Просмотр исходного кода

Stop a labour line doubling when a preset is applied right after an edit (#678)

* Stop a labour line doubling when a preset is applied right after an edit

* Keep lines a technician added while a save ran, and compare saved lines as the server returns them
Bernt Christian Egeland 3 дней назад
Родитель
Сommit
acdd2fbd9f

+ 320 - 0
src/__tests__/features/vehicles/edit-then-preset.test.tsx

@@ -0,0 +1,320 @@
+/**
+ * A line edited, then a labour preset applied before the edit has settled.
+ *
+ * The page saves by itself five seconds after an edit and reads the job again
+ * after every save. A preset picked while that save runs, or before the read
+ * after it comes back, leaves the page unsaved when the saved lines arrive.
+ * The page used to compare them with the lines as they were before the save,
+ * took the line it had just saved for one a technician added elsewhere, put
+ * it in the list a second time, and the next save wrote it twice.
+ *
+ * The page and the save are the real hooks here, wired as ServicePageClient
+ * wires them; only the server action and the router are stand-ins.
+ */
+import { act, cleanup, renderHook } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { ServiceLaborInput, ServicePartInput } from '@/features/vehicles/Schema/serviceSchema'
+
+vi.mock('next/navigation', () => ({
+  useRouter: () => ({ refresh: vi.fn(), push: vi.fn() }),
+  usePathname: () => '/vehicles/veh-1/service/rec-1',
+}))
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }))
+vi.mock('@/hooks/use-deferred-commit', () => ({
+  useDeferredCommit: () => ({ schedule: vi.fn(), cancel: vi.fn() }),
+}))
+vi.mock('@/components/confirm-dialog', async (importOriginal) => ({
+  ...(await importOriginal<typeof import('@/components/confirm-dialog')>()),
+  useConfirm: () => vi.fn(async () => true),
+}))
+const updateServiceRecord = vi.fn()
+vi.mock('@/features/vehicles/Actions/serviceActions', () => ({
+  updateServiceRecord: (input: unknown) => updateServiceRecord(input),
+  deleteServiceRecord: vi.fn(),
+  deleteServiceAttachment: vi.fn(),
+  toggleManuallyPaid: vi.fn(),
+}))
+vi.mock('@/features/payments/Actions/paymentActions', () => ({
+  createPayment: vi.fn(),
+  deletePayment: vi.fn(),
+}))
+vi.mock('@/features/sms/Actions/smsActions', () => ({ getSmsTemplates: vi.fn() }))
+
+import { useServiceActions } from '@/features/vehicles/Components/service-page/useServiceActions'
+import { useServiceFormState } from '@/features/vehicles/Components/service-page/useServiceFormState'
+
+const labor = (description: string, hours = 1, rate = 100): ServiceLaborInput => ({
+  description,
+  hours,
+  rate,
+  total: hours * rate,
+  pricingType: 'hourly',
+})
+const part = (name: string, unitPrice = 50): ServicePartInput => ({
+  name,
+  partNumber: '',
+  quantity: 1,
+  unitPrice,
+  total: unitPrice,
+  unitCost: 0,
+  markupPercent: 0,
+  inventoryPartId: '',
+})
+
+const ORIGINAL = labor('ZZ Repro', 1)
+const EDITED = labor('ZZ Repro B', 1.5)
+const PRESET = labor('ZZ Oil service', 0.5)
+const PRESET_PART = part('ZZ Oil filter', 12)
+const DESK_PART = part('ZZ Brake cleaner', 8)
+const EDITED_PART = part('ZZ Brake cleaner, 2 cans', 16)
+const FROM_THE_BAY = labor('ZZ Replaced the timing belt', 2)
+
+function props(laborItems: ServiceLaborInput[], partItems: ServicePartInput[] = [DESK_PART]) {
+  return {
+    vehicleId: 'veh-1',
+    defaultTaxRate: 0,
+    currentUserName: 'Desk',
+    record: { id: 'rec-1', attachments: [], payments: [] } as never,
+    initialData: {
+      id: 'rec-1',
+      status: 'in-progress',
+      concerns: [],
+      partItems,
+      laborItems,
+      taxRate: 0,
+      taxInclusive: false,
+      discountValue: 0,
+    } as never,
+  }
+}
+
+/** The work order page: its form state and its save, as ServicePageClient wires them. */
+function openPage() {
+  const hook = renderHook(
+    (p: ReturnType<typeof props>) => {
+      const formState = useServiceFormState(p)
+      const actions = useServiceActions({
+        record: p.record,
+        vehicleId: 'veh-1',
+        currencyCode: 'GBP',
+        formState,
+      })
+      return { formState, actions }
+    },
+    { initialProps: props([ORIGINAL]) }
+  )
+  const el = document.createElement('form')
+  el.innerHTML = '<input name="title" value="ZZ Brake inspection" />'
+  document.body.appendChild(el)
+  const submit = () =>
+    hook.result.current.actions.handleSubmit({
+      preventDefault: () => undefined,
+      currentTarget: el,
+    } as unknown as React.FormEvent<HTMLFormElement>)
+  const page = () => hook.result.current.formState
+  /** The read of the job after a save comes back with what the server holds. */
+  const refresh = (laborItems: ServiceLaborInput[], partItems?: ServicePartInput[]) =>
+    hook.rerender(props(laborItems, partItems))
+  return { page, submit, refresh }
+}
+
+/** The save the server is running, held open until the test lets it finish. */
+function heldSave() {
+  let finish: () => void = () => undefined
+  updateServiceRecord.mockImplementationOnce(
+    () =>
+      new Promise((resolve) => {
+        finish = () => resolve({ success: true })
+      })
+  )
+  return () => finish()
+}
+
+const sent = (call = -1) =>
+  updateServiceRecord.mock.calls.at(call)?.[0] as {
+    laborItems: ServiceLaborInput[]
+    partItems: ServicePartInput[]
+  }
+
+const applyPreset = (page: ReturnType<typeof openPage>['page']) =>
+  act(() => {
+    page().dirtySetLaborItems((prev) => [PRESET, ...prev])
+    page().dirtySetPartItems((prev) => [PRESET_PART, ...prev])
+  })
+
+beforeEach(() => {
+  updateServiceRecord.mockReset().mockResolvedValue({ success: true })
+})
+
+afterEach(() => {
+  cleanup()
+  document.body.innerHTML = ''
+})
+
+describe('a preset applied right after a line was edited', () => {
+  it('while the autosave of the edit runs: the edited line shows and saves once', async () => {
+    const { page, submit, refresh } = openPage()
+
+    act(() => {
+      page().dirtySetLaborItems([EDITED])
+      page().dirtySetPartItems([EDITED_PART])
+    })
+    const finish = heldSave()
+    let saving: Promise<void> = Promise.resolve()
+    act(() => {
+      saving = submit()
+    })
+    applyPreset(page)
+    await act(async () => {
+      finish()
+      await saving
+    })
+    // The read after the save: the server has the edits, not the preset yet.
+    refresh([EDITED], [EDITED_PART])
+
+    expect(page().laborItems).toEqual([PRESET, EDITED])
+    expect(page().laborAddedElsewhere).toEqual([])
+    expect(page().partItems).toEqual([PRESET_PART, EDITED_PART])
+    expect(page().partsAddedElsewhere).toEqual([])
+
+    await act(() => submit())
+    expect(sent().laborItems).toEqual([PRESET, EDITED])
+    expect(sent().partItems).toEqual([PRESET_PART, EDITED_PART])
+  })
+
+  it('after the save, before the read that follows it: the same', async () => {
+    const { page, submit, refresh } = openPage()
+
+    act(() => page().dirtySetLaborItems([EDITED]))
+    await act(() => submit())
+    expect(page().hasUnsavedChanges).toBe(false)
+    applyPreset(page)
+    refresh([EDITED], [DESK_PART])
+
+    expect(page().laborItems).toEqual([PRESET, EDITED])
+    expect(page().laborAddedElsewhere).toEqual([])
+    expect(page().partsAddedElsewhere).toEqual([])
+
+    await act(() => submit())
+    expect(sent().laborItems).toEqual([PRESET, EDITED])
+    expect(sent().partItems).toEqual([PRESET_PART, DESK_PART])
+  })
+
+  it('a technician line that arrives after that save still waits for the desk and is saved', async () => {
+    const { page, submit, refresh } = openPage()
+
+    act(() => page().dirtySetLaborItems([EDITED]))
+    const finish = heldSave()
+    let saving: Promise<void> = Promise.resolve()
+    act(() => {
+      saving = submit()
+    })
+    applyPreset(page)
+    await act(async () => {
+      finish()
+      await saving
+    })
+    refresh([EDITED, FROM_THE_BAY], [DESK_PART])
+
+    expect(page().laborItems).toEqual([PRESET, EDITED])
+    expect(page().laborAddedElsewhere).toEqual([FROM_THE_BAY])
+
+    await act(() => submit())
+    expect(sent().laborItems).toEqual([PRESET, EDITED, FROM_THE_BAY])
+  })
+})
+
+const SECOND_FROM_THE_BAY = labor('ZZ Brake fluid flush', 0.5)
+const SCANNED = part('ZZ Front pads', 72)
+const SECOND_SCANNED = part('ZZ Wear sensor', 15)
+
+/** Edit, save (held open), and apply a preset while it runs, so the page stays unsaved. */
+function editSaveAndPreset() {
+  const view = openPage()
+  act(() => view.page().dirtySetLaborItems([EDITED]))
+  const finish = heldSave()
+  let saving: Promise<void> = Promise.resolve()
+  act(() => {
+    saving = view.submit()
+  })
+  applyPreset(view.page)
+  const land = () =>
+    act(async () => {
+      finish()
+      await saving
+    })
+  return { ...view, land }
+}
+
+describe('lines a technician adds while a save runs', () => {
+  it('a read taken after the save wrote: each line waits once and is saved once', async () => {
+    const { page, submit, refresh, land } = editSaveAndPreset()
+
+    // The technician's line and part, read with the desk's own edit already on the server.
+    refresh([EDITED, FROM_THE_BAY], [DESK_PART, SCANNED])
+    expect(page().laborAddedElsewhere).toEqual([FROM_THE_BAY])
+    expect(page().partsAddedElsewhere).toEqual([SCANNED])
+
+    await land()
+    // Another line and part arrive; the first ones are still on the job.
+    refresh([EDITED, FROM_THE_BAY, SECOND_FROM_THE_BAY], [DESK_PART, SCANNED, SECOND_SCANNED])
+    expect(page().laborAddedElsewhere).toEqual([FROM_THE_BAY, SECOND_FROM_THE_BAY])
+    expect(page().partsAddedElsewhere).toEqual([SCANNED, SECOND_SCANNED])
+
+    await act(() => submit())
+    expect(sent().laborItems).toEqual([PRESET, EDITED, FROM_THE_BAY, SECOND_FROM_THE_BAY])
+    expect(sent().partItems).toEqual([PRESET_PART, DESK_PART, SCANNED, SECOND_SCANNED])
+  })
+
+  it('a read taken before the save wrote: the old line is not offered, the new one is saved once', async () => {
+    const { page, submit, refresh, land } = editSaveAndPreset()
+
+    refresh([ORIGINAL, FROM_THE_BAY])
+    expect(page().laborAddedElsewhere).toEqual([FROM_THE_BAY])
+
+    await land()
+    // The save replaced every line, so the server lost the technician's line
+    // for now; the page still holds it, and the next save puts it back.
+    refresh([EDITED])
+    expect(page().laborAddedElsewhere).toEqual([FROM_THE_BAY])
+    refresh([EDITED, SECOND_FROM_THE_BAY])
+    expect(page().laborAddedElsewhere).toEqual([FROM_THE_BAY, SECOND_FROM_THE_BAY])
+
+    await act(() => submit())
+    expect(sent().laborItems).toEqual([PRESET, EDITED, FROM_THE_BAY, SECOND_FROM_THE_BAY])
+  })
+})
+
+describe('saved lines compared as the server returns them', () => {
+  it('hours typed as text, and a preset part with empty links, are not read as added elsewhere', async () => {
+    const { page, submit, refresh } = openPage()
+
+    // Typed into the boxes: the editor keeps the strings.
+    act(() => {
+      page().updateLabor(0, 'description', 'ZZ Repro B')
+      page().updateLabor(0, 'hours', '1.5')
+    })
+    expect(page().laborItems[0].hours).toBe('1.5')
+    // A preset part carries '' for its part number and inventory link.
+    act(() => page().dirtySetPartItems((prev) => [PRESET_PART, ...prev]))
+    const finish = heldSave()
+    let saving: Promise<void> = Promise.resolve()
+    act(() => {
+      saving = submit()
+    })
+    // Edited while it runs, so the page is unsaved when the read comes back.
+    act(() => page().dirtySetLaborItems((prev) => [...prev, PRESET]))
+    await act(async () => {
+      finish()
+      await saving
+    })
+    // What the server hands back: numbers, and no inventory link at all.
+    refresh([EDITED], [{ ...PRESET_PART, inventoryPartId: undefined }, DESK_PART])
+
+    expect(page().laborAddedElsewhere).toEqual([])
+    expect(page().partsAddedElsewhere).toEqual([])
+    await act(() => submit())
+    expect(sent().laborItems.map((l) => l.description)).toEqual(['ZZ Repro B', 'ZZ Oil service'])
+    expect(sent().partItems.map((p) => p.name)).toEqual(['ZZ Oil filter', 'ZZ Brake cleaner'])
+  })
+})

