Browse Source

Keep the inventory cost on a part added from stock (#679)

* Keep the inventory cost on a part added from stock

* Keep a part's own price after a save and on a fluid added from stock
Bernt Christian Egeland 3 ngày trước cách đây
mục cha
commit
e11f37afa1

+ 18 - 1
src/__tests__/features/integrations/fluid-stock.test.ts

@@ -9,6 +9,7 @@ import {
   type StockPart,
   volumeUnitOf,
 } from '@/features/integrations/Lib/fluid-stock'
+import { repricePartRow } from '@/features/inventory/Lib/partPricing'
 
 function part(id: string, name: string, extra: Partial<StockPart> = {}): StockPart {
   return {
@@ -163,10 +164,25 @@ describe('fluidPartLine', () => {
       unit: 'l',
       category: null,
       unitCost: 100,
-      markupPercent: 0,
+      // The markup the sell price implies over the cost, as the part row shows it.
+      markupPercent: 89,
       unitPrice: 189,
       total: 1077.3,
       inventoryPartId: 'a',
+      priceOverridden: false,
+    })
+  })
+
+  it('keeps a stocked price the rounded markup cannot rebuild as set by hand', () => {
+    // 133.37 over 100 shows as 33.4%, which would make it 133.40 the moment
+    // the cost box is left, so the line must keep the item's own price.
+    const line = fluidPartLine(OIL, {
+      units: 'both',
+      part: part('a', 'Motorolje 0W-20', { sellPrice: 133.37 }),
+    })
+    expect(line).toMatchObject({ unitPrice: 133.37, markupPercent: 33.4, priceOverridden: true })
+    expect(repricePartRow({ ...line, unitCost: 100 }, 'unitCost', { commit: true })).toMatchObject({
+      unitPrice: 133.37,
     })
   })
 
@@ -200,6 +216,7 @@ describe('fluidPartLine', () => {
       unitPrice: 0,
       total: 0,
       inventoryPartId: null,
+      priceOverridden: false,
     })
     expect(fluidPartLine(OIL, { units: 'us' })).toMatchObject({ quantity: 6.02, unit: 'qt' })
   })

+ 21 - 4
src/__tests__/features/inventory/part-pricing.test.ts

@@ -277,8 +277,25 @@ describe('readPartsPricingSettings', () => {
 })
 
 describe('resolvePartPrice', () => {
-  it("uses the part's own sell price when it has one", () => {
+  it("uses the part's own sell price when it has one, with the markup that price implies", () => {
+    // Reported as 0 beside a price over cost, the line read as sold at cost.
     expect(resolvePartPrice({ unitCost: 10, sellPrice: 25 })).toEqual({
+      unitPrice: 25,
+      markupPercent: 150,
+    })
+  })
+
+  it('reports a sell-price markup the part row shows unchanged', () => {
+    // The live case: bought at 6.40, sold at 12.50. The row rebuilds the price
+    // from cost and markup, and it must land on the sell price, not move it.
+    const picked = resolvePartPrice({ unitCost: 6.4, sellPrice: 12.5 })
+    expect(picked).toEqual({ unitPrice: 12.5, markupPercent: 95.3 })
+    expect(priceFromCostAndMarkup(6.4, picked.markupPercent)).toBe(12.5)
+    expect(isPriceOverridden({ unitCost: 6.4, ...picked })).toBe(false)
+  })
+
+  it('reports no markup on a part with no cost, rather than an infinite one', () => {
+    expect(resolvePartPrice({ unitCost: 0, sellPrice: 25 })).toEqual({
       unitPrice: 25,
       markupPercent: 0,
     })
@@ -303,7 +320,7 @@ describe('resolvePartPrice', () => {
         { unitCost: 10, sellPrice: 25 },
         { markupAppliesToInventory: false, defaultMarkupPercent: 40 }
       )
-    ).toEqual({ unitPrice: 25, markupPercent: 0 })
+    ).toEqual({ unitPrice: 25, markupPercent: 150 })
   })
 
   it('prices from cost plus markup when the setting is on', () => {
@@ -342,7 +359,7 @@ describe('resolvePartPrice', () => {
           { unitCost: 10, sellPrice: 25 },
           { markupAppliesToInventory: true, defaultMarkupPercent }
         )
-      ).toEqual({ unitPrice: 25, markupPercent: 0 })
+      ).toEqual({ unitPrice: 25, markupPercent: 150 })
     }
   })
 })
