useQuoteFormState.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  1. 'use client'
  2. import { Trash2 } from 'lucide-react'
  3. import { useState, useCallback, useEffect, useRef, useMemo } from 'react'
  4. import { useRouter } from 'next/navigation'
  5. import { toast } from 'sonner'
  6. import { useSaveBeforeLeaving } from '@/hooks/use-save-before-leaving'
  7. import { useGlassModal } from '@/components/glass-modal'
  8. import { useConfirm } from '@/components/confirm-dialog'
  9. import { useDateSettings } from '@/components/date-settings-context'
  10. import {
  11. updateQuote,
  12. updateQuoteStatus,
  13. deleteQuote,
  14. convertQuoteToServiceRecord,
  15. addQuoteToServiceRecord,
  16. getQuoteConversionConflicts,
  17. getWorkOrdersForQuoteConversion,
  18. } from '@/features/quotes/Actions/quoteActions'
  19. import type {
  20. ConversionConflict,
  21. ConversionResolutions,
  22. } from '@/features/quotes/Lib/conversionConflicts'
  23. import { acknowledgeQuoteResponse } from '@/features/quotes/Actions/quoteResponseActions'
  24. import { calculateTotals, discountAmountFor, storedTaxableSubtotal } from '@/lib/tax'
  25. import {
  26. TAX_APPLIES_TO_ALL,
  27. type TaxApplies,
  28. type TaxableShare,
  29. taxableLaborTotal,
  30. taxablePartsTotal,
  31. } from '@/lib/taxable-lines'
  32. import { zonedDateInput } from '@/lib/timezone'
  33. import { parseTaxComponents } from '@/lib/tax-components'
  34. import { normalizeWarranty, WARRANTY_NONE, type WarrantyFields } from '@/lib/warranty'
  35. import { useDeferredCommit } from '@/hooks/use-deferred-commit'
  36. import {
  37. recalculateShopFeeLines,
  38. shopFeeLinesLast,
  39. type ShopFeeConfig,
  40. } from '@/features/settings/Lib/shopFee'
  41. import { isPriceOverridden, lineTotal, repricePartRow } from '@/features/inventory/Lib/partPricing'
  42. import type { QuoteRecord, QuotePartInput, QuoteLaborInput } from './quote-page-types'
  43. import { emptyPart, makeEmptyLabor, makeEmptyService } from './quote-page-types'
  44. interface SelectedVehicle {
  45. id: string
  46. make: string
  47. model: string
  48. year: number
  49. licensePlate: string | null
  50. customerId: string | null
  51. customer: { id: string; name: string } | null
  52. }
  53. /** An open work order the quote could be added to. */
  54. export interface ConvertTarget {
  55. id: string
  56. title: string
  57. invoiceNumber: string | null
  58. }
  59. interface SelectedCustomer {
  60. id: string
  61. name: string
  62. company: string | null
  63. }
  64. export function useQuoteFormState({
  65. quote,
  66. currencyCode,
  67. defaultTaxRate,
  68. taxEnabled,
  69. defaultLaborRate,
  70. locked = false,
  71. shopFee = null,
  72. taxApplies = TAX_APPLIES_TO_ALL,
  73. t,
  74. }: {
  75. quote: QuoteRecord
  76. currencyCode: string
  77. defaultTaxRate: number
  78. taxEnabled: boolean
  79. defaultLaborRate: number
  80. /** A locked quote refuses saves, so it must not queue one. */
  81. locked?: boolean
  82. /** The workshop's shop fee; a percentage one is re-priced as lines change. */
  83. shopFee?: ShopFeeConfig | null
  84. /** What a line that has not chosen is taxed as: the workshop's rule for its kind. */
  85. taxApplies?: TaxApplies
  86. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  87. t: (key: string, values?: any) => string
  88. }) {
  89. const router = useRouter()
  90. const modal = useGlassModal()
  91. const confirm = useConfirm()
  92. // Tab state
  93. const [activeTab, setActiveTab] = useState<'details' | 'images' | 'documents'>('details')
  94. // Form state
  95. const [saving, setSaving] = useState(false)
  96. const [downloading, setDownloading] = useState(false)
  97. const [status, setStatus] = useState(quote.status)
  98. // The customer can answer while the quote is open. A refresh brings the new
  99. // status in as a prop, and the page has to show it rather than the status it
  100. // was opened with; a status chosen here and not yet saved is left alone.
  101. useEffect(() => {
  102. setStatus(quote.status)
  103. }, [quote.status])
  104. const [customerId, setCustomerId] = useState(quote.customer?.id || '')
  105. const [vehicleId, setVehicleId] = useState(quote.vehicle?.id || '')
  106. const [partItems, setPartItems] = useState<QuotePartInput[]>(
  107. quote.partItems.map((p) => ({
  108. partNumber: p.partNumber || '',
  109. name: p.name,
  110. quantity: p.quantity,
  111. unit: p.unit ?? null,
  112. category: p.category ?? null,
  113. unitCost: p.unitCost ?? 0,
  114. markupPercent: p.markupPercent ?? 0,
  115. unitPrice: p.unitPrice,
  116. total: p.total,
  117. excluded: p.excluded ?? false,
  118. // The line's own answer; left out, a save would let the workshop's
  119. // default overwrite what had been chosen.
  120. taxable: p.taxable,
  121. inventoryPartId: p.inventoryPartId ?? null,
  122. // Evaluated once, on settled values from the database; see
  123. // isPriceOverridden for why it must not be recomputed while typing.
  124. priceOverridden: isPriceOverridden({
  125. unitCost: p.unitCost ?? 0,
  126. markupPercent: p.markupPercent ?? 0,
  127. unitPrice: p.unitPrice,
  128. }),
  129. }))
  130. )
  131. const { schedule: scheduleCommit, cancel: cancelCommit } = useDeferredCommit()
  132. const [laborItems, setLaborItems] = useState<QuoteLaborInput[]>(
  133. shopFeeLinesLast(quote.laborItems).map((l) => ({
  134. description: l.description,
  135. hours: l.hours,
  136. rate: l.rate,
  137. total: l.total,
  138. pricingType: (l.pricingType as 'hourly' | 'service' | 'shopFee') || 'hourly',
  139. excluded: l.excluded ?? false,
  140. taxable: l.taxable,
  141. }))
  142. )
  143. const [taxRate, setTaxRate] = useState(quote.taxRate ?? defaultTaxRate)
  144. const [taxInclusive] = useState<boolean>(quote.taxInclusive ?? false)
  145. // The split the quote was created with; the server re-derives the
  146. // amounts from it on every save.
  147. const [taxComponentDefinitions] = useState(() => parseTaxComponents(quote.taxComponents))
  148. const [discountType, setDiscountType] = useState<string>(quote.discountType || 'none')
  149. const [discountValue, setDiscountValue] = useState(quote.discountValue ?? 0)
  150. const [noteType, setNoteType] = useState<'public' | 'internal'>('public')
  151. const [description, setDescription] = useState(quote.description || '')
  152. const [notes, setNotes] = useState(quote.notes || '')
  153. // One value, because the four move together; see the work order's editor.
  154. const [warranty, setWarrantyState] = useState<WarrantyFields>(() => normalizeWarranty(quote))
  155. // Dialog state
  156. const [showEmailDialog, setShowEmailDialog] = useState(false)
  157. const [showShareDialog, setShowShareDialog] = useState(false)
  158. const [showConvertDialog, setShowConvertDialog] = useState(false)
  159. const [convertVehicleId, setConvertVehicleId] = useState(quote.vehicle?.id || '')
  160. const [converting, setConverting] = useState(false)
  161. // A new job is the default; adding to one the vehicle already has open is
  162. // the second choice, offered only when there is such a job.
  163. const [convertMode, setConvertMode] = useState<'new' | 'existing'>('new')
  164. const [convertTargets, setConvertTargets] = useState<ConvertTarget[]>([])
  165. const [convertTargetId, setConvertTargetId] = useState('')
  166. const [loadingConvertTargets, setLoadingConvertTargets] = useState(false)
  167. // Where the quote and the chosen job disagree, and what the user said the
  168. // job keeps. Adding waits until every conflict has an answer.
  169. const [convertConflicts, setConvertConflicts] = useState<ConversionConflict[]>([])
  170. const [convertResolutions, setConvertResolutions] = useState<ConversionResolutions>({})
  171. const [loadingConvertConflicts, setLoadingConvertConflicts] = useState(false)
  172. const [resolving, setResolving] = useState(false)
  173. // The day the quote is valid until, as the workshop's calendar has it. The
  174. // server reads the saved field in the workshop's zone, so the field has to
  175. // be filled in that zone too. Filled from the UTC date instead, every save
  176. // east of UTC moved the date a day earlier: a quote valid until the 19th
  177. // was sent out valid until the 17th after two saves.
  178. const { timezone } = useDateSettings()
  179. const [defaultValidDate] = useState(() =>
  180. quote.validUntil ? zonedDateInput(new Date(quote.validUntil), timezone) : ''
  181. )
  182. // Track selected vehicle/customer for display (initial from quote data)
  183. const [selectedVehicle, setSelectedVehicle] = useState<SelectedVehicle | null>(
  184. quote.vehicle
  185. ? {
  186. id: quote.vehicle.id,
  187. make: quote.vehicle.make,
  188. model: quote.vehicle.model,
  189. year: quote.vehicle.year,
  190. licensePlate: quote.vehicle.licensePlate,
  191. customerId: quote.customer?.id || null,
  192. customer: quote.customer ? { id: quote.customer.id, name: quote.customer.name } : null,
  193. }
  194. : null
  195. )
  196. const [selectedCustomer, setSelectedCustomer] = useState<SelectedCustomer | null>(
  197. quote.customer
  198. ? { id: quote.customer.id, name: quote.customer.name, company: quote.customer.company }
  199. : null
  200. )
  201. // Unsaved changes tracking & autosave
  202. const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false)
  203. // Read through a ref by code that awaits a save and must know its outcome.
  204. const hasUnsavedChangesRef = useRef(hasUnsavedChanges)
  205. hasUnsavedChangesRef.current = hasUnsavedChanges
  206. /**
  207. * Counts edits. A save clears the unsaved mark only when no edit was made
  208. * while it ran: the fields stay editable during a save, and an edit the
  209. * save did not carry must still be saved before the page is left.
  210. */
  211. const editRevisionRef = useRef(0)
  212. /** Why the last save failed, for the dialog that holds a link back. */
  213. const lastSaveErrorRef = useRef<string | null>(null)
  214. /** True while a link waits on its save: a failure goes into that dialog. */
  215. const leavingRef = useRef(false)
  216. const [showSaved, setShowSaved] = useState(false)
  217. const savedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
  218. const formRef = useRef<HTMLFormElement>(null)
  219. const autosaveTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
  220. const isSavingRef = useRef(false)
  221. // Custom fields save callback ref
  222. const customFieldsSaveRef = useRef<(() => Promise<{ valid: boolean }>) | null>(null)
  223. const onCustomFieldsReady = useCallback((save: () => Promise<{ valid: boolean }>) => {
  224. customFieldsSaveRef.current = save
  225. }, [])
  226. const markDirty = useCallback(() => {
  227. // A locked quote cannot be saved, so nothing may queue an autosave that
  228. // the server will only refuse five seconds later.
  229. if (locked) return
  230. editRevisionRef.current += 1
  231. hasUnsavedChangesRef.current = true
  232. setHasUnsavedChanges(true)
  233. if (autosaveTimer.current) clearTimeout(autosaveTimer.current)
  234. autosaveTimer.current = setTimeout(() => {
  235. if (!isSavingRef.current && formRef.current) {
  236. formRef.current.requestSubmit()
  237. }
  238. }, 5000)
  239. }, [locked])
  240. const setWarranty = useCallback(
  241. (next: WarrantyFields) => {
  242. setWarrantyState(next)
  243. markDirty()
  244. },
  245. [markDirty]
  246. )
  247. // A locked quote refuses a save, so its status is written on its own the
  248. // moment it is chosen. The server still refuses a status that would release
  249. // the lock, which is the owner-or-admin unlock by another route.
  250. const [changingStatus, setChangingStatus] = useState(false)
  251. const changeStatus = async (next: string) => {
  252. // The select also reports a value when the status changes under it, as
  253. // an empty string when no option matches; neither is somebody choosing.
  254. if (!next || next === status) return
  255. if (!locked) {
  256. setStatus(next)
  257. markDirty()
  258. return
  259. }
  260. const previous = status
  261. setStatus(next)
  262. setChangingStatus(true)
  263. const result = await updateQuoteStatus(quote.id, next)
  264. setChangingStatus(false)
  265. if (result.success) {
  266. router.refresh()
  267. } else {
  268. setStatus(previous)
  269. toast.error(result.error || t('page.failedSave'))
  270. }
  271. }
  272. // When the lock engages mid-session, a save already queued can only be
  273. // refused, and "Unsaved changes" would offer one that can never complete.
  274. useEffect(() => {
  275. if (!locked) return
  276. if (autosaveTimer.current) {
  277. clearTimeout(autosaveTimer.current)
  278. autosaveTimer.current = null
  279. }
  280. hasUnsavedChangesRef.current = false
  281. setHasUnsavedChanges(false)
  282. }, [locked])
  283. useEffect(() => {
  284. return () => {
  285. if (autosaveTimer.current) clearTimeout(autosaveTimer.current)
  286. }
  287. }, [])
  288. useEffect(() => {
  289. if (!hasUnsavedChanges) return
  290. const handler = (e: BeforeUnloadEvent) => {
  291. // Read live: "Leave without saving" drops the edits and goes in the
  292. // same moment, before this listener is taken down.
  293. if (!hasUnsavedChangesRef.current) return
  294. e.preventDefault()
  295. }
  296. window.addEventListener('beforeunload', handler)
  297. return () => window.removeEventListener('beforeunload', handler)
  298. }, [hasUnsavedChanges])
  299. // Calculations
  300. const partsSubtotal = useMemo(
  301. () => partItems.reduce((sum, p) => (p.excluded ? sum : sum + p.total), 0),
  302. [partItems]
  303. )
  304. const laborSubtotal = useMemo(
  305. () => laborItems.reduce((sum, l) => (l.excluded ? sum : sum + l.total), 0),
  306. [laborItems]
  307. )
  308. // A percentage shop fee follows the lines the customer is being quoted for.
  309. // A fee that moved is a change to save, or the PDF would print the old one.
  310. useEffect(() => {
  311. if (locked) return
  312. const next = recalculateShopFeeLines(laborItems, partsSubtotal, shopFee)
  313. if (next === laborItems) return
  314. setLaborItems(next)
  315. markDirty()
  316. }, [laborItems, partsSubtotal, shopFee, locked, markDirty])
  317. const subtotal = partsSubtotal + laborSubtotal
  318. const discountAmount = discountAmountFor(subtotal, discountType, discountValue)
  319. // The tax is charged on the taxable lines the customer kept. A line says
  320. // whether it is taxed, and one that has not been asked follows the
  321. // workshop's rule for its kind; the server settles it the same way.
  322. const taxableParts = taxablePartsTotal(
  323. partItems.filter((p) => !p.excluded),
  324. taxApplies
  325. )
  326. const taxableLabor = taxableLaborTotal(
  327. laborItems.filter((l) => !l.excluded),
  328. taxApplies
  329. )
  330. const taxableSubtotal = storedTaxableSubtotal(subtotal, taxableParts + taxableLabor)
  331. const {
  332. taxAmount,
  333. totalAmount,
  334. components: taxComponents,
  335. taxableAmount,
  336. } = calculateTotals({
  337. subtotal,
  338. discountAmount,
  339. taxRate,
  340. taxInclusive,
  341. components: taxComponentDefinitions,
  342. taxableSubtotal,
  343. })
  344. /** How much of each figure is taxed; null while every counted line is. */
  345. const taxableShare: TaxableShare | null =
  346. taxableSubtotal === null
  347. ? null
  348. : { parts: taxableParts, labor: taxableLabor, subtotal: taxableSubtotal, taxableAmount }
  349. // Cost, markup and price stay consistent with each other; repricePartRow
  350. // owns which of them moves, and work order parts use the same rules.
  351. const updatePart = useCallback(
  352. (
  353. index: number,
  354. field: keyof QuotePartInput,
  355. value: string | number | boolean | null,
  356. options: { commit?: boolean } = {}
  357. ) => {
  358. // Any edit ends the wait on the previous one.
  359. cancelCommit()
  360. setPartItems((prev) => {
  361. const updated = [...prev]
  362. const part = { ...updated[index], [field]: value }
  363. if (field === 'unitCost' || field === 'markupPercent' || field === 'unitPrice') {
  364. const priced = repricePartRow(part, field, options)
  365. part.unitPrice = priced.unitPrice
  366. part.markupPercent = priced.markupPercent
  367. part.priceOverridden = priced.priceOverridden
  368. }
  369. if (
  370. field === 'quantity' ||
  371. field === 'unitPrice' ||
  372. field === 'unitCost' ||
  373. field === 'markupPercent'
  374. ) {
  375. part.total = lineTotal(part.quantity, part.unitPrice)
  376. }
  377. updated[index] = part
  378. return updated
  379. })
  380. // A cost typed under a hand-set price restates the margin once typing
  381. // stops, so it lands on its own without needing the field to be left.
  382. if (field === 'unitCost' && !options.commit) {
  383. scheduleCommit(() =>
  384. setPartItems((prev) => {
  385. const row = prev[index]
  386. if (!row?.priceOverridden) return prev
  387. const updated = [...prev]
  388. updated[index] = { ...row, ...repricePartRow(row, 'unitCost', { commit: true }) }
  389. return updated
  390. })
  391. )
  392. }
  393. markDirty()
  394. },
  395. [markDirty, cancelCommit, scheduleCommit]
  396. )
  397. const updateLabor = useCallback(
  398. (index: number, field: keyof QuoteLaborInput, value: string | number | boolean) => {
  399. setLaborItems((prev) => {
  400. const updated = [...prev]
  401. const labor = { ...updated[index], [field]: value }
  402. if (field === 'hours' || field === 'rate')
  403. labor.total = Number(labor.hours) * Number(labor.rate)
  404. updated[index] = labor
  405. return updated
  406. })
  407. markDirty()
  408. },
  409. [markDirty]
  410. )
  411. const addPart = useCallback(() => {
  412. setPartItems((prev) => [...prev, emptyPart()])
  413. markDirty()
  414. }, [markDirty])
  415. const addLabor = useCallback(() => {
  416. setLaborItems((prev) => [...prev, makeEmptyLabor(defaultLaborRate)])
  417. markDirty()
  418. }, [defaultLaborRate, markDirty])
  419. const addService = useCallback(() => {
  420. setLaborItems((prev) => [...prev, makeEmptyService()])
  421. markDirty()
  422. }, [markDirty])
  423. const addLaborBulk = useCallback(
  424. (items: QuoteLaborInput[]) => {
  425. setLaborItems((prev) => [...prev, ...items])
  426. markDirty()
  427. },
  428. [markDirty]
  429. )
  430. const addPartBulk = useCallback(
  431. (items: QuotePartInput[]) => {
  432. setPartItems((prev) => [...prev, ...items])
  433. markDirty()
  434. },
  435. [markDirty]
  436. )
  437. const deletePart = useCallback(
  438. (index: number) => {
  439. setPartItems((prev) => prev.filter((_, j) => j !== index))
  440. markDirty()
  441. },
  442. [markDirty]
  443. )
  444. const deleteLabor = useCallback(
  445. (index: number) => {
  446. setLaborItems((prev) => prev.filter((_, j) => j !== index))
  447. markDirty()
  448. },
  449. [markDirty]
  450. )
  451. const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
  452. e.preventDefault()
  453. // currentTarget is nulled once the event has finished dispatching, which
  454. // happens during the custom-fields await below. Read the form now.
  455. const form = e.currentTarget
  456. if (isSavingRef.current) return
  457. if (autosaveTimer.current) clearTimeout(autosaveTimer.current)
  458. // Saving from here on, the custom fields included: whoever waits for this
  459. // save (a link held back, the PDF) must not take that first step for the end.
  460. isSavingRef.current = true
  461. // A save a link is waiting on says why it failed in the dialog that holds
  462. // the link, not in a toast or an error box on top of it.
  463. const failed = (message: string, show: () => void) => {
  464. lastSaveErrorRef.current = message
  465. if (!leavingRef.current) show()
  466. }
  467. // Validate and save custom fields before saving; a locked quote saves nothing.
  468. if (!locked && customFieldsSaveRef.current) {
  469. try {
  470. const { valid } = await customFieldsSaveRef.current()
  471. if (!valid) {
  472. isSavingRef.current = false
  473. const message = t('page.customFieldsInvalid')
  474. failed(message, () => toast.error(message))
  475. return
  476. }
  477. } catch (err) {
  478. console.error('Custom fields save error:', err)
  479. isSavingRef.current = false
  480. const message = t('page.customFieldsSaveFailed')
  481. failed(message, () => toast.error(message))
  482. return
  483. }
  484. }
  485. setSaving(true)
  486. try {
  487. const formData = new FormData(form)
  488. const revision = editRevisionRef.current
  489. const result = await updateQuote({
  490. id: quote.id,
  491. title: formData.get('title') as string,
  492. // Emptied fields go as '' (and a removed discount as 'none') so the
  493. // update action clears them; undefined would leave the old value.
  494. description,
  495. status,
  496. validUntil: (formData.get('validUntil') as string | null) ?? '',
  497. customerId,
  498. vehicleId,
  499. notes,
  500. partItems: partItems.filter((p) => p.name),
  501. laborItems: shopFeeLinesLast(laborItems.filter((l) => l.description)),
  502. subtotal,
  503. taxRate,
  504. taxInclusive,
  505. taxAmount,
  506. discountType,
  507. discountValue,
  508. discountAmount,
  509. totalAmount,
  510. // Cleared fields go as 'none', 0 and '' for the same reason as above.
  511. warrantyStatus: warranty.warrantyStatus ?? WARRANTY_NONE,
  512. warrantyMonths: warranty.warrantyMonths ?? 0,
  513. warrantyMileage: warranty.warrantyMileage ?? 0,
  514. warrantyNotes: warranty.warrantyNotes ?? '',
  515. })
  516. if (result.success && editRevisionRef.current !== revision) {
  517. // Edited while this save ran: still unsaved, and the autosave that
  518. // edit queued (or a link waiting to leave) saves it next.
  519. router.refresh()
  520. } else if (result.success) {
  521. hasUnsavedChangesRef.current = false
  522. setHasUnsavedChanges(false)
  523. if (savedTimerRef.current) clearTimeout(savedTimerRef.current)
  524. setShowSaved(true)
  525. savedTimerRef.current = setTimeout(() => setShowSaved(false), 2000)
  526. router.refresh()
  527. } else {
  528. const message = result.error || t('page.failedSave')
  529. failed(message, () => modal.open('error', 'Error', message))
  530. }
  531. } catch (err) {
  532. console.error('Quote save error:', err)
  533. const message = t('page.failedSave')
  534. failed(message, () => modal.open('error', 'Error', message))
  535. } finally {
  536. // Whatever happened, the save button must stop spinning.
  537. isSavingRef.current = false
  538. setSaving(false)
  539. }
  540. }
  541. const handleDelete = async () => {
  542. const ok = await confirm({
  543. title: t('page.deleteTitle'),
  544. description: t('page.deleteDescription'),
  545. confirmLabel: t('page.delete'),
  546. icon: Trash2,
  547. destructive: true,
  548. })
  549. if (!ok) return
  550. const result = await deleteQuote(quote.id)
  551. if (result.success) {
  552. router.push('/quotes')
  553. router.refresh()
  554. } else {
  555. modal.open('error', 'Error', result.error || t('page.failedDelete'))
  556. }
  557. }
  558. const saveNow = async () => {
  559. if (!formRef.current || isSavingRef.current) return
  560. if (autosaveTimer.current) clearTimeout(autosaveTimer.current)
  561. formRef.current.requestSubmit()
  562. await new Promise<void>((resolve) => {
  563. const check = () => {
  564. if (!isSavingRef.current) return resolve()
  565. setTimeout(check, 50)
  566. }
  567. setTimeout(check, 50)
  568. })
  569. }
  570. // Leaving by a link, a shortcut or the search palette saves first. The
  571. // autosave waits five seconds after the last edit, and until this guard an
  572. // edit made inside that window was dropped without a word when the page
  573. // was left. A save that fails holds the link and asks: stay, or leave
  574. // without the unsaved changes.
  575. const { blockedLeave, stayOnPage, leaveWithoutSaving } = useSaveBeforeLeaving({
  576. active: hasUnsavedChanges,
  577. isDirty: () => hasUnsavedChangesRef.current,
  578. isSaving: () => isSavingRef.current,
  579. save: saveNow,
  580. lastErrorRef: lastSaveErrorRef,
  581. leavingRef,
  582. discard: () => {
  583. if (autosaveTimer.current) {
  584. clearTimeout(autosaveTimer.current)
  585. autosaveTimer.current = null
  586. }
  587. hasUnsavedChangesRef.current = false
  588. setHasUnsavedChanges(false)
  589. },
  590. })
  591. const handleDownloadPDF = async () => {
  592. if (hasUnsavedChanges) await saveNow()
  593. setDownloading(true)
  594. try {
  595. const res = await fetch(`/api/protected/quotes/${quote.id}/pdf`)
  596. if (!res.ok) throw new Error(t('page.failedPdf'))
  597. const blob = await res.blob()
  598. const url = URL.createObjectURL(blob)
  599. const a = document.createElement('a')
  600. a.href = url
  601. a.download = `quote-${quote.quoteNumber || quote.id}.pdf`
  602. a.click()
  603. URL.revokeObjectURL(url)
  604. } catch {
  605. modal.open('error', 'Error', t('page.failedPdf'))
  606. }
  607. setDownloading(false)
  608. }
  609. // The open jobs follow the vehicle picked in the dialog, read each time it
  610. // opens so a job finished in the meantime is not offered.
  611. useEffect(() => {
  612. if (!showConvertDialog || !convertVehicleId) {
  613. setConvertTargets([])
  614. setConvertTargetId('')
  615. setConvertMode('new')
  616. return
  617. }
  618. let cancelled = false
  619. setLoadingConvertTargets(true)
  620. getWorkOrdersForQuoteConversion(convertVehicleId).then((result) => {
  621. if (cancelled) return
  622. const targets = result.success && result.data ? result.data : []
  623. setConvertTargets(targets)
  624. setConvertTargetId(targets[0]?.id ?? '')
  625. if (targets.length === 0) setConvertMode('new')
  626. setLoadingConvertTargets(false)
  627. })
  628. return () => {
  629. cancelled = true
  630. }
  631. }, [showConvertDialog, convertVehicleId])
  632. // The conflicts follow the job picked, read afresh each time so a job
  633. // edited in the meantime is asked about as it now stands. Earlier answers
  634. // are dropped with them: they were about another job.
  635. useEffect(() => {
  636. setConvertConflicts([])
  637. setConvertResolutions({})
  638. if (!showConvertDialog || convertMode !== 'existing' || !convertTargetId) return
  639. let cancelled = false
  640. setLoadingConvertConflicts(true)
  641. getQuoteConversionConflicts(quote.id, convertTargetId).then((result) => {
  642. if (cancelled) return
  643. setConvertConflicts(result.success && result.data ? result.data : [])
  644. setLoadingConvertConflicts(false)
  645. })
  646. return () => {
  647. cancelled = true
  648. }
  649. }, [showConvertDialog, convertMode, convertTargetId, quote.id])
  650. const setConvertResolution = <K extends keyof ConversionResolutions>(
  651. kind: K,
  652. choice: NonNullable<ConversionResolutions[K]>
  653. ) => setConvertResolutions((prev) => ({ ...prev, [kind]: choice }))
  654. const convertConflictsUnresolved = convertConflicts.some((c) => !convertResolutions[c.kind])
  655. const handleConvert = async () => {
  656. if (hasUnsavedChanges) await saveNow()
  657. if (!convertVehicleId) {
  658. modal.open('error', 'Error', t('page.selectVehicle'))
  659. return
  660. }
  661. const addToExisting = convertMode === 'existing'
  662. if (addToExisting && !convertTargetId) {
  663. modal.open('error', 'Error', t('page.convertSelectWorkOrder'))
  664. return
  665. }
  666. if (addToExisting && (loadingConvertConflicts || convertConflictsUnresolved)) {
  667. modal.open('error', 'Error', t('page.convertConflicts.unanswered'))
  668. return
  669. }
  670. setConverting(true)
  671. const result = addToExisting
  672. ? await addQuoteToServiceRecord(
  673. quote.id,
  674. convertVehicleId,
  675. convertTargetId,
  676. convertResolutions
  677. )
  678. : await convertQuoteToServiceRecord(quote.id, convertVehicleId)
  679. if (result.success && result.data) {
  680. router.push(`/vehicles/${convertVehicleId}/service/${result.data.id}`)
  681. router.refresh()
  682. } else {
  683. modal.open('error', 'Error', result.error || t('page.failedConvert'))
  684. }
  685. setConverting(false)
  686. }
  687. const handleResolveResponse = async () => {
  688. setResolving(true)
  689. const result = await acknowledgeQuoteResponse(quote.id)
  690. if (result.success) {
  691. // A change request goes back to draft; an acceptance keeps its status.
  692. if (result.data) setStatus(result.data.status)
  693. toast.success(t('page.responseResolved'))
  694. router.refresh()
  695. }
  696. setResolving(false)
  697. }
  698. return {
  699. // Tab
  700. activeTab,
  701. setActiveTab,
  702. // Form state
  703. saving,
  704. downloading,
  705. status,
  706. setStatus,
  707. customerId,
  708. setCustomerId,
  709. vehicleId,
  710. setVehicleId,
  711. partItems,
  712. laborItems,
  713. taxRate,
  714. setTaxRate,
  715. taxEnabled,
  716. taxInclusive,
  717. taxComponents,
  718. discountType,
  719. setDiscountType,
  720. discountValue,
  721. setDiscountValue,
  722. noteType,
  723. setNoteType,
  724. description,
  725. setDescription,
  726. notes,
  727. setNotes,
  728. warranty,
  729. setWarranty,
  730. // Dialogs
  731. showEmailDialog,
  732. setShowEmailDialog,
  733. showShareDialog,
  734. setShowShareDialog,
  735. showConvertDialog,
  736. setShowConvertDialog,
  737. convertVehicleId,
  738. setConvertVehicleId,
  739. converting,
  740. convertMode,
  741. setConvertMode,
  742. convertTargets,
  743. convertTargetId,
  744. setConvertTargetId,
  745. loadingConvertTargets,
  746. convertConflicts,
  747. convertResolutions,
  748. setConvertResolution,
  749. convertConflictsUnresolved,
  750. loadingConvertConflicts,
  751. resolving,
  752. changeStatus,
  753. changingStatus,
  754. defaultValidDate,
  755. // Unsaved
  756. hasUnsavedChanges,
  757. /** Whether edits are still unsaved, read at the moment of the call. */
  758. isDirty: () => hasUnsavedChangesRef.current,
  759. showSaved,
  760. formRef,
  761. // Computed
  762. partsSubtotal,
  763. taxableShare,
  764. laborSubtotal,
  765. subtotal,
  766. discountAmount,
  767. taxAmount,
  768. totalAmount,
  769. selectedVehicle,
  770. setSelectedVehicle,
  771. selectedCustomer,
  772. setSelectedCustomer,
  773. // Callbacks
  774. markDirty,
  775. onCustomFieldsReady,
  776. updatePart,
  777. updateLabor,
  778. addPart,
  779. addPartBulk,
  780. addLabor,
  781. addService,
  782. addLaborBulk,
  783. deletePart,
  784. deleteLabor,
  785. handleSubmit,
  786. handleDelete,
  787. handleDownloadPDF,
  788. handleConvert,
  789. handleResolveResponse,
  790. saveNow,
  791. blockedLeave,
  792. stayOnPage,
  793. leaveWithoutSaving,
  794. }
  795. }
  796. export type QuoteFormState = ReturnType<typeof useQuoteFormState>