+ 1 - 0
src/__tests__/features/vehicles/work-order-reading-question.test.tsx

@@ -86,6 +86,7 @@ function page(over: { confirmed?: number | null; saved?: number | null } = {}) {
     initialData: { id: 'job1', mileage: over.saved ?? null, lastReading: 148000 },
     confirmedReadingRef: { current: over.confirmed ?? null },
     acknowledgeSavedLines: vi.fn(),
+    sendingLinesRef: { current: null },
   }
   const hook = renderHook(() =>
     useServiceActions({

+ 1 - 0
src/__tests__/features/vehicles/work-order-required-meters-save.test.tsx

@@ -105,6 +105,7 @@ function page(status: string, saved: string) {
     initialData: { id: 'job1', status: saved, mileage: null, lastReading: null },
     confirmedReadingRef: { current: null },
     acknowledgeSavedLines: vi.fn(),
+    sendingLinesRef: { current: null },
   }
   const hook = renderHook(() =>
     useServiceActions({

+ 10 - 0
src/features/vehicles/Components/service-page/useServiceActions.ts

@@ -92,6 +92,7 @@ export function useServiceActions({
     markDirty,
     confirmedReadingRef,
     acknowledgeSavedLines,
+    sendingLinesRef,
   } = formState
 
   /**
@@ -269,9 +270,13 @@ export function useServiceActions({
     }
 
     let result: Awaited<ReturnType<typeof updateServiceRecord>>
+    // A refresh that lands while this runs must not take these lines, the
+    // page's own, for ones added elsewhere.
+    sendingLinesRef.current = { parts: payload.partItems, labor: payload.laborItems }
     try {
       result = await updateServiceRecord(payload)
     } catch (err) {
+      sendingLinesRef.current = null
       // The request never came back (the connection dropped). Saving has to
       // end here, or the next save, and a link waiting on this one, waits
       // forever.
@@ -279,6 +284,7 @@ export function useServiceActions({
       setLoading(false)
       throw err
     }
+    sendingLinesRef.current = null
 
     if (result.success && holdReading) {
       commitLaborAddedElsewhere()
@@ -298,6 +304,10 @@ export function useServiceActions({
     } else if (result.success) {
       commitLaborAddedElsewhere()
       commitPartsAddedElsewhere()
+      // The same on every save: a preset or an edit made while it ran, or
+      // before the refresh below comes back, leaves the page unsaved when the
+      // saved lines arrive, and they must not read as added elsewhere.
+      acknowledgeSavedLines({ parts: payload.partItems, labor: payload.laborItems })
       markSaved(revision)
       flashSaved()
       if (selectedVehicleId && selectedVehicleId !== vehicleId) {

+ 50 - 11
src/features/vehicles/Components/service-page/useServiceFormState.ts

@@ -12,8 +12,8 @@ import { useDeferredCommit } from '@/hooks/use-deferred-commit'
 import { useSaveBeforeLeaving } from '@/hooks/use-save-before-leaving'
 import { lineTotal, repricePartRow } from '@/features/inventory/Lib/partPricing'
 import { reconcileConcernRows } from '@/features/vehicles/Lib/concernStory'
-import { addedLaborLines } from '@/features/vehicles/Lib/laborLines'
-import { addedPartLines } from '@/features/vehicles/Lib/partLines'
+import { addedLaborLines, savedLaborShape } from '@/features/vehicles/Lib/laborLines'
+import { addedPartLines, savedPartShape } from '@/features/vehicles/Lib/partLines'
 import {
   recalculateShopFeeLines,
   shopFeeLinesLast,
@@ -187,6 +187,15 @@ export function useServiceFormState({
     setStatus(savedStatus)
   }, [savedStatus])
 
+  /**
+   * The lines of the save on its way to the server, if one is. A refresh can
+   * be read either side of its write; see addedLaborLines.
+   */
+  const sendingLinesRef = useRef<{
+    parts: ServicePartInput[]
+    labor: ServiceLaborInput[]
+  } | null>(null)
+
   const [laborAddedElsewhere, setLaborAddedElsewhere] = useState<ServiceLaborInput[]>([])
   const savedLaborKey = JSON.stringify(initialData.laborItems ?? [])
   const syncedLaborRef = useRef<ServiceLaborInput[]>(initialData.laborItems ?? [])
@@ -199,7 +208,7 @@ export function useServiceFormState({
       setLaborAddedElsewhere([])
       return
     }
-    const added = addedLaborLines(previous, saved)
+    const added = addedLaborLines(previous, saved, sendingLinesRef.current?.labor)
     if (added.length > 0) setLaborAddedElsewhere((current) => [...current, ...added])
   }, [savedLaborKey])
 
@@ -219,22 +228,51 @@ export function useServiceFormState({
       setPartsAddedElsewhere([])
       return
     }
-    const added = addedPartLines(previous, saved)
+    const added = addedPartLines(previous, saved, sendingLinesRef.current?.parts)
     if (added.length > 0) setPartsAddedElsewhere((current) => [...current, ...added])
   }, [savedPartsKey])
 
+  // What is waiting behind the banner as of the last render. A save's answer
+  // reads it: lines that arrived while the save ran are on the server too.
+  const laborPendingRef = useRef(laborAddedElsewhere)
+  const partsPendingRef = useRef(partsAddedElsewhere)
+  useEffect(() => {
+    laborPendingRef.current = laborAddedElsewhere
+  }, [laborAddedElsewhere])
+  useEffect(() => {
+    partsPendingRef.current = partsAddedElsewhere
+  }, [partsAddedElsewhere])
+
   /**
-   * A save went through while the page stays unsaved (a reading held back for
-   * its question): the lines it sent are the server's now. Without this the
-   * refresh after it brought them back as lines added elsewhere, and the next
-   * save sent them twice.
+   * A save went through: the lines it sent are the server's now. The page can
+   * be unsaved again when the refresh after it arrives (a reading held back
+   * for its question, or a preset applied while the save ran). Without this
+   * that refresh was compared with the lines from before the save, the line
+   * just edited read as one added elsewhere, it showed twice, and the next
+   * save sent it twice.
+   *
+   * Two things keep that comparison honest. The lines are kept as the server
+   * returns them (savedLaborShape, savedPartShape), not as typed. And a line
+   * a technician added while the save ran stays known: it is still waiting
+   * behind the banner, and forgetting it here brought it back a second time
+   * with the next refresh. Called from the save that was started in this
+   * render, so the waiting lines that save sent are the first ones counted
+   * here; the rest arrived after it (see commitLaborAddedElsewhere).
    */
+  const laborSent = laborAddedElsewhere.length
+  const partsSent = partsAddedElsewhere.length
   const acknowledgeSavedLines = useCallback(
     (lines: { parts: ServicePartInput[]; labor: ServiceLaborInput[] }) => {
-      syncedPartsRef.current = lines.parts
-      syncedLaborRef.current = lines.labor
+      syncedPartsRef.current = [
+        ...lines.parts.map(savedPartShape),
+        ...partsPendingRef.current.slice(partsSent),
+      ]
+      syncedLaborRef.current = [
+        ...lines.labor.map(savedLaborShape),
+        ...laborPendingRef.current.slice(laborSent),
+      ]
     },
-    []
+    [laborSent, partsSent]
   )
 
   useEffect(() => {
@@ -640,6 +678,7 @@ export function useServiceFormState({
     confirmedReadingRef,
     confirmReading,
     acknowledgeSavedLines,
+    sendingLinesRef,
     /**
      * Whether edits are still unsaved, read at the moment of the call. For
      * code that awaits saveNow and has to know whether the save went

+ 46 - 7
src/features/vehicles/Lib/laborLines.ts

@@ -10,17 +10,47 @@ import { isShopFeeLine } from '@/features/settings/Lib/shopFee'
  * booked twice) still reads as one line added.
  */
 
-const key = (line: ServiceLaborInput) =>
-  JSON.stringify([line.description, line.hours, line.rate, line.total, line.pricingType])
+/**
+ * A line as the server hands it back after a save. The editor holds what is
+ * typed (hours and rate as the strings in the boxes, the pricing type left
+ * out on an old row); the save coerces them, and the refresh after it brings
+ * back numbers. Both sides of every comparison go through this, so a line the
+ * page has just saved is never read as a different one.
+ */
+export function savedLaborShape(line: ServiceLaborInput): ServiceLaborInput {
+  return {
+    ...line,
+    hours: Number(line.hours) || 0,
+    rate: Number(line.rate) || 0,
+    total: Number(line.total) || 0,
+    pricingType: line.pricingType || 'hourly',
+  }
+}
+
+const key = (line: ServiceLaborInput) => {
+  const saved = savedLaborShape(line)
+  return JSON.stringify([
+    saved.description,
+    saved.hours,
+    saved.rate,
+    saved.total,
+    saved.pricingType,
+  ])
+}
 
 export function addedLaborLines(
   before: readonly ServiceLaborInput[],
-  after: readonly ServiceLaborInput[]
+  after: readonly ServiceLaborInput[],
+  /**
+   * What a save still on its way sent. A read of the job can land either side
+   * of that save's write, so a line counts as added only if it is new against
+   * both: the page's own edit coming back is not somebody else's work.
+   */
+  sending?: readonly ServiceLaborInput[]
 ): ServiceLaborInput[] {
-  const remaining = new Map<string, number>()
-  for (const line of before) {
-    const k = key(line)
-    remaining.set(k, (remaining.get(k) ?? 0) + 1)
+  const remaining = counts(before)
+  if (sending) {
+    for (const [k, n] of counts(sending)) remaining.set(k, Math.max(remaining.get(k) ?? 0, n))
   }
   const added: ServiceLaborInput[] = []
   for (const line of after) {
@@ -32,3 +62,12 @@ export function addedLaborLines(
   }
   return added
 }
+
+function counts(lines: readonly ServiceLaborInput[]): Map<string, number> {
+  const map = new Map<string, number>()
+  for (const line of lines) {
+    const k = key(line)
+    map.set(k, (map.get(k) ?? 0) + 1)
+  }
+  return map
+}

+ 44 - 13
src/features/vehicles/Lib/partLines.ts

@@ -10,24 +10,46 @@ import type { ServicePartInput } from '@/features/vehicles/Schema/serviceSchema'
  * part added.
  */
 
-const key = (part: ServicePartInput) =>
-  JSON.stringify([
-    part.name,
-    part.partNumber ?? null,
-    part.quantity,
-    part.unitPrice,
-    part.total,
-    part.inventoryPartId ?? null,
+/**
+ * A part as the server hands it back after a save. The editor holds what is
+ * typed (numbers as the strings in the boxes) and a preset's part carries an
+ * empty part number and inventory link where the page's own rows carry none;
+ * the save coerces both, and the refresh after it brings back numbers. Both
+ * sides of every comparison go through this, so a part the page has just
+ * saved is never read as a different one.
+ */
+export function savedPartShape(part: ServicePartInput): ServicePartInput {
+  return {
+    ...part,
+    partNumber: part.partNumber || '',
+    quantity: Number(part.quantity) || 0,
+    unitPrice: Number(part.unitPrice) || 0,
+    total: Number(part.total) || 0,
+    inventoryPartId: part.inventoryPartId || undefined,
+  }
+}
+
+const key = (part: ServicePartInput) => {
+  const saved = savedPartShape(part)
+  return JSON.stringify([
+    saved.name,
+    saved.partNumber,
+    saved.quantity,
+    saved.unitPrice,
+    saved.total,
+    saved.inventoryPartId ?? null,
   ])
+}
 
 export function addedPartLines(
   before: readonly ServicePartInput[],
-  after: readonly ServicePartInput[]
+  after: readonly ServicePartInput[],
+  /** What a save still on its way sent; see addedLaborLines. */
+  sending?: readonly ServicePartInput[]
 ): ServicePartInput[] {
-  const remaining = new Map<string, number>()
-  for (const part of before) {
-    const k = key(part)
-    remaining.set(k, (remaining.get(k) ?? 0) + 1)
+  const remaining = counts(before)
+  if (sending) {
+    for (const [k, n] of counts(sending)) remaining.set(k, Math.max(remaining.get(k) ?? 0, n))
   }
   const added: ServicePartInput[] = []
   for (const part of after) {
@@ -38,3 +60,12 @@ export function addedPartLines(
   }
   return added
 }
+
+function counts(parts: readonly ServicePartInput[]): Map<string, number> {
+  const map = new Map<string, number>()
+  for (const part of parts) {
+    const k = key(part)
+    map.set(k, (map.get(k) ?? 0) + 1)
+  }
+  return map
+}