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(invoicing): save the invoice customer instead of the sold-to customer
naveenkash9fde08dc2654
diff --git a/apps/erp/app/modules/invoicing/invoicing.models.test.ts b/apps/erp/app/modules/invoicing/invoicing.models.test.tsindex a802ddd057..49c443fa4b 100644--- a/apps/erp/app/modules/invoicing/invoicing.models.test.ts+++ b/apps/erp/app/modules/invoicing/invoicing.models.test.ts@@ -7,7 +7,9 @@ import {invoiceSettlementValidator,isInvoicePayable,memoValidator,- paymentValidator+ paymentValidator,+ purchaseInvoiceSupplierChange,+ salesInvoiceCustomerChange} from "./invoicing.models";describe("paymentValidator", () => {@@ -347,3 +349,69 @@ describe("memoValidator", () => {).toBe(false);});});++describe("salesInvoiceCustomerChange", () => {+ it("sets the invoice customer and clears its contact and location", () => {+ expect(salesInvoiceCustomerChange("cust_billing", null)).toEqual({+ invoiceCustomerId: "cust_billing",+ invoiceCustomerContactId: null,+ invoiceCustomerLocationId: null+ });+ });++ it("never writes the sold-to customer", () => {+ for (const currency of [+ null,+ { currencyCode: "EUR", exchangeRate: 0.92 }+ ]) {+ expect(+ salesInvoiceCustomerChange("cust_billing", currency)+ ).not.toHaveProperty("customerId");+ }+ });++ it("keeps the invoice currency when the customer has none", () => {+ const change = salesInvoiceCustomerChange("cust_billing", null);+ expect(change).not.toHaveProperty("currencyCode");+ expect(change).not.toHaveProperty("exchangeRate");+ });++ it("takes the customer's currency and rate when it has one", () => {+ expect(+ salesInvoiceCustomerChange("cust_billing", {+ currencyCode: "EUR",+ exchangeRate: 0.92+ })+ ).toMatchObject({ currencyCode: "EUR", exchangeRate: 0.92 });+ });+});++describe("purchaseInvoiceSupplierChange", () => {+ it("sets the invoice supplier and clears its contact and location", () => {+ expect(purchaseInvoiceSupplierChange("supp_billing", null)).toEqual({+ invoiceSupplierId: "supp_billing",+ invoiceSupplierContactId: null,+ invoiceSupplierLocationId: null+ });+ });++ it("never writes the supplier", () => {+ for (const currency of [+ null,+ { currencyCode: "EUR", exchangeRate: 0.92 }+ ]) {+ expect(+ purchaseInvoiceSupplierChange("supp_billing", currency)+ ).not.toHaveProperty("supplierId");+ }+ });++ it("takes the supplier's currency and rate when it has one", () => {+ expect(+ purchaseInvoiceSupplierChange("supp_billing", {+ currencyCode: "EUR",+ exchangeRate: 0.92+ })+ ).toMatchObject({ currencyCode: "EUR", exchangeRate: 0.92 });+ });+});diff --git a/apps/erp/app/modules/invoicing/invoicing.models.ts b/apps/erp/app/modules/invoicing/invoicing.models.tsindex c0c074b35e..2dd00c1c40 100644--- a/apps/erp/app/modules/invoicing/invoicing.models.ts+++ b/apps/erp/app/modules/invoicing/invoicing.models.ts@@ -76,6 +76,42 @@ export function isSalesInvoiceLocked(return status !== null && status !== undefined && status !== "Draft";}+type InvoiceCurrency = { currencyCode: string; exchangeRate: number };++/**+ * The columns written when a sales invoice's invoice customer changes. It+ * never writes `customerId`, the sold-to customer. A customer with no+ * currency (`currency` null) leaves the invoice's currency as it is.+ */+export function salesInvoiceCustomerChange(+ invoiceCustomerId: string,+ currency: InvoiceCurrency | null+) {+ return {+ invoiceCustomerId,+ invoiceCustomerContactId: null,+ invoiceCustomerLocationId: null,+ ...currency+ };+}++/**+ * The columns written when a purchase invoice's invoice supplier changes. It+ * never writes `supplierId`. A supplier with no currency (`currency` null)+ * leaves the invoice's currency as it is.+ */+export function purchaseInvoiceSupplierChange(+ invoiceSupplierId: string,+ currency: InvoiceCurrency | null+) {+ return {+ invoiceSupplierId,+ invoiceSupplierContactId: null,+ invoiceSupplierLocationId: null,+ ...currency+ };+}+export const purchaseInvoiceValidator = z.object({id: zfd.text(z.string().optional()),invoiceId: zfd.text(z.string().optional()),diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.test.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.test.tsxnew file mode 100644index 0000000000..88c32703c0--- /dev/null+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.test.tsx@@ -0,0 +1,95 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { ReactNode } from "react";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it, vi } from "vitest";++vi.mock("@carbon/auth", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@carbon/auth")>()),+ useCarbon: () => ({ carbon: null })+}));+vi.mock("@carbon/form", () => ({+ ValidatedForm: ({ children }: { children: ReactNode }) =>+ createElement("form", null, children)+}));+vi.mock("@carbon/react", () => {+ const Box = ({ children }: { children?: ReactNode }) =>+ createElement("div", null, children);+ return {+ Card: Box,+ CardContent: Box,+ CardDescription: Box,+ CardFooter: Box,+ CardHeader: Box,+ CardTitle: Box,+ VStack: Box,+ cn: (...classes: unknown[]) => classes.filter(Boolean).join(" "),+ toast: { error: vi.fn() }+ };+});+vi.mock("@lingui/react/macro", () => ({+ Trans: ({ children }: { children: ReactNode }) => children,+ useLingui: () => ({+ t: (parts: TemplateStringsArray, ...values: unknown[]) =>+ parts.reduce(+ (result, part, index) => result + part + (values[index] ?? ""),+ ""+ )+ })+}));+// The two pickers under test render the customer they are scoped to.+vi.mock("~/components/Form", () => {+ const Field = () => null;+ const ScopedPicker = ({+ name,+ customer+ }: {+ name: string;+ customer?: string;+ }) => createElement("input", { name, "data-customer": customer ?? "" });+ return {+ Currency: Field,+ Customer: Field,+ CustomerContact: ScopedPicker,+ CustomerLocation: ScopedPicker,+ CustomFormFields: Field,+ DatePicker: Field,+ Hidden: Field,+ Input: Field,+ Location: Field,+ SequenceOrCustomId: Field,+ Submit: Field+ };+});+vi.mock("~/components/Form/PaymentTerm", () => ({ default: () => null }));+vi.mock("~/hooks", () => ({+ usePermissions: () => ({ can: () => true }),+ useRouteData: () => undefined+}));+vi.mock("~/modules/invoicing", () => import("../../invoicing.models"));++import SalesInvoiceForm from "./SalesInvoiceForm";++function render() {+ return renderToStaticMarkup(+ createElement(SalesInvoiceForm, {+ initialValues: {+ customerId: "cust_sold_to",+ invoiceCustomerId: "cust_billing",+ locationId: "loc_1"+ }+ })+ );+}++describe("SalesInvoiceForm", () => {+ it.each([+ "invoiceCustomerContactId",+ "invoiceCustomerLocationId"+ ])("scopes %s to the invoice customer, not the sold-to customer", (name) => {+ expect(render()).toContain(`name="${name}" data-customer="cust_billing"`);+ });+});diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.tsxindex 136316cc0c..f0901996e7 100644--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.tsx+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceForm.tsx@@ -70,18 +70,11 @@ const SalesInvoiceForm = ({ initialValues }: SalesInvoiceFormProps) => {paymentTermId: initialValues.paymentTermId});- const [customer, setCustomer] = useState<{- id: string | undefined;- }>({- id: initialValues.customerId- });-const onCustomerChange = async (newValue: {value: string | undefined;} | null) => {- setCustomer({ id: newValue?.value });if (newValue?.value !== invoiceCustomer.id) {onInvoiceCustomerChange(newValue);}@@ -223,7 +216,7 @@ const SalesInvoiceForm = ({ initialValues }: SalesInvoiceFormProps) => {<CustomerLocationname="invoiceCustomerLocationId"label={t`Invoice Customer Location`}- customer={customer.id}+ customer={invoiceCustomer.id}value={invoiceCustomer.invoiceCustomerLocationId}onChange={(newValue) => {if (newValue?.id) {@@ -237,7 +230,7 @@ const SalesInvoiceForm = ({ initialValues }: SalesInvoiceFormProps) => {<CustomerContactname="invoiceCustomerContactId"label={t`Invoice Customer Contact`}- customer={customer.id}+ customer={invoiceCustomer.id}value={invoiceCustomer.invoiceCustomerContactId}onChange={(newValue) => {if (newValue?.id) {diff --git a/apps/erp/app/routes/x+/purchase-invoice+/update.tsx b/apps/erp/app/routes/x+/purchase-invoice+/update.tsxindex b1c8eb8801..9cf867b11b 100644--- a/apps/erp/app/routes/x+/purchase-invoice+/update.tsx+++ b/apps/erp/app/routes/x+/purchase-invoice+/update.tsx@@ -3,12 +3,13 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import { unchecked } from "@carbon/utils";+import { datetime, unchecked } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { getExchangeRate } from "~/modules/accounting";import {computeInvoiceDateDue,- isPurchaseInvoiceLocked+ isPurchaseInvoiceLocked,+ purchaseInvoiceSupplierChange} from "~/modules/invoicing";import { requireUnlockedBulk } from "~/utils/lockedGuard.server";@@ -46,42 +47,46 @@ export async function action({ request }: ActionFunctionArgs) {}switch (field) {- case "invoiceSupplierId":- let currencyCode: string | undefined;- if (value && ids.length === 1) {- const supplier = await client- ?.from("supplier")- .select("currencyCode")- .eq("id", value)- .single();+ case "invoiceSupplierId": {+ if (!value) {+ return {+ error: { message: "Invoice supplier is required" },+ data: null+ };+ }- if (supplier.data?.currencyCode) {- currencyCode = supplier.data.currencyCode;- const rate = await getExchangeRate(client, companyId, currencyCode);- if (rate.error) return rate;- return await client- .from("purchaseInvoice")- .update({- invoiceSupplierId: value ?? undefined,- invoiceSupplierContactId: null,- invoiceSupplierLocationId: null,- currencyCode: currencyCode ?? undefined,- exchangeRate: rate.data,- updatedBy: userId,- updatedAt: new Date().toISOString()- })- .in("id", ids as string[]);- }+ const supplier = await client+ .from("supplier")+ .select("currencyCode")+ .eq("id", value)+ .eq("companyId", companyId)+ .single();+ if (supplier.error) return supplier;++ let currency: { currencyCode: string; exchangeRate: number } | null =+ null;+ if (supplier.data.currencyCode) {+ const rate = await getExchangeRate(+ client,+ companyId,+ supplier.data.currencyCode+ );+ if (rate.error) return rate;+ currency = {+ currencyCode: supplier.data.currencyCode,+ exchangeRate: rate.data+ };}return await client.from("purchaseInvoice").update({- supplierId: value ?? undefined,+ ...purchaseInvoiceSupplierChange(value, currency),updatedBy: userId,- updatedAt: new Date().toISOString()+ updatedAt: datetime.timestamp()}).in("id", ids as string[]);+ }case "dateIssued":if (ids.length === 1) {const invoice = await clientdiff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.details.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.details.tsxindex c018063a52..6264e519dc 100644--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.details.tsx+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.details.tsx@@ -2,17 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { assertIsPost, error, success } from "@carbon/auth";+import { error } 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 { JSONContent } from "@carbon/react";import { redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";import type { FileObject } from "@supabase/storage-js";import { useRef } from "react";import { Fragment } from "react/jsx-runtime";-import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import type { LoaderFunctionArgs } from "react-router";import { useLoaderData, useParams } from "react-router";import { DeferredFiles } from "~/components";import { useRouteData, useUser } from "~/hooks";@@ -24,10 +23,7 @@ import type {import {getInvoiceSettlementsForInvoice,getSalesInvoice,- InvoicePaymentsPanel,- isSalesInvoiceLocked,- salesInvoiceValidator,- updateSalesInvoice+ InvoicePaymentsPanel} from "~/modules/invoicing";import type { SalesInvoiceShipmentFormRef } from "~/modules/invoicing/ui/SalesInvoice/SalesInvoiceShipmentForm";import SalesInvoiceShipmentForm from "~/modules/invoicing/ui/SalesInvoice/SalesInvoiceShipmentForm";@@ -37,8 +33,7 @@ import {OpportunityDocuments,OpportunityNotes} from "~/modules/sales/ui/Opportunity";-import { getCustomFields, setCustomFields } from "~/utils/form";-import { requireUnlocked } from "~/utils/lockedGuard.server";+import { getCustomFields } from "~/utils/form";import { path } from "~/utils/path";export async function loader({ request, params }: LoaderFunctionArgs) {@@ -66,80 +61,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {};}-export async function action({ request, params }: ActionFunctionArgs) {- assertIsPost(request);-- const { invoiceId: id } = params;- if (!id) throw new Error("Could not find invoiceId");-- // Check if SI is locked- const { client: viewClient } = await requirePermissions(request, {- view: "invoicing"- });-- const invoice = await getSalesInvoice(viewClient, id);- if (invoice.error) {- throw redirect(- path.to.salesInvoice(id),- await flash(request, error(invoice.error, "Failed to load sales invoice"))- );- }-- await requireUnlocked({- request,- isLocked: isSalesInvoiceLocked(invoice.data?.status),- redirectTo: path.to.salesInvoice(id),- message: "Cannot modify a locked sales invoice. Reopen it first."- });-- const { client, userId } = await requirePermissions(request, {- update: "invoicing"- });-- const formData = await request.formData();- const validation = await validator(salesInvoiceValidator).validate(formData);-- if (validation.error) {- return validationError(validation.error);- }-- const { invoiceId, ...d } = validation.data;- if (!invoiceId) throw new Error("Could not find invoiceId");-- const result = await updateSalesInvoice(client, {- id,- invoiceId,- customerId: d.customerId,- customerReference: d.customerReference || null,- paymentTermId: d.paymentTermId || null,- currencyCode: d.currencyCode,- locationId: d.locationId,- invoiceCustomerId: d.invoiceCustomerId || null,- invoiceCustomerContactId: d.invoiceCustomerContactId || null,- invoiceCustomerLocationId: d.invoiceCustomerLocationId || null,- dateIssued: d.dateIssued || null,- dateDue: d.dateDue || null,- exchangeRate: d.exchangeRate,- exchangeRateUpdatedAt: d.exchangeRateUpdatedAt,- customFields: setCustomFields(formData),- updatedBy: userId- });- if (result.error) {- throw redirect(- path.to.salesInvoice(id),- await flash(- request,- error(result.error, "Failed to update sales invoice")- )- );- }-- throw redirect(- path.to.salesInvoice(id),- await flash(request, success("Updated sales invoice"))- );-}-export default function SalesInvoiceBasicRoute() {const { t } = useLingui();const { internalNotes, paymentApplications } = useLoaderData<typeof loader>();@@ -165,20 +86,6 @@ export default function SalesInvoiceBasicRoute() {shipmentFormRef.current?.focusShippingCost();};- const initialValues = {- id: salesInvoice.id ?? "",- invoiceId: salesInvoice.invoiceId ?? "",- customerId: salesInvoice.customerId ?? "",- customerReference: salesInvoice.customerReference ?? "",- invoiceCustomerId: salesInvoice.invoiceCustomerId ?? "",- paymentTermId: salesInvoice.paymentTermId ?? "",- currencyCode: salesInvoice.currencyCode ?? "",- dateIssued: salesInvoice.dateIssued ?? "",- dateDue: salesInvoice.dateDue ?? "",- status: salesInvoice.status ?? ("Draft" as "Draft"),- ...getCustomFields(salesInvoice.customFields)- };-const shipmentInitialValues = {id: salesInvoiceShipment.id,locationId: salesInvoiceShipment.locationId ?? "",@@ -197,7 +104,7 @@ export default function SalesInvoiceBasicRoute() {<SalesInvoiceSummary onEditShippingCost={handleEditShippingCost} /><InvoicePaymentsPanel rows={paymentApplications} /><OpportunityNotes- key={`notes-${initialValues.id}`}+ key={`notes-${salesInvoice.id}`}id={invoiceId}title={t`Notes`}table="salesInvoice"@@ -217,7 +124,7 @@ export default function SalesInvoiceBasicRoute() {key={`shipment-${invoiceId}`}ref={shipmentFormRef}initialValues={shipmentInitialValues}- currencyCode={initialValues.currencyCode || company.baseCurrencyCode}+ currencyCode={salesInvoice.currencyCode || company.baseCurrencyCode}defaultCollapsed={false}/></Fragment>diff --git a/apps/erp/app/routes/x+/sales-invoice+/update.tsx b/apps/erp/app/routes/x+/sales-invoice+/update.tsxindex c9c875ae3c..dda805024d 100644--- a/apps/erp/app/routes/x+/sales-invoice+/update.tsx+++ b/apps/erp/app/routes/x+/sales-invoice+/update.tsx@@ -3,12 +3,13 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import { unchecked } from "@carbon/utils";+import { datetime, unchecked } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { getExchangeRate } from "~/modules/accounting";import {computeInvoiceDateDue,- isSalesInvoiceLocked+ isSalesInvoiceLocked,+ salesInvoiceCustomerChange} from "~/modules/invoicing";import { requireUnlockedBulk } from "~/utils/lockedGuard.server";@@ -45,42 +46,46 @@ export async function action({ request }: ActionFunctionArgs) {}switch (field) {- case "invoiceCustomerId":- let currencyCode: string | undefined;- if (value && ids.length === 1) {- const customer = await client- ?.from("customer")- .select("currencyCode")- .eq("id", value)- .single();+ case "invoiceCustomerId": {+ if (!value) {+ return {+ error: { message: "Invoice customer is required" },+ data: null+ };+ }- if (customer.data?.currencyCode) {- currencyCode = customer.data.currencyCode;- const rate = await getExchangeRate(client, companyId, currencyCode);- if (rate.error) return rate;- return await client- .from("salesInvoice")- .update({- invoiceCustomerId: value ?? undefined,- invoiceCustomerContactId: null,- invoiceCustomerLocationId: null,- currencyCode: currencyCode ?? undefined,- exchangeRate: rate.data,- updatedBy: userId,- updatedAt: new Date().toISOString()- })- .in("id", ids as string[]);- }+ const customer = await client+ .from("customer")+ .select("currencyCode")+ .eq("id", value)+ .eq("companyId", companyId)+ .single();+ if (customer.error) return customer;++ let currency: { currencyCode: string; exchangeRate: number } | null =+ null;+ if (customer.data.currencyCode) {+ const rate = await getExchangeRate(+ client,+ companyId,+ customer.data.currencyCode+ );+ if (rate.error) return rate;+ currency = {+ currencyCode: customer.data.currencyCode,+ exchangeRate: rate.data+ };}return await client.from("salesInvoice").update({- customerId: value ?? undefined,+ ...salesInvoiceCustomerChange(value, currency),updatedBy: userId,- updatedAt: new Date().toISOString()+ updatedAt: datetime.timestamp()}).in("id", ids as string[]);+ }case "dateIssued":if (ids.length === 1) {const invoice = await client