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.

add invoiced and paid amounts to sales order summary

Atharv95387524d369
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index 37ea263d62..b0d7601fc5 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -1331,6 +1331,16 @@ export async function getSalesOrderLines(
.order("itemReadableId", { ascending: true });
}
+export async function getSalesOrderInvoiceLines(
+ client: SupabaseClient<Database>,
+ salesOrderId: string
+) {
+ return client
+ .from("salesInvoiceLine")
+ .select("invoiceId")
+ .eq("salesOrderId", salesOrderId);
+}
+
export async function getSalesOrderLinesByItemId(
client: SupabaseClient<Database>,
itemId: string
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx
index 2f2a632c31..f4360baa11 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx
@@ -67,6 +67,11 @@ const SalesOrderSummary = ({
lines: SalesOrderLine[];
customer: Customer;
quote: Quotation;
+ invoiceSummary: {
+ invoicedAmount: number;
+ paidAmount: number;
+ currencyMismatchCount: number;
+ };
}>(path.to.salesOrder(orderId));
const salesOrderToJobsModal = useDisclosure();
@@ -263,6 +268,39 @@ const SalesOrderSummary = ({
locales={locale}
/>
</HStack>
+ <div className="h-px bg-border my-2 w-full" />
+ <HStack className="justify-between text-base text-muted-foreground w-full">
+ <span>Invoiced Amount:</span>
+ <MotionNumber
+ value={routeData?.invoiceSummary?.invoicedAmount ?? 0}
+ format={{
+ style: "currency",
+ currency: routeData?.salesOrder?.currencyCode ?? "USD"
+ }}
+ locales={locale}
+ />
+ </HStack>
+ <HStack className="justify-between text-base text-muted-foreground w-full">
+ <span>Paid Amount:</span>
+ <MotionNumber
+ value={routeData?.invoiceSummary?.paidAmount ?? 0}
+ format={{
+ style: "currency",
+ currency: routeData?.salesOrder?.currencyCode ?? "USD"
+ }}
+ locales={locale}
+ />
+ </HStack>
+ {(routeData?.invoiceSummary?.currencyMismatchCount ?? 0) > 0 && (
+ <span className="text-xs text-muted-foreground">
+ Excludes {routeData?.invoiceSummary?.currencyMismatchCount}{" "}
+ invoice
+ {(routeData?.invoiceSummary?.currencyMismatchCount ?? 0) > 1
+ ? "s"
+ : ""}{" "}
+ in a different currency.
+ </span>
+ )}
</VStack>
</CardContent>
</Card>
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.tsx
index fa15e056ef..083db9d652 100644
--- a/apps/erp/app/routes/x+/sales-order+/$orderId.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.tsx
@@ -6,12 +6,14 @@ import { VStack } from "@carbon/react";
import type { LoaderFunctionArgs } from "react-router";
import { Outlet, redirect, useParams } from "react-router";
import { PanelProvider, ResizablePanels } from "~/components/Layout/Panels";
+import { getSalesInvoice } from "~/modules/invoicing";
import {
getCustomer,
getOpportunity,
getOpportunityDocuments,
getQuote,
getSalesOrder,
+ getSalesOrderInvoiceLines,
getSalesOrderLines,
getSalesOrderRelatedItems
} from "~/modules/sales";
@@ -44,6 +46,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
getSalesOrderLines(client, orderId)
]);
+ if (salesOrder.error) {
+ throw redirect(
+ path.to.items,
+ await flash(request, error(salesOrder.error, "Failed to load salesOrder"))
+ );
+ }
+
const opportunity = await getOpportunity(
client,
salesOrder.data?.opportunityId ?? null
@@ -55,24 +64,81 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
if (!opportunity.data) throw new Error("Failed to get opportunity record");
- if (salesOrder.error) {
- throw redirect(
- path.to.items,
- await flash(request, error(salesOrder.error, "Failed to load salesOrder"))
- );
- }
-
const serviceRole = getCarbonServiceRole();
- const [quote, customer, companySettings] = await Promise.all([
+ const [quote, customer, companySettings, invoiceLines] = await Promise.all([
opportunity.data.quotes[0]?.id
? getQuote(client, opportunity.data.quotes[0].id)
: Promise.resolve(null),
salesOrder.data?.customerId
? getCustomer(client, salesOrder.data.customerId)
: Promise.resolve(null),
- getCompanySettings(serviceRole, companyId)
+ getCompanySettings(serviceRole, companyId),
+ getSalesOrderInvoiceLines(client, orderId)
]);
+ if (invoiceLines.error) {
+ throw redirect(
+ path.to.salesOrder(orderId),
+ await flash(
+ request,
+ error(invoiceLines.error, "Failed to load linked sales invoices")
+ )
+ );
+ }
+
+ const invoiceIds = Array.from(
+ new Set(
+ (invoiceLines.data ?? []).map((line) => line.invoiceId).filter(Boolean)
+ )
+ ) as string[];
+
+ let invoicedAmount = 0;
+ let paidAmount = 0;
+ let currencyMismatchCount = 0;
+
+ if (invoiceIds.length > 0) {
+ const invoiceResponses = await Promise.all(
+ invoiceIds.map((invoiceId) => getSalesInvoice(client, invoiceId))
+ );
+
+ const invoiceError = invoiceResponses.find(
+ (invoice) => invoice.error
+ )?.error;
+
+ if (invoiceError) {
+ throw redirect(
+ path.to.salesOrder(orderId),
+ await flash(
+ request,
+ error(invoiceError, "Failed to load sales invoice totals")
+ )
+ );
+ }
+
+ const orderCurrency = salesOrder.data?.currencyCode;
+
+ for (const invoice of invoiceResponses.map((response) => response.data)) {
+ if (!invoice) continue;
+ const invoiceTotal = invoice.invoiceTotal ?? 0;
+ const invoiceCurrency = invoice.currencyCode;
+
+ // Avoid mixing currencies in the same displayed number.
+ if (
+ orderCurrency &&
+ invoiceCurrency &&
+ invoiceCurrency !== orderCurrency
+ ) {
+ currencyMismatchCount += 1;
+ continue;
+ }
+
+ invoicedAmount += invoiceTotal;
+ if (invoice.status === "Paid") {
+ paidAmount += invoiceTotal;
+ }
+ }
+ }
+
const defaultCc = customer?.data?.defaultCc?.length
? customer.data.defaultCc
: (companySettings.data?.defaultCustomerCc ?? []);
@@ -89,6 +155,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
opportunity: opportunity.data,
customer: customer?.data ?? null,
quote: quote?.data ?? null,
+ invoiceSummary: {
+ invoicedAmount,
+ paidAmount,
+ currencyMismatchCount
+ },
originatedFromQuote: !!opportunity.data.quotes[0]?.id,
defaultCc
};