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
Invoice Posting (#49)
Brad Barbin7f0e0b6bd04f
diff --git a/apps/carbon/app/modules/accounting/accounting.models.ts b/apps/carbon/app/modules/accounting/accounting.models.tsindex 08471d43cc..43ee232882 100644--- a/apps/carbon/app/modules/accounting/accounting.models.ts+++ b/apps/carbon/app/modules/accounting/accounting.models.ts@@ -27,8 +27,7 @@ const costLedgerTypes = [] as const;export const journalLineDocumentType = [- "Quote",- "Order",+ "Receipt","Invoice","Credit Memo","Blanket Order",@@ -282,6 +281,9 @@ export const defaultAcountValidator = withZod(inventoryReceivedNotInvoicedAccount: z.string().min(1, {message: "Inventory received not invoiced account is required",}),+ inventoryInvoicedNotReceivedAccount: z.string().min(1, {+ message: "Inventory invoiced not received account is required",+ }),inventoryShippedNotInvoicedAccount: z.string().min(1, {message: "Inventory shipped not invoiced account is required",}),@@ -366,17 +368,15 @@ export const paymentTermValidator = withZod(}));-export const valueLedgerValidator = withZod(- z.object({- postingDate: zfd.text(z.string().optional()),- partLedgerType: z.enum(partLedgerTypes),- costLedgerType: z.enum(costLedgerTypes),- adjustment: z.boolean(),- documentType: z.union([z.enum(partLedgerDocumentTypes), z.undefined()]),- documentId: z.string().optional(),- costAmountActual: z.number(),- costAmountExpected: z.number(),- actualCostPostedToGl: z.number(),- expectedCostPostedToGl: z.number(),- })-);+export const costLedgerValidator = z.object({+ postingDate: zfd.text(z.string().optional()),+ partLedgerType: z.enum(partLedgerTypes),+ costLedgerType: z.enum(costLedgerTypes),+ adjustment: z.boolean(),+ documentType: z.union([z.enum(partLedgerDocumentTypes), z.undefined()]),+ documentId: z.string().optional(),+ partId: zfd.text(z.string()),+ quantity: z.number(),+ cost: z.number(),+ costPostedToGL: z.number(),+});diff --git a/apps/carbon/app/modules/accounting/accounting.service.ts b/apps/carbon/app/modules/accounting/accounting.service.tsindex fde35425bd..feb023d8f5 100644--- a/apps/carbon/app/modules/accounting/accounting.service.ts+++ b/apps/carbon/app/modules/accounting/accounting.service.ts@@ -15,7 +15,6 @@ import type {journalLineValidator,partLedgerValidator,paymentTermValidator,- valueLedgerValidator,} from "./accounting.models";import type { Account, Transaction } from "./types";@@ -611,20 +610,6 @@ export async function insertPartLedger(return client.from("partLedger").insert([partEntry]);}-export async function insertValueEntries(- client: SupabaseClient<Database>,- valueEntries: TypeOfValidator<typeof valueLedgerValidator>[]-) {- return client.from("valueLedger").insert(valueEntries);-}--export async function insertValueLedger(- client: SupabaseClient<Database>,- valueEntry: TypeOfValidator<typeof valueLedgerValidator>-) {- return client.from("valueLedger").insert([valueEntry]);-}-export async function updateDefaultAccounts(client: SupabaseClient<Database>,defaultAccounts: TypeOfValidator<typeof defaultAcountValidator> & {diff --git a/apps/carbon/app/modules/accounting/ui/AccountCategories/AccountCategoriesTable/AccountCategoriesTable.tsx b/apps/carbon/app/modules/accounting/ui/AccountCategories/AccountCategoriesTable/AccountCategoriesTable.tsxindex d96fb330dc..00792d2611 100644--- a/apps/carbon/app/modules/accounting/ui/AccountCategories/AccountCategoriesTable/AccountCategoriesTable.tsx+++ b/apps/carbon/app/modules/accounting/ui/AccountCategories/AccountCategoriesTable/AccountCategoriesTable.tsx@@ -1,5 +1,4 @@import {- Badge,Button,ButtonGroup,IconButton,@@ -63,18 +62,7 @@ const AccountCategoriesTable = memo({header: "Debit/Credit",accessorKey: "normalBalance",- cell: (item) => {- const isDebit = item.getValue<string>() === "Debit";- const isCredit = item.getValue<string>() === "Credit";- return (- <Badge- size="sm"- colorScheme={isDebit ? "green" : isCredit ? "red" : "gray"}- >- {item.getValue<string>()}- </Badge>- );- },+ cell: (item) => item.getValue(),},{diff --git a/apps/carbon/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsx b/apps/carbon/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsxindex e9ce0e87d6..c3df9d2c3a 100644--- a/apps/carbon/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsx+++ b/apps/carbon/app/modules/accounting/ui/AccountDefaults/AccountDefaultsForm.tsx@@ -91,7 +91,7 @@ const AccountDefaultsForm = ({</VStack><VStack w="full" alignItems="start" spacing={4}><Heading size="xs" color="gray.400" textTransform="uppercase">- Cost of Goods Sold+ Expenses</Heading><GridgridTemplateColumns={["1fr", "1fr 1fr", "1fr 1fr"]}@@ -130,19 +130,7 @@ const AccountDefaultsForm = ({label="Inventory Adjustment"options={incomeStatementAccountOptions}/>- </Grid>- </VStack>- <VStack w="full" alignItems="start" spacing={4}>- <Heading size="xs" color="gray.400" textTransform="uppercase">- Direct Costs- </Heading>- <Grid- gridTemplateColumns={["1fr", "1fr 1fr", "1fr 1fr"]}- gridColumnGap={8}- gridRowGap={4}- mb={4}- w="full"- >+<Selectname="materialVarianceAccount"label="Material Variance"@@ -167,7 +155,7 @@ const AccountDefaultsForm = ({</VStack><VStack w="full" alignItems="start" spacing={4}><Heading size="xs" color="gray.400" textTransform="uppercase">- Depreciation of Fixed Assets+ Fixed Assets</Heading><GridgridTemplateColumns={["1fr", "1fr 1fr", "1fr 1fr"]}@@ -261,9 +249,10 @@ const AccountDefaultsForm = ({label="Receivables"options={balanceSheetAccountOptions}/>+<Select- name="inventoryShippedNotInvoicedAccount"- label="Inventory Shipped Not Invoiced"+ name="inventoryInvoicedNotReceivedAccount"+ label="Inventory Invoiced Not Received"options={balanceSheetAccountOptions}/><Select@@ -342,6 +331,11 @@ const AccountDefaultsForm = ({label="Inventory Received Not Invoiced"options={balanceSheetAccountOptions}/>+ <Select+ name="inventoryShippedNotInvoicedAccount"+ label="Inventory Shipped Not Invoiced"+ options={balanceSheetAccountOptions}+ /><Selectname="salesTaxPayableAccount"label="Sales Tax Payable"diff --git a/apps/carbon/app/modules/accounting/ui/PostingGroups/InventoryPostingGroupsTable.tsx b/apps/carbon/app/modules/accounting/ui/PostingGroups/InventoryPostingGroupsTable.tsxindex 302f485859..91bdd5c314 100644--- a/apps/carbon/app/modules/accounting/ui/PostingGroups/InventoryPostingGroupsTable.tsx+++ b/apps/carbon/app/modules/accounting/ui/PostingGroups/InventoryPostingGroupsTable.tsx@@ -77,6 +77,11 @@ const InventoryPostingGroupsTable = ({header: "Received Not Invoiced",cell: (item) => item.getValue(),},+ {+ accessorKey: "inventoryInvoicedNotReceivedAccount",+ header: "Invoiced Not Received",+ cell: (item) => item.getValue(),+ },{accessorKey: "inventoryShippedNotInvoicedAccount",header: "Shipped Not Invoiced",@@ -140,6 +145,10 @@ const InventoryPostingGroupsTable = ({onCellEdit,balanceSheetAccountOptions),+ inventoryInvoicedNotReceivedAccount: EditableList(+ onCellEdit,+ balanceSheetAccountOptions+ ),inventoryShippedNotInvoicedAccount: EditableList(onCellEdit,balanceSheetAccountOptionsdiff --git a/apps/carbon/app/modules/accounting/ui/PostingGroups/PurchasingPostingGroupsTable.tsx b/apps/carbon/app/modules/accounting/ui/PostingGroups/PurchasingPostingGroupsTable.tsxindex aca1dd29a1..1e0248b960 100644--- a/apps/carbon/app/modules/accounting/ui/PostingGroups/PurchasingPostingGroupsTable.tsx+++ b/apps/carbon/app/modules/accounting/ui/PostingGroups/PurchasingPostingGroupsTable.tsx@@ -58,6 +58,11 @@ const PurchasingPostingGroupsTable = ({supplierTypes.find((type) => type.id === row.original.supplierTypeId)?.name,},+ {+ accessorKey: "payablesAccount",+ header: "Payables",+ cell: (item) => item.getValue(),+ },{accessorKey: "purchaseAccount",header: "Purchase",@@ -88,6 +93,7 @@ const PurchasingPostingGroupsTable = ({const editableComponents = useMemo(() => ({+ payablesAccount: EditableList(onCellEdit, balanceSheetAccountOptions),purchaseAccount: EditableList(onCellEdit, incomeStatementAccountOptions),purchaseDiscountAccount: EditableList(onCellEdit,diff --git a/apps/carbon/app/modules/accounting/ui/PostingGroups/SalesPostingGroupsTable.tsx b/apps/carbon/app/modules/accounting/ui/PostingGroups/SalesPostingGroupsTable.tsxindex 9051d6809d..080a5705b3 100644--- a/apps/carbon/app/modules/accounting/ui/PostingGroups/SalesPostingGroupsTable.tsx+++ b/apps/carbon/app/modules/accounting/ui/PostingGroups/SalesPostingGroupsTable.tsx@@ -55,6 +55,11 @@ const SalesPostingGroupsTable = ({customerTypes.find((type) => type.id === row.original.customerTypeId)?.name,},+ {+ accessorKey: "receivablesAccount",+ header: "Receivables",+ cell: (item) => item.getValue(),+ },{accessorKey: "salesAccount",header: "Sales",@@ -85,6 +90,7 @@ const SalesPostingGroupsTable = ({const editableComponents = useMemo(() => ({+ receivablesAccount: EditableList(onCellEdit, balanceSheetAccountOptions),salesAccount: EditableList(onCellEdit, incomeStatementAccountOptions),salesDiscountAccount: EditableList(onCellEdit,diff --git a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsxindex 17e6541591..ab2fa767cf 100644--- a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx+++ b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx@@ -72,11 +72,6 @@ const ReceiptForm = ({receiptLines: receiptLines ?? [],});- console.log({- initialValues,- isPosted,- });-return (<><Drawer onClose={onClose} isOpen={true} size="full">@@ -88,7 +83,7 @@ const ReceiptForm = ({<VStack spacing={4} w="full" alignItems="start"><Menubar mb={2} mt={-2}><MenubarItem isDisabled={!canPost || isPosted} onClick={onPost}>- Post Receipt+ Post</MenubarItem></Menubar>diff --git a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsxindex bc4fff9e14..539fded73f 100644--- a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx+++ b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptForm/useReceiptForm.tsx@@ -74,6 +74,10 @@ export default function useReceiptForm({navigate(path.to.receiptPost(receipt.id));};+ const onInvoice = () => {+ navigate(path.to.receiptInvoice(receipt.id));+ };+const sourceDocumentIdFromParams = params.get("sourceDocumentId");const sourceDocumentFromParams = params.get("sourceDocument");@@ -94,29 +98,23 @@ export default function useReceiptForm({if (!supabase) return;try {- await fetch(path.to.api.rollback("receipt", receipt.receiptId), {+ await fetch(path.to.api.rollback("receipt", receipt.id), {method: "DELETE",}).then(() => console.log("successfully rolled back receipt sequence")).catch(console.error);- await supabase- .from("receipt")- .delete()- .eq("receiptId", receipt.receiptId);+ await supabase.from("receipt").delete().eq("receiptId", receipt.id);} catch {setError("Failed to delete receipt");}- }, [receipt.receiptId, supabase]);+ }, [receipt.id, supabase]);const deleteReceiptLines = useCallback(async () => {if (!supabase) throw new Error("supabase client is not defined");- return supabase- .from("receiptLine")- .delete()- .eq("receiptId", receipt.receiptId);- }, [receipt.receiptId, supabase]);+ return supabase.from("receiptLine").delete().eq("receiptId", receipt.id);+ }, [receipt.id, supabase]);const fetchSourceDocuments = useCallback(() => {if (!supabase) return;@@ -150,35 +148,31 @@ export default function useReceiptForm({switch (sourceDocument) {case "Purchase Order":- const [- purchaseOrder,- receiptLines,- previouslyReceivedLines,- purchaseOrderLines,- ] = await Promise.all([- supabase- .from("purchaseOrders")- .select("*")- .eq("id", sourceDocumentId)- .single(),-- supabase- .from("receiptLine")- .select("*")- .eq("receiptId", receipt.receiptId),- supabase- .from("receiptQuantityReceivedByLine")- .select("*")- .eq("sourceDocumentId", sourceDocumentId),- locationId- ? supabase- .from("purchaseOrderLine")- .select("*")- .eq("purchaseOrderId", sourceDocumentId)- .eq("purchaseOrderLineType", "Part")- .eq("locationId", locationId)- : Promise.resolve({ data: [] as PurchaseOrderLine[], error: null }),- ]);+ const [purchaseOrder, receiptLines, purchaseOrderLines] =+ await Promise.all([+ supabase+ .from("purchaseOrders")+ .select("*")+ .eq("id", sourceDocumentId)+ .single(),++ supabase+ .from("receiptLine")+ .select("*")+ .eq("receiptId", receipt.id),++ locationId+ ? supabase+ .from("purchaseOrderLine")+ .select("*")+ .eq("purchaseOrderId", sourceDocumentId)+ .eq("purchaseOrderLineType", "Part")+ .eq("locationId", locationId)+ : Promise.resolve({+ data: [] as PurchaseOrderLine[],+ error: null,+ }),+ ]);if (purchaseOrder.error) {setError(purchaseOrder.error.message);@@ -215,9 +209,9 @@ export default function useReceiptForm({}const previouslyReceivedQuantitiesByLine = (- previouslyReceivedLines.data ?? []+ purchaseOrderLines.data ?? []).reduce<Record<string, number>>((acc, d) => {- if (d.lineId) acc[d.lineId] = d.receivedQuantity ?? 0;+ if (d.id) acc[d.id] = d.quantityReceived ?? 0;return acc;}, {});@@ -238,7 +232,7 @@ export default function useReceiptForm({(previouslyReceivedQuantitiesByLine[d.id] ?? 0);acc.push({- receiptId: receipt.receiptId,+ receiptId: receipt.id,lineId: d.id,partId: d.partId,orderQuantity: d.purchaseQuantity,@@ -267,7 +261,7 @@ export default function useReceiptForm({const { data: receiptLinesData, error: selectError } = await supabase.from("receiptLine").select("*")- .eq("receiptId", receipt.receiptId);+ .eq("receiptId", receipt.id);if (selectError) {setError(selectError.message);@@ -283,7 +277,7 @@ export default function useReceiptForm({}, [deleteReceiptLines,locationId,- receipt.receiptId,+ receipt.id,receipt.sourceDocumentId,sourceDocument,sourceDocumentId,@@ -385,6 +379,7 @@ export default function useReceiptForm({supplierId,sourceDocuments,onClose,+ onInvoice,onPost,setLocationId,setReceiptLines,diff --git a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptPostModal/ReceiptPostModal.tsx b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptPostModal/ReceiptPostModal.tsxindex 3c68b5c538..c25e3949af 100644--- a/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptPostModal/ReceiptPostModal.tsx+++ b/apps/carbon/app/modules/inventory/ui/Receipts/ReceiptPostModal/ReceiptPostModal.tsx@@ -34,9 +34,8 @@ const ReceiptPostModal = (props: ReceiptPostModalProps) => {Cancel</Button><Form method="post">- <input type="hidden" name="intent" value="receive" /><Button colorScheme="brand" type="submit">- Receive+ Post Receipt</Button></Form></HStack>diff --git a/apps/carbon/app/modules/invoicing/invoicing.models.ts b/apps/carbon/app/modules/invoicing/invoicing.models.tsindex 8879ec83cf..36174ed9aa 100644--- a/apps/carbon/app/modules/invoicing/invoicing.models.ts+++ b/apps/carbon/app/modules/invoicing/invoicing.models.ts@@ -4,6 +4,7 @@ import { zfd } from "zod-form-data";export const purchaseInvoiceStatusType = ["Draft",+ "Pending","Submitted","Return","Debit Note Issued",diff --git a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceForm/PurchaseInvoiceForm.tsx b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceForm/PurchaseInvoiceForm.tsxindex 1c3e5723e8..fcc1fc0b86 100644--- a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceForm/PurchaseInvoiceForm.tsx+++ b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceForm/PurchaseInvoiceForm.tsx@@ -72,7 +72,7 @@ const PurchaseInvoiceForm = ({{isEditing ? "Purchase Invoice" : "New Purchase Invoice"}</Heading>{!isEditing && (- <Text color="gray.500">+ <Text color="gray.500" fontWeight="normal">A purchase invoice is a document that specifies the products orservices purchased by a customer and the corresponding cost.</Text>diff --git a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader/PurchaseInvoiceHeader.tsx b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader/PurchaseInvoiceHeader.tsxindex 6ca4788dbf..433884af83 100644--- a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader/PurchaseInvoiceHeader.tsx+++ b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader/PurchaseInvoiceHeader.tsx@@ -6,11 +6,19 @@ import {CardHeader,HStack,Heading,+ Modal,+ ModalBody,+ ModalCloseButton,+ ModalContent,+ ModalFooter,+ ModalHeader,+ ModalOverlay,Stack,Text,VStack,+ useDisclosure,} from "@chakra-ui/react";-import { useParams } from "@remix-run/react";+import { Form, useParams } from "@remix-run/react";import { useMemo } from "react";import { FaHistory } from "react-icons/fa";import { usePermissions, useRouteData } from "~/hooks";@@ -24,13 +32,19 @@ import { path } from "~/utils/path";const PurchaseInvoiceHeader = () => {const permissions = usePermissions();const { invoiceId } = useParams();+ const postingModal = useDisclosure();- if (!invoiceId) throw new Error("Could not find invoiceId");+ if (!invoiceId) throw new Error("invoiceId not found");const routeData = useRouteData<{ purchaseInvoice: PurchaseInvoice }>(path.to.purchaseInvoice(invoiceId));+ if (!routeData?.purchaseInvoice) throw new Error("purchaseInvoice not found");+ const { purchaseInvoice } = routeData;++ const isPosted = purchaseInvoice.postingDate !== null;+const [purchaseInvoiceTotals] = usePurchaseInvoiceTotals();// TODO: factor in default currency, po currency and exchange rate@@ -41,77 +55,93 @@ const PurchaseInvoiceHeader = () => {);return (- <VStack w="full" alignItems="start" spacing={2}>- {permissions.is("employee") && (- <Menubar>- <MenubarItem- // onClick={() => {- // if (routeData?.purchaseInvoice) release(routeData.purchaseInvoice);- // }}- // isDisabled={- // !["Draft", "Approved"].includes(- // routeData?.purchaseInvoice?.status ?? ""- // )- // }- >- Action 1- </MenubarItem>- </Menubar>- )}-- <Card w="full">- <CardHeader>- <HStack justifyContent="space-between" alignItems="start">- <Stack direction="column" spacing={2}>- <Heading size="md">- {routeData?.purchaseInvoice?.invoiceId}- </Heading>- <Text color="gray.500">- {routeData?.purchaseInvoice?.supplierName}- </Text>- </Stack>- <Button onClick={() => alert("TODO")} leftIcon={<FaHistory />}>- Supplier Details- </Button>- </HStack>- </CardHeader>- <CardBody>- <Stack direction={["column", "column", "row"]} spacing={8}>- <Stack- direction={["row", "row", "column"]}- alignItems="start"- justifyContent="space-between"- >- <Text color="gray.500">Total</Text>- <Text fontWeight="bold">- {formatter.format(purchaseInvoiceTotals?.total ?? 0)}- </Text>- </Stack>- <Stack- direction={["row", "row", "column"]}- alignItems="start"- justifyContent="space-between"+ <>+ <VStack w="full" alignItems="start" spacing={2}>+ {permissions.is("employee") && (+ <Menubar>+ <MenubarItem+ isDisabled={!permissions.can("update", "invoicing") || isPosted}+ onClick={postingModal.onOpen}>- <Text color="gray.500">Date Issued</Text>- <Text fontWeight="bold">- {routeData?.purchaseInvoice?.dateIssued}- </Text>- </Stack>+ Post+ </MenubarItem>+ </Menubar>+ )}- <Stack- direction={["row", "row", "column"]}- alignItems="start"- justifyContent="space-between"- >- <Text color="gray.500">Status</Text>- <PurchaseInvoicingStatus- status={routeData?.purchaseInvoice?.status}- />+ <Card w="full">+ <CardHeader>+ <HStack justifyContent="space-between" alignItems="start">+ <Stack direction="column" spacing={2}>+ <Heading size="md">{purchaseInvoice.invoiceId}</Heading>+ <Text color="gray.500" fontWeight="normal">+ {purchaseInvoice.supplierName}+ </Text>+ </Stack>+ <Button onClick={() => alert("TODO")} leftIcon={<FaHistory />}>+ Supplier Details+ </Button>+ </HStack>+ </CardHeader>+ <CardBody>+ <Stack direction={["column", "column", "row"]} spacing={8}>+ <Stack+ direction={["row", "row", "column"]}+ alignItems="start"+ justifyContent="space-between"+ >+ <Text color="gray.500">Total</Text>+ <Text fontWeight="bold">+ {formatter.format(purchaseInvoiceTotals?.total ?? 0)}+ </Text>+ </Stack>+ <Stack+ direction={["row", "row", "column"]}+ alignItems="start"+ justifyContent="space-between"+ >+ <Text color="gray.500">Date Issued</Text>+ <Text fontWeight="bold">{purchaseInvoice.dateIssued}</Text>+ </Stack>++ <Stack+ direction={["row", "row", "column"]}+ alignItems="start"+ justifyContent="space-between"+ >+ <Text color="gray.500">Status</Text>+ <PurchaseInvoicingStatus status={purchaseInvoice.status} />+ </Stack></Stack>- </Stack>- </CardBody>- </Card>- </VStack>+ </CardBody>+ </Card>+ </VStack>+ <Modal isOpen={postingModal.isOpen} onClose={postingModal.onClose}>+ <ModalOverlay />+ <ModalContent>+ <ModalHeader>Post Invoice</ModalHeader>+ <ModalCloseButton />+ <ModalBody>+ Are you sure you want to post this invoice? This cannot be undone.+ </ModalBody>++ <ModalFooter>+ <HStack spacing={2}>+ <Button colorScheme="gray" onClick={postingModal.onClose}>+ Cancel+ </Button>+ <Form+ method="post"+ action={path.to.purchaseInvoicePost(invoiceId)}+ >+ <Button colorScheme="brand" type="submit">+ Post Invoice+ </Button>+ </Form>+ </HStack>+ </ModalFooter>+ </ModalContent>+ </Modal>+ </>);};diff --git a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLines/PurchaseInvoiceLines.tsx b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLines/PurchaseInvoiceLines.tsxindex 64a8f884d5..ef3615c16f 100644--- a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLines/PurchaseInvoiceLines.tsx+++ b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLines/PurchaseInvoiceLines.tsx@@ -54,9 +54,7 @@ const PurchaseInvoiceLines = () => {} = usePurchaseInvoiceLines();const [, setPurchaseInvoiceTotals] = usePurchaseInvoiceTotals();- const isEditable = ["Draft", "To Review"].includes(- routeData?.purchaseInvoice?.status ?? ""- );+ const isEditable = !routeData?.purchaseInvoice?.postingDate ?? false;const columns = useMemo<ColumnDef<PurchaseInvoiceLine>[]>(() => {return [diff --git a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicingStatus/PurchaseInvoicingStatus.tsx b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicingStatus/PurchaseInvoicingStatus.tsxindex d7f8ed7729..9b18c9b540 100644--- a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicingStatus/PurchaseInvoicingStatus.tsx+++ b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicingStatus/PurchaseInvoicingStatus.tsx@@ -12,6 +12,7 @@ const PurchaseInvoicingStatus = ({ status }: PurchaseInvoicingStatusProps) => {return <Status color="gray">{status}</Status>;case "Submitted":return <Status color="yellow">{status}</Status>;+ case "Pending":case "Partially Paid":return <Status color="orange">{status}</Status>;case "Overdue":diff --git a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoices/PurchaseInvoicesTable/PurchaseInvoicesTable.tsx b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoices/PurchaseInvoicesTable/PurchaseInvoicesTable.tsxindex 171f67501f..9755b5a04a 100644--- a/apps/carbon/app/modules/invoicing/ui/PurchaseInvoices/PurchaseInvoicesTable/PurchaseInvoicesTable.tsx+++ b/apps/carbon/app/modules/invoicing/ui/PurchaseInvoices/PurchaseInvoicesTable/PurchaseInvoicesTable.tsx@@ -6,7 +6,7 @@ import { BsPencilSquare } from "react-icons/bs";import { IoMdTrash } from "react-icons/io";import { Avatar, Table } from "~/components";import { ConfirmDelete } from "~/components/Modals";-import { usePermissions } from "~/hooks";+import { usePermissions, useRealtime } from "~/hooks";import type {PurchaseInvoice,purchaseInvoiceStatusType,@@ -21,6 +21,11 @@ type PurchaseInvoicesTableProps = {const PurchaseInvoicesTable = memo(({ data, count }: PurchaseInvoicesTableProps) => {+ useRealtime(+ "purchaseInvoice",+ `id=in.(${data.map((d) => d.id).join(",")})`+ );+const permissions = usePermissions();const navigate = useNavigate();diff --git a/apps/carbon/app/modules/parts/ui/Part/PartForm/PartForm.tsx b/apps/carbon/app/modules/parts/ui/Part/PartForm/PartForm.tsxindex aa5699fd54..dd6f165325 100644--- a/apps/carbon/app/modules/parts/ui/Part/PartForm/PartForm.tsx+++ b/apps/carbon/app/modules/parts/ui/Part/PartForm/PartForm.tsx@@ -138,7 +138,7 @@ const PartForm = ({ initialValues }: PartFormProps) => {<CardHeader><Heading size="md">{isEditing ? "Part Details" : "New Part"}</Heading>{!isEditing && (- <Text color="gray.500">+ <Text color="gray.500" fontWeight="normal">A part contains the information about a specific item that can bepurchased or manufactured.</Text>diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderForm/PurchaseOrderForm.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderForm/PurchaseOrderForm.tsxindex 0777aada79..1cda66d928 100644--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderForm/PurchaseOrderForm.tsx+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderForm/PurchaseOrderForm.tsx@@ -65,7 +65,7 @@ const PurchaseOrderForm = ({ initialValues }: PurchaseOrderFormProps) => {{isEditing ? "Purchase Order" : "New Purchase Order"}</Heading>{!isEditing && (- <Text color="gray.500">+ <Text color="gray.500" fontWeight="normal">A purchase order contains information about the agreement betweenthe company and a specific supplier for parts and services.</Text>diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader/PurchaseOrderHeader.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader/PurchaseOrderHeader.tsxindex ec6c05d3b2..aeb7328c26 100644--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader/PurchaseOrderHeader.tsx+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader/PurchaseOrderHeader.tsx@@ -93,7 +93,7 @@ const PurchaseOrderHeader = () => {<Heading size="md">{routeData?.purchaseOrder?.purchaseOrderId}</Heading>- <Text color="gray.500">+ <Text color="gray.500" fontWeight="normal">{routeData?.purchaseOrder?.supplierName}</Text></Stack>diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierForm/SupplierForm.tsx b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierForm/SupplierForm.tsxindex ac2ac87373..3ac63d9e91 100644--- a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierForm/SupplierForm.tsx+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierForm/SupplierForm.tsx@@ -58,7 +58,7 @@ const SupplierForm = ({ initialValues }: SupplierFormProps) => {{isEditing ? "Supplier Overview" : "New Supplier"}</Heading>{!isEditing && (- <Text color="gray.500">+ <Text color="gray.500" fontWeight="normal">A supplier is a business or person who sells you parts orservices.</Text>diff --git a/apps/carbon/app/modules/sales/ui/Customer/CustomerForm/CustomerForm.tsx b/apps/carbon/app/modules/sales/ui/Customer/CustomerForm/CustomerForm.tsxindex 591380a0e7..9d8fd41073 100644--- a/apps/carbon/app/modules/sales/ui/Customer/CustomerForm/CustomerForm.tsx+++ b/apps/carbon/app/modules/sales/ui/Customer/CustomerForm/CustomerForm.tsx@@ -58,7 +58,7 @@ const CustomerForm = ({ initialValues }: CustomerFormProps) => {{isEditing ? "Customer Overview" : "New Customer"}</Heading>{!isEditing && (- <Text color="gray.500">+ <Text color="gray.500" fontWeight="normal">A customer is a business or person who buys your parts orservices.</Text>diff --git a/apps/carbon/app/queues/accounting-posting.queue.server.ts b/apps/carbon/app/queues/accounting-posting.queue.server.tsindex 647f764757..3fb0de458c 100644--- a/apps/carbon/app/queues/accounting-posting.queue.server.ts+++ b/apps/carbon/app/queues/accounting-posting.queue.server.ts@@ -3,6 +3,7 @@ import { getSupabaseServiceRole } from "~/lib/supabase";export enum PostingQueueType {Receipt = "receipt",+ PurchaseInvoice = "purchase-invoice",}export type PostingQueueData = {@@ -16,7 +17,14 @@ export const postingQueue = Queue<PostingQueueData>("posting:v1",async (job) => {switch (job.data.type) {- case "receipt":+ case PostingQueueType.PurchaseInvoice:+ await client.functions.invoke("post-purchase-invoice", {+ body: {+ invoiceId: job.data.documentId,+ },+ });+ break;+ case PostingQueueType.Receipt:await client.functions.invoke("post-receipt", {body: {receiptId: job.data.documentId,diff --git a/apps/carbon/app/routes/x+/inventory+/receipts.$receiptId.post.tsx b/apps/carbon/app/routes/x+/inventory+/receipts.$receiptId.post.tsxindex 2803fe4d0b..3d9c6e98bd 100644--- a/apps/carbon/app/routes/x+/inventory+/receipts.$receiptId.post.tsx+++ b/apps/carbon/app/routes/x+/inventory+/receipts.$receiptId.post.tsx@@ -15,37 +15,28 @@ export async function action({ request, params }: ActionFunctionArgs) {const { receiptId } = params;if (!receiptId) throw new Error("receiptId not found");- const formData = await request.formData();-- switch (formData.get("intent")) {- case "receive":- const setPendingState = await client- .from("receipt")- .update({- status: "Pending",- })- .eq("id", receiptId);-- if (setPendingState.error) {- return redirect(- path.to.receipts,- await flash(- request,- error(setPendingState.error, "Failed to post receipt")- )- );- }-- postingQueue.add(`posting receipt ${receiptId}`, {- type: PostingQueueType.Receipt,- documentId: receiptId,- });-- return redirect(path.to.receipts);- default:- break;+ const setPendingState = await client+ .from("receipt")+ .update({+ status: "Pending",+ })+ .eq("id", receiptId);++ if (setPendingState.error) {+ return redirect(+ path.to.receipts,+ await flash(+ request,+ error(setPendingState.error, "Failed to post receipt")+ )+ );}+ postingQueue.add(`posting receipt ${receiptId}`, {+ type: PostingQueueType.Receipt,+ documentId: receiptId,+ });+return redirect(path.to.receipts);}diff --git a/apps/carbon/app/routes/x+/purchase-invoice+/$invoiceId.details.tsx b/apps/carbon/app/routes/x+/purchase-invoice+/$invoiceId.details.tsxindex baac392a8b..88e28d8d6f 100644--- a/apps/carbon/app/routes/x+/purchase-invoice+/$invoiceId.details.tsx+++ b/apps/carbon/app/routes/x+/purchase-invoice+/$invoiceId.details.tsx@@ -62,30 +62,33 @@ export async function action({ request, params }: ActionFunctionArgs) {export default function PurchaseInvoiceBasicRoute() {const { invoiceId } = useParams();- if (!invoiceId) throw new Error("Could not find invoiceId");+ if (!invoiceId) throw new Error("invoiceId not found");const sharedData = useRouteData<{ paymentTerms: ListItem[] }>(path.to.purchaseInvoiceRoot);const invoiceData = useRouteData<{ purchaseInvoice: PurchaseInvoice }>(path.to.purchaseInvoice(invoiceId));++ if (!invoiceData?.purchaseInvoice)+ throw new Error("purchaseInvoice not found");+ const { purchaseInvoice } = invoiceData;+if (!invoiceData) throw new Error("Could not find invoice data");const initialValues = {- id: invoiceData?.purchaseInvoice?.id ?? "",- invoiceId: invoiceData?.purchaseInvoice?.invoiceId ?? "",- supplierId: invoiceData?.purchaseInvoice?.supplierId ?? "",- supplierReference: invoiceData?.purchaseInvoice?.supplierReference ?? "",- invoiceSupplierId: invoiceData?.purchaseInvoice?.invoiceSupplierId ?? "",- invoiceSupplierContactId:- invoiceData?.purchaseInvoice?.invoiceSupplierContactId ?? "",- invoiceSupplierLocationId:- invoiceData?.purchaseInvoice.invoiceSupplierLocationId ?? "",- paymentTermId: invoiceData?.purchaseInvoice?.paymentTermId ?? "",- currencyCode: invoiceData?.purchaseInvoice?.currencyCode ?? "",- dateIssued: invoiceData?.purchaseInvoice?.dateIssued ?? "",- dateDue: invoiceData?.purchaseInvoice?.dateDue ?? "",- status: invoiceData?.purchaseInvoice?.status ?? ("Draft" as "Draft"),+ id: purchaseInvoice.id ?? "",+ invoiceId: purchaseInvoice.invoiceId ?? "",+ supplierId: purchaseInvoice.supplierId ?? "",+ supplierReference: purchaseInvoice.supplierReference ?? "",+ invoiceSupplierId: purchaseInvoice.invoiceSupplierId ?? "",+ invoiceSupplierContactId: purchaseInvoice.invoiceSupplierContactId ?? "",+ invoiceSupplierLocationId: purchaseInvoice.invoiceSupplierLocationId ?? "",+ paymentTermId: purchaseInvoice.paymentTermId ?? "",+ currencyCode: purchaseInvoice.currencyCode ?? "",+ dateIssued: purchaseInvoice.dateIssued ?? "",+ dateDue: purchaseInvoice.dateDue ?? "",+ status: purchaseInvoice.status ?? ("Draft" as "Draft"),};return (diff --git a/apps/carbon/app/routes/x+/purchase-invoice+/$invoiceId.post.tsx b/apps/carbon/app/routes/x+/purchase-invoice+/$invoiceId.post.tsxnew file mode 100644index 0000000000..65ffcc2422--- /dev/null+++ b/apps/carbon/app/routes/x+/purchase-invoice+/$invoiceId.post.tsx@@ -0,0 +1,40 @@+import type { ActionFunctionArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { postingQueue, PostingQueueType } from "~/queues";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { path } from "~/utils/path";+import { error } from "~/utils/result";++export async function action({ request, params }: ActionFunctionArgs) {+ const { client } = await requirePermissions(request, {+ update: "invoicing",+ });++ const { invoiceId } = params;+ if (!invoiceId) throw new Error("invoiceId not found");++ const setPendingState = await client+ .from("purchaseInvoice")+ .update({+ status: "Pending",+ })+ .eq("id", invoiceId);++ if (setPendingState.error) {+ return redirect(+ path.to.purchaseInvoices,+ await flash(+ request,+ error(setPendingState.error, "Failed to post purchase invoice")+ )+ );+ }++ postingQueue.add(`posting invoice ${invoiceId}`, {+ type: PostingQueueType.PurchaseInvoice,+ documentId: invoiceId,+ });++ return redirect(path.to.purchaseInvoices);+}diff --git a/apps/carbon/app/routes/x+/resources+/locations.new.tsx b/apps/carbon/app/routes/x+/resources+/locations.new.tsxindex 9bd69999af..39f6c3fb2f 100644--- a/apps/carbon/app/routes/x+/resources+/locations.new.tsx+++ b/apps/carbon/app/routes/x+/resources+/locations.new.tsx@@ -44,7 +44,7 @@ export async function action({ request }: ActionFunctionArgs) {return redirect(path.to.locations,- await flash(request, success("Location created."))+ await flash(request, success("Location created")));}diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.tsindex 995755df54..8e90b99439 100644--- a/apps/carbon/app/utils/path.ts+++ b/apps/carbon/app/utils/path.ts@@ -291,6 +291,8 @@ export const path = {generatePath(`${x}/purchase-invoice/${id}`),purchaseInvoiceDetails: (id: string) =>generatePath(`${x}/purchase-invoice/${id}/details`),+ purchaseInvoicePost: (id: string) =>+ generatePath(`${x}/purchase-invoice/${id}/post`),purchaseInvoiceRoot: `${x}/purchase-invoice`,purchaseInvoices: `${x}/invoicing/purchasing`,purchaseOrder: (id: string) => generatePath(`${x}/purchase-order/${id}`),@@ -306,6 +308,7 @@ export const path = {purchasing: `${x}/purchasing`,receipt: (id: string) => generatePath(`${x}/inventory/receipts/${id}`),receipts: `${x}/inventory/receipts`,+ receiptInvoice: (id: string) => generatePath(`${x}/receipt/${id}/invoice`),receiptPost: (id: string) =>generatePath(`${x}/inventory/receipts/${id}/post`),refreshSession: "/refresh-session",diff --git a/package-lock.json b/package-lock.jsonindex 197a8315ac..a4e420efe8 100644--- a/package-lock.json+++ b/package-lock.json@@ -2917,9 +2917,9 @@}},"node_modules/@internationalized/number": {- "version": "3.3.0",- "resolved": "https://registry.npmjs.org/@internationalized/number/-/number-3.3.0.tgz",- "integrity": "sha512-PuxgnKE5NJMOGKUcX1QROo8jq7sW7UWLrL5B6Rfe8BdWgU/be04cVvLyCeALD46vvbAv3d1mUvyHav/Q9a237g==",+ "version": "3.4.0",+ "resolved": "https://registry.npmjs.org/@internationalized/number/-/number-3.4.0.tgz",+ "integrity": "sha512-8TvotW3qVDHC4uv/BVoN6Qx0Dm8clHY1/vpH+dh+XRiPW/9NVpKn1P8d1A+WLphWrMwyqyWXI7uWehJPviaeIw==","dependencies": {"@swc/helpers": "^0.5.0"}@@ -4276,25 +4276,27 @@}},"node_modules/@react-aria/datepicker": {- "version": "3.8.1",- "resolved": "https://registry.npmjs.org/@react-aria/datepicker/-/datepicker-3.8.1.tgz",- "integrity": "sha512-q2Z5DYDkic3RWzvg3oysrA2VEebuxtEfqj8PSlNFndZh/pNrA+Tvkaatdk/BoxlsZsfeLof+/tBq6yWeqTDguQ==",+ "version": "3.9.0",+ "resolved": "https://registry.npmjs.org/@react-aria/datepicker/-/datepicker-3.9.0.tgz",+ "integrity": "sha512-FIpiJxwBNOM8a6hLOqQJ4JrvRiGL6Zr44E1mHtAWStp2kBEJ6+O2JRm4PQ5Pzvdw6xnCpOBdfESdNdlXN7lVqQ==","dependencies": {"@internationalized/date": "^3.5.0",- "@internationalized/number": "^3.3.0",+ "@internationalized/number": "^3.4.0","@internationalized/string": "^3.1.1",- "@react-aria/focus": "^3.14.3",- "@react-aria/i18n": "^3.8.4",- "@react-aria/interactions": "^3.19.1",- "@react-aria/label": "^3.7.2",- "@react-aria/spinbutton": "^3.5.4",- "@react-aria/utils": "^3.21.1",- "@react-stately/datepicker": "^3.8.0",- "@react-types/button": "^3.9.0",- "@react-types/calendar": "^3.4.1",- "@react-types/datepicker": "^3.6.1",- "@react-types/dialog": "^3.5.6",- "@react-types/shared": "^3.21.0",+ "@react-aria/focus": "^3.15.0",+ "@react-aria/form": "^3.0.0",+ "@react-aria/i18n": "^3.9.0",+ "@react-aria/interactions": "^3.20.0",+ "@react-aria/label": "^3.7.3",+ "@react-aria/spinbutton": "^3.6.0",+ "@react-aria/utils": "^3.22.0",+ "@react-stately/datepicker": "^3.9.0",+ "@react-stately/form": "^3.0.0",+ "@react-types/button": "^3.9.1",+ "@react-types/calendar": "^3.4.2",+ "@react-types/datepicker": "^3.7.0",+ "@react-types/dialog": "^3.5.7",+ "@react-types/shared": "^3.22.0","@swc/helpers": "^0.5.0"},"peerDependencies": {@@ -4303,13 +4305,13 @@}},"node_modules/@react-aria/focus": {- "version": "3.14.3",- "resolved": "https://registry.npmjs.org/@react-aria/focus/-/focus-3.14.3.tgz",- "integrity": "sha512-gvO/frZ7SxyfyHJYC+kRsUXnXct8hGHKlG1TwbkzCCXim9XIPKDgRzfNGuFfj0i8ZpR9xmsjOBUkHZny0uekFA==",+ "version": "3.15.0",+ "resolved": "https://registry.npmjs.org/@react-aria/focus/-/focus-3.15.0.tgz",+ "integrity": "sha512-nnxRyfqHuAjRwdQ4BpQyZPtGFKZmRU6cnaIb3pqWFCqEyJQensV7MA3TJ4Jhadq67cy1Ji5SYSlr1duBwjoYvw==","dependencies": {- "@react-aria/interactions": "^3.19.1",- "@react-aria/utils": "^3.21.1",- "@react-types/shared": "^3.21.0",+ "@react-aria/interactions": "^3.20.0",+ "@react-aria/utils": "^3.22.0",+ "@react-types/shared": "^3.22.0","@swc/helpers": "^0.5.0","clsx": "^1.1.1"},@@ -4317,18 +4319,33 @@"react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0"}},+ "node_modules/@react-aria/form": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/@react-aria/form/-/form-3.0.0.tgz",+ "integrity": "sha512-APeGph9oTO8nro4ZObuy1hk+0hpF/ji9O3odPGhLkzP/HvW2J7NI9pjKJOINfgtYr2yvVUZf/MbTMxPwtAxhaQ==",+ "dependencies": {+ "@react-aria/interactions": "^3.20.0",+ "@react-aria/utils": "^3.22.0",+ "@react-stately/form": "^3.0.0",+ "@react-types/shared": "^3.22.0",+ "@swc/helpers": "^0.5.0"+ },+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0"+ }+ },"node_modules/@react-aria/i18n": {- "version": "3.8.4",- "resolved": "https://registry.npmjs.org/@react-aria/i18n/-/i18n-3.8.4.tgz",- "integrity": "sha512-YlTJn7YJlUxds/T5dNtme551qc118NoDQhK+IgGpzcmPQ3xSnwBAQP4Zwc7wCpAU+xEwnNcsGw+L1wJd49He/A==",+ "version": "3.9.0",+ "resolved": "https://registry.npmjs.org/@react-aria/i18n/-/i18n-3.9.0.tgz",+ "integrity": "sha512-ebGP/sVG0ZtNF4RNFzs/W01tl7waYpBManh1kKWgA4roDPFt/odkgkDBzKGl+ggBb7TQRHsfUFHuqKsrsMy9TA==","dependencies": {"@internationalized/date": "^3.5.0","@internationalized/message": "^3.1.1",- "@internationalized/number": "^3.3.0",+ "@internationalized/number": "^3.4.0","@internationalized/string": "^3.1.1",- "@react-aria/ssr": "^3.8.0",- "@react-aria/utils": "^3.21.1",- "@react-types/shared": "^3.21.0",+ "@react-aria/ssr": "^3.9.0",+ "@react-aria/utils": "^3.22.0",+ "@react-types/shared": "^3.22.0","@swc/helpers": "^0.5.0"},"peerDependencies": {@@ -4336,13 +4353,13 @@}},"node_modules/@react-aria/interactions": {- "version": "3.19.1",- "resolved": "https://registry.npmjs.org/@react-aria/interactions/-/interactions-3.19.1.tgz",- "integrity": "sha512-2QFOvq/rJfMGEezmtYcGcJmfaD16kHKcSTLFrZ8aeBK6hYFddGVZJZk+dXf+G7iNaffa8rMt6uwzVe/malJPBA==",+ "version": "3.20.0",+ "resolved": "https://registry.npmjs.org/@react-aria/interactions/-/interactions-3.20.0.tgz",+ "integrity": "sha512-JCCEyK2Nb4mEHucrgmqhTHTNAEqhsiM07jJmmY22eikxnCQnsEfdwXyg9cgZLG79D5V7jyqVRqOp2OsG7Qx7kQ==","dependencies": {- "@react-aria/ssr": "^3.8.0",- "@react-aria/utils": "^3.21.1",- "@react-types/shared": "^3.21.0",+ "@react-aria/ssr": "^3.9.0",+ "@react-aria/utils": "^3.22.0",+ "@react-types/shared": "^3.22.0","@swc/helpers": "^0.5.0"},"peerDependencies": {@@ -4350,13 +4367,12 @@}},"node_modules/@react-aria/label": {- "version": "3.7.2",- "resolved": "https://registry.npmjs.org/@react-aria/label/-/label-3.7.2.tgz",- "integrity": "sha512-rS0xQy+4RH1+JLESzLZd9H285McjNNf2kKwBhzU0CW3akjlu7gqaMKEJhX9MlpPDIVOUc2oEObGdU3UMmqa8ew==",+ "version": "3.7.3",+ "resolved": "https://registry.npmjs.org/@react-aria/label/-/label-3.7.3.tgz",+ "integrity": "sha512-v1zuqbpYyYaPjrBWpceGjMpwP4ne6fLoOXdoIZoKLux2jkAcyIF2kIJFiyYoPQYQJWGRNo7q1oSwamxmng4xJw==","dependencies": {- "@react-aria/utils": "^3.21.1",- "@react-types/label": "^3.8.1",- "@react-types/shared": "^3.21.0",+ "@react-aria/utils": "^3.22.0",+ "@react-types/shared": "^3.22.0","@swc/helpers": "^0.5.0"},"peerDependencies": {@@ -4372,15 +4388,15 @@}},"node_modules/@react-aria/spinbutton": {- "version": "3.5.4",- "resolved": "https://registry.npmjs.org/@react-aria/spinbutton/-/spinbutton-3.5.4.tgz",- "integrity": "sha512-W5dhUOjyBIgd8d4z526fW/HXQ+BdFceeGyvNAXoYBi/1gt3KqN/6CZgskG7OQEufxCOWc9e4A2eWNwvkQVJvWg==",+ "version": "3.6.0",+ "resolved": "https://registry.npmjs.org/@react-aria/spinbutton/-/spinbutton-3.6.0.tgz",+ "integrity": "sha512-I7f1gfwVRcjguEXZijk0z5g8njZ2YWnQzVzcwGf8ocLPxfw1CnSivNCzwVj2ChXPX10uXewXVMLWVCz+BRC9uQ==","dependencies": {- "@react-aria/i18n": "^3.8.4",+ "@react-aria/i18n": "^3.9.0","@react-aria/live-announcer": "^3.3.1",- "@react-aria/utils": "^3.21.1",- "@react-types/button": "^3.9.0",- "@react-types/shared": "^3.21.0",+ "@react-aria/utils": "^3.22.0",+ "@react-types/button": "^3.9.1",+ "@react-types/shared": "^3.22.0","@swc/helpers": "^0.5.0"},"peerDependencies": {@@ -4389,9 +4405,9 @@}},"node_modules/@react-aria/ssr": {- "version": "3.8.0",- "resolved": "https://registry.npmjs.org/@react-aria/ssr/-/ssr-3.8.0.tgz",- "integrity": "sha512-Y54xs483rglN5DxbwfCPHxnkvZ+gZ0LbSYmR72LyWPGft8hN/lrl1VRS1EW2SMjnkEWlj+Km2mwvA3kEHDUA0A==",+ "version": "3.9.0",+ "resolved": "https://registry.npmjs.org/@react-aria/ssr/-/ssr-3.9.0.tgz",+ "integrity": "sha512-Bz6BqP6ZorCme9tSWHZVmmY+s7AU8l6Vl2NUYmBzezD//fVHHfFo4lFBn5tBuAaJEm3AuCLaJQ6H2qhxNSb7zg==","dependencies": {"@swc/helpers": "^0.5.0"},@@ -4403,13 +4419,13 @@}},"node_modules/@react-aria/utils": {- "version": "3.21.1",- "resolved": "https://registry.npmjs.org/@react-aria/utils/-/utils-3.21.1.tgz",- "integrity": "sha512-tySfyWHXOhd/b6JSrSOl7krngEXN3N6pi1hCAXObRu3+MZlaZOMDf/j18aoteaIF2Jpv8HMWUJUJtQKGmBJGRA==",+ "version": "3.22.0",+ "resolved": "https://registry.npmjs.org/@react-aria/utils/-/utils-3.22.0.tgz",+ "integrity": "sha512-Qi/m65GFFljXA/ayj1m5g3KZdgbZY3jacSSqD5vNUOEGiKsn4OQcsw8RfC2c0SgtLV1hLzsfvFI1OiryPlGCcw==","dependencies": {- "@react-aria/ssr": "^3.8.0",- "@react-stately/utils": "^3.8.0",- "@react-types/shared": "^3.21.0",+ "@react-aria/ssr": "^3.9.0",+ "@react-stately/utils": "^3.9.0",+ "@react-types/shared": "^3.22.0","@swc/helpers": "^0.5.0","clsx": "^1.1.1"},@@ -4434,16 +4450,29 @@}},"node_modules/@react-stately/datepicker": {- "version": "3.8.0",- "resolved": "https://registry.npmjs.org/@react-stately/datepicker/-/datepicker-3.8.0.tgz",- "integrity": "sha512-6YDSmkrRafYCWhRHks8Z2tZavM1rqSOy8GY8VYjYMCVTFpRuhPK9TQaFv2BdzZL/vJ6OGThxqoglcEwywZVq2g==",+ "version": "3.9.0",+ "resolved": "https://registry.npmjs.org/@react-stately/datepicker/-/datepicker-3.9.0.tgz",+ "integrity": "sha512-p6BuxPbDxjIgBZmskdv2dR6XIdPEftCjS7kYe/+iLZxfz1vYiDqpJVb3ascLyBjl84bDDyr4z2vWcKhdDwyhEA==","dependencies": {"@internationalized/date": "^3.5.0","@internationalized/string": "^3.1.1",- "@react-stately/overlays": "^3.6.3",- "@react-stately/utils": "^3.8.0",- "@react-types/datepicker": "^3.6.1",- "@react-types/shared": "^3.21.0",+ "@react-stately/form": "^3.0.0",+ "@react-stately/overlays": "^3.6.4",+ "@react-stately/utils": "^3.9.0",+ "@react-types/datepicker": "^3.7.0",+ "@react-types/shared": "^3.22.0",+ "@swc/helpers": "^0.5.0"+ },+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0"+ }+ },+ "node_modules/@react-stately/form": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/@react-stately/form/-/form-3.0.0.tgz",+ "integrity": "sha512-C8wkfFmtx1escizibhdka5JvTy9/Vp173CS9cakjvWTmnjYYC1nOlzwp7BsYWTgerCFbRY/BU/Cf/bJDxPiUKQ==",+ "dependencies": {+ "@react-types/shared": "^3.22.0","@swc/helpers": "^0.5.0"},"peerDependencies": {@@ -4451,12 +4480,12 @@}},"node_modules/@react-stately/overlays": {- "version": "3.6.3",- "resolved": "https://registry.npmjs.org/@react-stately/overlays/-/overlays-3.6.3.tgz",- "integrity": "sha512-K3eIiYAdAGTepYqNf2pVb+lPqLoVudXwmxPhyOSZXzjgpynD6tR3E9QfWQtkMazBuU73PnNX7zkH4l87r2AmTg==",+ "version": "3.6.4",+ "resolved": "https://registry.npmjs.org/@react-stately/overlays/-/overlays-3.6.4.tgz",+ "integrity": "sha512-tHEaoAGpE9dSnsskqLPVKum59yGteoSqsniTopodM+miQozbpPlSjdiQnzGLroy5Afx5OZYClE616muNHUILXA==","dependencies": {- "@react-stately/utils": "^3.8.0",- "@react-types/overlays": "^3.8.3",+ "@react-stately/utils": "^3.9.0",+ "@react-types/overlays": "^3.8.4","@swc/helpers": "^0.5.0"},"peerDependencies": {@@ -4478,9 +4507,9 @@}},"node_modules/@react-stately/utils": {- "version": "3.8.0",- "resolved": "https://registry.npmjs.org/@react-stately/utils/-/utils-3.8.0.tgz",- "integrity": "sha512-wCIoFDbt/uwNkWIBF+xV+21k8Z8Sj5qGO3uptTcVmjYcZngOaGGyB4NkiuZhmhG70Pkv+yVrRwoC1+4oav9cCg==",+ "version": "3.9.0",+ "resolved": "https://registry.npmjs.org/@react-stately/utils/-/utils-3.9.0.tgz",+ "integrity": "sha512-yPKFY1F88HxuZ15BG2qwAYxtpE4HnIU0Ofi4CuBE0xC6I8mwo4OQjDzi+DZjxQngM9D6AeTTD6F1V8gkozA0Gw==","dependencies": {"@swc/helpers": "^0.5.0"},@@ -4489,23 +4518,23 @@}},"node_modules/@react-types/button": {- "version": "3.9.0",- "resolved": "https://registry.npmjs.org/@react-types/button/-/button-3.9.0.tgz",- "integrity": "sha512-YhbchUDB7yL88ZFA0Zqod6qOMdzCLD5yVRmhWymk0yNLvB7EB1XX4c5sRANalfZSFP0RpCTlkjB05Hzp4+xOYg==",+ "version": "3.9.1",+ "resolved": "https://registry.npmjs.org/@react-types/button/-/button-3.9.1.tgz",+ "integrity": "sha512-bf9iTar3PtqnyV9rA+wyFyrskZKhwmOuOd/ifYIjPs56YNVXWH5Wfqj6Dx3xdFBgtKx8mEVQxVhoX+WkHX+rtw==","dependencies": {- "@react-types/shared": "^3.21.0"+ "@react-types/shared": "^3.22.0"},"peerDependencies": {"react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0"}},"node_modules/@react-types/calendar": {- "version": "3.4.1",- "resolved": "https://registry.npmjs.org/@react-types/calendar/-/calendar-3.4.1.tgz",- "integrity": "sha512-tiCkHi6IQtYcVoAESG79eUBWDXoo8NImo+Mj8WAWpo1lOA3SV1W2PpeXkoRNqtloilQ0aYcmsaJJUhciQG4ndg==",+ "version": "3.4.2",+ "resolved": "https://registry.npmjs.org/@react-types/calendar/-/calendar-3.4.2.tgz",+ "integrity": "sha512-tCZ21un/8OAhpNtmSXDkOVvS5Pzp+y/JwNr6VGFi8HBC5F/c8SzuwV0jKN8ymsZSWbDQ68xXGNWxFaG43Bw8Pg==","dependencies": {"@internationalized/date": "^3.5.0",- "@react-types/shared": "^3.21.0"+ "@react-types/shared": "^3.22.0"},"peerDependencies": {"react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0"@@ -4523,57 +4552,46 @@}},"node_modules/@react-types/datepicker": {- "version": "3.6.1",- "resolved": "https://registry.npmjs.org/@react-types/datepicker/-/datepicker-3.6.1.tgz",- "integrity": "sha512-/M+0e9hL9w98f5k4EoxeH2UfPsUPoS6fvmFsmwUZJcDiw7wP510XngnDLy9GOHj9xgqagZ20S79cxcEuTq7U6g==",+ "version": "3.7.0",+ "resolved": "https://registry.npmjs.org/@react-types/datepicker/-/datepicker-3.7.0.tgz",+ "integrity": "sha512-Uh+p6pZpMFc5ZBOns5TXCBbUvJp1KVROLBn2gk5dMEFVq78Qs1VFuAt4lwr9gQBOJrX5I/l65pRTwwWwAKxYtQ==","dependencies": {"@internationalized/date": "^3.5.0",- "@react-types/calendar": "^3.4.1",- "@react-types/overlays": "^3.8.3",- "@react-types/shared": "^3.21.0"+ "@react-types/calendar": "^3.4.2",+ "@react-types/overlays": "^3.8.4",+ "@react-types/shared": "^3.22.0"},"peerDependencies": {"react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0"}},"node_modules/@react-types/dialog": {- "version": "3.5.6",- "resolved": "https://registry.npmjs.org/@react-types/dialog/-/dialog-3.5.6.tgz",- "integrity": "sha512-lwwaAgoi4xe4eEJxBns+cBIRstIPTKWWddMkp51r7Teeh2uKs1Wki7N+Acb9CfT6JQTQDqtVJm6K76rcqNBVwg==",+ "version": "3.5.7",+ "resolved": "https://registry.npmjs.org/@react-types/dialog/-/dialog-3.5.7.tgz",+ "integrity": "sha512-geYoqAyQaTLG43AaXdMUVqZXYgkSifrD9cF7lR2kPAT0uGFv0YREi6ieU+aui8XJ83EW0xcxP+EPWd2YkN4D4w==","dependencies": {- "@react-types/overlays": "^3.8.3",- "@react-types/shared": "^3.21.0"- },- "peerDependencies": {- "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0"- }- },- "node_modules/@react-types/label": {- "version": "3.8.1",- "resolved": "https://registry.npmjs.org/@react-types/label/-/label-3.8.1.tgz",- "integrity": "sha512-fA6zMTF2TmfU7H8JBJi0pNd8t5Ak4gO+ZA3cZBysf8r3EmdAsgr3LLqFaGTnZzPH1Fux6c7ARI3qjVpyNiejZQ==",- "dependencies": {- "@react-types/shared": "^3.21.0"+ "@react-types/overlays": "^3.8.4",+ "@react-types/shared": "^3.22.0"},"peerDependencies": {"react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0"}},"node_modules/@react-types/overlays": {- "version": "3.8.3",- "resolved": "https://registry.npmjs.org/@react-types/overlays/-/overlays-3.8.3.tgz",- "integrity": "sha512-TrCG2I2+V+TD0PGi3CqfnyU5jEzcelSGgYJQvVxsl5Vv3ri7naBLIsOjF9x66tPxhINLCPUtOze/WYRAexp8aw==",+ "version": "3.8.4",+ "resolved": "https://registry.npmjs.org/@react-types/overlays/-/overlays-3.8.4.tgz",+ "integrity": "sha512-pfgNlQnbF6RB/R2oSxyqAP3Uzz0xE/k5q4n5gUeCDNLjY5qxFHGE8xniZZ503nZYw6VBa9XMN1efDOKQyeiO0w==","dependencies": {- "@react-types/shared": "^3.21.0"+ "@react-types/shared": "^3.22.0"},"peerDependencies": {"react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0"}},"node_modules/@react-types/shared": {- "version": "3.21.0",- "resolved": "https://registry.npmjs.org/@react-types/shared/-/shared-3.21.0.tgz",- "integrity": "sha512-wJA2cUF8dP4LkuNUt9Vh2kkfiQb2NLnV2pPXxVnKJZ7d4x2/7VPccN+LYPnH8m0X3+rt50cxWuPKQmjxSsCFOg==",+ "version": "3.22.0",+ "resolved": "https://registry.npmjs.org/@react-types/shared/-/shared-3.22.0.tgz",+ "integrity": "sha512-yVOekZWbtSmmiThGEIARbBpnmUIuePFlLyctjvCbgJgGhz8JnEJOipLQ/a4anaWfzAgzSceQP8j/K+VOOePleA==","peerDependencies": {"react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0"}@@ -26604,9 +26622,9 @@"@internationalized/date": "^3.3.0","@react-aria/button": "^3.8.0","@react-aria/calendar": "^3.4.0",- "@react-aria/datepicker": "^3.5.0",+ "@react-aria/datepicker": "^3.9.0","@react-stately/calendar": "^3.3.0",- "@react-stately/datepicker": "^3.5.0",+ "@react-stately/datepicker": "^3.9.0","@react-types/button": "^3.7.3","@react-types/calendar": "^3.3.0","@react-types/datepicker": "^3.4.0",diff --git a/packages/database/SCHEMA.md b/packages/database/SCHEMA.mdindex f5e6e873f9..b71d0f77eb 100644--- a/packages/database/SCHEMA.md+++ b/packages/database/SCHEMA.md@@ -4454,7 +4454,7 @@ CREATE TABLE "purchaseOrderLine" ("shelfId" TEXT,"setupPrice" NUMERIC(9,2),"receivedComplete" BOOLEAN NOT NULL DEFAULT FALSE,- "invoiceComplete" BOOLEAN NOT NULL DEFAULT FALSE,+ "invoicedComplete" BOOLEAN NOT NULL DEFAULT FALSE,"requiresInspection" BOOLEAN NOT NULL DEFAULT FALSE,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),"createdBy" TEXT NOT NULL,@@ -4790,9 +4790,14 @@ FOR DELETE USING (```sqlALTER TABLE "purchaseOrder" ENABLE ROW LEVEL SECURITY;-CREATE POLICY "Employees with purchasing_view can view purchase orders" ON "purchaseOrder"+CREATE POLICY "Employees with purchasing_view, inventory_view, or invoicing_view can view purchase orders" ON "purchaseOrder"FOR SELECT- USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (+ (+ coalesce(get_my_claim('purchasing_view')::boolean, false) = true OR+ coalesce(get_my_claim('inventory_view')::boolean, false) = true OR+ coalesce(get_my_claim('invoicing_view')::boolean, false) = true+ ) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Suppliers with purchasing_view can their own purchase orders" ON "purchaseOrder"FOR SELECT@@ -5295,8 +5300,7 @@ CREATE POLICY "Employees with accounting_create can insert journals" ON "journalCREATE TYPE "journalLineDocumentType" AS ENUM (- 'Quote',- 'Order',+ 'Receipt','Invoice','Credit Memo','Blanket Order',@@ -5309,9 +5313,12 @@ CREATE TABLE "journalLine" ("accountNumber" TEXT NOT NULL,"description" TEXT,"amount" NUMERIC(19, 4) NOT NULL,+ "quantity" NUMERIC(12, 4) NOT NULL DEFAULT 1,"documentType" "journalLineDocumentType","documentId" TEXT,"externalDocumentId" TEXT,+ "reference" TEXT,+ "accrual" BOOLEAN NOT NULL DEFAULT false,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),CONSTRAINT "journalLine_pkey" PRIMARY KEY ("id"),@@ -5380,7 +5387,7 @@ CREATE TYPE "partLedgerDocumentType" AS ENUM ('Direct Transfer');-CREATE TABLE "valueLedger" (+CREATE TABLE "costLedger" ("id" TEXT NOT NULL DEFAULT xid(),"entryNumber" SERIAL,"postingDate" DATE NOT NULL DEFAULT CURRENT_DATE,@@ -5390,36 +5397,36 @@ CREATE TABLE "valueLedger" ("documentType" "partLedgerDocumentType","documentId" TEXT,"externalDocumentId" TEXT,- "costAmountActual" NUMERIC(19, 4) NOT NULL DEFAULT 0,- "costAmountExpected" NUMERIC(19, 4) NOT NULL DEFAULT 0,- "actualCostPostedToGl" NUMERIC(19, 4) NOT NULL DEFAULT 0,- "expectedCostPostedToGl" NUMERIC(19, 4) NOT NULL DEFAULT 0,+ "partId" TEXT,+ "quantity" NUMERIC(12, 4) NOT NULL DEFAULT 0,+ "cost" NUMERIC(19, 4) NOT NULL DEFAULT 0,+ "costPostedToGL" NUMERIC(19, 4) NOT NULL DEFAULT 0,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),- CONSTRAINT "valueLedger_pkey" PRIMARY KEY ("id")+ CONSTRAINT "costLedger_pkey" PRIMARY KEY ("id"));-ALTER TABLE "valueLedger" ENABLE ROW LEVEL SECURITY;+ALTER TABLE "costLedger" ENABLE ROW LEVEL SECURITY;-CREATE POLICY "Employees with accounting_view can view the value ledger" ON "valueLedger"+CREATE POLICY "Employees with accounting_view can view the value ledger" ON "costLedger"FOR SELECTUSING (coalesce(get_my_claim('accounting_view')::boolean, false) = true AND(get_my_claim('role'::text)) = '"employee"'::jsonb);-CREATE TABLE "valueLedgerJournalLineRelation" (- "valueLedgerId" TEXT NOT NULL,+CREATE TABLE "costLedgerJournalLineRelation" (+ "costLedgerId" TEXT NOT NULL,"journalLineId" TEXT NOT NULL,- CONSTRAINT "valueLedgerJournalLineRelation_pkey" PRIMARY KEY ("valueLedgerId", "journalLineId"),- CONSTRAINT "valueLedgerJournalLineRelation_valueLedgerId_fkey" FOREIGN KEY ("valueLedgerId") REFERENCES "valueLedger"("id"),- CONSTRAINT "valueLedgerJournalLineRelation_journalLineId_fkey" FOREIGN KEY ("journalLineId") REFERENCES "journalLine"("id")+ CONSTRAINT "costLedgerJournalLineRelation_pkey" PRIMARY KEY ("costLedgerId", "journalLineId"),+ CONSTRAINT "costLedgerJournalLineRelation_costLedgerId_fkey" FOREIGN KEY ("costLedgerId") REFERENCES "costLedger"("id"),+ CONSTRAINT "costLedgerJournalLineRelation_journalLineId_fkey" FOREIGN KEY ("journalLineId") REFERENCES "journalLine"("id"));-ALTER TABLE "valueLedgerJournalLineRelation" ENABLE ROW LEVEL SECURITY;+ALTER TABLE "costLedgerJournalLineRelation" ENABLE ROW LEVEL SECURITY;-CREATE POLICY "Employees with accounting_view can view the value ledger/general ledger relations" ON "valueLedgerJournalLineRelation"+CREATE POLICY "Employees with accounting_view can view the value ledger/general ledger relations" ON "costLedgerJournalLineRelation"FOR SELECTUSING (coalesce(get_my_claim('accounting_view')::boolean, false) = true AND@@ -5458,24 +5465,6 @@ CREATE POLICY "Certain employees can view the parts ledger" ON "partLedger")AND (get_my_claim('role'::text)) = '"employee"'::jsonb);--CREATE TABLE "partLedgerValueLedgerRelation" (- "partLedgerId" TEXT NOT NULL,- "valueLedgerId" TEXT NOT NULL,-- CONSTRAINT "partLedgerValueLedgerRelation_pkey" PRIMARY KEY ("partLedgerId", "valueLedgerId"),- CONSTRAINT "partLedgerValueLedgerRelation_partLedgerId_fkey" FOREIGN KEY ("partLedgerId") REFERENCES "partLedger"("id"),- CONSTRAINT "partLedgerValueLedgerRelation_valueLedgerId_fkey" FOREIGN KEY ("valueLedgerId") REFERENCES "valueLedger"("id")-);--ALTER TABLE "partLedgerValueLedgerRelation" ENABLE ROW LEVEL SECURITY;--CREATE POLICY "Employees with accounting_view can view the part ledger/value ledger relations" ON "partLedgerValueLedgerRelation"- FOR SELECT- USING (- coalesce(get_my_claim('accounting_view')::boolean, false) = true AND- (get_my_claim('role'::text)) = '"employee"'::jsonb- );CREATE TYPE "supplierLedgerDocumentType" AS ENUM ('Payment',@@ -5529,6 +5518,8 @@ $$;++```@@ -5635,7 +5626,7 @@ CREATE TABLE "receiptLine" ("updatedBy" TEXT,CONSTRAINT "receiptLine_pkey" PRIMARY KEY ("id"),- CONSTRAINT "receiptLine_receiptId_fkey" FOREIGN KEY ("receiptId") REFERENCES "receipt" ("receiptId") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "receiptLine_receiptId_fkey" FOREIGN KEY ("receiptId") REFERENCES "receipt" ("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "receiptLine_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part" ("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "receiptLine_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location" ("id") ON DELETE SET NULL ON UPDATE CASCADE,CONSTRAINT "receiptLine_shelfId_fkey" FOREIGN KEY ("shelfId", "locationId") REFERENCES "shelf" ("id", "locationId") ON DELETE SET NULL ON UPDATE CASCADE,@@ -5678,15 +5669,7 @@ CREATE POLICY "Employees with inventory_delete can delete receipt lines" ON "recAND (get_my_claim('role'::text)) = '"employee"'::jsonb);-CREATE OR REPLACE VIEW "receiptQuantityReceivedByLine" AS- SELECT- r."sourceDocumentId",- l."lineId",- SUM(l."receivedQuantity") AS "receivedQuantity"- FROM "receipt" r- INNER JOIN "receiptLine" l- ON l."receiptId" = r."receiptId"- GROUP BY r."sourceDocumentId", l."lineId";+@@ -5755,6 +5738,7 @@ CREATE TABLE "accountDefault" ("workInProgressAccount" TEXT NOT NULL,"receivablesAccount" TEXT NOT NULL,"inventoryShippedNotInvoicedAccount" TEXT NOT NULL,+ "inventoryInvoicedNotReceivedAccount" TEXT NOT NULL,"bankCashAccount" TEXT NOT NULL,"bankLocalCurrencyAccount" TEXT NOT NULL,"bankForeignCurrencyAccount" TEXT NOT NULL,@@ -5846,6 +5830,7 @@ CREATE TABLE "postingGroupInventory" ("inventoryAccount" TEXT NOT NULL,"inventoryInterimAccrualAccount" TEXT NOT NULL,"inventoryReceivedNotInvoicedAccount" TEXT NOT NULL,+ "inventoryInvoicedNotReceivedAccount" TEXT NOT NULL,"inventoryShippedNotInvoicedAccount" TEXT NOT NULL,"workInProgressAccount" TEXT NOT NULL,"directCostAppliedAccount" TEXT NOT NULL,@@ -5865,6 +5850,7 @@ CREATE TABLE "postingGroupInventory" (CONSTRAINT "postingGroupInventory_inventoryAccount_fkey" FOREIGN KEY ("inventoryAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,CONSTRAINT "postingGroupInventory_inventoryInterimAccrualAccount_fkey" FOREIGN KEY ("inventoryInterimAccrualAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,CONSTRAINT "postingGroupInventory_inventoryReceivedNotInvoicedAccount_fkey" FOREIGN KEY ("inventoryReceivedNotInvoicedAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "postingGroupInventory_inventoryInvoicedNotReceivedAccount_fkey" FOREIGN KEY ("inventoryInvoicedNotReceivedAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,CONSTRAINT "postingGroupInventory_inventoryShippedNotInvoicedAccount_fkey" FOREIGN KEY ("inventoryShippedNotInvoicedAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,CONSTRAINT "postingGroupInventory_workInProgressAccount_fkey" FOREIGN KEY ("workInProgressAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,CONSTRAINT "postingGroupInventory_directCostAppliedAccount_fkey" FOREIGN KEY ("directCostAppliedAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,@@ -5900,6 +5886,7 @@ CREATE TABLE "postingGroupPurchasing" ("id" TEXT NOT NULL DEFAULT xid(),"supplierTypeId" TEXT,"partGroupId" TEXT,+ "payablesAccount" TEXT NOT NULL,"purchaseAccount" TEXT NOT NULL,"purchaseDiscountAccount" TEXT NOT NULL,"purchaseCreditAccount" TEXT NOT NULL,@@ -5911,6 +5898,7 @@ CREATE TABLE "postingGroupPurchasing" (CONSTRAINT "postingGroupPurchasing_id_supplierTypeId_partGroupId_key" UNIQUE ("supplierTypeId", "partGroupId"),CONSTRAINT "postingGroupPurchasing_partGroupId_fkey" FOREIGN KEY ("partGroupId") REFERENCES "partGroup" ("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "postingGroupPurchasing_supplierTypeId_fkey" FOREIGN KEY ("supplierTypeId") REFERENCES "supplierType" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "postingGroupPurchasing_payablesAccount_fkey" FOREIGN KEY ("payablesAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,CONSTRAINT "postingGroupPurchasing_purchaseAccount_fkey" FOREIGN KEY ("purchaseAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,CONSTRAINT "postingGroupPurchasing_purchaseDiscountAccount_fkey" FOREIGN KEY ("purchaseDiscountAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,CONSTRAINT "postingGroupPurchasing_purchaseCreditAccount_fkey" FOREIGN KEY ("purchaseCreditAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,@@ -5941,6 +5929,7 @@ CREATE TABLE "postingGroupSales" ("id" TEXT NOT NULL DEFAULT xid(),"customerTypeId" TEXT,"partGroupId" TEXT,+ "receivablesAccount" TEXT NOT NULL,"salesAccount" TEXT NOT NULL,"salesDiscountAccount" TEXT NOT NULL,"salesCreditAccount" TEXT NOT NULL,@@ -5952,6 +5941,7 @@ CREATE TABLE "postingGroupSales" (CONSTRAINT "postingGroupSales_id_customerTypeId_partGroupId_key" UNIQUE ("customerTypeId", "partGroupId"),CONSTRAINT "postingGroupSales_partGroupId_fkey" FOREIGN KEY ("partGroupId") REFERENCES "partGroup" ("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "postingGroupSales_customerTypeId_fkey" FOREIGN KEY ("customerTypeId") REFERENCES "customerType" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "postingGroupSales_receivablesAccount_fkey" FOREIGN KEY ("receivablesAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,CONSTRAINT "postingGroupSales_salesAccount_fkey" FOREIGN KEY ("salesAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,CONSTRAINT "postingGroupSales_salesDiscountAccount_fkey" FOREIGN KEY ("salesDiscountAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,CONSTRAINT "postingGroupSales_salesCreditAccount_fkey" FOREIGN KEY ("salesCreditAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,@@ -5993,6 +5983,7 @@ BEGIN"inventoryAccount","inventoryInterimAccrualAccount","inventoryReceivedNotInvoicedAccount",+ "inventoryInvoicedNotReceivedAccount","inventoryShippedNotInvoicedAccount","workInProgressAccount","directCostAppliedAccount",@@ -6010,6 +6001,7 @@ BEGINaccount_defaults."inventoryAccount",account_defaults."inventoryInterimAccrualAccount",account_defaults."inventoryReceivedNotInvoicedAccount",+ account_defaults."inventoryInvoicedNotReceivedAccount",account_defaults."inventoryShippedNotInvoicedAccount",account_defaults."workInProgressAccount",account_defaults."directCostAppliedAccount",@@ -6031,6 +6023,7 @@ BEGIN"inventoryAccount","inventoryInterimAccrualAccount","inventoryReceivedNotInvoicedAccount",+ "inventoryInvoicedNotReceivedAccount","inventoryShippedNotInvoicedAccount","workInProgressAccount","directCostAppliedAccount",@@ -6048,6 +6041,7 @@ BEGINaccount_defaults."inventoryAccount",account_defaults."inventoryInterimAccrualAccount",account_defaults."inventoryReceivedNotInvoicedAccount",+ account_defaults."inventoryInvoicedNotReceivedAccount",account_defaults."inventoryShippedNotInvoicedAccount",account_defaults."workInProgressAccount",account_defaults."directCostAppliedAccount",@@ -6082,6 +6076,7 @@ BEGININSERT INTO "postingGroupSales" ("partGroupId","customerTypeId",+ "receivablesAccount","salesAccount","salesDiscountAccount","salesCreditAccount",@@ -6091,6 +6086,7 @@ BEGIN) VALUES (new."id",rec."id",+ account_defaults."receivablesAccount",account_defaults."salesAccount",account_defaults."salesDiscountAccount",account_defaults."receivablesAccount",@@ -6104,6 +6100,7 @@ BEGININSERT INTO "postingGroupSales" ("partGroupId","customerTypeId",+ "receivablesAccount","salesAccount","salesDiscountAccount","salesCreditAccount",@@ -6113,6 +6110,7 @@ BEGIN) VALUES (new."id",NULL,+ account_defaults."receivablesAccount",account_defaults."salesAccount",account_defaults."salesDiscountAccount",account_defaults."receivablesAccount",@@ -6126,6 +6124,7 @@ BEGININSERT INTO "postingGroupPurchasing" ("partGroupId","supplierTypeId",+ "payablesAccount","purchaseAccount","purchaseDiscountAccount","purchaseCreditAccount",@@ -6135,6 +6134,7 @@ BEGIN) VALUES (new."id",rec."id",+ account_defaults."payablesAccount",account_defaults."purchaseAccount",account_defaults."purchaseAccount",account_defaults."payablesAccount",@@ -6148,6 +6148,7 @@ BEGININSERT INTO "postingGroupPurchasing" ("partGroupId","supplierTypeId",+ "payablesAccount","purchaseAccount","purchaseDiscountAccount","purchaseCreditAccount",@@ -6157,6 +6158,7 @@ BEGIN) VALUES (new."id",NULL,+ account_defaults."payablesAccount",account_defaults."purchaseAccount",account_defaults."purchaseAccount",account_defaults."payablesAccount",@@ -6174,6 +6176,7 @@ BEGIN"inventoryAccount","inventoryInterimAccrualAccount","inventoryReceivedNotInvoicedAccount",+ "inventoryInvoicedNotReceivedAccount","inventoryShippedNotInvoicedAccount","workInProgressAccount","directCostAppliedAccount",@@ -6191,6 +6194,7 @@ BEGINaccount_defaults."inventoryAccount",account_defaults."inventoryInterimAccrualAccount",account_defaults."inventoryReceivedNotInvoicedAccount",+ account_defaults."inventoryInvoicedNotReceivedAccount",account_defaults."inventoryShippedNotInvoicedAccount",account_defaults."workInProgressAccount",account_defaults."directCostAppliedAccount",@@ -6212,6 +6216,7 @@ BEGIN"inventoryAccount","inventoryInterimAccrualAccount","inventoryReceivedNotInvoicedAccount",+ "inventoryInvoicedNotReceivedAccount","inventoryShippedNotInvoicedAccount","workInProgressAccount","directCostAppliedAccount",@@ -6229,6 +6234,7 @@ BEGINaccount_defaults."inventoryAccount",account_defaults."inventoryInterimAccrualAccount",account_defaults."inventoryReceivedNotInvoicedAccount",+ account_defaults."inventoryInvoicedNotReceivedAccount",account_defaults."inventoryShippedNotInvoicedAccount",account_defaults."workInProgressAccount",account_defaults."directCostAppliedAccount",@@ -6263,6 +6269,7 @@ BEGININSERT INTO "postingGroupSales" ("customerTypeId","partGroupId",+ "receivablesAccount","salesAccount","salesDiscountAccount","salesCreditAccount",@@ -6272,6 +6279,7 @@ BEGIN) VALUES (new."id",rec."id",+ account_defaults."receivablesAccount",account_defaults."salesAccount",account_defaults."salesDiscountAccount",account_defaults."salesAccount",@@ -6285,6 +6293,7 @@ BEGININSERT INTO "postingGroupSales" ("customerTypeId","partGroupId",+ "receivablesAccount","salesAccount","salesDiscountAccount","salesCreditAccount",@@ -6294,6 +6303,7 @@ BEGIN) VALUES (new."id",NULL,+ account_defaults."receivablesAccount",account_defaults."salesAccount",account_defaults."salesDiscountAccount",account_defaults."salesAccount",@@ -6324,6 +6334,7 @@ BEGININSERT INTO "postingGroupPurchasing" ("supplierTypeId","partGroupId",+ "payablesAccount","purchaseAccount","purchaseDiscountAccount","purchaseCreditAccount",@@ -6333,6 +6344,7 @@ BEGIN) VALUES (new."id",rec."id",+ account_defaults."payablesAccount",account_defaults."purchaseAccount",account_defaults."purchaseAccount",account_defaults."purchaseAccount",@@ -6346,6 +6358,7 @@ BEGININSERT INTO "postingGroupPurchasing" ("supplierTypeId","partGroupId",+ "payablesAccount","purchaseAccount","purchaseDiscountAccount","purchaseCreditAccount",@@ -6355,6 +6368,7 @@ BEGIN) VALUES (new."id",NULL,+ account_defaults."payablesAccount",account_defaults."purchaseAccount",account_defaults."purchaseAccount",account_defaults."purchaseAccount",@@ -6471,6 +6485,7 @@ CREATE OR REPLACE VIEW "partQuantities" AS```sqlCREATE TYPE "purchaseInvoiceStatus" AS ENUM ('Draft',+ 'Pending','Submitted','Return','Debit Note Issued',@@ -6492,6 +6507,7 @@ CREATE TABLE "purchaseInvoice" ("paymentTermId" TEXT,"currencyCode" TEXT NOT NULL,"exchangeRate" NUMERIC(10, 4) NOT NULL DEFAULT 1,+ "postingDate" DATE,"dateIssued" DATE,"dateDue" DATE,"datePaid" DATE,@@ -6522,6 +6538,8 @@ CREATE INDEX "purchaseInvoice_supplierId_idx" ON "purchaseInvoice" ("supplierId"CREATE INDEX "purchaseInvoice_dateDue_idx" ON "purchaseInvoice" ("dateDue");CREATE INDEX "purchaseInvoice_datePaid_idx" ON "purchaseInvoice" ("datePaid");+ALTER publication supabase_realtime ADD TABLE "purchaseInvoice";+ALTER TABLE "purchaseInvoice" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with invoicing_view can view AP invoices" ON "purchaseInvoice"@@ -6587,6 +6605,7 @@ CREATE TABLE "purchaseInvoiceLine" ("purchaseOrderId" TEXT,"purchaseOrderLineId" TEXT,"partId" TEXT,+ "locationId" TEXT,"accountNumber" TEXT,"assetId" TEXT,"description" TEXT,@@ -6605,6 +6624,7 @@ CREATE TABLE "purchaseInvoiceLine" (CONSTRAINT "purchaseInvoiceLines_purchaseOrderId_fkey" FOREIGN KEY ("purchaseOrderId") REFERENCES "purchaseOrder" ("id") ON UPDATE CASCADE ON DELETE RESTRICT,CONSTRAINT "purchaseInvoiceLines_purchaseOrderLineId_fkey" FOREIGN KEY ("purchaseOrderLineId") REFERENCES "purchaseOrderLine" ("id") ON UPDATE CASCADE ON DELETE RESTRICT,CONSTRAINT "purchaseInvoiceLines_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part" ("id") ON UPDATE CASCADE ON DELETE RESTRICT,+ CONSTRAINT "purchaseInvoiceLines_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location" ("id") ON UPDATE CASCADE ON DELETE RESTRICT,CONSTRAINT "purchaseInvoiceLines_accountNumber_fkey" FOREIGN KEY ("accountNumber") REFERENCES "account" ("number") ON UPDATE CASCADE ON DELETE RESTRICT,-- CONSTRAINT "purchaseInvoiceLines_assetId_fkey" FOREIGN KEY ("assetId") REFERENCES "fixedAsset" ("id") ON UPDATE CASCADE ON DELETE RESTRICT,CONSTRAINT "purchaseInvoiceLines_currencyCode_fkey" FOREIGN KEY ("currencyCode") REFERENCES "currency" ("code") ON UPDATE CASCADE ON DELETE RESTRICT,@@ -6779,6 +6799,7 @@ CREATE OR REPLACE VIEW "purchaseInvoices" ASpi."invoiceSupplierId",pi."invoiceSupplierLocationId",pi."invoiceSupplierContactId",+ pi."postingDate",pi."dateIssued",pi."dateDue",pi."datePaid",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex cacbd1b082..762da4ba1d 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -270,6 +270,7 @@ export interface Database {inventoryAccount: stringinventoryAdjustmentVarianceAccount: stringinventoryInterimAccrualAccount: string+ inventoryInvoicedNotReceivedAccount: stringinventoryReceivedNotInvoicedAccount: stringinventoryShippedNotInvoicedAccount: stringmaintenanceAccount: string@@ -312,6 +313,7 @@ export interface Database {inventoryAccount: stringinventoryAdjustmentVarianceAccount: stringinventoryInterimAccrualAccount: string+ inventoryInvoicedNotReceivedAccount: stringinventoryReceivedNotInvoicedAccount: stringinventoryShippedNotInvoicedAccount: stringmaintenanceAccount: string@@ -354,6 +356,7 @@ export interface Database {inventoryAccount?: stringinventoryAdjustmentVarianceAccount?: stringinventoryInterimAccrualAccount?: string+ inventoryInvoicedNotReceivedAccount?: stringinventoryReceivedNotInvoicedAccount?: stringinventoryShippedNotInvoicedAccount?: stringmaintenanceAccount?: string@@ -1253,6 +1256,91 @@ export interface Database {}]}+ costLedger: {+ Row: {+ adjustment: boolean+ cost: number+ costLedgerType: Database["public"]["Enums"]["costLedgerType"]+ costPostedToGL: number+ createdAt: string+ documentId: string | null+ documentType:+ | Database["public"]["Enums"]["partLedgerDocumentType"]+ | null+ entryNumber: number+ externalDocumentId: string | null+ id: string+ partId: string | null+ partLedgerType: Database["public"]["Enums"]["partLedgerType"]+ postingDate: string+ quantity: number+ }+ Insert: {+ adjustment?: boolean+ cost?: number+ costLedgerType: Database["public"]["Enums"]["costLedgerType"]+ costPostedToGL?: number+ createdAt?: string+ documentId?: string | null+ documentType?:+ | Database["public"]["Enums"]["partLedgerDocumentType"]+ | null+ entryNumber?: number+ externalDocumentId?: string | null+ id?: string+ partId?: string | null+ partLedgerType: Database["public"]["Enums"]["partLedgerType"]+ postingDate?: string+ quantity?: number+ }+ Update: {+ adjustment?: boolean+ cost?: number+ costLedgerType?: Database["public"]["Enums"]["costLedgerType"]+ costPostedToGL?: number+ createdAt?: string+ documentId?: string | null+ documentType?:+ | Database["public"]["Enums"]["partLedgerDocumentType"]+ | null+ entryNumber?: number+ externalDocumentId?: string | null+ id?: string+ partId?: string | null+ partLedgerType?: Database["public"]["Enums"]["partLedgerType"]+ postingDate?: string+ quantity?: number+ }+ Relationships: []+ }+ costLedgerJournalLineRelation: {+ Row: {+ costLedgerId: string+ journalLineId: string+ }+ Insert: {+ costLedgerId: string+ journalLineId: string+ }+ Update: {+ costLedgerId?: string+ journalLineId?: string+ }+ Relationships: [+ {+ foreignKeyName: "costLedgerJournalLineRelation_costLedgerId_fkey"+ columns: ["costLedgerId"]+ referencedRelation: "costLedger"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "costLedgerJournalLineRelation_journalLineId_fkey"+ columns: ["journalLineId"]+ referencedRelation: "journalLine"+ referencedColumns: ["id"]+ }+ ]+ }country: {Row: {code: string@@ -2808,6 +2896,7 @@ export interface Database {journalLine: {Row: {accountNumber: string+ accrual: booleanamount: numbercreatedAt: stringdescription: string | null@@ -2818,9 +2907,12 @@ export interface Database {externalDocumentId: string | nullid: stringjournalId: number+ quantity: number+ reference: string | null}Insert: {accountNumber: string+ accrual?: booleanamount: numbercreatedAt?: stringdescription?: string | null@@ -2831,9 +2923,12 @@ export interface Database {externalDocumentId?: string | nullid?: stringjournalId: number+ quantity?: number+ reference?: string | null}Update: {accountNumber?: string+ accrual?: booleanamount?: numbercreatedAt?: stringdescription?: string | null@@ -2844,6 +2939,8 @@ export interface Database {externalDocumentId?: string | nullid?: stringjournalId?: number+ quantity?: number+ reference?: string | null}Relationships: [{@@ -3446,34 +3543,6 @@ export interface Database {}]}- partLedgerValueLedgerRelation: {- Row: {- partLedgerId: string- valueLedgerId: string- }- Insert: {- partLedgerId: string- valueLedgerId: string- }- Update: {- partLedgerId?: string- valueLedgerId?: string- }- Relationships: [- {- foreignKeyName: "partLedgerValueLedgerRelation_partLedgerId_fkey"- columns: ["partLedgerId"]- referencedRelation: "partLedger"- referencedColumns: ["id"]- },- {- foreignKeyName: "partLedgerValueLedgerRelation_valueLedgerId_fkey"- columns: ["valueLedgerId"]- referencedRelation: "valueLedger"- referencedColumns: ["id"]- }- ]- }partner: {Row: {active: boolean@@ -4141,6 +4210,7 @@ export interface Database {inventoryAccount: stringinventoryAdjustmentVarianceAccount: stringinventoryInterimAccrualAccount: string+ inventoryInvoicedNotReceivedAccount: stringinventoryReceivedNotInvoicedAccount: stringinventoryShippedNotInvoicedAccount: stringlocationId: string | null@@ -4160,6 +4230,7 @@ export interface Database {inventoryAccount: stringinventoryAdjustmentVarianceAccount: stringinventoryInterimAccrualAccount: string+ inventoryInvoicedNotReceivedAccount: stringinventoryReceivedNotInvoicedAccount: stringinventoryShippedNotInvoicedAccount: stringlocationId?: string | null@@ -4179,6 +4250,7 @@ export interface Database {inventoryAccount?: stringinventoryAdjustmentVarianceAccount?: stringinventoryInterimAccrualAccount?: string+ inventoryInvoicedNotReceivedAccount?: stringinventoryReceivedNotInvoicedAccount?: stringinventoryShippedNotInvoicedAccount?: stringlocationId?: string | null@@ -4263,6 +4335,18 @@ export interface Database {referencedRelation: "accounts"referencedColumns: ["number"]},+ {+ foreignKeyName: "postingGroupInventory_inventoryInvoicedNotReceivedAccount_fkey"+ columns: ["inventoryInvoicedNotReceivedAccount"]+ referencedRelation: "account"+ referencedColumns: ["number"]+ },+ {+ foreignKeyName: "postingGroupInventory_inventoryInvoicedNotReceivedAccount_fkey"+ columns: ["inventoryInvoicedNotReceivedAccount"]+ referencedRelation: "accounts"+ referencedColumns: ["number"]+ },{foreignKeyName: "postingGroupInventory_inventoryReceivedNotInvoicedAccount_fkey"columns: ["inventoryReceivedNotInvoicedAccount"]@@ -4389,6 +4473,7 @@ export interface Database {Row: {id: stringpartGroupId: string | null+ payablesAccount: stringpurchaseAccount: stringpurchaseCreditAccount: stringpurchaseDiscountAccount: string@@ -4400,6 +4485,7 @@ export interface Database {Insert: {id?: stringpartGroupId?: string | null+ payablesAccount: stringpurchaseAccount: stringpurchaseCreditAccount: stringpurchaseDiscountAccount: string@@ -4411,6 +4497,7 @@ export interface Database {Update: {id?: stringpartGroupId?: string | null+ payablesAccount?: stringpurchaseAccount?: stringpurchaseCreditAccount?: stringpurchaseDiscountAccount?: string@@ -4426,6 +4513,18 @@ export interface Database {referencedRelation: "partGroup"referencedColumns: ["id"]},+ {+ foreignKeyName: "postingGroupPurchasing_payablesAccount_fkey"+ columns: ["payablesAccount"]+ referencedRelation: "account"+ referencedColumns: ["number"]+ },+ {+ foreignKeyName: "postingGroupPurchasing_payablesAccount_fkey"+ columns: ["payablesAccount"]+ referencedRelation: "accounts"+ referencedColumns: ["number"]+ },{foreignKeyName: "postingGroupPurchasing_purchaseAccount_fkey"columns: ["purchaseAccount"]@@ -4511,6 +4610,7 @@ export interface Database {customerTypeId: string | nullid: stringpartGroupId: string | null+ receivablesAccount: stringsalesAccount: stringsalesCreditAccount: stringsalesDiscountAccount: string@@ -4522,6 +4622,7 @@ export interface Database {customerTypeId?: string | nullid?: stringpartGroupId?: string | null+ receivablesAccount: stringsalesAccount: stringsalesCreditAccount: stringsalesDiscountAccount: string@@ -4533,6 +4634,7 @@ export interface Database {customerTypeId?: string | nullid?: stringpartGroupId?: string | null+ receivablesAccount?: stringsalesAccount?: stringsalesCreditAccount?: stringsalesDiscountAccount?: string@@ -4553,6 +4655,18 @@ export interface Database {referencedRelation: "partGroup"referencedColumns: ["id"]},+ {+ foreignKeyName: "postingGroupSales_receivablesAccount_fkey"+ columns: ["receivablesAccount"]+ referencedRelation: "account"+ referencedColumns: ["number"]+ },+ {+ foreignKeyName: "postingGroupSales_receivablesAccount_fkey"+ columns: ["receivablesAccount"]+ referencedRelation: "accounts"+ referencedColumns: ["number"]+ },{foreignKeyName: "postingGroupSales_salesAccount_fkey"columns: ["salesAccount"]@@ -4643,6 +4757,7 @@ export interface Database {invoiceSupplierId: string | nullinvoiceSupplierLocationId: string | nullpaymentTermId: string | null+ postingDate: string | nullstatus: Database["public"]["Enums"]["purchaseInvoiceStatus"]subtotal: numbersupplierId: string | null@@ -4668,6 +4783,7 @@ export interface Database {invoiceSupplierId?: string | nullinvoiceSupplierLocationId?: string | nullpaymentTermId?: string | null+ postingDate?: string | nullstatus?: Database["public"]["Enums"]["purchaseInvoiceStatus"]subtotal?: numbersupplierId?: string | null@@ -4693,6 +4809,7 @@ export interface Database {invoiceSupplierId?: string | nullinvoiceSupplierLocationId?: string | nullpaymentTermId?: string | null+ postingDate?: string | nullstatus?: Database["public"]["Enums"]["purchaseInvoiceStatus"]subtotal?: numbersupplierId?: string | null@@ -4826,6 +4943,7 @@ export interface Database {id: stringinvoiceId: stringinvoiceLineType: Database["public"]["Enums"]["payableLineType"]+ locationId: string | nullpartId: string | nullpurchaseOrderId: string | nullpurchaseOrderLineId: string | null@@ -4846,6 +4964,7 @@ export interface Database {id?: stringinvoiceId: stringinvoiceLineType: Database["public"]["Enums"]["payableLineType"]+ locationId?: string | nullpartId?: string | nullpurchaseOrderId?: string | nullpurchaseOrderLineId?: string | null@@ -4866,6 +4985,7 @@ export interface Database {id?: stringinvoiceId?: stringinvoiceLineType?: Database["public"]["Enums"]["payableLineType"]+ locationId?: string | nullpartId?: string | nullpurchaseOrderId?: string | nullpurchaseOrderLineId?: string | null@@ -4918,6 +5038,24 @@ export interface Database {referencedRelation: "purchaseInvoices"referencedColumns: ["id"]},+ {+ foreignKeyName: "purchaseInvoiceLines_locationId_fkey"+ columns: ["locationId"]+ referencedRelation: "location"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "purchaseInvoiceLines_locationId_fkey"+ columns: ["locationId"]+ referencedRelation: "partQuantities"+ referencedColumns: ["locationId"]+ },+ {+ foreignKeyName: "purchaseInvoiceLines_locationId_fkey"+ columns: ["locationId"]+ referencedRelation: "purchaseOrders"+ referencedColumns: ["locationId"]+ },{foreignKeyName: "purchaseInvoiceLines_partId_fkey"columns: ["partId"]@@ -5402,7 +5540,7 @@ export interface Database {createdBy: stringdescription: string | nullid: string- invoiceComplete: boolean+ invoicedComplete: booleanlocationId: string | nullpartId: string | nullpurchaseOrderId: string@@ -5428,7 +5566,7 @@ export interface Database {createdBy: stringdescription?: string | nullid?: string- invoiceComplete?: boolean+ invoicedComplete?: booleanlocationId?: string | nullpartId?: string | nullpurchaseOrderId: string@@ -5454,7 +5592,7 @@ export interface Database {createdBy?: stringdescription?: string | nullid?: string- invoiceComplete?: boolean+ invoicedComplete?: booleanlocationId?: string | nullpartId?: string | nullpurchaseOrderId?: string@@ -6096,13 +6234,13 @@ export interface Database {foreignKeyName: "receiptLine_receiptId_fkey"columns: ["receiptId"]referencedRelation: "receipt"- referencedColumns: ["receiptId"]+ referencedColumns: ["id"]},{foreignKeyName: "receiptLine_receiptId_fkey"columns: ["receiptId"]referencedRelation: "receiptsPostedNotInvoiced"- referencedColumns: ["receiptId"]+ referencedColumns: ["id"]},{foreignKeyName: "receiptLine_shelfId_fkey"@@ -7518,91 +7656,6 @@ export interface Database {}]}- valueLedger: {- Row: {- actualCostPostedToGl: number- adjustment: boolean- costAmountActual: number- costAmountExpected: number- costLedgerType: Database["public"]["Enums"]["costLedgerType"]- createdAt: string- documentId: string | null- documentType:- | Database["public"]["Enums"]["partLedgerDocumentType"]- | null- entryNumber: number- expectedCostPostedToGl: number- externalDocumentId: string | null- id: string- partLedgerType: Database["public"]["Enums"]["partLedgerType"]- postingDate: string- }- Insert: {- actualCostPostedToGl?: number- adjustment?: boolean- costAmountActual?: number- costAmountExpected?: number- costLedgerType: Database["public"]["Enums"]["costLedgerType"]- createdAt?: string- documentId?: string | null- documentType?:- | Database["public"]["Enums"]["partLedgerDocumentType"]- | null- entryNumber?: number- expectedCostPostedToGl?: number- externalDocumentId?: string | null- id?: string- partLedgerType: Database["public"]["Enums"]["partLedgerType"]- postingDate?: string- }- Update: {- actualCostPostedToGl?: number- adjustment?: boolean- costAmountActual?: number- costAmountExpected?: number- costLedgerType?: Database["public"]["Enums"]["costLedgerType"]- createdAt?: string- documentId?: string | null- documentType?:- | Database["public"]["Enums"]["partLedgerDocumentType"]- | null- entryNumber?: number- expectedCostPostedToGl?: number- externalDocumentId?: string | null- id?: string- partLedgerType?: Database["public"]["Enums"]["partLedgerType"]- postingDate?: string- }- Relationships: []- }- valueLedgerJournalLineRelation: {- Row: {- journalLineId: string- valueLedgerId: string- }- Insert: {- journalLineId: string- valueLedgerId: string- }- Update: {- journalLineId?: string- valueLedgerId?: string- }- Relationships: [- {- foreignKeyName: "valueLedgerJournalLineRelation_journalLineId_fkey"- columns: ["journalLineId"]- referencedRelation: "journalLine"- referencedColumns: ["id"]- },- {- foreignKeyName: "valueLedgerJournalLineRelation_valueLedgerId_fkey"- columns: ["valueLedgerId"]- referencedRelation: "valueLedger"- referencedColumns: ["id"]- }- ]- }warehouse: {Row: {active: boolean@@ -8275,6 +8328,7 @@ export interface Database {invoiceSupplierId: string | nullinvoiceSupplierLocationId: string | nullpaymentTermId: string | null+ postingDate: string | nullstatus: Database["public"]["Enums"]["purchaseInvoiceStatus"] | nullsubtotal: number | nullsupplierId: string | null@@ -8514,14 +8568,6 @@ export interface Database {}Relationships: []}- receiptQuantityReceivedByLine: {- Row: {- lineId: string | null- receivedQuantity: number | null- sourceDocumentId: string | null- }- Relationships: []- }receiptsPostedNotInvoiced: {Row: {estimatedCost: number | null@@ -8811,8 +8857,7 @@ export interface Database {glIncomeBalance: "Balance Sheet" | "Income Statement"glNormalBalance: "Debit" | "Credit" | "Both"journalLineDocumentType:- | "Quote"- | "Order"+ | "Receipt"| "Invoice"| "Credit Memo"| "Blanket Order"@@ -8871,6 +8916,7 @@ export interface Database {paymentTermCalculationMethod: "Net" | "End of Month" | "Day of Month"purchaseInvoiceStatus:| "Draft"+ | "Pending"| "Submitted"| "Return"| "Debit Note Issued"diff --git a/packages/database/supabase/functions/create-purchase-invoice-from-purchase-order/index.ts b/packages/database/supabase/functions/create-purchase-invoice-from-purchase-order/index.tsindex 9c5a58ea17..155ac0525e 100644--- a/packages/database/supabase/functions/create-purchase-invoice-from-purchase-order/index.ts+++ b/packages/database/supabase/functions/create-purchase-invoice-from-purchase-order/index.ts@@ -114,6 +114,7 @@ serve(async (req: Request) => {purchaseOrderId: line.purchaseOrderId,purchaseOrderLineId: line.id,partId: line.partId,+ locationId: line.locationId,accountNumber: line.accountNumber,assetId: line.assetId,description: line.description,diff --git a/packages/database/supabase/functions/lib/utils.ts b/packages/database/supabase/functions/lib/utils.tsindex 56aa76f75c..81c544d859 100644--- a/packages/database/supabase/functions/lib/utils.ts+++ b/packages/database/supabase/functions/lib/utils.ts@@ -22,3 +22,40 @@ export const interpolateSequenceDate = (value?: string | null) => {return result;};++type AccountType = "asset" | "liability" | "equity" | "revenue" | "expense";++export const credit = (accountType: AccountType, amount: number) => {+ switch (accountType) {+ case "asset":+ case "expense":+ return -amount;+ case "liability":+ case "equity":+ case "revenue":+ return amount;+ default:+ throw new Error(`Invalid account type: ${accountType}`);+ }+};++export const debit = (accountType: AccountType, amount: number) => {+ switch (accountType) {+ case "asset":+ case "expense":+ return amount;+ case "liability":+ case "equity":+ case "revenue":+ return -amount;+ default:+ throw new Error(`Invalid account type: ${accountType}`);+ }+};++export const journalReference = {+ to: {+ purchaseInvoice: (id: string) => `purchase-invoice:${id}`,+ receipt: (id: string) => `receipt:${id}`,+ },+};diff --git a/packages/database/supabase/functions/post-purchase-invoice/index.ts b/packages/database/supabase/functions/post-purchase-invoice/index.tsnew file mode 100644index 0000000000..dbc3aaab70--- /dev/null+++ b/packages/database/supabase/functions/post-purchase-invoice/index.ts@@ -0,0 +1,641 @@+import { serve } from "https://deno.land/[email protected]/http/server.ts";+import { format } from "https://deno.land/[email protected]/datetime/mod.ts";+import type { Database } from "../../../src/types.ts";+import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { corsHeaders } from "../lib/headers.ts";+import { getSupabaseServiceRole } from "../lib/supabase.ts";+import { credit, debit, journalReference } from "../lib/utils.ts";+import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";+import {+ getInventoryPostingGroup,+ getPurchasingPostingGroup,+} from "../shared/get-posting-group.ts";++const pool = getConnectionPool(1);+const db = getDatabaseClient<DB>(pool);++serve(async (req: Request) => {+ if (req.method === "OPTIONS") {+ return new Response("ok", { headers: corsHeaders });+ }++ const { invoiceId } = await req.json();+ const today = format(new Date(), "yyyy-MM-dd");++ try {+ if (!invoiceId) throw new Error("Payload is missing invoiceId");++ const client = getSupabaseServiceRole(req.headers.get("Authorization"));++ const [purchaseInvoice, purchaseInvoiceLines] = await Promise.all([+ client.from("purchaseInvoice").select("*").eq("id", invoiceId).single(),+ client.from("purchaseInvoiceLine").select("*").eq("invoiceId", invoiceId),+ ]);++ if (purchaseInvoice.error)+ throw new Error("Failed to fetch purchaseInvoice");+ if (purchaseInvoiceLines.error)+ throw new Error("Failed to fetch receipt lines");++ const [partGroups, purchaseOrderLines, supplier] = await Promise.all([+ client+ .from("part")+ .select("id, partGroupId")+ .in(+ "id",+ purchaseInvoiceLines.data.reduce<string[]>((acc, invoiceLine) => {+ if (invoiceLine.partId && !acc.includes(invoiceLine.partId)) {+ acc.push(invoiceLine.partId);+ }+ return acc;+ }, [])+ ),+ client+ .from("purchaseOrderLine")+ .select("*")+ .in(+ "id",+ purchaseInvoiceLines.data.reduce<string[]>((acc, invoiceLine) => {+ if (+ invoiceLine.purchaseOrderLineId &&+ !acc.includes(invoiceLine.purchaseOrderLineId)+ ) {+ acc.push(invoiceLine.purchaseOrderLineId);+ }+ return acc;+ }, [])+ ),+ client+ .from("supplier")+ .select("*")+ .eq("id", purchaseInvoice.data.supplierId ?? "")+ .single(),+ ]);+ if (partGroups.error) throw new Error("Failed to fetch part groups");+ if (purchaseOrderLines.error)+ throw new Error("Failed to fetch purchase order lines");+ if (supplier.error) throw new Error("Failed to fetch supplier");++ const purchaseOrders = await client+ .from("purchaseOrder")+ .select("*")+ .in(+ "purchaseOrderId",+ purchaseOrderLines.data.reduce<string[]>((acc, purchaseOrderLine) => {+ if (+ purchaseOrderLine.purchaseOrderId &&+ !acc.includes(purchaseOrderLine.purchaseOrderId)+ ) {+ acc.push(purchaseOrderLine.purchaseOrderId);+ }+ return acc;+ }, [])+ );+ if (purchaseOrders.error)+ throw new Error("Failed to fetch purchase orders");++ const costLedgerInserts: Database["public"]["Tables"]["costLedger"]["Insert"][] =+ [];++ const journalLineInserts: Omit<+ Database["public"]["Tables"]["journalLine"]["Insert"],+ "journalId"+ >[] = [];++ const purchaseInvoiceLinesByPurchaseOrderLine =+ purchaseInvoiceLines.data.reduce<+ Record<+ string,+ Database["public"]["Tables"]["purchaseInvoiceLine"]["Row"]+ >+ >((acc, invoiceLine) => {+ if (invoiceLine.purchaseOrderLineId) {+ acc[invoiceLine.purchaseOrderLineId] = invoiceLine;+ }+ return acc;+ }, {});++ const purchaseOrderLineUpdates = purchaseOrderLines.data.reduce<+ Record<+ string,+ Database["public"]["Tables"]["purchaseOrderLine"]["Update"]+ >+ >((acc, purchaseOrderLine) => {+ const invoiceLine =+ purchaseInvoiceLinesByPurchaseOrderLine[purchaseOrderLine.id];+ if (+ invoiceLine &&+ invoiceLine.quantity &&+ purchaseOrderLine.purchaseQuantity &&+ purchaseOrderLine.purchaseQuantity > 0+ ) {+ const newQuantityInvoiced =+ (purchaseOrderLine.quantityInvoiced ?? 0) + invoiceLine.quantity;++ const invoicedComplete =+ purchaseOrderLine.invoicedComplete ||+ invoiceLine.quantity >=+ (purchaseOrderLine.quantityToInvoice ??+ purchaseOrderLine.purchaseQuantity);++ return {+ ...acc,+ [purchaseOrderLine.id]: {+ quantityInvoiced: newQuantityInvoiced,+ invoicedComplete,+ purchaseOrderId: purchaseOrderLine.purchaseOrderId,+ },+ };+ }++ return acc;+ }, {});++ const journalLines = await client+ .from("journalLine")+ .select("*")+ .in(+ "reference",+ purchaseOrderLines.data.reduce<string[]>((acc, purchaseOrderLine) => {+ if (+ (purchaseOrderLine.quantityReceived ?? 0) >+ (purchaseOrderLine.quantityInvoiced ?? 0)+ ) {+ acc.push(journalReference.to.receipt(purchaseOrderLine.id));+ }+ return acc;+ }, [])+ );+ if (journalLines.error) {+ throw new Error("Failed to fetch journal entries to reverse");+ }++ const journalLinesByPurchaseOrderLine = journalLines.data.reduce<+ Record<string, Database["public"]["Tables"]["journalLine"]["Row"][]>+ >((acc, journalEntry) => {+ const [type, purchaseOrderLineId] = (journalEntry.reference ?? "").split(+ ":"+ );+ if (type === "receipt") {+ if (+ acc[purchaseOrderLineId] &&+ Array.isArray(acc[purchaseOrderLineId])+ ) {+ acc[purchaseOrderLineId].push(journalEntry);+ } else {+ acc[purchaseOrderLineId] = [journalEntry];+ }+ }+ return acc;+ }, {});++ // save the posting groups in memory to avoid unnecessary queries+ const inventoryPostingGroups: Record<+ string,+ Database["public"]["Tables"]["postingGroupInventory"]["Row"] | null+ > = {};++ for await (const invoiceLine of purchaseInvoiceLines.data) {+ let postingGroupInventory:+ | Database["public"]["Tables"]["postingGroupInventory"]["Row"]+ | null = null;++ const partGroupId: string | null =+ partGroups.data.find((partGroup) => partGroup.id === invoiceLine.partId)+ ?.partGroupId ?? null;+ const locationId = invoiceLine.locationId ?? null;+ const supplierTypeId: string | null =+ supplier.data.supplierTypeId ?? null;++ // inventory posting group+ if (`${partGroupId}-${locationId}` in inventoryPostingGroups) {+ postingGroupInventory =+ inventoryPostingGroups[`${partGroupId}-${locationId}`];+ } else {+ const inventoryPostingGroup = await getInventoryPostingGroup(client, {+ partGroupId,+ locationId,+ });++ if (inventoryPostingGroup.error || !inventoryPostingGroup.data) {+ throw new Error("Error getting inventory posting group");+ }++ postingGroupInventory = inventoryPostingGroup.data ?? null;+ inventoryPostingGroups[`${partGroupId}-${locationId}`] =+ postingGroupInventory;+ }++ if (!postingGroupInventory) {+ throw new Error("No inventory posting group found");+ }++ // purchasing posting group+ const purchasingPostingGroups: Record<+ string,+ Database["public"]["Tables"]["postingGroupPurchasing"]["Row"] | null+ > = {};++ let postingGroupPurchasing:+ | Database["public"]["Tables"]["postingGroupPurchasing"]["Row"]+ | null = null;++ if (`${partGroupId}-${supplierTypeId}` in purchasingPostingGroups) {+ postingGroupPurchasing =+ purchasingPostingGroups[`${partGroupId}-${supplierTypeId}`];+ } else {+ const purchasingPostingGroup = await getPurchasingPostingGroup(client, {+ partGroupId,+ supplierTypeId,+ });++ if (purchasingPostingGroup.error || !purchasingPostingGroup.data) {+ throw new Error("Error getting purchasing posting group");+ }++ postingGroupPurchasing = purchasingPostingGroup.data ?? null;+ purchasingPostingGroups[`${partGroupId}-${supplierTypeId}`] =+ postingGroupPurchasing;+ }++ if (!postingGroupPurchasing) {+ throw new Error("No purchasing posting group found");+ }++ // determine the journal lines that should be reversed+ const existingJournalLines = invoiceLine.purchaseOrderLineId+ ? journalLinesByPurchaseOrderLine[invoiceLine.purchaseOrderLineId] ?? []+ : [];++ let previousJournalId: number | null = null;+ let previousAccrual: boolean | null = null;+ let currentGroup = 0;++ const existingJournalLineGroups = existingJournalLines.reduce<+ Database["public"]["Tables"]["journalLine"]["Row"][][]+ >((acc, entry) => {+ const { journalId, accrual } = entry;++ if (journalId === previousJournalId && accrual === previousAccrual) {+ acc[currentGroup - 1].push(entry);+ } else {+ acc.push([entry]);+ currentGroup++;+ }++ previousJournalId = journalId;+ previousAccrual = accrual;+ return acc;+ }, []);++ const purchaseOrderLine = purchaseOrderLines.data.find(+ (line) => line.id === invoiceLine.purchaseOrderLineId+ );++ const quantityReceived = purchaseOrderLine?.quantityReceived ?? 0;+ const quantityInvoiced = purchaseOrderLine?.quantityInvoiced ?? 0;+ const quantityToReverse = Math.max(+ 0,+ Math.min(invoiceLine.quantity ?? 0, quantityReceived - quantityInvoiced)+ );++ const quantityAlreadyReversed =+ quantityReceived > quantityInvoiced ? quantityInvoiced : 0;++ if (quantityToReverse > 0) {+ let counted = 0;+ let reversed = 0;++ existingJournalLineGroups.forEach((entry) => {+ if (entry[0].quantity) {+ const unitCostForEntry = (entry[0].amount ?? 0) / entry[0].quantity;++ // we don't want to reverse an entry twice, so we need to keep track of what's been previously reversed++ // akin to supply+ const quantityAvailableToReverseForEntry =+ quantityAlreadyReversed > counted+ ? entry[0].quantity + counted - quantityAlreadyReversed+ : entry[0].quantity;++ // akin to demand+ const quantityRequiredToReverse = quantityToReverse - reversed;++ // we can't reverse more than what's available or what's required+ const quantityToReverseForEntry = Math.max(+ 0,+ Math.min(+ quantityAvailableToReverseForEntry,+ quantityRequiredToReverse+ )+ );++ if (quantityToReverseForEntry > 0) {+ // create the reversal entries+ journalLineInserts.push({+ accountNumber: entry[0].accountNumber!,+ description: entry[0].description,+ amount:+ entry[0].description === "Interim Inventory Accrual"+ ? credit(+ "asset",+ quantityToReverseForEntry * unitCostForEntry+ )+ : debit(+ "liability",+ quantityToReverseForEntry * unitCostForEntry+ ),+ quantity: quantityToReverseForEntry,+ documentType: "Invoice",+ documentId: purchaseInvoice.data?.id,+ externalDocumentId: purchaseInvoice?.data.supplierReference,+ reference: invoiceLine.purchaseOrderLineId+ ? journalReference.to.purchaseInvoice(+ invoiceLine.purchaseOrderLineId+ )+ : null,+ });++ journalLineInserts.push({+ accountNumber: entry[1].accountNumber!,+ description: entry[1].description,+ amount:+ entry[1].description === "Interim Inventory Accrual"+ ? credit(+ "asset",+ quantityToReverseForEntry * unitCostForEntry+ )+ : debit(+ "liability",+ quantityToReverseForEntry * unitCostForEntry+ ),+ quantity: quantityToReverseForEntry,+ documentType: "Invoice",+ documentId: purchaseInvoice.data?.id,+ externalDocumentId: purchaseInvoice?.data.supplierReference,+ reference: journalReference.to.purchaseInvoice(+ invoiceLine.purchaseOrderLineId!+ ),+ });+ }++ counted += entry[0].quantity;+ reversed += quantityToReverseForEntry;+ }+ });++ // create the cost entry+ costLedgerInserts.push({+ partLedgerType: "Purchase",+ costLedgerType: "Direct Cost",+ adjustment: false,+ documentType: "Purchase Invoice",+ documentId: purchaseInvoice.data?.id ?? undefined,+ externalDocumentId:+ purchaseInvoice.data?.supplierReference ?? undefined,+ partId: invoiceLine.partId,+ quantity: quantityToReverse,+ cost: quantityToReverse * invoiceLine.unitPrice,+ costPostedToGL: quantityToReverse * invoiceLine.unitPrice,+ });++ // create the normal GL entries++ // debit the inventory account+ journalLineInserts.push({+ accountNumber: postingGroupInventory.inventoryAccount,+ description: "Inventory Account",+ amount: debit("asset", quantityToReverse * invoiceLine.unitPrice),+ quantity: quantityToReverse,+ documentType: "Invoice",+ documentId: purchaseInvoice.data?.id,+ externalDocumentId: purchaseInvoice.data?.supplierReference,+ reference: journalReference.to.purchaseInvoice(+ invoiceLine.purchaseOrderLineId!+ ),+ });++ // creidt the direct cost applied account+ journalLineInserts.push({+ accountNumber: postingGroupInventory.directCostAppliedAccount,+ description: "Direct Cost Applied",+ amount: credit("expense", quantityToReverse * invoiceLine.unitPrice),+ quantity: quantityToReverse,+ documentType: "Invoice",+ documentId: purchaseInvoice.data?.id,+ externalDocumentId: purchaseInvoice.data?.supplierReference,+ reference: journalReference.to.purchaseInvoice(+ invoiceLine.purchaseOrderLineId!+ ),+ });++ // debit the purchase account+ journalLineInserts.push({+ accountNumber: postingGroupPurchasing.purchaseAccount,+ description: "Purchase Account",+ amount: debit("expense", quantityToReverse * invoiceLine.unitPrice),+ quantity: quantityToReverse,+ documentType: "Invoice",+ documentId: purchaseInvoice.data?.id,+ externalDocumentId: purchaseInvoice.data?.supplierReference,+ reference: journalReference.to.purchaseInvoice(+ invoiceLine.purchaseOrderLineId!+ ),+ });++ // credit the accounts payable account+ journalLineInserts.push({+ accountNumber: postingGroupPurchasing.payablesAccount,+ description: "Accounts Payable",+ amount: credit(+ "liability",+ quantityToReverse * invoiceLine.unitPrice+ ),+ quantity: quantityToReverse,+ documentType: "Invoice",+ documentId: purchaseInvoice.data?.id,+ externalDocumentId: purchaseInvoice.data?.supplierReference,+ reference: journalReference.to.purchaseInvoice(+ invoiceLine.purchaseOrderLineId!+ ),+ });+ }++ if (invoiceLine.quantity > quantityToReverse) {+ // create the accrual entries for invoiced not received+ const quantityToAccrue = invoiceLine.quantity - quantityToReverse;++ // debit the inventory invoiced not received account+ journalLineInserts.push({+ accountNumber:+ postingGroupInventory.inventoryInvoicedNotReceivedAccount,+ description: "Inventory Invoiced Not Received",+ accrual: true,+ amount: debit("asset", quantityToAccrue * invoiceLine.unitPrice),+ quantity: quantityToAccrue,+ documentType: "Invoice",+ documentId: purchaseInvoice.data?.id,+ externalDocumentId: purchaseInvoice.data?.supplierReference,+ reference: invoiceLine.purchaseOrderLineId+ ? journalReference.to.purchaseInvoice(+ invoiceLine.purchaseOrderLineId+ )+ : null,+ });++ // credit the inventory interim accrual account+ journalLineInserts.push({+ accountNumber: postingGroupInventory.inventoryInterimAccrualAccount,+ accrual: true,+ description: "Interim Inventory Accrual",+ amount: credit("asset", quantityToAccrue * invoiceLine.unitPrice),+ quantity: quantityToAccrue,+ documentType: "Invoice",+ documentId: purchaseInvoice.data?.id,+ externalDocumentId: purchaseInvoice.data?.supplierReference,+ reference: invoiceLine.purchaseOrderLineId+ ? journalReference.to.purchaseInvoice(+ invoiceLine.purchaseOrderLineId+ )+ : null,+ });+ }+ }++ const accountingPeriodId = await getCurrentAccountingPeriod(client, db);++ 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();+ }++ const purchaseOrdersUpdated = Object.values(+ purchaseOrderLineUpdates+ ).reduce<string[]>((acc, update) => {+ if (update.purchaseOrderId && !acc.includes(update.purchaseOrderId)) {+ acc.push(update.purchaseOrderId);+ }+ return acc;+ }, []);++ for await (const purchaseOrderId of purchaseOrdersUpdated) {+ const purchaseOrderLines = await trx+ .selectFrom("purchaseOrderLine")+ .select(["id", "invoicedComplete", "receivedComplete"])+ .where("purchaseOrderId", "=", purchaseOrderId)+ .execute();++ const areAllLinesInvoiced = purchaseOrderLines.every(+ (line) => line.invoicedComplete+ );++ const areAllLinesReceived = purchaseOrderLines.every(+ (line) => line.receivedComplete+ );++ let status: Database["public"]["Tables"]["purchaseOrder"]["Row"]["status"] =+ "To Receive and Invoice";++ if (areAllLinesInvoiced && areAllLinesReceived) {+ status = "Completed";+ } else if (areAllLinesInvoiced) {+ status = "To Receive";+ } else if (areAllLinesReceived) {+ status = "To Invoice";+ }++ await trx+ .updateTable("purchaseOrder")+ .set({+ status,+ })+ .where("id", "=", purchaseOrderId)+ .execute();+ }++ const journal = await trx+ .insertInto("journal")+ .values({+ accountingPeriodId,+ description: `Purchase Invoice ${purchaseInvoice.data?.invoiceId}`,+ postingDate: today,+ })+ .returning(["id"])+ .execute();++ const journalId = journal[0].id;+ if (!journalId) throw new Error("Failed to insert journal");++ const journalLineIds = await trx+ .insertInto("journalLine")+ .values(+ journalLineInserts.map((journalLine) => ({+ ...journalLine,+ journalId,+ }))+ )+ .returning(["id"])+ .execute();++ if (costLedgerInserts.length > 0) {+ const costLedgerIds = await trx+ .insertInto("costLedger")+ .values(costLedgerInserts)+ .returning(["id"])+ .execute();++ const journalLinesPerCostEntry =+ journalLineIds.length / costLedgerIds.length;+ const costLedgerJournalLineRelationInserts = journalLineIds.map<+ Database["public"]["Tables"]["costLedgerJournalLineRelation"]["Insert"]+ >((journalLineId, i) => ({+ journalLineId: journalLineId.id!,+ costLedgerId:+ costLedgerIds[Math.floor(i / journalLinesPerCostEntry)].id!,+ }));++ await trx+ .insertInto("costLedgerJournalLineRelation")+ .values(costLedgerJournalLineRelationInserts)+ .execute();+ }++ await trx+ .updateTable("purchaseInvoice")+ .set({+ postingDate: today,+ status: "Submitted",+ })+ .where("id", "=", invoiceId)+ .execute();+ });++ return new Response(+ JSON.stringify({+ success: true,+ }),+ {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ }+ );+ } catch (err) {+ console.error(err);+ if (invoiceId) {+ const client = getSupabaseServiceRole(req.headers.get("Authorization"));+ client+ .from("purchaseInvoice")+ .update({ status: "Draft" })+ .eq("id", invoiceId);+ }+ return new Response(JSON.stringify(err), {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 500,+ });+ }+});diff --git a/packages/database/supabase/functions/post-receipt/index.ts b/packages/database/supabase/functions/post-receipt/index.tsindex ace853b987..14625a3fbc 100644--- a/packages/database/supabase/functions/post-receipt/index.ts+++ b/packages/database/supabase/functions/post-receipt/index.ts@@ -1,11 +1,15 @@import { serve } from "https://deno.land/[email protected]/http/server.ts";import { format } from "https://deno.land/[email protected]/datetime/mod.ts";-import type { SupabaseClient } from "https://esm.sh/@supabase/[email protected]";import type { Database } from "../../../src/types.ts";import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";import { corsHeaders } from "../lib/headers.ts";import { getSupabaseServiceRole } from "../lib/supabase.ts";+import { credit, debit, journalReference } from "../lib/utils.ts";import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";+import {+ getInventoryPostingGroup,+ getPurchasingPostingGroup,+} from "../shared/get-posting-group.ts";const pool = getConnectionPool(1);const db = getDatabaseClient<DB>(pool);@@ -23,17 +27,12 @@ serve(async (req: Request) => {const client = getSupabaseServiceRole(req.headers.get("Authorization"));- const receipt = await client- .from("receipt")- .select("*")- .eq("id", receiptId)- .single();- if (receipt.error) throw new Error("Failed to fetch receipt");+ const [receipt, receiptLines] = await Promise.all([+ client.from("receipt").select("*").eq("id", receiptId).single(),+ client.from("receiptLine").select("*").eq("receiptId", receiptId),+ ]);- const receiptLines = await client- .from("receiptLine")- .select("*")- .eq("receiptId", receipt.data.receiptId);+ if (receipt.error) throw new Error("Failed to fetch receipt");if (receiptLines.error) throw new Error("Failed to fetch receipt lines");const partGroups = await client@@ -52,20 +51,6 @@ serve(async (req: Request) => {switch (receipt.data?.sourceDocument) {case "Purchase Order": {- let purchaseOrderLineUpdates: Record<- string,- Database["public"]["Tables"]["purchaseOrderLine"]["Update"]- > = {};-- const valueLedgerInserts: Database["public"]["Tables"]["valueLedger"]["Insert"][] =- [];- const partLedgerInserts: Database["public"]["Tables"]["partLedger"]["Insert"][] =- [];- const journalLineInserts: Omit<- Database["public"]["Tables"]["journalLine"]["Insert"],- "journalId"- >[] = [];-if (!receipt.data.sourceDocumentId)throw new Error("Receipt has no sourceDocumentId");@@ -85,7 +70,23 @@ serve(async (req: Request) => {if (purchaseOrderLines.error)throw new Error("Failed to fetch purchase order lines");- const receiptLinesByLineId = receiptLines.data.reduce<+ const supplier = await client+ .from("supplier")+ .select("*")+ .eq("id", purchaseOrder.data.supplierId)+ .single();+ if (supplier.error) throw new Error("Failed to fetch supplier");++ const costLedgerInserts: Database["public"]["Tables"]["costLedger"]["Insert"][] =+ [];+ const partLedgerInserts: Database["public"]["Tables"]["partLedger"]["Insert"][] =+ [];+ const journalLineInserts: Omit<+ Database["public"]["Tables"]["journalLine"]["Insert"],+ "journalId"+ >[] = [];++ const receiptLinesByPurchaseOrderLineId = receiptLines.data.reduce<Record<string, Database["public"]["Tables"]["receiptLine"]["Row"]>>((acc, receiptLine) => {if (receiptLine.lineId) {@@ -94,13 +95,14 @@ serve(async (req: Request) => {return acc;}, {});- purchaseOrderLineUpdates = purchaseOrderLines.data.reduce<+ const purchaseOrderLineUpdates = purchaseOrderLines.data.reduce<Record<string,Database["public"]["Tables"]["purchaseOrderLine"]["Update"]>>((acc, purchaseOrderLine) => {- const receiptLine = receiptLinesByLineId[purchaseOrderLine.id];+ const receiptLine =+ receiptLinesByPurchaseOrderLineId[purchaseOrderLine.id];if (receiptLine &&receiptLine.receivedQuantity &&@@ -129,54 +131,72 @@ serve(async (req: Request) => {return acc;}, {});- const cachedInventoryPostingGroups: Record<+ const journalLines = await client+ .from("journalLine")+ .select("*")+ .in(+ "reference",+ purchaseOrderLines.data.reduce<string[]>(+ (acc, purchaseOrderLine) => {+ if (+ (purchaseOrderLine.quantityReceived ?? 0) <+ (purchaseOrderLine.quantityInvoiced ?? 0)+ ) {+ acc.push(+ journalReference.to.purchaseInvoice(purchaseOrderLine.id)+ );+ }+ return acc;+ },+ []+ )+ );+ if (journalLines.error) {+ throw new Error("Failed to fetch journal entries to reverse");+ }++ const journalLinesByPurchaseOrderLine = journalLines.data.reduce<+ Record<string, Database["public"]["Tables"]["journalLine"]["Row"][]>+ >((acc, journalEntry) => {+ const [type, purchaseOrderLineId] = (+ journalEntry.reference ?? ""+ ).split(":");+ if (type === "purchase-invoice") {+ if (+ acc[purchaseOrderLineId] &&+ Array.isArray(acc[purchaseOrderLineId])+ ) {+ acc[purchaseOrderLineId].push(journalEntry);+ } else {+ acc[purchaseOrderLineId] = [journalEntry];+ }+ }+ return acc;+ }, {});++ // save the posting groups in memory to avoid unnecessary queries+ const inventoryPostingGroups: Record<string,Database["public"]["Tables"]["postingGroupInventory"]["Row"] | null> = {};for await (const receiptLine of receiptLines.data) {- const expectedValue =- receiptLine.receivedQuantity * receiptLine.unitPrice;-- // value ledger entry- valueLedgerInserts.push({- partLedgerType: "Purchase",- costLedgerType: "Direct Cost",- adjustment: false,- documentType: "Purchase Receipt",- documentId: receipt.data?.receiptId ?? undefined,- externalDocumentId: receipt.data?.externalDocumentId ?? undefined,- costAmountActual: 0,- costAmountExpected: expectedValue,- actualCostPostedToGl: 0,- expectedCostPostedToGl: expectedValue,- });-- // part ledger entry- partLedgerInserts.push({- entryType: "Positive Adjmt.",- documentType: "Purchase Receipt",- documentId: receipt.data?.receiptId ?? undefined,- externalDocumentId: receipt.data?.externalDocumentId ?? undefined,- partId: receiptLine.partId,- locationId: receiptLine.locationId ?? undefined,- shelfId: receiptLine.shelfId ?? undefined,- quantity: receiptLine.receivedQuantity,- });-- // journal lines- let postingGroup:+ let postingGroupInventory:| Database["public"]["Tables"]["postingGroupInventory"]["Row"]| null = null;+const partGroupId: string | null =partGroups.data.find((partGroup) => partGroup.id === receiptLine.partId)?.partGroupId ?? null;const locationId = receiptLine.locationId ?? null;+ const supplierTypeId: string | null =+ supplier.data.supplierTypeId ?? null;- if (`${partGroupId}-${locationId}` in cachedInventoryPostingGroups) {- postingGroup =- cachedInventoryPostingGroups[`${partGroupId}-${locationId}`];+ // inventory posting group+ if (`${partGroupId}-${locationId}` in inventoryPostingGroups) {+ postingGroupInventory =+ inventoryPostingGroups[`${partGroupId}-${locationId}`];} else {const inventoryPostingGroup = await getInventoryPostingGroup(client,@@ -190,32 +210,295 @@ serve(async (req: Request) => {throw new Error("Error getting inventory posting group");}- postingGroup = inventoryPostingGroup.data ?? null;- cachedInventoryPostingGroups[`${partGroupId}-${locationId}`] =- postingGroup;+ postingGroupInventory = inventoryPostingGroup.data ?? null;+ inventoryPostingGroups[`${partGroupId}-${locationId}`] =+ postingGroupInventory;}- if (!postingGroup) {+ if (!postingGroupInventory) {throw new Error("No inventory posting group found");}- journalLineInserts.push({- accountNumber: postingGroup.inventoryInterimAccrualAccount,- description: "Interim Inventory Accrual",- amount: -expectedValue,- documentType: "Order",- documentId: receipt.data?.sourceDocumentReadableId ?? undefined,- externalDocumentId:- purchaseOrder.data?.supplierReference ?? undefined,- });- journalLineInserts.push({- accountNumber: postingGroup.inventoryReceivedNotInvoicedAccount,- description: "Inventory Received Not Invoiced",- amount: expectedValue,- documentType: "Order",- documentId: receipt.data?.sourceDocumentReadableId ?? undefined,- externalDocumentId:- purchaseOrder.data?.supplierReference ?? undefined,+ // purchasing posting group+ const purchasingPostingGroups: Record<+ string,+ Database["public"]["Tables"]["postingGroupPurchasing"]["Row"] | null+ > = {};++ let postingGroupPurchasing:+ | Database["public"]["Tables"]["postingGroupPurchasing"]["Row"]+ | null = null;++ if (`${partGroupId}-${supplierTypeId}` in purchasingPostingGroups) {+ postingGroupPurchasing =+ purchasingPostingGroups[`${partGroupId}-${supplierTypeId}`];+ } else {+ const purchasingPostingGroup = await getPurchasingPostingGroup(+ client,+ {+ partGroupId,+ supplierTypeId,+ }+ );++ if (purchasingPostingGroup.error || !purchasingPostingGroup.data) {+ throw new Error("Error getting purchasing posting group");+ }++ postingGroupPurchasing = purchasingPostingGroup.data ?? null;+ purchasingPostingGroups[`${partGroupId}-${supplierTypeId}`] =+ postingGroupPurchasing;+ }++ if (!postingGroupPurchasing) {+ throw new Error("No purchasing posting group found");+ }++ // determine the journal lines that should be reversed+ const existingJournalLines = receiptLine.lineId+ ? journalLinesByPurchaseOrderLine[receiptLine.lineId] ?? []+ : [];++ let previousJournalId: number | null = null;+ let previousAccrual: boolean | null = null;+ let currentGroup = 0;++ const existingJournalLineGroups = existingJournalLines.reduce<+ Database["public"]["Tables"]["journalLine"]["Row"][][]+ >((acc, entry) => {+ const { journalId, accrual } = entry;++ if (+ journalId === previousJournalId &&+ accrual === previousAccrual+ ) {+ acc[currentGroup - 1].push(entry);+ } else {+ acc.push([entry]);+ currentGroup++;+ }++ previousJournalId = journalId;+ previousAccrual = accrual;+ return acc;+ }, []);++ const purchaseOrderLine = purchaseOrderLines.data.find(+ (line) => line.id === receiptLine.lineId+ );++ const quantityReceived = purchaseOrderLine?.quantityReceived ?? 0;+ const quantityInvoiced = purchaseOrderLine?.quantityInvoiced ?? 0;++ const quantityToReverse = Math.max(+ 0,+ Math.min(+ receiptLine.receivedQuantity ?? 0,+ quantityInvoiced - quantityReceived+ )+ );++ const quantityAlreadyReversed =+ quantityReceived < quantityInvoiced ? quantityReceived : 0;++ if (quantityToReverse > 0) {+ let counted = 0;+ let reversed = 0;+ let value = 0;++ existingJournalLineGroups.forEach((entry) => {+ if (entry[0].quantity) {+ const unitCostForEntry =+ (entry[0].amount ?? 0) / entry[0].quantity;++ // we don't want to reverse an entry twice, so we need to keep track of what's been previously reversed++ // akin to supply+ const quantityAvailableToReverseForEntry =+ quantityAlreadyReversed > counted+ ? entry[0].quantity + counted - quantityAlreadyReversed+ : entry[0].quantity;++ // akin to demand+ const quantityRequiredToReverse = quantityToReverse - reversed;++ // we can't reverse more than what's available or what's required+ const quantityToReverseForEntry = Math.max(+ 0,+ Math.min(+ quantityAvailableToReverseForEntry,+ quantityRequiredToReverse+ )+ );++ if (quantityToReverseForEntry > 0) {+ if (+ entry[0].accrual === false ||+ entry[1].accrual === false+ ) {+ throw new Error("Cannot reverse non-accrual entries");+ }++ // create the reversal entries+ journalLineInserts.push({+ accountNumber: entry[0].accountNumber!,+ description: entry[0].description,+ amount:+ entry[0].description === "Inventory Invoiced Not Received"+ ? credit(+ "asset",+ quantityToReverseForEntry * unitCostForEntry+ )+ : debit(+ "asset", // "Interim Inventory Accrual"+ quantityToReverseForEntry * unitCostForEntry+ ),+ quantity: quantityToReverseForEntry,+ documentType: "Invoice",+ documentId: receipt.data?.id,+ externalDocumentId: receipt?.data.externalDocumentId,+ reference: journalReference.to.receipt(receiptLine.lineId!),+ });+ journalLineInserts.push({+ accountNumber: entry[1].accountNumber!,+ description: entry[1].description,+ amount:+ entry[1].description === "Inventory Invoiced Not Received"+ ? credit(+ "asset",+ quantityToReverseForEntry * unitCostForEntry+ )+ : debit(+ "asset", // "Interim Inventory Accrual"+ quantityToReverseForEntry * unitCostForEntry+ ),+ quantity: quantityToReverseForEntry,+ documentType: "Invoice",+ documentId: receipt.data?.id,+ externalDocumentId: receipt?.data.externalDocumentId,+ reference: journalReference.to.receipt(receiptLine.lineId!),+ });+ }++ counted += entry[0].quantity;+ reversed += quantityToReverseForEntry;+ value += unitCostForEntry * quantityToReverseForEntry;+ }+ });++ // create the cost ledger entry+ costLedgerInserts.push({+ partLedgerType: "Purchase",+ costLedgerType: "Direct Cost",+ adjustment: false,+ documentType: "Purchase Receipt",+ documentId: receipt.data?.id ?? undefined,+ externalDocumentId: receipt.data?.externalDocumentId ?? undefined,+ partId: receiptLine.partId,+ quantity: quantityToReverse,+ cost: value,+ costPostedToGL: value,+ });++ // create the normal GL entries++ // debit the inventory account+ journalLineInserts.push({+ accountNumber: postingGroupInventory.inventoryAccount,+ description: "Inventory Account",+ amount: debit("asset", value),+ quantity: quantityToReverse,+ documentType: "Receipt",+ documentId: receipt.data?.id,+ externalDocumentId: receipt.data?.externalDocumentId,+ reference: journalReference.to.receipt(receiptLine.lineId!),+ });++ // creidt the direct cost applied account+ journalLineInserts.push({+ accountNumber: postingGroupInventory.directCostAppliedAccount,+ description: "Direct Cost Applied",+ amount: credit("expense", value),+ quantity: quantityToReverse,+ documentType: "Receipt",+ documentId: receipt.data?.id,+ externalDocumentId: receipt.data?.externalDocumentId,+ reference: journalReference.to.receipt(receiptLine.lineId!),+ });++ // debit the purchase account+ journalLineInserts.push({+ accountNumber: postingGroupPurchasing.purchaseAccount,+ description: "Purchase Account",+ amount: debit("expense", value),+ quantity: quantityToReverse,+ documentType: "Receipt",+ documentId: receipt.data?.id,+ externalDocumentId: receipt.data?.externalDocumentId,+ reference: journalReference.to.receipt(receiptLine.lineId!),+ });++ // credit the accounts payable account+ journalLineInserts.push({+ accountNumber: postingGroupPurchasing.payablesAccount,+ description: "Accounts Payable",+ amount: credit("liability", value),+ quantity: quantityToReverse,+ documentType: "Receipt",+ documentId: receipt.data?.id,+ externalDocumentId: receipt.data?.externalDocumentId,+ reference: journalReference.to.receipt(receiptLine.lineId!),+ });+ }++ if (receiptLine.receivedQuantity > quantityToReverse) {+ // create the accrual entries for received not invoiced+ const quantityToAccrue =+ receiptLine.receivedQuantity - quantityToReverse;++ const expectedValue =+ (receiptLine.receivedQuantity - quantityToReverse) *+ receiptLine.unitPrice;++ journalLineInserts.push({+ accountNumber:+ postingGroupInventory.inventoryInterimAccrualAccount,+ description: "Interim Inventory Accrual",+ accrual: true,+ amount: debit("asset", expectedValue),+ quantity: quantityToAccrue,+ documentType: "Receipt",+ documentId: receipt.data?.id ?? undefined,+ externalDocumentId:+ purchaseOrder.data?.supplierReference ?? undefined,+ reference: `receipt:${receiptLine.lineId}`,+ });++ journalLineInserts.push({+ accountNumber:+ postingGroupInventory.inventoryReceivedNotInvoicedAccount,+ description: "Inventory Received Not Invoiced",+ accrual: true,+ amount: credit("liability", expectedValue),+ quantity: quantityToAccrue,+ documentType: "Receipt",+ documentId: receipt.data?.id ?? undefined,+ externalDocumentId:+ purchaseOrder.data?.supplierReference ?? undefined,+ reference: `receipt:${receiptLine.lineId}`,+ });+ }++ partLedgerInserts.push({+ postingDate: today,+ partId: receiptLine.partId,+ quantity: receiptLine.receivedQuantity,+ locationId: receiptLine.locationId,+ shelfId: receiptLine.shelfId,+ entryType: "Positive Adjmt.",+ documentType: "Purchase Receipt",+ documentId: receipt.data?.id ?? undefined,+ externalDocumentId: receipt.data?.externalDocumentId ?? undefined,});}@@ -232,22 +515,38 @@ serve(async (req: Request) => {.execute();}- const areAllLinesReceived = Object.values(- purchaseOrderLineUpdates- ).every((line) => line.receivedComplete);-- const isInvoiced = purchaseOrder.data.status === "To Receive";+ const purchaseOrderLines = await trx+ .selectFrom("purchaseOrderLine")+ .select(["id", "invoicedComplete", "receivedComplete"])+ .where("purchaseOrderId", "=", purchaseOrder.data.id)+ .execute();- if (areAllLinesReceived) {- await trx- .updateTable("purchaseOrder")- .set({- status: isInvoiced ? "Completed" : "To Invoice",- })- .where("id", "=", purchaseOrder.data.id)- .execute();+ const areAllLinesInvoiced = purchaseOrderLines.every(+ (line) => line.invoicedComplete+ );++ const areAllLinesReceived = purchaseOrderLines.every(+ (line) => line.receivedComplete+ );++ let status: Database["public"]["Tables"]["purchaseOrder"]["Row"]["status"] =+ "To Receive and Invoice";+ if (areAllLinesInvoiced && areAllLinesReceived) {+ status = "Completed";+ } else if (areAllLinesInvoiced) {+ status = "To Receive";+ } else if (areAllLinesReceived) {+ status = "To Invoice";}+ await trx+ .updateTable("purchaseOrder")+ .set({+ status,+ })+ .where("id", "=", purchaseOrder.data.id)+ .execute();+await trx.updateTable("purchaseOrderDelivery").set({@@ -257,7 +556,7 @@ serve(async (req: Request) => {.where("id", "=", receipt.data.sourceDocumentId).execute();- const partLedgerIds = await trx+ await trx.insertInto("partLedger").values(partLedgerInserts).returning(["id"])@@ -287,52 +586,28 @@ serve(async (req: Request) => {.returning(["id"]).execute();- const valueLedgerIds = await trx- .insertInto("valueLedger")- .values(valueLedgerInserts)- .returning(["id"])- .execute();-- const journalLinesPerValueEntry =- journalLineIds.length / valueLedgerIds.length;- if (- journalLinesPerValueEntry !== 2 ||- partLedgerIds.length !== valueLedgerIds.length- ) {- throw new Error("Failed to insert ledger entries");- }-- for (let i = 0; i < valueLedgerIds.length; i++) {- const valueLedgerId = valueLedgerIds[i].id;- const partLedgerId = partLedgerIds[i].id;+ if (costLedgerInserts.length > 0) {+ const costLedgerIds = await trx+ .insertInto("costLedger")+ .values(costLedgerInserts)+ .returning(["id"])+ .execute();- if (!valueLedgerId || !partLedgerId) {- throw new Error("Failed to insert ledger entries");- }+ // insert relationship between journal entry and value entry+ const journalLinesPerCostEntry =+ journalLineIds.length / costLedgerIds.length;+ const costLedgerJournalLineRelationInserts = journalLineIds.map<+ Database["public"]["Tables"]["costLedgerJournalLineRelation"]["Insert"]+ >((journalLineId, i) => ({+ journalLineId: journalLineId.id!,+ costLedgerId:+ costLedgerIds[Math.floor(i / journalLinesPerCostEntry)].id!,+ }));await trx- .insertInto("partLedgerValueLedgerRelation")- .values({- partLedgerId,- valueLedgerId,- })+ .insertInto("costLedgerJournalLineRelation")+ .values(costLedgerJournalLineRelationInserts).execute();-- for (let j = 0; j < journalLinesPerValueEntry; j++) {- const journalLineId =- journalLineIds[i * journalLinesPerValueEntry + j].id;- if (!journalLineId) {- throw new Error("Failed to insert ledger entries");- }-- await trx- .insertInto("valueLedgerJournalLineRelation")- .values({- valueLedgerId,- journalLineId,- })- .execute();- }}await trx@@ -371,28 +646,3 @@ serve(async (req: Request) => {});}});--// TODO: should this be in a shared package?-async function getInventoryPostingGroup(- client: SupabaseClient<Database>,- args: {- partGroupId: string | null;- locationId: string | null;- }-) {- let query = client.from("postingGroupInventory").select("*");-- if (args.partGroupId === null) {- query = query.is("partGroupId", null);- } else {- query = query.eq("partGroupId", args.partGroupId);- }-- if (args.locationId === null) {- query = query.is("locationId", null);- } else {- query = query.eq("locationId", args.locationId);- }-- return await query.single();-}diff --git a/packages/database/supabase/functions/shared/get-posting-group.ts b/packages/database/supabase/functions/shared/get-posting-group.tsnew file mode 100644index 0000000000..f62753ce39--- /dev/null+++ b/packages/database/supabase/functions/shared/get-posting-group.ts@@ -0,0 +1,50 @@+import { SupabaseClient } from "https://esm.sh/@supabase/[email protected]";+import { Database } from "../../../src/types.ts";++export async function getInventoryPostingGroup(+ client: SupabaseClient<Database>,+ args: {+ partGroupId: string | null;+ locationId: string | null;+ }+) {+ let query = client.from("postingGroupInventory").select("*");++ if (args.partGroupId === null) {+ query = query.is("partGroupId", null);+ } else {+ query = query.eq("partGroupId", args.partGroupId);+ }++ if (args.locationId === null) {+ query = query.is("locationId", null);+ } else {+ query = query.eq("locationId", args.locationId);+ }++ return await query.single();+}++export async function getPurchasingPostingGroup(+ client: SupabaseClient<Database>,+ args: {+ partGroupId: string | null;+ supplierTypeId: string | null;+ }+) {+ let query = client.from("postingGroupPurchasing").select("*");++ if (args.partGroupId === null) {+ query = query.is("partGroupId", null);+ } else {+ query = query.eq("partGroupId", args.partGroupId);+ }++ if (args.supplierTypeId === null) {+ query = query.is("supplierTypeId", null);+ } else {+ query = query.eq("supplierTypeId", args.supplierTypeId);+ }++ return await query.single();+}diff --git a/packages/database/supabase/migrations/20230510035345_purchasing.sql b/packages/database/supabase/migrations/20230510035345_purchasing.sqlindex 9715988281..3e53fbcf24 100644--- a/packages/database/supabase/migrations/20230510035345_purchasing.sql+++ b/packages/database/supabase/migrations/20230510035345_purchasing.sql@@ -228,7 +228,7 @@ CREATE TABLE "purchaseOrderLine" ("shelfId" TEXT,"setupPrice" NUMERIC(9,2),"receivedComplete" BOOLEAN NOT NULL DEFAULT FALSE,- "invoiceComplete" BOOLEAN NOT NULL DEFAULT FALSE,+ "invoicedComplete" BOOLEAN NOT NULL DEFAULT FALSE,"requiresInspection" BOOLEAN NOT NULL DEFAULT FALSE,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),"createdBy" TEXT NOT NULL,diff --git a/packages/database/supabase/migrations/20230702114301_purchasing-rls.sql b/packages/database/supabase/migrations/20230702114301_purchasing-rls.sqlindex d1be7ed00f..5e5dbff4f4 100644--- a/packages/database/supabase/migrations/20230702114301_purchasing-rls.sql+++ b/packages/database/supabase/migrations/20230702114301_purchasing-rls.sql@@ -1,8 +1,13 @@ALTER TABLE "purchaseOrder" ENABLE ROW LEVEL SECURITY;-CREATE POLICY "Employees with purchasing_view can view purchase orders" ON "purchaseOrder"+CREATE POLICY "Employees with purchasing_view, inventory_view, or invoicing_view can view purchase orders" ON "purchaseOrder"FOR SELECT- USING (coalesce(get_my_claim('purchasing_view')::boolean, false) = true AND (get_my_claim('role'::text)) = '"employee"'::jsonb);+ USING (+ (+ coalesce(get_my_claim('purchasing_view')::boolean, false) = true OR+ coalesce(get_my_claim('inventory_view')::boolean, false) = true OR+ coalesce(get_my_claim('invoicing_view')::boolean, false) = true+ ) AND (get_my_claim('role'::text)) = '"employee"'::jsonb);CREATE POLICY "Suppliers with purchasing_view can their own purchase orders" ON "purchaseOrder"FOR SELECTdiff --git a/packages/database/supabase/migrations/20230705033432_ledgers.sql b/packages/database/supabase/migrations/20230705033432_ledgers.sqlindex ab554178c8..4f4aa993f2 100644--- a/packages/database/supabase/migrations/20230705033432_ledgers.sql+++ b/packages/database/supabase/migrations/20230705033432_ledgers.sql@@ -81,8 +81,7 @@ CREATE POLICY "Employees with accounting_create can insert journals" ON "journalCREATE TYPE "journalLineDocumentType" AS ENUM (- 'Quote',- 'Order',+ 'Receipt','Invoice','Credit Memo','Blanket Order',@@ -95,9 +94,12 @@ CREATE TABLE "journalLine" ("accountNumber" TEXT NOT NULL,"description" TEXT,"amount" NUMERIC(19, 4) NOT NULL,+ "quantity" NUMERIC(12, 4) NOT NULL DEFAULT 1,"documentType" "journalLineDocumentType","documentId" TEXT,"externalDocumentId" TEXT,+ "reference" TEXT,+ "accrual" BOOLEAN NOT NULL DEFAULT false,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),CONSTRAINT "journalLine_pkey" PRIMARY KEY ("id"),@@ -166,7 +168,7 @@ CREATE TYPE "partLedgerDocumentType" AS ENUM ('Direct Transfer');-CREATE TABLE "valueLedger" (+CREATE TABLE "costLedger" ("id" TEXT NOT NULL DEFAULT xid(),"entryNumber" SERIAL,"postingDate" DATE NOT NULL DEFAULT CURRENT_DATE,@@ -176,36 +178,36 @@ CREATE TABLE "valueLedger" ("documentType" "partLedgerDocumentType","documentId" TEXT,"externalDocumentId" TEXT,- "costAmountActual" NUMERIC(19, 4) NOT NULL DEFAULT 0,- "costAmountExpected" NUMERIC(19, 4) NOT NULL DEFAULT 0,- "actualCostPostedToGl" NUMERIC(19, 4) NOT NULL DEFAULT 0,- "expectedCostPostedToGl" NUMERIC(19, 4) NOT NULL DEFAULT 0,+ "partId" TEXT,+ "quantity" NUMERIC(12, 4) NOT NULL DEFAULT 0,+ "cost" NUMERIC(19, 4) NOT NULL DEFAULT 0,+ "costPostedToGL" NUMERIC(19, 4) NOT NULL DEFAULT 0,"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),- CONSTRAINT "valueLedger_pkey" PRIMARY KEY ("id")+ CONSTRAINT "costLedger_pkey" PRIMARY KEY ("id"));-ALTER TABLE "valueLedger" ENABLE ROW LEVEL SECURITY;+ALTER TABLE "costLedger" ENABLE ROW LEVEL SECURITY;-CREATE POLICY "Employees with accounting_view can view the value ledger" ON "valueLedger"+CREATE POLICY "Employees with accounting_view can view the value ledger" ON "costLedger"FOR SELECTUSING (coalesce(get_my_claim('accounting_view')::boolean, false) = true AND(get_my_claim('role'::text)) = '"employee"'::jsonb);-CREATE TABLE "valueLedgerJournalLineRelation" (- "valueLedgerId" TEXT NOT NULL,+CREATE TABLE "costLedgerJournalLineRelation" (+ "costLedgerId" TEXT NOT NULL,"journalLineId" TEXT NOT NULL,- CONSTRAINT "valueLedgerJournalLineRelation_pkey" PRIMARY KEY ("valueLedgerId", "journalLineId"),- CONSTRAINT "valueLedgerJournalLineRelation_valueLedgerId_fkey" FOREIGN KEY ("valueLedgerId") REFERENCES "valueLedger"("id"),- CONSTRAINT "valueLedgerJournalLineRelation_journalLineId_fkey" FOREIGN KEY ("journalLineId") REFERENCES "journalLine"("id")+ CONSTRAINT "costLedgerJournalLineRelation_pkey" PRIMARY KEY ("costLedgerId", "journalLineId"),+ CONSTRAINT "costLedgerJournalLineRelation_costLedgerId_fkey" FOREIGN KEY ("costLedgerId") REFERENCES "costLedger"("id"),+ CONSTRAINT "costLedgerJournalLineRelation_journalLineId_fkey" FOREIGN KEY ("journalLineId") REFERENCES "journalLine"("id"));-ALTER TABLE "valueLedgerJournalLineRelation" ENABLE ROW LEVEL SECURITY;+ALTER TABLE "costLedgerJournalLineRelation" ENABLE ROW LEVEL SECURITY;-CREATE POLICY "Employees with accounting_view can view the value ledger/general ledger relations" ON "valueLedgerJournalLineRelation"+CREATE POLICY "Employees with accounting_view can view the value ledger/general ledger relations" ON "costLedgerJournalLineRelation"FOR SELECTUSING (coalesce(get_my_claim('accounting_view')::boolean, false) = true AND@@ -244,24 +246,6 @@ CREATE POLICY "Certain employees can view the parts ledger" ON "partLedger")AND (get_my_claim('role'::text)) = '"employee"'::jsonb);--CREATE TABLE "partLedgerValueLedgerRelation" (- "partLedgerId" TEXT NOT NULL,- "valueLedgerId" TEXT NOT NULL,-- CONSTRAINT "partLedgerValueLedgerRelation_pkey" PRIMARY KEY ("partLedgerId", "valueLedgerId"),- CONSTRAINT "partLedgerValueLedgerRelation_partLedgerId_fkey" FOREIGN KEY ("partLedgerId") REFERENCES "partLedger"("id"),- CONSTRAINT "partLedgerValueLedgerRelation_valueLedgerId_fkey" FOREIGN KEY ("valueLedgerId") REFERENCES "valueLedger"("id")-);--ALTER TABLE "partLedgerValueLedgerRelation" ENABLE ROW LEVEL SECURITY;--CREATE POLICY "Employees with accounting_view can view the part ledger/value ledger relations" ON "partLedgerValueLedgerRelation"- FOR SELECT- USING (- coalesce(get_my_claim('accounting_view')::boolean, false) = true AND- (get_my_claim('role'::text)) = '"employee"'::jsonb- );CREATE TYPE "supplierLedgerDocumentType" AS ENUM ('Payment',@@ -315,4 +299,6 @@ $$;++diff --git a/packages/database/supabase/migrations/20230728025201_receipts.sql b/packages/database/supabase/migrations/20230728025201_receipts.sqlindex d893de743a..55c2ae0e36 100644--- a/packages/database/supabase/migrations/20230728025201_receipts.sql+++ b/packages/database/supabase/migrations/20230728025201_receipts.sql@@ -95,7 +95,7 @@ CREATE TABLE "receiptLine" ("updatedBy" TEXT,CONSTRAINT "receiptLine_pkey" PRIMARY KEY ("id"),- CONSTRAINT "receiptLine_receiptId_fkey" FOREIGN KEY ("receiptId") REFERENCES "receipt" ("receiptId") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "receiptLine_receiptId_fkey" FOREIGN KEY ("receiptId") REFERENCES "receipt" ("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "receiptLine_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part" ("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "receiptLine_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location" ("id") ON DELETE SET NULL ON UPDATE CASCADE,CONSTRAINT "receiptLine_shelfId_fkey" FOREIGN KEY ("shelfId", "locationId") REFERENCES "shelf" ("id", "locationId") ON DELETE SET NULL ON UPDATE CASCADE,@@ -138,14 +138,6 @@ CREATE POLICY "Employees with inventory_delete can delete receipt lines" ON "recAND (get_my_claim('role'::text)) = '"employee"'::jsonb);-CREATE OR REPLACE VIEW "receiptQuantityReceivedByLine" AS- SELECT- r."sourceDocumentId",- l."lineId",- SUM(l."receivedQuantity") AS "receivedQuantity"- FROM "receipt" r- INNER JOIN "receiptLine" l- ON l."receiptId" = r."receiptId"- GROUP BY r."sourceDocumentId", l."lineId";+diff --git a/packages/database/supabase/migrations/20230820020844_posting-groups.sql b/packages/database/supabase/migrations/20230820020844_posting-groups.sqlindex 3ca83d6298..123b357451 100644--- a/packages/database/supabase/migrations/20230820020844_posting-groups.sql+++ b/packages/database/supabase/migrations/20230820020844_posting-groups.sql@@ -43,6 +43,7 @@ CREATE TABLE "accountDefault" ("workInProgressAccount" TEXT NOT NULL,"receivablesAccount" TEXT NOT NULL,"inventoryShippedNotInvoicedAccount" TEXT NOT NULL,+ "inventoryInvoicedNotReceivedAccount" TEXT NOT NULL,"bankCashAccount" TEXT NOT NULL,"bankLocalCurrencyAccount" TEXT NOT NULL,"bankForeignCurrencyAccount" TEXT NOT NULL,@@ -134,6 +135,7 @@ CREATE TABLE "postingGroupInventory" ("inventoryAccount" TEXT NOT NULL,"inventoryInterimAccrualAccount" TEXT NOT NULL,"inventoryReceivedNotInvoicedAccount" TEXT NOT NULL,+ "inventoryInvoicedNotReceivedAccount" TEXT NOT NULL,"inventoryShippedNotInvoicedAccount" TEXT NOT NULL,"workInProgressAccount" TEXT NOT NULL,"directCostAppliedAccount" TEXT NOT NULL,@@ -153,6 +155,7 @@ CREATE TABLE "postingGroupInventory" (CONSTRAINT "postingGroupInventory_inventoryAccount_fkey" FOREIGN KEY ("inventoryAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,CONSTRAINT "postingGroupInventory_inventoryInterimAccrualAccount_fkey" FOREIGN KEY ("inventoryInterimAccrualAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,CONSTRAINT "postingGroupInventory_inventoryReceivedNotInvoicedAccount_fkey" FOREIGN KEY ("inventoryReceivedNotInvoicedAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "postingGroupInventory_inventoryInvoicedNotReceivedAccount_fkey" FOREIGN KEY ("inventoryInvoicedNotReceivedAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,CONSTRAINT "postingGroupInventory_inventoryShippedNotInvoicedAccount_fkey" FOREIGN KEY ("inventoryShippedNotInvoicedAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,CONSTRAINT "postingGroupInventory_workInProgressAccount_fkey" FOREIGN KEY ("workInProgressAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,CONSTRAINT "postingGroupInventory_directCostAppliedAccount_fkey" FOREIGN KEY ("directCostAppliedAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,@@ -188,6 +191,7 @@ CREATE TABLE "postingGroupPurchasing" ("id" TEXT NOT NULL DEFAULT xid(),"supplierTypeId" TEXT,"partGroupId" TEXT,+ "payablesAccount" TEXT NOT NULL,"purchaseAccount" TEXT NOT NULL,"purchaseDiscountAccount" TEXT NOT NULL,"purchaseCreditAccount" TEXT NOT NULL,@@ -199,6 +203,7 @@ CREATE TABLE "postingGroupPurchasing" (CONSTRAINT "postingGroupPurchasing_id_supplierTypeId_partGroupId_key" UNIQUE ("supplierTypeId", "partGroupId"),CONSTRAINT "postingGroupPurchasing_partGroupId_fkey" FOREIGN KEY ("partGroupId") REFERENCES "partGroup" ("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "postingGroupPurchasing_supplierTypeId_fkey" FOREIGN KEY ("supplierTypeId") REFERENCES "supplierType" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "postingGroupPurchasing_payablesAccount_fkey" FOREIGN KEY ("payablesAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,CONSTRAINT "postingGroupPurchasing_purchaseAccount_fkey" FOREIGN KEY ("purchaseAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,CONSTRAINT "postingGroupPurchasing_purchaseDiscountAccount_fkey" FOREIGN KEY ("purchaseDiscountAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,CONSTRAINT "postingGroupPurchasing_purchaseCreditAccount_fkey" FOREIGN KEY ("purchaseCreditAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,@@ -229,6 +234,7 @@ CREATE TABLE "postingGroupSales" ("id" TEXT NOT NULL DEFAULT xid(),"customerTypeId" TEXT,"partGroupId" TEXT,+ "receivablesAccount" TEXT NOT NULL,"salesAccount" TEXT NOT NULL,"salesDiscountAccount" TEXT NOT NULL,"salesCreditAccount" TEXT NOT NULL,@@ -240,6 +246,7 @@ CREATE TABLE "postingGroupSales" (CONSTRAINT "postingGroupSales_id_customerTypeId_partGroupId_key" UNIQUE ("customerTypeId", "partGroupId"),CONSTRAINT "postingGroupSales_partGroupId_fkey" FOREIGN KEY ("partGroupId") REFERENCES "partGroup" ("id") ON DELETE CASCADE ON UPDATE CASCADE,CONSTRAINT "postingGroupSales_customerTypeId_fkey" FOREIGN KEY ("customerTypeId") REFERENCES "customerType" ("id") ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "postingGroupSales_receivablesAccount_fkey" FOREIGN KEY ("receivablesAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,CONSTRAINT "postingGroupSales_salesAccount_fkey" FOREIGN KEY ("salesAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,CONSTRAINT "postingGroupSales_salesDiscountAccount_fkey" FOREIGN KEY ("salesDiscountAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,CONSTRAINT "postingGroupSales_salesCreditAccount_fkey" FOREIGN KEY ("salesCreditAccount") REFERENCES "account" ("number") ON DELETE RESTRICT ON UPDATE CASCADE,@@ -281,6 +288,7 @@ BEGIN"inventoryAccount","inventoryInterimAccrualAccount","inventoryReceivedNotInvoicedAccount",+ "inventoryInvoicedNotReceivedAccount","inventoryShippedNotInvoicedAccount","workInProgressAccount","directCostAppliedAccount",@@ -298,6 +306,7 @@ BEGINaccount_defaults."inventoryAccount",account_defaults."inventoryInterimAccrualAccount",account_defaults."inventoryReceivedNotInvoicedAccount",+ account_defaults."inventoryInvoicedNotReceivedAccount",account_defaults."inventoryShippedNotInvoicedAccount",account_defaults."workInProgressAccount",account_defaults."directCostAppliedAccount",@@ -319,6 +328,7 @@ BEGIN"inventoryAccount","inventoryInterimAccrualAccount","inventoryReceivedNotInvoicedAccount",+ "inventoryInvoicedNotReceivedAccount","inventoryShippedNotInvoicedAccount","workInProgressAccount","directCostAppliedAccount",@@ -336,6 +346,7 @@ BEGINaccount_defaults."inventoryAccount",account_defaults."inventoryInterimAccrualAccount",account_defaults."inventoryReceivedNotInvoicedAccount",+ account_defaults."inventoryInvoicedNotReceivedAccount",account_defaults."inventoryShippedNotInvoicedAccount",account_defaults."workInProgressAccount",account_defaults."directCostAppliedAccount",@@ -370,6 +381,7 @@ BEGININSERT INTO "postingGroupSales" ("partGroupId","customerTypeId",+ "receivablesAccount","salesAccount","salesDiscountAccount","salesCreditAccount",@@ -379,6 +391,7 @@ BEGIN) VALUES (new."id",rec."id",+ account_defaults."receivablesAccount",account_defaults."salesAccount",account_defaults."salesDiscountAccount",account_defaults."receivablesAccount",@@ -392,6 +405,7 @@ BEGININSERT INTO "postingGroupSales" ("partGroupId","customerTypeId",+ "receivablesAccount","salesAccount","salesDiscountAccount","salesCreditAccount",@@ -401,6 +415,7 @@ BEGIN) VALUES (new."id",NULL,+ account_defaults."receivablesAccount",account_defaults."salesAccount",account_defaults."salesDiscountAccount",account_defaults."receivablesAccount",@@ -414,6 +429,7 @@ BEGININSERT INTO "postingGroupPurchasing" ("partGroupId","supplierTypeId",+ "payablesAccount","purchaseAccount","purchaseDiscountAccount","purchaseCreditAccount",@@ -423,6 +439,7 @@ BEGIN) VALUES (new."id",rec."id",+ account_defaults."payablesAccount",account_defaults."purchaseAccount",account_defaults."purchaseAccount",account_defaults."payablesAccount",@@ -436,6 +453,7 @@ BEGININSERT INTO "postingGroupPurchasing" ("partGroupId","supplierTypeId",+ "payablesAccount","purchaseAccount","purchaseDiscountAccount","purchaseCreditAccount",@@ -445,6 +463,7 @@ BEGIN) VALUES (new."id",NULL,+ account_defaults."payablesAccount",account_defaults."purchaseAccount",account_defaults."purchaseAccount",account_defaults."payablesAccount",@@ -462,6 +481,7 @@ BEGIN"inventoryAccount","inventoryInterimAccrualAccount","inventoryReceivedNotInvoicedAccount",+ "inventoryInvoicedNotReceivedAccount","inventoryShippedNotInvoicedAccount","workInProgressAccount","directCostAppliedAccount",@@ -479,6 +499,7 @@ BEGINaccount_defaults."inventoryAccount",account_defaults."inventoryInterimAccrualAccount",account_defaults."inventoryReceivedNotInvoicedAccount",+ account_defaults."inventoryInvoicedNotReceivedAccount",account_defaults."inventoryShippedNotInvoicedAccount",account_defaults."workInProgressAccount",account_defaults."directCostAppliedAccount",@@ -500,6 +521,7 @@ BEGIN"inventoryAccount","inventoryInterimAccrualAccount","inventoryReceivedNotInvoicedAccount",+ "inventoryInvoicedNotReceivedAccount","inventoryShippedNotInvoicedAccount","workInProgressAccount","directCostAppliedAccount",@@ -517,6 +539,7 @@ BEGINaccount_defaults."inventoryAccount",account_defaults."inventoryInterimAccrualAccount",account_defaults."inventoryReceivedNotInvoicedAccount",+ account_defaults."inventoryInvoicedNotReceivedAccount",account_defaults."inventoryShippedNotInvoicedAccount",account_defaults."workInProgressAccount",account_defaults."directCostAppliedAccount",@@ -551,6 +574,7 @@ BEGININSERT INTO "postingGroupSales" ("customerTypeId","partGroupId",+ "receivablesAccount","salesAccount","salesDiscountAccount","salesCreditAccount",@@ -560,6 +584,7 @@ BEGIN) VALUES (new."id",rec."id",+ account_defaults."receivablesAccount",account_defaults."salesAccount",account_defaults."salesDiscountAccount",account_defaults."salesAccount",@@ -573,6 +598,7 @@ BEGININSERT INTO "postingGroupSales" ("customerTypeId","partGroupId",+ "receivablesAccount","salesAccount","salesDiscountAccount","salesCreditAccount",@@ -582,6 +608,7 @@ BEGIN) VALUES (new."id",NULL,+ account_defaults."receivablesAccount",account_defaults."salesAccount",account_defaults."salesDiscountAccount",account_defaults."salesAccount",@@ -612,6 +639,7 @@ BEGININSERT INTO "postingGroupPurchasing" ("supplierTypeId","partGroupId",+ "payablesAccount","purchaseAccount","purchaseDiscountAccount","purchaseCreditAccount",@@ -621,6 +649,7 @@ BEGIN) VALUES (new."id",rec."id",+ account_defaults."payablesAccount",account_defaults."purchaseAccount",account_defaults."purchaseAccount",account_defaults."purchaseAccount",@@ -634,6 +663,7 @@ BEGININSERT INTO "postingGroupPurchasing" ("supplierTypeId","partGroupId",+ "payablesAccount","purchaseAccount","purchaseDiscountAccount","purchaseCreditAccount",@@ -643,6 +673,7 @@ BEGIN) VALUES (new."id",NULL,+ account_defaults."payablesAccount",account_defaults."purchaseAccount",account_defaults."purchaseAccount",account_defaults."purchaseAccount",diff --git a/packages/database/supabase/migrations/20230924004608_accounts-payable.sql b/packages/database/supabase/migrations/20230924004608_accounts-payable.sqlindex e20150aede..25ea3a5f51 100644--- a/packages/database/supabase/migrations/20230924004608_accounts-payable.sql+++ b/packages/database/supabase/migrations/20230924004608_accounts-payable.sql@@ -1,5 +1,6 @@CREATE TYPE "purchaseInvoiceStatus" AS ENUM ('Draft',+ 'Pending','Submitted','Return','Debit Note Issued',@@ -21,6 +22,7 @@ CREATE TABLE "purchaseInvoice" ("paymentTermId" TEXT,"currencyCode" TEXT NOT NULL,"exchangeRate" NUMERIC(10, 4) NOT NULL DEFAULT 1,+ "postingDate" DATE,"dateIssued" DATE,"dateDue" DATE,"datePaid" DATE,@@ -51,6 +53,8 @@ CREATE INDEX "purchaseInvoice_supplierId_idx" ON "purchaseInvoice" ("supplierId"CREATE INDEX "purchaseInvoice_dateDue_idx" ON "purchaseInvoice" ("dateDue");CREATE INDEX "purchaseInvoice_datePaid_idx" ON "purchaseInvoice" ("datePaid");+ALTER publication supabase_realtime ADD TABLE "purchaseInvoice";+ALTER TABLE "purchaseInvoice" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Employees with invoicing_view can view AP invoices" ON "purchaseInvoice"@@ -116,6 +120,7 @@ CREATE TABLE "purchaseInvoiceLine" ("purchaseOrderId" TEXT,"purchaseOrderLineId" TEXT,"partId" TEXT,+ "locationId" TEXT,"accountNumber" TEXT,"assetId" TEXT,"description" TEXT,@@ -134,6 +139,7 @@ CREATE TABLE "purchaseInvoiceLine" (CONSTRAINT "purchaseInvoiceLines_purchaseOrderId_fkey" FOREIGN KEY ("purchaseOrderId") REFERENCES "purchaseOrder" ("id") ON UPDATE CASCADE ON DELETE RESTRICT,CONSTRAINT "purchaseInvoiceLines_purchaseOrderLineId_fkey" FOREIGN KEY ("purchaseOrderLineId") REFERENCES "purchaseOrderLine" ("id") ON UPDATE CASCADE ON DELETE RESTRICT,CONSTRAINT "purchaseInvoiceLines_partId_fkey" FOREIGN KEY ("partId") REFERENCES "part" ("id") ON UPDATE CASCADE ON DELETE RESTRICT,+ CONSTRAINT "purchaseInvoiceLines_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location" ("id") ON UPDATE CASCADE ON DELETE RESTRICT,CONSTRAINT "purchaseInvoiceLines_accountNumber_fkey" FOREIGN KEY ("accountNumber") REFERENCES "account" ("number") ON UPDATE CASCADE ON DELETE RESTRICT,-- CONSTRAINT "purchaseInvoiceLines_assetId_fkey" FOREIGN KEY ("assetId") REFERENCES "fixedAsset" ("id") ON UPDATE CASCADE ON DELETE RESTRICT,CONSTRAINT "purchaseInvoiceLines_currencyCode_fkey" FOREIGN KEY ("currencyCode") REFERENCES "currency" ("code") ON UPDATE CASCADE ON DELETE RESTRICT,@@ -308,6 +314,7 @@ CREATE OR REPLACE VIEW "purchaseInvoices" ASpi."invoiceSupplierId",pi."invoiceSupplierLocationId",pi."invoiceSupplierContactId",+ pi."postingDate",pi."dateIssued",pi."dateDue",pi."datePaid",diff --git a/packages/database/supabase/seed.sql b/packages/database/supabase/seed.sqlindex 469b3ddfb3..011207be05 100644--- a/packages/database/supabase/seed.sql+++ b/packages/database/supabase/seed.sql@@ -130,18 +130,19 @@ VALUES('83120', 'Inventory Interim', 'Posting', 'cjgo71si60lg1aoj5p50', NULL, 'Balance Sheet', 'Debit', 'Average', true, true, 'system'),('83125', 'Work In Progress (WIP)', 'Posting', 'cjgo71si60lg1aoj5p50', NULL, 'Balance Sheet', 'Debit', 'Average', true, true, 'system'),('85005', 'Receivables', 'Posting', 'cjgo71si60lg1aoj5p4g', NULL, 'Balance Sheet', 'Credit', 'Average', true, true, 'system'),- ('85010', 'Inventory Shipped Not Invoiced', 'Posting', 'cjgo71si60lg1aoj5p4g', NULL, 'Balance Sheet', 'Credit', 'Average', true, true, 'system'),+ ('85020', 'Inventory Invoiced Not Received', 'Posting', 'cjgo71si60lg1aoj5p4g', NULL, 'Balance Sheet', 'Credit', 'Average', true, true, 'system'),('86005', 'Bank - Cash', 'Posting', 'cjgo71si60lg1aoj5p40', NULL, 'Balance Sheet', 'Credit', 'Average', true, true, 'system'),('86010', 'Bank - Local Currency', 'Posting', 'cjgo71si60lg1aoj5p40', NULL, 'Balance Sheet', 'Credit', 'Average', false, true, 'system'),('86015', 'Bank - Foreign Currency', 'Posting', 'cjgo71si60lg1aoj5p40', NULL, 'Balance Sheet', 'Credit', 'Average', false, true, 'system'),('87999', 'Current Assets, Total', 'End Total', NULL, NULL, 'Balance Sheet', 'Both', 'Average', false, true, 'system'),('89999', 'Assets, Total', 'End Total', NULL, NULL, 'Balance Sheet', 'Debit', 'Average', false, true, 'system'),('90000', 'Liabilities', 'Begin Total', NULL, NULL, 'Balance Sheet', 'Debit', 'Average', false, true, 'system'),- ('92210', 'Prepayments', 'Posting', 'cjgo71si60lg1aoj5p80', NULL, 'Balance Sheet', 'Debit', 'Average', true, true, 'system'),- ('93005', 'Payables', 'Posting', 'cjgo71si60lg1aoj5p7g', NULL, 'Balance Sheet', 'Debit', 'Average', true, true, 'system'),- ('93010', 'Inventory Received Not Invoiced', 'Posting', 'cjgo71si60lg1aoj5p7g', NULL, 'Balance Sheet', 'Debit', 'Average', true, true, 'system'),- ('94100', 'Sales Tax Payable', 'Posting', 'cjgo71si60lg1aoj5p80', NULL, 'Balance Sheet', 'Debit', 'Average', true, true, 'system'),- ('94110', 'Purchase Tax Payable', 'Posting', 'cjgo71si60lg1aoj5p80', NULL, 'Balance Sheet', 'Debit', 'Average', true, true, 'system'),+ ('92210', 'Prepayments', 'Posting', 'cjgo71si60lg1aoj5p80', NULL, 'Balance Sheet', 'Credit', 'Average', true, true, 'system'),+ ('93005', 'Payables', 'Posting', 'cjgo71si60lg1aoj5p7g', NULL, 'Balance Sheet', 'Credit', 'Average', true, true, 'system'),+ ('93010', 'Inventory Received Not Invoiced', 'Posting', 'cjgo71si60lg1aoj5p80', NULL, 'Balance Sheet', 'Credit', 'Average', true, true, 'system'),+ ('93110', 'Inventory Shipped Not Invoiced', 'Posting', 'cjgo71si60lg1aoj5p80', NULL, 'Balance Sheet', 'Debit', 'Average', true, true, 'system'),+ ('94100', 'Sales Tax Payable', 'Posting', 'cjgo71si60lg1aoj5p80', NULL, 'Balance Sheet', 'Credit', 'Average', true, true, 'system'),+ ('94110', 'Purchase Tax Payable', 'Posting', 'cjgo71si60lg1aoj5p80', NULL, 'Balance Sheet', 'Credit', 'Average', true, true, 'system'),('94115', 'Reverse Charge Tax Payable', 'Posting', 'cjgo71si60lg1aoj5p80', NULL, 'Balance Sheet', 'Debit', 'Average', true, true, 'system'),('94999', 'Liabilities, Total', 'End Total', NULL, NULL, 'Balance Sheet', 'Debit', 'Average', false, true, 'system'),('95000', 'Equity', 'Begin Total', NULL, NULL, 'Balance Sheet', 'Debit', 'Average', false, true, 'system'),@@ -179,13 +180,14 @@ VALUES"inventoryInterimAccrualAccount","workInProgressAccount","receivablesAccount",- "inventoryShippedNotInvoicedAccount",+ "inventoryInvoicedNotReceivedAccount","bankCashAccount","bankLocalCurrencyAccount","bankForeignCurrencyAccount","prepaymentAccount","payablesAccount","inventoryReceivedNotInvoicedAccount",+ "inventoryShippedNotInvoicedAccount","salesTaxPayableAccount","purchaseTaxPayableAccount","reverseChargeSalesTaxPayableAccount",@@ -220,13 +222,14 @@ VALUES'83120','83125','85005',- '85010',+ '85020','86005','86010','86015','92210','93005','93010',+ '93110','94100','94110','94115',@@ -241,6 +244,7 @@ INSERT INTO "postingGroupInventory" ("inventoryAccount","inventoryInterimAccrualAccount","inventoryReceivedNotInvoicedAccount",+ "inventoryInvoicedNotReceivedAccount","inventoryShippedNotInvoicedAccount","workInProgressAccount","directCostAppliedAccount",@@ -256,6 +260,7 @@ INSERT INTO "postingGroupInventory" ("inventoryAccount","inventoryInterimAccrualAccount","inventoryReceivedNotInvoicedAccount",+ "inventoryInvoicedNotReceivedAccount","inventoryShippedNotInvoicedAccount","workInProgressAccount","directCostAppliedAccount",@@ -270,6 +275,7 @@ FROM "accountDefault" WHERE "id" = true;INSERT INTO "postingGroupPurchasing" ("partGroupId","supplierTypeId",+ "payablesAccount","purchaseAccount","purchaseDiscountAccount","purchaseCreditAccount",@@ -279,6 +285,7 @@ INSERT INTO "postingGroupPurchasing" () SELECTNULL,NULL,+ "payablesAccount","purchaseAccount","purchaseAccount","purchaseAccount",@@ -290,6 +297,7 @@ FROM "accountDefault" WHERE "id" = true;INSERT INTO "postingGroupSales" ("partGroupId","customerTypeId",+ "receivablesAccount","salesAccount","salesDiscountAccount","salesCreditAccount",@@ -299,6 +307,7 @@ INSERT INTO "postingGroupSales" () SELECTNULL,NULL,+ "receivablesAccount","salesAccount","salesDiscountAccount","salesAccount",diff --git a/packages/react/package.json b/packages/react/package.jsonindex d21549e71b..465df51365 100644--- a/packages/react/package.json+++ b/packages/react/package.json@@ -27,9 +27,9 @@"@internationalized/date": "^3.3.0","@react-aria/button": "^3.8.0","@react-aria/calendar": "^3.4.0",- "@react-aria/datepicker": "^3.5.0",+ "@react-aria/datepicker": "^3.9.0","@react-stately/calendar": "^3.3.0",- "@react-stately/datepicker": "^3.5.0",+ "@react-stately/datepicker": "^3.9.0","@react-types/button": "^3.7.3","@react-types/calendar": "^3.3.0","@react-types/datepicker": "^3.4.0",diff --git a/packages/react/src/Inputs/Date/components/DateField.tsx b/packages/react/src/Inputs/Date/components/DateField.tsxindex 67dc9c9bed..7c64bcd256 100644--- a/packages/react/src/Inputs/Date/components/DateField.tsx+++ b/packages/react/src/Inputs/Date/components/DateField.tsx@@ -1,10 +1,10 @@-import { useRef } from "react";-import { useDateFieldState } from "@react-stately/datepicker";+import { Box } from "@chakra-ui/react";+import type { DateValue } from "@internationalized/date";+import { createCalendar } from "@internationalized/date";import type { AriaDateFieldProps } from "@react-aria/datepicker";import { useDateField } from "@react-aria/datepicker";-import { createCalendar } from "@internationalized/date";-import type { DateValue } from "@internationalized/date";-import { Box } from "@chakra-ui/react";+import { useDateFieldState } from "@react-stately/datepicker";+import { useRef } from "react";import { DateSegment } from "./DateSegment";const locale = "en-US"; // TODO use user's locale;diff --git a/packages/react/src/Theme/theme.ts b/packages/react/src/Theme/theme.tsindex f5a42315a4..a14e13e3e5 100644--- a/packages/react/src/Theme/theme.ts+++ b/packages/react/src/Theme/theme.ts@@ -64,6 +64,7 @@ export const theme = {borderColor: "gray.200",borderBottomWidth: "1px",borderBottomStyle: "solid",+ fontWeight: "bold",letterSpacing: "tight",},footer: {@@ -88,8 +89,9 @@ export const theme = {borderColor: "gray.200",borderBottomWidth: "1px",borderBottomStyle: "solid",- marginBottom: 4,+ fontWeight: "bold",letterSpacing: "tight",+ marginBottom: 4,},footer: {borderColor: "gray.200",@@ -124,6 +126,7 @@ export const theme = {Modal: {baseStyle: {header: {+ fontWeight: "bold",letterSpacing: "tight",},overlay: {diff --git a/packages/utils/src/accounting.ts b/packages/utils/src/accounting.tsnew file mode 100644index 0000000000..c237acbadc--- /dev/null+++ b/packages/utils/src/accounting.ts@@ -0,0 +1,29 @@+type AccountType = "asset" | "liability" | "equity" | "revenue" | "expense";++export const credit = (accountType: AccountType, amount: number) => {+ switch (accountType) {+ case "asset":+ case "expense":+ return -amount;+ case "liability":+ case "equity":+ case "revenue":+ return amount;+ default:+ throw new Error(`Invalid account type: ${accountType}`);+ }+};++export const debit = (accountType: AccountType, amount: number) => {+ switch (accountType) {+ case "asset":+ case "expense":+ return amount;+ case "liability":+ case "equity":+ case "revenue":+ return -amount;+ default:+ throw new Error(`Invalid account type: ${accountType}`);+ }+};diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.tsindex 5de7bf2708..95a087c7b2 100644--- a/packages/utils/src/index.ts+++ b/packages/utils/src/index.ts@@ -1,3 +1,4 @@+export * from "./accounting";export * from "./date";export * from "./file";export * from "./math";diff --git a/www/components/pages/Home.tsx b/www/components/pages/Home.tsxindex 7e1a2c1e66..ab7257dd4d 100644--- a/www/components/pages/Home.tsx+++ b/www/components/pages/Home.tsx@@ -26,12 +26,20 @@ export default function Home() {</p></div><div className="flex fix-flex-col h-32 mt-4 md:mt-0 mb-6 md:mb-0 items-center justify-center gap-3 md:flex-row xl:flex-row">+ <div className="rounded-md fix-width-auto xl:w-auto">+ <a+ className="flex items-center justify-center w-full px-8 py-3 text-base font-medium text-black no-underline bg-white border border-transparent rounded-md dark:bg-black dark:text-white betterhover:dark:hover:bg-gray-800 betterhover:hover:bg-gray-100 md:py-3 md:text-lg md:px-10 md:leading-6"+ href="/learn/introduction"+ >+ Learn+ </a>+ </div><div className="rounded-md fix-width-auto xl:w-auto"><aclassName="flex items-center justify-center w-full px-8 py-3 text-base font-medium text-white no-underline bg-black border border-transparent rounded-md dark:bg-white dark:text-black betterhover:dark:hover:bg-gray-300 betterhover:hover:bg-gray-700 md:py-3 md:text-lg md:px-10 md:leading-6"- href="/docs/getting-started"+ href="/develop/getting-started">- Get Started →+ Develop</a></div></div>diff --git a/www/pages/_meta.json b/www/pages/_meta.jsonindex 10ca8b2e2c..cc99bc2d4c 100644--- a/www/pages/_meta.json+++ b/www/pages/_meta.json@@ -12,5 +12,6 @@"toc": true}},- "docs": "Docs"+ "learn": "Learn",+ "develop": "Develop"}diff --git a/www/pages/docs/_meta.json b/www/pages/develop/_meta.jsonsimilarity index 60%rename from www/pages/docs/_meta.jsonrename to www/pages/develop/_meta.jsonindex a0e3133cb5..915f92f45a 100644--- a/www/pages/docs/_meta.json+++ b/www/pages/develop/_meta.json@@ -2,6 +2,6 @@"index": "Introduction","tech-stack": "Tech Stack","getting-started": "Getting Started",- "principles": "Principles",- "core-concepts": "Core Concepts"+ "core-concepts": "Core Concepts",+ "principles": "Principles"}diff --git a/www/pages/docs/core-concepts/_meta.json b/www/pages/develop/core-concepts/_meta.jsonsimilarity index 100%rename from www/pages/docs/core-concepts/_meta.jsonrename to www/pages/develop/core-concepts/_meta.jsondiff --git a/www/pages/docs/core-concepts/fetching.mdx b/www/pages/develop/core-concepts/fetching.mdxsimilarity index 100%rename from www/pages/docs/core-concepts/fetching.mdxrename to www/pages/develop/core-concepts/fetching.mdxdiff --git a/www/pages/docs/core-concepts/permissions.mdx b/www/pages/develop/core-concepts/permissions.mdxsimilarity index 100%rename from www/pages/docs/core-concepts/permissions.mdxrename to www/pages/develop/core-concepts/permissions.mdxdiff --git a/www/pages/docs/core-concepts/realtime.mdx b/www/pages/develop/core-concepts/realtime.mdxsimilarity index 100%rename from www/pages/docs/core-concepts/realtime.mdxrename to www/pages/develop/core-concepts/realtime.mdxdiff --git a/www/pages/docs/core-concepts/serverless.mdx b/www/pages/develop/core-concepts/serverless.mdxsimilarity index 100%rename from www/pages/docs/core-concepts/serverless.mdxrename to www/pages/develop/core-concepts/serverless.mdxdiff --git a/www/pages/docs/core-concepts/transactions.mdx b/www/pages/develop/core-concepts/transactions.mdxsimilarity index 100%rename from www/pages/docs/core-concepts/transactions.mdxrename to www/pages/develop/core-concepts/transactions.mdxdiff --git a/www/pages/docs/core-concepts/writing.mdx b/www/pages/develop/core-concepts/writing.mdxsimilarity index 97%rename from www/pages/docs/core-concepts/writing.mdxrename to www/pages/develop/core-concepts/writing.mdxindex 2cdc79f349..2484fb42c5 100644--- a/www/pages/docs/core-concepts/writing.mdx+++ b/www/pages/develop/core-concepts/writing.mdx@@ -158,7 +158,7 @@ import { getSupabaseServiceRole } from "../lib/supabase.ts";interface DB {generalLedger: Database["public"]["Tables"]["generalLedger"]["Update"];partLedger: Database["public"]["Tables"]["partLedger"]["Insert"];- valueLedger: Database["public"]["Tables"]["valueLedger"]["Insert"];+ costLedger: Database["public"]["Tables"]["costLedger"]["Insert"];}const pool = getConnectionPool(1);@@ -184,9 +184,9 @@ serve(async (req: Request) => {.values(generalLedgerInserts).execute();- const valueLedgerIds = await trx- .insertInto("valueLedger")- .values(valueLedgerInserts)+ const costLedgerIds = await trx+ .insertInto("costLedger")+ .values(costLedgerInserts).execute();});diff --git a/www/pages/docs/getting-started.mdx b/www/pages/develop/getting-started.mdxsimilarity index 100%rename from www/pages/docs/getting-started.mdxrename to www/pages/develop/getting-started.mdxdiff --git a/www/pages/docs/index.mdx b/www/pages/develop/index.mdxsimilarity index 91%rename from www/pages/docs/index.mdxrename to www/pages/develop/index.mdxindex 19687ba2c3..6df5092ad2 100644--- a/www/pages/docs/index.mdx+++ b/www/pages/develop/index.mdx@@ -1,5 +1,5 @@----title: What is Carbon ERP?+title: Develop - Introductiondescription: Carbon ERP is a high-performance, open-source ERP---@@ -27,7 +27,7 @@ Unlike most cloud-based ERP systems, Carbon ERP is designed to be a single-tenan### Realtime-We have first-class [support for realtime](/docs/core-concepts/realtime) data updates on any data in the system.+We have first-class [support for realtime](/docs/core-concepts/realtime) data updates on any data in the system. While realtime is not the default, it can be added anywhere.### Manufacturingdiff --git a/www/pages/docs/principles.mdx b/www/pages/develop/principles.mdxsimilarity index 100%rename from www/pages/docs/principles.mdxrename to www/pages/develop/principles.mdxdiff --git a/www/pages/docs/tech-stack.mdx b/www/pages/develop/tech-stack.mdxsimilarity index 100%rename from www/pages/docs/tech-stack.mdxrename to www/pages/develop/tech-stack.mdxdiff --git a/www/pages/learn/_meta.json b/www/pages/learn/_meta.jsonnew file mode 100644index 0000000000..94419e3aa2--- /dev/null+++ b/www/pages/learn/_meta.json@@ -0,0 +1,4 @@+{+ "introduction": "Introduction",+ "accounting": "Accounting"+}diff --git a/www/pages/learn/accounting/_meta.json b/www/pages/learn/accounting/_meta.jsonnew file mode 100644index 0000000000..ce3e2b1643--- /dev/null+++ b/www/pages/learn/accounting/_meta.json@@ -0,0 +1,6 @@+{+ "setup": "Setup",+ "chart-of-accounts": "Chart of Accounts",+ "posting-groups": "Posting Groups",+ "purchasing": "Purchasing"+}diff --git a/www/pages/learn/accounting/chart-of-accounts.mdx b/www/pages/learn/accounting/chart-of-accounts.mdxnew file mode 100644index 0000000000..4b8eef8702--- /dev/null+++ b/www/pages/learn/accounting/chart-of-accounts.mdx@@ -0,0 +1,28 @@+---+title: Learn - Accounting - Chart of Accounts+description: Learn about the chart of accounts in the accounting module+---++# Chart of Accounts++The chart of accounts is a list of all the accounts used by an organization. The chart of accounts is used to organize the finances of the organization and to segregate expenditures, revenue, assets and liabilities in order to give interested parties a better understanding of the financial health of the organization.++## Account Types++Accounts fall into one of two categories: balance sheet accounts and income statement accounts. Balance sheet accounts are used to track assets, liabilities and equity. Income statement accounts are used to track revenue and expenses.++Account categories and subcategories are provided to make it easier to create and edit accounts without worrying about which accounts go where.++You can create an infinite nesting of accounts by using the account types:++- **Begin Total** - The starting account number for a group of accounts+- **End Total** - The ending account number for a group of accounts+- **Posting** - An account that debits and credits are posted to++## Default Accounts++The default accounts form defines the bare-minimum accounts that are needed for automated transactions. There's nothing wrong with using a single account for multiple default accounts. For example, if you didn't care about tracking sales discounts, you could use the same account for both sales discounts and sales revenue.++## Posting Groups++Posting groups are used to define the particular accounts that are used in certain situations (in lieu of the default accounts). For example, you may want to use a different account for sales discounts depending on the customer. You can define a posting group for each customer and then assign the posting group to the customer.diff --git a/www/pages/learn/accounting/posting-groups.mdx b/www/pages/learn/accounting/posting-groups.mdxnew file mode 100644index 0000000000..65fd8cc734--- /dev/null+++ b/www/pages/learn/accounting/posting-groups.mdx@@ -0,0 +1,54 @@+---+title: Learn - Accounting - Posting Groups+description: Learn about posting groups in the accounting module+---++# Posting Groups++Posting groups are used to target specific accounts when posting transactions. For example, you may want to post sales of one product line to one account, while posting sales of another product line to a different account. Posting groups allow you to do this.++Different types of posting groups are used in different situations. Posting groups are created automatically and use the default accounts whenever a new group is created.++## Inventory Posting Groups++Inventory posting groups are used to target specific accounts when posting inventory and cost-of-goods sold transactions. An inventory part group is created automatically whenever a **Part Group** is created and whenever a **Location** is created. It uses the part's **Part Group** and the transaction's **Location** to determine which account to use at the time of posting.++The Inventory Posting Group accounts are:++- **Inventory:**+- **Inventory Interim Accrual:**+- **Inventory Received not Invoiced:**+- **Inventory Shipped not Invoiced:**+- **WIP:**+- **COGS:**+- **Direct Cost Applied:**+- **Overhead:**+- **Overhead Cost Applied:**+- **Purchase Variance:**+- **Inventory Adjustment Variance:**+- **Material Variance:**+- **Capacity Variance:**++## Purchasing Posting Groups++Purchasing posting groups are used to target specific accounts when posting purchasing transactions. A purchasing posting group is created automatically whenever a **Part Group** is created and whenever a **Supplier Type** is created. It uses the part's **Part Group** and the suppliers's **Supplier Type** to determine which account to use at the time of posting.++The Purchasing Posting Group accounts are:++- **Accounts Payable:**+- **Purchase:**+- **Purchase Discount:**+- **Purchase Credit:**+- **Purchase Tax Payable:**++## Sales Posting Groups++Sales posting groups are used to target specific accounts when posting sales transactions. A sales posting group is created automatically whenever a **Part Group** is created and whenever a **Customer Type** is created. It uses the part's **Part Group** and the customer's **Customer Type** to determine which account to use at the time of posting.++The Sales Posting Group accounts are:++- **Accounts Receivable:**+- **Sales:**+- **Sales Discount:**+- **Sales Credit:**+- **Sales Tax Payable:**diff --git a/www/pages/learn/accounting/purchasing.mdx b/www/pages/learn/accounting/purchasing.mdxnew file mode 100644index 0000000000..ba60934fc9--- /dev/null+++ b/www/pages/learn/accounting/purchasing.mdx@@ -0,0 +1,96 @@+---+title: Learn - Accounting - Purchasing+description: Learn about how we account for purchasing+---++# Accounting for Purchasing++Carbon uses three ledgers to track the purchasing process:++- **General Ledger** is populated when a line invoiced or received+- **Cost Ledger** is populated when a line is both invoiced and received+- **Part Ledger** is populated when a line is received++## Overview++A purchase order is made of one or more purchase order lines. Each purchase order line is for a specific part, and has a quantity and a price. The price is the price that we expect to pay for the part. The quantity is how many we expect to receive.++The basic accounting flow for purchasing is that a purchase order is created, then the purchase order is received, then the purchase order is invoiced. After the purchase order is received and invoiced, we should have a general ledger entry (journal line) to debit inventory and a general ledger entry to credit accounts payable for each part received.++In practice, it's a little more sophisticated than that. We have to account for the fact that we may receive a partial shipment, or we may receive a shipment that is different than what we ordered. We also have to account for the fact that we may receive a shipment before we receive the invoice, or we may receive the invoice before we receive the shipment. The price may also change between the purchase order and the invoice.++## Posting Groups++Each part has a posting group that determines which accounts we'll use when post to the general ledger. There are two posting groups that are relevant to purchasing:++1. **Inventory Posting Group** determines which general ledger accounts we'll use when we receive a part+2. **Purchase Posting Group** determines which general ledger accounts we'll use when we invoice a part++## General Ledger Entries++In order to decouple the receiving and invoicing processes, we use accrual accounting in the general ledger. This means that we post to the general ledger when we receive a part, and then we post again when we invoice the part. This allows us to receive a part before we receive the invoice, or receive the invoice before we receive the part.++Here are the basic entries that occur depending on the order of the transactions:++- **Goods Received Before Invoice:**+ - **Goods Received:**+ - **Accrual Entry**+ - Debit the asset Interim Inventory Accrual+ - Credit the liability Inventory Received Not Invoiced+ - **Invoice Received:**+ - **Reversing the Accrual Entry:**+ - Debit the liability Inventory Received Not Invoiced+ - Credit the asset Interim Inventory Accrual+ - This reversing entry cancels out the initial accrual+ - **Inventory Entry:**+ - Debit the asset Inventory (from Inventory posting group)+ - Credit the expense Direct Cost Applied (from posting group)+ - **Purchase Entry:**+ - Debit the expense Purchase Account (from Purchasing posting group)+ - Credit the liability Accounts Payable (from posting group)+ - **Payment:**+ - Debit the liability Accounts Payable (from Purchasing posting group)+ - Credit the asset of a Cash or Bank Account (from Bank Account posting group)+- **Invoice Received Before Goods:**+ - **Invoice Received:**+ - **Accrual Entry:**+ - Debit the asset Inventory Invoiced Not Received+ - Credit the asset Interim Inventory Accrual+ - **Goods Received:**+ - **Reversing the Accrual Entry**+ - Debit the asset Interim Inventory Accrual+ - Credit the asset Inventory Invoiced Not Received+ - **Inventory Entry:**+ - Debit the asset Inventory (from Inventory posting group)+ - Credit the expense Direct Cost Applied (from Inventory posting group)+ - **Purchase Entry:**+ - Debit the expense Purchase Account (from Purchasing posting group)+ - Credit the liability Accounts Payable (from Purchasing posting group)+ - **Payment:**+ - Debit the liability Accounts Payable (from Purchasing posting group)+ - Credit the asset of a Cash or Bank Account (from Bank Account posting group)+- **Goods Received and Invoiced at Same Time**+ - **Goods and Invoiced and Received**+ - **Inventory Entry:**+ - Debit the asset Inventory (from Inventory posting group)+ - Credit the expense Direct Cost Applied (from Inventory posting group)+ - **Purchase Entry:**+ - Debit the expense Purchase Account (from Purchasing posting group)+ - Credit the liability Accounts Payable (from Purchasing posting group)+ - **Payment:**+ - Debit the liability Accounts Payable (from Purchasing posting group)+ - Credit the asset of a Cash or Bank Account (from Bank Account posting group)++On thing that may be surprising here is the **Purchasing Account** and the **Direct Cost Applied** accounts. These are both income statement accounts that offset each other. One benefit of using this setup is that we can see the total amount of purchases of a particular purchasing account directly on the income statement for a period of time. This is useful for understanding the total amount of purchases for a particular group or location at a glance.++## Cost Ledger Entries++The cost ledger is used to track the cost of inventory. The cost ledger is populated when a purchase order line is both invoiced and received. The cost ledger is used to calculate the cost of of a part, particularly in relation to Cost of Goods Sold (COGS).++Unlike the general ledger, the cost ledger is not accrual based. The cost ledger is only populated when a purchase order line is both invoiced and received. Multiple cost ledger entries can be created for a single purchase order line. This can happen when a purchase order line is received in multiple shipments.++Cost ledger entries track quantity and cost.++## Part Ledger Entries++The part ledger is used to track the quantity of inventory. The part ledger is populated when a purchase order line is received. The part ledger is used to track the quantity of inventory on hand, and so entries are tied directly to the receipt of a part without regard for the invoiced amount.diff --git a/www/pages/learn/accounting/setup.mdx b/www/pages/learn/accounting/setup.mdxnew file mode 100644index 0000000000..f38d1e61ae--- /dev/null+++ b/www/pages/learn/accounting/setup.mdx@@ -0,0 +1,10 @@+---+title: Learn - Accounting - Setup+description: Learn about setting up the accounting module+---++# Setup Accounting++It's good to setup the [chart of accounts](./chart-of-accounts) before any transactions are entered. **This should be done before everything else**. While it's easy to add more specific accounts later, it's best to get the main accounts setup before using the system.++Carbon ERP includes a default chart of accounts that can be used as a starting point. It's recommended to review the default chart of accounts and make any changes before using the system.diff --git a/www/pages/learn/introduction.mdx b/www/pages/learn/introduction.mdxnew file mode 100644index 0000000000..fa54cc6aa2--- /dev/null+++ b/www/pages/learn/introduction.mdx@@ -0,0 +1,49 @@+---+title: Learn - Introduction+description: Carbon ERP is a high-performance, open-source ERP+---++import { Features } from "../../components";++# Carbon ERP++<Features />++Carbon ERP is a high permformance, [open-source](https://github.com/barbinbrad/carbon), single-tenant (incomplete) ERP. It allows customers, suppliers, and employees to share a common platform.++## Why Carbon ERP?++We built Carbon ERP because we wanted a real solution to manufacturing scheduling. But in order to solve this problem, we needed to build a complete ERP (and more).++Currently you shouldn't use Carbon ERP for your business. It is incomplete and not ready for the big time. However, it is currently a great learning tool for those who want to learn about business software. It is also a great opportunity for anyone who wants to make better business software with the [latest technologies](../develop/tech-stack).++By the time it's ready for production, it will have stable support the following modules:++- [x] Accounting+- [x] Inventory+- [x] Purchasing+- [x] Sales+- [x] Manufacturing+- [x] Resources Management+- [x] Timecards+- [x] Bill of Material and Routing Configuration+- [x] Supplier Accounts+- [x] Customer Accounts++We'll then be able to focus on the original goal of scheduling and planning.++## What about other open-source ERPs?++The major difference between Carbon and other open-source ERPs is the license. ERPs like [Odoo](https://www.odoo.com/) and [ERPNext](https://erpnext.com/) are licensed under the "copyleft" GPL-family of licenses where Carbon uses a "permissive" (Apache 2.0) license.++The big difference between a permissive license and a copyleft license is in the obligation of the user when modifications have been made to the code.++A permissive license may require that you make the original source code available to your users, but that does not necessarily apply to your modifications. So if, for example, I have written project X, and license it as Apache 2.0, and you add some features to it, and now a user wants to see the source code, then you can give them the original code to project X, but you are not required to provide the code for your privately developed features.++Conversely, with a copyleft license, in the same scenario, you would be required to release the code for your privately developed feature as well to your customer. Moreover, they would then be able to freely distribute that source code as well, including your privately developed features. That is why the copyleft licenses are often defined as being viral or infectious, because they propagate to whatever code they come into contact with.++So then, the question of boundaries comes into play. What if the software is on another system? For example, you write program Y, and it calls system X across the network. With the GPL version 2, the copy left license does not cross the network barrier. AGPL, however, removes this barrier, making the virality of project X extend to program Y.++Copyleft is generally hostile to any proprietary use, and many companies won't touch it for any software that must be distributed to customers. Again, this aligns with some people's political and philosophical wishes, so they do not see a problem with this.++In short, permissive versus copyleft is a fundamental difference in how freedom is defined. The permissive license gives you the freedom to use software however you see fit. The copyleft license tries to eliminate the possibility of proprietary control. It's really two different sides of freedom. Permissive is freedom of the individual from control of the many. Copyleft is freedom of the many from control of the one.diff --git a/www/styles.css b/www/styles.cssindex a110f4ebd2..8e8a1302dc 100644--- a/www/styles.css+++ b/www/styles.css@@ -43,7 +43,7 @@ body {--shiki-token-constant: var(--shiki-color-text);--shiki-token-comment: #999;--shiki-token-keyword: #ff0078;- --shiki-token-function: #12ff00;+ --shiki-token-function: #2a0093;--shiki-token-string-expression: #028265;--shiki-token-punctuation: var(--shiki-color-text);--shiki-token-string: #797afa;diff --git a/www/theme.config.js b/www/theme.config.jsindex 953fc0b5d4..a01c92b7fe 100644--- a/www/theme.config.js+++ b/www/theme.config.js@@ -1,7 +1,7 @@// theme.config.js-import Image from "next/image";import { useTheme } from "next-themes";-import { useState, useEffect } from "react";+import Image from "next/image";+import { useEffect, useState } from "react";const useDark = () => {const { resolvedTheme } = useTheme();@@ -51,4 +51,9 @@ export default {<meta name="viewport" content="width=device-width, initial-scale=1.0" /></>),+ useNextSeoProps() {+ return {+ titleTemplate: "%s – Carbon ERP",+ };+ },};