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
feat: create receipt instead of posting if there are tracked parts on purchase invoice
Brad Barbind82ab5ae2e93
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicePostModal.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicePostModal.tsxindex 90eb606725..467dec8332 100644--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicePostModal.tsx+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicePostModal.tsx@@ -1,4 +1,7 @@import {+ Alert,+ AlertDescription,+ AlertTitle,Button,HStack,Modal,@@ -18,10 +21,11 @@ import {} from "@carbon/react";import { getItemReadableId } from "@carbon/utils";-import { useEffect } from "react";-import { useFetcher } from "react-router";-import type { action } from "~/routes/x+/purchase-invoice+/$invoiceId.post";+import { useEffect, useMemo } from "react";+import { LuTriangleAlert } from "react-icons/lu";+import { useFetcher, useNavigate } from "react-router";import { useItems } from "~/stores";+import { Result } from "~/types";import { path } from "~/utils/path";type PurchaseInvoicePostModalProps = {@@ -42,13 +46,27 @@ const PurchaseInvoicePostModal = ({linesToReceive}: PurchaseInvoicePostModalProps) => {const [items] = useItems();+ const navigate = useNavigate();const hasLinesToReceive = linesToReceive.length > 0;- const fetcher = useFetcher<typeof action>();+ const hasTrackedItems = useMemo(() => {+ return linesToReceive.some((line) => {+ const item = items.find((i) => i.id === line.itemId);+ return (+ item?.itemTrackingType === "Serial" ||+ item?.itemTrackingType === "Batch"+ );+ });+ }, [linesToReceive, items]);++ const fetcher = useFetcher<Result & { receiptId?: string }>();// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationuseEffect(() => {if (fetcher.data?.success) {+ if (fetcher.data.receiptId) {+ navigate(path.to.receipt(fetcher.data.receiptId));+ }onClose();} else if (fetcher.data?.success === false && fetcher.data?.message) {toast.error(fetcher.data.message);@@ -69,10 +87,28 @@ const PurchaseInvoicePostModal = ({<ModalBody>{hasLinesToReceive ? (<div className="gap-4 w-full flex flex-col">- <p>- Are you sure you want to post this invoice? A receipt will be- automatically created and posted for:- </p>+ {hasTrackedItems ? (+ <>+ <p>+ Are you sure you want to post this invoice? A receipt will+ be created for:+ </p>+ <Alert variant="destructive">+ <LuTriangleAlert className="h-4 w-4" />+ <AlertTitle>Serial or Batch Tracking Required</AlertTitle>+ <AlertDescription>+ Some items require serial or batch tracking. The receipt+ will be created but not posted. You will be redirected to+ the receipt to enter tracking information.+ </AlertDescription>+ </Alert>+ </>+ ) : (+ <p>+ Are you sure you want to post this invoice? A receipt will be+ automatically created and posted for:+ </p>+ )}<Table><Thead><Tr>@@ -114,13 +150,18 @@ const PurchaseInvoicePostModal = ({method="post"action={path.to.purchaseInvoicePost(invoiceId)}>+ {hasTrackedItems && (+ <input type="hidden" name="skipReceiptPost" value="true" />+ )}<ButtonisDisabled={fetcher.state !== "idle"}isLoading={fetcher.state !== "idle"}type="submit">{hasLinesToReceive- ? "Post and Receive Invoice"+ ? hasTrackedItems+ ? "Post and Create Receipt"+ : "Post and Receive Invoice": "Post Invoice"}</Button></fetcher.Form>diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.post.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.post.tsxindex 5cc7178dd5..cc16c2044c 100644--- a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.post.tsx+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.post.tsx@@ -12,6 +12,9 @@ export async function action({ request, params }: ActionFunctionArgs) {const { invoiceId } = params;if (!invoiceId) throw new Error("invoiceId not found");+ const formData = await request.formData();+ const skipReceiptPost = formData.get("skipReceiptPost") === "true";+const setPendingState = await client.from("purchaseInvoice").update({@@ -26,19 +29,21 @@ export async function action({ request, params }: ActionFunctionArgs) {};}+ let receiptIds: string[] | undefined;+try {const serviceRole = await getCarbonServiceRole();- const postPurchaseInvoice = await serviceRole.functions.invoke(- "post-purchase-invoice",- {- body: {- invoiceId: invoiceId,- userId: userId,- companyId: companyId- },- region: FunctionRegion.UsEast1- }- );+ const postPurchaseInvoice = await serviceRole.functions.invoke<{+ receiptIds?: string[];+ }>("post-purchase-invoice", {+ body: {+ invoiceId: invoiceId,+ userId: userId,+ companyId: companyId,+ skipReceiptPost: skipReceiptPost+ },+ region: FunctionRegion.UsEast1+ });if (postPurchaseInvoice.error) {await client@@ -54,6 +59,8 @@ export async function action({ request, params }: ActionFunctionArgs) {};}+ receiptIds = postPurchaseInvoice.data?.receiptIds;+// Check if we should update prices on invoice postconst companySettings = await getCompanySettings(serviceRole, companyId);if (@@ -101,8 +108,12 @@ export async function action({ request, params }: ActionFunctionArgs) {};}+ const receiptId =+ skipReceiptPost && receiptIds?.[0] ? receiptIds[0] : undefined;+return {success: true,- message: "Purchase invoice posted successfully"+ message: "Purchase invoice posted successfully",+ receiptId};}diff --git a/packages/database/supabase/functions/post-purchase-invoice/index.ts b/packages/database/supabase/functions/post-purchase-invoice/index.tsindex b492cec79c..6efc13249c 100644--- a/packages/database/supabase/functions/post-purchase-invoice/index.ts+++ b/packages/database/supabase/functions/post-purchase-invoice/index.ts@@ -21,6 +21,7 @@ const payloadValidator = z.object({invoiceId: z.string(),userId: z.string(),companyId: z.string(),+ skipReceiptPost: z.boolean().optional(),});serve(async (req: Request) => {@@ -32,12 +33,14 @@ serve(async (req: Request) => {const today = format(new Date(), "yyyy-MM-dd");try {- const { invoiceId, userId, companyId } = payloadValidator.parse(payload);+ const { invoiceId, userId, companyId, skipReceiptPost } =+ payloadValidator.parse(payload);console.log({function: "post-purchase-invoice",invoiceId,userId,+ skipReceiptPost,});const client = await getSupabaseServiceRole(req.headers.get("Authorization"),@@ -311,9 +314,16 @@ serve(async (req: Request) => {case "Material":case "Tool":{- const itemTrackingType =- items.data.find((item) => item.id === invoiceLine.itemId)- ?.itemTrackingType ?? "Inventory";+ const item = items.data.find((item) => item.id === invoiceLine.itemId);+ const itemTrackingType = item?.itemTrackingType ?? "Inventory";++ console.log({+ invoiceLineItemId: invoiceLine.itemId,+ foundItem: item,+ itemTrackingType,+ requiresSerialTracking: itemTrackingType === "Serial",+ requiresBatchTracking: itemTrackingType === "Batch",+ });itemPostingGroupId =itemCosts.data.find((item) => item.itemId === invoiceLine.itemId)@@ -396,11 +406,15 @@ serve(async (req: Request) => {shelfId: invoiceLine.shelfId,unitOfMeasure: invoiceLine.inventoryUnitOfMeasureCode ?? "EA",unitPrice: invoiceLine.unitPrice ?? 0,+ requiresSerialTracking: itemTrackingType === "Serial",+ requiresBatchTracking: itemTrackingType === "Batch",createdBy: invoiceLine.createdBy,companyId,});- if (itemTrackingType === "Inventory") {+ // Only create item ledger entries if the receipt is being posted+ // (not when skipReceiptPost is true, as entries will be created when the receipt is posted later)+ if (itemTrackingType === "Inventory" && !skipReceiptPost) {// create the part ledger lineitemLedgerInserts.push({postingDate: today,@@ -437,10 +451,11 @@ serve(async (req: Request) => {});// create the normal GL entries for a part+ // When skipReceiptPost is true, use overhead accounts since inventory hasn't been received yetjournalLineReference = nanoid();- if (itemTrackingType === "Inventory") {+ if (itemTrackingType === "Inventory" && !skipReceiptPost) {// debit the inventory accountjournalLineInserts.push({accountNumber: postingGroupInventory.inventoryAccount,@@ -995,6 +1010,8 @@ serve(async (req: Request) => {db);+ const createdReceiptIds: string[] = [];+await db.transaction().execute(async (trx) => {if (receiptLineInserts.length > 0) {const receiptLinesGroupedByLocationId = receiptLineInserts.reduce<@@ -1029,9 +1046,9 @@ serve(async (req: Request) => {sourceDocumentReadableId: purchaseInvoice.data.invoiceId,externalDocumentId: purchaseInvoice.data.supplierReference,supplierId: purchaseInvoice.data.supplierId,- status: "Posted",- postingDate: today,- postedBy: userId,+ status: skipReceiptPost ? "Draft" : "Posted",+ postingDate: skipReceiptPost ? null : today,+ postedBy: skipReceiptPost ? null : userId,invoiced: true,companyId,createdBy: purchaseInvoice.data.createdBy,@@ -1041,6 +1058,7 @@ serve(async (req: Request) => {const receiptId = receipt[0].id;if (!receiptId) throw new Error("Failed to insert receipt");+ createdReceiptIds.push(receiptId);await trx.insertInto("receiptLine")@@ -1171,6 +1189,7 @@ serve(async (req: Request) => {return new Response(JSON.stringify({success: true,+ receiptIds: createdReceiptIds,}),{headers: { ...corsHeaders, "Content-Type": "application/json" },