@@ -360,7 +377,7 @@ describe('settings to line total, end to end', () => {
     const pricing = readSettings(settingsMap('50', 'false'))
     const { unitPrice, markupPercent } = resolvePartPrice(part, pricing)
     expect(unitPrice).toBe(90)
-    expect(markupPercent).toBe(0)
+    expect(markupPercent).toBe(125)
     expect(lineTotal(part.quantity, unitPrice)).toBe(270)
   })
 

+ 171 - 0
src/__tests__/features/inventory/stock-part-cost.test.tsx

@@ -0,0 +1,171 @@
+/**
+ * A part taken from stock keeps what the workshop paid for it.
+ *
+ * Picked from inventory, a part bought at 6.40 and sold at 12.50 used to land
+ * on the line at a markup of 0, and one brought in by a labour preset at a
+ * cost of 0, so the job and the reports showed no parts cost and no profit.
+ * The row now shows the item's cost and the markup its price implies, the
+ * same markup the row would work out itself, and those are what get saved.
+ */
+
+import { fireEvent, render, screen, within } from '@testing-library/react'
+import { useCallback, useState } from 'react'
+import { describe, expect, it, vi } from 'vitest'
+import { TooltipProvider } from '@/components/ui/tooltip'
+import { costFieldsForPrice } from '@/features/inventory/Lib/partPricing'
+import { QuotePartsEditor } from '@/features/quotes/Components/QuotePartsEditor'
+import type { QuotePartInput } from '@/features/quotes/Schema/quoteSchema'
+import { quotePartSchema } from '@/features/quotes/Schema/quoteSchema'
+import { InventoryPickerDialog } from '@/features/vehicles/Components/service-edit/InventoryPickerDialog'
+import { PartsEditor } from '@/features/vehicles/Components/service-edit/PartsEditor'
+import type { InventoryPartOption } from '@/features/vehicles/Components/service-edit/form-types'
+import { type ServicePartInput, servicePartSchema } from '@/features/vehicles/Schema/serviceSchema'
+
+const WIPER: InventoryPartOption = {
+  id: 'inv-wiper',
+  name: 'Wiper blade',
+  partNumber: 'WB-500',
+  barcode: null,
+  description: null,
+  unit: null,
+  unitCost: 6.4,
+  sellPrice: 12.5,
+  quantity: 8,
+  category: null,
+  tags: [],
+}
+
+/** The work order's parts card with its stock picker, as the page wires them. */
+function WorkOrderParts({ onChange }: { onChange: (rows: ServicePartInput[]) => void }) {
+  const [rows, setRows] = useState<ServicePartInput[]>([])
+  const [pickerOpen, setPickerOpen] = useState(false)
+  onChange(rows)
+  const update = useCallback(
+    (index: number, field: keyof ServicePartInput, value: string | number) =>
+      setRows((prev) => prev.map((row, i) => (i === index ? { ...row, [field]: value } : row))),
+    []
+  )
+  return (
+    <TooltipProvider>
+      <PartsEditor
+        partItems={rows}
+        setPartItems={setRows}
+        updatePart={update}
+        partsSubtotal={0}
+        currencyCode="GBP"
+        hasInventory
+        onOpenInventory={() => setPickerOpen(true)}
+      />
+      <InventoryPickerDialog
+        open={pickerOpen}
+        onOpenChange={setPickerOpen}
+        inventoryParts={[WIPER]}
+        currencyCode="GBP"
+        onSelectPart={(part) => setRows((prev) => [part, ...prev])}
+      />
+    </TooltipProvider>
+  )
+}
+
+const pickWiper = () => {
+  const dialog = screen.getByRole('dialog')
+  fireEvent.click(within(dialog).getByText('Wiper blade', { exact: false }))
+}
+
+describe('a part picked from inventory on a work order', () => {
+  it('shows the item cost and the markup its sell price implies', () => {
+    let rows: ServicePartInput[] = []
+    render(<WorkOrderParts onChange={(r) => (rows = r)} />)
+
+    fireEvent.click(screen.getByRole('button', { name: 'From Inventory' }))
+    pickWiper()
+
+    expect(screen.getByPlaceholderText('Cost')).toHaveValue(6.4)
+    expect(screen.getByPlaceholderText('Markup %')).toHaveValue(95.3)
+    expect(screen.getByDisplayValue('12.5')).toBeInTheDocument()
+
+    // What the save sends: the cost and markup survive the schema.
+    expect(servicePartSchema.parse(rows[0])).toMatchObject({
+      unitCost: 6.4,
+      markupPercent: 95.3,
+      unitPrice: 12.5,
+      total: 12.5,
+      inventoryPartId: 'inv-wiper',
+    })
+  })
+})
+
+describe('a part picked from inventory on a quote', () => {
+  it('arrives with the item cost and its markup, and shows them on the row', () => {
+    const onAddBulk = vi.fn()
+    const t = (key: string) => key
+    const { unmount } = render(
+      <QuotePartsEditor
+        partItems={[]}
+        currencyCode="GBP"
+        partsSubtotal={0}
+        onUpdate={vi.fn()}
+        onDelete={vi.fn()}
+        onMove={vi.fn()}
+        onAdd={vi.fn()}
+        onAddBulk={onAddBulk}
+        inventoryParts={[WIPER]}
+        t={t}
+      />
+    )
+    fireEvent.click(screen.getByRole('button', { name: /parts\.addFromInventory/ }))
+    pickWiper()
+
+    const [added] = onAddBulk.mock.calls[0][0] as QuotePartInput[]
+    expect(quotePartSchema.parse(added)).toMatchObject({
+      unitCost: 6.4,
+      markupPercent: 95.3,
+      unitPrice: 12.5,
+      inventoryPartId: 'inv-wiper',
+    })
+    unmount()
+
+    render(
+      <QuotePartsEditor
+        partItems={[added]}
+        currencyCode="GBP"
+        partsSubtotal={12.5}
+        onUpdate={vi.fn()}
+        onDelete={vi.fn()}
+        onMove={vi.fn()}
+        onAdd={vi.fn()}
+        t={t}
+      />
+    )
+    expect(screen.getByDisplayValue('6.4')).toBeInTheDocument()
+    expect(screen.getByDisplayValue('95.3')).toBeInTheDocument()
+    expect(screen.getByDisplayValue('12.5')).toBeInTheDocument()
+  })
+})
+
+describe('a part brought in by a labour preset', () => {
+  it('carries the linked stock cost under the preset price', () => {
+    expect(costFieldsForPrice(6.4, 12.5)).toEqual({
+      unitCost: 6.4,
+      markupPercent: 95.3,
+      priceOverridden: false,
+    })
+  })
+
+  it('keeps a price the rounded markup cannot rebuild as the preset set it', () => {
+    // 133.37 over 100 is 33.37%, held to 33.4%, which would make it 133.40.
+    expect(costFieldsForPrice(100, 133.37)).toEqual({
+      unitCost: 100,
+      markupPercent: 33.4,
+      priceOverridden: true,
+    })
+  })
+
+  it('has no cost and no markup when the part is not linked to stock', () => {
+    expect(costFieldsForPrice(undefined, 25)).toEqual({
+      unitCost: 0,
+      markupPercent: 0,
+      priceOverridden: true,
+    })
+  })
+})

