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
// 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 { assertIsPost, error, notFound, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
import { redirect } from "@carbon/utils";
import { msg } from "@lingui/core/macro";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { data, useLoaderData } from "react-router";
import { DocumentPage, DocumentSidebar } from "~/components/DocumentPage";
import { memoValidator } from "~/modules/invoicing/invoicing.models";
import {
getMemo,
getMemoApplications,
getSettlementRelatedItems,
upsertMemo
} from "~/modules/invoicing/invoicing.service";
import {
MemoApplicationsPanel,
MemoDocuments,
MemoForm,
MemoHeader
} from "~/modules/invoicing/ui";
import { setCustomFields } from "~/utils/form";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
// The memo detail page is one shared URL (so every inbound path.to.memo(id)
// link keeps working), but its crumb is party-aware: supplier memos are Vendor
// Credits (AP), customer memos are Credit Memos (AR), followed by the memo id.
export const handle: Handle = {
breadcrumb: (_params: unknown, data: unknown) => {
const memo = (
data as
| { memo?: { supplierId?: string | null; memoId?: string } }
| undefined
)?.memo;
return [
memo?.supplierId
? { breadcrumb: msg`Supplier Credits`, to: path.to.supplierCredits }
: { breadcrumb: msg`Credit Memos`, to: path.to.creditMemos },
{ breadcrumb: memo?.memoId }
];
},
module: "invoicing"
};
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
view: "invoicing"
});
const { memoId } = params;
if (!memoId) throw notFound("Missing memoId");
const memo = await getMemo(client, memoId, companyId);
if (memo.error || !memo.data) {
throw redirect(
path.to.invoicing,
await flash(request, error(memo.error, "Failed to load memo"))
);
}
const applications = await getMemoApplications(client, companyId, memoId);
return {
memo: memo.data,
applications: applications.data ?? [],
relatedItems: getSettlementRelatedItems(client, companyId, {
journalId: memo.data.journalId,
targets: (applications.data ?? []).map(({ target }) => ({
targetSalesInvoiceId: target.type === "salesInvoice" ? target.id : null,
targetPurchaseInvoiceId:
target.type === "purchaseInvoice" ? target.id : null,
targetMemoId: target.type === "memo" ? target.id : null,
targetReimbursementId:
target.type === "reimbursement" ? target.id : null
})),
salesReturnOrderId: memo.data.salesReturnOrderId,
purchaseReturnOrderId: memo.data.purchaseReturnOrderId,
rentalAgreementId: memo.data.rentalAgreementId
})
};
}
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
const { client, companyId, userId } = await requirePermissions(request, {
update: "invoicing"
});
const { memoId } = params;
if (!memoId) throw notFound("Missing memoId");
const formData = await request.formData();
const validation = await validator(memoValidator).validate(formData);
if (validation.error) {
return validationError(validation.error);
}
// Only Draft memos are editable; Posted/Voided are immutable.
const existing = await getMemo(client, memoId, companyId);
if (existing.error || !existing.data) {
throw redirect(
path.to.invoicing,
await flash(request, error(existing.error, "Failed to load memo"))
);
}
if (existing.data.status !== "Draft") {
throw redirect(
path.to.memo(memoId),
await flash(request, error(null, "Only draft memos can be edited"))
);
}
const { id: _omitId, ...memoData } = validation.data;
const update = await upsertMemo(client, {
...memoData,
id: memoId,
updatedBy: userId,
customFields: setCustomFields(formData)
});
if (update.error) {
return data(
{},
await flash(request, error(update.error, "Failed to update memo"))
);
}
throw redirect(
path.to.memo(memoId),
await flash(request, success("Memo updated"))
);
}
export default function MemoDetailRoute() {
const { memo, applications } = useLoaderData<typeof loader>();
const initialValues = {
id: memo.id,
memoId: memo.memoId,
direction: memo.direction,
customerId: memo.customerId ?? "",
supplierId: memo.supplierId ?? "",
memoDate: memo.memoDate,
currencyCode: memo.currencyCode ?? "",
exchangeRate: Number(memo.exchangeRate ?? 1),
amount: Number(memo.amount ?? 0),
reference: memo.reference ?? "",
notes: memo.notes ?? "",
status: memo.status ?? undefined
};
const type = memo.supplierId ? "supplierCredit" : "creditMemo";
return (
<DocumentPage
header={<MemoHeader />}
sidebar={
<DocumentSidebar
documents={<MemoDocuments />}
activity={{
entityType: "memo",
entityId: memo.id,
refreshKey: `${memo.updatedAt ?? ""}:${memo.status}`
}}
/>
}
>
<MemoForm initialValues={initialValues} type={type} />
<MemoApplicationsPanel
rows={applications}
currencyCode={memo.currencyCode ?? "USD"}
/>
</DocumentPage>
);
}