Skip to content

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

fix(sales): report actual paid amount on sales orders (#1617)

Brad Barbin85d9006e114c
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index b22b32079e..1240bd441e 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -1776,10 +1776,35 @@ export async function getSalesOrderInvoicesByIds(
) {
return client
.from("salesInvoices")
- .select("id, invoiceTotal, balance, status, currencyCode")
+ .select(
+ "id, invoiceTotal, balance, status, baseStatus, currencyCode, exchangeRate"
+ )
.in("id", invoiceIds);
}
+export async function getSalesOrderInvoicePaymentsByIds(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ invoiceIds: string[]
+) {
+ return fetchAllFromTable<{
+ targetSalesInvoiceId: string | null;
+ sourceAmount: number | null;
+ payment: { status: string } | null;
+ }>(
+ client,
+ "invoiceSettlement",
+ "targetSalesInvoiceId, sourceAmount, payment:payment!invoiceSettlement_paymentId_fkey!inner(status)",
+ (query) =>
+ query
+ .eq("companyId", companyId)
+ .eq("payment.companyId", companyId)
+ .eq("payment.status", "Posted")
+ .in("targetSalesInvoiceId", invoiceIds)
+ .order("id")
+ );
+}
+
export async function getSalesOrderLinesByItemId(
client: SupabaseClient<Database>,
itemId: string
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index fd06411ca7..c366b2df78 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -1,5 +1,5 @@
{
- "totalTools": 1552,
+ "totalTools": 1553,
"modules": 15,
"tools": [
{"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId","permission":"none","paginates":false},
@@ -1283,7 +1283,8 @@
{"name":"sales_getSalesOrderCustomerDetails","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"141326b70f84","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getSalesOrderCustomers","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"fc7a0345fc53","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getSalesOrderInvoiceLines","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"1ff852ae9154","injectAuth":"companyId","permission":"sales:view","paginates":false},
- {"name":"sales_getSalesOrderInvoicesByIds","classification":"READ","paramCount":1,"schema":"d51ae9969843","response":"7b2008a52299","injectAuth":"companyId","permission":"sales:view","paginates":false},
+ {"name":"sales_getSalesOrderInvoicePaymentsByIds","classification":"READ","paramCount":1,"schema":"d51ae9969843","response":"8d4d69c4c240","injectAuth":"companyId","permission":"sales:view","paginates":false},
+ {"name":"sales_getSalesOrderInvoicesByIds","classification":"READ","paramCount":1,"schema":"d51ae9969843","response":"59ff21b17d0d","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getSalesOrderLine","classification":"READ","paramCount":1,"schema":"58e3c9762923","response":"680c6abfc2c8","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getSalesOrderLines","classification":"READ","paramCount":1,"schema":"d160a49d6787","response":"12480eaf2ca4","injectAuth":"companyId","permission":"sales:view","paginates":false},
{"name":"sales_getSalesOrderLinesByItemId","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"12480eaf2ca4","injectAuth":"companyId","permission":"sales:view","paginates":false},
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.invoice-summary.test.ts b/apps/erp/app/routes/x+/sales-order+/$orderId.invoice-summary.test.ts
new file mode 100644
index 0000000000..5d8a31a2d3
--- /dev/null
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.invoice-summary.test.ts
@@ -0,0 +1,227 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import * as sales from "~/modules/sales";
+import { getCompanySettings } from "~/modules/settings";
+import { loader } from "./$orderId";
+
+vi.mock("@carbon/auth", () => ({
+ error: (cause: unknown, message: string) => ({ cause, message })
+}));
+vi.mock("@carbon/auth/auth.server", () => ({ requirePermissions: vi.fn() }));
+vi.mock("@carbon/auth/client.server", () => ({
+ getCarbonServiceRole: vi.fn()
+}));
+vi.mock("@carbon/auth/session.server", () => ({
+ flash: vi.fn(async () => ({}))
+}));
+vi.mock("@carbon/react", () => ({ VStack: () => null }));
+vi.mock("@lingui/core/macro", () => ({
+ msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })
+}));
+vi.mock("~/components/Layout/Panels", () => ({
+ PanelProvider: () => null,
+ ResizablePanels: () => null
+}));
+vi.mock("~/modules/sales/ui/SalesOrder", () => ({
+ SalesOrderExplorer: () => null,
+ SalesOrderHeader: () => null,
+ SalesOrderProperties: () => null
+}));
+vi.mock("~/modules/settings", () => ({ getCompanySettings: vi.fn() }));
+vi.mock("~/utils/handle", () => ({
+ detailBreadcrumb: () => undefined
+}));
+vi.mock("~/utils/path", () => ({
+ path: {
+ to: {
+ items: "/x/items",
+ salesOrders: "/x/sales-orders",
+ salesOrder: (id: string) => `/x/sales-order/${id}`
+ }
+ }
+}));
+vi.mock("~/modules/sales", () => ({
+ getCustomer: vi.fn(),
+ getOpportunity: vi.fn(),
+ getOpportunityDocuments: vi.fn(),
+ getQuote: vi.fn(),
+ getSalesOrder: vi.fn(),
+ getSalesOrderInvoiceLines: vi.fn(),
+ getSalesOrderInvoicePaymentsByIds: vi.fn(),
+ getSalesOrderInvoicesByIds: vi.fn(),
+ getSalesOrderLines: vi.fn(),
+ getSalesOrderRelatedItems: vi.fn()
+}));
+
+const getSalesOrderInvoicePaymentsByIds = vi.mocked(
+ sales.getSalesOrderInvoicePaymentsByIds
+);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(requirePermissions).mockResolvedValue({
+ client: {},
+ companyId: "company-1"
+ } as Awaited<ReturnType<typeof requirePermissions>>);
+ vi.mocked(getCarbonServiceRole).mockReturnValue({} as never);
+ vi.mocked(sales.getSalesOrder).mockResolvedValue({
+ data: {
+ id: "order-1",
+ companyId: "company-1",
+ opportunityId: "opportunity-1",
+ customerId: "customer-1",
+ currencyCode: "USD"
+ },
+ error: null
+ } as never);
+ vi.mocked(sales.getSalesOrderLines).mockResolvedValue({
+ data: [],
+ error: null
+ } as never);
+ vi.mocked(sales.getOpportunity).mockResolvedValue({
+ data: { id: "opportunity-1", quotes: [] },
+ error: null
+ } as never);
+ vi.mocked(sales.getCustomer).mockResolvedValue({
+ data: { defaultCc: [] },
+ error: null
+ } as never);
+ vi.mocked(getCompanySettings).mockResolvedValue({
+ data: { defaultCustomerCc: [] },
+ error: null
+ } as never);
+ vi.mocked(sales.getSalesOrderInvoiceLines).mockResolvedValue({
+ data: [{ invoiceId: "invoice-1" }],
+ error: null
+ } as never);
+ vi.mocked(sales.getSalesOrderInvoicesByIds).mockResolvedValue({
+ data: [
+ {
+ id: "invoice-1",
+ invoiceTotal: 100,
+ balance: 0,
+ status: "Paid",
+ baseStatus: "Submitted",
+ currencyCode: "USD",
+ exchangeRate: 1
+ }
+ ],
+ error: null
+ } as never);
+ getSalesOrderInvoicePaymentsByIds.mockResolvedValue({
+ data: [
+ {
+ targetSalesInvoiceId: "invoice-1",
+ sourceAmount: 80,
+ payment: { status: "Posted" }
+ }
+ ],
+ count: 1,
+ error: null
+ });
+ vi.mocked(sales.getOpportunityDocuments).mockResolvedValue({
+ data: [],
+ error: null
+ } as never);
+ vi.mocked(sales.getSalesOrderRelatedItems).mockResolvedValue({
+ data: [],
+ error: null
+ } as never);
+});
+
+describe("sales order invoice summary", () => {
+ it("counts posted cash principal instead of discounts and write-offs", async () => {
+ const result = await loader({
+ request: new Request("http://localhost/x/sales-order/order-1"),
+ params: { orderId: "order-1" },
+ context: {}
+ } as unknown as Parameters<typeof loader>[0]);
+
+ expect(result.invoiceSummary).toEqual({
+ invoicedAmount: 100,
+ paidAmount: 80,
+ currencyMismatchCount: 0
+ });
+ });
+
+ it("preserves legacy invoices explicitly marked paid", async () => {
+ vi.mocked(sales.getSalesOrderInvoicesByIds).mockResolvedValue({
+ data: [
+ {
+ id: "invoice-1",
+ invoiceTotal: 100,
+ balance: 0,
+ status: "Paid",
+ baseStatus: "Paid",
+ currencyCode: "USD",
+ exchangeRate: 1
+ }
+ ],
+ error: null
+ } as never);
+ getSalesOrderInvoicePaymentsByIds.mockResolvedValue({
+ data: [],
+ count: 0,
+ error: null
+ });
+
+ const result = await loader({
+ request: new Request("http://localhost/x/sales-order/order-1"),
+ params: { orderId: "order-1" },
+ context: {}
+ } as unknown as Parameters<typeof loader>[0]);
+
+ expect(result.invoiceSummary.paidAmount).toBe(100);
+ });
+
+ it("returns invoice and payment totals in the order currency", async () => {
+ vi.mocked(sales.getSalesOrder).mockResolvedValue({
+ data: {
+ id: "order-1",
+ companyId: "company-1",
+ opportunityId: "opportunity-1",
+ customerId: "customer-1",
+ currencyCode: "EUR"
+ },
+ error: null
+ } as never);
+ vi.mocked(sales.getSalesOrderInvoicesByIds).mockResolvedValue({
+ data: [
+ {
+ id: "invoice-1",
+ invoiceTotal: 100,
+ balance: 50,
+ status: "Partially Paid",
+ baseStatus: "Submitted",
+ currencyCode: "EUR",
+ exchangeRate: 0.8
+ }
+ ],
+ error: null
+ } as never);
+ getSalesOrderInvoicePaymentsByIds.mockResolvedValue({
+ data: [
+ {
+ targetSalesInvoiceId: "invoice-1",
+ sourceAmount: 40,
+ payment: { status: "Posted" }
+ }
+ ],
+ count: 1,
+ error: null
+ });
+
+ const result = await loader({
+ request: new Request("http://localhost/x/sales-order/order-1"),
+ params: { orderId: "order-1" },
+ context: {}
+ } as unknown as Parameters<typeof loader>[0]);
+
+ expect(result.invoiceSummary).toEqual({
+ invoicedAmount: 80,
+ paidAmount: 40,
+ currencyMismatchCount: 0
+ });
+ });
+});
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.tsx
index 184a87d4f0..2b2ef393c8 100644
--- a/apps/erp/app/routes/x+/sales-order+/$orderId.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.tsx
@@ -14,6 +14,7 @@ import {
getQuote,
getSalesOrder,
getSalesOrderInvoiceLines,
+ getSalesOrderInvoicePaymentsByIds,
getSalesOrderInvoicesByIds,
getSalesOrderLines,
getSalesOrderRelatedItems
@@ -118,7 +119,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
let currencyMismatchCount = 0;
if (invoiceIds.length > 0) {
- const invoices = await getSalesOrderInvoicesByIds(client, invoiceIds);
+ const [invoices, payments] = await Promise.all([
+ getSalesOrderInvoicesByIds(client, invoiceIds),
+ getSalesOrderInvoicePaymentsByIds(client, companyId, invoiceIds)
+ ]);
if (invoices.error) {
throw redirect(
@@ -130,6 +134,26 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
+ if (payments.error) {
+ throw redirect(
+ path.to.salesOrder(orderId),
+ await flash(
+ request,
+ error(payments.error, "Failed to load sales invoice payments")
+ )
+ );
+ }
+
+ const paidByInvoiceId = new Map<string, number>();
+ for (const payment of payments.data ?? []) {
+ if (!payment.targetSalesInvoiceId) continue;
+ paidByInvoiceId.set(
+ payment.targetSalesInvoiceId,
+ (paidByInvoiceId.get(payment.targetSalesInvoiceId) ?? 0) +
+ (payment.sourceAmount ?? 0)
+ );
+ }
+
const orderCurrency = salesOrder.data?.currencyCode;
for (const invoice of invoices.data ?? []) {
@@ -152,14 +176,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
continue;
}
- invoicedAmount += invoiceTotal;
-
- // Paid = the settled portion in document currency (invoiceTotal - balance
- // from the salesInvoices view, which only counts posted payments/memos).
- // A fully-Paid invoice reports balance 0, a partially-paid one reports its
- // outstanding remainder — so partial payments are counted, not ignored.
- const balance = invoice.balance ?? 0;
- paidAmount += invoiceTotal - balance;
+ const invoiceTotalInOrderCurrency =
+ invoiceTotal * (invoice.exchangeRate ?? 1);
+ invoicedAmount += invoiceTotalInOrderCurrency;
+ if (invoice.baseStatus === "Paid") {
+ paidAmount += invoiceTotalInOrderCurrency;
+ } else if (invoice.id) {
+ paidAmount += paidByInvoiceId.get(invoice.id) ?? 0;
+ }
}
}