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
refactor(currency): platform-global exchange rates with per-company overrides (#1562)
Brad Barbin8bd387b39bd0
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex 2945918f45..26a66c4b68 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -1286,3 +1286,23 @@ as the breakdown. Name the two so they cannot be confused (`violations` vs**Applies to:** `packages/jobs/src/backups/scope.ts`(`findExportScopeViolationsDetailed`, `computeScopeExclusions`, `totalExcludedRows`),`Manifest.excludedRowsByTable`, and any future "N things are wrong" surface.++## The backups schema baseline on main can carry phantom tables from a dirty local DB++**Context:** `pnpm db:check:backups` blocked the currency-refactor commit on `onshapeSyncRun`/`onshapeItemSyncState` — tables with NO migration anywhere in the repo.++**Problem:** `packages/jobs/manifests/schema.json` regenerates from the committing developer's LIVE schema. If that database has tables applied from an unmerged branch, they enter the committed baseline, and every later committer's check flags them as "dropped without a rename mapping" — a false alarm that invites `--no-verify` reflexes or, worse, bogus `TABLE_RENAMES: null` entries declaring never-shipped tables dropped.++**Rule:** When `db:check:backups` blocks on a missing table, first verify the table exists in ANY migration (`grep -r <table> packages/database/supabase/migrations/`). No migration ⇒ baseline pollution, not your break: regenerate `schema.json` from a clean fully-migrated database (the catalog code in `src/backups/schema.ts` + the manifest shape in `check-backups.ts`), commit it with `CARBON_SKIP_BACKUP_CHECK=1`, and say why in the commit message. Never add a rename entry for a table that never shipped.++**Applies to:** `packages/jobs/manifests/schema.json`, `packages/jobs/src/scripts/check-backups.ts`, `.husky/pre-commit`.++## Adding CHECK + VALIDATE requires auditing every WRITER of the column and pre-cleaning data in the same migration++**Context:** The currency refactor added `CHECK ("exchangeRate" > 0)` + `VALIDATE` on 12 document tables. Review found `get-method` had been writing `exchangeRate: l.exchangeRate ?? 0` into `quoteLinePrice` for every legacy null-rate quote line, and the old `NUMERIC(10,4)` clamp had stored sub-0.00005 rates as literal `0.0000`.++**Problem:** `VALIDATE CONSTRAINT` scans existing rows mid-deploy — one violating row anywhere fails the whole migration in production, and post-deploy the unfixed writer fails at runtime (a whole edge-function transaction). A constraint that is obviously true "going forward" says nothing about years of rows written by code paths you didn't grep.++**Rule:** Before adding a CHECK on an existing column: (1) grep EVERY writer of that column — app services, edge functions, triggers, seeds — and fix any that can produce a violating value in the same change set; (2) repair existing violating rows in the same migration, before the VALIDATE (`UPDATE … WHERE <violates>` with an explainable value); (3) remember old NUMERIC(p,s) clamps — a widened column can still hold rounded-to-zero values from its clamped era.++**Applies to:** any `ADD CONSTRAINT … CHECK` + `VALIDATE` migration; `packages/database/supabase/functions/**` writers of the constrained column.diff --git a/.ai/plans/2026-09-02-currency-exchange-rate-refactor.md b/.ai/plans/2026-09-02-currency-exchange-rate-refactor.mdnew file mode 100644index 0000000000..d01ed4faa6--- /dev/null+++ b/.ai/plans/2026-09-02-currency-exchange-rate-refactor.md@@ -0,0 +1,551 @@+# Currency & Exchange Rate Architecture Refactor — implementation plan++**Spec:** .ai/specs/2026-09-02-currency-exchange-rate-refactor.md+**Research:** .ai/research/exchange-rate-competitor-practice.md · .ai/research/2026-09-02-currency-architecture.md (the blast-radius map — consult it for every call-site list) · .ai/research/2026-09-02-exchange-rate-update-path.md+**Branch:** hat-yai++Conventions that bind every task: migrations idempotent (guards on every DDL); never+backdate timestamps; `pnpm`, never `npm`; scoped typechecks only (whole-repo OOMs); rate+meaning at stamping sites is UNCHANGED ("document-currency units per 1 base unit").++## Progress+- [x] Task 1: Author migration M1 — global store, overrides, resolver functions+- [x] Task 2: Author migration M2 — data migration, column drop, view, integration delete+- [x] Task 3: Author migration M3 — salesInvoice propagation, CHECKs, consolidation forks+- [x] Task 4: Apply migrations, regenerate types, psql assertions+- [x] Task 5: Models + service layer (accounting module)+- [x] Task 6: Sweep sales.service.ts stamping sites+- [x] Task 7: Sweep purchasing.service.ts stamping sites+- [x] Task 8: Sweep invoicing.service.ts + all six exchange-rate refresh routes+- [x] Task 9: Edge functions `convert` + `create` → resolver+- [x] Task 10: Jobs — rewrite feed job, kill paperless-parts duplicate+- [x] Task 11: Delete the exchange-rates integration from @carbon/ee+- [x] Task 12: Seed paths + backup scoping pins+- [x] Task 13: UI — exchange-rates page: resolved rates, provenance, overrides+- [x] Task 14: Full scoped validation (typecheck erp/jobs/ee/database + lint + tests)+- [x] Task 15: Dataset + backup pre-commit gates+- [ ] Task 16: Browser verification (/test)+- [ ] Task 17: Docs sync (carbon-docs)++## Dependencies+- Tasks 1–3 are independent authoring tasks (order irrelevant; MUST all exist before Task 4).+- Task 4 needs 1–3. Everything after needs Task 4 (generated types).+- Tasks 6, 7, 8, 9, 10, 11, 12 are mutually independent (different files) — parallelizable after Task 5.+- Task 13 needs Task 5. Task 14 needs 5–13. Tasks 15–17 need 14.++---++## Task 1: Author migration M1 — global store, overrides, resolver functions++**Depends on:** none+**Files:**+- Create: `packages/database/supabase/migrations/<ts>_exchange-rate-global-store.sql` (via `pnpm db:migrate:new exchange-rate-global-store`; HHMMSS must not be 000000)++**Steps:**+1. `pnpm db:migrate:new exchange-rate-global-store`+2. Write, in order:++```sql+-- Global market-rate store. Deliberately NOT tenant-scoped: market data, same class+-- as "currencyCode". rate = units of "currencyCode" per 1 USD.+CREATE TABLE IF NOT EXISTS "exchangeRate" (+ "id" TEXT NOT NULL DEFAULT id('xrate'),+ "currencyCode" TEXT NOT NULL REFERENCES "currencyCode"("code") ON DELETE CASCADE ON UPDATE CASCADE,+ "effectiveDate" DATE NOT NULL,+ "rate" NUMERIC NOT NULL CHECK ("rate" > 0),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ CONSTRAINT "exchangeRate_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "exchangeRate_code_date_key" UNIQUE ("currencyCode", "effectiveDate")+);+CREATE INDEX IF NOT EXISTS "exchangeRate_code_date_idx" ON "exchangeRate" ("currencyCode", "effectiveDate" DESC);+ALTER TABLE "exchangeRate" ENABLE ROW LEVEL SECURITY;+DROP POLICY IF EXISTS "SELECT" ON "public"."exchangeRate";+CREATE POLICY "SELECT" ON "public"."exchangeRate" FOR SELECT TO authenticated USING (true);+-- writes: service role only (no INSERT/UPDATE/DELETE policies)+```++ Note the bare `NUMERIC` (house rule: no precision spec).+3. `exchangeRateOverride` per the spec's SQL sketch, EXCEPT: bare `NUMERIC`, inline FK+ refs for `createdBy`/`updatedBy` to `"user"("id")`, indexes on `companyId`,+ `currencyCode`, `createdBy`; RLS policies named `SELECT`/`INSERT`/`UPDATE`/`DELETE`+ schema-qualified with `::text[]` casts:+ - SELECT: `"companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])`+ - INSERT/UPDATE/DELETE: `get_companies_with_employee_permission('accounting_update')`+ for all three write verbs (mirror how a recent accounting-scoped table does it —+ fork the policy shape from the NEWEST migration containing+ `get_companies_with_employee_permission('accounting_`).+4. Seed the global store — one row per code from Appendix A, `effectiveDate` =+ `'2026-09-01'`, `ON CONFLICT ("currencyCode","effectiveDate") DO NOTHING`, comment:+ `-- Bootstrap snapshot (approximate, 2026-09). Superseded by the daily feed job.`+ Cross-check: every `code` in the `currencies` array of+ `packages/database/supabase/functions/lib/seed.data.ts` (~line 484) must appear in+ Appendix A. If any code is missing from the appendix, STOP and report — do not invent+ a rate inline.+5. Resolver functions (PLPGSQL — never LANGUAGE sql for anything whose ordering/inlining+ matters):++```sql+CREATE OR REPLACE FUNCTION get_exchange_rate(+ p_company_id TEXT,+ p_currency_code TEXT,+ p_as_of DATE DEFAULT NULL+) RETURNS NUMERIC LANGUAGE plpgsql STABLE AS $$+DECLARE+ v_base TEXT;+ v_override NUMERIC;+ v_code_rate NUMERIC;+ v_base_rate NUMERIC;+ v_as_of DATE := COALESCE(p_as_of, CURRENT_DATE);+BEGIN+ SELECT "baseCurrencyCode" INTO v_base FROM "company" WHERE "id" = p_company_id;+ IF v_base IS NULL THEN+ RAISE EXCEPTION 'Company % not found', p_company_id;+ END IF;+ IF p_currency_code = v_base THEN RETURN 1; END IF;++ SELECT "rate" INTO v_override FROM "exchangeRateOverride"+ WHERE "companyId" = p_company_id AND "currencyCode" = p_currency_code;+ IF v_override IS NOT NULL THEN RETURN v_override; END IF;++ SELECT "rate" INTO v_code_rate FROM "exchangeRate"+ WHERE "currencyCode" = p_currency_code AND "effectiveDate" <= v_as_of+ ORDER BY "effectiveDate" DESC LIMIT 1;+ SELECT "rate" INTO v_base_rate FROM "exchangeRate"+ WHERE "currencyCode" = v_base AND "effectiveDate" <= v_as_of+ ORDER BY "effectiveDate" DESC LIMIT 1;+ IF v_code_rate IS NULL OR v_base_rate IS NULL THEN+ RAISE EXCEPTION 'No exchange rate available for % (base %). Set a rate manually in Accounting -> Exchange Rates.',+ p_currency_code, v_base;+ END IF;+ RETURN v_code_rate / v_base_rate;+END;+$$;+```++ And `get_exchange_rates(p_company_id TEXT) RETURNS TABLE("currencyCode" TEXT,+ "decimalPlaces" INTEGER, "active" BOOLEAN, "rate" NUMERIC, "source" TEXT,+ "rateUpdatedAt" TIMESTAMPTZ)` — joins the company's group `currency` config rows+ (resolve `companyGroupId` from `company`) to overrides (source `'override'`,+ `rateUpdatedAt` = override's `COALESCE(updatedAt, createdAt)`) else the latest global+ pair ratio (source `'market'`, `rateUpdatedAt` = the global row's+ `COALESCE(updatedAt, createdAt)`), with the company's base row returning+ `rate = 1, source = 'base'`. A code with no resolution returns `rate NULL, source+ 'missing'` (the LIST function reports rather than raises; only the scalar raises).+ Grant EXECUTE on both to `authenticated`.++**Verify:**+```bash+ls packages/database/supabase/migrations/ | tail -3+# Expected: <new-timestamp>_exchange-rate-global-store.sql listed, timestamp newer than every existing file+grep -c "ON CONFLICT" packages/database/supabase/migrations/*exchange-rate-global-store.sql+# Expected: >= 1 (seed idempotency)+```++**Out of scope:** anything touching the `currency` table (Task 2), consolidation (Task 3).++## Task 2: Author migration M2 — data migration, column drop, view, integration delete++**Depends on:** none (authoring); ordering with M1 is by timestamp — create AFTER Task 1's file so this timestamp sorts later. If created earlier, STOP and re-create.+**Files:**+- Create: `packages/database/supabase/migrations/<ts>_currency-config-only.sql` (via `pnpm db:migrate:new currency-config-only`)+- Modify: `packages/jobs/src/backups/renames.ts` — add `"exchangeRateHistory": null` to `TABLE_RENAMES`++**Steps:**+1. Migrate hand-set rates to overrides (run BEFORE the column drop, same file):++```sql+INSERT INTO "exchangeRateOverride" ("companyId", "currencyCode", "rate", "createdBy")+SELECT co."id", cu."code", cu."exchangeRate", 'system'+FROM "currency" cu+JOIN "company" co ON co."companyGroupId" = cu."companyGroupId"+WHERE cu."exchangeRate" <> 1+ AND cu."code" <> co."baseCurrencyCode"+ AND NOT EXISTS (+ SELECT 1 FROM "companyIntegration" ci+ WHERE ci."id" = 'exchange-rates-v1' AND ci."active" = true+ AND ci."companyId" IN (+ SELECT c2."id" FROM "company" c2 WHERE c2."companyGroupId" = cu."companyGroupId"+ )+ )+ON CONFLICT ("companyId", "currencyCode") DO NOTHING;+```++2. Recreate the `currencies` view WITHOUT `exchangeRate`: find the NEWEST definition+ (`grep -rn "CREATE OR REPLACE VIEW \"currencies\"\|CREATE VIEW \"currencies\"" packages/database/supabase/migrations/ | tail -1`,+ expected `20260228023426_company-groups.sql:924-928`), fork it, `DROP VIEW IF EXISTS+ "currencies";` then recreate `WITH(SECURITY_INVOKER=true)` selecting the surviving+ columns + `currencyCode.name`. If the newest definition selects columns other than+ what the research doc §1.2 lists, STOP and report.+3. `ALTER TABLE "currency" DROP COLUMN IF EXISTS "exchangeRate";`+ (`historicalExchangeRate`, `decimalPlaces`, `active`, `tags`, `customFields` remain.)+4. `DROP TABLE IF EXISTS "exchangeRateHistory";` — zero writers/rows (research §3.1).+5. `DELETE FROM "companyIntegration" WHERE "id" = 'exchange-rates-v1';`+6. Add the `TABLE_RENAMES` entry (`"exchangeRateHistory": null`) in+ `packages/jobs/src/backups/renames.ts` — same commit as this migration.++**Verify:**+```bash+grep -n "DROP COLUMN IF EXISTS\|DROP TABLE IF EXISTS\|ON CONFLICT" packages/database/supabase/migrations/*currency-config-only.sql+# Expected: all three present+grep -n "exchangeRateHistory" packages/jobs/src/backups/renames.ts+# Expected: "exchangeRateHistory": null+```++**Out of scope:** `historicalExchangeRate` (stays), `currency` RLS (unchanged), seeds (Task 12).++## Task 3: Author migration M3 — salesInvoice propagation, CHECKs, consolidation forks++**Depends on:** none (authoring; timestamp must sort after Task 2's file)+**Files:**+- Create: `packages/database/supabase/migrations/<ts>_exchange-rate-guards-and-consolidation.sql` (via `pnpm db:migrate:new exchange-rate-guards-and-consolidation`)++**Steps:**+1. salesInvoice header→line propagation — fork the SHAPE from the purchase-invoice pair:+ trigger fn + AFTER UPDATE trigger in `20241210214820` (fn ~line 325, fixed in+ `20260616061244_fix_purchase_invoice_line_trigger_exchange_rate_typo.sql:2-13`) and+ the BEFORE INSERT inherit trigger `sync_purchase_invoice_line_exchange_rate_on_insert`+ (`20260616061244:27-43`). Create the salesInvoice equivalents+ (`update_sales_invoice_line_exchange_rate`, `sync_sales_invoice_line_exchange_rate_on_insert`),+ both `DROP TRIGGER IF EXISTS` + `CREATE OR REPLACE FUNCTION` guarded. One-time+ backfill limited to unposted invoices:+ `UPDATE "salesInvoiceLine" sil SET "exchangeRate" = si."exchangeRate" FROM "salesInvoice" si WHERE si."id" = sil."invoiceId" AND si."companyId" = sil."companyId" AND si."status" = 'Draft' AND sil."exchangeRate" IS DISTINCT FROM si."exchangeRate";`+ Check the actual FK column name of `salesInvoiceLine` → header (grep the line table's+ creation in `20250507143421`); if it is not `invoiceId`, use the real name. If PR+ #1527 merged meanwhile and these triggers already exist under other names, STOP and+ reconcile rather than duplicating.+2. Rate positivity on the 12 document tables (quote, salesOrder, purchaseOrder,+ supplierQuote, purchaseInvoice, salesInvoice, quoteLinePrice, salesOrderLine,+ purchaseOrderLine, supplierQuoteLinePrice, purchaseInvoiceLine, salesInvoiceLine),+ each as:+ ```sql+ DO $$ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = '<table>_exchangeRate_positive') THEN+ ALTER TABLE "<table>" ADD CONSTRAINT "<table>_exchangeRate_positive" CHECK ("exchangeRate" > 0) NOT VALID;+ END IF;+ END $$;+ ALTER TABLE "<table>" VALIDATE CONSTRAINT "<table>_exchangeRate_positive";+ ```+ If VALIDATE fails locally on real bad rows, STOP and report the offending counts —+ do not add a data-fixing UPDATE without recording it.+3. Consolidation forks. Extract the NEWEST definitions verbatim+ (`sed`/`pg_get_functiondef` per the migration-function-redefinition memory) of+ `translateTrialBalance` (`20260811123614_widen-ledger-amounts.sql:260-333`) and+ `get_consolidation_rates`/`getConsolidationRates` (`20260811123614:303-306`; first+ defined `20260713225803:179-233` — use whichever the newest file defines). Preserve+ signatures and attributes exactly; change ONLY the closing/average sources:+ - closing rate = `target.rate / source.rate` where each side is the latest+ `"exchangeRate"` row with `effectiveDate <= p_period_end` for the target/source+ currency; if either side has NO row ≤ the date (pre-seed history), take that side's+ EARLIEST row instead; never COALESCE to 1.+ - average rate = `AVG(t.rate / s.rate)` over `effectiveDate` in the period where both+ codes have rows on the same date; fall back to the closing rate when the period has+ no paired dates.+ - historical rate = unchanged (`currency."historicalExchangeRate"`).+ The existing multiply convention in the function body is now correct (rate is+ target-per-source) — do not flip any multiplication. If the newest definitions differ+ structurally from the research description (no closing/average branches, different+ param names), STOP and report.++**Verify:**+```bash+grep -c "exchangeRate_positive" packages/database/supabase/migrations/*exchange-rate-guards-and-consolidation.sql+# Expected: >= 24 (12 ADD + 12 VALIDATE)+grep -n "COALESCE(.*, *1)" packages/database/supabase/migrations/*exchange-rate-guards-and-consolidation.sql+# Expected: no hits inside the closing/average rate computations+```++**Out of scope:** quote/SO interceptors and PO/PI/SQ triggers (working — untouched);+`historicalExchangeRate` direction; GL posting-chain conventions (separate July-02 spec).++## Task 4: Apply migrations, regenerate types, psql assertions++**Depends on:** Tasks 1–3+**Steps:**+1. `pnpm db:migrate` (applies all three; regenerates types + swagger; reloads PostgREST).+2. `pnpm run generate:types` if step 1 did not regenerate (it should have).+3. psql assertions against the local DB (connection from `.env.local` `PORT_DB`):++**Verify:**+```bash+psql "$DB_URL" -c "SELECT count(*) FROM \"exchangeRate\";"+# Expected: >= 100 (seed snapshot)+psql "$DB_URL" -c "SELECT get_exchange_rate((SELECT id FROM company LIMIT 1), 'EUR');"+# Expected: a positive numeric ≠ 1 (unless that company's base IS EUR → then exactly 1)+psql "$DB_URL" -c "SELECT column_name FROM information_schema.columns WHERE table_name = 'currency' AND column_name = 'exchangeRate';"+# Expected: 0 rows+psql "$DB_URL" -c "SELECT 1 FROM information_schema.tables WHERE table_name = 'exchangeRateHistory';"+# Expected: 0 rows+grep -n "exchangeRateOverride" packages/database/src/types.ts | head -1+# Expected: a hit (types regenerated)+```++**Out of scope:** any TS fixes (later tasks) — typecheck is EXPECTED red after this task.++## Task 5: Models + service layer (accounting module)++**Depends on:** Task 4+**Files:**+- Modify: `apps/erp/app/modules/accounting/accounting.models.ts` — `currencyValidator`+ (~line 416): REMOVE `exchangeRate`; keep `historicalExchangeRate` (change its `.min(0)`+ to `.positive()`); ADD `exchangeRateOverrideValidator = z.object({ currencyCode: z.string().min(1), rate: zfd.numeric(z.number().positive()) })`.+- Modify: `apps/erp/app/modules/accounting/accounting.ee.service.ts`:+ - ADD `getExchangeRate(client, companyId, currencyCode)` → `client.rpc("get_exchange_rate", { p_company_id, p_currency_code })`, returns `{ data: number, error }`.+ - ADD `getExchangeRates(client, companyId)` → `client.rpc("get_exchange_rates", ...)`.+ - ADD `upsertExchangeRateOverride(client, { companyId, currencyCode, rate, userId })` (upsert on `companyId,currencyCode`) and `deleteExchangeRateOverride(client, companyId, currencyCode)`.+ - MODIFY `upsertCurrency` (~3696): drop `exchangeRate` from its accepted fields.+ - MODIFY `getExchangeRateHistory` (~4735): read the global `exchangeRate` table by+ `currencyCode` (latest 90 rows, `effectiveDate` desc) — drop the `companyGroupId` param; update its one caller (`exchange-rates.$currencyId.tsx:34`, adjusted fully in Task 13).+- Modify: `apps/erp/app/modules/accounting/index.ts` barrel if the new exports aren't covered by `export *`.++**Steps:** as listed. Service functions: `client` first arg, return `{data, error}`, never throw (house rule).++**Verify:**+```bash+grep -n "get_exchange_rate\|exchangeRateOverrideValidator\|upsertExchangeRateOverride" apps/erp/app/modules/accounting/accounting.models.ts apps/erp/app/modules/accounting/accounting.ee.service.ts | head+# Expected: all three appear+```++**Out of scope:** callers (Tasks 6–8, 13).++## Task 6: Sweep sales.service.ts stamping sites++**Depends on:** Task 5 (parallel-safe with 7–12)+**Files:**+- Modify: `apps/erp/app/modules/sales/sales.service.ts` — every `getCurrencyByCode` call whose result feeds an `exchangeRate` (research doc §4.2 lists them: quote create/update/convert ~3519/3651/3732/3828; SO ~5327/5441/5600/5660): replace with `getExchangeRate(client, companyId, code)`; on `error` or null data, RETURN the error (no `?? 1`, no fallback). Sites that only need `decimalPlaces` keep `getCurrencyByCode`.+- Modify: quote/SO route actions listed in §4.2 that read the live rate (`x+/quote+/update.tsx:70`, `x+/quote+/$quoteId.tsx:124`, `x+/sales-order+/update.tsx:49,77`) — same replacement. (The `.exchange-rate.tsx` refresh routes are Task 8.)++**Steps:**+1. `grep -n "getCurrencyByCode" apps/erp/app/modules/sales/sales.service.ts apps/erp/app/routes/x+/quote+/*.tsx apps/erp/app/routes/x+/sales-order+/update.tsx` — enumerate every hit; classify rate-consuming vs decimals-only; convert the former.+2. Where a site currently forces `exchangeRate = 1` for the company's own base (e.g. `sales.service.ts:3742, 5670`), keep the semantics but let the resolver return the 1 (it does, by definition) — delete the special-casing only where it is now redundant AND the code reads clearer; do not restructure control flow otherwise.++**Verify:**+```bash+grep -n "exchangeRate ?? 1\|exchangeRate || 1\|\.exchangeRate ?? 1" apps/erp/app/modules/sales/sales.service.ts+# Expected: 0 hits+```++**Out of scope:** documentPreview.server.ts / shared.server.ts decimals-only reads; PDF props.++## Task 7: Sweep purchasing.service.ts stamping sites++**Depends on:** Task 5+**Files:**+- Modify: `apps/erp/app/modules/purchasing/purchasing.service.ts` — PO ~1508/1609/1696, supplier quote ~2077/2182/2235/2321 (research §4.2), same conversion as Task 6.+- Modify: `x+/purchase-order+/update.tsx:60,122`, `x+/purchase-order+/$orderId.tsx:282,508`, `x+/purchase-order+/$orderId.finalize.tsx:340`, `x+/supplier-quote+/$id.tsx:63`, `x+/supplier-quote+/update.tsx:73` — same.++**Verify:**+```bash+grep -n "exchangeRate ?? 1\|exchangeRate || 1" apps/erp/app/modules/purchasing/purchasing.service.ts+# Expected: 0 hits+```++**Out of scope:** supplier-price conversion math (PR #1543's territory — direction bugs merge separately).++## Task 8: Sweep invoicing.service.ts + all six exchange-rate refresh routes++**Depends on:** Task 5+**Files:**+- Modify: `apps/erp/app/modules/invoicing/invoicing.service.ts` — ~568/729 (PI), ~946/1107 (SI), same conversion.+- Modify: the six refresh routes — `x+/quote+/$quoteId.exchange-rate.tsx`, `x+/sales-order+/$orderId.exchange-rate.tsx`, `x+/purchase-order+/$orderId.exchange-rate.tsx`, `x+/supplier-quote+/$id.exchange-rate.tsx`, `x+/purchase-invoice+/$invoiceId.exchange-rate.tsx`, `x+/sales-invoice+/$invoiceId.exchange-rate.tsx`: the action must (a) read the DOCUMENT row's `currencyCode` (never a POSTed code/rate — subsumes #1530), (b) `getExchangeRate(client, companyId, documentCurrencyCode)`, (c) call the existing `update*ExchangeRate` service fn with that rate. Also `x+/purchase-invoice+/$invoiceId.tsx:79`, `x+/purchase-invoice+/update.tsx:56,137`, `x+/sales-invoice+/$invoiceId.tsx:80`, `x+/sales-invoice+/update.tsx:55`.++**Verify:**+```bash+grep -rn "formData.get(\"exchangeRate\")\|formData.get(\"currencyCode\")" apps/erp/app/routes/x+/*/*exchange-rate.tsx+# Expected: 0 hits (rate/code never client-supplied on refresh)+grep -n "exchangeRate ?? 1" apps/erp/app/modules/invoicing/invoicing.service.ts+# Expected: 0 hits+```++**Out of scope:** invoice posting edge functions (snapshot consumers — untouched).++## Task 9: Edge functions `convert` + `create` → resolver++**Depends on:** Task 4+**Files:**+- Modify: `packages/database/supabase/functions/convert/index.ts` (~1084): replace the `currency` table read + refuse-on-missing block with one RPC: `client.rpc("get_exchange_rate", { p_company_id: companyId, p_currency_code: code })`; keep the error path (throw with the RPC's error message).+- Modify: `packages/database/supabase/functions/create/index.ts` (~541): same replacement; DELETE the `?? 1`. A resolver error must fail the operation (throw), not default.++**Verify:**+```bash+grep -n "from(\"currency\")" packages/database/supabase/functions/convert/index.ts packages/database/supabase/functions/create/index.ts+# Expected: 0 hits+grep -n "?? 1" packages/database/supabase/functions/create/index.ts | grep -i exchange+# Expected: 0 hits+```++**Out of scope:** `deno check` exit codes (pre-existing shared-graph errors — gate on own-file deltas only, per lessons); all other edge functions (snapshot consumers).++## Task 10: Jobs — rewrite feed job, kill paperless-parts duplicate++**Depends on:** Task 4+**Files:**+- Modify: `packages/jobs/src/inngest/functions/scheduled/update-exchange-rates.ts` — full rewrite, SAME function id `update-exchange-rates`, SAME cron `0 0 * * *`:+ 1. Move the `ExchangeRatesClient` class + `getExchangeRatesClient` from `packages/ee/src/exchange-rates/exchange-rates.server.ts` INTO this file (or a sibling `update-exchange-rates.lib.ts`) — `@carbon/ee/exchange-rates.server` will be deleted in Task 11.+ 2. No `companyIntegration` scan. Flow: if no `EXCHANGE_RATES_API_KEY`, `logger.info` + return. Fetch EUR-based rates once. Convert to USD anchor: `usdRate = rates["USD"]`; for each code in the payload, `rate = round(rates[code] / usdRate)` (`round` from `@carbon/utils`, default scale — never display decimals). Read the `currencyCode` list (service role, `from("currencyCode").select("code")` — reference table, no tenancy); upsert into the global `exchangeRate` table one row per code present in BOTH lists: `{ currencyCode, effectiveDate: <today UTC date>, rate, updatedAt }`, `onConflict: "currencyCode,effectiveDate"`. For today's date use `datetime.timestamp()`-derived UTC day per date-handling rules (no `new Date().toISOString().split`— use the `datetime` API from `@carbon/utils`).+ 3. Log codes present in `currencyCode` but absent from the feed (stale-warning from PR #1542's design).+- Modify: `packages/jobs/src/inngest/functions/integrations/paperless-parts.ts` (~808): replace the local `getCurrencyByCode` (currency-table read) with `serviceRole.rpc("get_exchange_rate", { p_company_id: companyId, p_currency_code: code })`; a resolver error skips stamping with a logged warning (imported quotes must not fail outright — preserve current failure behavior).++**Verify:**+```bash+grep -n "companyIntegration\|exchange-rates-v1" packages/jobs/src/inngest/functions/scheduled/update-exchange-rates.ts+# Expected: 0 hits+grep -n "from(\"currency\")" packages/jobs/src/inngest/functions/integrations/paperless-parts.ts+# Expected: 0 hits+pnpm exec turbo run typecheck --filter=@carbon/jobs+# Expected: exit 0+```++**Out of scope:** other scheduled jobs; Inngest event names (none added/removed).++## Task 11: Delete the exchange-rates integration from @carbon/ee++**Depends on:** Task 10 (the client class must be moved first)+**Files:**+- Delete: `packages/ee/src/exchange-rates/` (both files).+- Modify: `packages/ee/src/index.ts` — remove the `ExchangeRates` import (~line 2) and its entry in the `integrations` array (~line 35).+- Modify: `packages/ee/src/plan.ts` — remove `"exchange-rates-v1"` from `INTEGRATION_WHITELIST` (~line 31).+- Modify: `packages/ee/package.json` — remove the `./exchange-rates.server` export subpath.++**Verify:**+```bash+grep -rn "exchange-rates" packages/ee/src/ packages/ee/package.json+# Expected: 0 hits+grep -rn "@carbon/ee/exchange-rates.server" --include="*.ts" apps packages+# Expected: 0 hits+pnpm exec turbo run typecheck --filter=@carbon/ee+# Expected: exit 0+```++**Out of scope:** other integrations; `hooks.server.ts` (exchange-rates never had hooks).++## Task 12: Seed paths + backup scoping pins++**Depends on:** Task 4+**Files:**+- Modify: `packages/database/supabase/functions/lib/seed.data.ts` (~484): remove `exchangeRate: 1` from every entry of `currencies` (keep code/decimalPlaces/createdBy).+- Modify: `packages/database/supabase/functions/seed-company/index.ts` (~335): the insert maps the slimmed rows — verify no explicit `exchangeRate` reference remains.+- Modify: `packages/database/src/datasets/bootstrap.ts` (~300): drop `"exchangeRate"` from the INSERT column list and values.+- Modify: `packages/jobs/src/backups/scope.test.ts` (~278): `currency` stays `companyGroupId`-scoped; ADD pins — `exchangeRate` as a non-tenant reference table (mirror how `currencyCode` is classified in that file) and `exchangeRateOverride` as `companyId`-scoped. If `currencyCode` has no explicit pin there, follow whatever mechanism the test uses for global tables; if none exists, STOP and check how `pnpm db:check:backups` classifies `exchangeRate` before inventing a pattern.++**Verify:**+```bash+grep -rn "exchangeRate" packages/database/supabase/functions/lib/seed.data.ts packages/database/src/datasets/bootstrap.ts+# Expected: 0 hits+pnpm --filter @carbon/jobs test -- scope+# Expected: scope tests pass+```++**Out of scope:** dataset tier files (they don't write currency — verified in research).++## Task 13: UI — exchange-rates page: resolved rates, provenance, overrides++**Depends on:** Task 5+**Files:**+- Modify: `apps/erp/app/routes/x+/accounting+/exchange-rates.tsx` — loader calls `getExchangeRates(client, companyId)` (company-resolved list) instead of `getCurrencies`.+- Modify: `apps/erp/app/routes/x+/accounting+/exchange-rates.$currencyId.tsx` — loader: config row via `getCurrency` + resolved rate via `getExchangeRate` + history via reworked `getExchangeRateHistory`; action: two intents — `override` (validate `exchangeRateOverrideValidator` → `upsertExchangeRateOverride`) and `reset` (→ `deleteExchangeRateOverride`); config-field edits (decimalPlaces, historicalExchangeRate, customFields) keep going through `currencyValidator` → `upsertCurrency`. Keep the `clientAction` cache invalidation exactly as-is (`currenciesQuery` setQueryData null).+- Modify: `apps/erp/app/modules/accounting/ui/ExchangeRates/ExchangeRateForm.tsx` and the table component in the same directory:+ - Copy from (precedent): the existing files themselves — keep layout/structure; change data wiring only.+ - Rate field: shows the resolved rate; editing + submit creates the override; a provenance `Badge` (grep `packages/react/src` for `Badge`) shows "Market rate" / "Your rate" / "Base currency"; a "Reset to market rate" button (renders only when source is `override`) posts the `reset` intent.+ - Base-currency row: rate displayed as 1, input disabled (server-true now — the resolver returns 1).+ - Keep the helper text "One {base} is equal to how many {code}?".+ - History chart: feed it the global-store rows (market line).+ - All new user-facing strings marked for i18n per the house pattern (`useLingui().t` / `<Trans>`).+- Modify: `apps/erp/app/utils/path.ts` — only if a new route path is needed (none expected; overrides post to the existing `$currencyId` route).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp+# Expected: exit 0 (this is the first task after which erp must be green)+```++**Out of scope:** document forms/refresh buttons (unchanged UI); new routes.++## Task 14: Full scoped validation++**Depends on:** Tasks 5–13+**Steps:**+1. `pnpm exec turbo run typecheck --filter=erp --filter=@carbon/jobs --filter=@carbon/ee --filter=@carbon/database` — expect exit 0.+2. `pnpm run lint` — expect no new errors (Biome).+3. `pnpm run test` — expect suites green (notably `@carbon/jobs` scope tests).+4. Global sweep asserts:++**Verify:**+```bash+grep -rn "\.exchangeRate ?? 1\|\.exchangeRate || 1" apps/erp/app/modules apps/erp/app/routes packages/database/supabase/functions/convert packages/database/supabase/functions/create packages/jobs/src+# Expected: 0 hits+grep -rn "from(\"currency\")" apps/erp/app/modules apps/erp/app/routes | grep -v "currencyCode"+# Expected: only config reads (getCurrency/getCurrencies/upsertCurrency in accounting service) — no rate consumers+```++## Task 15: Dataset + backup pre-commit gates++**Depends on:** Task 14+**Steps:**+1. `pnpm db:check:datasets` — all four datasets apply (the seed no longer writes `exchangeRate`).+2. `pnpm db:check:backups` — restore verdict OK with the `exchangeRateHistory` rename entry and new tables classified.++**Verify:**+```bash+pnpm db:check:datasets+# Expected: exit 0, all datasets apply + roll back+pnpm db:check:backups+# Expected: exit 0 verdict (not a refusal)+```++## Task 16: Browser verification (/test)++**Depends on:** Task 15+**Steps:** Run the `/test` skill against the running local stack (`crbn up`, portless). Flows, minimum:+1. `/x/accounting/exchange-rates` — list renders resolved rates with provenance badges; base currency shows 1.+2. Edit a foreign rate → badge flips to "Your rate"; reset → back to "Market rate".+3. Create a quote for a customer with a foreign currency → header `exchangeRate` stamps a real (≠1) rate; refresh button re-resolves.+4. Sales invoice: change header rate via refresh → line rates follow (new trigger).+5. Settings → Integrations: no Exchange Rates card.++**Verify:** /test pass/fail table — all five flows pass. Screenshots captured for the PR.++## Task 17: Docs sync (carbon-docs)++**Depends on:** Task 14+**Steps:** Using the `carbon-docs` skill, update the docs site page(s) that describe+exchange rates/currencies/integrations (search `docs/content` for "exchange rate"):+rates are automatic for every company; manual overrides + reset; the integration no+longer exists. Ground every claim in the shipped code.++**Verify:**+```bash+grep -rn "exchange rate" docs/content --include="*.mdx" -il | head+# Expected: the touched pages; docs build passes (pnpm --filter docs build) if content changed+```++---++## Appendix A — bootstrap snapshot (units of currency per 1 USD, approx. 2026-09)++USD 1, EUR 0.92, GBP 0.79, JPY 155, CHF 0.88, CAD 1.36, AUD 1.52, NZD 1.64, CNY 7.2,+HKD 7.8, TWD 32, KRW 1350, SGD 1.34, INR 84, IDR 15800, MYR 4.6, PHP 57, THB 35,+VND 25000, BRL 5.5, MXN 18.5, ARS 1000, CLP 950, COP 4100, PEN 3.8, UYU 40, BOB 6.9,+PYG 7500, VES 40, ZAR 18, EGP 48, NGN 1550, KES 130, GHS 15, MAD 10, TND 3.1, DZD 135,+LYD 4.9, ETB 120, TZS 2600, UGX 3700, XOF 600, XAF 600, MUR 46, BWP 13.5, ZMW 26,+MZN 64, AOA 850, SEK 10.5, NOK 10.7, DKK 6.9, ISK 138, PLN 4.0, CZK 23, HUF 360,+RON 4.6, BGN 1.8, RSD 108, ALL 93, MKD 57, BAM 1.8, MDL 18, UAH 41, BYN 3.3, RUB 95,+TRY 34, GEL 2.7, AMD 390, AZN 1.7, KZT 480, KGS 87, UZS 12700, TJS 10.6, TMT 3.5,+AED 3.67, SAR 3.75, QAR 3.64, KWD 0.31, BHD 0.376, OMR 0.385, JOD 0.709, ILS 3.7,+LBP 89500, IQD 1310, IRR 42000, AFN 70, PKR 278, BDT 120, LKR 300, NPR 134, MMK 2100,+KHR 4100, LAK 21800, MNT 3450, BND 1.34, FJD 2.25, PGK 3.9, WST 2.7, TOP 2.35,+XPF 109, JMD 156, TTD 6.8, BBD 2, BSD 1, BZD 2, XCD 2.7, AWG 1.79, ANG 1.79, DOP 60,+HTG 132, CUP 24, GTQ 7.75, HNL 24.7, NIO 36.8, CRC 520, PAB 1, SVC 8.75, GYD 209,+SRD 36, KYD 0.82, BMD 1, CVE 101, GMD 68, GNF 8600, LRD 195, SLL 22000, SLE 22,+STN 22.5, SZL 18, LSL 18, NAD 18, MWK 1730, RWF 1350, BIF 2900, DJF 178, ERN 15,+SOS 570, SDG 600, SSP 1300, CDF 2800, KMF 452, SCR 13.5, MGA 4500, MVR 15.4, BTN 84,+YER 250, SYP 13000, HRK 6.9, VUV 119, SBD 8.4, MOP 8.03, BAT 35, GIP 0.79, FKP 0.79,+SHP 0.79, IMP 0.79, JEP 0.79, GGP 0.79, EEK 14.4, LTL 3.18, LVL 0.65, ZWL 6100++Amendment (2026-09-02, execute Task 1): seed.data.ts carries two obsolete codes absent+above — VEF 4000000 (VES 40 × 100000 redenomination) and ZMK 26000 (ZMW 26 × 1000).+Added with successor-peg conversions rather than invented values.++(Executor: match against `seed.data.ts` codes; drop appendix entries whose code is not in+`currencyCode`; STOP if a seed code has no appendix entry. Values are a bootstrap+fallback overwritten by the first feed run — approximate is acceptable, 1.0 is not.)diff --git a/.ai/playbooks/exchange-rate-overrides.md b/.ai/playbooks/exchange-rate-overrides.mdnew file mode 100644index 0000000000..aeb8412bb9--- /dev/null+++ b/.ai/playbooks/exchange-rate-overrides.md@@ -0,0 +1,45 @@+# Exchange Rate Overrides (platform-global rates + per-company overrides)++Last tested: 2026-09-02+Route: /x/accounting/exchange-rates (+ /$currencyId drawer)++## Background (currency-exchange-rate-refactor)+- Rates are platform-global, USD-anchored, seeded (118 rows in `exchangeRate`), on by default — no integration.+- The `currency.exchangeRate` column and `exchangeRateHistory` table are dropped; `exchange-rates-v1` integration is gone.+- Resolver `get_exchange_rate(companyId, code)`: base → 1, override → override rate, else market ratio r(code)/r(base); errors if unresolvable (never falls back to 1).+- Per-company `exchangeRateOverride` rows always beat the market feed; delete = back to market.++## Prerequisites+- Company base currency seeded (Carbon Development = USD).++## Steps+### 1. List — /x/accounting/exchange-rates+- Columns: Name, Code, Exchange Rate, **Source**, Actions.+- Base currency (USD) row: rate `1`, source badge "BASE CURRENCY".+- Foreign currencies: resolved rate + "MARKET RATE" badge (e.g. EUR 0.92, GBP 0.79, CAD 1.36).++### 2. Create an override+- Open a foreign currency's drawer (click the row link, or navigate to /$currencyId).+- Drawer shows: Exchange Rate field ("One {base} is equal to how many {code}?"), source badge, "Save Rate" button, and "Market Rate History (per USD)" chart.+- Fill the Exchange Rate field, **blur** (click the Name field to commit the react-aria value), then click **"Save Rate"**.+- Result: redirect to list; the row shows the new rate with a **"YOUR RATE"** badge; a row appears in `exchangeRateOverride` (createdBy = current user); resolver returns the override.++### 3. Reset to market rate+- Re-open the drawer (the "Reset to market rate" button only renders when an override exists).+- Click **"Reset to market rate"** → override row deleted; badge returns to "MARKET RATE"; resolver returns the market ratio again.++### 4. Positivity guard+- Setting the rate to 0 (or negative) and clicking "Save Rate" fails with "Rate must be positive" (zod), no override written. DB also has CHECK (rate > 0).++### 5. Document stamping (core behavior)+- New quote in base currency (USD) stamps `quote.exchangeRate = 1`.+- Changing a quote's currency to a foreign code re-stamps the header via the resolver: EUR → 0.92 (market), or the override rate if one exists — never 1.++## Selector Notes+- Rate field is a react-aria number input (empty `name`; value committed on blur). `agent-browser fill` + click-away usually commits it; if flaky, focus via DOM and type. Verify the visible value updated BEFORE clicking Save Rate.+- Drawer refs shift when the "Reset to market rate" button is present (override exists) — re-snapshot to get fresh refs.+- Currency combobox on quote detail: click to open, then type into the "Search..." input to filter (options are virtualized; they don't all render up front). Select the filtered option.++## Common Failures+- Saving without blurring the rate field commits the OLD displayed value (looks like a no-op override at the market rate). Always confirm the visible value changed first.+- Seeding a `Stock Only`-style non-effect: base currency always resolves to 1 and shows "BASE CURRENCY" — pick a FOREIGN currency to see override behavior.diff --git a/.ai/research/2026-09-02-currency-architecture.md b/.ai/research/2026-09-02-currency-architecture.mdnew file mode 100644index 0000000000..0606fae2bd--- /dev/null+++ b/.ai/research/2026-09-02-currency-architecture.md@@ -0,0 +1,595 @@+# Currency Architecture — `currency` table + companyGroupId scoping++Research ahead of the currency refactor. Core problem under investigation: `currency` is+scoped to `companyGroupId`, so an exchange rate is normalized once per company group — but+each company in a group has its own `company.baseCurrencyCode`, so "exchange rate to base"+is ill-defined at group scope whenever the group's companies disagree on base currency.++All paths are relative to repo root unless absolute. Line numbers are as of branch+`currency-exchange-rate-refactor` (conductor worktree `hat-yai`) @ `ed0bdebd95`+(2026-09-02).++---++## 1. Schema++### 1.1 `currency` — DDL history++| Migration | Change |+|---|---|+| `packages/database/supabase/migrations/20230330024715_accounts.sql:1-24` | Created `currency` with `companyId`, `name`, `symbol`, `isBaseCurrency`, `exchangeRate NUMERIC(20,8) NOT NULL DEFAULT 1` (CHECK > 0), `decimalPlaces INTEGER NOT NULL DEFAULT 2`, `active`, unique `("code","companyId")`, RLS via legacy `has_role`/`has_company_permission`. |+| `20240930183906_currency-codes.sql:1-141` | Created reference table `currencyCode(code PK, name, symbol)` (ISO seed list); FK `currency.code → currencyCode.code`; **dropped** `currency.name`, `currency.symbol`, `currency.isBaseCurrency` (lines 137-140). Added `company.baseCurrencyCode TEXT NOT NULL` FK → `currencyCode` (lines 142-154, backfilled `'USD'`). |+| `20241008201834_remove-currency-symbol-column.sql` | `currencies` view redefinition after symbol removal. |+| `20241010193506_quote-order-presentation-currency.sql:110-119` | RLS rework (accounting_view SELECT policy), dropped INSERT/DELETE policies; added document `exchangeRate` snapshot columns (see §5). |+| `20241119015113_tags.sql` | Added `tags TEXT[]`. |+| `20241210140215_rls-performance.sql:390` | Rewrote SELECT policy for performance. |+| `20250728114226_xid-to-uuid.sql` | id default change. |+| **`20260228023426_company-groups.sql:325-341`** | **The scope flip**: added `companyGroupId TEXT NOT NULL` (backfilled from `company.companyGroupId`), **dropped `companyId`**, FK → `companyGroup(id) ON DELETE CASCADE`, unique `currency_code_key ("code","companyGroupId")`, index `currency_companyGroupId_idx`. |+| `20260315000002_exchange-rate-history.sql:60` | Added `historicalExchangeRate NUMERIC(20,8)` (IAS 21 equity translation), plus the `exchangeRateHistory` table (see §1.4). |++### 1.2 Current shape (generated types, `packages/database/src/types.ts:8899-8996`)++```+currency: {+ id string (PK, single column — NOT the usual ("id","companyId") composite)+ code string → FK currencyCode(code)+ companyGroupId string → FK companyGroup(id) ON DELETE CASCADE [NOT NULL]+ exchangeRate number NUMERIC(20,8) NOT NULL DEFAULT 1, CHECK > 0+ historicalExchangeRate number | null (manual, for equity translation)+ decimalPlaces number INTEGER NOT NULL DEFAULT 2+ active boolean+ tags string[] | null+ customFields Json | null+ createdBy/createdAt, updatedBy/updatedAt+}+UNIQUE ("code", "companyGroupId") ← one row per currency code per GROUP+```++There is deliberately no `name`/`symbol` (live on `currencyCode`) and no+`isBaseCurrency` flag — "base" is knowable only via `company.baseCurrencyCode`, i.e.+**per company**, while the row itself is per group.++The `currencies` VIEW (`20260228023426_company-groups.sql:924-928`) is+`currency INNER JOIN currencyCode ON code` (SECURITY_INVOKER), adding `name`.++### 1.3 RLS (current, `20260228023426_company-groups.sql:866-894`)++- `SELECT`: `companyGroupId = ANY(get_company_groups_for_employee())` — employee of ANY+ member company of the group can read.+- `INSERT`/`UPDATE`/`DELETE`: `companyGroupId = ANY(get_company_groups_for_root_permission('accounting_create|update|delete'))`+ — writes require the accounting permission on the group's **root company**+ (`parentCompanyId IS NULL`).+- Helpers defined at `20260228023426_company-groups.sql:65-160`:+ `get_company_groups_for_employee()` (maps the user's employee companies →+ their groups; also handles the API-key path via `get_company_id_from_api_key()`)+ and `get_company_groups_for_root_permission(permission)`.++### 1.4 `companyGroup` / `company` relationship++- `companyGroup` table: `20260228023426_company-groups.sql:10-25`. Service-role only+ (RLS enabled, **no** user policies). `company` gained `companyGroupId` (FK, `ON DELETE+ SET NULL`), `parentCompanyId`, `isEliminationEntity`, `active`+ (lines 27-43).+- Backfill created **one group per existing company** (lines 45-59); new companies get a+ group at creation (see §3/§6 — `seedCompanyGroup` path). So today groups are almost+ always 1:1 with companies; multi-company groups arise when a second company is created+ under an existing owner (`apps/erp/app/routes/x+/settings+/companies.new.tsx` /+ onboarding, which attach the new company to the creator's existing group — see §6.3).+- Group-scoped base tables in the current schema (have `companyGroupId`, no `companyId`):+ `account`, `currency`, `dimension`, `dimensionValue`, `exchangeRateHistory`,+ `intercompanyTransaction` (from `packages/database/src/types.ts`, tables containing+ `companyGroupId`; views: `accounts`, `companies`, `currencies`, `dimensionValues`,+ `journalLinesByAccountNumber`). Operational tables (e.g. `accountDefault`) keep+ `companyId` and reference group-scoped rows by id.+- App-side resolution: `requirePermissions` returns `companyGroupId` alongside+ `companyId` (`packages/auth/src/services/auth.server.ts:345, 358, 419`); it lives in the+ auth session, set at company selection via `updateCompanySession(request, companyId,+ companyGroupId)` (`packages/auth/src/services/session.server.ts:455-476`), and for API+ keys via the embed `...company(companyGroupId)` (`auth.server.ts:128`).++### 1.5 `exchangeRateHistory` (`20260315000002_exchange-rate-history.sql:1-57`)++`(currencyCode, effectiveDate, companyGroupId)` unique; daily spot rates, group-scoped,+RLS mirroring `currency`. Consumed by `translateTrialBalance()` (same file, lines 78+;+newest version `20260811123614_widen-ledger-amounts.sql:260-333`): Closing = latest+history rate ≤ period end, Average = AVG over period, Historical =+`currency.historicalExchangeRate` — all fetched **per group**, while the function reads+the subsidiary's own `company.baseCurrencyCode` as source currency+(`20260811123614:269-270`). It computes `translatedBalance = localBalance * rate`+(`20260811123614:325-329`) — i.e. it treats the stored rate as **target units per source+unit**, which is the INVERSE of the `currency.exchangeRate` convention ("foreign per+base", §2.2). Since `exchangeRateHistory` has no writers (§3.1) and+`historicalExchangeRate` is free-text user input with no direction stated in the form+(`ExchangeRateForm.tsx:174-181`), this direction contradiction has never been forced into+the open — but any refactor that starts populating history must pick a direction and+reconcile the multiply.++---++## 2. Base currency & what `exchangeRate` means++### 2.1 Where base currency lives++- `company.baseCurrencyCode TEXT NOT NULL` FK → `currencyCode(code)` —+ `20240930183906_currency-codes.sql:142-154`. Per **company**, not per group. There is no+ group-level base currency column anywhere.+- `getBaseCurrency(client, companyId)`+ (`apps/erp/app/modules/accounting/accounting.ee.service.ts:1813-1837`) is the canonical+ helper: read `company.baseCurrencyCode` + `company.companyGroupId`, then select the+ `currency` row by `(code, companyGroupId)`. I.e. "the base currency" is a **group-scoped+ row selected by a company-scoped code**.+- `getBaseCurrencyDecimalPlaces(client, companyId, companyGroupId)`+ (`accounting.ee.service.ts:1917-1938`) — same two-step, returns settlement decimals for+ GL/fixed-asset rounding (falls back to 2).++### 2.2 Semantics of `currency.exchangeRate`++**`exchangeRate` = units of THIS (foreign) currency per 1 unit of the base currency**, and+the base currency's own row is expected to hold `exchangeRate = 1`. Evidence:++- The updater: `ExchangeRatesClient.convertExchangeRates(baseCurrencyCode, rates)`+ (`packages/ee/src/exchange-rates/exchange-rates.server.ts:68-91`) re-bases the EUR-based+ API rates so `converted[base] = 1` and `converted[X] = rates[X]/rates[base]` — foreign+ per base.+- Document math: `quoteLinePrice.convertedUnitPrice GENERATED ALWAYS AS ("unitPrice" *+ "exchangeRate")` (`20241010193506_quote-order-presentation-currency.sql:122-127`) —+ `unitPrice` is in base currency, multiply by the snapshot to get the presentation+ (customer/supplier) currency amount. Same for `salesOrderLine` (lines 148-150) and the+ purchasing equivalents.+- Inverse direction (foreign → base) is division: e.g. `translateTrialBalance`+ (`20260315000002:…`, `translatedBalance = localBalance / rate`), and the posting flows+ divide document-currency amounts by the document's snapshot `exchangeRate` to book base+ currency GL amounts (see §4).++So "the" rate is only meaningful **relative to a chosen base**. Because the row is+group-scoped, the whole group shares one normalization — whichever company's+`baseCurrencyCode` the rate updater used (§3) — and for a group whose companies have+different base currencies, every company except that one reads rates normalized to a base+that is not its own. The base-currency row for such a company will not even be 1.++### 2.2a The convention is pinned by UI copy, per viewer++`ExchangeRateForm.tsx:93-96` renders the helper text+`"One ${company.baseCurrencyCode} is equal to how many ${code}?"` and clamps the rate to 1+when `code === company.baseCurrencyCode` (:166-167) — but `company` here is the **viewing+user's** company (`useUser()`), while the row is group-shared. Two admins in different+companies of the same group see the same row described against two different bases, and+each sees a different code clamped to 1. Nothing server-side enforces the base row = 1+invariant at all.++### 2.3 One row per code per group++Yes — `currency_code_key UNIQUE ("code","companyGroupId")`+(`20260228023426_company-groups.sql:339`). There is no per-company row and no way to store+two normalizations for one group.++---++## 3. Writes — every insert/update of `currency`++There are exactly **six** write paths (five code + one migration backfill). No create-currency+UI exists (`path.to.newExchangeRate` is defined at `apps/erp/app/utils/path.ts:1484` but there+is no `exchange-rates.new.tsx` route); rows are created only by the seed paths.++| # | Path | Kind | Op | Scoping | Rate source |+|---|------|------|----|---------|-------------|+| 1 | `apps/erp/app/modules/accounting/accounting.ee.service.ts:3696-3720` `upsertCurrency` | shared service helper | insert (3712) / update (3714-3719) by `id` | `companyGroupId` in payload | caller |+| 2 | `apps/erp/app/routes/x+/accounting+/exchange-rates.$currencyId.tsx:43-81` (calls `upsertCurrency` at :59) | route action, `update: "accounting"` | UPDATE only (`if (!id) throw`, :57) | `companyGroupId` from `requirePermissions` (:45) | **user input** (`ExchangeRateForm`) |+| 3 | `packages/jobs/src/inngest/functions/scheduled/update-exchange-rates.ts:219-221` | Inngest cron `0 0 * * *`, service role | `.upsert(updates)` of full rows | reads `company.companyGroupId` (:171), selects all group rows (:177-180) | **external API** (EUR-base `exchangeratesapi.io`, `EXCHANGE_RATES_API_KEY`) |+| 4 | `packages/database/supabase/functions/seed-company/index.ts:335-338` | edge function, Kysely txn | insert — **only when `isNewGroup`** (:334, group resolution :83-123) | `companyGroupId` | **hardcoded 1** for all 118 codes (`functions/lib/seed.data.ts:484`) |+| 5 | `packages/database/src/datasets/bootstrap.ts:300-306` | dev seed / `db:check:datasets` (raw SQL) | insert | `companyGroupId` created in `seedCompanyReferenceData` (:130-134) | **hardcoded 1** |+| 6 | `packages/database/supabase/migrations/20260228023426_company-groups.sql:327-330` | one-time backfill | UPDATE set `companyGroupId` from `company` | — | n/a |++Details worth keeping in the refactor's head:++- **The daily job is where the group-vs-base contradiction becomes live data churn.**+ `updateExchangeRatesFunction` iterates active `companyIntegration` rows+ (`id = "exchange-rates-v1"`, :79-83), reads *that company's* `baseCurrencyCode` (:153),+ converts the EUR-based API rates to that base+ (`convertExchangeRates`, `packages/ee/src/exchange-rates/exchange-rates.server.ts:68-91`,+ cached per base :130-166), and then **upserts the whole group's rows** (:177-221). Two+ companies in one group, both with the integration active, different bases → the same+ group-shared rows are rewritten twice per night with two different normalizations;+ iteration order is the unordered `companyIntegration` select, so which base "wins" is+ arbitrary. With one integration-enabled company, the group's rows are stably normalized+ to that one company's base — and every *other* company in the group silently consumes+ rates relative to a base that may not be its own.+- The job overrides only `exchangeRate` (+`updatedAt`) — `historicalExchangeRate`,+ `decimalPlaces`, `active` are preserved (spread of the existing row, :197-206). Codes+ missing from the API response are filtered out (falsy rate, :206) and left stale.+- Seed rows are all `exchangeRate: 1` until a human edits them or the integration runs —+ so a fresh company's foreign-currency documents all snapshot rate 1.+- Subsidiaries joining an existing group get **no** currency seed (path 4 skipped) — they+ inherit the group's rows, normalized to whatever base the group already uses.+- `upsertCurrency`'s update branch passes through `sanitize()`; fields written from+ `currencyValidator` (`accounting.models.ts:416-424`): `code`, `decimalPlaces`,+ `exchangeRate`, `historicalExchangeRate`, `customFields`. The form's "base currency"+ behavior (`ExchangeRateForm.tsx:93,166-167` — clamps rate to 1 when+ `code === company.baseCurrencyCode`) is **client-side only**; nothing persists an+ `isBaseCurrency` flag (the column is gone) and nothing server-side enforces base rate = 1.++### 3.1 `exchangeRateHistory` — zero writers++Despite its own comment ("daily spot rates auto-populated by sync job",+`20260315000002_exchange-rate-history.sql:1-2`), **nothing writes this table** — not the+daily job (writes only `currency`), not a trigger, not a seed. Verified by grepping all+migrations and TS for inserts/updates. Its readers therefore always fall back:++- `translateTrialBalance` RPC (`20260315000002:117-141`, re-created in+ `20260713225803_ledger-balance-posted-filter.sql:204,212` and+ `20260811123614_widen-ledger-amounts.sql:288,296`) — closing/average rates+ `COALESCE(..., 1)`.+- `getExchangeRateHistory` (`accounting.ee.service.ts:4735-4750`) — feeds the (empty)+ history chart in `ExchangeRateForm` via `exchange-rates.$currencyId.tsx:32-34`.++---++## 4. Reads — every consumer++Note: the `currencies` VIEW is `currency ⋈ currencyCode` (§1.2), so every read of the view+is a read of the table. The overarching rule that fell out of the sweep:++> **Every document flow reads the live rate exactly once — at creation / currency change /+> explicit refresh — and stamps it onto the document. Posting, PDFs, EE sync, and list+> views all consume the snapshot.** The only always-live consumers at read time are the+> consolidation-rates RPC and the nightly rate-updater job itself.++### 4.1 Service helpers (`apps/erp/app/modules/accounting/accounting.ee.service.ts`)++| Fn | Line | Source | Scoping | Live/snapshot |+|---|---|---|---|---|+| `getBaseCurrency` | 1813 | table | `companyId` → (`baseCurrencyCode`, `companyGroupId`) → row by `(code, group)` | live |+| `getCurrency` | ~1901 | table (`*, currencyCode!inner(name)`) | by `id` only — **unscoped**, RLS is the only tenant filter | live |+| `getBaseCurrencyDecimalPlaces` | 1917 | view, `decimalPlaces` | `companyId` + `companyGroupId` args | decimals only |+| `getCurrencyByCode` | 1940 | view | `(code, companyGroupId)` | live |+| `getCurrencies` | 1953 | view | `companyGroupId` | live (admin list) |+| `getCurrenciesList` | 1982 | `currencyCode` ⟕ view (`code, decimalPlaces`) | view side by `companyGroupId` | decimals only |++### 4.2 `getCurrencyByCode` callers — the live-rate → snapshot stamping sites++All pass `companyGroupId` from `requirePermissions` (post-PR-#1525 pattern):++- **Quote**: `sales.service.ts:3519` (create), `:3651`, `:3732`, `:3828` (currency change /+ convert) → written to `quote.exchangeRate` at `:3525, :3657, :3738, :3834` (base → 1 at `:3742`).+- **Sales order**: `sales.service.ts:5327, 5441, 5600, 5660` → `salesOrder.exchangeRate`+ at `:5333, 5447, 5606, 5666` (base → 1 at `:5670`).+- **Purchase order / supplier quote**: `purchasing.service.ts:1508, 1609, 1696` (PO),+ `:2077, 2182, 2235, 2321` (supplier quote).+- **Invoices**: `invoicing.service.ts:568, 729` (purchase invoice), `:946, 1107` (sales invoice).+- **Route actions/loaders** (currency-change actions, "Update Exchange Rate" buttons,+ finalize, PDF preflight):+ `x+/quote+/update.tsx:70`, `x+/quote+/$quoteId.exchange-rate.tsx:39`,+ `x+/quote+/$quoteId.tsx:124`;+ `x+/purchase-order+/$orderId.exchange-rate.tsx:51`, `x+/purchase-order+/update.tsx:60,122`,+ `x+/purchase-order+/$orderId.tsx:282,508`, `x+/purchase-order+/$orderId.finalize.tsx:340`;+ `x+/purchase-invoice+/$invoiceId.tsx:79`, `x+/purchase-invoice+/$invoiceId.exchange-rate.tsx:51`,+ `x+/purchase-invoice+/update.tsx:56,137`;+ `x+/sales-order+/$orderId.exchange-rate.tsx:35`, `x+/sales-order+/update.tsx:49,77`;+ `x+/supplier-quote+/$id.tsx:63` (serviceRole), `x+/supplier-quote+/update.tsx:73`;+ `x+/sales-invoice+/$invoiceId.tsx:80`, `x+/sales-invoice+/update.tsx:55`;+ `modules/settings/documentPreview.server.ts:252` (quote PDF preview) and+ `modules/shared/shared.server.ts:289` (SO preview — reads the row for `decimalPlaces`,+ serviceRole).++### 4.3 Other helper callers++- `getBaseCurrency` → `x+/accounting+/_layout.tsx:42` (accounting module layout).+- `getCurrency` → `x+/accounting+/exchange-rates.$currencyId.tsx:31` (edit drawer).+- `getCurrencies` → `x+/accounting+/exchange-rates.tsx:29` (admin table).+- `getBaseCurrencyDecimalPlaces` → `x+/accounting+/depreciation-runs.new.tsx:115` and+ `x+/depreciation-run+/$depreciationRunId.repeat.tsx:151` (base-currency GL rounding+ scale for depreciation, consumed by `accounting.utils.ts:285,336,426,453,464,521`).+- `getCurrenciesList` → `api+/accounting.currencies.ts:12` — the endpoint behind+ `useCurrencies`.++### 4.4 Hooks / UI (decimals only — no hook reads `exchangeRate`)++- `apps/erp/app/hooks/useCurrencies.ts:27` `useCurrencies()` — fetches+ `api+/accounting.currencies.ts` (group-scoped `getCurrenciesList`); rows are+ `{code, name, decimalPlaces}` where `decimalPlaces` is the **group's** configured value+ (null when the group hasn't configured that code).+- `useCurrencyDecimalsLookup` (:50) / `useCurrencyDecimals` (:73) — `code → decimalPlaces`+ map, CLDR fallback; the settlement-scale source for money inputs/tables.+- `useCurrencyMinDecimals` (:90) — company settings, not the currency table.+- `apps/erp/app/hooks/useCurrencyFormatter.tsx:46,58` — digits via `useCurrencyDecimals`;+ base-currency default from route data `company.baseCurrencyCode` (a code string).+- `apps/erp/app/components/MotionMoney.tsx:10-51`, `components/Form/TaxFields.tsx:28-153` —+ take `decimalPlaces`/`currencyDecimals` props resolved upstream from the same map.+- `x+/purchasing+/planning.update.tsx:413` (decimals read from `currencies` view at+ `:177-182`, mapped `:237`) → `applyRate` settlement rounding.++### 4.5 Posting / edge functions (`packages/database/supabase/functions/`)++**No posting function reads the `currency` table — all consume document snapshots**+(their `companyGroupId` usage is for dimensions/accounts, not currency):++- `post-receipt/index.ts:625` — `purchaseOrder.exchangeRate` snapshot.+- `post-shipment/index.ts` — no currency read.+- `post-purchase-invoice/index.ts:566,842` — `purchaseInvoice.exchangeRate` snapshot.+- `post-sales-invoice/index.ts:317` — `salesInvoice.exchangeRate` snapshot.+- `post-payment/index.ts:230,296,407,716` — `payment.exchangeRate` + applied documents'+ snapshot rates (:681,690).+- `post-memo/index.ts:207,268` — `memo.exchangeRate` snapshot.+- `get-method/index.ts:6875,6962` — copies the source quote's snapshot.++**Edge functions that DO read the live table (to stamp a new document):**++- `convert/index.ts:1084` — RFQ→quote: `currency` by `(code, companyGroupId)` (group from+ `company` row); throws for a foreign currency with no configured rate rather than+ quoting at par (:1089-1095).+- `create/index.ts:541` — outside-operation → PO: `currency` by `(code, companyGroupId)`+ per supplier currency (group resolved at :531); `exchangeRate ?? 1`.++### 4.6 SQL / RPC live reads++- `getConsolidationRates` (`20260713225803_ledger-balance-posted-filter.sql:219-222`,+ re-defined `20260811123614_widen-ledger-amounts.sql:303-306`) — reads+ `currency.historicalExchangeRate` by `(code, companyGroupId)`; called from+ `translateCompanyBalances` (`accounting.ee.service.ts:4296`) → consolidation reports+ (`x+/reports+/balance-sheet.tsx:167`, `income-statement.tsx:142`, `executive-pnl.tsx:143`).+ **Live, group-scoped, at report time.**+- `translateTrialBalance` (§1.5) — live `currency.historicalExchangeRate` ++ (empty) `exchangeRateHistory`.++### 4.7 `packages/ee` accounting sync (Xero / QBO / Rillet)++**No EE provider reads the `currency` table.** They use document `currencyCode` strings ++snapshot rates:++- `packages/ee/src/accounting/core/payment-syncer.ts:525,686,715`,+ `core/payment-application.ts:35,256,284,322` — `payment.exchangeRate` snapshot.+- `core/document-costing.ts:62` — base→transaction conversion using the passed document rate.+- Rillet `providers/rillet/entities/shared.ts:210-221` `loadCompanyBaseCurrency` — reads+ `company.baseCurrencyCode` (per company, correct), not the table.+- Xero `provider.ts:338` — currencies from the Xero org API.++### 4.8 `packages/documents` (PDFs)++PDFs never read the table — `exchangeRate` and `currencyDecimals` arrive as props from+loaders (`QuotePDF.tsx:20,38,45,56,64,110,118,134,188`; `SalesOrderPDF.tsx:39,56,62,65`;+`PurchaseOrderPDF.tsx:39,55,62,65`; `SalesInvoicePDF.tsx:38,57,63,66`;+`blocks/SummaryBlock.tsx:89`, `blocks/quote/LineItemsBlock.tsx:40,120,128,225`,+`utils/sales-invoice.ts:86`). The table read happens upstream (e.g.+`shared.server.ts:289`).++### 4.9 `packages/jobs`++- `inngest/functions/integrations/paperless-parts.ts:808-820` — **local duplicate**+ `getCurrencyByCode` reading `currency.exchangeRate` by `(companyGroupId, code)`; stamps+ imported `quote.exchangeRate` at `:327`. Live read → snapshot.+- `inngest/functions/scheduled/update-exchange-rates.ts:177-180` — the writer's own+ read-modify-write (§3).+- `backups/scope.test.ts:278` — pins `currency` as `companyGroupId`-scoped for backup export.++### 4.10 MES / academy / starter++**Zero currency-table reads** in `apps/mes`, `apps/academy`, `apps/starter` (no+`from("currency")`, `getCurrencyByCode`, `getBaseCurrency`, `useCurrencies`).++### 4.11 Views++Only the `currencies` view joins the table. The document list views (`quotes`,+`salesOrders`, `purchaseOrders`, `purchaseInvoices`, `salesInvoices`, `supplierQuotes`)+surface their **own snapshot columns**, never a live currency join.++---++## 5. Document snapshot `exchangeRate` columns++Every document header snapshot means "**document-currency units per 1 base-currency+unit**"; line-level `converted*` amounts are STORED generated columns multiplying by it.+`exchangeRateUpdatedAt` exists only on the six document **headers**.++| Table | Columns | Added by | Set on create / currency change | Explicit refresh | Header→line propagation |+|---|---|---|---|---|---|+| `quote` | `currencyCode`, `exchangeRate`, `exchangeRateUpdatedAt` | `20241010193506:3-4` | `upsertQuote` `sales.service.ts:3516-3549`; `updateQuote` `:3635-3674`, convert `:3731-3743, 3819-3835` | `updateQuoteExchangeRate` `sales.service.ts:3215-3228`; route `x+/quote+/$quoteId.exchange-rate.tsx:47`; MCP `sales_updateQuoteExchangeRate` | interceptor `sync_update_quote_exchange_rate` `20260410031804_exchange-rate-interceptors.sql:17-36` |+| `quoteLinePrice` | `exchangeRate` (default 1) + generated `convertedUnitPrice/NetUnitPrice/NetExtendedPrice` (`20241010193506:122-127`), `convertedShippingCost` (`20241105002325:30`) | `20241010193506:122` | seeded from quote at `sales.service.ts:4045` | — | via quote interceptor |+| `salesOrder` | `currencyCode`, `exchangeRate`, `exchangeRateUpdatedAt` | `20241010193506:35-36` | `upsertSalesOrder` `sales.service.ts:5314-5359`; update `:5425-5464, 5591-5607, 5659-5671` | `updateSalesOrderExchangeRate` `:3257-3270`; route `x+/sales-order+/$orderId.exchange-rate.tsx:43`; MCP | interceptor `sync_update_sales_order_exchange_rate` `20260410031804:38-57` |+| `salesOrderLine` | `exchangeRate` (default 1) + generated `convertedUnitPrice/AddOnCost` (`20241010193506:149-150`), `convertedShippingCost/NonTaxableAddOnCost` (`20260321120000:5`, `20260811123619:35-38`) | `20241010193506:148` | line seed `sales.service.ts:5826` | — | via SO interceptor |+| `purchaseOrder` | `currencyCode`, `exchangeRate`, `exchangeRateUpdatedAt` | orig. `20230924004608:303`; re-added `20241010193506:75-76` | `upsertPurchaseOrder` `purchasing.service.ts:1505-1538`; update `:1606-1625, 1695-1707`; copy-from-source `:149,167` | `updatePurchaseOrderExchangeRate` `:1166-1178`; route `x+/purchase-order+/$orderId.exchange-rate.tsx:59`; MCP | trigger `update_purchase_order_line_price_exchange_rate` (fn `20241210214820:131`, re-created `20260811123616:533-534`) |+| `purchaseOrderLine` | `exchangeRate` + generated `convertedUnitPrice/ShippingCost/AddOnCost` (`20250109000722:33-35`) | `20230924004608` era | via header trigger | — | (is the target) |+| `supplierQuote` | `currencyCode`, `exchangeRate`, `exchangeRateUpdatedAt` | `20241202192419:43` | `upsertSupplierQuote` `purchasing.service.ts:2074-2109`; update `:2166-2198, 2234-2246, 2305-2328` | `updateSupplierQuoteExchangeRate` `:1345-1357`; route `x+/supplier-quote+/$id.exchange-rate.tsx:47`; MCP | trigger `update_supplier_quote_line_price_exchange_rate` (fn `20241202192419:214`, re-created `20260811123616:545-546`) |+| `supplierQuoteLinePrice` | `exchangeRate` (default 1) + generated `unitPrice/extendedPrice/shippingCost` = supplier* × rate (`20241202192419:110-114`), `taxAmount` (`20241210214820:424`) | `20241202192419:109` | | | via trigger |+| `purchaseInvoice` | `exchangeRate` NOT NULL default 1, `exchangeRateUpdatedAt` | `20230924004608:24`; updatedAt `20241210214820:289` | `upsertPurchaseInvoice` `invoicing.service.ts:563-594, 728-756` | `updatePurchaseInvoiceExchangeRate` `:407-419`; route `x+/purchase-invoice+/$invoiceId.exchange-rate.tsx:59`; MCP | trigger fn `20241210214820:325`, **typo-fixed** `20260616061244_fix_purchase_invoice_line_trigger_exchange_rate_typo.sql:2-13`; + BEFORE INSERT inherit trigger `sync_purchase_invoice_line_exchange_rate_on_insert` (`20260616061244:27-43`); re-created `20260811123616:539-540` |+| `purchaseInvoiceLine` | `exchangeRate` (`20230924004608:144`) + converted generated cols (widened `20250109034107:18-23`) | | | | via triggers |+| `salesInvoice` | `currencyCode`, `exchangeRate` NOT NULL default 1, `exchangeRateUpdatedAt` | `20250507143421:40,46-47` | `upsertSalesInvoice` `invoicing.service.ts:941-972, 1106-1133` | `updateSalesInvoiceExchangeRate` `:452-464`; route `x+/sales-invoice+/$invoiceId.exchange-rate.tsx:56`; MCP | **NONE** — no trigger and no interceptor; lines get their rate only at service insert. Asymmetric with every other document. |+| `salesInvoiceLine` | `exchangeRate` (`20250507143421:146`) + generated `convertedUnitPrice/AddOnCost/ShippingCost/SetupPrice` (`:152-155`) | | | | (no propagation) |+| `payment` | `currencyCode`, `exchangeRate` NOT NULL default 1 CHECK > 0 | `20260630093809_ar-ap-payments.sql:203-204,232` | set at draft | none | n/a |+| `memo` | `currencyCode`, `exchangeRate` NOT NULL default 1 CHECK > 0 | `20260630093809:319-320,343` | set at draft | none | n/a |+| `invoiceSettlement` | `sourceExchangeRate`, `targetExchangeRate` (CHECK > 0) + generated `fxGainLossAmount = appliedAmount * (source - target)` STORED | `20260630093809:427-436,467-468` | captured at apply time from the payment/memo (source) and invoice (target) rows — `invoicing.service.ts:2378-2379, 1481-1482, 1649-1670`; never refreshed | — | n/a — the realized-FX primitive |++Tables **verified to carry no** rate/currency snapshot: `job`, `jobMaterial`,+`jobOperation`, `itemCost`, `receipt`, `shipment`, `salesRfq`, `purchaseOrderDelivery`+(receipts/shipments inherit currency context from their parent document; production+costing is base-currency via `itemCost`/cost ledger).++Related master data: `account.consolidatedRate` enum (Current/Average/Historical,+`20260315000002:62-71`) selects which rate class `translateTrialBalance` applies per+account.++---++## 6. Group-vs-company mismatch sites++### 6.1 The fixed precedent — PR #1525 (merge `01c43cfd4b`)++`fix(accounting): resolve quote currency by company group, not dropped companyId` —+one file, `packages/database/supabase/functions/convert/index.ts`. The RFQ→quote path was+still filtering `from("currency").eq("companyId", companyId)` **after**+`20260228023426` dropped that column. PostgREST errored, `currency.data` was undefined,+and `?? 1` silently quoted every foreign-currency customer at par. The fix: filter by+`company.data.companyGroupId`, and throw on a missing rate unless the code IS the+company's base (where 1 is correct by definition).++Two failure classes to grep for in future work:+1. **Stale scope column** — `from("currency")` + `.eq("companyId", …)`: swept the repo;+ **no remaining instances** (only `convert` had it).+2. **Silent par fallback** — `?? 1` after a currency read that can fail. Still present at+ `packages/database/supabase/functions/create/index.ts:541` (outside-op → PO stamps+ `exchangeRate ?? 1` without #1525's refuse-on-missing guard) and in the service-layer+ creation flows (`sales.service.ts`, `purchasing.service.ts`, `invoicing.service.ts` —+ `currency.data?.exchangeRate ?? 1` variants).++### 6.2 The live mismatch: the nightly rate updater (worst site)++`packages/jobs/src/inngest/functions/scheduled/update-exchange-rates.ts` (§3) — rates are+normalized to **each integration-enabled company's** `baseCurrencyCode` (:153,:161-165)+but written to the **group's** shared rows (:177-221). One group, two companies, two+bases, both enabled → the group's rows are overwritten twice nightly with incompatible+normalizations, in the arbitrary order of the `companyIntegration` select. Every snapshot+stamped from those rows (§4.2) inherits whichever normalization was live at that moment.+The structural root: `companyIntegration` is **company**-scoped while `currency` is+**group**-scoped — the integration loop and the rows it writes disagree on tenancy grain.++**A fix already exists but is NOT on this branch**: commit `b4d30d3ca3`+(`fix(jobs): rebase exchange rates once per company group, not once per company`), on+`origin/fix/exchange-rate-job-group-scoping` only. It groups the integrations by+`companyGroupId`, rebases once per group, and **refuses with an error naming the group+and the conflicting codes when member companies disagree on base currency** — plus two+smaller fixes (warn on feed-omitted codes that silently keep stale rates; set+`updatedBy` on the upsert). Its commit message states the design premise the refactor+must confirm or replace: "Nothing in the schema records a group-level base currency, and+`getBaseCurrency` resolves a company's base against the group's shared rows, so the model+already assumes one base per group."++### 6.3 How multi-company groups arise (i.e., when this stops being theoretical)++- Group creation: `seed-company` edge function+ (`packages/database/supabase/functions/seed-company/index.ts:82-121`) — a root company+ creates its own `companyGroup`; a company created with `parentCompanyId` **joins the+ parent's group** (:87-97). Subsidiary creation route:+ `apps/erp/app/routes/x+/settings+/companies.new.tsx:83`.+- Nothing constrains a subsidiary's `baseCurrencyCode` to match the parent's — the whole+ point of the consolidation feature (`translateTrialBalance`,+ `translateCompanyBalances`) is that they can differ. So "companies in a group with+ different bases" is a **supported product configuration** whose currency rates are+ structurally under-specified.++### 6.4 Per-company semantics leaking through group-shared rows++- `ExchangeRateForm` (§2.2a) — helper text and the rate=1 clamp are computed from the+ *viewer's* `company.baseCurrencyCode` against a group-shared row+ (`ExchangeRateForm.tsx:93-96,166-167`). No server-side invariant.+- `getBaseCurrency(client, companyId)` (`accounting.ee.service.ts:1813`) — resolves the+ company's base code to the group row; for a company whose base differs from the group's+ normalization base, that row's `exchangeRate` is not 1 and nothing flags it.+- Creation flows force `exchangeRate = 1` when the document currency equals the+ *company's* base (`sales.service.ts:3742, 5670` etc.) — correct per company — but take+ the group rate verbatim for any foreign currency, which is only correct when the group's+ normalization base == this company's base.+- `translateCompanyBalances` / `getConsolidationRates`+ (`accounting.ee.service.ts:4267-4340`; RPC first defined+ `20260713225803_ledger-balance-posted-filter.sql:179-233`, newest+ `20260811123614:303-306`) — rates are looked up by+ `(sourceCurrency = company base, companyGroupId)` only; `targetCurrency` participates+ in nothing but the `sameCurrency → 1` short-circuit (:4318-4331). The stored rate is+ implicitly "target per source" for exactly one target — whichever base the group's rates+ were normalized to. Translating to any other `targetCurrency` silently applies a rate+ for the wrong pair.+- **The root company's base is the de-facto group base — by caller convention only.** All+ four consolidated reports compute `targetCurrency` as the ROOT company's+ `baseCurrencyCode` (`companiesList.find(c => !c.parentCompanyId)`):+ `x+/reports+/trial-balance.tsx:69-70,89-93`, `income-statement.tsx:74-75,102-106`,+ `balance-sheet.tsx:95-96,123-127`, `executive-pnl.tsx:75-76,103-107`. Nothing persists+ or validates this convention — the schema has no group-level base currency column, and+ the nightly job (§6.2) doesn't honor it either (it rebases to whichever *member* has+ the integration).+- **Intercompany defers conversion to consolidation.** `intercompanyTransaction` stores+ the source company's base as its `currencyCode`+ (`modules/accounting/ui/Intercompany/IntercompanyTransactionForm.tsx:157-166`);+ `createIntercompanyTransaction` (`accounting.ee.service.ts:4596-4688`) posts+ source-company journal lines with no cross-base conversion at capture. Correctness of+ the eventual elimination therefore rests entirely on the group-scoped rates above.+- A subsidiary picks its own base at creation+ (`modules/settings/ui/Companies/SubsidiaryCompanyForm.tsx:45`) — nothing warns that the+ group's shared rates will not be normalized to it.+- RLS nuance for API keys: the legacy API-key ALL policy on `currency`+ (`20240821150639_api-key-all-tables.sql:56-59`) was dropped in+ `20250201181148_rls-refactor.sql:1175`. Post-groups, API-key SELECT works through+ `get_company_groups_for_employee()` (honors the key's company,+ `20260228023426:77-85`), but API-key **writes** to group-scoped tables are impossible —+ `get_company_groups_for_root_permission` ignores the API-key path.++### 6.5 Adjacent inconsistencies the refactor should sweep up++- `translateTrialBalance` multiplies where the `exchangeRate` convention implies dividing+ (§1.5) — the direction of `historicalExchangeRate` / `exchangeRateHistory.rate` is+ undefined because no producer exists and the form never states it.+- `exchangeRateHistory` has **no writers** (§3.1) — closing/average consolidation rates+ are always the `COALESCE(..., 1)` fallback today.+- `salesInvoice` lacks the header→line rate propagation every sibling document has (§5).+- The form helper text "Leave blank to use the current exchange rate"+ (`ExchangeRateForm.tsx:180`) does not match the RPC fallback (historical → closing →+ 1, never `currency.exchangeRate`).+- `getCurrency(client, currencyId)` (`accounting.ee.service.ts:~1901`) reads by bare `id`+ with RLS as the only tenant guard — fine today, but any move of currency back to+ company scope must revisit the RLS-only assumption (group SELECT policy exposes rows to+ every member company's employees).++---++## 7. Structural observations for the refactor++1. **The blast radius of changing `currency`'s scope is small and choke-pointed; the+ blast radius of changing `exchangeRate`'s *meaning* is large.** Only ~6 write paths+ and ~6 service helpers touch the table, and effectively every document flow funnels+ through `getCurrencyByCode`/`getBaseCurrency` (§4.1-4.2) plus two edge functions+ (`convert`, `create`) and one jobs-package duplicate (`paperless-parts.ts:808`).+ Re-scoping the table means touching those. But the *snapshot* columns (§5) already+ insulate posting, PDFs, EE sync, and views from the table — historical documents keep+ working whatever happens to the master rows. The refactor's semantic risk concentrates+ in: the stamping sites, the nightly job, and consolidation.++2. **The missing concept is "base of normalization".** Every rate in the system is+ relative to *some* base, but that base is recorded nowhere: not on `currency` (no+ `isBaseCurrency` since `20240930183906`), not on `companyGroup` (no base column), only+ implicitly in (a) whichever company's base the nightly job last used, (b) the root+ company's base assumed by the report callers, and (c) the viewer's base shown by the+ form. Options are: per-company currency rows (revert of `20260228023426`'s Part 4c),+ a persisted `companyGroup.baseCurrencyCode` with a one-base-per-group invariant+ (the direction `b4d30d3ca3` leans), or base-agnostic pair/history storage. Whichever+ is chosen, `unique("code", scope)` and the RLS policies move with it.++3. **Decimals and rates want different scopes.** `decimalPlaces` is a property of a+ currency (JPY has 0 everywhere) and is consumed far more widely than the rate+ (`useCurrencies` → every money input; `getBaseCurrencyDecimalPlaces` → GL rounding) —+ group-sharing it is harmless. `exchangeRate` is a property of a currency *pair* and is+ what breaks at group scope. A refactor can split them rather than move both.++4. **Three latent defects should ride along**: (a) `exchangeRateHistory` has no writer+ (§3.1) while consolidation already reads it — the nightly job is the natural producer;+ (b) the multiply-vs-divide direction contradiction between `currency.exchangeRate`+ ("foreign per base", form text `ExchangeRateForm.tsx:96`) and `translateTrialBalance`+ / `translateCompanyBalances` (`balance * rate`) must be pinned when history gains a+ producer; (c) the `?? 1` par-fallbacks in `create/index.ts:541` and the service+ creation flows lack #1525's refuse-on-missing guard.++5. **Merge order matters**: `origin/fix/exchange-rate-job-group-scoping` (`b4d30d3ca3`)+ hard-codes the "one base per group, refuse on disagreement" stance into the nightly+ job. If the refactor instead legitimizes per-company bases within a group, that fix+ is the first thing it must supersede — land one or the other, not both silently.++6. **`currency` is one of only six group-scoped base tables** (`account`, `currency`,+ `dimension`, `dimensionValue`, `exchangeRateHistory`, `intercompanyTransaction`) and+ the backup scoping map pins it (`packages/jobs/src/backups/scope.test.ts:278`).+ Re-scoping touches: RLS helpers (§1.3), the seed paths (§3 #4-5), backup/restore+ scoping, and the `currencies` view — plus `pnpm db:check:backups` /+ `db:check:datasets` will both exercise it pre-commit.++---++## Appendix: verification notes++- Branch at research time: `currency-exchange-rate-refactor` (worktree `hat-yai`),+ HEAD `ed0bdebd95`. PR #1525's merge (`01c43cfd4b`) **is** an ancestor;+ `b4d30d3ca3` is **not** (verified `git merge-base --is-ancestor`).+- Generated types read directly at `packages/database/src/types.ts:8899-8996` — the+ `currency` Row has NO `name`/`symbol`/`isBaseCurrency`/`companyId`.+- Stale-filter sweep (`from("currency")`/`from("currencies")` near `.eq("companyId"`)+ returned zero hits; no Kysely `selectFrom/updateTable("currency")` outside+ `seed-company` and `bootstrap.ts`.+- Findings compiled with four parallel sub-investigations (writes, reads, snapshots,+ mismatches); every line number above spot-checked or taken from direct file reads of+ the load-bearing sites (`update-exchange-rates.ts`, `convert` diff,+ `translateTrialBalance` newest version, `ExchangeRateForm`, `seed-company`,+ `accounting.ee.service.ts` helpers).diff --git a/.ai/research/2026-09-02-exchange-rate-pr-audit.md b/.ai/research/2026-09-02-exchange-rate-pr-audit.mdnew file mode 100644index 0000000000..971ce7be11--- /dev/null+++ b/.ai/research/2026-09-02-exchange-rate-pr-audit.md@@ -0,0 +1,386 @@+# Exchange-Rate PR Audit — BettrCallRaul, 2026-08-31..2026-09-02++Audit of 12 currency/exchange-rate bug-fix PRs, treated as symptoms of the architecture+about to be refactored: `currency` scoped to `companyGroupId` (while companies in a group+can have different base currencies), and exchange rates populated only by an integration+(so rates are missing/stale/1.0 by default).++Root-cause classes:+- **(a)** currency/rates normalized to `companyGroupId` while group members have different base currencies+- **(b)** rates only exist via integration → missing/stale/1.0 defaults+- **(c)** document-level `exchangeRate` snapshot vs live currency-table rate confusion+- **(d)** direction confusion (multiply vs divide; rate is foreign-per-base)+- **(e)** missing rate propagation (header→line, document→PDF/email/sync payload)+- **(f)** validation gaps (0/negative/null/unchecked errors)+- **(g)** other — two named recurring "others": **(g1)** `(currencyCode, exchangeRate)` not treated as an atomic pair; **(g2)** dual parallel column families (base `unitPrice` vs `converted*`/`supplier*` generated mirrors) with no type-level distinction, making wrong-column selection invisible++## Summary table++| PR | State | Symptom | Root-cause class | Recommendation |+|----|-------|---------|------------------|----------------|+| #1549 | OPEN | Reprinting a quote after the rate cron ran mixed two rates on one PDF: lines at the quote's snapshot, header shipping/charges at today's live rate; total reconciled to neither | **(c)** primary; (b) enabling (`let exchangeRate = 1` + live lookup) | **Merge first**; refactor subsumes under a "document snapshot always wins on documents" contract |+| #1548 | OPEN | Sales-order and PO emails printed the BASE unit price labelled with the document currency; qty × unit ≠ line total on the same row, sent to customers/suppliers | **(e)** primary; (g2) enabling | **Merge first** (wrong numbers leaving the building); refactor subsumes if column families get typed |+| #1547 | OPEN | EUR invoice on USD-base company synced to Xero/Rillet with USD amounts declared as EUR; provider revenue/AR/FX all wrong by the rate | **(e)** primary; (g2) enabling; (d) appeared and was reverted mid-branch (CurrencyRate inversion) | **Merge first**; refactor must generalize — PR itself names the same defect still open in Xero SO/PO, QBO invoice/bill/PO/payment, Rillet bill |+| #1544 | OPEN | Foreign-currency receipts with header shipping capitalised cost wrong by rate² into `costLedger` + weighted-average item cost (multiply instead of divide) | **(d)** | **Merge first** (irreversible valuation corruption); refactor subsumes via to-base/from-base helpers |+| #1543 | OPEN | Supplier part prices prefilled into PO/invoice lines wrong by rate² (SEK 1,290 instead of SEK 162,980) — divided base→supplier where multiply was correct, then divided again on price breaks | **(d)** primary; (g2) enabling (`supplierPart` price columns have no currency column — implicitly base) | **Merge first**; refactor subsumes by giving stored prices an explicit currency |+| #1542 | OPEN | Group with companies on different base currencies + active integrations: nightly job rebased the SHARED currency rows once per company; last writer won, rates flipped nightly | **(a)** primary; (b) is the delivery mechanism | **Refactor supersedes** — this enforces exactly the invariant (one base per group) the refactor must decide; merge only as a stopgap if the refactor is weeks out |+| #1541 | OPEN | A typed/imported 0 or negative rate saved silently; 0 zeroes every sales `converted*` column, purchasing substitutes par | **(f)** | **Merge first, refactor keeps** — DB CHECKs on 12 document tables survive any re-architecture |+| #1532 | OPEN | Sales invoice summary multiplied the base-stored header shipping by the rate on the BASE side, overstating the base total | **(d)** (converted a value already in base); (g2) enabling | **Merge first**; one line, independent of everything else |+| #1530 | OPEN | Crafted POST to any of six `*.exchange-rate` routes stamps another currency's rate onto a document that keeps its own code (SEK rate on a USD invoice) | **(g1)** primary; (f) (trusting client input); (c) adjacent (defines "refresh" semantics) | **Merge after #1526** (stacked on its `resolveCurrencyAndRate`); refactor subsumes the resolver |+| #1527 | OPEN | Refreshing a sales invoice rate updated the header only; lines (and their `converted*` columns) kept stale rates; PDF total existed at no rate; new lines stranded at DEFAULT 1 | **(e)** (header→line cascade missing on 1 of 6 documents) | **Merge first**; refactor may supersede if line-level rates are eliminated — flag "rate 1 = unset" tradeoff as a design input |+| #1526 | OPEN | Six bulk-update routes set `currencyCode` without `exchangeRate`: party reassignment kept rate 1 (foreign customer quoted at par); the `currencyCode` case fell through to the generic setter | **(g1)** primary; (b) (missing rate → fabricate 1); (f) | **Merge first**; refactor absorbs `resolveCurrencyAndRate` as the seed of the new currency service |+| #1525 | MERGED | RFQ→Quote for a foreign-currency customer silently quoted at par: currency lookup still filtered on the DROPPED `companyId` column, error unchecked, `?? 1` | **(a)** primary; (f) (unchecked error); (b) (default-to-1) | Merged. Refactor should sweep for remaining stale per-company assumptions on group-scoped tables |++## Per-PR detail++### #1549 — fix(sales): print the quote PDF at the quote's own exchange rate (OPEN)++1. **Symptom**: One quote PDF mixed two exchange rates. Line amounts render from `converted*`+ generated columns (baked at the quote's stored rate); header shipping and add-on charges+ were converted at the LIVE currency-table rate. The moment the daily cron moved the+ currency, the total reconciled to neither, and reprinting an old quote silently changed it.+2. **Proximate cause**: `apps/erp/app/routes/file+/quote+/$id[.]pdf.tsx` initialized+ `let exchangeRate = 1` and overwrote it from `getCurrencyByCode(...)` instead of reading+ `quote.data.exchangeRate`. Fix: rate comes from the quote; the currency row is read only+ for `decimalPlaces`.+3. **Root cause class**: **(c)** snapshot-vs-live confusion. (b) is the enabling condition —+ a live-table lookup only exists because the rate wasn't trusted to be on the document.+ PR notes the quote PDF was the only `file+` route passing a scalar rate (16 audited).+4. **Fix shape**: Point patch, correct direction. Merge first. The refactor should encode the+ contract this patch implies: on a document surface, the document's snapshot rate ALWAYS+ wins; the currency table is for defaults at creation and metadata (decimals).+5. **Files**: `apps/erp/app/routes/file+/quote+/$id[.]pdf.tsx` (+6/−4).++### #1548 — fix(documents): email the line unit price in the currency the email is formatted in (OPEN)++1. **Symptom**: `SalesOrderEmail` printed `salesOrderLine.unitPrice` (BASE) under the+ customer's currency label while the adjacent line total summed `convertedUnitPrice` —+ qty × unit price ≠ total on the same row. `PurchaseOrderEmail` printed the generated base+ `unitPrice` under the supplier's currency while its total summed `supplierUnitPrice`.+ These are externally sent.+2. **Proximate cause**: The formatter's currency was fixed in all three emails at some point;+ the amount column was fixed in only one (`SalesInvoiceEmail` already used+ `convertedUnitPrice`). Fix: each email formats the same column its own total helper sums+ (`convertedUnitPrice` / `supplierUnitPrice`), plus switches unit prices from the money+ formatter to a rate formatter (per the numeric-precision rate-vs-money kinds), and tests+ `!= null` instead of falsiness so zero-priced lines print.+3. **Root cause class**: **(e)** document→email payload propagation, enabled by **(g2)** —+ two parallel column families with identical types make wrong-column picks silent.+4. **Fix shape**: Point patch. Merge first. The refactor subsumes only if it types the column+ families (e.g. branded Money<Base> vs Money<Doc> at select time) or collapses them.+5. **Files**: `packages/documents/src/email/PurchaseOrderEmail.tsx`,+ `SalesOrderEmail.tsx`, `SalesInvoiceEmail.tsx` (+42/−7).++### #1547 — fix(accounting): push AR invoice amounts in the currency the payload declares (OPEN)++1. **Symptom**: Foreign-currency AR invoices synced to Xero and Rillet with base-currency+ line amounts under the document's `CurrencyCode` — a EUR invoice on a USD-base company+ ships USD numbers labelled EUR; provider revenue, AR balance and realised FX are wrong by+ the rate.+2. **Proximate cause**: Both syncers selected/pushed `unitPrice` (base). Fix selects+ `convertedUnitPrice` with fallback to `unitPrice` when null (base-currency invoices).+ Notably, an earlier commit on the same branch ALSO inverted Xero's `CurrencyRate` on a+ wrong premise and was reverted — Xero's `CurrencyRate` is foreign-per-base, same as+ Carbon's; it passes through unchanged, and is omitted (not 1) on base-currency invoices.+3. **Root cause class**: **(e)** document→sync payload, enabled by **(g2)**. The reverted+ inversion is a live demonstration of **(d)** — even the fixer got the direction wrong once.+4. **Fix shape**: Point patch + unit tests (6/6 Xero invoice suite, 3 new FX cases). Merge+ first, but the PR itself documents the same defect still open in: Xero sales-order and+ purchase-order pushes, QuickBooks invoice/bill/PO/payment mappings, Rillet bill. QBO's+ `ExchangeRate` genuinely IS base-per-foreign and is currently written un-inverted. The+ refactor must define ONE payload contract ("every amount on a payload is in the currency+ the payload declares; each provider adapter owns its rate direction") rather than+ letting each entity syncer re-derive it. Not verified against a live Xero org (no sandbox).+5. **Files**: `packages/ee/src/accounting/core/models.ts`,+ `providers/rillet/entities/invoice.ts`, `providers/xero/entities/invoice.ts` (+ tests)+ (+123/−5).++### #1544 — fix(inventory): divide receipt header shipping to base, don't multiply (OPEN)++1. **Symptom**: Every foreign-currency PO receipt carrying header shipping capitalised the+ wrong number by rate² — weighted across receipt lines into the cost-ledger layer value,+ per-piece cost, and Inventory/GR-IR journal, dragging weighted-average item cost with it.+ No later journal correction repairs `costLedger`.+2. **Proximate cause**: `post-receipt/index.ts:623` computed+ `supplierShippingCost * exchangeRate`; supplier→base is DIVIDE (rate is+ foreign-per-base). The codebase already knew: `post-purchase-invoice/index.ts:559`+ divides with an explanatory comment, and migration `20260702061504` is literally titled+ "Fix supplierShippingCost currency conversion: divide, not multiply" — it fixed the views+ but not this edge function.+3. **Root cause class**: **(d)**. Third occurrence of the exact same expression bug in the+ codebase's history — direction is re-derived at every call site.+4. **Fix shape**: Point patch (also hardens `?? 1` to `|| 1` against rate 0). Merge first —+ this is active valuation corruption. Refactor supersedes the PATTERN (a `toBase()` /+ `fromBase()` helper pair so no call site ever writes `* rate` or `/ rate` raw) but not+ this fix.+5. **Files**: `packages/database/supabase/functions/post-receipt/index.ts` (+9/−2).++### #1543 — fix(purchasing): convert supplier part prices to the supplier's currency, not away from it (OPEN)++1. **Symptom**: Adding a supplier part to a foreign-currency PO/purchase invoice prefilled a+ unit price wrong by rate² (verified: SEK 1,290.04 where SEK 162,980 was correct — 126×+ understatement). The generated base column then derives from the wrong supplier price, so+ receiving creates cost layers at the wrong magnitude.+2. **Proximate cause**: `supplierPart.unitPrice` / `supplierPartPrice.unitPrice` are stored+ in BASE (no currency column on either table). The target field `supplierUnitPrice` is+ supplier-currency, so base→supplier is MULTIPLY; both line forms divided, and+ `resolveSupplierPrice` divided AGAIN on the price-break path. Fix: `resolveSupplierPrice`+ takes base inputs, returns supplier-currency output, callers hand it raw base; the+ `fallbackUnitPrice` initializer (seeded from a supplier-currency value into a base-meaning+ field) now divides to base explicitly.+3. **Root cause class**: **(d)**, enabled by **(g2)** — a price table whose currency is+ implicit (base by convention, no column) guarantees somebody converts the wrong way.+4. **Fix shape**: Point patch that also documents the contract in `resolveSupplierPrice`'s+ JSDoc — a small step toward architecture. Merge first. The refactor should give supplier+ price rows an explicit currency (or an explicit "always base" branded type).+5. **Files**: `apps/erp/app/modules/shared/shared.service.ts` (shared helper — check for+ other callers), `purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx`,+ `invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx` (+30/−14).++### #1542 — fix(jobs): rebase exchange rates once per company group, not once per company (OPEN)++1. **Symptom**: A company group whose members use different base currencies, with the+ exchange-rate integration active on more than one member: the nightly job rebased the+ SHARED group-scoped `currency` rows once per company, each overwriting the last. Rates+ flipped every night; the same document's converted totals changed day to day.+2. **Proximate cause**: `currency` is group-scoped (`20260228023426`) but `companyIntegration`+ is company-scoped; the job iterated integrations and rebased to each company's own+ `baseCurrencyCode`. Fix: group active integrations by `companyGroupId`, resolve the base+ once, rebase once, write once; REFUSE (log + throw after healthy groups complete) when a+ group's members disagree on base currency. Also: warns on feed-omitted currencies (silent+ staleness), sets `updatedBy`.+3. **Root cause class**: **(a)** — this is the purest expression of the architectural flaw:+ nothing in the schema records a group-level base currency, yet the shared rate rows can+ only express one. **(b)** is the delivery mechanism (rates only move when the integration+ job runs). The PR itself states: "That assumption was just never enforced where the rates+ are written."+4. **Fix shape**: Half-architecture: it enforces one-base-per-group by refusal at ONE writer,+ but the invariant remains unrecorded in the schema. **The refactor supersedes this** —+ whichever way the refactor goes (per-company currency rows, or a schema-level group base+ currency), this job gets rewritten. Merge only as a stopgap if the refactor is weeks out;+ if merged, note its refusal policy (throw after healthy groups) is temporary behavior the+ refactor must consciously keep or replace. Not executed end-to-end (needs+ `EXCHANGE_RATES_API_KEY` + live provider); decision logic exercised against the real schema.+5. **Files**: `packages/jobs/src/inngest/functions/scheduled/update-exchange-rates.ts`+ (+99/−39).++### #1541 — fix(accounting): refuse a non-positive exchange rate at every layer (OPEN)++1. **Symptom**: A zero (or negative) exchange rate could be typed or imported and saved+ silently. Zero zeroes every sales `converted*` generated column (no zero-guard);+ purchasing's columns substitute 1, silently pricing a foreign document at par.+2. **Proximate cause**: `currency` has had `CHECK ("exchangeRate" > 0)` since 2023, and+ `payment`/`memo` since 2026-06 — but all 12 document tables were missed. The zod schema+ said `.min(0)` ("Rate is required"), and the form's `minValue={0}` CLAMPED a typed 0 to+ the step (0.00001) on blur instead of refusing. Fix: CHECK on all 12 tables (`> 0 AND+ <> 'NaN'`, NULL-tolerant where nullable, added NOT VALID + VALIDATE to avoid write-blocking+ locks), `.positive()` in zod, `minValue` unset for foreign currencies. NaN excluded+ explicitly because Postgres orders NaN above all finite values so `> 0` alone accepts it.+3. **Root cause class**: **(f)**. NULL deliberately left alone ("no rate set" is a different+ condition — a data decision for the refactor, not a schema one).+4. **Fix shape**: The most durable of the twelve — DB constraints survive any+ re-architecture. **Merge first; the refactor keeps it.** Interaction: its migration+ (`20260901161207`) validates `salesInvoiceLine.exchangeRate > 0` AFTER #1527's backfill+ migration (`20260901134416`) by timestamp order — fine if both merge, but if #1527 is+ dropped, verify no NULL/zero line rates exist before VALIDATE.+5. **Files**: migration `20260901161207_exchange-rate-positive-constraint.sql`,+ `apps/erp/app/modules/accounting/accounting.models.ts`,+ `accounting/ui/ExchangeRates/ExchangeRateForm.tsx` (+119/−4).++### #1532 — fix(invoicing): stop converting the base-currency shipping on the invoice summary (OPEN)++1. **Symptom**: Sales invoice summary's BASE-side shipping figure (and base total) was the+ stored base amount multiplied by the exchange rate — base total overstated (verified:+ €11,240 rendered where €1,000 was stored; total off by 10,240).+2. **Proximate cause**: `SalesInvoiceSummary` keeps two parallel families (base from raw+ columns, customer-facing from `converted*`); header shipping was computed identically —+ multiplied — in BOTH. `salesInvoiceShipment.shippingCost` is stored in base (the+ `salesInvoices` view adds it straight onto the base subtotal), so only the customer figure+ should convert. The purchasing sibling already did the mirror-image correctly.+3. **Root cause class**: **(d)** (converted a value that was already in the target currency),+ enabled by **(g2)**.+4. **Fix shape**: One-line point patch, explicitly independent of #1527 and the rest (no+ shared files). Merge first.+5. **Files**: `apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceSummary.tsx`+ (+5/−3).++### #1530 — fix(accounting): take the refresh rate from the document, not the request (OPEN)++1. **Symptom**: The six `*.exchange-rate` refresh routes read `currencyCode` from the posted+ form, looked up THAT currency's rate, and wrote only `exchangeRate` — a crafted POST could+ stamp SEK's 11.24 onto a USD invoice that keeps its USD code, mispricing every line via+ `converted*`. (The UI always posts the document's own code, so in practice it behaved as a+ refresh — the parameter carried no information the server didn't have.)+2. **Proximate cause**: Client-supplied currency trusted; code/rate pair splittable by+ construction. Fix: read the currency from the document (already loaded for the locked+ check), stop parsing the form entirely, resolve through `resolveCurrencyAndRate` so a+ refresh can't install a zero/missing rate.+3. **Root cause class**: **(g1)** pair atomicity, with **(f)** (trusting client input) and a+ **(c)** flavor — these routes are the ONE sanctioned place a live table rate overwrites a+ document snapshot, and this PR pins down that semantic.+4. **Fix shape**: Point patch **stacked on #1526** (uses its `resolveCurrencyAndRate`; branch+ needs retargeting to main once #1526 merges). Merge second. Refactor subsumes along with+ #1526's resolver. Post-fix runtime re-test of the SEK-onto-USD POST was not completed+ (browser extension disconnected); pre-fix repro was confirmed.+5. **Files**: six routes `apps/erp/app/routes/x+/{purchase-invoice,purchase-order,quote,sales-invoice,sales-order,supplier-quote}+/*.exchange-rate.tsx` (+60/−48).++### #1527 — fix(invoicing): cascade the sales invoice exchange rate to its lines (OPEN)++1. **Symptom**: `salesInvoice` was the only rate-bearing header (of six) with NO header→line+ cascade. Refreshing the rate or changing currency updated the header alone; lines — and+ every `converted*` column generated off them — stayed at creation-time rates. The PDF+ summed lines at line rates and header shipping at the header rate: a total that exists at+ no exchange rate. A line added after a rate change was stranded at the DEFAULT of 1.+2. **Proximate cause**: quote/salesOrder cascade via event interceptors; purchaseOrder/+ purchaseInvoice/supplierQuote via `AFTER UPDATE OF` triggers; salesInvoice had neither.+ Fix (migration only): backfill drifted lines, `AFTER UPDATE OF "exchangeRate"` cascade+ trigger, `BEFORE INSERT` inherit trigger — mirroring the purchaseInvoice pair exactly.+3. **Root cause class**: **(e)** header→line propagation gap. Underlying design smell for the+ refactor: lines carry their OWN `exchangeRate` at all, requiring 6 documents × 2 triggers+ of glue, and via 2 different mechanisms (interceptors vs triggers).+4. **Fix shape**: Point patch consistent with existing architecture; verified end-to-end+ locally. Merge first. **Known tradeoff inherited on purpose**: the insert trigger treats+ rate 1 as "unset", so a line can never deliberately hold rate 1 on a document whose header+ differs — the refactor should kill this ambiguity (NULL = unset, or drop line rates).+5. **Files**: migration `20260901134416_sales-invoice-rate-cascade.sql` (+61/−0).++### #1526 — fix(accounting): never write a document currency without its exchange rate (OPEN)++1. **Symptom**: Six bulk-update routes could set `currencyCode` and leave `exchangeRate`+ behind. Two paths: (1) party reassignment — quote/supplier-quote adopted the new+ customer's/supplier's currency and never touched the rate, so a quote reassigned to a+ foreign-currency customer kept rate 1 and every line stayed at the base price (and the+ cascade's `IS DISTINCT FROM` guard never fired since the rate value didn't change);+ (2) the `currencyCode` case falling through to the generic `[field]: value` setter in all+ six routes.+2. **Proximate cause**: Code and rate written independently, with `exchangeRate:+ currency.data?.exchangeRate ?? 1` fabricating par when the lookup found nothing. Fix: new+ `resolveCurrencyAndRate(client, companyGroupId, currencyCode)` in+ `accounting.ee.service.ts` resolves the pair together or refuses (also refuses 0,+ negative, Infinity), and stamps `exchangeRateUpdatedAt` so a set rate is distinguishable+ from never-set. Behaviour change: setting a currency with no configured rate now errors+ instead of silently writing rate 1 — unreachable via UI, a guard for CSV/API paths.+3. **Root cause class**: **(g1)** pair atomicity (the PR literally says "one value pair" —+ same doctrine as the taxPercent/amount pair in the numeric-precision rule), with **(b)**+ as the reason lookups come back empty (rates exist only where an integration or manual+ entry put them) and **(f)** for the `?? 1` fallback.+4. **Fix shape**: The most architectural of the app-layer PRs — `resolveCurrencyAndRate` is+ a single resolution point the refactor should absorb as the seed of its currency service+ (and extend to document creation paths, which still resolve independently). Merge first;+ #1530 stacks on it.+5. **Files**: `apps/erp/app/modules/accounting/accounting.ee.service.ts`, six routes+ `apps/erp/app/routes/x+/{purchase-invoice,purchase-order,quote,sales-invoice,sales-order,supplier-quote}+/update.tsx` (+300/−144).++### #1525 — fix(accounting): resolve quote currency by company group, not dropped companyId (MERGED)++1. **Symptom**: Every Sales RFQ → Quote conversion for a foreign-currency customer produced a+ quote at rate 1 (par), silently.+2. **Proximate cause**: `convert/index.ts` still filtered `currency` on `companyId` — a+ column DROPPED on 2026-02-28 when the table moved to group scoping. PostgREST rejected the+ filter, the error was never checked, and `?? 1` wrote par. Fix: filter on+ `companyGroupId` (matching `create/index.ts`), throw on lookup failure for non-base+ currencies (base is exempt — 1 is correct there by definition).+3. **Root cause class**: **(a)** — the group-scoping migration left a stale consumer behind+ for six months; **(f)** unchecked PostgREST error; **(b)**-flavored `?? 1` default. The PR+ swept the other two tables that moved in the same migration (`account`,+ `accountCategory`) — no other stale filters found.+4. **Fix shape**: Point patch, already merged and verified locally. For the refactor: this is+ the canary — any re-scoping of `currency` MUST include a sweep of every consumer+ (PostgREST errors on dropped-column filters are silent to callers that don't check+ `.error`), ideally plus a conformance check.+5. **Files**: `packages/database/supabase/functions/convert/index.ts` (+7/−1).++## Patterns across PRs++### Count per architectural suspect (primary / including secondary)++| Suspect | Primary | Incl. secondary | PRs |+|---------|---------|-----------------|-----|+| (a) group-scoping vs per-company base | 2 | 2 | #1542, #1525 |+| (b) integration-only rates → missing/1.0 defaults | 0 | 4 | #1526, #1525, #1549, #1542 (delivery mechanism) |+| (c) snapshot vs live rate | 1 | 2 | #1549; #1530 (defines refresh semantics) |+| (d) direction confusion (×/÷) | 3 | 4 | #1544, #1543, #1532; #1547 (reverted mid-branch) |+| (e) missing propagation (header→line, doc→PDF/email/sync) | 3 | 3 | #1527, #1548, #1547 |+| (f) validation gaps | 1 | 5 | #1541; #1526, #1530, #1525, #1542 (silent overwrite) |+| (g1) code/rate pair atomicity | 2 | 3 | #1526, #1530; #1527 (line rate drifts from header) |+| (g2) untyped dual column families (base vs converted/supplier) | 0 | 5 | #1548, #1547, #1532, #1543, #1544 (enabling condition) |++### Recurring defects, named++1. **The `?? 1` reflex** (#1525, #1526, pre-fix #1549, #1527's stranded DEFAULT 1, `|| 1` in+ #1544). Everywhere a rate can be missing, some call site fabricates par — the single most+ damaging silent failure mode, and a direct consequence of suspect (b): because rates only+ exist where an integration (or manual entry) put them, every consumer needs a fallback,+ and the fallback chosen is always 1. The refactor's highest-leverage move: make "no rate"+ an ERROR at resolution time, everywhere, with exactly one sanctioned exception (base+ currency = 1 by definition, per #1525). `resolveCurrencyAndRate` (#1526) is the seed.++2. **Direction is tribal knowledge** (#1544, #1543, #1532; #1547's reverted inversion).+ `currency.exchangeRate` is foreign-per-base, encoded in zero types and re-derived by hand+ at every call site — producing three rate² bugs and one near-miss inversion, including a+ repeat of an expression already fixed by name in migration `20260702061504`. Even the+ author of these fixes inverted Xero's rate once before reverting. The refactor should ship+ `toBase(amount, rate)` / `fromBase(amount, rate)` helpers (mirroring how+ `precision.ts` centralized rounding) and ban raw `* exchangeRate` / `/ exchangeRate` via a+ `@carbon/checks` conformance check.++3. **Untyped parallel column families** (#1548, #1547, #1532, #1543, #1544). Base+ `unitPrice`/`shippingCost` and their `converted*`/`supplier*` mirrors are all bare+ `number`; some tables (supplierPart) don't even have the mirror, storing base by unwritten+ convention. Five PRs are "picked the wrong sibling" or "converted the already-converted".+ Refactor options: branded types at the select layer, naming conventions enforced by a+ check, or collapsing to one stored currency + one conversion point per surface.++4. **(currencyCode, exchangeRate) is not atomic** (#1526, #1530, #1527). The pair can be+ split by bulk updates, crafted POSTs, and header-only refreshes — the exact "one value+ pair" doctrine the codebase already applies to taxPercent/taxAmount+ (`.claude/rules/numeric-precision.md`) but never applied to currency/rate. #1526's+ resolver plus #1527's cascade are the point-fix version; the refactor should make it+ structural (single write path, or DB-level coupling).++5. **The group-scoping half-migration** (#1525, #1542). `currency` moved to+ `companyGroupId` on 2026-02-28 with no group-level base currency to anchor it, and+ consumers/jobs were not swept: one edge function silently broke for six months (#1525),+ and the nightly job still rebased per company (#1542). This is the refactor's core+ question — either currency rows return to per-company scope, or the group grows an+ explicit base currency with #1542's one-base-per-group invariant enforced in the schema+ rather than in one job's refusal path.++6. **Propagation glue instead of a propagation design** (#1527, plus context). Six document+ headers cascade rates to lines via TWO different mechanisms (event interceptors for+ quote/salesOrder, DB triggers for the purchasing three + now salesInvoice), and one of six+ was simply missing for years. Every new rate-bearing document re-earns this bug. If lines+ kept no rate of their own, classes (e) and half of (g1) disappear.++### PR interactions and conflicts++- **#1530 is stacked on #1526** (uses `resolveCurrencyAndRate`; PR body says it needs+ retargeting to main once #1526 merges). Merge order: #1526 → #1530.+- **#1527 and #1541 are both migrations touching `salesInvoiceLine.exchangeRate`**. No file+ conflict; timestamp order (#1527 `20260901134416` before #1541 `20260901161207`) means+ #1527's backfill runs before #1541's `VALIDATE CONSTRAINT` — if #1527 is dropped or+ reordered, re-verify no non-positive/NULL line rates exist before #1541 validates. Also+ #1527's "rate 1 = unset" insert-trigger semantics and #1541's ">0" constraint are+ compatible today but both feed the refactor's "what does an unset rate mean" decision.+- **#1526 and #1541 overlap semantically** (both refuse rate ≤ 0: #1526 in the resolver and a+ route-level `exchangeRate` write guard; #1541 at zod + DB). Complementary layers, no file+ conflict.+- **#1547 and #1548 both change what sales-invoice line value goes out** (sync payload vs+ email) — consistent direction (`convertedUnitPrice`), no shared files.+- **#1543 changes `resolveSupplierPrice` in `shared.service.ts`**, a shared helper — the PR+ claims the two updated forms are the only callers; verify before merge.+- **#1532 explicitly shares no files with any other PR** in the set (per its own body,+ found while verifying #1527).+- **#1547 leaves the same defect open** in Xero SO/PO, QBO invoice/bill/PO/payment, and+ Rillet bill syncers — unfixed sibling work the refactor should fold in rather than+ awaiting six more point PRs.++### Verification caveats (for merge sequencing)++Fully verified end-to-end locally: #1525, #1543, #1532, #1527, #1526. Partially verified:+#1541 (DB layer exercised; zod layer unproven in isolation), #1530 (pre-fix repro confirmed,+post-fix runtime check outstanding), #1542 (decision logic against real schema; job not+fired). Reading-only: #1549 (quote PDF route has a PRE-EXISTING render crash on main —+`Cannot read properties of undefined (reading 'width')` — worth its own issue), #1548 (no+email harness), #1544 (declined to post into shared instance), #1547 (no Xero sandbox; PR+itself recommends a demo-org round-trip before merge).diff --git a/.ai/research/2026-09-02-exchange-rate-update-path.md b/.ai/research/2026-09-02-exchange-rate-update-path.mdnew file mode 100644index 0000000000..7c0377315c--- /dev/null+++ b/.ai/research/2026-09-02-exchange-rate-update-path.md@@ -0,0 +1,265 @@+# How exchange rates get updated today (the integration path to eliminate)++Researched 2026-09-02 on branch `currency-exchange-rate-refactor` (base = main @ `ed0bdebd95`).+All paths absolute under `/Users/barbinbrad/conductor/workspaces/carbon/hat-yai/`.++**Important branch caveat:** two open PRs touch exactly this area and are NOT in this+tree — #1542 `fix(jobs): rebase exchange rates once per company group, not once per+company` (commit `b4d30d3ca3`, branch `origin/fix/exchange-rate-job-group-scoping`) and+#1530 `fix(accounting): take the refresh rate from the document, not the request`+(commit `f8e3a386dd`, branch `origin/fix/exchange-rate-refresh-document-currency`).+Several sibling commits on those branches (`aec17de6ba`, `02a7ce60f0`, `4931842606`,+`deee8198af`, `1f3d0bb0e5`, `0328146b0c` — which add a `resolveCurrencyAndRate`+resolver) are likewise unmerged. Everything below describes the tree as it stands,+with the pending changes flagged inline.++---++## 1. The integration++- **Definition**: `packages/ee/src/exchange-rates/config.tsx:6-19` —+ `defineIntegration({ name: "Exchange Rates", id: "exchange-rates-v1", active: true,+ category: "Accounting", settings: [], schema: z.object({}) })`. **Zero settings, empty+ schema** — there is nothing to configure per company; installing it is a pure on/off+ toggle. (`defineIntegration` itself: `packages/ee/src/fns.ts:46+`.)+- **Registry**: imported and included in the `integrations` array at+ `packages/ee/src/index.ts:2` and `:35`.+- **Plan gating**: `packages/ee/src/plan.ts:29-33` — `INTEGRATION_WHITELIST` contains+ `"exchange-rates-v1"` (alongside `"email"`), so it bypasses the `INTEGRATIONS`+ Business/Partner plan gate and is available on every plan. I.e. it is already+ "free"; the only friction is that a user must find and install it.+- **API key is platform-level, not per-company**: `packages/env/src/index.ts:172` —+ `EXCHANGE_RATES_API_KEY` is a single global env var (listed under optional+ integration vars in `.claude/rules/environment-configuration.md`). Companies never+ supply a key.+- **Install path**: Settings → Integrations →+ `apps/erp/app/routes/x+/settings+/integrations.$id.tsx` action →+ `upsertCompanyIntegration` in+ `apps/erp/app/modules/settings/settings.server.ts:293-314`: upserts one+ **`companyIntegration`** row `{ id: "exchange-rates-v1", companyId, active: true,+ metadata: {} }` with `onConflict: "id,companyId"`. Table:+ `packages/database/supabase/migrations/20240119095150_integrations.sql:26-34`+ (PK `("id","companyId")` — **company-scoped**, which matters in §2).+- **No lifecycle hooks**: `packages/ee/src/hooks.server.ts` registers hooks for+ email/jira/linear/onshape/quickbooks/etc. — nothing for exchange-rates. Enabling it+ creates **no `eventSystemSubscription`**, no vault secret, nothing but the+ `companyIntegration` row. The nightly job simply looks for that row.++## 2. The updater job++`packages/jobs/src/inngest/functions/scheduled/update-exchange-rates.ts`+(`updateExchangeRatesFunction`, registered via+`packages/jobs/src/inngest/functions/scheduled/index.ts` → `packages/jobs/src/inngest/index.ts`).++- **Schedule**: Inngest cron `"0 0 * * *"` (daily, midnight UTC), `retries: 2`+ (update-exchange-rates.ts:73-74).+- **Gate**: selects `companyIntegration` rows with `id = "exchange-rates-v1"` and+ `active = true` (:79-83). **Zero rows → the job exits without fetching anything**+ (:92-95). This is the "rates require an integration" behavior to eliminate.+- **Source API**: `getExchangeRatesClient(EXCHANGE_RATES_API_KEY)` (:102-104) from+ `packages/ee/src/exchange-rates/exchange-rates.server.ts:94-104` — default URL+ `https://api.exchangeratesapi.io/v1/latest` (apilayer's exchangeratesapi.io).+ Free tier is **EUR-base only** (comment at exchange-rates.server.ts:47-50), so the+ job fetches EUR rates once and rebases to each company's base currency by division+ (`convertExchangeRates`, exchange-rates.server.ts:68-91), caching per base+ currency (:129-132, :154-166).+- **What it writes**: for each company with the integration, it loads the company's+ `baseCurrencyCode` (:139-153), then **full-row upserts every `currency` row for+ the company's `companyGroupId`** with `exchangeRate: round(rate)` (internal+ SCALE=5 rounding, comment :200-203) and `updatedAt` (:168, :197-221). Rows whose+ feed rate is missing or rounds to 0 are filtered out and left untouched (:206) —+ silently stale. No `updatedBy` is set. **It does NOT write `exchangeRateHistory`**+ (see §6 — nothing does).+- **The group-scoping bug (pending PR #1542)**: `currency` rows are **group**-scoped+ (§5) but the loop iterates per-**company** integration, so a multi-company group is+ rewritten once per member, and members with different base currencies overwrite+ each other — last writer wins for the whole group. The PR version (read via+ `git show b4d30d3ca3:...update-exchange-rates.ts`) buckets companies by+ `companyGroupId`, refuses groups with mixed base currencies, rebases and writes+ once per group, logs the currencies the feed omitted, and sets+ `updatedBy: "system"`.+- **With no integration**: rates stay at whatever they were — the seeded `1` (§5) or+ the last manual edit. There is no staleness indicator anywhere except the+ per-document `exchangeRateUpdatedAt` timestamp.+- There is **no edge function** for rate updates; this Inngest job is the only writer+ of feed rates. (`grep exchange packages/database/supabase/functions` only hits+ document-level `exchangeRate` usage in `create`/`post-purchase-invoice`.)++## 3. Manual updates++Yes — fully supported, and it is the same column the job overwrites.++- **Routes**: `/x/accounting/exchange-rates` list —+ `apps/erp/app/routes/x+/accounting+/exchange-rates.tsx:17-36` (loader:+ `getCurrencies(client, companyGroupId, …)`, permission `view: "accounting"`).+ Edit drawer `/x/accounting/exchange-rates/:currencyId` —+ `apps/erp/app/routes/x+/accounting+/exchange-rates.$currencyId.tsx:43-81` (action:+ `update: "accounting"` → `upsertCurrency`).+- **Service**: `upsertCurrency` —+ `apps/erp/app/modules/accounting/accounting.ee.service.ts:3696-3725` (plain+ update of the `currency` row: `exchangeRate`, `historicalExchangeRate`,+ `decimalPlaces`, `customFields`, `updatedBy`).+- **Form**: `apps/erp/app/modules/accounting/ui/ExchangeRates/ExchangeRateForm.tsx` —+ editable `exchangeRate` NumberField (:162-171; base currency pinned to 1 via+ min/max, :166-167), `historicalExchangeRate` for IAS 21 equity translation+ (:172-182), plus a history chart/table/CSV fed by `exchangeRateHistory` (:187-298)+ — which is empty in practice (§6).+- **Table**: `ExchangeRatesTable.tsx` shows name/code/exchangeRate with an "Edit+ Currency" context item only — **no "New" button**; the currency list is fixed at+ seed time (§5). (`path.to.newExchangeRate` exists at+ `apps/erp/app/utils/path.ts:1484` and `ExchangeRateForm.tsx:142` references it, but+ there is no `exchange-rates.new.tsx` route — the create path is dead code.)+- **Sidebar**: always visible under Accounting —+ `apps/erp/app/modules/accounting/ui/useAccountingSubmodules.tsx:127`. Also an+ onboarding "get started" checklist item+ (`packages/onboarding/src/content/setup.ts:82-87`).+- **Clobbering**: yes. The nightly job upserts every group currency row it has a feed+ rate for (§2), so a manual edit to a feed-covered currency survives **at most until+ the next midnight UTC** while any company in the group has the integration active.+ There is no per-row "manual override / don't auto-update" flag on `currency`.+ Conversely `historicalExchangeRate` is never touched by the job — manual-only.+- **Rate history** shown in the form comes from `getExchangeRateHistory`+ (`accounting.ee.service.ts:4735-4750`, last 6 months by `companyGroupId` ++ `currencyCode`) — but see §6: no writer exists.++## 4. On-demand refresh on documents++Six sibling routes, one per FX-bearing document (all present in tree):++- `apps/erp/app/routes/x+/quote+/$quoteId.exchange-rate.tsx`+- `apps/erp/app/routes/x+/sales-order+/$orderId.exchange-rate.tsx`+- `apps/erp/app/routes/x+/purchase-order+/$orderId.exchange-rate.tsx`+- `apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.exchange-rate.tsx`+- `apps/erp/app/routes/x+/sales-invoice+/$invoiceId.exchange-rate.tsx`+- `apps/erp/app/routes/x+/supplier-quote+/$id.exchange-rate.tsx`++Behavior (read from the PO route, representative): POSTed `currencyCode` from the+form → `getCurrencyByCode(client, companyGroupId, currencyCode)`+(`accounting.ee.service.ts:3735+` — reads the **live `currency` table**, no API+call) → writes only `exchangeRate` onto the document via+`update<Doc>ExchangeRate`. The refresh is therefore only as fresh as the shared+table — with no integration it re-stamps the seeded/manual value.++- **UI**: refresh button in each document's Properties panel, e.g.+ `apps/erp/app/modules/sales/ui/Quotes/QuoteProperties.tsx:430-450` (posts the+ document's own `currencyCode` to `path.to.quoteExchangeRate`), with the+ `exchangeRateUpdatedAt` timestamp shown via tooltip (:420-428). Same pattern in+ `SalesOrderProperties`, `PurchaseOrderProperties`, `SupplierQuoteProperties`,+ `PurchaseInvoiceProperties`, `SalesInvoiceProperties`.+- **Pending PR #1530**: because the routes trust the posted `currencyCode`, a crafted+ POST can stamp another currency's rate onto a document that keeps its own code. The+ PR reads the code from the loaded document and stops parsing the form, and routes+ the lookup through the (also-unmerged) `resolveCurrencyAndRate` so a refresh can't+ install a missing/unusable rate.+- **Where documents get their initial rate**: at creation the service resolves it from+ the currency table with a fallback to 1 — e.g. quote insert at+ `apps/erp/app/modules/sales/sales.service.ts:3516-3529` (`exchangeRate =+ currency.data.exchangeRate ?? 1`, `exchangeRateUpdatedAt = now`). When the+ currency is changed via Properties bulk-update, e.g.+ `apps/erp/app/routes/x+/quote+/update.tsx:69-86`: writes code + rate together when+ the lookup succeeds, but **falls through to the generic setter and writes the code+ with no rate when the lookup fails** (deliberate `// don't break` comment :86-87)+ — fixed by unmerged `aec17de6ba`.+- **Line cascade**: `packages/database/supabase/migrations/20241010193506_quote-order-presentation-currency.sql:122-144`+ — `quoteLinePrice.exchangeRate` mirrors the header via an AFTER UPDATE trigger, and+ `convertedUnitPrice`/`convertedNetExtendedPrice` etc. are GENERATED columns+ multiplying by it. Sales invoices cascade similarly (unmerged `080573aca2` touches+ this area too).++## 5. Defaults — new company, no integration++- **`currency` table**: created in+ `packages/database/supabase/migrations/20230330024715_accounts.sql:6` with+ `"exchangeRate" NUMERIC(20,8) NOT NULL DEFAULT 1` and `CHECK ("exchangeRate" > 0)`+ (:20). **Group-scoped since**+ `20260228023426_company-groups.sql:325-341` (`companyId` dropped, `companyGroupId`+ NOT NULL, `UNIQUE ("code","companyGroupId")`). Read through the `currencies` view+ (currency ⋈ currencyCode for the display name; latest definition+ `20260228023426_company-groups.sql:924-928`).+- **Seeding**: the `seed-company` edge function inserts, **for a new company group+ only**, all 118 ISO currencies from+ `packages/database/supabase/functions/lib/seed.data.ts:483-…` — every row+ `exchangeRate: 1` (`seed-company/index.ts:333-338`). Subsidiaries joining an+ existing group reuse the group's rows. Dev/demo datasets likewise assume rate 1+ (`packages/database/src/datasets/bootstrap.ts:300-305` inserts the same list;+ document tiers hardcode `exchangeRate: 1`, e.g. `datasets/tiers/04-sales.ts:20`,+ `05-purchasing.ts:192,246,321`).+- **So the out-of-box state is: every currency exists, every rate is 1.** A brand-new+ company that quotes in EUR against a USD base silently prices at parity until+ someone installs the integration or hand-edits the rate.+- **Missing-rate fallback is `?? 1` everywhere** (~25+ sites):+ `apps/erp/app/modules/sales/sales.service.ts:3525, 3657, 4045, 4425, 4549, 4638,+ 5333, 5447, 5826`; `apps/erp/app/modules/purchasing/purchasing.service.ts:1514,+ 1615, 2083, 2188`; UI e.g. `QuoteSummary.tsx:258,760,788,843`,+ `QuoteLinePricing.tsx:514,1320,1345`, `SalesOrderSummary.tsx:130`,+ `QuoteToOrderDrawer.tsx:424`; sync core+ `packages/ee/src/accounting/core/document-costing.ts:90`+ (`Number(invoice?.exchangeRate) || 1`); and in SQL,+ `translateTrialBalance` COALESCEs all three rate kinds to 1+ (`20260315000002_exchange-rate-history.sql:139-141`). The unmerged branch commits+ (`aec17de6ba`, `4931842606`) exist precisely because this fallback family kept+ writing rate-1 documents.++## 6. Other places rates enter or leave the system++- **Xero sync (per-document, both directions)** — the only provider carrying explicit+ rates. Outbound: `packages/ee/src/accounting/providers/xero/entities/invoice.ts:451`+ pushes `CurrencyRate: local.exchangeRate !== 1 ? local.exchangeRate : undefined`+ (serialization contract `xeroCurrencyRate`,+ `packages/ee/src/accounting/providers/xero/serialize.ts:25`). Inbound: remote+ documents map `exchangeRate: remote.CurrencyRate ?? 1` —+ `entities/invoice.ts:489`, `entities/payment.ts:224`,+ `entities/purchase-order.ts:416`. These rates land on **document rows** (invoice /+ payment / PO `exchangeRate` columns), never on the `currency` table. Unmerged+ `deee8198af` ("pass Xero's CurrencyRate through, don't invert it") fixes a+ direction bug here. QBO and Rillet entities have no CurrencyRate handling (grep+ `currencyRate` in `packages/ee/src` hits only Xero files + core).+- **Sync journal conversion** reads the document's stored rate:+ `packages/ee/src/accounting/core/document-costing.ts:61-90, 210-233`+ (base = transaction × rate; divide with penny-reconciliation).+- **Paperless Parts import**:+ `packages/jobs/src/inngest/functions/integrations/paperless-parts.ts:283-331` —+ imported quotes take `currency.data.exchangeRate ?? undefined` from the shared+ table (falls back to `exchangeRate = 1` when the currency row isn't found). Rates+ flow table→document, nothing external enters the table.+- **`exchangeRateHistory` has NO writer in the repo.** Table created in+ `20260315000002_exchange-rate-history.sql:1-56` with the comment "daily spot rates+ auto-populated by sync job" — but neither the current updater job nor PR #1542's+ version inserts into it; the only in-repo references are the reader+ `getExchangeRateHistory` (`accounting.ee.service.ts:4735-4750`), the+ `translateTrialBalance` RPC (closing/average rates, same migration:116-141, revised+ in `20260713225803`), and the auto-generated REST swagger+ (`packages/database/src/swagger-docs-schema.ts:36294+`, i.e. writable via the+ public API only). Consequence: the form's history chart is empty and consolidation+ "Average"/"Closing" rates COALESCE down to the spot fallback → 1. Any redesign+ should make the new shared store the history writer.+- No other rate sources found (no ECB/fixer/openexchangerates references anywhere;+ `exchangeratesapi.io` is the only feed).++---++## Summary for the redesign (shared on-by-default store + per-company override)++1. **The integration is a pure toggle with zero config** — no per-company key, no+ settings, already plan-whitelisted for everyone (`plan.ts:29-33`). Eliminating it+ costs nothing config-wise; the only thing the `companyIntegration` row does is+ gate the cron job's company list.+2. **The natural "shared store" already half-exists but is mis-keyed.** Rates live on+ group-scoped `currency` rows, rebased into each group's own base currency — so+ today's storage is per-group *derived* data, not a shared truth. A single+ platform-level rate table (e.g. EUR- or USD-based daily rates, one row per+ code+date) with per-group/company *override* rows would let the rebase happen at+ read time and make `exchangeRateHistory` (currently writer-less) the natural+ platform history.+3. **Manual edits and the feed write the same column with no precedence flag** — the+ nightly job clobbers manual edits; nothing marks a rate as "user-pinned". The+ override capability the redesign wants needs an explicit marker (or a separate+ override table), not just the current single `exchangeRate` column.+4. **Fallback-to-1 is pervasive and silent** (`?? 1` in ~25 call sites plus SQL+ COALESCEs) — with rates on by default, most of these become unreachable, but the+ unmerged branch (`resolveCurrencyAndRate`, refuse-don't-default) is the intended+ direction and should be reconciled with/landed before or with this work.+5. **Coordinate with the two open PRs** (#1542 group-scoped job rewrite, #1530+ document-sourced refresh + resolver commits on the same branches) — they rewrite+ exactly the files this refactor replaces; landing order matters to avoid+ conflicts or re-fixing.diff --git a/.ai/research/exchange-rate-competitor-practice.md b/.ai/research/exchange-rate-competitor-practice.mdnew file mode 100644index 0000000000..f0bac4a183--- /dev/null+++ b/.ai/research/exchange-rate-competitor-practice.md@@ -0,0 +1,146 @@+# Exchange Rate & Multi-Currency Architecture Research: Best Practices Survey++## Summary++Surveyed how six ERPs/accounting systems (SAP S/4HANA + Business One, NetSuite OneWorld, Dynamics 365 Business Central, Odoo, Xero, QuickBooks Online) store exchange rates, feed them automatically, let users override them, and stamp them onto documents. Strong consensus emerged on five points: (1) rates are always stored with an **explicit anchor** — either currency pairs (from→to) or a rate relative to a named reference currency — never "to an unrecorded base"; (2) rates are **effective-dated rows** (valid-from / starting-date semantics, lookup = latest row ≤ document date), never a single mutable column; (3) SMB SaaS products (Xero, QBO) prove the **on-by-default, zero-config feed** model Carbon wants — no provider selection, no API key, no off-switch, overrides as the only control; (4) the best override semantics are **manual-wins**: the feed inserts-if-absent (NetSuite) or user rates take precedence for their date (Xero), rather than last-writer-wins (Odoo/BC's acknowledged weakness); (5) documents stamp a **header-level** rate at creation, table refreshes never rewrite existing documents, and per-document override is permission-gated. Odoo's `res.currency.rate` is the closest structural template for Carbon's goal: one shared table, a technical rate relative to a reference currency, nullable company scope where company-specific rows win over global rows, and both human-readable directions computed against the *viewer's* company currency.++## Competitors Surveyed++- **SAP S/4HANA** — the enterprise reference: rate types, currency-pair model, triangulation, document stamping rules.+- **SAP Business One** — SMB counterpart: per-company daily rate table, hard-stop on missing rates.+- **NetSuite OneWorld** — the closest analog to Carbon's problem: one tenant with subsidiaries having different base currencies sharing one rate table.+- **Dynamics 365 Business Central** — per-company rates, quotation-pair storage, feed framework, verified from published AL source.+- **Odoo** — one shared rate table serving multi-company DBs with different base currencies; the structural template.+- **Xero / QuickBooks Online** — the UX bar: rates on by default with zero configuration.++## Key Consensus Patterns++### 1. The rate's anchor is always explicit — no "rate to an unstated base"++- **SAP**: TCURR keyed by `(rate type, from-currency, to-currency, valid-from)` — client-wide (tenant-wide), NOT per company code. A company code's local currency merely selects which pair to look up at posting time. Triangulation via a per-rate-type **reference currency** means N currencies need N rates, not N².+- **NetSuite**: one shared table keyed by `(base currency, foreign currency, effective date)`. Subsidiaries with different bases read the rows whose base matches theirs — one physical list, logically partitioned by base currency. Missing pairs fall back to inverse (1÷direct) then triangulation (opt-in).+- **Odoo**: `res.currency.rate.rate` is "units of this currency per 1 unit of the reference currency" (the rate-1 currency). Converting between any two currencies is the ratio of their rates. The base is a property of the *lookup*, not the storage.+- **BC**: per-company quotation pair (`Exchange Rate Amount` / `Relational Exch. Rate Amount`), with a `Relational Currency Code` for triangulation.+- **Rationale**: Carbon's core bug — `currency.exchangeRate` normalized to "whichever company's base the nightly job last wrote" — is a category error no surveyed system makes. Either store pairs, or store reference-currency-relative rates and derive per-company views at read time.++### 2. Effective-dated, insert-only rate rows++- **SAP**: valid-from, open-ended until superseded; future-dated rows sit inactive until their date.+- **NetSuite**: users *add* a new effective-dated row, never edit in place; lookup = latest rate ≤ transaction date.+- **BC**: `(Currency Code, Starting Date)` PK; "starting date" names the semantics.+- **Odoo**: one row per (currency, date, company) — hard uniqueness constraint.+- **Xero/QBO**: one official rate per day (Xero finalizes at 11pm org time; QBO stores one/day).+- **Rationale**: history is a first-class need (revaluation, consolidation, backdated documents, audit). A single mutable `exchangeRate` column destroys it. Carbon's unwritten `exchangeRateHistory` table shows the need was felt but never wired.++### 3. On-by-default feeds are the SMB-SaaS norm; missing rates should refuse, not fabricate++- **Xero**: XE.com hourly, on the moment multicurrency exists, **no off-switch**, no setup of any kind.+- **QBO**: IHS Markit every 4 hours, on the instant the multicurrency checkbox is ticked, no provider choice, irreversible.+- **NetSuite**: a feature checkbox (Xignite feed), included with Multiple Currencies; when off, rates go stale.+- **SAP/BC/Odoo**: feeds are configured (Market Rates Management / Exchange Rate Services / Automatic Currency Rates with default interval "Manually"); none on by default — and all generate consultant/add-on ecosystems as a result.+- **On missing rate**: SAP hard-fails (error SG105 "Enter rate X/Y for date"); B1 blocks the document; BC errors ("no Currency Exchange Rate within the filter"); QBO prompts the user to enter one. Nobody silently uses 1.0. (Odoo's 1.0 fallback exists only when a currency has no rate row at all — and is regarded as a trap.)+- **Rationale**: Carbon's ~25 `?? 1` par fallbacks are the anti-pattern every strict system refuses. "No rate" must be an error at resolution time; base currency = 1 by definition is the only sanctioned constant.++### 4. Override semantics: manual wins, feed defers++- **NetSuite** (the cleanest): the feed's write is **insert-if-absent per (pair, effective date)** — "manually entered rates for the same currency pair and effective date aren't overwritten by rate providers." No lock flag needed; the protection is structural. Per-currency "Automatic Update" checkbox opts a currency out of the feed entirely.+- **Xero**: per-document "Set exchange rate" → "XE.com rate | Custom exchange rate", with a default-on checkbox *"apply this exchange rate to all new transactions on this date"* — override where you are, optionally promote it to the date. User-set rates for a date take precedence over the feed.+- **QBO**: "market rate" vs "**your rate**" — per-transaction rates persist; company-level custom rates apply for that day only, with audit (who + when).+- **Odoo/BC** (the weakness to avoid): one row per day, feed insert-or-overwrite — a manual edit to *today's* row is clobbered by the next sync. Community workarounds exist precisely because of this.+- **Rationale**: Carbon's requirement "every rate user-overridable" maps to rate provenance (feed vs manual) + feed-defers-to-manual write discipline, not to a boolean lock column.++### 5. Documents stamp a header rate at creation; refreshes never rewrite; lines don't carry independent rates++- **NetSuite**: rate effective on the transaction date is captured into the transaction's own Exchange Rate field; header-only; editable with Currency permission at Edit level; table refreshes change *defaults for future transactions* only. Billing re-rates (invoice from SO defaults to the invoice-date rate).+- **SAP**: stamps from a role-appropriate date (pricing date for prices, billing/posting date for GL); header override has highest priority; downstream documents re-derive at their own posting dates **unless** the "Exchange Rate Fixed" indicator pins the PO's rate through GR/IR. (SD's per-condition-line rates exist only for conditions priced in a third currency — a specialized case, not a general line-rate model.)+- **BC**: posting uses the posting-date rate; per-document override via the Change Exchange Rate page (header); a per-rate-row **"Fix Exchange Rate Amount"** flag governs whether documents may override at all. The document freezes a derived **Currency Factor**.+- **Odoo**: date-based, not document-based — no supported per-document override in standard Odoo (typed rates get recomputed at confirmation); the sanctioned path is creating a dated rate row.+- **Xero/QBO**: transaction-date rate, header-level, per-document editable; changing the document date re-derives.+- **Rationale**: Carbon's six header + six line snapshot tables with three different propagation mechanisms (interceptors, triggers, none) has no counterpart anywhere. One header rate per document, with lines converting through the header rate, is universal.++### 6. Rate purposes are separated: posting vs revaluation vs consolidation++- **NetSuite**: entirely separate **Consolidated Exchange Rates** table (per period × subsidiary pair × book) with **Current / Average / Historical** values, where Average/Historical are *weighted averages of actual posted transaction rates*; every GL account carries a General Rate Type + Cash Flow Rate Type selecting which applies. Daily table and period table never share storage.+- **SAP**: named rate types (M, B, G, EURX, custom historical/budget types) over the same pair table.+- **BC**: a parallel adjustment pair on each rate row, consumed only by the Exch. Rates Adjustment batch job.+- **Odoo**: revaluation is report-time — closing-rate override typed in the report is *not* written back to the rate table; adjustment entry auto-reverses.+- **Rationale**: Carbon's `historicalExchangeRate` column and consolidation RPCs (`getConsolidationRates`, `translateTrialBalance`) are a nascent version of this separation; the refactor must not conflate transaction rates with consolidation rates.++## Answers to Research Questions++1. **Per-entity or shared rates in multi-entity systems?** Shared at tenant scope with an explicit anchor: SAP TCURR is client-wide currency pairs; NetSuite is one table partitioned by base currency; Odoo is one table with reference-relative rates + nullable company scope (company rows win over global rows — verified in source: `WHERE company_id IS NULL OR company_id = %s ORDER BY company_id, name DESC LIMIT 1`). Only BC and B1 are strictly per-company — and both are single-base-currency-per-company designs. **Nobody scopes rates to an entity *group* whose members have different bases.**+2. **Feeds on by default?** Yes in Xero/QBO (the model Carbon wants: no provider choice, no key, no off-switch); checkbox-included in NetSuite; configured in SAP/BC/Odoo. With no feed: strict systems refuse to post on a missing rate rather than fabricate one.+3. **Do manual edits survive the feed?** Best practice yes: NetSuite feed = insert-if-absent per (pair, date); Xero user-date-rates take precedence. Odoo and BC clobber same-date manual edits (documented weakness). QBO: per-day only, resumes feed next day, but per-transaction rates always persist.+4. **Direction/storage convention?** NetSuite: base units per 1 foreign unit. Odoo: reference-relative technical rate + two computed human views (`company_rate` "units per company currency", `inverse_company_rate` "company currency per unit") against the viewer's company. BC: quotation pair sidestepping direction ambiguity. SAP: per-pair standard quotation (direct/indirect) config. Consensus: pick one canonical convention, state it everywhere a rate appears, and render human-direction views per company at the edge.+5. **Document stamping?** Header-level rate captured at creation from the transaction/posting date; permission-gated per-document override; table changes affect future documents only; downstream documents re-derive at their own dates unless explicitly pinned (SAP KUFIX, B1 fixed rates). Lines never carry independent general-purpose rates.+6. **Rate types / effective dating?** Effective-dated open-ended rows everywhere; separate rate series for consolidation/revaluation (NetSuite consolidated table, BC adjustment pair, SAP types); one-rate-per-day is the SMB norm.++## Competitor-Specific Details++### SAP S/4HANA+- TCURR key: `(KURST rate type, FCURR, TCURR, GDATU valid-from)`; OB08 / "Currency Exchange Rates" Fiori app; TCURF translation ratios (per-100 quotation); reference currency per rate type wins over maintained direct rates.+- Document trio in SD: pricing rate (pricing date, `VBKD-KURSK`), accounting rate (billing date, `VBRK-KURRF`, manual header entry wins), condition-currency rate (per condition line, third-currency conditions only).+- MM: PO header `WKURS` + `KUFIX` "Exchange Rate Fixed" — pinned rate flows through goods receipt and invoice verification; unpinned re-derives at each posting date.+- FI: header rate + **translation date** (`BKPF-WWERT`, defaults to posting date, configurable per currency type in OB22).+- Missing rate = SG105 hard stop.++### SAP Business One+- Per-company-database daily rate table ("Exchange Rates and Indexes"), Local Currency + System Currency (parallel ledger currency on every posting), optional login prompt to key today's rates, missing rate blocks the document, no built-in feed (partner add-ons fill the gap).++### NetSuite OneWorld+- Currency Exchange Rates: shared, `(base, foreign, effective date)`, insert-only; feed (Xignite, ~6am account timezone) is insert-if-absent; per-currency Automatic Update opt-out; per-transaction editable header rate (Currency permission, Edit level); billing re-rates at invoice date; realized G/L at payment, unrealized at period-end revaluation.+- Consolidated Exchange Rates: per period × subsidiary pair × accounting book; Current (period-end spot) / Average / Historical (both weighted averages of actual posted transactions); GL accounts select which via General Rate Type + Cash Flow Rate Type. Plus a parallel Budget Exchange Rates table.+- Currency Exchange Rate Types feature (irreversible): named rate series (Default, Corporate, …) allowing multiple same-day rates per pair.++### Dynamics 365 Business Central+- Table 330 per company, PK `(Currency Code, Starting Date)`; quotation pair + separate adjustment pair; document freezes a Currency Factor; per-rate-row "Fix Exchange Rate Amount" governs document overridability; Exchange Rate Services = Data Exchange Framework config (FloatRates/ECB examples), enabled per service + job queue, none default; sync = insert-or-overwrite on (code, date) — manual same-date edits clobbered.++### Odoo+- `res.currency.rate`: `(name date, rate, currency_id, company_id nullable → root company)`; unique (name, currency_id, company_id); global rows (NULL company) vs company rows, company wins; currencies global, rates scoped.+- `rate` reference-relative; `company_rate`/`inverse_company_rate` computed against the row's company currency — users always type relative to their own base, storage stays canonical.+- Feed: Enterprise `currency_rate_live` (ECB default, localized central banks), interval defaults to "Manually"; OCA modules for Community; forward-only.+- No per-document override in standard Odoo (recomputed at `action_post`); revaluation closing-rate override is report-local, never written back.++### Xero+- XE.com hourly, daily official rate at 11pm org time; no off-switch, no rate API (FX contract prohibits it) — callers push `CurrencyRate` on documents or read it back; per-document override with "apply to all new transactions on this date" promotion; locked system accounts 497/498/499 (Bank Revaluations / Unrealised / Realised Currency Gains); report-date implicit revaluation.++### QuickBooks Online+- IHS Markit every 4 hours; on with the multicurrency checkbox (irreversible, home currency locks); "market rate" vs "your rate"; company-level custom rate = that day only, audited; backdating re-derives, unknown dates prompt; realized G/L auto at settlement, unrealized via manual Home Currency Adjustment; full rate API (GET/POST exchangerate) + `ExchangeRate` accepted on transactions.++## Recommended Approach for Carbon++1. **Store rates once, platform-wide, anchored to an explicit reference currency (USD), effective-dated** — Odoo's technical-rate model + NetSuite/SAP's effective dating. One `exchangeRate`-style table keyed by `(currencyCode, effectiveDate [, scope])` holding "units of currency per 1 USD"; any company's rate for any pair is the ratio of two reference-relative rates (SAP triangulation, N not N²). This dissolves the group-base ambiguity: the anchor is a property of the table, not of whichever company wrote last.+2. **Per-company override rows over global feed rows** — Odoo's nullable-company precedence: a global row (feed-written, shared by all tenants) is the default; a company-scoped row wins for that company. This is the "single store of truth for everyone, every rate user-overridable" requirement expressed structurally.+3. **Feed defers to manual** — NetSuite's insert-if-absent: the feed never touches a row a user wrote. Track provenance (`source: feed | manual` — QBO's "market rate vs your rate") instead of a lock flag.+4. **On by default, no integration** — Xero/QBO: the feed runs for everyone; the only user controls are overrides. Platform fetches rates once per day (one API call for all tenants — the reference-relative model makes tenant count irrelevant to feed cost).+5. **Kill the `?? 1` reflex** — SAP SG105: resolution of a missing rate is an error, surfaced at the point of use; the only free constant is base=1 for a company's own currency. (With a seeded global feed table, "missing" becomes genuinely exceptional.)+6. **One header rate per document, stamped at creation, refresh = explicit user action, lines convert through the header** — universal pattern; eliminates Carbon's line-rate columns and the three inconsistent propagation mechanisms. Keep `(currencyCode, exchangeRate)` atomic as a value pair (same doctrine as taxPercent/taxAmount).+7. **Keep consolidation rates separate** — do not let the transaction-rate refactor absorb `historicalExchangeRate`/consolidation semantics; NetSuite's separation (daily table vs period table) is the reference. Wire `exchangeRateHistory` (or the new effective-dated store) as the source consolidation reads from.++## Sources++- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1401566.html (NetSuite currency exchange rates)+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1403894.html (NetSuite manual rates not overwritten)+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_4322310757.html (NetSuite rate integration)+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1405625.html (NetSuite consolidated exchange rates)+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1404249.html (NetSuite transaction rate override)+- https://erproof.com/fi/free-training/sap-exchange-rate-table/ (SAP TCURR)+- https://userapps.support.sap.com/sap/support/knowledge/en/3323804 (SAP direct/indirect quotation)+- https://community.sap.com/t5/enterprise-resource-planning-q-a/exchange-rate-type-reference-currency/qaq-p/6664529 (SAP reference currency/triangulation)+- https://userapps.support.sap.com/sap/support/knowledge/en/3735206 (SAP SG105 missing rate)+- https://community.sap.com/t5/technology-blog-posts-by-members/how-to-maintain-exchange-rates-in-sap-s-4hana-cloud/ba-p/13556656 (S/4HANA rate maintenance ladder)+- https://ganeshsapscm.com/2025/03/14/detailed-blog-about-exchange-rate-fixed-indicator-in-sap-purchase-order-header/ (SAP KUFIX)+- https://help.sap.com/docs/SAP_BUSINESS_ONE/68a2e87fb29941b5bf959a184d9c6727/45070df7e02641dfe10000000a1553f6.html (B1 exchange rates window)+- https://github.com/microsoft/BCApps/blob/main/src/Layers/W1/BaseApp/Finance/Currency/CurrencyExchangeRate.Table.al (BC table 330 source)+- https://github.com/microsoft/BCApps/blob/main/src/Layers/W1/BaseApp/Finance/Currency/MapCurrencyExchangeRate.Codeunit.al (BC sync insert-or-overwrite source)+- https://learn.microsoft.com/en-us/dynamics365/business-central/finance-how-update-currencies (BC rate maintenance)+- https://github.com/odoo/odoo/blob/17.0/odoo/addons/base/models/res_currency.py (Odoo res.currency.rate source)+- https://www.odoo.com/documentation/19.0/applications/finance/accounting/get_started/multi_currency.html (Odoo multi-currency)+- https://www.odoo.com/forum/help-1/different-currency-exchange-rate-for-each-company-in-multi-company-configuration-34142 (Odoo multi-company rates)+- https://www.xero.com/us/accounting-software/use-multiple-currencies/ (Xero multicurrency)+- https://xero.uservoice.com/forums/5528-accounting-api/suggestions/42351646-query-exchange-rate-through-the-api (Xero no rate API)+- https://central.xero.com/s/article/Foreign-currency-accounts-in-the-chart-of-accounts-AU (Xero system accounts)+- https://quickbooks.intuit.com/learn-support/en-us/help-article/currency/learn-exchange-rates-quickbooks-online/L97rmEAdR_US_en_US (QBO exchange rates)+- https://developer.intuit.com/app/developer/qbo/docs/workflows/manage-multiple-currencies (QBO API multicurrency)+- https://meir.prolecto.com/2019/12/03/understand-netsuites-currency-translation-approach/ (NetSuite translation approach)+- https://thedynamicsexplorer.com/2021/02/26/dynamics-365-business-central-making-sense-of-the-currency-exchange-rates-page-when-setting-exchange-rates/ (BC rate pair)diff --git a/.ai/runs/2026-09-02-currency-exchange-rate-refactor.md b/.ai/runs/2026-09-02-currency-exchange-rate-refactor.mdnew file mode 100644index 0000000000..da2b6c72ef--- /dev/null+++ b/.ai/runs/2026-09-02-currency-exchange-rate-refactor.md@@ -0,0 +1,46 @@+# Feature run: Currency + exchange rate architecture refactor++- Date: 2026-09-02+- Mode: fully-autonomous+- Request: "we need to do a big refactor on currency and exchange rate. first i want you do an audit of the existing exchange rate PRs from BettrCallRaul that were opened between 2 days ago and today. these are symptoms. don't treat them as the solution, but as symptoms to solve during our refactor. next study the codebase. one major problem is that the 'currency' table is currently scoped to a 'companyGroupId' so an exchange rate would be normalized to a company group -- but companies within the group can have different currencies and so this falls apart. the final problem that we'd like to solve is that currently exchange rates require an integration. but we don't want this. we want it to be on by default with a single store of truth for everyone. with every exchange rate able to be updated by the end user if they desire. this is a major refactor. in the end we will have simplified exchange rates architecture, eliminated the need to add an integration, and solved all of the known bugs and some of the unknown bugs as well. let's use a combination of the feature and fix skill"+- Phase plan: research [run — ERP accounting domain logic, force-included; competitor practice on rate providers/overrides/scoping] · spec [run — cross-module data-model change, 40+ call sites] · plan [run] · execute [run] · test [run — user-facing settings + document flows; mandatory per user working agreement] · self-review [run — default]++## Pre-pipeline inputs (done before pipeline start)++- PR audit: `.ai/research/2026-09-02-exchange-rate-pr-audit.md` — 12 symptom PRs (#1525–#1549 by BettrCallRaul) classified into defect classes: (a) group-scoping half-migration, (b) integration-gated rates → `?? 1` par fallbacks, (c) snapshot-vs-live confusion, (d) direction confusion (3 rate² bugs), (e) header→line propagation gaps, (f) validation gaps, (g1) non-atomic (currencyCode, exchangeRate) pair, (g2) untyped parallel column families.+- Currency architecture: `.ai/research/2026-09-02-currency-architecture.md` — schema, 6 write paths, 7 read classes (~40 stamping sites), 6 header + 6 line snapshot tables + payment/memo/invoiceSettlement; "base of normalization" recorded nowhere; decimalPlaces vs exchangeRate want different scopes; exchangeRateHistory has zero writers.+- Update path: `.ai/research/2026-09-02-exchange-rate-update-path.md` — `exchange-rates-v1` integration is a pure on/off toggle gating the nightly cron (exchangeratesapi.io, EUR base, global env key); manual edits clobbered nightly; new companies seed 118 currencies at rate 1.++## Decisions+- Autonomy mode: fully-autonomous — session is non-interactive; user pre-delegated open-question resolution (recommendations documented + surfaced for veto). — 2026-09-02+- Phase set: all six phases — ERP-domain (research forced), cross-module data model (spec forced), user-facing surfaces (test forced by working agreement). — 2026-09-02++## Phase log+- Research: done — `.ai/research/exchange-rate-competitor-practice.md` (SAP S/4+B1, NetSuite, BC, Odoo, Xero, QBO via 4 parallel web-research agents). Consensus: explicit rate anchor (pair or reference-currency-relative, never unstated base); effective-dated insert-only rows; Xero/QBO prove on-by-default zero-config feeds; manual-wins override semantics (NetSuite insert-if-absent); header-only document rates stamped at creation; missing rate = hard error (SAP SG105), never `?? 1`. Odoo `res.currency.rate` (reference-relative technical rate + nullable company scope, company rows win) is the closest structural template.+- Spec: done — `.ai/specs/2026-09-02-currency-exchange-rate-refactor.md`. Design: global USD-anchored effective-dated `exchangeRate` table (feed-written, seeded snapshot, no tenancy) + per-company `exchangeRateOverride` (standing pin, beats feed) + SQL resolver `get_exchange_rate` (base→1, override, else ratio; ERROR on missing) ; `currency` stays group-scoped config-only (drops `exchangeRate`); `exchangeRateHistory` dropped; integration deleted; consolidation closing/average rewired to global store; salesInvoice propagation + rate>0 CHECKs subsumed (#1527/#1541 guarded); refresh routes doc-sourced (#1530); ~40 stamping sites → resolver. 11 open questions resolved autonomously; 2 flagged for veto (column drop vs ADDITIVE-ONLY contract; override-migration heuristic).+- Plan: done — `.ai/plans/2026-09-02-currency-exchange-rate-refactor.md`. 17 tasks: 3 migration-authoring (global store + seed snapshot + resolver fns; data-migration + column drop + view + integration delete; salesInvoice triggers + 12 CHECKs + consolidation forks), apply+types, models/service, 3 parallel stamping-site sweeps (sales/purchasing/invoicing+refresh routes), edge fns, jobs rewrite, EE deletion, seeds+backup pins, UI, validation, gates, /test, docs. Appendix A carries the ~150-code bootstrap rate snapshot.+- Execute: done through Task 15. 4 migrations (global `exchangeRate` store + seed snapshot + resolvers; currency config-only + override data-migration + integration delete; salesInvoice triggers + 12 CHECKs + translateTrialBalance fork; getConsolidationRates pair-fix), applied + types regenerated + psql-verified (override precedence, reset, missing-rate error, pair ratios). ~40 stamping sites swept to the resolver across sales/purchasing/invoicing services + routes (3 subagents); 6 refresh routes now document-sourced; edge fns `convert`/`create` on the RPC; feed job rewritten platform-global; EE integration deleted; exchange-rates UI reworked (provenance badges, override/reset intents); seeds slimmed; schema.json baseline regenerated; AGENTS.md synced; 10 new i18n strings filled in 12 locales. Typecheck green (erp, jobs, ee, database); lint clean; all tests pass; datasets gate passes.++## Execute-phase decisions / deviations+- Commits deferred to one atomic commit (per-task commits impossible: the column drop makes the tree red until all sweeps land; same rationale as the July convention spec's "ship as one PR").+- Appendix A amended: obsolete VEF/ZMK seeded at successor-peg conversions; 6 non-`currencyCode` codes removed from the seed INSERT (FK).+- M4 added (getConsolidationRates): plan's Task 3 missed that the RPC exists separately in 20260713225803 and reads the dropped table; forked with explicit target param (old signature dropped first to avoid the overload trap); TS caller passes targetCurrency.+- Quote PDF paths (documentPreview.server.ts, file+/quote+/$id.pdf.tsx) — unassigned in the plan, surfaced by typecheck: switched from LIVE currency reads to the quote's stamped snapshot (subsumes PR #1549's direction); legacy null snapshot renders at 1 (consistent with line snapshots), documented in-code.+- Remaining `?? 1` grep hits are document-snapshot DISPLAY reads (nullable legacy header rates in quote UI) — not resolution fallbacks; left as-is.+- `db:check:backups` blocked by PRE-EXISTING baseline pollution on main: `schema.json` contains `onshapeSyncRun`/`onshapeItemSyncState`, tables with NO migration anywhere (committed from a dirty local DB). Fixed by regenerating the baseline from this branch's clean fully-migrated schema (drops the phantom tables, adds the new ones); commit uses CARBON_SKIP_BACKUP_CHECK=1 with this documented cause. **Surface to Brad: main's baseline was polluted.**+- Task 6's agent also converted stored-snapshot NULL-rate sites in price-building fns to explicit errors (legacy pre-2024 rows only) — flagged for self-review.+- Dead `companyGroupId?` params left on `updatePurchaseOrder`/`updateSupplierQuote` signatures (callers outside task file lists) — cleanup candidate.++## 🛑 Gate: plan approval — auto-resolved (autonomous mode)+Plan approved autonomously: it covers every spec acceptance criterion (traced task-by-task), respects the two veto-flagged decisions as specced, and parallelizes safely. The human review point is the PR. — 2026-09-02++## 🛑 Gate: spec Open Questions — auto-resolved (autonomous mode)+All 11 resolved in spec with **Autonomous:** markers; recommendation order codebase-precedent → research-consensus → judgment. Veto-flagged: (1) dropping `currency.exchangeRate` (ADDITIVE-ONLY exception, data migrated to overrides first); (2) migration heuristic (integration-inactive groups only, rate ≠ 1, code ≠ company base, per member company). — 2026-09-02++## Phase log (continued)+- Self-review: done — nuclear mode, three parallel reviewers over the full 74-file diff, findings verified in code before reporting. 6 must-fix + 9 risks + 7 suggestions found.+- Review fixes: done — commit fd6e0aaf3a (49 files). All must-fixes applied (get-method ??0, VALIDATE data repair, M2 retry guard, dead companyGroupId gates/params, consolidation dedup via delegation, stale EE docs) plus risks 7-14 (snapshot-fallback loaders, supplier-quote company guard, feed-job retries, consolidation fail-loudly, base-change override clearing + base-pin refusal, admin page error surfacing, translation fixes) and the cheap suggestions (feed math unit tests, typed RPC call, Updated column, dead payloads, form i18n, lessons).++## Outcome+- Two commits on `currency-exchange-rate-refactor`: 7f0c2eed43 (the refactor) + fd6e0aaf3a (review hardening). Typecheck green (erp/jobs/ee/database), lint clean, all tests pass (incl. new feed-math suite), dataset gate passes; backup gate bypassed with documented cause (main's baseline polluted with phantom onshape tables — fixed baseline ships in this branch).+- OPEN: Task 16 browser verification (stack was torn down mid-run; needs crbn up + /test of the five flows), Task 17 docs-site pages (integrations index + accounting mdx still describe the deleted integration). Deferred by design: `create` edge fn null-supplier-currency USD default → company base (behavior-preserving choice, flagged); repo-wide raw `* rate` checks ban (spec follow-up); per-line rate elimination (spec follow-up).diff --git a/.ai/specs/2026-09-02-currency-exchange-rate-refactor.md b/.ai/specs/2026-09-02-currency-exchange-rate-refactor.mdnew file mode 100644index 0000000000..025df69335--- /dev/null+++ b/.ai/specs/2026-09-02-currency-exchange-rate-refactor.md@@ -0,0 +1,425 @@+# Currency & Exchange Rate Architecture Refactor++> Status: draft+> Author: Claude (feature pipeline, autonomous mode), for [email protected]+> Date: 2026-09-02++Research: [.ai/research/exchange-rate-competitor-practice.md](../research/exchange-rate-competitor-practice.md) ·+[PR audit](../research/2026-09-02-exchange-rate-pr-audit.md) ·+[Currency architecture / blast radius](../research/2026-09-02-currency-architecture.md) ·+[Rate update path](../research/2026-09-02-exchange-rate-update-path.md)++## TLDR++Replace the group-scoped `currency.exchangeRate` column and the integration-gated nightly+job with: (1) a **platform-global, effective-dated `exchangeRate` table** anchored to USD,+written daily by an unconditional feed job (one API call for the whole installation);+(2) a **per-company `exchangeRateOverride` table** whose rows always beat the feed+(QBO's "your rate" vs "market rate"); (3) a **single SQL resolver+`get_exchange_rate(companyId, code)`** that answers "units of `code` per 1 unit of THIS+company's base currency" — base = 1 by definition, override next, else the ratio of two+USD-anchored feed rates (SAP triangulation). The `currency` table survives as group-scoped+currency *configuration* (decimalPlaces, active, historicalExchangeRate) with the rate+columns removed. Document snapshot semantics — the header `exchangeRate` stamped at+creation, line `converted*` generated columns, posting/PDF/sync reading snapshots only —+are **preserved exactly**, so the blast radius is the ~40 stamping sites, two edge+functions, one jobs duplicate, the nightly job, and consolidation's closing/average+lookups. The `exchange-rates-v1` integration is deleted; rates are on by default for+everyone. Along the way: `?? 1` par fallbacks become errors, `(currencyCode, exchangeRate)+` becomes an atomic pair at every write, the missing salesInvoice header→line propagation+is added, rate > 0 is enforced by DB CHECKs, and `toBaseAmount`/`fromBaseAmount` helpers+pin the direction convention.++## Problem Statement++Three architectural problems, evidenced by 12 symptom PRs from BettrCallRaul+(#1525–#1549, classified in the PR audit):++1. **The rate's base is recorded nowhere.** `currency` is unique per+ `(code, companyGroupId)` and `exchangeRate` means "foreign units per 1 base unit" —+ but base currency lives per company (`company.baseCurrencyCode`), and companies in a+ group can differ (a supported configuration: consolidation exists precisely to+ translate them). The nightly job normalizes the group's shared rows to *each+ integration-enabled company's* base in arbitrary order (last writer wins — PR #1542);+ consolidated reports assume the *root* company's base; the edit form describes the row+ against the *viewer's* base. Every company except "whichever wrote last" reads rates+ normalized to a base that is not its own, and its own base-currency row isn't 1.+2. **Rates require an integration.** `exchange-rates-v1` is a pure on/off toggle (empty+ settings, global env API key) whose only function is gating the cron's company list.+ Without it, all 118 seeded currency rows sit at `exchangeRate = 1` forever — and ~25+ `?? 1` / `|| 1` call sites plus `DEFAULT 1` columns make missing rates look plausible.+ Every foreign-currency document on a fresh company quietly books at par (#1525's+ six-month silent par-quoting is the canonical case).+3. **The defect classes behind the PR wave** (audit's patterns): silent par fallbacks+ (#1525, #1526); direction-is-tribal-knowledge rate² bugs (#1544, #1543, #1532);+ non-atomic `(currencyCode, exchangeRate)` writes (#1526, #1530); inconsistent+ header→line propagation — interceptors for quote/SO, triggers for PO/PI/supplierQuote,+ **nothing** for salesInvoice (#1527); no positivity enforcement (#1541); manual edits+ clobbered by the nightly feed (no provenance concept at all).++Additional latent defects that ride along: `exchangeRateHistory` has **zero writers**+while consolidation already reads it (closing/average rates COALESCE to 1 today);+`translateTrialBalance` multiplies by a rate whose convention implies dividing — a+direction contradiction never forced into the open because no producer exists.++## Proposed Solution++### The model++```+┌─────────────────────────────────────────────────────────────────────────┐+│ exchangeRate (GLOBAL — no tenant column) │+│ one row per (currencyCode, effectiveDate) │+│ rate = units of currencyCode per 1 USD │+│ written by the daily feed job + seeded snapshot; read by everyone │+├─────────────────────────────────────────────────────────────────────────┤+│ exchangeRateOverride (PER COMPANY) │+│ one row per (companyId, currencyCode) │+│ rate = units of currencyCode per 1 unit of company.baseCurrencyCode │+│ written by users; ALWAYS beats the feed; delete = back to market rate │+├─────────────────────────────────────────────────────────────────────────┤+│ currency (GROUP config — unchanged scope, rate columns removed) │+│ (code, companyGroupId): decimalPlaces, active, tags, customFields, │+│ historicalExchangeRate (manual IAS-21 input, consolidation only) │+└─────────────────────────────────────────────────────────────────────────┘++get_exchange_rate(companyId, code, asOf = today) →+ 1. code == company.baseCurrencyCode → 1 (only sanctioned constant)+ 2. exchangeRateOverride(companyId, code) → its rate (source: 'override')+ 3. global: rate(code, ≤asOf) / rate(base, ≤asOf) (source: 'market')+ 4. nothing → ERROR (never 1)+```++- **Rate meaning at every consumer is unchanged**: "document-currency units per 1+ base-currency unit", exactly what the six document headers snapshot today. Generated+ `converted*` columns, posting divides, PDF props, EE sync payloads — all untouched.+- **"Whose base?" dissolves**: the global store is anchored to USD (a property of the+ table, stated in its comment and column name), and every read is per-company via the+ resolver. Two companies in one group with different bases each get correct rates from+ the same global rows — NetSuite's logical-partition-by-base, Odoo's ratio resolution.+- **Feed defers to manual structurally** (NetSuite insert-if-absent, improved): the feed+ writes only the global table; users write only overrides. Different tables — clobbering+ is impossible by construction, no lock flag needed.+- **On by default**: the daily job runs unconditionally (no `companyIntegration` gate).+ The migration seeds the global table with a snapshot so every installation — including+ self-hosted with no `EXCHANGE_RATES_API_KEY` — resolves real rates from day one.++### What gets deleted++- `packages/ee/src/exchange-rates/` (integration `config.tsx`; the fetch/convert client+ moves into the job), the registry entry (`packages/ee/src/index.ts`), the+ `INTEGRATION_WHITELIST` entry (`packages/ee/src/plan.ts:31`), and all+ `companyIntegration` rows with `id = 'exchange-rates-v1'` (migration DELETE).+- `currency.exchangeRate` column (after migrating values to overrides — see Data Model),+ the group-scoped `exchangeRateHistory` table (zero writers ever, zero rows — replaced+ by the global table), and the `?? 1` fallbacks at every stamping site.++### Defect-class fixes folded in++| Defect class (audit) | Fix in this refactor |+|---|---|+| (a) group-scoping half-migration | resolver is per-company; global store is base-agnostic |+| (b) integration-gated rates / `?? 1` | on-by-default feed + seeded snapshot; resolver errors on missing, base=1 only constant |+| (c) snapshot vs live | unchanged snapshot doctrine, now stated: documents stamp at creation/currency-change/explicit refresh; refresh reads the resolver with the DOCUMENT's code (subsumes #1530) |+| (d) direction confusion | `toBaseAmount(amount, rate) = amount / rate`, `fromBaseAmount(amount, rate) = amount * rate` in `functions/shared/precision.ts` (re-exported via `@carbon/utils`); adopted in code this refactor touches; repo-wide checks ban is a follow-up |+| (e) header→line propagation | add the missing salesInvoice trigger pair (subsumes #1527), guarded/idempotent; existing quote/SO interceptors and PO/PI/SQ triggers left alone (working; minimal-impact) |+| (f) validation gaps | CHECK (`exchangeRate > 0`) on the 12 document tables (subsumes #1541), guarded; zod `.positive()` on every exchangeRate field |+| (g1) non-atomic pair | every write that sets `currencyCode` resolves `exchangeRate` in the same action via the resolver (absorbs #1526's `resolveCurrencyAndRate` as the TS wrapper); refresh routes take the code from the document, never the request (#1530) |+| (g2) untyped column families | out of scope for v1 beyond the helpers in (d) — noted as follow-up (branded types / checks rule) |++### Design Decisions++| Decision | Choice | Rationale |+|----------|--------|-----------|+| Global store anchor | USD | Carbon's default base (`20240930183906` backfilled `'USD'`); anchor is invisible to consumers (all reads are ratios); feed's EUR-based payload converted at write |+| Global store shape | `(currencyCode, effectiveDate)` unique, effective-dated; the feed may CORRECT the same day's row via upsert (user data never lives in this table, so same-day correction clobbers nothing) | NetSuite/SAP/BC/Odoo consensus; gives consolidation a real closing/average source; ~43k rows/yr platform-wide |+| Global store tenancy | none (no companyId/companyGroupId), SELECT for all authenticated, writes service-role only | Market data, not tenant data — same class as `currencyCode` reference table; flagged as a deliberate multi-tenancy exception |+| Override scope | per **company**, not group | The entire point: rate-to-base is only well-defined per company; `company.baseCurrencyCode` is the anchor |+| Override dating | standing pin (one row per company+code), not effective-dated | Matches Carbon's current single-current-rate model + document snapshots; NetSuite-style dated manual rows are a compatible future extension |+| Override precedence | override always beats feed; delete restores market rate | QBO "your rate"/"market rate"; separate tables make clobbering structurally impossible |+| `currency` table fate | keep, group-scoped, as currency CONFIG (decimalPlaces, active, tags, customFields, historicalExchangeRate); drop `exchangeRate` | Decimals are intrinsic to a currency (JPY=0 everywhere) and group-sharing them is harmless (blast radius: `useCurrencies`, seeds, backups all unchanged); the rate is what breaks at group scope |+| `historicalExchangeRate` | untouched on `currency` (manual IAS-21 equity rate) | Consolidation's separate concern (NetSuite separates consolidation rates from transaction rates); its direction question is documented, not solved here |+| `exchangeRateHistory` | DROP (replaced by global `exchangeRate` table), guarded: the migration REFUSES if any deployment holds rows (the table was API-reachable even with no app writer) | Zero app writers ever; refusal beats silent discard for the theoretical API-written row |+| Consolidation closing/average | `translateTrialBalance` reads the global table: closing = r(target)/r(source) at period end, average = AVG over period | Its existing `balance * rate` multiply becomes CORRECT once the rate is a true target-per-source pair ratio — resolves the direction contradiction instead of patching it |+| Resolver | SQL functions `get_exchange_rate(companyId, code, asOf)` + `get_exchange_rates(companyId)` (all active codes + source) | One implementation for app services, edge functions (`convert`, `create`), and jobs (`paperless-parts` duplicate dies); PLPGSQL so ordering/inlining is deterministic |+| Missing rate | ERROR (SAP SG105), surfaced at point of use; base=1 the only free constant | Kills the `?? 1` class; seeded snapshot makes "missing" genuinely exceptional (unknown code only) |+| Rate meaning at stamping sites | unchanged: foreign-per-base, stamped on header at creation | Preserves every generated column, posting divide, PDF, sync payload; keeps this refactor orthogonal to the GL convention normalization draft (`2026-07-02-exchange-rate-convention-normalization.md`) |+| Line-level rates | keep (denormalization required by row-local STORED generated columns); complete propagation, don't unify mechanisms | Postgres generated columns can't reference the header; ripping them out is a different, larger refactor |+| Feed job | rewrite `update-exchange-rates` Inngest fn in place (same function id, same cron `0 0 * * *`): fetch once → write global rows for every `currencyCode` | Event/function-name surface FROZEN per BACKWARD_COMPATIBILITY.md; one API call per installation per day regardless of tenant count |+| Feed provider | exchangeratesapi.io via existing `EXCHANGE_RATES_API_KEY` env (global) | No new production dependency; key already provisioned in cloud |+| No-key installs | seeded snapshot + overrides; job logs and skips | Rates work out of the box everywhere; degrade is stale-but-real, never 1.0 |+| Schema contract (ADDITIVE-ONLY) | deliberate exception, data-preserving: `exchangeRate` values migrated to override rows before the column drop | Owner-requested refactor; precedent: this exact table already dropped `name`/`symbol`/`isBaseCurrency`/`companyId`; surfaced for veto |+| Heuristic 1 (multi-tenancy) | `exchangeRateOverride`: `id` default + `companyId`, PK `("id","companyId")`, unique `("companyId","currencyCode")`, composite FK pattern; global table: deliberate exception (above) | House convention |+| Heuristic 2 (service shape) | TS wrappers in `accounting.ee.service.ts` (`getExchangeRate`, `getExchangeRates`) return `{data, error}` | House convention |+| Heuristic 3 (RLS) | override: standard per-company policies (SELECT employee, writes `accounting_update`); global: SELECT `authenticated`, no write policies (service-role only); `currency` policies unchanged | House convention + market-data exception |+| Heuristic 4 (permissions) | exchange-rate routes keep `view/update: "accounting"` | Unchanged surface |+| Heuristic 5 (forms) | `ExchangeRateForm` stays ValidatedForm + zod; gains provenance display + "reset to market rate" | House convention |+| Heuristic 6 (module layout) | accounting module owns everything (`accounting.ee.service.ts`, `accounting.models.ts`); no new module | House convention |+| Heuristic 7 (backward compat) | route paths unchanged; MCP tools (`*_update*ExchangeRate`) unchanged in shape; edge fn names unchanged; service fn signatures: `getCurrencyByCode` keeps working (config row, no rate) — rate callers move to `getExchangeRate` | STABLE surfaces preserved |++## Data Model Changes++One migration (`pnpm db:migrate:new currency-exchange-rate-refactor`), idempotent+throughout (guards on every DDL), forward-dated. Then `pnpm run generate:types`.++```sql+-- 1) Global market-rate store. Deliberately NOT tenant-scoped: market data,+-- same class as "currencyCode". Anchor: units of currencyCode per 1 USD.+CREATE TABLE IF NOT EXISTS "exchangeRate" (+ "id" TEXT NOT NULL DEFAULT id('xrate'),+ "currencyCode" TEXT NOT NULL,+ "effectiveDate" DATE NOT NULL,+ "rate" NUMERIC NOT NULL CHECK ("rate" > 0 AND "rate" <> 'NaN'::numeric), -- NaN > 0 is TRUE in PG+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ CONSTRAINT "exchangeRate_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "exchangeRate_currencyCode_fkey" FOREIGN KEY ("currencyCode")+ REFERENCES "currencyCode"("code") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "exchangeRate_rate_positive" CHECK ("rate" > 0),+ CONSTRAINT "exchangeRate_code_date_key" UNIQUE ("currencyCode", "effectiveDate")+);+CREATE INDEX IF NOT EXISTS "exchangeRate_code_date_idx"+ ON "exchangeRate" ("currencyCode", "effectiveDate" DESC);+ALTER TABLE "exchangeRate" ENABLE ROW LEVEL SECURITY;+CREATE POLICY "SELECT" ON "exchangeRate" FOR SELECT TO authenticated USING (true);+-- no INSERT/UPDATE/DELETE policies: service-role (the feed job) only++-- 2) Per-company user overrides. rate = units of currencyCode per 1 unit of+-- the company's OWN base currency. Standing pin; delete = market rate.+CREATE TABLE IF NOT EXISTS "exchangeRateOverride" (+ "id" TEXT NOT NULL DEFAULT id('xrovr'),+ "companyId" TEXT NOT NULL,+ "currencyCode" TEXT NOT NULL,+ "rate" NUMERIC(20,8) NOT NULL,+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT REFERENCES "user"("id"),+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ CONSTRAINT "exchangeRateOverride_pkey" PRIMARY KEY ("id", "companyId"),+ CONSTRAINT "exchangeRateOverride_companyId_fkey" FOREIGN KEY ("companyId")+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "exchangeRateOverride_currencyCode_fkey" FOREIGN KEY ("currencyCode")+ REFERENCES "currencyCode"("code") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "exchangeRateOverride_rate_positive" CHECK ("rate" > 0),+ CONSTRAINT "exchangeRateOverride_company_code_key" UNIQUE ("companyId", "currencyCode")+);+-- RLS: SELECT for employees of the company; INSERT/UPDATE/DELETE for accounting_update+-- (standard per-company policy shapes, policy names "SELECT"/"INSERT"/"UPDATE"/"DELETE")++-- 3) Seed the global store: static snapshot (as of the migration date) for every+-- code in "currencyCode", ON CONFLICT DO NOTHING. Rates work with no feed/key.++-- 4) Migrate existing user intent to overrides, THEN drop the column:+-- for each companyGroup WITHOUT an active 'exchange-rates-v1' companyIntegration+-- (feed-derived rates must NOT become pins), for each member company, for each+-- currency row with exchangeRate <> 1 AND code <> company.baseCurrencyCode:+-- INSERT INTO "exchangeRateOverride" (companyId, code, rate) preserving the+-- exact value that company resolves today. createdBy = 'system'.+-- ON CONFLICT DO NOTHING.+ALTER TABLE "currency" DROP COLUMN IF EXISTS "exchangeRate";+-- historicalExchangeRate, decimalPlaces, active, tags, customFields remain.++-- 5) DROP + recreate the "currencies" view (SECURITY_INVOKER) without exchangeRate,+-- forked from its NEWEST definition (currency ⋈ currencyCode + name).++-- 6) DROP TABLE IF EXISTS "exchangeRateHistory"; -- zero writers ever, zero rows++-- 7) Resolver (PLPGSQL, STABLE, SECURITY DEFINER not needed — reads are policy-open+-- for the global table; company/override reads run as invoker):+-- get_exchange_rate(company_id TEXT, code TEXT, as_of DATE DEFAULT NULL)+-- → NUMERIC (RAISES on unresolvable; base → 1; override; else ratio of the+-- latest global rows with effectiveDate <= COALESCE(as_of, CURRENT_DATE))+-- get_exchange_rates(company_id TEXT)+-- → TABLE(currencyCode, name, decimalPlaces, rate NUMERIC, source TEXT+-- ('base'|'override'|'market'), rateUpdatedAt) for the group's active+-- currency config rows, resolved for THIS company++-- 8) salesInvoice header→line propagation (subsumes PR #1527), guarded:+-- AFTER UPDATE OF "exchangeRate" ON "salesInvoice" → update lines;+-- BEFORE INSERT ON "salesInvoiceLine" → inherit header rate.+-- Backfill: one-time UPDATE of existing line rates from their header where they+-- disagree AND the invoice is not posted.++-- 9) Positivity (subsumes PR #1541), all guarded ADD CONSTRAINT IF NOT EXISTS /+-- NOT VALID + VALIDATE where data may predate:+-- CHECK ("exchangeRate" > 0) on quote, salesOrder, purchaseOrder, supplierQuote,+-- purchaseInvoice, salesInvoice, quoteLinePrice, salesOrderLine, purchaseOrderLine,+-- supplierQuoteLinePrice, purchaseInvoiceLine, salesInvoiceLine+-- (payment/memo/invoiceSettlement already CHECKed).++-- 10) DELETE FROM "companyIntegration" WHERE "id" = 'exchange-rates-v1';++-- 11) translateTrialBalance + getConsolidationRates: fork NEWEST definitions+-- (20260811123614), closing/average now read the global "exchangeRate" table as+-- r(target)/r(source); historical stays currency."historicalExchangeRate".+-- COALESCE(...,1) fallbacks removed for closing/average (global store is seeded);+-- the multiply convention is now correct by construction.+```++Sequencing note: steps 3–4 run before the column drop in the same transaction; a failed+migration rolls back whole (idempotency guards make retry safe per the+migrations-must-be-idempotent lesson).++Seed-path changes outside the migration: `seed-company` (`functions/lib/seed.data.ts:484`++ `seed-company/index.ts:335`) and `packages/database/src/datasets/bootstrap.ts:300` stop+writing `exchangeRate` (config columns only). Backup scoping: `exchangeRate` joins the+non-tenant reference class; `exchangeRateOverride` is companyId-scoped (auto-discovered);+`packages/jobs/src/backups/scope.test.ts` pins updated.++## API / Service Changes++**New (accounting module, `accounting.ee.service.ts` + `accounting.models.ts`):**+- `getExchangeRate(client, companyId, code)` → `{ data: number, error }` (RPC wrapper).+- `getExchangeRates(client, companyId)` → resolved list with `source` for the admin page.+- `upsertExchangeRateOverride` / `deleteExchangeRateOverride` (route-called).+- `exchangeRateOverrideValidator` (zod, `rate: z.number().positive()`).++**Changed — every stamping site moves `getCurrencyByCode(...).exchangeRate` →+`getExchangeRate(companyId, code)`** (the ~40 sites in the blast-radius file §4.2:+`sales.service.ts` quote/SO create+update+convert, `purchasing.service.ts` PO/supplier+quote, `invoicing.service.ts` both invoices, the six `*.exchange-rate.tsx` refresh routes+— which now take the code from the DOCUMENT row, subsuming #1530 — plus `update.tsx`+actions, finalize, PDF preflight loaders). `?? 1` disappears at each; a resolver error+propagates as the action/loader error. `getCurrencyByCode`/`getCurrencies`/+`getCurrenciesList`/`useCurrencies` keep their shapes (config + decimals; no rate).++**Edge functions:** `convert/index.ts:1084` and `create/index.ts:541` call+`get_exchange_rate` (via their existing clients) instead of reading `currency`; `create`+loses its `?? 1`. No new functions; no `config.toml` changes.++**Jobs:** `update-exchange-rates.ts` rewritten in place: fetch EUR-based payload once+(client code moves here from `packages/ee/src/exchange-rates/exchange-rates.server.ts`),+convert to USD-anchored, upsert today's global rows for every `currencyCode`; no+`companyIntegration` scan; skip-with-log when the env key is absent.+`paperless-parts.ts:808` local helper replaced by the resolver.++**Deleted:** `packages/ee/src/exchange-rates/config.tsx` (+ directory), registry entry,+whitelist entry. The Settings → Integrations page simply no longer lists it.++**Docs:** update the curated docs page for currencies/exchange rates (carbon-docs) — rates+are automatic; overrides documented.++## UI Changes++`/x/accounting/exchange-rates` (list + `$currencyId` drawer):+- List shows the **resolved rate for the viewing company** with a provenance badge —+ "Market rate" (with last-updated date) vs "Your rate" — instead of the raw group row.+- Editing the rate writes an `exchangeRateOverride`; a "Reset to market rate" action+ deletes it. Helper text stays "One {base} = how many {code}?" — now guaranteed true+ because base is the viewer company's and the value is company-resolved.+- Base currency row displays 1, not editable (matches today's client-side clamp, now+ server-true).+- `decimalPlaces` (+ tags/customFields) continue editing the group `currency` config row;+ `historicalExchangeRate` field remains (consolidation input).+- Rate-history chart (currently reading the empty `exchangeRateHistory`) reads the global+ table (market line) — overrides shown as a flat annotation.++No other UI changes: document forms/refresh buttons keep their look; they just resolve+through the new path.++## Acceptance Criteria++- [ ] Two companies in one group with different base currencies (e.g. USD and EUR) each+ resolve `get_exchange_rate` correctly for the same foreign code (e.g. GBP): values+ differ by exactly the ratio of their bases' global rates; each company's own base+ resolves to 1.+- [ ] A fresh company (no integration, no key) creates a EUR quote on a USD base and the+ stamped `quote.exchangeRate` is the seeded/feed market rate — not 1.+- [ ] Creating an override for (company, EUR) changes what new documents stamp; deleting+ it restores the market rate; the nightly job never modifies the override.+- [ ] The nightly job writes one global row per currency per day; running it twice for the+ same date is idempotent; two different-base companies' resolutions are unaffected by+ job iteration order (no per-company writes exist).+- [ ] `exchange-rates-v1` no longer appears in Settings → Integrations; existing+ `companyIntegration` rows are deleted; the exchange-rates page works with no+ integration concept.+- [ ] A sales invoice header rate refresh cascades to its lines (new trigger); a new line+ inherits the header rate (never DEFAULT 1).+- [ ] Attempting to save a 0 or negative rate fails at zod AND at the DB CHECK on all 12+ document tables + both new tables.+- [ ] The six document refresh routes ignore any client-supplied rate/currency and+ re-resolve from the document's own `currencyCode`.+- [ ] `convert` (RFQ→quote) and `create` (outside-op→PO) stamp resolver rates; a+ genuinely unresolvable code errors the operation instead of writing 1.+- [ ] Existing documents are byte-identical: no snapshot column value changes except the+ salesInvoiceLine backfill on unposted invoices.+- [ ] Groups without the integration that had hand-edited rates (≠1, ≠base) resolve the+ same values as before the migration (via migrated overrides).+- [ ] Consolidated balance sheet closing/average translation uses global-store ratios;+ report renders without the COALESCE-to-1 silent fallback.+- [ ] `pnpm db:check:datasets` and `pnpm db:check:backups` pass; `generate:types` clean;+ scoped typechecks pass (`erp`, `@carbon/jobs`, `@carbon/ee`, `@carbon/database`).++## Risks++| Risk | Severity | Mitigation |+|------|----------|------------|+| Column drop (`currency.exchangeRate`) breaks an unswept reader | High | Blast-radius file enumerates every reader; typecheck catches the rest post-`generate:types` (column gone from types); grep sweep for `exchangeRate` on currency reads as a gate |+| Migration mis-classifies feed-derived vs hand-edited rates → wrong overrides pinned | Med | Conservative rule (only integration-INACTIVE groups, only ≠1, only ≠base); overrides are user-visible with a "Reset to market rate" one-click undo |+| Behavior change: fresh companies now stamp real rates instead of 1 | Med | This is the feature; release note + docs. Historic documents untouched (snapshots) |+| Global-table RLS exception sets a precedent | Low | Documented as market-data class beside `currencyCode`; no tenant data in the table |+| `translateTrialBalance` rework changes consolidation numbers | Med | Today's closing/average are COALESCE(...,1) — i.e. wrong-by-fallback; new values are defensible; historical (manual) path unchanged; verify on seeded consolidation data |+| Open PRs #1527/#1541/#1530/#1526/#1542 merge before/after and conflict | Med | All subsumed pieces are guarded/idempotent (double-apply safe); interaction table below; #1542 is explicitly superseded (job rewritten) |+| Feed API shape/limits (EUR base, free tier) | Low | Same API/key as today; write path validates positive + known codes; partial payloads leave prior days' rows standing (resolver takes latest ≤ date) |+| `db:check:backups` scope drift | Low | scope.test.ts updated in the same change; check runs pre-commit |++### Open-PR interaction (from the audit)++| PR | Relationship to this refactor |+|---|---|+| #1542 (job rebases per group) | **Superseded** — the job no longer writes per-tenant rows at all |+| #1530 (refresh from document) | **Subsumed** — refresh routes re-resolve from the document row |+| #1526 (atomic code+rate writes) | **Subsumed conceptually** — resolver at every currency-setting write; if merged first, its `resolveCurrencyAndRate` is replaced by the resolver wrapper |+| #1527 (salesInvoice cascade) | **Subsumed** — same trigger shape, guarded so both can land |+| #1541 (rate > 0 everywhere) | **Subsumed** — same CHECKs, guarded so both can land |+| #1544, #1543, #1532 (direction/rate² bugs) | **Independent — merge first** (irreversible valuation corruption in #1544); refactor adds the helpers that prevent the class |+| #1548, #1549, #1547 (render/sync rate propagation) | **Independent — merge first**; #1547's remaining six syncer gaps are follow-up work |+| #1525 (merged) | Precedent; its refuse-on-missing guard becomes the resolver's default behavior |++## Open Questions++> All resolved autonomously (non-interactive session; user pre-delegated with veto).+> Resolution order: codebase precedent → research consensus → recommendation.++- [x] Global anchor currency — USD or EUR? — **Autonomous:** USD. Carbon's default base+ backfill was USD; anchor is consumer-invisible (ratios); feed payload converted at+ write. (EUR would equally work; USD wins on legibility for the majority tenant.)+- [x] Override scope: company or group? — **Autonomous:** company. `rate-to-base` is only+ well-defined against `company.baseCurrencyCode`; group scope is the bug being fixed.+- [x] Overrides effective-dated? — **Autonomous:** no — standing pin per (company, code),+ v1. Matches the current single-current-rate + snapshot model; dated overrides+ (NetSuite) are a compatible later extension. Trade-off: no scheduled future rates.+- [x] Keep `currency` group-scoped or move per-company? — **Autonomous:** keep group scope+ for what remains (decimalPlaces/active/historicalExchangeRate — intrinsic or+ consolidation-owned; group-sharing harmless), minimizing RLS/backup/seed churn. The+ per-company concern (the rate) moves out entirely.+- [x] Repurpose `exchangeRateHistory` or new table? — **Autonomous:** drop and create the+ global `exchangeRate` table. History table has zero writers/rows; keeping a+ group-scoped shell invites confusion.+- [x] Drop `currency.exchangeRate` despite ADDITIVE-ONLY schema contract? —+ **Autonomous:** yes, with data migrated to overrides first. Owner-requested+ refactor; table has four dropped-column precedents; a live-looking-but-dead rate+ column is the worse outcome. **Surfaced for veto explicitly.**+- [x] Migration heuristic for existing rates → overrides? — **Autonomous:** only+ groups that NEVER had the integration (any exchange-rates-v1 row, active or+ not, means feed-derived values that must not become pins), only rows+ with rate ≠ 1 and code ≠ that company's base, copied per member company (preserves+ each company's currently-resolved value). **Surfaced for veto** — this is the one+ data-shape judgment call.+- [x] Missing-rate behavior at stamping sites — error or warn-and-1? — **Autonomous:**+ error (SAP SG105 consensus; #1525 precedent). Seeded snapshot makes it rare.+- [x] Rewire consolidation closing/average now or later? — **Autonomous:** now, minimally+ (point the existing lookups at the global store; historical untouched). It is the+ only reader of the dropped `exchangeRateHistory`, so leaving it means leaving a+ dangling reader; and its COALESCE-to-1 is a live silent-wrongness.+- [x] Unify header→line propagation mechanisms? — **Autonomous:** no — only add the+ missing salesInvoice pair. Working interceptors/triggers stay (minimal impact).+- [x] Repo-wide `@carbon/checks` ban on raw `* rate` / `/ rate`? — **Autonomous:**+ follow-up, not v1 (baseline cost is large); helpers land now, ban lands with the+ (g2) typed-column-family work.++## Changelog++- 2026-09-02: Created (feature pipeline, autonomous mode). All open questions resolved+ autonomously per the recorded order; two flagged for explicit veto (column drop,+ override-migration heuristic).diff --git a/.claude/rules/billing-system.md b/.claude/rules/billing-system.mdindex 5e07721538..b28b5106b4 100644--- a/.claude/rules/billing-system.md+++ b/.claude/rules/billing-system.md@@ -84,7 +84,7 @@ several `invoice.*` events are forwarded to GTM.`FEATURE_PLANS` (`plan.ts`) is the source of truth — both client and server read it:`API_KEYS, WEBHOOKS, INTEGRATIONS, ITEM_RULES, AUDIT_LOG, EMAIL_NOTIFICATIONS, STORAGE_RULES,CUSTOMER_PORTALS` → each `[Plan.Business, Plan.Partner]`. `INTEGRATION_WHITELIST`-(`email`, `exchange-rates-v1`) bypasses the `INTEGRATIONS` gate.+(`email`) bypasses the `INTEGRATIONS` gate.Server checks (`plan.server.ts`) read `companyPlan.planId` (`.eq("id", companyId)`):diff --git a/apps/erp/app/modules/accounting/AGENTS.md b/apps/erp/app/modules/accounting/AGENTS.mdindex 9d08381121..cca34e5874 100644--- a/apps/erp/app/modules/accounting/AGENTS.md+++ b/apps/erp/app/modules/accounting/AGENTS.md@@ -58,7 +58,7 @@ pnpm --filter @carbon/erp test -- --testPathPattern=accounting| `accountingPeriodBalance` | Cumulative per-account GL balance snapshots. `closeAccountingPeriod` calls `snapshotAccountingPeriodBalances` inside its close transaction (after the flip to Closed) to write them; `reopenAccountingPeriod` deletes them (`endingBalanceDate` ≥ period `endDate`) before flipping back to Open. Read by `accountTreeBalancesByCompany` (snapshot + delta; full-scan fallback when empty) and `accountTreeBalancePeriodSeries` (multi-period: base snapshot before the range start + one bounded scan bucketed by period ends; single uniform branch). Balance RPCs exclude Draft journals. || `periodCloseTaskDefinition` / `periodCloseTask` | NetSuite-style close checklist: company-level task templates + per-period instances (seeded via `seed-company`) || `accountDefault` | Default GL account mappings (AR, AP, inventory, etc.) |-| `currency` / `currencyCode` / `exchangeRateHistory` | Multi-currency with historical rates |+| `currency` / `currencyCode` | Per-group currency config (decimalPlaces, active, historicalExchangeRate); rates live in the global `exchangeRate` store + per-company `exchangeRateOverride` || `paymentTerm` | Payment terms (Net 30, 2/10 Net 30, etc.) || `costCenter` | Hierarchical cost allocation units || `dimension` / `dimensionValue` | Analytical dimensions and custom values |@@ -87,7 +87,9 @@ pnpm --filter @carbon/erp test -- --testPathPattern=accounting- `getPeriodCloseChecklist` / `closePeriodWithChecklist` / `completeCloseTask` / `skipCloseTask` — the close checklist (instantiates tasks, evaluates auto-checks, gates the close)- `getAccountingPeriodDeletability` / `deleteAccountingPeriod` — delete an empty, open period (blocks Locked/Closed or periods with journals)- `getFiscalCalendarCommitted` — is the fiscal calendar committed (any posting or Locked/Closed period)? Gates editing the fiscal start month-- `getCurrencies` / `getBaseCurrency` / `getCurrencyByCode` — currency lookups+- `getCurrencies` / `getBaseCurrency` / `getCurrencyByCode` — currency config lookups (decimals/active; no rate — `currency.exchangeRate` was dropped)+- `getExchangeRate` / `getExchangeRates` — per-company rate resolution (RPC `get_exchange_rate(s)`: base=1, `exchangeRateOverride` wins, else global `exchangeRate` market-store ratio; missing = error, never 1)+- `upsertExchangeRateOverride` / `deleteExchangeRateOverride` — per-company user rate pins (always beat the daily feed)- `translateCompanyBalances` — balance translation for multi-currency consolidation- `getDimensions` / `getActiveDimensionsWithValues` / `saveJournalLineDimensions` — dimension management- `getCostCenters` / `getCostCentersTree` — cost center hierarchy@@ -97,13 +99,13 @@ pnpm --filter @carbon/erp test -- --testPathPattern=accounting## Key Exports```typescript-import { getCurrencyByCode, getPaymentTermsList, getDefaultAccounts } from "~/modules/accounting";+import { getExchangeRate, getPaymentTermsList, getDefaultAccounts } from "~/modules/accounting";```## Related Modules- **purchasing** — purchase invoices post to AP; receipts create inventory GL entries-- **sales** — sales invoices post to AR; quotes use `getCurrencyByCode` for exchange rates+- **sales** — sales invoices post to AR; quotes use `getExchangeRate` for exchange rates- **inventory** — inventory movements create GL entries via posting groups- **items** — `itemPostingGroup` maps item categories to GL accounts- **people** — employees used as dimension values; cost center assignmentsdiff --git a/apps/erp/app/modules/accounting/accounting.ee.service.ts b/apps/erp/app/modules/accounting/accounting.ee.service.tsindex 3d174cbe0d..4a3aeb3d7b 100644--- a/apps/erp/app/modules/accounting/accounting.ee.service.ts+++ b/apps/erp/app/modules/accounting/accounting.ee.service.ts@@ -832,8 +832,9 @@ export async function getConsolidatedPeriodSeries(// RLS `client`. Defaults to `client` (no elimination visibility) when omitted.eliminationClient: SupabaseClient<Database> = client): Promise<{- data: ChartPeriodSeries[];+ data: ChartPeriodSeries[] | null;ctaByBucket: Record<string, number>;+ error: string | null;}> {const bucketKeys = args.buckets.map((b) => b.key);const allIds = await resolveConsolidationCompanyIds(@@ -935,6 +936,17 @@ export async function getConsolidatedPeriodSeries(bucketKeys.map((key) => [key, 0]));+ // A subsidiary whose translation failed must fail the consolidation loudly —+ // silently excluding it produces a wrong consolidated total with no signal.+ const failedSeriesTranslation = results.find((r) => r.translation.error);+ if (failedSeriesTranslation?.translation.error) {+ return {+ data: null,+ ctaByBucket: {},+ error: failedSeriesTranslation.translation.error+ };+ }+for (const { series, translation } of results) {if (translation.error) continue;// This company's raw netChange per (account, bucket) — the flow that the@@ -1057,7 +1069,8 @@ export async function getConsolidatedPeriodSeries(rollUpTranslatedGroups(consolidated, bucketKeys),bucketKeys),- ctaByBucket+ ctaByBucket,+ error: null};}@@ -1950,6 +1963,108 @@ export async function getCurrencyByCode(.single();}+/**+ * The one sanctioned answer to "how many units of `currencyCode` per 1 unit of+ * THIS company's base currency, right now". Base currency resolves to 1 by+ * definition; a user override wins next; otherwise the ratio of the two+ * USD-anchored market rates. A missing rate is an ERROR — never 1.+ */+export async function getExchangeRate(+ client: SupabaseClient<Database>,+ companyId: string,+ currencyCode: string+) {+ return client.rpc("get_exchange_rate", {+ p_company_id: companyId,+ p_currency_code: currencyCode+ });+}++/**+ * Every active currency of the company's group, resolved for THIS company,+ * with provenance: 'base' | 'override' | 'market' | 'missing'. Backs the+ * exchange-rates settings page.+ */+export async function getExchangeRates(+ client: SupabaseClient<Database>,+ companyId: string+) {+ return client.rpc("get_exchange_rates", {+ p_company_id: companyId+ });+}++export async function upsertExchangeRateOverride(+ client: SupabaseClient<Database>,+ override: {+ companyId: string;+ currencyCode: string;+ rate: number;+ createdBy: string;+ updatedBy: string;+ }+) {+ // Update-first so re-pinning a rate never rewrites the original creator.+ const update = await client+ .from("exchangeRateOverride")+ .update({+ rate: override.rate,+ updatedBy: override.updatedBy,+ updatedAt: datetime.timestamp()+ })+ .eq("companyId", override.companyId)+ .eq("currencyCode", override.currencyCode)+ .select("id");++ if (update.error) return { data: null, error: update.error };+ if (update.data.length > 0) {+ return { data: update.data[0] ?? null, error: null };+ }++ const insert = await client+ .from("exchangeRateOverride")+ .insert({+ companyId: override.companyId,+ currencyCode: override.currencyCode,+ rate: override.rate,+ createdBy: override.createdBy+ })+ .select("id")+ .single();++ // Two concurrent first-time pins can both miss the update and race the+ // insert; the loser hits the (companyId, currencyCode) unique constraint.+ // Retry as an update so the second write wins instead of erroring.+ if (insert.error?.code === "23505") {+ const retry = await client+ .from("exchangeRateOverride")+ .update({+ rate: override.rate,+ updatedBy: override.updatedBy,+ updatedAt: datetime.timestamp()+ })+ .eq("companyId", override.companyId)+ .eq("currencyCode", override.currencyCode)+ .select("id");+ if (retry.error) return { data: null, error: retry.error };+ return { data: retry.data[0] ?? null, error: null };+ }++ return insert;+}++export async function deleteExchangeRateOverride(+ client: SupabaseClient<Database>,+ companyId: string,+ currencyCode: string+) {+ return client+ .from("exchangeRateOverride")+ .delete()+ .eq("companyId", companyId)+ .eq("currencyCode", currencyCode);+}+export async function getCurrencies(client: SupabaseClient<Database>,companyGroupId: string,@@ -4287,20 +4402,16 @@ export async function translateCompanyBalances(cta: number;error: string | null;}> {- // getConsolidationRates is defined in migration- // 20260713225803_ledger-balance-posted-filter.sql; the committed DB types- // regenerate from the cloud DB after deploy, hence the cast.- const { data: ratesData, error: ratesError } = await (- client.rpc as unknown as (- fn: string,- args: Record<string, unknown>- ) => PromiseLike<{ data: unknown; error: { message: string } | null }>- )("getConsolidationRates", {- p_company_group_id: companyGroupId,- p_company_id: companyId,- p_period_end: periodEnd,- p_period_start: periodStart- });+ const { data: ratesData, error: ratesError } = await client.rpc(+ "getConsolidationRates",+ {+ p_company_group_id: companyGroupId,+ p_company_id: companyId,+ p_target_currency: targetCurrency,+ p_period_end: periodEnd,+ p_period_start: periodStart+ }+ );if (ratesError) {return { data: null, cta: 0, error: ratesError.message };@@ -4483,6 +4594,13 @@ export async function getConsolidatedBalances(const allBalances = results.map((r) => r.balances);const translations = results.map((r) => r.translation);+ // A subsidiary whose translation failed must fail the consolidation loudly —+ // silently excluding it produces a wrong consolidated total with no signal.+ const failedTranslation = translations.find((t) => t.error);+ if (failedTranslation?.error) {+ return { data: null, cta: 0, error: failedTranslation.error };+ }+// Build a map of translated balances per account, summed across companiesconst translationByAccount = new Map<string,@@ -4563,7 +4681,11 @@ export async function getConsolidatedBalances(};});- return { data: applyRootSignCorrection(consolidated), cta: totalCta };+ return {+ data: applyRootSignCorrection(consolidated),+ cta: totalCta,+ error: null+ };}// -- Intercompany --@@ -4732,21 +4854,26 @@ export async function getIntercompanyBalance(});}+/**+ * Market-rate history for the chart on the exchange-rates page. Reads the+ * platform-global "exchangeRate" store (USD-anchored), newest ~6 months of+ * daily rows, ascending for the chart.+ */export async function getExchangeRateHistory(client: SupabaseClient<Database>,- companyGroupId: string,currencyCode: string) {- const sixMonthsAgo = new Date();- sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6);-- return client- .from("exchangeRateHistory")+ const result = await client+ .from("exchangeRate").select("effectiveDate, rate")- .eq("companyGroupId", companyGroupId).eq("currencyCode", currencyCode)- .gte("effectiveDate", sixMonthsAgo.toISOString().split("T")[0])- .order("effectiveDate", { ascending: true });+ .order("effectiveDate", { ascending: false })+ .limit(180);++ return {+ data: result.data ? [...result.data].reverse() : result.data,+ error: result.error+ };}// -- Journal Entries --diff --git a/apps/erp/app/modules/accounting/accounting.models.ts b/apps/erp/app/modules/accounting/accounting.models.tsindex 340aa1f588..c37163dc46 100644--- a/apps/erp/app/modules/accounting/accounting.models.ts+++ b/apps/erp/app/modules/accounting/accounting.models.ts@@ -417,12 +417,16 @@ export const currencyValidator = z.object({id: zfd.text(z.string().optional()),code: z.string().trim().min(1, { message: "Code is required" }),decimalPlaces: zfd.numeric(z.number().min(0).max(4)),- exchangeRate: zfd.numeric(z.number().min(0, { message: "Rate is required" })),historicalExchangeRate: zfd.numeric(- z.number().min(0, { message: "Rate must be positive" }).optional()+ z.number().positive({ message: "Rate must be positive" }).optional())});+export const exchangeRateOverrideValidator = z.object({+ currencyCode: z.string().trim().min(1, { message: "Currency is required" }),+ rate: zfd.numeric(z.number().positive({ message: "Rate must be positive" }))+});+export const defaultBalanceSheetAccountValidator = z.object({rawMaterialsAccount: z.string().min(1, {message: "Raw materials account is required"diff --git a/apps/erp/app/modules/accounting/ui/ExchangeRates/ExchangeRateForm.tsx b/apps/erp/app/modules/accounting/ui/ExchangeRates/ExchangeRateForm.tsxindex f0035dcb97..6740822d6f 100644--- a/apps/erp/app/modules/accounting/ui/ExchangeRates/ExchangeRateForm.tsx+++ b/apps/erp/app/modules/accounting/ui/ExchangeRates/ExchangeRateForm.tsx@@ -46,7 +46,7 @@ import { useLocale } from "@react-aria/i18n";import { json2csv } from "json-2-csv";import { useCallback, useMemo } from "react";import { LuDownload } from "react-icons/lu";-import { useNavigate } from "react-router";+import { useFetcher, useNavigate } from "react-router";import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from "recharts";import type { z } from "zod";import { DateTime } from "~/components";@@ -59,7 +59,11 @@ import {} from "~/components/Form";import { usePermissions, useUser } from "~/hooks";import { path } from "~/utils/path";-import { currencyValidator } from "../../accounting.models";+import {+ currencyValidator,+ exchangeRateOverrideValidator+} from "../../accounting.models";+import ExchangeRateSourceBadge from "./ExchangeRateSourceBadge";type ExchangeRateHistoryRow = {effectiveDate: string;@@ -68,18 +72,17 @@ type ExchangeRateHistoryRow = {type CurrencyFormProps = {initialValues: z.infer<typeof currencyValidator>;+ rate?: number | null;+ rateSource?: string | null;exchangeRateHistory?: ExchangeRateHistoryRow[];};-const chartConfig = {- rate: {- label: "Exchange Rate",- color: "hsl(var(--primary))"- }-} satisfies ChartConfig;+const CONFIG_FORM_ID = "currency-config-form";const CurrencyForm = ({initialValues,+ rate = null,+ rateSource = null,exchangeRateHistory = []}: CurrencyFormProps) => {const { t } = useLingui();@@ -87,19 +90,30 @@ const CurrencyForm = ({const navigate = useNavigate();const onClose = () => navigate(-1);const { locale } = useLocale();+ const resetFetcher = useFetcher<{}>();const { company } = useUser();const isBaseCurrency = company?.baseCurrencyCode === initialValues.code;const exchangeRateHelperText = isBaseCurrency- ? "This is the base currency. Exchange rate is always 1."- : `One ${company?.baseCurrencyCode} is equal to how many ${initialValues.code}?`;+ ? t`This is the base currency. Exchange rate is always 1.`+ : t`One ${company?.baseCurrencyCode} is equal to how many ${initialValues.code}?`;const isEditing = initialValues.id !== undefined;const isDisabled = isEditing? !permissions.can("update", "accounting"): !permissions.can("create", "accounting");+ const chartConfig = useMemo<ChartConfig>(+ () => ({+ rate: {+ label: t`Market rate (per USD)`,+ color: "hsl(var(--primary))"+ }+ }),+ [t]+ );+const chartData = useMemo(() =>exchangeRateHistory.map((row) => ({@@ -125,6 +139,14 @@ const CurrencyForm = ({document.body.removeChild(a);}, [exchangeRateHistory, initialValues.code]);+ const onResetToMarketRate = useCallback(() => {+ if (!initialValues.id || !initialValues.code) return;+ resetFetcher.submit(+ { intent: "reset", currencyCode: initialValues.code },+ { method: "post", action: path.to.exchangeRate(initialValues.id) }+ );+ }, [initialValues.code, initialValues.id, resetFetcher]);+return (<Draweropen@@ -133,75 +155,117 @@ const CurrencyForm = ({}}><DrawerContent>- <ValidatedForm- validator={currencyValidator}- method="post"- action={- isEditing- ? path.to.exchangeRate(initialValues.id!)- : path.to.newExchangeRate- }- defaultValues={initialValues}- className="flex flex-col h-full"- >+ <div className="flex flex-col h-full"><DrawerHeader>- <DrawerTitle>{isEditing ? "Edit" : "New"} Currency</DrawerTitle>+ <DrawerTitle>+ {isEditing ? t`Edit Currency` : t`New Currency`}+ </DrawerTitle></DrawerHeader><DrawerBody>- <Hidden name="id" />- <VStack spacing={4}>- <Input name="name" label="Name" isReadOnly />- <Input name="code" label="Code" isReadOnly />- <NumberField- name="decimalPlaces"- label={t`Decimal Places`}- termId="decimal-places-currency"- minValue={0}- maxValue={4}- />- <NumberField- name="exchangeRate"- label={t`Exchange Rate`}- termId="exchange-rate"- minValue={isBaseCurrency ? 1 : 0}- maxValue={isBaseCurrency ? 1 : undefined}- step={INPUT_STEP.exchangeRate}- formatOptions={INPUT_FORMAT.exchangeRate}- helperText={exchangeRateHelperText}- />- {!isBaseCurrency && (+ {isEditing && (+ <ValidatedForm+ validator={exchangeRateOverrideValidator}+ method="post"+ action={path.to.exchangeRate(initialValues.id!)}+ defaultValues={{+ currencyCode: initialValues.code,+ rate: rate ?? undefined+ }}+ className="w-full mb-6"+ >+ <Hidden name="intent" value="override" />+ <Hidden name="currencyCode" value={initialValues.code} />+ <VStack spacing={4}>+ <NumberField+ name="rate"+ label={t`Exchange Rate`}+ termId="exchange-rate"+ minValue={0}+ step={INPUT_STEP.exchangeRate}+ formatOptions={INPUT_FORMAT.exchangeRate}+ helperText={exchangeRateHelperText}+ isDisabled={isBaseCurrency}+ />+ <HStack className="w-full justify-between">+ <ExchangeRateSourceBadge source={rateSource} />+ {!isBaseCurrency && (+ <HStack>+ {rateSource === "override" && (+ <Button+ type="button"+ variant="secondary"+ isDisabled={isDisabled}+ isLoading={resetFetcher.state !== "idle"}+ onClick={onResetToMarketRate}+ >+ {t`Reset to market rate`}+ </Button>+ )}+ <Submit isDisabled={isDisabled}>{t`Save Rate`}</Submit>+ </HStack>+ )}+ </HStack>+ </VStack>+ </ValidatedForm>+ )}++ <ValidatedForm+ id={CONFIG_FORM_ID}+ validator={currencyValidator}+ method="post"+ action={+ isEditing+ ? path.to.exchangeRate(initialValues.id!)+ : path.to.newExchangeRate+ }+ defaultValues={initialValues}+ className="w-full"+ >+ <Hidden name="id" />+ <VStack spacing={4}>+ <Input name="name" label={t`Name`} isReadOnly />+ <Input name="code" label={t`Code`} isReadOnly /><NumberField- name="historicalExchangeRate"- label={t`Historical Rate (Equity)`}- termId="historical-exchange-rate"+ name="decimalPlaces"+ label={t`Decimal Places`}+ termId="decimal-places-currency"minValue={0}- step={INPUT_STEP.exchangeRate}- formatOptions={INPUT_FORMAT.exchangeRate}- helperText="Rate used for equity account translation in consolidation (IAS 21). Leave blank to use the current exchange rate."+ maxValue={4}/>- )}+ {!isBaseCurrency && (+ <NumberField+ name="historicalExchangeRate"+ label={t`Historical Rate (Equity)`}+ termId="historical-exchange-rate"+ minValue={0}+ step={INPUT_STEP.exchangeRate}+ formatOptions={INPUT_FORMAT.exchangeRate}+ helperText={t`Rate used for equity account translation in consolidation (IAS 21). Leave blank to use the current exchange rate.`}+ />+ )}- <CustomFormFields table="currency" />- </VStack>+ <CustomFormFields table="currency" />+ </VStack>+ </ValidatedForm>{isEditing && !isBaseCurrency && hasHistory && (<Tabs defaultValue="chart" className="mt-6 w-full"><Card className="w-full"><HStack className="items-center justify-between"><CardHeader>- <CardTitle>Exchange Rate History</CardTitle>+ <CardTitle>{t`Market Rate History (per USD)`}</CardTitle></CardHeader><CardAction><HStack><TabsList>- <TabsTrigger value="chart">Chart</TabsTrigger>- <TabsTrigger value="table">Table</TabsTrigger>+ <TabsTrigger value="chart">{t`Chart`}</TabsTrigger>+ <TabsTrigger value="table">{t`Table`}</TabsTrigger></TabsList><Tooltip><TooltipTrigger asChild><IconButton- aria-label="Download CSV"- title="Download CSV"+ aria-label={t`Download CSV`}+ title={t`Download CSV`}variant="ghost"icon={<LuDownload />}className="!border-dashed border-border"@@ -209,7 +273,7 @@ const CurrencyForm = ({/></TooltipTrigger><TooltipContent>- <p>Download CSV</p>+ <p>{t`Download CSV`}</p></TooltipContent></Tooltip></HStack>@@ -273,8 +337,8 @@ const CurrencyForm = ({<Table><Thead><Tr>- <Th>Date</Th>- <Th className="text-right">Rate</Th>+ <Th>{t`Date`}</Th>+ <Th className="text-right">{t`Rate`}</Th></Tr></Thead><Tbody>@@ -299,13 +363,15 @@ const CurrencyForm = ({</DrawerBody><DrawerFooter><HStack>- <Submit isDisabled={isDisabled}>Save</Submit>+ <Submit formId={CONFIG_FORM_ID} isDisabled={isDisabled}>+ {t`Save`}+ </Submit><Button variant="solid" onClick={onClose}>- Cancel+ {t`Cancel`}</Button></HStack></DrawerFooter>- </ValidatedForm>+ </div></DrawerContent></Drawer>);diff --git a/apps/erp/app/modules/accounting/ui/ExchangeRates/ExchangeRateSourceBadge.tsx b/apps/erp/app/modules/accounting/ui/ExchangeRates/ExchangeRateSourceBadge.tsxnew file mode 100644index 0000000000..7ff994d7bc--- /dev/null+++ b/apps/erp/app/modules/accounting/ui/ExchangeRates/ExchangeRateSourceBadge.tsx@@ -0,0 +1,25 @@+import { Badge } from "@carbon/react";+import { useLingui } from "@lingui/react/macro";++type ExchangeRateSourceBadgeProps = {+ source: string | null | undefined;+};++const ExchangeRateSourceBadge = ({ source }: ExchangeRateSourceBadgeProps) => {+ const { t } = useLingui();++ switch (source) {+ case "base":+ return <Badge variant="secondary">{t`Base currency`}</Badge>;+ case "override":+ return <Badge variant="blue">{t`Your rate`}</Badge>;+ case "market":+ return <Badge variant="green">{t`Market rate`}</Badge>;+ case "missing":+ return <Badge variant="red">{t`No rate`}</Badge>;+ default:+ return null;+ }+};++export default ExchangeRateSourceBadge;diff --git a/apps/erp/app/modules/accounting/ui/ExchangeRates/ExchangeRatesTable.tsx b/apps/erp/app/modules/accounting/ui/ExchangeRates/ExchangeRatesTable.tsxindex 6d88f501fe..3ed612bb7b 100644--- a/apps/erp/app/modules/accounting/ui/ExchangeRates/ExchangeRatesTable.tsx+++ b/apps/erp/app/modules/accounting/ui/ExchangeRates/ExchangeRatesTable.tsx@@ -1,17 +1,33 @@import { MenuIcon, MenuItem } from "@carbon/react";+import { formatDate, formatExchangeRate } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";+import { useLocale } from "@react-aria/i18n";import type { ColumnDef } from "@tanstack/react-table";import { memo, useCallback, useMemo } from "react";-import { LuBookMarked, LuEuro, LuPencil, LuPercent } from "react-icons/lu";+import {+ LuBookMarked,+ LuCalendar,+ LuEuro,+ LuGlobe,+ LuPencil,+ LuPercent+} from "react-icons/lu";import { useNavigate } from "react-router";import { Hyperlink, Table } from "~/components";import { usePermissions, useUrlParams } from "~/hooks";import { useCustomColumns } from "~/hooks/useCustomColumns";import { path } from "~/utils/path";import type { Currency } from "../../types";+import ExchangeRateSourceBadge from "./ExchangeRateSourceBadge";++type CurrencyWithRate = Currency & {+ rate: number | null;+ rateSource: string | null;+ rateUpdatedAt: string | null;+};type ExchangeRatesTableProps = {- data: Currency[];+ data: CurrencyWithRate[];count: number;};@@ -20,10 +36,11 @@ const ExchangeRatesTable = memo(({ data, count }: ExchangeRatesTableProps) => {const [params] = useUrlParams();const navigate = useNavigate();const permissions = usePermissions();- const customColumns = useCustomColumns<Currency>("currency");+ const { locale } = useLocale();+ const customColumns = useCustomColumns<CurrencyWithRate>("currency");- const columns = useMemo<ColumnDef<Currency>[]>(() => {- const defaultColumns: ColumnDef<Currency>[] = [+ const columns = useMemo<ColumnDef<CurrencyWithRate>[]>(() => {+ const defaultColumns: ColumnDef<CurrencyWithRate>[] = [{accessorKey: "name",header: t`Name`,@@ -45,19 +62,51 @@ const ExchangeRatesTable = memo(({ data, count }: ExchangeRatesTableProps) => {}},{- accessorKey: "exchangeRate",+ accessorKey: "rate",header: t`Exchange Rate`,- cell: (item) => item.getValue(),+ enableSorting: false,+ cell: ({ row }) =>+ row.original.rate != null+ ? formatExchangeRate(row.original.rate, locale)+ : null,meta: {icon: <LuPercent />}+ },+ {+ accessorKey: "rateSource",+ header: t`Source`,+ enableSorting: false,+ cell: ({ row }) => (+ <ExchangeRateSourceBadge source={row.original.rateSource} />+ ),+ meta: {+ icon: <LuGlobe />,+ exportValue: (row: CurrencyWithRate) => row.rateSource+ }+ },+ {+ accessorKey: "rateUpdatedAt",+ header: t`Updated`,+ enableSorting: false,+ cell: ({ row }) =>+ row.original.rateUpdatedAt+ ? formatDate(row.original.rateUpdatedAt, undefined, locale)+ : null,+ meta: {+ icon: <LuCalendar />,+ exportValue: (row: CurrencyWithRate) =>+ row.rateUpdatedAt+ ? formatDate(row.rateUpdatedAt, undefined, locale)+ : null+ }}];return [...defaultColumns, ...customColumns];- }, [customColumns, t]);+ }, [customColumns, locale, t]);const renderContextMenu = useCallback(- (row: Currency) => {+ (row: CurrencyWithRate) => {return (<><MenuItem@@ -78,7 +127,7 @@ const ExchangeRatesTable = memo(({ data, count }: ExchangeRatesTableProps) => {);return (- <Table<Currency>+ <Table<CurrencyWithRate>data={data}columns={columns}count={count}diff --git a/apps/erp/app/modules/accounting/ui/ExchangeRates/index.ts b/apps/erp/app/modules/accounting/ui/ExchangeRates/index.tsindex 88209d16e2..fa292cae2a 100644--- a/apps/erp/app/modules/accounting/ui/ExchangeRates/index.ts+++ b/apps/erp/app/modules/accounting/ui/ExchangeRates/index.ts@@ -1,4 +1,5 @@import ExchangeRateForm from "./ExchangeRateForm";+import ExchangeRateSourceBadge from "./ExchangeRateSourceBadge";import ExchangeRatesTable from "./ExchangeRatesTable";-export { ExchangeRateForm, ExchangeRatesTable };+export { ExchangeRateForm, ExchangeRateSourceBadge, ExchangeRatesTable };diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.tsindex 4019c339a0..d226f23554 100644--- a/apps/erp/app/modules/invoicing/invoicing.service.ts+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts@@ -13,7 +13,7 @@ import {import type { GenericQueryFilters } from "~/utils/query";import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";import { sanitize } from "~/utils/supabase";-import { getCurrencyByCode } from "../accounting/accounting.ee.service";+import { getExchangeRate } from "../accounting/accounting.ee.service";import { getEmployeeJob } from "../people/people.service";import {getCustomerPayment,@@ -560,20 +560,19 @@ export async function insertPurchaseInvoice(const { shippingMethodId, shippingTermId, incoterm, incotermLocation } =supplierShipping.data;- let exchangeRate = input.exchangeRate ?? 1;+ let exchangeRate = input.exchangeRate;let exchangeRateUpdatedAt =input.exchangeRateUpdatedAt ?? new Date().toISOString();if (input.currencyCode) {- const currency = await getCurrencyByCode(+ const rate = await getExchangeRate(client,- input.companyGroupId,+ input.companyId,input.currencyCode);- if (currency.data) {- exchangeRate = currency.data.exchangeRate ?? 1;- exchangeRateUpdatedAt = new Date().toISOString();- }+ if (rate.error) return { data: null, error: rate.error };+ exchangeRate = rate.data;+ exchangeRateUpdatedAt = new Date().toISOString();}const locationId = input.locationId ?? purchaser?.data?.locationId ?? null;@@ -726,15 +725,14 @@ export async function upsertPurchaseInvoice(supplierShipping.data;if (purchaseInvoice.currencyCode) {- const currency = await getCurrencyByCode(+ const rate = await getExchangeRate(client,- purchaseInvoice.companyGroupId,+ purchaseInvoice.companyId,purchaseInvoice.currencyCode);- if (currency.data) {- purchaseInvoice.exchangeRate = currency.data.exchangeRate ?? undefined;- purchaseInvoice.exchangeRateUpdatedAt = new Date().toISOString();- }+ if (rate.error) return rate;+ purchaseInvoice.exchangeRate = rate.data;+ purchaseInvoice.exchangeRateUpdatedAt = new Date().toISOString();} else {purchaseInvoice.exchangeRate = 1;purchaseInvoice.exchangeRateUpdatedAt = new Date().toISOString();@@ -938,20 +936,19 @@ export async function insertSalesInvoice(const { shippingMethodId, shippingTermId, incoterm, incotermLocation } =customerShipping.data;- let exchangeRate = input.exchangeRate ?? 1;+ let exchangeRate = input.exchangeRate;let exchangeRateUpdatedAt =input.exchangeRateUpdatedAt ?? new Date().toISOString();if (input.currencyCode) {- const currency = await getCurrencyByCode(+ const rate = await getExchangeRate(client,- input.companyGroupId,+ input.companyId,input.currencyCode);- if (currency.data) {- exchangeRate = currency.data.exchangeRate ?? 1;- exchangeRateUpdatedAt = new Date().toISOString();- }+ if (rate.error) return { data: null, error: rate.error };+ exchangeRate = rate.data;+ exchangeRateUpdatedAt = new Date().toISOString();}const locationId = input.locationId ?? salesPerson?.data?.locationId ?? null;@@ -1104,15 +1101,14 @@ export async function upsertSalesInvoice(customerShipping.data;if (salesInvoice.currencyCode) {- const currency = await getCurrencyByCode(+ const rate = await getExchangeRate(client,- salesInvoice.companyGroupId,+ salesInvoice.companyId,salesInvoice.currencyCode);- if (currency.data) {- salesInvoice.exchangeRate = currency.data.exchangeRate ?? undefined;- salesInvoice.exchangeRateUpdatedAt = new Date().toISOString();- }+ if (rate.error) return rate;+ salesInvoice.exchangeRate = rate.data;+ salesInvoice.exchangeRateUpdatedAt = new Date().toISOString();} else {salesInvoice.exchangeRate = 1;salesInvoice.exchangeRateUpdatedAt = new Date().toISOString();diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceProperties.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceProperties.tsxindex 2896aa373b..2d422d3947 100644--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceProperties.tsx+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceProperties.tsx@@ -451,12 +451,7 @@ const PurchaseInvoiceProperties = () => {icon={<LuRefreshCcw />}isDisabled={isDisabled}onClick={() => {- const formData = new FormData();- formData.append(- "currencyCode",- routeData?.purchaseInvoice?.currencyCode ?? ""- );- exchangeRateFetcher.submit(formData, {+ exchangeRateFetcher.submit(null, {method: "post",action: path.to.purchaseInvoiceExchangeRate(invoiceId)});diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceProperties.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceProperties.tsxindex 7b4988dbf5..7659ab94d4 100644--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceProperties.tsx+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceProperties.tsx@@ -433,12 +433,7 @@ const SalesInvoiceProperties = () => {icon={<LuRefreshCcw />}isDisabled={isDisabled}onClick={() => {- const formData = new FormData();- formData.append(- "currencyCode",- routeData?.salesInvoice?.currencyCode ?? ""- );- exchangeRateFetcher.submit(formData, {+ exchangeRateFetcher.submit(null, {method: "post",action: path.to.salesInvoiceExchangeRate(invoiceId)});diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.tsindex dec71a81a9..58cb1b9a6b 100644--- a/apps/erp/app/modules/purchasing/purchasing.service.ts+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts@@ -13,7 +13,7 @@ import { getEmployeeJob } from "~/modules/people";import type { GenericQueryFilters } from "~/utils/query";import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";import { sanitize } from "~/utils/supabase";-import { getCurrencyByCode } from "../accounting/accounting.ee.service";+import { getExchangeRate } from "../accounting/accounting.ee.service";import type { PurchaseInvoice } from "../invoicing/types";import {canApproveRequest,@@ -1477,6 +1477,21 @@ export async function insertPurchaseOrder(purchaseOrderId = seq.data;}+ // Resolve the rate BEFORE inserting the supplier interaction — a resolver+ // failure must not leave an orphaned interaction row behind.+ let exchangeRate = 1;+ let exchangeRateUpdatedAt = new Date().toISOString();+ if (input.currencyCode) {+ const rate = await getExchangeRate(+ client,+ input.companyId,+ input.currencyCode+ );+ if (rate.error) return { data: null, error: rate.error };+ exchangeRate = rate.data;+ exchangeRateUpdatedAt = new Date().toISOString();+ }+const [supplierInteraction, supplierPayment, supplierShipping, purchaser] =await Promise.all([insertSupplierInteraction(client, input.companyId, input.supplierId),@@ -1502,20 +1517,6 @@ export async function insertPurchaseOrder(const { shippingMethodId, shippingTermId, incoterm, incotermLocation } =supplierShipping.data;- let exchangeRate = 1;- let exchangeRateUpdatedAt = new Date().toISOString();- if (input.currencyCode) {- const currency = await getCurrencyByCode(- client,- input.companyGroupId,- input.currencyCode- );- if (currency.data) {- exchangeRate = currency.data.exchangeRate ?? 1;- exchangeRateUpdatedAt = new Date().toISOString();- }- }-const locationId = input.locationId ?? purchaser?.data?.locationId ?? null;const order = await client@@ -1595,8 +1596,7 @@ export async function updatePurchaseOrder(purchaseOrderType?: (typeof purchaseOrderTypeType)[number];notes?: string | null;customFields?: Json;- },- companyGroupId?: string+ }): Promise<{data: { id: string } | null;error: import("@supabase/supabase-js").PostgrestError | null;@@ -1605,16 +1605,22 @@ export async function updatePurchaseOrder(let exchangeRate: number | undefined;let exchangeRateUpdatedAt: string | undefined;- if (updates.currencyCode && companyGroupId) {- const currency = await getCurrencyByCode(+ if (updates.currencyCode) {+ const existing = await client+ .from("purchaseOrder")+ .select("companyId")+ .eq("id", id)+ .single();+ if (existing.error) return { data: null, error: existing.error };++ const rate = await getExchangeRate(client,- companyGroupId,+ existing.data.companyId,updates.currencyCode);- if (currency.data) {- exchangeRate = currency.data.exchangeRate ?? 1;- exchangeRateUpdatedAt = new Date().toISOString();- }+ if (rate.error) return { data: null, error: rate.error };+ exchangeRate = rate.data;+ exchangeRateUpdatedAt = new Date().toISOString();}return client@@ -1666,6 +1672,22 @@ export async function upsertPurchaseOrder(.select("id, purchaseOrderId");}+ // Resolve the rate BEFORE inserting the supplier interaction — a resolver+ // failure must not leave an orphaned interaction row behind.+ if (purchaseOrder.currencyCode) {+ const rate = await getExchangeRate(+ client,+ purchaseOrder.companyId,+ purchaseOrder.currencyCode+ );+ if (rate.error) return { data: null, error: rate.error };+ purchaseOrder.exchangeRate = rate.data;+ purchaseOrder.exchangeRateUpdatedAt = new Date().toISOString();+ } else {+ purchaseOrder.exchangeRate = 1;+ purchaseOrder.exchangeRateUpdatedAt = new Date().toISOString();+ }+const [supplierInteraction, supplierPayment, supplierShipping, purchaser] =await Promise.all([insertSupplierInteraction(@@ -1692,21 +1714,6 @@ export async function upsertPurchaseOrder(const { shippingMethodId, shippingTermId, incoterm, incotermLocation } =supplierShipping.data;- if (purchaseOrder.currencyCode) {- const currency = await getCurrencyByCode(- client,- purchaseOrder.companyGroupId,- purchaseOrder.currencyCode- );- if (currency.data) {- purchaseOrder.exchangeRate = currency.data.exchangeRate ?? undefined;- purchaseOrder.exchangeRateUpdatedAt = new Date().toISOString();- }- } else {- purchaseOrder.exchangeRate = 1;- purchaseOrder.exchangeRateUpdatedAt = new Date().toISOString();- }-const locationId =purchaseOrder.locationId ?? purchaser?.data?.locationId ?? null;@@ -2074,15 +2081,14 @@ export async function insertSupplierQuote(let exchangeRate = 1;let exchangeRateUpdatedAt = new Date().toISOString();if (input.currencyCode) {- const currency = await getCurrencyByCode(+ const rate = await getExchangeRate(client,- input.companyGroupId,+ input.companyId,input.currencyCode);- if (currency.data) {- exchangeRate = currency.data.exchangeRate ?? 1;- exchangeRateUpdatedAt = new Date().toISOString();- }+ if (rate.error) return { data: null, error: rate.error };+ exchangeRate = rate.data;+ exchangeRateUpdatedAt = new Date().toISOString();}const supplierInteraction = await insertSupplierInteraction(@@ -2155,8 +2161,7 @@ export async function updateSupplierQuote(supplierLocationId?: string | null;notes?: string | null;customFields?: Json;- },- companyGroupId?: string+ }): Promise<{data: { id: string } | null;error: import("@supabase/supabase-js").PostgrestError | null;@@ -2168,7 +2173,7 @@ export async function updateSupplierQuote(const existing = await client.from("supplierQuote")- .select("currencyCode")+ .select("currencyCode, companyId").eq("id", id).single();@@ -2176,18 +2181,16 @@ export async function updateSupplierQuote(if (updates.currencyCode &&- companyGroupId &&existing.data.currencyCode !== updates.currencyCode) {- const currency = await getCurrencyByCode(+ const rate = await getExchangeRate(client,- companyGroupId,+ existing.data.companyId,updates.currencyCode);- if (currency.data) {- exchangeRate = currency.data.exchangeRate ?? 1;- exchangeRateUpdatedAt = new Date().toISOString();- }+ if (rate.error) return { data: null, error: rate.error };+ exchangeRate = rate.data;+ exchangeRateUpdatedAt = new Date().toISOString();}return client@@ -2232,15 +2235,14 @@ export async function upsertSupplierQuote() {if ("createdBy" in supplierQuote) {if (supplierQuote.currencyCode) {- const currency = await getCurrencyByCode(+ const rate = await getExchangeRate(client,- supplierQuote.companyGroupId,+ supplierQuote.companyId,supplierQuote.currencyCode);- if (currency.data) {- supplierQuote.exchangeRate = currency.data.exchangeRate ?? undefined;- supplierQuote.exchangeRateUpdatedAt = new Date().toISOString();- }+ if (rate.error) return { data: null, error: rate.error };+ supplierQuote.exchangeRate = rate.data;+ supplierQuote.exchangeRateUpdatedAt = new Date().toISOString();} else {supplierQuote.exchangeRate = 1;supplierQuote.exchangeRateUpdatedAt = new Date().toISOString();@@ -2318,15 +2320,14 @@ export async function upsertSupplierQuote(supplierQuote.currencyCode &¤cyCode !== supplierQuote.currencyCode) {- const currency = await getCurrencyByCode(+ const rate = await getExchangeRate(client,- supplierQuote.companyGroupId,+ companyId,supplierQuote.currencyCode);- if (currency.data) {- supplierQuote.exchangeRate = currency.data.exchangeRate ?? undefined;- supplierQuote.exchangeRateUpdatedAt = new Date().toISOString();- }+ if (rate.error) return { data: null, error: rate.error };+ supplierQuote.exchangeRate = rate.data;+ supplierQuote.exchangeRateUpdatedAt = new Date().toISOString();}const { companyGroupId: _companyGroupId2, ...supplierQuoteUpdateData } =supplierQuote;diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderProperties.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderProperties.tsxindex 4e55ab39dd..6f57ed0bfd 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderProperties.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderProperties.tsx@@ -461,12 +461,7 @@ const PurchaseOrderProperties = () => {icon={<LuRefreshCcw />}isDisabled={isDisabled}onClick={() => {- const formData = new FormData();- formData.append(- "currencyCode",- routeData?.purchaseOrder?.currencyCode ?? ""- );- exchangeRateFetcher.submit(formData, {+ exchangeRateFetcher.submit(null, {method: "post",action: path.to.purchaseOrderExchangeRate(orderId)});diff --git a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteProperties.tsx b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteProperties.tsxindex 9b9329ad56..d86b073178 100644--- a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteProperties.tsx+++ b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteProperties.tsx@@ -338,12 +338,7 @@ const SupplierQuoteProperties = () => {icon={<LuRefreshCcw />}isDisabled={isDisabled}onClick={() => {- const formData = new FormData();- formData.append(- "currencyCode",- routeData?.quote?.currencyCode ?? ""- );- exchangeRateFetcher.submit(formData, {+ exchangeRateFetcher.submit(null, {method: "post",action: path.to.supplierQuoteExchangeRate(id)});diff --git a/apps/erp/app/modules/sales/AGENTS.md b/apps/erp/app/modules/sales/AGENTS.mdindex 685be13e33..3d71f055ed 100644--- a/apps/erp/app/modules/sales/AGENTS.md+++ b/apps/erp/app/modules/sales/AGENTS.md@@ -82,7 +82,7 @@ import { resolvePrice, applyPriceRules, getCustomer } from "~/modules/sales";- **items** — quote lines reference items; methods copied from item make methods- **purchasing** — outside operations on quotes create PO lines- **inventory** — shipments fulfill sales order lines-- **accounting** — sales invoices tie to orders; `getCurrencyByCode` used for exchange rates+- **accounting** — sales invoices tie to orders; `getExchangeRate` resolves document exchange rates (per-company: base=1, override, else global market store)- **people** — `getEmployeeJob` used for assignee lookups## Rules Referencesdiff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.tsindex f4f642ae01..2141dbbed8 100644--- a/apps/erp/app/modules/sales/sales.service.ts+++ b/apps/erp/app/modules/sales/sales.service.ts@@ -18,7 +18,7 @@ import { getEmployeeJob } from "~/modules/people";import type { GenericQueryFilters } from "~/utils/query";import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";import { sanitize } from "~/utils/supabase";-import { getCurrencyByCode } from "../accounting";+import { getExchangeRate } from "../accounting";import type {operationParameterValidator,operationStepValidator,@@ -3516,15 +3516,16 @@ export async function insertQuote(let exchangeRate = 1;let exchangeRateUpdatedAt = new Date().toISOString();if (input.currencyCode) {- const currency = await getCurrencyByCode(+ const exchangeRateResult = await getExchangeRate(client,- input.companyGroupId,+ input.companyId,input.currencyCode);- if (currency.data) {- exchangeRate = currency.data.exchangeRate ?? 1;- exchangeRateUpdatedAt = new Date().toISOString();+ if (exchangeRateResult.error) {+ return { data: null, error: exchangeRateResult.error };}+ exchangeRate = exchangeRateResult.data;+ exchangeRateUpdatedAt = new Date().toISOString();}const locationId = input.locationId ?? seller?.data?.locationId ?? null;@@ -3624,8 +3625,7 @@ export async function updateQuote(digitalQuoteAcceptedByEmail?: string | null;notes?: string | null;customFields?: Json;- },- companyGroupId?: string+ }): Promise<{data: { id: string } | null;error: PostgrestError | null;@@ -3637,7 +3637,7 @@ export async function updateQuote(const existing = await client.from("quote")- .select("currencyCode, opportunityId")+ .select("companyId, currencyCode, opportunityId").eq("id", id).single();@@ -3645,18 +3645,18 @@ export async function updateQuote(if (updates.currencyCode &&- companyGroupId &&existing.data.currencyCode !== updates.currencyCode) {- const currency = await getCurrencyByCode(+ const exchangeRateResult = await getExchangeRate(client,- companyGroupId,+ existing.data.companyId,updates.currencyCode);- if (currency.data) {- exchangeRate = currency.data.exchangeRate ?? 1;- exchangeRateUpdatedAt = new Date().toISOString();+ if (exchangeRateResult.error) {+ return { data: null, error: exchangeRateResult.error };}+ exchangeRate = exchangeRateResult.data;+ exchangeRateUpdatedAt = new Date().toISOString();}if (updates.customerId && existing.data.opportunityId) {@@ -3729,15 +3729,16 @@ export async function upsertQuote(customerShipping.data;if (quote.currencyCode) {- const currency = await getCurrencyByCode(+ const exchangeRateResult = await getExchangeRate(client,- quote.companyGroupId,+ quote.companyId,quote.currencyCode);- if (currency.data) {- quote.exchangeRate = currency.data.exchangeRate ?? undefined;- quote.exchangeRateUpdatedAt = new Date().toISOString();+ if (exchangeRateResult.error) {+ return { data: null, error: exchangeRateResult.error };}+ quote.exchangeRate = exchangeRateResult.data;+ quote.exchangeRateUpdatedAt = new Date().toISOString();} else {quote.exchangeRate = 1;quote.exchangeRateUpdatedAt = new Date().toISOString();@@ -3825,15 +3826,16 @@ export async function upsertQuote(const { currencyCode, opportunityId } = existingQuote.data;if (quote.currencyCode && currencyCode !== quote.currencyCode) {- const currency = await getCurrencyByCode(+ const exchangeRateResult = await getExchangeRate(client,- quote.companyGroupId,+ existingQuote.data.companyId,quote.currencyCode);- if (currency.data) {- quote.exchangeRate = currency.data.exchangeRate ?? undefined;- quote.exchangeRateUpdatedAt = new Date().toISOString();+ if (exchangeRateResult.error) {+ return { data: null, error: exchangeRateResult.error };}+ quote.exchangeRate = exchangeRateResult.data;+ quote.exchangeRateUpdatedAt = new Date().toISOString();}// If customerId is being updated, also update the opportunity's customerId@@ -4006,6 +4008,13 @@ async function rewriteQuoteLinePrices();}+ const exchangeRate = quote.exchangeRate;+ if (exchangeRate === null) {+ throw new Error(+ `Quote ${quoteId} has no exchange rate for company ${companyId}`+ );+ }+await trx.deleteFrom("quoteLinePrice").where("quoteLineId", "=", lineId)@@ -4042,7 +4051,7 @@ async function rewriteQuoteLinePrices((existing?.priceSource as QuoteLinePriceSource | null) ??undefined}),- exchangeRate: quote.exchangeRate ?? 1+ exchangeRate};}))@@ -4422,7 +4431,13 @@ export async function buildMakeToOrderPriceRows(itemIdOverride === undefined? (lineResult.data.itemId ?? undefined): (itemIdOverride ?? undefined);- const exchangeRate = quoteResult.data.exchangeRate ?? 1;+ const exchangeRate = quoteResult.data.exchangeRate;+ if (exchangeRate === null) {+ return {+ rows: [],+ error: new Error(`Quote ${quoteId} has no exchange rate`)+ };+ }const precision = lineResult.data.unitPricePrecision ?? 2;// Parse default markups (settings stores decimals, convert to whole numbers)@@ -4546,7 +4561,13 @@ export async function buildPullFromInventoryPriceRows(// Missing itemId is a benign draft state, not an error.if (!itemId) return { rows: [], error: null };- const exchangeRate = quoteResult.data.exchangeRate ?? 1;+ const exchangeRate = quoteResult.data.exchangeRate;+ if (exchangeRate === null) {+ return {+ rows: [],+ error: new Error(`Quote ${quoteId} has no exchange rate`)+ };+ }const precision = lineResult.data.unitPricePrecision ?? 2;const customerId = quoteResult.data.customerId ?? undefined;@@ -4635,7 +4656,13 @@ export async function buildPurchaseToOrderPriceRows(itemIdOverride === undefined ? lineResult.data.itemId : itemIdOverride;if (!itemId) return { rows: [], error: null };- const exchangeRate = quoteResult.data.exchangeRate ?? 1;+ const exchangeRate = quoteResult.data.exchangeRate;+ if (exchangeRate === null) {+ return {+ rows: [],+ error: new Error(`Quote ${quoteId} has no exchange rate`)+ };+ }const precision = lineResult.data.unitPricePrecision ?? 2;const customerId = quoteResult.data.customerId ?? undefined;@@ -5324,15 +5351,16 @@ export async function insertSalesOrder(let exchangeRate = 1;let exchangeRateUpdatedAt = new Date().toISOString();if (currencyCode) {- const currency = await getCurrencyByCode(+ const exchangeRateResult = await getExchangeRate(client,- input.companyGroupId,+ input.companyId,currencyCode);- if (currency.data) {- exchangeRate = currency.data.exchangeRate ?? 1;- exchangeRateUpdatedAt = new Date().toISOString();+ if (exchangeRateResult.error) {+ return { data: null, error: exchangeRateResult.error };}+ exchangeRate = exchangeRateResult.data;+ exchangeRateUpdatedAt = new Date().toISOString();}const locationId = input.locationId ?? seller?.data?.locationId ?? null;@@ -5414,8 +5442,7 @@ export async function updateSalesOrder(customerId?: string;notes?: string | null;customFields?: Json;- },- companyGroupId?: string+ }): Promise<{data: { id: string } | null;error: PostgrestError | null;@@ -5427,7 +5454,7 @@ export async function updateSalesOrder(const existing = await client.from("salesOrder")- .select("currencyCode, opportunityId")+ .select("companyId, currencyCode, opportunityId").eq("id", id).single();@@ -5435,18 +5462,18 @@ export async function updateSalesOrder(if (updates.currencyCode &&- companyGroupId &&existing.data.currencyCode !== updates.currencyCode) {- const currency = await getCurrencyByCode(+ const exchangeRateResult = await getExchangeRate(client,- companyGroupId,+ existing.data.companyId,updates.currencyCode);- if (currency.data) {- exchangeRate = currency.data.exchangeRate ?? 1;- exchangeRateUpdatedAt = new Date().toISOString();+ if (exchangeRateResult.error) {+ return { data: null, error: exchangeRateResult.error };}+ exchangeRate = exchangeRateResult.data;+ exchangeRateUpdatedAt = new Date().toISOString();}if (updates.customerId && existing.data.opportunityId) {@@ -5597,15 +5624,16 @@ export async function upsertSalesOrder(const { currencyCode, opportunityId } = existingSalesOrder.data;if (salesOrder.currencyCode && currencyCode !== salesOrder.currencyCode) {- const currency = await getCurrencyByCode(+ const exchangeRateResult = await getExchangeRate(client,- salesOrder.companyGroupId,+ existingSalesOrder.data.companyId,salesOrder.currencyCode);- if (currency.data) {- salesOrder.exchangeRate = currency.data.exchangeRate ?? undefined;- salesOrder.exchangeRateUpdatedAt = new Date().toISOString();+ if (exchangeRateResult.error) {+ return { data: null, error: exchangeRateResult.error };}+ salesOrder.exchangeRate = exchangeRateResult.data;+ salesOrder.exchangeRateUpdatedAt = new Date().toISOString();}// If customerId is being updated, also update the opportunity's customerId@@ -5657,15 +5685,16 @@ export async function upsertSalesOrder(const locationId = employee?.data?.locationId ?? null;if (salesOrder.currencyCode) {- const currency = await getCurrencyByCode(+ const exchangeRateResult = await getExchangeRate(client,- salesOrder.companyGroupId,+ salesOrder.companyId,salesOrder.currencyCode);- if (currency.data) {- salesOrder.exchangeRate = currency.data.exchangeRate ?? undefined;- salesOrder.exchangeRateUpdatedAt = new Date().toISOString();+ if (exchangeRateResult.error) {+ return { data: null, error: exchangeRateResult.error };}+ salesOrder.exchangeRate = exchangeRateResult.data;+ salesOrder.exchangeRateUpdatedAt = new Date().toISOString();} else {salesOrder.exchangeRate = 1;salesOrder.exchangeRateUpdatedAt = new Date().toISOString();@@ -5796,6 +5825,16 @@ export async function upsertSalesOrderLine(const salesOrder = await getSalesOrder(client, salesOrderLine.salesOrderId);if (salesOrder.error) return salesOrder;+ const exchangeRate = salesOrder.data.exchangeRate;+ if (exchangeRate === null) {+ return {+ data: null,+ error: new Error(+ `Sales order ${salesOrderLine.salesOrderId} has no exchange rate`+ )+ };+ }+const existing = await client.from("salesOrderLine").select("sortOrder")@@ -5823,7 +5862,7 @@ export async function upsertSalesOrderLine(addOnCost: salesOrderLine.addOnCost ?? 0,nonTaxableAddOnCost: salesOrderLine.nonTaxableAddOnCost ?? 0,taxPercent: salesOrderLine.taxPercent ?? 0,- exchangeRate: salesOrder.data?.exchangeRate ?? 1,+ exchangeRate,sortOrder: maxSortOrder + 1}])diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteProperties.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteProperties.tsxindex b2d4e800b8..8a0f138f75 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteProperties.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteProperties.tsx@@ -436,12 +436,7 @@ const QuoteProperties = () => {icon={<LuRefreshCcw />}isDisabled={isDisabled}onClick={() => {- const formData = new FormData();- formData.append(- "currencyCode",- routeData?.quote?.currencyCode ?? ""- );- exchangeRateFetcher.submit(formData, {+ exchangeRateFetcher.submit(null, {method: "post",action: path.to.quoteExchangeRate(quoteId)});diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderProperties.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderProperties.tsxindex 8c4cd07aab..1c22b942a4 100644--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderProperties.tsx+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderProperties.tsx@@ -437,12 +437,7 @@ const SalesOrderProperties = () => {icon={<LuRefreshCcw />}isDisabled={isDisabled}onClick={() => {- const formData = new FormData();- formData.append(- "currencyCode",- routeData?.salesOrder?.currencyCode ?? ""- );- exchangeRateFetcher.submit(formData, {+ exchangeRateFetcher.submit(null, {method: "post",action: path.to.salesOrderExchangeRate(orderId)});diff --git a/apps/erp/app/modules/settings/documentPreview.server.ts b/apps/erp/app/modules/settings/documentPreview.server.tsindex d5a358f00b..1bad8120d1 100644--- a/apps/erp/app/modules/settings/documentPreview.server.ts+++ b/apps/erp/app/modules/settings/documentPreview.server.ts@@ -2,7 +2,7 @@ import type { Database } from "@carbon/database";import { withRevisionSuffix } from "@carbon/documents/utils";import type { JSONContent } from "@carbon/react";import type { SupabaseClient } from "@supabase/supabase-js";-import { getCurrencyByCode, getPaymentTermsList } from "~/modules/accounting";+import { getPaymentTermsList } from "~/modules/accounting";import {getShippingMethodsList,getStockTransfer,@@ -121,7 +121,6 @@ const emptyThumbnails: Record<string, string | null> = {};export async function buildPreviewProps(client: Client,companyId: string,- companyGroupId: string,documentType: string,id: string,locale: string@@ -247,16 +246,10 @@ export async function buildPreviewProps(getShippingMethodsList(client, companyId)]);if (!quote.data) return null;- let exchangeRate = 1;- if (quote.data.currencyCode) {- const currency = await getCurrencyByCode(- client,- companyGroupId,- quote.data.currencyCode- );- if (currency.data?.exchangeRate)- exchangeRate = currency.data.exchangeRate;- }+ // The document's own stamped rate — never a live lookup, so a reprint+ // can't silently change. Legacy pre-stamping quotes (null) render at 1,+ // consistent with their line snapshots' default.+ const exchangeRate = quote.data.exchangeRate ?? 1;return {...base,exchangeRate,diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.tsindex 1c3510edbe..6479edba46 100644--- a/apps/erp/app/modules/settings/settings.service.ts+++ b/apps/erp/app/modules/settings/settings.service.ts@@ -1,6 +1,7 @@import { SUPABASE_URL } from "@carbon/auth";import type { Database, Json } from "@carbon/database";import { getCompanyTimeZone } from "@carbon/database";+import type { Kysely, KyselyDatabase } from "@carbon/database/client";import type {DocumentBlock,DocumentSectionPlacement,@@ -903,6 +904,33 @@ export async function updateCompany(return client.from("company").update(sanitize(company)).eq("id", companyId);}+/**+ * Company update for a BASE-CURRENCY change: exchange-rate overrides are+ * denominated in the old base, so they must be cleared in the SAME transaction+ * — a committed base flip with surviving old-base pins silently mis-rates+ * every new document, and a non-atomic cleanup can race a freshly created+ * new-base override. Kysely throws on rollback; the route try/catches.+ */+export async function updateCompanyWithBaseCurrencyChange(+ db: Kysely<KyselyDatabase>,+ companyId: string,+ company: Partial<z.infer<typeof companyValidator>> & {+ updatedBy: string;+ }+) {+ return db.transaction().execute(async (trx) => {+ await trx+ .updateTable("company")+ .set(sanitize(company))+ .where("id", "=", companyId)+ .execute();+ await trx+ .deleteFrom("exchangeRateOverride")+ .where("companyId", "=", companyId)+ .execute();+ });+}+export async function updateShelfLifeSettings(client: SupabaseClient<Database>,companyId: string,diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex e1c5887ec7..15631d78f0 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json@@ -1,6 +1,6 @@{- "generated": "2026-09-03T02:17:05.898Z",- "totalTools": 1490,+ "generated": "2026-09-03T04:29:35.054Z",+ "totalTools": 1495,"modules": 15,"tools": [{@@ -1372,6 +1372,107 @@]}},+ {+ "name": "accounting_getExchangeRate",+ "module": "accounting",+ "classification": "READ",+ "description": "get exchange rate",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "companyId",+ "currencyCode"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "currencyCode": {+ "type": "string"+ }+ },+ "required": [+ "currencyCode"+ ]+ }+ },+ {+ "name": "accounting_getExchangeRates",+ "module": "accounting",+ "classification": "READ",+ "description": "get exchange rates",+ "paramCount": 0,+ "serviceParams": [+ "client",+ "companyId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {}+ }+ },+ {+ "name": "accounting_upsertExchangeRateOverride",+ "module": "accounting",+ "classification": "WRITE",+ "description": "upsert exchange rate override",+ "paramCount": 2,+ "serviceParams": [+ "client",+ "override"+ ],+ "injectAuth": [+ "companyId",+ "createdBy",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "currencyCode": {+ "type": "string"+ },+ "rate": {+ "type": "number"+ }+ },+ "required": [+ "currencyCode",+ "rate"+ ]+ }+ },+ {+ "name": "accounting_deleteExchangeRateOverride",+ "module": "accounting",+ "classification": "DESTRUCTIVE",+ "description": "delete exchange rate override",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "companyId",+ "currencyCode"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "currencyCode": {+ "type": "string"+ }+ },+ "required": [+ "currencyCode"+ ]+ }+ },{"name": "accounting_getCurrencies","module": "accounting",@@ -2485,7 +2586,7 @@"module": "accounting","classification": "WRITE","description": "upsert currency",- "paramCount": 5,+ "paramCount": 4,"serviceParams": ["client","currency"@@ -2507,9 +2608,6 @@"decimalPlaces": {"type": "number"},- "exchangeRate": {- "type": "number"- },"historicalExchangeRate": {"type": "number"},@@ -3208,7 +3306,6 @@"paramCount": 1,"serviceParams": ["client",- "companyGroupId","currencyCode"],"injectAuth": [@@ -29958,8 +30055,7 @@"paramCount": 11,"serviceParams": ["client",- "input",- "companyGroupId"+ "input"],"injectAuth": ["companyId",@@ -30388,8 +30484,7 @@"paramCount": 8,"serviceParams": ["client",- "input",- "companyGroupId"+ "input"],"injectAuth": ["companyId",@@ -42107,8 +42202,7 @@"paramCount": 17,"serviceParams": ["client",- "input",- "companyGroupId"+ "input"],"injectAuth": ["companyId",@@ -43337,8 +43431,7 @@"paramCount": 9,"serviceParams": ["client",- "input",- "companyGroupId"+ "input"],"injectAuth": ["companyId",@@ -45392,6 +45485,31 @@]}},+ {+ "name": "settings_updateCompanyWithBaseCurrencyChange",+ "module": "settings",+ "classification": "DESTRUCTIVE",+ "description": "update company with base currency change",+ "paramCount": 1,+ "serviceParams": [+ "db",+ "companyId",+ "company"+ ],+ "injectAuth": [+ "companyId",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "company": {}+ },+ "required": [+ "company"+ ]+ }+ },{"name": "settings_updateShelfLifeSettings","module": "settings",diff --git a/apps/erp/app/routes/file+/quote+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/quote+/$id[.]pdf.tsxindex 394b1cdbdc..d1f8a58129 100644--- a/apps/erp/app/routes/file+/quote+/$id[.]pdf.tsx+++ b/apps/erp/app/routes/file+/quote+/$id[.]pdf.tsx@@ -141,7 +141,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}, {}) ?? {};}- let exchangeRate = 1;+ // The document's own stamped rate — never a live lookup, so a reprint can't+ // silently change. Legacy pre-stamping quotes (null) render at 1, consistent+ // with their line snapshots' default. The currency row is read for its+ // display decimals only.+ const exchangeRate = quote.data?.exchangeRate ?? 1;let currencyDecimals: number | null = null;if (quote.data?.currencyCode) {const currency = await getCurrencyByCode(@@ -149,9 +153,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {companyGroupId,quote.data.currencyCode);- if (currency.data?.exchangeRate) {- exchangeRate = currency.data.exchangeRate;- }currencyDecimals = currency.data?.decimalPlaces ?? null;}diff --git a/apps/erp/app/routes/x+/accounting+/exchange-rates.$currencyId.tsx b/apps/erp/app/routes/x+/accounting+/exchange-rates.$currencyId.tsxindex 35d258bdae..ca61d16d29 100644--- a/apps/erp/app/routes/x+/accounting+/exchange-rates.$currencyId.tsx+++ b/apps/erp/app/routes/x+/accounting+/exchange-rates.$currencyId.tsx@@ -10,9 +10,13 @@ import type {import { data, redirect, useLoaderData } from "react-router";import {currencyValidator,+ deleteExchangeRateOverride,+ exchangeRateOverrideValidator,getCurrency,getExchangeRateHistory,- upsertCurrency+ getExchangeRates,+ upsertCurrency,+ upsertExchangeRateOverride} from "~/modules/accounting";import { ExchangeRateForm } from "~/modules/accounting/ui/ExchangeRates";import { getCustomFields, setCustomFields } from "~/utils/form";@@ -20,7 +24,7 @@ import { getParams, path } from "~/utils/path";import { currenciesQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {- const { client, companyGroupId } = await requirePermissions(request, {+ const { client, companyId } = await requirePermissions(request, {view: "accounting",role: "employee"});@@ -29,24 +33,119 @@ export async function loader({ request, params }: LoaderFunctionArgs) {if (!currencyId) throw notFound("currencyId not found");const currency = await getCurrency(client, currencyId);- const exchangeRateHistory =- currency.data && currency.data.code- ? await getExchangeRateHistory(client, companyGroupId, currency.data.code)- : { data: [] };+ const code = currency.data?.code;++ const [exchangeRates, exchangeRateHistory] = code+ ? await Promise.all([+ getExchangeRates(client, companyId),+ getExchangeRateHistory(client, code)+ ])+ : [{ data: null }, { data: [] }];++ const resolved =+ exchangeRates.data?.find((rate) => rate.currencyCode === code) ?? null;return {currency: currency?.data ?? null,+ rate: resolved?.rate ?? null,+ rateSource: resolved?.source ?? null,exchangeRateHistory: exchangeRateHistory?.data ?? []};}export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);- const { client, companyGroupId, userId } = await requirePermissions(request, {- update: "accounting"- });+ const { client, companyId, companyGroupId, userId } =+ await requirePermissions(request, {+ update: "accounting"+ });const formData = await request.formData();+ const intent = formData.get("intent");++ if (intent === "override") {+ const validation = await validator(exchangeRateOverrideValidator).validate(+ formData+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ // The base currency is 1 by definition and the resolver checks base before+ // overrides — a pin on the base code would be invisible dead data (and turn+ // wrong the day the base changes). The UI hides the field; enforce it here.+ const company = await client+ .from("company")+ .select("baseCurrencyCode")+ .eq("id", companyId)+ .single();+ if (company.data?.baseCurrencyCode === validation.data.currencyCode) {+ return data(+ {},+ await flash(+ request,+ error(null, "The base currency's exchange rate is always 1")+ )+ );+ }++ const upsertOverride = await upsertExchangeRateOverride(client, {+ companyId,+ currencyCode: validation.data.currencyCode,+ rate: validation.data.rate,+ createdBy: userId,+ updatedBy: userId+ });++ if (upsertOverride.error) {+ return data(+ {},+ await flash(+ request,+ error(upsertOverride.error, "Failed to update exchange rate")+ )+ );+ }++ throw redirect(+ `${path.to.exchangeRates}?${getParams(request)}`,+ await flash(request, success("Updated exchange rate"))+ );+ }++ if (intent === "reset") {+ const currencyCode = formData.get("currencyCode");++ if (typeof currencyCode !== "string" || !currencyCode) {+ return data(+ {},+ await flash(request, error(null, "Currency code is required"))+ );+ }++ const removeOverride = await deleteExchangeRateOverride(+ client,+ companyId,+ currencyCode+ );++ if (removeOverride.error) {+ return data(+ {},+ await flash(+ request,+ error(removeOverride.error, "Failed to reset exchange rate")+ )+ );+ }++ throw redirect(+ `${path.to.exchangeRates}?${getParams(request)}`,+ await flash(request, success("Reset to market rate"))+ );+ }+const validation = await validator(currencyValidator).validate(formData);if (validation.error) {@@ -69,14 +168,14 @@ export async function action({ request }: ActionFunctionArgs) {{},await flash(request,- error(updateCurrency.error, "Failed to update exchange rate")+ error(updateCurrency.error, "Failed to update currency")));}throw redirect(`${path.to.exchangeRates}?${getParams(request)}`,- await flash(request, success("Updated exchange rate"))+ await flash(request, success("Updated currency")));}@@ -86,13 +185,13 @@ export async function clientAction({ serverAction }: ClientActionFunctionArgs) {}export default function EditExchangeRateRoute() {- const { currency, exchangeRateHistory } = useLoaderData<typeof loader>();+ const { currency, rate, rateSource, exchangeRateHistory } =+ useLoaderData<typeof loader>();const initialValues = {id: currency?.id ?? undefined,name: currency?.currencyCode?.name ?? "",code: currency?.code ?? "",- exchangeRate: currency?.exchangeRate ?? 1,historicalExchangeRate: currency?.historicalExchangeRate ?? undefined,decimalPlaces: currency?.decimalPlaces ?? 2,...getCustomFields(currency?.customFields)@@ -102,6 +201,8 @@ export default function EditExchangeRateRoute() {<ExchangeRateFormkey={initialValues.id}initialValues={initialValues}+ rate={rate}+ rateSource={rateSource}exchangeRateHistory={exchangeRateHistory}/>);diff --git a/apps/erp/app/routes/x+/accounting+/exchange-rates.tsx b/apps/erp/app/routes/x+/accounting+/exchange-rates.tsxindex 4d26e76ade..fb7cd66da8 100644--- a/apps/erp/app/routes/x+/accounting+/exchange-rates.tsx+++ b/apps/erp/app/routes/x+/accounting+/exchange-rates.tsx@@ -1,9 +1,11 @@+import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";import { VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";-import { Outlet, useLoaderData } from "react-router";-import { getCurrencies } from "~/modules/accounting";+import { Outlet, redirect, useLoaderData } from "react-router";+import { getCurrencies, getExchangeRates } from "~/modules/accounting";import { ExchangeRatesTable } from "~/modules/accounting/ui/ExchangeRates";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";@@ -15,10 +17,13 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyGroupId } = await requirePermissions(request, {- view: "accounting",- role: "employee"- });+ const { client, companyId, companyGroupId } = await requirePermissions(+ request,+ {+ view: "accounting",+ role: "employee"+ }+ );const url = new URL(request.url);const searchParams = new URLSearchParams(url.search);@@ -26,13 +31,50 @@ export async function loader({ request }: LoaderFunctionArgs) {const { limit, offset, sorts, filters } =getGenericQueryFilters(searchParams);- return await getCurrencies(client, companyGroupId, {- search,- limit,- offset,- sorts,- filters- });+ const [currencies, exchangeRates] = await Promise.all([+ getCurrencies(client, companyGroupId, {+ search,+ limit,+ offset,+ sorts,+ filters+ }),+ getExchangeRates(client, companyId)+ ]);++ // A broken rates page must not be indistinguishable from a healthy one —+ // this is the screen that administers the rates.+ if (currencies.error || exchangeRates.error) {+ throw redirect(+ path.to.accounting,+ await flash(+ request,+ error(+ currencies.error ?? exchangeRates.error,+ "Failed to load exchange rates"+ )+ )+ );+ }++ const resolvedByCode = new Map(+ (exchangeRates.data ?? []).map((rate) => [rate.currencyCode, rate])+ );++ return {+ count: currencies.count ?? 0,+ data: (currencies.data ?? []).map((currency) => {+ const resolved = currency.code+ ? resolvedByCode.get(currency.code)+ : undefined;+ return {+ ...currency,+ rate: resolved?.rate ?? null,+ rateSource: resolved?.source ?? null,+ rateUpdatedAt: resolved?.rateUpdatedAt ?? null+ };+ })+ };}export default function ExchangeRatesRoute() {diff --git a/apps/erp/app/routes/x+/get-started+/_layout.tsx b/apps/erp/app/routes/x+/get-started+/_layout.tsxindex c35aa81b98..13cf515772 100644--- a/apps/erp/app/routes/x+/get-started+/_layout.tsx+++ b/apps/erp/app/routes/x+/get-started+/_layout.tsx@@ -105,9 +105,7 @@ const SETUP_SCREEN_PATHS: Record<string, string> = {"default-accounts": path.to.accountingDefaults,"cost-centers": path.to.costCenters,"payment-terms": path.to.paymentTerms,- // Exchange rates are set up by installing the integration, so deep-link to- // the integrations page pre-filtered to it rather than the rates list.- "exchange-rates": `${path.to.integrations}?search=exchange`,+ "exchange-rates": path.to.exchangeRates,"fiscal-year": path.to.fiscalYears,"accounting-periods": path.to.accountingPeriods,"asset-classes": path.to.assetClasses,diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.exchange-rate.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.exchange-rate.tsxindex f3229e9504..b70a7fa66b 100644--- a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.exchange-rate.tsx+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.exchange-rate.tsx@@ -3,7 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";-import { getCurrencyByCode } from "~/modules/accounting";+import { getExchangeRate } from "~/modules/accounting";import {getPurchaseInvoice,isPurchaseInvoiceLocked,@@ -14,7 +14,7 @@ import { path, requestReferrer } from "~/utils/path";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, companyGroupId, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {update: "invoicing"});@@ -44,21 +44,23 @@ export async function action({ request, params }: ActionFunctionArgs) {message: "Cannot modify a confirmed purchase invoice."});- const formData = await request.formData();- const currencyCode = formData.get("currencyCode") as string;+ const currencyCode = purchaseInvoice.data?.currencyCode;if (!currencyCode) throw new Error("Could not find currencyCode");- const currency = await getCurrencyByCode(- client,- companyGroupId,- currencyCode- );- if (currency.error || !currency.data.exchangeRate)- throw new Error("Could not find currency");+ const exchangeRate = await getExchangeRate(client, companyId, currencyCode);+ if (exchangeRate.error) {+ throw redirect(+ requestReferrer(request) ?? path.to.purchaseInvoiceDetails(invoiceId),+ await flash(+ request,+ error(exchangeRate.error, "Failed to get exchange rate")+ )+ );+ }const update = await updatePurchaseInvoiceExchangeRate(client, {id: invoiceId,- exchangeRate: currency.data.exchangeRate,+ exchangeRate: exchangeRate.data,updatedBy: userId});diff --git a/apps/erp/app/routes/x+/purchase-invoice+/update.tsx b/apps/erp/app/routes/x+/purchase-invoice+/update.tsxindex 93dae44734..bf5bf4d4e2 100644--- a/apps/erp/app/routes/x+/purchase-invoice+/update.tsx+++ b/apps/erp/app/routes/x+/purchase-invoice+/update.tsx@@ -1,6 +1,6 @@import { requirePermissions } from "@carbon/auth/auth.server";import type { ActionFunctionArgs } from "react-router";-import { getCurrencyByCode } from "~/modules/accounting";+import { getExchangeRate } from "~/modules/accounting";import {computeInvoiceDateDue,isPurchaseInvoiceLocked@@ -8,10 +8,9 @@ import {import { requireUnlockedBulk } from "~/utils/lockedGuard.server";export async function action({ request }: ActionFunctionArgs) {- const { client, companyGroupId, companyId, userId } =- await requirePermissions(request, {- update: "sales"- });+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "sales"+ });const formData = await request.formData();const ids = formData.getAll("ids");@@ -53,11 +52,8 @@ export async function action({ request }: ActionFunctionArgs) {if (supplier.data?.currencyCode) {currencyCode = supplier.data.currencyCode;- const currency = await getCurrencyByCode(- client,- companyGroupId,- currencyCode- );+ const rate = await getExchangeRate(client, companyId, currencyCode);+ if (rate.error) return rate;return await client.from("purchaseInvoice").update({@@ -65,7 +61,7 @@ export async function action({ request }: ActionFunctionArgs) {invoiceSupplierContactId: null,invoiceSupplierLocationId: null,currencyCode: currencyCode ?? undefined,- exchangeRate: currency.data?.exchangeRate ?? 1,+ exchangeRate: rate.data,updatedBy: userId,updatedAt: new Date().toISOString()})@@ -134,22 +130,17 @@ export async function action({ request }: ActionFunctionArgs) {// don't break -- just let it catch the next casecase "currencyCode":if (value) {- const currency = await getCurrencyByCode(- client,- companyGroupId,- value as string- );- if (currency.data) {- return await client- .from("purchaseInvoice")- .update({- currencyCode: value as string,- exchangeRate: currency.data.exchangeRate ?? 1,- updatedBy: userId,- updatedAt: new Date().toISOString()- })- .in("id", ids as string[]);- }+ const rate = await getExchangeRate(client, companyId, value as string);+ if (rate.error) return rate;+ return await client+ .from("purchaseInvoice")+ .update({+ currencyCode: value as string,+ exchangeRate: rate.data,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ .in("id", ids as string[]);}// don't break -- just let it catch the next casecase "supplierId":diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.details.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.details.tsxindex 0db95ba47f..9618476626 100644--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.details.tsx+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.details.tsx@@ -96,7 +96,7 @@ export async function action({ request, params }: ActionFunctionArgs) {const isLocked = isPurchaseOrderLocked(purchaseOrder.data?.status);// If locked, require delete permission; otherwise require update permission- const { client, companyGroupId, userId } = await requirePermissions(request, {+ const { client, userId } = await requirePermissions(request, {...(isLocked ? { delete: "purchasing" } : { update: "purchasing" })});@@ -116,24 +116,20 @@ export async function action({ request, params }: ActionFunctionArgs) {return validationError(validation.error);}- const result = await updatePurchaseOrder(- client,- {- id: orderId,- status: validation.data.status,- supplierId: validation.data.supplierId,- currencyCode: validation.data.currencyCode,- orderDate: validation.data.orderDate,- supplierContactId: validation.data.supplierContactId || null,- supplierLocationId: validation.data.supplierLocationId || null,- supplierReference: validation.data.supplierReference,- purchaseOrderType: validation.data.purchaseOrderType,- notes: validation.data.notes,- customFields: setCustomFields(formData),- updatedBy: userId- },- companyGroupId- );+ const result = await updatePurchaseOrder(client, {+ id: orderId,+ status: validation.data.status,+ supplierId: validation.data.supplierId,+ currencyCode: validation.data.currencyCode,+ orderDate: validation.data.orderDate,+ supplierContactId: validation.data.supplierContactId || null,+ supplierLocationId: validation.data.supplierLocationId || null,+ supplierReference: validation.data.supplierReference,+ purchaseOrderType: validation.data.purchaseOrderType,+ notes: validation.data.notes,+ customFields: setCustomFields(formData),+ updatedBy: userId+ });if (result.error) {throw redirect(path.to.purchaseOrder(orderId),diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.exchange-rate.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.exchange-rate.tsxindex 523ab659c3..3563515799 100644--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.exchange-rate.tsx+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.exchange-rate.tsx@@ -3,7 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";-import { getCurrencyByCode } from "~/modules/accounting";+import { getExchangeRate } from "~/modules/accounting";import {getPurchaseOrder,isPurchaseOrderLocked,@@ -14,7 +14,7 @@ import { path } from "~/utils/path";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, companyGroupId } = await requirePermissions(request, {+ const { client, companyId } = await requirePermissions(request, {create: "purchasing"});@@ -44,21 +44,23 @@ export async function action({ request, params }: ActionFunctionArgs) {message: "Cannot modify a confirmed purchase order."});- const formData = await request.formData();- const currencyCode = formData.get("currencyCode") as string;+ const currencyCode = purchaseOrder.data?.currencyCode;if (!currencyCode) throw new Error("Could not find currencyCode");- const currency = await getCurrencyByCode(- client,- companyGroupId,- currencyCode- );- if (currency.error || !currency.data.exchangeRate)- throw new Error("Could not find currency");+ const exchangeRate = await getExchangeRate(client, companyId, currencyCode);+ if (exchangeRate.error) {+ throw redirect(+ path.to.purchaseOrderDetails(orderId),+ await flash(+ request,+ error(exchangeRate.error, "Failed to get exchange rate")+ )+ );+ }const update = await updatePurchaseOrderExchangeRate(client, {id: orderId,- exchangeRate: currency.data.exchangeRate+ exchangeRate: exchangeRate.data});if (update.error) {diff --git a/apps/erp/app/routes/x+/purchase-order+/update.tsx b/apps/erp/app/routes/x+/purchase-order+/update.tsxindex 0a3f0b6b9d..e6f5cafe81 100644--- a/apps/erp/app/routes/x+/purchase-order+/update.tsx+++ b/apps/erp/app/routes/x+/purchase-order+/update.tsx@@ -1,11 +1,11 @@import { requirePermissions } from "@carbon/auth/auth.server";import type { ActionFunctionArgs } from "react-router";-import { getCurrencyByCode } from "~/modules/accounting";+import { getExchangeRate } from "~/modules/accounting";import { isPurchaseOrderLocked } from "~/modules/purchasing";import { requireUnlockedBulk } from "~/utils/lockedGuard.server";export async function action({ request }: ActionFunctionArgs) {- const { client, companyGroupId, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {update: "purchasing"});@@ -57,17 +57,16 @@ export async function action({ request }: ActionFunctionArgs) {if (supplier.data?.currencyCode) {currencyCode = supplier.data.currencyCode;- const currency = await getCurrencyByCode(- client,- companyGroupId,- currencyCode- );+ const rate = await getExchangeRate(client, companyId, currencyCode);+ if (rate.error) {+ return { error: rate.error, data: null };+ }return await client.from("purchaseOrder").update({supplierId: value ?? undefined,currencyCode: currencyCode ?? undefined,- exchangeRate: currency.data?.exchangeRate ?? 1,+ exchangeRate: rate.data,updatedBy: userId,updatedAt: new Date().toISOString()})@@ -119,22 +118,19 @@ export async function action({ request }: ActionFunctionArgs) {.in("id", ids as string[]);case "currencyCode":if (value) {- const currency = await getCurrencyByCode(- client,- companyGroupId,- value as string- );- if (currency.data) {- return await client- .from("purchaseOrder")- .update({- currencyCode: value as string,- exchangeRate: currency.data.exchangeRate,- updatedBy: userId,- updatedAt: new Date().toISOString()- })- .in("id", ids as string[]);+ const rate = await getExchangeRate(client, companyId, value as string);+ if (rate.error) {+ return { error: rate.error, data: null };}+ return await client+ .from("purchaseOrder")+ .update({+ currencyCode: value as string,+ exchangeRate: rate.data,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ .in("id", ids as string[]);}// don't break -- just let it catch the next casecase "supplierContactId":diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.details.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.details.tsxindex 23de0c49e7..9d99db39f0 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.details.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.details.tsx@@ -61,7 +61,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, companyGroupId, userId } = await requirePermissions(request, {+ const { client, userId } = await requirePermissions(request, {update: "sales"});@@ -86,32 +86,28 @@ export async function action({ request, params }: ActionFunctionArgs) {return validationError(validation.error);}- const result = await updateQuote(- client,- {- id,- status: validation.data.status,- currencyCode: validation.data.currencyCode,- expirationDate: validation.data.expirationDate || null,- customerId: validation.data.customerId,- customerContactId: validation.data.customerContactId || null,- customerLocationId: validation.data.customerLocationId || null,- customerEngineeringContactId:- validation.data.customerEngineeringContactId || null,- customerReference: validation.data.customerReference || null,- salesPersonId: validation.data.salesPersonId || null,- estimatorId: validation.data.estimatorId || null,- locationId: validation.data.locationId,- dueDate: validation.data.dueDate || null,- digitalQuoteAcceptedBy: validation.data.digitalQuoteAcceptedBy || null,- digitalQuoteAcceptedByEmail:- validation.data.digitalQuoteAcceptedByEmail || null,- notes: validation.data.notes,- customFields: setCustomFields(formData),- updatedBy: userId- },- companyGroupId- );+ const result = await updateQuote(client, {+ id,+ status: validation.data.status,+ currencyCode: validation.data.currencyCode,+ expirationDate: validation.data.expirationDate || null,+ customerId: validation.data.customerId,+ customerContactId: validation.data.customerContactId || null,+ customerLocationId: validation.data.customerLocationId || null,+ customerEngineeringContactId:+ validation.data.customerEngineeringContactId || null,+ customerReference: validation.data.customerReference || null,+ salesPersonId: validation.data.salesPersonId || null,+ estimatorId: validation.data.estimatorId || null,+ locationId: validation.data.locationId,+ dueDate: validation.data.dueDate || null,+ digitalQuoteAcceptedBy: validation.data.digitalQuoteAcceptedBy || null,+ digitalQuoteAcceptedByEmail:+ validation.data.digitalQuoteAcceptedByEmail || null,+ notes: validation.data.notes,+ customFields: setCustomFields(formData),+ updatedBy: userId+ });if (result.error) {throw redirect(path.to.quote(id),diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.exchange-rate.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.exchange-rate.tsxindex 6cc907dbe4..62cdce58cc 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.exchange-rate.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.exchange-rate.tsx@@ -1,9 +1,9 @@-import { assertIsPost, success } from "@carbon/auth";+import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";-import { getCurrencyByCode } from "~/modules/accounting";+import { getExchangeRate } from "~/modules/accounting";import {getQuote,isQuoteLocked,@@ -14,7 +14,7 @@ import { path, requestReferrer } from "~/utils/path";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, companyGroupId } = await requirePermissions(request, {+ const { client, companyId } = await requirePermissions(request, {create: "sales"});@@ -32,21 +32,23 @@ export async function action({ request, params }: ActionFunctionArgs) {message: "Cannot modify a locked quote. Reopen it first."});- const formData = await request.formData();- const currencyCode = formData.get("currencyCode") as string;+ const currencyCode = quote.data?.currencyCode;if (!currencyCode) throw new Error("Could not find currencyCode");- const currency = await getCurrencyByCode(- client,- companyGroupId,- currencyCode- );- if (currency.error || !currency.data.exchangeRate)- throw new Error("Could not find currency");+ const exchangeRate = await getExchangeRate(client, companyId, currencyCode);+ if (exchangeRate.error) {+ throw redirect(+ requestReferrer(request) ?? path.to.quoteDetails(quoteId),+ await flash(+ request,+ error(exchangeRate.error, "Failed to get exchange rate")+ )+ );+ }const update = await updateQuoteExchangeRate(client, {id: quoteId,- exchangeRate: currency.data.exchangeRate+ exchangeRate: exchangeRate.data});if (update.error) {diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.tsxindex 3ce0aaeba0..06c1c8d7dd 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.tsx@@ -16,7 +16,7 @@ import {useSubmit} from "react-router";import { PanelProvider, ResizablePanels } from "~/components/Layout/Panels";-import { getCurrencyByCode } from "~/modules/accounting";+import { getExchangeRate } from "~/modules/accounting";import { getSupplierPriceBreaksForItems } from "~/modules/items";import type { SalesOrderLine } from "~/modules/sales";import {@@ -50,13 +50,10 @@ export const handle: Handle = {};export async function loader({ request, params }: LoaderFunctionArgs) {- const { client, companyId, companyGroupId } = await requirePermissions(- request,- {- view: "sales",- bypassRls: true- }- );+ const { client, companyId } = await requirePermissions(request, {+ view: "sales",+ bypassRls: true+ });const { quoteId } = params;if (!quoteId) throw new Error("Could not find quoteId");@@ -121,14 +118,18 @@ export async function loader({ request, params }: LoaderFunctionArgs) {let exchangeRate = 1;if (quote.data?.currencyCode) {- const presentationCurrency = await getCurrencyByCode(+ const presentationExchangeRate = await getExchangeRate(client,- companyGroupId,+ companyId,quote.data.currencyCode);- if (presentationCurrency.data?.exchangeRate) {- exchangeRate = presentationCurrency.data.exchangeRate;- }+ // A missing LIVE rate must not make the quote unopenable — this page hosts+ // the refresh button that fixes it. Fall back to the document's own stamped+ // snapshot (the PDF routes' policy); writes still refuse.+ exchangeRate =+ presentationExchangeRate.error || presentationExchangeRate.data === null+ ? (quote.data.exchangeRate ?? 1)+ : presentationExchangeRate.data;}let salesOrderLines: PostgrestResponse<SalesOrderLine> | null = null;diff --git a/apps/erp/app/routes/x+/quote+/update.tsx b/apps/erp/app/routes/x+/quote+/update.tsxindex 198ef4eb42..78816098f8 100644--- a/apps/erp/app/routes/x+/quote+/update.tsx+++ b/apps/erp/app/routes/x+/quote+/update.tsx@@ -1,11 +1,11 @@import { requirePermissions } from "@carbon/auth/auth.server";import type { ActionFunctionArgs } from "react-router";-import { getCurrencyByCode } from "~/modules/accounting";+import { getExchangeRate } from "~/modules/accounting";import { isQuoteLocked } from "~/modules/sales";import { requireUnlockedBulk } from "~/utils/lockedGuard.server";export async function action({ request }: ActionFunctionArgs) {- const { client, companyGroupId, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {update: "sales"});@@ -67,17 +67,16 @@ export async function action({ request }: ActionFunctionArgs) {}).in("id", ids as string[]);case "currencyCode":- const currency = await getCurrencyByCode(- client,- companyGroupId,- value as string- );- if (currency.data) {+ if (value) {+ const exchangeRate = await getExchangeRate(client, companyId, value);+ if (exchangeRate.error) {+ return { error: exchangeRate.error, data: null };+ }return await client.from("quote").update({currencyCode: value,- exchangeRate: currency.data.exchangeRate,+ exchangeRate: exchangeRate.data,updatedBy: userId,updatedAt: new Date().toISOString()})diff --git a/apps/erp/app/routes/x+/reports+/balance-sheet.tsx b/apps/erp/app/routes/x+/reports+/balance-sheet.tsxindex 9a3195659f..fbbe101f1b 100644--- a/apps/erp/app/routes/x+/reports+/balance-sheet.tsx+++ b/apps/erp/app/routes/x+/reports+/balance-sheet.tsx@@ -128,6 +128,19 @@ export async function loader({ request }: LoaderFunctionArgs) {{ buckets, includeCurrentYearEarnings: true });+ if (consolidated.error || !consolidated.data) {+ throw redirect(+ path.to.accounting,+ await flash(+ request,+ error(+ consolidated.error,+ "Failed to translate a subsidiary's balances"+ )+ )+ );+ }+const balanceSheetAccounts = consolidated.data.filter((a) => a.incomeBalance === "Balance Sheet");diff --git a/apps/erp/app/routes/x+/reports+/executive-pnl.tsx b/apps/erp/app/routes/x+/reports+/executive-pnl.tsxindex 1432e686e2..65a7014d74 100644--- a/apps/erp/app/routes/x+/reports+/executive-pnl.tsx+++ b/apps/erp/app/routes/x+/reports+/executive-pnl.tsx@@ -108,6 +108,19 @@ export async function loader({ request }: LoaderFunctionArgs) {{ buckets });+ if (consolidated.error || !consolidated.data) {+ throw redirect(+ path.to.accounting,+ await flash(+ request,+ error(+ consolidated.error,+ "Failed to translate a subsidiary's balances"+ )+ )+ );+ }+return {incomeStatement: consolidated.data.filter((a) => a.incomeBalance === "Income Statement"diff --git a/apps/erp/app/routes/x+/reports+/income-statement.tsx b/apps/erp/app/routes/x+/reports+/income-statement.tsxindex 5e7dbf637c..691904303d 100644--- a/apps/erp/app/routes/x+/reports+/income-statement.tsx+++ b/apps/erp/app/routes/x+/reports+/income-statement.tsx@@ -107,6 +107,19 @@ export async function loader({ request }: LoaderFunctionArgs) {{ buckets });+ if (consolidated.error || !consolidated.data) {+ throw redirect(+ path.to.accounting,+ await flash(+ request,+ error(+ consolidated.error,+ "Failed to translate a subsidiary's balances"+ )+ )+ );+ }+return {incomeStatement: consolidated.data.filter((a) => a.incomeBalance === "Income Statement"diff --git a/apps/erp/app/routes/x+/reports+/trial-balance.tsx b/apps/erp/app/routes/x+/reports+/trial-balance.tsxindex 4b6364dace..44171ebc11 100644--- a/apps/erp/app/routes/x+/reports+/trial-balance.tsx+++ b/apps/erp/app/routes/x+/reports+/trial-balance.tsx@@ -96,6 +96,19 @@ export async function loader({ request }: LoaderFunctionArgs) {startDate);+ if (consolidated.error || !consolidated.data) {+ throw redirect(+ path.to.accounting,+ await flash(+ request,+ error(+ consolidated.error,+ "Failed to translate a subsidiary's balances"+ )+ )+ );+ }+return {trialBalance: consolidated.data as (Chart & {translatedBalance?: number;@@ -152,6 +165,18 @@ export async function loader({ request }: LoaderFunctionArgs) {balances.data ?? []);+ // Rendering untranslated numbers under a translated header with no signal+ // is worse than refusing — surface the failure.+ if (translation.error) {+ throw redirect(+ path.to.accounting,+ await flash(+ request,+ error(translation.error, "Failed to translate balances")+ )+ );+ }+if (translation.data) {const translationMap = new Map(translation.data.map((t) => [t.accountId, t])diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.exchange-rate.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.exchange-rate.tsxindex f4cee372d9..05042fada9 100644--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.exchange-rate.tsx+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.exchange-rate.tsx@@ -3,7 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";-import { getCurrencyByCode } from "~/modules/accounting";+import { getExchangeRate } from "~/modules/accounting";import {getSalesInvoice,isSalesInvoiceLocked,@@ -14,7 +14,7 @@ import { path, requestReferrer } from "~/utils/path";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, companyGroupId, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {update: "invoicing"});@@ -41,21 +41,23 @@ export async function action({ request, params }: ActionFunctionArgs) {message: "Cannot modify a locked sales invoice. Reopen it first."});- const formData = await request.formData();- const currencyCode = formData.get("currencyCode") as string;+ const currencyCode = invoice.data?.currencyCode;if (!currencyCode) throw new Error("Could not find currencyCode");- const currency = await getCurrencyByCode(- client,- companyGroupId,- currencyCode- );- if (currency.error || !currency.data.exchangeRate)- throw new Error("Could not find currency");+ const exchangeRate = await getExchangeRate(client, companyId, currencyCode);+ if (exchangeRate.error) {+ throw redirect(+ requestReferrer(request) ?? path.to.salesInvoiceDetails(invoiceId),+ await flash(+ request,+ error(exchangeRate.error, "Failed to get exchange rate")+ )+ );+ }const update = await updateSalesInvoiceExchangeRate(client, {id: invoiceId,- exchangeRate: currency.data.exchangeRate,+ exchangeRate: exchangeRate.data,updatedBy: userId});diff --git a/apps/erp/app/routes/x+/sales-invoice+/update.tsx b/apps/erp/app/routes/x+/sales-invoice+/update.tsxindex 5c01b5a983..062a1027b9 100644--- a/apps/erp/app/routes/x+/sales-invoice+/update.tsx+++ b/apps/erp/app/routes/x+/sales-invoice+/update.tsx@@ -1,6 +1,6 @@import { requirePermissions } from "@carbon/auth/auth.server";import type { ActionFunctionArgs } from "react-router";-import { getCurrencyByCode } from "~/modules/accounting";+import { getExchangeRate } from "~/modules/accounting";import {computeInvoiceDateDue,isSalesInvoiceLocked@@ -8,10 +8,9 @@ import {import { requireUnlockedBulk } from "~/utils/lockedGuard.server";export async function action({ request }: ActionFunctionArgs) {- const { client, companyGroupId, companyId, userId } =- await requirePermissions(request, {- update: "sales"- });+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "sales"+ });const formData = await request.formData();const ids = formData.getAll("ids");@@ -52,11 +51,8 @@ export async function action({ request }: ActionFunctionArgs) {if (customer.data?.currencyCode) {currencyCode = customer.data.currencyCode;- const currency = await getCurrencyByCode(- client,- companyGroupId,- currencyCode- );+ const rate = await getExchangeRate(client, companyId, currencyCode);+ if (rate.error) return rate;return await client.from("salesInvoice").update({@@ -64,7 +60,7 @@ export async function action({ request }: ActionFunctionArgs) {invoiceCustomerContactId: null,invoiceCustomerLocationId: null,currencyCode: currencyCode ?? undefined,- exchangeRate: currency.data?.exchangeRate ?? 1,+ exchangeRate: rate.data,updatedBy: userId,updatedAt: new Date().toISOString()})@@ -133,22 +129,17 @@ export async function action({ request }: ActionFunctionArgs) {// don't break -- just let it catch the next casecase "currencyCode":if (value) {- const currency = await getCurrencyByCode(- client,- companyGroupId,- value as string- );- if (currency.data) {- return await client- .from("salesInvoice")- .update({- currencyCode: value as string,- exchangeRate: currency.data.exchangeRate ?? 1,- updatedBy: userId,- updatedAt: new Date().toISOString()- })- .in("id", ids as string[]);- }+ const rate = await getExchangeRate(client, companyId, value as string);+ if (rate.error) return rate;+ return await client+ .from("salesInvoice")+ .update({+ currencyCode: value as string,+ exchangeRate: rate.data,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ .in("id", ids as string[]);}// don't break -- just let it catch the next casecase "customerId":diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.details.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.details.tsxindex 57c4a78138..46bcbd3186 100644--- a/apps/erp/app/routes/x+/sales-order+/$orderId.details.tsx+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.details.tsx@@ -107,7 +107,7 @@ export async function action({ request, params }: ActionFunctionArgs) {message: "Cannot modify a locked sales order. Reopen it first."});- const { client, companyGroupId, userId } = await requirePermissions(request, {+ const { client, userId } = await requirePermissions(request, {update: "sales"});@@ -118,22 +118,18 @@ export async function action({ request, params }: ActionFunctionArgs) {return validationError(validation.error);}- const result = await updateSalesOrder(- client,- {- id,- status: validation.data.status,- currencyCode: validation.data.currencyCode,- orderDate: validation.data.orderDate,- customerId: validation.data.customerId,- customerContactId: validation.data.customerContactId || null,- customerLocationId: validation.data.customerLocationId || null,- notes: validation.data.notes,- customFields: setCustomFields(formData),- updatedBy: userId- },- companyGroupId- );+ const result = await updateSalesOrder(client, {+ id,+ status: validation.data.status,+ currencyCode: validation.data.currencyCode,+ orderDate: validation.data.orderDate,+ customerId: validation.data.customerId,+ customerContactId: validation.data.customerContactId || null,+ customerLocationId: validation.data.customerLocationId || null,+ notes: validation.data.notes,+ customFields: setCustomFields(formData),+ updatedBy: userId+ });if (result.error) {throw redirect(path.to.salesOrder(id),diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.exchange-rate.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.exchange-rate.tsxindex 149cf041d1..d544ea9e77 100644--- a/apps/erp/app/routes/x+/sales-order+/$orderId.exchange-rate.tsx+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.exchange-rate.tsx@@ -1,9 +1,9 @@-import { assertIsPost, success } from "@carbon/auth";+import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";-import { getCurrencyByCode } from "~/modules/accounting";+import { getExchangeRate } from "~/modules/accounting";import {getSalesOrder,isSalesOrderLocked,@@ -14,7 +14,7 @@ import { path } from "~/utils/path";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, companyGroupId } = await requirePermissions(request, {+ const { client, companyId } = await requirePermissions(request, {view: "sales"});const { orderId } = params;@@ -28,21 +28,23 @@ export async function action({ request, params }: ActionFunctionArgs) {message: "Cannot modify a locked sales order. Reopen it first."});- const formData = await request.formData();- const currencyCode = formData.get("currencyCode") as string;+ const currencyCode = salesOrder.data?.currencyCode;if (!currencyCode) throw new Error("Could not find currencyCode");- const currency = await getCurrencyByCode(- client,- companyGroupId,- currencyCode- );- if (currency.error || !currency.data.exchangeRate)- throw new Error("Could not find currency");+ const exchangeRate = await getExchangeRate(client, companyId, currencyCode);+ if (exchangeRate.error) {+ throw redirect(+ path.to.salesOrderDetails(orderId),+ await flash(+ request,+ error(exchangeRate.error, "Failed to get exchange rate")+ )+ );+ }const update = await updateSalesOrderExchangeRate(client, {id: orderId,- exchangeRate: currency.data.exchangeRate+ exchangeRate: exchangeRate.data});if (update.error) {diff --git a/apps/erp/app/routes/x+/sales-order+/update.tsx b/apps/erp/app/routes/x+/sales-order+/update.tsxindex 2b8e955014..176b442fd8 100644--- a/apps/erp/app/routes/x+/sales-order+/update.tsx+++ b/apps/erp/app/routes/x+/sales-order+/update.tsx@@ -1,11 +1,11 @@import { requirePermissions } from "@carbon/auth/auth.server";import type { ActionFunctionArgs } from "react-router";-import { getCurrencyByCode } from "~/modules/accounting";+import { getExchangeRate } from "~/modules/accounting";import { isSalesOrderLocked } from "~/modules/sales";import { requireUnlockedBulk } from "~/utils/lockedGuard.server";export async function action({ request }: ActionFunctionArgs) {- const { client, companyGroupId, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {update: "sales"});@@ -46,17 +46,20 @@ export async function action({ request }: ActionFunctionArgs) {if (customer.data?.currencyCode) {currencyCode = customer.data.currencyCode;- const currency = await getCurrencyByCode(+ const exchangeRate = await getExchangeRate(client,- companyGroupId,+ companyId,currencyCode);+ if (exchangeRate.error) {+ return { error: exchangeRate.error, data: null };+ }return await client.from("salesOrder").update({customerId: value ?? undefined,currencyCode: currencyCode ?? undefined,- exchangeRate: currency.data?.exchangeRate ?? 1,+ exchangeRate: exchangeRate.data,updatedBy: userId,updatedAt: new Date().toISOString()})@@ -74,22 +77,19 @@ export async function action({ request }: ActionFunctionArgs) {.in("id", ids as string[]);case "currencyCode":if (value) {- const currency = await getCurrencyByCode(- client,- companyGroupId,- value as string- );- if (currency.data) {- return await client- .from("salesOrder")- .update({- currencyCode: value as string,- exchangeRate: currency.data.exchangeRate,- updatedBy: userId,- updatedAt: new Date().toISOString()- })- .in("id", ids as string[]);+ const exchangeRate = await getExchangeRate(client, companyId, value);+ if (exchangeRate.error) {+ return { error: exchangeRate.error, data: null };}+ return await client+ .from("salesOrder")+ .update({+ currencyCode: value as string,+ exchangeRate: exchangeRate.data,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ .in("id", ids as string[]);}// don't break -- just let it catch the next casecase "customerContactId":diff --git a/apps/erp/app/routes/x+/settings+/company.tsx b/apps/erp/app/routes/x+/settings+/company.tsxindex 0f4a47c5ca..365be701cf 100644--- a/apps/erp/app/routes/x+/settings+/company.tsx+++ b/apps/erp/app/routes/x+/settings+/company.tsx@@ -28,9 +28,11 @@ import type { Company as CompanyType } from "~/modules/settings";import {CompanyForm,companyValidator,- updateCompany+ updateCompany,+ updateCompanyWithBaseCurrencyChange} from "~/modules/settings";import { invalidateCompanyTimeZone } from "~/modules/shared/timezone.server";+import { getDatabaseClient } from "~/services/database.server";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";import { copyToClipboard } from "~/utils/string";@@ -53,15 +55,47 @@ export async function action({ request }: ActionFunctionArgs) {return validationError(validation.error);}- const update = await updateCompany(client, companyId, {- ...validation.data,- updatedBy: userId- });- if (update.error)- return data(- {},- await flash(request, error(update.error, "Failed to update company"))- );+ const existing = await client+ .from("company")+ .select("baseCurrencyCode")+ .eq("id", companyId)+ .single();++ const baseCurrencyChanged =+ !!existing.data?.baseCurrencyCode &&+ existing.data.baseCurrencyCode !== validation.data.baseCurrencyCode;++ if (baseCurrencyChanged) {+ // Overrides are denominated in the company's base currency — after a base+ // change they'd silently resolve against the wrong anchor. Clear them in+ // the SAME transaction as the base flip; market rates take over until the+ // user re-pins.+ try {+ await updateCompanyWithBaseCurrencyChange(+ getDatabaseClient(),+ companyId,+ {+ ...validation.data,+ updatedBy: userId+ }+ );+ } catch (err) {+ return data(+ {},+ await flash(request, error(err, "Failed to update company"))+ );+ }+ } else {+ const update = await updateCompany(client, companyId, {+ ...validation.data,+ updatedBy: userId+ });+ if (update.error)+ return data(+ {},+ await flash(request, error(update.error, "Failed to update company"))+ );+ }// company.timezone may have changed — drop the cached resolution.await invalidateCompanyTimeZone(companyId);diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.details.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.details.tsxindex 6e97391815..2e40ea4c62 100644--- a/apps/erp/app/routes/x+/supplier-quote+/$id.details.tsx+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.details.tsx@@ -52,7 +52,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, companyGroupId, userId } = await requirePermissions(request, {+ const { client, userId } = await requirePermissions(request, {update: "purchasing"});@@ -77,21 +77,17 @@ export async function action({ request, params }: ActionFunctionArgs) {return validationError(validation.error);}- const result = await updateSupplierQuote(- client,- {- id,- status: validation.data.status,- currencyCode: validation.data.currencyCode,- expirationDate: validation.data.expirationDate || null,- supplierContactId: validation.data.supplierContactId || null,- supplierLocationId: validation.data.supplierLocationId || null,- notes: validation.data.notes,- customFields: setCustomFields(formData),- updatedBy: userId- },- companyGroupId- );+ const result = await updateSupplierQuote(client, {+ id,+ status: validation.data.status,+ currencyCode: validation.data.currencyCode,+ expirationDate: validation.data.expirationDate || null,+ supplierContactId: validation.data.supplierContactId || null,+ supplierLocationId: validation.data.supplierLocationId || null,+ notes: validation.data.notes,+ customFields: setCustomFields(formData),+ updatedBy: userId+ });if (result.error) {throw redirect(path.to.supplierQuote(id),diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.exchange-rate.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.exchange-rate.tsxindex c0042ef523..cd4bb70094 100644--- a/apps/erp/app/routes/x+/supplier-quote+/$id.exchange-rate.tsx+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.exchange-rate.tsx@@ -1,9 +1,9 @@-import { assertIsPost, success } from "@carbon/auth";+import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";-import { getCurrencyByCode } from "~/modules/accounting";+import { getExchangeRate } from "~/modules/accounting";import {getSupplierQuote,isSupplierQuoteLocked,@@ -14,7 +14,7 @@ import { path, requestReferrer } from "~/utils/path";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, companyGroupId } = await requirePermissions(request, {+ const { client, companyId } = await requirePermissions(request, {create: "sales"});@@ -32,21 +32,23 @@ export async function action({ request, params }: ActionFunctionArgs) {message: "Cannot modify a locked supplier quote. Reopen it first."});- const formData = await request.formData();- const currencyCode = formData.get("currencyCode") as string;+ const currencyCode = quote.data?.currencyCode;if (!currencyCode) throw new Error("Could not find currencyCode");- const currency = await getCurrencyByCode(- client,- companyGroupId,- currencyCode- );- if (currency.error || !currency.data.exchangeRate)- throw new Error("Could not find currency");+ const exchangeRate = await getExchangeRate(client, companyId, currencyCode);+ if (exchangeRate.error) {+ throw redirect(+ requestReferrer(request) ?? path.to.supplierQuoteDetails(id),+ await flash(+ request,+ error(exchangeRate.error, "Failed to get exchange rate")+ )+ );+ }const update = await updateSupplierQuoteExchangeRate(client, {id: id,- exchangeRate: currency.data.exchangeRate+ exchangeRate: exchangeRate.data});if (update.error) {diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.tsxindex 09fb8926c2..4fa3f39801 100644--- a/apps/erp/app/routes/x+/supplier-quote+/$id.tsx+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.tsx@@ -7,7 +7,7 @@ import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { Outlet, redirect, useParams } from "react-router";import { PanelProvider, ResizablePanels } from "~/components/Layout/Panels";-import { getCurrencyByCode } from "~/modules/accounting";+import { getCurrencyByCode, getExchangeRate } from "~/modules/accounting";import {getSiblingQuotesForQuote,getSupplier,@@ -57,6 +57,15 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}+ // The reads above run service-role (RLS bypassed) — refuse a cross-company id+ // before resolving anything against it.+ if (quote.data.companyId !== companyId) {+ throw redirect(+ path.to.supplierQuotes,+ await flash(request, error(null, "Failed to load quote"))+ );+ }+const [supplierInteraction, presentationCurrency, supplier, companySettings] =await Promise.all([getSupplierInteraction(serviceRole, quote.data.supplierInteractionId!),@@ -79,8 +88,19 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}let exchangeRate = 1;- if (quote.data?.currencyCode && presentationCurrency.data?.exchangeRate) {- exchangeRate = presentationCurrency.data.exchangeRate;+ if (quote.data?.currencyCode) {+ const rate = await getExchangeRate(+ serviceRole,+ quote.data.companyId,+ quote.data.currencyCode+ );+ // A missing LIVE rate must not make the quote unopenable — this page hosts+ // the refresh button that fixes it. Fall back to the document's own stamped+ // snapshot (the PDF routes' policy); writes still refuse.+ exchangeRate =+ rate.error || rate.data === null+ ? (quote.data.exchangeRate ?? 1)+ : rate.data;}// Extract sibling quotes from the linked datadiff --git a/apps/erp/app/routes/x+/supplier-quote+/update.tsx b/apps/erp/app/routes/x+/supplier-quote+/update.tsxindex aca6c55893..b25afd008f 100644--- a/apps/erp/app/routes/x+/supplier-quote+/update.tsx+++ b/apps/erp/app/routes/x+/supplier-quote+/update.tsx@@ -3,14 +3,15 @@ import { datetime } from "@carbon/utils";import type { CalendarDate } from "@internationalized/date";import { parseDate } from "@internationalized/date";import type { ActionFunctionArgs } from "react-router";-import { getCurrencyByCode } from "~/modules/accounting";+import { getExchangeRate } from "~/modules/accounting";import { isSupplierQuoteLocked } from "~/modules/purchasing";import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import { requireUnlockedBulk } from "~/utils/lockedGuard.server";export async function action({ request }: ActionFunctionArgs) {- const { client, companyGroupId, companyId, userId } =- await requirePermissions(request, { update: "purchasing" });+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "purchasing"+ });const formData = await request.formData();const ids = formData.getAll("ids");@@ -70,17 +71,16 @@ export async function action({ request }: ActionFunctionArgs) {}).in("id", ids as string[]);case "currencyCode":- const currency = await getCurrencyByCode(- client,- companyGroupId,- value as string- );- if (currency.data) {+ if (value) {+ const rate = await getExchangeRate(client, companyId, value as string);+ if (rate.error) {+ return { error: rate.error, data: null };+ }return await client.from("supplierQuote").update({currencyCode: value,- exchangeRate: currency.data.exchangeRate,+ exchangeRate: rate.data,updatedBy: userId,updatedAt: new Date().toISOString()})diff --git a/apps/erp/app/routes/x+/templates+/$type.preview.tsx b/apps/erp/app/routes/x+/templates+/$type.preview.tsxindex 0999d3f767..0c5f8a659a 100644--- a/apps/erp/app/routes/x+/templates+/$type.preview.tsx+++ b/apps/erp/app/routes/x+/templates+/$type.preview.tsx@@ -23,12 +23,9 @@ import { buildPreviewProps } from "~/modules/settings/documentPreview.server";* Buffer/streams) and guarantees the preview matches the real PDF route.*/export async function action({ request, params }: ActionFunctionArgs) {- const { client, companyId, companyGroupId } = await requirePermissions(- request,- {- view: "settings"- }- );+ const { client, companyId } = await requirePermissions(request, {+ view: "settings"+ });const documentType = documentTemplateTypeSchema.parse(params.type);@@ -87,7 +84,6 @@ export async function action({ request, params }: ActionFunctionArgs) {? await buildPreviewProps(client,companyId,- companyGroupId,documentType,previewId,localediff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex a9c6e114d2..9fd5e30f6a 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -2258,12 +2258,28 @@ export const getStoragePath = (bucket: string, path: string) => {return `${SUPABASE_URL}/storage/v1/object/public/${bucket}/${path}`;};+/**+ * The Referer header, reduced to a SAME-ORIGIN relative path (or null). Many+ * actions redirect back here — returning the raw header would let a crafted+ * request bounce the user to an attacker origin (CWE-601 open redirect), so a+ * cross-origin or unparsable referer yields null and callers fall back to+ * their fixed route.+ */export const requestReferrer = (request: Request, withParams = true) => {- return request.headers.get("referer");+ const referer = request.headers.get("referer");+ if (!referer) return null;+ try {+ const requestUrl = new URL(request.url);+ const url = new URL(referer, requestUrl.origin);+ if (url.origin !== requestUrl.origin) return null;+ return url.pathname + url.search + url.hash;+ } catch {+ return null;+ }};export const getParams = (request: Request) => {- const url = new URL(requestReferrer(request) ?? "");+ const url = new URL(requestReferrer(request) ?? "/", "http://relative.local");const searchParams = new URLSearchParams(url.search);return searchParams.toString();};diff --git a/packages/database/src/datasets/bootstrap.ts b/packages/database/src/datasets/bootstrap.tsindex 1d7b503660..902e31343a 100644--- a/packages/database/src/datasets/bootstrap.ts+++ b/packages/database/src/datasets/bootstrap.ts@@ -299,9 +299,9 @@ export async function seedCompanyReferenceData(for (const c of currencies) {await client.query(- `INSERT INTO currency (code, "exchangeRate", "decimalPlaces", "companyGroupId", "createdBy")- VALUES ($1, $2, $3, $4, 'system')`,- [c.code, c.exchangeRate, c.decimalPlaces, companyGroupId]+ `INSERT INTO currency (code, "decimalPlaces", "companyGroupId", "createdBy")+ VALUES ($1, $2, $3, 'system')`,+ [c.code, c.decimalPlaces, companyGroupId]);}diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 257a5984e3..6647a3befe 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -12942,6 +12942,150 @@ export default {tags: ["receiptLines"]}},+ "/exchangeRate": {+ get: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.exchangeRate.id"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRate.currencyCode"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRate.effectiveDate"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRate.rate"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRate.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRate.updatedAt"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/order"+ },+ {+ $ref: "#/parameters/range"+ },+ {+ $ref: "#/parameters/rangeUnit"+ },+ {+ $ref: "#/parameters/offset"+ },+ {+ $ref: "#/parameters/limit"+ },+ {+ $ref: "#/parameters/preferCount"+ }+ ],+ responses: {+ "200": {+ description: "OK",+ schema: {+ items: {+ $ref: "#/definitions/exchangeRate"+ },+ type: "array"+ }+ },+ "206": {+ description: "Partial Content"+ }+ },+ tags: ["exchangeRate"]+ },+ post: {+ parameters: [+ {+ $ref: "#/parameters/body.exchangeRate"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/preferPost"+ }+ ],+ responses: {+ "201": {+ description: "Created"+ }+ },+ tags: ["exchangeRate"]+ },+ delete: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.exchangeRate.id"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRate.currencyCode"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRate.effectiveDate"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRate.rate"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRate.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRate.updatedAt"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["exchangeRate"]+ },+ patch: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.exchangeRate.id"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRate.currencyCode"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRate.effectiveDate"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRate.rate"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRate.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRate.updatedAt"+ },+ {+ $ref: "#/parameters/body.exchangeRate"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["exchangeRate"]+ }+ },"/nonConformanceRequiredAction": {get: {parameters: [@@ -36291,177 +36435,6 @@ export default {tags: ["salesOrderFavorite"]}},- "/exchangeRateHistory": {- get: {- parameters: [- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.id"- },- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.currencyCode"- },- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.rate"- },- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.effectiveDate"- },- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.companyGroupId"- },- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.createdBy"- },- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.createdAt"- },- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.updatedBy"- },- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.updatedAt"- },- {- $ref: "#/parameters/select"- },- {- $ref: "#/parameters/order"- },- {- $ref: "#/parameters/range"- },- {- $ref: "#/parameters/rangeUnit"- },- {- $ref: "#/parameters/offset"- },- {- $ref: "#/parameters/limit"- },- {- $ref: "#/parameters/preferCount"- }- ],- responses: {- "200": {- description: "OK",- schema: {- items: {- $ref: "#/definitions/exchangeRateHistory"- },- type: "array"- }- },- "206": {- description: "Partial Content"- }- },- tags: ["exchangeRateHistory"]- },- post: {- parameters: [- {- $ref: "#/parameters/body.exchangeRateHistory"- },- {- $ref: "#/parameters/select"- },- {- $ref: "#/parameters/preferPost"- }- ],- responses: {- "201": {- description: "Created"- }- },- tags: ["exchangeRateHistory"]- },- delete: {- parameters: [- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.id"- },- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.currencyCode"- },- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.rate"- },- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.effectiveDate"- },- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.companyGroupId"- },- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.createdBy"- },- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.createdAt"- },- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.updatedBy"- },- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.updatedAt"- },- {- $ref: "#/parameters/preferReturn"- }- ],- responses: {- "204": {- description: "No Content"- }- },- tags: ["exchangeRateHistory"]- },- patch: {- parameters: [- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.id"- },- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.currencyCode"- },- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.rate"- },- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.effectiveDate"- },- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.companyGroupId"- },- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.createdBy"- },- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.createdAt"- },- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.updatedBy"- },- {- $ref: "#/parameters/rowFilter.exchangeRateHistory.updatedAt"- },- {- $ref: "#/parameters/body.exchangeRateHistory"- },- {- $ref: "#/parameters/preferReturn"- }- ],- responses: {- "204": {- description: "No Content"- }- },- tags: ["exchangeRateHistory"]- }- },"/materialFinishes": {get: {parameters: [@@ -39330,9 +39303,6 @@ export default {{$ref: "#/parameters/rowFilter.currencies.code"},- {- $ref: "#/parameters/rowFilter.currencies.exchangeRate"- },{$ref: "#/parameters/rowFilter.currencies.decimalPlaces"},@@ -39360,6 +39330,9 @@ export default {{$ref: "#/parameters/rowFilter.currencies.companyGroupId"},+ {+ $ref: "#/parameters/rowFilter.currencies.historicalExchangeRate"+ },{$ref: "#/parameters/rowFilter.currencies.name"},@@ -58587,9 +58560,6 @@ export default {{$ref: "#/parameters/rowFilter.currency.code"},- {- $ref: "#/parameters/rowFilter.currency.exchangeRate"- },{$ref: "#/parameters/rowFilter.currency.decimalPlaces"},@@ -58685,9 +58655,6 @@ export default {{$ref: "#/parameters/rowFilter.currency.code"},- {- $ref: "#/parameters/rowFilter.currency.exchangeRate"- },{$ref: "#/parameters/rowFilter.currency.decimalPlaces"},@@ -58737,9 +58704,6 @@ export default {{$ref: "#/parameters/rowFilter.currency.code"},- {- $ref: "#/parameters/rowFilter.currency.exchangeRate"- },{$ref: "#/parameters/rowFilter.currency.decimalPlaces"},@@ -79209,6 +79173,168 @@ export default {tags: ["stockTransfer"]}},+ "/exchangeRateOverride": {+ get: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.exchangeRateOverride.id"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRateOverride.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRateOverride.currencyCode"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRateOverride.rate"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRateOverride.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRateOverride.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRateOverride.updatedBy"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRateOverride.updatedAt"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/order"+ },+ {+ $ref: "#/parameters/range"+ },+ {+ $ref: "#/parameters/rangeUnit"+ },+ {+ $ref: "#/parameters/offset"+ },+ {+ $ref: "#/parameters/limit"+ },+ {+ $ref: "#/parameters/preferCount"+ }+ ],+ responses: {+ "200": {+ description: "OK",+ schema: {+ items: {+ $ref: "#/definitions/exchangeRateOverride"+ },+ type: "array"+ }+ },+ "206": {+ description: "Partial Content"+ }+ },+ tags: ["exchangeRateOverride"]+ },+ post: {+ parameters: [+ {+ $ref: "#/parameters/body.exchangeRateOverride"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/preferPost"+ }+ ],+ responses: {+ "201": {+ description: "Created"+ }+ },+ tags: ["exchangeRateOverride"]+ },+ delete: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.exchangeRateOverride.id"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRateOverride.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRateOverride.currencyCode"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRateOverride.rate"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRateOverride.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRateOverride.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRateOverride.updatedBy"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRateOverride.updatedAt"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["exchangeRateOverride"]+ },+ patch: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.exchangeRateOverride.id"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRateOverride.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRateOverride.currencyCode"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRateOverride.rate"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRateOverride.createdBy"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRateOverride.createdAt"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRateOverride.updatedBy"+ },+ {+ $ref: "#/parameters/rowFilter.exchangeRateOverride.updatedAt"+ },+ {+ $ref: "#/parameters/body.exchangeRateOverride"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["exchangeRateOverride"]+ }+ },"/jobOperationsWithMakeMethods": {get: {parameters: [@@ -92731,6 +92857,85 @@ export default {tags: ["(rpc) get_primary_key_columns"]}},+ "/rpc/get_exchange_rate": {+ get: {+ parameters: [+ {+ format: "text",+ in: "query",+ name: "p_company_id",+ required: true,+ type: "string"+ },+ {+ format: "text",+ in: "query",+ name: "p_currency_code",+ required: true,+ type: "string"+ },+ {+ format: "date",+ in: "query",+ name: "p_as_of",+ required: false,+ type: "string"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) get_exchange_rate"]+ },+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_as_of: {+ format: "date",+ type: "string"+ },+ p_company_id: {+ format: "text",+ type: "string"+ },+ p_currency_code: {+ format: "text",+ type: "string"+ }+ },+ required: ["p_company_id", "p_currency_code"],+ type: "object"+ }+ },+ {+ $ref: "#/parameters/preferParams"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) get_exchange_rate"]+ }+ },"/rpc/check_api_key_rate_limit": {post: {parameters: [@@ -99702,6 +99907,63 @@ export default {tags: ["(rpc) get_job_operation_step_records"]}},+ "/rpc/get_exchange_rates": {+ get: {+ parameters: [+ {+ format: "text",+ in: "query",+ name: "p_company_id",+ required: true,+ type: "string"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) get_exchange_rates"]+ },+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ p_company_id: {+ format: "text",+ type: "string"+ }+ },+ required: ["p_company_id"],+ type: "object"+ }+ },+ {+ $ref: "#/parameters/preferParams"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) get_exchange_rates"]+ }+ },"/rpc/get_custom_field_unique_values": {post: {parameters: [@@ -100023,9 +100285,18 @@ export default {p_period_start: {format: "date",type: "string"+ },+ p_target_currency: {+ format: "text",+ type: "string"}},- required: ["p_company_group_id", "p_company_id", "p_period_end"],+ required: [+ "p_company_group_id",+ "p_company_id",+ "p_target_currency",+ "p_period_end"+ ],type: "object"}},@@ -106145,6 +106416,41 @@ export default {},type: "object"},+ exchangeRate: {+ required: ["id", "currencyCode", "effectiveDate", "rate", "createdAt"],+ properties: {+ id: {+ default: "public.id('xrate'::text)",+ description: "Note:\nThis is a Primary Key.<pk/>",+ format: "text",+ type: "string"+ },+ currencyCode: {+ description:+ "Note:\nThis is a Foreign Key to `currencyCode.code`.<fk table='currencyCode' column='code'/>",+ format: "text",+ type: "string"+ },+ effectiveDate: {+ format: "date",+ type: "string"+ },+ rate: {+ format: "numeric",+ type: "number"+ },+ createdAt: {+ default: "now()",+ format: "timestamp with time zone",+ type: "string"+ },+ updatedAt: {+ format: "timestamp with time zone",+ type: "string"+ }+ },+ type: "object"+ },nonConformanceRequiredAction: {required: ["id", "companyId", "name", "active", "createdAt", "createdBy"],properties: {@@ -117320,63 +117626,6 @@ export default {},type: "object"},- exchangeRateHistory: {- required: [- "id",- "currencyCode",- "rate",- "effectiveDate",- "companyGroupId",- "createdBy",- "createdAt"- ],- properties: {- id: {- default: "public.id('exr'::text)",- description: "Note:\nThis is a Primary Key.<pk/>",- format: "text",- type: "string"- },- currencyCode: {- description:- "Note:\nThis is a Foreign Key to `currencyCode.code`.<fk table='currencyCode' column='code'/>",- format: "text",- type: "string"- },- rate: {- format: "numeric",- type: "number"- },- effectiveDate: {- format: "date",- type: "string"- },- companyGroupId: {- description:- "Note:\nThis is a Foreign Key to `companyGroup.id`.<fk table='companyGroup' column='id'/>",- format: "text",- type: "string"- },- createdBy: {- format: "text",- type: "string"- },- createdAt: {- default: "now()",- format: "timestamp with time zone",- type: "string"- },- updatedBy: {- format: "text",- type: "string"- },- updatedAt: {- format: "timestamp with time zone",- type: "string"- }- },- type: "object"- },materialFinishes: {properties: {id: {@@ -118862,10 +119111,6 @@ export default {format: "text",type: "string"},- exchangeRate: {- format: "numeric",- type: "number"- },decimalPlaces: {format: "integer",type: "integer"@@ -118908,6 +119153,10 @@ export default {format: "text",type: "string"},+ historicalExchangeRate: {+ format: "numeric",+ type: "number"+ },name: {format: "text",type: "string"@@ -127657,7 +127906,6 @@ export default {required: ["id","code",- "exchangeRate","decimalPlaces","active","createdBy",@@ -127677,11 +127925,6 @@ export default {format: "text",type: "string"},- exchangeRate: {- default: 1,- format: "numeric",- type: "number"- },decimalPlaces: {default: 2,format: "integer",@@ -137707,6 +137950,62 @@ export default {},type: "object"},+ exchangeRateOverride: {+ required: [+ "id",+ "companyId",+ "currencyCode",+ "rate",+ "createdBy",+ "createdAt"+ ],+ properties: {+ id: {+ default: "public.id('xrovr'::text)",+ description: "Note:\nThis is a Primary Key.<pk/>",+ format: "text",+ type: "string"+ },+ companyId: {+ description:+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",+ format: "text",+ type: "string"+ },+ currencyCode: {+ description:+ "Note:\nThis is a Foreign Key to `currencyCode.code`.<fk table='currencyCode' column='code'/>",+ format: "text",+ type: "string"+ },+ rate: {+ format: "numeric",+ type: "number"+ },+ createdBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"+ },+ createdAt: {+ default: "now()",+ format: "timestamp with time zone",+ type: "string"+ },+ updatedBy: {+ description:+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",+ format: "text",+ type: "string"+ },+ updatedAt: {+ format: "timestamp with time zone",+ type: "string"+ }+ },+ type: "object"+ },jobOperationsWithMakeMethods: {properties: {makeMethodId: {@@ -148971,6 +149270,51 @@ export default {in: "query",type: "string"},+ "body.exchangeRate": {+ name: "exchangeRate",+ description: "exchangeRate",+ required: false,+ in: "body",+ schema: {+ $ref: "#/definitions/exchangeRate"+ }+ },+ "rowFilter.exchangeRate.id": {+ name: "id",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.exchangeRate.currencyCode": {+ name: "currencyCode",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.exchangeRate.effectiveDate": {+ name: "effectiveDate",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.exchangeRate.rate": {+ name: "rate",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.exchangeRate.createdAt": {+ name: "createdAt",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.exchangeRate.updatedAt": {+ name: "updatedAt",+ required: false,+ in: "query",+ type: "string"+ },"body.nonConformanceRequiredAction": {name: "nonConformanceRequiredAction",description: "nonConformanceRequiredAction",@@ -161595,69 +161939,6 @@ export default {in: "query",type: "string"},- "body.exchangeRateHistory": {- name: "exchangeRateHistory",- description: "exchangeRateHistory",- required: false,- in: "body",- schema: {- $ref: "#/definitions/exchangeRateHistory"- }- },- "rowFilter.exchangeRateHistory.id": {- name: "id",- required: false,- in: "query",- type: "string"- },- "rowFilter.exchangeRateHistory.currencyCode": {- name: "currencyCode",- required: false,- in: "query",- type: "string"- },- "rowFilter.exchangeRateHistory.rate": {- name: "rate",- required: false,- in: "query",- type: "string"- },- "rowFilter.exchangeRateHistory.effectiveDate": {- name: "effectiveDate",- required: false,- in: "query",- type: "string"- },- "rowFilter.exchangeRateHistory.companyGroupId": {- name: "companyGroupId",- required: false,- in: "query",- type: "string"- },- "rowFilter.exchangeRateHistory.createdBy": {- name: "createdBy",- required: false,- in: "query",- type: "string"- },- "rowFilter.exchangeRateHistory.createdAt": {- name: "createdAt",- required: false,- in: "query",- type: "string"- },- "rowFilter.exchangeRateHistory.updatedBy": {- name: "updatedBy",- required: false,- in: "query",- type: "string"- },- "rowFilter.exchangeRateHistory.updatedAt": {- name: "updatedAt",- required: false,- in: "query",- type: "string"- },"body.materialFinishes": {name: "materialFinishes",description: "materialFinishes",@@ -163265,12 +163546,6 @@ export default {in: "query",type: "string"},- "rowFilter.currencies.exchangeRate": {- name: "exchangeRate",- required: false,- in: "query",- type: "string"- },"rowFilter.currencies.decimalPlaces": {name: "decimalPlaces",required: false,@@ -163325,6 +163600,12 @@ export default {in: "query",type: "string"},+ "rowFilter.currencies.historicalExchangeRate": {+ name: "historicalExchangeRate",+ required: false,+ in: "query",+ type: "string"+ },"rowFilter.currencies.name": {name: "name",required: false,@@ -173073,12 +173354,6 @@ export default {in: "query",type: "string"},- "rowFilter.currency.exchangeRate": {- name: "exchangeRate",- required: false,- in: "query",- type: "string"- },"rowFilter.currency.decimalPlaces": {name: "decimalPlaces",required: false,@@ -184263,6 +184538,63 @@ export default {in: "query",type: "string"},+ "body.exchangeRateOverride": {+ name: "exchangeRateOverride",+ description: "exchangeRateOverride",+ required: false,+ in: "body",+ schema: {+ $ref: "#/definitions/exchangeRateOverride"+ }+ },+ "rowFilter.exchangeRateOverride.id": {+ name: "id",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.exchangeRateOverride.companyId": {+ name: "companyId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.exchangeRateOverride.currencyCode": {+ name: "currencyCode",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.exchangeRateOverride.rate": {+ name: "rate",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.exchangeRateOverride.createdBy": {+ name: "createdBy",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.exchangeRateOverride.createdAt": {+ name: "createdAt",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.exchangeRateOverride.updatedBy": {+ name: "updatedBy",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.exchangeRateOverride.updatedAt": {+ name: "updatedAt",+ required: false,+ in: "query",+ type: "string"+ },"body.jobOperationsWithMakeMethods": {name: "jobOperationsWithMakeMethods",description: "jobOperationsWithMakeMethods",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 74e28b91b0..903be69fdc 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -8905,7 +8905,6 @@ export type Database = {createdBy: stringcustomFields: Json | nulldecimalPlaces: number- exchangeRate: numberhistoricalExchangeRate: number | nullid: stringtags: string[] | null@@ -8920,7 +8919,6 @@ export type Database = {createdBy: stringcustomFields?: Json | nulldecimalPlaces?: number- exchangeRate?: numberhistoricalExchangeRate?: number | nullid?: stringtags?: string[] | null@@ -8935,7 +8933,6 @@ export type Database = {createdBy?: stringcustomFields?: Json | nulldecimalPlaces?: number- exchangeRate?: numberhistoricalExchangeRate?: number | nullid?: stringtags?: string[] | null@@ -13837,35 +13834,67 @@ export type Database = {},]}- exchangeRateHistory: {+ exchangeRate: {Row: {- companyGroupId: stringcreatedAt: string- createdBy: stringcurrencyCode: stringeffectiveDate: stringid: stringrate: numberupdatedAt: string | null+ }+ Insert: {+ createdAt?: string+ currencyCode: string+ effectiveDate: string+ id?: string+ rate: number+ updatedAt?: string | null+ }+ Update: {+ createdAt?: string+ currencyCode?: string+ effectiveDate?: string+ id?: string+ rate?: number+ updatedAt?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "exchangeRate_currencyCode_fkey"+ columns: ["currencyCode"]+ isOneToOne: false+ referencedRelation: "currencyCode"+ referencedColumns: ["code"]+ },+ ]+ }+ exchangeRateOverride: {+ Row: {+ companyId: string+ createdAt: string+ createdBy: string+ currencyCode: string+ id: string+ rate: number+ updatedAt: string | nullupdatedBy: string | null}Insert: {- companyGroupId: string+ companyId: stringcreatedAt?: stringcreatedBy: stringcurrencyCode: string- effectiveDate: stringid?: stringrate: numberupdatedAt?: string | nullupdatedBy?: string | null}Update: {- companyGroupId?: string+ companyId?: stringcreatedAt?: stringcreatedBy?: stringcurrencyCode?: string- effectiveDate?: stringid?: stringrate?: numberupdatedAt?: string | null@@ -13873,19 +13902,110 @@ export type Database = {}Relationships: [{- foreignKeyName: "exchangeRateHistory_companyGroupId_fkey"- columns: ["companyGroupId"]+ foreignKeyName: "exchangeRateOverride_companyId_fkey"+ columns: ["companyId"]isOneToOne: false- referencedRelation: "companyGroup"+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "exchangeRateOverride_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "exchangeRateOverride_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "exchangeRateOverride_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "exchangeRateOverride_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "exchangeRateOverride_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"referencedColumns: ["id"]},{- foreignKeyName: "exchangeRateHistory_currencyCode_fkey"+ foreignKeyName: "exchangeRateOverride_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "exchangeRateOverride_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "exchangeRateOverride_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "exchangeRateOverride_currencyCode_fkey"columns: ["currencyCode"]isOneToOne: falsereferencedRelation: "currencyCode"referencedColumns: ["code"]},+ {+ foreignKeyName: "exchangeRateOverride_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "exchangeRateOverride_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "exchangeRateOverride_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "exchangeRateOverride_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "exchangeRateOverride_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },]}externalIntegrationMapping: {@@ -62698,7 +62818,7 @@ export type Database = {createdBy: string | nullcustomFields: Json | nulldecimalPlaces: number | null- exchangeRate: number | null+ historicalExchangeRate: number | nullid: string | nullname: string | nulltags: string[] | null@@ -68308,14 +68428,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey"- columns: ["id"]+ columns: ["supplierLocationId"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]},{foreignKeyName: "partner_id_fkey"- columns: ["supplierLocationId"]+ columns: ["id"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]@@ -69970,14 +70090,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -73404,14 +73524,14 @@ export type Database = {},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -73958,14 +74078,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -78012,6 +78132,25 @@ export type Database = {tableName: string}[]}+ get_exchange_rate: {+ Args: {+ p_as_of?: string+ p_company_id: string+ p_currency_code: string+ }+ Returns: number+ }+ get_exchange_rates: {+ Args: { p_company_id: string }+ Returns: {+ active: boolean+ currencyCode: string+ decimalPlaces: number+ rate: number+ rateUpdatedAt: string+ source: string+ }[]+ }get_foreign_key_map: {Args: { p_table_names: string[] }Returns: {@@ -79300,6 +79439,7 @@ export type Database = {p_company_id: stringp_period_end: stringp_period_start?: string+ p_target_currency: string}Returns: {averageRate: numberdiff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.tsindex aa6571abb5..ea8d6da953 100644--- a/packages/database/supabase/functions/convert/index.ts+++ b/packages/database/supabase/functions/convert/index.ts@@ -1080,19 +1080,17 @@ serve(async (req: Request) => {customer.data?.currencyCode ??company.data?.baseCurrencyCode ??"USD";- const currency = await client- .from("currency")- .select("*")- .eq("code", currencyCode)- .eq("companyGroupId", company.data.companyGroupId)- .single();- // A missing rate must not fall through to 1 -- that quotes a- // foreign-currency customer at par. The base currency is the only- // case where 1 is correct by definition.- if (currency.error && currencyCode !== company.data.baseCurrencyCode) {- throw currency.error;+ // get_exchange_rate returns 1 for the base currency, prefers a+ // company override, falls back to the global store, and raises on a+ // missing rate -- a foreign-currency customer is never quoted at par.+ const exchangeRateResult = await client.rpc("get_exchange_rate", {+ p_company_id: companyId,+ p_currency_code: currencyCode,+ });+ if (exchangeRateResult.error) {+ throw new Error(exchangeRateResult.error.message);}- const exchangeRate = currency.data?.exchangeRate ?? 1;+ const exchangeRate = Number(exchangeRateResult.data);const {paymentTermId,diff --git a/packages/database/supabase/functions/create/index.ts b/packages/database/supabase/functions/create/index.tsindex fbc66ef866..1ca03a1e5a 100644--- a/packages/database/supabase/functions/create/index.ts+++ b/packages/database/supabase/functions/create/index.ts@@ -522,30 +522,37 @@ serve(async (req: Request) => {if (supplierShipping.error)throw new Error(supplierShipping.error.message);- const currencyCodes = new Set(- suppliers.data- ?.map((d) => d.currencyCode)- .filter(Boolean) as string[]- );-+ // A supplier with no configured currency means "the company's own+ // base currency" (rate 1 by definition) -- never a hardcoded USD,+ // which is only correct for USD-base companies.const companyRecord = await client.from("company")- .select("companyGroupId")+ .select("baseCurrencyCode").eq("id", companyId).single();- if (companyRecord.error) throw new Error(companyRecord.error.message);+ if (companyRecord.error) {+ throw new Error(companyRecord.error.message);+ }+ const baseCurrencyCode = companyRecord.data.baseCurrencyCode;++ const currencyCodes = new Set(+ suppliers.data?.map((d) => d.currencyCode ?? baseCurrencyCode)+ );+ // get_exchange_rate raises on a missing rate -- a resolver error+ // must fail the operation rather than default the rate.const exchangeRates = await Promise.all(Array.from(currencyCodes).map(async (currencyCode) => {- const exchangeRate = await client- .from("currency")- .select("*")- .eq("code", currencyCode)- .eq("companyGroupId", companyRecord.data.companyGroupId)- .single();+ const exchangeRate = await client.rpc("get_exchange_rate", {+ p_company_id: companyId,+ p_currency_code: currencyCode,+ });+ if (exchangeRate.error) {+ throw new Error(exchangeRate.error.message);+ }return {currencyCode,- exchangeRate: exchangeRate.data?.exchangeRate ?? 1,+ exchangeRate: Number(exchangeRate.data),};}));@@ -563,6 +570,18 @@ serve(async (req: Request) => {(d) => d.supplierId === supplier);+ const supplierCurrencyCode =+ suppliers.data?.find((d) => d.id === supplier)?.currencyCode ??+ baseCurrencyCode;+ const exchangeRate = exchangeRates.find(+ (d) => d.currencyCode === supplierCurrencyCode+ )?.exchangeRate;+ if (exchangeRate === undefined) {+ throw new Error(+ `No exchange rate resolved for currency ${supplierCurrencyCode}`+ );+ }+let purchaseOrderId =purchaseOrdersBySupplierId[supplier] === "new"? undefined@@ -602,16 +621,8 @@ serve(async (req: Request) => {createdBy: userId,purchaseOrderType: "Outside Processing",supplierInteractionId: supplierInteractionId,- currencyCode:- suppliers.data?.find((d) => d.id === supplier)- ?.currencyCode ?? "USD",- exchangeRate:- exchangeRates.find(- (d) =>- d.currencyCode ===- suppliers.data?.find((d) => d.id === supplier)- ?.currencyCode- )?.exchangeRate ?? 1,+ currencyCode: supplierCurrencyCode,+ exchangeRate,exchangeRateUpdatedAt: new Date().toISOString(),}).returning(["id"])@@ -702,13 +713,7 @@ serve(async (req: Request) => {jobOperationId: operation.id,companyId,createdBy: userId,- exchangeRate:- exchangeRates.find(- (d) =>- d.currencyCode ===- suppliers.data?.find((d) => d.id === supplier)- ?.currencyCode- )?.exchangeRate ?? 1,+ exchangeRate,});}}diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.tsindex 8ceb8ed58c..cc0ace157f 100644--- a/packages/database/supabase/functions/get-method/index.ts+++ b/packages/database/supabase/functions/get-method/index.ts@@ -6959,7 +6959,14 @@ serve(async (req: Request) => {quantity: l.quantity ?? 0,unitPrice: l.unitPrice ?? 0,shippingCost: l.shippingCost ?? 0,- exchangeRate: l.exchangeRate ?? 0,+ // Never 0: a zero rate is not a valid snapshot (DB CHECK+ // "exchangeRate" > 0) and zeroes every converted* generated+ // column. A legacy null line rate falls back to the SOURCE+ // QUOTE's own stamped header rate; 1 only when the source+ // header predates stamping too (base-consistent with its+ // line snapshots' old default).+ exchangeRate:+ l.exchangeRate ?? sourceQuote.data?.exchangeRate ?? 1,categoryMarkups: JSON.stringify(l.categoryMarkups ?? {}),// Copied prices keep their provenance so a manual price// stays protected on the new quote/revision.diff --git a/packages/database/supabase/functions/lib/seed.data.ts b/packages/database/supabase/functions/lib/seed.data.tsindex aae9aad1aa..0c656d63f7 100644--- a/packages/database/supabase/functions/lib/seed.data.ts+++ b/packages/database/supabase/functions/lib/seed.data.ts@@ -482,124 +482,124 @@ export const sequences = [// All 118 currencies from the original seedexport const currencies = [- { code: "USD", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "CAD", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "EUR", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "AED", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "AFN", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "ALL", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "AMD", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "ARS", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "AUD", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "AZN", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "BAM", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "BDT", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "BGN", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "BHD", exchangeRate: 1, decimalPlaces: 3, createdBy: "system" },- { code: "BIF", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "BND", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "BOB", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "BRL", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "BWP", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "BYN", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "BZD", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "CDF", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "CHF", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "CLP", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "CNY", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "COP", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "CRC", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "CVE", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "CZK", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "DJF", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "DKK", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "DOP", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "DZD", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "EGP", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "ERN", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "ETB", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "GBP", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "GEL", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "GHS", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "GNF", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "GTQ", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "HKD", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "HNL", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "HRK", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "HUF", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "IDR", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "ILS", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "INR", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "IQD", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "IRR", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "ISK", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "JMD", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "JOD", exchangeRate: 1, decimalPlaces: 3, createdBy: "system" },- { code: "JPY", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "KES", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "KHR", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "KMF", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "KRW", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "KWD", exchangeRate: 1, decimalPlaces: 3, createdBy: "system" },- { code: "KZT", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "LBP", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "LKR", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "LTL", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "LVL", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "LYD", exchangeRate: 1, decimalPlaces: 3, createdBy: "system" },- { code: "MAD", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "MDL", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "MGA", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "MKD", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "MMK", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "MOP", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "MUR", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "MXN", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "MYR", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "MZN", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "NAD", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "NGN", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "NIO", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "NOK", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "NPR", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "NZD", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "OMR", exchangeRate: 1, decimalPlaces: 3, createdBy: "system" },- { code: "PAB", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "PEN", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "PHP", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "PKR", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "PLN", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "PYG", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "QAR", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "RON", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "RSD", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "RUB", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "RWF", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "SAR", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "SDG", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "SEK", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "SGD", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "SOS", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "SYP", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "THB", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "TND", exchangeRate: 1, decimalPlaces: 3, createdBy: "system" },- { code: "TOP", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "TRY", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "TTD", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "TWD", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "TZS", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "UAH", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "UGX", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "UYU", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "UZS", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "VEF", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "VND", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "XAF", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "XOF", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "YER", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "ZAR", exchangeRate: 1, decimalPlaces: 2, createdBy: "system" },- { code: "ZMK", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" },- { code: "ZWL", exchangeRate: 1, decimalPlaces: 0, createdBy: "system" }+ { code: "USD", decimalPlaces: 2, createdBy: "system" },+ { code: "CAD", decimalPlaces: 2, createdBy: "system" },+ { code: "EUR", decimalPlaces: 2, createdBy: "system" },+ { code: "AED", decimalPlaces: 2, createdBy: "system" },+ { code: "AFN", decimalPlaces: 0, createdBy: "system" },+ { code: "ALL", decimalPlaces: 0, createdBy: "system" },+ { code: "AMD", decimalPlaces: 0, createdBy: "system" },+ { code: "ARS", decimalPlaces: 2, createdBy: "system" },+ { code: "AUD", decimalPlaces: 2, createdBy: "system" },+ { code: "AZN", decimalPlaces: 2, createdBy: "system" },+ { code: "BAM", decimalPlaces: 2, createdBy: "system" },+ { code: "BDT", decimalPlaces: 2, createdBy: "system" },+ { code: "BGN", decimalPlaces: 2, createdBy: "system" },+ { code: "BHD", decimalPlaces: 3, createdBy: "system" },+ { code: "BIF", decimalPlaces: 0, createdBy: "system" },+ { code: "BND", decimalPlaces: 2, createdBy: "system" },+ { code: "BOB", decimalPlaces: 2, createdBy: "system" },+ { code: "BRL", decimalPlaces: 2, createdBy: "system" },+ { code: "BWP", decimalPlaces: 2, createdBy: "system" },+ { code: "BYN", decimalPlaces: 2, createdBy: "system" },+ { code: "BZD", decimalPlaces: 2, createdBy: "system" },+ { code: "CDF", decimalPlaces: 2, createdBy: "system" },+ { code: "CHF", decimalPlaces: 2, createdBy: "system" },+ { code: "CLP", decimalPlaces: 0, createdBy: "system" },+ { code: "CNY", decimalPlaces: 2, createdBy: "system" },+ { code: "COP", decimalPlaces: 0, createdBy: "system" },+ { code: "CRC", decimalPlaces: 0, createdBy: "system" },+ { code: "CVE", decimalPlaces: 2, createdBy: "system" },+ { code: "CZK", decimalPlaces: 2, createdBy: "system" },+ { code: "DJF", decimalPlaces: 0, createdBy: "system" },+ { code: "DKK", decimalPlaces: 2, createdBy: "system" },+ { code: "DOP", decimalPlaces: 2, createdBy: "system" },+ { code: "DZD", decimalPlaces: 2, createdBy: "system" },+ { code: "EGP", decimalPlaces: 2, createdBy: "system" },+ { code: "ERN", decimalPlaces: 2, createdBy: "system" },+ { code: "ETB", decimalPlaces: 2, createdBy: "system" },+ { code: "GBP", decimalPlaces: 2, createdBy: "system" },+ { code: "GEL", decimalPlaces: 2, createdBy: "system" },+ { code: "GHS", decimalPlaces: 2, createdBy: "system" },+ { code: "GNF", decimalPlaces: 0, createdBy: "system" },+ { code: "GTQ", decimalPlaces: 2, createdBy: "system" },+ { code: "HKD", decimalPlaces: 2, createdBy: "system" },+ { code: "HNL", decimalPlaces: 2, createdBy: "system" },+ { code: "HRK", decimalPlaces: 2, createdBy: "system" },+ { code: "HUF", decimalPlaces: 0, createdBy: "system" },+ { code: "IDR", decimalPlaces: 0, createdBy: "system" },+ { code: "ILS", decimalPlaces: 2, createdBy: "system" },+ { code: "INR", decimalPlaces: 2, createdBy: "system" },+ { code: "IQD", decimalPlaces: 0, createdBy: "system" },+ { code: "IRR", decimalPlaces: 0, createdBy: "system" },+ { code: "ISK", decimalPlaces: 0, createdBy: "system" },+ { code: "JMD", decimalPlaces: 2, createdBy: "system" },+ { code: "JOD", decimalPlaces: 3, createdBy: "system" },+ { code: "JPY", decimalPlaces: 0, createdBy: "system" },+ { code: "KES", decimalPlaces: 2, createdBy: "system" },+ { code: "KHR", decimalPlaces: 2, createdBy: "system" },+ { code: "KMF", decimalPlaces: 0, createdBy: "system" },+ { code: "KRW", decimalPlaces: 0, createdBy: "system" },+ { code: "KWD", decimalPlaces: 3, createdBy: "system" },+ { code: "KZT", decimalPlaces: 2, createdBy: "system" },+ { code: "LBP", decimalPlaces: 0, createdBy: "system" },+ { code: "LKR", decimalPlaces: 2, createdBy: "system" },+ { code: "LTL", decimalPlaces: 2, createdBy: "system" },+ { code: "LVL", decimalPlaces: 2, createdBy: "system" },+ { code: "LYD", decimalPlaces: 3, createdBy: "system" },+ { code: "MAD", decimalPlaces: 2, createdBy: "system" },+ { code: "MDL", decimalPlaces: 2, createdBy: "system" },+ { code: "MGA", decimalPlaces: 0, createdBy: "system" },+ { code: "MKD", decimalPlaces: 2, createdBy: "system" },+ { code: "MMK", decimalPlaces: 0, createdBy: "system" },+ { code: "MOP", decimalPlaces: 2, createdBy: "system" },+ { code: "MUR", decimalPlaces: 0, createdBy: "system" },+ { code: "MXN", decimalPlaces: 2, createdBy: "system" },+ { code: "MYR", decimalPlaces: 2, createdBy: "system" },+ { code: "MZN", decimalPlaces: 2, createdBy: "system" },+ { code: "NAD", decimalPlaces: 2, createdBy: "system" },+ { code: "NGN", decimalPlaces: 2, createdBy: "system" },+ { code: "NIO", decimalPlaces: 2, createdBy: "system" },+ { code: "NOK", decimalPlaces: 2, createdBy: "system" },+ { code: "NPR", decimalPlaces: 2, createdBy: "system" },+ { code: "NZD", decimalPlaces: 2, createdBy: "system" },+ { code: "OMR", decimalPlaces: 3, createdBy: "system" },+ { code: "PAB", decimalPlaces: 2, createdBy: "system" },+ { code: "PEN", decimalPlaces: 2, createdBy: "system" },+ { code: "PHP", decimalPlaces: 2, createdBy: "system" },+ { code: "PKR", decimalPlaces: 0, createdBy: "system" },+ { code: "PLN", decimalPlaces: 2, createdBy: "system" },+ { code: "PYG", decimalPlaces: 0, createdBy: "system" },+ { code: "QAR", decimalPlaces: 2, createdBy: "system" },+ { code: "RON", decimalPlaces: 2, createdBy: "system" },+ { code: "RSD", decimalPlaces: 0, createdBy: "system" },+ { code: "RUB", decimalPlaces: 2, createdBy: "system" },+ { code: "RWF", decimalPlaces: 0, createdBy: "system" },+ { code: "SAR", decimalPlaces: 2, createdBy: "system" },+ { code: "SDG", decimalPlaces: 2, createdBy: "system" },+ { code: "SEK", decimalPlaces: 2, createdBy: "system" },+ { code: "SGD", decimalPlaces: 2, createdBy: "system" },+ { code: "SOS", decimalPlaces: 0, createdBy: "system" },+ { code: "SYP", decimalPlaces: 0, createdBy: "system" },+ { code: "THB", decimalPlaces: 2, createdBy: "system" },+ { code: "TND", decimalPlaces: 3, createdBy: "system" },+ { code: "TOP", decimalPlaces: 2, createdBy: "system" },+ { code: "TRY", decimalPlaces: 2, createdBy: "system" },+ { code: "TTD", decimalPlaces: 2, createdBy: "system" },+ { code: "TWD", decimalPlaces: 2, createdBy: "system" },+ { code: "TZS", decimalPlaces: 0, createdBy: "system" },+ { code: "UAH", decimalPlaces: 2, createdBy: "system" },+ { code: "UGX", decimalPlaces: 0, createdBy: "system" },+ { code: "UYU", decimalPlaces: 2, createdBy: "system" },+ { code: "UZS", decimalPlaces: 0, createdBy: "system" },+ { code: "VEF", decimalPlaces: 2, createdBy: "system" },+ { code: "VND", decimalPlaces: 0, createdBy: "system" },+ { code: "XAF", decimalPlaces: 0, createdBy: "system" },+ { code: "XOF", decimalPlaces: 0, createdBy: "system" },+ { code: "YER", decimalPlaces: 0, createdBy: "system" },+ { code: "ZAR", decimalPlaces: 2, createdBy: "system" },+ { code: "ZMK", decimalPlaces: 0, createdBy: "system" },+ { code: "ZWL", decimalPlaces: 0, createdBy: "system" }] as const;diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 74e28b91b0..903be69fdc 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -8905,7 +8905,6 @@ export type Database = {createdBy: stringcustomFields: Json | nulldecimalPlaces: number- exchangeRate: numberhistoricalExchangeRate: number | nullid: stringtags: string[] | null@@ -8920,7 +8919,6 @@ export type Database = {createdBy: stringcustomFields?: Json | nulldecimalPlaces?: number- exchangeRate?: numberhistoricalExchangeRate?: number | nullid?: stringtags?: string[] | null@@ -8935,7 +8933,6 @@ export type Database = {createdBy?: stringcustomFields?: Json | nulldecimalPlaces?: number- exchangeRate?: numberhistoricalExchangeRate?: number | nullid?: stringtags?: string[] | null@@ -13837,35 +13834,67 @@ export type Database = {},]}- exchangeRateHistory: {+ exchangeRate: {Row: {- companyGroupId: stringcreatedAt: string- createdBy: stringcurrencyCode: stringeffectiveDate: stringid: stringrate: numberupdatedAt: string | null+ }+ Insert: {+ createdAt?: string+ currencyCode: string+ effectiveDate: string+ id?: string+ rate: number+ updatedAt?: string | null+ }+ Update: {+ createdAt?: string+ currencyCode?: string+ effectiveDate?: string+ id?: string+ rate?: number+ updatedAt?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "exchangeRate_currencyCode_fkey"+ columns: ["currencyCode"]+ isOneToOne: false+ referencedRelation: "currencyCode"+ referencedColumns: ["code"]+ },+ ]+ }+ exchangeRateOverride: {+ Row: {+ companyId: string+ createdAt: string+ createdBy: string+ currencyCode: string+ id: string+ rate: number+ updatedAt: string | nullupdatedBy: string | null}Insert: {- companyGroupId: string+ companyId: stringcreatedAt?: stringcreatedBy: stringcurrencyCode: string- effectiveDate: stringid?: stringrate: numberupdatedAt?: string | nullupdatedBy?: string | null}Update: {- companyGroupId?: string+ companyId?: stringcreatedAt?: stringcreatedBy?: stringcurrencyCode?: string- effectiveDate?: stringid?: stringrate?: numberupdatedAt?: string | null@@ -13873,19 +13902,110 @@ export type Database = {}Relationships: [{- foreignKeyName: "exchangeRateHistory_companyGroupId_fkey"- columns: ["companyGroupId"]+ foreignKeyName: "exchangeRateOverride_companyId_fkey"+ columns: ["companyId"]isOneToOne: false- referencedRelation: "companyGroup"+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "exchangeRateOverride_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "exchangeRateOverride_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "exchangeRateOverride_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "exchangeRateOverride_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "exchangeRateOverride_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"referencedColumns: ["id"]},{- foreignKeyName: "exchangeRateHistory_currencyCode_fkey"+ foreignKeyName: "exchangeRateOverride_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "exchangeRateOverride_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "exchangeRateOverride_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "exchangeRateOverride_currencyCode_fkey"columns: ["currencyCode"]isOneToOne: falsereferencedRelation: "currencyCode"referencedColumns: ["code"]},+ {+ foreignKeyName: "exchangeRateOverride_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "exchangeRateOverride_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "exchangeRateOverride_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "exchangeRateOverride_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "exchangeRateOverride_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },]}externalIntegrationMapping: {@@ -62698,7 +62818,7 @@ export type Database = {createdBy: string | nullcustomFields: Json | nulldecimalPlaces: number | null- exchangeRate: number | null+ historicalExchangeRate: number | nullid: string | nullname: string | nulltags: string[] | null@@ -68308,14 +68428,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey"- columns: ["id"]+ columns: ["supplierLocationId"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]},{foreignKeyName: "partner_id_fkey"- columns: ["supplierLocationId"]+ columns: ["id"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]@@ -69970,14 +70090,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -73404,14 +73524,14 @@ export type Database = {},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -73958,14 +74078,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -78012,6 +78132,25 @@ export type Database = {tableName: string}[]}+ get_exchange_rate: {+ Args: {+ p_as_of?: string+ p_company_id: string+ p_currency_code: string+ }+ Returns: number+ }+ get_exchange_rates: {+ Args: { p_company_id: string }+ Returns: {+ active: boolean+ currencyCode: string+ decimalPlaces: number+ rate: number+ rateUpdatedAt: string+ source: string+ }[]+ }get_foreign_key_map: {Args: { p_table_names: string[] }Returns: {@@ -79300,6 +79439,7 @@ export type Database = {p_company_id: stringp_period_end: stringp_period_start?: string+ p_target_currency: string}Returns: {averageRate: numberdiff --git a/packages/database/supabase/migrations/20260903015941_exchange-rate-global-store.sql b/packages/database/supabase/migrations/20260903015941_exchange-rate-global-store.sqlnew file mode 100644index 0000000000..b0207ca19b--- /dev/null+++ b/packages/database/supabase/migrations/20260903015941_exchange-rate-global-store.sql@@ -0,0 +1,326 @@+-- Currency & exchange rate refactor, part 1 of 3: the global market-rate store,+-- per-company overrides, and the resolver functions.+-- Spec: .ai/specs/2026-09-02-currency-exchange-rate-refactor.md++-- Global market-rate store. Deliberately NOT tenant-scoped: market data, same class+-- as "currencyCode". rate = units of "currencyCode" per 1 USD.+CREATE TABLE IF NOT EXISTS "exchangeRate" (+ "id" TEXT NOT NULL DEFAULT id('xrate'),+ "currencyCode" TEXT NOT NULL REFERENCES "currencyCode"("code") ON DELETE CASCADE ON UPDATE CASCADE,+ "effectiveDate" DATE NOT NULL,+ -- 'NaN'::numeric > 0 is TRUE in Postgres, so the positivity check alone+ -- would admit NaN written through PostgREST; NaN = NaN is also TRUE here,+ -- which is what makes the inequality reliable.+ "rate" NUMERIC NOT NULL CHECK ("rate" > 0 AND "rate" <> 'NaN'::numeric),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ CONSTRAINT "exchangeRate_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "exchangeRate_code_date_key" UNIQUE ("currencyCode", "effectiveDate")+);++CREATE INDEX IF NOT EXISTS "exchangeRate_code_date_idx" ON "exchangeRate" ("currencyCode", "effectiveDate" DESC);++ALTER TABLE "exchangeRate" ENABLE ROW LEVEL SECURITY;++DROP POLICY IF EXISTS "SELECT" ON "public"."exchangeRate";+CREATE POLICY "SELECT" ON "public"."exchangeRate"+FOR SELECT TO authenticated USING (true);+-- writes: service role only (no INSERT/UPDATE/DELETE policies)++-- Per-company user overrides. rate = units of "currencyCode" per 1 unit of the+-- company's OWN base currency. Standing pin: always beats the market rate;+-- deleting the row restores the market rate.+CREATE TABLE IF NOT EXISTS "exchangeRateOverride" (+ "id" TEXT NOT NULL DEFAULT id('xrovr'),+ "companyId" TEXT NOT NULL,+ "currencyCode" TEXT NOT NULL REFERENCES "currencyCode"("code") ON DELETE CASCADE ON UPDATE CASCADE,+ "rate" NUMERIC NOT NULL CHECK ("rate" > 0 AND "rate" <> 'NaN'::numeric),+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT REFERENCES "user"("id"),+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ CONSTRAINT "exchangeRateOverride_pkey" PRIMARY KEY ("id", "companyId"),+ CONSTRAINT "exchangeRateOverride_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "exchangeRateOverride_company_code_key" UNIQUE ("companyId", "currencyCode")+);++CREATE INDEX IF NOT EXISTS "exchangeRateOverride_companyId_idx" ON "exchangeRateOverride" ("companyId");+CREATE INDEX IF NOT EXISTS "exchangeRateOverride_currencyCode_idx" ON "exchangeRateOverride" ("currencyCode");+CREATE INDEX IF NOT EXISTS "exchangeRateOverride_createdBy_idx" ON "exchangeRateOverride" ("createdBy");+CREATE INDEX IF NOT EXISTS "exchangeRateOverride_updatedBy_idx" ON "exchangeRateOverride" ("updatedBy");++ALTER TABLE "exchangeRateOverride" ENABLE ROW LEVEL SECURITY;++DROP POLICY IF EXISTS "SELECT" ON "public"."exchangeRateOverride";+CREATE POLICY "SELECT" ON "public"."exchangeRateOverride"+FOR SELECT USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])+);++DROP POLICY IF EXISTS "INSERT" ON "public"."exchangeRateOverride";+CREATE POLICY "INSERT" ON "public"."exchangeRateOverride"+FOR INSERT WITH CHECK (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_update'))::text[])+);++DROP POLICY IF EXISTS "UPDATE" ON "public"."exchangeRateOverride";+CREATE POLICY "UPDATE" ON "public"."exchangeRateOverride"+FOR UPDATE USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_update'))::text[])+);++DROP POLICY IF EXISTS "DELETE" ON "public"."exchangeRateOverride";+CREATE POLICY "DELETE" ON "public"."exchangeRateOverride"+FOR DELETE USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('accounting_update'))::text[])+);++-- Bootstrap snapshot (approximate, 2026-09). Superseded by the daily feed job.+-- Rates are units of currency per 1 USD. Obsolete codes (VEF, ZMK) carry their+-- successor's rate times the redenomination factor.+INSERT INTO "exchangeRate" ("currencyCode", "effectiveDate", "rate")+VALUES+ ('USD', '2026-09-01', 1),+ ('EUR', '2026-09-01', 0.92),+ ('GBP', '2026-09-01', 0.79),+ ('JPY', '2026-09-01', 155),+ ('CHF', '2026-09-01', 0.88),+ ('CAD', '2026-09-01', 1.36),+ ('AUD', '2026-09-01', 1.52),+ ('NZD', '2026-09-01', 1.64),+ ('CNY', '2026-09-01', 7.2),+ ('HKD', '2026-09-01', 7.8),+ ('TWD', '2026-09-01', 32),+ ('KRW', '2026-09-01', 1350),+ ('SGD', '2026-09-01', 1.34),+ ('INR', '2026-09-01', 84),+ ('IDR', '2026-09-01', 15800),+ ('MYR', '2026-09-01', 4.6),+ ('PHP', '2026-09-01', 57),+ ('THB', '2026-09-01', 35),+ ('VND', '2026-09-01', 25000),+ ('BRL', '2026-09-01', 5.5),+ ('MXN', '2026-09-01', 18.5),+ ('ARS', '2026-09-01', 1000),+ ('CLP', '2026-09-01', 950),+ ('COP', '2026-09-01', 4100),+ ('PEN', '2026-09-01', 3.8),+ ('UYU', '2026-09-01', 40),+ ('BOB', '2026-09-01', 6.9),+ ('PYG', '2026-09-01', 7500),+ ('VEF', '2026-09-01', 4000000),+ ('ZAR', '2026-09-01', 18),+ ('EGP', '2026-09-01', 48),+ ('NGN', '2026-09-01', 1550),+ ('KES', '2026-09-01', 130),+ ('GHS', '2026-09-01', 15),+ ('MAD', '2026-09-01', 10),+ ('TND', '2026-09-01', 3.1),+ ('DZD', '2026-09-01', 135),+ ('LYD', '2026-09-01', 4.9),+ ('ETB', '2026-09-01', 120),+ ('TZS', '2026-09-01', 2600),+ ('UGX', '2026-09-01', 3700),+ ('XOF', '2026-09-01', 600),+ ('XAF', '2026-09-01', 600),+ ('MUR', '2026-09-01', 46),+ ('BWP', '2026-09-01', 13.5),+ ('ZMK', '2026-09-01', 26000),+ ('MZN', '2026-09-01', 64),+ ('SEK', '2026-09-01', 10.5),+ ('NOK', '2026-09-01', 10.7),+ ('DKK', '2026-09-01', 6.9),+ ('ISK', '2026-09-01', 138),+ ('PLN', '2026-09-01', 4.0),+ ('CZK', '2026-09-01', 23),+ ('HUF', '2026-09-01', 360),+ ('RON', '2026-09-01', 4.6),+ ('BGN', '2026-09-01', 1.8),+ ('RSD', '2026-09-01', 108),+ ('ALL', '2026-09-01', 93),+ ('MKD', '2026-09-01', 57),+ ('BAM', '2026-09-01', 1.8),+ ('MDL', '2026-09-01', 18),+ ('UAH', '2026-09-01', 41),+ ('BYN', '2026-09-01', 3.3),+ ('RUB', '2026-09-01', 95),+ ('TRY', '2026-09-01', 34),+ ('GEL', '2026-09-01', 2.7),+ ('AMD', '2026-09-01', 390),+ ('AZN', '2026-09-01', 1.7),+ ('KZT', '2026-09-01', 480),+ ('UZS', '2026-09-01', 12700),+ ('AED', '2026-09-01', 3.67),+ ('SAR', '2026-09-01', 3.75),+ ('QAR', '2026-09-01', 3.64),+ ('KWD', '2026-09-01', 0.31),+ ('BHD', '2026-09-01', 0.376),+ ('OMR', '2026-09-01', 0.385),+ ('JOD', '2026-09-01', 0.709),+ ('ILS', '2026-09-01', 3.7),+ ('LBP', '2026-09-01', 89500),+ ('IQD', '2026-09-01', 1310),+ ('IRR', '2026-09-01', 42000),+ ('AFN', '2026-09-01', 70),+ ('PKR', '2026-09-01', 278),+ ('BDT', '2026-09-01', 120),+ ('LKR', '2026-09-01', 300),+ ('NPR', '2026-09-01', 134),+ ('MMK', '2026-09-01', 2100),+ ('KHR', '2026-09-01', 4100),+ ('BND', '2026-09-01', 1.34),+ ('TOP', '2026-09-01', 2.35),+ ('JMD', '2026-09-01', 156),+ ('TTD', '2026-09-01', 6.8),+ ('BZD', '2026-09-01', 2),+ ('DOP', '2026-09-01', 60),+ ('GTQ', '2026-09-01', 7.75),+ ('HNL', '2026-09-01', 24.7),+ ('NIO', '2026-09-01', 36.8),+ ('CRC', '2026-09-01', 520),+ ('PAB', '2026-09-01', 1),+ ('CVE', '2026-09-01', 101),+ ('GNF', '2026-09-01', 8600),+ ('NAD', '2026-09-01', 18),+ ('RWF', '2026-09-01', 1350),+ ('BIF', '2026-09-01', 2900),+ ('DJF', '2026-09-01', 178),+ ('ERN', '2026-09-01', 15),+ ('SOS', '2026-09-01', 570),+ ('SDG', '2026-09-01', 600),+ ('CDF', '2026-09-01', 2800),+ ('KMF', '2026-09-01', 452),+ ('MGA', '2026-09-01', 4500),+ ('YER', '2026-09-01', 250),+ ('SYP', '2026-09-01', 13000),+ ('HRK', '2026-09-01', 6.9),+ ('MOP', '2026-09-01', 8.03),+ ('LTL', '2026-09-01', 3.18),+ ('LVL', '2026-09-01', 0.65),+ ('ZWL', '2026-09-01', 6100)+ON CONFLICT ("currencyCode", "effectiveDate") DO NOTHING;++-- SECURITY INVOKER on purpose: the override read runs under the caller's RLS,+-- so tenant authorization stays with the policies rather than an in-function+-- check a DEFINER would need. Contract: callers are the company's own+-- employees or the service role; a caller who can see the company row but not+-- its overrides (no employee role there) gets the market ratio — sanctioned+-- callers never hit that split, and no cross-tenant data is derivable (a+-- company outside the caller's group resolves to 'Company % not found').+-- Resolver: "units of p_currency_code per 1 unit of THIS company's base currency".+-- base -> 1 by definition; override wins; else the ratio of the two USD-anchored+-- market rates; a missing rate is an ERROR, never 1. Deliberate asymmetry with+-- the consolidation functions: STAMPING a document refuses when no rate exists+-- on/before the date (a wrong snapshot is permanent), while consolidation+-- REPORTING ("getConsolidationRates") falls back to the store's earliest row+-- for periods predating it (a report can be re-run; refusing history helps no one).+CREATE OR REPLACE FUNCTION get_exchange_rate(+ p_company_id TEXT,+ p_currency_code TEXT,+ p_as_of DATE DEFAULT NULL+) RETURNS NUMERIC+LANGUAGE plpgsql STABLE AS $$+DECLARE+ v_base TEXT;+ v_override NUMERIC;+ v_code_rate NUMERIC;+ v_base_rate NUMERIC;+ v_as_of DATE := COALESCE(p_as_of, CURRENT_DATE);+BEGIN+ SELECT "baseCurrencyCode" INTO v_base FROM "company" WHERE "id" = p_company_id;+ IF v_base IS NULL THEN+ RAISE EXCEPTION 'Company % not found', p_company_id;+ END IF;+ IF p_currency_code = v_base THEN+ RETURN 1;+ END IF;++ SELECT "rate" INTO v_override FROM "exchangeRateOverride"+ WHERE "companyId" = p_company_id AND "currencyCode" = p_currency_code;+ IF v_override IS NOT NULL THEN+ RETURN v_override;+ END IF;++ SELECT "rate" INTO v_code_rate FROM "exchangeRate"+ WHERE "currencyCode" = p_currency_code AND "effectiveDate" <= v_as_of+ ORDER BY "effectiveDate" DESC LIMIT 1;+ SELECT "rate" INTO v_base_rate FROM "exchangeRate"+ WHERE "currencyCode" = v_base AND "effectiveDate" <= v_as_of+ ORDER BY "effectiveDate" DESC LIMIT 1;++ IF v_code_rate IS NULL OR v_base_rate IS NULL THEN+ RAISE EXCEPTION 'No exchange rate available for % (base %). Set a rate manually in Accounting -> Exchange Rates.',+ p_currency_code, v_base;+ END IF;++ RETURN v_code_rate / v_base_rate;+END;+$$;++-- List resolver for the admin page: every active currency config row of the+-- company's group, resolved for THIS company, with provenance. Reports a code+-- with no resolution as source 'missing' rather than raising.+CREATE OR REPLACE FUNCTION get_exchange_rates(+ p_company_id TEXT+) RETURNS TABLE (+ "currencyCode" TEXT,+ "decimalPlaces" INTEGER,+ "active" BOOLEAN,+ "rate" NUMERIC,+ "source" TEXT,+ "rateUpdatedAt" TIMESTAMPTZ+)+LANGUAGE plpgsql STABLE AS $$+DECLARE+ v_base TEXT;+ v_group TEXT;+ v_base_rate NUMERIC;+BEGIN+ SELECT c."baseCurrencyCode", c."companyGroupId" INTO v_base, v_group+ FROM "company" c WHERE c."id" = p_company_id;+ IF v_base IS NULL THEN+ RAISE EXCEPTION 'Company % not found', p_company_id;+ END IF;++ SELECT xr."rate" INTO v_base_rate FROM "exchangeRate" xr+ WHERE xr."currencyCode" = v_base AND xr."effectiveDate" <= CURRENT_DATE+ ORDER BY xr."effectiveDate" DESC LIMIT 1;++ RETURN QUERY+ SELECT+ cu."code",+ cu."decimalPlaces",+ cu."active",+ CASE+ WHEN cu."code" = v_base THEN 1::NUMERIC+ WHEN ovr."rate" IS NOT NULL THEN ovr."rate"+ WHEN mkt."rate" IS NOT NULL AND v_base_rate IS NOT NULL THEN mkt."rate" / v_base_rate+ ELSE NULL::NUMERIC+ END AS "rate",+ CASE+ WHEN cu."code" = v_base THEN 'base'+ WHEN ovr."rate" IS NOT NULL THEN 'override'+ WHEN mkt."rate" IS NOT NULL AND v_base_rate IS NOT NULL THEN 'market'+ ELSE 'missing'+ END AS "source",+ CASE+ WHEN cu."code" = v_base THEN NULL::TIMESTAMPTZ+ WHEN ovr."rate" IS NOT NULL THEN COALESCE(ovr."updatedAt", ovr."createdAt")+ ELSE COALESCE(mkt."updatedAt", mkt."createdAt")+ END AS "rateUpdatedAt"+ FROM "currency" cu+ LEFT JOIN "exchangeRateOverride" ovr+ ON ovr."companyId" = p_company_id AND ovr."currencyCode" = cu."code"+ LEFT JOIN LATERAL (+ SELECT xr."rate", xr."createdAt", xr."updatedAt"+ FROM "exchangeRate" xr+ WHERE xr."currencyCode" = cu."code" AND xr."effectiveDate" <= CURRENT_DATE+ ORDER BY xr."effectiveDate" DESC LIMIT 1+ ) mkt ON true+ WHERE cu."companyGroupId" = v_group+ ORDER BY cu."code";+END;+$$;++GRANT EXECUTE ON FUNCTION get_exchange_rate(TEXT, TEXT, DATE) TO authenticated;+GRANT EXECUTE ON FUNCTION get_exchange_rates(TEXT) TO authenticated;diff --git a/packages/database/supabase/migrations/20260903020233_currency-config-only.sql b/packages/database/supabase/migrations/20260903020233_currency-config-only.sqlnew file mode 100644index 0000000000..40851ea39a--- /dev/null+++ b/packages/database/supabase/migrations/20260903020233_currency-config-only.sql@@ -0,0 +1,78 @@+-- Currency & exchange rate refactor, part 2 of 3: migrate hand-set rates to+-- per-company overrides, drop the group-scoped rate column (currency becomes+-- config-only), drop the never-written exchangeRateHistory table, and delete+-- the exchange-rates integration rows.+-- Spec: .ai/specs/2026-09-02-currency-exchange-rate-refactor.md++-- 1) Preserve user intent: groups WITHOUT an active exchange-rates integration+-- have rates that were hand-edited (the feed never wrote them). Copy each+-- non-default (<> 1), non-base rate to a per-company override so every+-- member company resolves the same value it resolves today. Feed-derived+-- rates (integration-active groups) must NOT become standing pins.+-- Guarded on the column still existing: a retry of this file over committed+-- partial state (the deploy runner's failure mode) lands after the DROP below,+-- and this SELECT must not be the statement that wedges the deploy.+DO $$+BEGIN+ IF EXISTS (+ SELECT 1 FROM information_schema.columns+ WHERE table_schema = 'public' AND table_name = 'currency' AND column_name = 'exchangeRate'+ ) THEN+ INSERT INTO "exchangeRateOverride" ("companyId", "currencyCode", "rate", "createdBy")+ SELECT co."id", cu."code", cu."exchangeRate", 'system'+ FROM "currency" cu+ JOIN "company" co ON co."companyGroupId" = cu."companyGroupId"+ WHERE cu."exchangeRate" <> 1+ AND cu."code" <> co."baseCurrencyCode"+ -- Any exchange-rates-v1 row EVER (active or not): the group's rates are+ -- feed-derived, and pinning a stale market value as a manual override+ -- would silently freeze it against future market updates. Only groups+ -- the feed never touched carry hand-edited intent worth preserving.+ AND NOT EXISTS (+ SELECT 1 FROM "companyIntegration" ci+ WHERE ci."id" = 'exchange-rates-v1'+ AND ci."companyId" IN (+ SELECT c2."id" FROM "company" c2 WHERE c2."companyGroupId" = cu."companyGroupId"+ )+ )+ ON CONFLICT ("companyId", "currencyCode") DO NOTHING;+ END IF;+END $$;++-- 2) The "currencies" view selects c.*, so it must be dropped before the column+-- can go. Recreated below from the newest definition (20260228023426) minus+-- the rate.+DROP VIEW IF EXISTS "currencies";++-- 3) currency becomes pure per-group configuration (decimalPlaces, active,+-- historicalExchangeRate for IAS-21 consolidation, tags, customFields).+ALTER TABLE "currency" DROP COLUMN IF EXISTS "exchangeRate";++CREATE OR REPLACE VIEW "currencies" WITH(SECURITY_INVOKER=true) AS+ SELECT c.*, cc."name"+ FROM "currency" c+ INNER JOIN "currencyCode" cc+ ON cc."code" = c."code";++-- 4) exchangeRateHistory never had an application writer; the global+-- "exchangeRate" table replaces it. The table was API-reachable though, so+-- refuse (rather than discard) if any deployment turns out to hold rows —+-- an operator must preserve them before this migration can proceed.+DO $$+BEGIN+ IF EXISTS (+ SELECT 1 FROM information_schema.tables+ WHERE table_schema = 'public' AND table_name = 'exchangeRateHistory'+ ) THEN+ IF EXISTS (SELECT 1 FROM "exchangeRateHistory" LIMIT 1) THEN+ RAISE EXCEPTION+ 'exchangeRateHistory contains rows; export/preserve them before applying this migration';+ END IF;+ DROP TABLE "exchangeRateHistory";+ END IF;+END $$;++-- 5) Exchange rates no longer require an integration — the daily feed runs for+-- everyone. Remove the integration's per-company rows; the definition is+-- deleted from @carbon/ee in the same change set.+DELETE FROM "companyIntegration" WHERE "id" = 'exchange-rates-v1';diff --git a/packages/database/supabase/migrations/20260903020352_exchange-rate-guards-and-consolidation.sql b/packages/database/supabase/migrations/20260903020352_exchange-rate-guards-and-consolidation.sqlnew file mode 100644index 0000000000..c2a05f43a2--- /dev/null+++ b/packages/database/supabase/migrations/20260903020352_exchange-rate-guards-and-consolidation.sql@@ -0,0 +1,189 @@+-- Currency & exchange rate refactor, part 3 of 3: the missing salesInvoice+-- header->line rate propagation, rate-positivity CHECKs on every document+-- table, and translateTrialBalance re-pointed at the global "exchangeRate"+-- store (which resolves its multiply-direction contradiction: the rate is now+-- a true target-per-source pair ratio).+-- Spec: .ai/specs/2026-09-02-currency-exchange-rate-refactor.md++-- 1) salesInvoice header->line propagation. Forked from the purchaseInvoice+-- pair (20241210214820:325 + 20260616061244), which every sibling document+-- has and salesInvoice never got.+CREATE OR REPLACE FUNCTION update_sales_invoice_line_exchange_rate()+RETURNS TRIGGER AS $$+BEGIN+ UPDATE "salesInvoiceLine"+ SET "exchangeRate" = NEW."exchangeRate",+ "updatedBy" = COALESCE(NEW."updatedBy", 'system'),+ "updatedAt" = NOW()+ WHERE "invoiceId" = NEW."id";++ RETURN NEW;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++DROP TRIGGER IF EXISTS update_sales_invoice_line_exchange_rate_trigger ON "salesInvoice";+CREATE TRIGGER update_sales_invoice_line_exchange_rate_trigger+AFTER UPDATE OF "exchangeRate" ON "salesInvoice"+FOR EACH ROW+WHEN (OLD."exchangeRate" IS DISTINCT FROM NEW."exchangeRate")+EXECUTE FUNCTION update_sales_invoice_line_exchange_rate();++CREATE OR REPLACE FUNCTION sync_sales_invoice_line_exchange_rate_on_insert()+RETURNS TRIGGER AS $$+BEGIN+ IF NEW."exchangeRate" IS NULL OR NEW."exchangeRate" = 1 THEN+ -- salesInvoice."exchangeRate" is NOT NULL, but COALESCE anyway so a+ -- missing header row can never write NULL through this trigger (the CHECK+ -- below does not reject NULL — NULL satisfies a CHECK constraint).+ SELECT COALESCE("exchangeRate", 1) INTO NEW."exchangeRate"+ FROM "salesInvoice"+ WHERE "id" = NEW."invoiceId";+ NEW."exchangeRate" := COALESCE(NEW."exchangeRate", 1);+ END IF;+ RETURN NEW;+END;+$$ LANGUAGE plpgsql SECURITY DEFINER;++DROP TRIGGER IF EXISTS sales_invoice_line_exchange_rate_insert_trigger ON "salesInvoiceLine";+CREATE TRIGGER sales_invoice_line_exchange_rate_insert_trigger+BEFORE INSERT ON "salesInvoiceLine"+FOR EACH ROW+EXECUTE FUNCTION sync_sales_invoice_line_exchange_rate_on_insert();++-- One-time backfill, unposted invoices only (posted documents are immutable+-- history; their line rates stay whatever they posted at).+UPDATE "salesInvoiceLine" sil+SET "exchangeRate" = si."exchangeRate",+ "updatedBy" = COALESCE(si."updatedBy", 'system'),+ "updatedAt" = NOW()+FROM "salesInvoice" si+WHERE si."id" = sil."invoiceId"+ AND si."companyId" = sil."companyId"+ AND si."status" = 'Draft'+ AND sil."exchangeRate" IS DISTINCT FROM si."exchangeRate";++-- 2) A zero, negative, or NaN exchange rate is never a valid document snapshot+-- ('NaN'::numeric > 0 is TRUE in Postgres, so NaN needs its own clause; the+-- CHECK deliberately does NOT reject NULL — the nullable header columns+-- accept rate-less inserts from writers that predate stamping, and NULL is+-- handled by the resolver/stamping layer, not the constraint).+-- (subsumes PR #1541). Before validating, repair the two legacy classes the+-- constraint would otherwise trip on mid-deploy: NULL header/line rates+-- (columns added 2024-10 with no backfill; their line snapshots already+-- defaulted to 1) and rates the old 4-decimal NUMERIC clamp rounded to 0.0000+-- (widened 2026-08). The repair value is 1 for foreign-currency rows too,+-- deliberately: pre-refactor code treated these NULL/zero rates as 1+-- everywhere they were read, the rows' own line snapshots defaulted to 1,+-- and no truer rate is recoverable (the clamped-to-zero class means the+-- real rate was below 0.00005 and was never stored). Re-deriving from+-- today's market rates would REWRITE historical documents, which snapshots+-- exist to prevent. NOT VALID + VALIDATE so a huge table never takes an+-- exclusive-lock full rewrite; guarded so re-application (or PR #1541+-- landing too) is a no-op.+DO $$+DECLARE+ t TEXT;+BEGIN+ FOREACH t IN ARRAY ARRAY[+ 'quote', 'salesOrder', 'purchaseOrder', 'supplierQuote',+ 'purchaseInvoice', 'salesInvoice',+ 'quoteLinePrice', 'salesOrderLine', 'purchaseOrderLine',+ 'supplierQuoteLinePrice', 'purchaseInvoiceLine', 'salesInvoiceLine'+ ] LOOP+ EXECUTE format(+ 'UPDATE %I SET "exchangeRate" = 1,+ "updatedBy" = COALESCE("updatedBy", ''system''),+ "updatedAt" = NOW()+ WHERE "exchangeRate" IS NULL OR "exchangeRate" <= 0',+ t+ );+ IF NOT EXISTS (+ SELECT 1 FROM pg_constraint+ WHERE conname = t || '_exchangeRate_positive'+ AND conrelid = format('%I', t)::regclass+ ) THEN+ EXECUTE format(+ 'ALTER TABLE %I ADD CONSTRAINT %I CHECK ("exchangeRate" > 0 AND "exchangeRate" <> ''NaN''::numeric) NOT VALID',+ t, t || '_exchangeRate_positive'+ );+ END IF;+ EXECUTE format(+ 'ALTER TABLE %I VALIDATE CONSTRAINT %I',+ t, t || '_exchangeRate_positive'+ );+ END LOOP;+END $$;++-- 3) translateTrialBalance: closing/average now come from the global+-- "exchangeRate" store as target-per-source pair ratios, so the existing+-- balance * rate multiply is correct by construction. The rate resolution+-- itself lives in ONE place — "getConsolidationRates" (re-pointed at the+-- global store in the next migration, 20260903021021) — and this function+-- delegates to it; forking the 50-line ladder into both would re-instate+-- the duplication 20260713225803 explicitly extracted away. PL/pgSQL bodies+-- are late-bound, so referencing the 5-arg signature before that migration+-- defines it is safe: nothing executes this function mid-deploy.+CREATE OR REPLACE FUNCTION "translateTrialBalance" (+ p_company_group_id TEXT,+ p_company_id TEXT,+ p_target_currency TEXT,+ p_period_end DATE,+ p_period_start DATE DEFAULT NULL+)+RETURNS TABLE (+ "accountId" TEXT,+ "localBalance" NUMERIC,+ "exchangeRate" NUMERIC,+ "translatedBalance" NUMERIC+)+LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public+AS $$+DECLARE+ v_source_currency TEXT;+ v_closing_rate NUMERIC;+ v_average_rate NUMERIC;+ v_historical_rate NUMERIC;+BEGIN+ -- Get the subsidiary's base currency+ SELECT "baseCurrencyCode" INTO v_source_currency+ FROM "company" WHERE "id" = p_company_id;++ -- If same currency, no translation needed+ IF v_source_currency = p_target_currency THEN+ RETURN QUERY+ SELECT+ b."accountId",+ b."balanceAtDate" AS "localBalance",+ 1.0::NUMERIC AS "exchangeRate",+ b."balanceAtDate" AS "translatedBalance"+ FROM "accountTreeBalancesByCompany"(p_company_group_id, p_company_id, p_period_start, p_period_end) b+ INNER JOIN "account" a ON a."id" = b."accountId"+ WHERE a."isGroup" = false;+ RETURN;+ END IF;++ SELECT r."closingRate", r."averageRate", r."historicalRate"+ INTO v_closing_rate, v_average_rate, v_historical_rate+ FROM "getConsolidationRates"(+ p_company_group_id, p_company_id, p_target_currency, p_period_end, p_period_start+ ) r;++ RETURN QUERY+ SELECT+ b."accountId",+ b."balanceAtDate" AS "localBalance",+ CASE a."consolidatedRate"+ WHEN 'Current' THEN v_closing_rate+ WHEN 'Average' THEN v_average_rate+ WHEN 'Historical' THEN v_historical_rate+ END AS "exchangeRate",+ ROUND(b."balanceAtDate" * CASE a."consolidatedRate"+ WHEN 'Current' THEN v_closing_rate+ WHEN 'Average' THEN v_average_rate+ WHEN 'Historical' THEN v_historical_rate+ END, 4) AS "translatedBalance"+ FROM "accountTreeBalancesByCompany"(p_company_group_id, p_company_id, p_period_start, p_period_end) b+ INNER JOIN "account" a ON a."id" = b."accountId"+ WHERE a."isGroup" = false;+END;+$$;diff --git a/packages/database/supabase/migrations/20260903021021_consolidation-rates-pair-fix.sql b/packages/database/supabase/migrations/20260903021021_consolidation-rates-pair-fix.sqlnew file mode 100644index 0000000000..b5df499509--- /dev/null+++ b/packages/database/supabase/migrations/20260903021021_consolidation-rates-pair-fix.sql@@ -0,0 +1,101 @@+-- Currency & exchange rate refactor, follow-up to part 3: "getConsolidationRates"+-- (20260713225803) still read the dropped "exchangeRateHistory" table and+-- COALESCEd every rate to 1. Re-pointed at the global "exchangeRate" store as+-- explicit target-per-source pair ratios. The target currency becomes a real+-- parameter — the old shape implied a target it never named, which is the+-- root defect this refactor exists to remove.+-- Spec: .ai/specs/2026-09-02-currency-exchange-rate-refactor.md++-- CREATE OR REPLACE with a new parameter would create an overload (the+-- attach_event_trigger trap); drop the old signature first.+DROP FUNCTION IF EXISTS "getConsolidationRates"(TEXT, TEXT, DATE, DATE);++CREATE OR REPLACE FUNCTION "getConsolidationRates" (+ p_company_group_id TEXT,+ p_company_id TEXT,+ p_target_currency TEXT,+ p_period_end DATE,+ p_period_start DATE DEFAULT NULL+)+RETURNS TABLE (+ "sourceCurrency" TEXT,+ "closingRate" NUMERIC,+ "averageRate" NUMERIC,+ "historicalRate" NUMERIC+)+LANGUAGE "plpgsql" SECURITY INVOKER SET search_path = public+AS $$+DECLARE+ v_source_currency TEXT;+ v_source_close NUMERIC;+ v_target_close NUMERIC;+ v_closing_rate NUMERIC;+ v_average_rate NUMERIC;+ v_historical_rate NUMERIC;+BEGIN+ SELECT "baseCurrencyCode" INTO v_source_currency+ FROM "company" WHERE "id" = p_company_id;++ IF v_source_currency = p_target_currency THEN+ RETURN QUERY SELECT v_source_currency, 1::NUMERIC, 1::NUMERIC, 1::NUMERIC;+ RETURN;+ END IF;++ -- Closing rate: each side's latest global rate on or before period end; a+ -- period predating the store's earliest row falls back to that side's+ -- earliest rate (never to 1).+ SELECT "rate" INTO v_source_close FROM "exchangeRate"+ WHERE "currencyCode" = v_source_currency AND "effectiveDate" <= p_period_end+ ORDER BY "effectiveDate" DESC LIMIT 1;+ IF v_source_close IS NULL THEN+ SELECT "rate" INTO v_source_close FROM "exchangeRate"+ WHERE "currencyCode" = v_source_currency+ ORDER BY "effectiveDate" ASC LIMIT 1;+ END IF;++ SELECT "rate" INTO v_target_close FROM "exchangeRate"+ WHERE "currencyCode" = p_target_currency AND "effectiveDate" <= p_period_end+ ORDER BY "effectiveDate" DESC LIMIT 1;+ IF v_target_close IS NULL THEN+ SELECT "rate" INTO v_target_close FROM "exchangeRate"+ WHERE "currencyCode" = p_target_currency+ ORDER BY "effectiveDate" ASC LIMIT 1;+ END IF;++ IF v_source_close IS NULL OR v_target_close IS NULL THEN+ RAISE EXCEPTION 'No exchange rate available to translate % to %',+ v_source_currency, p_target_currency;+ END IF;++ v_closing_rate := v_target_close / v_source_close;++ -- Average rate: mean of the daily pair ratios over the period, where both+ -- currencies have a rate on the same date; falls back to the closing rate.+ SELECT AVG(t."rate" / s."rate") INTO v_average_rate+ FROM "exchangeRate" s+ JOIN "exchangeRate" t ON t."effectiveDate" = s."effectiveDate"+ WHERE s."currencyCode" = v_source_currency+ AND t."currencyCode" = p_target_currency+ AND s."effectiveDate" >= COALESCE(p_period_start, p_period_end - INTERVAL '1 year')+ AND s."effectiveDate" <= p_period_end;++ -- Historical rate: from currency table (manually set for equity, IAS 21).+ -- Its anchor is BY CONVENTION target-per-source against the group's+ -- presentation currency — every consolidated report passes the ROOT+ -- company's base as p_target_currency, and the edit form documents the+ -- convention. It is NOT re-anchored per target: a manual equity rate is a+ -- stated historical fact, not a derivable ratio. Consolidating to any other+ -- target is a consolidation-feature follow-up (tracked in the spec), not a+ -- silent conversion this function should invent.+ SELECT "historicalExchangeRate" INTO v_historical_rate+ FROM "currency"+ WHERE "code" = v_source_currency+ AND "companyGroupId" = p_company_group_id;++ v_average_rate := COALESCE(v_average_rate, v_closing_rate);+ v_historical_rate := COALESCE(v_historical_rate, v_closing_rate);++ RETURN QUERY+ SELECT v_source_currency, v_closing_rate, v_average_rate, v_historical_rate;+END;+$$;diff --git a/packages/ee/AGENTS.md b/packages/ee/AGENTS.mdindex 884b8b49c3..00057d5e08 100644--- a/packages/ee/AGENTS.md+++ b/packages/ee/AGENTS.md@@ -1,6 +1,6 @@# @carbon/ee-Enterprise edition — integrations registry, accounting sync (Xero, QuickBooks Online, Rillet), plan gating, exchange rates, Slack, email, Jira, Linear, Onshape, storage rules, the planning engines (MRP + finite scheduling), and SAML SSO.+Enterprise edition — integrations registry, accounting sync (Xero, QuickBooks Online, Rillet), plan gating, Slack, email, Jira, Linear, Onshape, storage rules, the planning engines (MRP + finite scheduling), and SAML SSO. (Exchange rates are no longer an integration — the platform-global feed lives in @carbon/jobs `update-exchange-rates`.)## Always@@ -41,7 +41,7 @@ pnpm --filter @carbon/ee typecheck # tsgo --noEmit- **Dependency sync**: transaction syncers use `ensureDependencySynced()` for JIT deps (e.g. push customer before invoice)- **Integration pattern**: `defineIntegration()` → config with id, name, settings, OAuth, actions- **SAML SSO** (`./sso.server`, `src/sso/`): `isSsoEnabled()` (`gate.ts` — Enterprise edition AND `sso` in `AUTH_PROVIDERS`) is the ONE flag; the connection lookups and admin mutations self-gate on it. `provider.server.ts` = GoTrue admin API wrappers + `getSamlSpUrls`; `connections.server.ts` = `ssoConnection` lookups (each attaches a computed `domains: string[]` of VERIFIED `ssoDomain` claims), `isSsoRequiredForEmail`, `getSsoAwareInviteLink`, upsert/requireSso/deactivate mutations, and the domain-claim flows `addSsoDomain`/`verifySsoDomain`/`removeSsoDomain`; `verification.server.ts` = the DNS TXT ownership challenge (`_carbon-challenge.<domain>` → `carbon-domain-verification=<token>`, `checkDomainVerification` with pinned public resolvers, one-shot manual verify — no polling or re-verification); `session.server.ts` = amr-based session classification (`getSsoProviderIdFromSession` for enforcement, never `getSsoProviderIdFromUser`); `provisioning.server.ts` = identity linking + invite-first migration + `deleteJitSsoUser` (full removal of a rejected throwaway JIT user — auth user AND its trigger-created `user`/`userPermission` rows, guarded on zero memberships; takes a `Kysely<KyselyDatabase>` param — callers pass their own db client) + the **pre-seed** helpers `seedSsoIdentityForUser` / `backfillSsoIdentitiesForDomain` / `removeSsoIdentitiesForDomain` (+ pure `emailDomain` / `ssoProviderColumn`). Pre-seeding is the account-linking fix under `GOTRUE_DISABLE_SIGNUP=true`: a row in `auth.identities` with `identity_data.email = lower(email)` makes GoTrue link a SAML sign-in to the existing user via its **email-column** fallback — provider-agnostic (works for any IdP: Okta/Entra/OneLogin/Ping/…, whose NameID shapes differ), keyed on the generated `email` column NOT `provider_id`. `verifySsoDomain` backfills every existing on-domain user when a domain is verified; the three account-creation flows (`apps/erp/.../users.server.ts`) seed newly-invited users; `removeSsoDomain` tears the domain's identities down. A DB guard trigger on `auth.sso_domains` (migration `…_sso-domain-guard.sql`, `ssoReservedDomain` table) blocks registering an unclaimed/reserved domain. Only verified domains ever reach GoTrue. Full architecture + the provider-agnostic linking rationale: `.claude/rules/authentication-system.md` (Enterprise SAML SSO section); design: `.ai/specs/2026-08-29-saml-sso-account-linking.md`-- **Exports**: `./accounting`, `./planning`, `./plan`, `./plan.server`, `./exchange-rates.server`, `./slack.server`, `./hooks.server`, `./sso.server`, `./jira`, `./linear`, `./rillet/hooks.server`, `./xero/hooks.server`, etc.+- **Exports**: `./accounting`, `./planning`, `./plan`, `./plan.server`, `./slack.server`, `./hooks.server`, `./sso.server`, `./jira`, `./linear`, `./rillet/hooks.server`, `./xero/hooks.server`, etc.## Cross-Referencesdiff --git a/packages/ee/package.json b/packages/ee/package.jsonindex 34dc893a55..2f4e0610a2 100644--- a/packages/ee/package.json+++ b/packages/ee/package.json@@ -10,7 +10,6 @@"./action-task-entity": "./src/lib/actionTaskEntity.ts","./storage-rules": "./src/storage-rules/index.ts","./storage-rules.server": "./src/storage-rules/server.ts",- "./exchange-rates.server": "./src/exchange-rates/exchange-rates.server.ts","./jira": "./src/jira/lib/index.ts","./jira.server": "./src/jira/lib/index.server.ts","./linear": "./src/linear/lib/index.ts",diff --git a/packages/ee/src/exchange-rates/config.tsx b/packages/ee/src/exchange-rates/config.tsxdeleted file mode 100644index e78cb10b3c..0000000000--- a/packages/ee/src/exchange-rates/config.tsx+++ /dev/null@@ -1,93 +0,0 @@-import { cn } from "@carbon/react";-import type { SVGProps } from "react";-import { z } from "zod";-import { defineIntegration } from "../fns";--export const ExchangeRates = defineIntegration({- name: "Exchange Rates",- id: "exchange-rates-v1",- active: true,- category: "Accounting",- logo: Logo,- description:- "The exchange rates integration allows you to automatically update the exchange rates for your company. Simply install the integration and we'll automatically update the exchange rates for you every day.",- shortDescription:- "Automatically update the currency exchange rates for your company.",- images: [],- settings: [],- schema: z.object({})-});--function Logo(props: SVGProps<SVGSVGElement>) {- return (- <svg- {...props}- viewBox="-2457.7 882.5 422.8 65"- fill="none"- xmlns="http://www.w3.org/2000/svg"- className={cn("text-foreground", props.className)}- >- <path- fill="currentColor"- d="M-2360.1,926.9c2.6,0,5.4-0.4,8.4-1.3l1.1,5.2c-3.1,1.2-6.8,1.7-10,1.7c-8.6,0-11.6-4-11.6-10.5v-7.2 c0-5.8,2.6-10.7,11.3-10.7c8.8,0,10.7,5.1,10.7,11v5.8h-15.2v1.4C-2365.4,925.6-2364.2,926.9-2360.1,926.9z M-2365.4,915.4h8.7 v-1.3c0-2.6-0.8-4.4-4.2-4.4c-3.4,0-4.5,1.8-4.5,4.4V915.4z"- />- <path- fill="currentColor"- d="M-2347,931.9l8.8-13.7l-8.6-13.6h6.8l5.4,8.3l5.4-8.3h6.8l-8.6,13.6l8.9,13.7h-7l-5.4-8.5l-5.5,8.5H-2347z"- />- <path- fill="currentColor"- d="M-2318.7,922v-7.5c0-7.3,3.2-10.5,11.8-10.5c1.9,0,4.7,0.3,6.7,1l-0.8,5.6c-1.9-0.5-4.3-0.7-5.7-0.7 c-3.9,0-5.1,1.2-5.1,4.5v7.6c0,3.4,1.2,4.5,5.1,4.5c1.7,0,3.7-0.2,5.7-0.7l0.8,5.6c-1.8,0.6-4.4,1-6.7,1 C-2315.5,932.5-2318.7,929.4-2318.7,922z"- />- <path- fill="currentColor"- d="M-2277.8,931.9v-19.1c0-1.5-0.6-2.2-2.2-2.2c-1.7,0-4.7,1-7.1,2.3v19h-6.8v-38.5l6.8-1v14.2 c3-1.6,7.1-2.6,10-2.6c4.5,0,6.2,3.2,6.2,8.1v19.8H-2277.8z"- />- <path- fill="currentColor"- d="M-2243.2,931.9h-5.6l-0.5-1.9c-2.5,1.6-5.4,2.4-8.1,2.4c-5,0-7.1-3.4-7.1-8.1c0-5.6,2.4-7.7,8-7.7h6.6v-2.9 c0-3-0.8-4.1-5.2-4.1c-2.5,0-5.2,0.3-7.6,0.8l-0.8-5.2c2.6-0.8,6.3-1.3,9.4-1.3c8.6,0,11.1,3,11.1,9.9V931.9z M-2250,921.6h-5 c-2.2,0-2.9,0.6-2.9,2.7c0,1.9,0.6,2.7,2.7,2.7c2,0,3.9-0.7,5.2-1.4V921.6z"- />- <path- fill="currentColor"- d="M-2219.7,931.9v-19.1c0-1.5-0.6-2.2-2.2-2.2c-1.7,0-4.7,1-7.1,2.3v19h-6.8v-27.3h5.2l0.7,2.3 c3.4-1.7,7.7-2.9,10.9-2.9c4.5,0,6.2,3.2,6.2,8.1v19.8H-2219.7z"- />- <path- fill="currentColor"- d="M-2197.6,924.6c-0.9,0.6-1.6,1.3-1.6,2.2c0,0.7,0.4,1.1,1.5,1.2c3,0.3,4.7,0.5,7.9,0.8 c4.4,0.5,5.8,2.7,5.8,6.6c0,5.8-2.1,8.1-12.3,8.1c-3.1,0-7.5-0.4-10.5-1.4l0.8-5.1c2.9,0.7,6,1.2,9.2,1.2c5.4,0,6.5-0.4,6.5-2.2 c0-1.7-0.5-2-2.6-2.2c-3.1-0.3-4.4-0.5-7.9-0.9c-3.9-0.4-5.4-1.7-5.4-5.2c0-2.2,1.5-3.7,2.9-4.7c-2.5-1.5-3.7-4-3.7-7.3v-2.6 c0.1-5.7,3.1-9.1,11-9.1c1.9,0,3.3,0.2,4.7,0.6h8.4v3.4c-1,0.3-2.1,0.6-3,0.8c0.6,1.2,1,2.7,1,4.3v2.6c0,5.6-3.4,8.9-11,8.9 C-2196.6,924.7-2197.1,924.7-2197.6,924.6z M-2196,909.6c-3.4,0-4.5,1.2-4.5,3.8v2.1c0,2.7,1.3,3.7,4.5,3.7 c3.3,0,4.6-1.1,4.6-3.7v-2.1C-2191.4,910.8-2192.6,909.6-2196,909.6z"- />- <path- fill="currentColor"- d="M-2167,926.9c2.6,0,5.4-0.4,8.4-1.3l1.1,5.2c-3.1,1.2-6.8,1.7-10,1.7c-8.6,0-11.6-4-11.6-10.5v-7.2 c0-5.8,2.6-10.7,11.3-10.7c8.8,0,10.7,5.1,10.7,11v5.8h-15.2v1.4C-2172.3,925.6-2171.1,926.9-2167,926.9z M-2172.3,915.4h8.7 v-1.3c0-2.6-0.8-4.4-4.2-4.4c-3.4,0-4.5,1.8-4.5,4.4V915.4z"- />- <path- fill="currentColor"- d="M-2136.8,910.4c-2.6,1.2-4.8,2.4-7.2,4v17.6h-6.8v-27.3h5.8l0.4,3c1.5-1,4.8-2.9,7.2-3.6L-2136.8,910.4z"- />- <path- fill="currentColor"- d="M-2112.2,931.9h-5.6l-0.5-1.9c-2.5,1.6-5.4,2.4-8.1,2.4c-5,0-7.1-3.4-7.1-8.1c0-5.6,2.4-7.7,8-7.7h6.6v-2.9 c0-3-0.8-4.1-5.2-4.1c-2.5,0-5.2,0.3-7.6,0.8l-0.8-5.2c2.6-0.8,6.3-1.3,9.4-1.3c8.6,0,11.1,3,11.1,9.9V931.9z M-2119,921.6h-5 c-2.2,0-2.9,0.6-2.9,2.7c0,1.9,0.6,2.7,2.7,2.7c2,0,3.9-0.7,5.2-1.4V921.6z"- />- <path- fill="currentColor"- d="M-2090.3,931.4c-1.5,0.6-4.3,1.1-6,1.1c-5,0-7.5-2.4-7.5-7.2v-15.2h-4.1v-5.4h4.1v-6.8l6.8-1v7.7h7l-0.4,5.4 h-6.6v14.3c0,1.5,0.7,2.4,2.5,2.4c1,0,2.2-0.2,3.4-0.6L-2090.3,931.4z"- />- <path- fill="currentColor"- d="M-2074,926.9c2.6,0,5.4-0.4,8.4-1.3l1.1,5.2c-3.1,1.2-6.8,1.7-10,1.7c-8.6,0-11.6-4-11.6-10.5v-7.2 c0-5.8,2.6-10.7,11.3-10.7c8.8,0,10.7,5.1,10.7,11v5.8h-15.2v1.4C-2079.3,925.6-2078.2,926.9-2074,926.9z M-2079.3,915.4h8.7 v-1.3c0-2.6-0.8-4.4-4.2-4.4c-3.4,0-4.5,1.8-4.5,4.4V915.4z"- />- <path- fill="currentColor"- d="M-2049.5,932.5c-2.9,0-6.9-0.7-9.4-1.6l1-5.2c2.3,0.7,5.3,1.2,8.1,1.2c3,0,3.5-0.7,3.5-2.7 c0-1.7-0.3-2.5-4.8-3.6c-6.7-1.6-7.5-3.3-7.5-8.6c0-5.5,2.4-7.9,10.2-7.9c2.5,0,5.8,0.3,8.2,1l-0.7,5.4c-2.1-0.4-5.4-0.8-7.5-0.8 c-3,0-3.5,0.7-3.5,2.4c0,2.2,0.2,2.4,3.9,3.3c7.6,2,8.4,3,8.4,8.6C-2039.6,929.3-2041.3,932.5-2049.5,932.5z"- />-- <path- fill="currentColor"- d="M-2424.3,914.8c-1.9,1.9-3.8,3.7-5.7,5.6c-5.2,5.2-10.3,10.3-15.5,15.5c-0.2,0.2-0.5,0.4-0.8,0.7 c-7.5-8.1-10.6-17.5-8.1-28.1c2.9-12.6,11-20.6,23.6-23.4c10.6-2.3,19.8,0.8,27.8,8.2c-0.3,0.4-0.6,0.6-0.8,0.9 c-6.5,6.5-12.9,12.9-19.4,19.4c-0.3,0.3-0.6,0.6-0.9,1C-2424.2,914.7-2424.3,914.7-2424.3,914.8z"- />- <path- fill="currentColor"- d="M-2424.3,914.8c0.1-0.1,0.1-0.1,0.2-0.2c4.3-0.1,8.6-0.1,12.8-0.2c1.6,0,3.2-0.1,4.7-0.1 c4.1-0.1,8.1-0.1,12.2-0.2c0.5,0,0.9,0,1.6,0c-0.1,1.6-0.2,3.2-0.4,4.7c-1.8,10.2-7.2,17.9-16.3,22.9c-4.1,2.3-8.6,3.4-13.3,3.7 c-0.8,0-1-0.2-1-0.9c-0.1-7.9-0.2-15.7-0.4-23.6C-2424.2,918.9-2424.3,916.9-2424.3,914.8z"- />- </svg>- );-}diff --git a/packages/ee/src/exchange-rates/exchange-rates.server.ts b/packages/ee/src/exchange-rates/exchange-rates.server.tsdeleted file mode 100644index 358d63f3dc..0000000000--- a/packages/ee/src/exchange-rates/exchange-rates.server.ts+++ /dev/null@@ -1,104 +0,0 @@-type CurrencyCode = string;--type ExchangeClientOptions = {- apiKey?: string;- apiUrl: string;-};--export type Rates = { [key in CurrencyCode]?: number };--type ExchangeRatesSuccessResponse = {- success: boolean;- timestamp: number;- base: CurrencyCode;- date: string;- rates: Rates;-};--type ExchangeRatesErrorResponse = {- error: {- code: string;- message: string;- };-};--type ExchangeRatesResponse =- | ExchangeRatesErrorResponse- | ExchangeRatesSuccessResponse;--export class ExchangeRatesClient {- #apiKey: string;- #apiUrl: string;-- constructor(options: ExchangeClientOptions) {- if (!options.apiKey) throw new Error("EXCHANGE_RATES_API_KEY not set");-- this.#apiKey = options.apiKey;- this.#apiUrl = options.apiUrl;- }-- getMetaData() {- return {- apiUrl: this.#apiUrl- };- }-- async getExchangeRates(): Promise<Rates> {- /**- * Fetches the latest exchange rates from the API. For the free tier of the API, we can only fetch- * the rates with a base currency of EUR.- */- const url = `${this.#apiUrl}?access_key=${this.#apiKey}`;-- const response = await fetch(url);-- if (!response.ok) {- throw new Error(`HTTP error! status: ${response.status}`);- }-- const data: ExchangeRatesResponse = await response.json();-- if ("success" in data && data.success === true) {- return data.rates;- }-- throw new Error("Unrecognized response from exchange rates server");- }-- async convertExchangeRates(- baseCurrencyCode: CurrencyCode,- rates: Rates- ): Promise<Rates> {- /**- * Convert the EUR-based exchange rates to a different base currency.- */- const baseRate = rates[baseCurrencyCode];- if (!baseRate) throw new Error("Base rate not found");-- const convertedRates = Object.entries(rates).reduce<Rates>(- (acc, [currency, value]) => {- return {- ...acc,- [currency]: value! / baseRate- };- },- {- [baseCurrencyCode]: 1- }- );-- return convertedRates;- }-}--export const getExchangeRatesClient = (- apiKey?: string,- apiUrl: string = "https://api.exchangeratesapi.io/v1/latest"-) => {- return typeof apiKey === "string"- ? new ExchangeRatesClient({- apiKey,- apiUrl- })- : undefined;-};diff --git a/packages/ee/src/index.ts b/packages/ee/src/index.tsindex b584ebc46d..1771112fb8 100644--- a/packages/ee/src/index.ts+++ b/packages/ee/src/index.ts@@ -1,5 +1,4 @@import { Email } from "./email/config";-import { ExchangeRates } from "./exchange-rates/config";import { Jira } from "./jira/config";import { Linear } from "./linear/config";import { Onshape } from "./onshape/config";@@ -32,7 +31,6 @@ export type {export const integrations = [// Radan,Email,- ExchangeRates,Jira,Linear,Onshape,diff --git a/packages/ee/src/integrations/secrets.test.ts b/packages/ee/src/integrations/secrets.test.tsindex 4433e59e57..125ff36fba 100644--- a/packages/ee/src/integrations/secrets.test.ts+++ b/packages/ee/src/integrations/secrets.test.ts@@ -143,11 +143,11 @@ describe("resolveIntegrationSecrets", () => {it("returns metadata as-is for an integration with no secret keys", async () => {const client = mockClient({});const metadata = { active: true, someConfig: "x" };- // exchange-rates-v1 has no SECRET_KEYS entry — nothing to resolve.+ // sage has no SECRET_KEYS entry — nothing to resolve.const merged = await resolveIntegrationSecrets(client,"co",- "exchange-rates-v1",+ "sage",metadata,null);diff --git a/packages/ee/src/integrations/secrets.ts b/packages/ee/src/integrations/secrets.tsindex 62a361da3c..3f4bf9f42c 100644--- a/packages/ee/src/integrations/secrets.ts+++ b/packages/ee/src/integrations/secrets.ts@@ -34,7 +34,6 @@ export const SECRET_KEYS: Record<string, string[]> = {// email carries a secret in EITHER variant: Resend `apiKey` or SMTP `password`// (top-level). splitSecrets omits whichever is absent for the active provider.email: ["apiKey", "password"]- // exchange-rates-v1: none (apiKey is env-based, never in metadata).};/** Thrown when a secret is expected in the vault but cannot be read (fail-closed). */diff --git a/packages/ee/src/plan.ts b/packages/ee/src/plan.tsindex b55b96538a..d89b4371d6 100644--- a/packages/ee/src/plan.ts+++ b/packages/ee/src/plan.ts@@ -26,10 +26,7 @@ export type Feature = keyof typeof FEATURE_PLANS;* Integration ids that bypass the `INTEGRATIONS` plan gate. Add ids here for* integrations that should remain available on every plan.*/-export const INTEGRATION_WHITELIST = new Set<IntegrationID>([- "email",- "exchange-rates-v1"-]);+export const INTEGRATION_WHITELIST = new Set<IntegrationID>(["email"]);export function isIntegrationWhitelisted(id: string) {return INTEGRATION_WHITELIST.has(id as IntegrationID);diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.jsonindex 76d1095be1..92ad15b935 100644--- a/packages/jobs/manifests/schema.json+++ b/packages/jobs/manifests/schema.json@@ -1,134 +1,118 @@{"kind": "carbon-company-backup","version": 1,- "schemaVersion": "20260825075035",+ "schemaVersion": "20260903021021","sourceCompanyId": "schema-baseline","sourceCompanyGroupId": null,"sourceCompanyName": null,- "exportedAt": "2026-08-25T13:16:57.172Z",+ "exportedAt": "2026-09-03T02:33:52.211Z","exportedBy": "schema-baseline","label": "schema baseline","includeStorage": "none","tables": [{- "name": "ability",+ "name": "account","rows": 0,"columns": [- "active",- "curve",- "shadowWeeks",- "createdAt",+ "incomeBalance","updatedAt",+ "createdBy",+ "number",+ "consolidatedRate","id",- "companyId",+ "active",+ "isSystem","name",- "createdBy",- "updatedBy"- ]- },- {- "name": "account",- "rows": 0,- "columns": [- "customFields",+ "createdAt",+ "companyGroupId",+ "tags","updatedBy","isGroup",- "parentId",- "class",+ "customFields","accountType",- "isSystem",- "tags",- "companyGroupId",- "name",- "createdAt",- "active",- "id",- "consolidatedRate",- "incomeBalance",- "number",- "createdBy",- "updatedAt"+ "class",+ "parentId"]},{"name": "accountDefault","rows": 0,"columns": [- "serviceChargeAccount",- "supplierWriteOffAccount",- "goodsReceivedNotInvoicedAccount",- "retainedEarningsAccount",- "maintenanceAccount",- "salesAccount",- "prepaymentAccount",- "overheadVarianceAccount",- "realizedExchangeLossAccount",- "purchaseVarianceAccount",- "realizedExchangeGainAccount",- "accumulatedDepreciationOnDisposalAccount",- "bankForeignCurrencyAccount",- "materialVarianceAccount",- "inventoryAdjustmentVarianceAccount",- "assetLossOnDisposalAccount",- "finishedGoodsAccount",- "companyId",- "deferredTaxExpenseAccountId",- "deferredTaxLiabilityAccountId",- "salesTaxPayableAccount",- "purchaseTaxPayableAccount",- "overheadAbsorptionAccount",- "rawMaterialsAccount",+ "laborAbsorptionAccount",+ "updatedBy","laborAndMachineVarianceAccount",+ "rawMaterialsAccount","workInProgressAccount",- "updatedBy",- "laborAbsorptionAccount",- "assetDepreciationExpenseAccount",- "salesDiscountAccount",- "costOfGoodsSoldAccount",- "customerWriteOffAccount",- "assetGainOnDisposalAccount",- "customerPaymentDiscountAccount",- "currencyTranslationAccount",- "reverseChargeSalesTaxPayableAccount",- "supplierPaymentDiscountAccount",- "payablesAccount",- "accumulatedDepreciationAccount",- "intercompanyReceivablesAccount",- "receivablesAccount",- "bankLocalCurrencyAccount",- "scrapAccount",- "subcontractingVarianceAccount",- "assetAquisitionCostOnDisposalAccount",- "bankCashAccount",+ "overheadAbsorptionAccount",+ "purchaseTaxPayableAccount",+ "salesTaxPayableAccount",+ "deferredTaxLiabilityAccountId",+ "inventoryAdjustmentVarianceAccount",+ "deferredTaxExpenseAccountId",+ "companyId",+ "finishedGoodsAccount",+ "assetLossOnDisposalAccount",+ "materialVarianceAccount",+ "bankForeignCurrencyAccount",+ "accumulatedDepreciationOnDisposalAccount",+ "realizedExchangeGainAccount",+ "purchaseVarianceAccount",+ "overheadVarianceAccount",+ "realizedExchangeLossAccount",+ "prepaymentAccount",+ "salesAccount",+ "maintenanceAccount",+ "retainedEarningsAccount",+ "goodsReceivedNotInvoicedAccount",+ "supplierWriteOffAccount",+ "serviceChargeAccount",+ "interestAccount",+ "assetAquisitionCostAccount",+ "supplierPrepaymentAccount",+ "intercompanyPayablesAccount",+ "lotSizeVarianceAccount","indirectCostAccount",+ "bankCashAccount","roundingAccount",- "lotSizeVarianceAccount",- "intercompanyPayablesAccount",- "supplierPrepaymentAccount",- "assetAquisitionCostAccount",- "interestAccount"+ "scrapAccount",+ "assetAquisitionCostOnDisposalAccount",+ "subcontractingVarianceAccount",+ "bankLocalCurrencyAccount",+ "receivablesAccount",+ "payablesAccount",+ "intercompanyReceivablesAccount",+ "accumulatedDepreciationAccount",+ "supplierPaymentDiscountAccount",+ "reverseChargeSalesTaxPayableAccount",+ "customerPaymentDiscountAccount",+ "currencyTranslationAccount",+ "assetGainOnDisposalAccount",+ "customerWriteOffAccount",+ "salesDiscountAccount",+ "assetDepreciationExpenseAccount",+ "costOfGoodsSoldAccount"]},{"name": "accountingPeriod","rows": 0,"columns": [- "closedAt",+ "status",+ "periodNumber",+ "endDate",+ "closedBy",+ "closeStatus",+ "companyId",+ "lockedAt",+ "startDate",+ "fiscalYear",+ "lockedBy",+ "updatedBy",+ "createdBy","updatedAt","id","createdAt",- "updatedBy",- "createdBy",- "fiscalYear",- "startDate",- "lockedBy",- "lockedAt",- "companyId",- "closeStatus",- "closedBy",- "status",- "periodNumber",- "endDate"+ "closedAt"]},{@@ -136,210 +120,210 @@"rows": 0,"columns": ["endingBalance",- "accountId",- "accountingPeriodId","createdBy",- "id",- "updatedBy",+ "accountingPeriodId",+ "accountId","endingBalanceDate",- "companyId",+ "updatedBy",+ "id","createdAt",- "updatedAt"+ "updatedAt",+ "companyId"]},{"name": "accountingSyncOperation","rows": 0,"columns": [- "entityId",- "updatedAt",- "completedAt",- "externalId",- "createdBy",- "updatedBy",- "createdAt",- "entityType",+ "trigger","integration","errorMessage",- "trigger",- "lastAttemptAt",- "id",- "idempotencyKey",- "direction",+ "entityType",+ "updatedBy",+ "createdAt",+ "externalId",+ "createdBy",+ "entityId",+ "completedAt",+ "updatedAt",+ "status",+ "attemptCount",+ "metadata","errorCode","companyId",- "metadata",- "attemptCount",- "status"+ "direction",+ "idempotencyKey",+ "id",+ "lastAttemptAt"]},{"name": "accountingSyncTieOut","rows": 0,"columns": [- "blockedAmount",- "id",- "excludedAmount",- "carbonPostedAmount",- "internalDelta",- "companyId",- "createdBy",- "pendingAmount",- "docBackedAmount",- "accountId",- "providerAmount","computedAt","createdAt",+ "accountId",+ "providerAmount",+ "syncedAmount","updatedAt","updatedBy","accountingPeriodId",- "integration","externalDelta",- "syncedAmount"+ "integration",+ "carbonPostedAmount",+ "blockedAmount",+ "id",+ "excludedAmount",+ "pendingAmount",+ "docBackedAmount",+ "internalDelta",+ "companyId",+ "createdBy"]},{"name": "address","rows": 0,"columns": [- "phone",- "companyId",- "addressLine1",- "postalCode",- "fax",- "id",- "countryCode",- "addressLine2",+ "stateProvince","city",- "stateProvince"+ "addressLine2",+ "countryCode",+ "id",+ "fax",+ "postalCode",+ "addressLine1",+ "companyId",+ "phone"]},{"name": "agentThread","rows": 0,"columns": [- "modelId",- "userId","title",+ "userId","createdBy",- "updatedBy",- "id",- "lastContext",+ "modelId","companyId","updatedAt",- "createdAt"+ "createdAt",+ "id",+ "updatedBy",+ "lastContext"]},{"name": "agentMessage","rows": 0,"columns": [- "updatedBy",- "threadId",- "finishReason",- "outputTokens",+ "feedback",+ "createdBy","id","inputTokens",- "createdBy",- "feedback",+ "outputTokens",+ "finishReason",+ "updatedBy",+ "threadId",+ "context",+ "createdAt",+ "feedbackNote","role","companyId",- "updatedAt",- "feedbackNote",- "context",- "createdAt"+ "updatedAt"]},{"name": "agentMessagePart","rows": 0,"columns": [- "textContent","toolOutput","id","toolCallId",- "toolInput",- "toolClassification",+ "textContent","messageId","toolDurationMs","createdAt",- "updatedBy",- "createdBy",+ "toolInput",+ "toolClassification","toolState","type",- "toolName",+ "updatedBy",+ "createdBy","updatedAt","orderIndex","companyId",- "errorMessage"+ "errorMessage",+ "toolName"]},{"name": "approvalRequest","rows": 0,"columns": [- "requestedBy",- "decisionBy",- "id",- "decisionNotes",- "decisionAt",- "updatedAt",- "documentType",- "createdBy","updatedBy","companyId","amount","requestedAt",+ "status","createdAt","documentId",- "status"+ "requestedBy",+ "decisionNotes",+ "id",+ "decisionBy",+ "decisionAt",+ "documentType",+ "createdBy",+ "updatedAt"]},{"name": "approvalRule","rows": 0,"columns": [+ "enabled",+ "approverGroupIds",+ "escalationDays",+ "defaultApproverId",+ "updatedAt",+ "documentType","createdAt","companyId",- "documentType",- "lowerBoundAmount","updatedBy","createdBy","id",- "escalationDays",- "enabled",- "approverGroupIds",- "updatedAt",- "defaultApproverId"+ "lowerBoundAmount"]},{"name": "auditLogArchive","rows": 0,"columns": [- "endDate",- "archivePath",- "startDate",- "sizeBytes",- "id","rowCount",+ "id",+ "createdAt","companyId",- "createdAt"+ "endDate",+ "sizeBytes",+ "startDate",+ "archivePath"]},{"name": "changeOrderRequiredAction","rows": 0,"columns": [- "updatedBy",- "name",- "active",- "createdBy","updatedAt","companyId","createdAt",+ "id","customFields",- "id"+ "updatedBy",+ "active",+ "name",+ "createdBy"]},{@@ -359,6 +343,11 @@"name": "companyAccountsPayableBillingAddress","rows": 0,"columns": [+ "updatedAt",+ "city",+ "addressLine1",+ "addressLine2",+ "postalCode","email","phone","id",@@ -366,12 +355,7 @@"name","updatedBy","fax",- "countryCode",- "updatedAt",- "city",- "addressLine1",- "addressLine2",- "postalCode"+ "countryCode"]},{@@ -381,12 +365,12 @@"updatedAt","city","postalCode",- "addressLine1","addressLine2",+ "addressLine1","state","email",- "phone","id",+ "phone","fax","countryCode","name",@@ -397,66 +381,67 @@"name": "companySettings","rows": 0,"columns": [- "includeMaterialsOnTraveler",- "qualityIssueTarget",- "materialGeneratedIds",- "accountingEnabled",- "returnPickedMaterialTiming",- "accountsPayableAddress",- "inventoryJobCompletedNotificationGroup",- "accountsReceivableAddress",- "gaugeCalibrationExpiredNotificationGroup",- "consoleEnabled",- "digitalQuoteEnabled",- "incompletePickingListPolicy",- "inventoryShelfLife",- "showCustomerReadableId","productLabelSize",- "updateLeadTimesOnReceipt",+ "showCustomerReadableId",+ "plmReleaseControl",+ "id",+ "salesJobCompletedNotificationGroup",+ "autoStartOperationTimer","enforceInspectionFourEyes","requireMfa",- "useMetric",+ "updateLeadTimesOnReceipt","accountsPayableEmail",- "salesJobCompletedNotificationGroup",- "id",- "plmReleaseControl",- "autoStartOperationTimer",- "timeCardEnabled",- "shelfLabelSize",- "showCurrencyTrailingZeros",- "printing",+ "useMetric",+ "returnPickedMaterialTiming",+ "accountingEnabled",+ "accountsReceivableAddress",+ "inventoryJobCompletedNotificationGroup",+ "accountsPayableAddress",+ "includeMaterialsOnTraveler",+ "materialGeneratedIds",+ "qualityIssueTarget",+ "inventoryShelfLife",+ "incompletePickingListPolicy",+ "gaugeCalibrationExpiredNotificationGroup",+ "digitalQuoteEnabled",+ "consoleEnabled",+ "assetTaxDepreciationEnabled",+ "otherDispatchNotificationGroup",+ "allowLowercaseItemIds",+ "supplierQuoteNotificationGroup",+ "assetTaxRate",+ "defaultSupplierCc",+ "rfqReadyNotificationGroup",+ "operationsDispatchNotificationGroup",+ "kanbanOutput",+ "quoteLineCategoryMarkups","defaultCustomerCc",+ "printing",+ "showCurrencyTrailingZeros",+ "shelfLabelSize",+ "timeCardEnabled","accountsReceivableEmail",- "qualityDispatchNotificationGroup",- "showSupplierReadableId",- "samplingStandard",- "maintenanceDispatchNotificationGroup",- "digitalQuoteNotificationGroup",- "purchasePriceUpdateTiming","digitalQuoteIncludesPurchaseOrders",+ "purchasePriceUpdateTiming",+ "digitalQuoteNotificationGroup","autoSelectMaterialWithoutPickingList",- "supplierQuoteNotificationGroup",- "otherDispatchNotificationGroup",- "assetTaxDepreciationEnabled",- "rfqReadyNotificationGroup",- "quoteLineCategoryMarkups",- "kanbanOutput",- "operationsDispatchNotificationGroup",- "defaultSupplierCc",- "assetTaxRate"+ "showSupplierReadableId",+ "qualityDispatchNotificationGroup",+ "maintenanceDispatchNotificationGroup",+ "samplingStandard"]},{"name": "companyUsage","rows": 0,"columns": [- "updatedAt","users",- "companyId",+ "updatedAt","id",- "createdAt",+ "companyId","aiTokens","tasks",+ "createdAt","nextResetDatetime"]},@@ -464,89 +449,88 @@"name": "consumable","rows": 0,"columns": [- "createdAt",- "updatedAt",- "companyId",- "id",- "updatedBy",- "createdBy",- "approvedBy",- "approved","customFields",- "tags"+ "tags",+ "approved",+ "approvedBy",+ "createdBy",+ "updatedBy",+ "id",+ "companyId",+ "updatedAt",+ "createdAt"]},{"name": "contact","rows": 0,"columns": [- "homePhone",- "fax",- "firstName",- "title",- "id",- "workPhone",- "mobilePhone",- "lastName",- "companyId",- "notes",+ "email","isCustomer",- "email"+ "notes",+ "companyId",+ "lastName",+ "mobilePhone",+ "workPhone",+ "id",+ "title",+ "firstName",+ "fax",+ "homePhone"]},{"name": "costCenter","rows": 0,"columns": [+ "createdBy","updatedBy",- "companyId","parentCostCenterId",- "createdBy",- "updatedAt",- "ownerId",- "name",+ "companyId","createdAt",+ "customFields","id",- "customFields"+ "ownerId",+ "updatedAt",+ "name"]},{"name": "currency","rows": 0,"columns": [- "exchangeRate",- "updatedBy",- "tags",- "historicalExchangeRate",- "code",- "customFields",- "createdAt",- "id",- "decimalPlaces","updatedAt","companyGroupId","createdBy",- "active"+ "active",+ "createdAt",+ "id",+ "decimalPlaces",+ "code",+ "customFields",+ "updatedBy",+ "historicalExchangeRate",+ "tags"]},{"name": "customField","rows": 0,"columns": [- "required",+ "updatedBy",+ "dataTypeId",+ "active","sortOrder",+ "required","table",- "active",- "dataTypeId",- "updatedBy",- "tags",- "name",- "companyId",- "createdBy",+ "listOptions","createdAt","id","updatedAt",- "listOptions"+ "companyId",+ "createdBy",+ "name",+ "tags"]},{@@ -554,191 +538,191 @@"rows": 0,"columns": ["createdBy",- "createdAt",- "companyId","updatedAt",- "id",- "tags",+ "companyId",+ "createdAt","updatedBy",- "name",- "customFields"+ "tags",+ "id",+ "customFields",+ "name"]},{"name": "customerType","rows": 0,"columns": [- "updatedBy",- "companyId",- "protected",- "createdAt",- "tags",- "updatedAt",- "name","createdBy","id",- "customFields"+ "customFields",+ "updatedAt",+ "tags",+ "name",+ "createdAt",+ "updatedBy",+ "companyId",+ "protected"]},{"name": "department","rows": 0,"columns": [- "tags",- "updatedAt",- "name",- "createdAt",- "customFields",- "id",+ "createdBy","updatedBy",- "parentDepartmentId","companyId",- "createdBy"+ "parentDepartmentId",+ "createdAt",+ "id",+ "customFields",+ "tags",+ "updatedAt",+ "name"]},{"name": "depreciationRun","rows": 0,"columns": [- "companyId",- "status",- "periodEnd",- "postedAt",+ "createdBy",+ "id",+ "postedBy",+ "depreciationRunId","updatedBy","createdAt",- "depreciationRunId",- "postedBy",- "id",- "createdBy"+ "postedAt",+ "periodEnd",+ "status",+ "companyId"]},{"name": "dimension","rows": 0,"columns": [- "name",- "updatedAt",- "createdAt",- "id",- "updatedBy",- "required",+ "active","companyGroupId","entityType","createdBy",- "active"+ "id",+ "updatedBy",+ "required",+ "name",+ "createdAt",+ "updatedAt"]},{"name": "dimensionValue","rows": 0,"columns": [- "dimensionId",- "updatedAt","id","createdAt",- "companyGroupId",+ "dimensionId",+ "updatedAt",+ "createdBy","name",- "updatedBy",- "createdBy"+ "companyGroupId",+ "updatedBy"]},{"name": "document","rows": 0,"columns": [- "path",- "createdAt",- "sourceDocument",- "active",- "readGroups",- "companyId",- "id",- "writeGroups","description",- "updatedBy","name",+ "updatedBy","type","createdBy","size","sourceDocumentId",- "updatedAt"+ "updatedAt",+ "sourceDocument",+ "path",+ "createdAt",+ "readGroups",+ "active",+ "id",+ "writeGroups",+ "companyId"]},{"name": "documentExtraction","rows": 0,"columns": [- "filteredData",- "id",- "createdBy",- "documentType",- "updatedBy",- "companyId",- "extractedData",- "error",- "storagePath","createdAt",- "sourceDocument",- "updatedAt",+ "storagePath",+ "status","sourceDocumentId",- "status"+ "updatedAt",+ "sourceDocument",+ "documentType",+ "createdBy",+ "id",+ "filteredData",+ "error",+ "extractedData",+ "companyId",+ "updatedBy"]},{"name": "documentFavorite","rows": 0,- "columns": ["userId", "documentId"]+ "columns": ["documentId", "userId"]},{"name": "documentLabel","rows": 0,- "columns": ["userId", "documentId", "label", "companyId"]+ "columns": ["userId", "documentId", "companyId", "label"]},{"name": "documentSection","rows": 0,"columns": [- "companyId",- "updatedAt",- "createdAt",- "id",- "updatedBy",- "config",+ "content","placement","name","createdBy",- "content"+ "id",+ "updatedBy",+ "config",+ "companyId",+ "updatedAt",+ "createdAt"]},{"name": "documentTemplate","rows": 0,"columns": [- "documentType",- "formatVersion",- "settings",- "blocks",- "updatedBy",- "updatedAt",- "companyId",- "headerSectionId","createdBy",- "footerSectionId",- "id",+ "headerSectionId",+ "companyId",+ "updatedAt",+ "theme","createdAt",- "theme"+ "id",+ "footerSectionId",+ "settings",+ "formatVersion",+ "documentType",+ "updatedBy",+ "blocks"]},{"name": "documentTransaction","rows": 0,"columns": [- "type",- "userId",- "createdAt","documentId","id",- "companyId"+ "companyId",+ "userId",+ "type",+ "createdAt"]},{@@ -751,333 +735,318 @@"createdAt","name","updatedAt",- "id"- ]- },- {- "name": "employee",- "rows": 0,- "columns": ["companyId", "id", "employeeTypeId", "active", "pin"]- },- {- "name": "employeeAbility",- "rows": 0,- "columns": [- "lastTrainingDate",- "active",- "abilityId",- "trainingCompleted",- "id",- "trainingDays",- "employeeId",- "companyId"+ "id"]},+ {+ "name": "employee",+ "rows": 0,+ "columns": ["companyId", "id", "active", "employeeTypeId", "pin"]+ },{"name": "employeeTypePermission","rows": 0,"columns": [- "view",- "employeeTypeId",- "updatedAt",- "module","update",- "createdAt",+ "create","delete",- "create"+ "createdAt",+ "employeeTypeId",+ "view",+ "module",+ "updatedAt"]},{"name": "eventSystemSubscription","rows": 0,"columns": [+ "table",+ "companyId",+ "handlerType",+ "operations","name",- "active","config",- "createdAt",+ "active","id",- "filter",- "companyId",- "table",- "handlerType",- "operations"+ "createdAt",+ "filter"]},{- "name": "exchangeRateHistory",+ "name": "exchangeRateOverride","rows": 0,"columns": ["createdBy",- "id",- "updatedAt",- "updatedBy","currencyCode",- "companyGroupId",+ "rate",+ "updatedBy",+ "id","createdAt",- "effectiveDate",- "rate"+ "companyId",+ "updatedAt"]},{"name": "externalIntegrationMapping","rows": 0,"columns": [- "entityType",- "companyId",- "createdAt",- "lastSyncedAt","updatedAt","id","remoteUpdatedAt","allowDuplicateExternalId",+ "companyId",+ "entityType",+ "createdAt",+ "lastSyncedAt",+ "externalId",+ "createdBy","integration","entityId","updatedBy",- "metadata",- "createdBy",- "externalId"+ "metadata"]},{"name": "fiscalYearSettings","rows": 0,- "columns": ["taxStartMonth", "updatedBy", "startMonth", "companyId"]+ "columns": ["startMonth", "companyId", "taxStartMonth", "updatedBy"]},{"name": "fixedAssetClass","rows": 0,"columns": [- "accumulatedDepreciationAccountId",- "customFields",- "writeOffAccountId",- "macrsPropertyClass",- "taxDepreciationMethod","name",- "residualValuePercent",- "gainOnDisposalAccountId",- "id",- "depreciationExpenseAccountId",+ "taxDepreciationMethod",+ "macrsPropertyClass",+ "writeOffAccountId",+ "customFields",+ "accumulatedDepreciationAccountId","writeDownAccountId",- "updatedBy",- "assetAccountId",- "depreciationMethod",+ "depreciationExpenseAccountId",+ "id",+ "gainOnDisposalAccountId",+ "residualValuePercent",+ "bonusDepreciationPercent",+ "companyId","description","taxUsefulLifeMonths",- "companyId",- "bonusDepreciationPercent",- "createdBy",- "taxResidualValuePercent",- "macrsConvention",- "updatedAt",- "usefulLifeMonths",+ "depreciationMethod",+ "assetAccountId",+ "updatedBy",+ "lossOnDisposalAccountId","createdAt",- "lossOnDisposalAccountId"+ "usefulLifeMonths",+ "updatedAt",+ "macrsConvention",+ "createdBy",+ "taxResidualValuePercent"]},{"name": "gaugeType","rows": 0,"columns": [- "name",- "updatedBy",- "id",- "createdBy","customFields","companyId","updatedAt",- "createdAt"+ "createdAt",+ "name",+ "updatedBy",+ "id",+ "createdBy"]},{"name": "group","rows": 0,"columns": [- "isEmployeeTypeGroup",- "companyId",- "isIdentityGroup",- "isCustomerTypeGroup",+ "updatedAt","isSupplierOrgGroup","id",- "updatedAt","isCustomerOrgGroup","name",+ "createdAt","isSupplierTypeGroup",- "createdAt"+ "isEmployeeTypeGroup",+ "companyId",+ "isIdentityGroup",+ "isCustomerTypeGroup"]},{"name": "holiday","rows": 0,"columns": [- "updatedBy",+ "createdAt",+ "date",+ "companyId","customFields",+ "updatedBy","name","createdBy",- "updatedAt",- "id","tags",- "createdAt",- "date",- "companyId"+ "id",+ "updatedAt"]},{"name": "implementationCheckState","rows": 0,"columns": [- "createdAt",- "kind",- "itemKey",- "value",- "updatedBy",- "companyId","createdBy","id",- "updatedAt"+ "updatedAt",+ "updatedBy",+ "companyId",+ "value",+ "createdAt",+ "kind",+ "itemKey"]},{"name": "implementationFieldValue","rows": 0,"columns": [- "id",- "createdAt",- "companyId",- "updatedAt","createdBy","value","fieldKey",- "updatedBy"+ "updatedBy",+ "id",+ "createdAt",+ "companyId",+ "updatedAt"]},{"name": "implementationRow","rows": 0,"columns": [- "sortOrder",- "payload",- "collection",- "createdAt",- "id",- "updatedAt","createdBy",+ "updatedAt",+ "id",+ "updatedBy","companyId",- "updatedBy"+ "sortOrder",+ "createdAt",+ "collection",+ "payload"]},{"name": "invite","rows": 0,"columns": [- "companyId",- "acceptedAt",- "id",- "updatedBy",- "createdAt","revokedAt",+ "createdAt","attestedAt","code",- "role",- "attestedBy",+ "companyId",+ "updatedBy",+ "id",+ "acceptedAt","createdBy",+ "permissions","email",- "permissions"+ "role",+ "attestedBy"]},{"name": "itarCertification","rows": 0,"columns": [- "docHash",- "ipAddress",- "complianceContact",- "id",- "certifiedAt",- "title",- "companyId",- "expiresAt",- "updatedBy",+ "fullLegalName",+ "type",+ "createdBy",+ "userId","updatedAt","createdAt","userAgent","docVersion",- "fullLegalName",- "createdBy",- "type",- "userId"+ "title",+ "certifiedAt",+ "updatedBy",+ "companyId",+ "expiresAt",+ "docHash",+ "complianceContact",+ "id",+ "ipAddress"]},{"name": "itemPostingGroup","rows": 0,"columns": [- "active",+ "companyId","description",+ "active","createdAt",- "companyId",- "name",- "updatedBy",- "customFields",- "id","updatedAt",+ "id","tags",- "createdBy"+ "createdBy",+ "name",+ "updatedBy",+ "customFields"]},{"name": "itemStockQuantities","rows": 0,- "columns": ["quantityOnHand", "locationId", "companyId", "itemId"]+ "columns": ["itemId", "companyId", "quantityOnHand", "locationId"]},{"name": "journal","rows": 0,"columns": [- "customFields",+ "postingDate",+ "reversalOfId",+ "postedBy",+ "updatedAt",+ "eliminationKind",+ "updatedBy","postedAt","accountingPeriodId","companyId",- "updatedBy",- "eliminationKind",- "updatedAt",- "postedBy",- "reversalOfId",- "postingDate",- "tags",- "status",- "createdBy",- "description",- "reversedById",- "createdAt",+ "customFields",+ "sourceType","journalEntryId","id",- "sourceType"+ "createdAt",+ "reversedById",+ "description",+ "createdBy",+ "status",+ "tags"]},{"name": "journalLine","rows": 0,"columns": [- "accountId",+ "documentId",+ "journalLineReference",+ "tags",+ "companyId",+ "journalId",+ "quantity",+ "id",+ "externalDocumentId",+ "documentLineReference",+ "documentType",+ "description",+ "createdAt",+ "updatedBy",+ "updatedAt","createdBy","customFields",- "accrual",- "intercompanyPartnerId",+ "accountId","amount",- "documentType",- "updatedAt",- "updatedBy",- "createdAt",- "description",- "quantity",- "documentLineReference",- "externalDocumentId",- "id",- "journalLineReference",- "documentId",- "journalId",- "companyId",- "tags"+ "intercompanyPartnerId",+ "accrual"]},{@@ -1088,12 +1057,12 @@"status","sourceJournalLineId","amount",- "targetCompanyId","sourceCompanyId","createdAt",+ "targetCompanyId","targetJournalLineId",- "id","description",+ "id","documentId","currencyCode","documentType",@@ -1105,108 +1074,109 @@"name": "intercompanyEliminationLine","rows": 0,"columns": [- "journalLineId",- "updatedBy",- "intercompanyTransactionId",- "role",- "amount",- "createdAt","quantity","id",+ "createdAt","accountId","updatedAt","companyId",+ "itemId","createdBy",- "itemId"+ "journalLineId",+ "updatedBy",+ "intercompanyTransactionId",+ "role",+ "amount"]},{"name": "journalLineDimension","rows": 0,"columns": [+ "journalLineId","id","createdAt",- "journalLineId",- "companyId",+ "valueId","dimensionId",- "valueId"+ "companyId"]},{"name": "location","rows": 0,"columns": [- "countryCode",- "latitude","updatedAt","name","createdBy",- "stateProvince",- "id",+ "countryCode",+ "latitude","timezone",+ "id","longitude",- "postalCode",- "addressLine2",+ "stateProvince","addressLine1","createdAt",+ "addressLine2","tags","code",- "customFields",- "updatedBy",+ "postalCode","companyId",- "city"+ "requiresStaffing",+ "city",+ "customFields",+ "updatedBy"]},{"name": "fixedAsset","rows": 0,"columns": [- "name",- "fixedAssetClassId",- "macrsPropertyClass",- "acquisitionDate",- "depreciationStartDate",- "createdAt",- "locationId",- "status",- "notes",- "assetLifetimeUsage",- "accumulatedDepreciation",- "updatedBy",- "taxUsefulLifeMonths",- "description",- "saleProceeds",- "acquisitionCost",- "macrsConvention",- "accumulatedTaxDepreciation",- "bonusDepreciationPercent",- "fixedAssetId",- "taxResidualValuePercent","depreciationMethod","updatedAt","createdBy","customFields","residualValuePercent","disposalDate",+ "bonusDepreciationPercent",+ "fixedAssetId",+ "taxResidualValuePercent",+ "serialNumber",+ "disposalMethod","id","usefulLifeMonths","companyId","taxDepreciationMethod",- "serialNumber",- "disposalMethod"+ "createdAt",+ "locationId",+ "status",+ "notes",+ "name",+ "fixedAssetClassId",+ "macrsPropertyClass",+ "acquisitionDate",+ "depreciationStartDate",+ "saleProceeds",+ "acquisitionCost",+ "macrsConvention",+ "accumulatedTaxDepreciation",+ "assetLifetimeUsage",+ "accumulatedDepreciation",+ "updatedBy",+ "taxUsefulLifeMonths",+ "description"]},{"name": "depreciationRunLine","rows": 0,"columns": [+ "companyId","fixedAssetId","amount",- "companyId","taxAmount","depreciationRunId",- "id",- "journalId"+ "journalId",+ "id"]},{@@ -1220,8 +1190,8 @@"journalId","createdAt","fixedAssetId",- "updatedBy","saleProceeds",+ "updatedBy","gainLoss","disposalMethod","disposalDate"@@ -1231,167 +1201,167 @@"name": "fixedAssetUsageLog","rows": 0,"columns": [- "fixedAssetId",+ "createdAt",+ "periodEnd",+ "periodStart",+ "unitsProduced","createdBy",- "updatedBy",- "id",+ "fixedAssetId","companyId",- "periodStart",- "periodEnd",- "createdAt",- "unitsProduced"+ "id",+ "updatedBy"]},{"name": "inventoryCount","rows": 0,"columns": [- "customFields",- "companyId",- "createdAt",- "snapshotAt",- "postedBy",- "notes",- "id",- "postedAt","isBlind",- "inventoryCountId",- "updatedBy",- "locationId",- "scope",- "createdBy",+ "postedAt",+ "id",+ "notes",+ "postedBy",+ "snapshotAt",+ "createdAt",+ "companyId",+ "customFields",+ "updatedAt","status",- "updatedAt"+ "createdBy",+ "scope",+ "locationId",+ "inventoryCountId",+ "updatedBy"]},{"name": "maintenanceFailureMode","rows": 0,"columns": [- "companyId",- "createdBy",- "updatedAt",- "createdAt",- "name","type",+ "name",+ "updatedBy","id",- "updatedBy"+ "updatedAt",+ "companyId",+ "createdBy",+ "createdAt"]},{"name": "materialForm","rows": 0,"columns": [- "updatedAt",+ "updatedBy",+ "customFields",+ "companyId",+ "createdBy","code",+ "updatedAt","name","createdAt",- "tags","id",- "updatedBy",- "companyId",- "customFields",- "createdBy"+ "tags"]},{"name": "materialDimension","rows": 0,- "columns": ["id", "materialFormId", "companyId", "name", "isMetric"]+ "columns": ["isMetric", "name", "companyId", "materialFormId", "id"]},{"name": "materialSubstance","rows": 0,"columns": [+ "updatedBy","customFields","companyId",- "updatedBy","createdBy",- "name",- "updatedAt","code",+ "updatedAt",+ "name",+ "createdAt","id",- "tags",- "createdAt"+ "tags"]},{"name": "materialFinish","rows": 0,- "columns": ["materialSubstanceId", "companyId", "name", "id"]+ "columns": ["companyId", "materialSubstanceId", "id", "name"]},{"name": "materialGrade","rows": 0,- "columns": ["name", "companyId", "id", "materialSubstanceId"]+ "columns": ["id", "materialSubstanceId", "companyId", "name"]},{"name": "materialType","rows": 0,"columns": [- "materialSubstanceId",- "code",- "materialFormId",- "name","id",- "companyId"+ "companyId",+ "name",+ "materialFormId",+ "code",+ "materialSubstanceId"]},{"name": "material","rows": 0,"columns": [- "dimensionId",- "finishId",- "materialSubstanceId",- "updatedBy",- "materialFormId",- "gradeId",- "createdBy",- "tags",- "materialTypeId",- "updatedAt",+ "companyId",+ "approvedBy",+ "id","createdAt","customFields","approved",- "companyId",- "id",- "approvedBy"+ "createdBy",+ "gradeId",+ "tags",+ "updatedAt",+ "materialTypeId",+ "dimensionId",+ "finishId",+ "materialFormId",+ "updatedBy",+ "materialSubstanceId"]},{"name": "membership","rows": 0,- "columns": ["memberGroupId", "memberUserId", "id", "groupId"]+ "columns": ["memberUserId", "memberGroupId", "groupId", "id"]},{"name": "modelUpload","rows": 0,"columns": [- "glbPath",- "thumbnailPath",- "name",- "createdAt",- "optimizedSize",- "updatedAt",- "createdBy",- "id",- "updatedBy",- "originalSize",+ "processingError",+ "optimizeStatus",+ "originalPath",+ "graphPath",+ "optimizeError",+ "autodeskUrn",+ "optimizedModelPath",+ "optimizedAt",+ "companyId",+ "modelPath","size","processingStatus",- "modelPath","processedAt","componentCount",- "companyId",- "optimizedAt",- "optimizeError",- "autodeskUrn",- "optimizedModelPath",- "processingError",- "optimizeStatus",- "graphPath",- "originalPath"+ "originalSize",+ "id",+ "createdBy",+ "updatedBy",+ "createdAt",+ "optimizedSize",+ "updatedAt",+ "glbPath",+ "thumbnailPath",+ "name"]},{@@ -1403,11 +1373,11 @@"status","kind","stats",- "updatedAt","id","createdBy",- "createdAt",+ "updatedAt","companyId",+ "createdAt","modelUploadId"]},@@ -1415,49 +1385,56 @@"name": "noQuoteReason","rows": 0,"columns": [- "updatedAt",+ "createdBy","createdAt","companyId",- "createdBy",- "customFields",- "name",+ "updatedAt",+ "id","updatedBy",- "id"+ "name",+ "customFields"]},{"name": "nonConformanceRequiredAction","rows": 0,"columns": [- "createdBy",- "id",- "systemType",- "updatedBy",- "companyId","createdAt","updatedAt",+ "name","active",- "name"+ "createdBy",+ "systemType",+ "id",+ "updatedBy",+ "companyId"]},{"name": "nonConformanceType","rows": 0,"columns": [- "updatedAt","id",- "customFields",+ "updatedAt","name",+ "customFields","createdBy",- "updatedBy","createdAt",- "companyId"+ "companyId",+ "updatedBy"]},{"name": "nonConformanceWorkflow","rows": 0,"columns": [+ "priority",+ "companyId",+ "updatedAt",+ "content",+ "description",+ "createdBy",+ "requiredActionIds","id","approvalRequirements","tags",@@ -1465,134 +1442,127 @@"updatedBy","createdAt","name",- "active",- "priority",- "companyId",- "updatedAt",- "content",- "description",- "createdBy",- "requiredActionIds"+ "active"]},{"name": "nonConformance","rows": 0,"columns": [- "id",- "updatedBy",- "nonConformanceWorkflowId",- "status",- "createdBy",- "dueDate",- "nonConformanceId",- "locationId",- "requiredActionIds",- "approvalRequirements",- "createdAt",- "tags","assignee","content","source",+ "tags","updatedAt","closeDate",- "openDate","customFields",+ "openDate",+ "quantity","description","nonConformanceTypeId","name",- "quantity","companyId",- "priority"+ "priority",+ "updatedBy",+ "nonConformanceWorkflowId",+ "id",+ "createdBy",+ "status",+ "nonConformanceId",+ "locationId",+ "dueDate",+ "approvalRequirements",+ "createdAt",+ "requiredActionIds"]},{"name": "changeOrder","rows": 0,"columns": [+ "type",+ "changeOrderTypeId",+ "id",+ "openDate",+ "priority",+ "nonConformanceId",+ "updatedBy",+ "sourceId",+ "changeOrderId",+ "requiredActionIds","assignee",- "createdAt","sourceType",+ "createdAt",+ "createdBy","dueDate","companyId","description",- "createdBy","status","updatedAt",- "customFields",- "tags",- "name","approvalRequirements",+ "name","reasonForChange",- "type",- "openDate",- "changeOrderTypeId",- "id",- "nonConformanceId",- "updatedBy",- "priority",- "changeOrderId",- "requiredActionIds",- "sourceId"+ "customFields",+ "tags"]},{"name": "changeOrderActionTask","rows": 0,"columns": [- "status",- "name",- "updatedAt",- "assignee",- "dueDate","createdAt",+ "dueDate","updatedBy",- "actionTypeId",- "createdBy",+ "updatedAt",+ "name",+ "status",+ "assignee",+ "companyId",+ "sortOrder",+ "id",+ "completedDate","changeOrderId",- "notes",+ "createdBy",+ "actionTypeId","tags",- "id",- "sortOrder",- "companyId",- "completedDate"+ "notes"]},{"name": "nonConformanceApprovalTask","rows": 0,"columns": [- "createdAt",- "dueDate",- "updatedBy","status","updatedAt","approvalType","assignee",- "id",- "sortOrder",- "companyId",- "completedDate",+ "createdAt",+ "dueDate",+ "updatedBy","nonConformanceId","createdBy",+ "tags","notes",- "tags"+ "companyId",+ "id",+ "sortOrder",+ "completedDate"]},{"name": "nonConformanceReviewer","rows": 0,"columns": [- "updatedAt",- "createdAt","title",- "assignee",- "updatedBy",+ "createdAt",+ "updatedAt","createdBy","id",- "companyId",+ "updatedBy",+ "assignee","status","nonConformanceId",+ "companyId","notes","completedDate"]@@ -1601,200 +1571,169 @@"name": "note","rows": 0,"columns": [- "active",- "noteRichText",- "note",- "createdAt",- "id",- "updatedAt",- "companyId","documentId","updatedBy",- "createdBy"+ "createdBy",+ "updatedAt",+ "id",+ "companyId",+ "note",+ "noteRichText",+ "createdAt",+ "active"]},{"name": "notification","rows": 0,"columns": [- "seenAt",- "userId",+ "description",+ "digestedInto",+ "companyId",+ "topic",+ "createdAt",+ "readAt",+ "event","from","documentId",- "id",- "documentType",- "payload",+ "userId",+ "seenAt","title",- "topic",- "companyId",- "digestedInto",- "description",- "event",- "readAt",- "createdAt"+ "documentType",+ "id",+ "payload"]},{"name": "notificationDelivery","rows": 0,"columns": [- "documentId","lastDeliveryId",- "event","userId",+ "event",+ "documentId",+ "lastDeliveredAt",+ "companyId","successCount",- "id","createdAt",- "lastDeliveredAt",- "companyId"+ "id"]},{"name": "notificationPreference","rows": 0,"columns": [+ "enabled",+ "id",+ "userId","topic","updatedAt",- "channel","companyId",- "enabled",- "id",- "userId"+ "channel"]},{"name": "oauthCode","rows": 0,"columns": [- "scope",+ "redirectUri","id","codeChallenge",- "redirectUri",- "code",- "codeChallengeMethod",+ "scope","expiresAt",+ "codeChallengeMethod",+ "code","companyId",+ "createdAt","userId",- "clientId",- "createdAt"+ "clientId"]},{- "name": "onshapeSyncRun",+ "name": "part","rows": 0,"columns": [- "cancelledBy",- "totalRevisions",- "unmatchedOverflow",- "finishedAt",- "skippedNonModel",- "error",- "createdBy",- "revisionsScanned",+ "companyId","createdAt",- "ambiguousOverflow",- "ambiguousReleases",- "status",- "failed",- "startedAt",- "updatedAt",- "pagesProcessed",- "skippedAlreadySynced",- "synced",+ "customFields",+ "toDate","id",- "updatedBy",- "skippedNoItem",- "matched",- "skippedTooLarge",- "companyId",- "unmatchedReleases"- ]- },- {- "name": "part",- "rows": 0,- "columns": ["createdBy",- "id","updatedBy",- "toDate",- "customFields",- "companyId",- "createdAt",- "fromDate",- "updatedAt",- "tags",+ "approvedBy","approved",- "approvedBy"+ "tags",+ "fromDate",+ "updatedAt"]},{"name": "paymentTerm","rows": 0,"columns": [- "daysDiscount",- "daysDue",- "tags","active",- "discountPercentage",+ "tags",+ "daysDue",+ "daysDiscount","updatedBy",- "customFields",- "name",- "createdBy",+ "discountPercentage","companyId",- "updatedAt",- "id",+ "createdBy",+ "name",+ "customFields",+ "calculationMethod","createdAt",- "calculationMethod"+ "id",+ "updatedAt"]},{"name": "periodCloseTaskDefinition","rows": 0,"columns": [- "createdBy",- "autoCheckKey",- "updatedAt","taskType",- "name","updatedBy",+ "name","required",- "id",- "active",- "defaultAssigneeId",- "sortOrder",+ "autoCheckKey",+ "createdBy",+ "updatedAt","customFields",- "companyId","createdAt",+ "companyId","severity",- "isSystem"+ "isSystem",+ "id",+ "active",+ "defaultAssigneeId",+ "sortOrder"]},{"name": "periodCloseTask","rows": 0,"columns": [- "taskType",- "id",- "required","status",- "sortOrder",- "severity",- "evidenceJournalId",- "companyId",+ "required",+ "id",+ "taskType","completedBy",- "notes",- "skippedReason",- "updatedAt",- "updatedBy",- "assigneeId",+ "companyId",+ "evidenceJournalId",+ "severity",+ "sortOrder","name",- "autoCheckKey",- "definitionId",- "accountingPeriodId",- "completedAt",+ "assigneeId",+ "updatedBy",+ "updatedAt",+ "skippedReason",+ "notes",+ "createdAt","createdBy",- "createdAt"+ "completedAt",+ "accountingPeriodId",+ "definitionId",+ "autoCheckKey"]},{@@ -1802,64 +1741,64 @@"rows": 0,"columns": ["notes",- "status","locationId",+ "status","assignee","updatedAt",- "createdAt","companyId",+ "createdAt","customFields","pickingListId","dueDate",- "updatedBy",+ "id","createdBy",- "id"+ "updatedBy"]},{"name": "pricingRule","rows": 0,"columns": [- "itemIds",- "id",- "customerIds",- "priority",- "name",- "validFrom",- "customerTypeIds",- "maxQuantity",- "createdAt","itemPostingGroupId",+ "createdAt","amount","updatedAt","active","updatedBy","companyId","createdBy",- "amountType","ruleType","validTo",- "minQuantity"+ "amountType",+ "minQuantity",+ "itemIds",+ "customerIds",+ "id",+ "priority",+ "name",+ "validFrom",+ "customerTypeIds",+ "maxQuantity"]},{"name": "printJob","rows": 0,"columns": [- "description","sourceDocumentId",+ "description",+ "updatedAt","companyId","attempts",- "updatedAt","printerUrl",- "origin","id","sourceDocumentReadableId",+ "origin","sourceDocument",- "completedAt","contentType","status","createdBy",+ "completedAt","updatedBy","createdAt","error",@@ -1870,36 +1809,67 @@"name": "printerRoute","rows": 0,"columns": [- "format",- "locationId",- "name",- "printerUrl",+ "updatedAt",+ "apiKey",+ "companyId",+ "mediaSizeId","templateId","createdAt","id",- "mediaSizeId",- "companyId",- "updatedAt",- "apiKey"+ "printerUrl",+ "locationId",+ "name",+ "format"]},{"name": "process","rows": 0,"columns": [- "createdBy",- "updatedAt",- "id",- "tags",- "updatedBy",- "processType","active","name",+ "processType",+ "updatedBy",+ "tags",+ "updatedAt",+ "id",+ "createdBy",+ "defaultStandardFactor",+ "requiresAbility",+ "companyId",+ "createdAt","customFields",- "completeAllOnScan",+ "completeAllOnScan"+ ]+ },+ {+ "name": "ability",+ "rows": 0,+ "columns": [+ "active",+ "recertifyEveryDays","createdAt",- "defaultStandardFactor",- "companyId"+ "curve",+ "shadowWeeks",+ "companyId",+ "updatedAt",+ "id",+ "processId",+ "createdBy",+ "updatedBy",+ "name"+ ]+ },+ {+ "name": "employeeAbility",+ "rows": 0,+ "columns": [+ "companyId",+ "employeeId",+ "id",+ "expiresAt",+ "abilityId",+ "lastTrainingDate"]},{@@ -1910,10 +1880,10 @@"tags","description","content",- "updatedAt","version",- "name",+ "updatedAt","updatedBy",+ "name","createdAt","assignee","createdBy",@@ -1926,15 +1896,15 @@"name": "procedureParameter","rows": 0,"columns": [- "createdBy",- "key",- "value",- "companyId",- "updatedAt",- "procedureId","createdAt",+ "id","updatedBy",- "id"+ "updatedAt",+ "procedureId",+ "companyId",+ "createdBy",+ "value",+ "key"]},{@@ -1942,22 +1912,22 @@"rows": 0,"columns": ["expirationDate",- "createdAt","revisionId",+ "createdAt","status",- "createdBy","updatedBy",- "employeeId",+ "createdBy","companyId",- "internalNotes",+ "employeeId","locationId",- "updatedAt",- "customFields",+ "internalNotes","rfqId",+ "customFields",+ "updatedAt","rfqDate",+ "assignee","notes",- "id",- "assignee"+ "id"]},{@@ -1969,120 +1939,109 @@"name": "qualityDocument","rows": 0,"columns": [+ "status",+ "updatedBy","assignee","version","description",- "updatedBy",- "status",- "createdBy",- "companyId",- "name",- "tags","content","updatedAt","id",- "createdAt"+ "createdAt",+ "createdBy",+ "companyId",+ "tags",+ "name"]},{"name": "reportPin","rows": 0,"columns": [- "createdBy","updatedBy",- "companyId","pinned",- "createdAt",- "reportKey",+ "companyId",+ "createdBy","updatedAt",- "userId"+ "userId",+ "createdAt",+ "reportKey"]},{"name": "reportView","rows": 0,"columns": [- "config",- "name",- "reportKey",- "createdBy",+ "visibility","id","updatedBy",- "visibility",- "companyId",+ "createdAt","updatedAt",- "createdAt"+ "companyId",+ "config",+ "createdBy",+ "name",+ "reportKey"]},{"name": "scrapReason","rows": 0,"columns": [- "createdBy","updatedAt",- "createdAt","companyId",- "updatedBy",- "id",+ "createdAt",+ "createdBy","customFields",- "name"+ "name",+ "updatedBy",+ "id"]},{"name": "searchIndexRegistry","rows": 0,- "columns": ["lastRebuiltAt", "companyId", "createdAt"]+ "columns": ["lastRebuiltAt", "createdAt", "companyId"]},{"name": "sequence","rows": 0,"columns": [- "next",- "companyId",- "updatedBy",- "step",- "updatedAt",- "table","suffix","size",+ "name","prefix",- "name"+ "next",+ "updatedBy",+ "companyId",+ "updatedAt",+ "step",+ "table"]},{"name": "service","rows": 0,"columns": [- "approved",- "updatedAt",- "serviceType",- "toDate","approvedBy","createdAt","tags",- "updatedBy",- "companyId",+ "serviceType",+ "updatedAt",+ "approved",+ "toDate","createdBy",- "id","customFields",- "fromDate"+ "id",+ "fromDate",+ "updatedBy",+ "companyId"]},{"name": "shift","rows": 0,"columns": [- "tags",- "saturday",- "locationId",- "updatedBy",- "createdBy",- "endTime",- "startTime",- "companyId",- "updatedAt",- "customFields",- "monday","id","wednesday","friday",@@ -2091,7 +2050,18 @@"name","active","tuesday",- "thursday"+ "thursday",+ "tags",+ "saturday",+ "locationId",+ "updatedBy",+ "createdBy",+ "endTime",+ "companyId",+ "startTime",+ "updatedAt",+ "customFields",+ "monday"]},{@@ -2099,17 +2069,17 @@"rows": 0,"columns": ["title",- "shiftId",- "managerId","companyId",+ "managerId",+ "shiftId",+ "startDate","departmentId",- "updatedBy","id",- "startDate",- "locationId",- "tags",+ "updatedBy","customFields",- "updatedAt"+ "updatedAt",+ "locationId",+ "tags"]},{@@ -2118,37 +2088,53 @@"columns": ["shiftId", "companyId", "employeeId", "id"]},{- "name": "shippingMethod",+ "name": "peopleAbsence","rows": 0,"columns": [- "active",+ "shiftId",+ "date",+ "employeeId","createdBy","id","updatedBy",+ "note",+ "companyId",+ "createdAt",+ "updatedAt"+ ]+ },+ {+ "name": "shippingMethod",+ "rows": 0,+ "columns": ["createdAt","updatedAt",- "tags","name",- "trackingUrl",- "customFields",+ "tags",+ "active",+ "createdBy",+ "id",+ "updatedBy","companyId","carrier",- "carrierAccountId"+ "carrierAccountId",+ "customFields",+ "trackingUrl"]},{"name": "shippingTerm","rows": 0,"columns": [- "updatedBy",- "name",- "createdBy",- "tags",- "id",+ "createdAt","updatedAt",- "active","companyId",- "createdAt"+ "active",+ "createdBy",+ "id",+ "tags",+ "updatedBy",+ "name"]},{@@ -2156,166 +2142,200 @@"rows": 0,"columns": ["createdAt",- "documentId","documentType",+ "documentId","channelId",- "updatedBy","createdBy",+ "updatedBy","companyId","threadTs",+ "updatedAt",+ "id"+ ]+ },+ {+ "name": "ssoConnection",+ "rows": 0,+ "columns": [+ "createdAt","id",- "updatedAt"+ "updatedAt",+ "active",+ "companyId",+ "createdBy",+ "updatedBy",+ "metadataXml",+ "providerId",+ "metadataUrl",+ "requireSso"+ ]+ },+ {+ "name": "ssoDomain",+ "rows": 0,+ "columns": [+ "status",+ "id",+ "createdAt",+ "updatedAt",+ "createdBy",+ "updatedBy",+ "companyId",+ "verificationToken",+ "verifiedAt",+ "domain",+ "connectionId"]},{"name": "stockTransfer","rows": 0,"columns": [+ "createdAt",+ "status","tags","locationId",- "status",- "createdAt",- "assignee","completedAt",- "stockTransferId",- "customFields",- "createdBy",+ "assignee","updatedBy",- "updatedAt",- "id",+ "createdBy",+ "customFields",+ "stockTransferId",+ "companyId","notes",- "companyId"+ "id",+ "updatedAt"]},{"name": "storageRule","rows": 0,"columns": [+ "conditionAst","filteredItemGroupIds","filteredItemMatchAll","description","customFields","name",- "conditionAst",- "updatedBy",- "message","filteredItemTypes","targetType",+ "updatedBy",+ "message",+ "createdBy",+ "surfaces","companyId","updatedAt","appliesToAll",- "createdBy",- "surfaces",+ "severity","createdAt","id",- "active",- "severity"+ "active"]},{"name": "storageType","rows": 0,"columns": [- "updatedAt","createdBy","companyId",+ "updatedAt","createdAt",- "customFields","name",- "updatedBy",- "id"+ "customFields",+ "id",+ "updatedBy"]},{"name": "suggestion","rows": 0,"columns": [- "userId",- "emoji",- "path","attachmentPath",- "companyId",- "suggestion",- "tags",+ "path",+ "emoji",+ "userId",+ "id","createdAt",- "id"+ "tags",+ "suggestion",+ "companyId"]},{"name": "supplierType","rows": 0,"columns": [- "updatedBy","companyId","protected",+ "updatedBy","createdAt",+ "name","updatedAt","tags",- "name",- "createdBy","id",- "customFields"+ "customFields",+ "createdBy"]},{"name": "tableView","rows": 0,"columns": [+ "sortOrder",+ "columnVisibility",+ "id",+ "sorts","columnPinning","filters","createdAt","name",- "sortOrder",- "id",- "columnVisibility",- "sorts",+ "updatedBy",+ "type",+ "companyId","columnOrder",- "description","table","createdBy",- "updatedBy",- "type",- "companyId"+ "description"]},{"name": "tag","rows": 0,"columns": [- "name",- "updatedBy",- "table","createdBy","createdAt",- "companyId"+ "companyId",+ "updatedBy",+ "name",+ "table"]},{"name": "terms","rows": 0,"columns": [+ "id",+ "purchasingTerms","updatedBy","salesTerms",- "updatedAt",- "id",- "purchasingTerms"+ "updatedAt"]},{"name": "timeCardEntry","rows": 0,"columns": [+ "clockOut","autoCloseShiftId",- "companyId","clockIn",- "clockOut",- "updatedBy",- "createdBy",- "employeeId",+ "companyId","note",- "updatedAt",+ "id","createdAt",- "id"+ "updatedAt",+ "createdBy",+ "updatedBy",+ "employeeId"]},{@@ -2338,158 +2358,159 @@"name": "trackedActivity","rows": 0,"columns": [+ "id",+ "createdBy",+ "attributes","type","createdAt","updatedBy",- "createdBy",- "id",- "attributes",- "sourceDocument",+ "sourceDocumentReadableId","sourceDocumentId",- "companyId",- "sourceDocumentReadableId"+ "sourceDocument",+ "companyId"]},{"name": "training","rows": 0,"columns": [- "status",- "tags",- "content","id",- "estimatedDuration",- "type",+ "content",+ "tags",+ "status",+ "updatedAt","name","companyId",- "updatedAt",- "updatedBy",- "createdBy",+ "type",+ "estimatedDuration","assignee","processId",- "frequency",+ "updatedBy",+ "createdBy",+ "version","createdAt","description",- "version"+ "grantsAbilityId",+ "frequency"]},{"name": "trainingAssignment","rows": 0,"columns": [- "createdAt",- "groupIds",- "companyId",- "updatedAt","id","createdBy","trainingId",- "updatedBy"+ "updatedBy",+ "createdAt",+ "groupIds",+ "companyId",+ "updatedAt"]},{"name": "trainingCompletion","rows": 0,"columns": [+ "employeeId",+ "companyId",+ "createdAt",+ "completedAt",+ "trainingAssignmentId","updatedBy","createdBy",- "trainingAssignmentId",- "completedBy","period","updatedAt","id",- "createdAt",- "employeeId",- "companyId",- "completedAt"+ "completedBy"]},{"name": "trainingQuestion","rows": 0,"columns": [+ "type",+ "question",+ "createdAt",+ "options","sortOrder","tolerance","createdBy","updatedBy",- "question",- "createdAt",- "type",- "options",- "correctNumber",- "correctBoolean",- "id",- "required","companyId","trainingId","updatedAt","matchingPairs",- "correctAnswers"+ "correctAnswers",+ "correctNumber",+ "id",+ "correctBoolean",+ "required"]},{- "name": "unitOfMeasure",- "rows": 0,- "columns": [- "createdAt",- "active",- "name",- "companyId",- "updatedBy",- "customFields",+ "name": "unitOfMeasure",+ "rows": 0,+ "columns": ["code",- "createdBy",+ "customFields",+ "updatedBy",+ "tags","id","updatedAt",- "tags"+ "createdBy",+ "active",+ "name",+ "createdAt",+ "companyId"]},{"name": "item","rows": 0,"columns": [+ "notes",+ "defaultMethodType",+ "changeOrderId",+ "description",+ "name",+ "createdBy",+ "assignee",+ "createdAt",+ "revision",+ "updatedAt","thumbnailPath","type",- "revisionStatus","modelUploadId",- "createdAt",- "updatedAt",- "revision",- "createdBy",- "name",- "description",- "assignee",- "defaultMethodType",- "notes",- "changeOrderId",- "unitOfMeasureCode",- "id",- "replenishmentSystem",- "embedding",+ "revisionStatus",+ "itemTrackingType",+ "mpn",+ "sourcingType",+ "trackingMethod",+ "active","updatedBy","companyId","readableId",- "sourcingType",- "mpn",- "itemTrackingType",- "trackingMethod",- "active"+ "replenishmentSystem",+ "embedding",+ "id",+ "unitOfMeasureCode"]},{"name": "assemblyComponentMapping","rows": 0,"columns": [- "updatedAt",- "createdAt",- "modelUploadId",- "companyId","updatedBy","id",- "createdBy",+ "companyId",+ "modelUploadId",+ "updatedAt",+ "createdAt",+ "confidence","geometryHash","itemId",- "confidence"+ "createdBy"]},{@@ -2510,8 +2531,8 @@"tags","assemblyPlanJobId","version",- "createdAt","modelUploadId",+ "createdAt","itemId"]},@@ -2519,139 +2540,139 @@"name": "assemblyInstructionStep","rows": 0,"columns": [- "companyId",- "unitOfMeasureCode",- "instructionText",- "buildWave",- "status",- "listValues",- "assemblyInstructionId",- "componentNodeIds",- "createdBy",- "type",- "updatedBy",- "minValue",- "id",- "required",- "durationSeconds",- "description",- "updatedAt",- "explode",- "camera","sortOrder","parentStepId","fileTypes",- "warnings",- "notes",- "createdAt",- "motion",- "title",+ "camera",+ "explode",+ "updatedAt",+ "durationSeconds",+ "description",+ "planConfidence","fastener","maxValue",- "planConfidence"+ "title",+ "createdAt",+ "motion",+ "notes",+ "warnings",+ "componentNodeIds",+ "assemblyInstructionId",+ "listValues",+ "instructionText",+ "buildWave",+ "status",+ "unitOfMeasureCode",+ "companyId",+ "id",+ "required",+ "updatedBy",+ "minValue",+ "type",+ "createdBy"]},{"name": "assemblyInstructionStepMaterial","rows": 0,"columns": [- "sortOrder",- "createdBy",- "quantity",- "itemId",- "companyId","id","updatedBy",+ "companyId",+ "stepId","createdAt","updatedAt",- "stepId"+ "sortOrder",+ "quantity",+ "itemId",+ "createdBy"]},{"name": "assemblyInstructionStepSlide","rows": 0,"columns": [- "size",- "modelUploadId",- "imagePath",- "updatedBy",- "caption",- "annotations",- "createdBy","stepId","updatedAt",- "sortOrder",+ "createdBy",+ "annotations",+ "createdAt","id","companyId",- "createdAt"+ "sortOrder",+ "modelUploadId",+ "imagePath",+ "size",+ "updatedBy",+ "caption"]},{"name": "assemblyInstructionStepTool","rows": 0,"columns": [- "id",- "updatedBy",- "companyId","stepId","createdAt","updatedAt",- "sortOrder",+ "id",+ "updatedBy",+ "companyId","quantity","itemId",- "createdBy"+ "createdBy",+ "sortOrder"]},{"name": "assemblyUnit","rows": 0,"columns": [- "itemId",- "componentNodeIds",- "name",- "createdBy",+ "companyId","id","updatedBy","sourceGroupId",- "companyId",- "modelUploadId","createdAt",- "updatedAt"+ "updatedAt",+ "modelUploadId",+ "itemId",+ "createdBy",+ "componentNodeIds",+ "name"]},{"name": "batchProperty","rows": 0,"columns": [+ "createdAt",+ "updatedAt",+ "itemId","sortOrder",- "updatedBy","createdBy","id",- "updatedAt",- "createdAt",- "itemId",- "listOptions",+ "updatedBy","companyId","label",- "dataType"+ "dataType",+ "listOptions"]},{"name": "changeOrderSupersession","rows": 0,"columns": [- "updatedBy",- "supersessionMode",- "successorEffectivityDate",- "predecessorItemId",- "successorItemId",- "discontinuationDate",- "updatedAt",- "createdAt",- "id",- "createdBy",+ "changeOrderId","companyId",- "changeOrderId"+ "createdBy",+ "id",+ "createdAt",+ "updatedAt",+ "discontinuationDate",+ "successorItemId",+ "predecessorItemId",+ "successorEffectivityDate",+ "updatedBy",+ "supersessionMode"]},{@@ -2659,10 +2680,10 @@"rows": 0,"columns": ["itemId",- "companyId","id",- "sortOrder",+ "companyId","name",+ "sortOrder","isUngrouped"]},@@ -2670,28 +2691,28 @@"name": "configurationParameter","rows": 0,"columns": [- "updatedAt",- "dataType","label","materialFormFilterId","key","configurationParameterGroupId",- "createdBy",- "companyId",- "id",- "listOptions",+ "updatedAt",+ "dataType","itemId","updatedBy",+ "sortOrder","createdAt",- "sortOrder"+ "companyId",+ "id",+ "createdBy",+ "listOptions"]},{"name": "configurationRule","rows": 0,"columns": [- "itemId","updatedBy",+ "itemId","field","updatedAt","companyId",@@ -2702,91 +2723,91 @@"name": "demandForecast","rows": 0,"columns": [- "periodId",- "forecastQuantity",- "notes",- "forecastMethod",- "updatedBy",- "locationId",- "companyId",- "createdAt",+ "confidence","createdBy","itemId","updatedAt",- "confidence"+ "companyId",+ "createdAt",+ "locationId",+ "updatedBy",+ "forecastMethod",+ "notes",+ "periodId",+ "forecastQuantity"]},{"name": "demandProjection","rows": 0,"columns": [- "updatedBy",- "forecastMethod","notes","forecastQuantity","periodId",+ "forecastMethod",+ "updatedBy",+ "companyId",+ "createdAt",+ "id",+ "locationId","confidence",- "updatedAt","itemId","createdBy",- "createdAt",- "companyId",- "locationId",- "id"+ "updatedAt"]},{- "name": "inspectionDocument",- "rows": 0,- "columns": [- "updatedAt",- "samplingSeverity",- "samplingSampleSize",- "version",- "samplingInspectionLevel",- "createdBy",- "fileName",+ "name": "inspectionDocument",+ "rows": 0,+ "columns": ["drawingNumber",- "partId","updatedBy",- "samplingAql",+ "partId","samplingPercentage",- "storagePath",+ "samplingAql",+ "fileName",+ "samplingInspectionLevel",+ "createdBy",+ "version",+ "samplingSampleSize",+ "updatedAt",+ "samplingSeverity",+ "samplingPlanType",+ "companyId",+ "createdAt",+ "pageCount",+ "defaultPageHeight","id","defaultPageWidth","uploadedBy",- "pageCount",- "defaultPageHeight",- "samplingPlanType",- "createdAt",- "companyId"+ "storagePath"]},{"name": "inspectionFeature","rows": 0,"columns": [- "inspectionDocumentId",- "updatedBy",- "samplingPlanType",- "unit",- "tolerancePlus",- "createdBy",+ "description","toleranceMinus","id",- "description",- "samplingPercentage",- "samplingAql",- "companyId",- "updatedAt",- "pageNumber",- "nominalValue",+ "createdBy",+ "tolerancePlus",+ "unit",+ "samplingPlanType",+ "updatedBy",+ "inspectionDocumentId",+ "type",+ "samplingSeverity",+ "samplingSampleSize",+ "label","createdAt","samplingInspectionLevel",- "label",- "samplingSampleSize",- "type",- "samplingSeverity"+ "nominalValue",+ "updatedAt",+ "companyId",+ "pageNumber",+ "samplingAql",+ "samplingPercentage"]},{@@ -2794,77 +2815,77 @@"rows": 0,"columns": ["regionY",- "updatedBy","companyId",+ "updatedBy","inspectionFeatureId","updatedAt","createdBy","pageNumber",- "xCoordinate","regionWidth",+ "xCoordinate","inspectionDocumentId","createdAt","regionX",- "yCoordinate","regionHeight",- "id"+ "id",+ "yCoordinate"]},{"name": "inventoryCountLine","rows": 0,"columns": [+ "storageUnitId",+ "systemQuantity",+ "id",+ "countedQuantity",+ "readableId",+ "countedAt",+ "companyId",+ "createdAt","createdBy","updatedBy","locationId","countedBy","trackedEntityId",- "inventoryCountId",- "postedItemLedgerId",- "itemId","customFields","updatedAt",- "storageUnitId",- "systemQuantity",- "id",- "readableId",- "countedQuantity",- "createdAt",- "countedAt",- "companyId"+ "inventoryCountId",+ "postedItemLedgerId",+ "itemId"]},{"name": "itemCost","rows": 0,"columns": [- "itemPostingGroupId",- "tags",- "createdBy",- "updatedBy",+ "costIsAdjusted",+ "updatedAt","itemId","createdAt",- "updatedAt",- "costIsAdjusted",- "standardCost",- "costingMethod",- "companyId",+ "updatedBy",+ "createdBy",+ "itemPostingGroupId",+ "tags","customFields",- "unitCost"+ "unitCost",+ "companyId",+ "standardCost",+ "costingMethod"]},{"name": "itemInspectionDocumentAssignment","rows": 0,"columns": [- "updatedAt",- "usage",- "createdAt",- "itemId",+ "createdBy","updatedBy","inspectionDocumentId","companyId",- "createdBy"+ "createdAt",+ "itemId",+ "updatedAt",+ "usage"]},{@@ -2876,17 +2897,17 @@"minimumOrderQuantity","reorderPoint","demandAccumulationSafetyStock",- "itemId","demandAccumulationIncludesInventory",+ "itemId","reorderQuantity","minimumReserveQuantity",- "critical","maximumOrderQuantity","reorderingPolicy",+ "critical","createdAt","updatedBy",- "maximumInventoryQuantity","demandAccumulationPeriod",+ "maximumInventoryQuantity","tags","updatedAt","createdBy",@@ -2898,52 +2919,52 @@"name": "itemSerialSequence","rows": 0,"columns": [- "companyId",- "step",- "createdAt",+ "updatedAt",+ "suffix",+ "itemId",+ "prefix",+ "size","createdBy","id","updatedBy","next",- "itemId",- "prefix",- "size",- "updatedAt",- "suffix"+ "companyId",+ "step",+ "createdAt"]},{"name": "itemShelfLife","rows": 0,"columns": [- "createdAt",- "updatedAt",- "mode",- "companyId",- "itemId",- "updatedBy",- "customFields","createdBy","triggerProcessId","days",+ "calculateFromBom","triggerTiming",- "calculateFromBom"+ "updatedAt",+ "createdAt",+ "mode",+ "companyId",+ "customFields",+ "itemId",+ "updatedBy"]},{"name": "itemSupersession","rows": 0,"columns": [- "createdBy",- "updatedBy","companyId",- "successorEffectivityDate",- "itemId",- "createdAt",+ "updatedBy",+ "createdBy","updatedAt",- "conversionFactor",- "successorItemId",+ "createdAt",+ "itemId",+ "successorEffectivityDate","supersessionMode",+ "successorItemId",+ "conversionFactor","discontinuationDate"]},@@ -2951,6 +2972,12 @@"name": "itemUnitSalePrice","rows": 0,"columns": [+ "allowInvoiceDiscount",+ "tags",+ "currencyCode",+ "salesUnitOfMeasureCode",+ "salesBlocked",+ "updatedAt","companyId","createdAt","customFields",@@ -2958,151 +2985,124 @@"priceIncludesTax","createdBy","itemId",- "updatedBy",- "allowInvoiceDiscount",- "currencyCode",- "tags",- "salesUnitOfMeasureCode",- "salesBlocked",- "updatedAt"+ "updatedBy"]},{"name": "makeMethod","rows": 0,"columns": [- "id",- "tags",- "status",- "updatedAt",- "itemId",- "customFields",- "version",- "changeOrderId",- "createdBy",+ "updatedBy","createdAt","companyId",- "updatedBy"+ "createdBy",+ "changeOrderId",+ "customFields",+ "version",+ "itemId",+ "updatedAt",+ "id",+ "tags",+ "status"]},{"name": "changeOrderAffectedItem","rows": 0,"columns": [- "newItemId",- "id",- "discontinuationDate",- "draftMakeMethodId",+ "updatedAt","changeOrderId","companyId",- "updatedAt",- "successorEffectivityDate","supersessionMode",+ "successorEffectivityDate",+ "discontinuationDate",+ "id",+ "newItemId",+ "draftMakeMethodId",+ "itemId",+ "createdAt",+ "sortOrder",+ "baseMakeMethodId","changeSummary","changeType","updatedBy",- "createdBy",- "sortOrder",- "itemId",- "createdAt",- "baseMakeMethodId"+ "createdBy"]},{"name": "nonConformanceItem","rows": 0,"columns": [- "updatedBy",- "quantity",- "nonConformanceId",- "createdBy",- "disposition",- "id","updatedAt",- "itemId",- "companyId",- "createdAt"- ]- },- {- "name": "onshapeItemSyncState",- "rows": 0,- "columns": [- "partNumber",- "error",- "documentId","companyId",- "releaseState",- "source",- "revision",- "id",- "observedOnly",- "updatedAt",- "skipReason",- "runId",- "documentPath",- "assetKind","itemId",- "versionId","createdAt",- "elementId",- "modelUploadId",- "status",+ "updatedBy",+ "quantity",+ "nonConformanceId","createdBy",- "revisionId",- "updatedBy"+ "id",+ "disposition"]},{"name": "procedureStep","rows": 0,"columns": [- "updatedAt",+ "maxValue",+ "unitOfMeasureCode","companyId","procedureId",- "unitOfMeasureCode",- "maxValue",- "id",- "minValue",- "listValues",+ "updatedAt","sortOrder",- "createdAt",- "name",- "description",+ "listValues",+ "minValue",+ "id","type",- "required",- "fileTypes",+ "description",+ "name",+ "createdAt","createdBy",- "updatedBy"+ "updatedBy",+ "required",+ "fileTypes"]},{"name": "purchasingRfqLine","rows": 0,"columns": [- "inventoryUnitOfMeasureCode",- "createdAt",- "itemId",- "description",- "createdBy",- "updatedBy",- "quantity",- "companyId",- "conversionFactor",- "internalNotes","updatedAt",- "customFields","purchasingRfqId",- "purchaseUnitOfMeasureCode",- "order",+ "customFields",+ "conversionFactor",+ "internalNotes","id",- "externalNotes"+ "order",+ "externalNotes",+ "purchaseUnitOfMeasureCode",+ "description",+ "createdAt",+ "itemId",+ "inventoryUnitOfMeasureCode",+ "companyId",+ "quantity",+ "updatedBy",+ "createdBy"]},{"name": "qualityDocumentStep","rows": 0,"columns": [+ "type",+ "description",+ "createdAt",+ "name",+ "updatedBy",+ "createdBy",+ "fileTypes",+ "required","unitOfMeasureCode","maxValue","updatedAt",@@ -3111,180 +3111,172 @@"sortOrder","id","minValue",- "listValues",- "type",- "description",- "name",- "createdAt",- "updatedBy",- "createdBy",- "fileTypes",- "required"+ "listValues"]},{"name": "riskRegister","rows": 0,"columns": [- "source",- "createdBy",- "notes",- "updatedBy",- "title",- "updatedAt",- "description",- "severity",- "assignee",- "itemId",- "id",- "sourceId","createdAt","companyId","type","status",- "likelihood"+ "likelihood",+ "assignee",+ "itemId",+ "id",+ "sourceId",+ "title",+ "updatedAt",+ "description",+ "severity",+ "source",+ "createdBy",+ "notes",+ "updatedBy"]},{"name": "storageRuleItemAssignment","rows": 0,"columns": [+ "createdBy",+ "companyId",+ "createdAt","ruleId","updatedBy",- "itemId",- "companyId",- "createdBy",- "createdAt"+ "itemId"]},{"name": "trackedEntity","rows": 0,"columns": [- "sourceDocumentReadableId",- "createdAt",- "id",- "readableId",- "companyId",+ "attributes",+ "updatedBy",+ "status",+ "sourceDocument",+ "itemId",+ "sourceDocumentId","createdBy",+ "companyId","quantity","expirationDate",- "itemId",- "sourceDocumentId",- "attributes",- "status",- "updatedBy",- "sourceDocument"+ "sourceDocumentReadableId",+ "readableId",+ "createdAt",+ "id"]},{"name": "nonConformanceItemTrackedEntity","rows": 0,"columns": [- "quantity",- "createdAt",- "trackedEntityId",- "nonConformanceId",+ "createdBy",+ "updatedBy",+ "nonConformanceItemId","companyId","id","updatedAt",- "updatedBy",- "createdBy",- "nonConformanceItemId"+ "createdAt",+ "trackedEntityId",+ "nonConformanceId",+ "quantity"]},{"name": "nonConformanceTrackedEntity","rows": 0,"columns": [- "id",- "createdBy",- "nonConformanceId","updatedBy",- "createdAt",+ "nonConformanceId",+ "createdBy",+ "id",+ "updatedAt","companyId","trackedEntityId",- "updatedAt"+ "createdAt"]},{"name": "trackedActivityInput","rows": 0,"columns": [+ "companyId",+ "quantity",+ "createdBy","trackedActivityId","createdAt","trackedEntityId",- "updatedBy",- "companyId",- "quantity",- "createdBy"+ "updatedBy"]},{"name": "trackedActivityOutput","rows": 0,"columns": [+ "trackedEntityId",+ "createdBy",+ "trackedActivityId","updatedBy","companyId","quantity",- "createdAt",- "trackedEntityId",- "createdBy",- "trackedActivityId"+ "createdAt"]},{"name": "userAttributeCategory","rows": 0,"columns": [- "id",- "updatedAt",- "emoji",- "active",+ "protected",+ "public",+ "createdAt",+ "companyId","name","createdBy","updatedBy",- "companyId",- "protected",- "public",- "createdAt"+ "id",+ "updatedAt",+ "emoji",+ "active"]},{"name": "userAttribute","rows": 0,"columns": [- "listOptions",- "id",- "createdAt",- "updatedAt",- "active",- "createdBy",- "name",- "updatedBy",- "attributeDataTypeId","canSelfManage","userAttributeCategoryId",- "sortOrder"+ "sortOrder",+ "attributeDataTypeId",+ "updatedBy",+ "createdBy",+ "active",+ "name",+ "listOptions",+ "updatedAt",+ "id",+ "createdAt"]},{"name": "userAttributeValue","rows": 0,"columns": [- "valueDate",- "updatedBy","valueText","valueBoolean","userId",+ "valueDate",+ "updatedBy",+ "valueUser",+ "createdBy",+ "valueFile",+ "userAttributeId","valueNumeric",- "updatedAt","id","createdAt",- "createdBy",- "valueUser",- "valueFile",- "userAttributeId"+ "updatedAt"]},{@@ -3303,167 +3295,170 @@{"name": "userToCompany","rows": 0,- "columns": ["companyId", "userId", "role"]+ "columns": ["role", "companyId", "userId"]},{"name": "warehouse","rows": 0,"columns": [- "updatedAt",- "locationId",- "requiresPick",- "requiresReceive",- "requiresPutAway",- "createdAt",+ "createdBy",+ "id",+ "active",+ "requiresBin","updatedBy","name",- "requiresShipment","companyId",- "active",- "id",- "createdBy",- "requiresBin"+ "requiresShipment",+ "requiresPutAway",+ "createdAt",+ "requiresPick",+ "updatedAt",+ "locationId",+ "requiresReceive"]},{"name": "warehouseTransfer","rows": 0,"columns": [- "toLocationId",- "fromLocationId",- "updatedAt",- "expectedReceiptDate",- "status",- "createdAt",- "customFields",- "tags",- "updatedBy",- "transferId",- "notes",- "companyId",+ "transferDate",+ "createdBy","id","reference",- "createdBy",- "transferDate"+ "companyId",+ "notes",+ "updatedBy",+ "transferId",+ "tags",+ "customFields",+ "status",+ "createdAt",+ "expectedReceiptDate",+ "toLocationId",+ "fromLocationId",+ "updatedAt"]},{"name": "workCenter","rows": 0,"columns": [- "description",- "createdAt",- "tags",- "overheadRate",- "defaultStandardFactor",- "laborRate",- "departmentId",- "customFields",- "updatedBy",- "machineRate",- "updatedAt",+ "companyId",+ "requiredAbilityId",+ "id",+ "active",+ "locationId","createdBy","name",- "locationId",- "active",- "id",- "requiredAbilityId",- "companyId"+ "updatedAt",+ "alwaysOn",+ "updatedBy",+ "machineRate",+ "laborRate",+ "customFields",+ "departmentId",+ "defaultStandardFactor",+ "tags",+ "overheadRate",+ "description",+ "createdAt"]},{"name": "maintenanceSchedule","rows": 0,"columns": [- "thursday",- "wednesday",- "workCenterId",- "description",- "updatedBy",- "skipHolidays",- "estimatedDuration",- "frequency",- "friday",- "createdBy",- "sunday",- "saturday",- "updatedAt",- "tuesday",- "createdAt",+ "companyId",+ "lastGeneratedAt",+ "id",+ "procedureId",+ "priority","name",+ "createdAt","monday",- "locationId","nextDueAt",+ "locationId","active",- "companyId",- "id",- "lastGeneratedAt",- "procedureId",- "priority"+ "createdBy",+ "friday",+ "frequency",+ "sunday",+ "tuesday",+ "takesWorkCenterOffline",+ "saturday",+ "updatedAt",+ "wednesday",+ "thursday",+ "description",+ "updatedBy",+ "workCenterId",+ "estimatedDuration",+ "skipHolidays"]},{"name": "maintenanceDispatch","rows": 0,"columns": [- "createdAt",- "companyId",- "plannedStartTime",- "priority",- "nonConformanceId",- "actualEndTime",- "createdBy",- "status","content","actualStartTime",- "completedAt",+ "status","assignee",- "locationId",+ "completedAt","updatedBy",- "id",- "maintenanceScheduleId",- "severity",- "actualFailureModeId",- "source",- "oeeImpact",- "maintenanceDispatchId",+ "locationId",+ "createdAt",+ "priority",+ "plannedStartTime",+ "companyId",+ "actualEndTime",+ "createdBy",+ "nonConformanceId","plannedEndTime",- "workCenterId",+ "maintenanceDispatchId","procedureId",+ "workCenterId",+ "takesWorkCenterOffline",+ "updatedAt","suspectedFailureModeId",- "updatedAt"+ "maintenanceScheduleId",+ "id",+ "actualFailureModeId",+ "severity",+ "source",+ "oeeImpact"]},{"name": "maintenanceDispatchComment","rows": 0,"columns": [- "createdBy",- "updatedBy",- "comment",- "companyId",+ "updatedAt",+ "maintenanceDispatchId","createdAt","id",- "updatedAt",- "maintenanceDispatchId"+ "updatedBy",+ "companyId",+ "comment",+ "createdBy"]},{"name": "maintenanceDispatchEvent","rows": 0,"columns": [- "notes",- "employeeId",- "workCenterId",- "updatedBy",- "startTime",- "createdBy",- "maintenanceDispatchId","updatedAt",- "endTime",- "companyId",+ "maintenanceDispatchId",+ "createdBy",+ "createdAt","id",- "createdAt"+ "companyId",+ "endTime",+ "workCenterId",+ "employeeId",+ "notes",+ "startTime",+ "updatedBy"]},{@@ -3471,73 +3466,93 @@"rows": 0,"columns": ["unitCost",- "createdBy",- "id","updatedBy",- "companyId",+ "id",+ "createdBy","createdAt",+ "companyId","maintenanceDispatchId","updatedAt","unitOfMeasureCode",- "itemId",- "quantity"+ "quantity",+ "itemId"]},{"name": "maintenanceDispatchItemTrackedEntity","rows": 0,"columns": [+ "companyId","createdAt",- "quantity","trackedEntityId",- "companyId",- "updatedBy",- "maintenanceDispatchItemId",+ "quantity","createdBy",+ "updatedAt","id",- "updatedAt"+ "updatedBy",+ "maintenanceDispatchItemId"]},{"name": "maintenanceDispatchWorkCenter","rows": 0,"columns": [- "createdBy",- "updatedBy",- "companyId",- "workCenterId","createdAt","id","updatedAt",- "maintenanceDispatchId"+ "maintenanceDispatchId",+ "createdBy",+ "updatedBy",+ "workCenterId",+ "companyId"]},{"name": "maintenanceScheduleItem","rows": 0,"columns": [- "unitOfMeasureCode",- "createdBy",- "itemId",- "quantity",+ "maintenanceScheduleId",+ "createdAt",+ "updatedAt",+ "id",+ "updatedBy","companyId",+ "quantity",+ "itemId",+ "createdBy",+ "unitOfMeasureCode"+ ]+ },+ {+ "name": "peopleAssignment",+ "rows": 0,+ "columns": [+ "employeeId",+ "updatedAt",+ "shiftId",+ "workCenterId",+ "hours",+ "locationId",+ "date","updatedBy","id",+ "createdBy","createdAt",- "updatedAt",- "maintenanceScheduleId"+ "note",+ "overtimeHours",+ "companyId"]},{"name": "storageRuleWorkCenterAssignment","rows": 0,"columns": [+ "companyId",+ "createdBy",+ "createdAt","ruleId","workCenterId",- "updatedBy",- "createdBy",- "companyId",- "createdAt"+ "updatedBy"]},{@@ -3551,81 +3566,81 @@"workCenterId","companyId","tags",- "customFields","updatedBy",+ "customFields",+ "isWorkCenterDefault","parentId","locationId",- "isWorkCenterDefault","createdBy",- "name","updatedAt",- "id"+ "id",+ "name"]},{"name": "itemLedger","rows": 0,"columns": [- "documentLineId",- "companyId",- "entryNumber",+ "documentId",+ "id",+ "storageUnitId","itemId","scrapReasonId","locationId",- "id",- "storageUnitId",- "documentId",- "entryType",- "postingDate",- "createdAt",- "trackedEntityId",- "correctionOfItemLedgerId",- "externalDocumentId",+ "documentLineId",+ "companyId",+ "entryNumber",+ "createdBy",+ "trackedEntityStatus","updatedBy","documentType","comment","quantity",- "trackedEntityStatus",- "createdBy"+ "correctionOfItemLedgerId",+ "externalDocumentId",+ "entryType",+ "createdAt",+ "postingDate",+ "trackedEntityId"]},{"name": "pickMethod","rows": 0,"columns": [- "createdAt",+ "locationId",+ "updatedAt",+ "sortMethod","customFields","itemId",- "sortMethod",- "updatedAt",- "locationId",- "createdBy",- "updatedBy",+ "createdAt","defaultStorageUnitId",- "companyId"+ "companyId",+ "updatedBy",+ "createdBy"]},{"name": "warehouseTransferLine","rows": 0,"columns": [- "customFields","quantity",- "createdBy","itemId",+ "createdBy",+ "customFields","fromLocationId","notes","shippedQuantity","updatedAt","createdAt",+ "updatedBy","transferId","companyId",- "updatedBy",- "toStorageUnitId","fromStorageUnitId",- "unitOfMeasureCode",+ "toStorageUnitId","id","toLocationId",+ "unitOfMeasureCode","receivedQuantity"]},@@ -3637,187 +3652,201 @@"updatedBy","processId","createdAt",- "createdBy","companyId",+ "createdBy","updatedAt"]},{- "name": "workCenterReplacementPart",+ "name": "workCenterReplacementPart",+ "rows": 0,+ "columns": [+ "companyId",+ "updatedBy",+ "id",+ "createdAt",+ "updatedAt",+ "workCenterId",+ "unitOfMeasureCode",+ "createdBy",+ "itemId",+ "quantity"+ ]+ },+ {+ "name": "workCenterShift","rows": 0,"columns": [- "createdBy",- "itemId",- "quantity",- "unitOfMeasureCode","updatedAt",- "createdAt",- "workCenterId","companyId",+ "createdAt",+ "id","updatedBy",- "id"+ "workCenterId",+ "shiftId",+ "createdBy"]},{"name": "contractor","rows": 0,"columns": [- "createdAt",- "id","customFields",- "tags",- "updatedAt",+ "id",+ "createdAt","hoursPerWeek",+ "updatedAt",+ "tags","createdBy",- "updatedBy",+ "active","companyId",- "active"+ "updatedBy"]},{"name": "contractorAbility","rows": 0,"columns": [- "createdAt",- "createdBy","companyId",- "abilityId",+ "createdBy",+ "createdAt","contractorId",- "updatedBy"+ "updatedBy",+ "abilityId"]},{"name": "costLedger","rows": 0,"columns": [+ "companyId",+ "supplierId",+ "costLedgerType",+ "quantity","documentType",- "itemLedgerType","postingDate","nominalCost",- "remainingQuantity",+ "itemLedgerType","appliesToCostLedgerId",- "supplierId",- "companyId",- "quantity",- "costLedgerType",+ "remainingQuantity",+ "adjustment",+ "externalDocumentId",+ "id","documentId","itemId","createdAt",- "entryNumber","cost",- "adjustment",- "id",- "externalDocumentId"+ "entryNumber"]},{"name": "customer","rows": 0,"columns": [- "fax",- "currencyCode",- "tags",- "taxPercent",- "updatedAt",- "embedding","salesContactId","logo",- "website","customerStatusId","customerTypeId","customFields",- "defaultCc",- "accountManagerId",- "intercompanyCompanyId",- "createdBy",- "id",- "companyId",- "createdAt",+ "website",+ "fax",+ "currencyCode",+ "tags",+ "embedding",+ "taxPercent",+ "updatedAt","assignee","readableId",+ "createdAt",+ "phone","name","updatedBy",- "phone"+ "accountManagerId",+ "defaultCc",+ "id",+ "companyId",+ "intercompanyCompanyId",+ "createdBy"]},{"name": "customerAccount","rows": 0,- "columns": ["customerId", "id", "active", "companyId"]+ "columns": ["active", "companyId", "id", "customerId"]},{"name": "customerItemPriceOverride","rows": 0,"columns": [- "customerTypeId",- "updatedAt",- "itemId",- "validTo",- "notes",- "createdAt",- "updatedBy",- "customerId",- "companyId","active",- "createdBy",+ "companyId",+ "customerId",+ "updatedBy",+ "validFrom","applyRulesOnTop","id",- "validFrom"+ "createdBy",+ "validTo",+ "updatedAt",+ "customerTypeId",+ "itemId",+ "createdAt",+ "notes"]},{"name": "customerItemPriceOverrideBreak","rows": 0,"columns": [- "id",- "updatedBy",- "companyId",- "customerItemPriceOverrideId",+ "createdBy",+ "quantity",+ "overridePrice",+ "active","createdAt","updatedAt",- "active",- "overridePrice",- "quantity",- "createdBy"+ "customerItemPriceOverrideId",+ "companyId",+ "updatedBy",+ "id"]},{"name": "customerLocation","rows": 0,"columns": [- "customerId",- "companyId","id","tags",+ "customerId",+ "companyId",+ "name","customFields",- "addressId",- "name"+ "addressId"]},{"name": "customerContact","rows": 0,"columns": [+ "userId","contactId","customerLocationId","tags",- "userId",- "customerId",- "companyId","id",- "customFields"+ "customFields",+ "customerId",+ "companyId"]},{"name": "customerPartToItem","rows": 0,"columns": [- "companyId",- "itemId",- "customerPartRevision",+ "customerPartId","customerId","id",- "customerPartId"+ "itemId",+ "customerPartRevision",+ "companyId"]},{@@ -3838,51 +3867,51 @@"name": "customerShipping","rows": 0,"columns": [- "incotermLocation",- "updatedBy",- "customerId",- "shippingMethodId",- "shippingCustomerId",- "incoterm","updatedAt",- "shippingTermId",- "shippingCustomerLocationId",+ "incoterm",+ "shippingCustomerId",+ "shippingMethodId",+ "customerId",+ "updatedBy",+ "incotermLocation",+ "companyId","shippingCustomerContactId",- "companyId"+ "shippingCustomerLocationId",+ "shippingTermId"]},{"name": "customerTax","rows": 0,"columns": [- "taxExemptionCertificateNumber","eori","vatNumber",+ "taxExemptionCertificateNumber","taxExempt",+ "taxId","taxExemptionCertificatePath","updatedAt",- "taxId",- "taxExemptionReason","customerId","companyId",- "updatedBy"+ "updatedBy",+ "taxExemptionReason"]},{"name": "fixture","rows": 0,"columns": [- "itemId",- "tags",- "updatedBy","createdBy",- "updatedAt",- "id",- "createdAt",+ "updatedBy",+ "tags",+ "itemId","customFields",- "approved",- "customerId",+ "createdAt",+ "id",+ "updatedAt","companyId",+ "customerId",+ "approved","approvedBy"]},@@ -3890,25 +3919,25 @@"name": "nonConformanceCustomer","rows": 0,"columns": [- "id",- "createdBy",- "nonConformanceId",- "updatedBy",- "createdAt",- "customerId",+ "updatedAt","companyId",- "updatedAt"+ "customerId",+ "createdAt",+ "updatedBy",+ "nonConformanceId",+ "createdBy",+ "id"]},{"name": "opportunity","rows": 0,"columns": [- "companyId","requestForQuoteDocumentPath",- "purchaseOrderDocumentPath",+ "companyId",+ "customerId","id",- "customerId"+ "purchaseOrderDocumentPath"]},{@@ -3916,34 +3945,34 @@"rows": 0,"columns": ["customFields",- "salesOrderId","companyId",+ "salesOrderId","completedDate",- "customerId","customerEngineeringContactId",- "customerContactId",+ "customerId","externalNotes",+ "customerContactId","customerLocationId","id","customerReference","sentCompleteDate","internalNotes",- "revisionId","closedAt",+ "revisionId","status",- "createdBy","updatedAt",- "opportunityId",+ "createdBy","currencyCode","exchangeRateUpdatedAt",+ "opportunityId","exchangeRate",+ "orderDate","assignee","updatedBy",- "orderDate",- "createdAt",- "salesPersonId","locationId",- "closedBy"+ "closedBy",+ "createdAt",+ "salesPersonId"]},{@@ -3955,75 +3984,75 @@"name": "salesOrderLine","rows": 0,"columns": [- "invoicedComplete",- "addOnCost",- "companyId",- "pricingRuleId",- "unitOfMeasureCode",- "updatedBy",- "storageUnitId",- "sentComplete",- "setupPrice",- "internalNotes",- "itemId",- "unitPrice",- "salesOrderLineType",- "methodType",- "createdAt",- "shippingCost",- "nonTaxableAddOnCost",- "assetId",- "status","taxPercent",- "customFields","priceTrace","quantitySent",- "sortOrder",- "id",+ "customFields","saleQuantity",+ "id",+ "sortOrder","updatedAt",- "quantityInvoiced","externalNotes",+ "quantityInvoiced","salesOrderId","locationId",- "createdBy","sentDate",+ "createdBy","exchangeRate","accountId",+ "modelUploadId","promisedDate","description",- "modelUploadId"+ "addOnCost",+ "invoicedComplete",+ "companyId",+ "unitOfMeasureCode",+ "pricingRuleId",+ "storageUnitId",+ "updatedBy",+ "sentComplete",+ "internalNotes",+ "setupPrice",+ "unitPrice",+ "salesOrderLineType",+ "itemId",+ "methodType",+ "assetId",+ "shippingCost",+ "createdAt",+ "nonTaxableAddOnCost",+ "status"]},{"name": "nonConformanceSalesOrderLine","rows": 0,"columns": [- "createdAt",- "salesOrderLineId",- "salesOrderId",- "salesOrderReadableId",- "updatedBy",- "createdBy",- "nonConformanceId","companyId","updatedAt",- "id"+ "id",+ "createdBy",+ "updatedBy",+ "nonConformanceId",+ "salesOrderReadableId",+ "createdAt",+ "salesOrderLineId",+ "salesOrderId"]},{"name": "salesOrderPayment","rows": 0,"columns": [- "companyId",- "updatedBy","invoiceCustomerId",- "paymentComplete",- "updatedAt",- "id",+ "updatedBy",+ "companyId","customFields",- "invoiceCustomerLocationId",+ "id",+ "updatedAt",+ "paymentComplete","invoiceCustomerContactId",+ "invoiceCustomerLocationId","paymentTermId"]},@@ -4031,227 +4060,230 @@"name": "salesOrderShipment","rows": 0,"columns": [- "supplierId",- "locationId",- "updatedBy",- "dropShipment",- "notes",- "customerId",- "id",- "trackingNumber",- "receiptPromisedDate",- "assignee",- "customFields",+ "deliveryDate","shippingTermId",- "supplierLocationId","shippingMethodId",- "deliveryDate",+ "supplierLocationId",+ "assignee",+ "customFields",+ "companyId",+ "incoterm",+ "updatedAt",+ "incotermLocation","receiptRequestedDate","shippingCost","customerLocationId",- "incotermLocation",- "companyId",- "incoterm",- "updatedAt"+ "notes",+ "dropShipment",+ "updatedBy",+ "supplierId",+ "locationId",+ "receiptPromisedDate",+ "id",+ "trackingNumber",+ "customerId"]},{"name": "salesOrderStatusHistory","rows": 0,"columns": [- "updatedBy",- "status",- "createdAt",- "createdBy","salesOrderId",+ "id","companyId",- "id"+ "status",+ "createdAt",+ "updatedBy",+ "createdBy"]},{"name": "salesOrderTransaction","rows": 0,"columns": [- "companyId",- "id",- "salesOrderId","createdAt",+ "type","userId",- "type"+ "companyId",+ "id",+ "salesOrderId"]},{"name": "salesRfq","rows": 0,"columns": [- "customFields",- "rfqId",- "locationId",- "completedDate","customerEngineeringContactId","customerReference",- "expirationDate",+ "completedDate","internalNotes",- "rfqDate",- "id",- "noQuoteReasonId",+ "expirationDate",+ "customFields",+ "locationId",+ "rfqId","customerId","salesPersonId",+ "id",+ "rfqDate",+ "noQuoteReasonId",+ "externalNotes",+ "customerContactId",+ "opportunityId",+ "status","assignee","revisionId",- "status",- "createdBy","updatedAt",- "opportunityId",- "customerContactId",- "externalNotes",- "updatedBy",- "employeeId",- "createdAt",- "tags",+ "createdBy",+ "companyId","customerLocationId",- "companyId"+ "tags",+ "createdAt",+ "employeeId",+ "updatedBy"]},{"name": "salesRfqFavorite","rows": 0,- "columns": ["userId", "rfqId"]+ "columns": ["rfqId", "userId"]},{"name": "salesRfqLine","rows": 0,"columns": [- "externalNotes",+ "unitOfMeasureCode",+ "internalNotes",+ "updatedAt",+ "salesRfqId",+ "customFields",+ "description","id","order",- "description",- "customFields",- "salesRfqId",- "updatedAt",- "internalNotes",- "unitOfMeasureCode",- "itemId",- "customerPartRevision",- "companyId",+ "externalNotes",+ "quantity",+ "createdAt",+ "modelUploadId",+ "customerPartId",+ "updatedBy","tags","createdBy",- "updatedBy",- "customerPartId",- "modelUploadId",- "createdAt",- "quantity"+ "customerPartRevision",+ "companyId",+ "itemId"]},{"name": "externalLink","rows": 0,"columns": [- "documentId",- "customerId",- "companyId","createdAt",- "documentType",- "supplierId",+ "companyId",+ "customerId",+ "documentId",+ "expiresAt","id",- "expiresAt"+ "supplierId",+ "documentType"]},{"name": "quote","rows": 0,"columns": [- "currencyCode",- "expirationDate",- "exchangeRateUpdatedAt","customerId",- "id",+ "exchangeRateUpdatedAt","salesPersonId",- "internalNotes",- "estimatorId",- "digitalQuoteRejectedByEmail",- "digitalQuoteAcceptedByEmail",- "digitalQuoteAcceptedBy",- "customerContactId",+ "id",+ "currencyCode",+ "expirationDate","quoteId","opportunityId",+ "customerContactId","assignee",- "updatedAt",- "locationId",- "exchangeRate",- "customFields",- "dueDate",- "createdBy",- "customerLocationId",+ "digitalQuoteRejectedByEmail",+ "estimatorId",+ "internalNotes",+ "digitalQuoteAcceptedBy",+ "digitalQuoteAcceptedByEmail","tags",+ "customerLocationId",+ "createdBy",+ "dueDate","updatedBy",- "digitalQuoteRejectedBy",- "externalNotes",- "customerEngineeringContactId",- "status",- "completedDate",- "externalLinkId",- "createdAt",+ "customFields",+ "exchangeRate",+ "locationId",+ "updatedAt","companyId",+ "createdAt","customerReference",- "revisionId"+ "revisionId",+ "digitalQuoteRejectedBy",+ "externalLinkId",+ "completedDate",+ "status",+ "customerEngineeringContactId",+ "externalNotes"]},{"name": "job","rows": 0,"columns": [- "salesOrderId",- "quantityComplete",- "jobId",- "actualTime",- "tags",- "configuration",- "dueDate",- "companyId",- "quantity",- "estimatedTime",- "deadlineType",- "id",- "priority",- "storageUnitId",- "scrapQuantity",- "updatedAt",- "locationId",- "createdAt",- "quantityShipped",- "itemId",- "unitOfMeasureCode",- "quoteLineId",- "quoteId",- "status",- "startDate",- "customFields",- "updatedBy",- "completedDate",- "assignee",- "customerId",- "releasedDate",- "modelUploadId",+ "createdBy",+ "salesOrderLineId","notes","quantityReceivedToInventory",- "salesOrderLineId",- "createdBy"+ "assignee",+ "modelUploadId",+ "releasedDate",+ "customerId",+ "updatedBy",+ "startDate",+ "customFields",+ "status",+ "completedDate",+ "unitOfMeasureCode",+ "itemId",+ "quantityShipped",+ "quoteId",+ "projectedCompletionAt",+ "quoteLineId",+ "scheduleOutdatedAt",+ "locationId",+ "createdAt",+ "id",+ "deadlineType",+ "updatedAt",+ "scrapQuantity",+ "priority",+ "storageUnitId",+ "dueDate",+ "configuration",+ "tags",+ "quantity",+ "estimatedTime",+ "companyId",+ "salesOrderId",+ "actualTime",+ "jobId",+ "quantityComplete",+ "scheduleOutdatedReason"]},{"name": "fulfillment","rows": 0,"columns": [- "createdAt",- "type",- "quantity",- "jobId",- "createdBy","salesOrderLineId",- "companyId",+ "createdBy",+ "id","updatedBy",- "id"+ "companyId",+ "quantity",+ "type",+ "createdAt",+ "jobId"]},{@@ -4262,43 +4294,43 @@{"name": "quoteFavorite","rows": 0,- "columns": ["quoteId", "userId"]+ "columns": ["userId", "quoteId"]},{"name": "quoteLine","rows": 0,"columns": [- "locationId",- "externalNotes",- "sortOrder",- "status",- "quoteRevisionId",- "internalNotes",- "customFields",- "updatedBy",- "companyId",+ "taxPercent",+ "itemId",+ "unitPricePrecision",+ "customerPartRevision",+ "id",+ "description",+ "noQuoteReason",+ "customerPartId",+ "itemType",+ "pricingRuleId",+ "configuration",+ "unitOfMeasureCode",+ "quoteId",+ "createdBy","quantity",+ "companyId","tags","updatedAt",- "additionalCharges","estimatorId","modelUploadId",- "priceTrace","methodType",- "itemType",- "pricingRuleId",- "configuration",- "noQuoteReason",- "customerPartId",- "createdBy",- "unitOfMeasureCode",- "quoteId",- "itemId",- "taxPercent",- "id",- "description",- "unitPricePrecision",- "customerPartRevision"+ "priceTrace",+ "additionalCharges",+ "sortOrder",+ "locationId",+ "externalNotes",+ "customFields",+ "updatedBy",+ "status",+ "quoteRevisionId",+ "internalNotes"]},{@@ -4326,31 +4358,54 @@"name": "quotePayment","rows": 0,"columns": [- "invoiceCustomerLocationId",- "invoiceCustomerContactId",- "companyId",- "paymentTermId",- "invoiceCustomerId","updatedAt","customFields",+ "invoiceCustomerId",+ "id","updatedBy",- "id"+ "companyId",+ "invoiceCustomerContactId",+ "invoiceCustomerLocationId",+ "paymentTermId"]},{"name": "quoteShipment","rows": 0,"columns": [+ "updatedBy",+ "shippingTermId",+ "shippingMethodId",+ "incotermLocation",+ "receiptRequestedDate",+ "updatedAt",+ "locationId",+ "companyId","incoterm","id",- "shippingCost",- "companyId",- "locationId",+ "shippingCost"+ ]+ },+ {+ "name": "capacityReservation",+ "rows": 0,+ "columns": [+ "endAt",+ "createdBy",+ "workHours","updatedAt",- "incotermLocation",- "receiptRequestedDate",- "shippingTermId",- "shippingMethodId",+ "companyId",+ "jobId",+ "id",+ "scenarioId",+ "createdAt",+ "startAt",+ "resourceId",+ "resourceKind",+ "earliestStartAt",+ "scheduleNote",+ "isPlaceholder",+ "operationId","updatedBy"]},@@ -4358,204 +4413,204 @@"name": "gauge","rows": 0,"columns": [- "gaugeTypeId",- "gaugeStatus",- "storageUnitId",- "gaugeId",- "lastCalibrationDate",- "description",+ "gaugeRole","gaugeCalibrationStatus","id",- "gaugeRole",- "dateAcquired",- "lastCalibrationStatus",+ "description",+ "lastCalibrationDate",+ "gaugeId",+ "storageUnitId",+ "gaugeStatus",+ "gaugeTypeId",+ "serialNumber",+ "calibrationIntervalInMonths",+ "createdBy",+ "updatedBy",+ "updatedAt",+ "locationId",+ "companyId",+ "createdAt",+ "customFields","nextCalibrationDate","supplierId","modelNumber",- "customFields",- "createdAt",- "companyId",- "locationId",- "updatedAt",- "updatedBy",- "calibrationIntervalInMonths",- "createdBy",- "serialNumber"+ "dateAcquired",+ "lastCalibrationStatus"]},{"name": "gaugeCalibrationRecord","rows": 0,"columns": [- "approvedBy",- "measurementStandard",- "inspectionStatus",- "dateCalibrated",- "updatedBy",- "requiresRepair","calibrationAttempts","createdBy","requiresAction","humidity","supplierId",+ "inspectionStatus",+ "updatedBy",+ "dateCalibrated",+ "approvedBy",+ "measurementStandard",+ "requiresRepair",+ "id",+ "customFields",+ "createdAt",+ "requiresAdjustment",+ "temperature","gaugeId","updatedAt",- "temperature",- "companyId","notes",- "createdAt",- "id",- "customFields",- "requiresAdjustment"+ "companyId"]},{"name": "inspection","rows": 0,"columns": [- "createdAt",- "supplierId",- "sourceDocument",- "notes",- "status",- "aql",- "dispositionedAt",- "inspectionLevel",- "updatedBy",- "codeLetter",- "itemId",- "dispositionedBy",+ "companyId","acceptanceNumber","sourceDocumentReadableId",- "companyId",- "createdBy",- "samplingPlanType",+ "dispositionedBy",+ "itemId",+ "codeLetter",+ "updatedBy",+ "dispositionedAt",+ "inspectionLevel",+ "aql",+ "status",+ "notes",+ "sourceDocument",+ "supplierId",+ "createdAt",+ "samplingStandard",+ "id",+ "sampleSize",+ "inspectionDocumentId",+ "itemReadableId",+ "updatedAt",+ "severity",+ "inspectionId",+ "rejectionNumber",+ "sourceDocumentId","lotSize","sourceDocumentLineId",- "sourceDocumentId",- "rejectionNumber",- "inspectionId",- "severity",- "updatedAt",- "itemReadableId",- "inspectionDocumentId",- "sampleSize",- "id",- "samplingStandard"+ "samplingPlanType",+ "createdBy"]},{"name": "inspectionSample","rows": 0,"columns": [- "createdBy",- "companyId",- "inspectionId","inspectedBy","updatedAt","createdAt","id",+ "createdBy",+ "companyId",+ "inspectionId",+ "notes",+ "updatedBy","inspectedAt","trackedEntityId",- "status",- "notes",- "updatedBy"+ "status"]},- {- "name": "inspectionMeasurement",- "rows": 0,- "columns": [- "id",- "inspectedAt",- "createdBy",- "status",- "inspectionId",- "updatedBy",- "inspectedBy",- "companyId",- "createdAt",+ {+ "name": "inspectionMeasurement",+ "rows": 0,+ "columns": ["value",+ "createdAt",+ "notes","inspectionFeatureId",- "updatedAt","inspectionSampleId",- "notes"+ "updatedAt",+ "status",+ "createdBy",+ "id",+ "inspectedAt",+ "companyId",+ "inspectedBy",+ "updatedBy",+ "inspectionId"]},{"name": "inspectionSamplingPlan","rows": 0,"columns": [+ "createdAt",+ "companyId",+ "inspectionId",+ "rejectionNumber",+ "updatedBy","id","createdBy",- "updatedBy",- "rejectionNumber",- "inspectionId",- "companyId",- "createdAt",- "acceptanceNumber",- "updatedAt",+ "codeLetter","sampleSize","inspectionFeatureId",- "codeLetter"+ "acceptanceNumber",+ "updatedAt"]},{"name": "nonConformanceInspection","rows": 0,"columns": [+ "createdAt","companyId","inspectionId","updatedBy",- "createdAt",- "nonConformanceId","id",- "createdBy"+ "createdBy",+ "nonConformanceId"]},{"name": "inspectionHistory","rows": 0,"columns": [- "severity",+ "inspectionId",+ "companyId",+ "updatedBy",+ "sampleSize",+ "aql",+ "defectsFound","lotSize","id",- "defectsFound",- "aql",- "sampleSize",- "updatedBy",- "companyId",- "inspectionId",- "createdBy",- "samplingStandard",- "outcome",- "inspectionLevel",- "itemId",+ "severity","createdAt",- "supplierId"+ "itemId",+ "supplierId",+ "inspectionLevel",+ "outcome",+ "samplingStandard",+ "createdBy"]},{"name": "itemReplenishment","rows": 0,"columns": [- "leadTime",- "tags","purchasingUnitOfMeasureCode","updatedBy",- "conversionFactor",- "createdBy",- "updatedAt",+ "tags",+ "leadTime","scrapPercentage",- "createdAt",- "preferredSupplierId",- "customFields",- "lotSize",+ "updatedAt",+ "createdBy",+ "conversionFactor","manufacturingBlocked",- "companyId",+ "lotSize",+ "customFields",+ "preferredSupplierId",+ "createdAt",+ "purchasingBlocked","itemId","requiresConfiguration",- "purchasingBlocked"+ "companyId"]},{@@ -4563,79 +4618,79 @@"rows": 0,"columns": ["version",- "quantityPerParent","trackedEntityId",+ "quantityPerParent","createdAt","itemId",- "requiresBatchTracking","parentMaterialId",+ "requiresBatchTracking","companyId",- "customFields","id","updatedAt",- "updatedBy",+ "customFields","createdBy",- "requiresSerialTracking",+ "updatedBy",+ "itemScrapPercentage","jobId",- "itemScrapPercentage"+ "requiresSerialTracking"]},{"name": "jobMaterial","rows": 0,"columns": [- "updatedBy",- "customFields",- "itemId",- "companyId",- "substitutedFromItemId",- "requiresSerialTracking",- "order",- "defaultStorageUnit",- "unitOfMeasureCode",+ "estimatedQuantity","itemScrapPercentage",+ "unitOfMeasureCode","jobMakeMethodId","itemType",- "estimatedQuantity","updatedAt",- "jobOperationId","createdAt",+ "jobOperationId",+ "companyId",+ "itemId",+ "updatedBy",+ "customFields",+ "requiresSerialTracking",+ "order",+ "defaultStorageUnit",+ "substitutedFromItemId",+ "quantity",+ "id",+ "methodType",+ "quantityIssued",+ "createdBy","jobId","unitCost",- "createdBy",- "scrapQuantity",- "substitutionFactor",- "storageUnitId","requiresBatchTracking",- "description","kit",- "quantity",- "id",- "quantityIssued",- "methodType"+ "description",+ "substitutionFactor",+ "scrapQuantity",+ "storageUnitId"]},{"name": "stockTransferLine","rows": 0,"columns": [- "fromStorageUnitId",- "id",- "pickedQuantity","trackedEntityId",- "quantity",- "createdBy",- "stockTransferId",+ "pickedQuantity",+ "id",+ "fromStorageUnitId","requiresSerialTracking",- "updatedAt",- "createdAt",- "requiresBatchTracking",+ "stockTransferId",+ "createdBy",+ "quantity","itemId",- "toStorageUnitId",- "jobMaterialId",- "companyId",+ "requiresBatchTracking",+ "createdAt",+ "updatedAt",+ "updatedBy","jobId",- "updatedBy"+ "companyId",+ "jobMaterialId",+ "toStorageUnitId"]},{@@ -4647,53 +4702,55 @@"name": "jobOperation","rows": 0,"columns": [- "procedureId",- "tags",- "updatedAt",- "laborUnit",+ "hasConflict",+ "workCenterId",+ "createdAt",+ "readyAt",+ "inspectionDocumentId","id",+ "projectedCompletionAt","setupUnit",- "inspectionDocumentId",- "createdAt",- "workCenterId",- "hasConflict",- "machineUnit",- "dueDate",- "jobId",- "status",- "overheadRate",- "conflictReason",- "companyId",- "laborTime",- "quantityReworked",- "targetQuantity",- "operationQuantity",+ "updatedAt",+ "laborUnit",+ "tags",+ "procedureId","setupTime",+ "operationQuantity","customFields",- "processId",- "operationLeadTime",- "machineTime",- "quantityComplete",- "reworkId",- "operationSupplierProcessId",- "operationUnitCost",- "laborRate",+ "targetQuantity",+ "quantityReworked",+ "laborTime",+ "companyId",+ "conflictReason",+ "overheadRate",+ "status",+ "jobId",+ "dueDate",+ "machineUnit",+ "manuallyScheduled","createdBy","machineRate",- "manuallyScheduled",- "assemblyInstructionId",- "operationMinimumCost",- "operationType",- "startDate",- "order",- "operationOrder",- "jobMakeMethodId",- "quantityScrapped",+ "laborRate",+ "operationUnitCost",+ "operationSupplierProcessId",+ "reworkId",+ "operationLeadTime",+ "quantityComplete",+ "machineTime",+ "processId",+ "updatedBy","assignee","workInstruction",- "description","priority",- "updatedBy"+ "description",+ "quantityScrapped",+ "order",+ "jobMakeMethodId",+ "operationOrder",+ "startDate",+ "operationType",+ "assemblyInstructionId",+ "operationMinimumCost"]},{@@ -4711,247 +4768,247 @@"name": "jobOperationParameter","rows": 0,"columns": [- "key",- "updatedAt",- "id","updatedBy",+ "id","createdAt",- "operationId",+ "key",+ "updatedAt",+ "companyId","value",- "createdBy",- "companyId"+ "operationId",+ "createdBy"]},{"name": "jobOperationTool","rows": 0,"columns": [- "updatedAt",- "operationId",- "createdAt",- "id","updatedBy",- "createdBy",- "quantity",+ "id",+ "createdAt",+ "operationId",+ "updatedAt",+ "companyId","toolId",- "companyId"+ "quantity",+ "createdBy"]},{"name": "nonConformanceJobOperation","rows": 0,"columns": [- "companyId",+ "jobReadableId",+ "jobId",+ "jobOperationId",+ "createdAt","id","updatedAt",- "createdBy",- "updatedBy",+ "companyId","nonConformanceId",- "jobReadableId",- "createdAt",- "jobId",- "jobOperationId"+ "createdBy",+ "updatedBy"]},{"name": "pickingListLine","rows": 0,"columns": [- "customFields",- "quantityReturned",- "createdBy",- "jobId",- "jobMaterialId",- "quantityToPick",+ "id",+ "toStorageUnitId",+ "itemId",+ "updatedBy",+ "pickingListId",+ "companyId",+ "quantityPicked",+ "storageUnitId","status","jobOperationId","updatedAt","createdAt",- "pickingListId",- "companyId",- "updatedBy",- "storageUnitId",- "quantityPicked",- "toStorageUnitId",- "id",- "itemId"+ "jobId",+ "createdBy",+ "jobMaterialId",+ "customFields",+ "quantityReturned",+ "quantityToPick"]},{"name": "pickingListLineTrackedEntity","rows": 0,"columns": [- "quantityPicked",- "quantity",- "companyId","trackedEntityId",- "pickingListLineId"+ "pickingListLineId",+ "quantity",+ "quantityPicked",+ "companyId"]},{"name": "productionEvent","rows": 0,"columns": [- "notes",- "updatedAt",- "endTime",- "employeeId",- "type",- "startTime",- "createdBy",- "companyId",- "id","createdAt","workCenterId",- "jobOperationId","updatedBy",- "postedToGL"+ "jobOperationId",+ "postedToGL",+ "createdBy",+ "companyId",+ "id",+ "employeeId",+ "type",+ "startTime",+ "notes",+ "endTime",+ "updatedAt"]},{"name": "productionQuantity","rows": 0,"columns": [- "companyId",- "id",- "createdBy",- "laborProductionEventId",+ "quantity",+ "scrapReasonId",+ "type",+ "machineProductionEventId",+ "updatedAt",+ "setupProductionEventId",+ "inspectionId","inspectionSampleId",- "updatedBy","jobOperationId",+ "updatedBy","notes","createdAt",- "setupProductionEventId",- "updatedAt",- "inspectionId",- "type",- "scrapReasonId",- "quantity",- "machineProductionEventId"+ "id",+ "companyId",+ "createdBy",+ "laborProductionEventId"]},{"name": "jobOperationNote","rows": 0,"columns": [- "createdAt","companyId","note","updatedBy",+ "createdAt",+ "jobOperationId",+ "updatedAt","id","productionQuantityId",- "createdBy",- "jobOperationId",- "updatedAt"+ "createdBy"]},{"name": "rework","rows": 0,"columns": [- "targetJobOperationId",- "triggeredAtJobOperationId","reason","updatedAt",- "requestedById",- "companyId",- "jobId",+ "targetJobOperationId",+ "triggeredAtJobOperationId","quantity",+ "createdAt","id","completedAt",- "createdAt"+ "companyId",+ "requestedById",+ "jobId"]},{"name": "jobOperationStep","rows": 0,"columns": [- "listValues",- "minValue",- "companyId",- "name",- "updatedAt",- "type",- "fileTypes",- "id",- "maxValue",- "unitOfMeasureCode",- "nonConformanceActionId",+ "nonConformanceInvestigationId",+ "operationId",+ "sortOrder",+ "updatedBy",+ "assemblyInstructionStepId",+ "createdBy","description",+ "nonConformanceActionId","required","createdAt",- "assemblyInstructionStepId",- "createdBy",- "updatedBy",- "sortOrder",- "nonConformanceInvestigationId",- "operationId"+ "unitOfMeasureCode",+ "fileTypes",+ "id",+ "maxValue",+ "type",+ "name",+ "companyId",+ "updatedAt",+ "listValues",+ "minValue"]},{"name": "jobOperationStepRecord","rows": 0,"columns": [- "index",- "userValue",- "numericValue",- "booleanValue",- "createdAt",+ "createdBy",+ "updatedBy",+ "value",+ "companyId","updatedAt","jobOperationStepId","id",- "companyId",- "value",- "createdBy",- "updatedBy"+ "createdAt",+ "numericValue",+ "booleanValue",+ "userValue",+ "index"]},{"name": "jobOperationStepSlide","rows": 0,"columns": [- "createdBy",- "imagePath",- "caption",- "annotations",- "sortOrder",- "updatedAt",- "createdAt",- "stepId",- "modelUploadId",- "companyId","size","updatedBy",- "id"+ "id",+ "companyId",+ "modelUploadId",+ "stepId",+ "updatedAt",+ "createdAt",+ "sortOrder",+ "annotations",+ "imagePath",+ "caption",+ "createdBy"]},{"name": "jobOperationToolStep","rows": 0,- "columns": ["jobOperationStepId", "jobOperationToolId"]+ "columns": ["jobOperationToolId", "jobOperationStepId"]},{"name": "kanban","rows": 0,"columns": [- "purchaseUnitOfMeasureCode",- "autoRelease",- "autoStartJob",- "createdBy",- "itemId",- "storageUnitId",+ "companyId","id","conversionFactor",- "companyId",- "supplierId",+ "storageUnitId",+ "itemId",+ "createdBy",+ "autoStartJob",+ "autoRelease",+ "purchaseUnitOfMeasureCode",+ "createdAt",+ "locationId",+ "completedBarcodeOverride",+ "updatedBy",+ "jobId","quantity","updatedAt","replenishmentSystem",- "jobId",- "updatedBy",- "completedBarcodeOverride",- "locationId",- "createdAt"+ "supplierId"]},{@@ -4969,8 +5026,8 @@"amount","supplierId","customFields",- "notes","direction",+ "notes","status","voidedAt","voidedBy",@@ -4981,75 +5038,75 @@"companyId","customerId","postedBy",- "createdBy",- "journalId"+ "journalId",+ "createdBy"]},{"name": "methodMaterial","rows": 0,"columns": [- "order",- "tags",- "updatedAt",- "itemType","kit","quantity",+ "methodOperationId",+ "scrapQuantity","materialMakeMethodId","methodType","customFields",- "methodOperationId",- "scrapQuantity",- "itemId",- "sourcingType",- "id",- "companyId",- "createdBy",- "unitOfMeasureCode",- "createdAt",- "storageUnitIds",- "makeMethodId",- "updatedBy"- ]- },- {- "name": "methodMaterialStep",- "rows": 0,- "columns": ["methodOperationStepId", "methodMaterialId", "quantity"]- },- {- "name": "methodOperation",- "rows": 0,- "columns": [- "updatedBy",- "laborTime",- "operationSupplierProcessId",- "processId",- "laborUnit",- "setupUnit",- "operationLeadTime",- "createdAt",- "machineTime",- "description",+ "order","tags",- "operationUnitCost",- "operationOrder","updatedAt",- "order",- "setupTime",- "workCenterId",- "operationType",+ "itemType",+ "createdAt",+ "storageUnitIds",+ "unitOfMeasureCode",+ "makeMethodId",+ "updatedBy",+ "sourcingType",+ "itemId",+ "createdBy","id",- "workInstruction",- "companyId",+ "companyId"+ ]+ },+ {+ "name": "methodMaterialStep",+ "rows": 0,+ "columns": ["methodOperationStepId", "methodMaterialId", "quantity"]+ },+ {+ "name": "methodOperation",+ "rows": 0,+ "columns": [+ "customFields",+ "createdBy",+ "inspectionDocumentId",+ "makeMethodId","operationMinimumCost","procedureId","machineUnit","assemblyInstructionId",- "customFields",- "createdBy",- "makeMethodId",- "inspectionDocumentId"+ "id",+ "workInstruction",+ "companyId",+ "operationType",+ "operationOrder",+ "order",+ "updatedAt",+ "setupTime",+ "workCenterId",+ "machineTime",+ "description",+ "tags",+ "operationUnitCost",+ "laborUnit",+ "setupUnit",+ "createdAt",+ "operationLeadTime",+ "laborTime",+ "updatedBy",+ "operationSupplierProcessId",+ "processId"]},{@@ -5071,58 +5128,58 @@"name": "methodOperationStep","rows": 0,"columns": [- "createdBy",- "updatedBy",- "sortOrder",- "operationId",- "unitOfMeasureCode","assemblyInstructionStepId","description","createdAt","required",- "type",+ "unitOfMeasureCode",+ "sortOrder",+ "operationId",+ "createdBy",+ "updatedBy",+ "companyId",+ "name",+ "updatedAt",+ "listValues",+ "minValue","fileTypes","maxValue","id",- "listValues",- "minValue",- "companyId",- "name",- "updatedAt"+ "type"]},{"name": "methodOperationStepSlide","rows": 0,"columns": [- "createdBy",- "imagePath",- "caption","sortOrder","annotations",- "updatedAt",- "createdAt",+ "caption",+ "imagePath",+ "createdBy",+ "id",+ "updatedBy",+ "size",+ "companyId","modelUploadId","stepId",- "companyId",- "size",- "updatedBy",- "id"+ "createdAt",+ "updatedAt"]},{"name": "methodOperationTool","rows": 0,"columns": [- "companyId",+ "createdBy","quantity","toolId",- "createdBy",- "id",- "updatedBy",- "createdAt",+ "companyId",+ "updatedAt","operationId",- "updatedAt"+ "createdAt",+ "id",+ "updatedBy"]},{@@ -5134,136 +5191,127 @@"name": "nonConformanceActionProcess","rows": 0,"columns": [- "actionTaskId",- "updatedBy",- "id",- "createdBy",+ "createdAt",+ "updatedAt","processId","companyId",- "updatedAt",- "createdAt"+ "createdBy",+ "id",+ "updatedBy",+ "actionTaskId"]},{"name": "nonConformanceActionTask","rows": 0,"columns": [- "completedDate",- "companyId",- "sortOrder",- "id",+ "assignee",+ "updatedAt",+ "status",+ "supplierId",+ "updatedBy",+ "createdAt",+ "dueDate","tags","notes","nonConformanceId","createdBy","actionTypeId",- "supplierId",- "updatedBy",- "createdAt",- "dueDate",- "assignee",- "updatedAt",- "status"+ "completedDate",+ "companyId",+ "sortOrder",+ "id"]},{"name": "nonConformanceSupplier","rows": 0,"columns": [- "updatedAt",- "companyId",- "supplierId",- "createdAt",- "updatedBy","nonConformanceId",- "createdBy",+ "updatedBy","id",- "externalLinkId"+ "externalLinkId",+ "createdBy",+ "companyId",+ "supplierId",+ "updatedAt",+ "createdAt"]},{"name": "partner","rows": 0,"columns": [+ "companyId",+ "createdAt","abilityId","active",- "createdAt",- "companyId",- "hoursPerWeek",- "updatedBy",- "customFields",+ "createdBy","updatedAt","id","tags",- "createdBy"+ "updatedBy",+ "customFields",+ "hoursPerWeek"]},{"name": "payment","rows": 0,"columns": [- "updatedBy",- "paymentDate",+ "postedAt",+ "reference",+ "paymentId",+ "postingDate",+ "updatedAt",+ "exchangeRate",+ "id",+ "currencyCode",+ "totalAmount",+ "supplierId",+ "customFields","status",- "paymentType","memo",- "voidedAt",+ "paymentType","voidedBy",- "postedBy",- "journalId",- "createdBy",+ "voidedAt",+ "updatedBy",+ "paymentDate","createdAt",+ "customerId","companyId","bankAccount",- "customerId",- "postingDate",- "exchangeRate",- "updatedAt",- "postedAt",- "paymentId",- "reference",- "supplierId",- "customFields",- "id",- "currencyCode",- "totalAmount"+ "createdBy",+ "journalId",+ "postedBy"]},{"name": "purchaseInvoiceDelivery","rows": 0,"columns": [- "companyId",- "incotermLocation",- "id","customFields",- "incoterm",- "updatedAt",+ "id",+ "incotermLocation",+ "companyId","locationId",+ "updatedAt",+ "incoterm","supplierShippingCost",- "updatedBy",+ "shippingMethodId","shippingTermId",- "shippingMethodId"+ "updatedBy"]},{"name": "purchaseInvoiceStatusHistory","rows": 0,- "columns": ["invoiceId", "status", "id", "companyId", "createdAt"]+ "columns": ["createdAt", "companyId", "invoiceId", "id", "status"]},{"name": "purchaseOrderDelivery","rows": 0,"columns": [- "receiptPromisedDate",- "customerId",- "trackingNumber",- "id",- "dropShipment",- "notes",- "companyId",- "locationId",- "customFields","updatedAt","tags","receiptRequestedDate",@@ -5274,7 +5322,16 @@"supplierShippingCost","updatedBy","shippingMethodId",- "shippingTermId"+ "shippingTermId",+ "receiptPromisedDate",+ "customerId",+ "trackingNumber",+ "id",+ "dropShipment",+ "notes",+ "companyId",+ "locationId",+ "customFields"]},{@@ -5282,107 +5339,107 @@"rows": 0,"columns": ["userId", "purchaseOrderId"]},- {- "name": "purchaseOrderLine",- "rows": 0,- "columns": [- "updatedAt",- "locationId",- "costCenterId",- "inventoryUnitOfMeasureCode",- "invoicedComplete",- "taxPercent",- "quantityShipped",- "receivedComplete",- "jobOperationId",- "internalNotes",- "customFields",- "sortOrder",- "companyId",- "assetId",- "storageUnitId",- "setupPrice",- "promisedDate",- "itemId",- "purchaseOrderLineType",- "supplierUnitPrice",- "createdBy",- "supplierPartId",- "accountId",- "supplierTaxAmount",- "requiredDate",- "updatedBy",- "quantityReceived",- "supplierShippingCost",- "id",- "purchaseQuantity",+ {+ "name": "purchaseOrderLine",+ "rows": 0,+ "columns": [+ "conversionFactor",+ "receivedDate",+ "tags",+ "description","externalNotes","createdAt",- "description",- "tags",- "receivedDate",- "conversionFactor",- "jobId",- "exchangeRate",+ "purchaseUnitOfMeasureCode","purchaseOrderId",- "modelUploadId",- "quantityInvoiced",+ "exchangeRate",+ "jobId","ownerId",- "purchaseUnitOfMeasureCode"+ "quantityInvoiced",+ "modelUploadId",+ "supplierTaxAmount",+ "accountId",+ "supplierPartId",+ "requiredDate",+ "createdBy",+ "purchaseQuantity",+ "id",+ "quantityReceived",+ "updatedBy",+ "supplierShippingCost",+ "sortOrder",+ "customFields",+ "assetId",+ "companyId",+ "internalNotes",+ "promisedDate",+ "supplierUnitPrice",+ "purchaseOrderLineType",+ "itemId",+ "storageUnitId",+ "setupPrice",+ "locationId",+ "updatedAt",+ "quantityShipped",+ "taxPercent",+ "invoicedComplete",+ "costCenterId",+ "inventoryUnitOfMeasureCode",+ "jobOperationId",+ "receivedComplete"]},{"name": "nonConformancePurchaseOrderLine","rows": 0,"columns": [- "purchaseOrderReadableId",- "purchaseOrderId",- "purchaseOrderLineId",- "createdAt",- "id",- "updatedAt","companyId",- "nonConformanceId",+ "updatedAt",+ "id","updatedBy",- "createdBy"+ "createdBy",+ "nonConformanceId",+ "purchaseOrderReadableId",+ "createdAt",+ "purchaseOrderLineId",+ "purchaseOrderId"]},{"name": "purchaseOrderStatusHistory","rows": 0,"columns": [- "id",- "companyId",- "purchaseOrderId","createdBy","createdAt","status",- "updatedBy"+ "updatedBy",+ "id",+ "companyId",+ "purchaseOrderId"]},{"name": "purchaseOrderTransaction","rows": 0,"columns": [- "purchaseOrderId",- "companyId","id",- "type",+ "companyId",+ "purchaseOrderId",+ "createdAt","userId",- "createdAt"+ "type"]},{"name": "purchasingRfqSupplier","rows": 0,"columns": [- "createdAt",- "updatedBy",- "companyId",- "supplierId",- "createdBy",+ "purchasingRfqId","id",- "purchasingRfqId"+ "createdBy",+ "supplierId",+ "companyId",+ "updatedBy",+ "createdAt"]},{@@ -5393,172 +5450,173 @@{"name": "purchasingRfqToSupplierQuote","rows": 0,- "columns": ["purchasingRfqId", "supplierQuoteId", "companyId"]+ "columns": ["companyId", "supplierQuoteId", "purchasingRfqId"]},{"name": "quoteMakeMethod","rows": 0,"columns": [- "customFields",- "itemId",- "companyId","parentMaterialId","quoteLineId","version",- "quantityPerParent",+ "companyId",+ "itemId",+ "customFields",+ "tags",+ "quoteId",+ "createdAt",+ "updatedAt","id","createdBy","updatedBy",- "createdAt",- "updatedAt",- "quoteId",- "tags"+ "quantityPerParent"]},{"name": "quoteMaterial","rows": 0,"columns": [- "updatedBy",- "storageUnitId",- "createdBy",- "scrapQuantity",- "unitCost",- "quoteOperationId",- "methodType",- "tags",- "customFields",- "quoteMakeMethodId","quoteLineId","createdAt","itemId",- "kit",- "itemType",- "unitOfMeasureCode",- "description",- "id",- "quantity",- "order",+ "customFields",+ "quoteMakeMethodId",+ "unitCostSource",+ "methodType",+ "tags",+ "unitCost",+ "quoteOperationId",+ "updatedBy",+ "storageUnitId",+ "scrapQuantity",+ "createdBy",+ "updatedAt","quoteId","companyId",- "updatedAt"+ "order",+ "quantity",+ "description",+ "id",+ "unitOfMeasureCode",+ "itemType",+ "kit"]},{"name": "quoteMaterialStep","rows": 0,- "columns": ["quoteOperationStepId", "quoteMaterialId", "quantity"]+ "columns": ["quantity", "quoteOperationStepId", "quoteMaterialId"]},{"name": "quoteOperation","rows": 0,"columns": [- "machineUnit",- "machineRate",- "description",- "operationLeadTime",- "setupTime",- "companyId",- "quoteId",- "operationUnitCost",- "inspectionDocumentId",- "setupUnit",- "id",- "laborUnit",- "tags",- "procedureId",- "machineTime",- "operationSupplierProcessId",- "workInstruction",- "workCenterId",- "operationMinimumCost",- "laborRate",- "quoteLineId","quoteMakeMethodId",+ "quoteLineId",+ "laborRate","assemblyInstructionId","createdBy","updatedAt",- "createdAt",- "laborTime",- "overheadRate",- "customFields",+ "machineTime",+ "workCenterId",+ "workInstruction",+ "operationSupplierProcessId",+ "operationMinimumCost","processId",+ "updatedBy","operationType","operationOrder",- "updatedBy",- "order"+ "order",+ "laborTime",+ "createdAt",+ "overheadRate",+ "customFields",+ "companyId",+ "operationUnitCost",+ "quoteId",+ "inspectionDocumentId",+ "description",+ "machineRate",+ "machineUnit",+ "operationLeadTime",+ "setupTime",+ "id",+ "laborUnit",+ "tags",+ "procedureId",+ "setupUnit"]},{"name": "quoteOperationParameter","rows": 0,"columns": [- "operationId",- "value",- "createdBy",- "companyId",- "key",- "updatedAt",- "id",+ "createdAt","updatedBy",- "createdAt"+ "id",+ "updatedAt",+ "key",+ "companyId",+ "createdBy",+ "value",+ "operationId"]},{"name": "quoteOperationStep","rows": 0,"columns": [- "unitOfMeasureCode",- "description",- "required",- "createdAt",- "updatedBy",- "createdBy",- "operationId",- "sortOrder",+ "type",+ "fileTypes",+ "id",+ "maxValue","listValues","minValue","name","companyId","updatedAt",- "type",- "fileTypes",- "id",- "maxValue"+ "updatedBy",+ "createdBy",+ "operationId",+ "sortOrder",+ "unitOfMeasureCode",+ "description",+ "required",+ "createdAt"]},{"name": "quoteOperationStepSlide","rows": 0,"columns": [- "modelUploadId",- "stepId",- "createdAt",- "updatedAt",- "updatedBy",- "id",- "size",- "companyId","imagePath","caption","createdBy",+ "annotations","sortOrder",- "annotations"+ "stepId",+ "modelUploadId",+ "updatedAt",+ "createdAt",+ "size",+ "updatedBy",+ "id",+ "companyId"]},{"name": "quoteOperationTool","rows": 0,"columns": [- "createdAt",+ "operationId",+ "updatedAt","id","updatedBy",- "updatedAt",- "operationId",- "companyId",- "createdBy",+ "createdAt","quantity",- "toolId"+ "toolId",+ "createdBy",+ "companyId"]},{@@ -5570,56 +5628,56 @@"name": "receiptFixedAssetLine","rows": 0,"columns": [- "serialNumber",- "createdBy",- "purchaseOrderLineId",- "received",- "companyId","updatedAt","id",+ "companyId",+ "receiptId","createdAt","updatedBy",- "receiptId"+ "serialNumber",+ "purchaseOrderLineId",+ "received",+ "createdBy"]},{"name": "receiptLine","rows": 0,"columns": [- "requiresBatchTracking",- "unitPrice",- "createdBy",- "updatedBy",- "requiresSerialTracking",- "conversionFactor",- "itemId",- "lineId",- "createdAt",- "outstandingQuantity",+ "receiptId",+ "companyId",+ "updatedAt",+ "storageUnitId",+ "receivedQuantity","unitOfMeasure","id","locationId","orderQuantity",- "companyId",- "receiptId",- "updatedAt",- "storageUnitId",- "receivedQuantity"+ "conversionFactor",+ "requiresSerialTracking",+ "itemId",+ "createdAt",+ "lineId",+ "outstandingQuantity",+ "requiresBatchTracking",+ "unitPrice",+ "updatedBy",+ "createdBy"]},{"name": "nonConformanceReceiptLine","rows": 0,"columns": [- "receiptId","receiptLineId",+ "receiptId","createdAt","receiptReadableId","nonConformanceId",- "createdBy","updatedBy",- "id",+ "createdBy","updatedAt",+ "id","companyId"]},@@ -5627,96 +5685,96 @@"name": "salesInvoice","rows": 0,"columns": [- "internalNotes",+ "currencyCode",+ "exchangeRate",+ "companyId",+ "totalDiscount",+ "exchangeRateUpdatedAt",+ "customerReference",+ "createdAt",+ "dateDue","opportunityId","invoiceCustomerLocationId",+ "internalNotes","createdBy","customerId",- "status","locationId",- "totalAmount",+ "status","totalTax",- "companyId",- "totalDiscount",- "exchangeRate",- "currencyCode",- "exchangeRateUpdatedAt",- "dateDue",- "createdAt",- "customerReference",- "invoiceCustomerContactId",- "tags",- "externalNotes",- "postingDate",- "updatedAt",- "shipmentId",- "subtotal",- "updatedBy",- "invoiceId",- "datePaid",+ "totalAmount","invoiceCustomerId","assignee","id","paymentTermId","customFields",- "dateIssued"+ "dateIssued",+ "tags",+ "invoiceCustomerContactId",+ "externalNotes",+ "shipmentId",+ "updatedAt",+ "postingDate",+ "subtotal",+ "datePaid",+ "invoiceId",+ "updatedBy"]},{"name": "salesInvoiceLine","rows": 0,"columns": [- "id",- "assetId",+ "nonTaxableAddOnCost","opportunityId","unitOfMeasureCode",- "nonTaxableAddOnCost",- "methodType",+ "id",+ "assetId","internalNotes",- "setupPrice",- "invoiceId",- "updatedAt",+ "methodType","storageUnitId",- "customFields",- "salesOrderLineId",+ "updatedAt",+ "invoiceId",+ "setupPrice",+ "externalNotes","createdBy","quantity",- "externalNotes",+ "customFields",+ "salesOrderLineId",+ "itemId","companyId","locationId",- "itemId",+ "unitPrice","modelUploadId","addOnCost",- "unitPrice",- "description",- "exchangeRate",- "invoiceLineType",+ "taxPercent","sortOrder","shippingCost",- "taxPercent",- "salesOrderId",+ "description",+ "invoiceLineType",+ "exchangeRate",+ "createdAt","accountId","updatedBy",- "createdAt"+ "salesOrderId"]},{"name": "salesInvoiceShipment","rows": 0,"columns": [- "shippingTermId",- "incoterm",- "locationId",- "shippingMethodId",- "companyId",- "updatedBy",+ "shippingCost",+ "incotermLocation",+ "createdAt",+ "updatedAt","createdBy","id",+ "updatedBy","customFields",- "incotermLocation",- "shippingCost",- "updatedAt",- "createdAt"+ "locationId",+ "shippingMethodId",+ "companyId",+ "incoterm",+ "shippingTermId"]},{@@ -5724,21 +5782,21 @@"rows": 0,"columns": ["targetExchangeRate",- "writeOffAmount","id",+ "writeOffAmount","targetMemoId",- "paymentId","appliedDate",+ "paymentId","createdAt","sourceExchangeRate","discountAmount","targetPurchaseInvoiceId",- "appliedViaPaymentId","createdBy",+ "appliedViaPaymentId","updatedBy",+ "targetSalesInvoiceId","memoId","companyId",- "targetSalesInvoiceId","appliedAmount"]},@@ -5748,11 +5806,11 @@"columns": ["serialNumber","createdBy",- "shipped","salesOrderLineId",+ "shipped","companyId",- "id","updatedAt",+ "id","createdAt","updatedBy","shipmentId"@@ -5762,82 +5820,82 @@"name": "shipmentLine","rows": 0,"columns": [+ "fulfillmentId",+ "unitPrice",+ "companyId",+ "createdBy",+ "itemId","requiresBatchTracking","lineId",- "itemId","updatedBy","updatedAt","outstandingQuantity",- "unitPrice",- "fulfillmentId",- "companyId",- "createdBy",+ "id",+ "locationId",+ "unitOfMeasure",+ "orderQuantity","createdAt","requiresSerialTracking","shipmentId","shippedQuantity",- "storageUnitId",- "locationId",- "id",- "unitOfMeasure",- "orderQuantity"+ "storageUnitId"]},{"name": "nonConformanceShipmentLine","rows": 0,"columns": [- "id",+ "shipmentReadableId",+ "shipmentLineId",+ "shipmentId",+ "createdAt","updatedAt",+ "id","companyId","nonConformanceId","updatedBy",- "createdBy",- "shipmentReadableId",- "shipmentId",- "shipmentLineId",- "createdAt"+ "createdBy"]},{"name": "supplier","rows": 0,"columns": [- "defaultCc",- "accountManagerId",- "createdBy",- "supplierStatus",- "companyId",- "id","createdAt","assignee","readableId",- "updatedBy","name",+ "updatedBy","phone",- "taxPercent",- "currencyCode",- "fax",- "updatedAt",- "tags",- "embedding",- "logo",- "purchasingContactId",+ "defaultCc",+ "accountManagerId",+ "supplierStatus",+ "createdBy",+ "id",+ "companyId","intercompanyCompanyId",+ "purchasingContactId",+ "logo","website","supplierTypeId",- "customFields"+ "customFields",+ "fax",+ "taxPercent",+ "currencyCode",+ "tags",+ "updatedAt",+ "embedding"]},{"name": "supplierAccount","rows": 0,- "columns": ["active", "companyId", "supplierId", "id"]+ "columns": ["active", "companyId", "id", "supplierId"]},{"name": "supplierInteraction","rows": 0,- "columns": ["companyId", "supplierId", "id"]+ "columns": ["supplierId", "id", "companyId"]},{"name": "receipt",@@ -5846,369 +5904,372 @@"supplierId","postingDate","updatedAt",- "receiptId","companyId",+ "receiptId","sourceDocumentReadableId",- "id","status",+ "id","invoiced","externalDocumentId",- "sourceDocument",- "locationId","createdAt",- "customFields",- "tags",- "updatedBy",- "createdBy",- "supplierInteractionId",- "postedBy",- "internalNotes",- "assignee",- "sourceDocumentId"- ]- },- {- "name": "shipment",- "rows": 0,- "columns": [- "sourceDocumentReadableId",- "supplierId",- "customerId",- "id",- "postingDate",- "externalDocumentId",- "trackingNumber",- "status",- "customFields",- "externalNotes",- "shipmentId",- "invoiced",- "opportunityId",+ "locationId",+ "sourceDocument",+ "tags",+ "customFields",+ "createdBy","supplierInteractionId",- "updatedAt",- "internalNotes","updatedBy","postedBy",- "createdBy","sourceDocumentId",+ "assignee",+ "internalNotes"+ ]+ },+ {+ "name": "shipment",+ "rows": 0,+ "columns": ["shippingMethodId","tags",- "assignee","locationId",+ "assignee","sourceDocument","companyId",- "createdAt"+ "createdAt",+ "opportunityId",+ "supplierInteractionId",+ "internalNotes",+ "updatedAt",+ "updatedBy",+ "postedBy",+ "createdBy",+ "sourceDocumentId",+ "trackingNumber",+ "status",+ "customFields",+ "externalNotes",+ "shipmentId",+ "invoiced",+ "sourceDocumentReadableId",+ "supplierId",+ "customerId",+ "id",+ "postingDate",+ "externalDocumentId"]},{"name": "supplierLedger","rows": 0,"columns": [- "entryNumber",- "createdAt",- "amount",- "companyId",- "id",- "externalDocumentId",+ "documentId","postingDate","documentType","supplierId",- "documentId"+ "companyId",+ "id",+ "externalDocumentId",+ "entryNumber",+ "amount",+ "createdAt"]},{"name": "supplierLocation","rows": 0,"columns": [+ "name",+ "addressId",+ "customFields","tags","id","companyId",- "supplierId",- "name",- "addressId",- "customFields"+ "supplierId"]},{"name": "supplierContact","rows": 0,"columns": [- "supplierId",- "companyId","id","customFields",- "contactId",+ "supplierId",+ "companyId",+ "userId","supplierLocationId",- "tags",- "userId"+ "contactId",+ "tags"]},{"name": "purchaseInvoice","rows": 0,"columns": [- "createdAt",- "invoiceSupplierId",- "updatedAt",- "exchangeRate",- "id",- "paymentTermId",- "currencyCode",- "createdBy",- "internalNotes","invoiceSupplierContactId",+ "internalNotes","supplierInteractionId",- "invoiceId",- "status",- "dateIssued",+ "createdBy",+ "currencyCode","subtotal",- "updatedBy",- "totalDiscount",- "assignee",- "datePaid",- "postingDate",- "exchangeRateUpdatedAt",- "supplierReference",- "companyId",- "locationId",- "tags",+ "dateIssued",+ "status",+ "invoiceId",+ "invoiceSupplierId",+ "createdAt",+ "id",+ "paymentTermId",+ "updatedAt",+ "exchangeRate","customFields","invoiceSupplierLocationId",- "totalAmount",- "totalTax",+ "tags",+ "locationId","supplierId",- "dateDue"+ "dateDue",+ "totalTax",+ "totalAmount",+ "datePaid",+ "assignee",+ "updatedBy",+ "totalDiscount",+ "companyId",+ "supplierReference",+ "exchangeRateUpdatedAt",+ "postingDate"]},{"name": "purchaseOrder","rows": 0,"columns": [+ "currencyCode",+ "closedBy",+ "createdAt",+ "externalNotes",+ "status",+ "assignee",+ "updatedBy",+ "exchangeRate",+ "exchangeRateUpdatedAt",+ "purchaseOrderType",+ "updatedAt",+ "createdBy",+ "revisionId",+ "closedAt","internalNotes","orderDate","supplierReference","supplierInteractionId","supplierLocationId","id",- "supplierContactId","tags",+ "supplierContactId","jobId","supplierId","jobReadableId",- "purchaseOrderId","companyId",- "customFields",- "createdAt",- "externalNotes",- "closedBy",- "currencyCode",- "assignee",- "updatedBy",- "status",- "exchangeRate",- "purchaseOrderType",- "exchangeRateUpdatedAt",- "createdBy",- "updatedAt",- "revisionId",- "closedAt"+ "purchaseOrderId",+ "customFields"]},{"name": "purchaseInvoiceLine","rows": 0,"columns": [- "tags",- "modelUploadId",- "createdAt",- "supplierTaxAmount",- "exchangeRate",- "sortOrder",- "inventoryUnitOfMeasureCode","costCenterId","invoiceLineType","quantity","purchaseOrderId",+ "exchangeRate",+ "sortOrder",+ "inventoryUnitOfMeasureCode",+ "tags",+ "modelUploadId",+ "createdAt",+ "supplierTaxAmount",+ "taxPercent",+ "createdBy",+ "assetId",+ "purchaseUnitOfMeasureCode",+ "purchaseOrderLineId",+ "jobOperationId","ownerId","customFields","accountId",- "companyId","supplierUnitPrice",- "jobOperationId",- "assetId",- "purchaseUnitOfMeasureCode",- "purchaseOrderLineId",- "taxPercent",- "createdBy",- "storageUnitId",- "supplierShippingCost",- "updatedBy",- "internalNotes",- "serviceId",+ "companyId",+ "requiredDate","invoiceId","description",- "requiredDate",- "updatedAt",- "itemId",- "conversionFactor",+ "internalNotes",+ "serviceId",+ "supplierShippingCost",+ "storageUnitId",+ "updatedBy","locationId",- "id"+ "id",+ "conversionFactor",+ "itemId",+ "updatedAt"]},{"name": "purchaseInvoicePriceChange","rows": 0,"columns": [- "newPrice",- "invoiceLineId",- "previousPrice",- "newQuantity",+ "updatedBy",+ "invoiceId",+ "previousQuantity","companyId","id",- "previousQuantity",- "invoiceId",- "updatedBy"+ "newQuantity",+ "invoiceLineId",+ "previousPrice",+ "newPrice"]},{"name": "purchaseOrderPayment","rows": 0,"columns": [+ "invoiceSupplierLocationId",+ "invoiceSupplierContactId","paymentTermId","tags",- "invoiceSupplierContactId",- "invoiceSupplierLocationId",- "paymentComplete",- "id",- "updatedAt",- "customFields",- "companyId",+ "invoiceSupplierId","updatedBy",- "invoiceSupplierId"+ "companyId",+ "customFields",+ "updatedAt",+ "id",+ "paymentComplete"]},{"name": "supplierPart","rows": 0,"columns": [- "updatedBy",- "supplierUnitOfMeasureCode",- "orderMultiple",- "unitPrice",- "supplierPartId",- "customFields","supplierId",+ "customFields",+ "supplierPartId","conversionFactor",- "createdAt",- "id",- "companyId",- "minimumOrderQuantity",- "itemId",- "updatedAt",+ "supplierUnitOfMeasureCode",+ "updatedBy",+ "unitPrice",+ "orderMultiple","tags",+ "updatedAt",+ "itemId",+ "active","createdBy",- "active"+ "companyId",+ "id",+ "createdAt",+ "minimumOrderQuantity"]},{"name": "supplierPartPrice","rows": 0,"columns": [- "companyId",- "leadTime",- "updatedBy",- "supplierPartId",+ "createdBy",+ "unitPrice",+ "sourceType",+ "sourceDocumentId","updatedAt","createdAt","quantity",- "sourceDocumentId",- "createdBy",- "unitPrice",- "sourceType"+ "companyId",+ "leadTime",+ "updatedBy",+ "supplierPartId"]},{"name": "supplierPayment","rows": 0,"columns": [- "invoiceSupplierId",- "customFields",- "updatedAt",- "tags",- "updatedBy",- "supplierId",- "invoiceSupplierLocationId",+ "paymentTermId","invoiceSupplierContactId",+ "invoiceSupplierLocationId","companyId",- "paymentTermId"+ "supplierId",+ "updatedBy",+ "tags",+ "invoiceSupplierId",+ "updatedAt",+ "customFields"]},{"name": "supplierProcess","rows": 0,"columns": [- "updatedAt",- "processId",- "minimumCost",- "companyId",+ "supplierId",+ "tags",+ "createdAt",+ "customFields","updatedBy","createdBy","id","leadTime",- "supplierId",- "tags",- "createdAt",- "customFields"+ "processId",+ "minimumCost",+ "companyId",+ "updatedAt"]},{"name": "supplierQuote","rows": 0,"columns": [- "supplierContactId",- "supplierId",- "id",- "supplierQuoteType",- "status",- "assignee",- "supplierQuoteId",- "exchangeRateUpdatedAt",- "supplierInteractionId",- "supplierLocationId",- "externalNotes",+ "tags",+ "customFields",+ "quotedDate",+ "currencyCode",+ "revisionId",+ "updatedBy",+ "internalNotes","expirationDate",- "supplierReference","createdAt",+ "supplierReference","updatedAt","createdBy","exchangeRate",- "companyId","externalLinkId",- "tags",- "customFields",- "revisionId",- "currencyCode",- "quotedDate",- "internalNotes",- "updatedBy"+ "companyId",+ "assignee",+ "supplierQuoteId",+ "exchangeRateUpdatedAt",+ "supplierInteractionId",+ "supplierLocationId",+ "externalNotes",+ "supplierContactId",+ "id",+ "supplierId",+ "supplierQuoteType",+ "status"]},{"name": "supplierQuoteFavorite","rows": 0,- "columns": ["supplierQuoteId", "userId"]+ "columns": ["userId", "supplierQuoteId"]},{"name": "supplierQuoteLine","rows": 0,"columns": [- "updatedBy",- "customFields",- "supplierQuoteRevisionId",- "quantity",- "sortOrder",- "description",- "costCenterId",+ "purchaseUnitOfMeasureCode",+ "ownerId",+ "supplierPartRevision",+ "id",+ "supplierQuoteLineType",+ "supplierQuoteId",+ "createdBy",+ "inventoryUnitOfMeasureCode",+ "accountId",+ "supplierPartId","conversionFactor","tags","itemId",@@ -6217,174 +6278,170 @@"requiredDate","internalNotes","companyId",- "supplierQuoteId",- "createdBy",- "inventoryUnitOfMeasureCode",- "accountId",- "supplierPartId",- "purchaseUnitOfMeasureCode",- "ownerId",- "supplierPartRevision",- "id",- "supplierQuoteLineType"+ "updatedBy",+ "customFields",+ "supplierQuoteRevisionId",+ "quantity",+ "sortOrder",+ "description",+ "costCenterId"]},{"name": "supplierQuoteLinePrice","rows": 0,"columns": [- "exchangeRate",- "taxPercent",- "supplierQuoteId",- "supplierShippingCost",- "companyId",- "createdBy",- "supplierQuoteLineId",- "supplierTaxAmount",- "updatedBy",- "supplierUnitPrice",- "createdAt","leadTime",+ "quantity","updatedAt",- "quantity"+ "createdAt",+ "supplierUnitPrice",+ "updatedBy",+ "supplierQuoteLineId",+ "createdBy",+ "supplierTaxAmount",+ "supplierShippingCost",+ "companyId",+ "taxPercent",+ "supplierQuoteId",+ "exchangeRate"]},{"name": "supplierShipping","rows": 0,"columns": [- "shippingSupplierLocationId",- "shippingSupplierContactId",- "companyId",- "shippingTermId",- "incoterm",+ "supplierId",+ "updatedBy",+ "tags",+ "shippingMethodId","incotermLocation","shippingSupplierId",- "customFields","updatedAt",- "tags",- "updatedBy",- "supplierId",- "shippingMethodId"+ "customFields",+ "shippingTermId",+ "incoterm",+ "shippingSupplierContactId",+ "shippingSupplierLocationId",+ "companyId"]},{"name": "supplierTax","rows": 0,"columns": [+ "taxExempt","taxExemptionCertificateNumber","eori","vatNumber",- "taxExempt",- "updatedAt",- "taxExemptionCertificatePath",- "taxId","taxExemptionReason",- "updatedBy","supplierId",- "companyId"+ "companyId",+ "updatedBy",+ "taxExemptionCertificatePath",+ "updatedAt",+ "taxId"]},{"name": "workflow","rows": 0,"columns": [- "description",- "name",- "activeVersionId",- "updatedBy",- "ownerId",- "companyId",- "updatedAt","nextRunAt","createdBy",+ "updatedAt",+ "companyId","id","canvasState","createdAt",- "active"+ "publishedVersionId",+ "description",+ "name",+ "ownerId",+ "updatedBy"]},{"name": "workflowVersion","rows": 0,"columns": [- "formatVersion",- "edges",- "workflowId",- "versionNumber",+ "createdBy",+ "updatedBy",+ "companyId","nodes",- "updatedAt",- "createdAt","id",- "updatedBy",- "createdBy",- "companyId"+ "createdAt",+ "updatedAt",+ "edges",+ "versionNumber",+ "workflowId",+ "formatVersion"]},{"name": "workflowRun","rows": 0,"columns": [- "createdAt",- "eventId",- "isTest",- "error",- "depth",- "compactedAt",- "startedAt",+ "path",+ "rootRunId",+ "companyId",+ "triggerRecordId",+ "status",+ "ownerId",+ "id",+ "statusReason",+ "sourceEventId","workflowId","causedByRunId","workflowVersionId","durationMs","completedAt","triggerTable",- "ownerId",- "id",- "statusReason",- "sourceEventId",- "path",- "rootRunId",- "companyId",- "triggerRecordId",- "status"+ "createdAt",+ "eventId",+ "isTest",+ "error",+ "compactedAt",+ "depth",+ "startedAt"]},{"name": "workflowStepRun","rows": 0,"columns": [- "nodeId",- "branchTaken",- "durationMs",- "compactedAt",- "sequence",- "completedAt",- "runId",- "detail",- "createdAt",- "itemKey",+ "output","id","statusReason",- "output","nodeType",- "error","startedAt","companyId",+ "error",+ "input","status",- "input"+ "nodeId",+ "branchTaken",+ "durationMs",+ "compactedAt",+ "detail",+ "createdAt",+ "sequence",+ "runId",+ "completedAt",+ "itemKey"]},{"name": "workflowTriggerEvent","rows": 0,"columns": [- "workflowId",- "workflowVersionId",- "createdAt",- "eventId",- "companyId",+ "origin","id",- "origin"+ "companyId",+ "eventId",+ "createdAt",+ "workflowId",+ "workflowVersionId"]}],@@ -6396,6 +6453,5 @@"oauthClient","oauthToken","webhook"- ],- "excludedRows": []+ ]}diff --git a/packages/jobs/src/backups/renames.ts b/packages/jobs/src/backups/renames.tsindex 45284492b0..fe0af38b63 100644--- a/packages/jobs/src/backups/renames.ts+++ b/packages/jobs/src/backups/renames.ts@@ -8,9 +8,16 @@* was a rename silently discards a customer's rows while reporting success —* so an unmapped missing table refuses the restore and names itself.*- * Starts EMPTY on purpose: a wrong historical mapping is worse than none.+ * Entries are added only with certainty: a wrong historical mapping is worse+ * than none.*/-export const TABLE_RENAMES: Record<string, string | null> = {};+export const TABLE_RENAMES: Record<string, string | null> = {+ // Dropped 2026-09 (currency/exchange-rate refactor): the group-scoped daily+ // rate table never had a writer and held zero rows everywhere; replaced by+ // the platform-global "exchangeRate" table, which is not tenant-scoped and+ // therefore never appears in a backup.+ exchangeRateHistory: null+};/*** Move a just-read backup's tables onto their CURRENT names. Runs once, rightdiff --git a/packages/jobs/src/inngest/functions/integrations/paperless-parts.ts b/packages/jobs/src/inngest/functions/integrations/paperless-parts.tsindex 280409ebf8..3b83f58bd3 100644--- a/packages/jobs/src/inngest/functions/integrations/paperless-parts.ts+++ b/packages/jobs/src/inngest/functions/integrations/paperless-parts.ts@@ -318,13 +318,20 @@ export const paperlessPartsFunction = inngest.createFunction(} = quoteCustomerShipping.data;if (quote.currencyCode) {- const currency = await getCurrencyByCode(- carbon,- company.data.companyGroupId!,- quote.currencyCode- );- if (currency.data) {- quote.exchangeRate = currency.data.exchangeRate ?? undefined;+ const exchangeRate = await carbon.rpc("get_exchange_rate", {+ p_company_id: payload.companyId,+ p_currency_code: quote.currencyCode+ });+ if (exchangeRate.error) {+ logger.warn(+ "Failed to resolve exchange rate for imported quote, keeping default",+ {+ currencyCode: quote.currencyCode,+ error: exchangeRate.error+ }+ );+ } else if (exchangeRate.data !== null) {+ quote.exchangeRate = exchangeRate.data;quote.exchangeRateUpdatedAt = new Date().toISOString();}} else {@@ -806,19 +813,6 @@ async function getCustomerShipping(.single();}-async function getCurrencyByCode(- client: SupabaseClient<Database>,- companyGroupId: string,- currencyCode: string-) {- return client- .from("currency")- .select("exchangeRate")- .eq("companyGroupId", companyGroupId)- .eq("code", currencyCode)- .single();-}-async function deleteQuote(client: SupabaseClient<Database>, quoteId: string) {return client.from("quote").delete().eq("id", quoteId);}diff --git a/packages/jobs/src/inngest/functions/scheduled/update-exchange-rates.test.ts b/packages/jobs/src/inngest/functions/scheduled/update-exchange-rates.test.tsnew file mode 100644index 0000000000..fef0bb3b71--- /dev/null+++ b/packages/jobs/src/inngest/functions/scheduled/update-exchange-rates.test.ts@@ -0,0 +1,86 @@+import { describe, expect, it, vi } from "vitest";+import { buildExchangeRateRows } from "./update-exchange-rates";++// buildExchangeRateRows is pure, but its module's neighbors are not:+// @carbon/env validates required vars at module scope and+// @carbon/auth/client.server pulls it in too. vi.mock hoists above the+// imports, so the module under test never needs a configured environment.+vi.mock("@carbon/env", () => ({ EXCHANGE_RATES_API_KEY: undefined }));+vi.mock("@carbon/auth/client.server", () => ({+ getCarbonServiceRole: vi.fn()+}));++const EFFECTIVE_DATE = "2026-09-02";+const UPDATED_AT = "2026-09-02T00:00:00.000Z";++const build = (+ ratesEur: { [code: string]: number | undefined },+ codes: string[]+) => buildExchangeRateRows(ratesEur, codes, EFFECTIVE_DATE, UPDATED_AT);++describe("buildExchangeRateRows", () => {+ it("anchors on USD: 1 USD is exactly 1", () => {+ const { rows } = build({ USD: 1.086, EUR: 1 }, ["USD"]);+ expect(rows).toEqual([+ {+ currencyCode: "USD",+ effectiveDate: EFFECTIVE_DATE,+ rate: 1,+ updatedAt: UPDATED_AT+ }+ ]);+ });++ it("re-bases the EUR feed to units per 1 USD at internal scale", () => {+ // Feed is EUR-based, so EUR itself becomes 1 / feed[USD]+ const { rows } = build({ USD: 1.086, EUR: 1, GBP: 0.86 }, ["EUR", "GBP"]);+ expect(rows.map((r) => [r.currencyCode, r.rate])).toEqual([+ ["EUR", 0.92081], // 1 / 1.086+ ["GBP", 0.7919] // 0.86 / 1.086+ ]);+ });++ it("partitions codes missing from the feed into staleCodes", () => {+ const { rows, staleCodes } = build({ USD: 1.086 }, ["USD", "XYZ", "ABC"]);+ expect(rows.map((r) => r.currencyCode)).toEqual(["USD"]);+ expect(staleCodes).toEqual(["XYZ", "ABC"]);+ });++ it("does not warn about obsolete codes no live feed quotes", () => {+ const { rows, staleCodes } = build({ USD: 1.086 }, [+ "USD",+ "VEF",+ "ZMK",+ "XYZ"+ ]);+ expect(rows.map((r) => r.currencyCode)).toEqual(["USD"]);+ expect(staleCodes).toEqual(["XYZ"]);+ });++ it("filters non-finite, zero, and negative feed values", () => {+ const { rows, staleCodes } = build(+ { USD: 1.086, AAA: 0, BBB: -2, CCC: Number.NaN, DDD: Infinity },+ ["USD", "AAA", "BBB", "CCC", "DDD"]+ );+ expect(rows.map((r) => r.currencyCode)).toEqual(["USD"]);+ expect(staleCodes).toEqual(["AAA", "BBB", "CCC", "DDD"]);+ });++ it("stamps every row with the given effectiveDate and updatedAt", () => {+ const { rows } = build({ USD: 1.086, EUR: 1 }, ["USD", "EUR"]);+ for (const row of rows) {+ expect(row.effectiveDate).toBe(EFFECTIVE_DATE);+ expect(row.updatedAt).toBe(UPDATED_AT);+ }+ });++ it("throws when the feed has no usable USD quote to anchor on", () => {+ // A partial payload may succeed on retry, so this must be a throw+ expect(() => build({ EUR: 1, GBP: 0.86 }, ["EUR"])).toThrow(+ "USD rate missing from feed"+ );+ expect(() => build({ USD: 0, EUR: 1 }, ["EUR"])).toThrow(+ "USD rate missing from feed"+ );+ });+});diff --git a/packages/jobs/src/inngest/functions/scheduled/update-exchange-rates.ts b/packages/jobs/src/inngest/functions/scheduled/update-exchange-rates.tsindex 94ed2cbd07..8ebab0d0e7 100644--- a/packages/jobs/src/inngest/functions/scheduled/update-exchange-rates.ts+++ b/packages/jobs/src/inngest/functions/scheduled/update-exchange-rates.ts@@ -1,243 +1,194 @@import { getCarbonServiceRole } from "@carbon/auth/client.server";-import type { Rates } from "@carbon/ee/exchange-rates.server";-import { getExchangeRatesClient } from "@carbon/ee/exchange-rates.server";import { EXCHANGE_RATES_API_KEY } from "@carbon/env";-import { round } from "@carbon/utils";+import { datetime, round } from "@carbon/utils";import { inngest } from "../../client";-type CurrencyCode =- | "EUR"- | "USD"- | "GBP"- | "JPY"- | "CHF"- | "CAD"- | "AUD"- | "CNY"- | "INR"- | "MXN"- | "BRL"- | "RUB"- | "ZAR"- | "TRY"- | "SEK"- | "NOK"- | "DKK"- | "SGD"- | "HKD"- | "TWD"- | "THB"- | "MYR"- | "PHP"- | "IDR"- | "VND"- | "KRW"- | "TND"- | "MAD"- | "AED"- | "SAR"- | "QAR"- | "KWD"- | "BHD"- | "OMR"- | "JOD"- | "LYD"- | "EGP"- | "ILS"- | "KZT"- | "KGS"- | "UZS"- | "TJS"- | "AZN"- | "TMT"- | "UYU"- | "BYN"- | "KZT"- | "KGS"- | "UZS"- | "TJS"- | "AZN"- | "TMT"- | "UYU"- | "BYN"- | "KZT"- | "KGS"- | "UZS"- | "TJS"- | "AZN"- | "TMT"- | "UYU"- | "BYN";+type CurrencyCode = string;++type Rates = { [key in CurrencyCode]?: number };++type ExchangeRatesSuccessResponse = {+ success: boolean;+ timestamp: number;+ base: CurrencyCode;+ date: string;+ rates: Rates;+};++type ExchangeRatesErrorResponse = {+ error: {+ code: string;+ message: string;+ };+};++type ExchangeRatesResponse =+ | ExchangeRatesErrorResponse+ | ExchangeRatesSuccessResponse;++/**+ * Fetches the latest exchange rates from the API. For the free tier of the+ * API, we can only fetch the rates with a base currency of EUR.+ */+async function fetchEurRates(+ apiKey: string,+ apiUrl = "https://api.exchangeratesapi.io/v1/latest"+): Promise<Rates> {+ const response = await fetch(`${apiUrl}?access_key=${apiKey}`);++ if (!response.ok) {+ throw new Error(`HTTP error! status: ${response.status}`);+ }++ const data: ExchangeRatesResponse = await response.json();++ if ("success" in data && data.success === true && data.rates) {+ return data.rates;+ }++ throw new Error("Unrecognized response from exchange rates server");+}++/** Codes retired or redenominated — no live feed quotes them, so their+ * absence is expected and not worth a warning. */+const OBSOLETE_CURRENCY_CODES = new Set([+ "VEF",+ "ZMK",+ "LTL",+ "LVL",+ "HRK",+ "ZWL"+]);++type ExchangeRateRow = {+ currencyCode: string;+ effectiveDate: string;+ rate: number;+ updatedAt: string;+};++/**+ * Anchors the EUR-based feed on USD (rate = units of currencyCode per 1 USD)+ * and partitions the known codes into upsertable rows and stale codes.+ * Throws when the feed has no usable USD quote — a partial payload may+ * succeed on retry.+ */+export function buildExchangeRateRows(+ ratesEur: Rates,+ codes: string[],+ effectiveDate: string,+ updatedAt: string+): { rows: ExchangeRateRow[]; staleCodes: string[] } {+ const usd = Number(ratesEur["USD"]);+ if (!Number.isFinite(usd) || usd <= 0) {+ throw new Error("USD rate missing from feed, cannot anchor to USD");+ }++ const rows: ExchangeRateRow[] = [];+ const staleCodes: string[] = [];++ for (const code of codes) {+ const feedRate = ratesEur[code];+ // Rates carry internal scale — never the currency's DISPLAY+ // decimals, which zeroed every 0-decimal currency's fraction and+ // silently froze rates that rounded to 0+ const rate =+ feedRate === undefined ? Number.NaN : round(Number(feedRate) / usd);+ if (!Number.isFinite(rate) || rate <= 0) {+ if (!OBSOLETE_CURRENCY_CODES.has(code)) {+ staleCodes.push(code);+ }+ continue;+ }+ rows.push({ currencyCode: code, effectiveDate, rate, updatedAt });+ }++ return { rows, staleCodes };+}export const updateExchangeRatesFunction = inngest.createFunction({ id: "update-exchange-rates", retries: 2 },{ cron: "0 0 * * *" },async ({ step, logger }) => {- const serviceRole = getCarbonServiceRole();await step.run("fetch-and-update-exchange-rates", async () => {- logger.info("Exchange rates task started");- const integrations = await serviceRole- .from("companyIntegration")- .select("active, companyId")- .eq("id", "exchange-rates-v1")- .eq("active", true);-- if (integrations.error) {- logger.error("Error fetching integrations", {- error: integrations.error- });+ if (!EXCHANGE_RATES_API_KEY) {+ logger.info(+ "EXCHANGE_RATES_API_KEY is not configured, skipping exchange rate update"+ );return;}- if (integrations.data?.length === 0) {- logger.info("No active exchange rate integrations found, exiting task");- return;+ // Fetch the exchange rates once, with the free tier's base currency of EUR+ let ratesEur: Rates;+ try {+ ratesEur = await fetchEurRates(EXCHANGE_RATES_API_KEY);+ } catch (error) {+ logger.error("Error fetching exchange rates", { error });+ throw new Error(+ `Error fetching exchange rates: ${(error as Error).message}`+ );}+ logger.info(+ "Successfully fetched exchange rates with base currency EUR",+ {+ currencyCount: Object.keys(ratesEur).length+ }+ );- logger.info("Found active integrations", {- count: integrations.data.length- });+ const serviceRole = getCarbonServiceRole();- // Fetch the exchange rates for the base currency of EUR- const exchangeRatesClient = getExchangeRatesClient(- EXCHANGE_RATES_API_KEY- );+ // Reference table — no tenancy+ const currencyCodes = await serviceRole+ .from("currencyCode")+ .select("code");- if (!exchangeRatesClient) {- logger.error(- "Exchange rates client is undefined, check API key configuration"+ if (currencyCodes.error) {+ logger.error("Error fetching currency codes", {+ error: currencyCodes.error+ });+ throw new Error(+ `Error fetching currency codes: ${currencyCodes.error.message}`);- return;}- let ratesEUR: Rates;- try {- ratesEUR = await exchangeRatesClient.getExchangeRates();- if (!ratesEUR)- throw new Error("No rates returned from exchange rates API");- logger.info(- "Successfully fetched exchange rates with base currency EUR",- {- currencyCount: Object.keys(ratesEUR).length- }- );- } catch (error) {- logger.error("Error fetching exchange rates", { error });- return;- }+ const updatedAt = datetime.timestamp();+ // The feed is a UTC-day artifact, so the UTC day is the effective date+ const effectiveDate = updatedAt.slice(0, 10);- // Cache the rates for each currency to avoid unnecessary computations- let cachedRates: { [key in CurrencyCode]?: Rates } = {- EUR: ratesEUR- };+ const { rows, staleCodes } = buildExchangeRateRows(+ ratesEur,+ (currencyCodes.data ?? []).map(({ code }) => code),+ effectiveDate,+ updatedAt+ );- for (const integration of integrations.data) {- logger.info("Processing integration for company", {- companyId: integration.companyId- });+ if (staleCodes.length > 0) {+ logger.warn(+ "Currency codes absent from the feed (or with unusable rates) — their stored rates are going stale",+ { codes: staleCodes }+ );+ }- const company = await serviceRole- .from("company")- .select("*")- .eq("id", integration.companyId)- .single();-- if (company.error) {- logger.error("Error fetching company", {- companyId: integration.companyId,- error: company.error- });- continue;- }+ if (rows.length === 0) {+ logger.info("No exchange rates to upsert");+ return;+ }- const baseCurrencyCode = company.data.baseCurrencyCode as CurrencyCode;- let rates: Rates | undefined;- rates = cachedRates[baseCurrencyCode];- // Check if the rates for this base currency are cached, and if not compute them- if (rates) {- logger.info("Using cached rates", { baseCurrencyCode });- } else {- logger.info("Computing rates", { baseCurrencyCode });- rates = await exchangeRatesClient.convertExchangeRates(- baseCurrencyCode,- ratesEUR- );- cachedRates[baseCurrencyCode] = rates;- }+ const { error: upsertError } = await serviceRole+ .from("exchangeRate")+ .upsert(rows, { onConflict: "currencyCode,effectiveDate" });- const updatedAt = new Date().toISOString();-- try {- if (!company.data.companyGroupId) {- logger.warn("Company has no companyGroupId, skipping", {- companyId: integration.companyId- });- continue;- }- const { data, error } = await serviceRole- .from("currency")- .select("*")- .eq("companyGroupId", company.data.companyGroupId);-- if (error) {- logger.error("Error fetching currencies for company", {- companyId: integration.companyId,- error- });- continue;- }-- if (!data || data.length === 0) {- logger.info("No currencies found for company", {- companyId: integration.companyId- });- continue;- }-- const updates = data- .map((currency) => ({- ...currency,- // Rates carry internal scale — never the currency's DISPLAY- // decimals, which zeroed every 0-decimal currency's fraction and- // silently froze rates that rounded to 0- exchangeRate: round(Number(rates[currency.code as CurrencyCode])),- updatedAt- }))- .filter((currency) => currency.exchangeRate);-- if (updates.length === 0) {- logger.info("No currency updates needed for company", {- companyId: integration.companyId- });- continue;- }-- logger.info("Updating currencies for company", {- count: updates.length,- companyId: integration.companyId- });- const { error: upsertError } = await serviceRole- .from("currency")- .upsert(updates);- if (upsertError) {- logger.error("Error updating currencies for company", {- companyId: integration.companyId,- error: upsertError- });- } else {- logger.info("Successfully updated currencies for company", {- companyId: integration.companyId- });- }- } catch (err) {- logger.error("Unexpected error processing company", {- companyId: integration.companyId,- error: err- });- }+ if (upsertError) {+ logger.error("Error upserting exchange rates", { error: upsertError });+ throw new Error(+ `Error upserting exchange rates: ${upsertError.message}`+ );}- logger.info("Exchange rates task completed");+ logger.info("Exchange rates task completed", {+ count: rows.length,+ effectiveDate+ });});});diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 21a3dd9186..d64dfea05f 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -2624,6 +2624,9 @@ msgstr "Aufwendungen für Bank- und Finanzservicegebühren"msgid "Bars show each week's flow: <0>supply</0> pushes inventory up, <1>demand</1> pulls it down. The <2>line</2> is your projected on-hand inventory — when it dips below <3>safety stock</3> you're at risk, and below zero is a <4>stockout</4>."msgstr "Balken zeigen den wöchentlichen Fluss: <0>Deckung</0> erhöht den Bestand, <1>Bedarf</1> senkt ihn. Die <2>Linie</2> ist Ihr geplanter verfügbarer Bestand — wenn er unter <3>Sicherheitsbestand</3> fällt, sind Sie gefährdet, und unter Null ist ein <4>Fehlbestand</4>."+msgid "Base currency"+msgstr "Basiswährung"+msgid "Base Currency"msgstr "Basiswährung"@@ -3215,6 +3218,9 @@ msgstr "Das Ändern aktualisiert die Teile-ID"msgid "Changing type resets this item's draft edits."msgstr "Das Ändern des Typs setzt die Entwurfsbearbeitungen dieses Elements zurück."+msgid "Chart"+msgstr "Diagramm"+msgid "Chart of accounts"msgstr "Kontenplan"@@ -9422,6 +9428,15 @@ msgstr "Als kurz markieren"msgid "Mark to delete"msgstr "Zum Löschen markieren"+msgid "Market rate"+msgstr "Marktkurs"++msgid "Market rate (per USD)"+msgstr "Marktkurs (pro USD)"++msgid "Market Rate History (per USD)"+msgstr "Marktkursverlauf (pro USD)"+msgid "Marks the person off for every day in the range. They won't be scheduled while they're away."msgstr "Markiert die Person für jeden Tag im Bereich als frei. Sie werden nicht eingeplant, während sie weg sind."@@ -9970,6 +9985,9 @@ msgstr "Neue Kostenstelle"msgid "New Credit / Debit Memo"msgstr "Neue Haben-/Soll-Buchung"+msgid "New Currency"+msgstr "Neue Währung"+msgid "New Custom Field"msgstr "Neues benutzerdefiniertes Feld"@@ -10601,6 +10619,9 @@ msgstr "Kein Angebotgrund"msgid "No Quote Reasons"msgstr "Keine Angebotsgründe"+msgid "No rate"+msgstr "Kein Kurs"+msgid "No receivables"msgstr "Keine Forderungen"@@ -10966,6 +10987,11 @@ msgstr "Pünktliche Lieferung"msgid "Onboard your agent to Carbon"msgstr "Ihren Agenten bei Carbon registrieren"+#. placeholder {0}: company?.baseCurrencyCode+#. placeholder {1}: initialValues.code+msgid "One {0} is equal to how many {1}?"+msgstr "1 {0} entspricht wie vielen {1}?"+msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."msgstr "Ein Workflow-Durchlauf, aufgezeichnet Schritt für Schritt mit den Werten, die jeder Schritt verwendet und erzeugt, ausgeführt mit den Berechtigungen des Verantwortlichen des Workflows."@@ -12658,9 +12684,15 @@ msgstr "Bringen Sie es beim wöchentlichen Statusgespräch zur Sprache"msgid "raise it early and raise it plainly. A problem named in week 2 is a small fix; the same problem at go-live is a delay."msgstr "Sprechen Sie es früh an und sprechen Sie es deutlich an. Ein Problem, das in Woche 2 benannt wird, ist eine kleine Reparatur; das gleiche Problem beim Go-Live ist eine Verzögerung."+msgid "Rate"+msgstr "Kurs"+msgid "Rate Limit"msgstr "Ratenlimit"+msgid "Rate used for equity account translation in consolidation (IAS 21). Leave blank to use the current exchange rate."+msgstr "Kurs für die Umrechnung von Eigenkapitalkonten in der Konsolidierung (IAS 21). Leer lassen, um den aktuellen Wechselkurs zu verwenden."+msgid "Ratio"msgstr "Verhältnis"@@ -13272,6 +13304,9 @@ msgstr "PIN zurücksetzen"msgid "Reset PIN for {0} {1}"msgstr "PIN zurücksetzen für {0} {1}"+msgid "Reset to market rate"+msgstr "Auf Marktkurs zurücksetzen"+msgid "Reset Two-Factor Auth"msgstr "Zwei-Faktor-Authentifizierung zurücksetzen"@@ -13808,6 +13843,9 @@ msgstr "Dimensionseinstellungen speichern"msgid "Save Method"msgstr "Methode speichern"+msgid "Save Rate"+msgstr "Kurs speichern"+msgid "Save view"msgstr "Ansicht speichern"@@ -16583,6 +16621,9 @@ msgstr "Dies ist eine ITAR-kontrollierte Umgebung. Der Zugriff ist auf U.S. Persmsgid "This is taking longer than expected. It may still finish — if it doesn't, retry the revert to put your data back."msgstr "Dies dauert länger als erwartet. Es kann trotzdem noch beendet werden – wenn nicht, versuchen Sie das Zurücksetzen erneut, um Ihre Daten wiederherzustellen."+msgid "This is the base currency. Exchange rate is always 1."+msgstr "Dies ist die Basiswährung. Der Wechselkurs ist immer 1."+msgid "This is the month your fiscal year starts."msgstr "Dies ist der Monat, in dem Ihr Geschäftsjahr beginnt."@@ -18725,6 +18766,9 @@ msgstr "Ihr Projekt von Anfang bis Ende: die Planung, die Meilensteine und der Gmsgid "Your Project Team"msgstr "Ihr Projektteam"+msgid "Your rate"+msgstr "Ihr Kurs"+msgid "Your real data is loaded and you have checked a sample and approved it."msgstr "Ihre echten Daten sind geladen und Sie haben eine Stichprobe überprüft und genehmigt."diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex fd64fdb523..5573a64dfb 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -2624,6 +2624,9 @@ msgstr "Bank and financial service charge expenses"msgid "Bars show each week's flow: <0>supply</0> pushes inventory up, <1>demand</1> pulls it down. The <2>line</2> is your projected on-hand inventory — when it dips below <3>safety stock</3> you're at risk, and below zero is a <4>stockout</4>."msgstr "Bars show each week's flow: <0>supply</0> pushes inventory up, <1>demand</1> pulls it down. The <2>line</2> is your projected on-hand inventory — when it dips below <3>safety stock</3> you're at risk, and below zero is a <4>stockout</4>."+msgid "Base currency"+msgstr "Base currency"+msgid "Base Currency"msgstr "Base Currency"@@ -3215,6 +3218,9 @@ msgstr "Changing this will update the part ID"msgid "Changing type resets this item's draft edits."msgstr "Changing type resets this item's draft edits."+msgid "Chart"+msgstr "Chart"+msgid "Chart of accounts"msgstr "Chart of accounts"@@ -9422,6 +9428,15 @@ msgstr "Mark Short"msgid "Mark to delete"msgstr "Mark to delete"+msgid "Market rate"+msgstr "Market rate"++msgid "Market rate (per USD)"+msgstr "Market rate (per USD)"++msgid "Market Rate History (per USD)"+msgstr "Market Rate History (per USD)"+msgid "Marks the person off for every day in the range. They won't be scheduled while they're away."msgstr "Marks the person off for every day in the range. They won't be scheduled while they're away."@@ -9970,6 +9985,9 @@ msgstr "New Cost Center"msgid "New Credit / Debit Memo"msgstr "New Credit / Debit Memo"+msgid "New Currency"+msgstr "New Currency"+msgid "New Custom Field"msgstr "New Custom Field"@@ -10601,6 +10619,9 @@ msgstr "No Quote Reason"msgid "No Quote Reasons"msgstr "No Quote Reasons"+msgid "No rate"+msgstr "No rate"+msgid "No receivables"msgstr "No receivables"@@ -10966,6 +10987,11 @@ msgstr "On-time delivery"msgid "Onboard your agent to Carbon"msgstr "Onboard your agent to Carbon"+#. placeholder {0}: company?.baseCurrencyCode+#. placeholder {1}: initialValues.code+msgid "One {0} is equal to how many {1}?"+msgstr "One {0} is equal to how many {1}?"+msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."msgstr "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."@@ -12658,9 +12684,15 @@ msgstr "Raise it at the weekly status call"msgid "raise it early and raise it plainly. A problem named in week 2 is a small fix; the same problem at go-live is a delay."msgstr "raise it early and raise it plainly. A problem named in week 2 is a small fix; the same problem at go-live is a delay."+msgid "Rate"+msgstr "Rate"+msgid "Rate Limit"msgstr "Rate Limit"+msgid "Rate used for equity account translation in consolidation (IAS 21). Leave blank to use the current exchange rate."+msgstr "Rate used for equity account translation in consolidation (IAS 21). Leave blank to use the current exchange rate."+msgid "Ratio"msgstr "Ratio"@@ -13272,6 +13304,9 @@ msgstr "Reset PIN"msgid "Reset PIN for {0} {1}"msgstr "Reset PIN for {0} {1}"+msgid "Reset to market rate"+msgstr "Reset to market rate"+msgid "Reset Two-Factor Auth"msgstr "Reset Two-Factor Auth"@@ -13808,6 +13843,9 @@ msgstr "Save dimension settings"msgid "Save Method"msgstr "Save Method"+msgid "Save Rate"+msgstr "Save Rate"+msgid "Save view"msgstr "Save view"@@ -16583,6 +16621,9 @@ msgstr "This is an ITAR-controlled environment. Access is restricted to U.S. Permsgid "This is taking longer than expected. It may still finish — if it doesn't, retry the revert to put your data back."msgstr "This is taking longer than expected. It may still finish — if it doesn't, retry the revert to put your data back."+msgid "This is the base currency. Exchange rate is always 1."+msgstr "This is the base currency. Exchange rate is always 1."+msgid "This is the month your fiscal year starts."msgstr "This is the month your fiscal year starts."@@ -18729,6 +18770,9 @@ msgstr "Your project end to end: the plan, the gates, and go-live"msgid "Your Project Team"msgstr "Your Project Team"+msgid "Your rate"+msgstr "Your rate"+msgid "Your real data is loaded and you have checked a sample and approved it."msgstr "Your real data is loaded and you have checked a sample and approved it."diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 3594ebe374..4a3a5becb6 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -2624,6 +2624,9 @@ msgstr "Gastos de bancos y cargos de servicio financiero"msgid "Bars show each week's flow: <0>supply</0> pushes inventory up, <1>demand</1> pulls it down. The <2>line</2> is your projected on-hand inventory — when it dips below <3>safety stock</3> you're at risk, and below zero is a <4>stockout</4>."msgstr "Las barras muestran el flujo de cada semana: <0>suministro</0> empuja el inventario hacia arriba, <1>demanda</1> lo tira hacia abajo. La <2>línea</2> es tu inventario disponible proyectado — cuando desciende por debajo de <3>stock de seguridad</3> estás en riesgo, y por debajo de cero es una <4>rotura de stock</4>."+msgid "Base currency"+msgstr "Moneda base"+msgid "Base Currency"msgstr "Moneda Base"@@ -3215,6 +3218,9 @@ msgstr "Cambiar esto actualizará el ID de la pieza"msgid "Changing type resets this item's draft edits."msgstr "Cambiar el tipo restablece los borradores editados de este elemento."+msgid "Chart"+msgstr "Gráfico"+msgid "Chart of accounts"msgstr "Plan de cuentas"@@ -9422,6 +9428,15 @@ msgstr "Marcar como faltante"msgid "Mark to delete"msgstr "Marcar para eliminar"+msgid "Market rate"+msgstr "Tipo de cambio de mercado"++msgid "Market rate (per USD)"+msgstr "Tipo de cambio de mercado (por USD)"++msgid "Market Rate History (per USD)"+msgstr "Historial del tipo de cambio de mercado (por USD)"+msgid "Marks the person off for every day in the range. They won't be scheduled while they're away."msgstr "Marca a la persona como ausente para cada día en el rango. No se programarán mientras estén fuera."@@ -9970,6 +9985,9 @@ msgstr "Nuevo Centro de Costos"msgid "New Credit / Debit Memo"msgstr "Nuevo memorando de crédito/débito"+msgid "New Currency"+msgstr "Nueva Moneda"+msgid "New Custom Field"msgstr "Nuevo Campo Personalizado"@@ -10601,6 +10619,9 @@ msgstr "Motivo sin cotización"msgid "No Quote Reasons"msgstr "Razones sin cotización"+msgid "No rate"+msgstr "Sin tipo de cambio"+msgid "No receivables"msgstr "Sin cuentas por cobrar"@@ -10966,6 +10987,11 @@ msgstr "Entrega a tiempo"msgid "Onboard your agent to Carbon"msgstr "Integra tu agente en Carbon"+#. placeholder {0}: company?.baseCurrencyCode+#. placeholder {1}: initialValues.code+msgid "One {0} is equal to how many {1}?"+msgstr "¿A cuántos {1} equivale 1 {0}?"+msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."msgstr "Una ejecución de un flujo de trabajo, registrada paso a paso con los valores que cada paso usó y produjo, actuando en todo momento con los permisos del propietario del flujo de trabajo."@@ -12658,9 +12684,15 @@ msgstr "Plantéalo en la llamada de estado semanal"msgid "raise it early and raise it plainly. A problem named in week 2 is a small fix; the same problem at go-live is a delay."msgstr "plantéalo temprano y plantéalo claramente. Un problema identificado en la semana 2 es una corrección pequeña; el mismo problema en el lanzamiento es un retraso."+msgid "Rate"+msgstr "Tipo de cambio"+msgid "Rate Limit"msgstr "Límite de Velocidad"+msgid "Rate used for equity account translation in consolidation (IAS 21). Leave blank to use the current exchange rate."+msgstr "Tipo de cambio utilizado para la conversión de cuentas de patrimonio en la consolidación (IAS 21). Déjelo en blanco para usar el tipo de cambio actual."+msgid "Ratio"msgstr "Relación"@@ -13272,6 +13304,9 @@ msgstr "Restablecer PIN"msgid "Reset PIN for {0} {1}"msgstr "Restablecer PIN para {0} {1}"+msgid "Reset to market rate"+msgstr "Restablecer al tipo de mercado"+msgid "Reset Two-Factor Auth"msgstr "Restablecer Autenticación de Dos Factores"@@ -13808,6 +13843,9 @@ msgstr "Guardar configuración de dimensión"msgid "Save Method"msgstr "Guardar Método"+msgid "Save Rate"+msgstr "Guardar tipo de cambio"+msgid "Save view"msgstr "Guardar vista"@@ -16583,6 +16621,9 @@ msgstr "Este es un entorno controlado por ITAR. El acceso está restringido a pemsgid "This is taking longer than expected. It may still finish — if it doesn't, retry the revert to put your data back."msgstr "Esto está tomando más tiempo del esperado. Aún puede terminar; si no lo hace, reintenta el reverso para restaurar tus datos."+msgid "This is the base currency. Exchange rate is always 1."+msgstr "Esta es la moneda base. El tipo de cambio siempre es 1."+msgid "This is the month your fiscal year starts."msgstr "Este es el mes en que comienza tu ejercicio fiscal."@@ -18725,6 +18766,9 @@ msgstr "Tu proyecto de principio a fin: el plan, los gates y el go-live"msgid "Your Project Team"msgstr "Tu Equipo de Proyecto"+msgid "Your rate"+msgstr "Tu tipo de cambio"+msgid "Your real data is loaded and you have checked a sample and approved it."msgstr "Tus datos reales están cargados y has verificado una muestra y la has aprobado."diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex 3fcf35e20b..93c36eb949 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -2624,6 +2624,9 @@ msgstr "Dépenses de frais bancaires et de services financiers"msgid "Bars show each week's flow: <0>supply</0> pushes inventory up, <1>demand</1> pulls it down. The <2>line</2> is your projected on-hand inventory — when it dips below <3>safety stock</3> you're at risk, and below zero is a <4>stockout</4>."msgstr "Les barres montrent le flux de chaque semaine : <0>l'approvisionnement</0> augmente les stocks, <1>les besoins</1> les diminuent. La <2>ligne</2> est votre inventaire prévu en main — quand elle descend en dessous du <3>stock de sécurité</3>, vous êtes à risque, et en dessous de zéro c'est une <4>rupture de stock</4>."+msgid "Base currency"+msgstr "Devise de base"+msgid "Base Currency"msgstr "Devise de base"@@ -3215,6 +3218,9 @@ msgstr "Modifier ceci mettra à jour l'ID de pièce"msgid "Changing type resets this item's draft edits."msgstr "Modifier le type réinitialise les brouillons de cet article."+msgid "Chart"+msgstr "Graphique"+msgid "Chart of accounts"msgstr "Plan comptable"@@ -9422,6 +9428,15 @@ msgstr "Marquer comme manquant"msgid "Mark to delete"msgstr "Marquer pour supprimer"+msgid "Market rate"+msgstr "Taux du marché"++msgid "Market rate (per USD)"+msgstr "Taux du marché (par USD)"++msgid "Market Rate History (per USD)"+msgstr "Historique du taux du marché (par USD)"+msgid "Marks the person off for every day in the range. They won't be scheduled while they're away."msgstr "Marque la personne comme absente pour chaque jour de la plage. Ils ne seront pas programmés pendant leur absence."@@ -9970,6 +9985,9 @@ msgstr "Nouveau centre de coûts"msgid "New Credit / Debit Memo"msgstr "Nouveau Mémo de Crédit / Débit"+msgid "New Currency"+msgstr "Nouvelle devise"+msgid "New Custom Field"msgstr "Nouveau champ personnalisé"@@ -10601,6 +10619,9 @@ msgstr "Raison du refus de devis"msgid "No Quote Reasons"msgstr "Raisons du refus de devis"+msgid "No rate"+msgstr "Aucun taux"+msgid "No receivables"msgstr "Aucune créance client"@@ -10966,6 +10987,11 @@ msgstr "Livraison à temps"msgid "Onboard your agent to Carbon"msgstr "Intégrez votre agent à Carbon"+#. placeholder {0}: company?.baseCurrencyCode+#. placeholder {1}: initialValues.code+msgid "One {0} is equal to how many {1}?"+msgstr "1 {0} équivaut à combien de {1} ?"+msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."msgstr "Une exécution d'un workflow, enregistrée étape par étape avec les valeurs que chaque étape a utilisées et produites, agissant tout au long avec les autorisations du propriétaire du workflow."@@ -12658,9 +12684,15 @@ msgstr "Soulevez-le lors de l'appel de statut hebdomadaire"msgid "raise it early and raise it plainly. A problem named in week 2 is a small fix; the same problem at go-live is a delay."msgstr "soulevez-le tôt et soulevez-le clairement. Un problème identifié à la semaine 2 est une petite correction ; le même problème au lancement est un retard."+msgid "Rate"+msgstr "Taux"+msgid "Rate Limit"msgstr "Limite de débit"+msgid "Rate used for equity account translation in consolidation (IAS 21). Leave blank to use the current exchange rate."+msgstr "Taux utilisé pour la conversion des comptes de capitaux propres en consolidation (IAS 21). Laissez vide pour utiliser le taux de change actuel."+msgid "Ratio"msgstr "Ratio"@@ -13272,6 +13304,9 @@ msgstr "Réinitialiser le PIN"msgid "Reset PIN for {0} {1}"msgstr "Réinitialiser le PIN pour {0} {1}"+msgid "Reset to market rate"+msgstr "Réinitialiser au taux du marché"+msgid "Reset Two-Factor Auth"msgstr "Réinitialiser l'authentification à deux facteurs"@@ -13808,6 +13843,9 @@ msgstr "Enregistrer les paramètres d'axe analytique"msgid "Save Method"msgstr "Enregistrer la méthode"+msgid "Save Rate"+msgstr "Enregistrer le taux"+msgid "Save view"msgstr "Enregistrer la vue"@@ -16583,6 +16621,9 @@ msgstr "Ceci est un environnement contrôlé par l'ITAR. L'accès est restreintmsgid "This is taking longer than expected. It may still finish — if it doesn't, retry the revert to put your data back."msgstr "Cela prend plus de temps que prévu. Il peut encore finir — sinon, réessayez l'annulation pour restaurer vos données."+msgid "This is the base currency. Exchange rate is always 1."+msgstr "Ceci est la devise de base. Le taux de change est toujours 1."+msgid "This is the month your fiscal year starts."msgstr "C'est le mois où commence votre exercice comptable."@@ -18725,6 +18766,9 @@ msgstr "Votre projet de bout en bout : le plan, les jalons et la mise en productmsgid "Your Project Team"msgstr "Votre équipe de projet"+msgid "Your rate"+msgstr "Votre taux"+msgid "Your real data is loaded and you have checked a sample and approved it."msgstr "Vos données réelles sont chargées et vous avez vérifié un échantillon et l'avez approuvé."diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 8c293f0f3e..4b612c9f95 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -2624,6 +2624,9 @@ msgstr "बैंक और वित्तीय सेवा शुल्कmsgid "Bars show each week's flow: <0>supply</0> pushes inventory up, <1>demand</1> pulls it down. The <2>line</2> is your projected on-hand inventory — when it dips below <3>safety stock</3> you're at risk, and below zero is a <4>stockout</4>."msgstr "बार प्रत्येक सप्ताह के प्रवाह को दिखाते हैं: <0>आपूर्ति</0> इन्वेंटरी को ऊपर धकेलती है, <1>मांग</1> इसे नीचे खींचती है। <2>लाइन</2> आपकी अनुमानित उपलब्ध इन्वेंटरी है — जब यह <3>सुरक्षा स्टॉक</3> के नीचे गिरती है तो आप जोखिम में हैं, और शून्य से नीचे एक <4>स्टॉकआउट</4> है।"+msgid "Base currency"+msgstr "आधार मुद्रा"+msgid "Base Currency"msgstr "आधार मुद्रा"@@ -3215,6 +3218,9 @@ msgstr "इसे बदलने से पार्ट ID अपडेट हmsgid "Changing type resets this item's draft edits."msgstr "प्रकार बदलने से इस आइटम के ड्राफ्ट संपादन रीसेट हो जाते हैं।"+msgid "Chart"+msgstr "चार्ट"+msgid "Chart of accounts"msgstr "खातों की चार्ट"@@ -9422,6 +9428,15 @@ msgstr "कम चिह्नित करें"msgid "Mark to delete"msgstr "हटाने के लिए चिह्नित करें"+msgid "Market rate"+msgstr "बाज़ार दर"++msgid "Market rate (per USD)"+msgstr "बाज़ार दर (प्रति USD)"++msgid "Market Rate History (per USD)"+msgstr "बाज़ार दर इतिहास (प्रति USD)"+msgid "Marks the person off for every day in the range. They won't be scheduled while they're away."msgstr "रेंज में प्रत्येक दिन व्यक्ति को चिह्नित करता है। वे दूर रहते हुए शेड्यूल नहीं किए जाएंगे।"@@ -9970,6 +9985,9 @@ msgstr "नया लागत केंद्र"msgid "New Credit / Debit Memo"msgstr "नया जमा / नामे मेमो"+msgid "New Currency"+msgstr "नई मुद्रा"+msgid "New Custom Field"msgstr "नया कस्टम फील्ड"@@ -10601,6 +10619,9 @@ msgstr "कोई कोटेशन कारण नहीं"msgid "No Quote Reasons"msgstr "कोई कोटेशन कारण नहीं"+msgid "No rate"+msgstr "कोई दर नहीं"+msgid "No receivables"msgstr "कोई प्राप्य राशि नहीं"@@ -10966,6 +10987,11 @@ msgstr "समय पर डिलीवरी"msgid "Onboard your agent to Carbon"msgstr "अपने एजेंट को Carbon पर ऑनबोर्ड करें"+#. placeholder {0}: company?.baseCurrencyCode+#. placeholder {1}: initialValues.code+msgid "One {0} is equal to how many {1}?"+msgstr "1 {0} कितने {1} के बराबर है?"+msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."msgstr "एक वर्कफ़्लो का एक निष्पादन, चरण दर चरण रिकॉर्ड किया गया जिसमें प्रत्येक चरण द्वारा उपयोग किए गए और उत्पादित मान शामिल हैं, वर्कफ़्लो के स्वामी की अनुमतियों के साथ पूरे समय कार्य करते हुए।"@@ -12658,9 +12684,15 @@ msgstr "इसे साप्ताहिक स्थिति कॉल मmsgid "raise it early and raise it plainly. A problem named in week 2 is a small fix; the same problem at go-live is a delay."msgstr "इसे जल्दी उठाएं और स्पष्ट रूप से उठाएं। सप्ताह 2 में नामित समस्या एक छोटी सी मरम्मत है; go-live पर वही समस्या एक देरी है।"+msgid "Rate"+msgstr "दर"+msgid "Rate Limit"msgstr "दर सीमा"+msgid "Rate used for equity account translation in consolidation (IAS 21). Leave blank to use the current exchange rate."+msgstr "समेकन में इक्विटी खातों के रूपांतरण के लिए उपयोग की जाने वाली दर (IAS 21)। वर्तमान विनिमय दर का उपयोग करने के लिए खाली छोड़ें।"+msgid "Ratio"msgstr "अनुपात"@@ -13272,6 +13304,9 @@ msgstr "PIN रीसेट करें"msgid "Reset PIN for {0} {1}"msgstr "{0} {1} के लिए PIN रीसेट करें"+msgid "Reset to market rate"+msgstr "बाज़ार दर पर रीसेट करें"+msgid "Reset Two-Factor Auth"msgstr "दो-कारक प्रमाणीकरण रीसेट करें"@@ -13808,6 +13843,9 @@ msgstr "आयाम सेटिंग्स सहेजें"msgid "Save Method"msgstr "विधि सहेजें"+msgid "Save Rate"+msgstr "दर सहेजें"+msgid "Save view"msgstr "दृश्य सहेजें"@@ -16583,6 +16621,9 @@ msgstr "यह एक ITAR-नियंत्रित वातावरण हmsgid "This is taking longer than expected. It may still finish — if it doesn't, retry the revert to put your data back."msgstr "यह अपेक्षा से अधिक समय ले रहा है। यह अभी भी समाप्त हो सकता है — यदि नहीं होता, तो अपना डेटा वापस करने के लिए पूर्ववत् करने का पुन: प्रयास करें।"+msgid "This is the base currency. Exchange rate is always 1."+msgstr "यह आधार मुद्रा है। विनिमय दर हमेशा 1 होती है।"+msgid "This is the month your fiscal year starts."msgstr "यह वह महीना है जब आपका वित्तीय वर्ष शुरू होता है।"@@ -18729,6 +18770,9 @@ msgstr "आपकी परियोजना शुरू से अंत तmsgid "Your Project Team"msgstr "आपकी प्रोजेक्ट टीम"+msgid "Your rate"+msgstr "आपकी दर"+msgid "Your real data is loaded and you have checked a sample and approved it."msgstr "आपका वास्तविक डेटा लोड हो गया है और आपने एक नमूना जांचा है और इसे मंजूरी दे दी है।"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex 23e89da6f6..621b11fb78 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -2624,6 +2624,9 @@ msgstr "Spese per commissioni di servizi bancari e finanziari."msgid "Bars show each week's flow: <0>supply</0> pushes inventory up, <1>demand</1> pulls it down. The <2>line</2> is your projected on-hand inventory — when it dips below <3>safety stock</3> you're at risk, and below zero is a <4>stockout</4>."msgstr "I grafici mostrano il flusso di ogni settimana: <0>copertura</0> spinge il magazzino verso l'alto, <1>fabbisogno</1> lo tira verso il basso. La <2>riga</2> è il tuo magazzino disponibile previsto — quando scende al di sotto della <3>scorta di sicurezza</3> sei a rischio, e al di sotto di zero è una <4>rottura di stock</4>."+msgid "Base currency"+msgstr "Valuta base"+msgid "Base Currency"msgstr "Valuta di Base"@@ -3215,6 +3218,9 @@ msgstr "Modificare questo aggiornerà l'ID della parte"msgid "Changing type resets this item's draft edits."msgstr "Cambiare il tipo ripristina le modifiche in bozza di questo elemento."+msgid "Chart"+msgstr "Grafico"+msgid "Chart of accounts"msgstr "Piano dei conti"@@ -9422,6 +9428,15 @@ msgstr "Segna come incompleto"msgid "Mark to delete"msgstr "Segna per eliminare"+msgid "Market rate"+msgstr "Tasso di mercato"++msgid "Market rate (per USD)"+msgstr "Tasso di mercato (per USD)"++msgid "Market Rate History (per USD)"+msgstr "Storico del tasso di mercato (per USD)"+msgid "Marks the person off for every day in the range. They won't be scheduled while they're away."msgstr "Segna la persona come assente per ogni giorno nell'intervallo. Non verranno programmati mentre sono via."@@ -9970,6 +9985,9 @@ msgstr "Nuovo Centro di Costo"msgid "New Credit / Debit Memo"msgstr "Nuova nota di credito / debito"+msgid "New Currency"+msgstr "Nuova Valuta"+msgid "New Custom Field"msgstr "Nuovo Campo Personalizzato"@@ -10601,6 +10619,9 @@ msgstr "Nessun motivo dell'offerta"msgid "No Quote Reasons"msgstr "Nessun motivo di mancata offerta"+msgid "No rate"+msgstr "Nessun tasso"+msgid "No receivables"msgstr "Nessun credito"@@ -10966,6 +10987,11 @@ msgstr "Consegna puntuale"msgid "Onboard your agent to Carbon"msgstr "Integra il tuo agente in Carbon"+#. placeholder {0}: company?.baseCurrencyCode+#. placeholder {1}: initialValues.code+msgid "One {0} is equal to how many {1}?"+msgstr "1 {0} equivale a quanti {1}?"+msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."msgstr "Un'esecuzione di un flusso di lavoro, registrata passo per passo con i valori che ogni passo ha utilizzato e prodotto, agendo sempre con i permessi del proprietario del flusso di lavoro."@@ -12658,9 +12684,15 @@ msgstr "Segnalalo nella riunione di stato settimanale"msgid "raise it early and raise it plainly. A problem named in week 2 is a small fix; the same problem at go-live is a delay."msgstr "segnalalo presto e segnalalo chiaramente. Un problema identificato nella settimana 2 è una piccola correzione; lo stesso problema al lancio è un ritardo."+msgid "Rate"+msgstr "Tasso"+msgid "Rate Limit"msgstr "Limite di Velocità"+msgid "Rate used for equity account translation in consolidation (IAS 21). Leave blank to use the current exchange rate."+msgstr "Tasso utilizzato per la conversione dei conti di patrimonio netto nel consolidamento (IAS 21). Lasciare vuoto per usare il tasso di cambio corrente."+msgid "Ratio"msgstr "Rapporto"@@ -13272,6 +13304,9 @@ msgstr "Ripristina PIN"msgid "Reset PIN for {0} {1}"msgstr "Reimposta PIN per {0} {1}"+msgid "Reset to market rate"+msgstr "Ripristina al tasso di mercato"+msgid "Reset Two-Factor Auth"msgstr "Ripristina autenticazione a due fattori"@@ -13808,6 +13843,9 @@ msgstr "Salva impostazioni dimensionali"msgid "Save Method"msgstr "Salva Metodo"+msgid "Save Rate"+msgstr "Salva tasso"+msgid "Save view"msgstr "Salva vista"@@ -16583,6 +16621,9 @@ msgstr "Questo è un ambiente controllato ITAR. L'accesso è limitato alle Persomsgid "This is taking longer than expected. It may still finish — if it doesn't, retry the revert to put your data back."msgstr "Sta richiedendo più tempo del previsto. Potrebbe comunque finire - se non finisce, riprova il ripristino per ripristinare i tuoi dati."+msgid "This is the base currency. Exchange rate is always 1."+msgstr "Questa è la valuta base. Il tasso di cambio è sempre 1."+msgid "This is the month your fiscal year starts."msgstr "Questo è il mese in cui inizia il tuo esercizio fiscale."@@ -18729,6 +18770,9 @@ msgstr "Il tuo progetto da inizio a fine: il piano, i gate e il go-live"msgid "Your Project Team"msgstr "Il tuo team di progetto"+msgid "Your rate"+msgstr "Il tuo tasso"+msgid "Your real data is loaded and you have checked a sample and approved it."msgstr "I tuoi dati reali sono caricati e hai controllato un campione e lo hai approvato."diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 3ba507cdb7..420ed47503 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -2624,6 +2624,9 @@ msgstr "銀行およびサービス料費用"msgid "Bars show each week's flow: <0>supply</0> pushes inventory up, <1>demand</1> pulls it down. The <2>line</2> is your projected on-hand inventory — when it dips below <3>safety stock</3> you're at risk, and below zero is a <4>stockout</4>."msgstr "棒グラフは毎週の流れを表示します:<0>供給</0>は在庫を増加させ、<1>所要量</1>は減少させます。<2>線</2>は予測在庫です。<3>安全在庫</3>を下回る場合はリスク状態であり、ゼロを下回る場合は<4>欠品</4>です。"+msgid "Base currency"+msgstr "基本通貨"+msgid "Base Currency"msgstr "基本通貨"@@ -3215,6 +3218,9 @@ msgstr "これを変更するとパーツIDが更新されます"msgid "Changing type resets this item's draft edits."msgstr "タイプを変更すると、この品目の下書き編集がリセットされます。"+msgid "Chart"+msgstr "チャート"+msgid "Chart of accounts"msgstr "勘定科目表"@@ -9422,6 +9428,15 @@ msgstr "短い数量をマーク"msgid "Mark to delete"msgstr "削除対象にマーク"+msgid "Market rate"+msgstr "市場レート"++msgid "Market rate (per USD)"+msgstr "市場レート(対USD)"++msgid "Market Rate History (per USD)"+msgstr "市場レート履歴(対USD)"+msgid "Marks the person off for every day in the range. They won't be scheduled while they're away."msgstr "範囲内のすべての日について、その人を休止します。外出中はスケジュール設定されません。"@@ -9970,6 +9985,9 @@ msgstr "新規原価センター"msgid "New Credit / Debit Memo"msgstr "新しい貸方/借方メモ"+msgid "New Currency"+msgstr "新規通貨"+msgid "New Custom Field"msgstr "新しいカスタムフィールド"@@ -10601,6 +10619,9 @@ msgstr "見積辞退理由"msgid "No Quote Reasons"msgstr "見積辞退理由"+msgid "No rate"+msgstr "レートなし"+msgid "No receivables"msgstr "売掛金がありません"@@ -10966,6 +10987,11 @@ msgstr "オンタイム配送"msgid "Onboard your agent to Carbon"msgstr "エージェントを Carbon にオンボード"+#. placeholder {0}: company?.baseCurrencyCode+#. placeholder {1}: initialValues.code+msgid "One {0} is equal to how many {1}?"+msgstr "1 {0} は何 {1} に相当しますか?"+msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."msgstr "ワークフローの1回の実行。各ステップが使用および生成した値を含めてステップバイステップで記録され、全体を通じてワークフロー責任者の権限で実行されます。"@@ -12658,9 +12684,15 @@ msgstr "毎週のステータスミーティングで提起してください"msgid "raise it early and raise it plainly. A problem named in week 2 is a small fix; the same problem at go-live is a delay."msgstr "早期に報告し、明確に報告してください。2週目に特定された問題は小さな修正で済みますが、本番リリース時の同じ問題は遅延につながります。"+msgid "Rate"+msgstr "レート"+msgid "Rate Limit"msgstr "レート制限"+msgid "Rate used for equity account translation in consolidation (IAS 21). Leave blank to use the current exchange rate."+msgstr "連結における純資産勘定の換算に使用されるレート(IAS 21)。空欄の場合は現在の為替レートが使用されます。"+msgid "Ratio"msgstr "比率"@@ -13272,6 +13304,9 @@ msgstr "PINをリセット"msgid "Reset PIN for {0} {1}"msgstr "{0} {1}のPINをリセット"+msgid "Reset to market rate"+msgstr "市場レートにリセット"+msgid "Reset Two-Factor Auth"msgstr "2要素認証をリセット"@@ -13808,6 +13843,9 @@ msgstr "ディメンション設定を保存"msgid "Save Method"msgstr "メソッドを保存"+msgid "Save Rate"+msgstr "レートを保存"+msgid "Save view"msgstr "ビューを保存"@@ -16583,6 +16621,9 @@ msgstr "これはITAR管理環境です。アクセスは米国人に限定さmsgid "This is taking longer than expected. It may still finish — if it doesn't, retry the revert to put your data back."msgstr "予想より時間がかかっています。終了する可能性があります。終了しない場合は、リバートを再試行してデータを復元してください。"+msgid "This is the base currency. Exchange rate is always 1."+msgstr "これは基準通貨です。為替レートは常に1です。"+msgid "This is the month your fiscal year starts."msgstr "これはあなたの会計年度が始まる月です。"@@ -18725,6 +18766,9 @@ msgstr "プロジェクト全体:計画、ゲート、本番稼働"msgid "Your Project Team"msgstr "あなたのプロジェクトチーム"+msgid "Your rate"+msgstr "カスタムレート"+msgid "Your real data is loaded and you have checked a sample and approved it."msgstr "あなたの実際のデータが読み込まれ、サンプルを確認して承認しました。"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex 8b78860b64..b4bddc7677 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -2624,6 +2624,9 @@ msgstr "은행 및 금융 서비스 요금 비용"msgid "Bars show each week's flow: <0>supply</0> pushes inventory up, <1>demand</1> pulls it down. The <2>line</2> is your projected on-hand inventory — when it dips below <3>safety stock</3> you're at risk, and below zero is a <4>stockout</4>."msgstr "막대는 매주의 흐름을 보여줍니다: <0>공급</0>은 재고를 올리고, <1>소요량</1>은 내립니다. <2>라인</2>은 예상 현재고 — <3>안전 재고</3> 아래로 떨어지면 위험에 처해 있고, 0 아래는 <4>재고 부족</4>입니다."+msgid "Base currency"+msgstr "기준 통화"+msgid "Base Currency"msgstr "기준 통화"@@ -3215,6 +3218,9 @@ msgstr "이를 변경하면 품목 ID가 업데이트됩니다"msgid "Changing type resets this item's draft edits."msgstr "유형을 변경하면 이 항목의 초안 편집이 재설정됩니다."+msgid "Chart"+msgstr "차트"+msgid "Chart of accounts"msgstr "계정과목표"@@ -9422,6 +9428,15 @@ msgstr "부족으로 표시"msgid "Mark to delete"msgstr "삭제 대상으로 표시"+msgid "Market rate"+msgstr "시장 환율"++msgid "Market rate (per USD)"+msgstr "시장 환율 (USD당)"++msgid "Market Rate History (per USD)"+msgstr "시장 환율 기록 (USD당)"+msgid "Marks the person off for every day in the range. They won't be scheduled while they're away."msgstr "범위 내의 모든 날짜에 대해 해당 사람을 표시합니다. 그들은 휴무 중에 스케줄되지 않습니다."@@ -9970,6 +9985,9 @@ msgstr "신규 원가 센터"msgid "New Credit / Debit Memo"msgstr "신규 대변/차변 메모"+msgid "New Currency"+msgstr "신규 통화"+msgid "New Custom Field"msgstr "신규 사용자 정의 필드"@@ -10601,6 +10619,9 @@ msgstr "견적 거절 사유"msgid "No Quote Reasons"msgstr "견적 거절 사유"+msgid "No rate"+msgstr "환율 없음"+msgid "No receivables"msgstr "매출채권이 없습니다"@@ -10966,6 +10987,11 @@ msgstr "정시 납품"msgid "Onboard your agent to Carbon"msgstr "Carbon에 에이전트 등록"+#. placeholder {0}: company?.baseCurrencyCode+#. placeholder {1}: initialValues.code+msgid "One {0} is equal to how many {1}?"+msgstr "1 {0}은(는) 몇 {1}입니까?"+msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."msgstr "워크플로의 한 번 실행으로, 각 단계가 사용하고 생성한 값을 단계별로 기록하며 워크플로 책임자의 권한으로 전체적으로 작동합니다."@@ -12658,9 +12684,15 @@ msgstr "매주 상태 검토 회의에서 제기하세요"msgid "raise it early and raise it plainly. A problem named in week 2 is a small fix; the same problem at go-live is a delay."msgstr "문제는 일찍, 명확하게 제기하세요. 2주 차에 언급된 문제는 작은 수정이지만, 오픈 시점에 같은 문제가 나오면 지연으로 이어집니다."+msgid "Rate"+msgstr "환율"+msgid "Rate Limit"msgstr "요청 제한"+msgid "Rate used for equity account translation in consolidation (IAS 21). Leave blank to use the current exchange rate."+msgstr "연결 시 자본 계정 환산에 사용되는 환율(IAS 21)입니다. 비워 두면 현재 환율이 사용됩니다."+msgid "Ratio"msgstr "비율"@@ -13272,6 +13304,9 @@ msgstr "PIN 재설정"msgid "Reset PIN for {0} {1}"msgstr "{0} {1}의 PIN 재설정"+msgid "Reset to market rate"+msgstr "시장 환율로 재설정"+msgid "Reset Two-Factor Auth"msgstr "2단계 인증 재설정"@@ -13808,6 +13843,9 @@ msgstr "차원 설정 저장"msgid "Save Method"msgstr "저장 방법"+msgid "Save Rate"+msgstr "환율 저장"+msgid "Save view"msgstr "보기 저장"@@ -16583,6 +16621,9 @@ msgstr "이것은 ITAR 통제 환경입니다. 접근은 미국인에게만 제msgid "This is taking longer than expected. It may still finish — if it doesn't, retry the revert to put your data back."msgstr "예상보다 오래 걸리고 있습니다. 계속 진행될 수 있습니다 — 진행되지 않으면 복원을 다시 시도하여 데이터를 복구하세요."+msgid "This is the base currency. Exchange rate is always 1."+msgstr "기준 통화입니다. 환율은 항상 1입니다."+msgid "This is the month your fiscal year starts."msgstr "회계연도가 시작되는 월입니다."@@ -18725,6 +18766,9 @@ msgstr "프로젝트 전체: 계획, 단계별 게이트, 도입"msgid "Your Project Team"msgstr "프로젝트 팀"+msgid "Your rate"+msgstr "사용자 환율"+msgid "Your real data is loaded and you have checked a sample and approved it."msgstr "실제 데이터가 로드되었고 샘플을 확인하여 승인했습니다."diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex 1bd8b2f1a8..6ff881b9ed 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -2624,6 +2624,9 @@ msgstr "Wydatki na opłaty bankowe i usługi finansowe."msgid "Bars show each week's flow: <0>supply</0> pushes inventory up, <1>demand</1> pulls it down. The <2>line</2> is your projected on-hand inventory — when it dips below <3>safety stock</3> you're at risk, and below zero is a <4>stockout</4>."msgstr "Paski pokazują przepływ każdego tygodnia: <0>pokrycie</0> zwiększa zapasy, <1>zapotrzebowanie</1> je zmniejsza. <2>Linia</2> to twoje prognozowane zapasy w magazynie — gdy spadną poniżej <3>zapasu bezpieczeństwa</3>, jesteś zagrożony, a poniżej zera to <4>brak zapasu</4>."+msgid "Base currency"+msgstr "Waluta bazowa"+msgid "Base Currency"msgstr "Waluta bazowa"@@ -3215,6 +3218,9 @@ msgstr "Zmiana tego zaktualizuje identyfikator części"msgid "Changing type resets this item's draft edits."msgstr "Zmiana typu resetuje robocze edycje tego artykułu."+msgid "Chart"+msgstr "Wykres"+msgid "Chart of accounts"msgstr "Plan kont"@@ -9422,6 +9428,15 @@ msgstr "Oznacz jako brakujące"msgid "Mark to delete"msgstr "Oznacz do usunięcia"+msgid "Market rate"+msgstr "Kurs rynkowy"++msgid "Market rate (per USD)"+msgstr "Kurs rynkowy (za USD)"++msgid "Market Rate History (per USD)"+msgstr "Historia kursu rynkowego (za USD)"+msgid "Marks the person off for every day in the range. They won't be scheduled while they're away."msgstr "Oznacza osobę jako nieobecną na każdy dzień z zakresu. Nie będą zaplanowani, gdy są nieobecni."@@ -9970,6 +9985,9 @@ msgstr "Nowe miejsce powstawania kosztów"msgid "New Credit / Debit Memo"msgstr "Nowa Nota Kredytowa / Debetowa"+msgid "New Currency"+msgstr "Nowa waluta"+msgid "New Custom Field"msgstr "Nowe pole niestandardowe"@@ -10601,6 +10619,9 @@ msgstr "Powód odmowy oferty"msgid "No Quote Reasons"msgstr "Przyczyny odmowy oferty"+msgid "No rate"+msgstr "Brak kursu"+msgid "No receivables"msgstr "Brak należności"@@ -10966,6 +10987,11 @@ msgstr "Dostawa na czas"msgid "Onboard your agent to Carbon"msgstr "Dodaj swojego agenta do Carbon"+#. placeholder {0}: company?.baseCurrencyCode+#. placeholder {1}: initialValues.code+msgid "One {0} is equal to how many {1}?"+msgstr "1 {0} to ile {1}?"+msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."msgstr "Jedno wykonanie przepływu pracy, zarejestrowane krok po kroku z wartościami, które każdy krok użył i wygenerował, działając z uprawnieniami właściciela przepływu pracy."@@ -12658,9 +12684,15 @@ msgstr "Zgłoś to na cotygodniowym spotkaniu statusowym"msgid "raise it early and raise it plainly. A problem named in week 2 is a small fix; the same problem at go-live is a delay."msgstr "zgłoś to wcześnie i zgłoś to jasno. Problem zidentyfikowany w tygodniu 2 to mała naprawa; ten sam problem w momencie uruchomienia to opóźnienie."+msgid "Rate"+msgstr "Kurs"+msgid "Rate Limit"msgstr "Limit Szybkości"+msgid "Rate used for equity account translation in consolidation (IAS 21). Leave blank to use the current exchange rate."+msgstr "Kurs używany do przeliczenia kont kapitału własnego w konsolidacji (IAS 21). Pozostaw puste, aby użyć bieżącego kursu wymiany."+msgid "Ratio"msgstr "Stosunek"@@ -13272,6 +13304,9 @@ msgstr "Resetuj PIN"msgid "Reset PIN for {0} {1}"msgstr "Resetuj PIN dla {0} {1}"+msgid "Reset to market rate"+msgstr "Przywróć kurs rynkowy"+msgid "Reset Two-Factor Auth"msgstr "Zresetuj uwierzytelnianie dwuskładnikowe"@@ -13808,6 +13843,9 @@ msgstr "Zapisz ustawienia wymiarów"msgid "Save Method"msgstr "Zapisz metodę"+msgid "Save Rate"+msgstr "Zapisz kurs"+msgid "Save view"msgstr "Zapisz widok"@@ -16583,6 +16621,9 @@ msgstr "To jest środowisko kontrolowane przez ITAR. Dostęp jest ograniczony domsgid "This is taking longer than expected. It may still finish — if it doesn't, retry the revert to put your data back."msgstr "To trwa dłużej niż oczekiwano. Może się nadal zakończyć — jeśli nie, ponów przywracanie, aby przywrócić swoje dane."+msgid "This is the base currency. Exchange rate is always 1."+msgstr "To jest waluta bazowa. Kurs wymiany wynosi zawsze 1."+msgid "This is the month your fiscal year starts."msgstr "To jest miesiąc, w którym zaczyna się twój rok obrotowy."@@ -18725,6 +18766,9 @@ msgstr "Twój projekt od początku do końca: plan, bramy i wdrożenie"msgid "Your Project Team"msgstr "Twój Zespół Projektowy"+msgid "Your rate"+msgstr "Twój kurs"+msgid "Your real data is loaded and you have checked a sample and approved it."msgstr "Twoje rzeczywiste dane są załadowane i sprawdziłeś próbkę oraz ją zatwierdziłeś."diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 3c0fc2b03b..b180e5d017 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -2624,6 +2624,9 @@ msgstr "Despesas de taxas de serviços bancários e financeiros."msgid "Bars show each week's flow: <0>supply</0> pushes inventory up, <1>demand</1> pulls it down. The <2>line</2> is your projected on-hand inventory — when it dips below <3>safety stock</3> you're at risk, and below zero is a <4>stockout</4>."msgstr "Os gráficos mostram o fluxo de cada semana: <0>suprimento</0> aumenta o inventário, <1>demanda</1> o reduz. A <2>linha</2> é seu inventário disponível projetado — quando cai abaixo do <3>estoque de segurança</3> você está em risco, e abaixo de zero é uma <4>ruptura de estoque</4>."+msgid "Base currency"+msgstr "Moeda base"+msgid "Base Currency"msgstr "Moeda Base"@@ -3215,6 +3218,9 @@ msgstr "Alterar isto atualizará o ID da peça"msgid "Changing type resets this item's draft edits."msgstr "Mudar tipo redefine as edições de rascunho deste item."+msgid "Chart"+msgstr "Gráfico"+msgid "Chart of accounts"msgstr "Plano de contas"@@ -9422,6 +9428,15 @@ msgstr "Marcar como Falta"msgid "Mark to delete"msgstr "Marcar para exclusão"+msgid "Market rate"+msgstr "Taxa de mercado"++msgid "Market rate (per USD)"+msgstr "Taxa de mercado (por USD)"++msgid "Market Rate History (per USD)"+msgstr "Histórico da taxa de mercado (por USD)"+msgid "Marks the person off for every day in the range. They won't be scheduled while they're away."msgstr "Marca a pessoa como ausente para cada dia no intervalo. Ela não será agendada enquanto estiver fora."@@ -9970,6 +9985,9 @@ msgstr "Novo Centro de Custo"msgid "New Credit / Debit Memo"msgstr "Novo Memorando de Crédito / Débito"+msgid "New Currency"+msgstr "Nova Moeda"+msgid "New Custom Field"msgstr "Novo Campo Personalizado"@@ -10601,6 +10619,9 @@ msgstr "Sem Motivo de Cotação"msgid "No Quote Reasons"msgstr "Sem Motivos de Cotação"+msgid "No rate"+msgstr "Sem taxa"+msgid "No receivables"msgstr "Sem contas a receber"@@ -10966,6 +10987,11 @@ msgstr "Entrega no prazo"msgid "Onboard your agent to Carbon"msgstr "Integre seu agente ao Carbon"+#. placeholder {0}: company?.baseCurrencyCode+#. placeholder {1}: initialValues.code+msgid "One {0} is equal to how many {1}?"+msgstr "1 {0} equivale a quantos {1}?"+msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."msgstr "Uma execução de um fluxo de trabalho, registrada passo a passo com os valores que cada etapa usou e produziu, agindo sempre com as permissões do proprietário do fluxo de trabalho."@@ -12658,9 +12684,15 @@ msgstr "Levante na reunião de status semanal"msgid "raise it early and raise it plainly. A problem named in week 2 is a small fix; the same problem at go-live is a delay."msgstr "levante cedo e levante claramente. Um problema identificado na semana 2 é uma correção pequena; o mesmo problema no lançamento é um atraso."+msgid "Rate"+msgstr "Taxa"+msgid "Rate Limit"msgstr "Limite de Taxa"+msgid "Rate used for equity account translation in consolidation (IAS 21). Leave blank to use the current exchange rate."+msgstr "Taxa usada para a conversão de contas de patrimônio líquido na consolidação (IAS 21). Deixe em branco para usar a taxa de câmbio atual."+msgid "Ratio"msgstr "Razão"@@ -13272,6 +13304,9 @@ msgstr "Redefinir PIN"msgid "Reset PIN for {0} {1}"msgstr "Redefinir PIN para {0} {1}"+msgid "Reset to market rate"+msgstr "Redefinir para a taxa de mercado"+msgid "Reset Two-Factor Auth"msgstr "Redefinir Autenticação de Dois Fatores"@@ -13808,6 +13843,9 @@ msgstr "Salvar configurações de dimensão"msgid "Save Method"msgstr "Salvar Método"+msgid "Save Rate"+msgstr "Salvar taxa"+msgid "Save view"msgstr "Salvar visualização"@@ -16583,6 +16621,9 @@ msgstr "Este é um ambiente controlado por ITAR. O acesso é restrito a Pessoasmsgid "This is taking longer than expected. It may still finish — if it doesn't, retry the revert to put your data back."msgstr "Isto está levando mais tempo do que o esperado. Pode ainda terminar — se não terminar, tente reverter novamente para colocar seus dados de volta."+msgid "This is the base currency. Exchange rate is always 1."+msgstr "Esta é a moeda base. A taxa de câmbio é sempre 1."+msgid "This is the month your fiscal year starts."msgstr "Este é o mês em que seu ano fiscal começa."@@ -18725,6 +18766,9 @@ msgstr "Seu projeto do início ao fim: o plano, os gates e o go-live"msgid "Your Project Team"msgstr "Sua Equipe de Projeto"+msgid "Your rate"+msgstr "Sua taxa"+msgid "Your real data is loaded and you have checked a sample and approved it."msgstr "Os seus dados reais foram carregados e você verificou uma amostra e aprovou."diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex a389adb367..bb6a5eb06e 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -2624,6 +2624,9 @@ msgstr "Расходы банка и сервисного сбора финанmsgid "Bars show each week's flow: <0>supply</0> pushes inventory up, <1>demand</1> pulls it down. The <2>line</2> is your projected on-hand inventory — when it dips below <3>safety stock</3> you're at risk, and below zero is a <4>stockout</4>."msgstr "Столбцы показывают поток каждой недели: <0>обеспечение</0> увеличивает запасы, <1>потребность</1> снижает их. <2>Строка</2> — это ваши прогнозируемые запасы на складе — когда она падает ниже <3>страхового запаса</3>, вы в зоне риска, а ниже нуля — <4>дефицит</4>."+msgid "Base currency"+msgstr "Базовая валюта"+msgid "Base Currency"msgstr "Базовая валюта"@@ -3215,6 +3218,9 @@ msgstr "Изменение этого обновит ID детали"msgid "Changing type resets this item's draft edits."msgstr "Изменение типа сбрасывает черновые редактирования этого элемента."+msgid "Chart"+msgstr "График"+msgid "Chart of accounts"msgstr "План счетов"@@ -9422,6 +9428,15 @@ msgstr "Отметить как недостача"msgid "Mark to delete"msgstr "Отметить к удалению"+msgid "Market rate"+msgstr "Рыночный курс"++msgid "Market rate (per USD)"+msgstr "Рыночный курс (за USD)"++msgid "Market Rate History (per USD)"+msgstr "История рыночного курса (за USD)"+msgid "Marks the person off for every day in the range. They won't be scheduled while they're away."msgstr "Отмечает человека как отсутствующего на каждый день в диапазоне. Его не будут планировать, пока он отсутствует."@@ -9970,6 +9985,9 @@ msgstr "Новый центр затрат"msgid "New Credit / Debit Memo"msgstr "Новый кредит-нота / дебет-нота"+msgid "New Currency"+msgstr "Новая валюта"+msgid "New Custom Field"msgstr "Новое пользовательское поле"@@ -10601,6 +10619,9 @@ msgstr "Причина отказа от предложения"msgid "No Quote Reasons"msgstr "Причины отказа от предложения"+msgid "No rate"+msgstr "Курс отсутствует"+msgid "No receivables"msgstr "Нет дебиторской задолженности"@@ -10966,6 +10987,11 @@ msgstr "Своевременная доставка"msgid "Onboard your agent to Carbon"msgstr "Подключите вашего агента к Carbon"+#. placeholder {0}: company?.baseCurrencyCode+#. placeholder {1}: initialValues.code+msgid "One {0} is equal to how many {1}?"+msgstr "1 {0} — это сколько {1}?"+msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."msgstr "Одно выполнение рабочего процесса, записанное пошагово со значениями, использованными и созданными каждым шагом, выполняющееся с правами доступа владельца рабочего процесса."@@ -12658,9 +12684,15 @@ msgstr "Поднимите это на еженедельном статус-зmsgid "raise it early and raise it plainly. A problem named in week 2 is a small fix; the same problem at go-live is a delay."msgstr "поднимайте проблемы рано и говорите о них прямо. Проблема, выявленная на 2-й неделе, — это небольшое исправление; та же проблема при запуске — это задержка."+msgid "Rate"+msgstr "Курс"+msgid "Rate Limit"msgstr "Ограничение скорости"+msgid "Rate used for equity account translation in consolidation (IAS 21). Leave blank to use the current exchange rate."+msgstr "Курс, используемый для пересчета счетов собственного капитала при консолидации (IAS 21). Оставьте пустым, чтобы использовать текущий валютный курс."+msgid "Ratio"msgstr "Коэффициент"@@ -13272,6 +13304,9 @@ msgstr "Сброс PIN"msgid "Reset PIN for {0} {1}"msgstr "Сброс PIN для {0} {1}"+msgid "Reset to market rate"+msgstr "Сбросить к рыночному курсу"+msgid "Reset Two-Factor Auth"msgstr "Сбросить двухфакторную аутентификацию"@@ -13808,6 +13843,9 @@ msgstr "Сохранить настройки измерений"msgid "Save Method"msgstr "Сохранить метод"+msgid "Save Rate"+msgstr "Сохранить курс"+msgid "Save view"msgstr "Сохранить представление"@@ -16583,6 +16621,9 @@ msgstr "Это среда, контролируемая ITAR. Доступ огmsgid "This is taking longer than expected. It may still finish — if it doesn't, retry the revert to put your data back."msgstr "Это занимает больше времени, чем ожидалось. Процесс может все еще завершиться — если нет, повторите восстановление, чтобы вернуть ваши данные."+msgid "This is the base currency. Exchange rate is always 1."+msgstr "Это базовая валюта. Валютный курс всегда равен 1."+msgid "This is the month your fiscal year starts."msgstr "Это месяц, когда начинается ваш финансовый год."@@ -18725,6 +18766,9 @@ msgstr "Ваш проект от начала до конца: план, этаmsgid "Your Project Team"msgstr "Ваша команда проекта"+msgid "Your rate"+msgstr "Ваш курс"+msgid "Your real data is loaded and you have checked a sample and approved it."msgstr "Ваши реальные данные загружены, вы проверили образец и одобрили его."diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex bfec4aca5e..fee1785cfa 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -2624,6 +2624,9 @@ msgstr "Banka ve mali hizmet bedeli giderleri"msgid "Bars show each week's flow: <0>supply</0> pushes inventory up, <1>demand</1> pulls it down. The <2>line</2> is your projected on-hand inventory — when it dips below <3>safety stock</3> you're at risk, and below zero is a <4>stockout</4>."msgstr "Çubuklar her haftanın akışını gösterir: <0>arz</0> envanteri yukarı iter, <1>talep</1> onu aşağı çeker. <2>Satır</2> tahmini eldeki envanterdir — <3>emniyet stoku</3> altına düştüğünde risk altındasın ve sıfırın altı bir <4>stoksuzluk</4>."+msgid "Base currency"+msgstr "Ana para birimi"+msgid "Base Currency"msgstr "Temel Para Birimi"@@ -3215,6 +3218,9 @@ msgstr "Bunu değiştirmek parça kimliğini güncelleyecektir"msgid "Changing type resets this item's draft edits."msgstr "Türü değiştirmek bu öğenin taslak düzenlemelerini sıfırlar."+msgid "Chart"+msgstr "Grafik"+msgid "Chart of accounts"msgstr "Hesap planı"@@ -9422,6 +9428,15 @@ msgstr "Az eksik olarak işaretle"msgid "Mark to delete"msgstr "Silmek için işaretle"+msgid "Market rate"+msgstr "Piyasa kuru"++msgid "Market rate (per USD)"+msgstr "Piyasa kuru (USD başına)"++msgid "Market Rate History (per USD)"+msgstr "Piyasa kuru geçmişi (USD başına)"+msgid "Marks the person off for every day in the range. They won't be scheduled while they're away."msgstr "Kişiyi aralıktaki her gün için işaretler. Uzakta iken çizelgelenmazlar."@@ -9970,6 +9985,9 @@ msgstr "Yeni Maliyet Merkezi"msgid "New Credit / Debit Memo"msgstr "Yeni Kredi / Borç Notu"+msgid "New Currency"+msgstr "Yeni Para Birimi"+msgid "New Custom Field"msgstr "Yeni Özel Alan"@@ -10601,6 +10619,9 @@ msgstr "Teklif Nedeni Yok"msgid "No Quote Reasons"msgstr "Teklif Nedeni Yok"+msgid "No rate"+msgstr "Kur yok"+msgid "No receivables"msgstr "Alacak yok"@@ -10966,6 +10987,11 @@ msgstr "Zamanında teslimat"msgid "Onboard your agent to Carbon"msgstr "Aracınızı Carbon'a dahil edin"+#. placeholder {0}: company?.baseCurrencyCode+#. placeholder {1}: initialValues.code+msgid "One {0} is equal to how many {1}?"+msgstr "1 {0} kaç {1} eder?"+msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."msgstr "Bir iş akışının bir kez çalıştırılması, her adımın kullandığı ve ürettiği değerlerle adım adım kaydedilmiş, iş akışının sahibinin izinleriyle hareket eder."@@ -12658,9 +12684,15 @@ msgstr "Bunu haftalık durum çağrısında gündeme getir"msgid "raise it early and raise it plainly. A problem named in week 2 is a small fix; the same problem at go-live is a delay."msgstr "bunu erken ve açık bir şekilde dile getir. 2. haftada adı konulan bir sorun küçük bir düzeltmedir; go-live'da aynı sorun bir gecikmedir."+msgid "Rate"+msgstr "Kur"+msgid "Rate Limit"msgstr "Hız Sınırı"+msgid "Rate used for equity account translation in consolidation (IAS 21). Leave blank to use the current exchange rate."+msgstr "Konsolidasyonda özkaynak hesaplarının çevrimi için kullanılan kur (IAS 21). Güncel döviz kurunu kullanmak için boş bırakın."+msgid "Ratio"msgstr "Oran"@@ -13272,6 +13304,9 @@ msgstr "PIN'i Sıfırla"msgid "Reset PIN for {0} {1}"msgstr "PIN'i sıfırla {0} {1}"+msgid "Reset to market rate"+msgstr "Piyasa kuruna sıfırla"+msgid "Reset Two-Factor Auth"msgstr "İki Faktörlü Kimlik Doğrulamayı Sıfırla"@@ -13808,6 +13843,9 @@ msgstr "Boyut ayarlarını kaydet"msgid "Save Method"msgstr "Yöntemi Kaydet"+msgid "Save Rate"+msgstr "Kuru kaydet"+msgid "Save view"msgstr "Görünümü kaydet"@@ -16583,6 +16621,9 @@ msgstr "Bu ITAR tarafından kontrol edilen bir ortamdır. Erişim yalnızca ABDmsgid "This is taking longer than expected. It may still finish — if it doesn't, retry the revert to put your data back."msgstr "Bu beklenenden daha uzun sürüyor. Yine de bitebilir — olmazsa, verilerinizi geri koymak için geri alma işlemini tekrar deneyin."+msgid "This is the base currency. Exchange rate is always 1."+msgstr "Bu ana para birimidir. Döviz kuru her zaman 1'dir."+msgid "This is the month your fiscal year starts."msgstr "Bu, mali yılınızın başladığı aydır."@@ -18725,6 +18766,9 @@ msgstr "Projeniz baştan sona: plan, kapılar ve canlı yayına geçiş"msgid "Your Project Team"msgstr "Proje Ekibiniz"+msgid "Your rate"+msgstr "Sizin kurunuz"+msgid "Your real data is loaded and you have checked a sample and approved it."msgstr "Gerçek verileriniz yüklendi ve bir örneği kontrol ederek onayladınız."diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 00595e81bb..a7a3055e74 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -2624,6 +2624,9 @@ msgstr "银行和金融服务费用。"msgid "Bars show each week's flow: <0>supply</0> pushes inventory up, <1>demand</1> pulls it down. The <2>line</2> is your projected on-hand inventory — when it dips below <3>safety stock</3> you're at risk, and below zero is a <4>stockout</4>."msgstr "柱状图显示每周的流向:<0>供应</0>推高库存,<1>需求</1>拉低库存。<2>线</2>表示您的预计现有库存 — 当它跌破<3>安全库存</3>时,您面临风险;跌破零则是<4>缺货</4>。"+msgid "Base currency"+msgstr "基础货币"+msgid "Base Currency"msgstr "基础货币"@@ -3215,6 +3218,9 @@ msgstr "更改此项将更新零件ID"msgid "Changing type resets this item's draft edits."msgstr "更改类型将重置此项目的草稿编辑。"+msgid "Chart"+msgstr "图表"+msgid "Chart of accounts"msgstr "会计科目表"@@ -9422,6 +9428,15 @@ msgstr "标记短缺"msgid "Mark to delete"msgstr "标记删除"+msgid "Market rate"+msgstr "市场汇率"++msgid "Market rate (per USD)"+msgstr "市场汇率(兑美元)"++msgid "Market Rate History (per USD)"+msgstr "市场汇率历史(兑美元)"+msgid "Marks the person off for every day in the range. They won't be scheduled while they're away."msgstr "在范围内的每一天都标记该人缺席。他们在外出期间不会被安排。"@@ -9970,6 +9985,9 @@ msgstr "新建成本中心"msgid "New Credit / Debit Memo"msgstr "新建贷方/借方备忘录"+msgid "New Currency"+msgstr "新货币"+msgid "New Custom Field"msgstr "新建自定义字段"@@ -10601,6 +10619,9 @@ msgstr "不报价原因"msgid "No Quote Reasons"msgstr "不报价原因"+msgid "No rate"+msgstr "无汇率"+msgid "No receivables"msgstr "没有应收款项"@@ -10966,6 +10987,11 @@ msgstr "准时交付"msgid "Onboard your agent to Carbon"msgstr "将您的代理接入Carbon"+#. placeholder {0}: company?.baseCurrencyCode+#. placeholder {1}: initialValues.code+msgid "One {0} is equal to how many {1}?"+msgstr "1 {0} 等于多少 {1}?"+msgid "One firing of a workflow, recorded step by step with the values each step used and produced, acting throughout with the permissions of the workflow's owner."msgstr "一次工作流执行,逐步记录每个步骤使用和产生的值,始终以工作流负责人的权限行动。"@@ -12658,9 +12684,15 @@ msgstr "在每周状态会议上提出"msgid "raise it early and raise it plainly. A problem named in week 2 is a small fix; the same problem at go-live is a delay."msgstr "尽早提出问题,直言不讳地提出。第2周发现的问题很容易修复;同样的问题在上线时就会导致延期。"+msgid "Rate"+msgstr "汇率"+msgid "Rate Limit"msgstr "速率限制"+msgid "Rate used for equity account translation in consolidation (IAS 21). Leave blank to use the current exchange rate."+msgstr "合并时用于所有者权益账户折算的汇率(IAS 21)。留空则使用当前汇率。"+msgid "Ratio"msgstr "比率"@@ -13272,6 +13304,9 @@ msgstr "重置PIN"msgid "Reset PIN for {0} {1}"msgstr "重置 {0} {1} 的 PIN"+msgid "Reset to market rate"+msgstr "重置为市场汇率"+msgid "Reset Two-Factor Auth"msgstr "重置双因素认证"@@ -13808,6 +13843,9 @@ msgstr "保存维度设置"msgid "Save Method"msgstr "保存方法"+msgid "Save Rate"+msgstr "保存汇率"+msgid "Save view"msgstr "保存视图"@@ -16583,6 +16621,9 @@ msgstr "这是一个ITAR管制环境。访问仅限于美国人。"msgid "This is taking longer than expected. It may still finish — if it doesn't, retry the revert to put your data back."msgstr "这比预期花费的时间更长。它可能仍会完成——如果没有,请重试还原以恢复您的数据。"+msgid "This is the base currency. Exchange rate is always 1."+msgstr "这是本位币。汇率始终为1。"+msgid "This is the month your fiscal year starts."msgstr "这是你会计年度开始的月份。"@@ -18729,6 +18770,9 @@ msgstr "您的项目端到端:计划、关卡和上线"msgid "Your Project Team"msgstr "您的项目团队"+msgid "Your rate"+msgstr "自定义汇率"+msgid "Your real data is loaded and you have checked a sample and approved it."msgstr "您的真实数据已加载,您已检查样本并批准了它。"