Skip to content

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

fix: invoice tax, wip ledger, edit production events, dimension labels (#1012)

Brad Barbinc476c942de9f
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 6a3f2f5dc9..6b5b9e543f 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -45,3 +45,23 @@ Format: `Context → Problem → Rule → Applies to`
**Rule:** Never merge a migration whose timestamp is older than the newest migration already on `main`/deployed. Before writing a view/RPC recreation, fork from the NEWEST definition of that view (grep all migrations, take the last). When rescuing a failed backdated migration, strip the superseded parts and re-land the still-wanted change in a fresh forward-dated migration; don't rename already-partially-applied files (re-applies them).
**Applies to:** `packages/database/supabase/migrations/`, `ci/src/migrations.ts`, any long-lived branch adding migrations.
+
+## Never resolve a control account by number/name
+
+**Context:** Posting intercompany invoices/payments needed the "Inter-Company Receivables" control account. The edge functions (`post-sales-invoice`, `post-payment`) fetched it with `.eq("number", "1130")`.
+
+**Problem:** Account `number` and `name` are user-editable at any time. Resolving a control account by a hardcoded number silently mis-posts the moment someone renumbers/renames the account — no error, wrong GL account. It also duplicates a magic constant across posting paths that can drift.
+
+**Rule:** Resolve internal/control accounts by **id** via a column on `accountDefault` scoped to the `companyId` (the same pattern as `receivablesAccount`/`payablesAccount`). If no default column exists, add one to `accountDefault` (+ seed it in `seed.data.ts` and `seed-company`, + one-time backfill migration resolving the seeded number → id), then read `ad.<xxx>Account`. The only legitimate uses of `.where("number"/"eq("number")` on `account` are: building the chart at seed time, and mapping **external** codes in an integration (e.g. Xero AccountCodes) — never resolving an internal control account at posting time.
+
+**Applies to:** `packages/database/supabase/functions/post-*`, `close-job`, `issue`, anything posting to `journalLine`; `accountDefault` schema + `lib/seed.data.ts`.
+
+## Chart-of-accounts group headers have no number — resolve parents by name/key
+
+**Context:** `20260524143827_fixed-assets.sql` seeded a "Deferred Tax Expense" (7090) account for every existing company group, resolving its parent with `number = '7000' AND "isGroup" = true`.
+
+**Problem:** Group header accounts in Carbon's chart carry `number = NULL` (they are identified by seed key/name, e.g. `other-expenses` / "Other Expenses") — only leaf posting accounts have numbers. The lookup silently returned NULL and the account was inserted with `parentId = NULL`, leaving it orphaned at the root of the chart for every pre-existing company. New companies were unaffected because `seed.data.ts` parents via `parentKey`. The bug is invisible in dev (fresh seeds go through `seed.data.ts`) and only shows on long-lived databases.
+
+**Rule:** In migrations that insert `account` rows, resolve the parent group by `"isGroup" = TRUE AND name = '<Group Name>'` (optionally + class), never by number — and treat a NULL parent as an error or explicit fallback, never insert silently orphaned. `20260630093809_ar-ap-payments.sql` is the correct precedent. When a past migration did orphan accounts, ship a follow-up UPDATE re-parenting `parentId IS NULL` rows to the group `seed.data.ts` assigns (see `20260702192816`).
+
+**Applies to:** `packages/database/supabase/migrations/` touching `account`; `packages/database/supabase/functions/lib/seed.data.ts`; anything walking the chart-of-accounts tree.
diff --git a/.ai/runs/2026-07-02-accounting-bugs.md b/.ai/runs/2026-07-02-accounting-bugs.md
new file mode 100644
index 0000000000..1464376a13
--- /dev/null
+++ b/.ai/runs/2026-07-02-accounting-bugs.md
@@ -0,0 +1,124 @@
+# Accounting Bugs Remediation — 2026-07-02
+
+Three user-reported accounting bugs, root-caused and fixed.
+
+## Bug 1 — Manual MES issue of backflush materials corrupts WIP
+
+**Symptom:** Issuing parts manually from MES (because the operation that would
+backflush them was skipped) corrupted the WIP journal/ledger entries.
+
+**Root cause:** `issueJobOperationMaterials()` in
+`packages/database/supabase/functions/issue/index.ts` backflushed
+`material.quantity × completedQuantity` unconditionally, ignoring
+`jobMaterial.quantityIssued`. The SQL `backflush_job_materials` caps at
+`GREATEST(target − quantityIssued, 0)`, but the edge-function path (used by
+MES operation complete/end, batch and serial complete) did not. Since a job
+can't complete until every operation is Done, the skipped operation is
+eventually ended, re-issuing the already-manually-issued materials: duplicate
+itemLedger/costLedger consumption and duplicate DR WIP / CR Inventory lines,
+which then inflate the WIP discharge into finished goods.
+
+**Fixes:**
+- [x] `issue/index.ts`: cap backflush at `estimatedQuantity − quantityIssued`,
+ skip materials with nothing remaining.
+- [x] `issue/index.ts` (`partToOperation`): "Positive Adjmt." (return to
+ inventory) now decrements `quantityIssued` instead of incrementing, keeping
+ the backflush cap in sync.
+- [x] `close-job/index.ts`: WIP variance entry is now sign-aware (was
+ `Math.abs`, which doubled a negative/over-credited WIP residual instead of
+ zeroing it).
+
+## Bug 2 — Invoice-line tax not reflected in payable/payment amount
+
+**Symptom:** Tax added on a purchase invoice line that wasn't on the PO
+produced a correct PPV entry, but the payment was still for the pre-tax
+amount.
+
+**Root cause:** `post-purchase-invoice` credits AP tax-inclusive (correct),
+but the `purchaseInvoices` view computed `balance` / derived `Paid` status /
+`datePaid` from the stored header `purchaseInvoice.totalAmount` — written
+pre-tax at PO→invoice conversion and never updated (deprecated by
+`20260604120000`). `post-payment` rejects applications above the view
+`balance`, pinning the payment to the pre-tax amount and stranding the tax as
+an un-relievable AP credit. Regression chain: fixed by `20260630102736`, then
+silently reverted by `20260630151500` (forked its view bodies from the
+pre-fix `20260630095023`), perpetuated by `20260702061504`. The same fork
+also reverted the memo-aware `settled` CTE (`20260630105334`) and dropped
+`salesInvoices.paymentTermName` (`20260629120000`).
+
+**Fixes:**
+- [x] Migration `20260702114500_invoice-balance-includes-line-tax.sql`:
+ recreates both invoice views with balance/status/datePaid derived from the
+ live line-derived total (incl. tax + shipping), restores the memo-aware
+ settled CTE and `salesInvoices.paymentTermName`, keeps dust forgiveness and
+ the supplierShippingCost divide-with-zero-guard.
+- [ ] After applying migrations: `pnpm run generate:types` (salesInvoices
+ gains `paymentTermName`). Not run here — no local DB in this environment.
+
+Expected visible side effect: invoices previously derived-'Paid' at the
+pre-tax amount reopen with a balance equal to the unpaid tax (correct
+outstanding AP).
+
+## Bug 3 — Manual production events in ERP post no journal entries
+
+**Symptom:** Adding/editing production events from ERP created no journal
+entries.
+
+**Root cause (chain):** the ERP routes do invoke `post-production-event`, but:
+1. The edge function marked events with no work center (or no
+ endTime/duration) as `postedToGL = true` and returned success — silently
+ skipping them AND permanently excluding them from the
+ `complete_job_to_inventory` fallback. Manual ERP entry is the only path
+ where `workCenterId` can be null (MES stamps it at start).
+2. The form's WorkCenter picker passed `jobOperationId` as a `processId`
+ filter, so in edit mode the dropdown was always empty — the field was
+ effectively impossible to set correctly.
+3. Both routes discarded the invoke response, so failures were invisible.
+4. Edits of already-posted events had no adjustment semantics (re-invoking
+ would double-post; journal lines weren't attributable to the event).
+
+**Fixes:**
+- [x] `post-production-event/index.ts`: unpostable events (no
+ endTime/duration/workCenter) no longer get `postedToGL = true`; they return
+ `{ success: false, reason }` so they can post later (manually or via the
+ completion fallback).
+- [x] `post-production-event/index.ts`: journal lines are now tagged
+ `production-event:{id}` (`journalReference.to.productionEvent`); reposting
+ an already-posted (edited) event first reverses the net previously posted
+ per account, then posts the new amount, in one balanced journal. Events
+ posted before per-event tagging return `success: false` instead of
+ double-posting.
+- [x] ERP create/edit routes flash "saved, but no journal entry was posted:
+ {reason}" when the invoke fails or is skipped.
+- [x] `ProductionEventForm`: WorkCenter is filtered by the selected
+ operation's `processId` (reactive to the Operation select).
+
+## Follow-ups (not done, out of scope)
+
+- `convert/index.ts` still writes the deprecated stored
+ `purchaseInvoice.totalAmount` pre-tax; only external (Xero) sync readers
+ see it.
+- ~~Deleting a posted production event does not reverse its journal entry~~
+ Done in a follow-up commit: `post-production-event` gained a
+ `reverse: true` mode (posts a reversal journal from the per-event tagged
+ lines, sets `postedToGL = false`); `deleteProductionEvent` reverses before
+ deleting and blocks the delete when reversal isn't possible (events posted
+ before per-event tagging). Covers both the ERP route and the MCP tool
+ (service signature gained `companyId`/`userId`; MCP metadata regenerated).
+- If manual-event posting still fails after these fixes, check edge-function
+ logs for auth: `requirePermissions` in `functions/lib/supabase.ts` rejects
+ opaque (`sb_secret_*`) service keys that `isTrustedBearer` accepts —
+ auth-sensitive, so not changed here.
+- Historical data repair (already-corrupted WIP/journal entries from bugs 1
+ and 3, invoices mis-flagged Paid from bug 2) is a data fix, not covered by
+ these code changes.
+
+## Verification
+
+- `pnpm --filter erp typecheck` — clean.
+- Biome on changed app files — clean.
+- Edge functions and migration SQL not executed here (no local DB / Deno);
+ verify by applying the migration and exercising: manual MES issue → end
+ skipped op → single consumption; invoice with added line tax → payment for
+ full amount; manual ERP production event create/edit → journal entries and
+ adjustment reversal.
diff --git a/.ai/runs/2026-07-02-invoice-payment-audit.md b/.ai/runs/2026-07-02-invoice-payment-audit.md
new file mode 100644
index 0000000000..23a3d13149
--- /dev/null
+++ b/.ai/runs/2026-07-02-invoice-payment-audit.md
@@ -0,0 +1,82 @@
+# Invoice & Payment Posting Audit — 2026-07-02
+
+Follow-up to the tax fix (migration `20260702114500`): audit of whether the
+amounts posted to AR/AP match the invoice views' totals (which cap payment
+application) for every component — tax, line shipping, header shipping,
+add-ons, discounts — plus an end-to-end audit of the payment/memo chain.
+
+Invariant checked: **posted AR/AP amount == view totalAmount/balance basis**.
+Any component on one side but not the other strands a control-account balance
+or blocks/over-relieves payments — the same family as the purchase-tax bug.
+
+## Sales invoices (`post-sales-invoice` vs `salesInvoices` view)
+
+| # | Severity | Finding |
+|---|---|---|
+| S1 | **Bug (high)** | `nonTaxableAddOnCost` is in the view subtotal but never posted to AR (`post-sales-invoice/index.ts:108-117, 302-306` omit it). Pay the full view balance → AR goes permanently negative by the add-on; revenue understated. |
+| S2 | **Bug (high)** | Header shipping is allocated across lines with tax-inclusive weights over a pre-tax denominator (`index.ts:302-314` vs `108-117`), so AR is debited `headerShipping × (1 + effective tax)` while the view adds header shipping untaxed. The tax portion of shipping is stranded in AR forever. |
+| S3 | Bug (edge) | If every line has a zero pre-tax basis, header shipping is allocated 0 and never posted, while the view still includes it. |
+| S4 | Design flag | Line tax is credited to the **sales account**, not a tax-payable account. Doesn't break the AR↔view invariant, but revenue is overstated by collected tax and no tax liability exists on the balance sheet. Product decision needed. |
+| S5 | Bug (edge) | Fixed Asset lines with null `assetId` silently post nothing (`index.ts:538` guard) and Comment lines can carry amounts; the view sums all lines regardless → view > AR. |
+| S6 | Inconsistency | `intercompanyTransaction.amount` uses pre-tax `totalLinesCost` (`index.ts:1168`), not the actually-posted AR amount. IC matching never ties to the 1130 balance. |
+| S7 | **Bug (high)** | Intercompany invoices are booked to AR account 1130 (`index.ts:277-291`) but `post-payment` always relieves the default receivables account (`post-payment/index.ts:392-395`). Paying an IC invoice strands 1130 and drives regular AR negative. |
+| S8 | Display | `SalesInvoiceSummary.tsx:416-425` multiplies header shipping by `exchangeRate` in both the document-currency and converted totals (identical duplicated expression). |
+
+Component matrix (sales): line price/tax/line shipping/addOnCost — consistent;
+`nonTaxableAddOnCost` — view only (S1); header shipping — over-posted ×(1+tax)
+(S2), dropped at zero basis (S3); discounts — consistently baked into
+unitPrice (ok); FX round-trip — consistent given S1/S2 fixed.
+
+## Purchase invoices (`post-purchase-invoice` vs `purchaseInvoices` view)
+
+| # | Severity | Finding |
+|---|---|---|
+| P1 | **Bug (high)** | Header `supplierShippingCost` is FX-converted in **opposite directions**: posting multiplies by exchangeRate (`post-purchase-invoice/index.ts:445-447`), the view divides (per the platform convention: rate = foreign-per-base). On every foreign-currency invoice with header freight, AP is left with a residual of `shipping × (R − 1)`; invisible at rate 1. |
+| P2 | **Systemic (FX)** | Posting multiplies already-base generated line columns by exchangeRate on a false premise (comment at `index.ts:666-670`; `purchaseInvoiceLine.unitPrice` etc. are generated as `supplierX / exchangeRate` = base). Consequences: phantom PPV of `lineBase × (R−1)` on every PO-matched FX invoice (receipt side posts base, invoice side posts ×R), and costLedger/fixed-asset amounts at ×R magnitude. Same inverted convention runs through the whole payment stack (see Pay1) — needs a coordinated, spec'd fix, not a patch. |
+| P3 | Bug (edge) | Shipping-only invoices (all lines zero-value): header shipping is allocated 0 and never credited to AP (`index.ts:681-682`), while the view includes it. Freight bills are a real-world case. |
+| P4 | **Bug** | PO→invoice conversion copies the **full** header `supplierShippingCost` and full flat line `supplierShippingCost`/`supplierTaxAmount` onto **every** partial invoice (`convert/index.ts:345-350, 370-376`). Two partial invoices → shipping and flat tax charged twice (AP and view agree, so it's overstated payable, not stranding). |
+| P5 | Bug (edge) | Same as S5 on the purchase side (`index.ts:1098`, `1313-1314`): asset-less Fixed Asset lines and valued Comment lines are in the view but never posted; Comment lines also absorb a share of header shipping that is then never journaled. |
+| P6 | Nit | `index.ts:1665` sets `datePaid: today` at posting ("TODO: remove once payments working") — with the new views, unpaid invoices can display a datePaid. |
+
+## Payments & memos (`post-payment`, `build-payment-journal`, `post-memo`)
+
+| # | Severity | Finding |
+|---|---|---|
+| Pay1 | **Systemic (FX)** | The entire payment/posting chain assumes base = doc × rate, but the platform convention (generated columns, migration `20260702061504`, `.ai/rules/purchasing-conversion-factors.md`) is base = doc ÷ rate. The chain is self-consistent (tie-outs pass; rate=1 hides it), but for FX documents: GL base magnitudes are wrong by the rate factor, payment seeding labels base sums with the foreign currency code (wrong remittance amount), and realized FX gain/loss signs are inverted. Fix together with P2 under a spec. |
+| Pay2 | **Bug** | Voiding a payment that applied a memo strands the memo credit forever: the memo-remaining calculators (`invoicing.service.ts:1910-1926, 2098-2110, 1970-1986`) count all memo-sourced settlement rows without checking the via-payment's status, while the views correctly stop counting them. |
+| Pay3 | **Bug** | `post-payment` commits staged memo credits without locking/validating the memos (no `status = 'Posted'` check at commit; `index.ts:234-261, 551-570`). A memo voided between staging and posting goes live silently; the invoice stays open while the user believes it settled. |
+| Pay4 | Bug (latent) | The in-transaction on-account credit pool (`post-payment/index.ts:576-616`) ignores `paymentType`, unlike the UI mirror. A posted refund disbursement counts as **positive** credit → later payments can over-apply. Latent until refund flows are used. |
+| Pay5 | Inconsistency | Voiding a payment whose unapplied cash was already drawn by a later payment isn't blocked; the party credit pool can go negative. |
+| Pay6 | Low | Stored `invoiceSettlement.fxGainLossAmount` isn't sign-normalized for AP; panel displays AP losses as positive. No GL effect. |
+| Pay7 | Latent | Cash refunds against a memo (`targetMemoId`) would double-dip memo credit — currently unreachable (service rejects such rows). |
+| Pay8 | Inconsistency | Multi-invoice payment seeding assumes one currency (`new.tsx:79-87`): mixed-currency selections produce spurious FX plugs and misformatted balances. |
+| Pay9 | Low | `salesInvoices` view INNER JOINs `salesInvoiceShipment` (purchase side is LEFT JOIN). An invoice missing its shipment row disappears from the view and becomes unpayable (balance defaults to 0). LEFT JOIN is strictly safer. |
+| Pay8+ | Verified good | Over-settlement guard (reads views, row locks, cumulative cash+memo cap), partial/multiple payments, dust forgiveness (matches `INVOICE_DUST_THRESHOLD`), settlement deletion cascades, void journal reversal, memo journal shape, exchange-rate edit locking. |
+
+## Remediation status
+
+Tier 1 was implemented on this branch immediately after the audit (see the
+follow-up commit). Tier 2 is captured in
+`.ai/specs/2026-07-02-exchange-rate-convention-normalization.md` (FX) and
+remains open for S4/S6/S8/Pay5/Pay6/Pay8/P6.
+
+**Tier 1 — same family as the fixed bugs, safe and minimal (IMPLEMENTED):**
+- S1 + S2 + S3: fix `post-sales-invoice` totals (add nonTaxableAddOnCost
+ outside the tax multiplier; weight header shipping by the pre-tax basis;
+ zero-basis fallback). One patch, makes AR == view total exactly.
+- P1 + P3: header shipping conversion (divide, zero-guarded) and zero-basis
+ fallback in `post-purchase-invoice`.
+- P4: prorate shipping/flat tax at PO→invoice conversion.
+- S7: `post-payment` resolves the control account per invoice (IC → 1130).
+- Pay2 + Pay3: gate memo-remaining calculators on via-payment status; lock and
+ validate memos as Posted at payment commit.
+- Pay9: LEFT JOIN salesInvoiceShipment (fold into the branch's migration).
+- Pay4 (minimal form): filter the credit pool by matching `paymentType`.
+
+**Tier 2 — needs product/architecture decision (spec first):**
+- P2 + Pay1: unify the exchange-rate convention (divide-to-base) across
+ post-sales-invoice, post-purchase-invoice, post-receipt header shipping,
+ post-payment/build-payment-journal, memo journal, tie-out RPCs, seeded
+ payment amounts, and the golden-master tests.
+- S4: split tax to a tax-payable account (needs an account default).
+- S6, S8, Pay5, Pay6, Pay8, P6: smaller consistency fixes.
diff --git a/.ai/specs/2026-07-02-exchange-rate-convention-normalization.md b/.ai/specs/2026-07-02-exchange-rate-convention-normalization.md
new file mode 100644
index 0000000000..e2aadec32b
--- /dev/null
+++ b/.ai/specs/2026-07-02-exchange-rate-convention-normalization.md
@@ -0,0 +1,147 @@
+# Exchange-Rate Convention Normalization (GL & Payments)
+
+> Status: draft
+> Author: Claude (audit follow-up), for [email protected]
+> Date: 2026-07-02
+
+## TLDR
+
+The platform's documented currency convention is `currency.exchangeRate` =
+**foreign units per base unit**, so document→base conversion is **divide**
+(this is how the `purchaseInvoiceLine` generated columns, the invoice views,
+and `.ai/rules/purchasing-conversion-factors.md` all work). The GL posting and
+payment chain (`post-sales-invoice`, `post-purchase-invoice`, `post-payment` /
+`build-payment-journal`, tie-out RPCs, seeded payment amounts) instead assumes
+base = document × rate. The chain is internally self-consistent — control
+accounts net to zero and tie-outs pass — but for every non-base-currency
+document the GL base amounts are wrong by the rate factor squared relative to
+true base, seeded payment `totalAmount`s label base sums with the foreign
+currency code (wrong remittance instruction), PO-matched FX invoices book a
+phantom PPV, and realized FX gain/loss signs are inverted. This spec proposes
+normalizing the whole chain to the documented divide-to-base convention in one
+coordinated change.
+
+## Problem Statement
+
+Facts established by the 2026-07-02 audit (`.ai/runs/2026-07-02-invoice-payment-audit.md`):
+
+1. `purchaseInvoiceLine.unitPrice/shippingCost/taxAmount` are GENERATED as
+ `supplierX / exchangeRate` (migration `20250807094441`) — i.e. **base**
+ currency. The `purchaseInvoices`/`salesInvoices` views therefore expose
+ base-denominated `totalAmount`/`balance`.
+2. `post-purchase-invoice/index.ts` multiplies those already-base line
+ amounts by `exchangeRate` before journaling (comment claims they are in
+ invoice currency — false). `post-sales-invoice` does the same on the sales
+ side (where `salesInvoiceLine.unitPrice` is also base).
+3. `post-receipt` books GR/IR at base (no multiplier), so the invoice-side
+ multiplier produces a **phantom PPV** of `lineBase × (R − 1)` on every
+ PO-matched foreign-currency invoice even at identical prices.
+4. `post-payment`/`build-payment-journal` mirror the multiply convention
+ (`applied × targetExchangeRate` control relief, `totalAmount ×
+ exchangeRate` cash), which is why the loop closes and nothing crashes.
+5. Payment seeding (`payments new.tsx`) sums view balances (base) into
+ `payment.totalAmount` but labels it with the invoice's foreign
+ `currencyCode` → the remittance instruction is wrong by the rate factor.
+6. FX gain/loss sign: with foreign-per-base rates, a falling rate means the
+ foreign currency strengthened (an AP loss), but the builder books a gain.
+7. Tie-out RPCs (`20260630104012`) treat the base-denominated view totals as
+ document-currency and multiply by rate.
+8. `$paymentId.tsx` converts base→"payment currency" by divide — the same
+ inverted convention.
+9. costLedger / fixedAsset acquisition costs from FX purchase invoices are
+ stored at the ×R magnitude, inconsistent with receipt-side costing.
+
+Interim state (already merged on this branch): header `supplierShippingCost`
+is divided to base at posting and folded in before the chain's ×R multiplier,
+so AP credit == view balance × R for every component and payments settle
+exactly. That keeps the loop closed but leaves the loop itself on the wrong
+convention.
+
+## Proposed Solution
+
+Adopt **divide-to-base everywhere; journal lines are true base amounts; rates
+appear only in FX gain/loss computation and display conversions.**
+
+Concretely (one coordinated change):
+
+1. `post-sales-invoice` / `post-purchase-invoice`: remove the
+ `× invoiceExchangeRate` multiplier — line amounts (and the header shipping,
+ already divided) are base already. Delete the false-premise comments.
+2. `post-receipt`: convert header shipping with divide (it currently
+ multiplies at `index.ts:562-564`); line amounts are already base.
+3. `build-payment-journal`: define `appliedAmount`/`discountAmount`/
+ `writeOffAmount` as base currency (they already are in practice — users
+ enter them against base-denominated view balances). Control/discount/
+ write-off lines post the raw amounts (no `× targetExchangeRate`). Cash line
+ = `totalAmount` where `payment.totalAmount` becomes a base amount, with the
+ document-currency amount derived for display (`× exchangeRate`), or vice
+ versa — decide in Open Questions. FX gain/loss = document-currency
+ principal × (1/payRate − 1/invRate), with the sign convention re-derived
+ and the `(isAR ? 1 : -1)` normalization + the stored
+ `invoiceSettlement.fxGainLossAmount` generated column updated together.
+4. Payment seeding (`new.tsx`): seed the document-currency amount
+ (`balance × exchangeRate`) when labeling with the foreign currency code, or
+ seed base and label with the base currency code (Open Question).
+5. Tie-out RPCs (`get_ar_tie_out` / `get_ap_tie_out` / aging): drop the ×rate
+ on view totals.
+6. `$paymentId.tsx` availableCredit conversion: flip to match.
+7. Update golden-master tests in `post-payment.test.ts` (they currently pin
+ the multiply convention) and the costLedger/fixedAsset magnitudes noted in
+ the audit.
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|----------|--------|-----------|
+| Rate semantics | foreign-per-base, divide to base | Matches generated columns, views, update-exchange-rates job, and `.ai/rules` docs |
+| Journal denominates | true base currency | GL must be base; display converts |
+| Settlement amounts | base currency | Users enter them against base view balances today; no data migration needed |
+| Migration of history | none (forward-only) | Historic journals were self-consistent; restating them is a separate decision |
+
+## Data Model Changes
+
+- `invoiceSettlement.fxGainLossAmount` generated column: re-derive formula
+ and sign normalization (migration).
+- No table shape changes expected.
+
+## API / Service Changes
+
+Edge functions: `post-sales-invoice`, `post-purchase-invoice`, `post-receipt`
+(header shipping), `post-payment`, `build-payment-journal`, `post-memo`
+(verify), tie-out RPC migrations. App: payment seeding route, PaymentApplyTable
+formatting, `$paymentId.tsx` credit conversion.
+
+## Acceptance Criteria
+
+- [ ] For a foreign-currency invoice, journal base amounts equal
+ document amount ÷ rate for every component.
+- [ ] PO-matched FX invoice at identical prices books zero PPV.
+- [ ] Payment seeded from an FX invoice shows the correct document-currency
+ remittance amount.
+- [ ] Realized FX gain/loss sign matches economic direction on both AR and AP.
+- [ ] Tie-out RPCs reconcile subledger to control accounts for FX documents.
+- [ ] post-payment golden-master tests updated and passing.
+- [ ] Rate = 1 behavior byte-identical to today (regression guard).
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| Historic FX journals inconsistent with new ones | Med | Forward-only cutover; document the cutover date; optional restatement tooling later |
+| Partial deployment (one function updated, another not) breaks the closed loop | High | Ship as one PR; the invariant "AP/AR credit == what payment debits" must hold at every commit |
+| Hidden consumers assuming ×R magnitudes (reports, Xero sync) | Med | Grep for exchangeRate usages across packages/ee and jobs before implementation |
+
+## Open Questions
+
+> HARD STOP: Do not proceed with implementation until these are answered.
+
+- [ ] Should `payment.totalAmount` store base or document currency? (Base
+ avoids migration of the seeding flow; document matches the remittance
+ mental model.)
+- [ ] Restate or leave historic FX journals? (Proposal: leave.)
+- [ ] Does Xero sync (BillSyncer/SalesInvoiceSyncer) push amounts derived
+ from the affected fields, and in which currency does Xero expect them?
+
+## Changelog
+
+- 2026-07-02: Created from the invoice/payment audit findings (P2 + Pay1).
diff --git a/apps/erp/app/components/Form/itemTypeLabel.ts b/apps/erp/app/components/Form/itemTypeLabel.ts
index 49b78cfb08..b88189e6ea 100644
--- a/apps/erp/app/components/Form/itemTypeLabel.ts
+++ b/apps/erp/app/components/Form/itemTypeLabel.ts
@@ -4,7 +4,13 @@ import { msg } from "@lingui/core/macro";
type ItemType = Database["public"]["Enums"]["itemType"];
-const LABELS: Record<ItemType, MessageDescriptor> = {
+// "Item" is the generic sentinel used across forms before a concrete item type
+// is chosen (see `MethodItemType | "Item"` in Item.tsx and the line forms). It
+// must resolve to a label so the field header isn't blank in that state.
+type ItemTypeOrGeneric = ItemType | "Item";
+
+const LABELS: Record<ItemTypeOrGeneric, MessageDescriptor> = {
+ Item: msg`Item`,
Part: msg`Part`,
Material: msg`Material`,
Tool: msg`Tool`,
@@ -13,7 +19,8 @@ const LABELS: Record<ItemType, MessageDescriptor> = {
Fixture: msg`Fixture`
};
-const ID_LABELS: Record<ItemType, MessageDescriptor> = {
+const ID_LABELS: Record<ItemTypeOrGeneric, MessageDescriptor> = {
+ Item: msg`Item ID`,
Part: msg`Part ID`,
Material: msg`Material ID`,
Tool: msg`Tool ID`,
@@ -22,10 +29,10 @@ const ID_LABELS: Record<ItemType, MessageDescriptor> = {
Fixture: msg`Fixture ID`
};
-export function itemTypeLabel(type: ItemType): MessageDescriptor {
+export function itemTypeLabel(type: ItemTypeOrGeneric): MessageDescriptor {
return LABELS[type];
}
-export function itemTypeIdLabel(type: ItemType): MessageDescriptor {
+export function itemTypeIdLabel(type: ItemTypeOrGeneric): MessageDescriptor {
return ID_LABELS[type];
}
diff --git a/apps/erp/app/modules/accounting/ui/JournalEntries/DimensionSelector.tsx b/apps/erp/app/modules/accounting/ui/JournalEntries/DimensionSelector.tsx
index af17ce3dcd..26cb59698a 100644
--- a/apps/erp/app/modules/accounting/ui/JournalEntries/DimensionSelector.tsx
+++ b/apps/erp/app/modules/accounting/ui/JournalEntries/DimensionSelector.tsx
@@ -19,6 +19,8 @@ import {
import { useCallback, useMemo, useState } from "react";
import { LuPlus } from "react-icons/lu";
import { useFetcher } from "react-router";
+import { useProcesses } from "~/components/Form/Process";
+import { useWorkCenters } from "~/components/Form/WorkCenter";
import { DimensionEntityTypeIcon } from "~/components/Icons";
import { useCustomers, useItems, useSuppliers } from "~/stores";
import { path } from "~/utils/path";
@@ -84,6 +86,22 @@ const DimensionSelector = ({
const [suppliers] = useSuppliers();
const [items] = useItems();
+ // WorkCenter and Process dimension values are stored as raw ids, so resolve
+ // their human labels from the same client-side lists their pickers use.
+ const processes = useProcesses();
+ const { options: workCenters } = useWorkCenters({});
+ const labelByEntityValue = useMemo(() => {
+ const map = new Map<string, string>();
+ for (const wc of workCenters) map.set(`WorkCenter:${wc.value}`, wc.label);
+ for (const p of processes) map.set(`Process:${p.value}`, p.label);
+ return map;
+ }, [workCenters, processes]);
+ const resolveValueLabel = useCallback(
+ (entityType: string, valueId: string, fallback: string) =>
+ labelByEntityValue.get(`${entityType}:${valueId}`) ?? fallback,
+ [labelByEntityValue]
+ );
+
// High-cardinality dimensions the user has chosen to add from the dropdown
// but not yet given a value — these render their searchable Combobox inline.
const [activeHighCardIds, setActiveHighCardIds] = useState<Set<string>>(
@@ -284,7 +302,7 @@ const DimensionSelector = ({
>
{dim.values.map((val) => (
<DropdownMenuRadioItem key={val.id} value={val.id}>
- {val.name}
+ {resolveValueLabel(dim.entityType, val.id, val.name)}
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
@@ -311,29 +329,33 @@ const DimensionSelector = ({
onChange={(valueId) => handleComboboxChange(dim, valueId)}
/>
))}
- {currentDimensions.map((dim) => (
- <Badge
- key={dim.dimensionId}
- role="group"
- tabIndex={0}
- variant="outline"
- className={cn(
- getColor(dimensionEntityTypeMap.get(dim.dimensionId) ?? ""),
- "inline-flex items-center gap-1"
- )}
- >
- <DimensionEntityTypeIcon
- entityType={dimensionEntityTypeMap.get(dim.dimensionId) as any}
- className="size-3"
- />
- <span>{dim.valueName}</span>
- <BadgeCloseButton
+ {currentDimensions.map((dim) => {
+ const entityType = dimensionEntityTypeMap.get(dim.dimensionId) ?? "";
+ const label = resolveValueLabel(entityType, dim.valueId, dim.valueName);
+ return (
+ <Badge
+ key={dim.dimensionId}
+ role="group"
tabIndex={0}
- onClick={() => handleRemove(dim.dimensionId)}
- aria-label={`Remove ${dim.valueName}`}
- />
- </Badge>
- ))}
+ variant="outline"
+ className={cn(
+ getColor(entityType),
+ "inline-flex items-center gap-1"
+ )}
+ >
+ <DimensionEntityTypeIcon
+ entityType={entityType as any}
+ className="size-3"
+ />
+ <span>{label}</span>
+ <BadgeCloseButton
+ tabIndex={0}
+ onClick={() => handleRemove(dim.dimensionId)}
+ aria-label={`Remove ${label}`}
+ />
+ </Badge>
+ );
+ })}
</div>
);
};
diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.ts
index 54d7a17bf2..ae5b61fc13 100644
--- a/apps/erp/app/modules/invoicing/invoicing.service.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts
@@ -1909,7 +1909,9 @@ export async function getAvailableCreditsForParty(
const ids = rows.map((m) => m.id as string);
const apps = await client
.from("invoiceSettlement")
- .select("memoId, appliedAmount, appliedViaPaymentId")
+ .select(
+ "memoId, appliedAmount, appliedViaPaymentId, appliedViaPayment:payment!invoiceSettlement_appliedViaPaymentId_fkey(status)"
+ )
.in("memoId", ids);
if (apps.error) return { data: null, error: apps.error };
@@ -1919,6 +1921,12 @@ export async function getAvailableCreditsForParty(
const viaId = (a as { appliedViaPaymentId: string | null })
.appliedViaPaymentId;
if (excludePaymentId && viaId === excludePaymentId) continue;
+ // A voided applying payment releases its credit application — the
+ // invoice balance reopens (the views stop counting the row), so the
+ // memo's remaining must reopen with it. Draft still reserves.
+ const viaStatus = (a as { appliedViaPayment: { status: string } | null })
+ .appliedViaPayment?.status;
+ if (viaId && viaStatus === "Voided") continue;
appliedByMemo.set(
a.memoId,
(appliedByMemo.get(a.memoId) ?? 0) + Number(a.appliedAmount)
@@ -1969,13 +1977,19 @@ export async function getCompanyHasOpenCredits(
const ids = rows.map((m) => m.id as string);
const apps = await client
.from("invoiceSettlement")
- .select("memoId, appliedAmount")
+ .select(
+ "memoId, appliedAmount, appliedViaPaymentId, appliedViaPayment:payment!invoiceSettlement_appliedViaPaymentId_fkey(status)"
+ )
.in("memoId", ids);
if (apps.error) return false;
const appliedByMemo = new Map<string, number>();
for (const a of apps.data ?? []) {
if (!a.memoId) continue;
+ // A voided applying payment releases its credit application.
+ const viaStatus = (a as { appliedViaPayment: { status: string } | null })
+ .appliedViaPayment?.status;
+ if (a.appliedViaPaymentId && viaStatus === "Voided") continue;
appliedByMemo.set(
a.memoId,
(appliedByMemo.get(a.memoId) ?? 0) + Number(a.appliedAmount)
@@ -2095,10 +2109,23 @@ export async function applyCreditsToInvoices(
.where("companyId", "=", args.companyId)
.forUpdate()
.execute();
+ // A voided applying payment releases its credit application; Draft
+ // still reserves (pessimistic, matches the composer's available list).
const priorByMemo = await trx
.selectFrom("invoiceSettlement")
- .select(["memoId", "appliedAmount"])
- .where("memoId", "in", memoIds)
+ .leftJoin(
+ "payment as vp",
+ "vp.id",
+ "invoiceSettlement.appliedViaPaymentId"
+ )
+ .select(["invoiceSettlement.memoId", "invoiceSettlement.appliedAmount"])
+ .where("invoiceSettlement.memoId", "in", memoIds)
+ .where((eb) =>
+ eb.or([
+ eb("invoiceSettlement.appliedViaPaymentId", "is", null),
+ eb("vp.status", "!=", "Voided")
+ ])
+ )
.execute();
const priorApplied = new Map<string, number>();
for (const p of priorByMemo) {
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index c2068f31ed..d4e0bd05fb 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -520,9 +520,55 @@ export async function deleteProcedureParameter(
export async function deleteProductionEvent(
client: SupabaseClient<Database>,
- productionEventId: string
+ productionEventId: string,
+ companyId: string,
+ userId: string
) {
- return client.from("productionEvent").delete().eq("id", productionEventId);
+ const event = await client
+ .from("productionEvent")
+ .select("id, postedToGL")
+ .eq("id", productionEventId)
+ .eq("companyId", companyId)
+ .single();
+ if (event.error) return event;
+
+ // A posted event's journal entry must be reversed before the row goes
+ // away, otherwise WIP keeps the orphaned absorption.
+ if (event.data.postedToGL) {
+ const reversal = await client.functions.invoke<{
+ success: boolean;
+ reason?: string;
+ }>("post-production-event", {
+ body: { productionEventId, companyId, userId, reverse: true }
+ });
+ if (reversal.error) {
+ return {
+ data: null,
+ error: {
+ message: `Failed to reverse the event's journal entry: ${reversal.error.message}`
+ }
+ };
+ }
+ if (reversal.data && reversal.data.success === false) {
+ return {
+ data: null,
+ error: {
+ message: `Cannot delete a posted production event: ${
+ reversal.data.reason ?? "unknown reason"
+ }`
+ }
+ };
+ }
+ }
+
+ // Recorded output quantities reference this event via ON DELETE SET NULL FKs
+ // (migration below), so they survive with their link cleared — the quantities
+ // are real output and outlive an individual time card.
+ return client
+ .from("productionEvent")
+ .delete()
+ .eq("id", productionEventId)
+ .eq("companyId", companyId);
}
export async function deleteProductionQuantity(
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
index d60fdd54c7..da300c110f 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
@@ -291,6 +291,7 @@ const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {
sourceDocumentId={makeMethod.id}
locationId={routeData?.job?.locationId ?? undefined}
context="workCenter"
+ variant="ghost"
fileRoutes={{
pdf: path.to.file.operationLabelsPdf,
zpl: path.to.file.operationLabelsZpl
diff --git a/apps/erp/app/modules/production/ui/Jobs/ProductionEventForm.tsx b/apps/erp/app/modules/production/ui/Jobs/ProductionEventForm.tsx
index 48f9ce5fd8..4616b1545a 100644
--- a/apps/erp/app/modules/production/ui/Jobs/ProductionEventForm.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/ProductionEventForm.tsx
@@ -38,6 +38,7 @@ type ProductionEventFormProps = {
label: string;
value: string;
helperText?: string;
+ processId?: string | null;
}[];
};
@@ -56,6 +57,13 @@ const ProductionEventForm = ({
];
const onClose = () => navigate(-1);
+ const [jobOperationId, setJobOperationId] = useState(
+ initialValues.jobOperationId ?? ""
+ );
+ const processId =
+ operationOptions.find((option) => option.value === jobOperationId)
+ ?.processId ?? undefined;
+
const [startTime, setStartTime] = useState(
toCalendarDateTime(
parseAbsolute(initialValues.startTime, getLocalTimeZone())
@@ -104,13 +112,14 @@ const ProductionEventForm = ({
label={t`Operation`}
termId="operation"
options={operationOptions ?? []}
+ onChange={(value) => setJobOperationId(value?.value ?? "")}
/>
<Employee name="employeeId" label={t`Employee`} />
<WorkCenter
name="workCenterId"
label={t`Work Center`}
termId="work-center"
- processId={initialValues.jobOperationId}
+ processId={processId}
/>
<Select
name="type"
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 1ab4dc34f7..c647f96917 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,5 +1,5 @@
{
- "generated": "2026-07-02T18:10:52.196Z",
+ "generated": "2026-07-03T02:39:35.521Z",
"totalTools": 1254,
"modules": 15,
"tools": [
@@ -15445,7 +15445,9 @@
"paramCount": 1,
"serviceParams": [
"client",
- "productionEventId"
+ "productionEventId",
+ "companyId",
+ "userId"
],
"injectAuth": [
"companyId"
diff --git a/apps/erp/app/routes/x+/job+/$jobId.events.$id.tsx b/apps/erp/app/routes/x+/job+/$jobId.events.$id.tsx
index 6f4f393805..55d6fc1bce 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.events.$id.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.events.$id.tsx
@@ -35,7 +35,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
workCenters.data?.find((center) => center.id === operation.workCenterId)
?.name
}`,
- value: operation.id
+ value: operation.id,
+ processId: operation.processId
}));
if (productionEvent.error) {
@@ -83,20 +84,38 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ let postingError: string | null = null;
if (d.endTime) {
const serviceRole = await getCarbonServiceRole();
- await serviceRole.functions.invoke("post-production-event", {
+ const posting = await serviceRole.functions.invoke<{
+ success: boolean;
+ reason?: string;
+ error?: string;
+ }>("post-production-event", {
body: {
productionEventId: id,
userId,
companyId
}
});
+ if (posting.error) {
+ postingError = posting.error.message;
+ } else if (posting.data && posting.data.success === false) {
+ postingError = posting.data.reason ?? "unknown reason";
+ }
}
throw redirect(
`${path.to.jobProductionEvents(jobId)}?${getParams(request)}`,
- await flash(request, success("Updated production event"))
+ await flash(
+ request,
+ postingError
+ ? error(
+ postingError,
+ `Production event updated, but no journal entry was posted: ${postingError}`
+ )
+ : success("Updated production event")
+ )
);
}
diff --git a/apps/erp/app/routes/x+/job+/$jobId.events.new.tsx b/apps/erp/app/routes/x+/job+/$jobId.events.new.tsx
index b700371119..4086de9d6a 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.events.new.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.events.new.tsx
@@ -29,7 +29,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const operationOptions =
jobOperations.data?.map((operation) => ({
label: operation.description ?? "",
- value: operation.id
+ value: operation.id,
+ processId: operation.processId
})) ?? [];
return { operationOptions };
@@ -86,22 +87,40 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ let postingError: string | null = null;
if (d.endTime) {
const serviceRole = await getCarbonServiceRole();
- await serviceRole.functions.invoke("post-production-event", {
+ const posting = await serviceRole.functions.invoke<{
+ success: boolean;
+ reason?: string;
+ error?: string;
+ }>("post-production-event", {
body: {
productionEventId: insert.data.id,
userId,
companyId
}
});
+ if (posting.error) {
+ postingError = posting.error.message;
+ } else if (posting.data && posting.data.success === false) {
+ postingError = posting.data.reason ?? "unknown reason";
+ }
}
return modal
? data(insert, { status: 201 })
: redirect(
`${path.to.jobProductionEvents(jobId)}?${getParams(request)}`,
- await flash(request, success("Production event created"))
+ await flash(
+ request,
+ postingError
+ ? error(
+ postingError,
+ `Production event created, but no journal entry was posted: ${postingError}`
+ )
+ : success("Production event created")
+ )
);
}
diff --git a/apps/erp/app/routes/x+/job+/methods+/event.delete.$id.tsx b/apps/erp/app/routes/x+/job+/methods+/event.delete.$id.tsx
index 42423a7516..2b73e69164 100644
--- a/apps/erp/app/routes/x+/job+/methods+/event.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/event.delete.$id.tsx
@@ -8,14 +8,14 @@ import { path, requestReferrer } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
delete: "production"
});
const { id } = params;
if (!id) throw new Error("Could not find id");
- const deletion = await deleteProductionEvent(client, id);
+ const deletion = await deleteProductionEvent(client, id, companyId, userId);
if (deletion.error) {
throw redirect(
requestReferrer(request) ?? path.to.jobs,
diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsx
index 2a577854e3..c604961260 100644
--- a/apps/mes/app/components/JobOperation/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx
@@ -1643,6 +1643,7 @@ export const JobOperation = ({
locationId={locationId}
context="workCenter"
workCenterId={operation.workCenterId ?? undefined}
+ size="lg"
fileRoutes={{
pdf: path.to.file.operationLabelsPdf,
zpl: path.to.file.operationLabelsZpl
@@ -1705,6 +1706,7 @@ export const JobOperation = ({
workCenterId={
operation.workCenterId ?? undefined
}
+ size="lg"
fileRoutes={{
pdf: path.to.file.trackedEntityLabelPdf,
zpl: path.to.file.trackedEntityLabelZpl
diff --git a/packages/database/supabase/functions/close-job/index.ts b/packages/database/supabase/functions/close-job/index.ts
index f8845ffbe1..f22a660c2f 100644
--- a/packages/database/supabase/functions/close-job/index.ts
+++ b/packages/database/supabase/functions/close-job/index.ts
@@ -116,7 +116,9 @@ serve(async (req: Request) => {
{
accountId: accountDefaults.data!.materialVarianceAccount,
description: "Production Variance",
- amount: debit("expense", Math.abs(remainingWip)),
+ // Signed: a positive residual debits variance / credits WIP; a
+ // negative (over-credited) residual reverses — always zeroing WIP.
+ amount: debit("expense", remainingWip),
quantity: 0,
documentType: "Job Close",
documentId: jobId,
@@ -127,7 +129,7 @@ serve(async (req: Request) => {
{
accountId: accountDefaults.data!.workInProgressAccount,
description: "WIP Account",
- amount: credit("asset", Math.abs(remainingWip)),
+ amount: credit("asset", remainingWip),
quantity: 0,
documentType: "Job Close",
documentId: jobId,
@@ -140,7 +142,7 @@ serve(async (req: Request) => {
const accountingPeriodId = await getCurrentAccountingPeriod(
client,
companyId,
- db
+ trx
);
const journalEntryId = await getNextSequence(
diff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.ts
index 2824e01b52..3757cfa314 100644
--- a/packages/database/supabase/functions/convert/index.ts
+++ b/packages/database/supabase/functions/convert/index.ts
@@ -300,6 +300,28 @@ serve(async (req: Request) => {
return acc;
}, 0);
+ // Flat header/line amounts (shipping, tax) must not be duplicated
+ // when a PO is invoiced in multiple partial invoices: the header
+ // shipping goes on the first (non-voided) invoice only, and flat
+ // line amounts are prorated by the fraction being invoiced.
+ const priorInvoiceLines = await client
+ .from("purchaseInvoiceLine")
+ .select("id, purchaseInvoice!inner(status)")
+ .eq("purchaseOrderId", purchaseOrderId)
+ .eq("companyId", companyId)
+ .neq("purchaseInvoice.status", "Voided")
+ .limit(1);
+ const hasPriorInvoice = (priorInvoiceLines.data?.length ?? 0) > 0;
+
+ const uninvoicedFraction = (line: {
+ purchaseQuantity: number | null;
+ quantityToInvoice: number | null;
+ }) => {
+ const ordered = line.purchaseQuantity ?? 0;
+ if (ordered <= 0) return 1;
+ return Math.min((line.quantityToInvoice ?? 0) / ordered, 1);
+ };
+
let purchaseInvoiceId = "";
await db.transaction().execute(async (trx) => {
@@ -346,8 +368,9 @@ serve(async (req: Request) => {
.values({
id: purchaseInvoiceId,
locationId: purchaseOrderDelivery.data.locationId,
- supplierShippingCost:
- purchaseOrderDelivery.data.supplierShippingCost ?? 0,
+ supplierShippingCost: hasPriorInvoice
+ ? 0
+ : purchaseOrderDelivery.data.supplierShippingCost ?? 0,
shippingMethodId: purchaseOrderDelivery.data.shippingMethodId,
shippingTermId: purchaseOrderDelivery.data.shippingTermId,
incoterm: purchaseOrderDelivery.data.incoterm,
@@ -372,8 +395,10 @@ serve(async (req: Request) => {
description: line.description,
quantity: line.quantityToInvoice,
supplierUnitPrice: line.supplierUnitPrice ?? 0,
- supplierShippingCost: line.supplierShippingCost ?? 0,
- supplierTaxAmount: line.supplierTaxAmount ?? 0,
+ supplierShippingCost:
+ (line.supplierShippingCost ?? 0) * uninvoicedFraction(line),
+ supplierTaxAmount:
+ (line.supplierTaxAmount ?? 0) * uninvoicedFraction(line),
purchaseUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,
inventoryUnitOfMeasureCode: line.inventoryUnitOfMeasureCode,
conversionFactor: line.conversionFactor,
diff --git a/packages/database/supabase/functions/issue/index.ts b/packages/database/supabase/functions/issue/index.ts
index 66aa3ff066..adf209b37d 100644
--- a/packages/database/supabase/functions/issue/index.ts
+++ b/packages/database/supabase/functions/issue/index.ts
@@ -198,8 +198,20 @@ async function issueJobOperationMaterials(
[];
for await (const material of materialsToIssue) {
+ // Cap the backflush at the material's remaining unissued requirement,
+ // mirroring backflush_job_materials. Without this, materials already
+ // issued manually (e.g. from MES after skipping the operation) get
+ // consumed a second time on operation completion — duplicate item/cost
+ // ledger entries and duplicate DR WIP / CR Inventory journal lines.
+ const demandQuantity = Number(material.quantity) * quantity;
+ const remainingQuantity = Math.max(
+ Number(material.estimatedQuantity ?? 0) -
+ Number(material.quantityIssued ?? 0),
+ 0
+ );
+ const quantityToIssue = Math.min(demandQuantity, remainingQuantity);
- const quantityToIssue = Number(material.quantity) * quantity;
+ if (quantityToIssue <= 0) continue;
let proposedStorageUnitId = material.storageUnitId;
@@ -406,7 +418,7 @@ async function issueJobOperationMaterials(
}
if (journalLineInserts.length > 0) {
- const accountingPeriodId = await getCurrentAccountingPeriod(client, companyId, db);
+ const accountingPeriodId = await getCurrentAccountingPeriod(client, companyId, trx);
const journalEntryId = await getNextSequence(trx, "journalEntry", companyId);
const journalResult = await trx
@@ -649,7 +661,7 @@ async function createMaterialWipEntries(
if (journalLineInserts.length === 0) return;
- const accountingPeriodId = await getCurrentAccountingPeriod(client, companyId, db);
+ const accountingPeriodId = await getCurrentAccountingPeriod(client, companyId, trx);
const journalEntryId = await getNextSequence(trx, "journalEntry", companyId);
const journalResult = await trx
@@ -1402,9 +1414,14 @@ serve(async (req: Request) => {
await trx
.updateTable("jobMaterial")
.set({
+ // A positive adjustment returns material to inventory, so it
+ // reduces quantityIssued — otherwise the backflush cap sees
+ // returned material as still issued.
quantityIssued:
(Number(material?.quantityIssued) ?? 0) +
- Number(quantityToIssue),
+ (adjustmentType === "Positive Adjmt."
+ ? -Number(quantityToIssue)
+ : Number(quantityToIssue)),
})
.where("id", "=", materialId)
.execute();
diff --git a/packages/database/supabase/functions/lib/seed.data.ts b/packages/database/supabase/functions/lib/seed.data.ts
index 687dd23a64..41d276c9d6 100644
--- a/packages/database/supabase/functions/lib/seed.data.ts
+++ b/packages/database/supabase/functions/lib/seed.data.ts
@@ -733,6 +733,7 @@ export const accountDefaults = {
inventoryAccount: "1210",
workInProgressAccount: "1230",
receivablesAccount: "1110",
+ intercompanyReceivablesAccount: "1130",
bankCashAccount: "1010",
bankLocalCurrencyAccount: "1020",
bankForeignCurrencyAccount: "1030",
diff --git a/packages/database/supabase/functions/lib/utils.ts b/packages/database/supabase/functions/lib/utils.ts
index 7d801885f4..88d225c678 100644
--- a/packages/database/supabase/functions/lib/utils.ts
+++ b/packages/database/supabase/functions/lib/utils.ts
@@ -90,5 +90,6 @@ export const journalReference = {
shipment: (id: string) => `shipment:${id}`,
job: (id: string) => `job:${id}`,
materialIssue: (id: string) => `material-issue:${id}`,
+ productionEvent: (id: string) => `production-event:${id}`,
},
};
diff --git a/packages/database/supabase/functions/post-payment/index.ts b/packages/database/supabase/functions/post-payment/index.ts
index 83cbec6678..d6b80164bc 100644
--- a/packages/database/supabase/functions/post-payment/index.ts
+++ b/packages/database/supabase/functions/post-payment/index.ts
@@ -310,6 +310,11 @@ serve(async (req: Request) => {
const ad = accountDefaults.data;
const journalLineReference = nanoid();
+ // Intercompany invoices are booked to the IC receivables account
+ // (1130) at posting, so the payment must relieve the same control
+ // account — otherwise 1130 stays debited and regular AR goes negative.
+ let controlAccountId = isAR ? ad.receivablesAccount : ad.payablesAccount;
+
// Resolve the counterparty type + entity dimensions for this payment.
const companyRecord = await client
.from("company")
@@ -327,7 +332,7 @@ serve(async (req: Request) => {
isAR
? client
.from("customer")
- .select("customerTypeId")
+ .select("customerTypeId, intercompanyCompanyId")
.eq("id", partyId)
.maybeSingle()
: client
@@ -365,6 +370,20 @@ serve(async (req: Request) => {
valueId: partyId,
});
}
+
+ if (isAR && party?.intercompanyCompanyId) {
+ // Relieve the same control account the invoice was booked to. Resolve
+ // it from accountDefault (stable id), not by account number — numbers
+ // are user-editable. Fall back to regular receivables if unset.
+ const icReceivablesAccount = (
+ ad as unknown as {
+ intercompanyReceivablesAccount?: string | null;
+ }
+ ).intercompanyReceivablesAccount;
+ if (icReceivablesAccount) {
+ controlAccountId = icReceivablesAccount;
+ }
+ }
}
// Build the balanced double-entry. Account-id resolution, the per-
@@ -390,9 +409,7 @@ serve(async (req: Request) => {
sourceExchangeRate: Number(a.sourceExchangeRate),
})),
accounts: {
- controlAccountId: isAR
- ? ad.receivablesAccount
- : ad.payablesAccount,
+ controlAccountId,
discountAccountId: isAR
? ad.customerPaymentDiscountAccount
: ad.supplierPaymentDiscountAccount,
@@ -569,17 +586,93 @@ serve(async (req: Request) => {
}
}
+ // The memos behind the staged credits must still be Posted with enough
+ // remaining when the payment posts — a memo voided (or drawn down by
+ // another payment) after staging must fail the post, not go live
+ // silently. FOR UPDATE serializes concurrent posts drawing on the same
+ // memo.
+ const stagedByMemo = new Map<string, number>();
+ for (const c of credits.data ?? []) {
+ if (!c.memoId) continue;
+ stagedByMemo.set(
+ c.memoId,
+ (stagedByMemo.get(c.memoId) ?? 0) + Number(c.appliedAmount)
+ );
+ }
+ if (stagedByMemo.size > 0) {
+ const memoIds = [...stagedByMemo.keys()];
+ const memos = await trx
+ .selectFrom("memo")
+ .select(["id", "status", "amount"])
+ .where("id", "in", memoIds)
+ .where("companyId", "=", companyId)
+ .forUpdate()
+ .execute();
+ const memoById = new Map(memos.map((m) => [m.id, m]));
+
+ // Live consumption of these memos: memo-sourced settlement rows that
+ // are not staged on a non-Posted payment. This payment's own staged
+ // rows are excluded (its via-payment is still Draft here).
+ const memoApps = await trx
+ .selectFrom("invoiceSettlement")
+ .leftJoin(
+ "payment as vp",
+ "vp.id",
+ "invoiceSettlement.appliedViaPaymentId"
+ )
+ .select(["invoiceSettlement.memoId", "invoiceSettlement.appliedAmount"])
+ .where("invoiceSettlement.memoId", "in", memoIds)
+ .where((eb) =>
+ eb.or([
+ eb("invoiceSettlement.appliedViaPaymentId", "is", null),
+ eb("vp.status", "=", "Posted"),
+ ])
+ )
+ .execute();
+ const appliedByMemo = new Map<string, number>();
+ for (const a of memoApps) {
+ if (!a.memoId) continue;
+ appliedByMemo.set(
+ a.memoId,
+ (appliedByMemo.get(a.memoId) ?? 0) + Number(a.appliedAmount)
+ );
+ }
+
+ for (const [memoId, staged] of stagedByMemo) {
+ const memo = memoById.get(memoId);
+ if (!memo) throw new Error(`Memo ${memoId} not found`);
+ if (memo.status !== "Posted") {
+ throw new Error(
+ `Cannot post payment: memo ${memoId} is ${memo.status} (must be Posted)`
+ );
+ }
+ const remaining =
+ Number(memo.amount) - (appliedByMemo.get(memoId) ?? 0);
+ if (staged > remaining + 0.0001) {
+ throw new Error(
+ `Staged credit (${staged}) exceeds remaining amount (${remaining}) on memo ${memoId}`
+ );
+ }
+ }
+ }
+
// When this payment applies more than its cash, the excess draws down the
// party's available on-account credit — the net unapplied cash left on
// their OTHER posted payments. Lock those payments FOR UPDATE so two
// concurrent credit-consuming posts can't both spend the same credit.
if (overAppliedBase > 0.0001) {
+ // Only same-direction payments contribute credit: a Receipt from a
+ // customer leaves on-account credit; a Disbursement to the same
+ // customer is a refund that CONSUMES credit, not a source of it.
+ // Mirrors getAvailableOnAccountCredit in invoicing.service.ts.
+ const creditPaymentType = isAR ? "Receipt" : "Disbursement";
const postedPayments = await (isAR
? trx
.selectFrom("payment")
.select(["id", "totalAmount", "exchangeRate"])
.where("companyId", "=", companyId)
.where("status", "=", "Posted")
+ .where("paymentType", "=", creditPaymentType)
.where("customerId", "=", paymentPartyId)
.forUpdate()
.execute()
@@ -588,6 +681,7 @@ serve(async (req: Request) => {
.select(["id", "totalAmount", "exchangeRate"])
.where("companyId", "=", companyId)
.where("status", "=", "Posted")
+ .where("paymentType", "=", creditPaymentType)
.where("supplierId", "=", paymentPartyId)
.forUpdate()
.execute());
diff --git a/packages/database/supabase/functions/post-production-event/index.ts b/packages/database/supabase/functions/post-production-event/index.ts
index c2970663dc..1f1608a95c 100644
--- a/packages/database/supabase/functions/post-production-event/index.ts
+++ b/packages/database/supabase/functions/post-production-event/index.ts
@@ -18,6 +18,9 @@ const payloadValidator = z.object({
productionEventId: z.string(),
userId: z.string(),
companyId: z.string(),
+ // Reverse the net journal lines previously posted for this event (e.g.
+ // before deleting it) instead of posting its current state.
+ reverse: z.boolean().optional(),
});
serve(async (req: Request) => {
@@ -29,7 +32,7 @@ serve(async (req: Request) => {
const today = format(new Date(), "yyyy-MM-dd");
try {
- const { productionEventId, userId, companyId } =
+ const { productionEventId, userId, companyId, reverse } =
payloadValidator.parse(payload);
const client = await requirePermissions(req, companyId, userId, { update: "production" });
@@ -81,38 +84,112 @@ serve(async (req: Request) => {
}
const event = productionEvent.data;
- if (!event.endTime || !event.duration || !event.workCenterId) {
- await client
- .from("productionEvent")
- .update({ postedToGL: true })
- .eq("id", productionEventId);
+
+ if (reverse && !event.postedToGL) {
+ // Nothing was posted for this event, so there is nothing to reverse.
return new Response(JSON.stringify({ success: true }), {
headers: { ...corsHeaders, "Content-Type": "application/json" },
});
}
+ if (!reverse && (!event.endTime || !event.duration || !event.workCenterId)) {
+ // Leave postedToGL untouched so the event can still be posted later
+ // (manually or by complete_job_to_inventory) once it's completable.
+ const reason = !event.endTime
+ ? "event has no end time"
+ : !event.duration
+ ? "event has no duration"
+ : "event has no work center";
+ return new Response(JSON.stringify({ success: false, reason }), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ });
+ }
+
const jobId = (event.jobOperation as any).jobId as string;
- const workCenter = await client
- .from("workCenter")
- .select("laborRate, machineRate")
- .eq("id", event.workCenterId)
- .single();
+ let cost = 0;
+ if (!reverse) {
+ const workCenter = await client
+ .from("workCenter")
+ .select("laborRate, machineRate")
+ .eq("id", event.workCenterId!)
+ .single();
- if (workCenter.error) throw new Error(`Failed to fetch work center ${event.workCenterId}: ${workCenter.error.message}`);
+ if (workCenter.error) throw new Error(`Failed to fetch work center ${event.workCenterId}: ${workCenter.error.message}`);
- const durationHours = event.duration / 3600;
- const rate =
- event.type === "Machine"
- ? Number(workCenter.data.machineRate ?? 0)
- : Number(workCenter.data.laborRate ?? 0);
+ const durationHours = (event.duration ?? 0) / 3600;
+ const rate =
+ event.type === "Machine"
+ ? Number(workCenter.data.machineRate ?? 0)
+ : Number(workCenter.data.laborRate ?? 0);
- const cost = durationHours * rate;
+ cost = durationHours * rate;
+ }
- if (cost <= 0) {
+ // Net amount already posted for this specific event, grouped by account.
+ const eventReference = journalReference.to.productionEvent(
+ productionEventId
+ );
+ const priorLines = event.postedToGL
+ ? await db
+ .selectFrom("journalLine")
+ .select(["accountId", (eb) => eb.fn.sum("amount").as("amount")])
+ .where("documentLineReference", "=", eventReference)
+ .where("companyId", "=", companyId)
+ .groupBy("accountId")
+ .execute()
+ : [];
+ const reversalLines = priorLines.filter(
+ (line) => Math.abs(Number(line.amount)) >= 0.000001
+ );
+
+ // Did this event's job post any production-event lines under the old
+ // job-tagged scheme (documentLineReference = job:...)? Those can't be
+ // attributed to one event, so editing/reversing a posted event that has no
+ // per-event lines can't be done safely — it needs a manual journal entry.
+ // This is rate-independent: unlike recomputing cost, it still recognizes a
+ // zero-cost posted event (which posted nothing) as safe to delete even
+ // after the work center's rate later changes.
+ const hasOldSchemePostings =
+ event.postedToGL && reversalLines.length === 0
+ ? Number(
+ (
+ await db
+ .selectFrom("journalLine")
+ .select((eb) => eb.fn.countAll().as("count"))
+ .where("documentType", "=", "Production Event")
+ .where("documentId", "=", jobId)
+ .where(
+ "documentLineReference",
+ "=",
+ journalReference.to.job(jobId)
+ )
+ .where("companyId", "=", companyId)
+ .executeTakeFirst()
+ )?.count ?? 0
+ ) > 0
+ : false;
+
+ // Block only when the event posted amounts under the old scheme that we
+ // can't attribute/reverse. A zero-cost posted event posted nothing, so
+ // there's nothing to reverse and it's safe to delete.
+ if (event.postedToGL && reversalLines.length === 0 && hasOldSchemePostings) {
+ return new Response(
+ JSON.stringify({
+ success: false,
+ reason:
+ "event was posted before per-event journal references; adjust with a manual journal entry",
+ }),
+ { headers: { ...corsHeaders, "Content-Type": "application/json" } }
+ );
+ }
+
+ if (cost <= 0 && reversalLines.length === 0) {
+ // Nothing to post and nothing to reverse. On a reversal this clears the
+ // flag so the event can be deleted; on a post it marks it done.
await client
.from("productionEvent")
- .update({ postedToGL: true })
+ .update({ postedToGL: !reverse })
.eq("id", productionEventId);
return new Response(JSON.stringify({ success: true }), {
headers: { ...corsHeaders, "Content-Type": "application/json" },
@@ -146,28 +223,45 @@ serve(async (req: Request) => {
const journalLineReference = nanoid();
const journalLineInserts = [
- {
- accountId: accountDefaults.data.workInProgressAccount,
- description: "WIP Account",
- amount: debit("asset", cost),
+ // Reposting an edited event: first negate the net previously posted for
+ // this event per account, then post the new amount.
+ ...reversalLines.map((line) => ({
+ accountId: line.accountId,
+ description: "Production Event Reversal",
+ amount: -Number(line.amount),
quantity: 1,
documentType: "Production Event",
documentId: jobId,
- documentLineReference: journalReference.to.job(jobId),
+ documentLineReference: eventReference,
journalLineReference,
companyId,
- },
- {
- accountId: accountDefaults.data.laborAbsorptionAccount!,
- description: "Labor/Machine Absorption",
- amount: credit("expense", cost),
- quantity: 1,
- documentType: "Production Event",
- documentId: jobId,
- documentLineReference: journalReference.to.job(jobId),
- journalLineReference,
- companyId,
- },
+ })),
+ ...(!reverse && cost > 0
+ ? [
+ {
+ accountId: accountDefaults.data.workInProgressAccount,
+ description: "WIP Account",
+ amount: debit("asset", cost),
+ quantity: 1,
+ documentType: "Production Event",
+ documentId: jobId,
+ documentLineReference: eventReference,
+ journalLineReference,
+ companyId,
+ },
+ {
+ accountId: accountDefaults.data.laborAbsorptionAccount!,
+ description: "Labor/Machine Absorption",
+ amount: credit("expense", cost),
+ quantity: 1,
+ documentType: "Production Event",
+ documentId: jobId,
+ documentLineReference: eventReference,
+ journalLineReference,
+ companyId,
+ },
+ ]
+ : []),
];
const accountingPeriodId = await getCurrentAccountingPeriod(
@@ -188,7 +282,13 @@ serve(async (req: Request) => {
.values({
journalEntryId,
accountingPeriodId,
- description: `${event.type} Time — Job ${job.data.jobId}`,
+ description: `${event.type} Time — Job ${job.data.jobId}${
+ reverse
+ ? " (Reversal)"
+ : reversalLines.length > 0
+ ? " (Adjustment)"
+ : ""
+ }`,
postingDate: today,
companyId,
sourceType: "Production Event",
@@ -284,7 +384,7 @@ serve(async (req: Request) => {
await trx
.updateTable("productionEvent")
- .set({ postedToGL: true })
+ .set({ postedToGL: !reverse })
.where("id", "=", productionEventId)
.execute();
});
diff --git a/packages/database/supabase/functions/post-purchase-invoice/index.ts b/packages/database/supabase/functions/post-purchase-invoice/index.ts
index 8b40b6c0d5..27f4159ac2 100644
--- a/packages/database/supabase/functions/post-purchase-invoice/index.ts
+++ b/packages/database/supabase/functions/post-purchase-invoice/index.ts
@@ -442,12 +442,21 @@ serve(async (req: Request) => {
if (dim.entityType) dimensionMap.set(dim.entityType, dim.id);
}
+ // supplierShippingCost is a supplier-currency amount; currency.exchangeRate
+ // stores foreign-units-per-base, so supplier→base is DIVIDE (matching the
+ // purchaseInvoices view and the line-level generated columns). It is then
+ // folded into the per-line totals BEFORE the payment-chain exchange-rate
+ // multiplier so AP is credited exactly what post-payment will debit.
const shippingCost =
- (purchaseInvoiceDelivery.data?.supplierShippingCost ?? 0) *
- (purchaseInvoice.data?.exchangeRate ?? 1);
+ (purchaseInvoiceDelivery.data?.supplierShippingCost ?? 0) /
+ (purchaseInvoice.data?.exchangeRate || 1);
+ // Pre-allocation denominator for the header shipping cost. Comment lines
+ // post no journal entries, so they must not absorb a share of the
+ // shipping (it would never reach the GL).
const totalLinesCost = purchaseInvoiceLines.data.reduce(
(acc, invoiceLine) => {
+ if (invoiceLine.invoiceLineType === "Comment") return acc;
const lineCost =
(invoiceLine.quantity ?? 0) * (invoiceLine.unitPrice ?? 0) +
(invoiceLine.shippingCost ?? 0) +
@@ -457,6 +466,10 @@ serve(async (req: Request) => {
0
);
+ const postableLineCount = purchaseInvoiceLines.data.filter(
+ (invoiceLine) => invoiceLine.invoiceLineType !== "Comment"
+ ).length;
+
const itemIds = purchaseInvoiceLines.data.reduce<string[]>(
(acc, invoiceLine) => {
if (invoiceLine.itemId && !acc.includes(invoiceLine.itemId)) {
@@ -664,9 +677,11 @@ serve(async (req: Request) => {
}
// Invoice exchange rate (defaults to 1 for base-currency invoices).
- // shippingCost (line 445) is already multiplied by the rate; per-line
- // unitPrice / shippingCost / taxAmount on purchaseInvoiceLine are in
- // invoice currency and need conversion before they reach a journal line.
+ // The payment chain (post-payment/build-payment-journal) relieves AP at
+ // `applied × exchangeRate`, so posting applies the same multiplier to the
+ // line totals (header shipping included, already divided to base above)
+ // to keep AP credit == what payments will debit. See the FX-convention
+ // spec for the planned normalization of this multiplier.
const invoiceExchangeRate = purchaseInvoice.data?.exchangeRate ?? 1;
for await (const invoiceLine of purchaseInvoiceLines.data) {
@@ -678,14 +693,22 @@ serve(async (req: Request) => {
(invoiceLine.shippingCost ?? 0) +
(invoiceLine.taxAmount ?? 0);
+ // When every line has a zero basis (e.g. a freight-only invoice), fall
+ // back to equal weights so the header shipping still reaches AP.
const lineCostPercentageOfTotalCost =
- totalLinesCost === 0 ? 0 : totalLineCost / totalLinesCost;
+ invoiceLine.invoiceLineType === "Comment"
+ ? 0
+ : totalLinesCost === 0
+ ? postableLineCount === 0
+ ? 0
+ : 1 / postableLineCount
+ : totalLineCost / totalLinesCost;
const lineWeightedShippingCost =
shippingCost * lineCostPercentageOfTotalCost;
- // Convert line cost to base currency before combining with the
- // already-converted shipping cost.
+ // Line cost and weighted shipping are both base currency here; the
+ // exchange-rate multiplier matches the payment chain's AP relief.
const totalLineCostWithWeightedShipping =
- totalLineCost * invoiceExchangeRate + lineWeightedShippingCost;
+ (totalLineCost + lineWeightedShippingCost) * invoiceExchangeRate;
const invoiceLineUnitCostInInventoryUnit =
totalLineCostWithWeightedShipping /
@@ -1095,6 +1118,13 @@ serve(async (req: Request) => {
break;
case "Fixed Asset": {
+ // Silently skipping would credit less to AP than the invoice total
+ // the payment flow is allowed to apply against.
+ if (accountingEnabled && !invoiceLine.assetId) {
+ throw new Error(
+ `Fixed Asset invoice line ${invoiceLine.id} has no asset selected`
+ );
+ }
if (accountingEnabled && accountDefaults?.data && invoiceLine.assetId) {
const purchaseOrderLine = purchaseOrderLines.data.find(
(line) => line.id === invoiceLine.purchaseOrderLineId
diff --git a/packages/database/supabase/functions/post-sales-invoice/index.ts b/packages/database/supabase/functions/post-sales-invoice/index.ts
index 9e620cecfa..2f6f59664e 100644
--- a/packages/database/supabase/functions/post-sales-invoice/index.ts
+++ b/packages/database/supabase/functions/post-sales-invoice/index.ts
@@ -105,8 +105,12 @@ serve(async (req: Request) => {
switch (type) {
case "post": {
+ // Pre-tax denominator for allocating the header shipping cost.
+ // Comment lines post no journal entries, so they must not absorb a
+ // share of the shipping (it would never reach the GL).
const totalLinesCost = salesInvoiceLines.data.reduce(
(acc, invoiceLine) => {
+ if (invoiceLine.invoiceLineType === "Comment") return acc;
const lineCost =
(invoiceLine.quantity ?? 0) * (invoiceLine.unitPrice ?? 0) +
(invoiceLine.shippingCost ?? 0) +
@@ -116,6 +120,10 @@ serve(async (req: Request) => {
0
);
+ const postableLineCount = salesInvoiceLines.data.filter(
+ (invoiceLine) => invoiceLine.invoiceLineType !== "Comment"
+ ).length;
+
const itemIds = salesInvoiceLines.data.reduce<string[]>(
(acc, invoiceLine) => {
if (invoiceLine.itemId && !acc.includes(invoiceLine.itemId)) {
@@ -273,22 +281,19 @@ serve(async (req: Request) => {
fixedAssetClassId: string | null;
}[] = [];
- // For IC transactions, use IC Receivables (1130) instead of regular AR
- let receivablesAccountId: string | undefined;
- if (isIntercompany && companyGroupId) {
- // TODO: consider storing the IC receivables account ID in a config
- // rather than looking it up by number each time
- const icAccount = await client
- .from("account")
- .select("id")
- .eq("number", "1130")
- .eq("companyGroupId", companyGroupId)
- .single();
- if (icAccount.error) throw new Error("Failed to fetch IC receivables account 1130");
- receivablesAccountId = icAccount.data.id;
- } else {
- receivablesAccountId = accountDefaults?.data?.receivablesAccount;
- }
+ // For IC transactions, book to Inter-Company Receivables instead of
+ // regular AR. Resolve it from accountDefault (stable id), not by account
+ // number — numbers are user-editable. Fall back to regular receivables
+ // if the IC default isn't configured.
+ const icReceivablesAccount = (
+ accountDefaults?.data as unknown as {
+ intercompanyReceivablesAccount?: string | null;
+ }
+ )?.intercompanyReceivablesAccount;
+ const receivablesAccountId: string | undefined =
+ isIntercompany && icReceivablesAccount
+ ? icReceivablesAccount
+ : accountDefaults?.data?.receivablesAccount;
// Invoice exchange rate (defaults to 1 for base-currency invoices).
// journalLine.amount is denominated in base currency, so all monetary
@@ -299,14 +304,30 @@ serve(async (req: Request) => {
for await (const invoiceLine of salesInvoiceLines.data) {
const invoiceLineQuantityInInventoryUnit = invoiceLine.quantity;
+ const preTaxLineCost =
+ invoiceLine.quantity * (invoiceLine.unitPrice ?? 0) +
+ (invoiceLine.shippingCost ?? 0) +
+ (invoiceLine.addOnCost ?? 0);
+
+ // nonTaxableAddOnCost is part of the invoice total (and of the
+ // salesInvoices view balance that caps payments) but is excluded
+ // from the tax basis.
const totalLineCost =
- (invoiceLine.quantity * (invoiceLine.unitPrice ?? 0) +
- (invoiceLine.shippingCost ?? 0) +
- (invoiceLine.addOnCost ?? 0)) *
- (1 + (invoiceLine.taxPercent ?? 0));
+ preTaxLineCost * (1 + (invoiceLine.taxPercent ?? 0)) +
+ (invoiceLine.nonTaxableAddOnCost ?? 0);
+ // Header shipping is untaxed (matching the salesInvoices view), so
+ // it is weighted by the pre-tax basis — weights sum to exactly 1.
+ // When every line has a zero basis, fall back to equal weights so
+ // the shipping still reaches AR.
const lineCostPercentageOfTotalCost =
- totalLinesCost === 0 ? 0 : totalLineCost / totalLinesCost;
+ invoiceLine.invoiceLineType === "Comment"
+ ? 0
+ : totalLinesCost === 0
+ ? postableLineCount === 0
+ ? 0
+ : 1 / postableLineCount
+ : preTaxLineCost / totalLinesCost;
const lineWeightedShippingCost =
shippingCost * lineCostPercentageOfTotalCost;
// Convert to base currency for the GL.
@@ -535,6 +556,13 @@ serve(async (req: Request) => {
break;
case "Fixed Asset": {
+ // Silently skipping would post less to AR than the invoice
+ // total the payment flow is allowed to apply against.
+ if (accountingEnabled && !invoiceLine.assetId) {
+ throw new Error(
+ `Fixed Asset invoice line ${invoiceLine.id} has no asset selected`
+ );
+ }
if (accountingEnabled && accountDefaults?.data && invoiceLine.assetId) {
const salesOrderLine = salesOrderLines?.find(
(sol) => sol.id === invoiceLine.salesOrderLineId
diff --git a/packages/database/supabase/functions/shared/get-accounting-period.ts b/packages/database/supabase/functions/shared/get-accounting-period.ts
index 6aad606096..8165ecd384 100644
--- a/packages/database/supabase/functions/shared/get-accounting-period.ts
+++ b/packages/database/supabase/functions/shared/get-accounting-period.ts
@@ -24,10 +24,26 @@ const daysInMonths: Record<number, number> = {
12: 31,
};
+// Run `fn` inside a transaction, reusing `db` when it is already one.
+// The edge-function connection pool is size 1, so opening a nested
+// `db.transaction()` while the caller already holds the pool's only connection
+// would wait forever for a second connection and the isolate would be killed
+// (wall-clock timeout). Callers already inside a transaction must therefore pass
+// their `trx` so we reuse it; callers that resolve the period before starting a
+// transaction pass the pool and we open one (the pre-existing behavior).
+async function runInTransaction<R>(
+ db: Kysely<DB>,
+ fn: (trx: Kysely<DB>) => Promise<R>
+): Promise<R> {
+ return db.isTransaction ? fn(db) : db.transaction().execute(fn);
+}
+
// tries to get the current accounting period
// and if not found, creates a fiscal year and accounting periods
// and updates the active accounting period/fiscal year
-
+//
+// Pass the caller's transaction (`trx`) as `db` when calling from inside a
+// transaction — see runInTransaction above.
export async function getCurrentAccountingPeriod<T>(
client: SupabaseClient<Database>,
companyId: string,
@@ -37,7 +53,7 @@ export async function getCurrentAccountingPeriod<T>(
const d = format(new Date(), "yyyy-MM-dd");
// get the current accounting period
- let currentAccountingPeriod = await client
+ const currentAccountingPeriod = await client
.from("accountingPeriod")
.select("*")
// .gte("endDate", d.toString())
@@ -58,7 +74,8 @@ export async function getCurrentAccountingPeriod<T>(
currentAccountingPeriod.data &&
currentAccountingPeriod.data.status === "Inactive"
) {
- await db.transaction().execute(async (trx) => {
+ const periodId = currentAccountingPeriod.data.id;
+ await runInTransaction(db, async (trx) => {
await trx
.updateTable("accountingPeriod")
.set({ status: "Inactive" })
@@ -69,12 +86,12 @@ export async function getCurrentAccountingPeriod<T>(
await trx
.updateTable("accountingPeriod")
.set({ status: "Active" })
- .where("id", "=", currentAccountingPeriod.data!.id)
+ .where("id", "=", periodId)
.where("companyId", "=", companyId)
.execute();
});
- return currentAccountingPeriod.data.id;
+ return periodId;
}
const year = new Date().getFullYear();
@@ -88,7 +105,7 @@ export async function getCurrentAccountingPeriod<T>(
endDate = `${year}-${month.toString().padStart(2, "0")}-29`;
}
- const newPeriod = await db.transaction().execute(async (trx) => {
+ const newPeriod = await runInTransaction(db, async (trx) => {
await trx
.updateTable("accountingPeriod")
.set({ status: "Inactive" })
@@ -96,7 +113,7 @@ export async function getCurrentAccountingPeriod<T>(
.where("companyId", "=", companyId)
.execute();
- const result = await trx
+ return await trx
.insertInto("accountingPeriod")
.values({
startDate,
@@ -107,8 +124,6 @@ export async function getCurrentAccountingPeriod<T>(
})
.returning("id")
.executeTakeFirstOrThrow();
-
- return result;
});
return newPeriod.id;
diff --git a/packages/database/supabase/migrations/20260702114500_invoice-balance-includes-line-tax.sql b/packages/database/supabase/migrations/20260702114500_invoice-balance-includes-line-tax.sql
new file mode 100644
index 0000000000..b4e0d08529
--- /dev/null
+++ b/packages/database/supabase/migrations/20260702114500_invoice-balance-includes-line-tax.sql
@@ -0,0 +1,273 @@
+-- ============================================================
+-- Invoice balance/status must derive from the LIVE line total (incl. tax)
+--
+-- Bug: tax added on a purchase invoice line that wasn't on the PO is posted
+-- to AP tax-inclusive (with correct PPV), but the payment could only be made
+-- for the pre-tax amount. Cause: the views' `balance`, derived `Paid` status,
+-- and `datePaid` keyed off the STORED header `totalAmount` — written pre-tax
+-- at PO→invoice conversion and deprecated/frozen since 20260604120000 — while
+-- the views' own `totalAmount`/`orderTotal` outputs are line-derived and
+-- tax-inclusive. post-payment caps applications at the view `balance`, so the
+-- tax portion was stranded as an un-relievable AP credit and the invoice
+-- flipped to 'Paid' at the pre-tax amount.
+--
+-- This was fixed in 20260630102736 (balance from live line total), but
+-- 20260630151500 (dust forgiveness) forked its view bodies verbatim from the
+-- pre-fix 20260630095023 and silently reverted it; 20260702061504 forked from
+-- 151500 and perpetuated it. The same fork also reverted:
+-- * 20260630105334 — memo-aware `settled` CTE (posted credit/debit memo
+-- settlements gated on the applying payment) — memo settlements stopped
+-- reducing the view balance.
+-- * 20260629120000 — `paymentTermName` on `salesInvoices`.
+--
+-- Forked verbatim from the newest definitions:
+-- * purchaseInvoices — 20260702061504 (keeps the supplierShippingCost
+-- divide with zero-guard)
+-- * salesInvoices — 20260630151500 (keeps dust forgiveness)
+-- Only the `settled` CTE, the `datePaid`/`balance`/`status` expressions
+-- (stored total → live line-derived total), and the restored
+-- `paymentTermName` column on salesInvoices change.
+--
+-- Side effect (correct, but visible): invoices previously derived-'Paid' at
+-- the pre-tax amount reopen with a balance equal to the unpaid tax.
+-- ============================================================
+
+DROP VIEW IF EXISTS "salesInvoices";
+DROP VIEW IF EXISTS "purchaseInvoices";
+
+
+-- ============================================================
+-- salesInvoices — balance/status/datePaid from the live line total,
+-- memo-aware settlements, dust forgiveness below $0.01
+-- ============================================================
+
+CREATE VIEW "salesInvoices" WITH(SECURITY_INVOKER=true) AS
+ WITH settled AS (
+ -- Amount applied TO this invoice (as the settlement target): Posted cash
+ -- payments, and Posted credit memos once the payment applying them is
+ -- Posted (a memo staged through a Draft payment doesn't count yet).
+ SELECT
+ s."targetSalesInvoiceId",
+ 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."targetSalesInvoiceId" 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."targetSalesInvoiceId"
+ )
+ SELECT
+ si."id",
+ si."invoiceId",
+ CASE
+ WHEN si."status" IN ('Draft','Pending','Voided','Return','Credit Note Issued') THEN si."status"::TEXT
+ WHEN COALESCE(s.amount, 0) > 0
+ AND (COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0)) > 0
+ AND ((COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0)) - COALESCE(s.amount, 0)) < 0.01 THEN 'Paid'
+ WHEN COALESCE(s.amount, 0) > 0 THEN 'Partially Paid'
+ WHEN si."dateDue" < CURRENT_DATE AND si."status" = 'Submitted' THEN 'Overdue'
+ ELSE si."status"::TEXT
+ END AS status,
+ si."customerId",
+ si."customerReference",
+ si."invoiceCustomerId",
+ si."invoiceCustomerLocationId",
+ si."invoiceCustomerContactId",
+ si."paymentTermId",
+ si."postingDate",
+ si."dateIssued",
+ si."dateDue",
+ CASE
+ WHEN COALESCE(s.amount, 0) > 0
+ AND (COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0)) > 0
+ AND ((COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0)) - COALESCE(s.amount, 0)) < 0.01 THEN COALESCE(s."lastSettlementDate", si."datePaid")
+ ELSE si."datePaid"
+ END AS "datePaid",
+ si."locationId",
+ si."currencyCode",
+ COALESCE(sil."subtotal", 0) AS "subtotal",
+ si."totalDiscount",
+ COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0) AS "totalAmount",
+ COALESCE(sil."totalTax", 0) AS "totalTax",
+ CASE
+ WHEN COALESCE(s.amount, 0) > 0
+ AND ((COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0)) - COALESCE(s.amount, 0)) > 0
+ AND ((COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0)) - COALESCE(s.amount, 0)) < 0.01 THEN 0
+ ELSE ((COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0)) - COALESCE(s.amount, 0))
+ END AS "balance",
+ si."exchangeRate",
+ si."exchangeRateUpdatedAt",
+ si."opportunityId",
+ si."shipmentId",
+ si."assignee",
+ si."companyId",
+ si."customFields",
+ si."internalNotes",
+ si."externalNotes",
+ si."tags",
+ si."createdAt",
+ si."createdBy",
+ si."updatedAt",
+ si."updatedBy",
+ sil."thumbnailPath",
+ sil."itemType",
+ COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0) AS "invoiceTotal",
+ sil."lines",
+ pt."name" AS "paymentTermName"
+ FROM "salesInvoice" si
+ LEFT JOIN (
+ SELECT
+ sil."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(sil."quantity", 0)*COALESCE(sil."unitPrice", 0)
+ + COALESCE(sil."addOnCost", 0)
+ + COALESCE(sil."nonTaxableAddOnCost", 0)
+ + COALESCE(sil."shippingCost", 0)
+ ) AS "subtotal",
+ SUM(
+ COALESCE(sil."taxPercent", 0) * (
+ COALESCE(sil."quantity", 0)*COALESCE(sil."unitPrice", 0)
+ + COALESCE(sil."addOnCost", 0)
+ + COALESCE(sil."shippingCost", 0)
+ )
+ ) AS "totalTax",
+ MIN(i."type") AS "itemType",
+ ARRAY_AGG(
+ json_build_object(
+ 'id', sil.id,
+ 'invoiceLineType', sil."invoiceLineType",
+ 'quantity', sil."quantity",
+ 'unitPrice', sil."unitPrice",
+ 'itemId', sil."itemId"
+ )
+ ) AS "lines"
+ FROM "salesInvoiceLine" sil
+ LEFT JOIN "item" i
+ ON i."id" = sil."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ GROUP BY sil."invoiceId"
+ ) sil ON sil."invoiceId" = si."id"
+ -- LEFT JOIN (was INNER): an invoice missing its shipment row must not
+ -- vanish from the view — post-payment would read its balance as 0 and
+ -- reject every application. shippingCost is already COALESCEd.
+ LEFT JOIN "salesInvoiceShipment" ss ON ss."id" = si."id"
+ LEFT JOIN "paymentTerm" pt ON pt."id" = si."paymentTermId"
+ LEFT JOIN settled s ON s."targetSalesInvoiceId" = si."id";
+
+
+-- ============================================================
+-- purchaseInvoices — balance/status/datePaid from the live line total,
+-- memo-aware settlements, dust forgiveness below $0.01
+-- ============================================================
+
+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 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 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 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"
+ 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";
diff --git a/packages/database/supabase/migrations/20260702174233_production-quantity-event-fk-set-null.sql b/packages/database/supabase/migrations/20260702174233_production-quantity-event-fk-set-null.sql
new file mode 100644
index 0000000000..b91bad0f00
--- /dev/null
+++ b/packages/database/supabase/migrations/20260702174233_production-quantity-event-fk-set-null.sql
@@ -0,0 +1,26 @@
+-- Deleting a production event (time card) must not be blocked by the output
+-- quantities that reference it. A productionQuantity records real output that
+-- outlives an individual time card, so when its setup/labor/machine event is
+-- deleted we clear the link (ON DELETE SET NULL) rather than block the delete
+-- or cascade-delete the quantity. The link columns are already nullable.
+
+ALTER TABLE "productionQuantity"
+ DROP CONSTRAINT IF EXISTS "productionQuantity_setupProductionEventId_fkey";
+ALTER TABLE "productionQuantity"
+ ADD CONSTRAINT "productionQuantity_setupProductionEventId_fkey"
+ FOREIGN KEY ("setupProductionEventId") REFERENCES "productionEvent"("id")
+ ON DELETE SET NULL;
+
+ALTER TABLE "productionQuantity"
+ DROP CONSTRAINT IF EXISTS "productionQuantity_laborProductionEventId_fkey";
+ALTER TABLE "productionQuantity"
+ ADD CONSTRAINT "productionQuantity_laborProductionEventId_fkey"
+ FOREIGN KEY ("laborProductionEventId") REFERENCES "productionEvent"("id")
+ ON DELETE SET NULL;
+
+ALTER TABLE "productionQuantity"
+ DROP CONSTRAINT IF EXISTS "productionQuantity_machineProductionEventId_fkey";
+ALTER TABLE "productionQuantity"
+ ADD CONSTRAINT "productionQuantity_machineProductionEventId_fkey"
+ FOREIGN KEY ("machineProductionEventId") REFERENCES "productionEvent"("id")
+ ON DELETE SET NULL;
diff --git a/packages/database/supabase/migrations/20260702181547_intercompany-receivables-account-default.sql b/packages/database/supabase/migrations/20260702181547_intercompany-receivables-account-default.sql
new file mode 100644
index 0000000000..362c040170
--- /dev/null
+++ b/packages/database/supabase/migrations/20260702181547_intercompany-receivables-account-default.sql
@@ -0,0 +1,30 @@
+-- Intercompany invoices are booked to (and their payments must relieve) the
+-- Inter-Company Receivables control account. That account was resolved by
+-- looking it up by number ("1130") at posting time, which is fragile: account
+-- numbers and names are user-editable, so a rename silently mis-posts.
+--
+-- Store the account id on accountDefault instead (the same pattern used for
+-- receivablesAccount / payablesAccount), resolved once here from the seeded
+-- number and authoritative by id thereafter.
+
+ALTER TABLE "accountDefault"
+ ADD COLUMN IF NOT EXISTS "intercompanyReceivablesAccount" TEXT;
+
+ALTER TABLE "accountDefault"
+ DROP CONSTRAINT IF EXISTS "accountDefault_intercompanyReceivablesAccount_fkey";
+ALTER TABLE "accountDefault"
+ ADD CONSTRAINT "accountDefault_intercompanyReceivablesAccount_fkey"
+ FOREIGN KEY ("intercompanyReceivablesAccount") REFERENCES "account"("id")
+ ON UPDATE CASCADE ON DELETE RESTRICT;
+
+-- Backfill existing companies from the seeded Inter-Company Receivables account
+-- (number 1130 within the company's group). One-time resolution: from here the
+-- stored id survives number/name changes. Nullable — companies that don't use
+-- intercompany simply leave it unset and fall back to regular receivables.
+UPDATE "accountDefault" ad
+SET "intercompanyReceivablesAccount" = a."id"
+FROM "account" a
+JOIN "company" c ON c."companyGroupId" = a."companyGroupId"
+WHERE c."id" = ad."companyId"
+ AND a."number" = '1130'
+ AND ad."intercompanyReceivablesAccount" IS NULL;
diff --git a/packages/database/supabase/migrations/20260702192816_reparent-deferred-tax-expense-account.sql b/packages/database/supabase/migrations/20260702192816_reparent-deferred-tax-expense-account.sql
new file mode 100644
index 0000000000..9ecfe08b1c
--- /dev/null
+++ b/packages/database/supabase/migrations/20260702192816_reparent-deferred-tax-expense-account.sql
@@ -0,0 +1,25 @@
+-- 20260524143827_fixed-assets.sql seeded the "Deferred Tax Expense" (7090)
+-- account for existing company groups with its parent resolved by
+-- `number = '7000' AND "isGroup" = true`. Group header accounts carry NO
+-- number (number IS NULL; they are keyed by name, e.g. 'Other Expenses'), so
+-- that lookup returned NULL and 7090 was inserted orphaned — hanging at the
+-- root of the chart of accounts instead of under Other Expenses. New
+-- companies are unaffected (seed.data.ts parents it via parentKey).
+--
+-- Re-parent the orphaned rows to their group's "Other Expenses" header, the
+-- same parent seed.data.ts assigns. No-op where already parented or where a
+-- custom chart has no such group.
+
+UPDATE "account" a
+SET "parentId" = g."id"
+FROM "account" g
+WHERE a."parentId" IS NULL
+ AND a."isGroup" = FALSE
+ AND (
+ a."number" = '7090'
+ OR (a."name" = 'Deferred Tax Expense' AND a."createdBy" = 'system')
+ )
+ AND g."companyGroupId" = a."companyGroupId"
+ AND g."isGroup" = TRUE
+ AND g."name" = 'Other Expenses'
+ AND g."class" = 'Expense';
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 27f5ec23af..ec034d368c 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -5723,7 +5723,7 @@ msgid "If items already exist"
msgstr "Wenn Artikel bereits vorhanden sind"
msgid "If ordered, no stockout projected in the next 48 weeks"
-msgstr ""
+msgstr "Falls bestellt, kein Lagerbestand in den nächsten 48 Wochen prognostiziert"
msgid "If something is off track"
msgstr "Wenn etwas aus dem Ruder läuft"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 57fdff9607..096d22a7d3 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -5723,7 +5723,7 @@ msgid "If items already exist"
msgstr "Si los artículos ya existen"
msgid "If ordered, no stockout projected in the next 48 weeks"
-msgstr ""
+msgstr "Si se ordena, no se proyecta falta de existencias en las próximas 48 semanas"
msgid "If something is off track"
msgstr "Si algo se desvía del plan"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index d2645821e4..ddbe63ac45 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -5723,7 +5723,7 @@ msgid "If items already exist"
msgstr "Si des articles existent déjà"
msgid "If ordered, no stockout projected in the next 48 weeks"
-msgstr ""
+msgstr "Si commandé, aucune rupture de stock prévue au cours des 48 prochaines semaines"
msgid "If something is off track"
msgstr "Si quelque chose déraille"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 62f18e19e3..edda13afbb 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -5723,7 +5723,7 @@ msgid "If items already exist"
msgstr "अगर आइटम पहले से मौजूद हैं"
msgid "If ordered, no stockout projected in the next 48 weeks"
-msgstr ""
+msgstr "यदि ऑर्डर किया जाता है, तो अगले 48 सप्ताह में कोई स्टॉकआउट प्रक्षेपित नहीं है"
msgid "If something is off track"
msgstr "अगर कुछ गलत रास्ते पर है"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 3976330cc3..7df8313954 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -5723,7 +5723,7 @@ msgid "If items already exist"
msgstr "Se gli articoli esistono già"
msgid "If ordered, no stockout projected in the next 48 weeks"
-msgstr ""
+msgstr "Se ordinato, nessun esaurimento delle scorte previsto nelle prossime 48 settimane"
msgid "If something is off track"
msgstr "Se qualcosa non è in linea"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index c92291dae7..9e1eb7417f 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -5723,7 +5723,7 @@ msgid "If items already exist"
msgstr "アイテムが既に存在する場合"
msgid "If ordered, no stockout projected in the next 48 weeks"
-msgstr ""
+msgstr "注文した場合、今後48週間の在庫切れは予測されていません"
msgid "If something is off track"
msgstr "何か問題が生じた場合"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index c291355e1f..b32c103114 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -5723,7 +5723,7 @@ msgid "If items already exist"
msgstr "Jeśli elementy już istnieją"
msgid "If ordered, no stockout projected in the next 48 weeks"
-msgstr ""
+msgstr "Jeśli zamówione, brak prognozowanego braku zapasów w ciągu następnych 48 tygodni"
msgid "If something is off track"
msgstr "Jeśli coś nie przebiega prawidłowo"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 07e861afbe..e842ebd8de 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -5723,7 +5723,7 @@ msgid "If items already exist"
msgstr "Se os itens já existem"
msgid "If ordered, no stockout projected in the next 48 weeks"
-msgstr ""
+msgstr "Se encomendado, nenhuma falta de estoque projetada nas próximas 48 semanas"
msgid "If something is off track"
msgstr "Se algo estiver fora do caminho"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index aaf2a7f222..207e307627 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -5723,7 +5723,7 @@ msgid "If items already exist"
msgstr "Если элементы уже существуют"
msgid "If ordered, no stockout projected in the next 48 weeks"
-msgstr ""
+msgstr "Если заказано, дефицит не прогнозируется в течение следующих 48 недель"
msgid "If something is off track"
msgstr "Если что-то идет не по плану"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index d388ad8801..b9b3cc5f06 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -5723,7 +5723,7 @@ msgid "If items already exist"
msgstr "Eğer öğeler zaten varsa"
msgid "If ordered, no stockout projected in the next 48 weeks"
-msgstr ""
+msgstr "Sipariş verilirse, sonraki 48 hafta içinde stok tükenmesi öngörülmemektedir"
msgid "If something is off track"
msgstr "Bir şey yolunda değilse"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 1493353cf1..c75787a9bd 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -5723,7 +5723,7 @@ msgid "If items already exist"
msgstr "如果项目已存在"
msgid "If ordered, no stockout projected in the next 48 weeks"
-msgstr ""
+msgstr "如果下单,未来48周内预计不会缺货"
msgid "If something is off track"
msgstr "如果有什么偏离轨道"
diff --git a/packages/printing/src/ui/PrintButton.tsx b/packages/printing/src/ui/PrintButton.tsx
index 2f1e784f2a..fa6869efe6 100644
--- a/packages/printing/src/ui/PrintButton.tsx
+++ b/packages/printing/src/ui/PrintButton.tsx
@@ -10,6 +10,7 @@ import {
useDisclosure
} from "@carbon/react";
import { Trans } from "@lingui/react/macro";
+import type { ComponentProps } from "react";
import { useEffect, useState } from "react";
import { LuCheck, LuPrinter } from "react-icons/lu";
import { useFetcher } from "react-router";
@@ -29,7 +30,9 @@ export function PrintButton({
context,
workCenterId,
fileRoutes,
- disabled
+ disabled,
+ variant = "secondary",
+ size
}: {
sourceDocument: string;
sourceDocumentId: string;
@@ -38,6 +41,8 @@ export function PrintButton({
workCenterId?: string;
fileRoutes: FileRoutes;
disabled?: boolean;
+ variant?: ComponentProps<typeof Button>["variant"];
+ size?: ComponentProps<typeof Button>["size"];
}) {
const { printerRoutes, resolvePrinterRoute, printPath } = usePrinting();
const modal = useDisclosure();
@@ -93,7 +98,8 @@ export function PrintButton({
<>
<Button
leftIcon={<LuPrinter />}
- variant="secondary"
+ variant={variant}
+ size={size}
disabled={disabled}
onClick={handleClick}
>