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: add the ability to void/reverse shipments
Brad Barbinced7927b13b5
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsxindex 2edf4709a8..9a758cd494 100644--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx@@ -34,8 +34,8 @@ import type { SalesInvoice } from "~/modules/invoicing/types";import SalesInvoiceStatus from "~/modules/invoicing/ui/SalesInvoice/SalesInvoiceStatus";import { path } from "~/utils/path";import ShipmentPostModal from "./ShipmentPostModal";-import ShipmentVoidModal from "./ShipmentVoidModal";import ShipmentStatus from "./ShipmentStatus";+import ShipmentVoidModal from "./ShipmentVoidModal";const ShipmentHeader = () => {const { shipmentId } = useParams();@@ -221,7 +221,7 @@ const ShipmentHeader = () => {) : (<ButtonleftIcon={<LuCreditCard />}- variant={"primary"}+ variant={isVoided ? "secondary" : "primary"}isDisabled={!isPosted}onClick={() => {invoice(routeData?.shipment);@@ -319,18 +319,22 @@ const ShipmentHeader = () => {</>)}<Button- variant={canPost && !isPosted ? "primary" : "secondary"}+ variant={+ canPost && !isPosted && !isVoided ? "primary" : "secondary"+ }onClick={postModal.onOpen}- isDisabled={!canPost || isPosted || !permissions.is("employee")}+ isDisabled={+ !canPost || isPosted || isVoided || !permissions.is("employee")+ }leftIcon={<LuCheckCheck />}>Post</Button>- {isPosted && !isVoided && (+ {(isPosted || isVoided) && (<Buttonvariant="destructive"onClick={voidModal.onOpen}- isDisabled={!permissions.is("employee")}+ isDisabled={isVoided || !permissions.is("employee")}leftIcon={<LuX />}>Voiddiff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsxindex 0b108fdddf..eba82aef03 100644--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx@@ -209,6 +209,8 @@ const ShipmentLines = () => {);const isPosted = routeData?.shipment?.status === "Posted";+ const isVoided = routeData?.shipment?.status === "Voided";+ const isReadOnly = isPosted || isVoided;return (<>@@ -255,7 +257,7 @@ const ShipmentLines = () => {);}) ?? false}- isReadOnly={isPosted}+ isReadOnly={isReadOnly}onUpdate={onUpdateShipmentLine}className={index === shipmentLines.length - 1 ? "border-none" : ""diff --git a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsxindex bf708b6bc5..4da33fe5eb 100644--- a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx+++ b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx@@ -110,6 +110,7 @@ export async function action({ request, params }: ActionFunctionArgs) {const postShipment = await serviceRole.functions.invoke("post-shipment", {body: {+ type: "post",shipmentId: shipmentId,userId: userId,companyId: companyId,diff --git a/apps/erp/app/routes/x+/shipment+/$shipmentId.void.tsx b/apps/erp/app/routes/x+/shipment+/$shipmentId.void.tsxindex 2005ea119e..9b4bb8fbe4 100644--- a/apps/erp/app/routes/x+/shipment+/$shipmentId.void.tsx+++ b/apps/erp/app/routes/x+/shipment+/$shipmentId.void.tsx@@ -1,4 +1,4 @@-import { error, getCarbonServiceRole } from "@carbon/auth";+import { error, getCarbonServiceRole, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { FunctionRegion } from "@supabase/supabase-js";@@ -29,13 +29,17 @@ export async function action({ request, params }: ActionFunctionArgs) {path.to.shipmentDetails(shipmentId),await flash(request,- error(new Error("Can only void posted shipments"), "Invalid operation")+ error(+ new Error("Can only void posted shipments"),+ "Invalid operation"+ )));}- const voidShipment = await serviceRole.functions.invoke("void-shipment", {+ const voidShipment = await serviceRole.functions.invoke("post-shipment", {body: {+ type: "void",shipmentId: shipmentId,userId: userId,companyId: companyId,@@ -53,21 +57,14 @@ export async function action({ request, params }: ActionFunctionArgs) {);}- throw redirect(+ return redirect(path.to.shipmentDetails(shipmentId),- await flash(request, {- type: "success",- title: "Shipment voided",- message: "The shipment has been successfully voided",- })+ await flash(request, success("Shipment voided")));} catch (err) {throw redirect(path.to.shipmentDetails(shipmentId),- await flash(- request,- error(err, "Failed to void shipment")- )+ await flash(request, error(err, "Failed to void shipment")));}-}\ No newline at end of file+}diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 738f7e3a8a..b1fef6f6ff 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -73400,7 +73400,7 @@ export default {},status: {default: "Draft",- enum: ["Draft", "Pending", "Posted"],+ enum: ["Draft", "Pending", "Posted", "Voided"],format: 'public."shipmentStatus"',type: "string",},diff --git a/packages/database/supabase/functions/post-receipt/index.ts b/packages/database/supabase/functions/post-receipt/index.tsindex 700c7a15ba..8e5c5112a3 100644--- a/packages/database/supabase/functions/post-receipt/index.ts+++ b/packages/database/supabase/functions/post-receipt/index.ts@@ -121,10 +121,13 @@ serve(async (req: Request) => {(purchaseOrder.data?.exchangeRate ?? 1);const totalLinesCost = receiptLines.data.reduce((acc, receiptLine) => {- const safeReceivedQuantity = isNaN(receiptLine.receivedQuantity) || receiptLine.receivedQuantity == null ? 0 : receiptLine.receivedQuantity;+ const safeReceivedQuantity =+ isNaN(receiptLine.receivedQuantity) ||+ receiptLine.receivedQuantity == null+ ? 0+ : receiptLine.receivedQuantity;const lineCost =- Math.abs(safeReceivedQuantity) *- (receiptLine.unitPrice ?? 0);+ Math.abs(safeReceivedQuantity) * (receiptLine.unitPrice ?? 0);return acc + lineCost;}, 0);@@ -173,7 +176,12 @@ serve(async (req: Request) => {]?.toString());- const safeReceivedQuantity = isNaN(receiptLine?.receivedQuantity) || receiptLine?.receivedQuantity == null ? 0 : receiptLine.receivedQuantity;+ const safeReceivedQuantity =+ // @ts-ignore - chillllllll+ isNaN(receiptLine?.receivedQuantity) ||+ receiptLine?.receivedQuantity == null+ ? 0+ : receiptLine.receivedQuantity;const quantity = receiptLine?.requiresSerialTracking? 1: safeReceivedQuantity || itemTracking.quantity;@@ -204,7 +212,11 @@ serve(async (req: Request) => {) {const recivedQuantityInPurchaseUnit =receiptLines.reduce((acc, receiptLine) => {- const safeReceivedQuantity = isNaN(receiptLine.receivedQuantity) || receiptLine.receivedQuantity == null ? 0 : receiptLine.receivedQuantity;+ const safeReceivedQuantity =+ isNaN(receiptLine.receivedQuantity) ||+ receiptLine.receivedQuantity == null+ ? 0+ : receiptLine.receivedQuantity;return acc + safeReceivedQuantity;}, 0) / (receiptLines[0].conversionFactor ?? 1);@@ -242,7 +254,11 @@ serve(async (req: Request) => {) {const recivedQuantityInPurchaseUnit =receiptLines.reduce((acc, receiptLine) => {- const safeReceivedQuantity = isNaN(receiptLine.receivedQuantity) || receiptLine.receivedQuantity == null ? 0 : receiptLine.receivedQuantity;+ const safeReceivedQuantity =+ isNaN(receiptLine.receivedQuantity) ||+ receiptLine.receivedQuantity == null+ ? 0+ : receiptLine.receivedQuantity;return acc + safeReceivedQuantity;}, 0) / (receiptLines[0].conversionFactor ?? 1);@@ -442,7 +458,11 @@ serve(async (req: Request) => {(purchaseOrderLine?.quantityInvoiced ?? 0) *(purchaseOrderLine?.conversionFactor ?? 1);- const safeReceiptLineQuantity = isNaN(receiptLine.receivedQuantity) || receiptLine.receivedQuantity == null ? 0 : receiptLine.receivedQuantity;+ const safeReceiptLineQuantity =+ isNaN(receiptLine.receivedQuantity) ||+ receiptLine.receivedQuantity == null+ ? 0+ : receiptLine.receivedQuantity;const quantityToReverse = Math.max(0,Math.min(@@ -662,7 +682,11 @@ serve(async (req: Request) => {});}- const receivedQuantity = isNaN(receiptLine.receivedQuantity) || receiptLine.receivedQuantity == null ? 0 : receiptLine.receivedQuantity;+ const receivedQuantity =+ isNaN(receiptLine.receivedQuantity) ||+ receiptLine.receivedQuantity == null+ ? 0+ : receiptLine.receivedQuantity;const isNegativeReceipt = receivedQuantity < 0;const absReceivedQuantity = Math.abs(receivedQuantity);@@ -803,7 +827,11 @@ serve(async (req: Request) => {] === receiptLine.id);- const safeReceiptLineQuantity = isNaN(receiptLine.receivedQuantity) || receiptLine.receivedQuantity == null ? 0 : receiptLine.receivedQuantity;+ const safeReceiptLineQuantity =+ isNaN(receiptLine.receivedQuantity) ||+ receiptLine.receivedQuantity == null+ ? 0+ : receiptLine.receivedQuantity;const absReceivedQuantity = Math.abs(safeReceiptLineQuantity);const entryType =receivedQuantity < 0 ? "Negative Adjmt." : "Positive Adjmt.";@@ -1062,7 +1090,11 @@ serve(async (req: Request) => {if (!warehouseTransferLine) continue;- const receivedQuantity = isNaN(receiptLine.receivedQuantity) || receiptLine.receivedQuantity == null ? 0 : receiptLine.receivedQuantity;+ const receivedQuantity =+ isNaN(receiptLine.receivedQuantity) ||+ receiptLine.receivedQuantity == null+ ? 0+ : receiptLine.receivedQuantity;if (receivedQuantity === 0) continue;// Update warehouse transfer line received quantitydiff --git a/packages/database/supabase/functions/post-shipment/index.ts b/packages/database/supabase/functions/post-shipment/index.tsindex 58b45af15d..14e8178b45 100644--- a/packages/database/supabase/functions/post-shipment/index.ts+++ b/packages/database/supabase/functions/post-shipment/index.ts@@ -11,6 +11,7 @@ const pool = getConnectionPool(1);const db = getDatabaseClient<DB>(pool);const payloadValidator = z.object({+ type: z.enum(["post", "void"]),shipmentId: z.string(),userId: z.string(),companyId: z.string(),@@ -25,10 +26,12 @@ serve(async (req: Request) => {const today = format(new Date(), "yyyy-MM-dd");try {- const { shipmentId, userId, companyId } = payloadValidator.parse(payload);+ const { type, shipmentId, userId, companyId } =+ payloadValidator.parse(payload);console.log({function: "post-shipment",+ type,shipmentId,userId,companyId,@@ -97,1199 +100,2154 @@ serve(async (req: Request) => {throw new Error("Failed to fetch jobs");}- switch (shipment.data?.sourceDocument) {- case "Sales Order": {- if (!shipment.data.sourceDocumentId)- throw new Error("Shipment has no sourceDocumentId");-- const [salesOrder, salesOrderLines, salesOrderDelivery] =- await Promise.all([- client- .from("salesOrder")- .select("*")- .eq("id", shipment.data.sourceDocumentId)- .single(),- client- .from("salesOrderLine")+ switch (type) {+ case "post": {+ switch (shipment.data?.sourceDocument) {+ case "Sales Order": {+ if (!shipment.data.sourceDocumentId)+ throw new Error("Shipment has no sourceDocumentId");++ const [salesOrder, salesOrderLines, salesOrderDelivery] =+ await Promise.all([+ client+ .from("salesOrder")+ .select("*")+ .eq("id", shipment.data.sourceDocumentId)+ .single(),+ client+ .from("salesOrderLine")+ .select("*")+ .eq("salesOrderId", shipment.data.sourceDocumentId),+ client+ .from("salesOrderShipment")+ .select("shippingCost")+ .eq("id", shipment.data.sourceDocumentId)+ .single(),+ ]);+ if (salesOrder.error)+ throw new Error("Failed to fetch purchase order");+ if (salesOrderLines.error)+ throw new Error("Failed to fetch sales order lines");+ if (salesOrderDelivery.error)+ throw new Error("Failed to fetch sales order delivery");++ const customer = await client+ .from("customer").select("*")- .eq("salesOrderId", shipment.data.sourceDocumentId),- client- .from("salesOrderShipment")- .select("shippingCost")- .eq("id", shipment.data.sourceDocumentId)- .single(),- ]);- if (salesOrder.error) throw new Error("Failed to fetch purchase order");- if (salesOrderLines.error)- throw new Error("Failed to fetch sales order lines");- if (salesOrderDelivery.error)- throw new Error("Failed to fetch sales order delivery");-- const customer = await client- .from("customer")- .select("*")- .eq("id", salesOrder.data.customerId)- .eq("companyId", companyId)- .single();- if (customer.error) throw new Error("Failed to fetch customer");-- const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =- [];-- const jobUpdates: Record<- string,- Database["public"]["Tables"]["job"]["Update"]- > = {};-- const serialNumbersConsumed: string[] = [];-- const locationId = shipment.data.locationId;- for await (const shipmentLine of shipmentLines.data) {- if (- shipmentLine.fulfillment?.type === "Job" &&- shipmentLine.fulfillment?.jobId- ) {- // Update quantity shipped on job, accumulating totals from multiple shipments- const jobId = shipmentLine.fulfillment.jobId;- const currentJob = jobs.data.find((j) => j.id === jobId);-- // Log job and shipment line data to debug NaN issues- console.log("Processing job update:", {- jobId,- currentJob: currentJob- ? {- id: currentJob.id,- quantity: currentJob.quantity,- quantityShipped: currentJob.quantityShipped,- quantityComplete: currentJob.quantityComplete,- status: currentJob.status,- }- : null,- shipmentLine: {- id: shipmentLine.id,- shippedQuantity: shipmentLine.shippedQuantity,- shippedQuantityType: typeof shipmentLine.shippedQuantity,- },- });+ .eq("id", salesOrder.data.customerId)+ .eq("companyId", companyId)+ .single();+ if (customer.error) throw new Error("Failed to fetch customer");- const currentQuantityShipped = currentJob?.quantityShipped ?? 0;+ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];- // Ensure shippedQuantity is a valid number to prevent "100NaN" errors- const shippedQuantity =- typeof shipmentLine.shippedQuantity === "number" &&- !isNaN(shipmentLine.shippedQuantity)- ? shipmentLine.shippedQuantity- : 0;+ const jobUpdates: Record<+ string,+ Database["public"]["Tables"]["job"]["Update"]+ > = {};++ const serialNumbersConsumed: string[] = [];++ const locationId = shipment.data.locationId;+ for await (const shipmentLine of shipmentLines.data) {+ if (+ shipmentLine.fulfillment?.type === "Job" &&+ shipmentLine.fulfillment?.jobId+ ) {+ // Update quantity shipped on job, accumulating totals from multiple shipments+ const jobId = shipmentLine.fulfillment.jobId;+ const currentJob = jobs.data.find((j) => j.id === jobId);++ // Log job and shipment line data to debug NaN issues+ console.log("Processing job update:", {+ jobId,+ currentJob: currentJob+ ? {+ id: currentJob.id,+ quantity: currentJob.quantity,+ quantityShipped: currentJob.quantityShipped,+ quantityComplete: currentJob.quantityComplete,+ status: currentJob.status,+ }+ : null,+ shipmentLine: {+ id: shipmentLine.id,+ shippedQuantity: shipmentLine.shippedQuantity,+ shippedQuantityType: typeof shipmentLine.shippedQuantity,+ },+ });++ const currentQuantityShipped = currentJob?.quantityShipped ?? 0;++ // Ensure shippedQuantity is a valid number to prevent "100NaN" errors+ const shippedQuantity =+ typeof shipmentLine.shippedQuantity === "number" &&+ !isNaN(shipmentLine.shippedQuantity)+ ? shipmentLine.shippedQuantity+ : 0;++ console.log("Calculated values:", {+ currentQuantityShipped,+ shippedQuantity,+ newTotal: currentQuantityShipped + shippedQuantity,+ jobQuantity: currentJob?.quantity,+ });++ // If we've already updated this job in this transaction, use that as the base+ // instead of the current DB value to avoid double counting+ if (jobUpdates[jobId]) {+ const newQuantityShipped =+ (jobUpdates[jobId]?.quantityShipped ?? 0) + shippedQuantity;+ const newQuantityComplete =+ currentJob?.status === "Completed"+ ? currentJob?.quantityComplete+ : (currentJob?.quantityComplete ?? 0) + shippedQuantity;+ const newStatus =+ currentQuantityShipped + shippedQuantity >=+ (currentJob?.quantity ?? 0)+ ? "Completed"+ : currentJob?.status;++ console.log("Updating existing job update:", {+ jobId,+ previousUpdate: jobUpdates[jobId],+ newUpdate: {+ status: newStatus,+ quantityComplete: newQuantityComplete,+ quantityShipped: newQuantityShipped,+ },+ });++ jobUpdates[jobId] = {+ status: newStatus,+ quantityComplete: newQuantityComplete,+ quantityShipped: newQuantityShipped,+ };+ } else {+ const newQuantityShipped =+ currentQuantityShipped + shippedQuantity;+ const newQuantityComplete =+ currentJob?.status === "Completed"+ ? currentJob?.quantityComplete+ : (currentJob?.quantityComplete ?? 0) + shippedQuantity;+ const newStatus =+ currentQuantityShipped + shippedQuantity >=+ (currentJob?.quantity ?? 0)+ ? "Completed"+ : currentJob?.status;++ console.log("Creating new job update:", {+ jobId,+ update: {+ status: newStatus,+ quantityComplete: newQuantityComplete,+ quantityShipped: newQuantityShipped,+ },+ });++ jobUpdates[jobId] = {+ status: newStatus,+ quantityComplete: newQuantityComplete,+ quantityShipped: newQuantityShipped,+ };+ }+ continue;+ }- console.log("Calculated values:", {- currentQuantityShipped,- shippedQuantity,- newTotal: currentQuantityShipped + shippedQuantity,- jobQuantity: currentJob?.quantity,- });+ const itemTrackingType =+ items.data.find((item) => item.id === shipmentLine.itemId)+ ?.itemTrackingType ?? "Inventory";++ // Default shippedQuantity to 0 if not defined or NaN+ const shippedQuantity =+ isNaN(shipmentLine.shippedQuantity) ||+ shipmentLine.shippedQuantity == null+ ? 0+ : shipmentLine.shippedQuantity;++ if (itemTrackingType === "Inventory") {+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: -shippedQuantity,+ locationId: shipmentLine.locationId ?? locationId,+ shelfId: shipmentLine.shelfId,+ entryType: "Negative Adjmt.",+ documentType: "Sales Shipment",+ documentId: shipment.data?.id ?? undefined,+ externalDocumentId: undefined,+ createdBy: userId,+ companyId,+ });+ }- // If we've already updated this job in this transaction, use that as the base- // instead of the current DB value to avoid double counting- if (jobUpdates[jobId]) {- const newQuantityShipped =- (jobUpdates[jobId]?.quantityShipped ?? 0) + shippedQuantity;- const newQuantityComplete =- currentJob?.status === "Completed"- ? currentJob?.quantityComplete- : (currentJob?.quantityComplete ?? 0) + shippedQuantity;- const newStatus =- currentQuantityShipped + shippedQuantity >=- (currentJob?.quantity ?? 0)- ? "Completed"- : currentJob?.status;-- console.log("Updating existing job update:", {- jobId,- previousUpdate: jobUpdates[jobId],- newUpdate: {- status: newStatus,- quantityComplete: newQuantityComplete,- quantityShipped: newQuantityShipped,- },- });+ if (shipmentLine.requiresBatchTracking) {+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: -shippedQuantity,+ locationId: shipmentLine.locationId ?? locationId,+ shelfId: shipmentLine.shelfId,+ entryType: "Negative Adjmt.",+ documentType: "Sales Shipment",+ documentId: shipment.data?.id ?? undefined,+ trackedEntityId: shipmentLineTracking.data?.find(+ (tracking) =>+ (+ tracking.attributes as+ | TrackedEntityAttributes+ | undefined+ )?.["Shipment Line"] === shipmentLine.id+ )?.id,+ externalDocumentId: undefined,+ createdBy: userId,+ companyId,+ });+ }- jobUpdates[jobId] = {- status: newStatus,- quantityComplete: newQuantityComplete,- quantityShipped: newQuantityShipped,- };- } else {- const newQuantityShipped =- currentQuantityShipped + shippedQuantity;- const newQuantityComplete =- currentJob?.status === "Completed"- ? currentJob?.quantityComplete- : (currentJob?.quantityComplete ?? 0) + shippedQuantity;- const newStatus =- currentQuantityShipped + shippedQuantity >=- (currentJob?.quantity ?? 0)- ? "Completed"- : currentJob?.status;-- console.log("Creating new job update:", {- jobId,- update: {- status: newStatus,- quantityComplete: newQuantityComplete,- quantityShipped: newQuantityShipped,- },- });+ if (shipmentLine.requiresSerialTracking) {+ const lineTracking = shipmentLineTracking.data?.filter(+ (tracking) =>+ (+ tracking.attributes as TrackedEntityAttributes | undefined+ )?.["Shipment Line"] === shipmentLine.id+ );++ lineTracking?.forEach((tracking) => {+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: -1,+ locationId: shipmentLine.locationId ?? locationId,+ shelfId: shipmentLine.shelfId,+ entryType: "Negative Adjmt.",+ documentType: "Sales Shipment",+ documentId: shipment.data?.id ?? undefined,+ trackedEntityId: tracking.id,+ externalDocumentId: undefined,+ createdBy: userId,+ companyId,+ });- jobUpdates[jobId] = {- status: newStatus,- quantityComplete: newQuantityComplete,- quantityShipped: newQuantityShipped,- };+ if (tracking.id) {+ serialNumbersConsumed.push(tracking.id);+ }+ });+ }}- continue;- }-- const itemTrackingType =- items.data.find((item) => item.id === shipmentLine.itemId)- ?.itemTrackingType ?? "Inventory";-- // Default shippedQuantity to 0 if not defined or NaN- const shippedQuantity = isNaN(shipmentLine.shippedQuantity) || shipmentLine.shippedQuantity == null ? 0 : shipmentLine.shippedQuantity;-- if (itemTrackingType === "Inventory") {- itemLedgerInserts.push({- postingDate: today,- itemId: shipmentLine.itemId,- quantity: -shippedQuantity,- locationId: shipmentLine.locationId ?? locationId,- shelfId: shipmentLine.shelfId,- entryType: "Negative Adjmt.",- documentType: "Sales Shipment",- documentId: shipment.data?.id ?? undefined,- externalDocumentId: undefined,- createdBy: userId,- companyId,- });- }-- if (shipmentLine.requiresBatchTracking) {- itemLedgerInserts.push({- postingDate: today,- itemId: shipmentLine.itemId,- quantity: -shippedQuantity,- locationId: shipmentLine.locationId ?? locationId,- shelfId: shipmentLine.shelfId,- entryType: "Negative Adjmt.",- documentType: "Sales Shipment",- documentId: shipment.data?.id ?? undefined,- trackedEntityId: shipmentLineTracking.data?.find(- (tracking) =>- (- tracking.attributes as TrackedEntityAttributes | undefined- )?.["Shipment Line"] === shipmentLine.id- )?.id,- externalDocumentId: undefined,- createdBy: userId,- companyId,- });- }-- if (shipmentLine.requiresSerialTracking) {- const lineTracking = shipmentLineTracking.data?.filter(- (tracking) =>- (tracking.attributes as TrackedEntityAttributes | undefined)?.[- "Shipment Line"- ] === shipmentLine.id- );- lineTracking?.forEach((tracking) => {- itemLedgerInserts.push({- postingDate: today,- itemId: shipmentLine.itemId,- quantity: -1,- locationId: shipmentLine.locationId ?? locationId,- shelfId: shipmentLine.shelfId,- entryType: "Negative Adjmt.",- documentType: "Sales Shipment",- documentId: shipment.data?.id ?? undefined,- trackedEntityId: tracking.id,- externalDocumentId: undefined,- createdBy: userId,- companyId,- });-- if (tracking.id) {- serialNumbersConsumed.push(tracking.id);+ const shipmentLinesBySalesOrderLineId = shipmentLines.data.reduce<+ Record<+ string,+ Database["public"]["Tables"]["shipmentLine"]["Row"][]+ >+ >((acc, shipmentLine) => {+ if (shipmentLine.lineId) {+ acc[shipmentLine.lineId] = [+ ...(acc[shipmentLine.lineId] ?? []),+ shipmentLine,+ ];}- });- }- }+ return acc;+ }, {});++ const salesOrderLineUpdates = salesOrderLines.data.reduce<+ Record<+ string,+ Database["public"]["Tables"]["salesOrderLine"]["Update"]+ >+ >((acc, salesOrderLine) => {+ const shipmentLines =+ shipmentLinesBySalesOrderLineId[salesOrderLine.id];+ if (+ shipmentLines &&+ shipmentLines.length > 0 &&+ salesOrderLine.saleQuantity &&+ salesOrderLine.saleQuantity > 0+ ) {+ const shippedQuantity = shipmentLines.reduce(+ (acc, shipmentLine) => {+ const safeShippedQuantity =+ isNaN(shipmentLine.shippedQuantity) ||+ shipmentLine.shippedQuantity == null+ ? 0+ : shipmentLine.shippedQuantity;+ return acc + safeShippedQuantity;+ },+ 0+ );++ const newQuantitySent =+ (salesOrderLine.quantitySent ?? 0) + shippedQuantity;++ const sentComplete =+ salesOrderLine.sentComplete ||+ newQuantitySent >= salesOrderLine.saleQuantity;++ const updates: Record<+ string,+ Database["public"]["Tables"]["salesOrderLine"]["Update"]+ > = {+ ...acc,+ [salesOrderLine.id]: {+ quantitySent: newQuantitySent,+ sentComplete,+ },+ };- const shipmentLinesBySalesOrderLineId = shipmentLines.data.reduce<- Record<string, Database["public"]["Tables"]["shipmentLine"]["Row"][]>- >((acc, shipmentLine) => {- if (shipmentLine.lineId) {- acc[shipmentLine.lineId] = [- ...(acc[shipmentLine.lineId] ?? []),- shipmentLine,- ];- }- return acc;- }, {});-- const salesOrderLineUpdates = salesOrderLines.data.reduce<- Record<- string,- Database["public"]["Tables"]["salesOrderLine"]["Update"]- >- >((acc, salesOrderLine) => {- const shipmentLines =- shipmentLinesBySalesOrderLineId[salesOrderLine.id];- if (- shipmentLines &&- shipmentLines.length > 0 &&- salesOrderLine.saleQuantity &&- salesOrderLine.saleQuantity > 0- ) {- const shippedQuantity = shipmentLines.reduce(- (acc, shipmentLine) => {- const safeShippedQuantity = isNaN(shipmentLine.shippedQuantity) || shipmentLine.shippedQuantity == null ? 0 : shipmentLine.shippedQuantity;- return acc + safeShippedQuantity;- },- 0- );+ if (sentComplete && !salesOrderLine.sentDate) {+ updates[salesOrderLine.id].sentDate = today;+ }- const newQuantitySent =- (salesOrderLine.quantitySent ?? 0) + shippedQuantity;+ return updates;+ }- const sentComplete =- salesOrderLine.sentComplete ||- newQuantitySent >= salesOrderLine.saleQuantity;+ return acc;+ }, {});- const updates: Record<+ const trackedEntitySplits: Record<string,- Database["public"]["Tables"]["salesOrderLine"]["Update"]- > = {- ...acc,- [salesOrderLine.id]: {- quantitySent: newQuantitySent,- sentComplete,- },- };-- if (sentComplete && !salesOrderLine.sentDate) {- updates[salesOrderLine.id].sentDate = today;- }+ {+ originalEntityId: string;+ originalQuantity: number;+ shippedQuantity: number;+ remainingQuantity: number;+ attributes: TrackedEntityAttributes;+ sourceDocument: string;+ sourceDocumentId: string;+ sourceDocumentReadableId: string | null;+ companyId: string;+ }+ > = {};++ const trackedEntityUpdates =+ shipmentLineTracking.data?.reduce<+ Record<+ string,+ Database["public"]["Tables"]["trackedEntity"]["Update"]+ >+ >((acc, trackedEntity) => {+ const shipmentLine = shipmentLines.data?.find(+ (shipmentLine) =>+ shipmentLine.id ===+ (trackedEntity.attributes as TrackedEntityAttributes)?.[+ "Shipment Line"+ ]+ );++ if (+ shipmentLine?.shippedQuantity !== undefined &&+ trackedEntity.quantity !== undefined &&+ shipmentLine.shippedQuantity < trackedEntity.quantity+ ) {+ // Need to split the batch+ trackedEntitySplits[trackedEntity.id] = {+ originalEntityId: trackedEntity.id,+ originalQuantity: trackedEntity.quantity,+ shippedQuantity: shipmentLine.shippedQuantity,+ remainingQuantity:+ trackedEntity.quantity - shipmentLine.shippedQuantity,+ attributes:+ trackedEntity.attributes as TrackedEntityAttributes,+ sourceDocument: trackedEntity.sourceDocument,+ sourceDocumentId: trackedEntity.sourceDocumentId,+ sourceDocumentReadableId:+ trackedEntity.sourceDocumentReadableId,+ companyId: trackedEntity.companyId,+ };+ }++ acc[trackedEntity.id] = {+ status: "Consumed",+ quantity:+ shipmentLine?.shippedQuantity ?? trackedEntity.quantity,+ };- return updates;- }+ return acc;+ }, {}) ?? {};- return acc;- }, {});-- const trackedEntitySplits: Record<- string,- {- originalEntityId: string;- originalQuantity: number;- shippedQuantity: number;- remainingQuantity: number;- attributes: TrackedEntityAttributes;- sourceDocument: string;- sourceDocumentId: string;- sourceDocumentReadableId: string | null;- companyId: string;- }- > = {};+ await db.transaction().execute(async (trx) => {+ for await (const [salesOrderLineId, update] of Object.entries(+ salesOrderLineUpdates+ )) {+ await trx+ .updateTable("salesOrderLine")+ .set(update)+ .where("id", "=", salesOrderLineId)+ .execute();+ }- const trackedEntityUpdates =- shipmentLineTracking.data?.reduce<- Record<- string,- Database["public"]["Tables"]["trackedEntity"]["Update"]- >- >((acc, trackedEntity) => {- const shipmentLine = shipmentLines.data?.find(- (shipmentLine) =>- shipmentLine.id ===- (trackedEntity.attributes as TrackedEntityAttributes)?.[- "Shipment Line"- ]- );+ const salesOrderLines = await trx+ .selectFrom("salesOrderLine")+ .select([+ "id",+ "salesOrderLineType",+ "invoicedComplete",+ "sentComplete",+ ])+ .where("salesOrderId", "=", salesOrder.data.id)+ .execute();- if (- shipmentLine?.shippedQuantity !== undefined &&- trackedEntity.quantity !== undefined &&- shipmentLine.shippedQuantity < trackedEntity.quantity- ) {- // Need to split the batch- trackedEntitySplits[trackedEntity.id] = {- originalEntityId: trackedEntity.id,- originalQuantity: trackedEntity.quantity,- shippedQuantity: shipmentLine.shippedQuantity,- remainingQuantity:- trackedEntity.quantity - shipmentLine.shippedQuantity,- attributes: trackedEntity.attributes as TrackedEntityAttributes,- sourceDocument: trackedEntity.sourceDocument,- sourceDocumentId: trackedEntity.sourceDocumentId,- sourceDocumentReadableId:- trackedEntity.sourceDocumentReadableId,- companyId: trackedEntity.companyId,- };- }+ const areAllLinesInvoiced = salesOrderLines.every(+ (line) =>+ line.salesOrderLineType === "Comment" || line.invoicedComplete+ );- acc[trackedEntity.id] = {- status: "Consumed",- quantity: shipmentLine?.shippedQuantity ?? trackedEntity.quantity,- };-- return acc;- }, {}) ?? {};-- await db.transaction().execute(async (trx) => {- for await (const [salesOrderLineId, update] of Object.entries(- salesOrderLineUpdates- )) {- await trx- .updateTable("salesOrderLine")- .set(update)- .where("id", "=", salesOrderLineId)- .execute();- }+ const areAllLinesShipped = salesOrderLines.every(+ (line) =>+ line.salesOrderLineType === "Comment" || line.sentComplete+ );- const salesOrderLines = await trx- .selectFrom("salesOrderLine")- .select([- "id",- "salesOrderLineType",- "invoicedComplete",- "sentComplete",- ])- .where("salesOrderId", "=", salesOrder.data.id)- .execute();-- const areAllLinesInvoiced = salesOrderLines.every(- (line) =>- line.salesOrderLineType === "Comment" || line.invoicedComplete- );-- const areAllLinesShipped = salesOrderLines.every(- (line) => line.salesOrderLineType === "Comment" || line.sentComplete- );-- let status: Database["public"]["Tables"]["salesOrder"]["Row"]["status"] =- "To Ship and Invoice";- if (areAllLinesInvoiced && areAllLinesShipped) {- status = "Completed";- } else if (areAllLinesShipped) {- status = "To Invoice";- } else if (areAllLinesInvoiced) {- status = "To Ship";- }+ let status: Database["public"]["Tables"]["salesOrder"]["Row"]["status"] =+ "To Ship and Invoice";+ if (areAllLinesInvoiced && areAllLinesShipped) {+ status = "Completed";+ } else if (areAllLinesShipped) {+ status = "To Invoice";+ } else if (areAllLinesInvoiced) {+ status = "To Ship";+ }- await trx- .updateTable("salesOrder")- .set({- status,- })- .where("id", "=", salesOrder.data.id)- .execute();-- await trx- .updateTable("shipment")- .set({- status: "Posted",- postingDate: today,- postedBy: userId,- })- .where("id", "=", shipmentId)- .execute();-- if (Object.keys(trackedEntityUpdates).length > 0) {- const trackedActivity = await trx- .insertInto("trackedActivity")- .values({- type: "Shipment",- sourceDocument: "Shipment",- sourceDocumentId: shipmentId,- sourceDocumentReadableId: shipment.data.shipmentId,- attributes: {- Shipment: shipmentId,- "Sales Order": salesOrder.data.id,- },- companyId,- createdBy: userId,- createdAt: today,- })- .returning(["id"])- .execute();-- const trackedActivityId = trackedActivity[0].id;-- // Handle batch splits first- for await (const splitInfo of Object.values(trackedEntitySplits)) {- // Create a split activity- const splitActivity = await trx- .insertInto("trackedActivity")- .values({- type: "Split",- sourceDocument: "Shipment",- sourceDocumentId: shipmentId,- sourceDocumentReadableId: shipment.data.shipmentId,- attributes: {- "Original Quantity": splitInfo.originalQuantity,- "Shipped Quantity": splitInfo.shippedQuantity,- "Remaining Quantity": splitInfo.remainingQuantity,- },- companyId: splitInfo.companyId,- createdBy: userId,- createdAt: today,+ await trx+ .updateTable("salesOrder")+ .set({+ status,})- .returning(["id"])+ .where("id", "=", salesOrder.data.id).execute();- const splitActivityId = splitActivity[0].id!;-- // Record the original entity as input to the splitawait trx- .insertInto("trackedActivityInput")- .values({- trackedActivityId: splitActivityId,- trackedEntityId: splitInfo.originalEntityId,- quantity: splitInfo.originalQuantity,- companyId: splitInfo.companyId,- createdBy: userId,- createdAt: today,+ .updateTable("shipment")+ .set({+ status: "Posted",+ postingDate: today,+ postedBy: userId,})+ .where("id", "=", shipmentId).execute();- // Create a new tracked entity for the remaining quantity- const newTrackedEntity = await trx- .insertInto("trackedEntity")- .values({- quantity: splitInfo.remainingQuantity,- status: "Available",- sourceDocument: splitInfo.sourceDocument,- sourceDocumentId: splitInfo.sourceDocumentId,- sourceDocumentReadableId: splitInfo.sourceDocumentReadableId,- attributes: splitInfo.attributes as unknown as Json,- companyId: splitInfo.companyId,- createdBy: userId,- createdAt: today,- })- .returning(["id"])- .execute();+ if (Object.keys(trackedEntityUpdates).length > 0) {+ const trackedActivity = await trx+ .insertInto("trackedActivity")+ .values({+ type: "Shipment",+ sourceDocument: "Shipment",+ sourceDocumentId: shipmentId,+ sourceDocumentReadableId: shipment.data.shipmentId,+ attributes: {+ Shipment: shipmentId,+ "Sales Order": salesOrder.data.id,+ },+ companyId,+ createdBy: userId,+ createdAt: today,+ })+ .returning(["id"])+ .execute();- const newTrackedEntityId = newTrackedEntity[0].id!;+ const trackedActivityId = trackedActivity[0].id;++ // Handle batch splits first+ for await (const splitInfo of Object.values(+ trackedEntitySplits+ )) {+ // Create a split activity+ const splitActivity = await trx+ .insertInto("trackedActivity")+ .values({+ type: "Split",+ sourceDocument: "Shipment",+ sourceDocumentId: shipmentId,+ sourceDocumentReadableId: shipment.data.shipmentId,+ attributes: {+ "Original Quantity": splitInfo.originalQuantity,+ "Shipped Quantity": splitInfo.shippedQuantity,+ "Remaining Quantity": splitInfo.remainingQuantity,+ },+ companyId: splitInfo.companyId,+ createdBy: userId,+ createdAt: today,+ })+ .returning(["id"])+ .execute();++ const splitActivityId = splitActivity[0].id!;++ // Record the original entity as input to the split+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: splitActivityId,+ trackedEntityId: splitInfo.originalEntityId,+ quantity: splitInfo.originalQuantity,+ companyId: splitInfo.companyId,+ createdBy: userId,+ createdAt: today,+ })+ .execute();++ // Create a new tracked entity for the remaining quantity+ const newTrackedEntity = await trx+ .insertInto("trackedEntity")+ .values({+ quantity: splitInfo.remainingQuantity,+ status: "Available",+ sourceDocument: splitInfo.sourceDocument,+ sourceDocumentId: splitInfo.sourceDocumentId,+ sourceDocumentReadableId:+ splitInfo.sourceDocumentReadableId,+ attributes: splitInfo.attributes as unknown as Json,+ companyId: splitInfo.companyId,+ createdBy: userId,+ createdAt: today,+ })+ .returning(["id"])+ .execute();++ const newTrackedEntityId = newTrackedEntity[0].id!;++ // Update the original entity's attributes to include the split entity ID+ const originalEntity = await trx+ .selectFrom("trackedEntity")+ .select(["attributes"])+ .where("id", "=", splitInfo.originalEntityId)+ .executeTakeFirst();++ if (originalEntity) {+ const updatedAttributes = {+ ...((originalEntity.attributes as TrackedEntityAttributes) ||+ {}),+ "Split Entity ID": newTrackedEntityId,+ };++ // Remove Shipment and Shipment Line attributes from the new entity+ const updatedAttributesObj = {+ ...((originalEntity.attributes as TrackedEntityAttributes) ||+ {}),+ };++ // Delete shipment-related attributes+ delete updatedAttributesObj["Shipment"];+ delete updatedAttributesObj["Shipment Line"];+ delete updatedAttributesObj["Shipment Line Index"];++ // Add the split entity reference+ updatedAttributesObj["Split Entity ID"] =+ newTrackedEntityId;++ // Update the original entity with the reference to the new split entity+ await trx+ .updateTable("trackedEntity")+ .set({+ attributes: updatedAttributes,+ })+ .where("id", "=", splitInfo.originalEntityId)+ .execute();+ }- // Update the original entity's attributes to include the split entity ID- const originalEntity = await trx- .selectFrom("trackedEntity")- .select(["attributes"])- .where("id", "=", splitInfo.originalEntityId)- .executeTakeFirst();+ // Record the new entity as output from the split+ await trx+ .insertInto("trackedActivityOutput")+ .values({+ trackedActivityId: splitActivityId,+ trackedEntityId: newTrackedEntityId,+ quantity: splitInfo.remainingQuantity,+ companyId: splitInfo.companyId,+ createdBy: userId,+ createdAt: today,+ })+ .execute();++ // Record the shipped portion as output (will be consumed by shipment)+ await trx+ .insertInto("trackedActivityOutput")+ .values({+ trackedActivityId: splitActivityId,+ trackedEntityId: splitInfo.originalEntityId,+ quantity: splitInfo.shippedQuantity,+ companyId: splitInfo.companyId,+ createdBy: userId,+ createdAt: today,+ })+ .execute();++ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLines.data.find(+ (sl) =>+ sl.id ===+ (splitInfo.attributes as TrackedEntityAttributes)?.[+ "Shipment Line"+ ]+ )?.itemId!,+ quantity: -splitInfo.originalQuantity,+ locationId: locationId,+ shelfId: shipmentLines.data.find(+ (sl) =>+ sl.id ===+ (splitInfo.attributes as TrackedEntityAttributes)?.[+ "Shipment Line"+ ]+ )?.shelfId,+ entryType: "Negative Adjmt.",+ documentType: "Batch Split",+ documentId: splitActivityId,+ trackedEntityId: splitInfo.originalEntityId,+ createdBy: userId,+ companyId,+ });++ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLines.data.find(+ (sl) =>+ sl.id ===+ (splitInfo.attributes as TrackedEntityAttributes)?.[+ "Shipment Line"+ ]+ )?.itemId!,+ quantity: splitInfo.shippedQuantity,+ locationId: locationId,+ shelfId: shipmentLines.data.find(+ (sl) =>+ sl.id ===+ (splitInfo.attributes as TrackedEntityAttributes)?.[+ "Shipment Line"+ ]+ )?.shelfId,+ entryType: "Positive Adjmt.",+ documentType: "Batch Split",+ documentId: splitActivityId,+ trackedEntityId: splitInfo.originalEntityId,+ createdBy: userId,+ companyId,+ });++ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLines.data.find(+ (sl) =>+ sl.id ===+ (splitInfo.attributes as TrackedEntityAttributes)?.[+ "Shipment Line"+ ]+ )?.itemId!,+ quantity: splitInfo.remainingQuantity,+ locationId: locationId,+ shelfId: shipmentLines.data.find(+ (sl) =>+ sl.id ===+ (splitInfo.attributes as TrackedEntityAttributes)?.[+ "Shipment Line"+ ]+ )?.shelfId,+ entryType: "Positive Adjmt.",+ documentType: "Batch Split",+ documentId: splitActivityId,+ trackedEntityId: newTrackedEntityId,+ createdBy: userId,+ companyId,+ });+ }++ // Now handle the shipment consumption+ for await (const [id, update] of Object.entries(+ trackedEntityUpdates+ )) {+ await trx+ .updateTable("trackedEntity")+ .set(update)+ .where("id", "=", id)+ .execute();++ if (trackedActivityId) {+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId,+ trackedEntityId: id,+ quantity: update.quantity ?? 0,+ companyId,+ createdBy: userId,+ createdAt: today,+ })+ .execute();+ }+ }+ }- if (originalEntity) {- const updatedAttributes = {- ...((originalEntity.attributes as TrackedEntityAttributes) ||- {}),- "Split Entity ID": newTrackedEntityId,- };+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .returning(["id"])+ .execute();+ }- // Remove Shipment and Shipment Line attributes from the new entity- const updatedAttributesObj = {- ...((originalEntity.attributes as TrackedEntityAttributes) ||- {}),- };+ if (Object.keys(jobUpdates).length > 0) {+ console.log("Final job updates to be applied:", jobUpdates);+ for await (const [jobId, update] of Object.entries(+ jobUpdates+ )) {+ console.log(`Updating job ${jobId} with:`, update);+ await trx+ .updateTable("job")+ .set(update)+ .where("id", "=", jobId)+ .execute();+ }+ }+ });+ break;+ }+ case "Purchase Order": {+ if (!shipment.data.sourceDocumentId)+ throw new Error("Shipment has no sourceDocumentId");++ const [purchaseOrder, purchaseOrderLines] = await Promise.all([+ client+ .from("purchaseOrder")+ .select("*")+ .eq("id", shipment.data.sourceDocumentId)+ .single(),+ client+ .from("purchaseOrderLine")+ .select("*")+ .eq("purchaseOrderId", shipment.data.sourceDocumentId),+ ]);+ if (purchaseOrder.error)+ throw new Error("Failed to fetch purchase order");+ if (purchaseOrderLines.error)+ throw new Error("Failed to fetch purchase order lines");++ const supplier = await client+ .from("supplier")+ .select("*")+ .eq("id", purchaseOrder.data.supplierId)+ .eq("companyId", companyId)+ .single();+ if (supplier.error) throw new Error("Failed to fetch supplier");- // Delete shipment-related attributes- delete updatedAttributesObj["Shipment"];- delete updatedAttributesObj["Shipment Line"];- delete updatedAttributesObj["Shipment Line Index"];+ const jobOperationsUpdates: Record<+ string,+ Database["public"]["Tables"]["jobOperation"]["Update"]+ > = {};- // Add the split entity reference- updatedAttributesObj["Split Entity ID"] = newTrackedEntityId;+ for await (const shipmentLine of shipmentLines.data) {+ const purchaseOrderLine = purchaseOrderLines.data.find(+ (pol) => pol.id === shipmentLine.lineId+ );- // Update the original entity with the reference to the new split entity- await trx- .updateTable("trackedEntity")- .set({- attributes: updatedAttributes,- })- .where("id", "=", splitInfo.originalEntityId)- .execute();+ if (+ purchaseOrderLine?.jobId &&+ purchaseOrderLine.jobOperationId+ ) {+ // Update quantity shipped on job, accumulating totals from multiple shipments+ const jobOperationId = purchaseOrderLine.jobOperationId;++ jobOperationsUpdates[jobOperationId] = {+ status: "In Progress",+ };+ continue;}+ }- // Record the new entity as output from the split- await trx- .insertInto("trackedActivityOutput")- .values({- trackedActivityId: splitActivityId,- trackedEntityId: newTrackedEntityId,- quantity: splitInfo.remainingQuantity,- companyId: splitInfo.companyId,- createdBy: userId,- createdAt: today,- })- .execute();+ const shipmentLinesByPurchaseOrderLineId =+ shipmentLines.data.reduce<+ Record<+ string,+ Database["public"]["Tables"]["shipmentLine"]["Row"][]+ >+ >((acc, shipmentLine) => {+ if (shipmentLine.lineId) {+ acc[shipmentLine.lineId] = [+ ...(acc[shipmentLine.lineId] ?? []),+ shipmentLine,+ ];+ }+ return acc;+ }, {});++ const purchaseOrderLineUpdates = purchaseOrderLines.data.reduce<+ Record<+ string,+ Database["public"]["Tables"]["purchaseOrderLine"]["Update"]+ >+ >((acc, purchaseOrderLine) => {+ const shipmentLines =+ shipmentLinesByPurchaseOrderLineId[purchaseOrderLine.id];+ if (+ shipmentLines &&+ shipmentLines.length > 0 &&+ purchaseOrderLine.purchaseQuantity &&+ purchaseOrderLine.purchaseQuantity > 0+ ) {+ const shippedQuantity = shipmentLines.reduce(+ (acc, shipmentLine) => {+ const safeShippedQuantity =+ isNaN(shipmentLine.shippedQuantity) ||+ shipmentLine.shippedQuantity == null+ ? 0+ : shipmentLine.shippedQuantity;+ return acc + safeShippedQuantity;+ },+ 0+ );++ const newQuantityShipped =+ (purchaseOrderLine.quantityShipped ?? 0) + shippedQuantity;++ const updates: Record<+ string,+ Database["public"]["Tables"]["purchaseOrderLine"]["Update"]+ > = {+ ...acc,+ [purchaseOrderLine.id]: {+ quantityShipped: newQuantityShipped,+ },+ };- // Record the shipped portion as output (will be consumed by shipment)- await trx- .insertInto("trackedActivityOutput")- .values({- trackedActivityId: splitActivityId,- trackedEntityId: splitInfo.originalEntityId,- quantity: splitInfo.shippedQuantity,- companyId: splitInfo.companyId,- createdBy: userId,- createdAt: today,- })- .execute();+ return updates;+ }- itemLedgerInserts.push({- postingDate: today,- itemId: shipmentLines.data.find(- (sl) =>- sl.id ===- (splitInfo.attributes as TrackedEntityAttributes)?.[- "Shipment Line"- ]- )?.itemId!,- quantity: -splitInfo.originalQuantity,- locationId: locationId,- shelfId: shipmentLines.data.find(- (sl) =>- sl.id ===- (splitInfo.attributes as TrackedEntityAttributes)?.[- "Shipment Line"- ]- )?.shelfId,- entryType: "Negative Adjmt.",- documentType: "Batch Split",- documentId: splitActivityId,- trackedEntityId: splitInfo.originalEntityId,- createdBy: userId,- companyId,- });-- itemLedgerInserts.push({- postingDate: today,- itemId: shipmentLines.data.find(- (sl) =>- sl.id ===- (splitInfo.attributes as TrackedEntityAttributes)?.[- "Shipment Line"- ]- )?.itemId!,- quantity: splitInfo.shippedQuantity,- locationId: locationId,- shelfId: shipmentLines.data.find(- (sl) =>- sl.id ===- (splitInfo.attributes as TrackedEntityAttributes)?.[- "Shipment Line"- ]- )?.shelfId,- entryType: "Positive Adjmt.",- documentType: "Batch Split",- documentId: splitActivityId,- trackedEntityId: splitInfo.originalEntityId,- createdBy: userId,- companyId,- });-- itemLedgerInserts.push({- postingDate: today,- itemId: shipmentLines.data.find(- (sl) =>- sl.id ===- (splitInfo.attributes as TrackedEntityAttributes)?.[- "Shipment Line"- ]- )?.itemId!,- quantity: splitInfo.remainingQuantity,- locationId: locationId,- shelfId: shipmentLines.data.find(- (sl) =>- sl.id ===- (splitInfo.attributes as TrackedEntityAttributes)?.[+ return acc;+ }, {});++ const trackedEntitySplits: Record<+ string,+ {+ originalEntityId: string;+ originalQuantity: number;+ shippedQuantity: number;+ remainingQuantity: number;+ attributes: TrackedEntityAttributes;+ sourceDocument: string;+ sourceDocumentId: string;+ sourceDocumentReadableId: string | null;+ companyId: string;+ }+ > = {};++ const trackedEntityUpdates =+ shipmentLineTracking.data?.reduce<+ Record<+ string,+ Database["public"]["Tables"]["trackedEntity"]["Update"]+ >+ >((acc, trackedEntity) => {+ const shipmentLine = shipmentLines.data?.find(+ (shipmentLine) =>+ shipmentLine.id ===+ (trackedEntity.attributes as TrackedEntityAttributes)?.["Shipment Line"]- )?.shelfId,- entryType: "Positive Adjmt.",- documentType: "Batch Split",- documentId: splitActivityId,- trackedEntityId: newTrackedEntityId,- createdBy: userId,- companyId,- });- }+ );++ if (+ shipmentLine?.shippedQuantity !== undefined &&+ trackedEntity.quantity !== undefined &&+ shipmentLine.shippedQuantity < trackedEntity.quantity+ ) {+ // Need to split the batch+ trackedEntitySplits[trackedEntity.id] = {+ originalEntityId: trackedEntity.id,+ originalQuantity: trackedEntity.quantity,+ shippedQuantity: shipmentLine.shippedQuantity,+ remainingQuantity:+ trackedEntity.quantity - shipmentLine.shippedQuantity,+ attributes:+ trackedEntity.attributes as TrackedEntityAttributes,+ sourceDocument: trackedEntity.sourceDocument,+ sourceDocumentId: trackedEntity.sourceDocumentId,+ sourceDocumentReadableId:+ trackedEntity.sourceDocumentReadableId,+ companyId: trackedEntity.companyId,+ };+ }++ acc[trackedEntity.id] = {+ quantity:+ shipmentLine?.shippedQuantity ?? trackedEntity.quantity,+ };++ return acc;+ }, {}) ?? {};++ await db.transaction().execute(async (trx) => {+ for await (const [purchaseOrderLineId, update] of Object.entries(+ purchaseOrderLineUpdates+ )) {+ await trx+ .updateTable("purchaseOrderLine")+ .set(update)+ .where("id", "=", purchaseOrderLineId)+ .execute();+ }- // Now handle the shipment consumption- for await (const [id, update] of Object.entries(- trackedEntityUpdates- )) {await trx- .updateTable("trackedEntity")- .set(update)- .where("id", "=", id)+ .updateTable("shipment")+ .set({+ status: "Posted",+ postingDate: today,+ postedBy: userId,+ })+ .where("id", "=", shipmentId).execute();- if (trackedActivityId) {- await trx- .insertInto("trackedActivityInput")+ if (Object.keys(trackedEntityUpdates).length > 0) {+ const trackedActivity = await trx+ .insertInto("trackedActivity").values({- trackedActivityId,- trackedEntityId: id,- quantity: update.quantity ?? 0,+ type: "Shipment",+ sourceDocument: "Shipment",+ sourceDocumentId: shipmentId,+ sourceDocumentReadableId: shipment.data.shipmentId,+ attributes: {+ Shipment: shipmentId,+ "Purchase Order": purchaseOrder.data.id,+ },companyId,createdBy: userId,createdAt: today,})+ .returning(["id"]).execute();++ const trackedActivityId = trackedActivity[0].id;++ // Handle batch splits first+ for await (const splitInfo of Object.values(+ trackedEntitySplits+ )) {+ // Create a split activity+ const splitActivity = await trx+ .insertInto("trackedActivity")+ .values({+ type: "Split",+ sourceDocument: "Shipment",+ sourceDocumentId: shipmentId,+ sourceDocumentReadableId: shipment.data.shipmentId,+ attributes: {+ "Original Quantity": splitInfo.originalQuantity,+ "Shipped Quantity": splitInfo.shippedQuantity,+ "Remaining Quantity": splitInfo.remainingQuantity,+ },+ companyId: splitInfo.companyId,+ createdBy: userId,+ createdAt: today,+ })+ .returning(["id"])+ .execute();++ const splitActivityId = splitActivity[0].id!;++ // Record the original entity as input to the split+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: splitActivityId,+ trackedEntityId: splitInfo.originalEntityId,+ quantity: splitInfo.originalQuantity,+ companyId: splitInfo.companyId,+ createdBy: userId,+ createdAt: today,+ })+ .execute();++ // Create a new tracked entity for the remaining quantity+ const newTrackedEntity = await trx+ .insertInto("trackedEntity")+ .values({+ quantity: splitInfo.remainingQuantity,+ status: "Available",+ sourceDocument: splitInfo.sourceDocument,+ sourceDocumentId: splitInfo.sourceDocumentId,+ sourceDocumentReadableId:+ splitInfo.sourceDocumentReadableId,+ attributes: splitInfo.attributes as unknown as Json,+ companyId: splitInfo.companyId,+ createdBy: userId,+ createdAt: today,+ })+ .returning(["id"])+ .execute();++ const newTrackedEntityId = newTrackedEntity[0].id!;++ // Update the original entity's attributes to include the split entity ID+ const originalEntity = await trx+ .selectFrom("trackedEntity")+ .select(["attributes"])+ .where("id", "=", splitInfo.originalEntityId)+ .executeTakeFirst();++ if (originalEntity) {+ const updatedAttributes = {+ ...((originalEntity.attributes as TrackedEntityAttributes) ||+ {}),+ "Split Entity ID": newTrackedEntityId,+ };++ // Remove Shipment and Shipment Line attributes from the new entity+ const updatedAttributesObj = {+ ...((originalEntity.attributes as TrackedEntityAttributes) ||+ {}),+ };++ // Delete shipment-related attributes+ delete updatedAttributesObj["Shipment"];+ delete updatedAttributesObj["Shipment Line"];+ delete updatedAttributesObj["Shipment Line Index"];++ // Add the split entity reference+ updatedAttributesObj["Split Entity ID"] =+ newTrackedEntityId;++ // Update the original entity with the reference to the new split entity+ await trx+ .updateTable("trackedEntity")+ .set({+ attributes: updatedAttributes,+ })+ .where("id", "=", splitInfo.originalEntityId)+ .execute();+ }++ // Record the new entity as output from the split+ await trx+ .insertInto("trackedActivityOutput")+ .values({+ trackedActivityId: splitActivityId,+ trackedEntityId: newTrackedEntityId,+ quantity: splitInfo.remainingQuantity,+ companyId: splitInfo.companyId,+ createdBy: userId,+ createdAt: today,+ })+ .execute();++ // Record the shipped portion as output (will be consumed by shipment)+ await trx+ .insertInto("trackedActivityOutput")+ .values({+ trackedActivityId: splitActivityId,+ trackedEntityId: splitInfo.originalEntityId,+ quantity: splitInfo.shippedQuantity,+ companyId: splitInfo.companyId,+ createdBy: userId,+ createdAt: today,+ })+ .execute();+ }++ // Now handle the shipment consumption+ for await (const [id, update] of Object.entries(+ trackedEntityUpdates+ )) {+ await trx+ .updateTable("trackedEntity")+ .set(update)+ .where("id", "=", id)+ .execute();++ if (trackedActivityId) {+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId,+ trackedEntityId: id,+ quantity: update.quantity ?? 0,+ companyId,+ createdBy: userId,+ createdAt: today,+ })+ .execute();+ }+ }}- }- }- if (itemLedgerInserts.length > 0) {- await trx- .insertInto("itemLedger")- .values(itemLedgerInserts)- .returning(["id"])- .execute();+ if (Object.keys(jobOperationsUpdates).length > 0) {+ console.log(+ "Final job updates to be applied:",+ jobOperationsUpdates+ );+ for await (const [jobOperationId, update] of Object.entries(+ jobOperationsUpdates+ )) {+ console.log(+ `Updating job operation ${jobOperationId} with:`,+ update+ );+ await trx+ .updateTable("jobOperation")+ .set(update)+ .where("id", "=", jobOperationId)+ .execute();+ }+ }+ });+ break;}+ case "Outbound Transfer": {+ if (!shipment.data.sourceDocumentId)+ throw new Error("Shipment has no sourceDocumentId");++ const [warehouseTransfer, warehouseTransferLines] =+ await Promise.all([+ client+ .from("warehouseTransfer")+ .select("*")+ .eq("id", shipment.data.sourceDocumentId)+ .single(),+ client+ .from("warehouseTransferLine")+ .select("*")+ .eq("transferId", shipment.data.sourceDocumentId),+ ]);++ if (warehouseTransfer.error)+ throw new Error("Failed to fetch warehouse transfer");+ if (warehouseTransferLines.error)+ throw new Error("Failed to fetch warehouse transfer lines");++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];+ const warehouseTransferLineUpdates: Record<+ string,+ Database["public"]["Tables"]["warehouseTransferLine"]["Update"]+ > = {};- if (Object.keys(jobUpdates).length > 0) {- console.log("Final job updates to be applied:", jobUpdates);- for await (const [jobId, update] of Object.entries(jobUpdates)) {- console.log(`Updating job ${jobId} with:`, update);- await trx- .updateTable("job")- .set(update)- .where("id", "=", jobId)- .execute();- }- }- });- break;- }- case "Purchase Order": {- if (!shipment.data.sourceDocumentId)- throw new Error("Shipment has no sourceDocumentId");-- const [purchaseOrder, purchaseOrderLines] = await Promise.all([- client- .from("purchaseOrder")- .select("*")- .eq("id", shipment.data.sourceDocumentId)- .single(),- client- .from("purchaseOrderLine")- .select("*")- .eq("purchaseOrderId", shipment.data.sourceDocumentId),- ]);- if (purchaseOrder.error)- throw new Error("Failed to fetch purchase order");- if (purchaseOrderLines.error)- throw new Error("Failed to fetch purchase order lines");-- const supplier = await client- .from("supplier")- .select("*")- .eq("id", purchaseOrder.data.supplierId)- .eq("companyId", companyId)- .single();- if (supplier.error) throw new Error("Failed to fetch supplier");-- const jobOperationsUpdates: Record<- string,- Database["public"]["Tables"]["jobOperation"]["Update"]- > = {};-- for await (const shipmentLine of shipmentLines.data) {- const purchaseOrderLine = purchaseOrderLines.data.find(- (pol) => pol.id === shipmentLine.lineId- );-- if (purchaseOrderLine?.jobId && purchaseOrderLine.jobOperationId) {- // Update quantity shipped on job, accumulating totals from multiple shipments- const jobOperationId = purchaseOrderLine.jobOperationId;-- jobOperationsUpdates[jobOperationId] = {- status: "In Progress",- };- continue;- }- }+ // Process each shipment line+ for await (const shipmentLine of shipmentLines.data) {+ const warehouseTransferLine = warehouseTransferLines.data.find(+ (line) => line.id === shipmentLine.lineId+ );- const shipmentLinesByPurchaseOrderLineId = shipmentLines.data.reduce<- Record<string, Database["public"]["Tables"]["shipmentLine"]["Row"][]>- >((acc, shipmentLine) => {- if (shipmentLine.lineId) {- acc[shipmentLine.lineId] = [- ...(acc[shipmentLine.lineId] ?? []),- shipmentLine,- ];- }- return acc;- }, {});-- const purchaseOrderLineUpdates = purchaseOrderLines.data.reduce<- Record<- string,- Database["public"]["Tables"]["purchaseOrderLine"]["Update"]- >- >((acc, purchaseOrderLine) => {- const shipmentLines =- shipmentLinesByPurchaseOrderLineId[purchaseOrderLine.id];- if (- shipmentLines &&- shipmentLines.length > 0 &&- purchaseOrderLine.purchaseQuantity &&- purchaseOrderLine.purchaseQuantity > 0- ) {- const shippedQuantity = shipmentLines.reduce(- (acc, shipmentLine) => {- const safeShippedQuantity = isNaN(shipmentLine.shippedQuantity) || shipmentLine.shippedQuantity == null ? 0 : shipmentLine.shippedQuantity;- return acc + safeShippedQuantity;- },- 0- );+ if (!warehouseTransferLine) continue;- const newQuantityShipped =- (purchaseOrderLine.quantityShipped ?? 0) + shippedQuantity;+ const shippedQuantity =+ isNaN(shipmentLine.shippedQuantity) ||+ shipmentLine.shippedQuantity == null+ ? 0+ : shipmentLine.shippedQuantity;- const updates: Record<- string,- Database["public"]["Tables"]["purchaseOrderLine"]["Update"]- > = {- ...acc,- [purchaseOrderLine.id]: {- quantityShipped: newQuantityShipped,- },- };-- return updates;- }+ // Update warehouse transfer line shipped quantity+ const newShippedQuantity =+ (warehouseTransferLine.shippedQuantity ?? 0) + shippedQuantity;- return acc;- }, {});-- const trackedEntitySplits: Record<- string,- {- originalEntityId: string;- originalQuantity: number;- shippedQuantity: number;- remainingQuantity: number;- attributes: TrackedEntityAttributes;- sourceDocument: string;- sourceDocumentId: string;- sourceDocumentReadableId: string | null;- companyId: string;- }- > = {};+ warehouseTransferLineUpdates[warehouseTransferLine.id] = {+ shippedQuantity: newShippedQuantity,+ };- const trackedEntityUpdates =- shipmentLineTracking.data?.reduce<- Record<- string,- Database["public"]["Tables"]["trackedEntity"]["Update"]- >- >((acc, trackedEntity) => {- const shipmentLine = shipmentLines.data?.find(- (shipmentLine) =>- shipmentLine.id ===- (trackedEntity.attributes as TrackedEntityAttributes)?.[- "Shipment Line"- ]+ // Create item ledger entry for negative adjustment at source+ if (shippedQuantity !== 0) {+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: -shippedQuantity, // Negative for outbound transfer+ locationId: shipmentLine.locationId,+ shelfId: shipmentLine.shelfId,+ entryType: "Transfer",+ documentType: "Transfer Shipment",+ documentId: warehouseTransfer.data?.transferId,+ externalDocumentId:+ shipment.data?.externalDocumentId ?? undefined,+ createdBy: userId,+ companyId,+ });+ }+ }++ // Check if all lines are fully shipped+ const allLinesFullyShipped = warehouseTransferLines.data.every(+ (line) => {+ const updates = warehouseTransferLineUpdates[line.id];+ const shippedQty =+ updates?.shippedQuantity ?? line.shippedQuantity ?? 0;+ return shippedQty >= (line.quantity ?? 0);+ });- if (- shipmentLine?.shippedQuantity !== undefined &&- trackedEntity.quantity !== undefined &&- shipmentLine.shippedQuantity < trackedEntity.quantity- ) {- // Need to split the batch- trackedEntitySplits[trackedEntity.id] = {- originalEntityId: trackedEntity.id,- originalQuantity: trackedEntity.quantity,- shippedQuantity: shipmentLine.shippedQuantity,- remainingQuantity:- trackedEntity.quantity - shipmentLine.shippedQuantity,- attributes: trackedEntity.attributes as TrackedEntityAttributes,- sourceDocument: trackedEntity.sourceDocument,- sourceDocumentId: trackedEntity.sourceDocumentId,- sourceDocumentReadableId:- trackedEntity.sourceDocumentReadableId,- companyId: trackedEntity.companyId,- };+ // Check if all lines are fully received+ const allLinesFullyReceived = warehouseTransferLines.data.every(+ (line) => {+ const receivedQty = line.receivedQuantity ?? 0;+ return receivedQty >= (line.quantity ?? 0);+ }+ );++ // Determine new warehouse transfer status+ let newStatus: Database["public"]["Tables"]["warehouseTransfer"]["Row"]["status"] =+ warehouseTransfer.data.status;++ if (allLinesFullyShipped && allLinesFullyReceived) {+ newStatus = "Completed";+ } else if (allLinesFullyShipped && !allLinesFullyReceived) {+ newStatus = "To Receive";+ } else if (!allLinesFullyShipped && allLinesFullyReceived) {+ newStatus = "To Ship";}- acc[trackedEntity.id] = {- quantity: shipmentLine?.shippedQuantity ?? trackedEntity.quantity,- };-- return acc;- }, {}) ?? {};-- await db.transaction().execute(async (trx) => {- for await (const [purchaseOrderLineId, update] of Object.entries(- purchaseOrderLineUpdates- )) {- await trx- .updateTable("purchaseOrderLine")- .set(update)- .where("id", "=", purchaseOrderLineId)- .execute();- }+ await db.transaction().execute(async (trx) => {+ // Update warehouse transfer lines+ for await (const [lineId, update] of Object.entries(+ warehouseTransferLineUpdates+ )) {+ await trx+ .updateTable("warehouseTransferLine")+ .set(update)+ .where("id", "=", lineId)+ .execute();+ }- await trx- .updateTable("shipment")- .set({- status: "Posted",- postingDate: today,- postedBy: userId,- })- .where("id", "=", shipmentId)- .execute();-- if (Object.keys(trackedEntityUpdates).length > 0) {- const trackedActivity = await trx- .insertInto("trackedActivity")- .values({- type: "Shipment",- sourceDocument: "Shipment",- sourceDocumentId: shipmentId,- sourceDocumentReadableId: shipment.data.shipmentId,- attributes: {- Shipment: shipmentId,- "Purchase Order": purchaseOrder.data.id,- },- companyId,- createdBy: userId,- createdAt: today,- })- .returning(["id"])- .execute();-- const trackedActivityId = trackedActivity[0].id;-- // Handle batch splits first- for await (const splitInfo of Object.values(trackedEntitySplits)) {- // Create a split activity- const splitActivity = await trx- .insertInto("trackedActivity")- .values({- type: "Split",- sourceDocument: "Shipment",- sourceDocumentId: shipmentId,- sourceDocumentReadableId: shipment.data.shipmentId,- attributes: {- "Original Quantity": splitInfo.originalQuantity,- "Shipped Quantity": splitInfo.shippedQuantity,- "Remaining Quantity": splitInfo.remainingQuantity,- },- companyId: splitInfo.companyId,- createdBy: userId,- createdAt: today,+ // Update warehouse transfer status+ await trx+ .updateTable("warehouseTransfer")+ .set({+ status: newStatus,+ transferDate: today,+ updatedBy: userId,})- .returning(["id"])+ .where("id", "=", warehouseTransfer.data.id).execute();- const splitActivityId = splitActivity[0].id!;+ // Create item ledger entries+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .returning(["id"])+ .execute();+ }- // Record the original entity as input to the split+ // Update shipment statusawait trx- .insertInto("trackedActivityInput")- .values({- trackedActivityId: splitActivityId,- trackedEntityId: splitInfo.originalEntityId,- quantity: splitInfo.originalQuantity,- companyId: splitInfo.companyId,- createdBy: userId,- createdAt: today,+ .updateTable("shipment")+ .set({+ status: "Posted",+ postedBy: userId,})+ .where("id", "=", shipmentId).execute();+ });- // Create a new tracked entity for the remaining quantity- const newTrackedEntity = await trx- .insertInto("trackedEntity")- .values({- quantity: splitInfo.remainingQuantity,- status: "Available",- sourceDocument: splitInfo.sourceDocument,- sourceDocumentId: splitInfo.sourceDocumentId,- sourceDocumentReadableId: splitInfo.sourceDocumentReadableId,- attributes: splitInfo.attributes as unknown as Json,- companyId: splitInfo.companyId,- createdBy: userId,- createdAt: today,- })- .returning(["id"])- .execute();+ break;+ }- const newTrackedEntityId = newTrackedEntity[0].id!;+ default: {+ throw new Error(+ `Invalid source document type: ${shipment.data.sourceDocument}`+ );+ }+ }+ break;+ }+ case "void": {+ switch (shipment.data?.sourceDocument) {+ case "Sales Order": {+ if (!shipment.data.sourceDocumentId)+ throw new Error("Shipment has no sourceDocumentId");++ const [salesOrder, salesOrderLines] = await Promise.all([+ client+ .from("salesOrder")+ .select("*")+ .eq("id", shipment.data.sourceDocumentId)+ .single(),+ client+ .from("salesOrderLine")+ .select("*")+ .eq("salesOrderId", shipment.data.sourceDocumentId),+ ]);+ if (salesOrder.error)+ throw new Error("Failed to fetch sales order");+ if (salesOrderLines.error)+ throw new Error("Failed to fetch sales order lines");++ const customer = await client+ .from("customer")+ .select("*")+ .eq("id", salesOrder.data.customerId)+ .eq("companyId", companyId)+ .single();+ if (customer.error) throw new Error("Failed to fetch customer");- // Update the original entity's attributes to include the split entity ID- const originalEntity = await trx- .selectFrom("trackedEntity")- .select(["attributes"])- .where("id", "=", splitInfo.originalEntityId)- .executeTakeFirst();+ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];- if (originalEntity) {- const updatedAttributes = {- ...((originalEntity.attributes as TrackedEntityAttributes) ||- {}),- "Split Entity ID": newTrackedEntityId,+ const jobUpdates: Record<+ string,+ Database["public"]["Tables"]["job"]["Update"]+ > = {};++ const locationId = shipment.data.locationId;+ for await (const shipmentLine of shipmentLines.data) {+ if (+ shipmentLine.fulfillment?.type === "Job" &&+ shipmentLine.fulfillment?.jobId+ ) {+ // Reverse job quantities for void shipment+ const jobId = shipmentLine.fulfillment.jobId;+ const currentJob = jobs.data.find((j) => j.id === jobId);++ console.log("Processing job void:", {+ jobId,+ currentJob: currentJob+ ? {+ id: currentJob.id,+ quantity: currentJob.quantity,+ quantityShipped: currentJob.quantityShipped,+ quantityComplete: currentJob.quantityComplete,+ status: currentJob.status,+ }+ : null,+ shipmentLine: {+ id: shipmentLine.id,+ shippedQuantity: shipmentLine.shippedQuantity,+ shippedQuantityType: typeof shipmentLine.shippedQuantity,+ },+ });++ const currentQuantityShipped = currentJob?.quantityShipped ?? 0;++ // Ensure shippedQuantity is a valid number+ const shippedQuantity =+ typeof shipmentLine.shippedQuantity === "number" &&+ !isNaN(shipmentLine.shippedQuantity)+ ? shipmentLine.shippedQuantity+ : 0;++ console.log("Calculated values for void:", {+ currentQuantityShipped,+ shippedQuantity,+ newTotal: currentQuantityShipped - shippedQuantity,+ jobQuantity: currentJob?.quantity,+ });++ // Reduce shipped quantity (reverse of posting)+ const newQuantityShipped = Math.max(+ 0,+ currentQuantityShipped - shippedQuantity+ );+ const newQuantityComplete = Math.max(+ 0,+ (currentJob?.quantityComplete ?? 0) - shippedQuantity+ );++ // Update status based on new quantities+ let newStatus = currentJob?.status;+ if (+ currentJob?.status === "Completed" &&+ newQuantityShipped < (currentJob?.quantity ?? 0)+ ) {+ newStatus = "In Progress";+ }++ jobUpdates[jobId] = {+ status: newStatus,+ quantityComplete: newQuantityComplete,+ quantityShipped: newQuantityShipped,};- // Remove Shipment and Shipment Line attributes from the new entity- const updatedAttributesObj = {- ...((originalEntity.attributes as TrackedEntityAttributes) ||- {}),+ continue;+ }++ const itemTrackingType =+ items.data.find((item) => item.id === shipmentLine.itemId)+ ?.itemTrackingType ?? "Inventory";++ // Default shippedQuantity to 0 if not defined or NaN+ const shippedQuantity =+ isNaN(shipmentLine.shippedQuantity) ||+ shipmentLine.shippedQuantity == null+ ? 0+ : shipmentLine.shippedQuantity;++ if (itemTrackingType === "Inventory") {+ // Create positive adjustment to restore inventory+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: shippedQuantity, // Positive to restore inventory+ locationId: shipmentLine.locationId ?? locationId,+ shelfId: shipmentLine.shelfId,+ entryType: "Positive Adjmt.",+ documentType: "Sales Shipment",+ documentId: shipment.data?.id ?? undefined,+ externalDocumentId: undefined,+ createdBy: userId,+ companyId,+ });+ }++ if (shipmentLine.requiresBatchTracking) {+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: shippedQuantity, // Positive to restore inventory+ locationId: shipmentLine.locationId ?? locationId,+ shelfId: shipmentLine.shelfId,+ entryType: "Positive Adjmt.",+ documentType: "Sales Shipment",+ documentId: shipment.data?.id ?? undefined,+ trackedEntityId: shipmentLineTracking.data?.find(+ (tracking) =>+ (+ tracking.attributes as+ | TrackedEntityAttributes+ | undefined+ )?.["Shipment Line"] === shipmentLine.id+ )?.id,+ externalDocumentId: undefined,+ createdBy: userId,+ companyId,+ });+ }++ if (shipmentLine.requiresSerialTracking) {+ const lineTracking = shipmentLineTracking.data?.filter(+ (tracking) =>+ (+ tracking.attributes as TrackedEntityAttributes | undefined+ )?.["Shipment Line"] === shipmentLine.id+ );++ lineTracking?.forEach((tracking) => {+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: 1, // Positive to restore inventory+ locationId: shipmentLine.locationId ?? locationId,+ shelfId: shipmentLine.shelfId,+ entryType: "Positive Adjmt.",+ documentType: "Sales Shipment",+ documentId: shipment.data?.id ?? undefined,+ trackedEntityId: tracking.id,+ externalDocumentId: undefined,+ createdBy: userId,+ companyId,+ });+ });+ }+ }++ const shipmentLinesBySalesOrderLineId = shipmentLines.data.reduce<+ Record<+ string,+ Database["public"]["Tables"]["shipmentLine"]["Row"][]+ >+ >((acc, shipmentLine) => {+ if (shipmentLine.lineId) {+ acc[shipmentLine.lineId] = [+ ...(acc[shipmentLine.lineId] ?? []),+ shipmentLine,+ ];+ }+ return acc;+ }, {});++ // Reverse sales order line updates+ const salesOrderLineUpdates = salesOrderLines.data.reduce<+ Record<+ string,+ Database["public"]["Tables"]["salesOrderLine"]["Update"]+ >+ >((acc, salesOrderLine) => {+ const shipmentLines =+ shipmentLinesBySalesOrderLineId[salesOrderLine.id];+ if (+ shipmentLines &&+ shipmentLines.length > 0 &&+ salesOrderLine.saleQuantity &&+ salesOrderLine.saleQuantity > 0+ ) {+ const shippedQuantity = shipmentLines.reduce(+ (acc, shipmentLine) => {+ const safeShippedQuantity =+ isNaN(shipmentLine.shippedQuantity) ||+ shipmentLine.shippedQuantity == null+ ? 0+ : shipmentLine.shippedQuantity;+ return acc + safeShippedQuantity;+ },+ 0+ );++ // Reduce shipped quantity (reverse of posting)+ const newQuantitySent = Math.max(+ 0,+ (salesOrderLine.quantitySent ?? 0) - shippedQuantity+ );++ const sentComplete =+ newQuantitySent >= salesOrderLine.saleQuantity;++ const updates: Record<+ string,+ Database["public"]["Tables"]["salesOrderLine"]["Update"]+ > = {+ ...acc,+ [salesOrderLine.id]: {+ quantitySent: newQuantitySent,+ sentComplete,+ },};- // Delete shipment-related attributes- delete updatedAttributesObj["Shipment"];- delete updatedAttributesObj["Shipment Line"];- delete updatedAttributesObj["Shipment Line Index"];+ // Clear sent date if no longer complete+ if (!sentComplete && salesOrderLine.sentDate) {+ updates[salesOrderLine.id].sentDate = null;+ }++ return updates;+ }++ return acc;+ }, {});++ // Restore tracked entities to available status+ const trackedEntityUpdates =+ shipmentLineTracking.data?.reduce<+ Record<+ string,+ Database["public"]["Tables"]["trackedEntity"]["Update"]+ >+ >((acc, trackedEntity) => {+ const shipmentLine = shipmentLines.data?.find(+ (shipmentLine) =>+ shipmentLine.id ===+ (trackedEntity.attributes as TrackedEntityAttributes)?.[+ "Shipment Line"+ ]+ );++ // Restore original quantity and set to available+ acc[trackedEntity.id] = {+ status: "Available",+ quantity: trackedEntity.quantity, // Restore original quantity+ };- // Add the split entity reference- updatedAttributesObj["Split Entity ID"] = newTrackedEntityId;+ return acc;+ }, {}) ?? {};- // Update the original entity with the reference to the new split entity+ await db.transaction().execute(async (trx) => {+ // Update sales order lines to reverse shipped quantities+ for await (const [salesOrderLineId, update] of Object.entries(+ salesOrderLineUpdates+ )) {await trx- .updateTable("trackedEntity")- .set({- attributes: updatedAttributes,- })- .where("id", "=", splitInfo.originalEntityId)+ .updateTable("salesOrderLine")+ .set(update)+ .where("id", "=", salesOrderLineId).execute();}- // Record the new entity as output from the split+ const salesOrderLines = await trx+ .selectFrom("salesOrderLine")+ .select([+ "id",+ "salesOrderLineType",+ "invoicedComplete",+ "sentComplete",+ ])+ .where("salesOrderId", "=", salesOrder.data.id)+ .execute();++ const areAllLinesInvoiced = salesOrderLines.every(+ (line) =>+ line.salesOrderLineType === "Comment" || line.invoicedComplete+ );++ const areAllLinesShipped = salesOrderLines.every(+ (line) =>+ line.salesOrderLineType === "Comment" || line.sentComplete+ );++ let status: Database["public"]["Tables"]["salesOrder"]["Row"]["status"] =+ "To Ship and Invoice";+ if (areAllLinesInvoiced && areAllLinesShipped) {+ status = "Completed";+ } else if (areAllLinesShipped) {+ status = "To Invoice";+ } else if (areAllLinesInvoiced) {+ status = "To Ship";+ }+await trx- .insertInto("trackedActivityOutput")- .values({- trackedActivityId: splitActivityId,- trackedEntityId: newTrackedEntityId,- quantity: splitInfo.remainingQuantity,- companyId: splitInfo.companyId,- createdBy: userId,- createdAt: today,+ .updateTable("salesOrder")+ .set({+ status,})+ .where("id", "=", salesOrder.data.id).execute();- // Record the shipped portion as output (will be consumed by shipment)+ // Update shipment status to Voidedawait trx- .insertInto("trackedActivityOutput")- .values({- trackedActivityId: splitActivityId,- trackedEntityId: splitInfo.originalEntityId,- quantity: splitInfo.shippedQuantity,- companyId: splitInfo.companyId,- createdBy: userId,- createdAt: today,+ .updateTable("shipment")+ .set({+ status: "Voided",+ updatedAt: today,+ updatedBy: userId,})+ .where("id", "=", shipmentId).execute();++ // Restore tracked entities to available status+ if (Object.keys(trackedEntityUpdates).length > 0) {+ const voidActivity = await trx+ .insertInto("trackedActivity")+ .values({+ type: "Void Shipment",+ sourceDocument: "Shipment",+ sourceDocumentId: shipmentId,+ sourceDocumentReadableId: shipment.data.shipmentId,+ attributes: {+ Shipment: shipmentId,+ "Sales Order": salesOrder.data.id,+ },+ companyId,+ createdBy: userId,+ createdAt: today,+ })+ .returning(["id"])+ .execute();++ const voidActivityId = voidActivity[0].id;++ // Restore tracked entities+ for await (const [id, update] of Object.entries(+ trackedEntityUpdates+ )) {+ await trx+ .updateTable("trackedEntity")+ .set(update)+ .where("id", "=", id)+ .execute();++ if (voidActivityId) {+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: voidActivityId,+ trackedEntityId: id,+ quantity: update.quantity ?? 0,+ companyId,+ createdBy: userId,+ createdAt: today,+ })+ .execute();+ }+ }+ }++ // Create reversing item ledger entries+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .returning(["id"])+ .execute();+ }++ // Update jobs to reverse shipped quantities+ if (Object.keys(jobUpdates).length > 0) {+ console.log(+ "Final job void updates to be applied:",+ jobUpdates+ );+ for await (const [jobId, update] of Object.entries(+ jobUpdates+ )) {+ console.log(`Voiding job ${jobId} with:`, update);+ await trx+ .updateTable("job")+ .set(update)+ .where("id", "=", jobId)+ .execute();+ }+ }+ });+ break;+ }+ case "Purchase Order": {+ if (!shipment.data.sourceDocumentId)+ throw new Error("Shipment has no sourceDocumentId");++ const [purchaseOrder, purchaseOrderLines] = await Promise.all([+ client+ .from("purchaseOrder")+ .select("*")+ .eq("id", shipment.data.sourceDocumentId)+ .single(),+ client+ .from("purchaseOrderLine")+ .select("*")+ .eq("purchaseOrderId", shipment.data.sourceDocumentId),+ ]);+ if (purchaseOrder.error)+ throw new Error("Failed to fetch purchase order");+ if (purchaseOrderLines.error)+ throw new Error("Failed to fetch purchase order lines");++ const supplier = await client+ .from("supplier")+ .select("*")+ .eq("id", purchaseOrder.data.supplierId)+ .eq("companyId", companyId)+ .single();+ if (supplier.error) throw new Error("Failed to fetch supplier");++ const jobOperationsUpdates: Record<+ string,+ Database["public"]["Tables"]["jobOperation"]["Update"]+ > = {};++ for await (const shipmentLine of shipmentLines.data) {+ const purchaseOrderLine = purchaseOrderLines.data.find(+ (pol) => pol.id === shipmentLine.lineId+ );++ if (+ purchaseOrderLine?.jobId &&+ purchaseOrderLine.jobOperationId+ ) {+ // Reset job operation status when voiding+ const jobOperationId = purchaseOrderLine.jobOperationId;++ jobOperationsUpdates[jobOperationId] = {+ status: "Ready",+ };+ continue;+ }}- // Now handle the shipment consumption- for await (const [id, update] of Object.entries(- trackedEntityUpdates- )) {+ const shipmentLinesByPurchaseOrderLineId =+ shipmentLines.data.reduce<+ Record<+ string,+ Database["public"]["Tables"]["shipmentLine"]["Row"][]+ >+ >((acc, shipmentLine) => {+ if (shipmentLine.lineId) {+ acc[shipmentLine.lineId] = [+ ...(acc[shipmentLine.lineId] ?? []),+ shipmentLine,+ ];+ }+ return acc;+ }, {});++ // Reverse purchase order line updates+ const purchaseOrderLineUpdates = purchaseOrderLines.data.reduce<+ Record<+ string,+ Database["public"]["Tables"]["purchaseOrderLine"]["Update"]+ >+ >((acc, purchaseOrderLine) => {+ const shipmentLines =+ shipmentLinesByPurchaseOrderLineId[purchaseOrderLine.id];+ if (+ shipmentLines &&+ shipmentLines.length > 0 &&+ purchaseOrderLine.purchaseQuantity &&+ purchaseOrderLine.purchaseQuantity > 0+ ) {+ const shippedQuantity = shipmentLines.reduce(+ (acc, shipmentLine) => {+ const safeShippedQuantity =+ isNaN(shipmentLine.shippedQuantity) ||+ shipmentLine.shippedQuantity == null+ ? 0+ : shipmentLine.shippedQuantity;+ return acc + safeShippedQuantity;+ },+ 0+ );++ // Reduce shipped quantity (reverse of posting)+ const newQuantityShipped = Math.max(+ 0,+ (purchaseOrderLine.quantityShipped ?? 0) - shippedQuantity+ );++ const updates: Record<+ string,+ Database["public"]["Tables"]["purchaseOrderLine"]["Update"]+ > = {+ ...acc,+ [purchaseOrderLine.id]: {+ quantityShipped: newQuantityShipped,+ },+ };++ return updates;+ }++ return acc;+ }, {});++ // Restore tracked entities to available status+ const trackedEntityUpdates =+ shipmentLineTracking.data?.reduce<+ Record<+ string,+ Database["public"]["Tables"]["trackedEntity"]["Update"]+ >+ >((acc, trackedEntity) => {+ // Restore original quantity and set to available+ acc[trackedEntity.id] = {+ status: "Available",+ quantity: trackedEntity.quantity,+ };++ return acc;+ }, {}) ?? {};++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];+ const locationId = shipment.data.locationId;++ // Create reversing item ledger entries for purchase order void+ for await (const shipmentLine of shipmentLines.data) {+ const itemTrackingType =+ items.data.find((item) => item.id === shipmentLine.itemId)+ ?.itemTrackingType ?? "Inventory";++ const shippedQuantity =+ isNaN(shipmentLine.shippedQuantity) ||+ shipmentLine.shippedQuantity == null+ ? 0+ : shipmentLine.shippedQuantity;++ if (itemTrackingType === "Inventory" && shippedQuantity !== 0) {+ // Create negative adjustment to remove inventory that was added during posting+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: -shippedQuantity, // Negative to remove inventory+ locationId: shipmentLine.locationId ?? locationId,+ shelfId: shipmentLine.shelfId,+ entryType: "Negative Adjmt.",+ documentType: "Purchase Receipt",+ documentId: shipment.data?.id ?? undefined,+ externalDocumentId: undefined,+ createdBy: userId,+ companyId,+ });+ }++ if (shipmentLine.requiresBatchTracking) {+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: -shippedQuantity, // Negative to remove inventory+ locationId: shipmentLine.locationId ?? locationId,+ shelfId: shipmentLine.shelfId,+ entryType: "Negative Adjmt.",+ documentType: "Purchase Receipt",+ documentId: shipment.data?.id ?? undefined,+ trackedEntityId: shipmentLineTracking.data?.find(+ (tracking) =>+ (+ tracking.attributes as+ | TrackedEntityAttributes+ | undefined+ )?.["Shipment Line"] === shipmentLine.id+ )?.id,+ externalDocumentId: undefined,+ createdBy: userId,+ companyId,+ });+ }++ if (shipmentLine.requiresSerialTracking) {+ const lineTracking = shipmentLineTracking.data?.filter(+ (tracking) =>+ (+ tracking.attributes as TrackedEntityAttributes | undefined+ )?.["Shipment Line"] === shipmentLine.id+ );++ lineTracking?.forEach((tracking) => {+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: -1, // Negative to remove inventory+ locationId: shipmentLine.locationId ?? locationId,+ shelfId: shipmentLine.shelfId,+ entryType: "Negative Adjmt.",+ documentType: "Purchase Receipt",+ documentId: shipment.data?.id ?? undefined,+ trackedEntityId: tracking.id,+ externalDocumentId: undefined,+ createdBy: userId,+ companyId,+ });+ });+ }+ }++ await db.transaction().execute(async (trx) => {+ // Update purchase order lines to reverse shipped quantities+ for await (const [purchaseOrderLineId, update] of Object.entries(+ purchaseOrderLineUpdates+ )) {+ await trx+ .updateTable("purchaseOrderLine")+ .set(update)+ .where("id", "=", purchaseOrderLineId)+ .execute();+ }++ // Create reversing item ledger entries+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .returning(["id"])+ .execute();+ }++ // Update shipment status to Voidedawait trx- .updateTable("trackedEntity")- .set(update)- .where("id", "=", id)+ .updateTable("shipment")+ .set({+ status: "Voided",+ updatedAt: today,+ updatedBy: userId,+ })+ .where("id", "=", shipmentId).execute();- if (trackedActivityId) {- await trx- .insertInto("trackedActivityInput")+ // Restore tracked entities+ if (Object.keys(trackedEntityUpdates).length > 0) {+ const voidActivity = await trx+ .insertInto("trackedActivity").values({- trackedActivityId,- trackedEntityId: id,- quantity: update.quantity ?? 0,+ type: "Void Shipment",+ sourceDocument: "Shipment",+ sourceDocumentId: shipmentId,+ sourceDocumentReadableId: shipment.data.shipmentId,+ attributes: {+ Shipment: shipmentId,+ "Purchase Order": purchaseOrder.data.id,+ },companyId,createdBy: userId,createdAt: today,})+ .returning(["id"]).execute();++ const voidActivityId = voidActivity[0].id;++ // Restore tracked entities+ for await (const [id, update] of Object.entries(+ trackedEntityUpdates+ )) {+ await trx+ .updateTable("trackedEntity")+ .set(update)+ .where("id", "=", id)+ .execute();++ if (voidActivityId) {+ await trx+ .insertInto("trackedActivityInput")+ .values({+ trackedActivityId: voidActivityId,+ trackedEntityId: id,+ quantity: update.quantity ?? 0,+ companyId,+ createdBy: userId,+ createdAt: today,+ })+ .execute();+ }+ }}- }++ // Update job operations to reset status+ if (Object.keys(jobOperationsUpdates).length > 0) {+ console.log(+ "Final job operation void updates to be applied:",+ jobOperationsUpdates+ );+ for await (const [jobOperationId, update] of Object.entries(+ jobOperationsUpdates+ )) {+ console.log(+ `Voiding job operation ${jobOperationId} with:`,+ update+ );+ await trx+ .updateTable("jobOperation")+ .set(update)+ .where("id", "=", jobOperationId)+ .execute();+ }+ }+ });+ break;}+ case "Outbound Transfer": {+ if (!shipment.data.sourceDocumentId)+ throw new Error("Shipment has no sourceDocumentId");++ const [warehouseTransfer, warehouseTransferLines] =+ await Promise.all([+ client+ .from("warehouseTransfer")+ .select("*")+ .eq("id", shipment.data.sourceDocumentId)+ .single(),+ client+ .from("warehouseTransferLine")+ .select("*")+ .eq("transferId", shipment.data.sourceDocumentId),+ ]);++ if (warehouseTransfer.error)+ throw new Error("Failed to fetch warehouse transfer");+ if (warehouseTransferLines.error)+ throw new Error("Failed to fetch warehouse transfer lines");++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];+ const warehouseTransferLineUpdates: Record<+ string,+ Database["public"]["Tables"]["warehouseTransferLine"]["Update"]+ > = {};- if (Object.keys(jobOperationsUpdates).length > 0) {- console.log(- "Final job updates to be applied:",- jobOperationsUpdates- );- for await (const [jobOperationId, update] of Object.entries(- jobOperationsUpdates- )) {- console.log(- `Updating job operation ${jobOperationId} with:`,- update+ // Process each shipment line+ for await (const shipmentLine of shipmentLines.data) {+ const warehouseTransferLine = warehouseTransferLines.data.find(+ (line) => line.id === shipmentLine.lineId);++ if (!warehouseTransferLine) continue;++ const shippedQuantity =+ isNaN(shipmentLine.shippedQuantity) ||+ shipmentLine.shippedQuantity == null+ ? 0+ : shipmentLine.shippedQuantity;++ // Reverse warehouse transfer line shipped quantity+ const newShippedQuantity = Math.max(+ 0,+ (warehouseTransferLine.shippedQuantity ?? 0) - shippedQuantity+ );++ warehouseTransferLineUpdates[warehouseTransferLine.id] = {+ shippedQuantity: newShippedQuantity,+ };++ // Create item ledger entry to restore inventory at source+ if (shippedQuantity !== 0) {+ itemLedgerInserts.push({+ postingDate: today,+ itemId: shipmentLine.itemId,+ quantity: shippedQuantity, // Positive to restore inventory+ locationId: shipmentLine.locationId,+ shelfId: shipmentLine.shelfId,+ entryType: "Transfer",+ documentType: "Transfer Shipment",+ documentId: warehouseTransfer.data?.transferId,+ externalDocumentId:+ shipment.data?.externalDocumentId ?? undefined,+ createdBy: userId,+ companyId,+ });+ }+ }++ // Check if all lines are fully shipped after void+ const allLinesFullyShipped = warehouseTransferLines.data.every(+ (line) => {+ const updates = warehouseTransferLineUpdates[line.id];+ const shippedQty =+ updates?.shippedQuantity ?? line.shippedQuantity ?? 0;+ return shippedQty >= (line.quantity ?? 0);+ }+ );++ // Check if all lines are fully received+ const allLinesFullyReceived = warehouseTransferLines.data.every(+ (line) => {+ const receivedQty = line.receivedQuantity ?? 0;+ return receivedQty >= (line.quantity ?? 0);+ }+ );++ // Determine new warehouse transfer status+ let newStatus: Database["public"]["Tables"]["warehouseTransfer"]["Row"]["status"] =+ warehouseTransfer.data.status;++ if (allLinesFullyShipped && allLinesFullyReceived) {+ newStatus = "Completed";+ } else if (allLinesFullyShipped && !allLinesFullyReceived) {+ newStatus = "To Receive";+ } else if (!allLinesFullyShipped && allLinesFullyReceived) {+ newStatus = "To Ship";+ } else {+ newStatus = "Draft";+ }++ await db.transaction().execute(async (trx) => {+ // Update warehouse transfer lines+ for await (const [lineId, update] of Object.entries(+ warehouseTransferLineUpdates+ )) {+ await trx+ .updateTable("warehouseTransferLine")+ .set(update)+ .where("id", "=", lineId)+ .execute();+ }++ // Update warehouse transfer statusawait trx- .updateTable("jobOperation")- .set(update)- .where("id", "=", jobOperationId)+ .updateTable("warehouseTransfer")+ .set({+ status: newStatus,+ updatedBy: userId,+ })+ .where("id", "=", warehouseTransfer.data.id).execute();- }- }- });- break;- }- case "Outbound Transfer": {- if (!shipment.data.sourceDocumentId)- throw new Error("Shipment has no sourceDocumentId");-- const [warehouseTransfer, warehouseTransferLines] = await Promise.all([- client- .from("warehouseTransfer")- .select("*")- .eq("id", shipment.data.sourceDocumentId)- .single(),- client- .from("warehouseTransferLine")- .select("*")- .eq("transferId", shipment.data.sourceDocumentId),- ]);-- if (warehouseTransfer.error)- throw new Error("Failed to fetch warehouse transfer");- if (warehouseTransferLines.error)- throw new Error("Failed to fetch warehouse transfer lines");-- const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =- [];- const warehouseTransferLineUpdates: Record<- string,- Database["public"]["Tables"]["warehouseTransferLine"]["Update"]- > = {};-- // Process each shipment line- for await (const shipmentLine of shipmentLines.data) {- const warehouseTransferLine = warehouseTransferLines.data.find(- (line) => line.id === shipmentLine.lineId- );-- if (!warehouseTransferLine) continue;-- const shippedQuantity = isNaN(shipmentLine.shippedQuantity) || shipmentLine.shippedQuantity == null ? 0 : shipmentLine.shippedQuantity;-- // Update warehouse transfer line shipped quantity- const newShippedQuantity =- (warehouseTransferLine.shippedQuantity ?? 0) + shippedQuantity;-- warehouseTransferLineUpdates[warehouseTransferLine.id] = {- shippedQuantity: newShippedQuantity,- };-- // Create item ledger entry for negative adjustment at source- if (shippedQuantity !== 0) {- itemLedgerInserts.push({- postingDate: today,- itemId: shipmentLine.itemId,- quantity: -shippedQuantity, // Negative for outbound transfer- locationId: shipmentLine.locationId,- shelfId: shipmentLine.shelfId,- entryType: "Transfer",- documentType: "Transfer Shipment",- documentId: warehouseTransfer.data?.transferId,- externalDocumentId:- shipment.data?.externalDocumentId ?? undefined,- createdBy: userId,- companyId,- });- }- }- // Check if all lines are fully shipped- const allLinesFullyShipped = warehouseTransferLines.data.every(- (line) => {- const updates = warehouseTransferLineUpdates[line.id];- const shippedQty =- updates?.shippedQuantity ?? line.shippedQuantity ?? 0;- return shippedQty >= (line.quantity ?? 0);- }- );+ // Create reversing item ledger entries+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .returning(["id"])+ .execute();+ }- // Check if all lines are fully received- const allLinesFullyReceived = warehouseTransferLines.data.every(- (line) => {- const receivedQty = line.receivedQuantity ?? 0;- return receivedQty >= (line.quantity ?? 0);- }- );-- // Determine new warehouse transfer status- let newStatus: Database["public"]["Tables"]["warehouseTransfer"]["Row"]["status"] =- warehouseTransfer.data.status;-- if (allLinesFullyShipped && allLinesFullyReceived) {- newStatus = "Completed";- } else if (allLinesFullyShipped && !allLinesFullyReceived) {- newStatus = "To Receive";- } else if (!allLinesFullyShipped && allLinesFullyReceived) {- newStatus = "To Ship";- }+ // Update shipment status to Voided+ await trx+ .updateTable("shipment")+ .set({+ status: "Voided",+ updatedAt: today,+ updatedBy: userId,+ })+ .where("id", "=", shipmentId)+ .execute();+ });- await db.transaction().execute(async (trx) => {- // Update warehouse transfer lines- for await (const [lineId, update] of Object.entries(- warehouseTransferLineUpdates- )) {- await trx- .updateTable("warehouseTransferLine")- .set(update)- .where("id", "=", lineId)- .execute();+ break;}- // Update warehouse transfer status- await trx- .updateTable("warehouseTransfer")- .set({- status: newStatus,- transferDate: today,- updatedBy: userId,- })- .where("id", "=", warehouseTransfer.data.id)- .execute();-- // Create item ledger entries- if (itemLedgerInserts.length > 0) {- await trx- .insertInto("itemLedger")- .values(itemLedgerInserts)- .returning(["id"])- .execute();+ default: {+ throw new Error(+ `Invalid source document type: ${shipment.data.sourceDocument}`+ );}-- // Update shipment status- await trx- .updateTable("shipment")- .set({- status: "Posted",- postedBy: userId,- })- .where("id", "=", shipmentId)- .execute();- });-+ }break;}-- default: {- throw new Error(- `Invalid source document type: ${shipment.data.sourceDocument}`- );- }}return new Response(diff --git a/packages/database/supabase/functions/void-shipment/index.ts b/packages/database/supabase/functions/void-shipment/index.tsdeleted file mode 100644index ab78689a04..0000000000--- a/packages/database/supabase/functions/void-shipment/index.ts+++ /dev/null@@ -1,890 +0,0 @@-import { serve } from "https://deno.land/[email protected]/http/server.ts";-import { format } from "https://deno.land/[email protected]/datetime/mod.ts";-import { z } from "https://deno.land/x/[email protected]/mod.ts";-import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";-import { corsHeaders } from "../lib/headers.ts";-import { getSupabaseServiceRole } from "../lib/supabase.ts";-import type { Database, Json } from "../lib/types.ts";-import { TrackedEntityAttributes } from "../lib/utils.ts";--const pool = getConnectionPool(1);-const db = getDatabaseClient<DB>(pool);--const payloadValidator = z.object({- shipmentId: z.string(),- userId: z.string(),- companyId: z.string(),-});--serve(async (req: Request) => {- if (req.method === "OPTIONS") {- return new Response("ok", { headers: corsHeaders });- }-- const payload = await req.json();- const today = format(new Date(), "yyyy-MM-dd");-- try {- const { shipmentId, userId, companyId } = payloadValidator.parse(payload);-- console.log({- function: "void-shipment",- shipmentId,- userId,- companyId,- });-- const client = await getSupabaseServiceRole(- req.headers.get("Authorization"),- req.headers.get("carbon-key") ?? "",- companyId- );-- const [shipment, shipmentLines, shipmentLineTracking] = await Promise.all([- client.from("shipment").select("*").eq("id", shipmentId).single(),- client- .from("shipmentLine")- .select("*, fulfillment(*)")- .eq("shipmentId", shipmentId),- client- .from("trackedEntity")- .select("*")- .eq("attributes->> Shipment", shipmentId),- ]);-- if (shipment.error) throw new Error("Failed to fetch shipment");- if (shipmentLines.error) throw new Error("Failed to fetch shipment lines");-- // Verify shipment is posted before allowing void- if (shipment.data?.status !== "Posted") {- throw new Error("Can only void posted shipments");- }-- const itemIds = shipmentLines.data.reduce<string[]>((acc, shipmentLine) => {- if (shipmentLine.itemId && !acc.includes(shipmentLine.itemId)) {- acc.push(shipmentLine.itemId);- }- return acc;- }, []);-- const jobIds = shipmentLines.data.reduce<string[]>((acc, shipmentLine) => {- if (- shipmentLine.fulfillment?.jobId &&- !acc.includes(shipmentLine.fulfillment?.jobId)- ) {- acc.push(shipmentLine.fulfillment?.jobId);- }- return acc;- }, []);-- const [items, itemCosts, jobs] = await Promise.all([- client- .from("item")- .select("id, itemTrackingType")- .in("id", itemIds)- .eq("companyId", companyId),- client- .from("itemCost")- .select("itemId, itemPostingGroupId")- .in("itemId", itemIds),- client- .from("job")- .select("id, quantity, quantityComplete, quantityShipped, status")- .in("id", jobIds),- ]);- if (items.error) {- throw new Error("Failed to fetch items");- }- if (itemCosts.error) {- throw new Error("Failed to fetch item costs");- }- if (jobs.error) {- throw new Error("Failed to fetch jobs");- }-- switch (shipment.data?.sourceDocument) {- case "Sales Order": {- if (!shipment.data.sourceDocumentId)- throw new Error("Shipment has no sourceDocumentId");-- const [salesOrder, salesOrderLines] = await Promise.all([- client- .from("salesOrder")- .select("*")- .eq("id", shipment.data.sourceDocumentId)- .single(),- client- .from("salesOrderLine")- .select("*")- .eq("salesOrderId", shipment.data.sourceDocumentId),- ]);- if (salesOrder.error) throw new Error("Failed to fetch sales order");- if (salesOrderLines.error)- throw new Error("Failed to fetch sales order lines");-- const customer = await client- .from("customer")- .select("*")- .eq("id", salesOrder.data.customerId)- .eq("companyId", companyId)- .single();- if (customer.error) throw new Error("Failed to fetch customer");-- const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =- [];-- const jobUpdates: Record<- string,- Database["public"]["Tables"]["job"]["Update"]- > = {};-- const locationId = shipment.data.locationId;- for await (const shipmentLine of shipmentLines.data) {- if (- shipmentLine.fulfillment?.type === "Job" &&- shipmentLine.fulfillment?.jobId- ) {- // Reverse job quantities for void shipment- const jobId = shipmentLine.fulfillment.jobId;- const currentJob = jobs.data.find((j) => j.id === jobId);-- console.log("Processing job void:", {- jobId,- currentJob: currentJob- ? {- id: currentJob.id,- quantity: currentJob.quantity,- quantityShipped: currentJob.quantityShipped,- quantityComplete: currentJob.quantityComplete,- status: currentJob.status,- }- : null,- shipmentLine: {- id: shipmentLine.id,- shippedQuantity: shipmentLine.shippedQuantity,- shippedQuantityType: typeof shipmentLine.shippedQuantity,- },- });-- const currentQuantityShipped = currentJob?.quantityShipped ?? 0;-- // Ensure shippedQuantity is a valid number- const shippedQuantity =- typeof shipmentLine.shippedQuantity === "number" &&- !isNaN(shipmentLine.shippedQuantity)- ? shipmentLine.shippedQuantity- : 0;-- console.log("Calculated values for void:", {- currentQuantityShipped,- shippedQuantity,- newTotal: currentQuantityShipped - shippedQuantity,- jobQuantity: currentJob?.quantity,- });-- // Reduce shipped quantity (reverse of posting)- const newQuantityShipped = Math.max(- 0,- currentQuantityShipped - shippedQuantity- );- const newQuantityComplete = Math.max(- 0,- (currentJob?.quantityComplete ?? 0) - shippedQuantity- );-- // Update status based on new quantities- let newStatus = currentJob?.status;- if (currentJob?.status === "Completed" && newQuantityShipped < (currentJob?.quantity ?? 0)) {- newStatus = "In Progress";- }-- jobUpdates[jobId] = {- status: newStatus,- quantityComplete: newQuantityComplete,- quantityShipped: newQuantityShipped,- };-- continue;- }-- const itemTrackingType =- items.data.find((item) => item.id === shipmentLine.itemId)- ?.itemTrackingType ?? "Inventory";-- // Default shippedQuantity to 0 if not defined or NaN- const shippedQuantity = isNaN(shipmentLine.shippedQuantity) || shipmentLine.shippedQuantity == null ? 0 : shipmentLine.shippedQuantity;-- if (itemTrackingType === "Inventory") {- // Create positive adjustment to restore inventory- itemLedgerInserts.push({- postingDate: today,- itemId: shipmentLine.itemId,- quantity: shippedQuantity, // Positive to restore inventory- locationId: shipmentLine.locationId ?? locationId,- shelfId: shipmentLine.shelfId,- entryType: "Positive Adjmt.",- documentType: "Sales Shipment Void",- documentId: shipment.data?.id ?? undefined,- externalDocumentId: undefined,- createdBy: userId,- companyId,- });- }-- if (shipmentLine.requiresBatchTracking) {- itemLedgerInserts.push({- postingDate: today,- itemId: shipmentLine.itemId,- quantity: shippedQuantity, // Positive to restore inventory- locationId: shipmentLine.locationId ?? locationId,- shelfId: shipmentLine.shelfId,- entryType: "Positive Adjmt.",- documentType: "Sales Shipment Void",- documentId: shipment.data?.id ?? undefined,- trackedEntityId: shipmentLineTracking.data?.find(- (tracking) =>- (- tracking.attributes as TrackedEntityAttributes | undefined- )?.["Shipment Line"] === shipmentLine.id- )?.id,- externalDocumentId: undefined,- createdBy: userId,- companyId,- });- }-- if (shipmentLine.requiresSerialTracking) {- const lineTracking = shipmentLineTracking.data?.filter(- (tracking) =>- (tracking.attributes as TrackedEntityAttributes | undefined)?.[- "Shipment Line"- ] === shipmentLine.id- );-- lineTracking?.forEach((tracking) => {- itemLedgerInserts.push({- postingDate: today,- itemId: shipmentLine.itemId,- quantity: 1, // Positive to restore inventory- locationId: shipmentLine.locationId ?? locationId,- shelfId: shipmentLine.shelfId,- entryType: "Positive Adjmt.",- documentType: "Sales Shipment Void",- documentId: shipment.data?.id ?? undefined,- trackedEntityId: tracking.id,- externalDocumentId: undefined,- createdBy: userId,- companyId,- });- });- }- }-- const shipmentLinesBySalesOrderLineId = shipmentLines.data.reduce<- Record<string, Database["public"]["Tables"]["shipmentLine"]["Row"][]>- >((acc, shipmentLine) => {- if (shipmentLine.lineId) {- acc[shipmentLine.lineId] = [- ...(acc[shipmentLine.lineId] ?? []),- shipmentLine,- ];- }- return acc;- }, {});-- // Reverse sales order line updates- const salesOrderLineUpdates = salesOrderLines.data.reduce<- Record<- string,- Database["public"]["Tables"]["salesOrderLine"]["Update"]- >- >((acc, salesOrderLine) => {- const shipmentLines =- shipmentLinesBySalesOrderLineId[salesOrderLine.id];- if (- shipmentLines &&- shipmentLines.length > 0 &&- salesOrderLine.saleQuantity &&- salesOrderLine.saleQuantity > 0- ) {- const shippedQuantity = shipmentLines.reduce(- (acc, shipmentLine) => {- const safeShippedQuantity = isNaN(shipmentLine.shippedQuantity) || shipmentLine.shippedQuantity == null ? 0 : shipmentLine.shippedQuantity;- return acc + safeShippedQuantity;- },- 0- );-- // Reduce shipped quantity (reverse of posting)- const newQuantitySent = Math.max(- 0,- (salesOrderLine.quantitySent ?? 0) - shippedQuantity- );-- const sentComplete = newQuantitySent >= salesOrderLine.saleQuantity;-- const updates: Record<- string,- Database["public"]["Tables"]["salesOrderLine"]["Update"]- > = {- ...acc,- [salesOrderLine.id]: {- quantitySent: newQuantitySent,- sentComplete,- },- };-- // Clear sent date if no longer complete- if (!sentComplete && salesOrderLine.sentDate) {- updates[salesOrderLine.id].sentDate = null;- }-- return updates;- }-- return acc;- }, {});-- // Restore tracked entities to available status- const trackedEntityUpdates =- shipmentLineTracking.data?.reduce<- Record<- string,- Database["public"]["Tables"]["trackedEntity"]["Update"]- >- >((acc, trackedEntity) => {- const shipmentLine = shipmentLines.data?.find(- (shipmentLine) =>- shipmentLine.id ===- (trackedEntity.attributes as TrackedEntityAttributes)?.[- "Shipment Line"- ]- );-- // Restore original quantity and set to available- acc[trackedEntity.id] = {- status: "Available",- quantity: trackedEntity.quantity, // Restore original quantity- };-- return acc;- }, {}) ?? {};-- await db.transaction().execute(async (trx) => {- // Update sales order lines to reverse shipped quantities- for await (const [salesOrderLineId, update] of Object.entries(- salesOrderLineUpdates- )) {- await trx- .updateTable("salesOrderLine")- .set(update)- .where("id", "=", salesOrderLineId)- .execute();- }-- const salesOrderLines = await trx- .selectFrom("salesOrderLine")- .select([- "id",- "salesOrderLineType",- "invoicedComplete",- "sentComplete",- ])- .where("salesOrderId", "=", salesOrder.data.id)- .execute();-- const areAllLinesInvoiced = salesOrderLines.every(- (line) =>- line.salesOrderLineType === "Comment" || line.invoicedComplete- );-- const areAllLinesShipped = salesOrderLines.every(- (line) => line.salesOrderLineType === "Comment" || line.sentComplete- );-- let status: Database["public"]["Tables"]["salesOrder"]["Row"]["status"] =- "To Ship and Invoice";- if (areAllLinesInvoiced && areAllLinesShipped) {- status = "Completed";- } else if (areAllLinesShipped) {- status = "To Invoice";- } else if (areAllLinesInvoiced) {- status = "To Ship";- }-- await trx- .updateTable("salesOrder")- .set({- status,- })- .where("id", "=", salesOrder.data.id)- .execute();-- // Update shipment status to Voided- await trx- .updateTable("shipment")- .set({- status: "Voided",- voidedDate: today,- voidedBy: userId,- })- .where("id", "=", shipmentId)- .execute();-- // Restore tracked entities to available status- if (Object.keys(trackedEntityUpdates).length > 0) {- const voidActivity = await trx- .insertInto("trackedActivity")- .values({- type: "Void Shipment",- sourceDocument: "Shipment",- sourceDocumentId: shipmentId,- sourceDocumentReadableId: shipment.data.shipmentId,- attributes: {- Shipment: shipmentId,- "Sales Order": salesOrder.data.id,- },- companyId,- createdBy: userId,- createdAt: today,- })- .returning(["id"])- .execute();-- const voidActivityId = voidActivity[0].id;-- // Restore tracked entities- for await (const [id, update] of Object.entries(- trackedEntityUpdates- )) {- await trx- .updateTable("trackedEntity")- .set(update)- .where("id", "=", id)- .execute();-- if (voidActivityId) {- await trx- .insertInto("trackedActivityInput")- .values({- trackedActivityId: voidActivityId,- trackedEntityId: id,- quantity: update.quantity ?? 0,- companyId,- createdBy: userId,- createdAt: today,- })- .execute();- }- }- }-- // Create reversing item ledger entries- if (itemLedgerInserts.length > 0) {- await trx- .insertInto("itemLedger")- .values(itemLedgerInserts)- .returning(["id"])- .execute();- }-- // Update jobs to reverse shipped quantities- if (Object.keys(jobUpdates).length > 0) {- console.log("Final job void updates to be applied:", jobUpdates);- for await (const [jobId, update] of Object.entries(jobUpdates)) {- console.log(`Voiding job ${jobId} with:`, update);- await trx- .updateTable("job")- .set(update)- .where("id", "=", jobId)- .execute();- }- }- });- break;- }- case "Purchase Order": {- if (!shipment.data.sourceDocumentId)- throw new Error("Shipment has no sourceDocumentId");-- const [purchaseOrder, purchaseOrderLines] = await Promise.all([- client- .from("purchaseOrder")- .select("*")- .eq("id", shipment.data.sourceDocumentId)- .single(),- client- .from("purchaseOrderLine")- .select("*")- .eq("purchaseOrderId", shipment.data.sourceDocumentId),- ]);- if (purchaseOrder.error)- throw new Error("Failed to fetch purchase order");- if (purchaseOrderLines.error)- throw new Error("Failed to fetch purchase order lines");-- const supplier = await client- .from("supplier")- .select("*")- .eq("id", purchaseOrder.data.supplierId)- .eq("companyId", companyId)- .single();- if (supplier.error) throw new Error("Failed to fetch supplier");-- const jobOperationsUpdates: Record<- string,- Database["public"]["Tables"]["jobOperation"]["Update"]- > = {};-- for await (const shipmentLine of shipmentLines.data) {- const purchaseOrderLine = purchaseOrderLines.data.find(- (pol) => pol.id === shipmentLine.lineId- );-- if (purchaseOrderLine?.jobId && purchaseOrderLine.jobOperationId) {- // Reset job operation status when voiding- const jobOperationId = purchaseOrderLine.jobOperationId;-- jobOperationsUpdates[jobOperationId] = {- status: "Planned",- };- continue;- }- }-- const shipmentLinesByPurchaseOrderLineId = shipmentLines.data.reduce<- Record<string, Database["public"]["Tables"]["shipmentLine"]["Row"][]>- >((acc, shipmentLine) => {- if (shipmentLine.lineId) {- acc[shipmentLine.lineId] = [- ...(acc[shipmentLine.lineId] ?? []),- shipmentLine,- ];- }- return acc;- }, {});-- // Reverse purchase order line updates- const purchaseOrderLineUpdates = purchaseOrderLines.data.reduce<- Record<- string,- Database["public"]["Tables"]["purchaseOrderLine"]["Update"]- >- >((acc, purchaseOrderLine) => {- const shipmentLines =- shipmentLinesByPurchaseOrderLineId[purchaseOrderLine.id];- if (- shipmentLines &&- shipmentLines.length > 0 &&- purchaseOrderLine.purchaseQuantity &&- purchaseOrderLine.purchaseQuantity > 0- ) {- const shippedQuantity = shipmentLines.reduce(- (acc, shipmentLine) => {- const safeShippedQuantity = isNaN(shipmentLine.shippedQuantity) || shipmentLine.shippedQuantity == null ? 0 : shipmentLine.shippedQuantity;- return acc + safeShippedQuantity;- },- 0- );-- // Reduce shipped quantity (reverse of posting)- const newQuantityShipped = Math.max(- 0,- (purchaseOrderLine.quantityShipped ?? 0) - shippedQuantity- );-- const updates: Record<- string,- Database["public"]["Tables"]["purchaseOrderLine"]["Update"]- > = {- ...acc,- [purchaseOrderLine.id]: {- quantityShipped: newQuantityShipped,- },- };-- return updates;- }-- return acc;- }, {});-- // Restore tracked entities to available status- const trackedEntityUpdates =- shipmentLineTracking.data?.reduce<- Record<- string,- Database["public"]["Tables"]["trackedEntity"]["Update"]- >- >((acc, trackedEntity) => {- // Restore original quantity and set to available- acc[trackedEntity.id] = {- status: "Available",- quantity: trackedEntity.quantity,- };-- return acc;- }, {}) ?? {};-- await db.transaction().execute(async (trx) => {- // Update purchase order lines to reverse shipped quantities- for await (const [purchaseOrderLineId, update] of Object.entries(- purchaseOrderLineUpdates- )) {- await trx- .updateTable("purchaseOrderLine")- .set(update)- .where("id", "=", purchaseOrderLineId)- .execute();- }-- // Update shipment status to Voided- await trx- .updateTable("shipment")- .set({- status: "Voided",- voidedDate: today,- voidedBy: userId,- })- .where("id", "=", shipmentId)- .execute();-- // Restore tracked entities- if (Object.keys(trackedEntityUpdates).length > 0) {- const voidActivity = await trx- .insertInto("trackedActivity")- .values({- type: "Void Shipment",- sourceDocument: "Shipment",- sourceDocumentId: shipmentId,- sourceDocumentReadableId: shipment.data.shipmentId,- attributes: {- Shipment: shipmentId,- "Purchase Order": purchaseOrder.data.id,- },- companyId,- createdBy: userId,- createdAt: today,- })- .returning(["id"])- .execute();-- const voidActivityId = voidActivity[0].id;-- // Restore tracked entities- for await (const [id, update] of Object.entries(- trackedEntityUpdates- )) {- await trx- .updateTable("trackedEntity")- .set(update)- .where("id", "=", id)- .execute();-- if (voidActivityId) {- await trx- .insertInto("trackedActivityInput")- .values({- trackedActivityId: voidActivityId,- trackedEntityId: id,- quantity: update.quantity ?? 0,- companyId,- createdBy: userId,- createdAt: today,- })- .execute();- }- }- }-- // Update job operations to reset status- if (Object.keys(jobOperationsUpdates).length > 0) {- console.log(- "Final job operation void updates to be applied:",- jobOperationsUpdates- );- for await (const [jobOperationId, update] of Object.entries(- jobOperationsUpdates- )) {- console.log(- `Voiding job operation ${jobOperationId} with:`,- update- );- await trx- .updateTable("jobOperation")- .set(update)- .where("id", "=", jobOperationId)- .execute();- }- }- });- break;- }- case "Outbound Transfer": {- if (!shipment.data.sourceDocumentId)- throw new Error("Shipment has no sourceDocumentId");-- const [warehouseTransfer, warehouseTransferLines] = await Promise.all([- client- .from("warehouseTransfer")- .select("*")- .eq("id", shipment.data.sourceDocumentId)- .single(),- client- .from("warehouseTransferLine")- .select("*")- .eq("transferId", shipment.data.sourceDocumentId),- ]);-- if (warehouseTransfer.error)- throw new Error("Failed to fetch warehouse transfer");- if (warehouseTransferLines.error)- throw new Error("Failed to fetch warehouse transfer lines");-- const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =- [];- const warehouseTransferLineUpdates: Record<- string,- Database["public"]["Tables"]["warehouseTransferLine"]["Update"]- > = {};-- // Process each shipment line- for await (const shipmentLine of shipmentLines.data) {- const warehouseTransferLine = warehouseTransferLines.data.find(- (line) => line.id === shipmentLine.lineId- );-- if (!warehouseTransferLine) continue;-- const shippedQuantity = isNaN(shipmentLine.shippedQuantity) || shipmentLine.shippedQuantity == null ? 0 : shipmentLine.shippedQuantity;-- // Reverse warehouse transfer line shipped quantity- const newShippedQuantity = Math.max(- 0,- (warehouseTransferLine.shippedQuantity ?? 0) - shippedQuantity- );-- warehouseTransferLineUpdates[warehouseTransferLine.id] = {- shippedQuantity: newShippedQuantity,- };-- // Create item ledger entry to restore inventory at source- if (shippedQuantity !== 0) {- itemLedgerInserts.push({- postingDate: today,- itemId: shipmentLine.itemId,- quantity: shippedQuantity, // Positive to restore inventory- locationId: shipmentLine.locationId,- shelfId: shipmentLine.shelfId,- entryType: "Transfer",- documentType: "Transfer Shipment Void",- documentId: warehouseTransfer.data?.transferId,- externalDocumentId:- shipment.data?.externalDocumentId ?? undefined,- createdBy: userId,- companyId,- });- }- }-- // Check if all lines are fully shipped after void- const allLinesFullyShipped = warehouseTransferLines.data.every(- (line) => {- const updates = warehouseTransferLineUpdates[line.id];- const shippedQty =- updates?.shippedQuantity ?? line.shippedQuantity ?? 0;- return shippedQty >= (line.quantity ?? 0);- }- );-- // Check if all lines are fully received- const allLinesFullyReceived = warehouseTransferLines.data.every(- (line) => {- const receivedQty = line.receivedQuantity ?? 0;- return receivedQty >= (line.quantity ?? 0);- }- );-- // Determine new warehouse transfer status- let newStatus: Database["public"]["Tables"]["warehouseTransfer"]["Row"]["status"] =- warehouseTransfer.data.status;-- if (allLinesFullyShipped && allLinesFullyReceived) {- newStatus = "Completed";- } else if (allLinesFullyShipped && !allLinesFullyReceived) {- newStatus = "To Receive";- } else if (!allLinesFullyShipped && allLinesFullyReceived) {- newStatus = "To Ship";- } else {- newStatus = "Draft";- }-- await db.transaction().execute(async (trx) => {- // Update warehouse transfer lines- for await (const [lineId, update] of Object.entries(- warehouseTransferLineUpdates- )) {- await trx- .updateTable("warehouseTransferLine")- .set(update)- .where("id", "=", lineId)- .execute();- }-- // Update warehouse transfer status- await trx- .updateTable("warehouseTransfer")- .set({- status: newStatus,- updatedBy: userId,- })- .where("id", "=", warehouseTransfer.data.id)- .execute();-- // Create reversing item ledger entries- if (itemLedgerInserts.length > 0) {- await trx- .insertInto("itemLedger")- .values(itemLedgerInserts)- .returning(["id"])- .execute();- }-- // Update shipment status to Voided- await trx- .updateTable("shipment")- .set({- status: "Voided",- voidedDate: today,- voidedBy: userId,- })- .where("id", "=", shipmentId)- .execute();- });-- break;- }-- default: {- throw new Error(- `Invalid source document type: ${shipment.data.sourceDocument}`- );- }- }-- return new Response(- JSON.stringify({- success: true,- }),- {- headers: { ...corsHeaders, "Content-Type": "application/json" },- }- );- } catch (err) {- console.error(err);- return new Response(JSON.stringify(err), {- headers: { ...corsHeaders, "Content-Type": "application/json" },- status: 500,- });- }-});\ No newline at end of filediff --git a/packages/ee/src/paperless-parts/lib/utils.ts b/packages/ee/src/paperless-parts/lib/utils.tsindex 935f8dca84..16da97276d 100644--- a/packages/ee/src/paperless-parts/lib/utils.ts+++ b/packages/ee/src/paperless-parts/lib/utils.ts@@ -1,4 +1,3 @@-import { generateObject } from "@ai-sdk/core";import { openai } from "@ai-sdk/openai";import type { Database } from "@carbon/database";import {@@ -9,6 +8,7 @@ import {textToTiptap,} from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";+import { generateObject } from "ai";import { nanoid } from "nanoid";import { z } from "zod";import type { PaperlessPartsClient, QuoteCostingVariable } from "./client";