+ 11 - 0
src/__tests__/features/tax/taxable-lines-retotal.test.ts

@@ -268,6 +268,17 @@ describe('a part booked onto a job', () => {
     unitCost: 120,
   }
 
+  it('keeps its cost and the markup its price implies', async () => {
+    // The technician app and the active-jobs scan add parts through here, and
+    // a line stored at markup 0 read as sold at cost on the job.
+    store.settings = PARTS_ONLY
+    store.labor = []
+
+    await addPart({ organizationId: 'org-1', userId: 'user-1', input })
+
+    expect(store.parts[0]).toMatchObject({ unitCost: 120, markupPercent: 66.7, unitPrice: 200 })
+  })
+
   it('is taxed where the workshop taxes parts, beside labor that is not', async () => {
     store.settings = PARTS_ONLY
     store.labor = [labor(300, false)]

+ 84 - 0
src/__tests__/features/vehicles/saved-part-price-override.test.tsx

@@ -0,0 +1,84 @@
+/**
+ * A part line's own price survives a save and a reload.
+ *
+ * A preset part sold at 133.37 over a stock cost of 100 shows a markup of
+ * 33.4%, which rebuilds 133.40, not 133.37. Whether a price was set over the
+ * formula is not stored, so the page read every saved line as following it,
+ * and the first cost edit after a save repriced the line: a cost of 110 made
+ * it 146.74. The page now reads that back from the stored figures, so the
+ * price holds and the markup is restated instead.
+ *
+ * The form state is the real hook; the rows come in the way the work order
+ * page builds them from the database.
+ */
+import { act, renderHook } from '@testing-library/react'
+import { describe, expect, it, vi } from 'vitest'
+import { useServiceFormState } from '@/features/vehicles/Components/service-page/useServiceFormState'
+import { editorPartRow } from '@/features/vehicles/Lib/partLines'
+
+vi.mock('next/navigation', () => ({
+  useRouter: () => ({ refresh: vi.fn(), push: vi.fn() }),
+  usePathname: () => '/vehicles/veh-1/service/rec-1',
+}))
+vi.mock('@/hooks/use-deferred-commit', () => ({
+  useDeferredCommit: () => ({ schedule: vi.fn(), cancel: vi.fn() }),
+}))
+
+/** A part line as the database holds it after the save. */
+const stored = (unitCost: number, markupPercent: number, unitPrice: number) => ({
+  partNumber: 'ZZ-WB-500',
+  name: 'ZZ Wiper blade',
+  quantity: 1,
+  unit: null,
+  category: null,
+  unitPrice,
+  total: unitPrice,
+  unitCost,
+  markupPercent,
+  inventoryPartId: 'inv-1',
+  taxable: true,
+})
+
+function openWorkOrder(parts: ReturnType<typeof stored>[]) {
+  return renderHook(() =>
+    useServiceFormState({
+      vehicleId: 'veh-1',
+      defaultTaxRate: 0,
+      currentUserName: 'Desk',
+      record: { id: 'rec-1', attachments: [], payments: [] } as never,
+      initialData: {
+        id: 'rec-1',
+        status: 'in-progress',
+        concerns: [],
+        partItems: parts.map(editorPartRow),
+        laborItems: [],
+        taxRate: 0,
+        taxInclusive: false,
+        discountValue: 0,
+      } as never,
+    })
+  )
+}
+
+describe('a saved part line, opened again', () => {
+  it('keeps a price the markup cannot rebuild when its cost is edited', () => {
+    const { result } = openWorkOrder([stored(100, 33.4, 133.37)])
+
+    act(() => result.current.updatePart(0, 'unitCost', '110', { commit: true }))
+
+    expect(result.current.partItems[0]).toMatchObject({
+      unitCost: '110',
+      unitPrice: 133.37,
+      markupPercent: 21.2,
+      total: 133.37,
+    })
+  })
+
+  it('still prices from cost and markup a line that follows them', () => {
+    const { result } = openWorkOrder([stored(6.4, 95.3, 12.5)])
+
+    act(() => result.current.updatePart(0, 'unitCost', '7', { commit: true }))
+
+    expect(result.current.partItems[0]).toMatchObject({ unitPrice: 13.67, markupPercent: 95.3 })
+  })
+})

+ 50 - 0
src/__tests__/multitenancy/labor-preset-isolation.test.ts

@@ -25,6 +25,7 @@ vi.mock('@/lib/db', () => ({
     laborPresetItem: {
       deleteMany: vi.fn(),
     },
+    inventoryPart: { findMany: vi.fn() },
     $transaction: vi.fn(),
   },
 }))
@@ -32,6 +33,7 @@ vi.mock('@/lib/db', () => ({
 import { getCachedSession, getCachedMembership } from '@/lib/cached-session'
 import { db } from '@/lib/db'
 import {
+  getLaborPresetsList,
   getLaborPreset,
   updateLaborPreset,
   deleteLaborPreset,
@@ -195,3 +197,51 @@ describe('deleteLaborPreset — cross-org isolation', () => {
     expect((result.data as any).deleted).toBe(true)
   })
 })
+
+describe('getLaborPresetsList — stock cost on preset parts', () => {
+  const presetPart = (name: string, inventoryPartId: string | null) => ({
+    name,
+    partNumber: null,
+    quantity: 1,
+    unit: null,
+    category: null,
+    unitPrice: 12.5,
+    inventoryPartId,
+    sortOrder: 0,
+  })
+
+  it("carries the linked item's cost, looked up only in the caller's workshop", async () => {
+    setupOrgAOwner()
+    vi.mocked(db.laborPreset.findMany).mockResolvedValue([
+      {
+        id: 'preset-a',
+        name: 'Wiper service',
+        description: null,
+        items: [],
+        parts: [
+          presetPart('Wiper blade', 'inv-wiper'),
+          presetPart('Shop rag', null),
+          presetPart('Foreign part', 'inv-org-b'),
+        ],
+      },
+    ] as any)
+    vi.mocked(db.inventoryPart.findMany).mockResolvedValue([
+      { id: 'inv-wiper', unitCost: 6.4 },
+    ] as any)
+
+    const result = await getLaborPresetsList()
+
+    expect(vi.mocked(db.inventoryPart.findMany)).toHaveBeenCalledWith(
+      expect.objectContaining({
+        where: { id: { in: ['inv-wiper', 'inv-org-b'] }, organizationId: ORG_A },
+      })
+    )
+    expect(result.success).toBe(true)
+    const parts = (result.data as any)[0].parts
+    expect(parts.map((p: { name: string; unitCost: number }) => [p.name, p.unitCost])).toEqual([
+      ['Wiper blade', 6.4],
+      ['Shop rag', 0],
+      ['Foreign part', 0],
+    ])
+  })
+})

+ 8 - 0
src/features/integrations/Lib/fluid-stock.ts

@@ -1,4 +1,5 @@
 import {
+  isPriceOverridden,
   lineTotal,
   type PricingSettings,
   resolvePartPrice,
@@ -46,6 +47,11 @@ export interface FluidPartLine {
   unitPrice: number
   total: number
   inventoryPartId: string | null
+  /**
+   * The price is the stocked item's own and the rounded markup cannot rebuild
+   * it, so a later cost edit keeps it instead of repricing the line.
+   */
+  priceOverridden: boolean
 }
 
 /**
@@ -248,6 +254,7 @@ export function fluidPartLine(
       unitPrice,
       total: lineTotal(quantity, unitPrice),
       inventoryPartId: part.id,
+      priceOverridden: isPriceOverridden({ unitCost: part.unitCost, markupPercent, unitPrice }),
     }
   }
   const unit = options.units === 'us' ? 'qt' : 'l'
@@ -262,5 +269,6 @@ export function fluidPartLine(
     unitPrice: 0,
     total: 0,
     inventoryPartId: null,
+    priceOverridden: false,
   }
 }

+ 29 - 1
src/features/inventory/Lib/partPricing.ts

@@ -144,6 +144,29 @@ export function markupFromCostAndPrice(cost: unknown, price: unknown): number {
   return Math.round((parseNumber(price) / parsedCost - 1) * 1000) / 10
 }
 
+/**
+ * The cost side of a line whose price is already settled, such as a part
+ * brought in by a labour preset: the preset fixes what the customer pays, and
+ * the cost is the linked stock item's (0 for a part with no stock link).
+ *
+ * The markup is the one the part row would show for that cost and price, and
+ * the price is marked as set by hand whenever the rounded markup cannot rebuild
+ * it exactly, so a later cost edit keeps the preset's price instead of
+ * repricing the line.
+ */
+export function costFieldsForPrice(
+  cost: unknown,
+  price: unknown
+): { unitCost: number; markupPercent: number; priceOverridden: boolean } {
+  const unitCost = parseNumber(cost)
+  const markupPercent = markupFromCostAndPrice(unitCost, price)
+  return {
+    unitCost,
+    markupPercent,
+    priceOverridden: isPriceOverridden({ unitCost, markupPercent, unitPrice: price }),
+  }
+}
+
 /**
  * What a line is worth. Rounded to the cent for the same reason every other
  * amount here is: this value is stored and then summed into a subtotal.
@@ -185,7 +208,12 @@ export function resolvePartPrice(
   // Otherwise the part's own sell price wins. Falling back to cost matters:
   // a part with no sell price set would otherwise be billed at zero, which is
   // worse than billing at cost and far easier to miss.
-  return { unitPrice: sell > 0 ? sell : cost, markupPercent: 0 }
+  //
+  // The markup is the one that price implies over the cost, worked out the way
+  // the part row works it out. Reported as 0 it read as "sold at cost" beside a
+  // price twice the cost, and the job's margin lost the difference.
+  const unitPrice = sell > 0 ? sell : cost
+  return { unitPrice, markupPercent: markupFromCostAndPrice(cost, unitPrice) }
 }
 
 /**

+ 25 - 1
src/features/labor-presets/Actions/laborPresetActions.ts

@@ -253,7 +253,7 @@ export async function deleteLaborPreset(presetId: string) {
 export async function getLaborPresetsList() {
   return withAuth(
     async ({ userId, organizationId }) => {
-      return db.laborPreset.findMany({
+      const presets = await db.laborPreset.findMany({
         where: { organizationId, isArchived: false },
         select: {
           id: true,
@@ -285,6 +285,30 @@ export async function getLaborPresetsList() {
         },
         orderBy: { name: 'asc' },
       })
+
+      // A preset part keeps no cost of its own. One linked to stock carries
+      // that item's current cost onto the line, so applying the preset does not
+      // book the part as free and wipe its profit off the job.
+      const stockIds = [
+        ...new Set(
+          presets.flatMap((p) => p.parts.map((part) => part.inventoryPartId).filter(Boolean))
+        ),
+      ] as string[]
+      const stock = stockIds.length
+        ? await db.inventoryPart.findMany({
+            where: { id: { in: stockIds }, organizationId },
+            select: { id: true, unitCost: true },
+          })
+        : []
+      const costOf = new Map(stock.map((s) => [s.id, s.unitCost]))
+
+      return presets.map((preset) => ({
+        ...preset,
+        parts: preset.parts.map((part) => ({
+          ...part,
+          unitCost: (part.inventoryPartId && costOf.get(part.inventoryPartId)) || 0,
+        })),
+      }))
     },
     {
       requiredPermissions: [

+ 2 - 0
src/features/labor-presets/Components/LaborPresetPickerDialog.tsx

@@ -24,6 +24,8 @@ export interface LaborPresetOption {
     unit: string | null
     category?: string | null
     unitPrice: number
+    /** The linked stock item's cost; 0 or absent for a part with no stock link. */
+    unitCost?: number
     inventoryPartId: string | null
     sortOrder: number
   }[]

+ 3 - 3
src/features/quotes/Components/QuotePageClient.tsx

@@ -61,7 +61,7 @@ import { QuoteNotesEditor } from './QuoteNotesEditor'
 import { QuoteRightColumn } from './QuoteRightColumn'
 import { QuoteCustomerResponse } from './QuoteCustomerResponse'
 import { VehicleCombobox } from './VehicleCombobox'
-import { lineTotal } from '@/features/inventory/Lib/partPricing'
+import { costFieldsForPrice, lineTotal } from '@/features/inventory/Lib/partPricing'
 import type { LaborGuideJob } from '@/features/vehicles/Components/labor-guide/LaborGuideDialog'
 import type { FluidPartLine } from '@/features/integrations/Lib/fluid-stock'
 import type { WarrantyTexts } from '@/lib/warranty'
@@ -190,8 +190,8 @@ export function QuotePageClient({
           quantity: part.quantity,
           unit: part.unit ?? null,
           category: part.category ?? null,
-          unitCost: 0,
-          markupPercent: 0,
+          // The cost of the linked stock item, so the quote's margin is real.
+          ...costFieldsForPrice(part.unitCost, part.unitPrice),
           unitPrice: part.unitPrice,
           total: lineTotal(part.quantity, part.unitPrice),
           excluded: false,

+ 1 - 0
src/features/quotes/Components/QuotePartsEditor.tsx

@@ -360,6 +360,7 @@ export const QuotePartsEditor = memo(function QuotePartsEditor({
                 unitCost: Number(picked.unitCost) || 0,
                 markupPercent: Number(picked.markupPercent) || 0,
                 unitPrice: picked.unitPrice,
+                priceOverridden: picked.priceOverridden ?? false,
                 total: lineTotal(picked.quantity, picked.unitPrice),
                 excluded: false,
                 inventoryPartId: picked.inventoryPartId ?? null,

+ 9 - 1
src/features/vehicles/Components/service-edit/InventoryPickerDialog.tsx

@@ -9,7 +9,7 @@ import { Search } from 'lucide-react'
 import { useFormatCurrency } from '@/components/currency-settings-context'
 import type { ServicePartInput } from '@/features/vehicles/Schema/serviceSchema'
 import type { InventoryPartOption } from './form-types'
-import { resolvePartPrice } from '@/features/inventory/Lib/partPricing'
+import { isPriceOverridden, resolvePartPrice } from '@/features/inventory/Lib/partPricing'
 import {
   type FitVehicle,
   fittingTags,
@@ -128,6 +128,14 @@ export function InventoryPickerDialog({
                   total: price,
                   unitCost: ip.unitCost,
                   markupPercent,
+                  // The markup is held to one decimal, so a sell price can sit
+                  // a cent off cost plus markup. It is the part's own price,
+                  // and a later cost edit must keep it rather than reprice it.
+                  priceOverridden: isPriceOverridden({
+                    unitCost: ip.unitCost,
+                    markupPercent,
+                    unitPrice: price,
+                  }),
                   inventoryPartId: ip.id,
                 })
                 onOpenChange(false)

+ 11 - 3
src/features/vehicles/Components/service-edit/PartsEditor.tsx

@@ -42,6 +42,7 @@ import {
   type PartSuggestion,
 } from '@/features/inventory/Components/PartNameSuggestions'
 import {
+  isPriceOverridden,
   lineTotal,
   priceFromCostAndMarkup,
   resolvePartPrice,
@@ -145,7 +146,7 @@ const SortablePartRow = memo(function SortablePartRow({
         // Stacked card while the editor is narrow, one table row once its
         // container is wide enough to hold every column at a usable size
         'grid grid-cols-[auto_1fr] gap-2 rounded-lg border p-2',
-        '@2xl:grid-cols-[auto_1fr_2fr_0.6fr_0.9fr_0.7fr_0.9fr_0.9fr_auto] @2xl:rounded-none @2xl:border-0 @2xl:p-0',
+        '@2xl:grid-cols-[auto_1fr_2fr_0.6fr_0.9fr_0.9fr_0.9fr_0.9fr_auto] @2xl:rounded-none @2xl:border-0 @2xl:p-0',
         isDragging && dragEnabled && 'z-10 opacity-75'
       )}
     >
@@ -246,7 +247,9 @@ const SortablePartRow = memo(function SortablePartRow({
               title={t('markupPercentHint')}
               value={part.markupPercent ?? 0}
               onChange={(e) => updatePart(index, 'markupPercent', e.target.value)}
-              className="pr-6"
+              // No spinner: beside the % sign it left room for two digits, and
+              // a markup of 95.3% read as "9".
+              className="pr-6 [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
             />
             <Percent className="pointer-events-none absolute right-2 top-1/2 h-3 w-3 -translate-y-1/2 text-muted-foreground" />
           </div>
@@ -337,6 +340,11 @@ export function PartsEditor({
             unitCost: picked.unitCost,
             unitPrice,
             markupPercent,
+            priceOverridden: isPriceOverridden({
+              unitCost: picked.unitCost,
+              markupPercent,
+              unitPrice,
+            }),
             // Derived from the row's own quantity, so the line still satisfies
             // total === quantity * unitPrice. Defaulting an empty or zero
             // quantity to 1 would bill a total its fields do not add up to.
@@ -461,7 +469,7 @@ export function PartsEditor({
               <option key={category} value={category} />
             ))}
           </datalist>
-          <div className="hidden grid-cols-[auto_1fr_2fr_0.6fr_0.9fr_0.7fr_0.9fr_0.9fr_auto] gap-2 text-xs font-medium text-muted-foreground @2xl:grid">
+          <div className="hidden grid-cols-[auto_1fr_2fr_0.6fr_0.9fr_0.9fr_0.9fr_0.9fr_auto] gap-2 text-xs font-medium text-muted-foreground @2xl:grid">
             <span className="w-6" />
             <span>{t('partNumber')}</span>
             <span>{t('name')}</span>

+ 13 - 3
src/features/vehicles/Components/service-page/ServicePageClient.tsx

@@ -73,7 +73,12 @@ import { referenceMissing } from '@/features/customer-reference/Lib/reference'
 import { ModernHero as ModernHeroBase } from './modern/ModernHero'
 import { revealRequiredMeters } from '@/features/meters/Lib/requiredMetersReveal'
 import type { WorkOrderJobProps, WorkOrderSidebarProps } from './modern/details-props'
-import { lineTotal, resolvePartPrice } from '@/features/inventory/Lib/partPricing'
+import {
+  costFieldsForPrice,
+  isPriceOverridden,
+  lineTotal,
+  resolvePartPrice,
+} from '@/features/inventory/Lib/partPricing'
 import { vehicleName } from '@/lib/vehicle-name'
 import { useDateSettings } from '@/components/date-settings-context'
 import { addDaysToDayKey, dayKeyToLocalDate, workshopTodayKey } from '@/lib/workshop-datetime'
@@ -301,6 +306,11 @@ export function ServicePageClient({
             total: lineTotal(1, unitPrice),
             unitCost: part.unitCost,
             markupPercent,
+            priceOverridden: isPriceOverridden({
+              unitCost: part.unitCost,
+              markupPercent,
+              unitPrice,
+            }),
             inventoryPartId: part.id,
           },
           ...prev,
@@ -443,8 +453,8 @@ export function ServicePageClient({
         category: part.category ?? null,
         unitPrice: part.unitPrice,
         total: lineTotal(part.quantity, part.unitPrice),
-        unitCost: 0,
-        markupPercent: 0,
+        // The cost of the linked stock item, so the job's margin is real.
+        ...costFieldsForPrice(part.unitCost, part.unitPrice),
         inventoryPartId: part.inventoryPartId || '',
       }))
       formState.dirtySetPartItems((prev) => [...newParts, ...prev])

+ 2 - 19
src/features/vehicles/Components/service-page/ServiceRecordPage.tsx

@@ -60,6 +60,7 @@ import { PageHeader } from '@/components/page-header'
 import { getLocale, getTranslations } from 'next-intl/server'
 import { workshopTimeZone } from '@/lib/workshop-timezone'
 import { zonedDayKey } from '@/lib/timezone'
+import { editorPartRow } from '@/features/vehicles/Lib/partLines'
 
 /**
  * Shared server component behind both service-record routes:
@@ -324,25 +325,7 @@ export async function ServiceRecordPage({
       confirmedAt: c.confirmedAt ? c.confirmedAt.toISOString() : null,
       confirmedByName: c.confirmedBy?.name ?? null,
     })),
-    partItems: record.partItems.map((p) => ({
-      partNumber: p.partNumber || '',
-      name: p.name,
-      quantity: p.quantity,
-      unit: p.unit ?? null,
-      category: p.category ?? null,
-      unitPrice: p.unitPrice,
-      total: p.total,
-      unitCost: p.unitCost ?? 0,
-      markupPercent: p.markupPercent ?? 0,
-      // Preserve the inventory link so editing/saving a work order keeps
-      // deducting the right stock. Without this, a saved edit sends unlinked
-      // parts and inventory reconciliation restocks the "removed" part.
-      inventoryPartId: p.inventoryPartId ?? undefined,
-      // Whether the line is taxed is the line's own. Left out here, a save
-      // would send the line back without it and the server would put the
-      // workshop's default over whatever had been chosen.
-      taxable: p.taxable,
-    })),
+    partItems: record.partItems.map(editorPartRow),
     laborItems: shopFeeLinesLast(record.laborItems).map((l) => ({
       description: l.description,
       hours: l.hours,

+ 4 - 0
src/features/vehicles/Lib/addPart.ts

@@ -6,6 +6,7 @@ import { loadTaxApplies } from '@/features/settings/Lib/loadTaxApplies'
 import { documentTotals } from '@/features/settings/Lib/workshopTax'
 import { reconcileInventoryForParts } from '@/features/inventory/Lib/reconcileStock'
 import { assertInvoiceEditable } from '@/lib/document-lock.server'
+import { markupFromCostAndPrice } from '@/features/inventory/Lib/partPricing'
 
 /**
  * Adds a part line to a job, recalculates the job's money, and moves the stock.
@@ -85,6 +86,9 @@ export async function addPart(args: {
         unitPrice: input.unitPrice,
         total: input.total,
         unitCost: input.unitCost,
+        // Stored beside the cost, as the work order's part row works it out,
+        // so the line reads the same margin there as everywhere else.
+        markupPercent: markupFromCostAndPrice(input.unitCost, input.unitPrice),
         inventoryPartId: input.inventoryPartId || null,
         taxable,
         serviceRecordId: record.id,

+ 47 - 0
src/features/vehicles/Lib/partLines.ts

@@ -1,5 +1,52 @@
+import { isPriceOverridden } from '@/features/inventory/Lib/partPricing'
 import type { ServicePartInput } from '@/features/vehicles/Schema/serviceSchema'
 
+/**
+ * A saved part line as the work order editor holds it.
+ *
+ * Whether the price was set over the cost-and-markup formula is not stored,
+ * so it is read back from the stored cost, markup and price, once, on settled
+ * values (see isPriceOverridden). Left out, a line whose price the rounded
+ * markup cannot rebuild, such as a preset's 133.37 over a cost of 100, was
+ * repriced from the formula the first time its cost was edited after a save.
+ */
+export function editorPartRow(p: {
+  partNumber: string | null
+  name: string
+  quantity: number
+  unit?: string | null
+  category?: string | null
+  unitPrice: number
+  total: number
+  unitCost: number | null
+  markupPercent: number | null
+  inventoryPartId: string | null
+  taxable: boolean
+}): ServicePartInput {
+  const unitCost = p.unitCost ?? 0
+  const markupPercent = p.markupPercent ?? 0
+  return {
+    partNumber: p.partNumber || '',
+    name: p.name,
+    quantity: p.quantity,
+    unit: p.unit ?? null,
+    category: p.category ?? null,
+    unitPrice: p.unitPrice,
+    total: p.total,
+    unitCost,
+    markupPercent,
+    // Preserve the inventory link so editing/saving a work order keeps
+    // deducting the right stock. Without this, a saved edit sends unlinked
+    // parts and inventory reconciliation restocks the "removed" part.
+    inventoryPartId: p.inventoryPartId ?? undefined,
+    // Whether the line is taxed is the line's own. Left out here, a save
+    // would send the line back without it and the server would put the
+    // workshop's default over whatever had been chosen.
+    taxable: p.taxable,
+    priceOverridden: isPriceOverridden({ unitCost, markupPercent, unitPrice: p.unitPrice }),
+  }
+}
+
 /**
  * What a job gained in parts while a page was open: a part a technician
  * scanned onto it from the app, say.