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.

feat: add duplicate purchase order functionality

naveenkashcbdf80d98817
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index 5579f632c0..c876aada7e 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -93,6 +93,98 @@ export async function deletePurchaseOrderLine(
.eq("id", purchaseOrderLineId);
}
+// Creates a new Draft PO header + delivery + payment via insertPurchaseOrder
+// and copies the source PO's lines into it. Receipt/invoice progress is
+// reset; only the order/line definition is duplicated.
+export async function duplicatePurchaseOrder(
+ client: SupabaseClient<Database>,
+ {
+ sourcePurchaseOrderId,
+ companyId,
+ companyGroupId,
+ userId
+ }: {
+ sourcePurchaseOrderId: string;
+ companyId: string;
+ companyGroupId: string;
+ userId: string;
+ }
+): Promise<{
+ data: { id: string; purchaseOrderId: string } | null;
+ error: import("@supabase/supabase-js").PostgrestError | null;
+}> {
+ const [source, sourceDelivery, sourceLines] = await Promise.all([
+ client
+ .from("purchaseOrder")
+ .select(
+ "id, supplierId, supplierContactId, supplierLocationId, supplierReference, currencyCode, purchaseOrderType, internalNotes, externalNotes"
+ )
+ .eq("id", sourcePurchaseOrderId)
+ .single(),
+ client
+ .from("purchaseOrderDelivery")
+ .select("locationId, receiptRequestedDate")
+ .eq("id", sourcePurchaseOrderId)
+ .maybeSingle(),
+ client
+ .from("purchaseOrderLine")
+ .select(
+ "purchaseOrderLineType, itemId, assetId, description, purchaseQuantity, supplierUnitPrice, inventoryUnitOfMeasureCode, purchaseUnitOfMeasureCode, locationId, storageUnitId, setupPrice, requiresInspection, customFields, conversionFactor, tags, internalNotes, externalNotes, exchangeRate, supplierShippingCost, modelUploadId, supplierTaxAmount, jobId, jobOperationId, promisedDate, requiredDate, accountId, costCenterId, ownerId, sortOrder, supplierPartId"
+ )
+ .eq("purchaseOrderId", sourcePurchaseOrderId)
+ ]);
+
+ if (source.error || !source.data) {
+ return { data: null, error: source.error };
+ }
+ if (sourceLines.error) {
+ return { data: null, error: sourceLines.error };
+ }
+
+ const insertResult = await insertPurchaseOrder(client, {
+ supplierId: source.data.supplierId,
+ supplierContactId: source.data.supplierContactId ?? undefined,
+ supplierLocationId: source.data.supplierLocationId ?? undefined,
+ supplierReference: source.data.supplierReference ?? undefined,
+ currencyCode: source.data.currencyCode ?? undefined,
+ purchaseOrderType: source.data.purchaseOrderType ?? undefined,
+ notes: source.data.internalNotes ?? undefined,
+ externalNotes: source.data.externalNotes ?? undefined,
+ locationId: sourceDelivery.data?.locationId ?? undefined,
+ receiptRequestedDate:
+ sourceDelivery.data?.receiptRequestedDate ?? undefined,
+ status: "Draft",
+ companyId,
+ companyGroupId,
+ createdBy: userId
+ });
+
+ if (insertResult.error || !insertResult.data) {
+ return insertResult;
+ }
+
+ const newId = insertResult.data.id;
+
+ if (sourceLines.data && sourceLines.data.length > 0) {
+ const lineRows = sourceLines.data.map((line) => ({
+ ...line,
+ purchaseOrderId: newId,
+ companyId,
+ createdBy: userId
+ }));
+ const lineInsert = await client
+ .from("purchaseOrderLine")
+ .insert(lineRows as never);
+ if (lineInsert.error) {
+ // Best-effort rollback so we don't leave an orphan header.
+ await deletePurchaseOrder(client, newId);
+ return { data: null, error: lineInsert.error };
+ }
+ }
+
+ return insertResult;
+}
+
export async function deleteSupplier(
client: SupabaseClient<Database>,
supplierId: string
@@ -1302,7 +1394,8 @@ export async function insertPurchaseOrder(
supplierQuoteId?: string;
receiptRequestedDate?: string;
supplierReference?: string;
- notes?: string;
+ notes?: Json;
+ externalNotes?: Json;
customFields?: Json;
}
): Promise<{
@@ -1387,6 +1480,7 @@ export async function insertPurchaseOrder(
exchangeRateUpdatedAt,
supplierReference: input.supplierReference ?? null,
internalNotes: input.notes ?? null,
+ externalNotes: input.externalNotes ?? null,
customFields: input.customFields,
companyId: input.companyId,
createdBy: input.createdBy,
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx
index d7297b7373..f35d902969 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx
@@ -19,6 +19,7 @@ import {
LuBookMarked,
LuCalendar,
LuContainer,
+ LuCopy,
LuCreditCard,
LuDollarSign,
LuHandCoins,
@@ -403,6 +404,20 @@ const PurchaseOrdersTable = memo(
<Trans>Edit</Trans>
</MenuItem>
+ <MenuItem
+ disabled={!permissions.can("create", "purchasing") || !row.id}
+ onClick={() => {
+ if (!row.id) return;
+ fetcher.submit(null, {
+ method: "post",
+ action: path.to.purchaseOrderDuplicate(row.id)
+ });
+ }}
+ >
+ <MenuIcon icon={<LuCopy />} />
+ <Trans>Duplicate</Trans>
+ </MenuItem>
+
<MenuItem
disabled={
!["To Receive", "To Receive and Invoice"].includes(
@@ -432,7 +447,7 @@ const PurchaseOrdersTable = memo(
</MenuItem>
</>
),
- [deletePurchaseOrderModal, edit, permissions, receive]
+ [deletePurchaseOrderModal, edit, fetcher, permissions, receive]
);
return (
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index cd9ab1039a..09ad34d856 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,6 +1,6 @@
{
- "generated": "2026-06-08T20:42:15.020Z",
- "totalTools": 1180,
+ "generated": "2026-06-09T18:06:44.043Z",
+ "totalTools": 1181,
"modules": 15,
"tools": [
{
@@ -17460,6 +17460,33 @@
]
}
},
+ {
+ "name": "purchasing_duplicatePurchaseOrder",
+ "module": "purchasing",
+ "classification": "WRITE",
+ "description": "duplicate purchase order",
+ "paramCount": 1,
+ "serviceParams": [
+ "client",
+ "{\n sourcePurchaseOrderId,\n companyId,\n companyGroupId,\n userId\n }"
+ ],
+ "injectAuth": [
+ "companyId",
+ "createdBy",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "sourcePurchaseOrderId": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "sourcePurchaseOrderId"
+ ]
+ }
+ },
{
"name": "purchasing_deleteSupplier",
"module": "purchasing",
@@ -19346,7 +19373,7 @@
"module": "purchasing",
"classification": "WRITE",
"description": "Create a new purchase order with all business logic - generates sequence, creates supplier interaction, resolves payment/shipping defaults from supplier. LLM can create a PO with just supplierId.",
- "paramCount": 14,
+ "paramCount": 15,
"serviceParams": [
"client",
"input"
@@ -19400,9 +19427,8 @@
"supplierReference": {
"type": "string"
},
- "notes": {
- "type": "string"
- },
+ "notes": {},
+ "externalNotes": {},
"customFields": {}
},
"required": [
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.duplicate.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.duplicate.tsx
new file mode 100644
index 0000000000..fd71b0c388
--- /dev/null
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.duplicate.tsx
@@ -0,0 +1,46 @@
+import { assertIsPost, error } from "@carbon/auth";
+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 { duplicatePurchaseOrder } from "~/modules/purchasing/purchasing.service";
+import { path } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, companyGroupId, userId } =
+ await requirePermissions(request, {
+ create: "purchasing",
+ bypassRls: true
+ });
+
+ const { orderId } = params;
+ if (!orderId) {
+ throw redirect(
+ path.to.purchaseOrders,
+ await flash(
+ request,
+ error(null, "Failed to duplicate purchase order: missing id")
+ )
+ );
+ }
+
+ const result = await duplicatePurchaseOrder(client, {
+ sourcePurchaseOrderId: orderId,
+ companyId,
+ companyGroupId,
+ userId
+ });
+
+ if (result.error || !result.data) {
+ throw redirect(
+ path.to.purchaseOrders,
+ await flash(
+ request,
+ error(result.error, "Failed to duplicate purchase order")
+ )
+ );
+ }
+
+ throw redirect(path.to.purchaseOrder(result.data.id));
+}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 419285c652..e3c74a6bb6 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -1385,6 +1385,8 @@ export const path = {
generatePath(`${x}/purchase-invoice/${id}/void`),
purchaseInvoices: `${x}/purchasing/invoices`,
purchaseOrder: (id: string) => generatePath(`${x}/purchase-order/${id}`),
+ purchaseOrderDuplicate: (id: string) =>
+ generatePath(`${x}/purchase-order/${id}/duplicate`),
purchaseOrderDelivery: (id: string) =>
generatePath(`${x}/purchase-order/${id}/delivery`),
purchaseOrderDetails: (id: string) =>