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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(accounting): reclassify payment discounts as contra-revenue / contra-COGS (#1600)
Brad Barbincd6d8776247c
diff --git a/.ai/plans/2026-09-08-payment-discount-account-classification.md b/.ai/plans/2026-09-08-payment-discount-account-classification.mdnew file mode 100644index 0000000000..eebeb62682--- /dev/null+++ b/.ai/plans/2026-09-08-payment-discount-account-classification.md@@ -0,0 +1,336 @@+# Payment Discount Account Reclassification — implementation plan++**Spec:** .ai/specs/2026-09-08-payment-discount-account-classification.md+**Research:** .ai/research/customer-payment-discount-classification.md+**Run record:** .ai/runs/2026-09-08-payment-discount-classification.md+**Branch:** abuja++## Progress+- [x] Task 1: Move `accountTypeFromClass` to `lib/utils.ts`+- [x] Task 2: Make the payment discount line class-driven (`build-payment-journal.ts`)+- [x] Task 3: Pass the discount account's class from `post-payment/index.ts`+- [x] Task 4: Update / add `post-payment.test.ts` discount assertions+- [x] Task 5: Reclassify `7020`/`7030` in `seed.data.ts` (new companies)+- [x] Task 6: Forward migration reclassifying existing `7020`/`7030` rows+- [x] Task 7: Final verification gates++## Dependencies+- Task 2 depends on Task 1 (import of `accountTypeFromClass`).+- Task 3 depends on Task 2 (the new `discountAccountClass` field).+- Task 4 depends on Tasks 2–3.+- Tasks 5 and 6 are independent of 1–4 and of each other (data changes), but keep them after so the test suite is green first.+- Task 7 is last.++## Grounded facts (verified against code — do not re-derive)+- `account` table: PK is **`id` alone**; tenant column is **`companyGroupId`** (there is NO `companyId` on `account`). `number` is unique per `companyGroupId`. Parent linkage column is **`parentId`** (FK → `account(id)`). Group flag is **`isGroup` BOOLEAN**. Group rows have `number = NULL`, identified by `name` + `isGroup = TRUE`.+- Enums: `class` = `glAccountClass` ∈ {Asset,Liability,Equity,Revenue,Expense}; `accountType` = `accountType` (includes Income, Cost of Goods Sold, Expense, Other Expense, …); `incomeBalance` = `glIncomeBalance` ∈ {Balance Sheet, Income Statement}.+- Target rows: customer `7030` → `class='Revenue', accountType='Income', incomeBalance='Income Statement'`, parent group name `'Revenue'`. Supplier `7020` → `class='Expense', accountType='Cost of Goods Sold', incomeBalance='Income Statement'`, parent group name `'Cost of Goods Sold'`.+- `accountTypeFromClass` is defined at `post-memo/build-memo-journal.ts:34-49`, used only once (same file, line 147). `lib/utils.ts:126` already has a private `type AccountType = "asset"|"liability"|"equity"|"revenue"|"expense"`.+- `build-payment-journal.ts:235-248` discount line is hardcoded `pushLine(cashIn ? "debit" : "credit", "expense", ...)`. Balance (`signedDebitTotal`) is driven by SIDE, not `accountType` — so changing the abstract type does not unbalance the entry.+- `post-payment/index.ts:403-433` calls `buildPaymentJournal`; `accounts.discountAccountId` is `isAR ? ad.customerPaymentDiscountAccount : ad.supplierPaymentDiscountAccount`. It does NOT currently fetch any account `class`.+- `post-payment.test.ts`: `ACCOUNTS` constant (lines 20-26) is typed `PaymentJournalAccounts`; adding a REQUIRED field breaks it → the new field must be OPTIONAL. AR discount asserted at lines 158-161 (`amount === 10`) and 718; no `"Supplier Payment Discount"` assertion exists.+- Deno tests: run from `packages/database/supabase/functions/`, command `deno test --no-lock <file>` (task alias `deno task test`). No package.json/turbo wiring.+- `reset-chart-of-accounts.sql` (20260315000000) is applied on `main` — NEVER edit it; fix forward with a new migration.++---++## Task 1: Move `accountTypeFromClass` to `lib/utils.ts`++**Depends on:** none+**Files:**+- Modify: `packages/database/supabase/functions/lib/utils.ts` — add exported `accountTypeFromClass`+- Modify: `packages/database/supabase/functions/post-memo/build-memo-journal.ts` — delete the local definition, import from `lib/utils.ts`++**Steps:**+1. In `lib/utils.ts`, directly after the `debit`/`credit` block (after line 154), add:+ ```ts+ // glAccountClass (Asset|Liability|Equity|Revenue|Expense) → the lowercase+ // AccountType the debit/credit helpers expect. Shared by the payment and memo+ // journal builders so a line's natural-balance sign follows the account's class.+ export function accountTypeFromClass(glClass: string): AccountType {+ switch (glClass) {+ case "Asset":+ return "asset";+ case "Liability":+ return "liability";+ case "Equity":+ return "equity";+ case "Revenue":+ return "revenue";+ case "Expense":+ return "expense";+ default:+ throw new Error(`Unknown GL account class: ${glClass}`);+ }+ }+ ```+ Reuse the existing private `AccountType` at line 126 (do NOT declare a second one). The error string must remain exactly `Unknown GL account class: ${glClass}` — `post-memo.test.ts:91` asserts `"Unknown GL account class"`.+2. In `build-memo-journal.ts`: delete the local `accountTypeFromClass` (lines 34-49) and the now-unused local `type AccountType` at line 30 **only if** nothing else in the file uses it — check: `credit`/`debit` are imported from `lib/utils.ts`, so line 30's `AccountType` is likely only used by the deleted function. If line 30 `AccountType` is referenced elsewhere in the file, keep it. Update the import on line 31 from `import { credit, debit } from "../lib/utils.ts";` to `import { accountTypeFromClass, credit, debit } from "../lib/utils.ts";`.+3. If any other file imported `accountTypeFromClass` from `build-memo-journal.ts`, repoint it (grep confirmed none today, but re-check).++**Verify:**+```bash+cd packages/database/supabase/functions && deno test --no-lock post-memo/post-memo.test.ts+# Expected: all post-memo tests pass (ok). The "Unknown GL account class" throw case still passes.+grep -rn "accountTypeFromClass" packages/database/supabase/functions+# Expected: definition now in lib/utils.ts; imported+used in build-memo-journal.ts; used in build-payment-journal.ts after Task 2. No duplicate definition.+```++**Out of scope:** `credit`/`debit` bodies; any change to memo posting behavior.++---++## Task 2: Make the payment discount line class-driven++**Depends on:** Task 1+**Files:**+- Modify: `packages/database/supabase/functions/post-payment/build-payment-journal.ts`++**Steps:**+1. Add the import: change line 44 `import { credit, debit } from "../lib/utils.ts";` to `import { accountTypeFromClass, credit, debit } from "../lib/utils.ts";`.+2. In `interface PaymentJournalAccounts` (lines 73-79) add an **optional** field (optional so existing test literals still compile):+ ```ts+ // The discount account's glAccountClass. Drives the discount line's natural-+ // balance sign so a customer discount (Revenue) debits contra-revenue and a+ // supplier discount (Expense/COGS) credits contra-cost. Resolved by index.ts.+ discountAccountClass?: string | null;+ ```+3. Destructure it alongside the other accounts (lines 139-145): add `discountAccountClass,`.+4. In the discount block (lines 235-248), keep the side and magnitude exactly as-is; change only the abstract type. Replace:+ ```ts+ pushLine(cashIn ? "debit" : "credit", "expense", round(discount * invRate), {+ ```+ with:+ ```ts+ pushLine(+ cashIn ? "debit" : "credit",+ discountAccountClass ? accountTypeFromClass(discountAccountClass) : "expense",+ round(discount * invRate),+ {+ ```+ (Keep the closing `}`/`);` and the `accountId`/`description`/`documentLineReference` fields unchanged.) The `? … : "expense"` fallback preserves behavior for any caller that does not pass a class; `index.ts` (Task 3) always passes it in production.++**Verify:**+```bash+cd packages/database/supabase/functions && deno test --no-lock post-payment/post-payment.test.ts+# Expected AFTER this task alone: the AR-discount assertions FAIL (still expect 10) — that is corrected in Task 4. All non-discount cases pass and every case still balances.+```+If a test other than the AR-discount ones (lines 158-161, 718) fails, or any `signedDebitTotal` balance assertion fails, STOP and report — the change was meant to alter only the discount line's stored sign, not any balance.++**Out of scope:** write-off line, FX lines, bank/control lines — leave their hardcoded abstract types unchanged.++---++## Task 3: Resolve and pass the discount account's class from `index.ts`++**Depends on:** Task 2+**Files:**+- Modify: `packages/database/supabase/functions/post-payment/index.ts`++**Steps:**+1. Before the `buildPaymentJournal(...)` call (line 403), compute the selected discount account id and fetch its class. Insert:+ ```ts+ const discountAccountId = isAR+ ? ad.customerPaymentDiscountAccount+ : ad.supplierPaymentDiscountAccount;+ let discountAccountClass: string | null = null;+ if (discountAccountId) {+ const discountAccount = await client+ .from("account")+ .select("class")+ .eq("id", discountAccountId)+ .single();+ if (discountAccount.error || !discountAccount.data) {+ throw new Error("Failed to fetch the payment discount account class");+ }+ discountAccountClass = discountAccount.data.class as string;+ }+ ```+ Place this in the same `accountingEnabled` scope where `ad` (accountDefaults) is available and where `buildPaymentJournal` is called. If `ad` is not in scope at that point, resolve it the same way the surrounding code already reads `ad.customerPaymentDiscountAccount`.+2. In the `accounts` object passed to `buildPaymentJournal` (lines 421-431), replace the inline `discountAccountId: isAR ? ad.customerPaymentDiscountAccount : ad.supplierPaymentDiscountAccount,` with `discountAccountId,` (the const from step 1) and add `discountAccountClass,`.++ Note this mirrors `post-memo/index.ts:255-274`, which already fetches the reason account's `class` the same way.++**Verify:**+```bash+grep -n "discountAccountClass" packages/database/supabase/functions/post-payment/index.ts+# Expected: the const is resolved from a client.from("account").select("class") read and passed into the accounts object.+```+Full typecheck of the edge functions is not part of the ERP turbo graph; rely on Task 7's `generate:types` + the deno tests. If `client.from("account").select("class")` cannot resolve `.class` on the generated type, STOP and report (the column exists; a type miss would indicate a stale generated type).++**Out of scope:** changing how `controlAccountId`, write-off, or FX accounts are resolved.++---++## Task 4: Update and extend the payment discount tests++**Depends on:** Tasks 2, 3+**Files:**+- Modify: `packages/database/supabase/functions/post-payment/post-payment.test.ts`++**Steps:**+1. In the shared `ACCOUNTS` constant (lines 20-26) add `discountAccountClass: "Revenue",` (the customer/AR default; AP cases that need "Expense" override it locally in step 3). This keeps the common AR path exercising the contra-revenue sign.+2. Update the AR-discount case (the test titled `"AR discount: bank 90 / receivables 100 / discount expense 10"`, lines ~139-162):+ - Rename the title to `"AR discount: bank 90 / receivables 100 / discount contra-revenue -10"`.+ - Change the discount amount assertion from `assertEquals(discount.amount, 10);` to `assertEquals(discount.amount, -10); // debit to a Revenue-class account (contra-revenue)`.+ - Leave the `Bank / Cash` (90) and `Accounts Receivable` (-100) assertions unchanged, and keep any `balanced(signedDebitTotal)` assertion.+3. Update the combined AR case that asserts `Customer Payment Discount` at line ~718: change its expected amount from `10` to `-10`.+4. Add a NEW AP test proving the supplier contra-COGS direction (none exists today). Model it on the AP write-off case (lines ~187-208) but with a discount application and `discountAccountClass: "Expense"`:+ - Build an AP payment (`isAR: false, cashIn: false`) with one application having `discountAmount` (e.g. 10), `appliedAmount` such that cash balances, `targetExchangeRate: 1`.+ - Pass `accounts: { ...apBase().accounts, discountAccountClass: "Expense" }` (or set it on the AP fixture).+ - Assert `line(lines, "Supplier Payment Discount")!.amount === -10` (credit to an Expense/COGS account → `credit("expense",10) = -10`) and `line(...).accountId === "discount"`, plus `balanced(signedDebitTotal)`.+5. If the property `matrix` test (lines ~841-891) passes a discount without a class, it now falls through to the `"expense"` default and still balances — leave it, but if it began asserting a discount sign, update it to the class it supplies.++**Verify:**+```bash+cd packages/database/supabase/functions && deno test --no-lock post-payment/post-payment.test.ts+# Expected: ALL cases pass (ok), including the updated AR contra-revenue (-10) and the new AP contra-COGS (-10) discount assertions.+```+If any non-discount line's expected value had to change to make the suite pass, STOP and report — only the discount line's stored sign should have moved.++**Out of scope:** rewriting unrelated golden-master cases; changing write-off/FX expectations.++---++## Task 5: Reclassify `7020`/`7030` in the seed data (new companies)++**Depends on:** none+**Files:**+- Modify: `packages/database/supabase/functions/lib/seed.data.ts`++**Steps:**+1. Edit the `7030` record (line 763) from:+ ```ts+ { key: "7030", number: "7030", name: "Customer Payment Discounts", isGroup: false, parentKey: "other-expenses", accountType: "Other Expense", incomeBalance: "Income Statement", class: "Expense", consolidatedRate: "Average", createdBy: "system" },+ ```+ to (mirroring `4020` "Sales Discounts", line 709):+ ```ts+ { key: "7030", number: "7030", name: "Customer Payment Discounts", isGroup: false, parentKey: "revenue", accountType: "Income", incomeBalance: "Income Statement", class: "Revenue", consolidatedRate: "Average", createdBy: "system" },+ ```+2. Edit the `7020` record (line 762) from:+ ```ts+ { key: "7020", number: "7020", name: "Supplier Payment Discounts", isGroup: false, parentKey: "other-expenses", accountType: "Other Expense", incomeBalance: "Income Statement", class: "Expense", consolidatedRate: "Average", createdBy: "system" },+ ```+ to (joining the `cogs` group, lines 720-724):+ ```ts+ { key: "7020", number: "7020", name: "Supplier Payment Discounts", isGroup: false, parentKey: "cogs", accountType: "Cost of Goods Sold", incomeBalance: "Income Statement", class: "Expense", consolidatedRate: "Average", createdBy: "system" },+ ```+3. Do NOT change the `accountDefaults` mapping (lines 793-794): `supplierPaymentDiscountAccount: "7020"` and `customerPaymentDiscountAccount: "7030"` stay — they resolve by key to the same (now reclassified) accounts.++**Verify:**+```bash+grep -n '"7030"\|"7020"' packages/database/supabase/functions/lib/seed.data.ts+# Expected: 7030 now parentKey "revenue"/accountType "Income"/class "Revenue"; 7020 now parentKey "cogs"/accountType "Cost of Goods Sold"/class "Expense"; both still mapped in accountDefaults.+pnpm exec turbo run typecheck --filter=@carbon/database+# Expected: passes — the string literals are valid for the seed record type.+```+If the seed record type rejects `accountType: "Cost of Goods Sold"` or `parentKey: "cogs"`, STOP and report (the `cogs` group key and that accountType are used elsewhere in the same file, so this should type-check).++**Out of scope:** any other account row; the `accountDefaults` object; renumbering.++---++## Task 6: Forward migration reclassifying existing `7020`/`7030`++**Depends on:** none (independent data change)+**Files:**+- Create: `packages/database/supabase/migrations/{generated}_payment-discount-reclassification.sql`++**Steps:**+1. Create the migration file (do NOT hand-pick the timestamp; do NOT use `000000` for HHMMSS):+ ```bash+ pnpm db:migrate:new payment-discount-reclassification+ ```+2. Write idempotent UPDATEs scoped by `number` (unique per `companyGroupId`), resolving the parent group id per company group via a correlated subquery on the group row (`isGroup = TRUE`, matched by `name`). `account` has **no `companyId`** — its tenant column is `companyGroupId`. Use `COALESCE(subquery, a."parentId")` so a company group missing the target group keeps its current parent instead of being orphaned (belt-and-suspenders; all seeded charts have these groups).+ ```sql+ -- Reclassify the payment-discount accounts to their correct GL homes.+ -- Customer early-payment discount is contra-revenue (ASC 606 / IFRS 15);+ -- supplier discount taken is a reduction of cost of goods (contra-COGS).+ -- Going-forward only: posted journalLine history is intentionally NOT rewritten.+ -- Idempotent: fixed target state, safe to re-run.++ -- Customer Payment Discounts (7030) -> Revenue (contra-revenue), parent "Revenue"+ UPDATE "account" a SET+ "class" = 'Revenue',+ "accountType" = 'Income',+ "incomeBalance" = 'Income Statement',+ "parentId" = COALESCE(+ (SELECT g."id" FROM "account" g+ WHERE g."companyGroupId" = a."companyGroupId"+ AND g."isGroup" = TRUE+ AND g."name" = 'Revenue'+ LIMIT 1),+ a."parentId"+ )+ WHERE a."number" = '7030';++ -- Supplier Payment Discounts (7020) -> Expense/COGS (contra-cost), parent "Cost of Goods Sold"+ UPDATE "account" a SET+ "class" = 'Expense',+ "accountType" = 'Cost of Goods Sold',+ "incomeBalance" = 'Income Statement',+ "parentId" = COALESCE(+ (SELECT g."id" FROM "account" g+ WHERE g."companyGroupId" = a."companyGroupId"+ AND g."isGroup" = TRUE+ AND g."name" = 'Cost of Goods Sold'+ LIMIT 1),+ a."parentId"+ )+ WHERE a."number" = '7020';+ ```+3. Do NOT touch `accountDefault` — the reclassified rows keep their ids, so the `customerPaymentDiscountAccount` / `supplierPaymentDiscountAccount` FKs stay valid.+4. Do NOT edit `20260315000000_reset-chart-of-accounts.sql` (applied on `main`).++**Verify:**+```bash+# Static checks only — DB apply is the user's job (never rebuild the DB yourself).+test -f packages/database/supabase/migrations/*payment-discount-reclassification.sql && echo "migration file created"+grep -c "companyGroupId" packages/database/supabase/migrations/*payment-discount-reclassification.sql+# Expected: file exists; the UPDATEs scope the parent subquery by companyGroupId (not companyId).+```+If `enum glAccountClass`/`accountType` rejects any literal at apply time, STOP — but the literals (`'Revenue'`,`'Income'`,`'Cost of Goods Sold'`,`'Expense'`,`'Income Statement'`) were verified valid. Applying the migration (`pnpm db:migrate`) and confirming in the UI is left to the user.++**Out of scope:** rewriting `journalLine` history; renumbering; `accountDefault`; any other account row.++---++## Task 7: Final verification gates++**Depends on:** Tasks 1–6+**Files:** none (verification only)++**Steps + Verify:**+```bash+# 1) Regenerate types (no shape change expected — no schema/column change).+pnpm run generate:types+# Expected: completes; git diff on packages/database/src/types.ts is empty or trivial. If it changes account columns, STOP — this feature adds none.++# 2) Scoped typecheck (NEVER whole-repo).+pnpm exec turbo run typecheck --filter=@carbon/database+# Expected: passes.++# 3) Edge-function unit tests.+cd packages/database/supabase/functions && deno test --no-lock post-payment/post-payment.test.ts post-memo/post-memo.test.ts && cd -+# Expected: all pass (ok). If deno is not installed, report that these could not be run locally — do NOT mark the test criterion green.++# 4) Dataset drift gate (reads live schema; writes nothing).+pnpm db:check:datasets+# Expected: all four datasets still apply (or the "database unreachable/no users" warning-skip — report which).+```+- `pnpm db:migrate` / `db:check:backups` require applying the migration to the live DB — that is the **user's** step; note it in the handoff, do not run a DB rebuild.++**Out of scope:** committing (the /feature run stops at a gated PR; commit via /check-and-commit only when asked).++---++## Acceptance criteria coverage+- Spec AC "seed 7030/7020 reclassified" → Task 5.+- "new company shows accounts under Revenue / COGS" → Task 5 (+ user UI check after migrate).+- "migration reclassifies existing rows, defaults still resolve" → Task 6.+- "accountTypeFromClass in lib/utils.ts; both builders use it; post-memo unchanged" → Tasks 1, 2 (+ post-memo test in Task 1 verify).+- "unit test: customer discount debits Revenue-class, balances" → Task 4 step 2.+- "unit test: supplier discount credits Expense/COGS, balances" → Task 4 step 4.+- "golden-master permutations updated, all pass" → Task 4 + Task 7 step 3.+- "db:check:datasets passes" → Task 7 step 4.+- "db:check:backups gives a verdict" → user step (Task 7 note).diff --git a/.ai/playbooks/create-and-apply-payment.md b/.ai/playbooks/create-and-apply-payment.mdindex 2258a64a8e..08f5e5e788 100644--- a/.ai/playbooks/create-and-apply-payment.md+++ b/.ai/playbooks/create-and-apply-payment.md@@ -26,8 +26,28 @@ Routes: `/x/payment`, `/x/payment/new`, `/x/payment/$paymentId`### 2. Fill the New Payment form- Type / Customer-or-Supplier / Currency / Exchange Rate / Total Amount are pre-filled.- **Bank / Cash Account** (required) — select an Asset account (e.g. "1010 Bank - Cash").-- Submit "Save". On submit the action auto-creates a starter `paymentApplication`- against the seed invoice for the full amount, then redirects to the payment detail.+- Submit "Save". On submit the action seeds one `paymentApplication` per invoice; each+ is `appliedAmount = balance − earlyPaymentDiscount`, `discountAmount = discount`, so+ `applied + discount = balance` (settles the invoice without over-settling).+ Redirects to the payment detail.++### 2a. Early-payment discount (auto-seeded from payment terms)+- If the invoice's payment term has `discountPercentage > 0` AND the payment date is+ within the discount window (`daysDiscount` from the issue date, per `calculationMethod`),+ the seeded **Total Amount** is NET of the discount (e.g. a 1000 invoice on "1% 10 Net 30"+ paid within 10 days pre-fills **990**), and the seeded application carries+ `discountAmount` (10) with `appliedAmount` (990).+- Past the window, or a 0% term → discount 0, full balance (unchanged behavior).+- Verified 2026-09-09: `si_EvjaoySwgfqMtHn6JamGBy` ("1% 10 Net 30", issued today) → payment+ total 990, application applied 990 / discount 10; posts to a GL journal:+ `DR Bank 990 / DR Customer Payment Discount (4040 contra-revenue) −10 / CR AR −1000`;+ invoice → Paid. The discount line signs by the account's `class` (post-payment resolves it).+- Logic: `computeEarlyPaymentDiscounts` (`invoicing.service.ts`), called from+ `payments/new.tsx` loader (total) and action (applications).+- The apply table (`PaymentApplyTable`) disables **Save applications** when any row's+ `applied + discount + write-off > balance` ("A line settles more than its invoice's open+ balance") — mirrors the authoritative cap in `post-payment`, so a manual over-settling+ discount is caught before Post instead of erroring server-side.### 3. Post the payment- On `/x/payment/$paymentId`, click **Post** (Draft only). Calls the `post-payment`diff --git a/.ai/research/customer-payment-discount-classification.md b/.ai/research/customer-payment-discount-classification.mdnew file mode 100644index 0000000000..329af59f9e--- /dev/null+++ b/.ai/research/customer-payment-discount-classification.md@@ -0,0 +1,111 @@+# Customer Payment Discount Classification Research: Best Practices Survey++## Summary++Question: should Carbon's `customerPaymentDiscountAccount` (the GL account an early-payment cash discount given to a customer posts to, e.g. terms "2/10 net 30") be classified as an **expense** account (Carbon's current default) or as a **contra-revenue** account?++Findings: the authoritative accounting standards (ASC 606 / IFRS 15) treat a customer prompt-payment discount as a **reduction of the transaction price → contra-revenue, not an operating expense**. Modern SMB/mid-market ERPs (QuickBooks, NetSuite, Dynamics 365 Business Central) follow this and post the customer side to a revenue-reducing account. SAP is the notable outlier: its out-of-the-box automatic-posting default (OBXI / transaction key SKT, "Cash Discount Granted") books the granted discount to an **expense** account, configurable to a revenue GL. Carbon today matches the SAP default (seeds account `7030` as class `Expense`, `Other Expense`) — and, crucially, this **diverges from Carbon's own `salesDiscountAccount`** (`4020`, under revenue), which the customer credit-memo path already uses. The symmetric vendor discount is a reduction of cost/inventory (net method, preferred) or a purchase-discount contra-account under COGS (gross method) — never "other income," though QuickBooks and SAP's gross default both book it as income as a simplification.++## Competitors Surveyed++- **SAP S/4HANA (ECC + S/4HANA)** — enterprise reference for account-determination patterns; defaults customer cash discount to expense.+- **Oracle NetSuite** — mid-market ERP closest to Carbon's audience; contra-revenue on the customer side.+- **Microsoft Dynamics 365 Business Central** — SMB/mid-market ERP; posting-group-mapped, standard mapping is contra-revenue.+- **QuickBooks (Online + Desktop)** — SMB accounting baseline; explicitly an Income (contra-revenue) account.+- **Xero** — SMB accounting; no built-in feature, user-coded, common convention is contra-revenue.+- **ASC 606 / IFRS 15** — the authoritative standard both frameworks converge on.++## Key Consensus Patterns++### 1. Customer early-payment discount = reduction of revenue (contra-revenue)++- **ASC 606 / IFRS 15**: a prompt-payment/cash/settlement discount is **variable consideration** and reduces the transaction price (Step 3), estimated by expected value / most-likely amount subject to the revenue-reversal constraint. Also framed as "consideration payable to a customer" (ASC 606-10-32-25), a reduction of revenue unless it buys a distinct good/service. It is **not** an operating expense. Pre-606 US GAAP convention was the same *direction* — a contra-revenue "Sales Discounts" account offsetting gross sales.+- **QuickBooks**: auto-creates a "Discounts given" account and its guidance is explicit — "Sales discounts should be a reduction in income, not an expense." Discount items are assigned to an **Income** account.+- **NetSuite**: customer term-based discounts recognized at payment via an Accounting-Preferences discount account, designed as a **contra-revenue / reduction of income** account.+- **Dynamics 365 BC**: "Sales Pmt. Disc. Debit/Credit Acc." in General Posting Setup, standard mapping is a sales-discount / **contra-revenue** account.+- **SAP** *(outlier)*: OBXI / SKT "Cash Discount Granted" posts to an **expense** account by default (`Dr Bank` net + `Dr Cash Discount Granted (expense)` + `Cr Customer` gross). Can be re-pointed to a revenue GL, but the default and documentation frame it as expense.+- **Rationale**: giving a discount does not consume a resource (no expense is *incurred*); the customer simply pays less, so the revenue you recognize is lower. Booking it as expense overstates both gross revenue and operating expense and distorts gross margin.++### 2. Recognition timing: gross method, at payment time++- **SAP, NetSuite, BC** all default to the **gross method** — invoice booked at full value, discount recognized only when the early payment is applied inside the discount window. None default to the net method.+- **BC** additionally gates it on the "Adjust for Payment Disc." setting.+- ASC 606/IFRS 15's estimate-up-front model is conceptually closest to the *net* method, but in practice the gross method (recognize when taken) is near-universal in software and immaterial for most SMBs.+- **Carbon already matches this**: the discount is posted in `post-payment` at payment time, not at invoice time.++### 3. Vendor/purchase discount taken = reduction of cost, not income++- **ASC/GAAP preferred**: reduce cost of purchased goods / inventory (net method preferred; gross method accumulates a "Purchase Discounts" contra-account deducted from Purchases in COGS). Booking it as "other income" overstates both cost and income.+- **SAP**: OBXU / SKE "Cash Discount Received" — gross default posts to an **income** account; net procedure (doc type RN) credits the **cost/stock** account directly.+- **NetSuite**: a "Purchase Discount Account" that Oracle labels an **expense** account (functionally contra-expense).+- **QuickBooks**: recommends an **Income** account (a software simplification that diverges from the GAAP-preferred cost-reduction treatment).+- **Note for Carbon**: Carbon's `supplierPaymentDiscountAccount` is also seeded as `Expense`/`Other Expense` (`7020`) and `post-payment` **credits** it (reducing net expense). That is defensible as a contra-expense but is a separate question from the customer-side classification this research targets.++## Answers to Research Questions++1. **Contra-revenue or expense under ASC 606 / IFRS 15?** — Contra-revenue (reduction of the transaction price / variable consideration). Not an operating expense. (Deloitte, PwC, ACCA, IFRSbox.)+2. **SAP customer side** — Expense by default (OBXI / SKT, "Cash Discount Granted"), gross method. Configurable to a revenue GL.+3. **SAP vendor side** — Income by default (OBXU / SKE, gross); reduces cost/inventory under the net procedure (doc type RN).+4. **NetSuite** — Customer: contra-revenue (Accounting Preferences discount account). Vendor: "Purchase Discount Account" (expense/contra-expense). Gross method, payment-time.+5. **Dynamics BC** — User-mapped via General Posting Setup; standard = sales discount is contra-revenue, purchase discount is contra-cost/income. Gross method, gated on "Adjust for Payment Disc."+6. **QuickBooks** — Customer: Income (contra-revenue) account, explicitly. Vendor: recommends an Income account (simplification).+7. **Xero** — No built-in early-payment discount feature; user codes a discount line / credit note to a chart-of-accounts account. Common convention mirrors QB (contra-revenue on sales).++## Recommended Approach for Carbon++**Reclassify `customerPaymentDiscountAccount` to contra-revenue** (follow ASC 606 / IFRS 15, QuickBooks, NetSuite, and Dynamics BC — the SMB/mid-market consensus and Carbon's actual audience). The current `Expense`/`Other Expense` classification matches only the SAP default, which is the enterprise outlier.++Two implementation shapes to decide between during spec/design:++1. **Reclassify the seeded account** — move seeded account `7030` "Customer Payment Discounts" from `class: "Expense" / accountType: "Other Expense"` under `other-expenses` to a revenue-contra classification (mirroring `salesDiscountAccount` `4020` under sales/revenue), and flip the `post-payment` journal line from `accountType: "expense"` debit to the revenue-side treatment. Note the sign/side implications in `build-payment-journal.ts` and `lib/utils.ts`.+2. **Consolidate onto `salesDiscountAccount`** — Carbon *already* has a contra-revenue customer-discount account (`4020`) that the credit-memo path (`post-memo`) uses. The early-payment-discount path (`post-payment`) using a *different, expense-classified* account (`7030`) is an internal inconsistency: the same economic event (a customer discount) lands in two different P&L sections depending on whether it came through a memo or an early payment. Consolidating both onto `salesDiscountAccount` removes the divergence, but changes the account-defaults contract and the integration payload.++**Migration & compatibility notes** (for the spec — do not decide here):+- Existing companies have a live `accountDefault.customerPaymentDiscountAccount` FK, and historical journal lines are already posted against `7030`. A reclassification changes future postings and the account's P&L placement; it should not retroactively rewrite posted history.+- The account is pushed to accounting integrations (`integrations.$id.tsx`), so external-system mappings (Xero/QBO/Rillet sync) may need to move too.+- `db:check:datasets` / `db:check:backups` gates apply since this touches seed data and chart-of-accounts migrations.+- Whether to also revisit the symmetric `supplierPaymentDiscountAccount` (currently `Expense`, arguably should be contra-cost/COGS) is a related but separable scope decision.++## Sources++SAP:+- https://help.sap.com/doc/saphelp_ewm70/7.0/en-US/1e/70b6531de6b64ce10000000a174cb4/content.htm+- https://help.sap.com/docs/SUPPORT_CONTENT/fiaccounting/3361878894.html+- https://sap96.com/2024/09/04/configuration-for-cash-discount-granted-to-customer-obxi/+- https://sap96.com/2024/09/04/configuration-for-cash-discount-received-from-vendor-obxu/++NetSuite:+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2248474.html+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1387022.html+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_4702988229.html++Dynamics 365 Business Central:+- https://learn.microsoft.com/en-us/previous-versions/dynamicsnav-2016/hh171792(v=nav.90)+- https://learn.microsoft.com/en-us/training/modules/customer-discounts-dynamics-365-business-central/7-summary++QuickBooks:+- https://quickbooks.intuit.com/learn-support/en-us/reports-and-accounting/how-to-catagorize-a-customer-discount-income-or-expense/00/1352577+- https://quickbooks.intuit.com/learn-support/en-us/payments/vendor-early-payment-discounts/00/823701++Xero:+- https://productideas.xero.com/forums/967115-invoices-quotes/suggestions/44960470-invoice-prompt-payment-settlement-discount+- https://www.paidnice.com/blog/apply-early-payment-discounts-xero++ASC 606 / IFRS 15:+- https://dart.deloitte.com/USDART/home/codification/revenue/asc606-10/roadmap-revenue-recognition/chapter-6-step-3-determine-transaction/6-6-consideration-payable-a-customer+- https://viewpoint.pwc.com/dt/us/en/fasb_financial_accou/trg_revenue/trg_revenue_US/consideration_payabl__3_US.html+- https://www.cpdbox.com/033-settlement-discounts-ifrs-15/+- https://www.accaglobal.com/africa/en/student/exam-support-resources/fundamentals-exams-study-resources/f3/technical-articles/discounts.html++Purchase discounts (net vs gross):+- https://www.accountinghub-online.com/accounting-for-purchase-discounts/+- https://legalclarity.org/purchase-discount-accounting-gross-vs-net-method/++## Carbon codebase grounding (current state)++- Column defined `accountDefault.customerPaymentDiscountAccount` — `migrations/20230820020844_posting-groups.sql:30`; FK re-pointed to `account(id)` in `20260315000000_reset-chart-of-accounts.sql:415-416`.+- Seeded as **class `Expense`, `Other Expense`, under `other-expenses`**: account `7030` "Customer Payment Discounts" — `functions/lib/seed.data.ts:763`; `reset-chart-of-accounts.sql:278`. Default mapping `customerPaymentDiscountAccount → "7030"` at `seed.data.ts:794`.+- Posted at **payment time** as `DR expense`: `post-payment/build-payment-journal.ts:235-248` (`pushLine(cashIn ? "debit" : "credit", "expense", ...)`); account selected at `post-payment/index.ts:421-431`. Entry: `DR Bank (net) + DR Customer Payment Discount (expense) + CR AR (gross)`.+- **Divergence**: the contra-revenue `salesDiscountAccount` (`4020`, under revenue) is what the customer **credit-memo** path uses — `post-memo/index.ts:241-250`. `customerPaymentDiscountAccount` is not referenced in `post-memo`.+- Symmetric `supplierPaymentDiscountAccount` (`7020`) also seeded `Expense`/`Other Expense`; `post-payment` credits it (reduces cost); also used as the supplier memo reason account in `post-memo`.+- Exposed to accounting integrations: `apps/erp/app/routes/x+/settings+/integrations.$id.tsx:773,782,807-808`.diff --git a/.ai/runs/2026-09-08-payment-discount-classification.md b/.ai/runs/2026-09-08-payment-discount-classification.mdnew file mode 100644index 0000000000..6cec42e758--- /dev/null+++ b/.ai/runs/2026-09-08-payment-discount-classification.md@@ -0,0 +1,43 @@+# Feature run: Reclassify payment discount accounts (customer contra-revenue, supplier contra-cost)++- Date: 2026-09-08+- Mode: fully-autonomous+- Request: "should we change customerPaymentDiscountAccount from an expense account to a contra revenue account?" → move forward as a feature. Cleanest structure, going-forward only (existing accounts/journals are throwaway test data — no back-compat migration for posted history). Include the supplier side. Keep both as dedicated accounts (reclassify, don't consolidate onto salesDiscountAccount).+- Phase plan: research [skip — done, .ai/research/customer-payment-discount-classification.md] · spec [run — crosses accounting + integrations + seed/chart-of-accounts; GL posting logic] · plan [run] · execute [run] · test [skip — user chose unit-tests-only; journal correctness verified via unit tests on build-payment-journal + db:check:datasets, no browser e2e] · self-review [run]++## Decisions+- Design shape (pre-spec, delegated by user "do the cleanest thing"): reclassify both dedicated accounts rather than consolidate. customerPaymentDiscountAccount → contra-revenue (kept distinct from salesDiscountAccount 4020); supplierPaymentDiscountAccount → contra-cost/COGS reduction. Rationale: symmetric with the supplier side (which stays a dedicated account), resolves the memo(4020)-vs-payment(7030) divergence by making both customer paths contra-revenue, and preserves the dedicated early-payment-discount reporting line that SAP/NetSuite/BC all keep. — 2026-09-08+- Going-forward only for POSTED JOURNAL HISTORY: no migration rewrites already-posted journal lines. — 2026-09-08+- (User follow-up 2026-09-08) DO write a migration that updates the EXISTING chart-of-accounts rows (7030, 7020) classification and the default-account mappings, so existing companies' charts are corrected — not only new-company seed data. Posted journal history still untouched. — 2026-09-08++## Autonomous spec resolutions (reviewed by human at PR, not mid-loop)+- Q1 classification: 7030 → class Revenue / accountType Income / parent `revenue` (mirror 4020 Sales Discounts). 7020 → class Expense / accountType "Cost of Goods Sold" / parent `cogs` (contra-COGS). Keep numbers 7020/7030 and names. — codebase precedent (4020) + research.+- Q1b renumbering to 4xxx/5xxx: DECLINED (out of scope). Numbers are labels; renumbering ripples into seed keys + integration mappings for cosmetic gain, and reclassify-in-place keeps accountDefault FK-by-id intact (no remap). Recorded as considered-and-declined.+- Q2 post-payment sign: adopt post-memo's class-driven pattern. index.ts resolves the selected discount account's `class`; builder uses accountTypeFromClass(class) for the discount line instead of hardcoded "expense". SIDE unchanged (balance uses side, not accountType, so journal stays balanced). Move accountTypeFromClass from build-memo-journal.ts → lib/utils.ts; import in both builders. Root-cause fix, not a second hardcode.+- Q3 post-memo: NO code change — already resolves reason-account class dynamically (index.ts:255-274). Reclassifying 7020 flows through automatically.+- Q4 lib/utils.ts debit/credit: unchanged; already handle revenue+expense. Only which abstract type the discount line uses changes (now class-derived).+- Q5 migration: new migration (reset-chart-of-accounts.sql is applied — never edit) UPDATEs account rows per company matched by number IN ('7020','7030'), setting class/accountType/incomeBalance/parentId (resolve new parent group id via name+isGroup subquery). Idempotent (fixed target state). accountDefault NOT remapped (same rows). Also edit seed.data.ts 7020/7030 records for new companies. Gates: db:migrate, generate:types, db:check:datasets, db:check:backups.+- Q6 (surfaced while grounding) integration sync payload (integrations.$id.tsx): unaffected — mapping is by account id, which does not change. No code change; verify in execute.+- Q7 (surfaced) companies that CUSTOMIZED 7020/7030 or repointed the default: out of scope — user confirmed existing accounting is throwaway test data; migration matches by number 7020/7030. Documented limitation.+- Plan gate (🛑) auto-approved (autonomous mode): plan is grounded in verified account schema (companyGroupId tenant col, parentId/isGroup, enum values), covers every spec AC, uses only scoped typecheck, and leaves DB apply to the user. No human blocker. — 2026-09-08++## Phase log+- research: complete — .ai/research/customer-payment-discount-classification.md (SAP/NetSuite/BC/QuickBooks/Xero + ASC 606/IFRS 15; codebase grounding)+- spec: complete — .ai/specs/2026-09-08-payment-discount-account-classification.md (all OQs resolved autonomously; spec gate passed)+- plan: complete — .ai/plans/2026-09-08-payment-discount-account-classification.md (7 tasks; verified account schema uses companyGroupId not companyId, parentId/isGroup, enum values)+- execute: complete — all 7 tasks. Edge-function tests 41 passed (34 post-payment incl. new AP contra-COGS + flipped AR contra-revenue; 7 post-memo). deno check on changed files: 0 new errors (only 6 pre-existing postgres/index.ts env errors). @carbon/database typecheck green. Migration 20260909014032 created. Verification deviations: (a) deno test run with --no-check due to a pre-existing typecheck failure in the unmodified lib/postgres/index.ts; (b) db:check:datasets + generate:types + db:migrate + db:check:backups are DB-dependent and the local stack is down → USER STEP (migration makes no schema change, so generate:types is a no-op). NOT committed (per no-auto-commit; feature stops at gated PR).+- self-review: complete — no Must-fix. Risks: silent "expense" fallback if a caller omits class; confirm sync/reports read the flipped AR discount line by natural balance (runtime); DB gates still need local run; deno test used --no-check for a pre-existing postgres/index.ts typecheck failure. Suggestions: throw when discount>0 but no class; sync supplier default too. Docs: nothing stale; optional lessons entry + move spec to implemented/ on merge.++## Follow-up (2026-09-08, after user screenshot)+- UI fix: AccountDefaultsForm "Customer Payment Discounts" field badgeType "Expense" → "Revenue". badgeType drives both the class badge AND the account-picker filter (accountOptions[badgeType], filtered by account.class), so with the account reclassified to Revenue the Expense-filtered picker went empty (user's screenshot). Supplier stays "Expense" (7020 is still class Expense/COGS). One-line change; type-safe ("Revenue" already used by 5 other fields). Spec UI Changes section corrected (was wrongly "None"). Branch is now `customer-payment-discount-account`.++## Follow-up 2 (2026-09-08, renumber): reclass + renumber into correct blocks+- User: a Revenue/COGS account shouldn't keep a 7xxx number. Renumbered 7030→4040 (Revenue block) and 7020→5080 (COGS block).+- KEY FINDING: a fresh `crbn reset` seeds the chart from seed.data.ts via bootstrap.ts (path b), NOT from reset-chart-of-accounts.sql's DO block — on a wiped reset there are zero companyGroups when migrations run, so that DO block inserts nothing. So seed.data.ts is the authoritative edit for reset; editing the old reset-chart migration is inert AND a never-edit violation → left untouched.+- Edits: (1) seed.data.ts — moved the two records into the revenue/cogs blocks, renumbered 4040/5080 (key==number kept for the seed-company subsidiary path which keys its id-map by number), updated accountDefaults mapping to 4040/5080. (2) forward migration 20260909014032 — folded renumber into the existing reclassify UPDATEs (SET number + class/type/parent), matched by OLD number, idempotent, COALESCE parent guard, scoped by companyGroupId; accountDefault untouched (FK by id survives renumber). (3) reset-chart-of-accounts.sql — NOT edited.+- Verified: no 7020/7030 refs remain anywhere in source (only the migration's WHERE on old numbers + comments); @carbon/database typecheck green; 4040/5080 confirmed free in both seed + reset-chart. Edge-function posting code unaffected (keys off account id/class, not number) — no test change. AccountDefaultsForm badgeType fix (customer→Revenue) from follow-up 1 still correct.+- Spec updated (target table, design-decision row reversed, data-model, ACs, OQs, changelog).+- STILL NOT applied/committed. User to `crbn reset` (fresh dev company gets 4040/5080 from seed.data.ts) or `pnpm db:migrate` on an existing DB (renumber migration runs).++## Outcome+- Feature implemented on branch `customer-payment-discount-account` (uncommitted, per no-auto-commit). 6 source files + 1 migration (20260909014032) + .ai research/spec/plan/run. Edge-function tests 41 passed. NOT committed — feature run stops at a gated PR; awaiting user to commit (via /check-and-commit) and run the DB-dependent gates (pnpm db:migrate, db:check:datasets, db:check:backups).diff --git a/.ai/specs/2026-09-08-payment-discount-account-classification.md b/.ai/specs/2026-09-08-payment-discount-account-classification.mdnew file mode 100644index 0000000000..9116c8dbee--- /dev/null+++ b/.ai/specs/2026-09-08-payment-discount-account-classification.md@@ -0,0 +1,305 @@+# Payment Discount Account Reclassification (Customer → Contra-Revenue, Supplier → Contra-COGS)++> Status: draft+> Author: Claude (autonomous /feature run, for Brad)+> Date: 2026-09-08++## TLDR++Carbon posts early-payment cash discounts to two GL accounts — `customerPaymentDiscountAccount`+(seeded `7030`) and `supplierPaymentDiscountAccount` (seeded `7020`) — both classified as+`Expense` / `Other Expense`. That is wrong under ASC 606 / IFRS 15 and out of step with+QuickBooks, NetSuite, and Dynamics 365 BC: a **customer** early-payment discount is a reduction+of the transaction price (**contra-revenue**), and a **supplier** discount taken is a reduction+of the cost of goods (**contra-COGS**), never an operating expense. It is also internally+inconsistent — customer *credit memos* already post to the contra-revenue `salesDiscountAccount`+(`4020`), so the same economic event (a customer discount) lands in two different P&L sections+depending on whether it came via a memo or an early payment.++This spec reclassifies both accounts to their correct GL homes (customer → `Revenue`, supplier →+`Cost of Goods Sold`), keeping them as dedicated accounts (not consolidated onto `4020`). It+fixes the seed data for new companies **and** migrates existing companies' chart rows. The+posting code is made class-driven (mirroring the already-correct `post-memo`) so a journal+line's natural-balance sign follows the account's actual `class` instead of a hardcoded literal.+Posted journal *history* is not rewritten.++Research: `.ai/research/customer-payment-discount-classification.md`.++## Problem Statement++`packages/database/supabase/functions/lib/seed.data.ts:762-763` seeds:++- `7020` "Supplier Payment Discounts" — `class: Expense`, `accountType: Other Expense`, parent `other-expenses`+- `7030` "Customer Payment Discounts" — `class: Expense`, `accountType: Other Expense`, parent `other-expenses`++At payment time (`post-payment/build-payment-journal.ts:235-248`) the discount line is pushed+with a hardcoded abstract type `"expense"`:++```ts+pushLine(cashIn ? "debit" : "credit", "expense", round(discount * invRate), { accountId: discountAccountId, ... })+```++So a customer taking an early-payment discount produces `DR Bank (net) + DR "Customer Payment+Discount" (expense) + CR AR (gross)` — booking the forgone amount as an **operating expense**.++Three things are wrong:++1. **Standard.** ASC 606 / IFRS 15 treat a prompt-payment discount as variable consideration —+ a reduction of the transaction price, i.e. **contra-revenue**. Not an expense. (Deloitte, PwC,+ ACCA, IFRSbox — see research.)+2. **Peers.** QuickBooks ("Sales discounts should be a reduction in income, not an expense"),+ NetSuite, and Dynamics 365 BC all post the customer side to a revenue-reducing account. Only+ SAP defaults to expense, and it is the enterprise outlier. Carbon matches only SAP.+3. **Internal inconsistency.** Customer credit memos post to `salesDiscountAccount` (`4020`,+ `class: Revenue`, parent `revenue`) via `post-memo/index.ts:241-243`. The early-payment path+ uses the expense-classed `7030`. The same event is split across two P&L sections.++Supplier symmetry: `supplierPaymentDiscountAccount` (`7020`) is also `Expense`. A vendor discount+taken is a **reduction of cost of goods** (GAAP-preferred: net method / reduction of+inventory-COGS; gross method: a purchase-discount contra-account under COGS). It is used by both+`post-payment` (AP branch, `cashIn=false` → credits the account) and `post-memo` (supplier reason+account).++## Proposed Solution++Reclassify both accounts to their correct GL homes, keep them dedicated, and make the payment+posting class-driven. No new tables, no schema changes — this is chart-of-accounts *data* plus a+one-line-shaped posting fix.++### Target classification (reclassify AND renumber)++The accounts are both reclassified and **renumbered** into their correct blocks — a `7xxx`+"Other Expenses" number is wrong for a Revenue/COGS account (the number is the reader's first+signal of where an account lives). Renumber is safe here: `accountDefault` stores the account+**id** (not the number), so the default mappings travel automatically; `key` is kept equal to+`number` so the `seed-company` subsidiary path (which keys its id-map by `number`) stays correct.++| Account | Old → New number/Name | class | accountType | incomeBalance | parent group |+|---|---|---|---|---|---|+| Customer payment discount | `7030` → **`4040`** "Customer Payment Discounts" | `Revenue` | `Income` | `Income Statement` | `revenue` |+| Supplier payment discount | `7020` → **`5080`** "Supplier Payment Discounts" | `Expense` | `Cost of Goods Sold` | `Income Statement` | `cogs` |++Customer target mirrors the existing `4020` "Sales Discounts" exactly (`seed.data.ts`). `4040` is+the next free number in the Revenue block (`4010/4020/4030`); `5080` is the next free number in+the COGS block (`5010/5050/5060/5070`) — both verified free in `seed.data.ts` and the reset-chart+migration.+Supplier target joins the `cogs` group (`seed.data.ts:720-724`), whose accountType is already+`Cost of Goods Sold` / class `Expense`.++### Why the journal stays balanced with only a sign change++`build-payment-journal.ts` tracks the debit/credit balance via `signedDebitTotal`, which is driven+by the line **side** (`side === "debit" ? +magnitude : -magnitude`, line 169) — *not* by the+abstract `accountType`. The `accountType` only sets the stored `amount`'s natural-balance sign via+`debit`/`credit` in `lib/utils.ts` (`debit("expense")=+amt`, `debit("revenue")=-amt`). So:++- **Customer (AR)**: keep the line a **debit** (a debit to a revenue account = contra-revenue),+ change its abstract type `expense → revenue`. `signedDebitTotal` contribution is unchanged →+ the journal still balances. Stored `amount` flips from `+discount` to `-discount` (natural+ credit-balance account debited), which is the correct contra-revenue representation.+- **Supplier (AP)**: the line is a **credit**; a contra-COGS account is still `Expense` natural+ balance, so the abstract type stays `expense`. `credit("expense") = -amount` unchanged. No sign+ change at all — only the chart classification moves.++### Class-driven posting (root-cause fix, mirrors post-memo)++Rather than replacing the hardcoded `"expense"` with a second hardcode (`isAR ? "revenue" :+"expense"`), adopt the pattern `post-memo` already uses: derive the abstract type from the+account's real `class`. `post-memo/index.ts:255-274` resolves the reason account's `class` and+passes `reasonAccountClass` into `buildMemoJournal`, which maps it via the exported+`accountTypeFromClass(glClass)` helper (`build-memo-journal.ts:35-52`). This is why **post-memo+needs zero change** — reclassifying `7020` flows through automatically.++Apply the same to payments:++1. Move `accountTypeFromClass` from `post-memo/build-memo-journal.ts` to `lib/utils.ts` (next to+ `debit`/`credit`); re-export or import it in `build-memo-journal.ts` so nothing else breaks.+2. `post-payment/index.ts`: resolve the `class` of the selected discount account (the one chosen+ at lines 423-425) with a single `client.from("account").select("class").eq("id", …).single()`,+ and pass it into `buildPaymentJournal` as `accounts.discountAccountClass`.+3. `build-payment-journal.ts`: the discount line uses+ `accountTypeFromClass(discountAccountClass)` instead of the literal `"expense"`. Keep the side+ (`cashIn ? "debit" : "credit"`) exactly as-is.++This removes the hardcoded assumption entirely, so the sign follows the chart even if a company+later repoints the default at a differently-classed account — the same robustness `post-memo`+already has. `write-off` and `FX` lines are left as-is: they are out of scope for this feature and+their seeded defaults (`6320` expense / `4130` revenue / `7060` loss / `4120` gain) already match+their hardcoded types.++### Design Decisions++| Decision | Choice | Rationale |+|----------|--------|-----------|+| Customer classification | `class: Revenue`, `accountType: Income`, parent `revenue` | Contra-revenue per ASC 606/IFRS 15 + QB/NetSuite/BC; mirrors existing `4020` |+| Supplier classification | `class: Expense`, `accountType: Cost of Goods Sold`, parent `cogs` | Reduction of cost of goods (net-method direction), not other income/expense |+| Reclassify vs consolidate | Keep `7030` distinct from `4020`; keep `7020` dedicated | User decision; matches SAP/NetSuite/BC keeping a dedicated cash-discount line for reporting |+| Renumber 7020/7030 → 4040/5080 | **Yes** (reversed after user review) | A `7xxx` number for a Revenue/COGS account is misleading. `accountDefault` stores the account **id**, so renumbering doesn't remap defaults; `key` is kept == `number` so the `seed-company` subsidiary path (id-map keyed by number) stays correct. Applied in `seed.data.ts` (fresh) + the forward migration (existing DBs) |+| Posting sign source | Class-driven via `accountTypeFromClass` (not a 2nd hardcode) | Root-cause fix; mirrors the already-correct `post-memo`; robust to reconfiguration |+| `post-memo` changes | None | Already class-driven; supplier reclassification flows through |+| Existing companies | Migrate chart rows via UPDATE | User asked for a migration; existing accounting is throwaway test data |+| Posted journal history | Not rewritten | Going-forward correctness only; historical lines keep their original account/sign |+| Heuristic 1-7 (new tables/services/RLS/forms) | N/A | No new table, service, route, form, or RLS — data + edge-function posting logic only |++## Data Model Changes++No schema changes (no new columns, tables, or types). Two data changes:++### 1. Seed data (new companies) — `seed.data.ts` — the authoritative source for a fresh `crbn reset`++**This is the change that actually takes effect on `crbn reset`.** On a volume-wiped reset there+are zero `companyGroup` rows when migrations run, so `reset-chart-of-accounts.sql`'s `DO` block+inserts nothing; the dev company's chart is seeded *afterward* from `seed.data.ts` via+`bootstrap.ts` (and the `seed-company` edge function for onboarding). So the seed file — not the+migration — is what a fresh reset reads.++- Move the two account records out of the `7000` "Other Expenses" block into their proper blocks,+ renumbered: `4040` "Customer Payment Discounts" after `4030` (Revenue), `5080` "Supplier Payment+ Discounts" after `5070` (COGS). `key` == `number` on both.+- Update the `accountDefaults` mapping: `customerPaymentDiscountAccount → "4040"`,+ `supplierPaymentDiscountAccount → "5080"` (it maps by account `key`).++### 2. Forward migration (existing / cloud companies)++Only relevant for databases already seeded with `7020`/`7030` (cloud, or a dev DB not reset). On a+fresh `crbn reset` this migration is inert (no accounts exist when it runs). `reset-chart-of-accounts.sql`+(`20260315000000`) is applied on `main` and is NOT edited — retro-editing it is both a never-edit+violation and inert on a fresh reset. Fix forward with `20260909014032_payment-discount-reclassification.sql`.++Per company group, `UPDATE "account"` matched by the OLD `number`, setting **`number`** (renumber),+`class`, `accountType`, `incomeBalance`, and `parentId`. The `account` table is scoped by+**`companyGroupId`** (no `companyId`); the parent group id is resolved via a correlated subquery on+the group row (`isGroup = TRUE`, matched by `name`), wrapped in `COALESCE(subquery, a."parentId")`+so a group missing the target parent keeps its current one rather than orphaning. `accountDefault`+is untouched — it stores the account **id**, which the renumber preserves.++```sql+-- Customer: 7030 → 4040, Revenue, parent "Revenue"+UPDATE "account" a SET+ "number" = '4040', "class" = 'Revenue', "accountType" = 'Income',+ "incomeBalance" = 'Income Statement',+ "parentId" = COALESCE((SELECT g."id" FROM "account" g+ WHERE g."companyGroupId" = a."companyGroupId" AND g."isGroup" = TRUE AND g."name" = 'Revenue' LIMIT 1), a."parentId")+WHERE a."number" = '7030';++-- Supplier: 7020 → 5080, Expense/COGS, parent "Cost of Goods Sold"+UPDATE "account" a SET+ "number" = '5080', "class" = 'Expense', "accountType" = 'Cost of Goods Sold',+ "incomeBalance" = 'Income Statement',+ "parentId" = COALESCE((SELECT g."id" FROM "account" g+ WHERE g."companyGroupId" = a."companyGroupId" AND g."isGroup" = TRUE AND g."name" = 'Cost of Goods Sold' LIMIT 1), a."parentId")+WHERE a."number" = '7020';+```++Idempotent: matched by the OLD number, so once renumbered the `WHERE` no-ops. Verified against the+live schema: `account.number`, `class` (enum `glAccountClass`), `accountType` (enum `accountType`,+includes `Income`/`Cost of Goods Sold`), `parentId` (FK → `account.id`), `isGroup`, `companyGroupId`.++**Collision safety** (CodeRabbit review): `number` is UNIQUE per `companyGroupId`, and a company+group could already hold a custom `4040`/`5080` account. So the reclassification (class /+accountType / incomeBalance / parent — none unique-constrained) is applied UNCONDITIONALLY by the+old number, and the **renumber is a separate `UPDATE` guarded by `NOT EXISTS (… target number in+this group)`**. A group with a conflicting custom account keeps its `7030`/`7020` number but is+still correctly reclassified, instead of the whole migration aborting on the unique constraint and+leaving every tenant unmigrated (the deploy runner would retry-fail forever).++**`accountDefault` is not touched** — the reclassified rows keep their ids, so the existing+`customerPaymentDiscountAccount` / `supplierPaymentDiscountAccount` FKs remain valid.++## API / Service Changes++Edge functions only (no ERP service/model changes):++- `packages/database/supabase/functions/lib/utils.ts` — add `accountTypeFromClass(glClass)`+ (moved from `build-memo-journal.ts`).+- `packages/database/supabase/functions/post-memo/build-memo-journal.ts` — import+ `accountTypeFromClass` from `lib/utils.ts` (or keep a re-export) instead of defining it.+- `packages/database/supabase/functions/post-payment/build-payment-journal.ts` — add+ `discountAccountClass` to `PaymentJournalAccounts`; use `accountTypeFromClass(discountAccountClass)`+ for the discount line in place of `"expense"`.+- `packages/database/supabase/functions/post-payment/index.ts` — resolve the selected discount+ account's `class` and pass it as `accounts.discountAccountClass`.++## UI Changes++**Account Defaults form** (`AccountDefaultsForm.tsx`): the "Customer Payment Discounts" field's+`badgeType` changes `"Expense" → "Revenue"`. `badgeType` drives BOTH the row's class badge and the+account-picker options (`options={accountOptions[field.badgeType]}`, where `accountOptions` filters+by `account.class`). With `badgeType: "Expense"` the picker only lists class=Expense accounts, so+after 7030 is reclassified to Revenue the picker is empty and the saved value can't render — this+was missed in the original "UI Changes: None" (the self-review overlooked the badge=class coupling).+The **supplier** field stays `"Expense"`: 7020 remains class Expense (COGS), so it still resolves.+Same one-property pattern already used by `assetGainOnDisposalAccount` (`badgeType: "Revenue"`).++The accounting integration sync payload (`integrations.$id.tsx:773-808`) is unaffected — it maps by+account id, which does not change.++## Acceptance Criteria++- [ ] `seed.data.ts` seeds `4040` "Customer Payment Discounts" (`class: Revenue / accountType:+ Income / parent: revenue`) and `5080` "Supplier Payment Discounts" (`class: Expense /+ accountType: Cost of Goods Sold / parent: cogs`); no `7020`/`7030` remain; `accountDefaults`+ maps `customerPaymentDiscountAccount → "4040"`, `supplierPaymentDiscountAccount → "5080"`.+- [ ] A new company (fresh `crbn reset`) shows "Customer Payment Discounts" numbered **4040 under+ Revenue** and "Supplier Payment Discounts" numbered **5080 under Cost of Goods Sold** in the+ chart of accounts, and the Account Defaults screen resolves both pickers.+- [ ] The forward migration renumbers + reclassifies existing companies' `7030→4040` / `7020→5080`+ rows, and the `customerPaymentDiscountAccount`/`supplierPaymentDiscountAccount` defaults still+ resolve (FK by id survives the renumber).+- [ ] `accountTypeFromClass` lives in `lib/utils.ts`; `build-memo-journal.ts` and+ `build-payment-journal.ts` both use it; `post-memo` behavior is byte-for-byte unchanged+ (its golden-master test still passes).+- [ ] Unit test: posting a **customer** early-payment discount emits the discount line as a+ **debit to a Revenue-class account** (stored `amount` negative), the entry balances+ (`signedDebitTotal ≈ 0`), and `assertBalanced` passes.+- [ ] Unit test: posting a **supplier** early-payment discount emits the discount line as a+ **credit to an Expense-class (COGS) account**, entry balances.+- [ ] Existing `post-payment.test.ts` golden-master permutations updated for the new discount+ sign and still pass (`deno test`); all non-discount lines byte-identical.+- [ ] `pnpm db:check:datasets` passes (all four datasets still apply).+- [ ] `pnpm db:check:backups` gives a verdict (no schema-shape change).++## Risks++| Risk | Severity | Mitigation |+|------|----------|------------|+| Golden-master payment tests break on the sign flip | Med (expected) | Intentional; update expected fixtures for the discount line only, assert every other line is unchanged |+| Migration parent/column-name assumption wrong (`parentId`/`isGroup`) | Med | Verify against live `account` schema in the plan before finalizing SQL; the UPDATE is a no-op if the WHERE/subquery misses |+| A company customized `7020`/`7030` or repointed the default | Low | User confirmed existing accounting is throwaway test data; number-match is scoped and documented (see Open Questions Q7) |+| Reports/aggregations assume the discount amount's old sign | Low | Sign is natural-balance-consistent with the new class; anything summing by account class stays correct. `get_job_quantity_on_hand` etc. don't read these accounts |+| Accounting sync pushes stale classification to Xero/QBO | Low | Sync maps by account id, unchanged; classification is Carbon-internal. Verify payload in execute |++## Open Questions++> All resolved autonomously (fully-autonomous /feature run). Human reviews at the PR.++- [x] Customer classification (parent/accountType) — **Autonomous:** `Revenue`/`Income`/parent+ `revenue`, mirroring `4020`. Contra-revenue per ASC 606/IFRS 15 + peer consensus.+- [x] Supplier classification — **Autonomous:** `Expense`/`Cost of Goods Sold`/parent `cogs`.+ Reduction of cost of goods, not other income/expense.+- [x] Renumber vs reclassify-in-place — **RESOLVED WITH USER (reversed):** renumber `7030→4040`+ (Revenue block) and `7020→5080` (COGS block). A `7xxx` number for a Revenue/COGS account is+ misleading; safe because `accountDefault` stores the account id (not number) and `key` is+ kept == `number` for the subsidiary seed path. Applied in `seed.data.ts` + the forward migration.+- [x] post-payment sign mechanism — **Autonomous:** class-driven via `accountTypeFromClass`+ (mirror `post-memo`), not a second hardcode. Side unchanged → journal stays balanced.+- [x] post-memo changes — **Autonomous:** none; already class-driven.+- [x] Migration approach — **RESOLVED WITH USER:** the fresh-`crbn reset` chart comes from+ `seed.data.ts` via `bootstrap.ts`, NOT the reset-chart migration (no company groups exist at+ migration time on a wiped reset) — so `seed.data.ts` is the authoritative edit; the forward+ migration `20260909014032` (renumber + reclassify by old number) covers existing/cloud DBs;+ `reset-chart-of-accounts.sql` is left untouched (applied + inert on reset).+- [x] Companies that customized `7020`/`7030` or repointed the default — **Autonomous:** out of+ scope (throwaway test data); migration matches by old number. Documented limitation.++## Changelog++- 2026-09-08: Created. All open questions resolved autonomously as part of a fully-autonomous+ /feature run (research → spec). Design grounded in `build-payment-journal.ts`,+ `build-memo-journal.ts`, `post-payment/index.ts`, `post-memo/index.ts`, `lib/utils.ts`, and+ `seed.data.ts`.+- 2026-09-08 (user review): (1) Added the Account Defaults UI change (customer field+ `badgeType: "Revenue"` — the picker filters by `badgeType === account.class`, previously "None").+ (2) Reversed the renumber decision: renumber `7030→4040` (Revenue) and `7020→5080` (COGS), applied+ in `seed.data.ts` (authoritative for a fresh `crbn reset` — chart seeds from `bootstrap.ts`, not+ the reset-chart migration) and folded into the forward migration for existing DBs.diff --git a/apps/erp/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsx b/apps/erp/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsxindex 765c96ef7f..2498a8c3dd 100644--- a/apps/erp/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsx+++ b/apps/erp/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsx@@ -287,6 +287,13 @@ const AccountDefaultsForm = ({badgeType: "Revenue",termId: "account-default-sales-discounts"},+ {+ name: "customerPaymentDiscountAccount",+ label: t`Customer Payment Discounts`,+ description: t`Discounts given to customers for early payment`,+ badgeType: "Revenue",+ termId: "account-default-customer-payment-discounts"+ },{name: "realizedExchangeGainAccount",label: t`Realized Exchange Gain`,@@ -313,6 +320,13 @@ const AccountDefaultsForm = ({description: t`Expense account for non-inventory purchases (services, supplies)`,badgeType: "Expense",termId: "account-default-indirect-materials-services"+ },+ {+ name: "supplierPaymentDiscountAccount",+ label: t`Supplier Payment Discounts`,+ description: t`Discounts earned for early payment to suppliers`,+ badgeType: "Expense",+ termId: "account-default-supplier-payment-discounts"}]},@@ -446,20 +460,6 @@ const AccountDefaultsForm = ({badgeType: "Expense",termId: "account-default-interest"},- {- name: "supplierPaymentDiscountAccount",- label: t`Supplier Payment Discounts`,- description: t`Discounts earned for early payment to suppliers`,- badgeType: "Expense",- termId: "account-default-supplier-payment-discounts"- },- {- name: "customerPaymentDiscountAccount",- label: t`Customer Payment Discounts`,- description: t`Discounts given to customers for early payment`,- badgeType: "Expense",- termId: "account-default-customer-payment-discounts"- },{name: "roundingAccount",label: t`Rounding Account`,diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.tsindex d226f23554..7b31b79190 100644--- a/apps/erp/app/modules/invoicing/invoicing.service.ts+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts@@ -1,7 +1,7 @@import type { Database, Json } from "@carbon/database";import { getCompanyTimeZone } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";-import { datetime, EPSILON, round } from "@carbon/utils";+import { applyRate, datetime, EPSILON, round } from "@carbon/utils";import { endOfMonth, parseDate } from "@internationalized/date";import type { SupabaseClient } from "@supabase/supabase-js";import type { z } from "zod";@@ -128,6 +128,109 @@ export async function computeInvoiceDateDue(}}+/**+ * Early-payment (cash) discount per invoice, for seeding a payment's+ * applications. A discount only applies when the payment lands within the+ * term's discount window (e.g. "2/10 net 30" → 2% only if paid within 10 days+ * of the issue date). Returns a Map keyed by invoice id; invoices with no term,+ * a zero discount percentage, a missing issue date, or a payment date past the+ * window map to 0.+ *+ * The discount is a settlement amount, so it rounds to the currency's decimals+ * via `applyRate` (`discountPercentage` is stored as points, e.g. 2 → 0.02).+ * The deadline uses the same calculationMethod anchoring as the due date (see+ * computeInvoiceDateDue) but with `daysDiscount` instead of `daysDue`. Terms are+ * batch-loaded in one query — never per invoice (N+1).+ */+export async function computeEarlyPaymentDiscounts(+ client: SupabaseClient<Database>,+ args: {+ companyId: string;+ asOfDate: string;+ currencyDecimals: number;+ invoices: {+ id: string;+ balance: number;+ dateIssued: string | null;+ paymentTermId: string | null;+ }[];+ }+): Promise<Map<string, number>> {+ const { companyId, asOfDate, currencyDecimals, invoices } = args;+ const result = new Map<string, number>(invoices.map((inv) => [inv.id, 0]));++ const termIds = [+ ...new Set(+ invoices+ .map((inv) => inv.paymentTermId)+ .filter((id): id is string => Boolean(id))+ )+ ];+ if (termIds.length === 0) return result;++ const terms = await client+ .from("paymentTerm")+ .select("id, daysDiscount, discountPercentage, calculationMethod")+ .in("id", termIds)+ .eq("companyId", companyId);+ if (terms.error) {+ throw new Error(+ `Failed to load payment terms while computing early-payment discounts: ${terms.error.message}`+ );+ }+ const termById = new Map((terms.data ?? []).map((term) => [term.id, term]));++ let asOf: ReturnType<typeof parseDate>;+ try {+ asOf = parseDate(asOfDate);+ } catch {+ return result;+ }++ for (const inv of invoices) {+ if (!inv.paymentTermId || !inv.dateIssued) continue;+ const term = termById.get(inv.paymentTermId);+ if (!term) continue;+ const pct = Number(term.discountPercentage ?? 0);+ const days = Number(term.daysDiscount ?? 0);+ if (pct <= 0) continue;++ let issued: ReturnType<typeof parseDate>;+ try {+ issued = parseDate(inv.dateIssued);+ } catch {+ continue;+ }++ let deadline: ReturnType<typeof parseDate>;+ switch (term.calculationMethod) {+ case "End of Month":+ deadline = endOfMonth(issued).add({ days });+ break;+ case "Day of Month": {+ const sameMonth = issued.set({ day: days });+ deadline =+ sameMonth.compare(issued) >= 0+ ? sameMonth+ : issued.add({ months: 1 }).set({ day: days });+ break;+ }+ default:+ deadline = issued.add({ days });+ }++ // Past the discount window → the early-payment discount is no longer offered.+ if (asOf.compare(deadline) > 0) continue;++ result.set(+ inv.id,+ applyRate(Number(inv.balance), pct / 100, currencyDecimals)+ );+ }++ return result;+}+export async function createPurchaseInvoiceFromPurchaseOrder(client: SupabaseClient<Database>,purchaseOrderId: string,@@ -1587,7 +1690,7 @@ export async function getOpenSalesInvoicesForCustomer(return client.from("salesInvoices").select(- "id, invoiceId, dateDue, currencyCode, exchangeRate, totalAmount, balance, status"+ "id, invoiceId, dateIssued, dateDue, paymentTermId, currencyCode, exchangeRate, totalAmount, balance, status").eq("companyId", companyId).eq("customerId", customerId)@@ -1604,7 +1707,7 @@ export async function getOpenPurchaseInvoicesForSupplier(return client.from("purchaseInvoices").select(- "id, invoiceId, dateDue, currencyCode, exchangeRate, totalAmount, balance, status"+ "id, invoiceId, dateIssued, dateDue, paymentTermId, currencyCode, exchangeRate, totalAmount, balance, status").eq("companyId", companyId).eq("supplierId", supplierId)diff --git a/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.tsx b/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.tsxindex b2e4f8d0d9..8aa1db4251 100644--- a/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.tsx+++ b/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.tsx@@ -177,6 +177,20 @@ const PaymentApplyTable = ({// coarser than the 1e-5 the values carry, and let a real over-application of// 0.0001 through.const overApplied = totalCash > maxApplicable + EPSILON;+ // A row can't settle more than the invoice's open balance+ // (applied + discount + write-off). Mirrors the authoritative cap in the+ // post-payment edge function, so a manual discount that over-settles is caught+ // here — before Post — instead of failing server-side.+ const overSettled = useMemo(+ () =>+ rows.some(+ (r) =>+ r.checked &&+ round(r.appliedAmount + r.discountAmount + r.writeOffAmount) >+ r.balance + EPSILON+ ),+ [rows]+ );const appliedPct =paymentTotal > 0? Math.min(100, Math.max(0, (totalCash / paymentTotal) * 100))@@ -469,7 +483,13 @@ const PaymentApplyTable = ({) : null}<HStack className="justify-between w-full"><span className="text-sm">- {overApplied ? (+ {overSettled ? (+ <span className="font-semibold text-destructive">+ <Trans>+ A line settles more than its invoice's open balance+ </Trans>+ </span>+ ) : overApplied ? (<span className="font-semibold text-destructive"><Trans>Over-applied by</Trans>{" "}{currencyFormatter.format(totalCash - maxApplicable)}@@ -495,7 +515,7 @@ const PaymentApplyTable = ({leftIcon={<LuSave />}onClick={onSave}isLoading={isSaving}- isDisabled={!canEdit || overApplied}+ isDisabled={!canEdit || overApplied || overSettled}><Trans>Save applications</Trans></Button>diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.jsonindex 7a3b901e24..dc00c0b8f2 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json@@ -1,5 +1,5 @@{- "totalTools": 1494,+ "totalTools": 1495,"modules": 15,"tools": [{"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId","permission":"none"},@@ -293,6 +293,7 @@{"name":"inventory_upsertWarehouseTransfer","classification":"WRITE","paramCount":9,"schema":"893e85262ecf","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update"},{"name":"inventory_upsertWarehouseTransferLine","classification":"WRITE","paramCount":1,"schema":"93538fae689b","response":"237082879d41","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update"},{"name":"invoicing_applyCreditsToInvoices","classification":"DESTRUCTIVE","paramCount":4,"schema":"a9944c8799d0","response":"none","injectAuth":"companyId","permission":"invoicing:update"},+ {"name":"invoicing_computeEarlyPaymentDiscounts","classification":"READ","paramCount":3,"schema":"0069677fb034","response":"d8bb760d2850","injectAuth":"companyId","permission":"invoicing:view"},{"name":"invoicing_computeInvoiceDateDue","classification":"READ","paramCount":2,"schema":"c07433aded5b","response":"174e29b899b9","injectAuth":"companyId","permission":"invoicing:view"},{"name":"invoicing_createPurchaseInvoiceFromPurchaseOrder","classification":"WRITE","paramCount":1,"schema":"28cffcd9d6e8","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create"},{"name":"invoicing_createSalesInvoiceFromSalesOrder","classification":"WRITE","paramCount":1,"schema":"d160a49d6787","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"invoicing:create"},@@ -318,8 +319,8 @@{"name":"invoicing_getMemo","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"ee27f56e2f82","injectAuth":"companyId","permission":"invoicing:view"},{"name":"invoicing_getMemoApplications","classification":"READ","paramCount":1,"schema":"188417093a55","response":"667060f6a7e4","injectAuth":"companyId","permission":"invoicing:view"},{"name":"invoicing_getMemos","classification":"READ","paramCount":6,"schema":"b120ea106813","response":"4b05f5647015","injectAuth":"companyId","permission":"invoicing:view"},- {"name":"invoicing_getOpenPurchaseInvoicesForSupplier","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"1e5e706e6a7c","injectAuth":"companyId","permission":"invoicing:view"},- {"name":"invoicing_getOpenSalesInvoicesForCustomer","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"1e5e706e6a7c","injectAuth":"companyId","permission":"invoicing:view"},+ {"name":"invoicing_getOpenPurchaseInvoicesForSupplier","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"1c5bb161d464","injectAuth":"companyId","permission":"invoicing:view"},+ {"name":"invoicing_getOpenSalesInvoicesForCustomer","classification":"READ","paramCount":1,"schema":"09e48c79fb16","response":"1c5bb161d464","injectAuth":"companyId","permission":"invoicing:view"},{"name":"invoicing_getPayment","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"dcd7a2b028c7","injectAuth":"companyId","permission":"invoicing:view"},{"name":"invoicing_getPayments","classification":"READ","paramCount":8,"schema":"8294255666da","response":"cb3415df82d8","injectAuth":"companyId","permission":"invoicing:view"},{"name":"invoicing_getPurchaseInvoice","classification":"READ","paramCount":1,"schema":"9fcbb4e4e012","response":"8af6fcfff1cc","injectAuth":"companyId","permission":"invoicing:view"},diff --git a/apps/erp/app/routes/x+/payments+/new.tsx b/apps/erp/app/routes/x+/payments+/new.tsxindex 715299a1c8..1567fef08b 100644--- a/apps/erp/app/routes/x+/payments+/new.tsx+++ b/apps/erp/app/routes/x+/payments+/new.tsx@@ -3,12 +3,13 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import type { Database } from "@carbon/database";import { validationError, validator } from "@carbon/form";-import { datetime } from "@carbon/utils";+import { datetime, round } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { redirect, useLoaderData } from "react-router";-import { getDefaultAccounts } from "~/modules/accounting";+import { getCurrencyByCode, getDefaultAccounts } from "~/modules/accounting";import {+ computeEarlyPaymentDiscounts,getOpenPurchaseInvoicesForSupplier,getOpenSalesInvoicesForCustomer,PaymentForm,@@ -37,6 +38,44 @@ async function getSeedableOpenInvoices(return res.data ?? [];}+// Resolve the payment currency's decimals, then the early-payment discount per+// invoice as of `asOfDate`. Returns an all-zero map (no discount) when the+// currency can't be resolved, so a missing currency never blocks seeding.+async function getSeededDiscounts(+ client: SupabaseClient<Database>,+ companyId: string,+ companyGroupId: string,+ currencyCode: string,+ asOfDate: string,+ invoices: {+ id?: string | null;+ balance?: number | null;+ dateIssued?: string | null;+ paymentTermId?: string | null;+ }[]+): Promise<Map<string, number>> {+ const currency = await getCurrencyByCode(+ client,+ companyGroupId,+ currencyCode+ );+ const currencyDecimals = currency.data?.decimalPlaces;+ if (currencyDecimals == null) {+ return new Map(invoices.map((inv) => [inv.id ?? "", 0]));+ }+ return computeEarlyPaymentDiscounts(client, {+ companyId,+ asOfDate,+ currencyDecimals,+ invoices: invoices.map((inv) => ({+ id: inv.id ?? "",+ balance: Number(inv.balance ?? 0),+ dateIssued: inv.dateIssued ?? null,+ paymentTermId: inv.paymentTermId ?? null+ }))+ });+}+// Loader pre-fills the form. Query params:// customerId -> seeds counterparty + paymentType=Receipt// supplierId -> seeds counterparty + paymentType=Disbursement@@ -44,9 +83,12 @@ async function getSeedableOpenInvoices(// and (on submit) one application is seeded per invoice// amount -> fallback total when no invoiceId is suppliedexport async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- create: "invoicing"- });+ const { client, companyId, companyGroupId } = await requirePermissions(+ request,+ {+ create: "invoicing"+ }+ );const url = new URL(request.url);const customerId = url.searchParams.get("customerId");@@ -69,8 +111,14 @@ export async function loader({ request }: LoaderFunctionArgs) {let exchangeRate = 1;let totalAmount = amount ? Number(amount) : 0;+ const paymentDate = datetime+ .today(await getCompanyTimeZone(client, companyId))+ .toString();+// When seeded from invoices, the total and currency come from the invoices- // themselves (authoritative), not the URL amount.+ // themselves (authoritative), not the URL amount. The seeded total is NET of+ // any early-payment discount the invoice's terms grant as of the payment date,+ // so a "2/10 net 30" invoice paid today pre-fills the discounted cash amount.if (invoiceIds.length > 0 && partyId) {const open = await getSeedableOpenInvoices(client,@@ -82,8 +130,18 @@ export async function loader({ request }: LoaderFunctionArgs) {if (selected.length > 0) {currencyCode = selected[0].currencyCode ?? currencyCode;exchangeRate = Number(selected[0].exchangeRate ?? 1);+ const discounts = await getSeededDiscounts(+ client,+ companyId,+ companyGroupId,+ currencyCode,+ paymentDate,+ selected+ );totalAmount = selected.reduce(- (sum, inv) => sum + Number(inv.balance ?? 0),+ (sum, inv) =>+ sum ++ round(Number(inv.balance ?? 0) - (discounts.get(inv.id ?? "") ?? 0)),0);}@@ -95,9 +153,7 @@ export async function loader({ request }: LoaderFunctionArgs) {paymentType,customerId: customerId ?? "",supplierId: supplierId ?? "",- paymentDate: datetime- .today(await getCompanyTimeZone(client, companyId))- .toString(),+ paymentDate,currencyCode,exchangeRate,totalAmount,@@ -111,9 +167,10 @@ export async function loader({ request }: LoaderFunctionArgs) {export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);- const { client, companyId, userId } = await requirePermissions(request, {- create: "invoicing"- });+ const { client, companyId, companyGroupId, userId } =+ await requirePermissions(request, {+ create: "invoicing"+ });const formData = await request.formData();// Hidden field set by the loader so the action can seed applications without@@ -144,8 +201,58 @@ export async function action({ request }: ActionFunctionArgs) {// branch must omit it so the table's xid() default generates the id.const { id: _omitId, ...paymentData } = validation.data;+ // Resolve the seeded invoices + their early-payment discounts (as of the chosen+ // payment date) BEFORE inserting, so the payment's cash total is derived from+ // the SAME discounts the applications carry (applied + discount = balance).+ // The loader's total is computed for today; recomputing here keeps the total in+ // step when the user changed the payment date before submitting.+ const isReceipt = validation.data.paymentType === "Receipt";+ const seedPartyId = isReceipt+ ? validation.data.customerId+ : validation.data.supplierId;+ let seededInvoices: Awaited<ReturnType<typeof getSeedableOpenInvoices>> = [];+ let seededDiscounts = new Map<string, number>();+ if (seedInvoiceIds.length > 0 && seedPartyId) {+ const open = await getSeedableOpenInvoices(+ client,+ companyId,+ validation.data.paymentType,+ seedPartyId+ );+ seededInvoices = open.filter((inv) =>+ seedInvoiceIds.includes(inv.id ?? "")+ );+ if (seededInvoices.length > 0) {+ seededDiscounts = await getSeededDiscounts(+ client,+ companyId,+ companyGroupId,+ validation.data.currencyCode,+ validation.data.paymentDate,+ seededInvoices+ );+ }+ }+ const seededTotal =+ seededInvoices.length > 0+ ? round(+ seededInvoices.reduce(+ (sum, inv) =>+ sum ++ round(+ Number(inv.balance ?? 0) -+ (seededDiscounts.get(inv.id ?? "") ?? 0)+ ),+ 0+ )+ )+ : null;+const insert = await upsertPayment(client, {...paymentData,+ // Seeded-from-invoice payments take their cash total from the invoices+ // (net of discount), authoritative over the form's pre-filled amount.+ totalAmount: seededTotal ?? paymentData.totalAmount,paymentId,companyId,createdBy: userId,@@ -158,45 +265,32 @@ export async function action({ request }: ActionFunctionArgs) {);}- // Seed one application per selected invoice for its full open balance. Each- // invoice's balance + rate are re-fetched server-side so the seed always- // reflects the current books. The user can still adjust via the apply table.- if (seedInvoiceIds.length > 0) {- const isReceipt = validation.data.paymentType === "Receipt";- const partyId = isReceipt- ? validation.data.customerId- : validation.data.supplierId;+ // Seed one application per selected invoice: appliedAmount = balance − discount+ // and discountAmount = discount, so applied + discount = balance (settles the+ // invoice in full without over-settling). The user can still adjust via the+ // apply table.+ if (seededInvoices.length > 0) {try {- const open = partyId- ? await getSeedableOpenInvoices(- client,- companyId,- validation.data.paymentType,- partyId- )- : [];- const selected = open.filter((inv) =>- seedInvoiceIds.includes(inv.id ?? "")- );- if (selected.length > 0) {- await replaceInvoiceSettlements(getDatabaseClient(), {- paymentId: insert.data.id,- companyId,- createdBy: userId,- applications: selected.map((inv) => ({+ await replaceInvoiceSettlements(getDatabaseClient(), {+ paymentId: insert.data.id,+ companyId,+ createdBy: userId,+ applications: seededInvoices.map((inv) => {+ const discount = seededDiscounts.get(inv.id ?? "") ?? 0;+ return {targetSalesInvoiceId: isReceipt ? (inv.id ?? undefined) : undefined,targetPurchaseInvoiceId: isReceipt? undefined: (inv.id ?? undefined),- appliedAmount: Number(inv.balance ?? 0),- discountAmount: 0,+ appliedAmount: round(Number(inv.balance ?? 0) - discount),+ discountAmount: discount,writeOffAmount: 0,targetExchangeRate: Number(inv.exchangeRate ?? 1),sourceExchangeRate: Number(validation.data.exchangeRate) || 1,appliedDate: validation.data.paymentDate- }))- });- }+ };+ })+ });} catch (e) {// The payment was created (a Draft with no applications is valid), but// seeding failed. Send the user to the detail page to apply manually.diff --git a/packages/database/supabase/functions/lib/seed.data.ts b/packages/database/supabase/functions/lib/seed.data.tsindex 4369b52eb1..3a3460d8b7 100644--- a/packages/database/supabase/functions/lib/seed.data.ts+++ b/packages/database/supabase/functions/lib/seed.data.ts@@ -708,6 +708,7 @@ export const accounts = [{ key: "4010", number: "4010", name: "Sales", isGroup: false, parentKey: "revenue", accountType: "Income", incomeBalance: "Income Statement", class: "Revenue", consolidatedRate: "Average", createdBy: "system" },{ key: "4020", number: "4020", name: "Sales Discounts", isGroup: false, parentKey: "revenue", accountType: "Income", incomeBalance: "Income Statement", class: "Revenue", consolidatedRate: "Average", createdBy: "system" },{ key: "4030", number: "4030", name: "Manufacturing Services Revenue", isGroup: false, parentKey: "revenue", accountType: "Income", incomeBalance: "Income Statement", class: "Revenue", consolidatedRate: "Average", createdBy: "system" },+ { key: "4040", number: "4040", name: "Customer Payment Discounts", isGroup: false, parentKey: "revenue", accountType: "Income", incomeBalance: "Income Statement", class: "Revenue", consolidatedRate: "Average", createdBy: "system" },// Other Income{ key: "other-income", number: null, name: "Other Income", isGroup: true, parentKey: "income-statement", accountType: "Other Income", incomeBalance: "Income Statement", class: "Revenue", consolidatedRate: "Average", createdBy: "system" },@@ -722,6 +723,7 @@ export const accounts = [{ key: "5050", number: "5050", name: "Indirect Materials & Services", isGroup: false, parentKey: "cogs", accountType: "Cost of Goods Sold", incomeBalance: "Income Statement", class: "Expense", consolidatedRate: "Average", createdBy: "system" },{ key: "5060", number: "5060", name: "Labor & Machine Absorption", isGroup: false, parentKey: "cogs", accountType: "Cost of Goods Sold", incomeBalance: "Income Statement", class: "Expense", consolidatedRate: "Average", createdBy: "system" },{ key: "5070", number: "5070", name: "Overhead Absorption", isGroup: false, parentKey: "cogs", accountType: "Cost of Goods Sold", incomeBalance: "Income Statement", class: "Expense", consolidatedRate: "Average", createdBy: "system" },+ { key: "5080", number: "5080", name: "Supplier Payment Discounts", isGroup: false, parentKey: "cogs", accountType: "Cost of Goods Sold", incomeBalance: "Income Statement", class: "Expense", consolidatedRate: "Average", createdBy: "system" },// Variances{ key: "variances", number: null, name: "Variances", isGroup: true, parentKey: "cogs", accountType: "Expense", incomeBalance: "Income Statement", class: "Expense", consolidatedRate: "Average", createdBy: "system" },@@ -759,8 +761,6 @@ export const accounts = [// ─── 7000-7999: OTHER / NON-OPERATING EXPENSES ───{ key: "other-expenses", number: null, name: "Other Expenses", isGroup: true, parentKey: "income-statement", accountType: "Other Expense", incomeBalance: "Income Statement", class: "Expense", consolidatedRate: "Average", createdBy: "system" },{ key: "7010", number: "7010", name: "Interest Expense", isGroup: false, parentKey: "other-expenses", accountType: "Other Expense", incomeBalance: "Income Statement", class: "Expense", consolidatedRate: "Average", createdBy: "system" },- { key: "7020", number: "7020", name: "Supplier Payment Discounts", isGroup: false, parentKey: "other-expenses", accountType: "Other Expense", incomeBalance: "Income Statement", class: "Expense", consolidatedRate: "Average", createdBy: "system" },- { key: "7030", number: "7030", name: "Customer Payment Discounts", isGroup: false, parentKey: "other-expenses", accountType: "Other Expense", incomeBalance: "Income Statement", class: "Expense", consolidatedRate: "Average", createdBy: "system" },{ key: "7040", number: "7040", name: "Service Charge Account", isGroup: false, parentKey: "other-expenses", accountType: "Other Expense", incomeBalance: "Income Statement", class: "Expense", consolidatedRate: "Average", createdBy: "system" },{ key: "7050", number: "7050", name: "Rounding Account", isGroup: false, parentKey: "other-expenses", accountType: "Other Expense", incomeBalance: "Income Statement", class: "Expense", consolidatedRate: "Average", createdBy: "system" },{ key: "7060", number: "7060", name: "Foreign Exchange Losses", isGroup: false, parentKey: "other-expenses", accountType: "Other Expense", incomeBalance: "Income Statement", class: "Expense", consolidatedRate: "Average", createdBy: "system" },@@ -790,8 +790,8 @@ export const accountDefaults = {assetLossOnDisposalAccount: "6320",serviceChargeAccount: "7040",interestAccount: "7010",- supplierPaymentDiscountAccount: "7020",- customerPaymentDiscountAccount: "7030",+ supplierPaymentDiscountAccount: "5080",+ customerPaymentDiscountAccount: "4040",roundingAccount: "7050",assetAquisitionCostAccount: "1310",assetAquisitionCostOnDisposalAccount: "1320",diff --git a/packages/database/supabase/functions/lib/utils.ts b/packages/database/supabase/functions/lib/utils.tsindex 0be961bf07..0e808eb6c4 100644--- a/packages/database/supabase/functions/lib/utils.ts+++ b/packages/database/supabase/functions/lib/utils.ts@@ -153,6 +153,26 @@ export const debit = (accountType: AccountType, amount: number) => {}};+// glAccountClass (Asset|Liability|Equity|Revenue|Expense) → the lowercase+// AccountType the debit/credit helpers expect. Shared by the payment and memo+// journal builders so a line's natural-balance sign follows the account's class.+export const accountTypeFromClass = (glClass: string): AccountType => {+ switch (glClass) {+ case "Asset":+ return "asset";+ case "Liability":+ return "liability";+ case "Equity":+ return "equity";+ case "Revenue":+ return "revenue";+ case "Expense":+ return "expense";+ default:+ throw new Error(`Unknown GL account class: ${glClass}`);+ }+};+export const journalReference = {to: {purchaseInvoice: (id: string) => `purchase-invoice:${id}`,diff --git a/packages/database/supabase/functions/post-memo/build-memo-journal.ts b/packages/database/supabase/functions/post-memo/build-memo-journal.tsindex 110cb55bf2..8bbb5c2ffb 100644--- a/packages/database/supabase/functions/post-memo/build-memo-journal.ts+++ b/packages/database/supabase/functions/post-memo/build-memo-journal.ts@@ -25,29 +25,10 @@// entry balances exactly.import { assertBalanced, round } from "../shared/precision.ts";-import { credit, debit } from "../lib/utils.ts";+import { accountTypeFromClass, credit, debit } from "../lib/utils.ts";type AccountType = "asset" | "liability" | "equity" | "revenue" | "expense";-// glAccountClass (Asset|Liability|Equity|Revenue|Expense) → the lowercase-// AccountType the debit/credit helpers expect.-export function accountTypeFromClass(glClass: string): AccountType {- switch (glClass) {- case "Asset":- return "asset";- case "Liability":- return "liability";- case "Equity":- return "equity";- case "Revenue":- return "revenue";- case "Expense":- return "expense";- default:- throw new Error(`Unknown GL account class: ${glClass}`);- }-}-// A journal line this builder emits. Self-contained — a pure unit shouldn't// depend on the generated DB types, and `journalLine.documentType`'s "Memo" enum// value (migration 20260628143012) isn't in the generated lib/types.ts until thediff --git a/packages/database/supabase/functions/post-payment/build-payment-journal.ts b/packages/database/supabase/functions/post-payment/build-payment-journal.tsindex 92915d8868..80706c6e08 100644--- a/packages/database/supabase/functions/post-payment/build-payment-journal.ts+++ b/packages/database/supabase/functions/post-payment/build-payment-journal.ts@@ -41,7 +41,7 @@// `invoiceSettlement.fxGainLossAmount` captures, so the subledger reconciles.import { assertBalanced, EPSILON, round } from "../shared/precision.ts";-import { credit, debit } from "../lib/utils.ts";+import { accountTypeFromClass, credit, debit } from "../lib/utils.ts";// A journal line this builder emits. Deliberately self-contained — a pure unit// shouldn't depend on the generated DB types, and `journalLine.documentType`'s@@ -73,6 +73,12 @@ export interface PaymentJournalApplicationInput {export interface PaymentJournalAccounts {controlAccountId: string | null;discountAccountId: string | null;+ // The discount account's glAccountClass. Drives the discount line's natural-+ // balance sign so a customer discount (Revenue) debits contra-revenue and a+ // supplier discount (Expense/COGS) credits contra-cost. Resolved by index.ts;+ // optional so callers without a discount need not supply it (falls back to+ // "expense" for back-compat).+ discountAccountClass?: string | null;writeOffAccountId: string | null;fxGainAccountId: string | null;fxLossAccountId: string | null;@@ -139,6 +145,7 @@ export function buildPaymentJournal(const {controlAccountId,discountAccountId,+ discountAccountClass,writeOffAccountId,fxGainAccountId,fxLossAccountId,@@ -238,13 +245,18 @@ export function buildPaymentJournal(`Missing ${isAR ? "customer" : "supplier"} payment discount account default`);}- pushLine(cashIn ? "debit" : "credit", "expense", round(discount * invRate), {- accountId: discountAccountId,- description: isAR- ? "Customer Payment Discount"- : "Supplier Payment Discount",- documentLineReference: invId,- });+ pushLine(+ cashIn ? "debit" : "credit",+ discountAccountClass ? accountTypeFromClass(discountAccountClass) : "expense",+ round(discount * invRate),+ {+ accountId: discountAccountId,+ description: isAR+ ? "Customer Payment Discount"+ : "Supplier Payment Discount",+ documentLineReference: invId,+ }+ );}// Write-off: at TARGET rate (an invoice-currency relief, not cash, so itdiff --git a/packages/database/supabase/functions/post-payment/index.ts b/packages/database/supabase/functions/post-payment/index.tsindex bc94c688a1..cb8cc8f3ac 100644--- a/packages/database/supabase/functions/post-payment/index.ts+++ b/packages/database/supabase/functions/post-payment/index.ts@@ -396,6 +396,26 @@ serve(async (req: Request) => {}}+ // Resolve the discount account's class so buildPaymentJournal signs the+ // discount line by the account's real natural balance (customer discount+ // → Revenue/contra-revenue; supplier discount → Expense/contra-COGS),+ // mirroring how post-memo resolves its reason account's class.+ const discountAccountId = isAR+ ? ad.customerPaymentDiscountAccount+ : ad.supplierPaymentDiscountAccount;+ let discountAccountClass: string | null = null;+ if (discountAccountId) {+ const discountAccount = await client+ .from("account")+ .select("class")+ .eq("id", discountAccountId)+ .single();+ if (discountAccount.error || !discountAccount.data) {+ throw new Error("Failed to fetch the payment discount account class");+ }+ discountAccountClass = discountAccount.data.class as string;+ }+// Build the balanced double-entry. Account-id resolution, the per-// application control/discount/write-off lines, the on-account-credit// line, the single FX plug, and the balance self-check all live in the@@ -420,9 +440,8 @@ serve(async (req: Request) => {})),accounts: {controlAccountId,- discountAccountId: isAR- ? ad.customerPaymentDiscountAccount- : ad.supplierPaymentDiscountAccount,+ discountAccountId,+ discountAccountClass,writeOffAccountId: isAR? ad.customerWriteOffAccount: ad.supplierWriteOffAccount,diff --git a/packages/database/supabase/functions/post-payment/post-payment.test.ts b/packages/database/supabase/functions/post-payment/post-payment.test.tsindex 540e1bb1ce..54cb7db6a4 100644--- a/packages/database/supabase/functions/post-payment/post-payment.test.ts+++ b/packages/database/supabase/functions/post-payment/post-payment.test.ts@@ -20,6 +20,7 @@ import { round } from "../shared/precision.ts";const ACCOUNTS: PaymentJournalAccounts = {controlAccountId: "control", // receivables (AR) or payables (AP); driver resolvesdiscountAccountId: "discount",+ discountAccountClass: "Revenue", // AR default: customer discount is contra-revenuewriteOffAccountId: "writeoff",fxGainAccountId: "fxgain",fxLossAccountId: "fxloss",@@ -66,6 +67,8 @@ const apBase = (sourceExchangeRate: 1,},],+ // AP: supplier discount is contra-COGS (Expense natural balance).+ accounts: { ...ACCOUNTS, discountAccountClass: "Expense" },...over,});@@ -136,7 +139,7 @@ Deno.test("AP full payment, no FX: CR bank / DR payables, balanced", () => {// Discount / write-off — invoice-currency reliefs, no FX.// ----------------------------------------------------------------------------Deno.test("AR discount: bank 90 / receivables 100 / discount expense 10", () => {+Deno.test("AR discount: bank 90 / receivables 100 / discount contra-revenue -10", () => {const { lines, signedDebitTotal } = buildPaymentJournal(arBase({totalAmount: 90,@@ -157,7 +160,7 @@ Deno.test("AR discount: bank 90 / receivables 100 / discount expense 10", () =>assertEquals(line(lines, "Accounts Receivable")!.amount, -100); // (90+10)*1const discount = line(lines, "Customer Payment Discount")!;assertEquals(discount.accountId, "discount");- assertEquals(discount.amount, 10); // debit expense+ assertEquals(discount.amount, -10); // debit to a Revenue-class account (contra-revenue)assert(balanced(signedDebitTotal));});@@ -207,6 +210,31 @@ Deno.test("AP write-off: vendor write-off income credited (revenue)", () => {assert(balanced(signedDebitTotal));});+Deno.test("AP discount: supplier discount credited to a contra-COGS (Expense) account", () => {+ const { lines, signedDebitTotal } = buildPaymentJournal(+ apBase({+ totalAmount: 90,+ applications: [+ {+ targetPurchaseInvoiceId: "pi_1",+ appliedAmount: 90,+ discountAmount: 10,+ writeOffAmount: 0,+ targetExchangeRate: 1,+ sourceExchangeRate: 1,+ },+ ],+ })+ );++ assertEquals(line(lines, "Bank / Cash")!.amount, -90); // credit asset (cash out)+ assertEquals(line(lines, "Accounts Payable")!.amount, -100); // (90+10)×1, debit liability → natural-negative+ const discount = line(lines, "Supplier Payment Discount")!;+ assertEquals(discount.accountId, "discount");+ assertEquals(discount.amount, -10); // credit to an Expense/COGS account → contra-cost+ assert(balanced(signedDebitTotal));+});+// ---------------------------------------------------------------------------// Processor fee — withheld at source (Stripe Connect), so it never touches the// bank line. One journal entry, not a payment entry plus a follow-up fee entry.@@ -715,7 +743,7 @@ Deno.test("AR discount + write-off + FX on one invoice all coexist, balanced", (assertEquals(line(lines, "Bank / Cash")!.amount, 96); // 80 × 1.2assertEquals(line(lines, "Accounts Receivable")!.amount, -100); // (80+10+10) × 1.0- assertEquals(line(lines, "Customer Payment Discount")!.amount, 10); // 10 × 1.0+ assertEquals(line(lines, "Customer Payment Discount")!.amount, -10); // −(10 × 1.0): debit to Revenue = contra-revenueassertEquals(line(lines, "Bad Debt Expense")!.amount, 10); // 10 × 1.0assertEquals(line(lines, "Realized FX Gain")!.amount, 16); // 80 × (1.2 − 1.0)assert(balanced(signedDebitTotal));diff --git a/packages/database/supabase/migrations/20260909014032_payment-discount-reclassification.sql b/packages/database/supabase/migrations/20260909014032_payment-discount-reclassification.sqlnew file mode 100644index 0000000000..c0ace6d25d--- /dev/null+++ b/packages/database/supabase/migrations/20260909014032_payment-discount-reclassification.sql@@ -0,0 +1,77 @@+-- Reclassify AND renumber the payment-discount accounts to their correct GL homes.+-- A customer early-payment discount is a reduction of the transaction price+-- (contra-revenue, per ASC 606 / IFRS 15), and a supplier discount taken is a+-- reduction of the cost of goods (contra-COGS) — neither is an operating expense.+-- Both were originally seeded as class = Expense / Other Expense in the 7000+-- "Other Expenses" block (7030 customer, 7020 supplier). This moves them to:+-- * 7030 -> 4040 "Customer Payment Discounts": class Revenue, under "Revenue"+-- * 7020 -> 5080 "Supplier Payment Discounts": class Expense / Cost of Goods+-- Sold, under "Cost of Goods Sold"+-- matching functions/lib/seed.data.ts (fresh companies seed 4040 / 5080 directly)+-- and the contra-revenue customer credit-memo account 4020 "Sales Discounts".+--+-- Going-forward only: already-posted journalLine history is intentionally NOT+-- rewritten. accountDefault is untouched — the rows keep their ids, so the+-- customerPaymentDiscountAccount / supplierPaymentDiscountAccount FKs travel with+-- the renumber automatically. The account table is scoped by "companyGroupId" (it+-- has no "companyId"), and "number" is unique per companyGroupId.+--+-- Collision safety: "number" is UNIQUE per companyGroupId, and a company group+-- could already hold a custom 4040 / 5080 account. So the reclassification (class,+-- accountType, incomeBalance, parent — none unique-constrained) is applied+-- UNCONDITIONALLY by the old number, and the RENUMBER is applied only where the+-- target number is still free in that group. A group with a conflicting custom+-- account therefore keeps its 7030 / 7020 number but is still correctly+-- reclassified, rather than the whole migration aborting on the unique constraint+-- and leaving every tenant unmigrated (the deploy runner would retry-fail forever).+--+-- Idempotent: reclassification re-applies the same fixed values; the renumber is+-- matched by the old number, so once renumbered its WHERE no longer matches.++-- Customer Payment Discounts (7030): reclassify to contra-revenue, parent "Revenue".+UPDATE "account" a SET+ "class" = 'Revenue',+ "accountType" = 'Income',+ "incomeBalance" = 'Income Statement',+ "parentId" = COALESCE(+ (SELECT g."id" FROM "account" g+ WHERE g."companyGroupId" = a."companyGroupId"+ AND g."isGroup" = TRUE+ AND g."name" = 'Revenue'+ LIMIT 1),+ a."parentId"+ )+WHERE a."number" = '7030';++-- ...then renumber 7030 -> 4040 only where 4040 is free in that company group.+UPDATE "account" a SET "number" = '4040'+WHERE a."number" = '7030'+ AND NOT EXISTS (+ SELECT 1 FROM "account" b+ WHERE b."companyGroupId" = a."companyGroupId"+ AND b."number" = '4040'+ );++-- Supplier Payment Discounts (7020): reclassify to contra-COGS, parent "Cost of Goods Sold".+UPDATE "account" a SET+ "class" = 'Expense',+ "accountType" = 'Cost of Goods Sold',+ "incomeBalance" = 'Income Statement',+ "parentId" = COALESCE(+ (SELECT g."id" FROM "account" g+ WHERE g."companyGroupId" = a."companyGroupId"+ AND g."isGroup" = TRUE+ AND g."name" = 'Cost of Goods Sold'+ LIMIT 1),+ a."parentId"+ )+WHERE a."number" = '7020';++-- ...then renumber 7020 -> 5080 only where 5080 is free in that company group.+UPDATE "account" a SET "number" = '5080'+WHERE a."number" = '7020'+ AND NOT EXISTS (+ SELECT 1 FROM "account" b+ WHERE b."companyGroupId" = a."companyGroupId"+ AND b."number" = '5080'+ );diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 1931b5755c..ba07a4f8f4 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -613,6 +613,9 @@ msgstr "Das Startdatum eines Auftrags ändert sich"msgid "A job's status changes"msgstr "Der Status eines Auftrags ändert sich"+msgid "A line settles more than its invoice's open balance"+msgstr "Eine Position begleicht mehr als den offenen Betrag ihrer Rechnung"+#. placeholder {0}: label( operationInputLabelKey(operationId, batchInput), batchInput )msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."msgstr "Eine Liste ist mit {0} verbunden, sodass dieser Schritt einmal für jedes Element ausgeführt wird und eine Liste von Ergebnissen zurückgibt."diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 63b7ea7ec9..397a8123a6 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -613,6 +613,9 @@ msgstr "A job's start date changes"msgid "A job's status changes"msgstr "A job's status changes"+msgid "A line settles more than its invoice's open balance"+msgstr "A line settles more than its invoice's open balance"+#. placeholder {0}: label( operationInputLabelKey(operationId, batchInput), batchInput )msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."msgstr "A list is wired into {0}, so this step runs once for each item and returns a list of results."diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 002cee6606..05e5bf565f 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -613,6 +613,9 @@ msgstr "La fecha de inicio de un trabajo cambia"msgid "A job's status changes"msgstr "El estado de un trabajo cambia"+msgid "A line settles more than its invoice's open balance"+msgstr "Una línea liquida más que el saldo pendiente de su factura"+#. placeholder {0}: label( operationInputLabelKey(operationId, batchInput), batchInput )msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."msgstr "Una lista está conectada a {0}, por lo que este paso se ejecuta una vez para cada elemento y devuelve una lista de resultados."diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex f3fde3b9c2..d2d86f881e 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -613,6 +613,9 @@ msgstr "La date de début d'un travail change"msgid "A job's status changes"msgstr "Le statut d'un travail change"+msgid "A line settles more than its invoice's open balance"+msgstr "Une ligne règle plus que le solde impayé de sa facture"+#. placeholder {0}: label( operationInputLabelKey(operationId, batchInput), batchInput )msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."msgstr "Une liste est connectée à {0}, donc cette étape s'exécute une fois pour chaque élément et retourne une liste de résultats."diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 28fd417f47..2d21458908 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -613,6 +613,9 @@ msgstr "किसी नौकरी की प्रारंभ तिथिmsgid "A job's status changes"msgstr "किसी नौकरी की स्थिति में परिवर्तन"+msgid "A line settles more than its invoice's open balance"+msgstr "एक पंक्ति अपने चालान के बकाया शेष से अधिक का निपटान करती है"+#. placeholder {0}: label( operationInputLabelKey(operationId, batchInput), batchInput )msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."msgstr "एक सूची {0} में जुड़ी हुई है, इसलिए यह चरण प्रत्येक आइटम के लिए एक बार चलता है और परिणामों की एक सूची लौटाता है।"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex 7effcf73c9..39fbecfe88 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -613,6 +613,9 @@ msgstr "La data di inizio del lavoro cambia"msgid "A job's status changes"msgstr "Lo stato del lavoro cambia"+msgid "A line settles more than its invoice's open balance"+msgstr "Una riga salda più del saldo aperto della sua fattura"+#. placeholder {0}: label( operationInputLabelKey(operationId, batchInput), batchInput )msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."msgstr "Un elenco è collegato a {0}, quindi questo passaggio viene eseguito una volta per ogni elemento e restituisce un elenco di risultati."diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 6dd2c57119..cf071ca1e0 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -613,6 +613,9 @@ msgstr "ジョブの開始日が変更されました"msgid "A job's status changes"msgstr "ジョブのステータスが変更されました"+msgid "A line settles more than its invoice's open balance"+msgstr "明細が請求書の未払い残高を超えて消込しています"+#. placeholder {0}: label( operationInputLabelKey(operationId, batchInput), batchInput )msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."msgstr "リストが{0}に接続されているため、このステップは各項目ごとに1回実行され、結果のリストを返します。"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex d54bb881d0..395d8ee818 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -613,6 +613,9 @@ msgstr "작업 지시의 시작일이 변경됨"msgid "A job's status changes"msgstr "작업의 상태가 변경됨"+msgid "A line settles more than its invoice's open balance"+msgstr "한 항목이 송장의 미결제 잔액보다 많이 정산합니다"+#. placeholder {0}: label( operationInputLabelKey(operationId, batchInput), batchInput )msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."msgstr "목록이 {0}에 연결되어 있으므로 이 단계는 각 항목마다 한 번씩 실행되고 결과 목록을 반환합니다."diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex 816e85725a..cbaa9c57da 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -613,6 +613,9 @@ msgstr "Data rozpoczęcia zadania zmienia się"msgid "A job's status changes"msgstr "Status zadania zmienia się"+msgid "A line settles more than its invoice's open balance"+msgstr "Pozycja rozlicza więcej niż otwarte saldo jej faktury"+#. placeholder {0}: label( operationInputLabelKey(operationId, batchInput), batchInput )msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."msgstr "Lista jest podłączona do {0}, więc ten krok uruchamia się raz dla każdego elementu i zwraca listę wyników."diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex aa74931335..8890aa2fc3 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -613,6 +613,9 @@ msgstr "A data de início de um trabalho muda"msgid "A job's status changes"msgstr "O status de um trabalho muda"+msgid "A line settles more than its invoice's open balance"+msgstr "Uma linha liquida mais do que o saldo em aberto da sua fatura"+#. placeholder {0}: label( operationInputLabelKey(operationId, batchInput), batchInput )msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."msgstr "Uma lista é conectada a {0}, portanto, esta etapa é executada uma vez para cada item e retorna uma lista de resultados."diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex d46ab90ef8..1fb09668a0 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -613,6 +613,9 @@ msgstr "Дата начала работы изменяется"msgid "A job's status changes"msgstr "Статус работы изменяется"+msgid "A line settles more than its invoice's open balance"+msgstr "Строка погашает больше, чем непогашенный остаток по счёту"+#. placeholder {0}: label( operationInputLabelKey(operationId, batchInput), batchInput )msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."msgstr "Список подключен к {0}, поэтому этот шаг выполняется один раз для каждого элемента и возвращает список результатов."diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex 76014ca96e..9d4984d6e3 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -613,6 +613,9 @@ msgstr "İş emrinin başlangıç tarihi değişiyor"msgid "A job's status changes"msgstr "Bir işin durumu değiştirildi"+msgid "A line settles more than its invoice's open balance"+msgstr "Bir satır, faturasının açık bakiyesinden fazlasını kapatıyor"+#. placeholder {0}: label( operationInputLabelKey(operationId, batchInput), batchInput )msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."msgstr "Bir liste {0} öğesine bağlandı, bu nedenle bu adım her öğe için bir kez çalışır ve sonuçların listesini döndürür."diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 9edc344ca9..e3be9bc4e9 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -613,6 +613,9 @@ msgstr "任务的开始日期已变更"msgid "A job's status changes"msgstr "任务的状态已变更"+msgid "A line settles more than its invoice's open balance"+msgstr "某行结算金额超过其发票的未结余额"+#. placeholder {0}: label( operationInputLabelKey(operationId, batchInput), batchInput )msgid "A list is wired into {0}, so this step runs once for each item and returns a list of results."msgstr "列表被接入到 {0},所以此步骤为每个项目运行一次并返回结果列表。"