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 sales invoices
Brad Barbinbb3c04078eac
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsxindex 9a758cd494..27691a4273 100644--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx@@ -20,8 +20,8 @@ import {LuCreditCard,LuQrCode,LuShoppingCart,+ LuTicketX,LuTruck,- LuX,} from "react-icons/lu";import { usePermissions, useRouteData } from "~/hooks";import type { ItemTracking, Shipment, ShipmentLine } from "~/modules/inventory";@@ -335,7 +335,7 @@ const ShipmentHeader = () => {variant="destructive"onClick={voidModal.onOpen}isDisabled={isVoided || !permissions.is("employee")}- leftIcon={<LuX />}+ leftIcon={<LuTicketX />}>Void</Button>diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsxindex b3257c1058..34ac4cec65 100644--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx@@ -23,6 +23,7 @@ import {LuDollarSign,LuPanelLeft,LuPanelRight,+ LuTicketX,LuTruck,} from "react-icons/lu";import { RiProgress8Line } from "react-icons/ri";@@ -37,11 +38,13 @@ import { useItems } from "~/stores";import { path } from "~/utils/path";import SalesInvoicePostModal from "./SalesInvoicePostModal";import SalesInvoiceStatus from "./SalesInvoiceStatus";+import SalesInvoiceVoidModal from "./SalesInvoiceVoidModal";const SalesInvoiceHeader = () => {const permissions = usePermissions();const { invoiceId } = useParams();const postingModal = useDisclosure();+ const voidModal = useDisclosure();const postFetcher = useFetcher<typeof action>();const statusFetcher = useFetcher<typeof statusAction>();@@ -67,6 +70,7 @@ const SalesInvoiceHeader = () => {const { salesInvoice } = routeData;const { toggleExplorer, toggleProperties } = usePanels();const isPosted = salesInvoice.postingDate !== null;+ const isVoided = salesInvoice.status === "Voided";const [relatedDocs, setRelatedDocs] = useState<{salesOrders: { id: string; readableId: string }[];@@ -249,14 +253,24 @@ const SalesInvoiceHeader = () => {>Post</Button>+ {isPosted && (+ <Button+ leftIcon={<LuTicketX />}+ variant="destructive"+ onClick={voidModal.onOpen}+ isDisabled={isVoided || !permissions.can("update", "invoicing")}+ >+ Void+ </Button>+ )}<DropdownMenu><DropdownMenuTrigger asChild><Buttonvariant="secondary"isDisabled={- salesInvoice.status === "Draft" ||- salesInvoice.status === "Pending" ||- !permissions.can("update", "invoicing")+ ["Voided", "Draft", "Pending"].includes(+ salesInvoice.status ?? ""+ ) || !permissions.can("update", "invoicing")}leftIcon={<LuDollarSign />}rightIcon={<LuChevronDown />}@@ -270,7 +284,10 @@ const SalesInvoiceHeader = () => {onValueChange={handleStatusChange}>{salesInvoiceStatusType- .filter((status) => !["Draft", "Pending"].includes(status))+ .filter(+ (status) =>+ !["Draft", "Pending", "Voided"].includes(status)+ ).map((status) => (<DropdownMenuRadioItem key={status} value={status}><SalesInvoiceStatus status={status} />@@ -300,6 +317,9 @@ const SalesInvoiceHeader = () => {fetcher={postFetcher}/>)}+ {voidModal.isOpen && (+ <SalesInvoiceVoidModal onClose={voidModal.onClose} />+ )}</>);};diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsxindex ac403bd503..3ade2c603d 100644--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsx+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsx@@ -1,4 +1,6 @@import {+ Alert,+ AlertTitle,cn,FormControl,FormLabel,@@ -20,6 +22,7 @@ import { ValidatedForm } from "@carbon/form";import { getItemReadableId } from "@carbon/utils";import { useParams } from "@remix-run/react";import { useEffect, useState } from "react";+import { LuCircleAlert } from "react-icons/lu";import type { z } from "zod";import { MethodIcon } from "~/components";import {@@ -118,7 +121,10 @@ const SalesInvoiceLineForm = ({]);const isEditing = initialValues.id !== undefined;+ const hasInvalidMethodType = itemData.methodType === "Make";const isDisabled = !isEditable+ ? true+ : hasInvalidMethodType? true: isEditing? !permissions.can("update", "purchasing")@@ -170,20 +176,13 @@ const SalesInvoiceLineForm = ({const itemCost = item?.data?.itemCost?.[0];const trackingType = item?.data?.itemTrackingType;- const methodType = item?.data?.defaultMethodType;- // Check if item requires a sales order- if (- trackingType === "Batch" ||- trackingType === "Serial" ||- methodType === "Make"- ) {+ // Check if item requires a sales order (excluding Make items which can be changed to Pick)+ if (trackingType === "Batch" || trackingType === "Serial") {const errorMessage =trackingType === "Batch"? "Batch items require a sales order"- : trackingType === "Serial"- ? "Serial items require a sales order"- : "Make items require a sales order";+ : "Serial items require a sales order";toast.error(errorMessage);setItemData({itemId: "",@@ -297,6 +296,15 @@ const SalesInvoiceLineForm = ({/><VStack>+ {itemData.methodType === "Make" && (+ <Alert variant="destructive" className="mb-4">+ <LuCircleAlert className="w-4 h-4" />+ <AlertTitle>+ Make items cannot be invoiced directly. Change method to+ Pick to continue.+ </AlertTitle>+ </Alert>+ )}<div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3"><Itemname="itemId"@@ -326,29 +334,31 @@ const SalesInvoiceLineForm = ({itemType) && (<>- <SelectControlled- name="methodType"- label="Method"- options={- methodType.map((m) => ({- label: (- <span className="flex items-center gap-2">- <MethodIcon type={m} />- {m}- </span>- ),- value: m,- })) ?? []- }- value={itemData.methodType}- onChange={(newValue) => {- if (newValue)- setItemData((d) => ({- ...d,- methodType: newValue?.value,- }));- }}- />+ <div className="space-y-2">+ <SelectControlled+ name="methodType"+ label="Method"+ options={+ methodType.map((m) => ({+ label: (+ <span className="flex items-center gap-2">+ <MethodIcon type={m} />+ {m}+ </span>+ ),+ value: m,+ })) ?? []+ }+ value={itemData.methodType}+ onChange={(newValue) => {+ if (newValue)+ setItemData((d) => ({+ ...d,+ methodType: newValue?.value,+ }));+ }}+ />+ </div><NumberControlledname="quantity"diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceStatus.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceStatus.tsxindex c8d21b6f62..ab76ef00ef 100644--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceStatus.tsx+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceStatus.tsx@@ -15,10 +15,10 @@ const SalesInvoicingStatus = ({ status }: SalesInvoicingStatusProps) => {case "Pending":case "Partially Paid":return <Status color="orange">{status}</Status>;+ case "Voided":case "Overdue":return <Status color="red">{status}</Status>;case "Credit Note Issued":- case "Voided":case "Paid":return <Status color="blue">{status}</Status>;default:diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceVoidModal.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceVoidModal.tsxnew file mode 100644index 0000000000..eedde14a8f--- /dev/null+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceVoidModal.tsx@@ -0,0 +1,97 @@+import {+ Alert,+ AlertDescription,+ AlertTitle,+ Button,+ HStack,+ Modal,+ ModalBody,+ ModalContent,+ ModalDescription,+ ModalFooter,+ ModalHeader,+ ModalOverlay,+ ModalTitle,+} from "@carbon/react";+import { useFetcher, useNavigation, useParams } from "@remix-run/react";+import { useEffect, useRef } from "react";+import { LuTriangleAlert } from "react-icons/lu";+import { path } from "~/utils/path";++const SalesInvoiceVoidModal = ({ onClose }: { onClose: () => void }) => {+ const { invoiceId } = useParams();+ if (!invoiceId) throw new Error("invoiceId not found");++ const navigation = useNavigation();+ const fetcher = useFetcher<{}>();+ const submitted = useRef(false);++ useEffect(() => {+ if (fetcher.state === "idle" && submitted.current) {+ onClose();+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [fetcher.state]);++ return (+ <Modal+ open={true}+ onOpenChange={(open) => {+ if (!open) onClose();+ }}+ >+ <ModalOverlay />+ <ModalContent>+ <ModalHeader>+ <ModalTitle>Void Sales Invoice</ModalTitle>+ <ModalDescription>+ Are you sure you want to void this sales invoice? This action will+ reverse all financial transactions and cannot be undone.+ </ModalDescription>+ </ModalHeader>+ <ModalBody>+ <Alert variant="destructive">+ <LuTriangleAlert className="h-4 w-4" />+ <AlertTitle>Warning</AlertTitle>+ <AlertDescription>+ Voiding this sales invoice will:+ <ul className="list-disc pl-4 mt-2 space-y-1">+ <li>Reverse all journal entries and financial transactions</li>+ <li>Restore inventory quantities if items were shipped</li>+ <li>Update related sales orders and shipments</li>+ <li>Create audit trail entries</li>+ </ul>+ </AlertDescription>+ </Alert>+ </ModalBody>+ <ModalFooter>+ <HStack>+ <Button variant="solid" onClick={onClose}>+ Cancel+ </Button>+ <fetcher.Form+ action={path.to.salesInvoiceVoid(invoiceId)}+ method="post"+ onSubmit={() => {+ submitted.current = true;+ }}+ >+ <Button+ variant="destructive"+ isLoading={fetcher.state !== "idle"}+ isDisabled={+ fetcher.state !== "idle" || navigation.state !== "idle"+ }+ type="submit"+ >+ Void Invoice+ </Button>+ </fetcher.Form>+ </HStack>+ </ModalFooter>+ </ModalContent>+ </Modal>+ );+};++export default SalesInvoiceVoidModal;diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.void.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.void.tsxnew file mode 100644index 0000000000..dbda02527d--- /dev/null+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.void.tsx@@ -0,0 +1,70 @@+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";+import type { ActionFunctionArgs } from "@vercel/remix";+import { redirect } from "@vercel/remix";+import { path } from "~/utils/path";++export async function action({ request, params }: ActionFunctionArgs) {+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "invoicing",+ });++ const { invoiceId } = params;+ if (!invoiceId) throw new Error("invoiceId not found");++ try {+ const serviceRole = getCarbonServiceRole();++ // Verify invoice is posted before allowing void+ const { data: salesInvoice } = await client+ .from("salesInvoice")+ .select("status, postingDate")+ .eq("id", invoiceId)+ .single();++ if (!salesInvoice?.postingDate) {+ throw redirect(+ path.to.salesInvoiceDetails(invoiceId),+ await flash(+ request,+ error(+ new Error("Can only void posted invoices"),+ "Invalid operation"+ )+ )+ );+ }++ const voidInvoice = await serviceRole.functions.invoke("post-sales-invoice", {+ body: {+ type: "void",+ invoiceId: invoiceId,+ userId: userId,+ companyId: companyId,+ },+ region: FunctionRegion.UsEast1,+ });++ if (voidInvoice.error) {+ throw redirect(+ path.to.salesInvoiceDetails(invoiceId),+ await flash(+ request,+ error(voidInvoice.error, "Failed to void sales invoice")+ )+ );+ }++ return redirect(+ path.to.salesInvoiceDetails(invoiceId),+ await flash(request, success("Sales invoice voided"))+ );+ } catch (err) {+ throw redirect(+ path.to.salesInvoiceDetails(invoiceId),+ await flash(request, error(err, "Failed to void sales invoice"))+ );+ }+}\ No newline at end of filediff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 3434825dab..fe2b3758e6 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -1155,6 +1155,8 @@ export const path = {generatePath(`${x}/sales-invoice/${id}/shipment`),salesInvoiceStatus: (id: string) =>generatePath(`${x}/sales-invoice/${id}/status`),+ salesInvoiceVoid: (id: string) =>+ generatePath(`${x}/sales-invoice/${id}/void`),salesInvoices: `${x}/sales/invoices`,salesOrder: (id: string) => generatePath(`${x}/sales-order/${id}`),salesOrderConfirm: (id: string) =>diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex d5975c8eb4..939d515d7f 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -43526,14 +43526,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex d5975c8eb4..939d515d7f 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -43526,14 +43526,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/functions/post-sales-invoice/index.ts b/packages/database/supabase/functions/post-sales-invoice/index.tsindex 4aad930891..6c38a8e2da 100644--- a/packages/database/supabase/functions/post-sales-invoice/index.ts+++ b/packages/database/supabase/functions/post-sales-invoice/index.ts@@ -18,6 +18,7 @@ const pool = getConnectionPool(1);const db = getDatabaseClient<DB>(pool);const payloadValidator = z.object({+ type: z.enum(["post", "void"]).default("post"),invoiceId: z.string(),userId: z.string(),companyId: z.string(),@@ -32,12 +33,15 @@ serve(async (req: Request) => {const today = format(new Date(), "yyyy-MM-dd");try {- const { invoiceId, userId, companyId } = payloadValidator.parse(payload);+ const { type, invoiceId, userId, companyId } =+ payloadValidator.parse(payload);console.log({function: "post-sales-invoice",+ type,invoiceId,userId,+ companyId,});const client = await getSupabaseServiceRole(@@ -65,649 +69,963 @@ serve(async (req: Request) => {const shippingCost = salesInvoiceShipment.data?.shippingCost ?? 0;- const totalLinesCost = salesInvoiceLines.data.reduce((acc, invoiceLine) => {- const lineCost =- (invoiceLine.quantity ?? 0) * (invoiceLine.unitPrice ?? 0) +- (invoiceLine.shippingCost ?? 0) +- (invoiceLine.addOnCost ?? 0);- return acc + lineCost;- }, 0);-- const itemIds = salesInvoiceLines.data.reduce<string[]>(+ // Fetch sales order lines (needed by both post and void cases)+ const salesOrderLineIds = salesInvoiceLines.data.reduce<string[]>((acc, invoiceLine) => {- if (invoiceLine.itemId && !acc.includes(invoiceLine.itemId)) {- acc.push(invoiceLine.itemId);+ if (+ invoiceLine.salesOrderLineId &&+ !acc.includes(invoiceLine.salesOrderLineId)+ ) {+ acc.push(invoiceLine.salesOrderLineId);}return acc;},[]);- const [items, itemCosts, salesOrderLines, customer] = 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("salesOrderLine")- .select("*")- .in(- "id",- salesInvoiceLines.data.reduce<string[]>((acc, invoiceLine) => {- if (- invoiceLine.salesOrderLineId &&- !acc.includes(invoiceLine.salesOrderLineId)- ) {- acc.push(invoiceLine.salesOrderLineId);+ const { data: salesOrderLines } = await client+ .from("salesOrderLine")+ .select("*")+ .in("id", salesOrderLineIds);++ if (!salesOrderLines) {+ throw new Error("Failed to fetch sales order lines");+ }++ switch (type) {+ case "post": {+ const totalLinesCost = salesInvoiceLines.data.reduce(+ (acc, invoiceLine) => {+ const lineCost =+ (invoiceLine.quantity ?? 0) * (invoiceLine.unitPrice ?? 0) ++ (invoiceLine.shippingCost ?? 0) ++ (invoiceLine.addOnCost ?? 0);+ return acc + lineCost;+ },+ 0+ );++ const itemIds = salesInvoiceLines.data.reduce<string[]>(+ (acc, invoiceLine) => {+ if (invoiceLine.itemId && !acc.includes(invoiceLine.itemId)) {+ acc.push(invoiceLine.itemId);}return acc;- }, [])- ),- client- .from("customer")- .select("*")- .eq("id", salesInvoice.data.customerId ?? "")- .eq("companyId", companyId)- .single(),- ]);- if (items.error) throw new Error("Failed to fetch items");- if (itemCosts.error) throw new Error("Failed to fetch item costs");- if (salesOrderLines.error)- throw new Error("Failed to fetch sales order lines");- if (customer.error) throw new Error("Failed to fetch customer");+ },+ []+ );- const salesOrders = await client- .from("salesOrder")- .select("*")- .in(- "salesOrderId",- salesOrderLines.data.reduce<string[]>((acc, salesOrderLine) => {+ const [items, itemCosts, customer] = 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("customer")+ .select("*")+ .eq("id", salesInvoice.data.customerId ?? "")+ .eq("companyId", companyId)+ .single(),+ ]);+ if (items.error) throw new Error("Failed to fetch items");+ if (itemCosts.error) throw new Error("Failed to fetch item costs");+ if (customer.error) throw new Error("Failed to fetch customer");++ const salesOrders = await client+ .from("salesOrder")+ .select("*")+ .in(+ "salesOrderId",+ salesOrderLines.reduce<string[]>((acc, salesOrderLine) => {+ if (+ salesOrderLine.salesOrderId &&+ !acc.includes(salesOrderLine.salesOrderId)+ ) {+ acc.push(salesOrderLine.salesOrderId);+ }+ return acc;+ }, [])+ )+ .eq("companyId", companyId);++ if (salesOrders.error) throw new Error("Failed to fetch sales orders");++ const journalLineInserts: Omit<+ Database["public"]["Tables"]["journalLine"]["Insert"],+ "journalId"+ >[] = [];++ const shipmentLineInserts: Omit<+ Database["public"]["Tables"]["shipmentLine"]["Insert"],+ "shipmentId"+ >[] = [];++ const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];++ const salesInvoiceLinesBySalesOrderLine = salesInvoiceLines.data.reduce<+ Record<+ string,+ Database["public"]["Tables"]["salesInvoiceLine"]["Row"]+ >+ >((acc, invoiceLine) => {+ if (invoiceLine.salesOrderLineId) {+ acc[invoiceLine.salesOrderLineId] = invoiceLine;+ }+ return acc;+ }, {});++ const salesOrderLineUpdates = salesOrderLines.reduce<+ Record<+ string,+ Database["public"]["Tables"]["salesOrderLine"]["Update"]+ >+ >((acc, salesOrderLine) => {+ const invoiceLine =+ salesInvoiceLinesBySalesOrderLine[salesOrderLine.id];if (- salesOrderLine.salesOrderId &&- !acc.includes(salesOrderLine.salesOrderId)+ invoiceLine &&+ invoiceLine.quantity &&+ salesOrderLine.saleQuantity &&+ salesOrderLine.saleQuantity > 0) {- acc.push(salesOrderLine.salesOrderId);+ const newQuantityInvoiced =+ (salesOrderLine.quantityInvoiced ?? 0) + invoiceLine.quantity;++ const invoicedComplete =+ newQuantityInvoiced >=+ (salesOrderLine.quantityToInvoice ?? salesOrderLine.saleQuantity);++ return {+ ...acc,+ [salesOrderLine.id]: {+ quantityInvoiced: newQuantityInvoiced,+ invoicedComplete,+ salesOrderId: salesOrderLine.salesOrderId,+ },+ };}+return acc;- }, [])- )- .eq("companyId", companyId);-- if (salesOrders.error) throw new Error("Failed to fetch sales orders");-- const journalLineInserts: Omit<- Database["public"]["Tables"]["journalLine"]["Insert"],- "journalId"- >[] = [];-- const shipmentLineInserts: Omit<- Database["public"]["Tables"]["shipmentLine"]["Insert"],- "shipmentId"- >[] = [];-- const itemLedgerInserts: Database["public"]["Tables"]["itemLedger"]["Insert"][] =- [];-- const salesInvoiceLinesBySalesOrderLine = salesInvoiceLines.data.reduce<- Record<string, Database["public"]["Tables"]["salesInvoiceLine"]["Row"]>- >((acc, invoiceLine) => {- if (invoiceLine.salesOrderLineId) {- acc[invoiceLine.salesOrderLineId] = invoiceLine;- }- return acc;- }, {});-- const salesOrderLineUpdates = salesOrderLines.data.reduce<- Record<string, Database["public"]["Tables"]["salesOrderLine"]["Update"]>- >((acc, salesOrderLine) => {- const invoiceLine = salesInvoiceLinesBySalesOrderLine[salesOrderLine.id];- if (- invoiceLine &&- invoiceLine.quantity &&- salesOrderLine.saleQuantity &&- salesOrderLine.saleQuantity > 0- ) {- const newQuantityInvoiced =- (salesOrderLine.quantityInvoiced ?? 0) + invoiceLine.quantity;-- const invoicedComplete =- salesOrderLine.invoicedComplete ||- newQuantityInvoiced >=- (salesOrderLine.quantityToInvoice ?? salesOrderLine.saleQuantity);-- return {- ...acc,- [salesOrderLine.id]: {- quantityInvoiced: newQuantityInvoiced,- invoicedComplete,- salesOrderId: salesOrderLine.salesOrderId,- },- };- }+ }, {});- return acc;- }, {});-- // save the posting groups in memory to avoid unnecessary queries- const inventoryPostingGroups: Record<- string,- Database["public"]["Tables"]["postingGroupInventory"]["Row"] | null- > = {};-- // sales posting group- const salesPostingGroups: Record<- string,- Database["public"]["Tables"]["postingGroupSales"]["Row"] | null- > = {};-- for await (const invoiceLine of salesInvoiceLines.data) {- const invoiceLineQuantityInInventoryUnit = invoiceLine.quantity;-- const totalLineCost =- (invoiceLine.quantity * (invoiceLine.unitPrice ?? 0) +- (invoiceLine.shippingCost ?? 0) +- (invoiceLine.addOnCost ?? 0)) *- (1 + (invoiceLine.taxPercent ?? 0));-- const lineCostPercentageOfTotalCost =- totalLinesCost === 0 ? 0 : totalLineCost / totalLinesCost;- const lineWeightedShippingCost =- shippingCost * lineCostPercentageOfTotalCost;- const totalLineCostWithWeightedShipping =- totalLineCost + lineWeightedShippingCost;-- const invoiceLineUnitCostInInventoryUnit =- totalLineCostWithWeightedShipping / invoiceLine.quantity;-- // declaring shared variables between part and service cases- // outside of the switch case to avoid redeclaring them- let postingGroupInventory:- | Database["public"]["Tables"]["postingGroupInventory"]["Row"]- | null = null;-- let itemPostingGroupId: string | null = null;-- let postingGroupSales:- | Database["public"]["Tables"]["postingGroupSales"]["Row"]- | null = null;-- const locationId = invoiceLine.locationId ?? null;- const customerTypeId: string | null =- customer.data.customerTypeId ?? null;-- let journalLineReference: string;-- switch (invoiceLine.invoiceLineType) {- case "Part":- case "Service":- case "Consumable":- case "Fixture":- case "Material":- case "Tool":- {- const itemTrackingType =- items.data.find((item) => item.id === invoiceLine.itemId)- ?.itemTrackingType ?? "Inventory";-- itemPostingGroupId =- itemCosts.data.find((item) => item.itemId === invoiceLine.itemId)- ?.itemPostingGroupId ?? null;-- // inventory posting group- if (- `${itemPostingGroupId}-${locationId}` in inventoryPostingGroups- ) {- postingGroupInventory =- inventoryPostingGroups[`${itemPostingGroupId}-${locationId}`];- } else {- const inventoryPostingGroup = await getInventoryPostingGroup(- client,- companyId,- {- itemPostingGroupId,- locationId,+ // save the posting groups in memory to avoid unnecessary queries+ const inventoryPostingGroups: Record<+ string,+ Database["public"]["Tables"]["postingGroupInventory"]["Row"] | null+ > = {};++ // sales posting group+ const salesPostingGroups: Record<+ string,+ Database["public"]["Tables"]["postingGroupSales"]["Row"] | null+ > = {};++ for await (const invoiceLine of salesInvoiceLines.data) {+ const invoiceLineQuantityInInventoryUnit = invoiceLine.quantity;++ const totalLineCost =+ (invoiceLine.quantity * (invoiceLine.unitPrice ?? 0) ++ (invoiceLine.shippingCost ?? 0) ++ (invoiceLine.addOnCost ?? 0)) *+ (1 + (invoiceLine.taxPercent ?? 0));++ const lineCostPercentageOfTotalCost =+ totalLinesCost === 0 ? 0 : totalLineCost / totalLinesCost;+ const lineWeightedShippingCost =+ shippingCost * lineCostPercentageOfTotalCost;+ const totalLineCostWithWeightedShipping =+ totalLineCost + lineWeightedShippingCost;++ const invoiceLineUnitCostInInventoryUnit =+ totalLineCostWithWeightedShipping / invoiceLine.quantity;++ // declaring shared variables between part and service cases+ // outside of the switch case to avoid redeclaring them+ let postingGroupInventory:+ | Database["public"]["Tables"]["postingGroupInventory"]["Row"]+ | null = null;++ let itemPostingGroupId: string | null = null;++ let postingGroupSales:+ | Database["public"]["Tables"]["postingGroupSales"]["Row"]+ | null = null;++ const locationId = invoiceLine.locationId ?? null;+ const customerTypeId: string | null =+ customer.data.customerTypeId ?? null;++ let journalLineReference: string;++ switch (invoiceLine.invoiceLineType) {+ case "Part":+ case "Service":+ case "Consumable":+ case "Fixture":+ case "Material":+ case "Tool":+ {+ const itemTrackingType =+ items.data.find((item) => item.id === invoiceLine.itemId)+ ?.itemTrackingType ?? "Inventory";++ itemPostingGroupId =+ itemCosts.data.find(+ (item) => item.itemId === invoiceLine.itemId+ )?.itemPostingGroupId ?? null;++ // inventory posting group+ if (+ `${itemPostingGroupId}-${locationId}` in+ inventoryPostingGroups+ ) {+ postingGroupInventory =+ inventoryPostingGroups[+ `${itemPostingGroupId}-${locationId}`+ ];+ } else {+ const inventoryPostingGroup = await getInventoryPostingGroup(+ client,+ companyId,+ {+ itemPostingGroupId,+ locationId,+ }+ );++ if (+ inventoryPostingGroup.error ||+ !inventoryPostingGroup.data+ ) {+ throw new Error("Error getting inventory posting group");+ }++ postingGroupInventory = inventoryPostingGroup.data ?? null;+ inventoryPostingGroups[+ `${itemPostingGroupId}-${locationId}`+ ] = postingGroupInventory;}- );- if (inventoryPostingGroup.error || !inventoryPostingGroup.data) {- throw new Error("Error getting inventory posting group");- }-- postingGroupInventory = inventoryPostingGroup.data ?? null;- inventoryPostingGroups[`${itemPostingGroupId}-${locationId}`] =- postingGroupInventory;- }+ if (!postingGroupInventory) {+ throw new Error("No inventory posting group found");+ }- if (!postingGroupInventory) {- throw new Error("No inventory posting group found");- }+ if (+ `${itemPostingGroupId}-${customerTypeId}` in+ salesPostingGroups+ ) {+ postingGroupSales =+ salesPostingGroups[+ `${itemPostingGroupId}-${customerTypeId}`+ ];+ } else {+ const salesPostingGroup = await getSalesPostingGroup(+ client,+ companyId,+ {+ itemPostingGroupId,+ customerTypeId,+ }+ );++ if (salesPostingGroup.error || !salesPostingGroup.data) {+ throw new Error("Error getting sales posting group");+ }++ postingGroupSales = salesPostingGroup.data ?? null;+ salesPostingGroups[+ `${itemPostingGroupId}-${customerTypeId}`+ ] = postingGroupSales;+ }- if (- `${itemPostingGroupId}-${customerTypeId}` in salesPostingGroups- ) {- postingGroupSales =- salesPostingGroups[`${itemPostingGroupId}-${customerTypeId}`];- } else {- const salesPostingGroup = await getSalesPostingGroup(- client,- companyId,- {- itemPostingGroupId,- customerTypeId,+ if (!postingGroupSales) {+ throw new Error("No sales posting group found");}- );- if (salesPostingGroup.error || !salesPostingGroup.data) {- throw new Error("Error getting sales posting group");+ // if the sales order line is null, we ship the part, do the normal entries and do not use accrual/reversing+ if (+ invoiceLine.salesOrderLineId === null &&+ invoiceLine.methodType !== "Make"+ ) {+ // create the shipment line+ shipmentLineInserts.push({+ itemId: invoiceLine.itemId!,+ lineId: invoiceLine.id,+ orderQuantity: invoiceLineQuantityInInventoryUnit,+ outstandingQuantity: invoiceLineQuantityInInventoryUnit,+ shippedQuantity: invoiceLineQuantityInInventoryUnit,+ locationId: invoiceLine.locationId,+ shelfId: invoiceLine.shelfId,+ unitOfMeasure: invoiceLine.unitOfMeasureCode ?? "EA",+ unitPrice: invoiceLine.unitPrice ?? 0,+ createdBy: invoiceLine.createdBy,+ companyId,+ });++ if (itemTrackingType === "Inventory") {+ // create the part ledger line+ itemLedgerInserts.push({+ postingDate: today,+ itemId: invoiceLine.itemId!,+ quantity: -invoiceLineQuantityInInventoryUnit,+ locationId: invoiceLine.locationId,+ shelfId: invoiceLine.shelfId,+ entryType: "Negative Adjmt.",+ documentType: "Sales Shipment",+ documentId: salesInvoice.data?.id ?? undefined,+ externalDocumentId:+ salesInvoice.data?.customerReference ?? undefined,+ createdBy: userId,+ companyId,+ });+ }++ // create the normal GL entries for a part++ journalLineReference = nanoid();++ if (itemTrackingType === "Inventory") {+ // debit the inventory account+ journalLineInserts.push({+ accountNumber: postingGroupInventory.inventoryAccount,+ description: "Inventory Account",+ amount: credit(+ "asset",+ totalLineCostWithWeightedShipping+ ),+ quantity: invoiceLineQuantityInInventoryUnit,+ documentType: "Invoice",+ documentId: salesInvoice.data?.id,+ externalDocumentId: salesInvoice.data?.customerReference,+ journalLineReference,+ companyId,+ });++ // creidt the cost of goods sold account+ journalLineInserts.push({+ accountNumber:+ postingGroupInventory.costOfGoodsSoldAccount,+ description: "Cost of Goods Sold",+ amount: debit(+ "expense",+ totalLineCostWithWeightedShipping+ ),+ quantity: invoiceLineQuantityInInventoryUnit,+ documentType: "Invoice",+ documentId: salesInvoice.data?.id,+ externalDocumentId: salesInvoice.data?.customerReference,+ journalLineReference,+ companyId,+ });+ }++ journalLineReference = nanoid();++ // credit the sales account+ journalLineInserts.push({+ accountNumber: postingGroupSales.salesAccount,+ description: "Sales Account",+ amount: credit(+ "revenue",+ totalLineCostWithWeightedShipping+ ),+ quantity: invoiceLineQuantityInInventoryUnit,+ documentType: "Invoice",+ documentId: salesInvoice.data?.id,+ externalDocumentId: salesInvoice.data?.customerReference,+ documentLineReference: journalReference.to.salesInvoice(+ invoiceLine.salesOrderLineId!+ ),+ journalLineReference,+ companyId,+ });++ // debit the accounts receivable account+ journalLineInserts.push({+ accountNumber: postingGroupSales.receivablesAccount,+ description: "Accounts Receivable",+ amount: debit("asset", totalLineCostWithWeightedShipping),+ quantity: invoiceLineQuantityInInventoryUnit,+ documentType: "Invoice",+ documentId: salesInvoice.data?.id,+ externalDocumentId: salesInvoice.data?.customerReference,+ documentLineReference: journalReference.to.salesInvoice(+ invoiceLine.salesOrderLineId!+ ),+ journalLineReference,+ companyId,+ });+ } // if the line is associated with a sales order line, we do accrual/reversing+ else {+ // Create the normal GL entries for the invoice+ journalLineReference = nanoid();++ // Credit the sales account+ journalLineInserts.push({+ accountNumber: postingGroupSales.salesAccount,+ description: "Sales Account",+ amount: credit(+ "revenue",+ totalLineCostWithWeightedShipping+ ),+ quantity: invoiceLineQuantityInInventoryUnit,+ documentType: "Invoice",+ documentId: salesInvoice.data?.id,+ externalDocumentId: salesInvoice.data?.customerReference,+ documentLineReference: invoiceLine.salesOrderLineId+ ? journalReference.to.salesInvoice(+ invoiceLine.salesOrderLineId+ )+ : null,+ journalLineReference,+ companyId,+ });++ // Debit the accounts receivable account+ journalLineInserts.push({+ accountNumber: postingGroupSales.receivablesAccount,+ description: "Accounts Receivable",+ amount: debit("asset", totalLineCostWithWeightedShipping),+ quantity: invoiceLineQuantityInInventoryUnit,+ documentType: "Invoice",+ documentId: salesInvoice.data?.id,+ externalDocumentId: salesInvoice.data?.customerReference,+ documentLineReference: invoiceLine.salesOrderLineId+ ? journalReference.to.salesInvoice(+ invoiceLine.salesOrderLineId+ )+ : null,+ journalLineReference,+ companyId,+ });++ // For inventory items, handle COGS and inventory+ if (itemTrackingType !== "Non-Inventory") {+ journalLineReference = nanoid();++ // Debit cost of goods sold+ journalLineInserts.push({+ accountNumber:+ postingGroupInventory.costOfGoodsSoldAccount,+ description: "Cost of Goods Sold",+ amount: debit(+ "expense",+ invoiceLineQuantityInInventoryUnit *+ invoiceLineUnitCostInInventoryUnit+ ),+ quantity: invoiceLineQuantityInInventoryUnit,+ documentType: "Invoice",+ documentId: salesInvoice.data?.id,+ externalDocumentId: salesInvoice.data?.customerReference,+ documentLineReference: invoiceLine.salesOrderLineId+ ? journalReference.to.salesInvoice(+ invoiceLine.salesOrderLineId+ )+ : null,+ journalLineReference,+ companyId,+ });++ // Credit inventory account+ journalLineInserts.push({+ accountNumber: postingGroupInventory.inventoryAccount,+ description: "Inventory Account",+ amount: credit(+ "asset",+ invoiceLineQuantityInInventoryUnit *+ invoiceLineUnitCostInInventoryUnit+ ),+ quantity: invoiceLineQuantityInInventoryUnit,+ documentType: "Invoice",+ documentId: salesInvoice.data?.id,+ externalDocumentId: salesInvoice.data?.customerReference,+ documentLineReference: invoiceLine.salesOrderLineId+ ? journalReference.to.salesInvoice(+ invoiceLine.salesOrderLineId+ )+ : null,+ journalLineReference,+ companyId,+ });+ }+ }}- postingGroupSales = salesPostingGroup.data ?? null;- salesPostingGroups[`${itemPostingGroupId}-${customerTypeId}`] =- postingGroupSales;- }+ break;+ case "Fixed Asset":+ // TODO: fixed assets+ break;+ case "Comment":+ break;- if (!postingGroupSales) {- throw new Error("No sales posting group found");- }+ default:+ throw new Error("Unsupported invoice line type");+ }+ }- // if the sales order line is null, we ship the part, do the normal entries and do not use accrual/reversing- if (- invoiceLine.salesOrderLineId === null &&- invoiceLine.methodType !== "Make"- ) {- // create the shipment line- shipmentLineInserts.push({- itemId: invoiceLine.itemId!,- lineId: invoiceLine.id,- orderQuantity: invoiceLineQuantityInInventoryUnit,- outstandingQuantity: invoiceLineQuantityInInventoryUnit,- shippedQuantity: invoiceLineQuantityInInventoryUnit,- locationId: invoiceLine.locationId,- shelfId: invoiceLine.shelfId,- unitOfMeasure: invoiceLine.unitOfMeasureCode ?? "EA",- unitPrice: invoiceLine.unitPrice ?? 0,- createdBy: invoiceLine.createdBy,- companyId,- });-- if (itemTrackingType === "Inventory") {- // create the part ledger line- itemLedgerInserts.push({- postingDate: today,- itemId: invoiceLine.itemId!,- quantity: -invoiceLineQuantityInInventoryUnit,- locationId: invoiceLine.locationId,- shelfId: invoiceLine.shelfId,- entryType: "Negative Adjmt.",- documentType: "Sales Shipment",- documentId: salesInvoice.data?.id ?? undefined,- externalDocumentId:- salesInvoice.data?.customerReference ?? undefined,- createdBy: userId,- companyId,- });- }+ const accountingPeriodId = await getCurrentAccountingPeriod(+ client,+ companyId,+ db+ );- // create the normal GL entries for a part-- journalLineReference = nanoid();-- if (itemTrackingType === "Inventory") {- // debit the inventory account- journalLineInserts.push({- accountNumber: postingGroupInventory.inventoryAccount,- description: "Inventory Account",- amount: credit("asset", totalLineCostWithWeightedShipping),- quantity: invoiceLineQuantityInInventoryUnit,- documentType: "Invoice",- documentId: salesInvoice.data?.id,- externalDocumentId: salesInvoice.data?.customerReference,- journalLineReference,- companyId,- });-- // creidt the cost of goods sold account- journalLineInserts.push({- accountNumber: postingGroupInventory.costOfGoodsSoldAccount,- description: "Cost of Goods Sold",- amount: debit("expense", totalLineCostWithWeightedShipping),- quantity: invoiceLineQuantityInInventoryUnit,- documentType: "Invoice",- documentId: salesInvoice.data?.id,- externalDocumentId: salesInvoice.data?.customerReference,- journalLineReference,- companyId,- });+ await db.transaction().execute(async (trx) => {+ if (shipmentLineInserts.length > 0) {+ const shipmentLinesGroupedByLocationId = shipmentLineInserts.reduce<+ Record<string, typeof shipmentLineInserts>+ >((acc, line) => {+ if (line.locationId) {+ if (line.locationId in acc) {+ acc[line.locationId].push(line);+ } else {+ acc[line.locationId] = [line];+ }}- journalLineReference = nanoid();-- // credit the sales account- journalLineInserts.push({- accountNumber: postingGroupSales.salesAccount,- description: "Sales Account",- amount: credit("revenue", totalLineCostWithWeightedShipping),- quantity: invoiceLineQuantityInInventoryUnit,- documentType: "Invoice",- documentId: salesInvoice.data?.id,- externalDocumentId: salesInvoice.data?.customerReference,- documentLineReference: journalReference.to.salesInvoice(- invoiceLine.salesOrderLineId!- ),- journalLineReference,- companyId,- });-- // debit the accounts receivable account- journalLineInserts.push({- accountNumber: postingGroupSales.receivablesAccount,- description: "Accounts Receivable",- amount: debit("asset", totalLineCostWithWeightedShipping),- quantity: invoiceLineQuantityInInventoryUnit,- documentType: "Invoice",- documentId: salesInvoice.data?.id,- externalDocumentId: salesInvoice.data?.customerReference,- documentLineReference: journalReference.to.salesInvoice(- invoiceLine.salesOrderLineId!- ),- journalLineReference,- companyId,- });- } // if the line is associated with a sales order line, we do accrual/reversing- else {- // Create the normal GL entries for the invoice- journalLineReference = nanoid();-- // Credit the sales account- journalLineInserts.push({- accountNumber: postingGroupSales.salesAccount,- description: "Sales Account",- amount: credit("revenue", totalLineCostWithWeightedShipping),- quantity: invoiceLineQuantityInInventoryUnit,- documentType: "Invoice",- documentId: salesInvoice.data?.id,- externalDocumentId: salesInvoice.data?.customerReference,- documentLineReference: invoiceLine.salesOrderLineId- ? journalReference.to.salesInvoice(- invoiceLine.salesOrderLineId- )- : null,- journalLineReference,- companyId,- });-- // Debit the accounts receivable account- journalLineInserts.push({- accountNumber: postingGroupSales.receivablesAccount,- description: "Accounts Receivable",- amount: debit("asset", totalLineCostWithWeightedShipping),- quantity: invoiceLineQuantityInInventoryUnit,- documentType: "Invoice",- documentId: salesInvoice.data?.id,- externalDocumentId: salesInvoice.data?.customerReference,- documentLineReference: invoiceLine.salesOrderLineId- ? journalReference.to.salesInvoice(- invoiceLine.salesOrderLineId- )- : null,- journalLineReference,- companyId,- });-- // For inventory items, handle COGS and inventory- if (itemTrackingType !== "Non-Inventory") {- journalLineReference = nanoid();-- // Debit cost of goods sold- journalLineInserts.push({- accountNumber: postingGroupInventory.costOfGoodsSoldAccount,- description: "Cost of Goods Sold",- amount: debit(- "expense",- invoiceLineQuantityInInventoryUnit *- invoiceLineUnitCostInInventoryUnit- ),- quantity: invoiceLineQuantityInInventoryUnit,- documentType: "Invoice",- documentId: salesInvoice.data?.id,- externalDocumentId: salesInvoice.data?.customerReference,- documentLineReference: invoiceLine.salesOrderLineId- ? journalReference.to.salesInvoice(- invoiceLine.salesOrderLineId- )- : null,- journalLineReference,- companyId,- });-- // Credit inventory account- journalLineInserts.push({- accountNumber: postingGroupInventory.inventoryAccount,- description: "Inventory Account",- amount: credit(- "asset",- invoiceLineQuantityInInventoryUnit *- invoiceLineUnitCostInInventoryUnit- ),- quantity: invoiceLineQuantityInInventoryUnit,- documentType: "Invoice",- documentId: salesInvoice.data?.id,- externalDocumentId: salesInvoice.data?.customerReference,- documentLineReference: invoiceLine.salesOrderLineId- ? journalReference.to.salesInvoice(- invoiceLine.salesOrderLineId- )- : null,- journalLineReference,+ return acc;+ }, {});++ for await (const [locationId, shipmentLines] of Object.entries(+ shipmentLinesGroupedByLocationId+ )) {+ const readableShipmentId = await getNextSequence(+ trx,+ "shipment",+ companyId+ );+ const shipment = await trx+ .insertInto("shipment")+ .values({+ shipmentId: readableShipmentId ?? "x",+ locationId,+ sourceDocument: "Sales Invoice",+ sourceDocumentId: salesInvoice.data.id,+ sourceDocumentReadableId: salesInvoice.data.invoiceId,+ shippingMethodId: salesInvoiceShipment.data?.shippingMethodId,+ customerId: salesInvoice.data.customerId,+ externalDocumentId: salesInvoice.data.customerReference,+ status: "Posted",+ postingDate: today,+ postedBy: userId,+ invoiced: true,+ opportunityId: salesInvoice.data.opportunityId,companyId,- });- }+ createdBy: salesInvoice.data.createdBy,+ })+ .returning(["id"])+ .execute();++ const shipmentId = shipment[0].id;+ if (!shipmentId) throw new Error("Failed to insert shipment");++ await trx+ .insertInto("shipmentLine")+ .values(+ shipmentLines.map((r) => ({+ ...r,+ shipmentId: shipmentId,+ }))+ )+ .returning(["id"])+ .execute();}}- break;- case "Fixed Asset":- // TODO: fixed assets- break;- case "Comment":- break;-- default:- throw new Error("Unsupported invoice line type");- }- }+ for await (const [salesOrderLineId, update] of Object.entries(+ salesOrderLineUpdates+ )) {+ await trx+ .updateTable("salesOrderLine")+ .set(update)+ .where("id", "=", salesOrderLineId)+ .execute();+ }- const accountingPeriodId = await getCurrentAccountingPeriod(- client,- companyId,- db- );+ const salesOrdersUpdated = Object.values(+ salesOrderLineUpdates+ ).reduce<string[]>((acc, update) => {+ if (update.salesOrderId && !acc.includes(update.salesOrderId)) {+ acc.push(update.salesOrderId);+ }+ return acc;+ }, []);++ for await (const salesOrderId of salesOrdersUpdated) {+ const salesOrderLines = await trx+ .selectFrom("salesOrderLine")+ .selectAll()+ .where("salesOrderId", "=", salesOrderId)+ .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 (areAllLinesInvoiced) {+ status = "To Ship";+ } else if (areAllLinesShipped) {+ status = "To Invoice";+ }- await db.transaction().execute(async (trx) => {- if (shipmentLineInserts.length > 0) {- const shipmentLinesGroupedByLocationId = shipmentLineInserts.reduce<- Record<string, typeof shipmentLineInserts>- >((acc, line) => {- if (line.locationId) {- if (line.locationId in acc) {- acc[line.locationId].push(line);- } else {- acc[line.locationId] = [line];+ if (areAllLinesInvoiced) {+ await trx+ .updateTable("shipment")+ .set({+ invoiced: true,+ })+ .where("sourceDocumentId", "=", salesOrderId)+ .execute();}- }- return acc;- }, {});+ await trx+ .updateTable("salesOrder")+ .set({+ status,+ })+ .where("id", "=", salesOrderId)+ .execute();+ }- for await (const [locationId, shipmentLines] of Object.entries(- shipmentLinesGroupedByLocationId- )) {- const readableShipmentId = await getNextSequence(- trx,- "shipment",- companyId- );- const shipment = await trx- .insertInto("shipment")+ const journal = await trx+ .insertInto("journal").values({- shipmentId: readableShipmentId ?? "x",- locationId,- sourceDocument: "Sales Invoice",- sourceDocumentId: salesInvoice.data.id,- sourceDocumentReadableId: salesInvoice.data.invoiceId,- shippingMethodId: salesInvoiceShipment.data?.shippingMethodId,- customerId: salesInvoice.data.customerId,- externalDocumentId: salesInvoice.data.customerReference,- status: "Posted",+ accountingPeriodId,+ description: `Sales Invoice ${salesInvoice.data?.invoiceId}`,postingDate: today,- postedBy: userId,- invoiced: true,- opportunityId: salesInvoice.data.opportunityId,companyId,- createdBy: salesInvoice.data.createdBy,}).returning(["id"]).execute();- const shipmentId = shipment[0].id;- if (!shipmentId) throw new Error("Failed to insert shipment");+ const journalId = journal[0].id;+ if (!journalId) throw new Error("Failed to insert journal");await trx- .insertInto("shipmentLine")+ .insertInto("journalLine").values(- shipmentLines.map((r) => ({- ...r,- shipmentId: shipmentId,+ journalLineInserts.map((journalLine) => ({+ ...journalLine,+ journalId,}))).returning(["id"]).execute();- }- }- for await (const [salesOrderLineId, update] of Object.entries(- salesOrderLineUpdates- )) {- await trx- .updateTable("salesOrderLine")- .set(update)- .where("id", "=", salesOrderLineId)- .execute();+ if (itemLedgerInserts.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(itemLedgerInserts)+ .returning(["id"])+ .execute();+ }++ if (salesInvoice.data.shipmentId) {+ await trx+ .updateTable("shipment")+ .set({+ invoiced: true,+ })+ .where("id", "=", salesInvoice.data.shipmentId)+ .execute();+ }++ await trx+ .updateTable("salesInvoice")+ .set({+ datePaid: today, // TODO: remove this once we have payments working+ postingDate: today,+ status: "Submitted",+ })+ .where("id", "=", invoiceId)+ .execute();+ });+ break;}- const salesOrdersUpdated = Object.values(salesOrderLineUpdates).reduce<- string[]- >((acc, update) => {- if (update.salesOrderId && !acc.includes(update.salesOrderId)) {- acc.push(update.salesOrderId);+ case "void": {+ // Get journal entries to reverse+ const { data: journalEntries } = await client+ .from("journalLine")+ .select("*")+ .eq("documentId", invoiceId)+ .eq("documentType", "Invoice");++ if (!journalEntries) {+ throw new Error("No journal entries found for invoice");}- return acc;- }, []);-- for await (const salesOrderId of salesOrdersUpdated) {- const salesOrderLines = await trx- .selectFrom("salesOrderLine")- .selectAll()- .where("salesOrderId", "=", salesOrderId)- .execute();-- const areAllLinesInvoiced = salesOrderLines.every(- (line) =>- line.salesOrderLineType === "Comment" || line.invoicedComplete- );- const areAllLinesShipped = salesOrderLines.every(- (line) => line.salesOrderLineType === "Comment" || line.sentComplete- );+ // Get shipments created from this invoice+ const { data: invoiceShipments } = await client+ .from("shipment")+ .select("id")+ .eq("sourceDocument", "Sales Invoice")+ .eq("sourceDocumentId", invoiceId);++ const salesOrderLinesBySalesOrderLineId = salesOrderLines.reduce<+ Record<string, Database["public"]["Tables"]["salesOrderLine"]["Row"]>+ >((acc, salesOrderLine) => {+ acc[salesOrderLine.id] = salesOrderLine;+ return acc;+ }, {});- let status: Database["public"]["Tables"]["salesOrder"]["Row"]["status"] =- "To Ship and Invoice";+ // Reverse sales order line updates+ const salesOrderLineUpdates = salesInvoiceLines.data.reduce<+ Record<+ string,+ Database["public"]["Tables"]["salesOrderLine"]["Update"]+ >+ >((acc, invoiceLine) => {+ const salesOrderLine =+ salesOrderLinesBySalesOrderLineId[+ invoiceLine.salesOrderLineId ?? ""+ ];+ if (+ invoiceLine.salesOrderLineId &&+ salesOrderLine &&+ invoiceLine.quantity &&+ salesOrderLine.saleQuantity &&+ salesOrderLine.saleQuantity > 0+ ) {+ const newQuantityInvoiced = Math.max(+ 0,+ (salesOrderLine.quantityInvoiced ?? 0) - invoiceLine.quantity+ );++ const invoicedComplete =+ newQuantityInvoiced >= salesOrderLine.saleQuantity;++ const updates: Database["public"]["Tables"]["salesOrderLine"]["Update"] =+ {+ quantityInvoiced: newQuantityInvoiced,+ invoicedComplete,+ salesOrderId: salesOrderLine.salesOrderId,+ };++ return {+ ...acc,+ [invoiceLine.salesOrderLineId]: updates,+ };+ }- if (areAllLinesInvoiced && areAllLinesShipped) {- status = "Completed";- } else if (areAllLinesInvoiced) {- status = "To Ship";- } else if (areAllLinesShipped) {- status = "To Invoice";+ return acc;+ }, {});++ // Create reversing journal entries+ const reversingJournalEntries = journalEntries.map((entry) => ({+ accountNumber: entry.accountNumber,+ description: `VOID: ${entry.description}`,+ amount: -entry.amount, // Reverse the amount+ quantity: -entry.quantity,+ documentType: "Invoice" as const,+ documentId: salesInvoice.data?.id,+ externalDocumentId: entry.externalDocumentId,+ documentLineReference: entry.documentLineReference,+ journalLineReference: entry.journalLineReference,+ companyId,+ }));++ // Create reversing item ledger entries+ const reversingItemLedgerEntries: Database["public"]["Tables"]["itemLedger"]["Insert"][] =+ [];++ const { data: originalItemLedgerEntries } = await client+ .from("itemLedger")+ .select("*")+ .eq("documentId", invoiceId)+ .eq("documentType", "Sales Shipment");++ if (originalItemLedgerEntries) {+ originalItemLedgerEntries.forEach((entry) => {+ reversingItemLedgerEntries.push({+ postingDate: today,+ itemId: entry.itemId,+ quantity: -entry.quantity, // Reverse the quantity+ locationId: entry.locationId,+ shelfId: entry.shelfId,+ entryType:+ entry.entryType === "Negative Adjmt."+ ? "Positive Adjmt."+ : "Negative Adjmt.",+ documentType: "Sales Shipment",+ documentId: salesInvoice.data?.id ?? undefined,+ externalDocumentId: entry.externalDocumentId,+ createdBy: userId,+ companyId,+ });+ });}- if (areAllLinesInvoiced) {- await trx- .updateTable("shipment")- .set({- invoiced: true,+ const accountingPeriodId = await getCurrentAccountingPeriod(+ client,+ companyId,+ db+ );++ await db.transaction().execute(async (trx) => {+ // Update sales order lines to reverse invoiced quantities+ for await (const [salesOrderLineId, update] of Object.entries(+ salesOrderLineUpdates+ )) {+ await trx+ .updateTable("salesOrderLine")+ .set(update)+ .where("id", "=", salesOrderLineId)+ .execute();+ }++ // Update sales orders status - fetch fresh data after updates+ const salesOrdersUpdated = Object.values(+ salesOrderLineUpdates+ ).reduce<string[]>((acc, update) => {+ if (update.salesOrderId && !acc.includes(update.salesOrderId)) {+ acc.push(update.salesOrderId);+ }+ return acc;+ }, []);++ for await (const salesOrderId of salesOrdersUpdated) {+ // Fetch fresh data after the sales order line updates+ const salesOrderLines = await trx+ .selectFrom("salesOrderLine")+ .selectAll()+ .where("salesOrderId", "=", salesOrderId)+ .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 (areAllLinesInvoiced) {+ status = "To Ship";+ } else if (areAllLinesShipped) {+ status = "To Invoice";+ }++ // If no lines are invoiced anymore, remove invoiced flag from shipments+ if (!areAllLinesInvoiced) {+ await trx+ .updateTable("shipment")+ .set({+ invoiced: false,+ })+ .where("sourceDocumentId", "=", salesOrderId)+ .execute();+ }++ await trx+ .updateTable("salesOrder")+ .set({+ status,+ })+ .where("id", "=", salesOrderId)+ .execute();+ }++ // Create reversing journal+ const journal = await trx+ .insertInto("journal")+ .values({+ accountingPeriodId,+ description: `VOID Sales Invoice ${salesInvoice.data?.invoiceId}`,+ postingDate: today,+ companyId,})- .where("sourceDocumentId", "=", salesOrderId)+ .returning(["id"]).execute();- }- await trx- .updateTable("salesOrder")- .set({- status,- })- .where("id", "=", salesOrderId)- .execute();- }+ const journalId = journal[0].id;+ if (!journalId) throw new Error("Failed to insert journal");- const journal = await trx- .insertInto("journal")- .values({- accountingPeriodId,- description: `Sales Invoice ${salesInvoice.data?.invoiceId}`,- postingDate: today,- companyId,- })- .returning(["id"])- .execute();-- const journalId = journal[0].id;- if (!journalId) throw new Error("Failed to insert journal");-- await trx- .insertInto("journalLine")- .values(- journalLineInserts.map((journalLine) => ({- ...journalLine,- journalId,- }))- )- .returning(["id"])- .execute();-- if (itemLedgerInserts.length > 0) {- await trx- .insertInto("itemLedger")- .values(itemLedgerInserts)- .returning(["id"])- .execute();- }+ // Insert reversing journal entries+ await trx+ .insertInto("journalLine")+ .values(+ reversingJournalEntries.map((journalLine) => ({+ ...journalLine,+ journalId,+ }))+ )+ .returning(["id"])+ .execute();- if (salesInvoice.data.shipmentId) {- await trx- .updateTable("shipment")- .set({- invoiced: true,- })- .where("id", "=", salesInvoice.data.shipmentId)- .execute();- }+ // Insert reversing item ledger entries+ if (reversingItemLedgerEntries.length > 0) {+ await trx+ .insertInto("itemLedger")+ .values(reversingItemLedgerEntries)+ .returning(["id"])+ .execute();+ }- await trx- .updateTable("salesInvoice")- .set({- datePaid: today, // TODO: remove this once we have payments working- postingDate: today,- status: "Submitted",- })- .where("id", "=", invoiceId)- .execute();- });+ // Delete invoice-created shipments+ if (invoiceShipments && invoiceShipments.length > 0) {+ for (const shipment of invoiceShipments) {+ await trx+ .deleteFrom("shipmentLine")+ .where("shipmentId", "=", shipment.id)+ .execute();++ await trx+ .deleteFrom("shipment")+ .where("id", "=", shipment.id)+ .execute();+ }+ }++ // Remove invoiced flag from related shipment if it exists+ if (salesInvoice.data.shipmentId) {+ await trx+ .updateTable("shipment")+ .set({+ invoiced: false,+ })+ .where("id", "=", salesInvoice.data.shipmentId)+ .execute();+ }++ // Update invoice status to voided+ await trx+ .updateTable("salesInvoice")+ .set({+ status: "Voided",+ updatedAt: today,+ updatedBy: userId,+ })+ .where("id", "=", invoiceId)+ .execute();+ });++ break;+ }+ }return new Response(JSON.stringify({