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.

feat: numeric precision & formatting standard (#1371)

Siddharth Gaikwadacdbcad23ed7
diff --git a/.ai/lessons.md b/.ai/lessons.md
index cc346f8f9a..39847e16c7 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -920,10 +920,19 @@ canvas hosting Radix popovers/selects.
**Problem:** The function keys the snapshot of existing rows by quantity and looks each one up while building the reinsert. Through PostgREST a `NUMERIC` column arrives as a JS `number`, so `pricesByQuantity[10]` matched. Through node-postgres — which Kysely uses — the same column arrives as the string `"10.00000"`, because pg does not parse `NUMERIC` (oid 1700) to float and this repo sets no `setTypeParser` anywhere. Every `Map.get(10)` therefore missed, `existing` was always `undefined`, and each preserved field fell back to the caller's value: shipping to the column default `0`, discount and lead time to the zeros the recalculate route passes. The generated types say `number` on both paths, so `tsgo` cannot see it — the mismatch exists only at runtime.
-**Rule:** When porting a query from supabase-js to Kysely, treat every `NUMERIC`/`DECIMAL`/`BIGINT` read as a **string** regardless of what the generated type claims. Normalize with `Number(...)` only where the value has to be a number — an object/`Map` key, a `===` comparison, arithmetic — and only for bounded fields like a quantity or a precision. Do **not** normalize a whole row for tidiness: `Number()` on a `BIGINT` or a wide `NUMERIC` silently loses precision past `Number.MAX_SAFE_INTEGER`, and money is exactly where that matters. Writing values back untouched is both safe and preferable — pg accepts the canonical string for a numeric param, and passing it straight through preserves the stored value exactly. More generally: a client swap can change runtime value types without changing a single TypeScript type, so a typecheck is not evidence that a port behaves identically — exercise it against a real database.
+**Rule (updated by the numeric-precision standard):** NUMERIC (oid 1700) now decodes to a JS number in BOTH runtimes — node-postgres via `setTypeParser` and deno-postgres via `controls.decoders`, registered once in `lib/postgres/index.ts` — so runtime finally matches the generated types for numerics. The caution below still applies to `BIGINT` and float8 (still strings), to any pool NOT built through the shared factory, and as history for why `Number(...)` coercions litter Kysely call sites (they are now harmless no-ops). Original rule: when porting a query from supabase-js to Kysely, treat every `NUMERIC`/`DECIMAL`/`BIGINT` read as a **string** regardless of what the generated type claims. Normalize with `Number(...)` only where the value has to be a number — an object/`Map` key, a `===` comparison, arithmetic — and only for bounded fields like a quantity or a precision. Do **not** normalize a whole row for tidiness: `Number()` on a `BIGINT` or a wide `NUMERIC` silently loses precision past `Number.MAX_SAFE_INTEGER`, and money is exactly where that matters. Writing values back untouched is both safe and preferable — pg accepts the canonical string for a numeric param, and passing it straight through preserves the stored value exactly. More generally: a client swap can change runtime value types without changing a single TypeScript type, so a typecheck is not evidence that a port behaves identically — exercise it against a real database.
**Applies to:** `apps/erp/app/modules/sales/sales.service.ts` (`upsertQuoteLinePrices`), any `Kysely<KyselyDatabase>` service in `apps/erp/app/modules/**` or `packages/database/supabase/functions/**`, and the `getPostgresClient` pool in `packages/database/supabase/functions/lib/postgres/index.ts`.
+## react-aria's blur commit makes the input formatter part of arithmetic
+
+**Context:** The numeric-precision standard's motivating bug — a user typed 6.25% tax, saved, reopened, and read 6.22%.
+
+**Problem:** react-aria NumberField commits on blur by running `parse(format(value))` — whatever `formatOptions` the input carries re-rounds the committed number. A currency-formatted amount input rounds to cents on blur; the old bidirectional tax pair (amount edit → percent = amount/subtotal, percent edit → amount = subtotal×percent) then overwrote the typed 6.25% with 0.56/9.00 = 6.22%. Nothing in zod, the column type, or the service was wrong — the INPUT FORMATTER did the rounding, and the coupling propagated it.
+
+**Rule:** Editable numeric inputs must use the named `INPUT_FORMAT.*` kinds from `@carbon/utils` (rate max 3 percent-digits, quantity max 5, money/price at the currency's decimals) so the blur round-trip preserves the stored scale. **Round a derived value to the scale of the field that will hold it BEFORE putting it there** — that is the actual fix. An unrounded 0.5625 in a cents-formatted input is re-committed as 0.56 on blur, which registers as a genuine change and feeds back through any coupling; a value derived through `applyRate` at the currency's decimals commits identically and triggers nothing. With that in place a value pair can safely stay coupled in both directions (`TaxFields` does, so the stored pair is always consistent), accepting that a rate derived back from an amount is limited by the amount's scale. When an input's digits look like a display preference, remember they are arithmetic on the persisted value.
+
+**Applies to:** every `formatOptions` on an editable `NumberField`/`NumberControlled`/`EditableNumberCell`; `apps/erp/app/components/Form/TaxFields.tsx`; `.claude/rules/numeric-precision.md`; the `no-inline-fraction-digits` conformance check.
## Postgres transition tables are visible ONLY to the function the trigger invokes directly
**Context:** The `itemStockQuantities` aggregate needed a statement-level handler on `itemLedger` so a bulk posting is one upsert instead of N. The event system already builds statement-level triggers (`trg_event_async_*` with `REFERENCING NEW TABLE AS batched_new`), so the obvious move was to have `dispatch_event_batch()` forward to a custom function.
diff --git a/.ai/plans/2026-08-11-numeric-precision-manual-testing.md b/.ai/plans/2026-08-11-numeric-precision-manual-testing.md
new file mode 100644
index 0000000000..fabb7b7c8e
--- /dev/null
+++ b/.ai/plans/2026-08-11-numeric-precision-manual-testing.md
@@ -0,0 +1,294 @@
+# Numeric Precision & Formatting — Manual Testing Checklist
+
+**Plan:** `.ai/plans/2026-08-11-numeric-precision-standard.md`
+**Spec:** `.ai/specs/2026-08-11-numeric-precision-standard.md` (not in repo; the plan is self-contained)
+
+## Prerequisites
+
+- [ ] Migrations applied in order (`flip-purchasing-tax-percent-writable`, `widen-ledger-amounts` (15a), the purchasing cascade (15b), the tail (15c)) and types regenerated
+- [ ] Dev stack running (`crbn up`); ERP + MES reachable
+- [ ] A test company with: base currency USD, at least one supplier, one customer, one purchasable part, one manufactured part with a BOM containing a **picked** (Pick methodType) raw material
+- [ ] For currency tests: add currencies JPY (decimalPlaces 0) and BHD (decimalPlaces 3) in Accounting → Currencies, any exchange rate
+- [ ] Note: jobs created BEFORE the fix keep their old integer `estimatedQuantity` until recalculate re-runs (edit the job quantity to re-trigger). Always create FRESH documents/jobs for these tests.
+
+---
+
+## 1. Fractional material consumption & return
+
+Setup: manufactured part whose BOM uses 1 EA of picked material per unit, 0% scrap.
+
+- [ ] 1.1 Create a job for **4.5** units. Job materials: the picked material's estimated quantity is **4.5** (NOT 5).
+- [ ] 1.2 Pick/issue 5 units of the material to the job (over-pick deliberately).
+- [ ] 1.3 Complete the job with quantity complete 4.5; decimal input accepted in the dialog.
+- [ ] 1.4 After completion: consumed = **4.5**; the return sweep puts **0.5** back (check inventory / item ledger for a 0.5 return movement).
+- [ ] 1.5 Scrap regression: Make child with 1% scrap, job quantity 31 → estimated total with scrap is **32** (scrap allowance still rounds UP to whole units).
+- [ ] 1.6 Discrete regression: job for 10 units behaves exactly as before (10 / 10 / 0 returned).
+- [ ] 1.7 Job operations for the 4.5-unit job show operation quantity **4.5** in ERP and MES (assembly/inspection screens) — not rounded to 5.
+
+## 2. Purchase invoice tax (the 6.25% → 6.22% bug)
+
+Setup: new purchase invoice, line: quantity 1, unit price **$9.00**, no shipping.
+
+- [ ] 2.1 Type **6.25** in Tax Percent → Tax Amount auto-fills **$0.56**.
+- [ ] 2.2 Tab through the Tax Amount field (blur), Save, reopen: Tax Percent reads **6.25%** (NOT 6.22%), amount $0.56.
+- [ ] 2.3 Amount override: set Tax Amount to **$0.57**, save, reopen: amount **$0.57** and percent **6.333%** — the pair is coupled both ways, so an amount edit re-derives the rate (`round(0.57 / 9.00)` = 0.06333). The old 6.25% is *not* retained; a stored pair that disagreed with itself is the bug this replaced.
+- [ ] 2.4 Base change: quantity → 2. Amount re-derives (6.25% of $18.00 = **$1.13**); percent unchanged.
+- [ ] 2.5 Fine-grained rate: **6.255%** survives blur and save, displays as **6.255%**.
+- [ ] 2.6 G/L-account and Fixed-Asset line types: repeat 2.1–2.2 on the second tax pair — same behavior.
+- [ ] 2.7 Zero-subtotal edge: unit price 0 — entering a percent yields $0.00, no NaN, no crash.
+
+## 3. Purchase order tax
+
+- [ ] 3.1 New PO line, qty 1 × $9.00: repeat 2.1–2.3 (6.25% → blur → save → reopen → 6.25%; amount override keeps rate). This exercises the PO-form seed fix — the form must read the STORED percent, not re-derive it from the amount.
+- [ ] 3.2 PO totals/summary reflect the tax amount correctly.
+
+## 4. Supplier quote tax (new capability)
+
+- [ ] 4.1 Supplier quote line pricing shows a **Tax Percent** row beside Tax Amount (per quantity break).
+- [ ] 4.2 Enter 6.25% → amount derives from that break's subtotal (qty × supplier unit price + shipping); save; reopen: rate persists.
+- [ ] 4.3 Editing the Tax Amount cell keeps the stored percent (value-pair one-way rule, same as the forms).
+- [ ] 4.4 Pre-migration quotes: open one — historical derived rate displays without error; editing saves the typed value.
+
+## 5. Sales invoice tax (directly-stored column)
+
+- [ ] 5.1 New sales invoice line qty 1 × $9.00: 6.25% → blur → save → reopen → 6.25%.
+- [ ] 5.2 Unit price → $11.00: amount re-derives ($0.69); rate unchanged.
+- [ ] 5.3 Fixed-asset tab: percent field accepts 6.255% and round-trips.
+- [ ] 5.4 Post the invoice — totals match (subtotal + tax), no balance error.
+
+## 6. Currency decimal places
+
+> **Status as of 2026-08-12 — read before running this suite.** Only the **tax
+> amount** field currently honours `currency.decimalPlaces`. Unit price,
+> shipping and add-on entry fields, and all read-only per-unit displays, still
+> fall back to Intl's CLDR default (2 for most currencies). So on a 0-decimal
+> currency, 6.1 and 6.4 **will fail on every field except Tax Amount** — that is
+> a known open gap (plan → Open items 1), not a new bug. Record it as
+> *expected-fail* rather than filing it. Run the suite anyway: it is the
+> acceptance test for that work when it lands.
+
+- [ ] 6.1 Purchase invoice in **JPY**: amounts show **0** fraction digits (¥1,000, never ¥1,000.00); 6.25% of ¥1,000 → **¥63**. *(Today: passes on Tax Amount only.)*
+- [ ] 6.2 Purchase invoice in **BHD**: **3** digits; 6.25% of BHD 9.000 → **0.563**.
+- [ ] 6.3 USD amounts pad: "$4.50", never "$4.5".
+- [ ] 6.4 Edit a currency's decimalPlaces (e.g. set a test currency to 0) — documents in it follow the column in both inputs and displays. *(Today: the Tax Amount field follows; the unit price does not.)*
+
+## 7. Exchange rate precision (nightly-sync bug)
+
+- [ ] 7.1 Trigger the exchange-rate update (Inngest `update-exchange-rates`). The **JPY** rate keeps its fraction (150.2345, not 150) in Accounting → Currencies.
+- [ ] 7.2 Rates carry up to 5 decimals for all currencies, regardless of each currency's own decimalPlaces.
+- [ ] 7.3 A currency whose rate is below 0.5 against a 0-decimal setting (previously frozen at 0 by the truthiness filter) now receives a real rate on the nightly run.
+
+## 8. Unit prices (Price kind)
+
+- [ ] 8.1 Supplier part at unit price **0.164**: survives blur/save; displays **$0.164** in the form, price-break rows, and supplier-parts table.
+- [ ] 8.2 Storage round-trip: hard-refresh and reopen — the value is 0.164 (the column holds the scale after 15b, not just the UI).
+- [ ] 8.3 Unit price 4.5 displays padded: **$4.50**.
+- [ ] 8.4 Extended price: 10,000 × $0.164 = **$1,640.00** (settlement-rounded, not $1,600 from a pre-rounded $0.16).
+- [ ] 8.5 Purchase history / quote line price displays show full stored precision (up to 5 decimals) — and purchase history renders in the account locale (the hardcoded en-US is gone).
+- [ ] 8.6 Customer portal (share link) sales-order lines: prices NOT truncated to 2 decimals (portal function return-type fix).
+
+## 9. Payments, memos & settlement (5dp GL, settlement decimals)
+
+### Orientation — where these live
+
+Two separate screens, both under **Invoicing** in the left sidebar, in the
+**Payments** group at the bottom of that menu:
+
+| Screen | Sidebar item | URL |
+|---|---|---|
+| Payments (cash in/out) | **Payments** | `/x/invoicing/payments` |
+| Credit & debit memos (non-cash adjustments) | **Credits & Debits** | `/x/invoicing/credits` |
+
+Both follow the same lifecycle: **Draft → Posted → Voided.** A document only
+writes GL entries when you press **Post**. While it is Draft you can edit it;
+once Posted it is immutable and the header's primary button changes from
+**Post** to a red **Void**.
+
+Two vocabulary points that decide which fields you get:
+
+- **Payment Type** — `Receipt` means money coming IN, so the form asks for a
+ **Customer**. `Disbursement` means money going OUT, so it asks for a
+ **Supplier**. Picking the wrong one and then hunting for the missing field is
+ the usual first stumble.
+- **Memo Direction** — party × direction gives four combinations:
+ Customer + Credit → AR down · Customer + Debit → AR up ·
+ Supplier + Debit → AP down · Supplier + Credit → AP up.
+ For 9.3 you want **Customer + Credit** (the customer owes you less).
+
+### Setup — you need an open invoice to pay first
+
+A payment with nothing to apply to proves nothing, so build the target first.
+
+1. Go to **Invoicing → Sales Invoices**, press **New**.
+2. Pick your customer. Set **Currency** to **EUR** (any currency that is not
+ your base USD) — this is what makes 9.1 a foreign-currency test.
+3. Set **Exchange Rate** to `1.25`.
+4. Add a line: quantity `10`, unit price `100.00`. Save.
+5. Press **Post** in the header. The invoice must reach **Posted** with an open
+ balance — if it is still Draft, the payment screen will not offer it.
+6. Repeat 1–5 for a **second** EUR invoice (quantity `4`, unit price `50.00`)
+ so 9.1 has two invoices to split across.
+
+Note the two balances shown on the invoice list; you will reconcile against
+them at the end.
+
+### 9.1 Foreign-currency payment across two invoices
+
+- [ ] 9.1 **Invoicing → Payments → New.** Fill in, top to bottom:
+ - **Payment ID** — leave it; the sequence fills it in.
+ - **Type** — `Receipt`. (A **Customer** field appears once you pick this.)
+ - **Customer** — the customer from setup.
+ - **Payment Date** — today.
+ - **Currency** — `EUR`.
+ - **Exchange Rate** — `1.25`.
+ - **Total Amount** — `900.00` (less than the 1200 + 200 = 1400 open, so the
+ applications are deliberately partial).
+ - **Bank / Cash Account** — pick any Asset account.
+ - **Reference** — `PRECISION-9.1`.
+
+ Save. You land on the payment detail page in **Draft**.
+
+ On that page, find the **Apply to invoices** panel. Both EUR invoices are
+ listed with their open balances. Type an applied amount against each —
+ `700.00` on the first, `200.00` on the second (900 total, matching the
+ payment). Then press **Post** in the header.
+
+ **Expected:** it posts. **No "journal does not balance" error.** This is the
+ case that broke when the JS balance check ran at 5dp while the column still
+ rounded to 4 — if you see that error, stop and record the exact message.
+
+- [ ] 9.2 On the same screen before posting (use a fresh Draft payment if 9.1 is
+ already Posted), press **Auto apply**. It should fill the rows top-down until
+ the payment is exhausted, and the unapplied remainder should read exactly
+ `0.00` — not `0.00001` or `-0.00`. Clear it and re-apply to confirm it
+ round-trips.
+
+- [ ] 9.3 **Invoicing → Credits & Debits → New.**
+ - **Memo ID** — leave it.
+ - **Direction** — `Credit`.
+ - **Customer** — same customer.
+ - **Memo Date** — today.
+ - **Currency** — `EUR`, **Exchange Rate** `1.25`.
+ - **Amount** — `150.00`.
+ - **Reference** — `PRECISION-9.3`.
+
+ Save, then **Post**. **Expected:** posts cleanly; the GL entries balance.
+ To see them: **Accounting → Journal Entries**, find the newest entry, and
+ confirm total debits equal total credits.
+
+- [ ] 9.4 Repeat 9.1 with a **USD** payment at **Exchange Rate `1.0`** against a
+ USD invoice. **Expected:** identical behaviour to before this branch — this is
+ the no-FX control case.
+
+- [ ] 9.5 **The settlement-vs-internal distinction — the point of the suite.**
+ After the 9.1 payment posts, open each invoice it touched and read the
+ **balance / amount due**. **Expected:** a clean settlement figure at the
+ currency's decimals — `€500.00`, never `€500.00000` or `€499.99998`.
+ Then open the GL entry behind it (**Accounting → Journal Entries** → the
+ entry for that payment). **Expected:** the internal journal lines there
+ *may* carry up to 5 decimals. That asymmetry is correct and deliberate:
+ settlement values round to the currency, internal GL lines carry scale 5.
+ A 5-decimal figure on the *invoice balance* is the bug; a 5-decimal figure on
+ a *journal line* is not.
+
+- [ ] 9.6 **Dust forgiveness.** Create a payment for `0.995` less than an
+ invoice's full open balance (e.g. balance `€500.00`, pay `€499.01`), apply it
+ all to that invoice, and post. **Expected:** the invoice flips to **Paid**
+ anyway — that is `INVOICE_DUST_THRESHOLD` (a penny or two of difference is
+ forgiven when deciding paid status, an existing Carbon concept, not something
+ this branch introduced). Also confirm no spurious on-account credit line was
+ created for sub-`0.0001` unapplied dust.
+
+- [ ] 9.7 **Period close.** Go to **Accounting → Periods**, find the period
+ containing today's postings, and close it. **Expected:** the close audit
+ passes with no debit/credit drift flagged. The close check uses a `0.001`
+ tolerance (manual journals and period close), deliberately tighter than the
+ `0.01` used by payment/memo posting — do not "fix" one to match the other.
+
+**If a post fails:** capture the full error text and the payment/memo ID before
+retrying. "Journal does not balance (off by …)" with a drift smaller than
+`0.01` is the specific regression this suite exists to catch.
+
+## 10. Tax value pair propagation (any write that sets one sets both)
+
+- [ ] 10.1 Duplicate a PO whose line has 6.25% / $0.56: the duplicate's line shows **6.25% AND $0.56** (not 0% + $0.56).
+- [ ] 10.2 Convert a supplier quote (with a taxed price break) to a PO: the PO line carries the break's percent and amount.
+- [ ] 10.3 Create a purchase invoice from a partially-received PO with tax: the invoice line's percent equals the PO line's percent; the amount is prorated by the uninvoiced fraction.
+- [ ] 10.4 Edit the invoice line's quantity afterwards: the amount re-derives from the carried percent (NOT from 0% — the pre-fix failure mode zeroed it).
+- [ ] 10.5 AI-extracted supplier invoice (upload a PDF with tax): the created line's percent = extracted tax / subtotal; reopening and editing the base re-derives sensibly.
+- [ ] 10.6 Supplier portal: submit a digital quote with a tax amount on a break — the stored row carries a derived percent, and converting it to a PO carries both.
+
+## 11. Percent displays & inputs app-wide
+
+- [ ] 11.1 Percents render up to 3 digits, only when real: 5% → "5%", 6.25% → "6.25%", 6.255% → "6.255%".
+- [ ] 11.2 Quote line discount: 12.345% survives blur and save (no 2-digit clamp).
+- [ ] 11.3 Read-only percent cells in tables render without regression (spot-check quotes list, tax columns).
+
+## 12. Quantity displays
+
+- [ ] 12.1 Read-only quantity cells show full stored precision up to 5 decimals: 4.33333 → "4.33333"; whole numbers stay whole ("3"); 0.00125 renders "0.00125" (old "<0.01" placeholder is gone).
+- [ ] 12.2 Editable quantity inputs preserve 5 decimals (4.33333 survives blur/save).
+- [ ] 12.3 MES: the 4.5-unit job's operation shows 4.5; serial/tracked-entity counts remain whole numbers.
+- [ ] 12.4 Dense tables (BOM, job materials, inventory) remain readable — common-case values render exactly as before; only genuinely-precise values show more digits.
+
+## 13. Locale formatting (hardcode fixes)
+
+Switch account language to German (or browser locale de-DE):
+
+- [ ] 13.1 Intercompany transaction table + balance matrix: locale separators (1.234,56), not US format.
+- [ ] 13.2 Quote line pricing history: same.
+- [ ] 13.3 Supplier part purchase history: same (was hardcoded en-US).
+- [ ] 13.4 Maintenance dispatch items: costs render as formatted currency (no literal `$` on a raw number). MES work-center maintenance display uses the app locale, not the browser default.
+- [ ] 13.5 Spot-check 3–4 money-heavy screens (invoices list, quote summary, payment tables) in de-DE — no mixed-locale artifacts.
+
+## 14. PDFs
+
+Generate a quote, a sales order, and a sales invoice PDF, each with a taxed line at 6.255%:
+
+- [ ] 14.1 Tax percent prints **6.255%** (not "6.26%").
+- [ ] 14.2 A 6.25% line prints "6.25%" (no forced third digit).
+- [ ] 14.3 Amounts/totals unchanged vs a pre-change control PDF of the same document.
+
+## 15. Xero boundary (engineer-run; needs a connected sandbox or unit tests)
+
+- [ ] 15.1 Payload builders round at serialization: totals/payments/balance at the currency's decimals; UnitAmount at 4dp. Verify via the EE unit tests if present, else inspect a captured payload.
+- [ ] 15.2 LineAmount no longer carries float garbage (0.45000000000000007-class values) — pre-existing bug fixed by the boundary rule.
+
+## 16. Conformance & regression gates (engineer-run)
+
+- [ ] 16.1 `pnpm --filter @carbon/utils test` — precision + format suites green (incl. the assertBalanced tolerance pins).
+- [ ] 16.2 `pnpm --filter @carbon/checks test` — all three new checks green; `newViolations()` = 0 against the fresh baseline.
+- [ ] 16.3 `pnpm run lint` + the scoped typechecks in the plan's Final validation — green.
+- [ ] 16.4 `grep -rn "round4" apps packages --include="*.ts" --include="*.tsx" | grep -v node_modules` → no output.
+- [ ] 16.5 `grep -rn "SUPPLIER_PART_PRICE_PRECISION" apps --include="*.ts" --include="*.tsx"` → no output (the constant never landed; the price kind covers those sites).
+- [ ] 16.6 Smoke: load each core ERP module (sales, purchasing, invoicing, production, inventory, accounting, quality) — no console errors.
+
+## Known gaps as of 2026-08-12 (expected-fail, already tracked)
+
+Distinct from the by-design list below: these are things the branch intends to
+do and does not do yet. Mark them expected-fail; don't file them.
+
+- **Currency decimals outside tax fields** — see the banner on suite 6. Affects
+ 6.1 and 6.4, and any unit-price display in suites 8 and 11 on a non-2-decimal
+ currency. Three commits attempting this were reverted on 2026-08-12 for
+ hardcoding `?? 2` against the plan's own rule; the fix needs `decimalPlaces`
+ exposed client-side first (plan → Open items 1).
+- **`SupplierQuoteLinePricing` is not on `TaxFields`** — suite 4 exercises a
+ hand-rolled percent/amount pair there, so its two-way coupling behaviour may
+ differ from the other three forms (plan → Open items 3).
+- **Exchange Rate input caps at 4 decimals** (`PaymentForm`), while exchange
+ rates are scale-5 internal values. Typing a 5-decimal rate truncates on blur.
+ Relevant to suite 7 and to the 9.x setup steps (plan → Open items 5).
+- **10 unclassified `Math.round` sites in MES** — suite 12 may show rounded
+ quantities on those screens (plan → Open items 4).
+
+## Known-acceptable outcomes (do not file as bugs)
+
+- Historical purchasing lines keep their previously-derived (drifted) rates — a stored 6.22% stays 6.22%; the original entry is unrecoverable by design (no backfill).
+- Jobs created before the fix keep integer estimated quantities until their recalculate re-runs.
+- GL journal lines now carry 5 decimals where they carried 4 (intentional; requires migration 15a). Settlement values (balances, applied amounts) stay at currency decimals by design.
+- A manual tax-amount override is replaced by the derived amount when the line's base (qty/price/shipping) changes afterward.
+- Quantity cells may show more decimals than before when the stored value genuinely has them (truthful display, not a formatting bug).
+- CSV table exports contain raw stored values, so they may now show 5 decimals where the old columns clamped earlier — truthful data, expect diff churn against old exports.
+- The first nightly FX run after deploy updates currencies that were previously frozen at a zero rate, and 0-decimal currencies' rates become fractional for the first time.
+- Xero syncs now include an explicit CurrencyRate for near-1 rates that previously snapshotted to exactly 1 and were omitted.
diff --git a/.ai/plans/2026-08-11-numeric-precision-standard.md b/.ai/plans/2026-08-11-numeric-precision-standard.md
new file mode 100644
index 0000000000..ce6c0adbe0
--- /dev/null
+++ b/.ai/plans/2026-08-11-numeric-precision-standard.md
@@ -0,0 +1,585 @@
+# Numeric Precision & Formatting Standard — Implementation Plan
+
+**Spec:** `.ai/specs/2026-08-11-numeric-precision-standard.md` (all decisions resolved — do not re-litigate). The spec file is not in the repo; this plan is self-contained and is the source of truth.
+**Branch:** `feat/numeric-precision-standard` off `main`
+**Manual QA:** `.ai/plans/2026-08-11-numeric-precision-manual-testing.md`
+
+## Ground rules
+
+- Do not run `pnpm db:migrate` on shared environments without coordination; regenerate types (`pnpm run generate:types`) only after migrations are applied.
+- Scoped typechecks only: `pnpm exec turbo run typecheck --filter=<pkg>` (whole-repo OOMs). ERP's filter name is `erp`.
+- **PR #1370 is merged with its supplier-price precision work REVERTED in-PR** (revert commit `8d2a155b`): the `SUPPLIER_PART_PRICE_PRECISION` constant and the `supplier-part-unit-price-precision` migration do NOT exist on `main`. This PR re-does that work through the precision system: change 15 widens `supplierPart.unitPrice` (+ `supplierPartPrice`), change 12 redoes the four UI files via the price kind.
+- **Migration order is load-bearing:** the ledger-widening migration (15a) must be applied before the 5dp posting flip (change 9) ships — otherwise the JS balance check passes on 5dp values and Postgres re-rounds each line to 4dp after the check (stored-imbalance window). The taxPercent flip (change 4) is catalog-only and independent. Never backdate migration timestamps (`.ai/lessons.md`).
+- `deno check` on edge functions is not clean at baseline — gate on the DELTA of errors attributed to touched files, not exit code (`.ai/lessons.md`).
+- Migration comments must not quote constrained types like `NUMERIC(10, 2)` literally — the `no-numeric-precision` conformance scan is a plain text match (this exact mistake was made and fixed inside PR #1370).
+- Suggested commit grouping: (1) precision module + scrap fixes, (2) migrations + types + validators + write-path propagation, (3) TaxFields + forms, (4) formatting layer + sweeps, (5) posting functions + Xero boundary, (6) conformance checks + docs.
+
+## Overview
+
+| # | Change | Nucleus |
+|---|--------|---------|
+| 1 | Precision module | `functions/shared/precision.ts` (new) |
+| 2 | Utils façade + tests | `packages/utils/src/math.ts`, `precision.test.ts` (new) |
+| 3 | Scrap-ceil fixes (operation-quantity ceils + consolidation sites) | `recalculate`, `get-method`, production/sales app sites |
+| 4 | taxPercent flip migration | new migration, 3 tables |
+| 5 | Types regen + validators + tax value-pair propagation | models, services, convert fn, 6 write paths |
+| 6 | Formatting layer (money / price / percent / quantity) | `packages/utils/src/format.ts` (new) |
+| 7 | TaxFields component + adoption in 4 forms | `components/Form/TaxFields.tsx` (new), 4 forms |
+| 8 | Formatter hooks + input-format sweep | 3 hooks + new `usePriceFormatter` |
+| 9 | 5dp GL posting + settlement decimals (all 12 posting functions) | post-* functions, 2 tables, 2 services |
+| 10 | Epsilon comparisons → equals | receiving, quality-disposition, quality AssociatedItemsList, traceability |
+| 11 | toFixed-as-arithmetic fixes (incl. exchange-rate bug) | `lib/methods.ts`, `update-exchange-rates.ts` |
+| 12 | Formatter sweep: raw Intl.NumberFormat + inline fraction digits | 17 files + supplier-part price UI redo |
+| 13 | PDF percent + MES quantity displays | documents pdf blocks, MES views |
+| 14 | NUMERIC type parser on pg pools | `lib/postgres/index.ts` (both branches) |
+| 15 | Storage-scale widening (3 migrations: ledger first, purchasing cascade, tail) | migrations + RPC redeclarations |
+| 16 | Conformance checks (3) + baseline | `packages/checks` |
+| 17 | Rule doc + AGENTS.md | `.claude/rules/numeric-precision.md` |
+| 18 | Xero boundary rounding | `packages/ee/src/accounting` payload builders |
+
+## Execution status — verified 2026-08-12 at `f25c4f088`
+
+Every ✅ below was confirmed by running the change's own verify command against
+the branch, not from the commit log. `pnpm --filter @carbon/checks test` reports
+**0 new violations**; scoped typecheck (`erp`, `@carbon/utils`) is clean; 160
+utils tests pass.
+
+| # | Status | Evidence / gap |
+|---|---|---|
+| 1 | ✅ | `functions/shared/precision.ts` present |
+| 2 | ✅ | re-export in place, `roundAmount` 0 refs |
+| 3 | ⚠️ | `Math.ceil` gone from `recalculate`/`get-method` and the target is never rounded — but written inline as `round(scrap, 0, Up)` + addition. **`withScrap()` has zero real call sites** despite being specified here and pinned in `precision.test.ts` |
+| 4 | ✅ | `20260811123612_flip-purchasing-tax-percent-writable.sql` |
+| 5 | 🟡 | validators carry `taxPercent`; duplicate PO copies it; `convert/index.ts` carries it. Two paths in the original six don't apply as written: `planning.update.tsx` writes no tax at all, and there is no `digital-quote.$id.tsx` route (the portal path is `share+/quote.$id.tsx`) |
+| 6 | ✅ | `format.ts` + `format.test.ts` |
+| 7 | ⚠️ | **3 of 4 forms.** `SupplierQuoteLinePricing` keeps a hand-rolled percent/amount pair instead of the component |
+| 8 | ✅ | price/percent/quantity hooks present |
+| 9 | ✅ | 0 refs of `round4` or `*10000/10000`; `post-receipt`/`post-shipment`/`post-sales-invoice`/`post-purchase-invoice` carry 38/20/33/58 explicit `round()` calls |
+| 10 | ✅ | only geometry `1e-6` remains (inspection-overlay clamps — correctly excluded, same reasoning as `packages/viewer`) |
+| 11 | ✅ | 0 `toFixed` in `lib/methods.ts` and `update-exchange-rates.ts` |
+| 12 | ✅ | 0 hardcoded `new Intl.NumberFormat("en-US"` outside a test that pins a locale deliberately |
+| 13 | 🟡 | PDF done (0 `taxPercent * 100`, 8 `formatPercent` uses). **10 `Math.round` sites in `apps/mes` were never classified display-vs-count** |
+| 14 | ✅ | both drivers registered in `functions/lib/postgres/index.ts` |
+| 15 | ✅ | 3 widening migrations applied; `journalLine.amount` is now bare NUMERIC (confirmed against the DB catalog), so change 9's 5dp is real and not re-rounded |
+| 16 | ✅ | 3 checks + `sources/typescript.ts`; `newViolations()` returns 0 |
+| 17 | ✅ | rule doc + Task Router row |
+| 18 | 🟡 | `xero/serialize.ts` with `xeroMoney`/`xeroUnitAmount`, consumed by 6 files. The answer's first half — *post-payment writes balance/amountDue at the currency's decimals* — could not be confirmed: `balance` is read from a **view** in `post-payment/index.ts`, not written by it |
+
+### Open items
+
+1. **Currency decimals are not reachable client-side.** `decimalPlaces` lives only
+ on the per-company `currency` table; `getCurrenciesList` selects `code, name`
+ only, and there is no currencies store. Consequence today: tax amount fields
+ honour the currency's decimals (via `TaxFields`), but **unit price, shipping
+ and add-on entry fields do not** — a 0-decimal CAD still renders 2 decimals
+ there. Read-only per-unit displays (document summaries, tables) and ~24
+ base-currency cost/rate inputs likewise cap at 2.
+ Three commits attempting this (`3901f4498`, `850b1e211`, `f508e843d`) were
+ **reverted** on 2026-08-12 for diverging from this plan: they hardcoded `?? 2`
+ (forbidden by change 7's rule) and loosened `priceFormatOptions` to make
+ `decimalPlaces` optional, which removed the type-level pressure forcing call
+ sites to supply real currency data. Recovery hash `f508e843d` (reflog).
+ **Decision needed before re-attempting:** expose decimals client-side (add
+ `decimalPlaces` to the currencies read + resolve in `usePriceFormatter`), or
+ flag the sites and leave them.
+2. `withScrap()` unused (change 3) — either route the sites through it or drop
+ the helper; a specified-and-tested-but-uncalled helper is worse than neither.
+3. `SupplierQuoteLinePricing` not on `TaxFields` (change 7).
+4. 10 unclassified `Math.round` sites in `apps/mes` (change 13).
+5. `PaymentForm.tsx` has an editable **Exchange Rate** input with inline
+ `minimumFractionDigits: 2, maximumFractionDigits: 4`. Exchange rates are
+ internal scale-5 values in this standard, so that input truncates a 5-decimal
+ rate on blur — the same class change 11 fixed server-side. Verify whether it
+ is baselined deliberately or was missed by change 12. Its **Total Amount**
+ input formats with the *base* currency while the form has its own Currency
+ field — worth confirming that is intended.
+6. **Final validation not run repo-wide** — scoped typecheck plus utils/checks
+ tests only; `pnpm run test` and `pnpm run build` still outstanding.
+
+## Digit standard (reference)
+
+Display digits equal input digits for every kind. Editable fields MUST use `INPUT_FORMAT` (react-aria's blur commit runs `parse(format(x))` — the input formatter is part of arithmetic).
+
+| Kind | Digits | Notes |
+|---|---|---|
+| Percent / rate | min 0, max 3 | "5%", "6.25%", "6.255%" — trailing zeros never render |
+| Quantity | min 0, max 5 | "3", "4.33333", "0.00125" — no "<0.01" placeholder |
+| Currency (money AND price) | max = `currency.decimalPlaces`; min = the same by default | "$300.00", "$3.50", "$0.00", "¥63", "BHD 0.563" — ONE kind. A price is an amount in the same currency, so both render at that currency's decimals. PADDED by default: the width states the amount in full, which is the accounting convention. The decimals are also a ceiling, so a stored 300.33323 displays "$300.33"; storage keeps the rest. `usePriceFormatter` is an alias of `useCurrencyFormatter`, not a second implementation |
+| ↳ trailing-zero preference | min 0 when set | `companySettings.hideCurrencyTrailingZeros` (default false) drops the non-significant zeros — "$300", "$3.5". DISPLAY and IN-APP only, and it covers EDITABLE fields too: `useCurrencyFormatter` and `MotionMoney` read it once via `useCurrencyMinDecimals`, and `~/components/Form`'s `Number`/`NumberControlled` wrappers (`CurrencyNumber.tsx`) apply it to any `style: "currency"` `formatOptions` — never a call site, which is why the ~80 `INPUT_FORMAT.money/price(...)` calls still pass two arguments. Overriding the MINIMUM is safe on an input even though `formatOptions` is part of the storage round-trip: react-aria commits `parse(format(x))` and only the MAXIMUM can change that. Documents render through the pure `formatMoney` and stay padded — a customer-facing invoice is where fixed-width money matters most — and an unauthenticated context (the public quote share page) has no settings to read, so it pads too |
+| Editable currency (`INPUT_FORMAT.money` / `.price`) | same as above | an input formats with the SAME digits it displays with, padding included — an empty cost reads "$0.00". react-aria's blur commit is literally `setNumberValue(parse(format(x)))`, so this is not decoration — it is what a typed amount is STORED at: 300.22121 commits as 300.22 in USD, 63.4 commits as 63 in JPY. A per-unit price is entered and kept at the currency's decimals |
+
+`currency.decimalPlaces` (DB column) is authoritative over Intl/CLDR defaults. Call sites never pass `minimumFractionDigits`/`maximumFractionDigits` — they pick a named kind; module-local `*_PRECISION` constants are the same violation.
+
+**Two storage scales.** Internal values (per-unit prices, rates, quantities, GL journal lines) carry `SCALE = 5`. Settlement values (invoice balance/amountDue, applied payment amounts, payment totals, document totals) are written at `currency.decimalPlaces` — they never carry 5dp. This is a decided rule, not a preference.
+
+---
+
+## 1. Precision module
+
+**Create** `packages/database/supabase/functions/shared/precision.ts`. Source lives Deno-side because the edge runtime only mounts `supabase/functions/` (same constraint as `sampling-engine.ts`). Dependency-free pure TS (imports nothing — this keeps the node re-export in change 2 safe per the `lib/database.ts` lesson). Exact content:
+
+```ts
+/** Internal precision: prices, rates, quantities, ledger amounts. */
+export const SCALE = 5;
+
+/** One comparison tolerance. 5dp values are multiples of 1e-5; float noise is ~1e-12. */
+export const EPSILON = 1e-6;
+
+export const RoundingMode = {
+ /** Ties away from zero — matches Postgres round(). (Math.round(-2.5) = -2; Postgres = -3.) */
+ HalfUp: "halfUp",
+ /** Away from zero to the next step — scrap allowances. */
+ Up: "up"
+} as const;
+export type RoundingMode = (typeof RoundingMode)[keyof typeof RoundingMode];
+
+/** Exponent-shift: decimal-string round-trip, immune to 1.005-style float artifacts. */
+const shift = (value: number, exp: number): number => {
+ const [m, e = "0"] = value.toExponential().split("e");
+ return Number(`${m}e${Number(e) + exp}`);
+};
+
+export function round(
+ value: number,
+ scale: number = SCALE,
+ mode: RoundingMode = RoundingMode.HalfUp
+): number {
+ if (!Number.isFinite(value)) return value;
+ const fn =
+ mode === RoundingMode.Up
+ ? (n: number) => Math.sign(n) * Math.ceil(Math.abs(n))
+ : (n: number) => Math.sign(n) * Math.round(Math.abs(n));
+ return shift(fn(shift(value, scale)), -scale);
+}
+
+/** Accumulates at full precision, rounds once at the end. */
+export function sum(values: number[], scale: number = SCALE): number {
+ let total = 0;
+ for (const v of values) total += v;
+ return round(total, scale);
+}
+
+export function equals(a: number, b: number): boolean {
+ return Math.abs(a - b) < EPSILON;
+}
+
+/** Scrap allowance rounds up to whole units; the target itself is NEVER rounded.
+ * withScrap(4.5, 0) === 4.5
+ * withScrap(31, 0.31) === 32 */
+export function withScrap(target: number, scrap: number): number {
+ return target + round(scrap, 0, RoundingMode.Up);
+}
+
+/** Tax/discount → settlement amount. `decimals` comes from currency.decimalPlaces — data, never a literal. */
+export function applyRate(base: number, rate: number, decimals: number): number {
+ return round(base * rate, decimals);
+}
+
+/** Ledger invariant. Throws with the drift so posting refuses rather than mis-posts.
+ * `tolerance` is a BUSINESS refusal threshold, distinct from EPSILON (float-noise guard):
+ * multi-currency journals legitimately carry small cross-rate residuals, so posting
+ * paths pass their domain tolerance explicitly (payment/memo: 0.01; manual/close: 0.001).
+ * The default EPSILON is for contexts that must balance exactly. */
+export function assertBalanced(
+ debits: number,
+ credits: number,
+ tolerance: number = EPSILON
+): void {
+ const drift = debits - credits;
+ if (Math.abs(drift) > tolerance) {
+ throw new Error(`Journal does not balance (off by ${round(drift)})`);
+ }
+}
+```
+
+No additional exports. No namespaces — flat API is a locked decision. Rule: a numeric literal as the `scale` argument outside this file is a violation — internal values use the default, settlement passes `currency.decimalPlaces`.
+
+**Verify:** `deno check packages/database/supabase/functions/shared/precision.ts` (delta-gated; the file itself has no imports, so it should be clean)
+
+## 2. Utils façade + tests
+
+**Modify** `packages/utils/src/math.ts`:
+- Delete `roundAmount` (zero consumers — verified).
+- Append `export * from "../../database/supabase/functions/shared/precision.ts";` (same pattern as `packages/database/src/sampling.ts`; safe because precision.ts imports nothing — never let it grow an import of `lib/database.ts`). Keep `clamp`, `twoDecimals` (one consumer: `ConversionFactor.tsx`, sig-fig semantics — leave), `lerp`, `inverseLerp`.
+
+**Create** `packages/utils/src/precision.test.ts` (import from `./math`; vitest config already exists in the package). Required pins:
+
+| Assertion | Guards |
+|---|---|
+| `round(1.005, 2) === 1.01` | exponent-shift vs float artifact |
+| `round(-2.5, 0) === -3` | Postgres tie parity |
+| `round(4.33333333) === 4.33333` | default scale 5 |
+| `withScrap(4.5, 0) === 4.5` | **the consumed-quantity regression** — target never rounded |
+| `withScrap(31, 0.31) === 32` | scrap allowance still ceils |
+| `applyRate(9, 0.0625, 2) === 0.56` | settlement rounding |
+| `applyRate(1000, 0.0625, 0) === 63` | 0-decimal currency |
+| `applyRate(9, 0.0625, 3) === 0.563` | 3-decimal currency |
+| `sum([0.1, 0.2, 0.3], 2) === 0.6` | round once, not per term |
+| `equals(0.1 + 0.2, 0.3)` true; `equals(1.00002, 1.00003)` false | tolerance |
+| `assertBalanced(100, 100.001)` throws; equal args don't | ledger invariant (default EPSILON) |
+| `assertBalanced(100, 100.005, 0.01)` does NOT throw; `assertBalanced(100, 100.02, 0.01)` throws | explicit business tolerance honored |
+
+**Verify:** `pnpm --filter @carbon/utils test && pnpm exec turbo run typecheck --filter=@carbon/utils`
+`grep -rn "roundAmount" apps packages --include="*.ts" --include="*.tsx" | grep -v node_modules` → no output.
+
+## 3. Scrap-ceil fixes
+
+PR #1312 already rewrote part of this area: `totalWithScrap = targetQuantity + scrapQuantity` is now computed WITHOUT a ceil (e.g. `recalculate/index.ts:226`), and the child-quantity ceils are gone. The surviving bug is downstream — **operation and tracked-entity quantities still ceil the whole total**:
+
+- `packages/database/supabase/functions/recalculate/index.ts:260` — `operationQuantity: Math.ceil(totalWithScrap)`
+- `packages/database/supabase/functions/recalculate/index.ts:273` — tracked-entity quantity
+- `packages/database/supabase/functions/get-method/index.ts:627, 1534` — `const operationQuantity = Math.ceil(totalWithScrap)`
+- `packages/database/supabase/functions/get-method/index.ts:5119` — `operationQuantity: Math.ceil(opQuantities.totalWithScrap)`
+
+Fix: where `totalWithScrap` is built from a raw fractional scrap allowance, build it with `withScrap(target, scrap)` (import from `../shared/precision.ts`); the downstream `Math.ceil(totalWithScrap)` then drops so a fractional target (4.5) flows through to operations. Classify `:273` at implementation: if the tracked-entity quantity is a serial/entity COUNT it stays integer (keep the ceil and say so in a comment); if it is a batch quantity it follows the same fix. Sites have drifted once already — re-verify each against current `main` while implementing.
+
+**Consolidation sites — `Math.ceil(qty * scrapPct)` (already correct direction); replace with `round(qty * scrapPct, 0, RoundingMode.Up)`** (import from `@carbon/utils`). Behavior-identical for positive inputs:
+
+- `apps/erp/app/routes/x+/job+/update.tsx:90`
+- `apps/erp/app/routes/x+/production+/planning.update.tsx:229`
+- `apps/erp/app/modules/production/production.service.ts:~239, ~2871`
+- `apps/erp/app/modules/production/ui/Jobs/JobForm.tsx:~183, ~320`
+- `apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineJobs.tsx:~112, ~230`
+
+Do NOT touch (integer-by-nature): `production.service.ts:184` (job count), `bulk.new.tsx:52` (job counts), `ItemReorderPolicy.tsx` (order multiples), `PurchasingPlanningOrderDrawer.tsx:215` (whole-unit purchase UoM), AQL sampling (`shared/sampling-engine.ts`, `quality/samplingStandards.ts`), lead-time/week buckets (`lib/mrp-engine.ts`, `duration-calculator.ts`, `PurchasingPlanningTable.tsx`), pagination/scroll/geometry. (`JobHeader.tsx:1037` is a `Math.floor` half-split — not a ceil site; leave.)
+
+Note: jobs created before this fix keep their inflated integer `estimatedQuantity` until `recalculate` next runs for them (any job quantity edit triggers it). No data migration.
+
+**Verify:** `grep -rn "Math.ceil" packages/database/supabase/functions/recalculate packages/database/supabase/functions/get-method` → no output, except any site proven to be a serial/entity count (comment required); `deno check` both files (delta-gated); `pnpm exec turbo run typecheck --filter=erp`.
+
+## 4. taxPercent flip migration
+
+`pnpm db:migrate:new flip-purchasing-tax-percent-writable` — content:
+
+```sql
+-- Purchasing stored tax AMOUNTS and derived the RATE via a GENERATED column
+-- (rate = amount / subtotal), making the rate a lossy echo of a cents-rounded
+-- amount. DROP EXPRESSION converts each column to plain writable IN PLACE:
+-- values are already materialized -> catalog-only, no backfill, no view drops.
+ALTER TABLE "purchaseOrderLine" ALTER COLUMN "taxPercent" DROP EXPRESSION;
+ALTER TABLE "purchaseOrderLine" ALTER COLUMN "taxPercent" SET DEFAULT 0;
+
+ALTER TABLE "purchaseInvoiceLine" ALTER COLUMN "taxPercent" DROP EXPRESSION;
+ALTER TABLE "purchaseInvoiceLine" ALTER COLUMN "taxPercent" SET DEFAULT 0;
+
+ALTER TABLE "supplierQuoteLinePrice" ALTER COLUMN "taxPercent" DROP EXPRESSION;
+ALTER TABLE "supplierQuoteLinePrice" ALTER COLUMN "taxPercent" SET DEFAULT 0;
+```
+
+Deliberately NOT included (locked decisions): no backfill/UPDATE, no retype to bare NUMERIC (already bare), no CHECK constraint (historical rows may exceed 1; range enforced in validators), no `SET NOT NULL` (columns stay nullable; every reader already does `?? 0`). Current generated definitions being replaced: `20250204164256_numeric-increase-2.sql:1861,1895,1925`. The generated denominator — the canonical subtotal per table — is uniform: `supplierUnitPrice * qty + supplierShippingCost` (qty column is `purchaseQuantity` on PO lines, `quantity` on the other two; shipping added once, not per unit). Forms and derivations must match it.
+
+Known pre-existing hazard (out of scope, chip filed): the Xero EE pull path (`bill.ts:707`, `purchase-order.ts:548`) inserts `taxPercent: null` plus four still-generated columns — it errors today and keeps erroring after the flip.
+
+**Verify (after apply):** the migration runs clean; change 5 confirms the types.
+
+## 5. Types regen + validators + tax value-pair propagation
+
+**The decided rule: `taxPercent` and the tax amount are ONE VALUE PAIR — one relative, one absolute. Any write that sets one must set both.** Forms set both via TaxFields (change 7); every programmatic write path below must too: copy the percent when the source row has one; derive it once (`amount / subtotal`, the old generated formula) when only an amount exists.
+
+1. After the change-4 migration is applied: `pnpm run generate:types`. Never hand-edit generated types. Confirm `taxPercent` is writable for all three tables in `packages/database/src/types.ts` (note: the generator includes generated columns in Insert/Update types, so typecheck proves nothing here — the migration is the gate).
+2. Add to each validator, adjacent to `supplierTaxAmount`:
+
+```ts
+taxPercent: zfd.numeric(z.number().min(0).max(1).optional().default(0)),
+```
+
+- `apps/erp/app/modules/invoicing/invoicing.models.ts` — `purchaseInvoiceLineValidator` (~:104, `supplierTaxAmount` at :130). The form already submits `taxPercent`; zod strips it today for lack of a key.
+- `apps/erp/app/modules/purchasing/purchasing.models.ts` — `purchaseOrderLineValidator` (:205; `supplierTaxAmount` at :235), `selectedLineSchema` (:317) AND `selectedLinesValidator` (:327). The `.default(0)` matters: `sanitize()` turns present-but-`undefined` into NULL on the update path (`.ai/lessons.md`).
+- **There is NO fetcher route or validator for the internal supplier-quote pricing grid** — `SupplierQuoteLinePricing.tsx` `onUpdatePrice` (:85-150) writes straight through the browser Supabase client (update :120-131, insert :137-141). Percent handling there is client-side (change 7). The portal path DOES validate: `api+/purchasing.digital-quote.$id.tsx` (:129-134) via `selectedLineSchema`/`nestedSelectedLinesValidator`, and its server mirror lives in `packages/database/supabase/functions/convert/index.ts:102-113` — amend both together.
+
+3. Services — `upsertPurchaseInvoiceLine` (`invoicing.service.ts:796`), `upsertPurchaseOrderLine` (`purchasing.service.ts:1761`): confirm validated `taxPercent` flows into insert/update. Watch for form-only fields leaking into inserts (PGRST204 class) — only `taxPercent` becomes newly writable.
+
+4. **Amount-carrying write paths that must now also set the percent** (today they'd write percent = 0 next to a real amount, and the form's base-change re-derivation would zero the amount on the next edit):
+
+| Path | Site | Percent source |
+|---|---|---|
+| Duplicate PO | `purchasing.service.ts:143` (select list) → insert :191 | copy `taxPercent` (add to the copied column list) |
+| Supplier quote → PO | `convert/index.ts:1656-1704` (`supplierTaxAmount` at :1689) | copy the break's `taxPercent` (exists after flip) |
+| PO → purchase invoice | `convert/index.ts:404-437` (prorated amount at :421) | copy `line.taxPercent` — proration leaves the rate invariant |
+| MRP planning order | `routes/x+/purchasing+/planning.update.tsx:378-394` | fix the ÷100 scale bug (`supplier.taxPercent` is a 0..1 FRACTION — `(unitPrice * taxPercent) / 100` at :390 is 100× off and ignores qty/shipping); write `taxPercent: supplier.taxPercent ?? 0` and derive the amount from the canonical denominator. Latent today (supplier.taxPercent has no edit UI), so fixing it changes nothing in practice |
+| AI-extracted supplier invoice | `routes/x+/purchase-invoice+/new.tsx:132-165` (whole extracted tax on first line) | derive once: `subtotal > 0 ? lineTax / subtotal : 0` |
+| Supplier portal quote submit | `api+/purchasing.digital-quote.$id.tsx:191-226` (:198, :215) | derive once from the break's amount/subtotal at write |
+
+Benign (verified — no tax amount carried, percent 0/absent is correct): kanban PO lines, fixed-asset purchase, `create` purchaseOrderFromJob, receipt/shipment/invoice posting updates, reorder/short-close/bulk-date routes, seeds.
+
+5. **PO line form reads the stored percent.** `PurchaseOrderLineForm.tsx` currently ignores the DB value and re-derives percent from the amount at mount (`getLineTaxPercent`, :165-170 and :221-226) — reopening a 6.25% line would show 6.22% forever, making the flip a no-op on that screen. Switch both tabs to seed from `initialValues.taxPercent ?? 0` (the route already passes it — `$orderId.$lineId.details.tsx:173`), mirroring `SalesInvoiceLineForm` (:132).
+
+6. Regenerate the MCP tool metadata (`apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json`) after the validator changes so `taxPercent` appears on the upsert tools — find and run its generation script; do not hand-edit.
+
+**Verify:** `pnpm exec turbo run typecheck --filter=erp`; `grep -n "getLineTaxPercent" apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx` → no mount-time derivation remains.
+
+## 6. Formatting layer
+
+**Create** `packages/utils/src/format.ts` + `format.test.ts`; **modify** `packages/utils/src/index.ts` to export it.
+
+```ts
+import { SCALE } from "./math";
+
+/** Settlement money: padded to the currency's decimals — settlement zeros aren't empty. */
+export function moneyFormatOptions(currency: string, decimalPlaces: number): Intl.NumberFormatOptions {
+ return {
+ style: "currency",
+ currency,
+ minimumFractionDigits: decimalPlaces,
+ maximumFractionDigits: decimalPlaces
+ };
+}
+
+/** Per-unit prices (scale 5): distributors quote in thousandths (0.164/ea, 0.00125/g).
+ * min = settlement padding, max = SCALE so the full stored price always renders. */
+export function priceFormatOptions(currency: string, decimalPlaces: number): Intl.NumberFormatOptions {
+ return {
+ style: "currency",
+ currency,
+ minimumFractionDigits: decimalPlaces,
+ maximumFractionDigits: SCALE
+ };
+}
+
+/** Rates (0-1 fractions): 3 percent-digits — a scale-5 fraction round-trips exactly. */
+export function percentFormatOptions(): Intl.NumberFormatOptions {
+ return { style: "percent", minimumFractionDigits: 0, maximumFractionDigits: 3 };
+}
+
+/** Quantities: full storage precision (trailing zeros never render — 3 stays "3"). */
+export function quantityFormatOptions(): Intl.NumberFormatOptions {
+ return { minimumFractionDigits: 0, maximumFractionDigits: SCALE };
+}
+
+/** Editable inputs MUST use these: react-aria's blur commit runs parse(format(x)),
+ * making the input formatter part of the storage round-trip. */
+export const INPUT_FORMAT = {
+ rate: percentFormatOptions(),
+ quantity: quantityFormatOptions(),
+ money: (currency: string, decimalPlaces: number) => moneyFormatOptions(currency, decimalPlaces),
+ price: (currency: string, decimalPlaces: number) => priceFormatOptions(currency, decimalPlaces)
+};
+
+export function formatMoney(value: number, locale: string, currency: string, decimalPlaces: number): string {
+ return new Intl.NumberFormat(locale, moneyFormatOptions(currency, decimalPlaces)).format(value);
+}
+export function formatPrice(value: number, locale: string, currency: string, decimalPlaces: number): string {
+ return new Intl.NumberFormat(locale, priceFormatOptions(currency, decimalPlaces)).format(value);
+}
+export function formatPercent(value: number, locale: string): string {
+ return new Intl.NumberFormat(locale, percentFormatOptions()).format(value);
+}
+export function formatQuantity(value: number, locale: string): string {
+ return new Intl.NumberFormat(locale, quantityFormatOptions()).format(value);
+}
+```
+
+The inline-literal returns are safe for react-aria inputs: `packages/react/src/Number.tsx` stabilizes `formatOptions` by value (`useStableFormatOptions`) — do not add memoization at call sites.
+
+Test pins: `formatPercent(0.0625, "en-US") === "6.25%"`; `formatPercent(0.06255, "en-US") === "6.255%"`; `formatMoney(4.5, "en-US", "USD", 2) === "$4.50"`; `formatPrice(0.164, "en-US", "USD", 2) === "$0.164"`; `formatPrice(4.5, "en-US", "USD", 2) === "$4.50"`; `formatQuantity(4.33333, "en-US") === "4.33333"`; `formatQuantity(3, "en-US") === "3"`; JPY has no fraction; BHD has 3; de-DE uses locale separators.
+
+**Verify:** `pnpm --filter @carbon/utils test`
+
+## 7. TaxFields component + adoption
+
+**Create** `apps/erp/app/components/Form/TaxFields.tsx`; export from `apps/erp/app/components/Form/index.ts`. Markup precedent: the two `NumberControlled` grid cells at `PurchaseInvoiceLineForm.tsx:733-775`.
+
+```ts
+type TaxFieldsProps = {
+ percentName: string; // form field name, e.g. "taxPercent"
+ amountName: string; // e.g. "supplierTaxAmount"
+ subtotal: number; // caller computes: unitPrice * qty + shippingCost (the SQL denominator)
+ currency: string;
+ currencyDecimals: number; // currency.decimalPlaces
+ percent: number;
+ amount: number;
+ onChange: (next: { percent: number; amount: number }) => void;
+};
+```
+
+Dataflow (the entire point of the component — the pair is coupled BOTH ways, so
+whatever is stored is internally consistent):
+- **Percent edited** → `onChange({ percent: v, amount: applyRate(subtotal, v, currencyDecimals) })`
+- **Amount edited** → `onChange({ percent: subtotal > 0 ? round(v / subtotal) : percent, amount: v })`. The derived rate is rounded to internal scale so the stored value is exactly what the percent input renders.
+- Precision only flows cleanly one way: a rate carries more decimals than a settlement amount, so a rate derived back from an amount is limited by that amount's scale (0.56 on a 9.00 subtotal is 6.222%, not the 6.25% that produced it). That is inherent, and is NOT the old 6.25% → 6.22% corruption — that came from deriving the amount UNROUNDED, so the money input re-committed a changed value on blur and fed it back through the coupling. Deriving the amount through `applyRate` makes blur commit an identical value, which triggers nothing.
+- Percent input: `formatOptions={INPUT_FORMAT.rate}`, `minValue={0} maxValue={1}`, `step` from `INPUT_STEP.rate` (a step coarser than the field's scale SNAPS the committed value — `0.0001` truncated a typed 6.255% to 6.25%). Amount input: `formatOptions={INPUT_FORMAT.money(currency, currencyDecimals)}`, `minValue={0}`.
+- Base-change re-derivation (qty/price/shipping edits recompute amount from percent) remains the caller's `useEffect` — component is controlled/stateless. Labels via `useLingui` macro.
+
+**Adopt** (replace each hand-rolled percent/amount pair; keep each form's field names via props):
+
+| Form | Sites |
+|---|---|
+| `invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx` | item pair :733-775 AND indirect (G/L + Fixed-Asset) pair :968-1011 |
+| `purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx` | item pair :850-894 AND indirect pair :1100-1145 (plus the change-5 seed fix) |
+| `invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsx` | item pair :691-733; base-change `useEffect` (:135-149) uses `applyRate`; asset-tab percent-only field (:876-893) just gets `INPUT_FORMAT.rate` |
+| `purchasing/ui/SupplierQuote/SupplierQuoteLinePricing.tsx` | **new percent ROW in the pricing grid** (per quantity break, beside the Tax Amount row :299-317). No validator exists — the grid writes client-side (`onUpdatePrice`); wire percent edits to write BOTH cells (value-pair rule): percent edit → `{ taxPercent, supplierTaxAmount: applyRate(breakSubtotal, v, decimals) }`; amount edit → keep stored percent |
+
+**`currencyDecimals` needs a new read in all four routes** — no line-form loader loads a currency row today (only code strings; `decimalPlaces` is consumed in exactly one place app-wide, the exchange-rates admin). Add it via `getCurrencyByCode` (`accounting.service.ts:1693`) in each route loader, or extend the parent document loaders that already load `currencyCode`. Do not hardcode 2.
+
+**Verify:** `pnpm exec turbo run typecheck --filter=erp`; `grep -rn "value / subtotal" apps/erp/app/modules --include="*.tsx"` → no output.
+
+## 8. Formatter hooks + input-format sweep
+
+- **Create** `apps/erp/app/hooks/usePriceFormatter.tsx` — thin wrapper over `priceFormatOptions`, same locale/currency resolution as `useCurrencyFormatter` (none exists today anywhere). Unit-price displays use this, never `useCurrencyFormatter({ maximumFractionDigits: ... })`.
+- `usePercentFormatter.tsx` → options from `percentFormatOptions()` (2 → 3 digits, intended).
+- `useQuantityFormatter.tsx` → options from `quantityFormatOptions()` (2 → 5 digits, intended). Delete the `"<0.01"` branch in `formatQuantityForDisplay` — unreachable at 5 digits (a scale-5 quantity below 0.01 renders itself, "0.00125"). Update `useQuantityFormatter.test.ts` (it tests the pure function — keep that pattern).
+- `useCurrencyFormatter.tsx` → build from `moneyFormatOptions(...)` where decimals are reachable; keep the JSON-stringify memo keying (load-bearing — see comment in the file). Where `decimalPlaces` isn't reachable, Intl's currency default remains the fallback.
+- MES has NO formatter hooks and imports nothing from ERP — its money/percent sites are handled per-site in changes 12/13.
+- Sweep editable percent inputs still at `maximumFractionDigits: 2` → `INPUT_FORMAT.rate`; editable quantity inputs with digit caps → `INPUT_FORMAT.quantity`:
+ `grep -rn 'style: "percent"' apps/erp/app apps/mes/app --include="*.tsx"` and check each for a digit cap + editability.
+
+**Verify:** `pnpm exec turbo run typecheck --filter=erp --filter=mes`
+
+## 9. 5dp GL posting + settlement decimals
+
+**Two decided scales, applied per write target:**
+- **GL journal lines (internal): `round(x)` at default scale 5.** Requires migration 15a applied first.
+- **Settlement values (invoice balance/amountDue updates, applied amounts, payment totals): `round(x, currency.decimalPlaces)`.** These NEVER carry 5dp. Invoice paid-status dust forgiveness (`INVOICE_DUST_THRESHOLD = 0.01`, `invoicing.models.ts:456`) and the post-payment `0.0001` unapplied-dust band (tested: "sub-dust unapplied emits no on-account line") are deliberate business behavior — preserve both exactly.
+
+Work:
+
+- `post-payment/build-payment-journal.ts` — delete `round4` (:59), import `{ round, assertBalanced }` from `../shared/precision.ts`, replace uses (:172, :196, :213, :234, :262, :278, :304): journal-line amounts → `round(x)`; settlement-facing values → currency decimals. The refusal check (:302-306) becomes `assertBalanced(debits, credits, 0.01)` — **the existing `BALANCE_TOLERANCE = 0.01` (:106) is kept, NOT tightened to EPSILON.** Refusal tolerances are business thresholds (multi-currency journals legitimately accumulate sub-cent cross-rate residuals); tightening would make payments that post today start failing.
+- `post-memo/build-memo-journal.ts` — same (`round4` def :29, uses :115, tolerance :92, predicate :166-169).
+- `post-payment/index.ts` — import (:14), uses (:286, :709). `:709`'s `+ 0.0001` is the unapplied-dust band — keep the value and semantics (it may reference a named constant, but do not change behavior).
+- The manual-journal and period-close checks (`accounting.service.ts:4599, :2515-2518`) keep their `0.001` if touched. **Do not silently unify 0.01 and 0.001 — they differ deliberately** (FX-accumulating vs user-entered journals).
+- **The other ten posting functions write RAW unrounded float amounts today** — the `NUMERIC(19,4)` column has been their only rounding. Once 15a widens the columns, every journal/ledger amount write in `post-receipt`, `post-shipment`, `post-purchase-invoice`, `post-sales-invoice`, `post-inventory-adjustment`, `post-inventory-count`, `post-stock-transfer`, `post-picking`, `post-production-event`, `close-job`, and `shared/post-adjustment.ts` gets wrapped in `round(x)` (5dp). Mechanical; preserve each function's arithmetic otherwise.
+- `post-payment/post-payment.test.ts` (local `round4` :79; literals at :745, :803): update helper + recompute expected values, don't hand-tweak.
+- App: `PaymentApplyTable.tsx:78` and `AvailableCreditsTable.tsx:67` (local `round4` defs + call sites) — applied amounts are settlement values → currency decimals (flag if decimals aren't reachable in the route; add the read, don't hardcode). `invoicing.service.ts:1654` (base-currency credit) → settlement at base-currency decimals. `accounting.service.ts:464` and `:3934` (inline `*10000/10000`, consolidation/translation — GL values) → `round(x)` from `@carbon/utils`.
+
+**Verify:** `grep -rn "round4\|10000) / 10000" apps packages --include="*.ts" --include="*.tsx" | grep -v node_modules` → no output.
+
+## 10. Epsilons → equals
+
+Replace hand-rolled `1e-6` comparisons with `equals`/`!equals`/`EPSILON` from `@carbon/utils`, preserving each site's boundary semantics exactly (`<` vs `<=`, signed vs abs):
+
+- `packages/utils/src/receiving.ts:52` (`total > ordered + 1e-6`)
+- `apps/erp/app/modules/quality/quality-disposition.server.ts:483, 485, 494, 526, 681, 905`
+- `apps/erp/app/modules/quality/ui/Issue/AssociatedItemsList.tsx:209` (quality module, not items)
+- `apps/erp/app/modules/inventory/ui/Traceability/utils.ts:160` — named `QTY_EPSILON = 1e-6` with SIGNED comparisons (:191, :198, :227, :243): import `EPSILON` and keep the signed forms verbatim.
+
+Leave untouched: `packages/viewer` (geometry), inspection-document geometry guards, `VARIANCE_EPSILON = 0.005` (valuation/AR-AP workbenches) and `TIE_OUT_EPSILON = 0.01` (dashboard) — those are business variance thresholds, not float guards.
+
+**Verify:** `grep -rn "1e-6" apps/erp/app apps/mes/app packages/utils packages/jobs --include="*.ts" --include="*.tsx" | grep -v node_modules | grep -v test | grep -v precision` → no output.
+
+## 11. toFixed-as-arithmetic
+
+- `packages/database/supabase/functions/lib/methods.ts:802`: `Number(unitPrice.toFixed(precision))` → `round(unitPrice, precision)` (import from `../shared/precision.ts`; `precision` is the per-quote-line `unitPricePrecision ?? 2` column — data, so no literal-scale violation).
+- `packages/jobs/src/inngest/functions/scheduled/update-exchange-rates.ts:199-202` — **live bug, twice over**: the rate is rounded to `currency.decimalPlaces` (a 0-decimal currency's rate loses its whole fraction; any rate < 0.005 rounds to 0), and the truthiness `.filter((c) => c.exchangeRate)` (:206) then silently DROPS the zeroed rate, freezing that currency forever. Replace with `round(rate)` at default scale 5 (`@carbon/utils`); keep the falsy filter for genuinely missing rates. Target column `currency.exchangeRate` is `NUMERIC(20,8)` — no migration needed. First post-deploy nightly run will update previously-frozen currencies (expected).
+
+**Verify:** `pnpm exec turbo run typecheck --filter=@carbon/jobs`; `deno check packages/database/supabase/functions/lib/methods.ts` (delta-gated)
+
+## 12. Formatter sweep: raw Intl.NumberFormat + inline fraction digits
+
+`grep -rln "new Intl.NumberFormat" apps/erp/app apps/mes/app --include="*.ts" --include="*.tsx"` — 17 files / 23 real constructions on current main.
+
+- **Locale bugs (fix first)** — hardcoded `"en-US"`: `IntercompanyTransactionTable.tsx:60`, `IntercompanyBalanceMatrix.tsx:46`, `QuoteLinePricingHistory.tsx:168,263`, **`items/ui/Item/SupplierPartForm.tsx:322`** (PurchaseHistory). Also `apps/mes/app/routes/display+/$workCenterId.maintenance.tsx:174` passes `undefined` locale (browser default) — use the app locale (MES wraps `I18nProvider` at `root.tsx:263`). Replace with the hooks / `useLocale()`-driven formatters (pattern: `PivotTree.tsx:127`).
+- Components → hooks; non-component code → pure `formatMoney/formatPrice/formatPercent/formatQuantity`.
+- String-built money like `` `$${x.toFixed(2)}` `` (`maintenance/$dispatchId.items.tsx:108,114`) → formatter (also removes the hardcoded `$`).
+- **Supplier-part price UI (the re-do of #1370's reverted hunks, via the price kind — no constant):** `SupplierPartForm.tsx` main unitPrice input → `INPUT_FORMAT.price(...)`; PurchaseHistory display → `usePriceFormatter`; PriceBreaks `EditableNumber` formatOptions → price kind; `SupplierParts/SupplierParts.tsx` grid formatter → `usePriceFormatter`; `PurchasingPlanningOrderDrawer.tsx:105` formatter → `usePriceFormatter`. (`SUPPLIER_PART_PRICE_PRECISION` never landed — there is nothing to delete.)
+- **Inline fraction-digit options**: `grep -rn "maximumFractionDigits\|minimumFractionDigits" apps/erp/app apps/mes/app --include="*.tsx" --include="*.ts"` — every hit outside the formatter hooks migrates to a named kind. Unit-price columns elsewhere (supplier quote pricing, PO line price displays) use the price kind too.
+- Every file is migrated or explicitly baselined in change 16 — none skipped silently.
+
+**Verify:** `grep -rn 'new Intl.NumberFormat("en-US"' apps --include="*.tsx" --include="*.ts"` → no output; `pnpm exec turbo run typecheck --filter=erp --filter=mes && pnpm run lint`.
+
+## 13. PDF percent + MES quantity displays
+
+- PDF: `(taxPercent * 100).toFixed(2) + "%"` → `formatPercent(taxPercent, locale)`:
+ `packages/documents/src/pdf/blocks/LineItemsBlock.tsx:125`, `blocks/salesOrder/LineItemsBlock.tsx:125`, `blocks/quote/LineItemsBlock.tsx:198`, `packages/documents/src/utils/shared.ts:81` (`formatTaxPercent`, consumed by the purchaseOrder block). Locale threading differs per block: the quote block already receives `locale`; the invoice and salesOrder blocks receive only a pre-built `numberFormatter` — thread `locale` from the same construction site that builds it; `formatTaxPercent` gains a locale parameter.
+- MES `Math.round(<quantity>)` cluster — classify per site:
+ - `apps/mes/app/utils/units.ts:35` — tracked-entity/serial COUNT, integer by nature: keep (baseline in change 16).
+ - `AssemblyView.tsx:826`, `assembly.$operationId.tsx:160` — operation-quantity → unit COUNT (`Math.max(1, ...)`): keep integer for the unit axis.
+ - `AssemblyView.tsx:840`, `InspectionView.tsx:583`, `assembly.$operationId.tsx:178` — `quantityComplete` rounded to INDEX the unit array / progress: the index math stays integer (material-issue attribution keys off it — see the comment at `assembly.$operationId.tsx:171-176`), but any DISPLAYED quantity uses `formatQuantity`. Split expressions that mix both.
+
+**Verify:** `pnpm exec turbo run typecheck --filter=@carbon/documents --filter=mes`
+
+## 14. NUMERIC type parser
+
+Reality of `lib/postgres/index.ts`: `import { Pool } from "pg"` resolves to **deno-postgres under Deno** (the `deno.json` import map pins `"pg": "jsr:@db/[email protected]"`) and **npm `pg` 8.x under Node** — one file, two drivers. `setTypeParser` is an npm-pg API and does not exist on deno-postgres.
+
+- **Node branch**: register once beside the pool construction — `import { types } from "pg"; types.setTypeParser(1700, (v: string) => Number(v));` guarded to the node path. This single registration covers every node Kysely consumer (jobs, ERP server) — they all reach pools through this file via `packages/database/src/client.ts`.
+- **Deno branch**: deno-postgres 0.19.x exposes `controls.decoders` instead, keyed by OID — register `1700: (value: string) => Number(value)` there so NUMERIC decodes to a JS number and Deno matches Node. The decoder only fits the ClientOptions **object** form of the connection config, not the URI-string form, so the connection URL is parsed by hand at that site (sslmode mapping mirrors the driver's own). Both branches decoding means edge functions no longer receive NUMERIC as strings.
+- Existing ad-hoc `Number(...)` coercions in edge functions stay — they are harmless no-ops once both decoders are registered. `float8` columns still arrive as strings; only OID 1700 is covered.
+- Script `pg.Client` sites (`packages/checks/src/scripts/*`, `packages/dev/src/services/migrations.ts`) are read-only tooling — leave.
+
+PostgREST/supabase-js reads are unaffected (already deserialize NUMERIC as JSON numbers).
+
+**Verify:** `pnpm exec turbo run typecheck --filter=@carbon/database`; `grep -rn "setTypeParser" packages --include="*.ts" | grep -v node_modules` → the node-branch hit; `grep -n "decoders" packages/database/supabase/functions/lib/postgres/index.ts` → the Deno-branch OID 1700 decoder.
+
+## 15. Storage-scale widening (audit executed — three migrations)
+
+The format layer cannot save a value the column already rounded (Postgres casts on write) — entry → display → **storage** must all carry the scale. The audit is done; these are the surviving clamps (newest-definition-wins across all 916 migrations). Mechanics that apply throughout: a NUMERIC scale change is a **full table rewrite** under ACCESS EXCLUSIVE — batch all of a table's columns into ONE `ALTER TABLE`; `GENERATED ... STORED` columns can't be `ALTER TYPE`d — drop and re-add them (forking the NEWEST definitions, and rebuild dependent views); array columns use `TYPE NUMERIC[] USING "col"::NUMERIC[]`; never quote old constrained types in comments (conformance text-scan).
+
+### 15a — Ledger + RPC signatures (MUST land before change 9 ships)
+
+`pnpm db:migrate:new widen-ledger-amounts` →
+
+- `journalLine.amount` NUMERIC(19,4) → NUMERIC; `journalLine.quantity` (12,4) → NUMERIC
+- `costLedger.cost`, `costLedger.nominalCost` (19,4); `costLedger.quantity`, `costLedger.remainingQuantity` (12,4) → NUMERIC
+- `itemLedger.quantity` (12,4) → NUMERIC — gotchas: it backs the `itemLedgerSnapshot` matview and sits in the `supabase_realtime` publication; handle both around the rewrite
+- `supplierLedger.amount` (19,4) → NUMERIC
+- `intercompanyTransaction.amount` (19,4) → NUMERIC
+- RPC redeclarations, forking each function's NEWEST definition (grep all migrations, take the last — lesson: forking an older body silently reverts fixes): `trialBalance`, `translateTrialBalance` (NUMERIC(19,4) returns), `getIntercompanyBalance`, `matchIntercompanyTransactions` (19,4), `get_job_operations_by_work_center` (10,2 — never revised unlike its siblings), `get_sales_order_lines_by_customer_id` (NUMERIC(9,2) returns; newest def `20250828115039_portal-steps-use-process-name.sql` — the portal truncates today) → bare NUMERIC.
+
+### 15b — Purchasing cascade
+
+- `purchaseOrderLine`: `conversionFactor` (10,2), `exchangeRate` (10,4), `setupPrice` (9,2). Widening `conversionFactor` requires dropping/re-adding the generated price chain that references it (`unitPrice`, `extendedPrice`, `shippingCost`, `taxAmount`, `supplierExtendedPrice` — fork from `20250807094441`, the newest) and rebuilding the dependent views. `taxPercent` is plain after change 4 — untouched by the cascade.
+- `purchaseInvoiceLine`: `conversionFactor` (10,2), `exchangeRate` (10,4) + the same generated-chain mechanics (incl. `totalAmount`).
+- `purchaseInvoice` header: `subtotal`/`totalDiscount`/`totalAmount`/`totalTax`/`balance` (10,2 — also a magnitude cap), `exchangeRate` (10,4).
+- `purchaseInvoicePriceChange`: previous/new price + quantity (10,2).
+- `receiptLine`: `conversionFactor` (10,2); `unitPrice`, `orderQuantity`, `outstandingQuantity`, `receivedQuantity` (18,4).
+- `supplierPart.unitPrice` (10,2 — the #1370 re-do; the `20260129150000` `ADD COLUMN IF NOT EXISTS` was a no-op on existing databases); `supplierPartPrice.quantity` (20,2 — PK member, index rebuild) and `unitPrice` (15,5 → bare for consistency).
+- `supplierQuote.exchangeRate`, `supplierQuoteLinePrice.exchangeRate` (10,4); `supplierQuoteLine.quantity` NUMERIC(20,2)[] (array); `purchasingRfqLine.quantity` (20,2)[].
+- `supplierProcess.unitCost`, `minimumCost` (10,4); `purchaseOrder.exchangeRate` (10,4).
+
+### 15c — Sales, production, master-data tail
+
+- Document FX snapshots (10,4) → NUMERIC: `salesOrder`, `salesOrderLine`, `quote`, `quoteLinePrice` `exchangeRate` (note `20260410031804_exchange-rate-interceptors.sql` writes header rates into line columns — after widening, header and line agree at full precision); `quoteShipment.shippingCost`, `salesOrderShipment.shippingCost` (10,4).
+- `quoteLine.quantity` (20,2)[] (elements key `quoteLinePrice`'s PK), `salesRfqLine.quantity` (20,2)[]; `quoteLinePrice` `discountPercent`/`markupPercent`/`unitCost`/`leadTime`/`extendedPrice` (10,5 — `extendedPrice` also a magnitude cap); `pricingRule.minQuantity`/`maxQuantity` (20,2); `customerItemPriceOverrideBreak.quantity` (20,2 — in a DEFERRABLE unique constraint; drop/re-add with the same deferrability).
+- Production: `job` quantity columns (10,4, incl. generated `productionQuantity`), `jobMaterial.productionQuantity` (GEN), `jobMakeMethod.quantityPerParent`, `quoteMakeMethod.quantityPerParent` (10,4), `jobOperation` quantities + rates (10,4 / `quantityReworked` 10,2), `quoteOperation` rates (10,4), `workCenter.machineRate`/`overheadRate` (10,4), `rework.quantity` (10,4), `pickingListLine` (12,4, generated `outstandingQuantity`), `pickingListLineTrackedEntity` (12,4), `nonConformanceItemTrackedEntity.quantity` (12,4).
+- Rate-shaped multipliers: `itemReplenishment.scrapPercentage`, `jobMaterial.itemScrapPercentage`, `jobMakeMethod.itemScrapPercentage` (5,2), `methodOperation.productionStandard`, `quoteOperation.productionStandard` (10,4), `fixedAsset`/`fixedAssetClass` `taxResidualValuePercent`/`bonusDepreciationPercent` + `companySettings.assetTaxRate` (5,2 — the sibling money columns are already bare).
+
+**Deliberately skipped** (not value-bearing at ledger scale): operation duration columns (`setupTime`/`laborTime`/`machineTime` 10,2 — product granularity decision), lead-time day columns, `version` columns (10,2), forecast `confidence` (3,2), AQL (5,3 — ISO ladder), counts/status numerics.
+
+Deploy note: `journalLine`, `itemLedger`, `costLedger`, `jobOperation`, `purchaseOrderLine`, `purchaseInvoiceLine`, `salesOrderLine`, `receiptLine`, `pickingListLine` are large transactional tables — each rewrite holds an exclusive lock; coordinate timing (that is why this is three migrations, riskiest first and reviewable alone).
+
+**Verify:** after apply + `pnpm run generate:types`: portal sales-order lines return full-precision prices; `pnpm exec turbo run typecheck --filter=erp`; `pnpm --filter @carbon/checks test` (no-numeric-precision baseline shrinks, no new hits).
+
+## 16. Conformance checks
+
+In `packages/checks` (precedents: `sources/migrations.ts` loader, `conformance/no-numeric-precision.ts` check shape — `ConformanceCheck` with pure `scan`). Registration reality: `CONFORMANCE_CHECKS` runs over SQL migrations, `SERVER_CHECKS` over server TS via `loadServerFiles` — the two new TS checks apply to client AND server code, so they get their OWN source + array, not a ride on `SERVER_CHECKS` (whose globs/masking exist for server-only rules).
+
+- **Create** `src/sources/typescript.ts`: recursive `.ts`/`.tsx` loader over `apps/erp/app/components`, `apps/erp/app/hooks`, `apps/erp/app/modules`, `apps/erp/app/routes`, `apps/mes/app`, `packages/database/supabase/functions` (exclude `image-resizer`, `logo-resizer`), `packages/ee/src`, `packages/jobs/src`, `packages/documents/src/pdf`, `packages/documents/src/utils`; exclude tests. The `components`/`hooks`/`ee` roots are not optional: `TaxFields.tsx`, the four formatter hooks, and the Xero serializer are the standard's own surface — `no-inline-fraction-digits` even carries per-file exclusions for the hooks, which are dead weight unless that root is scanned. Prove coverage: grep one known-bad file into the scan (lesson: a check is only as good as its source glob).
+- **Create** `src/conformance/no-derived-percent-column.ts` (SQL migrations source, register in `CONFORMANCE_CHECKS`): flag `"...Percent"`/`"...Rate"` columns `GENERATED ALWAYS AS` with `/` in the expression. Baseline the 5 historical migrations (`20241210214820`, `20250109000722`, `20250109034107`, `20250128195311`, `20250204164256`).
+- **Create** `src/conformance/no-raw-rounding.ts` (TS source): flag `Math.round(` / `Math.ceil(` / `Math.floor(` / `.toFixed(` per line. Message points to `@carbon/utils` + the rule doc.
+- **Create** `src/conformance/no-inline-fraction-digits.ts` (TS source): flag `minimumFractionDigits` / `maximumFractionDigits` — exclude `packages/utils/src/format.ts` and the formatter hooks. Message: "Pick a named kind from @carbon/utils format.ts (money/price/percent/quantity, INPUT_FORMAT.*) instead of passing digits."
+- **Snippet discipline:** `keyOf` is `checkId::file::snippet` (line-independent by design). For the TS checks use the TRIMMED FULL LINE as the snippet, not the bare match — a `Math.ceil(` snippet would collapse all of a file's hits into one baseline key and hide new violations in already-baselined files.
+- Register: both TS checks in a new `TS_CHECKS` array + a `scanAll(loadTypescriptFiles(root), TS_CHECKS)` line in `collectFindings`; export from `src/index.ts`. Unit tests for each (inline-literal `scan` calls, per house pattern); the real-scan test needs a raised timeout (see the `run.test.ts` precedent comment).
+- **Regenerate `baseline.json` last** (after changes 3, 9–13 land) via `pnpm --filter @carbon/checks baseline`. Surviving NOT-IN-CLASS sites (order multiples, lot sizes, lead-time/day buckets, sampling tables, time/HH:MM math, MES counts, pagination, label geometry) go in the baseline. Migrated classes must contribute zero entries — a nonzero count is a missed site; fix it, don't baseline it.
+
+**Verify:** `pnpm --filter @carbon/checks test`; fresh-baseline `newViolations()` count is 0.
+
+## 17. Rule doc + AGENTS.md
+
+- **Create** `.claude/rules/numeric-precision.md`: the two-scale table (internal `SCALE = 5`; settlement `currency.decimalPlaces`, DB column authoritative over CLDR), the digit-standard table from this plan, three-boundary rule (round only at persist/display/compare; Postgres computes derived values; intermediates full precision), no-scale-literals rule, no-inline-fraction-digits rule, `INPUT_FORMAT` editable-input rule, the tax value-pair rule ("percentages are stored facts; taxPercent+amount are one pair — any write that sets one sets both; amounts derive via `applyRate`"), external-boundary rule (serialize at the consumer's contract — Xero constants live in the adapter), the Deno/node driver asymmetry from change 14, pointers to the three conformance checks. `paths:` frontmatter covering precision.ts, math.ts, format.ts, the conformance checks, the Xero entity builders.
+- **Modify** root `AGENTS.md`: Task Router row for the rule; one line noting `packages/utils/src/math.ts` re-exports `functions/shared/precision.ts` by design (edge-runtime constraint) — not an import to "fix".
+- Add an `.ai/lessons.md` entry for the react-aria blur-commit formatter trap (`Context → Problem → Rule → Applies to`).
+
+**Verify:** `ls .claude/rules/numeric-precision.md && grep -n "numeric-precision" AGENTS.md` → file exists, router row present.
+
+## 18. Xero boundary rounding
+
+`packages/ee/src/accounting/providers/xero/entities/*` applies NO rounding at serialization — the DB typmods are the only clamp today, and 15a/15b remove several of them. Decided rule: **every amount rounds at serialization** — `currency.decimalPlaces` for totals/payments/balance (`SubTotal`, `TotalTax`, `Total`, `AmountDue`, `AmountPaid`, `LineAmount`, `TaxAmount`), 4dp for `UnitAmount` (Xero's max). Use named constants in the adapter (e.g. `XERO_UNIT_AMOUNT_DECIMALS = 4`) — this is an external contract, so the constants are data of the boundary, not scale literals.
+
+- Sites: `invoice.ts` (:337-345, :391-395), `bill.ts` (:366-377, :407-411), `purchase-order.ts` (:344-352, :373-375), `sales-order.ts` (:189-200, :275-278), `inventory-adjustment.ts` (:200, :214, :221 — the ManualJournal is raw `Math.abs(quantity) * unitCost` today).
+- This also fixes a pre-existing bug: `LineAmount` is sent as raw `quantity * unitPrice`, so float garbage (0.45000000000000007) can go out **today**, before any of our changes.
+- `CurrencyRate` behavior note (not a code change): rates now carry 5dp, so near-1 rates that used to snapshot to exactly 1 (and be omitted) will start being sent explicitly — expected.
+- Out of scope, chips filed: the sales-invoice `TaxAmount` ÷100 scale bug and the pull-path generated-column inserts.
+
+**Verify:** `pnpm exec turbo run typecheck --filter=@carbon/ee` (or the package's actual filter name); unit test the builders' rounding if the package has test infra, else code-review evidence in the PR.
+
+## Final validation
+
+```bash
+pnpm run lint
+pnpm exec turbo run typecheck --filter=erp --filter=mes --filter=@carbon/utils --filter=@carbon/checks --filter=@carbon/documents --filter=@carbon/jobs --filter=@carbon/database
+pnpm run test
+```
+
+Then run the manual checklist: `.ai/plans/2026-08-11-numeric-precision-manual-testing.md`.
+
+Local note: migrations must be applied locally before `pnpm run generate:types`; if `supabase migration up` trips on the known phantom-migration divergence, repair with `supabase migration repair --status applied` (see memory note) — coordinate before touching any shared database.
diff --git a/.claude/rules/numeric-precision.md b/.claude/rules/numeric-precision.md
new file mode 100644
index 0000000000..ccba56fc1b
--- /dev/null
+++ b/.claude/rules/numeric-precision.md
@@ -0,0 +1,172 @@
+paths:
+ - "packages/database/supabase/functions/shared/precision.ts"
+ - "packages/utils/src/math.ts"
+ - "packages/utils/src/format.ts"
+ - "packages/checks/src/conformance/no-derived-percent-column.ts"
+ - "packages/checks/src/conformance/no-raw-rounding.ts"
+ - "packages/checks/src/conformance/no-inline-fraction-digits.ts"
+ - "packages/checks/src/sources/typescript.ts"
+ - "packages/form/src/components/Number.tsx"
+ - "packages/ee/src/accounting/providers/xero/serialize.ts"
+ - "apps/erp/app/components/Form/TaxFields.tsx"
+ - "apps/erp/app/hooks/usePriceFormatter.tsx"
+
+# Numeric Precision & Formatting
+
+The numeric standard for every price, rate, quantity, and amount in Carbon.
+Source of truth: `packages/database/supabase/functions/shared/precision.ts`
+(Deno-side because the edge runtime only mounts `supabase/functions/`;
+`packages/utils/src/math.ts` re-exports it for Node/browser — that relative
+import is BY DESIGN, not an import to "fix").
+
+## Two storage scales
+
+| Class | Scale | Examples |
+|---|---|---|
+| Internal values | `SCALE = 5` | per-unit prices, rates (0–1 fractions), quantities, GL journal lines, exchange rates |
+| Settlement values | `currency.decimalPlaces` (DB column — authoritative over Intl/CLDR) | invoice balance/amountDue, applied payment amounts, document totals, tax amounts |
+
+Settlement values are rounded to the currency's decimals at the boundary that
+produces them — the applied amounts a user enters, and every amount serialized
+to an external system. The columns themselves are bare NUMERIC and an invoice
+`balance` is read from a view rather than written by `post-payment`, so storage
+does not enforce this; the rounding does. Only internal GL journal lines carry
+scale 5. Invoice paid-status dust forgiveness (`INVOICE_DUST_THRESHOLD = 0.01`,
+`invoicing.models.ts`) and post-payment's `0.0001` unapplied-dust band are
+deliberate business behavior layered on top.
+
+## Three-boundary rule
+
+Round only at **persist**, **display**, and **compare**. Intermediates stay at
+full float precision; Postgres computes derived values (generated columns);
+`sum()` accumulates first and rounds once.
+
+## The API (flat, no namespaces)
+
+- `round(value, scale = SCALE, mode = HalfUp)` — exponent-shift rounding
+ (`round(1.005, 2) === 1.01`), ties away from zero to match Postgres.
+- `scrapAllowance(target, rate)` — the extra WHOLE units to cover scrap; the
+ fractional target itself is never rounded, and callers add the two
+ (`4.5 + scrapAllowance(4.5, 0) === 4.5`; `31 + scrapAllowance(31, 0.01) === 32`).
+- `applyRate(base, rate, decimals)` — tax/discount → settlement amount;
+ `decimals` comes from `currency.decimalPlaces` — data, never a literal.
+- `deriveRate(amount, subtotal)` — the inverse of `applyRate`: recover the rate
+ an absolute amount implies, rounded to internal scale. The ONE place a rate is
+ derived from an amount; a bare `amount / subtotal` at a call site is a bug.
+- `equals(a, b)` / `EPSILON = 1e-6` — the one float-noise tolerance.
+- `assertBalanced(debits, credits, tolerance = EPSILON, label = "Journal")` —
+ ledger invariant. Pass a `label` so the refusal names the journal and its
+ currency (`"Payment journal (base currency)"`).
+ `tolerance` is a BUSINESS refusal threshold: payment/memo posting passes
+ `0.01`, manual journals and period close use `0.001`. Do not unify them and
+ do not tighten to EPSILON — FX journals carry genuine sub-cent residuals.
+
+**No scale literals**: a numeric literal as the `scale` argument outside
+`precision.ts` is a violation — internal values use the default, settlement
+passes `currency.decimalPlaces`. (Whole-unit ceils use `round(x, 0, Up)`;
+external boundaries like Xero use the adapter's named contract constants in
+`packages/ee/src/accounting/providers/xero/serialize.ts`.)
+
+## Percentages are stored facts
+
+`taxPercent` and its amount are ONE VALUE PAIR — one relative, one absolute.
+**Any write that sets one must set both**: copy the percent when the source
+row has one (duplicate, convert); derive it once (`amount / subtotal`, the
+canonical denominator `unitPrice × qty + shippingCost`) when only an amount
+exists (AI extraction, supplier portal). Never a GENERATED column that divides
+(`no-derived-percent-column`) — the old derived echo turned a typed 6.25% into
+6.22% via the cents-rounded amount.
+
+In the UI the pair is coupled BOTH ways (`TaxFields`), so what is stored is
+always internally consistent: a percent edit derives the amount via
+`applyRate` at `currency.decimalPlaces`; an amount edit derives the rate via
+`round(amount / subtotal)` at internal scale; a base change (qty, price,
+shipping) re-derives the amount from the rate. Precision only flows cleanly
+one way — a rate carries more decimals than a settlement amount, so a rate
+derived back from an amount is limited by that amount's scale (0.56 on a 9.00
+subtotal is 6.222%, not 6.25%). That is inherent, and distinct from the old
+corruption, which came from deriving the amount UNROUNDED so the money input
+re-committed a changed value on blur. Derive the amount through `applyRate`
+and blur commits an identical value, triggering nothing.
+
+`useDerivedTaxAmount` (exported from `TaxFields`) owns the base-change
+re-derivation and deliberately skips its first run — a saved line's stored
+pair is displayed as stored rather than silently recomputed on mount.
+
+Build the denominator with `taxableBase(unitPrice, quantity, shippingCost)`
+(also from `TaxFields`), never inline arithmetic. An EMPTIED number input
+commits **NaN**, not 0 — that is react-aria's empty state
+(`if (!newInputValue.length) setNumberValue(NaN)`) — and one NaN term makes
+the whole sum NaN, so `applyRate` returns NaN, the amount field renders blank,
+and saving writes 0 against a live 6.25% percent. The pair is broken and the
+tax silently vanishes. `taxableBase` reads each term as 0 BEFORE the sum, which
+is the only place it can be done: once the terms are added, no downstream guard
+can recover them. `useDerivedTaxAmount` additionally refuses a non-finite
+subtotal, so "never overwrite a stored amount with NaN" holds by construction.
+
+## Display digits = input digits (named kinds)
+
+`packages/utils/src/format.ts` defines the ONLY digit choices (`PERCENT_DIGITS`
+is module-private so the two percent kinds can never drift apart):
+
+| Kind | Digits | Notes |
+|---|---|---|
+| Percent / rate | min 0, max 3 | "5%", "6.25%", "6.255%" |
+| Percent points | min 0, max 3 | the same rate typed bare in a field already labelled "%" — `6.25`, caller divides by 100 |
+| Exchange rate | min 0, max 5 | "1.0852", "0.00781" — a plain multiplier, not a percent and not a currency. Intl's decimal default caps at 3, which truncates a stored rate on blur |
+| Quantity | min 0, max 5 | "3", "4.33333", "0.00125" — no "<0.01" placeholder |
+| Currency (money AND price) | max = `currency.decimalPlaces`; min = the same by default | "$300.00", "$3.50", "$0.00", "¥63", "BHD 0.563" — ONE kind. A price is an amount in the same currency, so both render at that currency's decimals. PADDED by default: the width states the amount in full, which is the accounting convention. The decimals are also a ceiling, so a stored 300.33323 displays "$300.33"; storage keeps the rest. `usePriceFormatter` is an alias of `useCurrencyFormatter`, not a second implementation |
+| ↳ trailing-zero preference | min 0 when set | `companySettings.hideCurrencyTrailingZeros` (default false) drops the non-significant zeros — "$300", "$3.5". DISPLAY and IN-APP only, and it covers EDITABLE fields too: `useCurrencyFormatter` and `MotionMoney` read it once via `useCurrencyMinDecimals`, and `~/components/Form`'s `Number`/`NumberControlled` wrappers (`CurrencyNumber.tsx`) apply it to any `style: "currency"` `formatOptions` — never a call site, which is why the ~80 `INPUT_FORMAT.money/price(...)` calls still pass two arguments. Overriding the MINIMUM is safe on an input even though `formatOptions` is part of the storage round-trip: react-aria commits `parse(format(x))` and only the MAXIMUM can change that. Documents render through the pure `formatMoney` and stay padded — a customer-facing invoice is where fixed-width money matters most — and an unauthenticated context (the public quote share page) has no settings to read, so it pads too |
+| Editable currency (`INPUT_FORMAT.money` / `.price`) | same as above | an input formats with the SAME digits it displays with, padding included — an empty cost reads "$0.00". react-aria's blur commit is literally `setNumberValue(parse(format(x)))`, so this is not decoration — it is what a typed amount is STORED at: 300.22121 commits as 300.22 in USD, 63.4 commits as 63 in JPY. A per-unit price is entered and kept at the currency's decimals |
+
+Call sites pick a kind (`formatMoney/Price/Percent/Quantity`, the
+`useCurrencyFormatter`/`usePriceFormatter`/`usePercentFormatter`/
+`useQuantityFormatter` hooks — the first two are the same function) — never `minimumFractionDigits`/
+`maximumFractionDigits` inline (`no-inline-fraction-digits`), and module-local
+`*_PRECISION` constants are the same violation. **Editable inputs MUST use
+`INPUT_FORMAT.*`**: react-aria's blur commit runs `parse(format(x))`, so the
+input formatter is part of arithmetic. (`packages/react/src/Number.tsx`
+stabilizes `formatOptions` by value, so inline `INPUT_FORMAT.money(c, d)`
+calls are safe.)
+
+**A `step` is arithmetic too** — react-aria SNAPS the committed value to the
+nearest multiple of it, so a step coarser than the field's scale silently
+truncates what the formatter would otherwise display: `step={0.0001}` on a
+rate turned a typed 6.255% into 6.25%, and 12.345% into 12.34%. Take the step
+from `INPUT_STEP.*` (paired with the kinds above — `rate`/`quantity`/
+`exchangeRate` at 1e-5, `money(decimalPlaces)` at the currency's own unit for
+money AND prices) or omit the prop. There is deliberately no finer price step:
+since the commit rounds through the format, a step below the field's own format
+can only produce values the formatter discards.
+A step literal at a call site is a violation for the same reason a digit
+literal is.
+
+## Raw rounding is banned
+
+`Math.round/ceil/floor` and `.toFixed` on value-bearing numbers fail the
+`no-raw-rounding` check — use the API above. Genuinely-integer sites (serial
+counts, pagination, lead-time buckets, AQL ladders, geometry) live in the
+`@carbon/checks` baseline, not in exemption lists.
+
+## Runtime NUMERIC decoding
+
+Both Postgres drivers decode NUMERIC (OID 1700) to JS numbers so runtime
+matches the generated types: node-postgres via `setTypeParser`, deno-postgres
+(v0.19.x, aliased `"pg"` in `functions/deno.json`) via `controls.decoders` —
+both registered in `functions/lib/postgres/index.ts`. Existing `Number(...)`
+coercions are harmless no-ops; float8 columns still arrive as strings.
+
+## Conformance
+
+Three checks in `@carbon/checks` guard the standard: `no-derived-percent-column`
+(SQL migrations), `no-raw-rounding` and `no-inline-fraction-digits` (all app TS
+via `sources/typescript.ts`). That source also covers the shared packages —
+`packages/{utils,form,react,printing,workflows}/src` — because the standard's own
+helpers live in `@carbon/utils` and `form`/`react` own the number inputs whose
+`formatOptions` are part of the storage round-trip. A bare `Number` field with no
+`formatOptions` defaults to the quantity kind (`packages/form/src/components/Number.tsx`).
+
+Fix new hits — baseline only NOT-IN-CLASS sites (calendar buckets, relative-time
+math, file sizes, label/pixel geometry, pagination). Note `no-numeric-precision`
+reads migration TEXT, so a column a widening migration SKIPPED produces no
+finding: the check cannot tell you the live schema is still clamped.
diff --git a/.claude/rules/purchasing-conversion-factors.md b/.claude/rules/purchasing-conversion-factors.md
index ffe73e50ab..7be6aeb1be 100644
--- a/.claude/rules/purchasing-conversion-factors.md
+++ b/.claude/rules/purchasing-conversion-factors.md
@@ -26,9 +26,9 @@ not the base column). Verify against the newest migration before relying on a de
| Table | Column | Type / default | Migration |
|---|---|---|---|
-| `purchaseOrderLine` | `conversionFactor` | `NUMERIC(10,2) DEFAULT 1` | `20240402052512_purchasing-conversion-factors.sql` |
-| `purchaseInvoiceLine` | `conversionFactor` | `NUMERIC(10,2) DEFAULT 1` | `20240402052512_purchasing-conversion-factors.sql` |
-| `receiptLine` | `conversionFactor` | `NUMERIC(10,2) DEFAULT 1` | `20240402052512_purchasing-conversion-factors.sql` |
+| `purchaseOrderLine` | `conversionFactor` | bare `NUMERIC DEFAULT 1` | widened by `20260811123616_widen-purchasing-scale.sql` (was `NUMERIC(10,2)`) |
+| `purchaseInvoiceLine` | `conversionFactor` | bare `NUMERIC DEFAULT 1` | widened by `20260811123616_widen-purchasing-scale.sql` (was `NUMERIC(10,2)`) |
+| `receiptLine` | `conversionFactor` | bare `NUMERIC DEFAULT 1` | widened by `20260811123616_widen-purchasing-scale.sql` (was `NUMERIC(10,2)`) |
| `supplierQuoteLine` | `conversionFactor` | `NUMERIC(10,5) DEFAULT 1`, NOT NULL | `20241202192419_supplier-quotes.sql` |
| `supplierPart` (was `buyMethod`) | `conversionFactor` | `NUMERIC(15,5) DEFAULT 1`, NOT NULL | `20230330024716_parts.sql` |
@@ -91,8 +91,11 @@ divide price by it for inventory unit price (`SupplierQuoteLinePricing.tsx`).
division is applied in **app/edge-function code**, not in those DB columns.
- Exchange-rate direction: `supplierUnitPrice / exchangeRate` (supplier→base
currency), guarded against divide-by-zero.
-- Precision differs by table (`supplierPart` 15,5 vs line tables 10,2) — a
- factor like `10.764` is rounded to 2 dp once it lands on a PO/invoice/receipt line.
+- The line tables used to clamp the factor to 2 dp, so `10.764` silently became
+ `10.76` once it landed on a PO/invoice/receipt line. `20260811123616_widen-purchasing-scale.sql`
+ retyped them to bare `NUMERIC` (along with `supplierPart.unitPrice`, which was
+ clamped to 2 dp and rounded distributor prices like `0.164` on entry), so the
+ factor is now stored exactly as entered. See `.claude/rules/numeric-precision.md`.
## UI component
diff --git a/AGENTS.md b/AGENTS.md
index 743d2733d9..cd4ee099c6 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -108,6 +108,7 @@ IMPORTANT: Before any research or coding, match the task to this table. A single
| **Architecture** | |
| General coding conventions | `.claude/rules/coding-conventions.md` |
| Date & time handling (no JS `Date`) | `.claude/rules/date-handling.md` |
+| Numeric precision & formatting (two scales, named kinds, tax pair) | `.claude/rules/numeric-precision.md` |
| Project overview | `.claude/rules/project-overview.md` |
| Customer/supplier DB schema | `.claude/rules/customer-supplier-database-schema.md` |
| User/employee/job relationships | `.claude/rules/user-employee-job-relationships.md` |
@@ -178,6 +179,7 @@ IMPORTANT: Before any research or coding, match the task to this table. A single
- **Multi-tenancy**: every table has `companyId` + composite PK `("id", "companyId")`
- **IDs**: `id('prefix')` default in SQL
- **Imports**: `~/*` → app code; `@carbon/*` → workspace packages
+- **Precision**: `packages/utils/src/math.ts` re-exports `functions/shared/precision.ts` by design (the edge runtime only mounts `supabase/functions/`) — not an import to "fix"
## ERP Module Layout
diff --git a/apps/erp/app/components/Form/ConversionFactor.tsx b/apps/erp/app/components/Form/ConversionFactor.tsx
index 3e1d68c972..7b99377477 100644
--- a/apps/erp/app/components/Form/ConversionFactor.tsx
+++ b/apps/erp/app/components/Form/ConversionFactor.tsx
@@ -22,7 +22,6 @@ import {
NumberInputStepper,
VStack
} from "@carbon/react";
-import { twoDecimals } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { ElementRef } from "react";
import { forwardRef, useEffect, useMemo, useRef, useState } from "react";
@@ -32,6 +31,7 @@ import {
LuChevronUp,
LuLanguages
} from "react-icons/lu";
+import { useQuantityFormatter } from "~/hooks";
import { useUnitOfMeasure } from "./UnitOfMeasure";
enum ConversionDirection {
@@ -108,6 +108,7 @@ const ConversionFactor = forwardRef<
};
const unitOfMeasureOptions = useUnitOfMeasure();
+ const formatQuantity = useQuantityFormatter();
const description = useMemo(() => {
const purchaseUnit =
@@ -129,7 +130,7 @@ const ConversionFactor = forwardRef<
return (
<>
<span className={cn(Number.isNaN(conversionFactor) && "opacity-0")}>
- {`There ${conversionFactor === 1 ? "is" : "are"} ${twoDecimals(
+ {`There ${conversionFactor === 1 ? "is" : "are"} ${formatQuantity(
conversionFactor
)} ${inventoryUnit.toLocaleLowerCase()} in one `}
<span className="text-primary">
@@ -143,7 +144,7 @@ const ConversionFactor = forwardRef<
return (
<>
<span>
- {`There ${conversionFactor === 1 ? "is" : "are"} ${twoDecimals(
+ {`There ${conversionFactor === 1 ? "is" : "are"} ${formatQuantity(
inverseOfConversion
)} `}
<span className="text-primary">
@@ -156,6 +157,7 @@ const ConversionFactor = forwardRef<
}, [
conversionDirection,
conversionFactor,
+ formatQuantity,
inventoryCode,
purchasingCode,
unitOfMeasureOptions,
@@ -220,7 +222,7 @@ const ConversionFactor = forwardRef<
ref={ref}
onClick={() => setOpen(true)}
>
- {controlValue ? twoDecimals(controlValue) : "-"}
+ {controlValue ? formatQuantity(controlValue) : "-"}
</CommandTrigger>
<ModalContent>
diff --git a/apps/erp/app/components/Form/Currency.tsx b/apps/erp/app/components/Form/Currency.tsx
index a3850087ed..f7dcdd2e0e 100644
--- a/apps/erp/app/components/Form/Currency.tsx
+++ b/apps/erp/app/components/Form/Currency.tsx
@@ -1,10 +1,7 @@
import type { ComboboxProps } from "@carbon/form";
import { Combobox } from "@carbon/form";
-import { useMount } from "@carbon/react";
import { useMemo } from "react";
-import { useFetcher } from "react-router";
-import type { getCurrenciesList } from "~/modules/accounting";
-import { path } from "~/utils/path";
+import { useCurrencies } from "~/hooks/useCurrencies";
type CurrencySelectProps = Omit<ComboboxProps, "options" | "inline"> & {
inline?: boolean;
@@ -37,23 +34,10 @@ Currency.displayName = "Currency";
export default Currency;
const useCurrencyCodes = () => {
- const currencyFetcher =
- useFetcher<Awaited<ReturnType<typeof getCurrenciesList>>>();
-
- useMount(() => {
- currencyFetcher.load(path.to.api.currencies);
- });
-
- const options = useMemo(
- () =>
- currencyFetcher.data?.data
- ? currencyFetcher.data?.data.map((c) => ({
- value: c.code,
- label: c.name
- }))
- : [],
- [currencyFetcher.data]
- );
+ const currencies = useCurrencies();
- return options;
+ return useMemo(
+ () => currencies.map((c) => ({ value: c.code, label: c.name })),
+ [currencies]
+ );
};
diff --git a/apps/erp/app/components/Form/CurrencyNumber.tsx b/apps/erp/app/components/Form/CurrencyNumber.tsx
new file mode 100644
index 0000000000..6b17a9c85a
--- /dev/null
+++ b/apps/erp/app/components/Form/CurrencyNumber.tsx
@@ -0,0 +1,52 @@
+import {
+ Number as BaseNumber,
+ NumberControlled as BaseNumberControlled
+} from "@carbon/form";
+import { withMinimumDecimals } from "@carbon/utils";
+import type { ComponentProps } from "react";
+import { useMemo } from "react";
+import { useCurrencyMinDecimals } from "~/hooks/useCurrencies";
+
+/**
+ * Applies the company's `showCurrencyTrailingZeros` preference to a number
+ * field's `formatOptions`, so an editable amount shows the same digits the
+ * read-only ones beside it do. Any field whose options are not currency-styled
+ * is passed straight through — quantities, rates and exchange rates have their
+ * own kinds and are not part of this preference.
+ *
+ * Doing it here rather than at the ~80 `INPUT_FORMAT.money/price(...)` call
+ * sites keeps the preference in one place, and is why those call sites still
+ * pass two arguments.
+ *
+ * Safe despite `formatOptions` being part of the storage round-trip: react-aria
+ * commits `parse(format(x))`, and only the MAXIMUM can change that. Padding
+ * zeros carry no value, so overriding the MINIMUM cannot alter what is stored —
+ * it changes what the field looks like, never what it saves.
+ */
+function useTrailingZeroPreference(
+ formatOptions: Intl.NumberFormatOptions | undefined
+) {
+ const minDecimals = useCurrencyMinDecimals();
+
+ // Memoized because react-stately keys its NumberFormatter off this object's
+ // identity — returning a fresh one each render rebuilds the formatter on
+ // every keystroke of every money field on the page.
+ return useMemo(() => {
+ if (minDecimals === undefined || formatOptions?.style !== "currency") {
+ return formatOptions;
+ }
+ return withMinimumDecimals(formatOptions, minDecimals);
+ }, [formatOptions, minDecimals]);
+}
+
+export function Number(props: ComponentProps<typeof BaseNumber>) {
+ const formatOptions = useTrailingZeroPreference(props.formatOptions);
+ return <BaseNumber {...props} formatOptions={formatOptions} />;
+}
+
+export function NumberControlled(
+ props: ComponentProps<typeof BaseNumberControlled>
+) {
+ const formatOptions = useTrailingZeroPreference(props.formatOptions);
+ return <BaseNumberControlled {...props} formatOptions={formatOptions} />;
+}
diff --git a/apps/erp/app/components/Form/TaxFields.tsx b/apps/erp/app/components/Form/TaxFields.tsx
new file mode 100644
index 0000000000..abb6612178
--- /dev/null
+++ b/apps/erp/app/components/Form/TaxFields.tsx
@@ -0,0 +1,158 @@
+// The SIBLING, not "@carbon/form" and not the ~/components/Form barrel: the
+// barrel imports this file, so taking it from there would be a cycle, and taking
+// it from @carbon/form would skip the company's trailing-zero preference — which
+// is exactly what left Tax Amount padded while the Shipping field beside it
+// wasn't. Any currency field must come from ./CurrencyNumber.
+
+import type { TaxPair } from "@carbon/utils";
+import {
+ INPUT_FORMAT,
+ INPUT_STEP,
+ taxableBase,
+ taxPairFromAmount,
+ taxPairFromPercent
+} from "@carbon/utils";
+import { useLingui } from "@lingui/react/macro";
+import { useEffect, useRef } from "react";
+import { NumberControlled } from "./CurrencyNumber";
+
+type UseTaxPairArgs = {
+ /** The three terms of the canonical base. Read them off your state — field
+ * names differ per document, so this hook never guesses at keys. */
+ unitPrice: number;
+ quantity: number;
+ shippingCost: number;
+ percent: number;
+ amount: number;
+ currency: string;
+ /** currency.decimalPlaces — data from the route, never a literal */
+ currencyDecimals: number;
+ onChange: (next: TaxPair) => void;
+};
+
+/** What the hook hands to the fields: the pair, the base it was derived
+ * against, and the currency it renders in. The three base TERMS stay with the
+ * caller — only their canonical combination travels. */
+export type TaxPairControl = TaxPair & {
+ subtotal: number;
+ currency: string;
+ currencyDecimals: number;
+ onChange: (next: TaxPair) => void;
+};
+
+/**
+ * Owns one document line's tax pair: the canonical base, and the re-derivation
+ * that keeps the amount honest when that base moves.
+ *
+ * The base is derived during render rather than mirrored into state — it is a
+ * function of values the caller already holds, so storing it could only let the
+ * two drift. The single effect exists for the one thing render cannot express:
+ * re-deriving the AMOUNT when the base changes, while skipping the first run so
+ * a saved line's manual amount override survives being reopened.
+ *
+ * Spread the result straight into <TaxFields>; it carries everything that
+ * component needs except the two form-field names.
+ */
+export function useTaxPair({
+ unitPrice,
+ quantity,
+ shippingCost,
+ percent,
+ amount,
+ currency,
+ currencyDecimals,
+ onChange
+}: UseTaxPairArgs): TaxPairControl {
+ const subtotal = taxableBase(unitPrice, quantity, shippingCost);
+
+ const isMounted = useRef(false);
+ // In a ref so an inline closure doesn't re-fire the effect every render.
+ // React 18 has no useEffectEvent; this is its stand-in.
+ const latestOnChange = useRef(onChange);
+ useEffect(() => {
+ latestOnChange.current = onChange;
+ });
+
+ useEffect(() => {
+ if (!isMounted.current) {
+ isMounted.current = true;
+ return;
+ }
+ // A base this can't evaluate is never a reason to destroy the stored pair:
+ // a NaN amount serializes to "" and saves as 0, leaving a 6.25% line with no
+ // tax. taxableBase already guards each term, so this should not fire — it is
+ // what makes "never write a non-finite amount" true by construction.
+ if (percent !== 0 && Number.isFinite(subtotal)) {
+ latestOnChange.current(
+ taxPairFromPercent(subtotal, percent, currencyDecimals)
+ );
+ }
+ }, [subtotal, percent, currencyDecimals]);
+
+ return {
+ subtotal,
+ percent,
+ amount,
+ currency,
+ currencyDecimals,
+ onChange
+ };
+}
+
+type TaxFieldsProps = TaxPairControl & {
+ /** Form field name for the stored rate, e.g. "taxPercent" */
+ percentName: string;
+ /** Form field name for the stored amount, e.g. "supplierTaxAmount". Kept
+ * independent of the state key — purchase invoices store `taxAmount` but
+ * submit `supplierTaxAmount`. */
+ amountName: string;
+ isReadOnly?: boolean;
+};
+
+/**
+ * The tax value pair: one rate, one absolute amount. Every edit sets both, in
+ * either direction. Controlled and stateless — the base and its re-derivation
+ * belong to useTaxPair.
+ */
+export function TaxFields({
+ percentName,
+ amountName,
+ subtotal,
+ currency,
+ currencyDecimals,
+ percent,
+ amount,
+ isReadOnly,
+ onChange
+}: TaxFieldsProps) {
+ const { t } = useLingui();
+
+ return (
+ <>
+ <NumberControlled
+ name={amountName}
+ label={t`Tax Amount`}
+ value={amount}
+ minValue={0}
+ formatOptions={INPUT_FORMAT.money(currency, currencyDecimals)}
+ isReadOnly={isReadOnly}
+ onChange={(value) =>
+ onChange(taxPairFromAmount(subtotal, value, percent))
+ }
+ />
+ <NumberControlled
+ name={percentName}
+ label={t`Tax Percent`}
+ value={percent}
+ minValue={0}
+ maxValue={1}
+ step={INPUT_STEP.rate}
+ formatOptions={INPUT_FORMAT.rate}
+ isReadOnly={isReadOnly}
+ onChange={(value) =>
+ onChange(taxPairFromPercent(subtotal, value, currencyDecimals))
+ }
+ />
+ </>
+ );
+}
diff --git a/apps/erp/app/components/Form/index.ts b/apps/erp/app/components/Form/index.ts
index 46ad72eb8e..f6b713e233 100644
--- a/apps/erp/app/components/Form/index.ts
+++ b/apps/erp/app/components/Form/index.ts
@@ -13,8 +13,6 @@ import {
Input,
InputControlled,
MultiSelect,
- Number,
- NumberControlled,
Password,
PhoneInput,
Radios,
@@ -35,6 +33,7 @@ import Color from "./Color";
import ConversionFactor from "./ConversionFactor";
import CostCenter from "./CostCenter";
import Currency from "./Currency";
+import { Number, NumberControlled } from "./CurrencyNumber";
import Customer from "./Customer";
import CustomerContact from "./CustomerContact";
import CustomerLocation from "./CustomerLocation";
@@ -82,6 +81,7 @@ import SupplierStatus from "./SupplierStatus";
import Suppliers from "./Suppliers";
import SupplierType from "./SupplierType";
import Tags from "./Tags";
+import { TaxFields, useTaxPair } from "./TaxFields";
import Timezone from "./Timezone";
import Tool from "./Tool";
import UnitHint from "./UnitHint";
@@ -172,6 +172,8 @@ export {
SupplierStatus,
SupplierType,
Tags,
+ TaxFields,
+ useTaxPair,
TextArea,
TimePicker,
Timezone,
diff --git a/apps/erp/app/components/MotionMoney.tsx b/apps/erp/app/components/MotionMoney.tsx
new file mode 100644
index 0000000000..886cda2e0d
--- /dev/null
+++ b/apps/erp/app/components/MotionMoney.tsx
@@ -0,0 +1,49 @@
+import { moneyFormatOptions } from "@carbon/utils";
+import { useLocale } from "@react-aria/i18n";
+import MotionNumber from "motion-number";
+import { useCurrencyMinDecimals } from "~/hooks/useCurrencies";
+
+type MotionMoneyProps = {
+ value: number;
+ currency: string;
+ /** The document currency's configured `currency.decimalPlaces` — resolve it
+ * once per component with `useCurrencyDecimals` and pass it down, rather
+ * than calling that hook per amount (it mounts a fetcher). */
+ decimalPlaces: number;
+ className?: string;
+};
+
+/**
+ * An animated currency amount. Exists so the document summaries name the kind
+ * once instead of each spreading their own options object, and so the currency
+ * and its decimals always travel together.
+ *
+ * MotionNumber narrows `notation` out of `Intl.NumberFormatOptions`, hence the
+ * explicit value.
+ */
+const MotionMoney = ({
+ value,
+ currency,
+ decimalPlaces,
+ className
+}: MotionMoneyProps) => {
+ const { locale } = useLocale();
+ const minDecimals = useCurrencyMinDecimals();
+
+ return (
+ <MotionNumber
+ value={value}
+ format={{
+ ...moneyFormatOptions(decimalPlaces, {
+ currency,
+ minDecimalPlaces: minDecimals
+ }),
+ notation: "standard" as const
+ }}
+ locales={locale}
+ className={className}
+ />
+ );
+};
+
+export default MotionMoney;
diff --git a/apps/erp/app/components/index.ts b/apps/erp/app/components/index.ts
index a8d5a3ec03..6de8d73664 100644
--- a/apps/erp/app/components/index.ts
+++ b/apps/erp/app/components/index.ts
@@ -34,6 +34,7 @@ import ItemThumbnail from "./ItemThumbnail";
import Location from "./Location";
import MetricCard from "./MetricCard";
import { ModelOptimizedIndicator } from "./ModelOptimizedIndicator";
+import MotionMoney from "./MotionMoney";
import New from "./New";
import PeriodSelector from "./PeriodSelector";
import RealtimeDataProvider from "./RealtimeDataProvider";
@@ -74,6 +75,7 @@ export {
MethodItemTypeIcon,
MetricCard,
ModelOptimizedIndicator,
+ MotionMoney,
ModuleIcon,
New,
OperationStatusIcon,
diff --git a/apps/erp/app/hooks/index.ts b/apps/erp/app/hooks/index.ts
index f8badf6c88..a78991445b 100644
--- a/apps/erp/app/hooks/index.ts
+++ b/apps/erp/app/hooks/index.ts
@@ -7,6 +7,11 @@ import {
} from "@carbon/react";
import { useCompanySettings } from "./useCompanySettings";
import { useCompanyTimeZone, useCompanyToday } from "./useCompanyTimeZone";
+import {
+ useCurrencies,
+ useCurrencyDecimals,
+ useCurrencyDecimalsLookup
+} from "./useCurrencies";
import { useCurrencyFormatter } from "./useCurrencyFormatter";
import { useDateFormatter } from "./useDateFormatter";
import { useFlags } from "./useFlags";
@@ -49,6 +54,9 @@ export {
useNotifications,
useOnboarding,
useOptimisticLocation,
+ useCurrencies,
+ useCurrencyDecimals,
+ useCurrencyDecimalsLookup,
usePercentFormatter,
usePermissions,
usePlanGate,
diff --git a/apps/erp/app/hooks/useCompanySettings.tsx b/apps/erp/app/hooks/useCompanySettings.tsx
index 1e7f0cc5bf..f5119a89ca 100644
--- a/apps/erp/app/hooks/useCompanySettings.tsx
+++ b/apps/erp/app/hooks/useCompanySettings.tsx
@@ -4,6 +4,7 @@ import { path } from "~/utils/path";
type CompanySettings = {
showSupplierReadableId?: boolean | null;
showCustomerReadableId?: boolean | null;
+ showCurrencyTrailingZeros?: boolean | null;
} & Record<string, unknown>;
export function useCompanySettings(): CompanySettings | undefined {
diff --git a/apps/erp/app/hooks/useCurrencies.ts b/apps/erp/app/hooks/useCurrencies.ts
new file mode 100644
index 0000000000..1cab1f2310
--- /dev/null
+++ b/apps/erp/app/hooks/useCurrencies.ts
@@ -0,0 +1,77 @@
+import { useMount } from "@carbon/react";
+import { cldrCurrencyDecimals, DEFAULT_CURRENCY_DECIMALS } from "@carbon/utils";
+import { useMemo } from "react";
+import { useFetcher } from "react-router";
+import type { getCurrenciesList } from "~/modules/accounting";
+import { path } from "~/utils/path";
+import { useCompanySettings } from "./useCompanySettings";
+
+/**
+ * The ISO currency list with the company group's configured `decimalPlaces`
+ * riding along (null for a currency the group hasn't set up). Served through
+ * the cached currencies clientLoader, so mounting this in many components
+ * costs one network round-trip per session, not per mount.
+ */
+export function useCurrencies() {
+ const currencyFetcher =
+ useFetcher<Awaited<ReturnType<typeof getCurrenciesList>>>();
+
+ useMount(() => {
+ currencyFetcher.load(path.to.api.currencies);
+ });
+
+ return currencyFetcher.data?.data ?? [];
+}
+
+/**
+ * Resolve settlement decimals for ANY currency code — a stable function, for
+ * the tables whose currency varies per row and so cannot call a hook per value.
+ *
+ * The group's configured `currency.decimalPlaces` row is authoritative; CLDR
+ * decides only when the currency isn't configured or the list is still loading.
+ * One index and one fallback policy, so a per-row table and a single-currency
+ * field can never disagree about how wide an amount is.
+ */
+export function useCurrencyDecimalsLookup(): (
+ currencyCode: string | null | undefined
+) => number {
+ const currencies = useCurrencies();
+
+ return useMemo(() => {
+ // Indexed rather than scanned: this runs inside every money formatter,
+ // which in a table means once per row per render over the full ISO list.
+ const configured = new Map(
+ currencies.flatMap((c) =>
+ c.decimalPlaces == null ? [] : [[c.code, c.decimalPlaces] as const]
+ )
+ );
+ return (currencyCode) =>
+ currencyCode
+ ? (configured.get(currencyCode) ?? cldrCurrencyDecimals(currencyCode))
+ : DEFAULT_CURRENCY_DECIMALS;
+ }, [currencies]);
+}
+
+/** Settlement decimals for one currency — money inputs need a concrete number
+ * for `INPUT_FORMAT.money`, and display formatters want the same answer so an
+ * editable amount and the read-only one beside it agree. */
+export function useCurrencyDecimals(
+ currencyCode: string | null | undefined
+): number {
+ return useCurrencyDecimalsLookup()(currencyCode);
+}
+
+/**
+ * The MINIMUM digits a currency amount displays with — the company's
+ * `showCurrencyTrailingZeros` preference resolved to a number for
+ * `moneyFormatOptions`.
+ *
+ * `undefined` means "pad to the currency's decimals", which is both the default
+ * and what an UNAUTHENTICATED context gets: the public quote share page has no
+ * company settings to read, and a customer-facing document should show money at
+ * full width regardless of an internal display preference.
+ */
+export function useCurrencyMinDecimals(): number | undefined {
+ const settings = useCompanySettings();
+ return settings?.showCurrencyTrailingZeros === false ? 0 : undefined;
+}
diff --git a/apps/erp/app/hooks/useCurrencyFormatter.tsx b/apps/erp/app/hooks/useCurrencyFormatter.tsx
index 3135c3ca5b..47d22cdc68 100644
--- a/apps/erp/app/hooks/useCurrencyFormatter.tsx
+++ b/apps/erp/app/hooks/useCurrencyFormatter.tsx
@@ -1,27 +1,75 @@
+import { moneyFormatOptions } from "@carbon/utils";
import { useLocale } from "@react-aria/i18n";
import { useMemo } from "react";
+import { useCurrencyDecimals, useCurrencyMinDecimals } from "./useCurrencies";
import { useUser } from "./useUser";
-export function useCurrencyFormatter(options?: Intl.NumberFormatOptions) {
+/** Everything a call site is allowed to override, and nothing else.
+ *
+ * The set is deliberately closed rather than the full `Intl.NumberFormatOptions`:
+ * it is what the 71 call sites actually pass, every value is a primitive, and
+ * that is what lets the memo below depend on the fields instead of the object.
+ * Widening it back to `Intl.NumberFormatOptions` reintroduces the identity
+ * problem — add a field here instead. */
+export type CurrencyFormatterOptions = {
+ currency?: string;
+ /** Overrides the configured lookup when the caller already has the row */
+ decimalPlaces?: number;
+ /** "$1.2M" for dashboard tiles, instead of the full amount. */
+ compact?: boolean;
+ /** Drop the fraction entirely — a report that deliberately shows whole units.
+ * Combined with `compact` this is "$1M" rather than "$1.2M". */
+ wholeUnits?: boolean;
+};
+
+/**
+ * Currency display — money and per-unit prices alike, because they are the same
+ * kind. Digits come from `useCurrencyDecimals` — the group's configured
+ * `currency.decimalPlaces` row, or CLDR's own digits for that currency when it
+ * isn't configured.
+ *
+ * By default the amount is PADDED to those decimals, so its width states the
+ * amount in full: "$300.00", "$3.50", "¥63", "BHD 0.563". A company can drop the
+ * non-significant zeros by turning `showCurrencyTrailingZeros` off; that
+ * preference is read here once (useCurrencyMinDecimals) rather than at 55 call sites.
+ *
+ * Callers pick a KIND, never a digit count: `wholeUnits` for a report that shows
+ * whole amounts, `compact` for a "$1.2M" dashboard tile.
+ */
+export function useCurrencyFormatter(options?: CurrencyFormatterOptions) {
const { company } = useUser();
const baseCurrency = company?.baseCurrencyCode ?? "USD";
const { locale } = useLocale();
const currency = options?.currency ?? baseCurrency;
+ const currencyDecimals = useCurrencyDecimals(currency);
+ const minDecimals = useCurrencyMinDecimals();
// Every call site passes an object literal, so depending on `options` by
// identity meant the memo never hit: a new Intl.NumberFormat on every render,
// and — since the formatter is itself a dep of the `columns` memo in several
- // tables — a full column rebuild with it. Depend on the fields instead.
- const optionsKey = options ? JSON.stringify(options) : "";
- const formatter = useMemo(() => {
- const opts = optionsKey
- ? (JSON.parse(optionsKey) as Intl.NumberFormatOptions)
- : undefined;
+ // tables — a full column rebuild with it. Depend on the primitive fields.
+ const { decimalPlaces, compact, wholeUnits } = options ?? {};
+
+ return useMemo(() => {
+ // `wholeUnits` is a digit count of zero, expressed as the intent rather than
+ // the number — this hook names kinds, it does not choose digits.
+ const decimals = wholeUnits ? 0 : (decimalPlaces ?? currencyDecimals);
return new Intl.NumberFormat(locale, {
- style: "currency",
- currency: currency,
- ...opts
+ ...moneyFormatOptions(decimals, {
+ currency,
+ minDecimalPlaces: wholeUnits ? 0 : minDecimals
+ }),
+ ...(compact
+ ? { notation: "compact" as const, compactDisplay: "short" as const }
+ : {})
});
- }, [locale, currency, optionsKey]);
- return formatter;
+ }, [
+ locale,
+ currency,
+ currencyDecimals,
+ minDecimals,
+ decimalPlaces,
+ compact,
+ wholeUnits
+ ]);
}
diff --git a/apps/erp/app/hooks/usePercentFormatter.tsx b/apps/erp/app/hooks/usePercentFormatter.tsx
index 13cb35dd93..c693ba9dd6 100644
--- a/apps/erp/app/hooks/usePercentFormatter.tsx
+++ b/apps/erp/app/hooks/usePercentFormatter.tsx
@@ -1,3 +1,4 @@
+import { PERCENT_FORMAT } from "@carbon/utils";
import { useLocale } from "@react-aria/i18n";
import { useMemo } from "react";
@@ -5,12 +6,7 @@ export function usePercentFormatter() {
const { locale } = useLocale();
const formatter = useMemo(
- () =>
- new Intl.NumberFormat(locale, {
- style: "percent",
-
- maximumFractionDigits: 2
- }),
+ () => new Intl.NumberFormat(locale, PERCENT_FORMAT),
[locale]
);
return formatter;
diff --git a/apps/erp/app/hooks/useQuantityFormatter.test.ts b/apps/erp/app/hooks/useQuantityFormatter.test.ts
index a6131e2a13..c87949c89e 100644
--- a/apps/erp/app/hooks/useQuantityFormatter.test.ts
+++ b/apps/erp/app/hooks/useQuantityFormatter.test.ts
@@ -1,20 +1,17 @@
+import { SCALE_FORMAT } from "@carbon/utils";
import { describe, expect, it } from "vitest";
import { formatQuantityForDisplay } from "./useQuantityFormatter";
-const formatter = new Intl.NumberFormat("en-US", {
- minimumFractionDigits: 0,
- maximumFractionDigits: 2
-});
+const formatter = new Intl.NumberFormat("en-US", SCALE_FORMAT);
const format = (quantity: number) =>
formatQuantityForDisplay(quantity, formatter);
describe("formatQuantityForDisplay", () => {
- it("rounds to two decimals", () => {
- expect(format(3.232227)).toBe("3.23");
- expect(format(1.983918)).toBe("1.98");
- expect(format(0.02008193)).toBe("0.02");
- expect(format(1.005)).toBe("1.01");
+ it("shows full storage precision up to five decimals", () => {
+ expect(format(4.33333)).toBe("4.33333");
+ expect(format(3.232227)).toBe("3.23223");
+ expect(format(1.983918)).toBe("1.98392");
});
it("keeps whole numbers whole", () => {
@@ -24,28 +21,34 @@ describe("formatQuantityForDisplay", () => {
expect(format(3.0)).toBe("3");
});
- it("drops a trailing zero on a single-decimal quantity", () => {
+ it("drops trailing zeros", () => {
expect(format(1.5)).toBe("1.5");
expect(format(2.1)).toBe("2.1");
});
- it("never renders a non-zero quantity as zero", () => {
- expect(format(0.004)).toBe("<0.01");
- expect(format(0.000001)).toBe("<0.01");
- expect(format(0.00999)).toBe("<0.01");
+ it("renders genuinely small quantities exactly, no placeholder", () => {
+ expect(format(0.004)).toBe("0.004");
+ expect(format(0.00125)).toBe("0.00125");
+ expect(format(0.00999)).toBe("0.00999");
});
it("renders a genuine zero as zero", () => {
expect(format(0)).toBe("0");
});
- it("keeps the boundary value exact", () => {
- expect(format(0.01)).toBe("0.01");
+ it("keeps the storage-scale boundary value exact", () => {
+ expect(format(0.00001)).toBe("0.00001");
+ });
+
+ it("never renders a non-zero quantity below the storage scale as zero", () => {
+ expect(format(0.000001)).toBe("<0.00001");
+ expect(format(1e-9)).toBe("<0.00001");
});
- it("handles small negative quantities symmetrically", () => {
- expect(format(-0.004)).toBe(">-0.01");
- expect(format(-2.567)).toBe("-2.57");
+ it("handles negative quantities", () => {
+ expect(format(-2.567)).toBe("-2.567");
+ expect(format(-0.004)).toBe("-0.004");
+ expect(format(-0.000001)).toBe(">-0.00001");
});
it("returns an empty string for non-finite values", () => {
@@ -54,22 +57,17 @@ describe("formatQuantityForDisplay", () => {
});
it("respects the locale of the formatter it is given", () => {
- const de = new Intl.NumberFormat("de-DE", {
- minimumFractionDigits: 0,
- maximumFractionDigits: 2
- });
- expect(formatQuantityForDisplay(3.232227, de)).toBe("3,23");
- expect(formatQuantityForDisplay(0.004, de)).toBe("<0,01");
+ const de = new Intl.NumberFormat("de-DE", SCALE_FORMAT);
+ expect(formatQuantityForDisplay(3.232227, de)).toBe("3,23223");
+ expect(formatQuantityForDisplay(1234.5, de)).toBe("1.234,5");
});
it("uses the locale's own negative sign below the threshold", () => {
// sv-SE renders negatives with U+2212 MINUS SIGN, not an ASCII hyphen.
- const sv = new Intl.NumberFormat("sv-SE", {
- minimumFractionDigits: 0,
- maximumFractionDigits: 2
- });
- expect(formatQuantityForDisplay(-0.004, sv)).toBe(`>${sv.format(-0.01)}`);
- expect(formatQuantityForDisplay(-0.004, sv)).toBe(">−0,01");
- expect(formatQuantityForDisplay(0.004, sv)).toBe("<0,01");
+ const sv = new Intl.NumberFormat("sv-SE", SCALE_FORMAT);
+ expect(formatQuantityForDisplay(-0.000001, sv)).toBe(
+ `>${sv.format(-0.00001)}`
+ );
+ expect(formatQuantityForDisplay(0.000001, sv)).toBe("<0,00001");
});
});
diff --git a/apps/erp/app/hooks/useQuantityFormatter.tsx b/apps/erp/app/hooks/useQuantityFormatter.tsx
index 7f5ea5fd43..67b709a17c 100644
--- a/apps/erp/app/hooks/useQuantityFormatter.tsx
+++ b/apps/erp/app/hooks/useQuantityFormatter.tsx
@@ -1,17 +1,20 @@
+import { SCALE, SCALE_FORMAT } from "@carbon/utils";
import { useLocale } from "@react-aria/i18n";
import { useMemo } from "react";
-const MAXIMUM_FRACTION_DIGITS = 2;
-const SMALLEST_DISPLAYABLE_QUANTITY = 0.01;
+/** Smallest quantity the storage scale can represent. Below it a value is real
+ * but unrenderable, and "0" would be a lie. */
+const SMALLEST_DISPLAYABLE_QUANTITY = 1 / 10 ** SCALE;
/**
- * Formats a quantity for display at two decimals. This is presentation only —
- * the underlying quantity is never rounded, so BOMs, costing, reports, exports
- * and the API keep the exact value.
+ * Formats a quantity for display at full storage precision (up to five
+ * decimals). Presentation only — the underlying quantity is never rounded, so
+ * BOMs, costing, reports, exports and the API keep the exact value.
*
- * - Whole numbers stay whole: `3` renders as "3", not "3.00".
- * - A non-zero quantity too small to render at two decimals shows as "<0.01"
- * rather than a misleading "0".
+ * - Whole numbers stay whole: `3` renders as "3", not "3.00000".
+ * - A stored value renders itself: `0.00125`, not a placeholder.
+ * - A non-zero quantity too small to render at all shows as "<0.00001" rather
+ * than a misleading "0".
*/
export function formatQuantityForDisplay(
quantity: number,
@@ -34,10 +37,7 @@ export function useQuantityFormatter() {
const { locale } = useLocale();
return useMemo(() => {
- const formatter = new Intl.NumberFormat(locale, {
- minimumFractionDigits: 0,
- maximumFractionDigits: MAXIMUM_FRACTION_DIGITS
- });
+ const formatter = new Intl.NumberFormat(locale, SCALE_FORMAT);
return (quantity: number) => formatQuantityForDisplay(quantity, formatter);
}, [locale]);
diff --git a/apps/erp/app/modules/accounting/accounting.service.ts b/apps/erp/app/modules/accounting/accounting.service.ts
index 73a2282faa..8a2f0d13f0 100644
--- a/apps/erp/app/modules/accounting/accounting.service.ts
+++ b/apps/erp/app/modules/accounting/accounting.service.ts
@@ -6,7 +6,9 @@ import {
datetime,
fiscalYearAndPeriodFor,
getDateNYearsAgo,
+ isBalanced,
MONTH_NUMBER,
+ round,
toDisplayCredit,
toDisplayDebit,
toStoredAmount
@@ -460,8 +462,7 @@ function overlayTranslationOnSeries<
// Translated period delta: apply the same per-account rate to netChange
// so flow reads (income statement / executive P&L) get a translated
// activity figure rather than the translated cumulative balance.
- translatedNetChange:
- Math.round(existing.netChange * exchangeRate * 10000) / 10000,
+ translatedNetChange: round(existing.netChange * exchangeRate),
exchangeRate
};
}
@@ -1690,6 +1691,34 @@ export async function getCurrency(
.single();
}
+/**
+ * Settlement decimals for the company's base currency. Fixed-asset and GL
+ * amounts are booked in base currency, so this is the scale their rounding must
+ * use. Falls back to 2 only when the currency row is unreachable.
+ */
+export async function getBaseCurrencyDecimalPlaces(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ companyGroupId: string
+): Promise<number> {
+ const company = await client
+ .from("company")
+ .select("baseCurrencyCode")
+ .eq("id", companyId)
+ .single();
+
+ if (company.error || !company.data?.baseCurrencyCode) return 2;
+
+ const currency = await client
+ .from("currencies")
+ .select("decimalPlaces")
+ .eq("code", company.data.baseCurrencyCode)
+ .eq("companyGroupId", companyGroupId)
+ .single();
+
+ return currency.data?.decimalPlaces ?? 2;
+}
+
export async function getCurrencyByCode(
client: SupabaseClient<Database>,
companyGroupId: string,
@@ -1725,11 +1754,40 @@ export async function getCurrencies(
return query;
}
-export async function getCurrenciesList(client: SupabaseClient<Database>) {
- return client
- .from("currencyCode")
- .select("code, name")
- .order("name", { ascending: true });
+/**
+ * The full ISO currency list for pickers, carrying the company group's
+ * configured `decimalPlaces` where the currency has been set up. Callers that
+ * format or round money need the settlement scale alongside the code — the DB
+ * column is authoritative over Intl/CLDR, so it has to travel with the option.
+ * `decimalPlaces` is null for an ISO currency the group has not configured.
+ */
+export async function getCurrenciesList(
+ client: SupabaseClient<Database>,
+ companyGroupId: string
+) {
+ const [codes, configured] = await Promise.all([
+ client.from("currencyCode").select("code, name").order("name", {
+ ascending: true
+ }),
+ client
+ .from("currencies")
+ .select("code, decimalPlaces")
+ .eq("companyGroupId", companyGroupId)
+ ]);
+
+ if (codes.error) return codes;
+
+ const decimalsByCode = new Map(
+ (configured.data ?? []).map((c) => [c.code, c.decimalPlaces])
+ );
+
+ return {
+ ...codes,
+ data: codes.data.map((c) => ({
+ ...c,
+ decimalPlaces: decimalsByCode.get(c.code) ?? null
+ }))
+ };
}
export async function getCurrentAccountingPeriod(
@@ -2391,6 +2449,12 @@ export type PeriodCloseUnpostedDocument = {
const UNPOSTED_DOCUMENT_LIMIT = 25;
+/** Business refusal threshold for a journal's debits-vs-credits drift — looser
+ * than EPSILON because multi-currency entries carry real cross-rate residuals.
+ * Shared by the manual-JE validator and the period-close checklist so the two
+ * can never disagree about which journals are unbalanced. */
+const JOURNAL_BALANCE_TOLERANCE = 0.001;
+
async function computePeriodReadiness(
client: SupabaseClient<Database>,
companyId: string,
@@ -2514,7 +2578,11 @@ async function computePeriodReadiness(
const unbalanced = (journalsInPeriod.data ?? []).filter(
(j) =>
- Math.abs(Number(j.totalDebits ?? 0) - Number(j.totalCredits ?? 0)) > 0.001
+ !isBalanced(
+ Number(j.totalDebits ?? 0),
+ Number(j.totalCredits ?? 0),
+ JOURNAL_BALANCE_TOLERANCE
+ )
);
const pendingPostings =
@@ -3930,8 +3998,7 @@ export async function translateCompanyBalances(
const exchangeRate = rateFor(account.consolidatedRate);
const localBalance = Number(account.balanceAtDate ?? 0);
- const translatedBalance =
- Math.round(localBalance * exchangeRate * 10000) / 10000;
+ const translatedBalance = round(localBalance * exchangeRate);
rows.push({
accountId: account.id,
@@ -4596,7 +4663,7 @@ export async function postJournalEntry(
totalCredit += toDisplayCredit(Number(l.amount), accountClass);
}
- if (Math.abs(totalDebit - totalCredit) > 0.001) {
+ if (!isBalanced(totalDebit, totalCredit, JOURNAL_BALANCE_TOLERANCE)) {
return {
data: null,
error: { message: "Total debits must equal total credits" }
diff --git a/apps/erp/app/modules/accounting/accounting.utils.test.ts b/apps/erp/app/modules/accounting/accounting.utils.test.ts
index ef996cc34a..0c26471759 100644
--- a/apps/erp/app/modules/accounting/accounting.utils.test.ts
+++ b/apps/erp/app/modules/accounting/accounting.utils.test.ts
@@ -336,7 +336,8 @@ describe("calculateMacrsDepreciation", () => {
periodEnd: "2025-12-31",
lastPostedPeriodEnd: null,
accumulatedTaxDepreciation: 0,
- bonusAmount: 0
+ bonusAmount: 0,
+ decimalPlaces: 2
})
).toBe(0);
});
@@ -350,7 +351,8 @@ describe("calculateMacrsDepreciation", () => {
periodEnd: "2025-12-31",
lastPostedPeriodEnd: null,
accumulatedTaxDepreciation: 0,
- bonusAmount: 0
+ bonusAmount: 0,
+ decimalPlaces: 2
});
// Year 1 at 20% of $100k = $20,000
expect(result).toBe(20000);
@@ -365,7 +367,8 @@ describe("calculateMacrsDepreciation", () => {
periodEnd: "2025-12-31",
lastPostedPeriodEnd: null,
accumulatedTaxDepreciation: 0,
- bonusAmount: 0
+ bonusAmount: 0,
+ decimalPlaces: 2
});
// $468,000 / (39*12) = $1,000/month; 11.5 months for first period
expect(result).toBeCloseTo(11500, -1);
@@ -380,7 +383,8 @@ describe("calculateMacrsDepreciation", () => {
periodEnd: "2025-12-31",
lastPostedPeriodEnd: null,
accumulatedTaxDepreciation: 9500,
- bonusAmount: 0
+ bonusAmount: 0,
+ decimalPlaces: 2
});
expect(result).toBeLessThanOrEqual(500);
});
@@ -406,29 +410,29 @@ describe("calculateDepreciation", () => {
it("calculates monthly depreciation correctly", () => {
// Cost 120k, residual 10% = 12k, depreciable = 108k, monthly = 1800
// Jan 1 to Jan 31 = 1 month
- const result = calculateDepreciation(baseAsset, "2025-01-31", null);
+ const result = calculateDepreciation(baseAsset, "2025-01-31", null, 2);
expect(result).toBe(1800);
});
it("calculates multi-month period", () => {
// 6 months: 1800 * 6 = 10800
- const result = calculateDepreciation(baseAsset, "2025-06-30", null);
+ const result = calculateDepreciation(baseAsset, "2025-06-30", null, 2);
expect(result).toBeCloseTo(10800, 0);
});
it("returns 0 when fully depreciated", () => {
const fullyDepr = { ...baseAsset, accumulatedDepreciation: 108000 };
- expect(calculateDepreciation(fullyDepr, "2025-06-30", null)).toBe(0);
+ expect(calculateDepreciation(fullyDepr, "2025-06-30", null, 2)).toBe(0);
});
it("returns 0 when start date is after period end", () => {
const futureStart = { ...baseAsset, depreciationStartDate: "2026-01-01" };
- expect(calculateDepreciation(futureStart, "2025-06-30", null)).toBe(0);
+ expect(calculateDepreciation(futureStart, "2025-06-30", null, 2)).toBe(0);
});
it("caps at remaining depreciable amount", () => {
const nearlyDone = { ...baseAsset, accumulatedDepreciation: 107500 };
- const result = calculateDepreciation(nearlyDone, "2025-06-30", null);
+ const result = calculateDepreciation(nearlyDone, "2025-06-30", null, 2);
expect(result).toBe(500);
});
@@ -437,7 +441,8 @@ describe("calculateDepreciation", () => {
const result = calculateDepreciation(
baseAsset,
"2025-03-31",
- "2025-01-31"
+ "2025-01-31",
+ 2
);
expect(result).toBeCloseTo(1800, 0);
});
@@ -447,14 +452,14 @@ describe("calculateDepreciation", () => {
const dbAsset = { ...baseAsset, depreciationMethod: "Declining Balance" };
it("first month produces higher amount than straight line", () => {
- const slResult = calculateDepreciation(baseAsset, "2025-01-31", null);
- const dbResult = calculateDepreciation(dbAsset, "2025-01-31", null);
+ const slResult = calculateDepreciation(baseAsset, "2025-01-31", null, 2);
+ const dbResult = calculateDepreciation(dbAsset, "2025-01-31", null, 2);
expect(dbResult).toBeGreaterThanOrEqual(slResult);
});
it("returns 0 when fully depreciated", () => {
const fullyDepr = { ...dbAsset, accumulatedDepreciation: 108000 };
- expect(calculateDepreciation(fullyDepr, "2025-06-30", null)).toBe(0);
+ expect(calculateDepreciation(fullyDepr, "2025-06-30", null, 2)).toBe(0);
});
});
@@ -467,20 +472,20 @@ describe("calculateDepreciation", () => {
it("calculates based on units produced", () => {
// depreciable 108k / 10k units = $10.80/unit, 100 units = $1080
- const result = calculateDepreciation(uopAsset, "2025-06-30", null, {
+ const result = calculateDepreciation(uopAsset, "2025-06-30", null, 2, {
unitsProduced: 100
});
expect(result).toBe(1080);
});
it("returns 0 without usage log", () => {
- expect(calculateDepreciation(uopAsset, "2025-06-30", null)).toBe(0);
+ expect(calculateDepreciation(uopAsset, "2025-06-30", null, 2)).toBe(0);
});
it("returns 0 with zero lifetime usage", () => {
const zeroLifetime = { ...uopAsset, assetLifetimeUsage: 0 };
expect(
- calculateDepreciation(zeroLifetime, "2025-06-30", null, {
+ calculateDepreciation(zeroLifetime, "2025-06-30", null, 2, {
unitsProduced: 100
})
).toBe(0);
@@ -489,7 +494,7 @@ describe("calculateDepreciation", () => {
it("returns 0 for unknown method", () => {
const unknown = { ...baseAsset, depreciationMethod: "SomethingElse" };
- expect(calculateDepreciation(unknown, "2025-06-30", null)).toBe(0);
+ expect(calculateDepreciation(unknown, "2025-06-30", null, 2)).toBe(0);
});
});
@@ -513,7 +518,8 @@ describe("calculateTaxDepreciation", () => {
bonusDepreciationPercent: null
},
"2025-12-31",
- null
+ null,
+ 2
);
expect(result).toBeNull();
});
@@ -533,13 +539,23 @@ describe("calculateTaxDepreciation", () => {
};
it("calculates year-1 MACRS without bonus", () => {
- const result = calculateTaxDepreciation(macrsAsset, "2025-12-31", null);
+ const result = calculateTaxDepreciation(
+ macrsAsset,
+ "2025-12-31",
+ null,
+ 2
+ );
// 5-year half-year year 1: 20% of $100k = $20,000
expect(result).toBe(20000);
});
it("calculates MACRS for a single-month period (how depreciation runs work)", () => {
- const result = calculateTaxDepreciation(macrsAsset, "2025-05-31", null);
+ const result = calculateTaxDepreciation(
+ macrsAsset,
+ "2025-05-31",
+ null,
+ 2
+ );
expect(result).not.toBeNull();
expect(result!).toBeGreaterThan(0);
});
@@ -554,7 +570,8 @@ describe("calculateTaxDepreciation", () => {
acquisitionDate: "2026-05-24"
},
"2026-06-30",
- "2026-05-31"
+ "2026-05-31",
+ 2
);
expect(result).not.toBeNull();
expect(result!).toBeGreaterThan(0);
@@ -565,7 +582,7 @@ describe("calculateTaxDepreciation", () => {
...macrsAsset,
bonusDepreciationPercent: null
};
- const result = calculateTaxDepreciation(nullBonus, "2025-12-31", null);
+ const result = calculateTaxDepreciation(nullBonus, "2025-12-31", null, 2);
expect(result).toBe(20000);
});
@@ -574,7 +591,7 @@ describe("calculateTaxDepreciation", () => {
...macrsAsset,
bonusDepreciationPercent: 60
};
- const result = calculateTaxDepreciation(withBonus, "2025-12-31", null);
+ const result = calculateTaxDepreciation(withBonus, "2025-12-31", null, 2);
// Bonus: 100k * 60% = 60k
// Adjusted basis: 40k, MACRS year 1: 40k * 20% = 8k
// Total: 60k + 8k = 68k
@@ -590,7 +607,8 @@ describe("calculateTaxDepreciation", () => {
const result = calculateTaxDepreciation(
withBonus,
"2026-12-31",
- "2025-12-31"
+ "2025-12-31",
+ 2
);
// Bonus should NOT be applied again (accumulatedTax > 0)
// Only MACRS on the $40k adjusted basis
@@ -604,7 +622,7 @@ describe("calculateTaxDepreciation", () => {
...macrsAsset,
bonusDepreciationPercent: 100
};
- const result = calculateTaxDepreciation(fullBonus, "2025-12-31", null);
+ const result = calculateTaxDepreciation(fullBonus, "2025-12-31", null, 2);
// Bonus = 100k, adjusted basis = 0, MACRS on 0 = 0
// Total = 100k
expect(result).toBe(100000);
@@ -615,7 +633,7 @@ describe("calculateTaxDepreciation", () => {
...macrsAsset,
macrsPropertyClass: "7"
};
- const result = calculateTaxDepreciation(sevenYear, "2025-12-31", null);
+ const result = calculateTaxDepreciation(sevenYear, "2025-12-31", null, 2);
// 7-year half-year year 1: 14.29% of $100k = $14,290
expect(result).toBe(14290);
});
@@ -637,13 +655,18 @@ describe("calculateTaxDepreciation", () => {
it("calculates tax straight-line depreciation", () => {
// $120k / 120 months = $1k/month; Jan to Dec = 12 months = $12k
- const result = calculateTaxDepreciation(slTaxAsset, "2025-12-31", null);
+ const result = calculateTaxDepreciation(
+ slTaxAsset,
+ "2025-12-31",
+ null,
+ 2
+ );
expect(result).toBeCloseTo(12000, 0);
});
it("returns 0 when fully depreciated", () => {
const fullyDepr = { ...slTaxAsset, accumulatedTaxDepreciation: 120000 };
- const result = calculateTaxDepreciation(fullyDepr, "2025-12-31", null);
+ const result = calculateTaxDepreciation(fullyDepr, "2025-12-31", null, 2);
expect(result).toBe(0);
});
});
@@ -663,14 +686,19 @@ describe("calculateTaxDepreciation", () => {
};
it("produces a positive result", () => {
- const result = calculateTaxDepreciation(dbTaxAsset, "2025-12-31", null);
+ const result = calculateTaxDepreciation(
+ dbTaxAsset,
+ "2025-12-31",
+ null,
+ 2
+ );
expect(result).not.toBeNull();
expect(result!).toBeGreaterThan(0);
});
it("returns 0 when fully depreciated", () => {
const fullyDepr = { ...dbTaxAsset, accumulatedTaxDepreciation: 90000 };
- const result = calculateTaxDepreciation(fullyDepr, "2025-12-31", null);
+ const result = calculateTaxDepreciation(fullyDepr, "2025-12-31", null, 2);
expect(result).toBe(0);
});
});
@@ -706,7 +734,8 @@ describe("buildDepreciationLines", () => {
"2025-12-31",
null,
true,
- new Map()
+ new Map(),
+ 2
);
expect(lines).toHaveLength(1);
expect(lines[0].amount).toBeGreaterThan(0);
@@ -720,7 +749,8 @@ describe("buildDepreciationLines", () => {
"2025-12-31",
null,
false,
- new Map()
+ new Map(),
+ 2
);
expect(lines).toHaveLength(1);
expect(lines[0].amount).toBeGreaterThan(0);
@@ -738,7 +768,8 @@ describe("buildDepreciationLines", () => {
"2025-12-31",
null,
true,
- new Map()
+ new Map(),
+ 2
);
expect(lines).toHaveLength(0);
});
@@ -754,7 +785,8 @@ describe("buildDepreciationLines", () => {
"2025-12-31",
null,
true,
- new Map()
+ new Map(),
+ 2
);
expect(lines).toHaveLength(1);
expect(lines[0].amount).toBe(0);
@@ -768,7 +800,8 @@ describe("buildDepreciationLines", () => {
"2025-12-31",
null,
true,
- new Map()
+ new Map(),
+ 2
);
expect(lines).toHaveLength(2);
});
@@ -779,7 +812,8 @@ describe("buildDepreciationLines", () => {
"2025-12-31",
null,
true,
- new Map()
+ new Map(),
+ 2
);
// Book SL: 108k/60mo * 12mo = $21,600
// Tax MACRS 5-yr HY: 120k * 20% = $24,000
diff --git a/apps/erp/app/modules/accounting/accounting.utils.ts b/apps/erp/app/modules/accounting/accounting.utils.ts
index 1f30b365b3..03cb2fa3ce 100644
--- a/apps/erp/app/modules/accounting/accounting.utils.ts
+++ b/apps/erp/app/modules/accounting/accounting.utils.ts
@@ -1,4 +1,4 @@
-import { credit, debit, toStoredAmount } from "@carbon/utils";
+import { credit, debit, round, toStoredAmount } from "@carbon/utils";
/**
* Gain/(loss) on disposal of a fixed asset = sale proceeds − net book value
@@ -248,6 +248,8 @@ export function calculateMacrsDepreciation(args: {
lastPostedPeriodEnd: string | null;
accumulatedTaxDepreciation: number;
bonusAmount: number;
+ /** Settlement decimals from currency.decimalPlaces — data, never a literal. */
+ decimalPlaces: number;
}): number {
const {
adjustedBasis,
@@ -256,6 +258,7 @@ export function calculateMacrsDepreciation(args: {
depreciationStartDate,
periodEnd,
lastPostedPeriodEnd,
+ decimalPlaces,
accumulatedTaxDepreciation,
bonusAmount
} = args;
@@ -279,7 +282,7 @@ export function calculateMacrsDepreciation(args: {
const amount = monthlyAmount * Math.max(0, months);
const remaining =
adjustedBasis - (accumulatedTaxDepreciation - bonusAmount);
- return Math.min(Math.round(amount * 100) / 100, Math.max(0, remaining));
+ return Math.min(round(amount, decimalPlaces), Math.max(0, remaining));
}
// Table-based MACRS: compute cumulative depreciation through periodEnd,
@@ -330,7 +333,7 @@ export function calculateMacrsDepreciation(args: {
const periodAmount = cumulativeThrough - Math.max(0, alreadyTaken);
const remaining = adjustedBasis - Math.max(0, alreadyTaken);
return Math.min(
- Math.round(Math.max(0, periodAmount) * 100) / 100,
+ round(Math.max(0, periodAmount), decimalPlaces),
Math.max(0, remaining)
);
}
@@ -393,6 +396,8 @@ export function calculateDepreciation(
},
periodEnd: string,
lastPostedPeriodEnd: string | null,
+ /** Settlement decimals from currency.decimalPlaces — data, never a literal. */
+ decimalPlaces: number,
usageLog?: { unitsProduced: number }
): number {
const cost = Number(asset.acquisitionCost);
@@ -418,7 +423,7 @@ export function calculateDepreciation(
: startDate;
const monthsToDepreciate = getMonthsBetween(from, periodEndDate);
const amount = monthlyAmount * monthsToDepreciate;
- return Math.min(Math.round(amount * 100) / 100, remainingDepreciable);
+ return Math.min(round(amount, decimalPlaces), remainingDepreciable);
}
case "Declining Balance": {
const annualRate = (1 / (asset.usefulLifeMonths / 12)) * 2;
@@ -445,7 +450,7 @@ export function calculateDepreciation(
totalDepr += capped;
nbv -= capped;
}
- return Math.min(Math.round(totalDepr * 100) / 100, remainingDepreciable);
+ return Math.min(round(totalDepr, decimalPlaces), remainingDepreciable);
}
case "Units of Production": {
if (
@@ -456,7 +461,7 @@ export function calculateDepreciation(
return 0;
const ratePerUnit = depreciableBase / Number(asset.assetLifetimeUsage);
const amount = ratePerUnit * usageLog.unitsProduced;
- return Math.min(Math.round(amount * 100) / 100, remainingDepreciable);
+ return Math.min(round(amount, decimalPlaces), remainingDepreciable);
}
default:
return 0;
@@ -477,7 +482,9 @@ export function calculateTaxDepreciation(
bonusDepreciationPercent: number | null;
},
periodEnd: string,
- lastPostedPeriodEnd: string | null
+ lastPostedPeriodEnd: string | null,
+ /** Settlement decimals from currency.decimalPlaces — data, never a literal. */
+ decimalPlaces: number
): number | null {
const taxMethod = asset.taxDepreciationMethod;
if (!taxMethod) return null;
@@ -507,10 +514,11 @@ export function calculateTaxDepreciation(
periodEnd,
lastPostedPeriodEnd,
accumulatedTaxDepreciation: accumulatedTax,
- bonusAmount
+ bonusAmount,
+ decimalPlaces
});
- return Math.round((bonus + macrsAmount) * 100) / 100;
+ return round(bonus + macrsAmount, decimalPlaces);
}
const taxLife = asset.taxUsefulLifeMonths!;
@@ -534,7 +542,7 @@ export function calculateTaxDepreciation(
if (taxMethod === "Straight Line") {
const monthlyAmount = depreciableBase / taxLife;
const amount = monthlyAmount * monthsToDepreciate;
- return Math.min(Math.round(amount * 100) / 100, remainingDepreciable);
+ return Math.min(round(amount, decimalPlaces), remainingDepreciable);
}
if (taxMethod === "Declining Balance") {
@@ -558,7 +566,7 @@ export function calculateTaxDepreciation(
totalDepr += capped;
nbv -= capped;
}
- return Math.min(Math.round(totalDepr * 100) / 100, remainingDepreciable);
+ return Math.min(round(totalDepr, decimalPlaces), remainingDepreciable);
}
return null;
@@ -586,7 +594,9 @@ export function buildDepreciationLines(
periodEnd: string,
lastPostedPeriodEnd: string | null,
taxEnabled: boolean,
- usageMap: Map<string, { unitsProduced: number }>
+ usageMap: Map<string, { unitsProduced: number }>,
+ /** Settlement decimals from currency.decimalPlaces — data, never a literal. */
+ decimalPlaces: number
): DepreciationLine[] {
const lines: DepreciationLine[] = [];
@@ -607,6 +617,7 @@ export function buildDepreciationLines(
},
periodEnd,
lastPostedPeriodEnd,
+ decimalPlaces,
usageLog
);
@@ -628,7 +639,8 @@ export function buildDepreciationLines(
bonusDepreciationPercent: asset.bonusDepreciationPercent
},
periodEnd,
- lastPostedPeriodEnd
+ lastPostedPeriodEnd,
+ decimalPlaces
);
if (taxAmount === null) {
taxAmount = amount;
diff --git a/apps/erp/app/modules/accounting/ui/ExchangeRates/ExchangeRateForm.tsx b/apps/erp/app/modules/accounting/ui/ExchangeRates/ExchangeRateForm.tsx
index 38427cc619..f0035dcb97 100644
--- a/apps/erp/app/modules/accounting/ui/ExchangeRates/ExchangeRateForm.tsx
+++ b/apps/erp/app/modules/accounting/ui/ExchangeRates/ExchangeRateForm.tsx
@@ -35,10 +35,16 @@ import {
ChartTooltip,
ChartTooltipContent
} from "@carbon/react/Chart";
-import { formatDate } from "@carbon/utils";
+import {
+ formatDate,
+ formatExchangeRate,
+ INPUT_FORMAT,
+ INPUT_STEP
+} from "@carbon/utils";
import { useLingui } from "@lingui/react/macro";
+import { useLocale } from "@react-aria/i18n";
import { json2csv } from "json-2-csv";
-import { useCallback, useMemo, useState } from "react";
+import { useCallback, useMemo } from "react";
import { LuDownload } from "react-icons/lu";
import { useNavigate } from "react-router";
import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts";
@@ -80,9 +86,7 @@ const CurrencyForm = ({
const permissions = usePermissions();
const navigate = useNavigate();
const onClose = () => navigate(-1);
- const [decimalPlaces, setDecimalPlaces] = useState(
- initialValues.decimalPlaces ?? 2
- );
+ const { locale } = useLocale();
const { company } = useUser();
@@ -154,7 +158,6 @@ const CurrencyForm = ({
termId="decimal-places-currency"
minValue={0}
maxValue={4}
- onChange={setDecimalPlaces}
/>
<NumberField
name="exchangeRate"
@@ -162,9 +165,8 @@ const CurrencyForm = ({
termId="exchange-rate"
minValue={isBaseCurrency ? 1 : 0}
maxValue={isBaseCurrency ? 1 : undefined}
- formatOptions={{
- minimumFractionDigits: decimalPlaces ?? 0
- }}
+ step={INPUT_STEP.exchangeRate}
+ formatOptions={INPUT_FORMAT.exchangeRate}
helperText={exchangeRateHelperText}
/>
{!isBaseCurrency && (
@@ -173,9 +175,8 @@ const CurrencyForm = ({
label={t`Historical Rate (Equity)`}
termId="historical-exchange-rate"
minValue={0}
- formatOptions={{
- minimumFractionDigits: decimalPlaces ?? 0
- }}
+ step={INPUT_STEP.exchangeRate}
+ formatOptions={INPUT_FORMAT.exchangeRate}
helperText="Rate used for equity account translation in consolidation (IAS 21). Leave blank to use the current exchange rate."
/>
)}
@@ -283,7 +284,7 @@ const CurrencyForm = ({
<DateTime value={row.date} variant="date" />
</Td>
<Td className="text-right">
- {row.rate.toFixed(decimalPlaces)}
+ {formatExchangeRate(row.rate, locale)}
</Td>
</Tr>
))}
diff --git a/apps/erp/app/modules/accounting/ui/FixedAssets/FixedAssetRegisterForm.tsx b/apps/erp/app/modules/accounting/ui/FixedAssets/FixedAssetRegisterForm.tsx
index 033f32ce33..f4e2870ea9 100644
--- a/apps/erp/app/modules/accounting/ui/FixedAssets/FixedAssetRegisterForm.tsx
+++ b/apps/erp/app/modules/accounting/ui/FixedAssets/FixedAssetRegisterForm.tsx
@@ -11,10 +11,11 @@ import {
ModalDrawerTitle,
VStack
} from "@carbon/react";
+import { INPUT_FORMAT } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { useFetcher } from "react-router";
import { DatePicker, Number, Submit } from "~/components/Form";
-import { usePermissions, useUser } from "~/hooks";
+import { useCurrencyDecimals, usePermissions, useUser } from "~/hooks";
import { fixedAssetRegisterValidator } from "../../accounting.models";
type FixedAssetRegisterFormProps = {
@@ -25,6 +26,9 @@ const FixedAssetRegisterForm = ({ onClose }: FixedAssetRegisterFormProps) => {
const { t } = useLingui();
const permissions = usePermissions();
const { company } = useUser();
+ const currencyDecimals = useCurrencyDecimals(
+ company?.baseCurrencyCode ?? "USD"
+ );
const fetcher = useFetcher();
return (
@@ -60,10 +64,10 @@ const FixedAssetRegisterForm = ({ onClose }: FixedAssetRegisterFormProps) => {
label={t`Acquisition Cost`}
termId="fixed-asset-acquisition-cost"
minValue={0}
- formatOptions={{
- style: "currency",
- currency: company?.baseCurrencyCode ?? "USD"
- }}
+ formatOptions={INPUT_FORMAT.money(
+ company?.baseCurrencyCode ?? "USD",
+ currencyDecimals
+ )}
/>
<DatePicker
name="acquisitionDate"
@@ -74,10 +78,10 @@ const FixedAssetRegisterForm = ({ onClose }: FixedAssetRegisterFormProps) => {
label={t`Accumulated Depreciation`}
termId="fixed-asset-opening-accumulated-depreciation"
minValue={0}
- formatOptions={{
- style: "currency",
- currency: company?.baseCurrencyCode ?? "USD"
- }}
+ formatOptions={INPUT_FORMAT.money(
+ company?.baseCurrencyCode ?? "USD",
+ currencyDecimals
+ )}
/>
<DatePicker
name="depreciationStartDate"
diff --git a/apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyBalanceMatrix.tsx b/apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyBalanceMatrix.tsx
index a0c6f87bf5..0e68092e45 100644
--- a/apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyBalanceMatrix.tsx
+++ b/apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyBalanceMatrix.tsx
@@ -1,6 +1,7 @@
import { Card, CardContent, CardHeader, CardTitle } from "@carbon/react";
import { Trans } from "@lingui/react/macro";
import { memo, useMemo } from "react";
+import { useCurrencyFormatter } from "~/hooks";
type BalanceEntry = {
sourceCompanyId: string;
@@ -16,6 +17,7 @@ type IntercompanyBalanceMatrixProps = {
const IntercompanyBalanceMatrix = memo(
({ data }: IntercompanyBalanceMatrixProps) => {
+ const formatter = useCurrencyFormatter({ wholeUnits: true });
const { companies, matrix } = useMemo(() => {
const companyMap = new Map<string, string>();
for (const entry of data) {
@@ -42,13 +44,7 @@ const IntercompanyBalanceMatrix = memo(
return null;
}
- const formatAmount = (amount: number) =>
- new Intl.NumberFormat("en-US", {
- style: "currency",
- currency: "USD",
- minimumFractionDigits: 0,
- maximumFractionDigits: 0
- }).format(amount);
+ const formatAmount = (amount: number) => formatter.format(amount);
return (
<Card>
diff --git a/apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyTransactionTable.tsx b/apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyTransactionTable.tsx
index c55767cc99..fb21064cfb 100644
--- a/apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyTransactionTable.tsx
+++ b/apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyTransactionTable.tsx
@@ -1,4 +1,6 @@
+import { formatMoney } from "@carbon/utils";
import { useLingui } from "@lingui/react/macro";
+import { useLocale } from "@react-aria/i18n";
import type { ColumnDef } from "@tanstack/react-table";
import type { ReactNode } from "react";
import { memo, useMemo } from "react";
@@ -9,6 +11,7 @@ import {
LuStar
} from "react-icons/lu";
import { DateTime, Table } from "~/components";
+import { useCurrencyDecimalsLookup } from "~/hooks";
import { intercompanyTransactionStatuses } from "../../accounting.models";
import IntercompanyTransactionStatus from "./IntercompanyTransactionStatus";
@@ -35,6 +38,10 @@ type IntercompanyTransactionTableProps = {
const IntercompanyTransactionTable = memo(
({ data, count, primaryAction }: IntercompanyTransactionTableProps) => {
const { t } = useLingui();
+ // Currency varies per row, so the formatter is built per cell from the
+ // app locale rather than a single-currency hook instance.
+ const { locale } = useLocale();
+ const currencyDecimals = useCurrencyDecimalsLookup();
const columns = useMemo<ColumnDef<IntercompanyTransaction>[]>(() => {
const defaultColumns: ColumnDef<IntercompanyTransaction>[] = [
{
@@ -57,11 +64,15 @@ const IntercompanyTransactionTable = memo(
accessorKey: "amount",
header: t`Amount`,
cell: ({ row }) => {
- const formatted = new Intl.NumberFormat("en-US", {
- style: "currency",
- currency: row.original.currencyCode || "USD"
- }).format(row.original.amount);
- return formatted;
+ // The currency varies per row, so the decimals are looked up from
+ // the cached list rather than by a hook (which cannot run per row).
+ const code = row.original.currencyCode || "USD";
+ return formatMoney(
+ row.original.amount,
+ locale,
+ code,
+ currencyDecimals(code)
+ );
},
meta: {
icon: <LuCircleDollarSign />
@@ -110,7 +121,7 @@ const IntercompanyTransactionTable = memo(
}
];
return defaultColumns;
- }, [t]);
+ }, [t, locale, currencyDecimals]);
return (
<Table<IntercompanyTransaction>
diff --git a/apps/erp/app/modules/accounting/ui/JournalEntries/JournalLineRow.tsx b/apps/erp/app/modules/accounting/ui/JournalEntries/JournalLineRow.tsx
index d189b7e5c1..51b1c2d33b 100644
--- a/apps/erp/app/modules/accounting/ui/JournalEntries/JournalLineRow.tsx
+++ b/apps/erp/app/modules/accounting/ui/JournalEntries/JournalLineRow.tsx
@@ -1,7 +1,9 @@
import { IconButton, Input, NumberField, NumberInput } from "@carbon/react";
+import { INPUT_FORMAT } from "@carbon/utils";
import { useLingui } from "@lingui/react/macro";
import { LuTrash } from "react-icons/lu";
import { AccountControlled } from "~/components/Form";
+import { useCurrencyDecimals } from "~/hooks";
import DimensionSelector from "./DimensionSelector";
import type {
ClientJournalLine,
@@ -33,6 +35,9 @@ const JournalLineRow = ({
autoSaveDimensions = false
}: JournalLineRowProps) => {
const { t } = useLingui();
+ // Debit/credit are GL journal lines — internal scale-5 values per the two-scale
+ // rule, so the currency's decimals are the MINIMUM here, never the maximum.
+ const currencyDecimals = useCurrencyDecimals(currencyCode);
const handleAccountChange = (accountId: string) => {
onChange({ ...line, accountId });
};
@@ -99,10 +104,7 @@ const JournalLineRow = ({
<NumberField
value={line.debit ?? 0}
onChange={handleDebitChange}
- formatOptions={{
- style: "currency",
- currency: currencyCode
- }}
+ formatOptions={INPUT_FORMAT.price(currencyCode, currencyDecimals)}
minValue={0}
isDisabled={isDisabled}
isReadOnly={isDisabled}
@@ -117,10 +119,7 @@ const JournalLineRow = ({
<NumberField
value={line.credit ?? 0}
onChange={handleCreditChange}
- formatOptions={{
- style: "currency",
- currency: currencyCode
- }}
+ formatOptions={INPUT_FORMAT.price(currencyCode, currencyDecimals)}
minValue={0}
isDisabled={isDisabled}
isReadOnly={isDisabled}
diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryDetails.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryDetails.tsx
index f8dc21665f..7d692f763e 100644
--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryDetails.tsx
+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryDetails.tsx
@@ -6,11 +6,11 @@ import {
VStack
} from "@carbon/react";
import { Trans } from "@lingui/react/macro";
-import { useLocale } from "@react-aria/i18n";
import { useState } from "react";
import { LuMoveDown, LuMoveUp } from "react-icons/lu";
import type { z } from "zod";
import { DateSelect } from "~/components/DateSelect";
+import { useQuantityFormatter } from "~/hooks";
import type {
ItemQuantities,
ItemStorageUnitQuantities,
@@ -43,12 +43,7 @@ const InventoryDetails = ({
quantities,
storageUnits
}: InventoryDetailsProps) => {
- const { locale } = useLocale();
- const formatter = Intl.NumberFormat(locale, {
- minimumFractionDigits: 0,
- maximumFractionDigits: 2,
- useGrouping: true
- });
+ const formatQuantity = useQuantityFormatter();
const [usageWindow, setUsageWindow] = useState<"30" | "90">("30");
const dailyUsage =
usageWindow === "30"
@@ -66,7 +61,7 @@ const InventoryDetails = ({
</CardHeader>
<CardContent>
<h3 className="text-4xl font-medium tracking-tighter">
- {formatter.format(quantities?.quantityOnHand ?? 0)}
+ {formatQuantity(quantities?.quantityOnHand ?? 0)}
</h3>
</CardContent>
</Card>
@@ -78,7 +73,7 @@ const InventoryDetails = ({
</CardHeader>
<CardContent>
<h3 className="text-4xl font-medium tracking-tighter">
- {formatter.format(quantities?.daysRemaining ?? 0)}
+ {formatQuantity(quantities?.daysRemaining ?? 0)}
</h3>
</CardContent>
</Card>
@@ -101,7 +96,7 @@ const InventoryDetails = ({
</CardHeader>
<CardContent>
<h3 className="text-4xl font-medium tracking-tighter">
- {formatter.format(dailyUsage)}
+ {formatQuantity(dailyUsage)}
</h3>
</CardContent>
</Card>
@@ -114,7 +109,7 @@ const InventoryDetails = ({
<CardContent>
<div className="flex justify-start items-center gap-1">
<h3 className="text-4xl font-medium tracking-tighter">
- {formatter.format(quantities?.quantityOnPurchaseOrder ?? 0)}
+ {formatQuantity(quantities?.quantityOnPurchaseOrder ?? 0)}
</h3>
<LuMoveUp className="text-emerald-500 text-lg" />
</div>
@@ -129,7 +124,7 @@ const InventoryDetails = ({
<CardContent>
<div className="flex justify-start items-center gap-1">
<h3 className="text-4xl font-medium tracking-tighter">
- {formatter.format(quantities?.quantityOnSalesOrder ?? 0)}
+ {formatQuantity(quantities?.quantityOnSalesOrder ?? 0)}
</h3>
<LuMoveDown className="text-red-500 text-lg" />
</div>
@@ -145,15 +140,13 @@ const InventoryDetails = ({
<div className="flex items-start justify-start gap-2">
<div className="flex justify-start items-center gap-1">
<h3 className="text-4xl font-medium tracking-tighter">
- {formatter.format(quantities?.quantityOnProductionOrder ?? 0)}
+ {formatQuantity(quantities?.quantityOnProductionOrder ?? 0)}
</h3>
<LuMoveUp className="text-emerald-500 text-lg" />
</div>
<div className="flex justify-start items-center gap-1">
<h3 className="text-4xl font-medium tracking-tighter">
- {formatter.format(
- quantities?.quantityOnProductionDemand ?? 0
- )}
+ {formatQuantity(quantities?.quantityOnProductionDemand ?? 0)}
</h3>
<LuMoveDown className="text-red-500 text-lg" />
</div>
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/utils.ts b/apps/erp/app/modules/inventory/ui/Traceability/utils.ts
index bdc2279040..79f4117904 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/utils.ts
+++ b/apps/erp/app/modules/inventory/ui/Traceability/utils.ts
@@ -1,3 +1,4 @@
+import { EPSILON } from "@carbon/utils";
import type { Edge, Node } from "@xyflow/react";
import type {
Activity,
@@ -157,8 +158,6 @@ type LotTimeline = {
wiring: LotEventWiring[];
};
-const QTY_EPSILON = 1e-6;
-
/**
* Replay an entity's visible events backward from its current quantity to
* recover the quantity at every point in time, then wire each event to
@@ -188,14 +187,14 @@ function buildLotTimeline(
for (let i = events.length - 1; i >= 0; i--) {
const ev = events[i];
if (ev.inQty !== null && ev.outQty !== null) {
- if (Math.abs(cur - ev.outQty) > QTY_EPSILON) return null;
+ if (Math.abs(cur - ev.outQty) > EPSILON) return null;
after[i] = ev.outQty;
before[i] = ev.inQty;
cur = ev.inQty;
} else if (ev.outQty !== null) {
if (i === 0) {
// Creation: the produced quantity must be what flowed forward.
- if (Math.abs(cur - ev.outQty) > QTY_EPSILON) return null;
+ if (Math.abs(cur - ev.outQty) > EPSILON) return null;
after[i] = ev.outQty;
before[i] = null;
} else {
@@ -224,7 +223,7 @@ function buildLotTimeline(
}
if (
before[i] !== null &&
- (before[i]! < -QTY_EPSILON || !Number.isFinite(before[i]!))
+ (before[i]! < -EPSILON || !Number.isFinite(before[i]!))
) {
return null;
}
@@ -240,7 +239,7 @@ function buildLotTimeline(
stateQuantities.push(before[i]!);
} else if (
Math.abs(stateQuantities[stateQuantities.length - 1] - before[i]!) >
- QTY_EPSILON
+ EPSILON
) {
return null;
}
diff --git a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLineForm.tsx b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLineForm.tsx
index 400445cdd4..82044aa907 100644
--- a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLineForm.tsx
+++ b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLineForm.tsx
@@ -11,6 +11,7 @@ import {
toast,
VStack
} from "@carbon/react";
+import { INPUT_FORMAT, INPUT_STEP } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { useEffect, useState } from "react";
import { useFetcher, useParams } from "react-router";
@@ -153,7 +154,8 @@ const WarehouseTransferLineForm = ({
name="quantity"
label={t`Quantity`}
minValue={0.0001}
- step={0.0001}
+ formatOptions={INPUT_FORMAT.quantity}
+ step={INPUT_STEP.quantity}
/>
<StorageUnit
name="fromStorageUnitId"
diff --git a/apps/erp/app/modules/invoicing/invoicing.models.ts b/apps/erp/app/modules/invoicing/invoicing.models.ts
index 051d97931d..6a6f1c321a 100644
--- a/apps/erp/app/modules/invoicing/invoicing.models.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.models.ts
@@ -128,6 +128,7 @@ export const purchaseInvoiceLineValidator = z
supplierUnitPrice: zfd.numeric(z.number().optional()),
supplierShippingCost: zfd.numeric(z.number().optional().default(0)),
supplierTaxAmount: zfd.numeric(z.number().optional().default(0)),
+ taxPercent: zfd.numeric(z.number().min(0).max(1).optional().default(0)),
requiredDate: zfd.text(z.string().optional()),
locationId: zfd.text(z.string().optional()),
storageUnitId: zfd.text(z.string().optional()),
diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.ts
index 70a2e7beee..c3b0eb03bf 100644
--- a/apps/erp/app/modules/invoicing/invoicing.service.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts
@@ -1,7 +1,7 @@
import type { Database, Json } from "@carbon/database";
import { getCompanyTimeZone } from "@carbon/database";
import type { Kysely, KyselyDatabase } from "@carbon/database/client";
-import { datetime } from "@carbon/utils";
+import { datetime, EPSILON, round } from "@carbon/utils";
import { endOfMonth, parseDate } from "@internationalized/date";
import type { SupabaseClient } from "@supabase/supabase-js";
import type { z } from "zod";
@@ -1651,7 +1651,7 @@ export async function getAvailableOnAccountCredit(
Number(p.totalAmount) * Number(p.exchangeRate) -
(appliedBaseByPayment.get(p.id) ?? 0);
}
- return Math.max(0, Math.round(baseCredit * 10000) / 10000);
+ return Math.max(0, round(baseCredit));
}
export async function upsertPayment(
@@ -2018,10 +2018,9 @@ export async function getAvailableCreditsForParty(
const result = rows
.map((m) => {
- const remaining =
- Math.round(
- (Number(m.amount) - (appliedByMemo.get(m.id) ?? 0)) * 10000
- ) / 10000;
+ const remaining = round(
+ Number(m.amount) - (appliedByMemo.get(m.id) ?? 0)
+ );
return {
id: m.id as string,
memoId: m.memoId as string,
@@ -2334,13 +2333,13 @@ export async function applyCreditsToInvoices(
const invoiceOpen =
Number(balById.get(app.invoiceId)?.balance ?? 0) -
(cashByInvoice.get(app.invoiceId) ?? 0);
- if (invoiceUse.get(app.invoiceId)! > invoiceOpen + 0.0001)
+ if (invoiceUse.get(app.invoiceId)! > invoiceOpen + EPSILON)
throw new Error(
- invoiceOpen <= 0.0001
+ invoiceOpen <= EPSILON
? `Invoice ${invoiceLabel} has no open balance to apply credit to (it is already fully settled)`
: `Credit applied to invoice ${invoiceLabel} (${invoiceUse.get(
app.invoiceId
- )}) exceeds its open balance of ${invoiceOpen.toFixed(2)}`
+ )}) exceeds its open balance of ${round(invoiceOpen)}`
);
}
diff --git a/apps/erp/app/modules/invoicing/ui/Memo/MemoForm.tsx b/apps/erp/app/modules/invoicing/ui/Memo/MemoForm.tsx
index fbdb3cf7d2..d133e558ef 100644
--- a/apps/erp/app/modules/invoicing/ui/Memo/MemoForm.tsx
+++ b/apps/erp/app/modules/invoicing/ui/Memo/MemoForm.tsx
@@ -19,6 +19,7 @@ import {
useDisclosure,
VStack
} from "@carbon/react";
+import { INPUT_FORMAT, INPUT_STEP } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { useState } from "react";
import { LuCheckCheck, LuTicketX, LuTrash } from "react-icons/lu";
@@ -41,7 +42,7 @@ import {
TextArea
} from "~/components/Form";
import { ConfirmDelete } from "~/components/Modals";
-import { usePermissions, useUser } from "~/hooks";
+import { useCurrencyDecimals, usePermissions, useUser } from "~/hooks";
import {
isMemoLocked,
memoDirection,
@@ -59,6 +60,9 @@ type MemoFormProps = {
const MemoForm = ({ initialValues }: MemoFormProps) => {
const { t } = useLingui();
const { company } = useUser();
+ const currencyDecimals = useCurrencyDecimals(
+ company?.baseCurrencyCode ?? "USD"
+ );
const permissions = usePermissions();
const post = useFetcher();
const voidFetcher = useFetcher();
@@ -216,18 +220,16 @@ const MemoForm = ({ initialValues }: MemoFormProps) => {
<Number
name="exchangeRate"
label={t`Exchange Rate`}
- formatOptions={{
- minimumFractionDigits: 2,
- maximumFractionDigits: 4
- }}
+ step={INPUT_STEP.exchangeRate}
+ formatOptions={INPUT_FORMAT.exchangeRate}
/>
<Number
name="amount"
label={t`Amount`}
- formatOptions={{
- style: "currency",
- currency: company?.baseCurrencyCode ?? "USD"
- }}
+ formatOptions={INPUT_FORMAT.money(
+ company?.baseCurrencyCode ?? "USD",
+ currencyDecimals
+ )}
/>
<Input name="reference" label={t`Reference`} />
<CustomFormFields table="memo" />
diff --git a/apps/erp/app/modules/invoicing/ui/Payment/AvailableCreditsTable.tsx b/apps/erp/app/modules/invoicing/ui/Payment/AvailableCreditsTable.tsx
index 033c5c1095..2c8dbfab1f 100644
--- a/apps/erp/app/modules/invoicing/ui/Payment/AvailableCreditsTable.tsx
+++ b/apps/erp/app/modules/invoicing/ui/Payment/AvailableCreditsTable.tsx
@@ -16,12 +16,17 @@ import {
SelectTrigger,
SelectValue
} from "@carbon/react";
+import { INPUT_FORMAT, round } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { useCallback, useMemo, useState } from "react";
import { LuSave } from "react-icons/lu";
import { useFetcher } from "react-router";
import { Enumerable } from "~/components/Enumerable";
-import { useCurrencyFormatter, usePermissions } from "~/hooks";
+import {
+ useCurrencyDecimals,
+ useCurrencyFormatter,
+ usePermissions
+} from "~/hooks";
import { path } from "~/utils/path";
// An available credit (a posted, balance-reducing memo) the party can apply to an
@@ -64,10 +69,6 @@ type CreditRow = {
amount: number;
};
-function round4(n: number): number {
- return Math.round(n * 10000) / 10000;
-}
-
const GRID =
"grid grid-cols-[2rem_minmax(8rem,1fr)_7rem_minmax(9rem,1fr)_8rem] gap-3";
@@ -83,6 +84,7 @@ const AvailableCreditsTable = ({
const permissions = usePermissions();
const fetcher = useFetcher();
const currencyFormatter = useCurrencyFormatter({ currency });
+ const currencyDecimals = useCurrencyDecimals(currency);
const canEdit = permissions.can("update", "invoicing");
const balanceByInvoice = useMemo(
@@ -118,7 +120,7 @@ const AvailableCreditsTable = ({
// invoice's open balance.
const capFor = useCallback(
(remaining: number, invoiceId: string) =>
- round4(Math.min(remaining, Number(balanceByInvoice.get(invoiceId) ?? 0))),
+ round(Math.min(remaining, Number(balanceByInvoice.get(invoiceId) ?? 0))),
[balanceByInvoice]
);
@@ -162,7 +164,7 @@ const AvailableCreditsTable = ({
setRows((prev) =>
prev.map((r) => {
if (r.id !== id) return r;
- const amount = round4(Math.max(0, value));
+ const amount = round(Math.max(0, value));
return { ...r, amount, checked: amount > 0 };
})
),
@@ -293,10 +295,10 @@ const AvailableCreditsTable = ({
}
minValue={0}
isDisabled={!canEdit}
- formatOptions={{
- minimumFractionDigits: 2,
- maximumFractionDigits: 4
- }}
+ formatOptions={INPUT_FORMAT.money(
+ currency,
+ currencyDecimals
+ )}
>
<NumberInputGroup>
<NumberInput className="text-right tabular-nums" />
diff --git a/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplications.tsx b/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplications.tsx
index 2096977e98..69236e3952 100644
--- a/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplications.tsx
+++ b/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplications.tsx
@@ -11,6 +11,7 @@ import {
Thead,
Tr
} from "@carbon/react";
+import { SCALE_FORMAT } from "@carbon/utils";
import { Trans } from "@lingui/react/macro";
import { useNumberFormatter } from "@react-aria/i18n";
import { DateTime, Hyperlink } from "~/components";
@@ -58,10 +59,7 @@ const PaymentApplications = ({
paymentTotal
}: PaymentApplicationsProps) => {
const currencyFormatter = useCurrencyFormatter();
- const rateFormatter = useNumberFormatter({
- minimumFractionDigits: 2,
- maximumFractionDigits: 4
- });
+ const rateFormatter = useNumberFormatter(SCALE_FORMAT);
const totalApplied = applications.reduce(
(sum, a) =>
diff --git a/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.tsx b/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.tsx
index 0b157949f0..b2e4f8d0d9 100644
--- a/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.tsx
+++ b/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.tsx
@@ -13,13 +13,18 @@ import {
NumberInput,
NumberInputGroup
} from "@carbon/react";
+import { EPSILON, INPUT_FORMAT, round } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { CSSProperties } from "react";
import { useCallback, useMemo, useState } from "react";
import { LuListChecks, LuRotateCcw, LuSave } from "react-icons/lu";
import { useFetcher } from "react-router";
import { DateTime } from "~/components";
-import { useCurrencyFormatter, usePermissions } from "~/hooks";
+import {
+ useCurrencyDecimals,
+ useCurrencyFormatter,
+ usePermissions
+} from "~/hooks";
import { path } from "~/utils/path";
// One row in the apply table — an open invoice for the payment's
@@ -75,10 +80,6 @@ type PaymentApplyTableProps = {
existingApplications: ExistingApplication[];
};
-function round4(n: number): number {
- return Math.round(n * 10000) / 10000;
-}
-
// Shared grid template so the header labels stay aligned with the rows. Wide
// enough to scroll horizontally on small screens rather than cramp the inputs.
const GRID = "grid grid-cols-[2rem_minmax(9rem,1fr)_7rem_8rem_8rem_8rem] gap-3";
@@ -88,12 +89,16 @@ const AmountInput = ({
value,
onChange,
isDisabled,
- label
+ label,
+ currency,
+ currencyDecimals
}: {
value: number;
onChange: (value: number) => void;
isDisabled: boolean;
label: string;
+ currency: string;
+ currencyDecimals: number;
}) => (
<NumberField
aria-label={label}
@@ -101,7 +106,7 @@ const AmountInput = ({
onChange={(v) => onChange(Number.isNaN(v) ? 0 : v)}
minValue={0}
isDisabled={isDisabled}
- formatOptions={{ minimumFractionDigits: 2, maximumFractionDigits: 4 }}
+ formatOptions={INPUT_FORMAT.money(currency, currencyDecimals)}
>
<NumberInputGroup>
<NumberInput className="text-right tabular-nums" />
@@ -123,6 +128,7 @@ const PaymentApplyTable = ({
const permissions = usePermissions();
const fetcher = useFetcher();
const currencyFormatter = useCurrencyFormatter({ currency: paymentCurrency });
+ const currencyDecimals = useCurrencyDecimals(paymentCurrency);
const today = new Date().toISOString().slice(0, 10);
const isReceipt = paymentType === "Receipt";
const canEdit = permissions.can("update", "invoicing");
@@ -166,7 +172,11 @@ const PaymentApplyTable = ({
0,
Math.min(availableCredit, totalCash - paymentTotal)
);
- const overApplied = totalCash > maxApplicable + 0.0001;
+ // EPSILON, not a hand-picked 1e-4: every amount here is already rounded to
+ // internal scale, so the only slack needed is float noise. A 1e-4 band is
+ // coarser than the 1e-5 the values carry, and let a real over-application of
+ // 0.0001 through.
+ const overApplied = totalCash > maxApplicable + EPSILON;
const appliedPct =
paymentTotal > 0
? Math.min(100, Math.max(0, (totalCash / paymentTotal) * 100))
@@ -185,7 +195,7 @@ const PaymentApplyTable = ({
checked: true,
appliedAmount:
r.appliedAmount === 0
- ? round4(Math.min(r.balance, maxApplicable))
+ ? round(Math.min(r.balance, maxApplicable))
: r.appliedAmount
};
}
@@ -208,7 +218,7 @@ const PaymentApplyTable = ({
setRows((prev) =>
prev.map((r) => {
if (r.id !== id) return r;
- const next = { ...r, [field]: round4(Math.max(0, value)) };
+ const next = { ...r, [field]: round(Math.max(0, value)) };
next.checked =
next.appliedAmount + next.discountAmount + next.writeOffAmount > 0;
return next;
@@ -227,8 +237,8 @@ const PaymentApplyTable = ({
return { ...r, checked: false, appliedAmount: 0 };
}
const take = Math.min(remaining, r.balance);
- remaining = round4(remaining - take);
- return { ...r, checked: true, appliedAmount: round4(take) };
+ remaining = round(remaining - take);
+ return { ...r, checked: true, appliedAmount: round(take) };
})
);
}, [paymentTotal]);
@@ -387,18 +397,24 @@ const PaymentApplyTable = ({
label={t`Applied amount for ${r.invoiceId}`}
value={r.appliedAmount}
isDisabled={!canEdit}
+ currency={paymentCurrency}
+ currencyDecimals={currencyDecimals}
onChange={(v) => updateAmount(r.id, "appliedAmount", v)}
/>
<AmountInput
label={t`Discount for ${r.invoiceId}`}
value={r.discountAmount}
isDisabled={!canEdit}
+ currency={paymentCurrency}
+ currencyDecimals={currencyDecimals}
onChange={(v) => updateAmount(r.id, "discountAmount", v)}
/>
<AmountInput
label={t`Write-off for ${r.invoiceId}`}
value={r.writeOffAmount}
isDisabled={!canEdit}
+ currency={paymentCurrency}
+ currencyDecimals={currencyDecimals}
onChange={(v) => updateAmount(r.id, "writeOffAmount", v)}
/>
</div>
diff --git a/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.tsx b/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.tsx
index c463874ff5..bc73ca9d4d 100644
--- a/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.tsx
+++ b/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.tsx
@@ -12,6 +12,7 @@ import {
useDisclosure,
VStack
} from "@carbon/react";
+import { INPUT_FORMAT, INPUT_STEP } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { useState } from "react";
import { LuCheckCheck, LuTicketX, LuTrash } from "react-icons/lu";
@@ -35,7 +36,7 @@ import {
TextArea
} from "~/components/Form";
import { ConfirmDelete } from "~/components/Modals";
-import { usePermissions, useUser } from "~/hooks";
+import { useCurrencyDecimals, usePermissions, useUser } from "~/hooks";
import {
isPaymentLocked,
paymentType,
@@ -90,6 +91,9 @@ type PaymentFormProps = {
const PaymentForm = ({ initialValues, seedInvoiceIds }: PaymentFormProps) => {
const { t } = useLingui();
const { company } = useUser();
+ const currencyDecimals = useCurrencyDecimals(
+ company?.baseCurrencyCode ?? "USD"
+ );
const permissions = usePermissions();
const post = useFetcher();
const voidFetcher = useFetcher();
@@ -228,18 +232,16 @@ const PaymentForm = ({ initialValues, seedInvoiceIds }: PaymentFormProps) => {
<Number
name="exchangeRate"
label={t`Exchange Rate`}
- formatOptions={{
- minimumFractionDigits: 2,
- maximumFractionDigits: 4
- }}
+ step={INPUT_STEP.exchangeRate}
+ formatOptions={INPUT_FORMAT.exchangeRate}
/>
<Number
name="totalAmount"
label={t`Total Amount`}
- formatOptions={{
- style: "currency",
- currency: company?.baseCurrencyCode ?? "USD"
- }}
+ formatOptions={INPUT_FORMAT.money(
+ company?.baseCurrencyCode ?? "USD",
+ currencyDecimals
+ )}
/>
<Account
name="bankAccount"
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceDeliveryForm.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceDeliveryForm.tsx
index 210c6dea47..7f3bab2558 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceDeliveryForm.tsx
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceDeliveryForm.tsx
@@ -6,6 +6,7 @@ import {
CardHeader,
CardTitle
} from "@carbon/react";
+import { INPUT_FORMAT } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { forwardRef, useImperativeHandle, useRef, useState } from "react";
import { useFetcher, useParams } from "react-router";
@@ -20,7 +21,7 @@ import {
ShippingMethod,
Submit
} from "~/components/Form";
-import { usePermissions, useRouteData } from "~/hooks";
+import { useCurrencyDecimals, usePermissions, useRouteData } from "~/hooks";
import type { PurchaseInvoice } from "~/modules/invoicing";
import {
isPurchaseInvoiceLocked,
@@ -45,6 +46,8 @@ const PurchaseInvoiceDeliveryForm = forwardRef<
PurchaseInvoiceDeliveryFormProps
>(({ initialValues, currencyCode, defaultCollapsed = false }, ref) => {
const { t } = useLingui();
+ // Settlement amount — digits follow the document currency's own decimals.
+ const currencyDecimals = useCurrencyDecimals(currencyCode);
const { invoiceId } = useParams();
if (!invoiceId) {
throw new Error("invoiceId not found");
@@ -108,10 +111,7 @@ const PurchaseInvoiceDeliveryForm = forwardRef<
name="supplierShippingCost"
label={t`Shipping Cost`}
minValue={0}
- formatOptions={{
- style: "currency",
- currency: currencyCode
- }}
+ formatOptions={INPUT_FORMAT.money(currencyCode, currencyDecimals)}
ref={shippingCostRef}
/>
<Location
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceExplorer.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceExplorer.tsx
index 943fc954e4..baae655eb5 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceExplorer.tsx
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceExplorer.tsx
@@ -78,6 +78,7 @@ export default function PurchaseInvoiceExplorer() {
supplierUnitPrice: 0,
supplierShippingCost: 0,
supplierTaxAmount: 0,
+ taxPercent: 0,
exchangeRate: purchaseInvoiceData?.purchaseInvoice?.exchangeRate ?? 1
};
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx
index 3c1d6a5ca1..fd5d2e36db 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx
@@ -31,9 +31,9 @@ import {
useMount,
VStack
} from "@carbon/react";
-import { getItemReadableId } from "@carbon/utils";
+import { getItemReadableId, INPUT_FORMAT } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
-import { useEffect, useState } from "react";
+import { useState } from "react";
import { LuBox, LuChevronRight, LuLandmark, LuReceipt } from "react-icons/lu";
import { useParams } from "react-router";
import type { z } from "zod";
@@ -48,9 +48,12 @@ import {
NumberControlled,
StorageUnit,
Submit,
- UnitOfMeasure
+ TaxFields,
+ UnitOfMeasure,
+ useTaxPair
} from "~/components/Form";
import {
+ useCurrencyDecimals,
useCurrencyFormatter,
usePercentFormatter,
usePermissions,
@@ -95,11 +98,23 @@ const PurchaseInvoiceLineForm = ({
const routeData = useRouteData<{
purchaseInvoice: PurchaseInvoice;
+ currency: { decimalPlaces: number } | null;
}>(path.to.purchaseInvoice(invoiceId));
const isEditable = ["Draft"].includes(
routeData?.purchaseInvoice?.status ?? ""
);
+ // Settlement decimals come from the document currency's row (loader data);
+ // 2 is only the last resort for a currency-less document
+ // The loader's currency row is the primary source — it is correct on first
+ // paint, which matters because these formatters take part in the blur commit.
+ // The hook covers documents whose loader doesn't carry the row; the single
+ // documented last-resort lives inside it rather than as a literal here.
+ const invoiceCurrency =
+ routeData?.purchaseInvoice?.currencyCode ?? company.baseCurrencyCode;
+ const configuredDecimals = useCurrencyDecimals(invoiceCurrency);
+ const currencyDecimals =
+ routeData?.currency?.decimalPlaces ?? configuredDecimals;
const [lineType, setLineType] = useState<ItemType>(
initialValues.invoiceLineType as ItemType
@@ -137,23 +152,19 @@ const PurchaseInvoiceLineForm = ({
fallbackUnitPrice: initialValues.supplierUnitPrice ?? 0
});
- // update tax amount when quantity or unit price changes
- useEffect(() => {
- const subtotal =
- itemData.supplierUnitPrice * itemData.quantity +
- itemData.supplierShippingCost;
- if (itemData.taxPercent !== 0) {
- setItemData((d) => ({
- ...d,
- taxAmount: subtotal * itemData.taxPercent
- }));
- }
- }, [
- itemData.supplierUnitPrice,
- itemData.quantity,
- itemData.supplierShippingCost,
- itemData.taxPercent
- ]);
+ // Re-derive the tax amount when the line's base changes — never on mount, so
+ // a saved manual override survives being reopened.
+ const itemTax = useTaxPair({
+ unitPrice: itemData.supplierUnitPrice,
+ quantity: itemData.quantity,
+ shippingCost: itemData.supplierShippingCost,
+ percent: itemData.taxPercent,
+ amount: itemData.taxAmount,
+ currency: invoiceCurrency,
+ currencyDecimals,
+ onChange: ({ percent, amount }) =>
+ setItemData((d) => ({ ...d, taxPercent: percent, taxAmount: amount }))
+ });
const isEditing = initialValues.id !== undefined;
const isGLAccount = initialValues.invoiceLineType === "G/L Account";
@@ -227,22 +238,17 @@ const PurchaseInvoiceLineForm = ({
taxPercent: initialValues.taxPercent ?? 0
});
- useEffect(() => {
- const subtotal =
- indirectData.supplierUnitPrice * indirectData.quantity +
- indirectData.supplierShippingCost;
- if (indirectData.taxPercent !== 0) {
- setIndirectData((d) => ({
- ...d,
- taxAmount: subtotal * indirectData.taxPercent
- }));
- }
- }, [
- indirectData.supplierUnitPrice,
- indirectData.quantity,
- indirectData.supplierShippingCost,
- indirectData.taxPercent
- ]);
+ const indirectTax = useTaxPair({
+ unitPrice: indirectData.supplierUnitPrice,
+ quantity: indirectData.quantity,
+ shippingCost: indirectData.supplierShippingCost,
+ percent: indirectData.taxPercent,
+ amount: indirectData.taxAmount,
+ currency: invoiceCurrency,
+ currencyDecimals,
+ onChange: ({ percent, amount }) =>
+ setIndirectData((d) => ({ ...d, taxPercent: percent, taxAmount: amount }))
+ });
// Load price breaks
useMount(() => {
@@ -273,7 +279,17 @@ const PurchaseInvoiceLineForm = ({
? !permissions.can("update", "purchasing")
: !permissions.can("create", "purchasing");
- const currencyFormatter = useCurrencyFormatter();
+ // These badges render DOCUMENT-currency values, so both formatters take the
+ // document's currency and decimals. Defaulting to base currency is what
+ // printed a JPY shipping cost as "$20.00".
+ const currencyFormatter = useCurrencyFormatter({
+ currency: invoiceCurrency,
+ decimalPlaces: currencyDecimals
+ });
+ const priceFormatter = useCurrencyFormatter({
+ currency: invoiceCurrency,
+ decimalPlaces: currencyDecimals
+ });
const percentFormatter = usePercentFormatter();
const onTypeChange = (t: ItemType | "Item") => {
@@ -479,7 +495,7 @@ const PurchaseInvoiceLineForm = ({
{initialValues?.quantity}
</Badge>
<Badge variant="green">
- {currencyFormatter.format(
+ {priceFormatter.format(
(initialValues?.supplierUnitPrice ?? 0) +
(initialValues?.supplierShippingCost ?? 0)
)}{" "}
@@ -627,12 +643,10 @@ const PurchaseInvoiceLineForm = ({
name="supplierUnitPrice"
label={t`Supplier Unit Price`}
value={itemData.supplierUnitPrice}
- formatOptions={{
- style: "currency",
- currency:
- routeData?.purchaseInvoice?.currencyCode ??
- company.baseCurrencyCode
- }}
+ formatOptions={INPUT_FORMAT.price(
+ invoiceCurrency,
+ currencyDecimals
+ )}
onChange={(value) =>
setItemData((d) => ({
...d,
@@ -717,12 +731,10 @@ const PurchaseInvoiceLineForm = ({
label={t`Shipping`}
value={itemData.supplierShippingCost}
minValue={0}
- formatOptions={{
- style: "currency",
- currency:
- routeData?.purchaseInvoice?.currencyCode ??
- company.baseCurrencyCode
- }}
+ formatOptions={INPUT_FORMAT.money(
+ invoiceCurrency,
+ currencyDecimals
+ )}
onChange={(value) =>
setItemData((d) => ({
...d,
@@ -730,49 +742,10 @@ const PurchaseInvoiceLineForm = ({
}))
}
/>
- <NumberControlled
- name="supplierTaxAmount"
- label={t`Tax Amount`}
- value={itemData.taxAmount}
- formatOptions={{
- style: "currency",
- currency:
- routeData?.purchaseInvoice?.currencyCode ??
- company.baseCurrencyCode
- }}
- onChange={(value) => {
- const subtotal =
- itemData.supplierUnitPrice * itemData.quantity +
- itemData.supplierShippingCost;
- setItemData((d) => ({
- ...d,
- taxAmount: value,
- taxPercent: subtotal > 0 ? value / subtotal : 0
- }));
- }}
- />
- <NumberControlled
- name="taxPercent"
- label={t`Tax Percent`}
- value={itemData.taxPercent}
- minValue={0}
- maxValue={1}
- step={0.0001}
- formatOptions={{
- style: "percent",
- minimumFractionDigits: 0,
- maximumFractionDigits: 2
- }}
- onChange={(value) => {
- const subtotal =
- itemData.supplierUnitPrice * itemData.quantity +
- itemData.supplierShippingCost;
- setItemData((d) => ({
- ...d,
- taxPercent: value,
- taxAmount: subtotal * value
- }));
- }}
+ <TaxFields
+ {...itemTax}
+ amountName="supplierTaxAmount"
+ percentName="taxPercent"
/>
</div>
</div>
@@ -883,12 +856,10 @@ const PurchaseInvoiceLineForm = ({
label={t`Unit Price`}
isOptional={false}
value={indirectData.supplierUnitPrice}
- formatOptions={{
- style: "currency",
- currency:
- routeData?.purchaseInvoice?.currencyCode ??
- company.baseCurrencyCode
- }}
+ formatOptions={INPUT_FORMAT.price(
+ invoiceCurrency,
+ currencyDecimals
+ )}
onChange={(value) =>
setIndirectData((d) => ({
...d,
@@ -952,12 +923,10 @@ const PurchaseInvoiceLineForm = ({
label={t`Shipping`}
minValue={0}
value={indirectData.supplierShippingCost}
- formatOptions={{
- style: "currency",
- currency:
- routeData?.purchaseInvoice?.currencyCode ??
- company.baseCurrencyCode
- }}
+ formatOptions={INPUT_FORMAT.money(
+ invoiceCurrency,
+ currencyDecimals
+ )}
onChange={(value) =>
setIndirectData((d) => ({
...d,
@@ -965,51 +934,10 @@ const PurchaseInvoiceLineForm = ({
}))
}
/>
- <NumberControlled
- name="supplierTaxAmount"
- label={t`Tax Amount`}
- value={indirectData.taxAmount}
- formatOptions={{
- style: "currency",
- currency:
- routeData?.purchaseInvoice?.currencyCode ??
- company.baseCurrencyCode
- }}
- onChange={(value) => {
- const subtotal =
- indirectData.supplierUnitPrice *
- indirectData.quantity +
- indirectData.supplierShippingCost;
- setIndirectData((d) => ({
- ...d,
- taxAmount: value,
- taxPercent: subtotal > 0 ? value / subtotal : 0
- }));
- }}
- />
- <NumberControlled
- name="taxPercent"
- label={t`Tax Percent`}
- value={indirectData.taxPercent}
- minValue={0}
- maxValue={1}
- step={0.0001}
- formatOptions={{
- style: "percent",
- minimumFractionDigits: 0,
- maximumFractionDigits: 2
- }}
- onChange={(value) => {
- const subtotal =
- indirectData.supplierUnitPrice *
- indirectData.quantity +
- indirectData.supplierShippingCost;
- setIndirectData((d) => ({
- ...d,
- taxPercent: value,
- taxAmount: subtotal * value
- }));
- }}
+ <TaxFields
+ {...indirectTax}
+ amountName="supplierTaxAmount"
+ percentName="taxPercent"
/>
</div>
</div>
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsx
index a7f4cd8693..37ef87714f 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsx
@@ -28,9 +28,15 @@ import {
useMount,
VStack
} from "@carbon/react";
-import { getItemReadableId } from "@carbon/utils";
+import {
+ getItemReadableId,
+ INPUT_FORMAT,
+ INPUT_STEP,
+ taxableBase,
+ taxPairFromPercent
+} from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
-import { useEffect, useState } from "react";
+import { useState } from "react";
import {
LuBox,
LuChevronRight,
@@ -51,9 +57,12 @@ import {
NumberControlled,
SelectControlled,
StorageUnit,
- Submit
+ Submit,
+ TaxFields,
+ useTaxPair
} from "~/components/Form";
import {
+ useCurrencyDecimals,
useCurrencyFormatter,
usePercentFormatter,
usePermissions,
@@ -96,8 +105,21 @@ const SalesInvoiceLineForm = ({
const [items] = useItems();
const routeData = useRouteData<{
salesInvoice: SalesInvoice;
+ currency: { decimalPlaces: number } | null;
}>(path.to.salesInvoice(invoiceId));
+ // Settlement decimals come from the document currency's row (loader data);
+ // 2 is only the last resort for a currency-less document
+ // The loader's currency row is the primary source — it is correct on first
+ // paint, which matters because these formatters take part in the blur commit.
+ // The hook covers documents whose loader doesn't carry the row; the single
+ // documented last-resort lives inside it rather than as a literal here.
+ const invoiceCurrency =
+ routeData?.salesInvoice?.currencyCode ?? company.baseCurrencyCode;
+ const configuredDecimals = useCurrencyDecimals(invoiceCurrency);
+ const currencyDecimals =
+ routeData?.currency?.decimalPlaces ?? configuredDecimals;
+
const isLocked = isSalesInvoiceLocked(routeData?.salesInvoice?.status);
const isEditable = !isLocked;
@@ -125,29 +147,31 @@ const SalesInvoiceLineForm = ({
shippingCost: initialValues.shippingCost ?? 0,
unitOfMeasureCode: initialValues.unitOfMeasureCode ?? "",
storageUnitId: initialValues.storageUnitId ?? "",
- taxAmount:
- ((initialValues.unitPrice ?? 0) * (initialValues.quantity ?? 1) +
- (initialValues.shippingCost ?? 0)) *
- (initialValues.taxPercent ?? 0),
+ // Seeded through the same coupling every later edit uses, so the opening
+ // amount is rounded to the currency's decimals rather than a raw product.
+ taxAmount: taxPairFromPercent(
+ taxableBase(
+ initialValues.unitPrice ?? 0,
+ initialValues.quantity ?? 1,
+ initialValues.shippingCost ?? 0
+ ),
+ initialValues.taxPercent ?? 0,
+ currencyDecimals
+ ).amount,
taxPercent: initialValues.taxPercent ?? 0
});
- // update tax amount when quantity or unit price changes
- useEffect(() => {
- const subtotal =
- itemData.unitPrice * itemData.quantity + itemData.shippingCost;
- if (itemData.taxPercent !== 0) {
- setItemData((d) => ({
- ...d,
- taxAmount: subtotal * itemData.taxPercent
- }));
- }
- }, [
- itemData.unitPrice,
- itemData.quantity,
- itemData.shippingCost,
- itemData.taxPercent
- ]);
+ const itemTax = useTaxPair({
+ unitPrice: itemData.unitPrice,
+ quantity: itemData.quantity,
+ shippingCost: itemData.shippingCost,
+ percent: itemData.taxPercent,
+ amount: itemData.taxAmount,
+ currency: invoiceCurrency,
+ currencyDecimals,
+ onChange: ({ percent, amount }) =>
+ setItemData((d) => ({ ...d, taxPercent: percent, taxAmount: amount }))
+ });
const isFixedAsset = initialValues.invoiceLineType === "Fixed Asset";
const [activeTab, setActiveTab] = useState<"item" | "asset">(
@@ -345,12 +369,19 @@ const SalesInvoiceLineForm = ({
}));
};
- const currencyFormatter = useCurrencyFormatter();
+ // These badges render DOCUMENT-currency values, so both formatters take the
+ // document's currency and decimals. Defaulting to base currency is what
+ // printed a JPY shipping cost as "$20.00".
+ const currencyFormatter = useCurrencyFormatter({
+ currency: routeData?.salesInvoice?.currencyCode ?? company.baseCurrencyCode,
+ decimalPlaces: currencyDecimals
+ });
+ const priceFormatter = useCurrencyFormatter({
+ currency: routeData?.salesInvoice?.currencyCode ?? company.baseCurrencyCode,
+ decimalPlaces: currencyDecimals
+ });
const percentFormatter = usePercentFormatter();
- const invoiceCurrency =
- routeData?.salesInvoice?.currencyCode ?? company.baseCurrencyCode;
-
return (
<Tabs
value={activeTab}
@@ -423,7 +454,7 @@ const SalesInvoiceLineForm = ({
)}
</Badge>
<Badge variant="green">
- {currencyFormatter.format(
+ {priceFormatter.format(
initialValues?.unitPrice ?? 0
)}{" "}
{initialValues?.unitOfMeasureCode}
@@ -567,10 +598,10 @@ const SalesInvoiceLineForm = ({
name="unitPrice"
label={t`Unit Price`}
value={itemData.unitPrice}
- formatOptions={{
- style: "currency",
- currency: invoiceCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(
+ invoiceCurrency,
+ currencyDecimals
+ )}
onChange={(value) =>
setItemData((d) => ({
...d,
@@ -688,58 +719,20 @@ const SalesInvoiceLineForm = ({
costsDisclosure.isOpen ? "" : "hidden"
}`}
>
- <NumberControlled
- name="taxPercent"
- label={t`Tax Percent`}
- value={itemData.taxPercent}
- minValue={0}
- maxValue={1}
- step={0.0001}
- formatOptions={{
- style: "percent",
- minimumFractionDigits: 0,
- maximumFractionDigits: 2
- }}
- onChange={(value) => {
- const subtotal =
- itemData.unitPrice * itemData.quantity +
- itemData.shippingCost;
- setItemData((d) => ({
- ...d,
- taxPercent: value,
- taxAmount: subtotal * value
- }));
- }}
- />
- <NumberControlled
- name="taxAmount"
- label={t`Tax Amount`}
- value={itemData.taxAmount}
- formatOptions={{
- style: "currency",
- currency: invoiceCurrency
- }}
- onChange={(value) => {
- const subtotal =
- itemData.unitPrice * itemData.quantity +
- itemData.shippingCost;
- setItemData((d) => ({
- ...d,
- taxAmount: value,
- taxPercent:
- subtotal > 0 ? value / subtotal : 0
- }));
- }}
+ <TaxFields
+ {...itemTax}
+ amountName="taxAmount"
+ percentName="taxPercent"
/>
<NumberControlled
name="shippingCost"
label={t`Shipping Cost`}
value={itemData.shippingCost}
minValue={0}
- formatOptions={{
- style: "currency",
- currency: invoiceCurrency
- }}
+ formatOptions={INPUT_FORMAT.money(
+ invoiceCurrency,
+ currencyDecimals
+ )}
onChange={(value) =>
setItemData((d) => ({
...d,
@@ -750,18 +743,18 @@ const SalesInvoiceLineForm = ({
<Number
name="addOnCost"
label={t`Add-On Cost`}
- formatOptions={{
- style: "currency",
- currency: invoiceCurrency
- }}
+ formatOptions={INPUT_FORMAT.money(
+ invoiceCurrency,
+ currencyDecimals
+ )}
/>
<Number
name="nonTaxableAddOnCost"
label={t`Non-Taxable Add-On Cost`}
- formatOptions={{
- style: "currency",
- currency: invoiceCurrency
- }}
+ formatOptions={INPUT_FORMAT.money(
+ invoiceCurrency,
+ currencyDecimals
+ )}
/>
</div>
</div>
@@ -823,10 +816,10 @@ const SalesInvoiceLineForm = ({
label={t`Unit Price`}
isOptional={false}
value={assetData.unitPrice}
- formatOptions={{
- style: "currency",
- currency: invoiceCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(
+ invoiceCurrency,
+ currencyDecimals
+ )}
onChange={(value) =>
setAssetData((d) => ({ ...d, unitPrice: value }))
}
@@ -879,12 +872,8 @@ const SalesInvoiceLineForm = ({
value={assetData.taxPercent}
minValue={0}
maxValue={1}
- step={0.0001}
- formatOptions={{
- style: "percent",
- minimumFractionDigits: 0,
- maximumFractionDigits: 2
- }}
+ step={INPUT_STEP.rate}
+ formatOptions={INPUT_FORMAT.rate}
onChange={(value) =>
setAssetData((d) => ({
...d,
@@ -897,10 +886,10 @@ const SalesInvoiceLineForm = ({
label={t`Shipping Cost`}
value={assetData.shippingCost}
minValue={0}
- formatOptions={{
- style: "currency",
- currency: invoiceCurrency
- }}
+ formatOptions={INPUT_FORMAT.money(
+ invoiceCurrency,
+ currencyDecimals
+ )}
onChange={(value) =>
setAssetData((d) => ({
...d,
@@ -912,10 +901,10 @@ const SalesInvoiceLineForm = ({
name="addOnCost"
label={t`Add-On Cost`}
value={assetData.addOnCost}
- formatOptions={{
- style: "currency",
- currency: invoiceCurrency
- }}
+ formatOptions={INPUT_FORMAT.money(
+ invoiceCurrency,
+ currencyDecimals
+ )}
onChange={(value) =>
setAssetData((d) => ({
...d,
@@ -927,10 +916,10 @@ const SalesInvoiceLineForm = ({
name="nonTaxableAddOnCost"
label={t`Non-Taxable Add-On Cost`}
value={assetData.nonTaxableAddOnCost}
- formatOptions={{
- style: "currency",
- currency: invoiceCurrency
- }}
+ formatOptions={INPUT_FORMAT.money(
+ invoiceCurrency,
+ currencyDecimals
+ )}
onChange={(value) =>
setAssetData((d) => ({
...d,
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceShipmentForm.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceShipmentForm.tsx
index 05c1005be4..676079220b 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceShipmentForm.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceShipmentForm.tsx
@@ -6,6 +6,7 @@ import {
CardHeader,
CardTitle
} from "@carbon/react";
+import { INPUT_FORMAT } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { forwardRef, useImperativeHandle, useRef, useState } from "react";
import { useFetcher, useParams } from "react-router";
@@ -20,7 +21,7 @@ import {
ShippingMethod,
Submit
} from "~/components/Form";
-import { usePermissions, useRouteData } from "~/hooks";
+import { useCurrencyDecimals, usePermissions, useRouteData } from "~/hooks";
import type { SalesInvoice } from "~/modules/invoicing";
import { salesInvoiceShipmentValidator } from "~/modules/invoicing";
import { incoterms } from "~/modules/shared";
@@ -43,6 +44,8 @@ const SalesInvoiceShipmentForm = forwardRef<
SalesInvoiceShipmentFormProps
>(({ initialValues, currencyCode, defaultCollapsed = false }, ref) => {
const { t } = useLingui();
+ // Settlement amount — digits follow the document currency's own decimals.
+ const currencyDecimals = useCurrencyDecimals(currencyCode);
const { invoiceId } = useParams();
if (!invoiceId) {
throw new Error("invoiceId not found");
@@ -105,10 +108,7 @@ const SalesInvoiceShipmentForm = forwardRef<
name="shippingCost"
label={t`Shipping Cost`}
minValue={0}
- formatOptions={{
- style: "currency",
- currency: currencyCode
- }}
+ formatOptions={INPUT_FORMAT.money(currencyCode, currencyDecimals)}
ref={shippingCostRef}
/>
<Location
diff --git a/apps/erp/app/modules/items/ui/Consumables/ConsumableForm.tsx b/apps/erp/app/modules/items/ui/Consumables/ConsumableForm.tsx
index fe57e752b9..9f7cc324ff 100644
--- a/apps/erp/app/modules/items/ui/Consumables/ConsumableForm.tsx
+++ b/apps/erp/app/modules/items/ui/Consumables/ConsumableForm.tsx
@@ -11,6 +11,7 @@ import {
ModalCardTitle,
toast
} from "@carbon/react";
+import { INPUT_FORMAT } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { PostgrestResponse } from "@supabase/supabase-js";
import { useEffect, useState } from "react";
@@ -30,7 +31,12 @@ import {
UnitOfMeasure
} from "~/components/Form";
import { TrackingTypeIcon } from "~/components/Icons";
-import { useNextItemId, usePermissions, useUser } from "~/hooks";
+import {
+ useCurrencyDecimals,
+ useNextItemId,
+ usePermissions,
+ useUser
+} from "~/hooks";
import { path } from "~/utils/path";
import { consumableValidator, itemTrackingTypes } from "../../items.models";
import ItemStorageFields from "../Item/ItemStorageFields";
@@ -52,6 +58,7 @@ const ConsumableForm = ({
}: ConsumableFormProps) => {
const { company } = useUser();
const baseCurrency = company?.baseCurrencyCode ?? "USD";
+ const currencyDecimals = useCurrencyDecimals(baseCurrency);
const fetcher = useFetcher<PostgrestResponse<{ id: string }>>();
const { t } = useLingui();
@@ -185,10 +192,10 @@ const ConsumableForm = ({
<Number
name="unitCost"
label={t`Unit Cost`}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(
+ baseCurrency,
+ currencyDecimals
+ )}
minValue={0}
/>
)}
diff --git a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx
index c94618153f..70d7193d5d 100644
--- a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx
@@ -37,7 +37,7 @@ import {
VStack
} from "@carbon/react";
import { Editor } from "@carbon/react/Editor";
-import { getItemById } from "@carbon/utils";
+import { getItemById, INPUT_FORMAT } from "@carbon/utils";
import { getLocalTimeZone, today } from "@internationalized/date";
import { Trans, useLingui } from "@lingui/react/macro";
import type { DragControls } from "framer-motion";
@@ -113,7 +113,7 @@ import {
SortableListItemToggle
} from "~/components/SortableList";
import { StepLinkEditor } from "~/components/StepLinkEditor";
-import { usePermissions, useUser } from "~/hooks";
+import { useCurrencyDecimals, usePermissions, useUser } from "~/hooks";
import { useTags } from "~/hooks/useTags";
import type {
OperationParameter,
@@ -956,6 +956,7 @@ function OperationForm({
const { carbon } = useCarbon();
const baseCurrency = company?.baseCurrencyCode ?? "USD";
+ const currencyDecimals = useCurrencyDecimals(baseCurrency);
useEffect(() => {
// Remove from temporary items after successful submission
@@ -1183,10 +1184,7 @@ function OperationForm({
label={t`Minimum Cost`}
minValue={0}
value={processData.operationMinimumCost}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(baseCurrency, currencyDecimals)}
onChange={(newValue) =>
setProcessData((d) => ({
...d,
@@ -1199,10 +1197,7 @@ function OperationForm({
label={t`Unit Cost`}
minValue={0}
value={processData.operationUnitCost}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(baseCurrency, currencyDecimals)}
onChange={(newValue) =>
setProcessData((d) => ({
...d,
diff --git a/apps/erp/app/modules/items/ui/Item/ItemCostingForm.tsx b/apps/erp/app/modules/items/ui/Item/ItemCostingForm.tsx
index b8845bf516..71afa48abf 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemCostingForm.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemCostingForm.tsx
@@ -8,6 +8,7 @@ import {
CardTitle,
useDisclosure
} from "@carbon/react";
+import { INPUT_FORMAT } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { z } from "zod";
import {
@@ -19,7 +20,7 @@ import {
Submit
} from "~/components/Form";
import { Confirm } from "~/components/Modals";
-import { usePermissions, useUser } from "~/hooks";
+import { useCurrencyDecimals, usePermissions, useUser } from "~/hooks";
import { useItems } from "~/stores/items";
import { path } from "~/utils/path";
import { itemCostingMethods, itemCostValidator } from "../../items.models";
@@ -37,6 +38,7 @@ const ItemCostingForm = ({ initialValues }: ItemCostingFormProps) => {
const { t } = useLingui();
const { company } = useUser();
const baseCurrency = company?.baseCurrencyCode ?? "USD";
+ const currencyDecimals = useCurrencyDecimals(baseCurrency);
const recalculateModal = useDisclosure();
@@ -80,10 +82,7 @@ const ItemCostingForm = ({ initialValues }: ItemCostingFormProps) => {
<Number
name="unitCost"
label={t`Unit Cost`}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(baseCurrency, currencyDecimals)}
helperText={
replenishmentSystem === "Make"
? undefined
diff --git a/apps/erp/app/modules/items/ui/Item/ItemManufacturingForm.tsx b/apps/erp/app/modules/items/ui/Item/ItemManufacturingForm.tsx
index ff55f163e8..0299e720ef 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemManufacturingForm.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemManufacturingForm.tsx
@@ -6,6 +6,7 @@ import {
CardHeader,
CardTitle
} from "@carbon/react";
+import { INPUT_FORMAT } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { useFetcher, useParams } from "react-router";
import type { z } from "zod";
@@ -63,9 +64,7 @@ const ItemManufacturingForm = ({
name="scrapPercentage"
label={t`Scrap Percent`}
termId="item-scrap-percent"
- formatOptions={{
- style: "percent"
- }}
+ formatOptions={INPUT_FORMAT.rate}
/>
<Number
name="leadTime"
diff --git a/apps/erp/app/modules/items/ui/Item/ItemSalePriceForm.tsx b/apps/erp/app/modules/items/ui/Item/ItemSalePriceForm.tsx
index 6d863ae61c..e8c6ef87f6 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemSalePriceForm.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemSalePriceForm.tsx
@@ -6,10 +6,11 @@ import {
CardHeader,
CardTitle
} from "@carbon/react";
+import { INPUT_FORMAT } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { z } from "zod";
import { CustomFormFields, Hidden, Number, Submit } from "~/components/Form";
-import { usePermissions, useUser } from "~/hooks";
+import { useCurrencyDecimals, usePermissions, useUser } from "~/hooks";
import { itemUnitSalePriceValidator } from "../../items.models";
type ItemSalePriceFormProps = {
@@ -20,6 +21,9 @@ const ItemSalePriceForm = ({ initialValues }: ItemSalePriceFormProps) => {
const permissions = usePermissions();
const { t } = useLingui();
const { company } = useUser();
+ const currencyDecimals = useCurrencyDecimals(
+ company?.baseCurrencyCode ?? "USD"
+ );
return (
<Card>
@@ -40,10 +44,10 @@ const ItemSalePriceForm = ({ initialValues }: ItemSalePriceFormProps) => {
name="unitSalePrice"
label={t`Unit Sale Price`}
minValue={0}
- formatOptions={{
- style: "currency",
- currency: company?.baseCurrencyCode ?? "USD"
- }}
+ formatOptions={INPUT_FORMAT.price(
+ company?.baseCurrencyCode ?? "USD",
+ currencyDecimals
+ )}
/>
{/* <Currency
name="currencyCode"
diff --git a/apps/erp/app/modules/items/ui/Item/SupplierPartForm.tsx b/apps/erp/app/modules/items/ui/Item/SupplierPartForm.tsx
index 3baf0f7491..29bf3dd49b 100644
--- a/apps/erp/app/modules/items/ui/Item/SupplierPartForm.tsx
+++ b/apps/erp/app/modules/items/ui/Item/SupplierPartForm.tsx
@@ -36,6 +36,7 @@ import {
CarouselPrevious
} from "@carbon/react/Carousel";
+import { INPUT_FORMAT } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { ColumnDef } from "@tanstack/react-table";
import { useCallback, useEffect, useMemo, useState } from "react";
@@ -55,7 +56,12 @@ import {
UnitOfMeasure
} from "~/components/Form";
import Grid from "~/components/Grid";
-import { useCurrencyFormatter, usePermissions, useUser } from "~/hooks";
+import {
+ useCurrencyDecimals,
+ useCurrencyFormatter,
+ usePermissions,
+ useUser
+} from "~/hooks";
import { path } from "~/utils/path";
import { supplierPartValidator } from "../../items.models";
@@ -106,6 +112,7 @@ const SupplierPartForm = ({
const { company } = useUser();
const baseCurrency = company?.baseCurrencyCode ?? "USD";
+ const currencyDecimals = useCurrencyDecimals(baseCurrency);
let { itemId } = useParams();
@@ -184,10 +191,10 @@ const SupplierPartForm = ({
name="unitPrice"
label={t`Unit Price`}
minValue={0}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(
+ baseCurrency,
+ currencyDecimals
+ )}
/>
<UnitOfMeasure
name="supplierUnitOfMeasureCode"
@@ -261,6 +268,7 @@ function PurchaseHistory({
baseCurrency: string;
}) {
const { t } = useLingui();
+ const priceFormatter = useCurrencyFormatter({ currency: baseCurrency });
if (history.length === 0) return null;
return (
@@ -319,10 +327,7 @@ function PurchaseHistory({
<Tr>
<Td>{line.purchaseQuantity}</Td>
<Td>
- {new Intl.NumberFormat("en-US", {
- style: "currency",
- currency: baseCurrency
- }).format(line.unitPrice ?? 0)}
+ {priceFormatter.format(line.unitPrice ?? 0)}
</Td>
</Tr>
</Tbody>
@@ -356,6 +361,7 @@ function PriceBreaks({
baseCurrency: string;
isDisabled: boolean;
}) {
+ const currencyDecimals = useCurrencyDecimals(baseCurrency);
const { t } = useLingui();
const formatter = useCurrencyFormatter();
@@ -386,10 +392,10 @@ function PriceBreaks({
() => ({
quantity: EditableNumber(noOpMutation),
unitPrice: EditableNumber(noOpMutation, {
- formatOptions: { style: "currency", currency: baseCurrency }
+ formatOptions: INPUT_FORMAT.price(baseCurrency, currencyDecimals)
})
}),
- [noOpMutation, baseCurrency]
+ [noOpMutation, baseCurrency, currencyDecimals]
);
const columns = useMemo<ColumnDef<PriceBreakRow>[]>(
diff --git a/apps/erp/app/modules/items/ui/Materials/MaterialForm.tsx b/apps/erp/app/modules/items/ui/Materials/MaterialForm.tsx
index 3cb3fba67b..9e84df54b1 100644
--- a/apps/erp/app/modules/items/ui/Materials/MaterialForm.tsx
+++ b/apps/erp/app/modules/items/ui/Materials/MaterialForm.tsx
@@ -11,7 +11,11 @@ import {
ModalCardTitle,
toast
} from "@carbon/react";
-import { getMaterialDescription, getMaterialId } from "@carbon/utils";
+import {
+ getMaterialDescription,
+ getMaterialId,
+ INPUT_FORMAT
+} from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { PostgrestResponse } from "@supabase/supabase-js";
import { useEffect, useState } from "react";
@@ -37,7 +41,12 @@ import MaterialGrade from "~/components/Form/MaterialGrade";
import MaterialType, { useMaterialTypes } from "~/components/Form/MaterialType";
import Shape, { useShape } from "~/components/Form/Shape";
import Substance, { useSubstance } from "~/components/Form/Substance";
-import { useNextItemId, usePermissions, useUser } from "~/hooks";
+import {
+ useCurrencyDecimals,
+ useNextItemId,
+ usePermissions,
+ useUser
+} from "~/hooks";
import { useSettings } from "~/hooks/useSettings";
import { path } from "~/utils/path";
import {
@@ -84,6 +93,7 @@ const MaterialForm = ({
const { company } = useUser();
const baseCurrency = company?.baseCurrencyCode ?? "USD";
+ const currencyDecimals = useCurrencyDecimals(baseCurrency);
const fetcher = useFetcher<PostgrestResponse<{ id: string }>>();
const materialTypes = useMaterialTypes(substanceId, formId);
@@ -311,10 +321,10 @@ const MaterialForm = ({
<Number
name="unitCost"
label={t`Unit Cost`}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(
+ baseCurrency,
+ currencyDecimals
+ )}
minValue={0}
/>
diff --git a/apps/erp/app/modules/items/ui/Parts/PartForm.tsx b/apps/erp/app/modules/items/ui/Parts/PartForm.tsx
index d3934abc15..f032f4d16b 100644
--- a/apps/erp/app/modules/items/ui/Parts/PartForm.tsx
+++ b/apps/erp/app/modules/items/ui/Parts/PartForm.tsx
@@ -18,6 +18,7 @@ import {
import {
convertKbToString,
getFileSizeLimit,
+ INPUT_FORMAT,
supportedModelTypes
} from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
@@ -46,6 +47,7 @@ import {
import { ReplenishmentSystemIcon } from "~/components/Icons";
import { ModelUploadProgress } from "~/components/ModelUploadProgress";
import {
+ useCurrencyDecimals,
useModelUpload,
useNextItemId,
usePermissions,
@@ -75,6 +77,7 @@ const PartForm = ({ initialValues, type = "card", onClose }: PartFormProps) => {
const { t } = useLingui();
const { company } = useUser();
const baseCurrency = company?.baseCurrencyCode ?? "USD";
+ const currencyDecimals = useCurrencyDecimals(baseCurrency);
const fetcher = useFetcher<PostgrestResponse<{ id: string }>>();
@@ -338,10 +341,10 @@ const PartForm = ({ initialValues, type = "card", onClose }: PartFormProps) => {
<Number
name="unitCost"
label={t`Unit Cost`}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(
+ baseCurrency,
+ currencyDecimals
+ )}
minValue={0}
/>
)}
diff --git a/apps/erp/app/modules/items/ui/Tools/ToolForm.tsx b/apps/erp/app/modules/items/ui/Tools/ToolForm.tsx
index ba09d47c8e..7ec4986833 100644
--- a/apps/erp/app/modules/items/ui/Tools/ToolForm.tsx
+++ b/apps/erp/app/modules/items/ui/Tools/ToolForm.tsx
@@ -18,6 +18,7 @@ import {
import {
convertKbToString,
getFileSizeLimit,
+ INPUT_FORMAT,
supportedModelTypes
} from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
@@ -45,6 +46,7 @@ import {
import { ReplenishmentSystemIcon, TrackingTypeIcon } from "~/components/Icons";
import { ModelUploadProgress } from "~/components/ModelUploadProgress";
import {
+ useCurrencyDecimals,
useModelUpload,
useNextItemId,
usePermissions,
@@ -74,6 +76,7 @@ const ToolForm = ({ initialValues, type = "card", onClose }: ToolFormProps) => {
const { t } = useLingui();
const { company } = useUser();
const baseCurrency = company?.baseCurrencyCode ?? "USD";
+ const currencyDecimals = useCurrencyDecimals(baseCurrency);
const fetcher = useFetcher<PostgrestResponse<{ id: string }>>();
@@ -330,10 +333,10 @@ const ToolForm = ({ initialValues, type = "card", onClose }: ToolFormProps) => {
<Number
name="unitCost"
label={t`Unit Cost`}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(
+ baseCurrency,
+ currencyDecimals
+ )}
minValue={0}
isReadOnly={replenishmentSystem === "Make"}
/>
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index b7198cb87b..40162223a3 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -5,7 +5,7 @@ import { ASSEMBLER_SERVICE_API_KEY, ASSEMBLER_SERVICE_URL } from "@carbon/env";
import { raiseMoment } from "@carbon/lib/workflows";
import { getLogger } from "@carbon/logger";
import type { JSONContent } from "@carbon/react";
-import { nameSimilarity, tiptapToText } from "@carbon/utils";
+import { nameSimilarity, scrapAllowance, tiptapToText } from "@carbon/utils";
import type {
AssemblyGraph,
AssemblyGraphIndex,
@@ -235,8 +235,7 @@ export async function convertSalesOrderLinesToJobs(
// Calculate scrap quantity based on item's scrap percentage
const scrapPercentage = manufacturing.data?.scrapPercentage ?? 0;
- const scrapQuantity =
- scrapPercentage > 0 ? Math.ceil(jobQuantity * scrapPercentage) : 0;
+ const scrapQuantity = scrapAllowance(jobQuantity, scrapPercentage);
const data = {
customerId: salesOrder.data?.customerId ?? undefined,
@@ -2867,8 +2866,7 @@ export async function insertJob(
input.companyId
));
- const scrapQuantity =
- scrapPercentage > 0 ? Math.ceil(input.quantity * scrapPercentage) : 0;
+ const scrapQuantity = scrapAllowance(input.quantity, scrapPercentage);
const job = await client
.from("job")
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
index 2831284672..d4f3c5492c 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
@@ -27,7 +27,7 @@ import {
useDisclosure,
VStack
} from "@carbon/react";
-import { getItemReadableId } from "@carbon/utils";
+import { getItemReadableId, INPUT_FORMAT } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { motion } from "framer-motion";
import { nanoid } from "nanoid";
@@ -74,7 +74,13 @@ import {
SortableListItemPanel,
SortableListItemToggle
} from "~/components/SortableList";
-import { usePermissions, useRouteData, useUrlParams, useUser } from "~/hooks";
+import {
+ useCurrencyDecimals,
+ usePermissions,
+ useRouteData,
+ useUrlParams,
+ useUser
+} from "~/hooks";
import { ItemTrackingType } from "~/modules/items";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
import type { MethodItemType, MethodType } from "~/modules/shared";
@@ -622,6 +628,7 @@ function MaterialForm({
const { company } = useUser();
const baseCurrency = company?.baseCurrencyCode ?? "USD";
+ const currencyDecimals = useCurrencyDecimals(baseCurrency);
useEffect(() => {
// Remove from temporary items after successful submission
@@ -835,10 +842,7 @@ function MaterialForm({
label={t`Unit Cost`}
value={itemData.unitCost}
minValue={0}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(baseCurrency, currencyDecimals)}
/>
)}
</div>
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
index 1a45113290..96a1d8d8aa 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
@@ -49,7 +49,7 @@ import {
VStack
} from "@carbon/react";
import { Editor } from "@carbon/react/Editor";
-import { formatDurationMilliseconds } from "@carbon/utils";
+import { formatDurationMilliseconds, INPUT_FORMAT } from "@carbon/utils";
import { getLocalTimeZone, today } from "@internationalized/date";
import { Trans, useLingui } from "@lingui/react/macro";
import { useNumberFormatter } from "@react-aria/i18n";
@@ -130,7 +130,13 @@ import {
SortableListItemToggle
} from "~/components/SortableList";
import { StepLinkEditor } from "~/components/StepLinkEditor";
-import { usePermissions, useRouteData, useUrlParams, useUser } from "~/hooks";
+import {
+ useCurrencyDecimals,
+ usePermissions,
+ useRouteData,
+ useUrlParams,
+ useUser
+} from "~/hooks";
import type {
OperationParameter,
OperationStep,
@@ -2724,6 +2730,7 @@ function OperationForm({
}>();
const { carbon } = useCarbon();
const baseCurrency = company?.baseCurrencyCode ?? "USD";
+ const currencyDecimals = useCurrencyDecimals(baseCurrency);
useEffect(() => {
if (fetcher.data?.id) {
@@ -2997,10 +3004,7 @@ function OperationForm({
label={t`Minimum Cost`}
minValue={0}
value={processData.operationMinimumCost}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(baseCurrency, currencyDecimals)}
onChange={(newValue) =>
setProcessData((d) => ({
...d,
@@ -3013,10 +3017,7 @@ function OperationForm({
label={t`Unit Cost`}
minValue={0}
value={processData.operationUnitCost}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(baseCurrency, currencyDecimals)}
onChange={(newValue) =>
setProcessData((d) => ({
...d,
@@ -3366,10 +3367,10 @@ function OperationForm({
label={t`Labor Rate`}
minValue={0}
value={processData.laborRate}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(
+ baseCurrency,
+ currencyDecimals
+ )}
onChange={(newValue) =>
setProcessData((d) => ({
...d,
@@ -3383,10 +3384,10 @@ function OperationForm({
label={t`Machine Rate`}
minValue={0}
value={processData.machineRate}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(
+ baseCurrency,
+ currencyDecimals
+ )}
onChange={(newValue) =>
setProcessData((d) => ({
...d,
@@ -3400,10 +3401,10 @@ function OperationForm({
label={t`Overhead Rate`}
minValue={0}
value={processData.overheadRate}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(
+ baseCurrency,
+ currencyDecimals
+ )}
onChange={(newValue) =>
setProcessData((d) => ({
...d,
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobForm.tsx b/apps/erp/app/modules/production/ui/Jobs/JobForm.tsx
index 4ff401184f..7352df93b1 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobForm.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobForm.tsx
@@ -17,6 +17,7 @@ import {
useDisclosure,
VStack
} from "@carbon/react";
+import { scrapAllowance } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { useState } from "react";
import { LuDiamond, LuLayers } from "react-icons/lu";
@@ -180,9 +181,9 @@ const JobForm = ({ initialValues }: JobFormProps) => {
: (manufacturing?.data?.lotSize ?? 0),
modelUploadId: item.data?.modelUploadId ?? null,
scrapPercentage: manufacturing?.data?.scrapPercentage ?? 0,
- scrapQuantity: Math.ceil(
- (manufacturing?.data?.lotSize ?? 0) *
- (manufacturing?.data?.scrapPercentage ?? 0)
+ scrapQuantity: scrapAllowance(
+ manufacturing?.data?.lotSize ?? 0,
+ manufacturing?.data?.scrapPercentage ?? 0
)
}));
@@ -317,8 +318,9 @@ const JobForm = ({ initialValues }: JobFormProps) => {
setItemData((prev) => ({
...prev,
quantity: value,
- scrapQuantity: Math.ceil(
- value * prev.scrapPercentage
+ scrapQuantity: scrapAllowance(
+ value,
+ prev.scrapPercentage
)
}))
}
diff --git a/apps/erp/app/modules/purchasing/purchasing.models.ts b/apps/erp/app/modules/purchasing/purchasing.models.ts
index 669ce47a6f..11cea52704 100644
--- a/apps/erp/app/modules/purchasing/purchasing.models.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.models.ts
@@ -233,7 +233,8 @@ export const purchaseOrderLineValidator = z
supplierPartId: zfd.text(z.string().optional()),
supplierShippingCost: zfd.numeric(z.number().optional()),
supplierTaxAmount: zfd.numeric(z.number().optional()),
- supplierUnitPrice: zfd.numeric(z.number().optional())
+ supplierUnitPrice: zfd.numeric(z.number().optional()),
+ taxPercent: zfd.numeric(z.number().min(0).max(1).optional().default(0))
})
.refine(
(data) =>
@@ -321,6 +322,9 @@ export const selectedLineSchema = z.object({
supplierShippingCost: z.number(),
supplierUnitPrice: z.number(),
supplierTaxAmount: z.number(),
+ // Same 0..1 fraction contract as purchaseOrderLineValidator — the two feed the
+ // same columns, so an unbounded rate here would bypass the form's bound.
+ taxPercent: z.number().min(0).max(1).optional().default(0),
unitPrice: z.number()
});
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index 21caab904f..091f42b298 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -135,6 +135,7 @@ export async function duplicatePurchaseOrder(
"id, supplierId, supplierContactId, supplierLocationId, supplierReference, currencyCode, purchaseOrderType, internalNotes, externalNotes"
)
.eq("id", sourcePurchaseOrderId)
+ .eq("companyId", companyId)
.single(),
client
.from("purchaseOrderDelivery")
@@ -144,9 +145,10 @@ export async function duplicatePurchaseOrder(
client
.from("purchaseOrderLine")
.select(
- "purchaseOrderLineType, itemId, assetId, description, purchaseQuantity, supplierUnitPrice, inventoryUnitOfMeasureCode, purchaseUnitOfMeasureCode, locationId, storageUnitId, setupPrice, customFields, conversionFactor, tags, internalNotes, externalNotes, exchangeRate, supplierShippingCost, modelUploadId, supplierTaxAmount, jobId, jobOperationId, promisedDate, requiredDate, accountId, costCenterId, ownerId, sortOrder, supplierPartId"
+ "purchaseOrderLineType, itemId, assetId, description, purchaseQuantity, supplierUnitPrice, inventoryUnitOfMeasureCode, purchaseUnitOfMeasureCode, locationId, storageUnitId, setupPrice, customFields, conversionFactor, tags, internalNotes, externalNotes, exchangeRate, supplierShippingCost, modelUploadId, supplierTaxAmount, taxPercent, jobId, jobOperationId, promisedDate, requiredDate, accountId, costCenterId, ownerId, sortOrder, supplierPartId"
)
.eq("purchaseOrderId", sourcePurchaseOrderId)
+ .eq("companyId", companyId)
]);
if (source.error || !source.data) {
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDeliveryForm.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDeliveryForm.tsx
index a2c539ff4d..c34425a6f9 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDeliveryForm.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDeliveryForm.tsx
@@ -6,6 +6,7 @@ import {
CardHeader,
CardTitle
} from "@carbon/react";
+import { INPUT_FORMAT } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { forwardRef, useImperativeHandle, useRef, useState } from "react";
import { useFetcher, useParams } from "react-router";
@@ -24,7 +25,7 @@ import {
ShippingMethod,
Submit
} from "~/components/Form";
-import { usePermissions, useRouteData } from "~/hooks";
+import { useCurrencyDecimals, usePermissions, useRouteData } from "~/hooks";
import type { PurchaseOrder } from "~/modules/purchasing";
import {
isPurchaseOrderLocked,
@@ -60,6 +61,8 @@ const PurchaseOrderDeliveryForm = forwardRef<
const isLocked = isPurchaseOrderLocked(routeData?.purchaseOrder?.status);
const { t } = useLingui();
+ // Settlement amount — digits follow the document currency's own decimals.
+ const currencyDecimals = useCurrencyDecimals(currencyCode);
const permissions = usePermissions();
const fetcher = useFetcher<typeof action>();
const [dropShip, setDropShip] = useState<boolean>(
@@ -116,10 +119,7 @@ const PurchaseOrderDeliveryForm = forwardRef<
name="supplierShippingCost"
label={t`Shipping Cost`}
minValue={0}
- formatOptions={{
- style: "currency",
- currency: currencyCode
- }}
+ formatOptions={INPUT_FORMAT.money(currencyCode, currencyDecimals)}
ref={shippingCostRef}
/>
<Location
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx
index c08eb363ff..1895a4ebb9 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx
@@ -75,6 +75,7 @@ export default function PurchaseOrderExplorer() {
locationId:
purchaseOrderData?.purchaseOrder?.locationId ?? defaults.locationId ?? "",
supplierTaxAmount: 0,
+ taxPercent: 0,
supplierShippingCost: 0,
exchangeRate: purchaseOrderData?.purchaseOrder?.exchangeRate ?? 1
};
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx
index c6310381f9..30c84fcd6c 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx
@@ -31,7 +31,7 @@ import {
useMount,
VStack
} from "@carbon/react";
-import { getItemReadableId } from "@carbon/utils";
+import { getItemReadableId, INPUT_FORMAT } from "@carbon/utils";
import { getLocalTimeZone, today } from "@internationalized/date";
import { Trans, useLingui } from "@lingui/react/macro";
import type { PostgrestResponse } from "@supabase/supabase-js";
@@ -51,10 +51,13 @@ import {
NumberControlled,
StorageUnit,
Submit,
- UnitOfMeasure
+ TaxFields,
+ UnitOfMeasure,
+ useTaxPair
} from "~/components/Form";
import { itemTypeLabel } from "~/components/Form/itemTypeLabel";
import {
+ useCurrencyDecimals,
useCurrencyFormatter,
usePercentFormatter,
usePermissions,
@@ -86,22 +89,6 @@ type PurchaseOrderLineFormProps = {
onClose?: () => void;
};
-const getLineSubtotal = (
- unitPrice: number,
- quantity: number,
- shippingCost: number
-) => unitPrice * quantity + shippingCost;
-
-const getLineTaxPercent = (
- unitPrice: number,
- quantity: number,
- shippingCost: number,
- taxAmount: number
-) => {
- const subtotal = getLineSubtotal(unitPrice, quantity, shippingCost);
- return subtotal > 0 ? taxAmount / subtotal : 0;
-};
-
const PurchaseOrderLineForm = ({
initialValues,
type,
@@ -119,8 +106,21 @@ const PurchaseOrderLineForm = ({
const routeData = useRouteData<{
purchaseOrder: PurchaseOrder;
+ currency: { decimalPlaces: number } | null;
}>(path.to.purchaseOrder(orderId));
+ // Settlement decimals come from the document currency's row (loader data);
+ // 2 is only the last resort for a currency-less document
+ // The loader's currency row is the primary source — it is correct on first
+ // paint, which matters because these formatters take part in the blur commit.
+ // The hook covers documents whose loader doesn't carry the row; the single
+ // documented last-resort lives inside it rather than as a literal here.
+ const orderCurrency =
+ routeData?.purchaseOrder?.currencyCode ?? company.baseCurrencyCode;
+ const configuredDecimals = useCurrencyDecimals(orderCurrency);
+ const currencyDecimals =
+ routeData?.currency?.decimalPlaces ?? configuredDecimals;
+
const isOutsideProcessing =
routeData?.purchaseOrder?.purchaseOrderType === "Outside Processing";
const isLocked = isPurchaseOrderLocked(routeData?.purchaseOrder?.status);
@@ -162,33 +162,24 @@ const PurchaseOrderLineForm = ({
supplierShippingCost: initialValues.supplierShippingCost ?? 0,
supplierTaxAmount: initialValues.supplierTaxAmount ?? 0,
supplierUnitPrice: initialValues.supplierUnitPrice ?? 0,
- taxPercent: getLineTaxPercent(
- initialValues.supplierUnitPrice ?? 0,
- initialValues.purchaseQuantity ?? 1,
- initialValues.supplierShippingCost ?? 0,
- initialValues.supplierTaxAmount ?? 0
- )
+ taxPercent: initialValues.taxPercent ?? 0
});
- // update tax amount when quantity or unit price changes
- useEffect(() => {
- const subtotal = getLineSubtotal(
- itemData.supplierUnitPrice,
- itemData.purchaseQuantity,
- itemData.supplierShippingCost
- );
- if (itemData.taxPercent !== 0) {
+ const itemTax = useTaxPair({
+ unitPrice: itemData.supplierUnitPrice,
+ quantity: itemData.purchaseQuantity,
+ shippingCost: itemData.supplierShippingCost,
+ percent: itemData.taxPercent,
+ amount: itemData.supplierTaxAmount,
+ currency: orderCurrency,
+ currencyDecimals,
+ onChange: ({ percent, amount }) =>
setItemData((d) => ({
...d,
- supplierTaxAmount: subtotal * itemData.taxPercent
- }));
- }
- }, [
- itemData.supplierUnitPrice,
- itemData.purchaseQuantity,
- itemData.supplierShippingCost,
- itemData.taxPercent
- ]);
+ taxPercent: percent,
+ supplierTaxAmount: amount
+ }))
+ });
const isEditing = initialValues.id !== undefined;
const isGLAccount = initialValues.purchaseOrderLineType === "G/L Account";
@@ -218,32 +209,24 @@ const PurchaseOrderLineForm = ({
supplierUnitPrice: initialValues.supplierUnitPrice ?? 0,
supplierShippingCost: initialValues.supplierShippingCost ?? 0,
supplierTaxAmount: initialValues.supplierTaxAmount ?? 0,
- taxPercent: getLineTaxPercent(
- initialValues.supplierUnitPrice ?? 0,
- initialValues.purchaseQuantity ?? 1,
- initialValues.supplierShippingCost ?? 0,
- initialValues.supplierTaxAmount ?? 0
- )
+ taxPercent: initialValues.taxPercent ?? 0
});
- useEffect(() => {
- const subtotal = getLineSubtotal(
- indirectData.supplierUnitPrice,
- indirectData.purchaseQuantity,
- indirectData.supplierShippingCost
- );
- if (indirectData.taxPercent !== 0) {
+ const indirectTax = useTaxPair({
+ unitPrice: indirectData.supplierUnitPrice,
+ quantity: indirectData.purchaseQuantity,
+ shippingCost: indirectData.supplierShippingCost,
+ percent: indirectData.taxPercent,
+ amount: indirectData.supplierTaxAmount,
+ currency: orderCurrency,
+ currencyDecimals,
+ onChange: ({ percent, amount }) =>
setIndirectData((d) => ({
...d,
- supplierTaxAmount: subtotal * indirectData.taxPercent
- }));
- }
- }, [
- indirectData.supplierUnitPrice,
- indirectData.purchaseQuantity,
- indirectData.supplierShippingCost,
- indirectData.taxPercent
- ]);
+ taxPercent: percent,
+ supplierTaxAmount: amount
+ }))
+ });
const costsDisclosure = useDisclosure();
const indirectCostsDisclosure = useDisclosure();
@@ -316,7 +299,17 @@ const PurchaseOrderLineForm = ({
: !permissions.can("create", "purchasing");
const deleteDisclosure = useDisclosure();
- const currencyFormatter = useCurrencyFormatter();
+ // These badges render DOCUMENT-currency values, so both formatters take the
+ // document's currency and decimals. Defaulting to base currency is what
+ // printed a JPY shipping cost as "$20.00".
+ const currencyFormatter = useCurrencyFormatter({
+ currency: orderCurrency,
+ decimalPlaces: currencyDecimals
+ });
+ const priceFormatter = useCurrencyFormatter({
+ currency: orderCurrency,
+ decimalPlaces: currencyDecimals
+ });
const percentFormatter = usePercentFormatter();
const onTypeChange = (t: ItemType | "Item") => {
@@ -461,12 +454,7 @@ const PurchaseOrderLineForm = ({
}));
};
- const collapsedTaxPercent = getLineTaxPercent(
- initialValues?.supplierUnitPrice ?? 0,
- initialValues?.purchaseQuantity ?? 1,
- initialValues?.supplierShippingCost ?? 0,
- initialValues?.supplierTaxAmount ?? 0
- );
+ const collapsedTaxPercent = initialValues?.taxPercent ?? 0;
return (
<>
@@ -555,7 +543,7 @@ const PurchaseOrderLineForm = ({
{initialValues?.purchaseQuantity}
</Badge>
<Badge variant="green">
- {currencyFormatter.format(
+ {priceFormatter.format(
(initialValues?.supplierUnitPrice ?? 0) +
(initialValues?.supplierShippingCost ?? 0)
)}{" "}
@@ -724,12 +712,10 @@ const PurchaseOrderLineForm = ({
name="supplierUnitPrice"
label={t`Unit Price`}
value={itemData.supplierUnitPrice}
- formatOptions={{
- style: "currency",
- currency:
- routeData?.purchaseOrder?.currencyCode ??
- company.baseCurrencyCode
- }}
+ formatOptions={INPUT_FORMAT.price(
+ orderCurrency,
+ currencyDecimals
+ )}
onChange={(value) =>
setItemData((d) => ({
...d,
@@ -834,12 +820,10 @@ const PurchaseOrderLineForm = ({
termId="purchase-order-line-shipping"
minValue={0}
value={itemData.supplierShippingCost}
- formatOptions={{
- style: "currency",
- currency:
- routeData?.purchaseOrder?.currencyCode ??
- company.baseCurrencyCode
- }}
+ formatOptions={INPUT_FORMAT.money(
+ orderCurrency,
+ currencyDecimals
+ )}
onChange={(value) =>
setItemData((d) => ({
...d,
@@ -847,51 +831,10 @@ const PurchaseOrderLineForm = ({
}))
}
/>
- <NumberControlled
- name="supplierTaxAmount"
- label={t`Tax Amount`}
- value={itemData.supplierTaxAmount}
- formatOptions={{
- style: "currency",
- currency:
- routeData?.purchaseOrder?.currencyCode ??
- company.baseCurrencyCode
- }}
- onChange={(value) => {
- const subtotal =
- itemData.supplierUnitPrice *
- itemData.purchaseQuantity +
- itemData.supplierShippingCost;
- setItemData((d) => ({
- ...d,
- supplierTaxAmount: value,
- taxPercent: subtotal > 0 ? value / subtotal : 0
- }));
- }}
- />
- <NumberControlled
- name="taxPercent"
- label={t`Tax Percent`}
- value={itemData.taxPercent}
- minValue={0}
- maxValue={1}
- step={0.0001}
- formatOptions={{
- style: "percent",
- minimumFractionDigits: 0,
- maximumFractionDigits: 2
- }}
- onChange={(value) => {
- const subtotal =
- itemData.supplierUnitPrice *
- itemData.purchaseQuantity +
- itemData.supplierShippingCost;
- setItemData((d) => ({
- ...d,
- taxPercent: value,
- supplierTaxAmount: subtotal * value
- }));
- }}
+ <TaxFields
+ {...itemTax}
+ amountName="supplierTaxAmount"
+ percentName="taxPercent"
/>
</div>
</div>
@@ -1014,12 +957,10 @@ const PurchaseOrderLineForm = ({
label={t`Unit Price`}
isOptional={false}
value={indirectData.supplierUnitPrice}
- formatOptions={{
- style: "currency",
- currency:
- routeData?.purchaseOrder?.currencyCode ??
- company.baseCurrencyCode
- }}
+ formatOptions={INPUT_FORMAT.price(
+ orderCurrency,
+ currencyDecimals
+ )}
onChange={(value) =>
setIndirectData((d) => ({
...d,
@@ -1084,12 +1025,10 @@ const PurchaseOrderLineForm = ({
termId="purchase-order-line-shipping"
minValue={0}
value={indirectData.supplierShippingCost}
- formatOptions={{
- style: "currency",
- currency:
- routeData?.purchaseOrder?.currencyCode ??
- company.baseCurrencyCode
- }}
+ formatOptions={INPUT_FORMAT.money(
+ orderCurrency,
+ currencyDecimals
+ )}
onChange={(value) =>
setIndirectData((d) => ({
...d,
@@ -1097,52 +1036,10 @@ const PurchaseOrderLineForm = ({
}))
}
/>
- <NumberControlled
- name="supplierTaxAmount"
- label={t`Tax Amount`}
- value={indirectData.supplierTaxAmount}
- formatOptions={{
- style: "currency",
- currency:
- routeData?.purchaseOrder?.currencyCode ??
- company.baseCurrencyCode
- }}
- onChange={(value) => {
- const subtotal =
- indirectData.supplierUnitPrice *
- indirectData.purchaseQuantity +
- indirectData.supplierShippingCost;
- setIndirectData((d) => ({
- ...d,
- supplierTaxAmount: value,
- taxPercent:
- subtotal > 0 ? value / subtotal : 0
- }));
- }}
- />
- <NumberControlled
- name="taxPercent"
- label={t`Tax Percent`}
- value={indirectData.taxPercent}
- minValue={0}
- maxValue={1}
- step={0.0001}
- formatOptions={{
- style: "percent",
- minimumFractionDigits: 0,
- maximumFractionDigits: 2
- }}
- onChange={(value) => {
- const subtotal =
- indirectData.supplierUnitPrice *
- indirectData.purchaseQuantity +
- indirectData.supplierShippingCost;
- setIndirectData((d) => ({
- ...d,
- taxPercent: value,
- supplierTaxAmount: subtotal * value
- }));
- }}
+ <TaxFields
+ {...indirectTax}
+ amountName="supplierTaxAmount"
+ percentName="taxPercent"
/>
</div>
</div>
diff --git a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierProcessForm.tsx b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierProcessForm.tsx
index c11a8210b6..2fba3557ca 100644
--- a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierProcessForm.tsx
+++ b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierProcessForm.tsx
@@ -12,6 +12,7 @@ import {
toast,
VStack
} from "@carbon/react";
+import { INPUT_FORMAT } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { PostgrestResponse } from "@supabase/supabase-js";
import { useEffect, useState } from "react";
@@ -25,7 +26,7 @@ import {
Submit,
Supplier
} from "~/components/Form";
-import { usePermissions, useUser } from "~/hooks";
+import { useCurrencyDecimals, usePermissions, useUser } from "~/hooks";
import type { SupplierProcess } from "~/modules/purchasing";
import { supplierProcessValidator } from "~/modules/purchasing";
import { path } from "~/utils/path";
@@ -52,6 +53,7 @@ const SupplierProcessForm = ({
const { company } = useUser();
const baseCurrency = company?.baseCurrencyCode ?? "USD";
+ const currencyDecimals = useCurrencyDecimals(baseCurrency);
useEffect(() => {
if (type !== "modal") return;
@@ -118,10 +120,10 @@ const SupplierProcessForm = ({
<Number
name="minimumCost"
label={t`Minimum Cost`}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(
+ baseCurrency,
+ currencyDecimals
+ )}
minValue={0}
termId="supplier-process-minimum-cost"
/>
diff --git a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierProcesses.tsx b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierProcesses.tsx
index f9ea95b3ef..dd34c2ec8f 100644
--- a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierProcesses.tsx
+++ b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierProcesses.tsx
@@ -13,6 +13,7 @@ import {
HStack,
IconButton
} from "@carbon/react";
+import { INPUT_FORMAT } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { ColumnDef } from "@tanstack/react-table";
import { useCallback, useMemo } from "react";
@@ -21,7 +22,12 @@ import { Outlet, useNavigate, useParams } from "react-router";
import { New } from "~/components";
import { EditableNumber } from "~/components/Editable";
import Grid from "~/components/Grid";
-import { useCurrencyFormatter, usePermissions, useUser } from "~/hooks";
+import {
+ useCurrencyDecimals,
+ useCurrencyFormatter,
+ usePermissions,
+ useUser
+} from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import type { SupplierProcess } from "~/modules/purchasing";
import { path } from "~/utils/path";
@@ -44,6 +50,7 @@ const SupplierProccesses = ({ processes }: SupplierProccessesProps) => {
const { carbon } = useCarbon();
const baseCurrency = company?.baseCurrencyCode ?? "USD";
+ const currencyDecimals = useCurrencyDecimals(baseCurrency);
const onCellEdit = useCallback(
async (id: string, value: unknown, row: SupplierProcess) => {
@@ -134,10 +141,7 @@ const SupplierProccesses = ({ processes }: SupplierProccessesProps) => {
const editableComponents = useMemo(
() => ({
minimumCost: EditableNumber(onCellEdit, {
- formatOptions: {
- style: "currency",
- currency: baseCurrency
- }
+ formatOptions: INPUT_FORMAT.price(baseCurrency, currencyDecimals)
}),
leadTime: EditableNumber(onCellEdit)
}),
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteCompareDrawer.tsx b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteCompareDrawer.tsx
index e32f26693f..cb06bb7bfa 100644
--- a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteCompareDrawer.tsx
+++ b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteCompareDrawer.tsx
@@ -760,7 +760,8 @@ const LinePricingOptions = ({
supplierShippingCost: selectedOption.supplierShippingCost ?? 0,
shippingCost: selectedOption.shippingCost ?? 0,
leadTime: selectedOption.leadTime ?? 0,
- supplierTaxAmount: selectedOption.supplierTaxAmount ?? 0
+ supplierTaxAmount: selectedOption.supplierTaxAmount ?? 0,
+ taxPercent: selectedOption.taxPercent ?? 0
}
}));
}
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteLinePricing.tsx b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteLinePricing.tsx
index 8d886301cb..b1e4e341e4 100644
--- a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteLinePricing.tsx
+++ b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteLinePricing.tsx
@@ -15,6 +15,13 @@ import {
toast,
VStack
} from "@carbon/react";
+import type { TaxPair } from "@carbon/utils";
+import {
+ INPUT_FORMAT,
+ taxableBase,
+ taxPairFromAmount,
+ taxPairFromPercent
+} from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { useCallback, useEffect, useState } from "react";
import { useParams } from "react-router";
@@ -22,6 +29,7 @@ import EditableNumberCell from "~/components/EditableNumberCell";
import { Enumerable } from "~/components/Enumerable";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
import {
+ useCurrencyDecimals,
useCurrencyFormatter,
usePermissions,
useRouteData,
@@ -68,6 +76,7 @@ const SupplierQuoteLinePricing = ({
const routeData = useRouteData<{
quote: SupplierQuote;
+ presentationCurrency: { decimalPlaces: number } | null;
}>(path.to.supplierQuote(id));
const isEditable =
permissions.can("update", "purchasing") &&
@@ -76,22 +85,24 @@ const SupplierQuoteLinePricing = ({
const { carbon } = useCarbon();
const { id: userId, company } = useUser();
const baseCurrency = company?.baseCurrencyCode ?? "USD";
+ // The loader's currency row first — correct on first paint; the hook covers
+ // the case where it isn't loaded, and carries the one documented fallback.
+ const quoteCurrency = routeData?.quote?.currencyCode ?? baseCurrency;
+ const configuredDecimals = useCurrencyDecimals(quoteCurrency);
+ const currencyDecimals =
+ routeData?.presentationCurrency?.decimalPlaces ?? configuredDecimals;
const formatter = useCurrencyFormatter();
const presentationCurrencyFormatter = useCurrencyFormatter({
- currency: routeData?.quote?.currencyCode ?? baseCurrency
+ currency: quoteCurrency
});
- const onUpdatePrice = useCallback(
- async (
- key:
- | "leadTime"
- | "supplierUnitPrice"
- | "supplierShippingCost"
- | "supplierTaxAmount",
- quantity: number,
- value: number
- ) => {
+ /** One writer for every price-break field. The optimistic patch, the
+ * insert-or-update branch and the rollback are identical whichever field
+ * moved, so they live here once; callers say WHAT changed, not how to save
+ * it. */
+ const onUpdateFields = useCallback(
+ async (quantity: number, patch: Partial<SupplierQuoteLinePrice>) => {
const hasPrice = !!editableFields.prices[quantity];
const oldPrices = { ...editableFields.prices };
@@ -106,10 +117,11 @@ const SupplierQuoteLinePricing = ({
supplierUnitPrice: 0,
supplierShippingCost: 0,
supplierTaxAmount: 0,
+ taxPercent: 0,
createdBy: userId
} as unknown as SupplierQuoteLinePrice;
}
- newPrices[quantity] = { ...newPrices[quantity], [key]: value };
+ newPrices[quantity] = { ...newPrices[quantity], ...patch };
setEditableFields((prev) => ({
...prev,
@@ -120,7 +132,7 @@ const SupplierQuoteLinePricing = ({
const update = await carbon
?.from("supplierQuoteLinePrice")
.update({
- [key]: value,
+ ...patch,
supplierQuoteLineId: lineId,
quantity,
updatedBy: userId
@@ -150,6 +162,32 @@ const SupplierQuoteLinePricing = ({
[editableFields.prices, id, lineId, exchangeRate, userId, carbon, t]
);
+ const onUpdatePrice = useCallback(
+ (
+ key:
+ | "leadTime"
+ | "supplierUnitPrice"
+ | "supplierShippingCost"
+ | "supplierTaxAmount",
+ quantity: number,
+ value: number
+ ) => onUpdateFields(quantity, { [key]: value }),
+ [onUpdateFields]
+ );
+
+ // The tax value pair: any edit writes BOTH the rate and the amount.
+ // NOTE: unlike the line forms, editing unit price or shipping here does NOT
+ // re-derive the amount for that break. That divergence is deliberate and
+ // predates this refactor — closing it is a product decision, not a cleanup.
+ const onUpdateTaxPair = useCallback(
+ (quantity: number, pair: TaxPair) =>
+ onUpdateFields(quantity, {
+ taxPercent: pair.percent,
+ supplierTaxAmount: pair.amount
+ }),
+ [onUpdateFields]
+ );
+
const unitOfMeasures = useUnitOfMeasure();
return (
@@ -223,10 +261,10 @@ const SupplierQuoteLinePricing = ({
<Td key={quantity.toString()}>
<EditableNumberCell
value={price}
- formatOptions={{
- style: "currency",
- currency: routeData?.quote?.currencyCode ?? baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(
+ quoteCurrency,
+ currencyDecimals
+ )}
minValue={0}
isEditable={isEditable}
onChange={(value) =>
@@ -278,10 +316,10 @@ const SupplierQuoteLinePricing = ({
<Td key={quantity.toString()}>
<EditableNumberCell
value={shippingCost}
- formatOptions={{
- style: "currency",
- currency: routeData?.quote?.currencyCode ?? baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.money(
+ quoteCurrency,
+ currencyDecimals
+ )}
minValue={0}
isEditable={isEditable}
onChange={(value) =>
@@ -300,20 +338,69 @@ const SupplierQuoteLinePricing = ({
</HStack>
</Td>
{quantities.map((quantity, index) => {
- const taxAmount =
- editableFields.prices[quantity]?.supplierTaxAmount ?? 0;
+ const price = editableFields.prices[quantity];
+ const taxAmount = price?.supplierTaxAmount ?? 0;
+ const taxPercent = price?.taxPercent ?? 0;
+ const breakSubtotal = taxableBase(
+ price?.supplierUnitPrice ?? 0,
+ quantity,
+ price?.supplierShippingCost ?? 0
+ );
return (
<Td key={index} className="group-hover:bg-muted/50">
<EditableNumberCell
value={taxAmount}
- formatOptions={{
- style: "currency",
- currency: routeData?.quote?.currencyCode ?? baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.money(
+ quoteCurrency,
+ currencyDecimals
+ )}
+ minValue={0}
+ isEditable={isEditable}
+ onChange={(value) =>
+ // Two-way: an amount edit restates the rate for this
+ // break, so the stored pair stays consistent
+ onUpdateTaxPair(
+ quantity,
+ taxPairFromAmount(breakSubtotal, value, taxPercent)
+ )
+ }
+ />
+ </Td>
+ );
+ })}
+ </Tr>
+
+ <Tr>
+ <Td className="border-r border-border group-hover:bg-muted/50">
+ <HStack className="w-full justify-between ">
+ <span>Tax Percent</span>
+ </HStack>
+ </Td>
+ {quantities.map((quantity, index) => {
+ const price = editableFields.prices[quantity];
+ const taxPercent = price?.taxPercent ?? 0;
+ const breakSubtotal = taxableBase(
+ price?.supplierUnitPrice ?? 0,
+ quantity,
+ price?.supplierShippingCost ?? 0
+ );
+ return (
+ <Td key={index} className="group-hover:bg-muted/50">
+ <EditableNumberCell
+ value={taxPercent}
+ formatOptions={INPUT_FORMAT.rate}
minValue={0}
+ maxValue={1}
isEditable={isEditable}
onChange={(value) =>
- onUpdatePrice("supplierTaxAmount", quantity, value)
+ onUpdateTaxPair(
+ quantity,
+ taxPairFromPercent(
+ breakSubtotal,
+ value,
+ currencyDecimals
+ )
+ )
}
/>
</Td>
@@ -344,7 +431,7 @@ const SupplierQuoteLinePricing = ({
);
})}
</Tr>
- {routeData?.quote?.currencyCode !== baseCurrency && (
+ {quoteCurrency !== baseCurrency && (
<>
<Tr className="[&>td]:bg-muted/60">
<Td className="border-r border-border group-hover:bg-muted/50">
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteToOrderDrawer.tsx b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteToOrderDrawer.tsx
index ca9fb661d9..5bb7299754 100644
--- a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteToOrderDrawer.tsx
+++ b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteToOrderDrawer.tsx
@@ -24,7 +24,12 @@ import {
Tr,
VStack
} from "@carbon/react";
-import { pluralize } from "@carbon/utils";
+import {
+ deriveRate,
+ INPUT_FORMAT,
+ pluralize,
+ taxableBase
+} from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { Dispatch, SetStateAction } from "react";
import { useEffect, useMemo, useState } from "react";
@@ -32,7 +37,7 @@ import { LuImage } from "react-icons/lu";
import { Form, useNavigation, useParams } from "react-router";
import type { z } from "zod";
import { useAccounts } from "~/components/Form/Account";
-import { useUser } from "~/hooks";
+import { useCurrencyDecimals, useUser } from "~/hooks";
import { useCurrencyFormatter } from "~/hooks/useCurrencyFormatter";
import { getPrivateUrl, path } from "~/utils/path";
import type { selectedLineSchema } from "../../purchasing.models";
@@ -262,6 +267,7 @@ const LinePricingOptions = ({
setSelectedLines
}: LinePricingOptionsProps) => {
const { t } = useLingui();
+ const currencyDecimals = useCurrencyDecimals(quoteCurrency);
const [selectedValue, setSelectedValue] = useState("");
const [showOverride, setShowOverride] = useState(false);
const [overridePricing, setOverridePricing] = useState<SelectedLine>({
@@ -271,7 +277,8 @@ const LinePricingOptions = ({
supplierUnitPrice: 0,
supplierShippingCost: 0,
shippingCost: 0,
- supplierTaxAmount: 0
+ supplierTaxAmount: 0,
+ taxPercent: 0
});
// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
@@ -286,7 +293,17 @@ const LinePricingOptions = ({
supplierShippingCost: overridePricing.supplierShippingCost,
shippingCost: overridePricing.shippingCost,
leadTime: overridePricing.leadTime,
- supplierTaxAmount: overridePricing.supplierTaxAmount
+ supplierTaxAmount: overridePricing.supplierTaxAmount,
+ // Override collects amounts only — seed the rate from the canonical
+ // denominator (unit price x quantity + shipping).
+ taxPercent: deriveRate(
+ overridePricing.supplierTaxAmount,
+ taxableBase(
+ overridePricing.supplierUnitPrice,
+ overridePricing.quantity,
+ overridePricing.supplierShippingCost
+ )
+ )
}
}));
}
@@ -319,7 +336,8 @@ const LinePricingOptions = ({
supplierShippingCost: selectedOption.supplierShippingCost ?? 0,
shippingCost: selectedOption.shippingCost ?? 0,
leadTime: selectedOption.leadTime,
- supplierTaxAmount: selectedOption.supplierTaxAmount ?? 0
+ supplierTaxAmount: selectedOption.supplierTaxAmount ?? 0,
+ taxPercent: selectedOption.taxPercent ?? 0
}
}));
setSelectedValue(value);
@@ -438,10 +456,10 @@ const LinePricingOptions = ({
aria-label={t`Unit Price`}
minValue={0}
value={overridePricing.supplierUnitPrice}
- formatOptions={{
- style: "currency",
- currency: quoteCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(
+ quoteCurrency,
+ currencyDecimals
+ )}
onChange={(unitPrice) =>
setOverridePricing((v) => ({
...v,
@@ -462,10 +480,10 @@ const LinePricingOptions = ({
aria-label={t`Shipping`}
minValue={0}
value={overridePricing.supplierShippingCost}
- formatOptions={{
- style: "currency",
- currency: quoteCurrency
- }}
+ formatOptions={INPUT_FORMAT.money(
+ quoteCurrency,
+ currencyDecimals
+ )}
onChange={(shippingCost) =>
setOverridePricing((v) => ({
...v,
@@ -511,10 +529,10 @@ const LinePricingOptions = ({
aria-label={t`Tax`}
minValue={0}
value={overridePricing.supplierTaxAmount}
- formatOptions={{
- style: "currency",
- currency: quoteCurrency
- }}
+ formatOptions={INPUT_FORMAT.money(
+ quoteCurrency,
+ currencyDecimals
+ )}
onChange={(taxAmount) =>
setOverridePricing((v) => ({
...v,
diff --git a/apps/erp/app/modules/quality/quality-disposition.server.ts b/apps/erp/app/modules/quality/quality-disposition.server.ts
index 0780e37290..4aff263102 100644
--- a/apps/erp/app/modules/quality/quality-disposition.server.ts
+++ b/apps/erp/app/modules/quality/quality-disposition.server.ts
@@ -1,5 +1,6 @@
import type { Database, Json } from "@carbon/database";
import type { KyselyTx } from "@carbon/database/client";
+import { EPSILON } from "@carbon/utils";
import { FunctionRegion, type SupabaseClient } from "@supabase/supabase-js";
import { nanoid } from "nanoid";
import { getDatabaseClient } from "~/services/database.server";
@@ -480,9 +481,9 @@ export async function splitIssueItem(args: {
} else if (typeof splitQuantity === "number" && splitQuantity > 0) {
let remaining = splitQuantity;
for (const link of links) {
- if (remaining <= 1e-6) break;
+ if (remaining <= EPSILON) break;
const q = Number(link.linkQuantity ?? 0);
- if (q <= remaining + 1e-6) {
+ if (q <= remaining + EPSILON) {
moves.push({ link, moveQty: q });
remaining -= q;
} else {
@@ -491,7 +492,7 @@ export async function splitIssueItem(args: {
break;
}
}
- if (remaining > 1e-6) {
+ if (remaining > EPSILON) {
throw new Error("Split quantity exceeds the linked entity quantity");
}
} else {
@@ -523,7 +524,7 @@ export async function splitIssueItem(args: {
for (const { link, moveQty } of moves) {
const entityQty = Number(link.entityQuantity ?? 0);
- if (moveQty >= entityQty - 1e-6) {
+ if (moveQty >= entityQty - EPSILON) {
// Whole lot moving — re-point the link, no physical change.
await trx
.updateTable("nonConformanceItemTrackedEntity")
@@ -678,7 +679,7 @@ export async function closeIssue(
// sum or status to reconcile, so the disposition alone is enough.
if (row.links.length === 0) continue;
const sum = row.links.reduce((acc, l) => acc + l.quantity, 0);
- if (Math.abs(sum - row.quantity) > 1e-6) {
+ if (Math.abs(sum - row.quantity) > EPSILON) {
blockers.push({
nonConformanceItemId: row.id,
reason: `Linked entity quantity (${sum}) does not match row quantity (${row.quantity})`
@@ -902,7 +903,7 @@ export async function closeIssue(
}
if (row.links.length === 0) continue;
const sum = row.links.reduce((acc, l) => acc + l.quantity, 0);
- if (Math.abs(sum - row.quantity) > 1e-6) {
+ if (Math.abs(sum - row.quantity) > EPSILON) {
throw new Error("Quantities changed while closing; please retry.");
}
for (const link of row.links) {
diff --git a/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordForm.tsx b/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordForm.tsx
index 57b59497bf..b5e3862a45 100644
--- a/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordForm.tsx
+++ b/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordForm.tsx
@@ -42,6 +42,7 @@ import {
VStack
} from "@carbon/react";
import { Editor } from "@carbon/react/Editor";
+import { INPUT_FORMAT } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { FileObject } from "@supabase/storage-js";
import { nanoid } from "nanoid";
@@ -324,11 +325,7 @@ const GaugeCalibrationRecordForm = ({
<Number
name="humidity"
label={t`Humidity`}
- formatOptions={{
- maximumFractionDigits: 2,
- style: "percent",
- minimumFractionDigits: 0
- }}
+ formatOptions={INPUT_FORMAT.rate}
/>
<Input
name="measurementStandard"
diff --git a/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordsTable.tsx b/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordsTable.tsx
index 4bd9a346bc..14a6f78670 100644
--- a/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordsTable.tsx
+++ b/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordsTable.tsx
@@ -30,7 +30,12 @@ import {
} from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { ConfirmDelete } from "~/components/Modals";
-import { usePermissions, useRouteData, useUrlParams } from "~/hooks";
+import {
+ usePercentFormatter,
+ usePermissions,
+ useRouteData,
+ useUrlParams
+} from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { usePeople, useSuppliers } from "~/stores";
import type { ListItem } from "~/types";
@@ -81,11 +86,7 @@ const GaugeCalibrationRecordsTable = memo(
style: "unit",
unit: isMetric ? "celsius" : "fahrenheit"
});
- const humidityFormatter = useNumberFormatter({
- maximumFractionDigits: 2,
- style: "percent",
- minimumFractionDigits: 0
- });
+ const humidityFormatter = usePercentFormatter();
const columns = useMemo<ColumnDef<GaugeCalibrationRecord>[]>(() => {
const defaultColumns: ColumnDef<GaugeCalibrationRecord>[] = [
diff --git a/apps/erp/app/modules/quality/ui/Issue/AssociatedItemsList.tsx b/apps/erp/app/modules/quality/ui/Issue/AssociatedItemsList.tsx
index 68e2f90ebc..d79e2a2cc3 100644
--- a/apps/erp/app/modules/quality/ui/Issue/AssociatedItemsList.tsx
+++ b/apps/erp/app/modules/quality/ui/Issue/AssociatedItemsList.tsx
@@ -31,6 +31,7 @@ import {
ModalTitle,
toast
} from "@carbon/react";
+import { EPSILON } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
@@ -206,7 +207,8 @@ export function AssociatedItemsList({
!row.disposition || row.disposition === "Pending" ? true : false,
// Only tracked rows reconcile a per-entity quantity sum; a non-tracked
// row carries its quantity directly with no links to add up.
- sumMismatch: links.length > 0 && Math.abs(linkedSum - quantity) > 1e-6
+ sumMismatch:
+ links.length > 0 && Math.abs(linkedSum - quantity) > EPSILON
};
});
}, [associatedItems]);
diff --git a/apps/erp/app/modules/resources/ui/WorkCenters/WorkCenterForm.tsx b/apps/erp/app/modules/resources/ui/WorkCenters/WorkCenterForm.tsx
index d6dc7a0151..175eb46854 100644
--- a/apps/erp/app/modules/resources/ui/WorkCenters/WorkCenterForm.tsx
+++ b/apps/erp/app/modules/resources/ui/WorkCenters/WorkCenterForm.tsx
@@ -19,6 +19,7 @@ import {
toast,
VStack
} from "@carbon/react";
+import { INPUT_FORMAT } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { PostgrestResponse } from "@supabase/supabase-js";
import { useEffect } from "react";
@@ -29,7 +30,7 @@ import Department from "~/components/Form/Department";
import Location from "~/components/Form/Location";
import Processes from "~/components/Form/Processes";
import StandardFactor from "~/components/Form/StandardFactor";
-import { usePermissions, useUser } from "~/hooks";
+import { useCurrencyDecimals, usePermissions, useUser } from "~/hooks";
import { workCenterValidator } from "~/modules/resources";
import { path } from "~/utils/path";
@@ -54,6 +55,7 @@ const WorkCenterForm = ({
const { company } = useUser();
const baseCurrency = company?.baseCurrencyCode ?? "USD";
+ const currencyDecimals = useCurrencyDecimals(baseCurrency);
useEffect(() => {
if (type !== "modal") return;
@@ -123,28 +125,28 @@ const WorkCenterForm = ({
name="laborRate"
label={t`Labor Rate (Hourly)`}
termId="work-center-labor-rate"
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(
+ baseCurrency,
+ currencyDecimals
+ )}
/>
<Number
name="machineRate"
label={t`Machine Rate (Hourly)`}
termId="work-center-machine-rate"
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(
+ baseCurrency,
+ currencyDecimals
+ )}
/>
<Number
name="overheadRate"
label={t`Overhead Rate (Hourly)`}
termId="work-center-overhead-rate"
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(
+ baseCurrency,
+ currencyDecimals
+ )}
/>
<StandardFactor
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index b142040b76..7fe1085120 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -4,7 +4,7 @@ import type { Kysely, KyselyDatabase, KyselyTx } from "@carbon/database/client";
import { raiseMoment } from "@carbon/lib/workflows";
import { getLogger } from "@carbon/logger";
import type { PickPartial } from "@carbon/utils";
-import { datetime } from "@carbon/utils";
+import { datetime, round } from "@carbon/utils";
import type {
PostgrestError,
PostgrestSingleResponse,
@@ -4013,7 +4013,7 @@ async function rewriteQuoteLinePrices(
quoteLineId: lineId,
companyId,
quoteId,
- unitPrice: Number(p.unitPrice.toFixed(quoteLine.unitPricePrecision)),
+ unitPrice: round(p.unitPrice, quoteLine.unitPricePrecision),
discountPercent: existing?.discountPercent ?? p.discountPercent,
leadTime: existing?.leadTime ?? p.leadTime,
shippingCost: existing?.shippingCost ?? 0,
@@ -4423,7 +4423,7 @@ export async function buildMakeToOrderPriceRows(
quoteLineId,
companyId,
quantity: qty,
- unitPrice: Number(finalPrice.toFixed(precision)),
+ unitPrice: round(finalPrice, precision),
categoryMarkups: effectiveDefaults,
priceSource: "system",
exchangeRate,
@@ -4513,7 +4513,7 @@ export async function buildPullFromInventoryPriceRows(
quoteLineId,
companyId,
quantity: qty,
- unitPrice: Number(resolved.finalPrice.toFixed(precision)),
+ unitPrice: round(resolved.finalPrice, precision),
exchangeRate,
createdBy: userId,
leadTime: 0,
@@ -4606,7 +4606,7 @@ export async function buildPurchaseToOrderPriceRows(
quoteLineId,
companyId,
quantity: qty,
- unitPrice: Number(resolved.finalPrice.toFixed(precision)),
+ unitPrice: round(resolved.finalPrice, precision),
exchangeRate,
createdBy: userId,
leadTime: 0,
@@ -4759,7 +4759,7 @@ export async function recalculateQuoteLinePrices(
repricedRows.push({
quantity: qty,
- unitPrice: Number(finalPrice.toFixed(precision)),
+ unitPrice: round(finalPrice, precision),
categoryMarkups: markups
});
}
diff --git a/apps/erp/app/modules/sales/ui/Customer/CustomerForm.tsx b/apps/erp/app/modules/sales/ui/Customer/CustomerForm.tsx
index 119e5b164b..b7d4203c8d 100644
--- a/apps/erp/app/modules/sales/ui/Customer/CustomerForm.tsx
+++ b/apps/erp/app/modules/sales/ui/Customer/CustomerForm.tsx
@@ -12,6 +12,7 @@ import {
ModalCardTitle,
toast
} from "@carbon/react";
+import { INPUT_FORMAT, INPUT_STEP } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { PostgrestResponse } from "@supabase/supabase-js";
import { useEffect, useRef } from "react";
@@ -195,12 +196,8 @@ const CustomerForm = ({
termId="customer-default-tax-percent"
minValue={0}
maxValue={1}
- step={0.0001}
- formatOptions={{
- style: "percent",
- minimumFractionDigits: 0,
- maximumFractionDigits: 2
- }}
+ step={INPUT_STEP.rate}
+ formatOptions={INPUT_FORMAT.rate}
/>
<Input name="website" label={t`Website`} />
diff --git a/apps/erp/app/modules/sales/ui/Pricing/PriceOverrideForm.tsx b/apps/erp/app/modules/sales/ui/Pricing/PriceOverrideForm.tsx
index 339a6a1e04..b3638f6941 100644
--- a/apps/erp/app/modules/sales/ui/Pricing/PriceOverrideForm.tsx
+++ b/apps/erp/app/modules/sales/ui/Pricing/PriceOverrideForm.tsx
@@ -37,6 +37,7 @@ import {
useDisclosure,
VStack
} from "@carbon/react";
+import { INPUT_FORMAT } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { ColumnDef } from "@tanstack/react-table";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -65,7 +66,12 @@ import {
TextArea
} from "~/components/Form";
import Grid from "~/components/Grid";
-import { useCurrencyFormatter, usePermissions, useUser } from "~/hooks";
+import {
+ useCurrencyDecimals,
+ useCurrencyFormatter,
+ usePermissions,
+ useUser
+} from "~/hooks";
import { priceOverrideValidator } from "../../sales.models";
import type { PriceOverrideBreak } from "../../types";
@@ -270,6 +276,7 @@ function PriceBreaks({
}) {
const { t } = useLingui();
const formatter = useCurrencyFormatter();
+ const currencyDecimals = useCurrencyDecimals(baseCurrency);
const [historyBreakId, setHistoryBreakId] = useState<string | null>(null);
const [pendingDelete, setPendingDelete] = useState<{
@@ -351,7 +358,7 @@ function PriceBreaks({
() => ({
quantity: EditableNumber(noOpMutation),
overridePrice: EditableNumber(noOpMutation, {
- formatOptions: { style: "currency", currency: baseCurrency }
+ formatOptions: INPUT_FORMAT.price(baseCurrency, currencyDecimals)
})
}),
[noOpMutation, baseCurrency]
diff --git a/apps/erp/app/modules/sales/ui/Pricing/PricingRuleForm.tsx b/apps/erp/app/modules/sales/ui/Pricing/PricingRuleForm.tsx
index ff9c72ddf4..f96428c8ad 100644
--- a/apps/erp/app/modules/sales/ui/Pricing/PricingRuleForm.tsx
+++ b/apps/erp/app/modules/sales/ui/Pricing/PricingRuleForm.tsx
@@ -12,6 +12,7 @@ import {
ModalDrawerTitle,
VStack
} from "@carbon/react";
+import { INPUT_FORMAT, INPUT_STEP } from "@carbon/utils";
import { useLingui } from "@lingui/react/macro";
import { useEffect, useState } from "react";
import {
@@ -36,7 +37,7 @@ import {
Select,
Submit
} from "~/components/Form";
-import { usePermissions, useUser } from "~/hooks";
+import { useCurrencyDecimals, usePermissions, useUser } from "~/hooks";
import {
pricingRuleAmountTypes,
pricingRuleTypes,
@@ -55,6 +56,9 @@ const PricingRuleForm = ({ initialValues, onClose }: PricingRuleFormProps) => {
const { t } = useLingui();
const permissions = usePermissions();
const { company } = useUser();
+ const currencyDecimals = useCurrencyDecimals(
+ company?.baseCurrencyCode ?? "USD"
+ );
const [amountType, setAmountType] = useState<
(typeof pricingRuleAmountTypes)[number]
@@ -135,22 +139,18 @@ const PricingRuleForm = ({ initialValues, onClose }: PricingRuleFormProps) => {
label={t`Amount`}
minValue={0}
maxValue={1}
- step={0.01}
- formatOptions={{
- style: "percent",
- minimumFractionDigits: 0,
- maximumFractionDigits: 2
- }}
+ step={INPUT_STEP.rate}
+ formatOptions={INPUT_FORMAT.rate}
/>
) : (
<Number
name="amount"
label={t`Amount`}
minValue={0}
- formatOptions={{
- style: "currency",
- currency: company?.baseCurrencyCode ?? "USD"
- }}
+ formatOptions={INPUT_FORMAT.money(
+ company?.baseCurrencyCode ?? "USD",
+ currencyDecimals
+ )}
/>
)}
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
index e17db3f600..c859a0519b 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
@@ -28,7 +28,7 @@ import {
useDisclosure,
VStack
} from "@carbon/react";
-import { getItemReadableId } from "@carbon/utils";
+import { getItemReadableId, INPUT_FORMAT } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { motion } from "framer-motion";
import { nanoid } from "nanoid";
@@ -69,7 +69,13 @@ import {
SortableListItemPanel,
SortableListItemToggle
} from "~/components/SortableList";
-import { usePermissions, useRouteData, useUrlParams, useUser } from "~/hooks";
+import {
+ useCurrencyDecimals,
+ usePermissions,
+ useRouteData,
+ useUrlParams,
+ useUser
+} from "~/hooks";
import { lookupBuyPrice as lookupBuyPriceAsync } from "~/modules/items";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
import type { MethodItemType, MethodType } from "~/modules/shared";
@@ -597,6 +603,7 @@ function MaterialForm({
const routeData = useRouteData<{ quote: Quotation }>(path.to.quote(quoteId));
const baseCurrency = company?.baseCurrencyCode ?? "USD";
+ const currencyDecimals = useCurrencyDecimals(baseCurrency);
useEffect(() => {
// Remove from temporary items after successful submission
@@ -824,10 +831,7 @@ function MaterialForm({
label={t`Unit Cost`}
value={itemData.unitCost}
minValue={0}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(baseCurrency, currencyDecimals)}
/>
)}
</div>
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
index 3d289096a3..e1ff4ead14 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
@@ -36,6 +36,7 @@ import {
VStack
} from "@carbon/react";
import { Editor } from "@carbon/react/Editor";
+import { INPUT_FORMAT } from "@carbon/utils";
import { getLocalTimeZone, today } from "@internationalized/date";
import { Trans, useLingui } from "@lingui/react/macro";
import type { DragControls } from "framer-motion";
@@ -99,7 +100,12 @@ import {
SortableListItemPanel,
SortableListItemToggle
} from "~/components/SortableList";
-import { usePermissions, useRouteData, useUser } from "~/hooks";
+import {
+ useCurrencyDecimals,
+ usePermissions,
+ useRouteData,
+ useUser
+} from "~/hooks";
import type {
OperationParameter,
OperationStep,
@@ -1738,6 +1744,7 @@ function OperationForm({
const { carbon } = useCarbon();
const baseCurrency = company?.baseCurrencyCode ?? "USD";
+ const currencyDecimals = useCurrencyDecimals(baseCurrency);
useEffect(() => {
if (fetcher.data && fetcher.data.id) {
@@ -2004,10 +2011,7 @@ function OperationForm({
label={t`Minimum Cost`}
minValue={0}
value={processData.operationMinimumCost}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(baseCurrency, currencyDecimals)}
onChange={(newValue) =>
setProcessData((d) => ({
...d,
@@ -2020,10 +2024,7 @@ function OperationForm({
label={t`Unit Cost`}
minValue={0}
value={processData.operationUnitCost}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(baseCurrency, currencyDecimals)}
onChange={(newValue) =>
setProcessData((d) => ({
...d,
@@ -2368,10 +2369,10 @@ function OperationForm({
label={t`Labor Rate`}
minValue={0}
value={processData.laborRate}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(
+ baseCurrency,
+ currencyDecimals
+ )}
onChange={(newValue) =>
setProcessData((d) => ({
...d,
@@ -2385,10 +2386,10 @@ function OperationForm({
label={t`Machine Rate`}
minValue={0}
value={processData.machineRate}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(
+ baseCurrency,
+ currencyDecimals
+ )}
onChange={(newValue) =>
setProcessData((d) => ({
...d,
@@ -2402,10 +2403,10 @@ function OperationForm({
label={t`Overhead Rate`}
minValue={0}
value={processData.overheadRate}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(
+ baseCurrency,
+ currencyDecimals
+ )}
onChange={(newValue) =>
setProcessData((d) => ({
...d,
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteLineCosting.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteLineCosting.tsx
index f99b778293..b0ccd6c898 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteLineCosting.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteLineCosting.tsx
@@ -49,7 +49,7 @@ const QuoteLineCosting = ({
const formatter = useCurrencyFormatter();
const unitCostFormatter = useCurrencyFormatter({
- maximumFractionDigits: unitPricePrecision
+ decimalPlaces: unitPricePrecision
});
const detailsDisclosure = useDisclosure();
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteLineForm.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
index 1992536eb3..e40157f3bc 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
@@ -23,7 +23,7 @@ import {
useDisclosure,
VStack
} from "@carbon/react";
-import { getItemReadableId } from "@carbon/utils";
+import { getItemReadableId, INPUT_FORMAT, INPUT_STEP } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { useState } from "react";
import { BsThreeDotsVertical } from "react-icons/bs";
@@ -496,12 +496,8 @@ const QuoteLineForm = ({
label={t`Tax Percent`}
minValue={0}
maxValue={1}
- step={0.0001}
- formatOptions={{
- style: "percent",
- minimumFractionDigits: 0,
- maximumFractionDigits: 2
- }}
+ step={INPUT_STEP.rate}
+ formatOptions={INPUT_FORMAT.rate}
/>
<CustomFormFields table="quoteLine" />
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx
index 8a8bc56441..45bce34ee4 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx
@@ -31,6 +31,7 @@ import {
toast,
VStack
} from "@carbon/react";
+import { INPUT_FORMAT, round } from "@carbon/utils";
import { getLocalTimeZone, today } from "@internationalized/date";
import { Trans, useLingui } from "@lingui/react/macro";
import { useCallback, useEffect, useMemo, useState } from "react";
@@ -45,7 +46,9 @@ import {
import { useFetcher, useParams } from "react-router";
import EditableNumberCell from "~/components/EditableNumberCell";
import {
+ useCurrencyDecimals,
useCurrencyFormatter,
+ usePercentFormatter,
usePermissions,
useRouteData,
useSettings,
@@ -175,15 +178,17 @@ const QuoteLinePricing = ({
const { carbon } = useCarbon();
const { id: userId, company } = useUser();
const baseCurrency = company?.baseCurrencyCode ?? "USD";
+ const currencyDecimals = useCurrencyDecimals(baseCurrency);
const formatter = useCurrencyFormatter();
+ const percentFormatter = usePercentFormatter();
const unitPriceFormatter = useCurrencyFormatter({
currency: routeData?.quote?.currencyCode ?? baseCurrency,
- maximumFractionDigits: unitPricePrecision
+ decimalPlaces: unitPricePrecision
});
const presentationCurrencyFormatter = useCurrencyFormatter({
currency: routeData?.quote?.currencyCode ?? baseCurrency,
- maximumFractionDigits: unitPricePrecision
+ decimalPlaces: unitPricePrecision
});
const additionalCharges = useMemo(() => {
@@ -510,7 +515,7 @@ const QuoteLinePricing = ({
let roundedValue = value;
if (key === "unitPrice") {
// Round the value to the precision of the quote line
- roundedValue = Number(value.toFixed(unitPricePrecision));
+ roundedValue = round(value, unitPricePrecision);
}
newPrices[quantity] = {
...newPrices[quantity],
@@ -652,10 +657,7 @@ const QuoteLinePricing = ({
customMarkup === "" ? undefined : Number(customMarkup)
}
minValue={0}
- formatOptions={{
- style: "decimal",
- maximumFractionDigits: 2
- }}
+ formatOptions={INPUT_FORMAT.percentPoints}
onChange={(val) => {
if (Number.isFinite(val)) setCustomMarkup(String(val));
}}
@@ -793,10 +795,10 @@ const QuoteLinePricing = ({
<Td key={index} className="group-hover:bg-muted/50">
<EditableNumberCell
value={editableFields.unitCost}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(
+ baseCurrency,
+ currencyDecimals
+ )}
minValue={0}
isEditable={isEditable}
onChange={(value) => onUpdateCost(value)}
@@ -833,10 +835,7 @@ const QuoteLinePricing = ({
{cost > 0 ? (
<EditableNumberCell
value={markup}
- formatOptions={{
- style: "percent",
- maximumFractionDigits: 2
- }}
+ formatOptions={INPUT_FORMAT.rate}
minValue={0}
isEditable={isEditable}
onChange={(value) =>
@@ -899,10 +898,7 @@ const QuoteLinePricing = ({
<VStack spacing={0}>
<EditableNumberCell
value={markupValue / 100}
- formatOptions={{
- style: "percent",
- maximumFractionDigits: 2
- }}
+ formatOptions={INPUT_FORMAT.rate}
minValue={0}
isEditable={isEditable}
onChange={(value) =>
@@ -940,11 +936,10 @@ const QuoteLinePricing = ({
<Td key={quantity.toString()}>
<EditableNumberCell
value={price}
- formatOptions={{
- style: "currency",
- currency: baseCurrency,
- maximumFractionDigits: unitPricePrecision
- }}
+ formatOptions={INPUT_FORMAT.price(
+ baseCurrency,
+ unitPricePrecision
+ )}
minValue={0}
isEditable={isEditable}
onChange={(value) =>
@@ -970,10 +965,7 @@ const QuoteLinePricing = ({
<Td key={index}>
<EditableNumberCell
value={discount}
- formatOptions={{
- style: "percent",
- maximumFractionDigits: 2
- }}
+ formatOptions={INPUT_FORMAT.rate}
minValue={0}
maxValue={1}
isEditable={isEditable}
@@ -1027,7 +1019,7 @@ const QuoteLinePricing = ({
<span
className={cn(profit < -0.01 && "text-red-500")}
>
- {profit.toFixed(2)}%
+ {percentFormatter.format(profit / 100)}
</span>
) : (
<span>-</span>
@@ -1080,10 +1072,10 @@ const QuoteLinePricing = ({
<Td key={quantity.toString()}>
<EditableNumberCell
value={shippingCost}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.money(
+ baseCurrency,
+ currencyDecimals
+ )}
minValue={0}
isEditable={isEditable}
onChange={(value) =>
@@ -1178,10 +1170,10 @@ const QuoteLinePricing = ({
<VStack spacing={0}>
<EditableNumberCell
value={amount}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.money(
+ baseCurrency,
+ currencyDecimals
+ )}
minValue={0}
isEditable={isEditable}
onChange={(value) =>
@@ -1265,10 +1257,7 @@ const QuoteLinePricing = ({
<Td key={index} className="group-hover:bg-muted/50">
<EditableNumberCell
value={taxPercent}
- formatOptions={{
- style: "percent",
- maximumFractionDigits: 2
- }}
+ formatOptions={INPUT_FORMAT.rate}
minValue={0}
isEditable={isEditable}
onChange={(value) => {
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricingHistory.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricingHistory.tsx
index 6abae3b43d..618ebd9385 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricingHistory.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteLinePricingHistory.tsx
@@ -26,6 +26,7 @@ import {
import { Trans } from "@lingui/react/macro";
import { Link } from "react-router";
import { DateTime, Empty } from "~/components";
+import { useCurrencyFormatter } from "~/hooks";
import { useCustomers } from "~/stores/customers";
import { path } from "~/utils/path";
import type { HistoricalQuotationPrice, SalesOrderLine } from "../../types";
@@ -64,6 +65,7 @@ const QuoteLinePricingHistory = ({
// Default to the tab that has items
const defaultTab = hasOrderLines ? "salesOrderLines" : "quoteLines";
const [customers] = useCustomers();
+ const priceFormatter = useCurrencyFormatter({ currency: baseCurrency });
return (
<Card>
@@ -165,10 +167,9 @@ const QuoteLinePricingHistory = ({
<Tr>
<Td>{line.saleQuantity}</Td>
<Td>
- {new Intl.NumberFormat("en-US", {
- style: "currency",
- currency: baseCurrency
- }).format(line.unitPrice ?? 0)}
+ {priceFormatter.format(
+ line.unitPrice ?? 0
+ )}
</Td>
</Tr>
</Tbody>
@@ -260,10 +261,9 @@ const QuoteLinePricingHistory = ({
<Tr key={quantity}>
<Td>{quantity}</Td>
<Td>
- {new Intl.NumberFormat("en-US", {
- style: "currency",
- currency: baseCurrency
- }).format(price as number)}
+ {priceFormatter.format(
+ price as number
+ )}
</Td>
</Tr>
)
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteShipmentForm.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteShipmentForm.tsx
index 6a1473e66d..5326b91f95 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteShipmentForm.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteShipmentForm.tsx
@@ -6,6 +6,7 @@ import {
CardHeader,
CardTitle
} from "@carbon/react";
+import { INPUT_FORMAT } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { forwardRef, useImperativeHandle, useRef, useState } from "react";
import { useFetcher, useParams } from "react-router";
@@ -20,7 +21,12 @@ import {
ShippingMethod,
Submit
} from "~/components/Form";
-import { usePermissions, useRouteData, useUser } from "~/hooks";
+import {
+ useCurrencyDecimals,
+ usePermissions,
+ useRouteData,
+ useUser
+} from "~/hooks";
import { incoterms } from "~/modules/shared";
import { path } from "~/utils/path";
import { isQuoteLocked, quoteShipmentValidator } from "../../sales.models";
@@ -72,6 +78,7 @@ const QuoteShipmentForm = forwardRef<
const isEditable = !isLocked;
const { company } = useUser();
+ const currencyDecimals = useCurrencyDecimals(company?.baseCurrencyCode);
return (
<Card
@@ -100,10 +107,10 @@ const QuoteShipmentForm = forwardRef<
<Number
name="shippingCost"
label={t`Shipping Cost`}
- formatOptions={{
- style: "currency",
- currency: company?.baseCurrencyCode
- }}
+ formatOptions={INPUT_FORMAT.money(
+ company?.baseCurrencyCode,
+ currencyDecimals
+ )}
minValue={0}
ref={shippingCostRef}
/>
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteSummary.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteSummary.tsx
index 6a423ad3e2..be11226c4f 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteSummary.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteSummary.tsx
@@ -20,13 +20,18 @@ import {
import { Trans } from "@lingui/react/macro";
import { useLocale } from "@react-aria/i18n";
import { motion } from "framer-motion";
-import MotionNumber from "motion-number";
import type { Dispatch, SetStateAction } from "react";
import { useEffect, useMemo, useState } from "react";
import { LuChevronRight, LuImage } from "react-icons/lu";
import { Link, useParams } from "react-router";
-import { CustomerAvatar, DateTime } from "~/components";
-import { usePercentFormatter, useRouteData, useUser } from "~/hooks";
+import { CustomerAvatar, DateTime, MotionMoney } from "~/components";
+import {
+ useCurrencyDecimals,
+ useCurrencyFormatter,
+ usePercentFormatter,
+ useRouteData,
+ useUser
+} from "~/hooks";
import { getPrivateUrl, path } from "~/utils/path";
import { isQuoteLocked } from "../../sales.models";
import type {
@@ -84,6 +89,8 @@ const LineItems = ({
selectedLines: Record<string, SelectedLine>;
setSelectedLines: Dispatch<SetStateAction<Record<string, SelectedLine>>>;
}) => {
+ // Settlement money at the document currency's configured decimals.
+ const currencyDecimals = useCurrencyDecimals(currencyCode);
const { company } = useUser();
const { quoteId } = useParams();
if (!quoteId) throw new Error("Could not find quote id");
@@ -192,8 +199,7 @@ const LineItems = ({
</Button>
</HStack>
<HStack spacing={4}>
- <MotionNumber
- className="font-bold text-xl"
+ <MotionMoney
value={
(selectedLine.convertedNetUnitPrice ?? 0) *
(selectedLine.quantity ?? 0) +
@@ -205,11 +211,8 @@ const LineItems = ({
(selectedLine.convertedShippingCost ?? 0)) *
(selectedLine.taxPercent ?? 0)
}
- format={{
- style: "currency",
- currency: currencyCode
- }}
- locales={locale}
+ currency={currencyCode}
+ decimalPlaces={currencyDecimals}
/>
<motion.div
animate={{
@@ -280,6 +283,8 @@ const LinePricingOptions = ({
selectedLine,
setSelectedLines
}: LinePricingOptionsProps) => {
+ // Settlement money at the document currency's configured decimals.
+ const currencyDecimals = useCurrencyDecimals(quoteCurrency);
const percentFormatter = usePercentFormatter();
const { quoteId } = useParams();
if (!quoteId) throw new Error("Could not find quote id");
@@ -538,13 +543,13 @@ const LinePricingOptions = ({
<Trans>Extended Price</Trans>
</Td>
<Td className="text-right">
- <MotionNumber
+ <MotionMoney
value={
(selectedLine.convertedUnitPrice ?? 0) *
selectedLine.quantity
}
- format={{ style: "currency", currency: quoteCurrency }}
- locales={locale}
+ currency={quoteCurrency}
+ decimalPlaces={currencyDecimals}
/>
</Td>
</Tr>
@@ -557,14 +562,14 @@ const LinePricingOptions = ({
</Td>
<Td className="text-right">
-
- <MotionNumber
+ <MotionMoney
value={
(selectedLine.convertedUnitPrice ?? 0) *
selectedLine.quantity *
selectedLine.discountPercent
}
- format={{ style: "currency", currency: quoteCurrency }}
- locales={locale}
+ currency={quoteCurrency}
+ decimalPlaces={currencyDecimals}
/>
</Td>
</Tr>
@@ -582,10 +587,10 @@ const LinePricingOptions = ({
>
<Td>{charge.name}</Td>
<Td className="text-right">
- <MotionNumber
+ <MotionMoney
value={charge.amount}
- format={{ style: "currency", currency: quoteCurrency }}
- locales={locale}
+ currency={quoteCurrency}
+ decimalPlaces={currencyDecimals}
/>
</Td>
</Tr>
@@ -596,18 +601,15 @@ const LinePricingOptions = ({
<Trans>Subtotal</Trans>
</Td>
<Td className="text-right">
- <MotionNumber
+ <MotionMoney
value={
(selectedLine.convertedNetUnitPrice ?? 0) *
selectedLine.quantity +
(selectedLine.convertedAddOn ?? 0) +
(selectedLine.convertedShippingCost ?? 0)
}
- format={{
- style: "currency",
- currency: quoteCurrency
- }}
- locales={locale}
+ currency={quoteCurrency}
+ decimalPlaces={currencyDecimals}
/>
</Td>
</Tr>
@@ -617,7 +619,7 @@ const LinePricingOptions = ({
Tax ({percentFormatter.format(selectedLine.taxPercent)})
</Td>
<Td className="text-right">
- <MotionNumber
+ <MotionMoney
value={
((selectedLine.convertedNetUnitPrice ?? 0) *
selectedLine.quantity +
@@ -625,11 +627,8 @@ const LinePricingOptions = ({
(selectedLine.convertedShippingCost ?? 0)) *
(selectedLine.taxPercent ?? 0)
}
- format={{
- style: "currency",
- currency: quoteCurrency
- }}
- locales={locale}
+ currency={quoteCurrency}
+ decimalPlaces={currencyDecimals}
/>
</Td>
</Tr>
@@ -639,7 +638,7 @@ const LinePricingOptions = ({
<Trans>Total</Trans>
</Td>
<Td className="text-right">
- <MotionNumber
+ <MotionMoney
value={
(selectedLine.convertedNetUnitPrice ?? 0) *
selectedLine.quantity +
@@ -651,11 +650,8 @@ const LinePricingOptions = ({
(selectedLine.convertedShippingCost ?? 0)) *
(selectedLine.taxPercent ?? 0)
}
- format={{
- style: "currency",
- currency: quoteCurrency
- }}
- locales={locale}
+ currency={quoteCurrency}
+ decimalPlaces={currencyDecimals}
/>
</Td>
</Tr>
@@ -685,13 +681,12 @@ const QuoteSummary = ({
const isEditable = !isQuoteLocked(routeData?.quote?.status);
const { locale } = useLocale();
- const formatter = useMemo(
- () =>
- new Intl.NumberFormat(locale, {
- style: "currency",
- currency: routeData?.quote.currencyCode ?? "USD"
- }),
- [locale, routeData?.quote.currencyCode]
+ const formatter = useCurrencyFormatter({
+ currency: routeData?.quote.currencyCode ?? "USD"
+ });
+ // Settlement money at the document currency's configured decimals.
+ const currencyDecimals = useCurrencyDecimals(
+ routeData?.quote?.currencyCode ?? "USD"
);
const [selectedLines, setSelectedLines] = useState<
@@ -884,13 +879,10 @@ const QuoteSummary = ({
<VStack spacing={2} className="mt-8">
<HStack className="justify-between text-sm text-muted-foreground w-full">
<span>Subtotal:</span>
- <MotionNumber
+ <MotionMoney
value={subtotal + totalDiscount}
- format={{
- style: "currency",
- currency: routeData?.quote?.currencyCode ?? "USD"
- }}
- locales={locale}
+ currency={routeData?.quote?.currencyCode ?? "USD"}
+ decimalPlaces={currencyDecimals}
/>
</HStack>
{totalDiscount > 0 && (
@@ -898,26 +890,20 @@ const QuoteSummary = ({
<span>Discount:</span>
<span className="text-muted-foreground">
-
- <MotionNumber
+ <MotionMoney
value={totalDiscount}
- format={{
- style: "currency",
- currency: routeData?.quote?.currencyCode ?? "USD"
- }}
- locales={locale}
+ currency={routeData?.quote?.currencyCode ?? "USD"}
+ decimalPlaces={currencyDecimals}
/>
</span>
</HStack>
)}
<HStack className="justify-between text-sm text-muted-foreground w-full">
<span>Tax:</span>
- <MotionNumber
+ <MotionMoney
value={tax}
- format={{
- style: "currency",
- currency: routeData?.quote?.currencyCode ?? "USD"
- }}
- locales={locale}
+ currency={routeData?.quote?.currencyCode ?? "USD"}
+ decimalPlaces={currencyDecimals}
/>
</HStack>
<HStack className="justify-between text-sm text-muted-foreground w-full">
@@ -934,13 +920,10 @@ const QuoteSummary = ({
<Trans>Edit Shipping</Trans>
</Button>
</VStack>
- <MotionNumber
+ <MotionMoney
value={convertedShippingCost}
- format={{
- style: "currency",
- currency: routeData?.quote.currencyCode ?? "USD"
- }}
- locales={locale}
+ currency={routeData?.quote?.currencyCode ?? "USD"}
+ decimalPlaces={currencyDecimals}
/>
</>
) : isEditable ? (
@@ -956,13 +939,10 @@ const QuoteSummary = ({
</HStack>
<HStack className="justify-between text-xl font-semibold w-full">
<span>Total:</span>
- <MotionNumber
+ <MotionMoney
value={total}
- format={{
- style: "currency",
- currency: routeData?.quote.currencyCode ?? "USD"
- }}
- locales={locale}
+ currency={routeData?.quote?.currencyCode ?? "USD"}
+ decimalPlaces={currencyDecimals}
/>
</HStack>
</VStack>
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteToOrderDrawer.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteToOrderDrawer.tsx
index c8d95f10d3..3f3b89f8f5 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteToOrderDrawer.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteToOrderDrawer.tsx
@@ -29,7 +29,7 @@ import {
toast,
VStack
} from "@carbon/react";
-import { pluralize } from "@carbon/utils";
+import { INPUT_FORMAT, pluralize } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { Dispatch, SetStateAction } from "react";
import { useEffect, useMemo, useState } from "react";
@@ -53,7 +53,7 @@ import { Enumerable } from "~/components/Enumerable";
import { CustomerContact, EmailRecipients } from "~/components/Form";
import { usePaymentTerm } from "~/components/Form/PaymentTerm";
import { useShippingMethod } from "~/components/Form/ShippingMethod";
-import { useRouteData, useUser } from "~/hooks";
+import { useCurrencyDecimals, useRouteData, useUser } from "~/hooks";
import { useCurrencyFormatter } from "~/hooks/useCurrencyFormatter";
import { useIntegrations } from "~/hooks/useIntegrations";
import { getDocumentType } from "~/modules/shared";
@@ -484,6 +484,7 @@ const LinePricingOptions = ({
setSelectedLines
}: LinePricingOptionsProps) => {
const [selectedValue, setSelectedValue] = useState("");
+ const currencyDecimals = useCurrencyDecimals(quoteCurrency);
const [showOverride, setShowOverride] = useState(false);
const [overridePricing, setOverridePricing] = useState<SelectedLine>({
quantity: 1,
@@ -721,10 +722,10 @@ const LinePricingOptions = ({
? overridePricing.convertedNetUnitPrice
: overridePricing.netUnitPrice
}
- formatOptions={{
- style: "currency",
- currency: quoteCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(
+ quoteCurrency,
+ currencyDecimals
+ )}
onChange={(netUnitPrice) =>
setOverridePricing((v) => ({
...v,
@@ -751,10 +752,10 @@ const LinePricingOptions = ({
? overridePricing.convertedShippingCost
: overridePricing.shippingCost
}
- formatOptions={{
- style: "currency",
- currency: quoteCurrency
- }}
+ formatOptions={INPUT_FORMAT.money(
+ quoteCurrency,
+ currencyDecimals
+ )}
onChange={(shippingCost) =>
setOverridePricing((v) => ({
...v,
@@ -781,10 +782,10 @@ const LinePricingOptions = ({
? overridePricing.convertedAddOn
: overridePricing.addOn
}
- formatOptions={{
- style: "currency",
- currency: quoteCurrency
- }}
+ formatOptions={INPUT_FORMAT.money(
+ quoteCurrency,
+ currencyDecimals
+ )}
onChange={(addOn) =>
setOverridePricing((v) => ({
...v,
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
index bd7ab14828..ac9eea34d7 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
@@ -34,7 +34,7 @@ import {
useMount,
VStack
} from "@carbon/react";
-import { getItemReadableId } from "@carbon/utils";
+import { getItemReadableId, INPUT_FORMAT, INPUT_STEP } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { useCallback, useEffect, useState } from "react";
import {
@@ -61,6 +61,7 @@ import {
} from "~/components/Form";
import { itemTypeLabel } from "~/components/Form/itemTypeLabel";
import {
+ useCurrencyDecimals,
useCurrencyFormatter,
usePercentFormatter,
usePermissions,
@@ -112,6 +113,7 @@ const SalesOrderLineForm = ({
const isEditable = !isLocked;
const baseCurrency = company?.baseCurrencyCode ?? "USD";
+ const currencyDecimals = useCurrencyDecimals(baseCurrency);
const [items] = useItems();
const [lineType, setLineType] = useState(initialValues.salesOrderLineType);
@@ -657,10 +659,10 @@ const SalesOrderLineForm = ({
<NumberControlled
name="unitPrice"
value={itemData.unitPrice}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(
+ baseCurrency,
+ currencyDecimals
+ )}
onChange={(value) =>
setItemData((d) => ({
...d,
@@ -797,39 +799,35 @@ const SalesOrderLineForm = ({
label={t`Tax Percent`}
minValue={0}
maxValue={1}
- step={0.0001}
- formatOptions={{
- style: "percent",
- minimumFractionDigits: 0,
- maximumFractionDigits: 2
- }}
+ step={INPUT_STEP.rate}
+ formatOptions={INPUT_FORMAT.rate}
/>
<Number
name="shippingCost"
label={t`Shipping Cost`}
minValue={0}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.money(
+ baseCurrency,
+ currencyDecimals
+ )}
termId="sales-order-line-shipping"
/>
<Number
name="addOnCost"
label={t`Add-On Cost`}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.money(
+ baseCurrency,
+ currencyDecimals
+ )}
termId="sales-order-line-add-on-cost"
/>
<Number
name="nonTaxableAddOnCost"
label={t`Non-Taxable Add-On Cost`}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.money(
+ baseCurrency,
+ currencyDecimals
+ )}
termId="sales-order-line-non-taxable-add-on-cost"
/>
</div>
@@ -897,10 +895,10 @@ const SalesOrderLineForm = ({
label={t`Unit Price`}
isOptional={false}
value={assetData.unitPrice}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.price(
+ baseCurrency,
+ currencyDecimals
+ )}
onChange={(value) =>
setAssetData((d) => ({
...d,
@@ -972,12 +970,8 @@ const SalesOrderLineForm = ({
value={assetData.taxPercent}
minValue={0}
maxValue={1}
- step={0.0001}
- formatOptions={{
- style: "percent",
- minimumFractionDigits: 0,
- maximumFractionDigits: 2
- }}
+ step={INPUT_STEP.rate}
+ formatOptions={INPUT_FORMAT.rate}
onChange={(value) =>
setAssetData((d) => ({
...d,
@@ -990,10 +984,10 @@ const SalesOrderLineForm = ({
label={t`Shipping Cost`}
value={assetData.shippingCost}
minValue={0}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.money(
+ baseCurrency,
+ currencyDecimals
+ )}
onChange={(value) =>
setAssetData((d) => ({
...d,
@@ -1006,10 +1000,10 @@ const SalesOrderLineForm = ({
name="addOnCost"
label={t`Add-On Cost`}
value={assetData.addOnCost}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.money(
+ baseCurrency,
+ currencyDecimals
+ )}
onChange={(value) =>
setAssetData((d) => ({
...d,
@@ -1022,10 +1016,10 @@ const SalesOrderLineForm = ({
name="nonTaxableAddOnCost"
label={t`Non-Taxable Add-On Cost`}
value={assetData.nonTaxableAddOnCost}
- formatOptions={{
- style: "currency",
- currency: baseCurrency
- }}
+ formatOptions={INPUT_FORMAT.money(
+ baseCurrency,
+ currencyDecimals
+ )}
onChange={(value) =>
setAssetData((d) => ({
...d,
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineJobs.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineJobs.tsx
index fac7b3586b..0a357a807e 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineJobs.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineJobs.tsx
@@ -25,6 +25,7 @@ import {
useMount,
VStack
} from "@carbon/react";
+import { scrapAllowance } from "@carbon/utils";
import {
getLocalTimeZone,
isSameDay,
@@ -104,12 +105,18 @@ export function SalesOrderLineJobs({
quantity: number;
scrapQuantity: number;
}>(() => {
- const quantity = itemReplenishment.lotSize
- ? Math.min(quantityRequired, itemReplenishment.lotSize)
- : quantityRequired;
+ // quantityRequired goes negative once jobs cover more than the sale
+ // quantity; without the clamp the scrap allowance below initializes
+ // negative, which the field's minValue={0} can no longer undo.
+ const quantity = Math.max(
+ 0,
+ itemReplenishment.lotSize
+ ? Math.min(quantityRequired, itemReplenishment.lotSize)
+ : quantityRequired
+ );
return {
quantity,
- scrapQuantity: Math.ceil(quantity * scrapPercentage)
+ scrapQuantity: scrapAllowance(quantity, scrapPercentage)
};
});
@@ -227,7 +234,7 @@ export function SalesOrderLineJobs({
setQuantities((prev) => ({
...prev,
quantity: value,
- scrapQuantity: Math.ceil(value * scrapPercentage)
+ scrapQuantity: scrapAllowance(value, scrapPercentage)
}));
}}
minValue={0}
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderShipmentForm.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderShipmentForm.tsx
index 4aa920e472..9905d62925 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderShipmentForm.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderShipmentForm.tsx
@@ -6,6 +6,7 @@ import {
CardHeader,
CardTitle
} from "@carbon/react";
+import { INPUT_FORMAT } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { forwardRef, useImperativeHandle, useRef, useState } from "react";
import { useFetcher, useParams } from "react-router";
@@ -24,7 +25,12 @@ import {
ShippingMethod,
Submit
} from "~/components/Form";
-import { usePermissions, useRouteData, useUser } from "~/hooks";
+import {
+ useCurrencyDecimals,
+ usePermissions,
+ useRouteData,
+ useUser
+} from "~/hooks";
import { incoterms } from "~/modules/shared";
import type { action } from "~/routes/x+/sales-order+/$orderId.shipment";
import { path } from "~/utils/path";
@@ -81,6 +87,9 @@ const SalesOrderShipmentForm = forwardRef<
}>(path.to.salesOrder(orderId));
const { company } = useUser();
+ const currencyDecimals = useCurrencyDecimals(
+ routeData?.salesOrder?.currencyCode ?? company?.baseCurrencyCode
+ );
const isLocked = isSalesOrderLocked(routeData?.salesOrder?.status);
const isCustomer = permissions.is("customer");
@@ -113,12 +122,11 @@ const SalesOrderShipmentForm = forwardRef<
name="shippingCost"
label={t`Shipping Cost`}
minValue={0}
- formatOptions={{
- style: "currency",
- currency:
- routeData?.salesOrder?.currencyCode ??
- company?.baseCurrencyCode
- }}
+ formatOptions={INPUT_FORMAT.money(
+ routeData?.salesOrder?.currencyCode ??
+ company?.baseCurrencyCode,
+ currencyDecimals
+ )}
ref={shippingCostRef}
/>
<Location
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx
index 5b4132a1bf..715a7bdd9d 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx
@@ -31,7 +31,6 @@ import {
import { Trans, useLingui } from "@lingui/react/macro";
import { useLocale } from "@react-aria/i18n";
import { motion } from "framer-motion";
-import MotionNumber from "motion-number";
import { useMemo, useState } from "react";
import {
LuChevronRight,
@@ -41,9 +40,21 @@ import {
LuTriangleAlert
} from "react-icons/lu";
import { Link, useParams } from "react-router";
-import { CustomerAvatar, DateTime, Hyperlink, MethodIcon } from "~/components";
+import {
+ CustomerAvatar,
+ DateTime,
+ Hyperlink,
+ MethodIcon,
+ MotionMoney
+} from "~/components";
import { Confirm } from "~/components/Modals";
-import { usePercentFormatter, usePermissions, useRouteData } from "~/hooks";
+import {
+ useCurrencyDecimals,
+ useCurrencyFormatter,
+ usePercentFormatter,
+ usePermissions,
+ useRouteData
+} from "~/hooks";
import JobStatus from "~/modules/production/ui/Jobs/JobStatus";
import { getPrivateUrl, path } from "~/utils/path";
import { isSalesOrderLocked } from "../../sales.models";
@@ -80,16 +91,15 @@ const SalesOrderSummary = ({
const salesOrderToJobsModal = useDisclosure();
const { locale } = useLocale();
- const formatter = useMemo(
- () =>
- new Intl.NumberFormat(locale, {
- style: "currency",
- currency: routeData?.salesOrder?.currencyCode ?? "USD"
- }),
- [locale, routeData?.salesOrder?.currencyCode]
- );
+ const formatter = useCurrencyFormatter({
+ currency: routeData?.salesOrder?.currencyCode ?? "USD"
+ });
const isEditable = !isSalesOrderLocked(routeData?.salesOrder?.status);
+ // Settlement money at the document currency's configured decimals.
+ const currencyDecimals = useCurrencyDecimals(
+ routeData?.salesOrder?.currencyCode ?? "USD"
+ );
// Calculate totals
const subtotal =
@@ -231,26 +241,20 @@ const SalesOrderSummary = ({
<span>
<Trans>Subtotal:</Trans>
</span>
- <MotionNumber
+ <MotionMoney
value={subtotal}
- format={{
- style: "currency",
- currency: routeData?.salesOrder?.currencyCode ?? "USD"
- }}
- locales={locale}
+ currency={routeData?.salesOrder?.currencyCode ?? "USD"}
+ decimalPlaces={currencyDecimals}
/>
</HStack>
<HStack className="justify-between text-sm text-muted-foreground w-full">
<span>
<Trans>Tax:</Trans>
</span>
- <MotionNumber
+ <MotionMoney
value={tax}
- format={{
- style: "currency",
- currency: routeData?.salesOrder?.currencyCode ?? "USD"
- }}
- locales={locale}
+ currency={routeData?.salesOrder?.currencyCode ?? "USD"}
+ decimalPlaces={currencyDecimals}
/>
</HStack>
<HStack className="justify-between text-sm text-muted-foreground w-full">
@@ -269,13 +273,10 @@ const SalesOrderSummary = ({
<Trans>Edit Shipping</Trans>
</Button>
</VStack>
- <MotionNumber
+ <MotionMoney
value={convertedShippingCost}
- format={{
- style: "currency",
- currency: routeData?.salesOrder.currencyCode ?? "USD"
- }}
- locales={locale}
+ currency={routeData?.salesOrder?.currencyCode ?? "USD"}
+ decimalPlaces={currencyDecimals}
/>
</>
) : isEditable ? (
@@ -293,13 +294,10 @@ const SalesOrderSummary = ({
<span>
<Trans>Total:</Trans>
</span>
- <MotionNumber
+ <MotionMoney
value={total}
- format={{
- style: "currency",
- currency: routeData?.salesOrder?.currencyCode ?? "USD"
- }}
- locales={locale}
+ currency={routeData?.salesOrder?.currencyCode ?? "USD"}
+ decimalPlaces={currencyDecimals}
/>
</HStack>
<div className="h-px bg-border my-2 w-full" />
@@ -307,26 +305,20 @@ const SalesOrderSummary = ({
<span>
<Trans>Invoiced Amount:</Trans>
</span>
- <MotionNumber
+ <MotionMoney
value={routeData?.invoiceSummary?.invoicedAmount ?? 0}
- format={{
- style: "currency",
- currency: routeData?.salesOrder?.currencyCode ?? "USD"
- }}
- locales={locale}
+ currency={routeData?.salesOrder?.currencyCode ?? "USD"}
+ decimalPlaces={currencyDecimals}
/>
</HStack>
<HStack className="justify-between text-sm text-muted-foreground w-full">
<span>
<Trans>Paid Amount:</Trans>
</span>
- <MotionNumber
+ <MotionMoney
value={routeData?.invoiceSummary?.paidAmount ?? 0}
- format={{
- style: "currency",
- currency: routeData?.salesOrder?.currencyCode ?? "USD"
- }}
- locales={locale}
+ currency={routeData?.salesOrder?.currencyCode ?? "USD"}
+ decimalPlaces={currencyDecimals}
/>
</HStack>
{(routeData?.invoiceSummary?.currencyMismatchCount ?? 0) > 0 && (
@@ -363,6 +355,8 @@ function LineItems({
if (!orderId) throw new Error("Could not find orderId");
const percentFormatter = usePercentFormatter();
+ // Settlement money at the document currency's configured decimals.
+ const currencyDecimals = useCurrencyDecimals(currencyCode);
const [openItems, setOpenItems] = useState<string[]>([]);
const todaysDate = useMemo(() => today(getLocalTimeZone()), []);
@@ -445,8 +439,7 @@ function LineItems({
className="flex-shrink-0 items-end w-auto"
>
<HStack spacing={4}>
- <MotionNumber
- className="font-bold text-xl whitespace-nowrap"
+ <MotionMoney
value={
((line?.convertedUnitPrice ?? 0) *
(line?.saleQuantity ?? 0) +
@@ -455,11 +448,8 @@ function LineItems({
(1 + (line?.taxPercent ?? 0)) +
(line?.convertedNonTaxableAddOnCost ?? 0)
}
- format={{
- style: "currency",
- currency: currencyCode
- }}
- locales={locale}
+ currency={currencyCode}
+ decimalPlaces={currencyDecimals}
/>
<motion.div
animate={{
@@ -574,23 +564,23 @@ function LineItems({
<Tr>
<Td>Unit Price</Td>
<Td className="text-right">
- <MotionNumber
+ <MotionMoney
value={line.convertedUnitPrice ?? 0}
- format={{ style: "currency", currency: currencyCode }}
- locales={locale}
+ currency={currencyCode}
+ decimalPlaces={currencyDecimals}
/>
</Td>
</Tr>
<Tr className="border-b border-border">
<Td>Extended Price</Td>
<Td className="text-right">
- <MotionNumber
+ <MotionMoney
value={
(line.convertedUnitPrice ?? 0) *
(line.saleQuantity ?? 0)
}
- format={{ style: "currency", currency: currencyCode }}
- locales={locale}
+ currency={currencyCode}
+ decimalPlaces={currencyDecimals}
/>
</Td>
</Tr>
@@ -599,13 +589,10 @@ function LineItems({
<Tr>
<Td>Additional Charges</Td>
<Td className="text-right">
- <MotionNumber
+ <MotionMoney
value={line.addOnCost ?? 0}
- format={{
- style: "currency",
- currency: currencyCode
- }}
- locales={locale}
+ currency={currencyCode}
+ decimalPlaces={currencyDecimals}
/>
</Td>
</Tr>
@@ -615,13 +602,10 @@ function LineItems({
<Tr>
<Td>Non-Taxable Charges</Td>
<Td className="text-right">
- <MotionNumber
+ <MotionMoney
value={line.nonTaxableAddOnCost ?? 0}
- format={{
- style: "currency",
- currency: currencyCode
- }}
- locales={locale}
+ currency={currencyCode}
+ decimalPlaces={currencyDecimals}
/>
</Td>
</Tr>
@@ -630,7 +614,7 @@ function LineItems({
<Tr key="subtotal">
<Td>Subtotal</Td>
<Td className="text-right">
- <MotionNumber
+ <MotionMoney
value={
(line.convertedUnitPrice ?? 0) *
(line.saleQuantity ?? 0) +
@@ -638,11 +622,8 @@ function LineItems({
(line.convertedNonTaxableAddOnCost ?? 0) +
(line.convertedShippingCost ?? 0)
}
- format={{
- style: "currency",
- currency: currencyCode
- }}
- locales={locale}
+ currency={currencyCode}
+ decimalPlaces={currencyDecimals}
/>
</Td>
</Tr>
@@ -652,7 +633,7 @@ function LineItems({
Tax ({percentFormatter.format(line.taxPercent ?? 0)})
</Td>
<Td className="text-right">
- <MotionNumber
+ <MotionMoney
value={
((line.convertedUnitPrice ?? 0) *
(line.saleQuantity ?? 0) +
@@ -660,11 +641,8 @@ function LineItems({
(line.convertedShippingCost ?? 0)) *
(line.taxPercent ?? 0)
}
- format={{
- style: "currency",
- currency: currencyCode
- }}
- locales={locale}
+ currency={currencyCode}
+ decimalPlaces={currencyDecimals}
/>
</Td>
</Tr>
@@ -672,7 +650,7 @@ function LineItems({
<Tr key="total" className="font-bold">
<Td>Total</Td>
<Td className="text-right">
- <MotionNumber
+ <MotionMoney
value={
((line.convertedUnitPrice ?? 0) *
(line.saleQuantity ?? 0) +
@@ -681,11 +659,8 @@ function LineItems({
(1 + (line.taxPercent ?? 0)) +
(line.convertedNonTaxableAddOnCost ?? 0)
}
- format={{
- style: "currency",
- currency: currencyCode
- }}
- locales={locale}
+ currency={currencyCode}
+ decimalPlaces={currencyDecimals}
/>
</Td>
</Tr>
diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.ts
index 15f43edc04..3b86eb11bf 100644
--- a/apps/erp/app/modules/settings/settings.service.ts
+++ b/apps/erp/app/modules/settings/settings.service.ts
@@ -1475,6 +1475,17 @@ export async function updateDefaultSupplierCc(
.eq("id", companyId);
}
+export async function updateShowCurrencyTrailingZerosSetting(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ showCurrencyTrailingZeros: boolean
+) {
+ return client
+ .from("companySettings")
+ .update(sanitize({ showCurrencyTrailingZeros }))
+ .eq("id", companyId);
+}
+
export async function updateShowSupplierReadableIdSetting(
client: SupabaseClient<Database>,
companyId: string,
diff --git a/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleCard.tsx b/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleCard.tsx
index f09dad4cc6..a69d799082 100644
--- a/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleCard.tsx
+++ b/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleCard.tsx
@@ -42,10 +42,7 @@ const ApprovalRuleCard = memo(
const [params] = useUrlParams();
const navigate = useNavigate();
const permissions = usePermissions();
- const currencyFormatter = useCurrencyFormatter({
- notation: "compact", // short/compact form
- compactDisplay: "short" // "short" → 1.2M, "long" → 1.2 million
- });
+ const currencyFormatter = useCurrencyFormatter({ compact: true });
const deleteDisclosure = useDisclosure();
const canEdit = permissions.can("update", "settings");
diff --git a/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleForm.tsx b/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleForm.tsx
index 6c2bc4c15c..dc7373a434 100644
--- a/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleForm.tsx
+++ b/apps/erp/app/modules/settings/ui/Approvals/ApprovalRuleForm.tsx
@@ -16,9 +16,10 @@ import {
HStack,
VStack
} from "@carbon/react";
+import { INPUT_FORMAT } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { Employee, Users } from "~/components/Form";
-import { usePermissions, useUser } from "~/hooks";
+import { useCurrencyDecimals, usePermissions, useUser } from "~/hooks";
import type { ApprovalRule } from "~/modules/shared";
import {
type ApprovalDocumentType,
@@ -43,6 +44,7 @@ const ApprovalRuleForm = ({
const {
company: { baseCurrencyCode }
} = useUser();
+ const currencyDecimals = useCurrencyDecimals(baseCurrencyCode);
const isEditing = !!rule?.id;
const isDisabled = !permissions.can("update", "settings");
const effectiveDocumentType = rule?.documentType || documentType;
@@ -107,10 +109,10 @@ const ApprovalRuleForm = ({
name="lowerBoundAmount"
label={t`Minimum Amount`}
helperText={t`Approval is required at or above this amount, up to the next rule's minimum`}
- formatOptions={{
- style: "currency",
- currency: baseCurrencyCode
- }}
+ formatOptions={INPUT_FORMAT.money(
+ baseCurrencyCode,
+ currencyDecimals
+ )}
/>
)}
diff --git a/apps/erp/app/modules/shared/shared.server.ts b/apps/erp/app/modules/shared/shared.server.ts
index 226cb84191..789ffb3ede 100644
--- a/apps/erp/app/modules/shared/shared.server.ts
+++ b/apps/erp/app/modules/shared/shared.server.ts
@@ -7,7 +7,7 @@ import { startOfWeek } from "@internationalized/date";
import { renderAsync } from "@react-email/components";
import type { SupabaseClient } from "@supabase/supabase-js";
import type { LoaderFunctionArgs } from "react-router";
-import { getPaymentTermsList } from "~/modules/accounting";
+import { getCurrencyByCode, getPaymentTermsList } from "~/modules/accounting";
import {
getCustomerContact,
getSalesOrder,
@@ -224,6 +224,7 @@ export async function generateAndAttachSalesOrderPdf(args: {
export async function sendSalesOrderEmail(args: {
salesOrderId: string;
companyId: string;
+ companyGroupId: string;
userId: string;
customerContactId: string;
cc?: string[];
@@ -235,6 +236,7 @@ export async function sendSalesOrderEmail(args: {
const {
salesOrderId,
companyId,
+ companyGroupId,
userId,
customerContactId,
cc: ccSelections,
@@ -281,7 +283,18 @@ export async function sendSalesOrderEmail(args: {
return { success: false, message: "Failed to get payment terms" };
}
+ // Amounts render at the ORDER currency's decimals, same as the PDF of the
+ // same order — otherwise the two disagree about the width of a total.
+ const currencyRow = salesOrder.data.currencyCode
+ ? await getCurrencyByCode(
+ serviceRole,
+ companyGroupId,
+ salesOrder.data.currencyCode
+ )
+ : null;
+
const emailTemplate = SalesOrderEmail({
+ currencyDecimals: currencyRow?.data?.decimalPlaces ?? null,
company: company.data as any,
locale: locales?.[0] ?? "en-US",
salesOrder: salesOrder.data,
diff --git a/apps/erp/app/routes/api+/accounting.currencies.ts b/apps/erp/app/routes/api+/accounting.currencies.ts
index aa1019985c..f3dede1ef3 100644
--- a/apps/erp/app/routes/api+/accounting.currencies.ts
+++ b/apps/erp/app/routes/api+/accounting.currencies.ts
@@ -7,9 +7,9 @@ import { getCurrenciesList } from "~/modules/accounting";
import { currenciesQuery } from "~/utils/react-query";
export async function loader({ request }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {});
+ const { client, companyGroupId } = await requirePermissions(request, {});
- return await getCurrenciesList(client);
+ return await getCurrenciesList(client, companyGroupId);
}
export async function clientLoader({ serverLoader }: ClientLoaderFunctionArgs) {
diff --git a/apps/erp/app/routes/api+/kanban.$id.tsx b/apps/erp/app/routes/api+/kanban.$id.tsx
index cecccb1603..f64f3cdfa2 100644
--- a/apps/erp/app/routes/api+/kanban.$id.tsx
+++ b/apps/erp/app/routes/api+/kanban.$id.tsx
@@ -304,6 +304,7 @@ async function handleKanban({
supplierPart?.data?.unitPrice ?? itemCost?.unitCost ?? 0,
supplierShippingCost: 0,
supplierTaxAmount: 0,
+ taxPercent: 0,
exchangeRate: 1,
purchaseUnitOfMeasureCode: kanban.data.purchaseUnitOfMeasureCode!,
inventoryUnitOfMeasureCode:
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 b9df085b8a..49d00b403f 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,6 +1,6 @@
{
- "generated": "2026-08-12T17:55:02.705Z",
- "totalTools": 1434,
+ "generated": "2026-08-13T13:42:54.728Z",
+ "totalTools": 1436,
"modules": 15,
"tools": [
{
@@ -1291,6 +1291,25 @@
]
}
},
+ {
+ "name": "accounting_getBaseCurrencyDecimalPlaces",
+ "module": "accounting",
+ "classification": "READ",
+ "description": "get base currency decimal places",
+ "paramCount": 0,
+ "serviceParams": [
+ "client",
+ "companyId",
+ "companyGroupId"
+ ],
+ "injectAuth": [
+ "companyId"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {}
+ }
+ },
{
"name": "accounting_getCurrencyByCode",
"module": "accounting",
@@ -1363,7 +1382,8 @@
"description": "get currencies list",
"paramCount": 0,
"serviceParams": [
- "client"
+ "client",
+ "companyGroupId"
],
"injectAuth": [
"companyId"
@@ -42783,6 +42803,33 @@
]
}
},
+ {
+ "name": "settings_updateHideCurrencyTrailingZerosSetting",
+ "module": "settings",
+ "classification": "WRITE",
+ "description": "update hide currency trailing zeros setting",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "companyId",
+ "hideCurrencyTrailingZeros"
+ ],
+ "injectAuth": [
+ "companyId",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "hideCurrencyTrailingZeros": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "hideCurrencyTrailingZeros"
+ ]
+ }
+ },
{
"name": "settings_updateShowSupplierReadableIdSetting",
"module": "settings",
diff --git a/apps/erp/app/routes/api+/purchasing.digital-quote.$id.tsx b/apps/erp/app/routes/api+/purchasing.digital-quote.$id.tsx
index 6604e5a7eb..49511ff329 100644
--- a/apps/erp/app/routes/api+/purchasing.digital-quote.$id.tsx
+++ b/apps/erp/app/routes/api+/purchasing.digital-quote.$id.tsx
@@ -4,6 +4,7 @@ import { validationError, validator } from "@carbon/form";
import { trigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
import { NotificationEvent } from "@carbon/notifications";
+import { deriveRate, taxableBase } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import { z } from "zod";
import {
@@ -186,6 +187,17 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { lineId, quantity, selectedLine } = priceRecordsToProcess[i];
const existingPrice = existingPriceChecks[i];
+ // The portal collects amounts only; seed the stored rate from the
+ // canonical denominator (unit price x quantity + shipping).
+ const taxPercent = deriveRate(
+ selectedLine.supplierTaxAmount ?? 0,
+ taxableBase(
+ selectedLine.supplierUnitPrice ?? 0,
+ quantity,
+ selectedLine.supplierShippingCost ?? 0
+ )
+ );
+
if (existingPrice.data) {
// Update existing price record
priceUpdates.push(
@@ -196,6 +208,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
leadTime: selectedLine.leadTime ?? 0,
supplierShippingCost: selectedLine.supplierShippingCost ?? 0,
supplierTaxAmount: selectedLine.supplierTaxAmount ?? 0,
+ taxPercent,
updatedAt: new Date().toISOString(),
updatedBy: quote.data.createdBy
})
@@ -213,20 +226,35 @@ export async function action({ request, params }: ActionFunctionArgs) {
leadTime: selectedLine.leadTime ?? 0,
supplierShippingCost: selectedLine.supplierShippingCost ?? 0,
supplierTaxAmount: selectedLine.supplierTaxAmount ?? 0,
+ taxPercent,
exchangeRate: quote.data.exchangeRate ?? 1,
createdBy: quote.data.createdBy
});
}
}
- // Execute all updates and inserts
- await Promise.all([
+ // Execute all updates and inserts. The Supabase client resolves rather
+ // than throwing, so a failed price write is invisible unless every result
+ // is inspected — without this the quote still flipped to Active carrying
+ // the supplier's old prices.
+ const priceWrites = await Promise.all([
...priceUpdates,
priceInserts.length > 0
? serviceRole.from("supplierQuoteLinePrice").insert(priceInserts)
: Promise.resolve({ data: null, error: null })
]);
+ const priceWriteError = priceWrites.find(
+ (result) => result?.error
+ )?.error;
+ if (priceWriteError) {
+ logger.error("Failed to save digital quote prices", {
+ error: priceWriteError,
+ quoteId: quote.data.id
+ });
+ return { success: false, message: "Failed to save quote prices" };
+ }
+
const now = new Date().toISOString();
// Update quote status to Active (submit moves from Draft to Active)
diff --git a/apps/erp/app/routes/file+/purchase-order+/$orderId[.]pdf.tsx b/apps/erp/app/routes/file+/purchase-order+/$orderId[.]pdf.tsx
index 00d47002a2..2e591ca679 100644
--- a/apps/erp/app/routes/file+/purchase-order+/$orderId[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/purchase-order+/$orderId[.]pdf.tsx
@@ -11,7 +11,7 @@ import type { JSONContent } from "@carbon/react";
import { getPreferenceHeaders } from "@carbon/utils";
import { renderToStream } from "@react-pdf/renderer";
import type { LoaderFunctionArgs } from "react-router";
-import { getPaymentTermsList } from "~/modules/accounting";
+import { getCurrencyByCode, getPaymentTermsList } from "~/modules/accounting";
import {
getPurchaseOrder,
getPurchaseOrderLines,
@@ -30,9 +30,12 @@ import { getBase64ImageFromSupabase } from "~/modules/shared";
const logger = getLogger("erp", "purchase-order", "pdf");
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {
- view: "purchasing"
- });
+ const { client, companyId, companyGroupId } = await requirePermissions(
+ request,
+ {
+ view: "purchasing"
+ }
+ );
const { orderId } = params;
if (!orderId) throw new Error("Could not find orderId");
@@ -148,6 +151,17 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
await ensureFont(resolved.settings.fontFamily);
+ // Settlement decimals from the document currency's row (authoritative over
+ // CLDR); null keeps the PDF's historical 2dp fallback.
+ const currencyRow = purchaseOrder.data?.currencyCode
+ ? await getCurrencyByCode(
+ client,
+ companyGroupId,
+ purchaseOrder.data.currencyCode
+ )
+ : null;
+ const currencyDecimals = currencyRow?.data?.decimalPlaces ?? null;
+
const stream = await renderToStream(
<PurchaseOrderPDF
company={company.data as any}
@@ -158,6 +172,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
: null
}
locale={locale}
+ currencyDecimals={currencyDecimals}
paymentTerms={paymentTerms.data ?? []}
purchaseOrder={purchaseOrder.data}
purchaseOrderLines={purchaseOrderLines.data ?? []}
diff --git a/apps/erp/app/routes/file+/quote+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/quote+/$id[.]pdf.tsx
index 0ac818b744..498dd23321 100644
--- a/apps/erp/app/routes/file+/quote+/$id[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/quote+/$id[.]pdf.tsx
@@ -142,6 +142,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
let exchangeRate = 1;
+ let currencyDecimals: number | null = null;
if (quote.data?.currencyCode) {
const currency = await getCurrencyByCode(
client,
@@ -151,6 +152,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
if (currency.data?.exchangeRate) {
exchangeRate = currency.data.exchangeRate;
}
+ currencyDecimals = currency.data?.decimalPlaces ?? null;
}
const resolved = resolveTemplate("quote", templateConfig);
@@ -166,6 +168,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
company={company.data as any}
companySettings={companySettings.data}
locale={locale}
+ currencyDecimals={currencyDecimals}
exchangeRate={exchangeRate}
quote={quote.data}
quoteLines={quoteLines.data ?? []}
diff --git a/apps/erp/app/routes/file+/sales-invoice+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/sales-invoice+/$id[.]pdf.tsx
index 67c31b84be..d7a30f53e3 100644
--- a/apps/erp/app/routes/file+/sales-invoice+/$id[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/sales-invoice+/$id[.]pdf.tsx
@@ -11,7 +11,7 @@ import type { JSONContent } from "@carbon/react";
import { getPreferenceHeaders } from "@carbon/utils";
import { renderToStream } from "@react-pdf/renderer";
import type { LoaderFunctionArgs } from "react-router";
-import { getPaymentTermsList } from "~/modules/accounting";
+import { getCurrencyByCode, getPaymentTermsList } from "~/modules/accounting";
import { getShippingMethodsList } from "~/modules/inventory";
import {
getSalesInvoice,
@@ -32,9 +32,12 @@ import { getBase64ImageFromSupabase } from "~/modules/shared";
const logger = getLogger("erp", "sales-invoice", "pdf");
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {
- view: "sales"
- });
+ const { client, companyId, companyGroupId } = await requirePermissions(
+ request,
+ {
+ view: "sales"
+ }
+ );
const { id } = params;
if (!id) throw new Error("Could not find id");
@@ -186,11 +189,23 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
// Register the chosen Google font (no-op for built-ins / Inter) before render.
await ensureFont(resolved.settings.fontFamily);
+ // Settlement decimals from the document currency's row (authoritative over
+ // CLDR); null keeps the PDF's historical 2dp fallback.
+ const currencyRow = salesInvoice.data?.currencyCode
+ ? await getCurrencyByCode(
+ client,
+ companyGroupId,
+ salesInvoice.data.currencyCode
+ )
+ : null;
+ const currencyDecimals = currencyRow?.data?.decimalPlaces ?? null;
+
const stream = await renderToStream(
<SalesInvoicePDF
company={company.data as any}
companySettings={companySettings.data}
locale={locale}
+ currencyDecimals={currencyDecimals}
meta={{
author: "Carbon",
keywords: "sales order",
diff --git a/apps/erp/app/routes/file+/sales-order+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/sales-order+/$id[.]pdf.tsx
index 02275b467d..254b1a5ff7 100644
--- a/apps/erp/app/routes/file+/sales-order+/$id[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/sales-order+/$id[.]pdf.tsx
@@ -11,7 +11,7 @@ import type { JSONContent } from "@carbon/react";
import { getPreferenceHeaders } from "@carbon/utils";
import { renderToStream } from "@react-pdf/renderer";
import type { LoaderFunctionArgs } from "react-router";
-import { getPaymentTermsList } from "~/modules/accounting";
+import { getCurrencyByCode, getPaymentTermsList } from "~/modules/accounting";
import { getShippingMethodsList } from "~/modules/inventory";
import {
getSalesOrder,
@@ -31,9 +31,12 @@ import { getBase64ImageFromSupabase } from "~/modules/shared";
const logger = getLogger("erp", "sales-order", "pdf");
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {
- view: "sales"
- });
+ const { client, companyId, companyGroupId } = await requirePermissions(
+ request,
+ {
+ view: "sales"
+ }
+ );
const { id } = params;
if (!id) throw new Error("Could not find id");
@@ -146,11 +149,23 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
await ensureFont(resolved.settings.fontFamily);
+ // Settlement decimals from the document currency's row (authoritative over
+ // CLDR); null keeps the PDF's historical 2dp fallback.
+ const currencyRow = salesOrder.data?.currencyCode
+ ? await getCurrencyByCode(
+ client,
+ companyGroupId,
+ salesOrder.data.currencyCode
+ )
+ : null;
+ const currencyDecimals = currencyRow?.data?.decimalPlaces ?? null;
+
const stream = await renderToStream(
<SalesOrderPDF
company={company.data as any}
companySettings={companySettings.data}
locale={locale}
+ currencyDecimals={currencyDecimals}
meta={{
author: "Carbon",
keywords: "sales order",
diff --git a/apps/erp/app/routes/share+/customer.$id.tsx b/apps/erp/app/routes/share+/customer.$id.tsx
index eeb6fb7282..5e035ea921 100644
--- a/apps/erp/app/routes/share+/customer.$id.tsx
+++ b/apps/erp/app/routes/share+/customer.$id.tsx
@@ -2,6 +2,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { companyHasPlan } from "@carbon/ee/plan.server";
import { getLogger } from "@carbon/logger";
import { Avatar } from "@carbon/react";
+import { SCALE_FORMAT } from "@carbon/utils";
import { useLocale, useNumberFormatter } from "@react-aria/i18n";
import type { ColumnDef } from "@tanstack/react-table";
import { useMemo } from "react";
@@ -154,10 +155,7 @@ export default function CustomerPortal() {
} = useLoaderData<typeof loader>();
const { locale } = useLocale();
- const formatter = useNumberFormatter({
- minimumFractionDigits: 0,
- maximumFractionDigits: 2
- });
+ const formatter = useNumberFormatter(SCALE_FORMAT);
const columns = useMemo<ColumnDef<(typeof salesOrderLines)[number]>[]>(() => {
return [
diff --git a/apps/erp/app/routes/share+/quote.$id.tsx b/apps/erp/app/routes/share+/quote.$id.tsx
index 0a5230c3c3..bceb5478bf 100644
--- a/apps/erp/app/routes/share+/quote.$id.tsx
+++ b/apps/erp/app/routes/share+/quote.$id.tsx
@@ -34,12 +34,11 @@ import {
useMode,
VStack
} from "@carbon/react";
-import { formatCityStatePostalCode } from "@carbon/utils";
+import { formatCityStatePostalCode, moneyFormatOptions } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { useLocale } from "@react-aria/i18n";
import type { PostgrestResponse } from "@supabase/supabase-js";
import { motion } from "framer-motion";
-import MotionNumber from "motion-number";
import type { Dispatch, SetStateAction } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useDropzone } from "react-dropzone";
@@ -53,8 +52,12 @@ import {
} from "react-icons/lu";
import type { LoaderFunctionArgs } from "react-router";
import { useFetcher, useLoaderData, useParams } from "react-router";
-import { DateTime } from "~/components";
-import { usePercentFormatter } from "~/hooks";
+import { DateTime, MotionMoney } from "~/components";
+import {
+ useCurrencyDecimals,
+ useCurrencyFormatter,
+ usePercentFormatter
+} from "~/hooks";
import { getPaymentTermsList } from "~/modules/accounting";
import { getShippingMethodsList } from "~/modules/inventory";
import type {
@@ -324,6 +327,8 @@ const LineItems = ({
selectedLines: Record<string, SelectedLine>;
setSelectedLines: Dispatch<SetStateAction<Record<string, SelectedLine>>>;
}) => {
+ // Settlement money at the document currency's configured decimals.
+ const currencyDecimals = useCurrencyDecimals(currencyCode);
const { company, quote, quoteLines, quoteLinePrices, thumbnails } =
useLoaderData<typeof loader>().data!;
@@ -404,8 +409,7 @@ const LineItems = ({
<div className="flex items-center gap-x-4 justify-between flex-grow">
<Heading>{line.itemReadableId}</Heading>
<HStack spacing={4}>
- <MotionNumber
- className="font-bold text-xl"
+ <MotionMoney
value={
(selectedLines[line.id!]?.convertedNetUnitPrice ??
0) *
@@ -422,11 +426,8 @@ const LineItems = ({
0)) *
(selectedLines[line.id!]?.taxPercent ?? 0)
}
- format={{
- style: "currency",
- currency: currencyCode
- }}
- locales={locale}
+ currency={currencyCode}
+ decimalPlaces={currencyDecimals}
/>
<motion.div
animate={{
@@ -505,6 +506,8 @@ const LinePricingOptions = ({
selectedLine,
setSelectedLines
}: LinePricingOptionsProps) => {
+ // Settlement money at the document currency's configured decimals.
+ const currencyDecimals = useCurrencyDecimals(quoteCurrency);
const percentFormatter = usePercentFormatter();
const { quote } = useLoaderData<typeof loader>().data!;
@@ -581,11 +584,12 @@ const LinePricingOptions = ({
const unitPriceformatter = useMemo(
() =>
- new Intl.NumberFormat(locale, {
- style: "currency",
- currency: quote.currencyCode ?? "USD",
- maximumFractionDigits: line.unitPricePrecision ?? 2
- }),
+ new Intl.NumberFormat(
+ locale,
+ moneyFormatOptions(line.unitPricePrecision ?? 2, {
+ currency: quote.currencyCode ?? "USD"
+ })
+ ),
[locale, quote.currencyCode, line.unitPricePrecision]
);
@@ -780,13 +784,13 @@ const LinePricingOptions = ({
<Trans>Extended Price</Trans>
</Td>
<Td className="text-right">
- <MotionNumber
+ <MotionMoney
value={
(selectedLine.convertedUnitPrice ?? 0) *
selectedLine.quantity
}
- format={{ style: "currency", currency: quoteCurrency }}
- locales={locale}
+ currency={quoteCurrency}
+ decimalPlaces={currencyDecimals}
/>
</Td>
</Tr>
@@ -799,14 +803,14 @@ const LinePricingOptions = ({
</Td>
<Td className="text-right">
-
- <MotionNumber
+ <MotionMoney
value={
(selectedLine.convertedUnitPrice ?? 0) *
selectedLine.quantity *
selectedLine.discountPercent
}
- format={{ style: "currency", currency: quoteCurrency }}
- locales={locale}
+ currency={quoteCurrency}
+ decimalPlaces={currencyDecimals}
/>
</Td>
</Tr>
@@ -824,10 +828,10 @@ const LinePricingOptions = ({
>
<Td>{charge.name}</Td>
<Td className="text-right">
- <MotionNumber
+ <MotionMoney
value={charge.amount}
- format={{ style: "currency", currency: quoteCurrency }}
- locales={locale}
+ currency={quoteCurrency}
+ decimalPlaces={currencyDecimals}
/>
</Td>
</Tr>
@@ -838,18 +842,15 @@ const LinePricingOptions = ({
<Trans>Subtotal</Trans>
</Td>
<Td className="text-right">
- <MotionNumber
+ <MotionMoney
value={
(selectedLine.convertedNetUnitPrice ?? 0) *
selectedLine.quantity +
selectedLine.convertedAddOn +
selectedLine.convertedShippingCost
}
- format={{
- style: "currency",
- currency: quoteCurrency
- }}
- locales={locale}
+ currency={quoteCurrency}
+ decimalPlaces={currencyDecimals}
/>
</Td>
</Tr>
@@ -860,7 +861,7 @@ const LinePricingOptions = ({
{percentFormatter.format(selectedLine.taxPercent)})
</Td>
<Td className="text-right">
- <MotionNumber
+ <MotionMoney
value={
((selectedLine.convertedNetUnitPrice ?? 0) *
selectedLine.quantity +
@@ -868,11 +869,8 @@ const LinePricingOptions = ({
selectedLine.convertedShippingCost) *
selectedLine.taxPercent
}
- format={{
- style: "currency",
- currency: quoteCurrency
- }}
- locales={locale}
+ currency={quoteCurrency}
+ decimalPlaces={currencyDecimals}
/>
</Td>
</Tr>
@@ -882,7 +880,7 @@ const LinePricingOptions = ({
<Trans>Total</Trans>
</Td>
<Td className="text-right">
- <MotionNumber
+ <MotionMoney
value={
(selectedLine.convertedNetUnitPrice ?? 0) *
selectedLine.quantity +
@@ -894,11 +892,8 @@ const LinePricingOptions = ({
selectedLine.convertedShippingCost) *
selectedLine.taxPercent
}
- format={{
- style: "currency",
- currency: quoteCurrency
- }}
- locales={locale}
+ currency={quoteCurrency}
+ decimalPlaces={currencyDecimals}
/>
</Td>
</Tr>
@@ -947,14 +942,11 @@ const Quote = ({ data }: { data: QuoteData }) => {
} = data;
const { t } = useLingui();
const { locale } = useLocale();
- const formatter = useMemo(
- () =>
- new Intl.NumberFormat(locale, {
- style: "currency",
- currency: quote.currencyCode ?? "USD"
- }),
- [locale, quote.currencyCode]
- );
+ const formatter = useCurrencyFormatter({
+ currency: quote.currencyCode ?? "USD"
+ });
+ // Settlement money at the document currency's configured decimals.
+ const currencyDecimals = useCurrencyDecimals(quote.currencyCode ?? "USD");
const { id } = useParams();
if (!id) throw new Error("Could not find external quote id");
@@ -1227,13 +1219,10 @@ const Quote = ({ data }: { data: QuoteData }) => {
<span>
<Trans>Subtotal</Trans>:
</span>
- <MotionNumber
+ <MotionMoney
value={subtotal + totalDiscount}
- format={{
- style: "currency",
- currency: quote.currencyCode ?? "USD"
- }}
- locales={locale}
+ currency={quote.currencyCode ?? "USD"}
+ decimalPlaces={currencyDecimals}
/>
</HStack>
{totalDiscount > 0 && (
@@ -1241,13 +1230,10 @@ const Quote = ({ data }: { data: QuoteData }) => {
<span>Discount:</span>
<span className="text-muted-foreground">
-
- <MotionNumber
+ <MotionMoney
value={totalDiscount}
- format={{
- style: "currency",
- currency: quote.currencyCode ?? "USD"
- }}
- locales={locale}
+ currency={quote.currencyCode ?? "USD"}
+ decimalPlaces={currencyDecimals}
/>
</span>
</HStack>
@@ -1256,13 +1242,10 @@ const Quote = ({ data }: { data: QuoteData }) => {
<span>
<Trans>Tax</Trans>:
</span>
- <MotionNumber
+ <MotionMoney
value={tax}
- format={{
- style: "currency",
- currency: quote.currencyCode ?? "USD"
- }}
- locales={locale}
+ currency={quote.currencyCode ?? "USD"}
+ decimalPlaces={currencyDecimals}
/>
</HStack>
{convertedShippingCost > 0 && (
@@ -1270,13 +1253,10 @@ const Quote = ({ data }: { data: QuoteData }) => {
<span>
<Trans>Shipping</Trans>:
</span>
- <MotionNumber
+ <MotionMoney
value={convertedShippingCost}
- format={{
- style: "currency",
- currency: quote.currencyCode ?? "USD"
- }}
- locales={locale}
+ currency={quote.currencyCode ?? "USD"}
+ decimalPlaces={currencyDecimals}
/>
</HStack>
)}
@@ -1285,13 +1265,10 @@ const Quote = ({ data }: { data: QuoteData }) => {
<span>
<Trans>Total</Trans>:
</span>
- <MotionNumber
+ <MotionMoney
value={total}
- format={{
- style: "currency",
- currency: quote.currencyCode ?? "USD"
- }}
- locales={locale}
+ currency={quote.currencyCode ?? "USD"}
+ decimalPlaces={currencyDecimals}
/>
</HStack>
</VStack>
diff --git a/apps/erp/app/routes/x+/accounting+/depreciation-runs.new.tsx b/apps/erp/app/routes/x+/accounting+/depreciation-runs.new.tsx
index b7a7f48aae..3f5ec9e94b 100644
--- a/apps/erp/app/routes/x+/accounting+/depreciation-runs.new.tsx
+++ b/apps/erp/app/routes/x+/accounting+/depreciation-runs.new.tsx
@@ -3,7 +3,10 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
-import { insertDepreciationRun } from "~/modules/accounting";
+import {
+ getBaseCurrencyDecimalPlaces,
+ insertDepreciationRun
+} from "~/modules/accounting";
import {
buildDepreciationLines,
getNextPeriodEnd
@@ -12,9 +15,10 @@ import { path } from "~/utils/path";
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- create: "accounting"
- });
+ const { client, companyId, companyGroupId, userId } =
+ await requirePermissions(request, {
+ create: "accounting"
+ });
// Find the last run (posted or draft) to determine the next period
const lastRun = await client
@@ -107,7 +111,8 @@ export async function action({ request }: ActionFunctionArgs) {
periodEnd,
lastPostedPeriodEnd,
taxEnabled,
- usageMap
+ usageMap,
+ await getBaseCurrencyDecimalPlaces(client, companyId, companyGroupId)
);
const result = await insertDepreciationRun(client, {
diff --git a/apps/erp/app/routes/x+/depreciation-run+/$depreciationRunId.repeat.tsx b/apps/erp/app/routes/x+/depreciation-run+/$depreciationRunId.repeat.tsx
index 008fba81a7..928ab69524 100644
--- a/apps/erp/app/routes/x+/depreciation-run+/$depreciationRunId.repeat.tsx
+++ b/apps/erp/app/routes/x+/depreciation-run+/$depreciationRunId.repeat.tsx
@@ -3,15 +3,19 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
-import { insertDepreciationRun } from "~/modules/accounting";
+import {
+ getBaseCurrencyDecimalPlaces,
+ insertDepreciationRun
+} from "~/modules/accounting";
import { buildDepreciationLines } from "~/modules/accounting/accounting.utils";
import { path } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- create: "accounting"
- });
+ const { client, companyId, companyGroupId, userId } =
+ await requirePermissions(request, {
+ create: "accounting"
+ });
const { depreciationRunId } = params;
if (!depreciationRunId) {
@@ -143,7 +147,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
periodEnd,
lastPostedPeriodEnd,
taxEnabled,
- usageMap
+ usageMap,
+ await getBaseCurrencyDecimalPlaces(client, companyId, companyGroupId)
);
if (lines.length === 0) {
diff --git a/apps/erp/app/routes/x+/fixed-asset+/$fixedAssetId.purchase.tsx b/apps/erp/app/routes/x+/fixed-asset+/$fixedAssetId.purchase.tsx
index a8aa6c91d6..d7c539453e 100644
--- a/apps/erp/app/routes/x+/fixed-asset+/$fixedAssetId.purchase.tsx
+++ b/apps/erp/app/routes/x+/fixed-asset+/$fixedAssetId.purchase.tsx
@@ -121,6 +121,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
supplierUnitPrice: 0,
supplierShippingCost: 0,
supplierTaxAmount: 0,
+ taxPercent: 0,
exchangeRate: 1,
purchaseUnitOfMeasureCode: "EA",
inventoryUnitOfMeasureCode: "EA",
diff --git a/apps/erp/app/routes/x+/job+/update.tsx b/apps/erp/app/routes/x+/job+/update.tsx
index ed25a77e67..c07f1bc666 100644
--- a/apps/erp/app/routes/x+/job+/update.tsx
+++ b/apps/erp/app/routes/x+/job+/update.tsx
@@ -2,6 +2,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { trigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
+import { scrapAllowance } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import {
calculateJobPriority,
@@ -87,9 +88,9 @@ export async function action({ request }: ActionFunctionArgs) {
? undefined
: (manufacturing?.data?.lotSize ?? 0),
modelUploadId: item.data?.modelUploadId ?? null,
- scrapQuantity: Math.ceil(
- (manufacturing?.data?.lotSize ?? 0) *
- (manufacturing?.data?.scrapPercentage ?? 0)
+ scrapQuantity: scrapAllowance(
+ manufacturing?.data?.lotSize ?? 0,
+ manufacturing?.data?.scrapPercentage ?? 0
),
updatedBy: userId,
updatedAt: new Date().toISOString()
diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId.items.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId.items.tsx
index b34331c48d..dd9ed2bfa2 100644
--- a/apps/erp/app/routes/x+/maintenance+/$dispatchId.items.tsx
+++ b/apps/erp/app/routes/x+/maintenance+/$dispatchId.items.tsx
@@ -5,7 +5,7 @@ import { validationError, validator } from "@carbon/form";
import { Card, CardContent, HStack, VStack } from "@carbon/react";
import type { ActionFunctionArgs } from "react-router";
import { data, useParams } from "react-router";
-import { useRouteData } from "~/hooks";
+import { useCurrencyFormatter, useRouteData } from "~/hooks";
import {
isMaintenanceDispatchLocked,
maintenanceDispatchItemValidator,
@@ -68,6 +68,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
export default function MaintenanceDispatchItemsRoute() {
const { dispatchId } = useParams();
+ const currencyFormatter = useCurrencyFormatter();
if (!dispatchId) throw new Error("dispatchId not found");
const routeData = useRouteData<{
@@ -105,13 +106,13 @@ export default function MaintenanceDispatchItemsRoute() {
<div>
<span className="text-muted-foreground">Unit Cost:</span>{" "}
{item.unitCost
- ? `$${Number(item.unitCost).toFixed(2)}`
+ ? currencyFormatter.format(Number(item.unitCost))
: "-"}
</div>
<div>
<span className="text-muted-foreground">Total Cost:</span>{" "}
{item.totalCost
- ? `$${Number(item.totalCost).toFixed(2)}`
+ ? currencyFormatter.format(Number(item.totalCost))
: "-"}
</div>
</div>
diff --git a/apps/erp/app/routes/x+/production+/planning.update.tsx b/apps/erp/app/routes/x+/production+/planning.update.tsx
index fae716748f..7895c10056 100644
--- a/apps/erp/app/routes/x+/production+/planning.update.tsx
+++ b/apps/erp/app/routes/x+/production+/planning.update.tsx
@@ -1,5 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { getLogger } from "@carbon/logger";
+import { scrapAllowance } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { z } from "zod";
@@ -224,10 +225,10 @@ export async function action({ request }: ActionFunctionArgs) {
// Calculate scrap quantity based on scrap percentage
const updateScrapPercentage =
manufacturing.data?.scrapPercentage ?? 0;
- const updateScrapQuantity =
- updateScrapPercentage > 0
- ? Math.ceil(order.quantity * updateScrapPercentage)
- : 0;
+ const updateScrapQuantity = scrapAllowance(
+ order.quantity,
+ updateScrapPercentage
+ );
const updateJob = await client
.from("job")
diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.new.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.new.tsx
index 43fa6dfede..4cac657e39 100644
--- a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.new.tsx
+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.new.tsx
@@ -108,6 +108,7 @@ export default function NewPurchaseInvoiceLineRoute() {
supplierUnitPrice: 0,
supplierShippingCost: 0,
supplierTaxAmount: 0,
+ taxPercent: 0,
exchangeRate: purchaseInvoiceData?.purchaseInvoice?.exchangeRate ?? 1
};
diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.tsx
index b8ca7d3455..92b422756e 100644
--- a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.tsx
+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.tsx
@@ -6,6 +6,7 @@ import { msg } from "@lingui/core/macro";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { Outlet, redirect, useParams } from "react-router";
import { PanelProvider, ResizablePanels } from "~/components/Layout";
+import { getCurrencyByCode } from "~/modules/accounting";
import {
getCompanyHasOpenCredits,
getPurchaseInvoice,
@@ -31,9 +32,12 @@ export const handle: Handle = {
};
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {
- view: "invoicing"
- });
+ const { client, companyId, companyGroupId } = await requirePermissions(
+ request,
+ {
+ view: "invoicing"
+ }
+ );
const { invoiceId } = params;
if (!invoiceId) throw new Error("Could not find invoiceId");
@@ -55,21 +59,33 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
- const [supplier, interaction, files, orgHasCredits] = await Promise.all([
- purchaseInvoice.data?.supplierId
- ? getSupplier(client, purchaseInvoice.data.supplierId)
- : null,
- getSupplierInteraction(client, purchaseInvoice.data.supplierInteractionId!),
- getSupplierInteractionDocuments(
- client,
- companyId,
- purchaseInvoice.data.supplierInteractionId!
- ),
- getCompanyHasOpenCredits(client, companyId, "purchase")
- ]);
+ const [supplier, interaction, files, orgHasCredits, currency] =
+ await Promise.all([
+ purchaseInvoice.data?.supplierId
+ ? getSupplier(client, purchaseInvoice.data.supplierId)
+ : null,
+ getSupplierInteraction(
+ client,
+ purchaseInvoice.data.supplierInteractionId!
+ ),
+ getSupplierInteractionDocuments(
+ client,
+ companyId,
+ purchaseInvoice.data.supplierInteractionId!
+ ),
+ getCompanyHasOpenCredits(client, companyId, "purchase"),
+ purchaseInvoice.data?.currencyCode
+ ? getCurrencyByCode(
+ client,
+ companyGroupId,
+ purchaseInvoice.data.currencyCode
+ )
+ : null
+ ]);
return {
purchaseInvoice: purchaseInvoice.data,
+ currency: currency?.data ?? null,
purchaseInvoiceLines: purchaseInvoiceLines.data ?? [],
purchaseInvoiceDelivery: purchaseInvoiceDelivery.data,
files,
diff --git a/apps/erp/app/routes/x+/purchase-invoice+/new.tsx b/apps/erp/app/routes/x+/purchase-invoice+/new.tsx
index 7a6f309da6..73cb6b1795 100644
--- a/apps/erp/app/routes/x+/purchase-invoice+/new.tsx
+++ b/apps/erp/app/routes/x+/purchase-invoice+/new.tsx
@@ -3,6 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
+import { deriveRate, taxableBase } from "@carbon/utils";
import { msg } from "@lingui/core/macro";
import type { FunctionsResponse } from "@supabase/functions-js";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
@@ -136,6 +137,20 @@ export async function action({ request }: ActionFunctionArgs) {
const lineTax = !taxApplied ? extractedTaxAmount : 0;
taxApplied = true;
+ // The whole document's tax lands on the first line, so it can exceed that
+ // one line's own subtotal. The AMOUNT is what the supplier actually
+ // charged and stays authoritative; the rate is the derived half of the
+ // pair, rounded to internal scale and held inside the 0..1 fraction the
+ // validator and TaxFields both require.
+ // No shipping term: this path hardcodes supplierShippingCost to 0 below,
+ // so the base is deliberately unit price x quantity only.
+ const lineSubtotal = taxableBase(
+ item.unitPrice || 0,
+ item.quantity || 1,
+ 0
+ );
+ const lineTaxPercent = Math.min(1, deriveRate(lineTax, lineSubtotal));
+
// Map the line up front when the extracted text directly matches an
// existing record — only lines with no direct match are left as
// comments for the review modal.
@@ -156,6 +171,7 @@ export async function action({ request }: ActionFunctionArgs) {
supplierUnitPrice: item.unitPrice || 0,
supplierShippingCost: 0,
supplierTaxAmount: lineTax,
+ taxPercent: lineTaxPercent,
locationId: d.locationId,
companyId,
createdBy: userId,
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
index 74470f8ccf..e15a87646a 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
@@ -12,7 +12,7 @@ import { renderAsync } from "@react-email/components";
import { parseAcceptLanguage } from "intl-parse-accept-language";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
-import { getPaymentTermsList } from "~/modules/accounting";
+import { getCurrencyByCode, getPaymentTermsList } from "~/modules/accounting";
import { upsertDocument } from "~/modules/documents";
import {
finalizePurchaseOrder,
@@ -45,10 +45,11 @@ export async function action(args: ActionFunctionArgs) {
const { request, params } = args;
assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- create: "purchasing",
- role: "employee"
- });
+ const { client, companyId, companyGroupId, userId } =
+ await requirePermissions(request, {
+ create: "purchasing",
+ role: "employee"
+ });
const { orderId } = params;
if (!orderId) throw new Error("Could not find orderId");
@@ -316,9 +317,19 @@ export async function action(args: ActionFunctionArgs) {
if (!paymentTerms.data) throw new Error("Failed to get payment terms");
if (!supplier.data.contact.email) break;
+ // Same decimals the PDF of this order uses.
+ const currencyRow = purchaseOrder.data.currencyCode
+ ? await getCurrencyByCode(
+ serviceRole,
+ companyGroupId,
+ purchaseOrder.data.currencyCode
+ )
+ : null;
+
const emailTemplate = PurchaseOrderEmail({
// @ts-expect-error TS2739 - TODO: fix type
company: company.data,
+ currencyDecimals: currencyRow?.data?.decimalPlaces ?? null,
locale: locales?.[0] ?? "en-US",
purchaseOrder: purchaseOrder.data,
purchaseOrderLines: purchaseOrderLines.data ?? [],
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.new.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.new.tsx
index cd6d21d3b0..46cbcc4de6 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.new.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.new.tsx
@@ -103,7 +103,8 @@ export default function NewPurchaseOrderLineRoute() {
storageUnitId: "",
supplierShippingCost: 0,
supplierTaxAmount: 0,
- supplierUnitPrice: 0
+ supplierUnitPrice: 0,
+ taxPercent: 0
};
return <PurchaseOrderLineForm initialValues={initialValues} />;
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
index 30b214ba90..89e0b685de 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
@@ -14,7 +14,7 @@ import { parseAcceptLanguage } from "intl-parse-accept-language";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { Outlet, redirect, useParams } from "react-router";
import { PanelProvider, ResizablePanels } from "~/components/Layout/Panels";
-import { getPaymentTermsList } from "~/modules/accounting";
+import { getCurrencyByCode, getPaymentTermsList } from "~/modules/accounting";
import { upsertDocument } from "~/modules/documents";
import {
getDefaultAttachmentsForPO,
@@ -62,9 +62,12 @@ export const handle: Handle = {
export async function action(args: ActionFunctionArgs) {
const { request, params } = args;
assertIsPost(request);
- const { userId, companyId } = await requirePermissions(request, {
- update: "purchasing"
- });
+ const { userId, companyId, companyGroupId } = await requirePermissions(
+ request,
+ {
+ update: "purchasing"
+ }
+ );
const { orderId } = params;
if (!orderId) throw new Error("Could not find orderId");
@@ -273,6 +276,15 @@ export async function action(args: ActionFunctionArgs) {
getUser(serviceRole, userId)
]);
+ // Same decimals the PDF of this order uses.
+ const currencyRow = purchaseOrder.data.currencyCode
+ ? await getCurrencyByCode(
+ serviceRole,
+ companyGroupId,
+ purchaseOrder.data.currencyCode
+ )
+ : null;
+
const supplierEmail = supplier?.data?.contact?.email;
if (
supplierEmail &&
@@ -284,6 +296,7 @@ export async function action(args: ActionFunctionArgs) {
const emailTemplate = PurchaseOrderEmail({
// @ts-expect-error TS2739 - TODO: fix type
company: company.data,
+ currencyDecimals: currencyRow?.data?.decimalPlaces ?? null,
locale: locales?.[0] ?? "en-US",
purchaseOrder: purchaseOrder.data,
purchaseOrderLines: purchaseOrderLines.data ?? [],
@@ -370,10 +383,11 @@ export async function action(args: ActionFunctionArgs) {
}
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client, companyId, userId } = await requirePermissions(request, {
- view: "purchasing",
- bypassRls: true
- });
+ const { client, companyId, companyGroupId, userId } =
+ await requirePermissions(request, {
+ view: "purchasing",
+ bypassRls: true
+ });
const { orderId } = params;
if (!orderId) throw new Error("Could not find orderId");
@@ -476,7 +490,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
)
);
const supplierInteractionId = purchaseOrder.data?.supplierInteractionId;
- const [defaultAttachments, adHocDocs] = await Promise.all([
+ const [defaultAttachments, adHocDocs, currency] = await Promise.all([
getDefaultAttachmentsForPO(serviceRole, {
companyId,
supplierId: purchaseOrder.data?.supplierId ?? null,
@@ -488,7 +502,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
companyId,
supplierInteractionId
)
- : Promise.resolve([])
+ : Promise.resolve([]),
+ purchaseOrder.data?.currencyCode
+ ? getCurrencyByCode(
+ serviceRole,
+ companyGroupId,
+ purchaseOrder.data.currencyCode
+ )
+ : null
]);
const adHocAttachments = adHocDocs.map((d) => ({
source: "po" as const,
@@ -504,6 +525,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return {
purchaseOrder: purchaseOrder.data,
purchaseOrderDelivery: purchaseOrderDelivery.data,
+ currency: currency?.data ?? null,
lines: lines.data ?? [],
files: getSupplierInteractionDocuments(
client,
diff --git a/apps/erp/app/routes/x+/purchasing+/_index.tsx b/apps/erp/app/routes/x+/purchasing+/_index.tsx
index d80c1aaf4d..ec525b5e7f 100644
--- a/apps/erp/app/routes/x+/purchasing+/_index.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/_index.tsx
@@ -265,9 +265,8 @@ export default function PurchaseDashboard() {
const currencyCompactFormatter = useCurrencyFormatter({
currency: company.baseCurrencyCode,
- maximumFractionDigits: 0,
- notation: "compact",
- compactDisplay: "short"
+ compact: true,
+ wholeUnits: true
});
const currencyFormatter = useCurrencyFormatter();
const numberFormatter = useNumberFormatter({
diff --git a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx b/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
index e74993f2a4..fa1556c38e 100644
--- a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
@@ -1,5 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { getLogger } from "@carbon/logger";
+import { applyRate, SCALE, taxableBase } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { z } from "zod";
@@ -156,22 +157,27 @@ export async function action({ request }: ActionFunctionArgs) {
}
}
- const [suppliers, supplierParts, periods, company] = await Promise.all([
- client
- .from("supplier")
- .select("id, name, taxPercent, currencyCode")
- .in("id", Array.from(supplierIds)),
- client
- .from("supplierPart")
- .select("*")
- .in("itemId", Array.from(itemIds)),
- client.from("period").select("*").in("id", Array.from(periodIds)),
- client
- .from("company")
- .select("id, baseCurrencyCode")
- .eq("id", companyId)
- .single()
- ]);
+ const [suppliers, supplierParts, periods, company, currencies] =
+ await Promise.all([
+ client
+ .from("supplier")
+ .select("id, name, taxPercent, currencyCode")
+ .in("id", Array.from(supplierIds)),
+ client
+ .from("supplierPart")
+ .select("*")
+ .in("itemId", Array.from(itemIds)),
+ client.from("period").select("*").in("id", Array.from(periodIds)),
+ client
+ .from("company")
+ .select("id, baseCurrencyCode")
+ .eq("id", companyId)
+ .single(),
+ client
+ .from("currencies")
+ .select("code, decimalPlaces")
+ .eq("companyGroupId", companyGroupId)
+ ]);
if (suppliers.error) {
logger.error("Failed to fetch suppliers", { error: suppliers.error });
@@ -226,6 +232,12 @@ export async function action({ request }: ActionFunctionArgs) {
const baseCurrencyCode = company.data?.baseCurrencyCode ?? "USD";
+ // Settlement amounts round at the currency's own decimals, so the
+ // planned order carries a real money value rather than a raw product.
+ const currencyDecimals = new Map(
+ currencies.data?.map((c) => [c.code, c.decimalPlaces]) ?? []
+ );
+
let processedItems = 0;
// ── UPDATE existing draft/planned lines ──
@@ -387,10 +399,21 @@ export async function action({ request }: ActionFunctionArgs) {
inventoryUnitOfMeasureCode: order.unitOfMeasureCode,
conversionFactor: supplierPart?.conversionFactor ?? 1,
supplierUnitPrice: supplierPart?.unitPrice ?? 0,
- supplierTaxAmount:
- ((supplierPart?.unitPrice ?? 0) *
- (supplier.taxPercent ?? 0)) /
- 100,
+ // supplier.taxPercent is a 0..1 fraction; the amount follows
+ // the canonical denominator. Shipping is hardcoded 0 on this
+ // path, so it is passed explicitly rather than omitted.
+ taxPercent: supplier.taxPercent ?? 0,
+ supplierTaxAmount: applyRate(
+ taxableBase(
+ supplierPart?.unitPrice ?? 0,
+ adjustedQuantity,
+ 0
+ ),
+ supplier.taxPercent ?? 0,
+ currencyDecimals.get(
+ supplier.currencyCode ?? baseCurrencyCode
+ ) ?? SCALE
+ ),
supplierShippingCost: 0,
requiredDate: order.dueDate ?? undefined,
locationId,
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.convert.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.convert.tsx
index 920caf12fd..9bedde865b 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.convert.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.convert.tsx
@@ -27,9 +27,12 @@ const logger = getLogger("erp", "quoteid-convert");
export async function action(args: ActionFunctionArgs) {
const { request, params } = args;
assertIsPost(request);
- const { companyId, userId } = await requirePermissions(request, {
- create: "sales"
- });
+ const { companyId, companyGroupId, userId } = await requirePermissions(
+ request,
+ {
+ create: "sales"
+ }
+ );
const { quoteId } = params;
if (!quoteId) throw new Error("Could not find quoteId");
@@ -115,6 +118,7 @@ export async function action(args: ActionFunctionArgs) {
await sendSalesOrderEmail({
salesOrderId,
companyId,
+ companyGroupId,
userId,
customerContactId: customerContact,
cc,
diff --git a/apps/erp/app/routes/x+/sales+/_index.tsx b/apps/erp/app/routes/x+/sales+/_index.tsx
index f21569a7bd..0ed89f7a6f 100644
--- a/apps/erp/app/routes/x+/sales+/_index.tsx
+++ b/apps/erp/app/routes/x+/sales+/_index.tsx
@@ -206,10 +206,7 @@ export default function SalesDashboard() {
day: "numeric"
});
- const currencyCompactFormatter = useCurrencyFormatter({
- notation: "compact",
- compactDisplay: "short"
- });
+ const currencyCompactFormatter = useCurrencyFormatter({ compact: true });
const currencyFormatter = useCurrencyFormatter();
const numberFormatter = useNumberFormatter({
maximumFractionDigits: 0,
diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx
index c773a1601f..f849108510 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx
@@ -8,7 +8,7 @@ import { raiseMoment } from "@carbon/lib/workflows";
import { renderAsync } from "@react-email/components";
import { parseAcceptLanguage } from "intl-parse-accept-language";
import type { ActionFunctionArgs } from "react-router";
-import { getPaymentTermsList } from "~/modules/accounting";
+import { getCurrencyByCode, getPaymentTermsList } from "~/modules/accounting";
import { upsertDocument } from "~/modules/documents";
import {
getSalesInvoice,
@@ -26,10 +26,11 @@ export async function action(args: ActionFunctionArgs) {
const { request, params } = args;
assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- create: "invoicing",
- role: "employee"
- });
+ const { client, companyId, companyGroupId, userId } =
+ await requirePermissions(request, {
+ create: "invoicing",
+ role: "employee"
+ });
const { invoiceId } = params;
if (!invoiceId) {
@@ -276,9 +277,19 @@ export async function action(args: ActionFunctionArgs) {
};
}
+ // Same decimals the PDF of this invoice uses.
+ const currencyRow = salesInvoice.data.currencyCode
+ ? await getCurrencyByCode(
+ serviceRole,
+ companyGroupId,
+ salesInvoice.data.currencyCode
+ )
+ : null;
+
const emailTemplate = SalesInvoiceEmail({
// @ts-expect-error TS2739 - TODO: fix type
company: company.data,
+ currencyDecimals: currencyRow?.data?.decimalPlaces ?? null,
locale: locales?.[0] ?? "en-US",
salesInvoice: salesInvoice.data,
salesInvoiceLines: salesInvoiceLines.data ?? [],
diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.tsx
index 10f6d98b16..261b380968 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.tsx
@@ -7,6 +7,7 @@ import { msg } from "@lingui/core/macro";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { Outlet, redirect, useParams } from "react-router";
import { PanelProvider, ResizablePanels } from "~/components/Layout";
+import { getCurrencyByCode } from "~/modules/accounting";
import {
getCompanyHasOpenCredits,
getSalesInvoice,
@@ -33,9 +34,12 @@ export const handle: Handle = {
};
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {
- view: "invoicing"
- });
+ const { client, companyId, companyGroupId } = await requirePermissions(
+ request,
+ {
+ view: "invoicing"
+ }
+ );
const { invoiceId } = params;
if (!invoiceId) throw new Error("Could not find invoiceId");
@@ -58,7 +62,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
const serviceRole = getCarbonServiceRole();
- const [customer, opportunity, companySettings, orgHasCredits] =
+ const [customer, opportunity, companySettings, orgHasCredits, currency] =
await Promise.all([
salesInvoice.data?.customerId
? getCustomer(client, salesInvoice.data.customerId)
@@ -67,7 +71,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
? getOpportunity(client, salesInvoice.data.opportunityId)
: null,
getCompanySettings(serviceRole, companyId),
- getCompanyHasOpenCredits(client, companyId, "sales")
+ getCompanyHasOpenCredits(client, companyId, "sales"),
+ salesInvoice.data?.currencyCode
+ ? getCurrencyByCode(
+ serviceRole,
+ companyGroupId,
+ salesInvoice.data.currencyCode
+ )
+ : null
]);
const defaultCc = customer?.data?.defaultCc?.length
@@ -76,6 +87,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return {
salesInvoice: salesInvoice.data,
+ currency: currency?.data ?? null,
salesInvoiceLines: salesInvoiceLines.data ?? [],
salesInvoiceShipment: salesInvoiceShipment.data,
files: getOpportunityDocuments(
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx
index 817ce9d86b..455f758731 100644
--- a/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx
@@ -24,10 +24,11 @@ export async function action(args: ActionFunctionArgs) {
try {
assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- create: "sales",
- role: "employee"
- });
+ const { client, companyId, companyGroupId, userId } =
+ await requirePermissions(request, {
+ create: "sales",
+ role: "employee"
+ });
const { orderId } = params;
if (!orderId) {
@@ -109,6 +110,7 @@ export async function action(args: ActionFunctionArgs) {
const emailResult = await sendSalesOrderEmail({
salesOrderId: orderId,
companyId,
+ companyGroupId,
userId,
customerContactId: customerContact,
cc: ccSelections,
diff --git a/apps/erp/app/routes/x+/settings+/accounting.tsx b/apps/erp/app/routes/x+/settings+/accounting.tsx
index 29a428c324..e061d5c1cc 100644
--- a/apps/erp/app/routes/x+/settings+/accounting.tsx
+++ b/apps/erp/app/routes/x+/settings+/accounting.tsx
@@ -36,7 +36,8 @@ import { getDefaultAccounts } from "~/modules/accounting";
import {
getCompanySettings,
updateAccountingEnabledSetting,
- updateAssetTaxDepreciationSettings
+ updateAssetTaxDepreciationSettings,
+ updateShowCurrencyTrailingZerosSetting
} from "~/modules/settings";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -101,6 +102,17 @@ export async function action({ request }: ActionFunctionArgs) {
return { success: true, message: "Accounting settings updated" };
}
+ if (intent === "showCurrencyTrailingZeros") {
+ const enabled = formData.get("enabled") === "true";
+ const update = await updateShowCurrencyTrailingZerosSetting(
+ client,
+ companyId,
+ enabled
+ );
+ if (update.error) return { success: false, message: update.error.message };
+ return { success: true, message: "Currency display updated" };
+ }
+
if (intent === "assetTaxDepreciationEnabled") {
const enabled = formData.get("enabled") === "true";
const update = await updateAssetTaxDepreciationSettings(client, companyId, {
@@ -159,8 +171,7 @@ export default function AccountingSettingsRoute() {
const taxFetcher = useFetcher<typeof action>();
const { isInternal } = useFlags();
- const taxEnabled =
- (companySettings as any).assetTaxDepreciationEnabled ?? false;
+ const taxEnabled = companySettings.assetTaxDepreciationEnabled ?? false;
useEffect(() => {
if (fetcher.data && "success" in fetcher.data) {
@@ -194,6 +205,19 @@ export default function AccountingSettingsRoute() {
[fetcher]
);
+ const handleTrailingZerosToggle = useCallback(
+ (showTrailingZeros: boolean) => {
+ fetcher.submit(
+ {
+ intent: "showCurrencyTrailingZeros",
+ enabled: String(showTrailingZeros)
+ },
+ { method: "POST" }
+ );
+ },
+ [fetcher]
+ );
+
const handleTaxDepreciationToggle = useCallback(
(checked: boolean) => {
fetcher.submit(
@@ -235,7 +259,7 @@ export default function AccountingSettingsRoute() {
<VStack className="items-start" spacing={1}>
<HStack className="items-center gap-2">
<span className="font-medium">
- {(companySettings as any).accountingEnabled ? (
+ {companySettings.accountingEnabled ? (
<Trans>Accounting is enabled</Trans>
) : (
<Trans>Accounting is disabled</Trans>
@@ -246,7 +270,7 @@ export default function AccountingSettingsRoute() {
</Badge>
</HStack>
<span className="text-sm text-muted-foreground">
- {(companySettings as any).accountingEnabled ? (
+ {companySettings.accountingEnabled ? (
<Trans>
Transactions will create journal entries and update the
general ledger.
@@ -260,7 +284,7 @@ export default function AccountingSettingsRoute() {
</span>
</VStack>
<Switch
- checked={(companySettings as any).accountingEnabled ?? false}
+ checked={companySettings.accountingEnabled ?? false}
onCheckedChange={handleAccountingToggle}
disabled={!isInternal}
/>
@@ -268,6 +292,35 @@ export default function AccountingSettingsRoute() {
</CardContent>
</Card>
+ <SettingsSectionHeader>
+ <Trans>Currency</Trans>
+ </SettingsSectionHeader>
+
+ <Card>
+ <CardHeader>
+ <HStack className="justify-between items-center">
+ <div>
+ <CardTitle>
+ <Trans>Show Trailing Zeros</Trans>
+ </CardTitle>
+ <CardDescription>
+ <Trans>
+ Pad amounts to their currency's decimal places, so 300
+ appears as 300.00 and columns of figures stay aligned. Turn
+ this off to show only the digits that carry value. Printed
+ documents and stored amounts are unaffected either way.
+ </Trans>
+ </CardDescription>
+ </div>
+ <Switch
+ checked={companySettings.showCurrencyTrailingZeros}
+ onCheckedChange={handleTrailingZerosToggle}
+ disabled={fetcher.state !== "idle"}
+ />
+ </HStack>
+ </CardHeader>
+ </Card>
+
<SettingsSectionHeader>
<Trans>Assets</Trans>
</SettingsSectionHeader>
@@ -279,9 +332,9 @@ export default function AccountingSettingsRoute() {
fetcher={taxFetcher}
defaultValues={{
intent: "assetTaxDepreciation",
- assetTaxRate: parseFloat(
- (companySettings as any).assetTaxRate ?? "0"
- ),
+ // Already a NUMERIC column; the parseFloat this replaced only
+ // worked because JS coerced the number back to a string first.
+ assetTaxRate: companySettings.assetTaxRate ?? 0,
deferredTaxLiabilityAccountId:
(accountDefaults as any)?.deferredTaxLiabilityAccountId ?? "",
deferredTaxExpenseAccountId:
diff --git a/apps/erp/app/routes/x+/settings+/sales.tsx b/apps/erp/app/routes/x+/settings+/sales.tsx
index 845ddc29b6..e999d2e172 100644
--- a/apps/erp/app/routes/x+/settings+/sales.tsx
+++ b/apps/erp/app/routes/x+/settings+/sales.tsx
@@ -26,6 +26,7 @@ import {
toast,
VStack
} from "@carbon/react";
+import { INPUT_FORMAT } from "@carbon/utils";
import { msg } from "@lingui/core/macro";
import { Trans, useLingui } from "@lingui/react/macro";
import { useCallback, useEffect, useState } from "react";
@@ -714,11 +715,7 @@ function CategoryMarkupsCard({
<Number
name={key}
label=""
- formatOptions={{
- style: "percent",
- minimumFractionDigits: 0,
- maximumFractionDigits: 2
- }}
+ formatOptions={INPUT_FORMAT.rate}
minValue={0}
/>
</div>
diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.tsx
index 10272a2252..b1a5a339da 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/$id.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.tsx
@@ -103,6 +103,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return {
quote: quote.data,
+ presentationCurrency: presentationCurrency.data ?? null,
lines: lines.data ?? [],
prices: prices.data ?? [],
files: getSupplierInteractionDocuments(
diff --git a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
index 62e7381888..1439e52451 100644
--- a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
+++ b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
@@ -37,7 +37,7 @@ import {
TabsTrigger,
toast
} from "@carbon/react";
-import { formatDate, getItemReadableId } from "@carbon/utils";
+import { formatDate, getItemReadableId, SCALE_FORMAT } from "@carbon/utils";
import { getLocalTimeZone, parseDate, today } from "@internationalized/date";
import { useLingui } from "@lingui/react/macro";
import { useNumberFormatter } from "@react-aria/i18n";
@@ -130,7 +130,7 @@ export function IssueMaterialModal({
const { carbon } = useCarbon();
const { t } = useLingui();
const [items] = useItems();
- const numberFormatter = useNumberFormatter({ maximumFractionDigits: 4 });
+ const numberFormatter = useNumberFormatter(SCALE_FORMAT);
// Item selection state
const [selectedItemId, setSelectedItemId] = useState<string>(
diff --git a/apps/mes/app/routes/display+/$workCenterId.maintenance.tsx b/apps/mes/app/routes/display+/$workCenterId.maintenance.tsx
index e0986e53fe..a144ccc074 100644
--- a/apps/mes/app/routes/display+/$workCenterId.maintenance.tsx
+++ b/apps/mes/app/routes/display+/$workCenterId.maintenance.tsx
@@ -2,6 +2,7 @@ import { notFound } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { Trans, useLingui } from "@lingui/react/macro";
+import { useLocale } from "@react-aria/i18n";
import type { LoaderFunctionArgs } from "react-router";
import { useLoaderData } from "react-router";
import {
@@ -70,6 +71,7 @@ export async function loader({ params, request }: LoaderFunctionArgs) {
export default function MaintenanceDisplayRoute() {
const { t } = useLingui();
+ const { locale } = useLocale();
const {
workCenter,
dispatches,
@@ -156,7 +158,11 @@ export default function MaintenanceDisplayRoute() {
days
</Trans>
}
- answer={formatCurrency(board.unplannedCost.total, currencyCode)}
+ answer={formatCurrency(
+ board.unplannedCost.total,
+ currencyCode,
+ locale
+ )}
tone={board.unplannedCost.total > 0 ? "warn" : "neutral"}
/>
<ScoreboardRow
@@ -170,8 +176,8 @@ export default function MaintenanceDisplayRoute() {
);
}
-function formatCurrency(value: number, currency: string) {
- return new Intl.NumberFormat(undefined, {
+function formatCurrency(value: number, currency: string, locale: string) {
+ return new Intl.NumberFormat(locale, {
style: "currency",
currency,
maximumFractionDigits: 0
diff --git a/packages/checks/AGENTS.md b/packages/checks/AGENTS.md
index a635b8f9f9..179e829d08 100644
--- a/packages/checks/AGENTS.md
+++ b/packages/checks/AGENTS.md
@@ -6,7 +6,7 @@ Conformance checking, clobber detection, invariant queries, and module structure
- **Run checks against real migrations and module directories** — `collectFindings(root)` scans both SQL migrations and app module structure
- **Use `newViolations()` for CI** — filters findings against the baseline so only new violations fail the build
-- **Add new conformance rules to `CONFORMANCE_CHECKS` or `STRUCTURE_CHECKS` arrays** — follow the `ConformanceCheck` / `StructureCheck` interface
+- **Add new conformance rules to the array that matches the rule's SOURCE** — `CONFORMANCE_CHECKS` (SQL migrations), `SERVER_CHECKS` (server-only TS), `TS_CHECKS` (all app + shared-package TS, client and server), or `STRUCTURE_CHECKS` (module layout). Follow the `ConformanceCheck` / `StructureCheck` interface
- **Write invariants as `.sql` files** — each returns rows that VIOLATE the rule (empty = healthy); loaded from directory by `loadInvariants(dir)`
## Ask First
@@ -31,7 +31,8 @@ pnpm --filter @carbon/checks baseline # regenerate baseline (careful!)
## Key Patterns
-- **Conformance checks**: `noNumericPrecision`, `noLegacyRls` — scan SQL migrations for anti-patterns; `noLocalTimezone` (in `SERVER_CHECKS`) scans server TS (`sources/server-files.ts`) for `getLocalTimeZone()`, UTC day-slicing, local date-parts of now (`new Date().getDay()` etc.), and `setHours(0,0,0,0)` midnights. Scanned files: MES services, `packages/jobs`, edge functions, ERP module `.service.ts`/`.server.ts`, **plus both apps' route trees** — route modules are server AND client in one file, so `maskClientCode` blanks the browser half (default export, `clientLoader`/`clientAction`, PascalCase/`use*` declarations) while keeping loaders, actions, and the module-level helpers they call
+- **Conformance checks**: `noNumericPrecision`, `noLegacyRls`, `noDerivedPercentColumn` — scan SQL migrations for anti-patterns (`noDerivedPercentColumn` flags a `*Percent`/`*Rate` column `GENERATED ALWAYS AS` an expression that divides — a percentage is an entered fact, never a lossy echo of a rounded amount); `noLocalTimezone` (in `SERVER_CHECKS`) scans server TS (`sources/server-files.ts`) for `getLocalTimeZone()`, UTC day-slicing, local date-parts of now (`new Date().getDay()` etc.), and `setHours(0,0,0,0)` midnights. Scanned files: MES services, `packages/jobs`, edge functions, ERP module `.service.ts`/`.server.ts`, **plus both apps' route trees** — route modules are server AND client in one file, so `maskClientCode` blanks the browser half (default export, `clientLoader`/`clientAction`, PascalCase/`use*` declarations) while keeping loaders, actions, and the module-level helpers they call
+- **Numeric-precision checks** (in `TS_CHECKS`, over `sources/typescript.ts`): `noRawRounding` flags `Math.round/ceil/floor` and `.toFixed` on value-bearing numbers (use `round`/`scrapAllowance`/`applyRate`/`deriveRate` from `@carbon/utils`); `noInlineFractionDigits` flags `minimum`/`maximumFractionDigits` at a call site (pick a named kind from `@carbon/utils` `format.ts`, and `INPUT_FORMAT.*` for anything editable). `sources/typescript.ts` walks `apps/erp/app/{components,hooks,modules,routes}`, `apps/mes/app`, `packages/database/supabase/functions`, `packages/{ee,jobs}/src`, `packages/documents/src/{pdf,utils}` and the shared packages `packages/{utils,form,react,printing,workflows}/src` — tests and the image/logo resizers excluded. The shared packages matter: `@carbon/utils` is where the standard's own helpers live, and `form`/`react` own the number inputs whose `formatOptions` are part of the storage round-trip. See `.claude/rules/numeric-precision.md`
- **Structure checks**: `moduleShape` — validates ERP modules have `types.ts`, `ui/`, `index.ts`, `<name>.service.ts`, `<name>.models.ts`
- **Clobber detection**: `findClobbers(branch, main)` — identifies DB objects redefined on both sides
- **Baseline**: `src/baseline.ts` — grandfathered violations keyed by `checkId + file + line + snippet`
diff --git a/packages/checks/src/check.ts b/packages/checks/src/check.ts
index 0739b1320c..91d3fb2522 100644
--- a/packages/checks/src/check.ts
+++ b/packages/checks/src/check.ts
@@ -1,3 +1,6 @@
+/** A source file handed to a check: any text file, SQL or TypeScript. */
+export type SourceFile = { file: string; contents: string };
+
/** One occurrence of a forbidden pattern. */
export type Violation = {
/** Migration file basename, e.g. "20260101120000_foo.sql", or "<inline>" in unit tests. */
diff --git a/packages/checks/src/clobber.ts b/packages/checks/src/clobber.ts
index 6d14284b3b..3f3fd2d884 100644
--- a/packages/checks/src/clobber.ts
+++ b/packages/checks/src/clobber.ts
@@ -1,6 +1,4 @@
-import type { Violation } from "./check";
-
-export type SourceFile = { file: string; contents: string };
+import type { SourceFile, Violation } from "./check";
/** Patterns that identify a FULL redefinition of a DB object. Add a row to grow coverage. */
const OBJECT_PATTERNS: { kind: string; re: RegExp }[] = [
diff --git a/packages/checks/src/conformance/baseline.json b/packages/checks/src/conformance/baseline.json
index 39d82abca0..230f232fbe 100644
--- a/packages/checks/src/conformance/baseline.json
+++ b/packages/checks/src/conformance/baseline.json
@@ -3,6 +3,83 @@
"module-shape::shared::extra-models:imports.models.ts",
"module-shape::shared::missing:ui",
"module-shape::storage-rules::missing:types.ts",
+ "no-derived-percent-column::20241210214820_purchasing-redux.sql::ALTER TABLE \"purchaseInvoiceLine\" ADD COLUMN \"taxPercent\" NUMERIC(10,5) GENERATED ALWAYS AS (",
+ "no-derived-percent-column::20241210214820_purchasing-redux.sql::ALTER TABLE \"purchaseOrderLine\" ADD COLUMN IF NOT EXISTS \"taxPercent\" NUMERIC(10,5) GENERATED ALWAYS AS (",
+ "no-derived-percent-column::20241210214820_purchasing-redux.sql::ALTER TABLE \"supplierQuoteLinePrice\" ADD COLUMN \"taxPercent\" NUMERIC(10,5) GENERATED ALWAYS AS (",
+ "no-derived-percent-column::20250109000722_increase-numeric-values.sql::ALTER TABLE \"purchaseInvoiceLine\" ADD COLUMN IF NOT EXISTS \"taxPercent\" NUMERIC(10,5) GENERATED ALWAYS AS (",
+ "no-derived-percent-column::20250109000722_increase-numeric-values.sql::ALTER TABLE \"purchaseOrderLine\" ADD COLUMN IF NOT EXISTS \"taxPercent\" NUMERIC(10,5) GENERATED ALWAYS AS (",
+ "no-derived-percent-column::20250109000722_increase-numeric-values.sql::ALTER TABLE \"supplierQuoteLinePrice\" ADD COLUMN \"taxPercent\" NUMERIC(10,5) GENERATED ALWAYS AS (",
+ "no-derived-percent-column::20250109034107_increase-numeric-values-2.sql::ALTER TABLE \"purchaseInvoiceLine\" ADD COLUMN IF NOT EXISTS \"taxPercent\" NUMERIC(10,5) GENERATED ALWAYS AS (",
+ "no-derived-percent-column::20250109034107_increase-numeric-values-2.sql::ALTER TABLE \"purchaseOrderLine\" ADD COLUMN IF NOT EXISTS \"taxPercent\" NUMERIC(10,5) GENERATED ALWAYS AS (",
+ "no-derived-percent-column::20250109034107_increase-numeric-values-2.sql::ALTER TABLE \"supplierQuoteLinePrice\" ADD COLUMN \"taxPercent\" NUMERIC(10,5) GENERATED ALWAYS AS (",
+ "no-derived-percent-column::20250128195311_fix-purchasing-tax-percent.sql::ALTER TABLE \"purchaseInvoiceLine\" ADD COLUMN \"taxPercent\" NUMERIC(10,5) GENERATED ALWAYS AS (",
+ "no-derived-percent-column::20250128195311_fix-purchasing-tax-percent.sql::ALTER TABLE \"purchaseOrderLine\" ADD COLUMN \"taxPercent\" NUMERIC(10,5) GENERATED ALWAYS AS (",
+ "no-derived-percent-column::20250128195311_fix-purchasing-tax-percent.sql::ALTER TABLE \"supplierQuoteLinePrice\" ADD COLUMN \"taxPercent\" NUMERIC(10,5) GENERATED ALWAYS AS (",
+ "no-derived-percent-column::20250204164256_numeric-increase-2.sql::ALTER TABLE \"purchaseInvoiceLine\" ADD COLUMN \"taxPercent\" NUMERIC GENERATED ALWAYS AS (",
+ "no-derived-percent-column::20250204164256_numeric-increase-2.sql::ALTER TABLE \"purchaseInvoiceLine\" ADD COLUMN IF NOT EXISTS \"taxPercent\" NUMERIC GENERATED ALWAYS AS (",
+ "no-derived-percent-column::20250204164256_numeric-increase-2.sql::ALTER TABLE \"purchaseOrderLine\" ADD COLUMN \"taxPercent\" NUMERIC GENERATED ALWAYS AS (",
+ "no-derived-percent-column::20250204164256_numeric-increase-2.sql::ALTER TABLE \"purchaseOrderLine\" ADD COLUMN IF NOT EXISTS \"taxPercent\" NUMERIC GENERATED ALWAYS AS (",
+ "no-derived-percent-column::20250204164256_numeric-increase-2.sql::ALTER TABLE \"supplierQuoteLinePrice\" ADD COLUMN \"taxPercent\" NUMERIC GENERATED ALWAYS AS (",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTree.tsx::maximumFractionDigits: 2",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTree.tsx::minimumFractionDigits: 2,",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyBalanceMatrix.tsx::maximumFractionDigits: 0",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyBalanceMatrix.tsx::minimumFractionDigits: 0,",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/AccountLedgerDrawer.tsx::maximumFractionDigits: 2",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/AccountLedgerDrawer.tsx::minimumFractionDigits: 2,",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/ExecutivePnlSummary.tsx::maximumFractionDigits: 1",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/ExecutivePnlSummary.tsx::maximumFractionDigits: 2",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/ExecutivePnlSummary.tsx::minimumFractionDigits: 1,",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/ExecutivePnlSummary.tsx::minimumFractionDigits: 2,",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/MultiPeriodStatementTree.tsx::maximumFractionDigits: 2",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/MultiPeriodStatementTree.tsx::minimumFractionDigits: 2,",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/PivotLinesDrawer.tsx::maximumFractionDigits: 2",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/PivotLinesDrawer.tsx::minimumFractionDigits: 2,",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/PivotLinesDrawer.tsx::return value.toLocaleString(undefined, { maximumFractionDigits: 2 });",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/PivotTree.tsx::maximumFractionDigits: 1",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/PivotTree.tsx::maximumFractionDigits: 2",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/PivotTree.tsx::minimumFractionDigits: 1,",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/PivotTree.tsx::minimumFractionDigits: 2,",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/PivotTree.tsx::return value.toLocaleString(undefined, { maximumFractionDigits: 0 });",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/PivotTree.tsx::return value.toLocaleString(undefined, { maximumFractionDigits: 2 });",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/PurchaseLinesDrawer.tsx::maximumFractionDigits: 2",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/PurchaseLinesDrawer.tsx::minimumFractionDigits: 2,",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/PurchaseLinesDrawer.tsx::return value.toLocaleString(undefined, { maximumFractionDigits: 2 });",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/TrialBalanceTable.tsx::maximumFractionDigits: 2",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/TrialBalanceTable.tsx::minimumFractionDigits: 2,",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/TrialBalanceTree.tsx::maximumFractionDigits: 2",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/TrialBalanceTree.tsx::minimumFractionDigits: 1,",
+ "no-inline-fraction-digits::apps/erp/app/modules/accounting/ui/Reports/TrialBalanceTree.tsx::minimumFractionDigits: 2,",
+ "no-inline-fraction-digits::apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx::maximumFractionDigits: 10",
+ "no-inline-fraction-digits::apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx::minimumFractionDigits: 0,",
+ "no-inline-fraction-digits::apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx::maximumFractionDigits: 10",
+ "no-inline-fraction-digits::apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx::minimumFractionDigits: 0,",
+ "no-inline-fraction-digits::apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx::maximumFractionDigits: 10",
+ "no-inline-fraction-digits::apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx::minimumFractionDigits: 0,",
+ "no-inline-fraction-digits::apps/erp/app/modules/production/ui/Procedures/ProcedureExplorer.tsx::maximumFractionDigits: 10",
+ "no-inline-fraction-digits::apps/erp/app/modules/production/ui/Procedures/ProcedureExplorer.tsx::minimumFractionDigits: 0,",
+ "no-inline-fraction-digits::apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordForm.tsx::maximumFractionDigits: 2,",
+ "no-inline-fraction-digits::apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordsTable.tsx::maximumFractionDigits: 2,",
+ "no-inline-fraction-digits::apps/erp/app/modules/quality/ui/Documents/QualityDocumentExplorer.tsx::maximumFractionDigits: 10",
+ "no-inline-fraction-digits::apps/erp/app/modules/quality/ui/Documents/QualityDocumentExplorer.tsx::minimumFractionDigits: 0,",
+ "no-inline-fraction-digits::apps/erp/app/modules/quality/ui/Inspections/InspectionMeasurementGrid.tsx::{ formatOptions: { maximumFractionDigits: 6 } },",
+ "no-inline-fraction-digits::apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx::maximumFractionDigits: 10",
+ "no-inline-fraction-digits::apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx::minimumFractionDigits: 0,",
+ "no-inline-fraction-digits::apps/erp/app/modules/settings/ui/Webhooks/WebhooksTable.tsx::maximumFractionDigits: 0,",
+ "no-inline-fraction-digits::apps/erp/app/routes/onboarding+/plan.tsx::maximumFractionDigits: 0",
+ "no-inline-fraction-digits::apps/erp/app/routes/onboarding+/plan.tsx::minimumFractionDigits: 0,",
+ "no-inline-fraction-digits::apps/erp/app/routes/onboarding+/plan.tsx::style: \"currency\",",
+ "no-inline-fraction-digits::apps/erp/app/routes/share+/supplier-quote.$id.tsx::style: \"currency\",",
+ "no-inline-fraction-digits::apps/erp/app/routes/x+/purchasing+/_index.tsx::maximumFractionDigits: 0,",
+ "no-inline-fraction-digits::apps/erp/app/routes/x+/resources+/_index.tsx::maximumFractionDigits: 0,",
+ "no-inline-fraction-digits::apps/erp/app/routes/x+/sales+/_index.tsx::maximumFractionDigits: 0,",
+ "no-inline-fraction-digits::apps/mes/app/components/JobOperation/components/QuantityModal.tsx::maximumFractionDigits: 2",
+ "no-inline-fraction-digits::apps/mes/app/components/JobOperation/components/QuantityModal.tsx::minimumFractionDigits: 0,",
+ "no-inline-fraction-digits::apps/mes/app/routes/display+/$workCenterId.maintenance.tsx::maximumFractionDigits: 0",
+ "no-inline-fraction-digits::apps/mes/app/routes/display+/$workCenterId.maintenance.tsx::style: \"currency\",",
+ "no-inline-fraction-digits::packages/documents/src/pdf/blocks/quote/LineItemsBlock.tsx::maximumFractionDigits: line.unitPricePrecision ?? 2",
+ "no-inline-fraction-digits::packages/documents/src/pdf/blocks/quote/LineItemsBlock.tsx::minimumFractionDigits: line.unitPricePrecision ?? 2,",
+ "no-inline-fraction-digits::packages/jobs/src/inngest/functions/notifications/content.ts::return amount.toLocaleString(\"en-US\", { minimumFractionDigits: 2 });",
+ "no-inline-fraction-digits::packages/jobs/src/inngest/functions/notifications/content.ts::style: \"currency\"",
"no-legacy-rls::20230123004206_claims.sql::has_company_permission(",
"no-legacy-rls::20230123004317_companies-rls.sql::has_company_permission(",
"no-legacy-rls::20230123004339_employee-types.sql::has_company_permission(",
@@ -203,5 +280,231 @@
"no-numeric-precision::20260601143527_picking-lists.sql::NUMERIC(12,4)",
"no-numeric-precision::20260604120000_invoice-totals-computed-in-views.sql::NUMERIC(10,2)",
"no-numeric-precision::20260604120000_invoice-totals-computed-in-views.sql::numeric(10,2)",
- "no-numeric-precision::20260618171234_material-supersession.sql::NUMERIC(10,2)"
+ "no-numeric-precision::20260618171234_material-supersession.sql::NUMERIC(10,2)",
+ "no-raw-rounding::apps/erp/app/components/CadModel.tsx::Math.round(artifacts.optimizedSize / 1024)",
+ "no-raw-rounding::apps/erp/app/components/CadModel.tsx::{convertKbToString(Math.ceil(file.size / 1024))}",
+ "no-raw-rounding::apps/erp/app/components/CadModel.tsx::{convertKbToString(Math.round(artifacts.size / 1024))}",
+ "no-raw-rounding::apps/erp/app/components/DefaultAttachmentsPanel.tsx::? Math.round(f.metadata.size / 1024)",
+ "no-raw-rounding::apps/erp/app/components/DocumentTemplateEditor/BlockConfig.tsx::value={Math.round((block.opacity ?? 0.07) * 100)}",
+ "no-raw-rounding::apps/erp/app/components/Documents.tsx::Math.floor((file.metadata?.size ?? 0) / 1024)",
+ "no-raw-rounding::apps/erp/app/components/Documents.tsx::Math.floor((modelUpload.modelSize ?? 0) / 1024)",
+ "no-raw-rounding::apps/erp/app/components/Documents.tsx::formData.append(\"size\", Math.round(file.size / 1024).toString());",
+ "no-raw-rounding::apps/erp/app/components/ModelUploadProgress.tsx::if (n >= 1024 ** 2) return `${(n / 1024 ** 2).toFixed(1)} MB`;",
+ "no-raw-rounding::apps/erp/app/components/ModelUploadProgress.tsx::if (n >= 1024 ** 3) return `${(n / 1024 ** 3).toFixed(2)} GB`;",
+ "no-raw-rounding::apps/erp/app/components/ModelUploadProgress.tsx::if (n >= 1024) return `${Math.round(n / 1024)} KB`;",
+ "no-raw-rounding::apps/erp/app/components/ModelUploadProgress.tsx::value={`${Math.round(percent)}%`}",
+ "no-raw-rounding::apps/erp/app/components/PeriodSelector.tsx::const month = Math.floor((date.month - 1) / 3) * 3 + 1;",
+ "no-raw-rounding::apps/erp/app/components/Table/Table.tsx::const mid = Math.floor(sorted.length / 2);",
+ "no-raw-rounding::apps/erp/app/components/Table/components/Pagination/usePagination.tsx::const canNextPage = pageIndex < Math.ceil(count / pageSize);",
+ "no-raw-rounding::apps/erp/app/components/Table/components/Pagination/usePagination.tsx::const pageCount = Math.ceil(count / pageSize);",
+ "no-raw-rounding::apps/erp/app/components/Table/components/Pagination/usePagination.tsx::const pageIndex = Math.floor(offset / pageSize) + 1;",
+ "no-raw-rounding::apps/erp/app/components/TimeCardWarning.tsx::const hoursElapsed = Math.floor(",
+ "no-raw-rounding::apps/erp/app/hooks/useScrollPosition.tsx::Math.ceil(el.scrollLeft + el.clientWidth) < el.scrollWidth",
+ "no-raw-rounding::apps/erp/app/hooks/useScrollPosition.tsx::setCanScrollRight(Math.ceil(scrollLeft + clientWidth) < scrollWidth);",
+ "no-raw-rounding::apps/erp/app/modules/accounting/accounting.service.ts::const year = firstYear + Math.floor((startMonth - 1 + (p - 1)) / 12);",
+ "no-raw-rounding::apps/erp/app/modules/accounting/accounting.utils.ts::const quarterPlaced = Math.ceil((startDate.getMonth() + 1) / 3);",
+ "no-raw-rounding::apps/erp/app/modules/accounting/ui/FixedAssets/AssetClassesTable.tsx::const years = life ? Math.round((life / 12) * 10) / 10 : null;",
+ "no-raw-rounding::apps/erp/app/modules/agent/ui/greetings.ts::return GREETINGS[Math.floor(Math.random() * GREETINGS.length)]();",
+ "no-raw-rounding::apps/erp/app/modules/documents/ui/Documents/DocumentCreateForm.tsx::formData.append(\"size\", Math.round(size / 1024).toString());",
+ "no-raw-rounding::apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx::Math.round(",
+ "no-raw-rounding::apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx::formData.append(\"size\", Math.round(file.size / 1024).toString());",
+ "no-raw-rounding::apps/erp/app/modules/inventory/ui/Traceability/utils.ts::if (q >= 1000) return `${(q / 1000).toFixed(1)}k`;",
+ "no-raw-rounding::apps/erp/app/modules/inventory/ui/Traceability/utils.ts::return q.toFixed(1);",
+ "no-raw-rounding::apps/erp/app/modules/inventory/ui/Traceability/worker/core.ts::const clamped = Math.min(Math.max(1, Math.round(spacingLevel)), 5);",
+ "no-raw-rounding::apps/erp/app/modules/invoicing/ui/Dashboard/InvoicingDashboard.tsx::ap.total > 0 ? Math.round((apOverdue / ap.total) * 100) : 0;",
+ "no-raw-rounding::apps/erp/app/modules/invoicing/ui/Dashboard/InvoicingDashboard.tsx::ar.total > 0 ? Math.round((arOverdue / ar.total) * 100) : 0;",
+ "no-raw-rounding::apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx::Math.floor((file.metadata?.size ?? 0) / 1024)",
+ "no-raw-rounding::apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx::Math.floor((modelUpload.modelSize ?? 0) / 1024)",
+ "no-raw-rounding::apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx::formData.append(\"size\", Math.round(file.size / 1024).toString());",
+ "no-raw-rounding::apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx::const exponent = Math.floor(Math.log10(value));",
+ "no-raw-rounding::apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx::const niceMax = Math.ceil(hi / step) * step;",
+ "no-raw-rounding::apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx::const niceMin = Math.floor(lo / step) * step;",
+ "no-raw-rounding::apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx::ticks.push(Math.round(v));",
+ "no-raw-rounding::apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx::? Math.ceil(order.quantity / conversionFactor)",
+ "no-raw-rounding::apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx::Math.ceil(orderQuantity / orderMultiple) * orderMultiple;",
+ "no-raw-rounding::apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx::Math.ceil(totalOrderQuantity / orderMultiple) * orderMultiple;",
+ "no-raw-rounding::apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx::const dueDateOffset = Math.floor(",
+ "no-raw-rounding::apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx::const numberOfBatches = Math.ceil(totalOrderQuantity / lotSize);",
+ "no-raw-rounding::apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx::orderQuantity = Math.ceil(orderQuantity / lotSize) * lotSize;",
+ "no-raw-rounding::apps/erp/app/modules/items/ui/Parts/PartForm.tsx::{convertKbToString(Math.ceil(modelFile.size / 1024))}",
+ "no-raw-rounding::apps/erp/app/modules/items/ui/Tools/ToolForm.tsx::{convertKbToString(Math.ceil(modelFile.size / 1024))}",
+ "no-raw-rounding::apps/erp/app/modules/people/ui/Timecards/TimecardsTable.tsx::const hours = Math.floor(ms / 3600000);",
+ "no-raw-rounding::apps/erp/app/modules/people/ui/Timecards/TimecardsTable.tsx::const minutes = Math.floor((ms % 3600000) / 60000);",
+ "no-raw-rounding::apps/erp/app/modules/production/production.service.ts::const count = Math.round(material.quantity);",
+ "no-raw-rounding::apps/erp/app/modules/production/production.service.ts::const totalJobs = lotSize > 0 ? Math.ceil(totalQuantity / lotSize) : 1;",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx::` · BOM qty ${Math.round(bomLine.quantity)} ≠ model ${group.count}`}",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx::bomLine !== undefined && Math.round(bomLine.quantity) !== group.count;",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx::if (mm3 >= 1000) return `${(mm3 / 1000).toFixed(1)} cm³`;",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx::return `${mm3.toFixed(0)} mm³`;",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx::return mm >= 100 ? mm.toFixed(0) : mm.toFixed(1);",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx::×{Math.round(material.quantity)}",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx::? Math.max(0, Math.round((solveNow - solveStartedAt) / 1000))",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx::const solveElapsedLabel = `${Math.floor(solveElapsedSeconds / 60)}:${String(",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyStepBom.tsx::)}, ${Math.round(color[2] * 255)}, ${color[3]})`",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/AssemblyStepBom.tsx::backgroundColor: `rgba(${Math.round(color[0] * 255)}, ${Math.round(",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/ModelConvertProgress.tsx::if (n >= 1024 * 1024) return `${(n / (1024 * 1024)).toFixed(1)} MB`;",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/ModelConvertProgress.tsx::if (n >= 1024) return `${Math.round(n / 1024)} KB`;",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/Assemblies/ModelConvertProgress.tsx::return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/InspectionDocument/InspectionDocumentEditor.tsx::Math.min(26, Math.round(radius * 1.15))",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/InspectionDocument/InspectionDocumentEditor.tsx::Math.min(3, Number((zoomScale * Math.min(fitX, fitY)).toFixed(2)))",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/InspectionDocument/InspectionDocumentEditor.tsx::aria-valuenow={Math.round(pdfPaneHeightPx)}",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/InspectionDocument/InspectionDocumentEditor.tsx::setZoomScale((z) => Math.max(0.5, Number((z - 0.1).toFixed(2))))",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/InspectionDocument/InspectionDocumentEditor.tsx::setZoomScale((z) => Math.min(3, Number((z + 0.1).toFixed(2))))",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/InspectionDocument/InspectionDocumentEditor.tsx::{Math.round(zoomScale * 100)}%",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/InspectionDocument/cropInspectionAnchorToPng.ts::Math.max(1, Math.floor(renderedPageWidthPx * VISION_RENDER_SCALE)),",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/InspectionDocument/cropInspectionAnchorToPng.ts::const ch = Math.max(1, Math.floor(viewport.height));",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/InspectionDocument/cropInspectionAnchorToPng.ts::const cw = Math.max(1, Math.floor(viewport.width));",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/InspectionDocument/cropInspectionAnchorToPng.ts::const sh = Math.max(1, Math.floor((rh / 100) * ch));",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/InspectionDocument/cropInspectionAnchorToPng.ts::const sw = Math.max(1, Math.floor((rw / 100) * cw));",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/InspectionDocument/cropInspectionAnchorToPng.ts::const sx = Math.floor((rx / 100) * cw);",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/InspectionDocument/cropInspectionAnchorToPng.ts::const sy = Math.floor((ry / 100) * ch);",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/InspectionDocument/exportInspectionDocumentPdfWithOverlays.ts::Math.min(26, Math.round(radius * 1.15))",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/InspectionDocument/exportInspectionDocumentPdfWithOverlays.ts::const ch = Math.floor(viewport.height);",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/InspectionDocument/exportInspectionDocumentPdfWithOverlays.ts::const cw = Math.floor(viewport.width);",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx::Math.floor((file.metadata?.size ?? 0) / 1024)",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx::Math.floor((modelUpload.modelSize ?? 0) / 1024)",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx::formData.append(\"size\", Math.round(size / 1024).toString());",
+ "no-raw-rounding::apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx::const halfQty = Math.floor(leftoverQuantity / 2);",
+ "no-raw-rounding::apps/erp/app/modules/purchasing/purchasing.service.ts::? Math.round(",
+ "no-raw-rounding::apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningOrderDrawer.tsx::? Math.ceil(inventoryQuantity / conversionFactor)",
+ "no-raw-rounding::apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx::const weeks = Math.ceil(leadTime / 7);",
+ "no-raw-rounding::apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionDocuments.tsx::Math.floor((attachment.metadata?.size ?? 0) / 1024)",
+ "no-raw-rounding::apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionDocuments.tsx::formData.append(\"size\", Math.round(size / 1024).toString());",
+ "no-raw-rounding::apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineDocuments.tsx::Math.floor((file.metadata?.size ?? 0) / 1024)",
+ "no-raw-rounding::apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineDocuments.tsx::formData.append(\"size\", Math.round(size / 1024).toString());",
+ "no-raw-rounding::apps/erp/app/modules/quality/samplingStandards.ts::const n = Math.max(1, Math.min(safeLot, Math.ceil((safeLot * pct) / 100)));",
+ "no-raw-rounding::apps/erp/app/modules/quality/samplingStandards.ts::const safeLot = Math.max(1, Math.floor(lotSize));",
+ "no-raw-rounding::apps/erp/app/modules/quality/ui/Inspections/InspectionView.tsx::aria-valuenow={Math.round(pdfPaneHeightPx)}",
+ "no-raw-rounding::apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchNotes.tsx::Math.floor((file.metadata?.size ?? 0) / 1024)",
+ "no-raw-rounding::apps/erp/app/modules/sales/ui/Opportunity/OpportunityDocuments.tsx::Math.floor((attachment.metadata?.size ?? 0) / 1024)",
+ "no-raw-rounding::apps/erp/app/modules/sales/ui/Opportunity/OpportunityDocuments.tsx::formData.append(\"size\", Math.round(size / 1024).toString());",
+ "no-raw-rounding::apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx::Math.floor((file.metadata?.size ?? 0) / 1024)",
+ "no-raw-rounding::apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx::Math.floor((modelUpload.modelSize ?? 0) / 1024)",
+ "no-raw-rounding::apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx::formData.append(\"size\", Math.round(size / 1024).toString());",
+ "no-raw-rounding::apps/erp/app/modules/settings/settings.service.ts::generatedPin = Math.floor(1000 + Math.random() * 9000).toString();",
+ "no-raw-rounding::apps/erp/app/modules/settings/ui/AuditLog/AuditLogSettings.tsx::const i = Math.floor(Math.log(bytes) / Math.log(k));",
+ "no-raw-rounding::apps/erp/app/modules/settings/ui/AuditLog/AuditLogSettings.tsx::return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;",
+ "no-raw-rounding::apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx::const m = Math.floor(s / 60);",
+ "no-raw-rounding::apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx::const s = Math.max(0, Math.floor(ms / 1000));",
+ "no-raw-rounding::apps/erp/app/modules/settings/ui/Company/CompanyLogoForm.tsx::).toFixed(2)}MB`",
+ "no-raw-rounding::apps/erp/app/modules/settings/ui/Printing/PrintJobsTable.tsx::? Math.max(0.5, Math.round((Number(llMatch[1]) / dpi) * 10) / 10)",
+ "no-raw-rounding::apps/erp/app/modules/settings/ui/Printing/PrintJobsTable.tsx::? Math.max(0.5, Math.round((Number(pwMatch[1]) / dpi) * 10) / 10)",
+ "no-raw-rounding::apps/erp/app/modules/settings/ui/Printing/PrintJobsTable.tsx::const dpmm = Math.round(dpi / 25.4);",
+ "no-raw-rounding::apps/erp/app/modules/shared/shared.server.ts::size: Math.round(file.byteLength / 1024),",
+ "no-raw-rounding::apps/erp/app/modules/workflows/ui/Builder/layout.ts::x: Math.round(laid.x - width / 2),",
+ "no-raw-rounding::apps/erp/app/modules/workflows/ui/Builder/layout.ts::y: Math.round(laid.y - height / 2)",
+ "no-raw-rounding::apps/erp/app/modules/workflows/ui/Runs/WorkflowRunSteps.tsx::return `${(ms / 1000).toFixed(1)}s`;",
+ "no-raw-rounding::apps/erp/app/routes/_oauth+/register.ts::client_id_issued_at: Math.floor(Date.now() / 1000),",
+ "no-raw-rounding::apps/erp/app/routes/api+/items.$itemId.recalculate-cost.ts::message: `Unit cost updated to ${unitCost.toFixed(2)}`",
+ "no-raw-rounding::apps/erp/app/routes/api+/quality.kpi.$key.ts::const days = Math.floor(",
+ "no-raw-rounding::apps/erp/app/routes/api+/quality.kpi.$key.ts::const week = Math.ceil(",
+ "no-raw-rounding::apps/erp/app/routes/api+/quality.kpi.$key.ts::const weeksOpen = Math.floor(",
+ "no-raw-rounding::apps/erp/app/routes/api+/quality.kpi.$key.ts::cumulative: total > 0 ? Math.round((cumulative / total) * 100) : 0",
+ "no-raw-rounding::apps/erp/app/routes/api+/quality.kpi.$key.ts::data: [{ value: count > 0 ? Math.round(total / count) : null }],",
+ "no-raw-rounding::apps/erp/app/routes/share+/training.$id.tsx::(Passing score: {Math.round(PASSING_THRESHOLD * 100)}%)",
+ "no-raw-rounding::apps/erp/app/routes/share+/training.$id.tsx::const scorePercent = Math.round(actionData.score * 100);",
+ "no-raw-rounding::apps/erp/app/routes/share+/training.$id.tsx::least {Math.round(PASSING_THRESHOLD * 100)}% to pass. Please",
+ "no-raw-rounding::apps/erp/app/routes/x+/fixed-asset+/$fixedAssetId.tsx::value={`${depreciationPercent.toFixed(1)}%`}",
+ "no-raw-rounding::apps/erp/app/routes/x+/fixed-asset+/$fixedAssetId.tsx::value={`${taxDepreciationPercent.toFixed(1)}%`}",
+ "no-raw-rounding::apps/erp/app/routes/x+/job+/bulk.new.tsx::const dayOffset = Math.floor(cumulativeJobs / jobsPerDay);",
+ "no-raw-rounding::apps/erp/app/routes/x+/job+/bulk.new.tsx::const dayOffset = Math.floor(i * daysPerJob);",
+ "no-raw-rounding::apps/erp/app/routes/x+/job+/bulk.new.tsx::const jobs = Math.ceil(totalQuantity / quantityPerJob);",
+ "no-raw-rounding::apps/erp/app/routes/x+/person+/$personId.timecard.tsx::const hours = Math.floor(ms / 3600000);",
+ "no-raw-rounding::apps/erp/app/routes/x+/person+/$personId.timecard.tsx::const hours = Math.floor(totalMs / 3600000);",
+ "no-raw-rounding::apps/erp/app/routes/x+/person+/$personId.timecard.tsx::const minutes = Math.floor((ms % 3600000) / 60000);",
+ "no-raw-rounding::apps/erp/app/routes/x+/person+/$personId.timecard.tsx::const minutes = Math.floor((totalMs % 3600000) / 60000);",
+ "no-raw-rounding::apps/erp/app/routes/x+/production+/_index.tsx::).toFixed(2);",
+ "no-raw-rounding::apps/erp/app/routes/x+/production+/_index.tsx::+{percentageChange.toFixed(0)}%",
+ "no-raw-rounding::apps/erp/app/routes/x+/production+/_index.tsx::<Badge variant=\"red\">{percentageChange.toFixed(0)}%</Badge>",
+ "no-raw-rounding::apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx::? Math.round(file.byteLength / 1024) +",
+ "no-raw-rounding::apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx::size: Math.round(file.byteLength / 1024),",
+ "no-raw-rounding::apps/erp/app/routes/x+/purchase-order+/$orderId.tsx::? Math.round(((d.metadata as { size?: number }).size as number) / 1024)",
+ "no-raw-rounding::apps/erp/app/routes/x+/purchase-order+/$orderId.tsx::size: Math.round(file.byteLength / 1024),",
+ "no-raw-rounding::apps/erp/app/routes/x+/purchasing+/_index.tsx::<Badge variant=\"green\">+{percentageChange.toFixed(0)}%</Badge>",
+ "no-raw-rounding::apps/erp/app/routes/x+/purchasing+/_index.tsx::<Badge variant=\"red\">{percentageChange.toFixed(0)}%</Badge>",
+ "no-raw-rounding::apps/erp/app/routes/x+/quality+/_index.tsx::const pct = total > 0 ? Math.round(((value as number) / total) * 100) : 0;",
+ "no-raw-rounding::apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx::size: Math.round(file.byteLength / 1024),",
+ "no-raw-rounding::apps/erp/app/routes/x+/resources+/_index.tsx::{percentageChange.toFixed(0)}%",
+ "no-raw-rounding::apps/erp/app/routes/x+/sales+/_index.tsx::<Badge variant=\"green\">+{percentageChange.toFixed(0)}%</Badge>",
+ "no-raw-rounding::apps/erp/app/routes/x+/sales+/_index.tsx::<Badge variant=\"red\">{percentageChange.toFixed(0)}%</Badge>",
+ "no-raw-rounding::apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx::size: Math.round(file.byteLength / 1024),",
+ "no-raw-rounding::apps/erp/app/routes/x+/settings+/backups.tsx::{convertKbToString(Math.round(file.sizeBytes / 1024))}",
+ "no-raw-rounding::apps/erp/app/routes/x+/settings+/printing.tsx::const heightDots = Math.round(height * dpi);",
+ "no-raw-rounding::apps/erp/app/routes/x+/settings+/printing.tsx::const widthDots = Math.round(width * dpi);",
+ "no-raw-rounding::apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx::size: Math.round(file.byteLength / 1024),",
+ "no-raw-rounding::apps/erp/app/routes/x+/users+/operators.new.tsx::return Math.floor(1000 + Math.random() * 9000).toString();",
+ "no-raw-rounding::apps/erp/app/routes/x+/users+/operators.reset-pin.$operatorId.tsx::return Math.floor(1000 + Math.random() * 9000).toString();",
+ "no-raw-rounding::apps/mes/app/components/AssemblyView.tsx::Math.round(operation?.operationQuantity ?? trackedEntities.length)",
+ "no-raw-rounding::apps/mes/app/components/AssemblyView.tsx::Math.round(operation?.quantityComplete ?? 0)",
+ "no-raw-rounding::apps/mes/app/components/AssemblyView.tsx::const h = Math.floor(s / 3600)",
+ "no-raw-rounding::apps/mes/app/components/AssemblyView.tsx::const m = Math.floor((s % 3600) / 60)",
+ "no-raw-rounding::apps/mes/app/components/AssemblyView.tsx::return Math.max(0, Math.floor((Date.now() - start) / 1000));",
+ "no-raw-rounding::apps/mes/app/components/Display/ActiveWorkPanel.tsx::style={{ width: `${Math.round(progress * 100)}%` }}",
+ "no-raw-rounding::apps/mes/app/components/Inspection/InspectionView.tsx::Math.round((operation.quantityComplete as number) ?? 0)",
+ "no-raw-rounding::apps/mes/app/components/Inspection/InspectionView.tsx::aria-valuenow={Math.round(pdfPaneHeightPx)}",
+ "no-raw-rounding::apps/mes/app/components/Inspection/InspectionView.tsx::const h = Math.floor(s / 3600)",
+ "no-raw-rounding::apps/mes/app/components/Inspection/InspectionView.tsx::const m = Math.floor((s % 3600) / 60)",
+ "no-raw-rounding::apps/mes/app/components/Inspection/InspectionView.tsx::return Math.max(0, Math.floor((Date.now() - start) / 1000));",
+ "no-raw-rounding::apps/mes/app/components/JobOperation/JobOperation.tsx::Math.floor(",
+ "no-raw-rounding::apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx::Array(Math.max(1, Math.ceil(initialQuantity)))",
+ "no-raw-rounding::apps/mes/app/components/TimeCardButton.tsx::const hours = Math.floor(ms / 3600000);",
+ "no-raw-rounding::apps/mes/app/components/TimeCardButton.tsx::const minutes = Math.floor((ms % 3600000) / 60000);",
+ "no-raw-rounding::apps/mes/app/components/TimeCardWarning.tsx::const hoursElapsed = Math.floor(",
+ "no-raw-rounding::apps/mes/app/routes/x+/assembly.$operationId.tsx::Math.round((op.operationQuantity as number) ?? allEntities.length)",
+ "no-raw-rounding::apps/mes/app/routes/x+/assembly.$operationId.tsx::Math.round((op.quantityComplete as number) ?? 0)",
+ "no-raw-rounding::apps/mes/app/routes/x+/dispatch.$dispatchId.tsx::const hours = Math.floor(seconds / 3600);",
+ "no-raw-rounding::apps/mes/app/routes/x+/dispatch.$dispatchId.tsx::const minutes = Math.floor((seconds % 3600) / 60);",
+ "no-raw-rounding::apps/mes/app/routes/x+/picking._index.tsx::? Math.round((completedLineCount / lineCount) * 100)",
+ "no-raw-rounding::apps/mes/app/routes/x+/timecard.tsx::const hours = Math.floor(ms / 3600000);",
+ "no-raw-rounding::apps/mes/app/routes/x+/timecard.tsx::const hours = Math.floor(totalMs / 3600000);",
+ "no-raw-rounding::apps/mes/app/routes/x+/timecard.tsx::const minutes = Math.floor((ms % 3600000) / 60000);",
+ "no-raw-rounding::apps/mes/app/routes/x+/timecard.tsx::const minutes = Math.floor((totalMs % 3600000) / 60000);",
+ "no-raw-rounding::apps/mes/app/utils/display.ts::Math.floor((now.getTime() - started) / 1000)",
+ "no-raw-rounding::apps/mes/app/utils/display.ts::const days = Math.floor(hours / 24);",
+ "no-raw-rounding::apps/mes/app/utils/display.ts::const hours = Math.floor(minutes / 60);",
+ "no-raw-rounding::apps/mes/app/utils/display.ts::const hours = Math.floor(totalSeconds / 3600);",
+ "no-raw-rounding::apps/mes/app/utils/display.ts::const minutes = Math.floor((totalSeconds % 3600) / 60);",
+ "no-raw-rounding::apps/mes/app/utils/display.ts::const minutes = Math.floor(Math.abs(diffMs) / 60000);",
+ "no-raw-rounding::apps/mes/app/utils/display.ts::return `${Math.floor(days / 7)}w`;",
+ "no-raw-rounding::apps/mes/app/utils/units.ts::* existing `Math.max(1, Math.round(operationQuantity))` behavior).",
+ "no-raw-rounding::apps/mes/app/utils/units.ts::const total = Math.max(1, Math.round(Number.isFinite(count) ? count : 1));",
+ "no-raw-rounding::packages/database/supabase/functions/assign-serial-numbers/index.ts::trackingType === \"Batch\" ? 1 : Math.round(Number(job.quantity));",
+ "no-raw-rounding::packages/database/supabase/functions/lib/mrp-engine.ts::const childLeadTimeWeeks = Math.ceil(childLeadTimeDays / 7);",
+ "no-raw-rounding::packages/database/supabase/functions/lib/scheduling/duration-calculator.ts::const totalDays = Math.max(Math.ceil(totalHours / HOURS_PER_WORKDAY), 1);",
+ "no-raw-rounding::packages/database/supabase/functions/lib/scheduling/duration-calculator.ts::return Math.max(Math.ceil(hours / hoursPerDay), 1);",
+ "no-raw-rounding::packages/database/supabase/functions/lib/utils.ts::Math.floor(",
+ "no-raw-rounding::packages/database/supabase/functions/reschedule/index.ts::return Math.max(Math.ceil(days), 1);",
+ "no-raw-rounding::packages/database/supabase/functions/shared/sampling-engine.ts::const n = Math.max(1, Math.min(safeLot, Math.ceil((safeLot * pct) / 100)));",
+ "no-raw-rounding::packages/database/supabase/functions/shared/sampling-engine.ts::const safeLot = Math.max(1, Math.floor(lotSize));",
+ "no-raw-rounding::packages/database/supabase/functions/update-purchased-prices/index.ts::itemReplenishmentUpdate.leadTime = Math.round(",
+ "no-raw-rounding::packages/documents/src/pdf/KanbanLabelPDF.tsx::const pageCount = Math.ceil(labels.length / labelsPerPage);",
+ "no-raw-rounding::packages/documents/src/pdf/ProductLabelPDF.tsx::const pageCount = Math.ceil(items.length / labelsPerPage);",
+ "no-raw-rounding::packages/documents/src/pdf/components/labelGeometry.ts::const qrModuleSize = Math.max(2, Math.min(8, Math.round(4 * scale)));",
+ "no-raw-rounding::packages/ee/src/onshape/lib/client.ts::`Onshape external data ${foreignId} exceeds the ${Math.round(",
+ "no-raw-rounding::packages/ee/src/slack/lib/client.ts::const currentTime = Math.floor(Date.now() / 1000);",
+ "no-raw-rounding::packages/ee/src/slack/lib/messages.ts::? `on <!date^${Math.floor(",
+ "no-raw-rounding::packages/ee/src/slack/lib/messages.ts::? `• Completed <!date^${Math.floor(",
+ "no-raw-rounding::packages/ee/src/slack/lib/messages.ts::text: `Updated by <@${update.updatedBy}> at <!date^${Math.floor(",
+ "no-raw-rounding::packages/jobs/src/inngest/functions/scheduled/cleanup.ts::await step.sleep(\"jitter\", `${Math.floor(Math.random() * 3600)}s`);",
+ "no-raw-rounding::packages/react/src/BarProgress.tsx::<span className=\"sr-only\">{Math.round(percentage)}%</span>",
+ "no-raw-rounding::packages/react/src/BarProgress.tsx::const activeBars = Math.round((clampedProgress / max) * barCount);",
+ "no-raw-rounding::packages/react/src/BarProgress.tsx::const bl = Math.round(a[2] + (b[2] - a[2]) * t);",
+ "no-raw-rounding::packages/react/src/BarProgress.tsx::const count = Math.floor((width + BAR_GAP) / (BAR_WIDTH + BAR_GAP));",
+ "no-raw-rounding::packages/react/src/BarProgress.tsx::const g = Math.round(a[1] + (b[1] - a[1]) * t);",
+ "no-raw-rounding::packages/react/src/BarProgress.tsx::const r = Math.round(a[0] + (b[0] - a[0]) * t);",
+ "no-raw-rounding::packages/react/src/BarProgress.tsx::const segBars = Math.round((seg.value / max) * barCount);",
+ "no-raw-rounding::packages/react/src/Sidebar.tsx::return `${Math.floor(Math.random() * 40) + 50}%`;",
+ "no-raw-rounding::packages/utils/src/accounting.ts::const quarter = Math.ceil(periodNumber / 3);",
+ "no-raw-rounding::packages/utils/src/date.ts::const count = Math.floor(remaining / seconds);",
+ "no-raw-rounding::packages/utils/src/date.ts::const days = Math.round(",
+ "no-raw-rounding::packages/utils/src/date.ts::let remaining = Math.floor(Math.abs(diffMs) / 1000);",
+ "no-raw-rounding::packages/utils/src/date.ts::return formatter.format(Math.round(days / 30.44), \"months\");",
+ "no-raw-rounding::packages/utils/src/date.ts::return formatter.format(Math.round(days / 365.25), \"years\");",
+ "no-raw-rounding::packages/utils/src/date.ts::return relativeFormatter.format(Math.round(-1 * duration), division.name);",
+ "no-raw-rounding::packages/utils/src/date.ts::return relativeFormatter.format(Math.round(duration), division.name);",
+ "no-raw-rounding::packages/utils/src/datetime.ts::Math.floor(thursday.compare(new CalendarDate(thursday.year, 1, 1)) / 7) + 1",
+ "no-raw-rounding::packages/utils/src/file.ts::return `${gb.toFixed(2)} GB`;",
+ "no-raw-rounding::packages/utils/src/file.ts::return `${mb.toFixed(2)} MB`;",
+ "no-raw-rounding::packages/utils/src/labels.ts::const heightMm = Math.round(size.height * 25.4);",
+ "no-raw-rounding::packages/utils/src/labels.ts::const widthMm = Math.round(size.width * 25.4);"
]
diff --git a/packages/checks/src/conformance/no-derived-percent-column.test.ts b/packages/checks/src/conformance/no-derived-percent-column.test.ts
new file mode 100644
index 0000000000..71a4b767f8
--- /dev/null
+++ b/packages/checks/src/conformance/no-derived-percent-column.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from "vitest";
+import { noDerivedPercentColumn } from "./no-derived-percent-column";
+
+describe("no-derived-percent-column", () => {
+ it("flags a generated percent column that divides", () => {
+ const sql = `ALTER TABLE "purchaseOrderLine" ADD COLUMN "taxPercent" NUMERIC GENERATED ALWAYS AS (
+ CASE
+ WHEN ("supplierUnitPrice" * "purchaseQuantity" + "supplierShippingCost") = 0 THEN 0
+ ELSE "supplierTaxAmount" / ("supplierUnitPrice" * "purchaseQuantity" + "supplierShippingCost")
+ END
+) STORED;`;
+ const violations = noDerivedPercentColumn.scan("a.sql", sql);
+ expect(violations).toHaveLength(1);
+ expect(violations[0]?.line).toBe(1);
+ expect(violations[0]?.snippet).toContain("taxPercent");
+ });
+
+ it("flags a rate column derived on a single line", () => {
+ const sql = `ALTER TABLE "t" ADD COLUMN "marginRate" NUMERIC GENERATED ALWAYS AS ("profit" / "revenue") STORED;`;
+ expect(noDerivedPercentColumn.scan("a.sql", sql)).toHaveLength(1);
+ });
+
+ it("allows a generated percent column without division", () => {
+ const sql = `ALTER TABLE "t" ADD COLUMN "combinedPercent" NUMERIC GENERATED ALWAYS AS ("aPercent" + "bPercent") STORED;`;
+ expect(noDerivedPercentColumn.scan("a.sql", sql)).toHaveLength(0);
+ });
+
+ it("allows plain stored percent columns", () => {
+ const sql = `ALTER TABLE "t" ADD COLUMN "taxPercent" NUMERIC NOT NULL DEFAULT 0;`;
+ expect(noDerivedPercentColumn.scan("a.sql", sql)).toHaveLength(0);
+ });
+
+ it("allows generated non-percent columns that divide", () => {
+ const sql = `ALTER TABLE "t" ADD COLUMN "unitPrice" NUMERIC GENERATED ALWAYS AS ("supplierUnitPrice" / "exchangeRate") STORED;`;
+ expect(noDerivedPercentColumn.scan("a.sql", sql)).toHaveLength(0);
+ });
+
+ it("stops at a same-line terminator instead of swallowing what follows", () => {
+ // The percent column is self-contained and does not divide. The division
+ // below belongs to a different column; a multiline walk that ignored the
+ // terminator on line 1 would blame it on the percent column.
+ const sql = [
+ `ALTER TABLE "t" ADD COLUMN "combinedPercent" NUMERIC GENERATED ALWAYS AS ("aPercent" + "bPercent") STORED;`,
+ `ALTER TABLE "t" ADD COLUMN "unitPrice" NUMERIC GENERATED ALWAYS AS ("supplierUnitPrice" / "exchangeRate") STORED;`
+ ].join("\n");
+ expect(noDerivedPercentColumn.scan("a.sql", sql)).toHaveLength(0);
+ });
+});
diff --git a/packages/checks/src/conformance/no-derived-percent-column.ts b/packages/checks/src/conformance/no-derived-percent-column.ts
new file mode 100644
index 0000000000..40ffc4f1fa
--- /dev/null
+++ b/packages/checks/src/conformance/no-derived-percent-column.ts
@@ -0,0 +1,57 @@
+import type { ConformanceCheck, Violation } from "../check";
+
+// A generated `*Percent`/`*Rate` column whose expression DIVIDES is a lossy
+// echo of a rounded amount, not a stored fact — the purchasing taxPercent bug:
+// rate = amount / subtotal turned a typed 6.25% into 6.22% after the amount
+// was rounded to cents. Percentages are entered facts; amounts derive from
+// them (applyRate), never the reverse.
+const PERCENT_COLUMN =
+ /"[A-Za-z]*(?:Percent|Rate)"\s+[A-Za-z(,0-9\s)]*GENERATED\s+ALWAYS\s+AS/i;
+
+export const noDerivedPercentColumn: ConformanceCheck = {
+ id: "no-derived-percent-column",
+ description:
+ "Percent/rate columns must be plain stored values, never GENERATED expressions that divide",
+ provenance: {
+ deprecates:
+ "generated percent columns derived by division (rate = amount / subtotal)",
+ replacedBy:
+ "writable percent columns; amounts derive via applyRate in @carbon/utils",
+ since: "2026-08-11"
+ },
+ scan(file: string, contents: string): Violation[] {
+ const violations: Violation[] = [];
+ const lines = contents.split("\n");
+
+ for (let i = 0; i < lines.length; i++) {
+ const text = lines[i] ?? "";
+ if (!PERCENT_COLUMN.test(text)) continue;
+
+ // The generated expression may span lines until `) STORED`; a division
+ // anywhere inside it is the smell. Bound the walk so a malformed
+ // migration can't send us to the end of the file.
+ let expression = text;
+ // A single-line generated column already carries its terminator, so
+ // walking on would swallow whatever follows — an unrelated division on
+ // the next line would then be blamed on this column.
+ if (!/\)\s*STORED/i.test(text)) {
+ for (let j = i + 1; j < Math.min(i + 12, lines.length); j++) {
+ const next = lines[j] ?? "";
+ expression += `\n${next}`;
+ if (/\)\s*STORED/i.test(next)) break;
+ }
+ }
+ if (/STORED/i.test(expression) && expression.includes("/")) {
+ violations.push({
+ file,
+ line: i + 1,
+ snippet: text.trim(),
+ message:
+ "Generated percent/rate column derives by division — store the entered rate and derive the amount via applyRate (@carbon/utils; see .claude/rules/numeric-precision.md)"
+ });
+ }
+ }
+
+ return violations;
+ }
+};
diff --git a/packages/checks/src/conformance/no-inline-fraction-digits.test.ts b/packages/checks/src/conformance/no-inline-fraction-digits.test.ts
new file mode 100644
index 0000000000..6015219356
--- /dev/null
+++ b/packages/checks/src/conformance/no-inline-fraction-digits.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from "vitest";
+import { noInlineFractionDigits } from "./no-inline-fraction-digits";
+
+describe("no-inline-fraction-digits", () => {
+ it("flags inline fraction-digit options", () => {
+ const src = [
+ "const f = new Intl.NumberFormat(locale, {",
+ " minimumFractionDigits: 2,",
+ " maximumFractionDigits: 4",
+ "});"
+ ].join("\n");
+ const violations = noInlineFractionDigits.scan("a.tsx", src);
+ expect(violations).toHaveLength(2);
+ expect(violations[0]?.message).toContain("named kind");
+ });
+
+ it("excludes the one file where digits are defined", () => {
+ const src = "const opts = { maximumFractionDigits: SCALE };";
+ expect(
+ noInlineFractionDigits.scan("packages/utils/src/format.ts", src)
+ ).toHaveLength(0);
+ });
+
+ it("does NOT exclude a file that merely consumes a kind", () => {
+ // Hook files were once listed as exclusions even though they contain no
+ // digits at all, which exempted whatever got added to them later. A file
+ // that consumes a kind has nothing to exempt, so it must still be scanned.
+ const src = "const opts = { maximumFractionDigits: 2 };";
+ for (const file of [
+ "apps/erp/app/hooks/usePercentFormatter.tsx",
+ "apps/erp/app/hooks/useQuantityFormatter.tsx",
+ "packages/documents/src/utils/shared.ts"
+ ]) {
+ expect(noInlineFractionDigits.scan(file, src)).toHaveLength(1);
+ }
+ });
+
+ it("allows named kinds", () => {
+ const src = "formatOptions={INPUT_FORMAT.rate}";
+ expect(noInlineFractionDigits.scan("a.tsx", src)).toHaveLength(0);
+ });
+});
diff --git a/packages/checks/src/conformance/no-inline-fraction-digits.ts b/packages/checks/src/conformance/no-inline-fraction-digits.ts
new file mode 100644
index 0000000000..4b202f9976
--- /dev/null
+++ b/packages/checks/src/conformance/no-inline-fraction-digits.ts
@@ -0,0 +1,74 @@
+import type { ConformanceCheck, Violation } from "../check";
+
+// Call sites never pick digit counts — they pick a NAMED KIND (money, price,
+// percent, quantity) whose digits are defined once in @carbon/utils format.ts.
+// Editable inputs must use INPUT_FORMAT.* because react-aria's blur commit
+// runs parse(format(x)) — the input formatter is part of arithmetic.
+const INLINE_DIGITS = /minimumFractionDigits|maximumFractionDigits/;
+
+// Naming NO digits is the same violation, and the one that hid longest: a bare
+// `style: "currency"` reads as neutral, so nothing flagged it, while Intl
+// quietly supplied the CLDR default for the code and `currency.decimalPlaces`
+// never got a say. That is how a currency configured to 0 kept rendering 2 —
+// and, on an editable input, committed the truncation on blur.
+const BARE_CURRENCY_STYLE = /style:\s*["']currency["']/;
+
+// The kinds themselves are built from `style: "currency"` — this is where it is
+// SUPPOSED to appear. Everything else picks a kind instead.
+const CURRENCY_STYLE_ALLOWED = new Set([
+ "packages/utils/src/format.ts",
+ // Builds the CLDR-only branch for a currency the group hasn't configured.
+ "apps/erp/app/hooks/useCurrencyFormatter.tsx"
+]);
+
+// The formatter layer itself is where the digits are DEFINED. Note
+// useCurrencyFormatter is deliberately NOT excluded — it delegates to
+// moneyFormatOptions, so a digit literal creeping back in should flag.
+//
+// Nothing else belongs here. A file that merely CONSUMES a kind has no digits
+// to exclude, and listing it exempts whatever gets added to it later — three
+// hook files were listed for exactly that reason and each exempted zero lines,
+// and packages/documents/src/utils/shared.ts was listed because it duplicated
+// the money kind instead of importing it, which is the drift this check exists
+// to catch rather than something to exempt.
+const EXCLUDED_FILES = new Set(["packages/utils/src/format.ts"]);
+
+export const noInlineFractionDigits: ConformanceCheck = {
+ id: "no-inline-fraction-digits",
+ description:
+ "Pick a named kind from @carbon/utils format.ts (money/price/percent/quantity, INPUT_FORMAT.*) instead of passing digits",
+ provenance: {
+ deprecates:
+ "inline minimumFractionDigits/maximumFractionDigits at call sites",
+ replacedBy:
+ "moneyFormatOptions + the PERCENT_FORMAT / PERCENT_POINTS_FORMAT / SCALE_FORMAT constants and INPUT_FORMAT from @carbon/utils",
+ since: "2026-08-11"
+ },
+ scan(file: string, contents: string): Violation[] {
+ const violations: Violation[] = [];
+ const digitsExcluded = EXCLUDED_FILES.has(file);
+ const currencyExcluded = CURRENCY_STYLE_ALLOWED.has(file);
+ contents.split("\n").forEach((text, i) => {
+ if (!digitsExcluded && INLINE_DIGITS.test(text)) {
+ violations.push({
+ file,
+ line: i + 1,
+ snippet: text.trim(),
+ message:
+ "Pick a named kind from @carbon/utils format.ts (money/price/percent/quantity, INPUT_FORMAT.*) instead of passing digits"
+ });
+ return;
+ }
+ if (!currencyExcluded && BARE_CURRENCY_STYLE.test(text)) {
+ violations.push({
+ file,
+ line: i + 1,
+ snippet: text.trim(),
+ message:
+ "Naming no digits picks the money kind by omission — Intl's CLDR default wins over currency.decimalPlaces. Use INPUT_FORMAT.money/price for inputs, or the money/price formatter hooks for displays"
+ });
+ }
+ });
+ return violations;
+ }
+};
diff --git a/packages/checks/src/conformance/no-raw-rounding.test.ts b/packages/checks/src/conformance/no-raw-rounding.test.ts
new file mode 100644
index 0000000000..0d4ba7a513
--- /dev/null
+++ b/packages/checks/src/conformance/no-raw-rounding.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from "vitest";
+import { noRawRounding } from "./no-raw-rounding";
+
+describe("no-raw-rounding", () => {
+ it("flags Math.round / Math.ceil / Math.floor / toFixed", () => {
+ const src = [
+ "const a = Math.round(x * 100) / 100;",
+ "const b = Math.ceil(qty * scrapPct);",
+ "const c = Math.floor(total);",
+ "const d = Number(price.toFixed(2));"
+ ].join("\n");
+ const violations = noRawRounding.scan("a.ts", src);
+ expect(violations).toHaveLength(4);
+ expect(violations.map((v) => v.line)).toEqual([1, 2, 3, 4]);
+ });
+
+ it("uses the full trimmed line as the snippet so sites never collapse", () => {
+ const src = ["Math.ceil(a);", "Math.ceil(b);"].join("\n");
+ const [first, second] = noRawRounding.scan("a.ts", src);
+ expect(first?.snippet).not.toBe(second?.snippet);
+ });
+
+ it("allows the precision module's helpers", () => {
+ const src = [
+ 'import { round, scrapAllowance } from "@carbon/utils";',
+ "const a = round(x);",
+ "const b = scrapAllowance(target, rate);"
+ ].join("\n");
+ expect(noRawRounding.scan("a.ts", src)).toHaveLength(0);
+ });
+});
diff --git a/packages/checks/src/conformance/no-raw-rounding.ts b/packages/checks/src/conformance/no-raw-rounding.ts
new file mode 100644
index 0000000000..bf9c44f628
--- /dev/null
+++ b/packages/checks/src/conformance/no-raw-rounding.ts
@@ -0,0 +1,47 @@
+import type { ConformanceCheck, Violation } from "../check";
+
+// Raw JS rounding on value-bearing numbers loses the numeric standard's
+// guarantees: Math.round breaks tie parity with Postgres, Math.ceil on a
+// quantity inflates fractional targets (the 4.5 -> 5 consumption bug), and
+// toFixed is string arithmetic. Use round/scrapAllowance/applyRate/deriveRate from
+// @carbon/utils (or functions/shared/precision.ts in edge functions).
+// Genuinely-integer sites (counts, pagination, geometry, day buckets) are
+// baselined, not exempted here.
+const RAW_ROUNDING = /Math\.(?:round|ceil|floor)\(|\.toFixed\(/;
+
+// The precision module IS the implementation of rounding.
+const EXCLUDED_FILES = new Set([
+ "packages/database/supabase/functions/shared/precision.ts"
+]);
+
+export const noRawRounding: ConformanceCheck = {
+ id: "no-raw-rounding",
+ description:
+ "Value-bearing rounding goes through @carbon/utils round/scrapAllowance/applyRate/deriveRate, not Math.round/ceil/floor or toFixed",
+ provenance: {
+ deprecates:
+ "ad-hoc Math.round/Math.ceil/Math.floor/toFixed on prices, rates, and quantities",
+ replacedBy:
+ "round/scrapAllowance/applyRate/deriveRate from @carbon/utils (functions/shared/precision.ts)",
+ since: "2026-08-11"
+ },
+ scan(file: string, contents: string): Violation[] {
+ if (EXCLUDED_FILES.has(file)) return [];
+ const violations: Violation[] = [];
+ // Match per line to avoid cross-line lastIndex state, and use the full
+ // trimmed line as the snippet so two different sites in one file never
+ // collapse into one baseline key.
+ contents.split("\n").forEach((text, i) => {
+ if (RAW_ROUNDING.test(text)) {
+ violations.push({
+ file,
+ line: i + 1,
+ snippet: text.trim(),
+ message:
+ "Raw rounding — use round/scrapAllowance/applyRate/deriveRate from @carbon/utils (see .claude/rules/numeric-precision.md); baseline only genuinely-integer sites"
+ });
+ }
+ });
+ return violations;
+ }
+};
diff --git a/packages/checks/src/index.ts b/packages/checks/src/index.ts
index 713a06ca12..f7c5988ea2 100644
--- a/packages/checks/src/index.ts
+++ b/packages/checks/src/index.ts
@@ -1,14 +1,18 @@
export type {
ConformanceCheck,
ModuleDir,
+ SourceFile,
StructureCheck,
Violation
} from "./check";
-export { findClobbers, objectRefs, type SourceFile } from "./clobber";
+export { findClobbers, objectRefs } from "./clobber";
export { moduleShape } from "./conformance/module-shape";
+export { noDerivedPercentColumn } from "./conformance/no-derived-percent-column";
+export { noInlineFractionDigits } from "./conformance/no-inline-fraction-digits";
export { noLegacyRls } from "./conformance/no-legacy-rls";
export { noLocalTimezone } from "./conformance/no-local-timezone";
export { noNumericPrecision } from "./conformance/no-numeric-precision";
+export { noRawRounding } from "./conformance/no-raw-rounding";
export { noZeroConcurrency } from "./conformance/no-zero-concurrency";
export {
type Invariant,
@@ -25,7 +29,9 @@ export {
SERVER_CHECKS,
STRUCTURE_CHECKS,
scanAll,
- scanModules
+ scanModules,
+ TS_CHECKS
} from "./run";
export { loadModules, modulesDir } from "./sources/modules";
export { loadServerFiles } from "./sources/server-files";
+export { loadTypescriptFiles } from "./sources/typescript";
diff --git a/packages/checks/src/run.ts b/packages/checks/src/run.ts
index 900958a345..bbc839ee17 100644
--- a/packages/checks/src/run.ts
+++ b/packages/checks/src/run.ts
@@ -2,26 +2,27 @@ import { keyOf, loadBaseline } from "./baseline";
import type {
ConformanceCheck,
ModuleDir,
+ SourceFile,
StructureCheck,
Violation
} from "./check";
import { moduleShape } from "./conformance/module-shape";
+import { noDerivedPercentColumn } from "./conformance/no-derived-percent-column";
+import { noInlineFractionDigits } from "./conformance/no-inline-fraction-digits";
import { noLegacyRls } from "./conformance/no-legacy-rls";
import { noLocalTimezone } from "./conformance/no-local-timezone";
import { noNumericPrecision } from "./conformance/no-numeric-precision";
+import { noRawRounding } from "./conformance/no-raw-rounding";
import { noZeroConcurrency } from "./conformance/no-zero-concurrency";
-import {
- loadSqlFiles,
- migrationsDir,
- repoRoot,
- type SqlFile
-} from "./sources/migrations";
+import { loadSqlFiles, migrationsDir, repoRoot } from "./sources/migrations";
import { loadModules, modulesDir } from "./sources/modules";
import { loadServerFiles } from "./sources/server-files";
+import { loadTypescriptFiles } from "./sources/typescript";
export const CONFORMANCE_CHECKS: ConformanceCheck[] = [
noNumericPrecision,
- noLegacyRls
+ noLegacyRls,
+ noDerivedPercentColumn
];
/** Checks that run over server-side TS, not SQL migrations. */
@@ -30,12 +31,18 @@ export const SERVER_CHECKS: ConformanceCheck[] = [
noZeroConcurrency
];
+/** Numeric-precision checks that run over ALL app TS (client and server). */
+export const TS_CHECKS: ConformanceCheck[] = [
+ noRawRounding,
+ noInlineFractionDigits
+];
+
export const STRUCTURE_CHECKS: StructureCheck[] = [moduleShape];
export type Finding = { checkId: string; violation: Violation };
export function scanAll(
- files: SqlFile[],
+ files: SourceFile[],
checks: ConformanceCheck[] = CONFORMANCE_CHECKS
): Finding[] {
const out: Finding[] = [];
@@ -64,12 +71,13 @@ export function scanModules(
return out;
}
-/** Every finding across the real migrations (text) + modules (structure) + server TS under `root`. */
+/** Every finding across the real migrations (text) + modules (structure) + server TS + app TS under `root`. */
export function collectFindings(root: string = repoRoot()): Finding[] {
return [
...scanAll(loadSqlFiles(migrationsDir(root))),
...scanModules(loadModules(modulesDir(root))),
- ...scanAll(loadServerFiles(root), SERVER_CHECKS)
+ ...scanAll(loadServerFiles(root), SERVER_CHECKS),
+ ...scanAll(loadTypescriptFiles(root), TS_CHECKS)
];
}
diff --git a/packages/checks/src/scripts/check-clobbers.ts b/packages/checks/src/scripts/check-clobbers.ts
index ded8216b12..277ef990b6 100644
--- a/packages/checks/src/scripts/check-clobbers.ts
+++ b/packages/checks/src/scripts/check-clobbers.ts
@@ -1,5 +1,6 @@
import { execFileSync } from "node:child_process";
-import { findClobbers, type SourceFile } from "../clobber";
+import type { SourceFile } from "../check";
+import { findClobbers } from "../clobber";
import { repoRoot } from "../sources/migrations";
const MIGRATIONS = "packages/database/supabase/migrations";
diff --git a/packages/checks/src/sources/migrations.ts b/packages/checks/src/sources/migrations.ts
index 88e24eee5c..0c2ab2dedb 100644
--- a/packages/checks/src/sources/migrations.ts
+++ b/packages/checks/src/sources/migrations.ts
@@ -2,7 +2,7 @@ import { existsSync, readdirSync, readFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
-export type SqlFile = { file: string; contents: string };
+import type { SourceFile } from "../check";
const MIGRATIONS_REL = "packages/database/supabase/migrations";
@@ -24,7 +24,7 @@ export function migrationsDir(root: string): string {
return join(root, MIGRATIONS_REL);
}
-export function loadSqlFiles(dir: string): SqlFile[] {
+export function loadSqlFiles(dir: string): SourceFile[] {
return readdirSync(dir)
.filter((f) => f.endsWith(".sql"))
.sort()
diff --git a/packages/checks/src/sources/server-files.ts b/packages/checks/src/sources/server-files.ts
index afbcb8d77d..efd65dadc4 100644
--- a/packages/checks/src/sources/server-files.ts
+++ b/packages/checks/src/sources/server-files.ts
@@ -1,6 +1,6 @@
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
import { join, relative } from "node:path";
-import type { SqlFile } from "./migrations";
+import type { SourceFile } from "../check";
/**
* Server-side TypeScript that must derive calendar days through the `datetime`
@@ -111,7 +111,7 @@ export function maskClientCode(contents: string): string {
}
/** Every server-side TS file, as repo-relative { file, contents }. */
-export function loadServerFiles(root: string): SqlFile[] {
+export function loadServerFiles(root: string): SourceFile[] {
const paths: string[] = [];
for (const rel of SERVER_ROOTS) {
diff --git a/packages/checks/src/sources/typescript.ts b/packages/checks/src/sources/typescript.ts
new file mode 100644
index 0000000000..fa8cd9adbf
--- /dev/null
+++ b/packages/checks/src/sources/typescript.ts
@@ -0,0 +1,68 @@
+import { readdirSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+import type { SourceFile } from "../check";
+
+// Directories the numeric-precision checks cover: everywhere app code does
+// arithmetic or builds number formatters. The two image functions are pure
+// binary plumbing and the resizers' `Math.round` is pixel geometry.
+const TYPESCRIPT_ROOTS = [
+ "apps/erp/app/components",
+ "apps/erp/app/hooks",
+ "apps/erp/app/modules",
+ "apps/erp/app/routes",
+ "apps/mes/app",
+ "packages/database/supabase/functions",
+ "packages/ee/src",
+ "packages/jobs/src",
+ "packages/documents/src/pdf",
+ "packages/documents/src/utils",
+ // Shared packages are in scope too: @carbon/utils is where the standard's own
+ // helpers live (a local `round` shadow hid here), and form/react own the
+ // number inputs whose formatOptions are part of the storage round-trip.
+ "packages/utils/src",
+ "packages/form/src",
+ "packages/react/src",
+ "packages/printing/src",
+ "packages/workflows/src"
+];
+
+const EXCLUDED_DIRS = new Set([
+ "node_modules",
+ "image-resizer",
+ "logo-resizer"
+]);
+
+const isTest = (name: string) =>
+ name.endsWith(".test.ts") ||
+ name.endsWith(".test.tsx") ||
+ name.endsWith(".spec.ts") ||
+ name.endsWith(".spec.tsx");
+
+const isTypescript = (name: string) =>
+ name.endsWith(".ts") || name.endsWith(".tsx");
+
+function walk(dir: string, out: SourceFile[], repoRootDir: string) {
+ // withFileTypes so the directory read already tells us what each entry is —
+ // a stat() per entry over the whole app tree is the bulk of this walk.
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ if (EXCLUDED_DIRS.has(entry.name)) continue;
+ const full = join(dir, entry.name);
+ if (entry.isDirectory()) {
+ walk(full, out, repoRootDir);
+ } else if (isTypescript(entry.name) && !isTest(entry.name)) {
+ out.push({
+ // Repo-relative path so baseline keys are machine-independent
+ file: full.slice(repoRootDir.length + 1),
+ contents: readFileSync(full, "utf8")
+ });
+ }
+ }
+}
+
+export function loadTypescriptFiles(root: string): SourceFile[] {
+ const out: SourceFile[] = [];
+ for (const dir of TYPESCRIPT_ROOTS) {
+ walk(join(root, dir), out, root);
+ }
+ return out;
+}
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 9e71d6ef05..029d79ba65 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -6330,6 +6330,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperationsWithDependencies.assemblyInstructionId"
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.inspectionDocumentId"
+ },
{
$ref: "#/parameters/rowFilter.jobOperationsWithDependencies.dependencies"
},
@@ -6530,6 +6533,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperationsWithDependencies.assemblyInstructionId"
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.inspectionDocumentId"
+ },
{
$ref: "#/parameters/rowFilter.jobOperationsWithDependencies.dependencies"
},
@@ -6684,6 +6690,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperationsWithDependencies.assemblyInstructionId"
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.inspectionDocumentId"
+ },
{
$ref: "#/parameters/rowFilter.jobOperationsWithDependencies.dependencies"
},
@@ -13227,6 +13236,12 @@ export default {
{
$ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.itemScrapPercentage"
},
+ {
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.substitutedFromItemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.substitutionFactor"
+ },
{
$ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.storageUnitName"
},
@@ -18714,9 +18729,6 @@ export default {
{
$ref: "#/parameters/rowFilter.jobs.scrapQuantity"
},
- {
- $ref: "#/parameters/rowFilter.jobs.productionQuantity"
- },
{
$ref: "#/parameters/rowFilter.jobs.quantityComplete"
},
@@ -18795,6 +18807,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobs.priority"
},
+ {
+ $ref: "#/parameters/rowFilter.jobs.productionQuantity"
+ },
{
$ref: "#/parameters/rowFilter.jobs.jobMakeMethodId"
},
@@ -27586,34 +27601,34 @@ export default {
$ref: "#/parameters/rowFilter.purchaseInvoiceLines.jobOperationId"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLines.unitPrice"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLines.accountId"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLines.extendedPrice"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLines.costCenterId"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLines.shippingCost"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLines.requiredDate"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLines.taxAmount"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLines.ownerId"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLines.totalAmount"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLines.sortOrder"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLines.accountId"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLines.unitPrice"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLines.costCenterId"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLines.extendedPrice"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLines.requiredDate"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLines.shippingCost"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLines.ownerId"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLines.taxAmount"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLines.sortOrder"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLines.totalAmount"
},
{
$ref: "#/parameters/rowFilter.purchaseInvoiceLines.thumbnailPath"
@@ -30279,6 +30294,9 @@ export default {
{
$ref: "#/parameters/rowFilter.itemLedgers.correctionOfItemLedgerId"
},
+ {
+ $ref: "#/parameters/rowFilter.itemLedgers.scrapReasonId"
+ },
{
$ref: "#/parameters/rowFilter.itemLedgers.isCorrection"
},
@@ -30378,6 +30396,9 @@ export default {
{
$ref: "#/parameters/rowFilter.supplierProcesses.updatedAt"
},
+ {
+ $ref: "#/parameters/rowFilter.supplierProcesses.tags"
+ },
{
$ref: "#/parameters/rowFilter.supplierProcesses.processName"
},
@@ -31398,9 +31419,6 @@ export default {
{
$ref: "#/parameters/rowFilter.job.scrapQuantity"
},
- {
- $ref: "#/parameters/rowFilter.job.productionQuantity"
- },
{
$ref: "#/parameters/rowFilter.job.quantityComplete"
},
@@ -31479,6 +31497,9 @@ export default {
{
$ref: "#/parameters/rowFilter.job.priority"
},
+ {
+ $ref: "#/parameters/rowFilter.job.productionQuantity"
+ },
{
$ref: "#/parameters/select"
},
@@ -31571,9 +31592,6 @@ export default {
{
$ref: "#/parameters/rowFilter.job.scrapQuantity"
},
- {
- $ref: "#/parameters/rowFilter.job.productionQuantity"
- },
{
$ref: "#/parameters/rowFilter.job.quantityComplete"
},
@@ -31652,6 +31670,9 @@ export default {
{
$ref: "#/parameters/rowFilter.job.priority"
},
+ {
+ $ref: "#/parameters/rowFilter.job.productionQuantity"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -31698,9 +31719,6 @@ export default {
{
$ref: "#/parameters/rowFilter.job.scrapQuantity"
},
- {
- $ref: "#/parameters/rowFilter.job.productionQuantity"
- },
{
$ref: "#/parameters/rowFilter.job.quantityComplete"
},
@@ -31779,6 +31797,9 @@ export default {
{
$ref: "#/parameters/rowFilter.job.priority"
},
+ {
+ $ref: "#/parameters/rowFilter.job.productionQuantity"
+ },
{
$ref: "#/parameters/body.job"
},
@@ -36493,37 +36514,37 @@ export default {
$ref: "#/parameters/rowFilter.purchaseOrderLine.promisedDate"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.unitPrice"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.accountId"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.extendedPrice"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.requiredDate"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.shippingCost"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.receivedDate"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.taxAmount"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.costCenterId"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.accountId"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.ownerId"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.requiredDate"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.sortOrder"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.receivedDate"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.supplierPartId"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.costCenterId"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.unitPrice"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.ownerId"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.extendedPrice"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.sortOrder"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.shippingCost"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.supplierPartId"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.taxAmount"
},
{
$ref: "#/parameters/select"
@@ -36702,37 +36723,37 @@ export default {
$ref: "#/parameters/rowFilter.purchaseOrderLine.promisedDate"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.unitPrice"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.accountId"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.extendedPrice"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.requiredDate"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.shippingCost"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.receivedDate"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.taxAmount"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.costCenterId"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.accountId"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.ownerId"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.requiredDate"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.sortOrder"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.receivedDate"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.supplierPartId"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.costCenterId"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.unitPrice"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.ownerId"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.extendedPrice"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.sortOrder"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.shippingCost"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.supplierPartId"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.taxAmount"
},
{
$ref: "#/parameters/preferReturn"
@@ -36865,37 +36886,37 @@ export default {
$ref: "#/parameters/rowFilter.purchaseOrderLine.promisedDate"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.unitPrice"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.accountId"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.extendedPrice"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.requiredDate"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.shippingCost"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.receivedDate"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.taxAmount"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.costCenterId"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.accountId"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.ownerId"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.requiredDate"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.sortOrder"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.receivedDate"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.supplierPartId"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.costCenterId"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.unitPrice"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.ownerId"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.extendedPrice"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.sortOrder"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.shippingCost"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLine.supplierPartId"
+ $ref: "#/parameters/rowFilter.purchaseOrderLine.taxAmount"
},
{
$ref: "#/parameters/body.purchaseOrderLine"
@@ -44290,34 +44311,34 @@ export default {
$ref: "#/parameters/rowFilter.purchaseInvoiceLine.jobOperationId"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.unitPrice"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.accountId"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.extendedPrice"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.costCenterId"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.shippingCost"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.requiredDate"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.taxAmount"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.ownerId"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.totalAmount"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.sortOrder"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.accountId"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.unitPrice"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.costCenterId"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.extendedPrice"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.requiredDate"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.shippingCost"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.ownerId"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.taxAmount"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.sortOrder"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.totalAmount"
},
{
$ref: "#/parameters/select"
@@ -44472,34 +44493,34 @@ export default {
$ref: "#/parameters/rowFilter.purchaseInvoiceLine.jobOperationId"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.unitPrice"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.accountId"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.extendedPrice"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.costCenterId"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.shippingCost"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.requiredDate"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.taxAmount"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.ownerId"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.totalAmount"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.sortOrder"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.accountId"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.unitPrice"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.costCenterId"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.extendedPrice"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.requiredDate"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.shippingCost"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.ownerId"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.taxAmount"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.sortOrder"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.totalAmount"
},
{
$ref: "#/parameters/preferReturn"
@@ -44608,34 +44629,34 @@ export default {
$ref: "#/parameters/rowFilter.purchaseInvoiceLine.jobOperationId"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.unitPrice"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.accountId"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.extendedPrice"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.costCenterId"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.shippingCost"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.requiredDate"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.taxAmount"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.ownerId"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.totalAmount"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.sortOrder"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.accountId"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.unitPrice"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.costCenterId"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.extendedPrice"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.requiredDate"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.shippingCost"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.ownerId"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.taxAmount"
},
{
- $ref: "#/parameters/rowFilter.purchaseInvoiceLine.sortOrder"
+ $ref: "#/parameters/rowFilter.purchaseInvoiceLine.totalAmount"
},
{
$ref: "#/parameters/body.purchaseInvoiceLine"
@@ -46476,9 +46497,6 @@ export default {
{
$ref: "#/parameters/rowFilter.pickingListLine.quantityPicked"
},
- {
- $ref: "#/parameters/rowFilter.pickingListLine.outstandingQuantity"
- },
{
$ref: "#/parameters/rowFilter.pickingListLine.storageUnitId"
},
@@ -46509,6 +46527,9 @@ export default {
{
$ref: "#/parameters/rowFilter.pickingListLine.quantityReturned"
},
+ {
+ $ref: "#/parameters/rowFilter.pickingListLine.outstandingQuantity"
+ },
{
$ref: "#/parameters/select"
},
@@ -46592,9 +46613,76 @@ export default {
{
$ref: "#/parameters/rowFilter.pickingListLine.quantityPicked"
},
+ {
+ $ref: "#/parameters/rowFilter.pickingListLine.storageUnitId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pickingListLine.toStorageUnitId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pickingListLine.status"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pickingListLine.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pickingListLine.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pickingListLine.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pickingListLine.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pickingListLine.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pickingListLine.customFields"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pickingListLine.quantityReturned"
+ },
{
$ref: "#/parameters/rowFilter.pickingListLine.outstandingQuantity"
},
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["pickingListLine"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.pickingListLine.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pickingListLine.pickingListId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pickingListLine.jobId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pickingListLine.jobMaterialId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pickingListLine.jobOperationId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pickingListLine.itemId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pickingListLine.quantityToPick"
+ },
+ {
+ $ref: "#/parameters/rowFilter.pickingListLine.quantityPicked"
+ },
{
$ref: "#/parameters/rowFilter.pickingListLine.storageUnitId"
},
@@ -46625,76 +46713,9 @@ export default {
{
$ref: "#/parameters/rowFilter.pickingListLine.quantityReturned"
},
- {
- $ref: "#/parameters/preferReturn"
- }
- ],
- responses: {
- "204": {
- description: "No Content"
- }
- },
- tags: ["pickingListLine"]
- },
- patch: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.pickingListLine.id"
- },
- {
- $ref: "#/parameters/rowFilter.pickingListLine.pickingListId"
- },
- {
- $ref: "#/parameters/rowFilter.pickingListLine.jobId"
- },
- {
- $ref: "#/parameters/rowFilter.pickingListLine.jobMaterialId"
- },
- {
- $ref: "#/parameters/rowFilter.pickingListLine.jobOperationId"
- },
- {
- $ref: "#/parameters/rowFilter.pickingListLine.itemId"
- },
- {
- $ref: "#/parameters/rowFilter.pickingListLine.quantityToPick"
- },
- {
- $ref: "#/parameters/rowFilter.pickingListLine.quantityPicked"
- },
{
$ref: "#/parameters/rowFilter.pickingListLine.outstandingQuantity"
},
- {
- $ref: "#/parameters/rowFilter.pickingListLine.storageUnitId"
- },
- {
- $ref: "#/parameters/rowFilter.pickingListLine.toStorageUnitId"
- },
- {
- $ref: "#/parameters/rowFilter.pickingListLine.status"
- },
- {
- $ref: "#/parameters/rowFilter.pickingListLine.companyId"
- },
- {
- $ref: "#/parameters/rowFilter.pickingListLine.createdBy"
- },
- {
- $ref: "#/parameters/rowFilter.pickingListLine.createdAt"
- },
- {
- $ref: "#/parameters/rowFilter.pickingListLine.updatedBy"
- },
- {
- $ref: "#/parameters/rowFilter.pickingListLine.updatedAt"
- },
- {
- $ref: "#/parameters/rowFilter.pickingListLine.customFields"
- },
- {
- $ref: "#/parameters/rowFilter.pickingListLine.quantityReturned"
- },
{
$ref: "#/parameters/body.pickingListLine"
},
@@ -55315,34 +55336,34 @@ export default {
$ref: "#/parameters/rowFilter.salesOrderLines.quantityToInvoice"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLines.convertedAddOnCost"
+ $ref: "#/parameters/rowFilter.salesOrderLines.sentDate"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLines.convertedShippingCost"
+ $ref: "#/parameters/rowFilter.salesOrderLines.accountId"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLines.convertedUnitPrice"
+ $ref: "#/parameters/rowFilter.salesOrderLines.nonTaxableAddOnCost"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLines.sentDate"
+ $ref: "#/parameters/rowFilter.salesOrderLines.pricingRuleId"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLines.accountId"
+ $ref: "#/parameters/rowFilter.salesOrderLines.priceTrace"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLines.nonTaxableAddOnCost"
+ $ref: "#/parameters/rowFilter.salesOrderLines.sortOrder"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLines.convertedNonTaxableAddOnCost"
+ $ref: "#/parameters/rowFilter.salesOrderLines.convertedAddOnCost"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLines.pricingRuleId"
+ $ref: "#/parameters/rowFilter.salesOrderLines.convertedShippingCost"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLines.priceTrace"
+ $ref: "#/parameters/rowFilter.salesOrderLines.convertedUnitPrice"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLines.sortOrder"
+ $ref: "#/parameters/rowFilter.salesOrderLines.convertedNonTaxableAddOnCost"
},
{
$ref: "#/parameters/rowFilter.salesOrderLines.itemReadableId"
@@ -62506,31 +62527,31 @@ export default {
$ref: "#/parameters/rowFilter.quoteLinePrice.shippingCost"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.convertedUnitPrice"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.categoryMarkups"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.netUnitPrice"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.companyId"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.netExtendedPrice"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.priceSource"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.convertedNetUnitPrice"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.convertedUnitPrice"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.convertedNetExtendedPrice"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.netUnitPrice"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.convertedShippingCost"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.netExtendedPrice"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.categoryMarkups"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.convertedNetUnitPrice"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.companyId"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.convertedNetExtendedPrice"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.priceSource"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.convertedShippingCost"
},
{
$ref: "#/parameters/select"
@@ -62628,31 +62649,31 @@ export default {
$ref: "#/parameters/rowFilter.quoteLinePrice.shippingCost"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.convertedUnitPrice"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.categoryMarkups"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.netUnitPrice"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.companyId"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.netExtendedPrice"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.priceSource"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.convertedNetUnitPrice"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.convertedUnitPrice"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.convertedNetExtendedPrice"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.netUnitPrice"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.convertedShippingCost"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.netExtendedPrice"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.categoryMarkups"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.convertedNetUnitPrice"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.companyId"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.convertedNetExtendedPrice"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.priceSource"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.convertedShippingCost"
},
{
$ref: "#/parameters/preferReturn"
@@ -62704,31 +62725,31 @@ export default {
$ref: "#/parameters/rowFilter.quoteLinePrice.shippingCost"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.convertedUnitPrice"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.categoryMarkups"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.netUnitPrice"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.companyId"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.netExtendedPrice"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.priceSource"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.convertedNetUnitPrice"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.convertedUnitPrice"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.convertedNetExtendedPrice"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.netUnitPrice"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.convertedShippingCost"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.netExtendedPrice"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.categoryMarkups"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.convertedNetUnitPrice"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.companyId"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.convertedNetExtendedPrice"
},
{
- $ref: "#/parameters/rowFilter.quoteLinePrice.priceSource"
+ $ref: "#/parameters/rowFilter.quoteLinePrice.convertedShippingCost"
},
{
$ref: "#/parameters/body.quoteLinePrice"
@@ -63756,6 +63777,9 @@ export default {
{
$ref: "#/parameters/rowFilter.supplierQuoteLinePrice.taxPercent"
},
+ {
+ $ref: "#/parameters/rowFilter.supplierQuoteLinePrice.companyId"
+ },
{
$ref: "#/parameters/rowFilter.supplierQuoteLinePrice.unitPrice"
},
@@ -63768,9 +63792,6 @@ export default {
{
$ref: "#/parameters/rowFilter.supplierQuoteLinePrice.taxAmount"
},
- {
- $ref: "#/parameters/rowFilter.supplierQuoteLinePrice.companyId"
- },
{
$ref: "#/parameters/select"
},
@@ -63872,6 +63893,9 @@ export default {
{
$ref: "#/parameters/rowFilter.supplierQuoteLinePrice.taxPercent"
},
+ {
+ $ref: "#/parameters/rowFilter.supplierQuoteLinePrice.companyId"
+ },
{
$ref: "#/parameters/rowFilter.supplierQuoteLinePrice.unitPrice"
},
@@ -63884,9 +63908,6 @@ export default {
{
$ref: "#/parameters/rowFilter.supplierQuoteLinePrice.taxAmount"
},
- {
- $ref: "#/parameters/rowFilter.supplierQuoteLinePrice.companyId"
- },
{
$ref: "#/parameters/preferReturn"
}
@@ -63942,6 +63963,9 @@ export default {
{
$ref: "#/parameters/rowFilter.supplierQuoteLinePrice.taxPercent"
},
+ {
+ $ref: "#/parameters/rowFilter.supplierQuoteLinePrice.companyId"
+ },
{
$ref: "#/parameters/rowFilter.supplierQuoteLinePrice.unitPrice"
},
@@ -63954,9 +63978,6 @@ export default {
{
$ref: "#/parameters/rowFilter.supplierQuoteLinePrice.taxAmount"
},
- {
- $ref: "#/parameters/rowFilter.supplierQuoteLinePrice.companyId"
- },
{
$ref: "#/parameters/body.supplierQuoteLinePrice"
},
@@ -66192,6 +66213,12 @@ export default {
{
$ref: "#/parameters/rowFilter.quoteOperationsWithMakeMethods.procedureId"
},
+ {
+ $ref: "#/parameters/rowFilter.quoteOperationsWithMakeMethods.assemblyInstructionId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteOperationsWithMakeMethods.inspectionDocumentId"
+ },
{
$ref: "#/parameters/select"
},
@@ -66454,34 +66481,34 @@ export default {
$ref: "#/parameters/rowFilter.salesOrderLine.quantityToInvoice"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.convertedAddOnCost"
+ $ref: "#/parameters/rowFilter.salesOrderLine.sentDate"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.convertedShippingCost"
+ $ref: "#/parameters/rowFilter.salesOrderLine.accountId"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.convertedUnitPrice"
+ $ref: "#/parameters/rowFilter.salesOrderLine.nonTaxableAddOnCost"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.sentDate"
+ $ref: "#/parameters/rowFilter.salesOrderLine.pricingRuleId"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.accountId"
+ $ref: "#/parameters/rowFilter.salesOrderLine.priceTrace"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.nonTaxableAddOnCost"
+ $ref: "#/parameters/rowFilter.salesOrderLine.sortOrder"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.convertedNonTaxableAddOnCost"
+ $ref: "#/parameters/rowFilter.salesOrderLine.convertedAddOnCost"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.pricingRuleId"
+ $ref: "#/parameters/rowFilter.salesOrderLine.convertedShippingCost"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.priceTrace"
+ $ref: "#/parameters/rowFilter.salesOrderLine.convertedUnitPrice"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.sortOrder"
+ $ref: "#/parameters/rowFilter.salesOrderLine.convertedNonTaxableAddOnCost"
},
{
$ref: "#/parameters/select"
@@ -66645,34 +66672,34 @@ export default {
$ref: "#/parameters/rowFilter.salesOrderLine.quantityToInvoice"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.convertedAddOnCost"
+ $ref: "#/parameters/rowFilter.salesOrderLine.sentDate"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.convertedShippingCost"
+ $ref: "#/parameters/rowFilter.salesOrderLine.accountId"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.convertedUnitPrice"
+ $ref: "#/parameters/rowFilter.salesOrderLine.nonTaxableAddOnCost"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.sentDate"
+ $ref: "#/parameters/rowFilter.salesOrderLine.pricingRuleId"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.accountId"
+ $ref: "#/parameters/rowFilter.salesOrderLine.priceTrace"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.nonTaxableAddOnCost"
+ $ref: "#/parameters/rowFilter.salesOrderLine.sortOrder"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.convertedNonTaxableAddOnCost"
+ $ref: "#/parameters/rowFilter.salesOrderLine.convertedAddOnCost"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.pricingRuleId"
+ $ref: "#/parameters/rowFilter.salesOrderLine.convertedShippingCost"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.priceTrace"
+ $ref: "#/parameters/rowFilter.salesOrderLine.convertedUnitPrice"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.sortOrder"
+ $ref: "#/parameters/rowFilter.salesOrderLine.convertedNonTaxableAddOnCost"
},
{
$ref: "#/parameters/preferReturn"
@@ -66790,34 +66817,34 @@ export default {
$ref: "#/parameters/rowFilter.salesOrderLine.quantityToInvoice"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.convertedAddOnCost"
+ $ref: "#/parameters/rowFilter.salesOrderLine.sentDate"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.convertedShippingCost"
+ $ref: "#/parameters/rowFilter.salesOrderLine.accountId"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.convertedUnitPrice"
+ $ref: "#/parameters/rowFilter.salesOrderLine.nonTaxableAddOnCost"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.sentDate"
+ $ref: "#/parameters/rowFilter.salesOrderLine.pricingRuleId"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.accountId"
+ $ref: "#/parameters/rowFilter.salesOrderLine.priceTrace"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.nonTaxableAddOnCost"
+ $ref: "#/parameters/rowFilter.salesOrderLine.sortOrder"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.convertedNonTaxableAddOnCost"
+ $ref: "#/parameters/rowFilter.salesOrderLine.convertedAddOnCost"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.pricingRuleId"
+ $ref: "#/parameters/rowFilter.salesOrderLine.convertedShippingCost"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.priceTrace"
+ $ref: "#/parameters/rowFilter.salesOrderLine.convertedUnitPrice"
},
{
- $ref: "#/parameters/rowFilter.salesOrderLine.sortOrder"
+ $ref: "#/parameters/rowFilter.salesOrderLine.convertedNonTaxableAddOnCost"
},
{
$ref: "#/parameters/body.salesOrderLine"
@@ -72700,37 +72727,37 @@ export default {
$ref: "#/parameters/rowFilter.purchaseOrderLines.promisedDate"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLines.unitPrice"
+ $ref: "#/parameters/rowFilter.purchaseOrderLines.accountId"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLines.extendedPrice"
+ $ref: "#/parameters/rowFilter.purchaseOrderLines.requiredDate"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLines.shippingCost"
+ $ref: "#/parameters/rowFilter.purchaseOrderLines.receivedDate"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLines.taxAmount"
+ $ref: "#/parameters/rowFilter.purchaseOrderLines.costCenterId"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLines.accountId"
+ $ref: "#/parameters/rowFilter.purchaseOrderLines.ownerId"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLines.requiredDate"
+ $ref: "#/parameters/rowFilter.purchaseOrderLines.sortOrder"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLines.receivedDate"
+ $ref: "#/parameters/rowFilter.purchaseOrderLines.supplierPartId"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLines.costCenterId"
+ $ref: "#/parameters/rowFilter.purchaseOrderLines.unitPrice"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLines.ownerId"
+ $ref: "#/parameters/rowFilter.purchaseOrderLines.extendedPrice"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLines.sortOrder"
+ $ref: "#/parameters/rowFilter.purchaseOrderLines.shippingCost"
},
{
- $ref: "#/parameters/rowFilter.purchaseOrderLines.supplierPartId"
+ $ref: "#/parameters/rowFilter.purchaseOrderLines.taxAmount"
},
{
$ref: "#/parameters/rowFilter.purchaseOrderLines.supplierPartIdFromSupplier"
@@ -77298,6 +77325,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperationsWithMakeMethods.assemblyInstructionId"
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithMakeMethods.inspectionDocumentId"
+ },
{
$ref: "#/parameters/select"
},
@@ -78774,6 +78804,15 @@ export default {
{
$ref: "#/parameters/rowFilter.quoteLinePrices.configuration"
},
+ {
+ $ref: "#/parameters/rowFilter.quoteLinePrices.pricingRuleId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteLinePrices.priceTrace"
+ },
+ {
+ $ref: "#/parameters/rowFilter.quoteLinePrices.sortOrder"
+ },
{
$ref: "#/parameters/rowFilter.quoteLinePrices.itemReadableId"
},
@@ -84789,6 +84828,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.returnPickedMaterialTiming"
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.showCurrencyTrailingZeros"
+ },
{
$ref: "#/parameters/select"
},
@@ -84983,6 +85025,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.returnPickedMaterialTiming"
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.showCurrencyTrailingZeros"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -85131,6 +85176,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.returnPickedMaterialTiming"
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.showCurrencyTrailingZeros"
+ },
{
$ref: "#/parameters/body.companySettings"
},
@@ -100698,6 +100746,12 @@ export default {
format: "text",
type: "string"
},
+ inspectionDocumentId: {
+ description:
+ "Note:\nThis is a Foreign Key to `inspectionDocument.id`.<fk table='inspectionDocument' column='id'/>",
+ format: "text",
+ type: "string"
+ },
dependencies: {
format: "text[]",
items: {
@@ -103881,6 +103935,14 @@ export default {
format: "numeric",
type: "number"
},
+ substitutedFromItemId: {
+ format: "text",
+ type: "string"
+ },
+ substitutionFactor: {
+ format: "numeric",
+ type: "number"
+ },
storageUnitName: {
format: "text",
type: "string"
@@ -106548,10 +106610,6 @@ export default {
format: "numeric",
type: "number"
},
- productionQuantity: {
- format: "numeric",
- type: "number"
- },
quantityComplete: {
format: "numeric",
type: "number"
@@ -106672,6 +106730,10 @@ export default {
format: "double precision",
type: "number"
},
+ productionQuantity: {
+ format: "numeric",
+ type: "number"
+ },
jobMakeMethodId: {
description: "Note:\nThis is a Primary Key.<pk/>",
format: "text",
@@ -110937,26 +110999,6 @@ export default {
format: "text",
type: "string"
},
- unitPrice: {
- format: "numeric",
- type: "number"
- },
- extendedPrice: {
- format: "numeric",
- type: "number"
- },
- shippingCost: {
- format: "numeric",
- type: "number"
- },
- taxAmount: {
- format: "numeric",
- type: "number"
- },
- totalAmount: {
- format: "numeric",
- type: "number"
- },
accountId: {
description:
"Note:\nThis is a Foreign Key to `account.id`.<fk table='account' column='id'/>",
@@ -110983,6 +111025,26 @@ export default {
format: "double precision",
type: "number"
},
+ unitPrice: {
+ format: "numeric",
+ type: "number"
+ },
+ extendedPrice: {
+ format: "numeric",
+ type: "number"
+ },
+ shippingCost: {
+ format: "numeric",
+ type: "number"
+ },
+ taxAmount: {
+ format: "numeric",
+ type: "number"
+ },
+ totalAmount: {
+ format: "numeric",
+ type: "number"
+ },
thumbnailPath: {
format: "text",
type: "string"
@@ -112150,6 +112212,12 @@ export default {
format: "text",
type: "string"
},
+ scrapReasonId: {
+ description:
+ "Note:\nThis is a Foreign Key to `scrapReason.id`.<fk table='scrapReason' column='id'/>",
+ format: "text",
+ type: "string"
+ },
isCorrection: {
format: "boolean",
type: "boolean"
@@ -112247,6 +112315,13 @@ export default {
format: "timestamp with time zone",
type: "string"
},
+ tags: {
+ format: "text[]",
+ items: {
+ type: "string"
+ },
+ type: "array"
+ },
processName: {
format: "text",
type: "string"
@@ -112736,10 +112811,6 @@ export default {
format: "numeric",
type: "number"
},
- productionQuantity: {
- format: "numeric",
- type: "number"
- },
quantityComplete: {
default: 0,
format: "numeric",
@@ -112864,6 +112935,10 @@ export default {
default: 1,
format: "double precision",
type: "number"
+ },
+ productionQuantity: {
+ format: "numeric",
+ type: "number"
}
},
type: "object"
@@ -114997,6 +115072,7 @@ export default {
type: "number"
},
taxPercent: {
+ default: 0,
format: "numeric",
type: "number"
},
@@ -115020,22 +115096,6 @@ export default {
format: "date",
type: "string"
},
- unitPrice: {
- format: "numeric",
- type: "number"
- },
- extendedPrice: {
- format: "numeric",
- type: "number"
- },
- shippingCost: {
- format: "numeric",
- type: "number"
- },
- taxAmount: {
- format: "numeric",
- type: "number"
- },
accountId: {
description:
"Note:\nThis is a Foreign Key to `account.id`.<fk table='account' column='id'/>",
@@ -115070,6 +115130,22 @@ export default {
supplierPartId: {
format: "text",
type: "string"
+ },
+ unitPrice: {
+ format: "numeric",
+ type: "number"
+ },
+ extendedPrice: {
+ format: "numeric",
+ type: "number"
+ },
+ shippingCost: {
+ format: "numeric",
+ type: "number"
+ },
+ taxAmount: {
+ format: "numeric",
+ type: "number"
}
},
type: "object"
@@ -118740,6 +118816,7 @@ export default {
type: "number"
},
taxPercent: {
+ default: 0,
format: "numeric",
type: "number"
},
@@ -118749,26 +118826,6 @@ export default {
format: "text",
type: "string"
},
- unitPrice: {
- format: "numeric",
- type: "number"
- },
- extendedPrice: {
- format: "numeric",
- type: "number"
- },
- shippingCost: {
- format: "numeric",
- type: "number"
- },
- taxAmount: {
- format: "numeric",
- type: "number"
- },
- totalAmount: {
- format: "numeric",
- type: "number"
- },
accountId: {
description:
"Note:\nThis is a Foreign Key to `account.id`.<fk table='account' column='id'/>",
@@ -118795,6 +118852,26 @@ export default {
default: 1,
format: "double precision",
type: "number"
+ },
+ unitPrice: {
+ format: "numeric",
+ type: "number"
+ },
+ extendedPrice: {
+ format: "numeric",
+ type: "number"
+ },
+ shippingCost: {
+ format: "numeric",
+ type: "number"
+ },
+ taxAmount: {
+ format: "numeric",
+ type: "number"
+ },
+ totalAmount: {
+ format: "numeric",
+ type: "number"
}
},
type: "object"
@@ -119922,10 +119999,6 @@ export default {
format: "numeric",
type: "number"
},
- outstandingQuantity: {
- format: "numeric",
- type: "number"
- },
storageUnitId: {
description:
"Note:\nThis is a Foreign Key to `storageUnit.id`.<fk table='storageUnit' column='id'/>",
@@ -119978,6 +120051,10 @@ export default {
default: 0,
format: "numeric",
type: "number"
+ },
+ outstandingQuantity: {
+ format: "numeric",
+ type: "number"
}
},
type: "object"
@@ -123540,18 +123617,6 @@ export default {
format: "numeric",
type: "number"
},
- convertedAddOnCost: {
- format: "numeric",
- type: "number"
- },
- convertedShippingCost: {
- format: "numeric",
- type: "number"
- },
- convertedUnitPrice: {
- format: "numeric",
- type: "number"
- },
sentDate: {
format: "date",
type: "string"
@@ -123566,10 +123631,6 @@ export default {
format: "numeric",
type: "number"
},
- convertedNonTaxableAddOnCost: {
- format: "numeric",
- type: "number"
- },
pricingRuleId: {
description:
"Note:\nThis is a Foreign Key to `pricingRule.id`.<fk table='pricingRule' column='id'/>",
@@ -123583,6 +123644,22 @@ export default {
format: "double precision",
type: "number"
},
+ convertedAddOnCost: {
+ format: "numeric",
+ type: "number"
+ },
+ convertedShippingCost: {
+ format: "numeric",
+ type: "number"
+ },
+ convertedUnitPrice: {
+ format: "numeric",
+ type: "number"
+ },
+ convertedNonTaxableAddOnCost: {
+ format: "numeric",
+ type: "number"
+ },
itemReadableId: {
format: "text",
type: "string"
@@ -127370,6 +127447,18 @@ export default {
format: "numeric",
type: "number"
},
+ categoryMarkups: {
+ format: "jsonb"
+ },
+ companyId: {
+ format: "text",
+ type: "string"
+ },
+ priceSource: {
+ default: "system",
+ format: "text",
+ type: "string"
+ },
convertedUnitPrice: {
format: "numeric",
type: "number"
@@ -127393,18 +127482,6 @@ export default {
convertedShippingCost: {
format: "numeric",
type: "number"
- },
- categoryMarkups: {
- format: "jsonb"
- },
- companyId: {
- format: "text",
- type: "string"
- },
- priceSource: {
- default: "system",
- format: "text",
- type: "string"
}
},
type: "object"
@@ -128005,9 +128082,14 @@ export default {
type: "number"
},
taxPercent: {
+ default: 0,
format: "numeric",
type: "number"
},
+ companyId: {
+ format: "text",
+ type: "string"
+ },
unitPrice: {
format: "numeric",
type: "number"
@@ -128023,10 +128105,6 @@ export default {
taxAmount: {
format: "numeric",
type: "number"
- },
- companyId: {
- format: "text",
- type: "string"
}
},
type: "object"
@@ -129181,6 +129259,18 @@ export default {
"Note:\nThis is a Foreign Key to `procedure.id`.<fk table='procedure' column='id'/>",
format: "text",
type: "string"
+ },
+ assemblyInstructionId: {
+ description:
+ "Note:\nThis is a Foreign Key to `assemblyInstruction.id`.<fk table='assemblyInstruction' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ inspectionDocumentId: {
+ description:
+ "Note:\nThis is a Foreign Key to `inspectionDocument.id`.<fk table='inspectionDocument' column='id'/>",
+ format: "text",
+ type: "string"
}
},
type: "object"
@@ -129395,18 +129485,6 @@ export default {
format: "numeric",
type: "number"
},
- convertedAddOnCost: {
- format: "numeric",
- type: "number"
- },
- convertedShippingCost: {
- format: "numeric",
- type: "number"
- },
- convertedUnitPrice: {
- format: "numeric",
- type: "number"
- },
sentDate: {
format: "date",
type: "string"
@@ -129422,10 +129500,6 @@ export default {
format: "numeric",
type: "number"
},
- convertedNonTaxableAddOnCost: {
- format: "numeric",
- type: "number"
- },
pricingRuleId: {
description:
"Note:\nThis is a Foreign Key to `pricingRule.id`.<fk table='pricingRule' column='id'/>",
@@ -129439,6 +129513,22 @@ export default {
default: 1,
format: "double precision",
type: "number"
+ },
+ convertedAddOnCost: {
+ format: "numeric",
+ type: "number"
+ },
+ convertedShippingCost: {
+ format: "numeric",
+ type: "number"
+ },
+ convertedUnitPrice: {
+ format: "numeric",
+ type: "number"
+ },
+ convertedNonTaxableAddOnCost: {
+ format: "numeric",
+ type: "number"
}
},
type: "object"
@@ -132095,22 +132185,6 @@ export default {
format: "date",
type: "string"
},
- unitPrice: {
- format: "numeric",
- type: "number"
- },
- extendedPrice: {
- format: "numeric",
- type: "number"
- },
- shippingCost: {
- format: "numeric",
- type: "number"
- },
- taxAmount: {
- format: "numeric",
- type: "number"
- },
accountId: {
description:
"Note:\nThis is a Foreign Key to `account.id`.<fk table='account' column='id'/>",
@@ -132145,6 +132219,22 @@ export default {
format: "text",
type: "string"
},
+ unitPrice: {
+ format: "numeric",
+ type: "number"
+ },
+ extendedPrice: {
+ format: "numeric",
+ type: "number"
+ },
+ shippingCost: {
+ format: "numeric",
+ type: "number"
+ },
+ taxAmount: {
+ format: "numeric",
+ type: "number"
+ },
supplierPartIdFromSupplier: {
format: "text",
type: "string"
@@ -134548,6 +134638,12 @@ export default {
"Note:\nThis is a Foreign Key to `assemblyInstruction.id`.<fk table='assemblyInstruction' column='id'/>",
format: "text",
type: "string"
+ },
+ inspectionDocumentId: {
+ description:
+ "Note:\nThis is a Foreign Key to `inspectionDocument.id`.<fk table='inspectionDocument' column='id'/>",
+ format: "text",
+ type: "string"
}
},
type: "object"
@@ -135469,6 +135565,19 @@ export default {
configuration: {
format: "jsonb"
},
+ pricingRuleId: {
+ description:
+ "Note:\nThis is a Foreign Key to `pricingRule.id`.<fk table='pricingRule' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ priceTrace: {
+ format: "jsonb"
+ },
+ sortOrder: {
+ format: "double precision",
+ type: "number"
+ },
itemReadableId: {
format: "text",
type: "string"
@@ -137993,7 +138102,8 @@ export default {
"autoSelectMaterialWithoutPickingList",
"incompletePickingListPolicy",
"includeMaterialsOnTraveler",
- "returnPickedMaterialTiming"
+ "returnPickedMaterialTiming",
+ "showCurrencyTrailingZeros"
],
properties: {
id: {
@@ -138239,6 +138349,11 @@ export default {
default: "job",
format: "text",
type: "string"
+ },
+ showCurrencyTrailingZeros: {
+ default: true,
+ format: "boolean",
+ type: "boolean"
}
},
type: "object"
@@ -142179,6 +142294,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.jobOperationsWithDependencies.inspectionDocumentId": {
+ name: "inspectionDocumentId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"rowFilter.jobOperationsWithDependencies.dependencies": {
name: "dependencies",
required: false,
@@ -145665,6 +145786,18 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.jobMaterialWithMakeMethodId.substitutedFromItemId": {
+ name: "substitutedFromItemId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.jobMaterialWithMakeMethodId.substitutionFactor": {
+ name: "substitutionFactor",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"rowFilter.jobMaterialWithMakeMethodId.storageUnitName": {
name: "storageUnitName",
required: false,
@@ -148704,12 +148837,6 @@ export default {
in: "query",
type: "string"
},
- "rowFilter.jobs.productionQuantity": {
- name: "productionQuantity",
- required: false,
- in: "query",
- type: "string"
- },
"rowFilter.jobs.quantityComplete": {
name: "quantityComplete",
required: false,
@@ -148866,6 +148993,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.jobs.productionQuantity": {
+ name: "productionQuantity",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"rowFilter.jobs.jobMakeMethodId": {
name: "jobMakeMethodId",
required: false,
@@ -153644,62 +153777,62 @@ export default {
in: "query",
type: "string"
},
- "rowFilter.purchaseInvoiceLines.unitPrice": {
- name: "unitPrice",
+ "rowFilter.purchaseInvoiceLines.accountId": {
+ name: "accountId",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseInvoiceLines.extendedPrice": {
- name: "extendedPrice",
+ "rowFilter.purchaseInvoiceLines.costCenterId": {
+ name: "costCenterId",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseInvoiceLines.shippingCost": {
- name: "shippingCost",
+ "rowFilter.purchaseInvoiceLines.requiredDate": {
+ name: "requiredDate",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseInvoiceLines.taxAmount": {
- name: "taxAmount",
+ "rowFilter.purchaseInvoiceLines.ownerId": {
+ name: "ownerId",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseInvoiceLines.totalAmount": {
- name: "totalAmount",
+ "rowFilter.purchaseInvoiceLines.sortOrder": {
+ name: "sortOrder",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseInvoiceLines.accountId": {
- name: "accountId",
+ "rowFilter.purchaseInvoiceLines.unitPrice": {
+ name: "unitPrice",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseInvoiceLines.costCenterId": {
- name: "costCenterId",
+ "rowFilter.purchaseInvoiceLines.extendedPrice": {
+ name: "extendedPrice",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseInvoiceLines.requiredDate": {
- name: "requiredDate",
+ "rowFilter.purchaseInvoiceLines.shippingCost": {
+ name: "shippingCost",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseInvoiceLines.ownerId": {
- name: "ownerId",
+ "rowFilter.purchaseInvoiceLines.taxAmount": {
+ name: "taxAmount",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseInvoiceLines.sortOrder": {
- name: "sortOrder",
+ "rowFilter.purchaseInvoiceLines.totalAmount": {
+ name: "totalAmount",
required: false,
in: "query",
type: "string"
@@ -155036,6 +155169,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.itemLedgers.scrapReasonId": {
+ name: "scrapReasonId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"rowFilter.itemLedgers.isCorrection": {
name: "isCorrection",
required: false,
@@ -155159,6 +155298,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.supplierProcesses.tags": {
+ name: "tags",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"rowFilter.supplierProcesses.processName": {
name: "processName",
required: false,
@@ -155642,12 +155787,6 @@ export default {
in: "query",
type: "string"
},
- "rowFilter.job.productionQuantity": {
- name: "productionQuantity",
- required: false,
- in: "query",
- type: "string"
- },
"rowFilter.job.quantityComplete": {
name: "quantityComplete",
required: false,
@@ -155804,6 +155943,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.job.productionQuantity": {
+ name: "productionQuantity",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.changeOrderAffectedItem": {
name: "changeOrderAffectedItem",
description: "changeOrderAffectedItem",
@@ -158201,68 +158346,68 @@ export default {
in: "query",
type: "string"
},
- "rowFilter.purchaseOrderLine.unitPrice": {
- name: "unitPrice",
+ "rowFilter.purchaseOrderLine.accountId": {
+ name: "accountId",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseOrderLine.extendedPrice": {
- name: "extendedPrice",
+ "rowFilter.purchaseOrderLine.requiredDate": {
+ name: "requiredDate",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseOrderLine.shippingCost": {
- name: "shippingCost",
+ "rowFilter.purchaseOrderLine.receivedDate": {
+ name: "receivedDate",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseOrderLine.taxAmount": {
- name: "taxAmount",
+ "rowFilter.purchaseOrderLine.costCenterId": {
+ name: "costCenterId",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseOrderLine.accountId": {
- name: "accountId",
+ "rowFilter.purchaseOrderLine.ownerId": {
+ name: "ownerId",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseOrderLine.requiredDate": {
- name: "requiredDate",
+ "rowFilter.purchaseOrderLine.sortOrder": {
+ name: "sortOrder",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseOrderLine.receivedDate": {
- name: "receivedDate",
+ "rowFilter.purchaseOrderLine.supplierPartId": {
+ name: "supplierPartId",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseOrderLine.costCenterId": {
- name: "costCenterId",
+ "rowFilter.purchaseOrderLine.unitPrice": {
+ name: "unitPrice",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseOrderLine.ownerId": {
- name: "ownerId",
+ "rowFilter.purchaseOrderLine.extendedPrice": {
+ name: "extendedPrice",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseOrderLine.sortOrder": {
- name: "sortOrder",
+ "rowFilter.purchaseOrderLine.shippingCost": {
+ name: "shippingCost",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseOrderLine.supplierPartId": {
- name: "supplierPartId",
+ "rowFilter.purchaseOrderLine.taxAmount": {
+ name: "taxAmount",
required: false,
in: "query",
type: "string"
@@ -162175,62 +162320,62 @@ export default {
in: "query",
type: "string"
},
- "rowFilter.purchaseInvoiceLine.unitPrice": {
- name: "unitPrice",
+ "rowFilter.purchaseInvoiceLine.accountId": {
+ name: "accountId",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseInvoiceLine.extendedPrice": {
- name: "extendedPrice",
+ "rowFilter.purchaseInvoiceLine.costCenterId": {
+ name: "costCenterId",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseInvoiceLine.shippingCost": {
- name: "shippingCost",
+ "rowFilter.purchaseInvoiceLine.requiredDate": {
+ name: "requiredDate",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseInvoiceLine.taxAmount": {
- name: "taxAmount",
+ "rowFilter.purchaseInvoiceLine.ownerId": {
+ name: "ownerId",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseInvoiceLine.totalAmount": {
- name: "totalAmount",
+ "rowFilter.purchaseInvoiceLine.sortOrder": {
+ name: "sortOrder",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseInvoiceLine.accountId": {
- name: "accountId",
+ "rowFilter.purchaseInvoiceLine.unitPrice": {
+ name: "unitPrice",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseInvoiceLine.costCenterId": {
- name: "costCenterId",
+ "rowFilter.purchaseInvoiceLine.extendedPrice": {
+ name: "extendedPrice",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseInvoiceLine.requiredDate": {
- name: "requiredDate",
+ "rowFilter.purchaseInvoiceLine.shippingCost": {
+ name: "shippingCost",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseInvoiceLine.ownerId": {
- name: "ownerId",
+ "rowFilter.purchaseInvoiceLine.taxAmount": {
+ name: "taxAmount",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseInvoiceLine.sortOrder": {
- name: "sortOrder",
+ "rowFilter.purchaseInvoiceLine.totalAmount": {
+ name: "totalAmount",
required: false,
in: "query",
type: "string"
@@ -163582,12 +163727,6 @@ export default {
in: "query",
type: "string"
},
- "rowFilter.pickingListLine.outstandingQuantity": {
- name: "outstandingQuantity",
- required: false,
- in: "query",
- type: "string"
- },
"rowFilter.pickingListLine.storageUnitId": {
name: "storageUnitId",
required: false,
@@ -163648,6 +163787,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.pickingListLine.outstandingQuantity": {
+ name: "outstandingQuantity",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.storageType": {
name: "storageType",
description: "storageType",
@@ -167579,62 +167724,62 @@ export default {
in: "query",
type: "string"
},
- "rowFilter.salesOrderLines.convertedAddOnCost": {
- name: "convertedAddOnCost",
+ "rowFilter.salesOrderLines.sentDate": {
+ name: "sentDate",
required: false,
in: "query",
type: "string"
},
- "rowFilter.salesOrderLines.convertedShippingCost": {
- name: "convertedShippingCost",
+ "rowFilter.salesOrderLines.accountId": {
+ name: "accountId",
required: false,
in: "query",
type: "string"
},
- "rowFilter.salesOrderLines.convertedUnitPrice": {
- name: "convertedUnitPrice",
+ "rowFilter.salesOrderLines.nonTaxableAddOnCost": {
+ name: "nonTaxableAddOnCost",
required: false,
in: "query",
type: "string"
},
- "rowFilter.salesOrderLines.sentDate": {
- name: "sentDate",
+ "rowFilter.salesOrderLines.pricingRuleId": {
+ name: "pricingRuleId",
required: false,
in: "query",
type: "string"
},
- "rowFilter.salesOrderLines.accountId": {
- name: "accountId",
+ "rowFilter.salesOrderLines.priceTrace": {
+ name: "priceTrace",
required: false,
in: "query",
type: "string"
},
- "rowFilter.salesOrderLines.nonTaxableAddOnCost": {
- name: "nonTaxableAddOnCost",
+ "rowFilter.salesOrderLines.sortOrder": {
+ name: "sortOrder",
required: false,
in: "query",
type: "string"
},
- "rowFilter.salesOrderLines.convertedNonTaxableAddOnCost": {
- name: "convertedNonTaxableAddOnCost",
+ "rowFilter.salesOrderLines.convertedAddOnCost": {
+ name: "convertedAddOnCost",
required: false,
in: "query",
type: "string"
},
- "rowFilter.salesOrderLines.pricingRuleId": {
- name: "pricingRuleId",
+ "rowFilter.salesOrderLines.convertedShippingCost": {
+ name: "convertedShippingCost",
required: false,
in: "query",
type: "string"
},
- "rowFilter.salesOrderLines.priceTrace": {
- name: "priceTrace",
+ "rowFilter.salesOrderLines.convertedUnitPrice": {
+ name: "convertedUnitPrice",
required: false,
in: "query",
type: "string"
},
- "rowFilter.salesOrderLines.sortOrder": {
- name: "sortOrder",
+ "rowFilter.salesOrderLines.convertedNonTaxableAddOnCost": {
+ name: "convertedNonTaxableAddOnCost",
required: false,
in: "query",
type: "string"
@@ -171949,56 +172094,56 @@ export default {
in: "query",
type: "string"
},
- "rowFilter.quoteLinePrice.convertedUnitPrice": {
- name: "convertedUnitPrice",
+ "rowFilter.quoteLinePrice.categoryMarkups": {
+ name: "categoryMarkups",
required: false,
in: "query",
type: "string"
},
- "rowFilter.quoteLinePrice.netUnitPrice": {
- name: "netUnitPrice",
+ "rowFilter.quoteLinePrice.companyId": {
+ name: "companyId",
required: false,
in: "query",
type: "string"
},
- "rowFilter.quoteLinePrice.netExtendedPrice": {
- name: "netExtendedPrice",
+ "rowFilter.quoteLinePrice.priceSource": {
+ name: "priceSource",
required: false,
in: "query",
type: "string"
},
- "rowFilter.quoteLinePrice.convertedNetUnitPrice": {
- name: "convertedNetUnitPrice",
+ "rowFilter.quoteLinePrice.convertedUnitPrice": {
+ name: "convertedUnitPrice",
required: false,
in: "query",
type: "string"
},
- "rowFilter.quoteLinePrice.convertedNetExtendedPrice": {
- name: "convertedNetExtendedPrice",
+ "rowFilter.quoteLinePrice.netUnitPrice": {
+ name: "netUnitPrice",
required: false,
in: "query",
type: "string"
},
- "rowFilter.quoteLinePrice.convertedShippingCost": {
- name: "convertedShippingCost",
+ "rowFilter.quoteLinePrice.netExtendedPrice": {
+ name: "netExtendedPrice",
required: false,
in: "query",
type: "string"
},
- "rowFilter.quoteLinePrice.categoryMarkups": {
- name: "categoryMarkups",
+ "rowFilter.quoteLinePrice.convertedNetUnitPrice": {
+ name: "convertedNetUnitPrice",
required: false,
in: "query",
type: "string"
},
- "rowFilter.quoteLinePrice.companyId": {
- name: "companyId",
+ "rowFilter.quoteLinePrice.convertedNetExtendedPrice": {
+ name: "convertedNetExtendedPrice",
required: false,
in: "query",
type: "string"
},
- "rowFilter.quoteLinePrice.priceSource": {
- name: "priceSource",
+ "rowFilter.quoteLinePrice.convertedShippingCost": {
+ name: "convertedShippingCost",
required: false,
in: "query",
type: "string"
@@ -172602,6 +172747,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.supplierQuoteLinePrice.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"rowFilter.supplierQuoteLinePrice.unitPrice": {
name: "unitPrice",
required: false,
@@ -172626,12 +172777,6 @@ export default {
in: "query",
type: "string"
},
- "rowFilter.supplierQuoteLinePrice.companyId": {
- name: "companyId",
- required: false,
- in: "query",
- type: "string"
- },
"body.purchaseOrderSuppliers": {
name: "purchaseOrderSuppliers",
description: "purchaseOrderSuppliers",
@@ -173895,6 +174040,18 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.quoteOperationsWithMakeMethods.assemblyInstructionId": {
+ name: "assemblyInstructionId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.quoteOperationsWithMakeMethods.inspectionDocumentId": {
+ name: "inspectionDocumentId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.config": {
name: "config",
description: "config",
@@ -174135,62 +174292,62 @@ export default {
in: "query",
type: "string"
},
- "rowFilter.salesOrderLine.convertedAddOnCost": {
- name: "convertedAddOnCost",
+ "rowFilter.salesOrderLine.sentDate": {
+ name: "sentDate",
required: false,
in: "query",
type: "string"
},
- "rowFilter.salesOrderLine.convertedShippingCost": {
- name: "convertedShippingCost",
+ "rowFilter.salesOrderLine.accountId": {
+ name: "accountId",
required: false,
in: "query",
type: "string"
},
- "rowFilter.salesOrderLine.convertedUnitPrice": {
- name: "convertedUnitPrice",
+ "rowFilter.salesOrderLine.nonTaxableAddOnCost": {
+ name: "nonTaxableAddOnCost",
required: false,
in: "query",
type: "string"
},
- "rowFilter.salesOrderLine.sentDate": {
- name: "sentDate",
+ "rowFilter.salesOrderLine.pricingRuleId": {
+ name: "pricingRuleId",
required: false,
in: "query",
type: "string"
},
- "rowFilter.salesOrderLine.accountId": {
- name: "accountId",
+ "rowFilter.salesOrderLine.priceTrace": {
+ name: "priceTrace",
required: false,
in: "query",
type: "string"
},
- "rowFilter.salesOrderLine.nonTaxableAddOnCost": {
- name: "nonTaxableAddOnCost",
+ "rowFilter.salesOrderLine.sortOrder": {
+ name: "sortOrder",
required: false,
in: "query",
type: "string"
},
- "rowFilter.salesOrderLine.convertedNonTaxableAddOnCost": {
- name: "convertedNonTaxableAddOnCost",
+ "rowFilter.salesOrderLine.convertedAddOnCost": {
+ name: "convertedAddOnCost",
required: false,
in: "query",
type: "string"
},
- "rowFilter.salesOrderLine.pricingRuleId": {
- name: "pricingRuleId",
+ "rowFilter.salesOrderLine.convertedShippingCost": {
+ name: "convertedShippingCost",
required: false,
in: "query",
type: "string"
},
- "rowFilter.salesOrderLine.priceTrace": {
- name: "priceTrace",
+ "rowFilter.salesOrderLine.convertedUnitPrice": {
+ name: "convertedUnitPrice",
required: false,
in: "query",
type: "string"
},
- "rowFilter.salesOrderLine.sortOrder": {
- name: "sortOrder",
+ "rowFilter.salesOrderLine.convertedNonTaxableAddOnCost": {
+ name: "convertedNonTaxableAddOnCost",
required: false,
in: "query",
type: "string"
@@ -177168,68 +177325,68 @@ export default {
in: "query",
type: "string"
},
- "rowFilter.purchaseOrderLines.unitPrice": {
- name: "unitPrice",
+ "rowFilter.purchaseOrderLines.accountId": {
+ name: "accountId",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseOrderLines.extendedPrice": {
- name: "extendedPrice",
+ "rowFilter.purchaseOrderLines.requiredDate": {
+ name: "requiredDate",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseOrderLines.shippingCost": {
- name: "shippingCost",
+ "rowFilter.purchaseOrderLines.receivedDate": {
+ name: "receivedDate",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseOrderLines.taxAmount": {
- name: "taxAmount",
+ "rowFilter.purchaseOrderLines.costCenterId": {
+ name: "costCenterId",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseOrderLines.accountId": {
- name: "accountId",
+ "rowFilter.purchaseOrderLines.ownerId": {
+ name: "ownerId",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseOrderLines.requiredDate": {
- name: "requiredDate",
+ "rowFilter.purchaseOrderLines.sortOrder": {
+ name: "sortOrder",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseOrderLines.receivedDate": {
- name: "receivedDate",
+ "rowFilter.purchaseOrderLines.supplierPartId": {
+ name: "supplierPartId",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseOrderLines.costCenterId": {
- name: "costCenterId",
+ "rowFilter.purchaseOrderLines.unitPrice": {
+ name: "unitPrice",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseOrderLines.ownerId": {
- name: "ownerId",
+ "rowFilter.purchaseOrderLines.extendedPrice": {
+ name: "extendedPrice",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseOrderLines.sortOrder": {
- name: "sortOrder",
+ "rowFilter.purchaseOrderLines.shippingCost": {
+ name: "shippingCost",
required: false,
in: "query",
type: "string"
},
- "rowFilter.purchaseOrderLines.supplierPartId": {
- name: "supplierPartId",
+ "rowFilter.purchaseOrderLines.taxAmount": {
+ name: "taxAmount",
required: false,
in: "query",
type: "string"
@@ -179937,6 +180094,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.jobOperationsWithMakeMethods.inspectionDocumentId": {
+ name: "inspectionDocumentId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.supplierLedger": {
name: "supplierLedger",
description: "supplierLedger",
@@ -181014,6 +181177,24 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.quoteLinePrices.pricingRuleId": {
+ name: "pricingRuleId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.quoteLinePrices.priceTrace": {
+ name: "priceTrace",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.quoteLinePrices.sortOrder": {
+ name: "sortOrder",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"rowFilter.quoteLinePrices.itemReadableId": {
name: "itemReadableId",
required: false,
@@ -183990,6 +184171,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.companySettings.showCurrencyTrailingZeros": {
+ name: "showCurrencyTrailingZeros",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.part": {
name: "part",
description: "part",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 3570c6224e..b414c38e84 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -6763,6 +6763,7 @@ export type Database = {
salesJobCompletedNotificationGroup: string[]
samplingStandard: Database["public"]["Enums"]["samplingStandard"]
shelfLabelSize: string | null
+ showCurrencyTrailingZeros: boolean
showCustomerReadableId: boolean
showSupplierReadableId: boolean
supplierQuoteNotificationGroup: string[]
@@ -6810,6 +6811,7 @@ export type Database = {
salesJobCompletedNotificationGroup?: string[]
samplingStandard?: Database["public"]["Enums"]["samplingStandard"]
shelfLabelSize?: string | null
+ showCurrencyTrailingZeros?: boolean
showCustomerReadableId?: boolean
showSupplierReadableId?: boolean
supplierQuoteNotificationGroup?: string[]
@@ -6857,6 +6859,7 @@ export type Database = {
salesJobCompletedNotificationGroup?: string[]
samplingStandard?: Database["public"]["Enums"]["samplingStandard"]
shelfLabelSize?: string | null
+ showCurrencyTrailingZeros?: boolean
showCustomerReadableId?: boolean
showSupplierReadableId?: boolean
supplierQuoteNotificationGroup?: string[]
@@ -62761,6 +62764,7 @@ export type Database = {
locationName: string | null
postingDate: string | null
quantity: number | null
+ scrapReasonId: string | null
storageUnitId: string | null
storageUnitName: string | null
thumbnailPath: string | null
@@ -62856,6 +62860,13 @@ export type Database = {
referencedRelation: "location"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "itemLedger_scrapReasonId_fkey"
+ columns: ["scrapReasonId"]
+ isOneToOne: false
+ referencedRelation: "scrapReason"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "itemLedger_storageUnitId_fkey"
columns: ["storageUnitId"]
@@ -63212,6 +63223,8 @@ export type Database = {
scrapQuantity: number | null
storageUnitId: string | null
storageUnitName: string | null
+ substitutedFromItemId: string | null
+ substitutionFactor: number | null
unitCost: number | null
unitOfMeasureCode: string | null
updatedAt: string | null
@@ -63452,6 +63465,7 @@ export type Database = {
dueDate: string | null
hasConflict: boolean | null
id: string | null
+ inspectionDocumentId: string | null
jobId: string | null
jobMakeMethodId: string | null
laborRate: number | null
@@ -63503,6 +63517,7 @@ export type Database = {
dueDate?: string | null
hasConflict?: boolean | null
id?: string | null
+ inspectionDocumentId?: string | null
jobId?: string | null
jobMakeMethodId?: string | null
laborRate?: number | null
@@ -63554,6 +63569,7 @@ export type Database = {
dueDate?: string | null
hasConflict?: boolean | null
id?: string | null
+ inspectionDocumentId?: string | null
jobId?: string | null
jobMakeMethodId?: string | null
laborRate?: number | null
@@ -63705,6 +63721,20 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "jobOperation_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocument"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocuments"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "jobOperation_jobId_fkey"
columns: ["jobId"]
@@ -63860,6 +63890,7 @@ export type Database = {
dueDate: string | null
hasConflict: boolean | null
id: string | null
+ inspectionDocumentId: string | null
jobId: string | null
jobMakeMethodId: string | null
laborRate: number | null
@@ -64012,6 +64043,20 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "jobOperation_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocument"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocuments"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "jobOperation_jobId_fkey"
columns: ["jobId"]
@@ -69016,12 +69061,15 @@ export type Database = {
modelSize: number | null
modelUploadId: string | null
noQuoteReason: string | null
+ priceTrace: Json | null
+ pricingRuleId: string | null
qty: number | null
quantity: number[] | null
quoteCreatedAt: string | null
quoteId: string | null
quoteReadableId: string | null
quoteRevisionId: number | null
+ sortOrder: number | null
status: Database["public"]["Enums"]["quoteLineStatus"] | null
tags: string[] | null
taxPercent: number | null
@@ -69202,6 +69250,13 @@ export type Database = {
referencedRelation: "salesRfqLines"
referencedColumns: ["modelId"]
},
+ {
+ foreignKeyName: "quoteLine_pricingRuleId_fkey"
+ columns: ["pricingRuleId"]
+ isOneToOne: false
+ referencedRelation: "pricingRule"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteLine_quoteId_fkey"
columns: ["quoteId"]
@@ -69808,12 +69863,14 @@ export type Database = {
}
quoteOperationsWithMakeMethods: {
Row: {
+ assemblyInstructionId: string | null
companyId: string | null
createdAt: string | null
createdBy: string | null
customFields: Json | null
description: string | null
id: string | null
+ inspectionDocumentId: string | null
laborRate: number | null
laborTime: number | null
laborUnit: Database["public"]["Enums"]["factor"] | null
@@ -69845,6 +69902,20 @@ export type Database = {
workInstruction: Json | null
}
Relationships: [
+ {
+ foreignKeyName: "quoteOperation_assemblyInstructionId_fkey"
+ columns: ["assemblyInstructionId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstruction"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperation_assemblyInstructionId_fkey"
+ columns: ["assemblyInstructionId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstructions"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteOperation_companyId_fkey"
columns: ["companyId"]
@@ -69908,6 +69979,20 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "quoteOperation_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocument"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperation_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocuments"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteOperation_operationSupplierProcessId_fkey"
columns: ["operationSupplierProcessId"]
@@ -71309,21 +71394,21 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -71870,14 +71955,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"]
@@ -73491,6 +73576,7 @@ export type Database = {
processId: string | null
processName: string | null
supplierId: string | null
+ tags: string[] | null
updatedAt: string | null
updatedBy: string | null
}
diff --git a/packages/database/supabase/functions/close-job/index.ts b/packages/database/supabase/functions/close-job/index.ts
index ec1dfb7482..9dc4a8bfc4 100644
--- a/packages/database/supabase/functions/close-job/index.ts
+++ b/packages/database/supabase/functions/close-job/index.ts
@@ -9,6 +9,7 @@ import { credit, debit, journalReference } from "../lib/utils.ts";
import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
import { getNextSequence } from "../shared/get-next-sequence.ts";
import { getDefaultPostingGroup } from "../shared/get-posting-group.ts";
+import { round } from "../shared/precision.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -115,7 +116,7 @@ serve(async (req: Request) => {
description: "Production Variance",
// Signed: a positive residual debits variance / credits WIP; a
// negative (over-credited) residual reverses — always zeroing WIP.
- amount: debit("expense", remainingWip),
+ amount: round(debit("expense", remainingWip)),
quantity: 0,
documentType: "Job Close",
documentId: jobId,
@@ -126,7 +127,7 @@ serve(async (req: Request) => {
{
accountId: accountDefaults.data!.workInProgressAccount,
description: "WIP Account",
- amount: credit("asset", remainingWip),
+ amount: round(credit("asset", remainingWip)),
quantity: 0,
documentType: "Job Close",
documentId: jobId,
diff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.ts
index 1d09304cd0..5099642424 100644
--- a/packages/database/supabase/functions/convert/index.ts
+++ b/packages/database/supabase/functions/convert/index.ts
@@ -9,6 +9,7 @@ import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { requirePermissions } from "../lib/supabase.ts";
import { Database } from "../lib/types.ts";
import { getNextSequence } from "../shared/get-next-sequence.ts";
+import { deriveRate } from "../shared/precision.ts";
import { getRemainingQuantityToInvoice } from "../shared/short-close.ts";
const pool = getConnectionPool(2);
@@ -108,6 +109,10 @@ const payloadValidator = z.discriminatedUnion("type", [
supplierShippingCost: z.number(),
supplierUnitPrice: z.number(),
supplierTaxAmount: z.number(),
+ // Mirrors selectedLineSchema in purchasing.models.ts — a 0..1 fraction.
+ // Left optional so existing clients keep working; resolveTaxPercent
+ // derives it from the amount rather than storing 0 beside a real one.
+ taxPercent: z.number().min(0).max(1).optional().default(0),
unitPrice: z.number(),
})
),
@@ -126,6 +131,28 @@ const payloadValidator = z.discriminatedUnion("type", [
}),
]);
+/**
+ * taxPercent and the tax amount are one value pair — a write that sets one sets
+ * both. The payload's rate is optional for client compatibility, so when a
+ * client sends a real amount without a rate, derive the rate once from the
+ * canonical denominator (unit price x quantity + shipping) instead of storing 0
+ * next to it, which the form would then treat as "no tax" and zero out.
+ */
+function resolveTaxPercent(line: {
+ taxPercent?: number;
+ supplierTaxAmount: number;
+ supplierUnitPrice: number;
+ quantity: number;
+ supplierShippingCost: number;
+}): number {
+ if (line.taxPercent) return line.taxPercent;
+ if (!line.supplierTaxAmount) return 0;
+ return deriveRate(
+ line.supplierTaxAmount,
+ line.supplierUnitPrice * line.quantity + line.supplierShippingCost
+ );
+}
+
serve(async (req: Request) => {
const preflight = corsPreflight(req);
if (preflight) return preflight;
@@ -420,6 +447,8 @@ serve(async (req: Request) => {
(line.supplierShippingCost ?? 0) * uninvoicedFraction(line),
supplierTaxAmount:
(line.supplierTaxAmount ?? 0) * uninvoicedFraction(line),
+ // The rate is invariant under proration; only the amount scales
+ taxPercent: line.taxPercent ?? 0,
purchaseUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,
inventoryUnitOfMeasureCode: line.inventoryUnitOfMeasureCode,
conversionFactor: line.conversionFactor,
@@ -1689,6 +1718,7 @@ serve(async (req: Request) => {
supplierShippingCost:
selectedLines![line.id!].supplierShippingCost,
supplierTaxAmount: selectedLines![line.id!].supplierTaxAmount,
+ taxPercent: resolveTaxPercent(selectedLines![line.id!]),
sortOrder: line.sortOrder ?? 1,
createdBy: userId,
companyId,
diff --git a/packages/database/supabase/functions/deno.json b/packages/database/supabase/functions/deno.json
index 4c25f88fa4..8932605604 100644
--- a/packages/database/supabase/functions/deno.json
+++ b/packages/database/supabase/functions/deno.json
@@ -7,7 +7,7 @@
"imports": {
"@internationalized/date": "npm:@internationalized/[email protected]",
"kysely": "npm:[email protected]",
- "pg": "https://deno.land/x/[email protected]/mod.ts",
+ "pg": "jsr:@db/[email protected]",
"@supabase/supabase-js": "npm:@supabase/[email protected]",
"@logtape/logtape": "jsr:@logtape/[email protected]",
"@logtape/redaction": "jsr:@logtape/[email protected]"
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index ce693f7a02..047c66db7e 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -34,6 +34,7 @@ import {
getNextRevisionSequence,
getNextSequence,
} from "../shared/get-next-sequence.ts";
+import { scrapAllowance } from "../shared/precision.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -614,17 +615,19 @@ serve(async (req: Request) => {
// - For Buy/Pick parts: estimatedQuantity = target + scrap (what we need to procure)
// - scrapQuantity = targetQuantity * scrapRate (the extra needed for scrap)
// - totalForChildren = target + scrap (passed to children for cascade)
- const nodeScrapQuantity = targetQuantity * nodeScrapPercentage;
+ const nodeScrapQuantity = scrapAllowance(
+ targetQuantity,
+ nodeScrapPercentage
+ );
const totalWithScrap = targetQuantity + nodeScrapQuantity;
// For Make: estimatedQuantity is the good quantity (without scrap)
// For Buy/Pick: estimatedQuantity includes scrap since that's what we procure
const estimatedQuantity =
node.data.methodType === "Make to Order" ? targetQuantity : totalWithScrap;
- // operationQuantity should be the total (including scrap) since that's what we need to make
- // Operation/production counts stay whole even when material
- // quantities are fractional
- const operationQuantity = Math.ceil(totalWithScrap);
+ // operationQuantity is the total (including scrap); fractional
+ // targets flow through — the scrap allowance is already whole
+ const operationQuantity = totalWithScrap;
// Pass total (including scrap) to children so cascade works correctly
const totalQuantityForChildren = totalWithScrap;
@@ -1093,7 +1096,10 @@ serve(async (req: Request) => {
// targetQuantity for this child = parent's total (including scrap) * quantity per parent
const childTargetQuantity = totalQuantityForChildren * quantity;
// scrapQuantity = portion attributable to scrap
- const childScrapQuantity = childTargetQuantity * itemScrapPercentage;
+ const childScrapQuantity = scrapAllowance(
+ childTargetQuantity,
+ itemScrapPercentage
+ );
const childTotalWithScrap =
childTargetQuantity + childScrapQuantity;
// For Make: estimatedQuantity is the good quantity (without scrap)
@@ -1525,13 +1531,16 @@ serve(async (req: Request) => {
// Calculate quantities:
// - For Make parts: estimatedQuantity = targetQuantity (good quantity, NOT including scrap)
// - For Buy/Pick parts: estimatedQuantity = target + scrap (what we need to procure)
- const nodeScrapQuantity = targetQuantity * nodeScrapPercentage;
+ const nodeScrapQuantity = scrapAllowance(
+ targetQuantity,
+ nodeScrapPercentage
+ );
const totalWithScrap = targetQuantity + nodeScrapQuantity;
const estimatedQuantity =
node.data.methodType === "Make to Order" ? targetQuantity : totalWithScrap;
- // Operation/production counts stay whole even when material
- // quantities are fractional
- const operationQuantity = Math.ceil(totalWithScrap);
+ // operationQuantity is the total (including scrap); fractional
+ // targets flow through — the scrap allowance is already whole
+ const operationQuantity = totalWithScrap;
const totalQuantityForChildren = totalWithScrap;
const relatedOperations = await client
@@ -1781,8 +1790,10 @@ serve(async (req: Request) => {
// Use totalQuantityForChildren (parent's total including scrap) for child calculations
const childTargetQuantity =
totalQuantityForChildren * (child.data.quantity ?? 1);
- const childScrapQuantity =
- childTargetQuantity * itemScrapPercentage;
+ const childScrapQuantity = scrapAllowance(
+ childTargetQuantity,
+ itemScrapPercentage
+ );
const childTotalWithScrap =
childTargetQuantity + childScrapQuantity;
// For Make: estimatedQuantity is the good quantity (without scrap)
@@ -4897,7 +4908,10 @@ serve(async (req: Request) => {
);
const rootTarget = job.data?.quantity ?? 1;
// Scrap applies to every method type (mirrors itemToJob)
- const rootScrapQuantity = rootTarget * rootScrapPercentage;
+ const rootScrapQuantity = scrapAllowance(
+ rootTarget,
+ rootScrapPercentage
+ );
const rootTotalWithScrap = rootTarget + rootScrapQuantity;
// For Make: estimatedQuantity is good quantity (without scrap)
// For Buy/Pick: estimatedQuantity includes scrap since that's what we procure
@@ -4942,8 +4956,10 @@ serve(async (req: Request) => {
const childTargetQuantity =
nodeTotalForChildren * (child.data.quantity ?? 1);
// Scrap applies to every method type (mirrors itemToJob)
- const childScrapQuantity =
- childTargetQuantity * itemScrapPercentage;
+ const childScrapQuantity = scrapAllowance(
+ childTargetQuantity,
+ itemScrapPercentage
+ );
const childTotalWithScrap =
childTargetQuantity + childScrapQuantity;
// For Make: estimatedQuantity is good quantity (without scrap)
@@ -5114,9 +5130,8 @@ serve(async (req: Request) => {
tags: op.tags ?? [],
workInstruction: parts.workInstructions ? op.workInstruction : {},
targetQuantity: opQuantities.targetQuantity,
- // Operation/production counts stay whole even when material
- // quantities are fractional
- operationQuantity: Math.ceil(opQuantities.totalWithScrap),
+ // Fractional targets flow through; the scrap allowance is already whole
+ operationQuantity: opQuantities.totalWithScrap,
companyId,
createdBy: userId,
customFields: {},
diff --git a/packages/database/supabase/functions/lib/methods.ts b/packages/database/supabase/functions/lib/methods.ts
index 732468e823..fcc7686d05 100644
--- a/packages/database/supabase/functions/lib/methods.ts
+++ b/packages/database/supabase/functions/lib/methods.ts
@@ -1,4 +1,5 @@
import { SupabaseClient } from "@supabase/supabase-js";
+import { round } from "../shared/precision.ts";
import type { Database } from "./types.ts";
export type JobMethod = NonNullable<
@@ -799,7 +800,7 @@ export async function calculateQuoteLinePrices(
return sum + cost * (1 + markup / 100);
}, 0);
- const roundedUnitPrice = Number(unitPrice.toFixed(precision));
+ const roundedUnitPrice = round(unitPrice, precision);
return {
quoteId,
diff --git a/packages/database/supabase/functions/lib/postgres/index.ts b/packages/database/supabase/functions/lib/postgres/index.ts
index 401c0884e9..ebe50125a6 100644
--- a/packages/database/supabase/functions/lib/postgres/index.ts
+++ b/packages/database/supabase/functions/lib/postgres/index.ts
@@ -10,6 +10,7 @@ import {
import type { KyselifyDatabase } from "./kysely-supabase.types.ts";
// Aliased it as pg so can be imported as-is in Node environment
import { Pool } from "pg";
+import * as pg from "pg";
import type { Database as SupabaseDatabase } from "../../../../src/types.ts";
export type KyselyDatabase = KyselifyDatabase<SupabaseDatabase>;
@@ -39,6 +40,45 @@ export function getRuntime() {
// no-op for them).
const poolCache = new Map<number, Pool>();
+/** NUMERIC. Both drivers hand it over as text by default, so a scale-5 price
+ * would arrive as a string where the generated types promise a number. */
+const NUMERIC_OID = 1700;
+
+/** The deno-postgres constructor shape. "pg" resolves to node-postgres types in
+ * the Node build, so the Deno branch has to describe its own driver — but it
+ * describes it PROPERLY: the TLS block below is the one place a typo silently
+ * turns encryption off, which is not something to hand to `unknown`. */
+type DenoTlsOptions = { enabled: boolean; enforce: boolean };
+type DenoClientOptions = {
+ user: string;
+ password: string;
+ hostname: string;
+ port: string | number;
+ database?: string;
+ tls?: DenoTlsOptions;
+ controls?: { decoders?: Record<number, (value: string) => unknown> };
+};
+type DenoPoolConstructor = new (
+ options: DenoClientOptions,
+ size: number
+) => Pool;
+
+/** node-postgres keeps type parsers in a PROCESS-GLOBAL registry, so this is
+ * registered once at module load rather than as a side effect of constructing a
+ * pool — a factory that reconfigures global state on every call is a trap for
+ * whoever calls it next. No-ops on Deno, whose driver takes per-pool decoders
+ * (see `controls` below) and exposes no `types` namespace. */
+function registerNodeNumericParser(): void {
+ (
+ pg as unknown as {
+ types?: {
+ setTypeParser: (oid: number, fn: (v: string) => unknown) => void;
+ };
+ }
+ ).types?.setTypeParser(NUMERIC_OID, Number);
+}
+registerNodeNumericParser();
+
export function getPostgresConnectionPool(connections: number): Pool {
const cached = poolCache.get(connections);
// An ended pool can never serve connections again ("Cannot use a pool after
@@ -62,8 +102,33 @@ function createPostgresConnectionPool(connections: number): Pool {
const connectionPoolerUrl = url.includes("supabase.co")
? url.replace("5432", "6543")
: url;
- // @ts-ignore Compat
- return new Pool(connectionPoolerUrl, connections);
+ // deno-postgres accepts EITHER a URI string OR a ClientOptions object —
+ // the NUMERIC decoder (`controls`) only fits on the object form, so
+ // parse the URL ourselves. sslmode mapping mirrors the driver's own:
+ // disable -> off; require/verify-* -> enforce; otherwise attempt TLS
+ // and fall back (its default).
+ const u = new URL(connectionPoolerUrl);
+ const sslmode = u.searchParams.get("sslmode");
+ const DenoPool = Pool as unknown as DenoPoolConstructor;
+ const options: DenoClientOptions = {
+ user: decodeURIComponent(u.username),
+ password: decodeURIComponent(u.password),
+ hostname: u.hostname,
+ port: u.port || 5432,
+ database: u.pathname.replace(/^\//, "") || undefined,
+ controls: {
+ // The driver applies this element-wise to numeric[] via the base-type
+ // fallback, so arrays decode too.
+ decoders: { [NUMERIC_OID]: Number },
+ },
+ };
+ if (sslmode) {
+ options.tls = {
+ enabled: sslmode !== "disable",
+ enforce: ["require", "verify-ca", "verify-full"].includes(sslmode),
+ };
+ }
+ return new DenoPool(options, connections);
}
case "node": {
const url = process.env.SUPABASE_DB_URL!;
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 3570c6224e..b414c38e84 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -6763,6 +6763,7 @@ export type Database = {
salesJobCompletedNotificationGroup: string[]
samplingStandard: Database["public"]["Enums"]["samplingStandard"]
shelfLabelSize: string | null
+ showCurrencyTrailingZeros: boolean
showCustomerReadableId: boolean
showSupplierReadableId: boolean
supplierQuoteNotificationGroup: string[]
@@ -6810,6 +6811,7 @@ export type Database = {
salesJobCompletedNotificationGroup?: string[]
samplingStandard?: Database["public"]["Enums"]["samplingStandard"]
shelfLabelSize?: string | null
+ showCurrencyTrailingZeros?: boolean
showCustomerReadableId?: boolean
showSupplierReadableId?: boolean
supplierQuoteNotificationGroup?: string[]
@@ -6857,6 +6859,7 @@ export type Database = {
salesJobCompletedNotificationGroup?: string[]
samplingStandard?: Database["public"]["Enums"]["samplingStandard"]
shelfLabelSize?: string | null
+ showCurrencyTrailingZeros?: boolean
showCustomerReadableId?: boolean
showSupplierReadableId?: boolean
supplierQuoteNotificationGroup?: string[]
@@ -62761,6 +62764,7 @@ export type Database = {
locationName: string | null
postingDate: string | null
quantity: number | null
+ scrapReasonId: string | null
storageUnitId: string | null
storageUnitName: string | null
thumbnailPath: string | null
@@ -62856,6 +62860,13 @@ export type Database = {
referencedRelation: "location"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "itemLedger_scrapReasonId_fkey"
+ columns: ["scrapReasonId"]
+ isOneToOne: false
+ referencedRelation: "scrapReason"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "itemLedger_storageUnitId_fkey"
columns: ["storageUnitId"]
@@ -63212,6 +63223,8 @@ export type Database = {
scrapQuantity: number | null
storageUnitId: string | null
storageUnitName: string | null
+ substitutedFromItemId: string | null
+ substitutionFactor: number | null
unitCost: number | null
unitOfMeasureCode: string | null
updatedAt: string | null
@@ -63452,6 +63465,7 @@ export type Database = {
dueDate: string | null
hasConflict: boolean | null
id: string | null
+ inspectionDocumentId: string | null
jobId: string | null
jobMakeMethodId: string | null
laborRate: number | null
@@ -63503,6 +63517,7 @@ export type Database = {
dueDate?: string | null
hasConflict?: boolean | null
id?: string | null
+ inspectionDocumentId?: string | null
jobId?: string | null
jobMakeMethodId?: string | null
laborRate?: number | null
@@ -63554,6 +63569,7 @@ export type Database = {
dueDate?: string | null
hasConflict?: boolean | null
id?: string | null
+ inspectionDocumentId?: string | null
jobId?: string | null
jobMakeMethodId?: string | null
laborRate?: number | null
@@ -63705,6 +63721,20 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "jobOperation_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocument"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocuments"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "jobOperation_jobId_fkey"
columns: ["jobId"]
@@ -63860,6 +63890,7 @@ export type Database = {
dueDate: string | null
hasConflict: boolean | null
id: string | null
+ inspectionDocumentId: string | null
jobId: string | null
jobMakeMethodId: string | null
laborRate: number | null
@@ -64012,6 +64043,20 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "jobOperation_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocument"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocuments"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "jobOperation_jobId_fkey"
columns: ["jobId"]
@@ -69016,12 +69061,15 @@ export type Database = {
modelSize: number | null
modelUploadId: string | null
noQuoteReason: string | null
+ priceTrace: Json | null
+ pricingRuleId: string | null
qty: number | null
quantity: number[] | null
quoteCreatedAt: string | null
quoteId: string | null
quoteReadableId: string | null
quoteRevisionId: number | null
+ sortOrder: number | null
status: Database["public"]["Enums"]["quoteLineStatus"] | null
tags: string[] | null
taxPercent: number | null
@@ -69202,6 +69250,13 @@ export type Database = {
referencedRelation: "salesRfqLines"
referencedColumns: ["modelId"]
},
+ {
+ foreignKeyName: "quoteLine_pricingRuleId_fkey"
+ columns: ["pricingRuleId"]
+ isOneToOne: false
+ referencedRelation: "pricingRule"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteLine_quoteId_fkey"
columns: ["quoteId"]
@@ -69808,12 +69863,14 @@ export type Database = {
}
quoteOperationsWithMakeMethods: {
Row: {
+ assemblyInstructionId: string | null
companyId: string | null
createdAt: string | null
createdBy: string | null
customFields: Json | null
description: string | null
id: string | null
+ inspectionDocumentId: string | null
laborRate: number | null
laborTime: number | null
laborUnit: Database["public"]["Enums"]["factor"] | null
@@ -69845,6 +69902,20 @@ export type Database = {
workInstruction: Json | null
}
Relationships: [
+ {
+ foreignKeyName: "quoteOperation_assemblyInstructionId_fkey"
+ columns: ["assemblyInstructionId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstruction"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperation_assemblyInstructionId_fkey"
+ columns: ["assemblyInstructionId"]
+ isOneToOne: false
+ referencedRelation: "assemblyInstructions"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteOperation_companyId_fkey"
columns: ["companyId"]
@@ -69908,6 +69979,20 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "quoteOperation_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocument"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperation_inspectionDocumentId_fkey"
+ columns: ["inspectionDocumentId"]
+ isOneToOne: false
+ referencedRelation: "inspectionDocuments"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteOperation_operationSupplierProcessId_fkey"
columns: ["operationSupplierProcessId"]
@@ -71309,21 +71394,21 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -71870,14 +71955,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"]
@@ -73491,6 +73576,7 @@ export type Database = {
processId: string | null
processName: string | null
supplierId: string | null
+ tags: string[] | null
updatedAt: string | null
updatedBy: string | null
}
diff --git a/packages/database/supabase/functions/post-inventory-adjustment/index.ts b/packages/database/supabase/functions/post-inventory-adjustment/index.ts
index e5d104be17..d3dc9670b4 100644
--- a/packages/database/supabase/functions/post-inventory-adjustment/index.ts
+++ b/packages/database/supabase/functions/post-inventory-adjustment/index.ts
@@ -13,6 +13,7 @@ import type { Json } from "../lib/types.ts";
import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
import { getDefaultPostingGroup } from "../shared/get-posting-group.ts";
import { bookAdjustment } from "../shared/post-adjustment.ts";
+import { round } from "../shared/precision.ts";
import { resolveUnscrapUnitCost } from "./resolve-unscrap-cost.ts";
const pool = getConnectionPool(1);
@@ -480,6 +481,7 @@ serve(async (req: Request) => {
split.ledgerInserts.map((ledgerRow) => ({
...ledgerRow,
itemId: ledgerRow.itemId ?? itemId,
+ quantity: round(ledgerRow.quantity),
}))
)
.execute();
diff --git a/packages/database/supabase/functions/post-memo/build-memo-journal.ts b/packages/database/supabase/functions/post-memo/build-memo-journal.ts
index 08ebad44f1..110cb55bf2 100644
--- a/packages/database/supabase/functions/post-memo/build-memo-journal.ts
+++ b/packages/database/supabase/functions/post-memo/build-memo-journal.ts
@@ -24,10 +24,9 @@
// memo — a separate payment posting). Both legs use the same base amount, so the
// entry balances exactly.
+import { assertBalanced, round } from "../shared/precision.ts";
import { credit, debit } from "../lib/utils.ts";
-export const round4 = (n: number) => Math.round(n * 10000) / 10000;
-
type AccountType = "asset" | "liability" | "equity" | "revenue" | "expense";
// glAccountClass (Asset|Liability|Equity|Revenue|Expense) → the lowercase
@@ -112,7 +111,7 @@ export function buildMemoJournal(
);
}
- const magnitude = round4(Math.abs(amountBase));
+ const magnitude = round(Math.abs(amountBase));
if (magnitude < 0.0001) {
throw new Error("Memo amount must be greater than 0 to post");
}
@@ -163,11 +162,14 @@ export function buildMemoJournal(
direction === "Credit" ? "Credit memo" : "Debit memo"
);
- if (Math.abs(signedDebitTotal) > BALANCE_TOLERANCE) {
- throw new Error(
- `Memo journal does not balance (off by ${round4(signedDebitTotal)} in base currency); refusing to post`
- );
- }
+ // BALANCE_TOLERANCE is a business threshold (multi-currency memos carry
+ // sub-cent cross-rate residuals), NOT the float-noise default.
+ assertBalanced(
+ signedDebitTotal,
+ 0,
+ BALANCE_TOLERANCE,
+ "Memo journal (base currency)"
+ );
return { lines, signedDebitTotal };
}
diff --git a/packages/database/supabase/functions/post-memo/post-memo.test.ts b/packages/database/supabase/functions/post-memo/post-memo.test.ts
index dd282e1844..7a6d827d62 100644
--- a/packages/database/supabase/functions/post-memo/post-memo.test.ts
+++ b/packages/database/supabase/functions/post-memo/post-memo.test.ts
@@ -72,9 +72,10 @@ Deno.test("supplier Debit memo: DR AP (liability), CR reason; balances", () => {
assert(Math.abs(r.signedDebitTotal) < 0.01);
});
-Deno.test("rounds to 4dp and stays balanced on fractional amounts", () => {
+Deno.test("rounds to internal scale and stays balanced on fractional amounts", () => {
const r = buildMemoJournal(base({ amountBase: 123.456789 }));
- assertEquals(line(r, "acct_ar").amount, -123.4568);
+ // SCALE = 5: GL lines carry internal precision, not the old 4dp column clamp.
+ assertEquals(line(r, "acct_ar").amount, -123.45679);
assert(Math.abs(r.signedDebitTotal) < 0.01);
});
diff --git a/packages/database/supabase/functions/post-payment/build-payment-journal.ts b/packages/database/supabase/functions/post-payment/build-payment-journal.ts
index f3415dc829..2ef9028f31 100644
--- a/packages/database/supabase/functions/post-payment/build-payment-journal.ts
+++ b/packages/database/supabase/functions/post-payment/build-payment-journal.ts
@@ -34,6 +34,7 @@
// means a loss, for both AR and AP. This is the same quantity the stored
// `invoiceSettlement.fxGainLossAmount` captures, so the subledger reconciles.
+import { assertBalanced, EPSILON, round } from "../shared/precision.ts";
import { credit, debit } from "../lib/utils.ts";
// A journal line this builder emits. Deliberately self-contained — a pure unit
@@ -53,11 +54,6 @@ export interface PaymentJournalLine {
companyId: string;
}
-// Round to 4 decimal places to match NUMERIC(19,4) storage and prevent
-// floating-point cruft from making the journal fail its balance check. Shared
-// with the driver so amounts are rounded identically everywhere.
-export const round4 = (n: number) => Math.round(n * 10000) / 10000;
-
export interface PaymentJournalApplicationInput {
targetSalesInvoiceId?: string | null;
targetPurchaseInvoiceId?: string | null;
@@ -169,7 +165,7 @@ export function buildPaymentJournal(
};
// 1) Cash: DR Bank (cash in) / CR Bank (cash out), full cash in base.
- const cashBase = round4(totalAmount * exchangeRate);
+ const cashBase = round(totalAmount * exchangeRate);
pushLine(cashIn ? "debit" : "credit", "asset", cashBase, {
accountId: bankAccount,
description: "Bank / Cash",
@@ -193,7 +189,7 @@ export function buildPaymentJournal(
pushLine(
cashIn ? "credit" : "debit",
isAR ? "asset" : "liability",
- round4((applied + discount + writeOff) * invRate),
+ round((applied + discount + writeOff) * invRate),
{
accountId: controlAccountId,
description: isAR ? "Accounts Receivable" : "Accounts Payable",
@@ -210,7 +206,7 @@ export function buildPaymentJournal(
`Missing ${isAR ? "customer" : "supplier"} payment discount account default`
);
}
- pushLine(cashIn ? "debit" : "credit", "expense", round4(discount * invRate), {
+ pushLine(cashIn ? "debit" : "credit", "expense", round(discount * invRate), {
accountId: discountAccountId,
description: isAR
? "Customer Payment Discount"
@@ -231,7 +227,7 @@ export function buildPaymentJournal(
pushLine(
cashIn ? "debit" : "credit",
isAR ? "expense" : "revenue",
- round4(writeOff * invRate),
+ round(writeOff * invRate),
{
accountId: writeOffAccountId,
description: isAR ? "Bad Debt Expense" : "Vendor Write-Off Income",
@@ -252,14 +248,19 @@ export function buildPaymentJournal(
// Positive: cash beyond what was applied becomes new on-account credit.
// Negative: this payment applied more than its cash, drawing down the
// party's existing on-account credit (the inverse posting side).
+ // The band is EPSILON, not a hand-picked 1e-4: whatever we DON'T book here
+ // stays in the cash line with nothing to offset it, so anything the ledger
+ // can store must get a line or the entry is stored out of balance. When the
+ // columns were NUMERIC(19,4) a 1e-4 band was exactly "smaller than one
+ // storable unit"; at scale 5 that same literal drops ten storable units.
const unappliedInPaymentCcy =
totalAmount - applications.reduce((sum, a) => sum + Number(a.appliedAmount), 0);
- if (Math.abs(unappliedInPaymentCcy) > 0.0001) {
+ if (Math.abs(unappliedInPaymentCcy) > EPSILON) {
const buildingCredit = unappliedInPaymentCcy > 0;
pushLine(
cashIn === buildingCredit ? "credit" : "debit",
isAR ? "asset" : "liability",
- round4(Math.abs(unappliedInPaymentCcy) * exchangeRate),
+ round(Math.abs(unappliedInPaymentCcy) * exchangeRate),
{
accountId: controlAccountId,
description: isAR
@@ -273,9 +274,10 @@ export function buildPaymentJournal(
);
}
- // 4) FX plug (single line).
- if (Math.abs(totalFxImpact) > 0.0001) {
- const fxBase = round4(Math.abs(totalFxImpact));
+ // 4) FX plug (single line). Same reasoning as the unapplied band above — an
+ // unbooked FX residual has nothing to offset it.
+ if (Math.abs(totalFxImpact) > EPSILON) {
+ const fxBase = round(Math.abs(totalFxImpact));
if (totalFxImpact > 0) {
if (!fxGainAccountId) {
throw new Error("Missing realized FX gain account default");
@@ -298,12 +300,15 @@ export function buildPaymentJournal(
// Self-check: the entry must balance in true debit/credit space. The FX plug
// (same formula as the stored fxGainLossAmount) should make this ~0; a larger
// residual means a logic/rounding bug, so we refuse to post rather than write
- // an unbalanced journal to the GL.
- if (Math.abs(signedDebitTotal) > BALANCE_TOLERANCE) {
- throw new Error(
- `Payment journal does not balance (off by ${round4(signedDebitTotal)} in base currency); refusing to post`
- );
- }
+ // an unbalanced journal to the GL. BALANCE_TOLERANCE is a business threshold
+ // (multi-currency journals carry sub-cent cross-rate residuals), NOT the
+ // float-noise default.
+ assertBalanced(
+ signedDebitTotal,
+ 0,
+ BALANCE_TOLERANCE,
+ "Payment journal (base currency)"
+ );
return { lines, signedDebitTotal, totalFxImpact };
}
diff --git a/packages/database/supabase/functions/post-payment/index.ts b/packages/database/supabase/functions/post-payment/index.ts
index 1fbb3ff687..901eee73c0 100644
--- a/packages/database/supabase/functions/post-payment/index.ts
+++ b/packages/database/supabase/functions/post-payment/index.ts
@@ -11,9 +11,9 @@ import { getNextSequence } from "../shared/get-next-sequence.ts";
import { getDefaultPostingGroup } from "../shared/get-posting-group.ts";
import {
buildPaymentJournal,
- round4,
type PaymentJournalLine,
} from "./build-payment-journal.ts";
+import { round } from "../shared/precision.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -283,7 +283,7 @@ serve(async (req: Request) => {
0
);
const paymentTotalBase = Number(payment.data.totalAmount) * Number(payment.data.exchangeRate);
- const overAppliedBase = round4(totalAppliedBase - paymentTotalBase);
+ const overAppliedBase = round(totalAppliedBase - paymentTotalBase);
// --------------------------------------------------------------
// Build journal lines (in base currency)
@@ -706,9 +706,9 @@ serve(async (req: Request) => {
}
}
- if (overAppliedBase > round4(availableCreditBase) + 0.0001) {
+ if (overAppliedBase > round(availableCreditBase) + 0.0001) {
throw new Error(
- `Applied exceeds payment cash by ${overAppliedBase} in base currency, but only ${round4(availableCreditBase)} of on-account credit is available for this ${isAR ? "customer" : "supplier"}`
+ `Applied exceeds payment cash by ${overAppliedBase} in base currency, but only ${round(availableCreditBase)} of on-account credit is available for this ${isAR ? "customer" : "supplier"}`
);
}
}
diff --git a/packages/database/supabase/functions/post-payment/post-payment.test.ts b/packages/database/supabase/functions/post-payment/post-payment.test.ts
index 13622fac7b..aa4572e351 100644
--- a/packages/database/supabase/functions/post-payment/post-payment.test.ts
+++ b/packages/database/supabase/functions/post-payment/post-payment.test.ts
@@ -8,6 +8,7 @@ import {
type BuildPaymentJournalInput,
type PaymentJournalAccounts,
} from "./build-payment-journal.ts";
+import { round } from "../shared/precision.ts";
// Golden-master tests for the GL journal a payment posts. Each asserts the exact
// natural-balance-signed `amount` on each line (asset/expense debits are +,
@@ -76,7 +77,6 @@ const line = <T extends { description: string }>(
description: string
) => lines.find((l) => l.description === description);
-const round4 = (n: number) => Math.round(n * 10000) / 10000;
// Magnitude posted to the control account for a specific invoice (the lines are
// natural-balance signed, so take the absolute value to compare to the
@@ -528,14 +528,40 @@ Deno.test("applied exactly equal to cash emits no unapplied line", () => {
assert(line(lines, "Accounts Receivable (credit applied)") === undefined);
});
-Deno.test("sub-dust unapplied (< 0.0001) emits no on-account line", () => {
+// Anything the ledger can STORE has to be booked: the cash line already carries
+// the full amount, so a dropped residual would be stored out of balance. At scale
+// 5 that means 0.00005 gets its own on-account line; only float noise is dropped.
+Deno.test("storable unapplied dust still emits an on-account line", () => {
const { lines, signedDebitTotal } = buildPaymentJournal(
arBase({
totalAmount: 100,
applications: [
{
targetSalesInvoiceId: "si_1",
- appliedAmount: 99.99995, // unapplied 0.00005 < threshold
+ appliedAmount: 99.99995, // unapplied 0.00005 — representable at scale 5
+ discountAmount: 0,
+ writeOffAmount: 0,
+ targetExchangeRate: 1,
+ sourceExchangeRate: 1,
+ },
+ ],
+ })
+ );
+ assertEquals(
+ line(lines, "Accounts Receivable (on-account credit)")?.amount,
+ -0.00005
+ );
+ assert(balanced(signedDebitTotal));
+});
+
+Deno.test("float-noise unapplied is dropped and the entry still balances", () => {
+ const { lines, signedDebitTotal } = buildPaymentJournal(
+ arBase({
+ totalAmount: 100,
+ applications: [
+ {
+ targetSalesInvoiceId: "si_1",
+ appliedAmount: 99.9999999, // below EPSILON — not storable
discountAmount: 0,
writeOffAmount: 0,
targetExchangeRate: 1,
@@ -742,7 +768,7 @@ Deno.test("control posting ties out to subledger settled per invoice (AR & AP)",
});
apps.forEach((a, i) => {
- const expected = round4((a.applied + a.discount + a.writeOff) * a.invRate);
+ const expected = round((a.applied + a.discount + a.writeOff) * a.invRate);
assertEquals(controlMagnitudeFor(lines, `inv_${i}`), expected);
});
assert(balanced(signedDebitTotal));
@@ -800,7 +826,7 @@ Deno.test("matrix: every scenario balances with the correct FX side", () => {
assert(line(lines, side) !== undefined, `missing ${side}`);
assert(line(lines, wrong) === undefined, `unexpected ${wrong}`);
}
- assert(Math.abs(round4(totalFxImpact) - round4(expectedFx)) < 1e-9);
+ assert(Math.abs(round(totalFxImpact) - round(expectedFx)) < 1e-9);
}
}
}
diff --git a/packages/database/supabase/functions/post-picking/index.ts b/packages/database/supabase/functions/post-picking/index.ts
index 030116affe..6b87d960b9 100644
--- a/packages/database/supabase/functions/post-picking/index.ts
+++ b/packages/database/supabase/functions/post-picking/index.ts
@@ -11,6 +11,7 @@ import {
buildBatchSplitRecords,
buildMergeRecords
} from "../shared/batch-split.ts";
+import { round } from "../shared/precision.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -147,7 +148,7 @@ serve(async (req: Request) => {
{
postingDate: today,
itemId: line.itemId,
- quantity: -quantity,
+ quantity: round(-quantity),
locationId,
storageUnitId: line.storageUnitId,
entryType: "Transfer",
@@ -159,7 +160,7 @@ serve(async (req: Request) => {
{
postingDate: today,
itemId: line.itemId,
- quantity: quantity,
+ quantity: round(quantity),
locationId,
storageUnitId: line.toStorageUnitId,
entryType: "Transfer",
@@ -212,7 +213,7 @@ serve(async (req: Request) => {
{
postingDate: today,
itemId: line.itemId,
- quantity: -quantity,
+ quantity: round(-quantity),
locationId,
storageUnitId: line.toStorageUnitId,
entryType: "Transfer",
@@ -224,7 +225,7 @@ serve(async (req: Request) => {
{
postingDate: today,
itemId: line.itemId,
- quantity: quantity,
+ quantity: round(quantity),
locationId,
storageUnitId: line.storageUnitId,
entryType: "Transfer",
@@ -468,7 +469,12 @@ serve(async (req: Request) => {
.where("id", "=", trackedEntityId)
.execute();
- inserts.push(...split.ledgerInserts);
+ inserts.push(
+ ...split.ledgerInserts.map((ledgerRow) => ({
+ ...ledgerRow,
+ quantity: round(ledgerRow.quantity)
+ }))
+ );
}
const activityId = nanoid();
@@ -506,7 +512,7 @@ serve(async (req: Request) => {
{
postingDate: today,
itemId: line.itemId,
- quantity: -transferQuantity,
+ quantity: round(-transferQuantity),
locationId,
storageUnitId: fromStorageUnitId,
entryType: "Transfer",
@@ -519,7 +525,7 @@ serve(async (req: Request) => {
{
postingDate: today,
itemId: line.itemId,
- quantity: transferQuantity,
+ quantity: round(transferQuantity),
locationId,
storageUnitId: line.toStorageUnitId,
entryType: "Transfer",
@@ -623,7 +629,7 @@ serve(async (req: Request) => {
{
postingDate: today,
itemId: line.itemId,
- quantity: -qty,
+ quantity: round(-qty),
locationId,
storageUnitId: line.toStorageUnitId,
entryType: "Transfer",
@@ -636,7 +642,7 @@ serve(async (req: Request) => {
{
postingDate: today,
itemId: line.itemId,
- quantity: qty,
+ quantity: round(qty),
locationId,
storageUnitId: line.storageUnitId,
entryType: "Transfer",
@@ -749,7 +755,7 @@ serve(async (req: Request) => {
{
postingDate: today,
itemId: line.itemId,
- quantity: -unpickQuantity,
+ quantity: round(-unpickQuantity),
locationId,
storageUnitId: line.toStorageUnitId,
entryType: "Transfer",
@@ -762,7 +768,7 @@ serve(async (req: Request) => {
{
postingDate: today,
itemId: line.itemId,
- quantity: unpickQuantity,
+ quantity: round(unpickQuantity),
locationId,
storageUnitId: line.storageUnitId,
entryType: "Transfer",
@@ -835,7 +841,7 @@ serve(async (req: Request) => {
{
postingDate: today,
itemId: line.itemId,
- quantity: -unpickQuantity,
+ quantity: round(-unpickQuantity),
locationId,
storageUnitId: line.storageUnitId,
entryType: "Negative Adjmt.",
@@ -848,7 +854,7 @@ serve(async (req: Request) => {
{
postingDate: today,
itemId: line.itemId,
- quantity: unpickQuantity,
+ quantity: round(unpickQuantity),
locationId,
storageUnitId: line.storageUnitId,
entryType: "Positive Adjmt.",
@@ -1047,8 +1053,8 @@ function transferPair(args: {
companyId: args.companyId
};
return [
- { ...base, quantity: -args.quantity, storageUnitId: args.fromStorageUnitId },
- { ...base, quantity: args.quantity, storageUnitId: args.toStorageUnitId }
+ { ...base, quantity: round(-args.quantity), storageUnitId: args.fromStorageUnitId },
+ { ...base, quantity: round(args.quantity), storageUnitId: args.toStorageUnitId }
];
}
@@ -1266,7 +1272,7 @@ async function returnTrackedAllocationRemainder(
{
postingDate: today,
itemId: line.itemId,
- quantity: -onHand,
+ quantity: round(-onHand),
locationId,
storageUnitId: lineside,
entryType: "Transfer",
@@ -1279,7 +1285,7 @@ async function returnTrackedAllocationRemainder(
{
postingDate: today,
itemId: line.itemId,
- quantity: onHand,
+ quantity: round(onHand),
locationId,
storageUnitId: source,
entryType: "Transfer",
@@ -1469,8 +1475,8 @@ async function returnUntrackedMaterialRemainder(
companyId
};
inserts.push(
- { ...base, quantity: -quantity, storageUnitId: line.toStorageUnitId },
- { ...base, quantity, storageUnitId: target }
+ { ...base, quantity: round(-quantity), storageUnitId: line.toStorageUnitId },
+ { ...base, quantity: round(quantity), storageUnitId: target }
);
await trx
diff --git a/packages/database/supabase/functions/post-production-event/index.ts b/packages/database/supabase/functions/post-production-event/index.ts
index eb789740c5..4a1b1af5f2 100644
--- a/packages/database/supabase/functions/post-production-event/index.ts
+++ b/packages/database/supabase/functions/post-production-event/index.ts
@@ -10,6 +10,7 @@ import { credit, debit, journalReference } from "../lib/utils.ts";
import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
import { getNextSequence } from "../shared/get-next-sequence.ts";
import { getDefaultPostingGroup } from "../shared/get-posting-group.ts";
+import { round } from "../shared/precision.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -231,7 +232,7 @@ serve(async (req: Request) => {
...reversalLines.map((line) => ({
accountId: line.accountId,
description: "Production Event Reversal",
- amount: -Number(line.amount),
+ amount: round(-Number(line.amount)),
quantity: 1,
documentType: "Production Event",
documentId: jobId,
@@ -244,7 +245,7 @@ serve(async (req: Request) => {
{
accountId: accountDefaults.data.workInProgressAccount,
description: "WIP Account",
- amount: debit("asset", cost),
+ amount: round(debit("asset", cost)),
quantity: 1,
documentType: "Production Event",
documentId: jobId,
@@ -255,7 +256,7 @@ serve(async (req: Request) => {
{
accountId: accountDefaults.data.laborAbsorptionAccount!,
description: "Labor/Machine Absorption",
- amount: credit("expense", cost),
+ amount: round(credit("expense", cost)),
quantity: 1,
documentType: "Production Event",
documentId: jobId,
@@ -270,7 +271,7 @@ serve(async (req: Request) => {
{
accountId: accountDefaults.data.workInProgressAccount,
description: "WIP Account (Overhead)",
- amount: debit("asset", overheadCost),
+ amount: round(debit("asset", overheadCost)),
quantity: 1,
documentType: "Production Event",
documentId: jobId,
@@ -281,7 +282,7 @@ serve(async (req: Request) => {
{
accountId: overheadAbsorptionAccount!,
description: "Overhead Absorption",
- amount: credit("expense", overheadCost),
+ amount: round(credit("expense", overheadCost)),
quantity: 1,
documentType: "Production Event",
documentId: jobId,
diff --git a/packages/database/supabase/functions/post-purchase-invoice/index.ts b/packages/database/supabase/functions/post-purchase-invoice/index.ts
index 14c4f6548c..bf33b40339 100644
--- a/packages/database/supabase/functions/post-purchase-invoice/index.ts
+++ b/packages/database/supabase/functions/post-purchase-invoice/index.ts
@@ -22,6 +22,7 @@ import {
getDefaultPostingGroup,
resolveInventoryAccount,
} from "../shared/get-posting-group.ts";
+import { round } from "../shared/precision.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -263,6 +264,8 @@ serve(async (req: Request) => {
accountId: entry.accountId,
accrual: entry.accrual,
description: `VOID: ${entry.description}`,
+ // A reversal is a sign flip of an already-posted value, which is
+ // exact — no rounding to do.
amount: -entry.amount,
quantity: -entry.quantity,
documentType: entry.documentType,
@@ -435,10 +438,10 @@ serve(async (req: Request) => {
documentId: child.documentId,
externalDocumentId: child.externalDocumentId,
itemId: child.itemId,
- quantity: child.quantity,
- nominalCost: -child.nominalCost,
- cost: -child.cost,
- remainingQuantity: child.remainingQuantity,
+ quantity: round(child.quantity),
+ nominalCost: round(-child.nominalCost),
+ cost: round(-child.cost),
+ remainingQuantity: round(child.remainingQuantity),
supplierId: child.supplierId,
companyId,
postingDate: today,
@@ -470,9 +473,9 @@ serve(async (req: Request) => {
documentId: layer.documentId,
externalDocumentId: layer.externalDocumentId,
itemId: layer.itemId,
- quantity: -layer.quantity,
- nominalCost: -layer.nominalCost,
- cost: -layer.cost,
+ quantity: round(-layer.quantity),
+ nominalCost: round(-layer.nominalCost),
+ cost: round(-layer.cost),
remainingQuantity: 0,
supplierId: layer.supplierId,
companyId,
@@ -879,7 +882,7 @@ serve(async (req: Request) => {
itemLedgerInserts.push({
postingDate: today,
itemId: invoiceLine.itemId!,
- quantity: invoiceLineQuantityInInventoryUnit,
+ quantity: round(invoiceLineQuantityInInventoryUnit),
locationId: invoiceLine.locationId,
storageUnitId: invoiceLine.storageUnitId,
entryType: "Positive Adjmt.",
@@ -905,11 +908,12 @@ serve(async (req: Request) => {
externalDocumentId:
purchaseInvoice.data?.supplierReference ?? undefined,
itemId: invoiceLine.itemId,
- quantity: invoiceLineQuantityInInventoryUnit,
- nominalCost:
- invoiceLine.quantity * (invoiceLine.unitPrice ?? 0),
- cost: totalLineCostWithWeightedShipping,
- remainingQuantity: invoiceLineQuantityInInventoryUnit,
+ quantity: round(invoiceLineQuantityInInventoryUnit),
+ nominalCost: round(
+ invoiceLine.quantity * (invoiceLine.unitPrice ?? 0)
+ ),
+ cost: round(totalLineCostWithWeightedShipping),
+ remainingQuantity: round(invoiceLineQuantityInInventoryUnit),
supplierId: purchaseInvoice.data?.supplierId,
companyId,
postingDate: today,
@@ -941,8 +945,8 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: debitAccount,
description: debitDescription,
- amount: debit("asset", totalLineCostWithWeightedShipping),
- quantity: invoiceLineQuantityInInventoryUnit,
+ amount: round(debit("asset", totalLineCostWithWeightedShipping)),
+ quantity: round(invoiceLineQuantityInInventoryUnit),
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
externalDocumentId: purchaseInvoice.data?.supplierReference,
@@ -953,8 +957,8 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: accountDefaults.data.payablesAccount,
description: "Accounts Payable",
- amount: credit("liability", totalLineCostWithWeightedShipping),
- quantity: invoiceLineQuantityInInventoryUnit,
+ amount: round(credit("liability", totalLineCostWithWeightedShipping)),
+ quantity: round(invoiceLineQuantityInInventoryUnit),
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
externalDocumentId: purchaseInvoice.data?.supplierReference,
@@ -1089,8 +1093,8 @@ serve(async (req: Request) => {
accountId:
accountDefaults.data.goodsReceivedNotInvoicedAccount,
description: "GR/IR Clearing",
- amount: debit("liability", receiptCostForReversedQty),
- quantity: quantityToReverse,
+ amount: round(debit("liability", receiptCostForReversedQty)),
+ quantity: round(quantityToReverse),
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
externalDocumentId: purchaseInvoice.data?.supplierReference,
@@ -1198,10 +1202,10 @@ serve(async (req: Request) => {
externalDocumentId:
purchaseInvoice.data?.supplierReference ?? undefined,
itemId: invoiceLine.itemId,
- quantity: entry.appliedQuantity,
- nominalCost: entry.adjustmentCost,
- cost: entry.adjustmentCost,
- remainingQuantity: entry.appliedQuantity,
+ quantity: round(entry.appliedQuantity),
+ nominalCost: round(entry.adjustmentCost),
+ cost: round(entry.adjustmentCost),
+ remainingQuantity: round(entry.appliedQuantity),
supplierId: purchaseInvoice.data?.supplierId,
companyId,
postingDate: today,
@@ -1257,13 +1261,15 @@ serve(async (req: Request) => {
externalDocumentId:
purchaseInvoice.data?.supplierReference ?? undefined,
itemId: invoiceLine.itemId,
- quantity: coveredQuantity,
- nominalCost:
- coveredQuantity * invoiceLineUnitCostInInventoryUnit,
- cost:
+ quantity: round(coveredQuantity),
+ nominalCost: round(
+ coveredQuantity * invoiceLineUnitCostInInventoryUnit
+ ),
+ cost: round(
receiptCostForReversedQty * coverageRatio +
- allocation.inventoryShare,
- remainingQuantity: coveredQuantity,
+ allocation.inventoryShare
+ ),
+ remainingQuantity: round(coveredQuantity),
supplierId: purchaseInvoice.data?.supplierId,
companyId,
postingDate: today,
@@ -1286,8 +1292,8 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: inventoryAccount.account,
description: inventoryAccount.description,
- amount: debit("asset", allocation.inventoryShare),
- quantity: quantityToReverse,
+ amount: round(debit("asset", allocation.inventoryShare)),
+ quantity: round(quantityToReverse),
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
externalDocumentId: purchaseInvoice.data?.supplierReference,
@@ -1304,8 +1310,8 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: accountDefaults.data.purchaseVarianceAccount,
description: "Purchase Price Variance",
- amount: debit("expense", allocation.ppvShare),
- quantity: quantityToReverse,
+ amount: round(debit("expense", allocation.ppvShare)),
+ quantity: round(quantityToReverse),
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
externalDocumentId: purchaseInvoice.data?.supplierReference,
@@ -1321,8 +1327,8 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: accountDefaults.data.payablesAccount,
description: "Accounts Payable",
- amount: credit("liability", invoiceCostForReversedQty),
- quantity: quantityToReverse,
+ amount: round(credit("liability", invoiceCostForReversedQty)),
+ quantity: round(quantityToReverse),
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
externalDocumentId: purchaseInvoice.data?.supplierReference,
@@ -1373,8 +1379,8 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: accountDefaults.data.indirectCostAccount,
description: "Indirect Cost Account",
- amount: debit("asset", accrualCost),
- quantity: quantityToAccrue,
+ amount: round(debit("asset", accrualCost)),
+ quantity: round(quantityToAccrue),
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
externalDocumentId: purchaseInvoice.data?.supplierReference,
@@ -1393,8 +1399,8 @@ serve(async (req: Request) => {
accountDefaults.data.goodsReceivedNotInvoicedAccount,
description: "GR/IR Clearing",
accrual: true,
- amount: debit("liability", accrualCost),
- quantity: quantityToAccrue,
+ amount: round(debit("liability", accrualCost)),
+ quantity: round(quantityToAccrue),
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
externalDocumentId: purchaseInvoice.data?.supplierReference,
@@ -1413,8 +1419,8 @@ serve(async (req: Request) => {
accountId: accountDefaults.data.payablesAccount,
description: "Accounts Payable",
accrual: isService ? undefined : true,
- amount: credit("liability", accrualCost),
- quantity: quantityToAccrue,
+ amount: round(credit("liability", accrualCost)),
+ quantity: round(quantityToAccrue),
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
externalDocumentId: purchaseInvoice.data?.supplierReference,
@@ -1514,8 +1520,8 @@ serve(async (req: Request) => {
accountId:
accountDefaults.data.goodsReceivedNotInvoicedAccount,
description: "GR/IR Clearing",
- amount: debit("liability", receiptCost),
- quantity: invoiceLineQuantityInInventoryUnit,
+ amount: round(debit("liability", receiptCost)),
+ quantity: round(invoiceLineQuantityInInventoryUnit),
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
externalDocumentId: purchaseInvoice.data?.supplierReference,
@@ -1530,8 +1536,8 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: accountDefaults.data.purchaseVarianceAccount,
description: "Purchase Price Variance",
- amount: debit("expense", variance),
- quantity: invoiceLineQuantityInInventoryUnit,
+ amount: round(debit("expense", variance)),
+ quantity: round(invoiceLineQuantityInInventoryUnit),
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
externalDocumentId: purchaseInvoice.data?.supplierReference,
@@ -1547,8 +1553,8 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: accountDefaults.data.payablesAccount,
description: "Accounts Payable",
- amount: credit("liability", invoiceCost),
- quantity: invoiceLineQuantityInInventoryUnit,
+ amount: round(credit("liability", invoiceCost)),
+ quantity: round(invoiceLineQuantityInInventoryUnit),
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
externalDocumentId: purchaseInvoice.data?.supplierReference,
@@ -1599,8 +1605,8 @@ serve(async (req: Request) => {
accountId: (assetRecord.data.fixedAssetClass as any)
.assetAccountId,
description: "Fixed Asset Acquisition",
- amount: debit("asset", totalLineCostWithWeightedShipping),
- quantity: invoiceLineQuantityInInventoryUnit,
+ amount: round(debit("asset", totalLineCostWithWeightedShipping)),
+ quantity: round(invoiceLineQuantityInInventoryUnit),
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
externalDocumentId: purchaseInvoice.data?.supplierReference,
@@ -1616,8 +1622,8 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: accountDefaults.data.payablesAccount,
description: "Accounts Payable",
- amount: credit("liability", totalLineCostWithWeightedShipping),
- quantity: invoiceLineQuantityInInventoryUnit,
+ amount: round(credit("liability", totalLineCostWithWeightedShipping)),
+ quantity: round(invoiceLineQuantityInInventoryUnit),
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
externalDocumentId: purchaseInvoice.data?.supplierReference,
@@ -1692,8 +1698,8 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: account.data.id,
description: account.data.name!,
- amount: debit("asset", totalLineCostWithWeightedShipping),
- quantity: invoiceLineQuantityInInventoryUnit,
+ amount: round(debit("asset", totalLineCostWithWeightedShipping)),
+ quantity: round(invoiceLineQuantityInInventoryUnit),
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
externalDocumentId: purchaseInvoice.data?.supplierReference,
@@ -1709,8 +1715,8 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: accountDefaults.data.payablesAccount,
description: "Accounts Payable",
- amount: credit("liability", totalLineCostWithWeightedShipping),
- quantity: invoiceLineQuantityInInventoryUnit,
+ amount: round(credit("liability", totalLineCostWithWeightedShipping)),
+ quantity: round(invoiceLineQuantityInInventoryUnit),
documentType: "Invoice",
documentId: purchaseInvoice.data?.id,
externalDocumentId: purchaseInvoice.data?.supplierReference,
diff --git a/packages/database/supabase/functions/post-receipt/index.ts b/packages/database/supabase/functions/post-receipt/index.ts
index be44909279..9f33821d9e 100644
--- a/packages/database/supabase/functions/post-receipt/index.ts
+++ b/packages/database/supabase/functions/post-receipt/index.ts
@@ -19,6 +19,7 @@ import {
getDefaultPostingGroup,
resolveInventoryAccount,
} from "../shared/get-posting-group.ts";
+import { round } from "../shared/precision.ts";
import {
resolveFeatureSamplingPlan,
resolveSamplingPlan,
@@ -269,6 +270,8 @@ serve(async (req: Request) => {
accountId: entry.accountId,
accrual: entry.accrual,
description: `VOID: ${entry.description}`,
+ // A reversal is a sign flip of an already-posted value, which is
+ // exact — no rounding to do.
amount: -entry.amount,
quantity: -entry.quantity,
documentType: entry.documentType,
@@ -1138,8 +1141,8 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: accountDefaults.data.goodsReceivedNotInvoicedAccount,
description: "Goods Received Not Invoiced",
- amount: debit("liability", cost),
- quantity: absReceivedQuantity,
+ amount: round(debit("liability", cost)),
+ quantity: round(absReceivedQuantity),
documentType: "Receipt",
documentId: receipt.data?.id ?? undefined,
externalDocumentId:
@@ -1155,8 +1158,8 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: debitAccount,
description: debitDescription,
- amount: credit("asset", cost),
- quantity: absReceivedQuantity,
+ amount: round(credit("asset", cost)),
+ quantity: round(absReceivedQuantity),
documentType: "Receipt",
documentId: receipt.data?.id ?? undefined,
externalDocumentId:
@@ -1183,8 +1186,8 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: debitAccount,
description: debitDescription,
- amount: debit("asset", glCost),
- quantity: absReceivedQuantity,
+ amount: round(debit("asset", glCost)),
+ quantity: round(absReceivedQuantity),
documentType: "Receipt",
documentId: receipt.data?.id ?? undefined,
externalDocumentId:
@@ -1199,8 +1202,8 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: accountDefaults.data.goodsReceivedNotInvoicedAccount,
description: "Goods Received Not Invoiced",
- amount: credit("liability", glCost),
- quantity: absReceivedQuantity,
+ amount: round(credit("liability", glCost)),
+ quantity: round(absReceivedQuantity),
documentType: "Receipt",
documentId: receipt.data?.id ?? undefined,
externalDocumentId:
@@ -1236,10 +1239,10 @@ serve(async (req: Request) => {
externalDocumentId:
receipt.data?.externalDocumentId ?? undefined,
itemId: receiptLine.itemId,
- quantity: invoiceFirstQty,
- nominalCost: invoiceFirstQty * (receiptLine.unitPrice ?? 0),
- cost: invoiceFirstPortionCost,
- remainingQuantity: invoiceFirstQty,
+ quantity: round(invoiceFirstQty),
+ nominalCost: round(invoiceFirstQty * (receiptLine.unitPrice ?? 0)),
+ cost: round(invoiceFirstPortionCost),
+ remainingQuantity: round(invoiceFirstQty),
supplierId: purchaseOrder.data?.supplierId ?? undefined,
companyId,
postingDate: today,
@@ -1257,10 +1260,10 @@ serve(async (req: Request) => {
externalDocumentId:
receipt.data?.externalDocumentId ?? undefined,
itemId: receiptLine.itemId,
- quantity: normalQty,
- nominalCost: normalQty * (receiptLine.unitPrice ?? 0),
- cost: normalPortionCost,
- remainingQuantity: normalQty,
+ quantity: round(normalQty),
+ nominalCost: round(normalQty * (receiptLine.unitPrice ?? 0)),
+ cost: round(normalPortionCost),
+ remainingQuantity: round(normalQty),
supplierId: purchaseOrder.data?.supplierId ?? undefined,
companyId,
postingDate: today,
@@ -1276,7 +1279,7 @@ serve(async (req: Request) => {
itemLedgerInserts.push({
postingDate: today,
itemId: receiptLine.itemId,
- quantity: receivedQuantity,
+ quantity: round(receivedQuantity),
locationId: receiptLine.locationId,
storageUnitId: receiptLine.storageUnitId,
entryType,
@@ -1295,7 +1298,7 @@ serve(async (req: Request) => {
itemLedgerInserts.push({
postingDate: today,
itemId: receiptLine.itemId,
- quantity: receivedQuantity,
+ quantity: round(receivedQuantity),
locationId: receiptLine.locationId,
storageUnitId: receiptLine.storageUnitId,
entryType,
@@ -1342,7 +1345,7 @@ serve(async (req: Request) => {
itemLedgerInserts.push({
postingDate: today,
itemId: receiptLine.itemId,
- quantity: quantityPerEntry,
+ quantity: round(quantityPerEntry),
locationId: receiptLine.locationId,
storageUnitId: receiptLine.storageUnitId,
entryType,
@@ -1429,8 +1432,8 @@ serve(async (req: Request) => {
accountId: (assetRecord.data.fixedAssetClass as any)
.assetAccountId,
description: "Fixed Asset Acquisition",
- amount: debit("asset", cost),
- quantity,
+ amount: round(debit("asset", cost)),
+ quantity: round(quantity),
documentType: "Receipt",
documentId: receipt.data?.id ?? undefined,
externalDocumentId:
@@ -1443,8 +1446,8 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: accountDefaults.data.goodsReceivedNotInvoicedAccount,
description: "Goods Received Not Invoiced",
- amount: credit("liability", cost),
- quantity,
+ amount: round(credit("liability", cost)),
+ quantity: round(quantity),
documentType: "Receipt",
documentId: receipt.data?.id ?? undefined,
externalDocumentId:
@@ -1527,14 +1530,13 @@ serve(async (req: Request) => {
? cogsResult.totalCost
: consumption.fallbackCost;
if (consumption.grIrLineIndex !== null) {
- journalLineInserts[consumption.grIrLineIndex].amount = debit(
- "liability",
- consumedCost
+ journalLineInserts[consumption.grIrLineIndex].amount = round(
+ debit("liability", consumedCost)
);
}
if (consumption.inventoryLineIndex !== null) {
journalLineInserts[consumption.inventoryLineIndex].amount =
- credit("asset", consumedCost);
+ round(credit("asset", consumedCost));
}
costLedgerInserts.push({
itemLedgerType: "Purchase",
@@ -1543,8 +1545,8 @@ serve(async (req: Request) => {
documentType: "Purchase Receipt",
documentId: receipt.data?.id ?? undefined,
itemId: consumption.itemId,
- quantity: -consumption.quantity,
- cost: -consumedCost,
+ quantity: round(-consumption.quantity),
+ cost: round(-consumedCost),
remainingQuantity: 0,
supplierId: purchaseOrder.data?.supplierId ?? undefined,
companyId,
@@ -1650,11 +1652,11 @@ serve(async (req: Request) => {
const layerQty = rowQty - excludedQty;
if (layerQty <= 0) continue;
const scale = layerQty / rowQty;
- insertRow.quantity = layerQty;
- insertRow.cost = Number(insertRow.cost ?? 0) * scale;
+ insertRow.quantity = round(layerQty);
+ insertRow.cost = round(Number(insertRow.cost ?? 0) * scale);
insertRow.nominalCost =
- Number(insertRow.nominalCost ?? 0) * scale;
- insertRow.remainingQuantity = layerQty;
+ round(Number(insertRow.nominalCost ?? 0) * scale);
+ insertRow.remainingQuantity = round(layerQty);
}
}
costLedgerRows.push(insertRow);
@@ -2096,8 +2098,8 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: inventoryAccount.account,
description: `Transfer Out - ${warehouseTransfer.data?.transferId}`,
- amount: credit("asset", totalValue),
- quantity: Math.abs(receivedQuantity),
+ amount: round(credit("asset", totalValue)),
+ quantity: round(Math.abs(receivedQuantity)),
documentType: "Receipt",
documentId: receipt.data?.id,
externalDocumentId: warehouseTransfer.data?.transferId,
@@ -2109,8 +2111,8 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: inventoryAccount.account,
description: `Transfer In - ${warehouseTransfer.data?.transferId}`,
- amount: debit("asset", totalValue),
- quantity: Math.abs(receivedQuantity),
+ amount: round(debit("asset", totalValue)),
+ quantity: round(Math.abs(receivedQuantity)),
documentType: "Receipt",
documentId: receipt.data?.id,
externalDocumentId: warehouseTransfer.data?.transferId,
diff --git a/packages/database/supabase/functions/post-sales-invoice/index.ts b/packages/database/supabase/functions/post-sales-invoice/index.ts
index 4eb8e4c318..d396d096e0 100644
--- a/packages/database/supabase/functions/post-sales-invoice/index.ts
+++ b/packages/database/supabase/functions/post-sales-invoice/index.ts
@@ -15,6 +15,7 @@ import {
getDefaultPostingGroup,
resolveInventoryAccount,
} from "../shared/get-posting-group.ts";
+import { round } from "../shared/precision.ts";
import { calculateCOGS } from "../shared/calculate-cogs.ts";
const pool = getConnectionPool(1);
@@ -396,7 +397,7 @@ serve(async (req: Request) => {
itemLedgerInserts.push({
postingDate: today,
itemId: invoiceLine.itemId!,
- quantity: -invoiceLineQuantityInInventoryUnit,
+ quantity: round(-invoiceLineQuantityInInventoryUnit),
locationId: invoiceLine.locationId,
storageUnitId: invoiceLine.storageUnitId,
entryType: "Negative Adjmt.",
@@ -423,11 +424,10 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: accountDefaults.data.salesAccount,
description: "Sales Account",
- amount: credit(
- "revenue",
- totalLineCostWithWeightedShipping
+ amount: round(
+ credit("revenue", totalLineCostWithWeightedShipping)
),
- quantity: invoiceLineQuantityInInventoryUnit,
+ quantity: round(invoiceLineQuantityInInventoryUnit),
documentType: "Invoice",
documentId: salesInvoice.data?.id,
externalDocumentId: salesInvoice.data?.customerReference,
@@ -444,8 +444,8 @@ serve(async (req: Request) => {
description: isIntercompany
? "IC Receivables"
: "Accounts Receivable",
- amount: debit("asset", totalLineCostWithWeightedShipping),
- quantity: invoiceLineQuantityInInventoryUnit,
+ amount: round(debit("asset", totalLineCostWithWeightedShipping)),
+ quantity: round(invoiceLineQuantityInInventoryUnit),
documentType: "Invoice",
documentId: salesInvoice.data?.id,
externalDocumentId: salesInvoice.data?.customerReference,
@@ -475,7 +475,7 @@ serve(async (req: Request) => {
accountId: accountDefaults.data.costOfGoodsSoldAccount,
description: "Cost of Goods Sold",
amount: 0,
- quantity: invoiceLineQuantityInInventoryUnit,
+ quantity: round(invoiceLineQuantityInInventoryUnit),
documentType: "Invoice",
documentId: salesInvoice.data?.id,
externalDocumentId: salesInvoice.data?.customerReference,
@@ -491,7 +491,7 @@ serve(async (req: Request) => {
accountId: inventoryAccount.account,
description: inventoryAccount.description,
amount: 0,
- quantity: invoiceLineQuantityInInventoryUnit,
+ quantity: round(invoiceLineQuantityInInventoryUnit),
documentType: "Invoice",
documentId: salesInvoice.data?.id,
externalDocumentId: salesInvoice.data?.customerReference,
@@ -521,11 +521,10 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: accountDefaults.data.salesAccount,
description: "Sales Account",
- amount: credit(
- "revenue",
- totalLineCostWithWeightedShipping
+ amount: round(
+ credit("revenue", totalLineCostWithWeightedShipping)
),
- quantity: invoiceLineQuantityInInventoryUnit,
+ quantity: round(invoiceLineQuantityInInventoryUnit),
documentType: "Invoice",
documentId: salesInvoice.data?.id,
externalDocumentId: salesInvoice.data?.customerReference,
@@ -544,8 +543,8 @@ serve(async (req: Request) => {
description: isIntercompany
? "IC Receivables"
: "Accounts Receivable",
- amount: debit("asset", totalLineCostWithWeightedShipping),
- quantity: invoiceLineQuantityInInventoryUnit,
+ amount: round(debit("asset", totalLineCostWithWeightedShipping)),
+ quantity: round(invoiceLineQuantityInInventoryUnit),
documentType: "Invoice",
documentId: salesInvoice.data?.id,
externalDocumentId: salesInvoice.data?.customerReference,
@@ -644,8 +643,8 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: receivablesAccountId,
description: "Accounts Receivable",
- amount: debit("asset", saleProceeds),
- quantity: invoiceLineQuantityInInventoryUnit,
+ amount: round(debit("asset", saleProceeds)),
+ quantity: round(invoiceLineQuantityInInventoryUnit),
documentType: "Invoice",
documentId: salesInvoice.data?.id ?? undefined,
externalDocumentId:
@@ -663,8 +662,8 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: writeOffAccountId,
description: "Clear disposal clearing",
- amount: credit("expense", nbv),
- quantity: invoiceLineQuantityInInventoryUnit,
+ amount: round(credit("expense", nbv)),
+ quantity: round(invoiceLineQuantityInInventoryUnit),
documentType: "Invoice",
documentId: salesInvoice.data?.id ?? undefined,
externalDocumentId:
@@ -700,9 +699,9 @@ serve(async (req: Request) => {
gainLoss > 0 ? "Gain on disposal" : "Loss on disposal",
amount:
gainLoss > 0
- ? credit("revenue", gainLoss)
- : debit("expense", -gainLoss),
- quantity: invoiceLineQuantityInInventoryUnit,
+ ? round(credit("revenue", gainLoss))
+ : round(debit("expense", -gainLoss)),
+ quantity: round(invoiceLineQuantityInInventoryUnit),
documentType: "Invoice",
documentId: salesInvoice.data?.id ?? undefined,
externalDocumentId:
@@ -786,7 +785,7 @@ serve(async (req: Request) => {
accountId:
assetClass.accumulatedDepreciationAccountId,
description: "Clear accumulated depreciation",
- amount: debit("asset", accumulatedDepreciation),
+ amount: round(debit("asset", accumulatedDepreciation)),
quantity: 1,
documentType: "Invoice",
documentId: salesInvoice.data?.id ?? undefined,
@@ -804,7 +803,7 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: assetClass.assetAccountId,
description: "Remove asset at cost",
- amount: credit("asset", acquisitionCost),
+ amount: round(credit("asset", acquisitionCost)),
quantity: 1,
documentType: "Invoice",
documentId: salesInvoice.data?.id ?? undefined,
@@ -821,8 +820,8 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: receivablesAccountId,
description: "Accounts Receivable",
- amount: debit("asset", saleProceeds),
- quantity: invoiceLineQuantityInInventoryUnit,
+ amount: round(debit("asset", saleProceeds)),
+ quantity: round(invoiceLineQuantityInInventoryUnit),
documentType: "Invoice",
documentId: salesInvoice.data?.id ?? undefined,
externalDocumentId:
@@ -848,8 +847,8 @@ serve(async (req: Request) => {
gainLoss > 0 ? "Gain on disposal" : "Loss on disposal",
amount:
gainLoss > 0
- ? credit("revenue", gainLoss)
- : debit("expense", -gainLoss),
+ ? round(credit("revenue", gainLoss))
+ : round(debit("expense", -gainLoss)),
quantity: 1,
documentType: "Invoice",
documentId: salesInvoice.data?.id ?? undefined,
@@ -1056,11 +1055,15 @@ serve(async (req: Request) => {
if (
jl.description === "Cost of Goods Sold" &&
jl.amount === 0 &&
- jl.quantity === directLine.quantity
+ jl.quantity === round(directLine.quantity)
) {
- journalLineInserts[i].amount = debit("expense", cogsResult.totalCost);
+ journalLineInserts[i].amount = round(
+ debit("expense", cogsResult.totalCost)
+ );
if (i + 1 < journalLineInserts.length) {
- journalLineInserts[i + 1].amount = credit("asset", cogsResult.totalCost);
+ journalLineInserts[i + 1].amount = round(
+ credit("asset", cogsResult.totalCost)
+ );
}
await trx
@@ -1072,8 +1075,8 @@ serve(async (req: Request) => {
documentType: "Sales Shipment",
documentId: salesInvoice.data?.id ?? "",
itemId: directLine.itemId,
- quantity: -directLine.quantity,
- cost: -cogsResult.totalCost,
+ quantity: round(-directLine.quantity),
+ cost: round(-cogsResult.totalCost),
remainingQuantity: 0,
companyId,
postingDate: today,
@@ -1233,7 +1236,7 @@ serve(async (req: Request) => {
sourceCompanyId: companyId,
targetCompanyId: intercompanyPartnerId,
sourceJournalLineId: icJournalLineId,
- amount: totalLinesCost,
+ amount: round(totalLinesCost),
currencyCode: salesInvoice.data?.currencyCode ?? "USD",
description: `Sales Invoice ${salesInvoice.data?.invoiceId}`,
documentType: "Invoice",
@@ -1368,7 +1371,9 @@ serve(async (req: Request) => {
? journalEntries.map((entry) => ({
accountId: entry.accountId,
description: `VOID: ${entry.description}`,
- amount: -entry.amount, // Reverse the amount
+ // A reversal is a sign flip of an already-posted value, which is
+ // exact — no rounding to do.
+ amount: -entry.amount,
quantity: -entry.quantity,
documentType: "Invoice" as const,
documentId: salesInvoice.data?.id,
@@ -1394,7 +1399,7 @@ serve(async (req: Request) => {
reversingItemLedgerEntries.push({
postingDate: today,
itemId: entry.itemId,
- quantity: -entry.quantity, // Reverse the quantity
+ quantity: -entry.quantity,
locationId: entry.locationId,
storageUnitId: entry.storageUnitId,
entryType:
diff --git a/packages/database/supabase/functions/post-shipment/index.ts b/packages/database/supabase/functions/post-shipment/index.ts
index cb9f83a145..67f992bcea 100644
--- a/packages/database/supabase/functions/post-shipment/index.ts
+++ b/packages/database/supabase/functions/post-shipment/index.ts
@@ -15,6 +15,7 @@ import {
getDefaultPostingGroup,
resolveInventoryAccount,
} from "../shared/get-posting-group.ts";
+import { round } from "../shared/precision.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -348,7 +349,7 @@ serve(async (req: Request) => {
itemLedgerInserts.push({
postingDate: today,
itemId: shipmentLine.itemId,
- quantity: -shippedQuantity,
+ quantity: round(-shippedQuantity),
locationId: shipmentLine.locationId ?? locationId,
storageUnitId: shipmentLine.storageUnitId,
entryType: "Negative Adjmt.",
@@ -364,7 +365,7 @@ serve(async (req: Request) => {
itemLedgerInserts.push({
postingDate: today,
itemId: shipmentLine.itemId,
- quantity: -shippedQuantity,
+ quantity: round(-shippedQuantity),
locationId: shipmentLine.locationId ?? locationId,
storageUnitId: shipmentLine.storageUnitId,
entryType: "Negative Adjmt.",
@@ -437,7 +438,7 @@ serve(async (req: Request) => {
accountId: accountDefaults.data.costOfGoodsSoldAccount,
description: "Cost of Goods Sold",
amount: 0,
- quantity: shippedQuantity,
+ quantity: round(shippedQuantity),
documentType: "Sales Shipment",
documentId: shipment.data?.id,
externalDocumentId: salesOrder.data?.customerReference ?? undefined,
@@ -454,7 +455,7 @@ serve(async (req: Request) => {
accountId: inventoryAccount.account,
description: inventoryAccount.description,
amount: 0,
- quantity: shippedQuantity,
+ quantity: round(shippedQuantity),
documentType: "Sales Shipment",
documentId: shipment.data?.id,
externalDocumentId: salesOrder.data?.customerReference ?? undefined,
@@ -590,7 +591,7 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: assetClass.accumulatedDepreciationAccountId,
description: "Clear accumulated depreciation",
- amount: debit("asset", accumulatedDepreciation),
+ amount: round(debit("asset", accumulatedDepreciation)),
quantity: 1,
documentType: "Sales Shipment",
documentId: shipment.data?.id,
@@ -622,7 +623,7 @@ serve(async (req: Request) => {
// holding, not a P&L loss) until the invoice recognizes
// proceeds and clears it back to zero — no interim full loss.
description: "Transfer net book value to disposal clearing",
- amount: debit("expense", nbv),
+ amount: round(debit("expense", nbv)),
quantity: 1,
documentType: "Sales Shipment",
documentId: shipment.data?.id,
@@ -649,7 +650,7 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountId: assetClass.assetAccountId,
description: "Remove asset at cost",
- amount: credit("asset", acquisitionCost),
+ amount: round(credit("asset", acquisitionCost)),
quantity: 1,
documentType: "Sales Shipment",
documentId: shipment.data?.id,
@@ -967,7 +968,12 @@ serve(async (req: Request) => {
.where("id", "=", splitInfo.originalEntityId)
.execute();
- itemLedgerInserts.push(...split.ledgerInserts);
+ itemLedgerInserts.push(
+ ...split.ledgerInserts.map((ledgerRow) => ({
+ ...ledgerRow,
+ quantity: round(ledgerRow.quantity),
+ }))
+ );
// The shipment's own ledger rows (built per line above)
// and its activity input book against the shipped child.
@@ -1091,8 +1097,12 @@ serve(async (req: Request) => {
: (lineQty / info.totalQuantity) * cogsResult.totalCost;
costAssigned += lineCost;
- journalLineInserts[jlIdx].amount = debit("expense", lineCost);
- journalLineInserts[jlIdx + 1].amount = credit("asset", lineCost);
+ journalLineInserts[jlIdx].amount = round(
+ debit("expense", lineCost)
+ );
+ journalLineInserts[jlIdx + 1].amount = round(
+ credit("asset", lineCost)
+ );
}
await trx
@@ -1104,8 +1114,8 @@ serve(async (req: Request) => {
documentType: "Sales Shipment",
documentId: shipment.data?.id ?? "",
itemId,
- quantity: -info.totalQuantity,
- cost: -cogsResult.totalCost,
+ quantity: round(-info.totalQuantity),
+ cost: round(-cogsResult.totalCost),
remainingQuantity: 0,
companyId,
postingDate: today,
@@ -1679,7 +1689,7 @@ serve(async (req: Request) => {
itemLedgerInserts.push({
postingDate: today,
itemId: shipmentLine.itemId,
- quantity: -shippedQuantity, // Negative for outbound transfer
+ quantity: round(-shippedQuantity), // Negative for outbound transfer
locationId: shipmentLine.locationId,
storageUnitId: shipmentLine.storageUnitId,
entryType: "Transfer",
@@ -1828,6 +1838,8 @@ serve(async (req: Request) => {
accountId: entry.accountId,
accrual: entry.accrual,
description: `VOID: ${entry.description}`,
+ // A reversal is a sign flip of an already-posted value, which
+ // is exact — no rounding to do.
amount: -entry.amount,
quantity: -entry.quantity,
documentType: entry.documentType,
@@ -1941,7 +1953,7 @@ serve(async (req: Request) => {
itemLedgerInserts.push({
postingDate: today,
itemId: shipmentLine.itemId,
- quantity: shippedQuantity, // Positive to restore inventory
+ quantity: round(shippedQuantity), // Positive to restore inventory
locationId: shipmentLine.locationId ?? locationId,
storageUnitId: shipmentLine.storageUnitId,
entryType: "Positive Adjmt.",
@@ -1957,7 +1969,7 @@ serve(async (req: Request) => {
itemLedgerInserts.push({
postingDate: today,
itemId: shipmentLine.itemId,
- quantity: shippedQuantity, // Positive to restore inventory
+ quantity: round(shippedQuantity), // Positive to restore inventory
locationId: shipmentLine.locationId ?? locationId,
storageUnitId: shipmentLine.storageUnitId,
entryType: "Positive Adjmt.",
@@ -2483,7 +2495,7 @@ serve(async (req: Request) => {
itemLedgerInserts.push({
postingDate: today,
itemId: shipmentLine.itemId,
- quantity: -shippedQuantity, // Negative to remove inventory
+ quantity: round(-shippedQuantity), // Negative to remove inventory
locationId: shipmentLine.locationId ?? locationId,
storageUnitId: shipmentLine.storageUnitId,
entryType: "Negative Adjmt.",
@@ -2499,7 +2511,7 @@ serve(async (req: Request) => {
itemLedgerInserts.push({
postingDate: today,
itemId: shipmentLine.itemId,
- quantity: -shippedQuantity, // Negative to remove inventory
+ quantity: round(-shippedQuantity), // Negative to remove inventory
locationId: shipmentLine.locationId ?? locationId,
storageUnitId: shipmentLine.storageUnitId,
entryType: "Negative Adjmt.",
@@ -2707,7 +2719,7 @@ serve(async (req: Request) => {
itemLedgerInserts.push({
postingDate: today,
itemId: shipmentLine.itemId,
- quantity: shippedQuantity, // Positive to restore inventory
+ quantity: round(shippedQuantity), // Positive to restore inventory
locationId: shipmentLine.locationId,
storageUnitId: shipmentLine.storageUnitId,
entryType: "Transfer",
diff --git a/packages/database/supabase/functions/post-stock-transfer/index.ts b/packages/database/supabase/functions/post-stock-transfer/index.ts
index 5ebc22fab2..d0269995a6 100644
--- a/packages/database/supabase/functions/post-stock-transfer/index.ts
+++ b/packages/database/supabase/functions/post-stock-transfer/index.ts
@@ -8,6 +8,7 @@ import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";
import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import type { Database } from "../lib/types.ts";
import { buildBatchSplitRecords } from "../shared/batch-split.ts";
+import { round } from "../shared/precision.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -167,7 +168,7 @@ serve(async (req: Request) => {
itemLedgerInserts.push({
postingDate: today,
itemId: stockTransferLine.itemId,
- quantity: -quantity,
+ quantity: round(-quantity),
locationId: locationId,
storageUnitId: stockTransferLine.fromStorageUnitId,
entryType: "Transfer",
@@ -180,7 +181,7 @@ serve(async (req: Request) => {
itemLedgerInserts.push({
postingDate: today,
itemId: stockTransferLine.itemId,
- quantity: quantity,
+ quantity: round(quantity),
locationId: locationId,
storageUnitId: stockTransferLine.toStorageUnitId,
entryType: "Transfer",
@@ -243,7 +244,7 @@ serve(async (req: Request) => {
itemLedgerInserts.push({
postingDate: today,
itemId: stockTransferLine.itemId,
- quantity: currentPickedQuantity, // Positive to restore inventory at from shelf
+ quantity: round(currentPickedQuantity), // Positive to restore inventory at from shelf
locationId: locationId,
storageUnitId: stockTransferLine.fromStorageUnitId,
entryType: "Transfer",
@@ -256,7 +257,7 @@ serve(async (req: Request) => {
itemLedgerInserts.push({
postingDate: today,
itemId: stockTransferLine.itemId,
- quantity: -currentPickedQuantity, // Negative to remove inventory from to shelf
+ quantity: round(-currentPickedQuantity), // Negative to remove inventory from to shelf
locationId: locationId,
storageUnitId: stockTransferLine.toStorageUnitId,
entryType: "Transfer",
@@ -519,7 +520,12 @@ serve(async (req: Request) => {
.where("id", "=", trackedEntityId)
.execute();
- itemLedgerInserts.push(...split.ledgerInserts);
+ itemLedgerInserts.push(
+ ...split.ledgerInserts.map((ledgerRow) => ({
+ ...ledgerRow,
+ quantity: round(ledgerRow.quantity),
+ }))
+ );
}
// Create transfer activity
@@ -567,7 +573,7 @@ serve(async (req: Request) => {
{
postingDate: today,
itemId: stockTransferLine.itemId,
- quantity: -transferQuantity,
+ quantity: round(-transferQuantity),
locationId: locationId,
storageUnitId: fromStorageUnitId,
entryType: "Transfer",
@@ -580,7 +586,7 @@ serve(async (req: Request) => {
{
postingDate: today,
itemId: stockTransferLine.itemId,
- quantity: transferQuantity,
+ quantity: round(transferQuantity),
locationId: locationId,
storageUnitId: stockTransferLine.toStorageUnitId,
entryType: "Transfer",
@@ -842,7 +848,7 @@ serve(async (req: Request) => {
{
postingDate: today,
itemId: stockTransferLine.itemId,
- quantity: -transferQuantity, // drain the child at the destination
+ quantity: round(-transferQuantity), // drain the child at the destination
locationId: locationId,
storageUnitId: stockTransferLine.toStorageUnitId,
entryType: "Negative Adjmt.",
@@ -855,7 +861,7 @@ serve(async (req: Request) => {
{
postingDate: today,
itemId: stockTransferLine.itemId,
- quantity: transferQuantity, // restore the parent at the source
+ quantity: round(transferQuantity), // restore the parent at the source
locationId: locationId,
storageUnitId: stockTransferLine.fromStorageUnitId,
entryType: "Positive Adjmt.",
@@ -950,7 +956,7 @@ serve(async (req: Request) => {
{
postingDate: today,
itemId: stockTransferLine.itemId,
- quantity: originalQuantity, // zero out the split entity
+ quantity: round(originalQuantity), // zero out the split entity
locationId: locationId,
storageUnitId: stockTransferLine.fromStorageUnitId,
entryType: "Positive Adjmt.",
@@ -963,7 +969,7 @@ serve(async (req: Request) => {
{
postingDate: today,
itemId: stockTransferLine.itemId,
- quantity: -transferQuantity, // Positive to restore to original entity
+ quantity: round(-transferQuantity), // Positive to restore to original entity
locationId: locationId,
storageUnitId: stockTransferLine.toStorageUnitId, // Both entities are on the source shelf
entryType: "Negative Adjmt.",
@@ -976,7 +982,7 @@ serve(async (req: Request) => {
{
postingDate: today,
itemId: stockTransferLine.itemId,
- quantity: -(originalQuantity - transferQuantity), // Positive to restore to original entity
+ quantity: round(-(originalQuantity - transferQuantity)), // Positive to restore to original entity
locationId: locationId,
storageUnitId: stockTransferLine.fromStorageUnitId, // Both entities are on the source shelf
entryType: "Negative Adjmt.",
@@ -1021,7 +1027,7 @@ serve(async (req: Request) => {
itemLedgerInserts.push({
postingDate: today,
itemId: stockTransferLine.itemId,
- quantity: transferQuantity, // Positive to restore inventory at from shelf
+ quantity: round(transferQuantity), // Positive to restore inventory at from shelf
locationId: locationId,
storageUnitId: stockTransferLine.fromStorageUnitId,
entryType: "Transfer",
@@ -1035,7 +1041,7 @@ serve(async (req: Request) => {
itemLedgerInserts.push({
postingDate: today,
itemId: stockTransferLine.itemId,
- quantity: -transferQuantity, // Negative to remove inventory from to shelf
+ quantity: round(-transferQuantity), // Negative to remove inventory from to shelf
locationId: locationId,
storageUnitId: stockTransferLine.toStorageUnitId,
entryType: "Transfer",
diff --git a/packages/database/supabase/functions/recalculate/index.ts b/packages/database/supabase/functions/recalculate/index.ts
index 0fe8cbb945..abe4d93478 100644
--- a/packages/database/supabase/functions/recalculate/index.ts
+++ b/packages/database/supabase/functions/recalculate/index.ts
@@ -7,6 +7,7 @@ import { Transaction } from "kysely";
import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
import { getJobMethodTree, JobMethodTreeItem } from "../lib/methods.ts";
import { requirePermissions } from "../lib/supabase.ts";
+import { scrapAllowance } from "../shared/precision.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -222,7 +223,8 @@ const updateJobQuantities = async (
// scrapQuantity = portion attributable to scrap
// totalWithScrap = target + scrap allowance (what we need to make/procure)
// estimatedQuantity: For Make = good quantity (without scrap), For Buy/Pick = total
- const scrapQuantity = targetQuantity * scrapPercentage;
+ // Whole-unit scrap allowance; the fractional target itself is never rounded
+ const scrapQuantity = scrapAllowance(targetQuantity, scrapPercentage);
const totalWithScrap = targetQuantity + scrapQuantity;
// For Make: estimatedQuantity is good quantity (without scrap)
// For Buy/Pick: estimatedQuantity includes scrap since that's what we procure
@@ -255,9 +257,8 @@ const updateJobQuantities = async (
.updateTable("jobOperation")
.set({
targetQuantity: targetQuantity,
- // Operation/production counts stay whole even when material
- // quantities are fractional
- operationQuantity: Math.ceil(totalWithScrap),
+ // Fractional targets flow through; the scrap allowance is already whole
+ operationQuantity: totalWithScrap,
})
.where("jobMakeMethodId", "=", tree.data.jobMaterialMakeMethodId)
.where("reworkId", "is", null)
@@ -270,7 +271,7 @@ const updateJobQuantities = async (
.set({
quantity: jobMakeMethod.requiresSerialTracking
? 1
- : Math.ceil(totalWithScrap),
+ : totalWithScrap,
})
.where("id", "=", jobMakeMethod.trackedEntityId)
.execute();
diff --git a/packages/database/supabase/functions/shared/post-adjustment.ts b/packages/database/supabase/functions/shared/post-adjustment.ts
index 9e971017fd..4801de6537 100644
--- a/packages/database/supabase/functions/shared/post-adjustment.ts
+++ b/packages/database/supabase/functions/shared/post-adjustment.ts
@@ -10,6 +10,7 @@ import {
AdjustmentItemCost,
computeCurrentUnitCost,
} from "./post-adjustment-cost.ts";
+import { round } from "./precision.ts";
export { computeCurrentUnitCost } from "./post-adjustment-cost.ts";
export type {
@@ -190,7 +191,7 @@ export async function bookAdjustment(
locationId: ledger.locationId,
storageUnitId: ledger.storageUnitId,
trackedEntityId: ledger.trackedEntityId,
- quantity: ledger.quantity,
+ quantity: round(ledger.quantity),
comment: ledger.comment ?? null,
scrapReasonId: ledger.scrapReasonId ?? null,
companyId,
@@ -230,8 +231,8 @@ export async function bookAdjustment(
documentType: ledger.documentType ?? null,
documentId,
itemId: ledger.itemId,
- quantity: -absQuantity,
- cost: -cogs.totalCost,
+ quantity: round(-absQuantity),
+ cost: round(-cogs.totalCost),
remainingQuantity: 0,
postingDate: ledger.postingDate,
companyId,
@@ -251,9 +252,9 @@ export async function bookAdjustment(
documentType: ledger.documentType ?? null,
documentId,
itemId: ledger.itemId,
- quantity: absQuantity,
- cost,
- remainingQuantity: absQuantity,
+ quantity: round(absQuantity),
+ cost: round(cost),
+ remainingQuantity: round(absQuantity),
postingDate: ledger.postingDate,
companyId,
})
@@ -318,9 +319,9 @@ export async function bookAdjustment(
documentType: ledger.documentType ?? null,
documentId,
itemId: ledger.itemId,
- quantity: absQuantity,
- cost,
- remainingQuantity: absQuantity,
+ quantity: round(absQuantity),
+ cost: round(cost),
+ remainingQuantity: round(absQuantity),
postingDate: ledger.postingDate,
companyId,
})
@@ -364,8 +365,8 @@ export async function bookAdjustment(
journalId,
accountId: inventoryAccount.account,
description: inventoryAccount.description,
- amount: isGain ? debit("asset", cost) : credit("asset", cost),
- quantity: absQuantity,
+ amount: round(isGain ? debit("asset", cost) : credit("asset", cost)),
+ quantity: round(absQuantity),
documentType: journalLineDocumentType,
documentId,
journalLineReference,
@@ -377,8 +378,8 @@ export async function bookAdjustment(
accounting.offsetAccount ??
accounting.accountDefaults.inventoryAdjustmentVarianceAccount,
description: accounting.offsetDescription ?? "Inventory Adjustment",
- amount: isGain ? credit("expense", cost) : debit("expense", cost),
- quantity: absQuantity,
+ amount: round(isGain ? credit("expense", cost) : debit("expense", cost)),
+ quantity: round(absQuantity),
documentType: journalLineDocumentType,
documentId,
journalLineReference,
diff --git a/packages/database/supabase/functions/shared/precision.ts b/packages/database/supabase/functions/shared/precision.ts
new file mode 100644
index 0000000000..509dce72e1
--- /dev/null
+++ b/packages/database/supabase/functions/shared/precision.ts
@@ -0,0 +1,86 @@
+/** Internal precision: prices, rates, quantities, ledger amounts. */
+export const SCALE = 5;
+
+/** One comparison tolerance. 5dp values are multiples of 1e-5; float noise is ~1e-12. */
+export const EPSILON = 1e-6;
+
+export const RoundingMode = {
+ /** Ties away from zero — matches Postgres round(). (Math.round(-2.5) = -2; Postgres = -3.) */
+ HalfUp: "halfUp",
+ /** Away from zero to the next step — scrap allowances. */
+ Up: "up"
+} as const;
+export type RoundingMode = (typeof RoundingMode)[keyof typeof RoundingMode];
+
+/** Exponent-shift: decimal-string round-trip, immune to 1.005-style float artifacts. */
+const shift = (value: number, exp: number): number => {
+ const [m, e = "0"] = value.toExponential().split("e");
+ return Number(`${m}e${Number(e) + exp}`);
+};
+
+export function round(
+ value: number,
+ scale: number = SCALE,
+ mode: RoundingMode = RoundingMode.HalfUp
+): number {
+ if (!Number.isFinite(value)) return value;
+ const fn =
+ mode === RoundingMode.Up
+ ? (n: number) => Math.sign(n) * Math.ceil(Math.abs(n))
+ : (n: number) => Math.sign(n) * Math.round(Math.abs(n));
+ return shift(fn(shift(value, scale)), -scale);
+}
+
+/** The extra whole units to make/procure to cover scrap at `rate`. Ceils to
+ * whole units — you cannot make a third of a part to throw away — while the
+ * fractional target itself is NEVER rounded (callers add the two).
+ * scrapAllowance(4.5, 0) === 0 -> total stays 4.5
+ * scrapAllowance(31, 0.01) === 1 -> total 32 */
+export function scrapAllowance(target: number, rate: number): number {
+ return round(target * rate, 0, RoundingMode.Up);
+}
+
+/** Tax/discount → settlement amount. `decimals` comes from currency.decimalPlaces — data, never a literal. */
+export function applyRate(base: number, rate: number, decimals: number): number {
+ return round(base * rate, decimals);
+}
+
+/** The other half of the value pair: recover the rate an absolute amount implies.
+ * Rounded to internal scale so the stored rate is a real 5dp fact, not a raw
+ * float. Precision only flows cleanly one way — a rate derived back from a
+ * cents-rounded amount is limited by that amount's scale. */
+export function deriveRate(amount: number, subtotal: number): number {
+ return subtotal > 0 ? round(amount / subtotal) : 0;
+}
+
+/** The ledger invariant, as a predicate. `tolerance` is a BUSINESS refusal
+ * threshold, distinct from EPSILON (the float-noise guard): multi-currency
+ * journals legitimately carry small cross-rate residuals, so callers pass their
+ * domain tolerance explicitly. The default EPSILON is for contexts that must
+ * balance exactly.
+ *
+ * Use this where the caller decides what an imbalance MEANS — a validator
+ * returning `{ data, error }`, or a filter listing unbalanced journals. Use
+ * assertBalanced where the only correct response is to refuse. */
+export function isBalanced(
+ debits: number,
+ credits: number,
+ tolerance: number = EPSILON
+): boolean {
+ return Math.abs(debits - credits) <= tolerance;
+}
+
+/** isBalanced, for posting paths where an imbalance can only mean "stop": throws
+ * with the drift so posting refuses rather than mis-posts. */
+export function assertBalanced(
+ debits: number,
+ credits: number,
+ tolerance: number = EPSILON,
+ label = "Journal"
+): void {
+ if (!isBalanced(debits, credits, tolerance)) {
+ throw new Error(
+ `${label} does not balance (off by ${round(debits - credits)}); refusing to post`
+ );
+ }
+}
diff --git a/packages/database/supabase/migrations/20260811123612_flip-purchasing-tax-percent-writable.sql b/packages/database/supabase/migrations/20260811123612_flip-purchasing-tax-percent-writable.sql
new file mode 100644
index 0000000000..4302eef97e
--- /dev/null
+++ b/packages/database/supabase/migrations/20260811123612_flip-purchasing-tax-percent-writable.sql
@@ -0,0 +1,12 @@
+-- Purchasing stored tax AMOUNTS and derived the RATE via a GENERATED column
+-- (rate = amount / subtotal), making the rate a lossy echo of a cents-rounded
+-- amount. DROP EXPRESSION converts each column to plain writable IN PLACE:
+-- values are already materialized -> catalog-only, no backfill, no view drops.
+ALTER TABLE "purchaseOrderLine" ALTER COLUMN "taxPercent" DROP EXPRESSION IF EXISTS;
+ALTER TABLE "purchaseOrderLine" ALTER COLUMN "taxPercent" SET DEFAULT 0;
+
+ALTER TABLE "purchaseInvoiceLine" ALTER COLUMN "taxPercent" DROP EXPRESSION IF EXISTS;
+ALTER TABLE "purchaseInvoiceLine" ALTER COLUMN "taxPercent" SET DEFAULT 0;
+
+ALTER TABLE "supplierQuoteLinePrice" ALTER COLUMN "taxPercent" DROP EXPRESSION IF EXISTS;
+ALTER TABLE "supplierQuoteLinePrice" ALTER COLUMN "taxPercent" SET DEFAULT 0;
diff --git a/packages/database/supabase/migrations/20260811123614_widen-ledger-amounts.sql b/packages/database/supabase/migrations/20260811123614_widen-ledger-amounts.sql
new file mode 100644
index 0000000000..24d062c2b7
--- /dev/null
+++ b/packages/database/supabase/migrations/20260811123614_widen-ledger-amounts.sql
@@ -0,0 +1,459 @@
+-- Ledger tables clamp value scale below the app's internal precision (scale 5),
+-- so Postgres re-rounds every posted line AFTER the app's balance check passes —
+-- a stored journal can drift out of balance by up to half a unit of the column
+-- scale per line. Widen the ledger value columns to bare NUMERIC so the posting
+-- functions' explicit rounding is the only rounding.
+--
+-- This migration must be applied BEFORE the app starts posting 5-decimal
+-- amounts (the posting-function change rides in the same release).
+
+-- journalLine.amount is referenced by the "journalEntries" and "journalLines"
+-- views; Postgres refuses to retype a column a view depends on, so drop and
+-- recreate them (bodies forked verbatim from their newest definitions:
+-- journalEntries 20260402000000, journalLines 20260711011724).
+DROP VIEW IF EXISTS "journalLines";
+DROP VIEW IF EXISTS "journalEntries";
+
+ALTER TABLE "journalLine"
+ ALTER COLUMN "amount" TYPE NUMERIC,
+ ALTER COLUMN "quantity" TYPE NUMERIC;
+
+ALTER TABLE "costLedger"
+ ALTER COLUMN "cost" TYPE NUMERIC,
+ ALTER COLUMN "nominalCost" TYPE NUMERIC,
+ ALTER COLUMN "quantity" TYPE NUMERIC,
+ ALTER COLUMN "remainingQuantity" TYPE NUMERIC;
+
+ALTER TABLE "supplierLedger"
+ ALTER COLUMN "amount" TYPE NUMERIC;
+
+ALTER TABLE "intercompanyTransaction"
+ ALTER COLUMN "amount" TYPE NUMERIC;
+
+-- itemLedger.quantity is referenced by the "itemLedgers" view and the
+-- "itemStockQuantities" / "itemLedgerSnapshot" materialized views. The
+-- pg_cron refresh job for the snapshot references it by name at runtime and
+-- survives the drop/recreate; publication membership (supabase_realtime)
+-- survives a column retype.
+DROP VIEW IF EXISTS "itemLedgers";
+-- itemStockQuantities is a matview here in a from-scratch apply, but migration
+-- 20260812002454 (later timestamp, but already applied on any environment that
+-- deployed main first — so this migration lands OUT OF ORDER there) converts it
+-- to a trigger-maintained TABLE. A table does not depend on itemLedger.quantity's
+-- type, so it neither blocks the ALTER below nor may be clobbered back into a
+-- matview. Only drop it when it is actually still a matview.
+DO $$
+BEGIN
+ IF EXISTS (
+ SELECT 1 FROM pg_matviews
+ WHERE schemaname = 'public' AND matviewname = 'itemStockQuantities'
+ ) THEN
+ DROP MATERIALIZED VIEW "itemStockQuantities";
+ END IF;
+END $$;
+DROP MATERIALIZED VIEW IF EXISTS "itemLedgerSnapshot";
+
+ALTER TABLE "itemLedger"
+ ALTER COLUMN "quantity" TYPE NUMERIC;
+
+-- Recreate (verbatim from 20260713130718)
+CREATE OR REPLACE VIEW "itemLedgers" WITH (security_invoker = true) AS
+SELECT
+ il.*,
+ (il."correctionOfItemLedgerId" IS NOT NULL) AS "isCorrection",
+ i."readableIdWithRevision" AS "itemReadableId",
+ i."name" AS "itemDescription",
+ i."type" AS "itemType",
+ l."name" AS "locationName",
+ su."name" AS "storageUnitName",
+ te."readableId" AS "trackedEntityReadableId",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL
+ THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath"
+FROM "itemLedger" il
+INNER JOIN "item" i ON i."id" = il."itemId" AND i."companyId" = il."companyId"
+LEFT JOIN "modelUpload" mu ON mu."id" = i."modelUploadId"
+LEFT JOIN "location" l ON l."id" = il."locationId" AND l."companyId" = il."companyId"
+LEFT JOIN "storageUnit" su ON su."id" = il."storageUnitId" AND su."companyId" = il."companyId"
+LEFT JOIN "trackedEntity" te ON te."id" = il."trackedEntityId" AND te."companyId" = il."companyId";
+
+-- Recreate itemStockQuantities as a matview ONLY when it is not already present
+-- as a relation. In a from-scratch apply the guarded DROP above removed the
+-- matview, so it is recreated here and 20260812002454 later converts it to a
+-- table. Where 20260812002454 already ran (out-of-order deploy), the table
+-- exists and is left exactly as-is — its statement-level triggers and realtime
+-- membership intact. Verbatim from 20260420112047.
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_class c
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = 'public' AND c.relname = 'itemStockQuantities'
+ ) THEN
+ EXECUTE $mv$
+ CREATE MATERIALIZED VIEW "itemStockQuantities" AS
+ SELECT
+ "itemId",
+ "companyId",
+ COALESCE("locationId", '') AS "locationId",
+ SUM("quantity") FILTER (
+ WHERE "trackedEntityStatus" IS NULL
+ OR "trackedEntityStatus" != 'Rejected'
+ ) AS "quantityOnHand"
+ FROM "itemLedger"
+ GROUP BY "itemId", "companyId", COALESCE("locationId", '')
+ $mv$;
+ EXECUTE $ix$
+ CREATE UNIQUE INDEX "itemStockQuantities_itemId_companyId_locationId_idx"
+ ON "itemStockQuantities" ("itemId", "companyId", "locationId")
+ $ix$;
+ END IF;
+END $$;
+
+-- Recreate (verbatim from 20260713235406)
+CREATE MATERIALIZED VIEW "itemLedgerSnapshot" AS
+SELECT
+ "itemId",
+ "companyId",
+ COALESCE("locationId", '') AS "locationId",
+ SUM("quantity") AS "quantity",
+ SUM(CASE
+ WHEN "entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')
+ AND "createdAt" >= CURRENT_DATE - INTERVAL '30 days'
+ THEN -"quantity"
+ ELSE 0
+ END) AS "consumed30",
+ SUM(CASE
+ WHEN "entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')
+ AND "createdAt" >= CURRENT_DATE - INTERVAL '90 days'
+ THEN -"quantity"
+ ELSE 0
+ END) AS "consumed90",
+ ARRAY_AGG(DISTINCT "storageUnitId") FILTER (WHERE "storageUnitId" IS NOT NULL) AS "storageUnitIds",
+ now() - INTERVAL '1 hour' AS "snapshotCutoff"
+FROM "itemLedger"
+WHERE "trackedEntityId" IS NULL
+ AND "createdAt" < now() - INTERVAL '1 hour'
+GROUP BY "itemId", "companyId", COALESCE("locationId", '');
+
+CREATE UNIQUE INDEX "itemLedgerSnapshot_itemId_companyId_locationId_idx"
+ ON "itemLedgerSnapshot" ("itemId", "companyId", "locationId");
+
+CREATE INDEX "itemLedgerSnapshot_companyId_locationId_idx"
+ ON "itemLedgerSnapshot" ("companyId", "locationId");
+
+-- Matviews don't support RLS; this one is only read inside SECURITY DEFINER
+-- functions, so keep it out of PostgREST entirely.
+REVOKE ALL ON "itemLedgerSnapshot" FROM anon, authenticated;
+
+-- Recreate (verbatim from 20260402000000)
+CREATE OR REPLACE VIEW "journalEntries"
+WITH (security_invoker = true)
+AS
+ SELECT
+ j.*,
+ COALESCE(SUM(
+ CASE
+ WHEN a."class" IN ('Asset', 'Expense') AND jl."amount" > 0 THEN jl."amount"
+ WHEN a."class" IN ('Liability', 'Equity', 'Revenue') AND jl."amount" < 0 THEN ABS(jl."amount")
+ ELSE 0
+ END
+ ), 0) AS "totalDebits",
+ COALESCE(SUM(
+ CASE
+ WHEN a."class" IN ('Asset', 'Expense') AND jl."amount" < 0 THEN ABS(jl."amount")
+ WHEN a."class" IN ('Liability', 'Equity', 'Revenue') AND jl."amount" > 0 THEN jl."amount"
+ ELSE 0
+ END
+ ), 0) AS "totalCredits",
+ COUNT(jl."id")::integer AS "lineCount"
+ FROM "journal" j
+ LEFT JOIN "journalLine" jl ON jl."journalId" = j."id"
+ LEFT JOIN "account" a ON a."id" = jl."accountId"
+ GROUP BY j."id";
+
+-- Recreate (verbatim from 20260711011724)
+CREATE VIEW "journalLines" WITH(SECURITY_INVOKER=true) AS
+SELECT
+ jl.*,
+ j."postingDate",
+ j."journalEntryId",
+ j."status",
+ j."sourceType",
+ j."description" AS "journalDescription"
+FROM "journalLine" jl
+JOIN "journal" j ON j."id" = jl."journalId"
+WHERE j."status" != 'Draft';
+
+-- The balance RPCs declare clamped RETURN types, which cast full-precision
+-- sums back down on read. Redeclare with bare NUMERIC returns; bodies are
+-- forked verbatim from each function's newest definition.
+
+-- Forked from 20260315000001_per-company-balance-rpc.sql
+DROP FUNCTION IF EXISTS "trialBalance"(TEXT, TEXT, DATE, DATE);
+CREATE OR REPLACE FUNCTION "trialBalance" (
+ p_company_group_id TEXT,
+ p_company_id TEXT DEFAULT NULL,
+ from_date DATE DEFAULT (now() - INTERVAL '100 year'),
+ to_date DATE DEFAULT now()
+)
+RETURNS TABLE (
+ "accountId" TEXT,
+ "accountNumber" TEXT,
+ "accountName" TEXT,
+ "accountClass" "glAccountClass",
+ "incomeBalance" "glIncomeBalance",
+ "debitBalance" NUMERIC,
+ "creditBalance" NUMERIC,
+ "netChange" NUMERIC
+)
+LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public
+AS $$
+BEGIN
+ RETURN QUERY
+ SELECT
+ a."id" AS "accountId",
+ a."number" AS "accountNumber",
+ a."name" AS "accountName",
+ a."class" AS "accountClass",
+ a."incomeBalance",
+ CASE
+ WHEN a."class" IN ('Asset', 'Expense') AND b."balanceAtDate" > 0 THEN b."balanceAtDate"
+ WHEN a."class" IN ('Liability', 'Equity', 'Revenue') AND b."balanceAtDate" < 0 THEN ABS(b."balanceAtDate")
+ ELSE 0::NUMERIC
+ END AS "debitBalance",
+ CASE
+ WHEN a."class" IN ('Liability', 'Equity', 'Revenue') AND b."balanceAtDate" >= 0 THEN b."balanceAtDate"
+ WHEN a."class" IN ('Asset', 'Expense') AND b."balanceAtDate" < 0 THEN ABS(b."balanceAtDate")
+ ELSE 0::NUMERIC
+ END AS "creditBalance",
+ b."netChange"
+ FROM "account" a
+ INNER JOIN "accountTreeBalancesByCompany"(p_company_group_id, p_company_id, from_date, to_date) b
+ ON b."accountId" = a."id"
+ WHERE a."isGroup" = false
+ AND a."companyGroupId" = p_company_group_id
+ AND a."active" = true
+ AND (b."balanceAtDate" != 0 OR b."netChange" != 0)
+ ORDER BY a."number";
+END;
+$$;
+
+-- Forked from 20260315000002_exchange-rate-history.sql. The 4-decimal ROUND on
+-- the translated balance is deliberate consolidation behavior and is preserved.
+DROP FUNCTION IF EXISTS "translateTrialBalance"(TEXT, TEXT, TEXT, DATE, DATE);
+CREATE OR REPLACE FUNCTION "translateTrialBalance" (
+ p_company_group_id TEXT,
+ p_company_id TEXT,
+ p_target_currency TEXT,
+ p_period_end DATE,
+ p_period_start DATE DEFAULT NULL
+)
+RETURNS TABLE (
+ "accountId" TEXT,
+ "localBalance" NUMERIC,
+ "exchangeRate" NUMERIC,
+ "translatedBalance" NUMERIC
+)
+LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public
+AS $$
+DECLARE
+ v_source_currency TEXT;
+ v_closing_rate NUMERIC;
+ v_average_rate NUMERIC;
+ v_historical_rate NUMERIC;
+BEGIN
+ -- Get the subsidiary's base currency
+ SELECT "baseCurrencyCode" INTO v_source_currency
+ FROM "company" WHERE "id" = p_company_id;
+
+ -- If same currency, no translation needed
+ IF v_source_currency = p_target_currency THEN
+ RETURN QUERY
+ SELECT
+ b."accountId",
+ b."balanceAtDate" AS "localBalance",
+ 1.0::NUMERIC AS "exchangeRate",
+ b."balanceAtDate" AS "translatedBalance"
+ FROM "accountTreeBalancesByCompany"(p_company_group_id, p_company_id, p_period_start, p_period_end) b
+ INNER JOIN "account" a ON a."id" = b."accountId"
+ WHERE a."isGroup" = false;
+ RETURN;
+ END IF;
+
+ -- Closing rate: latest daily rate on or before period end
+ SELECT "rate" INTO v_closing_rate
+ FROM "exchangeRateHistory"
+ WHERE "currencyCode" = v_source_currency
+ AND "companyGroupId" = p_company_group_id
+ AND "effectiveDate" <= p_period_end
+ ORDER BY "effectiveDate" DESC LIMIT 1;
+
+ -- Average rate: mean of daily rates over the period
+ SELECT AVG("rate") INTO v_average_rate
+ FROM "exchangeRateHistory"
+ WHERE "currencyCode" = v_source_currency
+ AND "companyGroupId" = p_company_group_id
+ AND "effectiveDate" >= COALESCE(p_period_start, p_period_end - INTERVAL '1 year')
+ AND "effectiveDate" <= p_period_end;
+
+ -- Historical rate: from currency table (manually set for equity)
+ SELECT "historicalExchangeRate" INTO v_historical_rate
+ FROM "currency"
+ WHERE "code" = v_source_currency
+ AND "companyGroupId" = p_company_group_id;
+
+ -- Defaults: average falls back to closing, historical falls back to closing, all fall back to 1
+ v_average_rate := COALESCE(v_average_rate, v_closing_rate, 1);
+ v_historical_rate := COALESCE(v_historical_rate, v_closing_rate, 1);
+ v_closing_rate := COALESCE(v_closing_rate, 1);
+
+ RETURN QUERY
+ SELECT
+ b."accountId",
+ b."balanceAtDate" AS "localBalance",
+ CASE a."consolidatedRate"
+ WHEN 'Current' THEN v_closing_rate
+ WHEN 'Average' THEN v_average_rate
+ WHEN 'Historical' THEN v_historical_rate
+ END AS "exchangeRate",
+ ROUND(b."balanceAtDate" * CASE a."consolidatedRate"
+ WHEN 'Current' THEN v_closing_rate
+ WHEN 'Average' THEN v_average_rate
+ WHEN 'Historical' THEN v_historical_rate
+ END, 4) AS "translatedBalance"
+ FROM "accountTreeBalancesByCompany"(p_company_group_id, p_company_id, p_period_start, p_period_end) b
+ INNER JOIN "account" a ON a."id" = b."accountId"
+ WHERE a."isGroup" = false;
+END;
+$$;
+
+-- Forked from 20260403120000_intercompany-tracking.sql
+DROP FUNCTION IF EXISTS "matchIntercompanyTransactions"(TEXT);
+CREATE OR REPLACE FUNCTION "matchIntercompanyTransactions" (
+ p_company_group_id TEXT
+)
+RETURNS TABLE (
+ "id" TEXT,
+ "sourceCompanyId" TEXT,
+ "targetCompanyId" TEXT,
+ "amount" NUMERIC,
+ "status" TEXT,
+ "matchedWithId" TEXT
+)
+LANGUAGE "plpgsql"
+SECURITY INVOKER
+SET search_path = public
+AS $$
+BEGIN
+ -- Check that user belongs to at least one company in this group
+ IF NOT EXISTS (
+ SELECT 1
+ FROM "userToCompany" utc
+ INNER JOIN "company" c ON c."id" = utc."companyId"
+ WHERE utc."userId" = auth.uid()::text
+ AND utc."role" = 'employee'
+ AND c."companyGroupId" = p_company_group_id
+ ) THEN
+ RAISE EXCEPTION 'Insufficient permissions to match intercompany transactions';
+ END IF;
+
+ -- Match unmatched IC transactions:
+ -- Source's receivable against target's payable for the same amount and partner
+ WITH matches AS (
+ SELECT
+ src."id" AS "sourceId",
+ tgt."id" AS "targetId"
+ FROM "intercompanyTransaction" src
+ INNER JOIN "intercompanyTransaction" tgt
+ ON src."sourceCompanyId" = tgt."targetCompanyId"
+ AND src."targetCompanyId" = tgt."sourceCompanyId"
+ AND src."amount" = tgt."amount"
+ AND src."companyGroupId" = tgt."companyGroupId"
+ WHERE src."companyGroupId" = p_company_group_id
+ AND src."status" = 'Unmatched'
+ AND tgt."status" = 'Unmatched'
+ AND src."sourceJournalLineId" < tgt."sourceJournalLineId"
+ )
+ UPDATE "intercompanyTransaction" ict
+ SET
+ "status" = 'Matched',
+ "targetJournalLineId" = CASE
+ WHEN ict."id" = m."sourceId" THEN (SELECT t."sourceJournalLineId" FROM "intercompanyTransaction" t WHERE t."id" = m."targetId")
+ ELSE (SELECT t."sourceJournalLineId" FROM "intercompanyTransaction" t WHERE t."id" = m."sourceId")
+ END,
+ "updatedAt" = NOW()
+ FROM matches m
+ WHERE ict."id" IN (m."sourceId", m."targetId");
+
+ -- Return current state
+ RETURN QUERY
+ SELECT
+ ict."id",
+ ict."sourceCompanyId",
+ ict."targetCompanyId",
+ ict."amount",
+ ict."status",
+ ict."targetJournalLineId" AS "matchedWithId"
+ FROM "intercompanyTransaction" ict
+ WHERE ict."companyGroupId" = p_company_group_id
+ ORDER BY ict."createdAt" DESC;
+END;
+$$;
+
+-- Forked from 20260403120000_intercompany-tracking.sql
+DROP FUNCTION IF EXISTS "getIntercompanyBalance"(TEXT);
+CREATE OR REPLACE FUNCTION "getIntercompanyBalance" (
+ p_company_group_id TEXT
+)
+RETURNS TABLE (
+ "sourceCompanyId" TEXT,
+ "sourceCompanyName" TEXT,
+ "targetCompanyId" TEXT,
+ "targetCompanyName" TEXT,
+ "balance" NUMERIC
+)
+LANGUAGE "plpgsql"
+SECURITY INVOKER
+SET search_path = public
+AS $$
+BEGIN
+ -- Check that user belongs to at least one company in this group
+ IF NOT EXISTS (
+ SELECT 1
+ FROM "userToCompany" utc
+ INNER JOIN "company" c ON c."id" = utc."companyId"
+ WHERE utc."userId" = auth.uid()::text
+ AND utc."role" = 'employee'
+ AND c."companyGroupId" = p_company_group_id
+ ) THEN
+ RAISE EXCEPTION 'Insufficient permissions to view intercompany balance';
+ END IF;
+
+ RETURN QUERY
+ SELECT
+ ict."sourceCompanyId",
+ sc."name" AS "sourceCompanyName",
+ ict."targetCompanyId",
+ tc."name" AS "targetCompanyName",
+ SUM(
+ CASE
+ WHEN ict."status" != 'Eliminated' THEN ict."amount"
+ ELSE 0
+ END
+ ) AS "balance"
+ FROM "intercompanyTransaction" ict
+ INNER JOIN "company" sc ON sc."id" = ict."sourceCompanyId"
+ INNER JOIN "company" tc ON tc."id" = ict."targetCompanyId"
+ WHERE ict."companyGroupId" = p_company_group_id
+ GROUP BY ict."sourceCompanyId", sc."name", ict."targetCompanyId", tc."name"
+ HAVING SUM(
+ CASE
+ WHEN ict."status" != 'Eliminated' THEN ict."amount"
+ ELSE 0
+ END
+ ) != 0;
+END;
+$$;
diff --git a/packages/database/supabase/migrations/20260811123616_widen-purchasing-scale.sql b/packages/database/supabase/migrations/20260811123616_widen-purchasing-scale.sql
new file mode 100644
index 0000000000..0bc65e1746
--- /dev/null
+++ b/packages/database/supabase/migrations/20260811123616_widen-purchasing-scale.sql
@@ -0,0 +1,549 @@
+-- Widen the purchasing-side value columns that still clamp scale below the
+-- app's internal precision, so entered prices, rates, and factors are stored
+-- exactly as validated. Generated price columns that reference the retyped
+-- columns must be dropped and re-added (bodies forked verbatim from
+-- 20250807094441 / 20250204164256); dependent views are dropped and recreated
+-- from their newest definitions.
+
+DROP VIEW IF EXISTS "openPurchaseOrderLines";
+DROP VIEW IF EXISTS "purchaseOrders";
+DROP VIEW IF EXISTS "purchaseOrderLines";
+DROP VIEW IF EXISTS "purchaseInvoices";
+DROP VIEW IF EXISTS "purchaseInvoiceLines";
+DROP VIEW IF EXISTS "receiptLines";
+DROP VIEW IF EXISTS "supplierQuotes";
+DROP VIEW IF EXISTS "supplierQuoteLines";
+DROP VIEW IF EXISTS "purchasingRfqLines";
+DROP VIEW IF EXISTS "supplierProcesses";
+
+-- Column-list triggers (UPDATE OF "exchangeRate") pin the column type; drop
+-- and recreate around the retype (DDL captured verbatim from the live schema).
+DROP TRIGGER IF EXISTS "update_purchase_order_line_price_exchange_rate_trigger" ON "purchaseOrder";
+DROP TRIGGER IF EXISTS "update_purchase_invoice_line_price_exchange_rate_trigger" ON "purchaseInvoice";
+DROP TRIGGER IF EXISTS "update_supplier_quote_line_price_exchange_rate_trigger" ON "supplierQuote";
+
+-- purchaseOrderLine ---------------------------------------------------------
+
+ALTER TABLE "purchaseOrderLine" DROP COLUMN IF EXISTS "unitPrice";
+ALTER TABLE "purchaseOrderLine" DROP COLUMN IF EXISTS "extendedPrice";
+ALTER TABLE "purchaseOrderLine" DROP COLUMN IF EXISTS "shippingCost";
+ALTER TABLE "purchaseOrderLine" DROP COLUMN IF EXISTS "taxAmount";
+
+ALTER TABLE "purchaseOrderLine"
+ ALTER COLUMN "conversionFactor" TYPE NUMERIC,
+ ALTER COLUMN "exchangeRate" TYPE NUMERIC,
+ ALTER COLUMN "setupPrice" TYPE NUMERIC;
+
+ALTER TABLE "purchaseOrderLine" ADD COLUMN "unitPrice" NUMERIC GENERATED ALWAYS AS (
+ "supplierUnitPrice" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END
+) STORED;
+
+ALTER TABLE "purchaseOrderLine" ADD COLUMN "extendedPrice" NUMERIC GENERATED ALWAYS AS (
+ "supplierUnitPrice" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END * "purchaseQuantity"
+) STORED;
+
+ALTER TABLE "purchaseOrderLine" ADD COLUMN "shippingCost" NUMERIC GENERATED ALWAYS AS (
+ "supplierShippingCost" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END
+) STORED;
+
+ALTER TABLE "purchaseOrderLine" ADD COLUMN "taxAmount" NUMERIC GENERATED ALWAYS AS (
+ "supplierTaxAmount" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END
+) STORED;
+
+-- purchaseInvoiceLine -------------------------------------------------------
+
+ALTER TABLE "purchaseInvoiceLine" DROP COLUMN IF EXISTS "unitPrice";
+ALTER TABLE "purchaseInvoiceLine" DROP COLUMN IF EXISTS "extendedPrice";
+ALTER TABLE "purchaseInvoiceLine" DROP COLUMN IF EXISTS "shippingCost";
+ALTER TABLE "purchaseInvoiceLine" DROP COLUMN IF EXISTS "taxAmount";
+ALTER TABLE "purchaseInvoiceLine" DROP COLUMN IF EXISTS "totalAmount";
+
+ALTER TABLE "purchaseInvoiceLine"
+ ALTER COLUMN "conversionFactor" TYPE NUMERIC,
+ ALTER COLUMN "exchangeRate" TYPE NUMERIC;
+
+ALTER TABLE "purchaseInvoiceLine" ADD COLUMN "unitPrice" NUMERIC GENERATED ALWAYS AS (
+ "supplierUnitPrice" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END
+) STORED;
+
+ALTER TABLE "purchaseInvoiceLine" ADD COLUMN "extendedPrice" NUMERIC GENERATED ALWAYS AS (
+ "supplierUnitPrice" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END * "quantity"
+) STORED;
+
+ALTER TABLE "purchaseInvoiceLine" ADD COLUMN "shippingCost" NUMERIC GENERATED ALWAYS AS (
+ "supplierShippingCost" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END
+) STORED;
+
+ALTER TABLE "purchaseInvoiceLine" ADD COLUMN "taxAmount" NUMERIC GENERATED ALWAYS AS (
+ "supplierTaxAmount" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END
+) STORED;
+
+ALTER TABLE "purchaseInvoiceLine" ADD COLUMN "totalAmount" NUMERIC GENERATED ALWAYS AS (
+ ("supplierUnitPrice" * "quantity" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END) +
+ ("supplierShippingCost" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END) +
+ ("supplierTaxAmount" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END)
+) STORED;
+
+-- supplierQuoteLinePrice ----------------------------------------------------
+
+ALTER TABLE "supplierQuoteLinePrice" DROP COLUMN IF EXISTS "unitPrice";
+ALTER TABLE "supplierQuoteLinePrice" DROP COLUMN IF EXISTS "extendedPrice";
+ALTER TABLE "supplierQuoteLinePrice" DROP COLUMN IF EXISTS "shippingCost";
+ALTER TABLE "supplierQuoteLinePrice" DROP COLUMN IF EXISTS "taxAmount";
+
+ALTER TABLE "supplierQuoteLinePrice"
+ ALTER COLUMN "exchangeRate" TYPE NUMERIC;
+
+ALTER TABLE "supplierQuoteLinePrice" ADD COLUMN "unitPrice" NUMERIC GENERATED ALWAYS AS (
+ "supplierUnitPrice" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END
+) STORED;
+
+ALTER TABLE "supplierQuoteLinePrice" ADD COLUMN "extendedPrice" NUMERIC GENERATED ALWAYS AS (
+ "supplierUnitPrice" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END * "quantity"
+) STORED;
+
+ALTER TABLE "supplierQuoteLinePrice" ADD COLUMN "shippingCost" NUMERIC GENERATED ALWAYS AS (
+ "supplierShippingCost" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END
+) STORED;
+
+ALTER TABLE "supplierQuoteLinePrice" ADD COLUMN "taxAmount" NUMERIC GENERATED ALWAYS AS (
+ "supplierTaxAmount" / CASE WHEN "exchangeRate" = 0 THEN 1 ELSE "exchangeRate" END
+) STORED;
+
+-- Headers and the rest ------------------------------------------------------
+
+ALTER TABLE "purchaseOrder"
+ ALTER COLUMN "exchangeRate" TYPE NUMERIC;
+
+ALTER TABLE "purchaseInvoice"
+ ALTER COLUMN "subtotal" TYPE NUMERIC,
+ ALTER COLUMN "totalDiscount" TYPE NUMERIC,
+ ALTER COLUMN "totalAmount" TYPE NUMERIC,
+ ALTER COLUMN "totalTax" TYPE NUMERIC,
+ ALTER COLUMN "exchangeRate" TYPE NUMERIC;
+
+ALTER TABLE "purchaseInvoicePriceChange"
+ ALTER COLUMN "previousPrice" TYPE NUMERIC,
+ ALTER COLUMN "newPrice" TYPE NUMERIC,
+ ALTER COLUMN "previousQuantity" TYPE NUMERIC,
+ ALTER COLUMN "newQuantity" TYPE NUMERIC;
+
+ALTER TABLE "receiptLine"
+ ALTER COLUMN "conversionFactor" TYPE NUMERIC,
+ ALTER COLUMN "unitPrice" TYPE NUMERIC,
+ ALTER COLUMN "orderQuantity" TYPE NUMERIC,
+ ALTER COLUMN "outstandingQuantity" TYPE NUMERIC,
+ ALTER COLUMN "receivedQuantity" TYPE NUMERIC;
+
+-- supplierPart."unitPrice" was born clamped to 2 decimals and a later widening
+-- used ADD COLUMN IF NOT EXISTS, a no-op wherever the column already existed,
+-- so distributor prices silently rounded on entry (0.164 -> 0.16). The
+-- price-break rows are the same price on the same screen, so they follow.
+ALTER TABLE "supplierPart"
+ ALTER COLUMN "unitPrice" TYPE NUMERIC;
+
+ALTER TABLE "supplierPartPrice"
+ ALTER COLUMN "unitPrice" TYPE NUMERIC,
+ ALTER COLUMN "quantity" TYPE NUMERIC;
+
+ALTER TABLE "supplierQuote"
+ ALTER COLUMN "exchangeRate" TYPE NUMERIC;
+
+ALTER TABLE "supplierQuoteLine"
+ ALTER COLUMN "quantity" TYPE NUMERIC[] USING "quantity"::NUMERIC[];
+
+ALTER TABLE "purchasingRfqLine"
+ ALTER COLUMN "quantity" TYPE NUMERIC[] USING "quantity"::NUMERIC[];
+
+ALTER TABLE "supplierProcess"
+ ALTER COLUMN "minimumCost" TYPE NUMERIC;
+
+-- Recreate views (each forked verbatim from its newest definition) ----------
+
+-- Forked from 20260708204214_partial-gr-visibility-and-short-close.sql
+CREATE OR REPLACE VIEW "openPurchaseOrderLines" WITH (security_invoker=true) AS (
+ SELECT
+ pol."id",
+ pol."purchaseOrderId",
+ po."purchaseOrderId" as "purchaseOrderReadableId",
+ po."supplierId",
+ pol."itemId",
+ pol."quantityToReceive" * pol."conversionFactor" AS "quantityToReceive",
+ i."unitOfMeasureCode",
+ pol."purchaseOrderLineType",
+ pol."requiredDate" AS "dueDate",
+ pol."companyId",
+ pol."locationId",
+ po."orderDate",
+ po."status",
+ COALESCE(pol."promisedDate", pod."receiptPromisedDate") AS "promisedDate",
+ i."replenishmentSystem",
+ i."itemTrackingType",
+ ir."leadTime" AS "leadTime"
+ FROM "purchaseOrderLine" pol
+ INNER JOIN "purchaseOrder" po ON pol."purchaseOrderId" = po."id"
+ INNER JOIN "purchaseOrderDelivery" pod ON pod."id" = po."id"
+ INNER JOIN "item" i ON pol."itemId" = i."id"
+ INNER JOIN "itemReplenishment" ir ON i."id" = ir."itemId"
+ WHERE
+ pol."purchaseOrderLineType" != 'Service'
+ AND po."status" IN ('To Receive', 'To Receive and Invoice', 'Planned')
+ AND pol."receivedComplete" = false
+);
+
+-- Forked from 20260807011742_lateralize-order-list-views.sql
+CREATE OR REPLACE VIEW "purchaseOrders" WITH (security_invoker = true) AS
+ SELECT p.id,
+ p."purchaseOrderId",
+ p."revisionId",
+ p.status,
+ p."orderDate",
+ p."supplierId",
+ p."supplierLocationId",
+ p."supplierContactId",
+ p."supplierReference",
+ p.assignee,
+ p."companyId",
+ p."closedAt",
+ p."closedBy",
+ p."customFields",
+ p."createdAt",
+ p."createdBy",
+ p."updatedAt",
+ p."updatedBy",
+ p."currencyCode",
+ p."exchangeRate",
+ p."exchangeRateUpdatedAt",
+ p.tags,
+ p."internalNotes",
+ p."externalNotes",
+ p."supplierInteractionId",
+ p."purchaseOrderType",
+ p."jobId",
+ p."jobReadableId",
+ pl."thumbnailPath",
+ pl."itemType",
+ pl."orderTotal" + pd."supplierShippingCost" /
+ CASE
+ WHEN p."exchangeRate" = 0::numeric THEN 1::numeric
+ ELSE p."exchangeRate"
+ END AS "orderTotal",
+ COALESCE(pl."receivableQuantity", 0::numeric) AS "receivableQuantity",
+ COALESCE(pl."receivedQuantity", 0::numeric) AS "receivedQuantity",
+ pd."shippingMethodId",
+ pd."shippingTermId",
+ pd."receiptRequestedDate",
+ pd."receiptPromisedDate",
+ pd."deliveryDate",
+ pd."dropShipment",
+ pp."paymentTermId",
+ pd."locationId",
+ pd."supplierShippingCost",
+ pd.incoterm,
+ pd."incotermLocation",
+ u."fullName" AS "createdByFullName",
+ u.email AS "createdByEmail",
+ u.phone AS "createdByPhone",
+ ua."fullName" AS "assigneeFullName",
+ ua.email AS "assigneeEmail",
+ ua.phone AS "assigneePhone",
+ uam."fullName" AS "accountManagerFullName",
+ uam.email AS "accountManagerEmail",
+ uam.phone AS "accountManagerPhone"
+ FROM "purchaseOrder" p
+ LEFT JOIN LATERAL ( SELECT
+ min(
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END) AS "thumbnailPath",
+ sum(COALESCE(pol."purchaseQuantity", 0::numeric) * COALESCE(pol."unitPrice", 0::numeric) + COALESCE(pol."shippingCost", 0::numeric) + COALESCE(pol."taxAmount", 0::numeric)) AS "orderTotal",
+ sum(
+ CASE
+ WHEN pol."purchaseOrderLineType" <> ALL (ARRAY['Comment'::"purchaseOrderLineType", 'G/L Account'::"purchaseOrderLineType"]) THEN COALESCE(pol."purchaseQuantity", 0::numeric)
+ ELSE 0::numeric
+ END) AS "receivableQuantity",
+ sum(
+ CASE
+ WHEN pol."purchaseOrderLineType" <> ALL (ARRAY['Comment'::"purchaseOrderLineType", 'G/L Account'::"purchaseOrderLineType"]) THEN COALESCE(pol."quantityReceived", 0::numeric)
+ ELSE 0::numeric
+ END) AS "receivedQuantity",
+ min(i.type) AS "itemType"
+ FROM "purchaseOrderLine" pol
+ LEFT JOIN item i ON i.id = pol."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ WHERE pol."purchaseOrderId" = p.id) pl ON true
+ LEFT JOIN "purchaseOrderDelivery" pd ON pd.id = p.id
+ LEFT JOIN "shippingTerm" st ON st.id = pd."shippingTermId"
+ LEFT JOIN "purchaseOrderPayment" pp ON pp.id = p.id
+ LEFT JOIN "user" u ON u.id = p."createdBy"
+ LEFT JOIN "user" ua ON ua.id = p.assignee
+ LEFT JOIN supplier s ON s.id = p."supplierId"
+ LEFT JOIN "user" uam ON uam.id = s."accountManagerId";
+
+-- Forked from 20260726234512_drop-requires-inspection.sql
+CREATE VIEW "purchaseOrderLines" WITH(SECURITY_INVOKER=true) AS (
+ SELECT DISTINCT ON (pl.id)
+ pl.*,
+ sp."supplierPartId" as "supplierPartIdFromSupplier",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ WHEN i."thumbnailPath" IS NULL AND imu."thumbnailPath" IS NOT NULL THEN imu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END as "thumbnailPath",
+ i.name as "itemName",
+ i."readableIdWithRevision" as "itemReadableId",
+ i.description as "itemDescription",
+ COALESCE(mu.id, imu.id) as "modelId",
+ COALESCE(mu."autodeskUrn", imu."autodeskUrn") as "autodeskUrn",
+ COALESCE(mu."modelPath", imu."modelPath") as "modelPath",
+ COALESCE(mu."name", imu."name") as "modelName",
+ COALESCE(mu."size", imu."size") as "modelSize",
+ ic."unitCost" as "unitCost",
+ jo."description" as "jobOperationDescription",
+ a."name" as "accountName",
+ fa."fixedAssetId" as "assetReadableId",
+ fa."name" as "assetName"
+ FROM "purchaseOrderLine" pl
+ INNER JOIN "purchaseOrder" so ON so.id = pl."purchaseOrderId"
+ LEFT JOIN "modelUpload" mu ON pl."modelUploadId" = mu."id"
+ LEFT JOIN "item" i ON i.id = pl."itemId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ LEFT JOIN "modelUpload" imu ON imu.id = i."modelUploadId"
+ LEFT JOIN "jobOperation" jo ON jo."id" = pl."jobOperationId"
+ LEFT JOIN "account" a ON a.id = pl."accountId"
+ LEFT JOIN "fixedAsset" fa ON fa.id = pl."assetId"
+ LEFT JOIN "supplierPart" sp ON sp."supplierId" = so."supplierId" AND sp."itemId" = i.id
+);
+
+-- Forked from 20260702224219_fix-ar-ap-legacy-paid.sql
+CREATE VIEW "purchaseInvoices" WITH(SECURITY_INVOKER=true) AS
+ WITH settled AS (
+ SELECT
+ s."targetPurchaseInvoiceId",
+ SUM(s."appliedAmount" + s."discountAmount" + s."writeOffAmount") AS amount,
+ MAX(s."appliedDate") AS "lastSettlementDate"
+ FROM "invoiceSettlement" s
+ LEFT JOIN "payment" p ON p."id" = s."paymentId"
+ LEFT JOIN "memo" m ON m."id" = s."memoId"
+ LEFT JOIN "payment" vp ON vp."id" = s."appliedViaPaymentId"
+ WHERE s."targetPurchaseInvoiceId" IS NOT NULL
+ AND (
+ (s."paymentId" IS NOT NULL AND p."status" = 'Posted')
+ OR (
+ s."memoId" IS NOT NULL AND m."status" = 'Posted'
+ AND (s."appliedViaPaymentId" IS NULL OR vp."status" = 'Posted')
+ )
+ )
+ GROUP BY s."targetPurchaseInvoiceId"
+ )
+ SELECT
+ pi."id",
+ pi."invoiceId",
+ pi."supplierId",
+ pi."invoiceSupplierId",
+ pi."supplierInteractionId",
+ pi."supplierReference",
+ pi."invoiceSupplierContactId",
+ pi."invoiceSupplierLocationId",
+ pi."locationId",
+ pi."postingDate",
+ pi."dateIssued",
+ pi."dateDue",
+ CASE
+ WHEN pi."status" = 'Paid' THEN pi."datePaid"
+ WHEN COALESCE(s.amount, 0) > 0
+ AND (COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) > 0
+ AND ((COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) - COALESCE(s.amount, 0)) < 0.01 THEN COALESCE(s."lastSettlementDate", pi."datePaid")
+ ELSE pi."datePaid"
+ END AS "datePaid",
+ pi."paymentTermId",
+ pi."currencyCode",
+ pi."exchangeRate",
+ pi."exchangeRateUpdatedAt",
+ COALESCE(pl."subtotal", 0) AS "subtotal",
+ pi."totalDiscount",
+ (COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) AS "totalAmount",
+ COALESCE(pl."totalTax", 0) AS "totalTax",
+ CASE
+ WHEN pi."status" = 'Paid' THEN 0
+ WHEN COALESCE(s.amount, 0) > 0
+ AND ((COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) - COALESCE(s.amount, 0)) > 0
+ AND ((COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) - COALESCE(s.amount, 0)) < 0.01 THEN 0
+ ELSE ((COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) - COALESCE(s.amount, 0))
+ END AS "balance",
+ pi."assignee",
+ pi."createdBy",
+ pi."createdAt",
+ pi."updatedBy",
+ pi."updatedAt",
+ pi."internalNotes",
+ pi."customFields",
+ pi."companyId",
+ pl."thumbnailPath",
+ pl."itemType",
+ COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END AS "orderTotal",
+ CASE
+ WHEN pi."status" IN ('Draft','Pending','Voided','Return','Debit Note Issued') THEN pi."status"::TEXT
+ WHEN pi."status" = 'Paid' THEN 'Paid'
+ WHEN COALESCE(s.amount, 0) > 0
+ AND (COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) > 0
+ AND ((COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) - COALESCE(s.amount, 0)) < 0.01 THEN 'Paid'
+ WHEN COALESCE(s.amount, 0) > 0 THEN 'Partially Paid'
+ WHEN pi."dateDue" < CURRENT_DATE AND pi."status" = 'Open' THEN 'Overdue'
+ ELSE pi."status"::TEXT
+ END AS status,
+ pt."name" AS "paymentTermName",
+ pi."status" AS "baseStatus"
+ FROM "purchaseInvoice" pi
+ LEFT JOIN (
+ SELECT
+ pol."invoiceId",
+ MIN(CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END) AS "thumbnailPath",
+ SUM(
+ COALESCE(pol."quantity", 0)*COALESCE(pol."unitPrice", 0) + COALESCE(pol."shippingCost", 0)
+ ) AS "subtotal",
+ SUM(COALESCE(pol."taxAmount", 0)) AS "totalTax",
+ SUM(
+ COALESCE(pol."quantity", 0)*COALESCE(pol."unitPrice", 0) + COALESCE(pol."shippingCost", 0) + COALESCE(pol."taxAmount", 0)
+ ) AS "orderTotal",
+ MIN(i."type") AS "itemType"
+ FROM "purchaseInvoiceLine" pol
+ LEFT JOIN "item" i
+ ON i."id" = pol."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ GROUP BY pol."invoiceId"
+ ) pl ON pl."invoiceId" = pi."id"
+ LEFT JOIN "paymentTerm" pt ON pt."id" = pi."paymentTermId"
+ LEFT JOIN "purchaseInvoiceDelivery" pid ON pid."id" = pi."id"
+ LEFT JOIN settled s ON s."targetPurchaseInvoiceId" = pi."id";
+
+-- Forked from 20260524143827_fixed-assets.sql
+CREATE OR REPLACE VIEW "purchaseInvoiceLines" WITH(SECURITY_INVOKER=true) AS (
+ SELECT
+ pl.*,
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ WHEN i."thumbnailPath" IS NULL AND imu."thumbnailPath" IS NOT NULL THEN imu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END as "thumbnailPath",
+ i."readableIdWithRevision" as "itemReadableId",
+ i.name as "itemName",
+ i.description as "itemDescription",
+ ic."unitCost" as "unitCost",
+ sp."supplierPartId",
+ a."name" as "accountName",
+ fa."fixedAssetId" as "assetReadableId",
+ fa."name" as "assetName"
+ FROM "purchaseInvoiceLine" pl
+ INNER JOIN "purchaseInvoice" pi ON pi.id = pl."invoiceId"
+ LEFT JOIN "modelUpload" mu ON pl."modelUploadId" = mu."id"
+ LEFT JOIN "item" i ON i.id = pl."itemId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ LEFT JOIN "modelUpload" imu ON imu.id = i."modelUploadId"
+ LEFT JOIN "supplierPart" sp ON sp."supplierId" = pi."supplierId" AND sp."itemId" = i.id
+ LEFT JOIN "account" a ON a.id = pl."accountId"
+ LEFT JOIN "fixedAsset" fa ON fa.id = pl."assetId"
+);
+
+-- Forked from 20260417000300_storage-unit-recreate-dependents.sql
+CREATE OR REPLACE VIEW "receiptLines" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ rl.*,
+ i."readableIdWithRevision" as "itemReadableId",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ i."name" as "description"
+ FROM "receiptLine" rl
+ INNER JOIN "item" i ON i."id" = rl."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId";
+
+-- Forked from 20251127000000_supplier_quote_updates.sql
+CREATE OR REPLACE VIEW "supplierQuotes"
+WITH
+ (SECURITY_INVOKER = true) AS
+SELECT
+ q.*,
+ ql."thumbnailPath",
+ ql."itemType"
+FROM
+ "supplierQuote" q
+ LEFT JOIN (
+ SELECT
+ "supplierQuoteId",
+ MIN(
+ CASE
+ WHEN i."thumbnailPath" IS NULL
+ AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END
+ ) AS "thumbnailPath",
+ MIN(i."type") AS "itemType"
+ FROM
+ "supplierQuoteLine"
+ INNER JOIN "item" i ON i."id" = "supplierQuoteLine"."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ GROUP BY
+ "supplierQuoteId"
+ ) ql ON ql."supplierQuoteId" = q.id;
+
+-- Forked from 20260513120000_line-item-sort-order.sql
+CREATE OR REPLACE VIEW "supplierQuoteLines" WITH(SECURITY_INVOKER=true) AS (
+ SELECT
+ ql.*,
+ i."readableIdWithRevision" as "itemReadableId",
+ i."type" as "itemType",
+ COALESCE(i."thumbnailPath", mu."thumbnailPath") as "thumbnailPath",
+ ic."unitCost" as "unitCost",
+ a."name" as "accountName"
+ FROM "supplierQuoteLine" ql
+ LEFT JOIN "item" i ON i.id = ql."itemId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN "account" a ON a.id = ql."accountId"
+);
+
+-- Forked from 20260115143000_purchasing-rfq.sql
+CREATE OR REPLACE VIEW "purchasingRfqLines" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ prl.*,
+ i."name" as "itemName",
+ i."readableId" AS "itemReadableId",
+ i."type" AS "itemType",
+ i."thumbnailPath",
+ mu."modelPath"
+ FROM "purchasingRfqLine" prl
+ LEFT JOIN "item" i ON i.id = prl."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId";
+
+-- Forked from 20241115011318_remove-supplier-process-unit-cost.sql
+CREATE VIEW "supplierProcesses" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ sp.*,
+ p.name as "processName"
+ FROM "supplierProcess" sp
+ INNER JOIN "process" p ON sp."processId" = p.id;
+
+-- Recreate the exchange-rate sync triggers
+CREATE TRIGGER update_purchase_order_line_price_exchange_rate_trigger
+AFTER UPDATE OF "exchangeRate" ON "purchaseOrder"
+FOR EACH ROW
+WHEN (OLD."exchangeRate" IS DISTINCT FROM NEW."exchangeRate")
+EXECUTE FUNCTION update_purchase_order_line_price_exchange_rate();
+
+CREATE TRIGGER update_purchase_invoice_line_price_exchange_rate_trigger
+AFTER UPDATE OF "exchangeRate" ON "purchaseInvoice"
+FOR EACH ROW
+WHEN (OLD."exchangeRate" IS DISTINCT FROM NEW."exchangeRate")
+EXECUTE FUNCTION update_purchase_invoice_line_price_exchange_rate();
+
+CREATE TRIGGER update_supplier_quote_line_price_exchange_rate_trigger
+AFTER UPDATE OF "exchangeRate" ON "supplierQuote"
+FOR EACH ROW
+WHEN (OLD."exchangeRate" IS DISTINCT FROM NEW."exchangeRate")
+EXECUTE FUNCTION update_supplier_quote_line_price_exchange_rate();
diff --git a/packages/database/supabase/migrations/20260811123619_widen-sales-production-scale.sql b/packages/database/supabase/migrations/20260811123619_widen-sales-production-scale.sql
new file mode 100644
index 0000000000..c43af4c98b
--- /dev/null
+++ b/packages/database/supabase/migrations/20260811123619_widen-sales-production-scale.sql
@@ -0,0 +1,825 @@
+-- Widen the sales, production, and master-data value columns still clamping
+-- scale below the app's internal precision. Generated converted-price columns
+-- that reference the retyped columns are dropped and re-added (bodies forked
+-- verbatim from 20250204164256 / 20260321120000); dependent views are dropped
+-- and recreated from their newest definitions.
+
+DROP VIEW IF EXISTS "openSalesOrderLines";
+DROP VIEW IF EXISTS "salesOrders";
+DROP VIEW IF EXISTS "salesOrderLines";
+DROP VIEW IF EXISTS "quotes";
+DROP VIEW IF EXISTS "quoteLines";
+DROP VIEW IF EXISTS "quoteLinePrices";
+DROP VIEW IF EXISTS "salesRfqLines";
+DROP VIEW IF EXISTS "jobs";
+DROP VIEW IF EXISTS "openProductionOrders";
+DROP VIEW IF EXISTS "openJobMaterialLines";
+DROP VIEW IF EXISTS "jobMaterialWithMakeMethodId";
+DROP VIEW IF EXISTS "jobOperationsWithMakeMethods";
+DROP VIEW IF EXISTS "jobOperationsWithDependencies";
+DROP VIEW IF EXISTS "quoteOperationsWithMakeMethods";
+DROP VIEW IF EXISTS "workCenters";
+DROP VIEW IF EXISTS "workCentersWithBlockingStatus";
+
+-- salesOrderLine ------------------------------------------------------------
+
+ALTER TABLE "salesOrderLine" DROP COLUMN IF EXISTS "convertedAddOnCost";
+ALTER TABLE "salesOrderLine" DROP COLUMN IF EXISTS "convertedShippingCost";
+ALTER TABLE "salesOrderLine" DROP COLUMN IF EXISTS "convertedUnitPrice";
+ALTER TABLE "salesOrderLine" DROP COLUMN IF EXISTS "convertedNonTaxableAddOnCost";
+
+ALTER TABLE "salesOrderLine"
+ ALTER COLUMN "exchangeRate" TYPE NUMERIC;
+
+ALTER TABLE "salesOrderLine"
+ ADD COLUMN "convertedAddOnCost" NUMERIC GENERATED ALWAYS AS ("addOnCost" * "exchangeRate") STORED,
+ ADD COLUMN "convertedShippingCost" NUMERIC GENERATED ALWAYS AS ("shippingCost" * "exchangeRate") STORED,
+ ADD COLUMN "convertedUnitPrice" NUMERIC GENERATED ALWAYS AS ("unitPrice" * "exchangeRate") STORED,
+ ADD COLUMN "convertedNonTaxableAddOnCost" NUMERIC GENERATED ALWAYS AS ("nonTaxableAddOnCost" * "exchangeRate") STORED;
+
+-- quoteLinePrice ------------------------------------------------------------
+
+ALTER TABLE "quoteLinePrice"
+ DROP COLUMN IF EXISTS "convertedUnitPrice",
+ DROP COLUMN IF EXISTS "convertedNetUnitPrice",
+ DROP COLUMN IF EXISTS "convertedNetExtendedPrice",
+ DROP COLUMN IF EXISTS "convertedShippingCost",
+ DROP COLUMN IF EXISTS "netUnitPrice",
+ DROP COLUMN IF EXISTS "netExtendedPrice";
+
+ALTER TABLE "quoteLinePrice"
+ ALTER COLUMN "exchangeRate" TYPE NUMERIC;
+
+ALTER TABLE "quoteLinePrice"
+ ADD COLUMN "convertedUnitPrice" NUMERIC GENERATED ALWAYS AS ("unitPrice" * "exchangeRate") STORED,
+ ADD COLUMN "netUnitPrice" NUMERIC GENERATED ALWAYS AS ("unitPrice" * (1 - "discountPercent")) STORED,
+ ADD COLUMN "netExtendedPrice" NUMERIC GENERATED ALWAYS AS ("unitPrice" * (1 - "discountPercent") * "quantity") STORED,
+ ADD COLUMN "convertedNetUnitPrice" NUMERIC GENERATED ALWAYS AS ("unitPrice" * "exchangeRate" * (1 - "discountPercent")) STORED,
+ ADD COLUMN "convertedNetExtendedPrice" NUMERIC GENERATED ALWAYS AS ("unitPrice" * "exchangeRate" * (1 - "discountPercent") * "quantity") STORED,
+ ADD COLUMN "convertedShippingCost" NUMERIC GENERATED ALWAYS AS ("shippingCost" * "exchangeRate") STORED;
+
+-- Headers, shipments, quantity ladders --------------------------------------
+
+ALTER TABLE "salesOrder"
+ ALTER COLUMN "exchangeRate" TYPE NUMERIC;
+
+ALTER TABLE "quote"
+ ALTER COLUMN "exchangeRate" TYPE NUMERIC;
+
+ALTER TABLE "quoteShipment"
+ ALTER COLUMN "shippingCost" TYPE NUMERIC;
+
+ALTER TABLE "salesOrderShipment"
+ ALTER COLUMN "shippingCost" TYPE NUMERIC;
+
+ALTER TABLE "quoteLine"
+ ALTER COLUMN "quantity" TYPE NUMERIC[] USING "quantity"::NUMERIC[];
+
+ALTER TABLE "salesRfqLine"
+ ALTER COLUMN "quantity" TYPE NUMERIC[] USING "quantity"::NUMERIC[];
+
+ALTER TABLE "pricingRule"
+ ALTER COLUMN "minQuantity" TYPE NUMERIC,
+ ALTER COLUMN "maxQuantity" TYPE NUMERIC;
+
+-- The deferrable UNIQUE on (override, quantity) survives a column retype;
+-- Postgres rebuilds the backing index with the same attributes.
+ALTER TABLE "customerItemPriceOverrideBreak"
+ ALTER COLUMN "quantity" TYPE NUMERIC;
+
+-- Production ----------------------------------------------------------------
+
+ALTER TABLE "job" DROP COLUMN IF EXISTS "productionQuantity";
+
+ALTER TABLE "job"
+ ALTER COLUMN "quantity" TYPE NUMERIC,
+ ALTER COLUMN "scrapQuantity" TYPE NUMERIC,
+ ALTER COLUMN "quantityComplete" TYPE NUMERIC,
+ ALTER COLUMN "quantityShipped" TYPE NUMERIC,
+ ALTER COLUMN "quantityReceivedToInventory" TYPE NUMERIC;
+
+ALTER TABLE "job"
+ ADD COLUMN "productionQuantity" NUMERIC GENERATED ALWAYS AS ("quantity" + "scrapQuantity") STORED;
+
+ALTER TABLE "jobMakeMethod"
+ ALTER COLUMN "quantityPerParent" TYPE NUMERIC,
+ ALTER COLUMN "itemScrapPercentage" TYPE NUMERIC;
+
+ALTER TABLE "quoteMakeMethod"
+ ALTER COLUMN "quantityPerParent" TYPE NUMERIC;
+
+ALTER TABLE "jobMaterial"
+ ALTER COLUMN "itemScrapPercentage" TYPE NUMERIC;
+
+ALTER TABLE "jobOperation"
+ ALTER COLUMN "operationQuantity" TYPE NUMERIC,
+ ALTER COLUMN "quantityComplete" TYPE NUMERIC,
+ ALTER COLUMN "quantityScrapped" TYPE NUMERIC,
+ ALTER COLUMN "quantityReworked" TYPE NUMERIC,
+ ALTER COLUMN "laborRate" TYPE NUMERIC,
+ ALTER COLUMN "machineRate" TYPE NUMERIC,
+ ALTER COLUMN "overheadRate" TYPE NUMERIC,
+ ALTER COLUMN "operationMinimumCost" TYPE NUMERIC,
+ ALTER COLUMN "operationUnitCost" TYPE NUMERIC;
+
+ALTER TABLE "quoteOperation"
+ ALTER COLUMN "laborRate" TYPE NUMERIC,
+ ALTER COLUMN "machineRate" TYPE NUMERIC,
+ ALTER COLUMN "overheadRate" TYPE NUMERIC,
+ ALTER COLUMN "operationMinimumCost" TYPE NUMERIC,
+ ALTER COLUMN "operationUnitCost" TYPE NUMERIC;
+
+ALTER TABLE "workCenter"
+ ALTER COLUMN "machineRate" TYPE NUMERIC,
+ ALTER COLUMN "overheadRate" TYPE NUMERIC;
+
+ALTER TABLE "rework"
+ ALTER COLUMN "quantity" TYPE NUMERIC;
+
+ALTER TABLE "pickingListLine" DROP COLUMN IF EXISTS "outstandingQuantity";
+
+ALTER TABLE "pickingListLine"
+ ALTER COLUMN "quantityToPick" TYPE NUMERIC,
+ ALTER COLUMN "quantityPicked" TYPE NUMERIC;
+
+ALTER TABLE "pickingListLine"
+ ADD COLUMN "outstandingQuantity" NUMERIC GENERATED ALWAYS AS (CASE WHEN "quantityToPick" >= "quantityPicked" THEN "quantityToPick" - "quantityPicked" ELSE 0 END) STORED;
+
+ALTER TABLE "pickingListLineTrackedEntity"
+ ALTER COLUMN "quantity" TYPE NUMERIC,
+ ALTER COLUMN "quantityPicked" TYPE NUMERIC;
+
+ALTER TABLE "nonConformanceItemTrackedEntity"
+ ALTER COLUMN "quantity" TYPE NUMERIC;
+
+-- Rate-shaped multipliers (they scale quantities and money) ------------------
+
+ALTER TABLE "itemReplenishment"
+ ALTER COLUMN "scrapPercentage" TYPE NUMERIC;
+
+ALTER TABLE "fixedAsset"
+ ALTER COLUMN "taxResidualValuePercent" TYPE NUMERIC,
+ ALTER COLUMN "bonusDepreciationPercent" TYPE NUMERIC;
+
+ALTER TABLE "fixedAssetClass"
+ ALTER COLUMN "taxResidualValuePercent" TYPE NUMERIC,
+ ALTER COLUMN "bonusDepreciationPercent" TYPE NUMERIC;
+
+ALTER TABLE "companySettings"
+ ALTER COLUMN "assetTaxRate" TYPE NUMERIC;
+
+-- Recreate views (each forked verbatim from its newest definition) ----------
+
+-- Forked from 20260807011742_lateralize-order-list-views.sql
+CREATE OR REPLACE VIEW "salesOrders" WITH (security_invoker = true) AS
+ SELECT s.id,
+ s."salesOrderId",
+ s."revisionId",
+ s.status,
+ s."orderDate",
+ s."currencyCode",
+ s."customerId",
+ s."customerLocationId",
+ s."customerContactId",
+ s."customerReference",
+ s.assignee,
+ s."companyId",
+ s."closedAt",
+ s."closedBy",
+ s."customFields",
+ s."createdAt",
+ s."createdBy",
+ s."updatedAt",
+ s."updatedBy",
+ s."locationId",
+ s."exchangeRate",
+ s."exchangeRateUpdatedAt",
+ s."externalNotes",
+ s."internalNotes",
+ s."salesPersonId",
+ s."sentCompleteDate",
+ s."opportunityId",
+ s."completedDate",
+ s."customerEngineeringContactId",
+ CASE
+ WHEN (s.status <> ALL (ARRAY['Closed'::"salesOrderStatus", 'Cancelled'::"salesOrderStatus"])) AND (EXISTS ( SELECT 1
+ FROM "salesOrderLine" sol
+ WHERE sol."salesOrderId" = s.id AND sol."methodType" = 'Make to Order'::"methodType" AND COALESCE(( SELECT sum(j."quantityComplete") AS sum
+ FROM job j
+ WHERE j."salesOrderLineId" = sol.id AND j."salesOrderId" = sol."salesOrderId"), 0::numeric) < sol."saleQuantity")) THEN 'In Progress'::"salesOrderStatus"
+ ELSE s.status
+ END AS "displayStatus",
+ sl."thumbnailPath",
+ sl."itemType",
+ sl."orderTotal" + COALESCE(ss."shippingCost", 0::numeric) AS "orderTotal",
+ sl.jobs,
+ sl.lines,
+ st.name AS "shippingTermName",
+ sp."paymentTermId",
+ ss."shippingMethodId",
+ ss."receiptRequestedDate",
+ ss."receiptPromisedDate",
+ ss."dropShipment",
+ ss."shippingCost",
+ ss.incoterm,
+ ss."incotermLocation",
+ ( SELECT COALESCE(jsonb_object_agg(eim.integration,
+ CASE
+ WHEN eim.metadata IS NOT NULL THEN eim.metadata
+ ELSE to_jsonb(eim."externalId")
+ END) FILTER (WHERE eim."externalId" IS NOT NULL OR eim.metadata IS NOT NULL), '{}'::jsonb) AS "coalesce"
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'salesOrder'::text AND eim."entityId" = s.id) AS "externalId"
+ FROM "salesOrder" s
+ LEFT JOIN LATERAL ( SELECT
+ min(
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END) AS "thumbnailPath",
+ sum(DISTINCT (1::numeric + COALESCE(sol."taxPercent", 0::numeric)) * (COALESCE(sol."saleQuantity", 0::numeric) * COALESCE(sol."unitPrice", 0::numeric) + COALESCE(sol."shippingCost", 0::numeric) + COALESCE(sol."addOnCost", 0::numeric)) + COALESCE(sol."nonTaxableAddOnCost", 0::numeric)) AS "orderTotal",
+ min(i.type) AS "itemType",
+ array_agg(
+ CASE
+ WHEN j.id IS NOT NULL THEN json_build_object('id', j.id, 'jobId', j."jobId", 'status', j.status, 'dueDate', j."dueDate", 'productionQuantity', j."productionQuantity", 'quantityComplete', j."quantityComplete", 'quantityShipped', j."quantityShipped", 'quantity', j.quantity, 'scrapQuantity', j."scrapQuantity", 'salesOrderLineId', sol.id, 'assignee', j.assignee)
+ ELSE NULL::json
+ END ORDER BY sol.id, j.id) FILTER (WHERE j.id IS NOT NULL) AS jobs,
+ array_agg(json_build_object('id', sol.id, 'methodType', sol."methodType", 'saleQuantity', sol."saleQuantity") ORDER BY sol.id) AS lines
+ FROM "salesOrderLine" sol
+ LEFT JOIN item i ON i.id = sol."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN job j ON j."salesOrderId" = sol."salesOrderId" AND j."salesOrderLineId" = sol.id
+ WHERE sol."salesOrderId" = s.id) sl ON true
+ LEFT JOIN "salesOrderShipment" ss ON ss.id = s.id
+ LEFT JOIN "shippingTerm" st ON st.id = ss."shippingTermId"
+ LEFT JOIN "salesOrderPayment" sp ON sp.id = s.id;
+
+-- Forked from 20260726234512_drop-requires-inspection.sql
+CREATE VIEW "salesOrderLines" WITH(SECURITY_INVOKER=true) AS (
+ SELECT
+ sl.*,
+ i."readableIdWithRevision" as "itemReadableId",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ WHEN i."thumbnailPath" IS NULL AND imu."thumbnailPath" IS NOT NULL THEN imu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END as "thumbnailPath",
+ COALESCE(mu.id, imu.id) as "modelId",
+ COALESCE(mu."autodeskUrn", imu."autodeskUrn") as "autodeskUrn",
+ COALESCE(mu."modelPath", imu."modelPath") as "modelPath",
+ COALESCE(mu."name", imu."name") as "modelName",
+ COALESCE(mu."size", imu."size") as "modelSize",
+ ic."unitCost" as "unitCost",
+ cp."customerPartId",
+ cp."customerPartRevision",
+ so."orderDate",
+ so."customerId",
+ so."salesOrderId" as "salesOrderReadableId",
+ fa."fixedAssetId" as "assetReadableId",
+ fa."name" as "assetName"
+ FROM "salesOrderLine" sl
+ INNER JOIN "salesOrder" so ON so.id = sl."salesOrderId"
+ LEFT JOIN "modelUpload" mu ON sl."modelUploadId" = mu."id"
+ LEFT JOIN "item" i ON i.id = sl."itemId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ LEFT JOIN "modelUpload" imu ON imu.id = i."modelUploadId"
+ LEFT JOIN "customerPartToItem" cp ON cp."customerId" = so."customerId" AND cp."itemId" = i.id
+ LEFT JOIN "fixedAsset" fa ON fa.id = sl."assetId"
+);
+
+-- Forked from 20260710051147_mto-sales-lines-drive-demand.sql
+CREATE VIEW "openSalesOrderLines" WITH (security_invoker=true) AS (
+ SELECT
+ sol."id",
+ sol."salesOrderId",
+ sol."itemId",
+ sol."promisedDate",
+ sol."methodType",
+ sol."unitOfMeasureCode",
+ CASE
+ WHEN sol."methodType" = 'Make to Order' THEN GREATEST(
+ sol."quantityToSend" - COALESCE((
+ SELECT SUM(GREATEST(j."quantity" - j."quantityReceivedToInventory" - j."quantityShipped", 0))
+ FROM "job" j
+ WHERE j."salesOrderLineId" = sol."id"
+ AND j."companyId" = sol."companyId"
+ AND j."status" IN ('Planned', 'Ready', 'In Progress', 'Paused')
+ ), 0),
+ 0
+ )
+ ELSE sol."quantityToSend"
+ END AS "quantityToSend",
+ sol."salesOrderLineType",
+ sol."companyId",
+ COALESCE(sol."locationId", so."locationId") AS "locationId",
+ i."replenishmentSystem",
+ i."itemTrackingType",
+ ir."leadTime"
+ FROM "salesOrderLine" sol
+ INNER JOIN "salesOrder" so ON sol."salesOrderId" = so."id"
+ INNER JOIN "item" i ON sol."itemId" = i."id"
+ INNER JOIN "itemReplenishment" ir ON i."id" = ir."itemId"
+ WHERE sol."salesOrderLineType" != 'Service'
+ AND so."status" IN ('To Ship', 'To Ship and Invoice')
+);
+
+-- Forked from 20260209163250_revert-quote-lead-time.sql
+CREATE OR REPLACE VIEW "quotes" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ q.*,
+ ql."thumbnailPath",
+ ql."itemType",
+ l."name" AS "locationName",
+ ql."lines",
+ ql."completedLines",
+ qs."shippingCost"
+ FROM "quote" q
+ LEFT JOIN (
+ SELECT
+ "quoteId",
+ COUNT("quoteLine"."id") FILTER (WHERE "quoteLine"."status" != 'No Quote') AS "lines",
+ COUNT("quoteLine"."id") FILTER (WHERE "quoteLine"."status" = 'Complete') AS "completedLines",
+ MIN(CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END) AS "thumbnailPath",
+ MIN(i."type") AS "itemType"
+ FROM "quoteLine"
+ INNER JOIN "item" i
+ ON i."id" = "quoteLine"."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ GROUP BY "quoteId"
+ ) ql ON ql."quoteId" = q.id
+ LEFT JOIN "quoteShipment" qs ON qs."id" = q."id"
+ LEFT JOIN "location" l
+ ON l.id = q."locationId";
+
+-- Forked from 20260513120000_line-item-sort-order.sql
+CREATE OR REPLACE VIEW "quoteLines" WITH(SECURITY_INVOKER=true) AS (
+ SELECT
+ ql.*,
+ i."readableIdWithRevision" as "itemReadableId",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ WHEN i."thumbnailPath" IS NULL AND imu."thumbnailPath" IS NOT NULL THEN imu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END as "thumbnailPath",
+ COALESCE(mu.id, imu.id) as "modelId",
+ COALESCE(mu."autodeskUrn", imu."autodeskUrn") as "autodeskUrn",
+ COALESCE(mu."modelPath", imu."modelPath") as "modelPath",
+ COALESCE(mu."name", imu."name") as "modelName",
+ COALESCE(mu."size", imu."size") as "modelSize",
+ ic."unitCost" as "unitCost"
+ FROM "quoteLine" ql
+ LEFT JOIN "modelUpload" mu ON ql."modelUploadId" = mu."id"
+ INNER JOIN "item" i ON i.id = ql."itemId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ LEFT JOIN "modelUpload" imu ON imu.id = i."modelUploadId"
+);
+
+-- Forked from 20260321143847_method-type-migration.sql
+CREATE OR REPLACE VIEW "quoteLinePrices" WITH(SECURITY_INVOKER=true) AS (
+ SELECT
+ ql.*,
+ i."readableIdWithRevision" as "itemReadableId",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ WHEN i."thumbnailPath" IS NULL AND imu."thumbnailPath" IS NOT NULL THEN imu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END as "thumbnailPath",
+ COALESCE(mu.id, imu.id) as "modelId",
+ COALESCE(mu."autodeskUrn", imu."autodeskUrn") as "autodeskUrn",
+ COALESCE(mu."modelPath", imu."modelPath") as "modelPath",
+ COALESCE(mu."name", imu."name") as "modelName",
+ COALESCE(mu."size", imu."size") as "modelSize",
+ ic."unitCost" as "unitCost",
+ qlp."quantity" as "qty",
+ qlp."unitPrice",
+ CASE
+ WHEN q."revisionId" > 0 THEN q."quoteId" || '-' || q."revisionId"::text
+ ELSE q."quoteId"
+ END as "quoteReadableId",
+ q."createdAt" as "quoteCreatedAt",
+ q."customerId"
+ FROM "quoteLine" ql
+ INNER JOIN "quote" q ON q.id = ql."quoteId"
+ LEFT JOIN "modelUpload" mu ON ql."modelUploadId" = mu."id"
+ INNER JOIN "item" i ON i.id = ql."itemId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ LEFT JOIN "modelUpload" imu ON imu.id = i."modelUploadId"
+ LEFT JOIN "quoteLinePrice" qlp ON qlp."quoteLineId" = ql.id
+);
+
+-- Forked from 20241021200602_thumbnails.sql
+CREATE OR REPLACE VIEW "salesRfqLines" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ srl.*,
+ mu.id AS "modelId",
+ mu."autodeskUrn",
+ mu."modelPath",
+ mu.name AS "modelName",
+ mu.size AS "modelSize",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ i.name AS "itemName",
+ i."defaultMethodType" AS "methodType",
+ i."readableId" AS "itemReadableId",
+ i.type AS "itemType"
+ FROM "salesRfqLine" srl
+ LEFT JOIN "item" i ON i.id = srl."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = srl."modelUploadId";
+
+-- Forked from 20260417000300_storage-unit-recreate-dependents.sql
+CREATE OR REPLACE VIEW "jobs" WITH(SECURITY_INVOKER=true) AS
+WITH job_model AS (
+ SELECT
+ j.id AS job_id,
+ j."companyId",
+ COALESCE(j."modelUploadId", i."modelUploadId") AS model_upload_id
+ FROM "job" j
+ INNER JOIN "item" i ON j."itemId" = i."id" AND j."companyId" = i."companyId"
+)
+SELECT
+ j.*,
+ jmm."id" as "jobMakeMethodId",
+ i.name,
+ i."readableIdWithRevision" as "itemReadableIdWithRevision",
+ i.type as "itemType",
+ i.name as "description",
+ i."itemTrackingType",
+ i.active,
+ i."replenishmentSystem",
+ mu.id as "modelId",
+ mu."autodeskUrn",
+ mu."modelPath",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END as "thumbnailPath",
+ mu."name" as "modelName",
+ mu."size" as "modelSize",
+ so."salesOrderId" as "salesOrderReadableId",
+ qo."quoteId" as "quoteReadableId"
+FROM "job" j
+LEFT JOIN "jobMakeMethod" jmm ON jmm."jobId" = j.id AND jmm."parentMaterialId" IS NULL
+INNER JOIN "item" i ON j."itemId" = i."id" AND j."companyId" = i."companyId"
+LEFT JOIN job_model jm ON j.id = jm.job_id AND j."companyId" = jm."companyId"
+LEFT JOIN "modelUpload" mu ON mu.id = jm.model_upload_id
+LEFT JOIN "salesOrder" so on j."salesOrderId" = so.id AND j."companyId" = so."companyId"
+LEFT JOIN "quote" qo ON j."quoteId" = qo.id AND j."companyId" = qo."companyId";
+
+-- Forked from 20260417000300_storage-unit-recreate-dependents.sql
+CREATE OR REPLACE VIEW "openProductionOrders"
+WITH (security_invoker = true)
+AS (
+ SELECT
+ j."id",
+ j."itemId",
+ j."jobId",
+ j."productionQuantity" - j."quantityReceivedToInventory" AS "quantityToReceive",
+ j."unitOfMeasureCode",
+ j."companyId",
+ i."replenishmentSystem",
+ i."itemTrackingType",
+ ir."leadTime" AS "leadTime",
+ j."locationId",
+ j."dueDate",
+ j."deadlineType"
+ FROM "job" j
+ INNER JOIN "item" i ON j."itemId" = i."id"
+ INNER JOIN "itemReplenishment" ir ON i."id" = ir."itemId"
+ WHERE j."status" IN (
+ 'Planned',
+ 'Ready',
+ 'In Progress',
+ 'Paused'
+ )
+ AND j."salesOrderId" IS NULL
+);
+
+-- Forked from 20260417000300_storage-unit-recreate-dependents.sql
+CREATE OR REPLACE VIEW "openJobMaterialLines" AS (
+ SELECT
+ jm."id",
+ jm."jobId",
+ jmm."parentMaterialId",
+ jm."jobMakeMethodId",
+ j."jobId" as "jobReadableId",
+ jm."itemId",
+ jm."quantityToIssue",
+ jm."unitOfMeasureCode",
+ jm."companyId",
+ i1."replenishmentSystem",
+ i1."itemTrackingType",
+ ir."leadTime" AS "leadTime",
+ j."locationId",
+ j."dueDate"
+ FROM "jobMaterial" jm
+ INNER JOIN "job" j ON jm."jobId" = j."id"
+ INNER JOIN "jobMakeMethod" jmm ON jm."jobMakeMethodId" = jmm."id"
+ INNER JOIN "item" i1 ON jm."itemId" = i1."id"
+ INNER JOIN "item" i2 ON j."itemId" = i2."id"
+ INNER JOIN "itemReplenishment" ir ON i2."id" = ir."itemId"
+ WHERE j."status" IN (
+ 'Planned',
+ 'Ready',
+ 'In Progress',
+ 'Paused'
+ )
+ AND jm."methodType" != 'Make to Order'
+);
+
+-- Forked from 20260417000300_storage-unit-recreate-dependents.sql
+CREATE OR REPLACE VIEW "jobMaterialWithMakeMethodId" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ jm.*,
+ s."name" AS "storageUnitName",
+ jmm."id" AS "jobMaterialMakeMethodId",
+ jmm.version AS "version",
+ i."readableIdWithRevision" as "itemReadableId",
+ i."readableId" as "itemReadableIdWithoutRevision"
+ FROM "jobMaterial" jm
+ LEFT JOIN "jobMakeMethod" jmm
+ ON jmm."parentMaterialId" = jm."id"
+ LEFT JOIN "storageUnit" s ON s.id = jm."storageUnitId"
+ INNER JOIN "item" i ON i.id = jm."itemId";
+
+-- Forked from 20260721004140_operation-type-consolidation.sql
+CREATE OR REPLACE VIEW "jobOperationsWithMakeMethods" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ mm.id AS "makeMethodId",
+ jo.*
+ FROM "jobOperation" jo
+ INNER JOIN "jobMakeMethod" jmm
+ ON jo."jobMakeMethodId" = jmm.id
+ LEFT JOIN "makeMethod" mm
+ ON jmm."itemId" = mm."itemId" AND jmm."version" = mm."version";
+
+-- Forked from 20260721004140_operation-type-consolidation.sql
+CREATE OR REPLACE VIEW "jobOperationsWithDependencies"
+WITH (security_invoker = true)
+AS
+SELECT
+ jo.*,
+ COALESCE(
+ (
+ SELECT array_agg(jod."dependsOnId")
+ FROM "jobOperationDependency" jod
+ WHERE jod."operationId" = jo.id
+ ),
+ '{}'::text[]
+ ) AS "dependencies"
+FROM "jobOperation" jo;
+
+-- Forked from 20260721004140_operation-type-consolidation.sql
+CREATE OR REPLACE VIEW "quoteOperationsWithMakeMethods" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ mm.id AS "makeMethodId",
+ qo.*
+ FROM "quoteOperation" qo
+ INNER JOIN "quoteMakeMethod" qmm
+ ON qo."quoteMakeMethodId" = qmm.id
+ LEFT JOIN "makeMethod" mm
+ ON qmm."itemId" = mm."itemId" AND qmm."version" = mm."version";
+
+-- Forked from 20260524143827_fixed-assets.sql
+CREATE OR REPLACE VIEW "workCenters" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ wc.*,
+ l.name as "locationName",
+ d.name as "departmentName",
+ wcp.processes
+ FROM "workCenter" wc
+ LEFT JOIN "location" l
+ ON wc."locationId" = l.id
+ LEFT JOIN "department" d
+ ON wc."departmentId" = d.id
+ LEFT JOIN (
+ SELECT
+ "workCenterId",
+ array_agg("processId"::text) as processes
+ FROM "workCenterProcess" wcp
+ INNER JOIN "process" p ON wcp."processId" = p.id
+ GROUP BY "workCenterId"
+ ) wcp ON wc.id = wcp."workCenterId";
+
+-- Forked from 20260524143827_fixed-assets.sql
+CREATE OR REPLACE VIEW "workCentersWithBlockingStatus" WITH (security_invoker = true) AS
+SELECT
+ wc.*,
+ l.name AS "locationName",
+ COALESCE(
+ (SELECT COUNT(*) > 0
+ FROM "maintenanceDispatch" md
+ WHERE md."workCenterId" = wc.id
+ AND md.status = 'In Progress'
+ AND md."oeeImpact" IN ('Down', 'Planned')
+ ), false
+ ) AS "isBlocked",
+ (
+ SELECT md.id
+ FROM "maintenanceDispatch" md
+ WHERE md."workCenterId" = wc.id
+ AND md.status = 'In Progress'
+ AND md."oeeImpact" IN ('Down', 'Planned')
+ ORDER BY md."createdAt" DESC
+ LIMIT 1
+ ) AS "blockingDispatchId",
+ (
+ SELECT md."maintenanceDispatchId"
+ FROM "maintenanceDispatch" md
+ WHERE md."workCenterId" = wc.id
+ AND md.status = 'In Progress'
+ AND md."oeeImpact" IN ('Down', 'Planned')
+ ORDER BY md."createdAt" DESC
+ LIMIT 1
+ ) AS "blockingDispatchReadableId"
+FROM "workCenter" wc
+LEFT JOIN "location" l ON wc."locationId" = l.id;
+
+-- RPCs whose RETURNS TABLE clamped scale on read (redeclared with bare
+-- NUMERIC; bodies forked verbatim from their newest definitions) -------------
+
+-- Forked from 20240927033740_job-operations-for-mes.sql
+DROP FUNCTION IF EXISTS get_job_operations_by_work_center(TEXT, TEXT);
+CREATE OR REPLACE FUNCTION get_job_operations_by_work_center(
+ work_center_id TEXT,
+ location_id TEXT
+)
+RETURNS TABLE (
+ "id" TEXT,
+ "jobId" TEXT,
+ "operationOrder" DOUBLE PRECISION,
+ "processId" TEXT,
+ "workCenterId" TEXT,
+ "description" TEXT,
+ "setupTime" NUMERIC,
+ "setupUnit" factor,
+ "laborTime" NUMERIC,
+ "laborUnit" factor,
+ "machineTime" NUMERIC,
+ "machineUnit" factor,
+ "operationOrderType" "methodOperationOrder",
+ "jobReadableId" TEXT,
+ "jobStatus" "jobStatus",
+ "jobDueDate" DATE,
+ "jobDeadlineType" "deadlineType",
+ "parentMaterialId" TEXT,
+ "itemReadableId" TEXT,
+ "operationStatus" "jobOperationStatus",
+ "operationQuantity" NUMERIC,
+ "quantityComplete" NUMERIC,
+ "quantityScrapped" NUMERIC
+)
+SECURITY INVOKER
+AS $$
+BEGIN
+ RETURN QUERY
+ WITH relevant_jobs AS (
+ SELECT *
+ FROM "job"
+ WHERE "locationId" = location_id
+ AND ("status" = 'Ready' OR "status" = 'In Progress' OR "status" = 'Paused')
+ )
+ SELECT
+ jo."id",
+ jo."jobId",
+ jo."order" AS "operationOrder",
+ jo."processId",
+ jo."workCenterId",
+ jo."description",
+ jo."setupTime",
+ jo."setupUnit",
+ jo."laborTime",
+ jo."laborUnit",
+ jo."machineTime",
+ jo."machineUnit",
+ jo."operationOrder" AS "operationOrderType",
+ rj."jobId" AS "jobReadableId",
+ rj."status" AS "jobStatus",
+ rj."dueDate" AS "jobDueDate",
+ rj."deadlineType" AS "jobDeadlineType",
+ jmm."parentMaterialId",
+ i."readableId" as "itemReadableId",
+ CASE
+ WHEN rj."status" = 'Paused' THEN 'Paused'
+ ELSE jo."status"
+ END AS "operationStatus",
+ jo."operationQuantity",
+ jo."quantityComplete",
+ jo."quantityScrapped"
+ FROM "jobOperation" jo
+ JOIN relevant_jobs rj ON rj.id = jo."jobId"
+ LEFT JOIN "jobMakeMethod" jmm ON jo."jobMakeMethodId" = jmm.id
+ LEFT JOIN "item" i ON jmm."itemId" = i.id
+ WHERE jo."workCenterId" = work_center_id;
+END;
+$$ LANGUAGE plpgsql;
+
+-- Forked from 20250828115039_portal-steps-use-process-name.sql. The clamped
+-- return types truncated portal prices and quantities on read.
+DROP FUNCTION IF EXISTS get_sales_order_lines_by_customer_id(TEXT);
+CREATE OR REPLACE FUNCTION get_sales_order_lines_by_customer_id(customer_id TEXT)
+RETURNS TABLE (
+ "customerReference" TEXT,
+ "salesOrderId" TEXT,
+ "customerContactName" TEXT,
+ "customerEngineeringContactName" TEXT,
+ "saleQuantity" NUMERIC,
+ "quantityToSend" NUMERIC,
+ "quantitySent" NUMERIC,
+ "quantityInvoiced" NUMERIC,
+ "unitPrice" NUMERIC,
+ "unitOfMeasureCode" TEXT,
+ "locationId" TEXT,
+ "orderDate" DATE,
+ "promisedDate" DATE,
+ "receiptRequestedDate" DATE,
+ "receiptPromisedDate" DATE,
+ "salesOrderStatus" "salesOrderStatus",
+ "readableId" TEXT,
+ "revision" TEXT,
+ "readableIdWithRevision" TEXT,
+ "customerId" TEXT,
+ "thumbnailPath" TEXT,
+ "jobOperations" JSONB,
+ "jobQuantityShipped" NUMERIC,
+ "jobQuantityComplete" NUMERIC,
+ "jobProductionQuantity" NUMERIC,
+ "jobStatus" "jobStatus"
+) AS $$
+BEGIN
+ RETURN QUERY
+ SELECT
+ so."customerReference",
+ so."salesOrderId",
+ COALESCE(pc."fullName", pc."email") AS "customerContactName",
+ COALESCE(ec."fullName", ec."email") AS "customerEngineeringContactName",
+ sol."saleQuantity",
+ sol."quantityToSend",
+ sol."quantitySent",
+ sol."quantityInvoiced",
+ sol."unitPrice",
+ sol."unitOfMeasureCode",
+ sol."locationId",
+ so."orderDate",
+ sol."promisedDate",
+ ss."receiptRequestedDate",
+ ss."receiptPromisedDate",
+ so."status" AS "salesOrderStatus",
+ i."readableId",
+ i."revision",
+ i."readableIdWithRevision",
+ so."customerId",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ COALESCE(
+ (
+ SELECT jsonb_agg(DISTINCT
+ jsonb_build_object(
+ 'id', jo.id,
+ 'jobId', jo."jobId",
+ 'order', jo."order",
+ 'status', jo.status,
+ 'description', p."name",
+ 'operationType', jo."operationType",
+ 'operationQuantity', jo."operationQuantity",
+ 'quantityComplete', jo."quantityComplete"
+ )
+ )
+ FROM "jobOperation" jo
+ INNER JOIN "jobMakeMethod" jmm ON jmm."id" = jo."jobMakeMethodId"
+ INNER JOIN "process" p ON p."id" = jo."processId"
+ WHERE jo."jobId" = j.id AND jmm."parentMaterialId" IS NULL
+ ),
+ '[]'::jsonb
+ ) AS "jobOperations",
+ j."quantityShipped" AS "jobQuantityShipped",
+ j."quantityComplete" AS "jobQuantityComplete",
+ j."productionQuantity" AS "jobProductionQuantity",
+ j."status" AS "jobStatus"
+ FROM "salesOrderLine" sol
+ INNER JOIN "salesOrder" so
+ ON so."id" = sol."salesOrderId"
+ LEFT JOIN "salesOrderShipment" ss
+ ON ss."id" = so."id"
+ INNER JOIN "item" i
+ ON i."id" = sol."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN "job" j
+ ON j."salesOrderLineId" = sol."id"
+ LEFT JOIN "customerContact" pcc
+ ON pcc."id" = so."customerContactId"
+ LEFT JOIN "contact" pc
+ ON pc."id" = pcc."contactId"
+ LEFT JOIN "customerContact" ecc
+ ON ecc."id" = so."customerEngineeringContactId"
+ LEFT JOIN "contact" ec
+ ON ec."id" = ecc."contactId"
+ WHERE so."customerId" = customer_id;
+END;
+$$ LANGUAGE plpgsql;
diff --git a/packages/database/supabase/migrations/20260813113309_currency-trailing-zeros-setting.sql b/packages/database/supabase/migrations/20260813113309_currency-trailing-zeros-setting.sql
new file mode 100644
index 0000000000..f4f33a6210
--- /dev/null
+++ b/packages/database/supabase/migrations/20260813113309_currency-trailing-zeros-setting.sql
@@ -0,0 +1,25 @@
+-- Currency display: whether a currency amount keeps the non-significant zeros
+-- its currency's decimals imply.
+--
+-- The DEFAULT is true — amounts pad to currency.decimalPlaces ("$300.00",
+-- "$3.50", "¥63"). Fixed-width money is the accounting convention: it keeps
+-- columns of amounts aligned in ledgers, invoices and reports, and an explicit
+-- ".00" reads as a currency amount rather than a bare count. We are not
+-- innovating on that by default.
+--
+-- Set false and display drops the padding instead ("$300", "$3.5"), which is
+-- what some teams prefer for dense on-screen tables. QuickBooks exposes the
+-- same choice as a preference rather than picking for the customer.
+--
+-- Named POSITIVELY, like its neighbours showSupplierReadableId and
+-- showCustomerReadableId. The negative form it replaced ("hide...") had to be
+-- inverted at three separate layers — the switch, the fetcher payload, and the
+-- formatter hook — each one a place to get the polarity backwards.
+--
+-- DISPLAY ONLY, and in-app only: stored values are unaffected (rounding still
+-- happens at the currency's decimals either way), and printed documents keep
+-- padding regardless, since a customer-facing invoice is exactly where
+-- fixed-width money matters most.
+
+ALTER TABLE "companySettings"
+ ADD COLUMN IF NOT EXISTS "showCurrencyTrailingZeros" BOOLEAN NOT NULL DEFAULT true;
diff --git a/packages/documents/src/email/PurchaseOrderEmail.tsx b/packages/documents/src/email/PurchaseOrderEmail.tsx
index 00b2b0ee8c..666ecc066b 100644
--- a/packages/documents/src/email/PurchaseOrderEmail.tsx
+++ b/packages/documents/src/email/PurchaseOrderEmail.tsx
@@ -17,7 +17,7 @@ import {
getLineDescriptionDetails,
getTotal
} from "../utils/purchase-order";
-import { getCurrencyFormatter } from "../utils/shared";
+import { getMoneyFormatter } from "../utils/shared";
import ExternalNotes from "./components/ExternalNotes";
import {
EmailThemeProvider,
@@ -30,6 +30,8 @@ interface PurchaseOrderEmailProps extends Email {
purchaseOrderLines: Database["public"]["Views"]["purchaseOrderLines"]["Row"][];
purchaseOrderLocations: Database["public"]["Views"]["purchaseOrderLocations"]["Row"];
paymentTerms: { id: string; name: string }[];
+ /** currency.decimalPlaces for the document currency; null falls back to 2 */
+ currencyDecimals?: number | null;
}
const PurchaseOrderEmail = ({
@@ -40,7 +42,8 @@ const PurchaseOrderEmail = ({
purchaseOrderLocations,
recipient,
sender,
- paymentTerms
+ paymentTerms,
+ currencyDecimals
}: PurchaseOrderEmailProps) => {
const {
deliveryName,
@@ -60,9 +63,12 @@ const PurchaseOrderEmail = ({
customerCountryName
} = purchaseOrderLocations;
- const formatter = getCurrencyFormatter(
- company.baseCurrencyCode ?? "USD",
- locale
+ // The DOCUMENT's currency, not the company's — a supplier priced in JPY must
+ // not be emailed as "$20.00". Decimals come from that currency's row.
+ const formatter = getMoneyFormatter(
+ locale,
+ currencyDecimals,
+ purchaseOrder.currencyCode ?? company.baseCurrencyCode ?? "USD"
);
const preview = (
<Preview>{`${purchaseOrder.purchaseOrderId} from ${company.name}`}</Preview>
diff --git a/packages/documents/src/email/SalesInvoiceEmail.tsx b/packages/documents/src/email/SalesInvoiceEmail.tsx
index 2c2890d61a..84a27b3a3f 100644
--- a/packages/documents/src/email/SalesInvoiceEmail.tsx
+++ b/packages/documents/src/email/SalesInvoiceEmail.tsx
@@ -18,7 +18,7 @@ import {
getLineTotal,
getTotal
} from "../utils/sales-invoice";
-import { getCurrencyFormatter } from "../utils/shared";
+import { getMoneyFormatter } from "../utils/shared";
import ExternalNotes from "./components/ExternalNotes";
import {
EmailThemeProvider,
@@ -32,6 +32,8 @@ interface SalesInvoiceEmailProps extends Email {
salesInvoiceLocations: Database["public"]["Views"]["salesInvoiceLocations"]["Row"];
salesInvoiceShipment: Database["public"]["Tables"]["salesInvoiceShipment"]["Row"];
paymentTerms: { id: string; name: string }[];
+ /** currency.decimalPlaces for the document currency; null falls back to 2 */
+ currencyDecimals?: number | null;
}
const SalesInvoiceEmail = ({
@@ -43,6 +45,7 @@ const SalesInvoiceEmail = ({
salesInvoiceShipment,
recipient,
sender,
+ currencyDecimals,
paymentTerms
}: SalesInvoiceEmailProps) => {
const {
@@ -56,7 +59,7 @@ const SalesInvoiceEmail = ({
} = salesInvoiceLocations;
const currencyCode = salesInvoice.currencyCode ?? company.baseCurrencyCode;
- const formatter = getCurrencyFormatter(currencyCode ?? "USD", locale);
+ const formatter = getMoneyFormatter(locale, currencyDecimals, currencyCode);
const preview = (
<Preview>{`${salesInvoice.invoiceId} from ${company.name}`}</Preview>
);
diff --git a/packages/documents/src/email/SalesOrderEmail.tsx b/packages/documents/src/email/SalesOrderEmail.tsx
index d430e633c5..6b81e7c92f 100644
--- a/packages/documents/src/email/SalesOrderEmail.tsx
+++ b/packages/documents/src/email/SalesOrderEmail.tsx
@@ -18,7 +18,7 @@ import {
getLineTotal,
getTotal
} from "../utils/sales-order";
-import { getCurrencyFormatter } from "../utils/shared";
+import { getMoneyFormatter } from "../utils/shared";
import ExternalNotes from "./components/ExternalNotes";
import {
EmailThemeProvider,
@@ -31,6 +31,8 @@ interface SalesOrderEmailProps extends Email {
salesOrderLines: Database["public"]["Views"]["salesOrderLines"]["Row"][];
salesOrderLocations: Database["public"]["Views"]["salesOrderLocations"]["Row"];
paymentTerms: { id: string; name: string }[];
+ /** currency.decimalPlaces for the document currency; null falls back to 2 */
+ currencyDecimals?: number | null;
}
const SalesOrderEmail = ({
@@ -41,7 +43,8 @@ const SalesOrderEmail = ({
salesOrderLocations,
recipient,
sender,
- paymentTerms
+ paymentTerms,
+ currencyDecimals
}: SalesOrderEmailProps) => {
const {
customerName,
@@ -60,9 +63,12 @@ const SalesOrderEmail = ({
// paymentCountryName,
} = salesOrderLocations;
- const formatter = getCurrencyFormatter(
- company.baseCurrencyCode ?? "USD",
- locale
+ // The DOCUMENT's currency, not the company's — a supplier priced in JPY must
+ // not be emailed as "$20.00". Decimals come from that currency's row.
+ const formatter = getMoneyFormatter(
+ locale,
+ currencyDecimals,
+ salesOrder.currencyCode ?? company.baseCurrencyCode ?? "USD"
);
const preview = (
<Preview>{`${salesOrder.salesOrderId} from ${company.name}`}</Preview>
diff --git a/packages/documents/src/pdf/PurchaseOrderPDF.tsx b/packages/documents/src/pdf/PurchaseOrderPDF.tsx
index d068c13ba0..fd2da26a7c 100644
--- a/packages/documents/src/pdf/PurchaseOrderPDF.tsx
+++ b/packages/documents/src/pdf/PurchaseOrderPDF.tsx
@@ -8,7 +8,7 @@ import {
resolveTemplate
} from "../template";
import type { AccountsPayableBillingAddress, PDF } from "../types";
-import { resolveRegistrationLine } from "../utils/shared";
+import { getMoneyFormatter, resolveRegistrationLine } from "../utils/shared";
import type { PurchaseOrderData } from "./blocks/purchaseOrder";
import {
buildPurchaseOrderVars,
@@ -31,6 +31,8 @@ interface PurchaseOrderPDFProps extends PDF {
template?: DocumentTemplate | null;
/** Shared sections referenced by the template, keyed by id. */
sections?: Record<string, ResolvedSection>;
+ /** Settlement decimals from the document currency's row; null/omitted falls back to 2. */
+ currencyDecimals?: number | null;
}
const PurchaseOrderPDF = ({
@@ -45,17 +47,14 @@ const PurchaseOrderPDF = ({
terms,
thumbnails,
locale,
+ currencyDecimals,
template,
sections = {},
title = "Purchase Order"
}: PurchaseOrderPDFProps) => {
const currencyCode =
purchaseOrder.currencyCode ?? company.baseCurrencyCode ?? "USD";
- const numberFormatter = new Intl.NumberFormat(locale, {
- style: "decimal",
- minimumFractionDigits: 2,
- maximumFractionDigits: 2
- });
+ const numberFormatter = getMoneyFormatter(locale, currencyDecimals);
const headerTitle = purchaseOrder?.purchaseOrderId
? `${title}: ${purchaseOrder.purchaseOrderId}`
diff --git a/packages/documents/src/pdf/QuotePDF.tsx b/packages/documents/src/pdf/QuotePDF.tsx
index 1d27beb8b7..6c06c69c3a 100644
--- a/packages/documents/src/pdf/QuotePDF.tsx
+++ b/packages/documents/src/pdf/QuotePDF.tsx
@@ -8,7 +8,7 @@ import {
resolveTemplate
} from "../template";
import type { AccountsReceivableBillingAddress, PDF } from "../types";
-import { resolveRegistrationLine } from "../utils/shared";
+import { getMoneyFormatter, resolveRegistrationLine } from "../utils/shared";
import type { QuoteCustomerDetails, QuoteData } from "./blocks/quote";
import { buildQuoteVars, quoteBlockRegistry } from "./blocks/quote";
import { Template } from "./components";
@@ -33,6 +33,8 @@ interface QuotePDFProps extends PDF {
thumbnails: Record<string, string | null>;
template?: DocumentTemplate | null;
sections?: Record<string, ResolvedSection>;
+ /** Settlement decimals from the document currency's row; null/omitted falls back to 2. */
+ currencyDecimals?: number | null;
}
const QuotePDF = ({
@@ -50,6 +52,7 @@ const QuotePDF = ({
terms,
thumbnails,
locale,
+ currencyDecimals,
template,
sections = {},
title = "Quote"
@@ -57,11 +60,7 @@ const QuotePDF = ({
const currencyCode = quote.currencyCode ?? company.baseCurrencyCode;
const shouldConvertCurrency =
!!currencyCode && currencyCode !== company.baseCurrencyCode;
- const numberFormatter = new Intl.NumberFormat(locale, {
- style: "decimal",
- minimumFractionDigits: 2,
- maximumFractionDigits: 2
- });
+ const numberFormatter = getMoneyFormatter(locale, currencyDecimals);
const pricesByLine = quoteLinePrices.reduce<Record<string, QuoteLinePrice[]>>(
(acc, price) => {
diff --git a/packages/documents/src/pdf/SalesInvoicePDF.tsx b/packages/documents/src/pdf/SalesInvoicePDF.tsx
index baf013d83d..01096a4236 100644
--- a/packages/documents/src/pdf/SalesInvoicePDF.tsx
+++ b/packages/documents/src/pdf/SalesInvoicePDF.tsx
@@ -8,7 +8,7 @@ import {
resolveTemplate
} from "../template";
import type { AccountsReceivableBillingAddress, PDF } from "../types";
-import { resolveRegistrationLine } from "../utils/shared";
+import { getMoneyFormatter, resolveRegistrationLine } from "../utils/shared";
import type { SalesInvoiceData, SalesInvoiceLocations } from "./blocks";
import { buildSalesInvoiceVars, salesInvoiceBlockRegistry } from "./blocks";
import { Template } from "./components";
@@ -31,6 +31,8 @@ interface SalesInvoicePDFProps extends PDF {
template?: DocumentTemplate | null;
/** Shared sections referenced by the template, keyed by id. */
sections?: Record<string, ResolvedSection>;
+ /** Settlement decimals from the document currency's row; null/omitted falls back to 2. */
+ currencyDecimals?: number | null;
}
const SalesInvoicePDF = ({
@@ -48,16 +50,13 @@ const SalesInvoicePDF = ({
shippingMethods,
thumbnails,
locale,
+ currencyDecimals,
template,
sections = {},
title = "Invoice"
}: SalesInvoicePDFProps) => {
const currencyCode = salesInvoice.currencyCode ?? company.baseCurrencyCode;
- const numberFormatter = new Intl.NumberFormat(locale, {
- style: "decimal",
- minimumFractionDigits: 2,
- maximumFractionDigits: 2
- });
+ const numberFormatter = getMoneyFormatter(locale, currencyDecimals);
const { blocks, theme, settings, headerSectionId, footerSectionId } =
resolveTemplate("salesInvoice", template);
diff --git a/packages/documents/src/pdf/SalesOrderPDF.tsx b/packages/documents/src/pdf/SalesOrderPDF.tsx
index 5e30c0c7ff..06dfb3ad6e 100644
--- a/packages/documents/src/pdf/SalesOrderPDF.tsx
+++ b/packages/documents/src/pdf/SalesOrderPDF.tsx
@@ -8,7 +8,7 @@ import {
resolveTemplate
} from "../template";
import type { AccountsReceivableBillingAddress, PDF } from "../types";
-import { resolveRegistrationLine } from "../utils/shared";
+import { getMoneyFormatter, resolveRegistrationLine } from "../utils/shared";
import type { SalesOrderData, SalesOrderLocations } from "./blocks/salesOrder";
import {
buildSalesOrderVars,
@@ -32,6 +32,8 @@ interface SalesOrderPDFProps extends PDF {
template?: DocumentTemplate | null;
/** Shared sections referenced by the template, keyed by id. */
sections?: Record<string, ResolvedSection>;
+ /** Settlement decimals from the document currency's row; null/omitted falls back to 2. */
+ currencyDecimals?: number | null;
}
const SalesOrderPDF = ({
@@ -47,16 +49,13 @@ const SalesOrderPDF = ({
shippingMethods,
thumbnails,
locale,
+ currencyDecimals,
template,
sections = {},
title = "Sales Order"
}: SalesOrderPDFProps) => {
const currencyCode = salesOrder.currencyCode ?? company.baseCurrencyCode;
- const numberFormatter = new Intl.NumberFormat(locale, {
- style: "decimal",
- minimumFractionDigits: 2,
- maximumFractionDigits: 2
- });
+ const numberFormatter = getMoneyFormatter(locale, currencyDecimals);
const { blocks, theme, settings, headerSectionId, footerSectionId } =
resolveTemplate("salesOrder", template);
diff --git a/packages/documents/src/pdf/blocks/LineItemsBlock.tsx b/packages/documents/src/pdf/blocks/LineItemsBlock.tsx
index c4ccf01370..b4367ea0a3 100644
--- a/packages/documents/src/pdf/blocks/LineItemsBlock.tsx
+++ b/packages/documents/src/pdf/blocks/LineItemsBlock.tsx
@@ -1,4 +1,5 @@
import type { JSONContent } from "@carbon/react";
+import { formatPercent } from "@carbon/utils";
import { Image, Text, View } from "@react-pdf/renderer";
import {
DEFAULT_LINE_ITEMS_OPTIONS,
@@ -23,7 +24,8 @@ export function LineItemsBlock({
data: SalesInvoiceData;
}) {
const tw = useTw();
- const { salesInvoiceLines, thumbnails, numberFormatter, theme } = data;
+ const { salesInvoiceLines, thumbnails, numberFormatter, theme, locale } =
+ data;
const opts = { ...DEFAULT_LINE_ITEMS_OPTIONS, ...block.options };
const overflow = itemTextOverflowStyle(opts);
let rowIndex = 0;
@@ -122,7 +124,7 @@ export function LineItemsBlock({
)}
{lineTaxPercent > 0 && (
<Text style={tw("text-[9px] text-gray-600")}>
- - Tax ({(lineTaxPercent * 100).toFixed(2)}%)
+ - Tax ({formatPercent(lineTaxPercent, locale)})
</Text>
)}
</View>
diff --git a/packages/documents/src/pdf/blocks/purchaseOrder/LineItemsBlock.tsx b/packages/documents/src/pdf/blocks/purchaseOrder/LineItemsBlock.tsx
index 8bcf80087f..3c9e0f94a5 100644
--- a/packages/documents/src/pdf/blocks/purchaseOrder/LineItemsBlock.tsx
+++ b/packages/documents/src/pdf/blocks/purchaseOrder/LineItemsBlock.tsx
@@ -73,6 +73,7 @@ export function LineItemsBlock({
const netValue =
(line.purchaseQuantity ?? 0) * (line.supplierUnitPrice ?? 0);
+ const taxPercentLabel = formatTaxPercent(line.taxPercent, locale);
return (
<View key={line.id}>
@@ -171,9 +172,9 @@ export function LineItemsBlock({
<Text style={tw("text-gray-600")}>
{numberFormatter.format(line.supplierTaxAmount ?? 0)}
</Text>
- {formatTaxPercent(line.taxPercent) && (
+ {taxPercentLabel && (
<Text style={tw("text-[6px] text-gray-400")}>
- {formatTaxPercent(line.taxPercent)}
+ {taxPercentLabel}
</Text>
)}
</View>
diff --git a/packages/documents/src/pdf/blocks/quote/LineItemsBlock.tsx b/packages/documents/src/pdf/blocks/quote/LineItemsBlock.tsx
index 1e5a5bfd08..61a22df1cd 100644
--- a/packages/documents/src/pdf/blocks/quote/LineItemsBlock.tsx
+++ b/packages/documents/src/pdf/blocks/quote/LineItemsBlock.tsx
@@ -1,6 +1,11 @@
import type { Database } from "@carbon/database";
import type { JSONContent } from "@carbon/react";
-import { pluralize } from "@carbon/utils";
+import {
+ DEFAULT_CURRENCY_DECIMALS,
+ formatPercent,
+ moneyFormatOptions,
+ pluralize
+} from "@carbon/utils";
import { Image, Text, View } from "@react-pdf/renderer";
import {
DEFAULT_LINE_ITEMS_OPTIONS,
@@ -42,6 +47,21 @@ export function LineItemsBlock({
const overflow = itemTextOverflowStyle(opts);
let rowIndex = 0;
+ // Unlike its sales-order/purchase-order siblings, a quote carries a PER-LINE
+ // unit-price precision (`quoteLine.unitPricePrecision`, constrained to 2/3/4),
+ // so it cannot reuse the single hoisted `numberFormatter`. Index the few
+ // distinct precisions once instead of constructing a formatter per line.
+ const unitPriceFormatters = new Map<number, Intl.NumberFormat>();
+ const unitPriceFormatter = (precision: number | null | undefined) => {
+ const digits = precision ?? DEFAULT_CURRENCY_DECIMALS;
+ let formatter = unitPriceFormatters.get(digits);
+ if (!formatter) {
+ formatter = new Intl.NumberFormat(locale, moneyFormatOptions(digits));
+ unitPriceFormatters.set(digits, formatter);
+ }
+ return formatter;
+ };
+
return (
<View>
{/* Header */}
@@ -69,11 +89,9 @@ export function LineItemsBlock({
</View>
{quoteLines.map((line) => {
- const unitPriceNumberFormatter = new Intl.NumberFormat(locale, {
- style: "decimal",
- minimumFractionDigits: line.unitPricePrecision ?? 2,
- maximumFractionDigits: line.unitPricePrecision ?? 2
- });
+ const unitPriceNumberFormatter = unitPriceFormatter(
+ line.unitPricePrecision
+ );
const additionalCharges = line.additionalCharges ?? {};
@@ -195,7 +213,7 @@ export function LineItemsBlock({
))}
{taxPercent > 0 && (
<Text style={tw("text-[8px] text-gray-400")}>
- - Tax ({(taxPercent * 100).toFixed(2)}%)
+ - Tax ({formatPercent(taxPercent, locale)})
</Text>
)}
</View>
diff --git a/packages/documents/src/pdf/blocks/salesOrder/LineItemsBlock.tsx b/packages/documents/src/pdf/blocks/salesOrder/LineItemsBlock.tsx
index 934f90dc62..f2927f56ea 100644
--- a/packages/documents/src/pdf/blocks/salesOrder/LineItemsBlock.tsx
+++ b/packages/documents/src/pdf/blocks/salesOrder/LineItemsBlock.tsx
@@ -1,4 +1,5 @@
import type { JSONContent } from "@carbon/react";
+import { formatPercent } from "@carbon/utils";
import { Image, Text, View } from "@react-pdf/renderer";
import {
DEFAULT_LINE_ITEMS_OPTIONS,
@@ -23,7 +24,7 @@ export function LineItemsBlock({
data: SalesOrderData;
}) {
const tw = useTw();
- const { salesOrderLines, thumbnails, numberFormatter, theme } = data;
+ const { salesOrderLines, thumbnails, numberFormatter, theme, locale } = data;
const opts = { ...DEFAULT_LINE_ITEMS_OPTIONS, ...block.options };
const overflow = itemTextOverflowStyle(opts);
let rowIndex = 0;
@@ -122,7 +123,7 @@ export function LineItemsBlock({
)}
{lineTaxPercent > 0 && (
<Text style={tw("text-[9px] text-gray-600")}>
- - Tax ({(lineTaxPercent * 100).toFixed(2)}%)
+ - Tax ({formatPercent(lineTaxPercent, locale)})
</Text>
)}
</View>
diff --git a/packages/documents/src/utils/shared.ts b/packages/documents/src/utils/shared.ts
index 7a4e9686c8..006c945cfb 100644
--- a/packages/documents/src/utils/shared.ts
+++ b/packages/documents/src/utils/shared.ts
@@ -1,3 +1,8 @@
+import {
+ DEFAULT_CURRENCY_DECIMALS,
+ formatPercent,
+ moneyFormatOptions
+} from "@carbon/utils";
import type { ResolvedSection } from "../template";
import { DEFAULT_REGISTRATION_NUMBER, interpolateString } from "../template";
@@ -75,20 +80,25 @@ export const resolveRegistrationLine = ({
};
export const formatTaxPercent = (
- taxPercent: number | null | undefined
+ taxPercent: number | null | undefined,
+ locale: string
): string | null => {
if (!taxPercent) return null;
- return `${(taxPercent * 100).toFixed(2)}%`;
+ return formatPercent(taxPercent, locale);
};
-export const getCurrencyFormatter = (
- baseCurrencyCode: string,
+/** Money for documents. `currency` decides only whether the SYMBOL renders:
+ * pass it for emails ("$300.00"), omit it for the PDF amount columns, which
+ * print the currency code separately ("300.00"). The digits are the same
+ * question either way and come from the currency row. */
+export const getMoneyFormatter = (
locale: string,
- maximumFractionDigits?: number
-) => {
- return new Intl.NumberFormat(locale, {
- style: "currency",
- currency: baseCurrencyCode,
- maximumFractionDigits: maximumFractionDigits ?? 2
- });
-};
+ decimalPlaces?: number | null,
+ currency?: string | null
+) =>
+ new Intl.NumberFormat(
+ locale,
+ moneyFormatOptions(decimalPlaces ?? DEFAULT_CURRENCY_DECIMALS, {
+ currency: currency ?? undefined
+ })
+ );
diff --git a/packages/ee/src/accounting/providers/xero/entities/bill.ts b/packages/ee/src/accounting/providers/xero/entities/bill.ts
index 91c24ec714..7221b5045f 100644
--- a/packages/ee/src/accounting/providers/xero/entities/bill.ts
+++ b/packages/ee/src/accounting/providers/xero/entities/bill.ts
@@ -5,6 +5,12 @@ import { type Accounting, BaseEntitySyncer } from "../../../core/types";
import { throwXeroApiError } from "../../../core/utils";
import { parseDotnetDate, type Xero } from "../models";
import type { XeroProvider } from "../provider";
+import {
+ xeroCurrencyRate,
+ xeroMoney,
+ xeroQuantity,
+ xeroUnitAmount
+} from "../serialize";
// Note: This syncer uses the default ID mapping from BaseEntitySyncer
// which uses the externalIntegrationMapping table with entityType "bill"
@@ -368,13 +374,14 @@ export class BillSyncer extends BaseEntitySyncer<
return {
Description: description,
- Quantity: line.quantity,
- UnitAmount: line.unitPrice,
+ Quantity: xeroQuantity(line.quantity),
+ UnitAmount: xeroUnitAmount(line.unitPrice),
ItemCode: itemCode?.slice(0, 30) ?? undefined,
// Use line's account number if specified, otherwise use default from settings
AccountCode: line.accountNumber ?? defaultAccountCode,
- TaxAmount: line.taxAmount ?? undefined,
- LineAmount: line.totalAmount,
+ TaxAmount:
+ line.taxAmount != null ? xeroMoney(line.taxAmount) : undefined,
+ LineAmount: xeroMoney(line.totalAmount),
// TaxType is required by Xero: INPUT for purchase tax, NONE for zero tax
TaxType: hasTax ? "INPUT" : "NONE"
};
@@ -404,11 +411,14 @@ export class BillSyncer extends BaseEntitySyncer<
DueDate: dueDate,
Status: CARBON_TO_XERO_STATUS[local.status],
CurrencyCode: local.currencyCode,
- CurrencyRate: local.exchangeRate !== 1 ? local.exchangeRate : undefined,
+ CurrencyRate:
+ local.exchangeRate !== 1
+ ? xeroCurrencyRate(local.exchangeRate)
+ : undefined,
LineItems: lineItems,
- SubTotal: local.subtotal,
- TotalTax: local.totalTax,
- Total: local.totalAmount
+ SubTotal: xeroMoney(local.subtotal),
+ TotalTax: xeroMoney(local.totalTax),
+ Total: xeroMoney(local.totalAmount)
};
}
diff --git a/packages/ee/src/accounting/providers/xero/entities/inventory-adjustment.ts b/packages/ee/src/accounting/providers/xero/entities/inventory-adjustment.ts
index 64fbd18123..c768dea8d0 100644
--- a/packages/ee/src/accounting/providers/xero/entities/inventory-adjustment.ts
+++ b/packages/ee/src/accounting/providers/xero/entities/inventory-adjustment.ts
@@ -2,6 +2,7 @@ import type { KyselyTx } from "@carbon/database/client";
import { type Accounting, BaseEntitySyncer } from "../../../core/types";
import { throwXeroApiError } from "../../../core/utils";
import { parseDotnetDate, type Xero } from "../models";
+import { xeroMoney } from "../serialize";
// Note: This is a push-only syncer (Carbon -> Xero).
// Inventory adjustments are pushed as Manual Journals to Xero since
@@ -197,7 +198,9 @@ export class InventoryAdjustmentSyncer extends BaseEntitySyncer<
local: Accounting.InventoryAdjustment
): Promise<Omit<Xero.ManualJournal, "UpdatedDateUTC">> {
const existingRemoteId = await this.getRemoteId(local.id);
- const amount = Math.abs(local.quantity) * local.unitCost;
+ // Serialize at Xero's monetary contract — raw float products must not
+ // reach the API
+ const amount = xeroMoney(Math.abs(local.quantity) * local.unitCost);
const isPositive = local.entryType === "Positive Adjmt.";
// Ensure item dependency is synced
diff --git a/packages/ee/src/accounting/providers/xero/entities/invoice.ts b/packages/ee/src/accounting/providers/xero/entities/invoice.ts
index a501c0daf0..f791aa7e5c 100644
--- a/packages/ee/src/accounting/providers/xero/entities/invoice.ts
+++ b/packages/ee/src/accounting/providers/xero/entities/invoice.ts
@@ -9,6 +9,12 @@ import {
import { throwXeroApiError } from "../../../core/utils";
import { parseDotnetDate, type Xero } from "../models";
import type { XeroProvider } from "../provider";
+import {
+ xeroCurrencyRate,
+ xeroMoney,
+ xeroQuantity,
+ xeroUnitAmount
+} from "../serialize";
const logger = getLogger("ee", "accounting", "xero");
@@ -334,15 +340,19 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<
// Build line items, resolving item dependencies
const lineItems: Xero.InvoiceLineItem[] = [];
for (const line of local.lines) {
- const taxAmount =
- (line.quantity * line.unitPrice * line.taxPercent) / 100;
+ // Round once, then derive: Xero recomputes the extension from what we
+ // send, so a rounded Quantity with an extension built from the unrounded
+ // one makes Quantity x UnitAmount disagree with LineAmount.
+ const quantity = xeroQuantity(line.quantity);
+ const unitAmount = xeroUnitAmount(line.unitPrice);
+ const taxAmount = (quantity * unitAmount * line.taxPercent) / 100;
const lineItem: Xero.InvoiceLineItem = {
Description: line.description ?? undefined,
- Quantity: line.quantity,
- UnitAmount: line.unitPrice,
- TaxAmount: taxAmount,
- LineAmount: line.quantity * line.unitPrice,
+ Quantity: quantity,
+ UnitAmount: unitAmount,
+ TaxAmount: xeroMoney(taxAmount),
+ LineAmount: xeroMoney(quantity * unitAmount),
// Use default account code from settings if no account specified
AccountCode: defaultAccountCode,
// TaxType is required by Xero: OUTPUT for sales tax, NONE for zero tax
@@ -388,13 +398,16 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<
Status: CARBON_TO_XERO_STATUS[local.status],
LineAmountTypes: "Exclusive", // Tax is calculated separately
LineItems: lineItems,
- SubTotal: local.subtotal,
- TotalTax: local.totalTax,
- Total: local.totalAmount,
- AmountDue: local.balance,
- AmountPaid: local.totalAmount - local.balance,
+ SubTotal: xeroMoney(local.subtotal),
+ TotalTax: xeroMoney(local.totalTax),
+ Total: xeroMoney(local.totalAmount),
+ AmountDue: xeroMoney(local.balance),
+ AmountPaid: xeroMoney(local.totalAmount - local.balance),
CurrencyCode: local.currencyCode,
- CurrencyRate: local.exchangeRate !== 1 ? local.exchangeRate : undefined
+ CurrencyRate:
+ local.exchangeRate !== 1
+ ? xeroCurrencyRate(local.exchangeRate)
+ : undefined
};
}
diff --git a/packages/ee/src/accounting/providers/xero/entities/purchase-order.ts b/packages/ee/src/accounting/providers/xero/entities/purchase-order.ts
index f858882ea7..3b08246a36 100644
--- a/packages/ee/src/accounting/providers/xero/entities/purchase-order.ts
+++ b/packages/ee/src/accounting/providers/xero/entities/purchase-order.ts
@@ -8,6 +8,12 @@ import {
import { throwXeroApiError } from "../../../core/utils";
import { parseDotnetDate, type Xero } from "../models";
import type { XeroProvider } from "../provider";
+import {
+ xeroCurrencyRate,
+ xeroMoney,
+ xeroQuantity,
+ xeroUnitAmount
+} from "../serialize";
// Note: This syncer uses the default ID mapping from BaseEntitySyncer
// which uses the externalIntegrationMapping table with entityType "purchaseOrder"
@@ -341,13 +347,14 @@ export class PurchaseOrderSyncer extends BaseEntitySyncer<
return {
Description: line.description ?? undefined,
- Quantity: line.quantity,
- UnitAmount: line.unitPrice,
+ Quantity: xeroQuantity(line.quantity),
+ UnitAmount: xeroUnitAmount(line.unitPrice),
ItemCode: itemCode?.slice(0, 30) ?? undefined,
// Use line's account number if specified, otherwise use default from settings
AccountCode: line.accountNumber ?? defaultAccountCode,
- TaxAmount: line.taxAmount ?? undefined,
- LineAmount: line.totalAmount,
+ TaxAmount:
+ line.taxAmount != null ? xeroMoney(line.taxAmount) : undefined,
+ LineAmount: xeroMoney(line.totalAmount),
// TaxType is required by Xero: INPUT for purchase tax, NONE for zero tax
TaxType: hasTax ? "INPUT" : "NONE"
};
@@ -367,12 +374,12 @@ export class PurchaseOrderSyncer extends BaseEntitySyncer<
CurrencyCode: local.currencyCode ?? undefined,
CurrencyRate:
local.exchangeRate && local.exchangeRate !== 1
- ? local.exchangeRate
+ ? xeroCurrencyRate(local.exchangeRate)
: undefined,
LineItems: lineItems,
- SubTotal: local.subtotal,
- TotalTax: local.totalTax,
- Total: local.totalAmount
+ SubTotal: xeroMoney(local.subtotal),
+ TotalTax: xeroMoney(local.totalTax),
+ Total: xeroMoney(local.totalAmount)
};
}
diff --git a/packages/ee/src/accounting/providers/xero/entities/sales-order.ts b/packages/ee/src/accounting/providers/xero/entities/sales-order.ts
index 6869eb2f6d..1cdc5fc5a6 100644
--- a/packages/ee/src/accounting/providers/xero/entities/sales-order.ts
+++ b/packages/ee/src/accounting/providers/xero/entities/sales-order.ts
@@ -6,6 +6,12 @@ import {
} from "../../../core/types";
import { throwXeroApiError } from "../../../core/utils";
import { parseDotnetDate, type Xero } from "../models";
+import {
+ xeroCurrencyRate,
+ xeroMoney,
+ xeroQuantity,
+ xeroUnitAmount
+} from "../serialize";
// Note: This is a push-only syncer (Carbon -> Xero).
// Carbon sales orders are pushed as Xero Quotes since Xero
@@ -270,12 +276,13 @@ export class SalesOrderSyncer extends BaseEntitySyncer<
continue;
}
+ const quantity = xeroQuantity(line.quantity);
const lineItem: Xero.QuoteLineItem = {
Description: line.description ?? undefined,
- Quantity: line.quantity,
- UnitAmount: line.unitPrice,
+ Quantity: quantity,
+ UnitAmount: xeroUnitAmount(line.unitPrice),
AccountCode: line.accountNumber ?? undefined,
- LineAmount: line.lineAmount
+ LineAmount: xeroMoney(line.lineAmount)
};
// If line has an item, ensure it's synced and set ItemCode
@@ -301,7 +308,10 @@ export class SalesOrderSyncer extends BaseEntitySyncer<
LineAmountTypes: "Exclusive",
LineItems: lineItems,
CurrencyCode: local.currencyCode,
- CurrencyRate: local.exchangeRate !== 1 ? local.exchangeRate : undefined,
+ CurrencyRate:
+ local.exchangeRate !== 1
+ ? xeroCurrencyRate(local.exchangeRate)
+ : undefined,
Title: `Sales Order ${local.salesOrderId}`
};
}
diff --git a/packages/ee/src/accounting/providers/xero/serialize.ts b/packages/ee/src/accounting/providers/xero/serialize.ts
new file mode 100644
index 0000000000..af7767b595
--- /dev/null
+++ b/packages/ee/src/accounting/providers/xero/serialize.ts
@@ -0,0 +1,26 @@
+import { round } from "@carbon/utils";
+
+// Xero's API rounds/validates decimal places per field class. These constants
+// are the boundary's external contract (not internal scale choices): monetary
+// line/total/payment fields carry two decimals, per-unit amounts allow four,
+// and exchange rates allow six. Rounding at serialization keeps payloads valid
+// no matter what precision Carbon carries internally — and stops raw float
+// artifacts (0.45000000000000007) from reaching the API.
+export const XERO_MONEY_DECIMALS = 2;
+export const XERO_UNIT_AMOUNT_DECIMALS = 4;
+export const XERO_QUANTITY_DECIMALS = 4;
+export const XERO_CURRENCY_RATE_DECIMALS = 6;
+
+export const xeroMoney = (value: number) => round(value, XERO_MONEY_DECIMALS);
+
+export const xeroUnitAmount = (value: number) =>
+ round(value, XERO_UNIT_AMOUNT_DECIMALS);
+
+/** Xero recomputes LineAmount as Quantity x UnitAmount, so the quantity we send
+ * has to be the same one the extension is derived from — round it once, here,
+ * and build the line off the result. */
+export const xeroQuantity = (value: number) =>
+ round(value, XERO_QUANTITY_DECIMALS);
+
+export const xeroCurrencyRate = (value: number) =>
+ round(value, XERO_CURRENCY_RATE_DECIMALS);
diff --git a/packages/form/src/components/Number.tsx b/packages/form/src/components/Number.tsx
index 04c96d8c7f..f9e8af9074 100644
--- a/packages/form/src/components/Number.tsx
+++ b/packages/form/src/components/Number.tsx
@@ -13,6 +13,7 @@ import {
NumberInputGroup,
NumberInputStepper
} from "@carbon/react";
+import { SCALE_FORMAT } from "@carbon/utils";
import { forwardRef } from "react";
import { LuChevronDown, LuChevronUp } from "react-icons/lu";
@@ -57,12 +58,11 @@ const Number = forwardRef<HTMLInputElement, FormNumberProps>(
const formState = useFormStateContext();
const isReadOnly = formState.isReadOnly || isReadOnlyProp;
const isDisabled = formState.isDisabled || isDisabledProp;
- const formatOptions =
- rest.formatOptions ??
- ({
- minimumFractionDigits: 0,
- maximumFractionDigits: 10
- } satisfies Intl.NumberFormatOptions);
+ // react-aria commits on blur via parse(format(x)), so this default is
+ // arithmetic on the stored value, not decoration. Quantity is the right
+ // fallback kind: it renders the full storage scale and no more. Money,
+ // price and rate fields pass their own INPUT_FORMAT.* kind.
+ const formatOptions = rest.formatOptions ?? SCALE_FORMAT;
const resolvedIsOptional =
isOptional ?? (isRequired ? false : (fieldIsOptional ?? false));
diff --git a/packages/jobs/src/inngest/functions/scheduled/update-exchange-rates.ts b/packages/jobs/src/inngest/functions/scheduled/update-exchange-rates.ts
index 4944d320eb..94ed2cbd07 100644
--- a/packages/jobs/src/inngest/functions/scheduled/update-exchange-rates.ts
+++ b/packages/jobs/src/inngest/functions/scheduled/update-exchange-rates.ts
@@ -2,6 +2,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { Rates } from "@carbon/ee/exchange-rates.server";
import { getExchangeRatesClient } from "@carbon/ee/exchange-rates.server";
import { EXCHANGE_RATES_API_KEY } from "@carbon/env";
+import { round } from "@carbon/utils";
import { inngest } from "../../client";
type CurrencyCode =
@@ -196,11 +197,10 @@ export const updateExchangeRatesFunction = inngest.createFunction(
const updates = data
.map((currency) => ({
...currency,
- exchangeRate: Number(
- rates[currency.code as CurrencyCode]?.toFixed(
- currency.decimalPlaces
- )
- ),
+ // Rates carry internal scale — never the currency's DISPLAY
+ // decimals, which zeroed every 0-decimal currency's fraction and
+ // silently froze rates that rounded to 0
+ exchangeRate: round(Number(rates[currency.code as CurrencyCode])),
updatedAt
}))
.filter((currency) => currency.exchangeRate);
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 16b4f542e0..030a023aed 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -10370,6 +10370,9 @@ msgstr "Verwaltet: {0}"
msgid "Packing Slip"
msgstr "Packzettel"
+msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."
+msgstr ""
+
msgid "Page"
msgstr "Seite"
@@ -13223,6 +13226,9 @@ msgstr "Lieferanten-IDs anzeigen"
msgid "Show sync options"
msgstr "Synchronisierungsoptionen anzeigen"
+msgid "Show Trailing Zeros"
+msgstr ""
+
#. placeholder {0}: data.length
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "Zeige {0} von {totalCount} — verfeinern Sie Ihre Suche"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 3c335b7ed1..84c1c0a3ee 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -10370,6 +10370,9 @@ msgstr "Owns: {0}"
msgid "Packing Slip"
msgstr "Packing Slip"
+msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."
+msgstr "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."
+
msgid "Page"
msgstr "Page"
@@ -13223,6 +13226,9 @@ msgstr "Show Supplier IDs"
msgid "Show sync options"
msgstr "Show sync options"
+msgid "Show Trailing Zeros"
+msgstr "Show Trailing Zeros"
+
#. placeholder {0}: data.length
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "Showing {0} of {totalCount} — refine your search"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 51abe312ee..a81bb02fd2 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -10370,6 +10370,9 @@ msgstr "Propietario: {0}"
msgid "Packing Slip"
msgstr "Albarán de Empaque"
+msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."
+msgstr ""
+
msgid "Page"
msgstr "Página"
@@ -13223,6 +13226,9 @@ msgstr "Mostrar IDs de Proveedores"
msgid "Show sync options"
msgstr "Mostrar opciones de sincronización"
+msgid "Show Trailing Zeros"
+msgstr ""
+
#. placeholder {0}: data.length
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "Mostrando {0} de {totalCount} — refine su búsqueda"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 354e400f9f..c1b6d1313a 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -10370,6 +10370,9 @@ msgstr "Responsable de : {0}"
msgid "Packing Slip"
msgstr "Bon de livraison"
+msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."
+msgstr ""
+
msgid "Page"
msgstr "Page"
@@ -13223,6 +13226,9 @@ msgstr "Afficher les ID fournisseur"
msgid "Show sync options"
msgstr "Afficher les options de synchronisation"
+msgid "Show Trailing Zeros"
+msgstr ""
+
#. placeholder {0}: data.length
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "Affichage de {0} sur {totalCount} — affinez votre recherche"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 19db19473f..5507b0beb8 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -10370,6 +10370,9 @@ msgstr "स्वामित्व: {0}"
msgid "Packing Slip"
msgstr "पैकिंग स्लिप"
+msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."
+msgstr ""
+
msgid "Page"
msgstr "पृष्ठ"
@@ -13223,6 +13226,9 @@ msgstr "आपूर्तिकर्ता आईडी दिखाएं"
msgid "Show sync options"
msgstr "सिंक विकल्प दिखाएं"
+msgid "Show Trailing Zeros"
+msgstr ""
+
#. placeholder {0}: data.length
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "दिखा रहा है {0} का {totalCount} — अपनी खोज को परिष्कृत करें"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index b15fc22151..ee12f47db6 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -10370,6 +10370,9 @@ msgstr "Possiede: {0}"
msgid "Packing Slip"
msgstr "Documento di trasporto"
+msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."
+msgstr ""
+
msgid "Page"
msgstr "Pagina"
@@ -13223,6 +13226,9 @@ msgstr "Mostra ID Fornitore"
msgid "Show sync options"
msgstr "Mostra opzioni di sincronizzazione"
+msgid "Show Trailing Zeros"
+msgstr ""
+
#. placeholder {0}: data.length
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "Mostrando {0} di {totalCount} — raffina la tua ricerca"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 84d5865edd..ebc6cc869e 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -10370,6 +10370,9 @@ msgstr "所有者: {0}"
msgid "Packing Slip"
msgstr "梱包明細書"
+msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."
+msgstr ""
+
msgid "Page"
msgstr "ページ"
@@ -13223,6 +13226,9 @@ msgstr "仕入先IDを表示"
msgid "Show sync options"
msgstr "同期オプションを表示"
+msgid "Show Trailing Zeros"
+msgstr ""
+
#. placeholder {0}: data.length
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "{0} / {totalCount} を表示中 — 検索を絞り込みます"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 9938754797..a78911b059 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -10370,6 +10370,9 @@ msgstr "소유: {0}"
msgid "Packing Slip"
msgstr "포장명세서"
+msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."
+msgstr ""
+
msgid "Page"
msgstr "페이지"
@@ -13223,6 +13226,9 @@ msgstr "공급업체 ID 표시"
msgid "Show sync options"
msgstr "동기화 옵션 표시"
+msgid "Show Trailing Zeros"
+msgstr ""
+
#. placeholder {0}: data.length
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "{0}개/총 {totalCount}개 표시 — 검색 범위 좁혀보기"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 24f4827c7d..11e93d04b8 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -10370,6 +10370,9 @@ msgstr "Odpowiada za: {0}"
msgid "Packing Slip"
msgstr "Dokument wysyłki"
+msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."
+msgstr ""
+
msgid "Page"
msgstr "Strona"
@@ -13223,6 +13226,9 @@ msgstr "Pokaż identyfikatory dostawców"
msgid "Show sync options"
msgstr "Pokaż opcje synchronizacji"
+msgid "Show Trailing Zeros"
+msgstr ""
+
#. placeholder {0}: data.length
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "Wyświetlanie {0} z {totalCount} — uściśl wyszukiwanie"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index ec72ebf1d0..1e27624aa0 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -10370,6 +10370,9 @@ msgstr "Responsável por: {0}"
msgid "Packing Slip"
msgstr "Guia de Remessa"
+msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."
+msgstr ""
+
msgid "Page"
msgstr "Página"
@@ -13223,6 +13226,9 @@ msgstr "Mostrar IDs de Fornecedor"
msgid "Show sync options"
msgstr "Mostrar opções de sincronização"
+msgid "Show Trailing Zeros"
+msgstr ""
+
#. placeholder {0}: data.length
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "Mostrando {0} de {totalCount} — refine sua pesquisa"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index cc13e5372f..d80bde0604 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -10370,6 +10370,9 @@ msgstr "Владеет: {0}"
msgid "Packing Slip"
msgstr "Упаковочный лист"
+msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."
+msgstr ""
+
msgid "Page"
msgstr "Страница"
@@ -13223,6 +13226,9 @@ msgstr "Показать ID поставщиков"
msgid "Show sync options"
msgstr "Показать параметры синхронизации"
+msgid "Show Trailing Zeros"
+msgstr ""
+
#. placeholder {0}: data.length
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "Показано {0} из {totalCount} — уточните поиск"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index b215f7e597..bd4b177971 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -10370,6 +10370,9 @@ msgstr "Sahibi: {0}"
msgid "Packing Slip"
msgstr "Paketleme Fişi"
+msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."
+msgstr ""
+
msgid "Page"
msgstr "Sayfa"
@@ -13223,6 +13226,9 @@ msgstr "Tedarikçi Kimliklerini Göster"
msgid "Show sync options"
msgstr "Senkronizasyon seçeneklerini göster"
+msgid "Show Trailing Zeros"
+msgstr ""
+
#. placeholder {0}: data.length
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "{0} / {totalCount} gösteriliyor — aramanızı daraltın"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 9d33236407..90da12d161 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -10370,6 +10370,9 @@ msgstr "拥有:{0}"
msgid "Packing Slip"
msgstr "装箱单"
+msgid "Pad amounts to their currency's decimal places, so 300 appears as 300.00 and columns of figures stay aligned. Turn this off to show only the digits that carry value. Printed documents and stored amounts are unaffected either way."
+msgstr ""
+
msgid "Page"
msgstr "页面"
@@ -13223,6 +13226,9 @@ msgstr "显示供应商ID"
msgid "Show sync options"
msgstr "显示同步选项"
+msgid "Show Trailing Zeros"
+msgstr ""
+
#. placeholder {0}: data.length
msgid "Showing {0} of {totalCount} — refine your search"
msgstr "显示 {0} 个,共 {totalCount} 个 — 优化搜索"
diff --git a/packages/utils/AGENTS.md b/packages/utils/AGENTS.md
index a8c587fc23..e148be97c1 100644
--- a/packages/utils/AGENTS.md
+++ b/packages/utils/AGENTS.md
@@ -1,6 +1,6 @@
# @carbon/utils
-Pure utility functions shared across all Carbon packages and apps. Covers accounting, arrays, BOM, dates, math, strings, status helpers, storage rules, URL manipulation, and more.
+Pure utility functions shared across all Carbon packages and apps. Covers accounting, arrays, BOM, dates, numeric precision and formatting, math, strings, status helpers, storage rules, URL manipulation, and more.
## Always
@@ -17,7 +17,7 @@ Pure utility functions shared across all Carbon packages and apps. Covers accoun
## Never
-- Import server-only packages (`@carbon/auth`, `@carbon/database`, `@carbon/kv`) from here — `@carbon/utils` must remain client-safe.
+- Import server-only packages (`@carbon/auth`, `@carbon/database`, `@carbon/kv`) from here — `@carbon/utils` must remain client-safe. **One deliberate exception:** `math.ts` re-exports `packages/database/supabase/functions/shared/precision.ts` by relative path. That file is dependency-free pure TS and lives there because the Supabase edge runtime only mounts `supabase/functions/`; it is not a package import and not something to "fix" (same pattern as `packages/database/src/sampling.ts`).
- Add async/IO operations — utilities should be synchronous pure functions (the one exception is `supabase.ts` helpers which are typed wrappers).
- Duplicate what already exists — check the barrel export (`src/index.ts`) before adding a new utility.
@@ -38,7 +38,8 @@ pnpm --filter @carbon/utils typecheck
| `date` | Date formatting, parsing, range helpers (uses `@internationalized/date`) |
| `datetime` | Server-side date derivation with mandatory explicit timezone: `timestamp()`, `today(tz)`, `now(tz)`, `businessDay(instant, tz)`, `weekBounds(tz, offset?, anchor?)` (DST-safe Monday→Sunday instant bounds), `weekNumber(date)`. DST/exotic-zone stress suite in `datetime.test.ts` (gap/overlap disambiguation, midnight-skipping zones, 167/169h weeks, ±30/45-min offsets). Mirrored for Deno at `packages/database/supabase/functions/lib/datetime.ts` — keep in sync |
| `hash` | The repo's stable content hashes — `fnv1a32`/`fnv1a64` (cache and idempotency keys) and `getBucket`. Browser-safe; never add `node:crypto` here |
-| `math` | Rounding, precision, numeric utilities |
+| `math` | `clamp`/`lerp`/`inverseLerp`, plus the whole numeric-precision API re-exported from the edge-runtime module: `SCALE`, `EPSILON`, `round`, `sum`, `equals`, `scrapAllowance`, `applyRate`, `deriveRate`, `assertBalanced`, `RoundingMode` |
+| `format` | The ONLY place display/input digit counts are chosen: `moneyFormatOptions`, `priceFormatOptions`, `percentFormatOptions`, `percentPointsFormatOptions`, `quantityFormatOptions`, `exchangeRateFormatOptions`, their `format*` helpers, and `INPUT_FORMAT` / `INPUT_STEP` for editable fields. Call sites pick a KIND, never a digit count |
| `string` | Slugify, truncate, camelCase/titleCase conversions |
| `revalidate` | `isSearchParamOnlyNavigation` — shared by both apps' shell `shouldRevalidate` |
| `status` | Status resolution, status color mapping |
@@ -49,6 +50,15 @@ pnpm --filter @carbon/utils typecheck
| `labels` | Human-readable label generation |
| `url` | URL construction and manipulation |
+## Numeric precision
+
+Every price, rate, quantity and amount follows the standard in
+`.claude/rules/numeric-precision.md`: internal values at `SCALE = 5`, settlement
+values at the currency's `decimalPlaces` (the DB column, authoritative over
+Intl/CLDR), rounding only at persist / display / compare. Three checks in
+`@carbon/checks` enforce it (`no-raw-rounding`, `no-inline-fraction-digits`,
+`no-derived-percent-column`) and they scan this package.
+
## Cross-References
- `packages/env/` — imports `Edition` and `isBrowser` from this package
diff --git a/packages/utils/src/format.test.ts b/packages/utils/src/format.test.ts
new file mode 100644
index 0000000000..f4a5494133
--- /dev/null
+++ b/packages/utils/src/format.test.ts
@@ -0,0 +1,100 @@
+import { describe, expect, it } from "vitest";
+import {
+ formatMoney,
+ formatPercent,
+ formatQuantity,
+ INPUT_FORMAT,
+ INPUT_STEP
+} from "./format";
+
+describe("formatPercent", () => {
+ it("renders up to 3 digits, only when real", () => {
+ expect(formatPercent(0.0625, "en-US")).toBe("6.25%");
+ expect(formatPercent(0.06255, "en-US")).toBe("6.255%");
+ expect(formatPercent(0.05, "en-US")).toBe("5%");
+ });
+});
+
+describe("formatMoney", () => {
+ it("pads to the currency's decimals, so the width states the amount in full", () => {
+ expect(formatMoney(300, "en-US", "USD", 2)).toBe("$300.00");
+ expect(formatMoney(3.5, "en-US", "USD", 2)).toBe("$3.50");
+ expect(formatMoney(0, "en-US", "USD", 2)).toBe("$0.00");
+ expect(formatMoney(1234.5, "en-US", "USD", 2)).toBe("$1,234.50");
+ });
+
+ it("takes the currency's decimals as the CEILING too", () => {
+ // The DB column is authoritative, so a stored value wider than the currency
+ // rounds to it on screen — storage keeps the rest.
+ expect(formatMoney(300.22121, "en-US", "USD", 2)).toBe("$300.22");
+ expect(formatMoney(18.7638, "en-US", "USD", 2)).toBe("$18.76");
+ });
+
+ it("respects a 0-decimal and a 3-decimal currency", () => {
+ expect(formatMoney(63, "en-US", "JPY", 0)).toBe("¥63");
+ expect(formatMoney(63.4, "en-US", "JPY", 0)).toBe("¥63");
+ // Intl separates code and value with a non-breaking space
+ expect(formatMoney(0.563, "en-US", "BHD", 3)).toBe("BHD\u00a00.563");
+ expect(formatMoney(0.5, "en-US", "BHD", 3)).toBe("BHD\u00a00.500");
+ });
+
+ it("gives editable fields the SAME digits they display with", () => {
+ // react-aria's blur commit is setNumberValue(parse(format(x))), so this
+ // options object decides the precision a typed amount is STORED at.
+ const usd = new Intl.NumberFormat("en-US", INPUT_FORMAT.price("USD", 2));
+ expect(usd.format(300)).toBe("$300.00");
+ expect(usd.format(300.22121)).toBe("$300.22");
+
+ const jpy = new Intl.NumberFormat("en-US", INPUT_FORMAT.money("JPY", 0));
+ expect(jpy.format(63.4)).toBe("¥63");
+ });
+
+ it("formats money and price inputs identically", () => {
+ for (const v of [0, 300, 300.22121, 18.75]) {
+ expect(
+ new Intl.NumberFormat("en-US", INPUT_FORMAT.price("USD", 2)).format(v)
+ ).toBe(
+ new Intl.NumberFormat("en-US", INPUT_FORMAT.money("USD", 2)).format(v)
+ );
+ }
+ });
+});
+
+describe("formatQuantity", () => {
+ it("shows full storage precision without padding", () => {
+ expect(formatQuantity(4.33333, "en-US")).toBe("4.33333");
+ expect(formatQuantity(3, "en-US")).toBe("3");
+ expect(formatQuantity(0.00125, "en-US")).toBe("0.00125");
+ });
+
+ it("uses locale separators", () => {
+ expect(formatQuantity(1234.5, "de-DE")).toBe("1.234,5");
+ });
+});
+
+describe("INPUT_STEP", () => {
+ it("is never coarser than the scale the field holds", () => {
+ // A step coarser than the stored scale SNAPS on commit: step 0.0001 turned
+ // a typed 6.255% into 6.25%, silently, before anything could format it.
+ expect(INPUT_STEP.rate).toBe(1e-5);
+ expect(INPUT_STEP.quantity).toBe(1e-5);
+ expect(INPUT_STEP.exchangeRate).toBe(1e-5);
+ });
+
+ it("lets every value the rate kind can DISPLAY also be committed", () => {
+ // 3 percent-digits == 5 fraction decimals; each must be a whole multiple
+ // of the step, or react-aria snaps it away.
+ for (const percent of [0.0625, 0.06255, 0.12345, 0.05, 0.001]) {
+ expect(Math.round(percent / INPUT_STEP.rate)).toBeCloseTo(
+ percent / INPUT_STEP.rate,
+ 9
+ );
+ }
+ });
+
+ it("steps settlement money in its own smallest unit", () => {
+ expect(INPUT_STEP.money(2)).toBe(0.01);
+ expect(INPUT_STEP.money(0)).toBe(1);
+ expect(INPUT_STEP.money(3)).toBe(0.001);
+ });
+});
diff --git a/packages/utils/src/format.ts b/packages/utils/src/format.ts
new file mode 100644
index 0000000000..4df2ae4c96
--- /dev/null
+++ b/packages/utils/src/format.ts
@@ -0,0 +1,188 @@
+import { SCALE } from "./precision";
+
+export type MoneyFormatOptions = {
+ /** The ISO code. Present -> the symbol renders ("$300.00"); absent -> a bare
+ * amount ("300.00") for surfaces that print the code separately, like the PDF
+ * amount columns. It is an INPUT to the money kind, not a second kind. */
+ currency?: string;
+ /** Drops the non-significant zeros when 0. See below. */
+ minDecimalPlaces?: number;
+};
+
+/** The one stand-in when no currency is in play at all. ISO's own default. */
+export const DEFAULT_CURRENCY_DECIMALS = 2;
+
+/** What CLDR says a currency's settlement decimals are — JPY 0, USD 2, BHD 3.
+ * Per-currency, not per-locale, so the probe locale is arbitrary and the answer
+ * is cached for the process.
+ *
+ * This is the ONLY fallback when a currency has no configured `decimalPlaces`
+ * row. Asking CLDR beats assuming 2, which is what made an unconfigured JPY
+ * field offer two decimal places. A malformed code throws, so 2 stands in — the
+ * same ISO default Intl uses for an unknown-but-well-formed one. */
+const cldrDecimalsByCode = new Map<string, number>();
+export function cldrCurrencyDecimals(currencyCode: string): number {
+ const cached = cldrDecimalsByCode.get(currencyCode);
+ if (cached !== undefined) return cached;
+
+ let decimals = DEFAULT_CURRENCY_DECIMALS;
+ try {
+ decimals =
+ new Intl.NumberFormat("en", {
+ style: "currency",
+ currency: currencyCode
+ }).resolvedOptions().maximumFractionDigits ?? DEFAULT_CURRENCY_DECIMALS;
+ } catch {
+ // Not a valid ISO code — keep the default rather than throwing at render.
+ }
+ cldrDecimalsByCode.set(currencyCode, decimals);
+ return decimals;
+}
+
+/** THE money kind. Money, per-unit prices, and bare document amounts are all
+ * this one thing: from the business's point of view a price is an amount in the
+ * same currency, so they render at the same decimals.
+ *
+ * `decimalPlaces` is `currency.decimalPlaces` — the DB column, authoritative
+ * over Intl/CLDR, and never a literal. It is always the MAXIMUM.
+ *
+ * `minDecimalPlaces` decides whether the non-significant zeros it implies are
+ * kept, and DEFAULTS to keeping them: "$300.00", "$3.50", "$0.00", "¥63".
+ * Fixed-width money is the accounting convention — it keeps columns of amounts
+ * aligned and an explicit ".00" reads as money rather than a bare count. Pass 0
+ * to drop the padding ("$300", "$3.5"); that is a per-company display
+ * preference (`companySettings.showCurrencyTrailingZeros`), which is why it is
+ * a parameter here rather than a second kind.
+ *
+ * Display rounds to this width; STORAGE is a separate question — a value wider
+ * than the currency (a scale-5 unit price) is shown rounded, and the editable
+ * field commits at this width too (see INPUT_FORMAT). */
+export function moneyFormatOptions(
+ decimalPlaces: number,
+ { currency, minDecimalPlaces = decimalPlaces }: MoneyFormatOptions = {}
+): Intl.NumberFormatOptions {
+ return {
+ // The symbol is the only thing `currency` decides. Digits are the same
+ // question either way, answered once here — answering it twice is how the
+ // PDF column and the email of the same document came to disagree, one
+ // following `currency.decimalPlaces` and the other capped at CLDR's 2.
+ ...(currency
+ ? { style: "currency" as const, currency }
+ : { style: "decimal" as const }),
+ minimumFractionDigits: minDecimalPlaces,
+ maximumFractionDigits: decimalPlaces
+ };
+}
+
+/** Already-built currency options with a different MINIMUM — the company's
+ * trailing-zero preference, applied by the editable-field wrapper, which sees
+ * a finished options object rather than the kind that produced it.
+ *
+ * Lives here because this file is the one place digit counts are chosen; a
+ * wrapper writing `minimumFractionDigits` itself is the drift
+ * `no-inline-fraction-digits` exists to catch. Only the minimum moves, so the
+ * value a field commits is unchanged (react-aria commits parse(format(x)) and
+ * padding zeros carry no value). */
+export function withMinimumDecimals(
+ options: Intl.NumberFormatOptions,
+ minDecimalPlaces: number
+): Intl.NumberFormatOptions {
+ return { ...options, minimumFractionDigits: minDecimalPlaces };
+}
+
+/** How many digits a percent carries. A scale-5 fraction is 3 percent-digits,
+ * so a rate round-trips exactly through either of the two kinds below. */
+const PERCENT_DIGITS = 3;
+
+/** The digit-count kinds that take no arguments are frozen CONSTANTS, not
+ * factories. They are read on every render of every field and cell, and
+ * react-stately memoizes its NumberFormatter on the options object's identity —
+ * a fresh object per call defeats that memo and rebuilds the formatter each
+ * render. */
+
+/** Rates (0-1 fractions): rendered as a percentage, "6.25%". */
+export const PERCENT_FORMAT: Intl.NumberFormatOptions = Object.freeze({
+ style: "percent",
+ minimumFractionDigits: 0,
+ maximumFractionDigits: PERCENT_DIGITS
+});
+
+/** The same rate typed as percentage POINTS — a bare 6.25 in a field already
+ * labelled "%", where the caller divides by 100. Same digits as the percent
+ * kind, so the two agree on what a rate can express. */
+export const PERCENT_POINTS_FORMAT: Intl.NumberFormatOptions = Object.freeze({
+ style: "decimal",
+ minimumFractionDigits: 0,
+ maximumFractionDigits: PERCENT_DIGITS
+});
+
+/** Quantities: full storage precision (trailing zeros never render — 3 stays
+ * "3"). FX rates are the same shape — a plain scale-5 multiplier, neither a
+ * 0-1 percent nor a currency — and deliberately share this one constant rather
+ * than duplicating it. Intl's decimal default caps at 3 fraction digits, which
+ * silently truncates a stored value on an input's blur commit, so both have to
+ * be explicit. */
+export const SCALE_FORMAT: Intl.NumberFormatOptions = Object.freeze({
+ minimumFractionDigits: 0,
+ maximumFractionDigits: SCALE
+});
+
+/** Editable inputs MUST use these: react-aria's blur commit runs parse(format(x)),
+ * making the input formatter part of the storage round-trip. */
+export const INPUT_FORMAT = {
+ rate: PERCENT_FORMAT,
+ percentPoints: PERCENT_POINTS_FORMAT,
+ quantity: SCALE_FORMAT,
+ exchangeRate: SCALE_FORMAT,
+ /** Editable currency — money and per-unit prices alike, and the SAME digits
+ * they display with, padding included: an empty cost reads "$0.00".
+ * react-aria's blur commit is literally `setNumberValue(parse(format(x)))`,
+ * so this options object is what decides the precision a typed amount is
+ * STORED at: at USD's 2 places a typed 300.22121 commits as 300.22, and at
+ * JPY's 0 a typed 63.4 commits as 63. */
+ money: (currency: string, decimalPlaces: number, minDecimalPlaces?: number) =>
+ moneyFormatOptions(decimalPlaces, { currency, minDecimalPlaces }),
+ price: (currency: string, decimalPlaces: number, minDecimalPlaces?: number) =>
+ moneyFormatOptions(decimalPlaces, { currency, minDecimalPlaces })
+};
+
+const SCALE_STEP = 1 / 10 ** SCALE;
+
+/** Stepper granularity, paired with the kinds above. react-aria SNAPS the
+ * committed value to the nearest multiple of `step`, so a step coarser than
+ * the field's scale truncates it — take the step from here or omit the prop. */
+export const INPUT_STEP = {
+ rate: SCALE_STEP,
+ quantity: SCALE_STEP,
+ exchangeRate: SCALE_STEP,
+ /** Currency steps in its own smallest unit (1 for JPY, 0.01 for USD) — for
+ * money and prices alike, since they share one format. There is deliberately
+ * no finer `price` step: react-aria commits parse(format(x)), so a step below
+ * the field's own format can only produce values the formatter rounds away. */
+ money: (decimalPlaces: number) => 1 / 10 ** decimalPlaces
+};
+
+export function formatMoney(
+ value: number,
+ locale: string,
+ currency: string,
+ decimalPlaces: number,
+ minDecimalPlaces?: number
+): string {
+ return new Intl.NumberFormat(
+ locale,
+ moneyFormatOptions(decimalPlaces, { currency, minDecimalPlaces })
+ ).format(value);
+}
+
+export function formatPercent(value: number, locale: string): string {
+ return new Intl.NumberFormat(locale, PERCENT_FORMAT).format(value);
+}
+
+export function formatQuantity(value: number, locale: string): string {
+ return new Intl.NumberFormat(locale, SCALE_FORMAT).format(value);
+}
+
+export function formatExchangeRate(value: number, locale: string): string {
+ return new Intl.NumberFormat(locale, SCALE_FORMAT).format(value);
+}
diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts
index 1512732ad9..783a5d79ef 100644
--- a/packages/utils/src/index.ts
+++ b/packages/utils/src/index.ts
@@ -12,6 +12,7 @@ export * from "./datetime";
export * from "./duration";
export * from "./field-registry";
export * from "./file";
+export * from "./format";
export * from "./geo";
export * from "./hash";
export * from "./headers";
@@ -21,6 +22,7 @@ export * from "./labels";
export * from "./llm";
export * from "./math";
export * from "./object";
+export * from "./precision";
export * from "./receiving";
export * from "./revalidate";
export * from "./ssr";
@@ -29,6 +31,7 @@ export * from "./status-colors";
export * from "./storage-rules";
export * from "./string";
export * from "./supabase";
+export * from "./tax";
export * from "./themes";
export * from "./tiptap";
export * from "./types";
diff --git a/packages/utils/src/math.ts b/packages/utils/src/math.ts
index 0d0316ea9a..b15e055d57 100644
--- a/packages/utils/src/math.ts
+++ b/packages/utils/src/math.ts
@@ -1,13 +1,6 @@
export const clamp = (value: number, min: number, max: number) =>
Math.min(Math.max(value, min), max);
-export const twoDecimals = (n: number) => {
- var log10 = n ? Math.floor(Math.log10(n)) : 0,
- div = log10 < 0 ? Math.pow(10, 1 - log10) : 100;
-
- return Math.round(n * div) / div;
-};
-
export const lerp = (min: number, max: number, t: number) => {
return min + (max - min) * clamp(t, 0, 1);
};
@@ -15,7 +8,3 @@ export const lerp = (min: number, max: number, t: number) => {
export const inverseLerp = (min: number, max: number, value: number) => {
return (value - min) / (max - min);
};
-
-export const roundAmount = (value: number) => {
- return Math.round(value * 100) / 100;
-};
diff --git a/packages/utils/src/precision.test.ts b/packages/utils/src/precision.test.ts
new file mode 100644
index 0000000000..ed836a4dff
--- /dev/null
+++ b/packages/utils/src/precision.test.ts
@@ -0,0 +1,117 @@
+import { describe, expect, it } from "vitest";
+import {
+ applyRate,
+ assertBalanced,
+ deriveRate,
+ isBalanced,
+ RoundingMode,
+ round,
+ scrapAllowance
+} from "./precision";
+
+describe("round", () => {
+ it("rounds 1.005 to 1.01 at 2dp (exponent-shift beats the float artifact)", () => {
+ expect(round(1.005, 2)).toBe(1.01);
+ });
+
+ it("rounds ties away from zero like Postgres (round(-2.5, 0) === -3)", () => {
+ expect(round(-2.5, 0)).toBe(-3);
+ expect(round(2.5, 0)).toBe(3);
+ });
+
+ it("defaults to scale 5", () => {
+ expect(round(4.33333333)).toBe(4.33333);
+ });
+
+ it("passes non-finite values through", () => {
+ expect(round(Infinity)).toBe(Infinity);
+ expect(round(-Infinity)).toBe(-Infinity);
+ expect(Number.isNaN(round(NaN))).toBe(true);
+ });
+
+ it("rounds up away from zero in Up mode", () => {
+ expect(round(0.31, 0, RoundingMode.Up)).toBe(1);
+ expect(round(-0.31, 0, RoundingMode.Up)).toBe(-1);
+ expect(round(2.00001, 0, RoundingMode.Up)).toBe(3);
+ });
+});
+
+describe("scrapAllowance", () => {
+ it("is zero at a zero rate, so the target passes through unrounded", () => {
+ expect(scrapAllowance(4.5, 0)).toBe(0);
+ expect(4.5 + scrapAllowance(4.5, 0)).toBe(4.5);
+ });
+
+ it("ceils a partial allowance to whole units", () => {
+ expect(scrapAllowance(31, 0.01)).toBe(1);
+ expect(31 + scrapAllowance(31, 0.01)).toBe(32);
+ });
+
+ it("ceils rather than rounds — 2.00001 units of scrap needs 3", () => {
+ expect(scrapAllowance(200001, 0.00001)).toBe(3);
+ });
+});
+
+describe("deriveRate", () => {
+ it("recovers the rate an amount implies, at internal scale", () => {
+ expect(deriveRate(0.56, 9)).toBe(0.06222);
+ });
+
+ it("is zero when there is no base to divide by", () => {
+ expect(deriveRate(5, 0)).toBe(0);
+ expect(deriveRate(5, -1)).toBe(0);
+ });
+
+ it("round-trips a typed rate through applyRate at internal scale", () => {
+ expect(deriveRate(applyRate(9, 0.0625, 5), 9)).toBe(0.0625);
+ });
+});
+
+describe("applyRate", () => {
+ it("rounds to settlement decimals", () => {
+ expect(applyRate(9, 0.0625, 2)).toBe(0.56);
+ });
+
+ it("handles 0-decimal currencies", () => {
+ expect(applyRate(1000, 0.0625, 0)).toBe(63);
+ });
+
+ it("handles 3-decimal currencies", () => {
+ expect(applyRate(9, 0.0625, 3)).toBe(0.563);
+ });
+});
+
+describe("isBalanced", () => {
+ it("absorbs float noise at the default EPSILON", () => {
+ expect(isBalanced(0.1 + 0.2, 0.3)).toBe(true);
+ });
+
+ it("distinguishes adjacent scale-5 values", () => {
+ expect(isBalanced(1.00002, 1.00003)).toBe(false);
+ });
+
+ it("accepts drift inside an explicit business tolerance and rejects it outside", () => {
+ expect(isBalanced(100, 100.0005, 0.001)).toBe(true);
+ expect(isBalanced(100, 100.002, 0.001)).toBe(false);
+ });
+
+ it("is sign-agnostic — credits over debits reads the same", () => {
+ expect(isBalanced(100.005, 100, 0.01)).toBe(true);
+ expect(isBalanced(100, 100.005, 0.01)).toBe(true);
+ });
+});
+
+describe("assertBalanced", () => {
+ it("throws on drift beyond the default EPSILON", () => {
+ expect(() => assertBalanced(100, 100.001)).toThrow(/does not balance/);
+ });
+
+ it("passes equal debits and credits", () => {
+ expect(() => assertBalanced(100, 100)).not.toThrow();
+ });
+
+ it("honors an explicit business tolerance", () => {
+ expect(() => assertBalanced(100, 100.005, 0.01)).not.toThrow();
+ expect(() => assertBalanced(100, 100.02, 0.01)).toThrow(/does not balance/);
+ });
+});
diff --git a/packages/utils/src/precision.ts b/packages/utils/src/precision.ts
new file mode 100644
index 0000000000..16aa78c05b
--- /dev/null
+++ b/packages/utils/src/precision.ts
@@ -0,0 +1,4 @@
+// Node-side re-export of the edge-runtime precision module (same pattern as
+// packages/database/src/sampling.ts). The source lives under supabase/functions/
+// because the edge runtime only mounts that tree; it is dependency-free pure TS.
+export * from "../../database/supabase/functions/shared/precision.ts";
diff --git a/packages/utils/src/receiving.ts b/packages/utils/src/receiving.ts
index f15672ad8a..6c66643088 100644
--- a/packages/utils/src/receiving.ts
+++ b/packages/utils/src/receiving.ts
@@ -1,3 +1,4 @@
+import { EPSILON, round } from "./precision";
import type { Violation } from "./storage-rules";
export type OverReceiptReceiptLine = {
@@ -36,8 +37,6 @@ export function getOverReceiptViolations(
);
}
- const round = (value: number) => Math.round(value * 100000) / 100000;
-
const violations: Violation[] = [];
const ruleNames: Record<string, string> = {};
for (const poLine of purchaseOrderLines) {
@@ -49,7 +48,7 @@ export function getOverReceiptViolations(
const total = alreadyReceived + incoming;
// Small tolerance so float artifacts from unit conversion don't flag an
// exact receipt as over.
- if (total > ordered + 1e-6) {
+ if (total > ordered + EPSILON) {
const ruleId = `over-receipt:${poLine.id}`;
violations.push({
ruleId,
diff --git a/packages/utils/src/tax.ts b/packages/utils/src/tax.ts
new file mode 100644
index 0000000000..66b63ad8b1
--- /dev/null
+++ b/packages/utils/src/tax.ts
@@ -0,0 +1,63 @@
+import { applyRate, deriveRate } from "./precision";
+
+/** An EMPTIED number input commits NaN, not 0 — that is react-aria's empty
+ * state (`if (!newInputValue.length) setNumberValue(NaN)`). For a cost
+ * component, empty means zero, and it has to be read that way BEFORE the sum:
+ * once one NaN is in, `unitPrice * qty + NaN` is NaN and nothing downstream can
+ * recover the other terms. */
+const finiteOrZero = (value: number) => (Number.isFinite(value) ? value : 0);
+
+/**
+ * The canonical tax denominator — `unitPrice × qty + shippingCost`. One named
+ * function so every document computes the base the same way, and so clearing a
+ * cost field cannot poison it: clearing Shipping on a 300.00 line re-derives the
+ * tax against 300, which is what the user asked for, rather than against NaN.
+ *
+ * Paths with no shipping term pass 0 explicitly rather than omitting it, so the
+ * omission reads as a decision instead of an oversight.
+ */
+export function taxableBase(
+ unitPrice: number,
+ quantity: number,
+ shippingCost: number
+): number {
+ return (
+ finiteOrZero(unitPrice) * finiteOrZero(quantity) +
+ finiteOrZero(shippingCost)
+ );
+}
+
+export type TaxPair = { percent: number; amount: number };
+
+/**
+ * The tax value pair, one direction each. These two functions ARE the coupling —
+ * every consumer goes through them, including the ones that cannot use the
+ * TaxFields component (a pricing table holds one pair per quantity break, so it
+ * cannot call a hook per row, and the server paths have no React at all).
+ *
+ * Precision only flows cleanly one way: an amount derived from a rate is exact
+ * at the currency's decimals, but a rate derived back from a cents-rounded
+ * amount is limited by that amount's scale — entering $0.56 on a $9.00 line
+ * yields 6.222%, not 6.25%. Type the rate when the rate is what you mean.
+ */
+export function taxPairFromPercent(
+ subtotal: number,
+ percent: number,
+ currencyDecimals: number
+): TaxPair {
+ return { percent, amount: applyRate(subtotal, percent, currencyDecimals) };
+}
+
+/** No base to divide by -> keep the rate the caller already holds, rather than
+ * zeroing it. `deriveRate` rounds to internal scale, so the stored rate is what
+ * the input renders back. */
+export function taxPairFromAmount(
+ subtotal: number,
+ amount: number,
+ currentPercent: number
+): TaxPair {
+ return {
+ percent: subtotal > 0 ? deriveRate(amount, subtotal) : currentPercent,
+ amount
+ };
+}