Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(sales): stop default markup from overwriting set quote-line prices (#1141)

Brad Barbin542fa8eb5e92
diff --git a/.ai/plans/2026-07-14-quote-line-markup-preservation.md b/.ai/plans/2026-07-14-quote-line-markup-preservation.md
new file mode 100644
index 0000000000..3bd6d4f1b5
--- /dev/null
+++ b/.ai/plans/2026-07-14-quote-line-markup-preservation.md
@@ -0,0 +1,445 @@
+# Quote Line Markup Preservation — implementation plan
+
+**Spec:** .ai/specs/2026-07-14-quote-line-markup-preservation.md
+**Research:** N/A (focused bug-fix; no competitor research — see spec)
+**Branch:** fixquote-markup-aggressiveness
+
+## Progress
+- [x] Task 1: Add pure pricing-decision helpers + unit tests (`sales.utils.ts`)
+- [x] Task 2: Wire helpers into `recalculateQuoteLinePrices` + `calculatePricesForQuantities`
+- [x] Task 3: Clear `categoryMarkups` on direct price / virtual-markup edits (UI)
+- [ ] Task 4: Browser-verify the acceptance criteria via `/test`
+
+## Dependencies
+- Task 2 needs Task 1 (imports the helpers).
+- Task 3 is independent of Tasks 1–2 (different file); may run in parallel.
+- Task 4 needs Tasks 2 and 3 (verifies end-to-end behavior).
+
+## Context the executor must know (no session memory assumed)
+
+- **Markup is virtual.** The only stored fields are `quoteLinePrice.unitPrice` and
+ `quoteLinePrice.categoryMarkups` (a JSONB map of cost-category → whole-percent
+ markup, e.g. `{ laborCost: 25 }` = 25%). The UI shows markup as
+ `(price − cost) / cost`.
+- **Company defaults** live in `companySettings.quoteLineCategoryMarkups`, stored
+ as **fractions** (0.30 = 30%); both service functions already multiply each
+ value by 100 to build a whole-percent `defaultMarkups` map.
+- **The bug:** `recalculateQuoteLinePrices` (runs on any BOM cost change) falls
+ back to `defaultMarkups` whenever a row's `categoryMarkups` is empty `{}`, and
+ recomputes `unitPrice` from cost — silently overwriting a price the user set.
+- **The fix (three row states):**
+ - *cost-plus* (`categoryMarkups` non-empty) → reprice from those markups (keep).
+ - *fixed price* (`categoryMarkups` empty **and** `unitPrice > 0`) → **preserve
+ `unitPrice`; never apply the default**.
+ - *unpriced* (`unitPrice` 0/null) → apply the default **if enabled**, else price
+ at cost.
+- **Disabled default:** when every category default is `0` (or empty), the whole
+ default-markup feature is off — never applied or seeded.
+- **No schema change.** All decisions key on `unitPrice` + `categoryMarkups`.
+
+---
+
+## Task 1: Add pure pricing-decision helpers + unit tests
+
+**Depends on:** none
+**Files:**
+- Create: `apps/erp/app/modules/sales/sales.utils.ts`
+- Create: `apps/erp/app/modules/sales/sales.utils.test.ts`
+- Copy from (precedent): `apps/erp/app/modules/accounting/accounting.utils.ts` and its test `apps/erp/app/modules/accounting/accounting.utils.test.ts` (pure functions + colocated vitest, zero DB/env imports)
+
+**Why a separate `sales.utils.ts`:** the pricing logic must be unit-testable
+without a database. `sales.service.ts` transitively imports `@carbon/env`,
+Supabase clients, and edge-function code — importing it into a test is heavy and
+side-effectful. `accounting.utils.ts` is the established home for DB-free logic;
+mirror it. Keep `sales.utils.ts` dependency-free (no imports).
+
+**Steps:**
+
+1. Create `apps/erp/app/modules/sales/sales.utils.ts` with exactly these exports:
+
+ ```ts
+ export type CategoryMarkups = Record<string, number>;
+
+ /**
+ * Company default markups are "enabled" only when at least one cost category
+ * has a positive markup. An all-zero or empty default means the feature is
+ * off, so it is treated as "no defaults" everywhere it is consumed.
+ * (Markups are whole-percent, non-negative — e.g. `{ laborCost: 25 }`.)
+ */
+ export function getEffectiveDefaultMarkups(
+ defaultMarkups: CategoryMarkups
+ ): CategoryMarkups {
+ const enabled = Object.values(defaultMarkups).some((v) => v > 0);
+ return enabled ? defaultMarkups : {};
+ }
+
+ export type RecalcPricingDecision =
+ | { mode: "reprice"; markups: CategoryMarkups }
+ | { mode: "preserve" };
+
+ /**
+ * Decide how `recalculateQuoteLinePrices` should treat one existing price row
+ * when a BOM cost changes:
+ * - cost-plus (explicit `categoryMarkups`) → reprice from those markups
+ * - fixed price (no markups but a set `unitPrice`) → preserve; never apply
+ * the default markup (the core fix)
+ * - unpriced (no markups, no price) → reprice from the effective defaults
+ * (which is `{}` — i.e. price at cost — when defaults are disabled)
+ */
+ export function decideRecalcPricing(
+ row: { categoryMarkups: CategoryMarkups | null; unitPrice: number | null },
+ effectiveDefaults: CategoryMarkups
+ ): RecalcPricingDecision {
+ const rowMarkups = row.categoryMarkups ?? {};
+ if (Object.keys(rowMarkups).length > 0) {
+ return { mode: "reprice", markups: rowMarkups };
+ }
+ if ((row.unitPrice ?? 0) > 0) {
+ return { mode: "preserve" };
+ }
+ return { mode: "reprice", markups: effectiveDefaults };
+ }
+ ```
+
+2. Create `apps/erp/app/modules/sales/sales.utils.test.ts` importing from
+ `./sales.utils` (relative import, like the accounting precedent). Cover every
+ spec acceptance criterion at the logic level:
+
+ ```ts
+ import { describe, expect, it } from "vitest";
+ import { decideRecalcPricing, getEffectiveDefaultMarkups } from "./sales.utils";
+
+ describe("getEffectiveDefaultMarkups", () => {
+ it("returns {} when all category defaults are 0 (feature disabled)", () => {
+ expect(getEffectiveDefaultMarkups({ laborCost: 0, materialCost: 0 })).toEqual({});
+ });
+ it("returns {} when the defaults object is empty", () => {
+ expect(getEffectiveDefaultMarkups({})).toEqual({});
+ });
+ it("returns the defaults unchanged when at least one is positive", () => {
+ const d = { laborCost: 30, materialCost: 0 };
+ expect(getEffectiveDefaultMarkups(d)).toEqual(d);
+ });
+ });
+
+ describe("decideRecalcPricing", () => {
+ it("reprices a cost-plus row from its explicit categoryMarkups", () => {
+ expect(
+ decideRecalcPricing({ categoryMarkups: { laborCost: 20 }, unitPrice: 120 }, { laborCost: 30 })
+ ).toEqual({ mode: "reprice", markups: { laborCost: 20 } });
+ });
+ it("PRESERVES a fixed-price row (empty markups, price set) — default never overrides", () => {
+ expect(
+ decideRecalcPricing({ categoryMarkups: {}, unitPrice: 110 }, { laborCost: 30 })
+ ).toEqual({ mode: "preserve" });
+ });
+ it("preserves a fixed-price row even when the default is 0% (the reported case)", () => {
+ expect(
+ decideRecalcPricing({ categoryMarkups: {}, unitPrice: 110 }, {})
+ ).toEqual({ mode: "preserve" });
+ });
+ it("treats null categoryMarkups as empty", () => {
+ expect(
+ decideRecalcPricing({ categoryMarkups: null, unitPrice: 110 }, {})
+ ).toEqual({ mode: "preserve" });
+ });
+ it("prices an unpriced row from the effective defaults", () => {
+ expect(
+ decideRecalcPricing({ categoryMarkups: {}, unitPrice: 0 }, { laborCost: 30 })
+ ).toEqual({ mode: "reprice", markups: { laborCost: 30 } });
+ });
+ it("prices an unpriced row at cost (empty markups) when defaults are disabled", () => {
+ expect(
+ decideRecalcPricing({ categoryMarkups: {}, unitPrice: 0 }, {})
+ ).toEqual({ mode: "reprice", markups: {} });
+ });
+ });
+ ```
+
+**Verify:**
+```bash
+pnpm --filter erp exec vitest run app/modules/sales/sales.utils.test.ts
+# Expected: "Test Files 1 passed (1)" and all tests passing (9 tests)
+```
+
+**Out of scope:** Do NOT put these helpers in `sales.service.ts`, and do NOT add
+DB/env/Supabase imports to `sales.utils.ts` (keeps the test fast and pure). Do
+not add them to the `index.ts` barrel — `sales.service.ts` and the test import
+them directly via `./sales.utils`.
+
+---
+
+## Task 2: Wire helpers into the two service functions
+
+**Depends on:** Task 1
+**Files:**
+- Modify: `apps/erp/app/modules/sales/sales.service.ts` — add import; rewrite the per-row loop in `recalculateQuoteLinePrices`; use effective defaults in `calculatePricesForQuantities`
+
+**Steps:**
+
+1. Add the import near the existing `import { costCategoryKeys } from "./sales.models";`
+ (line ~58):
+ ```ts
+ import { decideRecalcPricing, getEffectiveDefaultMarkups } from "./sales.utils";
+ ```
+
+2. **`recalculateQuoteLinePrices`** (currently `:4423-4551`). The defaults are
+ built into `defaultMarkups` at `:4457-4474` — leave that block as is. Replace
+ the per-row loop that currently starts at `const updatedRows = [];` (`:4482`)
+ and runs through the end of the `for` loop (`:4526`) with:
+
+ ```ts
+ const effectiveDefaults = getEffectiveDefaultMarkups(defaultMarkups);
+
+ const updatedRows = [];
+ for (const row of existingPrices.data) {
+ const qty = row.quantity;
+
+ const decision = decideRecalcPricing(
+ {
+ categoryMarkups: row.categoryMarkups as Record<string, number> | null,
+ unitPrice: row.unitPrice
+ },
+ effectiveDefaults
+ );
+
+ // Fixed price: the user set an explicit price and the row has no
+ // per-category markups. Preserve it exactly — never re-derive from the
+ // default markup (the core fix).
+ if (decision.mode === "preserve") {
+ updatedRows.push({
+ quoteId: row.quoteId,
+ quoteLineId: row.quoteLineId,
+ companyId: row.companyId,
+ quantity: row.quantity,
+ unitPrice: row.unitPrice,
+ categoryMarkups: row.categoryMarkups ?? {},
+ exchangeRate: row.exchangeRate,
+ createdBy: row.createdBy,
+ updatedBy: userId,
+ leadTime: row.leadTime,
+ discountPercent: row.discountPercent
+ });
+ continue;
+ }
+
+ const markups = decision.markups;
+
+ const categoryCosts: Record<string, number> = {};
+ for (const key of costCategoryKeys) {
+ const total = effects[key].reduce((acc, fn) => acc + fn(qty), 0);
+ categoryCosts[key] = qty > 0 ? total / qty : 0;
+ }
+
+ const rollupPrice = costCategoryKeys.reduce((sum, key) => {
+ const cost = categoryCosts[key] ?? 0;
+ const markup = markups[key] ?? 0;
+ return sum + cost * (1 + markup / 100);
+ }, 0);
+
+ const finalPrice =
+ itemId && companyId
+ ? (
+ await resolvePrice(client, companyId, {
+ itemId,
+ quantity: qty,
+ customerId,
+ existingBasePrice: rollupPrice
+ })
+ ).finalPrice
+ : rollupPrice;
+
+ updatedRows.push({
+ quoteId: row.quoteId,
+ quoteLineId: row.quoteLineId,
+ companyId: row.companyId,
+ quantity: row.quantity,
+ unitPrice: Number(finalPrice.toFixed(precision)),
+ categoryMarkups: markups,
+ exchangeRate: row.exchangeRate,
+ createdBy: row.createdBy,
+ updatedBy: userId,
+ leadTime: row.leadTime,
+ discountPercent: row.discountPercent
+ });
+ }
+ ```
+
+ The delete-then-reinsert block after the loop (`:4528-4550`) is unchanged.
+
+3. **`calculatePricesForQuantities`** (currently `:4182-4288`). The defaults are
+ built into `defaultMarkups` at `:4223-4230` — leave that block as is. Then:
+
+ a. Immediately after that block, add:
+ ```ts
+ const effectiveDefaults = getEffectiveDefaultMarkups(defaultMarkups);
+ ```
+
+ b. In the `rollupPrice` reducer (`:4248-4252`), change the markup lookup from
+ `defaultMarkups[key]` to `effectiveDefaults[key]`:
+ ```ts
+ const rollupPrice = costCategoryKeys.reduce((sum, key) => {
+ const cost = categoryCosts[key] ?? 0;
+ const markup = effectiveDefaults[key] ?? 0;
+ return sum + cost * (1 + markup / 100);
+ }, 0);
+ ```
+
+ c. In the `priceRows.push({...})` object (`:4271`), change
+ `categoryMarkups: defaultMarkups` to `categoryMarkups: effectiveDefaults` so a
+ disabled default seeds `{}` (fixed/unpriced) instead of a stale `{ …: 0 }`
+ cost-plus row.
+
+4. Do not touch `resolveQuoteLinePrices`, `resolvePurchaseToOrderPrices`, or
+ `upsertQuoteLinePrices` — they already insert/preserve empty `categoryMarkups`
+ and behave correctly under the new recalc rules.
+
+ If a grep shows any **other** function in `sales.service.ts` reads
+ `quoteLineCategoryMarkups` or seeds `categoryMarkups` from defaults, STOP and
+ report — the spec accounted for exactly these two sites.
+
+**Verify:**
+```bash
+grep -n "quoteLineCategoryMarkups\|effectiveDefaults\|getEffectiveDefaultMarkups\|decideRecalcPricing" apps/erp/app/modules/sales/sales.service.ts
+# Expected: the two default-building sites (calculatePricesForQuantities, recalculateQuoteLinePrices),
+# two `getEffectiveDefaultMarkups(...)` calls, one `decideRecalcPricing(...)` call,
+# and effectiveDefaults used in both functions. No third consumer of quoteLineCategoryMarkups.
+
+pnpm exec turbo run typecheck --filter=erp
+# Expected: tasks succeed, no TypeScript errors. (tsgo --noEmit for the erp app)
+```
+
+**Out of scope:** No behavior change to `resolvePrice`/`applyPriceRules`; no
+schema/migration; do not alter the delete-then-reinsert mechanics or the
+preserved `discountPercent`/`leadTime`/`exchangeRate` handling.
+
+---
+
+## Task 3: Clear `categoryMarkups` on direct price / virtual-markup edits (UI)
+
+**Depends on:** none (independent of Tasks 1–2; may run in parallel)
+**Files:**
+- Modify: `apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx` — `onUpdatePrice` (`:481-558`)
+- Reference (do NOT change): `onUpdateCategoryMarkup` (`:430-479`) already writes `categoryMarkups` + `unitPrice`; it is the *cost-plus* path and stays as-is.
+
+**Why:** `onUpdatePrice` handles both the direct price cell and the virtual
+**Markup Percent** cell (`:825-830`, which calls `onUpdatePrice("unitPrice", …)`).
+Today it saves only `unitPrice`, leaving any stale `categoryMarkups` in place — so
+a later recalc reverts a Make-to-Order line to its seeded markup (the non-zero
+default variant, spec Q3-A). Clearing `categoryMarkups` on a `unitPrice` edit
+makes the row a *fixed price* so the explicit value wins. Non-`unitPrice` keys
+(`leadTime`, `discountPercent`, `shippingCost`) must NOT clear markups.
+
+**Steps:**
+
+1. In `onUpdatePrice`, the optimistic-state line (`:510`):
+ ```ts
+ newPrices[quantity] = { ...newPrices[quantity], [key]: roundedValue };
+ ```
+ Replace with (adds an empty-markups clear only for `unitPrice`):
+ ```ts
+ newPrices[quantity] = {
+ ...newPrices[quantity],
+ [key]: roundedValue,
+ ...(key === "unitPrice" ? { categoryMarkups: {} } : {})
+ };
+ ```
+
+2. In the `hasPrice` DB update branch (`:518-526`), change:
+ ```ts
+ .update({
+ [key]: roundedValue,
+ quoteLineId: lineId,
+ quantity
+ })
+ ```
+ to:
+ ```ts
+ .update({
+ [key]: roundedValue,
+ ...(key === "unitPrice" ? { categoryMarkups: {} } : {}),
+ quoteLineId: lineId,
+ quantity
+ })
+ ```
+
+3. The `else` insert branch (`:534-538`) inserts `...newPrices[quantity]`, which
+ now already carries `categoryMarkups: {}` for a `unitPrice` edit (from step 1)
+ — no change needed there.
+
+4. `onUpdateCategoryMarkup` (`:430`) is unchanged — do not edit it.
+
+ If TypeScript rejects `categoryMarkups: {}` on either the `QuotationPrice`
+ spread or the Supabase `.update(...)`, cast the empty object with
+ `{} as Record<string, number>` (this matches how `onUpdateCategoryMarkup`
+ passes `Record<string, number>` to the same `.update`). If it still fails,
+ STOP and report — do not silence it with `@ts-expect-error`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: tasks succeed, no TypeScript errors.
+```
+
+**Out of scope:** No display-fallback change — the per-category cells already
+render `?? 0` (spec UI §2); the virtual **Markup Percent** row reads the real
+price and is accurate. Do not touch the settings UI (`CategoryMarkupsCard`).
+
+---
+
+## Task 4: Browser-verify the acceptance criteria via `/test`
+
+**Depends on:** Tasks 2 and 3
+**Files:** none (verification only)
+
+**Preconditions:**
+- Boot the local stack with `crbn up` (portless `*.dev`). If it will not boot,
+ STOP and report — the fix is unverified, not done.
+- Use the `/auth` skill to log into the ERP dev server, then `/test`.
+
+**Steps (drive the running app; each maps to a spec acceptance criterion):**
+
+1. **Configure defaults = 0%.** Go to `/x/settings/sales`, ensure every category
+ in the "Category Markups" card is `0`, save. (This is the "disabled" state.)
+2. **Reported case — 0% default must not clobber a set markup.** Open (or create)
+ a Draft quote with a line that has a costed make method (BOM with at least one
+ material). In the line's Pricing card, set the **Markup Percent** cell to 10%
+ for a quantity break; note the resulting unit price (e.g. cost $100 → $110).
+ Then edit a BOM material's unit cost (via the line's Materials). Reload the
+ Pricing card:
+ - **Expect:** the unit price is still the value you set (≈ $110), NOT collapsed
+ to cost. The markup reads ~10% adjusted only by the cost change — never 0%.
+3. **Cost-plus still reprices.** On another quantity break, use the per-category
+ **markup** editor to set e.g. labor 20%. Change a BOM cost. Reload:
+ - **Expect:** the price updated to reflect the new cost at 20% (markup held,
+ price moved) — the cost-plus feature still works.
+4. **Non-zero default variant.** Set the "Category Markups" default to a non-zero
+ value (e.g. 30%). Create a new Make-to-Order quote line (seeded at 30%), then
+ override its price directly in the price cell (e.g. to $150). Change a BOM cost.
+ Reload:
+ - **Expect:** the price stays $150 — the stale 30% does not revert it.
+5. **Discount/leadtime survive.** On any line above, set a discount %, then change
+ a BOM cost. **Expect:** the discount (and lead time) are unchanged after recalc.
+
+**Verify:** All five expectations hold in the browser. Capture a screenshot of the
+Pricing card in step 2 before/after the cost change (per the surface-designs/PR
+convention) and attach to the PR. If any expectation fails, STOP and report — do
+not adjust the assertions to pass.
+
+**Out of scope:** Do not re-test unrelated quote flows; this task verifies only
+the markup-preservation behavior.
+
+---
+
+## Coverage check (spec acceptance criteria → tasks)
+
+| Spec AC | Covered by |
+|---|---|
+| 0% default: 10% line stays at price, not cost | Task 1 (logic) + Task 4 step 2 |
+| Non-zero default: direct override survives cost change | Task 3 + Task 4 step 4 |
+| Per-category markup still reprices | Task 1 (logic) + Task 4 step 3 |
+| Disabled default: new MtO line priced at cost, empty markups | Task 1 (logic) + Task 2 step 3 |
+| Enabled default: new line still auto-prices | Task 1 (logic) + Task 2 |
+| Pull / P2O prices survive cost change | Task 1 (logic — fixed-price preserve) + Task 4 |
+| discount/leadTime/exchangeRate survive recalc | Task 2 (preserved in both branches) + Task 4 step 5 |
+| `typecheck` passes | Tasks 2 & 3 Verify |
diff --git a/.ai/specs/2026-07-14-quote-line-markup-preservation.md b/.ai/specs/2026-07-14-quote-line-markup-preservation.md
new file mode 100644
index 0000000000..66e4718dc6
--- /dev/null
+++ b/.ai/specs/2026-07-14-quote-line-markup-preservation.md
@@ -0,0 +1,256 @@
+# Quote Line Markup Preservation — stop the default markup from overwriting a set price
+
+> Status: draft
+> Author: Brad Barbin
+> Date: 2026-07-14
+
+## TLDR
+
+When a BOM cost changes on a quote line, `recalculateQuoteLinePrices` reprices
+every quantity break. Today, any price row whose stored `categoryMarkups` is
+empty falls back to the **company default markups** and recomputes `unitPrice`
+from cost — silently overwriting a price the user had already set. With a 0%
+default, a line the user marked up 10% collapses to cost. This spec makes an
+already-set price authoritative: the default markup only ever prices rows that
+have **no price yet**, an all-zero default is treated as "feature off," and a
+direct price/markup edit clears any stored category markups so the user's value
+always wins. Markup is virtual (`(price − cost)/cost`), so "a price is set" is
+the signal we key on — no new schema column.
+
+## Problem Statement
+
+Markup on a quote line price is not stored as a scalar — it is derived in the UI
+as `(price − cost) / cost` (`apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx:812`).
+The persisted fields are `quoteLinePrice.unitPrice` and a per-cost-category
+`categoryMarkups` JSONB (whole-percent values, e.g. `25` = 25%). Company defaults
+live in `companySettings.quoteLineCategoryMarkups` (stored as fractions, ×100 on
+use); the default company value is `{}`.
+
+`recalculateQuoteLinePrices` (`apps/erp/app/modules/sales/sales.service.ts:4423-4551`)
+runs on every BOM material/operation change (add / edit / delete of a
+`quoteMaterial` or `quoteOperation`, and on quote-line creation). Its per-row
+logic:
+
+```ts
+// sales.service.ts:4485-4487
+const rowMarkups = (row.categoryMarkups as Record<string, number>) ?? {};
+const markups =
+ Object.keys(rowMarkups).length > 0 ? rowMarkups : defaultMarkups; // ← bug
+// unitPrice := Σ categoryCost × (1 + markups[cat]/100), then resolvePrice(...)
+```
+
+**How a row ends up with empty `categoryMarkups`:** the two most common editing
+paths save only `unitPrice` and never touch `categoryMarkups`:
+
+- Editing the price cell directly → `onUpdatePrice("unitPrice", …)` (`QuoteLinePricing.tsx:481`).
+- Editing the virtual **Markup Percent** cell → `onUpdatePrice("unitPrice", quantity, cost * (1 + value))` (`QuoteLinePricing.tsx:825-830`).
+
+Pull-from-inventory (`resolveQuoteLinePrices`) and purchase-to-order
+(`resolvePurchaseToOrderPrices`) rows also start with empty `categoryMarkups`.
+
+So a user-set price row has empty `categoryMarkups` → on the next cost change the
+fallback recomputes it from the **default** markup. With the default at 0% the
+price drops to cost. This is silent and, on a customer-facing quote,
+potentially devastating.
+
+**Second path to the same symptom (non-zero default):** `calculatePricesForQuantities`
+(Make-to-Order initial pricing, `sales.service.ts:4271`) *seeds*
+`categoryMarkups: defaultMarkups`. When the default is 0% it seeds
+`{ …: 0 }` — a non-empty object of zeros. The user then sets a price/markup
+(saving only `unitPrice`, leaving the stale zeros in place). On recalc, the
+non-empty branch reprices from those stale zeros → back to cost. From the user's
+seat this reads as "the 0% default overwrote my markup."
+
+### Concrete example (the reported case)
+
+1. Company default markups are all 0%.
+2. A quote line is priced; the user sets the **Markup Percent** cell to 10%
+ (cost $100 → price $110). Only `unitPrice = 110` is saved.
+3. The user changes a material's unit cost on the BOM.
+4. `recalculateQuoteLinePrices` runs, sees empty (or stale-zero) `categoryMarkups`,
+ applies the 0% default, and rewrites `unitPrice = 100`.
+5. The quoted price silently dropped to cost; margin is gone.
+
+## Proposed Solution
+
+Treat a quote line price as one of three states, distinguished by the **price**
+(the user's stated signal — no new column):
+
+| State | Signal | Behavior on BOM cost change |
+|-------|--------|------------------------------|
+| **Cost-plus** | `categoryMarkups` non-empty | Reprice = Σ cost × (1 + markup). Keeps the markup, updates the price. *(unchanged — the intended feature)* |
+| **Fixed price** | `categoryMarkups` empty **and** `unitPrice > 0` | **Preserve `unitPrice` exactly. Never apply the default.** *(the fix — Q1: preserve price)* |
+| **Unpriced** | `unitPrice` is null or `0` | Apply the default markup **if enabled**; otherwise price at cost (empty `categoryMarkups`). |
+
+Plus two supporting rules:
+
+1. **Default markups are "disabled" when every category value is `0` (or the
+ object is empty).** When disabled, defaults are never applied and never
+ seeded — anywhere. *(Q2)*
+2. **A direct price or virtual-markup edit clears the row's stored
+ `categoryMarkups`.** This turns the row into a *fixed price* so the user's
+ explicit value always wins on the next recalc — closing the non-zero-default
+ stale-markup hole. *(Q3: option A)* The per-category markup editor
+ (`onUpdateCategoryMarkup`) still writes `categoryMarkups` and keeps the row
+ *cost-plus*.
+
+Net effect: **an explicitly set price is authoritative** — the only thing that
+reprices a row on a cost change is an explicit per-category markup the user chose.
+
+### "Disabled" helper
+
+A single predicate governs both service functions:
+
+```ts
+// true when at least one category default is a positive markup
+const defaultsEnabled = Object.values(defaultMarkups).some((v) => v > 0);
+const effectiveDefaults = defaultsEnabled ? defaultMarkups : {};
+```
+
+`defaultMarkups` is the ×100 (whole-percent) form already built in both
+functions from `companySettings.quoteLineCategoryMarkups`.
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| Preserve **price** or **markup %** for a fixed-price row on cost change | Preserve the **price** | Q1. Matches "if a price is set we shouldn't set a new price." A silent customer-facing price change is the harm we're removing; the displayed markup % is virtual and may drift as cost moves — acceptable. |
+| Detect "a price is set" | `unitPrice > 0` (no new column) | Q4 (folded in). User's steer: "since markup is virtual, we can probably look at the price." A genuine $0 line is not treated as set — acceptable edge (a $0 line is already a "please price me" state). |
+| Detect "cost-plus" vs "fixed" | `categoryMarkups` non-empty ⇒ cost-plus | Reuses the existing signal; per-category markups are the only explicit cost-plus intent in the model. |
+| When is the default "disabled" | Every category default `0` (or empty `{}`) | Q2. Company default is `{}` today, so the feature is off until configured; all-zeros is the user turning it off. |
+| Effect of a direct price / virtual-markup edit | Clear `categoryMarkups` on that row | Q3-A. Makes "explicit price wins" universal, including non-zero-default MtO lines where stale seeded markups otherwise revert the override. |
+| Schema change | None | Q4. Heuristic on `unitPrice` + `categoryMarkups` is sufficient; no migration, no Ask-First schema touch. |
+| Backward compatibility (heuristic 7) | No FROZEN/STABLE surface touched | Behavior-only change inside two service functions and two UI edit handlers; `quoteLinePrice` shape unchanged, `upsertQuoteLinePrices` preservation semantics unchanged. |
+
+## Data Model Changes
+
+**None.** No tables, columns, or migrations. The fix relies entirely on the
+existing `quoteLinePrice.unitPrice` and `quoteLinePrice.categoryMarkups`
+columns and `companySettings.quoteLineCategoryMarkups`.
+
+Cost categories in scope (keys of `categoryMarkups` / the settings validator,
+`settings.models.ts:334-343`): `materialCost`, `partCost`, `toolCost`,
+`consumableCost`, `laborCost`, `machineCost`, `overheadCost`, `outsideCost`.
+
+## API / Service Changes
+
+All changes are in `apps/erp/app/modules/sales/sales.service.ts`.
+
+### 1. `recalculateQuoteLinePrices` (`:4423-4551`) — the core fix
+
+Replace the per-row markup resolution + unconditional reprice. New per-row logic:
+
+- Compute `effectiveDefaults` (empty when disabled).
+- `const rowMarkups = row.categoryMarkups ?? {}`.
+- **If `rowMarkups` is non-empty (cost-plus):** reprice exactly as today —
+ `rollupPrice = Σ cost × (1 + rowMarkups[cat]/100)`, then `resolvePrice(...)`,
+ write `unitPrice` and keep `categoryMarkups: rowMarkups`.
+- **Else if `row.unitPrice > 0` (fixed price):** preserve the row unchanged —
+ re-insert with the same `unitPrice` and empty `categoryMarkups`. Do **not**
+ call `resolvePrice`, do **not** apply defaults.
+- **Else (unpriced):** if `effectiveDefaults` is non-empty, reprice using it and
+ seed `categoryMarkups: effectiveDefaults`; otherwise price at cost rollup
+ (markup 0) with empty `categoryMarkups`.
+
+`discountPercent`, `leadTime`, `exchangeRate`, and the delete-then-reinsert
+mechanics stay as-is (the function still preserves those fields).
+
+### 2. `calculatePricesForQuantities` (`:4182-4288`) — don't seed a disabled default
+
+- Build `defaultMarkups` as today, then apply the `defaultsEnabled` gate.
+- `rollupPrice` uses `effectiveDefaults` (so a disabled default prices at cost).
+- Seed `categoryMarkups: effectiveDefaults` — i.e. `{}` when disabled, so the row
+ is created as *fixed/unpriced* rather than a stale-zeros *cost-plus* row.
+
+### 3. No change to siblings
+
+`resolveQuoteLinePrices` (Pull) and `resolvePurchaseToOrderPrices` (P2O) already
+insert empty `categoryMarkups`; under the new recalc rules their prices are
+preserved (fixed price) rather than clobbered — no edit needed.
+`upsertQuoteLinePrices` (`:3830-3911`) already preserves existing
+`categoryMarkups` and is unchanged.
+
+## UI Changes
+
+All in `apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx`.
+
+### 1. Direct price + virtual-markup edits clear `categoryMarkups` (Q3-A)
+
+`onUpdatePrice` (`:481`) is used by both the price cell and the virtual **Markup
+Percent** cell (`:825-830`). When it updates `unitPrice`, it must also clear the
+row's `categoryMarkups` (set to `{}`) in both the optimistic `editableFields`
+state and the `quoteLinePrice` update, so the row becomes *fixed price* and the
+next recalc preserves it. (Non-`unitPrice` keys — `leadTime`, `discountPercent`,
+`shippingCost` — must **not** clear markups.)
+
+`onUpdateCategoryMarkup` (`:430`) is unchanged: it writes `categoryMarkups` +
+`unitPrice`, keeping the row *cost-plus*.
+
+### 2. No display change required
+
+Investigated and rejected: the per-category markup cells already render
+`categoryMarkupsByQuantity[quantity]?.[category] ?? 0` (`:877`), so an all-zero
+(disabled) default shows `0%` regardless — the fallback is already visually inert
+for the disabled case. The virtual **Markup Percent** row (`:793-838`) reads the
+real price and is always accurate. The one pre-existing quirk (an *enabled*
+non-zero default shows in the per-category cells of a fixed-price row) is
+unchanged by this fix and out of scope. No settings-UI change either:
+`CategoryMarkupsCard` (`routes/x+/settings+/sales.tsx`) already lets the user set
+all categories to 0, which now means "disabled."
+
+## Acceptance Criteria
+
+- [ ] With default markups all 0%: on a Draft quote, a user sets a line's Markup
+ Percent to 10% (cost $100 → $110), then edits a BOM material's unit cost.
+ The quantity break still shows **$110** (not $100); the markup reads ~10%
+ minus any drift from the cost change, never 0%.
+- [ ] With a **non-zero** default (e.g. 30%): a Make-to-Order line is created
+ (seeded at 30%), the user overrides the price to $150, then changes a BOM
+ cost. The line stays at **$150** — the stale 30% does not revert it.
+- [ ] A line with an explicit **per-category** markup (set via the category
+ markup editor) still reprices when a BOM cost changes — markup held, price
+ updated. *(cost-plus behavior preserved)*
+- [ ] With defaults all 0%: a new Make-to-Order line is created priced **at cost**
+ with empty `categoryMarkups` (no `{…:0}` seed).
+- [ ] With a non-zero default: a **new, never-priced** line still auto-prices from
+ the default on creation/recalc (feature intact when enabled).
+- [ ] Pull-from-inventory and purchase-to-order lines keep their resolved prices
+ across a BOM cost change (not recomputed to cost-plus).
+- [ ] `discountPercent`, `leadTime`, and `exchangeRate` survive every recalc for
+ all three row states.
+- [ ] `pnpm --filter @carbon/erp typecheck` passes.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| A never-touched, disabled-default line priced at cost is preserved on later cost changes and goes stale (price < new cost) | Low | Accepted per Q1 — with defaults off the user prices manually anyway; cost vs price is visible in the pricing grid. A $0-margin line is already a "set a price" prompt. |
+| `unitPrice > 0` misclassifies a legitimately free ($0) line as unpriced and reprices it | Low | Edge case; current code already reprices $0 lines. Documented in Design Decisions. |
+| Clearing `categoryMarkups` on a price edit discards a user's earlier per-category markup breakdown | Low | Intentional (Q3-A): a direct price edit is an explicit override of the whole line; the per-category editor remains the way to stay cost-plus. |
+| Other callers apply/seed defaults and are missed | Med | Implementation greps `quoteLineCategoryMarkups`, `defaultMarkups`, and `categoryMarkups` across `sales.service.ts` and routes to confirm only the three sites above consume defaults. |
+| Existing rows already carrying stale `{…:0}` markups (from before this fix) still revert on recalc | Low | These are cost-plus-at-0 = price-at-cost; a single price/virtual-markup edit now clears them permanently. No data migration required; note in PR. |
+
+## Open Questions
+
+> Resolved with the user before this spec was written (spec-writing Step 5).
+
+- [x] **For a fixed-price row (empty `categoryMarkups`), preserve the price or the
+ markup % when BOM cost changes?** — **Answer:** Preserve the **price** (Q1).
+ "If a price is set we shouldn't set a new price"; the virtual markup may
+ drift and that is acceptable.
+- [x] **What counts as "the default markup feature is disabled"?** — **Answer:**
+ Every category default is `0` (or the setting is empty `{}`) (Q2). When
+ disabled, defaults are never applied or seeded.
+- [x] **Also fix the non-zero-default variant, where a Make-to-Order line's
+ seeded `categoryMarkups` reverts a later direct price/markup override?** —
+ **Answer:** Yes — a direct price/markup edit clears the row's
+ `categoryMarkups` so the explicit value wins (Q3, option A).
+- [x] **Detect "a price is set" via `unitPrice > 0`, or add an override flag
+ column?** — **Answer:** Use the `unitPrice > 0` heuristic, no new schema —
+ per the user's "look at the price" steer (folded into Q1).
+
+## Changelog
+
+- 2026-07-14: Created. Open questions Q1/Q2/Q3 resolved with the user before
+ writing (Q1 = preserve price, Q2 = confirmed all-zero/empty ⇒ disabled,
+ Q3 = A = clear `categoryMarkups` on direct price/markup edits).
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index ad789a744b..5fbd9123aa 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -56,6 +56,7 @@ import type {
selectedLinesValidator
} from "./sales.models";
import { costCategoryKeys } from "./sales.models";
+import { decideRecalcPricing, getEffectiveDefaultMarkups } from "./sales.utils";
import type {
MatchedRule,
OverrideEntry,
@@ -3839,6 +3840,7 @@ export async function upsertQuoteLinePrices(
quantity: number;
createdBy: string;
categoryMarkups?: Record<string, number>;
+ priceSource?: "system" | "manual";
}[]
) {
const existingPrices = await client
@@ -3876,6 +3878,7 @@ export async function upsertQuoteLinePrices(
discountPercent: number;
leadTime: number;
categoryMarkups: unknown;
+ priceSource: string;
}
>
>((acc, price) => {
@@ -3897,6 +3900,9 @@ export async function upsertQuoteLinePrices(
discountPercent: existing?.discountPercent ?? p.discountPercent,
leadTime: existing?.leadTime ?? p.leadTime,
categoryMarkups: p.categoryMarkups ?? existing?.categoryMarkups ?? {},
+ // Explicit caller intent wins; otherwise keep the row's provenance so a
+ // delete+reinsert can never turn a manual price back into a system one.
+ priceSource: p.priceSource ?? existing?.priceSource ?? "system",
quoteId: quoteId,
exchangeRate: quoteExchangeRate.data?.exchangeRate ?? 1
};
@@ -4228,6 +4234,7 @@ export async function calculatePricesForQuantities(
for (const [key, value] of Object.entries(rawMarkups)) {
defaultMarkups[key] = value * 100;
}
+ const effectiveDefaults = getEffectiveDefaultMarkups(defaultMarkups);
// 2. Build cost effects
const result = await buildCostEffects(client, quoteLineId);
@@ -4247,7 +4254,7 @@ export async function calculatePricesForQuantities(
const rollupPrice = costCategoryKeys.reduce((sum, key) => {
const cost = categoryCosts[key] ?? 0;
- const markup = defaultMarkups[key] ?? 0;
+ const markup = effectiveDefaults[key] ?? 0;
return sum + cost * (1 + markup / 100);
}, 0);
@@ -4268,7 +4275,8 @@ export async function calculatePricesForQuantities(
companyId,
quantity: qty,
unitPrice: Number(finalPrice.toFixed(precision)),
- categoryMarkups: defaultMarkups,
+ categoryMarkups: effectiveDefaults,
+ priceSource: "system",
exchangeRate,
createdBy: userId,
leadTime: 0,
@@ -4479,12 +4487,32 @@ export async function recalculateQuoteLinePrices(
const { effects } = result;
- const updatedRows = [];
+ const effectiveDefaults = getEffectiveDefaultMarkups(defaultMarkups);
+
+ const repricedRows: {
+ quantity: number;
+ unitPrice: number;
+ categoryMarkups: Record<string, number>;
+ }[] = [];
for (const row of existingPrices.data) {
const qty = row.quantity;
- const rowMarkups = (row.categoryMarkups as Record<string, number>) ?? {};
- const markups =
- Object.keys(rowMarkups).length > 0 ? rowMarkups : defaultMarkups;
+
+ const decision = decideRecalcPricing(
+ {
+ priceSource: row.priceSource,
+ categoryMarkups: row.categoryMarkups as Record<string, number> | null
+ },
+ effectiveDefaults
+ );
+
+ // Manual price: a person or an external system stated this price.
+ // Leave the row untouched — never re-derive it from costs or defaults
+ // (the core fix).
+ if (decision.mode === "preserve") {
+ continue;
+ }
+
+ const markups = decision.markups;
const categoryCosts: Record<string, number> = {};
for (const key of costCategoryKeys) {
@@ -4510,42 +4538,35 @@ export async function recalculateQuoteLinePrices(
).finalPrice
: rollupPrice;
- updatedRows.push({
- quoteId: row.quoteId,
- quoteLineId: row.quoteLineId,
- companyId: row.companyId,
- quantity: row.quantity,
+ repricedRows.push({
+ quantity: qty,
unitPrice: Number(finalPrice.toFixed(precision)),
- categoryMarkups: markups,
- exchangeRate: row.exchangeRate,
- createdBy: row.createdBy,
- updatedBy: userId,
- leadTime: row.leadTime,
- discountPercent: row.discountPercent
- });
- }
-
- // 5. Delete existing and re-insert with updated prices
- const deleteResult = await client
- .from("quoteLinePrice")
- .delete()
- .eq("quoteLineId", quoteLineId);
-
- if (deleteResult.error) {
- logger.error("Failed to delete quote line prices during recalc", {
- quoteLineId,
- error: deleteResult.error
+ categoryMarkups: markups
});
- return { error: deleteResult.error };
}
- const insertResult = await client.from("quoteLinePrice").insert(updatedRows);
- if (insertResult.error) {
- logger.error("Failed to insert quote line prices during recalc", {
- quoteLineId,
- error: insertResult.error
- });
- return { error: insertResult.error };
+ // 5. Update only the repriced rows in place. Preserved (manual) rows are
+ // not written at all, so no column can be lost or clobbered.
+ for (const row of repricedRows) {
+ const updateResult = await client
+ .from("quoteLinePrice")
+ .update({
+ unitPrice: row.unitPrice,
+ categoryMarkups: row.categoryMarkups,
+ priceSource: "system",
+ updatedBy: userId
+ })
+ .eq("quoteLineId", quoteLineId)
+ .eq("quantity", row.quantity);
+
+ if (updateResult.error) {
+ logger.error("Failed to update quote line price during recalc", {
+ quoteLineId,
+ quantity: row.quantity,
+ error: updateResult.error
+ });
+ return { error: updateResult.error };
+ }
}
return { error: null };
}
diff --git a/apps/erp/app/modules/sales/sales.utils.test.ts b/apps/erp/app/modules/sales/sales.utils.test.ts
new file mode 100644
index 0000000000..5a3ae1864d
--- /dev/null
+++ b/apps/erp/app/modules/sales/sales.utils.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from "vitest";
+import { decideRecalcPricing, getEffectiveDefaultMarkups } from "./sales.utils";
+
+describe("getEffectiveDefaultMarkups", () => {
+ it("returns {} when all category defaults are 0 (feature disabled)", () => {
+ expect(
+ getEffectiveDefaultMarkups({ laborCost: 0, materialCost: 0 })
+ ).toEqual({});
+ });
+ it("returns {} when the defaults object is empty", () => {
+ expect(getEffectiveDefaultMarkups({})).toEqual({});
+ });
+ it("returns the defaults unchanged when at least one is positive", () => {
+ const d = { laborCost: 30, materialCost: 0 };
+ expect(getEffectiveDefaultMarkups(d)).toEqual(d);
+ });
+});
+
+describe("decideRecalcPricing", () => {
+ it("PRESERVES a manual row — no recalc may change a stated price", () => {
+ expect(
+ decideRecalcPricing(
+ { priceSource: "manual", categoryMarkups: {} },
+ { laborCost: 30 }
+ )
+ ).toEqual({ mode: "preserve" });
+ });
+ it("preserves a manual row even when it has stale categoryMarkups", () => {
+ expect(
+ decideRecalcPricing(
+ { priceSource: "manual", categoryMarkups: { laborCost: 20 } },
+ { laborCost: 30 }
+ )
+ ).toEqual({ mode: "preserve" });
+ });
+ it("preserves a manual row when defaults are disabled (the reported case)", () => {
+ expect(
+ decideRecalcPricing({ priceSource: "manual", categoryMarkups: {} }, {})
+ ).toEqual({ mode: "preserve" });
+ });
+ it("reprices a system cost-plus row from its explicit categoryMarkups", () => {
+ expect(
+ decideRecalcPricing(
+ { priceSource: "system", categoryMarkups: { laborCost: 20 } },
+ { laborCost: 30 }
+ )
+ ).toEqual({ mode: "reprice", markups: { laborCost: 20 } });
+ });
+ it("reprices a system row without markups from the effective defaults", () => {
+ expect(
+ decideRecalcPricing(
+ { priceSource: "system", categoryMarkups: {} },
+ { laborCost: 30 }
+ )
+ ).toEqual({ mode: "reprice", markups: { laborCost: 30 } });
+ });
+ it("reprices a system row at cost (empty markups) when defaults are disabled — no freeze", () => {
+ expect(
+ decideRecalcPricing({ priceSource: "system", categoryMarkups: {} }, {})
+ ).toEqual({ mode: "reprice", markups: {} });
+ });
+ it("treats null categoryMarkups as empty", () => {
+ expect(
+ decideRecalcPricing({ priceSource: "system", categoryMarkups: null }, {})
+ ).toEqual({ mode: "reprice", markups: {} });
+ });
+ it("treats a null priceSource as system (legacy safety)", () => {
+ expect(
+ decideRecalcPricing(
+ { priceSource: null, categoryMarkups: { laborCost: 20 } },
+ {}
+ )
+ ).toEqual({ mode: "reprice", markups: { laborCost: 20 } });
+ });
+});
diff --git a/apps/erp/app/modules/sales/sales.utils.ts b/apps/erp/app/modules/sales/sales.utils.ts
new file mode 100644
index 0000000000..6ef950ae5b
--- /dev/null
+++ b/apps/erp/app/modules/sales/sales.utils.ts
@@ -0,0 +1,54 @@
+export type CategoryMarkups = Record<string, number>;
+
+export type QuoteLinePriceSource = "system" | "manual";
+
+/**
+ * Company default markups are "enabled" only when at least one cost category
+ * has a positive markup. An all-zero or empty default means the feature is
+ * off, so it is treated as "no defaults" everywhere it is consumed.
+ * (Markups are whole-percent, non-negative — e.g. `{ laborCost: 25 }`.)
+ *
+ * Mirrored in the Deno edge runtime (`functions/lib/methods.ts`), which cannot
+ * import app code — keep both in sync.
+ */
+export function getEffectiveDefaultMarkups(
+ defaultMarkups: CategoryMarkups
+): CategoryMarkups {
+ const enabled = Object.values(defaultMarkups).some((v) => v > 0);
+ return enabled ? defaultMarkups : {};
+}
+
+export type RecalcPricingDecision =
+ | { mode: "reprice"; markups: CategoryMarkups }
+ | { mode: "preserve" };
+
+/**
+ * Decide how a recalculation should treat one existing price row when a BOM
+ * cost changes, based on the row's explicit provenance
+ * (`quoteLinePrice.priceSource`):
+ * - `'manual'` (user-typed price, Paperless import) → preserve; no recalc
+ * may change the price
+ * - `'system'` with explicit `categoryMarkups` → cost-plus; reprice from
+ * those markups
+ * - `'system'` without markups → reprice from the effective defaults (which
+ * is `{}` — i.e. price at cost — when defaults are disabled)
+ *
+ * Mirrored in the Deno edge runtime (`functions/lib/methods.ts`) — keep both
+ * in sync.
+ */
+export function decideRecalcPricing(
+ row: {
+ priceSource: string | null;
+ categoryMarkups: CategoryMarkups | null;
+ },
+ effectiveDefaults: CategoryMarkups
+): RecalcPricingDecision {
+ if (row.priceSource === "manual") {
+ return { mode: "preserve" };
+ }
+ const rowMarkups = row.categoryMarkups ?? {};
+ if (Object.keys(rowMarkups).length > 0) {
+ return { mode: "reprice", markups: rowMarkups };
+ }
+ return { mode: "reprice", markups: effectiveDefaults };
+}
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx
index f4c6c82a52..8a8bc56441 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx
@@ -446,15 +446,20 @@ const QuoteLinePricing = ({
[quantity]: {
...prev.prices[quantity],
categoryMarkups: newMarkups,
+ priceSource: "system",
unitPrice
}
}
}));
+ // Editing a per-category markup is explicit cost-plus intent: the row
+ // goes back to system pricing so BOM changes reprice it from these
+ // markups.
const priceUpdate = await carbon
?.from("quoteLinePrice")
.update({
categoryMarkups: newMarkups,
+ priceSource: "system",
unitPrice
})
.eq("quoteLineId", lineId)
@@ -507,7 +512,16 @@ const QuoteLinePricing = ({
// Round the value to the precision of the quote line
roundedValue = Number(value.toFixed(unitPricePrecision));
}
- newPrices[quantity] = { ...newPrices[quantity], [key]: roundedValue };
+ newPrices[quantity] = {
+ ...newPrices[quantity],
+ [key]: roundedValue,
+ // A direct price / virtual-markup edit makes this a manual price:
+ // priceSource 'manual' tells every recalc to preserve it, and clearing
+ // the stored per-category markups keeps the display consistent.
+ ...(key === "unitPrice"
+ ? { categoryMarkups: {}, priceSource: "manual" }
+ : {})
+ };
setEditableFields((prev) => ({
...prev,
@@ -519,6 +533,9 @@ const QuoteLinePricing = ({
?.from("quoteLinePrice")
.update({
[key]: roundedValue,
+ ...(key === "unitPrice"
+ ? { categoryMarkups: {}, priceSource: "manual" }
+ : {}),
quoteLineId: lineId,
quantity
})
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index c48a40ca58..a43ba9a135 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,5 +1,5 @@
{
- "generated": "2026-07-15T00:11:05.860Z",
+ "generated": "2026-07-15T04:00:40.500Z",
"totalTools": 1331,
"modules": 15,
"tools": [
@@ -35452,7 +35452,14 @@
"quantity": {
"type": "number"
},
- "categoryMarkups": {}
+ "categoryMarkups": {},
+ "priceSource": {
+ "type": "string",
+ "enum": [
+ "system",
+ "manual"
+ ]
+ }
},
"required": [
"quoteLineId",
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.recalculate-price.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.recalculate-price.tsx
index bc49dfd91a..7b8ee04815 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.recalculate-price.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.recalculate-price.tsx
@@ -76,7 +76,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
discountPercent: 0,
leadTime: 0,
createdBy: userId,
- categoryMarkups: categoryMarkupsByQuantity.data[quantity] ?? undefined
+ categoryMarkups: categoryMarkupsByQuantity.data[quantity] ?? undefined,
+ // Applying a markup is explicit cost-plus intent: the row goes back to
+ // system pricing so future BOM changes reprice it from these markups.
+ priceSource: "system" as const
};
});
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 528a617910..e5a5fc722a 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -4928,6 +4928,7 @@ export type Database = {
accountsReceivableEmail: string | null
assetTaxDepreciationEnabled: boolean
assetTaxRate: number | null
+ autoStartOperationTimer: boolean
consoleEnabled: boolean
defaultCustomerCc: string[] | null
defaultSupplierCc: string[] | null
@@ -4971,6 +4972,7 @@ export type Database = {
accountsReceivableEmail?: string | null
assetTaxDepreciationEnabled?: boolean
assetTaxRate?: number | null
+ autoStartOperationTimer?: boolean
consoleEnabled?: boolean
defaultCustomerCc?: string[] | null
defaultSupplierCc?: string[] | null
@@ -5014,6 +5016,7 @@ export type Database = {
accountsReceivableEmail?: string | null
assetTaxDepreciationEnabled?: boolean
assetTaxRate?: number | null
+ autoStartOperationTimer?: boolean
consoleEnabled?: boolean
defaultCustomerCc?: string[] | null
defaultSupplierCc?: string[] | null
@@ -19751,6 +19754,50 @@ export type Database = {
},
]
}
+ jobMaterialStep: {
+ Row: {
+ jobMaterialId: string
+ jobOperationStepId: string
+ }
+ Insert: {
+ jobMaterialId: string
+ jobOperationStepId: string
+ }
+ Update: {
+ jobMaterialId?: string
+ jobOperationStepId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "jobMaterialStep_jobMaterialId_fkey"
+ columns: ["jobMaterialId"]
+ isOneToOne: false
+ referencedRelation: "jobMaterial"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterialStep_jobMaterialId_fkey"
+ columns: ["jobMaterialId"]
+ isOneToOne: false
+ referencedRelation: "jobMaterialWithMakeMethodId"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterialStep_jobMaterialId_fkey"
+ columns: ["jobMaterialId"]
+ isOneToOne: false
+ referencedRelation: "openJobMaterialLines"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterialStep_jobOperationStepId_fkey"
+ columns: ["jobOperationStepId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationStep"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
jobOperation: {
Row: {
assemblyInstructionId: string | null
@@ -19773,6 +19820,7 @@ export type Database = {
machineTime: number
machineUnit: Database["public"]["Enums"]["factor"]
manuallyScheduled: boolean
+ operationKind: Database["public"]["Enums"]["operationKind"]
operationLeadTime: number
operationMinimumCost: number
operationOrder: Database["public"]["Enums"]["methodOperationOrder"]
@@ -19821,6 +19869,7 @@ export type Database = {
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
manuallyScheduled?: boolean
+ operationKind?: Database["public"]["Enums"]["operationKind"]
operationLeadTime?: number
operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
@@ -19869,6 +19918,7 @@ export type Database = {
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
manuallyScheduled?: boolean
+ operationKind?: Database["public"]["Enums"]["operationKind"]
operationLeadTime?: number
operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
@@ -20888,6 +20938,157 @@ export type Database = {
},
]
}
+ jobOperationStepSlide: {
+ Row: {
+ annotations: Json
+ caption: string | null
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ imagePath: string
+ size: string
+ sortOrder: number
+ stepId: string
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ annotations?: Json
+ caption?: string | null
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ imagePath: string
+ size?: string
+ sortOrder?: number
+ stepId: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ annotations?: Json
+ caption?: string | null
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ imagePath?: string
+ size?: string
+ sortOrder?: number
+ stepId?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "jobOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_stepId_fkey"
+ columns: ["stepId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
jobOperationTool: {
Row: {
companyId: string
@@ -21086,6 +21287,36 @@ export type Database = {
},
]
}
+ jobOperationToolStep: {
+ Row: {
+ jobOperationStepId: string
+ jobOperationToolId: string
+ }
+ Insert: {
+ jobOperationStepId: string
+ jobOperationToolId: string
+ }
+ Update: {
+ jobOperationStepId?: string
+ jobOperationToolId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "jobOperationToolStep_jobOperationStepId_fkey"
+ columns: ["jobOperationStepId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationToolStep_jobOperationToolId_fkey"
+ columns: ["jobOperationToolId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationTool"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
journal: {
Row: {
accountingPeriodId: string | null
@@ -25436,6 +25667,36 @@ export type Database = {
},
]
}
+ methodMaterialStep: {
+ Row: {
+ methodMaterialId: string
+ methodOperationStepId: string
+ }
+ Insert: {
+ methodMaterialId: string
+ methodOperationStepId: string
+ }
+ Update: {
+ methodMaterialId?: string
+ methodOperationStepId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "methodMaterialStep_methodMaterialId_fkey"
+ columns: ["methodMaterialId"]
+ isOneToOne: false
+ referencedRelation: "methodMaterial"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodMaterialStep_methodOperationStepId_fkey"
+ columns: ["methodOperationStepId"]
+ isOneToOne: false
+ referencedRelation: "methodOperationStep"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
methodOperation: {
Row: {
assemblyInstructionId: string | null
@@ -25450,6 +25711,7 @@ export type Database = {
machineTime: number
machineUnit: Database["public"]["Enums"]["factor"]
makeMethodId: string
+ operationKind: Database["public"]["Enums"]["operationKind"]
operationLeadTime: number | null
operationMinimumCost: number | null
operationOrder: Database["public"]["Enums"]["methodOperationOrder"]
@@ -25480,6 +25742,7 @@ export type Database = {
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
makeMethodId: string
+ operationKind?: Database["public"]["Enums"]["operationKind"]
operationLeadTime?: number | null
operationMinimumCost?: number | null
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
@@ -25510,6 +25773,7 @@ export type Database = {
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
makeMethodId?: string
+ operationKind?: Database["public"]["Enums"]["operationKind"]
operationLeadTime?: number | null
operationMinimumCost?: number | null
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
@@ -25985,6 +26249,157 @@ export type Database = {
},
]
}
+ methodOperationStepSlide: {
+ Row: {
+ annotations: Json
+ caption: string | null
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ imagePath: string
+ size: string
+ sortOrder: number
+ stepId: string
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ annotations?: Json
+ caption?: string | null
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ imagePath: string
+ size?: string
+ sortOrder?: number
+ stepId: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ annotations?: Json
+ caption?: string | null
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ imagePath?: string
+ size?: string
+ sortOrder?: number
+ stepId?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "methodOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_stepId_fkey"
+ columns: ["stepId"]
+ isOneToOne: false
+ referencedRelation: "methodOperationStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
methodOperationTool: {
Row: {
companyId: string
@@ -26169,6 +26584,36 @@ export type Database = {
},
]
}
+ methodOperationToolStep: {
+ Row: {
+ methodOperationStepId: string
+ methodOperationToolId: string
+ }
+ Insert: {
+ methodOperationStepId: string
+ methodOperationToolId: string
+ }
+ Update: {
+ methodOperationStepId?: string
+ methodOperationToolId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "methodOperationToolStep_methodOperationStepId_fkey"
+ columns: ["methodOperationStepId"]
+ isOneToOne: false
+ referencedRelation: "methodOperationStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationToolStep_methodOperationToolId_fkey"
+ columns: ["methodOperationToolId"]
+ isOneToOne: false
+ referencedRelation: "methodOperationTool"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
modelUpload: {
Row: {
autodeskUrn: string | null
@@ -38517,6 +38962,7 @@ export type Database = {
leadTime: number
netExtendedPrice: number | null
netUnitPrice: number | null
+ priceSource: string
quantity: number
quoteId: string
quoteLineId: string
@@ -38539,6 +38985,7 @@ export type Database = {
leadTime?: number
netExtendedPrice?: number | null
netUnitPrice?: number | null
+ priceSource?: string
quantity?: number
quoteId: string
quoteLineId: string
@@ -38561,6 +39008,7 @@ export type Database = {
leadTime?: number
netExtendedPrice?: number | null
netUnitPrice?: number | null
+ priceSource?: string
quantity?: number
quoteId?: string
quoteLineId?: string
@@ -39238,6 +39686,43 @@ export type Database = {
},
]
}
+ quoteMaterialStep: {
+ Row: {
+ quoteMaterialId: string
+ quoteOperationStepId: string
+ }
+ Insert: {
+ quoteMaterialId: string
+ quoteOperationStepId: string
+ }
+ Update: {
+ quoteMaterialId?: string
+ quoteOperationStepId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "quoteMaterialStep_quoteMaterialId_fkey"
+ columns: ["quoteMaterialId"]
+ isOneToOne: false
+ referencedRelation: "quoteMaterial"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteMaterialStep_quoteMaterialId_fkey"
+ columns: ["quoteMaterialId"]
+ isOneToOne: false
+ referencedRelation: "quoteMaterialWithMakeMethodId"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteMaterialStep_quoteOperationStepId_fkey"
+ columns: ["quoteOperationStepId"]
+ isOneToOne: false
+ referencedRelation: "quoteOperationStep"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
quoteOperation: {
Row: {
companyId: string
@@ -39252,6 +39737,7 @@ export type Database = {
machineRate: number | null
machineTime: number
machineUnit: Database["public"]["Enums"]["factor"]
+ operationKind: Database["public"]["Enums"]["operationKind"]
operationLeadTime: number
operationMinimumCost: number
operationOrder: Database["public"]["Enums"]["methodOperationOrder"]
@@ -39286,6 +39772,7 @@ export type Database = {
machineRate?: number | null
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
+ operationKind?: Database["public"]["Enums"]["operationKind"]
operationLeadTime?: number
operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
@@ -39320,6 +39807,7 @@ export type Database = {
machineRate?: number | null
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
+ operationKind?: Database["public"]["Enums"]["operationKind"]
operationLeadTime?: number
operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
@@ -39834,6 +40322,157 @@ export type Database = {
},
]
}
+ quoteOperationStepSlide: {
+ Row: {
+ annotations: Json
+ caption: string | null
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ imagePath: string
+ size: string
+ sortOrder: number
+ stepId: string
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ annotations?: Json
+ caption?: string | null
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ imagePath: string
+ size?: string
+ sortOrder?: number
+ stepId: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ annotations?: Json
+ caption?: string | null
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ imagePath?: string
+ size?: string
+ sortOrder?: number
+ stepId?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "quoteOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_stepId_fkey"
+ columns: ["stepId"]
+ isOneToOne: false
+ referencedRelation: "quoteOperationStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
quoteOperationTool: {
Row: {
companyId: string
@@ -40025,6 +40664,36 @@ export type Database = {
},
]
}
+ quoteOperationToolStep: {
+ Row: {
+ quoteOperationStepId: string
+ quoteOperationToolId: string
+ }
+ Insert: {
+ quoteOperationStepId: string
+ quoteOperationToolId: string
+ }
+ Update: {
+ quoteOperationStepId?: string
+ quoteOperationToolId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "quoteOperationToolStep_quoteOperationStepId_fkey"
+ columns: ["quoteOperationStepId"]
+ isOneToOne: false
+ referencedRelation: "quoteOperationStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationToolStep_quoteOperationToolId_fkey"
+ columns: ["quoteOperationToolId"]
+ isOneToOne: false
+ referencedRelation: "quoteOperationTool"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
quotePayment: {
Row: {
companyId: string
@@ -62452,14 +63121,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -66398,14 +67067,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -70540,6 +71209,7 @@ export type Database = {
machineTime: number
machineUnit: Database["public"]["Enums"]["factor"]
operationDueDate: string
+ operationKind: Database["public"]["Enums"]["operationKind"]
operationOrder: number
operationOrderType: Database["public"]["Enums"]["methodOperationOrder"]
operationQuantity: number
@@ -70811,6 +71481,7 @@ export type Database = {
makeMethodId: string
materialMakeMethodId: string
methodMaterialId: string
+ methodOperationStepIds: Json
methodType: Database["public"]["Enums"]["methodType"]
operationId: string
order: number
@@ -72496,6 +73167,7 @@ export type Database = {
| "Completed"
| "Skipped"
oeeImpact: "Down" | "Planned" | "Impact" | "No Impact"
+ operationKind: "Operation" | "Assembly" | "Inspection"
operationType: "Inside" | "Outside"
payableLineType:
| "Comment"
@@ -73863,6 +74535,7 @@ export const Constants = {
"Skipped",
],
oeeImpact: ["Down", "Planned", "Impact", "No Impact"],
+ operationKind: ["Operation", "Assembly", "Inspection"],
operationType: ["Inside", "Outside"],
payableLineType: [
"Comment",
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index f541c075c5..d659a8a825 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -5166,12 +5166,17 @@ serve(async (req: Request) => {
sourceQuotePricingForLine.map((l) => ({
quoteId: newQuoteId!,
quoteLineId: newLine.id!,
+ companyId,
leadTime: l.leadTime ?? 0,
discountPercent: l.discountPercent ?? 0,
quantity: l.quantity ?? 0,
unitPrice: l.unitPrice ?? 0,
shippingCost: l.shippingCost ?? 0,
exchangeRate: l.exchangeRate ?? 0,
+ categoryMarkups: JSON.stringify(l.categoryMarkups ?? {}),
+ // Copied prices keep their provenance so a manual price
+ // stays protected on the new quote/revision.
+ priceSource: l.priceSource ?? "system",
createdBy: userId,
}))
)
diff --git a/packages/database/supabase/functions/lib/methods.ts b/packages/database/supabase/functions/lib/methods.ts
index 719262525e..2f11d9b372 100644
--- a/packages/database/supabase/functions/lib/methods.ts
+++ b/packages/database/supabase/functions/lib/methods.ts
@@ -494,6 +494,35 @@ export async function calculateQuoteLinePrices(
defaultMarkups[key] = value * 100;
}
+ // Defaults are "enabled" only when at least one category markup is positive;
+ // an all-zero/empty default means the feature is off. Mirrors
+ // getEffectiveDefaultMarkups in apps/erp/app/modules/sales/sales.utils.ts —
+ // keep both in sync (the edge runtime cannot import app code).
+ const defaultsEnabled = Object.values(defaultMarkups).some((v) => v > 0);
+ const effectiveDefaults = defaultsEnabled ? defaultMarkups : {};
+
+ // Rows whose price was stated by a person or an external system
+ // (priceSource = 'manual') are never recomputed. Mirrors decideRecalcPricing
+ // in sales.utils.ts.
+ const existingPricesResult = await client
+ .from("quoteLinePrice")
+ .select("quantity, priceSource")
+ .eq("quoteLineId", quoteLineId)
+ .eq("companyId", companyId);
+ // A failed read must abort: treating it as "no manual rows" would let the
+ // delete/replace below wipe manually priced rows.
+ if (existingPricesResult.error)
+ throw new Error("Failed to get existing quote line prices");
+ const manualQuantities = new Set(
+ (existingPricesResult.data ?? [])
+ .filter(
+ (row) =>
+ row.priceSource === "manual" &&
+ quantities.some((qty) => Number(qty) === Number(row.quantity))
+ )
+ .map((row) => Number(row.quantity))
+ );
+
// 2. Fix Buy material costs with supplier price breaks
const buyMaterials = await client
.from("quoteMaterial")
@@ -737,54 +766,77 @@ export async function calculateQuoteLinePrices(
}
// 6. Compute prices for each quantity
- const priceRows = quantities.map((qty) => {
- const categoryCosts: Record<CostCategoryKey, number> = {
- materialCost: 0,
- partCost: 0,
- toolCost: 0,
- consumableCost: 0,
- serviceCost: 0,
- laborCost: 0,
- machineCost: 0,
- overheadCost: 0,
- outsideCost: 0,
- };
+ const priceRows = quantities
+ .filter((qty) => !manualQuantities.has(Number(qty)))
+ .map((qty) => {
+ const categoryCosts: Record<CostCategoryKey, number> = {
+ materialCost: 0,
+ partCost: 0,
+ toolCost: 0,
+ consumableCost: 0,
+ serviceCost: 0,
+ laborCost: 0,
+ machineCost: 0,
+ overheadCost: 0,
+ outsideCost: 0,
+ };
- for (const key of costCategoryKeys) {
- categoryCosts[key] = effects[key].reduce(
- (acc, effect) => acc + effect(qty),
- 0
- );
- // Convert to per-unit cost
- if (qty > 0) {
- categoryCosts[key] = categoryCosts[key] / qty;
+ for (const key of costCategoryKeys) {
+ categoryCosts[key] = effects[key].reduce(
+ (acc, effect) => acc + effect(qty),
+ 0
+ );
+ // Convert to per-unit cost
+ if (qty > 0) {
+ categoryCosts[key] = categoryCosts[key] / qty;
+ }
}
- }
- // Apply markups
- const unitPrice = costCategoryKeys.reduce((sum, key) => {
- const cost = categoryCosts[key] ?? 0;
- const markup = defaultMarkups[key] ?? 0;
- return sum + cost * (1 + markup / 100);
- }, 0);
+ // Apply markups
+ const unitPrice = costCategoryKeys.reduce((sum, key) => {
+ const cost = categoryCosts[key] ?? 0;
+ const markup = effectiveDefaults[key] ?? 0;
+ return sum + cost * (1 + markup / 100);
+ }, 0);
- const roundedUnitPrice = Number(unitPrice.toFixed(precision));
+ const roundedUnitPrice = Number(unitPrice.toFixed(precision));
- return {
- quoteId,
- quoteLineId,
- quantity: qty,
- unitPrice: roundedUnitPrice,
- categoryMarkups: defaultMarkups,
- exchangeRate,
- createdBy: userId,
- leadTime: 0,
- discountPercent: 0,
- };
- });
+ return {
+ quoteId,
+ quoteLineId,
+ companyId,
+ quantity: qty,
+ unitPrice: roundedUnitPrice,
+ categoryMarkups: effectiveDefaults,
+ priceSource: "system",
+ exchangeRate,
+ createdBy: userId,
+ leadTime: 0,
+ discountPercent: 0,
+ };
+ });
- // 7. Delete existing and insert quoteLinePrice rows
- await client.from("quoteLinePrice").delete().eq("quoteLineId", quoteLineId);
- const insertResult = await client.from("quoteLinePrice").insert(priceRows);
- if (insertResult.error) throw new Error("Failed to insert quote line prices");
+ // 7. Replace system-priced rows; manual rows for current quantities are
+ // preserved untouched. Manual rows for removed quantity breaks are deleted
+ // along with the system rows.
+ let deleteQuery = client
+ .from("quoteLinePrice")
+ .delete()
+ .eq("quoteLineId", quoteLineId)
+ .eq("companyId", companyId);
+ if (manualQuantities.size > 0) {
+ deleteQuery = deleteQuery.not(
+ "quantity",
+ "in",
+ `(${[...manualQuantities].join(",")})`
+ );
+ }
+ const deleteResult = await deleteQuery;
+ if (deleteResult.error) throw new Error("Failed to delete quote line prices");
+
+ if (priceRows.length > 0) {
+ const insertResult = await client.from("quoteLinePrice").insert(priceRows);
+ if (insertResult.error)
+ throw new Error("Failed to insert quote line prices");
+ }
}
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 528a617910..e5a5fc722a 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -4928,6 +4928,7 @@ export type Database = {
accountsReceivableEmail: string | null
assetTaxDepreciationEnabled: boolean
assetTaxRate: number | null
+ autoStartOperationTimer: boolean
consoleEnabled: boolean
defaultCustomerCc: string[] | null
defaultSupplierCc: string[] | null
@@ -4971,6 +4972,7 @@ export type Database = {
accountsReceivableEmail?: string | null
assetTaxDepreciationEnabled?: boolean
assetTaxRate?: number | null
+ autoStartOperationTimer?: boolean
consoleEnabled?: boolean
defaultCustomerCc?: string[] | null
defaultSupplierCc?: string[] | null
@@ -5014,6 +5016,7 @@ export type Database = {
accountsReceivableEmail?: string | null
assetTaxDepreciationEnabled?: boolean
assetTaxRate?: number | null
+ autoStartOperationTimer?: boolean
consoleEnabled?: boolean
defaultCustomerCc?: string[] | null
defaultSupplierCc?: string[] | null
@@ -19751,6 +19754,50 @@ export type Database = {
},
]
}
+ jobMaterialStep: {
+ Row: {
+ jobMaterialId: string
+ jobOperationStepId: string
+ }
+ Insert: {
+ jobMaterialId: string
+ jobOperationStepId: string
+ }
+ Update: {
+ jobMaterialId?: string
+ jobOperationStepId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "jobMaterialStep_jobMaterialId_fkey"
+ columns: ["jobMaterialId"]
+ isOneToOne: false
+ referencedRelation: "jobMaterial"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterialStep_jobMaterialId_fkey"
+ columns: ["jobMaterialId"]
+ isOneToOne: false
+ referencedRelation: "jobMaterialWithMakeMethodId"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterialStep_jobMaterialId_fkey"
+ columns: ["jobMaterialId"]
+ isOneToOne: false
+ referencedRelation: "openJobMaterialLines"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterialStep_jobOperationStepId_fkey"
+ columns: ["jobOperationStepId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationStep"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
jobOperation: {
Row: {
assemblyInstructionId: string | null
@@ -19773,6 +19820,7 @@ export type Database = {
machineTime: number
machineUnit: Database["public"]["Enums"]["factor"]
manuallyScheduled: boolean
+ operationKind: Database["public"]["Enums"]["operationKind"]
operationLeadTime: number
operationMinimumCost: number
operationOrder: Database["public"]["Enums"]["methodOperationOrder"]
@@ -19821,6 +19869,7 @@ export type Database = {
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
manuallyScheduled?: boolean
+ operationKind?: Database["public"]["Enums"]["operationKind"]
operationLeadTime?: number
operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
@@ -19869,6 +19918,7 @@ export type Database = {
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
manuallyScheduled?: boolean
+ operationKind?: Database["public"]["Enums"]["operationKind"]
operationLeadTime?: number
operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
@@ -20888,6 +20938,157 @@ export type Database = {
},
]
}
+ jobOperationStepSlide: {
+ Row: {
+ annotations: Json
+ caption: string | null
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ imagePath: string
+ size: string
+ sortOrder: number
+ stepId: string
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ annotations?: Json
+ caption?: string | null
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ imagePath: string
+ size?: string
+ sortOrder?: number
+ stepId: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ annotations?: Json
+ caption?: string | null
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ imagePath?: string
+ size?: string
+ sortOrder?: number
+ stepId?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "jobOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_stepId_fkey"
+ columns: ["stepId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
jobOperationTool: {
Row: {
companyId: string
@@ -21086,6 +21287,36 @@ export type Database = {
},
]
}
+ jobOperationToolStep: {
+ Row: {
+ jobOperationStepId: string
+ jobOperationToolId: string
+ }
+ Insert: {
+ jobOperationStepId: string
+ jobOperationToolId: string
+ }
+ Update: {
+ jobOperationStepId?: string
+ jobOperationToolId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "jobOperationToolStep_jobOperationStepId_fkey"
+ columns: ["jobOperationStepId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationToolStep_jobOperationToolId_fkey"
+ columns: ["jobOperationToolId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationTool"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
journal: {
Row: {
accountingPeriodId: string | null
@@ -25436,6 +25667,36 @@ export type Database = {
},
]
}
+ methodMaterialStep: {
+ Row: {
+ methodMaterialId: string
+ methodOperationStepId: string
+ }
+ Insert: {
+ methodMaterialId: string
+ methodOperationStepId: string
+ }
+ Update: {
+ methodMaterialId?: string
+ methodOperationStepId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "methodMaterialStep_methodMaterialId_fkey"
+ columns: ["methodMaterialId"]
+ isOneToOne: false
+ referencedRelation: "methodMaterial"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodMaterialStep_methodOperationStepId_fkey"
+ columns: ["methodOperationStepId"]
+ isOneToOne: false
+ referencedRelation: "methodOperationStep"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
methodOperation: {
Row: {
assemblyInstructionId: string | null
@@ -25450,6 +25711,7 @@ export type Database = {
machineTime: number
machineUnit: Database["public"]["Enums"]["factor"]
makeMethodId: string
+ operationKind: Database["public"]["Enums"]["operationKind"]
operationLeadTime: number | null
operationMinimumCost: number | null
operationOrder: Database["public"]["Enums"]["methodOperationOrder"]
@@ -25480,6 +25742,7 @@ export type Database = {
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
makeMethodId: string
+ operationKind?: Database["public"]["Enums"]["operationKind"]
operationLeadTime?: number | null
operationMinimumCost?: number | null
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
@@ -25510,6 +25773,7 @@ export type Database = {
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
makeMethodId?: string
+ operationKind?: Database["public"]["Enums"]["operationKind"]
operationLeadTime?: number | null
operationMinimumCost?: number | null
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
@@ -25985,6 +26249,157 @@ export type Database = {
},
]
}
+ methodOperationStepSlide: {
+ Row: {
+ annotations: Json
+ caption: string | null
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ imagePath: string
+ size: string
+ sortOrder: number
+ stepId: string
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ annotations?: Json
+ caption?: string | null
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ imagePath: string
+ size?: string
+ sortOrder?: number
+ stepId: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ annotations?: Json
+ caption?: string | null
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ imagePath?: string
+ size?: string
+ sortOrder?: number
+ stepId?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "methodOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_stepId_fkey"
+ columns: ["stepId"]
+ isOneToOne: false
+ referencedRelation: "methodOperationStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
methodOperationTool: {
Row: {
companyId: string
@@ -26169,6 +26584,36 @@ export type Database = {
},
]
}
+ methodOperationToolStep: {
+ Row: {
+ methodOperationStepId: string
+ methodOperationToolId: string
+ }
+ Insert: {
+ methodOperationStepId: string
+ methodOperationToolId: string
+ }
+ Update: {
+ methodOperationStepId?: string
+ methodOperationToolId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "methodOperationToolStep_methodOperationStepId_fkey"
+ columns: ["methodOperationStepId"]
+ isOneToOne: false
+ referencedRelation: "methodOperationStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "methodOperationToolStep_methodOperationToolId_fkey"
+ columns: ["methodOperationToolId"]
+ isOneToOne: false
+ referencedRelation: "methodOperationTool"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
modelUpload: {
Row: {
autodeskUrn: string | null
@@ -38517,6 +38962,7 @@ export type Database = {
leadTime: number
netExtendedPrice: number | null
netUnitPrice: number | null
+ priceSource: string
quantity: number
quoteId: string
quoteLineId: string
@@ -38539,6 +38985,7 @@ export type Database = {
leadTime?: number
netExtendedPrice?: number | null
netUnitPrice?: number | null
+ priceSource?: string
quantity?: number
quoteId: string
quoteLineId: string
@@ -38561,6 +39008,7 @@ export type Database = {
leadTime?: number
netExtendedPrice?: number | null
netUnitPrice?: number | null
+ priceSource?: string
quantity?: number
quoteId?: string
quoteLineId?: string
@@ -39238,6 +39686,43 @@ export type Database = {
},
]
}
+ quoteMaterialStep: {
+ Row: {
+ quoteMaterialId: string
+ quoteOperationStepId: string
+ }
+ Insert: {
+ quoteMaterialId: string
+ quoteOperationStepId: string
+ }
+ Update: {
+ quoteMaterialId?: string
+ quoteOperationStepId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "quoteMaterialStep_quoteMaterialId_fkey"
+ columns: ["quoteMaterialId"]
+ isOneToOne: false
+ referencedRelation: "quoteMaterial"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteMaterialStep_quoteMaterialId_fkey"
+ columns: ["quoteMaterialId"]
+ isOneToOne: false
+ referencedRelation: "quoteMaterialWithMakeMethodId"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteMaterialStep_quoteOperationStepId_fkey"
+ columns: ["quoteOperationStepId"]
+ isOneToOne: false
+ referencedRelation: "quoteOperationStep"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
quoteOperation: {
Row: {
companyId: string
@@ -39252,6 +39737,7 @@ export type Database = {
machineRate: number | null
machineTime: number
machineUnit: Database["public"]["Enums"]["factor"]
+ operationKind: Database["public"]["Enums"]["operationKind"]
operationLeadTime: number
operationMinimumCost: number
operationOrder: Database["public"]["Enums"]["methodOperationOrder"]
@@ -39286,6 +39772,7 @@ export type Database = {
machineRate?: number | null
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
+ operationKind?: Database["public"]["Enums"]["operationKind"]
operationLeadTime?: number
operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
@@ -39320,6 +39807,7 @@ export type Database = {
machineRate?: number | null
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
+ operationKind?: Database["public"]["Enums"]["operationKind"]
operationLeadTime?: number
operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
@@ -39834,6 +40322,157 @@ export type Database = {
},
]
}
+ quoteOperationStepSlide: {
+ Row: {
+ annotations: Json
+ caption: string | null
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ imagePath: string
+ size: string
+ sortOrder: number
+ stepId: string
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ annotations?: Json
+ caption?: string | null
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ imagePath: string
+ size?: string
+ sortOrder?: number
+ stepId: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ annotations?: Json
+ caption?: string | null
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ imagePath?: string
+ size?: string
+ sortOrder?: number
+ stepId?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "quoteOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_stepId_fkey"
+ columns: ["stepId"]
+ isOneToOne: false
+ referencedRelation: "quoteOperationStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationStepSlide_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
quoteOperationTool: {
Row: {
companyId: string
@@ -40025,6 +40664,36 @@ export type Database = {
},
]
}
+ quoteOperationToolStep: {
+ Row: {
+ quoteOperationStepId: string
+ quoteOperationToolId: string
+ }
+ Insert: {
+ quoteOperationStepId: string
+ quoteOperationToolId: string
+ }
+ Update: {
+ quoteOperationStepId?: string
+ quoteOperationToolId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "quoteOperationToolStep_quoteOperationStepId_fkey"
+ columns: ["quoteOperationStepId"]
+ isOneToOne: false
+ referencedRelation: "quoteOperationStep"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationToolStep_quoteOperationToolId_fkey"
+ columns: ["quoteOperationToolId"]
+ isOneToOne: false
+ referencedRelation: "quoteOperationTool"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
quotePayment: {
Row: {
companyId: string
@@ -62452,14 +63121,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -66398,14 +67067,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -70540,6 +71209,7 @@ export type Database = {
machineTime: number
machineUnit: Database["public"]["Enums"]["factor"]
operationDueDate: string
+ operationKind: Database["public"]["Enums"]["operationKind"]
operationOrder: number
operationOrderType: Database["public"]["Enums"]["methodOperationOrder"]
operationQuantity: number
@@ -70811,6 +71481,7 @@ export type Database = {
makeMethodId: string
materialMakeMethodId: string
methodMaterialId: string
+ methodOperationStepIds: Json
methodType: Database["public"]["Enums"]["methodType"]
operationId: string
order: number
@@ -72496,6 +73167,7 @@ export type Database = {
| "Completed"
| "Skipped"
oeeImpact: "Down" | "Planned" | "Impact" | "No Impact"
+ operationKind: "Operation" | "Assembly" | "Inspection"
operationType: "Inside" | "Outside"
payableLineType:
| "Comment"
@@ -73863,6 +74535,7 @@ export const Constants = {
"Skipped",
],
oeeImpact: ["Down", "Planned", "Impact", "No Impact"],
+ operationKind: ["Operation", "Assembly", "Inspection"],
operationType: ["Inside", "Outside"],
payableLineType: [
"Comment",
diff --git a/packages/database/supabase/migrations/20260714180443_quote-line-price-source.sql b/packages/database/supabase/migrations/20260714180443_quote-line-price-source.sql
new file mode 100644
index 0000000000..6fcad60e01
--- /dev/null
+++ b/packages/database/supabase/migrations/20260714180443_quote-line-price-source.sql
@@ -0,0 +1,39 @@
+-- Add an explicit price provenance flag to quoteLinePrice.
+--
+-- 'system' = Carbon computed this price (cost rollup × markups, price
+-- resolution). Recalculations keep repricing these rows.
+-- 'manual' = a person or an external system (UI price edit, Paperless Parts
+-- import) stated this price. No recalculation may change it.
+--
+-- Replaces the ambiguous heuristic (empty categoryMarkups + unitPrice > 0)
+-- which could not distinguish a user-typed price from a system-computed one.
+
+ALTER TABLE "quoteLinePrice"
+ ADD COLUMN "priceSource" TEXT NOT NULL DEFAULT 'system';
+
+-- NOT VALID skips the full-table validation scan under the ACCESS EXCLUSIVE
+-- lock; the constraint is validated explicitly after the backfill under a
+-- weaker lock.
+ALTER TABLE "quoteLinePrice"
+ ADD CONSTRAINT "quoteLinePrice_priceSource_check"
+ CHECK ("priceSource" IN ('system', 'manual')) NOT VALID;
+
+-- Backfill: err on the side of never overwriting a price. A frozen price is
+-- visible and recoverable (edit a markup to re-enable cost tracking); a
+-- silently overwritten customer-facing quote price is not. Any priced row
+-- without a positive per-category markup is treated as manually priced.
+UPDATE "quoteLinePrice"
+SET "priceSource" = 'manual'
+WHERE "unitPrice" > 0
+ AND (
+ "categoryMarkups" IS NULL
+ OR "categoryMarkups" = '{}'::jsonb
+ OR NOT EXISTS (
+ SELECT 1
+ FROM jsonb_each_text("categoryMarkups") AS kv
+ WHERE kv.value::numeric > 0
+ )
+ );
+
+ALTER TABLE "quoteLinePrice"
+ VALIDATE CONSTRAINT "quoteLinePrice_priceSource_check";
diff --git a/packages/ee/src/paperless-parts/lib/lib.ts b/packages/ee/src/paperless-parts/lib/lib.ts
index 5692ccf355..d7847b9df7 100644
--- a/packages/ee/src/paperless-parts/lib/lib.ts
+++ b/packages/ee/src/paperless-parts/lib/lib.ts
@@ -3045,6 +3045,9 @@ export async function insertQuoteLines(
unitPrice: qp.unit_price ?? 0,
leadTime: qp.lead_time ?? 0,
discountPercent: 0,
+ // Paperless is the pricing source of truth for imported quotes —
+ // mark the price manual so no Carbon recalc ever overwrites it.
+ priceSource: "manual",
createdBy
}));