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
AR/AP Payments (#833)
Brad Barbinc938d809046e
diff --git a/.claude/skills/test/SKILL.md b/.claude/skills/test/SKILL.mdindex e6879dc2eb..60f12df719 100644--- a/.claude/skills/test/SKILL.md+++ b/.claude/skills/test/SKILL.md@@ -96,13 +96,41 @@ agent-browser click @eN # open the dropdownagent-browser snapshot -i # find the option refsagent-browser click @eM # select the option```+Clicking an option updates the field's React state correctly (it persists across+re-renders), so comboboxes are reliable.-**Submit:**+**Number / currency / date fields (react-aria — IMPORTANT):**+These render a *visible* formatted input plus a *hidden* input that actually carries+the form value (e.g. `<input type=hidden name="amount">`). react-aria only commits+the hidden input **on blur**, not on each keystroke. So you MUST fill, then blur:```bash-agent-browser click @eN # click the submit/save button+agent-browser fill @eN "300" # the visible field+agent-browser click @eM # click ANY other field to blur → commits hidden input+# verify it committed:+agent-browser eval "document.querySelector('input[name=amount]').value" # => "300"+```+`agent-browser type` often does NOT reach these fields — use `fill` + blur.++**Submit (CRITICAL — do NOT click the submit button):**+Carbon forms are `@carbon/form` `ValidatedForm` (vendored remix-validated-form). Its+submit handler only runs on a **native `submit` event that carries a `submitter`**+(`if (submitter?.form !== target) return;` — it bails silently otherwise). An+agent-browser `click` on the Save button does **not** trigger that native submit, so+nothing happens (no error, no navigation). Submit programmatically instead, passing+the button as the submitter:+```bash+agent-browser eval "(()=>{const b=[...document.querySelectorAll('button')].find(x=>x.type==='submit'&&x.textContent.trim()==='Save');const f=b.closest('form');f.requestSubmit(b);return 'submitted'})()"agent-browser wait --load networkidle-agent-browser snapshot -i # verify the result+agent-browser snapshot -i # verify the result (redirect / toast)```+Adjust the button text (`'Save'`/`'Create'`/`'Submit'`) to match the form. The+handler validates `new FormData(form)` (the real DOM) synchronously, so as long as+every field's value/hidden-input is set (see number-field note above), this submits+exactly as a real user click would — exercising the real client validation + action.++> If a submit "does nothing", it's almost always one of: (a) you clicked the button+> instead of `requestSubmit`-ing, or (b) a react-aria number/date field's hidden input+> never committed (you didn't blur it). Verify the hidden inputs before blaming the form.#### 6c. Verify the result@@ -146,7 +174,7 @@ Route: <URL path>- ...### 3. Submit-- Button: "<button label>"+- `requestSubmit` the form whose submit button reads "<button label>" (NOT a click)### 4. Verify- Expected redirect: `/x/<route>/<id>`@@ -193,11 +221,14 @@ agent-browser close- **Required fields** are marked with asterisks or show validation errors on submit- **Combobox/select fields** need a click to open, then a search or click on an option-- **Date fields** can be typed directly in `YYYY-MM-DD` format-- **Number fields** accept plain numbers-- **The submit button** is usually labeled "Save", "Create", or "Submit" and is at the bottom of the form or in the footer+- **Number / currency / date fields** are react-aria: `fill` the visible input then+ **blur** (click another field) so the hidden `name=...` input commits. `type` often+ doesn't reach them. Verify with `eval "document.querySelector('input[name=X]').value"`.+- **Submit with `requestSubmit`, never a click** — see step 6b. A plain agent-browser+ click on the Save button does NOT fire the native submit that `ValidatedForm`+ requires, so the form silently does nothing.- **After creating a record**, the app typically redirects to the detail page with the new record's ID in the URL-- **Drawer forms** (child routes) appear as overlays — look for the drawer's submit button, not the parent page's+- **Drawer forms** (child routes) appear as overlays — `requestSubmit` the drawer's own form (the one containing the drawer's submit button), not the parent page's- **Toast notifications** appear briefly — check the snapshot immediately after submission## Failure Handlingdiff --git a/.claude/skills/test/playbooks/create-and-apply-payment.md b/.claude/skills/test/playbooks/create-and-apply-payment.mdnew file mode 100644index 0000000000..2258a64a8e--- /dev/null+++ b/.claude/skills/test/playbooks/create-and-apply-payment.md@@ -0,0 +1,60 @@+# Create & Apply Payment (AR Receipt / AP Disbursement)++Last tested: 2026-06-16+Routes: `/x/payment`, `/x/payment/new`, `/x/payment/$paymentId`++## Prerequisites+- A `payment` sequence row must exist for the company. New companies get it from the+ `sequences` array in `seed.data.ts`; existing companies from migration+ `20260519120000` Phase 8. If missing, payment creation fails with+ "Failed to allocate payment id".+- At least one open invoice:+ - AR: a `salesInvoice` with status `Submitted` (or `Partially Paid`/`Overdue`) and balance > 0.+ - AP: a `purchaseInvoice` with status `Open` (or `Partially Paid`/`Overdue`) and balance > 0.+- At least one `Asset`-class GL account to use as the bank/cash account.++## Steps (invoice-driven, the primary flow)++### 1. Open the invoice and start a payment+- Sales: `/x/sales/invoices` → open the invoice → header button **"Receive Payment"**+ (only shown when status ∉ {Voided, Draft, Pending, Paid} and balance > 0).+- Purchase: equivalent "pay" entry on the purchase invoice header.+- This navigates to `/x/payment/new` pre-filled:+ `?customerId=…&invoiceId=…&amount=<balance>` (AR, paymentType=Receipt) or+ `?supplierId=…&invoiceId=…&amount=<balance>` (AP, paymentType=Disbursement).++### 2. Fill the New Payment form+- Type / Customer-or-Supplier / Currency / Exchange Rate / Total Amount are pre-filled.+- **Bank / Cash Account** (required) — select an Asset account (e.g. "1010 Bank - Cash").+- Submit "Save". On submit the action auto-creates a starter `paymentApplication`+ against the seed invoice for the full amount, then redirects to the payment detail.++### 3. Post the payment+- On `/x/payment/$paymentId`, click **Post** (Draft only). Calls the `post-payment`+ edge function: sets status `Posted`, and creates GL journals only if+ `accountingEnabled` for the company (otherwise journalId stays null — expected).++### 4. Verify (derived status + balance)+- Balance/status are DERIVED in the `salesInvoices` / `purchaseInvoices` views from+ Posted payment applications (migration `20260519130000`). Draft payments are ignored.+- Partial pay → invoice `Partially Paid`, balance = total − applied.+- Full pay → invoice `Paid`, balance 0.++## Selector Notes+- Bank/Cash Account combobox is the one whose value reads "Select" before selection;+ the submitted value is the account `id` (`acct_…`), rendered as "<number> <name>".+- The Number (Total Amount) field is finicky in agent-browser: `fill` appends to the+ pre-filled value, and the hidden input resets when sibling fields re-render. Easiest:+ leave the pre-filled amount untouched (full balance), or set amount LAST.+- After Save the browser may show a lingering spinner even though the server succeeded —+ verify by checking the DB / navigating to `/x/payment/$id` directly.++## Common Failures (all fixed on feat/ar-ap-payments)+- "Failed to allocate payment id" — no `payment` sequence row for the company.+- "Failed to create payment" — `new.tsx` spread a hidden `id:""` (→ null) into the+ insert, violating the NOT NULL `id` (which has an `xid()` default). Fix: omit `id` on create.+- `ERR_TOO_MANY_REDIRECTS` on the detail page — `$paymentId._index.tsx` redirected to+ `path.to.payment(id)` (itself). Fix: removed the vestigial index; `$paymentId.tsx`+ renders the detail directly.+- `payment_party_check` — a Receipt must have customerId set & supplierId null+ (Disbursement the reverse). The form omits the inactive party, so it's null — fine.diff --git a/apps/academy/app/config.tsx b/apps/academy/app/config.tsxindex 4bbfe37574..132ad4aad6 100644--- a/apps/academy/app/config.tsx+++ b/apps/academy/app/config.tsx@@ -1,4 +1,5 @@import {+ LuBlocks,LuBox,LuCalculator,LuCirclePlay,@@ -8,7 +9,6 @@ import {LuHexagon,LuShapes,LuShoppingCart,- LuSquareStack,LuTruck,LuTvMinimalPlay,LuUpload@@ -362,7 +362,7 @@ export const modules: Config = [id: "defining-item",description:"Learn how to define and manage different types of items in Carbon.",- icon: <LuSquareStack />,+ icon: <LuBlocks />,topics: [{name: "Item Types",diff --git a/apps/erp/app/assets/icons/BanknoteArrows.tsx b/apps/erp/app/assets/icons/BanknoteArrows.tsxnew file mode 100644index 0000000000..1d57023bfa--- /dev/null+++ b/apps/erp/app/assets/icons/BanknoteArrows.tsx@@ -0,0 +1,53 @@+import { GenIcon } from "react-icons/lib";++// Lucide `banknote-arrow-up` / `banknote-arrow-down` (ISC license). These icons+// exist in Lucide but are not yet shipped in [email protected] — the latest+// published release — so there is no react-icons version to upgrade to that+// exposes them as `LuBanknoteArrowUp` / `LuBanknoteArrowDown`. We render them via+// react-icons' own `GenIcon` so they are drop-in identical to the other `Lu*`+// icons (1em sizing, currentColor stroke, className, IconContext). When a future+// react-icons release adds them, swap these for the `Lu*` imports and delete this+// file. Path data copied verbatim from [email protected].++const lucideSvgAttr = {+ fill: "none",+ stroke: "currentColor",+ strokeWidth: "2",+ strokeLinecap: "round",+ strokeLinejoin: "round",+ viewBox: "0 0 24 24"+};++export const BanknoteArrowUp = GenIcon({+ tag: "svg",+ attr: lucideSvgAttr,+ child: [+ {+ tag: "path",+ attr: { d: "M12 18H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5" },+ child: []+ },+ { tag: "path", attr: { d: "M18 12h.01" }, child: [] },+ { tag: "path", attr: { d: "M19 22v-6" }, child: [] },+ { tag: "path", attr: { d: "m22 19-3-3-3 3" }, child: [] },+ { tag: "path", attr: { d: "M6 12h.01" }, child: [] },+ { tag: "circle", attr: { cx: "12", cy: "12", r: "2" }, child: [] }+ ]+});++export const BanknoteArrowDown = GenIcon({+ tag: "svg",+ attr: lucideSvgAttr,+ child: [+ {+ tag: "path",+ attr: { d: "M12 18H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5" },+ child: []+ },+ { tag: "path", attr: { d: "m16 19 3 3 3-3" }, child: [] },+ { tag: "path", attr: { d: "M18 12h.01" }, child: [] },+ { tag: "path", attr: { d: "M19 16v6" }, child: [] },+ { tag: "path", attr: { d: "M6 12h.01" }, child: [] },+ { tag: "circle", attr: { cx: "12", cy: "12", r: "2" }, child: [] }+ ]+});diff --git a/apps/erp/app/components/Icons.tsx b/apps/erp/app/components/Icons.tsxindex 4cbbc1a8de..c2cfc0eb19 100644--- a/apps/erp/app/components/Icons.tsx+++ b/apps/erp/app/components/Icons.tsx@@ -17,7 +17,9 @@ import { FaCodePullRequest } from "react-icons/fa6";import {LuArrowLeftRight,LuAtom,+ LuBanknote,LuBarcode,+ LuBlocks,LuBookOpen,LuBox,LuBuilding,@@ -46,7 +48,6 @@ import {LuLandmark,LuList,LuMapPin,- LuPackage,LuPizza,LuQrCode,LuRotateCcw,@@ -581,7 +582,7 @@ export const JournalEntrySourceTypeIcon = ({case "Transfer Receipt":return <LuArrowLeftRight className={className} />;case "Inventory Adjustment":- return <LuPackage className={className} />;+ return <LuBlocks className={className} />;case "Production Order":return <LuCirclePlay className={className} />;case "Job Consumption":@@ -596,6 +597,12 @@ export const JournalEntrySourceTypeIcon = ({return <LuClock className={className} />;case "Asset Disposal":return <LuBuilding2 className={className} />;+ case "Payment":+ return <LuBanknote className={className} />;+ case "Credit Memo":+ return <LuCreditCard className={className} />;+ case "Debit Memo":+ return <LuCreditCard className={className} />;}return <LuSquare className={cn("text-muted-foreground", className)} />;@@ -619,6 +626,12 @@ export const DimensionEntityTypeIcon = ({return <LuContainer className={className} />;case "CustomerType":return <LuUsers className={className} />;+ case "Customer":+ return <LuUser className={className} />;+ case "Supplier":+ return <LuContainer className={className} />;+ case "Item":+ return <LuBlocks className={className} />;case "Department":return <LuBuilding className={className} />;case "Employee":diff --git a/apps/erp/app/components/ItemThumbnail.tsx b/apps/erp/app/components/ItemThumbnail.tsxindex 6a00cabe33..00a0aea27f 100644--- a/apps/erp/app/components/ItemThumbnail.tsx+++ b/apps/erp/app/components/ItemThumbnail.tsx@@ -1,6 +1,6 @@import { cn } from "@carbon/react";import { cva } from "class-variance-authority";-import { LuSquareStack } from "react-icons/lu";+import { LuBlocks } from "react-icons/lu";import type { MethodItemType } from "~/modules/shared";import { getPrivateUrl } from "~/utils/path";import { MethodItemTypeIcon } from "./Icons";@@ -85,7 +85,7 @@ const ItemThumbnail = ({{type ? (<MethodItemTypeIcon className={iconVariants({ size })} type={type} />) : (- <LuSquareStack className={iconVariants({ size })} />+ <LuBlocks className={iconVariants({ size })} />)}</div>);diff --git a/apps/erp/app/components/Layout/Topbar/CreateMenu.tsx b/apps/erp/app/components/Layout/Topbar/CreateMenu.tsxindex 29043cfbe2..474d379327 100644--- a/apps/erp/app/components/Layout/Topbar/CreateMenu.tsx+++ b/apps/erp/app/components/Layout/Topbar/CreateMenu.tsx@@ -8,11 +8,11 @@ import {import { useLingui } from "@lingui/react/macro";import { useMemo } from "react";import {+ LuBlocks,LuCirclePlay,LuContainer,LuShieldX,LuShoppingCart,- LuSquareStack,LuSquareUser,LuUsers,LuWrench@@ -37,7 +37,7 @@ function useCreate(): Route[] {links.push({name: t`Part`,to: path.to.newPart,- icon: <LuSquareStack />+ icon: <LuBlocks />});}diff --git a/apps/erp/app/components/Layout/Topbar/Search.tsx b/apps/erp/app/components/Layout/Topbar/Search.tsxindex fa894a0b1f..a3827a386f 100644--- a/apps/erp/app/components/Layout/Topbar/Search.tsx+++ b/apps/erp/app/components/Layout/Topbar/Search.tsx@@ -524,14 +524,14 @@ function useGroupedSubmodules() {const groups = groupedSubmodules[moduleName].groups;acc = {...acc,- [module.name]: groups.flatMap((group) =>- group.routes.map((route) => ({+ [module.name]: groups+ .flatMap((group) => group.routes)+ .map((route) => ({to: route.to,name: route.name,icon: module.icon,iconElement: route.icon}))- )};} else if (moduleName in ungroupedSubmodules ||diff --git a/apps/erp/app/hooks/useModules.tsx b/apps/erp/app/hooks/useModules.tsxindex b9435e7bf3..cea8c2d02e 100644--- a/apps/erp/app/hooks/useModules.tsx+++ b/apps/erp/app/hooks/useModules.tsx@@ -1,16 +1,16 @@import { useRouteData } from "@carbon/react";import { useLingui } from "@lingui/react/macro";import {+ LuBlocks,LuBox,+ LuCreditCard,LuCrown,LuFactory,- LuFiles,LuFolderCheck,LuLandmark,LuSettings,LuShield,LuShoppingCart,- LuSquareStack,LuTvMinimalPlay,LuUsers,LuWrench@@ -52,13 +52,14 @@ function useModuleDefinitions(): ModuleDefinition[] {to: path.to.chartOfAccounts,icon: LuLandmark},- {- key: "documents",- permission: "documents",- name: t`Documents`,- to: path.to.documents,- icon: LuFiles- },+ // Documents module hidden for now.+ // {+ // key: "documents",+ // permission: "documents",+ // name: t`Documents`,+ // to: path.to.documents,+ // icon: LuFiles+ // },{key: "inventory",permission: "inventory",@@ -66,12 +67,19 @@ function useModuleDefinitions(): ModuleDefinition[] {to: path.to.inventory,icon: LuBox},+ {+ key: "invoicing",+ permission: "invoicing",+ name: t`Invoicing`,+ to: path.to.invoicing,+ icon: LuCreditCard+ },{key: "parts",permission: "parts",name: t`Items`,to: path.to.parts,- icon: LuSquareStack+ icon: LuBlocks},{key: "people",diff --git a/apps/erp/app/hooks/usePlanGate.ts b/apps/erp/app/hooks/usePlanGate.tsindex b6fe684240..5f94a503e3 100644--- a/apps/erp/app/hooks/usePlanGate.ts+++ b/apps/erp/app/hooks/usePlanGate.ts@@ -8,10 +8,11 @@ import { useFlags } from "~/hooks/useFlags";export function usePlanGate(spec: GateSpec) {const currentPlan = usePlan();- const { isCloud } = useFlags();+ const { isCloud, isCommunity } = useFlags();const requirement = resolveRequirement(spec);- const isGated = isCloud && !planMeetsRequirement(currentPlan, requirement);+ const isGated =+ isCommunity || (isCloud && !planMeetsRequirement(currentPlan, requirement));return { isGated, plan: currentPlan, allowedPlans: requirement };}diff --git a/apps/erp/app/modules/accounting/accounting.models.ts b/apps/erp/app/modules/accounting/accounting.models.tsindex 20892f2aff..eb1876cfdb 100644--- a/apps/erp/app/modules/accounting/accounting.models.ts+++ b/apps/erp/app/modules/accounting/accounting.models.ts@@ -336,6 +336,18 @@ export const defaultIncomeAcountValidator = z.object({customerPaymentDiscountAccount: z.string().min(1, {message: "Customer payment discount account is required"}),+ customerWriteOffAccount: z.string().min(1, {+ message: "Customer write-off account is required"+ }),+ supplierWriteOffAccount: z.string().min(1, {+ message: "Supplier write-off account is required"+ }),+ realizedExchangeGainAccount: z.string().min(1, {+ message: "Realized exchange gain account is required"+ }),+ realizedExchangeLossAccount: z.string().min(1, {+ message: "Realized exchange loss account is required"+ }),roundingAccount: z.string().min(1, {message: "Rounding account is required"}),@@ -461,7 +473,10 @@ export const journalEntrySourceTypes = ["Production Event","Job Close","Asset Depreciation",- "Asset Disposal"+ "Asset Disposal",+ "Payment",+ "Credit Memo",+ "Debit Memo"] as const;export const journalEntryStatuses = ["Draft", "Posted", "Reversed"] as const;@@ -493,13 +508,16 @@ export const journalEntryLineValidator = zexport const dimensionEntityTypes = ["CostCenter","Custom",+ "Customer","CustomerType","Department","Employee","FixedAssetClass",+ "Item","ItemPostingGroup","Location","Process",+ "Supplier","SupplierType","WorkCenter"] as const;diff --git a/apps/erp/app/modules/accounting/accounting.service.ts b/apps/erp/app/modules/accounting/accounting.service.tsindex e73d7484f2..5cdd6be830 100644--- a/apps/erp/app/modules/accounting/accounting.service.ts+++ b/apps/erp/app/modules/accounting/accounting.service.ts@@ -29,6 +29,7 @@ import type {taxDepreciationMethods} from "./accounting.models";import type { Transaction, TranslatedBalance } from "./types";+import { NET_INCOME_ACCOUNT_ID } from "./types";/*** Sign multiplier for root account aggregation.@@ -139,6 +140,8 @@ export async function getFinancialStatementBalances(args: {startDate: string | null;endDate: string | null;+ // Balance sheet only: append a computed "Net Income" equity line.+ includeCurrentYearEarnings?: boolean;}) {let accountsQuery = client@@ -176,17 +179,68 @@ export async function getFinancialStatementBalances(return acc;}, {});+ const mapped = (accountsResponse.data ?? [])+ .filter((a): a is typeof a & { id: string } => a.id !== null)+ .map((account) => ({+ ...account,+ netChange: balancesByAccountId[account.id]?.netChange ?? 0,+ balance: balancesByAccountId[account.id]?.balance ?? 0,+ balanceAtDate: balancesByAccountId[account.id]?.balanceAtDate ?? 0+ }));++ // Undistributed net income lives only in income-statement accounts until it is+ // closed. A balance sheet at any date must carry it inside equity, or+ // Assets ≠ Liabilities + Equity. We surface it as a computed "Net Income"+ // equity line — the same pattern NetSuite ("Net Income" line), QuickBooks, and+ // SAP (FSV net-result node) use: a calculated equity row, never a posted close.+ if (args.includeCurrentYearEarnings) {+ const balanceSheetRoot = mapped.find(+ (a) =>+ a.incomeBalance === "Balance Sheet" &&+ (a.isSystem ?? a.parentId === null)+ );+ const equityGroup = mapped.find(+ (a) =>+ a.class === "Equity" && a.isGroup && a.parentId === balanceSheetRoot?.id+ );+ if (balanceSheetRoot && equityGroup) {+ // Net income = Revenue − Expenses over income-statement LEAF accounts,+ // signed exactly like the Income Statement report's bottom line.+ let balance = 0;+ let balanceAtDate = 0;+ let netChange = 0;+ for (const a of mapped) {+ if (a.incomeBalance !== "Income Statement" || a.isGroup) continue;+ const sign = rootSignMultiplier(a.class);+ balance += sign * a.balance;+ balanceAtDate += sign * a.balanceAtDate;+ netChange += sign * a.netChange;+ }+ // Roll into the Equity group subtotal so the section ties out;+ // applyRootSignCorrection recomputes the Balance Sheet root from its+ // direct children, so the root nets to ~0.+ equityGroup.balance += balance;+ equityGroup.balanceAtDate += balanceAtDate;+ equityGroup.netChange += netChange;+ // Clone the Equity group to inherit every account column the report needs,+ // then override identity + balances. Must NOT be isSystem — a system row+ // is treated as a root by applyRootSignCorrection and recomputed to zero.+ mapped.push({+ ...equityGroup,+ id: NET_INCOME_ACCOUNT_ID,+ name: "Net Income",+ isGroup: false,+ isSystem: false,+ parentId: equityGroup.id,+ balance,+ balanceAtDate,+ netChange+ });+ }+ }+return {- data: applyRootSignCorrection(- (accountsResponse.data ?? [])- .filter((a): a is typeof a & { id: string } => a.id !== null)- .map((account) => ({- ...account,- netChange: balancesByAccountId[account.id]?.netChange ?? 0,- balance: balancesByAccountId[account.id]?.balance ?? 0,- balanceAtDate: balancesByAccountId[account.id]?.balanceAtDate ?? 0- }))- ),+ data: applyRootSignCorrection(mapped),error: null};}@@ -1047,6 +1101,12 @@ function getEntityDimensionValues(.select("id, name").eq("companyId", companyId).order("name");+ // Customer / Supplier / Item are high-cardinality: intentionally NOT+ // eager-loaded here. The DimensionSelector sources their options lazily+ // from the client stores (useCustomers / useSuppliers / useItems).+ case "Customer":+ case "Supplier":+ case "Item":default:return Promise.resolve({data: [] as { id: string; name: string }[],@@ -1167,6 +1227,16 @@ function getEntityValuesByIds(return client.from("costCenter").select("id, name").in("id", ids);case "FixedAssetClass":return client.from("fixedAssetClass").select("id, name").in("id", ids);+ case "Customer":+ return client.from("customer").select("id, name").in("id", ids);+ case "Supplier":+ return client.from("supplier").select("id, name").in("id", ids);+ case "Item":+ // The human-friendly label for an item is its readableId-with-revision.+ return client+ .from("item")+ .select("id, name:readableIdWithRevision")+ .in("id", ids);default:return Promise.resolve({data: [] as { id: string; name: string }[],@@ -1843,25 +1913,31 @@ export async function postJournalEntry(return { data: null, error: { message: "Journal entry has no lines" } };}- // 2. Validate balance. Amounts are stored in natural-balance convention- // (toStoredAmount), so a balanced entry has Σdebits === Σcredits, not- // Σamount === 0 (that only holds if every account were natural-debit).- let debits = 0;- let credits = 0;- for (const line of lines) {- const accountClass = line.account?.class;+ // 2. Validate balance. journalLine.amount is a class-signed *natural balance*+ // (e.g. a liability credit and an expense debit are both positive), so a+ // balanced entry does NOT sum to zero — it has equal total debits and+ // credits once each amount is decoded by its account class.+ let totalDebit = 0;+ let totalCredit = 0;+ for (const l of lines) {+ const account = l.account as+ | { class?: string }+ | { class?: string }[]+ | null;+ const accountClass = (+ Array.isArray(account) ? account[0]?.class : account?.class+ ) as Parameters<typeof toDisplayDebit>[1] | undefined;if (!accountClass) {return {data: null,- error: { message: "Journal line is missing an account" }+ error: { message: "A journal line is missing its account class" }};}- const amount = Number(line.amount);- debits += toDisplayDebit(amount, accountClass);- credits += toDisplayCredit(amount, accountClass);+ totalDebit += toDisplayDebit(Number(l.amount), accountClass);+ totalCredit += toDisplayCredit(Number(l.amount), accountClass);}- if (Math.abs(debits - credits) > 0.001) {+ if (Math.abs(totalDebit - totalCredit) > 0.001) {return {data: null,error: { message: "Total debits must equal total credits" }diff --git a/apps/erp/app/modules/accounting/types.ts b/apps/erp/app/modules/accounting/types.tsindex 54dad17d8a..6fb97a5592 100644--- a/apps/erp/app/modules/accounting/types.ts+++ b/apps/erp/app/modules/accounting/types.ts@@ -32,6 +32,11 @@ export type AccountType = Database["public"]["Enums"]["accountType"];export type Chart = Account & Transaction;+// Synthetic id for the computed "Net Income" equity line on the balance sheet+// (undistributed current earnings rolled into equity — never a posted account).+// Shared so the report tree can recognize and order/decorate the row.+export const NET_INCOME_ACCOUNT_ID = "net-income";+export type CostCenter = NonNullable<Awaited<ReturnType<typeof getCostCenters>>["data"]>[number];diff --git a/apps/erp/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsx b/apps/erp/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsxindex 2545728c75..ae8988f442 100644--- a/apps/erp/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsx+++ b/apps/erp/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsx@@ -20,7 +20,7 @@ type AccountDefaultField = {description: string;accountType: AccountType;badgeType: BadgeType;- termId: TermId;+ termId?: TermId;};type CategoryGroup = {@@ -115,6 +115,13 @@ const AccountDefaultsForm = ({accountType: "balance",badgeType: "Asset",termId: "account-default-prepayments"+ },+ {+ name: "customerWriteOffAccount",+ label: t`Customer Write-Off (Bad Debt)`,+ description: t`Expense account for customer balances written off as uncollectable on AR settlement`,+ accountType: "income",+ badgeType: "Expense"}]},@@ -208,6 +215,13 @@ const AccountDefaultsForm = ({accountType: "balance",badgeType: "Liability",termId: "account-default-gr-ir"+ },+ {+ name: "supplierWriteOffAccount",+ label: t`Vendor Write-Off Income`,+ description: t`Other Income account for vendor balances cleared without full payment on AP settlement`,+ accountType: "income",+ badgeType: "Revenue"}]},@@ -293,6 +307,13 @@ const AccountDefaultsForm = ({accountType: "income",badgeType: "Revenue",termId: "account-default-sales-discounts"+ },+ {+ name: "realizedExchangeGainAccount",+ label: t`Realized Exchange Gain`,+ description: t`Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate`,+ accountType: "income",+ badgeType: "Revenue"}]},@@ -459,6 +480,13 @@ const AccountDefaultsForm = ({accountType: "income",badgeType: "Expense",termId: "account-default-deferred-tax-expense"+ },+ {+ name: "realizedExchangeLossAccount",+ label: t`Realized Exchange Loss`,+ description: t`Expense account for FX losses when a payment settles a foreign-currency invoice at a less favorable rate`,+ accountType: "income",+ badgeType: "Expense"}]}@@ -549,12 +577,16 @@ const AccountDefaultsForm = ({<div className="flex-1 min-w-0"><div className="flex items-center gap-2 mb-1"><h3 className="text-sm font-medium text-foreground">- <LabelWithHelp- variant="inline"- termId={field.termId}- >- {field.label}- </LabelWithHelp>+ {field.termId ? (+ <LabelWithHelp+ variant="inline"+ termId={field.termId}+ >+ {field.label}+ </LabelWithHelp>+ ) : (+ field.label+ )}</h3><Badge variant={badgeColors[field.badgeType]}>{field.badgeType}diff --git a/apps/erp/app/modules/accounting/ui/Dimensions/DimensionForm.tsx b/apps/erp/app/modules/accounting/ui/Dimensions/DimensionForm.tsxindex 3fb44752c0..f3cc442059 100644--- a/apps/erp/app/modules/accounting/ui/Dimensions/DimensionForm.tsx+++ b/apps/erp/app/modules/accounting/ui/Dimensions/DimensionForm.tsx@@ -29,13 +29,18 @@ type DimensionFormProps = {const entityTypeLabels: Record<string, string> = {Custom: "Custom",Location: "Location",+ Item: "Item",ItemPostingGroup: "Item Group",+ Supplier: "Supplier",SupplierType: "Supplier Type",+ Customer: "Customer",CustomerType: "Customer Type",Department: "Department",Employee: "Employee",FixedAssetClass: "Asset Class",- CostCenter: "Cost Center"+ CostCenter: "Cost Center",+ WorkCenter: "Work Center",+ Process: "Process"};const DimensionForm = ({ initialValues, onClose }: DimensionFormProps) => {diff --git a/apps/erp/app/modules/accounting/ui/JournalEntries/DimensionSelector.tsx b/apps/erp/app/modules/accounting/ui/JournalEntries/DimensionSelector.tsxindex 2cc01b198e..af17ce3dcd 100644--- a/apps/erp/app/modules/accounting/ui/JournalEntries/DimensionSelector.tsx+++ b/apps/erp/app/modules/accounting/ui/JournalEntries/DimensionSelector.tsx@@ -1,10 +1,12 @@import {Badge,BadgeCloseButton,+ Combobox,cn,DropdownMenu,DropdownMenuContent,DropdownMenuIcon,+ DropdownMenuItem,DropdownMenuLabel,DropdownMenuRadioGroup,DropdownMenuRadioItem,@@ -14,13 +16,21 @@ import {DropdownMenuSubTrigger,DropdownMenuTrigger} from "@carbon/react";-import { useCallback } from "react";+import { useCallback, useMemo, useState } from "react";import { LuPlus } from "react-icons/lu";import { useFetcher } from "react-router";import { DimensionEntityTypeIcon } from "~/components/Icons";+import { useCustomers, useItems, useSuppliers } from "~/stores";import { path } from "~/utils/path";import type { DimensionWithValues, JournalLineDimensionValue } from "./types";+/**+ * Entity types with far too many rows to eagerly load into a radio list. Their+ * options are sourced lazily from the client stores (useCustomers / useSuppliers+ * / useItems) and rendered with a searchable, virtualized Combobox instead.+ */+const HIGH_CARDINALITY_ENTITY_TYPES = new Set(["Customer", "Supplier", "Item"]);+type DimensionSelectorProps = {journalLineId: string;availableDimensions: DimensionWithValues[];@@ -37,8 +47,13 @@ const entityTypeColors: Record<string, string> = {"bg-indigo-100 text-indigo-800 dark:bg-indigo-500/15 dark:text-indigo-400 border-indigo-500/20",CustomerType:"bg-yellow-100 text-yellow-800 dark:bg-yellow-500/15 dark:text-yellow-400 border-yellow-500/20",+ Customer:+ "bg-amber-100 text-amber-800 dark:bg-amber-500/15 dark:text-amber-400 border-amber-500/20",SupplierType:"bg-emerald-100 text-emerald-800 dark:bg-emerald-500/15 dark:text-emerald-400 border-emerald-500/20",+ Supplier:+ "bg-green-100 text-green-800 dark:bg-green-500/15 dark:text-green-400 border-green-500/20",+ Item: "bg-fuchsia-100 text-fuchsia-800 dark:bg-fuchsia-500/15 dark:text-fuchsia-400 border-fuchsia-500/20",Location:"bg-blue-100 text-blue-800 dark:bg-blue-500/15 dark:text-blue-400 border-blue-500/20",CostCenter:@@ -65,6 +80,32 @@ const DimensionSelector = ({}: DimensionSelectorProps) => {const fetcher = useFetcher();+ const [customers] = useCustomers();+ const [suppliers] = useSuppliers();+ const [items] = useItems();++ // High-cardinality dimensions the user has chosen to add from the dropdown+ // but not yet given a value — these render their searchable Combobox inline.+ const [activeHighCardIds, setActiveHighCardIds] = useState<Set<string>>(+ new Set()+ );++ // Lazily-sourced options for the high-cardinality entity types, keyed by+ // entityType. Built from the client stores so we never round-trip thousands+ // of rows through the loader.+ const optionsByEntityType = useMemo(+ () => ({+ Customer: customers.map((c) => ({ value: c.id, label: c.name })),+ Supplier: suppliers.map((s) => ({ value: s.id, label: s.name })),+ Item: items.map((i) => ({+ value: i.id,+ label: i.readableIdWithRevision,+ helper: i.name+ }))+ }),+ [customers, suppliers, items]+ );+const valueByDimension = new Map(currentDimensions.map((d) => [d.dimensionId, d.valueId]));@@ -89,38 +130,98 @@ const DimensionSelector = ({[autoSave, fetcher, journalLineId]);- function handleValueChange(dim: DimensionWithValues, valueId: string) {- const val = dim.values.find((v) => v.id === valueId);- if (!val) return;-+ function applyDimension(+ dim: DimensionWithValues,+ valueId: string,+ valueName: string+ ) {const updated = [...currentDimensions.filter((d) => d.dimensionId !== dim.dimensionId),{dimensionId: dim.dimensionId,dimensionName: dim.dimensionName,- valueId: val.id,- valueName: val.name+ valueId,+ valueName}];onChange(updated);persistDimensions(updated);}+ // Low-cardinality types: value + name both come from the preloaded radio list.+ function handleValueChange(dim: DimensionWithValues, valueId: string) {+ const val = dim.values.find((v) => v.id === valueId);+ if (!val) return;+ applyDimension(dim, val.id, val.name);+ }++ // High-cardinality types: resolve the name from the store-backed option.+ function handleComboboxChange(dim: DimensionWithValues, valueId: string) {+ if (!valueId) {+ handleRemove(dim.dimensionId);+ return;+ }+ const options =+ optionsByEntityType[dim.entityType as keyof typeof optionsByEntityType] ??+ [];+ const option = options.find((o) => o.value === valueId);+ applyDimension(dim, valueId, option?.label ?? valueId);+ // Once a value is chosen it shows as a badge; collapse the inline combobox.+ deactivateHighCard(dim.dimensionId);+ }++ function deactivateHighCard(dimensionId: string) {+ setActiveHighCardIds((prev) => {+ if (!prev.has(dimensionId)) return prev;+ const next = new Set(prev);+ next.delete(dimensionId);+ return next;+ });+ }+function handleRemove(dimensionId: string) {const updated = currentDimensions.filter((d) => d.dimensionId !== dimensionId);onChange(updated);persistDimensions(updated);+ deactivateHighCard(dimensionId);}const dimensionEntityTypeMap = new Map(availableDimensions.map((d) => [d.dimensionId, d.entityType]));+ // Low-cardinality dimensions live in the "Dimension +" dropdown. High-+ // cardinality ones are offered in the dropdown too, but selecting one reveals+ // an inline searchable Combobox (sourced from the stores) rather than a list.+ const lowCardinalityDimensions = availableDimensions.filter(+ (d) => !HIGH_CARDINALITY_ENTITY_TYPES.has(d.entityType)+ );+ const selectedDimensionIds = new Set(+ currentDimensions.map((d) => d.dimensionId)+ );+ // High-cardinality dimensions awaiting a value: user-activated and not yet set.+ const pendingHighCardinalityDimensions = availableDimensions.filter(+ (d) =>+ HIGH_CARDINALITY_ENTITY_TYPES.has(d.entityType) &&+ activeHighCardIds.has(d.dimensionId) &&+ !selectedDimensionIds.has(d.dimensionId)+ );+ // High-cardinality dimensions still offerable in the dropdown.+ const addableHighCardinalityDimensions = availableDimensions.filter(+ (d) =>+ HIGH_CARDINALITY_ENTITY_TYPES.has(d.entityType) &&+ !activeHighCardIds.has(d.dimensionId) &&+ !selectedDimensionIds.has(d.dimensionId)+ );+ const showDropdown =+ lowCardinalityDimensions.length > 0 ||+ addableHighCardinalityDimensions.length > 0;+return (<div className="flex flex-wrap items-center gap-1.5">- {availableDimensions.length > 0 && (+ {showDropdown && (<DropdownMenu><DropdownMenuTrigger asChild><Badge@@ -134,7 +235,26 @@ const DimensionSelector = ({<DropdownMenuContent align="start" className="w-56"><DropdownMenuLabel>Dimensions</DropdownMenuLabel><DropdownMenuSeparator />- {availableDimensions.map((dim) =>+ {addableHighCardinalityDimensions.map((dim) => (+ <DropdownMenuItem+ key={dim.dimensionId}+ onSelect={() =>+ setActiveHighCardIds((prev) =>+ new Set(prev).add(dim.dimensionId)+ )+ }+ >+ <DropdownMenuIcon+ icon={+ <DimensionEntityTypeIcon+ entityType={dim.entityType as any}+ />+ }+ />+ {dim.dimensionName}+ </DropdownMenuItem>+ ))}+ {lowCardinalityDimensions.map((dim) =>dim.values.length === 0 ? (<DropdownMenuLabelkey={dim.dimensionId}@@ -175,6 +295,22 @@ const DimensionSelector = ({</DropdownMenuContent></DropdownMenu>)}+ {pendingHighCardinalityDimensions.map((dim) => (+ <Combobox+ key={dim.dimensionId}+ size="sm"+ className="w-44"+ isClearable+ placeholder={dim.dimensionName}+ value=""+ options={+ optionsByEntityType[+ dim.entityType as keyof typeof optionsByEntityType+ ] ?? []+ }+ onChange={(valueId) => handleComboboxChange(dim, valueId)}+ />+ ))}{currentDimensions.map((dim) => (<Badgekey={dim.dimensionId}diff --git a/apps/erp/app/modules/accounting/ui/JournalEntries/JournalEntryForm.tsx b/apps/erp/app/modules/accounting/ui/JournalEntries/JournalEntryForm.tsxindex 7d051ec642..df240675db 100644--- a/apps/erp/app/modules/accounting/ui/JournalEntries/JournalEntryForm.tsx+++ b/apps/erp/app/modules/accounting/ui/JournalEntries/JournalEntryForm.tsx@@ -24,6 +24,7 @@ import { useCallback, useMemo, useState } from "react";import {LuCheckCheck,LuEllipsisVertical,+ LuExternalLink,LuPlus,LuRotateCcw,LuSave,@@ -52,6 +53,7 @@ type JournalEntryFormProps = {displayId: string;status: string;sourceType: string;+ sourceDocument?: { readableId: string; to: string } | null;reversedById?: string | null;initialValues: {id: string;@@ -87,6 +89,7 @@ const JournalEntryForm = ({displayId,status,sourceType,+ sourceDocument,reversedById,initialValues,initialLines,@@ -228,6 +231,17 @@ const JournalEntryForm = ({<JournalEntryStatus status={status as any} /></HStack><HStack>+ {sourceDocument && (+ <Button+ variant="secondary"+ leftIcon={<LuExternalLink />}+ asChild+ >+ <Link to={sourceDocument.to}>+ {sourceDocument.readableId}+ </Link>+ </Button>+ )}{isReversed && reversedById && (<Button variant="secondary" asChild><Link to={path.to.journalEntryDetails(reversedById)}>diff --git a/apps/erp/app/modules/accounting/ui/Reports/FinancialStatementTree.tsx b/apps/erp/app/modules/accounting/ui/Reports/FinancialStatementTree.tsxindex 3a5e6e41a4..1602cc2cfb 100644--- a/apps/erp/app/modules/accounting/ui/Reports/FinancialStatementTree.tsx+++ b/apps/erp/app/modules/accounting/ui/Reports/FinancialStatementTree.tsx@@ -1,6 +1,7 @@import { cn, ScrollArea } from "@carbon/react";import { memo, useMemo, useRef } from "react";import {+ LuCalculator,LuChevronDown,LuChevronRight,LuFolder,@@ -10,6 +11,7 @@ import type { FlatTree, FlatTreeItem } from "~/components/TreeView";import { LevelLine, TreeView, useTree } from "~/components/TreeView";import { useRealtime } from "~/hooks";import type { Chart } from "../../types";+import { NET_INCOME_ACCOUNT_ID } from "../../types";type TranslatedChart = Chart & {translatedBalance?: number;@@ -41,6 +43,9 @@ function accountsToFlatTree(const aIsGroup = a.isGroup ? 1 : 0;const bIsGroup = b.isGroup ? 1 : 0;if (aIsGroup !== bIsGroup) return aIsGroup - bIsGroup;+ // The computed Net Income line always sorts to the end of its group.+ if (a.id === NET_INCOME_ACCOUNT_ID) return 1;+ if (b.id === NET_INCOME_ACCOUNT_ID) return -1;return (a.name ?? "").localeCompare(b.name ?? "");});@@ -216,6 +221,9 @@ const FinancialStatementTree = memo(</span>)}<span className="truncate">{account.name}</span>+ {account.id === NET_INCOME_ACCOUNT_ID && (+ <LuCalculator className="h-3.5 w-3.5 text-muted-foreground shrink-0" />+ )}</div>{/* Balance */}diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsxindex cfd9eba2cb..69c216e632 100644--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx@@ -14,6 +14,7 @@ import { useNumberFormatter } from "@react-aria/i18n";import type { ColumnDef } from "@tanstack/react-table";import { memo, useCallback, useMemo } from "react";import {+ LuBlocks,LuBookMarked,LuBox,LuBoxes,@@ -27,7 +28,6 @@ import {LuLoaderCircle,LuMoveDown,LuMoveUp,- LuPackage,LuPaintBucket,LuPuzzle,LuRuler,@@ -150,7 +150,7 @@ const InventoryTable = memo(formatNumber(row.original.quantityOnHand)),meta: {- icon: <LuPackage />,+ icon: <LuBlocks />,renderTotal: true,formatter: formatNumber}diff --git a/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx b/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsxindex 879c68c252..a7fd5b576d 100644--- a/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx+++ b/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx@@ -26,13 +26,13 @@ import { Trans, useLingui } from "@lingui/react/macro";import type { ColumnDef } from "@tanstack/react-table";import { memo, useCallback, useMemo, useState } from "react";import {+ LuBlocks,LuCalendar,LuCheck,LuContainer,LuHash,LuLink,LuMapPin,- LuPackage,LuPencil,LuPrinter,LuQrCode,@@ -121,7 +121,7 @@ const KanbansTable = memo(label: item.readableIdWithRevision}))},- icon: <LuPackage />+ icon: <LuBlocks />}},{diff --git a/apps/erp/app/modules/inventory/ui/PickingLists/PickingItemCard.tsx b/apps/erp/app/modules/inventory/ui/PickingLists/PickingItemCard.tsxindex 0ed0bdf2a0..2002d43082 100644--- a/apps/erp/app/modules/inventory/ui/PickingLists/PickingItemCard.tsx+++ b/apps/erp/app/modules/inventory/ui/PickingLists/PickingItemCard.tsx@@ -16,9 +16,9 @@ import {} from "@carbon/utils";import { cva } from "class-variance-authority";import {+ LuBlocks,LuCirclePlay,LuClipboardCheck,- LuPackage,LuSquareUser,LuTimer,LuTrash@@ -224,7 +224,7 @@ export function PickingItemCard({{/* Parts to pick — the reason this operation is on the picking schedule */}<HStack className="justify-start space-x-2 font-medium">- <LuPackage className="text-muted-foreground shrink-0" />+ <LuBlocks className="text-muted-foreground shrink-0" /><span className="text-sm tabular-nums">{Number(item.partsToPickCount).toLocaleString()}{" "}{Number(item.partsToPickCount) === 1 ? "part" : "parts"} ·{" "}diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsxindex a47791de01..4210409bb0 100644--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx@@ -19,7 +19,7 @@ import {LuTrash,LuTruck} from "react-icons/lu";-import { Link, useParams } from "react-router";+import { Link, useNavigation, useParams } from "react-router";import type { z } from "zod";import { DocumentHeader, PrintButton } from "~/components";import { useAuditLog } from "~/components/AuditLog";@@ -75,6 +75,7 @@ const ReceiptForm = ({const { company } = useUser();const permissions = usePermissions();const { t } = useLingui();+ const navigation = useNavigation();const {locationId,sourceDocuments,@@ -115,6 +116,10 @@ const ReceiptForm = ({routeData?.receipt?.sourceDocumentId &&permissions.can("create", "invoicing");+ const isInvoicing =+ navigation.state !== "idle" &&+ navigation.location?.pathname === path.to.newPurchaseInvoice;+return (<><Card>@@ -190,7 +195,8 @@ const ReceiptForm = ({/><Buttonvariant={canInvoice ? "primary" : "secondary"}- isDisabled={!canInvoice}+ isDisabled={!canInvoice || isInvoicing}+ isLoading={isInvoicing}leftIcon={<LuCreditCard />}asChild>diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/ShipmentForm.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/ShipmentForm.tsxindex bf04e48ccf..b3f6aee581 100644--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/ShipmentForm.tsx+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/ShipmentForm.tsx@@ -28,7 +28,13 @@ import {LuTruck} from "react-icons/lu";import { RiProgress8Line } from "react-icons/ri";-import { Await, Link, useNavigate, useParams } from "react-router";+import {+ Await,+ Link,+ useNavigate,+ useNavigation,+ useParams+} from "react-router";import type { z } from "zod";import { DocumentHeader, PrintButton } from "~/components";import { useAuditLog } from "~/components/AuditLog";@@ -388,6 +394,11 @@ function InvoiceButtons({isVoided: boolean;onCreateInvoice: (shipment?: Shipment) => void;}) {+ const navigation = useNavigation();+ const isInvoicing =+ navigation.state !== "idle" &&+ navigation.location?.pathname === path.to.newSalesInvoice;+if (!shipment) return null;if (shipment.sourceDocument === "Sales Order") {@@ -427,7 +438,7 @@ function InvoiceButtons({</DropdownMenuTrigger><DropdownMenuContent align="end"><DropdownMenuItem- disabled={!isPosted}+ disabled={!isPosted || isInvoicing}onClick={() => onCreateInvoice(shipment)}><DropdownMenuIcon icon={<LuCirclePlus />} />@@ -452,7 +463,8 @@ function InvoiceButtons({<ButtonleftIcon={<LuCreditCard />}variant={isPosted && !isVoided ? "primary" : "secondary"}- isDisabled={!isPosted}+ isDisabled={!isPosted || isInvoicing}+ isLoading={isInvoicing}onClick={() => onCreateInvoice(shipment)}><Trans>Invoice</Trans>diff --git a/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsx b/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsxindex f9472ce424..5288fe2d7e 100644--- a/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsx+++ b/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsx@@ -4,13 +4,13 @@ import type { ColumnDef } from "@tanstack/react-table";import { memo, useMemo } from "react";import {LuArrowRightLeft,+ LuBlocks,LuCalendar,LuFileText,LuHash,LuMapPin,LuMoveDown,LuMoveUp,- LuPackage,LuQrCode,LuUser,LuWarehouse@@ -76,7 +76,7 @@ const StockMovementsTable = memo(</HStack>),meta: {- icon: <LuPackage />+ icon: <LuBlocks />}},{diff --git a/apps/erp/app/modules/inventory/ui/Traceability/ExpiryTracePopover.tsx b/apps/erp/app/modules/inventory/ui/Traceability/ExpiryTracePopover.tsxindex 0d8adeb250..9ec3a016ec 100644--- a/apps/erp/app/modules/inventory/ui/Traceability/ExpiryTracePopover.tsx+++ b/apps/erp/app/modules/inventory/ui/Traceability/ExpiryTracePopover.tsx@@ -8,10 +8,10 @@ import {import { Trans } from "@lingui/react/macro";import type { ReactNode } from "react";import {+ LuBlocks,LuCalendarCheck,LuExternalLink,LuLayers,- LuPackage,LuPencil,LuShieldCheck} from "react-icons/lu";@@ -46,7 +46,7 @@ type ExpiryTraceStep = {};const STEP_ICON: Record<ExpiryTraceStep["step"], ReactNode> = {- Source: <LuPackage className="size-3.5" />,+ Source: <LuBlocks className="size-3.5" />,Policy: <LuShieldCheck className="size-3.5" />,Inputs: <LuLayers className="size-3.5" />,Override: <LuPencil className="size-3.5" />,diff --git a/apps/erp/app/modules/inventory/ui/Traceability/metadata.ts b/apps/erp/app/modules/inventory/ui/Traceability/metadata.tsindex 638dffd9d2..0ffd61dfc3 100644--- a/apps/erp/app/modules/inventory/ui/Traceability/metadata.ts+++ b/apps/erp/app/modules/inventory/ui/Traceability/metadata.ts@@ -1,9 +1,9 @@import type { IconType } from "react-icons";import {+ LuBlocks,LuClipboardCheck,LuFactory,LuForklift,- LuPackage,LuPackageCheck,LuPackageMinus,LuPackageOpen,@@ -91,7 +91,7 @@ export const ACTIVITY_KIND_META: Record<ActivityKind, ActivityKindMeta> = {color: "hsl(330 70% 60%)",icon: LuClipboardCheck},- Other: { label: "Other", color: "hsl(280 65% 60%)", icon: LuPackage }+ Other: { label: "Other", color: "hsl(280 65% 60%)", icon: LuBlocks }};export function activityKindFor(type: string | undefined | null): ActivityKind {diff --git a/apps/erp/app/modules/invoicing/invoicing.models.test.ts b/apps/erp/app/modules/invoicing/invoicing.models.test.tsnew file mode 100644index 0000000000..7c82d415b5--- /dev/null+++ b/apps/erp/app/modules/invoicing/invoicing.models.test.ts@@ -0,0 +1,160 @@+import { describe, expect, it } from "vitest";+import {+ invoiceSettlementValidator,+ paymentValidator+} from "./invoicing.models";++describe("paymentValidator", () => {+ const validReceipt = {+ paymentType: "Receipt" as const,+ customerId: "cust1",+ paymentDate: "2026-05-19",+ currencyCode: "USD",+ exchangeRate: 1,+ totalAmount: 100,+ bankAccount: "acc1"+ };++ it("accepts a Receipt with a customer", () => {+ const r = paymentValidator.safeParse(validReceipt);+ expect(r.success).toBe(true);+ });++ it("accepts a Disbursement with a supplier", () => {+ const r = paymentValidator.safeParse({+ ...validReceipt,+ paymentType: "Disbursement",+ customerId: undefined,+ supplierId: "supp1"+ });+ expect(r.success).toBe(true);+ });++ it("rejects a Receipt missing customer", () => {+ const r = paymentValidator.safeParse({+ ...validReceipt,+ customerId: undefined+ });+ expect(r.success).toBe(false);+ });++ it("rejects a Disbursement missing supplier", () => {+ const r = paymentValidator.safeParse({+ ...validReceipt,+ paymentType: "Disbursement",+ customerId: undefined+ });+ expect(r.success).toBe(false);+ });++ it("accepts a zero totalAmount (pure credit-application, no cash)", () => {+ const r = paymentValidator.safeParse({+ ...validReceipt,+ totalAmount: 0+ });+ expect(r.success).toBe(true);+ });++ it("rejects a negative totalAmount", () => {+ const r = paymentValidator.safeParse({+ ...validReceipt,+ totalAmount: -10+ });+ expect(r.success).toBe(false);+ });++ it("rejects a zero exchange rate", () => {+ const r = paymentValidator.safeParse({+ ...validReceipt,+ exchangeRate: 0+ });+ expect(r.success).toBe(false);+ });+});++describe("invoiceSettlementValidator", () => {+ const validApp = {+ paymentId: "p1",+ targetSalesInvoiceId: "si1",+ appliedAmount: 50,+ discountAmount: 0,+ writeOffAmount: 0,+ targetExchangeRate: 1,+ sourceExchangeRate: 1,+ appliedDate: "2026-05-19"+ };++ it("accepts an application against a sales invoice", () => {+ const r = invoiceSettlementValidator.safeParse(validApp);+ expect(r.success).toBe(true);+ });++ it("accepts an application against a purchase invoice", () => {+ const r = invoiceSettlementValidator.safeParse({+ ...validApp,+ targetSalesInvoiceId: undefined,+ targetPurchaseInvoiceId: "pi1"+ });+ expect(r.success).toBe(true);+ });++ it("rejects when both sales and purchase ids set", () => {+ const r = invoiceSettlementValidator.safeParse({+ ...validApp,+ targetPurchaseInvoiceId: "pi1"+ });+ expect(r.success).toBe(false);+ });++ it("rejects when neither sales nor purchase id set", () => {+ const r = invoiceSettlementValidator.safeParse({+ ...validApp,+ targetSalesInvoiceId: undefined+ });+ expect(r.success).toBe(false);+ });++ it("rejects when all three components are zero", () => {+ const r = invoiceSettlementValidator.safeParse({+ ...validApp,+ appliedAmount: 0,+ discountAmount: 0,+ writeOffAmount: 0+ });+ expect(r.success).toBe(false);+ });++ it("accepts a discount-only application (no cash applied)", () => {+ const r = invoiceSettlementValidator.safeParse({+ ...validApp,+ appliedAmount: 0,+ discountAmount: 5+ });+ expect(r.success).toBe(true);+ });++ it("accepts a write-off-only application", () => {+ const r = invoiceSettlementValidator.safeParse({+ ...validApp,+ appliedAmount: 0,+ writeOffAmount: 5+ });+ expect(r.success).toBe(true);+ });++ it("rejects a zero invoice exchange rate", () => {+ const r = invoiceSettlementValidator.safeParse({+ ...validApp,+ targetExchangeRate: 0+ });+ expect(r.success).toBe(false);+ });++ it("rejects a negative payment exchange rate", () => {+ const r = invoiceSettlementValidator.safeParse({+ ...validApp,+ sourceExchangeRate: -1+ });+ expect(r.success).toBe(false);+ });+});diff --git a/apps/erp/app/modules/invoicing/invoicing.models.ts b/apps/erp/app/modules/invoicing/invoicing.models.tsindex c6f0079f5c..8b28cbbdd5 100644--- a/apps/erp/app/modules/invoicing/invoicing.models.ts+++ b/apps/erp/app/modules/invoicing/invoicing.models.ts@@ -1,6 +1,9 @@import { z } from "zod";import { zfd } from "zod-form-data";-import { incoterms, methodItemType, methodType } from "../shared";+// Import the constants from the models file directly (not the `../shared` barrel),+// which also re-exports shared.service/shared.server — those transitively pull in+// `@carbon/auth`'s Lingui-macro glossary and break plain unit tests of this module.+import { incoterms, methodItemType, methodType } from "../shared/shared.models";export const purchaseInvoiceLineType = ["Part",@@ -298,3 +301,159 @@ export const salesInvoiceLineValidator = zpath: ["quantity"]});++// ----------------------------------------------------------------------+// Credit / Debit Memos — payment-shaped documents (the `memo` table). A memo is+// a party + amount + reason GL account, applied to invoices via+// invoiceSettlement exactly like a payment, but the offset is a GL account+// (returns/allowance/adjustment) instead of cash. NOT an invoice row.+//+// The four combos = party (customer/supplier) × direction (Credit/Debit):+// Customer Credit -> AR down, Customer Debit -> AR up+// Supplier Debit -> AP down, Supplier Credit -> AP up+// ----------------------------------------------------------------------++export const memoDirection = ["Credit", "Debit"] as const;+export const memoStatus = ["Draft", "Posted", "Voided"] as const;++export type MemoDirection = (typeof memoDirection)[number];+export type MemoStatusType = (typeof memoStatus)[number];++export function isMemoLocked(status: string | null | undefined): boolean {+ return status !== null && status !== undefined && status !== "Draft";+}++export const memoValidator = z+ .object({+ id: zfd.text(z.string().optional()),+ memoId: zfd.text(z.string().optional()),+ direction: z.enum(memoDirection, {+ errorMap: () => ({ message: "Direction is required" })+ }),+ customerId: zfd.text(z.string().optional()),+ supplierId: zfd.text(z.string().optional()),+ memoDate: z.string().min(1, { message: "Date is required" }),+ currencyCode: z.string().min(1, { message: "Currency is required" }),+ exchangeRate: zfd.numeric(z.number().positive().default(1)),+ amount: zfd.numeric(z.number().positive({ message: "Amount must be > 0" })),+ reference: zfd.text(z.string().optional()),+ notes: zfd.text(z.string().optional())+ })+ .refine((d) => Boolean(d.customerId) !== Boolean(d.supplierId), {+ message: "A memo is for exactly one party (customer or supplier)",+ path: ["customerId"]+ });++// ----------------------------------------------------------------------+// Payments (AR receipts + AP disbursements + applications)+// ----------------------------------------------------------------------++export const paymentType = ["Receipt", "Disbursement"] as const;+export const paymentStatus = ["Draft", "Posted", "Voided"] as const;++export type PaymentType = (typeof paymentType)[number];+export type PaymentStatusType = (typeof paymentStatus)[number];++export function isPaymentLocked(status: string | null | undefined): boolean {+ return status !== null && status !== undefined && status !== "Draft";+}++export const paymentValidator = z+ .object({+ id: zfd.text(z.string().optional()),+ paymentId: zfd.text(z.string().optional()),+ paymentType: z.enum(paymentType, {+ errorMap: () => ({ message: "Payment type is required" })+ }),+ customerId: zfd.text(z.string().optional()),+ supplierId: zfd.text(z.string().optional()),+ paymentDate: z.string().min(1, { message: "Payment date is required" }),+ currencyCode: z.string().min(1, { message: "Currency is required" }),+ exchangeRate: zfd.numeric(z.number().positive().default(1)),+ // Cash may be 0: a receipt/payment can be a pure credit-application (apply+ // the party's posted credits to invoices with no cash changing hands).+ totalAmount: zfd.numeric(+ z.number().nonnegative({ message: "Total amount cannot be negative" })+ ),+ bankAccount: z.string().min(1, { message: "Bank account is required" }),+ reference: zfd.text(z.string().optional()),+ memo: zfd.text(z.string().optional())+ })+ .refine(+ (d) =>+ d.paymentType === "Receipt"+ ? Boolean(d.customerId)+ : Boolean(d.supplierId),+ {+ message: "Receipt requires a customer; Disbursement requires a supplier",+ path: ["customerId"]+ }+ );++// The raw object schema (no refinements). Routes that need to `.omit()` a source+// key before injecting it from the URL use THIS — peeling `.refine()` layers off+// the refined validator below with `.innerType()` is brittle (it breaks whenever+// a refinement is added/removed).+export const invoiceSettlementBase = z.object({+ id: zfd.text(z.string().optional()),+ // Source: exactly one of a payment or a memo settles the target.+ paymentId: zfd.text(z.string().optional()),+ memoId: zfd.text(z.string().optional()),+ // Target: exactly one of a sales invoice, purchase invoice, or memo.+ targetSalesInvoiceId: zfd.text(z.string().optional()),+ targetPurchaseInvoiceId: zfd.text(z.string().optional()),+ targetMemoId: zfd.text(z.string().optional()),+ appliedAmount: zfd.numeric(z.number().nonnegative().default(0)),+ discountAmount: zfd.numeric(z.number().nonnegative().default(0)),+ writeOffAmount: zfd.numeric(z.number().nonnegative().default(0)),+ targetExchangeRate: zfd.numeric(+ z.number().positive({ message: "Target exchange rate must be > 0" })+ ),+ sourceExchangeRate: zfd.numeric(+ z.number().positive({ message: "Source exchange rate must be > 0" })+ ),+ appliedDate: z.string().min(1, { message: "Applied date is required" })+});++export const invoiceSettlementValidator = invoiceSettlementBase+ .refine((d) => Boolean(d.paymentId) !== Boolean(d.memoId), {+ message: "A settlement must have exactly one source (payment or memo)",+ path: ["paymentId"]+ })+ .refine(+ (d) =>+ [+ d.targetSalesInvoiceId,+ d.targetPurchaseInvoiceId,+ d.targetMemoId+ ].filter(Boolean).length === 1,+ {+ message:+ "Application must target exactly one document (sales invoice, purchase invoice, or memo)",+ path: ["targetSalesInvoiceId"]+ }+ )+ .refine(+ (d) =>+ Number(d.appliedAmount) ++ Number(d.discountAmount) ++ Number(d.writeOffAmount) >+ 0,+ {+ message: "At least one of applied / discount / write-off must be > 0",+ path: ["appliedAmount"]+ }+ );++// An invoice is payable when it's posted with an outstanding balance — i.e. not+// draft/pending, voided, or already fully paid. Shared by the sales (AR) and+// purchase (AP) invoice headers; the caller AND-s in the permission check.+export function isInvoicePayable(+ status: string | null | undefined,+ balance: number | null | undefined+): boolean {+ return (+ !["Voided", "Draft", "Pending", "Paid"].includes(status ?? "") &&+ Number(balance ?? 0) > 0+ );+}diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.tsindex 31bff017cd..2212ead78d 100644--- a/apps/erp/app/modules/invoicing/invoicing.service.ts+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts@@ -1,6 +1,6 @@import type { Database, Json } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";-import { getLocalTimeZone, now, today } from "@internationalized/date";+import { getLocalTimeZone, today } from "@internationalized/date";import type { SupabaseClient } from "@supabase/supabase-js";import type { z } from "zod";import {@@ -18,6 +18,10 @@ import {getCustomerShipping} from "../sales/sales.service";import type {+ invoiceSettlementValidator,+ memoValidator,+ PaymentStatusType,+ paymentValidator,purchaseInvoiceDeliveryValidator,purchaseInvoiceLineValidator,purchaseInvoiceStatusType,@@ -329,18 +333,22 @@ export async function updatePurchaseInvoiceStatus(updatedBy: string;}) {- const { status, ...rest } = update;-- // Set completedDate when status is Confirmed- const updateData = {- status,- ...rest,- ...(["Paid"].includes(status)- ? { datePaid: now(getLocalTimeZone()).toAbsoluteString() }- : {})- };+ // Paid / Partially Paid / Overdue are derived in the purchaseInvoices view+ // from invoiceSettlement. Rejecting them here ensures status integrity.+ if (+ update.status === "Paid" ||+ update.status === "Partially Paid" ||+ update.status === "Overdue"+ ) {+ return {+ data: null,+ error: {+ message: `Cannot set status to ${update.status} directly — this status is derived from payment applications.`+ }+ };+ }- return client.from("purchaseInvoice").update(updateData).eq("id", update.id);+ return client.from("purchaseInvoice").update(update).eq("id", update.id);}export async function updateSalesInvoiceExchangeRate(@@ -368,17 +376,22 @@ export async function updateSalesInvoiceStatus(updatedBy: string;}) {- const { status, ...rest } = update;-- const updateData = {- status,- ...rest,- ...(["Paid"].includes(status)- ? { datePaid: now(getLocalTimeZone()).toAbsoluteString() }- : {})- };+ // Paid / Partially Paid / Overdue are derived in the salesInvoices view+ // from invoiceSettlement. Rejecting them here ensures status integrity.+ if (+ update.status === "Paid" ||+ update.status === "Partially Paid" ||+ update.status === "Overdue"+ ) {+ return {+ data: null,+ error: {+ message: `Cannot set status to ${update.status} directly — this status is derived from payment applications.`+ }+ };+ }- return client.from("salesInvoice").update(updateData).eq("id", update.id);+ return client.from("salesInvoice").update(update).eq("id", update.id);}export async function insertPurchaseInvoice(@@ -1121,3 +1134,1207 @@ export async function updateSalesInvoiceLineOrder(}});}++// ======================================================================+// Payments (AR receipts + AP disbursements + applications)+// ======================================================================++export async function getPayment(client: SupabaseClient<Database>, id: string) {+ return client.from("payment").select("*").eq("id", id).single();+}++export async function getPayments(+ client: SupabaseClient<Database>,+ companyId: string,+ args: GenericQueryFilters & {+ search: string | null;+ paymentType: "Receipt" | "Disbursement" | null;+ status: PaymentStatusType | null;+ customerId: string | null;+ supplierId: string | null;+ // Combined counterparty filter (customer OR supplier ids) from the table's+ // "Counterparty" filter, which sources options from both stores.+ counterpartyIds?: string[] | null;+ }+) {+ let query = client+ .from("payment")+ .select("*", { count: "exact" })+ .eq("companyId", companyId);++ if (args.search) {+ query = query.ilike("paymentId", `%${args.search}%`);+ }+ if (args.paymentType) {+ query = query.eq("paymentType", args.paymentType);+ }+ if (args.status) {+ query = query.eq("status", args.status);+ }+ if (args.customerId) {+ query = query.eq("customerId", args.customerId);+ }+ if (args.supplierId) {+ query = query.eq("supplierId", args.supplierId);+ }+ if (args.counterpartyIds && args.counterpartyIds.length > 0) {+ // A payment carries either customerId or supplierId; match the selected+ // ids against both columns (customer/supplier id spaces don't overlap).+ const csv = args.counterpartyIds.join(",");+ query = query.or(`customerId.in.(${csv}),supplierId.in.(${csv})`);+ }++ // Default to newest first by the sequential paymentId (PAY-yyyy-mm-NNNNNN),+ // matching the sales/purchase invoice lists (invoiceId desc) and guaranteeing+ // the most recently created payment is at the top (paymentDate ties otherwise).+ query = setGenericQueryFilters(query, args, [+ { column: "paymentId", ascending: false }+ ]);+ return query;+}++export async function getInvoiceSettlements(+ client: SupabaseClient<Database>,+ companyId: string,+ paymentId: string+) {+ // Embed the invoice's human-readable id (salesInvoice/purchaseInvoice.invoiceId)+ // so the UI can show "AP000001" rather than the raw FK id.+ return client+ .from("invoiceSettlement")+ .select(+ "*, salesInvoice:targetSalesInvoiceId(invoiceId), purchaseInvoice:targetPurchaseInvoiceId(invoiceId)"+ )+ .eq("companyId", companyId)+ .eq("paymentId", paymentId)+ .order("appliedDate", { ascending: true });+}++// A settlement against an invoice can be sourced by either a cash payment or a+// credit/debit memo — both are invoiceSettlement rows. The panel shows them+// together, so the source is a tagged union.+export type InvoiceSettlementSource =+ | {+ type: "payment";+ id: string;+ readableId: string;+ status: string | null;+ date: string | null;+ currencyCode: string;+ }+ | {+ type: "memo";+ id: string;+ readableId: string;+ status: string | null;+ date: string | null;+ currencyCode: string;+ direction: string;+ };++export type InvoiceSettlementForInvoice = {+ id: string;+ appliedAmount: number;+ discountAmount: number;+ writeOffAmount: number;+ fxGainLossAmount: number | null;+ targetExchangeRate: number;+ sourceExchangeRate: number;+ appliedDate: string;+ source: InvoiceSettlementSource;+};++// Posted settlements against a specific invoice — BOTH cash payments and applied+// credit/debit memos. Used by the "Applied" panel on the sales/purchase invoice+// detail page. Two-step query (settlements, then their parent payments/memos)+// dodges the supabase JS type depth limit a !inner join hits, and lets us drop+// settlements whose source is still Draft/Voided.+export async function getInvoiceSettlementsForInvoice(+ client: SupabaseClient<Database>,+ companyId: string,+ side: "sales" | "purchase",+ invoiceId: string+): Promise<{+ data: InvoiceSettlementForInvoice[] | null;+ error: unknown;+}> {+ const column =+ side === "sales" ? "targetSalesInvoiceId" : "targetPurchaseInvoiceId";+ const apps = await client+ .from("invoiceSettlement")+ .select(+ "id, paymentId, memoId, appliedViaPaymentId, appliedAmount, discountAmount, writeOffAmount, fxGainLossAmount, targetExchangeRate, sourceExchangeRate, appliedDate"+ )+ .eq("companyId", companyId)+ .eq(column, invoiceId)+ .order("appliedDate", { ascending: false });++ if (apps.error) return { data: null, error: apps.error };+ if (!apps.data || apps.data.length === 0) return { data: [], error: null };++ const paymentIds = apps.data+ .map((a) => a.paymentId)+ .filter((id): id is string => Boolean(id));+ const memoIds = apps.data+ .map((a) => (a as { memoId: string | null }).memoId)+ .filter((id): id is string => Boolean(id));++ const [payments, memos] = await Promise.all([+ paymentIds.length > 0+ ? client+ .from("payment")+ .select("id, paymentId, status, paymentDate, currencyCode")+ .in("id", paymentIds)+ .eq("status", "Posted")+ : Promise.resolve({ data: [], error: null }),+ memoIds.length > 0+ ? client+ .from("memo")+ .select(+ "id, memoId, status, postingDate, memoDate, currencyCode, direction"+ )+ .in("id", memoIds)+ .eq("status", "Posted")+ : Promise.resolve({ data: [], error: null })+ ]);++ if (payments.error) return { data: null, error: payments.error };+ if (memos.error) return { data: null, error: memos.error };++ // deno-lint-ignore no-explicit-any+ const paymentById = new Map(+ ((payments.data ?? []) as any[]).map((p) => [p.id, p])+ );+ // deno-lint-ignore no-explicit-any+ const memoById = new Map(((memos.data ?? []) as any[]).map((m) => [m.id, m]));++ // A credit applied through a payment is staged on that payment and only counts+ // once the payment is Posted (mirrors the invoice-balance view gating).+ const viaPaymentIds = apps.data+ .map(+ (a) => (a as { appliedViaPaymentId: string | null }).appliedViaPaymentId+ )+ .filter((id): id is string => Boolean(id));+ const postedViaPayments =+ viaPaymentIds.length > 0+ ? await client+ .from("payment")+ .select("id")+ .in("id", viaPaymentIds)+ .eq("status", "Posted")+ : { data: [] as { id: string }[], error: null };+ if (postedViaPayments.error)+ return { data: null, error: postedViaPayments.error };+ const postedViaSet = new Set(+ ((postedViaPayments.data ?? []) as { id: string }[]).map((p) => p.id)+ );++ const merged: InvoiceSettlementForInvoice[] = [];+ for (const a of apps.data) {+ const memoId = (a as { memoId: string | null }).memoId;+ let source: InvoiceSettlementSource | null = null;+ if (a.paymentId && paymentById.has(a.paymentId)) {+ const p = paymentById.get(a.paymentId);+ source = {+ type: "payment",+ id: p.id,+ readableId: p.paymentId,+ status: p.status,+ date: p.paymentDate,+ currencyCode: p.currencyCode+ };+ } else if (memoId && memoById.has(memoId)) {+ const viaId = (a as { appliedViaPaymentId: string | null })+ .appliedViaPaymentId;+ // Staged on a Draft payment — not applied yet, so omit it from the card.+ if (viaId && !postedViaSet.has(viaId)) continue;+ const m = memoById.get(memoId);+ source = {+ type: "memo",+ id: m.id,+ readableId: m.memoId,+ status: m.status,+ date: m.postingDate ?? m.memoDate,+ currencyCode: m.currencyCode,+ direction: m.direction+ };+ }+ // Skip settlements whose source isn't Posted (a Draft/Voided payment/memo).+ if (!source) continue;+ merged.push({+ id: a.id,+ appliedAmount: Number(a.appliedAmount),+ discountAmount: Number(a.discountAmount),+ writeOffAmount: Number(a.writeOffAmount),+ fxGainLossAmount:+ a.fxGainLossAmount == null ? null : Number(a.fxGainLossAmount),+ targetExchangeRate: Number(a.targetExchangeRate),+ sourceExchangeRate: Number(a.sourceExchangeRate),+ appliedDate: a.appliedDate,+ source+ });+ }++ return { data: merged, error: null };+}++// Where a posted credit/debit memo's balance went — the documents it has been+// applied to. The reverse of the invoice "Payments" panel: drives the "Applied To"+// card on the memo detail page so you can see at a glance which invoices a memo+// settled without opening each one. Target is a tagged union (sales/purchase+// invoice, or another memo when refunding a balance-increasing memo).+export type MemoApplication = {+ id: string;+ appliedAmount: number;+ appliedDate: string;+ target:+ | { type: "salesInvoice"; id: string; readableId: string }+ | { type: "purchaseInvoice"; id: string; readableId: string }+ | { type: "memo"; id: string; readableId: string };+};++export async function getMemoApplications(+ client: SupabaseClient<Database>,+ memoId: string+): Promise<{ data: MemoApplication[] | null; error: unknown }> {+ // Embed the target documents' human-readable ids so the card can link out.+ const settlements = await client+ .from("invoiceSettlement")+ .select(+ "id, appliedAmount, appliedDate, appliedViaPaymentId, targetSalesInvoiceId, targetPurchaseInvoiceId, targetMemoId, salesInvoice:targetSalesInvoiceId(invoiceId), purchaseInvoice:targetPurchaseInvoiceId(invoiceId), targetMemo:targetMemoId(memoId)"+ )+ .eq("memoId", memoId)+ .order("appliedDate", { ascending: false });++ if (settlements.error) return { data: null, error: settlements.error };+ if (!settlements.data || settlements.data.length === 0)+ return { data: [], error: null };++ // A credit applied through a payment only takes effect once that payment is+ // Posted (mirrors getInvoiceSettlementsForInvoice and the balance views).+ const viaPaymentIds = (+ settlements.data as { appliedViaPaymentId: string | null }[]+ )+ .map((s) => s.appliedViaPaymentId)+ .filter((id): id is string => Boolean(id));+ const postedViaPayments =+ viaPaymentIds.length > 0+ ? await client+ .from("payment")+ .select("id")+ .in("id", viaPaymentIds)+ .eq("status", "Posted")+ : { data: [] as { id: string }[], error: null };+ if (postedViaPayments.error)+ return { data: null, error: postedViaPayments.error };+ const postedViaSet = new Set(+ ((postedViaPayments.data ?? []) as { id: string }[]).map((p) => p.id)+ );++ const rows: MemoApplication[] = [];+ // deno-lint-ignore no-explicit-any+ for (const s of settlements.data as any[]) {+ // Staged on a Draft payment — not applied yet, so omit it.+ if (s.appliedViaPaymentId && !postedViaSet.has(s.appliedViaPaymentId))+ continue;++ let target: MemoApplication["target"] | null = null;+ if (s.targetSalesInvoiceId) {+ target = {+ type: "salesInvoice",+ id: s.targetSalesInvoiceId,+ readableId: s.salesInvoice?.invoiceId ?? s.targetSalesInvoiceId+ };+ } else if (s.targetPurchaseInvoiceId) {+ target = {+ type: "purchaseInvoice",+ id: s.targetPurchaseInvoiceId,+ readableId: s.purchaseInvoice?.invoiceId ?? s.targetPurchaseInvoiceId+ };+ } else if (s.targetMemoId) {+ target = {+ type: "memo",+ id: s.targetMemoId,+ readableId: s.targetMemo?.memoId ?? s.targetMemoId+ };+ }+ if (!target) continue;++ rows.push({+ id: s.id,+ appliedAmount: Number(s.appliedAmount),+ appliedDate: s.appliedDate,+ target+ });+ }++ return { data: rows, error: null };+}++// Open sales invoices for a customer (active status and a positive+// balance). Drives the apply table on the AR payment detail.+export async function getOpenSalesInvoicesForCustomer(+ client: SupabaseClient<Database>,+ companyId: string,+ customerId: string+) {+ return client+ .from("salesInvoices")+ .select(+ "id, invoiceId, dateDue, currencyCode, exchangeRate, totalAmount, balance, status"+ )+ .eq("companyId", companyId)+ .eq("customerId", customerId)+ .in("status", ["Submitted", "Partially Paid", "Overdue"])+ .gt("balance", 0)+ .order("dateDue", { ascending: true });+}++export async function getOpenPurchaseInvoicesForSupplier(+ client: SupabaseClient<Database>,+ companyId: string,+ supplierId: string+) {+ return client+ .from("purchaseInvoices")+ .select(+ "id, invoiceId, dateDue, currencyCode, exchangeRate, totalAmount, balance, status"+ )+ .eq("companyId", companyId)+ .eq("supplierId", supplierId)+ .in("status", ["Open", "Partially Paid", "Overdue"])+ .gt("balance", 0)+ .order("dateDue", { ascending: true });+}++// The party's available on-account credit in BASE currency: the net unapplied+// cash across their posted payments (Σ cash − Σ applied). This is the pool a new+// payment may draw on when it applies more than its own cash. Mirrors the+// authoritative check in the post-payment edge function; returns 0 on any read+// error (conservative — posting re-validates under lock). Returns base currency;+// callers convert to the payment's currency for display via the exchange rate.+export async function getAvailableOnAccountCredit(+ client: SupabaseClient<Database>,+ companyId: string,+ party:+ | { paymentType: "Receipt"; customerId: string }+ | { paymentType: "Disbursement"; supplierId: string }+): Promise<number> {+ let query = client+ .from("payment")+ .select("id, totalAmount, exchangeRate")+ .eq("companyId", companyId)+ .eq("status", "Posted")+ .eq("paymentType", party.paymentType);+ query =+ party.paymentType === "Receipt"+ ? query.eq("customerId", party.customerId)+ : query.eq("supplierId", party.supplierId);++ const payments = await query;+ if (payments.error || !payments.data || payments.data.length === 0) return 0;++ const apps = await client+ .from("invoiceSettlement")+ .select("paymentId, appliedAmount, sourceExchangeRate")+ .eq("companyId", companyId)+ .in(+ "paymentId",+ payments.data.map((p) => p.id)+ );+ if (apps.error) return 0;++ const appliedBaseByPayment = new Map<string, number>();+ for (const a of apps.data ?? []) {+ if (!a.paymentId) continue;+ appliedBaseByPayment.set(+ a.paymentId,+ (appliedBaseByPayment.get(a.paymentId) ?? 0) ++ Number(a.appliedAmount) * Number(a.sourceExchangeRate)+ );+ }++ let baseCredit = 0;+ for (const p of payments.data) {+ baseCredit +=+ Number(p.totalAmount) * Number(p.exchangeRate) -+ (appliedBaseByPayment.get(p.id) ?? 0);+ }+ return Math.max(0, Math.round(baseCredit * 10000) / 10000);+}++export async function upsertPayment(+ client: SupabaseClient<Database>,+ payment:+ | (Omit<z.infer<typeof paymentValidator>, "id" | "paymentId"> & {+ paymentId: string;+ companyId: string;+ createdBy: string;+ customFields?: Json;+ })+ | (Omit<z.infer<typeof paymentValidator>, "id"> & {+ id: string;+ updatedBy: string;+ customFields?: Json;+ })+) {+ if ("createdBy" in payment) {+ return client+ .from("payment")+ .insert([sanitize(payment)])+ .select("id, paymentId")+ .single();+ }+ return client+ .from("payment")+ .update(sanitize(payment))+ .eq("id", payment.id)+ .select("id, paymentId")+ .single();+}++// RLS DELETE policy on payment restricts to status='Draft'.+export async function deletePayment(+ client: SupabaseClient<Database>,+ id: string+) {+ return client.from("payment").delete().eq("id", id);+}++export async function upsertInvoiceSettlement(+ client: SupabaseClient<Database>,+ app:+ | (Omit<z.infer<typeof invoiceSettlementValidator>, "id"> & {+ companyId: string;+ createdBy: string;+ })+ | (Omit<z.infer<typeof invoiceSettlementValidator>, "id"> & {+ id: string;+ })+) {+ if ("createdBy" in app) {+ return client+ .from("invoiceSettlement")+ .insert([sanitize(app)])+ .select("id")+ .single();+ }+ return client+ .from("invoiceSettlement")+ .update(sanitize(app))+ .eq("id", app.id)+ .select("id")+ .single();+}++// RLS DELETE policy requires parent payment.status='Draft'.+export async function deleteInvoiceSettlement(+ client: SupabaseClient<Database>,+ id: string+) {+ return client.from("invoiceSettlement").delete().eq("id", id);+}++// Replace-all for the apply table. The delete + insert run in a single+// transaction so a failed insert can never leave the payment with its+// applications wiped and nothing in their place. Kysely bypasses RLS, so we+// re-assert the payment is Draft inside the txn — the FOR UPDATE lock also+// serializes this against a concurrent post/void of the same payment.+export async function replaceInvoiceSettlements(+ db: Kysely<KyselyDatabase>,+ args: {+ paymentId: string;+ companyId: string;+ createdBy: string;+ applications: Omit<+ z.infer<typeof invoiceSettlementValidator>,+ "id" | "paymentId"+ >[];+ }+) {+ return db.transaction().execute(async (trx) => {+ const payment = await trx+ .selectFrom("payment")+ .select(["id", "status", "paymentType", "customerId", "supplierId"])+ .where("id", "=", args.paymentId)+ .where("companyId", "=", args.companyId)+ .forUpdate()+ .executeTakeFirst();++ if (!payment) {+ throw new Error("Payment not found");+ }+ if (payment.status !== "Draft") {+ throw new Error(+ "Applications can only be edited while the payment is Draft"+ );+ }++ await trx+ .deleteFrom("invoiceSettlement")+ .where("paymentId", "=", args.paymentId)+ .execute();++ if (args.applications.length === 0) return;++ // Guard the source→target relationship before inserting. Kysely bypasses+ // RLS, so this is the only enforcement point for the cash path: a Receipt+ // may only settle ITS customer's sales invoices, a Disbursement only ITS+ // supplier's purchase invoices. (Memo targets aren't persisted here — the+ // insert below maps only invoice targets — so reject them rather than write+ // an orphan row with every target FK null.)+ if (args.applications.some((a) => a.targetMemoId)) {+ throw new Error("Settling a memo from a payment is not supported here");+ }+ const isReceipt = payment.paymentType === "Receipt";+ const salesInvoiceIds = [+ ...new Set(+ args.applications+ .map((a) => a.targetSalesInvoiceId)+ .filter((id): id is string => Boolean(id))+ )+ ];+ const purchaseInvoiceIds = [+ ...new Set(+ args.applications+ .map((a) => a.targetPurchaseInvoiceId)+ .filter((id): id is string => Boolean(id))+ )+ ];+ if (isReceipt && purchaseInvoiceIds.length > 0) {+ throw new Error("A receipt can only be applied to sales invoices");+ }+ if (!isReceipt && salesInvoiceIds.length > 0) {+ throw new Error(+ "A disbursement can only be applied to purchase invoices"+ );+ }+ if (salesInvoiceIds.length > 0) {+ const rows = await trx+ .selectFrom("salesInvoice")+ .select(["id", "customerId"])+ .where("id", "in", salesInvoiceIds)+ .where("companyId", "=", args.companyId)+ .execute();+ const customerById = new Map(rows.map((r) => [r.id, r.customerId]));+ for (const id of salesInvoiceIds) {+ if (!customerById.has(id))+ throw new Error(`Sales invoice ${id} not found`);+ if (customerById.get(id) !== payment.customerId)+ throw new Error(+ "A payment can only be applied to its own customer's invoices"+ );+ }+ }+ if (purchaseInvoiceIds.length > 0) {+ const rows = await trx+ .selectFrom("purchaseInvoice")+ .select(["id", "supplierId"])+ .where("id", "in", purchaseInvoiceIds)+ .where("companyId", "=", args.companyId)+ .execute();+ const supplierById = new Map(rows.map((r) => [r.id, r.supplierId]));+ for (const id of purchaseInvoiceIds) {+ if (!supplierById.has(id))+ throw new Error(`Purchase invoice ${id} not found`);+ if (supplierById.get(id) !== payment.supplierId)+ throw new Error(+ "A payment can only be applied to its own supplier's invoices"+ );+ }+ }++ await trx+ .insertInto("invoiceSettlement")+ .values(+ args.applications.map((a) => ({+ paymentId: args.paymentId,+ companyId: args.companyId,+ createdBy: args.createdBy,+ targetSalesInvoiceId: a.targetSalesInvoiceId ?? null,+ targetPurchaseInvoiceId: a.targetPurchaseInvoiceId ?? null,+ appliedAmount: a.appliedAmount,+ discountAmount: a.discountAmount,+ writeOffAmount: a.writeOffAmount,+ targetExchangeRate: a.targetExchangeRate,+ sourceExchangeRate: a.sourceExchangeRate,+ appliedDate: a.appliedDate+ }))+ )+ .execute();+ });+}++// Memos (credit/debit). A memo is payment-shaped: a party (customer XOR+// supplier), a signed amount against a reason GL account, and a set of+// invoiceSettlement applications (memo as SOURCE) to open invoices of the same+// party. Direction (Credit/Debit) is the discriminator; numbering uses the+// creditMemo / debitMemo sequences. Posting is handled by the post-memo edge+// function; the apply table is editable only while the memo is Draft.++export async function getMemo(client: SupabaseClient<Database>, id: string) {+ return client.from("memo").select("*").eq("id", id).single();+}++export async function getMemos(+ client: SupabaseClient<Database>,+ companyId: string,+ args: GenericQueryFilters & {+ search: string | null;+ direction: "Credit" | "Debit" | null;+ status: "Draft" | "Posted" | "Voided" | null;+ counterpartyIds: string[] | null;+ }+) {+ let query = client+ .from("memo")+ .select("*", { count: "exact" })+ .eq("companyId", companyId);++ if (args.search) {+ query = query.ilike("memoId", `%${args.search}%`);+ }+ if (args.direction) {+ query = query.eq("direction", args.direction);+ }+ if (args.status) {+ query = query.eq("status", args.status);+ }+ if (args.counterpartyIds && args.counterpartyIds.length > 0) {+ // A memo carries either customerId or supplierId; match the selected ids+ // against both columns (customer/supplier id spaces don't overlap).+ const csv = args.counterpartyIds.join(",");+ query = query.or(`customerId.in.(${csv}),supplierId.in.(${csv})`);+ }++ // Newest first by creation date (not the readable memoId — Credit and Debit+ // share the table but use separate CR-/DR- sequences, so a memoId sort+ // interleaves them oddly).+ query = setGenericQueryFilters(query, args, [+ { column: "createdAt", ascending: false }+ ]);+ return query;+}++export async function upsertMemo(+ client: SupabaseClient<Database>,+ memo:+ | (Omit<z.infer<typeof memoValidator>, "id" | "memoId"> & {+ memoId: string;+ companyId: string;+ createdBy: string;+ customFields?: Json;+ })+ | (Omit<z.infer<typeof memoValidator>, "id"> & {+ id: string;+ updatedBy: string;+ customFields?: Json;+ })+) {+ if ("createdBy" in memo) {+ return client+ .from("memo")+ .insert([sanitize(memo)])+ .select("id, memoId")+ .single();+ }+ return client+ .from("memo")+ .update(sanitize(memo))+ .eq("id", memo.id)+ .select("id, memoId")+ .single();+}++// RLS DELETE policy on memo restricts to status='Draft'.+export async function deleteMemo(client: SupabaseClient<Database>, id: string) {+ return client.from("memo").delete().eq("id", id);+}++// The party's available credit to draw on when clearing invoices alongside cash:+// their POSTED, balance-reducing memos with credit remaining. A customer's Credit+// memos reduce AR (apply to sales invoices); a supplier's Debit memos reduce AP+// (apply to purchase invoices). `remaining` = amount − Σ already applied (memo as+// settlement source). Drives the credits section of the invoice "Receive Payment"+// composer.+export async function getAvailableCreditsForParty(+ client: SupabaseClient<Database>,+ companyId: string,+ party:+ | { side: "sales"; customerId: string }+ | { side: "purchase"; supplierId: string },+ // When editing a Draft payment's composer, that payment's own staged credits+ // should NOT count as used — they show as staged, not consumed.+ excludePaymentId?: string+): Promise<{+ data:+ | {+ id: string;+ memoId: string;+ direction: string;+ currencyCode: string;+ exchangeRate: number;+ amount: number;+ remaining: number;+ }[]+ | null;+ error: unknown;+}> {+ const direction = party.side === "sales" ? "Credit" : "Debit";+ let query = client+ .from("memo")+ .select("id, memoId, direction, currencyCode, exchangeRate, amount")+ .eq("companyId", companyId)+ .eq("status", "Posted")+ .eq("direction", direction);+ query =+ party.side === "sales"+ ? query.eq("customerId", party.customerId)+ : query.eq("supplierId", party.supplierId);++ const memos = await query;+ if (memos.error) return { data: null, error: memos.error };+ if (!memos.data || memos.data.length === 0) return { data: [], error: null };++ // deno-lint-ignore no-explicit-any+ const rows = memos.data as any[];+ const ids = rows.map((m) => m.id as string);+ const apps = await client+ .from("invoiceSettlement")+ .select("memoId, appliedAmount, appliedViaPaymentId")+ .in("memoId", ids);+ if (apps.error) return { data: null, error: apps.error };++ const appliedByMemo = new Map<string, number>();+ for (const a of apps.data ?? []) {+ if (!a.memoId) continue;+ const viaId = (a as { appliedViaPaymentId: string | null })+ .appliedViaPaymentId;+ if (excludePaymentId && viaId === excludePaymentId) continue;+ appliedByMemo.set(+ a.memoId,+ (appliedByMemo.get(a.memoId) ?? 0) + Number(a.appliedAmount)+ );+ }++ const result = rows+ .map((m) => {+ const remaining =+ Math.round(+ (Number(m.amount) - (appliedByMemo.get(m.id) ?? 0)) * 10000+ ) / 10000;+ return {+ id: m.id as string,+ memoId: m.memoId as string,+ direction: m.direction as string,+ currencyCode: m.currencyCode as string,+ exchangeRate: Number(m.exchangeRate),+ amount: Number(m.amount),+ remaining+ };+ })+ .filter((m) => m.remaining > 0.0001);++ return { data: result, error: null };+}++// Does the company have ANY open credits to apply on this side? (sales → posted+// customer Credit memos; purchase → posted supplier Debit memos, each with credit+// remaining.) Cheap org-level gate for the invoice "Apply Credit" action — we+// don't surface it at all unless there's something to apply.+export async function getCompanyHasOpenCredits(+ client: SupabaseClient<Database>,+ companyId: string,+ side: "sales" | "purchase"+): Promise<boolean> {+ const direction = side === "sales" ? "Credit" : "Debit";+ const memos = await client+ .from("memo")+ .select("id, amount")+ .eq("companyId", companyId)+ .eq("status", "Posted")+ .eq("direction", direction);+ if (memos.error || !memos.data || memos.data.length === 0) return false;++ // deno-lint-ignore no-explicit-any+ const rows = memos.data as any[];+ const ids = rows.map((m) => m.id as string);+ const apps = await client+ .from("invoiceSettlement")+ .select("memoId, appliedAmount")+ .in("memoId", ids);+ if (apps.error) return false;++ const appliedByMemo = new Map<string, number>();+ for (const a of apps.data ?? []) {+ if (!a.memoId) continue;+ appliedByMemo.set(+ a.memoId,+ (appliedByMemo.get(a.memoId) ?? 0) + Number(a.appliedAmount)+ );+ }+ return rows.some(+ (m) => Number(m.amount) - (appliedByMemo.get(m.id) ?? 0) > 0.0001+ );+}++// Apply posted credits to invoices — additive insert of memo-sourced+// invoiceSettlement rows (the credits half of the "Receive Payment" composer).+// GL-neutral (the memos already posted their own journals), so no journal here;+// caps are validated under FOR UPDATE locks. Each application matches the memo's+// exchange rate to the invoice's (v1 requires equal rates — no cross-rate FX on+// credit application).+// The credit applications currently staged on a (Draft) payment — drives the+// composer's pre-fill so a staged credit stays visible and editable instead of+// silently vanishing from the available list.+export async function getStagedCreditsForPayment(+ client: SupabaseClient<Database>,+ paymentId: string,+ side: "sales" | "purchase"+): Promise<{+ data: { memoId: string; invoiceId: string; amount: number }[] | null;+ error: unknown;+}> {+ const apps = await client+ .from("invoiceSettlement")+ .select(+ "memoId, targetSalesInvoiceId, targetPurchaseInvoiceId, appliedAmount"+ )+ .eq("appliedViaPaymentId", paymentId);+ if (apps.error) return { data: null, error: apps.error };+ const rows = (apps.data ?? []) as Array<{+ memoId: string | null;+ targetSalesInvoiceId: string | null;+ targetPurchaseInvoiceId: string | null;+ appliedAmount: number;+ }>;+ const data = rows+ .map((r) => ({+ memoId: r.memoId ?? "",+ invoiceId:+ side === "sales"+ ? (r.targetSalesInvoiceId ?? "")+ : (r.targetPurchaseInvoiceId ?? ""),+ amount: Number(r.appliedAmount)+ }))+ .filter((r) => r.memoId && r.invoiceId);+ return { data, error: null };+}++export async function applyCreditsToInvoices(+ db: Kysely<KyselyDatabase>,+ args: {+ paymentId: string;+ companyId: string;+ createdBy: string;+ appliedDate: string;+ side: "sales" | "purchase";+ applications: { memoId: string; invoiceId: string; amount: number }[];+ }+) {+ const isSales = args.side === "sales";+ const activeStatuses = isSales+ ? ["Submitted", "Partially Paid", "Overdue"]+ : ["Open", "Partially Paid", "Overdue"];++ return db.transaction().execute(async (trx) => {+ // Credit applications are STAGED on a Draft payment and only go live when it+ // posts (the invoice views gate memo settlements on appliedViaPaymentId's+ // payment status). The composer pre-fills the currently-staged set and submits+ // the FULL set each time, so this is a delete-then-insert REPLACE keyed on the+ // payment — exactly like cash applications (replaceInvoiceSettlements).+ const payment = await trx+ .selectFrom("payment")+ .select(["id", "status", "customerId", "supplierId"])+ .where("id", "=", args.paymentId)+ .where("companyId", "=", args.companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!payment) throw new Error("Payment not found");+ if (payment.status !== "Draft") {+ throw new Error(+ "Credit applications can only be edited while the payment is Draft"+ );+ }+ // The party every memo and invoice in this batch must belong to: a payment's+ // credits can only clear ITS own party's invoices using ITS own party's+ // credit memos (a customer's credit can't settle another customer's invoice).+ const paymentParty = isSales ? payment.customerId : payment.supplierId;++ // Replace this payment's prior credit applications with the submitted set.+ await trx+ .deleteFrom("invoiceSettlement")+ .where("appliedViaPaymentId", "=", args.paymentId)+ .execute();++ if (args.applications.length === 0) return;++ const memoIds = [...new Set(args.applications.map((a) => a.memoId))];+ const invoiceIds = [...new Set(args.applications.map((a) => a.invoiceId))];++ // Lock the memos + read their remaining credit (amount - Σ applied elsewhere).+ const memos = await trx+ .selectFrom("memo")+ .select([+ "id",+ "status",+ "exchangeRate",+ "amount",+ "customerId",+ "supplierId"+ ])+ .where("id", "in", memoIds)+ .where("companyId", "=", args.companyId)+ .forUpdate()+ .execute();+ const priorByMemo = await trx+ .selectFrom("invoiceSettlement")+ .select(["memoId", "appliedAmount"])+ .where("memoId", "in", memoIds)+ .execute();+ const priorApplied = new Map<string, number>();+ for (const p of priorByMemo) {+ if (!p.memoId) continue;+ priorApplied.set(+ p.memoId,+ (priorApplied.get(p.memoId) ?? 0) + Number(p.appliedAmount)+ );+ }+ const memoById = new Map(memos.map((m) => [m.id, m]));++ // Lock the invoices + read open balance + status from the view.+ const invoiceTable = isSales ? "salesInvoice" : "purchaseInvoice";+ const invoiceView = isSales ? "salesInvoices" : "purchaseInvoices";+ const lockedInvoices = await trx+ .selectFrom(invoiceTable)+ .select(["id", "invoiceId", "status", "exchangeRate"])+ .where("id", "in", invoiceIds)+ .where("companyId", "=", args.companyId)+ .forUpdate()+ .execute();+ const invoiceBalances = await trx+ .selectFrom(invoiceView)+ .select(["id", "balance"])+ .where("id", "in", invoiceIds)+ .execute();+ const balById = new Map(invoiceBalances.map((b) => [b.id, b]));+ const invById = new Map(lockedInvoices.map((i) => [i.id, i]));++ // Party of each targeted invoice (the column differs by side, so fetch+ // per-branch). Used below to reject applying a credit to an invoice that+ // belongs to a different party than the payment.+ const partyByInvoice = new Map<string, string | null>();+ if (isSales) {+ const rows = await trx+ .selectFrom("salesInvoice")+ .select(["id", "customerId"])+ .where("id", "in", invoiceIds)+ .where("companyId", "=", args.companyId)+ .execute();+ for (const r of rows) partyByInvoice.set(r.id, r.customerId);+ } else {+ const rows = await trx+ .selectFrom("purchaseInvoice")+ .select(["id", "supplierId"])+ .where("id", "in", invoiceIds)+ .where("companyId", "=", args.companyId)+ .execute();+ for (const r of rows) partyByInvoice.set(r.id, r.supplierId);+ }++ // This payment's own cash applications aren't in the live balance yet (the+ // payment is Draft) and its prior credits were just deleted above, so reserve+ // room for the cash when capping these credits.+ const cashApps = await trx+ .selectFrom("invoiceSettlement")+ .select([+ "targetSalesInvoiceId",+ "targetPurchaseInvoiceId",+ "appliedAmount",+ "discountAmount",+ "writeOffAmount"+ ])+ .where("paymentId", "=", args.paymentId)+ .execute();+ const cashByInvoice = new Map<string, number>();+ for (const c of cashApps) {+ const inv = isSales ? c.targetSalesInvoiceId : c.targetPurchaseInvoiceId;+ if (!inv) continue;+ cashByInvoice.set(+ inv,+ (cashByInvoice.get(inv) ?? 0) ++ Number(c.appliedAmount) ++ Number(c.discountAmount) ++ Number(c.writeOffAmount)+ );+ }++ // Validate each application, accumulating per-memo and per-invoice caps.+ const memoUse = new Map<string, number>();+ const invoiceUse = new Map<string, number>();+ for (const app of args.applications) {+ if (app.amount <= 0)+ throw new Error("Applied amount must be greater than 0");+ const memo = memoById.get(app.memoId);+ if (!memo) throw new Error(`Credit memo ${app.memoId} not found`);+ if (memo.status !== "Posted")+ throw new Error("Only posted credits can be applied");+ const memoParty = isSales ? memo.customerId : memo.supplierId;+ if (memoParty !== paymentParty)+ throw new Error(+ "A credit memo can only be applied through a payment for the same party"+ );+ const inv = invById.get(app.invoiceId);+ if (!inv) throw new Error(`Invoice ${app.invoiceId} not found`);+ const invoiceLabel = inv.invoiceId ?? app.invoiceId;+ if (partyByInvoice.get(app.invoiceId) !== paymentParty)+ throw new Error(+ `Invoice ${invoiceLabel} belongs to a different party than the payment`+ );+ if (!activeStatuses.includes(String(inv.status)))+ throw new Error(+ `Invoice ${invoiceLabel} is ${String(inv.status).toLowerCase()}, so no credit can be applied to it`+ );+ if (Number(memo.exchangeRate) !== Number(inv.exchangeRate))+ throw new Error(+ "Applying a credit requires matching exchange rates (cross-rate FX not yet supported)"+ );++ memoUse.set(app.memoId, (memoUse.get(app.memoId) ?? 0) + app.amount);+ invoiceUse.set(+ app.invoiceId,+ (invoiceUse.get(app.invoiceId) ?? 0) + app.amount+ );++ const memoRemaining =+ Number(memo.amount) - (priorApplied.get(app.memoId) ?? 0);+ if (memoUse.get(app.memoId)! > memoRemaining + 0.0001)+ throw new Error(+ `Applied (${memoUse.get(app.memoId)}) exceeds the credit's remaining balance (${memoRemaining})`+ );++ const invoiceOpen =+ Number(balById.get(app.invoiceId)?.balance ?? 0) -+ (cashByInvoice.get(app.invoiceId) ?? 0);+ if (invoiceUse.get(app.invoiceId)! > invoiceOpen + 0.0001)+ throw new Error(+ invoiceOpen <= 0.0001+ ? `Invoice ${invoiceLabel} has no open balance to apply credit to (it is already fully settled)`+ : `Credit applied to invoice ${invoiceLabel} (${invoiceUse.get(+ app.invoiceId+ )}) exceeds its open balance of ${invoiceOpen.toFixed(2)}`+ );+ }++ await trx+ .insertInto("invoiceSettlement")+ .values(+ args.applications.map((app) => ({+ memoId: app.memoId,+ appliedViaPaymentId: args.paymentId,+ companyId: args.companyId,+ createdBy: args.createdBy,+ targetSalesInvoiceId: isSales ? app.invoiceId : null,+ targetPurchaseInvoiceId: isSales ? null : app.invoiceId,+ appliedAmount: app.amount,+ discountAmount: 0,+ writeOffAmount: 0,+ sourceExchangeRate: Number(memoById.get(app.memoId)!.exchangeRate),+ targetExchangeRate: Number(invById.get(app.invoiceId)!.exchangeRate),+ appliedDate: args.appliedDate+ }))+ )+ .execute();+ });+}++// Tie-out RPCs (migration 20260519140000_ar-ap-tie-out)++export async function getArTieOut(+ client: SupabaseClient<Database>,+ companyId: string,+ asOfDate: string+) {+ return client+ .rpc("get_ar_tie_out", {+ _company_id: companyId,+ _as_of_date: asOfDate+ })+ .single();+}++export async function getApTieOut(+ client: SupabaseClient<Database>,+ companyId: string,+ asOfDate: string+) {+ return client+ .rpc("get_ap_tie_out", {+ _company_id: companyId,+ _as_of_date: asOfDate+ })+ .single();+}++export async function getArOpenByCustomer(+ client: SupabaseClient<Database>,+ companyId: string,+ asOfDate: string+) {+ return client.rpc("get_ar_open_by_customer", {+ _company_id: companyId,+ _as_of_date: asOfDate+ });+}++export async function getApOpenBySupplier(+ client: SupabaseClient<Database>,+ companyId: string,+ asOfDate: string+) {+ return client.rpc("get_ap_open_by_supplier", {+ _company_id: companyId,+ _as_of_date: asOfDate+ });+}++// Aging RPCs (migration 20260519150000_ar-ap-aging)++export type AgingOptions = {+ agingMethod?: "dueDate" | "documentDate";+ bucketDays?: [number, number, number];+};++export async function getArAging(+ client: SupabaseClient<Database>,+ companyId: string,+ asOfDate: string,+ options: AgingOptions = {}+) {+ const [b1, b2, b3] = options.bucketDays ?? [30, 60, 90];+ return client.rpc("get_ar_aging", {+ _company_id: companyId,+ _as_of_date: asOfDate,+ _aging_method: options.agingMethod ?? "dueDate",+ _bucket1: b1,+ _bucket2: b2,+ _bucket3: b3+ });+}++export async function getApAging(+ client: SupabaseClient<Database>,+ companyId: string,+ asOfDate: string,+ options: AgingOptions = {}+) {+ const [b1, b2, b3] = options.bucketDays ?? [30, 60, 90];+ return client.rpc("get_ap_aging", {+ _company_id: companyId,+ _as_of_date: asOfDate,+ _aging_method: options.agingMethod ?? "dueDate",+ _bucket1: b1,+ _bucket2: b2,+ _bucket3: b3+ });+}diff --git a/apps/erp/app/modules/invoicing/ui/Dashboard/InvoicingDashboard.tsx b/apps/erp/app/modules/invoicing/ui/Dashboard/InvoicingDashboard.tsxnew file mode 100644index 0000000000..f2d393d2c0--- /dev/null+++ b/apps/erp/app/modules/invoicing/ui/Dashboard/InvoicingDashboard.tsx@@ -0,0 +1,412 @@+import {+ Button,+ Card,+ CardContent,+ CardFooter,+ CardHeader,+ CardTitle,+ HStack,+ Status,+ Table,+ Tbody,+ Td,+ Th,+ Thead,+ Tr+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import { useMemo } from "react";+import {+ LuArrowUpRight,+ LuBanknote,+ LuClock,+ LuHandCoins+} from "react-icons/lu";+import { Link } from "react-router";+import { useCurrencyFormatter, useDateFormatter } from "~/hooks";+import { useCustomers, useSuppliers } from "~/stores";+import { path } from "~/utils/path";+import PaymentStatus from "../Payment/PaymentStatus";++export type AgingTotals = {+ current: number;+ bucket1: number;+ bucket2: number;+ bucket3: number;+ bucket4: number;+ unapplied: number;+ total: number;+ count: number;+};++export type TieOut = {+ subledgerBalance: number;+ glBalance: number;+ variance: number;+} | null;++export type RecentPayment = {+ id: string;+ paymentId: string;+ paymentType: "Receipt" | "Disbursement";+ status: "Draft" | "Posted" | "Voided" | null;+ paymentDate: string | null;+ totalAmount: number;+ currencyCode: string;+ customerId: string | null;+ supplierId: string | null;+};++type InvoicingDashboardProps = {+ asOfDate: string;+ ar: AgingTotals;+ ap: AgingTotals;+ arTieOut: TieOut;+ apTieOut: TieOut;+ bucketDays: [number, number, number];+ recentPayments: RecentPayment[];+};++// Variance below this (in base currency) is treated as tied-out — guards against+// floating-point dust in the subledger-vs-GL comparison. Matches TieOut.tsx.+const TIE_OUT_EPSILON = 0.01;++const overdueOf = (t: AgingTotals) =>+ t.bucket1 + t.bucket2 + t.bucket3 + t.bucket4;++const AgingCard = ({+ title,+ icon,+ totals,+ tieOut,+ bucketLabels,+ format+}: {+ title: React.ReactNode;+ icon: React.ReactNode;+ totals: AgingTotals;+ tieOut: TieOut;+ bucketLabels: string[];+ format: (n: number) => string;+}) => {+ const buckets = [+ { label: <Trans>Current</Trans>, value: totals.current },+ { label: bucketLabels[0], value: totals.bucket1 },+ { label: bucketLabels[1], value: totals.bucket2 },+ { label: bucketLabels[2], value: totals.bucket3 },+ { label: bucketLabels[3], value: totals.bucket4 }+ ];+ const tied = tieOut ? Math.abs(tieOut.variance) < TIE_OUT_EPSILON : true;++ return (+ <Card>+ <CardHeader className="flex-row gap-2">+ <span className="text-muted-foreground">{icon}</span>+ <CardTitle>{title}</CardTitle>+ </CardHeader>+ <CardContent>+ <Table>+ <Thead>+ <Tr>+ <Th>+ <Trans>Bucket</Trans>+ </Th>+ <Th className="text-right">+ <Trans>Amount</Trans>+ </Th>+ </Tr>+ </Thead>+ <Tbody>+ {buckets.map((b, i) => (+ <Tr key={i}>+ <Td>{b.label}</Td>+ <Td className="text-right tabular-nums">{format(b.value)}</Td>+ </Tr>+ ))}+ {totals.unapplied !== 0 ? (+ <Tr className="text-muted-foreground">+ <Td>+ <Trans>Unapplied</Trans>+ </Td>+ <Td className="text-right tabular-nums">+ {format(totals.unapplied)}+ </Td>+ </Tr>+ ) : null}+ <Tr className="font-medium">+ <Td>+ <Trans>Total</Trans>+ </Td>+ <Td className="text-right tabular-nums">+ {format(totals.total)}+ </Td>+ </Tr>+ </Tbody>+ </Table>+ </CardContent>+ <CardFooter className="justify-between text-xs">+ <span className="text-muted-foreground">+ <Trans>GL tie-out</Trans>+ </span>+ {tieOut ? (+ tied ? (+ <Status color="green">+ <Trans>Balanced</Trans>+ </Status>+ ) : (+ <Status color="red">+ <span className="tabular-nums">{format(tieOut.variance)}</span>+ </Status>+ )+ ) : (+ <span className="text-muted-foreground">—</span>+ )}+ </CardFooter>+ </Card>+ );+};++const InvoicingDashboard = ({+ ar,+ ap,+ arTieOut,+ apTieOut,+ bucketDays,+ recentPayments+}: InvoicingDashboardProps) => {+ const { t } = useLingui();+ const { formatDate } = useDateFormatter();+ const currencyFormatter = useCurrencyFormatter();+ const format = (n: number) => currencyFormatter.format(n);+ const [customers] = useCustomers();+ const [suppliers] = useSuppliers();++ const customerName = useMemo(+ () => new Map(customers.map((c) => [c.id, c.name])),+ [customers]+ );+ const supplierName = useMemo(+ () => new Map(suppliers.map((s) => [s.id, s.name])),+ [suppliers]+ );++ const [b1, b2, b3] = bucketDays;+ const bucketLabels = [+ `1–${b1}`,+ `${b1 + 1}–${b2}`,+ `${b2 + 1}–${b3}`,+ `${b3}+`+ ];++ const arOverdue = overdueOf(ar);+ const apOverdue = overdueOf(ap);+ const arOverduePct =+ ar.total > 0 ? Math.round((arOverdue / ar.total) * 100) : 0;+ const apOverduePct =+ ap.total > 0 ? Math.round((apOverdue / ap.total) * 100) : 0;++ return (+ <div className="flex flex-col gap-4 w-full p-4 h-[calc(100dvh-var(--header-height))] overflow-y-auto scrollbar-thin scrollbar-thumb-rounded-full scrollbar-thumb-muted-foreground">+ {/* KPI Cards */}+ <div className="grid w-full gap-4 grid-cols-1 sm:grid-cols-2 lg:grid-cols-4">+ <Card>+ <CardHeader className="flex-row gap-2">+ <LuHandCoins className="text-muted-foreground" />+ <CardTitle>+ <Trans>AR Outstanding</Trans>+ </CardTitle>+ </CardHeader>+ <CardContent>+ <HStack className="justify-between w-full items-center">+ <h3 className="text-4xl font-medium tracking-tighter tabular-nums">+ {format(ar.total)}+ </h3>+ <Button+ rightIcon={<LuArrowUpRight />}+ variant="secondary"+ asChild+ >+ <Link to={path.to.receivables}>+ <Trans>View</Trans>+ </Link>+ </Button>+ </HStack>+ <span className="text-xs text-muted-foreground">+ {t`${ar.count} customers with a balance`}+ </span>+ </CardContent>+ </Card>++ <Card>+ <CardHeader className="flex-row gap-2">+ <LuClock className="text-muted-foreground" />+ <CardTitle>+ <Trans>AR Overdue</Trans>+ </CardTitle>+ </CardHeader>+ <CardContent>+ <h3 className="text-4xl font-medium tracking-tighter tabular-nums">+ {format(arOverdue)}+ </h3>+ <span className="text-xs text-muted-foreground">+ {ar.total > 0+ ? t`${arOverduePct}% of receivables`+ : t`No receivables`}+ </span>+ </CardContent>+ </Card>++ <Card>+ <CardHeader className="flex-row gap-2">+ <LuHandCoins className="text-muted-foreground" />+ <CardTitle>+ <Trans>AP Outstanding</Trans>+ </CardTitle>+ </CardHeader>+ <CardContent>+ <HStack className="justify-between w-full items-center">+ <h3 className="text-4xl font-medium tracking-tighter tabular-nums">+ {format(ap.total)}+ </h3>+ <Button+ rightIcon={<LuArrowUpRight />}+ variant="secondary"+ asChild+ >+ <Link to={path.to.payables}>+ <Trans>View</Trans>+ </Link>+ </Button>+ </HStack>+ <span className="text-xs text-muted-foreground">+ {t`${ap.count} suppliers with a balance`}+ </span>+ </CardContent>+ </Card>++ <Card>+ <CardHeader className="flex-row gap-2">+ <LuClock className="text-muted-foreground" />+ <CardTitle>+ <Trans>AP Overdue</Trans>+ </CardTitle>+ </CardHeader>+ <CardContent>+ <h3 className="text-4xl font-medium tracking-tighter tabular-nums">+ {format(apOverdue)}+ </h3>+ <span className="text-xs text-muted-foreground">+ {ap.total > 0 ? t`${apOverduePct}% of payables` : t`No payables`}+ </span>+ </CardContent>+ </Card>+ </div>++ {/* Aging breakdown */}+ <div className="grid w-full gap-4 grid-cols-1 lg:grid-cols-2">+ <AgingCard+ title={<Trans>Receivables aging</Trans>}+ icon={<LuClock />}+ totals={ar}+ tieOut={arTieOut}+ bucketLabels={bucketLabels}+ format={format}+ />+ <AgingCard+ title={<Trans>Payables aging</Trans>}+ icon={<LuClock />}+ totals={ap}+ tieOut={apTieOut}+ bucketLabels={bucketLabels}+ format={format}+ />+ </div>++ {/* Recent payments */}+ <Card>+ <CardHeader className="flex-row gap-2">+ <LuBanknote className="text-muted-foreground" />+ <CardTitle>+ <Trans>Recent payments</Trans>+ </CardTitle>+ </CardHeader>+ <CardContent>+ <div className="min-h-[120px] w-full">+ {recentPayments.length === 0 ? (+ <p className="text-sm text-muted-foreground py-6 text-center">+ <Trans>No payments yet.</Trans>+ </p>+ ) : (+ <Table>+ <Thead>+ <Tr>+ <Th>+ <Trans>Date</Trans>+ </Th>+ <Th>+ <Trans>Payment</Trans>+ </Th>+ <Th>+ <Trans>Counterparty</Trans>+ </Th>+ <Th>+ <Trans>Type</Trans>+ </Th>+ <Th className="text-right">+ <Trans>Amount</Trans>+ </Th>+ <Th>+ <Trans>Status</Trans>+ </Th>+ </Tr>+ </Thead>+ <Tbody>+ {recentPayments.map((p) => {+ const name =+ p.paymentType === "Receipt"+ ? (customerName.get(p.customerId ?? "") ?? p.customerId)+ : (supplierName.get(p.supplierId ?? "") ??+ p.supplierId);+ return (+ <Tr key={p.id}>+ <Td>+ {p.paymentDate ? formatDate(p.paymentDate) : "—"}+ </Td>+ <Td>+ <Link+ to={path.to.payment(p.id)}+ className="text-primary hover:underline"+ >+ {p.paymentId}+ </Link>+ </Td>+ <Td className="max-w-[200px] truncate">+ {name ?? "—"}+ </Td>+ <Td>+ {p.paymentType === "Receipt" ? (+ <Trans>From customer</Trans>+ ) : (+ <Trans>To supplier</Trans>+ )}+ </Td>+ <Td className="text-right tabular-nums">+ {currencyFormatter.format(Number(p.totalAmount))}+ </Td>+ <Td>+ <PaymentStatus status={p.status ?? undefined} />+ </Td>+ </Tr>+ );+ })}+ </Tbody>+ </Table>+ )}+ </div>+ </CardContent>+ </Card>+ </div>+ );+};++export default InvoicingDashboard;diff --git a/apps/erp/app/modules/invoicing/ui/Dashboard/index.ts b/apps/erp/app/modules/invoicing/ui/Dashboard/index.tsnew file mode 100644index 0000000000..271a7d4eb6--- /dev/null+++ b/apps/erp/app/modules/invoicing/ui/Dashboard/index.ts@@ -0,0 +1,6 @@+export type {+ AgingTotals,+ RecentPayment,+ TieOut+} from "./InvoicingDashboard";+export { default as InvoicingDashboard } from "./InvoicingDashboard";diff --git a/apps/erp/app/modules/invoicing/ui/Memo/MemoApplicationsPanel.tsx b/apps/erp/app/modules/invoicing/ui/Memo/MemoApplicationsPanel.tsxnew file mode 100644index 0000000000..c3581523f5--- /dev/null+++ b/apps/erp/app/modules/invoicing/ui/Memo/MemoApplicationsPanel.tsx@@ -0,0 +1,116 @@+import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ Table,+ Tbody,+ Td,+ Th,+ Thead,+ Tr+} from "@carbon/react";+import { Trans } from "@lingui/react/macro";+import { Link } from "react-router";+import { Empty } from "~/components";+import { Enumerable } from "~/components/Enumerable";+import { useCurrencyFormatter, useDateFormatter } from "~/hooks";+import type { MemoApplication } from "~/modules/invoicing";+import { path } from "~/utils/path";++type MemoApplicationsPanelProps = {+ rows: MemoApplication[];+ // Applied amounts are in the memo's source currency.+ currencyCode: string;+};++const TARGET_LABEL: Record<MemoApplication["target"]["type"], string> = {+ salesInvoice: "Sales Invoice",+ purchaseInvoice: "Purchase Invoice",+ memo: "Memo"+};++function targetPath(target: MemoApplication["target"]): string {+ switch (target.type) {+ case "salesInvoice":+ return path.to.salesInvoice(target.id);+ case "purchaseInvoice":+ return path.to.purchaseInvoice(target.id);+ case "memo":+ return path.to.memo(target.id);+ }+}++// Where this credit/debit memo's balance went — the invoices (and memos) it has+// been applied to. The reverse of the invoice "Payments" panel.+const MemoApplicationsPanel = ({+ rows,+ currencyCode+}: MemoApplicationsPanelProps) => {+ const { formatDate } = useDateFormatter();+ const currencyFormatter = useCurrencyFormatter({ currency: currencyCode });++ return (+ <Card>+ <CardHeader>+ <CardTitle>+ <Trans>Applied To</Trans>+ </CardTitle>+ <CardDescription>+ <Trans>+ Invoices this memo has been applied to. Click a row to open the+ document.+ </Trans>+ </CardDescription>+ </CardHeader>+ <CardContent>+ {rows.length === 0 ? (+ <Empty />+ ) : (+ <Table>+ <Thead>+ <Tr>+ <Th>+ <Trans>Date</Trans>+ </Th>+ <Th>+ <Trans>Type</Trans>+ </Th>+ <Th>+ <Trans>Document</Trans>+ </Th>+ <Th className="text-right">+ <Trans>Applied</Trans>+ </Th>+ </Tr>+ </Thead>+ <Tbody>+ {rows.map((r) => (+ <Tr key={r.id}>+ <Td>{formatDate(r.appliedDate)}</Td>+ <Td>+ <Enumerable value={TARGET_LABEL[r.target.type]} />+ </Td>+ <Td>+ <Link+ to={targetPath(r.target)}+ className="text-primary hover:underline"+ >+ {r.target.readableId}+ </Link>+ </Td>+ <Td className="text-right tabular-nums">+ {currencyFormatter.format(Number(r.appliedAmount))}+ </Td>+ </Tr>+ ))}+ </Tbody>+ </Table>+ )}+ </CardContent>+ </Card>+ );+};++export default MemoApplicationsPanel;diff --git a/apps/erp/app/modules/invoicing/ui/Memo/MemoForm.tsx b/apps/erp/app/modules/invoicing/ui/Memo/MemoForm.tsxnew file mode 100644index 0000000000..fbdb3cf7d2--- /dev/null+++ b/apps/erp/app/modules/invoicing/ui/Memo/MemoForm.tsx@@ -0,0 +1,267 @@+import { ValidatedForm } from "@carbon/form";+import {+ Button,+ Card,+ CardContent,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+ DropdownMenuIcon,+ DropdownMenuItem,+ FormControl,+ FormLabel,+ Select as PartySelect,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ useDisclosure,+ VStack+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import { useState } from "react";+import { LuCheckCheck, LuTicketX, LuTrash } from "react-icons/lu";+import { useFetcher } from "react-router";+import type { z } from "zod";+import { DocumentHeader } from "~/components";+import { Enumerable } from "~/components/Enumerable";+import {+ Currency,+ Customer,+ CustomFormFields,+ DatePicker,+ Hidden,+ Input,+ Number,+ Select,+ SequenceOrCustomId,+ Submit,+ Supplier,+ TextArea+} from "~/components/Form";+import { ConfirmDelete } from "~/components/Modals";+import { usePermissions, useUser } from "~/hooks";+import {+ isMemoLocked,+ memoDirection,+ memoValidator+} from "~/modules/invoicing";+import { path } from "~/utils/path";+import MemoStatus from "./MemoStatus";++type MemoFormValues = z.infer<typeof memoValidator>;++type MemoFormProps = {+ initialValues: MemoFormValues & { status?: string };+};++const MemoForm = ({ initialValues }: MemoFormProps) => {+ const { t } = useLingui();+ const { company } = useUser();+ const permissions = usePermissions();+ const post = useFetcher();+ const voidFetcher = useFetcher();+ const isEditing = Boolean(initialValues.id);+ const status = initialValues.status as+ | "Draft"+ | "Posted"+ | "Voided"+ | undefined;+ const isLocked = isMemoLocked(initialValues.status);+ const canMutate = permissions.can("update", "invoicing");+ const canDelete = permissions.can("delete", "invoicing");+ const deleteModal = useDisclosure();++ // Party type is a UI-only toggle — NOT a validator field. It switches which of+ // customerId/supplierId is shown; the hidden one stays empty. A memo can be for+ // a customer OR a supplier in either direction (all four combos are valid), so+ // this is independent of the direction control below. When editing, derive the+ // initial value from whichever party id is set.+ const [partyType, setPartyType] = useState<"Customer" | "Supplier">(+ initialValues.supplierId ? "Supplier" : "Customer"+ );++ const directionOptions = memoDirection.map((d) => ({+ label: <Enumerable value={d} />,+ value: d+ }));++ return (+ <>+ <ValidatedForm+ method="post"+ validator={memoValidator}+ defaultValues={initialValues}+ isDisabled={isEditing && isLocked}+ className="w-full"+ >+ <Card>+ {isEditing ? (+ <DocumentHeader+ title={initialValues.memoId ?? ""}+ status={+ <>+ <Enumerable value={initialValues.direction} />+ <MemoStatus status={status} />+ </>+ }+ menuItems={+ status === "Draft" && canDelete ? (+ <DropdownMenuItem destructive onClick={deleteModal.onOpen}>+ <DropdownMenuIcon icon={<LuTrash />} />+ <Trans>Delete</Trans>+ </DropdownMenuItem>+ ) : undefined+ }+ actions={+ status === "Draft" ? (+ <Button+ leftIcon={<LuCheckCheck />}+ variant="primary"+ isLoading={post.state !== "idle"}+ isDisabled={!canMutate}+ onClick={() =>+ post.submit(null, {+ method: "post",+ action: path.to.memoPost(initialValues.id!)+ })+ }+ >+ <Trans>Post</Trans>+ </Button>+ ) : status === "Posted" ? (+ <Button+ leftIcon={<LuTicketX />}+ variant="destructive"+ isLoading={voidFetcher.state !== "idle"}+ isDisabled={!canMutate}+ onClick={() =>+ voidFetcher.submit(null, {+ method: "post",+ action: path.to.memoVoid(initialValues.id!)+ })+ }+ >+ <Trans>Void</Trans>+ </Button>+ ) : undefined+ }+ />+ ) : (+ <CardHeader>+ <CardTitle>+ <Trans>New Credit / Debit Memo</Trans>+ </CardTitle>+ <CardDescription>+ <Trans>+ Record a credit or debit memo against a customer or supplier.+ Applications to specific invoices are added after the memo is+ created.+ </Trans>+ </CardDescription>+ </CardHeader>+ )}+ <CardContent>+ <Hidden name="id" />+ {isEditing && <Hidden name="memoId" />}+ <VStack>+ <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 md:grid-cols-2">+ {!isEditing && (+ <SequenceOrCustomId+ name="memoId"+ label={t`Memo ID`}+ table="memo"+ />+ )}+ <Select+ name="direction"+ label={t`Direction`}+ options={directionOptions}+ />+ {/* UI-only party-type select; no validator field. It only+ controls which of customerId/supplierId is shown. */}+ <FormControl>+ <FormLabel>+ <Trans>Party Type</Trans>+ </FormLabel>+ <PartySelect+ value={partyType}+ onValueChange={(value) => {+ if (value === "Customer" || value === "Supplier") {+ setPartyType(value);+ }+ }}+ >+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="Customer">+ <Enumerable value="Customer" />+ </SelectItem>+ <SelectItem value="Supplier">+ <Enumerable value="Supplier" />+ </SelectItem>+ </SelectContent>+ </PartySelect>+ </FormControl>+ {partyType === "Customer" ? (+ <Customer name="customerId" label={t`Customer`} />+ ) : (+ <Supplier name="supplierId" label={t`Supplier`} />+ )}+ <DatePicker name="memoDate" label={t`Memo Date`} />+ <Currency name="currencyCode" label={t`Currency`} />+ <Number+ name="exchangeRate"+ label={t`Exchange Rate`}+ formatOptions={{+ minimumFractionDigits: 2,+ maximumFractionDigits: 4+ }}+ />+ <Number+ name="amount"+ label={t`Amount`}+ formatOptions={{+ style: "currency",+ currency: company?.baseCurrencyCode ?? "USD"+ }}+ />+ <Input name="reference" label={t`Reference`} />+ <CustomFormFields table="memo" />+ </div>+ <div className="mt-4 w-full">+ <TextArea name="notes" label={t`Notes`} />+ </div>+ </VStack>+ </CardContent>+ <CardFooter>+ <Submit+ isDisabled={+ isEditing+ ? isLocked || !canMutate+ : !permissions.can("create", "invoicing")+ }+ >+ <Trans>Save</Trans>+ </Submit>+ </CardFooter>+ </Card>+ </ValidatedForm>+ {deleteModal.isOpen && (+ <ConfirmDelete+ action={path.to.memoDelete(initialValues.id!)}+ isOpen={deleteModal.isOpen}+ name={initialValues.memoId ?? ""}+ text={t`Are you sure you want to delete ${initialValues.memoId}? This cannot be undone.`}+ onCancel={deleteModal.onClose}+ onSubmit={deleteModal.onClose}+ />+ )}+ </>+ );+};++export default MemoForm;diff --git a/apps/erp/app/modules/invoicing/ui/Memo/MemoStatus.tsx b/apps/erp/app/modules/invoicing/ui/Memo/MemoStatus.tsxnew file mode 100644index 0000000000..82a166ba94--- /dev/null+++ b/apps/erp/app/modules/invoicing/ui/Memo/MemoStatus.tsx@@ -0,0 +1,21 @@+import { Status } from "@carbon/react";+import type { memoStatus } from "~/modules/invoicing";++type MemoStatusProps = {+ status?: (typeof memoStatus)[number] | null;+};++const MemoStatus = ({ status }: MemoStatusProps) => {+ switch (status) {+ case "Draft":+ return <Status color="gray">{status}</Status>;+ case "Posted":+ return <Status color="green">{status}</Status>;+ case "Voided":+ return <Status color="red">{status}</Status>;+ default:+ return null;+ }+};++export default MemoStatus;diff --git a/apps/erp/app/modules/invoicing/ui/Memo/MemosTable.tsx b/apps/erp/app/modules/invoicing/ui/Memo/MemosTable.tsxnew file mode 100644index 0000000000..0a700e9c1a--- /dev/null+++ b/apps/erp/app/modules/invoicing/ui/Memo/MemosTable.tsx@@ -0,0 +1,265 @@+import { MenuIcon, MenuItem, useDisclosure } from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import type { ColumnDef } from "@tanstack/react-table";+import { memo, useCallback, useMemo, useState } from "react";+import {+ LuCalendar,+ LuCircleDot,+ LuCoins,+ LuEye,+ LuHash,+ LuLandmark,+ LuPencil,+ LuTrash,+ LuUser+} from "react-icons/lu";+import { useNavigate } from "react-router";+import {+ CustomerAvatar,+ Hyperlink,+ New,+ SupplierAvatar,+ Table+} from "~/components";+import { Enumerable } from "~/components/Enumerable";+import { useAccounts } from "~/components/Form/Account";+import { ConfirmDelete } from "~/components/Modals";+import {+ useCurrencyFormatter,+ useDateFormatter,+ usePermissions+} from "~/hooks";+import { useCustomers, useSuppliers } from "~/stores";+import { path } from "~/utils/path";+import { memoDirection, memoStatus } from "../../invoicing.models";+import MemoStatus from "./MemoStatus";++// The `memo` table is not present in the committed (cloud-generated) DB types, so+// declare the row shape locally from the migration schema.+type MemoRow = {+ id: string;+ memoId: string;+ direction: "Credit" | "Debit";+ status: "Draft" | "Posted" | "Voided";+ customerId: string | null;+ supplierId: string | null;+ memoDate: string;+ currencyCode: string;+ amount: number;+ reasonAccount: string | null;+ reference: string | null;+};++type MemosTableProps = {+ data: MemoRow[];+ count: number;+};++const MemosTable = memo(({ data, count }: MemosTableProps) => {+ const { t } = useLingui();+ const permissions = usePermissions();+ const navigate = useNavigate();+ const currencyFormatter = useCurrencyFormatter();+ const { formatDate } = useDateFormatter();+ const [customers] = useCustomers();+ const [suppliers] = useSuppliers();+ const accounts = useAccounts();+ const deleteModal = useDisclosure();+ const [selectedMemo, setSelectedMemo] = useState<MemoRow | null>(null);++ const renderContextMenu = useCallback(+ (row: MemoRow) => (+ <>+ <MenuItem onClick={() => navigate(path.to.memo(row.id))}>+ <MenuIcon icon={row.status === "Draft" ? <LuPencil /> : <LuEye />} />+ {row.status === "Draft" ? (+ <Trans>Edit Memo</Trans>+ ) : (+ <Trans>View Memo</Trans>+ )}+ </MenuItem>+ <MenuItem+ destructive+ disabled={+ row.status !== "Draft" || !permissions.can("delete", "invoicing")+ }+ onClick={() => {+ setSelectedMemo(row);+ deleteModal.onOpen();+ }}+ >+ <MenuIcon icon={<LuTrash />} />+ <Trans>Delete Memo</Trans>+ </MenuItem>+ </>+ ),+ [navigate, permissions, deleteModal]+ );++ const columns = useMemo<ColumnDef<MemoRow>[]>(+ () => [+ {+ accessorKey: "memoId",+ header: t`Memo ID`,+ cell: ({ row }) => (+ <Hyperlink to={path.to.memo(row.original.id)}>+ {row.original.memoId}+ </Hyperlink>+ ),+ meta: { icon: <LuHash /> }+ },+ {+ accessorKey: "direction",+ header: t`Direction`,+ cell: ({ row }) => <Enumerable value={row.original.direction} />,+ meta: {+ icon: <LuCircleDot />,+ filter: {+ type: "static",+ options: memoDirection.map((direction) => ({+ value: direction,+ label: <Enumerable value={direction} />+ }))+ },+ pluralHeader: t`Directions`+ }+ },+ {+ id: "counterparty",+ header: t`Counterparty`,+ cell: ({ row }) =>+ row.original.customerId ? (+ <CustomerAvatar customerId={row.original.customerId} />+ ) : row.original.supplierId ? (+ <SupplierAvatar supplierId={row.original.supplierId} />+ ) : null,+ meta: {+ icon: <LuUser />,+ filter: {+ type: "static",+ // Combined customer + supplier options; the loader maps the chosen+ // ids onto customerId OR supplierId.+ options: [+ ...(customers ?? []).map((c) => ({+ value: c.id,+ label: c.name+ })),+ ...(suppliers ?? []).map((s) => ({+ value: s.id,+ label: s.name+ }))+ ]+ },+ pluralHeader: t`Counterparties`+ }+ },+ {+ accessorKey: "memoDate",+ header: t`Memo Date`,+ cell: (item) => formatDate(item.getValue<string>()),+ meta: { icon: <LuCalendar /> }+ },+ {+ accessorKey: "amount",+ header: t`Amount`,+ cell: (item) => (+ <span className="tabular-nums">+ {currencyFormatter.format(item.getValue<number>())}+ </span>+ ),+ meta: {+ icon: <LuCoins />,+ renderTotal: true,+ formatter: currencyFormatter.format+ }+ },+ {+ accessorKey: "reasonAccount",+ header: t`Reason Account`,+ cell: ({ row }) => {+ const account = accounts.find(+ (a) => a.id === row.original.reasonAccount+ );+ if (!account) return row.original.reasonAccount;+ return (+ <span className="truncate">+ <span className="text-muted-foreground">{account.number}</span>{" "}+ {account.name}+ </span>+ );+ },+ meta: { icon: <LuLandmark /> }+ },+ {+ accessorKey: "currencyCode",+ header: t`Currency`,+ cell: ({ row }) => <Enumerable value={row.original.currencyCode} />+ },+ {+ accessorKey: "status",+ header: t`Status`,+ cell: ({ row }) => <MemoStatus status={row.original.status} />,+ meta: {+ icon: <LuCircleDot />,+ filter: {+ type: "static",+ options: memoStatus.map((status) => ({+ value: status,+ label: <MemoStatus status={status} />+ }))+ },+ pluralHeader: t`Statuses`+ }+ },+ {+ accessorKey: "reference",+ header: t`Reference`,+ cell: ({ row }) => row.original.reference ?? null+ }+ ],+ [t, formatDate, currencyFormatter, customers, suppliers, accounts]+ );++ return (+ <>+ <Table<MemoRow>+ count={count}+ columns={columns}+ data={data}+ defaultColumnPinning={{ left: ["memoId"] }}+ defaultColumnVisibility={{+ reference: false+ }}+ primaryAction={+ permissions.can("create", "invoicing") && (+ <New label={t`Memo`} to={path.to.memoNew} />+ )+ }+ renderContextMenu={renderContextMenu}+ title={t`Credit / Debit Memos`}+ table="memo"+ withSavedView+ />+ {selectedMemo && (+ <ConfirmDelete+ action={path.to.memoDelete(selectedMemo.id)}+ isOpen={deleteModal.isOpen}+ name={selectedMemo.memoId}+ text={t`Are you sure you want to delete ${selectedMemo.memoId}? This cannot be undone.`}+ onCancel={() => {+ deleteModal.onClose();+ setSelectedMemo(null);+ }}+ onSubmit={() => {+ deleteModal.onClose();+ setSelectedMemo(null);+ }}+ />+ )}+ </>+ );+});++MemosTable.displayName = "MemosTable";++export default MemosTable;diff --git a/apps/erp/app/modules/invoicing/ui/Memo/index.ts b/apps/erp/app/modules/invoicing/ui/Memo/index.tsnew file mode 100644index 0000000000..a14d7b2ff6--- /dev/null+++ b/apps/erp/app/modules/invoicing/ui/Memo/index.ts@@ -0,0 +1,4 @@+export { default as MemoApplicationsPanel } from "./MemoApplicationsPanel";+export { default as MemoForm } from "./MemoForm";+export { default as MemoStatus } from "./MemoStatus";+export { default as MemosTable } from "./MemosTable";diff --git a/apps/erp/app/modules/invoicing/ui/Payment/AvailableCreditsTable.tsx b/apps/erp/app/modules/invoicing/ui/Payment/AvailableCreditsTable.tsxnew file mode 100644index 0000000000..ade763a494--- /dev/null+++ b/apps/erp/app/modules/invoicing/ui/Payment/AvailableCreditsTable.tsx@@ -0,0 +1,357 @@+import {+ Button,+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ Checkbox,+ cn,+ NumberField,+ NumberInput,+ NumberInputGroup,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import { useCallback, useMemo, useState } from "react";+import { LuSave } from "react-icons/lu";+import { useFetcher } from "react-router";+import { Enumerable } from "~/components/Enumerable";+import { useCurrencyFormatter, usePermissions } from "~/hooks";+import { path } from "~/utils/path";++// An available credit (a posted, balance-reducing memo) the party can apply to an+// open invoice alongside the cash payment.+type AvailableCredit = {+ id: string;+ memoId: string;+ direction: string;+ currencyCode: string;+ exchangeRate: number;+ remaining: number;+};++type OpenInvoiceOption = {+ id: string;+ invoiceId: string;+ exchangeRate: number;+ balance: number;+};++type AvailableCreditsTableProps = {+ paymentId: string;+ // Drives which invoice column the settlement targets.+ side: "sales" | "purchase";+ currency: string;+ credits: AvailableCredit[];+ openInvoices: OpenInvoiceOption[];+ // Credit applications already staged on this (Draft) payment — pre-fills the+ // table so a staged credit shows as selected instead of vanishing.+ staged?: { memoId: string; invoiceId: string; amount: number }[];+};++type CreditRow = {+ id: string;+ memoId: string;+ direction: string;+ remaining: number;+ checked: boolean;+ invoiceId: string; // target invoice id+ amount: number;+};++function round4(n: number): number {+ return Math.round(n * 10000) / 10000;+}++const GRID =+ "grid grid-cols-[2rem_minmax(8rem,1fr)_7rem_minmax(9rem,1fr)_8rem] gap-3";++const AvailableCreditsTable = ({+ paymentId,+ side,+ currency,+ credits,+ openInvoices,+ staged = []+}: AvailableCreditsTableProps) => {+ const { t } = useLingui();+ const permissions = usePermissions();+ const fetcher = useFetcher();+ const currencyFormatter = useCurrencyFormatter({ currency });+ const canEdit = permissions.can("update", "invoicing");++ const balanceByInvoice = useMemo(+ () => new Map(openInvoices.map((i) => [i.id, i.balance])),+ [openInvoices]+ );++ // staged is keyed by the memo's row id (== credit.id).+ const stagedByMemo = useMemo(+ () => new Map(staged.map((s) => [s.memoId, s])),+ [staged]+ );+ const seed = useMemo<CreditRow[]>(+ () =>+ credits.map((c) => {+ const s = stagedByMemo.get(c.id);+ return {+ id: c.id,+ memoId: c.memoId,+ direction: c.direction,+ remaining: c.remaining,+ checked: Boolean(s),+ invoiceId: s?.invoiceId ?? openInvoices[0]?.id ?? "",+ amount: s?.amount ?? 0+ };+ }),+ [credits, openInvoices, stagedByMemo]+ );++ const [rows, setRows] = useState<CreditRow[]>(seed);++ // The most a credit can apply to the chosen invoice: its remaining vs the+ // invoice's open balance.+ const capFor = useCallback(+ (remaining: number, invoiceId: string) =>+ round4(Math.min(remaining, Number(balanceByInvoice.get(invoiceId) ?? 0))),+ [balanceByInvoice]+ );++ const toggleRow = useCallback(+ (id: string, checked: boolean) =>+ setRows((prev) =>+ prev.map((r) => {+ if (r.id !== id) return r;+ if (checked) {+ return {+ ...r,+ checked: true,+ amount:+ r.amount === 0 ? capFor(r.remaining, r.invoiceId) : r.amount+ };+ }+ return { ...r, checked: false, amount: 0 };+ })+ ),+ [capFor]+ );++ const updateInvoice = useCallback(+ (id: string, invoiceId: string) =>+ setRows((prev) =>+ prev.map((r) =>+ r.id === id+ ? {+ ...r,+ invoiceId,+ amount: r.checked ? capFor(r.remaining, invoiceId) : r.amount+ }+ : r+ )+ ),+ [capFor]+ );++ const updateAmount = useCallback(+ (id: string, value: number) =>+ setRows((prev) =>+ prev.map((r) => {+ if (r.id !== id) return r;+ const amount = round4(Math.max(0, value));+ return { ...r, amount, checked: amount > 0 };+ })+ ),+ []+ );++ const totalApplied = useMemo(+ () => rows.reduce((sum, r) => (r.checked ? sum + r.amount : sum), 0),+ [rows]+ );++ const onSave = () => {+ const applications = rows+ .filter((r) => r.checked && r.amount > 0 && r.invoiceId)+ .map((r) => ({+ memoId: r.id,+ invoiceId: r.invoiceId,+ amount: r.amount+ }));++ const formData = new FormData();+ formData.set("applications", JSON.stringify(applications));+ fetcher.submit(formData, {+ method: "post",+ action: path.to.paymentCreditsSet(paymentId)+ });+ };++ const isSaving = fetcher.state !== "idle";++ if (credits.length === 0) return null;++ return (+ <Card className="w-full">+ <CardHeader>+ <CardTitle>+ <Trans>Apply available credits</Trans>+ </CardTitle>+ <CardDescription>+ <Trans>+ Clear this invoice with the party's posted credits as well as cash.+ Credits apply directly — no posting needed.+ </Trans>+ </CardDescription>+ </CardHeader>+ <CardContent>+ {openInvoices.length === 0 ? (+ <div className="rounded-xl border border-dashed border-border py-10 px-6 text-center">+ <p className="text-sm font-medium text-foreground">+ <Trans>No open invoices</Trans>+ </p>+ <p className="text-sm text-muted-foreground mt-1 text-pretty">+ <Trans>+ There's nothing outstanding to apply these credits to.+ </Trans>+ </p>+ </div>+ ) : (+ <div className="overflow-x-auto">+ <div className="min-w-[40rem]">+ <div+ className={cn(GRID, "px-2 pb-2 text-xs text-muted-foreground")}+ >+ <span aria-hidden />+ <span>+ <Trans>Credit</Trans>+ </span>+ <span className="text-right">+ <Trans>Remaining</Trans>+ </span>+ <span>+ <Trans>Apply to invoice</Trans>+ </span>+ <span className="text-right">+ <Trans>Amount</Trans>+ </span>+ </div>+ <div className="border-t border-border/70 divide-y divide-border/70">+ {rows.map((r) => (+ <div+ key={r.id}+ className={cn(+ GRID,+ "items-center px-2 py-2 transition-colors",+ r.checked ? "bg-muted/50" : "hover:bg-muted/30"+ )}+ >+ <div className="flex items-center justify-center">+ <Checkbox+ checked={r.checked}+ onCheckedChange={(checked) =>+ toggleRow(r.id, Boolean(checked))+ }+ disabled={!canEdit}+ />+ </div>+ <div className="min-w-0">+ <div className="font-medium text-foreground truncate">+ {r.memoId}+ </div>+ <div className="mt-0.5">+ <Enumerable value={r.direction} />+ </div>+ </div>+ <div className="text-right tabular-nums text-sm text-muted-foreground self-center">+ {currencyFormatter.format(Number(r.remaining))}+ </div>+ <Select+ value={r.invoiceId}+ onValueChange={(v) => updateInvoice(r.id, v)}+ >+ <SelectTrigger size="sm">+ <SelectValue placeholder={t`Select invoice`} />+ </SelectTrigger>+ <SelectContent>+ {openInvoices.map((inv) => (+ <SelectItem key={inv.id} value={inv.id}>+ {inv.invoiceId}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <NumberField+ aria-label={t`Amount to apply for ${r.memoId}`}+ value={r.amount}+ onChange={(v) =>+ updateAmount(r.id, Number.isNaN(v) ? 0 : v)+ }+ minValue={0}+ isDisabled={!canEdit}+ formatOptions={{+ minimumFractionDigits: 2,+ maximumFractionDigits: 4+ }}+ >+ <NumberInputGroup>+ <NumberInput className="text-right tabular-nums" />+ </NumberInputGroup>+ </NumberField>+ </div>+ ))}+ </div>+ </div>+ </div>+ )}+ </CardContent>+ {openInvoices.length > 0 ? (+ <CardFooterRow+ totalApplied={totalApplied}+ format={currencyFormatter.format}+ onSave={onSave}+ isSaving={isSaving}+ canEdit={canEdit}+ />+ ) : null}+ </Card>+ );+};++// Small footer so the Card import list stays tidy.+const CardFooterRow = ({+ totalApplied,+ format,+ onSave,+ isSaving,+ canEdit+}: {+ totalApplied: number;+ format: (n: number) => string;+ onSave: () => void;+ isSaving: boolean;+ canEdit: boolean;+}) => (+ <div className="flex items-center justify-between gap-4 px-6 pt-4 pb-6">+ <span className="text-sm text-muted-foreground">+ <Trans>Credits applied</Trans>{" "}+ <span className="tabular-nums font-medium text-foreground">+ {format(totalApplied)}+ </span>+ </span>+ <Button+ leftIcon={<LuSave />}+ onClick={onSave}+ isLoading={isSaving}+ isDisabled={!canEdit || totalApplied <= 0}+ >+ <Trans>Apply credits</Trans>+ </Button>+ </div>+);++export default AvailableCreditsTable;diff --git a/apps/erp/app/modules/invoicing/ui/Payment/InvoicePaymentsPanel.tsx b/apps/erp/app/modules/invoicing/ui/Payment/InvoicePaymentsPanel.tsxnew file mode 100644index 0000000000..5a9fe16d54--- /dev/null+++ b/apps/erp/app/modules/invoicing/ui/Payment/InvoicePaymentsPanel.tsx@@ -0,0 +1,123 @@+import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ Table,+ Tbody,+ Td,+ Th,+ Thead,+ Tr+} from "@carbon/react";+import { Trans } from "@lingui/react/macro";+import { Link } from "react-router";+import { Empty } from "~/components";+import { Enumerable } from "~/components/Enumerable";+import { useCurrencyFormatter, useDateFormatter } from "~/hooks";+import type { InvoiceSettlementForInvoice } from "~/modules/invoicing";+import { path } from "~/utils/path";++type InvoiceSettlementsPanelProps = {+ rows: InvoiceSettlementForInvoice[];+};++// Everything applied to the invoice — cash payments AND credit/debit memos —+// in one list. (Export name kept as InvoicePaymentsPanel for its callers.)+const InvoicePaymentsPanel = ({ rows }: InvoiceSettlementsPanelProps) => {+ const { formatDate } = useDateFormatter();+ // FX gain/loss is recorded in base currency.+ const currencyFormatter = useCurrencyFormatter();++ return (+ <Card>+ <CardHeader>+ <CardTitle>+ <Trans>Payments</Trans>+ </CardTitle>+ <CardDescription>+ <Trans>+ Payments and credits applied to this invoice. Click a row to open+ the source document.+ </Trans>+ </CardDescription>+ </CardHeader>+ <CardContent>+ {rows.length === 0 ? (+ <Empty />+ ) : (+ <Table>+ <Thead>+ <Tr>+ <Th>+ <Trans>Date</Trans>+ </Th>+ <Th>+ <Trans>Type</Trans>+ </Th>+ <Th>+ <Trans>Source</Trans>+ </Th>+ <Th className="text-right">+ <Trans>Applied</Trans>+ </Th>+ <Th className="text-right">+ <Trans>Discount</Trans>+ </Th>+ <Th className="text-right">+ <Trans>Write-Off</Trans>+ </Th>+ <Th className="text-right">+ <Trans>FX G/L</Trans>+ </Th>+ </Tr>+ </Thead>+ <Tbody>+ {rows.map((r) => (+ <Tr key={r.id}>+ <Td>{formatDate(r.appliedDate)}</Td>+ <Td>+ <Enumerable+ value={+ r.source.type === "payment"+ ? "Cash"+ : r.source.direction+ }+ />+ </Td>+ <Td>+ <Link+ to={+ r.source.type === "payment"+ ? path.to.payment(r.source.id)+ : path.to.memo(r.source.id)+ }+ className="text-primary hover:underline"+ >+ {r.source.readableId}+ </Link>+ </Td>+ <Td className="text-right tabular-nums">+ {currencyFormatter.format(Number(r.appliedAmount))}+ </Td>+ <Td className="text-right tabular-nums">+ {currencyFormatter.format(Number(r.discountAmount))}+ </Td>+ <Td className="text-right tabular-nums">+ {currencyFormatter.format(Number(r.writeOffAmount))}+ </Td>+ <Td className="text-right tabular-nums">+ {currencyFormatter.format(Number(r.fxGainLossAmount ?? 0))}+ </Td>+ </Tr>+ ))}+ </Tbody>+ </Table>+ )}+ </CardContent>+ </Card>+ );+};++export default InvoicePaymentsPanel;diff --git a/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplications.tsx b/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplications.tsxnew file mode 100644index 0000000000..fd5e51de0c--- /dev/null+++ b/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplications.tsx@@ -0,0 +1,189 @@+import {+ Card,+ CardContent,+ CardHeader,+ CardTitle,+ Table,+ Tbody,+ Td,+ Tfoot,+ Th,+ Thead,+ Tr+} from "@carbon/react";+import { Trans } from "@lingui/react/macro";+import { useNumberFormatter } from "@react-aria/i18n";+import { Hyperlink } from "~/components";+import { useCurrencyFormatter, useDateFormatter } from "~/hooks";+import type { getInvoiceSettlements } from "~/modules/invoicing";+import { path } from "~/utils/path";++type PaymentApplication = NonNullable<+ Awaited<ReturnType<typeof getInvoiceSettlements>>["data"]+>[number];++type PaymentApplicationsProps = {+ applications: PaymentApplication[];+ paymentTotal: number;+};++// The applied invoice's human-readable id comes from the embedded+// salesInvoice/purchaseInvoice relation (getInvoiceSettlements); fall back to+// the raw FK id if the relation didn't resolve.+function invoiceLabel(a: PaymentApplication) {+ const rec = a as unknown as {+ salesInvoice?:+ | { invoiceId?: string | null }+ | { invoiceId?: string | null }[]+ | null;+ purchaseInvoice?:+ | { invoiceId?: string | null }+ | { invoiceId?: string | null }[]+ | null;+ targetSalesInvoiceId?: string | null;+ targetPurchaseInvoiceId?: string | null;+ };+ const pick = (x: typeof rec.salesInvoice) =>+ Array.isArray(x) ? x[0]?.invoiceId : x?.invoiceId;+ return (+ pick(rec.salesInvoice) ??+ pick(rec.purchaseInvoice) ??+ rec.targetSalesInvoiceId ??+ rec.targetPurchaseInvoiceId+ );+}++const PaymentApplications = ({+ applications,+ paymentTotal+}: PaymentApplicationsProps) => {+ const { formatDate } = useDateFormatter();+ const currencyFormatter = useCurrencyFormatter();+ const rateFormatter = useNumberFormatter({+ minimumFractionDigits: 2,+ maximumFractionDigits: 4+ });++ const totalApplied = applications.reduce(+ (sum, a) =>+ sum ++ Number(a.appliedAmount) ++ Number(a.discountAmount) ++ Number(a.writeOffAmount),+ 0+ );+ const unapplied =+ paymentTotal -+ applications.reduce((s, a) => s + Number(a.appliedAmount), 0);++ return (+ <Card className="w-full">+ <CardHeader>+ <CardTitle>+ <Trans>Payment Applications</Trans>+ </CardTitle>+ </CardHeader>+ <CardContent>+ <Table>+ <Thead>+ <Tr>+ <Th>+ <Trans>Invoice</Trans>+ </Th>+ <Th className="text-right">+ <Trans>Applied</Trans>+ </Th>+ <Th className="text-right">+ <Trans>Discount</Trans>+ </Th>+ <Th className="text-right">+ <Trans>Write-Off</Trans>+ </Th>+ <Th className="text-right">+ <Trans>Inv Rate</Trans>+ </Th>+ <Th className="text-right">+ <Trans>Pay Rate</Trans>+ </Th>+ <Th className="text-right">+ <Trans>FX G/L</Trans>+ </Th>+ <Th>+ <Trans>Applied Date</Trans>+ </Th>+ </Tr>+ </Thead>+ <Tbody>+ {applications.length === 0 ? (+ <Tr>+ <Td colSpan={8} className="text-center text-muted-foreground">+ <Trans>No applications. Payment will be on-account.</Trans>+ </Td>+ </Tr>+ ) : (+ applications.map((a) => (+ <Tr key={a.id}>+ <Td>+ {a.targetSalesInvoiceId ? (+ <Hyperlink+ to={path.to.salesInvoice(a.targetSalesInvoiceId)}+ >+ {invoiceLabel(a)}+ </Hyperlink>+ ) : a.targetPurchaseInvoiceId ? (+ <Hyperlink+ to={path.to.purchaseInvoice(a.targetPurchaseInvoiceId)}+ >+ {invoiceLabel(a)}+ </Hyperlink>+ ) : (+ invoiceLabel(a)+ )}+ </Td>+ <Td className="text-right tabular-nums">+ {currencyFormatter.format(Number(a.appliedAmount))}+ </Td>+ <Td className="text-right tabular-nums">+ {currencyFormatter.format(Number(a.discountAmount))}+ </Td>+ <Td className="text-right tabular-nums">+ {currencyFormatter.format(Number(a.writeOffAmount))}+ </Td>+ <Td className="text-right tabular-nums">+ {rateFormatter.format(Number(a.targetExchangeRate))}+ </Td>+ <Td className="text-right tabular-nums">+ {rateFormatter.format(Number(a.sourceExchangeRate))}+ </Td>+ <Td className="text-right tabular-nums">+ {currencyFormatter.format(Number(a.fxGainLossAmount ?? 0))}+ </Td>+ <Td>{formatDate(a.appliedDate)}</Td>+ </Tr>+ ))+ )}+ </Tbody>+ {applications.length > 0 && (+ <Tfoot>+ <Tr>+ <Td className="text-right font-semibold">+ <Trans>Totals</Trans>+ </Td>+ <Td className="text-right tabular-nums font-semibold">+ {currencyFormatter.format(totalApplied)}+ </Td>+ <Td colSpan={5} />+ <Td className="text-right tabular-nums">+ <Trans>Unapplied:</Trans>{" "}+ {currencyFormatter.format(unapplied)}+ </Td>+ </Tr>+ </Tfoot>+ )}+ </Table>+ </CardContent>+ </Card>+ );+};++export default PaymentApplications;diff --git a/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.tsx b/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.tsxnew file mode 100644index 0000000000..b65533c9e3--- /dev/null+++ b/apps/erp/app/modules/invoicing/ui/Payment/PaymentApplyTable.tsx@@ -0,0 +1,492 @@+import {+ Button,+ Card,+ CardContent,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+ Checkbox,+ cn,+ HStack,+ NumberField,+ NumberInput,+ NumberInputGroup+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import type { CSSProperties } from "react";+import { useCallback, useMemo, useState } from "react";+import { LuListChecks, LuRotateCcw, LuSave } from "react-icons/lu";+import { useFetcher } from "react-router";+import {+ useCurrencyFormatter,+ useDateFormatter,+ usePermissions+} from "~/hooks";+import { path } from "~/utils/path";++// One row in the apply table — an open invoice for the payment's+// counterparty, plus the user's selection + entered amounts.+type OpenInvoice = {+ id: string;+ invoiceId: string;+ dateDue: string | null;+ currencyCode: string;+ exchangeRate: number;+ totalAmount: number;+ balance: number;+ status: string | null;+};++type ExistingApplication = {+ targetSalesInvoiceId: string | null;+ targetPurchaseInvoiceId: string | null;+ appliedAmount: number;+ discountAmount: number;+ writeOffAmount: number;+ targetExchangeRate: number;+ sourceExchangeRate: number;+ appliedDate: string;+};++// The invoice's read-only fields plus the editable selection state.+type ApplyRow = {+ id: string;+ invoiceId: string;+ dateDue: string | null;+ currencyCode: string;+ exchangeRate: number;+ balance: number;+ checked: boolean;+ appliedAmount: number;+ discountAmount: number;+ writeOffAmount: number;+};++type AmountField = "appliedAmount" | "discountAmount" | "writeOffAmount";++type PaymentApplyTableProps = {+ paymentId: string;+ paymentType: "Receipt" | "Disbursement";+ paymentCurrency: string;+ paymentTotal: number;+ paymentExchangeRate: number;+ // On-account credit (in payment currency) the counterparty can draw on when+ // applying more than this payment's cash. 0 when none is available.+ availableCredit: number;+ openInvoices: OpenInvoice[];+ existingApplications: ExistingApplication[];+};++function round4(n: number): number {+ return Math.round(n * 10000) / 10000;+}++// Shared grid template so the header labels stay aligned with the rows. Wide+// enough to scroll horizontally on small screens rather than cramp the inputs.+const GRID = "grid grid-cols-[2rem_minmax(9rem,1fr)_7rem_8rem_8rem_8rem] gap-3";++// Compact, right-aligned numeric input for the editable amount cells.+const AmountInput = ({+ value,+ onChange,+ isDisabled,+ label+}: {+ value: number;+ onChange: (value: number) => void;+ isDisabled: boolean;+ label: string;+}) => (+ <NumberField+ aria-label={label}+ value={value}+ onChange={(v) => onChange(Number.isNaN(v) ? 0 : v)}+ minValue={0}+ isDisabled={isDisabled}+ formatOptions={{ minimumFractionDigits: 2, maximumFractionDigits: 4 }}+ >+ <NumberInputGroup>+ <NumberInput className="text-right tabular-nums" />+ </NumberInputGroup>+ </NumberField>+);++const PaymentApplyTable = ({+ paymentId,+ paymentType,+ paymentCurrency,+ paymentTotal,+ paymentExchangeRate,+ availableCredit,+ openInvoices,+ existingApplications+}: PaymentApplyTableProps) => {+ const { t } = useLingui();+ const permissions = usePermissions();+ const fetcher = useFetcher();+ const currencyFormatter = useCurrencyFormatter({ currency: paymentCurrency });+ const { formatDate } = useDateFormatter();+ const today = new Date().toISOString().slice(0, 10);+ const isReceipt = paymentType === "Receipt";+ const canEdit = permissions.can("update", "invoicing");++ // Seed rows from existing applications so users see what's already+ // applied when they reopen a Draft payment.+ const seed = useMemo<ApplyRow[]>(() => {+ const byInvoice = new Map<string, ExistingApplication>();+ for (const a of existingApplications) {+ const id = isReceipt ? a.targetSalesInvoiceId : a.targetPurchaseInvoiceId;+ if (id) byInvoice.set(id, a);+ }+ return openInvoices.map((inv) => {+ const existing = byInvoice.get(inv.id);+ return {+ id: inv.id,+ invoiceId: inv.invoiceId,+ dateDue: inv.dateDue,+ currencyCode: inv.currencyCode,+ exchangeRate: inv.exchangeRate,+ balance: inv.balance,+ checked: Boolean(existing),+ appliedAmount: existing?.appliedAmount ?? 0,+ discountAmount: existing?.discountAmount ?? 0,+ writeOffAmount: existing?.writeOffAmount ?? 0+ };+ });+ }, [openInvoices, existingApplications, isReceipt]);++ const [rows, setRows] = useState<ApplyRow[]>(seed);++ const totalCash = useMemo(+ () => rows.reduce((sum, r) => (r.checked ? sum + r.appliedAmount : sum), 0),+ [rows]+ );+ // The most this payment can apply is its own cash plus the counterparty's+ // available on-account credit; applying beyond cash draws that credit down.+ const maxApplicable = paymentTotal + availableCredit;+ const unapplied = paymentTotal - totalCash;+ const creditDraw = Math.max(+ 0,+ Math.min(availableCredit, totalCash - paymentTotal)+ );+ const overApplied = totalCash > maxApplicable + 0.0001;+ const appliedPct =+ paymentTotal > 0+ ? Math.min(100, Math.max(0, (totalCash / paymentTotal) * 100))+ : 0;++ const toggleRow = useCallback(+ (id: string, checked: boolean) =>+ setRows((prev) =>+ prev.map((r) => {+ if (r.id !== id) return r;+ // Checking an empty row auto-fills the applied amount with the+ // open balance (capped at the payment total). Unchecking zeroes it.+ if (checked) {+ return {+ ...r,+ checked: true,+ appliedAmount:+ r.appliedAmount === 0+ ? round4(Math.min(r.balance, maxApplicable))+ : r.appliedAmount+ };+ }+ return {+ ...r,+ checked: false,+ appliedAmount: 0,+ discountAmount: 0,+ writeOffAmount: 0+ };+ })+ ),+ [maxApplicable]+ );++ // Entering any amount auto-checks the row so it's included on save (mirrors+ // the check-to-apply affordance).+ const updateAmount = useCallback(+ (id: string, field: AmountField, value: number) =>+ setRows((prev) =>+ prev.map((r) => {+ if (r.id !== id) return r;+ const next = { ...r, [field]: round4(Math.max(0, value)) };+ next.checked =+ next.appliedAmount + next.discountAmount + next.writeOffAmount > 0;+ return next;+ })+ ),+ []+ );++ const onAutoApply = useCallback(() => {+ // Distribute payment cash oldest-first (openInvoices is already sorted by+ // dateDue ascending from the loader).+ let remaining = paymentTotal;+ setRows((prev) =>+ prev.map((r) => {+ if (remaining <= 0) {+ return { ...r, checked: false, appliedAmount: 0 };+ }+ const take = Math.min(remaining, r.balance);+ remaining = round4(remaining - take);+ return { ...r, checked: true, appliedAmount: round4(take) };+ })+ );+ }, [paymentTotal]);++ const onClear = useCallback(+ () =>+ setRows((prev) =>+ prev.map((r) => ({+ ...r,+ checked: false,+ appliedAmount: 0,+ discountAmount: 0,+ writeOffAmount: 0+ }))+ ),+ []+ );++ const onSave = () => {+ const applications = rows+ .filter(+ (r) =>+ r.checked && r.appliedAmount + r.discountAmount + r.writeOffAmount > 0+ )+ .map((r) => ({+ targetSalesInvoiceId: isReceipt ? r.id : undefined,+ targetPurchaseInvoiceId: isReceipt ? undefined : r.id,+ appliedAmount: r.appliedAmount,+ discountAmount: r.discountAmount,+ writeOffAmount: r.writeOffAmount,+ targetExchangeRate: r.exchangeRate || 1,+ sourceExchangeRate: paymentExchangeRate || 1,+ appliedDate: today+ }));++ const formData = new FormData();+ formData.set("applications", JSON.stringify(applications));+ fetcher.submit(formData, {+ method: "post",+ action: path.to.paymentApplicationsSet(paymentId)+ });+ };++ const isSaving = fetcher.state !== "idle";++ return (+ <Card className="w-full">+ <CardHeader>+ <HStack className="justify-between w-full">+ <div>+ <CardTitle>+ <Trans>Apply to invoices</Trans>+ </CardTitle>+ <CardDescription>+ <Trans>+ Select the invoices this payment settles. Discount and write-off+ are in invoice currency.+ </Trans>+ </CardDescription>+ </div>+ <HStack>+ <Button+ size="sm"+ variant="secondary"+ leftIcon={<LuListChecks />}+ onClick={onAutoApply}+ isDisabled={!canEdit || openInvoices.length === 0}+ >+ <Trans>Auto apply</Trans>+ </Button>+ <Button+ size="sm"+ variant="secondary"+ leftIcon={<LuRotateCcw />}+ onClick={onClear}+ isDisabled={!canEdit}+ >+ <Trans>Clear</Trans>+ </Button>+ </HStack>+ </HStack>+ </CardHeader>+ <CardContent>+ {openInvoices.length === 0 ? (+ <div className="rounded-xl border border-dashed border-border py-10 px-6 text-center">+ <p className="text-sm font-medium text-foreground">+ <Trans>No open invoices</Trans>+ </p>+ <p className="text-sm text-muted-foreground mt-1 text-pretty">+ <Trans>+ This counterparty has nothing outstanding — the payment will be+ recorded on-account.+ </Trans>+ </p>+ </div>+ ) : (+ <div className="overflow-x-auto">+ <div className="min-w-[44rem]">+ <div+ className={cn(GRID, "px-2 pb-2 text-xs text-muted-foreground")}+ >+ <span aria-hidden />+ <span>+ <Trans>Invoice</Trans>+ </span>+ <span className="text-right">+ <Trans>Open</Trans>+ </span>+ <span className="text-right">+ <Trans>Applied</Trans>+ </span>+ <span className="text-right">+ <Trans>Discount</Trans>+ </span>+ <span className="text-right">+ <Trans>Write-off</Trans>+ </span>+ </div>+ <div className="border-t border-border/70 divide-y divide-border/70">+ {rows.map((r) => (+ <div+ key={r.id}+ className={cn(+ GRID,+ "items-center px-2 py-2 transition-colors",+ r.checked ? "bg-muted/50" : "hover:bg-muted/30"+ )}+ >+ <div className="flex items-center justify-center">+ <Checkbox+ checked={r.checked}+ onCheckedChange={(checked) =>+ toggleRow(r.id, Boolean(checked))+ }+ disabled={!canEdit}+ />+ </div>+ <div className="min-w-0">+ <div className="font-medium text-foreground truncate">+ {r.invoiceId}+ </div>+ <div className="text-xs text-muted-foreground">+ {r.dateDue ? formatDate(r.dateDue) : t`No due date`}+ {" · "}+ {r.currencyCode}+ </div>+ </div>+ <div className="text-right tabular-nums text-sm text-muted-foreground self-center">+ {currencyFormatter.format(Number(r.balance))}+ </div>+ <AmountInput+ label={t`Applied amount for ${r.invoiceId}`}+ value={r.appliedAmount}+ isDisabled={!canEdit}+ onChange={(v) => updateAmount(r.id, "appliedAmount", v)}+ />+ <AmountInput+ label={t`Discount for ${r.invoiceId}`}+ value={r.discountAmount}+ isDisabled={!canEdit}+ onChange={(v) => updateAmount(r.id, "discountAmount", v)}+ />+ <AmountInput+ label={t`Write-off for ${r.invoiceId}`}+ value={r.writeOffAmount}+ isDisabled={!canEdit}+ onChange={(v) => updateAmount(r.id, "writeOffAmount", v)}+ />+ </div>+ ))}+ </div>+ </div>+ </div>+ )}+ </CardContent>+ <CardFooter className="flex-col items-stretch gap-4">+ {openInvoices.length > 0 ? (+ <div className="w-full">+ <div className="flex items-baseline justify-between text-sm">+ <span className="text-muted-foreground">+ <Trans>Applied</Trans>+ </span>+ <span className="tabular-nums">+ <span+ className={cn(+ "font-semibold",+ overApplied ? "text-destructive" : "text-foreground"+ )}+ >+ {currencyFormatter.format(totalCash)}+ </span>+ <span className="text-muted-foreground">+ {" / "}+ {currencyFormatter.format(paymentTotal)}+ </span>+ </span>+ </div>+ <div className="mt-2 h-1.5 w-full overflow-hidden rounded-full bg-muted">+ <div+ className={cn(+ "h-full rounded-full w-(--applied) transition-[width] duration-300",+ overApplied ? "bg-destructive" : "bg-primary"+ )}+ style={{ "--applied": `${appliedPct}%` } as CSSProperties}+ />+ </div>+ {availableCredit > 0.0001 ? (+ <div className="mt-2 flex items-baseline justify-between text-xs text-muted-foreground">+ <span>+ <Trans>On-account credit available</Trans>+ </span>+ <span className="tabular-nums">+ {currencyFormatter.format(availableCredit)}+ </span>+ </div>+ ) : null}+ </div>+ ) : null}+ <HStack className="justify-between w-full">+ <span className="text-sm">+ {overApplied ? (+ <span className="font-semibold text-destructive">+ <Trans>Over-applied by</Trans>{" "}+ {currencyFormatter.format(totalCash - maxApplicable)}+ </span>+ ) : creditDraw > 0.0001 ? (+ <span className="text-muted-foreground">+ <Trans>Drawing</Trans>{" "}+ <span className="tabular-nums font-medium text-foreground">+ {currencyFormatter.format(creditDraw)}+ </span>{" "}+ <Trans>from on-account credit</Trans>+ </span>+ ) : (+ <span className="text-muted-foreground">+ <Trans>Unapplied</Trans>{" "}+ <span className="tabular-nums font-medium text-foreground">+ {currencyFormatter.format(unapplied)}+ </span>+ </span>+ )}+ </span>+ <Button+ leftIcon={<LuSave />}+ onClick={onSave}+ isLoading={isSaving}+ isDisabled={!canEdit || overApplied}+ >+ <Trans>Save applications</Trans>+ </Button>+ </HStack>+ </CardFooter>+ </Card>+ );+};++export default PaymentApplyTable;diff --git a/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.tsx b/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.tsxnew file mode 100644index 0000000000..c463874ff5--- /dev/null+++ b/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.tsx@@ -0,0 +1,284 @@+import { ValidatedForm } from "@carbon/form";+import {+ Button,+ Card,+ CardContent,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+ DropdownMenuIcon,+ DropdownMenuItem,+ useDisclosure,+ VStack+} from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import { useState } from "react";+import { LuCheckCheck, LuTicketX, LuTrash } from "react-icons/lu";+import { useFetcher } from "react-router";+import type { z } from "zod";+import { DocumentHeader } from "~/components";+import { Enumerable } from "~/components/Enumerable";+import {+ Account,+ Currency,+ Customer,+ CustomFormFields,+ DatePicker,+ Hidden,+ Input,+ Number,+ Select,+ SequenceOrCustomId,+ Submit,+ Supplier,+ TextArea+} from "~/components/Form";+import { ConfirmDelete } from "~/components/Modals";+import { usePermissions, useUser } from "~/hooks";+import {+ isPaymentLocked,+ paymentType,+ paymentValidator+} from "~/modules/invoicing";+import { path } from "~/utils/path";+import PaymentStatus from "./PaymentStatus";++// Builds the "new payment" URL pre-filled from an invoice. side "ar" seeds the+// customer (→ Receipt); "ap" seeds the supplier (→ Disbursement). Lives with the+// PaymentForm (the form on the page these links open) rather than in+// invoicing.models.ts, which must stay free of the `~/utils/path` import so the+// model unit tests don't pull in the Lingui-macro glossary via @carbon/auth.+export function getPayInvoiceHref(args: {+ side: "ar" | "ap";+ partyId: string | null | undefined;+ invoiceId: string;+ balance: number | null | undefined;+}): string {+ const partyParam = args.side === "ar" ? "customerId" : "supplierId";+ return `${path.to.paymentNew}?${partyParam}=${encodeURIComponent(+ args.partyId ?? ""+ )}&invoiceId=${encodeURIComponent(+ args.invoiceId+ )}&amount=${encodeURIComponent(String(args.balance ?? 0))}`;+}++// Builds the "apply credit" URL: a $0 receipt/payment for the party, so the+// settlement composer opens with no cash and the party's posted credits ready to+// apply. No invoiceId (that would seed a cash amount from the invoice balance).+export function getApplyCreditHref(args: {+ side: "ar" | "ap";+ partyId: string | null | undefined;+}): string {+ const partyParam = args.side === "ar" ? "customerId" : "supplierId";+ return `${path.to.paymentNew}?${partyParam}=${encodeURIComponent(+ args.partyId ?? ""+ )}&amount=0`;+}++type PaymentFormValues = z.infer<typeof paymentValidator>;++type PaymentFormProps = {+ initialValues: PaymentFormValues & { status?: string };+ // When set, a hidden field carries the seed invoice ids through to the+ // action, which auto-creates a starter application against each (re-fetching+ // their open balances server-side). Drives the workbench "pay N invoices"+ // hand-off as well as the single-invoice "Pay Invoice" link.+ seedInvoiceIds?: string[];+};++const PaymentForm = ({ initialValues, seedInvoiceIds }: PaymentFormProps) => {+ const { t } = useLingui();+ const { company } = useUser();+ const permissions = usePermissions();+ const post = useFetcher();+ const voidFetcher = useFetcher();+ const isEditing = Boolean(initialValues.id);+ const status = initialValues.status as+ | "Draft"+ | "Posted"+ | "Voided"+ | undefined;+ const isLocked = isPaymentLocked(initialValues.status);+ const canMutate = permissions.can("update", "invoicing");+ const canDelete = permissions.can("delete", "invoicing");+ const deleteModal = useDisclosure();++ // The counterparty selector visibility tracks paymentType so users+ // see Customer for Receipts and Supplier for Disbursements.+ const [currentType, setCurrentType] = useState<"Receipt" | "Disbursement">(+ initialValues.paymentType ?? "Receipt"+ );++ const typeOptions = paymentType.map((t) => ({+ label: t === "Receipt" ? "Payment from Customer" : "Payment to Supplier",+ value: t+ }));++ return (+ <>+ <ValidatedForm+ method="post"+ validator={paymentValidator}+ defaultValues={initialValues}+ isDisabled={isEditing && isLocked}+ className="w-full"+ >+ <Card>+ {isEditing ? (+ <DocumentHeader+ title={initialValues.paymentId ?? ""}+ status={+ <>+ <Enumerable value={initialValues.paymentType} />+ <PaymentStatus status={status} />+ </>+ }+ menuItems={+ status === "Draft" && canDelete ? (+ <DropdownMenuItem destructive onClick={deleteModal.onOpen}>+ <DropdownMenuIcon icon={<LuTrash />} />+ <Trans>Delete</Trans>+ </DropdownMenuItem>+ ) : undefined+ }+ actions={+ status === "Draft" ? (+ <Button+ leftIcon={<LuCheckCheck />}+ variant="primary"+ isLoading={post.state !== "idle"}+ isDisabled={!canMutate}+ onClick={() =>+ post.submit(null, {+ method: "post",+ action: path.to.paymentPost(initialValues.id!)+ })+ }+ >+ <Trans>Post</Trans>+ </Button>+ ) : status === "Posted" ? (+ <Button+ leftIcon={<LuTicketX />}+ variant="destructive"+ isLoading={voidFetcher.state !== "idle"}+ isDisabled={!canMutate}+ onClick={() =>+ voidFetcher.submit(null, {+ method: "post",+ action: path.to.paymentVoid(initialValues.id!)+ })+ }+ >+ <Trans>Void</Trans>+ </Button>+ ) : undefined+ }+ />+ ) : (+ <CardHeader>+ <CardTitle>+ <Trans>New Payment</Trans>+ </CardTitle>+ <CardDescription>+ <Trans>+ Record cash received from a customer (Receipt) or paid to a+ supplier (Disbursement). Applications to specific invoices are+ added after the payment is created.+ </Trans>+ </CardDescription>+ </CardHeader>+ )}+ <CardContent>+ <Hidden name="id" />+ {isEditing && <Hidden name="paymentId" />}+ {seedInvoiceIds && seedInvoiceIds.length > 0 && (+ <Hidden name="seedInvoiceIds" value={seedInvoiceIds.join(",")} />+ )}+ <VStack>+ <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 md:grid-cols-2">+ {!isEditing && (+ <SequenceOrCustomId+ name="paymentId"+ label={t`Payment ID`}+ table="payment"+ />+ )}+ <Select+ name="paymentType"+ label={t`Type`}+ options={typeOptions}+ onChange={(opt) => {+ if (+ opt?.value === "Receipt" ||+ opt?.value === "Disbursement"+ ) {+ setCurrentType(opt.value);+ }+ }}+ />+ {currentType === "Receipt" ? (+ <Customer name="customerId" label={t`Customer`} />+ ) : (+ <Supplier name="supplierId" label={t`Supplier`} />+ )}+ <DatePicker name="paymentDate" label={t`Payment Date`} />+ <Currency name="currencyCode" label={t`Currency`} />+ <Number+ name="exchangeRate"+ label={t`Exchange Rate`}+ formatOptions={{+ minimumFractionDigits: 2,+ maximumFractionDigits: 4+ }}+ />+ <Number+ name="totalAmount"+ label={t`Total Amount`}+ formatOptions={{+ style: "currency",+ currency: company?.baseCurrencyCode ?? "USD"+ }}+ />+ <Account+ name="bankAccount"+ label={t`Bank / Cash Account`}+ classes={["Asset"]}+ />+ <Input name="reference" label={t`Reference`} />+ <CustomFormFields table="payment" />+ </div>+ <div className="mt-4 w-full">+ <TextArea name="memo" label={t`Memo`} />+ </div>+ </VStack>+ </CardContent>+ <CardFooter>+ <Submit+ isDisabled={+ isEditing+ ? isLocked || !canMutate+ : !permissions.can("create", "invoicing")+ }+ >+ <Trans>Save</Trans>+ </Submit>+ </CardFooter>+ </Card>+ </ValidatedForm>+ {deleteModal.isOpen && (+ <ConfirmDelete+ action={path.to.paymentDelete(initialValues.id!)}+ isOpen={deleteModal.isOpen}+ name={initialValues.paymentId ?? ""}+ text={t`Are you sure you want to delete ${initialValues.paymentId}? This cannot be undone.`}+ onCancel={deleteModal.onClose}+ onSubmit={deleteModal.onClose}+ />+ )}+ </>+ );+};++export default PaymentForm;diff --git a/apps/erp/app/modules/invoicing/ui/Payment/PaymentStatus.tsx b/apps/erp/app/modules/invoicing/ui/Payment/PaymentStatus.tsxnew file mode 100644index 0000000000..bccccc0f1a--- /dev/null+++ b/apps/erp/app/modules/invoicing/ui/Payment/PaymentStatus.tsx@@ -0,0 +1,21 @@+import { Status } from "@carbon/react";+import type { paymentStatus } from "~/modules/invoicing";++type PaymentStatusProps = {+ status?: (typeof paymentStatus)[number] | null;+};++const PaymentStatus = ({ status }: PaymentStatusProps) => {+ switch (status) {+ case "Draft":+ return <Status color="gray">{status}</Status>;+ case "Posted":+ return <Status color="green">{status}</Status>;+ case "Voided":+ return <Status color="red">{status}</Status>;+ default:+ return null;+ }+};++export default PaymentStatus;diff --git a/apps/erp/app/modules/invoicing/ui/Payment/PaymentsTable.tsx b/apps/erp/app/modules/invoicing/ui/Payment/PaymentsTable.tsxnew file mode 100644index 0000000000..e7f8d803b4--- /dev/null+++ b/apps/erp/app/modules/invoicing/ui/Payment/PaymentsTable.tsx@@ -0,0 +1,234 @@+import type { Database } from "@carbon/database";+import { MenuIcon, MenuItem, useDisclosure } from "@carbon/react";+import { Trans, useLingui } from "@lingui/react/macro";+import type { ColumnDef } from "@tanstack/react-table";+import { memo, useCallback, useMemo, useState } from "react";+import {+ LuCalendar,+ LuCircleDot,+ LuCoins,+ LuEye,+ LuHash,+ LuPencil,+ LuTrash,+ LuUser+} from "react-icons/lu";+import { useNavigate } from "react-router";+import {+ CustomerAvatar,+ Hyperlink,+ New,+ SupplierAvatar,+ Table+} from "~/components";+import { Enumerable } from "~/components/Enumerable";+import { ConfirmDelete } from "~/components/Modals";+import {+ useCurrencyFormatter,+ useDateFormatter,+ usePermissions+} from "~/hooks";+import { useCustomers, useSuppliers } from "~/stores";+import { path } from "~/utils/path";+import { paymentStatus, paymentType } from "../../invoicing.models";+import PaymentStatus from "./PaymentStatus";++type PaymentRow = Database["public"]["Tables"]["payment"]["Row"];++type PaymentsTableProps = {+ data: PaymentRow[];+ count: number;+};++const PaymentsTable = memo(({ data, count }: PaymentsTableProps) => {+ const { t } = useLingui();+ const permissions = usePermissions();+ const navigate = useNavigate();+ const currencyFormatter = useCurrencyFormatter();+ const { formatDate } = useDateFormatter();+ const [customers] = useCustomers();+ const [suppliers] = useSuppliers();+ const deleteModal = useDisclosure();+ const [selectedPayment, setSelectedPayment] = useState<PaymentRow | null>(+ null+ );++ const renderContextMenu = useCallback(+ (row: PaymentRow) => (+ <>+ <MenuItem onClick={() => navigate(path.to.payment(row.id))}>+ <MenuIcon icon={row.status === "Draft" ? <LuPencil /> : <LuEye />} />+ {row.status === "Draft" ? (+ <Trans>Edit Payment</Trans>+ ) : (+ <Trans>View Payment</Trans>+ )}+ </MenuItem>+ <MenuItem+ destructive+ disabled={+ row.status !== "Draft" || !permissions.can("delete", "invoicing")+ }+ onClick={() => {+ setSelectedPayment(row);+ deleteModal.onOpen();+ }}+ >+ <MenuIcon icon={<LuTrash />} />+ <Trans>Delete Payment</Trans>+ </MenuItem>+ </>+ ),+ [navigate, permissions, deleteModal]+ );++ const columns = useMemo<ColumnDef<PaymentRow>[]>(+ () => [+ {+ accessorKey: "paymentId",+ header: t`Payment ID`,+ cell: ({ row }) => (+ <Hyperlink to={path.to.payment(row.original.id)}>+ {row.original.paymentId}+ </Hyperlink>+ ),+ meta: { icon: <LuHash /> }+ },+ {+ accessorKey: "paymentType",+ header: t`Type`,+ cell: ({ row }) => <Enumerable value={row.original.paymentType} />,+ meta: {+ icon: <LuCircleDot />,+ filter: {+ type: "static",+ options: paymentType.map((type) => ({+ value: type,+ label: <Enumerable value={type} />+ }))+ },+ pluralHeader: t`Types`+ }+ },+ {+ id: "counterparty",+ header: t`Counterparty`,+ cell: ({ row }) =>+ row.original.customerId ? (+ <CustomerAvatar customerId={row.original.customerId} />+ ) : row.original.supplierId ? (+ <SupplierAvatar supplierId={row.original.supplierId} />+ ) : null,+ meta: {+ icon: <LuUser />,+ filter: {+ type: "static",+ // Combined customer + supplier options; the loader maps the chosen+ // ids onto customerId OR supplierId.+ options: [+ ...(customers ?? []).map((c) => ({+ value: c.id,+ label: c.name+ })),+ ...(suppliers ?? []).map((s) => ({+ value: s.id,+ label: s.name+ }))+ ]+ },+ pluralHeader: t`Counterparties`+ }+ },+ {+ accessorKey: "paymentDate",+ header: t`Payment Date`,+ cell: (item) => formatDate(item.getValue<string>()),+ meta: { icon: <LuCalendar /> }+ },+ {+ accessorKey: "totalAmount",+ header: t`Total`,+ cell: (item) => (+ <span className="tabular-nums">+ {currencyFormatter.format(item.getValue<number>())}+ </span>+ ),+ meta: {+ icon: <LuCoins />,+ renderTotal: true,+ formatter: currencyFormatter.format+ }+ },+ {+ accessorKey: "currencyCode",+ header: t`Currency`,+ cell: ({ row }) => <Enumerable value={row.original.currencyCode} />+ },+ {+ accessorKey: "status",+ header: t`Status`,+ cell: ({ row }) => <PaymentStatus status={row.original.status} />,+ meta: {+ icon: <LuCircleDot />,+ filter: {+ type: "static",+ options: paymentStatus.map((status) => ({+ value: status,+ label: <PaymentStatus status={status} />+ }))+ },+ pluralHeader: t`Statuses`+ }+ },+ {+ accessorKey: "reference",+ header: t`Reference`,+ cell: ({ row }) => row.original.reference ?? null+ }+ ],+ [t, formatDate, currencyFormatter, customers, suppliers]+ );++ return (+ <>+ <Table<PaymentRow>+ count={count}+ columns={columns}+ data={data}+ defaultColumnPinning={{ left: ["paymentId"] }}+ defaultColumnVisibility={{+ reference: false+ }}+ primaryAction={+ permissions.can("create", "invoicing") && (+ <New label={t`Payment`} to={path.to.paymentNew} />+ )+ }+ renderContextMenu={renderContextMenu}+ title={t`Payments`}+ table="payment"+ withSavedView+ />+ {selectedPayment && (+ <ConfirmDelete+ action={path.to.paymentDelete(selectedPayment.id)}+ isOpen={deleteModal.isOpen}+ name={selectedPayment.paymentId}+ text={t`Are you sure you want to delete ${selectedPayment.paymentId}? This cannot be undone.`}+ onCancel={() => {+ deleteModal.onClose();+ setSelectedPayment(null);+ }}+ onSubmit={() => {+ deleteModal.onClose();+ setSelectedPayment(null);+ }}+ />+ )}+ </>+ );+});++PaymentsTable.displayName = "PaymentsTable";++export default PaymentsTable;diff --git a/apps/erp/app/modules/invoicing/ui/Payment/index.ts b/apps/erp/app/modules/invoicing/ui/Payment/index.tsnew file mode 100644index 0000000000..8867f4f041--- /dev/null+++ b/apps/erp/app/modules/invoicing/ui/Payment/index.ts@@ -0,0 +1,7 @@+export { default as AvailableCreditsTable } from "./AvailableCreditsTable";+export { default as InvoicePaymentsPanel } from "./InvoicePaymentsPanel";+export { default as PaymentApplications } from "./PaymentApplications";+export { default as PaymentApplyTable } from "./PaymentApplyTable";+export { default as PaymentForm } from "./PaymentForm";+export { default as PaymentStatus } from "./PaymentStatus";+export { default as PaymentsTable } from "./PaymentsTable";diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsxindex 8a792c19ce..94a35a0dba 100644--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx@@ -6,8 +6,6 @@ import {DropdownMenuContent,DropdownMenuIcon,DropdownMenuItem,- DropdownMenuRadioGroup,- DropdownMenuRadioItem,DropdownMenuSeparator,DropdownMenuTrigger,Heading,@@ -22,7 +20,6 @@ import { useEffect, useMemo, useState } from "react";import { flushSync } from "react-dom";import {LuCheckCheck,- LuChevronDown,LuEllipsisVertical,LuHandCoins,LuPanelLeft,@@ -31,7 +28,7 @@ import {LuTicketX,LuTrash} from "react-icons/lu";-import { Link, useFetcher, useParams } from "react-router";+import { Link, useParams } from "react-router";import { useAuditLog } from "~/components/AuditLog";import { usePanels } from "~/components/Layout/Panels";import ConfirmDelete from "~/components/Modals/ConfirmDelete";@@ -42,8 +39,8 @@ import {useUser} from "~/hooks";import type { PurchaseInvoice, PurchaseInvoiceLine } from "~/modules/invoicing";-import { PurchaseInvoicingStatus } from "~/modules/invoicing";-import type { action as statusAction } from "~/routes/x+/purchase-invoice+/$invoiceId.status";+import { isInvoicePayable, PurchaseInvoicingStatus } from "~/modules/invoicing";+import { getPayInvoiceHref } from "~/modules/invoicing/ui/Payment/PaymentForm";import { useItems } from "~/stores";import { useSuppliers } from "~/stores/suppliers";import { path } from "~/utils/path";@@ -68,8 +65,6 @@ const PurchaseInvoiceHeader = () => {variant: "dropdown"});- const statusFetcher = useFetcher<typeof statusAction>();-const { carbon } = useCarbon();const [linesNotAssociatedWithPO, setLinesNotAssociatedWithPO] = useState<{@@ -87,6 +82,7 @@ const PurchaseInvoiceHeader = () => {const routeData = useRouteData<{purchaseInvoice: PurchaseInvoice;purchaseInvoiceLines: PurchaseInvoiceLine[];+ orgHasCredits: boolean;}>(path.to.purchaseInvoice(invoiceId));const isSupplierApproved = useMemo(@@ -187,13 +183,17 @@ const PurchaseInvoiceHeader = () => {postingModal.onOpen();};- const handleStatusChange = (status: string) => {- statusFetcher.submit(- { status },- { method: "post", action: path.to.purchaseInvoiceStatus(invoiceId) }- );- };-+ // Status is derived from invoiceSettlement rows (migration+ // 20260519130000); manual mutation removed.+ const canMakePayment =+ isInvoicePayable(purchaseInvoice.status, purchaseInvoice.balance) &&+ permissions.can("create", "invoicing");+ const makePaymentHref = getPayInvoiceHref({+ side: "ap",+ partyId: purchaseInvoice.supplierId,+ invoiceId,+ balance: purchaseInvoice.balance+ });return (<><div className="flex flex-shrink-0 items-center justify-between p-2 bg-background border-b h-[50px] overflow-x-auto scrollbar-hide">@@ -340,52 +340,13 @@ const PurchaseInvoiceHeader = () => {<Trans>Post</Trans></Button>- {(() => {- const isPaymentDisabled =- purchaseInvoice.status === "Draft" ||- purchaseInvoice.status === "Pending" ||- isVoided ||- !permissions.can("update", "invoicing");-- if (isPaymentDisabled) {- return (- <Button- variant="secondary"- isDisabled- leftIcon={<LuHandCoins />}- rightIcon={<LuChevronDown />}- >- <Trans>Payment</Trans>- </Button>- );- }-- return (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button- variant="secondary"- leftIcon={<LuHandCoins />}- rightIcon={<LuChevronDown />}- >- <Trans>Payment</Trans>- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent>- <DropdownMenuRadioGroup- value={purchaseInvoice.status ?? "Draft"}- onValueChange={handleStatusChange}- >- {(["Paid", "Partially Paid"] as const).map((status) => (- <DropdownMenuRadioItem key={status} value={status}>- <PurchaseInvoicingStatus status={status} />- </DropdownMenuRadioItem>- ))}- </DropdownMenuRadioGroup>- </DropdownMenuContent>- </DropdownMenu>- );- })()}+ {canMakePayment && (+ <Button variant="primary" leftIcon={<LuHandCoins />} asChild>+ <Link to={makePaymentHref}>+ <Trans>Payment</Trans>+ </Link>+ </Button>+ )}<IconButtonaria-label={t`Toggle Properties`}diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicesTable.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicesTable.tsxindex e4c6c425f1..bea9ef4b79 100644--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicesTable.tsx+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicesTable.tsx@@ -160,6 +160,16 @@ const PurchaseInvoicesTable = memo(renderTotal: true}},+ {+ accessorKey: "balance",+ header: t`Balance`,+ cell: (item) => currencyFormatter.format(item.getValue<number>()),+ meta: {+ icon: <LuDollarSign />,+ formatter: currencyFormatter.format,+ renderTotal: true+ }+ },{id: "assignee",header: t`Assignee`,@@ -211,7 +221,7 @@ const PurchaseInvoicesTable = memo(},{accessorKey: "paymentTermName",- header: t`Payment Method`,+ header: t`Payment Terms`,cell: (item) => <Enumerable value={item.getValue<string>()} />,meta: {icon: <LuCreditCard />diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsxindex eb5775e87e..fe8672cfad 100644--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx@@ -6,8 +6,6 @@ import {DropdownMenuContent,DropdownMenuIcon,DropdownMenuItem,- DropdownMenuRadioGroup,- DropdownMenuRadioItem,DropdownMenuSeparator,DropdownMenuTrigger,Heading,@@ -40,9 +38,12 @@ import ConfirmDelete from "~/components/Modals/ConfirmDelete";import { usePermissions, useRouteData, useUser } from "~/hooks";import { ShipmentStatus } from "~/modules/inventory/ui/Shipments";import type { SalesInvoice, SalesInvoiceLine } from "~/modules/invoicing";-import { salesInvoiceStatusType } from "~/modules/invoicing";+import { isInvoicePayable } from "~/modules/invoicing";+import { getPayInvoiceHref } from "~/modules/invoicing/ui/Payment/PaymentForm";+// status mutation route still exists for the manual Draft -> Pending ->+// Submitted transitions, but the dropdown in this header no longer+// drives it.import type { action } from "~/routes/x+/sales-invoice+/$invoiceId.post";-import type { action as statusAction } from "~/routes/x+/sales-invoice+/$invoiceId.status";import { useItems } from "~/stores";import { path } from "~/utils/path";import SalesInvoicePostModal from "./SalesInvoicePostModal";@@ -66,7 +67,6 @@ const SalesInvoiceHeader = () => {});const postFetcher = useFetcher<typeof action>();- const statusFetcher = useFetcher<typeof statusAction>();const { carbon } = useCarbon();const [linesNotAssociatedWithSO, setLinesNotAssociatedWithSO] = useState<@@ -85,6 +85,7 @@ const SalesInvoiceHeader = () => {salesInvoice: SalesInvoice;salesInvoiceLines: SalesInvoiceLine[];defaultCc: string[];+ orgHasCredits: boolean;}>(path.to.salesInvoice(invoiceId));if (!routeData?.salesInvoice) throw new Error("salesInvoice not found");@@ -171,17 +172,20 @@ const SalesInvoiceHeader = () => {postingModal.onOpen();};- const handleStatusChange = (status: string) => {- statusFetcher.submit(- { status },- { method: "post", action: path.to.salesInvoiceStatus(invoiceId) }- );- };-- const IS_PAYMENT_DROPDOWN_DISABLED =- ["Voided", "Draft", "Pending"].includes(salesInvoice.status ?? "") ||- !permissions.can("update", "invoicing");-+ // Status is now derived from invoiceSettlement rows (see migration+ // 20260519130000); manual status mutation has been removed.+ // "Receive Payment" launches the payment form pre-filled for this+ // invoice — NetSuite's Accept Payment pattern. Hidden once the+ // invoice is fully settled, voided, or pre-posting.+ const canReceivePayment =+ isInvoicePayable(salesInvoice.status, salesInvoice.balance) &&+ permissions.can("create", "invoicing");+ const receivePaymentHref = getPayInvoiceHref({+ side: "ar",+ partyId: salesInvoice.customerId,+ invoiceId,+ balance: salesInvoice.balance+ });return (<><div className="flex flex-shrink-0 items-center justify-between p-2 bg-background border-b h-[50px] overflow-x-auto scrollbar-hide">@@ -353,38 +357,13 @@ const SalesInvoiceHeader = () => {><Trans>Post</Trans></Button>- <DropdownMenu>- <DropdownMenuTrigger- asChild- disabled={IS_PAYMENT_DROPDOWN_DISABLED}- >- <Button- variant="secondary"- isDisabled={IS_PAYMENT_DROPDOWN_DISABLED}- leftIcon={<LuDollarSign />}- rightIcon={<LuChevronDown />}- >+ {canReceivePayment && (+ <Button variant="primary" leftIcon={<LuDollarSign />} asChild>+ <Link to={receivePaymentHref}><Trans>Payment</Trans>- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent>- <DropdownMenuRadioGroup- value={salesInvoice.status ?? "Draft"}- onValueChange={handleStatusChange}- >- {salesInvoiceStatusType- .filter(- (status) =>- !["Draft", "Pending", "Voided"].includes(status)- )- .map((status) => (- <DropdownMenuRadioItem key={status} value={status}>- <SalesInvoiceStatus status={status} />- </DropdownMenuRadioItem>- ))}- </DropdownMenuRadioGroup>- </DropdownMenuContent>- </DropdownMenu>+ </Link>+ </Button>+ )}<IconButtonaria-label={t`Toggle Properties`}icon={<LuPanelRight />}diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsxindex bafea8848c..a9de58a314 100644--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsx+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsx@@ -154,6 +154,16 @@ const SalesInvoicesTable = memo(({ data, count }: SalesInvoicesTableProps) => {renderTotal: true}},+ {+ accessorKey: "balance",+ header: t`Balance`,+ cell: (item) => currencyFormatter.format(item.getValue<number>()),+ meta: {+ icon: <LuDollarSign />,+ formatter: currencyFormatter.format,+ renderTotal: true+ }+ },{id: "assignee",header: t`Assignee`,@@ -205,7 +215,7 @@ const SalesInvoicesTable = memo(({ data, count }: SalesInvoicesTableProps) => {},{accessorKey: "paymentTermName",- header: t`Payment Method`,+ header: t`Payment Terms`,cell: (item) => <Enumerable value={item.getValue<string>()} />,meta: {icon: <LuCreditCard />diff --git a/apps/erp/app/modules/invoicing/ui/Workbench/ARAPWorkbench.tsx b/apps/erp/app/modules/invoicing/ui/Workbench/ARAPWorkbench.tsxnew file mode 100644index 0000000000..6a33c0241c--- /dev/null+++ b/apps/erp/app/modules/invoicing/ui/Workbench/ARAPWorkbench.tsx@@ -0,0 +1,534 @@+import {+ Button,+ cn,+ DatePicker,+ HStack,+ Popover,+ PopoverContent,+ PopoverHeader,+ PopoverTrigger,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+ VStack+} from "@carbon/react";+import { parseDate } from "@internationalized/date";+import { Trans, useLingui } from "@lingui/react/macro";+import type { ColumnDef } from "@tanstack/react-table";+import { useCallback, useMemo, useState } from "react";+import {+ LuChevronDown,+ LuChevronRight,+ LuScale,+ LuTriangleAlert,+ LuUser+} from "react-icons/lu";+import { useFetcher, useNavigate } from "react-router";+import { CustomerAvatar, SupplierAvatar, Table } from "~/components";+import { Enumerable } from "~/components/Enumerable";+import { IndeterminateCheckbox } from "~/components/Table/components";+import {+ useCurrencyFormatter,+ useDateFormatter,+ usePermissions,+ useUrlParams+} from "~/hooks";+import { path } from "~/utils/path";++type TieOutResult = {+ subledgerBalance: number;+ glBalance: number;+ variance: number;+};++type AgingRow = {+ customerId?: string;+ supplierId?: string;+ paymentTerm?: string | null;+ current: number;+ bucket1: number;+ bucket2: number;+ bucket3: number;+ bucket4: number;+ unapplied: number;+ total: number;+};++type OpenInvoiceRow = {+ invoiceId: string;+ invoiceNumber: string;+ dateDue: string | null;+ currencyCode: string;+ exchangeRate: number;+ totalAmount: number;+ settled: number;+ openInCurrency: number;+ openInBase: number;+ customerId?: string;+ supplierId?: string;+};++type ARAPWorkbenchProps = {+ side: "ar" | "ap";+ result: TieOutResult | null;+ aging: AgingRow[];+ open: OpenInvoiceRow[];+ asOfDate: string;+ agingMethod: "dueDate" | "documentDate";+ bucketDays: [number, number, number];+};++// A counterparty (root) row carries the aging buckets; an invoice (child) row+// carries the open amount. One union type so a single ColumnDef set can render+// both, branching on `kind` — the heterogeneous-tree analogue of the+// StorageUnit tree-table.+type WorkbenchRow =+ | ({ kind: "counterparty"; id: string; partyId: string } & AgingRow)+ | ({ kind: "invoice"; id: string; partyId: string } & OpenInvoiceRow);++// Tolerance mirrors TieOut/Dashboard: swallow floating-point dust in the+// subledger-vs-GL comparison.+const VARIANCE_EPSILON = 0.005;++// Single workbench rendered by both the receivables and payables routes. The+// two routes differ only in which RPCs they call; the presentation is shared.+export function ARAPWorkbench({+ side,+ result,+ aging,+ open,+ asOfDate,+ agingMethod,+ bucketDays+}: ARAPWorkbenchProps) {+ const { t } = useLingui();+ const [, setParams] = useUrlParams();+ const navigate = useNavigate();+ const adjustFetcher = useFetcher();+ const permissions = usePermissions();+ const currencyFormatter = useCurrencyFormatter();+ const { formatDate } = useDateFormatter();+ const [b1, b2, b3] = bucketDays;++ const money = useCallback(+ (n: number) => currencyFormatter.format(Number(n)),+ [currencyFormatter]+ );+ const partyIdOf = useCallback(+ (r: { customerId?: string; supplierId?: string }) =>+ side === "ar" ? r.customerId : r.supplierId,+ [side]+ );++ // Group open invoices under their counterparty so expanding a row reveals+ // exactly the invoices that make up its balance. Pre-grouped from the loader+ // payload — no lazy fetch.+ const childrenByParty = useMemo(() => {+ const map: Record<string, OpenInvoiceRow[]> = {};+ for (const inv of open) {+ const pid = partyIdOf(inv);+ if (!pid) continue;+ (map[pid] ??= []).push(inv);+ }+ return map;+ }, [open, partyIdOf]);++ const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());+ const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());++ const toggleExpand = useCallback((id: string) => {+ setExpandedIds((prev) => {+ const next = new Set(prev);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });+ }, []);++ // Selecting a counterparty cascades to all its open invoices; selecting+ // individual invoices is also allowed. Only invoices are selectable — a+ // payment settles invoices, so the counterparty checkbox is purely a+ // select-all-its-children affordance.+ const toggleInvoice = useCallback((invoiceId: string) => {+ setSelectedIds((prev) => {+ const next = new Set(prev);+ if (next.has(invoiceId)) next.delete(invoiceId);+ else next.add(invoiceId);+ return next;+ });+ }, []);++ const toggleCounterparty = useCallback(+ (partyId: string) => {+ const kids = childrenByParty[partyId] ?? [];+ setSelectedIds((prev) => {+ const next = new Set(prev);+ const allSelected =+ kids.length > 0 && kids.every((k) => next.has(k.invoiceId));+ for (const k of kids) {+ if (allSelected) next.delete(k.invoiceId);+ else next.add(k.invoiceId);+ }+ return next;+ });+ },+ [childrenByParty]+ );++ // Flatten counterparties (roots) and, for expanded ones, their invoices.+ const displayRows = useMemo<WorkbenchRow[]>(() => {+ const out: WorkbenchRow[] = [];+ for (const a of aging) {+ const pid = partyIdOf(a);+ if (!pid) continue;+ out.push({ kind: "counterparty", id: pid, partyId: pid, ...a });+ if (expandedIds.has(pid)) {+ for (const inv of childrenByParty[pid] ?? []) {+ out.push({+ kind: "invoice",+ id: inv.invoiceId,+ partyId: pid,+ ...inv+ });+ }+ }+ }+ return out;+ }, [aging, childrenByParty, expandedIds, partyIdOf]);++ // The selected invoices, and whether they can become one payment. A payment+ // has one counterparty and one currency, so the action is enabled only when+ // the selection is homogeneous on both.+ const selectedInvoices = useMemo(+ () => open.filter((inv) => selectedIds.has(inv.invoiceId)),+ [open, selectedIds]+ );+ const selectedPartyIds = useMemo(+ () => new Set(selectedInvoices.map((inv) => partyIdOf(inv))),+ [selectedInvoices, partyIdOf]+ );+ const selectedCurrencies = useMemo(+ () => new Set(selectedInvoices.map((inv) => inv.currencyCode)),+ [selectedInvoices]+ );+ const sameParty = selectedPartyIds.size === 1;+ const sameCurrency = selectedCurrencies.size === 1;+ const canPay = selectedInvoices.length > 0 && sameParty && sameCurrency;++ const payHref = useMemo(() => {+ if (!canPay) return null;+ const pid = [...selectedPartyIds][0];+ if (!pid) return null;+ const params = new URLSearchParams();+ params.set(side === "ar" ? "customerId" : "supplierId", pid);+ for (const inv of selectedInvoices)+ params.append("invoiceId", inv.invoiceId);+ return `${path.to.paymentNew}?${params.toString()}`;+ }, [canPay, selectedPartyIds, selectedInvoices, side]);++ const columns = useMemo<ColumnDef<WorkbenchRow>[]>(() => {+ return [+ {+ id: "Select",+ size: 50,+ minSize: 1,+ header: () => null,+ cell: ({ row }) => {+ const r = row.original;+ if (r.kind === "counterparty") {+ const kids = childrenByParty[r.partyId] ?? [];+ if (kids.length === 0) return null;+ const checked = kids.every((k) => selectedIds.has(k.invoiceId));+ const indeterminate =+ !checked && kids.some((k) => selectedIds.has(k.invoiceId));+ return (+ <IndeterminateCheckbox+ checked={checked}+ indeterminate={indeterminate}+ onChange={() => toggleCounterparty(r.partyId)}+ />+ );+ }+ return (+ <IndeterminateCheckbox+ checked={selectedIds.has(r.invoiceId)}+ indeterminate={false}+ onChange={() => toggleInvoice(r.invoiceId)}+ />+ );+ }+ },+ {+ id: "counterparty",+ header: side === "ar" ? t`Customer` : t`Supplier`,+ cell: ({ row }) => {+ const r = row.original;+ if (r.kind === "counterparty") {+ const kids = childrenByParty[r.partyId] ?? [];+ const isExpanded = expandedIds.has(r.partyId);+ return (+ <div className="flex items-center">+ <div className="w-5 shrink-0 flex items-center justify-center self-center">+ {kids.length > 0 ? (+ <button+ type="button"+ aria-label={isExpanded ? t`Collapse` : t`Expand`}+ className="text-muted-foreground hover:text-foreground"+ onClick={(e) => {+ e.stopPropagation();+ toggleExpand(r.partyId);+ }}+ >+ {isExpanded ? (+ <LuChevronDown className="size-4" />+ ) : (+ <LuChevronRight className="size-4" />+ )}+ </button>+ ) : null}+ </div>+ {r.customerId ? (+ <CustomerAvatar customerId={r.customerId} />+ ) : r.supplierId ? (+ <SupplierAvatar supplierId={r.supplierId} />+ ) : null}+ </div>+ );+ }+ return (+ <div className="flex items-center">+ <div+ aria-hidden+ className="w-5 shrink-0 border-l border-border -my-2"+ />+ <div className="flex items-center gap-2 pl-2 py-1">+ <span className="text-foreground/90">{r.invoiceNumber}</span>+ <span className="text-xs text-muted-foreground">+ {r.dateDue ? formatDate(r.dateDue) : "—"}+ </span>+ </div>+ </div>+ );+ },+ meta: { icon: <LuUser /> }+ },+ {+ id: "paymentTerm",+ header: t`Payment Term`,+ cell: ({ row }) =>+ row.original.kind === "counterparty" ? (+ <Enumerable value={row.original.paymentTerm ?? null} />+ ) : null+ },+ // Aging buckets only carry a value on counterparty rows. They aren't+ // common to both union members, so they use `id` + `cell` (not+ // `accessorKey`) to stay valid against ColumnDef<WorkbenchRow>.+ ...(+ [+ ["current", t`Current`],+ ["bucket1", `1-${b1}`],+ ["bucket2", `${b1 + 1}-${b2}`],+ ["bucket3", `${b2 + 1}-${b3}`],+ ["bucket4", `${b3}+`],+ ["unapplied", t`Unapplied`]+ ] as const+ ).map(+ ([key, header]): ColumnDef<WorkbenchRow> => ({+ id: key,+ header,+ cell: ({ row }) =>+ row.original.kind === "counterparty" ? (+ <span className="tabular-nums">{money(row.original[key])}</span>+ ) : null+ })+ ),+ {+ id: "total",+ header: t`Total`,+ cell: ({ row }) => {+ const r = row.original;+ const value = r.kind === "counterparty" ? r.total : r.openInBase;+ return (+ <span+ className={cn(+ "tabular-nums",+ r.kind === "counterparty" && "font-semibold"+ )}+ >+ {money(value)}+ </span>+ );+ }+ }+ ];+ }, [+ t,+ side,+ b1,+ b2,+ b3,+ money,+ formatDate,+ childrenByParty,+ expandedIds,+ selectedIds,+ toggleExpand,+ toggleCounterparty,+ toggleInvoice+ ]);++ const hasVariance = result+ ? Math.abs(result.variance) > VARIANCE_EPSILON+ : false;+ const canAdjust = permissions.can("create", "accounting");++ const filters = (+ <HStack>+ {result ? (+ <Popover>+ <PopoverTrigger asChild>+ <Button+ variant={hasVariance ? "destructive" : "secondary"}+ leftIcon={hasVariance ? <LuTriangleAlert /> : <LuScale />}+ >+ <Trans>Tie-Out</Trans>+ </Button>+ </PopoverTrigger>+ <PopoverContent side="bottom" align="end" className="w-80">+ <PopoverHeader>+ <Trans>GL Tie-Out</Trans>+ </PopoverHeader>+ <div className="flex flex-col gap-3 p-4">+ <div className="flex items-center justify-between text-sm">+ <span className="text-muted-foreground">+ <Trans>Subledger</Trans>+ </span>+ <span className="tabular-nums">+ {money(result.subledgerBalance)}+ </span>+ </div>+ <div className="flex items-center justify-between text-sm">+ <span className="text-muted-foreground">+ <Trans>GL</Trans>+ </span>+ <span className="tabular-nums">{money(result.glBalance)}</span>+ </div>+ <div className="flex items-center justify-between text-sm border-t border-border pt-3">+ <span className="text-muted-foreground">+ <Trans>Variance</Trans>+ </span>+ <span+ className={cn(+ "tabular-nums font-semibold flex items-center gap-1",+ hasVariance+ ? "text-red-600 dark:text-red-400"+ : "text-emerald-600 dark:text-emerald-400"+ )}+ >+ {hasVariance ? (+ <LuTriangleAlert className="size-3.5" />+ ) : null}+ {money(result.variance)}+ </span>+ </div>+ {hasVariance && canAdjust ? (+ <adjustFetcher.Form+ method="post"+ action={+ side === "ar"+ ? path.to.receivablesAdjust+ : path.to.payablesAdjust+ }+ >+ <input type="hidden" name="asOfDate" value={asOfDate} />+ <Button+ type="submit"+ variant="secondary"+ className="w-full"+ isLoading={adjustFetcher.state !== "idle"}+ isDisabled={adjustFetcher.state !== "idle"}+ >+ <Trans>Create adjusting entry</Trans>+ </Button>+ </adjustFetcher.Form>+ ) : null}+ </div>+ </PopoverContent>+ </Popover>+ ) : null}+ {canPay && payHref ? (+ <Button variant="primary" onClick={() => navigate(payHref)}>+ {side === "ar" ? (+ <Trans>Receive Payment · {selectedInvoices.length} invoices</Trans>+ ) : (+ <Trans>Make Payment · {selectedInvoices.length} invoices</Trans>+ )}+ </Button>+ ) : selectedInvoices.length > 0 ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button variant="secondary" isDisabled>+ {side === "ar" ? (+ <Trans>Receive Payment</Trans>+ ) : (+ <Trans>Make Payment</Trans>+ )}+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ {!sameParty ? (+ <Trans>Select invoices from a single counterparty</Trans>+ ) : (+ <Trans>Select invoices in a single currency</Trans>+ )}+ </TooltipContent>+ </Tooltip>+ ) : null}+ <Select+ value={agingMethod}+ onValueChange={(value) => setParams({ agingMethod: value })}+ >+ <SelectTrigger className="w-[180px]">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="dueDate">+ <Trans>By Due Date</Trans>+ </SelectItem>+ <SelectItem value="documentDate">+ <Trans>By Document Date</Trans>+ </SelectItem>+ </SelectContent>+ </Select>+ <span className="text-sm text-muted-foreground whitespace-nowrap">+ <Trans>As of:</Trans>+ </span>+ <DatePicker+ value={parseDate(asOfDate)}+ onChange={(value) =>+ setParams({ asOfDate: value?.toString() ?? asOfDate })+ }+ />+ </HStack>+ );++ return (+ <VStack spacing={0} className="h-full">+ <div className="flex-1 w-full">+ <Table<WorkbenchRow>+ data={displayRows}+ columns={columns}+ count={displayRows.length}+ title={side === "ar" ? t`Receivables` : t`Payables`}+ primaryAction={filters}+ defaultColumnPinning={{ left: ["Select", "counterparty"] }}+ />+ </div>+ </VStack>+ );+}diff --git a/apps/erp/app/modules/invoicing/ui/Workbench/index.ts b/apps/erp/app/modules/invoicing/ui/Workbench/index.tsnew file mode 100644index 0000000000..a7953df6c8--- /dev/null+++ b/apps/erp/app/modules/invoicing/ui/Workbench/index.ts@@ -0,0 +1 @@+export { ARAPWorkbench } from "./ARAPWorkbench";diff --git a/apps/erp/app/modules/invoicing/ui/index.ts b/apps/erp/app/modules/invoicing/ui/index.tsindex 952b566efd..c0d7ccbe96 100644--- a/apps/erp/app/modules/invoicing/ui/index.ts+++ b/apps/erp/app/modules/invoicing/ui/index.ts@@ -1,5 +1,9 @@import useInvoicingSubmodules from "./useInvoicingSubmodules";+export * from "./Dashboard";+export * from "./Memo";+export * from "./Payment";export * from "./PurchaseInvoice";+export * from "./Workbench";export { useInvoicingSubmodules };diff --git a/apps/erp/app/modules/invoicing/ui/useInvoicingSubmodules.tsx b/apps/erp/app/modules/invoicing/ui/useInvoicingSubmodules.tsxindex 1fd6ef3d64..b0ae81fd68 100644--- a/apps/erp/app/modules/invoicing/ui/useInvoicingSubmodules.tsx+++ b/apps/erp/app/modules/invoicing/ui/useInvoicingSubmodules.tsx@@ -1,38 +1,86 @@import { useLingui } from "@lingui/react/macro";-import { BsCartDash } from "react-icons/bs";+import { LuBanknote, LuCreditCard, LuReceiptText } from "react-icons/lu";+import {+ BanknoteArrowDown,+ BanknoteArrowUp+} from "~/assets/icons/BanknoteArrows";import { usePermissions } from "~/hooks";+import { useSavedViews } from "~/hooks/useSavedViews";import type { AuthenticatedRouteGroup } from "~/types";import { path } from "~/utils/path";-const useInvoicingRoutes = (t: any): AuthenticatedRouteGroup[] => [- {- name: t`Manage`,- routes: [- {- name: t`Purchasing`,- to: path.to.purchaseInvoices,- role: "employee",- icon: <BsCartDash />- }- // {- // name: "Sales",- // to: path.to.salesInvoices,- // role: "employee",- // icon: <BsCartPlus />,- // },- ]- }-];-export default function useInvoicingSubmodules() {const { t } = useLingui();const permissions = usePermissions();+ const { addSavedViewsToRoutes } = useSavedViews();++ const invoicingRoutes: AuthenticatedRouteGroup[] = [+ {+ name: t`Accounts Payable`,+ routes: [+ {+ name: t`Payables`,+ to: path.to.payables,+ icon: <BanknoteArrowUp />,+ permission: "invoicing"+ },+ {+ name: t`Purchasing Invoices`,+ to: path.to.invoicingPurchasing,+ icon: <LuReceiptText />,+ table: "purchaseInvoice",+ permission: "invoicing"+ }+ ]+ },+ {+ name: t`Accounts Receivable`,+ routes: [+ {+ name: t`Receivables`,+ to: path.to.receivables,+ icon: <BanknoteArrowDown />,+ permission: "invoicing"+ },+ {+ name: t`Sales Invoices`,+ to: path.to.invoicingSales,+ icon: <LuCreditCard />,+ table: "salesInvoice",+ permission: "invoicing"+ }+ ]+ },++ {+ name: t`Payments`,+ routes: [+ {+ name: t`Payments`,+ to: path.to.payments,+ icon: <LuBanknote />,+ table: "payment",+ permission: "invoicing"+ },+ {+ name: t`Credits & Debits`,+ to: path.to.memos,+ icon: <LuCreditCard />,+ table: "memo",+ permission: "invoicing"+ }+ ]+ }+ ];+return {- groups: useInvoicingRoutes(t)+ groups: invoicingRoutes.filter((group) => {const filteredRoutes = group.routes.filter((route) => {if (route.role) {return permissions.is(route.role);+ } else if (route.permission) {+ return permissions.can("view", route.permission);} else {return true;}@@ -42,13 +90,17 @@ export default function useInvoicingSubmodules() {}).map((group) => ({...group,- routes: group.routes.filter((route) => {- if (route.role) {- return permissions.is(route.role);- } else {- return true;- }- })+ routes: group.routes+ .filter((route) => {+ if (route.role) {+ return permissions.is(route.role);+ } else if (route.permission) {+ return permissions.can("view", route.permission);+ } else {+ return true;+ }+ })+ .map(addSavedViewsToRoutes)}))};}diff --git a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsxindex fb8d1cd736..82bcc8827d 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx@@ -40,6 +40,7 @@ import { Trans, useLingui } from "@lingui/react/macro";import { useMemo, useState } from "react";import { flushSync } from "react-dom";import {+ LuBlocks,LuCheckCheck,LuChevronDown,LuCircleCheck,@@ -51,7 +52,6 @@ import {LuEllipsisVertical,LuList,LuLoaderCircle,- LuPackage,LuPanelLeft,LuPanelRight,LuQrCode,@@ -464,7 +464,7 @@ export default JobHeader;function getExplorerMenuIcon(type: string) {switch (type) {case "materials":- return <LuPackage />;+ return <LuBlocks />;case "operations":return <LuSettings />;case "dag":@@ -1129,7 +1129,7 @@ function JobCompleteModal({{hasLeftover && (<><Alert>- <LuPackage />+ <LuBlocks /><AlertTitle><Trans>Leftover Parts Detected</Trans></AlertTitle>diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsxindex eea7f37084..d60fdd54c7 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx@@ -32,12 +32,12 @@ import {import { Trans, useLingui } from "@lingui/react/macro";import { Fragment, useEffect, useState } from "react";import {+ LuBlocks,LuChevronRight,LuGitBranch,LuGitFork,LuGitMerge,LuSettings,- LuSquareStack,LuTriangleAlert} from "react-icons/lu";import { RiProgress4Line } from "react-icons/ri";@@ -331,7 +331,7 @@ const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {{isJobMethod && (<TabsList className="grid w-full grid-cols-2 mb-4"><TabsTrigger value="item">- <LuSquareStack className="mr-2" /> Item+ <LuBlocks className="mr-2" /> Item</TabsTrigger><TabsTrigger value="quote"><RiProgress4Line className="mr-2" />diff --git a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningOrderDrawer.tsx b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningOrderDrawer.tsxindex fe72d03c8a..9ad19622c3 100644--- a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningOrderDrawer.tsx+++ b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningOrderDrawer.tsx@@ -32,12 +32,12 @@ import { getLocalTimeZone, parseDate, today } from "@internationalized/date";import { Trans, useLingui } from "@lingui/react/macro";import { memo, useCallback, useEffect, useMemo } from "react";import {+ LuBlocks,LuCalendar,LuChevronDown,LuChevronUp,LuCirclePlay,LuExternalLink,- LuPackage,LuPlus,LuStar,LuTrash2@@ -377,7 +377,7 @@ export const ProductionPlanningOrderDrawer = memo(</Th><Th><div className="flex items-center gap-2 text-right">- <LuPackage />+ <LuBlocks /><span><Trans>Quantity</Trans></span>diff --git a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsxindex c2d7bab6b8..82cc689642 100644--- a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx+++ b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx@@ -27,11 +27,11 @@ import {useTransition} from "react";import {+ LuBlocks,LuBookMarked,LuBox,LuCircleCheck,LuCirclePlay,- LuPackage,LuSquareChartGantt} from "react-icons/lu";import { useFetcher } from "react-router";@@ -340,7 +340,7 @@ const ProductionPlanningTable = ({header: t`On Hand`,cell: ({ row }) => numberFormatter.format(row.original.quantityOnHand),meta: {- icon: <LuPackage />,+ icon: <LuBlocks />,renderTotal: true}},diff --git a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningOrderDrawer.tsx b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningOrderDrawer.tsxindex a3848c2e01..f7b3ed8a83 100644--- a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningOrderDrawer.tsx+++ b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningOrderDrawer.tsx@@ -37,6 +37,7 @@ import { getLocalTimeZone, parseDate, today } from "@internationalized/date";import { Trans, useLingui } from "@lingui/react/macro";import { memo, useCallback, useEffect, useState } from "react";import {+ LuBlocks,LuCalendar,LuChevronDown,LuChevronUp,@@ -44,7 +45,6 @@ import {LuCirclePlay,LuCirclePlus,LuExternalLink,- LuPackage,LuPlus,LuStar,LuTrash2@@ -674,7 +674,7 @@ export const PurchasingPlanningOrderDrawer = memo(</Th><Th><div className="flex items-center gap-2 text-right">- <LuPackage />+ <LuBlocks /><span><Trans>Purchase Qty</Trans></span>diff --git a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsxindex b6f6184452..6e2e541c06 100644--- a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx+++ b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx@@ -29,13 +29,13 @@ import {useTransition} from "react";import {+ LuBlocks,LuBookMarked,LuBox,LuCircleCheck,LuCirclePlay,LuClock,LuContainer,- LuPackage,LuSquareChartGantt} from "react-icons/lu";import { Link, useFetcher } from "react-router";@@ -473,7 +473,7 @@ const PlanningTable = memo(cell: ({ row }) =>numberFormatter.format(row.original.quantityOnHand),meta: {- icon: <LuPackage />,+ icon: <LuBlocks />,renderTotal: true}},diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsxindex 03537ca28c..b5362b2a86 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx@@ -249,7 +249,7 @@ const PurchaseOrdersTable = memo(},{accessorKey: "paymentTermId",- header: t`Payment Method`,+ header: t`Payment Terms`,cell: (item) => (<Enumerablevalue={diff --git a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierSidebar/useSupplierSidebar.tsx b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierSidebar/useSupplierSidebar.tsxindex dacad498d3..d808da66c5 100644--- a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierSidebar/useSupplierSidebar.tsx+++ b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierSidebar/useSupplierSidebar.tsx@@ -104,7 +104,7 @@ export function useSupplierSidebar({ contacts, locations }: Props) {},{name: t`Invoices`,- to: `${path.to.purchaseInvoices}?filter=supplierId:eq:${supplierId}`,+ to: `${path.to.invoicingPurchasing}?filter=supplierId:eq:${supplierId}`,icon: <LuCreditCard />}// {diff --git a/apps/erp/app/modules/purchasing/ui/usePurchasingSubmodules.tsx b/apps/erp/app/modules/purchasing/ui/usePurchasingSubmodules.tsxindex 697c261bf5..67858fc102 100644--- a/apps/erp/app/modules/purchasing/ui/usePurchasingSubmodules.tsx+++ b/apps/erp/app/modules/purchasing/ui/usePurchasingSubmodules.tsx@@ -1,7 +1,6 @@import { useLingui } from "@lingui/react/macro";import {LuContainer,- LuCreditCard,LuFileText,LuLayoutList,LuPackageSearch,@@ -45,13 +44,6 @@ export default function usePurchasingSubmodules() {to: path.to.purchaseOrders,icon: <LuLayoutList />,table: "purchaseOrder"- },- {- name: t`Invoices`,- to: path.to.purchaseInvoices,- icon: <LuCreditCard />,- table: "purchaseInvoice",- permission: "invoicing"}]},diff --git a/apps/erp/app/modules/quality/ui/Actions/ActionsTable.tsx b/apps/erp/app/modules/quality/ui/Actions/ActionsTable.tsxindex 0610a27d46..9c7106d99b 100644--- a/apps/erp/app/modules/quality/ui/Actions/ActionsTable.tsx+++ b/apps/erp/app/modules/quality/ui/Actions/ActionsTable.tsx@@ -3,13 +3,13 @@ import { Trans, useLingui } from "@lingui/react/macro";import type { ColumnDef } from "@tanstack/react-table";import { memo, useCallback, useMemo } from "react";import {+ LuBlocks,LuBookMarked,LuCalendar,LuCircleGauge,LuFileText,LuOctagonX,LuPencil,- LuSquareStack,LuUser} from "react-icons/lu";import { useNavigate } from "react-router";@@ -128,7 +128,7 @@ const ActionsTable = memo(</span>),meta: {- icon: <LuSquareStack />,+ icon: <LuBlocks />,filter: {type: "static",options: items.map((item) => ({diff --git a/apps/erp/app/modules/quality/ui/InboundInspections/InboundInspectionsTable.tsx b/apps/erp/app/modules/quality/ui/InboundInspections/InboundInspectionsTable.tsxindex 2a45e8df22..7111fb23da 100644--- a/apps/erp/app/modules/quality/ui/InboundInspections/InboundInspectionsTable.tsx+++ b/apps/erp/app/modules/quality/ui/InboundInspections/InboundInspectionsTable.tsx@@ -4,11 +4,11 @@ import { useLingui } from "@lingui/react/macro";import type { ColumnDef } from "@tanstack/react-table";import { memo, useMemo } from "react";import {+ LuBlocks,LuBookMarked,LuCalendar,LuClipboardCheck,LuHash,- LuPackage,LuTruck} from "react-icons/lu";import { EmployeeAvatar, Hyperlink, Table } from "~/components";@@ -116,7 +116,7 @@ const InboundInspectionsTable = memo({(row.original as any).lotSize ?? 0}</span>),- meta: { icon: <LuPackage /> }+ meta: { icon: <LuBlocks /> }},{accessorKey: "sampleSize",@@ -156,7 +156,7 @@ const InboundInspectionsTable = memo(cell: ({ row }) => (<EmployeeAvatar employeeId={row.original.createdBy} />),- meta: { icon: <LuPackage /> }+ meta: { icon: <LuBlocks /> }},{accessorKey: "createdAt",diff --git a/apps/erp/app/modules/quality/ui/Issue/IssuesTable.tsx b/apps/erp/app/modules/quality/ui/Issue/IssuesTable.tsxindex f92e8cc7b2..8947cdadd9 100644--- a/apps/erp/app/modules/quality/ui/Issue/IssuesTable.tsx+++ b/apps/erp/app/modules/quality/ui/Issue/IssuesTable.tsx@@ -4,6 +4,7 @@ import type { ColumnDef } from "@tanstack/react-table";import { memo, useCallback, useMemo, useState } from "react";import { flushSync } from "react-dom";import {+ LuBlocks,LuBookMarked,LuCalendar,LuChartNoAxesColumnIncreasing,@@ -13,7 +14,6 @@ import {LuOctagonX,LuPencil,LuShieldCheck,- LuSquareStack,LuTrash,LuUser} from "react-icons/lu";@@ -237,7 +237,7 @@ const IssuesTable = memo(({ data, types, count }: IssuesTableProps) => {</span>),meta: {- icon: <LuSquareStack />,+ icon: <LuBlocks />,filter: {type: "static",options: items.map((item) => ({diff --git a/apps/erp/app/modules/quality/ui/RiskRegister/RiskRegistersTable.tsx b/apps/erp/app/modules/quality/ui/RiskRegister/RiskRegistersTable.tsxindex 3adf39dcd2..87d55913fc 100644--- a/apps/erp/app/modules/quality/ui/RiskRegister/RiskRegistersTable.tsx+++ b/apps/erp/app/modules/quality/ui/RiskRegister/RiskRegistersTable.tsx@@ -4,11 +4,11 @@ import { useLingui } from "@lingui/react/macro";import type { ColumnDef } from "@tanstack/react-table";import { memo, useCallback, useMemo, useState } from "react";import {+ LuBlocks,LuDice5,LuDna,LuPencil,LuShapes,- LuSquareStack,LuStar,LuTrash,LuTriangleAlert,@@ -110,7 +110,7 @@ const RiskRegistersTable = memo(({ data, count }: RiskRegistersTableProps) => {header: t`Item`,cell: ({ row }) => getItemReadableId(items, row.original.itemId),meta: {- icon: <LuSquareStack />,+ icon: <LuBlocks />,filter: {type: "static",options: items.map((item) => ({diff --git a/apps/erp/app/modules/sales/ui/Customer/CustomerSidebar/useCustomerSidebar.tsx b/apps/erp/app/modules/sales/ui/Customer/CustomerSidebar/useCustomerSidebar.tsxindex a1276fdb69..a14884a9da 100644--- a/apps/erp/app/modules/sales/ui/Customer/CustomerSidebar/useCustomerSidebar.tsx+++ b/apps/erp/app/modules/sales/ui/Customer/CustomerSidebar/useCustomerSidebar.tsx@@ -98,7 +98,7 @@ export function useCustomerSidebar({ contacts, locations }: Props) {},{name: t`Invoices`,- to: `${path.to.salesInvoices}?filter=customerId:eq:${customerId}`,+ to: `${path.to.invoicingSales}?filter=customerId:eq:${customerId}`,icon: <LuCreditCard />}// {diff --git a/apps/erp/app/modules/sales/ui/Pricing/PricingRuleForm.tsx b/apps/erp/app/modules/sales/ui/Pricing/PricingRuleForm.tsxindex 9b384d4b72..9a8c5ed00a 100644--- a/apps/erp/app/modules/sales/ui/Pricing/PricingRuleForm.tsx+++ b/apps/erp/app/modules/sales/ui/Pricing/PricingRuleForm.tsx@@ -15,9 +15,9 @@ import {import { useLingui } from "@lingui/react/macro";import { useEffect, useState } from "react";import {+ LuBlocks,LuBoxes,LuLayers,- LuPackage,LuSquareUser,LuUsers,LuUsersRound@@ -225,7 +225,7 @@ const PricingRuleForm = ({ initialValues, onClose }: PricingRuleFormProps) => {value: "item",title: t`Specific Items`,description: t`Target one or more items.`,- icon: <LuPackage />+ icon: <LuBlocks />},{value: "group",diff --git a/apps/erp/app/modules/sales/ui/Pricing/PricingRulesTable.tsx b/apps/erp/app/modules/sales/ui/Pricing/PricingRulesTable.tsxindex 1c89ea4b43..86f8f35171 100644--- a/apps/erp/app/modules/sales/ui/Pricing/PricingRulesTable.tsx+++ b/apps/erp/app/modules/sales/ui/Pricing/PricingRulesTable.tsx@@ -13,10 +13,10 @@ import { memo, useCallback, useMemo } from "react";import {LuArrowDown,LuArrowUp,+ LuBlocks,LuBoxes,LuCalendar,LuCopy,- LuPackage,LuPencil,LuSquareUser,LuTag,@@ -209,7 +209,7 @@ const PricingRulesTable = memo(({ data, count }: PricingRulesTableProps) => {isArray: true},pluralHeader: t`Items`,- icon: <LuPackage />+ icon: <LuBlocks />}},{@@ -336,7 +336,7 @@ const PricingRulesTable = memo(({ data, count }: PricingRulesTableProps) => {);},meta: {- icon: <LuPackage />,+ icon: <LuBlocks />,exportValue: (row) => {const labels: string[] = [];if (row.itemPostingGroupId) {diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsxindex c2d10fd1ea..f021055e6d 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx@@ -32,12 +32,12 @@ import {import { Trans, useLingui } from "@lingui/react/macro";import { Fragment, useEffect, useState } from "react";import {+ LuBlocks,LuChevronRight,LuGitBranch,LuGitFork,LuGitMerge,LuSettings,- LuSquareStack,LuTriangleAlert} from "react-icons/lu";import { RiProgress4Line } from "react-icons/ri";@@ -319,7 +319,7 @@ const QuoteMakeMethodTools = () => {<Tabs defaultValue="item" className="w-full"><TabsList className="grid w-full grid-cols-2 mb-4"><TabsTrigger value="item">- <LuSquareStack className="mr-2" /> Item+ <LuBlocks className="mr-2" /> Item</TabsTrigger><TabsTrigger value="quote"><RiProgress4Line className="mr-2" />diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsxindex b069f2de4c..7a72de5212 100644--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx@@ -418,7 +418,7 @@ const SalesOrdersTable = memo(({ data, count }: SalesOrdersTableProps) => {},{accessorKey: "paymentTermId",- header: t`Payment Method`,+ header: t`Payment Terms`,cell: (item) => (<Enumerablevalue={diff --git a/apps/erp/app/modules/sales/ui/useSalesSubmodules.tsx b/apps/erp/app/modules/sales/ui/useSalesSubmodules.tsxindex 437c495b81..20f673e69d 100644--- a/apps/erp/app/modules/sales/ui/useSalesSubmodules.tsx+++ b/apps/erp/app/modules/sales/ui/useSalesSubmodules.tsx@@ -1,7 +1,6 @@import { useLingui } from "@lingui/react/macro";import {LuBan,- LuCreditCard,LuGlobe,LuList,LuPercent,@@ -51,13 +50,6 @@ export default function useSalesSubmodules() {icon: <RiProgress8Line />,table: "salesOrder"},- {- name: t`Invoices`,- to: path.to.salesInvoices,- icon: <LuCreditCard />,- permission: "invoicing",- table: "salesInvoice"- },{name: t`Portals`,to: path.to.customerPortals,diff --git a/apps/erp/app/modules/settings/ui/Printing/AssignmentsCard.tsx b/apps/erp/app/modules/settings/ui/Printing/AssignmentsCard.tsxindex 4bfb6b1b7f..a2b2897952 100644--- a/apps/erp/app/modules/settings/ui/Printing/AssignmentsCard.tsx+++ b/apps/erp/app/modules/settings/ui/Printing/AssignmentsCard.tsx@@ -19,9 +19,9 @@ import { Trans, useLingui } from "@lingui/react/macro";import type { ReactNode } from "react";import { useCallback, useEffect, useMemo } from "react";import {+ LuBlocks,LuHandCoins,LuMapPin,- LuPackage,LuTruck,LuWrench} from "react-icons/lu";@@ -209,7 +209,7 @@ function LocationSection({{context: "inventory",label: "Inventory",- icon: <LuPackage />,+ icon: <LuBlocks />,explicit: assignment?.inventory ?? null},...workCenters.map<AssignmentRowModel>((wc) => ({diff --git a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsxindex a848eab2df..126549d006 100644--- a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx+++ b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx@@ -1,6 +1,7 @@import { useLingui } from "@lingui/react/macro";import { useMemo } from "react";import {+ LuBlocks,LuBox,LuCircleCheck,LuClipboardCheck,@@ -18,7 +19,6 @@ import {LuPrinter,LuSheet,LuShoppingCart,- LuSquareStack,LuUsers,LuWebhook,LuWorkflow,@@ -112,7 +112,7 @@ export default function useSettingsSubmodules() {name: t`Items`,to: path.to.itemsSettings,role: "employee",- icon: <LuSquareStack />+ icon: <LuBlocks />},{name: t`People`,diff --git a/apps/erp/app/modules/storage-rules/ui/FieldCombobox.tsx b/apps/erp/app/modules/storage-rules/ui/FieldCombobox.tsxindex 32bd87d5fe..6c7880a85e 100644--- a/apps/erp/app/modules/storage-rules/ui/FieldCombobox.tsx+++ b/apps/erp/app/modules/storage-rules/ui/FieldCombobox.tsx@@ -26,11 +26,11 @@ import {import { useLingui } from "@lingui/react/macro";import { useMemo, useState } from "react";import {+ LuBlocks,LuBox,LuCheck,LuChevronDown,LuInfo,- LuPackage,LuReceipt} from "react-icons/lu";@@ -38,7 +38,7 @@ const CONTEXT: Record<FieldDef["context"],{ label: string; icon: JSX.Element }> = {- item: { label: "Item", icon: <LuPackage className="h-3.5 w-3.5" /> },+ item: { label: "Item", icon: <LuBlocks className="h-3.5 w-3.5" /> },storage: { label: "Storage unit", icon: <LuBox className="h-3.5 w-3.5" /> },workCenter: {label: "Work center",diff --git a/apps/erp/app/modules/storage-rules/ui/StorageRulesGroups.tsx b/apps/erp/app/modules/storage-rules/ui/StorageRulesGroups.tsxindex a18f8b4f50..9f0cc01632 100644--- a/apps/erp/app/modules/storage-rules/ui/StorageRulesGroups.tsx+++ b/apps/erp/app/modules/storage-rules/ui/StorageRulesGroups.tsx@@ -26,8 +26,8 @@ import {import type { TargetType, TransactionSurface } from "@carbon/utils";import { memo, useCallback, useMemo } from "react";import {+ LuBlocks,LuEllipsisVertical,- LuPackage,LuPencil,LuPlus,LuTrash@@ -174,7 +174,7 @@ const StorageRulesGroups = memo(({ rules }: StorageRulesGroupsProps) => {<RuleSectionCardtitle="Storage rules"description="Fire on receipts, shipments, transfers, inventory adjustments and bin moves (place/pick)."- icon={<LuPackage className="size-4 text-muted-foreground" />}+ icon={<LuBlocks className="size-4 text-muted-foreground" />}newRuleHref={`${path.to.newStorageRule}?targetType=item`}newRuleLabel="Storage Rule"canCreate={canCreate}diff --git a/apps/erp/app/modules/storage-rules/ui/SurfaceChips.tsx b/apps/erp/app/modules/storage-rules/ui/SurfaceChips.tsxindex 32754cbb63..35d42e7728 100644--- a/apps/erp/app/modules/storage-rules/ui/SurfaceChips.tsx+++ b/apps/erp/app/modules/storage-rules/ui/SurfaceChips.tsx@@ -7,7 +7,7 @@ import {} from "@carbon/utils";import {LuArrowRightLeft,- LuPackage,+ LuBlocks,LuScale,LuTruck,LuWarehouse@@ -18,7 +18,7 @@ const SURFACE_VISUALS: Record<{ label: string; icon: JSX.Element }> = {receipt: { label: "Receipts", icon: <LuTruck className="size-3.5" /> },- shipment: { label: "Shipments", icon: <LuPackage className="size-3.5" /> },+ shipment: { label: "Shipments", icon: <LuBlocks className="size-3.5" /> },stockTransfer: {label: "Stock transfers",icon: <LuArrowRightLeft className="size-3.5" />@@ -31,8 +31,8 @@ const SURFACE_VISUALS: Record<label: "Inventory adjustments",icon: <LuScale className="size-3.5" />},- place: { label: "Place", icon: <LuPackage className="size-3.5" /> },- pick: { label: "Pick", icon: <LuPackage className="size-3.5" /> },+ place: { label: "Place", icon: <LuBlocks className="size-3.5" /> },+ pick: { label: "Pick", icon: <LuBlocks className="size-3.5" /> },operationStart: {label: "Operation start",icon: <LuArrowRightLeft className="size-3.5" />diff --git a/apps/erp/app/modules/storage-rules/ui/SurfacesField.tsx b/apps/erp/app/modules/storage-rules/ui/SurfacesField.tsxindex 6e2000ba3e..795e0172e2 100644--- a/apps/erp/app/modules/storage-rules/ui/SurfacesField.tsx+++ b/apps/erp/app/modules/storage-rules/ui/SurfacesField.tsx@@ -15,7 +15,7 @@ import { useLingui } from "@lingui/react/macro";import { useEffect } from "react";import {LuArrowRightLeft,- LuPackage,+ LuBlocks,LuScale,LuTruck,LuWarehouse@@ -33,7 +33,7 @@ const SURFACE_META: Record<shipment: {title: "Shipments",description: "When goods leave a location",- icon: <LuPackage />+ icon: <LuBlocks />},stockTransfer: {title: "Stock transfers",@@ -53,12 +53,12 @@ const SURFACE_META: Record<place: {title: "Place",description: "When stock is placed into a storage unit",- icon: <LuPackage />+ icon: <LuBlocks />},pick: {title: "Pick",description: "When stock is taken from a storage unit",- icon: <LuPackage />+ icon: <LuBlocks />},operationStart: {title: "Operation start",diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex f78b516599..be281ae17b 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-06-29T10:40:00.802Z",- "totalTools": 1221,+ "generated": "2026-06-30T03:55:04.384Z",+ "totalTools": 1248,"modules": 15,"tools": [{@@ -314,7 +314,7 @@"module": "accounting","classification": "READ","description": "get financial statement balances",- "paramCount": 2,+ "paramCount": 3,"serviceParams": ["client","companyGroupId",@@ -338,6 +338,9 @@"string","null"]+ },+ "// Balance sheet only: append a computed \"Net Income\" equity line.\n includeCurrentYearEarnings": {+ "type": "boolean"}},"required": [@@ -976,7 +979,7 @@"module": "accounting","classification": "WRITE","description": "update default income accounts",- "paramCount": 21,+ "paramCount": 25,"serviceParams": ["client","defaultAccounts"@@ -1045,6 +1048,18 @@"customerPaymentDiscountAccount": {"type": "string"},+ "customerWriteOffAccount": {+ "type": "string"+ },+ "supplierWriteOffAccount": {+ "type": "string"+ },+ "realizedExchangeGainAccount": {+ "type": "string"+ },+ "realizedExchangeLossAccount": {+ "type": "string"+ },"roundingAccount": {"type": "string"},@@ -1072,6 +1087,10 @@"interestAccount","supplierPaymentDiscountAccount","customerPaymentDiscountAccount",+ "customerWriteOffAccount",+ "supplierWriteOffAccount",+ "realizedExchangeGainAccount",+ "realizedExchangeLossAccount","roundingAccount","deferredTaxExpenseAccountId"]@@ -8146,6 +8165,858 @@]}},+ {+ "name": "invoicing_getPayment",+ "module": "invoicing",+ "classification": "READ",+ "description": "get payment",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "id"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ]+ }+ },+ {+ "name": "invoicing_getPayments",+ "module": "invoicing",+ "classification": "READ",+ "description": "get payments",+ "paramCount": 8,+ "serviceParams": [+ "client",+ "companyId",+ "args"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "args": {+ "type": "object",+ "properties": {+ "limit": {+ "type": "integer",+ "default": 100+ },+ "offset": {+ "type": "integer",+ "default": 0+ },+ "search": {+ "type": [+ "string",+ "null"+ ]+ },+ "paymentType": {+ "type": [+ "string",+ "null"+ ],+ "enum": [+ "Receipt",+ "Disbursement"+ ]+ },+ "status": {},+ "customerId": {+ "type": [+ "string",+ "null"+ ]+ },+ "supplierId": {+ "type": [+ "string",+ "null"+ ]+ },+ "// Combined counterparty filter (customer OR supplier ids) from the table's\n // \"Counterparty\" filter, which sources options from both stores.\n counterpartyIds": {+ "type": [+ "array",+ "null"+ ],+ "items": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },+ {+ "name": "invoicing_getInvoiceSettlements",+ "module": "invoicing",+ "classification": "READ",+ "description": "get invoice settlements",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "companyId",+ "paymentId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "paymentId": {+ "type": "string"+ }+ },+ "required": [+ "paymentId"+ ]+ }+ },+ {+ "name": "invoicing_getInvoiceSettlementsForInvoice",+ "module": "invoicing",+ "classification": "READ",+ "description": "get invoice settlements for invoice",+ "paramCount": 2,+ "serviceParams": [+ "client",+ "companyId",+ "side",+ "invoiceId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "side": {+ "type": "string",+ "enum": [+ "sales",+ "purchase"+ ]+ },+ "invoiceId": {+ "type": "string"+ }+ },+ "required": [+ "side",+ "invoiceId"+ ]+ }+ },+ {+ "name": "invoicing_getMemoApplications",+ "module": "invoicing",+ "classification": "READ",+ "description": "get memo applications",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "memoId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "memoId": {+ "type": "string"+ }+ },+ "required": [+ "memoId"+ ]+ }+ },+ {+ "name": "invoicing_getOpenSalesInvoicesForCustomer",+ "module": "invoicing",+ "classification": "READ",+ "description": "get open sales invoices for customer",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "companyId",+ "customerId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "customerId": {+ "type": "string"+ }+ },+ "required": [+ "customerId"+ ]+ }+ },+ {+ "name": "invoicing_getOpenPurchaseInvoicesForSupplier",+ "module": "invoicing",+ "classification": "READ",+ "description": "get open purchase invoices for supplier",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "companyId",+ "supplierId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "supplierId": {+ "type": "string"+ }+ },+ "required": [+ "supplierId"+ ]+ }+ },+ {+ "name": "invoicing_getAvailableOnAccountCredit",+ "module": "invoicing",+ "classification": "READ",+ "description": "get available on account credit",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "companyId",+ "party"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "party": {}+ },+ "required": [+ "party"+ ]+ }+ },+ {+ "name": "invoicing_upsertPayment",+ "module": "invoicing",+ "classification": "WRITE",+ "description": "upsert payment",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "payment"+ ],+ "injectAuth": [+ "companyId",+ "createdBy",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "payment": {}+ },+ "required": [+ "payment"+ ]+ }+ },+ {+ "name": "invoicing_deletePayment",+ "module": "invoicing",+ "classification": "DESTRUCTIVE",+ "description": "delete payment",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "id"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ]+ }+ },+ {+ "name": "invoicing_upsertInvoiceSettlement",+ "module": "invoicing",+ "classification": "WRITE",+ "description": "upsert invoice settlement",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "app"+ ],+ "injectAuth": [+ "companyId",+ "createdBy",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "app": {}+ },+ "required": [+ "app"+ ]+ }+ },+ {+ "name": "invoicing_deleteInvoiceSettlement",+ "module": "invoicing",+ "classification": "DESTRUCTIVE",+ "description": "delete invoice settlement",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "id"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ]+ }+ },+ {+ "name": "invoicing_replaceInvoiceSettlements",+ "module": "invoicing",+ "classification": "WRITE",+ "description": "replace invoice settlements",+ "paramCount": 2,+ "serviceParams": [+ "db",+ "args"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "paymentId": {+ "type": "string"+ },+ "applications": {+ "type": "array",+ "items": {}+ }+ },+ "required": [+ "paymentId",+ "applications"+ ]+ }+ },+ {+ "name": "invoicing_getMemo",+ "module": "invoicing",+ "classification": "READ",+ "description": "get memo",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "id"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ]+ }+ },+ {+ "name": "invoicing_getMemos",+ "module": "invoicing",+ "classification": "READ",+ "description": "get memos",+ "paramCount": 6,+ "serviceParams": [+ "client",+ "companyId",+ "args"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "args": {+ "type": "object",+ "properties": {+ "limit": {+ "type": "integer",+ "default": 100+ },+ "offset": {+ "type": "integer",+ "default": 0+ },+ "search": {+ "type": [+ "string",+ "null"+ ]+ },+ "direction": {+ "type": [+ "string",+ "null"+ ],+ "enum": [+ "Credit",+ "Debit"+ ]+ },+ "status": {+ "type": [+ "string",+ "null"+ ],+ "enum": [+ "Draft",+ "Posted",+ "Voided"+ ]+ },+ "counterpartyIds": {+ "type": [+ "array",+ "null"+ ],+ "items": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },+ {+ "name": "invoicing_upsertMemo",+ "module": "invoicing",+ "classification": "WRITE",+ "description": "upsert memo",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "memo"+ ],+ "injectAuth": [+ "companyId",+ "createdBy",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "memo": {}+ },+ "required": [+ "memo"+ ]+ }+ },+ {+ "name": "invoicing_deleteMemo",+ "module": "invoicing",+ "classification": "DESTRUCTIVE",+ "description": "delete memo",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "id"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ]+ }+ },+ {+ "name": "invoicing_getAvailableCreditsForParty",+ "module": "invoicing",+ "classification": "READ",+ "description": "get available credits for party",+ "paramCount": 4,+ "serviceParams": [+ "client",+ "companyId",+ "party",+ "// When editing a Draft payment's composer",+ "that payment's own staged credits\n // should NOT count as used — they show as staged",+ "not consumed.\n excludePaymentId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "party": {},+ "// When editing a Draft payment's composer": {},+ "that payment's own staged credits\n // should NOT count as used — they show as staged": {},+ "not consumed.\n excludePaymentId": {+ "type": "string"+ }+ },+ "required": [+ "party",+ "// When editing a Draft payment's composer",+ "that payment's own staged credits\n // should NOT count as used — they show as staged"+ ]+ }+ },+ {+ "name": "invoicing_getCompanyHasOpenCredits",+ "module": "invoicing",+ "classification": "READ",+ "description": "get company has open credits",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "companyId",+ "side"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "side": {+ "type": "string",+ "enum": [+ "sales",+ "purchase"+ ]+ }+ },+ "required": [+ "side"+ ]+ }+ },+ {+ "name": "invoicing_getStagedCreditsForPayment",+ "module": "invoicing",+ "classification": "READ",+ "description": "get staged credits for payment",+ "paramCount": 2,+ "serviceParams": [+ "client",+ "paymentId",+ "side"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "paymentId": {+ "type": "string"+ },+ "side": {+ "type": "string",+ "enum": [+ "sales",+ "purchase"+ ]+ }+ },+ "required": [+ "paymentId",+ "side"+ ]+ }+ },+ {+ "name": "invoicing_applyCreditsToInvoices",+ "module": "invoicing",+ "classification": "WRITE",+ "description": "apply credits to invoices",+ "paramCount": 4,+ "serviceParams": [+ "db",+ "args"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "paymentId": {+ "type": "string"+ },+ "appliedDate": {+ "type": "string"+ },+ "side": {+ "type": "string",+ "enum": [+ "sales",+ "purchase"+ ]+ },+ "applications": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "memoId": {+ "type": "string"+ },+ "invoiceId": {+ "type": "string"+ },+ "amount": {+ "type": "number"+ }+ },+ "required": [+ "memoId",+ "invoiceId",+ "amount"+ ]+ }+ }+ },+ "required": [+ "paymentId",+ "appliedDate",+ "side",+ "applications"+ ]+ }+ },+ {+ "name": "invoicing_getArTieOut",+ "module": "invoicing",+ "classification": "READ",+ "description": "get ar tie out",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "companyId",+ "asOfDate"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "asOfDate": {+ "type": "string"+ }+ },+ "required": [+ "asOfDate"+ ]+ }+ },+ {+ "name": "invoicing_getApTieOut",+ "module": "invoicing",+ "classification": "READ",+ "description": "get ap tie out",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "companyId",+ "asOfDate"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "asOfDate": {+ "type": "string"+ }+ },+ "required": [+ "asOfDate"+ ]+ }+ },+ {+ "name": "invoicing_getArOpenByCustomer",+ "module": "invoicing",+ "classification": "READ",+ "description": "get ar open by customer",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "companyId",+ "asOfDate"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "asOfDate": {+ "type": "string"+ }+ },+ "required": [+ "asOfDate"+ ]+ }+ },+ {+ "name": "invoicing_getApOpenBySupplier",+ "module": "invoicing",+ "classification": "READ",+ "description": "get ap open by supplier",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "companyId",+ "asOfDate"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "asOfDate": {+ "type": "string"+ }+ },+ "required": [+ "asOfDate"+ ]+ }+ },+ {+ "name": "invoicing_getArAging",+ "module": "invoicing",+ "classification": "READ",+ "description": "get ar aging",+ "paramCount": 2,+ "serviceParams": [+ "client",+ "companyId",+ "asOfDate",+ "options"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "asOfDate": {+ "type": "string"+ },+ "options": {}+ },+ "required": [+ "asOfDate",+ "options"+ ]+ }+ },+ {+ "name": "invoicing_getApAging",+ "module": "invoicing",+ "classification": "READ",+ "description": "get ap aging",+ "paramCount": 2,+ "serviceParams": [+ "client",+ "companyId",+ "asOfDate",+ "options"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "asOfDate": {+ "type": "string"+ },+ "options": {}+ },+ "required": [+ "asOfDate",+ "options"+ ]+ }+ },{"name": "items_activateMethodVersion","module": "items",diff --git a/apps/erp/app/routes/x+/accounting+/balance-sheet.tsx b/apps/erp/app/routes/x+/accounting+/balance-sheet.tsxindex 1b2eae4383..0f2af33a94 100644--- a/apps/erp/app/routes/x+/accounting+/balance-sheet.tsx+++ b/apps/erp/app/routes/x+/accounting+/balance-sheet.tsx@@ -93,7 +93,7 @@ export async function loader({ request }: LoaderFunctionArgs) {client,companyGroupId,selectedCompanyId,- { startDate: null, endDate }+ { startDate: null, endDate, includeCurrentYearEarnings: true });if (balances.error) {diff --git a/apps/erp/app/routes/x+/credits+/$memoId.delete.tsx b/apps/erp/app/routes/x+/credits+/$memoId.delete.tsxnew file mode 100644index 0000000000..5510dfa91d--- /dev/null+++ b/apps/erp/app/routes/x+/credits+/$memoId.delete.tsx@@ -0,0 +1,38 @@+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 { deleteMemo } from "~/modules/invoicing";+import { path } from "~/utils/path";++// Action-only route — the delete confirmation modal (ConfirmDelete) posts here.+// The memo table's RLS DELETE policy restricts deletes to Draft memos, so a+// non-draft delete fails at the database; the UI also hides the action.+export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client } = await requirePermissions(request, {+ delete: "invoicing"+ });++ const { memoId } = params;+ if (!memoId) {+ throw redirect(+ path.to.memos,+ await flash(request, error(params, "Failed to get a memo id"))+ );+ }++ const remove = await deleteMemo(client, memoId);+ if (remove.error) {+ throw redirect(+ path.to.memo(memoId),+ await flash(request, error(remove.error, "Failed to delete memo"))+ );+ }++ throw redirect(+ path.to.memos,+ await flash(request, success("Successfully deleted memo"))+ );+}diff --git a/apps/erp/app/routes/x+/credits+/$memoId.post.tsx b/apps/erp/app/routes/x+/credits+/$memoId.post.tsxnew file mode 100644index 0000000000..1520308678--- /dev/null+++ b/apps/erp/app/routes/x+/credits+/$memoId.post.tsx@@ -0,0 +1,50 @@+import { assertIsPost, error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { flash } from "@carbon/auth/session.server";+import type { ActionFunctionArgs } from "react-router";+import { redirect } from "react-router";+import { path } from "~/utils/path";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { companyId, userId } = await requirePermissions(request, {+ update: "invoicing"+ });+ const { memoId } = params;+ if (!memoId) {+ return { success: false, message: "Missing memoId" };+ }++ const serviceRole = getCarbonServiceRole();+ try {+ const result = await serviceRole.functions.invoke("post-memo", {+ body: {+ type: "post",+ memoId,+ userId,+ companyId+ }+ });+ if (result.error) {+ const message =+ (result.data as { message?: string } | undefined)?.message ??+ result.error.message ??+ "Failed to post memo";+ throw redirect(+ path.to.memo(memoId),+ await flash(request, error(result.error, message))+ );+ }+ } catch (err) {+ throw redirect(+ path.to.memo(memoId),+ await flash(request, error(err, "Failed to post memo"))+ );+ }++ throw redirect(+ path.to.memo(memoId),+ await flash(request, success("Memo posted"))+ );+}diff --git a/apps/erp/app/routes/x+/credits+/$memoId.tsx b/apps/erp/app/routes/x+/credits+/$memoId.tsxnew file mode 100644index 0000000000..f4e37269bc--- /dev/null+++ b/apps/erp/app/routes/x+/credits+/$memoId.tsx@@ -0,0 +1,125 @@+import { assertIsPost, error, notFound, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { validationError, validator } from "@carbon/form";+import { VStack } from "@carbon/react";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { data, redirect, useLoaderData } from "react-router";+import {+ getMemo,+ getMemoApplications,+ MemoApplicationsPanel,+ MemoForm,+ memoValidator,+ upsertMemo+} from "~/modules/invoicing";+import { setCustomFields } from "~/utils/form";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const handle: Handle = {+ breadcrumb: "Credit / Debit Memos",+ to: path.to.memos+};++// A memo is just the credit/debit document — create it, then post it. Applying+// it to invoices happens on the payment/receipt screen (alongside cash), so the+// settlement UI lives in one place. The invoice's "Applied" panel shows where a+// posted credit ended up.+export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client } = await requirePermissions(request, {+ view: "invoicing"+ });+ const { memoId } = params;+ if (!memoId) throw notFound("Missing memoId");++ const memo = await getMemo(client, memoId);+ if (memo.error || !memo.data) {+ throw redirect(+ path.to.memos,+ await flash(request, error(memo.error, "Failed to load memo"))+ );+ }++ const applications = await getMemoApplications(client, memoId);++ return { memo: memo.data, applications: applications.data ?? [] };+}++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "invoicing"+ });+ const { memoId } = params;+ if (!memoId) throw notFound("Missing memoId");++ const formData = await request.formData();+ const validation = await validator(memoValidator).validate(formData);+ if (validation.error) {+ return validationError(validation.error);+ }++ // Only Draft memos are editable; Posted/Voided are immutable.+ const existing = await getMemo(client, memoId);+ if (existing.error || !existing.data) {+ throw redirect(+ path.to.memos,+ await flash(request, error(existing.error, "Failed to load memo"))+ );+ }+ if (existing.data.status !== "Draft") {+ throw redirect(+ path.to.memo(memoId),+ await flash(request, error(null, "Only draft memos can be edited"))+ );+ }++ const { id: _omitId, ...memoData } = validation.data;+ const update = await upsertMemo(client, {+ ...memoData,+ id: memoId,+ updatedBy: userId,+ customFields: setCustomFields(formData)+ });+ if (update.error) {+ return data(+ {},+ await flash(request, error(update.error, "Failed to update memo"))+ );+ }++ throw redirect(+ path.to.memo(memoId),+ await flash(request, success("Memo updated"))+ );+}++export default function MemoDetailRoute() {+ const { memo, applications } = useLoaderData<typeof loader>();++ const initialValues = {+ id: memo.id,+ memoId: memo.memoId,+ direction: memo.direction,+ customerId: memo.customerId ?? "",+ supplierId: memo.supplierId ?? "",+ memoDate: memo.memoDate,+ currencyCode: memo.currencyCode ?? "",+ exchangeRate: Number(memo.exchangeRate ?? 1),+ amount: Number(memo.amount ?? 0),+ reference: memo.reference ?? "",+ notes: memo.notes ?? "",+ status: memo.status ?? undefined+ };++ return (+ <VStack spacing={4} className="p-6 max-w-6xl w-full mx-auto">+ <MemoForm initialValues={initialValues} />+ <MemoApplicationsPanel+ rows={applications}+ currencyCode={memo.currencyCode ?? "USD"}+ />+ </VStack>+ );+}diff --git a/apps/erp/app/routes/x+/credits+/$memoId.void.tsx b/apps/erp/app/routes/x+/credits+/$memoId.void.tsxnew file mode 100644index 0000000000..1b8252160f--- /dev/null+++ b/apps/erp/app/routes/x+/credits+/$memoId.void.tsx@@ -0,0 +1,46 @@+import { assertIsPost, error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { flash } from "@carbon/auth/session.server";+import type { ActionFunctionArgs } from "react-router";+import { redirect } from "react-router";+import { path } from "~/utils/path";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { companyId, userId } = await requirePermissions(request, {+ update: "invoicing"+ });+ const { memoId } = params;+ if (!memoId) {+ return { success: false, message: "Missing memoId" };+ }++ const serviceRole = getCarbonServiceRole();+ try {+ const result = await serviceRole.functions.invoke("post-memo", {+ body: {+ type: "void",+ memoId,+ userId,+ companyId+ }+ });+ if (result.error) {+ throw redirect(+ path.to.memo(memoId),+ await flash(request, error(result.error, "Failed to void memo"))+ );+ }+ } catch (err) {+ throw redirect(+ path.to.memo(memoId),+ await flash(request, error(err, "Failed to void memo"))+ );+ }++ throw redirect(+ path.to.memo(memoId),+ await flash(request, success("Memo voided"))+ );+}diff --git a/apps/erp/app/routes/x+/credits+/_layout.tsx b/apps/erp/app/routes/x+/credits+/_layout.tsxnew file mode 100644index 0000000000..af35e8bd38--- /dev/null+++ b/apps/erp/app/routes/x+/credits+/_layout.tsx@@ -0,0 +1,18 @@+import type { MetaFunction } from "react-router";+import { Outlet } from "react-router";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const meta: MetaFunction = () => {+ return [{ title: "Carbon | Credit / Debit Memos" }];+};++export const handle: Handle = {+ breadcrumb: "Invoicing",+ to: path.to.invoicing,+ module: "invoicing"+};++export default function MemosRoute() {+ return <Outlet />;+}diff --git a/apps/erp/app/routes/x+/credits+/new.tsx b/apps/erp/app/routes/x+/credits+/new.tsxnew file mode 100644index 0000000000..f70e71afd8--- /dev/null+++ b/apps/erp/app/routes/x+/credits+/new.tsx@@ -0,0 +1,95 @@+import { assertIsPost, error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { validationError, validator } from "@carbon/form";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { redirect, useLoaderData } from "react-router";+import { MemoForm, memoValidator, upsertMemo } from "~/modules/invoicing";+import { getCompany, getNextSequence } from "~/modules/settings";+import { setCustomFields } from "~/utils/form";+import { path } from "~/utils/path";++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ create: "invoicing"+ });++ const company = await getCompany(client, companyId);+ const currencyCode = company.data?.baseCurrencyCode ?? "";++ return {+ initialValues: {+ memoId: "",+ direction: "Credit" as const,+ customerId: "",+ supplierId: "",+ memoDate: new Date().toISOString().slice(0, 10),+ currencyCode,+ exchangeRate: 1,+ amount: 0,+ reference: "",+ notes: ""+ }+ };+}++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ create: "invoicing"+ });++ const formData = await request.formData();+ const validation = await validator(memoValidator).validate(formData);+ if (validation.error) {+ return validationError(validation.error);+ }++ let memoId = validation.data.memoId;+ if (!memoId) {+ const next = await getNextSequence(+ client,+ validation.data.direction === "Credit" ? "creditMemo" : "debitMemo",+ companyId+ );+ if (next.error || !next.data) {+ throw redirect(+ path.to.memos,+ await flash(request, error(next.error, "Failed to allocate memo id"))+ );+ }+ memoId = next.data;+ }++ // The form posts a hidden `id` as "" which validates to null. The create+ // branch must omit it so the table's xid() default generates the id.+ const { id: _omitId, ...memoData } = validation.data;++ const insert = await upsertMemo(client, {+ ...memoData,+ memoId,+ companyId,+ createdBy: userId,+ customFields: setCustomFields(formData)+ });+ if (insert.error || !insert.data) {+ throw redirect(+ path.to.memos,+ await flash(request, error(insert.error, "Failed to create memo"))+ );+ }++ throw redirect(+ path.to.memo(insert.data.id),+ await flash(request, success("Memo created"))+ );+}++export default function NewMemoRoute() {+ const { initialValues } = useLoaderData<typeof loader>();+ return (+ <div className="max-w-4xl w-full p-2 sm:p-0 mx-auto mt-0 md:mt-8">+ <MemoForm initialValues={initialValues} />+ </div>+ );+}diff --git a/apps/erp/app/routes/x+/invoicing+/_index.tsx b/apps/erp/app/routes/x+/invoicing+/_index.tsxnew file mode 100644index 0000000000..dba6564bd5--- /dev/null+++ b/apps/erp/app/routes/x+/invoicing+/_index.tsx@@ -0,0 +1,108 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import type { LoaderFunctionArgs, MetaFunction } from "react-router";+import { useLoaderData } from "react-router";+import type { AgingTotals, RecentPayment } from "~/modules/invoicing";+import {+ getApAging,+ getApTieOut,+ getArAging,+ getArTieOut,+ getPayments,+ InvoicingDashboard+} from "~/modules/invoicing";+import { getGenericQueryFilters } from "~/utils/query";++export const meta: MetaFunction = () => {+ return [{ title: "Carbon | Invoicing" }];+};++// The four bucket boundaries the dashboard rolls aging into (Current, 1–30,+// 31–60, 61–90, 90+). Kept in sync with the aging report defaults.+const BUCKET_DAYS: [number, number, number] = [30, 60, 90];++type AgingRow = {+ current: number | null;+ bucket1: number | null;+ bucket2: number | null;+ bucket3: number | null;+ bucket4: number | null;+ unapplied: number | null;+ total: number | null;+};++function sumAging(rows: AgingRow[]): AgingTotals {+ const totals: AgingTotals = {+ current: 0,+ bucket1: 0,+ bucket2: 0,+ bucket3: 0,+ bucket4: 0,+ unapplied: 0,+ total: 0,+ count: 0+ };+ for (const r of rows) {+ totals.current += Number(r.current ?? 0);+ totals.bucket1 += Number(r.bucket1 ?? 0);+ totals.bucket2 += Number(r.bucket2 ?? 0);+ totals.bucket3 += Number(r.bucket3 ?? 0);+ totals.bucket4 += Number(r.bucket4 ?? 0);+ totals.unapplied += Number(r.unapplied ?? 0);+ totals.total += Number(r.total ?? 0);+ // Only count counterparties that actually carry an open balance.+ if (Number(r.total ?? 0) !== 0) totals.count += 1;+ }+ return totals;+}++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "invoicing"+ });++ const asOfDate = new Date().toISOString().slice(0, 10);+ const { sorts, filters } = getGenericQueryFilters(new URLSearchParams());++ const [arAging, apAging, arTieOut, apTieOut, payments] = await Promise.all([+ getArAging(client, companyId, asOfDate, { bucketDays: BUCKET_DAYS }),+ getApAging(client, companyId, asOfDate, { bucketDays: BUCKET_DAYS }),+ getArTieOut(client, companyId, asOfDate),+ getApTieOut(client, companyId, asOfDate),+ getPayments(client, companyId, {+ search: null,+ paymentType: null,+ status: null,+ customerId: null,+ supplierId: null,+ limit: 6,+ offset: 0,+ sorts,+ filters+ })+ ]);++ return {+ asOfDate,+ bucketDays: BUCKET_DAYS,+ ar: sumAging((arAging.data ?? []) as AgingRow[]),+ ap: sumAging((apAging.data ?? []) as AgingRow[]),+ arTieOut: arTieOut.data ?? null,+ apTieOut: apTieOut.data ?? null,+ recentPayments: (payments.data ?? []) as unknown as RecentPayment[]+ };+}++export default function InvoicingIndexRoute() {+ const data = useLoaderData<typeof loader>();+ return (+ <InvoicingDashboard+ asOfDate={data.asOfDate}+ bucketDays={data.bucketDays}+ ar={data.ar}+ ap={data.ap}+ arTieOut={data.arTieOut}+ apTieOut={data.apTieOut}+ recentPayments={data.recentPayments}+ />+ );+}diff --git a/apps/erp/app/routes/x+/invoicing+/_layout.tsx b/apps/erp/app/routes/x+/invoicing+/_layout.tsxnew file mode 100644index 0000000000..d4eee79cf4--- /dev/null+++ b/apps/erp/app/routes/x+/invoicing+/_layout.tsx@@ -0,0 +1,43 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import { VStack } from "@carbon/react";+import { msg } from "@lingui/core/macro";+import type { LoaderFunctionArgs, MetaFunction } from "react-router";+import { Outlet } from "react-router";+import { GroupedContentSidebar } from "~/components/Layout";+import { CollapsibleSidebarProvider } from "~/components/Layout/Navigation";+import useInvoicingSubmodules from "~/modules/invoicing/ui/useInvoicingSubmodules";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const meta: MetaFunction = () => {+ return [{ title: "Carbon | Invoicing" }];+};++export const handle: Handle = {+ breadcrumb: msg`Invoicing`,+ to: path.to.invoicing,+ module: "invoicing"+};++export async function loader({ request }: LoaderFunctionArgs) {+ await requirePermissions(request, {+ view: "invoicing"+ });++ return null;+}++export default function InvoicingRoute() {+ const { groups } = useInvoicingSubmodules();++ return (+ <CollapsibleSidebarProvider>+ <div className="grid grid-cols-[auto_1fr] w-full h-full">+ <GroupedContentSidebar groups={groups} />+ <VStack spacing={0} className="h-full">+ <Outlet />+ </VStack>+ </div>+ </CollapsibleSidebarProvider>+ );+}diff --git a/apps/erp/app/routes/x+/invoicing+/credits.tsx b/apps/erp/app/routes/x+/invoicing+/credits.tsxnew file mode 100644index 0000000000..acff346283--- /dev/null+++ b/apps/erp/app/routes/x+/invoicing+/credits.tsx@@ -0,0 +1,75 @@+import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { LoaderFunctionArgs } from "react-router";+import { redirect, useLoaderData } from "react-router";+import { getMemos, MemosTable } from "~/modules/invoicing";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";+import { getGenericQueryFilters } from "~/utils/query";++export const handle: Handle = {+ breadcrumb: "Credit / Debit Memos",+ to: path.to.memos,+ module: "invoicing"+};++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "invoicing"+ });++ const url = new URL(request.url);+ const searchParams = url.searchParams;+ const search = searchParams.get("search");+ const direction = searchParams.get("direction") as "Credit" | "Debit" | null;+ const status = searchParams.get("status") as+ | "Draft"+ | "Posted"+ | "Voided"+ | null;++ const {+ limit,+ offset,+ sorts,+ filters = []+ } = getGenericQueryFilters(searchParams);++ // The "Counterparty" column filter spans two columns (customerId OR+ // supplierId), so pull it out of the generic filters and hand it to getMemos,+ // which applies it as an OR. The rest pass through normally.+ const counterpartyIds = filters+ .filter((f) => f.column === "counterparty")+ .flatMap((f) => (f.value ?? "").split(","))+ .filter(Boolean);+ const passThroughFilters = filters.filter((f) => f.column !== "counterparty");++ const memos = await getMemos(client, companyId, {+ search,+ direction,+ status,+ counterpartyIds: counterpartyIds.length > 0 ? counterpartyIds : null,+ limit,+ offset,+ sorts,+ filters: passThroughFilters+ });++ if (memos.error) {+ throw redirect(+ path.to.invoicing,+ await flash(request, error(memos.error, "Failed to fetch memos"))+ );+ }++ return {+ count: memos.count ?? 0,+ memos: memos.data ?? []+ };+}++export default function MemosRoute() {+ const { count, memos } = useLoaderData<typeof loader>();+ return <MemosTable data={memos} count={count} />;+}diff --git a/apps/erp/app/routes/x+/invoicing+/payables.adjust.tsx b/apps/erp/app/routes/x+/invoicing+/payables.adjust.tsxnew file mode 100644index 0000000000..c0f63b9ee6--- /dev/null+++ b/apps/erp/app/routes/x+/invoicing+/payables.adjust.tsx@@ -0,0 +1,105 @@+import { assertIsPost, error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { flash } from "@carbon/auth/session.server";+import { FunctionRegion } from "@supabase/supabase-js";+import type { ActionFunctionArgs } from "react-router";+import { redirect } from "react-router";+import {+ getDefaultAccounts,+ saveJournalEntryWithLines+} from "~/modules/accounting";+import { getApTieOut } from "~/modules/invoicing";+import { path } from "~/utils/path";++// Turns a non-zero AP tie-out variance into a balanced Draft journal entry — the+// payables control account against the rounding account — then drops the user on+// the journal-entry editor to review and post. The variance is recomputed+// server-side (not trusted from the form) so the seeded lines always match the+// current books.+export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, companyGroupId, userId } =+ await requirePermissions(request, { create: "accounting" });++ const formData = await request.formData();+ const asOfDate =+ (formData.get("asOfDate") as string | null) ??+ new Date().toISOString().slice(0, 10);++ const [tieOut, defaults] = await Promise.all([+ getApTieOut(client, companyId, asOfDate),+ getDefaultAccounts(client, companyId)+ ]);++ const variance = Number(tieOut.data?.variance ?? 0);+ const payablesAccount = defaults.data?.payablesAccount;+ const offsetAccount = defaults.data?.roundingAccount;++ if (!payablesAccount || !offsetAccount || variance === 0) {+ throw redirect(+ path.to.payables,+ await flash(request, error(null, "No payables variance to adjust"))+ );+ }++ const serviceRole = getCarbonServiceRole();+ const journalEntry = await serviceRole.functions.invoke<{ id: string }>(+ "create",+ {+ body: { type: "journalEntry", companyId, userId },+ region: FunctionRegion.UsEast1+ }+ );++ if (!journalEntry.data || journalEntry.error) {+ throw redirect(+ path.to.payables,+ await flash(+ request,+ error(journalEntry.error, "Failed to create adjusting entry")+ )+ );+ }++ const journalId = String(journalEntry.data.id);+ const description = `AP tie-out adjustment as of ${asOfDate}`;++ // Payables is a liability: subledger > GL (variance > 0) means the liability+ // is understated in the GL — credit payables to raise it; otherwise debit.+ // The offsetting half lands in the rounding account so the entry is balanced.+ const saved = await saveJournalEntryWithLines(client, {+ journalEntryId: journalId,+ postingDate: asOfDate,+ description,+ updatedBy: userId,+ companyId,+ companyGroupId,+ lines: [+ {+ accountId: payablesAccount,+ description,+ debit: variance < 0 ? -variance : 0,+ credit: variance > 0 ? variance : 0+ },+ {+ accountId: offsetAccount,+ description,+ debit: variance > 0 ? variance : 0,+ credit: variance < 0 ? -variance : 0+ }+ ]+ });++ if (saved.error) {+ throw redirect(+ path.to.journalEntryDetails(journalId),+ await flash(+ request,+ error(saved.error, "Entry created, but seeding the lines failed")+ )+ );+ }++ throw redirect(path.to.journalEntryDetails(journalId));+}diff --git a/apps/erp/app/routes/x+/invoicing+/payables.tsx b/apps/erp/app/routes/x+/invoicing+/payables.tsxnew file mode 100644index 0000000000..b545a4acfd--- /dev/null+++ b/apps/erp/app/routes/x+/invoicing+/payables.tsx@@ -0,0 +1,75 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import type { LoaderFunctionArgs } from "react-router";+import { useLoaderData } from "react-router";+import {+ ARAPWorkbench,+ getApAging,+ getApOpenBySupplier,+ getApTieOut+} from "~/modules/invoicing";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const handle: Handle = {+ breadcrumb: "Payables",+ to: path.to.payables,+ module: "invoicing"+};++function parseBuckets(raw: string | null): [number, number, number] {+ const parts = (raw ?? "").split(",").map((n) => Number.parseInt(n, 10));+ if (parts.length === 3 && parts.every((n) => Number.isFinite(n) && n > 0)) {+ return [parts[0], parts[1], parts[2]];+ }+ return [30, 60, 90];+}++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "invoicing"+ });++ const url = new URL(request.url);+ const asOfDate =+ url.searchParams.get("asOfDate") ?? new Date().toISOString().slice(0, 10);+ const agingMethod: "dueDate" | "documentDate" =+ url.searchParams.get("agingMethod") === "documentDate"+ ? "documentDate"+ : "dueDate";+ const bucketDays = parseBuckets(url.searchParams.get("bucketDays"));++ const [tieOut, aging, open] = await Promise.all([+ getApTieOut(client, companyId, asOfDate),+ getApAging(client, companyId, asOfDate, { agingMethod, bucketDays }),+ getApOpenBySupplier(client, companyId, asOfDate)+ ]);++ return {+ asOfDate,+ agingMethod,+ bucketDays,+ result: tieOut.data ?? null,+ aging: aging.data ?? [],+ open: (open.data ?? []).map((r) => ({+ ...r,+ invoiceId: r.documentId,+ invoiceNumber: r.documentNumber+ }))+ };+}++export default function PayablesRoute() {+ const { asOfDate, agingMethod, bucketDays, result, aging, open } =+ useLoaderData<typeof loader>();+ return (+ <ARAPWorkbench+ side="ap"+ result={result}+ aging={aging}+ open={open}+ asOfDate={asOfDate}+ agingMethod={agingMethod}+ bucketDays={bucketDays}+ />+ );+}diff --git a/apps/erp/app/routes/x+/invoicing+/payments.tsx b/apps/erp/app/routes/x+/invoicing+/payments.tsxnew file mode 100644index 0000000000..ab86b84ad7--- /dev/null+++ b/apps/erp/app/routes/x+/invoicing+/payments.tsx@@ -0,0 +1,82 @@+import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { LoaderFunctionArgs } from "react-router";+import { redirect, useLoaderData } from "react-router";+import { getPayments, PaymentsTable } from "~/modules/invoicing";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";+import { getGenericQueryFilters } from "~/utils/query";++export const handle: Handle = {+ breadcrumb: "Payments",+ to: path.to.payments,+ module: "invoicing"+};++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "invoicing"+ });++ const url = new URL(request.url);+ const searchParams = url.searchParams;+ const search = searchParams.get("search");+ const paymentType = searchParams.get("paymentType") as+ | "Receipt"+ | "Disbursement"+ | null;+ const status = searchParams.get("status") as+ | "Draft"+ | "Posted"+ | "Voided"+ | null;+ const customerId = searchParams.get("customerId");+ const supplierId = searchParams.get("supplierId");++ const {+ limit,+ offset,+ sorts,+ filters = []+ } = getGenericQueryFilters(searchParams);++ // The "Counterparty" column filter spans two columns (customerId OR+ // supplierId), so pull it out of the generic filters and hand it to+ // getPayments, which applies it as an OR. The rest pass through normally.+ const counterpartyIds = filters+ .filter((f) => f.column === "counterparty")+ .flatMap((f) => (f.value ?? "").split(","))+ .filter(Boolean);+ const passThroughFilters = filters.filter((f) => f.column !== "counterparty");++ const payments = await getPayments(client, companyId, {+ search,+ paymentType,+ status,+ customerId,+ supplierId,+ counterpartyIds: counterpartyIds.length > 0 ? counterpartyIds : null,+ limit,+ offset,+ sorts,+ filters: passThroughFilters+ });++ if (payments.error) {+ throw redirect(+ path.to.invoicing,+ await flash(request, error(payments.error, "Failed to fetch payments"))+ );+ }++ return {+ count: payments.count ?? 0,+ payments: payments.data ?? []+ };+}++export default function PaymentsRoute() {+ const { count, payments } = useLoaderData<typeof loader>();+ return <PaymentsTable data={payments} count={count} />;+}diff --git a/apps/erp/app/routes/x+/invoicing+/purchasing.tsx b/apps/erp/app/routes/x+/invoicing+/purchasing.tsxnew file mode 100644index 0000000000..cb134c75e1--- /dev/null+++ b/apps/erp/app/routes/x+/invoicing+/purchasing.tsx@@ -0,0 +1,69 @@+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, redirect, useLoaderData } from "react-router";+import {+ getPurchaseInvoices,+ PurchaseInvoicesTable+} from "~/modules/invoicing";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";+import { getGenericQueryFilters } from "~/utils/query";++export const handle: Handle = {+ breadcrumb: msg`Purchasing Invoices`,+ to: path.to.invoicingPurchasing,+ module: "invoicing"+};++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "invoicing"+ });++ const url = new URL(request.url);+ const searchParams = new URLSearchParams(url.search);+ const search = searchParams.get("search");+ const supplierId = searchParams.get("supplierId");++ const { limit, offset, sorts, filters } =+ getGenericQueryFilters(searchParams);++ const purchaseInvoices = await getPurchaseInvoices(client, companyId, {+ search,+ supplierId,+ limit,+ offset,+ sorts,+ filters+ });++ if (purchaseInvoices.error) {+ redirect(+ path.to.invoicing,+ await flash(+ request,+ error(purchaseInvoices.error, "Failed to fetch purchase invoices")+ )+ );+ }++ return {+ count: purchaseInvoices.count ?? 0,+ purchaseInvoices: purchaseInvoices.data ?? []+ };+}++export default function InvoicingPurchaseInvoicesRoute() {+ const { count, purchaseInvoices } = useLoaderData<typeof loader>();++ return (+ <VStack spacing={0} className="h-full">+ <PurchaseInvoicesTable data={purchaseInvoices} count={count} />+ <Outlet />+ </VStack>+ );+}diff --git a/apps/erp/app/routes/x+/invoicing+/receivables.adjust.tsx b/apps/erp/app/routes/x+/invoicing+/receivables.adjust.tsxnew file mode 100644index 0000000000..0aa44c2a09--- /dev/null+++ b/apps/erp/app/routes/x+/invoicing+/receivables.adjust.tsx@@ -0,0 +1,107 @@+import { assertIsPost, error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { flash } from "@carbon/auth/session.server";+import { FunctionRegion } from "@supabase/supabase-js";+import type { ActionFunctionArgs } from "react-router";+import { redirect } from "react-router";+import {+ getDefaultAccounts,+ saveJournalEntryWithLines+} from "~/modules/accounting";+import { getArTieOut } from "~/modules/invoicing";+import { path } from "~/utils/path";++// Turns a non-zero AR tie-out variance into a balanced Draft journal entry — the+// receivables control account against the rounding account — then drops the user+// on the journal-entry editor to review and post. The variance is recomputed+// server-side (not trusted from the form) so the seeded lines always match the+// current books.+export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, companyGroupId, userId } =+ await requirePermissions(request, { create: "accounting" });++ const formData = await request.formData();+ const asOfDate =+ (formData.get("asOfDate") as string | null) ??+ new Date().toISOString().slice(0, 10);++ const [tieOut, defaults] = await Promise.all([+ getArTieOut(client, companyId, asOfDate),+ getDefaultAccounts(client, companyId)+ ]);++ const variance = Number(tieOut.data?.variance ?? 0);+ const receivablesAccount = defaults.data?.receivablesAccount;+ const offsetAccount = defaults.data?.roundingAccount;++ if (!receivablesAccount || !offsetAccount || variance === 0) {+ throw redirect(+ path.to.receivables,+ await flash(request, error(null, "No receivables variance to adjust"))+ );+ }++ const serviceRole = getCarbonServiceRole();+ const journalEntry = await serviceRole.functions.invoke<{ id: string }>(+ "create",+ {+ body: { type: "journalEntry", companyId, userId },+ region: FunctionRegion.UsEast1+ }+ );++ if (!journalEntry.data || journalEntry.error) {+ throw redirect(+ path.to.receivables,+ await flash(+ request,+ error(journalEntry.error, "Failed to create adjusting entry")+ )+ );+ }++ const journalId = String(journalEntry.data.id);+ const description = `AR tie-out adjustment as of ${asOfDate}`;++ // Receivables is an asset: subledger > GL (variance > 0) means the asset is+ // understated in the GL — debit receivables to raise it; otherwise credit.+ // The offsetting half lands in the rounding account so the entry is balanced.+ const saved = await saveJournalEntryWithLines(client, {+ journalEntryId: journalId,+ postingDate: asOfDate,+ description,+ updatedBy: userId,+ companyId,+ companyGroupId,+ lines: [+ {+ accountId: receivablesAccount,+ description,+ debit: variance > 0 ? variance : 0,+ credit: variance < 0 ? -variance : 0+ },+ {+ accountId: offsetAccount,+ description,+ debit: variance < 0 ? -variance : 0,+ credit: variance > 0 ? variance : 0+ }+ ]+ });++ if (saved.error) {+ // The Draft journal exists; send the user to it to finish by hand rather+ // than reporting a clean success.+ throw redirect(+ path.to.journalEntryDetails(journalId),+ await flash(+ request,+ error(saved.error, "Entry created, but seeding the lines failed")+ )+ );+ }++ throw redirect(path.to.journalEntryDetails(journalId));+}diff --git a/apps/erp/app/routes/x+/invoicing+/receivables.tsx b/apps/erp/app/routes/x+/invoicing+/receivables.tsxnew file mode 100644index 0000000000..e9c3e50dcf--- /dev/null+++ b/apps/erp/app/routes/x+/invoicing+/receivables.tsx@@ -0,0 +1,75 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import type { LoaderFunctionArgs } from "react-router";+import { useLoaderData } from "react-router";+import {+ ARAPWorkbench,+ getArAging,+ getArOpenByCustomer,+ getArTieOut+} from "~/modules/invoicing";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const handle: Handle = {+ breadcrumb: "Receivables",+ to: path.to.receivables,+ module: "invoicing"+};++function parseBuckets(raw: string | null): [number, number, number] {+ const parts = (raw ?? "").split(",").map((n) => Number.parseInt(n, 10));+ if (parts.length === 3 && parts.every((n) => Number.isFinite(n) && n > 0)) {+ return [parts[0], parts[1], parts[2]];+ }+ return [30, 60, 90];+}++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "invoicing"+ });++ const url = new URL(request.url);+ const asOfDate =+ url.searchParams.get("asOfDate") ?? new Date().toISOString().slice(0, 10);+ const agingMethod: "dueDate" | "documentDate" =+ url.searchParams.get("agingMethod") === "documentDate"+ ? "documentDate"+ : "dueDate";+ const bucketDays = parseBuckets(url.searchParams.get("bucketDays"));++ const [tieOut, aging, open] = await Promise.all([+ getArTieOut(client, companyId, asOfDate),+ getArAging(client, companyId, asOfDate, { agingMethod, bucketDays }),+ getArOpenByCustomer(client, companyId, asOfDate)+ ]);++ return {+ asOfDate,+ agingMethod,+ bucketDays,+ result: tieOut.data ?? null,+ aging: aging.data ?? [],+ open: (open.data ?? []).map((r) => ({+ ...r,+ invoiceId: r.documentId,+ invoiceNumber: r.documentNumber+ }))+ };+}++export default function ReceivablesRoute() {+ const { asOfDate, agingMethod, bucketDays, result, aging, open } =+ useLoaderData<typeof loader>();+ return (+ <ARAPWorkbench+ side="ar"+ result={result}+ aging={aging}+ open={open}+ asOfDate={asOfDate}+ agingMethod={agingMethod}+ bucketDays={bucketDays}+ />+ );+}diff --git a/apps/erp/app/routes/x+/invoicing+/sales.tsx b/apps/erp/app/routes/x+/invoicing+/sales.tsxnew file mode 100644index 0000000000..9967284878--- /dev/null+++ b/apps/erp/app/routes/x+/invoicing+/sales.tsx@@ -0,0 +1,67 @@+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, redirect, useLoaderData } from "react-router";+import { getSalesInvoices } from "~/modules/invoicing";+import SalesInvoicesTable from "~/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";+import { getGenericQueryFilters } from "~/utils/query";++export const handle: Handle = {+ breadcrumb: msg`Sales Invoices`,+ to: path.to.invoicingSales,+ module: "invoicing"+};++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "invoicing"+ });++ const url = new URL(request.url);+ const searchParams = new URLSearchParams(url.search);+ const search = searchParams.get("search");+ const customerId = searchParams.get("customerId");++ const { limit, offset, sorts, filters } =+ getGenericQueryFilters(searchParams);++ const salesInvoices = await getSalesInvoices(client, companyId, {+ search,+ customerId,+ limit,+ offset,+ sorts,+ filters+ });++ if (salesInvoices.error) {+ redirect(+ path.to.invoicing,+ await flash(+ request,+ error(salesInvoices.error, "Failed to fetch sales invoices")+ )+ );+ }++ return {+ count: salesInvoices.count ?? 0,+ salesInvoices: salesInvoices.data ?? []+ };+}++export default function InvoicingSalesInvoicesRoute() {+ const { count, salesInvoices } = useLoaderData<typeof loader>();++ return (+ <VStack spacing={0} className="h-full">+ <SalesInvoicesTable data={salesInvoices} count={count} />+ <Outlet />+ </VStack>+ );+}diff --git a/apps/erp/app/routes/x+/journal-entry+/$journalEntryId.details.tsx b/apps/erp/app/routes/x+/journal-entry+/$journalEntryId.details.tsxindex bc0be9668f..8f644ba2ca 100644--- a/apps/erp/app/routes/x+/journal-entry+/$journalEntryId.details.tsx+++ b/apps/erp/app/routes/x+/journal-entry+/$journalEntryId.details.tsx@@ -129,6 +129,7 @@ export default function JournalEntryDetailsRoute() {companies: { id: string; name: string }[];dimensions: DimensionWithValues[];lineDimensions: Record<string, JournalLineDimensionValue[]>;+ sourceDocument: { readableId: string; to: string } | null;}>(path.to.journalEntry(journalEntryId));if (!routeData?.journalEntry)@@ -158,6 +159,7 @@ export default function JournalEntryDetailsRoute() {displayId={routeData.journalEntry.journalEntryId}status={routeData.journalEntry.status}sourceType={routeData.journalEntry.sourceType ?? "Manual"}+ sourceDocument={routeData.sourceDocument ?? null}reversedById={routeData.journalEntry.reversedById}initialValues={{id: routeData.journalEntry.id,diff --git a/apps/erp/app/routes/x+/journal-entry+/$journalEntryId.tsx b/apps/erp/app/routes/x+/journal-entry+/$journalEntryId.tsxindex 94d3e5f9b9..22662b4551 100644--- a/apps/erp/app/routes/x+/journal-entry+/$journalEntryId.tsx+++ b/apps/erp/app/routes/x+/journal-entry+/$journalEntryId.tsx@@ -17,6 +17,40 @@ export const handle: Handle = {to: path.to.accountingJournals};+// Maps a journal's sourceType to the document it was posted from, so the+// details screen can link back to it (like the Sales Order button on an+// invoice). `Manual` entries and unmapped sources show no link.+const journalSourceDocumentMap: Record<+ string,+ { table: string; column: string; to: (id: string) => string }+> = {+ Payment: {+ table: "payment",+ column: "paymentId",+ to: (id) => path.to.payment(id)+ },+ "Sales Invoice": {+ table: "salesInvoice",+ column: "invoiceId",+ to: (id) => path.to.salesInvoiceDetails(id)+ },+ "Purchase Invoice": {+ table: "purchaseInvoice",+ column: "invoiceId",+ to: (id) => path.to.purchaseInvoiceDetails(id)+ },+ "Sales Shipment": {+ table: "shipment",+ column: "shipmentId",+ to: (id) => path.to.shipmentDetails(id)+ },+ "Purchase Receipt": {+ table: "receipt",+ column: "receiptId",+ to: (id) => path.to.receiptDetails(id)+ }+};+export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId, companyGroupId } = await requirePermissions(request,@@ -51,11 +85,38 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const journalLineIds = (journalEntry.data.journalLine ?? []).map((l) => l.id);const lineDimensions = await getJournalLineDimensions(client, journalLineIds);+ // Resolve the source document (if any) so the screen can link back to it.+ const sourceType = journalEntry.data.sourceType;+ const documentId =+ (journalEntry.data.journalLine ?? []).find((l) => l.documentId)+ ?.documentId ?? null;+ let sourceDocument: { readableId: string; to: string } | null = null;+ if (sourceType && sourceType !== "Manual" && documentId) {+ const spec = journalSourceDocumentMap[sourceType];+ if (spec) {+ const doc = await client+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ .from(spec.table as any)+ .select(`id, ${spec.column}`)+ .eq("id", documentId)+ .maybeSingle();+ if (doc.data) {+ sourceDocument = {+ readableId: (doc.data as unknown as Record<string, string>)[+ spec.column+ ],+ to: spec.to(documentId)+ };+ }+ }+ }+return {journalEntry: journalEntry.data,companies: companies.data ?? [],dimensions: dimensions.data ?? [],- lineDimensions: lineDimensions.data ?? {}+ lineDimensions: lineDimensions.data ?? {},+ sourceDocument};}diff --git a/apps/erp/app/routes/x+/payments+/$paymentId.applications.set.tsx b/apps/erp/app/routes/x+/payments+/$paymentId.applications.set.tsxnew file mode 100644index 0000000000..0c1ee7acc6--- /dev/null+++ b/apps/erp/app/routes/x+/payments+/$paymentId.applications.set.tsx@@ -0,0 +1,107 @@+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 { z } from "zod";+import {+ invoiceSettlementBase,+ invoiceSettlementValidator,+ replaceInvoiceSettlements+} from "~/modules/invoicing";+import { getDatabaseClient } from "~/services/database.server";+import { path } from "~/utils/path";++// Apply-table submits the full list of applications as one JSON payload.+// Each row is validated against invoiceSettlementValidator (with the+// paymentId injected from the URL), then replaceInvoiceSettlements+// runs a delete-then-insert under RLS (Draft-only via the parent+// payment policy).+const setApplicationsValidator = z.object({+ applications: z.string() // JSON-encoded array+});++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { companyId, userId } = await requirePermissions(request, {+ update: "invoicing"+ });++ const { paymentId } = params;+ if (!paymentId) throw redirect(path.to.payments);++ const formData = await request.formData();+ const raw = setApplicationsValidator.safeParse({+ applications: formData.get("applications")+ });+ if (!raw.success) {+ throw redirect(+ path.to.payment(paymentId),+ await flash(request, error(raw.error, "Invalid payload"))+ );+ }++ let parsed: unknown;+ try {+ parsed = JSON.parse(raw.data.applications);+ } catch (e) {+ throw redirect(+ path.to.payment(paymentId),+ await flash(request, error(e, "Applications payload is not valid JSON"))+ );+ }++ // Per-row validation through the shared zod validator. paymentId is+ // injected so the validator's required-field check passes without+ // depending on the client to send it on every row.+ const rowsValidator = z.array(+ invoiceSettlementBase.omit({ paymentId: true })+ );+ const rowsResult = rowsValidator.safeParse(parsed);+ if (!rowsResult.success) {+ throw redirect(+ path.to.payment(paymentId),+ await flash(request, error(rowsResult.error, "Invalid applications"))+ );+ }++ // Re-validate each row through the full refined validator now that+ // paymentId is present.+ const applications = [];+ for (const row of rowsResult.data) {+ const validated = invoiceSettlementValidator.safeParse({+ ...row,+ paymentId+ });+ if (!validated.success) {+ throw redirect(+ path.to.payment(paymentId),+ await flash(+ request,+ error(validated.error, "Application failed validation")+ )+ );+ }+ const { id: _omit, paymentId: _omit2, ...rest } = validated.data;+ applications.push(rest);+ }++ try {+ await replaceInvoiceSettlements(getDatabaseClient(), {+ paymentId,+ companyId,+ createdBy: userId,+ applications+ });+ } catch (e) {+ throw redirect(+ path.to.payment(paymentId),+ await flash(request, error(e, "Failed to save applications"))+ );+ }++ throw redirect(+ path.to.payment(paymentId),+ await flash(request, success("Applications saved"))+ );+}diff --git a/apps/erp/app/routes/x+/payments+/$paymentId.credits.set.tsx b/apps/erp/app/routes/x+/payments+/$paymentId.credits.set.tsxnew file mode 100644index 0000000000..11088d28b8--- /dev/null+++ b/apps/erp/app/routes/x+/payments+/$paymentId.credits.set.tsx@@ -0,0 +1,103 @@+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 { z } from "zod";+import { applyCreditsToInvoices, getPayment } from "~/modules/invoicing";+import { getDatabaseClient } from "~/services/database.server";+import { path } from "~/utils/path";++// The credits half of the invoice "Receive Payment" composer. Applies the party's+// posted credits to their open invoices (memo-sourced invoiceSettlement rows,+// GL-neutral) — independent of the payment's own cash applications, but driven+// from the same screen so an invoice can be cleared with cash + credits at once.+const setCreditsValidator = z.object({+ applications: z.string() // JSON-encoded array+});++const rowsValidator = z.array(+ z.object({+ memoId: z.string().min(1),+ invoiceId: z.string().min(1),+ amount: z.number().positive()+ })+);++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "invoicing"+ });++ const { paymentId } = params;+ if (!paymentId) throw redirect(path.to.payments);++ const formData = await request.formData();+ const raw = setCreditsValidator.safeParse({+ applications: formData.get("applications")+ });+ if (!raw.success) {+ throw redirect(+ path.to.payment(paymentId),+ await flash(request, error(raw.error, "Invalid payload"))+ );+ }++ let parsed: unknown;+ try {+ parsed = JSON.parse(raw.data.applications);+ } catch (e) {+ throw redirect(+ path.to.payment(paymentId),+ await flash(request, error(e, "Credits payload is not valid JSON"))+ );+ }++ const rows = rowsValidator.safeParse(parsed);+ if (!rows.success) {+ throw redirect(+ path.to.payment(paymentId),+ await flash(request, error(rows.error, "Invalid credit applications"))+ );+ }++ // The invoice side follows the payment's party: a customer's credits clear+ // sales invoices; a supplier's clear purchase invoices.+ const payment = await getPayment(client, paymentId);+ if (payment.error || !payment.data) {+ throw redirect(+ path.to.payment(paymentId),+ await flash(request, error(payment.error, "Failed to load payment"))+ );+ }+ const side: "sales" | "purchase" = payment.data.customerId+ ? "sales"+ : "purchase";++ try {+ await applyCreditsToInvoices(getDatabaseClient(), {+ paymentId,+ companyId,+ createdBy: userId,+ appliedDate: new Date().toISOString().slice(0, 10),+ side,+ applications: rows.data+ });+ } catch (e) {+ // applyCreditsToInvoices throws Error with a specific, user-actionable+ // reason (over-applied, invoice already settled, exchange-rate mismatch,+ // etc.). Surface that instead of a generic message so the user knows why.+ const reason =+ e instanceof Error && e.message ? e.message : "Failed to apply credits";+ throw redirect(+ path.to.payment(paymentId),+ await flash(request, error(e, reason))+ );+ }++ throw redirect(+ path.to.payment(paymentId),+ await flash(request, success("Credits applied"))+ );+}diff --git a/apps/erp/app/routes/x+/payments+/$paymentId.delete.tsx b/apps/erp/app/routes/x+/payments+/$paymentId.delete.tsxnew file mode 100644index 0000000000..5c638d70ed--- /dev/null+++ b/apps/erp/app/routes/x+/payments+/$paymentId.delete.tsx@@ -0,0 +1,38 @@+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 { deletePayment } from "~/modules/invoicing";+import { path } from "~/utils/path";++// Action-only route — the delete confirmation modal (ConfirmDelete) posts here.+// The payment table's RLS DELETE policy restricts deletes to Draft payments, so+// a non-draft delete fails at the database; the UI also hides the action.+export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client } = await requirePermissions(request, {+ delete: "invoicing"+ });++ const { paymentId } = params;+ if (!paymentId) {+ throw redirect(+ path.to.payments,+ await flash(request, error(params, "Failed to get a payment id"))+ );+ }++ const remove = await deletePayment(client, paymentId);+ if (remove.error) {+ throw redirect(+ path.to.payment(paymentId),+ await flash(request, error(remove.error, "Failed to delete payment"))+ );+ }++ throw redirect(+ path.to.payments,+ await flash(request, success("Successfully deleted payment"))+ );+}diff --git a/apps/erp/app/routes/x+/payments+/$paymentId.post.tsx b/apps/erp/app/routes/x+/payments+/$paymentId.post.tsxnew file mode 100644index 0000000000..f73d75e8d2--- /dev/null+++ b/apps/erp/app/routes/x+/payments+/$paymentId.post.tsx@@ -0,0 +1,50 @@+import { assertIsPost, error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { flash } from "@carbon/auth/session.server";+import type { ActionFunctionArgs } from "react-router";+import { redirect } from "react-router";+import { path } from "~/utils/path";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { companyId, userId } = await requirePermissions(request, {+ update: "invoicing"+ });+ const { paymentId } = params;+ if (!paymentId) {+ return { success: false, message: "Missing paymentId" };+ }++ const serviceRole = getCarbonServiceRole();+ try {+ const result = await serviceRole.functions.invoke("post-payment", {+ body: {+ type: "post",+ paymentId,+ userId,+ companyId+ }+ });+ if (result.error) {+ const message =+ (result.data as { message?: string } | undefined)?.message ??+ result.error.message ??+ "Failed to post payment";+ throw redirect(+ path.to.payment(paymentId),+ await flash(request, error(result.error, message))+ );+ }+ } catch (err) {+ throw redirect(+ path.to.payment(paymentId),+ await flash(request, error(err, "Failed to post payment"))+ );+ }++ throw redirect(+ path.to.payment(paymentId),+ await flash(request, success("Payment posted"))+ );+}diff --git a/apps/erp/app/routes/x+/payments+/$paymentId.tsx b/apps/erp/app/routes/x+/payments+/$paymentId.tsxnew file mode 100644index 0000000000..479ab342ef--- /dev/null+++ b/apps/erp/app/routes/x+/payments+/$paymentId.tsx@@ -0,0 +1,289 @@+import { assertIsPost, error, notFound, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { validationError, validator } from "@carbon/form";+import { VStack } from "@carbon/react";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { data, redirect, useLoaderData } from "react-router";+import {+ AvailableCreditsTable,+ getAvailableCreditsForParty,+ getAvailableOnAccountCredit,+ getInvoiceSettlements,+ getOpenPurchaseInvoicesForSupplier,+ getOpenSalesInvoicesForCustomer,+ getPayment,+ getStagedCreditsForPayment,+ isPaymentLocked,+ PaymentApplications,+ PaymentApplyTable,+ PaymentForm,+ paymentValidator,+ upsertPayment+} from "~/modules/invoicing";+import { setCustomFields } from "~/utils/form";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const handle: Handle = {+ breadcrumb: "Payments",+ to: path.to.payments+};++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "invoicing"+ });+ const { paymentId } = params;+ if (!paymentId) throw notFound("Missing paymentId");++ const [payment, applications] = await Promise.all([+ getPayment(client, paymentId),+ getInvoiceSettlements(client, companyId, paymentId)+ ]);++ if (payment.error || !payment.data) {+ throw redirect(+ path.to.payments,+ await flash(request, error(payment.error, "Failed to load payment"))+ );+ }++ // Apply table needs the counterparty's open invoices. Only fetched+ // for Draft payments to keep the Posted/Voided detail render lean.+ // Cast to a common shape — sales and purchase status enums differ+ // ('Submitted' vs 'Open') so TypeScript can't unify the two without+ // help.+ type OpenInvoiceRow = {+ id: string;+ invoiceId: string | null;+ dateDue: string | null;+ currencyCode: string;+ exchangeRate: number;+ totalAmount: number;+ balance: number;+ status: string | null;+ };+ // Available on-account credit (base ccy) the counterparty can draw on when+ // this payment applies more than its cash. Only needed while editing a Draft.+ // Posted credits (balance-reducing memos) the party can apply to open invoices+ // alongside this payment's cash — the credits half of the settlement composer.+ type AvailableCreditRow = {+ id: string;+ memoId: string;+ direction: string;+ currencyCode: string;+ exchangeRate: number;+ remaining: number;+ };+ let availableCreditBase = 0;+ let openInvoices: OpenInvoiceRow[] = [];+ let availableCredits: AvailableCreditRow[] = [];+ let stagedCredits: { memoId: string; invoiceId: string; amount: number }[] =+ [];+ if (payment.data.status === "Draft") {+ if (payment.data.customerId) {+ const [res, credit, credits, staged] = await Promise.all([+ getOpenSalesInvoicesForCustomer(+ client,+ companyId,+ payment.data.customerId+ ),+ getAvailableOnAccountCredit(client, companyId, {+ paymentType: "Receipt",+ customerId: payment.data.customerId+ }),+ getAvailableCreditsForParty(+ client,+ companyId,+ { side: "sales", customerId: payment.data.customerId },+ paymentId+ ),+ getStagedCreditsForPayment(client, paymentId, "sales")+ ]);+ openInvoices = (res.data ?? []) as OpenInvoiceRow[];+ availableCreditBase = credit;+ availableCredits = (credits.data ?? []) as AvailableCreditRow[];+ stagedCredits = staged.data ?? [];+ } else if (payment.data.supplierId) {+ const [res, credit, credits, staged] = await Promise.all([+ getOpenPurchaseInvoicesForSupplier(+ client,+ companyId,+ payment.data.supplierId+ ),+ getAvailableOnAccountCredit(client, companyId, {+ paymentType: "Disbursement",+ supplierId: payment.data.supplierId+ }),+ getAvailableCreditsForParty(+ client,+ companyId,+ { side: "purchase", supplierId: payment.data.supplierId },+ paymentId+ ),+ getStagedCreditsForPayment(client, paymentId, "purchase")+ ]);+ openInvoices = (res.data ?? []) as OpenInvoiceRow[];+ availableCreditBase = credit;+ availableCredits = (credits.data ?? []) as AvailableCreditRow[];+ stagedCredits = staged.data ?? [];+ }+ }++ return {+ payment: payment.data,+ applications: applications.data ?? [],+ openInvoices: openInvoices ?? [],+ availableCreditBase,+ availableCredits,+ stagedCredits+ };+}++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ update: "invoicing"+ });+ const { paymentId } = params;+ if (!paymentId) throw notFound("Missing paymentId");++ const formData = await request.formData();+ const validation = await validator(paymentValidator).validate(formData);+ if (validation.error) {+ return validationError(validation.error);+ }++ // Only Draft payments are editable; Posted/Voided are immutable.+ const existing = await getPayment(client, paymentId);+ if (existing.error || !existing.data) {+ throw redirect(+ path.to.payments,+ await flash(request, error(existing.error, "Failed to load payment"))+ );+ }+ if (existing.data.status !== "Draft") {+ throw redirect(+ path.to.payment(paymentId),+ await flash(request, error(null, "Only draft payments can be edited"))+ );+ }++ const { id: _omitId, ...paymentData } = validation.data;+ const update = await upsertPayment(client, {+ ...paymentData,+ id: paymentId,+ updatedBy: userId,+ customFields: setCustomFields(formData)+ });+ if (update.error) {+ return data(+ {},+ await flash(request, error(update.error, "Failed to update payment"))+ );+ }++ throw redirect(+ path.to.payment(paymentId),+ await flash(request, success("Payment updated"))+ );+}++export default function PaymentDetailRoute() {+ const {+ payment,+ applications,+ openInvoices,+ availableCreditBase,+ availableCredits,+ stagedCredits+ } = useLoaderData<typeof loader>();+ const locked = isPaymentLocked(payment.status);+ const side: "sales" | "purchase" = payment.customerId ? "sales" : "purchase";++ // Convert the base-currency credit pool into the payment's currency so the+ // apply table can compare it against amounts entered in payment currency.+ const exchangeRate = Number(payment.exchangeRate ?? 1) || 1;+ const availableCredit = (availableCreditBase ?? 0) / exchangeRate;++ const initialValues = {+ id: payment.id,+ paymentId: payment.paymentId,+ paymentType: payment.paymentType,+ customerId: payment.customerId ?? "",+ supplierId: payment.supplierId ?? "",+ paymentDate: payment.paymentDate,+ currencyCode: payment.currencyCode ?? "",+ exchangeRate: Number(payment.exchangeRate ?? 1),+ totalAmount: Number(payment.totalAmount ?? 0),+ bankAccount: payment.bankAccount ?? "",+ reference: payment.reference ?? "",+ memo: payment.memo ?? "",+ status: payment.status ?? undefined+ };++ return (+ <VStack spacing={4} className="p-6 max-w-6xl w-full mx-auto">+ <PaymentForm initialValues={initialValues} />+ <PaymentApplications+ applications={applications}+ paymentTotal={Number(payment.totalAmount)}+ />++ {!locked && (+ <PaymentApplyTable+ paymentId={payment.id}+ paymentType={payment.paymentType}+ paymentCurrency={payment.currencyCode}+ paymentTotal={Number(payment.totalAmount)}+ paymentExchangeRate={Number(payment.exchangeRate)}+ availableCredit={availableCredit}+ openInvoices={(openInvoices ?? []).map((inv) => ({+ id: inv.id,+ invoiceId: inv.invoiceId ?? inv.id,+ dateDue: inv.dateDue,+ currencyCode: inv.currencyCode,+ exchangeRate: Number(inv.exchangeRate ?? 1),+ totalAmount: Number(inv.totalAmount ?? 0),+ balance: Number(inv.balance ?? 0),+ status: inv.status+ }))}+ existingApplications={applications.map((a) => ({+ targetSalesInvoiceId: a.targetSalesInvoiceId,+ targetPurchaseInvoiceId: a.targetPurchaseInvoiceId,+ appliedAmount: Number(a.appliedAmount),+ discountAmount: Number(a.discountAmount),+ writeOffAmount: Number(a.writeOffAmount),+ targetExchangeRate: Number(a.targetExchangeRate),+ sourceExchangeRate: Number(a.sourceExchangeRate),+ appliedDate: a.appliedDate+ }))}+ />+ )}++ {!locked && availableCredits.length > 0 && (+ <AvailableCreditsTable+ paymentId={payment.id}+ side={side}+ currency={payment.currencyCode}+ credits={availableCredits.map((c) => ({+ id: c.id,+ memoId: c.memoId,+ direction: c.direction,+ currencyCode: c.currencyCode,+ exchangeRate: Number(c.exchangeRate),+ remaining: Number(c.remaining)+ }))}+ openInvoices={(openInvoices ?? []).map((inv) => ({+ id: inv.id,+ invoiceId: inv.invoiceId ?? inv.id,+ exchangeRate: Number(inv.exchangeRate ?? 1),+ balance: Number(inv.balance ?? 0)+ }))}+ staged={stagedCredits}+ />+ )}+ </VStack>+ );+}diff --git a/apps/erp/app/routes/x+/payments+/$paymentId.void.tsx b/apps/erp/app/routes/x+/payments+/$paymentId.void.tsxnew file mode 100644index 0000000000..e0494090ba--- /dev/null+++ b/apps/erp/app/routes/x+/payments+/$paymentId.void.tsx@@ -0,0 +1,46 @@+import { assertIsPost, error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { flash } from "@carbon/auth/session.server";+import type { ActionFunctionArgs } from "react-router";+import { redirect } from "react-router";+import { path } from "~/utils/path";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { companyId, userId } = await requirePermissions(request, {+ update: "invoicing"+ });+ const { paymentId } = params;+ if (!paymentId) {+ return { success: false, message: "Missing paymentId" };+ }++ const serviceRole = getCarbonServiceRole();+ try {+ const result = await serviceRole.functions.invoke("post-payment", {+ body: {+ type: "void",+ paymentId,+ userId,+ companyId+ }+ });+ if (result.error) {+ throw redirect(+ path.to.payment(paymentId),+ await flash(request, error(result.error, "Failed to void payment"))+ );+ }+ } catch (err) {+ throw redirect(+ path.to.payment(paymentId),+ await flash(request, error(err, "Failed to void payment"))+ );+ }++ throw redirect(+ path.to.payment(paymentId),+ await flash(request, success("Payment voided"))+ );+}diff --git a/apps/erp/app/routes/x+/payments+/_layout.tsx b/apps/erp/app/routes/x+/payments+/_layout.tsxnew file mode 100644index 0000000000..1257b30214--- /dev/null+++ b/apps/erp/app/routes/x+/payments+/_layout.tsx@@ -0,0 +1,18 @@+import type { MetaFunction } from "react-router";+import { Outlet } from "react-router";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const meta: MetaFunction = () => {+ return [{ title: "Carbon | Payments" }];+};++export const handle: Handle = {+ breadcrumb: "Invoicing",+ to: path.to.invoicing,+ module: "invoicing"+};++export default function PaymentsRoute() {+ return <Outlet />;+}diff --git a/apps/erp/app/routes/x+/payments+/new.tsx b/apps/erp/app/routes/x+/payments+/new.tsxnew file mode 100644index 0000000000..e62432c4c6--- /dev/null+++ b/apps/erp/app/routes/x+/payments+/new.tsx@@ -0,0 +1,225 @@+import { assertIsPost, error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type { Database } from "@carbon/database";+import { validationError, validator } from "@carbon/form";+import type { SupabaseClient } from "@supabase/supabase-js";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { redirect, useLoaderData } from "react-router";+import { getDefaultAccounts } from "~/modules/accounting";+import {+ getOpenPurchaseInvoicesForSupplier,+ getOpenSalesInvoicesForCustomer,+ PaymentForm,+ paymentValidator,+ replaceInvoiceSettlements,+ upsertPayment+} from "~/modules/invoicing";+import { getCompany, getNextSequence } from "~/modules/settings";+import { getDatabaseClient } from "~/services/database.server";+import { setCustomFields } from "~/utils/form";+import { path } from "~/utils/path";++// Open invoices the apply table / seed logic can settle, keyed by id with the+// fields needed to seed one application per invoice.+async function getSeedableOpenInvoices(+ client: SupabaseClient<Database>,+ companyId: string,+ paymentType: "Receipt" | "Disbursement",+ partyId: string+) {+ const res =+ paymentType === "Receipt"+ ? await getOpenSalesInvoicesForCustomer(client, companyId, partyId)+ : await getOpenPurchaseInvoicesForSupplier(client, companyId, partyId);+ return res.data ?? [];+}++// Loader pre-fills the form. Query params:+// customerId -> seeds counterparty + paymentType=Receipt+// supplierId -> seeds counterparty + paymentType=Disbursement+// invoiceId -> one or more; their open balances are summed into the total+// and (on submit) one application is seeded per invoice+// amount -> fallback total when no invoiceId is supplied+export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ create: "invoicing"+ });++ const url = new URL(request.url);+ const customerId = url.searchParams.get("customerId");+ const supplierId = url.searchParams.get("supplierId");+ const invoiceIds = url.searchParams.getAll("invoiceId");+ const amount = url.searchParams.get("amount");++ const paymentType: "Receipt" | "Disbursement" = supplierId+ ? "Disbursement"+ : "Receipt";+ const partyId = paymentType === "Receipt" ? customerId : supplierId;++ const [company, defaults] = await Promise.all([+ getCompany(client, companyId),+ getDefaultAccounts(client, companyId)+ ]);+ const bankAccount = defaults.data?.bankCashAccount ?? "";++ let currencyCode = company.data?.baseCurrencyCode ?? "";+ let exchangeRate = 1;+ let totalAmount = amount ? Number(amount) : 0;++ // When seeded from invoices, the total and currency come from the invoices+ // themselves (authoritative), not the URL amount.+ if (invoiceIds.length > 0 && partyId) {+ const open = await getSeedableOpenInvoices(+ client,+ companyId,+ paymentType,+ partyId+ );+ const selected = open.filter((inv) => invoiceIds.includes(inv.id ?? ""));+ if (selected.length > 0) {+ currencyCode = selected[0].currencyCode ?? currencyCode;+ exchangeRate = Number(selected[0].exchangeRate ?? 1);+ totalAmount = selected.reduce(+ (sum, inv) => sum + Number(inv.balance ?? 0),+ 0+ );+ }+ }++ return {+ initialValues: {+ paymentId: "",+ paymentType,+ customerId: customerId ?? "",+ supplierId: supplierId ?? "",+ paymentDate: new Date().toISOString().slice(0, 10),+ currencyCode,+ exchangeRate,+ totalAmount,+ bankAccount,+ reference: "",+ memo: ""+ },+ seedInvoiceIds: invoiceIds+ };+}++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ create: "invoicing"+ });++ const formData = await request.formData();+ // Hidden field set by the loader so the action can seed applications without+ // re-reading the URL.+ const seedInvoiceIds = String(formData.get("seedInvoiceIds") ?? "")+ .split(",")+ .map((s) => s.trim())+ .filter(Boolean);++ const validation = await validator(paymentValidator).validate(formData);+ if (validation.error) {+ return validationError(validation.error);+ }++ let paymentId = validation.data.paymentId;+ if (!paymentId) {+ const next = await getNextSequence(client, "payment", companyId);+ if (next.error || !next.data) {+ throw redirect(+ path.to.payments,+ await flash(request, error(next.error, "Failed to allocate payment id"))+ );+ }+ paymentId = next.data;+ }++ // The form posts a hidden `id` as "" which validates to null. The create+ // branch must omit it so the table's xid() default generates the id.+ const { id: _omitId, ...paymentData } = validation.data;++ const insert = await upsertPayment(client, {+ ...paymentData,+ paymentId,+ companyId,+ createdBy: userId,+ customFields: setCustomFields(formData)+ });+ if (insert.error || !insert.data) {+ throw redirect(+ path.to.payments,+ await flash(request, error(insert.error, "Failed to create payment"))+ );+ }++ // Seed one application per selected invoice for its full open balance. Each+ // invoice's balance + rate are re-fetched server-side so the seed always+ // reflects the current books. The user can still adjust via the apply table.+ if (seedInvoiceIds.length > 0) {+ const isReceipt = validation.data.paymentType === "Receipt";+ const partyId = isReceipt+ ? validation.data.customerId+ : validation.data.supplierId;+ try {+ const open = partyId+ ? await getSeedableOpenInvoices(+ client,+ companyId,+ validation.data.paymentType,+ partyId+ )+ : [];+ const selected = open.filter((inv) =>+ seedInvoiceIds.includes(inv.id ?? "")+ );+ if (selected.length > 0) {+ await replaceInvoiceSettlements(getDatabaseClient(), {+ paymentId: insert.data.id,+ companyId,+ createdBy: userId,+ applications: selected.map((inv) => ({+ targetSalesInvoiceId: isReceipt ? (inv.id ?? undefined) : undefined,+ targetPurchaseInvoiceId: isReceipt+ ? undefined+ : (inv.id ?? undefined),+ appliedAmount: Number(inv.balance ?? 0),+ discountAmount: 0,+ writeOffAmount: 0,+ targetExchangeRate: Number(inv.exchangeRate ?? 1),+ sourceExchangeRate: Number(validation.data.exchangeRate) || 1,+ appliedDate: validation.data.paymentDate+ }))+ });+ }+ } catch (e) {+ // The payment was created (a Draft with no applications is valid), but+ // seeding failed. Send the user to the detail page to apply manually.+ throw redirect(+ path.to.payment(insert.data.id),+ await flash(+ request,+ error(e, "Payment created, but applying it to the invoices failed")+ )+ );+ }+ }++ throw redirect(+ path.to.payment(insert.data.id),+ await flash(request, success("Payment created"))+ );+}++export default function NewPaymentRoute() {+ const { initialValues, seedInvoiceIds } = useLoaderData<typeof loader>();+ return (+ <div className="max-w-4xl w-full p-2 sm:p-0 mx-auto mt-0 md:mt-8">+ <PaymentForm+ initialValues={initialValues}+ seedInvoiceIds={seedInvoiceIds}+ />+ </div>+ );+}diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.delete.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.delete.tsxindex fadc2cc1ea..d5100d6ffc 100644--- a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.delete.tsx+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.delete.tsx@@ -19,7 +19,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (remove.error) {throw redirect(- path.to.purchaseInvoices,+ path.to.invoicingPurchasing,await flash(request,error(remove.error, "Failed to delete purchase invoice")@@ -27,5 +27,5 @@ export async function action({ request, params }: ActionFunctionArgs) {);}- throw redirect(path.to.purchaseInvoices);+ throw redirect(path.to.invoicingPurchasing);}diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.details.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.details.tsxindex 6247aaf8a3..e73b302e19 100644--- a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.details.tsx+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.details.tsx@@ -17,7 +17,9 @@ import type {PurchaseInvoiceLine} from "~/modules/invoicing";import {+ getInvoiceSettlementsForInvoice,getPurchaseInvoice,+ InvoicePaymentsPanel,isPurchaseInvoiceLocked,PurchaseInvoiceSummary,purchaseInvoiceValidator,@@ -35,17 +37,20 @@ import { requireUnlocked } from "~/utils/lockedGuard.server";import { path } from "~/utils/path";export async function loader({ request, params }: LoaderFunctionArgs) {- const { client } = await requirePermissions(request, {+ const { client, companyId } = await requirePermissions(request, {view: "invoicing"});const { invoiceId } = params;if (!invoiceId) throw new Error("Could not find invoiceId");- const invoice = await getPurchaseInvoice(client, invoiceId);+ const [invoice, applications] = await Promise.all([+ getPurchaseInvoice(client, invoiceId),+ getInvoiceSettlementsForInvoice(client, companyId, "purchase", invoiceId)+ ]);if (invoice.error) {throw redirect(- path.to.purchaseInvoices,+ path.to.invoicingPurchasing,await flash(request,error(invoice.error, "Failed to load purchase invoice")@@ -54,7 +59,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}return {- internalNotes: (invoice.data?.internalNotes ?? {}) as JSONContent+ internalNotes: (invoice.data?.internalNotes ?? {}) as JSONContent,+ paymentApplications: applications.data ?? []};}@@ -139,7 +145,7 @@ export async function action({ request, params }: ActionFunctionArgs) {export default function PurchaseInvoiceBasicRoute() {const { t } = useLingui();- const { internalNotes } = useLoaderData<typeof loader>();+ const { internalNotes, paymentApplications } = useLoaderData<typeof loader>();const { invoiceId } = useParams();if (!invoiceId) throw new Error("invoiceId not found");@@ -193,6 +199,7 @@ export default function PurchaseInvoiceBasicRoute() {return (<Fragment key={invoiceId}><PurchaseInvoiceSummary onEditShippingCost={handleEditShippingCost} />+ <InvoicePaymentsPanel rows={paymentApplications} /><SupplierInteractionNoteskey={`notes-${initialValues.id}`}id={invoiceId}diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.tsxindex 52e9946882..c68c426c71 100644--- a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.tsx+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.tsx@@ -7,6 +7,7 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { Outlet, redirect, useParams } from "react-router";import { PanelProvider, ResizablePanels } from "~/components/Layout";import {+ getCompanyHasOpenCredits,getPurchaseInvoice,getPurchaseInvoiceDelivery,getPurchaseInvoiceLines,@@ -23,8 +24,8 @@ import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";export const handle: Handle = {- breadcrumb: msg`Invoices`,- to: path.to.purchaseInvoices+ breadcrumb: msg`Purchasing Invoices`,+ to: path.to.invoicingPurchasing};export async function loader({ request, params }: LoaderFunctionArgs) {@@ -44,7 +45,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {if (purchaseInvoice.error) {throw redirect(- path.to.purchaseInvoices,+ path.to.invoicingPurchasing,await flash(request,error(purchaseInvoice.error, "Failed to load purchase invoice")@@ -52,7 +53,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- const [supplier, interaction, files] = await Promise.all([+ const [supplier, interaction, files, orgHasCredits] = await Promise.all([purchaseInvoice.data?.supplierId? getSupplier(client, purchaseInvoice.data.supplierId): null,@@ -61,7 +62,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {client,companyId,purchaseInvoice.data.supplierInteractionId!- )+ ),+ getCompanyHasOpenCredits(client, companyId, "purchase")]);return {@@ -70,7 +72,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {purchaseInvoiceDelivery: purchaseInvoiceDelivery.data,files,interaction: interaction.data,- supplier: supplier?.data ?? null+ supplier: supplier?.data ?? null,+ orgHasCredits};}diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.void.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.void.tsxindex 1af237db48..008b5041a5 100644--- a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.void.tsx+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.void.tsx@@ -26,7 +26,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (!purchaseInvoice) {throw redirect(- path.to.purchaseInvoices,+ path.to.invoicingPurchasing,await flash(request,error(new Error("Purchase invoice not found"), "Invalid operation")diff --git a/apps/erp/app/routes/x+/purchase-invoice+/_layout.tsx b/apps/erp/app/routes/x+/purchase-invoice+/_layout.tsxindex f5ef19f3f5..7cb7fc1226 100644--- a/apps/erp/app/routes/x+/purchase-invoice+/_layout.tsx+++ b/apps/erp/app/routes/x+/purchase-invoice+/_layout.tsx@@ -9,9 +9,9 @@ export const meta: MetaFunction = () => {};export const handle: Handle = {- breadcrumb: msg`Purchasing`,- to: path.to.purchasing,- module: "purchasing"+ breadcrumb: msg`Invoicing`,+ to: path.to.invoicing,+ module: "invoicing"};export default function PurchaseInvoiceRoute() {diff --git a/apps/erp/app/routes/x+/purchase-invoice+/new.tsx b/apps/erp/app/routes/x+/purchase-invoice+/new.tsxindex 60e1701863..6590087445 100644--- a/apps/erp/app/routes/x+/purchase-invoice+/new.tsx+++ b/apps/erp/app/routes/x+/purchase-invoice+/new.tsx@@ -93,7 +93,7 @@ export async function action({ request }: ActionFunctionArgs) {if (result.error || !result.data) {throw redirect(- path.to.purchaseInvoices,+ path.to.invoicingPurchasing,await flash(request,error(result.error, "Failed to insert purchase invoice")diff --git a/apps/erp/app/routes/x+/purchasing+/_index.tsx b/apps/erp/app/routes/x+/purchasing+/_index.tsxindex f609cd5fbc..7dbb6e253c 100644--- a/apps/erp/app/routes/x+/purchasing+/_index.tsx+++ b/apps/erp/app/routes/x+/purchasing+/_index.tsx@@ -469,7 +469,7 @@ export default function PurchaseDashboard() {><Linkto={`${- path.to.purchaseInvoices+ path.to.invoicingPurchasing}?filter=status:in:${OPEN_INVOICE_STATUSES.join(",")}`}><Trans>View Open Invoices</Trans>diff --git a/apps/erp/app/routes/x+/purchasing+/invoices.tsx b/apps/erp/app/routes/x+/purchasing+/invoices.tsxindex 08acbb0432..b59923f13b 100644--- a/apps/erp/app/routes/x+/purchasing+/invoices.tsx+++ b/apps/erp/app/routes/x+/purchasing+/invoices.tsx@@ -1,68 +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, redirect, useLoaderData } from "react-router";-import {- getPurchaseInvoices,- PurchaseInvoicesTable-} from "~/modules/invoicing";-import type { Handle } from "~/utils/handle";+import { redirect } from "react-router";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";--export const handle: Handle = {- breadcrumb: msg`Invoices`,- to: path.to.purchaseInvoices-};+// Purchase invoices now live solely in the invoicing module. This legacy+// Purchasing-module URL redirects there, preserving any filter query string+// (e.g. ?filter=supplierId:eq:...).export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "invoicing"- });-const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const supplierId = searchParams.get("supplierId");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const purchaseInvoices = await getPurchaseInvoices(client, companyId, {- search,- supplierId,- limit,- offset,- sorts,- filters- });-- if (purchaseInvoices.error) {- redirect(- path.to.invoicing,- await flash(- request,- error(purchaseInvoices.error, "Failed to fetch purchase invoices")- )- );- }-- return {- count: purchaseInvoices.count ?? 0,- purchaseInvoices: purchaseInvoices.data ?? []- };-}--export default function PurchaseInvoicesSearchRoute() {- const { count, purchaseInvoices } = useLoaderData<typeof loader>();-- return (- <VStack spacing={0} className="h-full">- <PurchaseInvoicesTable data={purchaseInvoices} count={count} />- <Outlet />- </VStack>- );+ throw redirect(`${path.to.invoicingPurchasing}${url.search}`);}diff --git a/apps/erp/app/routes/x+/sales+/invoices.tsx b/apps/erp/app/routes/x+/sales+/invoices.tsxindex dc83e85e6f..60760ae7c8 100644--- a/apps/erp/app/routes/x+/sales+/invoices.tsx+++ b/apps/erp/app/routes/x+/sales+/invoices.tsx@@ -1,66 +1,10 @@-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, redirect, useLoaderData } from "react-router";-import { getSalesInvoices } from "~/modules/invoicing";-import SalesInvoicesTable from "~/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable";-import type { Handle } from "~/utils/handle";+import { redirect } from "react-router";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";--export const handle: Handle = {- breadcrumb: msg`Invoices`,- to: path.to.salesInvoices-};+// Sales invoices now live solely in the invoicing module. This legacy Sales-module+// URL redirects there, preserving any filter query string (e.g. ?filter=customerId:eq:...).export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "invoicing"- });-const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const customerId = searchParams.get("customerId");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const salesInvoices = await getSalesInvoices(client, companyId, {- search,- customerId,- limit,- offset,- sorts,- filters- });-- if (salesInvoices.error) {- redirect(- path.to.invoicing,- await flash(- request,- error(salesInvoices.error, "Failed to fetch sales invoices")- )- );- }-- return {- count: salesInvoices.count ?? 0,- salesInvoices: salesInvoices.data ?? []- };-}--export default function SalesInvoicesSearchRoute() {- const { count, salesInvoices } = useLoaderData<typeof loader>();-- return (- <VStack spacing={0} className="h-full">- <SalesInvoicesTable data={salesInvoices} count={count} />- <Outlet />- </VStack>- );+ throw redirect(`${path.to.invoicingSales}${url.search}`);}diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.delete.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.delete.tsxindex 053b3a46e5..42292a408d 100644--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.delete.tsx+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.delete.tsx@@ -19,7 +19,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (remove.error) {throw redirect(- path.to.salesInvoices,+ path.to.invoicingSales,await flash(request,error(remove.error, "Failed to delete sales invoice")@@ -27,5 +27,5 @@ export async function action({ request, params }: ActionFunctionArgs) {);}- throw redirect(path.to.salesInvoices);+ throw redirect(path.to.invoicingSales);}diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.details.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.details.tsxindex 7954e98ebd..474103b3e9 100644--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.details.tsx+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.details.tsx@@ -17,7 +17,9 @@ import type {SalesInvoiceShipment} from "~/modules/invoicing";import {+ getInvoiceSettlementsForInvoice,getSalesInvoice,+ InvoicePaymentsPanel,isSalesInvoiceLocked,salesInvoiceValidator,updateSalesInvoice@@ -35,23 +37,27 @@ import { requireUnlocked } from "~/utils/lockedGuard.server";import { path } from "~/utils/path";export async function loader({ request, params }: LoaderFunctionArgs) {- const { client } = await requirePermissions(request, {+ const { client, companyId } = await requirePermissions(request, {view: "invoicing"});const { invoiceId } = params;if (!invoiceId) throw new Error("Could not find invoiceId");- const invoice = await getSalesInvoice(client, invoiceId);+ const [invoice, applications] = await Promise.all([+ getSalesInvoice(client, invoiceId),+ getInvoiceSettlementsForInvoice(client, companyId, "sales", invoiceId)+ ]);if (invoice.error) {throw redirect(- path.to.salesInvoices,+ path.to.invoicingSales,await flash(request, error(invoice.error, "Failed to load sales invoice")));}return {- internalNotes: (invoice.data?.internalNotes ?? {}) as JSONContent+ internalNotes: (invoice.data?.internalNotes ?? {}) as JSONContent,+ paymentApplications: applications.data ?? []};}@@ -131,7 +137,7 @@ export async function action({ request, params }: ActionFunctionArgs) {export default function SalesInvoiceBasicRoute() {const { t } = useLingui();- const { internalNotes } = useLoaderData<typeof loader>();+ const { internalNotes, paymentApplications } = useLoaderData<typeof loader>();const { invoiceId } = useParams();if (!invoiceId) throw new Error("invoiceId not found");@@ -184,6 +190,7 @@ export default function SalesInvoiceBasicRoute() {return (<Fragment key={invoiceId}><SalesInvoiceSummary onEditShippingCost={handleEditShippingCost} />+ <InvoicePaymentsPanel rows={paymentApplications} /><OpportunityNoteskey={`notes-${initialValues.id}`}id={invoiceId}diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.tsxindex c546122906..29fdfdad9f 100644--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.tsx+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.tsx@@ -8,6 +8,7 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { Outlet, redirect, useParams } from "react-router";import { PanelProvider, ResizablePanels } from "~/components/Layout";import {+ getCompanyHasOpenCredits,getSalesInvoice,getSalesInvoiceLines,getSalesInvoiceShipment@@ -25,8 +26,8 @@ import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";export const handle: Handle = {- breadcrumb: msg`Invoices`,- to: path.to.salesInvoices+ breadcrumb: msg`Sales Invoices`,+ to: path.to.invoicingSales};export async function loader({ request, params }: LoaderFunctionArgs) {@@ -46,7 +47,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {if (salesInvoice.error) {throw redirect(- path.to.salesInvoices,+ path.to.invoicingSales,await flash(request,error(salesInvoice.error, "Failed to load sales invoice")@@ -55,15 +56,17 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}const serviceRole = getCarbonServiceRole();- const [customer, opportunity, companySettings] = await Promise.all([- salesInvoice.data?.customerId- ? getCustomer(client, salesInvoice.data.customerId)- : null,- salesInvoice.data?.opportunityId- ? getOpportunity(client, salesInvoice.data.opportunityId)- : null,- getCompanySettings(serviceRole, companyId)- ]);+ const [customer, opportunity, companySettings, orgHasCredits] =+ await Promise.all([+ salesInvoice.data?.customerId+ ? getCustomer(client, salesInvoice.data.customerId)+ : null,+ salesInvoice.data?.opportunityId+ ? getOpportunity(client, salesInvoice.data.opportunityId)+ : null,+ getCompanySettings(serviceRole, companyId),+ getCompanyHasOpenCredits(client, companyId, "sales")+ ]);const defaultCc = customer?.data?.defaultCc?.length? customer.data.defaultCc@@ -80,7 +83,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {),opportunity: opportunity?.data ?? null,customer: customer?.data ?? null,- defaultCc+ defaultCc,+ orgHasCredits};}diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.void.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.void.tsxindex c2bf520720..bfa85a720d 100644--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.void.tsx+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.void.tsx@@ -27,7 +27,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (!salesInvoice) {throw redirect(- path.to.salesInvoices,+ path.to.invoicingSales,await flash(request,error(new Error("Sales invoice not found"), "Invalid operation")diff --git a/apps/erp/app/routes/x+/sales-invoice+/_layout.tsx b/apps/erp/app/routes/x+/sales-invoice+/_layout.tsxindex dc835e7360..f8cc510572 100644--- a/apps/erp/app/routes/x+/sales-invoice+/_layout.tsx+++ b/apps/erp/app/routes/x+/sales-invoice+/_layout.tsx@@ -9,9 +9,9 @@ export const meta: MetaFunction = () => {};export const handle: Handle = {- breadcrumb: msg`Sales`,- to: path.to.sales,- module: "sales"+ breadcrumb: msg`Invoicing`,+ to: path.to.invoicing,+ module: "invoicing"};export default function SalesInvoiceRoute() {diff --git a/apps/erp/app/routes/x+/sales-invoice+/new.tsx b/apps/erp/app/routes/x+/sales-invoice+/new.tsxindex 5234835dd5..37289f7112 100644--- a/apps/erp/app/routes/x+/sales-invoice+/new.tsx+++ b/apps/erp/app/routes/x+/sales-invoice+/new.tsx@@ -114,7 +114,7 @@ export async function action({ request }: ActionFunctionArgs) {if (result.error || !result.data) {throw redirect(- path.to.salesInvoices,+ path.to.invoicingSales,await flash(request,error(result.error, "Failed to insert sales invoice")diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 754913c7ae..a94a275628 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -986,6 +986,8 @@ export const path = {stockMovements: `${x}/inventory/stock-movements`,inventorySettings: `${x}/settings/inventory`,invoicing: `${x}/invoicing`,+ invoicingPurchasing: `${x}/invoicing/purchasing`,+ invoicingSales: `${x}/invoicing/sales`,issues: `${x}/quality/issues`,issue: (id: string) => generatePath(`${x}/issue/${id}`),issueDetails: (id: string) => generatePath(`${x}/issue/${id}/details`),@@ -1377,6 +1379,20 @@ export const path = {partner: (id: string, abilityId: string) =>generatePath(`${x}/resources/partners/${id}/${abilityId}`),partners: `${x}/resources/partners`,+ payment: (id: string) => generatePath(`${x}/payments/${id}`),+ paymentApplicationsSet: (id: string) =>+ generatePath(`${x}/payments/${id}/applications/set`),+ paymentCreditsSet: (id: string) =>+ generatePath(`${x}/payments/${id}/credits/set`),+ paymentDelete: (id: string) => generatePath(`${x}/payments/${id}/delete`),+ paymentNew: `${x}/payments/new`,+ paymentPost: (id: string) => generatePath(`${x}/payments/${id}/post`),+ paymentVoid: (id: string) => generatePath(`${x}/payments/${id}/void`),+ payments: `${x}/invoicing/payments`,+ receivables: `${x}/invoicing/receivables`,+ receivablesAdjust: `${x}/invoicing/receivables/adjust`,+ payables: `${x}/invoicing/payables`,+ payablesAdjust: `${x}/invoicing/payables/adjust`,paymentTerm: (id: string) =>generatePath(`${x}/accounting/payment-terms/${id}`),paymentTerms: `${x}/accounting/payment-terms`,@@ -1450,7 +1466,6 @@ export const path = {generatePath(`${x}/purchase-invoice/${id}/status`),purchaseInvoiceVoid: (id: string) =>generatePath(`${x}/purchase-invoice/${id}/void`),- purchaseInvoices: `${x}/purchasing/invoices`,purchaseOrder: (id: string) => generatePath(`${x}/purchase-order/${id}`),purchaseOrderDuplicate: (id: string) =>generatePath(`${x}/purchase-order/${id}/duplicate`),@@ -1592,7 +1607,14 @@ export const path = {generatePath(`${x}/sales-invoice/${id}/status`),salesInvoiceVoid: (id: string) =>generatePath(`${x}/sales-invoice/${id}/void`),- salesInvoices: `${x}/sales/invoices`,+ // Credit / Debit memos — payment-shaped documents (the `memo` table). The+ // list lives in the invoicing nav beside Payments; details mirror payments.+ memo: (id: string) => generatePath(`${x}/credits/${id}`),+ memoDelete: (id: string) => generatePath(`${x}/credits/${id}/delete`),+ memoNew: `${x}/credits/new`,+ memoPost: (id: string) => generatePath(`${x}/credits/${id}/post`),+ memoVoid: (id: string) => generatePath(`${x}/credits/${id}/void`),+ memos: `${x}/invoicing/credits`,salesOrder: (id: string) => generatePath(`${x}/sales-order/${id}`),salesOrderConfirm: (id: string) =>generatePath(`${x}/sales-order/${id}/confirm`),diff --git a/apps/erp/vitest.config.ts b/apps/erp/vitest.config.tsindex 54ab7b7624..c86e50dba2 100644--- a/apps/erp/vitest.config.ts+++ b/apps/erp/vitest.config.ts@@ -6,6 +6,20 @@ export default defineConfig({},test: {include: ["app/**/*.test.ts", "app/**/*.test.tsx", "test/**/*.test.ts"],- passWithNoTests: true+ passWithNoTests: true,+ // @carbon/env throws at import time when these are unset; tests that+ // transitively import a module barrel (e.g. modules/shared) hit it.+ // Stub values that satisfy "is set" without enabling any side-effects.+ env: {+ INNGEST_SIGNING_KEY: "test",+ INNGEST_EVENT_KEY: "test",+ SUPABASE_URL: "http://localhost",+ SUPABASE_ANON_KEY: "test",+ SUPABASE_SERVICE_ROLE_KEY: "test",+ SUPABASE_API_URL: "http://localhost",+ SUPABASE_DB_URL: "postgresql://localhost",+ SESSION_SECRET: "test",+ REDIS_URL: "redis://localhost"+ }}});diff --git a/apps/mes/app/components/ItemThumbnail.tsx b/apps/mes/app/components/ItemThumbnail.tsxindex 708b91980d..5125d3d4f8 100644--- a/apps/mes/app/components/ItemThumbnail.tsx+++ b/apps/mes/app/components/ItemThumbnail.tsx@@ -1,6 +1,6 @@import { cn } from "@carbon/react";import { cva } from "class-variance-authority";-import { LuSquareStack } from "react-icons/lu";+import { LuBlocks } from "react-icons/lu";import { getPrivateUrl } from "~/utils/path";import { MethodItemTypeIcon } from "./Icons";@@ -90,7 +90,7 @@ const ItemThumbnail = ({{type ? (<MethodItemTypeIcon className={iconVariants({ size })} type={type} />) : (- <LuSquareStack className={iconVariants({ size })} />+ <LuBlocks className={iconVariants({ size })} />)}</div>);diff --git a/llm/tasks/memo-refactor-plan.md b/llm/tasks/memo-refactor-plan.mdnew file mode 100644index 0000000000..822c423345--- /dev/null+++ b/llm/tasks/memo-refactor-plan.md@@ -0,0 +1,141 @@+# Refactor: Credit/Debit Memos → payment-shaped "Credits & Debits"++## Goal+Stop modeling a memo as "a salesInvoice/purchaseInvoice row (`invoiceType`) with line+items." Model it like a **payment**: a party-level, non-cash settlement document =+`party + amount + reason GL account + applications to invoices`. No line builder, no+items/assets. One nav concept (a customer or supplier can have credits or debits),+sitting beside Payments — not buried in the AR/AP groups.++## Working principle (per branch state)+The branch's payment/memo migrations (`20260622*`, `20260623*`) are **unmerged and not in+production**, so we **edit them in place** and re-run a DB reset — no new add-then-remove+migrations. All schema changes below are edits to those existing files.++---++## DECISIONS (locked)+1. **Parallel `memo` table** (Option B) — a credit/debit memo isn't literally a "payment".+2. **Separate numbering** — own sequences (`CR-…` for credits, `DR-…` for debits), not `PAY-`.+3. **Expose all four** party×direction combos.++---++## Target model (Option B: `memo` table)+- New `memo` table mirroring `payment` but with `reasonAccount` (FK→account, the+ returns/allowance/adjustment GL) **instead of** `bankAccount`. Columns: `id`, `memoId`+ (seq), `companyId`, `customerId` XOR `supplierId` (party → AR vs AP control), `direction+ memoDirection` (`Credit`|`Debit`), `amount`, `reasonAccount`, `currencyCode`,+ `exchangeRate`, `status memoStatus` (`Draft|Posted|Voided`), `memoDate`, `postingDate`,+ `journalId`, posted/voided audit, `reference`, `notes`, audit, `customFields`.+- **The four combos by control-account sign:**+ | Combo | Party | Direction | Effect | Journal |+ |---|---|---|---|---|+ | AR Credit Memo | Customer | Credit | AR ↓ (owe us less) | DR reason / CR AR |+ | AR Debit Memo | Customer | Debit | AR ↑ (owe us more) | DR AR / CR reason |+ | AP Debit Memo | Supplier | Debit | AP ↓ (we owe less) | DR AP / CR reason |+ | AP Credit Memo | Supplier | Credit | AP ↑ (we owe more) | DR reason / CR AP |+- **Numbering:** two sequences (`creditMemo` → `CR-%{yyyy}-%{mm}-`, `debitMemo` →+ `DR-%{yyyy}-%{mm}-`), seeded in `seed.data.ts` + migration backfill (replacing the+ retired `salesCreditMemo`/`purchaseDebitMemo`).++## ⚠️ The one place "all four" diverges from copy-payments: reducers vs increasers+Two combos **reduce** the party balance (AR Credit, AP Debit) — these behave like payments:+they have an **apply table** and settle open invoices, or sit as an on-account credit.+The other two **increase** the balance (AR Debit, AP Credit) — these are **new open items**+the counterparty must settle (like a mini-invoice). Consequences:+- The **apply table only renders for the reducer direction** at creation.+- An increaser memo is itself a settleable open item, so **`invoiceSettlement.target` must+ generalize** to point at an invoice **or a memo** (add `targetMemoId`), so a payment or a+ reducer-memo can settle a debit/credit memo. (The reducer's apply list = open invoices ++ opposite-direction open memos.)+- The subledger/tie-out signs each open memo: reducers −, increasers +.++This is the real added scope of exposing all four. It's the right general model (it's how+Oracle AR/AP net any two open items), just more than a literal payments copy.++## Settlement primitive+- `invoiceSettlement` **source**: `paymentId` XOR **`memoId`** (replaces the retired+ `sourceSalesInvoiceId`/`sourcePurchaseInvoiceId`).+- `invoiceSettlement` **target**: `targetSalesInvoiceId` XOR `targetPurchaseInvoiceId` XOR+ **`targetMemoId`** (new — lets credits/payments settle an increaser memo).++## Subledger / GL consequences (important)+- Memos are **no longer invoice rows**, so they leave the `salesInvoices`/`purchaseInvoices`+ views. The "memo signed negative as an open invoice" logic in the tie-out RPCs is+ **removed**; instead memos are subtracted as **unapplied credits** — the same way the+ tie-out already subtracts unapplied payment cash. (Cleaner and symmetric.)+- Posting (`post-payment`): for `kind!='Cash'`, book **DR reasonAccount / CR AR** (Credit)+ or **DR AP / CR reasonAccount** (Debit) instead of the bank line. The per-application+ control/FX logic is unchanged. (Discount/write-off: memos don't carry them — keep the+ existing `invoiceSettlement` check that gates discount/write-off to cash payments.)++---++## Work plan++### 1. Schema (edit existing migrations, then reset)+- `20260622143012_ar-ap-payments.sql`:+ - **Remove** `invoiceType` columns + `salesInvoiceType`/`purchaseInvoiceType` enums.+ - **Remove** `invoiceSettlement.sourceSalesInvoiceId`/`sourcePurchaseInvoiceId` + their+ checks; the source is just `paymentId` (+ keep target sales/purchase XOR).+ - **Add** `payment.kind`, `payment.reasonAccount`, make `bankAccount` nullable + a check+ (`kind='Cash'` ⇒ bankAccount NOT NULL; else reasonAccount NOT NULL).+ - Repurpose the `salesCreditMemo`/`purchaseDebitMemo` sequences → a single memo sequence+ (or reuse the `payment` sequence; decide numbering, e.g. `CR-`/`DR-` by kind).+ - Keep the `'Credit Memo'`/`'Debit Memo'` `journalEntrySourceType` values for posting.+- `20260623151204_invoice-balance-from-line-total.sql`: drop the memo-settlement branch+ that read `sourceSalesInvoiceId` memos; balance = total − settled(payments only).+- `20260623154712_tie-out-aging-from-view-total.sql`: remove memo-as-negative-invoice+ signing; subtract unapplied memo credits alongside unapplied payment cash.+- `seed.data.ts`: drop the CM/DM sequences (or replace with the memo sequence).++### 2. Edge function `post-payment`+- Branch on `kind`: cash → existing DR bank/CR control; credit/debit → DR/CR `reasonAccount`+ vs control. Reuse the signed-debit balance check + FX plug unchanged.++### 3. Service + validators (`invoicing.service.ts` / `invoicing.models.ts`)+- Extend `paymentValidator`: `kind`, `reasonAccount`, make `bankAccount` conditionally+ required (refine on `kind`). Retire `creditMemoValidator`/`debitMemoValidator`,+ `creditMemoStatusType`/`debitMemoStatusType`, `isCreditMemoLocked`/`isDebitMemoLocked`.+- `getPayments`: add `kind` filter. Add `getMemos` = `getPayments` filtered to Credit/Debit+ (or just a `kind` filter param). Retire `getCreditMemos`/`getDebitMemos`.+- `insertSalesInvoice`/`insertPurchaseInvoice`: remove the `invoiceType` memo branch.++### 4. UI (reuse, don't copy)+- **Reuse `PaymentApplyTable` verbatim** (apply mechanics identical).+- `PaymentForm`: add `kind`; when memo, swap the **Bank Account** field for a **Reason+ (GL account)** field, hide cash-only bits. One component, conditional fields.+- A `CreditsTable` (or reuse `PaymentsTable` with a `kind` filter) for the list.+- Detail route reuses `PaymentHeader`/`PaymentSummary`/`PaymentApplications`/apply table.++### 5. Routes+- New `x+/credits+/` (or reuse `payments+` with a `kind` query) + `invoicing+/credits.tsx`+ list. Mirror the payment routes (new/$id/post/void/delete/applications.set).+- Path helpers: add `credit*`/`memo*` (or generalize the payment helpers with a kind).++### 6. Navigation+- One **"Credits & Debits"** entry beside **Payments** (its own group), filterable by party+ type + direction — mirroring the Payments list filters.+- **Remove** "Credit Memos" (AR group) and "Debit Memos" (AP group) entries.++### 7. RETIRE (delete)+- `x+/credit-memo+/` (14 files), `x+/debit-memo+/` (14 files),+ `invoicing+/credit-memos.tsx`, `invoicing+/debit-memos.tsx`.+- `ui/CreditMemo/` (12 files), `ui/DebitMemo/` (12 files).+- `creditMemo*` + `debitMemo*` path helpers.+- The retired validators/enums/service fns above.++### 8. Verify (reset + the SQL harness from the stress test)+- `crbn` reset (picks up edited migrations + seed).+- Re-run the controlled rolled-back SQL scenarios: derived balance/status, FX generated+ column, **tie-out variance 0 with an unapplied memo credit** (the new subledger path),+ AR + AP. Then a UI pass: create a credit (customer + amount + reason), apply, post.++## Risks / open questions+- **Numbering**: keep separate memo numbers (CR-/DR-) or fold into PAY-? (Decision 1-adjacent.)+- **Itemized returns** are explicitly **out of scope** here (separate return/RMA concern).+- **AR debit / AP credit** memos (the other two combos) come free once `kind`+party is the+ model — confirm we want all four exposed now or just the two we have today.+- Editing the merged-in `20260623*` migrations: they were authored by other work this+ branch absorbed — make sure reshaping them doesn't break their non-memo intent.diff --git a/packages/database/src/seed-dev.ts b/packages/database/src/seed-dev.tsindex 9820129054..4358ad082a 100644--- a/packages/database/src/seed-dev.ts+++ b/packages/database/src/seed-dev.ts@@ -425,10 +425,13 @@ async function seedDev() {"bankLocalCurrencyAccount", "bankForeignCurrencyAccount", "prepaymentAccount","payablesAccount", "goodsReceivedNotInvoicedAccount", "inventoryShippedNotInvoicedAccount","salesTaxPayableAccount", "purchaseTaxPayableAccount", "reverseChargeSalesTaxPayableAccount",- "retainedEarningsAccount", "currencyTranslationAccount", "companyId"+ "retainedEarningsAccount", "currencyTranslationAccount",+ "customerWriteOffAccount", "supplierWriteOffAccount",+ "realizedExchangeGainAccount", "realizedExchangeLossAccount", "companyId") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19,- $20, $21, $22, $23, $24, $25, $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40+ $20, $21, $22, $23, $24, $25, $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40,+ $41, $42, $43, $44)`,[resolveAccountId(accountDefaults.salesAccount),@@ -474,6 +477,10 @@ async function seedDev() {resolveAccountId(accountDefaults.reverseChargeSalesTaxPayableAccount),resolveAccountId(accountDefaults.retainedEarningsAccount),resolveAccountId(accountDefaults.currencyTranslationAccount),+ resolveAccountId(accountDefaults.customerWriteOffAccount),+ resolveAccountId(accountDefaults.supplierWriteOffAccount),+ resolveAccountId(accountDefaults.realizedExchangeGainAccount),+ resolveAccountId(accountDefaults.realizedExchangeLossAccount),companyId]);diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 22bd406b07..090fb5ba11 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -342,6 +342,7 @@ export type Database = {costOfGoodsSoldAccount: stringcurrencyTranslationAccount: stringcustomerPaymentDiscountAccount: string+ customerWriteOffAccount: stringdeferredTaxExpenseAccountId: string | nulldeferredTaxLiabilityAccountId: string | nullgoodsReceivedNotInvoicedAccount: string@@ -360,6 +361,8 @@ export type Database = {prepaymentAccount: stringpurchaseTaxPayableAccount: stringpurchaseVarianceAccount: string+ realizedExchangeGainAccount: string+ realizedExchangeLossAccount: stringreceivablesAccount: stringretainedEarningsAccount: stringreverseChargeSalesTaxPayableAccount: string@@ -370,6 +373,7 @@ export type Database = {serviceChargeAccount: stringsubcontractingVarianceAccount: stringsupplierPaymentDiscountAccount: string+ supplierWriteOffAccount: stringupdatedBy: string | nullworkInProgressAccount: string}@@ -387,6 +391,7 @@ export type Database = {costOfGoodsSoldAccount: stringcurrencyTranslationAccount: stringcustomerPaymentDiscountAccount: string+ customerWriteOffAccount: stringdeferredTaxExpenseAccountId?: string | nulldeferredTaxLiabilityAccountId?: string | nullgoodsReceivedNotInvoicedAccount: string@@ -405,6 +410,8 @@ export type Database = {prepaymentAccount: stringpurchaseTaxPayableAccount: stringpurchaseVarianceAccount: string+ realizedExchangeGainAccount: string+ realizedExchangeLossAccount: stringreceivablesAccount: stringretainedEarningsAccount: stringreverseChargeSalesTaxPayableAccount: string@@ -415,6 +422,7 @@ export type Database = {serviceChargeAccount: stringsubcontractingVarianceAccount: stringsupplierPaymentDiscountAccount: string+ supplierWriteOffAccount: stringupdatedBy?: string | nullworkInProgressAccount: string}@@ -432,6 +440,7 @@ export type Database = {costOfGoodsSoldAccount?: stringcurrencyTranslationAccount?: stringcustomerPaymentDiscountAccount?: string+ customerWriteOffAccount?: stringdeferredTaxExpenseAccountId?: string | nulldeferredTaxLiabilityAccountId?: string | nullgoodsReceivedNotInvoicedAccount?: string@@ -450,6 +459,8 @@ export type Database = {prepaymentAccount?: stringpurchaseTaxPayableAccount?: stringpurchaseVarianceAccount?: string+ realizedExchangeGainAccount?: string+ realizedExchangeLossAccount?: stringreceivablesAccount?: stringretainedEarningsAccount?: stringreverseChargeSalesTaxPayableAccount?: string@@ -460,6 +471,7 @@ export type Database = {serviceChargeAccount?: stringsubcontractingVarianceAccount?: stringsupplierPaymentDiscountAccount?: string+ supplierWriteOffAccount?: stringupdatedBy?: string | nullworkInProgressAccount?: string}@@ -632,6 +644,20 @@ export type Database = {referencedRelation: "accounts"referencedColumns: ["id"]},+ {+ foreignKeyName: "accountDefault_customerWriteOffAccount_fkey"+ columns: ["customerWriteOffAccount"]+ isOneToOne: false+ referencedRelation: "account"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountDefault_customerWriteOffAccount_fkey"+ columns: ["customerWriteOffAccount"]+ isOneToOne: false+ referencedRelation: "accounts"+ referencedColumns: ["id"]+ },{foreignKeyName: "accountDefault_deferredTaxExpenseAccountId_fkey"columns: ["deferredTaxExpenseAccountId"]@@ -912,6 +938,34 @@ export type Database = {referencedRelation: "accounts"referencedColumns: ["id"]},+ {+ foreignKeyName: "accountDefault_realizedExchangeGainAccount_fkey"+ columns: ["realizedExchangeGainAccount"]+ isOneToOne: false+ referencedRelation: "account"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountDefault_realizedExchangeGainAccount_fkey"+ columns: ["realizedExchangeGainAccount"]+ isOneToOne: false+ referencedRelation: "accounts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountDefault_realizedExchangeLossAccount_fkey"+ columns: ["realizedExchangeLossAccount"]+ isOneToOne: false+ referencedRelation: "account"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountDefault_realizedExchangeLossAccount_fkey"+ columns: ["realizedExchangeLossAccount"]+ isOneToOne: false+ referencedRelation: "accounts"+ referencedColumns: ["id"]+ },{foreignKeyName: "accountDefault_receivablesAccount_fkey"columns: ["receivablesAccount"]@@ -1052,6 +1106,20 @@ export type Database = {referencedRelation: "accounts"referencedColumns: ["id"]},+ {+ foreignKeyName: "accountDefault_supplierWriteOffAccount_fkey"+ columns: ["supplierWriteOffAccount"]+ isOneToOne: false+ referencedRelation: "account"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountDefault_supplierWriteOffAccount_fkey"+ columns: ["supplierWriteOffAccount"]+ isOneToOne: false+ referencedRelation: "accounts"+ referencedColumns: ["id"]+ },{foreignKeyName: "accountDefault_updatedBy_fkey"columns: ["updatedBy"]@@ -4128,18 +4196,21 @@ export type Database = {contractorAbility: {Row: {abilityId: string+ companyId: stringcontractorId: stringcreatedAt: stringcreatedBy: string}Insert: {abilityId: string+ companyId: stringcontractorId: stringcreatedAt?: stringcreatedBy: string}Update: {abilityId?: string+ companyId?: stringcontractorId?: stringcreatedAt?: stringcreatedBy?: string@@ -5058,6 +5129,7 @@ export type Database = {}customerContact: {Row: {+ companyId: stringcontactId: stringcustomerId: stringcustomerLocationId: string | null@@ -5067,6 +5139,7 @@ export type Database = {userId: string | null}Insert: {+ companyId: stringcontactId: stringcustomerId: stringcustomerLocationId?: string | null@@ -5076,6 +5149,7 @@ export type Database = {userId?: string | null}Update: {+ companyId?: stringcontactId?: stringcustomerId?: stringcustomerLocationId?: string | null@@ -5525,6 +5599,7 @@ export type Database = {customerLocation: {Row: {addressId: string+ companyId: stringcustomerId: stringcustomFields: Json | nullid: string@@ -5533,6 +5608,7 @@ export type Database = {}Insert: {addressId: string+ companyId: stringcustomerId: stringcustomFields?: Json | nullid?: string@@ -5541,6 +5617,7 @@ export type Database = {}Update: {addressId?: string+ companyId?: stringcustomerId?: stringcustomFields?: Json | nullid?: string@@ -8237,16 +8314,19 @@ export type Database = {}documentLabel: {Row: {+ companyId: stringdocumentId: stringlabel: stringuserId: string}Insert: {+ companyId: stringdocumentId: stringlabel: stringuserId: string}Update: {+ companyId?: stringdocumentId?: stringlabel?: stringuserId?: string@@ -8590,6 +8670,7 @@ export type Database = {}documentTransaction: {Row: {+ companyId: stringcreatedAt: stringdocumentId: stringid: string@@ -8597,6 +8678,7 @@ export type Database = {userId: string}Insert: {+ companyId: stringcreatedAt?: stringdocumentId: stringid?: string@@ -8604,6 +8686,7 @@ export type Database = {userId: string}Update: {+ companyId?: stringcreatedAt?: stringdocumentId?: stringid?: string@@ -9035,16 +9118,19 @@ export type Database = {}employeeShift: {Row: {+ companyId: stringemployeeId: stringid: stringshiftId: string}Insert: {+ companyId: stringemployeeId: stringid?: stringshiftId: string}Update: {+ companyId?: stringemployeeId?: stringid?: stringshiftId?: string@@ -13672,6 +13758,193 @@ export type Database = {},]}+ invoiceSettlement: {+ Row: {+ appliedAmount: number+ appliedDate: string+ appliedViaPaymentId: string | null+ companyId: string+ createdAt: string+ createdBy: string+ discountAmount: number+ fxGainLossAmount: number | null+ id: string+ memoId: string | null+ paymentId: string | null+ sourceExchangeRate: number+ targetExchangeRate: number+ targetMemoId: string | null+ targetPurchaseInvoiceId: string | null+ targetSalesInvoiceId: string | null+ writeOffAmount: number+ }+ Insert: {+ appliedAmount: number+ appliedDate: string+ appliedViaPaymentId?: string | null+ companyId: string+ createdAt?: string+ createdBy: string+ discountAmount?: number+ fxGainLossAmount?: number | null+ id?: string+ memoId?: string | null+ paymentId?: string | null+ sourceExchangeRate: number+ targetExchangeRate: number+ targetMemoId?: string | null+ targetPurchaseInvoiceId?: string | null+ targetSalesInvoiceId?: string | null+ writeOffAmount?: number+ }+ Update: {+ appliedAmount?: number+ appliedDate?: string+ appliedViaPaymentId?: string | null+ companyId?: string+ createdAt?: string+ createdBy?: string+ discountAmount?: number+ fxGainLossAmount?: number | null+ id?: string+ memoId?: string | null+ paymentId?: string | null+ sourceExchangeRate?: number+ targetExchangeRate?: number+ targetMemoId?: string | null+ targetPurchaseInvoiceId?: string | null+ targetSalesInvoiceId?: string | null+ writeOffAmount?: number+ }+ Relationships: [+ {+ foreignKeyName: "invoiceSettlement_appliedViaPaymentId_fkey"+ columns: ["appliedViaPaymentId"]+ isOneToOne: false+ referencedRelation: "payment"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "invoiceSettlement_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "invoiceSettlement_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "invoiceSettlement_memoId_fkey"+ columns: ["memoId"]+ isOneToOne: false+ referencedRelation: "memo"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_paymentId_fkey"+ columns: ["paymentId"]+ isOneToOne: false+ referencedRelation: "payment"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_targetMemoId_fkey"+ columns: ["targetMemoId"]+ isOneToOne: false+ referencedRelation: "memo"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_targetPurchaseInvoiceId_fkey"+ columns: ["targetPurchaseInvoiceId"]+ isOneToOne: false+ referencedRelation: "purchaseInvoice"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_targetPurchaseInvoiceId_fkey"+ columns: ["targetPurchaseInvoiceId"]+ isOneToOne: false+ referencedRelation: "purchaseInvoices"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_targetSalesInvoiceId_fkey"+ columns: ["targetSalesInvoiceId"]+ isOneToOne: false+ referencedRelation: "salesInvoice"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_targetSalesInvoiceId_fkey"+ columns: ["targetSalesInvoiceId"]+ isOneToOne: false+ referencedRelation: "salesInvoiceLocations"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_targetSalesInvoiceId_fkey"+ columns: ["targetSalesInvoiceId"]+ isOneToOne: false+ referencedRelation: "salesInvoices"+ referencedColumns: ["id"]+ },+ ]+ }item: {Row: {active: boolean@@ -21805,6 +22078,350 @@ export type Database = {},]}+ memo: {+ Row: {+ amount: number+ companyId: string+ createdAt: string+ createdBy: string+ currencyCode: string+ customerId: string | null+ customFields: Json | null+ direction: Database["public"]["Enums"]["memoDirection"]+ exchangeRate: number+ id: string+ journalId: string | null+ memoDate: string+ memoId: string+ notes: string | null+ postedAt: string | null+ postedBy: string | null+ postingDate: string | null+ reasonAccount: string | null+ reference: string | null+ status: Database["public"]["Enums"]["memoStatus"]+ supplierId: string | null+ updatedAt: string | null+ updatedBy: string | null+ voidedAt: string | null+ voidedBy: string | null+ }+ Insert: {+ amount: number+ companyId: string+ createdAt?: string+ createdBy: string+ currencyCode: string+ customerId?: string | null+ customFields?: Json | null+ direction: Database["public"]["Enums"]["memoDirection"]+ exchangeRate?: number+ id?: string+ journalId?: string | null+ memoDate: string+ memoId: string+ notes?: string | null+ postedAt?: string | null+ postedBy?: string | null+ postingDate?: string | null+ reasonAccount?: string | null+ reference?: string | null+ status?: Database["public"]["Enums"]["memoStatus"]+ supplierId?: string | null+ updatedAt?: string | null+ updatedBy?: string | null+ voidedAt?: string | null+ voidedBy?: string | null+ }+ Update: {+ amount?: number+ companyId?: string+ createdAt?: string+ createdBy?: string+ currencyCode?: string+ customerId?: string | null+ customFields?: Json | null+ direction?: Database["public"]["Enums"]["memoDirection"]+ exchangeRate?: number+ id?: string+ journalId?: string | null+ memoDate?: string+ memoId?: string+ notes?: string | null+ postedAt?: string | null+ postedBy?: string | null+ postingDate?: string | null+ reasonAccount?: string | null+ reference?: string | null+ status?: Database["public"]["Enums"]["memoStatus"]+ supplierId?: string | null+ updatedAt?: string | null+ updatedBy?: string | null+ voidedAt?: string | null+ voidedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "memo_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "memo_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "memo_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "memo_currencyCode_fkey"+ columns: ["currencyCode"]+ isOneToOne: false+ referencedRelation: "currencyCode"+ referencedColumns: ["code"]+ },+ {+ foreignKeyName: "memo_customerId_fkey"+ columns: ["customerId"]+ isOneToOne: false+ referencedRelation: "customer"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_customerId_fkey"+ columns: ["customerId"]+ isOneToOne: false+ referencedRelation: "customers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_customerId_fkey"+ columns: ["customerId"]+ isOneToOne: false+ referencedRelation: "salesOrderCustomers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_journalId_fkey"+ columns: ["journalId"]+ isOneToOne: false+ referencedRelation: "journal"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_journalId_fkey"+ columns: ["journalId"]+ isOneToOne: false+ referencedRelation: "journalEntries"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_postedBy_fkey"+ columns: ["postedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_postedBy_fkey"+ columns: ["postedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_postedBy_fkey"+ columns: ["postedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_postedBy_fkey"+ columns: ["postedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_postedBy_fkey"+ columns: ["postedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "memo_reasonAccount_fkey"+ columns: ["reasonAccount"]+ isOneToOne: false+ referencedRelation: "account"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_reasonAccount_fkey"+ columns: ["reasonAccount"]+ isOneToOne: false+ referencedRelation: "accounts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "contractors"+ referencedColumns: ["supplierId"]+ },+ {+ foreignKeyName: "memo_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "partners"+ referencedColumns: ["supplierId"]+ },+ {+ foreignKeyName: "memo_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "purchaseOrderSuppliers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "supplier"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "suppliers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "memo_voidedBy_fkey"+ columns: ["voidedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_voidedBy_fkey"+ columns: ["voidedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_voidedBy_fkey"+ columns: ["voidedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_voidedBy_fkey"+ columns: ["voidedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_voidedBy_fkey"+ columns: ["voidedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }methodMaterial: {Row: {companyId: string@@ -27488,6 +28105,350 @@ export type Database = {},]}+ payment: {+ Row: {+ bankAccount: string+ companyId: string+ createdAt: string+ createdBy: string+ currencyCode: string+ customerId: string | null+ customFields: Json | null+ exchangeRate: number+ id: string+ journalId: string | null+ memo: string | null+ paymentDate: string+ paymentId: string+ paymentType: Database["public"]["Enums"]["paymentType"]+ postedAt: string | null+ postedBy: string | null+ postingDate: string | null+ reference: string | null+ status: Database["public"]["Enums"]["paymentStatus"]+ supplierId: string | null+ totalAmount: number+ updatedAt: string | null+ updatedBy: string | null+ voidedAt: string | null+ voidedBy: string | null+ }+ Insert: {+ bankAccount: string+ companyId: string+ createdAt?: string+ createdBy: string+ currencyCode: string+ customerId?: string | null+ customFields?: Json | null+ exchangeRate?: number+ id?: string+ journalId?: string | null+ memo?: string | null+ paymentDate: string+ paymentId: string+ paymentType: Database["public"]["Enums"]["paymentType"]+ postedAt?: string | null+ postedBy?: string | null+ postingDate?: string | null+ reference?: string | null+ status?: Database["public"]["Enums"]["paymentStatus"]+ supplierId?: string | null+ totalAmount: number+ updatedAt?: string | null+ updatedBy?: string | null+ voidedAt?: string | null+ voidedBy?: string | null+ }+ Update: {+ bankAccount?: string+ companyId?: string+ createdAt?: string+ createdBy?: string+ currencyCode?: string+ customerId?: string | null+ customFields?: Json | null+ exchangeRate?: number+ id?: string+ journalId?: string | null+ memo?: string | null+ paymentDate?: string+ paymentId?: string+ paymentType?: Database["public"]["Enums"]["paymentType"]+ postedAt?: string | null+ postedBy?: string | null+ postingDate?: string | null+ reference?: string | null+ status?: Database["public"]["Enums"]["paymentStatus"]+ supplierId?: string | null+ totalAmount?: number+ updatedAt?: string | null+ updatedBy?: string | null+ voidedAt?: string | null+ voidedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "payment_bankAccount_fkey"+ columns: ["bankAccount"]+ isOneToOne: false+ referencedRelation: "account"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_bankAccount_fkey"+ columns: ["bankAccount"]+ isOneToOne: false+ referencedRelation: "accounts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "payment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "payment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "payment_currencyCode_fkey"+ columns: ["currencyCode"]+ isOneToOne: false+ referencedRelation: "currencyCode"+ referencedColumns: ["code"]+ },+ {+ foreignKeyName: "payment_customerId_fkey"+ columns: ["customerId"]+ isOneToOne: false+ referencedRelation: "customer"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_customerId_fkey"+ columns: ["customerId"]+ isOneToOne: false+ referencedRelation: "customers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_customerId_fkey"+ columns: ["customerId"]+ isOneToOne: false+ referencedRelation: "salesOrderCustomers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_journalId_fkey"+ columns: ["journalId"]+ isOneToOne: false+ referencedRelation: "journal"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_journalId_fkey"+ columns: ["journalId"]+ isOneToOne: false+ referencedRelation: "journalEntries"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_postedBy_fkey"+ columns: ["postedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_postedBy_fkey"+ columns: ["postedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_postedBy_fkey"+ columns: ["postedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_postedBy_fkey"+ columns: ["postedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_postedBy_fkey"+ columns: ["postedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "payment_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "contractors"+ referencedColumns: ["supplierId"]+ },+ {+ foreignKeyName: "payment_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "partners"+ referencedColumns: ["supplierId"]+ },+ {+ foreignKeyName: "payment_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "purchaseOrderSuppliers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "supplier"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "suppliers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "payment_voidedBy_fkey"+ columns: ["voidedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_voidedBy_fkey"+ columns: ["voidedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_voidedBy_fkey"+ columns: ["voidedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_voidedBy_fkey"+ columns: ["voidedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_voidedBy_fkey"+ columns: ["voidedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }paymentTerm: {Row: {active: boolean@@ -28148,18 +29109,21 @@ export type Database = {}pickingListLineTrackedEntity: {Row: {+ companyId: stringpickingListLineId: stringquantity: numberquantityPicked: numbertrackedEntityId: string}Insert: {+ companyId: stringpickingListLineId: stringquantity: numberquantityPicked?: numbertrackedEntityId: string}Update: {+ companyId?: stringpickingListLineId?: stringquantity?: numberquantityPicked?: number@@ -29839,7 +30803,6 @@ export type Database = {purchaseInvoice: {Row: {assignee: string | null- balance: numbercompanyId: stringcreatedAt: stringcreatedBy: string@@ -29873,7 +30836,6 @@ export type Database = {}Insert: {assignee?: string | null- balance?: numbercompanyId: stringcreatedAt?: stringcreatedBy: string@@ -29907,7 +30869,6 @@ export type Database = {}Update: {assignee?: string | null- balance?: numbercompanyId?: stringcreatedAt?: stringcreatedBy?: string@@ -30755,48 +31716,9 @@ export type Database = {},]}- purchaseInvoicePaymentRelation: {- Row: {- id: string- invoiceId: string- paymentId: string- }- Insert: {- id?: string- invoiceId: string- paymentId: string- }- Update: {- id?: string- invoiceId?: string- paymentId?: string- }- Relationships: [- {- foreignKeyName: "purchasePayments_invoiceId_fkey"- columns: ["invoiceId"]- isOneToOne: false- referencedRelation: "purchaseInvoice"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayments_invoiceId_fkey"- columns: ["invoiceId"]- isOneToOne: false- referencedRelation: "purchaseInvoices"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayments_paymentId_fkey"- columns: ["paymentId"]- isOneToOne: false- referencedRelation: "purchasePayment"- referencedColumns: ["id"]- },- ]- }purchaseInvoicePriceChange: {Row: {+ companyId: stringid: stringinvoiceId: stringinvoiceLineId: string@@ -30807,6 +31729,7 @@ export type Database = {updatedBy: string}Insert: {+ companyId: stringid?: stringinvoiceId: stringinvoiceLineId: string@@ -30817,6 +31740,7 @@ export type Database = {updatedBy: string}Update: {+ companyId?: stringid?: stringinvoiceId?: stringinvoiceLineId?: string@@ -30894,18 +31818,21 @@ export type Database = {}purchaseInvoiceStatusHistory: {Row: {+ companyId: stringcreatedAt: stringid: stringinvoiceId: stringstatus: Database["public"]["Enums"]["purchaseInvoiceStatus"]}Insert: {+ companyId: stringcreatedAt?: stringid?: stringinvoiceId: stringstatus: Database["public"]["Enums"]["purchaseInvoiceStatus"]}Update: {+ companyId?: stringcreatedAt?: stringid?: stringinvoiceId?: string@@ -32086,6 +33013,7 @@ export type Database = {}purchaseOrderStatusHistory: {Row: {+ companyId: stringcreatedAt: stringcreatedBy: stringid: string@@ -32093,6 +33021,7 @@ export type Database = {status: Database["public"]["Enums"]["purchaseOrderStatus"]}Insert: {+ companyId: stringcreatedAt?: stringcreatedBy: stringid?: string@@ -32100,6 +33029,7 @@ export type Database = {status: Database["public"]["Enums"]["purchaseOrderStatus"]}Update: {+ companyId?: stringcreatedAt?: stringcreatedBy?: stringid?: string@@ -32167,6 +33097,7 @@ export type Database = {}purchaseOrderTransaction: {Row: {+ companyId: stringcreatedAt: stringid: stringpurchaseOrderId: string@@ -32174,6 +33105,7 @@ export type Database = {userId: string}Insert: {+ companyId: stringcreatedAt?: stringid?: stringpurchaseOrderId: string@@ -32181,6 +33113,7 @@ export type Database = {userId: string}Update: {+ companyId?: stringcreatedAt?: stringid?: stringpurchaseOrderId?: string@@ -32246,195 +33179,6 @@ export type Database = {},]}- purchasePayment: {- Row: {- companyId: string- createdAt: string- createdBy: string- currencyCode: string- customFields: Json | null- exchangeRate: number- id: string- paymentDate: string | null- paymentId: string- supplierId: string- totalAmount: number- updatedAt: string | null- updatedBy: string | null- }- Insert: {- companyId: string- createdAt?: string- createdBy: string- currencyCode: string- customFields?: Json | null- exchangeRate?: number- id?: string- paymentDate?: string | null- paymentId: string- supplierId: string- totalAmount?: number- updatedAt?: string | null- updatedBy?: string | null- }- Update: {- companyId?: string- createdAt?: string- createdBy?: string- currencyCode?: string- customFields?: Json | null- exchangeRate?: number- id?: string- paymentDate?: string | null- paymentId?: string- supplierId?: string- totalAmount?: number- updatedAt?: string | null- updatedBy?: string | null- }- Relationships: [- {- foreignKeyName: "purchasePayment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "companies"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "company"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "customFieldTables"- referencedColumns: ["companyId"]- },- {- foreignKeyName: "purchasePayment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "integrations"- referencedColumns: ["companyId"]- },- {- foreignKeyName: "purchasePayment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },- {- foreignKeyName: "purchasePayment_currencyCode_fkey"- columns: ["currencyCode"]- isOneToOne: false- referencedRelation: "currencyCode"- referencedColumns: ["code"]- },- {- foreignKeyName: "purchasePayment_supplierId_fkey"- columns: ["supplierId"]- isOneToOne: false- referencedRelation: "contractors"- referencedColumns: ["supplierId"]- },- {- foreignKeyName: "purchasePayment_supplierId_fkey"- columns: ["supplierId"]- isOneToOne: false- referencedRelation: "partners"- referencedColumns: ["supplierId"]- },- {- foreignKeyName: "purchasePayment_supplierId_fkey"- columns: ["supplierId"]- isOneToOne: false- referencedRelation: "purchaseOrderSuppliers"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_supplierId_fkey"- columns: ["supplierId"]- isOneToOne: false- referencedRelation: "supplier"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_supplierId_fkey"- columns: ["supplierId"]- isOneToOne: false- referencedRelation: "suppliers"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },- ]- }purchasingRfq: {Row: {assignee: string | null@@ -34425,6 +35169,7 @@ export type Database = {quoteLinePrice: {Row: {categoryMarkups: Json | null+ companyId: stringconvertedNetExtendedPrice: number | nullconvertedNetUnitPrice: number | nullconvertedShippingCost: number | null@@ -34446,6 +35191,7 @@ export type Database = {}Insert: {categoryMarkups?: Json | null+ companyId: stringconvertedNetExtendedPrice?: number | nullconvertedNetUnitPrice?: number | nullconvertedShippingCost?: number | null@@ -34467,6 +35213,7 @@ export type Database = {}Update: {categoryMarkups?: Json | null+ companyId?: stringconvertedNetExtendedPrice?: number | nullconvertedNetUnitPrice?: number | nullconvertedShippingCost?: number | null@@ -37270,7 +38017,6 @@ export type Database = {salesInvoice: {Row: {assignee: string | null- balance: numbercompanyId: stringcreatedAt: stringcreatedBy: string@@ -37306,7 +38052,6 @@ export type Database = {}Insert: {assignee?: string | null- balance?: numbercompanyId: stringcreatedAt?: stringcreatedBy: string@@ -37342,7 +38087,6 @@ export type Database = {}Update: {assignee?: string | null- balance?: numbercompanyId?: stringcreatedAt?: stringcreatedBy?: string@@ -39220,6 +39964,7 @@ export type Database = {}salesOrderStatusHistory: {Row: {+ companyId: stringcreatedAt: stringcreatedBy: stringid: string@@ -39227,6 +39972,7 @@ export type Database = {status: Database["public"]["Enums"]["salesOrderStatus"]}Insert: {+ companyId: stringcreatedAt?: stringcreatedBy: stringid?: string@@ -39234,6 +39980,7 @@ export type Database = {status: Database["public"]["Enums"]["salesOrderStatus"]}Update: {+ companyId?: stringcreatedAt?: stringcreatedBy?: stringid?: string@@ -39301,6 +40048,7 @@ export type Database = {}salesOrderTransaction: {Row: {+ companyId: stringcreatedAt: stringid: stringsalesOrderId: string@@ -39308,6 +40056,7 @@ export type Database = {userId: string}Insert: {+ companyId: stringcreatedAt?: stringid?: stringsalesOrderId: string@@ -39315,6 +40064,7 @@ export type Database = {userId: string}Update: {+ companyId?: stringcreatedAt?: stringid?: stringsalesOrderId?: string@@ -40148,7 +40898,7 @@ export type Database = {},]}- searchIndex_d8u703oeq0gg2jnc1k2g: {+ searchIndex_d90t6nfl60gg2fpujaag: {Row: {createdAt: stringdescription: string | null@@ -43621,6 +44371,7 @@ export type Database = {}supplierContact: {Row: {+ companyId: stringcontactId: stringcustomFields: Json | nullid: string@@ -43630,6 +44381,7 @@ export type Database = {userId: string | null}Insert: {+ companyId: stringcontactId: stringcustomFields?: Json | nullid?: string@@ -43639,6 +44391,7 @@ export type Database = {userId?: string | null}Update: {+ companyId?: stringcontactId?: stringcustomFields?: Json | nullid?: string@@ -43928,6 +44681,7 @@ export type Database = {supplierLocation: {Row: {addressId: string+ companyId: stringcustomFields: Json | nullid: stringname: string@@ -43936,6 +44690,7 @@ export type Database = {}Insert: {addressId: string+ companyId: stringcustomFields?: Json | nullid?: stringname: string@@ -43944,6 +44699,7 @@ export type Database = {}Update: {addressId?: string+ companyId?: stringcustomFields?: Json | nullid?: stringname?: string@@ -45433,6 +46189,7 @@ export type Database = {}supplierQuoteLinePrice: {Row: {+ companyId: stringcreatedAt: stringcreatedBy: stringexchangeRate: number | null@@ -45453,6 +46210,7 @@ export type Database = {updatedBy: string | null}Insert: {+ companyId: stringcreatedAt?: stringcreatedBy: stringexchangeRate?: number | null@@ -45473,6 +46231,7 @@ export type Database = {updatedBy?: string | null}Update: {+ companyId?: stringcreatedAt?: stringcreatedBy?: stringexchangeRate?: number | null@@ -56440,14 +57199,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"]@@ -57458,7 +58217,7 @@ export type Database = {paymentTermId: string | nullpaymentTermName: string | nullpostingDate: string | null- status: Database["public"]["Enums"]["purchaseInvoiceStatus"] | null+ status: string | nullsubtotal: number | nullsupplierId: string | nullsupplierInteractionId: string | null@@ -58111,14 +58870,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -61544,21 +62303,21 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -61596,7 +62355,7 @@ export type Database = {paymentTermId: string | nullpostingDate: string | nullshipmentId: string | null- status: Database["public"]["Enums"]["salesInvoiceStatus"] | null+ status: string | nullsubtotal: number | nulltags: string[] | nullthumbnailPath: string | null@@ -65723,7 +66482,97 @@ export type Database = {workCenterId: string}[]}+ get_ap_aging: {+ Args: {+ _aging_method?: string+ _as_of_date: string+ _bucket1?: number+ _bucket2?: number+ _bucket3?: number+ _company_id: string+ }+ Returns: {+ bucket1: number+ bucket2: number+ bucket3: number+ bucket4: number+ current: number+ paymentTerm: string+ supplierId: string+ total: number+ unapplied: number+ }[]+ }+ get_ap_open_by_supplier: {+ Args: { _as_of_date: string; _company_id: string }+ Returns: {+ currencyCode: string+ dateDue: string+ documentId: string+ documentNumber: string+ documentType: string+ exchangeRate: number+ openInBase: number+ openInCurrency: number+ settled: number+ supplierId: string+ totalAmount: number+ }[]+ }+ get_ap_tie_out: {+ Args: { _as_of_date: string; _company_id: string }+ Returns: {+ glBalance: number+ subledgerBalance: number+ variance: number+ }[]+ }get_api_key_scopes: { Args: never; Returns: Json }+ get_ar_aging: {+ Args: {+ _aging_method?: string+ _as_of_date: string+ _bucket1?: number+ _bucket2?: number+ _bucket3?: number+ _company_id: string+ }+ Returns: {+ bucket1: number+ bucket2: number+ bucket3: number+ bucket4: number+ current: number+ customerId: string+ paymentTerm: string+ total: number+ unapplied: number+ }[]+ }+ get_ar_open_by_customer: {+ Args: { _as_of_date: string; _company_id: string }+ Returns: {+ currencyCode: string+ customerId: string+ dateDue: string+ documentId: string+ documentNumber: string+ documentType: string+ exchangeRate: number+ openInBase: number+ openInCurrency: number+ settled: number+ totalAmount: number+ }[]+ }+ get_ar_tie_out: {+ Args: { _as_of_date: string; _company_id: string }+ Returns: {+ glBalance: number+ subledgerBalance: number+ variance: number+ }[]+ }get_assigned_job_operations: {Args: { company_id: string; user_id: string }Returns: {@@ -67759,6 +68608,9 @@ export type Database = {| "WorkCenter"| "Process"| "FixedAssetClass"+ | "Customer"+ | "Supplier"+ | "Item"disposalMethod: "Sale" | "Scrapping"disposition:| "Conditional Acceptance"@@ -67978,6 +68830,9 @@ export type Database = {| "Job Close"| "Asset Depreciation"| "Asset Disposal"+ | "Payment"+ | "Credit Memo"+ | "Debit Memo"journalEntryStatus: "Draft" | "Posted" | "Reversed"journalLineDocumentType:| "Receipt"@@ -67995,6 +68850,8 @@ export type Database = {| "Maintenance Consumption"| "Production Event"| "Job Close"+ | "Payment"+ | "Memo"kanbanOutput: "label" | "qrcode" | "url"macrsConvention: "Half-Year" | "Mid-Quarter"macrsPropertyClass: "3" | "5" | "7" | "10" | "15" | "20" | "27.5" | "39"@@ -68023,6 +68880,8 @@ export type Database = {| "OEM Required"maintenanceSource: "Scheduled" | "Reactive" | "Non-Conformance"makeMethodStatus: "Draft" | "Active" | "Archived"+ memoDirection: "Credit" | "Debit"+ memoStatus: "Draft" | "Posted" | "Voided"methodOperationOrder: "After Previous" | "With Previous"methodType: "Purchase to Order" | "Pull from Inventory" | "Make to Order"module:@@ -68082,7 +68941,9 @@ export type Database = {| "Service"| "Consumable"| "Fixture"+ paymentStatus: "Draft" | "Posted" | "Voided"paymentTermCalculationMethod: "Net" | "End of Month" | "Day of Month"+ paymentType: "Receipt" | "Disbursement"periodType: "Week" | "Day" | "Month"pickingListLineStatus: "Pending" | "Picked" | "Short" | "Cancelled"pickingListStatus: "Draft" | "In Progress" | "Completed" | "Cancelled"@@ -69057,6 +69918,9 @@ export const Constants = {"WorkCenter","Process","FixedAssetClass",+ "Customer",+ "Supplier",+ "Item",],disposalMethod: ["Sale", "Scrapping"],disposition: [@@ -69296,6 +70160,9 @@ export const Constants = {"Job Close","Asset Depreciation","Asset Disposal",+ "Payment",+ "Credit Memo",+ "Debit Memo",],journalEntryStatus: ["Draft", "Posted", "Reversed"],journalLineDocumentType: [@@ -69314,6 +70181,8 @@ export const Constants = {"Maintenance Consumption","Production Event","Job Close",+ "Payment",+ "Memo",],kanbanOutput: ["label", "qrcode", "url"],macrsConvention: ["Half-Year", "Mid-Quarter"],@@ -69347,6 +70216,8 @@ export const Constants = {],maintenanceSource: ["Scheduled", "Reactive", "Non-Conformance"],makeMethodStatus: ["Draft", "Active", "Archived"],+ memoDirection: ["Credit", "Debit"],+ memoStatus: ["Draft", "Posted", "Voided"],methodOperationOrder: ["After Previous", "With Previous"],methodType: ["Purchase to Order", "Pull from Inventory", "Make to Order"],module: [@@ -69411,7 +70282,9 @@ export const Constants = {"Consumable","Fixture",],+ paymentStatus: ["Draft", "Posted", "Voided"],paymentTermCalculationMethod: ["Net", "End of Month", "Day of Month"],+ paymentType: ["Receipt", "Disbursement"],periodType: ["Week", "Day", "Month"],pickingListLineStatus: ["Pending", "Picked", "Short", "Cancelled"],pickingListStatus: ["Draft", "In Progress", "Completed", "Cancelled"],diff --git a/packages/database/supabase/functions/close-job/index.ts b/packages/database/supabase/functions/close-job/index.tsindex 5f6d162d70..f8845ffbe1 100644--- a/packages/database/supabase/functions/close-job/index.ts+++ b/packages/database/supabase/functions/close-job/index.ts@@ -81,9 +81,35 @@ serve(async (req: Request) => {const job = await trx.selectFrom("job").where("id", "=", jobId)- .select(["jobId"])+ .select(["jobId", "itemId", "locationId"]).executeTakeFirstOrThrow();+ // Resolve the item dimensions so the WIP variance lines are attributable+ // to the finished good (mirrors the WIP lines posted during completion).+ const companyGroupId = companyRecord.data.companyGroupId;+ const dimensionMap = new Map<string, string>();+ if (companyGroupId) {+ const dimensions = await trx+ .selectFrom("dimension")+ .select(["id", "entityType"])+ .where("companyGroupId", "=", companyGroupId)+ .where("active", "=", true)+ .where("entityType", "in", ["ItemPostingGroup", "Item", "Location"])+ .execute();+ for (const dim of dimensions) {+ if (dim.entityType) dimensionMap.set(dim.entityType, dim.id);+ }+ }++ const finishedItemCost = job.itemId+ ? await trx+ .selectFrom("itemCost")+ .select(["itemPostingGroupId"])+ .where("itemId", "=", job.itemId)+ .where("companyId", "=", companyId)+ .executeTakeFirst()+ : null;+const journalLineReference = nanoid();const journalLineInserts = [@@ -140,7 +166,7 @@ serve(async (req: Request) => {.returning(["id"]).executeTakeFirstOrThrow();- await trx+ const journalLineResults = await trx.insertInto("journalLine").values(journalLineInserts.map((line) => ({@@ -148,7 +174,54 @@ serve(async (req: Request) => {journalId: journalResult.id,})))+ .returning(["id"]).execute();++ if (dimensionMap.size > 0) {+ const dimensionInserts: {+ journalLineId: string;+ dimensionId: string;+ valueId: string;+ companyId: string;+ }[] = [];++ journalLineResults.forEach((jl) => {+ if (job.itemId && dimensionMap.has("Item")) {+ dimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Item")!,+ valueId: job.itemId,+ companyId,+ });+ }+ if (+ finishedItemCost?.itemPostingGroupId &&+ dimensionMap.has("ItemPostingGroup")+ ) {+ dimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("ItemPostingGroup")!,+ valueId: finishedItemCost.itemPostingGroupId,+ companyId,+ });+ }+ if (job.locationId && dimensionMap.has("Location")) {+ dimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Location")!,+ valueId: job.locationId,+ companyId,+ });+ }+ });++ if (dimensionInserts.length > 0) {+ await trx+ .insertInto("journalLineDimension")+ .values(dimensionInserts)+ .execute();+ }+ }});return new Response(JSON.stringify({ success: true }), {diff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.tsindex 73d8534514..2824e01b52 100644--- a/packages/database/supabase/functions/convert/index.ts+++ b/packages/database/supabase/functions/convert/index.ts@@ -331,7 +331,6 @@ serve(async (req: Request) => {totalDiscount: 0,totalAmount: uninvoicedSubtotal ?? 0,totalTax: 0,- balance: uninvoicedSubtotal ?? 0,companyId,createdBy: userId,})@@ -737,7 +736,6 @@ serve(async (req: Request) => {totalDiscount: 0,totalAmount: uninvoicedSubtotal ?? 0,totalTax: 0,- balance: uninvoicedSubtotal ?? 0,companyId,createdBy: userId,})@@ -1326,7 +1324,6 @@ serve(async (req: Request) => {totalDiscount: 0,totalAmount: uninvoicedSubtotal ?? 0,totalTax: 0,- balance: uninvoicedSubtotal ?? 0,companyId,createdBy: userId,})diff --git a/packages/database/supabase/functions/deno.lock b/packages/database/supabase/functions/deno.locknew file mode 100644index 0000000000..1f11c2c232--- /dev/null+++ b/packages/database/supabase/functions/deno.lock@@ -0,0 +1,266 @@+{+ "version": "3",+ "packages": {+ "specifiers": {+ "npm:@supabase/[email protected]": "npm:@supabase/[email protected]",+ "npm:[email protected]": "npm:[email protected]",+ "npm:zod@^3.24.1": "npm:[email protected]"+ },+ "npm": {+ "@supabase/[email protected]": {+ "integrity": "sha512-xi/IAjjbebh6xA9Nkkb7ZwC5ACKJ38OqMoYk1y20ScW5Wt+pxTCcOcaWDWu+2u2Pwc3vTYnXhbknVcQt9UcChQ==",+ "dependencies": {}+ },+ "@supabase/[email protected]": {+ "integrity": "sha512-AT2s/8/3Ffb7IkcUXK6sA/iPCzJhh4Fh/XqzAGNGsVd1xCA/ZGniqU8BL03TqPkN1sR0iDaShjMLLIlHEflyPQ==",+ "dependencies": {}+ },+ "@supabase/[email protected]": {+ "integrity": "sha512-2LExuOHuU6odXorNTvq4M/OvueW+wOs3KDsaCpk+scQMnB6LbmqNidEjXAsKpZu3zyE8MmmtdbJBlRNN/KLdcw==",+ "dependencies": {}+ },+ "@supabase/[email protected]": {+ "integrity": "sha512-L/pX7fkV31x7zPrUOcD6KMtZ03j16o41XxgkACFoOAE9lFz8KaJOBSHvn2QLeWEa2kLz7jwpisvpshPSMjuxOw==",+ "dependencies": {}+ },+ "@supabase/[email protected]": {+ "integrity": "sha512-wz7heB3wwzmRdLRgqngd2VjPPNIdv6/Y8Q0dX/ZvjcL9/Nk8BYSZ7yjypapLpra+swRnbEJ4jAU6eAShiaB1Hg==",+ "dependencies": {}+ },+ "@supabase/[email protected]": {+ "integrity": "sha512-+ihtqFNURc8ssULgQoHQBR4AtUmxez9dtqjclqOV0y5r65SX7Ginmiby4XDW9LPlqHT+MB7OyD1vk0T6pQUtPA==",+ "dependencies": {}+ },+ "@supabase/[email protected]": {+ "integrity": "sha512-QkEfRDiuuQwcfASo2DIJZ59AFV6xpqhPNo4r0kSVt38StYk3iL7ZcSOkZvGQWLlJ8kXKPBWEMhLnfHQF9r+Xfg==",+ "dependencies": {}+ },+ "@supabase/[email protected]": {+ "integrity": "sha512-1tQFbrH1KJhWJqHrY087XPz1WRi20eKG1pebG+6PjSD6XN+j0+x1PTOtBZrylXgY1fOg8BqgU8kl3KX8hI5l9w==",+ "dependencies": {}+ },+ "@supabase/[email protected]": {+ "integrity": "sha512-RNUX8EiBy3iLwAX19jtRzLyePnl11/fHcgwDHLnpKcDSXt/5qBnh3LUwAtIjT21Q66QsmNUR2esrHziLCpNubw==",+ "dependencies": {+ "tslib": "[email protected]"+ }+ },+ "@supabase/[email protected]": {+ "integrity": "sha512-88Gi7LGA4V6Viytb/OoJnF8UTmTflmFiLU3wbwdqlfKJTA6+/mqDo9C27ppHLSUJi+1rfhszpSEEuybFWcwhEA==",+ "dependencies": {+ "tslib": "[email protected]"+ }+ },+ "@supabase/[email protected]": {+ "integrity": "sha512-1ibVeYUacxWYi9i0cf5efil6adJ9WRyZBLivgjs+AUpewx1F3xPi7gLgaASI2SmIQxPoCEjAsLAzKPgMJVgOUQ==",+ "dependencies": {+ "whatwg-url": "[email protected]"+ }+ },+ "@supabase/[email protected]": {+ "integrity": "sha512-jZL/2uPEiK58RFJ+7rctex60AHTdtVWwqw4cqu+5JGrXdu/ZM7ZwttO+yRsRN/E/Xik6s+tmbvH7XAQux4m9nQ==",+ "dependencies": {}+ },+ "@supabase/[email protected]": {+ "integrity": "sha512-TxZCIjxk6/dP9abAi89VQbWWMBbybpGWyvmIzTd79OeravM13OjR/YEYeyUOPcM1C3QyvXkvPZhUfItvmhY1IQ==",+ "dependencies": {+ "@supabase/node-fetch": "@supabase/[email protected]"+ }+ },+ "@supabase/[email protected]": {+ "integrity": "sha512-aAGxCSUemZvQIibnCdvNvgaKib28I4rfrNjKbQ9cG1uBLwUsI7hVpGXgEbypCCDhLjQlDTAiJlu7rgljYUT73g==",+ "dependencies": {+ "@supabase/phoenix": "@supabase/[email protected]",+ "tslib": "[email protected]"+ }+ },+ "@supabase/[email protected]": {+ "integrity": "sha512-TVZPQxXGxY2+A6yTtm77zUHsh70lBhYUEaJL8RQC+BghcX/ygiMG/rmXrNVBce30/WAeNPa8FiG8HbqlGeV05g==",+ "dependencies": {+ "iceberg-js": "[email protected]",+ "tslib": "[email protected]"+ }+ },+ "@supabase/[email protected]": {+ "integrity": "sha512-jA00rquPTppPOHpBB6KABW98lfg0gYXcuGqP3TB1iiduznRVsi3GGk2qBKXPDLMYSe0kRlQp5xCwWWthaJr8eA==",+ "dependencies": {+ "@supabase/functions-js": "@supabase/[email protected]",+ "@supabase/gotrue-js": "@supabase/[email protected]",+ "@supabase/postgrest-js": "@supabase/[email protected]",+ "@supabase/realtime-js": "@supabase/[email protected]",+ "@supabase/storage-js": "@supabase/[email protected]",+ "cross-fetch": "[email protected]"+ }+ },+ "[email protected]": {+ "integrity": "sha512-Q+xVJLoGOeIMXZmbUK4HYk+69cQH6LudR0Vu/pRm2YlU/hDV9CiS0gKUMaWY5f2NeUH9C1nV3bsTlCo0FsTV1Q==",+ "dependencies": {+ "node-fetch": "[email protected]"+ }+ },+ "[email protected]": {+ "integrity": "sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA==",+ "dependencies": {}+ },+ "integrity": "sha512-3oL6pLXACy4QfoidvwIBc+g+01fAx46sQGlIaEl4cScMskuIC/GbEDjzsSwPHzfw80XX0gYZ9eytXikfzV5oew==",+ "dependencies": {+ "kysely": "[email protected]",+ "supabase": "[email protected]"+ }+ },+ "[email protected]": {+ "integrity": "sha512-yWSgGi9bY13b/W06DD2OCDDHQmq1kwTGYlQ4wpZkMOJqMGCstVCFIvxCCVG4KfY1/3G0MhDAcZsip/Lw8/vJWw==",+ "dependencies": {}+ },+ "[email protected]": {+ "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",+ "dependencies": {+ "whatwg-url": "[email protected]"+ }+ },+ "[email protected]": {+ "integrity": "sha512-jV0PJi5LqXUMZ4kriRLvST3DX1YDhrxOgnFJLOn6oUw3KQEFJPXhA60yLQ9aWG1E1uZCp4vUJwSuSGq3HPfaSQ==",+ "dependencies": {+ "@supabase/cli-darwin-arm64": "@supabase/[email protected]",+ "@supabase/cli-darwin-x64": "@supabase/[email protected]",+ "@supabase/cli-linux-arm64": "@supabase/[email protected]",+ "@supabase/cli-linux-arm64-musl": "@supabase/[email protected]",+ "@supabase/cli-linux-x64": "@supabase/[email protected]",+ "@supabase/cli-linux-x64-musl": "@supabase/[email protected]",+ "@supabase/cli-windows-arm64": "@supabase/[email protected]",+ "@supabase/cli-windows-x64": "@supabase/[email protected]"+ }+ },+ "[email protected]": {+ "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",+ "dependencies": {}+ },+ "[email protected]": {+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",+ "dependencies": {}+ },+ "[email protected]": {+ "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",+ "dependencies": {}+ },+ "[email protected]": {+ "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",+ "dependencies": {+ "tr46": "[email protected]",+ "webidl-conversions": "[email protected]"+ }+ },+ "[email protected]": {+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",+ "dependencies": {}+ }+ }+ },+ "remote": {+ "https://deno.land/[email protected]/_util/assert.ts": "e94f2eb37cebd7f199952e242c77654e43333c1ac4c5c700e929ea3aa5489f74",+ "https://deno.land/[email protected]/_util/os.ts": "8a33345f74990e627b9dfe2de9b040004b08ea5146c7c9e8fe9a29070d193934",+ "https://deno.land/[email protected]/async/abortable.ts": "87aa7230be8360c24ad437212311c9e8d4328854baec27b4c7abb26e85515c06",+ "https://deno.land/[email protected]/async/deadline.ts": "48ac998d7564969f3e6ec6b6f9bf0217ebd00239b1b2292feba61272d5dd58d0",+ "https://deno.land/[email protected]/async/debounce.ts": "dc8b92d4a4fe7eac32c924f2b8d3e62112530db70cadce27042689d82970b350",+ "https://deno.land/[email protected]/async/deferred.ts": "d8fb253ffde2a056e4889ef7e90f3928f28be9f9294b6505773d33f136aab4e6",+ "https://deno.land/[email protected]/async/delay.ts": "0419dfc993752849692d1f9647edf13407c7facc3509b099381be99ffbc9d699",+ "https://deno.land/[email protected]/async/mod.ts": "dd0a8ed4f3984ffabe2fcca7c9f466b7932d57b1864ffee148a5d5388316db6b",+ "https://deno.land/[email protected]/async/mux_async_iterator.ts": "3447b28a2a582224a3d4d3596bccbba6e85040da3b97ed64012f7decce98d093",+ "https://deno.land/[email protected]/async/pool.ts": "ef9eb97b388543acbf0ac32647121e4dbe629236899586c4d4311a8770fbb239",+ "https://deno.land/[email protected]/async/tee.ts": "9af3a3e7612af75861308b52249e167f5ebc3dcfc8a1a4d45462d96606ee2b70",+ "https://deno.land/[email protected]/bytes/bytes_list.ts": "aba5e2369e77d426b10af1de0dcc4531acecec27f9b9056f4f7bfbf8ac147ab4",+ "https://deno.land/[email protected]/bytes/equals.ts": "3c3558c3ae85526f84510aa2b48ab2ad7bdd899e2e0f5b7a8ffc85acb3a6043a",+ "https://deno.land/[email protected]/bytes/mod.ts": "b2e342fd3669176a27a4e15061e9d588b89c1aaf5008ab71766e23669565d179",+ "https://deno.land/[email protected]/crypto/_fnv/fnv32.ts": "aa9bddead8c6345087d3abd4ef35fb9655622afc333fc41fff382b36e64280b5",+ "https://deno.land/[email protected]/crypto/_fnv/fnv64.ts": "625d7e7505b6cb2e9801b5fd6ed0a89256bac12b2bbb3e4664b85a88b0ec5bef",+ "https://deno.land/[email protected]/crypto/_fnv/index.ts": "a8f6a361b4c6d54e5e89c16098f99b6962a1dd6ad1307dbc97fa1ecac5d7060a",+ "https://deno.land/[email protected]/crypto/_fnv/util.ts": "4848313bed7f00f55be3cb080aa0583fc007812ba965b03e4009665bde614ce3",+ "https://deno.land/[email protected]/crypto/_wasm_crypto/lib/deno_std_wasm_crypto.generated.mjs": "258b484c2da27578bec61c01d4b62c21f72268d928d03c968c4eb590cb3bd830",+ "https://deno.land/[email protected]/crypto/_wasm_crypto/mod.ts": "6c60d332716147ded0eece0861780678d51b560f533b27db2e15c64a4ef83665",+ "https://deno.land/[email protected]/crypto/keystack.ts": "e481eed28007395e554a435e880fee83a5c73b9259ed8a135a75e4b1e4f381f7",+ "https://deno.land/[email protected]/crypto/mod.ts": "fadedc013b4a86fda6305f1adc6d1c02225834d53cff5d95cc05f62b25127517",+ "https://deno.land/[email protected]/crypto/timing_safe_equal.ts": "82a29b737bc8932d75d7a20c404136089d5d23629e94ba14efa98a8cc066c73e",+ "https://deno.land/[email protected]/datetime/formatter.ts": "7c8e6d16a0950f400aef41b9f1eb9168249869776ec520265dfda785d746589e",+ "https://deno.land/[email protected]/datetime/mod.ts": "ea927ca96dfb28c7b9a5eed5bdc7ac46bb9db38038c4922631895cea342fea87",+ "https://deno.land/[email protected]/datetime/tokenizer.ts": "7381e28f6ab51cb504c7e132be31773d73ef2f3e1e50a812736962b9df1e8c47",+ "https://deno.land/[email protected]/encoding/base64.ts": "c57868ca7fa2fbe919f57f88a623ad34e3d970d675bdc1ff3a9d02bba7409db2",+ "https://deno.land/[email protected]/encoding/base64url.ts": "a5f82a9fa703bd85a5eb8e7c1296bc6529e601ebd9642cc2b5eaa6b38fa9e05a",+ "https://deno.land/[email protected]/encoding/hex.ts": "4cc5324417cbb4ac9b828453d35aed45b9cc29506fad658f1f138d981ae33795",+ "https://deno.land/[email protected]/fmt/colors.ts": "9e36a716611dcd2e4865adea9c4bec916b5c60caad4cdcdc630d4974e6bb8bd4",+ "https://deno.land/[email protected]/io/buffer.ts": "fae02290f52301c4e0188670e730cd902f9307fb732d79c4aa14ebdc82497289",+ "https://deno.land/[email protected]/path/_constants.ts": "df1db3ffa6dd6d1252cc9617e5d72165cd2483df90e93833e13580687b6083c3",+ "https://deno.land/[email protected]/path/_interface.ts": "ee3b431a336b80cf445441109d089b70d87d5e248f4f90ff906820889ecf8d09",+ "https://deno.land/[email protected]/path/_util.ts": "d16be2a16e1204b65f9d0dfc54a9bc472cafe5f4a190b3c8471ec2016ccd1677",+ "https://deno.land/[email protected]/path/common.ts": "bee563630abd2d97f99d83c96c2fa0cca7cee103e8cb4e7699ec4d5db7bd2633",+ "https://deno.land/[email protected]/path/glob.ts": "cb5255638de1048973c3e69e420c77dc04f75755524cb3b2e160fe9277d939ee",+ "https://deno.land/[email protected]/path/mod.ts": "56fec03ad0ebd61b6ab39ddb9b0ddb4c4a5c9f2f4f632e09dd37ec9ebfd722ac",+ "https://deno.land/[email protected]/path/posix.ts": "6b63de7097e68c8663c84ccedc0fd977656eb134432d818ecd3a4e122638ac24",+ "https://deno.land/[email protected]/path/separator.ts": "fe1816cb765a8068afb3e8f13ad272351c85cbc739af56dacfc7d93d710fe0f9",+ "https://deno.land/[email protected]/path/win32.ts": "ee8826dce087d31c5c81cd414714e677eb68febc40308de87a2ce4b40e10fb8d",+ "https://deno.land/[email protected]/testing/_diff.ts": "a23e7fc2b4d8daa3e158fa06856bedf5334ce2a2831e8bf9e509717f455adb2c",+ "https://deno.land/[email protected]/testing/_format.ts": "cd11136e1797791045e639e9f0f4640d5b4166148796cad37e6ef75f7d7f3832",+ "https://deno.land/[email protected]/testing/asserts.ts": "1e340c589853e82e0807629ba31a43c84ebdcdeca910c4a9705715dfdb0f5ce8",+ "https://deno.land/[email protected]/async/abortable.ts": "73acfb3ed7261ce0d930dbe89e43db8d34e017b063cf0eaa7d215477bf53442e",+ "https://deno.land/[email protected]/async/deadline.ts": "b98e50d2c42399af03ad13bbb8cf59dadb9f0cd5d70648cc0c3b9202d75ab565",+ "https://deno.land/[email protected]/async/debounce.ts": "adab11d04ca38d699444ac8a9d9856b4155e8dda2afd07ce78276c01ea5a4332",+ "https://deno.land/[email protected]/async/deferred.ts": "42790112f36a75a57db4a96d33974a936deb7b04d25c6084a9fa8a49f135def8",+ "https://deno.land/[email protected]/async/delay.ts": "73aa04cec034c84fc748c7be49bb15cac3dd43a57174bfdb7a4aec22c248f0dd",+ "https://deno.land/[email protected]/async/mod.ts": "f04344fa21738e5ad6bea37a6bfffd57c617c2d372bb9f9dcfd118a1b622e576",+ "https://deno.land/[email protected]/async/mux_async_iterator.ts": "70c7f2ee4e9466161350473ad61cac0b9f115cff4c552eaa7ef9d50c4cbb4cc9",+ "https://deno.land/[email protected]/async/pool.ts": "fd082bd4aaf26445909889435a5c74334c017847842ec035739b4ae637ae8260",+ "https://deno.land/[email protected]/async/retry.ts": "5efa3ba450ac0c07a40a82e2df296287b5013755d232049efd7ea2244f15b20f",+ "https://deno.land/[email protected]/async/tee.ts": "47e42d35f622650b02234d43803d0383a89eb4387e1b83b5a40106d18ae36757",+ "https://deno.land/[email protected]/fmt/colors.ts": "938c5d44d889fb82eff6c358bea8baa7e85950a16c9f6dae3ec3a7a729164471",+ "https://deno.land/[email protected]/http/server.ts": "cbb17b594651215ba95c01a395700684e569c165a567e4e04bba327f41197433",+ "https://deno.land/[email protected]/testing/_diff.ts": "1a3c044aedf77647d6cac86b798c6417603361b66b54c53331b312caeb447aea",+ "https://deno.land/[email protected]/testing/_format.ts": "a69126e8a469009adf4cf2a50af889aca364c349797e63174884a52ff75cf4c7",+ "https://deno.land/[email protected]/testing/asserts.ts": "984ab0bfb3faeed92ffaa3a6b06536c66811185328c5dd146257c702c41b01ab",+ "https://deno.land/[email protected]/datetime/_common.ts": "32ab92a6a9353e2f7ee23a30f0dfbd458b750e1c6fd71af1ec83f93a8f7c268a",+ "https://deno.land/[email protected]/datetime/constants.ts": "b63a6b702e06fa028fb2ffa25e0cf775e3b21cf7f38e53a6f219e9641894dfbb",+ "https://deno.land/[email protected]/datetime/day_of_year.ts": "2d50431735f4b1b171dcd8c339f991c3efca8c8d8618a3ebfe501a7aa0e1efd5",+ "https://deno.land/[email protected]/datetime/difference.ts": "fab879a5a7caf44604c240898ed2c7cdd16f037a3bd6e0cb185994fafbd71e4b",+ "https://deno.land/[email protected]/datetime/format.ts": "2d7a430ca9571e054ac181dcb950faf9ac23445e081dcb230ca37134e6eaad0c",+ "https://deno.land/[email protected]/datetime/is_leap.ts": "706c3579a34d38111eea92c1b8683e859e5c5db9ec05f08a9b611ec888fbd787",+ "https://deno.land/[email protected]/datetime/mod.ts": "8fccadb22ad67775374a375e0077ef008bed80a20ccf8a3285115a071d08f75e",+ "https://deno.land/[email protected]/datetime/parse.ts": "b59f583e7fe5ef2105c6dd4a74825670c9f4e1e35462c047c6f0a207b5653aac",+ "https://deno.land/[email protected]/datetime/to_imf.ts": "a181a2733fb9df76b6b30cdb7a429d8752ebe42313fcc98c8ca7d075224faced",+ "https://deno.land/[email protected]/datetime/week_of_year.ts": "4f327c5656959759fac0a0bb642cfd6a0a64440e5a876ab218edbee006d98d20",+ "https://deno.land/x/[email protected]/customAlphabet.ts": "1cfd7cfd2f07ca8d78a7e7855fcc9f59abf01ef2a127484ef94328fadf940ead",+ "https://deno.land/x/[email protected]/customRandom.ts": "af56e19038c891a4b4ef2be931554c27579bd407ee5bbea5cb64f6ee1347cbe3",+ "https://deno.land/x/[email protected]/mod.ts": "3ead610e40c58d8fdca21d5da9ec661445a2b82526e19c34d05de5f90be8a1be",+ "https://deno.land/x/[email protected]/nanoid.ts": "8d119bc89a0f34e7bbe0c2dbdc280d01753e431af553d189663492310a31085d",+ "https://deno.land/x/[email protected]/random.ts": "4da71d5f72f2bfcc6a4ee79b5d4e72f48dcf4fe4c3835fd5ebab08b9f33cd598",+ "https://deno.land/x/[email protected]/urlAlphabet.ts": "8b1511deb1ecb23c66202b6000dc10fb68f9a96b5550c6c8cef5009324793431",+ "https://deno.land/x/[email protected]/client.ts": "348779c9f6a1c75ef1336db662faf08dce7d2101ff72f0d1e341ba1505c8431d",+ "https://deno.land/x/[email protected]/client/error.ts": "0817583b666fd546664ed52c1d37beccc5a9eebcc6e3c2ead20ada99b681e5f7",+ "https://deno.land/x/[email protected]/connection/auth.ts": "1070125e2ac4ca4ade36d69a4222d37001903092826d313217987583edd61ce9",+ "https://deno.land/x/[email protected]/connection/connection.ts": "428ed3efa055870db505092b5d3545ef743497b7b4b72cf8f0593e7dd4788acd",+ "https://deno.land/x/[email protected]/connection/connection_params.ts": "52bfe90e8860f584b95b1b08c254dde97c3aa763c4b6bee0c80c5930e35459e0",+ "https://deno.land/x/[email protected]/connection/message.ts": "f9257948b7f87d58bfbfe3fc6e2e08f0de3ef885655904d56a5f73655cc22c5a",+ "https://deno.land/x/[email protected]/connection/message_code.ts": "466719008b298770c366c5c63f6cf8285b7f76514dadb4b11e7d9756a8a1ddbf",+ "https://deno.land/x/[email protected]/connection/packet.ts": "050aeff1fc13c9349e89451a155ffcd0b1343dc313a51f84439e3e45f64b56c8",+ "https://deno.land/x/[email protected]/connection/scram.ts": "0c7a2551fe7b1a1c62dd856b7714731a7e7534ccca10093336782d1bfc5b2bd2",+ "https://deno.land/x/[email protected]/deps.ts": "f47ccb41f7f97eaad455d94f407ef97146ae99443dbe782894422c869fbba69e",+ "https://deno.land/x/[email protected]/mod.ts": "a1e18fd9e6fedc8bc24e5aeec3ae6de45e2274be1411fb66e9081420c5e81d7d",+ "https://deno.land/x/[email protected]/pool.ts": "892db7b5e1787988babecc994a151ebbd7d017f080905cbe9c3d7b44a73032a9",+ "https://deno.land/x/[email protected]/query/array_parser.ts": "f8a229d82c3801de8266fa2cc4afe12e94fef8d0c479e73655c86ed3667ef33f",+ "https://deno.land/x/[email protected]/query/decode.ts": "44a4a6cbcf494ed91a4fecae38a57dce63a7b519166f02c702791d9717371419",+ "https://deno.land/x/[email protected]/query/decoders.ts": "16cb0e60227d86692931e315421b15768c78526e3aeb84e25fcc4111096de9fd",+ "https://deno.land/x/[email protected]/query/encode.ts": "5f1418a2932b7c2231556e4a5f5f56efef48728014070cfafe7656963f342933",+ "https://deno.land/x/[email protected]/query/oid.ts": "8c33e1325f34e4ca9f11a48b8066c8cfcace5f64bc1eb17ad7247af4936999e1",+ "https://deno.land/x/[email protected]/query/query.ts": "edb473cbcfeff2ee1c631272afb25d079d06b66b5853f42492725b03ffa742b6",+ "https://deno.land/x/[email protected]/query/transaction.ts": "8e75c3ce0aca97da7fe126e68f8e6c08d640e5c8d2016e62cee5c254bebe7fe8",+ "https://deno.land/x/[email protected]/query/types.ts": "a6dc8024867fe7ccb0ba4b4fa403ee5d474c7742174128c8e689c3b5e5eaa933",+ "https://deno.land/x/[email protected]/utils/deferred.ts": "dd94f2a57355355c47812b061a51b55263f72d24e9cb3fdb474c7519f4d61083",+ "https://deno.land/x/[email protected]/utils/utils.ts": "19c3527ddd5c6c4c49ae36397120274c7f41f9d3cbf479cb36065d23329e9f90"+ },+ "workspace": {+ "dependencies": [+ "npm:@supabase/[email protected]",+ "npm:kysely-supabase",+ "npm:[email protected]"+ ]+ }+}diff --git a/packages/database/supabase/functions/issue/index.ts b/packages/database/supabase/functions/issue/index.tsindex 4b336be5b5..66aa3ff066 100644--- a/packages/database/supabase/functions/issue/index.ts+++ b/packages/database/supabase/functions/issue/index.ts@@ -321,6 +321,7 @@ async function issueJobOperationMaterials(const journalLineDimensionsMeta: {itemPostingGroupId: string | null;+ itemId: string | null;locationId: string | null;}[] = [];@@ -398,6 +399,7 @@ async function issueJobOperationMaterials(for (let i = 0; i < 2; i++) {journalLineDimensionsMeta.push({itemPostingGroupId: consumedPostingGroupMap.get(ledger.itemId) ?? null,+ itemId: ledger.itemId ?? null,locationId: jobForLocation?.locationId ?? null,});}@@ -455,6 +457,14 @@ async function issueJobOperationMaterials(companyId,});}+ if (meta.itemId && dimensionMap.has("Item")) {+ dimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Item")!,+ valueId: meta.itemId,+ companyId,+ });+ }if (meta.locationId && dimensionMap.has("Location")) {dimensionInserts.push({journalLineId: jl.id,@@ -514,6 +524,7 @@ async function createMaterialWipEntries(const journalLineDimensionsMeta: {itemPostingGroupId: string | null;+ itemId: string | null;locationId: string | null;}[] = [];@@ -630,6 +641,7 @@ async function createMaterialWipEntries(for (let i = 0; i < 2; i++) {journalLineDimensionsMeta.push({itemPostingGroupId: consumedPostingGroupMap.get(ledger.itemId) ?? null,+ itemId: ledger.itemId ?? null,locationId: jobLocationId,});}@@ -687,6 +699,14 @@ async function createMaterialWipEntries(companyId,});}+ if (meta.itemId && dimensionMap.has("Item")) {+ dimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Item")!,+ valueId: meta.itemId,+ companyId,+ });+ }if (meta.locationId && dimensionMap.has("Location")) {dimensionInserts.push({journalLineId: jl.id,@@ -901,7 +921,7 @@ serve(async (req: Request) => {.select("id, entityType").eq("companyGroupId", companyRecord.data.companyGroupId).eq("active", true)- .in("entityType", ["ItemPostingGroup", "Location"])+ .in("entityType", ["ItemPostingGroup", "Item", "Location"]): null;const dimensionMap = new Map<string, string>();@@ -972,7 +992,7 @@ serve(async (req: Request) => {.select("id, entityType").eq("companyGroupId", companyRecordBatch.data.companyGroupId).eq("active", true)- .in("entityType", ["ItemPostingGroup", "Location"])+ .in("entityType", ["ItemPostingGroup", "Item", "Location"]): null;const dimensionMapBatch = new Map<string, string>();@@ -1126,7 +1146,7 @@ serve(async (req: Request) => {.select("id, entityType").eq("companyGroupId", companyRecordSerial.data.companyGroupId).eq("active", true)- .in("entityType", ["ItemPostingGroup", "Location"])+ .in("entityType", ["ItemPostingGroup", "Item", "Location"]): null;const dimensionMapSerial = new Map<string, string>();@@ -1288,7 +1308,7 @@ serve(async (req: Request) => {.select("id, entityType").eq("companyGroupId", companyRecord.data.companyGroupId).eq("active", true)- .in("entityType", ["ItemPostingGroup", "Location"])+ .in("entityType", ["ItemPostingGroup", "Item", "Location"]): null;const dimensionMap = new Map<string, string>();@@ -1576,7 +1596,7 @@ serve(async (req: Request) => {.select("id, entityType").eq("companyGroupId", companyRecordScrap.data.companyGroupId).eq("active", true)- .in("entityType", ["ItemPostingGroup", "Location"])+ .in("entityType", ["ItemPostingGroup", "Item", "Location"]): null;const dimensionMapScrap = new Map<string, string>();@@ -1775,7 +1795,7 @@ serve(async (req: Request) => {.select("id, entityType").eq("companyGroupId", companyRecordTracked.data.companyGroupId).eq("active", true)- .in("entityType", ["ItemPostingGroup", "Location"])+ .in("entityType", ["ItemPostingGroup", "Item", "Location"]): null;const dimensionMapTracked = new Map<string, string>();@@ -2382,7 +2402,7 @@ serve(async (req: Request) => {.select("id, entityType").eq("companyGroupId", companyRecordUnconsume.data.companyGroupId).eq("active", true)- .in("entityType", ["ItemPostingGroup", "Location"])+ .in("entityType", ["ItemPostingGroup", "Item", "Location"]): null;const dimensionMapUnconsume = new Map<string, string>();diff --git a/packages/database/supabase/functions/lib/seed.data.ts b/packages/database/supabase/functions/lib/seed.data.tsindex 5bfdefc519..687dd23a64 100644--- a/packages/database/supabase/functions/lib/seed.data.ts+++ b/packages/database/supabase/functions/lib/seed.data.ts@@ -16,6 +16,9 @@ export const dimensions = [{ name: "Work Center", entityType: "WorkCenter" },{ name: "Process", entityType: "Process" },{ name: "Asset Class", entityType: "FixedAssetClass" },+ { name: "Customer", entityType: "Customer" },+ { name: "Supplier", entityType: "Supplier" },+ { name: "Item", entityType: "Item" },] as const;export const supplierStatuses = [@@ -393,6 +396,36 @@ export const sequences = [next: 0,size: 6,step: 1+ },+ {+ table: "payment",+ name: "Payment",+ prefix: "PAY-%{yyyy}-%{mm}-",+ suffix: null,+ next: 0,+ size: 6,+ step: 1+ },+ {+ // Credit/debit memos are payment-shaped `memo` documents with their own+ // numbering; the insert path picks the sequence by direction. Mirrors the+ // backfill in 20260628143012_ar-ap-payments.sql.+ table: "creditMemo",+ name: "Credit Memo",+ prefix: "CR-%{yyyy}-%{mm}-",+ suffix: null,+ next: 0,+ size: 6,+ step: 1+ },+ {+ table: "debitMemo",+ name: "Debit Memo",+ prefix: "DR-%{yyyy}-%{mm}-",+ suffix: null,+ next: 0,+ size: 6,+ step: 1}] as const;@@ -619,6 +652,7 @@ export const accounts = [{ key: "other-income", number: null, name: "Other Income", isGroup: true, parentKey: "income-statement", accountType: "Other Income", incomeBalance: "Income Statement", class: "Revenue", consolidatedRate: "Average", createdBy: "system" },{ key: "4110", number: "4110", name: "Scrap Sales", isGroup: false, parentKey: "other-income", accountType: "Other Income", incomeBalance: "Income Statement", class: "Revenue", consolidatedRate: "Average", createdBy: "system" },{ key: "4120", number: "4120", name: "Foreign Exchange Gains", isGroup: false, parentKey: "other-income", accountType: "Other Income", incomeBalance: "Income Statement", class: "Revenue", consolidatedRate: "Average", createdBy: "system" },+ { key: "4130", number: "4130", name: "Vendor Write-Off Income", isGroup: false, parentKey: "other-income", accountType: "Other Income", incomeBalance: "Income Statement", class: "Revenue", consolidatedRate: "Average", createdBy: "system" },// ─── 5000-5999: COST OF GOODS SOLD ───{ key: "cogs", number: null, name: "Cost of Goods Sold", isGroup: true, parentKey: "income-statement", accountType: "Cost of Goods Sold", incomeBalance: "Income Statement", class: "Expense", consolidatedRate: "Average", createdBy: "system" },@@ -711,6 +745,10 @@ export const accountDefaults = {reverseChargeSalesTaxPayableAccount: "2230",retainedEarningsAccount: "3100",currencyTranslationAccount: "3200",+ customerWriteOffAccount: "6050",+ supplierWriteOffAccount: "4130",+ realizedExchangeGainAccount: "4120",+ realizedExchangeLossAccount: "7060",deferredTaxLiabilityAccountId: "2420",deferredTaxExpenseAccountId: "7090",} as const;diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 22bd406b07..090fb5ba11 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -342,6 +342,7 @@ export type Database = {costOfGoodsSoldAccount: stringcurrencyTranslationAccount: stringcustomerPaymentDiscountAccount: string+ customerWriteOffAccount: stringdeferredTaxExpenseAccountId: string | nulldeferredTaxLiabilityAccountId: string | nullgoodsReceivedNotInvoicedAccount: string@@ -360,6 +361,8 @@ export type Database = {prepaymentAccount: stringpurchaseTaxPayableAccount: stringpurchaseVarianceAccount: string+ realizedExchangeGainAccount: string+ realizedExchangeLossAccount: stringreceivablesAccount: stringretainedEarningsAccount: stringreverseChargeSalesTaxPayableAccount: string@@ -370,6 +373,7 @@ export type Database = {serviceChargeAccount: stringsubcontractingVarianceAccount: stringsupplierPaymentDiscountAccount: string+ supplierWriteOffAccount: stringupdatedBy: string | nullworkInProgressAccount: string}@@ -387,6 +391,7 @@ export type Database = {costOfGoodsSoldAccount: stringcurrencyTranslationAccount: stringcustomerPaymentDiscountAccount: string+ customerWriteOffAccount: stringdeferredTaxExpenseAccountId?: string | nulldeferredTaxLiabilityAccountId?: string | nullgoodsReceivedNotInvoicedAccount: string@@ -405,6 +410,8 @@ export type Database = {prepaymentAccount: stringpurchaseTaxPayableAccount: stringpurchaseVarianceAccount: string+ realizedExchangeGainAccount: string+ realizedExchangeLossAccount: stringreceivablesAccount: stringretainedEarningsAccount: stringreverseChargeSalesTaxPayableAccount: string@@ -415,6 +422,7 @@ export type Database = {serviceChargeAccount: stringsubcontractingVarianceAccount: stringsupplierPaymentDiscountAccount: string+ supplierWriteOffAccount: stringupdatedBy?: string | nullworkInProgressAccount: string}@@ -432,6 +440,7 @@ export type Database = {costOfGoodsSoldAccount?: stringcurrencyTranslationAccount?: stringcustomerPaymentDiscountAccount?: string+ customerWriteOffAccount?: stringdeferredTaxExpenseAccountId?: string | nulldeferredTaxLiabilityAccountId?: string | nullgoodsReceivedNotInvoicedAccount?: string@@ -450,6 +459,8 @@ export type Database = {prepaymentAccount?: stringpurchaseTaxPayableAccount?: stringpurchaseVarianceAccount?: string+ realizedExchangeGainAccount?: string+ realizedExchangeLossAccount?: stringreceivablesAccount?: stringretainedEarningsAccount?: stringreverseChargeSalesTaxPayableAccount?: string@@ -460,6 +471,7 @@ export type Database = {serviceChargeAccount?: stringsubcontractingVarianceAccount?: stringsupplierPaymentDiscountAccount?: string+ supplierWriteOffAccount?: stringupdatedBy?: string | nullworkInProgressAccount?: string}@@ -632,6 +644,20 @@ export type Database = {referencedRelation: "accounts"referencedColumns: ["id"]},+ {+ foreignKeyName: "accountDefault_customerWriteOffAccount_fkey"+ columns: ["customerWriteOffAccount"]+ isOneToOne: false+ referencedRelation: "account"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountDefault_customerWriteOffAccount_fkey"+ columns: ["customerWriteOffAccount"]+ isOneToOne: false+ referencedRelation: "accounts"+ referencedColumns: ["id"]+ },{foreignKeyName: "accountDefault_deferredTaxExpenseAccountId_fkey"columns: ["deferredTaxExpenseAccountId"]@@ -912,6 +938,34 @@ export type Database = {referencedRelation: "accounts"referencedColumns: ["id"]},+ {+ foreignKeyName: "accountDefault_realizedExchangeGainAccount_fkey"+ columns: ["realizedExchangeGainAccount"]+ isOneToOne: false+ referencedRelation: "account"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountDefault_realizedExchangeGainAccount_fkey"+ columns: ["realizedExchangeGainAccount"]+ isOneToOne: false+ referencedRelation: "accounts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountDefault_realizedExchangeLossAccount_fkey"+ columns: ["realizedExchangeLossAccount"]+ isOneToOne: false+ referencedRelation: "account"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountDefault_realizedExchangeLossAccount_fkey"+ columns: ["realizedExchangeLossAccount"]+ isOneToOne: false+ referencedRelation: "accounts"+ referencedColumns: ["id"]+ },{foreignKeyName: "accountDefault_receivablesAccount_fkey"columns: ["receivablesAccount"]@@ -1052,6 +1106,20 @@ export type Database = {referencedRelation: "accounts"referencedColumns: ["id"]},+ {+ foreignKeyName: "accountDefault_supplierWriteOffAccount_fkey"+ columns: ["supplierWriteOffAccount"]+ isOneToOne: false+ referencedRelation: "account"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountDefault_supplierWriteOffAccount_fkey"+ columns: ["supplierWriteOffAccount"]+ isOneToOne: false+ referencedRelation: "accounts"+ referencedColumns: ["id"]+ },{foreignKeyName: "accountDefault_updatedBy_fkey"columns: ["updatedBy"]@@ -4128,18 +4196,21 @@ export type Database = {contractorAbility: {Row: {abilityId: string+ companyId: stringcontractorId: stringcreatedAt: stringcreatedBy: string}Insert: {abilityId: string+ companyId: stringcontractorId: stringcreatedAt?: stringcreatedBy: string}Update: {abilityId?: string+ companyId?: stringcontractorId?: stringcreatedAt?: stringcreatedBy?: string@@ -5058,6 +5129,7 @@ export type Database = {}customerContact: {Row: {+ companyId: stringcontactId: stringcustomerId: stringcustomerLocationId: string | null@@ -5067,6 +5139,7 @@ export type Database = {userId: string | null}Insert: {+ companyId: stringcontactId: stringcustomerId: stringcustomerLocationId?: string | null@@ -5076,6 +5149,7 @@ export type Database = {userId?: string | null}Update: {+ companyId?: stringcontactId?: stringcustomerId?: stringcustomerLocationId?: string | null@@ -5525,6 +5599,7 @@ export type Database = {customerLocation: {Row: {addressId: string+ companyId: stringcustomerId: stringcustomFields: Json | nullid: string@@ -5533,6 +5608,7 @@ export type Database = {}Insert: {addressId: string+ companyId: stringcustomerId: stringcustomFields?: Json | nullid?: string@@ -5541,6 +5617,7 @@ export type Database = {}Update: {addressId?: string+ companyId?: stringcustomerId?: stringcustomFields?: Json | nullid?: string@@ -8237,16 +8314,19 @@ export type Database = {}documentLabel: {Row: {+ companyId: stringdocumentId: stringlabel: stringuserId: string}Insert: {+ companyId: stringdocumentId: stringlabel: stringuserId: string}Update: {+ companyId?: stringdocumentId?: stringlabel?: stringuserId?: string@@ -8590,6 +8670,7 @@ export type Database = {}documentTransaction: {Row: {+ companyId: stringcreatedAt: stringdocumentId: stringid: string@@ -8597,6 +8678,7 @@ export type Database = {userId: string}Insert: {+ companyId: stringcreatedAt?: stringdocumentId: stringid?: string@@ -8604,6 +8686,7 @@ export type Database = {userId: string}Update: {+ companyId?: stringcreatedAt?: stringdocumentId?: stringid?: string@@ -9035,16 +9118,19 @@ export type Database = {}employeeShift: {Row: {+ companyId: stringemployeeId: stringid: stringshiftId: string}Insert: {+ companyId: stringemployeeId: stringid?: stringshiftId: string}Update: {+ companyId?: stringemployeeId?: stringid?: stringshiftId?: string@@ -13672,6 +13758,193 @@ export type Database = {},]}+ invoiceSettlement: {+ Row: {+ appliedAmount: number+ appliedDate: string+ appliedViaPaymentId: string | null+ companyId: string+ createdAt: string+ createdBy: string+ discountAmount: number+ fxGainLossAmount: number | null+ id: string+ memoId: string | null+ paymentId: string | null+ sourceExchangeRate: number+ targetExchangeRate: number+ targetMemoId: string | null+ targetPurchaseInvoiceId: string | null+ targetSalesInvoiceId: string | null+ writeOffAmount: number+ }+ Insert: {+ appliedAmount: number+ appliedDate: string+ appliedViaPaymentId?: string | null+ companyId: string+ createdAt?: string+ createdBy: string+ discountAmount?: number+ fxGainLossAmount?: number | null+ id?: string+ memoId?: string | null+ paymentId?: string | null+ sourceExchangeRate: number+ targetExchangeRate: number+ targetMemoId?: string | null+ targetPurchaseInvoiceId?: string | null+ targetSalesInvoiceId?: string | null+ writeOffAmount?: number+ }+ Update: {+ appliedAmount?: number+ appliedDate?: string+ appliedViaPaymentId?: string | null+ companyId?: string+ createdAt?: string+ createdBy?: string+ discountAmount?: number+ fxGainLossAmount?: number | null+ id?: string+ memoId?: string | null+ paymentId?: string | null+ sourceExchangeRate?: number+ targetExchangeRate?: number+ targetMemoId?: string | null+ targetPurchaseInvoiceId?: string | null+ targetSalesInvoiceId?: string | null+ writeOffAmount?: number+ }+ Relationships: [+ {+ foreignKeyName: "invoiceSettlement_appliedViaPaymentId_fkey"+ columns: ["appliedViaPaymentId"]+ isOneToOne: false+ referencedRelation: "payment"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "invoiceSettlement_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "invoiceSettlement_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "invoiceSettlement_memoId_fkey"+ columns: ["memoId"]+ isOneToOne: false+ referencedRelation: "memo"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_paymentId_fkey"+ columns: ["paymentId"]+ isOneToOne: false+ referencedRelation: "payment"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_targetMemoId_fkey"+ columns: ["targetMemoId"]+ isOneToOne: false+ referencedRelation: "memo"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_targetPurchaseInvoiceId_fkey"+ columns: ["targetPurchaseInvoiceId"]+ isOneToOne: false+ referencedRelation: "purchaseInvoice"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_targetPurchaseInvoiceId_fkey"+ columns: ["targetPurchaseInvoiceId"]+ isOneToOne: false+ referencedRelation: "purchaseInvoices"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_targetSalesInvoiceId_fkey"+ columns: ["targetSalesInvoiceId"]+ isOneToOne: false+ referencedRelation: "salesInvoice"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_targetSalesInvoiceId_fkey"+ columns: ["targetSalesInvoiceId"]+ isOneToOne: false+ referencedRelation: "salesInvoiceLocations"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "invoiceSettlement_targetSalesInvoiceId_fkey"+ columns: ["targetSalesInvoiceId"]+ isOneToOne: false+ referencedRelation: "salesInvoices"+ referencedColumns: ["id"]+ },+ ]+ }item: {Row: {active: boolean@@ -21805,6 +22078,350 @@ export type Database = {},]}+ memo: {+ Row: {+ amount: number+ companyId: string+ createdAt: string+ createdBy: string+ currencyCode: string+ customerId: string | null+ customFields: Json | null+ direction: Database["public"]["Enums"]["memoDirection"]+ exchangeRate: number+ id: string+ journalId: string | null+ memoDate: string+ memoId: string+ notes: string | null+ postedAt: string | null+ postedBy: string | null+ postingDate: string | null+ reasonAccount: string | null+ reference: string | null+ status: Database["public"]["Enums"]["memoStatus"]+ supplierId: string | null+ updatedAt: string | null+ updatedBy: string | null+ voidedAt: string | null+ voidedBy: string | null+ }+ Insert: {+ amount: number+ companyId: string+ createdAt?: string+ createdBy: string+ currencyCode: string+ customerId?: string | null+ customFields?: Json | null+ direction: Database["public"]["Enums"]["memoDirection"]+ exchangeRate?: number+ id?: string+ journalId?: string | null+ memoDate: string+ memoId: string+ notes?: string | null+ postedAt?: string | null+ postedBy?: string | null+ postingDate?: string | null+ reasonAccount?: string | null+ reference?: string | null+ status?: Database["public"]["Enums"]["memoStatus"]+ supplierId?: string | null+ updatedAt?: string | null+ updatedBy?: string | null+ voidedAt?: string | null+ voidedBy?: string | null+ }+ Update: {+ amount?: number+ companyId?: string+ createdAt?: string+ createdBy?: string+ currencyCode?: string+ customerId?: string | null+ customFields?: Json | null+ direction?: Database["public"]["Enums"]["memoDirection"]+ exchangeRate?: number+ id?: string+ journalId?: string | null+ memoDate?: string+ memoId?: string+ notes?: string | null+ postedAt?: string | null+ postedBy?: string | null+ postingDate?: string | null+ reasonAccount?: string | null+ reference?: string | null+ status?: Database["public"]["Enums"]["memoStatus"]+ supplierId?: string | null+ updatedAt?: string | null+ updatedBy?: string | null+ voidedAt?: string | null+ voidedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "memo_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "memo_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "memo_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "memo_currencyCode_fkey"+ columns: ["currencyCode"]+ isOneToOne: false+ referencedRelation: "currencyCode"+ referencedColumns: ["code"]+ },+ {+ foreignKeyName: "memo_customerId_fkey"+ columns: ["customerId"]+ isOneToOne: false+ referencedRelation: "customer"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_customerId_fkey"+ columns: ["customerId"]+ isOneToOne: false+ referencedRelation: "customers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_customerId_fkey"+ columns: ["customerId"]+ isOneToOne: false+ referencedRelation: "salesOrderCustomers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_journalId_fkey"+ columns: ["journalId"]+ isOneToOne: false+ referencedRelation: "journal"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_journalId_fkey"+ columns: ["journalId"]+ isOneToOne: false+ referencedRelation: "journalEntries"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_postedBy_fkey"+ columns: ["postedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_postedBy_fkey"+ columns: ["postedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_postedBy_fkey"+ columns: ["postedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_postedBy_fkey"+ columns: ["postedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_postedBy_fkey"+ columns: ["postedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "memo_reasonAccount_fkey"+ columns: ["reasonAccount"]+ isOneToOne: false+ referencedRelation: "account"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_reasonAccount_fkey"+ columns: ["reasonAccount"]+ isOneToOne: false+ referencedRelation: "accounts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "contractors"+ referencedColumns: ["supplierId"]+ },+ {+ foreignKeyName: "memo_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "partners"+ referencedColumns: ["supplierId"]+ },+ {+ foreignKeyName: "memo_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "purchaseOrderSuppliers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "supplier"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "suppliers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "memo_voidedBy_fkey"+ columns: ["voidedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_voidedBy_fkey"+ columns: ["voidedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_voidedBy_fkey"+ columns: ["voidedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_voidedBy_fkey"+ columns: ["voidedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "memo_voidedBy_fkey"+ columns: ["voidedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }methodMaterial: {Row: {companyId: string@@ -27488,6 +28105,350 @@ export type Database = {},]}+ payment: {+ Row: {+ bankAccount: string+ companyId: string+ createdAt: string+ createdBy: string+ currencyCode: string+ customerId: string | null+ customFields: Json | null+ exchangeRate: number+ id: string+ journalId: string | null+ memo: string | null+ paymentDate: string+ paymentId: string+ paymentType: Database["public"]["Enums"]["paymentType"]+ postedAt: string | null+ postedBy: string | null+ postingDate: string | null+ reference: string | null+ status: Database["public"]["Enums"]["paymentStatus"]+ supplierId: string | null+ totalAmount: number+ updatedAt: string | null+ updatedBy: string | null+ voidedAt: string | null+ voidedBy: string | null+ }+ Insert: {+ bankAccount: string+ companyId: string+ createdAt?: string+ createdBy: string+ currencyCode: string+ customerId?: string | null+ customFields?: Json | null+ exchangeRate?: number+ id?: string+ journalId?: string | null+ memo?: string | null+ paymentDate: string+ paymentId: string+ paymentType: Database["public"]["Enums"]["paymentType"]+ postedAt?: string | null+ postedBy?: string | null+ postingDate?: string | null+ reference?: string | null+ status?: Database["public"]["Enums"]["paymentStatus"]+ supplierId?: string | null+ totalAmount: number+ updatedAt?: string | null+ updatedBy?: string | null+ voidedAt?: string | null+ voidedBy?: string | null+ }+ Update: {+ bankAccount?: string+ companyId?: string+ createdAt?: string+ createdBy?: string+ currencyCode?: string+ customerId?: string | null+ customFields?: Json | null+ exchangeRate?: number+ id?: string+ journalId?: string | null+ memo?: string | null+ paymentDate?: string+ paymentId?: string+ paymentType?: Database["public"]["Enums"]["paymentType"]+ postedAt?: string | null+ postedBy?: string | null+ postingDate?: string | null+ reference?: string | null+ status?: Database["public"]["Enums"]["paymentStatus"]+ supplierId?: string | null+ totalAmount?: number+ updatedAt?: string | null+ updatedBy?: string | null+ voidedAt?: string | null+ voidedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "payment_bankAccount_fkey"+ columns: ["bankAccount"]+ isOneToOne: false+ referencedRelation: "account"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_bankAccount_fkey"+ columns: ["bankAccount"]+ isOneToOne: false+ referencedRelation: "accounts"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "payment_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "payment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "payment_currencyCode_fkey"+ columns: ["currencyCode"]+ isOneToOne: false+ referencedRelation: "currencyCode"+ referencedColumns: ["code"]+ },+ {+ foreignKeyName: "payment_customerId_fkey"+ columns: ["customerId"]+ isOneToOne: false+ referencedRelation: "customer"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_customerId_fkey"+ columns: ["customerId"]+ isOneToOne: false+ referencedRelation: "customers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_customerId_fkey"+ columns: ["customerId"]+ isOneToOne: false+ referencedRelation: "salesOrderCustomers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_journalId_fkey"+ columns: ["journalId"]+ isOneToOne: false+ referencedRelation: "journal"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_journalId_fkey"+ columns: ["journalId"]+ isOneToOne: false+ referencedRelation: "journalEntries"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_postedBy_fkey"+ columns: ["postedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_postedBy_fkey"+ columns: ["postedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_postedBy_fkey"+ columns: ["postedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_postedBy_fkey"+ columns: ["postedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_postedBy_fkey"+ columns: ["postedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "payment_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "contractors"+ referencedColumns: ["supplierId"]+ },+ {+ foreignKeyName: "payment_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "partners"+ referencedColumns: ["supplierId"]+ },+ {+ foreignKeyName: "payment_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "purchaseOrderSuppliers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "supplier"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_supplierId_fkey"+ columns: ["supplierId"]+ isOneToOne: false+ referencedRelation: "suppliers"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "payment_voidedBy_fkey"+ columns: ["voidedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_voidedBy_fkey"+ columns: ["voidedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_voidedBy_fkey"+ columns: ["voidedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_voidedBy_fkey"+ columns: ["voidedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "payment_voidedBy_fkey"+ columns: ["voidedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }paymentTerm: {Row: {active: boolean@@ -28148,18 +29109,21 @@ export type Database = {}pickingListLineTrackedEntity: {Row: {+ companyId: stringpickingListLineId: stringquantity: numberquantityPicked: numbertrackedEntityId: string}Insert: {+ companyId: stringpickingListLineId: stringquantity: numberquantityPicked?: numbertrackedEntityId: string}Update: {+ companyId?: stringpickingListLineId?: stringquantity?: numberquantityPicked?: number@@ -29839,7 +30803,6 @@ export type Database = {purchaseInvoice: {Row: {assignee: string | null- balance: numbercompanyId: stringcreatedAt: stringcreatedBy: string@@ -29873,7 +30836,6 @@ export type Database = {}Insert: {assignee?: string | null- balance?: numbercompanyId: stringcreatedAt?: stringcreatedBy: string@@ -29907,7 +30869,6 @@ export type Database = {}Update: {assignee?: string | null- balance?: numbercompanyId?: stringcreatedAt?: stringcreatedBy?: string@@ -30755,48 +31716,9 @@ export type Database = {},]}- purchaseInvoicePaymentRelation: {- Row: {- id: string- invoiceId: string- paymentId: string- }- Insert: {- id?: string- invoiceId: string- paymentId: string- }- Update: {- id?: string- invoiceId?: string- paymentId?: string- }- Relationships: [- {- foreignKeyName: "purchasePayments_invoiceId_fkey"- columns: ["invoiceId"]- isOneToOne: false- referencedRelation: "purchaseInvoice"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayments_invoiceId_fkey"- columns: ["invoiceId"]- isOneToOne: false- referencedRelation: "purchaseInvoices"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayments_paymentId_fkey"- columns: ["paymentId"]- isOneToOne: false- referencedRelation: "purchasePayment"- referencedColumns: ["id"]- },- ]- }purchaseInvoicePriceChange: {Row: {+ companyId: stringid: stringinvoiceId: stringinvoiceLineId: string@@ -30807,6 +31729,7 @@ export type Database = {updatedBy: string}Insert: {+ companyId: stringid?: stringinvoiceId: stringinvoiceLineId: string@@ -30817,6 +31740,7 @@ export type Database = {updatedBy: string}Update: {+ companyId?: stringid?: stringinvoiceId?: stringinvoiceLineId?: string@@ -30894,18 +31818,21 @@ export type Database = {}purchaseInvoiceStatusHistory: {Row: {+ companyId: stringcreatedAt: stringid: stringinvoiceId: stringstatus: Database["public"]["Enums"]["purchaseInvoiceStatus"]}Insert: {+ companyId: stringcreatedAt?: stringid?: stringinvoiceId: stringstatus: Database["public"]["Enums"]["purchaseInvoiceStatus"]}Update: {+ companyId?: stringcreatedAt?: stringid?: stringinvoiceId?: string@@ -32086,6 +33013,7 @@ export type Database = {}purchaseOrderStatusHistory: {Row: {+ companyId: stringcreatedAt: stringcreatedBy: stringid: string@@ -32093,6 +33021,7 @@ export type Database = {status: Database["public"]["Enums"]["purchaseOrderStatus"]}Insert: {+ companyId: stringcreatedAt?: stringcreatedBy: stringid?: string@@ -32100,6 +33029,7 @@ export type Database = {status: Database["public"]["Enums"]["purchaseOrderStatus"]}Update: {+ companyId?: stringcreatedAt?: stringcreatedBy?: stringid?: string@@ -32167,6 +33097,7 @@ export type Database = {}purchaseOrderTransaction: {Row: {+ companyId: stringcreatedAt: stringid: stringpurchaseOrderId: string@@ -32174,6 +33105,7 @@ export type Database = {userId: string}Insert: {+ companyId: stringcreatedAt?: stringid?: stringpurchaseOrderId: string@@ -32181,6 +33113,7 @@ export type Database = {userId: string}Update: {+ companyId?: stringcreatedAt?: stringid?: stringpurchaseOrderId?: string@@ -32246,195 +33179,6 @@ export type Database = {},]}- purchasePayment: {- Row: {- companyId: string- createdAt: string- createdBy: string- currencyCode: string- customFields: Json | null- exchangeRate: number- id: string- paymentDate: string | null- paymentId: string- supplierId: string- totalAmount: number- updatedAt: string | null- updatedBy: string | null- }- Insert: {- companyId: string- createdAt?: string- createdBy: string- currencyCode: string- customFields?: Json | null- exchangeRate?: number- id?: string- paymentDate?: string | null- paymentId: string- supplierId: string- totalAmount?: number- updatedAt?: string | null- updatedBy?: string | null- }- Update: {- companyId?: string- createdAt?: string- createdBy?: string- currencyCode?: string- customFields?: Json | null- exchangeRate?: number- id?: string- paymentDate?: string | null- paymentId?: string- supplierId?: string- totalAmount?: number- updatedAt?: string | null- updatedBy?: string | null- }- Relationships: [- {- foreignKeyName: "purchasePayment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "companies"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "company"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "customFieldTables"- referencedColumns: ["companyId"]- },- {- foreignKeyName: "purchasePayment_companyId_fkey"- columns: ["companyId"]- isOneToOne: false- referencedRelation: "integrations"- referencedColumns: ["companyId"]- },- {- foreignKeyName: "purchasePayment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_createdBy_fkey"- columns: ["createdBy"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },- {- foreignKeyName: "purchasePayment_currencyCode_fkey"- columns: ["currencyCode"]- isOneToOne: false- referencedRelation: "currencyCode"- referencedColumns: ["code"]- },- {- foreignKeyName: "purchasePayment_supplierId_fkey"- columns: ["supplierId"]- isOneToOne: false- referencedRelation: "contractors"- referencedColumns: ["supplierId"]- },- {- foreignKeyName: "purchasePayment_supplierId_fkey"- columns: ["supplierId"]- isOneToOne: false- referencedRelation: "partners"- referencedColumns: ["supplierId"]- },- {- foreignKeyName: "purchasePayment_supplierId_fkey"- columns: ["supplierId"]- isOneToOne: false- referencedRelation: "purchaseOrderSuppliers"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_supplierId_fkey"- columns: ["supplierId"]- isOneToOne: false- referencedRelation: "supplier"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_supplierId_fkey"- columns: ["supplierId"]- isOneToOne: false- referencedRelation: "suppliers"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employees"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employeesAcrossCompanies"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "employeeSummary"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "user"- referencedColumns: ["id"]- },- {- foreignKeyName: "purchasePayment_updatedBy_fkey"- columns: ["updatedBy"]- isOneToOne: false- referencedRelation: "userDefaults"- referencedColumns: ["userId"]- },- ]- }purchasingRfq: {Row: {assignee: string | null@@ -34425,6 +35169,7 @@ export type Database = {quoteLinePrice: {Row: {categoryMarkups: Json | null+ companyId: stringconvertedNetExtendedPrice: number | nullconvertedNetUnitPrice: number | nullconvertedShippingCost: number | null@@ -34446,6 +35191,7 @@ export type Database = {}Insert: {categoryMarkups?: Json | null+ companyId: stringconvertedNetExtendedPrice?: number | nullconvertedNetUnitPrice?: number | nullconvertedShippingCost?: number | null@@ -34467,6 +35213,7 @@ export type Database = {}Update: {categoryMarkups?: Json | null+ companyId?: stringconvertedNetExtendedPrice?: number | nullconvertedNetUnitPrice?: number | nullconvertedShippingCost?: number | null@@ -37270,7 +38017,6 @@ export type Database = {salesInvoice: {Row: {assignee: string | null- balance: numbercompanyId: stringcreatedAt: stringcreatedBy: string@@ -37306,7 +38052,6 @@ export type Database = {}Insert: {assignee?: string | null- balance?: numbercompanyId: stringcreatedAt?: stringcreatedBy: string@@ -37342,7 +38087,6 @@ export type Database = {}Update: {assignee?: string | null- balance?: numbercompanyId?: stringcreatedAt?: stringcreatedBy?: string@@ -39220,6 +39964,7 @@ export type Database = {}salesOrderStatusHistory: {Row: {+ companyId: stringcreatedAt: stringcreatedBy: stringid: string@@ -39227,6 +39972,7 @@ export type Database = {status: Database["public"]["Enums"]["salesOrderStatus"]}Insert: {+ companyId: stringcreatedAt?: stringcreatedBy: stringid?: string@@ -39234,6 +39980,7 @@ export type Database = {status: Database["public"]["Enums"]["salesOrderStatus"]}Update: {+ companyId?: stringcreatedAt?: stringcreatedBy?: stringid?: string@@ -39301,6 +40048,7 @@ export type Database = {}salesOrderTransaction: {Row: {+ companyId: stringcreatedAt: stringid: stringsalesOrderId: string@@ -39308,6 +40056,7 @@ export type Database = {userId: string}Insert: {+ companyId: stringcreatedAt?: stringid?: stringsalesOrderId: string@@ -39315,6 +40064,7 @@ export type Database = {userId: string}Update: {+ companyId?: stringcreatedAt?: stringid?: stringsalesOrderId?: string@@ -40148,7 +40898,7 @@ export type Database = {},]}- searchIndex_d8u703oeq0gg2jnc1k2g: {+ searchIndex_d90t6nfl60gg2fpujaag: {Row: {createdAt: stringdescription: string | null@@ -43621,6 +44371,7 @@ export type Database = {}supplierContact: {Row: {+ companyId: stringcontactId: stringcustomFields: Json | nullid: string@@ -43630,6 +44381,7 @@ export type Database = {userId: string | null}Insert: {+ companyId: stringcontactId: stringcustomFields?: Json | nullid?: string@@ -43639,6 +44391,7 @@ export type Database = {userId?: string | null}Update: {+ companyId?: stringcontactId?: stringcustomFields?: Json | nullid?: string@@ -43928,6 +44681,7 @@ export type Database = {supplierLocation: {Row: {addressId: string+ companyId: stringcustomFields: Json | nullid: stringname: string@@ -43936,6 +44690,7 @@ export type Database = {}Insert: {addressId: string+ companyId: stringcustomFields?: Json | nullid?: stringname: string@@ -43944,6 +44699,7 @@ export type Database = {}Update: {addressId?: string+ companyId?: stringcustomFields?: Json | nullid?: stringname?: string@@ -45433,6 +46189,7 @@ export type Database = {}supplierQuoteLinePrice: {Row: {+ companyId: stringcreatedAt: stringcreatedBy: stringexchangeRate: number | null@@ -45453,6 +46210,7 @@ export type Database = {updatedBy: string | null}Insert: {+ companyId: stringcreatedAt?: stringcreatedBy: stringexchangeRate?: number | null@@ -45473,6 +46231,7 @@ export type Database = {updatedBy?: string | null}Update: {+ companyId?: stringcreatedAt?: stringcreatedBy?: stringexchangeRate?: number | null@@ -56440,14 +57199,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"]@@ -57458,7 +58217,7 @@ export type Database = {paymentTermId: string | nullpaymentTermName: string | nullpostingDate: string | null- status: Database["public"]["Enums"]["purchaseInvoiceStatus"] | null+ status: string | nullsubtotal: number | nullsupplierId: string | nullsupplierInteractionId: string | null@@ -58111,14 +58870,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -61544,21 +62303,21 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -61596,7 +62355,7 @@ export type Database = {paymentTermId: string | nullpostingDate: string | nullshipmentId: string | null- status: Database["public"]["Enums"]["salesInvoiceStatus"] | null+ status: string | nullsubtotal: number | nulltags: string[] | nullthumbnailPath: string | null@@ -65723,7 +66482,97 @@ export type Database = {workCenterId: string}[]}+ get_ap_aging: {+ Args: {+ _aging_method?: string+ _as_of_date: string+ _bucket1?: number+ _bucket2?: number+ _bucket3?: number+ _company_id: string+ }+ Returns: {+ bucket1: number+ bucket2: number+ bucket3: number+ bucket4: number+ current: number+ paymentTerm: string+ supplierId: string+ total: number+ unapplied: number+ }[]+ }+ get_ap_open_by_supplier: {+ Args: { _as_of_date: string; _company_id: string }+ Returns: {+ currencyCode: string+ dateDue: string+ documentId: string+ documentNumber: string+ documentType: string+ exchangeRate: number+ openInBase: number+ openInCurrency: number+ settled: number+ supplierId: string+ totalAmount: number+ }[]+ }+ get_ap_tie_out: {+ Args: { _as_of_date: string; _company_id: string }+ Returns: {+ glBalance: number+ subledgerBalance: number+ variance: number+ }[]+ }get_api_key_scopes: { Args: never; Returns: Json }+ get_ar_aging: {+ Args: {+ _aging_method?: string+ _as_of_date: string+ _bucket1?: number+ _bucket2?: number+ _bucket3?: number+ _company_id: string+ }+ Returns: {+ bucket1: number+ bucket2: number+ bucket3: number+ bucket4: number+ current: number+ customerId: string+ paymentTerm: string+ total: number+ unapplied: number+ }[]+ }+ get_ar_open_by_customer: {+ Args: { _as_of_date: string; _company_id: string }+ Returns: {+ currencyCode: string+ customerId: string+ dateDue: string+ documentId: string+ documentNumber: string+ documentType: string+ exchangeRate: number+ openInBase: number+ openInCurrency: number+ settled: number+ totalAmount: number+ }[]+ }+ get_ar_tie_out: {+ Args: { _as_of_date: string; _company_id: string }+ Returns: {+ glBalance: number+ subledgerBalance: number+ variance: number+ }[]+ }get_assigned_job_operations: {Args: { company_id: string; user_id: string }Returns: {@@ -67759,6 +68608,9 @@ export type Database = {| "WorkCenter"| "Process"| "FixedAssetClass"+ | "Customer"+ | "Supplier"+ | "Item"disposalMethod: "Sale" | "Scrapping"disposition:| "Conditional Acceptance"@@ -67978,6 +68830,9 @@ export type Database = {| "Job Close"| "Asset Depreciation"| "Asset Disposal"+ | "Payment"+ | "Credit Memo"+ | "Debit Memo"journalEntryStatus: "Draft" | "Posted" | "Reversed"journalLineDocumentType:| "Receipt"@@ -67995,6 +68850,8 @@ export type Database = {| "Maintenance Consumption"| "Production Event"| "Job Close"+ | "Payment"+ | "Memo"kanbanOutput: "label" | "qrcode" | "url"macrsConvention: "Half-Year" | "Mid-Quarter"macrsPropertyClass: "3" | "5" | "7" | "10" | "15" | "20" | "27.5" | "39"@@ -68023,6 +68880,8 @@ export type Database = {| "OEM Required"maintenanceSource: "Scheduled" | "Reactive" | "Non-Conformance"makeMethodStatus: "Draft" | "Active" | "Archived"+ memoDirection: "Credit" | "Debit"+ memoStatus: "Draft" | "Posted" | "Voided"methodOperationOrder: "After Previous" | "With Previous"methodType: "Purchase to Order" | "Pull from Inventory" | "Make to Order"module:@@ -68082,7 +68941,9 @@ export type Database = {| "Service"| "Consumable"| "Fixture"+ paymentStatus: "Draft" | "Posted" | "Voided"paymentTermCalculationMethod: "Net" | "End of Month" | "Day of Month"+ paymentType: "Receipt" | "Disbursement"periodType: "Week" | "Day" | "Month"pickingListLineStatus: "Pending" | "Picked" | "Short" | "Cancelled"pickingListStatus: "Draft" | "In Progress" | "Completed" | "Cancelled"@@ -69057,6 +69918,9 @@ export const Constants = {"WorkCenter","Process","FixedAssetClass",+ "Customer",+ "Supplier",+ "Item",],disposalMethod: ["Sale", "Scrapping"],disposition: [@@ -69296,6 +70160,9 @@ export const Constants = {"Job Close","Asset Depreciation","Asset Disposal",+ "Payment",+ "Credit Memo",+ "Debit Memo",],journalEntryStatus: ["Draft", "Posted", "Reversed"],journalLineDocumentType: [@@ -69314,6 +70181,8 @@ export const Constants = {"Maintenance Consumption","Production Event","Job Close",+ "Payment",+ "Memo",],kanbanOutput: ["label", "qrcode", "url"],macrsConvention: ["Half-Year", "Mid-Quarter"],@@ -69347,6 +70216,8 @@ export const Constants = {],maintenanceSource: ["Scheduled", "Reactive", "Non-Conformance"],makeMethodStatus: ["Draft", "Active", "Archived"],+ memoDirection: ["Credit", "Debit"],+ memoStatus: ["Draft", "Posted", "Voided"],methodOperationOrder: ["After Previous", "With Previous"],methodType: ["Purchase to Order", "Pull from Inventory", "Make to Order"],module: [@@ -69411,7 +70282,9 @@ export const Constants = {"Consumable","Fixture",],+ paymentStatus: ["Draft", "Posted", "Voided"],paymentTermCalculationMethod: ["Net", "End of Month", "Day of Month"],+ paymentType: ["Receipt", "Disbursement"],periodType: ["Week", "Day", "Month"],pickingListLineStatus: ["Pending", "Picked", "Short", "Cancelled"],pickingListStatus: ["Draft", "In Progress", "Completed", "Cancelled"],diff --git a/packages/database/supabase/functions/post-memo/build-memo-journal.ts b/packages/database/supabase/functions/post-memo/build-memo-journal.tsnew file mode 100644index 0000000000..08ebad44f1--- /dev/null+++ b/packages/database/supabase/functions/post-memo/build-memo-journal.ts@@ -0,0 +1,173 @@+// Pure construction of the GL journal for posting a credit/debit memo. No DB, no+// I/O, no clock — so it is unit-testable with `deno test`. The driver+// (`index.ts`) resolves the control + reason account ids, the reason account's+// class, the accounting period and `journalLineReference` (all impure), then+// hands them here to compute the balanced two-line double-entry.+//+// A memo is payment-shaped, NOT invoice-shaped: it moves an amount between the+// party's AR/AP control account and a single chosen reason account. There are+// four combos (customer/supplier × credit/debit); two axes drive the posting:+// * isAR — customer (AR, asset control) vs supplier (AP, liability control)+// * direction — 'Credit' or 'Debit'. This alone decides the control side:+// a Debit memo DEBITS the control account, a Credit memo CREDITS+// it — for BOTH AR and AP. Worked through:+// Customer Credit → reduce AR → CR asset (control credit)+// Customer Debit → increase AR→ DR asset (control debit)+// Supplier Credit → increase AP→ CR liab. (control credit)+// Supplier Debit → reduce AP → DR liab. (control debit)+// i.e. controlIsDebit === (direction === 'Debit') universally.+// The reason leg is always the inverse side, booked at the reason account's+// natural class so its stored natural-balance `amount` sign is correct.+//+// A memo is a single-currency document booked at its own exchange rate, so there+// is no realized FX at post time (FX only realizes when CASH later settles the+// memo — a separate payment posting). Both legs use the same base amount, so the+// entry balances exactly.++import { credit, debit } from "../lib/utils.ts";++export const round4 = (n: number) => Math.round(n * 10000) / 10000;++type AccountType = "asset" | "liability" | "equity" | "revenue" | "expense";++// glAccountClass (Asset|Liability|Equity|Revenue|Expense) → the lowercase+// AccountType the debit/credit helpers expect.+export function accountTypeFromClass(glClass: string): AccountType {+ switch (glClass) {+ case "Asset":+ return "asset";+ case "Liability":+ return "liability";+ case "Equity":+ return "equity";+ case "Revenue":+ return "revenue";+ case "Expense":+ return "expense";+ default:+ throw new Error(`Unknown GL account class: ${glClass}`);+ }+}++// A journal line this builder emits. Self-contained — a pure unit shouldn't+// depend on the generated DB types, and `journalLine.documentType`'s "Memo" enum+// value (migration 20260628143012) isn't in the generated lib/types.ts until the+// DB is rebuilt. The driver spreads `journalId` on before the Kysely insert.+export interface MemoJournalLine {+ accountId: string;+ description: string;+ amount: number;+ quantity: number;+ documentType: "Memo";+ documentId: string;+ journalLineReference: string;+ companyId: string;+}++export interface BuildMemoJournalInput {+ // Internal memo record id — becomes `documentId` on every line.+ memoId: string;+ companyId: string;+ // customer (AR) vs supplier (AP). Drives control account TYPE (asset/liability).+ isAR: boolean;+ direction: "Credit" | "Debit";+ // memo.amount × memo.exchangeRate (base currency).+ amountBase: number;+ // Resolved once by the driver (nanoid) so this stays pure.+ journalLineReference: string;+ // receivables (AR) / payables (AP) control account.+ controlAccountId: string;+ // the memo's chosen reason account + its glAccountClass.+ reasonAccountId: string;+ reasonAccountClass: string;+}++export interface BuildMemoJournalResult {+ lines: MemoJournalLine[];+ // Running debit(+)/credit(−) balance; ~0 for a balanced entry.+ signedDebitTotal: number;+}++// Maximum residual (base ccy) we tolerate before refusing to post.+const BALANCE_TOLERANCE = 0.01;++export function buildMemoJournal(+ input: BuildMemoJournalInput+): BuildMemoJournalResult {+ const {+ memoId,+ companyId,+ isAR,+ direction,+ amountBase,+ journalLineReference,+ controlAccountId,+ reasonAccountId,+ reasonAccountClass,+ } = input;++ if (!controlAccountId) {+ throw new Error(+ `Missing ${isAR ? "receivables" : "payables"} account default; cannot post memo to GL`+ );+ }++ const magnitude = round4(Math.abs(amountBase));+ if (magnitude < 0.0001) {+ throw new Error("Memo amount must be greater than 0 to post");+ }++ const lines: MemoJournalLine[] = [];+ let signedDebitTotal = 0;++ const pushLine = (+ side: "debit" | "credit",+ accountType: AccountType,+ accountId: string,+ description: string+ ) => {+ signedDebitTotal += side === "debit" ? magnitude : -magnitude;+ lines.push({+ accountId,+ description,+ amount:+ side === "debit"+ ? debit(accountType, magnitude)+ : credit(accountType, magnitude),+ quantity: 1,+ documentType: "Memo",+ documentId: memoId,+ journalLineReference,+ companyId,+ });+ };++ // Control side is decided by direction alone (see header note).+ const controlIsDebit = direction === "Debit";+ const controlType: AccountType = isAR ? "asset" : "liability";+ const reasonType = accountTypeFromClass(reasonAccountClass);++ // 1) Control leg (AR/AP).+ pushLine(+ controlIsDebit ? "debit" : "credit",+ controlType,+ controlAccountId,+ isAR ? "Accounts Receivable" : "Accounts Payable"+ );++ // 2) Reason leg — always the inverse side, so the entry balances.+ pushLine(+ controlIsDebit ? "credit" : "debit",+ reasonType,+ reasonAccountId,+ direction === "Credit" ? "Credit memo" : "Debit memo"+ );++ if (Math.abs(signedDebitTotal) > BALANCE_TOLERANCE) {+ throw new Error(+ `Memo journal does not balance (off by ${round4(signedDebitTotal)} in base currency); refusing to post`+ );+ }++ return { lines, signedDebitTotal };+}diff --git a/packages/database/supabase/functions/post-memo/index.ts b/packages/database/supabase/functions/post-memo/index.tsnew file mode 100644index 0000000000..790e6ad98c--- /dev/null+++ b/packages/database/supabase/functions/post-memo/index.ts@@ -0,0 +1,448 @@+import { serve } from "https://deno.land/[email protected]/http/server.ts";+import { format } from "https://deno.land/[email protected]/datetime/mod.ts";+import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";+import z from "npm:zod@^3.24.1";+import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { corsHeaders } from "../lib/headers.ts";+import { getSupabaseServiceRole } from "../lib/supabase.ts";++import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";+import { getNextSequence } from "../shared/get-next-sequence.ts";+import { getDefaultPostingGroup } from "../shared/get-posting-group.ts";+import { buildMemoJournal, type MemoJournalLine } from "./build-memo-journal.ts";++const pool = getConnectionPool(1);+const db = getDatabaseClient<DB>(pool);++const payloadValidator = z.object({+ type: z.enum(["post", "void"]).default("post"),+ memoId: z.string(),+ userId: z.string(),+ companyId: z.string(),+});++serve(async (req: Request) => {+ if (req.method === "OPTIONS") {+ return new Response("ok", { headers: corsHeaders });+ }++ const payload = await req.json();+ const today = format(new Date(), "yyyy-MM-dd");++ try {+ const { type, memoId, userId, companyId } = payloadValidator.parse(payload);++ console.log({ function: "post-memo", type, memoId, userId, companyId });++ const client = await getSupabaseServiceRole(+ req.headers.get("Authorization"),+ req.headers.get("carbon-key") ?? "",+ companyId+ );++ const accountingSettings = await client+ .from("companySettings")+ .select("accountingEnabled")+ .eq("id", companyId)+ .single();+ const accountingEnabled =+ accountingSettings.data?.accountingEnabled ?? false;++ const [memo, accountDefaults] = await Promise.all([+ client.from("memo").select("*").eq("id", memoId).single(),+ getDefaultPostingGroup(client, companyId),+ ]);++ if (memo.error) throw new Error("Failed to fetch memo");+ if (accountingEnabled && accountDefaults.error)+ throw new Error("Failed to fetch account defaults");++ // isAR: a customer memo settles AR; a supplier memo settles AP.+ const isAR = memo.data.customerId != null;++ // --------------------------------------------------------------+ // VOID+ // --------------------------------------------------------------+ if (type === "void") {+ if (memo.data.status !== "Posted") {+ throw new Error(+ `Cannot void memo in status ${memo.data.status} (only Posted)`+ );+ }++ const accountingPeriodId = accountingEnabled+ ? await getCurrentAccountingPeriod(client, companyId, db)+ : null;++ await db.transaction().execute(async (trx) => {+ // Lock the memo row and re-assert it's still Posted INSIDE the+ // transaction. The status check above runs before the lock (a TOCTOU+ // window): two concurrent voids could otherwise both pass it and each+ // emit a reversing journal. The FOR UPDATE serializes them.+ const lockedMemo = await trx+ .selectFrom("memo")+ .select(["id", "status"])+ .where("id", "=", memoId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!lockedMemo) throw new Error("Memo not found");+ if (lockedMemo.status !== "Posted") {+ throw new Error(+ `Cannot void memo in status ${lockedMemo.status} (only Posted)`+ );+ }++ if (accountingEnabled && memo.data.journalId) {+ // Mirror the original journal's lines into a reversing journal (the+ // same paired-journal approach post-payment/post-purchase-invoice use+ // for voids — never mutate the original).+ const originalLines = await trx+ .selectFrom("journalLine")+ .selectAll()+ .where("journalId", "=", memo.data.journalId)+ .execute();++ if (originalLines.length > 0) {+ const voidEntryId = await getNextSequence(+ trx,+ "journalEntry",+ companyId+ );++ const voidJournal = await trx+ .insertInto("journal")+ .values({+ journalEntryId: voidEntryId,+ accountingPeriodId,+ description: `VOID Memo ${memo.data.memoId}`,+ postingDate: today,+ companyId,+ sourceType:+ memo.data.direction === "Credit"+ ? "Credit Memo"+ : "Debit Memo",+ status: "Posted",+ postedAt: new Date().toISOString(),+ postedBy: userId,+ createdBy: userId,+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ const voidLineResults = await trx+ .insertInto("journalLine")+ .values(+ originalLines.map((line) => ({+ journalId: voidJournal.id,+ accountId: line.accountId,+ amount: -line.amount,+ quantity: line.quantity,+ description: `VOID: ${line.description ?? ""}`,+ documentType: "Memo" as const,+ documentId: memoId,+ documentLineReference: line.documentLineReference,+ journalLineReference: line.journalLineReference,+ companyId,+ }))+ )+ .returning(["id"])+ .execute();++ // Carry the original lines' dimensions onto the reversing lines so+ // dimension-filtered balances net to zero after the void.+ const origDimensions = await trx+ .selectFrom("journalLineDimension")+ .select(["journalLineId", "dimensionId", "valueId"])+ .where(+ "journalLineId",+ "in",+ originalLines.map((l) => l.id)+ )+ .execute();+ if (origDimensions.length > 0) {+ const idxByOriginalId = new Map(+ originalLines.map((l, i) => [l.id, i])+ );+ await trx+ .insertInto("journalLineDimension")+ .values(+ origDimensions.map((d) => ({+ journalLineId:+ voidLineResults[idxByOriginalId.get(d.journalLineId)!].id,+ dimensionId: d.dimensionId,+ valueId: d.valueId,+ companyId,+ }))+ )+ .execute();+ }+ }+ }++ await trx+ .updateTable("memo")+ .set({+ status: "Voided",+ voidedAt: new Date().toISOString(),+ voidedBy: userId,+ updatedAt: new Date().toISOString(),+ updatedBy: userId,+ })+ .where("id", "=", memoId)+ .where("companyId", "=", companyId)+ .execute();+ });++ return new Response(JSON.stringify({ success: true }), {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ });+ }++ // --------------------------------------------------------------+ // POST+ // --------------------------------------------------------------+ if (memo.data.status !== "Draft") {+ throw new Error(+ `Cannot post memo in status ${memo.data.status} (only Draft)`+ );+ }+ if (memo.data.exchangeRate <= 0) {+ throw new Error("Memo exchange rate must be > 0");+ }++ const accountingPeriodId = accountingEnabled+ ? await getCurrentAccountingPeriod(client, companyId, db)+ : null;++ // Build the (balanced, two-line) journal in base currency. Account-id+ // resolution + the control/reason sign logic live in the pure+ // `buildMemoJournal` so they are unit-tested (post-memo.test.ts).+ const journalLineInserts: MemoJournalLine[] = [];+ const partyDimensions: { dimensionId: string; valueId: string }[] = [];+ // The offset ("reason") account is derived here (not a user choice) and+ // stored on the memo at posting for the audit trail / list display.+ let derivedReasonAccountId: string | null = null;++ if (accountingEnabled) {+ if (!accountDefaults.data) {+ throw new Error(+ "Accounting is enabled but this company has no account defaults configured"+ );+ }+ const ad = accountDefaults.data;+ const controlAccountId = isAR+ ? ad.receivablesAccount+ : ad.payablesAccount;++ // The offset account is deterministic by party side (NOT a user choice):+ // customer memos adjust sales (salesDiscountAccount); supplier memos adjust+ // purchases (supplierPaymentDiscountAccount). Direction only flips the+ // debit/credit side, handled inside buildMemoJournal.+ const reasonAccountId = isAR+ ? ad.salesDiscountAccount+ : ad.supplierPaymentDiscountAccount;+ if (!reasonAccountId) {+ throw new Error(+ `Missing ${+ isAR ? "salesDiscountAccount" : "supplierPaymentDiscountAccount"+ } account default; cannot post memo to GL`+ );+ }+ derivedReasonAccountId = reasonAccountId;++ // Resolve the reason account's class so its natural-balance amount sign is+ // correct (the account can be any class).+ const reasonAccount = await client+ .from("account")+ .select("class")+ .eq("id", reasonAccountId)+ .single();+ if (reasonAccount.error || !reasonAccount.data) {+ throw new Error("Failed to fetch the derived reason account");+ }++ const journalLineReference = nanoid();+ const { lines } = buildMemoJournal({+ memoId,+ companyId,+ isAR,+ direction: memo.data.direction as "Credit" | "Debit",+ amountBase: Number(memo.data.amount) * Number(memo.data.exchangeRate),+ journalLineReference,+ controlAccountId,+ reasonAccountId,+ reasonAccountClass: reasonAccount.data.class as string,+ });+ journalLineInserts.push(...lines);++ // Tag the journal lines with the counterparty type + entity dimensions so+ // AR/AP can be reported by counterparty (mirrors post-payment).+ const companyRecord = await client+ .from("company")+ .select("companyGroupId")+ .eq("id", companyId)+ .single();+ const companyGroupId = companyRecord.data?.companyGroupId ?? null;+ const partyId = isAR+ ? (memo.data.customerId as string | null)+ : (memo.data.supplierId as string | null);+ const typeEntityType = isAR ? "CustomerType" : "SupplierType";+ const entityEntityType = isAR ? "Customer" : "Supplier";+ if (companyGroupId && partyId) {+ const [partyRow, dimRows] = await Promise.all([+ isAR+ ? client+ .from("customer")+ .select("customerTypeId")+ .eq("id", partyId)+ .maybeSingle()+ : client+ .from("supplier")+ .select("supplierTypeId")+ .eq("id", partyId)+ .maybeSingle(),+ client+ .from("dimension")+ .select("id, entityType")+ .eq("companyGroupId", companyGroupId)+ .eq("active", true)+ .in("entityType", [typeEntityType, entityEntityType]),+ ]);+ const dimByEntityType = new Map<string, string>();+ for (const d of dimRows.data ?? []) {+ if (d.entityType) dimByEntityType.set(d.entityType, d.id);+ }+ // deno-lint-ignore no-explicit-any+ const party = partyRow.data as any;+ const partyTypeId = isAR+ ? (party?.customerTypeId ?? null)+ : (party?.supplierTypeId ?? null);+ const typeDimensionId = dimByEntityType.get(typeEntityType);+ if (typeDimensionId && partyTypeId) {+ partyDimensions.push({+ dimensionId: typeDimensionId,+ valueId: partyTypeId,+ });+ }+ const entityDimensionId = dimByEntityType.get(entityEntityType);+ if (entityDimensionId) {+ partyDimensions.push({ dimensionId: entityDimensionId, valueId: partyId });+ }+ }+ }++ // --------------------------------------------------------------+ // Commit: lock the memo, re-check Draft, post the journal, flip Posted.+ // Applying a memo to invoices is GL-neutral (both sit in AR/AP), so there is+ // no invoice validation here — that lives in replaceMemoSettlements.+ // --------------------------------------------------------------+ let createdJournalId: string | null = null;+ await db.transaction().execute(async (trx) => {+ const locked = await trx+ .selectFrom("memo")+ .select(["id", "status"])+ .where("id", "=", memoId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!locked) throw new Error("Memo not found");+ if (locked.status !== "Draft") {+ throw new Error(+ `Cannot post memo in status ${locked.status} (only Draft)`+ );+ }++ let journalId: string | null = null;+ if (accountingEnabled) {+ const journalEntryId = await getNextSequence(+ trx,+ "journalEntry",+ companyId+ );+ const journalResult = await trx+ .insertInto("journal")+ .values({+ journalEntryId,+ accountingPeriodId,+ description: `${memo.data.direction} Memo ${memo.data.memoId}`,+ postingDate: today,+ companyId,+ sourceType:+ memo.data.direction === "Credit" ? "Credit Memo" : "Debit Memo",+ status: "Posted",+ postedAt: new Date().toISOString(),+ postedBy: userId,+ createdBy: userId,+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();+ journalId = journalResult.id;++ if (journalLineInserts.length > 0) {+ const journalLineResults = await trx+ .insertInto("journalLine")+ .values(+ journalLineInserts.map((line) => ({+ ...line,+ journalId: journalResult.id,+ }))+ )+ .returning(["id"])+ .execute();++ if (partyDimensions.length > 0) {+ await trx+ .insertInto("journalLineDimension")+ .values(+ journalLineResults.flatMap((jl) =>+ partyDimensions.map((d) => ({+ journalLineId: jl.id,+ dimensionId: d.dimensionId,+ valueId: d.valueId,+ companyId,+ }))+ )+ )+ .execute();+ }+ }+ }++ await trx+ .updateTable("memo")+ .set({+ status: "Posted",+ postingDate: today,+ journalId,+ reasonAccount: derivedReasonAccountId,+ postedAt: new Date().toISOString(),+ postedBy: userId,+ updatedAt: new Date().toISOString(),+ updatedBy: userId,+ })+ .where("id", "=", memoId)+ .where("companyId", "=", companyId)+ .execute();++ createdJournalId = journalId;+ });++ return new Response(+ JSON.stringify({ success: true, journalId: createdJournalId }),+ { headers: { ...corsHeaders, "Content-Type": "application/json" } }+ );+ } catch (err) {+ console.error(err);+ return new Response(+ JSON.stringify({+ success: false,+ message: err instanceof Error ? err.message : String(err),+ }),+ {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 500,+ }+ );+ }+});diff --git a/packages/database/supabase/functions/post-memo/post-memo.test.ts b/packages/database/supabase/functions/post-memo/post-memo.test.tsnew file mode 100644index 0000000000..dd282e1844--- /dev/null+++ b/packages/database/supabase/functions/post-memo/post-memo.test.ts@@ -0,0 +1,91 @@+import {+ assert,+ assertEquals,+ assertThrows,+} from "https://deno.land/[email protected]/testing/asserts.ts";+import { buildMemoJournal, type BuildMemoJournalInput } from "./build-memo-journal.ts";++// Golden-master tests for the GL journal a credit/debit memo posts. A memo is a+// two-line entry: the AR/AP control leg and a reason leg. Direction alone decides+// the control side (Debit memo → DR control, Credit memo → CR control) for BOTH+// AR and AP. The reason leg is the inverse side, booked at the reason account's+// natural class. Every combo must balance (signedDebitTotal ~ 0).++const base = (+ overrides: Partial<BuildMemoJournalInput>+): BuildMemoJournalInput => ({+ memoId: "memo_1",+ companyId: "co_1",+ isAR: true,+ direction: "Credit",+ amountBase: 300,+ journalLineReference: "ref_1",+ controlAccountId: "acct_ar",+ reasonAccountId: "acct_reason",+ reasonAccountClass: "Revenue",+ ...overrides,+});++// Helpers: stored `amount` is natural-balance signed. For an asset, a debit is+// +mag and a credit is −mag; for a liability/revenue it's the opposite.+const line = (r: ReturnType<typeof buildMemoJournal>, accountId: string) =>+ r.lines.find((l) => l.accountId === accountId)!;++Deno.test("customer Credit memo: CR AR (asset), DR reason; balances", () => {+ const r = buildMemoJournal(base({ isAR: true, direction: "Credit" }));+ assertEquals(r.lines.length, 2);+ // Control AR is an asset; a credit stores −magnitude.+ assertEquals(line(r, "acct_ar").amount, -300);+ // Reason is Revenue; a debit stores −magnitude.+ assertEquals(line(r, "acct_reason").amount, -300);+ assert(Math.abs(r.signedDebitTotal) < 0.01);+});++Deno.test("customer Debit memo: DR AR (asset), CR reason; balances", () => {+ const r = buildMemoJournal(base({ isAR: true, direction: "Debit" }));+ // Control AR debit stores +magnitude.+ assertEquals(line(r, "acct_ar").amount, 300);+ // Reason Revenue credit stores +magnitude.+ assertEquals(line(r, "acct_reason").amount, 300);+ assert(Math.abs(r.signedDebitTotal) < 0.01);+});++Deno.test("supplier Credit memo: CR AP (liability), DR reason; balances", () => {+ const r = buildMemoJournal(+ base({ isAR: false, direction: "Credit", reasonAccountClass: "Expense" })+ );+ // Control AP is a liability; a credit stores +magnitude.+ assertEquals(line(r, "acct_ar").amount, 300);+ // Reason Expense debit stores +magnitude.+ assertEquals(line(r, "acct_reason").amount, 300);+ assert(Math.abs(r.signedDebitTotal) < 0.01);+});++Deno.test("supplier Debit memo: DR AP (liability), CR reason; balances", () => {+ const r = buildMemoJournal(+ base({ isAR: false, direction: "Debit", reasonAccountClass: "Expense" })+ );+ // Control AP debit (liability) stores −magnitude.+ assertEquals(line(r, "acct_ar").amount, -300);+ // Reason Expense credit stores −magnitude.+ assertEquals(line(r, "acct_reason").amount, -300);+ assert(Math.abs(r.signedDebitTotal) < 0.01);+});++Deno.test("rounds to 4dp and stays balanced on fractional amounts", () => {+ const r = buildMemoJournal(base({ amountBase: 123.456789 }));+ assertEquals(line(r, "acct_ar").amount, -123.4568);+ assert(Math.abs(r.signedDebitTotal) < 0.01);+});++Deno.test("rejects a zero amount", () => {+ assertThrows(() => buildMemoJournal(base({ amountBase: 0 })), Error, "greater than 0");+});++Deno.test("rejects an unknown reason account class", () => {+ assertThrows(+ () => buildMemoJournal(base({ reasonAccountClass: "Bogus" })),+ Error,+ "Unknown GL account class"+ );+});diff --git a/packages/database/supabase/functions/post-payment/build-payment-journal.ts b/packages/database/supabase/functions/post-payment/build-payment-journal.tsnew file mode 100644index 0000000000..f3415dc829--- /dev/null+++ b/packages/database/supabase/functions/post-payment/build-payment-journal.ts@@ -0,0 +1,309 @@+// Pure construction of the GL journal for posting an AR/AP payment. No DB, no+// I/O, no clock — so it is unit-testable with `deno test`. The driver+// (`index.ts`) resolves the account ids, dimensions, accounting period and+// `journalLineReference` (all impure), then hands them here to compute the+// balanced double-entry. Keeping this pure is what lets the golden-master tests+// pin the exact journal for every AR/AP × partial/full × discount/write-off ×+// FX-gain/loss × unapplied-credit permutation — the lines that hit the general+// ledger must be provably correct, not merely inspected.+//+// TWO independent axes (decoupled so REFUNDS work — a refund is cash flowing the+// "wrong" way for its ledger):+// * isAR — does this payment settle AR (customer) or AP (supplier)? Drives+// account SELECTION (receivables vs payables, customer vs supplier+// discount/write-off) and the realized-FX gain/loss DIRECTION.+// * cashIn — does cash come INTO our bank (Receipt) or leave it (Disbursement)?+// Drives the debit/credit SIDE of every line.+// Normal receipt: isAR && cashIn. Normal disbursement: !isAR && !cashIn.+// AR refund (cash out to a customer against a credit memo): isAR && !cashIn.+// AP refund (cash in from a supplier against a debit memo): !isAR && cashIn.+//+// Posting model (all amounts converted to base currency):+// 1) Cash — DR Bank (cashIn) / CR Bank (!cashIn) for the full cash.+// 2) Per app — control account (AR/AP) at the TARGET rate so it reverses the+// original booking exactly; discount and write-off (also+// invoice-currency reliefs) at the target rate; realized FX on+// the cash-settled principal accumulated for a single plug.+// 3) Unapplied — cash beyond what was applied becomes new on-account credit;+// applying more than the cash draws down existing credit (the+// inverse posting side).+// 4) FX plug — one Realized FX Gain / Loss line for the accumulated FX.+//+// FX sign convention: `totalFxImpact` is normalized by the (isAR ? 1 : -1)+// factor so a POSITIVE value ALWAYS means a gain and a NEGATIVE value ALWAYS+// means a loss, for both AR and AP. This is the same quantity the stored+// `invoiceSettlement.fxGainLossAmount` captures, so the subledger reconciles.++import { credit, debit } from "../lib/utils.ts";++// A journal line this builder emits. Deliberately self-contained — a pure unit+// shouldn't depend on the generated DB types, and `journalLine.documentType`'s+// "Payment" enum value (migration 20260628143012) isn't in the generated+// lib/types.ts until the DB is rebuilt and `db:types` is regenerated. The driver+// spreads `journalId` on before the Kysely insert.+export interface PaymentJournalLine {+ accountId: string;+ description: string;+ amount: number;+ quantity: number;+ documentType: "Payment";+ documentId: string;+ documentLineReference?: string;+ journalLineReference: string;+ companyId: string;+}++// Round to 4 decimal places to match NUMERIC(19,4) storage and prevent+// floating-point cruft from making the journal fail its balance check. Shared+// with the driver so amounts are rounded identically everywhere.+export const round4 = (n: number) => Math.round(n * 10000) / 10000;++export interface PaymentJournalApplicationInput {+ targetSalesInvoiceId?: string | null;+ targetPurchaseInvoiceId?: string | null;+ appliedAmount: number;+ discountAmount: number;+ writeOffAmount: number;+ targetExchangeRate: number;+ sourceExchangeRate: number;+}++export interface PaymentJournalAccounts {+ controlAccountId: string | null;+ discountAccountId: string | null;+ writeOffAccountId: string | null;+ fxGainAccountId: string | null;+ fxLossAccountId: string | null;+}++export interface BuildPaymentJournalInput {+ // Internal payment record id — becomes `documentId` on every line.+ paymentId: string;+ companyId: string;+ // See the two-axis note at the top of the file.+ isAR: boolean;+ cashIn: boolean;+ totalAmount: number;+ exchangeRate: number;+ bankAccount: string;+ // Resolved once by the driver (nanoid) so this stays pure.+ journalLineReference: string;+ applications: PaymentJournalApplicationInput[];+ accounts: PaymentJournalAccounts;+}++export interface BuildPaymentJournalResult {+ lines: PaymentJournalLine[];+ // Running debit(+)/credit(−) balance; ~0 for a balanced entry.+ signedDebitTotal: number;+ // Accumulated realized FX in base currency (+gain / −loss). Mirrors the sum of+ // the applications' stored fxGainLossAmount.+ totalFxImpact: number;+}++// Maximum residual (base ccy) we tolerate before refusing to post. Above this a+// logic/rounding bug has produced an unbalanced entry.+const BALANCE_TOLERANCE = 0.01;++export function buildPaymentJournal(+ input: BuildPaymentJournalInput+): BuildPaymentJournalResult {+ const {+ paymentId,+ companyId,+ isAR,+ cashIn,+ totalAmount,+ exchangeRate,+ bankAccount,+ journalLineReference,+ applications,+ accounts,+ } = input;++ const {+ controlAccountId,+ discountAccountId,+ writeOffAccountId,+ fxGainAccountId,+ fxLossAccountId,+ } = accounts;++ if (!controlAccountId) {+ throw new Error(+ `Missing ${isAR ? "receivables" : "payables"} account default; cannot post payment to GL`+ );+ }++ const lines: PaymentJournalLine[] = [];+ // True debit(+)/credit(−) space. A balanced double entry sums to ~0 here. (The+ // stored `amount` is natural-balance signed — credit("asset") is negative — so+ // it does NOT sum to zero; we track debit/credit balance separately.)+ let signedDebitTotal = 0;++ const pushLine = (+ side: "debit" | "credit",+ accountType: "asset" | "liability" | "equity" | "revenue" | "expense",+ magnitude: number,+ fields: {+ accountId: string;+ description: string;+ documentLineReference?: string;+ }+ ) => {+ signedDebitTotal += side === "debit" ? magnitude : -magnitude;+ lines.push({+ accountId: fields.accountId,+ description: fields.description,+ amount:+ side === "debit"+ ? debit(accountType, magnitude)+ : credit(accountType, magnitude),+ quantity: 1,+ documentType: "Payment",+ documentId: paymentId,+ documentLineReference: fields.documentLineReference,+ journalLineReference,+ companyId,+ });+ };++ // 1) Cash: DR Bank (cash in) / CR Bank (cash out), full cash in base.+ const cashBase = round4(totalAmount * exchangeRate);+ pushLine(cashIn ? "debit" : "credit", "asset", cashBase, {+ accountId: bankAccount,+ description: "Bank / Cash",+ });++ // 2) Per application: control at TARGET rate; discount / write-off at target+ // rate. FX is accumulated and plugged once below.+ let totalFxImpact = 0; // base ccy; +ve = gain, −ve = loss (both AR and AP)+ for (const app of applications) {+ const invId = (isAR+ ? app.targetSalesInvoiceId+ : app.targetPurchaseInvoiceId) as string;+ const applied = Number(app.appliedAmount);+ const discount = Number(app.discountAmount);+ const writeOff = Number(app.writeOffAmount);+ const invRate = Number(app.targetExchangeRate);+ const payRate = Number(app.sourceExchangeRate);++ // Control account (AR/AP): at target rate (mirrors the original booking).+ // Side follows the cash direction so it offsets the bank line.+ pushLine(+ cashIn ? "credit" : "debit",+ isAR ? "asset" : "liability",+ round4((applied + discount + writeOff) * invRate),+ {+ accountId: controlAccountId,+ description: isAR ? "Accounts Receivable" : "Accounts Payable",+ documentLineReference: invId,+ }+ );++ // Discount: at TARGET rate (an invoice-currency relief, not cash, so it+ // carries no FX). AR debits (forgone revenue); AP credits (vendor allowance+ // reduces our cost).+ if (discount > 0) {+ if (!discountAccountId) {+ throw new Error(+ `Missing ${isAR ? "customer" : "supplier"} payment discount account default`+ );+ }+ pushLine(cashIn ? "debit" : "credit", "expense", round4(discount * invRate), {+ accountId: discountAccountId,+ description: isAR+ ? "Customer Payment Discount"+ : "Supplier Payment Discount",+ documentLineReference: invId,+ });+ }++ // Write-off: at TARGET rate (an invoice-currency relief, not cash, so it+ // carries no FX). AR is bad debt (expense); AP is vendor write-off (income —+ // class=Revenue).+ if (writeOff > 0) {+ if (!writeOffAccountId) {+ throw new Error(+ `Missing ${isAR ? "customer" : "supplier"} write-off account default`+ );+ }+ pushLine(+ cashIn ? "debit" : "credit",+ isAR ? "expense" : "revenue",+ round4(writeOff * invRate),+ {+ accountId: writeOffAccountId,+ description: isAR ? "Bad Debt Expense" : "Vendor Write-Off Income",+ documentLineReference: invId,+ }+ );+ }++ // Realized FX on the cash-settled principal only: applied × (sourceRate −+ // targetRate). Discount and write-off are invoice-currency reliefs booked at+ // the target rate above, so they carry no FX. The (isAR ? 1 : −1) factor+ // normalizes the sign so +ve is always a gain. Matches the stored+ // invoiceSettlement.fxGainLossAmount so the subledger reconciles.+ totalFxImpact += (isAR ? 1 : -1) * applied * (payRate - invRate);+ }++ // 3) Unapplied cash → control account (no invoice anchor), payment rate.+ // Positive: cash beyond what was applied becomes new on-account credit.+ // Negative: this payment applied more than its cash, drawing down the+ // party's existing on-account credit (the inverse posting side).+ const unappliedInPaymentCcy =+ totalAmount - applications.reduce((sum, a) => sum + Number(a.appliedAmount), 0);+ if (Math.abs(unappliedInPaymentCcy) > 0.0001) {+ const buildingCredit = unappliedInPaymentCcy > 0;+ pushLine(+ cashIn === buildingCredit ? "credit" : "debit",+ isAR ? "asset" : "liability",+ round4(Math.abs(unappliedInPaymentCcy) * exchangeRate),+ {+ accountId: controlAccountId,+ description: isAR+ ? buildingCredit+ ? "Accounts Receivable (on-account credit)"+ : "Accounts Receivable (credit applied)"+ : buildingCredit+ ? "Accounts Payable (on-account credit)"+ : "Accounts Payable (credit applied)",+ }+ );+ }++ // 4) FX plug (single line).+ if (Math.abs(totalFxImpact) > 0.0001) {+ const fxBase = round4(Math.abs(totalFxImpact));+ if (totalFxImpact > 0) {+ if (!fxGainAccountId) {+ throw new Error("Missing realized FX gain account default");+ }+ pushLine("credit", "revenue", fxBase, {+ accountId: fxGainAccountId,+ description: "Realized FX Gain",+ });+ } else {+ if (!fxLossAccountId) {+ throw new Error("Missing realized FX loss account default");+ }+ pushLine("debit", "expense", fxBase, {+ accountId: fxLossAccountId,+ description: "Realized FX Loss",+ });+ }+ }++ // Self-check: the entry must balance in true debit/credit space. The FX plug+ // (same formula as the stored fxGainLossAmount) should make this ~0; a larger+ // residual means a logic/rounding bug, so we refuse to post rather than write+ // an unbalanced journal to the GL.+ if (Math.abs(signedDebitTotal) > BALANCE_TOLERANCE) {+ throw new Error(+ `Payment journal does not balance (off by ${round4(signedDebitTotal)} in base currency); refusing to post`+ );+ }++ return { lines, signedDebitTotal, totalFxImpact };+}diff --git a/packages/database/supabase/functions/post-payment/index.ts b/packages/database/supabase/functions/post-payment/index.tsnew file mode 100644index 0000000000..83cbec6678--- /dev/null+++ b/packages/database/supabase/functions/post-payment/index.ts@@ -0,0 +1,717 @@+import { serve } from "https://deno.land/[email protected]/http/server.ts";+import { format } from "https://deno.land/[email protected]/datetime/mod.ts";+import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";+import z from "npm:zod@^3.24.1";+import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { corsHeaders } from "../lib/headers.ts";+import { getSupabaseServiceRole } from "../lib/supabase.ts";++import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";+import { getNextSequence } from "../shared/get-next-sequence.ts";+import { getDefaultPostingGroup } from "../shared/get-posting-group.ts";+import {+ buildPaymentJournal,+ round4,+ type PaymentJournalLine,+} from "./build-payment-journal.ts";++const pool = getConnectionPool(1);+const db = getDatabaseClient<DB>(pool);++const payloadValidator = z.object({+ type: z.enum(["post", "void"]).default("post"),+ paymentId: z.string(),+ userId: z.string(),+ companyId: z.string(),+});++serve(async (req: Request) => {+ if (req.method === "OPTIONS") {+ return new Response("ok", { headers: corsHeaders });+ }++ const payload = await req.json();+ const today = format(new Date(), "yyyy-MM-dd");++ try {+ const { type, paymentId, userId, companyId } =+ payloadValidator.parse(payload);++ console.log({ function: "post-payment", type, paymentId, userId, companyId });++ const client = await getSupabaseServiceRole(+ req.headers.get("Authorization"),+ req.headers.get("carbon-key") ?? "",+ companyId+ );++ const accountingSettings = await client+ .from("companySettings")+ .select("accountingEnabled")+ .eq("id", companyId)+ .single();+ const accountingEnabled = accountingSettings.data?.accountingEnabled ?? false;++ const [payment, applications, credits, accountDefaults] = await Promise.all([+ client.from("payment").select("*").eq("id", paymentId).single(),+ client.from("invoiceSettlement").select("*").eq("paymentId", paymentId),+ client+ .from("invoiceSettlement")+ .select("*")+ .eq("appliedViaPaymentId", paymentId),+ getDefaultPostingGroup(client, companyId),+ ]);++ if (payment.error) throw new Error("Failed to fetch payment");+ if (applications.error) throw new Error("Failed to fetch payment applications");+ if (credits.error) throw new Error("Failed to fetch credit applications");+ if (accountingEnabled && accountDefaults.error)+ throw new Error("Failed to fetch account defaults");++ // cashIn: direction of cash (Receipt = into our bank). isAR: which ledger+ // this settles (a customer → AR, a supplier → AP). Decoupled so refunds work+ // (a Disbursement to a customer is an AR refund; a Receipt from a supplier is+ // an AP refund). See build-payment-journal's two-axis note.+ const cashIn = payment.data.paymentType === "Receipt";+ const isAR = payment.data.customerId != null;++ // --------------------------------------------------------------+ // VOID+ // --------------------------------------------------------------+ if (type === "void") {+ if (payment.data.status !== "Posted") {+ throw new Error(+ `Cannot void payment in status ${payment.data.status} (only Posted)`+ );+ }++ const accountingPeriodId = accountingEnabled+ ? await getCurrentAccountingPeriod(client, companyId, db)+ : null;++ await db.transaction().execute(async (trx) => {+ // Lock the payment row and re-assert it's still Posted INSIDE the+ // transaction. The status check above runs before the lock (a TOCTOU+ // window): two concurrent voids could otherwise both pass it and each+ // emit a reversing journal. The FOR UPDATE serializes them.+ const lockedPayment = await trx+ .selectFrom("payment")+ .select(["id", "status"])+ .where("id", "=", paymentId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!lockedPayment) throw new Error("Payment not found");+ if (lockedPayment.status !== "Posted") {+ throw new Error(+ `Cannot void payment in status ${lockedPayment.status} (only Posted)`+ );+ }++ if (accountingEnabled && payment.data.journalId) {+ // Pull the original journal's lines and emit a reversing journal+ // (mirror amounts). This matches post-purchase-invoice's void+ // approach — a paired journal rather than mutating the original.+ const originalLines = await trx+ .selectFrom("journalLine")+ .selectAll()+ .where("journalId", "=", payment.data.journalId)+ .execute();++ if (originalLines.length > 0) {+ const voidEntryId = await getNextSequence(+ trx,+ "journalEntry",+ companyId+ );++ const voidJournal = await trx+ .insertInto("journal")+ .values({+ journalEntryId: voidEntryId,+ accountingPeriodId,+ description: `VOID Payment ${payment.data.paymentId}`,+ postingDate: today,+ companyId,+ sourceType: "Payment",+ status: "Posted",+ postedAt: new Date().toISOString(),+ postedBy: userId,+ createdBy: userId,+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();++ const voidLineResults = await trx+ .insertInto("journalLine")+ .values(+ originalLines.map((line) => ({+ journalId: voidJournal.id,+ accountId: line.accountId,+ amount: -line.amount,+ quantity: line.quantity,+ description: `VOID: ${line.description ?? ""}`,+ documentType: "Payment" as const,+ documentId: paymentId,+ documentLineReference: line.documentLineReference,+ journalLineReference: line.journalLineReference,+ companyId,+ }))+ )+ .returning(["id"])+ .execute();++ // Carry the original lines' dimensions onto the reversing lines so+ // dimension-filtered balances net to zero after the void.+ const origDimensions = await trx+ .selectFrom("journalLineDimension")+ .select(["journalLineId", "dimensionId", "valueId"])+ .where(+ "journalLineId",+ "in",+ originalLines.map((l) => l.id)+ )+ .execute();+ if (origDimensions.length > 0) {+ const idxByOriginalId = new Map(+ originalLines.map((l, i) => [l.id, i])+ );+ await trx+ .insertInto("journalLineDimension")+ .values(+ origDimensions.map((d) => ({+ journalLineId:+ voidLineResults[idxByOriginalId.get(d.journalLineId)!].id,+ dimensionId: d.dimensionId,+ valueId: d.valueId,+ companyId,+ }))+ )+ .execute();+ }+ }+ }++ await trx+ .updateTable("payment")+ .set({+ status: "Voided",+ voidedAt: new Date().toISOString(),+ voidedBy: userId,+ updatedAt: new Date().toISOString(),+ updatedBy: userId,+ })+ .where("id", "=", paymentId)+ .where("companyId", "=", companyId)+ .execute();+ });++ return new Response(JSON.stringify({ success: true }), {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ });+ }++ // --------------------------------------------------------------+ // POST+ // --------------------------------------------------------------+ if (payment.data.status !== "Draft") {+ throw new Error(+ `Cannot post payment in status ${payment.data.status} (only Draft)`+ );+ }+ if (payment.data.exchangeRate <= 0) {+ throw new Error("Payment exchange rate must be > 0");+ }++ // Invoice ids referenced by this payment's applications. The lock ++ // validation against invoice state (existence, counterparty, active+ // status, over-settlement cap) happens inside the commit transaction+ // below, NOT here — see the note on the application-level checks.+ // Credit applications staged on this payment (memo-sourced, GL-neutral). They+ // go live when the payment posts, so they share the per-invoice over-settlement+ // cap with cash — but they are NOT cash, so they don't post GL or count toward+ // the cash-vs-total (overApplied) check below.+ const creditByInvoice = new Map<string, number>();+ for (const c of credits.data ?? []) {+ const invId = (isAR+ ? c.targetSalesInvoiceId+ : c.targetPurchaseInvoiceId) as string | null;+ if (!invId) continue;+ creditByInvoice.set(+ invId,+ (creditByInvoice.get(invId) ?? 0) + Number(c.appliedAmount)+ );+ }++ const salesInvoiceIds = [+ ...new Set([+ ...applications.data+ .filter((a) => a.targetSalesInvoiceId)+ .map((a) => a.targetSalesInvoiceId as string),+ ...(isAR ? [...creditByInvoice.keys()] : []),+ ]),+ ];+ const purchaseInvoiceIds = [+ ...new Set([+ ...applications.data+ .filter((a) => a.targetPurchaseInvoiceId)+ .map((a) => a.targetPurchaseInvoiceId as string),+ ...(!isAR ? [...creditByInvoice.keys()] : []),+ ]),+ ];++ if (isAR && purchaseInvoiceIds.length > 0) {+ throw new Error("Receipt cannot apply to purchase invoices");+ }+ if (!isAR && salesInvoiceIds.length > 0) {+ throw new Error("Disbursement cannot apply to sales invoices");+ }++ // Application-level checks that need no invoice state. The invoice-+ // dependent checks run INSIDE the transaction below, after the invoice+ // rows are locked — otherwise two concurrent posts could both read the+ // same prior-settled total and both slip past the over-settlement cap.+ for (const app of applications.data) {+ if (app.targetExchangeRate <= 0 || app.sourceExchangeRate <= 0) {+ throw new Error("Application exchange rates must be > 0");+ }+ }++ // Cash vs applied (base ccy). When applied < cash the remainder is new+ // on-account credit; when applied > cash the excess must be funded by the+ // party's existing on-account credit (validated under lock inside the+ // commit transaction below, where prior posted payments are serialized).+ const totalAppliedBase = applications.data.reduce(+ (sum, a) => sum + Number(a.appliedAmount) * Number(a.sourceExchangeRate),+ 0+ );+ const paymentTotalBase = Number(payment.data.totalAmount) * Number(payment.data.exchangeRate);+ const overAppliedBase = round4(totalAppliedBase - paymentTotalBase);++ // --------------------------------------------------------------+ // Build journal lines (in base currency)+ // --------------------------------------------------------------+ const accountingPeriodId = accountingEnabled+ ? await getCurrentAccountingPeriod(client, companyId, db)+ : null;++ const journalLineInserts: PaymentJournalLine[] = [];+ // Dimensions to tag on every payment journal line so AR/AP can be reported+ // by counterparty. We tag both the counterparty *type* (CustomerType /+ // SupplierType) and the specific counterparty *entity* (Customer / Supplier).+ const partyDimensions: { dimensionId: string; valueId: string }[] = [];++ if (accountingEnabled) {+ if (!accountDefaults.data) {+ throw new Error(+ "Accounting is enabled but this company has no account defaults configured"+ );+ }+ const ad = accountDefaults.data;+ const journalLineReference = nanoid();++ // Resolve the counterparty type + entity dimensions for this payment.+ const companyRecord = await client+ .from("company")+ .select("companyGroupId")+ .eq("id", companyId)+ .single();+ const companyGroupId = companyRecord.data?.companyGroupId ?? null;+ const partyId = isAR+ ? (payment.data.customerId as string | null)+ : (payment.data.supplierId as string | null);+ const typeEntityType = isAR ? "CustomerType" : "SupplierType";+ const entityEntityType = isAR ? "Customer" : "Supplier";+ if (companyGroupId && partyId) {+ const [partyRow, dimRows] = await Promise.all([+ isAR+ ? client+ .from("customer")+ .select("customerTypeId")+ .eq("id", partyId)+ .maybeSingle()+ : client+ .from("supplier")+ .select("supplierTypeId")+ .eq("id", partyId)+ .maybeSingle(),+ client+ .from("dimension")+ .select("id, entityType")+ .eq("companyGroupId", companyGroupId)+ .eq("active", true)+ .in("entityType", [typeEntityType, entityEntityType]),+ ]);+ const dimByEntityType = new Map<string, string>();+ for (const d of dimRows.data ?? []) {+ if (d.entityType) dimByEntityType.set(d.entityType, d.id);+ }+ // deno-lint-ignore no-explicit-any+ const party = partyRow.data as any;+ const partyTypeId = isAR+ ? (party?.customerTypeId ?? null)+ : (party?.supplierTypeId ?? null);+ const typeDimensionId = dimByEntityType.get(typeEntityType);+ if (typeDimensionId && partyTypeId) {+ partyDimensions.push({+ dimensionId: typeDimensionId,+ valueId: partyTypeId,+ });+ }+ const entityDimensionId = dimByEntityType.get(entityEntityType);+ if (entityDimensionId) {+ partyDimensions.push({+ dimensionId: entityDimensionId,+ valueId: partyId,+ });+ }+ }++ // Build the balanced double-entry. Account-id resolution, the per-+ // application control/discount/write-off lines, the on-account-credit+ // line, the single FX plug, and the balance self-check all live in the+ // pure `buildPaymentJournal` so they are unit-tested (post-payment.test.ts).+ const { lines } = buildPaymentJournal({+ paymentId,+ companyId,+ isAR,+ cashIn,+ totalAmount: Number(payment.data.totalAmount),+ exchangeRate: Number(payment.data.exchangeRate),+ bankAccount: payment.data.bankAccount,+ journalLineReference,+ applications: applications.data.map((a) => ({+ targetSalesInvoiceId: a.targetSalesInvoiceId,+ targetPurchaseInvoiceId: a.targetPurchaseInvoiceId,+ appliedAmount: Number(a.appliedAmount),+ discountAmount: Number(a.discountAmount),+ writeOffAmount: Number(a.writeOffAmount),+ targetExchangeRate: Number(a.targetExchangeRate),+ sourceExchangeRate: Number(a.sourceExchangeRate),+ })),+ accounts: {+ controlAccountId: isAR+ ? ad.receivablesAccount+ : ad.payablesAccount,+ discountAccountId: isAR+ ? ad.customerPaymentDiscountAccount+ : ad.supplierPaymentDiscountAccount,+ writeOffAccountId: isAR+ ? ad.customerWriteOffAccount+ : ad.supplierWriteOffAccount,+ fxGainAccountId: ad.realizedExchangeGainAccount,+ fxLossAccountId: ad.realizedExchangeLossAccount,+ },+ });+ journalLineInserts.push(...lines);+ }++ // --------------------------------------------------------------+ // Commit: lock + validate the invoices under the transaction, then post.+ // --------------------------------------------------------------+ const paymentPartyId = isAR+ ? payment.data.customerId+ : payment.data.supplierId;+ const activeStatus = isAR ? "Submitted" : "Open";++ let createdJournalId: string | null = null;+ await db.transaction().execute(async (trx) => {+ // Lock the payment row and re-assert it's still Draft INSIDE the+ // transaction. The status check above runs before the lock (a TOCTOU+ // window): two concurrent posts could otherwise both pass it and each+ // write a journal + settlements (the invoice lock below doesn't help a+ // payment with no invoice applications, or a partial application under the+ // over-settlement cap). The FOR UPDATE serializes them so the second aborts.+ const lockedPayment = await trx+ .selectFrom("payment")+ .select(["id", "status"])+ .where("id", "=", paymentId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!lockedPayment) throw new Error("Payment not found");+ if (lockedPayment.status !== "Draft") {+ throw new Error(+ `Cannot post payment in status ${lockedPayment.status} (only Draft)`+ );+ }++ // Lock + read the target invoices in one shot. Holding the row locks for+ // the rest of the transaction serializes concurrent posts so the+ // over-settlement cap below can't be raced (TOCTOU).+ const invoiceById = new Map<+ string,+ {+ status: string;+ totalAmount: number;+ // View balance = remaining open amount on the invoice.+ balance: number;+ partyId: string | null;+ }+ >();+ // The stored base "totalAmount" is deprecated (always 0 for invoices+ // posted after migration 20260604120000); the live total lives in the+ // salesInvoices/purchaseInvoices views. We can't lock a view (it joins ++ // aggregates), so we lock the base row FOR UPDATE — which serializes+ // concurrent posts and gives the raw posting status/party — and read the+ // live total from the view separately. Status MUST come from the base+ // row, not the view: the view derives 'Partially Paid'/'Paid', which+ // would wrongly fail the activeStatus check on a partially-settled+ // invoice.+ if (isAR && salesInvoiceIds.length > 0) {+ const rows = await trx+ .selectFrom("salesInvoice")+ .select(["id", "status", "customerId"])+ .where("id", "in", salesInvoiceIds)+ .forUpdate()+ .execute();+ const totals = await trx+ .selectFrom("salesInvoices")+ .select(["id", "totalAmount", "balance"])+ .where("id", "in", salesInvoiceIds)+ .execute();+ const viewById = new Map(totals.map((t) => [t.id, t]));+ for (const r of rows) {+ const v = viewById.get(r.id);+ invoiceById.set(r.id, {+ status: r.status as string,+ totalAmount: Number(v?.totalAmount ?? 0),+ balance: Number(v?.balance ?? 0),+ partyId: r.customerId,+ });+ }+ }+ if (!isAR && purchaseInvoiceIds.length > 0) {+ const rows = await trx+ .selectFrom("purchaseInvoice")+ .select(["id", "status", "supplierId"])+ .where("id", "in", purchaseInvoiceIds)+ .forUpdate()+ .execute();+ const totals = await trx+ .selectFrom("purchaseInvoices")+ .select(["id", "totalAmount", "balance"])+ .where("id", "in", purchaseInvoiceIds)+ .execute();+ const viewById = new Map(totals.map((t) => [t.id, t]));+ for (const r of rows) {+ const v = viewById.get(r.id);+ invoiceById.set(r.id, {+ status: r.status as string,+ totalAmount: Number(v?.totalAmount ?? 0),+ balance: Number(v?.balance ?? 0),+ partyId: r.supplierId,+ });+ }+ }++ // Validate each application against the locked invoice state.+ const currentSettledByInvoice = new Map<string, number>();+ for (const app of applications.data) {+ const invId = (isAR+ ? app.targetSalesInvoiceId+ : app.targetPurchaseInvoiceId) as string;+ const inv = invoiceById.get(invId);+ if (!inv) throw new Error(`Invoice ${invId} not found`);+ if (inv.partyId !== paymentPartyId) {+ throw new Error(+ `Invoice ${invId} belongs to a different ${isAR ? "customer" : "supplier"} than the payment`+ );+ }+ const settledByThisApp =+ Number(app.appliedAmount) ++ Number(app.discountAmount) ++ Number(app.writeOffAmount);+ currentSettledByInvoice.set(+ invId,+ (currentSettledByInvoice.get(invId) ?? 0) + settledByThisApp+ );+ const wouldSettle = currentSettledByInvoice.get(invId)!;++ if (inv.status !== activeStatus) {+ throw new Error(+ `Cannot apply payment to invoice ${invId} in status ${inv.status} (must be ${activeStatus})`+ );+ }+ // The view balance nets ALL posted settlements against this invoice —+ // cash AND credit/debit memos — so it's the true remaining open. (The+ // current Draft payment isn't posted, so its own applications aren't in+ // it yet.) Capping against it prevents over-settling an invoice already+ // (partly) cleared by a memo.+ const remainingOpen = inv.balance;+ if (wouldSettle > remainingOpen + 0.0001) {+ throw new Error(+ `Application total (${wouldSettle}) exceeds remaining open amount (${remainingOpen}) on invoice ${invId}`+ );+ }+ }++ // Staged credit applications go live when this payment posts, so fold them+ // into the same per-invoice cap: cash + credit must not over-settle.+ for (const [invId, creditAmt] of creditByInvoice) {+ const inv = invoiceById.get(invId);+ if (!inv) throw new Error(`Invoice ${invId} not found`);+ if (inv.partyId !== paymentPartyId) {+ throw new Error(+ `Invoice ${invId} belongs to a different ${isAR ? "customer" : "supplier"} than the payment`+ );+ }+ if (inv.status !== activeStatus) {+ throw new Error(+ `Cannot apply credit to invoice ${invId} in status ${inv.status} (must be ${activeStatus})`+ );+ }+ const wouldSettle = (currentSettledByInvoice.get(invId) ?? 0) + creditAmt;+ if (wouldSettle > inv.balance + 0.0001) {+ throw new Error(+ `Application total (${wouldSettle}) exceeds remaining open amount (${inv.balance}) on invoice ${invId}`+ );+ }+ }++ // When this payment applies more than its cash, the excess draws down the+ // party's available on-account credit — the net unapplied cash left on+ // their OTHER posted payments. Lock those payments FOR UPDATE so two+ // concurrent credit-consuming posts can't both spend the same credit.+ if (overAppliedBase > 0.0001) {+ const postedPayments = await (isAR+ ? trx+ .selectFrom("payment")+ .select(["id", "totalAmount", "exchangeRate"])+ .where("companyId", "=", companyId)+ .where("status", "=", "Posted")+ .where("customerId", "=", paymentPartyId)+ .forUpdate()+ .execute()+ : trx+ .selectFrom("payment")+ .select(["id", "totalAmount", "exchangeRate"])+ .where("companyId", "=", companyId)+ .where("status", "=", "Posted")+ .where("supplierId", "=", paymentPartyId)+ .forUpdate()+ .execute());++ let availableCreditBase = 0;+ if (postedPayments.length > 0) {+ const postedIds = postedPayments.map((p) => p.id);+ const priorApps = await trx+ .selectFrom("invoiceSettlement")+ .select(["paymentId", "appliedAmount", "sourceExchangeRate"])+ .where("paymentId", "in", postedIds)+ .execute();+ const appliedBaseByPayment = new Map<string, number>();+ for (const a of priorApps) {+ appliedBaseByPayment.set(+ a.paymentId,+ (appliedBaseByPayment.get(a.paymentId) ?? 0) ++ Number(a.appliedAmount) * Number(a.sourceExchangeRate)+ );+ }+ for (const p of postedPayments) {+ availableCreditBase +=+ Number(p.totalAmount) * Number(p.exchangeRate) -+ (appliedBaseByPayment.get(p.id) ?? 0);+ }+ }++ if (overAppliedBase > round4(availableCreditBase) + 0.0001) {+ throw new Error(+ `Applied exceeds payment cash by ${overAppliedBase} in base currency, but only ${round4(availableCreditBase)} of on-account credit is available for this ${isAR ? "customer" : "supplier"}`+ );+ }+ }++ // GL journal (only when accounting is enabled).+ let journalId: string | null = null;+ if (accountingEnabled) {+ const journalEntryId = await getNextSequence(+ trx,+ "journalEntry",+ companyId+ );+ const journalResult = await trx+ .insertInto("journal")+ .values({+ journalEntryId,+ accountingPeriodId,+ description: `Payment ${payment.data.paymentId}`,+ postingDate: today,+ companyId,+ sourceType: "Payment",+ status: "Posted",+ postedAt: new Date().toISOString(),+ postedBy: userId,+ createdBy: userId,+ })+ .returning(["id"])+ .executeTakeFirstOrThrow();+ journalId = journalResult.id;++ if (journalLineInserts.length > 0) {+ const journalLineResults = await trx+ .insertInto("journalLine")+ .values(+ journalLineInserts.map((line) => ({+ ...line,+ journalId: journalResult.id,+ }))+ )+ .returning(["id"])+ .execute();++ // Tag every line with the counterparty dimensions (type + entity).+ if (partyDimensions.length > 0) {+ await trx+ .insertInto("journalLineDimension")+ .values(+ journalLineResults.flatMap((jl) =>+ partyDimensions.map((d) => ({+ journalLineId: jl.id,+ dimensionId: d.dimensionId,+ valueId: d.valueId,+ companyId,+ }))+ )+ )+ .execute();+ }+ }+ }++ await trx+ .updateTable("payment")+ .set({+ status: "Posted",+ postingDate: today,+ journalId,+ postedAt: new Date().toISOString(),+ postedBy: userId,+ updatedAt: new Date().toISOString(),+ updatedBy: userId,+ })+ .where("id", "=", paymentId)+ .where("companyId", "=", companyId)+ .execute();++ createdJournalId = journalId;+ });++ return new Response(+ JSON.stringify({ success: true, journalId: createdJournalId }),+ { headers: { ...corsHeaders, "Content-Type": "application/json" } }+ );+ } catch (err) {+ console.error(err);+ return new Response(+ JSON.stringify({+ success: false,+ message: err instanceof Error ? err.message : String(err),+ }),+ {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 500,+ }+ );+ }+});diff --git a/packages/database/supabase/functions/post-payment/post-payment.test.ts b/packages/database/supabase/functions/post-payment/post-payment.test.tsnew file mode 100644index 0000000000..13622fac7b--- /dev/null+++ b/packages/database/supabase/functions/post-payment/post-payment.test.ts@@ -0,0 +1,808 @@+import {+ assert,+ assertEquals,+ assertThrows,+} from "https://deno.land/[email protected]/testing/asserts.ts";+import {+ buildPaymentJournal,+ type BuildPaymentJournalInput,+ type PaymentJournalAccounts,+} from "./build-payment-journal.ts";++// Golden-master tests for the GL journal a payment posts. Each asserts the exact+// natural-balance-signed `amount` on each line (asset/expense debits are +,+// credits −; liability/revenue/equity are the mirror — see lib/utils.ts) AND+// that the entry balances in debit/credit space (signedDebitTotal ≈ 0). The+// matrix covers AR/AP × full/partial/over × discount/write-off × FX gain/loss,+// so the ledger that hits the books is provably correct, not merely inspected.++const ACCOUNTS: PaymentJournalAccounts = {+ controlAccountId: "control", // receivables (AR) or payables (AP); driver resolves+ discountAccountId: "discount",+ writeOffAccountId: "writeoff",+ fxGainAccountId: "fxgain",+ fxLossAccountId: "fxloss",+};++const arBase = (+ over: Partial<BuildPaymentJournalInput> = {}+): BuildPaymentJournalInput => ({+ paymentId: "pay_1",+ companyId: "co_1",+ isAR: true,+ cashIn: true,+ totalAmount: 100,+ exchangeRate: 1,+ bankAccount: "bank",+ journalLineReference: "ref_1",+ applications: [+ {+ targetSalesInvoiceId: "si_1",+ appliedAmount: 100,+ discountAmount: 0,+ writeOffAmount: 0,+ targetExchangeRate: 1,+ sourceExchangeRate: 1,+ },+ ],+ accounts: { ...ACCOUNTS },+ ...over,+});++const apBase = (+ over: Partial<BuildPaymentJournalInput> = {}+): BuildPaymentJournalInput => ({+ ...arBase(),+ isAR: false,+ cashIn: false,+ applications: [+ {+ targetPurchaseInvoiceId: "pi_1",+ appliedAmount: 100,+ discountAmount: 0,+ writeOffAmount: 0,+ targetExchangeRate: 1,+ sourceExchangeRate: 1,+ },+ ],+ ...over,+});++const balanced = (signedDebitTotal: number) =>+ Math.abs(signedDebitTotal) < 1e-9;++const line = <T extends { description: string }>(+ lines: T[],+ description: string+) => lines.find((l) => l.description === description);++const round4 = (n: number) => Math.round(n * 10000) / 10000;++// Magnitude posted to the control account for a specific invoice (the lines are+// natural-balance signed, so take the absolute value to compare to the+// subledger settled amount).+const controlMagnitudeFor = (+ lines: { description: string; documentLineReference?: string; amount: number }[],+ invoiceId: string+) => {+ const l = lines.find(+ (x) =>+ (x.description === "Accounts Receivable" ||+ x.description === "Accounts Payable") &&+ x.documentLineReference === invoiceId+ );+ return l ? Math.abs(l.amount) : 0;+};++// ---------------------------------------------------------------------------+// Simple, no-FX cases — assert the full line set.+// ---------------------------------------------------------------------------++Deno.test("AR full payment, no FX: DR bank / CR receivables, balanced", () => {+ const { lines, signedDebitTotal } = buildPaymentJournal(arBase());++ assertEquals(lines.length, 2);+ assertEquals(lines[0].accountId, "bank");+ assertEquals(lines[0].amount, 100); // debit asset+ assertEquals(lines[0].description, "Bank / Cash");+ assertEquals(lines[0].documentType, "Payment");+ assertEquals(lines[0].documentId, "pay_1");+ assertEquals(lines[0].journalLineReference, "ref_1");+ assertEquals(lines[0].companyId, "co_1");++ assertEquals(lines[1].accountId, "control");+ assertEquals(lines[1].amount, -100); // credit asset+ assertEquals(lines[1].description, "Accounts Receivable");+ assertEquals(lines[1].documentLineReference, "si_1");++ assert(balanced(signedDebitTotal));+});++Deno.test("AP full payment, no FX: CR bank / DR payables, balanced", () => {+ const { lines, signedDebitTotal } = buildPaymentJournal(apBase());++ assertEquals(lines.length, 2);+ assertEquals(lines[0].accountId, "bank");+ assertEquals(lines[0].amount, -100); // credit asset+ assertEquals(lines[1].accountId, "control");+ assertEquals(lines[1].amount, -100); // debit liability → natural-negative+ assertEquals(lines[1].description, "Accounts Payable");+ assertEquals(lines[1].documentLineReference, "pi_1");++ assert(balanced(signedDebitTotal));+});++// ---------------------------------------------------------------------------+// Discount / write-off — invoice-currency reliefs, no FX.+// ---------------------------------------------------------------------------++Deno.test("AR discount: bank 90 / receivables 100 / discount expense 10", () => {+ const { lines, signedDebitTotal } = buildPaymentJournal(+ arBase({+ totalAmount: 90,+ applications: [+ {+ targetSalesInvoiceId: "si_1",+ appliedAmount: 90,+ discountAmount: 10,+ writeOffAmount: 0,+ targetExchangeRate: 1,+ sourceExchangeRate: 1,+ },+ ],+ })+ );++ assertEquals(line(lines, "Bank / Cash")!.amount, 90);+ assertEquals(line(lines, "Accounts Receivable")!.amount, -100); // (90+10)*1+ const discount = line(lines, "Customer Payment Discount")!;+ assertEquals(discount.accountId, "discount");+ assertEquals(discount.amount, 10); // debit expense+ assert(balanced(signedDebitTotal));+});++Deno.test("AR write-off: bad debt expense debited", () => {+ const { lines, signedDebitTotal } = buildPaymentJournal(+ arBase({+ totalAmount: 90,+ applications: [+ {+ targetSalesInvoiceId: "si_1",+ appliedAmount: 90,+ discountAmount: 0,+ writeOffAmount: 10,+ targetExchangeRate: 1,+ sourceExchangeRate: 1,+ },+ ],+ })+ );++ const wo = line(lines, "Bad Debt Expense")!;+ assertEquals(wo.accountId, "writeoff");+ assertEquals(wo.amount, 10); // debit expense+ assert(balanced(signedDebitTotal));+});++Deno.test("AP write-off: vendor write-off income credited (revenue)", () => {+ const { lines, signedDebitTotal } = buildPaymentJournal(+ apBase({+ totalAmount: 90,+ applications: [+ {+ targetPurchaseInvoiceId: "pi_1",+ appliedAmount: 90,+ discountAmount: 0,+ writeOffAmount: 10,+ targetExchangeRate: 1,+ sourceExchangeRate: 1,+ },+ ],+ })+ );++ const wo = line(lines, "Vendor Write-Off Income")!;+ assertEquals(wo.accountId, "writeoff");+ assertEquals(wo.amount, 10); // credit revenue → natural-positive+ assert(balanced(signedDebitTotal));+});++// ---------------------------------------------------------------------------+// Realized FX — the sign convention. These pin that AR collected high = gain,+// AP paid high = LOSS (the case a reviewer mis-called as inverted).+// ---------------------------------------------------------------------------++Deno.test("AR collected above booked rate → FX Gain (credit revenue)", () => {+ const { lines, signedDebitTotal } = buildPaymentJournal(+ arBase({+ exchangeRate: 1.2,+ applications: [+ {+ targetSalesInvoiceId: "si_1",+ appliedAmount: 100,+ discountAmount: 0,+ writeOffAmount: 0,+ targetExchangeRate: 1.0,+ sourceExchangeRate: 1.2,+ },+ ],+ })+ );++ assertEquals(line(lines, "Bank / Cash")!.amount, 120); // 100 × 1.2+ assertEquals(line(lines, "Accounts Receivable")!.amount, -100); // 100 × 1.0+ const fx = line(lines, "Realized FX Gain")!;+ assertEquals(fx.accountId, "fxgain");+ assertEquals(fx.amount, 20); // credit revenue+ assert(line(lines, "Realized FX Loss") === undefined);+ assert(balanced(signedDebitTotal));+});++Deno.test("AR collected below booked rate → FX Loss (debit expense)", () => {+ const { lines, signedDebitTotal } = buildPaymentJournal(+ arBase({+ exchangeRate: 0.8,+ applications: [+ {+ targetSalesInvoiceId: "si_1",+ appliedAmount: 100,+ discountAmount: 0,+ writeOffAmount: 0,+ targetExchangeRate: 1.0,+ sourceExchangeRate: 0.8,+ },+ ],+ })+ );++ const fx = line(lines, "Realized FX Loss")!;+ assertEquals(fx.accountId, "fxloss");+ assertEquals(fx.amount, 20); // debit expense+ assert(line(lines, "Realized FX Gain") === undefined);+ assert(balanced(signedDebitTotal));+});++Deno.test("AP paid ABOVE booked rate → FX Loss (debit expense)", () => {+ // The case a reviewer wrongly flagged as a sign inversion. Paying a supplier+ // at a higher rate than the liability was booked is a real loss.+ const { lines, signedDebitTotal } = buildPaymentJournal(+ apBase({+ exchangeRate: 1.2,+ applications: [+ {+ targetPurchaseInvoiceId: "pi_1",+ appliedAmount: 100,+ discountAmount: 0,+ writeOffAmount: 0,+ targetExchangeRate: 1.0,+ sourceExchangeRate: 1.2,+ },+ ],+ })+ );++ assertEquals(line(lines, "Bank / Cash")!.amount, -120); // credit asset 100×1.2+ const fx = line(lines, "Realized FX Loss")!;+ assertEquals(fx.accountId, "fxloss");+ assertEquals(fx.amount, 20); // debit expense+ assert(line(lines, "Realized FX Gain") === undefined);+ assert(balanced(signedDebitTotal));+});++Deno.test("AP paid BELOW booked rate → FX Gain (credit revenue)", () => {+ const { lines, signedDebitTotal } = buildPaymentJournal(+ apBase({+ exchangeRate: 0.8,+ applications: [+ {+ targetPurchaseInvoiceId: "pi_1",+ appliedAmount: 100,+ discountAmount: 0,+ writeOffAmount: 0,+ targetExchangeRate: 1.0,+ sourceExchangeRate: 0.8,+ },+ ],+ })+ );++ const fx = line(lines, "Realized FX Gain")!;+ assertEquals(fx.accountId, "fxgain");+ assertEquals(fx.amount, 20); // credit revenue+ assert(line(lines, "Realized FX Loss") === undefined);+ assert(balanced(signedDebitTotal));+});++// ---------------------------------------------------------------------------+// Unapplied cash — building vs drawing down on-account credit.+// ---------------------------------------------------------------------------++Deno.test("AR partial: unapplied cash builds on-account credit", () => {+ const { lines, signedDebitTotal } = buildPaymentJournal(+ arBase({+ totalAmount: 100,+ applications: [+ {+ targetSalesInvoiceId: "si_1",+ appliedAmount: 60,+ discountAmount: 0,+ writeOffAmount: 0,+ targetExchangeRate: 1,+ sourceExchangeRate: 1,+ },+ ],+ })+ );++ assertEquals(line(lines, "Bank / Cash")!.amount, 100);+ assertEquals(line(lines, "Accounts Receivable")!.amount, -60);+ const credit = line(lines, "Accounts Receivable (on-account credit)")!;+ assertEquals(credit.amount, -40); // credit asset (no invoice anchor)+ assertEquals(credit.documentLineReference, undefined);+ assert(balanced(signedDebitTotal));+});++Deno.test("AR over-application draws down existing credit (inverse side)", () => {+ const { lines, signedDebitTotal } = buildPaymentJournal(+ arBase({+ totalAmount: 80,+ applications: [+ {+ targetSalesInvoiceId: "si_1",+ appliedAmount: 100,+ discountAmount: 0,+ writeOffAmount: 0,+ targetExchangeRate: 1,+ sourceExchangeRate: 1,+ },+ ],+ })+ );++ assertEquals(line(lines, "Bank / Cash")!.amount, 80);+ assertEquals(line(lines, "Accounts Receivable")!.amount, -100);+ const draw = line(lines, "Accounts Receivable (credit applied)")!;+ assertEquals(draw.amount, 20); // debit asset — inverse of building credit+ assert(balanced(signedDebitTotal));+});++// ---------------------------------------------------------------------------+// Multi-invoice + combined relief still balances.+// ---------------------------------------------------------------------------++Deno.test("AR two invoices with discount and FX all balance", () => {+ const { lines, signedDebitTotal } = buildPaymentJournal(+ arBase({+ exchangeRate: 1.1,+ totalAmount: 190,+ applications: [+ {+ targetSalesInvoiceId: "si_1",+ appliedAmount: 100,+ discountAmount: 0,+ writeOffAmount: 0,+ targetExchangeRate: 1.0,+ sourceExchangeRate: 1.1,+ },+ {+ targetSalesInvoiceId: "si_2",+ appliedAmount: 90,+ discountAmount: 10,+ writeOffAmount: 0,+ targetExchangeRate: 1.0,+ sourceExchangeRate: 1.1,+ },+ ],+ })+ );++ // Two control lines, one discount, one FX gain, cash — and it balances.+ assert(line(lines, "Customer Payment Discount") !== undefined);+ assert(line(lines, "Realized FX Gain") !== undefined);+ assert(balanced(signedDebitTotal));+});++// ---------------------------------------------------------------------------+// Refusal paths — missing account defaults and an unbalanced entry.+// ---------------------------------------------------------------------------++Deno.test("throws when the control account default is missing", () => {+ assertThrows(+ () =>+ buildPaymentJournal(+ arBase({ accounts: { ...ACCOUNTS, controlAccountId: null } })+ ),+ Error,+ "receivables account default"+ );+});++Deno.test("throws when a discount is taken but no discount account is set", () => {+ assertThrows(+ () =>+ buildPaymentJournal(+ arBase({+ totalAmount: 90,+ accounts: { ...ACCOUNTS, discountAccountId: null },+ applications: [+ {+ targetSalesInvoiceId: "si_1",+ appliedAmount: 90,+ discountAmount: 10,+ writeOffAmount: 0,+ targetExchangeRate: 1,+ sourceExchangeRate: 1,+ },+ ],+ })+ ),+ Error,+ "payment discount account default"+ );+});++Deno.test("throws when an FX gain arises but no FX gain account is set", () => {+ assertThrows(+ () =>+ buildPaymentJournal(+ arBase({+ exchangeRate: 1.2,+ accounts: { ...ACCOUNTS, fxGainAccountId: null },+ applications: [+ {+ targetSalesInvoiceId: "si_1",+ appliedAmount: 100,+ discountAmount: 0,+ writeOffAmount: 0,+ targetExchangeRate: 1.0,+ sourceExchangeRate: 1.2,+ },+ ],+ })+ ),+ Error,+ "realized FX gain account default"+ );+});++Deno.test("throws when a write-off arises but no write-off account is set", () => {+ assertThrows(+ () =>+ buildPaymentJournal(+ apBase({+ totalAmount: 90,+ accounts: { ...ACCOUNTS, writeOffAccountId: null },+ applications: [+ {+ targetPurchaseInvoiceId: "pi_1",+ appliedAmount: 90,+ discountAmount: 0,+ writeOffAmount: 10,+ targetExchangeRate: 1,+ sourceExchangeRate: 1,+ },+ ],+ })+ ),+ Error,+ "write-off account default"+ );+});++// ---------------------------------------------------------------------------+// No applications — a pure prepayment / on-account receipt or supplier advance.+// ---------------------------------------------------------------------------++Deno.test("AR prepayment with no applications: cash + full on-account credit", () => {+ const { lines, signedDebitTotal, totalFxImpact } = buildPaymentJournal(+ arBase({ totalAmount: 250, applications: [] })+ );++ assertEquals(lines.length, 2);+ assertEquals(line(lines, "Bank / Cash")!.amount, 250); // debit asset+ const credit = line(lines, "Accounts Receivable (on-account credit)")!;+ assertEquals(credit.amount, -250); // credit asset, no invoice anchor+ assertEquals(credit.documentLineReference, undefined);+ assertEquals(totalFxImpact, 0);+ assert(balanced(signedDebitTotal));+});++Deno.test("AP advance with no applications: CR bank + on-account credit", () => {+ const { lines, signedDebitTotal } = buildPaymentJournal(+ apBase({ totalAmount: 250, applications: [] })+ );++ assertEquals(lines.length, 2);+ assertEquals(line(lines, "Bank / Cash")!.amount, -250); // credit asset+ assert(line(lines, "Accounts Payable (on-account credit)") !== undefined);+ assert(balanced(signedDebitTotal));+});++// ---------------------------------------------------------------------------+// Unapplied threshold — the 0.0001 dust band must not emit a spurious line.+// ---------------------------------------------------------------------------++Deno.test("applied exactly equal to cash emits no unapplied line", () => {+ const { lines } = buildPaymentJournal(arBase());+ assert(line(lines, "Accounts Receivable (on-account credit)") === undefined);+ assert(line(lines, "Accounts Receivable (credit applied)") === undefined);+});++Deno.test("sub-dust unapplied (< 0.0001) emits no on-account line", () => {+ const { lines, signedDebitTotal } = buildPaymentJournal(+ arBase({+ totalAmount: 100,+ applications: [+ {+ targetSalesInvoiceId: "si_1",+ appliedAmount: 99.99995, // unapplied 0.00005 < threshold+ discountAmount: 0,+ writeOffAmount: 0,+ targetExchangeRate: 1,+ sourceExchangeRate: 1,+ },+ ],+ })+ );+ assert(line(lines, "Accounts Receivable (on-account credit)") === undefined);+ assert(balanced(signedDebitTotal));+});++// ---------------------------------------------------------------------------+// Multiple invoices — full settlement, over-application, under-application.+// ---------------------------------------------------------------------------++Deno.test("AR three invoices fully settled: one cash + three control lines", () => {+ const { lines, signedDebitTotal } = buildPaymentJournal(+ arBase({+ totalAmount: 60,+ applications: [+ { targetSalesInvoiceId: "si_1", appliedAmount: 10, discountAmount: 0, writeOffAmount: 0, targetExchangeRate: 1, sourceExchangeRate: 1 },+ { targetSalesInvoiceId: "si_2", appliedAmount: 20, discountAmount: 0, writeOffAmount: 0, targetExchangeRate: 1, sourceExchangeRate: 1 },+ { targetSalesInvoiceId: "si_3", appliedAmount: 30, discountAmount: 0, writeOffAmount: 0, targetExchangeRate: 1, sourceExchangeRate: 1 },+ ],+ })+ );++ assertEquals(lines.filter((l) => l.description === "Accounts Receivable").length, 3);+ assertEquals(line(lines, "Bank / Cash")!.amount, 60);+ assert(line(lines, "Accounts Receivable (on-account credit)") === undefined);+ assertEquals(controlMagnitudeFor(lines, "si_1"), 10);+ assertEquals(controlMagnitudeFor(lines, "si_2"), 20);+ assertEquals(controlMagnitudeFor(lines, "si_3"), 30);+ assert(balanced(signedDebitTotal));+});++Deno.test("AR overpayment across multiple invoices: single draw-down line", () => {+ const { lines, signedDebitTotal } = buildPaymentJournal(+ arBase({+ totalAmount: 150,+ applications: [+ { targetSalesInvoiceId: "si_1", appliedAmount: 100, discountAmount: 0, writeOffAmount: 0, targetExchangeRate: 1, sourceExchangeRate: 1 },+ { targetSalesInvoiceId: "si_2", appliedAmount: 80, discountAmount: 0, writeOffAmount: 0, targetExchangeRate: 1, sourceExchangeRate: 1 },+ ],+ })+ );++ // applied 180 vs cash 150 → 30 drawn from existing credit (inverse side).+ const draw = line(lines, "Accounts Receivable (credit applied)")!;+ assertEquals(draw.amount, 30); // debit asset+ assertEquals(lines.filter((l) => l.description === "Accounts Receivable (on-account credit)").length, 0);+ assert(balanced(signedDebitTotal));+});++Deno.test("AP underpayment across multiple invoices builds credit", () => {+ const { lines, signedDebitTotal } = buildPaymentJournal(+ apBase({+ totalAmount: 200,+ applications: [+ { targetPurchaseInvoiceId: "pi_1", appliedAmount: 60, discountAmount: 0, writeOffAmount: 0, targetExchangeRate: 1, sourceExchangeRate: 1 },+ { targetPurchaseInvoiceId: "pi_2", appliedAmount: 60, discountAmount: 0, writeOffAmount: 0, targetExchangeRate: 1, sourceExchangeRate: 1 },+ ],+ })+ );++ // 200 cash − 120 applied → 80 on-account credit.+ const credit = line(lines, "Accounts Payable (on-account credit)")!;+ assertEquals(Math.abs(credit.amount), 80);+ assert(balanced(signedDebitTotal));+});++// ---------------------------------------------------------------------------+// Combined relief + FX on the same application.+// ---------------------------------------------------------------------------++Deno.test("AR discount + write-off + FX on one invoice all coexist, balanced", () => {+ const { lines, signedDebitTotal } = buildPaymentJournal(+ arBase({+ exchangeRate: 1.2,+ totalAmount: 80, // pays 80 cash; 10 discount + 10 write-off settle a 100 invoice+ applications: [+ {+ targetSalesInvoiceId: "si_1",+ appliedAmount: 80,+ discountAmount: 10,+ writeOffAmount: 10,+ targetExchangeRate: 1.0,+ sourceExchangeRate: 1.2,+ },+ ],+ })+ );++ assertEquals(line(lines, "Bank / Cash")!.amount, 96); // 80 × 1.2+ assertEquals(line(lines, "Accounts Receivable")!.amount, -100); // (80+10+10) × 1.0+ assertEquals(line(lines, "Customer Payment Discount")!.amount, 10); // 10 × 1.0+ assertEquals(line(lines, "Bad Debt Expense")!.amount, 10); // 10 × 1.0+ assertEquals(line(lines, "Realized FX Gain")!.amount, 16); // 80 × (1.2 − 1.0)+ assert(balanced(signedDebitTotal));+});++Deno.test("FX accrues on applied principal only, never on discount/write-off", () => {+ // Pure discount settlement with a rate gap: applied 0 ⇒ no FX line at all.+ const { lines, totalFxImpact } = buildPaymentJournal(+ arBase({+ totalAmount: 0,+ applications: [+ {+ targetSalesInvoiceId: "si_1",+ appliedAmount: 0,+ discountAmount: 50,+ writeOffAmount: 0,+ targetExchangeRate: 1.0,+ sourceExchangeRate: 1.5,+ },+ ],+ })+ );++ assertEquals(totalFxImpact, 0);+ assert(line(lines, "Realized FX Gain") === undefined);+ assert(line(lines, "Realized FX Loss") === undefined);+});++Deno.test("opposing per-invoice FX nets to zero → no FX plug line", () => {+ const { lines, signedDebitTotal, totalFxImpact } = buildPaymentJournal(+ arBase({+ exchangeRate: 1.0,+ totalAmount: 200,+ applications: [+ { targetSalesInvoiceId: "si_1", appliedAmount: 100, discountAmount: 0, writeOffAmount: 0, targetExchangeRate: 1.0, sourceExchangeRate: 1.1 }, // +10+ { targetSalesInvoiceId: "si_2", appliedAmount: 100, discountAmount: 0, writeOffAmount: 0, targetExchangeRate: 1.0, sourceExchangeRate: 0.9 }, // −10+ ],+ })+ );++ assert(Math.abs(totalFxImpact) < 1e-9);+ assert(line(lines, "Realized FX Gain") === undefined);+ assert(line(lines, "Realized FX Loss") === undefined);+ assert(balanced(signedDebitTotal));+});++// ---------------------------------------------------------------------------+// Rounding — NUMERIC(19,4): every magnitude is rounded to 4 dp and the entry+// still balances within tolerance under messy rates.+// ---------------------------------------------------------------------------++Deno.test("magnitudes round to 4 dp and the entry still balances", () => {+ // Consistent rates (cash exchangeRate == application paymentExchangeRate).+ // cash = 100 × 1.11111 = 111.111; control = 100 × 1.0 = 100;+ // FX = 100 × (1.11111 − 1.0) = 11.111 → all land on 4 dp and net to zero.+ const { lines, signedDebitTotal } = buildPaymentJournal(+ arBase({+ exchangeRate: 1.11111,+ totalAmount: 100,+ applications: [+ {+ targetSalesInvoiceId: "si_1",+ appliedAmount: 100,+ discountAmount: 0,+ writeOffAmount: 0,+ targetExchangeRate: 1.0,+ sourceExchangeRate: 1.11111,+ },+ ],+ })+ );++ assertEquals(line(lines, "Bank / Cash")!.amount, 111.111);+ assertEquals(line(lines, "Accounts Receivable")!.amount, -100);+ assertEquals(line(lines, "Realized FX Gain")!.amount, 11.111);+ assert(balanced(signedDebitTotal));+});++// ---------------------------------------------------------------------------+// Subledger tie-out — the property the SQL tie-out RPCs depend on. For every+// application, the magnitude posted to the control account equals the settled+// amount (applied + discount + write-off) at the INVOICE rate, so the GL+// reconciles to the subledger invoice-by-invoice.+// ---------------------------------------------------------------------------++Deno.test("control posting ties out to subledger settled per invoice (AR & AP)", () => {+ const apps = [+ { applied: 100, discount: 5, writeOff: 0, invRate: 1.0 },+ { applied: 40, discount: 0, writeOff: 10, invRate: 1.25 },+ { applied: 7.5, discount: 2.5, writeOff: 0, invRate: 0.8 },+ ];++ for (const isReceipt of [true, false]) {+ const base = isReceipt ? arBase() : apBase();+ const { lines, signedDebitTotal } = buildPaymentJournal({+ ...base,+ exchangeRate: 1.0,+ totalAmount: apps.reduce((s, a) => s + a.applied, 0),+ applications: apps.map((a, i) => ({+ [isReceipt ? "targetSalesInvoiceId" : "targetPurchaseInvoiceId"]: `inv_${i}`,+ appliedAmount: a.applied,+ discountAmount: a.discount,+ writeOffAmount: a.writeOff,+ targetExchangeRate: a.invRate,+ sourceExchangeRate: 1.0,+ })),+ });++ apps.forEach((a, i) => {+ const expected = round4((a.applied + a.discount + a.writeOff) * a.invRate);+ assertEquals(controlMagnitudeFor(lines, `inv_${i}`), expected);+ });+ assert(balanced(signedDebitTotal));+ }+});++// ---------------------------------------------------------------------------+// Property matrix — every AR/AP × rate × relief combination must balance and+// must post the correct FX side (gain when collected/under-paid high, loss when+// collected low / over-paid high).+// ---------------------------------------------------------------------------++Deno.test("matrix: every scenario balances with the correct FX side", () => {+ const invRates = [0.75, 1.0, 1.37];+ const payRates = [0.75, 1.0, 1.37];+ const reliefs = [+ { discount: 0, writeOff: 0 },+ { discount: 5, writeOff: 0 },+ { discount: 0, writeOff: 5 },+ { discount: 3, writeOff: 4 },+ ];++ for (const isReceipt of [true, false]) {+ for (const invRate of invRates) {+ for (const payRate of payRates) {+ for (const relief of reliefs) {+ const applied = 100;+ const base = isReceipt ? arBase() : apBase();+ const { lines, signedDebitTotal, totalFxImpact } = buildPaymentJournal({+ ...base,+ exchangeRate: payRate,+ totalAmount: applied,+ applications: [+ {+ [isReceipt ? "targetSalesInvoiceId" : "targetPurchaseInvoiceId"]: "inv",+ appliedAmount: applied,+ discountAmount: relief.discount,+ writeOffAmount: relief.writeOff,+ targetExchangeRate: invRate,+ sourceExchangeRate: payRate,+ },+ ],+ });++ assert(+ Math.abs(signedDebitTotal) < 0.01,+ `unbalanced: receipt=${isReceipt} inv=${invRate} pay=${payRate}`+ );++ const expectedFx =+ (isReceipt ? 1 : -1) * applied * (payRate - invRate);+ if (Math.abs(expectedFx) > 0.0001) {+ const side = expectedFx > 0 ? "Realized FX Gain" : "Realized FX Loss";+ const wrong = expectedFx > 0 ? "Realized FX Loss" : "Realized FX Gain";+ assert(line(lines, side) !== undefined, `missing ${side}`);+ assert(line(lines, wrong) === undefined, `unexpected ${wrong}`);+ }+ assert(Math.abs(round4(totalFxImpact) - round4(expectedFx)) < 1e-9);+ }+ }+ }+ }+});diff --git a/packages/database/supabase/functions/post-production-event/index.ts b/packages/database/supabase/functions/post-production-event/index.tsindex deda022946..c2970663dc 100644--- a/packages/database/supabase/functions/post-production-event/index.ts+++ b/packages/database/supabase/functions/post-production-event/index.ts@@ -69,7 +69,7 @@ serve(async (req: Request) => {.select("id, entityType").eq("companyGroupId", companyRecord.data.companyGroupId).eq("active", true)- .in("entityType", ["ItemPostingGroup", "Location", "Employee", "WorkCenter", "Process"]),+ .in("entityType", ["ItemPostingGroup", "Item", "Location", "Employee", "WorkCenter", "Process"]),]);if (productionEvent.error) throw new Error("Failed to fetch production event");@@ -231,6 +231,14 @@ serve(async (req: Request) => {companyId,});}+ if (job.data.itemId && dimensionMap.has("Item")) {+ dimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Item")!,+ valueId: job.data.itemId,+ companyId,+ });+ }if (job.data.locationId && dimensionMap.has("Location")) {dimensionInserts.push({journalLineId: jl.id,diff --git a/packages/database/supabase/functions/post-purchase-invoice/index.ts b/packages/database/supabase/functions/post-purchase-invoice/index.tsindex 258aa3d274..8b40b6c0d5 100644--- a/packages/database/supabase/functions/post-purchase-invoice/index.ts+++ b/packages/database/supabase/functions/post-purchase-invoice/index.ts@@ -417,7 +417,9 @@ serve(async (req: Request) => {.eq("active", true).in("entityType", ["SupplierType",+ "Supplier","ItemPostingGroup",+ "Item","Location","CostCenter","Process",@@ -534,6 +536,7 @@ serve(async (req: Request) => {const journalLineDimensionsMeta: {supplierTypeId: string | null;itemPostingGroupId: string | null;+ itemId: string | null;locationId: string | null;costCenterId: string | null;processId: string | null;@@ -660,6 +663,12 @@ serve(async (req: Request) => {throw new Error("Error getting account defaults");}+ // Invoice exchange rate (defaults to 1 for base-currency invoices).+ // shippingCost (line 445) is already multiplied by the rate; per-line+ // unitPrice / shippingCost / taxAmount on purchaseInvoiceLine are in+ // invoice currency and need conversion before they reach a journal line.+ const invoiceExchangeRate = purchaseInvoice.data?.exchangeRate ?? 1;+for await (const invoiceLine of purchaseInvoiceLines.data) {const invoiceLineQuantityInInventoryUnit =invoiceLine.quantity * (invoiceLine.conversionFactor ?? 1);@@ -673,8 +682,10 @@ serve(async (req: Request) => {totalLinesCost === 0 ? 0 : totalLineCost / totalLinesCost;const lineWeightedShippingCost =shippingCost * lineCostPercentageOfTotalCost;+ // Convert line cost to base currency before combining with the+ // already-converted shipping cost.const totalLineCostWithWeightedShipping =- totalLineCost + lineWeightedShippingCost;+ totalLineCost * invoiceExchangeRate + lineWeightedShippingCost;const invoiceLineUnitCostInInventoryUnit =totalLineCostWithWeightedShipping /@@ -810,6 +821,7 @@ serve(async (req: Request) => {const itemDimMeta = {supplierTypeId: supplier.data.supplierTypeId ?? null,itemPostingGroupId: lineItemPostingGroupId,+ itemId: invoiceLine.itemId ?? null,locationId: invoiceLine.locationId ?? null,costCenterId: null,processId: null,@@ -1000,6 +1012,7 @@ serve(async (req: Request) => {const reverseDimMeta = {supplierTypeId: supplier.data.supplierTypeId ?? null,itemPostingGroupId: reverseLineItemPostingGroupId,+ itemId: invoiceLine.itemId ?? null,locationId: invoiceLine.locationId ?? null,costCenterId: null,processId: lineProcessId,@@ -1069,6 +1082,7 @@ serve(async (req: Request) => {const accrualDimMeta = {supplierTypeId: supplier.data.supplierTypeId ?? null,itemPostingGroupId: accrualLineItemPostingGroupId,+ itemId: invoiceLine.itemId ?? null,locationId: invoiceLine.locationId ?? null,costCenterId: null,processId: accrualProcessId,@@ -1284,6 +1298,7 @@ serve(async (req: Request) => {const assetDimMeta = {supplierTypeId: supplier.data.supplierTypeId ?? null,itemPostingGroupId: null,+ itemId: null,locationId: invoiceLine.locationId ?? purchaseOrderLine?.locationId ?? faLocationId,costCenterId: null,processId: null,@@ -1349,6 +1364,7 @@ serve(async (req: Request) => {const glDimMeta = {supplierTypeId: null,itemPostingGroupId: null,+ itemId: null,locationId: invoiceLine.locationId ?? null,costCenterId: invoiceLine.costCenterId ?? null,processId: null,@@ -1565,6 +1581,25 @@ serve(async (req: Request) => {companyId,});}+ if (meta.itemId && dimensionMap.has("Item")) {+ journalLineDimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Item")!,+ valueId: meta.itemId,+ companyId,+ });+ }+ if (+ purchaseInvoice.data?.supplierId &&+ dimensionMap.has("Supplier")+ ) {+ journalLineDimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Supplier")!,+ valueId: purchaseInvoice.data.supplierId,+ companyId,+ });+ }if (meta.locationId && dimensionMap.has("Location")) {journalLineDimensionInserts.push({journalLineId: jl.id,diff --git a/packages/database/supabase/functions/post-receipt/index.ts b/packages/database/supabase/functions/post-receipt/index.tsindex ca31b3da13..82ab7700ce 100644--- a/packages/database/supabase/functions/post-receipt/index.ts+++ b/packages/database/supabase/functions/post-receipt/index.ts@@ -81,7 +81,7 @@ serve(async (req: Request) => {.select("id, entityType").eq("companyGroupId", companyGroupId).eq("active", true)- .in("entityType", ["SupplierType", "ItemPostingGroup", "Location", "Process", "FixedAssetClass"]),+ .in("entityType", ["SupplierType", "Supplier", "ItemPostingGroup", "Item", "Location", "Process", "FixedAssetClass"]),]);if (receipt.error) throw new Error("Failed to fetch receipt");@@ -591,6 +591,7 @@ serve(async (req: Request) => {const journalLineDimensionsMeta: {supplierTypeId: string | null;itemPostingGroupId: string | null;+ itemId: string | null;locationId: string | null;processId: string | null;fixedAssetClassId: string | null;@@ -1173,6 +1174,7 @@ serve(async (req: Request) => {journalLineDimensionsMeta.push({supplierTypeId: supplier.data.supplierTypeId ?? null,itemPostingGroupId: lineItemPostingGroupId,+ itemId: receiptLine.itemId ?? null,locationId: receiptLine.locationId ?? null,processId: lineProcessId,fixedAssetClassId: null,@@ -1256,6 +1258,7 @@ serve(async (req: Request) => {journalLineDimensionsMeta.push({supplierTypeId: supplier.data.supplierTypeId ?? null,itemPostingGroupId: null,+ itemId: null,locationId: faPoLine.locationId ?? receipt.data.locationId ?? assetRecord.data.locationId ?? null,processId: null,fixedAssetClassId: assetRecord.data.fixedAssetClassId ?? null,@@ -1445,6 +1448,25 @@ serve(async (req: Request) => {companyId,});}+ if (meta.itemId && dimensionMap.has("Item")) {+ journalLineDimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Item")!,+ valueId: meta.itemId,+ companyId,+ });+ }+ if (+ purchaseOrder.data.supplierId &&+ dimensionMap.has("Supplier")+ ) {+ journalLineDimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Supplier")!,+ valueId: purchaseOrder.data.supplierId,+ companyId,+ });+ }if (meta.locationId && dimensionMap.has("Location")) {journalLineDimensionInserts.push({journalLineId: jl.id,@@ -1603,6 +1625,7 @@ serve(async (req: Request) => {>[] = [];const journalLineDimensionsMeta: {itemPostingGroupId: string | null;+ itemId: string | null;locationId: string | null;fixedAssetClassId: string | null;}[] = [];@@ -1703,6 +1726,7 @@ serve(async (req: Request) => {for (let i = 0; i < jlCount; i++) {journalLineDimensionsMeta.push({itemPostingGroupId: itemCost?.itemPostingGroupId ?? null,+ itemId: receiptLine.itemId ?? null,locationId: receiptLine.locationId ?? null,fixedAssetClassId: null,});@@ -1826,6 +1850,14 @@ serve(async (req: Request) => {companyId,});}+ if (meta.itemId && dimensionMap.has("Item")) {+ journalLineDimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Item")!,+ valueId: meta.itemId,+ companyId,+ });+ }if (meta.locationId && dimensionMap.has("Location")) {journalLineDimensionInserts.push({journalLineId: jl.id,diff --git a/packages/database/supabase/functions/post-sales-invoice/index.ts b/packages/database/supabase/functions/post-sales-invoice/index.tsindex c4409ce198..9e620cecfa 100644--- a/packages/database/supabase/functions/post-sales-invoice/index.ts+++ b/packages/database/supabase/functions/post-sales-invoice/index.ts@@ -252,6 +252,8 @@ serve(async (req: Request) => {"Location","CostCenter","FixedAssetClass",+ "Customer",+ "Item",]): null;@@ -265,6 +267,7 @@ serve(async (req: Request) => {const journalLineDimensionsMeta: {customerTypeId: string | null;itemPostingGroupId: string | null;+ itemId: string | null;locationId: string | null;costCenterId: string | null;fixedAssetClassId: string | null;@@ -287,6 +290,12 @@ serve(async (req: Request) => {receivablesAccountId = accountDefaults?.data?.receivablesAccount;}+ // Invoice exchange rate (defaults to 1 for base-currency invoices).+ // journalLine.amount is denominated in base currency, so all monetary+ // amounts derived from the invoice's foreign-currency unitPrice etc.+ // must be multiplied by this rate before they reach a journal line.+ const invoiceExchangeRate = salesInvoice.data?.exchangeRate ?? 1;+for await (const invoiceLine of salesInvoiceLines.data) {const invoiceLineQuantityInInventoryUnit = invoiceLine.quantity;@@ -300,8 +309,9 @@ serve(async (req: Request) => {totalLinesCost === 0 ? 0 : totalLineCost / totalLinesCost;const lineWeightedShippingCost =shippingCost * lineCostPercentageOfTotalCost;+ // Convert to base currency for the GL.const totalLineCostWithWeightedShipping =- totalLineCost + lineWeightedShippingCost;+ (totalLineCost + lineWeightedShippingCost) * invoiceExchangeRate;const invoiceLineUnitCostInInventoryUnit =totalLineCostWithWeightedShipping / invoiceLine.quantity;@@ -410,6 +420,7 @@ serve(async (req: Request) => {journalLineDimensionsMeta.push({customerTypeId: customer.data.customerTypeId ?? null,itemPostingGroupId: lineItemPostingGroupId,+ itemId: invoiceLine.itemId ?? null,locationId: invoiceLine.locationId ?? null,costCenterId: null,fixedAssetClassId: null,@@ -447,6 +458,7 @@ serve(async (req: Request) => {journalLineDimensionsMeta.push({customerTypeId: customer.data.customerTypeId ?? null,itemPostingGroupId: lineItemPostingGroupId,+ itemId: invoiceLine.itemId ?? null,locationId: invoiceLine.locationId ?? null,costCenterId: null,fixedAssetClassId: null,@@ -511,6 +523,7 @@ serve(async (req: Request) => {journalLineDimensionsMeta.push({customerTypeId: customer.data.customerTypeId ?? null,itemPostingGroupId,+ itemId: invoiceLine.itemId ?? null,locationId: invoiceLine.locationId ?? null,costCenterId: null,fixedAssetClassId: null,@@ -586,6 +599,7 @@ serve(async (req: Request) => {journalLineDimensionsMeta.push({customerTypeId: customer.data.customerTypeId ?? null,itemPostingGroupId: null,+ itemId: null,locationId: invoiceLine.locationId ?? salesOrderLine?.locationId ?? assetRecord.data.locationId ?? null,costCenterId: null,fixedAssetClassId: (assetRecord.data.fixedAssetClass as any)?.id ?? null,@@ -667,6 +681,7 @@ serve(async (req: Request) => {customerTypeId:customer.data.customerTypeId ?? null,itemPostingGroupId: null,+ itemId: null,locationId: invoiceLine.locationId ?? salesOrderLine?.locationId ?? assetRecord.data.locationId ?? null,costCenterId: null,fixedAssetClassId: (assetRecord.data.fixedAssetClass as any)?.id ?? null,@@ -697,6 +712,7 @@ serve(async (req: Request) => {customerTypeId:customer.data.customerTypeId ?? null,itemPostingGroupId: null,+ itemId: null,locationId: invoiceLine.locationId ?? salesOrderLine?.locationId ?? assetRecord.data.locationId ?? null,costCenterId: null,fixedAssetClassId: (assetRecord.data.fixedAssetClass as any)?.id ?? null,@@ -726,6 +742,7 @@ serve(async (req: Request) => {customerTypeId:customer.data.customerTypeId ?? null,itemPostingGroupId: null,+ itemId: null,locationId: invoiceLine.locationId ?? salesOrderLine?.locationId ?? null,costCenterId: null,fixedAssetClassId: (assetRecord.data.fixedAssetClass as any)?.id ?? null,@@ -775,6 +792,7 @@ serve(async (req: Request) => {customerTypeId:customer.data.customerTypeId ?? null,itemPostingGroupId: null,+ itemId: null,locationId: invoiceLine.locationId ?? salesOrderLine?.locationId ?? assetRecord.data.locationId ?? null,costCenterId: null,fixedAssetClassId: (assetRecord.data.fixedAssetClass as any)?.id ?? null,@@ -1089,6 +1107,22 @@ serve(async (req: Request) => {companyId,});}+ if (meta.itemId && dimensionMap.has("Item")) {+ journalLineDimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Item")!,+ valueId: meta.itemId,+ companyId,+ });+ }+ if (salesInvoice.data?.customerId && dimensionMap.has("Customer")) {+ journalLineDimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Customer")!,+ valueId: salesInvoice.data.customerId,+ companyId,+ });+ }});if (journalLineDimensionInserts.length > 0) {diff --git a/packages/database/supabase/functions/post-shipment/index.ts b/packages/database/supabase/functions/post-shipment/index.tsindex 984873bd31..93f3cf4cd1 100644--- a/packages/database/supabase/functions/post-shipment/index.ts+++ b/packages/database/supabase/functions/post-shipment/index.ts@@ -172,7 +172,9 @@ serve(async (req: Request) => {.eq("companyGroupId", companyGroupId).eq("active", true).in("entityType", [+ "Customer","CustomerType",+ "Item","ItemPostingGroup","Location","CostCenter",@@ -197,6 +199,7 @@ serve(async (req: Request) => {const journalLineDimensionsMeta: {customerTypeId: string | null;+ itemId: string | null;itemPostingGroupId: string | null;locationId: string | null;costCenterId: string | null;@@ -454,6 +457,7 @@ serve(async (req: Request) => {for (let i = 0; i < 2; i++) {journalLineDimensionsMeta.push({customerTypeId: customer.data.customerTypeId ?? null,+ itemId: shipmentLine.itemId ?? null,itemPostingGroupId,locationId: shipmentLine.locationId ?? locationId ?? null,costCenterId: salesOrderLine?.costCenterId ?? null,@@ -592,6 +596,7 @@ serve(async (req: Request) => {journalLineDimensionsMeta.push({customerTypeId: customer.data.customerTypeId ?? null,+ itemId: null,itemPostingGroupId: null,locationId: locationId ?? assetRecord.data.locationId ?? null,costCenterId: faSoLine.costCenterId ?? null,@@ -619,6 +624,7 @@ serve(async (req: Request) => {journalLineDimensionsMeta.push({customerTypeId: customer.data.customerTypeId ?? null,+ itemId: null,itemPostingGroupId: null,locationId: locationId ?? assetRecord.data.locationId ?? null,costCenterId: faSoLine.costCenterId ?? null,@@ -645,6 +651,7 @@ serve(async (req: Request) => {journalLineDimensionsMeta.push({customerTypeId: customer.data.customerTypeId ?? null,+ itemId: null,itemPostingGroupId: null,locationId: locationId ?? assetRecord.data.locationId ?? null,costCenterId: faSoLine.costCenterId ?? null,@@ -1206,6 +1213,17 @@ serve(async (req: Request) => {const meta = journalLineDimensionsMeta[index];if (!meta) return;+ if (+ salesOrder.data?.customerId &&+ dimensionMap.has("Customer")+ ) {+ journalLineDimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Customer")!,+ valueId: salesOrder.data.customerId,+ companyId,+ });+ }if (meta.customerTypeId && dimensionMap.has("CustomerType")) {journalLineDimensionInserts.push({journalLineId: jl.id,@@ -1214,6 +1232,14 @@ serve(async (req: Request) => {companyId,});}+ if (meta.itemId && dimensionMap.has("Item")) {+ journalLineDimensionInserts.push({+ journalLineId: jl.id,+ dimensionId: dimensionMap.get("Item")!,+ valueId: meta.itemId,+ companyId,+ });+ }if (meta.itemPostingGroupId && dimensionMap.has("ItemPostingGroup")) {journalLineDimensionInserts.push({journalLineId: jl.id,diff --git a/packages/database/supabase/migrations/20260630090112_customer-supplier-item-dimensions.sql b/packages/database/supabase/migrations/20260630090112_customer-supplier-item-dimensions.sqlnew file mode 100644index 0000000000..f0e7472df9--- /dev/null+++ b/packages/database/supabase/migrations/20260630090112_customer-supplier-item-dimensions.sql@@ -0,0 +1,7 @@+-- Add Customer, Supplier, and Item to the dimensionEntityType enum.+-- Enum-add only: Postgres will not allow a newly added enum value to be used+-- in the same transaction that adds it, so the backfill that references these+-- values lives in a separate, later migration.+ALTER TYPE "dimensionEntityType" ADD VALUE 'Customer';+ALTER TYPE "dimensionEntityType" ADD VALUE 'Supplier';+ALTER TYPE "dimensionEntityType" ADD VALUE 'Item';diff --git a/packages/database/supabase/migrations/20260630091344_backfill-entity-dimensions.sql b/packages/database/supabase/migrations/20260630091344_backfill-entity-dimensions.sqlnew file mode 100644index 0000000000..1b496ef198--- /dev/null+++ b/packages/database/supabase/migrations/20260630091344_backfill-entity-dimensions.sql@@ -0,0 +1,26 @@+-- Backfill default entity-backed dimensions for every existing company group.+-- Idempotent: the dimension (name, companyGroupId) unique constraint plus+-- ON CONFLICT DO NOTHING guarantees we never insert a duplicate, so this is+-- safe to (re)run and safe alongside the new-company seed.+--+-- Covers the three new dimensions (Customer, Supplier, Item) and also the+-- WorkCenter / Process / FixedAssetClass dimensions, which were added to the+-- new-company seed (functions/lib/seed.data.ts) but were never backfilled to+-- company groups that predate them. Names mirror seed.data.ts exactly.+INSERT INTO "dimension" ("name", "entityType", "companyGroupId", "createdBy")+SELECT d."name", d."entityType"::"dimensionEntityType", cg."id", 'system'+FROM "companyGroup" cg+CROSS JOIN (+ VALUES+ ('Customer', 'Customer'),+ ('Supplier', 'Supplier'),+ ('Item', 'Item'),+ ('Work Center', 'WorkCenter'),+ ('Process', 'Process'),+ ('Asset Class', 'FixedAssetClass')+) AS d("name", "entityType")+-- The unique constraint on (name, companyGroupId) was replaced by a PARTIAL+-- unique index `WHERE active = true` in 20260524143827_fixed-assets.sql, so the+-- conflict target must repeat that predicate to match (matches the sibling+-- backfills in that migration). Inserted rows default active = true.+ON CONFLICT ("name", "companyGroupId") WHERE "active" = true DO NOTHING;diff --git a/packages/database/supabase/migrations/20260630092517_job-costing-item-dimension.sql b/packages/database/supabase/migrations/20260630092517_job-costing-item-dimension.sqlnew file mode 100644index 0000000000..f12c3b540c--- /dev/null+++ b/packages/database/supabase/migrations/20260630092517_job-costing-item-dimension.sql@@ -0,0 +1,886 @@+-- Add the "Item" accounting dimension to job-costing journal lines.+--+-- Forked verbatim from 20260511120000_backflush-job-materials.sql. The only+-- changes are surgical additions that tag a parallel "Item" dimension (using the+-- raw item id) alongside the existing "ItemPostingGroup" dimension on the journal+-- lines posted by backflush_job_materials and complete_job_to_inventory:+-- * a v_dimension_item TEXT declaration,+-- * adding 'Item' to the dimension-resolution SELECT (IN list + MAX CASE), and+-- * new journalLineDimension INSERTs for the Item dimension.+-- Everything else is copied unchanged.++CREATE OR REPLACE FUNCTION backflush_job_materials(+ p_job_id TEXT,+ p_quantity_complete NUMERIC,+ p_company_id TEXT,+ p_user_id TEXT+)+RETURNS VOID+LANGUAGE plpgsql+SECURITY DEFINER+SET search_path = public+AS $$+DECLARE+ v_job_quantity NUMERIC;+ v_job_location_id TEXT;+ v_job_id_readable TEXT;+ v_ratio NUMERIC;+ v_target NUMERIC;+ v_material RECORD;+ v_material_qty_to_issue NUMERIC;+ v_material_storage_unit_id TEXT;+ v_material_costing_method TEXT;+ v_material_standard_cost NUMERIC;+ v_material_unit_cost NUMERIC;+ v_material_item_posting_group_id TEXT;+ v_material_cogs_total NUMERIC;+ v_cost_layer RECORD;+ v_remaining_to_consume NUMERIC;+ v_layer_unit_cost NUMERIC;+ v_quantity_from_layer NUMERIC;+ v_accounting_enabled BOOLEAN;+ v_company_group_id TEXT;+ v_inventory_account TEXT;+ v_wip_account TEXT;+ v_dimension_item_posting_group TEXT;+ v_dimension_item TEXT;+ v_dimension_location TEXT;+ v_bf_item_ids TEXT[] := '{}';+ v_bf_quantities NUMERIC[] := '{}';+ v_bf_storage_unit_ids TEXT[] := '{}';+ v_bf_journal_id TEXT;+ v_bf_journal_entry_id TEXT;+ v_bf_accounting_period_id TEXT;+ v_bf_journal_line_ref TEXT;+ v_bf_jl_id TEXT;+ v_bf_jl_ids TEXT[];+ v_bf_posting_group_ids TEXT[];+BEGIN+ -- Fetch job details+ SELECT quantity, "locationId", "jobId"+ INTO STRICT v_job_quantity, v_job_location_id, v_job_id_readable+ FROM "job"+ WHERE id = p_job_id;++ IF v_job_quantity IS NULL OR v_job_quantity <= 0 THEN+ RETURN;+ END IF;++ v_ratio := p_quantity_complete / v_job_quantity;++ -- Backflush non-tracked materials+ FOR v_material IN+ SELECT jm.id, jm."itemId", jm."quantityToIssue", jm."quantityIssued",+ jm."estimatedQuantity", jm."storageUnitId", jm."defaultStorageUnit"+ FROM "jobMaterial" jm+ WHERE jm."jobId" = p_job_id+ AND jm."itemType" IN ('Material', 'Part', 'Consumable')+ AND jm."methodType" != 'Make to Order'+ AND jm."requiresBatchTracking" = false+ AND jm."requiresSerialTracking" = false+ AND jm."quantityToIssue" > 0+ LOOP+ -- Prorate: only issue what's needed for the completed quantity+ v_target := v_material."estimatedQuantity" * v_ratio;+ v_material_qty_to_issue := GREATEST(v_target - COALESCE(v_material."quantityIssued", 0), 0);++ IF v_material_qty_to_issue <= 0 THEN+ CONTINUE;+ END IF;++ -- Resolve storage unit+ v_material_storage_unit_id := v_material."storageUnitId";++ IF v_material_storage_unit_id IS NULL AND v_material."defaultStorageUnit" THEN+ SELECT "defaultStorageUnitId" INTO v_material_storage_unit_id+ FROM "pickMethod"+ WHERE "itemId" = v_material."itemId"+ AND "locationId" = v_job_location_id+ AND "companyId" = p_company_id;+ END IF;++ IF v_material_storage_unit_id IS NULL THEN+ SELECT "storageUnitId" INTO v_material_storage_unit_id+ FROM "itemLedger"+ WHERE "itemId" = v_material."itemId"+ AND "locationId" = v_job_location_id+ AND "storageUnitId" IS NOT NULL+ GROUP BY "storageUnitId"+ HAVING SUM(quantity) > 0+ ORDER BY SUM(quantity) DESC+ LIMIT 1;+ END IF;++ INSERT INTO "itemLedger" (+ "entryType", "documentType", "documentId", "companyId",+ "itemId", quantity, "locationId", "storageUnitId", "createdBy"+ ) VALUES (+ 'Consumption', 'Job Consumption', p_job_id, p_company_id,+ v_material."itemId", -v_material_qty_to_issue,+ v_job_location_id, v_material_storage_unit_id, p_user_id+ );++ UPDATE "jobMaterial"+ SET "quantityIssued" = COALESCE("quantityIssued", 0) + v_material_qty_to_issue+ WHERE id = v_material.id;++ v_bf_item_ids := v_bf_item_ids || v_material."itemId";+ v_bf_quantities := v_bf_quantities || v_material_qty_to_issue;+ v_bf_storage_unit_ids := v_bf_storage_unit_ids || COALESCE(v_material_storage_unit_id, '');+ END LOOP;++ -- Check if accounting is enabled+ SELECT "accountingEnabled"+ INTO v_accounting_enabled+ FROM "companySettings"+ WHERE id = p_company_id;++ v_accounting_enabled := COALESCE(v_accounting_enabled, false);++ IF NOT v_accounting_enabled THEN+ RETURN;+ END IF;++ IF array_length(v_bf_item_ids, 1) IS NULL OR array_length(v_bf_item_ids, 1) = 0 THEN+ RETURN;+ END IF;++ -- Fetch company group+ SELECT "companyGroupId"+ INTO STRICT v_company_group_id+ FROM company+ WHERE id = p_company_id;++ -- Fetch account defaults+ SELECT "inventoryAccount", "workInProgressAccount"+ INTO STRICT v_inventory_account, v_wip_account+ FROM "accountDefault"+ WHERE "companyId" = p_company_id;++ -- Fetch dimension IDs+ SELECT+ MAX(CASE WHEN "entityType" = 'ItemPostingGroup' THEN id END),+ MAX(CASE WHEN "entityType" = 'Item' THEN "id" END),+ MAX(CASE WHEN "entityType" = 'Location' THEN id END)+ INTO v_dimension_item_posting_group, v_dimension_item, v_dimension_location+ FROM dimension+ WHERE "companyGroupId" = v_company_group_id+ AND active = true+ AND "entityType" IN ('ItemPostingGroup', 'Item', 'Location');++ -- Get accounting period+ SELECT id INTO v_bf_accounting_period_id+ FROM "accountingPeriod"+ WHERE "companyId" = p_company_id+ AND "startDate" <= CURRENT_DATE+ AND "endDate" >= CURRENT_DATE+ AND status = 'Active'+ LIMIT 1;++ IF v_bf_accounting_period_id IS NULL THEN+ UPDATE "accountingPeriod"+ SET status = 'Inactive'+ WHERE status = 'Active' AND "companyId" = p_company_id;++ UPDATE "accountingPeriod"+ SET status = 'Active'+ WHERE "companyId" = p_company_id+ AND "startDate" <= CURRENT_DATE+ AND "endDate" >= CURRENT_DATE+ RETURNING id INTO v_bf_accounting_period_id;++ IF v_bf_accounting_period_id IS NULL THEN+ INSERT INTO "accountingPeriod" (+ "startDate", "endDate", "companyId", status, "createdBy"+ ) VALUES (+ date_trunc('month', CURRENT_DATE)::DATE,+ (date_trunc('month', CURRENT_DATE) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,+ p_company_id, 'Active', 'system'+ )+ RETURNING id INTO v_bf_accounting_period_id;+ END IF;+ END IF;++ v_bf_journal_entry_id := get_next_sequence('journalEntry', p_company_id);++ INSERT INTO journal (+ "journalEntryId", "accountingPeriodId", description,+ "postingDate", "companyId", "sourceType", status,+ "postedAt", "postedBy", "createdBy"+ ) VALUES (+ v_bf_journal_entry_id, v_bf_accounting_period_id,+ 'Material Issue — Job ' || v_job_id_readable,+ CURRENT_DATE, p_company_id, 'Job Consumption', 'Posted',+ NOW(), p_user_id, p_user_id+ )+ RETURNING id INTO v_bf_journal_id;++ v_bf_jl_ids := '{}';+ v_bf_posting_group_ids := '{}';++ FOR i IN 1..array_length(v_bf_item_ids, 1)+ LOOP+ -- Get itemCost for COGS calculation+ SELECT "costingMethod", "standardCost", "unitCost", "itemPostingGroupId"+ INTO v_material_costing_method, v_material_standard_cost, v_material_unit_cost, v_material_item_posting_group_id+ FROM "itemCost"+ WHERE "itemId" = v_bf_item_ids[i]+ AND "companyId" = p_company_id;++ IF v_material_costing_method IS NULL THEN+ CONTINUE;+ END IF;++ -- Calculate COGS based on costing method+ v_material_cogs_total := 0;++ IF v_material_costing_method = 'Standard' THEN+ v_material_cogs_total := COALESCE(v_material_standard_cost, 0) * v_bf_quantities[i];++ ELSIF v_material_costing_method = 'Average' THEN+ v_material_cogs_total := COALESCE(v_material_unit_cost, 0) * v_bf_quantities[i];++ ELSIF v_material_costing_method IN ('FIFO', 'LIFO') THEN+ v_remaining_to_consume := v_bf_quantities[i];++ FOR v_cost_layer IN+ SELECT id, quantity, cost, "remainingQuantity"+ FROM "costLedger"+ WHERE "itemId" = v_bf_item_ids[i]+ AND "companyId" = p_company_id+ AND "remainingQuantity" > 0+ ORDER BY+ CASE WHEN v_material_costing_method = 'FIFO' THEN "postingDate" END ASC,+ CASE WHEN v_material_costing_method = 'LIFO' THEN "postingDate" END DESC,+ CASE WHEN v_material_costing_method = 'FIFO' THEN "createdAt" END ASC,+ CASE WHEN v_material_costing_method = 'LIFO' THEN "createdAt" END DESC+ LOOP+ EXIT WHEN v_remaining_to_consume <= 0;++ v_layer_unit_cost := CASE+ WHEN v_cost_layer.quantity > 0 THEN v_cost_layer.cost / v_cost_layer.quantity+ ELSE 0+ END;++ v_quantity_from_layer := LEAST(v_remaining_to_consume, v_cost_layer."remainingQuantity");+ v_material_cogs_total := v_material_cogs_total + v_quantity_from_layer * v_layer_unit_cost;+ v_remaining_to_consume := v_remaining_to_consume - v_quantity_from_layer;++ UPDATE "costLedger"+ SET "remainingQuantity" = "remainingQuantity" - v_quantity_from_layer+ WHERE id = v_cost_layer.id;+ END LOOP;++ -- Fallback for negative inventory+ IF v_remaining_to_consume > 0 THEN+ v_material_cogs_total := v_material_cogs_total + v_remaining_to_consume * COALESCE(v_material_unit_cost, 0);+ END IF;+ END IF;++ IF v_material_cogs_total <= 0 THEN+ CONTINUE;+ END IF;++ v_bf_journal_line_ref := nanoid();++ -- DR WIP+ INSERT INTO "journalLine" (+ "journalId", "accountId", description, amount, quantity,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", "companyId"+ ) VALUES (+ v_bf_journal_id, v_wip_account, 'WIP Account',+ v_material_cogs_total, v_bf_quantities[i],+ 'Job Consumption', p_job_id, 'job:' || p_job_id,+ v_bf_journal_line_ref, p_company_id+ )+ RETURNING id INTO v_bf_jl_id;++ v_bf_jl_ids := v_bf_jl_ids || v_bf_jl_id;+ v_bf_posting_group_ids := v_bf_posting_group_ids || COALESCE(v_material_item_posting_group_id, '');++ -- CR Inventory+ INSERT INTO "journalLine" (+ "journalId", "accountId", description, amount, quantity,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", "companyId"+ ) VALUES (+ v_bf_journal_id, v_inventory_account, 'Inventory Account',+ -v_material_cogs_total, v_bf_quantities[i],+ 'Job Consumption', p_job_id, 'job:' || p_job_id,+ v_bf_journal_line_ref, p_company_id+ )+ RETURNING id INTO v_bf_jl_id;++ v_bf_jl_ids := v_bf_jl_ids || v_bf_jl_id;+ v_bf_posting_group_ids := v_bf_posting_group_ids || COALESCE(v_material_item_posting_group_id, '');++ -- Cost ledger entry for consumption+ INSERT INTO "costLedger" (+ "itemLedgerType", "costLedgerType", adjustment,+ "documentType", "documentId", "itemId",+ quantity, cost, "remainingQuantity", "companyId"+ ) VALUES (+ 'Consumption', 'Direct Cost', false,+ 'Job Consumption', p_job_id, v_bf_item_ids[i],+ -v_bf_quantities[i], -v_material_cogs_total,+ 0, p_company_id+ );+ END LOOP;++ -- Dimensions for material consumption journal lines+ IF array_length(v_bf_jl_ids, 1) IS NOT NULL THEN+ FOR i IN 1..array_length(v_bf_jl_ids, 1)+ LOOP+ IF v_bf_posting_group_ids[i] != '' AND v_dimension_item_posting_group IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_bf_jl_ids[i], v_dimension_item_posting_group, v_bf_posting_group_ids[i], p_company_id+ );+ END IF;++ IF v_dimension_item IS NOT NULL AND v_bf_item_ids[i] IS NOT NULL AND v_bf_item_ids[i] != '' THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_bf_jl_ids[i], v_dimension_item, v_bf_item_ids[i], p_company_id+ );+ END IF;++ IF v_job_location_id IS NOT NULL AND v_dimension_location IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_bf_jl_ids[i], v_dimension_location, v_job_location_id, p_company_id+ );+ END IF;+ END LOOP;+ END IF;+END;+$$;++-- Refactor complete_job_to_inventory to delegate backflush to the new function+CREATE OR REPLACE FUNCTION complete_job_to_inventory(+ p_job_id TEXT,+ p_quantity_complete NUMERIC,+ p_storage_unit_id TEXT DEFAULT NULL,+ p_location_id TEXT DEFAULT NULL,+ p_company_id TEXT DEFAULT NULL,+ p_user_id TEXT DEFAULT NULL+)+RETURNS VOID+LANGUAGE plpgsql+SECURITY DEFINER+SET search_path = public+AS $$+DECLARE+ v_item_id TEXT;+ v_quantity_received_to_inventory NUMERIC;+ v_job_id_readable TEXT;+ v_job_make_method RECORD;+ v_tracked_entity RECORD;+ v_accounting_enabled BOOLEAN;+ v_company_group_id TEXT;+ v_inventory_account TEXT;+ v_wip_account TEXT;+ v_labor_absorption_account TEXT;+ v_dimension_item_posting_group TEXT;+ v_dimension_item TEXT;+ v_dimension_location TEXT;+ v_dimension_cost_center TEXT;+ v_dimension_employee TEXT;+ v_event RECORD;+ v_duration_hours NUMERIC;+ v_rate NUMERIC;+ v_labor_cost NUMERIC;+ v_labor_journal_line_reference TEXT;+ v_labor_accounting_period_id TEXT;+ v_labor_journal_entry_id TEXT;+ v_labor_journal_id TEXT;+ v_labor_jl_id TEXT;+ v_accumulated_wip_cost NUMERIC;+ v_today DATE;+ v_journal_line_reference TEXT;+ v_accounting_period_id TEXT;+ v_journal_entry_id TEXT;+ v_journal_id TEXT;+ v_jl_ids TEXT[];+ v_new_per_unit_cost NUMERIC;+ v_costing_method TEXT;+ v_existing_unit_cost NUMERIC;+ v_item_posting_group_id TEXT;+ v_job_location_id TEXT;+ v_total_qty_on_hand NUMERIC;+ v_prior_qty NUMERIC;+ v_prior_value NUMERIC;+ v_new_unit_cost NUMERIC;+BEGIN+ -- Fetch job details+ SELECT "itemId", "quantityReceivedToInventory", "jobId", "locationId"+ INTO STRICT v_item_id, v_quantity_received_to_inventory, v_job_id_readable, v_job_location_id+ FROM "job"+ WHERE id = p_job_id;++ v_quantity_received_to_inventory := p_quantity_complete - COALESCE(v_quantity_received_to_inventory, 0);++ -- Fetch jobMakeMethod for the top-level (no parentMaterialId)+ SELECT *+ INTO STRICT v_job_make_method+ FROM "jobMakeMethod"+ WHERE "jobId" = p_job_id+ AND "parentMaterialId" IS NULL;++ -- Update job status+ UPDATE "job"+ SET status = 'Completed',+ "completedDate" = NOW(),+ "quantityComplete" = p_quantity_complete,+ "quantityReceivedToInventory" = v_quantity_received_to_inventory,+ "updatedAt" = NOW(),+ "updatedBy" = p_user_id+ WHERE id = p_job_id;++ -- Insert itemLedger entries based on tracking type+ IF v_job_make_method."requiresBatchTracking" THEN+ SELECT *+ INTO v_tracked_entity+ FROM "trackedEntity"+ WHERE attributes->>'Job Make Method' = v_job_make_method.id+ AND status != 'Consumed'+ ORDER BY "createdAt" DESC+ LIMIT 1;++ IF v_tracked_entity.id IS NULL THEN+ RAISE EXCEPTION 'Tracked entity not found';+ END IF;++ INSERT INTO "itemLedger" (+ "entryType", "documentType", "documentId", "companyId",+ "itemId", quantity, "locationId", "storageUnitId",+ "trackedEntityId", "createdBy"+ ) VALUES (+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,+ v_tracked_entity.id, p_user_id+ );++ ELSIF v_job_make_method."requiresSerialTracking" THEN+ FOR v_tracked_entity IN+ SELECT *+ FROM "trackedEntity"+ WHERE attributes->>'Job Make Method' = v_job_make_method.id+ AND status != 'Consumed'+ LOOP+ INSERT INTO "itemLedger" (+ "entryType", "documentType", "documentId", "companyId",+ "itemId", quantity, "locationId", "storageUnitId",+ "trackedEntityId", "createdBy"+ ) VALUES (+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,+ v_item_id, 1, p_location_id, p_storage_unit_id,+ v_tracked_entity.id, p_user_id+ );+ END LOOP;++ UPDATE "trackedEntity"+ SET status = 'Available'+ WHERE attributes->>'Job Make Method' = v_job_make_method.id+ AND status != 'Consumed';++ ELSE+ INSERT INTO "itemLedger" (+ "entryType", "documentType", "documentId", "companyId",+ "itemId", quantity, "locationId", "storageUnitId", "createdBy"+ ) VALUES (+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,+ p_user_id+ );+ END IF;++ -- Update pickMethod defaultStorageUnitId if needed+ IF p_storage_unit_id IS NOT NULL AND p_location_id IS NOT NULL THEN+ IF NOT EXISTS (+ SELECT 1 FROM "itemLedger"+ WHERE "itemId" = v_item_id+ AND "locationId" = p_location_id+ AND "storageUnitId" IS NOT NULL+ AND "storageUnitId" != p_storage_unit_id+ LIMIT 1+ ) THEN+ IF EXISTS (+ SELECT 1 FROM "pickMethod"+ WHERE "itemId" = v_item_id AND "locationId" = p_location_id+ ) THEN+ UPDATE "pickMethod"+ SET "defaultStorageUnitId" = p_storage_unit_id,+ "updatedBy" = p_user_id,+ "updatedAt" = NOW()+ WHERE "itemId" = v_item_id+ AND "locationId" = p_location_id;+ ELSE+ INSERT INTO "pickMethod" (+ "itemId", "locationId", "defaultStorageUnitId",+ "companyId", "createdBy", "createdAt"+ ) VALUES (+ v_item_id, p_location_id, p_storage_unit_id,+ p_company_id, p_user_id, NOW()+ );+ END IF;+ END IF;+ END IF;++ -- Backflush unissued materials (delegated to shared function)+ PERFORM backflush_job_materials(p_job_id, p_quantity_complete, p_company_id, p_user_id);++ -- Check if accounting is enabled+ SELECT "accountingEnabled"+ INTO v_accounting_enabled+ FROM "companySettings"+ WHERE id = p_company_id;++ v_accounting_enabled := COALESCE(v_accounting_enabled, false);++ IF NOT v_accounting_enabled THEN+ RETURN;+ END IF;++ -- Fetch company group+ SELECT "companyGroupId"+ INTO STRICT v_company_group_id+ FROM company+ WHERE id = p_company_id;++ -- Fetch account defaults+ SELECT "inventoryAccount", "workInProgressAccount", "laborAbsorptionAccount"+ INTO STRICT v_inventory_account, v_wip_account, v_labor_absorption_account+ FROM "accountDefault"+ WHERE "companyId" = p_company_id;++ -- Fetch dimension IDs+ SELECT+ MAX(CASE WHEN "entityType" = 'ItemPostingGroup' THEN id END),+ MAX(CASE WHEN "entityType" = 'Item' THEN "id" END),+ MAX(CASE WHEN "entityType" = 'Location' THEN id END),+ MAX(CASE WHEN "entityType" = 'CostCenter' THEN id END),+ MAX(CASE WHEN "entityType" = 'Employee' THEN id END)+ INTO v_dimension_item_posting_group, v_dimension_item, v_dimension_location,+ v_dimension_cost_center, v_dimension_employee+ FROM dimension+ WHERE "companyGroupId" = v_company_group_id+ AND active = true+ AND "entityType" IN ('ItemPostingGroup', 'Item', 'Location', 'CostCenter', 'Employee');++ -- Post unposted production events as labor/machine absorption JEs+ FOR v_event IN+ SELECT+ pe.id,+ pe.duration,+ pe.type,+ pe."employeeId",+ wc."laborRate",+ wc."machineRate"+ FROM "productionEvent" pe+ INNER JOIN "jobOperation" jo ON jo.id = pe."jobOperationId"+ INNER JOIN "workCenter" wc ON wc.id = pe."workCenterId"+ WHERE jo."jobId" = p_job_id+ AND pe."endTime" IS NOT NULL+ AND pe."postedToGL" = false+ AND pe.duration > 0+ LOOP+ v_duration_hours := v_event.duration::NUMERIC / 3600;+ v_rate := CASE+ WHEN v_event.type = 'Machine' THEN COALESCE(v_event."machineRate", 0)+ ELSE COALESCE(v_event."laborRate", 0)+ END;+ v_labor_cost := v_duration_hours * v_rate;++ IF v_labor_cost > 0 AND v_labor_absorption_account IS NOT NULL THEN+ v_labor_journal_line_reference := nanoid();++ -- Get current accounting period+ SELECT id INTO v_labor_accounting_period_id+ FROM "accountingPeriod"+ WHERE "companyId" = p_company_id+ AND "startDate" <= CURRENT_DATE+ AND "endDate" >= CURRENT_DATE+ AND status = 'Active'+ LIMIT 1;++ IF v_labor_accounting_period_id IS NULL THEN+ UPDATE "accountingPeriod"+ SET status = 'Inactive'+ WHERE status = 'Active' AND "companyId" = p_company_id;++ UPDATE "accountingPeriod"+ SET status = 'Active'+ WHERE "companyId" = p_company_id+ AND "startDate" <= CURRENT_DATE+ AND "endDate" >= CURRENT_DATE+ RETURNING id INTO v_labor_accounting_period_id;++ IF v_labor_accounting_period_id IS NULL THEN+ INSERT INTO "accountingPeriod" (+ "startDate", "endDate", "companyId", status, "createdBy"+ ) VALUES (+ date_trunc('month', CURRENT_DATE)::DATE,+ (date_trunc('month', CURRENT_DATE) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,+ p_company_id, 'Active', 'system'+ )+ RETURNING id INTO v_labor_accounting_period_id;+ END IF;+ END IF;++ v_labor_journal_entry_id := get_next_sequence('journalEntry', p_company_id);++ INSERT INTO journal (+ "journalEntryId", "accountingPeriodId", description,+ "postingDate", "companyId", "sourceType", status,+ "postedAt", "postedBy", "createdBy"+ ) VALUES (+ v_labor_journal_entry_id, v_labor_accounting_period_id,+ v_event.type || ' Time — Job ' || v_job_id_readable,+ CURRENT_DATE, p_company_id, 'Production Event', 'Posted',+ NOW(), p_user_id, p_user_id+ )+ RETURNING id INTO v_labor_journal_id;++ -- DR WIP+ INSERT INTO "journalLine" (+ "journalId", "accountId", description, amount, quantity,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", "companyId"+ ) VALUES (+ v_labor_journal_id, v_wip_account, 'WIP Account',+ v_labor_cost, 1,+ 'Production Event', p_job_id, 'job:' || p_job_id,+ v_labor_journal_line_reference, p_company_id+ )+ RETURNING id INTO v_labor_jl_id;++ -- Employee dimension on WIP line+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id+ );+ END IF;++ -- Item dimension on WIP line (the finished good this labor rolls into)+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id+ );+ END IF;++ -- CR Labor/Machine Absorption+ INSERT INTO "journalLine" (+ "journalId", "accountId", description, amount, quantity,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", "companyId"+ ) VALUES (+ v_labor_journal_id, v_labor_absorption_account, 'Labor/Machine Absorption',+ -v_labor_cost, 1,+ 'Production Event', p_job_id, 'job:' || p_job_id,+ v_labor_journal_line_reference, p_company_id+ )+ RETURNING id INTO v_labor_jl_id;++ -- Employee dimension on absorption line+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id+ );+ END IF;++ -- Item dimension on absorption line+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id+ );+ END IF;+ END IF;++ UPDATE "productionEvent"+ SET "postedToGL" = true+ WHERE id = v_event.id;+ END LOOP;++ -- Calculate accumulated WIP cost for this job+ SELECT COALESCE(ABS(SUM(jl.amount)), 0)+ INTO v_accumulated_wip_cost+ FROM "journalLine" jl+ INNER JOIN journal j ON j.id = jl."journalId"+ WHERE jl."accountId" = v_wip_account+ AND jl."documentId" = p_job_id+ AND j."companyId" = p_company_id;++ IF v_accumulated_wip_cost <= 0 THEN+ RETURN;+ END IF;++ v_today := CURRENT_DATE;+ v_journal_line_reference := nanoid();++ -- Get accounting period for WIP discharge+ SELECT id INTO v_accounting_period_id+ FROM "accountingPeriod"+ WHERE "companyId" = p_company_id+ AND "startDate" <= v_today+ AND "endDate" >= v_today+ AND status = 'Active'+ LIMIT 1;++ IF v_accounting_period_id IS NULL THEN+ UPDATE "accountingPeriod"+ SET status = 'Inactive'+ WHERE status = 'Active' AND "companyId" = p_company_id;++ UPDATE "accountingPeriod"+ SET status = 'Active'+ WHERE "companyId" = p_company_id+ AND "startDate" <= v_today+ AND "endDate" >= v_today+ RETURNING id INTO v_accounting_period_id;++ IF v_accounting_period_id IS NULL THEN+ INSERT INTO "accountingPeriod" (+ "startDate", "endDate", "companyId", status, "createdBy"+ ) VALUES (+ date_trunc('month', v_today)::DATE,+ (date_trunc('month', v_today) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,+ p_company_id, 'Active', 'system'+ )+ RETURNING id INTO v_accounting_period_id;+ END IF;+ END IF;++ v_journal_entry_id := get_next_sequence('journalEntry', p_company_id);++ INSERT INTO journal (+ "journalEntryId", "accountingPeriodId", description,+ "postingDate", "companyId", "sourceType", status,+ "postedAt", "postedBy", "createdBy"+ ) VALUES (+ v_journal_entry_id, v_accounting_period_id,+ 'Job Completion ' || v_job_id_readable,+ v_today, p_company_id, 'Job Receipt', 'Posted',+ NOW(), p_user_id, p_user_id+ )+ RETURNING id INTO v_journal_id;++ -- DR FG Inventory+ INSERT INTO "journalLine" (+ "journalId", "accountId", description, amount, quantity,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", "companyId"+ ) VALUES (+ v_journal_id, v_inventory_account, 'Finished Goods Inventory',+ v_accumulated_wip_cost, v_quantity_received_to_inventory,+ 'Job Receipt', p_job_id, 'job:' || p_job_id,+ v_journal_line_reference, p_company_id+ )+ RETURNING id INTO v_labor_jl_id;++ v_jl_ids := ARRAY[v_labor_jl_id];++ -- CR WIP+ INSERT INTO "journalLine" (+ "journalId", "accountId", description, amount, quantity,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", "companyId"+ ) VALUES (+ v_journal_id, v_wip_account, 'WIP Account',+ -v_accumulated_wip_cost, v_quantity_received_to_inventory,+ 'Job Receipt', p_job_id, 'job:' || p_job_id,+ v_journal_line_reference, p_company_id+ )+ RETURNING id INTO v_labor_jl_id;++ v_jl_ids := v_jl_ids || v_labor_jl_id;++ -- Write costLedger entry for finished good+ INSERT INTO "costLedger" (+ "itemLedgerType", "costLedgerType", adjustment,+ "documentType", "documentId", "itemId",+ quantity, cost, "remainingQuantity", "companyId"+ ) VALUES (+ 'Output', 'Direct Cost', false,+ 'Job Receipt', p_job_id, v_item_id,+ v_quantity_received_to_inventory, v_accumulated_wip_cost,+ v_quantity_received_to_inventory, p_company_id+ );++ -- Update item cost+ SELECT "costingMethod", "unitCost", "itemPostingGroupId"+ INTO v_costing_method, v_existing_unit_cost, v_item_posting_group_id+ FROM "itemCost"+ WHERE "itemId" = v_item_id+ AND "companyId" = p_company_id;++ v_new_per_unit_cost := v_accumulated_wip_cost / v_quantity_received_to_inventory;++ IF v_costing_method = 'Average' THEN+ SELECT COALESCE(SUM(quantity), 0)+ INTO v_total_qty_on_hand+ FROM "itemLedger"+ WHERE "itemId" = v_item_id+ AND "companyId" = p_company_id;++ v_prior_qty := v_total_qty_on_hand - v_quantity_received_to_inventory;+ v_prior_value := v_prior_qty * COALESCE(v_existing_unit_cost, 0);++ IF v_total_qty_on_hand > 0 THEN+ v_new_unit_cost := (v_prior_value + v_accumulated_wip_cost) / v_total_qty_on_hand;+ UPDATE "itemCost"+ SET "unitCost" = v_new_unit_cost+ WHERE "itemId" = v_item_id+ AND "companyId" = p_company_id;+ END IF;++ ELSIF v_costing_method IN ('FIFO', 'LIFO') THEN+ UPDATE "itemCost"+ SET "unitCost" = v_new_per_unit_cost+ WHERE "itemId" = v_item_id+ AND "companyId" = p_company_id;+ END IF;++ -- Insert dimensions on WIP discharge journal lines+ IF v_jl_ids IS NOT NULL AND array_length(v_jl_ids, 1) > 0 THEN+ FOR i IN 1..array_length(v_jl_ids, 1)+ LOOP+ IF v_item_posting_group_id IS NOT NULL AND v_dimension_item_posting_group IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_jl_ids[i], v_dimension_item_posting_group, v_item_posting_group_id, p_company_id+ );+ END IF;++ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_jl_ids[i], v_dimension_item, v_item_id, p_company_id+ );+ END IF;++ IF v_job_location_id IS NOT NULL AND v_dimension_location IS NOT NULL THEN+ INSERT INTO "journalLineDimension" (+ "journalLineId", "dimensionId", "valueId", "companyId"+ ) VALUES (+ v_jl_ids[i], v_dimension_location, v_job_location_id, p_company_id+ );+ END IF;+ END LOOP;+ END IF;+END;+$$;diff --git a/packages/database/supabase/migrations/20260630093809_ar-ap-payments.sql b/packages/database/supabase/migrations/20260630093809_ar-ap-payments.sqlnew file mode 100644index 0000000000..39832f4161--- /dev/null+++ b/packages/database/supabase/migrations/20260630093809_ar-ap-payments.sql@@ -0,0 +1,533 @@+-- ============================================================+-- AR & AP Payments and Cash Application+--+-- Replaces the unused purchasePayment/purchaseInvoicePaymentRelation+-- stubs with a unified payment + invoiceSettlement model+-- (type-discriminated for AR vs AP, NetSuite-style settlements+-- carrying principal/discount/write-off, multi-currency-aware).+--+-- invoiceSettlement is the ONE settlement primitive: it nets a funding+-- source (a cash payment OR a credit/debit memo) against a target document+-- (an invoice, or a memo when settling/refunding an increaser memo).+-- A memo is its own payment-shaped document (the `memo` table) — party ++-- amount + reason GL account — NOT an invoice row. Applying a balance-reducing+-- memo to an invoice is a subledger row here (GL-neutral except realized FX).+--+-- Also adds four new accountDefault columns (customer/supplier+-- write-off, realized FX gain/loss) and one new chart-of-accounts+-- entry (4130 Vendor Write-Off Income). The remaining defaults+-- map to existing accounts (6050 Bad Debts Expense, 4120 FX Gains,+-- 7060 FX Losses).+-- ============================================================+++-- ============================================================+-- Phase 1: Drop the unused AP stubs+-- ============================================================+-- The relation table has no amount/discount/write-off columns and+-- is unused in app code; the purchasePayment table is referenced+-- only by metadata (customFieldTable). DROP TABLE cascades to its+-- policies and any FK-attached customField rows.++DELETE FROM "customFieldTable" WHERE "table" = 'purchasePayment';++DROP TABLE IF EXISTS "purchaseInvoicePaymentRelation";+DROP TABLE IF EXISTS "purchasePayment";+++-- ============================================================+-- Phase 2: New chart-of-accounts entry 4130 (Vendor Write-Off Income)+-- ============================================================+-- AR write-off uses existing 6050 Bad Debts Expense.+-- Realized FX gain/loss use existing 4120 / 7060.+-- AP write-off needs a new Other Income account.++DO $$+DECLARE+ cg RECORD;+ parent_id TEXT;+BEGIN+ FOR cg IN SELECT id FROM "companyGroup"+ LOOP+ -- Other Income group header has isGroup=TRUE and number IS NULL.+ SELECT id INTO parent_id+ FROM "account"+ WHERE "companyGroupId" = cg.id AND "isGroup" = TRUE AND name = 'Other Income'+ LIMIT 1;++ INSERT INTO "account" (+ number, name, "isGroup", "accountType", "incomeBalance", class,+ "parentId", "isSystem", "companyGroupId", "createdBy"+ )+ SELECT+ '4130', 'Vendor Write-Off Income', FALSE,+ 'Other Income'::"accountType",+ 'Income Statement'::"glIncomeBalance",+ 'Revenue'::"glAccountClass",+ parent_id, FALSE, cg.id, 'system'+ WHERE NOT EXISTS (+ SELECT 1 FROM "account"+ WHERE "companyGroupId" = cg.id AND number = '4130'+ );+ END LOOP;+END $$;+++-- ============================================================+-- Phase 3: Extend accountDefault with the four new mappings+-- ============================================================+-- Add nullable, backfill, then SET NOT NULL to match existing+-- column nullability convention on this table.++ALTER TABLE "accountDefault"+ ADD COLUMN "customerWriteOffAccount" TEXT,+ ADD COLUMN "supplierWriteOffAccount" TEXT,+ ADD COLUMN "realizedExchangeGainAccount" TEXT,+ ADD COLUMN "realizedExchangeLossAccount" TEXT;++-- Backfill: look up the account.id for each company's group by account.number.+UPDATE "accountDefault" ad+SET+ "customerWriteOffAccount" = (+ SELECT a.id FROM "account" a+ INNER JOIN "company" c ON c."companyGroupId" = a."companyGroupId"+ WHERE c.id = ad."companyId" AND a.number = '6050' LIMIT 1+ ),+ "supplierWriteOffAccount" = (+ SELECT a.id FROM "account" a+ INNER JOIN "company" c ON c."companyGroupId" = a."companyGroupId"+ WHERE c.id = ad."companyId" AND a.number = '4130' LIMIT 1+ ),+ "realizedExchangeGainAccount" = (+ SELECT a.id FROM "account" a+ INNER JOIN "company" c ON c."companyGroupId" = a."companyGroupId"+ WHERE c.id = ad."companyId" AND a.number = '4120' LIMIT 1+ ),+ "realizedExchangeLossAccount" = (+ SELECT a.id FROM "account" a+ INNER JOIN "company" c ON c."companyGroupId" = a."companyGroupId"+ WHERE c.id = ad."companyId" AND a.number = '7060' LIMIT 1+ );++ALTER TABLE "accountDefault"+ ALTER COLUMN "customerWriteOffAccount" SET NOT NULL,+ ALTER COLUMN "supplierWriteOffAccount" SET NOT NULL,+ ALTER COLUMN "realizedExchangeGainAccount" SET NOT NULL,+ ALTER COLUMN "realizedExchangeLossAccount" SET NOT NULL;++ALTER TABLE "accountDefault"+ ADD CONSTRAINT "accountDefault_customerWriteOffAccount_fkey"+ FOREIGN KEY ("customerWriteOffAccount") REFERENCES "account"("id")+ ON DELETE RESTRICT ON UPDATE CASCADE,+ ADD CONSTRAINT "accountDefault_supplierWriteOffAccount_fkey"+ FOREIGN KEY ("supplierWriteOffAccount") REFERENCES "account"("id")+ ON DELETE RESTRICT ON UPDATE CASCADE,+ ADD CONSTRAINT "accountDefault_realizedExchangeGainAccount_fkey"+ FOREIGN KEY ("realizedExchangeGainAccount") REFERENCES "account"("id")+ ON DELETE RESTRICT ON UPDATE CASCADE,+ ADD CONSTRAINT "accountDefault_realizedExchangeLossAccount_fkey"+ FOREIGN KEY ("realizedExchangeLossAccount") REFERENCES "account"("id")+ ON DELETE RESTRICT ON UPDATE CASCADE;+++-- ============================================================+-- Phase 4: Enums+-- ============================================================++CREATE TYPE "paymentType" AS ENUM ('Receipt', 'Disbursement');+CREATE TYPE "paymentStatus" AS ENUM ('Draft', 'Posted', 'Voided');++-- A credit/debit memo is a standalone, payment-shaped document (Phase 5b) — NOT+-- an invoice row. `direction` is whether it credits or debits the party's+-- control account (Credit ⇒ DR reason / CR control; Debit ⇒ DR control / CR+-- reason); status mirrors payment's lifecycle.+CREATE TYPE "memoDirection" AS ENUM ('Credit', 'Debit');+CREATE TYPE "memoStatus" AS ENUM ('Draft', 'Posted', 'Voided');++ALTER TYPE "journalLineDocumentType" ADD VALUE IF NOT EXISTS 'Payment';+-- post-memo writes its journal lines with documentType 'Memo'.+ALTER TYPE "journalLineDocumentType" ADD VALUE IF NOT EXISTS 'Memo';+-- journal.sourceType: post-payment writes 'Payment'; post-memo writes+-- 'Credit Memo' / 'Debit Memo'.+ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Payment';+ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Credit Memo';+ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Debit Memo';+++-- ============================================================+-- Phase 5: payment table+-- ============================================================+-- The cash event. Receipt (AR cash-in) or Disbursement (AP cash-out)+-- discriminated by paymentType. customerId xor supplierId enforced+-- by check matching the type.++CREATE TABLE "payment" (+ "id" TEXT NOT NULL PRIMARY KEY DEFAULT xid(),+ "paymentId" TEXT NOT NULL,+ "paymentType" "paymentType" NOT NULL,+ "status" "paymentStatus" NOT NULL DEFAULT 'Draft',+ "customerId" TEXT,+ "supplierId" TEXT,+ "paymentDate" DATE NOT NULL,+ "postingDate" DATE,+ "currencyCode" TEXT NOT NULL,+ "exchangeRate" NUMERIC NOT NULL DEFAULT 1,+ "totalAmount" NUMERIC NOT NULL,+ "bankAccount" TEXT NOT NULL,+ "reference" TEXT,+ "memo" TEXT,+ "journalId" TEXT,+ "postedAt" TIMESTAMP WITH TIME ZONE,+ "postedBy" TEXT,+ "voidedAt" TIMESTAMP WITH TIME ZONE,+ "voidedBy" TEXT,+ "companyId" TEXT NOT NULL,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT,+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ "customFields" JSONB,++ -- Exactly one counterparty. Direction (paymentType) is intentionally decoupled+ -- from the party so refunds work: a Disbursement can pay a CUSTOMER (refund of+ -- an AR credit) and a Receipt can come from a SUPPLIER (refund of an AP debit).+ -- The per-flow type↔party↔target pairing is enforced by the posting functions.+ CONSTRAINT "payment_party_check" CHECK (+ ("customerId" IS NOT NULL AND "supplierId" IS NULL) OR+ ("customerId" IS NULL AND "supplierId" IS NOT NULL)+ ),+ -- 0 is allowed: a receipt/payment can be a pure credit-application (apply the+ -- party's posted credits to invoices with no cash changing hands).+ CONSTRAINT "payment_totalAmount_check" CHECK ("totalAmount" >= 0),+ CONSTRAINT "payment_exchangeRate_check" CHECK ("exchangeRate" > 0),+ CONSTRAINT "payment_paymentId_companyId_key" UNIQUE ("paymentId", "companyId"),++ CONSTRAINT "payment_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "customer"("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "payment_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier"("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "payment_currencyCode_fkey" FOREIGN KEY ("currencyCode") REFERENCES "currencyCode"("code") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "payment_bankAccount_fkey" FOREIGN KEY ("bankAccount") REFERENCES "account"("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "payment_journalId_fkey" FOREIGN KEY ("journalId") REFERENCES "journal"("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "payment_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "payment_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "payment_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "payment_postedBy_fkey" FOREIGN KEY ("postedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "payment_voidedBy_fkey" FOREIGN KEY ("voidedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE+);++CREATE INDEX "payment_companyId_idx" ON "payment" ("companyId");+CREATE INDEX "payment_customerId_idx" ON "payment" ("customerId") WHERE "customerId" IS NOT NULL;+CREATE INDEX "payment_supplierId_idx" ON "payment" ("supplierId") WHERE "supplierId" IS NOT NULL;+CREATE INDEX "payment_status_idx" ON "payment" ("status");+CREATE INDEX "payment_paymentDate_idx" ON "payment" ("paymentDate");++ALTER TABLE "payment" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "public"."payment"+FOR SELECT USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_role())::text[]+ )+);++CREATE POLICY "INSERT" ON "public"."payment"+FOR INSERT WITH CHECK (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('invoicing_create'))::text[]+ )+);++-- Mutability ties to status: Draft is freely editable, Posted only+-- transitions to Voided (via post-payment edge function), Voided is+-- terminal. App-side service rejects illegal transitions.+CREATE POLICY "UPDATE" ON "public"."payment"+FOR UPDATE USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('invoicing_update'))::text[]+ )+);++-- DELETE allowed only on Draft (Posted payments must be voided).+CREATE POLICY "DELETE" ON "public"."payment"+FOR DELETE USING (+ "status" = 'Draft' AND+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('invoicing_delete'))::text[]+ )+);+++-- ============================================================+-- Phase 5b: memo table (credit / debit memos — payment-shaped)+-- ============================================================+-- A non-cash adjustment to a party's AR/AP balance. Mirrors `payment` but the+-- offset is a GL account instead of a bank account. The offset account is NOT a+-- user choice: it's derived deterministically at posting from the company's+-- account defaults by party side (customer -> salesDiscountAccount, supplier ->+-- supplierPaymentDiscountAccount), and stored on `reasonAccount` for audit. The+-- four combos:+-- Customer + Credit -> AR down (DR reason / CR receivables)+-- Customer + Debit -> AR up (DR receivables / CR reason)+-- Supplier + Debit -> AP down (DR payables / CR reason)+-- Supplier + Credit -> AP up (DR reason / CR payables)+-- Balance-reducing memos (Customer Credit, Supplier Debit) are applied to open+-- invoices via invoiceSettlement (source = memoId). Balance-increasing memos are+-- themselves open items, settled via invoiceSettlement (target = targetMemoId).++CREATE TABLE "memo" (+ "id" TEXT NOT NULL PRIMARY KEY DEFAULT xid(),+ "memoId" TEXT NOT NULL,+ "direction" "memoDirection" NOT NULL,+ "status" "memoStatus" NOT NULL DEFAULT 'Draft',+ "customerId" TEXT,+ "supplierId" TEXT,+ "memoDate" DATE NOT NULL,+ "postingDate" DATE,+ "currencyCode" TEXT NOT NULL,+ "exchangeRate" NUMERIC NOT NULL DEFAULT 1,+ "amount" NUMERIC NOT NULL,+ -- Derived at posting from account defaults (party side); null while Draft.+ "reasonAccount" TEXT,+ "reference" TEXT,+ "notes" TEXT,+ "journalId" TEXT,+ "postedAt" TIMESTAMP WITH TIME ZONE,+ "postedBy" TEXT,+ "voidedAt" TIMESTAMP WITH TIME ZONE,+ "voidedBy" TEXT,+ "companyId" TEXT NOT NULL,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT,+ "updatedAt" TIMESTAMP WITH TIME ZONE,+ "customFields" JSONB,++ CONSTRAINT "memo_party_check" CHECK (+ ("customerId" IS NOT NULL AND "supplierId" IS NULL) OR+ ("customerId" IS NULL AND "supplierId" IS NOT NULL)+ ),+ CONSTRAINT "memo_amount_check" CHECK ("amount" > 0),+ CONSTRAINT "memo_exchangeRate_check" CHECK ("exchangeRate" > 0),+ CONSTRAINT "memo_memoId_companyId_key" UNIQUE ("memoId", "companyId"),++ CONSTRAINT "memo_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "customer"("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "memo_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier"("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "memo_currencyCode_fkey" FOREIGN KEY ("currencyCode") REFERENCES "currencyCode"("code") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "memo_reasonAccount_fkey" FOREIGN KEY ("reasonAccount") REFERENCES "account"("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "memo_journalId_fkey" FOREIGN KEY ("journalId") REFERENCES "journal"("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "memo_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "memo_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "memo_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "memo_postedBy_fkey" FOREIGN KEY ("postedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "memo_voidedBy_fkey" FOREIGN KEY ("voidedBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE+);++CREATE INDEX "memo_companyId_idx" ON "memo" ("companyId");+CREATE INDEX "memo_customerId_idx" ON "memo" ("customerId") WHERE "customerId" IS NOT NULL;+CREATE INDEX "memo_supplierId_idx" ON "memo" ("supplierId") WHERE "supplierId" IS NOT NULL;+CREATE INDEX "memo_status_idx" ON "memo" ("status");+CREATE INDEX "memo_memoDate_idx" ON "memo" ("memoDate");++ALTER TABLE "memo" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "public"."memo"+FOR SELECT USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])+);++CREATE POLICY "INSERT" ON "public"."memo"+FOR INSERT WITH CHECK (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('invoicing_create'))::text[])+);++CREATE POLICY "UPDATE" ON "public"."memo"+FOR UPDATE USING (+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('invoicing_update'))::text[])+);++-- DELETE allowed only on Draft (Posted memos must be voided).+CREATE POLICY "DELETE" ON "public"."memo"+FOR DELETE USING (+ "status" = 'Draft' AND+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('invoicing_delete'))::text[])+);+++-- ============================================================+-- Phase 6: invoiceSettlement table (unified settlement primitive)+-- ============================================================+-- ONE table nets a funding SOURCE against a TARGET document:+-- * source = exactly one of:+-- - paymentId (a cash receipt/disbursement), or+-- - memoId (a credit/debit memo).+-- * target = exactly one of targetSalesInvoiceId / targetPurchaseInvoiceId /+-- targetMemoId (the open item being settled — an invoice, or a+-- balance-increasing memo being paid/credited down).+--+-- Carries principal/discount/write-off in the source/target currency.+-- fxGainLoss is a stored generated column on the settled principal+-- (appliedAmount): discount/write-off are invoice-currency reliefs that carry+-- no FX, and only cash payments carry them (memos do not).+--+-- Party/side consistency (an AR source only settles AR targets, same+-- counterparty) is enforced by the posting/apply functions — the source's+-- AR/AP side lives in the payment/memo row, not structurally here.++CREATE TABLE "invoiceSettlement" (+ "id" TEXT NOT NULL PRIMARY KEY DEFAULT xid(),+ -- funding source (exactly one): a cash payment OR a memo+ "paymentId" TEXT,+ "memoId" TEXT,+ -- target document (exactly one): an invoice, or a memo (settling / refunding+ -- a balance-increasing memo)+ "targetSalesInvoiceId" TEXT,+ "targetPurchaseInvoiceId" TEXT,+ "targetMemoId" TEXT,+ "appliedAmount" NUMERIC NOT NULL,+ "discountAmount" NUMERIC NOT NULL DEFAULT 0,+ "writeOffAmount" NUMERIC NOT NULL DEFAULT 0,+ -- rate of the funding source and of the target invoice at application time+ "sourceExchangeRate" NUMERIC NOT NULL,+ "targetExchangeRate" NUMERIC NOT NULL,+ -- Realized FX on this settlement, in base currency. FX accrues only on the+ -- settled principal (appliedAmount): discount and write-off are+ -- invoice-currency reliefs booked at the target rate and carry no FX. Bare+ -- NUMERIC keeps this exact so it reconciles to the GL FX plug with no+ -- fixed-scale rounding drift. Presentation rounds at the edge, not in storage.+ "fxGainLossAmount" NUMERIC GENERATED ALWAYS AS (+ "appliedAmount" * ("sourceExchangeRate" - "targetExchangeRate")+ ) STORED,+ "appliedDate" DATE NOT NULL,+ "companyId" TEXT NOT NULL,+ "createdBy" TEXT NOT NULL,+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),++ CONSTRAINT "invoiceSettlement_source_check" CHECK (+ (("paymentId" IS NOT NULL)::int + ("memoId" IS NOT NULL)::int) = 1+ ),+ CONSTRAINT "invoiceSettlement_target_check" CHECK (+ (("targetSalesInvoiceId" IS NOT NULL)::int+ + ("targetPurchaseInvoiceId" IS NOT NULL)::int+ + ("targetMemoId" IS NOT NULL)::int) = 1+ ),+ -- A memo cannot settle itself. (Party/side consistency between the source's+ -- AR/AP side and the target — e.g. an AR memo can only settle an AR invoice or+ -- AR memo — is enforced by the posting/apply functions, since the memo's party+ -- lives in the `memo` table and isn't structurally visible here.)+ CONSTRAINT "invoiceSettlement_self_check" CHECK (+ NOT ("memoId" IS NOT NULL AND "memoId" = "targetMemoId")+ ),+ -- Discount/write-off are cash-payment reliefs; memo sources carry neither.+ CONSTRAINT "invoiceSettlement_memoSource_noReliefs_check" CHECK (+ "paymentId" IS NOT NULL OR ("discountAmount" = 0 AND "writeOffAmount" = 0)+ ),+ CONSTRAINT "invoiceSettlement_amounts_nonnegative" CHECK (+ "appliedAmount" >= 0 AND "discountAmount" >= 0 AND "writeOffAmount" >= 0+ ),+ CONSTRAINT "invoiceSettlement_anyComponent_check" CHECK (+ "appliedAmount" + "discountAmount" + "writeOffAmount" > 0+ ),+ CONSTRAINT "invoiceSettlement_sourceExchangeRate_check" CHECK ("sourceExchangeRate" > 0),+ CONSTRAINT "invoiceSettlement_targetExchangeRate_check" CHECK ("targetExchangeRate" > 0),++ CONSTRAINT "invoiceSettlement_paymentId_fkey" FOREIGN KEY ("paymentId") REFERENCES "payment"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "invoiceSettlement_memoId_fkey" FOREIGN KEY ("memoId") REFERENCES "memo"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "invoiceSettlement_targetSalesInvoiceId_fkey" FOREIGN KEY ("targetSalesInvoiceId") REFERENCES "salesInvoice"("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "invoiceSettlement_targetPurchaseInvoiceId_fkey" FOREIGN KEY ("targetPurchaseInvoiceId") REFERENCES "purchaseInvoice"("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "invoiceSettlement_targetMemoId_fkey" FOREIGN KEY ("targetMemoId") REFERENCES "memo"("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "invoiceSettlement_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "invoiceSettlement_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE+);++CREATE INDEX "invoiceSettlement_paymentId_idx" ON "invoiceSettlement" ("paymentId") WHERE "paymentId" IS NOT NULL;+CREATE INDEX "invoiceSettlement_memoId_idx" ON "invoiceSettlement" ("memoId") WHERE "memoId" IS NOT NULL;+CREATE INDEX "invoiceSettlement_targetSalesInvoiceId_idx" ON "invoiceSettlement" ("targetSalesInvoiceId") WHERE "targetSalesInvoiceId" IS NOT NULL;+CREATE INDEX "invoiceSettlement_targetPurchaseInvoiceId_idx" ON "invoiceSettlement" ("targetPurchaseInvoiceId") WHERE "targetPurchaseInvoiceId" IS NOT NULL;+CREATE INDEX "invoiceSettlement_targetMemoId_idx" ON "invoiceSettlement" ("targetMemoId") WHERE "targetMemoId" IS NOT NULL;+CREATE INDEX "invoiceSettlement_appliedDate_idx" ON "invoiceSettlement" ("appliedDate");+CREATE INDEX "invoiceSettlement_companyId_idx" ON "invoiceSettlement" ("companyId");++ALTER TABLE "invoiceSettlement" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "public"."invoiceSettlement"+FOR SELECT USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_role())::text[]+ )+);++-- Settlement rows are staged while their parent source (payment OR memo) is+-- Draft; the post-payment / post-memo edge function then posts them. Exactly one+-- of paymentId/memoId is set, so the other gate is a NULL no-op.+CREATE POLICY "INSERT" ON "public"."invoiceSettlement"+FOR INSERT WITH CHECK (+ ("paymentId" IS NULL OR EXISTS (+ SELECT 1 FROM "payment" p WHERE p.id = "paymentId" AND p.status = 'Draft'+ )) AND+ ("memoId" IS NULL OR EXISTS (+ SELECT 1 FROM "memo" m WHERE m.id = "memoId" AND m.status = 'Draft'+ )) AND+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('invoicing_create'))::text[]+ )+);++CREATE POLICY "UPDATE" ON "public"."invoiceSettlement"+FOR UPDATE USING (+ ("paymentId" IS NULL OR EXISTS (+ SELECT 1 FROM "payment" p WHERE p.id = "paymentId" AND p.status = 'Draft'+ )) AND+ ("memoId" IS NULL OR EXISTS (+ SELECT 1 FROM "memo" m WHERE m.id = "memoId" AND m.status = 'Draft'+ )) AND+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('invoicing_update'))::text[]+ )+);++CREATE POLICY "DELETE" ON "public"."invoiceSettlement"+FOR DELETE USING (+ ("paymentId" IS NULL OR EXISTS (+ SELECT 1 FROM "payment" p WHERE p.id = "paymentId" AND p.status = 'Draft'+ )) AND+ ("memoId" IS NULL OR EXISTS (+ SELECT 1 FROM "memo" m WHERE m.id = "memoId" AND m.status = 'Draft'+ )) AND+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('invoicing_delete'))::text[]+ )+);+++-- ============================================================+-- Phase 7: Custom field registry+-- ============================================================++INSERT INTO "customFieldTable" ("table", "name", "module") VALUES+ ('payment', 'Payment', 'Invoicing'),+ ('memo', 'Memo', 'Invoicing'),+ ('invoiceSettlement', 'Invoice Settlement', 'Invoicing')+ON CONFLICT ("table") DO NOTHING;+++-- ============================================================+-- Phase 8: Seed payment sequence for existing companies+-- ============================================================+-- New companies pick this up via seed-company/index.ts; this clause+-- handles companies that already exist.++INSERT INTO "sequence" ("table", "name", "prefix", "suffix", "next", "size", "step", "companyId")+SELECT 'payment', 'Payment', 'PAY-%{yyyy}-%{mm}-', NULL, 0, 6, 1, c.id+FROM "company" c+ON CONFLICT DO NOTHING;++-- Credit/debit memos number independently; the insert path picks the sequence+-- by direction (Credit -> CR-, Debit -> DR-).+INSERT INTO "sequence" ("table", "name", "prefix", "suffix", "next", "size", "step", "companyId")+SELECT 'creditMemo', 'Credit Memo', 'CR-%{yyyy}-%{mm}-', NULL, 0, 6, 1, c.id+FROM "company" c+ON CONFLICT DO NOTHING;++INSERT INTO "sequence" ("table", "name", "prefix", "suffix", "next", "size", "step", "companyId")+SELECT 'debitMemo', 'Debit Memo', 'DR-%{yyyy}-%{mm}-', NULL, 0, 6, 1, c.id+FROM "company" c+ON CONFLICT DO NOTHING;diff --git a/packages/database/supabase/migrations/20260630095023_invoice-derived-status.sql b/packages/database/supabase/migrations/20260630095023_invoice-derived-status.sqlnew file mode 100644index 0000000000..e62cb3b11e--- /dev/null+++ b/packages/database/supabase/migrations/20260630095023_invoice-derived-status.sql@@ -0,0 +1,236 @@+-- ============================================================+-- Invoice status + balance derived from invoiceSettlement+--+-- Today `balance` is a cached NUMERIC column on salesInvoice and+-- purchaseInvoice that is never decremented by anything, and the+-- `Paid` / `Partially Paid` status values are set by hand via+-- updateSalesInvoiceStatus / updatePurchaseInvoiceStatus. The+-- payment + invoiceSettlement tables now make this derivable: a+-- Posted payment's applications sum exactly equals the AR/AP+-- reduction. This migration drops the cached column and recomputes+-- balance + status in the views.+--+-- This forks the view bodies from 20260604120000 (which moved+-- subtotal/totalTax/totalAmount onto live, line-derived computation)+-- and changes only two columns per view: `balance` and `status`.+-- Everything else (the computed totals, thumbnailPath, lines, etc.)+-- is preserved verbatim from that migration.+--+-- Balance/status key off the STORED `totalAmount` (the amount actually+-- invoiced to the counterparty), NOT the live computed display total,+-- so the open balance reconciles with the AR/AP tie-out RPCs (which+-- also use stored totalAmount) and with the apply table.+--+-- Precedence in the status CASE (Paid > Overdue): a paid invoice can+-- never be overdue.+-- ============================================================+++-- ============================================================+-- Phase 1: Drop the existing views (they project `balance` from the+-- base table, so the column can't be dropped while they exist)+-- ============================================================++DROP VIEW IF EXISTS "salesInvoices";+DROP VIEW IF EXISTS "purchaseInvoices";+++-- ============================================================+-- Phase 2: Drop the cached `balance` column from the base tables+-- ============================================================+-- The views were the only consumers in apps/erp; they're recreated+-- below with a derived balance. The convert edge function and the+-- packages/ee Xero sync providers (bill.ts / invoice.ts) also touched+-- the base column directly and were updated alongside this migration+-- to insert without it / read it from the views.++ALTER TABLE "salesInvoice" DROP COLUMN IF EXISTS "balance";+ALTER TABLE "purchaseInvoice" DROP COLUMN IF EXISTS "balance";+++-- ============================================================+-- Phase 3: Recreate salesInvoices with derived balance + status+-- (computed subtotal/totalTax/totalAmount preserved from 20260604120000)+-- ============================================================+-- Active state for sales invoices is 'Submitted'.++CREATE OR REPLACE VIEW "salesInvoices" WITH(SECURITY_INVOKER=true) AS+ WITH settled AS (+ SELECT+ pa."targetSalesInvoiceId",+ SUM(pa."appliedAmount" + pa."discountAmount" + pa."writeOffAmount") AS amount+ FROM "invoiceSettlement" pa+ JOIN "payment" p ON p."id" = pa."paymentId"+ WHERE p."status" = 'Posted' AND pa."targetSalesInvoiceId" IS NOT NULL+ GROUP BY pa."targetSalesInvoiceId"+ )+ SELECT+ si."id",+ si."invoiceId",+ CASE+ WHEN si."status" IN ('Draft','Pending','Voided','Return','Credit Note Issued') THEN si."status"::TEXT+ WHEN COALESCE(s.amount, 0) >= si."totalAmount" AND si."totalAmount" > 0 THEN 'Paid'+ WHEN COALESCE(s.amount, 0) > 0 THEN 'Partially Paid'+ WHEN si."dateDue" < CURRENT_DATE AND si."status" = 'Submitted' THEN 'Overdue'+ ELSE si."status"::TEXT+ END AS status,+ si."customerId",+ si."customerReference",+ si."invoiceCustomerId",+ si."invoiceCustomerLocationId",+ si."invoiceCustomerContactId",+ si."paymentTermId",+ si."postingDate",+ si."dateIssued",+ si."dateDue",+ si."datePaid",+ si."locationId",+ si."currencyCode",+ COALESCE(sil."subtotal", 0) AS "subtotal",+ si."totalDiscount",+ COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0) AS "totalAmount",+ COALESCE(sil."totalTax", 0) AS "totalTax",+ (si."totalAmount" - COALESCE(s.amount, 0)) AS "balance",+ si."exchangeRate",+ si."exchangeRateUpdatedAt",+ si."opportunityId",+ si."shipmentId",+ si."assignee",+ si."companyId",+ si."customFields",+ si."internalNotes",+ si."externalNotes",+ si."tags",+ si."createdAt",+ si."createdBy",+ si."updatedAt",+ si."updatedBy",+ sil."thumbnailPath",+ sil."itemType",+ COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0) AS "invoiceTotal",+ sil."lines"+ FROM "salesInvoice" si+ LEFT JOIN (+ SELECT+ sil."invoiceId",+ MIN(CASE+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"+ ELSE i."thumbnailPath"+ END) AS "thumbnailPath",+ SUM(+ COALESCE(sil."quantity", 0)*COALESCE(sil."unitPrice", 0)+ + COALESCE(sil."addOnCost", 0)+ + COALESCE(sil."nonTaxableAddOnCost", 0)+ + COALESCE(sil."shippingCost", 0)+ ) AS "subtotal",+ SUM(+ COALESCE(sil."taxPercent", 0) * (+ COALESCE(sil."quantity", 0)*COALESCE(sil."unitPrice", 0)+ + COALESCE(sil."addOnCost", 0)+ + COALESCE(sil."shippingCost", 0)+ )+ ) AS "totalTax",+ MIN(i."type") AS "itemType",+ ARRAY_AGG(+ json_build_object(+ 'id', sil.id,+ 'invoiceLineType', sil."invoiceLineType",+ 'quantity', sil."quantity",+ 'unitPrice', sil."unitPrice",+ 'itemId', sil."itemId"+ )+ ) AS "lines"+ FROM "salesInvoiceLine" sil+ LEFT JOIN "item" i+ ON i."id" = sil."itemId"+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"+ GROUP BY sil."invoiceId"+ ) sil ON sil."invoiceId" = si."id"+ JOIN "salesInvoiceShipment" ss ON ss."id" = si."id"+ LEFT JOIN settled s ON s."targetSalesInvoiceId" = si."id";+++-- ============================================================+-- Phase 4: Recreate purchaseInvoices with derived balance + status+-- (computed subtotal/totalTax/totalAmount preserved from 20260604120000)+-- ============================================================+-- Active state for purchase invoices is 'Open' (renamed from+-- 'Submitted' in 20260422004200).++CREATE OR REPLACE VIEW "purchaseInvoices" WITH(SECURITY_INVOKER=true) AS+ WITH settled AS (+ SELECT+ pa."targetPurchaseInvoiceId",+ SUM(pa."appliedAmount" + pa."discountAmount" + pa."writeOffAmount") AS amount+ FROM "invoiceSettlement" pa+ JOIN "payment" p ON p."id" = pa."paymentId"+ WHERE p."status" = 'Posted' AND pa."targetPurchaseInvoiceId" IS NOT NULL+ GROUP BY pa."targetPurchaseInvoiceId"+ )+ SELECT+ pi."id",+ pi."invoiceId",+ pi."supplierId",+ pi."invoiceSupplierId",+ pi."supplierInteractionId",+ pi."supplierReference",+ pi."invoiceSupplierContactId",+ pi."invoiceSupplierLocationId",+ pi."locationId",+ pi."postingDate",+ pi."dateIssued",+ pi."dateDue",+ pi."datePaid",+ pi."paymentTermId",+ pi."currencyCode",+ pi."exchangeRate",+ pi."exchangeRateUpdatedAt",+ COALESCE(pl."subtotal", 0) AS "subtotal",+ pi."totalDiscount",+ (COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) * CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) AS "totalAmount",+ COALESCE(pl."totalTax", 0) AS "totalTax",+ (pi."totalAmount" - COALESCE(s.amount, 0)) AS "balance",+ pi."assignee",+ pi."createdBy",+ pi."createdAt",+ pi."updatedBy",+ pi."updatedAt",+ pi."internalNotes",+ pi."customFields",+ pi."companyId",+ pl."thumbnailPath",+ pl."itemType",+ COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) * CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END AS "orderTotal",+ CASE+ WHEN pi."status" IN ('Draft','Pending','Voided','Return','Debit Note Issued') THEN pi."status"::TEXT+ WHEN COALESCE(s.amount, 0) >= pi."totalAmount" AND pi."totalAmount" > 0 THEN 'Paid'+ WHEN COALESCE(s.amount, 0) > 0 THEN 'Partially Paid'+ WHEN pi."dateDue" < CURRENT_DATE AND pi."status" = 'Open' THEN 'Overdue'+ ELSE pi."status"::TEXT+ END AS status,+ pt."name" AS "paymentTermName"+ FROM "purchaseInvoice" pi+ LEFT JOIN (+ SELECT+ pol."invoiceId",+ MIN(CASE+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"+ ELSE i."thumbnailPath"+ END) AS "thumbnailPath",+ SUM(+ COALESCE(pol."quantity", 0)*COALESCE(pol."unitPrice", 0) + COALESCE(pol."shippingCost", 0)+ ) AS "subtotal",+ SUM(COALESCE(pol."taxAmount", 0)) AS "totalTax",+ SUM(+ COALESCE(pol."quantity", 0)*COALESCE(pol."unitPrice", 0) + COALESCE(pol."shippingCost", 0) + COALESCE(pol."taxAmount", 0)+ ) AS "orderTotal",+ MIN(i."type") AS "itemType"+ FROM "purchaseInvoiceLine" pol+ LEFT JOIN "item" i+ ON i."id" = pol."itemId"+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"+ GROUP BY pol."invoiceId"+ ) pl ON pl."invoiceId" = pi."id"+ LEFT JOIN "paymentTerm" pt ON pt."id" = pi."paymentTermId"+ LEFT JOIN "purchaseInvoiceDelivery" pid ON pid."id" = pi."id"+ LEFT JOIN settled s ON s."targetPurchaseInvoiceId" = pi."id";diff --git a/packages/database/supabase/migrations/20260630100241_ar-ap-tie-out.sql b/packages/database/supabase/migrations/20260630100241_ar-ap-tie-out.sqlnew file mode 100644index 0000000000..a59edc9e84--- /dev/null+++ b/packages/database/supabase/migrations/20260630100241_ar-ap-tie-out.sql@@ -0,0 +1,295 @@+-- ============================================================+-- AR & AP subledger-to-GL tie-out RPCs+--+-- The subledger (payment + invoiceSettlement + invoice) must+-- equal the GL control account balance for the same as-of date.+-- These RPCs return that comparison.+--+-- Subledger calculation (base currency):+-- SUM((invoice.totalAmount - settled) * invoice.exchangeRate)+-- where settled = sum of applied + discount + writeOff+-- across Posted-payment applications dated <= as_of+-- - SUM(payment unapplied * payment.exchangeRate)+-- where unapplied = totalAmount - sum of applications applied+-- across Posted payments dated <= as_of+--+-- GL calculation:+-- SUM(journalLine.amount) over the control account+-- (receivablesAccount for AR, payablesAccount for AP)+-- where journal.postingDate <= as_of+--+-- Both should equal in base currency. A non-zero variance+-- indicates a break — manual journal entry, voided payment with+-- stale applications, or a posting bug.+-- ============================================================+++-- ============================================================+-- AR tie-out+-- ============================================================++CREATE OR REPLACE FUNCTION get_ar_tie_out(+ _company_id TEXT,+ _as_of_date DATE+)+RETURNS TABLE (+ "subledgerBalance" NUMERIC,+ "glBalance" NUMERIC,+ "variance" NUMERIC+)+LANGUAGE SQL+SECURITY INVOKER+AS $$+ WITH+ -- Active invoices' open amount in invoice currency.+ invoice_open AS (+ SELECT+ si."id",+ si."totalAmount",+ si."exchangeRate",+ si."totalAmount" - COALESCE((+ SELECT SUM(pa."appliedAmount" + pa."discountAmount" + pa."writeOffAmount")+ FROM "invoiceSettlement" pa+ JOIN "payment" p ON p."id" = pa."paymentId"+ WHERE pa."targetSalesInvoiceId" = si."id"+ AND p."status" = 'Posted'+ -- Cut on the payment's posting date (= the journal postingDate+ -- the GL side uses), NOT the free-form appliedDate, so the+ -- subledger and GL reconcile as of the same clock.+ AND p."postingDate" <= _as_of_date+ ), 0) AS open_inv_ccy+ FROM "salesInvoice" si+ WHERE si."companyId" = _company_id+ AND si."postingDate" <= _as_of_date+ AND si."status" NOT IN ('Draft', 'Pending', 'Voided')+ ),+ -- Unapplied portion of Posted Receipts, in payment currency.+ payment_unapplied AS (+ SELECT+ p."id",+ p."totalAmount",+ p."exchangeRate",+ p."totalAmount" - COALESCE((+ SELECT SUM(pa."appliedAmount")+ FROM "invoiceSettlement" pa+ WHERE pa."paymentId" = p."id"+ ), 0) AS unapplied_pay_ccy+ FROM "payment" p+ WHERE p."companyId" = _company_id+ AND p."paymentType" = 'Receipt'+ AND p."status" = 'Posted'+ AND p."postingDate" <= _as_of_date+ ),+ subledger AS (+ SELECT+ COALESCE(SUM(open_inv_ccy * "exchangeRate"), 0)+ -+ COALESCE((SELECT SUM(unapplied_pay_ccy * "exchangeRate") FROM payment_unapplied), 0)+ AS amount+ FROM invoice_open+ ),+ ar_account AS (+ SELECT "receivablesAccount" AS account_id+ FROM "accountDefault"+ WHERE "companyId" = _company_id+ ),+ gl AS (+ SELECT COALESCE(SUM(jl."amount"), 0) AS amount+ FROM "journalLine" jl+ JOIN "journal" j ON j."id" = jl."journalId"+ JOIN ar_account a ON jl."accountId" = a.account_id+ WHERE jl."companyId" = _company_id+ AND j."postingDate" <= _as_of_date+ AND j."status" = 'Posted'+ )+ SELECT+ subledger.amount AS "subledgerBalance",+ gl.amount AS "glBalance",+ subledger.amount - gl.amount AS "variance"+ FROM subledger, gl;+$$;+++-- ============================================================+-- AP tie-out (mirror of AR)+-- ============================================================+-- Active state for purchase invoices is 'Open'.++CREATE OR REPLACE FUNCTION get_ap_tie_out(+ _company_id TEXT,+ _as_of_date DATE+)+RETURNS TABLE (+ "subledgerBalance" NUMERIC,+ "glBalance" NUMERIC,+ "variance" NUMERIC+)+LANGUAGE SQL+SECURITY INVOKER+AS $$+ WITH+ invoice_open AS (+ SELECT+ pi."id",+ pi."totalAmount",+ pi."exchangeRate",+ pi."totalAmount" - COALESCE((+ SELECT SUM(pa."appliedAmount" + pa."discountAmount" + pa."writeOffAmount")+ FROM "invoiceSettlement" pa+ JOIN "payment" p ON p."id" = pa."paymentId"+ WHERE pa."targetPurchaseInvoiceId" = pi."id"+ AND p."status" = 'Posted'+ -- See AR note: reconcile on payment.postingDate, not appliedDate.+ AND p."postingDate" <= _as_of_date+ ), 0) AS open_inv_ccy+ FROM "purchaseInvoice" pi+ WHERE pi."companyId" = _company_id+ AND pi."postingDate" <= _as_of_date+ AND pi."status" NOT IN ('Draft', 'Pending', 'Voided')+ ),+ payment_unapplied AS (+ SELECT+ p."id",+ p."totalAmount",+ p."exchangeRate",+ p."totalAmount" - COALESCE((+ SELECT SUM(pa."appliedAmount")+ FROM "invoiceSettlement" pa+ WHERE pa."paymentId" = p."id"+ ), 0) AS unapplied_pay_ccy+ FROM "payment" p+ WHERE p."companyId" = _company_id+ AND p."paymentType" = 'Disbursement'+ AND p."status" = 'Posted'+ AND p."postingDate" <= _as_of_date+ ),+ subledger AS (+ SELECT+ COALESCE(SUM(open_inv_ccy * "exchangeRate"), 0)+ -+ COALESCE((SELECT SUM(unapplied_pay_ccy * "exchangeRate") FROM payment_unapplied), 0)+ AS amount+ FROM invoice_open+ ),+ ap_account AS (+ SELECT "payablesAccount" AS account_id+ FROM "accountDefault"+ WHERE "companyId" = _company_id+ ),+ gl AS (+ SELECT COALESCE(SUM(jl."amount"), 0) AS amount+ FROM "journalLine" jl+ JOIN "journal" j ON j."id" = jl."journalId"+ JOIN ap_account a ON jl."accountId" = a.account_id+ WHERE jl."companyId" = _company_id+ AND j."postingDate" <= _as_of_date+ AND j."status" = 'Posted'+ )+ SELECT+ subledger.amount AS "subledgerBalance",+ gl.amount AS "glBalance",+ subledger.amount - gl.amount AS "variance"+ FROM subledger, gl;+$$;+++-- ============================================================+-- Drill-down: open AR invoices per customer (as-of date)+-- ============================================================++CREATE OR REPLACE FUNCTION get_ar_open_by_customer(+ _company_id TEXT,+ _as_of_date DATE+)+RETURNS TABLE (+ "customerId" TEXT,+ "invoiceId" TEXT,+ "invoiceNumber" TEXT,+ "dateDue" DATE,+ "currencyCode" TEXT,+ "exchangeRate" NUMERIC,+ "totalAmount" NUMERIC,+ "settled" NUMERIC,+ "openInCurrency" NUMERIC,+ "openInBase" NUMERIC+)+LANGUAGE SQL+SECURITY INVOKER+AS $$+ SELECT+ si."customerId",+ si."id" AS "invoiceId",+ si."invoiceId" AS "invoiceNumber",+ si."dateDue",+ si."currencyCode",+ si."exchangeRate",+ si."totalAmount",+ COALESCE(s.settled, 0) AS "settled",+ (si."totalAmount" - COALESCE(s.settled, 0)) AS "openInCurrency",+ (si."totalAmount" - COALESCE(s.settled, 0)) * si."exchangeRate" AS "openInBase"+ FROM "salesInvoice" si+ LEFT JOIN LATERAL (+ SELECT SUM(pa."appliedAmount" + pa."discountAmount" + pa."writeOffAmount") AS settled+ FROM "invoiceSettlement" pa+ JOIN "payment" p ON p."id" = pa."paymentId"+ WHERE pa."targetSalesInvoiceId" = si."id"+ AND p."status" = 'Posted'+ AND p."postingDate" <= _as_of_date+ ) s ON true+ WHERE si."companyId" = _company_id+ AND si."postingDate" <= _as_of_date+ AND si."status" NOT IN ('Draft', 'Pending', 'Voided')+ AND (si."totalAmount" - COALESCE(s.settled, 0)) <> 0+ ORDER BY si."customerId", si."dateDue" NULLS LAST;+$$;+++-- ============================================================+-- Drill-down: open AP invoices per supplier (as-of date)+-- ============================================================++CREATE OR REPLACE FUNCTION get_ap_open_by_supplier(+ _company_id TEXT,+ _as_of_date DATE+)+RETURNS TABLE (+ "supplierId" TEXT,+ "invoiceId" TEXT,+ "invoiceNumber" TEXT,+ "dateDue" DATE,+ "currencyCode" TEXT,+ "exchangeRate" NUMERIC,+ "totalAmount" NUMERIC,+ "settled" NUMERIC,+ "openInCurrency" NUMERIC,+ "openInBase" NUMERIC+)+LANGUAGE SQL+SECURITY INVOKER+AS $$+ SELECT+ pi."supplierId",+ pi."id" AS "invoiceId",+ pi."invoiceId" AS "invoiceNumber",+ pi."dateDue",+ pi."currencyCode",+ pi."exchangeRate",+ pi."totalAmount",+ COALESCE(s.settled, 0) AS "settled",+ (pi."totalAmount" - COALESCE(s.settled, 0)) AS "openInCurrency",+ (pi."totalAmount" - COALESCE(s.settled, 0)) * pi."exchangeRate" AS "openInBase"+ FROM "purchaseInvoice" pi+ LEFT JOIN LATERAL (+ SELECT SUM(pa."appliedAmount" + pa."discountAmount" + pa."writeOffAmount") AS settled+ FROM "invoiceSettlement" pa+ JOIN "payment" p ON p."id" = pa."paymentId"+ WHERE pa."targetPurchaseInvoiceId" = pi."id"+ AND p."status" = 'Posted'+ AND p."postingDate" <= _as_of_date+ ) s ON true+ WHERE pi."companyId" = _company_id+ AND pi."postingDate" <= _as_of_date+ AND pi."status" NOT IN ('Draft', 'Pending', 'Voided')+ AND (pi."totalAmount" - COALESCE(s.settled, 0)) <> 0+ ORDER BY pi."supplierId", pi."dateDue" NULLS LAST;+$$;diff --git a/packages/database/supabase/migrations/20260630101458_ar-ap-aging.sql b/packages/database/supabase/migrations/20260630101458_ar-ap-aging.sqlnew file mode 100644index 0000000000..b02a393933--- /dev/null+++ b/packages/database/supabase/migrations/20260630101458_ar-ap-aging.sql@@ -0,0 +1,253 @@+-- ============================================================+-- AR & AP aging reports+--+-- Per-counterparty bucketed open amounts derived from the same+-- invoiceSettlement subledger the tie-out uses. Buckets and the+-- age basis (due date vs document date) are parameters so the UI+-- can offer the standard NetSuite/SAP toggles without a schema+-- change.+--+-- Open amount per invoice (base currency) =+-- (totalAmount - settled) * exchangeRate+-- where settled = applied + discount + writeOff across Posted-payment+-- applications dated <= as_of.+--+-- Unapplied Posted payments (on-account credits) are included as a+-- negative amount per counterparty so an overpaid customer shows as+-- a net credit rather than a phantom receivable.+-- ============================================================+++-- ============================================================+-- AR aging+-- ============================================================++DROP FUNCTION IF EXISTS get_ar_aging(TEXT, DATE, TEXT, INTEGER, INTEGER, INTEGER);++CREATE OR REPLACE FUNCTION get_ar_aging(+ _company_id TEXT,+ _as_of_date DATE,+ _aging_method TEXT DEFAULT 'dueDate',+ _bucket1 INTEGER DEFAULT 30,+ _bucket2 INTEGER DEFAULT 60,+ _bucket3 INTEGER DEFAULT 90+)+RETURNS TABLE (+ "customerId" TEXT,+ "paymentTerm" TEXT,+ "current" NUMERIC,+ "bucket1" NUMERIC,+ "bucket2" NUMERIC,+ "bucket3" NUMERIC,+ "bucket4" NUMERIC,+ "unapplied" NUMERIC,+ "total" NUMERIC+)+LANGUAGE SQL+SECURITY INVOKER+AS $$+ WITH open_invoices AS (+ SELECT+ si."customerId",+ CASE+ WHEN _aging_method = 'documentDate'+ THEN COALESCE(si."dateIssued", si."postingDate")+ ELSE si."dateDue"+ END AS age_date,+ (si."totalAmount" - COALESCE((+ SELECT SUM(pa."appliedAmount" + pa."discountAmount" + pa."writeOffAmount")+ FROM "invoiceSettlement" pa+ JOIN "payment" p ON p."id" = pa."paymentId"+ WHERE pa."targetSalesInvoiceId" = si."id"+ AND p."status" = 'Posted'+ -- Reconcile on payment.postingDate (matches the tie-out report),+ -- not the free-form appliedDate.+ AND p."postingDate" <= _as_of_date+ ), 0)) * si."exchangeRate" AS open_base+ FROM "salesInvoice" si+ WHERE si."companyId" = _company_id+ AND si."postingDate" <= _as_of_date+ AND si."status" NOT IN ('Draft', 'Pending', 'Voided')+ ),+ invoice_buckets AS (+ SELECT+ "customerId",+ COALESCE(SUM(open_base) FILTER (+ WHERE age_date IS NULL OR age_date >= _as_of_date+ ), 0) AS "current",+ COALESCE(SUM(open_base) FILTER (+ WHERE age_date < _as_of_date+ AND _as_of_date - age_date BETWEEN 1 AND _bucket1+ ), 0) AS "bucket1",+ COALESCE(SUM(open_base) FILTER (+ WHERE _as_of_date - age_date BETWEEN _bucket1 + 1 AND _bucket2+ ), 0) AS "bucket2",+ COALESCE(SUM(open_base) FILTER (+ WHERE _as_of_date - age_date BETWEEN _bucket2 + 1 AND _bucket3+ ), 0) AS "bucket3",+ COALESCE(SUM(open_base) FILTER (+ WHERE _as_of_date - age_date > _bucket3+ ), 0) AS "bucket4"+ FROM open_invoices+ WHERE open_base <> 0+ GROUP BY "customerId"+ ),+ unapplied AS (+ SELECT+ p."customerId",+ -COALESCE(SUM(+ (p."totalAmount" - COALESCE((+ SELECT SUM(pa."appliedAmount")+ FROM "invoiceSettlement" pa+ WHERE pa."paymentId" = p."id"+ ), 0)) * p."exchangeRate"+ ), 0) AS "unapplied"+ FROM "payment" p+ WHERE p."companyId" = _company_id+ AND p."paymentType" = 'Receipt'+ AND p."status" = 'Posted'+ AND p."postingDate" <= _as_of_date+ AND p."customerId" IS NOT NULL+ GROUP BY p."customerId"+ )+ SELECT+ COALESCE(ib."customerId", u."customerId") AS "customerId",+ pt."name" AS "paymentTerm",+ COALESCE(ib."current", 0) AS "current",+ COALESCE(ib."bucket1", 0) AS "bucket1",+ COALESCE(ib."bucket2", 0) AS "bucket2",+ COALESCE(ib."bucket3", 0) AS "bucket3",+ COALESCE(ib."bucket4", 0) AS "bucket4",+ COALESCE(u."unapplied", 0) AS "unapplied",+ COALESCE(ib."current", 0) + COALESCE(ib."bucket1", 0)+ + COALESCE(ib."bucket2", 0) + COALESCE(ib."bucket3", 0)+ + COALESCE(ib."bucket4", 0) + COALESCE(u."unapplied", 0) AS "total"+ FROM invoice_buckets ib+ FULL OUTER JOIN unapplied u ON u."customerId" = ib."customerId"+ LEFT JOIN "customerPayment" cp+ ON cp."customerId" = COALESCE(ib."customerId", u."customerId")+ AND cp."companyId" = _company_id+ LEFT JOIN "paymentTerm" pt ON pt."id" = cp."paymentTermId"+ WHERE+ COALESCE(ib."current", 0) + COALESCE(ib."bucket1", 0)+ + COALESCE(ib."bucket2", 0) + COALESCE(ib."bucket3", 0)+ + COALESCE(ib."bucket4", 0) + COALESCE(u."unapplied", 0) <> 0+ ORDER BY "total" DESC;+$$;+++-- ============================================================+-- AP aging (mirror — supplier + purchaseInvoice + Disbursement)+-- ============================================================++DROP FUNCTION IF EXISTS get_ap_aging(TEXT, DATE, TEXT, INTEGER, INTEGER, INTEGER);++CREATE OR REPLACE FUNCTION get_ap_aging(+ _company_id TEXT,+ _as_of_date DATE,+ _aging_method TEXT DEFAULT 'dueDate',+ _bucket1 INTEGER DEFAULT 30,+ _bucket2 INTEGER DEFAULT 60,+ _bucket3 INTEGER DEFAULT 90+)+RETURNS TABLE (+ "supplierId" TEXT,+ "paymentTerm" TEXT,+ "current" NUMERIC,+ "bucket1" NUMERIC,+ "bucket2" NUMERIC,+ "bucket3" NUMERIC,+ "bucket4" NUMERIC,+ "unapplied" NUMERIC,+ "total" NUMERIC+)+LANGUAGE SQL+SECURITY INVOKER+AS $$+ WITH open_invoices AS (+ SELECT+ pi."supplierId",+ CASE+ WHEN _aging_method = 'documentDate'+ THEN COALESCE(pi."dateIssued", pi."postingDate")+ ELSE pi."dateDue"+ END AS age_date,+ (pi."totalAmount" - COALESCE((+ SELECT SUM(pa."appliedAmount" + pa."discountAmount" + pa."writeOffAmount")+ FROM "invoiceSettlement" pa+ JOIN "payment" p ON p."id" = pa."paymentId"+ WHERE pa."targetPurchaseInvoiceId" = pi."id"+ AND p."status" = 'Posted'+ -- See AR note: reconcile on payment.postingDate, not appliedDate.+ AND p."postingDate" <= _as_of_date+ ), 0)) * pi."exchangeRate" AS open_base+ FROM "purchaseInvoice" pi+ WHERE pi."companyId" = _company_id+ AND pi."postingDate" <= _as_of_date+ AND pi."status" NOT IN ('Draft', 'Pending', 'Voided')+ ),+ invoice_buckets AS (+ SELECT+ "supplierId",+ COALESCE(SUM(open_base) FILTER (+ WHERE age_date IS NULL OR age_date >= _as_of_date+ ), 0) AS "current",+ COALESCE(SUM(open_base) FILTER (+ WHERE age_date < _as_of_date+ AND _as_of_date - age_date BETWEEN 1 AND _bucket1+ ), 0) AS "bucket1",+ COALESCE(SUM(open_base) FILTER (+ WHERE _as_of_date - age_date BETWEEN _bucket1 + 1 AND _bucket2+ ), 0) AS "bucket2",+ COALESCE(SUM(open_base) FILTER (+ WHERE _as_of_date - age_date BETWEEN _bucket2 + 1 AND _bucket3+ ), 0) AS "bucket3",+ COALESCE(SUM(open_base) FILTER (+ WHERE _as_of_date - age_date > _bucket3+ ), 0) AS "bucket4"+ FROM open_invoices+ WHERE open_base <> 0+ GROUP BY "supplierId"+ ),+ unapplied AS (+ SELECT+ p."supplierId",+ -COALESCE(SUM(+ (p."totalAmount" - COALESCE((+ SELECT SUM(pa."appliedAmount")+ FROM "invoiceSettlement" pa+ WHERE pa."paymentId" = p."id"+ ), 0)) * p."exchangeRate"+ ), 0) AS "unapplied"+ FROM "payment" p+ WHERE p."companyId" = _company_id+ AND p."paymentType" = 'Disbursement'+ AND p."status" = 'Posted'+ AND p."postingDate" <= _as_of_date+ AND p."supplierId" IS NOT NULL+ GROUP BY p."supplierId"+ )+ SELECT+ COALESCE(ib."supplierId", u."supplierId") AS "supplierId",+ pt."name" AS "paymentTerm",+ COALESCE(ib."current", 0) AS "current",+ COALESCE(ib."bucket1", 0) AS "bucket1",+ COALESCE(ib."bucket2", 0) AS "bucket2",+ COALESCE(ib."bucket3", 0) AS "bucket3",+ COALESCE(ib."bucket4", 0) AS "bucket4",+ COALESCE(u."unapplied", 0) AS "unapplied",+ COALESCE(ib."current", 0) + COALESCE(ib."bucket1", 0)+ + COALESCE(ib."bucket2", 0) + COALESCE(ib."bucket3", 0)+ + COALESCE(ib."bucket4", 0) + COALESCE(u."unapplied", 0) AS "total"+ FROM invoice_buckets ib+ FULL OUTER JOIN unapplied u ON u."supplierId" = ib."supplierId"+ LEFT JOIN "supplierPayment" sp+ ON sp."supplierId" = COALESCE(ib."supplierId", u."supplierId")+ AND sp."companyId" = _company_id+ LEFT JOIN "paymentTerm" pt ON pt."id" = sp."paymentTermId"+ WHERE+ COALESCE(ib."current", 0) + COALESCE(ib."bucket1", 0)+ + COALESCE(ib."bucket2", 0) + COALESCE(ib."bucket3", 0)+ + COALESCE(ib."bucket4", 0) + COALESCE(u."unapplied", 0) <> 0+ ORDER BY "total" DESC;+$$;diff --git a/packages/database/supabase/migrations/20260630102736_invoice-balance-from-line-total.sql b/packages/database/supabase/migrations/20260630102736_invoice-balance-from-line-total.sqlnew file mode 100644index 0000000000..8d26e71c1a--- /dev/null+++ b/packages/database/supabase/migrations/20260630102736_invoice-balance-from-line-total.sql@@ -0,0 +1,218 @@+-- ============================================================+-- Derive invoice balance + Paid status from the LIVE line total, on the unified+-- invoiceSettlement model.+--+-- Migration 20260604120000 deprecated the stored+-- salesInvoice/purchaseInvoice.{subtotal,totalTax,totalAmount} columns and moved+-- totals into the views. `balance` and the 'Paid' status derive from the live+-- line total (exposed as totalAmount/invoiceTotal/orderTotal), not the stored+-- column.+--+-- An invoice is reduced ("consumed") by rows in "invoiceSettlement" that TARGET+-- it: cash payments once Posted, and credit/debit memos once Posted. Memos are+-- their own `memo` documents (not invoice rows), so an ordinary invoice is never+-- a settlement SOURCE — there is no "credit handed out" term here.+-- ============================================================++CREATE OR REPLACE VIEW "salesInvoices" WITH(SECURITY_INVOKER=true) AS+ WITH settled AS (+ -- Amount applied TO this invoice (as the settlement target): Posted cash+ -- payments and Posted credit memos.+ SELECT+ s."targetSalesInvoiceId" AS "salesInvoiceId",+ SUM(s."appliedAmount" + s."discountAmount" + s."writeOffAmount") AS amount,+ MAX(COALESCE(p."postingDate", m."postingDate")) AS "lastPaymentDate"+ FROM "invoiceSettlement" s+ LEFT JOIN "payment" p ON p."id" = s."paymentId"+ LEFT JOIN "memo" m ON m."id" = s."memoId"+ WHERE s."targetSalesInvoiceId" IS NOT NULL+ AND (+ (s."paymentId" IS NOT NULL AND p."status" = 'Posted')+ OR (s."memoId" IS NOT NULL AND m."status" = 'Posted')+ )+ GROUP BY s."targetSalesInvoiceId"+ )+ SELECT+ si."id",+ si."invoiceId",+ CASE+ WHEN si."status" IN ('Draft','Pending','Voided','Return','Credit Note Issued') THEN si."status"::TEXT+ WHEN COALESCE(s.amount, 0) >= (COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0))+ AND (COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0)) > 0 THEN 'Paid'+ WHEN COALESCE(s.amount, 0) > 0 THEN 'Partially Paid'+ WHEN si."dateDue" < CURRENT_DATE AND si."status" = 'Submitted' THEN 'Overdue'+ ELSE si."status"::TEXT+ END AS status,+ si."customerId",+ si."customerReference",+ si."invoiceCustomerId",+ si."invoiceCustomerLocationId",+ si."invoiceCustomerContactId",+ si."paymentTermId",+ si."postingDate",+ si."dateIssued",+ si."dateDue",+ -- A fully-settled invoice's "Paid" status is derived; the base datePaid+ -- column is never written, so derive it from the latest posted settlement+ -- date when fully settled, otherwise pass the base column through.+ CASE+ WHEN COALESCE(s.amount, 0) >= (COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0))+ AND (COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0)) > 0+ THEN COALESCE(si."datePaid", s."lastPaymentDate")+ ELSE si."datePaid"+ END AS "datePaid",+ si."locationId",+ si."currencyCode",+ COALESCE(sil."subtotal", 0) AS "subtotal",+ si."totalDiscount",+ COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0) AS "totalAmount",+ COALESCE(sil."totalTax", 0) AS "totalTax",+ ((COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0)) - COALESCE(s.amount, 0)) AS "balance",+ si."exchangeRate",+ si."exchangeRateUpdatedAt",+ si."opportunityId",+ si."shipmentId",+ si."assignee",+ si."companyId",+ si."customFields",+ si."internalNotes",+ si."externalNotes",+ si."tags",+ si."createdAt",+ si."createdBy",+ si."updatedAt",+ si."updatedBy",+ sil."thumbnailPath",+ sil."itemType",+ COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0) AS "invoiceTotal",+ sil."lines"+ FROM "salesInvoice" si+ LEFT JOIN (+ SELECT+ sil."invoiceId",+ MIN(CASE+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"+ ELSE i."thumbnailPath"+ END) AS "thumbnailPath",+ SUM(+ COALESCE(sil."quantity", 0)*COALESCE(sil."unitPrice", 0)+ + COALESCE(sil."addOnCost", 0)+ + COALESCE(sil."nonTaxableAddOnCost", 0)+ + COALESCE(sil."shippingCost", 0)+ ) AS "subtotal",+ SUM(+ COALESCE(sil."taxPercent", 0) * (+ COALESCE(sil."quantity", 0)*COALESCE(sil."unitPrice", 0)+ + COALESCE(sil."addOnCost", 0)+ + COALESCE(sil."shippingCost", 0)+ )+ ) AS "totalTax",+ MIN(i."type") AS "itemType",+ ARRAY_AGG(+ json_build_object(+ 'id', sil.id,+ 'invoiceLineType', sil."invoiceLineType",+ 'quantity', sil."quantity",+ 'unitPrice', sil."unitPrice",+ 'itemId', sil."itemId"+ )+ ) AS "lines"+ FROM "salesInvoiceLine" sil+ LEFT JOIN "item" i+ ON i."id" = sil."itemId"+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"+ GROUP BY sil."invoiceId"+ ) sil ON sil."invoiceId" = si."id"+ JOIN "salesInvoiceShipment" ss ON ss."id" = si."id"+ LEFT JOIN settled s ON s."salesInvoiceId" = si."id";+++CREATE OR REPLACE VIEW "purchaseInvoices" WITH(SECURITY_INVOKER=true) AS+ WITH settled AS (+ SELECT+ s."targetPurchaseInvoiceId" AS "purchaseInvoiceId",+ SUM(s."appliedAmount" + s."discountAmount" + s."writeOffAmount") AS amount,+ MAX(COALESCE(p."postingDate", m."postingDate")) AS "lastPaymentDate"+ FROM "invoiceSettlement" s+ LEFT JOIN "payment" p ON p."id" = s."paymentId"+ LEFT JOIN "memo" m ON m."id" = s."memoId"+ WHERE s."targetPurchaseInvoiceId" IS NOT NULL+ AND (+ (s."paymentId" IS NOT NULL AND p."status" = 'Posted')+ OR (s."memoId" IS NOT NULL AND m."status" = 'Posted')+ )+ GROUP BY s."targetPurchaseInvoiceId"+ )+ SELECT+ pi."id",+ pi."invoiceId",+ pi."supplierId",+ pi."invoiceSupplierId",+ pi."supplierInteractionId",+ pi."supplierReference",+ pi."invoiceSupplierContactId",+ pi."invoiceSupplierLocationId",+ pi."locationId",+ pi."postingDate",+ pi."dateIssued",+ pi."dateDue",+ CASE+ WHEN COALESCE(s.amount, 0) >= (COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) * CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END)+ AND (COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) * CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) > 0+ THEN COALESCE(pi."datePaid", s."lastPaymentDate")+ ELSE pi."datePaid"+ END AS "datePaid",+ pi."paymentTermId",+ pi."currencyCode",+ pi."exchangeRate",+ pi."exchangeRateUpdatedAt",+ COALESCE(pl."subtotal", 0) AS "subtotal",+ pi."totalDiscount",+ (COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) * CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) AS "totalAmount",+ COALESCE(pl."totalTax", 0) AS "totalTax",+ ((COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) * CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) - COALESCE(s.amount, 0)) AS "balance",+ pi."assignee",+ pi."createdBy",+ pi."createdAt",+ pi."updatedBy",+ pi."updatedAt",+ pi."internalNotes",+ pi."customFields",+ pi."companyId",+ pl."thumbnailPath",+ pl."itemType",+ COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) * CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END AS "orderTotal",+ CASE+ WHEN pi."status" IN ('Draft','Pending','Voided','Return','Debit Note Issued') THEN pi."status"::TEXT+ WHEN COALESCE(s.amount, 0) >= (COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) * CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END)+ AND (COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) * CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) > 0 THEN 'Paid'+ WHEN COALESCE(s.amount, 0) > 0 THEN 'Partially Paid'+ WHEN pi."dateDue" < CURRENT_DATE AND pi."status" = 'Open' THEN 'Overdue'+ ELSE pi."status"::TEXT+ END AS status,+ pt."name" AS "paymentTermName"+ FROM "purchaseInvoice" pi+ LEFT JOIN (+ SELECT+ pol."invoiceId",+ MIN(CASE+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"+ ELSE i."thumbnailPath"+ END) AS "thumbnailPath",+ SUM(+ COALESCE(pol."quantity", 0)*COALESCE(pol."unitPrice", 0) + COALESCE(pol."shippingCost", 0)+ ) AS "subtotal",+ SUM(COALESCE(pol."taxAmount", 0)) AS "totalTax",+ SUM(+ COALESCE(pol."quantity", 0)*COALESCE(pol."unitPrice", 0) + COALESCE(pol."shippingCost", 0) + COALESCE(pol."taxAmount", 0)+ ) AS "orderTotal",+ MIN(i."type") AS "itemType"+ FROM "purchaseInvoiceLine" pol+ LEFT JOIN "item" i+ ON i."id" = pol."itemId"+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"+ GROUP BY pol."invoiceId"+ ) pl ON pl."invoiceId" = pi."id"+ LEFT JOIN "paymentTerm" pt ON pt."id" = pi."paymentTermId"+ LEFT JOIN "purchaseInvoiceDelivery" pid ON pid."id" = pi."id"+ LEFT JOIN settled s ON s."purchaseInvoiceId" = pi."id";diff --git a/packages/database/supabase/migrations/20260630104012_tie-out-aging-from-view-total.sql b/packages/database/supabase/migrations/20260630104012_tie-out-aging-from-view-total.sqlnew file mode 100644index 0000000000..2e9b435944--- /dev/null+++ b/packages/database/supabase/migrations/20260630104012_tie-out-aging-from-view-total.sql@@ -0,0 +1,636 @@+-- ============================================================+-- Tie-out + aging RPCs on the unified invoiceSettlement model, accounting for+-- credit/debit memos (now their own `memo` documents, NOT invoice rows).+--+-- Invoice totals come from the salesInvoices / purchaseInvoices views+-- ("totalAmount" = live line total). The subledger control balance =+-- Σ open invoices (+)+-- + Σ open memos (signed by what they do to the control account)+-- − Σ unapplied cash.+--+-- Memo sign on the control account:+-- AR: Credit -> CR receivables (−), Debit -> DR receivables (+)+-- AP: Debit -> DR payables (−), Credit -> CR payables (+)+--+-- Each document's "open" is reduced only by CASH (payment-sourced settlement):+-- invoice payments, or refunds against a memo. Memo→invoice credit applications+-- (memoId-sourced) are GL-neutral and net to zero in the signed total (they+-- lower the invoice's open and the memo's remaining by the same amount), so they+-- are intentionally excluded. Cash cuts on payment.postingDate so the subledger+-- reconciles to the GL as of one clock.+-- ============================================================+++-- ============================================================+-- AR tie-out+-- ============================================================++CREATE OR REPLACE FUNCTION get_ar_tie_out(+ _company_id TEXT,+ _as_of_date DATE+)+RETURNS TABLE (+ "subledgerBalance" NUMERIC,+ "glBalance" NUMERIC,+ "variance" NUMERIC+)+LANGUAGE SQL+SECURITY INVOKER+AS $$+ WITH+ invoice_open AS (+ SELECT+ si."totalAmount" - COALESCE((+ SELECT SUM(pa."appliedAmount" + pa."discountAmount" + pa."writeOffAmount")+ FROM "invoiceSettlement" pa+ JOIN "payment" p ON p."id" = pa."paymentId"+ WHERE pa."targetSalesInvoiceId" = si."id"+ AND p."status" = 'Posted'+ AND p."postingDate" <= _as_of_date+ ), 0) AS open_inv_ccy,+ si."exchangeRate"+ FROM "salesInvoices" si+ WHERE si."companyId" = _company_id+ AND si."postingDate" <= _as_of_date+ AND si."status" NOT IN ('Draft', 'Pending', 'Voided')+ ),+ -- Posted AR memos, signed: Credit reduces AR (−), Debit increases AR (+).+ -- Open = amount − cash applied against the memo (refund / settlement).+ memo_open AS (+ SELECT+ (CASE WHEN m."direction" = 'Credit' THEN -1 ELSE 1 END)+ * (m."amount" - COALESCE((+ SELECT SUM(pa."appliedAmount")+ FROM "invoiceSettlement" pa+ JOIN "payment" p ON p."id" = pa."paymentId"+ WHERE pa."targetMemoId" = m."id"+ AND p."status" = 'Posted'+ AND p."postingDate" <= _as_of_date+ ), 0))+ * m."exchangeRate" AS open_base+ FROM "memo" m+ WHERE m."companyId" = _company_id+ AND m."customerId" IS NOT NULL+ AND m."status" = 'Posted'+ AND m."postingDate" <= _as_of_date+ ),+ -- Unapplied portion of Posted Receipts, in payment currency.+ payment_unapplied AS (+ SELECT+ p."exchangeRate",+ p."totalAmount" - COALESCE((+ SELECT SUM(pa."appliedAmount")+ FROM "invoiceSettlement" pa+ WHERE pa."paymentId" = p."id"+ ), 0) AS unapplied_pay_ccy+ FROM "payment" p+ WHERE p."companyId" = _company_id+ AND p."paymentType" = 'Receipt'+ AND p."status" = 'Posted'+ AND p."postingDate" <= _as_of_date+ ),+ subledger AS (+ SELECT+ COALESCE((SELECT SUM(open_inv_ccy * "exchangeRate") FROM invoice_open), 0)+ + COALESCE((SELECT SUM(open_base) FROM memo_open), 0)+ - COALESCE((SELECT SUM(unapplied_pay_ccy * "exchangeRate") FROM payment_unapplied), 0)+ AS amount+ ),+ ar_account AS (+ SELECT "receivablesAccount" AS account_id+ FROM "accountDefault"+ WHERE "companyId" = _company_id+ ),+ gl AS (+ SELECT COALESCE(SUM(jl."amount"), 0) AS amount+ FROM "journalLine" jl+ JOIN "journal" j ON j."id" = jl."journalId"+ JOIN ar_account a ON jl."accountId" = a.account_id+ WHERE jl."companyId" = _company_id+ AND j."postingDate" <= _as_of_date+ AND j."status" = 'Posted'+ )+ SELECT+ subledger.amount AS "subledgerBalance",+ gl.amount AS "glBalance",+ subledger.amount - gl.amount AS "variance"+ FROM subledger, gl;+$$;+++-- ============================================================+-- AP tie-out (mirror of AR)+-- ============================================================++CREATE OR REPLACE FUNCTION get_ap_tie_out(+ _company_id TEXT,+ _as_of_date DATE+)+RETURNS TABLE (+ "subledgerBalance" NUMERIC,+ "glBalance" NUMERIC,+ "variance" NUMERIC+)+LANGUAGE SQL+SECURITY INVOKER+AS $$+ WITH+ invoice_open AS (+ SELECT+ pi."totalAmount" - COALESCE((+ SELECT SUM(pa."appliedAmount" + pa."discountAmount" + pa."writeOffAmount")+ FROM "invoiceSettlement" pa+ JOIN "payment" p ON p."id" = pa."paymentId"+ WHERE pa."targetPurchaseInvoiceId" = pi."id"+ AND p."status" = 'Posted'+ AND p."postingDate" <= _as_of_date+ ), 0) AS open_inv_ccy,+ pi."exchangeRate"+ FROM "purchaseInvoices" pi+ WHERE pi."companyId" = _company_id+ AND pi."postingDate" <= _as_of_date+ AND pi."status" NOT IN ('Draft', 'Pending', 'Voided')+ ),+ -- Posted AP memos, signed: Debit reduces AP (−), Credit increases AP (+).+ memo_open AS (+ SELECT+ (CASE WHEN m."direction" = 'Debit' THEN -1 ELSE 1 END)+ * (m."amount" - COALESCE((+ SELECT SUM(pa."appliedAmount")+ FROM "invoiceSettlement" pa+ JOIN "payment" p ON p."id" = pa."paymentId"+ WHERE pa."targetMemoId" = m."id"+ AND p."status" = 'Posted'+ AND p."postingDate" <= _as_of_date+ ), 0))+ * m."exchangeRate" AS open_base+ FROM "memo" m+ WHERE m."companyId" = _company_id+ AND m."supplierId" IS NOT NULL+ AND m."status" = 'Posted'+ AND m."postingDate" <= _as_of_date+ ),+ payment_unapplied AS (+ SELECT+ p."exchangeRate",+ p."totalAmount" - COALESCE((+ SELECT SUM(pa."appliedAmount")+ FROM "invoiceSettlement" pa+ WHERE pa."paymentId" = p."id"+ ), 0) AS unapplied_pay_ccy+ FROM "payment" p+ WHERE p."companyId" = _company_id+ AND p."paymentType" = 'Disbursement'+ AND p."status" = 'Posted'+ AND p."postingDate" <= _as_of_date+ ),+ subledger AS (+ SELECT+ COALESCE((SELECT SUM(open_inv_ccy * "exchangeRate") FROM invoice_open), 0)+ + COALESCE((SELECT SUM(open_base) FROM memo_open), 0)+ - COALESCE((SELECT SUM(unapplied_pay_ccy * "exchangeRate") FROM payment_unapplied), 0)+ AS amount+ ),+ ap_account AS (+ SELECT "payablesAccount" AS account_id+ FROM "accountDefault"+ WHERE "companyId" = _company_id+ ),+ gl AS (+ SELECT COALESCE(SUM(jl."amount"), 0) AS amount+ FROM "journalLine" jl+ JOIN "journal" j ON j."id" = jl."journalId"+ JOIN ap_account a ON jl."accountId" = a.account_id+ WHERE jl."companyId" = _company_id+ AND j."postingDate" <= _as_of_date+ AND j."status" = 'Posted'+ )+ SELECT+ subledger.amount AS "subledgerBalance",+ gl.amount AS "glBalance",+ subledger.amount - gl.amount AS "variance"+ FROM subledger, gl;+$$;+++-- ============================================================+-- Drill-down: open AR items per customer (invoices + memos)+-- ============================================================+-- `documentType` is 'Invoice' | 'Credit Memo' | 'Debit Memo'. openInCurrency /+-- openInBase carry the control-account sign, so the drill-down sums to the+-- tie-out subledger.++DROP FUNCTION IF EXISTS get_ar_open_by_customer(TEXT, DATE);+CREATE OR REPLACE FUNCTION get_ar_open_by_customer(+ _company_id TEXT,+ _as_of_date DATE+)+RETURNS TABLE (+ "customerId" TEXT,+ "documentId" TEXT,+ "documentNumber" TEXT,+ "documentType" TEXT,+ "dateDue" DATE,+ "currencyCode" TEXT,+ "exchangeRate" NUMERIC,+ "totalAmount" NUMERIC,+ "settled" NUMERIC,+ "openInCurrency" NUMERIC,+ "openInBase" NUMERIC+)+LANGUAGE SQL+SECURITY INVOKER+AS $$+ -- Invoices (+open)+ SELECT+ si."customerId",+ si."id" AS "documentId",+ si."invoiceId" AS "documentNumber",+ 'Invoice' AS "documentType",+ si."dateDue",+ si."currencyCode",+ si."exchangeRate",+ si."totalAmount",+ COALESCE(s.settled, 0) AS "settled",+ (si."totalAmount" - COALESCE(s.settled, 0)) AS "openInCurrency",+ (si."totalAmount" - COALESCE(s.settled, 0)) * si."exchangeRate" AS "openInBase"+ FROM "salesInvoices" si+ LEFT JOIN LATERAL (+ SELECT SUM(pa."appliedAmount" + pa."discountAmount" + pa."writeOffAmount") AS settled+ FROM "invoiceSettlement" pa+ JOIN "payment" p ON p."id" = pa."paymentId"+ WHERE pa."targetSalesInvoiceId" = si."id"+ AND p."status" = 'Posted'+ AND p."postingDate" <= _as_of_date+ ) s ON true+ WHERE si."companyId" = _company_id+ AND si."postingDate" <= _as_of_date+ AND si."status" NOT IN ('Draft', 'Pending', 'Voided')+ AND (si."totalAmount" - COALESCE(s.settled, 0)) <> 0++ UNION ALL++ -- Memos (Credit −, Debit +)+ SELECT+ m."customerId",+ m."id" AS "documentId",+ m."memoId" AS "documentNumber",+ (m."direction" || ' Memo') AS "documentType",+ NULL::DATE AS "dateDue",+ m."currencyCode",+ m."exchangeRate",+ m."amount" AS "totalAmount",+ COALESCE(s.settled, 0) AS "settled",+ (CASE WHEN m."direction" = 'Credit' THEN -1 ELSE 1 END)+ * (m."amount" - COALESCE(s.settled, 0)) AS "openInCurrency",+ (CASE WHEN m."direction" = 'Credit' THEN -1 ELSE 1 END)+ * (m."amount" - COALESCE(s.settled, 0)) * m."exchangeRate" AS "openInBase"+ FROM "memo" m+ LEFT JOIN LATERAL (+ SELECT SUM(pa."appliedAmount") AS settled+ FROM "invoiceSettlement" pa+ JOIN "payment" p ON p."id" = pa."paymentId"+ WHERE pa."targetMemoId" = m."id"+ AND p."status" = 'Posted'+ AND p."postingDate" <= _as_of_date+ ) s ON true+ WHERE m."companyId" = _company_id+ AND m."customerId" IS NOT NULL+ AND m."status" = 'Posted'+ AND m."postingDate" <= _as_of_date+ AND (m."amount" - COALESCE(s.settled, 0)) <> 0+ ORDER BY 1, 5 NULLS LAST;+$$;+++-- ============================================================+-- Drill-down: open AP items per supplier (invoices + memos)+-- ============================================================++DROP FUNCTION IF EXISTS get_ap_open_by_supplier(TEXT, DATE);+CREATE OR REPLACE FUNCTION get_ap_open_by_supplier(+ _company_id TEXT,+ _as_of_date DATE+)+RETURNS TABLE (+ "supplierId" TEXT,+ "documentId" TEXT,+ "documentNumber" TEXT,+ "documentType" TEXT,+ "dateDue" DATE,+ "currencyCode" TEXT,+ "exchangeRate" NUMERIC,+ "totalAmount" NUMERIC,+ "settled" NUMERIC,+ "openInCurrency" NUMERIC,+ "openInBase" NUMERIC+)+LANGUAGE SQL+SECURITY INVOKER+AS $$+ SELECT+ pi."supplierId",+ pi."id" AS "documentId",+ pi."invoiceId" AS "documentNumber",+ 'Invoice' AS "documentType",+ pi."dateDue",+ pi."currencyCode",+ pi."exchangeRate",+ pi."totalAmount",+ COALESCE(s.settled, 0) AS "settled",+ (pi."totalAmount" - COALESCE(s.settled, 0)) AS "openInCurrency",+ (pi."totalAmount" - COALESCE(s.settled, 0)) * pi."exchangeRate" AS "openInBase"+ FROM "purchaseInvoices" pi+ LEFT JOIN LATERAL (+ SELECT SUM(pa."appliedAmount" + pa."discountAmount" + pa."writeOffAmount") AS settled+ FROM "invoiceSettlement" pa+ JOIN "payment" p ON p."id" = pa."paymentId"+ WHERE pa."targetPurchaseInvoiceId" = pi."id"+ AND p."status" = 'Posted'+ AND p."postingDate" <= _as_of_date+ ) s ON true+ WHERE pi."companyId" = _company_id+ AND pi."postingDate" <= _as_of_date+ AND pi."status" NOT IN ('Draft', 'Pending', 'Voided')+ AND (pi."totalAmount" - COALESCE(s.settled, 0)) <> 0++ UNION ALL++ SELECT+ m."supplierId",+ m."id" AS "documentId",+ m."memoId" AS "documentNumber",+ (m."direction" || ' Memo') AS "documentType",+ NULL::DATE AS "dateDue",+ m."currencyCode",+ m."exchangeRate",+ m."amount" AS "totalAmount",+ COALESCE(s.settled, 0) AS "settled",+ (CASE WHEN m."direction" = 'Debit' THEN -1 ELSE 1 END)+ * (m."amount" - COALESCE(s.settled, 0)) AS "openInCurrency",+ (CASE WHEN m."direction" = 'Debit' THEN -1 ELSE 1 END)+ * (m."amount" - COALESCE(s.settled, 0)) * m."exchangeRate" AS "openInBase"+ FROM "memo" m+ LEFT JOIN LATERAL (+ SELECT SUM(pa."appliedAmount") AS settled+ FROM "invoiceSettlement" pa+ JOIN "payment" p ON p."id" = pa."paymentId"+ WHERE pa."targetMemoId" = m."id"+ AND p."status" = 'Posted'+ AND p."postingDate" <= _as_of_date+ ) s ON true+ WHERE m."companyId" = _company_id+ AND m."supplierId" IS NOT NULL+ AND m."status" = 'Posted'+ AND m."postingDate" <= _as_of_date+ AND (m."amount" - COALESCE(s.settled, 0)) <> 0+ ORDER BY 1, 5 NULLS LAST;+$$;+++-- ============================================================+-- AR aging (invoices + memos bucketed by age; unapplied cash separate)+-- ============================================================++CREATE OR REPLACE FUNCTION get_ar_aging(+ _company_id TEXT,+ _as_of_date DATE,+ _aging_method TEXT DEFAULT 'dueDate',+ _bucket1 INTEGER DEFAULT 30,+ _bucket2 INTEGER DEFAULT 60,+ _bucket3 INTEGER DEFAULT 90+)+RETURNS TABLE (+ "customerId" TEXT,+ "paymentTerm" TEXT,+ "current" NUMERIC,+ "bucket1" NUMERIC,+ "bucket2" NUMERIC,+ "bucket3" NUMERIC,+ "bucket4" NUMERIC,+ "unapplied" NUMERIC,+ "total" NUMERIC+)+LANGUAGE SQL+SECURITY INVOKER+AS $$+ WITH open_items AS (+ -- Invoices (+open)+ SELECT+ si."customerId",+ CASE+ WHEN _aging_method = 'documentDate'+ THEN COALESCE(si."dateIssued", si."postingDate")+ ELSE si."dateDue"+ END AS age_date,+ (si."totalAmount" - COALESCE((+ SELECT SUM(pa."appliedAmount" + pa."discountAmount" + pa."writeOffAmount")+ FROM "invoiceSettlement" pa+ JOIN "payment" p ON p."id" = pa."paymentId"+ WHERE pa."targetSalesInvoiceId" = si."id"+ AND p."status" = 'Posted'+ AND p."postingDate" <= _as_of_date+ ), 0)) * si."exchangeRate" AS open_base+ FROM "salesInvoices" si+ WHERE si."companyId" = _company_id+ AND si."postingDate" <= _as_of_date+ AND si."status" NOT IN ('Draft', 'Pending', 'Voided')++ UNION ALL++ -- Memos (Credit −, Debit +), aged by their own date+ SELECT+ m."customerId",+ CASE WHEN _aging_method = 'documentDate' THEN m."memoDate" ELSE m."memoDate" END AS age_date,+ (CASE WHEN m."direction" = 'Credit' THEN -1 ELSE 1 END)+ * (m."amount" - COALESCE((+ SELECT SUM(pa."appliedAmount")+ FROM "invoiceSettlement" pa+ JOIN "payment" p ON p."id" = pa."paymentId"+ WHERE pa."targetMemoId" = m."id"+ AND p."status" = 'Posted'+ AND p."postingDate" <= _as_of_date+ ), 0)) * m."exchangeRate" AS open_base+ FROM "memo" m+ WHERE m."companyId" = _company_id+ AND m."customerId" IS NOT NULL+ AND m."status" = 'Posted'+ AND m."postingDate" <= _as_of_date+ ),+ buckets AS (+ SELECT+ "customerId",+ COALESCE(SUM(open_base) FILTER (WHERE age_date IS NULL OR age_date >= _as_of_date), 0) AS "current",+ COALESCE(SUM(open_base) FILTER (WHERE age_date < _as_of_date AND _as_of_date - age_date BETWEEN 1 AND _bucket1), 0) AS "bucket1",+ COALESCE(SUM(open_base) FILTER (WHERE _as_of_date - age_date BETWEEN _bucket1 + 1 AND _bucket2), 0) AS "bucket2",+ COALESCE(SUM(open_base) FILTER (WHERE _as_of_date - age_date BETWEEN _bucket2 + 1 AND _bucket3), 0) AS "bucket3",+ COALESCE(SUM(open_base) FILTER (WHERE _as_of_date - age_date > _bucket3), 0) AS "bucket4"+ FROM open_items+ WHERE open_base <> 0+ GROUP BY "customerId"+ ),+ unapplied AS (+ SELECT+ p."customerId",+ -COALESCE(SUM(+ (p."totalAmount" - COALESCE((+ SELECT SUM(pa."appliedAmount")+ FROM "invoiceSettlement" pa+ WHERE pa."paymentId" = p."id"+ ), 0)) * p."exchangeRate"+ ), 0) AS "unapplied"+ FROM "payment" p+ WHERE p."companyId" = _company_id+ AND p."paymentType" = 'Receipt'+ AND p."status" = 'Posted'+ AND p."postingDate" <= _as_of_date+ AND p."customerId" IS NOT NULL+ GROUP BY p."customerId"+ )+ SELECT+ COALESCE(ib."customerId", u."customerId") AS "customerId",+ pt."name" AS "paymentTerm",+ COALESCE(ib."current", 0) AS "current",+ COALESCE(ib."bucket1", 0) AS "bucket1",+ COALESCE(ib."bucket2", 0) AS "bucket2",+ COALESCE(ib."bucket3", 0) AS "bucket3",+ COALESCE(ib."bucket4", 0) AS "bucket4",+ COALESCE(u."unapplied", 0) AS "unapplied",+ COALESCE(ib."current", 0) + COALESCE(ib."bucket1", 0)+ + COALESCE(ib."bucket2", 0) + COALESCE(ib."bucket3", 0)+ + COALESCE(ib."bucket4", 0) + COALESCE(u."unapplied", 0) AS "total"+ FROM buckets ib+ FULL OUTER JOIN unapplied u ON u."customerId" = ib."customerId"+ LEFT JOIN "customerPayment" cp+ ON cp."customerId" = COALESCE(ib."customerId", u."customerId")+ AND cp."companyId" = _company_id+ LEFT JOIN "paymentTerm" pt ON pt."id" = cp."paymentTermId"+ WHERE+ COALESCE(ib."current", 0) + COALESCE(ib."bucket1", 0)+ + COALESCE(ib."bucket2", 0) + COALESCE(ib."bucket3", 0)+ + COALESCE(ib."bucket4", 0) + COALESCE(u."unapplied", 0) <> 0+ ORDER BY "total" DESC;+$$;+++-- ============================================================+-- AP aging (mirror — supplier + purchaseInvoice + Disbursement)+-- ============================================================++CREATE OR REPLACE FUNCTION get_ap_aging(+ _company_id TEXT,+ _as_of_date DATE,+ _aging_method TEXT DEFAULT 'dueDate',+ _bucket1 INTEGER DEFAULT 30,+ _bucket2 INTEGER DEFAULT 60,+ _bucket3 INTEGER DEFAULT 90+)+RETURNS TABLE (+ "supplierId" TEXT,+ "paymentTerm" TEXT,+ "current" NUMERIC,+ "bucket1" NUMERIC,+ "bucket2" NUMERIC,+ "bucket3" NUMERIC,+ "bucket4" NUMERIC,+ "unapplied" NUMERIC,+ "total" NUMERIC+)+LANGUAGE SQL+SECURITY INVOKER+AS $$+ WITH open_items AS (+ SELECT+ pi."supplierId",+ CASE+ WHEN _aging_method = 'documentDate'+ THEN COALESCE(pi."dateIssued", pi."postingDate")+ ELSE pi."dateDue"+ END AS age_date,+ (pi."totalAmount" - COALESCE((+ SELECT SUM(pa."appliedAmount" + pa."discountAmount" + pa."writeOffAmount")+ FROM "invoiceSettlement" pa+ JOIN "payment" p ON p."id" = pa."paymentId"+ WHERE pa."targetPurchaseInvoiceId" = pi."id"+ AND p."status" = 'Posted'+ AND p."postingDate" <= _as_of_date+ ), 0)) * pi."exchangeRate" AS open_base+ FROM "purchaseInvoices" pi+ WHERE pi."companyId" = _company_id+ AND pi."postingDate" <= _as_of_date+ AND pi."status" NOT IN ('Draft', 'Pending', 'Voided')++ UNION ALL++ SELECT+ m."supplierId",+ m."memoDate" AS age_date,+ (CASE WHEN m."direction" = 'Debit' THEN -1 ELSE 1 END)+ * (m."amount" - COALESCE((+ SELECT SUM(pa."appliedAmount")+ FROM "invoiceSettlement" pa+ JOIN "payment" p ON p."id" = pa."paymentId"+ WHERE pa."targetMemoId" = m."id"+ AND p."status" = 'Posted'+ AND p."postingDate" <= _as_of_date+ ), 0)) * m."exchangeRate" AS open_base+ FROM "memo" m+ WHERE m."companyId" = _company_id+ AND m."supplierId" IS NOT NULL+ AND m."status" = 'Posted'+ AND m."postingDate" <= _as_of_date+ ),+ buckets AS (+ SELECT+ "supplierId",+ COALESCE(SUM(open_base) FILTER (WHERE age_date IS NULL OR age_date >= _as_of_date), 0) AS "current",+ COALESCE(SUM(open_base) FILTER (WHERE age_date < _as_of_date AND _as_of_date - age_date BETWEEN 1 AND _bucket1), 0) AS "bucket1",+ COALESCE(SUM(open_base) FILTER (WHERE _as_of_date - age_date BETWEEN _bucket1 + 1 AND _bucket2), 0) AS "bucket2",+ COALESCE(SUM(open_base) FILTER (WHERE _as_of_date - age_date BETWEEN _bucket2 + 1 AND _bucket3), 0) AS "bucket3",+ COALESCE(SUM(open_base) FILTER (WHERE _as_of_date - age_date > _bucket3), 0) AS "bucket4"+ FROM open_items+ WHERE open_base <> 0+ GROUP BY "supplierId"+ ),+ unapplied AS (+ SELECT+ p."supplierId",+ -COALESCE(SUM(+ (p."totalAmount" - COALESCE((+ SELECT SUM(pa."appliedAmount")+ FROM "invoiceSettlement" pa+ WHERE pa."paymentId" = p."id"+ ), 0)) * p."exchangeRate"+ ), 0) AS "unapplied"+ FROM "payment" p+ WHERE p."companyId" = _company_id+ AND p."paymentType" = 'Disbursement'+ AND p."status" = 'Posted'+ AND p."postingDate" <= _as_of_date+ AND p."supplierId" IS NOT NULL+ GROUP BY p."supplierId"+ )+ SELECT+ COALESCE(ib."supplierId", u."supplierId") AS "supplierId",+ pt."name" AS "paymentTerm",+ COALESCE(ib."current", 0) AS "current",+ COALESCE(ib."bucket1", 0) AS "bucket1",+ COALESCE(ib."bucket2", 0) AS "bucket2",+ COALESCE(ib."bucket3", 0) AS "bucket3",+ COALESCE(ib."bucket4", 0) AS "bucket4",+ COALESCE(u."unapplied", 0) AS "unapplied",+ COALESCE(ib."current", 0) + COALESCE(ib."bucket1", 0)+ + COALESCE(ib."bucket2", 0) + COALESCE(ib."bucket3", 0)+ + COALESCE(ib."bucket4", 0) + COALESCE(u."unapplied", 0) AS "total"+ FROM buckets ib+ FULL OUTER JOIN unapplied u ON u."supplierId" = ib."supplierId"+ LEFT JOIN "supplierPayment" sp+ ON sp."supplierId" = COALESCE(ib."supplierId", u."supplierId")+ AND sp."companyId" = _company_id+ LEFT JOIN "paymentTerm" pt ON pt."id" = sp."paymentTermId"+ WHERE+ COALESCE(ib."current", 0) + COALESCE(ib."bucket1", 0)+ + COALESCE(ib."bucket2", 0) + COALESCE(ib."bucket3", 0)+ + COALESCE(ib."bucket4", 0) + COALESCE(u."unapplied", 0) <> 0+ ORDER BY "total" DESC;+$$;diff --git a/packages/database/supabase/migrations/20260630105334_credit-applications-via-payment.sql b/packages/database/supabase/migrations/20260630105334_credit-applications-via-payment.sqlnew file mode 100644index 0000000000..ef990d5f20--- /dev/null+++ b/packages/database/supabase/migrations/20260630105334_credit-applications-via-payment.sql@@ -0,0 +1,251 @@+-- ============================================================+-- Defer credit-memo applications to the payment that applies them.+--+-- A credit/debit memo is itself Posted, so a memo-sourced invoiceSettlement row+-- went live the instant it was written — even while the cash payment driving the+-- composer was still Draft. That made "apply credit" take effect immediately and+-- show in the invoice's applied card before posting, inconsistent with cash+-- applications (which stay Draft until the payment posts).+--+-- Fix: tie each credit application to the payment it was applied through+-- (`appliedViaPaymentId`) and only count it once THAT payment is Posted. Cash+-- applications are unchanged (source = paymentId, already gated on payment status).+-- ============================================================++ALTER TABLE "invoiceSettlement"+ ADD COLUMN "appliedViaPaymentId" TEXT;++-- Only memo-sourced settlements (credits) are "applied via" a payment; a cash+-- settlement's source IS the payment.+ALTER TABLE "invoiceSettlement"+ ADD CONSTRAINT "invoiceSettlement_appliedViaPaymentId_check"+ CHECK ("appliedViaPaymentId" IS NULL OR "memoId" IS NOT NULL);++-- Deleting the draft payment releases its staged credit applications.+ALTER TABLE "invoiceSettlement"+ ADD CONSTRAINT "invoiceSettlement_appliedViaPaymentId_fkey"+ FOREIGN KEY ("appliedViaPaymentId") REFERENCES "payment"("id")+ ON DELETE CASCADE ON UPDATE CASCADE;++CREATE INDEX "invoiceSettlement_appliedViaPaymentId_idx"+ ON "invoiceSettlement" ("appliedViaPaymentId")+ WHERE "appliedViaPaymentId" IS NOT NULL;++-- ============================================================+-- Redefine the invoice views: a memo-sourced settlement now counts only when its+-- memo is Posted AND (it isn't applied via a payment, or that payment is Posted).+-- Everything else matches 20260628151204 verbatim.+-- ============================================================++CREATE OR REPLACE VIEW "salesInvoices" WITH(SECURITY_INVOKER=true) AS+ WITH settled AS (+ -- Amount applied TO this invoice (as the settlement target): Posted cash+ -- payments, and Posted credit memos once the payment applying them is Posted.+ SELECT+ s."targetSalesInvoiceId" AS "salesInvoiceId",+ SUM(s."appliedAmount" + s."discountAmount" + s."writeOffAmount") AS amount,+ MAX(COALESCE(p."postingDate", vp."postingDate", m."postingDate")) AS "lastPaymentDate"+ FROM "invoiceSettlement" s+ LEFT JOIN "payment" p ON p."id" = s."paymentId"+ LEFT JOIN "memo" m ON m."id" = s."memoId"+ LEFT JOIN "payment" vp ON vp."id" = s."appliedViaPaymentId"+ WHERE s."targetSalesInvoiceId" IS NOT NULL+ AND (+ (s."paymentId" IS NOT NULL AND p."status" = 'Posted')+ OR (+ s."memoId" IS NOT NULL AND m."status" = 'Posted'+ AND (s."appliedViaPaymentId" IS NULL OR vp."status" = 'Posted')+ )+ )+ GROUP BY s."targetSalesInvoiceId"+ )+ SELECT+ si."id",+ si."invoiceId",+ CASE+ WHEN si."status" IN ('Draft','Pending','Voided','Return','Credit Note Issued') THEN si."status"::TEXT+ WHEN COALESCE(s.amount, 0) >= (COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0))+ AND (COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0)) > 0 THEN 'Paid'+ WHEN COALESCE(s.amount, 0) > 0 THEN 'Partially Paid'+ WHEN si."dateDue" < CURRENT_DATE AND si."status" = 'Submitted' THEN 'Overdue'+ ELSE si."status"::TEXT+ END AS status,+ si."customerId",+ si."customerReference",+ si."invoiceCustomerId",+ si."invoiceCustomerLocationId",+ si."invoiceCustomerContactId",+ si."paymentTermId",+ si."postingDate",+ si."dateIssued",+ si."dateDue",+ -- A fully-settled invoice's "Paid" status is derived; the base datePaid+ -- column is never written, so derive it from the latest posted settlement+ -- date when fully settled, otherwise pass the base column through.+ CASE+ WHEN COALESCE(s.amount, 0) >= (COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0))+ AND (COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0)) > 0+ THEN COALESCE(si."datePaid", s."lastPaymentDate")+ ELSE si."datePaid"+ END AS "datePaid",+ si."locationId",+ si."currencyCode",+ COALESCE(sil."subtotal", 0) AS "subtotal",+ si."totalDiscount",+ COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0) AS "totalAmount",+ COALESCE(sil."totalTax", 0) AS "totalTax",+ ((COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0)) - COALESCE(s.amount, 0)) AS "balance",+ si."exchangeRate",+ si."exchangeRateUpdatedAt",+ si."opportunityId",+ si."shipmentId",+ si."assignee",+ si."companyId",+ si."customFields",+ si."internalNotes",+ si."externalNotes",+ si."tags",+ si."createdAt",+ si."createdBy",+ si."updatedAt",+ si."updatedBy",+ sil."thumbnailPath",+ sil."itemType",+ COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0) AS "invoiceTotal",+ sil."lines",+ pt."name" AS "paymentTermName"+ FROM "salesInvoice" si+ LEFT JOIN (+ SELECT+ sil."invoiceId",+ MIN(CASE+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"+ ELSE i."thumbnailPath"+ END) AS "thumbnailPath",+ SUM(+ COALESCE(sil."quantity", 0)*COALESCE(sil."unitPrice", 0)+ + COALESCE(sil."addOnCost", 0)+ + COALESCE(sil."nonTaxableAddOnCost", 0)+ + COALESCE(sil."shippingCost", 0)+ ) AS "subtotal",+ SUM(+ COALESCE(sil."taxPercent", 0) * (+ COALESCE(sil."quantity", 0)*COALESCE(sil."unitPrice", 0)+ + COALESCE(sil."addOnCost", 0)+ + COALESCE(sil."shippingCost", 0)+ )+ ) AS "totalTax",+ MIN(i."type") AS "itemType",+ ARRAY_AGG(+ json_build_object(+ 'id', sil.id,+ 'invoiceLineType', sil."invoiceLineType",+ 'quantity', sil."quantity",+ 'unitPrice', sil."unitPrice",+ 'itemId', sil."itemId"+ )+ ) AS "lines"+ FROM "salesInvoiceLine" sil+ LEFT JOIN "item" i+ ON i."id" = sil."itemId"+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"+ GROUP BY sil."invoiceId"+ ) sil ON sil."invoiceId" = si."id"+ JOIN "salesInvoiceShipment" ss ON ss."id" = si."id"+ LEFT JOIN "paymentTerm" pt ON pt."id" = si."paymentTermId"+ LEFT JOIN settled s ON s."salesInvoiceId" = si."id";+++CREATE OR REPLACE VIEW "purchaseInvoices" WITH(SECURITY_INVOKER=true) AS+ WITH settled AS (+ SELECT+ s."targetPurchaseInvoiceId" AS "purchaseInvoiceId",+ SUM(s."appliedAmount" + s."discountAmount" + s."writeOffAmount") AS amount,+ MAX(COALESCE(p."postingDate", vp."postingDate", m."postingDate")) AS "lastPaymentDate"+ FROM "invoiceSettlement" s+ LEFT JOIN "payment" p ON p."id" = s."paymentId"+ LEFT JOIN "memo" m ON m."id" = s."memoId"+ LEFT JOIN "payment" vp ON vp."id" = s."appliedViaPaymentId"+ WHERE s."targetPurchaseInvoiceId" IS NOT NULL+ AND (+ (s."paymentId" IS NOT NULL AND p."status" = 'Posted')+ OR (+ s."memoId" IS NOT NULL AND m."status" = 'Posted'+ AND (s."appliedViaPaymentId" IS NULL OR vp."status" = 'Posted')+ )+ )+ GROUP BY s."targetPurchaseInvoiceId"+ )+ SELECT+ pi."id",+ pi."invoiceId",+ pi."supplierId",+ pi."invoiceSupplierId",+ pi."supplierInteractionId",+ pi."supplierReference",+ pi."invoiceSupplierContactId",+ pi."invoiceSupplierLocationId",+ pi."locationId",+ pi."postingDate",+ pi."dateIssued",+ pi."dateDue",+ CASE+ WHEN COALESCE(s.amount, 0) >= (COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) * CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END)+ AND (COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) * CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) > 0+ THEN COALESCE(pi."datePaid", s."lastPaymentDate")+ ELSE pi."datePaid"+ END AS "datePaid",+ pi."paymentTermId",+ pi."currencyCode",+ pi."exchangeRate",+ pi."exchangeRateUpdatedAt",+ COALESCE(pl."subtotal", 0) AS "subtotal",+ pi."totalDiscount",+ (COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) * CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) AS "totalAmount",+ COALESCE(pl."totalTax", 0) AS "totalTax",+ ((COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) * CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) - COALESCE(s.amount, 0)) AS "balance",+ pi."assignee",+ pi."createdBy",+ pi."createdAt",+ pi."updatedBy",+ pi."updatedAt",+ pi."internalNotes",+ pi."customFields",+ pi."companyId",+ pl."thumbnailPath",+ pl."itemType",+ COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) * CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END AS "orderTotal",+ CASE+ WHEN pi."status" IN ('Draft','Pending','Voided','Return','Debit Note Issued') THEN pi."status"::TEXT+ WHEN COALESCE(s.amount, 0) >= (COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) * CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END)+ AND (COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) * CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) > 0 THEN 'Paid'+ WHEN COALESCE(s.amount, 0) > 0 THEN 'Partially Paid'+ WHEN pi."dateDue" < CURRENT_DATE AND pi."status" = 'Open' THEN 'Overdue'+ ELSE pi."status"::TEXT+ END AS status,+ pt."name" AS "paymentTermName"+ FROM "purchaseInvoice" pi+ LEFT JOIN (+ SELECT+ pol."invoiceId",+ MIN(CASE+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"+ ELSE i."thumbnailPath"+ END) AS "thumbnailPath",+ SUM(+ COALESCE(pol."quantity", 0)*COALESCE(pol."unitPrice", 0) + COALESCE(pol."shippingCost", 0)+ ) AS "subtotal",+ SUM(COALESCE(pol."taxAmount", 0)) AS "totalTax",+ SUM(+ COALESCE(pol."quantity", 0)*COALESCE(pol."unitPrice", 0) + COALESCE(pol."shippingCost", 0) + COALESCE(pol."taxAmount", 0)+ ) AS "orderTotal",+ MIN(i."type") AS "itemType"+ FROM "purchaseInvoiceLine" pol+ LEFT JOIN "item" i+ ON i."id" = pol."itemId"+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"+ GROUP BY pol."invoiceId"+ ) pl ON pl."invoiceId" = pi."id"+ LEFT JOIN "paymentTerm" pt ON pt."id" = pi."paymentTermId"+ LEFT JOIN "purchaseInvoiceDelivery" pid ON pid."id" = pi."id"+ LEFT JOIN settled s ON s."purchaseInvoiceId" = pi."id";diff --git a/packages/database/supabase/migrations/20260630110657_purchase-invoice-unique-id.sql b/packages/database/supabase/migrations/20260630110657_purchase-invoice-unique-id.sqlnew file mode 100644index 0000000000..c26a38dea0--- /dev/null+++ b/packages/database/supabase/migrations/20260630110657_purchase-invoice-unique-id.sql@@ -0,0 +1,36 @@+-- ============================================================+-- Enforce unique readable invoice ids on purchaseInvoice.+--+-- salesInvoice has had `UNIQUE ("invoiceId", "companyId")` since+-- 20250507143421_sales-invoice.sql, but purchaseInvoice (from the 2023+-- accounts-payable migration) only ever got a plain, NON-unique index. So while+-- a duplicate readable id on a sales invoice is rejected by the DB, the same+-- collision on a purchase invoice slips through — `invoiceId` is generated in+-- app code (get_next_sequence) with no DB guard. This adds the matching+-- constraint so the two sides are symmetric.+-- ============================================================++-- Resolve any pre-existing duplicates before building the unique index (it can't+-- build over duplicate rows). Keep the earliest-created row's id; suffix the rest+-- with their own row id, which is the PK and therefore guaranteed unique — so the+-- rename itself can never collide. No-op when there are no duplicates.+WITH ranked AS (+ SELECT+ "id",+ ROW_NUMBER() OVER (+ PARTITION BY "companyId", "invoiceId" ORDER BY "createdAt", "id"+ ) AS rn+ FROM "purchaseInvoice"+)+UPDATE "purchaseInvoice" pi+SET "invoiceId" = pi."invoiceId" || '-' || pi."id"+FROM ranked+WHERE ranked."id" = pi."id" AND ranked.rn > 1;++ALTER TABLE "purchaseInvoice"+ ADD CONSTRAINT "purchaseInvoice_invoiceId_key" UNIQUE ("invoiceId", "companyId");++-- The old non-unique composite index is now redundant with the unique index+-- (which covers the same columns). Mirror salesInvoice, which keeps only the+-- single-column idx_*_invoiceId alongside its unique key.+DROP INDEX IF EXISTS "purchaseInvoice_invoiceId_idx";diff --git a/packages/database/supabase/migrations/20260630111923_ar-ap-fk-indexes.sql b/packages/database/supabase/migrations/20260630111923_ar-ap-fk-indexes.sqlnew file mode 100644index 0000000000..00a845fe70--- /dev/null+++ b/packages/database/supabase/migrations/20260630111923_ar-ap-fk-indexes.sql@@ -0,0 +1,39 @@+-- ============================================================+-- Index every foreign key on the AR/AP payment tables.+--+-- The base tables (20260628143012_ar-ap-payments,+-- 20260628171834_credit-applications-via-payment) indexed companyId, the+-- party/status/date columns, and the invoiceSettlement source/target FKs, but+-- left the remaining FK columns (account, journal, currency, audit/user refs)+-- unindexed. Carbon's convention is to index companyId AND every FK; this+-- backfills the gap. Nullable FKs use a partial index (matching the existing+-- `... WHERE "col" IS NOT NULL` style); NOT NULL FKs are plain.+-- ============================================================++-- payment+CREATE INDEX "payment_currencyCode_idx" ON "payment" ("currencyCode");+CREATE INDEX "payment_bankAccount_idx" ON "payment" ("bankAccount");+CREATE INDEX "payment_journalId_idx" ON "payment" ("journalId") WHERE "journalId" IS NOT NULL;+CREATE INDEX "payment_createdBy_idx" ON "payment" ("createdBy");+CREATE INDEX "payment_updatedBy_idx" ON "payment" ("updatedBy") WHERE "updatedBy" IS NOT NULL;+CREATE INDEX "payment_postedBy_idx" ON "payment" ("postedBy") WHERE "postedBy" IS NOT NULL;+CREATE INDEX "payment_voidedBy_idx" ON "payment" ("voidedBy") WHERE "voidedBy" IS NOT NULL;++-- memo+CREATE INDEX "memo_currencyCode_idx" ON "memo" ("currencyCode");+CREATE INDEX "memo_reasonAccount_idx" ON "memo" ("reasonAccount") WHERE "reasonAccount" IS NOT NULL;+CREATE INDEX "memo_journalId_idx" ON "memo" ("journalId") WHERE "journalId" IS NOT NULL;+CREATE INDEX "memo_createdBy_idx" ON "memo" ("createdBy");+CREATE INDEX "memo_updatedBy_idx" ON "memo" ("updatedBy") WHERE "updatedBy" IS NOT NULL;+CREATE INDEX "memo_postedBy_idx" ON "memo" ("postedBy") WHERE "postedBy" IS NOT NULL;+CREATE INDEX "memo_voidedBy_idx" ON "memo" ("voidedBy") WHERE "voidedBy" IS NOT NULL;++-- invoiceSettlement (paymentId / memoId / target* / appliedViaPaymentId already indexed)+CREATE INDEX "invoiceSettlement_createdBy_idx" ON "invoiceSettlement" ("createdBy");++-- accountDefault FK columns added by the AR/AP migration (one row per company, so+-- these are convention/consistency indexes — negligible runtime impact).+CREATE INDEX "accountDefault_customerWriteOffAccount_idx" ON "accountDefault" ("customerWriteOffAccount");+CREATE INDEX "accountDefault_supplierWriteOffAccount_idx" ON "accountDefault" ("supplierWriteOffAccount") WHERE "supplierWriteOffAccount" IS NOT NULL;+CREATE INDEX "accountDefault_realizedExchangeGainAccount_idx" ON "accountDefault" ("realizedExchangeGainAccount");+CREATE INDEX "accountDefault_realizedExchangeLossAccount_idx" ON "accountDefault" ("realizedExchangeLossAccount");diff --git a/packages/ee/src/accounting/providers/xero/entities/bill.ts b/packages/ee/src/accounting/providers/xero/entities/bill.tsindex ba9c4ee892..91c24ec714 100644--- a/packages/ee/src/accounting/providers/xero/entities/bill.ts+++ b/packages/ee/src/accounting/providers/xero/entities/bill.ts@@ -138,28 +138,31 @@ export class BillSyncer extends BaseEntitySyncer<// Fetch billsconst billRows = await this.database.selectFrom("purchaseInvoice")+ // `balance` is derived (totalAmount - posted payment applications) and+ // lives only on the `purchaseInvoices` view now, not the base table.+ .leftJoin("purchaseInvoices", "purchaseInvoices.id", "purchaseInvoice.id").select([- "id",- "companyId",- "invoiceId",- "supplierId",- "status",- "dateIssued",- "dateDue",- "datePaid",- "currencyCode",- "exchangeRate",- "subtotal",- "totalTax",- "totalDiscount",- "totalAmount",- "balance",- "supplierReference",- "updatedAt",- "customFields"+ "purchaseInvoice.id",+ "purchaseInvoice.companyId",+ "purchaseInvoice.invoiceId",+ "purchaseInvoice.supplierId",+ "purchaseInvoice.status",+ "purchaseInvoice.dateIssued",+ "purchaseInvoice.dateDue",+ "purchaseInvoice.datePaid",+ "purchaseInvoice.currencyCode",+ "purchaseInvoice.exchangeRate",+ "purchaseInvoice.subtotal",+ "purchaseInvoice.totalTax",+ "purchaseInvoice.totalDiscount",+ "purchaseInvoice.totalAmount",+ "purchaseInvoices.balance",+ "purchaseInvoice.supplierReference",+ "purchaseInvoice.updatedAt",+ "purchaseInvoice.customFields"])- .where("id", "in", ids)- .where("companyId", "=", this.companyId)+ .where("purchaseInvoice.id", "in", ids)+ .where("purchaseInvoice.companyId", "=", this.companyId).execute();if (billRows.length === 0) return new Map();@@ -524,7 +527,6 @@ export class BillSyncer extends BaseEntitySyncer<totalTax: data.totalTax,totalDiscount: data.totalDiscount,totalAmount: data.totalAmount,- balance: data.balance,supplierReference: data.supplierReference,updatedAt: new Date().toISOString()})@@ -594,7 +596,6 @@ export class BillSyncer extends BaseEntitySyncer<totalTax: data.totalTax ?? 0,totalDiscount: data.totalDiscount ?? 0,totalAmount: data.totalAmount ?? 0,- balance: data.balance ?? 0,supplierReference: data.supplierReference ?? null}).returning("id")diff --git a/packages/ee/src/accounting/providers/xero/entities/invoice.ts b/packages/ee/src/accounting/providers/xero/entities/invoice.tsindex 4101fb2139..2a51ce60a5 100644--- a/packages/ee/src/accounting/providers/xero/entities/invoice.ts+++ b/packages/ee/src/accounting/providers/xero/entities/invoice.ts@@ -163,6 +163,9 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<// Fetch invoice headersconst invoiceRows = await this.database.selectFrom("salesInvoice")+ // `balance` is derived (totalAmount - posted payment applications) and+ // lives only on the `salesInvoices` view now, not the base table.+ .leftJoin("salesInvoices", "salesInvoices.id", "salesInvoice.id").select(["salesInvoice.id","salesInvoice.invoiceId",@@ -179,7 +182,7 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<"salesInvoice.totalTax","salesInvoice.totalDiscount","salesInvoice.totalAmount",- "salesInvoice.balance",+ "salesInvoices.balance","salesInvoice.updatedAt"]).where("salesInvoice.id", "in", ids)@@ -463,7 +466,6 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<subtotal: data.subtotal,totalTax: data.totalTax,totalAmount: data.totalAmount,- balance: data.balance,currencyCode: data.currencyCode,exchangeRate: data.exchangeRate,updatedAt: new Date().toISOString()diff --git a/packages/jobs/src/inngest/functions/events/audit.ts b/packages/jobs/src/inngest/functions/events/audit.tsindex 0629099916..b7dc67830b 100644--- a/packages/jobs/src/inngest/functions/events/audit.ts+++ b/packages/jobs/src/inngest/functions/events/audit.ts@@ -338,8 +338,8 @@ export const auditFunction = inngest.createFunction(} else if (isIndirectTable(tableConfig)) {const { junction, fk, entityIdColumn } = tableConfig.resolve;- const { data: junctionRow } = await client- .from(junction as any)+ const { data: junctionRow } = await (client as any)+ .from(junction).select(entityIdColumn).eq(fk, record.event.recordId).limit(1)diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 844f5eb61f..1ed1884ec6 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -31,6 +31,10 @@ msgstr "\"Niemand wurde gefeuert, weil er es gekauft hat.\" Ein etablierter Komfmsgid "(excluded for this customer)"msgstr "(für diesen Kunden ausgeschlossen)"+#. placeholder {0}: ar.count+msgid "{0} customers with a balance"+msgstr "{0} Kunden mit einem Saldo"+#. placeholder {0}: rule.escalationDaysmsgid "{0} days"msgstr "{0} Tage"@@ -48,6 +52,10 @@ msgstr "{0} Bestellungen"msgid "{0} Processes"msgstr "{0} Prozesse"+#. placeholder {0}: ap.count+msgid "{0} suppliers with a balance"+msgstr "{0} Lieferanten mit einem Saldo"+#. placeholder {0}: lotEntities.length - inspectedmsgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "{0} nicht beprobte Entitäten werden freigegeben. Beprobte Annahmen bleiben verfügbar und beprobte Fehler bleiben abgelehnt."@@ -60,6 +68,12 @@ msgstr "{0} erfolgreich hochgeladen"msgid "{0} values missing"msgstr "{0} Werte fehlen"+msgid "{apOverduePct}% of payables"+msgstr "{apOverduePct}% der Verbindlichkeiten"++msgid "{arOverduePct}% of receivables"+msgstr "{arOverduePct}% der Forderungen"+msgid "{chainLabel}. Consider pointing this part directly at the final successor."msgstr "{chainLabel}. Erwägen Sie, diesen Teil direkt auf den endgültigen Nachfolger zu verweisen."@@ -743,6 +757,10 @@ msgstr "Ein Betrag, der Vermögenswerte/Ausgaben erhöht oder Verbindlichkeiten/msgid "Amount that increases liabilities/equity/revenue or decreases assets/expenses on this line."msgstr "Ein Betrag, der Verbindlichkeiten/Eigenkapital/Einnahmen erhöht oder Vermögenswerte/Ausgaben bei dieser Position verringert."+#. placeholder {0}: r.memoId+msgid "Amount to apply for {0}"+msgstr "Anzuwendender Betrag für {0}"+msgid "Amount Type"msgstr "Betragtyp"@@ -806,6 +824,12 @@ msgstr "Alles, was oben nicht explizit im Umfang aufgeführt ist"msgid "AP Clerk"msgstr "AP-Sachbearbeiter"+msgid "AP Outstanding"+msgstr "AP ausstehend"++msgid "AP Overdue"+msgstr "AP Überfällig"+msgid "API and Webhooks"msgstr "API und Webhooks"@@ -824,6 +848,19 @@ msgstr "API-Schlüssel"msgid "API keys for programmatic access to your Carbon data."msgstr "API-Schlüssel für programmgesteuerten Zugriff auf Ihre Carbon-Daten."+msgid "Applied"+msgstr "Angewendet"++#. placeholder {0}: r.invoiceId+msgid "Applied amount for {0}"+msgstr "Angewendeter Betrag für {0}"++msgid "Applied Date"+msgstr "Anwendungsdatum"++msgid "Applied To"+msgstr "Angewendet auf"+msgid "Applies to"msgstr "Gilt für"@@ -833,6 +870,12 @@ msgstr "Gilt für alle"msgid "Applies to all work centers"msgstr "Gilt für alle Arbeitszentren"+msgid "Apply available credits"+msgstr "Verfügbare Gutschriften anwenden"++msgid "Apply credits"+msgstr "Guthaben anwenden"+msgid "Apply payments and track aging"msgstr "Zahlungen anwenden und Fälligkeitsanalyse verfolgen"@@ -845,6 +888,12 @@ msgstr "Wenden Sie Regeln Oben An"msgid "Apply To"msgstr "Anwenden auf"+msgid "Apply to invoice"+msgstr "Auf Rechnung anwenden"++msgid "Apply to invoices"+msgstr "Auf Rechnungen anwenden"+msgid "Approaching {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB cap."msgstr "Nähert sich dem Limit von {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB."@@ -875,6 +924,12 @@ msgstr "AQL (Z1.4 / ISO 2859-1)"msgid "AR Clerk"msgstr "AR-Sachbearbeiter"+msgid "AR Outstanding"+msgstr "Forderungen ausstehend"++msgid "AR Overdue"+msgstr "AR Überfällig"+msgid "Archive"msgstr "Archiv"@@ -955,9 +1010,9 @@ msgstr "Sind Sie sicher, dass Sie {0} aus diesem Vorgang löschen möchten? Diesmsgid "Are you sure you want to delete {0}?"msgstr "Sind Sie sicher, dass Sie {0} löschen möchten?"+#. placeholder {0}: initialValues.memoId+#. placeholder {0}: initialValues.paymentId#. placeholder {0}: pickingList.pickingListId-#. placeholder {0}: routeData?.consumableSummary?.readableIdWithRevision-#. placeholder {0}: routeData?.customer?.name!msgid "Are you sure you want to delete {0}? This cannot be undone."msgstr "Sind Sie sicher, dass Sie {0} löschen möchten? Dies kann nicht rückgängig gemacht werden."@@ -1243,6 +1298,9 @@ msgstr "Sind Sie sicher?"msgid "As needed"msgstr "Nach Bedarf"+msgid "As of:"+msgstr "Zum Stand von:"+msgid "As the company owner, you can transfer ownership to another employee. This will give them full access to billing and administrative settings."msgstr "Als Unternehmenseigentümer können Sie das Eigentum an einen anderen Mitarbeiter übertragen. Dies gibt ihm vollständigen Zugriff auf Abrechnungs- und Verwaltungseinstellungen."@@ -1371,6 +1429,9 @@ msgstr "Audit-Protokolle"msgid "Authentication Error"msgstr "Authentifizierungsfehler"+msgid "Auto apply"+msgstr "Automatisch anwenden"+msgid "Auto Release"msgstr "Automatische Freigabe"@@ -1440,9 +1501,15 @@ msgstr "Rücklauf"msgid "Backups"msgstr "Sicherungen"+msgid "Balance"+msgstr "Saldo"+msgid "Balance Sheet"msgstr "Bilanz"+msgid "Balanced"+msgstr "Ausgeglichen"+msgid "Balloon"msgstr "Ballon"@@ -1464,6 +1531,9 @@ msgstr "Bank — Fremdwährung (Standard)"msgid "Bank — Local Currency (default)"msgstr "Bank — Landeswährung (Standard)"+msgid "Bank / Cash Account"+msgstr "Bank-/Bargeldkonto"+msgid "Bank account denominated in a foreign currency"msgstr "Bankkonto, das auf eine Fremdwährung lautet."@@ -1643,6 +1713,12 @@ msgstr "von {byUser}"msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."msgstr "Durch Annahme der Einladung stimmen Sie den <0>Nutzungsbedingungen</0> und der <1>Datenschutzrichtlinie</1> zu."+msgid "By Document Date"+msgstr "Nach Dokumentdatum"++msgid "By Due Date"+msgstr "Nach Fälligkeitsdatum"+msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"msgstr "Durch die Anmeldung stimmen Sie den <0>Nutzungsbedingungen</0> und der <1>Datenschutzrichtlinie</1> zu."@@ -1931,6 +2007,9 @@ msgstr "Suche löschen"msgid "Clear search query"msgstr "Suchanfrage löschen"+msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."+msgstr "Begleichen Sie diese Rechnung mit den gebuchten Gutschriften der Partei sowie mit Bargeld. Gutschriften werden direkt angewendet — keine Buchung erforderlich."+msgid "Clearing account between goods receipt and supplier invoice; balances when both have posted."msgstr "Verrechnungskonto zwischen Wareneingang und Lieferantenrechnung; wird ausgeglichen, wenn beide gebucht wurden."@@ -1977,6 +2056,9 @@ msgstr "Cloud oder Ihre selbst gehostete Umgebung."msgid "Code"msgstr "Code"+msgid "Collapse"+msgstr "Einklappen"+msgid "Collapse all"msgstr "Alle einklappen"@@ -2552,6 +2634,12 @@ msgstr "Dokumente konnten nicht geladen werden"msgid "Count"msgstr "Anzahl"+msgid "Counterparties"+msgstr "Gegenparteien"++msgid "Counterparty"+msgstr "Gegenpartei"+msgid "Country"msgstr "Land"@@ -2582,6 +2670,9 @@ msgstr "Erstellen Sie ein Angebot mit einer neuen Angebots-ID"msgid "Create Account"msgstr "Konto erstellen"+msgid "Create adjusting entry"+msgstr "Anpassungseintrag erstellen"+msgid "Create an account"msgstr "Konto erstellen"@@ -2755,12 +2846,21 @@ msgstr "Teil wird erstellt..."msgid "Credit"msgstr "Gutschrift"+msgid "Credit / Debit Memos"+msgstr "Gutschrift- / Lastschriftmemos"+msgid "Credit Account"msgstr "Gutschriftkonto"msgid "Credit account when labor/machine time is absorbed into WIP"msgstr "Gutschriftkonto, wenn Arbeits- / Maschinenzeit in WIP aufgenommen wird"+msgid "Credits & Debits"+msgstr "Gutschriften & Belastungen"++msgid "Credits applied"+msgstr "Angewendete Gutschriften"+msgid "Critical"msgstr "Kritisch"@@ -2935,6 +3035,9 @@ msgstr "Kundentypen"msgid "Customer Types"msgstr "Kundentypen"+msgid "Customer Write-Off (Bad Debt)"+msgstr "Kundenabschreibung (Forderungsausfälle)"+msgid "customers"msgstr "Kunden"@@ -3314,12 +3417,18 @@ msgstr "Materialform löschen"msgid "Delete Material Type"msgstr "Materialtyp löschen"+msgid "Delete Memo"+msgstr "Memo löschen"+msgid "Delete Part"msgstr "Teil löschen"msgid "Delete Partner"msgstr "Partner löschen"+msgid "Delete Payment"+msgstr "Zahlung löschen"+msgid "Delete Payment Term"msgstr "Zahlungsbedingung löschen"@@ -3566,6 +3675,12 @@ msgstr "Abmessungen"msgid "Direct"msgstr "Direkt"+msgid "Direction"+msgstr "Richtung"++msgid "Directions"+msgstr "Richtungen"+msgid "Disabled"msgstr "Deaktiviert"@@ -3584,6 +3699,10 @@ msgstr "Rabatttage"msgid "Discount Days after {selectedCalculationMethod}"msgstr "Rabatttage nach {selectedCalculationMethod}"+#. placeholder {0}: r.invoiceId+msgid "Discount for {0}"+msgstr "Rabatt für {0}"+msgid "Discount Percent"msgstr "Rabatt Prozent"@@ -3717,6 +3836,9 @@ msgstr "Ziehen Sie, um das Diagramm und die Funktionen zu ändern"msgid "Drag to zoom"msgstr "Zum Zoomen ziehen"+msgid "Drawing"+msgstr "Abheben"+msgid "Drawing Number"msgstr "Zeichnungsnummer"@@ -3952,6 +4074,9 @@ msgstr "Material Substance bearbeiten"msgid "Edit Material Type"msgstr "Material Type bearbeiten"+msgid "Edit Memo"+msgstr "Memo bearbeiten"+msgid "Edit Non Conformance Type"msgstr "Nichtkonformitätstyp bearbeiten"@@ -3961,6 +4086,9 @@ msgstr "Teil bearbeiten"msgid "Edit Partner"msgstr "Partner bearbeiten"+msgid "Edit Payment"+msgstr "Zahlung bearbeiten"+msgid "Edit Payment Term"msgstr "Zahlungsbedingung bearbeiten"@@ -4442,12 +4570,18 @@ msgstr "Erwarteter Eingang"msgid "Expected Receipt Date"msgstr "Erwartetes Eingangsdatum"+msgid "Expense account for customer balances written off as uncollectable on AR settlement"+msgstr "Aufwandskonto für Kundenguthaben, die bei der Debitorenausgleichung als uneinbringlich abgeschrieben werden"+msgid "Expense account for deferred tax adjustments on depreciation"msgstr "Aufwandskonto für aufgeschobene Steueranpassungen auf Abschreibungen"msgid "Expense account for equipment and facility maintenance"msgstr "Aufwandskonto für Ausrüstungs- und Anlagenwartung"+msgid "Expense account for FX losses when a payment settles a foreign-currency invoice at a less favorable rate"+msgstr "Ausgabenkonto für Devisenverluste, wenn eine Zahlung eine Rechnung in Fremdwährung zu einem ungünstigeren Kurs ausgleicht"+msgid "Expense account for non-inventory purchases (services, supplies)"msgstr "Aufwandskonto für Einkäufe ohne Lagerbestand (Dienstleistungen, Verbrauchsmaterial)"@@ -5028,9 +5162,15 @@ msgstr "Freitag"msgid "From {0}"msgstr "Von {0}"+msgid "From customer"+msgstr "Vom Kunden"+msgid "From Location"msgstr "Von Standort"+msgid "from on-account credit"+msgstr "aus dem Gutschrift-Konto"+msgid "From Storage Unit"msgstr "Von Lagereinheit"@@ -5040,6 +5180,9 @@ msgstr "Erfüllungsort"msgid "Fully trained for"msgstr "Vollständig geschult für"+msgid "FX G/L"+msgstr "FX G/L"+msgid "Gains and Losses"msgstr "Gewinne und Verluste (Standard)"@@ -5127,6 +5270,9 @@ msgstr "Navigation in Carbon"msgid "Getting set up"msgstr "Erste Schritte"+msgid "GL"+msgstr "GL"+msgid "GL Account"msgstr "Sachkonto"@@ -5241,6 +5387,12 @@ msgstr "GL-Ausgabenkonto für Käufe ohne Bestandsaufnahme (Verbrauchsmaterialiemsgid "GL liability account credited for sales tax collected from customers."msgstr "GL-Haftungskonto für Umsatzsteuer, die von Kunden eingezogen wird."+msgid "GL tie-out"+msgstr "GL-Abstimmung"++msgid "GL Tie-Out"+msgstr "GL-Abstimmung"+msgid "Go live right the first time — with our team alongside you"msgstr "Starten Sie richtig beim ersten Mal — mit unserem Team an Ihrer Seite"@@ -5773,6 +5925,9 @@ msgstr "Interne Referenz, um zu sehen, wo jedes Tool stärker ist. Nutzen Sie esmsgid "inv"msgstr "Inv"+msgid "Inv Rate"+msgstr "Rechnungskurs"+msgid "Invalid Invite"msgstr "Ungültige Einladung"@@ -5884,6 +6039,12 @@ msgstr "Fakturierte Status"msgid "Invoices"msgstr "Rechnungen"+msgid "Invoices this memo has been applied to. Click a row to open the document."+msgstr "Rechnungen, auf die dieses Memo angewendet wurde. Klicken Sie auf eine Zeile, um das Dokument zu öffnen."++msgid "Invoicing"+msgstr "Rechnungsstellung"+msgid "is"msgstr "ist"@@ -6451,6 +6612,13 @@ msgstr "Make-Artikel können nicht direkt in Rechnung gestellt werden. Ändern Smsgid "Make Method Version"msgstr "Herstellungsmethode-Version"+msgid "Make Payment"+msgstr "Zahlung leisten"++#. placeholder {0}: selectedInvoices.length+msgid "Make Payment · {0} invoices"+msgstr "Zahlung leisten · {0} Rechnungen"+#. placeholder {0}: selectedRevision.revisionmsgid "Make revision {0} default?"msgstr "Revision {0} als Standard festlegen?"@@ -6693,6 +6861,15 @@ msgstr "Besprechungsrhythmus"msgid "Members"msgstr "Mitglieder"+msgid "Memo"+msgstr "Memo"++msgid "Memo Date"+msgstr "Memo-Datum"++msgid "Memo ID"+msgstr "Memo-ID"+msgid "MES"msgstr "MES"@@ -6953,6 +7130,9 @@ msgstr "Neuer Verbrauchsstoff"msgid "New Contractor"msgstr "Neuer Auftragnehmer"+msgid "New Credit / Debit Memo"+msgstr "Neue Gutschrift / Lastschrift-Notiz"+msgid "New Custom Field"msgstr "Neues benutzerdefiniertes Feld"@@ -7061,6 +7241,9 @@ msgstr "Neuer Teil"msgid "New Password"msgstr "Neues Passwort"+msgid "New Payment"+msgstr "Neue Zahlung"+msgid "New Payment Term"msgstr "Neuer Zahlungsbegriff"@@ -7252,6 +7435,9 @@ msgstr "Keine aktiven Angebote"msgid "No addresses found"msgstr "Keine Adressen gefunden"+msgid "No applications. Payment will be on-account."+msgstr "Keine Anwendungen. Zahlung erfolgt auf Kontostand."+#. placeholder {0}: auditConfig.retentionDaysmsgid "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."msgstr "Noch keine archivierten Protokolle. Protokolle älter als {0} Tage werden automatisch archiviert und sind hier zum Download verfügbar."@@ -7370,6 +7556,9 @@ msgstr "Keine neuen Benachrichtigungen"msgid "No notes"msgstr "Keine Notizen"+msgid "No open invoices"+msgstr "Keine offenen Rechnungen"+msgid "No operations require picking at this location"msgstr "Keine Operationen erfordern Kommissionierung an diesem Standort"@@ -7397,6 +7586,12 @@ msgstr "Noch keine übergeordneten Quellen aufgezeichnet. Klicken Sie auf der Plmsgid "No part ID"msgstr "Keine Teile-ID"+msgid "No payables"+msgstr "Keine Verbindlichkeiten"++msgid "No payments yet."+msgstr "Noch keine Zahlungen."+msgid "No planning data"msgstr "Keine Planungsdaten"@@ -7421,6 +7616,9 @@ msgstr "Kein Angebotgrund"msgid "No Quote Reasons"msgstr "Keine Angebotsgründe"+msgid "No receivables"+msgstr "Keine Forderungen"+msgid "No remaining entities to inspect."msgstr "Keine verbleibenden Entitäten zur Überprüfung."@@ -7598,6 +7796,9 @@ msgstr "In Verkaufsauftrag"msgid "On Storage Unit"msgstr "Auf Lagereinheit"+msgid "On-account credit available"+msgstr "Verfügbarer Kontokorrentkreditrahmen"+msgid "On-hand counts"msgstr "Verfügbare Bestände"@@ -7818,6 +8019,12 @@ msgstr "Bestellungen eingereicht"msgid "Origin"msgstr "Ursprung"+msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"+msgstr "Sonstige Einnahmen für Wechselkursgewinne, wenn eine Zahlung eine Rechnung in Fremdwährung zu einem günstigeren Kurs ausgleicht"++msgid "Other Income account for vendor balances cleared without full payment on AP settlement"+msgstr "Sonstige Einnahmenkonto für Lieferantensalden, die ohne vollständige Zahlung bei AP-Ausgleich gelöscht wurden"+msgid "Other Type"msgstr "Sonstiger Typ"@@ -7839,6 +8046,9 @@ msgstr "Die Ausgabe überlebt ihre Rohstoffe nie. Fällt auf die feste Dauer zurmsgid "Outside operation"msgstr "Gemeinkostenabweichung"+msgid "Over-applied by"+msgstr "Überangewendet um"+msgid "Overdue"msgstr "Überfällig"@@ -7975,6 +8185,9 @@ msgstr "Teile & Artikel"msgid "Parts, materials, and how you classify them."msgstr "Teile, Materialien und wie Sie diese klassifizieren."+msgid "Party Type"+msgstr "Parteityp"+msgid "Pass"msgstr "Bestanden"@@ -7984,17 +8197,29 @@ msgstr "Bestanden · erneut öffnen"msgid "Path"msgstr "Pfad"+msgid "Pay Rate"+msgstr "Zahlungskurs"+msgid "Payables"msgstr "Kreditorenkonten (Standard)"msgid "Payables (default)"msgstr "Zahlungsbedingung"+msgid "Payables aging"+msgstr "Verbindlichkeiten nach Fälligkeit"+msgid "Payment"msgstr "Zahlung"-msgid "Payment Method"-msgstr "Zahlungsmethode"+msgid "Payment Applications"+msgstr "Zahlungsanwendungen"++msgid "Payment Date"+msgstr "Zahlungsdatum"++msgid "Payment ID"+msgstr "Zahlungs-ID"msgid "payment term"msgstr "Zahlungsbedingungen"@@ -8011,6 +8236,12 @@ msgstr "Zahlungsbedingungen"msgid "Payment terms like Net 30 or due on receipt"msgstr "Zahlungsbedingungen wie Net 30 oder zahlbar bei Erhalt"+msgid "Payments"+msgstr "Zahlungen"++msgid "Payments and credits applied to this invoice. Click a row to open the source document."+msgstr "Zahlungen und Gutschriften, die auf diese Rechnung angewendet wurden. Klicken Sie auf eine Zeile, um das Quelldokument zu öffnen."+msgid "PDF"msgstr "PDF"@@ -8672,6 +8903,9 @@ msgstr "Beschaffung und automatische Planung"msgid "Purchasing Contact"msgstr "Einkaufskontakt"+msgid "Purchasing Invoices"+msgstr "Einkaufsrechnungen"+msgid "Purchasing Unit of Measure"msgstr "Einkaufsmaßeinheit"@@ -8866,9 +9100,18 @@ msgstr "Echtzeit-Bestandsverwaltung und Shopfloor-Sichtbarkeit"msgid "Real-time questions during hypercare"msgstr "Echtzeitfragen während der Hypercare"+msgid "Realized Exchange Gain"+msgstr "Realisierter Wechselkursgewinn"++msgid "Realized Exchange Loss"+msgstr "Realisierter Wechselkursverlust"+msgid "Reason"msgstr "Grund"+msgid "Reason Account"+msgstr "Grund-Konto"+msgid "Reason for declining (Optional)"msgstr "Grund für Ablehnung (Optional)"@@ -8911,6 +9154,9 @@ msgstr "Debitorenkonten (Standard)"msgid "Receivables (default)"msgstr "Abstimmung einer Bestellung mit dem Empfangenen und Rechnungsgestellten — implizit in Carbon über die Zeilenmengen und GR/IR-Bilanz."+msgid "Receivables aging"+msgstr "Forderungen nach Alter"+msgid "Receive"msgstr "Empfangen"@@ -8921,6 +9167,13 @@ msgstr "Empfangen Sie {0} im Bestand"msgid "Receive against a PO and update inventory"msgstr "Gegen eine Bestellung empfangen und Bestand aktualisieren"+msgid "Receive Payment"+msgstr "Zahlung erhalten"++#. placeholder {0}: selectedInvoices.length+msgid "Receive Payment · {0} invoices"+msgstr "Zahlung erhalten · {0} Rechnungen"+msgid "Receive to Inventory"msgstr "In Bestand empfangen"@@ -8944,6 +9197,9 @@ msgstr "Empfangsort"msgid "Recent"msgstr "Kürzlich"+msgid "Recent payments"+msgstr "Kürzliche Zahlungen"+msgid "Recently Created"msgstr "Kürzlich erstellt"@@ -8953,6 +9209,12 @@ msgstr "Abschreibungsdauer"msgid "Record"msgstr "Aufnahme"+msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."+msgstr "Erfassen Sie eine Gutschrift oder Belastungsmitteilung für einen Kunden oder Lieferanten. Anwendungen auf bestimmte Rechnungen werden nach der Erstellung der Mitteilung hinzugefügt."++msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."+msgstr "Erfassen Sie Bargeld, das von einem Kunden (Quittung) eingegangen ist oder an einen Lieferanten (Auszahlung) gezahlt wurde. Anwendungen auf bestimmte Rechnungen werden nach der Erstellung der Zahlung hinzugefügt."+msgid "Record deleted"msgstr "Datensatz gelöscht"@@ -9037,6 +9299,9 @@ msgstr "Auftrag freigeben"msgid "Released"msgstr "Freigegeben"+msgid "Remaining"+msgstr "Verbleibend"+msgid "Remaining after split stays on the original row."msgstr "Verbleibende Menge bleibt in der ursprünglichen Zeile."@@ -9583,6 +9848,9 @@ msgstr "Speichern & Schließen"msgid "Save and Overwrite"msgstr "Speichern und Überschreiben"+msgid "Save applications"+msgstr "Anwendungen speichern"+msgid "Save contacts"msgstr "Kontakte speichern"@@ -9824,6 +10092,15 @@ msgstr "Messuhr auswählen"msgid "Select groups or individuals"msgstr "Gruppen oder Einzelpersonen auswählen"+msgid "Select invoice"+msgstr "Rechnung auswählen"++msgid "Select invoices from a single counterparty"+msgstr "Wählen Sie Rechnungen von einem einzelnen Geschäftspartner aus"++msgid "Select invoices in a single currency"+msgstr "Wählen Sie Rechnungen in einer einzigen Währung aus"+msgid "Select Item Type"msgstr "Elementtyp auswählen"@@ -9860,6 +10137,9 @@ msgstr "Oberflächen auswählen"msgid "Select the groups that should complete this training"msgstr "Wählen Sie die Gruppen aus, die diese Schulung absolvieren sollen"+msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."+msgstr "Wählen Sie die Rechnungen aus, die diese Zahlung begleicht. Rabatt und Abschreibung sind in Rechnungswährung."+msgid "Select value"msgstr "Wert auswählen"@@ -10575,6 +10855,9 @@ msgstr "Fremdvergabe-Abweichung"msgid "Subcontracting Variance (default)"msgstr "Fremdvergabe-Abweichung (Standard)"+msgid "Subledger"+msgstr "Nebenbuch"+msgid "Submit anonymously"msgstr "Anonym einreichen"@@ -11597,6 +11880,9 @@ msgstr "Es gibt keine aktiven Lieferantenofferten zum Vergleichen für diese Anfmsgid "There are outside operations associated with this job that have no suppliers. Please assign a supplier to each outside operation before releasing it."msgstr "Es gibt externe Operationen, die mit diesem Auftrag verknüpft sind und keine Lieferanten haben. Bitte weisen Sie jedem externen Betrieb einen Lieferanten zu, bevor Sie ihn freigeben."+msgid "There's nothing outstanding to apply these credits to."+msgstr "Es gibt nichts Ausstehende, auf das diese Gutschriften angewendet werden können."+msgid "These custom fields will only be available for entities with the same tags"msgstr "Diese benutzerdefinierten Felder sind nur für Entitäten mit denselben Tags verfügbar"@@ -11612,6 +11898,9 @@ msgstr "Diese Aufträge haben Operationen, die diesem Arbeitszentrum zugewiesenmsgid "This completes the Discovery step."msgstr "Dies schließt den Discovery-Schritt ab."+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."+msgstr "Dieser Geschäftspartner hat keine ausstehenden Forderungen — die Zahlung wird auf Kontokorrent verbucht."+msgid "This information will be used on document headers"msgstr "Diese Informationen werden in Dokumentkopfzeilen verwendet"@@ -11720,6 +12009,9 @@ msgstr "Donnerstag"msgid "Tie shipments through to an invoice with no re-keying"msgstr "Lieferungen direkt mit einer Rechnung verknüpfen ohne erneute Eingabe"+msgid "Tie-Out"+msgstr "Abstimmung"+msgid "Tightened"msgstr "Gestrafft"@@ -11756,6 +12048,9 @@ msgstr "Zum Versand und Empfang"msgid "To Storage Unit"msgstr "Zu Lagereinheit"+msgid "To supplier"+msgstr "An Lieferant"+msgid "Today"msgstr "Heute"@@ -11825,6 +12120,9 @@ msgstr "Klassifizierung auf oberster Ebene (Anlage / Verbindlichkeit / Eigenkapimsgid "Total"msgstr "Gesamt"+msgid "Total Amount"+msgstr "Gesamtbetrag"+msgid "Total capitalized cost of the asset (purchase price plus freight, install, and other costs that become part of book value)."msgstr "Gesamtkapitalisierten Kosten des Vermögenswerts (Kaufpreis plus Fracht, Installation und andere Kosten, die Teil des Buchwerts werden)."@@ -11852,6 +12150,9 @@ msgstr "Gesamtmenge, die über alle aktiven Aufträge und Kundenaufträge an diemsgid "Total:"msgstr "Gesamt:"+msgid "Totals"+msgstr "Summen"+msgid "Traceability"msgstr "Rückverfolgbarkeit"@@ -12008,6 +12309,12 @@ msgstr "Typen"msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."msgstr "Nicht beprobte Entitäten bleiben in Warteschleife, damit Sie weiterhin inspizieren und später dispositieren können. Beprobte Ergebnisse bleiben erhalten."+msgid "Unapplied"+msgstr "Nicht angewendet"++msgid "Unapplied:"+msgstr "Nicht angewendet:"+msgid "Unapproved Supplier"msgstr "Nicht genehmigter Lieferant"@@ -12351,6 +12658,9 @@ msgstr "Umsatzsteuer-Identifikationsnummer; erforderlich auf EU-Rechnungen fürmsgid "Values"msgstr "Werte"+msgid "Variance"+msgstr "Abweichung"+msgid "Variance between actual and standard BOM component consumption"msgstr "Abweichung zwischen tatsächlichem und Standard-BOM-Komponentenverbrauch"@@ -12372,6 +12682,9 @@ msgstr "Abweichung bei Fremdbearbeitungskosten"msgid "VAT Number"msgstr "Umsatzsteuer-Identifikationsnummer"+msgid "Vendor Write-Off Income"+msgstr "Lieferantenschreib-Off-Ertrag"+msgid "Verification Error"msgstr "Verifizierungsfehler"@@ -12453,6 +12766,9 @@ msgstr "Listen anzeigen"msgid "View maintenance dispatch"msgstr "Wartungseinsatz anzeigen"+msgid "View Memo"+msgstr "Memo anzeigen"+msgid "View missing values"msgstr "Fehlende Werte anzeigen"@@ -12474,6 +12790,9 @@ msgstr "Offene Angebote anzeigen"msgid "View Open RFQs"msgstr "Offene Anfragen anzeigen"+msgid "View Payment"+msgstr "Zahlung anzeigen"+msgid "View permissions"msgstr "Anzeigeberechtigungen"@@ -13042,9 +13361,19 @@ msgstr "Schlechteste Maschinen"msgid "Write-Down Account"msgstr "Wertberichtigungskonto"+msgid "Write-off"+msgstr "Abschreibung"++msgid "Write-Off"+msgstr "Abschreibung"+msgid "Write-Off Account"msgstr "Abschreibungskonto"+#. placeholder {0}: r.invoiceId+msgid "Write-off for {0}"+msgstr "Abschreibung für {0}"+msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."msgstr "Den Wert eines Vermögenswerts über seine Lebensdauer abschreiben — ein monatlicher Batch, den Sie erstellen, als Entwurf überprüfen und dann buchen."diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex aa670a19c1..a2d1203395 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -31,6 +31,10 @@ msgstr "\"Nobody got fired for buying it.\" An incumbent comfort factor."msgid "(excluded for this customer)"msgstr "(excluded for this customer)"+#. placeholder {0}: ar.count+msgid "{0} customers with a balance"+msgstr "{0} customers with a balance"+#. placeholder {0}: rule.escalationDaysmsgid "{0} days"msgstr "{0} days"@@ -48,6 +52,10 @@ msgstr "{0} orders"msgid "{0} Processes"msgstr "{0} Processes"+#. placeholder {0}: ap.count+msgid "{0} suppliers with a balance"+msgstr "{0} suppliers with a balance"+#. placeholder {0}: lotEntities.length - inspectedmsgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."@@ -60,6 +68,12 @@ msgstr "{0} uploaded successfully"msgid "{0} values missing"msgstr "{0} values missing"+msgid "{apOverduePct}% of payables"+msgstr "{apOverduePct}% of payables"++msgid "{arOverduePct}% of receivables"+msgstr "{arOverduePct}% of receivables"+msgid "{chainLabel}. Consider pointing this part directly at the final successor."msgstr "{chainLabel}. Consider pointing this part directly at the final successor."@@ -743,6 +757,10 @@ msgstr "Amount that increases assets/expenses or decreases liabilities/equity/remsgid "Amount that increases liabilities/equity/revenue or decreases assets/expenses on this line."msgstr "Amount that increases liabilities/equity/revenue or decreases assets/expenses on this line."+#. placeholder {0}: r.memoId+msgid "Amount to apply for {0}"+msgstr "Amount to apply for {0}"+msgid "Amount Type"msgstr "Amount Type"@@ -806,6 +824,12 @@ msgstr "Anything not explicitly listed in scope above"msgid "AP Clerk"msgstr "AP Clerk"+msgid "AP Outstanding"+msgstr "AP Outstanding"++msgid "AP Overdue"+msgstr "AP Overdue"+msgid "API and Webhooks"msgstr "API and Webhooks"@@ -824,6 +848,19 @@ msgstr "API Keys"msgid "API keys for programmatic access to your Carbon data."msgstr "API keys for programmatic access to your Carbon data."+msgid "Applied"+msgstr "Applied"++#. placeholder {0}: r.invoiceId+msgid "Applied amount for {0}"+msgstr "Applied amount for {0}"++msgid "Applied Date"+msgstr "Applied Date"++msgid "Applied To"+msgstr "Applied To"+msgid "Applies to"msgstr "Applies to"@@ -833,6 +870,12 @@ msgstr "Applies to all"msgid "Applies to all work centers"msgstr "Applies to all work centers"+msgid "Apply available credits"+msgstr "Apply available credits"++msgid "Apply credits"+msgstr "Apply credits"+msgid "Apply payments and track aging"msgstr "Apply payments and track aging"@@ -845,6 +888,12 @@ msgstr "Apply Rules On Top"msgid "Apply To"msgstr "Apply To"+msgid "Apply to invoice"+msgstr "Apply to invoice"++msgid "Apply to invoices"+msgstr "Apply to invoices"+msgid "Approaching {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB cap."msgstr "Approaching {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB cap."@@ -875,6 +924,12 @@ msgstr "AQL (Z1.4 / ISO 2859-1)"msgid "AR Clerk"msgstr "AR Clerk"+msgid "AR Outstanding"+msgstr "AR Outstanding"++msgid "AR Overdue"+msgstr "AR Overdue"+msgid "Archive"msgstr "Archive"@@ -955,9 +1010,9 @@ msgstr "Are you sure you want to delete {0} from this operation? This cannot bemsgid "Are you sure you want to delete {0}?"msgstr "Are you sure you want to delete {0}?"+#. placeholder {0}: initialValues.memoId+#. placeholder {0}: initialValues.paymentId#. placeholder {0}: pickingList.pickingListId-#. placeholder {0}: routeData?.consumableSummary?.readableIdWithRevision-#. placeholder {0}: routeData?.customer?.name!msgid "Are you sure you want to delete {0}? This cannot be undone."msgstr "Are you sure you want to delete {0}? This cannot be undone."@@ -1243,6 +1298,9 @@ msgstr "Are you sure?"msgid "As needed"msgstr "As needed"+msgid "As of:"+msgstr "As of:"+msgid "As the company owner, you can transfer ownership to another employee. This will give them full access to billing and administrative settings."msgstr "As the company owner, you can transfer ownership to another employee. This will give them full access to billing and administrative settings."@@ -1371,6 +1429,9 @@ msgstr "Audit Logs"msgid "Authentication Error"msgstr "Authentication Error"+msgid "Auto apply"+msgstr "Auto apply"+msgid "Auto Release"msgstr "Auto Release"@@ -1440,9 +1501,15 @@ msgstr "Backflush"msgid "Backups"msgstr "Backups"+msgid "Balance"+msgstr "Balance"+msgid "Balance Sheet"msgstr "Balance Sheet"+msgid "Balanced"+msgstr "Balanced"+msgid "Balloon"msgstr "Balloon"@@ -1464,6 +1531,9 @@ msgstr "Bank — Foreign Currency (default)"msgid "Bank — Local Currency (default)"msgstr "Bank — Local Currency (default)"+msgid "Bank / Cash Account"+msgstr "Bank / Cash Account"+msgid "Bank account denominated in a foreign currency"msgstr "Bank account denominated in a foreign currency"@@ -1643,6 +1713,12 @@ msgstr "by {byUser}"msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."msgstr "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."+msgid "By Document Date"+msgstr "By Document Date"++msgid "By Due Date"+msgstr "By Due Date"+msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"msgstr "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"@@ -1931,6 +2007,9 @@ msgstr "Clear search"msgid "Clear search query"msgstr "Clear search query"+msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."+msgstr "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."+msgid "Clearing account between goods receipt and supplier invoice; balances when both have posted."msgstr "Clearing account between goods receipt and supplier invoice; balances when both have posted."@@ -1977,6 +2056,9 @@ msgstr "Cloud, or your self-hosted environment."msgid "Code"msgstr "Code"+msgid "Collapse"+msgstr "Collapse"+msgid "Collapse all"msgstr "Collapse all"@@ -2552,6 +2634,12 @@ msgstr "Couldn't load documents"msgid "Count"msgstr "Count"+msgid "Counterparties"+msgstr "Counterparties"++msgid "Counterparty"+msgstr "Counterparty"+msgid "Country"msgstr "Country"@@ -2582,6 +2670,9 @@ msgstr "Create a quote with a new quote ID"msgid "Create Account"msgstr "Create Account"+msgid "Create adjusting entry"+msgstr "Create adjusting entry"+msgid "Create an account"msgstr "Create an account"@@ -2755,12 +2846,21 @@ msgstr "Creating part..."msgid "Credit"msgstr "Credit"+msgid "Credit / Debit Memos"+msgstr "Credit / Debit Memos"+msgid "Credit Account"msgstr "Credit Account"msgid "Credit account when labor/machine time is absorbed into WIP"msgstr "Credit account when labor/machine time is absorbed into WIP"+msgid "Credits & Debits"+msgstr "Credits & Debits"++msgid "Credits applied"+msgstr "Credits applied"+msgid "Critical"msgstr "Critical"@@ -2935,6 +3035,9 @@ msgstr "customer types"msgid "Customer Types"msgstr "Customer Types"+msgid "Customer Write-Off (Bad Debt)"+msgstr "Customer Write-Off (Bad Debt)"+msgid "customers"msgstr "customers"@@ -3314,12 +3417,18 @@ msgstr "Delete Material Shape"msgid "Delete Material Type"msgstr "Delete Material Type"+msgid "Delete Memo"+msgstr "Delete Memo"+msgid "Delete Part"msgstr "Delete Part"msgid "Delete Partner"msgstr "Delete Partner"+msgid "Delete Payment"+msgstr "Delete Payment"+msgid "Delete Payment Term"msgstr "Delete Payment Term"@@ -3566,6 +3675,12 @@ msgstr "Dimensions"msgid "Direct"msgstr "Direct"+msgid "Direction"+msgstr "Direction"++msgid "Directions"+msgstr "Directions"+msgid "Disabled"msgstr "Disabled"@@ -3584,6 +3699,10 @@ msgstr "Discount Days"msgid "Discount Days after {selectedCalculationMethod}"msgstr "Discount Days after {selectedCalculationMethod}"+#. placeholder {0}: r.invoiceId+msgid "Discount for {0}"+msgstr "Discount for {0}"+msgid "Discount Percent"msgstr "Discount Percent"@@ -3717,6 +3836,9 @@ msgstr "Drag to resize diagram and features"msgid "Drag to zoom"msgstr "Drag to zoom"+msgid "Drawing"+msgstr "Drawing"+msgid "Drawing Number"msgstr "Drawing Number"@@ -3952,6 +4074,9 @@ msgstr "Edit Material Substance"msgid "Edit Material Type"msgstr "Edit Material Type"+msgid "Edit Memo"+msgstr "Edit Memo"+msgid "Edit Non Conformance Type"msgstr "Edit Non Conformance Type"@@ -3961,6 +4086,9 @@ msgstr "Edit Part"msgid "Edit Partner"msgstr "Edit Partner"+msgid "Edit Payment"+msgstr "Edit Payment"+msgid "Edit Payment Term"msgstr "Edit Payment Term"@@ -4442,12 +4570,18 @@ msgstr "Expected Receipt"msgid "Expected Receipt Date"msgstr "Expected Receipt Date"+msgid "Expense account for customer balances written off as uncollectable on AR settlement"+msgstr "Expense account for customer balances written off as uncollectable on AR settlement"+msgid "Expense account for deferred tax adjustments on depreciation"msgstr "Expense account for deferred tax adjustments on depreciation"msgid "Expense account for equipment and facility maintenance"msgstr "Expense account for equipment and facility maintenance"+msgid "Expense account for FX losses when a payment settles a foreign-currency invoice at a less favorable rate"+msgstr "Expense account for FX losses when a payment settles a foreign-currency invoice at a less favorable rate"+msgid "Expense account for non-inventory purchases (services, supplies)"msgstr "Expense account for non-inventory purchases (services, supplies)"@@ -5028,9 +5162,15 @@ msgstr "Friday"msgid "From {0}"msgstr "From {0}"+msgid "From customer"+msgstr "From customer"+msgid "From Location"msgstr "From Location"+msgid "from on-account credit"+msgstr "from on-account credit"+msgid "From Storage Unit"msgstr "From Storage Unit"@@ -5040,6 +5180,9 @@ msgstr "Fulfillment Location"msgid "Fully trained for"msgstr "Fully trained for"+msgid "FX G/L"+msgstr "FX G/L"+msgid "Gains and Losses"msgstr "Gains and Losses"@@ -5127,6 +5270,9 @@ msgstr "Getting around Carbon"msgid "Getting set up"msgstr "Getting set up"+msgid "GL"+msgstr "GL"+msgid "GL Account"msgstr "GL Account"@@ -5241,6 +5387,12 @@ msgstr "GL expense account for non-inventory purchases (supplies, services)."msgid "GL liability account credited for sales tax collected from customers."msgstr "GL liability account credited for sales tax collected from customers."+msgid "GL tie-out"+msgstr "GL tie-out"++msgid "GL Tie-Out"+msgstr "GL Tie-Out"+msgid "Go live right the first time — with our team alongside you"msgstr "Go live right the first time — with our team alongside you"@@ -5773,6 +5925,9 @@ msgstr "Internal reference for where each tool is stronger. Use it to set expectmsgid "inv"msgstr "inv"+msgid "Inv Rate"+msgstr "Inv Rate"+msgid "Invalid Invite"msgstr "Invalid Invite"@@ -5884,6 +6039,12 @@ msgstr "Invoiced Statuses"msgid "Invoices"msgstr "Invoices"+msgid "Invoices this memo has been applied to. Click a row to open the document."+msgstr "Invoices this memo has been applied to. Click a row to open the document."++msgid "Invoicing"+msgstr "Invoicing"+msgid "is"msgstr "is"@@ -6451,6 +6612,13 @@ msgstr "Make items cannot be invoiced directly. Change method to Pick to continumsgid "Make Method Version"msgstr "Make Method Version"+msgid "Make Payment"+msgstr "Make Payment"++#. placeholder {0}: selectedInvoices.length+msgid "Make Payment · {0} invoices"+msgstr "Make Payment · {0} invoices"+#. placeholder {0}: selectedRevision.revisionmsgid "Make revision {0} default?"msgstr "Make revision {0} default?"@@ -6693,6 +6861,15 @@ msgstr "Meeting cadence"msgid "Members"msgstr "Members"+msgid "Memo"+msgstr "Memo"++msgid "Memo Date"+msgstr "Memo Date"++msgid "Memo ID"+msgstr "Memo ID"+msgid "MES"msgstr "MES"@@ -6953,6 +7130,9 @@ msgstr "New Consumable"msgid "New Contractor"msgstr "New Contractor"+msgid "New Credit / Debit Memo"+msgstr "New Credit / Debit Memo"+msgid "New Custom Field"msgstr "New Custom Field"@@ -7061,6 +7241,9 @@ msgstr "New Part"msgid "New Password"msgstr "New Password"+msgid "New Payment"+msgstr "New Payment"+msgid "New Payment Term"msgstr "New Payment Term"@@ -7252,6 +7435,9 @@ msgstr "No Active Quotes"msgid "No addresses found"msgstr "No addresses found"+msgid "No applications. Payment will be on-account."+msgstr "No applications. Payment will be on-account."+#. placeholder {0}: auditConfig.retentionDaysmsgid "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."msgstr "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."@@ -7370,6 +7556,9 @@ msgstr "No new notifications"msgid "No notes"msgstr "No notes"+msgid "No open invoices"+msgstr "No open invoices"+msgid "No operations require picking at this location"msgstr "No operations require picking at this location"@@ -7397,6 +7586,12 @@ msgstr "No parent sources recorded yet. Click Recalculate on the planning page tmsgid "No part ID"msgstr "No part ID"+msgid "No payables"+msgstr "No payables"++msgid "No payments yet."+msgstr "No payments yet."+msgid "No planning data"msgstr "No planning data"@@ -7421,6 +7616,9 @@ msgstr "No Quote Reason"msgid "No Quote Reasons"msgstr "No Quote Reasons"+msgid "No receivables"+msgstr "No receivables"+msgid "No remaining entities to inspect."msgstr "No remaining entities to inspect."@@ -7598,6 +7796,9 @@ msgstr "On Sales Order"msgid "On Storage Unit"msgstr "On Storage Unit"+msgid "On-account credit available"+msgstr "On-account credit available"+msgid "On-hand counts"msgstr "On-hand counts"@@ -7818,6 +8019,12 @@ msgstr "Orders submitted"msgid "Origin"msgstr "Origin"+msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"+msgstr "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"++msgid "Other Income account for vendor balances cleared without full payment on AP settlement"+msgstr "Other Income account for vendor balances cleared without full payment on AP settlement"+msgid "Other Type"msgstr "Other Type"@@ -7839,6 +8046,9 @@ msgstr "Output never outlasts its raw materials. Falls back to the fixed duratiomsgid "Outside operation"msgstr "Outside operation"+msgid "Over-applied by"+msgstr "Over-applied by"+msgid "Overdue"msgstr "Overdue"@@ -7975,6 +8185,9 @@ msgstr "Parts & items"msgid "Parts, materials, and how you classify them."msgstr "Parts, materials, and how you classify them."+msgid "Party Type"+msgstr "Party Type"+msgid "Pass"msgstr "Pass"@@ -7984,17 +8197,29 @@ msgstr "Passed · reopen"msgid "Path"msgstr "Path"+msgid "Pay Rate"+msgstr "Pay Rate"+msgid "Payables"msgstr "Payables"msgid "Payables (default)"msgstr "Payables (default)"+msgid "Payables aging"+msgstr "Payables aging"+msgid "Payment"msgstr "Payment"-msgid "Payment Method"-msgstr "Payment Method"+msgid "Payment Applications"+msgstr "Payment Applications"++msgid "Payment Date"+msgstr "Payment Date"++msgid "Payment ID"+msgstr "Payment ID"msgid "payment term"msgstr "payment term"@@ -8011,6 +8236,12 @@ msgstr "Payment Terms"msgid "Payment terms like Net 30 or due on receipt"msgstr "Payment terms like Net 30 or due on receipt"+msgid "Payments"+msgstr "Payments"++msgid "Payments and credits applied to this invoice. Click a row to open the source document."+msgstr "Payments and credits applied to this invoice. Click a row to open the source document."+msgid "PDF"msgstr "PDF"@@ -8672,6 +8903,9 @@ msgstr "Purchasing and auto-planning"msgid "Purchasing Contact"msgstr "Purchasing Contact"+msgid "Purchasing Invoices"+msgstr "Purchasing Invoices"+msgid "Purchasing Unit of Measure"msgstr "Purchasing Unit of Measure"@@ -8866,9 +9100,18 @@ msgstr "Real-time inventory and shop-floor visibility"msgid "Real-time questions during hypercare"msgstr "Real-time questions during hypercare"+msgid "Realized Exchange Gain"+msgstr "Realized Exchange Gain"++msgid "Realized Exchange Loss"+msgstr "Realized Exchange Loss"+msgid "Reason"msgstr "Reason"+msgid "Reason Account"+msgstr "Reason Account"+msgid "Reason for declining (Optional)"msgstr "Reason for declining (Optional)"@@ -8911,6 +9154,9 @@ msgstr "Receivables"msgid "Receivables (default)"msgstr "Receivables (default)"+msgid "Receivables aging"+msgstr "Receivables aging"+msgid "Receive"msgstr "Receive"@@ -8921,6 +9167,13 @@ msgstr "Receive {0} to Inventory"msgid "Receive against a PO and update inventory"msgstr "Receive against a PO and update inventory"+msgid "Receive Payment"+msgstr "Receive Payment"++#. placeholder {0}: selectedInvoices.length+msgid "Receive Payment · {0} invoices"+msgstr "Receive Payment · {0} invoices"+msgid "Receive to Inventory"msgstr "Receive to Inventory"@@ -8944,6 +9197,9 @@ msgstr "Receiving Location"msgid "Recent"msgstr "Recent"+msgid "Recent payments"+msgstr "Recent payments"+msgid "Recently Created"msgstr "Recently Created"@@ -8953,6 +9209,12 @@ msgstr "Reconciling a purchase order against what was received and invoiced —msgid "Record"msgstr "Record"+msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."+msgstr "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."++msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."+msgstr "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."+msgid "Record deleted"msgstr "Record deleted"@@ -9037,6 +9299,9 @@ msgstr "Release Job"msgid "Released"msgstr "Released"+msgid "Remaining"+msgstr "Remaining"+msgid "Remaining after split stays on the original row."msgstr "Remaining after split stays on the original row."@@ -9583,6 +9848,9 @@ msgstr "Save & Close"msgid "Save and Overwrite"msgstr "Save and Overwrite"+msgid "Save applications"+msgstr "Save applications"+msgid "Save contacts"msgstr "Save contacts"@@ -9824,6 +10092,15 @@ msgstr "Select Gauge"msgid "Select groups or individuals"msgstr "Select groups or individuals"+msgid "Select invoice"+msgstr "Select invoice"++msgid "Select invoices from a single counterparty"+msgstr "Select invoices from a single counterparty"++msgid "Select invoices in a single currency"+msgstr "Select invoices in a single currency"+msgid "Select Item Type"msgstr "Select Item Type"@@ -9860,6 +10137,9 @@ msgstr "Select surfaces"msgid "Select the groups that should complete this training"msgstr "Select the groups that should complete this training"+msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."+msgstr "Select the invoices this payment settles. Discount and write-off are in invoice currency."+msgid "Select value"msgstr "Select value"@@ -10575,6 +10855,9 @@ msgstr "Subcontracting Variance"msgid "Subcontracting Variance (default)"msgstr "Subcontracting Variance (default)"+msgid "Subledger"+msgstr "Subledger"+msgid "Submit anonymously"msgstr "Submit anonymously"@@ -11597,6 +11880,9 @@ msgstr "There are no active supplier quotes to compare for this RFQ."msgid "There are outside operations associated with this job that have no suppliers. Please assign a supplier to each outside operation before releasing it."msgstr "There are outside operations associated with this job that have no suppliers. Please assign a supplier to each outside operation before releasing it."+msgid "There's nothing outstanding to apply these credits to."+msgstr "There's nothing outstanding to apply these credits to."+msgid "These custom fields will only be available for entities with the same tags"msgstr "These custom fields will only be available for entities with the same tags"@@ -11612,6 +11898,9 @@ msgstr "These jobs have operations assigned to this work center:"msgid "This completes the Discovery step."msgstr "This completes the Discovery step."+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."+msgstr "This counterparty has nothing outstanding — the payment will be recorded on-account."+msgid "This information will be used on document headers"msgstr "This information will be used on document headers"@@ -11720,6 +12009,9 @@ msgstr "Thursday"msgid "Tie shipments through to an invoice with no re-keying"msgstr "Tie shipments through to an invoice with no re-keying"+msgid "Tie-Out"+msgstr "Tie-Out"+msgid "Tightened"msgstr "Tightened"@@ -11756,6 +12048,9 @@ msgstr "To Ship and Receive"msgid "To Storage Unit"msgstr "To Storage Unit"+msgid "To supplier"+msgstr "To supplier"+msgid "Today"msgstr "Today"@@ -11825,6 +12120,9 @@ msgstr "Top-level classification (asset / liability / equity / revenue / expensemsgid "Total"msgstr "Total"+msgid "Total Amount"+msgstr "Total Amount"+msgid "Total capitalized cost of the asset (purchase price plus freight, install, and other costs that become part of book value)."msgstr "Total capitalized cost of the asset (purchase price plus freight, install, and other costs that become part of book value)."@@ -11852,6 +12150,9 @@ msgstr "Total quantity required across all active jobs and sales orders at thismsgid "Total:"msgstr "Total:"+msgid "Totals"+msgstr "Totals"+msgid "Traceability"msgstr "Traceability"@@ -12008,6 +12309,12 @@ msgstr "Types"msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."msgstr "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."+msgid "Unapplied"+msgstr "Unapplied"++msgid "Unapplied:"+msgstr "Unapplied:"+msgid "Unapproved Supplier"msgstr "Unapproved Supplier"@@ -12351,6 +12658,9 @@ msgstr "Value-added-tax registration number; required on EU invoices for reversemsgid "Values"msgstr "Values"+msgid "Variance"+msgstr "Variance"+msgid "Variance between actual and standard BOM component consumption"msgstr "Variance between actual and standard BOM component consumption"@@ -12372,6 +12682,9 @@ msgstr "Variance in outside processing costs"msgid "VAT Number"msgstr "VAT Number"+msgid "Vendor Write-Off Income"+msgstr "Vendor Write-Off Income"+msgid "Verification Error"msgstr "Verification Error"@@ -12453,6 +12766,9 @@ msgstr "View Lists"msgid "View maintenance dispatch"msgstr "View maintenance dispatch"+msgid "View Memo"+msgstr "View Memo"+msgid "View missing values"msgstr "View missing values"@@ -12474,6 +12790,9 @@ msgstr "View Open Quotes"msgid "View Open RFQs"msgstr "View Open RFQs"+msgid "View Payment"+msgstr "View Payment"+msgid "View permissions"msgstr "View permissions"@@ -13042,9 +13361,19 @@ msgstr "Worst Performing Machines"msgid "Write-Down Account"msgstr "Write-Down Account"+msgid "Write-off"+msgstr "Write-off"++msgid "Write-Off"+msgstr "Write-Off"+msgid "Write-Off Account"msgstr "Write-Off Account"+#. placeholder {0}: r.invoiceId+msgid "Write-off for {0}"+msgstr "Write-off for {0}"+msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."msgstr "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 86c7e945ba..5c49d71001 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -31,6 +31,10 @@ msgstr "\"Nadie fue despedido por comprarlo.\" Un factor de comodidad del incumbmsgid "(excluded for this customer)"msgstr "(excluido para este cliente)"+#. placeholder {0}: ar.count+msgid "{0} customers with a balance"+msgstr "{0} clientes con saldo"+#. placeholder {0}: rule.escalationDaysmsgid "{0} days"msgstr "{0} días"@@ -48,6 +52,10 @@ msgstr "{0} pedidos"msgid "{0} Processes"msgstr "{0} Procesos"+#. placeholder {0}: ap.count+msgid "{0} suppliers with a balance"+msgstr "{0} proveedores con saldo"+#. placeholder {0}: lotEntities.length - inspectedmsgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "{0} entidades no muestreadas serán liberadas a Disponible. Los pases muestreados permanecen Disponibles y los fallos muestreados permanecen Rechazados."@@ -60,6 +68,12 @@ msgstr "{0} cargado exitosamente"msgid "{0} values missing"msgstr "{0} valores faltantes"+msgid "{apOverduePct}% of payables"+msgstr "{apOverduePct}% de cuentas por pagar"++msgid "{arOverduePct}% of receivables"+msgstr "{arOverduePct}% de cuentas por cobrar"+msgid "{chainLabel}. Consider pointing this part directly at the final successor."msgstr "{chainLabel}. Considere apuntar esta pieza directamente al sucesor final."@@ -743,6 +757,10 @@ msgstr "Monto que aumenta activos/gastos o disminuye pasivos/patrimonio/ingresosmsgid "Amount that increases liabilities/equity/revenue or decreases assets/expenses on this line."msgstr "Monto que aumenta pasivos/patrimonio/ingresos o disminuye activos/gastos en esta línea."+#. placeholder {0}: r.memoId+msgid "Amount to apply for {0}"+msgstr "Cantidad a aplicar para {0}"+msgid "Amount Type"msgstr "Tipo de Cantidad"@@ -806,6 +824,12 @@ msgstr "Cualquier cosa no explícitamente listada en el alcance anterior"msgid "AP Clerk"msgstr "Empleado de Cuentas por Pagar"+msgid "AP Outstanding"+msgstr "AP Pendiente"++msgid "AP Overdue"+msgstr "AP Vencido"+msgid "API and Webhooks"msgstr "API y Webhooks"@@ -824,6 +848,19 @@ msgstr "Claves API"msgid "API keys for programmatic access to your Carbon data."msgstr "Claves API para acceso programático a tus datos de Carbon."+msgid "Applied"+msgstr "Aplicado"++#. placeholder {0}: r.invoiceId+msgid "Applied amount for {0}"+msgstr "Importe aplicado para {0}"++msgid "Applied Date"+msgstr "Fecha de Aplicación"++msgid "Applied To"+msgstr "Aplicado a"+msgid "Applies to"msgstr "Se aplica a"@@ -833,6 +870,12 @@ msgstr "Se aplica a todos"msgid "Applies to all work centers"msgstr "Se aplica a todos los centros de trabajo"+msgid "Apply available credits"+msgstr "Aplicar créditos disponibles"++msgid "Apply credits"+msgstr "Aplicar créditos"+msgid "Apply payments and track aging"msgstr "Aplicar pagos y rastrear antigüedad"@@ -845,6 +888,12 @@ msgstr "Aplicar reglas en la parte superior"msgid "Apply To"msgstr "Aplicar a"+msgid "Apply to invoice"+msgstr "Aplicar a factura"++msgid "Apply to invoices"+msgstr "Aplicar a facturas"+msgid "Approaching {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB cap."msgstr "Aproximándose al límite de {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB."@@ -875,6 +924,12 @@ msgstr "AQL (Z1.4 / ISO 2859-1)"msgid "AR Clerk"msgstr "Empleado de Cuentas por Cobrar"+msgid "AR Outstanding"+msgstr "Cuentas por Cobrar Pendientes"++msgid "AR Overdue"+msgstr "AR Vencido"+msgid "Archive"msgstr "Archivo"@@ -955,9 +1010,9 @@ msgstr "¿Está seguro de que desea eliminar {0} de esta operación? Esto no semsgid "Are you sure you want to delete {0}?"msgstr "¿Estás seguro de que deseas eliminar {0}?"+#. placeholder {0}: initialValues.memoId+#. placeholder {0}: initialValues.paymentId#. placeholder {0}: pickingList.pickingListId-#. placeholder {0}: routeData?.consumableSummary?.readableIdWithRevision-#. placeholder {0}: routeData?.customer?.name!msgid "Are you sure you want to delete {0}? This cannot be undone."msgstr "¿Estás seguro de que deseas eliminar {0}? Esto no se puede deshacer."@@ -1243,6 +1298,9 @@ msgstr "¿Estás seguro?"msgid "As needed"msgstr "Según sea necesario"+msgid "As of:"+msgstr "A partir de:"+msgid "As the company owner, you can transfer ownership to another employee. This will give them full access to billing and administrative settings."msgstr "Como propietario de la empresa, puedes transferir la propiedad a otro empleado. Esto le dará acceso completo a la facturación y la configuración administrativa."@@ -1371,6 +1429,9 @@ msgstr "Registros de Auditoría"msgid "Authentication Error"msgstr "Error de autenticación"+msgid "Auto apply"+msgstr "Aplicar automáticamente"+msgid "Auto Release"msgstr "Liberación Automática"@@ -1440,9 +1501,15 @@ msgstr "Retroceso"msgid "Backups"msgstr "Copias de seguridad"+msgid "Balance"+msgstr "Saldo"+msgid "Balance Sheet"msgstr "Balance General"+msgid "Balanced"+msgstr "Equilibrado"+msgid "Balloon"msgstr "Globo"@@ -1464,6 +1531,9 @@ msgstr "Banco — Moneda extranjera (predeterminada)"msgid "Bank — Local Currency (default)"msgstr "Banco — Moneda local (predeterminada)"+msgid "Bank / Cash Account"+msgstr "Cuenta Bancaria / Caja"+msgid "Bank account denominated in a foreign currency"msgstr "Cuenta bancaria denominada en una moneda extranjera."@@ -1643,6 +1713,12 @@ msgstr "por {byUser}"msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."msgstr "Al aceptar la invitación, aceptas los <0>Términos de Servicio</0> y la <1>Política de Privacidad</1>."+msgid "By Document Date"+msgstr "Por Fecha de Documento"++msgid "By Due Date"+msgstr "Por Fecha de Vencimiento"+msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"msgstr "Al iniciar sesión, aceptas los <0>Términos de Servicio</0> y la <1>Política de Privacidad.</1>"@@ -1931,6 +2007,9 @@ msgstr "Limpiar búsqueda"msgid "Clear search query"msgstr "Borrar consulta de búsqueda"+msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."+msgstr "Liquida esta factura con los créditos registrados de la parte así como con efectivo. Los créditos se aplican directamente — no se requiere registro."+msgid "Clearing account between goods receipt and supplier invoice; balances when both have posted."msgstr "Cuenta de compensación entre recepción de bienes e factura del proveedor; se compensa cuando ambos se han registrado."@@ -1977,6 +2056,9 @@ msgstr "Nube, o tu entorno autohospedado."msgid "Code"msgstr "Código"+msgid "Collapse"+msgstr "Contraer"+msgid "Collapse all"msgstr "Contraer todo"@@ -2552,6 +2634,12 @@ msgstr "No se pudieron cargar los documentos"msgid "Count"msgstr "Cantidad"+msgid "Counterparties"+msgstr "Contrapartes"++msgid "Counterparty"+msgstr "Contraparte"+msgid "Country"msgstr "País"@@ -2582,6 +2670,9 @@ msgstr "Crear una cotización con un nuevo ID de cotización"msgid "Create Account"msgstr "Crear Cuenta"+msgid "Create adjusting entry"+msgstr "Crear asiento de ajuste"+msgid "Create an account"msgstr "Crear una cuenta"@@ -2755,12 +2846,21 @@ msgstr "Creando parte..."msgid "Credit"msgstr "Crédito"+msgid "Credit / Debit Memos"+msgstr "Memorandos de Crédito / Débito"+msgid "Credit Account"msgstr "Cuenta de Crédito"msgid "Credit account when labor/machine time is absorbed into WIP"msgstr "Cuenta de Crédito cuando se absorbe el tiempo de trabajo/máquina en WIP"+msgid "Credits & Debits"+msgstr "Créditos y Débitos"++msgid "Credits applied"+msgstr "Créditos aplicados"+msgid "Critical"msgstr "Crítico"@@ -2935,6 +3035,9 @@ msgstr "tipos de cliente"msgid "Customer Types"msgstr "Tipos de Cliente"+msgid "Customer Write-Off (Bad Debt)"+msgstr "Cancelación de Cliente (Deuda Incobrable)"+msgid "customers"msgstr "clientes"@@ -3314,12 +3417,18 @@ msgstr "Eliminar Forma de Material"msgid "Delete Material Type"msgstr "Eliminar Tipo de Material"+msgid "Delete Memo"+msgstr "Eliminar Memo"+msgid "Delete Part"msgstr "Eliminar Parte"msgid "Delete Partner"msgstr "Eliminar Socio"+msgid "Delete Payment"+msgstr "Eliminar Pago"+msgid "Delete Payment Term"msgstr "Eliminar Término de Pago"@@ -3566,6 +3675,12 @@ msgstr "Dimensiones"msgid "Direct"msgstr "Directo"+msgid "Direction"+msgstr "Dirección"++msgid "Directions"+msgstr "Direcciones"+msgid "Disabled"msgstr "Deshabilitado"@@ -3584,6 +3699,10 @@ msgstr "Días de Descuento"msgid "Discount Days after {selectedCalculationMethod}"msgstr "Días de descuento después de {selectedCalculationMethod}"+#. placeholder {0}: r.invoiceId+msgid "Discount for {0}"+msgstr "Descuento para {0}"+msgid "Discount Percent"msgstr "Porcentaje de Descuento"@@ -3717,6 +3836,9 @@ msgstr "Arrastra para redimensionar el diagrama y las características"msgid "Drag to zoom"msgstr "Arrastra para ampliar"+msgid "Drawing"+msgstr "Extrayendo"+msgid "Drawing Number"msgstr "Número de Dibujo"@@ -3952,6 +4074,9 @@ msgstr "Editar Sustancia Material"msgid "Edit Material Type"msgstr "Editar Tipo de Material"+msgid "Edit Memo"+msgstr "Editar Memorándum"+msgid "Edit Non Conformance Type"msgstr "Editar Tipo de No Conformidad"@@ -3961,6 +4086,9 @@ msgstr "Editar Parte"msgid "Edit Partner"msgstr "Editar Socio"+msgid "Edit Payment"+msgstr "Editar Pago"+msgid "Edit Payment Term"msgstr "Editar Término de Pago"@@ -4442,12 +4570,18 @@ msgstr "Recepción Esperada"msgid "Expected Receipt Date"msgstr "Fecha de Recepción Esperada"+msgid "Expense account for customer balances written off as uncollectable on AR settlement"+msgstr "Cuenta de gastos para saldos de clientes cancelados como incobrables en la liquidación de cuentas por cobrar"+msgid "Expense account for deferred tax adjustments on depreciation"msgstr "Cuenta de gastos para ajustes de impuestos diferidos sobre depreciación"msgid "Expense account for equipment and facility maintenance"msgstr "Cuenta de gastos para mantenimiento de equipos e instalaciones"+msgid "Expense account for FX losses when a payment settles a foreign-currency invoice at a less favorable rate"+msgstr "Cuenta de gastos para pérdidas de divisas cuando un pago liquida una factura en moneda extranjera a una tasa menos favorable"+msgid "Expense account for non-inventory purchases (services, supplies)"msgstr "Cuenta de gastos para compras que no son de inventario (servicios, suministros)"@@ -5028,9 +5162,15 @@ msgstr "Viernes"msgid "From {0}"msgstr "Desde {0}"+msgid "From customer"+msgstr "Del cliente"+msgid "From Location"msgstr "Desde Ubicación"+msgid "from on-account credit"+msgstr "del crédito en cuenta"+msgid "From Storage Unit"msgstr "Desde Unidad de Almacenamiento"@@ -5040,6 +5180,9 @@ msgstr "Ubicación de Cumplimiento"msgid "Fully trained for"msgstr "Completamente capacitado para"+msgid "FX G/L"+msgstr "FX G/L"+msgid "Gains and Losses"msgstr "Ganancias y Pérdidas (predeterminado)"@@ -5127,6 +5270,9 @@ msgstr "Navegando por Carbon"msgid "Getting set up"msgstr "Configuración en curso"+msgid "GL"+msgstr "GL"+msgid "GL Account"msgstr "Cuenta Contable"@@ -5241,6 +5387,12 @@ msgstr "Cuenta GL de gastos para compras que no son de inventario (suministros,msgid "GL liability account credited for sales tax collected from customers."msgstr "Cuenta GL de pasivos acreditada por impuesto a las ventas cobrado de los clientes."+msgid "GL tie-out"+msgstr "Conciliación GL"++msgid "GL Tie-Out"+msgstr "Conciliación GL"+msgid "Go live right the first time — with our team alongside you"msgstr "Activa en el primer intento — con nuestro equipo a tu lado"@@ -5773,6 +5925,9 @@ msgstr "Referencia interna para ver dónde es más fuerte cada herramienta. Úsamsgid "inv"msgstr "inv"+msgid "Inv Rate"+msgstr "Tasa Inv"+msgid "Invalid Invite"msgstr "Invitación Inválida"@@ -5884,6 +6039,12 @@ msgstr "Estados Facturados"msgid "Invoices"msgstr "Facturas"+msgid "Invoices this memo has been applied to. Click a row to open the document."+msgstr "Facturas a las que se ha aplicado este memorándum. Haga clic en una fila para abrir el documento."++msgid "Invoicing"+msgstr "Facturación"+msgid "is"msgstr "es"@@ -6451,6 +6612,13 @@ msgstr "Los artículos de fabricación no se pueden facturar directamente. Cambimsgid "Make Method Version"msgstr "Versión del Método de Fabricación"+msgid "Make Payment"+msgstr "Realizar Pago"++#. placeholder {0}: selectedInvoices.length+msgid "Make Payment · {0} invoices"+msgstr "Realizar Pago · {0} facturas"+#. placeholder {0}: selectedRevision.revisionmsgid "Make revision {0} default?"msgstr "¿Hacer la revisión {0} predeterminada?"@@ -6693,6 +6861,15 @@ msgstr "Cadencia de reuniones"msgid "Members"msgstr "Miembros"+msgid "Memo"+msgstr "Memorándum"++msgid "Memo Date"+msgstr "Fecha del Memorándum"++msgid "Memo ID"+msgstr "ID de Memorándum"+msgid "MES"msgstr "MES"@@ -6953,6 +7130,9 @@ msgstr "Nuevo Consumible"msgid "New Contractor"msgstr "Nuevo Contratista"+msgid "New Credit / Debit Memo"+msgstr "Nuevo Memorándum de Crédito / Débito"+msgid "New Custom Field"msgstr "Nuevo Campo Personalizado"@@ -7061,6 +7241,9 @@ msgstr "Pieza Nueva"msgid "New Password"msgstr "Nueva Contraseña"+msgid "New Payment"+msgstr "Nuevo Pago"+msgid "New Payment Term"msgstr "Nuevo Término de Pago"@@ -7252,6 +7435,9 @@ msgstr "Sin presupuestos activos"msgid "No addresses found"msgstr "No se encontraron direcciones"+msgid "No applications. Payment will be on-account."+msgstr "Sin aplicaciones. El pago será a cuenta."+#. placeholder {0}: auditConfig.retentionDaysmsgid "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."msgstr "No hay registros archivados aún. Los registros más antiguos de {0} días se archivarán automáticamente y estarán disponibles para descargar aquí."@@ -7370,6 +7556,9 @@ msgstr "Sin notificaciones nuevas"msgid "No notes"msgstr "Sin notas"+msgid "No open invoices"+msgstr "Sin facturas abiertas"+msgid "No operations require picking at this location"msgstr "No se requieren operaciones de picking en esta ubicación"@@ -7397,6 +7586,12 @@ msgstr "No hay fuentes principales registradas aún. Haz clic en Recalcular en lmsgid "No part ID"msgstr "Sin ID de pieza"+msgid "No payables"+msgstr "Sin cuentas por pagar"++msgid "No payments yet."+msgstr "Sin pagos aún."+msgid "No planning data"msgstr "Sin datos de planificación"@@ -7421,6 +7616,9 @@ msgstr "Motivo sin cotización"msgid "No Quote Reasons"msgstr "Razones sin cotización"+msgid "No receivables"+msgstr "Sin cuentas por cobrar"+msgid "No remaining entities to inspect."msgstr "No hay entidades restantes para inspeccionar."@@ -7598,6 +7796,9 @@ msgstr "En Orden de Venta"msgid "On Storage Unit"msgstr "En Unidad de Almacenamiento"+msgid "On-account credit available"+msgstr "Crédito disponible en cuenta"+msgid "On-hand counts"msgstr "Conteos disponibles"@@ -7818,6 +8019,12 @@ msgstr "Pedidos enviados"msgid "Origin"msgstr "Origen"+msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"+msgstr "Cuenta de Otros Ingresos para ganancias de divisas cuando un pago liquida una factura en moneda extranjera a una tasa más favorable"++msgid "Other Income account for vendor balances cleared without full payment on AP settlement"+msgstr "Cuenta de Otros Ingresos para saldos de proveedores liquidados sin pago completo en la liquidación de AP"+msgid "Other Type"msgstr "Otro Tipo"@@ -7839,6 +8046,9 @@ msgstr "El producto nunca durará más que sus materias primas. Vuelve a la duramsgid "Outside operation"msgstr "Varianza de Gastos Indirectos"+msgid "Over-applied by"+msgstr "Aplicado en exceso por"+msgid "Overdue"msgstr "Vencido"@@ -7975,6 +8185,9 @@ msgstr "Partes y artículos"msgid "Parts, materials, and how you classify them."msgstr "Piezas, materiales y cómo los clasificas."+msgid "Party Type"+msgstr "Tipo de Parte"+msgid "Pass"msgstr "Aprobar"@@ -7984,17 +8197,29 @@ msgstr "Aprobado · reabrirr"msgid "Path"msgstr "Ruta"+msgid "Pay Rate"+msgstr "Tasa de Pago"+msgid "Payables"msgstr "Cuentas por Pagar (predeterminada)"msgid "Payables (default)"msgstr "término de pago"+msgid "Payables aging"+msgstr "Envejecimiento de cuentas por pagar"+msgid "Payment"msgstr "Pago"-msgid "Payment Method"-msgstr "Método de Pago"+msgid "Payment Applications"+msgstr "Aplicaciones de Pago"++msgid "Payment Date"+msgstr "Fecha de Pago"++msgid "Payment ID"+msgstr "ID de Pago"msgid "payment term"msgstr "términos de pago"@@ -8011,6 +8236,12 @@ msgstr "Términos de Pago"msgid "Payment terms like Net 30 or due on receipt"msgstr "Términos de pago como Neto 30 o pagadero a la recepción"+msgid "Payments"+msgstr "Pagos"++msgid "Payments and credits applied to this invoice. Click a row to open the source document."+msgstr "Pagos y créditos aplicados a esta factura. Haz clic en una fila para abrir el documento de origen."+msgid "PDF"msgstr "PDF"@@ -8672,6 +8903,9 @@ msgstr "Compras y planificación automática"msgid "Purchasing Contact"msgstr "Contacto de Compras"+msgid "Purchasing Invoices"+msgstr "Facturas de Compra"+msgid "Purchasing Unit of Measure"msgstr "Unidad de Medida de Compra"@@ -8866,9 +9100,18 @@ msgstr "Visibilidad del inventario y la planta de producción en tiempo real"msgid "Real-time questions during hypercare"msgstr "Preguntas en tiempo real durante la hipercarencia"+msgid "Realized Exchange Gain"+msgstr "Ganancia por Cambio de Divisas Realizada"++msgid "Realized Exchange Loss"+msgstr "Pérdida por Cambio de Divisas Realizada"+msgid "Reason"msgstr "Razón"+msgid "Reason Account"+msgstr "Cuenta de Razón"+msgid "Reason for declining (Optional)"msgstr "Motivo de rechazo (Opcional)"@@ -8911,6 +9154,9 @@ msgstr "Cuentas por Cobrar (predeterminada)"msgid "Receivables (default)"msgstr "Conciliación de una orden de compra con lo que se recibió y se facturó — implícito en Carbon, a través de las cantidades de línea y el balance GR/IR."+msgid "Receivables aging"+msgstr "Envejecimiento de cuentas por cobrar"+msgid "Receive"msgstr "Recibir"@@ -8921,6 +9167,13 @@ msgstr "Recibir {0} al Inventario"msgid "Receive against a PO and update inventory"msgstr "Recibir contra una PO y actualizar inventario"+msgid "Receive Payment"+msgstr "Recibir Pago"++#. placeholder {0}: selectedInvoices.length+msgid "Receive Payment · {0} invoices"+msgstr "Recibir Pago · {0} facturas"+msgid "Receive to Inventory"msgstr "Recibir al Inventario"@@ -8944,6 +9197,9 @@ msgstr "Ubicación de Recepción"msgid "Recent"msgstr "Reciente"+msgid "Recent payments"+msgstr "Pagos recientes"+msgid "Recently Created"msgstr "Creado Recientemente"@@ -8953,6 +9209,12 @@ msgstr "Período de Recuperación"msgid "Record"msgstr "Registro"+msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."+msgstr "Registre un memorándum de crédito o débito contra un cliente o proveedor. Las aplicaciones a facturas específicas se agregan después de que se crea el memorándum."++msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."+msgstr "Registre el efectivo recibido de un cliente (Recepción) o pagado a un proveedor (Desembolso). Las aplicaciones a facturas específicas se agregan después de que se crea el pago."+msgid "Record deleted"msgstr "Registro eliminado"@@ -9037,6 +9299,9 @@ msgstr "Liberar Trabajo"msgid "Released"msgstr "Liberado"+msgid "Remaining"+msgstr "Restante"+msgid "Remaining after split stays on the original row."msgstr "Lo restante después de dividir permanece en la fila original."@@ -9583,6 +9848,9 @@ msgstr "Guardar y cerrar"msgid "Save and Overwrite"msgstr "Guardar y Sobrescribir"+msgid "Save applications"+msgstr "Guardar aplicaciones"+msgid "Save contacts"msgstr "Guardar contactos"@@ -9824,6 +10092,15 @@ msgstr "Seleccionar Calibrador"msgid "Select groups or individuals"msgstr "Seleccionar grupos o individuos"+msgid "Select invoice"+msgstr "Seleccionar factura"++msgid "Select invoices from a single counterparty"+msgstr "Selecciona facturas de un único tercero"++msgid "Select invoices in a single currency"+msgstr "Selecciona facturas en una sola moneda"+msgid "Select Item Type"msgstr "Seleccionar Tipo de Artículo"@@ -9860,6 +10137,9 @@ msgstr "Seleccionar superficies"msgid "Select the groups that should complete this training"msgstr "Selecciona los grupos que deben completar esta capacitación"+msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."+msgstr "Selecciona las facturas que este pago liquida. El descuento y la cancelación están en la moneda de la factura."+msgid "Select value"msgstr "Seleccionar valor"@@ -10575,6 +10855,9 @@ msgstr "Variación de Subcontratación"msgid "Subcontracting Variance (default)"msgstr "Variación de Subcontratación (predeterminada)"+msgid "Subledger"+msgstr "Subdiario"+msgid "Submit anonymously"msgstr "Enviar anónimamente"@@ -11597,6 +11880,9 @@ msgstr "No hay presupuestos de proveedores activos para comparar en esta solicitmsgid "There are outside operations associated with this job that have no suppliers. Please assign a supplier to each outside operation before releasing it."msgstr "Hay operaciones externas asociadas con este trabajo que no tienen proveedores. Por favor, asigne un proveedor a cada operación externa antes de liberarlo."+msgid "There's nothing outstanding to apply these credits to."+msgstr "No hay nada pendiente para aplicar estos créditos."+msgid "These custom fields will only be available for entities with the same tags"msgstr "Estos campos personalizados solo estarán disponibles para entidades con las mismas etiquetas"@@ -11612,6 +11898,9 @@ msgstr "Estos trabajos tienen operaciones asignadas a este centro de trabajo:"msgid "This completes the Discovery step."msgstr "Esto completa el paso de Descubrimiento."+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."+msgstr "Este tercero no tiene nada pendiente — el pago se registrará en cuenta."+msgid "This information will be used on document headers"msgstr "Esta información se utilizará en los encabezados de documentos"@@ -11720,6 +12009,9 @@ msgstr "Jueves"msgid "Tie shipments through to an invoice with no re-keying"msgstr "Vincular envíos a una factura sin re-ingreso de datos"+msgid "Tie-Out"+msgstr "Conciliación"+msgid "Tightened"msgstr "Apretado"@@ -11756,6 +12048,9 @@ msgstr "Para Enviar y Recibir"msgid "To Storage Unit"msgstr "Unidad de almacenamiento destino"+msgid "To supplier"+msgstr "Al proveedor"+msgid "Today"msgstr "Hoy"@@ -11825,6 +12120,9 @@ msgstr "Clasificación de nivel superior (activo/pasivo/patrimonio/ingresos/gastmsgid "Total"msgstr "Total"+msgid "Total Amount"+msgstr "Monto Total"+msgid "Total capitalized cost of the asset (purchase price plus freight, install, and other costs that become part of book value)."msgstr "Costo total capitalizado del activo (precio de compra más flete, instalación y otros costos que se convierten en parte del valor en libros)."@@ -11852,6 +12150,9 @@ msgstr "Cantidad total requerida en todos los trabajos activos y órdenes de venmsgid "Total:"msgstr "Total:"+msgid "Totals"+msgstr "Totales"+msgid "Traceability"msgstr "Trazabilidad"@@ -12008,6 +12309,12 @@ msgstr "Tipos"msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."msgstr "Las entidades no muestreadas permanecerán En Espera para que puedas seguir inspeccionando y disponer más tarde. Los resultados muestreados se conservan."+msgid "Unapplied"+msgstr "No aplicado"++msgid "Unapplied:"+msgstr "No aplicado:"+msgid "Unapproved Supplier"msgstr "Proveedor No Aprobado"@@ -12351,6 +12658,9 @@ msgstr "Número de registro del impuesto al valor agregado; requerido en facturamsgid "Values"msgstr "Valores"+msgid "Variance"+msgstr "Variación"+msgid "Variance between actual and standard BOM component consumption"msgstr "Varianza entre el consumo real y el estándar de componentes de BOM"@@ -12372,6 +12682,9 @@ msgstr "Varianza en los costos de procesamiento externo"msgid "VAT Number"msgstr "Número de IVA"+msgid "Vendor Write-Off Income"+msgstr "Ingresos por Cancelación de Proveedores"+msgid "Verification Error"msgstr "Error de verificación"@@ -12453,6 +12766,9 @@ msgstr "Ver Listas"msgid "View maintenance dispatch"msgstr "Ver despacho de mantenimiento"+msgid "View Memo"+msgstr "Ver Memorándum"+msgid "View missing values"msgstr "Ver valores faltantes"@@ -12474,6 +12790,9 @@ msgstr "Ver Cotizaciones Abiertas"msgid "View Open RFQs"msgstr "Ver RFQs Abiertos"+msgid "View Payment"+msgstr "Ver Pago"+msgid "View permissions"msgstr "Permisos de visualización"@@ -13042,9 +13361,19 @@ msgstr "Máquinas con Peor Desempeño"msgid "Write-Down Account"msgstr "Cuenta de Reducción de Valor"+msgid "Write-off"+msgstr "Cancelación"++msgid "Write-Off"+msgstr "Cancelación"+msgid "Write-Off Account"msgstr "Cuenta de Cancelación"+#. placeholder {0}: r.invoiceId+msgid "Write-off for {0}"+msgstr "Cancelación para {0}"+msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."msgstr "Reducir el valor de un activo a lo largo de su vida útil — un lote mensual que crea, revisa como borrador y luego contabiliza."diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex 7a56c865d0..b65ed38f4b 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -31,6 +31,10 @@ msgstr "« Personne n'a jamais été licencié pour l'avoir acheté. » Un factemsgid "(excluded for this customer)"msgstr "(exclu pour ce client)"+#. placeholder {0}: ar.count+msgid "{0} customers with a balance"+msgstr "{0} clients avec un solde"+#. placeholder {0}: rule.escalationDaysmsgid "{0} days"msgstr "{0} jours"@@ -48,6 +52,10 @@ msgstr "{0} commandes"msgid "{0} Processes"msgstr "{0} Processus"+#. placeholder {0}: ap.count+msgid "{0} suppliers with a balance"+msgstr "{0} fournisseurs avec un solde"+#. placeholder {0}: lotEntities.length - inspectedmsgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "{0} entités non échantillonnées seront libérées en Disponible. Les passes échantillonnées restent Disponible et les défaillances échantillonnées restent Rejetées."@@ -60,6 +68,12 @@ msgstr "{0} téléchargé avec succès"msgid "{0} values missing"msgstr "{0} valeurs manquantes"+msgid "{apOverduePct}% of payables"+msgstr "{apOverduePct}% des comptes créditeurs"++msgid "{arOverduePct}% of receivables"+msgstr "{arOverduePct}% des créances"+msgid "{chainLabel}. Consider pointing this part directly at the final successor."msgstr "{chainLabel}. Envisagez de pointer cette pièce directement vers le successeur final."@@ -743,6 +757,10 @@ msgstr "Montant qui augmente les actifs/frais ou diminue les passifs/capitaux prmsgid "Amount that increases liabilities/equity/revenue or decreases assets/expenses on this line."msgstr "Montant qui augmente les passifs/capitaux propres/revenus ou diminue les actifs/frais sur cette ligne."+#. placeholder {0}: r.memoId+msgid "Amount to apply for {0}"+msgstr "Montant à appliquer pour {0}"+msgid "Amount Type"msgstr "Type de montant"@@ -806,6 +824,12 @@ msgstr "Tout ce qui n'est pas explicitement listé dans le périmètre ci-dessusmsgid "AP Clerk"msgstr "Commis aux comptes créditeurs"+msgid "AP Outstanding"+msgstr "AP à payer"++msgid "AP Overdue"+msgstr "AP En retard"+msgid "API and Webhooks"msgstr "API et Webhooks"@@ -824,6 +848,19 @@ msgstr "Clés API"msgid "API keys for programmatic access to your Carbon data."msgstr "Clés API pour un accès programmatique à vos données Carbon."+msgid "Applied"+msgstr "Appliqué"++#. placeholder {0}: r.invoiceId+msgid "Applied amount for {0}"+msgstr "Montant appliqué pour {0}"++msgid "Applied Date"+msgstr "Date d'application"++msgid "Applied To"+msgstr "Appliqué à"+msgid "Applies to"msgstr "S'applique à"@@ -833,6 +870,12 @@ msgstr "S'applique à tous"msgid "Applies to all work centers"msgstr "S'applique à tous les centres de travail"+msgid "Apply available credits"+msgstr "Appliquer les crédits disponibles"++msgid "Apply credits"+msgstr "Appliquer les crédits"+msgid "Apply payments and track aging"msgstr "Appliquer les paiements et suivre l'ancienneté"@@ -845,6 +888,12 @@ msgstr "Appliquer les règles en premier"msgid "Apply To"msgstr "Appliquer à"+msgid "Apply to invoice"+msgstr "Appliquer à la facture"++msgid "Apply to invoices"+msgstr "Appliquer aux factures"+msgid "Approaching {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB cap."msgstr "Approche de la limite de {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB."@@ -875,6 +924,12 @@ msgstr "NQA (Z1.4 / ISO 2859-1)"msgid "AR Clerk"msgstr "Commis aux comptes clients"+msgid "AR Outstanding"+msgstr "Créances clients en attente"++msgid "AR Overdue"+msgstr "AR En retard"+msgid "Archive"msgstr "Archiver"@@ -955,9 +1010,9 @@ msgstr "Êtes-vous sûr de vouloir supprimer {0} de cette opération ? Cette actmsgid "Are you sure you want to delete {0}?"msgstr "Êtes-vous sûr de vouloir supprimer {0} ?"+#. placeholder {0}: initialValues.memoId+#. placeholder {0}: initialValues.paymentId#. placeholder {0}: pickingList.pickingListId-#. placeholder {0}: routeData?.consumableSummary?.readableIdWithRevision-#. placeholder {0}: routeData?.customer?.name!msgid "Are you sure you want to delete {0}? This cannot be undone."msgstr "Êtes-vous sûr de vouloir supprimer {0} ? Cette action ne peut pas être annulée."@@ -1243,6 +1298,9 @@ msgstr "Êtes-vous sûr ?"msgid "As needed"msgstr "Selon les besoins"+msgid "As of:"+msgstr "Au :"+msgid "As the company owner, you can transfer ownership to another employee. This will give them full access to billing and administrative settings."msgstr "En tant que propriétaire de l'entreprise, vous pouvez transférer la propriété à un autre employé. Cela lui donnera un accès complet à la facturation et aux paramètres administratifs."@@ -1371,6 +1429,9 @@ msgstr "Journaux d'audit"msgid "Authentication Error"msgstr "Erreur d'authentification"+msgid "Auto apply"+msgstr "Appliquer automatiquement"+msgid "Auto Release"msgstr "Libération automatique"@@ -1440,9 +1501,15 @@ msgstr "Retrait automatique"msgid "Backups"msgstr "Sauvegardes"+msgid "Balance"+msgstr "Solde"+msgid "Balance Sheet"msgstr "Bilan"+msgid "Balanced"+msgstr "Équilibré"+msgid "Balloon"msgstr "Ballon"@@ -1464,6 +1531,9 @@ msgstr "Banque — Devise étrangère (par défaut)"msgid "Bank — Local Currency (default)"msgstr "Banque — Devise locale (par défaut)"+msgid "Bank / Cash Account"+msgstr "Compte Bancaire / Caisse"+msgid "Bank account denominated in a foreign currency"msgstr "Compte bancaire libellé en devise étrangère."@@ -1643,6 +1713,12 @@ msgstr "par {byUser}"msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."msgstr "En acceptant l'invitation, vous acceptez les <0>Conditions d'utilisation</0> et la <1>Politique de confidentialité</1>."+msgid "By Document Date"+msgstr "Par date du document"++msgid "By Due Date"+msgstr "Par date d'échéance"+msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"msgstr "En vous connectant, vous acceptez les <0>Conditions d'utilisation</0> et la <1>Politique de confidentialité.</1>"@@ -1931,6 +2007,9 @@ msgstr "Effacer la recherche"msgid "Clear search query"msgstr "Effacer la requête de recherche"+msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."+msgstr "Réglez cette facture avec les crédits comptabilisés de la partie ainsi qu'en espèces. Les crédits s'appliquent directement — aucune comptabilisation nécessaire."+msgid "Clearing account between goods receipt and supplier invoice; balances when both have posted."msgstr "Compte de compensation entre la réception de marchandises et la facture du fournisseur; se compense lorsque les deux ont été comptabilisés."@@ -1977,6 +2056,9 @@ msgstr "Cloud, ou votre environnement auto-hébergé."msgid "Code"msgstr "Code"+msgid "Collapse"+msgstr "Réduire"+msgid "Collapse all"msgstr "Réduire tout"@@ -2552,6 +2634,12 @@ msgstr "Impossible de charger les documents"msgid "Count"msgstr "Nombre"+msgid "Counterparties"+msgstr "Contreparties"++msgid "Counterparty"+msgstr "Contrepartie"+msgid "Country"msgstr "Pays"@@ -2582,6 +2670,9 @@ msgstr "Créer un devis avec un nouvel identifiant de devis"msgid "Create Account"msgstr "Créer un compte"+msgid "Create adjusting entry"+msgstr "Créer une écriture de régularisation"+msgid "Create an account"msgstr "Créer un compte"@@ -2755,12 +2846,21 @@ msgstr "Création de la pièce..."msgid "Credit"msgstr "Crédit"+msgid "Credit / Debit Memos"+msgstr "Mémos de crédit / débit"+msgid "Credit Account"msgstr "Compte Créditeur"msgid "Credit account when labor/machine time is absorbed into WIP"msgstr "Compte créditeur lorsque le temps de main-d'œuvre/machine est absorbé en travaux en cours"+msgid "Credits & Debits"+msgstr "Crédits et débits"++msgid "Credits applied"+msgstr "Crédits appliqués"+msgid "Critical"msgstr "Critique"@@ -2935,6 +3035,9 @@ msgstr "types de clients"msgid "Customer Types"msgstr "Types de clients"+msgid "Customer Write-Off (Bad Debt)"+msgstr "Radiation client (Créance douteuse)"+msgid "customers"msgstr "clients"@@ -3314,12 +3417,18 @@ msgstr "Supprimer la forme de matériau"msgid "Delete Material Type"msgstr "Supprimer le type de matériau"+msgid "Delete Memo"+msgstr "Supprimer le mémo"+msgid "Delete Part"msgstr "Supprimer la pièce"msgid "Delete Partner"msgstr "Supprimer le partenaire"+msgid "Delete Payment"+msgstr "Supprimer le paiement"+msgid "Delete Payment Term"msgstr "Supprimer le délai de paiement"@@ -3566,6 +3675,12 @@ msgstr "Dimensions"msgid "Direct"msgstr "Direct"+msgid "Direction"+msgstr "Direction"++msgid "Directions"+msgstr "Directions"+msgid "Disabled"msgstr "Désactivé"@@ -3584,6 +3699,10 @@ msgstr "Jours de Remise"msgid "Discount Days after {selectedCalculationMethod}"msgstr "Jours de remise après {selectedCalculationMethod}"+#. placeholder {0}: r.invoiceId+msgid "Discount for {0}"+msgstr "Remise pour {0}"+msgid "Discount Percent"msgstr "Pourcentage de remise"@@ -3717,6 +3836,9 @@ msgstr "Faites glisser pour redimensionner le diagramme et les fonctionnalités"msgid "Drag to zoom"msgstr "Glisser pour zoomer"+msgid "Drawing"+msgstr "Prélèvement"+msgid "Drawing Number"msgstr "Numéro de dessin"@@ -3952,6 +4074,9 @@ msgstr "Modifier la substance matérielle"msgid "Edit Material Type"msgstr "Modifier le type de matériau"+msgid "Edit Memo"+msgstr "Modifier le mémo"+msgid "Edit Non Conformance Type"msgstr "Modifier le type de non-conformité"@@ -3961,6 +4086,9 @@ msgstr "Modifier la pièce"msgid "Edit Partner"msgstr "Modifier le partenaire"+msgid "Edit Payment"+msgstr "Modifier le paiement"+msgid "Edit Payment Term"msgstr "Modifier le délai de paiement"@@ -4442,12 +4570,18 @@ msgstr "Réception prévue"msgid "Expected Receipt Date"msgstr "Date de réception prévue"+msgid "Expense account for customer balances written off as uncollectable on AR settlement"+msgstr "Compte de dépenses pour les soldes clients radiés comme irrécouvrables lors du règlement des créances clients"+msgid "Expense account for deferred tax adjustments on depreciation"msgstr "Compte de charges pour ajustements d'impôt différé sur amortissement"msgid "Expense account for equipment and facility maintenance"msgstr "Compte de charges pour l'entretien des équipements et des installations"+msgid "Expense account for FX losses when a payment settles a foreign-currency invoice at a less favorable rate"+msgstr "Compte de dépenses pour les pertes de change lorsqu'un paiement règle une facture en devise étrangère à un taux moins favorable"+msgid "Expense account for non-inventory purchases (services, supplies)"msgstr "Compte de charges pour achats hors inventaire (services, fournitures)"@@ -5028,9 +5162,15 @@ msgstr "Vendredi"msgid "From {0}"msgstr "À partir de {0}"+msgid "From customer"+msgstr "Du client"+msgid "From Location"msgstr "De l'emplacement"+msgid "from on-account credit"+msgstr "du crédit en compte"+msgid "From Storage Unit"msgstr "Unité de stockage source"@@ -5040,6 +5180,9 @@ msgstr "Lieu d'Exécution"msgid "Fully trained for"msgstr "Entièrement formé pour"+msgid "FX G/L"+msgstr "G/P de change"+msgid "Gains and Losses"msgstr "Gains et Pertes (par défaut)"@@ -5127,6 +5270,9 @@ msgstr "Se repérer dans Carbon"msgid "Getting set up"msgstr "Mise en place"+msgid "GL"+msgstr "GL"+msgid "GL Account"msgstr "Compte GL"@@ -5241,6 +5387,12 @@ msgstr "Compte GL de dépenses pour les achats non inventoriables (fournitures,msgid "GL liability account credited for sales tax collected from customers."msgstr "Compte GL de passif crédité pour la taxe de vente collectée auprès des clients."+msgid "GL tie-out"+msgstr "Rapprochement GL"++msgid "GL Tie-Out"+msgstr "Rapprochement GL"+msgid "Go live right the first time — with our team alongside you"msgstr "Lancez-vous correctement du premier coup — avec notre équipe à vos côtés"@@ -5773,6 +5925,9 @@ msgstr "Référence interne pour voir où chaque outil est plus performant. Utilmsgid "inv"msgstr "inv"+msgid "Inv Rate"+msgstr "Taux Fact"+msgid "Invalid Invite"msgstr "Invitation invalide"@@ -5884,6 +6039,12 @@ msgstr "Statuts facturés"msgid "Invoices"msgstr "Factures"+msgid "Invoices this memo has been applied to. Click a row to open the document."+msgstr "Factures auxquelles ce mémo a été appliqué. Cliquez sur une ligne pour ouvrir le document."++msgid "Invoicing"+msgstr "Facturation"+msgid "is"msgstr "est"@@ -6451,6 +6612,13 @@ msgstr "Les articles de fabrication ne peuvent pas être facturés directement.msgid "Make Method Version"msgstr "Version de la méthode de fabrication"+msgid "Make Payment"+msgstr "Effectuer un paiement"++#. placeholder {0}: selectedInvoices.length+msgid "Make Payment · {0} invoices"+msgstr "Effectuer un paiement · {0} factures"+#. placeholder {0}: selectedRevision.revisionmsgid "Make revision {0} default?"msgstr "Rendre la révision {0} par défaut ?"@@ -6693,6 +6861,15 @@ msgstr "Cadence de réunion"msgid "Members"msgstr "Membres"+msgid "Memo"+msgstr "Mémo"++msgid "Memo Date"+msgstr "Date du mémo"++msgid "Memo ID"+msgstr "ID du mémo"+msgid "MES"msgstr "MES"@@ -6953,6 +7130,9 @@ msgstr "Nouveau consommable"msgid "New Contractor"msgstr "Nouveau Contractant"+msgid "New Credit / Debit Memo"+msgstr "Nouveau Mémo de Crédit / Débit"+msgid "New Custom Field"msgstr "Nouveau champ personnalisé"@@ -7061,6 +7241,9 @@ msgstr "Nouvelle Pièce"msgid "New Password"msgstr "Nouveau mot de passe"+msgid "New Payment"+msgstr "Nouveau Paiement"+msgid "New Payment Term"msgstr "Nouveau Terme de Paiement"@@ -7252,6 +7435,9 @@ msgstr "Aucun devis actif"msgid "No addresses found"msgstr "Aucune adresse trouvée"+msgid "No applications. Payment will be on-account."+msgstr "Aucune application. Le paiement sera sur compte."+#. placeholder {0}: auditConfig.retentionDaysmsgid "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."msgstr "Aucun journal archivé pour le moment. Les journaux antérieurs à {0} jours seront automatiquement archivés et disponibles au téléchargement ici."@@ -7370,6 +7556,9 @@ msgstr "Aucune nouvelle notification"msgid "No notes"msgstr "Aucune note"+msgid "No open invoices"+msgstr "Aucune facture ouverte"+msgid "No operations require picking at this location"msgstr "Aucune opération ne nécessite de prélèvement à cet endroit"@@ -7397,6 +7586,12 @@ msgstr "Aucune source parent enregistrée pour le moment. Cliquez sur Recalculermsgid "No part ID"msgstr "Aucun ID de pièce"+msgid "No payables"+msgstr "Aucun compte créditeur"++msgid "No payments yet."+msgstr "Aucun paiement pour le moment."+msgid "No planning data"msgstr "Aucune donnée de planification"@@ -7421,6 +7616,9 @@ msgstr "Aucune raison de devis"msgid "No Quote Reasons"msgstr "Aucune raison de devis"+msgid "No receivables"+msgstr "Aucune créance"+msgid "No remaining entities to inspect."msgstr "Aucune entité restante à inspecter."@@ -7598,6 +7796,9 @@ msgstr "Sur commande client"msgid "On Storage Unit"msgstr "Sur l'unité de stockage"+msgid "On-account credit available"+msgstr "Crédit en compte disponible"+msgid "On-hand counts"msgstr "Stocks disponibles"@@ -7818,6 +8019,12 @@ msgstr "Commandes soumises"msgid "Origin"msgstr "Origine"+msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"+msgstr "Compte de revenus divers pour les gains de change lorsqu'un paiement règle une facture en devise étrangère à un taux plus favorable"++msgid "Other Income account for vendor balances cleared without full payment on AP settlement"+msgstr "Compte de revenu supplémentaire pour les soldes fournisseurs apurés sans paiement intégral lors du règlement des comptes créditeurs"+msgid "Other Type"msgstr "Autre Type"@@ -7839,6 +8046,9 @@ msgstr "La production ne dépasse jamais la durée de vie de ses matières premimsgid "Outside operation"msgstr "Écart de Frais Généraux"+msgid "Over-applied by"+msgstr "Appliqué en excédent de"+msgid "Overdue"msgstr "En retard"@@ -7975,6 +8185,9 @@ msgstr "Pièces & articles"msgid "Parts, materials, and how you classify them."msgstr "Pièces, matériaux et comment vous les classez."+msgid "Party Type"+msgstr "Type de tiers"+msgid "Pass"msgstr "Réussir"@@ -7984,17 +8197,29 @@ msgstr "Réussi · rouvrir"msgid "Path"msgstr "Chemin"+msgid "Pay Rate"+msgstr "Taux de paiement"+msgid "Payables"msgstr "Comptes Créditeurs (par défaut)"msgid "Payables (default)"msgstr "condition de paiement"+msgid "Payables aging"+msgstr "Vieillissement des comptes créditeurs"+msgid "Payment"msgstr "Paiement"-msgid "Payment Method"-msgstr "Méthode de paiement"+msgid "Payment Applications"+msgstr "Applications de paiement"++msgid "Payment Date"+msgstr "Date de paiement"++msgid "Payment ID"+msgstr "ID de paiement"msgid "payment term"msgstr "conditions de paiement"@@ -8011,6 +8236,12 @@ msgstr "Conditions de paiement"msgid "Payment terms like Net 30 or due on receipt"msgstr "Conditions de paiement comme Net 30 ou à la réception"+msgid "Payments"+msgstr "Paiements"++msgid "Payments and credits applied to this invoice. Click a row to open the source document."+msgstr "Paiements et crédits appliqués à cette facture. Cliquez sur une ligne pour ouvrir le document source."+msgid "PDF"msgstr "PDF"@@ -8672,6 +8903,9 @@ msgstr "Achat et planification automatique"msgid "Purchasing Contact"msgstr "Contact d'achat"+msgid "Purchasing Invoices"+msgstr "Factures d'achat"+msgid "Purchasing Unit of Measure"msgstr "Unité de mesure d'achat"@@ -8866,9 +9100,18 @@ msgstr "Visibilité en temps réel de l'inventaire et de l'atelier"msgid "Real-time questions during hypercare"msgstr "Questions en temps réel pendant l'hypercare"+msgid "Realized Exchange Gain"+msgstr "Gain de change réalisé"++msgid "Realized Exchange Loss"+msgstr "Perte de change réalisée"+msgid "Reason"msgstr "Raison"+msgid "Reason Account"+msgstr "Compte de raison"+msgid "Reason for declining (Optional)"msgstr "Raison du refus (Facultatif)"@@ -8911,6 +9154,9 @@ msgstr "Comptes Clients (par défaut)"msgid "Receivables (default)"msgstr "Rapprochement d'une commande d'achat avec ce qui a été reçu et facturé — implicite dans Carbon, via les quantités de ligne et le solde GR/IR."+msgid "Receivables aging"+msgstr "Vieillissement des créances"+msgid "Receive"msgstr "Recevoir"@@ -8921,6 +9167,13 @@ msgstr "Recevoir {0} à l'inventaire"msgid "Receive against a PO and update inventory"msgstr "Recevoir contre un bon de commande et mettre à jour l'inventaire"+msgid "Receive Payment"+msgstr "Recevoir le paiement"++#. placeholder {0}: selectedInvoices.length+msgid "Receive Payment · {0} invoices"+msgstr "Recevoir le paiement · {0} factures"+msgid "Receive to Inventory"msgstr "Recevoir en inventaire"@@ -8944,6 +9197,9 @@ msgstr "Lieu de réception"msgid "Recent"msgstr "Récent"+msgid "Recent payments"+msgstr "Paiements récents"+msgid "Recently Created"msgstr "Récemment créé"@@ -8953,6 +9209,12 @@ msgstr "Durée d'Amortissement"msgid "Record"msgstr "Enregistrer"+msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."+msgstr "Enregistrez un avoir ou un débit contre un client ou un fournisseur. Les applications à des factures spécifiques sont ajoutées après la création de l'avoir."++msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."+msgstr "Enregistrez les espèces reçues d'un client (Reçu) ou versées à un fournisseur (Décaissement). Les applications à des factures spécifiques sont ajoutées après la création du paiement."+msgid "Record deleted"msgstr "Enregistrement supprimé"@@ -9037,6 +9299,9 @@ msgstr "Lancer le travail"msgid "Released"msgstr "Libéré"+msgid "Remaining"+msgstr "Restant"+msgid "Remaining after split stays on the original row."msgstr "Le reste après la division reste sur la ligne d'origine."@@ -9583,6 +9848,9 @@ msgstr "Enregistrer et fermer"msgid "Save and Overwrite"msgstr "Enregistrer et remplacer"+msgid "Save applications"+msgstr "Enregistrer les applications"+msgid "Save contacts"msgstr "Enregistrer les contacts"@@ -9824,6 +10092,15 @@ msgstr "Sélectionner un calibre"msgid "Select groups or individuals"msgstr "Sélectionner des groupes ou des individus"+msgid "Select invoice"+msgstr "Sélectionner une facture"++msgid "Select invoices from a single counterparty"+msgstr "Sélectionnez les factures d'un seul tiers"++msgid "Select invoices in a single currency"+msgstr "Sélectionnez les factures dans une seule devise"+msgid "Select Item Type"msgstr "Sélectionner le type d'article"@@ -9860,6 +10137,9 @@ msgstr "Sélectionner les surfaces"msgid "Select the groups that should complete this training"msgstr "Sélectionnez les groupes qui doivent suivre cette formation"+msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."+msgstr "Sélectionnez les factures que ce paiement règle. La remise et la radiation sont en devise de facture."+msgid "Select value"msgstr "Sélectionner une valeur"@@ -10575,6 +10855,9 @@ msgstr "Écart de Sous-Traitance"msgid "Subcontracting Variance (default)"msgstr "Écart de Sous-Traitance (par défaut)"+msgid "Subledger"+msgstr "Grand-livre auxiliaire"+msgid "Submit anonymously"msgstr "Soumettre anonymement"@@ -11597,6 +11880,9 @@ msgstr "Il n'y a pas de devis fournisseurs actifs à comparer pour cette demandemsgid "There are outside operations associated with this job that have no suppliers. Please assign a supplier to each outside operation before releasing it."msgstr "Il y a des opérations externes associées à ce travail qui n'ont pas de fournisseurs. Veuillez assigner un fournisseur à chaque opération externe avant de le lancer."+msgid "There's nothing outstanding to apply these credits to."+msgstr "Il n'y a rien d'impayé pour appliquer ces crédits."+msgid "These custom fields will only be available for entities with the same tags"msgstr "Ces champs personnalisés ne seront disponibles que pour les entités ayant les mêmes balises"@@ -11612,6 +11898,9 @@ msgstr "Ces travaux ont des opérations assignées à ce centre de travail :"msgid "This completes the Discovery step."msgstr "Cela complète l'étape de découverte."+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."+msgstr "Ce tiers n'a rien en suspens — le paiement sera enregistré en compte courant."+msgid "This information will be used on document headers"msgstr "Ces informations seront utilisées dans les en-têtes de document"@@ -11720,6 +12009,9 @@ msgstr "Jeudi"msgid "Tie shipments through to an invoice with no re-keying"msgstr "Lier les expéditions à une facture sans ressaisie"+msgid "Tie-Out"+msgstr "Rapprochement"+msgid "Tightened"msgstr "Serré"@@ -11756,6 +12048,9 @@ msgstr "À expédier et recevoir"msgid "To Storage Unit"msgstr "Vers l'unité de stockage"+msgid "To supplier"+msgstr "Au fournisseur"+msgid "Today"msgstr "Aujourd'hui"@@ -11825,6 +12120,9 @@ msgstr "Classification de niveau supérieur (actif/passif/capitaux propres/revenmsgid "Total"msgstr "Total"+msgid "Total Amount"+msgstr "Montant Total"+msgid "Total capitalized cost of the asset (purchase price plus freight, install, and other costs that become part of book value)."msgstr "Coût total capitalisé de l'actif (prix d'achat plus fret, installation et autres frais qui deviennent partie de la valeur nette comptable)."@@ -11852,6 +12150,9 @@ msgstr "Quantité totale requise sur toutes les tâches actives et commandes climsgid "Total:"msgstr "Total :"+msgid "Totals"+msgstr "Totaux"+msgid "Traceability"msgstr "Traçabilité"@@ -12008,6 +12309,12 @@ msgstr "Types"msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."msgstr "Les entités non échantillonnées resteront En attente pour que vous puissiez continuer l'inspection et disposer ultérieurement. Les résultats échantillonnés sont conservés."+msgid "Unapplied"+msgstr "Non appliqué"++msgid "Unapplied:"+msgstr "Non appliqué :"+msgid "Unapproved Supplier"msgstr "Fournisseur non approuvé"@@ -12351,6 +12658,9 @@ msgstr "Numéro d'enregistrement de la taxe sur la valeur ajoutée ; requis surmsgid "Values"msgstr "Valeurs"+msgid "Variance"+msgstr "Écart"+msgid "Variance between actual and standard BOM component consumption"msgstr "Écart entre la consommation réelle et standard des composants de nomenclature"@@ -12372,6 +12682,9 @@ msgstr "Écart dans les coûts de traitement externe"msgid "VAT Number"msgstr "Numéro de TVA"+msgid "Vendor Write-Off Income"+msgstr "Revenu de Radiation Fournisseur"+msgid "Verification Error"msgstr "Erreur de vérification"@@ -12453,6 +12766,9 @@ msgstr "Afficher les listes"msgid "View maintenance dispatch"msgstr "Afficher la dépêche de maintenance"+msgid "View Memo"+msgstr "Afficher le mémo"+msgid "View missing values"msgstr "Afficher les valeurs manquantes"@@ -12474,6 +12790,9 @@ msgstr "Afficher les devis ouverts"msgid "View Open RFQs"msgstr "Afficher les demandes de devis ouvertes"+msgid "View Payment"+msgstr "Afficher le paiement"+msgid "View permissions"msgstr "Autorisations de consultation"@@ -13042,9 +13361,19 @@ msgstr "Machines les plus défaillantes"msgid "Write-Down Account"msgstr "Compte de Dévaluation"+msgid "Write-off"+msgstr "Radiation"++msgid "Write-Off"+msgstr "Radiation"+msgid "Write-Off Account"msgstr "Compte de Radiation"+#. placeholder {0}: r.invoiceId+msgid "Write-off for {0}"+msgstr "Radiation pour {0}"+msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."msgstr "Réduire la valeur d'un actif au cours de sa vie utile — un lot mensuel que vous créez, vérifiez en tant que brouillon, puis comptabilisez."diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex ad076a9d21..4ad255dc6f 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -31,6 +31,10 @@ msgstr "\"इसे खरीदने के लिए किसी को नmsgid "(excluded for this customer)"msgstr "(इस ग्राहक के लिए बाहर रखा गया)"+#. placeholder {0}: ar.count+msgid "{0} customers with a balance"+msgstr "{0} ग्राहकों के साथ शेष"+#. placeholder {0}: rule.escalationDaysmsgid "{0} days"msgstr "{0} दिन"@@ -48,6 +52,10 @@ msgstr "{0} ऑर्डर"msgid "{0} Processes"msgstr "{0} प्रक्रियाएं"+#. placeholder {0}: ap.count+msgid "{0} suppliers with a balance"+msgstr "{0} आपूर्तिकर्ता शेष के साथ"+#. placeholder {0}: lotEntities.length - inspectedmsgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "{0} नमूना न किए गए इकाइयों को उपलब्ध में जारी किया जाएगा। नमूना किए गए पास उपलब्ध रहेंगे और नमूना किए गए विफलताएं अस्वीकृत रहेंगी।"@@ -60,6 +68,12 @@ msgstr "{0} सफलतापूर्वक अपलोड हो गया"msgid "{0} values missing"msgstr "{0} मान गायब हैं"+msgid "{apOverduePct}% of payables"+msgstr "{apOverduePct}% देय राशि का"++msgid "{arOverduePct}% of receivables"+msgstr "{arOverduePct}% प्राप्य"+msgid "{chainLabel}. Consider pointing this part directly at the final successor."msgstr "{chainLabel}. इस भाग को सीधे अंतिम उत्तराधिकारी की ओर इंगित करने पर विचार करें।"@@ -743,6 +757,10 @@ msgstr "राशि जो इस पंक्ति पर संपत्तmsgid "Amount that increases liabilities/equity/revenue or decreases assets/expenses on this line."msgstr "राशि जो इस पंक्ति पर देयता/इक्विटी/राजस्व बढ़ाती है या संपत्ति/व्यय घटाती है।"+#. placeholder {0}: r.memoId+msgid "Amount to apply for {0}"+msgstr "{0} के लिए लागू करने की राशि"+msgid "Amount Type"msgstr "राशि प्रकार"@@ -806,6 +824,12 @@ msgstr "स्कोप में ऊपर स्पष्ट रूप सेmsgid "AP Clerk"msgstr "AP क्लर्क"+msgid "AP Outstanding"+msgstr "AP बकाया"++msgid "AP Overdue"+msgstr "AP देय"+msgid "API and Webhooks"msgstr "API और Webhooks"@@ -824,6 +848,19 @@ msgstr "एपीआई कुंजियाँ"msgid "API keys for programmatic access to your Carbon data."msgstr "आपके Carbon डेटा के लिए प्रोग्रामेटिक एक्सेस के लिए API कुंजियाँ।"+msgid "Applied"+msgstr "लागू"++#. placeholder {0}: r.invoiceId+msgid "Applied amount for {0}"+msgstr "{0} के लिए लागू राशि"++msgid "Applied Date"+msgstr "लागू तारीख"++msgid "Applied To"+msgstr "लागू किया गया"+msgid "Applies to"msgstr "लागू होता है"@@ -833,6 +870,12 @@ msgstr "सभी पर लागू होता है"msgid "Applies to all work centers"msgstr "सभी कार्य केंद्रों पर लागू होता है"+msgid "Apply available credits"+msgstr "उपलब्ध क्रेडिट लागू करें"++msgid "Apply credits"+msgstr "क्रेडिट लागू करें"+msgid "Apply payments and track aging"msgstr "भुगतान लागू करें और उम्र ट्रैक करें"@@ -845,6 +888,12 @@ msgstr "शीर्ष पर नियम लागू करें"msgid "Apply To"msgstr "लागू करें"+msgid "Apply to invoice"+msgstr "चालान पर लागू करें"++msgid "Apply to invoices"+msgstr "चालानों पर लागू करें"+msgid "Approaching {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB cap."msgstr "{PO_EMAIL_ATTACHMENT_LIMIT_MB} MB सीमा के करीब पहुंच रहे हैं।"@@ -875,6 +924,12 @@ msgstr "AQL (Z1.4 / ISO 2859-1)"msgid "AR Clerk"msgstr "AR क्लर्क"+msgid "AR Outstanding"+msgstr "AR बकाया"++msgid "AR Overdue"+msgstr "AR अतिदेय"+msgid "Archive"msgstr "संग्रह"@@ -955,9 +1010,9 @@ msgstr "क्या आप सुनिश्चित हैं कि आपmsgid "Are you sure you want to delete {0}?"msgstr "क्या आप {0} को हटाना सुनिश्चित हैं?"+#. placeholder {0}: initialValues.memoId+#. placeholder {0}: initialValues.paymentId#. placeholder {0}: pickingList.pickingListId-#. placeholder {0}: routeData?.consumableSummary?.readableIdWithRevision-#. placeholder {0}: routeData?.customer?.name!msgid "Are you sure you want to delete {0}? This cannot be undone."msgstr "क्या आप सुनिश्चित हैं कि आप {0} को हटाना चाहते हैं? यह पूर्ववत नहीं किया जा सकता।"@@ -1243,6 +1298,9 @@ msgstr "क्या आप सुनिश्चित हैं?"msgid "As needed"msgstr "आवश्यकतानुसार"+msgid "As of:"+msgstr "इसके अनुसार:"+msgid "As the company owner, you can transfer ownership to another employee. This will give them full access to billing and administrative settings."msgstr "कंपनी के मालिक के रूप में, आप स्वामित्व किसी अन्य कर्मचारी को स्थानांतरित कर सकते हैं। यह उन्हें बिलिंग और प्रशासनिक सेटिंग्स तक पूर्ण पहुंच देगा।"@@ -1371,6 +1429,9 @@ msgstr "ऑडिट लॉग्स"msgid "Authentication Error"msgstr "प्रमाणीकरण त्रुटि"+msgid "Auto apply"+msgstr "स्वचालित रूप से लागू करें"+msgid "Auto Release"msgstr "ऑटो रिलीज़"@@ -1440,9 +1501,15 @@ msgstr "बैकफ्लश"msgid "Backups"msgstr "बैकअप"+msgid "Balance"+msgstr "शेष"+msgid "Balance Sheet"msgstr "बैलेंस शीट"+msgid "Balanced"+msgstr "संतुलित"+msgid "Balloon"msgstr "गुब्बारा"@@ -1464,6 +1531,9 @@ msgstr "बैंक — विदेशी मुद्रा (डिफ़ॉmsgid "Bank — Local Currency (default)"msgstr "बैंक — स्थानीय मुद्रा (डिफ़ॉल्ट)"+msgid "Bank / Cash Account"+msgstr "बैंक / नकद खाता"+msgid "Bank account denominated in a foreign currency"msgstr "बैंक खाता एक विदेशी मुद्रा में मूल्यवर्गित।"@@ -1643,6 +1713,12 @@ msgstr "द्वारा {byUser}"msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."msgstr "आमंत्रण स्वीकार करके, आप <0>सेवा की शर्तें</0> और <1>गोपनीयता नीति</1> से सहमत हैं।"+msgid "By Document Date"+msgstr "दस्तावेज़ तारीख के अनुसार"++msgid "By Due Date"+msgstr "देय तारीख के अनुसार"+msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"msgstr "साइन इन करके, आप <0>सेवा की शर्तें</0> और <1>गोपनीयता नीति</1> से सहमत हैं।"@@ -1931,6 +2007,9 @@ msgstr "खोज साफ़ करें"msgid "Clear search query"msgstr "खोज क्वेरी साफ़ करें"+msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."+msgstr "इस चालान को पार्टी के पोस्ट किए गए क्रेडिट के साथ-साथ नकद से साफ़ करें। क्रेडिट सीधे लागू होते हैं — कोई पोस्टिंग की आवश्यकता नहीं है।"+msgid "Clearing account between goods receipt and supplier invoice; balances when both have posted."msgstr "माल की प्राप्ति और आपूर्तिकर्ता चालान के बीच समाशोधन खाता; जब दोनों को पोस्ट किया जाता है तो संतुलन होता है।"@@ -1977,6 +2056,9 @@ msgstr "क्लाउड, या आपका स्व-होस्ट किmsgid "Code"msgstr "कोड"+msgid "Collapse"+msgstr "संक्षिप्त करें"+msgid "Collapse all"msgstr "सभी को संक्षिप्त करें"@@ -2552,6 +2634,12 @@ msgstr "दस्तावेज़ लोड नहीं हो सके"msgid "Count"msgstr "गिनती"+msgid "Counterparties"+msgstr "प्रतिपक्ष"++msgid "Counterparty"+msgstr "प्रतिपक्ष"+msgid "Country"msgstr "देश"@@ -2582,6 +2670,9 @@ msgstr "एक नई उद्धरण ID के साथ एक उद्धmsgid "Create Account"msgstr "खाता बनाएं"+msgid "Create adjusting entry"+msgstr "समायोजन प्रविष्टि बनाएं"+msgid "Create an account"msgstr "एक खाता बनाएं"@@ -2755,12 +2846,21 @@ msgstr "भाग बनाया जा रहा है..."msgid "Credit"msgstr "क्रेडिट"+msgid "Credit / Debit Memos"+msgstr "क्रेडिट / डेबिट मेमो"+msgid "Credit Account"msgstr "क्रेडिट खाता"msgid "Credit account when labor/machine time is absorbed into WIP"msgstr "क्रेडिट खाता जब श्रम / मशीन समय WIP में अवशोषित होता है"+msgid "Credits & Debits"+msgstr "क्रेडिट और डेबिट"++msgid "Credits applied"+msgstr "क्रेडिट लागू किए गए"+msgid "Critical"msgstr "महत्वपूर्ण"@@ -2935,6 +3035,9 @@ msgstr "ग्राहक प्रकार"msgid "Customer Types"msgstr "ग्राहक प्रकार"+msgid "Customer Write-Off (Bad Debt)"+msgstr "ग्राहक राइट-ऑफ (बुरा कर्ज)"+msgid "customers"msgstr "ग्राहकों"@@ -3314,12 +3417,18 @@ msgstr "सामग्री आकार हटाएं"msgid "Delete Material Type"msgstr "सामग्री प्रकार हटाएं"+msgid "Delete Memo"+msgstr "मेमो हटाएं"+msgid "Delete Part"msgstr "भाग हटाएं"msgid "Delete Partner"msgstr "पार्टनर हटाएं"+msgid "Delete Payment"+msgstr "भुगतान हटाएं"+msgid "Delete Payment Term"msgstr "भुगतान अवधि हटाएं"@@ -3566,6 +3675,12 @@ msgstr "आयाम"msgid "Direct"msgstr "सीधा"+msgid "Direction"+msgstr "दिशा"++msgid "Directions"+msgstr "दिशाएं"+msgid "Disabled"msgstr "अक्षम"@@ -3584,6 +3699,10 @@ msgstr "छूट दिन"msgid "Discount Days after {selectedCalculationMethod}"msgstr "{selectedCalculationMethod} के बाद छूट के दिन"+#. placeholder {0}: r.invoiceId+msgid "Discount for {0}"+msgstr "{0} के लिए छूट"+msgid "Discount Percent"msgstr "छूट प्रतिशत"@@ -3717,6 +3836,9 @@ msgstr "आरेख और सुविधाओं को पुनः आकmsgid "Drag to zoom"msgstr "ज़ूम करने के लिए ड्रैग करें"+msgid "Drawing"+msgstr "आहरण"+msgid "Drawing Number"msgstr "ड्राइंग नंबर"@@ -3952,6 +4074,9 @@ msgstr "सामग्री पदार्थ संपादित करेmsgid "Edit Material Type"msgstr "सामग्री प्रकार संपादित करें"+msgid "Edit Memo"+msgstr "मेमो संपादित करें"+msgid "Edit Non Conformance Type"msgstr "गैर अनुरूपता प्रकार संपादित करें"@@ -3961,6 +4086,9 @@ msgstr "भाग संपादित करें"msgid "Edit Partner"msgstr "पार्टनर संपादित करें"+msgid "Edit Payment"+msgstr "भुगतान संपादित करें"+msgid "Edit Payment Term"msgstr "भुगतान शर्त संपादित करें"@@ -4442,12 +4570,18 @@ msgstr "अपेक्षित रसीद"msgid "Expected Receipt Date"msgstr "अपेक्षित प्राप्ति तारीख"+msgid "Expense account for customer balances written off as uncollectable on AR settlement"+msgstr "AR निपटान पर अनिर्धारणीय के रूप में लिखे गए ग्राहक शेष के लिए व्यय खाता"+msgid "Expense account for deferred tax adjustments on depreciation"msgstr "मूल्यह्रास पर स्थगित कर समायोजन के लिए व्यय खाता"msgid "Expense account for equipment and facility maintenance"msgstr "उपकरण और सुविधा रखरखाव के लिए व्यय खाता"+msgid "Expense account for FX losses when a payment settles a foreign-currency invoice at a less favorable rate"+msgstr "विदेशी मुद्रा हानि के लिए व्यय खाता जब कोई भुगतान विदेशी मुद्रा चालान को कम अनुकूल दर पर निपटाता है"+msgid "Expense account for non-inventory purchases (services, supplies)"msgstr "गैर-इन्वेंटरी खरीद (सेवाएं, आपूर्ति) के लिए व्यय खाता"@@ -5028,9 +5162,15 @@ msgstr "शुक्रवार"msgid "From {0}"msgstr "{0} से"+msgid "From customer"+msgstr "ग्राहक से"+msgid "From Location"msgstr "स्थान से"+msgid "from on-account credit"+msgstr "खाता-पर क्रेडिट से"+msgid "From Storage Unit"msgstr "स्टोरेज यूनिट से"@@ -5040,6 +5180,9 @@ msgstr "पूरा करने का स्थान"msgid "Fully trained for"msgstr "पूरी तरह प्रशिक्षित"+msgid "FX G/L"+msgstr "FX G/L"+msgid "Gains and Losses"msgstr "लाभ और हानि (डिफ़ॉल्ट)"@@ -5127,6 +5270,9 @@ msgstr "कार्बन के चारों ओर घूमना"msgid "Getting set up"msgstr "सेटअप हो रहा है"+msgid "GL"+msgstr "GL"+msgid "GL Account"msgstr "जीएल खाता"@@ -5241,6 +5387,12 @@ msgstr "गैर-इन्वेंटरी खरीद के लिए GLmsgid "GL liability account credited for sales tax collected from customers."msgstr "ग्राहकों से एकत्र किए गए बिक्री कर के लिए GL देयता खाता।"+msgid "GL tie-out"+msgstr "GL समाधान"++msgid "GL Tie-Out"+msgstr "GL टाई-आउट"+msgid "Go live right the first time — with our team alongside you"msgstr "पहली बार ही सही तरीके से लाइव जाएं — हमारी टीम आपके साथ है"@@ -5773,6 +5925,9 @@ msgstr "आंतरिक संदर्भ जहां प्रत्येmsgid "inv"msgstr "इन्व"+msgid "Inv Rate"+msgstr "इनवॉइस दर"+msgid "Invalid Invite"msgstr "अमान्य निमंत्रण"@@ -5884,6 +6039,12 @@ msgstr "चालान किए गए स्थितियां"msgid "Invoices"msgstr "चालान"+msgid "Invoices this memo has been applied to. Click a row to open the document."+msgstr "इस मेमो को लागू किए गए चालान। दस्तावेज़ खोलने के लिए एक पंक्ति पर क्लिक करें।"++msgid "Invoicing"+msgstr "चालान"+msgid "is"msgstr "है"@@ -6451,6 +6612,13 @@ msgstr "Make आइटम्स को सीधे इनवॉइस नहीmsgid "Make Method Version"msgstr "मेक मेथड संस्करण"+msgid "Make Payment"+msgstr "भुगतान करें"++#. placeholder {0}: selectedInvoices.length+msgid "Make Payment · {0} invoices"+msgstr "भुगतान करें · {0} चालान"+#. placeholder {0}: selectedRevision.revisionmsgid "Make revision {0} default?"msgstr "संशोधन {0} को डिफ़ॉल्ट बनाएं?"@@ -6693,6 +6861,15 @@ msgstr "मीटिंग कैडेंस"msgid "Members"msgstr "सदस्य"+msgid "Memo"+msgstr "मेमो"++msgid "Memo Date"+msgstr "मेमो तारीख"++msgid "Memo ID"+msgstr "मेमो आईडी"+msgid "MES"msgstr "MES"@@ -6953,6 +7130,9 @@ msgstr "नया उपभोग्य"msgid "New Contractor"msgstr "नया ठेकेदार"+msgid "New Credit / Debit Memo"+msgstr "नया क्रेडिट / डेबिट मेमो"+msgid "New Custom Field"msgstr "नया कस्टम फील्ड"@@ -7061,6 +7241,9 @@ msgstr "नया पार्ट"msgid "New Password"msgstr "नया पासवर्ड"+msgid "New Payment"+msgstr "नया भुगतान"+msgid "New Payment Term"msgstr "नया भुगतान शर्त"@@ -7252,6 +7435,9 @@ msgstr "कोई सक्रिय उद्धरण नहीं"msgid "No addresses found"msgstr "कोई पता नहीं मिला"+msgid "No applications. Payment will be on-account."+msgstr "कोई आवेदन नहीं। भुगतान खाते पर होगा।"+#. placeholder {0}: auditConfig.retentionDaysmsgid "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."msgstr "अभी तक कोई संग्रहीत लॉग नहीं है। {0} दिन से पुराने लॉग स्वचालित रूप से संग्रहीत किए जाएंगे और यहां डाउनलोड के लिए उपलब्ध होंगे।"@@ -7370,6 +7556,9 @@ msgstr "कोई नई सूचनाएं नहीं"msgid "No notes"msgstr "कोई नोट नहीं"+msgid "No open invoices"+msgstr "कोई खुले चालान नहीं"+msgid "No operations require picking at this location"msgstr "इस स्थान पर कोई भी ऑपरेशन पिकिंग की आवश्यकता नहीं है"@@ -7397,6 +7586,12 @@ msgstr "अभी तक कोई मूल स्रोत दर्ज नहmsgid "No part ID"msgstr "कोई भाग ID नहीं"+msgid "No payables"+msgstr "कोई देय नहीं"++msgid "No payments yet."+msgstr "अभी तक कोई भुगतान नहीं।"+msgid "No planning data"msgstr "कोई योजना डेटा नहीं"@@ -7421,6 +7616,9 @@ msgstr "कोई उद्धरण कारण नहीं"msgid "No Quote Reasons"msgstr "कोई उद्धरण कारण नहीं"+msgid "No receivables"+msgstr "कोई प्राप्य नहीं"+msgid "No remaining entities to inspect."msgstr "निरीक्षण के लिए कोई शेष इकाई नहीं है।"@@ -7598,6 +7796,9 @@ msgstr "बिक्रय आदेश पर"msgid "On Storage Unit"msgstr "स्टोरेज यूनिट पर"+msgid "On-account credit available"+msgstr "खाते पर उपलब्ध क्रेडिट"+msgid "On-hand counts"msgstr "हाथ में मौजूद गिनती"@@ -7818,6 +8019,12 @@ msgstr "ऑर्डर जमा किए गए"msgid "Origin"msgstr "मूल"+msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"+msgstr "विदेशी मुद्रा लाभ के लिए अन्य आय खाता जब कोई भुगतान विदेशी-मुद्रा चालान को अधिक अनुकूल दर पर निपटाता है"++msgid "Other Income account for vendor balances cleared without full payment on AP settlement"+msgstr "विक्रेता शेष राशि के लिए अन्य आय खाता जो AP निपटान पर पूर्ण भुगतान के बिना साफ़ किया गया है"+msgid "Other Type"msgstr "अन्य प्रकार"@@ -7839,6 +8046,9 @@ msgstr "आउटपुट कभी भी अपनी कच्ची साmsgid "Outside operation"msgstr "ओवरहेड विचरण"+msgid "Over-applied by"+msgstr "अत्यधिक लागू किया गया"+msgid "Overdue"msgstr "अतिदेय"@@ -7975,6 +8185,9 @@ msgstr "पार्ट्स और आइटम्स"msgid "Parts, materials, and how you classify them."msgstr "पार्ट्स, सामग्री, और आप उन्हें कैसे वर्गीकृत करते हैं।"+msgid "Party Type"+msgstr "पक्ष प्रकार"+msgid "Pass"msgstr "पास"@@ -7984,17 +8197,29 @@ msgstr "पास · फिर से खोलें"msgid "Path"msgstr "पथ"+msgid "Pay Rate"+msgstr "भुगतान दर"+msgid "Payables"msgstr "देय खाते (डिफ़ॉल्ट)"msgid "Payables (default)"msgstr "भुगतान अवधि"+msgid "Payables aging"+msgstr "देय राशि की आयु"+msgid "Payment"msgstr "भुगतान"-msgid "Payment Method"-msgstr "भुगतान विधि"+msgid "Payment Applications"+msgstr "भुगतान अनुप्रयोग"++msgid "Payment Date"+msgstr "भुगतान तारीख"++msgid "Payment ID"+msgstr "भुगतान ID"msgid "payment term"msgstr "भुगतान अवधि"@@ -8011,6 +8236,12 @@ msgstr "भुगतान शर्तें"msgid "Payment terms like Net 30 or due on receipt"msgstr "Net 30 जैसी भुगतान शर्तें या प्राप्ति पर देय"+msgid "Payments"+msgstr "भुगतान"++msgid "Payments and credits applied to this invoice. Click a row to open the source document."+msgstr "इस चालान पर लागू किए गए भुगतान और क्रेडिट। स्रोत दस्तावेज़ खोलने के लिए एक पंक्ति पर क्लिक करें।"+msgid "PDF"msgstr "PDF"@@ -8672,6 +8903,9 @@ msgstr "क्रय और स्वचालित योजना"msgid "Purchasing Contact"msgstr "क्रय संपर्क"+msgid "Purchasing Invoices"+msgstr "खरीद चालान"+msgid "Purchasing Unit of Measure"msgstr "क्रय माप की इकाई"@@ -8866,9 +9100,18 @@ msgstr "रीयल-टाइम इन्वेंटरी और शॉप-msgid "Real-time questions during hypercare"msgstr "हाइपरकेयर के दौरान रीयल-टाइम प्रश्न"+msgid "Realized Exchange Gain"+msgstr "वास्तविक विनिमय लाभ"++msgid "Realized Exchange Loss"+msgstr "वास्तविक विनिमय हानि"+msgid "Reason"msgstr "कारण"+msgid "Reason Account"+msgstr "कारण खाता"+msgid "Reason for declining (Optional)"msgstr "अस्वीकार करने का कारण (वैकल्पिक)"@@ -8911,6 +9154,9 @@ msgstr "प्राप्य खाते (डिफ़ॉल्ट)"msgid "Receivables (default)"msgstr "एक क्रय आदेश को प्राप्त और चालान किए गए के साथ समेटना — Carbon में निहित, लाइन मात्रा और GR/IR शेष के माध्यम से।"+msgid "Receivables aging"+msgstr "प्राप्य उम्र बढ़ना"+msgid "Receive"msgstr "प्राप्त करें"@@ -8921,6 +9167,13 @@ msgstr "{0} को इन्वेंटरी में प्राप्तmsgid "Receive against a PO and update inventory"msgstr "PO के विरुद्ध प्राप्त करें और इन्वेंटरी अपडेट करें"+msgid "Receive Payment"+msgstr "भुगतान प्राप्त करें"++#. placeholder {0}: selectedInvoices.length+msgid "Receive Payment · {0} invoices"+msgstr "भुगतान प्राप्त करें · {0} चालान"+msgid "Receive to Inventory"msgstr "इन्वेंटरी में प्राप्त करें"@@ -8944,6 +9197,9 @@ msgstr "प्राप्ति स्थान"msgid "Recent"msgstr "हाल ही में"+msgid "Recent payments"+msgstr "हाल के भुगतान"+msgid "Recently Created"msgstr "हाल ही में बनाया गया"@@ -8953,6 +9209,12 @@ msgstr "वसूली अवधि"msgid "Record"msgstr "रिकॉर्ड करें"+msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."+msgstr "एक ग्राहक या आपूर्तिकर्ता के विरुद्ध क्रेडिट या डेबिट मेमो रिकॉर्ड करें। विशिष्ट चालानों के लिए आवेदन मेमो बनाने के बाद जोड़े जाते हैं।"++msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."+msgstr "ग्राहक से प्राप्त नकद (रसीद) या आपूर्तिकर्ता को दिया गया नकद (वितरण) दर्ज करें। विशिष्ट चालानों के लिए आवेदन भुगतान बनाने के बाद जोड़े जाते हैं।"+msgid "Record deleted"msgstr "रिकॉर्ड हटाया गया"@@ -9037,6 +9299,9 @@ msgstr "जॉब रिलीज़ करें"msgid "Released"msgstr "जारी किया गया"+msgid "Remaining"+msgstr "शेष"+msgid "Remaining after split stays on the original row."msgstr "विभाजन के बाद शेष मूल पंक्ति पर रहता है।"@@ -9583,6 +9848,9 @@ msgstr "सहेजें और बंद करें"msgid "Save and Overwrite"msgstr "सहेजें और अधिलेखित करें"+msgid "Save applications"+msgstr "आवेदन सहेजें"+msgid "Save contacts"msgstr "संपर्क सहेजें"@@ -9824,6 +10092,15 @@ msgstr "गेज चुनें"msgid "Select groups or individuals"msgstr "समूह या व्यक्तियों का चयन करें"+msgid "Select invoice"+msgstr "चालान चुनें"++msgid "Select invoices from a single counterparty"+msgstr "एक ही प्रतिपक्ष से चालान चुनें"++msgid "Select invoices in a single currency"+msgstr "एक ही मुद्रा में चालान चुनें"+msgid "Select Item Type"msgstr "आइटम प्रकार चुनें"@@ -9860,6 +10137,9 @@ msgstr "सतहें चुनें"msgid "Select the groups that should complete this training"msgstr "उन समूहों का चयन करें जिन्हें इस प्रशिक्षण को पूरा करना चाहिए"+msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."+msgstr "इस भुगतान को निपटाने वाले चालान चुनें। छूट और राइट-ऑफ चालान मुद्रा में हैं।"+msgid "Select value"msgstr "मान चुनें"@@ -10575,6 +10855,9 @@ msgstr "उप-अनुबंध विचलन"msgid "Subcontracting Variance (default)"msgstr "उप-अनुबंध विचलन (डिफ़ॉल्ट)"+msgid "Subledger"+msgstr "सहायक बहीखाता"+msgid "Submit anonymously"msgstr "गुमनाम रूप से सबमिट करें"@@ -11597,6 +11880,9 @@ msgstr "इस RFQ के लिए तुलना करने के लिmsgid "There are outside operations associated with this job that have no suppliers. Please assign a supplier to each outside operation before releasing it."msgstr "इस नौकरी से जुड़े बाहरी संचालन हैं जिनके पास कोई आपूर्तिकर्ता नहीं है। इसे जारी करने से पहले कृपया प्रत्येक बाहरी संचालन को एक आपूर्तिकर्ता असाइन करें।"+msgid "There's nothing outstanding to apply these credits to."+msgstr "इन क्रेडिट्स को लागू करने के लिए कुछ भी बकाया नहीं है।"+msgid "These custom fields will only be available for entities with the same tags"msgstr "ये कस्टम फ़ील्ड केवल समान टैग वाली संस्थाओं के लिए उपलब्ध होंगी"@@ -11612,6 +11898,9 @@ msgstr "इन कार्यों के पास इस कार्य कmsgid "This completes the Discovery step."msgstr "यह Discovery चरण को पूरा करता है।"+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."+msgstr "यह प्रतिपक्ष के पास कुछ भी बकाया नहीं है — भुगतान खाते पर दर्ज किया जाएगा।"+msgid "This information will be used on document headers"msgstr "यह जानकारी दस्तावेज़ शीर्षलेख पर उपयोग की जाएगी"@@ -11720,6 +12009,9 @@ msgstr "गुरुवार"msgid "Tie shipments through to an invoice with no re-keying"msgstr "शिपमेंट को बिना पुनः-कुंजीयन के चालान से जोड़ें"+msgid "Tie-Out"+msgstr "टाई-आउट"+msgid "Tightened"msgstr "कड़ा"@@ -11756,6 +12048,9 @@ msgstr "भेजने और प्राप्त करने के लिmsgid "To Storage Unit"msgstr "स्टोरेज यूनिट को"+msgid "To supplier"+msgstr "आपूर्तिकर्ता को"+msgid "Today"msgstr "आज"@@ -11825,6 +12120,9 @@ msgstr "शीर्ष-स्तर वर्गीकरण (संपत्msgid "Total"msgstr "कुल"+msgid "Total Amount"+msgstr "कुल राशि"+msgid "Total capitalized cost of the asset (purchase price plus freight, install, and other costs that become part of book value)."msgstr "संपत्ति की कुल पूंजीकृत लागत (खरीद मूल्य प्लस माल ढुलाई, स्थापना, और अन्य लागतें जो बही मूल्य का हिस्सा बन जाती हैं)।"@@ -11852,6 +12150,9 @@ msgstr "इस स्थान पर सभी सक्रिय कार्msgid "Total:"msgstr "कुल:"+msgid "Totals"+msgstr "कुल"+msgid "Traceability"msgstr "ट्रेसेबिलिटी"@@ -12008,6 +12309,12 @@ msgstr "प्रकार"msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."msgstr "नमूना न लिए गए इकाइयां On Hold पर रहेंगी ताकि आप निरीक्षण जारी रख सकें और बाद में निपटान कर सकें। नमूना किए गए परिणाम संरक्षित रहते हैं।"+msgid "Unapplied"+msgstr "अप्रयुक्त"++msgid "Unapplied:"+msgstr "लागू नहीं:"+msgid "Unapproved Supplier"msgstr "अनुमोदित नहीं आपूर्तिकर्ता"@@ -12351,6 +12658,9 @@ msgstr "मूल्य वर्धित कर पंजीकरण संmsgid "Values"msgstr "मूल्य"+msgid "Variance"+msgstr "विचरण"+msgid "Variance between actual and standard BOM component consumption"msgstr "वास्तविक और मानक बीओएम घटक खपत के बीच विचरण"@@ -12372,6 +12682,9 @@ msgstr "बाहरी प्रसंस्करण लागत मेंmsgid "VAT Number"msgstr "VAT संख्या"+msgid "Vendor Write-Off Income"+msgstr "विक्रेता राइट-ऑफ आय"+msgid "Verification Error"msgstr "सत्यापन त्रुटि"@@ -12453,6 +12766,9 @@ msgstr "सूचियाँ देखें"msgid "View maintenance dispatch"msgstr "रखरखाव डिस्पैच देखें"+msgid "View Memo"+msgstr "मेमो देखें"+msgid "View missing values"msgstr "लापता मानों को देखें"@@ -12474,6 +12790,9 @@ msgstr "खुली उद्धरणें देखें"msgid "View Open RFQs"msgstr "खुले RFQ देखें"+msgid "View Payment"+msgstr "भुगतान देखें"+msgid "View permissions"msgstr "देखने की अनुमतियाँ"@@ -13042,9 +13361,19 @@ msgstr "सबसे खराब प्रदर्शन करने वाmsgid "Write-Down Account"msgstr "मूल्य ह्रास खाता"+msgid "Write-off"+msgstr "लिखित-बंद"++msgid "Write-Off"+msgstr "लिखित-बंद"+msgid "Write-Off Account"msgstr "बट्टे खाता"+#. placeholder {0}: r.invoiceId+msgid "Write-off for {0}"+msgstr "{0} के लिए राइट-ऑफ"+msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."msgstr "किसी संपत्ति के मूल्य को उसके जीवन काल में कम करना — एक मासिक बैच जो आप बनाते हैं, ड्राफ्ट के रूप में समीक्षा करते हैं, फिर पोस्ट करते हैं।"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex bce0ad41ee..c172be71be 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -31,6 +31,10 @@ msgstr "\"Nessuno è stato licenziato per averlo comprato.\" Un fattore di comfomsgid "(excluded for this customer)"msgstr "(escluso per questo cliente)"+#. placeholder {0}: ar.count+msgid "{0} customers with a balance"+msgstr "{0} clienti con saldo"+#. placeholder {0}: rule.escalationDaysmsgid "{0} days"msgstr "{0} giorni"@@ -48,6 +52,10 @@ msgstr "{0} ordini"msgid "{0} Processes"msgstr "{0} Processi"+#. placeholder {0}: ap.count+msgid "{0} suppliers with a balance"+msgstr "{0} fornitori con un saldo"+#. placeholder {0}: lotEntities.length - inspectedmsgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "{0} entità non campionate verranno rilasciate a Disponibile. I campioni approvati rimangono Disponibili e i campioni rifiutati rimangono Rifiutati."@@ -60,6 +68,12 @@ msgstr "{0} caricato con successo"msgid "{0} values missing"msgstr "{0} valori mancanti"+msgid "{apOverduePct}% of payables"+msgstr "{apOverduePct}% dei debiti"++msgid "{arOverduePct}% of receivables"+msgstr "{arOverduePct}% dei crediti"+msgid "{chainLabel}. Consider pointing this part directly at the final successor."msgstr "{chainLabel}. Considera di indirizzare direttamente questa parte al successore finale."@@ -743,6 +757,10 @@ msgstr "Importo che aumenta i cespiti/spese o diminuisce i debiti/patrimonio netmsgid "Amount that increases liabilities/equity/revenue or decreases assets/expenses on this line."msgstr "Importo che aumenta i debiti/patrimonio netto/ricavi o diminuisce i cespiti/spese su questa riga."+#. placeholder {0}: r.memoId+msgid "Amount to apply for {0}"+msgstr "Importo da applicare per {0}"+msgid "Amount Type"msgstr "Tipo di Importo"@@ -806,6 +824,12 @@ msgstr "Qualsiasi cosa non esplicitamente elencata nell'ambito di cui sopra"msgid "AP Clerk"msgstr "Addetto Contabilità Fornitori"+msgid "AP Outstanding"+msgstr "AP in sospeso"++msgid "AP Overdue"+msgstr "AP Scaduto"+msgid "API and Webhooks"msgstr "API e Webhook"@@ -824,6 +848,19 @@ msgstr "Chiavi API"msgid "API keys for programmatic access to your Carbon data."msgstr "Chiavi API per l'accesso programmatico ai tuoi dati Carbon."+msgid "Applied"+msgstr "Applicato"++#. placeholder {0}: r.invoiceId+msgid "Applied amount for {0}"+msgstr "Importo applicato per {0}"++msgid "Applied Date"+msgstr "Data di applicazione"++msgid "Applied To"+msgstr "Applicato A"+msgid "Applies to"msgstr "Si applica a"@@ -833,6 +870,12 @@ msgstr "Si applica a tutti"msgid "Applies to all work centers"msgstr "Si applica a tutti i centri di lavoro"+msgid "Apply available credits"+msgstr "Applica crediti disponibili"++msgid "Apply credits"+msgstr "Applica crediti"+msgid "Apply payments and track aging"msgstr "Applicare i pagamenti e tracciare l'invecchiamento"@@ -845,6 +888,12 @@ msgstr "Applica regole in alto"msgid "Apply To"msgstr "Applica a"+msgid "Apply to invoice"+msgstr "Applica alla fattura"++msgid "Apply to invoices"+msgstr "Applica alle fatture"+msgid "Approaching {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB cap."msgstr "Avvicinandosi al limite di {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB."@@ -875,6 +924,12 @@ msgstr "AQL (Z1.4 / ISO 2859-1)"msgid "AR Clerk"msgstr "Addetto Contabilità Clienti"+msgid "AR Outstanding"+msgstr "Crediti in sospeso"++msgid "AR Overdue"+msgstr "AR Scaduto"+msgid "Archive"msgstr "Archivio"@@ -955,9 +1010,9 @@ msgstr "Sei sicuro di voler eliminare {0} da questa operazione? Questa azione nomsgid "Are you sure you want to delete {0}?"msgstr "Sei sicuro di voler eliminare {0}?"+#. placeholder {0}: initialValues.memoId+#. placeholder {0}: initialValues.paymentId#. placeholder {0}: pickingList.pickingListId-#. placeholder {0}: routeData?.consumableSummary?.readableIdWithRevision-#. placeholder {0}: routeData?.customer?.name!msgid "Are you sure you want to delete {0}? This cannot be undone."msgstr "Sei sicuro di voler eliminare {0}? Questa azione non può essere annullata."@@ -1243,6 +1298,9 @@ msgstr "Sei sicuro?"msgid "As needed"msgstr "Su richiesta"+msgid "As of:"+msgstr "A partire da:"+msgid "As the company owner, you can transfer ownership to another employee. This will give them full access to billing and administrative settings."msgstr "Come proprietario dell'azienda, puoi trasferire la proprietà a un altro dipendente. Questo darà loro accesso completo alla fatturazione e alle impostazioni amministrative."@@ -1371,6 +1429,9 @@ msgstr "Registri di Audit"msgid "Authentication Error"msgstr "Errore di autenticazione"+msgid "Auto apply"+msgstr "Applica automaticamente"+msgid "Auto Release"msgstr "Rilascio Automatico"@@ -1440,9 +1501,15 @@ msgstr "Scarico automatico"msgid "Backups"msgstr "Backup"+msgid "Balance"+msgstr "Saldo"+msgid "Balance Sheet"msgstr "Bilancio"+msgid "Balanced"+msgstr "Equilibrato"+msgid "Balloon"msgstr "Palloncino"@@ -1464,6 +1531,9 @@ msgstr "Banca — Valuta estera (predefinita)"msgid "Bank — Local Currency (default)"msgstr "Banca — Valuta locale (predefinita)"+msgid "Bank / Cash Account"+msgstr "Conto Bancario / Cassa"+msgid "Bank account denominated in a foreign currency"msgstr "Conto bancario denominato in una valuta estera."@@ -1643,6 +1713,12 @@ msgstr "da {byUser}"msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."msgstr "Accettando l'invito, accetti i <0>Termini di Servizio</0> e l'<1>Informativa sulla Privacy</1>."+msgid "By Document Date"+msgstr "Per Data Documento"++msgid "By Due Date"+msgstr "Per Data di Scadenza"+msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"msgstr "Accedendo, accetti i <0>Termini di Servizio</0> e l'<1>Informativa sulla Privacy.</1>"@@ -1931,6 +2007,9 @@ msgstr "Cancella ricerca"msgid "Clear search query"msgstr "Cancella query di ricerca"+msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."+msgstr "Cancella questa fattura con i crediti registrati della parte nonché in contanti. I crediti si applicano direttamente — nessuna registrazione necessaria."+msgid "Clearing account between goods receipt and supplier invoice; balances when both have posted."msgstr "Conto di compensazione tra ricevimento merce e fattura fornitore; si compensa quando entrambi sono stati registrati."@@ -1977,6 +2056,9 @@ msgstr "Cloud, o il tuo ambiente self-hosted."msgid "Code"msgstr "Codice"+msgid "Collapse"+msgstr "Comprimi"+msgid "Collapse all"msgstr "Comprimi tutto"@@ -2552,6 +2634,12 @@ msgstr "Impossibile caricare i documenti"msgid "Count"msgstr "Conteggio"+msgid "Counterparties"+msgstr "Controparte"++msgid "Counterparty"+msgstr "Controparte"+msgid "Country"msgstr "Paese"@@ -2582,6 +2670,9 @@ msgstr "Crea un preventivo con un nuovo ID preventivo"msgid "Create Account"msgstr "Crea Account"+msgid "Create adjusting entry"+msgstr "Crea voce di rettifica"+msgid "Create an account"msgstr "Crea un account"@@ -2755,12 +2846,21 @@ msgstr "Creazione parte in corso..."msgid "Credit"msgstr "Credito"+msgid "Credit / Debit Memos"+msgstr "Memo di Credito / Debito"+msgid "Credit Account"msgstr "Conto Credito"msgid "Credit account when labor/machine time is absorbed into WIP"msgstr "Conto credito quando il tempo di lavoro/macchina viene assorbito in WIP"+msgid "Credits & Debits"+msgstr "Crediti e Debiti"++msgid "Credits applied"+msgstr "Crediti applicati"+msgid "Critical"msgstr "Critico"@@ -2935,6 +3035,9 @@ msgstr "tipi di cliente"msgid "Customer Types"msgstr "Tipi di Cliente"+msgid "Customer Write-Off (Bad Debt)"+msgstr "Cancellazione Cliente (Crediti Inesigibili)"+msgid "customers"msgstr "clienti"@@ -3314,12 +3417,18 @@ msgstr "Elimina Forma Materiale"msgid "Delete Material Type"msgstr "Elimina Tipo di Materiale"+msgid "Delete Memo"+msgstr "Elimina Memo"+msgid "Delete Part"msgstr "Elimina Parte"msgid "Delete Partner"msgstr "Elimina Partner"+msgid "Delete Payment"+msgstr "Elimina Pagamento"+msgid "Delete Payment Term"msgstr "Elimina Termine di Pagamento"@@ -3566,6 +3675,12 @@ msgstr "Dimensioni"msgid "Direct"msgstr "Diretto"+msgid "Direction"+msgstr "Direzione"++msgid "Directions"+msgstr "Direzioni"+msgid "Disabled"msgstr "Disabilitato"@@ -3584,6 +3699,10 @@ msgstr "Giorni di Sconto"msgid "Discount Days after {selectedCalculationMethod}"msgstr "Giorni di sconto dopo {selectedCalculationMethod}"+#. placeholder {0}: r.invoiceId+msgid "Discount for {0}"+msgstr "Sconto per {0}"+msgid "Discount Percent"msgstr "Percentuale di Sconto"@@ -3717,6 +3836,9 @@ msgstr "Trascinare per ridimensionare il diagramma e le funzioni"msgid "Drag to zoom"msgstr "Trascina per ingrandire"+msgid "Drawing"+msgstr "Prelievo"+msgid "Drawing Number"msgstr "Numero di Disegno"@@ -3952,6 +4074,9 @@ msgstr "Modifica Sostanza Materiale"msgid "Edit Material Type"msgstr "Modifica Tipo di Materiale"+msgid "Edit Memo"+msgstr "Modifica Memo"+msgid "Edit Non Conformance Type"msgstr "Modifica Tipo di Non Conformità"@@ -3961,6 +4086,9 @@ msgstr "Modifica Parte"msgid "Edit Partner"msgstr "Modifica Partner"+msgid "Edit Payment"+msgstr "Modifica Pagamento"+msgid "Edit Payment Term"msgstr "Modifica Condizioni di Pagamento"@@ -4442,12 +4570,18 @@ msgstr "Ricevimento Previsto"msgid "Expected Receipt Date"msgstr "Data di Ricezione Prevista"+msgid "Expense account for customer balances written off as uncollectable on AR settlement"+msgstr "Conto spese per i saldi dei clienti cancellati come non riscuotibili al momento del regolamento dei crediti"+msgid "Expense account for deferred tax adjustments on depreciation"msgstr "Conto spese per rettifiche di imposte differite su ammortamenti"msgid "Expense account for equipment and facility maintenance"msgstr "Conto spese per la manutenzione di attrezzature e impianti"+msgid "Expense account for FX losses when a payment settles a foreign-currency invoice at a less favorable rate"+msgstr "Conto spese per le perdite in valuta estera quando un pagamento regola una fattura in valuta estera a un tasso meno favorevole"+msgid "Expense account for non-inventory purchases (services, supplies)"msgstr "Conto spese per acquisti non di magazzino (servizi, forniture)"@@ -5028,9 +5162,15 @@ msgstr "Venerdì"msgid "From {0}"msgstr "Da {0}"+msgid "From customer"+msgstr "Da cliente"+msgid "From Location"msgstr "Da Ubicazione"+msgid "from on-account credit"+msgstr "dal credito a conto"+msgid "From Storage Unit"msgstr "Da Unità di Stoccaggio"@@ -5040,6 +5180,9 @@ msgstr "Ubicazione di Adempimento"msgid "Fully trained for"msgstr "Completamente formato per"+msgid "FX G/L"+msgstr "Utile/Perdita Cambi"+msgid "Gains and Losses"msgstr "Utili e Perdite (predefinito)"@@ -5127,6 +5270,9 @@ msgstr "Navigazione in Carbon"msgid "Getting set up"msgstr "Configurazione in corso"+msgid "GL"+msgstr "GL"+msgid "GL Account"msgstr "Conto Contabile"@@ -5241,6 +5387,12 @@ msgstr "Conto GL di spesa per acquisti non di magazzino (forniture, servizi)."msgid "GL liability account credited for sales tax collected from customers."msgstr "Conto GL di passività accreditato per l'IVA riscossa dai clienti."+msgid "GL tie-out"+msgstr "Riconciliazione GL"++msgid "GL Tie-Out"+msgstr "Riconciliazione GL"+msgid "Go live right the first time — with our team alongside you"msgstr "Vai in produzione al primo tentativo — con il nostro team al tuo fianco"@@ -5773,6 +5925,9 @@ msgstr "Riferimento interno per vedere dove ogni strumento è più forte. Usalomsgid "inv"msgstr "inv"+msgid "Inv Rate"+msgstr "Tasso Fattura"+msgid "Invalid Invite"msgstr "Invito Non Valido"@@ -5884,6 +6039,12 @@ msgstr "Stati Fatturati"msgid "Invoices"msgstr "Fatture"+msgid "Invoices this memo has been applied to. Click a row to open the document."+msgstr "Fatture a cui è stato applicato questo memo. Fare clic su una riga per aprire il documento."++msgid "Invoicing"+msgstr "Fatturazione"+msgid "is"msgstr "è"@@ -6451,6 +6612,13 @@ msgstr "Gli articoli Make non possono essere fatturati direttamente. Cambia il mmsgid "Make Method Version"msgstr "Versione Metodo di Produzione"+msgid "Make Payment"+msgstr "Effettua Pagamento"++#. placeholder {0}: selectedInvoices.length+msgid "Make Payment · {0} invoices"+msgstr "Effettua Pagamento · {0} fatture"+#. placeholder {0}: selectedRevision.revisionmsgid "Make revision {0} default?"msgstr "Rendere la revisione {0} predefinita?"@@ -6693,6 +6861,15 @@ msgstr "Cadenza di riunioni"msgid "Members"msgstr "Membri"+msgid "Memo"+msgstr "Nota"++msgid "Memo Date"+msgstr "Data Memo"++msgid "Memo ID"+msgstr "ID Memo"+msgid "MES"msgstr "MES"@@ -6953,6 +7130,9 @@ msgstr "Nuovo Consumabile"msgid "New Contractor"msgstr "Nuovo Appaltatore"+msgid "New Credit / Debit Memo"+msgstr "Nuovo Memo di Credito / Debito"+msgid "New Custom Field"msgstr "Nuovo Campo Personalizzato"@@ -7061,6 +7241,9 @@ msgstr "Nuova Parte"msgid "New Password"msgstr "Nuova Password"+msgid "New Payment"+msgstr "Nuovo Pagamento"+msgid "New Payment Term"msgstr "Nuovo Termine di Pagamento"@@ -7252,6 +7435,9 @@ msgstr "Nessuna Quotazione Attiva"msgid "No addresses found"msgstr "Nessun indirizzo trovato"+msgid "No applications. Payment will be on-account."+msgstr "Nessuna applicazione. Il pagamento sarà a conto."+#. placeholder {0}: auditConfig.retentionDaysmsgid "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."msgstr "Nessun log archiviato ancora. I log più vecchi di {0} giorni verranno archiviati automaticamente e disponibili per il download qui."@@ -7370,6 +7556,9 @@ msgstr "Nessuna nuova notifica"msgid "No notes"msgstr "Nessuna nota"+msgid "No open invoices"+msgstr "Nessuna fattura aperta"+msgid "No operations require picking at this location"msgstr "Nessuna operazione richiede il prelievo in questa posizione"@@ -7397,6 +7586,12 @@ msgstr "Nessuna fonte padre registrata ancora. Fai clic su Ricalcola nella paginmsgid "No part ID"msgstr "Nessun ID parte"+msgid "No payables"+msgstr "Nessun debito"++msgid "No payments yet."+msgstr "Nessun pagamento ancora."+msgid "No planning data"msgstr "Nessun dato di pianificazione"@@ -7421,6 +7616,9 @@ msgstr "Nessun motivo di preventivo"msgid "No Quote Reasons"msgstr "Nessun motivo di mancata offerta"+msgid "No receivables"+msgstr "Nessun credito"+msgid "No remaining entities to inspect."msgstr "Nessuna entità rimanente da ispezionare."@@ -7598,6 +7796,9 @@ msgstr "Su Ordine di Vendita"msgid "On Storage Unit"msgstr "Su Unità di Stoccaggio"+msgid "On-account credit available"+msgstr "Credito a conto disponibile"+msgid "On-hand counts"msgstr "Conteggi disponibili"@@ -7818,6 +8019,12 @@ msgstr "Ordini inviati"msgid "Origin"msgstr "Origine"+msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"+msgstr "Account di Altro Reddito per guadagni in valuta estera quando un pagamento regola una fattura in valuta estera a un tasso più favorevole"++msgid "Other Income account for vendor balances cleared without full payment on AP settlement"+msgstr "Account Altre Entrate per saldi fornitori liquidati senza pagamento completo al momento del regolamento dei Debiti verso Fornitori"+msgid "Other Type"msgstr "Altro Tipo"@@ -7839,6 +8046,9 @@ msgstr "L'output non supera mai i suoi materiali grezzi. Ritorna alla durata fismsgid "Outside operation"msgstr "Varianza Indiretta"+msgid "Over-applied by"+msgstr "Applicato in eccesso di"+msgid "Overdue"msgstr "Scaduto"@@ -7975,6 +8185,9 @@ msgstr "Parti e articoli"msgid "Parts, materials, and how you classify them."msgstr "Parti, materiali e come li classifichi."+msgid "Party Type"+msgstr "Tipo di Parte"+msgid "Pass"msgstr "Passa"@@ -7984,17 +8197,29 @@ msgstr "Superato · riapri"msgid "Path"msgstr "Percorso"+msgid "Pay Rate"+msgstr "Tasso di Pagamento"+msgid "Payables"msgstr "Debiti verso Fornitori (predefinito)"msgid "Payables (default)"msgstr "termine di pagamento"+msgid "Payables aging"+msgstr "Invecchiamento dei debiti"+msgid "Payment"msgstr "Pagamento"-msgid "Payment Method"-msgstr "Metodo di Pagamento"+msgid "Payment Applications"+msgstr "Applicazioni di Pagamento"++msgid "Payment Date"+msgstr "Data di Pagamento"++msgid "Payment ID"+msgstr "ID Pagamento"msgid "payment term"msgstr "termini di pagamento"@@ -8011,6 +8236,12 @@ msgstr "Condizioni di Pagamento"msgid "Payment terms like Net 30 or due on receipt"msgstr "Termini di pagamento come Net 30 o pagamento alla ricezione"+msgid "Payments"+msgstr "Pagamenti"++msgid "Payments and credits applied to this invoice. Click a row to open the source document."+msgstr "Pagamenti e crediti applicati a questa fattura. Fai clic su una riga per aprire il documento di origine."+msgid "PDF"msgstr "PDF"@@ -8672,6 +8903,9 @@ msgstr "Acquisti e pianificazione automatica"msgid "Purchasing Contact"msgstr "Contatto Acquisti"+msgid "Purchasing Invoices"+msgstr "Fatture di Acquisto"+msgid "Purchasing Unit of Measure"msgstr "Unità di Misura di Acquisto"@@ -8866,9 +9100,18 @@ msgstr "Visibilità dell'inventario e del reparto di produzione in tempo reale"msgid "Real-time questions during hypercare"msgstr "Domande in tempo reale durante l'hypercare"+msgid "Realized Exchange Gain"+msgstr "Guadagno da Cambio Realizzato"++msgid "Realized Exchange Loss"+msgstr "Perdita di cambio realizzata"+msgid "Reason"msgstr "Motivo"+msgid "Reason Account"+msgstr "Conto Motivo"+msgid "Reason for declining (Optional)"msgstr "Motivo del rifiuto (Facoltativo)"@@ -8911,6 +9154,9 @@ msgstr "Crediti verso Clienti (predefinito)"msgid "Receivables (default)"msgstr "Riconciliazione di un ordine di acquisto con quanto ricevuto e fatturato — implicito in Carbon, tramite le quantità di riga e il saldo GR/IR."+msgid "Receivables aging"+msgstr "Invecchiamento crediti"+msgid "Receive"msgstr "Ricevi"@@ -8921,6 +9167,13 @@ msgstr "Ricevi {0} in Inventario"msgid "Receive against a PO and update inventory"msgstr "Ricevere contro un PO e aggiornare l'inventario"+msgid "Receive Payment"+msgstr "Ricevi Pagamento"++#. placeholder {0}: selectedInvoices.length+msgid "Receive Payment · {0} invoices"+msgstr "Ricevi Pagamento · {0} fatture"+msgid "Receive to Inventory"msgstr "Ricevi in Inventario"@@ -8944,6 +9197,9 @@ msgstr "Ubicazione di ricezione"msgid "Recent"msgstr "Recenti"+msgid "Recent payments"+msgstr "Pagamenti recenti"+msgid "Recently Created"msgstr "Creato di recente"@@ -8953,6 +9209,12 @@ msgstr "Periodo di Recupero"msgid "Record"msgstr "Registra"+msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."+msgstr "Registra una nota di credito o di debito contro un cliente o fornitore. Le applicazioni a fatture specifiche vengono aggiunte dopo la creazione della nota."++msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."+msgstr "Registra il denaro ricevuto da un cliente (Ricevuta) o pagato a un fornitore (Versamento). Le applicazioni a fatture specifiche vengono aggiunte dopo la creazione del pagamento."+msgid "Record deleted"msgstr "Record eliminato"@@ -9037,6 +9299,9 @@ msgstr "Rilascia Commessa"msgid "Released"msgstr "Rilasciato"+msgid "Remaining"+msgstr "Rimanente"+msgid "Remaining after split stays on the original row."msgstr "La quantità rimanente dopo la divisione rimane sulla riga originale."@@ -9583,6 +9848,9 @@ msgstr "Salva e chiudi"msgid "Save and Overwrite"msgstr "Salva e Sovrascrivi"+msgid "Save applications"+msgstr "Salva applicazioni"+msgid "Save contacts"msgstr "Salva contatti"@@ -9824,6 +10092,15 @@ msgstr "Seleziona Calibro"msgid "Select groups or individuals"msgstr "Seleziona gruppi o individui"+msgid "Select invoice"+msgstr "Seleziona fattura"++msgid "Select invoices from a single counterparty"+msgstr "Seleziona fatture da un singolo controparte"++msgid "Select invoices in a single currency"+msgstr "Seleziona fatture in una singola valuta"+msgid "Select Item Type"msgstr "Seleziona Tipo di Articolo"@@ -9860,6 +10137,9 @@ msgstr "Seleziona superfici"msgid "Select the groups that should complete this training"msgstr "Seleziona i gruppi che devono completare questo training"+msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."+msgstr "Seleziona le fatture che questo pagamento regola. Lo sconto e la cancellazione sono nella valuta della fattura."+msgid "Select value"msgstr "Seleziona valore"@@ -10575,6 +10855,9 @@ msgstr "Varianza di Terziarizzazione"msgid "Subcontracting Variance (default)"msgstr "Varianza di Terziarizzazione (predefinita)"+msgid "Subledger"+msgstr "Sottolibro"+msgid "Submit anonymously"msgstr "Invia in modo anonimo"@@ -11597,6 +11880,9 @@ msgstr "Non ci sono preventivi fornitori attivi da confrontare per questa RFQ."msgid "There are outside operations associated with this job that have no suppliers. Please assign a supplier to each outside operation before releasing it."msgstr "Ci sono operazioni esterne associate a questo lavoro che non hanno fornitori. Assegna un fornitore a ogni operazione esterna prima di rilasciarlo."+msgid "There's nothing outstanding to apply these credits to."+msgstr "Non c'è nulla in sospeso a cui applicare questi crediti."+msgid "These custom fields will only be available for entities with the same tags"msgstr "Questi campi personalizzati saranno disponibili solo per le entità con gli stessi tag"@@ -11612,6 +11898,9 @@ msgstr "Questi lavori hanno operazioni assegnate a questo centro di lavoro:"msgid "This completes the Discovery step."msgstr "Questo completa il passaggio Discovery."+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."+msgstr "Questa controparte non ha nulla in sospeso — il pagamento verrà registrato come credito in conto."+msgid "This information will be used on document headers"msgstr "Queste informazioni verranno utilizzate nelle intestazioni dei documenti"@@ -11720,6 +12009,9 @@ msgstr "Giovedì"msgid "Tie shipments through to an invoice with no re-keying"msgstr "Collegare le spedizioni a una fattura senza reinserimento dati"+msgid "Tie-Out"+msgstr "Riconciliazione"+msgid "Tightened"msgstr "Stretto"@@ -11756,6 +12048,9 @@ msgstr "Da spedire e ricevere"msgid "To Storage Unit"msgstr "A Storage Unit"+msgid "To supplier"+msgstr "Al fornitore"+msgid "Today"msgstr "Oggi"@@ -11825,6 +12120,9 @@ msgstr "Classificazione di primo livello (attivo/passivo/patrimonio netto/ricavimsgid "Total"msgstr "Totale"+msgid "Total Amount"+msgstr "Importo Totale"+msgid "Total capitalized cost of the asset (purchase price plus freight, install, and other costs that become part of book value)."msgstr "Costo totale capitalizzato dell'asset (prezzo di acquisto più trasporto, installazione e altri costi che diventano parte del valore netto contabile)."@@ -11852,6 +12150,9 @@ msgstr "Quantità totale richiesta su tutti i lavori attivi e gli ordini di vendmsgid "Total:"msgstr "Totale:"+msgid "Totals"+msgstr "Totali"+msgid "Traceability"msgstr "Tracciabilità"@@ -12008,6 +12309,12 @@ msgstr "Tipi"msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."msgstr "Le entità non campionate rimarranno In Sospeso in modo che tu possa continuare a ispezionare e disporre in seguito. I risultati campionati vengono conservati."+msgid "Unapplied"+msgstr "Non applicato"++msgid "Unapplied:"+msgstr "Non applicato:"+msgid "Unapproved Supplier"msgstr "Fornitore non approvato"@@ -12351,6 +12658,9 @@ msgstr "Numero di registrazione dell'imposta sul valore aggiunto; richiesto sullmsgid "Values"msgstr "Valori"+msgid "Variance"+msgstr "Varianza"+msgid "Variance between actual and standard BOM component consumption"msgstr "Varianza tra il consumo reale e standard dei componenti della distinta base"@@ -12372,6 +12682,9 @@ msgstr "Varianza nei costi di lavorazione esterna"msgid "VAT Number"msgstr "Numero IVA"+msgid "Vendor Write-Off Income"+msgstr "Reddito da Cancellazione Fornitore"+msgid "Verification Error"msgstr "Errore di verifica"@@ -12453,6 +12766,9 @@ msgstr "Visualizza Elenchi"msgid "View maintenance dispatch"msgstr "Visualizza manutenzione dispatch"+msgid "View Memo"+msgstr "Visualizza Memo"+msgid "View missing values"msgstr "Visualizza valori mancanti"@@ -12474,6 +12790,9 @@ msgstr "Visualizza Preventivi Aperti"msgid "View Open RFQs"msgstr "Visualizza RFQ Aperti"+msgid "View Payment"+msgstr "Visualizza Pagamento"+msgid "View permissions"msgstr "Permessi di visualizzazione"@@ -13042,9 +13361,19 @@ msgstr "Macchine con Prestazioni Peggiori"msgid "Write-Down Account"msgstr "Conto di Svalutazione"+msgid "Write-off"+msgstr "Cancellazione"++msgid "Write-Off"+msgstr "Cancellazione"+msgid "Write-Off Account"msgstr "Conto di Cancellazione"+#. placeholder {0}: r.invoiceId+msgid "Write-off for {0}"+msgstr "Cancellazione per {0}"+msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."msgstr "Ridurre il valore di un bene nel corso della sua vita utile — un batch mensile che crei, rivedi come bozza, quindi contabilizzi."diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 4c03051ddd..37fef13e7f 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -31,6 +31,10 @@ msgstr "「それを買ったからといって誰も解雇されなかった。msgid "(excluded for this customer)"msgstr "(このお客様では除外されています)"+#. placeholder {0}: ar.count+msgid "{0} customers with a balance"+msgstr "{0}件の残高のある顧客"+#. placeholder {0}: rule.escalationDaysmsgid "{0} days"msgstr "{0}日"@@ -48,6 +52,10 @@ msgstr "{0}件の注文"msgid "{0} Processes"msgstr "{0}個のプロセス"+#. placeholder {0}: ap.count+msgid "{0} suppliers with a balance"+msgstr "{0}件の残高のある仕入先"+#. placeholder {0}: lotEntities.length - inspectedmsgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "{0}個の未サンプリングエンティティが利用可能にリリースされます。サンプリング済みの合格品は利用可能なままで、サンプリング済みの不合格品は却下されたままです。"@@ -60,6 +68,12 @@ msgstr "{0}が正常にアップロードされました"msgid "{0} values missing"msgstr "{0}個の値が見つかりません"+msgid "{apOverduePct}% of payables"+msgstr "{apOverduePct}%の買掛金"++msgid "{arOverduePct}% of receivables"+msgstr "{arOverduePct}%の売掛金"+msgid "{chainLabel}. Consider pointing this part directly at the final successor."msgstr "{chainLabel}。このパーツを最終的な後継品に直接指定することを検討してください。"@@ -743,6 +757,10 @@ msgstr "この行の資産/経費を増加させるか、負債/資本/収益をmsgid "Amount that increases liabilities/equity/revenue or decreases assets/expenses on this line."msgstr "この行の負債/資本/収益を増加させるか、資産/経費を減少させる金額。"+#. placeholder {0}: r.memoId+msgid "Amount to apply for {0}"+msgstr "{0}に適用する金額"+msgid "Amount Type"msgstr "金額タイプ"@@ -806,6 +824,12 @@ msgstr "上記の範囲に明示的にリストされていないもの"msgid "AP Clerk"msgstr "AP クラーク"+msgid "AP Outstanding"+msgstr "AP未払金"++msgid "AP Overdue"+msgstr "AP 期限超過"+msgid "API and Webhooks"msgstr "APIとWebhooks"@@ -824,6 +848,19 @@ msgstr "APIキー"msgid "API keys for programmatic access to your Carbon data."msgstr "Carbonデータへのプログラマティックアクセス用のAPIキー。"+msgid "Applied"+msgstr "適用"++#. placeholder {0}: r.invoiceId+msgid "Applied amount for {0}"+msgstr "{0}の適用額"++msgid "Applied Date"+msgstr "適用日"++msgid "Applied To"+msgstr "適用先"+msgid "Applies to"msgstr "適用対象"@@ -833,6 +870,12 @@ msgstr "すべてに適用"msgid "Applies to all work centers"msgstr "すべてのワークセンターに適用"+msgid "Apply available credits"+msgstr "利用可能なクレジットを適用"++msgid "Apply credits"+msgstr "クレジットを適用"+msgid "Apply payments and track aging"msgstr "支払いを適用し、経過期間を追跡する"@@ -845,6 +888,12 @@ msgstr "上にルールを適用"msgid "Apply To"msgstr "適用対象"+msgid "Apply to invoice"+msgstr "請求書に適用"++msgid "Apply to invoices"+msgstr "請求書に適用"+msgid "Approaching {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB cap."msgstr "{PO_EMAIL_ATTACHMENT_LIMIT_MB} MBの上限に近づいています。"@@ -875,6 +924,12 @@ msgstr "AQL (Z1.4 / ISO 2859-1)"msgid "AR Clerk"msgstr "AR事務員"+msgid "AR Outstanding"+msgstr "売掛金未払い"++msgid "AR Overdue"+msgstr "売掛金滞納"+msgid "Archive"msgstr "アーカイブ"@@ -955,9 +1010,9 @@ msgstr "{0}をこの操作から削除してもよろしいですか?これはmsgid "Are you sure you want to delete {0}?"msgstr "{0}を削除してもよろしいですか?"+#. placeholder {0}: initialValues.memoId+#. placeholder {0}: initialValues.paymentId#. placeholder {0}: pickingList.pickingListId-#. placeholder {0}: routeData?.consumableSummary?.readableIdWithRevision-#. placeholder {0}: routeData?.customer?.name!msgid "Are you sure you want to delete {0}? This cannot be undone."msgstr "本当に{0}を削除してもよろしいですか?この操作は取り消せません。"@@ -1243,6 +1298,9 @@ msgstr "本当ですか?"msgid "As needed"msgstr "必要に応じて"+msgid "As of:"+msgstr "以下の日付時点:"+msgid "As the company owner, you can transfer ownership to another employee. This will give them full access to billing and administrative settings."msgstr "会社のオーナーとして、別の従業員に所有権を譲渡できます。これにより、彼らは請求と管理設定に完全にアクセスできるようになります。"@@ -1371,6 +1429,9 @@ msgstr "監査ログ"msgid "Authentication Error"msgstr "認証エラー"+msgid "Auto apply"+msgstr "自動適用"+msgid "Auto Release"msgstr "自動リリース"@@ -1440,9 +1501,15 @@ msgstr "バックフラッシュ"msgid "Backups"msgstr "バックアップ"+msgid "Balance"+msgstr "残高"+msgid "Balance Sheet"msgstr "貸借対照表"+msgid "Balanced"+msgstr "バランスが取れています"+msgid "Balloon"msgstr "バルーン"@@ -1464,6 +1531,9 @@ msgstr "銀行—外国為替(デフォルト)"msgid "Bank — Local Currency (default)"msgstr "銀行—地元通貨(デフォルト)"+msgid "Bank / Cash Account"+msgstr "銀行 / 現金口座"+msgid "Bank account denominated in a foreign currency"msgstr "外国為替で示された銀行口座。"@@ -1643,6 +1713,12 @@ msgstr "{byUser}による"msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."msgstr "招待を受け入れることで、<0>利用規約</0>および<1>プライバシーポリシー</1>に同意するものとします。"+msgid "By Document Date"+msgstr "ドキュメント日付別"++msgid "By Due Date"+msgstr "支払期日別"+msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"msgstr "サインインすることで、<0>利用規約</0>および<1>プライバシーポリシー</1>に同意するものとします。"@@ -1931,6 +2007,9 @@ msgstr "検索をクリア"msgid "Clear search query"msgstr "検索クエリをクリア"+msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."+msgstr "このインボイスをパーティの転記済みクレジットおよび現金でクリアします。クレジットは直接適用されます — 転記は不要です。"+msgid "Clearing account between goods receipt and supplier invoice; balances when both have posted."msgstr "商品受領と仕入先請求書間の相殺勘定; 両方が転記された場合に残高が取られます。"@@ -1977,6 +2056,9 @@ msgstr "クラウド、またはセルフホストされた環境。"msgid "Code"msgstr "コード"+msgid "Collapse"+msgstr "折りたたむ"+msgid "Collapse all"msgstr "すべて折りたたむ"@@ -2552,6 +2634,12 @@ msgstr "ドキュメントを読み込めませんでした"msgid "Count"msgstr "数"+msgid "Counterparties"+msgstr "取引先"++msgid "Counterparty"+msgstr "相手先"+msgid "Country"msgstr "国"@@ -2582,6 +2670,9 @@ msgstr "新しい見積ID で見積を作成"msgid "Create Account"msgstr "アカウントを作成"+msgid "Create adjusting entry"+msgstr "調整仕訳を作成"+msgid "Create an account"msgstr "アカウントを作成"@@ -2755,12 +2846,21 @@ msgstr "パーツを作成中..."msgid "Credit"msgstr "クレジット"+msgid "Credit / Debit Memos"+msgstr "貸方/借方メモ"+msgid "Credit Account"msgstr "クレジット勘定"msgid "Credit account when labor/machine time is absorbed into WIP"msgstr "労力/機械時間がWIPに吸収される場合のクレジット勘定"+msgid "Credits & Debits"+msgstr "クレジット&デビット"++msgid "Credits applied"+msgstr "適用されたクレジット"+msgid "Critical"msgstr "重大"@@ -2935,6 +3035,9 @@ msgstr "顧客タイプ"msgid "Customer Types"msgstr "顧客タイプ"+msgid "Customer Write-Off (Bad Debt)"+msgstr "顧客償却(貸倒金)"+msgid "customers"msgstr "顧客"@@ -3314,12 +3417,18 @@ msgstr "材料形状を削除"msgid "Delete Material Type"msgstr "材料タイプを削除"+msgid "Delete Memo"+msgstr "メモを削除"+msgid "Delete Part"msgstr "パーツを削除"msgid "Delete Partner"msgstr "パートナーを削除"+msgid "Delete Payment"+msgstr "支払いを削除"+msgid "Delete Payment Term"msgstr "支払い条件を削除"@@ -3566,6 +3675,12 @@ msgstr "寸法"msgid "Direct"msgstr "直接"+msgid "Direction"+msgstr "方向"++msgid "Directions"+msgstr "方向"+msgid "Disabled"msgstr "無効"@@ -3584,6 +3699,10 @@ msgstr "割引日数"msgid "Discount Days after {selectedCalculationMethod}"msgstr "{selectedCalculationMethod}後の割引日数"+#. placeholder {0}: r.invoiceId+msgid "Discount for {0}"+msgstr "{0}の割引"+msgid "Discount Percent"msgstr "割引率"@@ -3717,6 +3836,9 @@ msgstr "図と機能をリサイズするにはドラッグしてください"msgid "Drag to zoom"msgstr "ズームするにはドラッグしてください"+msgid "Drawing"+msgstr "引き出し中"+msgid "Drawing Number"msgstr "図面番号"@@ -3952,6 +4074,9 @@ msgstr "材料物質を編集"msgid "Edit Material Type"msgstr "材料タイプを編集"+msgid "Edit Memo"+msgstr "メモを編集"+msgid "Edit Non Conformance Type"msgstr "不適合タイプを編集"@@ -3961,6 +4086,9 @@ msgstr "パーツを編集"msgid "Edit Partner"msgstr "パートナーを編集"+msgid "Edit Payment"+msgstr "支払いを編集"+msgid "Edit Payment Term"msgstr "支払い条件を編集"@@ -4442,12 +4570,18 @@ msgstr "予想受取日"msgid "Expected Receipt Date"msgstr "予想受取日"+msgid "Expense account for customer balances written off as uncollectable on AR settlement"+msgstr "AR決済時に回収不可能として償却された顧客残高の費用勘定"+msgid "Expense account for deferred tax adjustments on depreciation"msgstr "減価償却に関する繰延税金調整の費用勘定"msgid "Expense account for equipment and facility maintenance"msgstr "機器と施設保守の費用勘定"+msgid "Expense account for FX losses when a payment settles a foreign-currency invoice at a less favorable rate"+msgstr "支払いが外貨建て請求書をより不利なレートで決済する場合のFX損失に対する費用勘定"+msgid "Expense account for non-inventory purchases (services, supplies)"msgstr "在庫以外の購入 (サービス、供給品) の費用勘定"@@ -5028,9 +5162,15 @@ msgstr "金曜日"msgid "From {0}"msgstr "{0}から"+msgid "From customer"+msgstr "顧客から"+msgid "From Location"msgstr "出発地"+msgid "from on-account credit"+msgstr "オンアカウントクレジットから"+msgid "From Storage Unit"msgstr "保管場所から"@@ -5040,6 +5180,9 @@ msgstr "履行場所"msgid "Fully trained for"msgstr "完全に訓練済み"+msgid "FX G/L"+msgstr "FX G/L"+msgid "Gains and Losses"msgstr "利益と損失(デフォルト)"@@ -5127,6 +5270,9 @@ msgstr "Carbonの基本操作"msgid "Getting set up"msgstr "セットアップ中"+msgid "GL"+msgstr "GL"+msgid "GL Account"msgstr "GLアカウント"@@ -5241,6 +5387,12 @@ msgstr "非インベントリ購入(用品、サービス)のためのGL支msgid "GL liability account credited for sales tax collected from customers."msgstr "顧客から徴収された売上税についてクレジットされるGL負債勘定。"+msgid "GL tie-out"+msgstr "GL照合"++msgid "GL Tie-Out"+msgstr "GL照合"+msgid "Go live right the first time — with our team alongside you"msgstr "初回から正しく本番運用を開始 — 当社チームがサポートします"@@ -5773,6 +5925,9 @@ msgstr "各ツールがどこで優れているかについての内部参考資msgid "inv"msgstr "在庫"+msgid "Inv Rate"+msgstr "請求書レート"+msgid "Invalid Invite"msgstr "無効な招待"@@ -5884,6 +6039,12 @@ msgstr "請求済みステータス"msgid "Invoices"msgstr "請求書"+msgid "Invoices this memo has been applied to. Click a row to open the document."+msgstr "このメモが適用された請求書です。行をクリックしてドキュメントを開きます。"++msgid "Invoicing"+msgstr "請求"+msgid "is"msgstr "です"@@ -6451,6 +6612,13 @@ msgstr "製造品は直接請求できません。方法をピックに変更しmsgid "Make Method Version"msgstr "製造方法バージョン"+msgid "Make Payment"+msgstr "支払いを実行"++#. placeholder {0}: selectedInvoices.length+msgid "Make Payment · {0} invoices"+msgstr "支払いを実行 · {0} 件の請求書"+#. placeholder {0}: selectedRevision.revisionmsgid "Make revision {0} default?"msgstr "リビジョン {0} をデフォルトにしますか?"@@ -6693,6 +6861,15 @@ msgstr "ミーティング頻度"msgid "Members"msgstr "メンバー"+msgid "Memo"+msgstr "メモ"++msgid "Memo Date"+msgstr "メモ日付"++msgid "Memo ID"+msgstr "メモID"+msgid "MES"msgstr "MES"@@ -6953,6 +7130,9 @@ msgstr "新しい消耗品"msgid "New Contractor"msgstr "新しい契約者"+msgid "New Credit / Debit Memo"+msgstr "新しい貸方/借方メモ"+msgid "New Custom Field"msgstr "新しいカスタムフィールド"@@ -7061,6 +7241,9 @@ msgstr "新しい部品"msgid "New Password"msgstr "新しいパスワード"+msgid "New Payment"+msgstr "新しい支払い"+msgid "New Payment Term"msgstr "新しい支払い条件"@@ -7252,6 +7435,9 @@ msgstr "アクティブな見積がありません"msgid "No addresses found"msgstr "住所が見つかりません"+msgid "No applications. Payment will be on-account."+msgstr "申請がありません。支払いはオンアカウントになります。"+#. placeholder {0}: auditConfig.retentionDaysmsgid "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."msgstr "まだアーカイブされたログはありません。{0}日以上前のログは自動的にアーカイブされ、ここからダウンロードできます。"@@ -7370,6 +7556,9 @@ msgstr "新しい通知はありません"msgid "No notes"msgstr "ノートなし"+msgid "No open invoices"+msgstr "未処理の請求書がありません"+msgid "No operations require picking at this location"msgstr "この場所でのピッキングが必要な操作はありません"@@ -7397,6 +7586,12 @@ msgstr "親ソースはまだ記録されていません。計画ページの「msgid "No part ID"msgstr "パーツIDなし"+msgid "No payables"+msgstr "支払い義務なし"++msgid "No payments yet."+msgstr "まだ支払いはありません。"+msgid "No planning data"msgstr "計画データなし"@@ -7421,6 +7616,9 @@ msgstr "見積なし理由"msgid "No Quote Reasons"msgstr "見積なし理由"+msgid "No receivables"+msgstr "売掛金がありません"+msgid "No remaining entities to inspect."msgstr "検査する残りのエンティティはありません。"@@ -7598,6 +7796,9 @@ msgstr "販売注文中"msgid "On Storage Unit"msgstr "保管ユニット上"+msgid "On-account credit available"+msgstr "掛け売掛金利用可能"+msgid "On-hand counts"msgstr "手持在庫数"@@ -7818,6 +8019,12 @@ msgstr "注文が送信されました"msgid "Origin"msgstr "オリジン"+msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"+msgstr "支払いが外貨建て請求書をより有利なレートで決済する場合のFX利益に対するその他の収益勘定"++msgid "Other Income account for vendor balances cleared without full payment on AP settlement"+msgstr "仕入先残高が全額支払いなしでAP決済時にクリアされた場合のその他の収益勘定"+msgid "Other Type"msgstr "その他のタイプ"@@ -7839,6 +8046,9 @@ msgstr "出力は原材料より長く持ちません。入力に有効期限がmsgid "Outside operation"msgstr "間接費差異"+msgid "Over-applied by"+msgstr "超過適用額"+msgid "Overdue"msgstr "期限超過"@@ -7975,6 +8185,9 @@ msgstr "部品・品目"msgid "Parts, materials, and how you classify them."msgstr "部品、材料、およびそれらの分類方法。"+msgid "Party Type"+msgstr "取引先タイプ"+msgid "Pass"msgstr "合格"@@ -7984,17 +8197,29 @@ msgstr "完了 · 再度開く"msgid "Path"msgstr "パス"+msgid "Pay Rate"+msgstr "支払レート"+msgid "Payables"msgstr "買掛金(デフォルト)"msgid "Payables (default)"msgstr "支払条件"+msgid "Payables aging"+msgstr "支払い債務の経過"+msgid "Payment"msgstr "支払い"-msgid "Payment Method"-msgstr "支払い方法"+msgid "Payment Applications"+msgstr "支払い適用"++msgid "Payment Date"+msgstr "支払日"++msgid "Payment ID"+msgstr "支払いID"msgid "payment term"msgstr "支払条件"@@ -8011,6 +8236,12 @@ msgstr "支払条件"msgid "Payment terms like Net 30 or due on receipt"msgstr "Net 30などの支払い条件または領収書時の支払い"+msgid "Payments"+msgstr "支払い"++msgid "Payments and credits applied to this invoice. Click a row to open the source document."+msgstr "このインボイスに適用された支払いとクレジット。行をクリックしてソースドキュメントを開きます。"+msgid "PDF"msgstr "PDF"@@ -8672,6 +8903,9 @@ msgstr "購買と自動計画"msgid "Purchasing Contact"msgstr "購買担当者"+msgid "Purchasing Invoices"+msgstr "購買請求書"+msgid "Purchasing Unit of Measure"msgstr "購買単位"@@ -8866,9 +9100,18 @@ msgstr "リアルタイム在庫と工場フロアの可視性"msgid "Real-time questions during hypercare"msgstr "ハイパーケア中のリアルタイム質問"+msgid "Realized Exchange Gain"+msgstr "実現為替利益"++msgid "Realized Exchange Loss"+msgstr "実現為替損失"+msgid "Reason"msgstr "理由"+msgid "Reason Account"+msgstr "理由アカウント"+msgid "Reason for declining (Optional)"msgstr "辞退する理由(オプション)"@@ -8911,6 +9154,9 @@ msgstr "売掛金(デフォルト)"msgid "Receivables (default)"msgstr "購買注文を受け取った内容と請求内容で調整する — Carbon に暗黙的に含まれており、行数量と GR/IR 残高を通じて。"+msgid "Receivables aging"+msgstr "売掛金の経過"+msgid "Receive"msgstr "受け取る"@@ -8921,6 +9167,13 @@ msgstr "{0}を在庫に受け取る"msgid "Receive against a PO and update inventory"msgstr "POに対して受け取り、在庫を更新"+msgid "Receive Payment"+msgstr "支払いを受け取る"++#. placeholder {0}: selectedInvoices.length+msgid "Receive Payment · {0} invoices"+msgstr "支払いを受け取る · {0} 件の請求書"+msgid "Receive to Inventory"msgstr "在庫に受け取る"@@ -8944,6 +9197,9 @@ msgstr "受取場所"msgid "Recent"msgstr "最近"+msgid "Recent payments"+msgstr "最近の支払い"+msgid "Recently Created"msgstr "最近作成"@@ -8953,6 +9209,12 @@ msgstr "回収期間"msgid "Record"msgstr "記録"+msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."+msgstr "顧客またはサプライヤーに対するクレジットまたはデビットメモを記録します。特定の請求書への適用は、メモが作成された後に追加されます。"++msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."+msgstr "顧客から受け取った現金(領収書)または仕入先に支払った現金(支払)を記録します。特定の請求書への適用は、支払が作成された後に追加されます。"+msgid "Record deleted"msgstr "レコード削除済み"@@ -9037,6 +9299,9 @@ msgstr "ジョブをリリース"msgid "Released"msgstr "リリース済み"+msgid "Remaining"+msgstr "残高"+msgid "Remaining after split stays on the original row."msgstr "分割後の残りは元の行に留まります。"@@ -9583,6 +9848,9 @@ msgstr "保存して閉じる"msgid "Save and Overwrite"msgstr "保存して上書き"+msgid "Save applications"+msgstr "アプリケーションを保存"+msgid "Save contacts"msgstr "連絡先を保存"@@ -9824,6 +10092,15 @@ msgstr "ゲージを選択"msgid "Select groups or individuals"msgstr "グループまたは個人を選択"+msgid "Select invoice"+msgstr "請求書を選択"++msgid "Select invoices from a single counterparty"+msgstr "単一の取引先から請求書を選択してください"++msgid "Select invoices in a single currency"+msgstr "単一通貨の請求書を選択してください"+msgid "Select Item Type"msgstr "アイテムタイプを選択"@@ -9860,6 +10137,9 @@ msgstr "サーフェスを選択"msgid "Select the groups that should complete this training"msgstr "このトレーニングを完了する必要があるグループを選択してください"+msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."+msgstr "この支払いで決済する請求書を選択してください。割引と償却は請求書通貨です。"+msgid "Select value"msgstr "値を選択"@@ -10575,6 +10855,9 @@ msgstr "外注差異"msgid "Subcontracting Variance (default)"msgstr "外注差異(デフォルト)"+msgid "Subledger"+msgstr "補助元帳"+msgid "Submit anonymously"msgstr "匿名で送信"@@ -11597,6 +11880,9 @@ msgstr "このRFQに比較するアクティブなサプライヤー見積もりmsgid "There are outside operations associated with this job that have no suppliers. Please assign a supplier to each outside operation before releasing it."msgstr "このジョブに関連付けられた外部オペレーションにはサプライヤーがありません。リリースする前に、各外部オペレーションにサプライヤーを割り当ててください。"+msgid "There's nothing outstanding to apply these credits to."+msgstr "これらのクレジットを適用する未処理項目がありません。"+msgid "These custom fields will only be available for entities with the same tags"msgstr "これらのカスタムフィールドは、同じタグを持つエンティティでのみ利用可能です"@@ -11612,6 +11898,9 @@ msgstr "これらのジョブにはこのワークセンターに割り当てらmsgid "This completes the Discovery step."msgstr "これはDiscoveryステップを完了します。"+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."+msgstr "この取引先には未払い金がありません。支払いは掛け金として記録されます。"+msgid "This information will be used on document headers"msgstr "この情報はドキュメントヘッダーで使用されます"@@ -11720,6 +12009,9 @@ msgstr "木曜日"msgid "Tie shipments through to an invoice with no re-keying"msgstr "出荷を請求書に結びつけ、再入力なしで処理する"+msgid "Tie-Out"+msgstr "照合"+msgid "Tightened"msgstr "厳しい"@@ -11756,6 +12048,9 @@ msgstr "配送と受取"msgid "To Storage Unit"msgstr "保管単位へ"+msgid "To supplier"+msgstr "仕入先へ"+msgid "Today"msgstr "今日"@@ -11825,6 +12120,9 @@ msgstr "トップレベルの分類(資産/負債/資本/収益/費用)。msgid "Total"msgstr "合計"+msgid "Total Amount"+msgstr "合計金額"+msgid "Total capitalized cost of the asset (purchase price plus freight, install, and other costs that become part of book value)."msgstr "資産の総資本化コスト(購入価格、運送、設置、および帳簿価額の一部となるその他のコスト)。"@@ -11852,6 +12150,9 @@ msgstr "このロケーションのすべての進行中ジョブおよび受注msgid "Total:"msgstr "合計:"+msgid "Totals"+msgstr "合計"+msgid "Traceability"msgstr "トレーサビリティ"@@ -12008,6 +12309,12 @@ msgstr "タイプ"msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."msgstr "未サンプリングされたエンティティは保留中のままになるため、検査を続けて後で処分できます。サンプリングされた結果は保持されます。"+msgid "Unapplied"+msgstr "未適用"++msgid "Unapplied:"+msgstr "未適用:"+msgid "Unapproved Supplier"msgstr "未承認サプライヤー"@@ -12351,6 +12658,9 @@ msgstr "付加価値税登録番号;EUの請求書でのリバースチャージmsgid "Values"msgstr "値"+msgid "Variance"+msgstr "差異"+msgid "Variance between actual and standard BOM component consumption"msgstr "実際のBOM部品消費と標準消費の差異"@@ -12372,6 +12682,9 @@ msgstr "外部処理コストの差異"msgid "VAT Number"msgstr "VAT番号"+msgid "Vendor Write-Off Income"+msgstr "仕入先償却益"+msgid "Verification Error"msgstr "認証エラー"@@ -12453,6 +12766,9 @@ msgstr "リストを表示"msgid "View maintenance dispatch"msgstr "メンテナンスディスパッチを表示"+msgid "View Memo"+msgstr "メモを表示"+msgid "View missing values"msgstr "欠落値を表示"@@ -12474,6 +12790,9 @@ msgstr "オープンな見積もりを表示"msgid "View Open RFQs"msgstr "オープンなRFQを表示"+msgid "View Payment"+msgstr "支払いを表示"+msgid "View permissions"msgstr "閲覧権限"@@ -13042,9 +13361,19 @@ msgstr "最も性能が低い機械"msgid "Write-Down Account"msgstr "評価減勘定"+msgid "Write-off"+msgstr "償却"++msgid "Write-Off"+msgstr "償却"+msgid "Write-Off Account"msgstr "償却勘定"+#. placeholder {0}: r.invoiceId+msgid "Write-off for {0}"+msgstr "{0}の償却"+msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."msgstr "資産の価値をその耐用年数にわたって削減する — 作成、ドラフトとしてレビュー、その後ポストするメンバッチ。"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex e6faa44ffd..7d6aa6f8f0 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -31,6 +31,10 @@ msgstr "\"Nikt nie stracił pracy za jego kupienie.\" Czynnik komfortu dla dotycmsgid "(excluded for this customer)"msgstr "(wykluczone dla tego klienta)"+#. placeholder {0}: ar.count+msgid "{0} customers with a balance"+msgstr "{0} klientów z saldem"+#. placeholder {0}: rule.escalationDaysmsgid "{0} days"msgstr "{0} dni"@@ -48,6 +52,10 @@ msgstr "{0} zamówień"msgid "{0} Processes"msgstr "{0} Procesy"+#. placeholder {0}: ap.count+msgid "{0} suppliers with a balance"+msgstr "{0} dostawców z saldem"+#. placeholder {0}: lotEntities.length - inspectedmsgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "{0} nieprzetestowane jednostki zostaną zwolnione do Dostępne. Przebadane pozytywne pozostają Dostępne, a przebadane negatywne pozostają Odrzucone."@@ -60,6 +68,12 @@ msgstr "{0} przesłano pomyślnie"msgid "{0} values missing"msgstr "{0} brakujących wartości"+msgid "{apOverduePct}% of payables"+msgstr "{apOverduePct}% zobowiązań"++msgid "{arOverduePct}% of receivables"+msgstr "{arOverduePct}% należności"+msgid "{chainLabel}. Consider pointing this part directly at the final successor."msgstr "{chainLabel}. Rozważ wskazanie tej części bezpośrednio na ostatecznego następcę."@@ -743,6 +757,10 @@ msgstr "Kwota, która zwiększa aktywa/wydatki lub zmniejsza pasywa/kapitał/przmsgid "Amount that increases liabilities/equity/revenue or decreases assets/expenses on this line."msgstr "Kwota, która zwiększa pasywa/kapitał/przychody lub zmniejsza aktywa/wydatki w tej linii."+#. placeholder {0}: r.memoId+msgid "Amount to apply for {0}"+msgstr "Kwota do zastosowania dla {0}"+msgid "Amount Type"msgstr "Typ kwoty"@@ -806,6 +824,12 @@ msgstr "Wszystko, co nie jest wyraźnie wymienione w zakresie powyżej"msgid "AP Clerk"msgstr "Pracownik ds. zobowiązań"+msgid "AP Outstanding"+msgstr "Zobowiązania do zapłaty"++msgid "AP Overdue"+msgstr "AP Zaległy"+msgid "API and Webhooks"msgstr "API i Webhooks"@@ -824,6 +848,19 @@ msgstr "Klucze API"msgid "API keys for programmatic access to your Carbon data."msgstr "Klucze API do programowego dostępu do danych Carbon."+msgid "Applied"+msgstr "Zastosowano"++#. placeholder {0}: r.invoiceId+msgid "Applied amount for {0}"+msgstr "Zastosowana kwota dla {0}"++msgid "Applied Date"+msgstr "Data zastosowania"++msgid "Applied To"+msgstr "Zastosowano do"+msgid "Applies to"msgstr "Dotyczy"@@ -833,6 +870,12 @@ msgstr "Dotyczy wszystkich"msgid "Applies to all work centers"msgstr "Dotyczy wszystkich centrów pracy"+msgid "Apply available credits"+msgstr "Zastosuj dostępne kredyty"++msgid "Apply credits"+msgstr "Zastosuj kredyty"+msgid "Apply payments and track aging"msgstr "Stosuj płatności i śledź wiekowanie"@@ -845,6 +888,12 @@ msgstr "Zastosuj reguły na górze"msgid "Apply To"msgstr "Zastosuj do"+msgid "Apply to invoice"+msgstr "Zastosuj do faktury"++msgid "Apply to invoices"+msgstr "Zastosuj do faktur"+msgid "Approaching {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB cap."msgstr "Zbliżanie się do limitu {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB."@@ -875,6 +924,12 @@ msgstr "AQL (Z1.4 / ISO 2859-1)"msgid "AR Clerk"msgstr "Pracownik ds. rozrachunków z odbiorcami"+msgid "AR Outstanding"+msgstr "Zaległości z tytułu należności"++msgid "AR Overdue"+msgstr "AR Zaległy"+msgid "Archive"msgstr "Archiwum"@@ -955,9 +1010,9 @@ msgstr "Czy na pewno chcesz usunąć {0} z tej operacji? Tej czynności nie możmsgid "Are you sure you want to delete {0}?"msgstr "Czy na pewno chcesz usunąć {0}?"+#. placeholder {0}: initialValues.memoId+#. placeholder {0}: initialValues.paymentId#. placeholder {0}: pickingList.pickingListId-#. placeholder {0}: routeData?.consumableSummary?.readableIdWithRevision-#. placeholder {0}: routeData?.customer?.name!msgid "Are you sure you want to delete {0}? This cannot be undone."msgstr "Czy na pewno chcesz usunąć {0}? Tej operacji nie można cofnąć."@@ -1243,6 +1298,9 @@ msgstr "Jesteś pewny?"msgid "As needed"msgstr "W razie potrzeby"+msgid "As of:"+msgstr "Na dzień:"+msgid "As the company owner, you can transfer ownership to another employee. This will give them full access to billing and administrative settings."msgstr "Jako właściciel firmy możesz przenieść własność na innego pracownika. Daje mu to pełny dostęp do rozliczeń i ustawień administracyjnych."@@ -1371,6 +1429,9 @@ msgstr "Dzienniki audytu"msgid "Authentication Error"msgstr "Błąd uwierzytelniania"+msgid "Auto apply"+msgstr "Automatyczne zastosowanie"+msgid "Auto Release"msgstr "Automatyczne zwolnienie"@@ -1440,9 +1501,15 @@ msgstr "Cofnięcie"msgid "Backups"msgstr "Kopie zapasowe"+msgid "Balance"+msgstr "Saldo"+msgid "Balance Sheet"msgstr "Bilans"+msgid "Balanced"+msgstr "Zrównoważone"+msgid "Balloon"msgstr "Balon"@@ -1464,6 +1531,9 @@ msgstr "Bank — Waluta obca (domyślnie)"msgid "Bank — Local Currency (default)"msgstr "Bank — Waluta lokalna (domyślnie)"+msgid "Bank / Cash Account"+msgstr "Konto bankowe / gotówkowe"+msgid "Bank account denominated in a foreign currency"msgstr "Rachunek bankowy denominowany w walucie obcej."@@ -1643,6 +1713,12 @@ msgstr "przez {byUser}"msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."msgstr "Akceptując zaproszenie, zgadzasz się na <0>Warunki Usługi</0> i <1>Politykę Prywatności</1>."+msgid "By Document Date"+msgstr "Według daty dokumentu"++msgid "By Due Date"+msgstr "Według daty wymagalności"+msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"msgstr "Logując się, wyrażasz zgodę na <0>Warunki korzystania z usługi</0> i <1>Politykę prywatności.</1>"@@ -1931,6 +2007,9 @@ msgstr "Wyczyść wyszukiwanie"msgid "Clear search query"msgstr "Wyczyść zapytanie wyszukiwania"+msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."+msgstr "Wyczyść tę fakturę za pomocą zaksięgowanych kredytów strony oraz gotówki. Kredyty są stosowane bezpośrednio — nie jest wymagane żadne zaksięgowanie."+msgid "Clearing account between goods receipt and supplier invoice; balances when both have posted."msgstr "Konto rozliczeniowe między przyjęciem towaru a fakturą dostawcy; wyrównuje się, gdy oba zostały zaksięgowane."@@ -1977,6 +2056,9 @@ msgstr "Chmura lub Twoje środowisko hostowane samodzielnie."msgid "Code"msgstr "Kod"+msgid "Collapse"+msgstr "Zwiń"+msgid "Collapse all"msgstr "Zwiń wszystko"@@ -2552,6 +2634,12 @@ msgstr "Nie udało się załadować dokumentów"msgid "Count"msgstr "Liczba"+msgid "Counterparties"+msgstr "Kontrahenci"++msgid "Counterparty"+msgstr "Kontrahent"+msgid "Country"msgstr "Kraj"@@ -2582,6 +2670,9 @@ msgstr "Utwórz ofertę z nowym identyfikatorem oferty"msgid "Create Account"msgstr "Utwórz konto"+msgid "Create adjusting entry"+msgstr "Utwórz wpis korygujący"+msgid "Create an account"msgstr "Utwórz konto"@@ -2755,12 +2846,21 @@ msgstr "Tworzenie części..."msgid "Credit"msgstr "Kredyt"+msgid "Credit / Debit Memos"+msgstr "Noty kredytowe / debetowe"+msgid "Credit Account"msgstr "Konto Kredytowe"msgid "Credit account when labor/machine time is absorbed into WIP"msgstr "Konto kredytowe, gdy czas pracy/maszyny jest absorbowany w WIP"+msgid "Credits & Debits"+msgstr "Kredyty i Debety"++msgid "Credits applied"+msgstr "Zastosowane kredyty"+msgid "Critical"msgstr "Krytyczne"@@ -2935,6 +3035,9 @@ msgstr "typy klientów"msgid "Customer Types"msgstr "Typy klientów"+msgid "Customer Write-Off (Bad Debt)"+msgstr "Odpis klienta (Nieściągalne należności)"+msgid "customers"msgstr "klienci"@@ -3314,12 +3417,18 @@ msgstr "Usuń kształt materiału"msgid "Delete Material Type"msgstr "Usuń typ materiału"+msgid "Delete Memo"+msgstr "Usuń Notatkę"+msgid "Delete Part"msgstr "Usuń część"msgid "Delete Partner"msgstr "Usuń partnera"+msgid "Delete Payment"+msgstr "Usuń płatność"+msgid "Delete Payment Term"msgstr "Usuń Warunki Płatności"@@ -3566,6 +3675,12 @@ msgstr "Wymiary"msgid "Direct"msgstr "Bezpośredni"+msgid "Direction"+msgstr "Kierunek"++msgid "Directions"+msgstr "Kierunki"+msgid "Disabled"msgstr "Wyłączone"@@ -3584,6 +3699,10 @@ msgstr "Dni Rabatu"msgid "Discount Days after {selectedCalculationMethod}"msgstr "Dni rabatu po {selectedCalculationMethod}"+#. placeholder {0}: r.invoiceId+msgid "Discount for {0}"+msgstr "Rabat dla {0}"+msgid "Discount Percent"msgstr "Procent rabatu"@@ -3717,6 +3836,9 @@ msgstr "Przeciągnij, aby zmienić rozmiar diagramu i funkcji"msgid "Drag to zoom"msgstr "Przeciągnij, aby powiększyć"+msgid "Drawing"+msgstr "Pobieranie"+msgid "Drawing Number"msgstr "Numer rysunku"@@ -3952,6 +4074,9 @@ msgstr "Edytuj Substancję Materiałową"msgid "Edit Material Type"msgstr "Edytuj Typ Materiału"+msgid "Edit Memo"+msgstr "Edytuj Notatkę"+msgid "Edit Non Conformance Type"msgstr "Edytuj typ niezgodności"@@ -3961,6 +4086,9 @@ msgstr "Edytuj Część"msgid "Edit Partner"msgstr "Edytuj Partnera"+msgid "Edit Payment"+msgstr "Edytuj Płatność"+msgid "Edit Payment Term"msgstr "Edytuj Warunki Płatności"@@ -4442,12 +4570,18 @@ msgstr "Oczekiwane Potwierdzenie Odbioru"msgid "Expected Receipt Date"msgstr "Oczekiwana data przyjęcia"+msgid "Expense account for customer balances written off as uncollectable on AR settlement"+msgstr "Konto wydatków dla sald klientów odpisanych jako nieściągalne w rozliczeniu AR"+msgid "Expense account for deferred tax adjustments on depreciation"msgstr "Konto wydatków na wyrównania podatku odroczonego od amortyzacji"msgid "Expense account for equipment and facility maintenance"msgstr "Konto wydatków na konserwację sprzętu i obiektu"+msgid "Expense account for FX losses when a payment settles a foreign-currency invoice at a less favorable rate"+msgstr "Konto wydatków dla strat walutowych, gdy płatność rozlicza fakturę w walucie obcej po mniej korzystnym kursie"+msgid "Expense account for non-inventory purchases (services, supplies)"msgstr "Konto wydatków na zakupy poza magazynem (usługi, materiały)"@@ -5028,9 +5162,15 @@ msgstr "Piątek"msgid "From {0}"msgstr "Od {0}"+msgid "From customer"+msgstr "Od klienta"+msgid "From Location"msgstr "Z lokalizacji"+msgid "from on-account credit"+msgstr "z kredytu na koncie"+msgid "From Storage Unit"msgstr "Z jednostki magazynowej"@@ -5040,6 +5180,9 @@ msgstr "Lokalizacja Realizacji"msgid "Fully trained for"msgstr "W pełni przeszkolony do"+msgid "FX G/L"+msgstr "FX Z/S"+msgid "Gains and Losses"msgstr "Zyski i Straty (domyślnie)"@@ -5127,6 +5270,9 @@ msgstr "Poruszanie się w Carbon"msgid "Getting set up"msgstr "Przygotowanie"+msgid "GL"+msgstr "GL"+msgid "GL Account"msgstr "Konto księgi głównej"@@ -5241,6 +5387,12 @@ msgstr "Konto GL wydatków dla zakupów spoza zapasów (materiały, usługi)."msgid "GL liability account credited for sales tax collected from customers."msgstr "Konto GL zobowiązań kredytowane dla podatku od sprzedaży pobranego od klientów."+msgid "GL tie-out"+msgstr "Uzgodnienie GL"++msgid "GL Tie-Out"+msgstr "Uzgodnienie GL"+msgid "Go live right the first time — with our team alongside you"msgstr "Wdrażaj bez błędów za pierwszym razem — z naszym zespołem u boku"@@ -5773,6 +5925,9 @@ msgstr "Wewnętrzne odniesienie do tego, gdzie każde narzędzie jest silniejszemsgid "inv"msgstr "inv"+msgid "Inv Rate"+msgstr "Kurs Fakt"+msgid "Invalid Invite"msgstr "Nieprawidłowe zaproszenie"@@ -5884,6 +6039,12 @@ msgstr "Statusy Zafakturowane"msgid "Invoices"msgstr "Faktury"+msgid "Invoices this memo has been applied to. Click a row to open the document."+msgstr "Faktury, do których zastosowano tę notatkę. Kliknij wiersz, aby otworzyć dokument."++msgid "Invoicing"+msgstr "Fakturowanie"+msgid "is"msgstr "jest"@@ -6451,6 +6612,13 @@ msgstr "Artykuły Make nie mogą być fakturowane bezpośrednio. Zmień metodęmsgid "Make Method Version"msgstr "Wersja metody produkcji"+msgid "Make Payment"+msgstr "Dokonaj płatności"++#. placeholder {0}: selectedInvoices.length+msgid "Make Payment · {0} invoices"+msgstr "Dokonaj płatności · {0} faktury"+#. placeholder {0}: selectedRevision.revisionmsgid "Make revision {0} default?"msgstr "Uczynić wersję {0} domyślną?"@@ -6693,6 +6861,15 @@ msgstr "Częstotliwość spotkań"msgid "Members"msgstr "Członkowie"+msgid "Memo"+msgstr "Notatka"++msgid "Memo Date"+msgstr "Data memorandum"++msgid "Memo ID"+msgstr "ID Notatki"+msgid "MES"msgstr "MES"@@ -6953,6 +7130,9 @@ msgstr "Nowy materiał zużywalny"msgid "New Contractor"msgstr "Nowy Wykonawca"+msgid "New Credit / Debit Memo"+msgstr "Nowy Dokument Kredytowy / Debetowy"+msgid "New Custom Field"msgstr "Nowe pole niestandardowe"@@ -7061,6 +7241,9 @@ msgstr "Nowa Część"msgid "New Password"msgstr "Nowe Hasło"+msgid "New Payment"+msgstr "Nowa Płatność"+msgid "New Payment Term"msgstr "Nowy Termin Płatności"@@ -7252,6 +7435,9 @@ msgstr "Brak aktywnych ofert"msgid "No addresses found"msgstr "Nie znaleziono adresów"+msgid "No applications. Payment will be on-account."+msgstr "Brak aplikacji. Płatność będzie na rachunek."+#. placeholder {0}: auditConfig.retentionDaysmsgid "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."msgstr "Brak zarchiwizowanych dzienników. Dzienniki starsze niż {0} dni będą automatycznie archiwizowane i dostępne do pobrania tutaj."@@ -7370,6 +7556,9 @@ msgstr "Brak nowych powiadomień"msgid "No notes"msgstr "Brak notek"+msgid "No open invoices"+msgstr "Brak otwartych faktur"+msgid "No operations require picking at this location"msgstr "Żadne operacje nie wymagają pobrania w tej lokalizacji"@@ -7397,6 +7586,12 @@ msgstr "Brak zarejestrowanych źródeł nadrzędnych. Kliknij Przelicz na stronimsgid "No part ID"msgstr "Brak identyfikatora części"+msgid "No payables"+msgstr "Brak zobowiązań"++msgid "No payments yet."+msgstr "Brak płatności."+msgid "No planning data"msgstr "Brak danych planowania"@@ -7421,6 +7616,9 @@ msgstr "Brak powodu oferty"msgid "No Quote Reasons"msgstr "Brak powodów oferty"+msgid "No receivables"+msgstr "Brak należności"+msgid "No remaining entities to inspect."msgstr "Brak pozostałych jednostek do sprawdzenia."@@ -7598,6 +7796,9 @@ msgstr "Na zamówieniu sprzedaży"msgid "On Storage Unit"msgstr "Na jednostce magazynowej"+msgid "On-account credit available"+msgstr "Dostępny kredyt na koncie"+msgid "On-hand counts"msgstr "Dostępne ilości"@@ -7818,6 +8019,12 @@ msgstr "Zamówienia przesłane"msgid "Origin"msgstr "Pochodzenie"+msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"+msgstr "Konto dochodów pozostałych dla zysków walutowych, gdy płatność rozlicza fakturę w walucie obcej po kursie bardziej korzystnym"++msgid "Other Income account for vendor balances cleared without full payment on AP settlement"+msgstr "Konto dochodów pozostałych dla sald dostawców rozliczonych bez pełnej płatności przy rozliczeniu zobowiązań"+msgid "Other Type"msgstr "Inny typ"@@ -7839,6 +8046,9 @@ msgstr "Produkt nigdy nie przetrwa dłużej niż jego surowce. Powraca do stałemsgid "Outside operation"msgstr "Odchylenie Kosztów Pośrednich"+msgid "Over-applied by"+msgstr "Przekroczone o"+msgid "Overdue"msgstr "Zaległy"@@ -7975,6 +8185,9 @@ msgstr "Części i artykuły"msgid "Parts, materials, and how you classify them."msgstr "Części, materiały i sposób ich klasyfikacji."+msgid "Party Type"+msgstr "Typ strony"+msgid "Pass"msgstr "Zatwierdź"@@ -7984,17 +8197,29 @@ msgstr "Zaliczone · ponownie otwórz"msgid "Path"msgstr "Ścieżka"+msgid "Pay Rate"+msgstr "Kurs płatności"+msgid "Payables"msgstr "Zobowiązania (domyślnie)"msgid "Payables (default)"msgstr "warunek płatności"+msgid "Payables aging"+msgstr "Wiekowanie zobowiązań"+msgid "Payment"msgstr "Płatność"-msgid "Payment Method"-msgstr "Metoda Płatności"+msgid "Payment Applications"+msgstr "Zastosowania Płatności"++msgid "Payment Date"+msgstr "Data płatności"++msgid "Payment ID"+msgstr "Identyfikator płatności"msgid "payment term"msgstr "warunki płatności"@@ -8011,6 +8236,12 @@ msgstr "Warunki Płatności"msgid "Payment terms like Net 30 or due on receipt"msgstr "Warunki płatności takie jak Net 30 lub płatne przy odbiorze"+msgid "Payments"+msgstr "Płatności"++msgid "Payments and credits applied to this invoice. Click a row to open the source document."+msgstr "Płatności i kredyty zastosowane do tej faktury. Kliknij wiersz, aby otworzyć dokument źródłowy."+msgid "PDF"msgstr "PDF"@@ -8672,6 +8903,9 @@ msgstr "Zakupy i automatyczne planowanie"msgid "Purchasing Contact"msgstr "Kontakt ds. Zakupów"+msgid "Purchasing Invoices"+msgstr "Faktury zakupu"+msgid "Purchasing Unit of Measure"msgstr "Jednostka miary zakupu"@@ -8866,9 +9100,18 @@ msgstr "Widoczność zapasów i hali produkcyjnej w czasie rzeczywistym"msgid "Real-time questions during hypercare"msgstr "Pytania w czasie rzeczywistym podczas hypercare"+msgid "Realized Exchange Gain"+msgstr "Zrealizowany zysk z wymiany walut"++msgid "Realized Exchange Loss"+msgstr "Zrealizowana strata walutowa"+msgid "Reason"msgstr "Powód"+msgid "Reason Account"+msgstr "Konto przyczyny"+msgid "Reason for declining (Optional)"msgstr "Powód odrzucenia (Opcjonalnie)"@@ -8911,6 +9154,9 @@ msgstr "Należności (domyślnie)"msgid "Receivables (default)"msgstr "Uzgodnienie zamówienia zakupowego z tym, co zostało odebrane i zafakturowane — niejawnie w Carbon, przez ilości wierszy i saldo GR/IR."+msgid "Receivables aging"+msgstr "Starzenie się należności"+msgid "Receive"msgstr "Odbierz"@@ -8921,6 +9167,13 @@ msgstr "Odbierz {0} do Magazynu"msgid "Receive against a PO and update inventory"msgstr "Odbierz względem PO i zaktualizuj zapasy"+msgid "Receive Payment"+msgstr "Otrzymaj płatność"++#. placeholder {0}: selectedInvoices.length+msgid "Receive Payment · {0} invoices"+msgstr "Otrzymaj płatność · {0} faktury"+msgid "Receive to Inventory"msgstr "Odbierz do Magazynu"@@ -8944,6 +9197,9 @@ msgstr "Lokalizacja odbioru"msgid "Recent"msgstr "Ostatnie"+msgid "Recent payments"+msgstr "Ostatnie płatności"+msgid "Recently Created"msgstr "Niedawno utworzone"@@ -8953,6 +9209,12 @@ msgstr "Okres Odzysku"msgid "Record"msgstr "Nagrywaj"+msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."+msgstr "Zarejestruj notę kredytową lub debetową dla klienta lub dostawcy. Zastosowania do konkretnych faktur są dodawane po utworzeniu noty."++msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."+msgstr "Zarejestruj gotówkę otrzymaną od klienta (Wpłata) lub zapłaconą dostawcy (Wypłata). Aplikacje do konkretnych faktur są dodawane po utworzeniu płatności."+msgid "Record deleted"msgstr "Rekord usunięty"@@ -9037,6 +9299,9 @@ msgstr "Zwolnij zadanie"msgid "Released"msgstr "Wydane"+msgid "Remaining"+msgstr "Pozostało"+msgid "Remaining after split stays on the original row."msgstr "Pozostała ilość po podziale pozostaje w oryginalnym wierszu."@@ -9583,6 +9848,9 @@ msgstr "Zapisz i zamknij"msgid "Save and Overwrite"msgstr "Zapisz i Zastąp"+msgid "Save applications"+msgstr "Zapisz aplikacje"+msgid "Save contacts"msgstr "Zapisz kontakty"@@ -9824,6 +10092,15 @@ msgstr "Wybierz Miernik"msgid "Select groups or individuals"msgstr "Wybierz grupy lub osoby"+msgid "Select invoice"+msgstr "Wybierz fakturę"++msgid "Select invoices from a single counterparty"+msgstr "Wybierz faktury od jednego kontrahenta"++msgid "Select invoices in a single currency"+msgstr "Wybierz faktury w jednej walucie"+msgid "Select Item Type"msgstr "Wybierz typ elementu"@@ -9860,6 +10137,9 @@ msgstr "Wybierz powierzchnie"msgid "Select the groups that should complete this training"msgstr "Wybierz grupy, które powinny ukończyć to szkolenie"+msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."+msgstr "Wybierz faktury, które ta płatność rozlicza. Rabat i odpis są w walucie faktury."+msgid "Select value"msgstr "Wybierz wartość"@@ -10575,6 +10855,9 @@ msgstr "Wariancja Podwykonawstwa"msgid "Subcontracting Variance (default)"msgstr "Wariancja Podwykonawstwa (domyślnie)"+msgid "Subledger"+msgstr "Księga pomocnicza"+msgid "Submit anonymously"msgstr "Wyslij anonimowo"@@ -11597,6 +11880,9 @@ msgstr "Brak aktywnych ofert dostawców do porównania dla tego zapytania ofertomsgid "There are outside operations associated with this job that have no suppliers. Please assign a supplier to each outside operation before releasing it."msgstr "Istnieją operacje zewnętrzne powiązane z tym zadaniem, które nie mają dostawców. Proszę przypisać dostawcę do każdej operacji zewnętrznej przed jej uruchomieniem."+msgid "There's nothing outstanding to apply these credits to."+msgstr "Nie ma nic do wyrównania, do czego można by zastosować te kredyty."+msgid "These custom fields will only be available for entities with the same tags"msgstr "Te niestandardowe pola będą dostępne tylko dla jednostek z tymi samymi tagami"@@ -11612,6 +11898,9 @@ msgstr "Te zadania mają operacje przypisane do tego centrum pracy:"msgid "This completes the Discovery step."msgstr "To uzupełnia krok Discovery."+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."+msgstr "Ta strona nie ma żadnych zaległości — płatność zostanie zarejestrowana na koncie."+msgid "This information will be used on document headers"msgstr "Te informacje będą używane w nagłówkach dokumentów"@@ -11720,6 +12009,9 @@ msgstr "Czwartek"msgid "Tie shipments through to an invoice with no re-keying"msgstr "Powiąż przesyłki z fakturą bez ponownego wprowadzania danych"+msgid "Tie-Out"+msgstr "Uzgodnienie"+msgid "Tightened"msgstr "Ścisły"@@ -11756,6 +12048,9 @@ msgstr "Do wysłania i odebrania"msgid "To Storage Unit"msgstr "Do jednostki magazynowej"+msgid "To supplier"+msgstr "Do dostawcy"+msgid "Today"msgstr "Dzisiaj"@@ -11825,6 +12120,9 @@ msgstr "Klasyfikacja najwyższego poziomu (aktywa/pasywa/kapitał własny/przychmsgid "Total"msgstr "Razem"+msgid "Total Amount"+msgstr "Kwota całkowita"+msgid "Total capitalized cost of the asset (purchase price plus freight, install, and other costs that become part of book value)."msgstr "Całkowity skapitalizowany koszt zasobu (cena nabycia plus fracht, instalacja i inne koszty, które stają się częścią wartości netto w księgach)."@@ -11852,6 +12150,9 @@ msgstr "Łączna ilość wymagana we wszystkich aktywnych zadaniach i zamówienimsgid "Total:"msgstr "Razem:"+msgid "Totals"+msgstr "Razem"+msgid "Traceability"msgstr "Możliwość śledzenia"@@ -12008,6 +12309,12 @@ msgstr "Typy"msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."msgstr "Nieprzetestowane jednostki pozostaną w stanie Wstrzymane, aby można było kontynuować inspekcję i podjąć decyzję później. Wyniki testowanych jednostek są zachowywane."+msgid "Unapplied"+msgstr "Niezastosowane"++msgid "Unapplied:"+msgstr "Niezastosowane:"+msgid "Unapproved Supplier"msgstr "Niezatwierdzony dostawca"@@ -12351,6 +12658,9 @@ msgstr "Numer rejestracyjny podatku od wartości dodanej; wymagany na fakturachmsgid "Values"msgstr "Wartości"+msgid "Variance"+msgstr "Odchylenie"+msgid "Variance between actual and standard BOM component consumption"msgstr "Odchylenie między rzeczywistym i standardowym zużyciem komponentów listy materiałów"@@ -12372,6 +12682,9 @@ msgstr "Odchylenie w kosztach przetwarzania zewnętrznego"msgid "VAT Number"msgstr "Numer VAT"+msgid "Vendor Write-Off Income"+msgstr "Dochód ze sprzedaży zobowiązań dostawcy"+msgid "Verification Error"msgstr "Błąd weryfikacji"@@ -12453,6 +12766,9 @@ msgstr "Wyświetl listy"msgid "View maintenance dispatch"msgstr "Wyświetl dyspozycję konserwacji"+msgid "View Memo"+msgstr "Wyświetl Notatkę"+msgid "View missing values"msgstr "Wyświetl brakujące wartości"@@ -12474,6 +12790,9 @@ msgstr "Wyświetl otwarte oferty"msgid "View Open RFQs"msgstr "Wyświetl otwarte zapytania ofertowe"+msgid "View Payment"+msgstr "Wyświetl Płatność"+msgid "View permissions"msgstr "Uprawnienia do podglądu"@@ -13042,9 +13361,19 @@ msgstr "Maszyny o najgorszych wynikach"msgid "Write-Down Account"msgstr "Konto Obniżenia Wartości"+msgid "Write-off"+msgstr "Odpis"++msgid "Write-Off"+msgstr "Odpis"+msgid "Write-Off Account"msgstr "Konto Odpisu"+#. placeholder {0}: r.invoiceId+msgid "Write-off for {0}"+msgstr "Odpis dla {0}"+msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."msgstr "Zmniejszanie wartości składnika aktywów w trakcie jego użyteczności — monta miesięczny, który tworzysz, przeglądam jako wersję roboczą, a następnie księgujesz."diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 34b74111df..5b786fc283 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -31,6 +31,10 @@ msgstr "\"Ninguém foi demitido por comprar.\" Um fator de conforto do incumbentmsgid "(excluded for this customer)"msgstr "(excluído para este cliente)"+#. placeholder {0}: ar.count+msgid "{0} customers with a balance"+msgstr "{0} clientes com saldo"+#. placeholder {0}: rule.escalationDaysmsgid "{0} days"msgstr "{0} dias"@@ -48,6 +52,10 @@ msgstr "{0} pedidos"msgid "{0} Processes"msgstr "{0} Processos"+#. placeholder {0}: ap.count+msgid "{0} suppliers with a balance"+msgstr "{0} fornecedores com saldo"+#. placeholder {0}: lotEntities.length - inspectedmsgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "{0} entidades não amostradas serão liberadas para Disponível. Passes amostradas permanecem Disponível e falhas amostradas permanecem Rejeitadas."@@ -60,6 +68,12 @@ msgstr "{0} enviado com sucesso"msgid "{0} values missing"msgstr "{0} valores ausentes"+msgid "{apOverduePct}% of payables"+msgstr "{apOverduePct}% de contas a pagar"++msgid "{arOverduePct}% of receivables"+msgstr "{arOverduePct}% de contas a receber"+msgid "{chainLabel}. Consider pointing this part directly at the final successor."msgstr "{chainLabel}. Considere apontar esta peça diretamente para o sucessor final."@@ -743,6 +757,10 @@ msgstr "Montante que aumenta ativos/despesas ou diminui passivos/patrimônio/recmsgid "Amount that increases liabilities/equity/revenue or decreases assets/expenses on this line."msgstr "Montante que aumenta passivos/patrimônio/receitas ou diminui ativos/despesas nesta linha."+#. placeholder {0}: r.memoId+msgid "Amount to apply for {0}"+msgstr "Valor a aplicar para {0}"+msgid "Amount Type"msgstr "Tipo de Valor"@@ -806,6 +824,12 @@ msgstr "Qualquer coisa não explicitamente listada no escopo acima"msgid "AP Clerk"msgstr "Assistente de Contas a Pagar"+msgid "AP Outstanding"+msgstr "AP Pendente"++msgid "AP Overdue"+msgstr "AP Vencido"+msgid "API and Webhooks"msgstr "API e Webhooks"@@ -824,6 +848,19 @@ msgstr "Chaves de API"msgid "API keys for programmatic access to your Carbon data."msgstr "Chaves de API para acesso programático aos seus dados do Carbon."+msgid "Applied"+msgstr "Aplicado"++#. placeholder {0}: r.invoiceId+msgid "Applied amount for {0}"+msgstr "Valor aplicado para {0}"++msgid "Applied Date"+msgstr "Data de Aplicação"++msgid "Applied To"+msgstr "Aplicado a"+msgid "Applies to"msgstr "Aplica-se a"@@ -833,6 +870,12 @@ msgstr "Aplica-se a todos"msgid "Applies to all work centers"msgstr "Aplica-se a todos os centros de trabalho"+msgid "Apply available credits"+msgstr "Aplicar créditos disponíveis"++msgid "Apply credits"+msgstr "Aplicar créditos"+msgid "Apply payments and track aging"msgstr "Aplicar pagamentos e rastrear vencimento"@@ -845,6 +888,12 @@ msgstr "Aplicar regras na parte superior"msgid "Apply To"msgstr "Aplicar a"+msgid "Apply to invoice"+msgstr "Aplicar à fatura"++msgid "Apply to invoices"+msgstr "Aplicar a faturas"+msgid "Approaching {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB cap."msgstr "Aproximando-se do limite de {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB."@@ -875,6 +924,12 @@ msgstr "AQL (Z1.4 / ISO 2859-1)"msgid "AR Clerk"msgstr "Funcionário de Contas a Receber"+msgid "AR Outstanding"+msgstr "AR Pendente"++msgid "AR Overdue"+msgstr "AR Vencido"+msgid "Archive"msgstr "Arquivo"@@ -955,9 +1010,9 @@ msgstr "Tem a certeza de que deseja eliminar {0} desta operação? Isto não podmsgid "Are you sure you want to delete {0}?"msgstr "Tem a certeza de que deseja eliminar {0}?"+#. placeholder {0}: initialValues.memoId+#. placeholder {0}: initialValues.paymentId#. placeholder {0}: pickingList.pickingListId-#. placeholder {0}: routeData?.consumableSummary?.readableIdWithRevision-#. placeholder {0}: routeData?.customer?.name!msgid "Are you sure you want to delete {0}? This cannot be undone."msgstr "Tem a certeza de que deseja eliminar {0}? Esta ação não pode ser desfeita."@@ -1243,6 +1298,9 @@ msgstr "Tem a certeza?"msgid "As needed"msgstr "Conforme necessário"+msgid "As of:"+msgstr "A partir de:"+msgid "As the company owner, you can transfer ownership to another employee. This will give them full access to billing and administrative settings."msgstr "Como proprietário da empresa, você pode transferir a propriedade para outro funcionário. Isso lhe dará acesso total às configurações de faturamento e administrativas."@@ -1371,6 +1429,9 @@ msgstr "Registos de Auditoria"msgid "Authentication Error"msgstr "Erro de Autenticação"+msgid "Auto apply"+msgstr "Aplicar automaticamente"+msgid "Auto Release"msgstr "Lançamento Automático"@@ -1440,9 +1501,15 @@ msgstr "Descarga Automática"msgid "Backups"msgstr "Backups"+msgid "Balance"+msgstr "Saldo"+msgid "Balance Sheet"msgstr "Balanço Patrimonial"+msgid "Balanced"+msgstr "Equilibrado"+msgid "Balloon"msgstr "Balão"@@ -1464,6 +1531,9 @@ msgstr "Banco — Moeda estrangeira (padrão)"msgid "Bank — Local Currency (default)"msgstr "Banco — Moeda local (padrão)"+msgid "Bank / Cash Account"+msgstr "Conta Bancária / Caixa"+msgid "Bank account denominated in a foreign currency"msgstr "Conta bancária denominada em moeda estrangeira."@@ -1643,6 +1713,12 @@ msgstr "por {byUser}"msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."msgstr "Ao aceitar o convite, você concorda com os <0>Termos de Serviço</0> e a <1>Política de Privacidade</1>."+msgid "By Document Date"+msgstr "Por Data do Documento"++msgid "By Due Date"+msgstr "Por Data de Vencimento"+msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"msgstr "Ao fazer login, você concorda com os <0>Termos de Serviço</0> e a <1>Política de Privacidade.</1>"@@ -1931,6 +2007,9 @@ msgstr "Limpar pesquisa"msgid "Clear search query"msgstr "Limpar consulta de pesquisa"+msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."+msgstr "Limpe esta fatura com os créditos lançados da parte bem como dinheiro. Os créditos se aplicam diretamente — nenhum lançamento necessário."+msgid "Clearing account between goods receipt and supplier invoice; balances when both have posted."msgstr "Conta de compensação entre recebimento de mercadorias e fatura do fornecedor; equilibra quando ambos foram lançados."@@ -1977,6 +2056,9 @@ msgstr "Nuvem, ou seu ambiente auto-hospedado."msgid "Code"msgstr "Código"+msgid "Collapse"+msgstr "Recolher"+msgid "Collapse all"msgstr "Recolher tudo"@@ -2552,6 +2634,12 @@ msgstr "Não foi possível carregar documentos"msgid "Count"msgstr "Contagem"+msgid "Counterparties"+msgstr "Contrapartes"++msgid "Counterparty"+msgstr "Contraparte"+msgid "Country"msgstr "País"@@ -2582,6 +2670,9 @@ msgstr "Criar uma cotação com um novo ID de cotação"msgid "Create Account"msgstr "Criar Conta"+msgid "Create adjusting entry"+msgstr "Criar entrada de ajuste"+msgid "Create an account"msgstr "Criar uma conta"@@ -2755,12 +2846,21 @@ msgstr "Criando peça..."msgid "Credit"msgstr "Crédito"+msgid "Credit / Debit Memos"+msgstr "Memorandos de Crédito / Débito"+msgid "Credit Account"msgstr "Conta de Crédito"msgid "Credit account when labor/machine time is absorbed into WIP"msgstr "Conta de crédito quando tempo de mão de obra/máquina é absorvido em WIP"+msgid "Credits & Debits"+msgstr "Créditos e Débitos"++msgid "Credits applied"+msgstr "Créditos aplicados"+msgid "Critical"msgstr "Crítico"@@ -2935,6 +3035,9 @@ msgstr "tipos de cliente"msgid "Customer Types"msgstr "Tipos de Cliente"+msgid "Customer Write-Off (Bad Debt)"+msgstr "Baixa de Cliente (Crédito Duvidoso)"+msgid "customers"msgstr "clientes"@@ -3314,12 +3417,18 @@ msgstr "Eliminar Forma de Material"msgid "Delete Material Type"msgstr "Eliminar Tipo de Material"+msgid "Delete Memo"+msgstr "Excluir Memorando"+msgid "Delete Part"msgstr "Eliminar Peça"msgid "Delete Partner"msgstr "Eliminar Parceiro"+msgid "Delete Payment"+msgstr "Eliminar Pagamento"+msgid "Delete Payment Term"msgstr "Eliminar Termo de Pagamento"@@ -3566,6 +3675,12 @@ msgstr "Dimensões"msgid "Direct"msgstr "Direto"+msgid "Direction"+msgstr "Direção"++msgid "Directions"+msgstr "Direções"+msgid "Disabled"msgstr "Desativado"@@ -3584,6 +3699,10 @@ msgstr "Dias de Desconto"msgid "Discount Days after {selectedCalculationMethod}"msgstr "Dias de Desconto após {selectedCalculationMethod}"+#. placeholder {0}: r.invoiceId+msgid "Discount for {0}"+msgstr "Desconto para {0}"+msgid "Discount Percent"msgstr "Percentual de Desconto"@@ -3717,6 +3836,9 @@ msgstr "Arraste para redimensionar diagrama e recursos"msgid "Drag to zoom"msgstr "Arrastar para ampliar"+msgid "Drawing"+msgstr "Sacando"+msgid "Drawing Number"msgstr "Número do Desenho"@@ -3952,6 +4074,9 @@ msgstr "Editar Substância Material"msgid "Edit Material Type"msgstr "Editar Tipo de Material"+msgid "Edit Memo"+msgstr "Editar Memorando"+msgid "Edit Non Conformance Type"msgstr "Editar Tipo de Não Conformidade"@@ -3961,6 +4086,9 @@ msgstr "Editar Peça"msgid "Edit Partner"msgstr "Editar Parceiro"+msgid "Edit Payment"+msgstr "Editar Pagamento"+msgid "Edit Payment Term"msgstr "Editar Termo de Pagamento"@@ -4442,12 +4570,18 @@ msgstr "Recebimento Esperado"msgid "Expected Receipt Date"msgstr "Data de Recebimento Esperada"+msgid "Expense account for customer balances written off as uncollectable on AR settlement"+msgstr "Conta de despesa para saldos de clientes baixados como incobrável na liquidação de AR"+msgid "Expense account for deferred tax adjustments on depreciation"msgstr "Conta de despesas para ajustes de imposto diferido sobre depreciação"msgid "Expense account for equipment and facility maintenance"msgstr "Conta de despesas para manutenção de equipamentos e instalações"+msgid "Expense account for FX losses when a payment settles a foreign-currency invoice at a less favorable rate"+msgstr "Conta de despesa para perdas de câmbio quando um pagamento liquida uma fatura em moeda estrangeira a uma taxa menos favorável"+msgid "Expense account for non-inventory purchases (services, supplies)"msgstr "Conta de despesas para compras fora do inventário (serviços, suprimentos)"@@ -5028,9 +5162,15 @@ msgstr "Sexta-feira"msgid "From {0}"msgstr "De {0}"+msgid "From customer"+msgstr "Do cliente"+msgid "From Location"msgstr "De Localização"+msgid "from on-account credit"+msgstr "do crédito em conta"+msgid "From Storage Unit"msgstr "Unidade de Armazenamento De"@@ -5040,6 +5180,9 @@ msgstr "Local de Cumprimento"msgid "Fully trained for"msgstr "Totalmente treinado para"+msgid "FX G/L"+msgstr "FX G/L"+msgid "Gains and Losses"msgstr "Ganhos e Perdas (padrão)"@@ -5127,6 +5270,9 @@ msgstr "Navegando pelo Carbon"msgid "Getting set up"msgstr "Configurando"+msgid "GL"+msgstr "GL"+msgid "GL Account"msgstr "Conta Contábil"@@ -5241,6 +5387,12 @@ msgstr "Conta GL de despesa para compras fora do inventário (suprimentos, servimsgid "GL liability account credited for sales tax collected from customers."msgstr "Conta GL de passivo creditada para imposto sobre vendas cobrado de clientes."+msgid "GL tie-out"+msgstr "Reconciliação GL"++msgid "GL Tie-Out"+msgstr "Reconciliação GL"+msgid "Go live right the first time — with our team alongside you"msgstr "Ative-se corretamente na primeira vez — com nossa equipe ao seu lado"@@ -5773,6 +5925,9 @@ msgstr "Referência interna para onde cada ferramenta é mais forte. Use-a paramsgid "inv"msgstr "inv"+msgid "Inv Rate"+msgstr "Taxa Inv"+msgid "Invalid Invite"msgstr "Convite Inválido"@@ -5884,6 +6039,12 @@ msgstr "Estados Faturados"msgid "Invoices"msgstr "Faturas"+msgid "Invoices this memo has been applied to. Click a row to open the document."+msgstr "Faturas às quais este memorando foi aplicado. Clique em uma linha para abrir o documento."++msgid "Invoicing"+msgstr "Faturação"+msgid "is"msgstr "é"@@ -6451,6 +6612,13 @@ msgstr "Itens de fabricação não podem ser faturados diretamente. Altere o mémsgid "Make Method Version"msgstr "Versão do Método de Fabricação"+msgid "Make Payment"+msgstr "Efetuar Pagamento"++#. placeholder {0}: selectedInvoices.length+msgid "Make Payment · {0} invoices"+msgstr "Efetuar Pagamento · {0} faturas"+#. placeholder {0}: selectedRevision.revisionmsgid "Make revision {0} default?"msgstr "Tornar revisão {0} padrão?"@@ -6693,6 +6861,15 @@ msgstr "Cadência de reuniões"msgid "Members"msgstr "Membros"+msgid "Memo"+msgstr "Memorando"++msgid "Memo Date"+msgstr "Data do Memorando"++msgid "Memo ID"+msgstr "ID do Memorando"+msgid "MES"msgstr "MES"@@ -6953,6 +7130,9 @@ msgstr "Novo Consumível"msgid "New Contractor"msgstr "Novo Contratante"+msgid "New Credit / Debit Memo"+msgstr "Novo Memorando de Crédito / Débito"+msgid "New Custom Field"msgstr "Novo Campo Personalizado"@@ -7061,6 +7241,9 @@ msgstr "Nova Peça"msgid "New Password"msgstr "Nova Senha"+msgid "New Payment"+msgstr "Novo Pagamento"+msgid "New Payment Term"msgstr "Novo Termo de Pagamento"@@ -7252,6 +7435,9 @@ msgstr "Sem Cotações Ativas"msgid "No addresses found"msgstr "Nenhum endereço encontrado"+msgid "No applications. Payment will be on-account."+msgstr "Sem aplicações. O pagamento será na conta."+#. placeholder {0}: auditConfig.retentionDaysmsgid "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."msgstr "Nenhum log arquivado ainda. Logs com mais de {0} dias serão automaticamente arquivados e disponíveis para download aqui."@@ -7370,6 +7556,9 @@ msgstr "Sem notificações novas"msgid "No notes"msgstr "Sem notas"+msgid "No open invoices"+msgstr "Nenhuma fatura aberta"+msgid "No operations require picking at this location"msgstr "Nenhuma operação requer picking neste local"@@ -7397,6 +7586,12 @@ msgstr "Nenhuma fonte pai registrada ainda. Clique em Recalcular na página de pmsgid "No part ID"msgstr "Sem ID de peça"+msgid "No payables"+msgstr "Sem contas a pagar"++msgid "No payments yet."+msgstr "Nenhum pagamento ainda."+msgid "No planning data"msgstr "Sem dados de planejamento"@@ -7421,6 +7616,9 @@ msgstr "Sem Motivo de Cotação"msgid "No Quote Reasons"msgstr "Sem Motivos de Cotação"+msgid "No receivables"+msgstr "Sem recebíveis"+msgid "No remaining entities to inspect."msgstr "Nenhuma entidade restante para inspecionar."@@ -7598,6 +7796,9 @@ msgstr "Em Pedido de Venda"msgid "On Storage Unit"msgstr "Na Unidade de Armazenamento"+msgid "On-account credit available"+msgstr "Crédito em conta disponível"+msgid "On-hand counts"msgstr "Contagens em estoque"@@ -7818,6 +8019,12 @@ msgstr "Pedidos enviados"msgid "Origin"msgstr "Origem"+msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"+msgstr "Conta de Outras Receitas para ganhos de câmbio quando um pagamento liquida uma fatura em moeda estrangeira a uma taxa mais favorável"++msgid "Other Income account for vendor balances cleared without full payment on AP settlement"+msgstr "Conta de Outras Receitas para saldos de fornecedores liquidados sem pagamento integral na liquidação de AP"+msgid "Other Type"msgstr "Outro Tipo"@@ -7839,6 +8046,9 @@ msgstr "O resultado nunca dura mais do que suas matérias-primas. Volta à duramsgid "Outside operation"msgstr "Variação de Despesas Gerais"+msgid "Over-applied by"+msgstr "Aplicado em excesso por"+msgid "Overdue"msgstr "Vencido"@@ -7975,6 +8185,9 @@ msgstr "Peças e itens"msgid "Parts, materials, and how you classify them."msgstr "Peças, materiais e como você os classifica."+msgid "Party Type"+msgstr "Tipo de Parte"+msgid "Pass"msgstr "Passar"@@ -7984,17 +8197,29 @@ msgstr "Aprovado · reabrir"msgid "Path"msgstr "Caminho"+msgid "Pay Rate"+msgstr "Taxa de Pagamento"+msgid "Payables"msgstr "Contas a Pagar (padrão)"msgid "Payables (default)"msgstr "prazo de pagamento"+msgid "Payables aging"+msgstr "Envelhecimento de contas a pagar"+msgid "Payment"msgstr "Pagamento"-msgid "Payment Method"-msgstr "Método de Pagamento"+msgid "Payment Applications"+msgstr "Aplicações de Pagamento"++msgid "Payment Date"+msgstr "Data de Pagamento"++msgid "Payment ID"+msgstr "ID de Pagamento"msgid "payment term"msgstr "prazos de pagamento"@@ -8011,6 +8236,12 @@ msgstr "Condições de Pagamento"msgid "Payment terms like Net 30 or due on receipt"msgstr "Termos de pagamento como Net 30 ou vencimento no recebimento"+msgid "Payments"+msgstr "Pagamentos"++msgid "Payments and credits applied to this invoice. Click a row to open the source document."+msgstr "Pagamentos e créditos aplicados a esta fatura. Clique em uma linha para abrir o documento de origem."+msgid "PDF"msgstr "PDF"@@ -8672,6 +8903,9 @@ msgstr "Compras e planejamento automático"msgid "Purchasing Contact"msgstr "Contacto de Compras"+msgid "Purchasing Invoices"+msgstr "Faturas de Compra"+msgid "Purchasing Unit of Measure"msgstr "Unidade de Medida de Compra"@@ -8866,9 +9100,18 @@ msgstr "Visibilidade em tempo real do inventário e do chão de fábrica"msgid "Real-time questions during hypercare"msgstr "Perguntas em tempo real durante o hipercare"+msgid "Realized Exchange Gain"+msgstr "Ganho Cambial Realizado"++msgid "Realized Exchange Loss"+msgstr "Perda Cambial Realizada"+msgid "Reason"msgstr "Motivo"+msgid "Reason Account"+msgstr "Conta de Motivo"+msgid "Reason for declining (Optional)"msgstr "Motivo da recusa (Opcional)"@@ -8911,6 +9154,9 @@ msgstr "Contas a Receber (padrão)"msgid "Receivables (default)"msgstr "Reconciliação de um pedido de compra com o que foi recebido e faturado — implícito em Carbon, através das quantidades de linha e saldo GR/IR."+msgid "Receivables aging"+msgstr "Envelhecimento de contas a receber"+msgid "Receive"msgstr "Receber"@@ -8921,6 +9167,13 @@ msgstr "Receber {0} para Inventário"msgid "Receive against a PO and update inventory"msgstr "Receber contra um PO e atualizar inventário"+msgid "Receive Payment"+msgstr "Receber Pagamento"++#. placeholder {0}: selectedInvoices.length+msgid "Receive Payment · {0} invoices"+msgstr "Receber Pagamento · {0} faturas"+msgid "Receive to Inventory"msgstr "Receber para Inventário"@@ -8944,6 +9197,9 @@ msgstr "Local de Recebimento"msgid "Recent"msgstr "Recente"+msgid "Recent payments"+msgstr "Pagamentos recentes"+msgid "Recently Created"msgstr "Criado Recentemente"@@ -8953,6 +9209,12 @@ msgstr "Período de Recuperação"msgid "Record"msgstr "Gravar"+msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."+msgstr "Registre um memorando de crédito ou débito contra um cliente ou fornecedor. As aplicações a faturas específicas são adicionadas após a criação do memorando."++msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."+msgstr "Registre o dinheiro recebido de um cliente (Recebimento) ou pago a um fornecedor (Desembolso). As aplicações para faturas específicas são adicionadas após a criação do pagamento."+msgid "Record deleted"msgstr "Registro eliminado"@@ -9037,6 +9299,9 @@ msgstr "Liberar Trabalho"msgid "Released"msgstr "Liberado"+msgid "Remaining"+msgstr "Restante"+msgid "Remaining after split stays on the original row."msgstr "Restante após divisão permanece na linha original."@@ -9583,6 +9848,9 @@ msgstr "Guardar e Fechar"msgid "Save and Overwrite"msgstr "Guardar e Sobrescrever"+msgid "Save applications"+msgstr "Guardar aplicações"+msgid "Save contacts"msgstr "Guardar contactos"@@ -9824,6 +10092,15 @@ msgstr "Selecionar Medidor"msgid "Select groups or individuals"msgstr "Selecione grupos ou indivíduos"+msgid "Select invoice"+msgstr "Selecionar fatura"++msgid "Select invoices from a single counterparty"+msgstr "Selecione faturas de um único contraparte"++msgid "Select invoices in a single currency"+msgstr "Selecione faturas em uma única moeda"+msgid "Select Item Type"msgstr "Selecionar Tipo de Item"@@ -9860,6 +10137,9 @@ msgstr "Selecionar superfícies"msgid "Select the groups that should complete this training"msgstr "Selecione os grupos que devem concluir este treinamento"+msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."+msgstr "Selecione as faturas que este pagamento liquida. Desconto e cancelamento estão na moeda da fatura."+msgid "Select value"msgstr "Selecionar valor"@@ -10575,6 +10855,9 @@ msgstr "Variação de Subcontratação"msgid "Subcontracting Variance (default)"msgstr "Variação de Subcontratação (padrão)"+msgid "Subledger"+msgstr "Razão Auxiliar"+msgid "Submit anonymously"msgstr "Enviar anonimamente"@@ -11597,6 +11880,9 @@ msgstr "Não há cotações de fornecedor ativas para comparar para este RFQ."msgid "There are outside operations associated with this job that have no suppliers. Please assign a supplier to each outside operation before releasing it."msgstr "Existem operações externas associadas a este trabalho que não têm fornecedores. Atribua um fornecedor a cada operação externa antes de liberá-lo."+msgid "There's nothing outstanding to apply these credits to."+msgstr "Não há nada pendente para aplicar esses créditos."+msgid "These custom fields will only be available for entities with the same tags"msgstr "Estes campos personalizados estarão disponíveis apenas para entidades com as mesmas tags"@@ -11612,6 +11898,9 @@ msgstr "Estes trabalhos têm operações atribuídas a este centro de trabalho:"msgid "This completes the Discovery step."msgstr "Isto completa a etapa de Descoberta."+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."+msgstr "Este terceiro não tem nada pendente — o pagamento será registrado em conta."+msgid "This information will be used on document headers"msgstr "Esta informação será usada nos cabeçalhos de documentos"@@ -11720,6 +12009,9 @@ msgstr "Quinta-feira"msgid "Tie shipments through to an invoice with no re-keying"msgstr "Vincular remessas a uma fatura sem re-digitação"+msgid "Tie-Out"+msgstr "Reconciliação"+msgid "Tightened"msgstr "Apertado"@@ -11756,6 +12048,9 @@ msgstr "Para Enviar e Receber"msgid "To Storage Unit"msgstr "Para Unidade de Armazenamento"+msgid "To supplier"+msgstr "Para fornecedor"+msgid "Today"msgstr "Hoje"@@ -11825,6 +12120,9 @@ msgstr "Classificação de nível superior (ativo/passivo/patrimônio/receita/demsgid "Total"msgstr "Total"+msgid "Total Amount"+msgstr "Valor Total"+msgid "Total capitalized cost of the asset (purchase price plus freight, install, and other costs that become part of book value)."msgstr "Custo total capitalizado do ativo (preço de compra mais frete, instalação e outros custos que se tornam parte do valor líquido contábil)."@@ -11852,6 +12150,9 @@ msgstr "Quantidade total exigida em todos os trabalhos ativos e pedidos de vendamsgid "Total:"msgstr "Total:"+msgid "Totals"+msgstr "Totais"+msgid "Traceability"msgstr "Rastreabilidade"@@ -12008,6 +12309,12 @@ msgstr "Tipos"msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."msgstr "Entidades não amostradas permanecerão Em Espera para que você possa continuar inspecionando e fazer a disposição posteriormente. Os resultados das amostras são preservados."+msgid "Unapplied"+msgstr "Não aplicado"++msgid "Unapplied:"+msgstr "Não aplicado:"+msgid "Unapproved Supplier"msgstr "Fornecedor Não Aprovado"@@ -12351,6 +12658,9 @@ msgstr "Número de registro de imposto sobre valor agregado; obrigatório em fatmsgid "Values"msgstr "Valores"+msgid "Variance"+msgstr "Variação"+msgid "Variance between actual and standard BOM component consumption"msgstr "Variância entre consumo real e padrão de componentes da BOM"@@ -12372,6 +12682,9 @@ msgstr "Variância em custos de processamento externo"msgid "VAT Number"msgstr "Número de IVA"+msgid "Vendor Write-Off Income"+msgstr "Rendimento de Cancelamento de Fornecedor"+msgid "Verification Error"msgstr "Erro de Verificação"@@ -12453,6 +12766,9 @@ msgstr "Ver Listas"msgid "View maintenance dispatch"msgstr "Ver despacho de manutenção"+msgid "View Memo"+msgstr "Ver Memorando"+msgid "View missing values"msgstr "Ver valores ausentes"@@ -12474,6 +12790,9 @@ msgstr "Ver Cotações Abertas"msgid "View Open RFQs"msgstr "Ver RFQs Abertos"+msgid "View Payment"+msgstr "Ver Pagamento"+msgid "View permissions"msgstr "Permissões de visualização"@@ -13042,9 +13361,19 @@ msgstr "Máquinas com Pior Desempenho"msgid "Write-Down Account"msgstr "Conta de Redução de Valor"+msgid "Write-off"+msgstr "Cancelamento"++msgid "Write-Off"+msgstr "Cancelamento"+msgid "Write-Off Account"msgstr "Conta de Cancelamento"+#. placeholder {0}: r.invoiceId+msgid "Write-off for {0}"+msgstr "Cancelamento para {0}"+msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."msgstr "Reduzir o valor de um ativo ao longo de sua vida útil — um lote mensal que você cria, revisa como rascunho e depois contabiliza."diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex c696544e5f..6beb3b5646 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -31,6 +31,10 @@ msgstr "\"Никто не был уволен за его покупку.\" Фаmsgid "(excluded for this customer)"msgstr "(исключено для этого клиента)"+#. placeholder {0}: ar.count+msgid "{0} customers with a balance"+msgstr "{0} клиентов с остатком"+#. placeholder {0}: rule.escalationDaysmsgid "{0} days"msgstr "{0} дней"@@ -48,6 +52,10 @@ msgstr "{0} заказов"msgid "{0} Processes"msgstr "{0} Процессов"+#. placeholder {0}: ap.count+msgid "{0} suppliers with a balance"+msgstr "{0} поставщиков с остатком"+#. placeholder {0}: lotEntities.length - inspectedmsgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "{0} необследованных объектов будут отпущены в статус Available. Проверенные успешные остаются Available, а проверенные отказы остаются Rejected."@@ -60,6 +68,12 @@ msgstr "{0} успешно загружен"msgid "{0} values missing"msgstr "{0} значений отсутствует"+msgid "{apOverduePct}% of payables"+msgstr "{apOverduePct}% кредиторской задолженности"++msgid "{arOverduePct}% of receivables"+msgstr "{arOverduePct}% дебиторской задолженности"+msgid "{chainLabel}. Consider pointing this part directly at the final successor."msgstr "{chainLabel}. Рассмотрите возможность указания этой детали непосредственно на финального преемника."@@ -743,6 +757,10 @@ msgstr "Сумма, которая увеличивает активы/расхmsgid "Amount that increases liabilities/equity/revenue or decreases assets/expenses on this line."msgstr "Сумма, которая увеличивает пассивы/собственный капитал/доходы или уменьшает активы/расходы на этой строке."+#. placeholder {0}: r.memoId+msgid "Amount to apply for {0}"+msgstr "Сумма для применения для {0}"+msgid "Amount Type"msgstr "Тип суммы"@@ -806,6 +824,12 @@ msgstr "Все, что не указано явно в области дейстmsgid "AP Clerk"msgstr "Специалист по учету кредиторской задолженности"+msgid "AP Outstanding"+msgstr "Задолженность перед поставщиками"++msgid "AP Overdue"+msgstr "Просроченные кредиторские задолженности"+msgid "API and Webhooks"msgstr "API и Webhooks"@@ -824,6 +848,19 @@ msgstr "API ключи"msgid "API keys for programmatic access to your Carbon data."msgstr "API ключи для программного доступа к вашим данным Carbon."+msgid "Applied"+msgstr "Применено"++#. placeholder {0}: r.invoiceId+msgid "Applied amount for {0}"+msgstr "Примененная сумма для {0}"++msgid "Applied Date"+msgstr "Дата применения"++msgid "Applied To"+msgstr "Применено к"+msgid "Applies to"msgstr "Применяется к"@@ -833,6 +870,12 @@ msgstr "Применяется ко всем"msgid "Applies to all work centers"msgstr "Применяется ко всем рабочим центрам"+msgid "Apply available credits"+msgstr "Применить доступные кредиты"++msgid "Apply credits"+msgstr "Применить кредиты"+msgid "Apply payments and track aging"msgstr "Применять платежи и отслеживать просрочку"@@ -845,6 +888,12 @@ msgstr "Применить правила выше"msgid "Apply To"msgstr "Применить к"+msgid "Apply to invoice"+msgstr "Применить к счету"++msgid "Apply to invoices"+msgstr "Применить к счетам"+msgid "Approaching {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB cap."msgstr "Приближение к лимиту {PO_EMAIL_ATTACHMENT_LIMIT_MB} МБ."@@ -875,6 +924,12 @@ msgstr "АПК (Z1.4 / ISO 2859-1)"msgid "AR Clerk"msgstr "Специалист по расчетам с дебиторами"+msgid "AR Outstanding"+msgstr "Дебиторская задолженность"++msgid "AR Overdue"+msgstr "Просроченная дебиторская задолженность"+msgid "Archive"msgstr "Архив"@@ -955,9 +1010,9 @@ msgstr "Вы уверены, что хотите удалить {0} из этоmsgid "Are you sure you want to delete {0}?"msgstr "Вы уверены, что хотите удалить {0}?"+#. placeholder {0}: initialValues.memoId+#. placeholder {0}: initialValues.paymentId#. placeholder {0}: pickingList.pickingListId-#. placeholder {0}: routeData?.consumableSummary?.readableIdWithRevision-#. placeholder {0}: routeData?.customer?.name!msgid "Are you sure you want to delete {0}? This cannot be undone."msgstr "Вы уверены, что хотите удалить {0}? Это действие невозможно отменить."@@ -1243,6 +1298,9 @@ msgstr "Вы уверены?"msgid "As needed"msgstr "По мере необходимости"+msgid "As of:"+msgstr "По состоянию на:"+msgid "As the company owner, you can transfer ownership to another employee. This will give them full access to billing and administrative settings."msgstr "Как владелец компании, вы можете передать право собственности другому сотруднику. Это даст им полный доступ к биллингу и административным параметрам."@@ -1371,6 +1429,9 @@ msgstr "Журналы аудита"msgid "Authentication Error"msgstr "Ошибка аутентификации"+msgid "Auto apply"+msgstr "Автоматически применить"+msgid "Auto Release"msgstr "Автоматический выпуск"@@ -1440,9 +1501,15 @@ msgstr "Обратный отвод"msgid "Backups"msgstr "Резервные копии"+msgid "Balance"+msgstr "Баланс"+msgid "Balance Sheet"msgstr "Баланс"+msgid "Balanced"+msgstr "Сбалансировано"+msgid "Balloon"msgstr "Выноска"@@ -1464,6 +1531,9 @@ msgstr "Банк — Иностранная валюта (по умолчаниmsgid "Bank — Local Currency (default)"msgstr "Банк — Местная валюта (по умолчанию)"+msgid "Bank / Cash Account"+msgstr "Банковский / Кассовый счет"+msgid "Bank account denominated in a foreign currency"msgstr "Банковский счет в иностранной валюте."@@ -1643,6 +1713,12 @@ msgstr "от {byUser}"msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."msgstr "Принимая приглашение, вы соглашаетесь с <0>Условиями обслуживания</0> и <1>Политикой конфиденциальности</1>."+msgid "By Document Date"+msgstr "По дате документа"++msgid "By Due Date"+msgstr "По дате платежа"+msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"msgstr "Подписываясь, вы соглашаетесь с <0>Условиями обслуживания</0> и <1>Политикой конфиденциальности.</1>"@@ -1931,6 +2007,9 @@ msgstr "Очистить поиск"msgid "Clear search query"msgstr "Очистить поисковый запрос"+msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."+msgstr "Погасите этот счет с помощью опубликованных кредитов стороны, а также наличных средств. Кредиты применяются напрямую — публикация не требуется."+msgid "Clearing account between goods receipt and supplier invoice; balances when both have posted."msgstr "Транзитный счет между поступлением товаров и счетом поставщика; уравновешивается, когда оба были выполнены."@@ -1977,6 +2056,9 @@ msgstr "Облако или ваша собственная размещённаmsgid "Code"msgstr "Код"+msgid "Collapse"+msgstr "Свернуть"+msgid "Collapse all"msgstr "Свернуть все"@@ -2552,6 +2634,12 @@ msgstr "Не удалось загрузить документы"msgid "Count"msgstr "Количество"+msgid "Counterparties"+msgstr "Контрагенты"++msgid "Counterparty"+msgstr "Контрагент"+msgid "Country"msgstr "Страна"@@ -2582,6 +2670,9 @@ msgstr "Создать предложение с новым ID предложеmsgid "Create Account"msgstr "Создать учетную запись"+msgid "Create adjusting entry"+msgstr "Создать корректирующую запись"+msgid "Create an account"msgstr "Создать учетную запись"@@ -2755,12 +2846,21 @@ msgstr "Создание детали..."msgid "Credit"msgstr "Кредит"+msgid "Credit / Debit Memos"+msgstr "Кредит-ноты / Дебет-ноты"+msgid "Credit Account"msgstr "Счет кредита"msgid "Credit account when labor/machine time is absorbed into WIP"msgstr "Счет кредита при поглощении времени труда/машины в WIP"+msgid "Credits & Debits"+msgstr "Кредиты и дебеты"++msgid "Credits applied"+msgstr "Применённые кредиты"+msgid "Critical"msgstr "Критический"@@ -2935,6 +3035,9 @@ msgstr "типы клиентов"msgid "Customer Types"msgstr "Типы клиентов"+msgid "Customer Write-Off (Bad Debt)"+msgstr "Списание задолженности клиента (безнадежный долг)"+msgid "customers"msgstr "клиенты"@@ -3314,12 +3417,18 @@ msgstr "Удалить форму материала"msgid "Delete Material Type"msgstr "Удалить тип материала"+msgid "Delete Memo"+msgstr "Удалить Memo"+msgid "Delete Part"msgstr "Удалить деталь"msgid "Delete Partner"msgstr "Удалить партнера"+msgid "Delete Payment"+msgstr "Удалить платеж"+msgid "Delete Payment Term"msgstr "Удалить условие платежа"@@ -3566,6 +3675,12 @@ msgstr "Размеры"msgid "Direct"msgstr "Прямой"+msgid "Direction"+msgstr "Направление"++msgid "Directions"+msgstr "Направления"+msgid "Disabled"msgstr "Отключено"@@ -3584,6 +3699,10 @@ msgstr "Дни скидки"msgid "Discount Days after {selectedCalculationMethod}"msgstr "Дни скидки после {selectedCalculationMethod}"+#. placeholder {0}: r.invoiceId+msgid "Discount for {0}"+msgstr "Скидка для {0}"+msgid "Discount Percent"msgstr "Процент скидки"@@ -3717,6 +3836,9 @@ msgstr "Перетащите, чтобы изменить размер диагmsgid "Drag to zoom"msgstr "Перетащите для масштабирования"+msgid "Drawing"+msgstr "Снятие"+msgid "Drawing Number"msgstr "Номер чертежа"@@ -3952,6 +4074,9 @@ msgstr "Редактировать материальное вещество"msgid "Edit Material Type"msgstr "Редактировать тип материала"+msgid "Edit Memo"+msgstr "Редактировать Memo"+msgid "Edit Non Conformance Type"msgstr "Редактировать тип несоответствия"@@ -3961,6 +4086,9 @@ msgstr "Редактировать деталь"msgid "Edit Partner"msgstr "Редактировать партнера"+msgid "Edit Payment"+msgstr "Редактировать платеж"+msgid "Edit Payment Term"msgstr "Редактировать условие платежа"@@ -4442,12 +4570,18 @@ msgstr "Ожидаемое получение"msgid "Expected Receipt Date"msgstr "Ожидаемая дата получения"+msgid "Expense account for customer balances written off as uncollectable on AR settlement"+msgstr "Счет расходов для остатков клиентов, списанных как невзыскиваемые при расчете по дебиторской задолженности"+msgid "Expense account for deferred tax adjustments on depreciation"msgstr "Счет расходов для корректировок отложенного налога на амортизацию"msgid "Expense account for equipment and facility maintenance"msgstr "Счет расходов на содержание оборудования и объектов"+msgid "Expense account for FX losses when a payment settles a foreign-currency invoice at a less favorable rate"+msgstr "Счет расходов для убытков от валютных операций, когда платеж погашает счет в иностранной валюте по менее выгодному курсу"+msgid "Expense account for non-inventory purchases (services, supplies)"msgstr "Счет расходов на закупки не из запасов (услуги, расходники)"@@ -5028,9 +5162,15 @@ msgstr "Пятница"msgid "From {0}"msgstr "С {0}"+msgid "From customer"+msgstr "От клиента"+msgid "From Location"msgstr "Из местоположения"+msgid "from on-account credit"+msgstr "со счета авансовых платежей"+msgid "From Storage Unit"msgstr "Из хранилища"@@ -5040,6 +5180,9 @@ msgstr "Местоположение исполнения"msgid "Fully trained for"msgstr "Полностью обучен для"+msgid "FX G/L"+msgstr "Прибыль/убыток по курсу"+msgid "Gains and Losses"msgstr "Прибыли и Убытки (по умолчанию)"@@ -5127,6 +5270,9 @@ msgstr "Навигация в Carbon"msgid "Getting set up"msgstr "Начало работы"+msgid "GL"+msgstr "ГЛ"+msgid "GL Account"msgstr "Счет ГЛ"@@ -5241,6 +5387,12 @@ msgstr "Счет GL расходов для покупок, не входящиmsgid "GL liability account credited for sales tax collected from customers."msgstr "Счет GL обязательств, кредитуемый по налогу с продаж, собранному у клиентов."+msgid "GL tie-out"+msgstr "Сверка ГЛ"++msgid "GL Tie-Out"+msgstr "Сверка ГЛ"+msgid "Go live right the first time — with our team alongside you"msgstr "Запустите систему с первой попытки — с нашей командой рядом с вами"@@ -5773,6 +5925,9 @@ msgstr "Внутренний справочник о том, где каждыйmsgid "inv"msgstr "инв"+msgid "Inv Rate"+msgstr "Курс счета"+msgid "Invalid Invite"msgstr "Недействительное приглашение"@@ -5884,6 +6039,12 @@ msgstr "Статусы счетов"msgid "Invoices"msgstr "Счета"+msgid "Invoices this memo has been applied to. Click a row to open the document."+msgstr "Счета, к которым применена эта справка. Нажмите на строку, чтобы открыть документ."++msgid "Invoicing"+msgstr "Выставление счетов"+msgid "is"msgstr "это"@@ -6451,6 +6612,13 @@ msgstr "Товары типа \"Make\" не могут быть выставлеmsgid "Make Method Version"msgstr "Версия метода производства"+msgid "Make Payment"+msgstr "Произвести платеж"++#. placeholder {0}: selectedInvoices.length+msgid "Make Payment · {0} invoices"+msgstr "Произвести платеж · {0} счетов"+#. placeholder {0}: selectedRevision.revisionmsgid "Make revision {0} default?"msgstr "Сделать редакцию {0} по умолчанию?"@@ -6693,6 +6861,15 @@ msgstr "Периодичность встреч"msgid "Members"msgstr "Участники"+msgid "Memo"+msgstr "Памятка"++msgid "Memo Date"+msgstr "Дата меморандума"++msgid "Memo ID"+msgstr "ID Памятки"+msgid "MES"msgstr "MES"@@ -6953,6 +7130,9 @@ msgstr "Новый расходный материал"msgid "New Contractor"msgstr "Новый подрядчик"+msgid "New Credit / Debit Memo"+msgstr "Новый кредит-нота / дебет-нота"+msgid "New Custom Field"msgstr "Новое пользовательское поле"@@ -7061,6 +7241,9 @@ msgstr "Новая деталь"msgid "New Password"msgstr "Новый пароль"+msgid "New Payment"+msgstr "Новый платеж"+msgid "New Payment Term"msgstr "Новый платежный срок"@@ -7252,6 +7435,9 @@ msgstr "Нет активных предложений"msgid "No addresses found"msgstr "Адреса не найдены"+msgid "No applications. Payment will be on-account."+msgstr "Нет приложений. Платеж будет на счет."+#. placeholder {0}: auditConfig.retentionDaysmsgid "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."msgstr "Нет архивированных логов. Логи старше {0} дней будут автоматически архивированы и доступны для скачивания здесь."@@ -7370,6 +7556,9 @@ msgstr "Нет новых уведомлений"msgid "No notes"msgstr "Нет заметок"+msgid "No open invoices"+msgstr "Нет открытых счетов"+msgid "No operations require picking at this location"msgstr "На этом месте нет операций, требующих комплектации"@@ -7397,6 +7586,12 @@ msgstr "Родительские источники еще не записаныmsgid "No part ID"msgstr "Нет ID детали"+msgid "No payables"+msgstr "Нет кредиторской задолженности"++msgid "No payments yet."+msgstr "Платежей пока нет."+msgid "No planning data"msgstr "Нет данных планирования"@@ -7421,6 +7616,9 @@ msgstr "Причина отсутствия предложения"msgid "No Quote Reasons"msgstr "Причины отсутствия предложения"+msgid "No receivables"+msgstr "Нет дебиторской задолженности"+msgid "No remaining entities to inspect."msgstr "Нет оставшихся объектов для проверки."@@ -7598,6 +7796,9 @@ msgstr "На заказе продажи"msgid "On Storage Unit"msgstr "На складском отделении"+msgid "On-account credit available"+msgstr "Доступный кредит на счете"+msgid "On-hand counts"msgstr "Наличные остатки"@@ -7818,6 +8019,12 @@ msgstr "Заказы отправлены"msgid "Origin"msgstr "Источник"+msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"+msgstr "Счет прочих доходов для прибыли от валютных операций при расчете по иностранной валюте по более выгодному курсу"++msgid "Other Income account for vendor balances cleared without full payment on AP settlement"+msgstr "Счет прочих доходов для остатков поставщиков, погашенных без полной оплаты при расчете по кредиторской задолженности"+msgid "Other Type"msgstr "Другой тип"@@ -7839,6 +8046,9 @@ msgstr "Выпуск никогда не превышает срок дейстmsgid "Outside operation"msgstr "Отклонение косвенных затрат"+msgid "Over-applied by"+msgstr "Переприменено на"+msgid "Overdue"msgstr "Просрочено"@@ -7975,6 +8185,9 @@ msgstr "Детали и товары"msgid "Parts, materials, and how you classify them."msgstr "Детали, материалы и способы их классификации."+msgid "Party Type"+msgstr "Тип контрагента"+msgid "Pass"msgstr "Пройти"@@ -7984,17 +8197,29 @@ msgstr "Пройдено · повторно открыть"msgid "Path"msgstr "Путь"+msgid "Pay Rate"+msgstr "Курс платежа"+msgid "Payables"msgstr "Кредиторская задолженность (по умолчанию)"msgid "Payables (default)"msgstr "условие платежа"+msgid "Payables aging"+msgstr "Старение кредиторской задолженности"+msgid "Payment"msgstr "Платеж"-msgid "Payment Method"-msgstr "Способ оплаты"+msgid "Payment Applications"+msgstr "Применение платежей"++msgid "Payment Date"+msgstr "Дата платежа"++msgid "Payment ID"+msgstr "ID платежа"msgid "payment term"msgstr "условия платежа"@@ -8011,6 +8236,12 @@ msgstr "Условия платежа"msgid "Payment terms like Net 30 or due on receipt"msgstr "Условия оплаты, такие как Net 30 или оплата при получении"+msgid "Payments"+msgstr "Платежи"++msgid "Payments and credits applied to this invoice. Click a row to open the source document."+msgstr "Платежи и кредиты, применённые к этому счёту. Нажмите на строку, чтобы открыть исходный документ."+msgid "PDF"msgstr "PDF"@@ -8672,6 +8903,9 @@ msgstr "Закупки и автоматическое планирование"msgid "Purchasing Contact"msgstr "Контакт по закупкам"+msgid "Purchasing Invoices"+msgstr "Счета на покупку"+msgid "Purchasing Unit of Measure"msgstr "Единица измерения закупки"@@ -8866,9 +9100,18 @@ msgstr "Видимость запасов и производства в реаmsgid "Real-time questions during hypercare"msgstr "Вопросы в реальном времени во время гиперухода"+msgid "Realized Exchange Gain"+msgstr "Реализованный валютный доход"++msgid "Realized Exchange Loss"+msgstr "Реализованный убыток от обмена валют"+msgid "Reason"msgstr "Причина"+msgid "Reason Account"+msgstr "Счет причины"+msgid "Reason for declining (Optional)"msgstr "Причина отказа (Необязательно)"@@ -8911,6 +9154,9 @@ msgstr "Дебиторская задолженность (по умолчаниmsgid "Receivables (default)"msgstr "Сверка заказа на покупку с полученным и выставленным счетом — неявно в Carbon через количество строк и остаток GR/IR."+msgid "Receivables aging"+msgstr "Старение дебиторской задолженности"+msgid "Receive"msgstr "Получить"@@ -8921,6 +9167,13 @@ msgstr "Получить {0} в инвентарь"msgid "Receive against a PO and update inventory"msgstr "Получить товар по заказу и обновить инвентарь"+msgid "Receive Payment"+msgstr "Получить платеж"++#. placeholder {0}: selectedInvoices.length+msgid "Receive Payment · {0} invoices"+msgstr "Получить платеж · {0} счетов"+msgid "Receive to Inventory"msgstr "Получить в инвентарь"@@ -8944,6 +9197,9 @@ msgstr "Место получения"msgid "Recent"msgstr "Недавние"+msgid "Recent payments"+msgstr "Недавние платежи"+msgid "Recently Created"msgstr "Недавно созданные"@@ -8953,6 +9209,12 @@ msgstr "Период восстановления"msgid "Record"msgstr "Записать"+msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."+msgstr "Запишите кредит-ноту или дебет-ноту для клиента или поставщика. Применение к конкретным счетам добавляется после создания ноты."++msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."+msgstr "Записывайте денежные средства, полученные от клиента (Поступление) или выплаченные поставщику (Выплата). Применение к конкретным счетам добавляется после создания платежа."+msgid "Record deleted"msgstr "Запись удалена"@@ -9037,6 +9299,9 @@ msgstr "Выпустить задание"msgid "Released"msgstr "Выпущено"+msgid "Remaining"+msgstr "Остаток"+msgid "Remaining after split stays on the original row."msgstr "Остаток после разделения остается в исходной строке."@@ -9583,6 +9848,9 @@ msgstr "Сохранить и закрыть"msgid "Save and Overwrite"msgstr "Сохранить и перезаписать"+msgid "Save applications"+msgstr "Сохранить применения"+msgid "Save contacts"msgstr "Сохранить контакты"@@ -9824,6 +10092,15 @@ msgstr "Выбрать датчик"msgid "Select groups or individuals"msgstr "Выберите группы или отдельных лиц"+msgid "Select invoice"+msgstr "Выберите счет"++msgid "Select invoices from a single counterparty"+msgstr "Выберите счета-фактуры от одного контрагента"++msgid "Select invoices in a single currency"+msgstr "Выберите счета в одной валюте"+msgid "Select Item Type"msgstr "Выберите тип элемента"@@ -9860,6 +10137,9 @@ msgstr "Выберите поверхности"msgid "Select the groups that should complete this training"msgstr "Выберите группы, которые должны пройти это обучение"+msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."+msgstr "Выберите счета, которые погашает этот платеж. Скидка и списание указаны в валюте счета."+msgid "Select value"msgstr "Выберите значение"@@ -10575,6 +10855,9 @@ msgstr "Отклонение по субподряду"msgid "Subcontracting Variance (default)"msgstr "Отклонение по субподряду (по умолчанию)"+msgid "Subledger"+msgstr "Вспомогательная книга"+msgid "Submit anonymously"msgstr "Отправить анонимно"@@ -11597,6 +11880,9 @@ msgstr "Нет активных предложений поставщиков дmsgid "There are outside operations associated with this job that have no suppliers. Please assign a supplier to each outside operation before releasing it."msgstr "В этой работе есть внешние операции, которым не назначены поставщики. Пожалуйста, назначьте поставщика для каждой внешней операции перед выпуском."+msgid "There's nothing outstanding to apply these credits to."+msgstr "Нечего применять эти кредиты."+msgid "These custom fields will only be available for entities with the same tags"msgstr "Эти пользовательские поля будут доступны только для сущностей с одинаковыми тегами"@@ -11612,6 +11898,9 @@ msgstr "Эти задания имеют операции, назначенныmsgid "This completes the Discovery step."msgstr "Это завершает этап Discovery."+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."+msgstr "Эта контрагент не имеет задолженности — платеж будет записан на счет."+msgid "This information will be used on document headers"msgstr "Эта информация будет использована в заголовках документов"@@ -11720,6 +12009,9 @@ msgstr "Четверг"msgid "Tie shipments through to an invoice with no re-keying"msgstr "Связать отправки с счетом без повторного ввода данных"+msgid "Tie-Out"+msgstr "Сверка"+msgid "Tightened"msgstr "Ужесточенный"@@ -11756,6 +12048,9 @@ msgstr "К отправке и получению"msgid "To Storage Unit"msgstr "На хранилище"+msgid "To supplier"+msgstr "Поставщику"+msgid "Today"msgstr "Сегодня"@@ -11825,6 +12120,9 @@ msgstr "Классификация верхнего уровня (активы/msgid "Total"msgstr "Итого"+msgid "Total Amount"+msgstr "Общая сумма"+msgid "Total capitalized cost of the asset (purchase price plus freight, install, and other costs that become part of book value)."msgstr "Общая капитализированная стоимость актива (цена покупки плюс доставка, установка и другие затраты, которые становятся частью чистой балансовой стоимости)."@@ -11852,6 +12150,9 @@ msgstr "Общее требуемое количество по всем актmsgid "Total:"msgstr "Итого:"+msgid "Totals"+msgstr "Итоги"+msgid "Traceability"msgstr "Отслеживаемость"@@ -12008,6 +12309,12 @@ msgstr "Типы"msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."msgstr "Необработанные сущности останутся в статусе \"На удержании\", чтобы вы могли продолжить проверку и принять решение позже. Результаты проверенных образцов сохраняются."+msgid "Unapplied"+msgstr "Неприменённые"++msgid "Unapplied:"+msgstr "Неприменено:"+msgid "Unapproved Supplier"msgstr "Неодобренный поставщик"@@ -12351,6 +12658,9 @@ msgstr "Номер регистрации налога на добавленнуmsgid "Values"msgstr "Значения"+msgid "Variance"+msgstr "Расхождение"+msgid "Variance between actual and standard BOM component consumption"msgstr "Расхождение между фактическим и стандартным потреблением компонентов спецификации"@@ -12372,6 +12682,9 @@ msgstr "Расхождение в затратах на внешнюю обраmsgid "VAT Number"msgstr "Номер НДС"+msgid "Vendor Write-Off Income"+msgstr "Доход от списания задолженности перед поставщиком"+msgid "Verification Error"msgstr "Ошибка проверки"@@ -12453,6 +12766,9 @@ msgstr "Просмотр списков"msgid "View maintenance dispatch"msgstr "Просмотр заказа на техническое обслуживание"+msgid "View Memo"+msgstr "Просмотр Memo"+msgid "View missing values"msgstr "Просмотреть отсутствующие значения"@@ -12474,6 +12790,9 @@ msgstr "Просмотреть открытые предложения"msgid "View Open RFQs"msgstr "Просмотреть открытые РФП"+msgid "View Payment"+msgstr "Просмотр платежа"+msgid "View permissions"msgstr "Права просмотра"@@ -13042,9 +13361,19 @@ msgstr "Машины с наихудшей производительностьmsgid "Write-Down Account"msgstr "Счет уменьшения стоимости"+msgid "Write-off"+msgstr "Списание"++msgid "Write-Off"+msgstr "Списание"+msgid "Write-Off Account"msgstr "Счет списания"+#. placeholder {0}: r.invoiceId+msgid "Write-off for {0}"+msgstr "Списание для {0}"+msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."msgstr "Снижение стоимости актива в течение его полезного использования — ежемесячный пакет, который вы создаете, проверяете как черновик, затем контируете."diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex c05ea566de..68c89d7c83 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -31,6 +31,10 @@ msgstr "\"Bunu satın almak için kimse işten çıkarılmadı.\" Yerleşik birmsgid "(excluded for this customer)"msgstr "(bu müşteri için hariç tutulmuş)"+#. placeholder {0}: ar.count+msgid "{0} customers with a balance"+msgstr "{0} müşteri bakiye ile"+#. placeholder {0}: rule.escalationDaysmsgid "{0} days"msgstr "{0} gün"@@ -48,6 +52,10 @@ msgstr "{0} sipariş"msgid "{0} Processes"msgstr "{0} Süreçler"+#. placeholder {0}: ap.count+msgid "{0} suppliers with a balance"+msgstr "{0} bakiyesi olan tedarikçi"+#. placeholder {0}: lotEntities.length - inspectedmsgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "{0} örneklenmemiş varlıklar Kullanılabilir'e bırakılacaktır. Örneklenen başarılılar Kullanılabilir ve örneklenen başarısızlar Reddedilmiş olarak kalır."@@ -60,6 +68,12 @@ msgstr "{0} başarıyla yüklendi"msgid "{0} values missing"msgstr "{0} değeri eksik"+msgid "{apOverduePct}% of payables"+msgstr "{apOverduePct}% borç"++msgid "{arOverduePct}% of receivables"+msgstr "{arOverduePct}% alacakların"+msgid "{chainLabel}. Consider pointing this part directly at the final successor."msgstr "{chainLabel}. Bu parçayı doğrudan son halefine yönlendirmeyi düşünün."@@ -743,6 +757,10 @@ msgstr "Bu satırda varlıkları/giderleri artıran veya yükümlülükleri/özkmsgid "Amount that increases liabilities/equity/revenue or decreases assets/expenses on this line."msgstr "Bu satırda yükümlülükleri/özkaynakları/gelirleri artıran veya varlıkları/giderleri azaltan tutar."+#. placeholder {0}: r.memoId+msgid "Amount to apply for {0}"+msgstr "{0} için uygulanacak tutar"+msgid "Amount Type"msgstr "Tutar Türü"@@ -806,6 +824,12 @@ msgstr "Yukarıda açıkça kapsamda listelenmemiş herhangi bir şey"msgid "AP Clerk"msgstr "AP Muhasebesi Görevlisi"+msgid "AP Outstanding"+msgstr "AP Ödenmemiş"++msgid "AP Overdue"+msgstr "AP Vadesi Geçmiş"+msgid "API and Webhooks"msgstr "API ve Webhook'lar"@@ -824,6 +848,19 @@ msgstr "API Anahtarları"msgid "API keys for programmatic access to your Carbon data."msgstr "Carbon verilerinize programatik erişim için API anahtarları."+msgid "Applied"+msgstr "Uygulandı"++#. placeholder {0}: r.invoiceId+msgid "Applied amount for {0}"+msgstr "{0} için uygulanan tutar"++msgid "Applied Date"+msgstr "Uygulama Tarihi"++msgid "Applied To"+msgstr "Uygulandı"+msgid "Applies to"msgstr "Uygulama"@@ -833,6 +870,12 @@ msgstr "Tümüne uygulanır"msgid "Applies to all work centers"msgstr "Tüm iş merkezlerine uygulanır"+msgid "Apply available credits"+msgstr "Mevcut kredileri uygula"++msgid "Apply credits"+msgstr "Kredileri uygula"+msgid "Apply payments and track aging"msgstr "Ödemeleri uygula ve yaşlandırmayı takip et"@@ -845,6 +888,12 @@ msgstr "Kuralları üste uygula"msgid "Apply To"msgstr "Uygulanacak Alan"+msgid "Apply to invoice"+msgstr "Faturaya uygula"++msgid "Apply to invoices"+msgstr "Faturaları uygula"+msgid "Approaching {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB cap."msgstr "Yaklaşan {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB sınırı."@@ -875,6 +924,12 @@ msgstr "AQL (Z1.4 / ISO 2859-1)"msgid "AR Clerk"msgstr "AR Görevlisi"+msgid "AR Outstanding"+msgstr "AR Ödenmemiş"++msgid "AR Overdue"+msgstr "AR Vadesi Geçmiş"+msgid "Archive"msgstr "Arşiv"@@ -955,9 +1010,9 @@ msgstr "Bu işlemden {0}'ı silmek istediğinizden emin misiniz? Bu geri alınammsgid "Are you sure you want to delete {0}?"msgstr "{0} öğesini silmek istediğinizden emin misiniz?"+#. placeholder {0}: initialValues.memoId+#. placeholder {0}: initialValues.paymentId#. placeholder {0}: pickingList.pickingListId-#. placeholder {0}: routeData?.consumableSummary?.readableIdWithRevision-#. placeholder {0}: routeData?.customer?.name!msgid "Are you sure you want to delete {0}? This cannot be undone."msgstr "Emin misiniz ki {0}'ı silmek istiyorsunuz? Bu geri alınamaz."@@ -1243,6 +1298,9 @@ msgstr "Emin misiniz?"msgid "As needed"msgstr "Gerektiğinde"+msgid "As of:"+msgstr "Şu tarih itibariyle:"+msgid "As the company owner, you can transfer ownership to another employee. This will give them full access to billing and administrative settings."msgstr "Şirket sahibi olarak, sahipliği başka bir çalışana devredebilirsiniz. Bu, onlara faturalandırma ve yönetici ayarlarına tam erişim sağlayacaktır."@@ -1371,6 +1429,9 @@ msgstr "Denetim Kayıtları"msgid "Authentication Error"msgstr "Kimlik Doğrulama Hatası"+msgid "Auto apply"+msgstr "Otomatik uygula"+msgid "Auto Release"msgstr "Otomatik Serbest Bırakma"@@ -1440,9 +1501,15 @@ msgstr "Geri Akış"msgid "Backups"msgstr "Yedeklemeler"+msgid "Balance"+msgstr "Bakiye"+msgid "Balance Sheet"msgstr "Bilanço"+msgid "Balanced"+msgstr "Dengeli"+msgid "Balloon"msgstr "Balon"@@ -1464,6 +1531,9 @@ msgstr "Banka — Dış ticaret (varsayılan)"msgid "Bank — Local Currency (default)"msgstr "Banka — Yerel para (varsayılan)"+msgid "Bank / Cash Account"+msgstr "Banka / Nakit Hesabı"+msgid "Bank account denominated in a foreign currency"msgstr "Yabancı para cinsinden ifade edilen banka hesabı."@@ -1643,6 +1713,12 @@ msgstr "by {byUser}"msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."msgstr "Davetiyeyi kabul ederek, <0>Hizmet Şartları</0> ve <1>Gizlilik Politikası</1>'na katılırsınız."+msgid "By Document Date"+msgstr "Belge Tarihine Göre"++msgid "By Due Date"+msgstr "Vade Tarihine Göre"+msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"msgstr "Oturum açarak <0>Hizmet Şartları</0> ve <1>Gizlilik Politikası</1>'na katılıyorsunuz."@@ -1931,6 +2007,9 @@ msgstr "Aramayı temizle"msgid "Clear search query"msgstr "Arama sorgusunu temizle"+msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."+msgstr "Bu faturayı tarafın deftere nakledilmiş kredileri ve nakit ile kapatın. Krediler doğrudan uygulanır — deftere nakil gerekmez."+msgid "Clearing account between goods receipt and supplier invoice; balances when both have posted."msgstr "Mal alımı ve tedarikçi faturası arasındaki mahsup hesabı; her ikisi de deftere geçirildiğinde bakiye alınır."@@ -1977,6 +2056,9 @@ msgstr "Bulut veya kendi barındırılan ortamınız."msgid "Code"msgstr "Kod"+msgid "Collapse"+msgstr "Daralt"+msgid "Collapse all"msgstr "Tümünü daralt"@@ -2552,6 +2634,12 @@ msgstr "Belgeler yüklenemedi"msgid "Count"msgstr "Adet"+msgid "Counterparties"+msgstr "Muhasebeleştirilecek Taraflar"++msgid "Counterparty"+msgstr "Karşı Taraf"+msgid "Country"msgstr "Ülke"@@ -2582,6 +2670,9 @@ msgstr "Yeni bir teklif kimliği ile teklif oluştur"msgid "Create Account"msgstr "Hesap Oluştur"+msgid "Create adjusting entry"+msgstr "Düzeltme girişi oluştur"+msgid "Create an account"msgstr "Hesap oluştur"@@ -2755,12 +2846,21 @@ msgstr "Parça oluşturuluyor..."msgid "Credit"msgstr "Kredi"+msgid "Credit / Debit Memos"+msgstr "Kredi / Borç Muhasebe Notları"+msgid "Credit Account"msgstr "Kredi Hesabı"msgid "Credit account when labor/machine time is absorbed into WIP"msgstr "İşçilik/makine zamanı WIP'de emildiğinde kredi hesabı"+msgid "Credits & Debits"+msgstr "Krediler ve Borçlar"++msgid "Credits applied"+msgstr "Uygulanan krediler"+msgid "Critical"msgstr "Kritik"@@ -2935,6 +3035,9 @@ msgstr "müşteri türleri"msgid "Customer Types"msgstr "Müşteri Tipleri"+msgid "Customer Write-Off (Bad Debt)"+msgstr "Müşteri Silme (Şüpheli Alacak)"+msgid "customers"msgstr "müşteriler"@@ -3314,12 +3417,18 @@ msgstr "Malzeme Şeklini Sil"msgid "Delete Material Type"msgstr "Malzeme Türünü Sil"+msgid "Delete Memo"+msgstr "Notu Sil"+msgid "Delete Part"msgstr "Parçayı Sil"msgid "Delete Partner"msgstr "Partneri Sil"+msgid "Delete Payment"+msgstr "Ödemeyi Sil"+msgid "Delete Payment Term"msgstr "Ödeme Şartını Sil"@@ -3566,6 +3675,12 @@ msgstr "Boyutlar"msgid "Direct"msgstr "Doğrudan"+msgid "Direction"+msgstr "Yön"++msgid "Directions"+msgstr "Yönler"+msgid "Disabled"msgstr "Devre Dışı"@@ -3584,6 +3699,10 @@ msgstr "İndirim Günleri"msgid "Discount Days after {selectedCalculationMethod}"msgstr "{selectedCalculationMethod} sonrası İskonto Günleri"+#. placeholder {0}: r.invoiceId+msgid "Discount for {0}"+msgstr "{0} için indirim"+msgid "Discount Percent"msgstr "İskonto Yüzdesi"@@ -3717,6 +3836,9 @@ msgstr "Şemayı ve özellikleri yeniden boyutlandırmak için sürükleyin"msgid "Drag to zoom"msgstr "Yakınlaştırmak için sürükleyin"+msgid "Drawing"+msgstr "Çekiliyor"+msgid "Drawing Number"msgstr "Çizim Numarası"@@ -3952,6 +4074,9 @@ msgstr "Malzeme Maddesini Düzenle"msgid "Edit Material Type"msgstr "Malzeme Tipini Düzenle"+msgid "Edit Memo"+msgstr "Memo Düzenle"+msgid "Edit Non Conformance Type"msgstr "Uygunsuzluk Türünü Düzenle"@@ -3961,6 +4086,9 @@ msgstr "Parç Düzenle"msgid "Edit Partner"msgstr "Partneri Düzenle"+msgid "Edit Payment"+msgstr "Ödemeyi Düzenle"+msgid "Edit Payment Term"msgstr "Ödeme Şartını Düzenle"@@ -4442,12 +4570,18 @@ msgstr "Beklenen Teslim Alma"msgid "Expected Receipt Date"msgstr "Beklenen Teslim Alma Tarihi"+msgid "Expense account for customer balances written off as uncollectable on AR settlement"+msgstr "Müşteri bakiyelerinin AR kapatılması sırasında tahsil edilemez olarak silinen gider hesabı"+msgid "Expense account for deferred tax adjustments on depreciation"msgstr "Amortisman üzerindeki ertelenmiş vergi ayarlamaları için gider hesabı"msgid "Expense account for equipment and facility maintenance"msgstr "Ekipman ve tesis bakımı için gider hesabı"+msgid "Expense account for FX losses when a payment settles a foreign-currency invoice at a less favorable rate"+msgstr "Ödeme, yabancı para biriminde bir faturayı daha az uygun bir oranda kapatırken FX kayıpları için gider hesabı"+msgid "Expense account for non-inventory purchases (services, supplies)"msgstr "Envanter dışı satın almalar (hizmetler, malzemeler) için gider hesabı"@@ -5028,9 +5162,15 @@ msgstr "Cuma"msgid "From {0}"msgstr "{0} tarihinden itibaren"+msgid "From customer"+msgstr "Müşteriden"+msgid "From Location"msgstr "Kaynak Konum"+msgid "from on-account credit"+msgstr "hesap kredisinden"+msgid "From Storage Unit"msgstr "Kaynak Depo Birimi"@@ -5040,6 +5180,9 @@ msgstr "Yerine Getirme Konumu"msgid "Fully trained for"msgstr "Tamamen eğitilmiş"+msgid "FX G/L"+msgstr "FX K/Z"+msgid "Gains and Losses"msgstr "Kazançlar ve Zararlar (varsayılan)"@@ -5127,6 +5270,9 @@ msgstr "Carbon'da Gezinme"msgid "Getting set up"msgstr "Kurulum yapılıyor"+msgid "GL"+msgstr "GL"+msgid "GL Account"msgstr "BÜTÇE HESABI"@@ -5241,6 +5387,12 @@ msgstr "Stok dışı satın almalar (malzemeleri, hizmetleri) için GL gider hesmsgid "GL liability account credited for sales tax collected from customers."msgstr "Müşterilerden toplanan satış vergisi için alacaklandırılan GL yükümlülük hesabı."+msgid "GL tie-out"+msgstr "GL mutabakatı"++msgid "GL Tie-Out"+msgstr "GL Mutabakatı"+msgid "Go live right the first time — with our team alongside you"msgstr "İlk seferde canlı yayına geç — ekibimiz yanınızda"@@ -5773,6 +5925,9 @@ msgstr "Her aracın nerede daha güçlü olduğu için dahili referans. Beklentimsgid "inv"msgstr "stok"+msgid "Inv Rate"+msgstr "Fatura Oranı"+msgid "Invalid Invite"msgstr "Geçersiz Davetiye"@@ -5884,6 +6039,12 @@ msgstr "Fatura Durumları"msgid "Invoices"msgstr "Faturalar"+msgid "Invoices this memo has been applied to. Click a row to open the document."+msgstr "Bu muhasebe belgesinin uygulandığı faturalar. Belgeyi açmak için bir satıra tıklayın."++msgid "Invoicing"+msgstr "Faturalama"+msgid "is"msgstr "eşittir"@@ -6451,6 +6612,13 @@ msgstr "Üretim ürünleri doğrudan faturalandırılamaz. Devam etmek için yömsgid "Make Method Version"msgstr "Üretim Yöntemi Sürümü"+msgid "Make Payment"+msgstr "Ödeme Yap"++#. placeholder {0}: selectedInvoices.length+msgid "Make Payment · {0} invoices"+msgstr "Ödeme Yap · {0} fatura"+#. placeholder {0}: selectedRevision.revisionmsgid "Make revision {0} default?"msgstr "Revizyonu {0} varsayılan yapmak mı?"@@ -6693,6 +6861,15 @@ msgstr "Toplantı sıklığı"msgid "Members"msgstr "Üyeler"+msgid "Memo"+msgstr "Not"++msgid "Memo Date"+msgstr "Muhasebe Tarihi"++msgid "Memo ID"+msgstr "Muhasebe Belgesi Kimliği"+msgid "MES"msgstr "MES"@@ -6953,6 +7130,9 @@ msgstr "Yeni Sarf Malzemesi"msgid "New Contractor"msgstr "Yeni Yüklenici"+msgid "New Credit / Debit Memo"+msgstr "Yeni Kredi / Borç Notu"+msgid "New Custom Field"msgstr "Yeni Özel Alan"@@ -7061,6 +7241,9 @@ msgstr "Yeni Ürün"msgid "New Password"msgstr "Yeni Şifre"+msgid "New Payment"+msgstr "Yeni Ödeme"+msgid "New Payment Term"msgstr "Yeni Ödeme Şartı"@@ -7252,6 +7435,9 @@ msgstr "Aktif Teklif Yok"msgid "No addresses found"msgstr "Adres bulunamadı"+msgid "No applications. Payment will be on-account."+msgstr "Başvuru yok. Ödeme hesap üzerinden yapılacak."+#. placeholder {0}: auditConfig.retentionDaysmsgid "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."msgstr "Henüz arşivlenmiş günlük yok. {0} günden eski günlükler otomatik olarak arşivlenecek ve buradan indirilmeye hazır olacak."@@ -7370,6 +7556,9 @@ msgstr "Yeni bildirim yok"msgid "No notes"msgstr "Notlar yok"+msgid "No open invoices"+msgstr "Açık fatura yok"+msgid "No operations require picking at this location"msgstr "Bu konumda toplama gerektiren işlem yok"@@ -7397,6 +7586,12 @@ msgstr "Henüz üst kaynaklar kaydedilmedi. Atıfı yenilemek için planlama saymsgid "No part ID"msgstr "Parça kimliği yok"+msgid "No payables"+msgstr "Ödeme yükümlülüğü yok"++msgid "No payments yet."+msgstr "Henüz ödeme yok."+msgid "No planning data"msgstr "Planlama verisi yok"@@ -7421,6 +7616,9 @@ msgstr "Teklif Nedeni Yok"msgid "No Quote Reasons"msgstr "Teklif Nedeni Yok"+msgid "No receivables"+msgstr "Alacak yok"+msgid "No remaining entities to inspect."msgstr "İncelenecek kalan varlık yok."@@ -7598,6 +7796,9 @@ msgstr "Satış Siparişi'nde"msgid "On Storage Unit"msgstr "Depolizdeki"+msgid "On-account credit available"+msgstr "Hesapta mevcut kredi"+msgid "On-hand counts"msgstr "Eldeki stok sayıları"@@ -7818,6 +8019,12 @@ msgstr "Siparişler gönderildi"msgid "Origin"msgstr "Kaynak"+msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"+msgstr "Bir ödeme yabancı para birimindeki bir faturayı daha uygun bir oranda kapatırken FX kazançları için Diğer Gelir hesabı"++msgid "Other Income account for vendor balances cleared without full payment on AP settlement"+msgstr "Satıcı bakiyelerinin AP kapatılması sırasında tam ödeme yapılmadan temizlenmesi için Diğer Gelir hesabı"+msgid "Other Type"msgstr "Diğer Tür"@@ -7839,6 +8046,9 @@ msgstr "Çıktı, ham malzemelerinin ömrünü asla aşmaz. Hiçbir girdinin sonmsgid "Outside operation"msgstr "Genel Gider Sapması"+msgid "Over-applied by"+msgstr "Fazla uygulandı"+msgid "Overdue"msgstr "Geçmiş"@@ -7975,6 +8185,9 @@ msgstr "Parçalar ve ürünler"msgid "Parts, materials, and how you classify them."msgstr "Parçalar, malzemeler ve bunları nasıl sınıflandırdığınız."+msgid "Party Type"+msgstr "Taraf Türü"+msgid "Pass"msgstr "Geçerli"@@ -7984,17 +8197,29 @@ msgstr "Geçti · yeniden aç"msgid "Path"msgstr "Yol"+msgid "Pay Rate"+msgstr "Ödeme Oranı"+msgid "Payables"msgstr "Ödenecek Hesaplar (varsayılan)"msgid "Payables (default)"msgstr "ödeme terimi"+msgid "Payables aging"+msgstr "Ödenecek hesaplar yaşlandırması"+msgid "Payment"msgstr "Ödeme"-msgid "Payment Method"-msgstr "Ödeme Yöntemi"+msgid "Payment Applications"+msgstr "Ödeme Uygulamaları"++msgid "Payment Date"+msgstr "Ödeme Tarihi"++msgid "Payment ID"+msgstr "Ödeme Kimliği"msgid "payment term"msgstr "ödeme şartları"@@ -8011,6 +8236,12 @@ msgstr "Ödeme Koşulları"msgid "Payment terms like Net 30 or due on receipt"msgstr "Net 30 gibi ödeme koşulları veya alındığında ödeme"+msgid "Payments"+msgstr "Ödemeler"++msgid "Payments and credits applied to this invoice. Click a row to open the source document."+msgstr "Bu faturaya uygulanan ödemeler ve krediler. Kaynak belgeyi açmak için bir satıra tıklayın."+msgid "PDF"msgstr "PDF"@@ -8672,6 +8903,9 @@ msgstr "Satın alma ve otomatik planlama"msgid "Purchasing Contact"msgstr "Satın Alma İletişim Kişisi"+msgid "Purchasing Invoices"+msgstr "Satın Alma Faturaları"+msgid "Purchasing Unit of Measure"msgstr "Satın Alma Birimi"@@ -8866,9 +9100,18 @@ msgstr "Gerçek zamanlı envanter ve atölye tabanı görünürlüğü"msgid "Real-time questions during hypercare"msgstr "Hipercare sırasında gerçek zamanlı sorular"+msgid "Realized Exchange Gain"+msgstr "Gerçekleşen Döviz Kazancı"++msgid "Realized Exchange Loss"+msgstr "Gerçekleşen Döviz Kaybı"+msgid "Reason"msgstr "Neden"+msgid "Reason Account"+msgstr "Neden Hesabı"+msgid "Reason for declining (Optional)"msgstr "Reddetme nedeni (İsteğe bağlı)"@@ -8911,6 +9154,9 @@ msgstr "Alacak Hesapları (varsayılan)"msgid "Receivables (default)"msgstr "Bir satın alma siparişini alınan ve faturalandırılan tutarla uzlaştırma — Carbon'da kapalı, satır miktarları ve GR/IR bakiyesi aracılığıyla."+msgid "Receivables aging"+msgstr "Alacaklar yaşlandırması"+msgid "Receive"msgstr "Teslim Al"@@ -8921,6 +9167,13 @@ msgstr "{0}'yi Envantere Al"msgid "Receive against a PO and update inventory"msgstr "PO'ya karşı teslim alın ve envanteri güncelleyin"+msgid "Receive Payment"+msgstr "Ödeme Al"++#. placeholder {0}: selectedInvoices.length+msgid "Receive Payment · {0} invoices"+msgstr "Ödeme Al · {0} fatura"+msgid "Receive to Inventory"msgstr "Envantere Al"@@ -8944,6 +9197,9 @@ msgstr "Teslim Alma Yeri"msgid "Recent"msgstr "Son Aramalar"+msgid "Recent payments"+msgstr "Son ödemeler"+msgid "Recently Created"msgstr "Son Oluşturulanlar"@@ -8953,6 +9209,12 @@ msgstr "Geri Kazanım Süresi"msgid "Record"msgstr "Kayıt"+msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."+msgstr "Bir müşteri veya tedarikçiye karşı kredi veya borç notu kaydedin. Belirli faturaların uygulamaları, not oluşturulduktan sonra eklenir."++msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."+msgstr "Müşteriden alınan nakit (Makbuz) veya tedarikçiye ödenen nakit (Ödeme) kaydedin. Belirli faturalara yapılan uygulamalar ödeme oluşturulduktan sonra eklenir."+msgid "Record deleted"msgstr "Kayıt silindi"@@ -9037,6 +9299,9 @@ msgstr "İşi Yayınla"msgid "Released"msgstr "Yayınlandı"+msgid "Remaining"+msgstr "Kalan"+msgid "Remaining after split stays on the original row."msgstr "Bölme sonrası kalan orijinal satırda kalır."@@ -9583,6 +9848,9 @@ msgstr "Kaydet ve Kapat"msgid "Save and Overwrite"msgstr "Kaydet ve Üzerine Yaz"+msgid "Save applications"+msgstr "Uygulamaları kaydet"+msgid "Save contacts"msgstr "Kişileri kaydet"@@ -9824,6 +10092,15 @@ msgstr "Kalıbrasyon Cihazı Seç"msgid "Select groups or individuals"msgstr "Grupları veya bireyleri seçin"+msgid "Select invoice"+msgstr "Faturayı seçin"++msgid "Select invoices from a single counterparty"+msgstr "Tek bir muhasebe karşılığından faturaları seçin"++msgid "Select invoices in a single currency"+msgstr "Tek bir para biriminde faturaları seçin"+msgid "Select Item Type"msgstr "Ürün Türü Seçin"@@ -9860,6 +10137,9 @@ msgstr "Yüzeyleri seç"msgid "Select the groups that should complete this training"msgstr "Bu eğitimi tamamlaması gereken grupları seçin"+msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."+msgstr "Bu ödemenin kapatacağı faturaları seçin. İndirim ve silme işlemi fatura para birimindedir."+msgid "Select value"msgstr "Değer seçin"@@ -10575,6 +10855,9 @@ msgstr "Taşeğremenin Farkı"msgid "Subcontracting Variance (default)"msgstr "Taşeğremenin Farkı (varsayılan)"+msgid "Subledger"+msgstr "Yardımcı Defter"+msgid "Submit anonymously"msgstr "Anonim olarak gönder"@@ -11597,6 +11880,9 @@ msgstr "Bu RFQ için karşılaştırılacak aktif tedarikçi teklifi bulunmamaktmsgid "There are outside operations associated with this job that have no suppliers. Please assign a supplier to each outside operation before releasing it."msgstr "Bu işle ilgili tedarikçisi olmayan dış operasyonlar bulunmaktadır. İşlemden önce her dış operasyona bir tedarikçi atayınız."+msgid "There's nothing outstanding to apply these credits to."+msgstr "Bu kredileri uygulanacak hiçbir ödenmemiş tutar yok."+msgid "These custom fields will only be available for entities with the same tags"msgstr "Bu özel alanlar yalnızca aynı etiketlere sahip varlıklar için kullanılabilir"@@ -11612,6 +11898,9 @@ msgstr "Bu işler bu iş merkezine atanmış işlemlere sahiptir:"msgid "This completes the Discovery step."msgstr "Bu, Keşif adımını tamamlar."+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."+msgstr "Bu muhasebe ortağının ödenmemiş bir borcu yok — ödeme hesap üzerinde kaydedilecektir."+msgid "This information will be used on document headers"msgstr "Bu bilgiler belge başlıklarında kullanılacaktır"@@ -11720,6 +12009,9 @@ msgstr "Perşembe"msgid "Tie shipments through to an invoice with no re-keying"msgstr "Sevkiyatları faturaya bağlayın, yeniden veri girişi olmadan"+msgid "Tie-Out"+msgstr "Mutabakat Kontrolü"+msgid "Tightened"msgstr "Sıkı"@@ -11756,6 +12048,9 @@ msgstr "Gönderilecek ve Alınacak"msgid "To Storage Unit"msgstr "Hedef Depo Birimi"+msgid "To supplier"+msgstr "Tedarikçiye"+msgid "Today"msgstr "Bugün"@@ -11825,6 +12120,9 @@ msgstr "Üst düzey sınıflandırma (varlık/yükümlülük/öz sermaye/gelir/gmsgid "Total"msgstr "Toplam"+msgid "Total Amount"+msgstr "Toplam Tutar"+msgid "Total capitalized cost of the asset (purchase price plus freight, install, and other costs that become part of book value)."msgstr "Varlığın toplam kapitalize edilen maliyeti (satın alma fiyatı artı navlun, kurulum ve defter değerinin parçası haline gelen diğer maliyetler)."@@ -11852,6 +12150,9 @@ msgstr "Bu konumdaki tüm aktif işler ve satış siparişleri genelinde gerekenmsgid "Total:"msgstr "Toplam:"+msgid "Totals"+msgstr "Toplamlar"+msgid "Traceability"msgstr "İzlenebilirlik"@@ -12008,6 +12309,12 @@ msgstr "Tipler"msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."msgstr "Örneklenmeyen varlıklar daha sonra incelemeye ve elden çıkarmaya devam edebilmeniz için Beklemede kalacaktır. Örneklenen sonuçlar korunur."+msgid "Unapplied"+msgstr "Uygulanmamış"++msgid "Unapplied:"+msgstr "Uygulanmamış:"+msgid "Unapproved Supplier"msgstr "Onaylanmamış Tedarikçi"@@ -12351,6 +12658,9 @@ msgstr "Katma değer vergisi kayıt numarası; AB faturalarında ters ücretlendmsgid "Values"msgstr "Değerler"+msgid "Variance"+msgstr "Varyans"+msgid "Variance between actual and standard BOM component consumption"msgstr "Gerçek ve standart BOM bileşen tüketimi arasındaki varyans"@@ -12372,6 +12682,9 @@ msgstr "Dış işleme maliyetlerinde varyans"msgid "VAT Number"msgstr "KDV Numarası"+msgid "Vendor Write-Off Income"+msgstr "Satıcı Silme Geliri"+msgid "Verification Error"msgstr "Doğrulama Hatası"@@ -12453,6 +12766,9 @@ msgstr "Listeleri Görüntüle"msgid "View maintenance dispatch"msgstr "Bakım sevkıyatını görüntüle"+msgid "View Memo"+msgstr "Memo Görüntüle"+msgid "View missing values"msgstr "Eksik değerleri görüntüle"@@ -12474,6 +12790,9 @@ msgstr "Açık Teklifleri Görüntüle"msgid "View Open RFQs"msgstr "Açık RFQ'ları Görüntüle"+msgid "View Payment"+msgstr "Ödemeyi Görüntüle"+msgid "View permissions"msgstr "Görüntüleme izinleri"@@ -13042,9 +13361,19 @@ msgstr "En kötü performans gösteren makineler"msgid "Write-Down Account"msgstr "Değer Düşüş Hesabı"+msgid "Write-off"+msgstr "Silme"++msgid "Write-Off"+msgstr "Silme"+msgid "Write-Off Account"msgstr "Silme Hesabı"+#. placeholder {0}: r.invoiceId+msgid "Write-off for {0}"+msgstr "{0} için silme"+msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."msgstr "Bir varlığın değerini faydalı kullanım süresi boyunca azaltma — oluşturduğunuz, taslak olarak gözden geçirdiğiniz ve deftere naklettiyiniz aylık batch."diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 40f24dede3..fcf0d0f4ed 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -31,6 +31,10 @@ msgstr "\"没有人因为购买它而被解雇。\"一个现任者的舒适因msgid "(excluded for this customer)"msgstr "(已为此客户排除)"+#. placeholder {0}: ar.count+msgid "{0} customers with a balance"+msgstr "{0}个有余额的客户"+#. placeholder {0}: rule.escalationDaysmsgid "{0} days"msgstr "{0} 天"@@ -48,6 +52,10 @@ msgstr "{0} 个订单"msgid "{0} Processes"msgstr "{0} 个流程"+#. placeholder {0}: ap.count+msgid "{0} suppliers with a balance"+msgstr "{0}个有余额的供应商"+#. placeholder {0}: lotEntities.length - inspectedmsgid "{0} un-sampled entities will be released to Available. Sampled passes stay Available and sampled failures stay Rejected."msgstr "{0} 个未采样的实体将被释放到可用状态。已采样的合格品保持可用状态,已采样的不合格品保持被拒绝状态。"@@ -60,6 +68,12 @@ msgstr "{0} 上传成功"msgid "{0} values missing"msgstr "{0} 个值缺失"+msgid "{apOverduePct}% of payables"+msgstr "{apOverduePct}% 的应付账款"++msgid "{arOverduePct}% of receivables"+msgstr "{arOverduePct}% 的应收账款"+msgid "{chainLabel}. Consider pointing this part directly at the final successor."msgstr "{chainLabel}。考虑将此零件直接指向最终后继产品。"@@ -743,6 +757,10 @@ msgstr "在该行增加资产/费用或减少负债/权益/收入的金额。"msgid "Amount that increases liabilities/equity/revenue or decreases assets/expenses on this line."msgstr "在该行增加负债/权益/收入或减少资产/费用的金额。"+#. placeholder {0}: r.memoId+msgid "Amount to apply for {0}"+msgstr "应用于 {0} 的金额"+msgid "Amount Type"msgstr "金额类型"@@ -806,6 +824,12 @@ msgstr "未在上述范围内明确列出的任何内容"msgid "AP Clerk"msgstr "应付账款文员"+msgid "AP Outstanding"+msgstr "应付账款未结"++msgid "AP Overdue"+msgstr "应付账款逾期"+msgid "API and Webhooks"msgstr "API 和 Webhooks"@@ -824,6 +848,19 @@ msgstr "API 密钥"msgid "API keys for programmatic access to your Carbon data."msgstr "用于以编程方式访问您的 Carbon 数据的 API 密钥。"+msgid "Applied"+msgstr "已应用"++#. placeholder {0}: r.invoiceId+msgid "Applied amount for {0}"+msgstr "已应用金额 {0}"++msgid "Applied Date"+msgstr "应用日期"++msgid "Applied To"+msgstr "应用于"+msgid "Applies to"msgstr "适用于"@@ -833,6 +870,12 @@ msgstr "适用于全部"msgid "Applies to all work centers"msgstr "适用于所有工作中心"+msgid "Apply available credits"+msgstr "应用可用额度"++msgid "Apply credits"+msgstr "应用额度"+msgid "Apply payments and track aging"msgstr "应用付款并跟踪账龄"@@ -845,6 +888,12 @@ msgstr "在顶部应用规则"msgid "Apply To"msgstr "应用于"+msgid "Apply to invoice"+msgstr "应用到发票"++msgid "Apply to invoices"+msgstr "应用于发票"+msgid "Approaching {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB cap."msgstr "接近 {PO_EMAIL_ATTACHMENT_LIMIT_MB} MB 上限。"@@ -875,6 +924,12 @@ msgstr "AQL (Z1.4 / ISO 2859-1)"msgid "AR Clerk"msgstr "应收账款文员"+msgid "AR Outstanding"+msgstr "应收账款未结"++msgid "AR Overdue"+msgstr "应收账款逾期"+msgid "Archive"msgstr "存档"@@ -955,9 +1010,9 @@ msgstr "你确定要从此操作中删除 {0} 吗?此操作无法撤销。"msgid "Are you sure you want to delete {0}?"msgstr "你确定要删除 {0} 吗?"+#. placeholder {0}: initialValues.memoId+#. placeholder {0}: initialValues.paymentId#. placeholder {0}: pickingList.pickingListId-#. placeholder {0}: routeData?.consumableSummary?.readableIdWithRevision-#. placeholder {0}: routeData?.customer?.name!msgid "Are you sure you want to delete {0}? This cannot be undone."msgstr "您确定要删除 {0} 吗?此操作无法撤销。"@@ -1243,6 +1298,9 @@ msgstr "你确定吗?"msgid "As needed"msgstr "按需"+msgid "As of:"+msgstr "截至:"+msgid "As the company owner, you can transfer ownership to another employee. This will give them full access to billing and administrative settings."msgstr "作为公司所有者,您可以将所有权转移给另一名员工。这将授予他们对账单和管理设置的完全访问权限。"@@ -1371,6 +1429,9 @@ msgstr "审计日志"msgid "Authentication Error"msgstr "身份验证错误"+msgid "Auto apply"+msgstr "自动应用"+msgid "Auto Release"msgstr "自动发放"@@ -1440,9 +1501,15 @@ msgstr "反冲"msgid "Backups"msgstr "备份"+msgid "Balance"+msgstr "余额"+msgid "Balance Sheet"msgstr "资产负债表"+msgid "Balanced"+msgstr "平衡"+msgid "Balloon"msgstr "气球"@@ -1464,6 +1531,9 @@ msgstr "银行—外币(默认)"msgid "Bank — Local Currency (default)"msgstr "银行—本地货币(默认)"+msgid "Bank / Cash Account"+msgstr "银行/现金账户"+msgid "Bank account denominated in a foreign currency"msgstr "以外币计价的银行账户。"@@ -1643,6 +1713,12 @@ msgstr "由 {byUser}"msgid "By accepting the invite, you agree to the <0>Terms of Service</0> and <1>Privacy Policy</1>."msgstr "通过接受邀请,您同意<0>服务条款</0>和<1>隐私政策</1>。"+msgid "By Document Date"+msgstr "按单据日期"++msgid "By Due Date"+msgstr "按到期日期"+msgid "By signing in, you agree to the <0>Terms of Service</0> and <1>Privacy Policy.</1>"msgstr "通过登录,您同意<0>服务条款</0>和<1>隐私政策。</1>"@@ -1931,6 +2007,9 @@ msgstr "清除搜索"msgid "Clear search query"msgstr "清除搜索查询"+msgid "Clear this invoice with the party's posted credits as well as cash. Credits apply directly — no posting needed."+msgstr "用该方的已过账贷项和现金清算此发票。贷项直接应用——无需过账。"+msgid "Clearing account between goods receipt and supplier invoice; balances when both have posted."msgstr "商品收据和供应商发票之间的清算账户; 当两者都已过帐时余额。"@@ -1977,6 +2056,9 @@ msgstr "云端或您自托管的环境。"msgid "Code"msgstr "代码"+msgid "Collapse"+msgstr "折叠"+msgid "Collapse all"msgstr "全部折叠"@@ -2552,6 +2634,12 @@ msgstr "无法加载文档"msgid "Count"msgstr "数量"+msgid "Counterparties"+msgstr "交易对手"++msgid "Counterparty"+msgstr "交易对手"+msgid "Country"msgstr "国家"@@ -2582,6 +2670,9 @@ msgstr "使用新报价ID创建报价"msgid "Create Account"msgstr "创建账户"+msgid "Create adjusting entry"+msgstr "创建调整分录"+msgid "Create an account"msgstr "创建账户"@@ -2755,12 +2846,21 @@ msgstr "正在创建零件..."msgid "Credit"msgstr "信用"+msgid "Credit / Debit Memos"+msgstr "贷项/借项备忘录"+msgid "Credit Account"msgstr "信用账户"msgid "Credit account when labor/machine time is absorbed into WIP"msgstr "当劳动力/机器时间被吸收到WIP中时的信用账户"+msgid "Credits & Debits"+msgstr "贷项和借项"++msgid "Credits applied"+msgstr "已应用的额度"+msgid "Critical"msgstr "关键"@@ -2935,6 +3035,9 @@ msgstr "客户类型"msgid "Customer Types"msgstr "客户类型"+msgid "Customer Write-Off (Bad Debt)"+msgstr "客户核销(坏账)"+msgid "customers"msgstr "客户"@@ -3314,12 +3417,18 @@ msgstr "删除材料形状"msgid "Delete Material Type"msgstr "删除材料类型"+msgid "Delete Memo"+msgstr "删除备忘录"+msgid "Delete Part"msgstr "删除零件"msgid "Delete Partner"msgstr "删除合作伙伴"+msgid "Delete Payment"+msgstr "删除付款"+msgid "Delete Payment Term"msgstr "删除付款条款"@@ -3566,6 +3675,12 @@ msgstr "尺寸"msgid "Direct"msgstr "直接"+msgid "Direction"+msgstr "方向"++msgid "Directions"+msgstr "方向"+msgid "Disabled"msgstr "已禁用"@@ -3584,6 +3699,10 @@ msgstr "折扣天数"msgid "Discount Days after {selectedCalculationMethod}"msgstr "折扣天数({selectedCalculationMethod}之后)"+#. placeholder {0}: r.invoiceId+msgid "Discount for {0}"+msgstr "{0}的折扣"+msgid "Discount Percent"msgstr "折扣百分比"@@ -3717,6 +3836,9 @@ msgstr "拖动以调整图表和功能的大小"msgid "Drag to zoom"msgstr "拖动以缩放"+msgid "Drawing"+msgstr "提取"+msgid "Drawing Number"msgstr "图纸编号"@@ -3952,6 +4074,9 @@ msgstr "编辑物质材料"msgid "Edit Material Type"msgstr "编辑材料类型"+msgid "Edit Memo"+msgstr "编辑备忘录"+msgid "Edit Non Conformance Type"msgstr "编辑不符合项类型"@@ -3961,6 +4086,9 @@ msgstr "编辑零件"msgid "Edit Partner"msgstr "编辑合作伙伴"+msgid "Edit Payment"+msgstr "编辑付款"+msgid "Edit Payment Term"msgstr "编辑付款条款"@@ -4442,12 +4570,18 @@ msgstr "预期收货"msgid "Expected Receipt Date"msgstr "预期收货日期"+msgid "Expense account for customer balances written off as uncollectable on AR settlement"+msgstr "应收账款结算时作为无法收回的客户余额的费用账户"+msgid "Expense account for deferred tax adjustments on depreciation"msgstr "折旧延期税调整的费用账户"msgid "Expense account for equipment and facility maintenance"msgstr "设备和设施维护的费用账户"+msgid "Expense account for FX losses when a payment settles a foreign-currency invoice at a less favorable rate"+msgstr "支付结算外币发票时汇率不利而产生的外汇损失的费用账户"+msgid "Expense account for non-inventory purchases (services, supplies)"msgstr "非库存采购(服务、物资)的费用账户"@@ -5028,9 +5162,15 @@ msgstr "星期五"msgid "From {0}"msgstr "从 {0}"+msgid "From customer"+msgstr "来自客户"+msgid "From Location"msgstr "从位置"+msgid "from on-account credit"+msgstr "从应收账款信用额度"+msgid "From Storage Unit"msgstr "从存储单位"@@ -5040,6 +5180,9 @@ msgstr "履行地点"msgid "Fully trained for"msgstr "完全培训"+msgid "FX G/L"+msgstr "外汇损益"+msgid "Gains and Losses"msgstr "收益和损失(默认)"@@ -5127,6 +5270,9 @@ msgstr "在 Carbon 中导航"msgid "Getting set up"msgstr "正在设置"+msgid "GL"+msgstr "GL"+msgid "GL Account"msgstr "总账账户"@@ -5241,6 +5387,12 @@ msgstr "非库存购买(用品、服务)的GL支出账户。"msgid "GL liability account credited for sales tax collected from customers."msgstr "从客户征收的销售税的GL负债账户。"+msgid "GL tie-out"+msgstr "总账对账"++msgid "GL Tie-Out"+msgstr "总账对账"+msgid "Go live right the first time — with our team alongside you"msgstr "立即上线,一次就做对——我们的团队与您同行"@@ -5773,6 +5925,9 @@ msgstr "内部参考,用于了解每个工具的优势所在。使用它来诚msgid "inv"msgstr "库存"+msgid "Inv Rate"+msgstr "发票汇率"+msgid "Invalid Invite"msgstr "无效邀请"@@ -5884,6 +6039,12 @@ msgstr "已开票状态"msgid "Invoices"msgstr "发票"+msgid "Invoices this memo has been applied to. Click a row to open the document."+msgstr "此备忘录已应用到的发票。单击一行以打开文档。"++msgid "Invoicing"+msgstr "开票"+msgid "is"msgstr "是"@@ -6451,6 +6612,13 @@ msgstr "制造项目无法直接开票。请将方法更改为\"拣选\"以继msgid "Make Method Version"msgstr "制造方法版本"+msgid "Make Payment"+msgstr "付款"++#. placeholder {0}: selectedInvoices.length+msgid "Make Payment · {0} invoices"+msgstr "付款 · {0} 张发票"+#. placeholder {0}: selectedRevision.revisionmsgid "Make revision {0} default?"msgstr "将修订版本 {0} 设为默认?"@@ -6693,6 +6861,15 @@ msgstr "会议节奏"msgid "Members"msgstr "成员"+msgid "Memo"+msgstr "备忘录"++msgid "Memo Date"+msgstr "备忘录日期"++msgid "Memo ID"+msgstr "备忘录 ID"+msgid "MES"msgstr "MES"@@ -6953,6 +7130,9 @@ msgstr "新消耗品"msgid "New Contractor"msgstr "新承包商"+msgid "New Credit / Debit Memo"+msgstr "新的贷项/借项备忘录"+msgid "New Custom Field"msgstr "新建自定义字段"@@ -7061,6 +7241,9 @@ msgstr "新零件"msgid "New Password"msgstr "新密码"+msgid "New Payment"+msgstr "新付款"+msgid "New Payment Term"msgstr "新付款条款"@@ -7252,6 +7435,9 @@ msgstr "没有活跃报价"msgid "No addresses found"msgstr "未找到地址"+msgid "No applications. Payment will be on-account."+msgstr "无应用。付款将按账户处理。"+#. placeholder {0}: auditConfig.retentionDaysmsgid "No archived logs yet. Logs older than {0} days will be automatically archived and available for download here."msgstr "还没有存档日志。超过 {0} 天的日志将自动存档,并可在此处下载。"@@ -7370,6 +7556,9 @@ msgstr "没有新通知"msgid "No notes"msgstr "没有备注"+msgid "No open invoices"+msgstr "没有未结发票"+msgid "No operations require picking at this location"msgstr "此位置不需要进行任何操作拣选"@@ -7397,6 +7586,12 @@ msgstr "尚未记录任何父源。点击计划页面上的\"重新计算\"以msgid "No part ID"msgstr "无零件ID"+msgid "No payables"+msgstr "无应付款"++msgid "No payments yet."+msgstr "还没有付款。"+msgid "No planning data"msgstr "没有规划数据"@@ -7421,6 +7616,9 @@ msgstr "无报价原因"msgid "No Quote Reasons"msgstr "无报价原因"+msgid "No receivables"+msgstr "无应收账款"+msgid "No remaining entities to inspect."msgstr "没有剩余的实体可检查。"@@ -7598,6 +7796,9 @@ msgstr "在销售订单上"msgid "On Storage Unit"msgstr "在存储单元上"+msgid "On-account credit available"+msgstr "账户信用额度可用"+msgid "On-hand counts"msgstr "现有库存数量"@@ -7818,6 +8019,12 @@ msgstr "订单已提交"msgid "Origin"msgstr "来源"+msgid "Other Income account for FX gains when a payment settles a foreign-currency invoice at a more favorable rate"+msgstr "当付款以更优惠的汇率结清外币发票时,外汇收益的其他收入账户"++msgid "Other Income account for vendor balances cleared without full payment on AP settlement"+msgstr "其他收入账户,用于在应付账款结算时清除未全额支付的供应商余额"+msgid "Other Type"msgstr "其他类型"@@ -7839,6 +8046,9 @@ msgstr "输出永远不会超过其原材料的保质期。当没有输入具有msgid "Outside operation"msgstr "间接费用差异"+msgid "Over-applied by"+msgstr "超额应用"+msgid "Overdue"msgstr "逾期"@@ -7975,6 +8185,9 @@ msgstr "零件和物品"msgid "Parts, materials, and how you classify them."msgstr "零件、材料及其分类方式。"+msgid "Party Type"+msgstr "方当事人类型"+msgid "Pass"msgstr "通过"@@ -7984,17 +8197,29 @@ msgstr "已通过 · 重新打开"msgid "Path"msgstr "路径"+msgid "Pay Rate"+msgstr "支付汇率"+msgid "Payables"msgstr "应付账款(默认)"msgid "Payables (default)"msgstr "付款条件"+msgid "Payables aging"+msgstr "应付账款账龄"+msgid "Payment"msgstr "付款"-msgid "Payment Method"-msgstr "支付方式"+msgid "Payment Applications"+msgstr "付款应用"++msgid "Payment Date"+msgstr "付款日期"++msgid "Payment ID"+msgstr "付款ID"msgid "payment term"msgstr "付款条件"@@ -8011,6 +8236,12 @@ msgstr "付款条款"msgid "Payment terms like Net 30 or due on receipt"msgstr "像 Net 30 或到期时支付这样的付款条款"+msgid "Payments"+msgstr "付款"++msgid "Payments and credits applied to this invoice. Click a row to open the source document."+msgstr "已应用于此发票的付款和贷项。点击一行以打开源文档。"+msgid "PDF"msgstr "PDF"@@ -8672,6 +8903,9 @@ msgstr "采购和自动规划"msgid "Purchasing Contact"msgstr "采购联系人"+msgid "Purchasing Invoices"+msgstr "采购发票"+msgid "Purchasing Unit of Measure"msgstr "采购计量单位"@@ -8866,9 +9100,18 @@ msgstr "实时库存和车间可见性"msgid "Real-time questions during hypercare"msgstr "超护期间的实时问题"+msgid "Realized Exchange Gain"+msgstr "已实现汇兑收益"++msgid "Realized Exchange Loss"+msgstr "已实现汇兑损失"+msgid "Reason"msgstr "原因"+msgid "Reason Account"+msgstr "原因账户"+msgid "Reason for declining (Optional)"msgstr "拒绝原因(可选)"@@ -8911,6 +9154,9 @@ msgstr "应收账款(默认)"msgid "Receivables (default)"msgstr "将采购订单与所收货物和发票进行对账——在Carbon中隐含进行,通过行数量和GR/IR余额。"+msgid "Receivables aging"+msgstr "应收账款账龄"+msgid "Receive"msgstr "接收"@@ -8921,6 +9167,13 @@ msgstr "将 {0} 接收到库存"msgid "Receive against a PO and update inventory"msgstr "根据采购订单收货并更新库存"+msgid "Receive Payment"+msgstr "收款"++#. placeholder {0}: selectedInvoices.length+msgid "Receive Payment · {0} invoices"+msgstr "收款 · {0} 张发票"+msgid "Receive to Inventory"msgstr "接收到库存"@@ -8944,6 +9197,9 @@ msgstr "收货地点"msgid "Recent"msgstr "最近"+msgid "Recent payments"+msgstr "最近的付款"+msgid "Recently Created"msgstr "最近创建"@@ -8953,6 +9209,12 @@ msgstr "回收期"msgid "Record"msgstr "录音"+msgid "Record a credit or debit memo against a customer or supplier. Applications to specific invoices are added after the memo is created."+msgstr "记录针对客户或供应商的贷项或借项备忘录。针对特定发票的应用在备忘录创建后添加。"++msgid "Record cash received from a customer (Receipt) or paid to a supplier (Disbursement). Applications to specific invoices are added after the payment is created."+msgstr "记录从客户收到的现金(收据)或支付给供应商的现金(支付)。对特定发票的应用在创建付款后添加。"+msgid "Record deleted"msgstr "记录已删除"@@ -9037,6 +9299,9 @@ msgstr "发布工作"msgid "Released"msgstr "已发布"+msgid "Remaining"+msgstr "剩余"+msgid "Remaining after split stays on the original row."msgstr "分割后的剩余部分保留在原始行上。"@@ -9583,6 +9848,9 @@ msgstr "保存并关闭"msgid "Save and Overwrite"msgstr "保存并覆盖"+msgid "Save applications"+msgstr "保存应用"+msgid "Save contacts"msgstr "保存联系人"@@ -9824,6 +10092,15 @@ msgstr "选择量具"msgid "Select groups or individuals"msgstr "选择群组或个人"+msgid "Select invoice"+msgstr "选择发票"++msgid "Select invoices from a single counterparty"+msgstr "从单个交易对手选择发票"++msgid "Select invoices in a single currency"+msgstr "选择单一货币中的发票"+msgid "Select Item Type"msgstr "选择项目类型"@@ -9860,6 +10137,9 @@ msgstr "选择表面"msgid "Select the groups that should complete this training"msgstr "选择应该完成此培训的组"+msgid "Select the invoices this payment settles. Discount and write-off are in invoice currency."+msgstr "选择此付款结算的发票。折扣和核销以发票货币计。"+msgid "Select value"msgstr "选择值"@@ -10575,6 +10855,9 @@ msgstr "外包差异"msgid "Subcontracting Variance (default)"msgstr "外包差异(默认)"+msgid "Subledger"+msgstr "子分类账"+msgid "Submit anonymously"msgstr "匿名提交"@@ -11597,6 +11880,9 @@ msgstr "此RFQ没有有效的供应商报价可比较。"msgid "There are outside operations associated with this job that have no suppliers. Please assign a supplier to each outside operation before releasing it."msgstr "此工作有无供应商的外部操作。请在发布前为每个外部操作分配一个供应商。"+msgid "There's nothing outstanding to apply these credits to."+msgstr "没有未结清的发票可以应用这些信用额。"+msgid "These custom fields will only be available for entities with the same tags"msgstr "这些自定义字段仅适用于具有相同标签的实体"@@ -11612,6 +11898,9 @@ msgstr "这些工作有分配给此工作中心的操作:"msgid "This completes the Discovery step."msgstr "这完成了发现步骤。"+msgid "This counterparty has nothing outstanding — the payment will be recorded on-account."+msgstr "该交易对手没有未结余额——该付款将记录为应收账款。"+msgid "This information will be used on document headers"msgstr "此信息将用于文档标题"@@ -11720,6 +12009,9 @@ msgstr "星期四"msgid "Tie shipments through to an invoice with no re-keying"msgstr "将发货与发票关联,无需重新输入"+msgid "Tie-Out"+msgstr "对账"+msgid "Tightened"msgstr "紧张"@@ -11756,6 +12048,9 @@ msgstr "待发货和待收货"msgid "To Storage Unit"msgstr "至存储单位"+msgid "To supplier"+msgstr "给供应商"+msgid "Today"msgstr "今天"@@ -11825,6 +12120,9 @@ msgstr "顶级分类(资产/负债/权益/收益/费用);仅在根组上msgid "Total"msgstr "总计"+msgid "Total Amount"+msgstr "总金额"+msgid "Total capitalized cost of the asset (purchase price plus freight, install, and other costs that become part of book value)."msgstr "资产的总资本化成本(购买价格加运输、安装和其他成为账面价值一部分的成本)。"@@ -11852,6 +12150,9 @@ msgstr "此地点所有活动作业和销售订单所需的总数量——而不msgid "Total:"msgstr "总计:"+msgid "Totals"+msgstr "合计"+msgid "Traceability"msgstr "可追溯性"@@ -12008,6 +12309,12 @@ msgstr "类型"msgid "Un-sampled entities will remain On Hold so you can keep inspecting and disposition later. Sampled outcomes are preserved."msgstr "未采样的实体将保持\"待处理\"状态,以便您可以继续检验并稍后进行处置。已采样的结果将被保留。"+msgid "Unapplied"+msgstr "未应用"++msgid "Unapplied:"+msgstr "未应用:"+msgid "Unapproved Supplier"msgstr "未批准的供应商"@@ -12351,6 +12658,9 @@ msgstr "增值税注册号;欧盟发票中反向收费或零税率供应所需msgid "Values"msgstr "值"+msgid "Variance"+msgstr "差异"+msgid "Variance between actual and standard BOM component consumption"msgstr "实际与标准物料清单成分消耗之间的差异"@@ -12372,6 +12682,9 @@ msgstr "外部加工成本的差异"msgid "VAT Number"msgstr "增值税号"+msgid "Vendor Write-Off Income"+msgstr "供应商核销收入"+msgid "Verification Error"msgstr "验证错误"@@ -12453,6 +12766,9 @@ msgstr "查看列表"msgid "View maintenance dispatch"msgstr "查看维护派遣"+msgid "View Memo"+msgstr "查看备忘录"+msgid "View missing values"msgstr "查看缺失值"@@ -12474,6 +12790,9 @@ msgstr "查看未结报价"msgid "View Open RFQs"msgstr "查看未结束的询价单"+msgid "View Payment"+msgstr "查看付款"+msgid "View permissions"msgstr "查看权限"@@ -13042,9 +13361,19 @@ msgstr "性能最差的机器"msgid "Write-Down Account"msgstr "评估减少账户"+msgid "Write-off"+msgstr "核销"++msgid "Write-Off"+msgstr "核销"+msgid "Write-Off Account"msgstr "核销账户"+#. placeholder {0}: r.invoiceId+msgid "Write-off for {0}"+msgstr "{0}的核销"+msgid "Writing an asset's value down over its life — a monthly batch you create, review as a draft, then post."msgstr "在资产的使用寿命期间降低其价值 — 您创建、作为草稿审阅然后过账的月度批次。"diff --git a/playbooks/create-credit-debit-memo.md b/playbooks/create-credit-debit-memo.mdnew file mode 100644index 0000000000..50cd0ab919--- /dev/null+++ b/playbooks/create-credit-debit-memo.md@@ -0,0 +1,63 @@+# Create a Credit / Debit Memo (Credits & Debits)++Last tested: 2026-06-25+Route: `/x/credits/new` (list at `/x/invoicing/credits`, detail at `/x/credits/:id`)++## Prerequisites+- At least one customer (for a credit/debit to a customer) or supplier (for a+ credit/debit to a supplier). The seed DB has none — create one first.+- A GL account to use as the "Reason Account" (any class; e.g. `4010 Sales`).+- To test posting with a GL journal, the company must have `accountingEnabled = true`+ and account defaults configured. The seed "Carbon Development" company has+ accounting DISABLED, so posting succeeds but writes no journal (journalId stays NULL).++## Steps++### 1. Navigate+- URL: `/x/credits/new`+- Expected: "New Credit / Debit Memo" form with fields: Memo ID (Next Sequence),+ Direction (Credit/Debit), Party Type toggle (Customer/Supplier), Customer or+ Supplier selector, Memo Date, Currency, Exchange Rate, Amount, Reason Account,+ Reference, Notes.++### 2. Fill form+- Direction (first combobox): "Credit" or "Debit"+- Party Type (radio toggle): "Customer" or "Supplier" — switches which selector shows+- Customer / Supplier (combobox): pick the party+- Amount: a positive number+- Reason Account (combobox, no class filter — type to search e.g. "Sales"): pick one+- Memo Date / Currency / Exchange Rate default to today / base / 1++### 3. Submit+- Button: "Save"+- The memoId is generated server-side: Credit → `CR-yyyy-mm-NNNNNN`,+ Debit → `DR-yyyy-mm-NNNNNN`.++### 4. Verify+- Redirect to `/x/credits/:id`+- Detail shows the memo header, the form, the "Memo Applications" panel, and (Draft+ only) an "Apply to invoices" table of the party's open invoices.++### 5. Apply + Post+- Apply table lists the party's OPEN invoices (customer → open sales invoices,+ supplier → open purchase invoices). Enter amounts, "Save applications".+- "Post" button → posts via the `post-memo` edge function; status → Posted.+ Applying is GL-neutral; posting books DR/CR control (AR/AP) vs the reason account.++## Selector Notes+- Direction and Party Type are INDEPENDENT controls (all four combos are valid).+ The Party Type toggle is UI-only (not a form field) — it only switches which of+ customerId/supplierId is submitted.+- The Reason Account combobox is unfiltered (any GL account); type to search.++## Common Failures / Harness Notes+- "Reason account is required" / "Amount must be > 0" — a required field is empty.+- **Amount must be blurred to commit.** The Amount field is react-aria: `fill @ref "300"`+ then click another field to blur, so the hidden `input[name=amount]` commits. Verify+ with `eval "document.querySelector('input[name=amount]').value"` → "300".+- **Submit via `requestSubmit`, not a click.** A plain agent-browser click on "Save"+ does NOT fire the native submit `ValidatedForm` needs (it bails on a missing submitter):+ `eval "(()=>{const b=[...document.querySelectorAll('button')].find(x=>x.type==='submit'&&x.textContent.trim()==='Save');b.closest('form').requestSubmit(b)})()"`.+ This was verified end-to-end (created CR-2026-06-000003). See the `/test` skill step 6b.+- **Post / Void** buttons (`fetcher.submit` onClick) also don't fire under a click; POST+ directly to the path (`/x/credits/:id/post`) to exercise the `post-memo` edge function.