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
fix: backwards compatibility for invoicing without accounting (#1022)
Brad Barbinf0d83ce4a0d0
diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.tsindex ae5b61fc13..7a4d7480da 100644--- a/apps/erp/app/modules/invoicing/invoicing.service.ts+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts@@ -334,15 +334,14 @@ export async function updatePurchaseInvoiceStatus(status: (typeof purchaseInvoiceStatusType)[number];assignee: null | undefined;updatedBy: string;+ datePaid?: string | null;}) {- // 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"- ) {+ // Partially Paid / Overdue are derived in the purchaseInvoices view from+ // invoiceSettlement. Base-status 'Paid' is the manual/legacy/Xero "settled"+ // signal honored by the views and aging/tie-out RPCs; the route enforces+ // that manual 'Paid' is only allowed when accounting is disabled.+ if (update.status === "Partially Paid" || update.status === "Overdue") {return {data: null,error: {@@ -380,15 +379,14 @@ export async function updateSalesInvoiceStatus(status: (typeof salesInvoiceStatusType)[number];assignee: null | undefined;updatedBy: string;+ datePaid?: string | null;}) {- // 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"- ) {+ // Partially Paid / Overdue are derived in the salesInvoices view from+ // invoiceSettlement. Base-status 'Paid' is the manual/legacy/Xero "settled"+ // signal honored by the views and aging/tie-out RPCs; the route enforces+ // that manual 'Paid' is only allowed when accounting is disabled.+ if (update.status === "Partially Paid" || update.status === "Overdue") {return {data: null,error: {diff --git a/apps/erp/app/modules/invoicing/ui/Dashboard/InvoicingDashboard.tsx b/apps/erp/app/modules/invoicing/ui/Dashboard/InvoicingDashboard.tsxindex f2d393d2c0..d93b849112 100644--- a/apps/erp/app/modules/invoicing/ui/Dashboard/InvoicingDashboard.tsx+++ b/apps/erp/app/modules/invoicing/ui/Dashboard/InvoicingDashboard.tsx@@ -59,6 +59,7 @@ export type RecentPayment = {type InvoicingDashboardProps = {asOfDate: string;+ accountingEnabled: boolean;ar: AgingTotals;ap: AgingTotals;arTieOut: TieOut;@@ -79,6 +80,7 @@ const AgingCard = ({icon,totals,tieOut,+ showTieOut,bucketLabels,format}: {@@ -86,6 +88,7 @@ const AgingCard = ({icon: React.ReactNode;totals: AgingTotals;tieOut: TieOut;+ showTieOut: boolean;bucketLabels: string[];format: (n: number) => string;}) => {@@ -144,29 +147,32 @@ const AgingCard = ({</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>+ {showTieOut && (+ <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>+ )) : (- <Status color="red">- <span className="tabular-nums">{format(tieOut.variance)}</span>- </Status>- )- ) : (- <span className="text-muted-foreground">—</span>- )}- </CardFooter>+ <span className="text-muted-foreground">—</span>+ )}+ </CardFooter>+ )}</Card>);};const InvoicingDashboard = ({+ accountingEnabled,ar,ap,arTieOut,@@ -309,6 +315,7 @@ const InvoicingDashboard = ({icon={<LuClock />}totals={ar}tieOut={arTieOut}+ showTieOut={accountingEnabled}bucketLabels={bucketLabels}format={format}/>@@ -317,6 +324,7 @@ const InvoicingDashboard = ({icon={<LuClock />}totals={ap}tieOut={apTieOut}+ showTieOut={accountingEnabled}bucketLabels={bucketLabels}format={format}/>diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsxindex 94a35a0dba..72e27045e4 100644--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx@@ -20,6 +20,8 @@ import { useEffect, useMemo, useState } from "react";import { flushSync } from "react-dom";import {LuCheckCheck,+ LuCircleCheck,+ LuCircleX,LuEllipsisVertical,LuHandCoins,LuPanelLeft,@@ -28,13 +30,14 @@ import {LuTicketX,LuTrash} from "react-icons/lu";-import { Link, useParams } from "react-router";+import { Link, useFetcher, useParams } from "react-router";import { useAuditLog } from "~/components/AuditLog";import { usePanels } from "~/components/Layout/Panels";import ConfirmDelete from "~/components/Modals/ConfirmDelete";import {usePermissions,useRouteData,+ useSettings,useSupplierApprovalRequired,useUser} from "~/hooks";@@ -107,6 +110,21 @@ const PurchaseInvoiceHeader = () => {purchaseInvoice.status === "Partially Paid";const canVoid = isPosted && !isVoided && !hasPayment;+ // Manual Mark as Paid is the settled signal for companies without+ // accounting; with accounting enabled invoices settle only via payments.+ // baseStatus is the stored purchaseInvoice.status (the view's status column+ // is derived from settlements, so a settlement-paid invoice stays untouched).+ const settings = useSettings();+ const accountingEnabled =+ (settings as { accountingEnabled?: boolean }).accountingEnabled ?? false;+ const baseStatus = (purchaseInvoice as { baseStatus?: string | null })+ .baseStatus;+ const statusFetcher = useFetcher<{}>();+ const canToggleManualPaid =+ !accountingEnabled && isPosted && permissions.can("update", "invoicing");+ const canMarkPaid = canToggleManualPaid && baseStatus === "Open";+ const canMarkUnpaid = canToggleManualPaid && baseStatus === "Paid";+const [relatedDocs, setRelatedDocs] = useState<{purchaseOrders: { id: string; readableId: string }[];receipts: { id: string; readableId: string }[];@@ -183,8 +201,10 @@ const PurchaseInvoiceHeader = () => {postingModal.onOpen();};- // Status is derived from invoiceSettlement rows (migration- // 20260519130000); manual mutation removed.+ // Status is derived from invoiceSettlement rows, except base-status 'Paid',+ // which is the manual/legacy/Xero "settled" signal. Companies without+ // accounting can toggle it via Mark as Paid / Mark as Unpaid; the status+ // route rejects manual 'Paid' when accounting is enabled.const canMakePayment =isInvoicePayable(purchaseInvoice.status, purchaseInvoice.balance) &&permissions.can("create", "invoicing");@@ -222,6 +242,46 @@ const PurchaseInvoiceHeader = () => {</DropdownMenuTrigger><DropdownMenuContent>{auditLogTrigger}+ {canMarkPaid && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ disabled={statusFetcher.state !== "idle"}+ onClick={() =>+ statusFetcher.submit(+ { status: "Paid" },+ {+ method: "post",+ action: path.to.purchaseInvoiceStatus(invoiceId)+ }+ )+ }+ >+ <DropdownMenuIcon icon={<LuCircleCheck />} />+ <Trans>Mark as Paid</Trans>+ </DropdownMenuItem>+ </>+ )}+ {canMarkUnpaid && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ disabled={statusFetcher.state !== "idle"}+ onClick={() =>+ statusFetcher.submit(+ { status: "Open" },+ {+ method: "post",+ action: path.to.purchaseInvoiceStatus(invoiceId)+ }+ )+ }+ >+ <DropdownMenuIcon icon={<LuCircleX />} />+ <Trans>Mark as Unpaid</Trans>+ </DropdownMenuItem>+ </>+ )}{isPosted && (<><DropdownMenuSeparator />diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsxindex fe8672cfad..f50c766a2d 100644--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx@@ -20,6 +20,8 @@ import { flushSync } from "react-dom";import {LuCheckCheck,LuChevronDown,+ LuCircleCheck,+ LuCircleX,LuDollarSign,LuEllipsisVertical,LuEye,@@ -35,14 +37,11 @@ import { Link, useFetcher, useParams } from "react-router";import { useAuditLog } from "~/components/AuditLog";import { usePanels } from "~/components/Layout/Panels";import ConfirmDelete from "~/components/Modals/ConfirmDelete";-import { usePermissions, useRouteData, useUser } from "~/hooks";+import { usePermissions, useRouteData, useSettings, useUser } from "~/hooks";import { ShipmentStatus } from "~/modules/inventory/ui/Shipments";import type { SalesInvoice, SalesInvoiceLine } 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 { useItems } from "~/stores";import { path } from "~/utils/path";@@ -94,6 +93,21 @@ const SalesInvoiceHeader = () => {const isPosted = salesInvoice.postingDate !== null;const isVoided = salesInvoice.status === "Voided";+ // Manual Mark as Paid is the settled signal for companies without+ // accounting; with accounting enabled invoices settle only via payments.+ // baseStatus is the stored salesInvoice.status (the view's status column is+ // derived from settlements, so a settlement-paid invoice stays untouched).+ const settings = useSettings();+ const accountingEnabled =+ (settings as { accountingEnabled?: boolean }).accountingEnabled ?? false;+ const baseStatus = (salesInvoice as { baseStatus?: string | null })+ .baseStatus;+ const statusFetcher = useFetcher<{}>();+ const canToggleManualPaid =+ !accountingEnabled && isPosted && permissions.can("update", "invoicing");+ const canMarkPaid = canToggleManualPaid && baseStatus === "Submitted";+ const canMarkUnpaid = canToggleManualPaid && baseStatus === "Paid";+const [relatedDocs, setRelatedDocs] = useState<{salesOrders: { id: string; readableId: string }[];shipments: { id: string; readableId: string; status: string }[];@@ -172,8 +186,10 @@ const SalesInvoiceHeader = () => {postingModal.onOpen();};- // Status is now derived from invoiceSettlement rows (see migration- // 20260519130000); manual status mutation has been removed.+ // Status is derived from invoiceSettlement rows, except base-status 'Paid',+ // which is the manual/legacy/Xero "settled" signal. Companies without+ // accounting can toggle it via Mark as Paid / Mark as Unpaid below; the+ // status route rejects manual 'Paid' when accounting is enabled.// "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.@@ -214,6 +230,46 @@ const SalesInvoiceHeader = () => {</DropdownMenuTrigger><DropdownMenuContent>{auditLogTrigger}+ {canMarkPaid && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ disabled={statusFetcher.state !== "idle"}+ onClick={() =>+ statusFetcher.submit(+ { status: "Paid" },+ {+ method: "post",+ action: path.to.salesInvoiceStatus(invoiceId)+ }+ )+ }+ >+ <DropdownMenuIcon icon={<LuCircleCheck />} />+ <Trans>Mark as Paid</Trans>+ </DropdownMenuItem>+ </>+ )}+ {canMarkUnpaid && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ disabled={statusFetcher.state !== "idle"}+ onClick={() =>+ statusFetcher.submit(+ { status: "Submitted" },+ {+ method: "post",+ action: path.to.salesInvoiceStatus(invoiceId)+ }+ )+ }+ >+ <DropdownMenuIcon icon={<LuCircleX />} />+ <Trans>Mark as Unpaid</Trans>+ </DropdownMenuItem>+ </>+ )}{isPosted && (<><DropdownMenuSeparator />diff --git a/apps/erp/app/modules/invoicing/ui/Workbench/ARAPWorkbench.tsx b/apps/erp/app/modules/invoicing/ui/Workbench/ARAPWorkbench.tsxindex 6a33c0241c..20e18c8d54 100644--- a/apps/erp/app/modules/invoicing/ui/Workbench/ARAPWorkbench.tsx+++ b/apps/erp/app/modules/invoicing/ui/Workbench/ARAPWorkbench.tsx@@ -28,7 +28,7 @@ import {LuTriangleAlert,LuUser} from "react-icons/lu";-import { useFetcher, useNavigate } from "react-router";+import { Link, useFetcher, useNavigate } from "react-router";import { CustomerAvatar, SupplierAvatar, Table } from "~/components";import { Enumerable } from "~/components/Enumerable";import { IndeterminateCheckbox } from "~/components/Table/components";@@ -62,6 +62,8 @@ type AgingRow = {type OpenInvoiceRow = {invoiceId: string;invoiceNumber: string;+ // 'Invoice' | 'Credit Memo' | 'Debit Memo' — from the open-by drill-down+ documentType?: string;dateDue: string | null;currencyCode: string;exchangeRate: number;@@ -300,6 +302,12 @@ export function ARAPWorkbench({</div>);}+ const documentHref =+ r.documentType === "Invoice"+ ? side === "ar"+ ? path.to.salesInvoiceDetails(r.invoiceId)+ : path.to.purchaseInvoiceDetails(r.invoiceId)+ : path.to.memo(r.invoiceId);return (<div className="flex items-center"><div@@ -307,7 +315,12 @@ export function ARAPWorkbench({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>+ <Link+ to={documentHref}+ className="text-foreground/90 hover:underline"+ >+ {r.invoiceNumber}+ </Link><span className="text-xs text-muted-foreground">{r.dateDue ? formatDate(r.dateDue) : "—"}</span>@@ -493,7 +506,7 @@ export function ARAPWorkbench({value={agingMethod}onValueChange={(value) => setParams({ agingMethod: value })}>- <SelectTrigger className="w-[180px]">+ <SelectTrigger size="sm" className="w-[180px]"><SelectValue /></SelectTrigger><SelectContent>@@ -509,6 +522,7 @@ export function ARAPWorkbench({<Trans>As of:</Trans></span><DatePicker+ size="sm"value={parseDate(asOfDate)}onChange={(value) =>setParams({ asOfDate: value?.toString() ?? asOfDate })diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex c647f96917..a8e3eef658 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json@@ -1,5 +1,5 @@{- "generated": "2026-07-03T02:39:35.521Z",+ "generated": "2026-07-03T04:10:08.875Z","totalTools": 1254,"modules": 15,"tools": [@@ -7561,7 +7561,7 @@"module": "invoicing","classification": "WRITE","description": "update purchase invoice status",- "paramCount": 3,+ "paramCount": 4,"serviceParams": ["client","update"@@ -7579,7 +7579,13 @@"status": {"type": "string"},- "assignee": {}+ "assignee": {},+ "datePaid": {+ "type": [+ "string",+ "null"+ ]+ }},"required": ["id",@@ -7623,7 +7629,7 @@"module": "invoicing","classification": "WRITE","description": "update sales invoice status",- "paramCount": 3,+ "paramCount": 4,"serviceParams": ["client","update"@@ -7641,7 +7647,13 @@"status": {"type": "string"},- "assignee": {}+ "assignee": {},+ "datePaid": {+ "type": [+ "string",+ "null"+ ]+ }},"required": ["id",diff --git a/apps/erp/app/routes/x+/invoicing+/_index.tsx b/apps/erp/app/routes/x+/invoicing+/_index.tsxindex dba6564bd5..f9bc9fdb8b 100644--- a/apps/erp/app/routes/x+/invoicing+/_index.tsx+++ b/apps/erp/app/routes/x+/invoicing+/_index.tsx@@ -10,6 +10,7 @@ import {getPayments,InvoicingDashboard} from "~/modules/invoicing";+import { getCompanySettings } from "~/modules/settings";import { getGenericQueryFilters } from "~/utils/query";export const meta: MetaFunction = () => {@@ -63,11 +64,22 @@ export async function loader({ request }: LoaderFunctionArgs) {const asOfDate = new Date().toISOString().slice(0, 10);const { sorts, filters } = getGenericQueryFilters(new URLSearchParams());+ // GL tie-outs only mean something when journals are being posted — skip+ // them entirely when accounting is disabled.+ const companySettings = await getCompanySettings(client, companyId);+ const accountingEnabled =+ (companySettings.data as { accountingEnabled?: boolean } | null)+ ?.accountingEnabled ?? false;+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),+ accountingEnabled+ ? getArTieOut(client, companyId, asOfDate)+ : Promise.resolve({ data: null }),+ accountingEnabled+ ? getApTieOut(client, companyId, asOfDate)+ : Promise.resolve({ data: null }),getPayments(client, companyId, {search: null,paymentType: null,@@ -84,6 +96,7 @@ export async function loader({ request }: LoaderFunctionArgs) {return {asOfDate,bucketDays: BUCKET_DAYS,+ accountingEnabled,ar: sumAging((arAging.data ?? []) as AgingRow[]),ap: sumAging((apAging.data ?? []) as AgingRow[]),arTieOut: arTieOut.data ?? null,@@ -98,6 +111,7 @@ export default function InvoicingIndexRoute() {<InvoicingDashboardasOfDate={data.asOfDate}bucketDays={data.bucketDays}+ accountingEnabled={data.accountingEnabled}ar={data.ar}ap={data.ap}arTieOut={data.arTieOut}diff --git a/apps/erp/app/routes/x+/invoicing+/payables.adjust.tsx b/apps/erp/app/routes/x+/invoicing+/payables.adjust.tsxindex c0f63b9ee6..e39367adc2 100644--- a/apps/erp/app/routes/x+/invoicing+/payables.adjust.tsx+++ b/apps/erp/app/routes/x+/invoicing+/payables.adjust.tsx@@ -10,6 +10,7 @@ import {saveJournalEntryWithLines} from "~/modules/accounting";import { getApTieOut } from "~/modules/invoicing";+import { getCompanySettings } from "~/modules/settings";import { path } from "~/utils/path";// Turns a non-zero AP tie-out variance into a balanced Draft journal entry — the@@ -22,6 +23,20 @@ export async function action({ request }: ActionFunctionArgs) {const { client, companyId, companyGroupId, userId } =await requirePermissions(request, { create: "accounting" });+ // Adjusting entries only make sense when journals are being posted.+ const companySettings = await getCompanySettings(client, companyId);+ if (+ !(+ (companySettings.data as { accountingEnabled?: boolean } | null)+ ?.accountingEnabled ?? false+ )+ ) {+ throw redirect(+ path.to.payables,+ await flash(request, error(null, "Accounting is not enabled"))+ );+ }+const formData = await request.formData();const asOfDate =(formData.get("asOfDate") as string | null) ??diff --git a/apps/erp/app/routes/x+/invoicing+/payables.tsx b/apps/erp/app/routes/x+/invoicing+/payables.tsxindex b545a4acfd..12f461fa7e 100644--- a/apps/erp/app/routes/x+/invoicing+/payables.tsx+++ b/apps/erp/app/routes/x+/invoicing+/payables.tsx@@ -7,6 +7,7 @@ import {getApOpenBySupplier,getApTieOut} from "~/modules/invoicing";+import { getCompanySettings } from "~/modules/settings";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";@@ -38,8 +39,18 @@ export async function loader({ request }: LoaderFunctionArgs) {: "dueDate";const bucketDays = parseBuckets(url.searchParams.get("bucketDays"));+ // GL tie-outs only mean something when journals are being posted — skip+ // them entirely when accounting is disabled (result: null hides the+ // tie-out panel and the adjusting-entry form in ARAPWorkbench).+ const companySettings = await getCompanySettings(client, companyId);+ const accountingEnabled =+ (companySettings.data as { accountingEnabled?: boolean } | null)+ ?.accountingEnabled ?? false;+const [tieOut, aging, open] = await Promise.all([- getApTieOut(client, companyId, asOfDate),+ accountingEnabled+ ? getApTieOut(client, companyId, asOfDate)+ : Promise.resolve({ data: null }),getApAging(client, companyId, asOfDate, { agingMethod, bucketDays }),getApOpenBySupplier(client, companyId, asOfDate)]);diff --git a/apps/erp/app/routes/x+/invoicing+/receivables.adjust.tsx b/apps/erp/app/routes/x+/invoicing+/receivables.adjust.tsxindex 0aa44c2a09..950c3856e2 100644--- a/apps/erp/app/routes/x+/invoicing+/receivables.adjust.tsx+++ b/apps/erp/app/routes/x+/invoicing+/receivables.adjust.tsx@@ -10,6 +10,7 @@ import {saveJournalEntryWithLines} from "~/modules/accounting";import { getArTieOut } from "~/modules/invoicing";+import { getCompanySettings } from "~/modules/settings";import { path } from "~/utils/path";// Turns a non-zero AR tie-out variance into a balanced Draft journal entry — the@@ -22,6 +23,20 @@ export async function action({ request }: ActionFunctionArgs) {const { client, companyId, companyGroupId, userId } =await requirePermissions(request, { create: "accounting" });+ // Adjusting entries only make sense when journals are being posted.+ const companySettings = await getCompanySettings(client, companyId);+ if (+ !(+ (companySettings.data as { accountingEnabled?: boolean } | null)+ ?.accountingEnabled ?? false+ )+ ) {+ throw redirect(+ path.to.receivables,+ await flash(request, error(null, "Accounting is not enabled"))+ );+ }+const formData = await request.formData();const asOfDate =(formData.get("asOfDate") as string | null) ??diff --git a/apps/erp/app/routes/x+/invoicing+/receivables.tsx b/apps/erp/app/routes/x+/invoicing+/receivables.tsxindex e9c3e50dcf..ee3de012c7 100644--- a/apps/erp/app/routes/x+/invoicing+/receivables.tsx+++ b/apps/erp/app/routes/x+/invoicing+/receivables.tsx@@ -7,6 +7,7 @@ import {getArOpenByCustomer,getArTieOut} from "~/modules/invoicing";+import { getCompanySettings } from "~/modules/settings";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";@@ -38,8 +39,18 @@ export async function loader({ request }: LoaderFunctionArgs) {: "dueDate";const bucketDays = parseBuckets(url.searchParams.get("bucketDays"));+ // GL tie-outs only mean something when journals are being posted — skip+ // them entirely when accounting is disabled (result: null hides the+ // tie-out panel and the adjusting-entry form in ARAPWorkbench).+ const companySettings = await getCompanySettings(client, companyId);+ const accountingEnabled =+ (companySettings.data as { accountingEnabled?: boolean } | null)+ ?.accountingEnabled ?? false;+const [tieOut, aging, open] = await Promise.all([- getArTieOut(client, companyId, asOfDate),+ accountingEnabled+ ? getArTieOut(client, companyId, asOfDate)+ : Promise.resolve({ data: null }),getArAging(client, companyId, asOfDate, { agingMethod, bucketDays }),getArOpenByCustomer(client, companyId, asOfDate)]);diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.status.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.status.tsxindex 6a07098821..9cb6183a8d 100644--- a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.status.tsx+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.status.tsx@@ -3,16 +3,14 @@ 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 {- getPurchaseInvoice,- updatePurchaseInvoiceStatus-} from "~/modules/invoicing";+import { updatePurchaseInvoiceStatus } from "~/modules/invoicing";import { purchaseInvoiceStatusType } from "~/modules/invoicing/invoicing.models";+import { getCompanySettings } from "~/modules/settings";import { path, requestReferrer } from "~/utils/path";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {update: "invoicing"});@@ -31,7 +29,14 @@ export async function action({ request, params }: ActionFunctionArgs) {);}- const invoice = await getPurchaseInvoice(client, id);+ // Read the base table, not the purchaseInvoices view — the view derives+ // status/datePaid from settlements, but the manual transitions below key+ // on the stored base status.+ const invoice = await client+ .from("purchaseInvoice")+ .select("status, datePaid, postingDate")+ .eq("id", id)+ .single();if (invoice.error || !invoice.data) {throw redirect(@@ -56,11 +61,51 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ // Manual Paid (and its revert) is the settled signal for companies without+ // accounting. With accounting enabled, invoices settle only via payments so+ // the subledger stays tied to the GL.+ let datePaid: string | null | undefined;+ const isMarkingPaid = status === "Paid";+ const isReverting = invoice.data.status === "Paid" && status === "Open";++ if (isMarkingPaid || isReverting) {+ const companySettings = await getCompanySettings(client, companyId);+ const accountingEnabled =+ (companySettings.data as { accountingEnabled?: boolean } | null)+ ?.accountingEnabled ?? false;++ if (accountingEnabled) {+ throw redirect(+ requestReferrer(request) ?? path.to.purchaseInvoiceDetails(id),+ await flash(+ request,+ error(+ null,+ "Invoices are settled by payments when accounting is enabled"+ )+ )+ );+ }++ if (isMarkingPaid && invoice.data.status !== "Open") {+ throw redirect(+ requestReferrer(request) ?? path.to.purchaseInvoiceDetails(id),+ await flash(+ request,+ error(null, "Only open invoices can be marked as paid")+ )+ );+ }++ datePaid = isMarkingPaid ? new Date().toISOString().slice(0, 10) : null;+ }+const update = await updatePurchaseInvoiceStatus(client, {id,status,assignee: !["Partially Paid"].includes(status) ? null : undefined,- updatedBy: userId+ updatedBy: userId,+ ...(datePaid !== undefined ? { datePaid } : {})});if (update.error) {throw redirect(@@ -73,7 +118,7 @@ export async function action({ request, params }: ActionFunctionArgs) {}throw redirect(- requestReferrer(request) ?? path.to.quote(id),+ requestReferrer(request) ?? path.to.purchaseInvoiceDetails(id),await flash(request, success("Updated purchase invoice status")));}diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.status.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.status.tsxindex e03efc1227..a998f45e62 100644--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.status.tsx+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.status.tsx@@ -5,11 +5,12 @@ import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import { updateSalesInvoiceStatus } from "~/modules/invoicing";import { salesInvoiceStatusType } from "~/modules/invoicing/invoicing.models";+import { getCompanySettings } from "~/modules/settings";import { path, requestReferrer } from "~/utils/path";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId } = await requirePermissions(request, {+ const { client, companyId, userId } = await requirePermissions(request, {update: "invoicing"});@@ -28,11 +29,80 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ // Read the base table, not the salesInvoices view — the view derives+ // status/datePaid from settlements, but the manual transitions below key+ // on the stored base status.+ const invoice = await client+ .from("salesInvoice")+ .select("status, datePaid, postingDate")+ .eq("id", id)+ .single();++ if (invoice.error || !invoice.data) {+ throw redirect(+ requestReferrer(request) ?? path.to.salesInvoiceDetails(id),+ await flash(request, error(invoice.error, "Failed to get sales invoice"))+ );+ }++ if (!invoice.data.postingDate) {+ throw redirect(+ requestReferrer(request) ?? path.to.salesInvoiceDetails(id),+ await flash(+ request,+ error(+ null,+ "Cannot update status of draft sales invoice. Please post the invoice first."+ )+ )+ );+ }++ // Manual Paid (and its revert) is the settled signal for companies without+ // accounting. With accounting enabled, invoices settle only via payments so+ // the subledger stays tied to the GL.+ let datePaid: string | null | undefined;+ const isMarkingPaid = status === "Paid";+ const isReverting = invoice.data.status === "Paid" && status === "Submitted";++ if (isMarkingPaid || isReverting) {+ const companySettings = await getCompanySettings(client, companyId);+ const accountingEnabled =+ (companySettings.data as { accountingEnabled?: boolean } | null)+ ?.accountingEnabled ?? false;++ if (accountingEnabled) {+ throw redirect(+ requestReferrer(request) ?? path.to.salesInvoiceDetails(id),+ await flash(+ request,+ error(+ null,+ "Invoices are settled by payments when accounting is enabled"+ )+ )+ );+ }++ if (isMarkingPaid && invoice.data.status !== "Submitted") {+ throw redirect(+ requestReferrer(request) ?? path.to.salesInvoiceDetails(id),+ await flash(+ request,+ error(null, "Only submitted invoices can be marked as paid")+ )+ );+ }++ datePaid = isMarkingPaid ? new Date().toISOString().slice(0, 10) : null;+ }+const update = await updateSalesInvoiceStatus(client, {id,status,assignee: !["Partially Paid"].includes(status) ? null : undefined,- updatedBy: userId+ updatedBy: userId,+ ...(datePaid !== undefined ? { datePaid } : {})});if (update.error) {@@ -46,7 +116,7 @@ export async function action({ request, params }: ActionFunctionArgs) {}throw redirect(- requestReferrer(request) ?? path.to.quote(id),+ requestReferrer(request) ?? path.to.salesInvoiceDetails(id),await flash(request, success("Updated sales invoice status")));}diff --git a/packages/database/supabase/migrations/20260702224219_fix-ar-ap-legacy-paid.sql b/packages/database/supabase/migrations/20260702224219_fix-ar-ap-legacy-paid.sqlnew file mode 100644index 0000000000..27bc838397--- /dev/null+++ b/packages/database/supabase/migrations/20260702224219_fix-ar-ap-legacy-paid.sql@@ -0,0 +1,925 @@+-- ============================================================+-- Honor legacy base-status 'Paid' invoices as settled + fix view fork regressions+--+-- Problem: invoices whose BASE-table status is 'Paid' with no invoiceSettlement+-- rows (manually marked pre-payments, or written by the Xero sync, which still+-- sets base status + datePaid directly) fell through the views' status CASE to+-- ELSE (displayed 'Paid') but computed balance = totalAmount − 0, and the+-- aging/tie-out RPCs (filter: status NOT IN ('Draft','Pending','Voided'))+-- counted them fully open — inflating aging buckets, dashboard KPIs, and the+-- tie-out subledger. They also can't be settled via post-payment (it requires+-- base status 'Submitted'/'Open').+--+-- Fix: base-table status 'Paid' is now an authoritative "settled" signal:+-- * views: status 'Paid', balance 0, datePaid = base datePaid+-- * RPCs: excluded from the invoice arms when+-- base status = 'Paid' AND (datePaid IS NULL OR datePaid <= _as_of_date)+-- (an invoice paid AFTER the as-of date still shows open historically).+-- The exclusion keys on the BASE table because view status 'Paid' is also+-- produced for settlement-derived paid invoices, which must keep the+-- existing payment.postingDate as-of math.+-- Base 'Partially Paid' with no settlements stays FULLY OPEN (deliberate:+-- the paid amount is unknowable; remediate via a real payment or write-off).+--+-- Fork sources (full bodies, minimal edits):+-- * both views — 20260702114500_invoice-balance-includes-line-tax.sql+-- (keeps its live line-derived total in the balance/status/datePaid+-- math, memo-aware settled CTE, paymentTermName on salesInvoices, the+-- LEFT JOIN on salesInvoiceShipment, dust forgiveness, and the+-- supplierShippingCost divide with zero-guard). The only view edits here+-- are the base-'Paid' branches and the new baseStatus column.+-- * six RPCs — 20260630104012_tie-out-aging-from-view-total.sql+-- ============================================================++DROP VIEW IF EXISTS "salesInvoices";+CREATE VIEW "salesInvoices" WITH(SECURITY_INVOKER=true) AS+ WITH settled AS (+ -- Amount applied TO this invoice (as the settlement target): Posted cash+ -- payments, and Posted credit memos once the payment applying them is+ -- Posted (a memo staged through a Draft payment doesn't count yet).+ SELECT+ s."targetSalesInvoiceId",+ SUM(s."appliedAmount" + s."discountAmount" + s."writeOffAmount") AS amount,+ MAX(s."appliedDate") AS "lastSettlementDate"+ FROM "invoiceSettlement" s+ LEFT JOIN "payment" p ON p."id" = s."paymentId"+ LEFT JOIN "memo" m ON m."id" = s."memoId"+ LEFT JOIN "payment" vp ON vp."id" = s."appliedViaPaymentId"+ WHERE s."targetSalesInvoiceId" IS NOT NULL+ AND (+ (s."paymentId" IS NOT NULL AND p."status" = 'Posted')+ OR (+ s."memoId" IS NOT NULL AND m."status" = 'Posted'+ AND (s."appliedViaPaymentId" IS NULL OR vp."status" = 'Posted')+ )+ )+ GROUP BY s."targetSalesInvoiceId"+ )+ SELECT+ si."id",+ si."invoiceId",+ CASE+ WHEN si."status" IN ('Draft','Pending','Voided','Return','Credit Note Issued') THEN si."status"::TEXT+ WHEN si."status" = 'Paid' THEN 'Paid'+ WHEN COALESCE(s.amount, 0) > 0+ AND (COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0)) > 0+ AND ((COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0)) - COALESCE(s.amount, 0)) < 0.01 THEN 'Paid'+ WHEN COALESCE(s.amount, 0) > 0 THEN 'Partially Paid'+ WHEN si."dateDue" < CURRENT_DATE AND si."status" = 'Submitted' THEN 'Overdue'+ ELSE si."status"::TEXT+ END AS status,+ si."customerId",+ si."customerReference",+ si."invoiceCustomerId",+ si."invoiceCustomerLocationId",+ si."invoiceCustomerContactId",+ si."paymentTermId",+ si."postingDate",+ si."dateIssued",+ si."dateDue",+ CASE+ WHEN si."status" = 'Paid' THEN si."datePaid"+ WHEN COALESCE(s.amount, 0) > 0+ AND (COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0)) > 0+ AND ((COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0)) - COALESCE(s.amount, 0)) < 0.01 THEN COALESCE(s."lastSettlementDate", si."datePaid")+ ELSE si."datePaid"+ END AS "datePaid",+ si."locationId",+ si."currencyCode",+ COALESCE(sil."subtotal", 0) AS "subtotal",+ si."totalDiscount",+ COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0) AS "totalAmount",+ COALESCE(sil."totalTax", 0) AS "totalTax",+ CASE+ WHEN si."status" = 'Paid' THEN 0+ WHEN COALESCE(s.amount, 0) > 0+ AND ((COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0)) - COALESCE(s.amount, 0)) > 0+ AND ((COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0)) - COALESCE(s.amount, 0)) < 0.01 THEN 0+ ELSE ((COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0)) - COALESCE(s.amount, 0))+ END AS "balance",+ si."exchangeRate",+ si."exchangeRateUpdatedAt",+ si."opportunityId",+ si."shipmentId",+ si."assignee",+ si."companyId",+ si."customFields",+ si."internalNotes",+ si."externalNotes",+ si."tags",+ si."createdAt",+ si."createdBy",+ si."updatedAt",+ si."updatedBy",+ sil."thumbnailPath",+ sil."itemType",+ COALESCE(sil."subtotal", 0) + COALESCE(sil."totalTax", 0) + COALESCE(ss."shippingCost", 0) AS "invoiceTotal",+ sil."lines",+ pt."name" AS "paymentTermName",+ si."status" AS "baseStatus"+ FROM "salesInvoice" si+ LEFT JOIN (+ SELECT+ sil."invoiceId",+ MIN(CASE+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"+ ELSE i."thumbnailPath"+ END) AS "thumbnailPath",+ SUM(+ COALESCE(sil."quantity", 0)*COALESCE(sil."unitPrice", 0)+ + COALESCE(sil."addOnCost", 0)+ + COALESCE(sil."nonTaxableAddOnCost", 0)+ + COALESCE(sil."shippingCost", 0)+ ) AS "subtotal",+ SUM(+ COALESCE(sil."taxPercent", 0) * (+ COALESCE(sil."quantity", 0)*COALESCE(sil."unitPrice", 0)+ + COALESCE(sil."addOnCost", 0)+ + COALESCE(sil."shippingCost", 0)+ )+ ) AS "totalTax",+ MIN(i."type") AS "itemType",+ ARRAY_AGG(+ json_build_object(+ 'id', sil.id,+ 'invoiceLineType', sil."invoiceLineType",+ 'quantity', sil."quantity",+ 'unitPrice', sil."unitPrice",+ 'itemId', sil."itemId"+ )+ ) AS "lines"+ FROM "salesInvoiceLine" sil+ LEFT JOIN "item" i+ ON i."id" = sil."itemId"+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"+ GROUP BY sil."invoiceId"+ ) sil ON sil."invoiceId" = si."id"+ -- LEFT JOIN (was INNER): an invoice missing its shipment row must not+ -- vanish from the view — post-payment would read its balance as 0 and+ -- reject every application. shippingCost is already COALESCEd.+ LEFT JOIN "salesInvoiceShipment" ss ON ss."id" = si."id"+ LEFT JOIN "paymentTerm" pt ON pt."id" = si."paymentTermId"+ LEFT JOIN settled s ON s."targetSalesInvoiceId" = si."id";+++DROP VIEW IF EXISTS "purchaseInvoices";+CREATE VIEW "purchaseInvoices" WITH(SECURITY_INVOKER=true) AS+ WITH settled AS (+ SELECT+ s."targetPurchaseInvoiceId",+ SUM(s."appliedAmount" + s."discountAmount" + s."writeOffAmount") AS amount,+ MAX(s."appliedDate") AS "lastSettlementDate"+ FROM "invoiceSettlement" s+ LEFT JOIN "payment" p ON p."id" = s."paymentId"+ LEFT JOIN "memo" m ON m."id" = s."memoId"+ LEFT JOIN "payment" vp ON vp."id" = s."appliedViaPaymentId"+ WHERE s."targetPurchaseInvoiceId" IS NOT NULL+ AND (+ (s."paymentId" IS NOT NULL AND p."status" = 'Posted')+ OR (+ s."memoId" IS NOT NULL AND m."status" = 'Posted'+ AND (s."appliedViaPaymentId" IS NULL OR vp."status" = 'Posted')+ )+ )+ GROUP BY s."targetPurchaseInvoiceId"+ )+ SELECT+ pi."id",+ pi."invoiceId",+ pi."supplierId",+ pi."invoiceSupplierId",+ pi."supplierInteractionId",+ pi."supplierReference",+ pi."invoiceSupplierContactId",+ pi."invoiceSupplierLocationId",+ pi."locationId",+ pi."postingDate",+ pi."dateIssued",+ pi."dateDue",+ CASE+ WHEN pi."status" = 'Paid' THEN pi."datePaid"+ WHEN COALESCE(s.amount, 0) > 0+ AND (COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) > 0+ AND ((COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) - COALESCE(s.amount, 0)) < 0.01 THEN COALESCE(s."lastSettlementDate", pi."datePaid")+ ELSE pi."datePaid"+ END AS "datePaid",+ pi."paymentTermId",+ pi."currencyCode",+ pi."exchangeRate",+ pi."exchangeRateUpdatedAt",+ COALESCE(pl."subtotal", 0) AS "subtotal",+ pi."totalDiscount",+ (COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) AS "totalAmount",+ COALESCE(pl."totalTax", 0) AS "totalTax",+ CASE+ WHEN pi."status" = 'Paid' THEN 0+ WHEN COALESCE(s.amount, 0) > 0+ AND ((COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) - COALESCE(s.amount, 0)) > 0+ AND ((COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) - COALESCE(s.amount, 0)) < 0.01 THEN 0+ ELSE ((COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) - COALESCE(s.amount, 0))+ END AS "balance",+ pi."assignee",+ pi."createdBy",+ pi."createdAt",+ pi."updatedBy",+ pi."updatedAt",+ pi."internalNotes",+ pi."customFields",+ pi."companyId",+ pl."thumbnailPath",+ pl."itemType",+ COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END AS "orderTotal",+ CASE+ WHEN pi."status" IN ('Draft','Pending','Voided','Return','Debit Note Issued') THEN pi."status"::TEXT+ WHEN pi."status" = 'Paid' THEN 'Paid'+ WHEN COALESCE(s.amount, 0) > 0+ AND (COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) > 0+ AND ((COALESCE(pl."orderTotal", 0) + COALESCE(pid."supplierShippingCost", 0) / CASE WHEN pi."exchangeRate" = 0 THEN 1 ELSE pi."exchangeRate" END) - COALESCE(s.amount, 0)) < 0.01 THEN 'Paid'+ WHEN COALESCE(s.amount, 0) > 0 THEN 'Partially Paid'+ WHEN pi."dateDue" < CURRENT_DATE AND pi."status" = 'Open' THEN 'Overdue'+ ELSE pi."status"::TEXT+ END AS status,+ pt."name" AS "paymentTermName",+ pi."status" AS "baseStatus"+ FROM "purchaseInvoice" pi+ LEFT JOIN (+ SELECT+ pol."invoiceId",+ MIN(CASE+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"+ ELSE i."thumbnailPath"+ END) AS "thumbnailPath",+ SUM(+ COALESCE(pol."quantity", 0)*COALESCE(pol."unitPrice", 0) + COALESCE(pol."shippingCost", 0)+ ) AS "subtotal",+ SUM(COALESCE(pol."taxAmount", 0)) AS "totalTax",+ SUM(+ COALESCE(pol."quantity", 0)*COALESCE(pol."unitPrice", 0) + COALESCE(pol."shippingCost", 0) + COALESCE(pol."taxAmount", 0)+ ) AS "orderTotal",+ MIN(i."type") AS "itemType"+ FROM "purchaseInvoiceLine" pol+ LEFT JOIN "item" i+ ON i."id" = pol."itemId"+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"+ GROUP BY pol."invoiceId"+ ) pl ON pl."invoiceId" = pi."id"+ LEFT JOIN "paymentTerm" pt ON pt."id" = pi."paymentTermId"+ LEFT JOIN "purchaseInvoiceDelivery" pid ON pid."id" = pi."id"+ LEFT JOIN settled s ON s."targetPurchaseInvoiceId" = pi."id";+++-- ============================================================+-- RPCs — forked from 20260630104012, single change per invoice arm:+-- join the BASE invoice table and exclude legacy/base-'Paid' invoices+-- (unless their datePaid is after the as-of date).+-- ============================================================++DROP FUNCTION IF EXISTS get_ar_tie_out(TEXT, DATE);+DROP FUNCTION IF EXISTS get_ap_tie_out(TEXT, DATE);+DROP FUNCTION IF EXISTS get_ar_open_by_customer(TEXT, DATE);+DROP FUNCTION IF EXISTS get_ap_open_by_supplier(TEXT, DATE);+DROP FUNCTION IF EXISTS get_ar_aging(TEXT, DATE, TEXT, INTEGER, INTEGER, INTEGER);+DROP FUNCTION IF EXISTS get_ap_aging(TEXT, DATE, TEXT, INTEGER, INTEGER, INTEGER);+++-- ============================================================+-- AR tie-out+-- ============================================================++CREATE 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+ JOIN "salesInvoice" sib ON sib."id" = si."id" AND sib."companyId" = si."companyId"+ WHERE si."companyId" = _company_id+ AND si."postingDate" <= _as_of_date+ AND si."status" NOT IN ('Draft', 'Pending', 'Voided')+ AND NOT (+ sib."status" = 'Paid'+ AND (sib."datePaid" IS NULL OR sib."datePaid" <= _as_of_date)+ )+ ),+ -- 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 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+ JOIN "purchaseInvoice" pib ON pib."id" = pi."id" AND pib."companyId" = pi."companyId"+ WHERE pi."companyId" = _company_id+ AND pi."postingDate" <= _as_of_date+ AND pi."status" NOT IN ('Draft', 'Pending', 'Voided')+ AND NOT (+ pib."status" = 'Paid'+ AND (pib."datePaid" IS NULL OR pib."datePaid" <= _as_of_date)+ )+ ),+ -- 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.++CREATE 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+ JOIN "salesInvoice" sib ON sib."id" = si."id" AND sib."companyId" = si."companyId"+ 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 NOT (+ sib."status" = 'Paid'+ AND (sib."datePaid" IS NULL OR sib."datePaid" <= _as_of_date)+ )+ 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)+-- ============================================================++CREATE 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+ JOIN "purchaseInvoice" pib ON pib."id" = pi."id" AND pib."companyId" = pi."companyId"+ 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 NOT (+ pib."status" = 'Paid'+ AND (pib."datePaid" IS NULL OR pib."datePaid" <= _as_of_date)+ )+ 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 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+ JOIN "salesInvoice" sib ON sib."id" = si."id" AND sib."companyId" = si."companyId"+ WHERE si."companyId" = _company_id+ AND si."postingDate" <= _as_of_date+ AND si."status" NOT IN ('Draft', 'Pending', 'Voided')+ AND NOT (+ sib."status" = 'Paid'+ AND (sib."datePaid" IS NULL OR sib."datePaid" <= _as_of_date)+ )++ 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 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+ JOIN "purchaseInvoice" pib ON pib."id" = pi."id" AND pib."companyId" = pi."companyId"+ WHERE pi."companyId" = _company_id+ AND pi."postingDate" <= _as_of_date+ AND pi."status" NOT IN ('Draft', 'Pending', 'Voided')+ AND NOT (+ pib."status" = 'Paid'+ AND (pib."datePaid" IS NULL OR pib."datePaid" <= _as_of_date)+ )++ 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/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex ec034d368c..884ce5c547 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -6730,12 +6730,18 @@ msgstr "Zeilen jetzt zuordnen"msgid "Map your current process, systems, and data"msgstr "Ordnen Sie Ihren aktuellen Prozess, Ihre Systeme und Daten"+msgid "Mark as Paid"+msgstr "Als bezahlt markieren"+msgid "Mark as Planned"msgstr "Als geplant markieren"msgid "Mark as read"msgstr "Als gelesen markieren"+msgid "Mark as Unpaid"+msgstr "Als unbezahlt markieren"+msgid "Mark checkpoint passed"msgstr "Checkpoint als bestanden markieren"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 50fa7720b4..6d0e5aaf2b 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -6730,12 +6730,18 @@ msgstr "Map Lines Now"msgid "Map your current process, systems, and data"msgstr "Map your current process, systems, and data"+msgid "Mark as Paid"+msgstr "Mark as Paid"+msgid "Mark as Planned"msgstr "Mark as Planned"msgid "Mark as read"msgstr "Mark as read"+msgid "Mark as Unpaid"+msgstr "Mark as Unpaid"+msgid "Mark checkpoint passed"msgstr "Mark checkpoint passed"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 096d22a7d3..6a6be422d8 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -6730,12 +6730,18 @@ msgstr "Mapear líneas ahora"msgid "Map your current process, systems, and data"msgstr "Mapea tu proceso actual, sistemas y datos"+msgid "Mark as Paid"+msgstr "Marcar como Pagado"+msgid "Mark as Planned"msgstr "Marcar como Planificado"msgid "Mark as read"msgstr "Marcar como leído"+msgid "Mark as Unpaid"+msgstr "Marcar como No Pagado"+msgid "Mark checkpoint passed"msgstr "Marcar punto de control como completado"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex ddbe63ac45..3c6f8035eb 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -6730,12 +6730,18 @@ msgstr "Mapper les lignes maintenant"msgid "Map your current process, systems, and data"msgstr "Cartographiez votre processus actuel, vos systèmes et vos données"+msgid "Mark as Paid"+msgstr "Marquer comme payé"+msgid "Mark as Planned"msgstr "Marquer comme planifié"msgid "Mark as read"msgstr "Marquer comme lu"+msgid "Mark as Unpaid"+msgstr "Marquer comme non payé"+msgid "Mark checkpoint passed"msgstr "Marquer le point de contrôle comme réussi"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex edda13afbb..f923b0f258 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -6730,12 +6730,18 @@ msgstr "अभी लाइनें मैप करें"msgid "Map your current process, systems, and data"msgstr "अपनी वर्तमान प्रक्रिया, सिस्टम और डेटा को मैप करें"+msgid "Mark as Paid"+msgstr "भुगतान के रूप में चिह्नित करें"+msgid "Mark as Planned"msgstr "योजना के रूप में चिह्नित करें"msgid "Mark as read"msgstr "पढ़ा हुआ चिह्नित करें"+msgid "Mark as Unpaid"+msgstr "अदा न किए गए के रूप में चिह्नित करें"+msgid "Mark checkpoint passed"msgstr "चेकपॉइंट पास किया गया चिह्नित करें"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex 7df8313954..3ddcafa1e8 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -6730,12 +6730,18 @@ msgstr "Mappa Righe Ora"msgid "Map your current process, systems, and data"msgstr "Mappa il tuo processo attuale, i sistemi e i dati"+msgid "Mark as Paid"+msgstr "Segna come Pagato"+msgid "Mark as Planned"msgstr "Contrassegna come Pianificato"msgid "Mark as read"msgstr "Segna come letto"+msgid "Mark as Unpaid"+msgstr "Contrassegna come Non Pagato"+msgid "Mark checkpoint passed"msgstr "Contrassegna checkpoint come superato"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 9e1eb7417f..913f5c5708 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -6730,12 +6730,18 @@ msgstr "今すぐラインをマップ"msgid "Map your current process, systems, and data"msgstr "現在のプロセス、システム、データをマップする"+msgid "Mark as Paid"+msgstr "支払い済みとしてマーク"+msgid "Mark as Planned"msgstr "計画済みとしてマーク"msgid "Mark as read"msgstr "読み取り済みにマーク"+msgid "Mark as Unpaid"+msgstr "未払いとしてマーク"+msgid "Mark checkpoint passed"msgstr "チェックポイント完了をマーク"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex b32c103114..777a0b45b6 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -6730,12 +6730,18 @@ msgstr "Mapuj linie teraz"msgid "Map your current process, systems, and data"msgstr "Zmapuj swój obecny proces, systemy i dane"+msgid "Mark as Paid"+msgstr "Oznacz jako opłacone"+msgid "Mark as Planned"msgstr "Oznacz jako zaplanowane"msgid "Mark as read"msgstr "Oznacz jako przeczytane"+msgid "Mark as Unpaid"+msgstr "Oznacz jako nieopłacone"+msgid "Mark checkpoint passed"msgstr "Oznacz punkt kontrolny jako ukończony"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex e842ebd8de..6c54f594a9 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -6730,12 +6730,18 @@ msgstr "Mapear Linhas Agora"msgid "Map your current process, systems, and data"msgstr "Mapeie seu processo, sistemas e dados atuais"+msgid "Mark as Paid"+msgstr "Marcar como Pago"+msgid "Mark as Planned"msgstr "Marcar como Planejado"msgid "Mark as read"msgstr "Marcar como lido"+msgid "Mark as Unpaid"+msgstr "Marcar como Não Pago"+msgid "Mark checkpoint passed"msgstr "Marcar checkpoint como aprovado"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex 207e307627..721881043c 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -6730,12 +6730,18 @@ msgstr "Сопоставить строки сейчас"msgid "Map your current process, systems, and data"msgstr "Сопоставьте ваш текущий процесс, системы и данные"+msgid "Mark as Paid"+msgstr "Отметить как оплачено"+msgid "Mark as Planned"msgstr "Отметить как запланировано"msgid "Mark as read"msgstr "Отметить как прочитанное"+msgid "Mark as Unpaid"+msgstr "Отметить как неоплаченный"+msgid "Mark checkpoint passed"msgstr "Отметить контрольную точку как пройденную"diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex b9b3cc5f06..05f3d26453 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -6730,12 +6730,18 @@ msgstr "Satırları Şimdi Eşle"msgid "Map your current process, systems, and data"msgstr "Mevcut sürecinizi, sistemlerinizi ve verilerinizi eşleyin"+msgid "Mark as Paid"+msgstr "Ödendi Olarak İşaretle"+msgid "Mark as Planned"msgstr "Planlanmış olarak işaretle"msgid "Mark as read"msgstr "Okundu olarak işaretle"+msgid "Mark as Unpaid"+msgstr "Ödenmemiş Olarak İşaretle"+msgid "Mark checkpoint passed"msgstr "Kontrol noktasını geçildi olarak işaretle"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex c75787a9bd..05bdd494d8 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -6730,12 +6730,18 @@ msgstr "立即映射行"msgid "Map your current process, systems, and data"msgstr "映射您当前的流程、系统和数据"+msgid "Mark as Paid"+msgstr "标记为已支付"+msgid "Mark as Planned"msgstr "标记为已计划"msgid "Mark as read"msgstr "标记为已读"+msgid "Mark as Unpaid"+msgstr "标记为未支付"+msgid "Mark checkpoint passed"msgstr "标记检查点已通过"diff --git a/packages/react/src/Date/DatePicker.tsx b/packages/react/src/Date/DatePicker.tsxindex 489822ec69..36b209b26f 100644--- a/packages/react/src/Date/DatePicker.tsx+++ b/packages/react/src/Date/DatePicker.tsx@@ -27,6 +27,7 @@ const DatePicker = (isPreviewInline?: boolean;helperText?: string;closeOnSelect?: boolean;+ size?: "sm" | "md" | "lg";}) => {const state = useDatePickerState({@@ -94,11 +95,18 @@ const DatePicker = (<InputGroup{...groupProps}ref={ref}+ size={props.size}className="w-full inline-flex"isDisabled={props.isDisabled || props.isReadOnly}>- <div className="flex w-full px-4 py-2">- <DateField {...fieldProps} />+ <div+ className={+ props.size === "sm"+ ? "flex w-full items-center px-3 py-1"+ : "flex w-full px-4 py-2"+ }+ >+ <DateField {...fieldProps} size={props.size} />{state.isInvalid && (<LuBan className="!text-destructive-foreground absolute right-[12px] top-[12px]" />)}@@ -108,7 +116,11 @@ const DatePicker = (react-aria's buttonProps on FieldButton. */}<PopoverAnchor asChild><div className="flex-shrink-0 -mt-px">- <FieldButton {...buttonProps} isPressed={state.isOpen} />+ <FieldButton+ {...buttonProps}+ size={props.size}+ isPressed={state.isOpen}+ /></div></PopoverAnchor></InputGroup>