|
@@ -5,6 +5,11 @@ import { useState, useCallback, useEffect, useRef, useMemo } from 'react'
|
|
|
import { useRouter } from 'next/navigation'
|
|
import { useRouter } from 'next/navigation'
|
|
|
import { arrayMove } from '@dnd-kit/sortable'
|
|
import { arrayMove } from '@dnd-kit/sortable'
|
|
|
import { toast } from 'sonner'
|
|
import { toast } from 'sonner'
|
|
|
|
|
+import { useFormatter, useTranslations } from 'next-intl'
|
|
|
|
|
+import { roundMoney } from '@/lib/money'
|
|
|
|
|
+import { LINE_TOTAL_MAX, QUANTITY_MAX, READING_MAX, UNIT_PRICE_MAX } from '@/lib/input-limits'
|
|
|
|
|
+import { LINE_ERROR_SELECTOR, useFieldErrorText } from '@/components/field-errors'
|
|
|
|
|
+import { findQuoteLineProblem } from '@/features/quotes/Lib/validateQuoteLines'
|
|
|
import { useSaveBeforeLeaving } from '@/hooks/use-save-before-leaving'
|
|
import { useSaveBeforeLeaving } from '@/hooks/use-save-before-leaving'
|
|
|
import { useGlassModal } from '@/components/glass-modal'
|
|
import { useGlassModal } from '@/components/glass-modal'
|
|
|
import { useConfirm } from '@/components/confirm-dialog'
|
|
import { useConfirm } from '@/components/confirm-dialog'
|
|
@@ -96,6 +101,11 @@ export function useQuoteFormState({
|
|
|
const router = useRouter()
|
|
const router = useRouter()
|
|
|
const modal = useGlassModal()
|
|
const modal = useGlassModal()
|
|
|
const confirm = useConfirm()
|
|
const confirm = useConfirm()
|
|
|
|
|
+ // A line's figures are refused in the work order's own words.
|
|
|
|
|
+ const tService = useTranslations('service')
|
|
|
|
|
+ const { number: formatNumber } = useFormatter()
|
|
|
|
|
+ const tCommon = useTranslations('common')
|
|
|
|
|
+ const fieldErrorText = useFieldErrorText()
|
|
|
|
|
|
|
|
// Tab state
|
|
// Tab state
|
|
|
const [activeTab, setActiveTab] = useState<'details' | 'images' | 'documents'>('details')
|
|
const [activeTab, setActiveTab] = useState<'details' | 'images' | 'documents'>('details')
|
|
@@ -326,12 +336,16 @@ export function useQuoteFormState({
|
|
|
}, [hasUnsavedChanges])
|
|
}, [hasUnsavedChanges])
|
|
|
|
|
|
|
|
// Calculations
|
|
// Calculations
|
|
|
|
|
+ // Each line to the cent first, as the save stores it (quoteSchema), so the
|
|
|
|
|
+ // subtotal is what the stored lines add up to, as on a work order.
|
|
|
const partsSubtotal = useMemo(
|
|
const partsSubtotal = useMemo(
|
|
|
- () => partItems.reduce((sum, p) => (p.excluded ? sum : sum + p.total), 0),
|
|
|
|
|
|
|
+ () =>
|
|
|
|
|
+ roundMoney(partItems.reduce((sum, p) => (p.excluded ? sum : sum + roundMoney(p.total)), 0)),
|
|
|
[partItems]
|
|
[partItems]
|
|
|
)
|
|
)
|
|
|
const laborSubtotal = useMemo(
|
|
const laborSubtotal = useMemo(
|
|
|
- () => laborItems.reduce((sum, l) => (l.excluded ? sum : sum + l.total), 0),
|
|
|
|
|
|
|
+ () =>
|
|
|
|
|
+ roundMoney(laborItems.reduce((sum, l) => (l.excluded ? sum : sum + roundMoney(l.total)), 0)),
|
|
|
[laborItems]
|
|
[laborItems]
|
|
|
)
|
|
)
|
|
|
// A percentage shop fee follows the lines the customer is being quoted for.
|
|
// A percentage shop fee follows the lines the customer is being quoted for.
|
|
@@ -344,17 +358,19 @@ export function useQuoteFormState({
|
|
|
markDirty()
|
|
markDirty()
|
|
|
}, [laborItems, partsSubtotal, shopFee, locked, markDirty])
|
|
}, [laborItems, partsSubtotal, shopFee, locked, markDirty])
|
|
|
|
|
|
|
|
- const subtotal = partsSubtotal + laborSubtotal
|
|
|
|
|
|
|
+ const subtotal = roundMoney(partsSubtotal + laborSubtotal)
|
|
|
const discountAmount = discountAmountFor(subtotal, discountType, discountValue)
|
|
const discountAmount = discountAmountFor(subtotal, discountType, discountValue)
|
|
|
// The tax is charged on the taxable lines the customer kept. A line says
|
|
// The tax is charged on the taxable lines the customer kept. A line says
|
|
|
// whether it is taxed, and one that has not been asked follows the
|
|
// whether it is taxed, and one that has not been asked follows the
|
|
|
// workshop's rule for its kind; the server settles it the same way.
|
|
// workshop's rule for its kind; the server settles it the same way.
|
|
|
|
|
+ // Each line to the cent here too, or the taxed share is summed from other
|
|
|
|
|
+ // figures than the subtotal (3 x 2.5 h at 19.99: 149.94 against 149.93).
|
|
|
const taxableParts = taxablePartsTotal(
|
|
const taxableParts = taxablePartsTotal(
|
|
|
- partItems.filter((p) => !p.excluded),
|
|
|
|
|
|
|
+ partItems.filter((p) => !p.excluded).map((p) => ({ ...p, total: roundMoney(p.total) })),
|
|
|
taxApplies
|
|
taxApplies
|
|
|
)
|
|
)
|
|
|
const taxableLabor = taxableLaborTotal(
|
|
const taxableLabor = taxableLaborTotal(
|
|
|
- laborItems.filter((l) => !l.excluded),
|
|
|
|
|
|
|
+ laborItems.filter((l) => !l.excluded).map((l) => ({ ...l, total: roundMoney(l.total) })),
|
|
|
taxApplies
|
|
taxApplies
|
|
|
)
|
|
)
|
|
|
const taxableSubtotal = storedTaxableSubtotal(subtotal, taxableParts + taxableLabor)
|
|
const taxableSubtotal = storedTaxableSubtotal(subtotal, taxableParts + taxableLabor)
|
|
@@ -434,7 +450,7 @@ export function useQuoteFormState({
|
|
|
const updated = [...prev]
|
|
const updated = [...prev]
|
|
|
const labor = { ...updated[index], [field]: value }
|
|
const labor = { ...updated[index], [field]: value }
|
|
|
if (field === 'hours' || field === 'rate')
|
|
if (field === 'hours' || field === 'rate')
|
|
|
- labor.total = Number(labor.hours) * Number(labor.rate)
|
|
|
|
|
|
|
+ labor.total = roundMoney(Number(labor.hours) * Number(labor.rate))
|
|
|
updated[index] = labor
|
|
updated[index] = labor
|
|
|
return updated
|
|
return updated
|
|
|
})
|
|
})
|
|
@@ -518,6 +534,8 @@ export function useQuoteFormState({
|
|
|
autosaveRunRef.current = false
|
|
autosaveRunRef.current = false
|
|
|
if (isSavingRef.current) return
|
|
if (isSavingRef.current) return
|
|
|
if (autosaveTimer.current) clearTimeout(autosaveTimer.current)
|
|
if (autosaveTimer.current) clearTimeout(autosaveTimer.current)
|
|
|
|
|
+ // This save's answer, not an earlier one's (see saveNow).
|
|
|
|
|
+ lastSaveErrorRef.current = null
|
|
|
// Saving from here on, the custom fields included: whoever waits for this
|
|
// Saving from here on, the custom fields included: whoever waits for this
|
|
|
// save (a link held back, the PDF) must not take that first step for the end.
|
|
// save (a link held back, the PDF) must not take that first step for the end.
|
|
|
isSavingRef.current = true
|
|
isSavingRef.current = true
|
|
@@ -560,6 +578,23 @@ export function useQuoteFormState({
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
+ // A figure the server would refuse is said now, in the work order's words,
|
|
|
|
|
+ // and the cursor put on the first marked field (see partLineIssues),
|
|
|
|
|
+ // unless this is an autosave and the person is typing somewhere.
|
|
|
|
|
+ const lineProblem = locked ? null : findQuoteLineProblem(partItems, laborItems)
|
|
|
|
|
+ if (lineProblem) {
|
|
|
|
|
+ isSavingRef.current = false
|
|
|
|
|
+ const message = tService(`page.problems.${lineProblem}`, {
|
|
|
|
|
+ quantity: formatNumber(QUANTITY_MAX),
|
|
|
|
|
+ price: formatNumber(UNIT_PRICE_MAX),
|
|
|
|
|
+ total: formatNumber(LINE_TOTAL_MAX),
|
|
|
|
|
+ reading: formatNumber(READING_MAX),
|
|
|
|
|
+ })
|
|
|
|
|
+ failed(message, () => toast.error(message))
|
|
|
|
|
+ if (!autosave) form.querySelector<HTMLElement>(LINE_ERROR_SELECTOR)?.focus()
|
|
|
|
|
+ return
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
setSaving(true)
|
|
setSaving(true)
|
|
|
try {
|
|
try {
|
|
|
const formData = new FormData(form)
|
|
const formData = new FormData(form)
|
|
@@ -603,7 +638,23 @@ export function useQuoteFormState({
|
|
|
savedTimerRef.current = setTimeout(() => setShowSaved(false), 2000)
|
|
savedTimerRef.current = setTimeout(() => setShowSaved(false), 2000)
|
|
|
router.refresh()
|
|
router.refresh()
|
|
|
} else {
|
|
} else {
|
|
|
- const message = result.error || t('page.failedSave')
|
|
|
|
|
|
|
+ // What the schema refused, in the person's language and named by the
|
|
|
|
|
+ // section it is in ("Parts: Must be 100,000 or less."), not zod's English.
|
|
|
|
|
+ const message = result.fieldErrors?.length
|
|
|
|
|
+ ? result.fieldErrors
|
|
|
|
|
+ .map((error) => {
|
|
|
|
|
+ const problem = fieldErrorText(error)
|
|
|
|
|
+ const [head] = error.field.split('.')
|
|
|
|
|
+ const label =
|
|
|
|
|
+ head === 'partItems'
|
|
|
|
|
+ ? tService('parts.title')
|
|
|
|
|
+ : head === 'laborItems'
|
|
|
|
|
+ ? tService('labor.title')
|
|
|
|
|
+ : null
|
|
|
|
|
+ return label ? tCommon('fieldErrors.withLabel', { label, problem }) : problem
|
|
|
|
|
+ })
|
|
|
|
|
+ .join(' ')
|
|
|
|
|
+ : result.error || t('page.failedSave')
|
|
|
failed(message, () => modal.open('error', 'Error', message))
|
|
failed(message, () => modal.open('error', 'Error', message))
|
|
|
}
|
|
}
|
|
|
} catch (err) {
|
|
} catch (err) {
|
|
@@ -635,17 +686,31 @@ export function useQuoteFormState({
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
- const saveNow = async () => {
|
|
|
|
|
- if (!formRef.current || isSavingRef.current) return
|
|
|
|
|
|
|
+ /**
|
|
|
|
|
+ * Saves now and says whether it went through. A save refused (a line past
|
|
|
|
|
+ * the limits, a custom field missing, the server saying no) has already
|
|
|
|
|
+ * said why; whatever waited on it (convert, the PDF, sending) stops there
|
|
|
|
|
+ * rather than going on with what the database held before the edit.
|
|
|
|
|
+ */
|
|
|
|
|
+ const saveNow = async (): Promise<boolean> => {
|
|
|
|
|
+ if (!formRef.current) return false
|
|
|
|
|
+ const settled = () =>
|
|
|
|
|
+ new Promise<void>((resolve) => {
|
|
|
|
|
+ const check = () => {
|
|
|
|
|
+ if (!isSavingRef.current) return resolve()
|
|
|
|
|
+ setTimeout(check, 50)
|
|
|
|
|
+ }
|
|
|
|
|
+ setTimeout(check, 50)
|
|
|
|
|
+ })
|
|
|
|
|
+ // An autosave already under way is the save; its answer is the answer.
|
|
|
|
|
+ if (isSavingRef.current) {
|
|
|
|
|
+ await settled()
|
|
|
|
|
+ return lastSaveErrorRef.current === null
|
|
|
|
|
+ }
|
|
|
if (autosaveTimer.current) clearTimeout(autosaveTimer.current)
|
|
if (autosaveTimer.current) clearTimeout(autosaveTimer.current)
|
|
|
formRef.current.requestSubmit()
|
|
formRef.current.requestSubmit()
|
|
|
- await new Promise<void>((resolve) => {
|
|
|
|
|
- const check = () => {
|
|
|
|
|
- if (!isSavingRef.current) return resolve()
|
|
|
|
|
- setTimeout(check, 50)
|
|
|
|
|
- }
|
|
|
|
|
- setTimeout(check, 50)
|
|
|
|
|
- })
|
|
|
|
|
|
|
+ await settled()
|
|
|
|
|
+ return lastSaveErrorRef.current === null
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
// Leaving by a link, a shortcut or the search palette saves first. The
|
|
// Leaving by a link, a shortcut or the search palette saves first. The
|
|
@@ -671,7 +736,7 @@ export function useQuoteFormState({
|
|
|
})
|
|
})
|
|
|
|
|
|
|
|
const handleDownloadPDF = async () => {
|
|
const handleDownloadPDF = async () => {
|
|
|
- if (hasUnsavedChanges) await saveNow()
|
|
|
|
|
|
|
+ if (hasUnsavedChanges && !(await saveNow())) return
|
|
|
setDownloading(true)
|
|
setDownloading(true)
|
|
|
try {
|
|
try {
|
|
|
const res = await fetch(`/api/protected/quotes/${quote.id}/pdf`)
|
|
const res = await fetch(`/api/protected/quotes/${quote.id}/pdf`)
|
|
@@ -740,7 +805,9 @@ export function useQuoteFormState({
|
|
|
const convertConflictsUnresolved = convertConflicts.some((c) => !convertResolutions[c.kind])
|
|
const convertConflictsUnresolved = convertConflicts.some((c) => !convertResolutions[c.kind])
|
|
|
|
|
|
|
|
const handleConvert = async () => {
|
|
const handleConvert = async () => {
|
|
|
- if (hasUnsavedChanges) await saveNow()
|
|
|
|
|
|
|
+ // A refused save stops the conversion: going on would convert what the
|
|
|
|
|
+ // database held, and the edit on screen would be lost with no word.
|
|
|
|
|
+ if (hasUnsavedChanges && !(await saveNow())) return
|
|
|
if (!convertVehicleId) {
|
|
if (!convertVehicleId) {
|
|
|
modal.open('error', 'Error', t('page.selectVehicle'))
|
|
modal.open('error', 'Error', t('page.selectVehicle'))
|
|
|
return
|
|
return
|