Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix: migrate to default posting group

Sidwebworkse047571c914b
diff --git a/packages/database/supabase/functions/post-purchase-invoice/index.ts b/packages/database/supabase/functions/post-purchase-invoice/index.ts
index 6efc13249c..861bc715d7 100644
--- a/packages/database/supabase/functions/post-purchase-invoice/index.ts
+++ b/packages/database/supabase/functions/post-purchase-invoice/index.ts
@@ -9,10 +9,7 @@ import type { Database } from "../lib/types.ts";
import { credit, debit, journalReference } from "../lib/utils.ts";
import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
import { getNextSequence } from "../shared/get-next-sequence.ts";
-import {
- getInventoryPostingGroup,
- getPurchasingPostingGroup,
-} from "../shared/get-posting-group.ts";
+import { getDefaultPostingGroup } from "../shared/get-posting-group.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -256,17 +253,11 @@ serve(async (req: Request) => {
return acc;
}, {});
- // save the posting groups in memory to avoid unnecessary queries
- const inventoryPostingGroups: Record<
- string,
- Database["public"]["Tables"]["postingGroupInventory"]["Row"] | null
- > = {};
-
- // purchasing posting group
- const purchasingPostingGroups: Record<
- string,
- Database["public"]["Tables"]["postingGroupPurchasing"]["Row"] | null
- > = {};
+ // Get account defaults (once for all lines)
+ const accountDefaults = await getDefaultPostingGroup(client, companyId);
+ if (accountDefaults.error || !accountDefaults.data) {
+ throw new Error("Error getting account defaults");
+ }
for await (const invoiceLine of purchaseInvoiceLines.data) {
const invoiceLineQuantityInInventoryUnit =
@@ -288,22 +279,6 @@ serve(async (req: Request) => {
totalLineCostWithWeightedShipping /
(invoiceLine.quantity * (invoiceLine.conversionFactor ?? 1));
- // declaring shared variables between part and service cases
- // outside of the switch case to avoid redeclaring them
- let postingGroupInventory:
- | Database["public"]["Tables"]["postingGroupInventory"]["Row"]
- | null = null;
-
- let itemPostingGroupId: string | null = null;
-
- let postingGroupPurchasing:
- | Database["public"]["Tables"]["postingGroupPurchasing"]["Row"]
- | null = null;
-
- const locationId = invoiceLine.locationId ?? null;
- const supplierTypeId: string | null =
- supplier.data.supplierTypeId ?? null;
-
let journalLineReference: string;
switch (invoiceLine.invoiceLineType) {
@@ -314,7 +289,9 @@ serve(async (req: Request) => {
case "Material":
case "Tool":
{
- const item = items.data.find((item) => item.id === invoiceLine.itemId);
+ const item = items.data.find(
+ (item) => item.id === invoiceLine.itemId
+ );
const itemTrackingType = item?.itemTrackingType ?? "Inventory";
console.log({
@@ -325,74 +302,6 @@ serve(async (req: Request) => {
requiresBatchTracking: itemTrackingType === "Batch",
});
- itemPostingGroupId =
- itemCosts.data.find((item) => item.itemId === invoiceLine.itemId)
- ?.itemPostingGroupId ?? null;
-
- // inventory posting group
- if (
- `${itemPostingGroupId}-${locationId}` in inventoryPostingGroups
- ) {
- postingGroupInventory =
- inventoryPostingGroups[`${itemPostingGroupId}-${locationId}`];
- } else {
- const inventoryPostingGroup = await getInventoryPostingGroup(
- client,
- companyId,
- {
- itemPostingGroupId,
- locationId,
- }
- );
-
- if (inventoryPostingGroup.error || !inventoryPostingGroup.data) {
- throw new Error("Error getting inventory posting group");
- }
-
- postingGroupInventory = inventoryPostingGroup.data ?? null;
- inventoryPostingGroups[`${itemPostingGroupId}-${locationId}`] =
- postingGroupInventory;
- }
-
- if (!postingGroupInventory) {
- throw new Error("No inventory posting group found");
- }
-
- if (
- `${itemPostingGroupId}-${supplierTypeId}` in
- purchasingPostingGroups
- ) {
- postingGroupPurchasing =
- purchasingPostingGroups[
- `${itemPostingGroupId}-${supplierTypeId}`
- ];
- } else {
- const purchasingPostingGroup = await getPurchasingPostingGroup(
- client,
- companyId,
- {
- itemPostingGroupId,
- supplierTypeId,
- }
- );
-
- if (
- purchasingPostingGroup.error ||
- !purchasingPostingGroup.data
- ) {
- throw new Error("Error getting purchasing posting group");
- }
-
- postingGroupPurchasing = purchasingPostingGroup.data ?? null;
- purchasingPostingGroups[
- `${itemPostingGroupId}-${supplierTypeId}`
- ] = postingGroupPurchasing;
- }
-
- if (!postingGroupPurchasing) {
- throw new Error("No purchasing posting group found");
- }
-
// if the purchase order line is null, we receive the part, do the normal entries and do not use accrual/reversing
if (invoiceLine.purchaseOrderLineId === null) {
// create the receipt line
@@ -458,7 +367,7 @@ serve(async (req: Request) => {
if (itemTrackingType === "Inventory" && !skipReceiptPost) {
// debit the inventory account
journalLineInserts.push({
- accountNumber: postingGroupInventory.inventoryAccount,
+ accountNumber: accountDefaults.data.inventoryAccount,
description: "Inventory Account",
amount: debit("asset", totalLineCostWithWeightedShipping),
quantity: invoiceLineQuantityInInventoryUnit,
@@ -471,7 +380,7 @@ serve(async (req: Request) => {
// creidt the direct cost applied account
journalLineInserts.push({
- accountNumber: postingGroupInventory.directCostAppliedAccount,
+ accountNumber: accountDefaults.data.directCostAppliedAccount,
description: "Direct Cost Applied",
amount: credit("expense", totalLineCostWithWeightedShipping),
quantity: invoiceLineQuantityInInventoryUnit,
@@ -484,7 +393,7 @@ serve(async (req: Request) => {
} else {
// debit the overhead account
journalLineInserts.push({
- accountNumber: postingGroupInventory.overheadAccount,
+ accountNumber: accountDefaults.data.overheadAccount,
description: "Overhead Account",
amount: debit("asset", totalLineCostWithWeightedShipping),
quantity: invoiceLineQuantityInInventoryUnit,
@@ -498,7 +407,7 @@ serve(async (req: Request) => {
// creidt the overhead cost applied account
journalLineInserts.push({
accountNumber:
- postingGroupInventory.overheadCostAppliedAccount,
+ accountDefaults.data.overheadCostAppliedAccount,
description: "Overhead Cost Applied",
amount: credit("expense", totalLineCostWithWeightedShipping),
quantity: invoiceLineQuantityInInventoryUnit,
@@ -514,7 +423,7 @@ serve(async (req: Request) => {
// debit the purchase account
journalLineInserts.push({
- accountNumber: postingGroupPurchasing.purchaseAccount,
+ accountNumber: accountDefaults.data.purchaseAccount,
description: "Purchase Account",
amount: debit("expense", totalLineCostWithWeightedShipping),
quantity: invoiceLineQuantityInInventoryUnit,
@@ -530,7 +439,7 @@ serve(async (req: Request) => {
// credit the accounts payable account
journalLineInserts.push({
- accountNumber: postingGroupPurchasing.payablesAccount,
+ accountNumber: accountDefaults.data.payablesAccount,
description: "Accounts Payable",
amount: credit("liability", totalLineCostWithWeightedShipping),
quantity: invoiceLineQuantityInInventoryUnit,
@@ -722,8 +631,8 @@ serve(async (req: Request) => {
// debit the inventory account
journalLineInserts.push({
accountNumber: isOutsideProcessing
- ? postingGroupInventory.workInProgressAccount
- : postingGroupInventory.inventoryAccount,
+ ? accountDefaults.data.workInProgressAccount
+ : accountDefaults.data.inventoryAccount,
description: isOutsideProcessing
? "WIP Account"
: "Inventory Account",
@@ -745,7 +654,7 @@ serve(async (req: Request) => {
// creidt the direct cost applied account
journalLineInserts.push({
accountNumber:
- postingGroupInventory.directCostAppliedAccount,
+ accountDefaults.data.directCostAppliedAccount,
description: "Direct Cost Applied",
amount: credit(
"expense",
@@ -764,7 +673,7 @@ serve(async (req: Request) => {
} else {
// debit the overhead account
journalLineInserts.push({
- accountNumber: postingGroupInventory.overheadAccount,
+ accountNumber: accountDefaults.data.overheadAccount,
description: "Overhead Account",
amount: debit(
"asset",
@@ -784,7 +693,7 @@ serve(async (req: Request) => {
// creidt the overhead cost applied account
journalLineInserts.push({
accountNumber:
- postingGroupInventory.overheadCostAppliedAccount,
+ accountDefaults.data.overheadCostAppliedAccount,
description: "Overhead Cost Applied",
amount: credit(
"expense",
@@ -806,7 +715,7 @@ serve(async (req: Request) => {
// debit the purchase account
journalLineInserts.push({
- accountNumber: postingGroupPurchasing.purchaseAccount,
+ accountNumber: accountDefaults.data.purchaseAccount,
description: "Purchase Account",
amount: debit(
"expense",
@@ -825,7 +734,7 @@ serve(async (req: Request) => {
// credit the accounts payable account
journalLineInserts.push({
- accountNumber: postingGroupPurchasing.payablesAccount,
+ accountNumber: accountDefaults.data.payablesAccount,
description: "Accounts Payable",
amount: credit(
"liability",
@@ -853,7 +762,7 @@ serve(async (req: Request) => {
// debit the inventory invoiced not received account
journalLineInserts.push({
accountNumber:
- postingGroupInventory.inventoryInvoicedNotReceivedAccount,
+ accountDefaults.data.inventoryInvoicedNotReceivedAccount,
description: "Inventory Invoiced Not Received",
accrual: true,
amount: debit(
@@ -876,7 +785,7 @@ serve(async (req: Request) => {
// credit the inventory interim accrual account
journalLineInserts.push({
accountNumber:
- postingGroupInventory.inventoryInterimAccrualAccount,
+ accountDefaults.data.inventoryInterimAccrualAccount,
accrual: true,
description: "Interim Inventory Accrual",
amount: credit(
diff --git a/packages/database/supabase/functions/post-receipt/index.ts b/packages/database/supabase/functions/post-receipt/index.ts
index 8e5c5112a3..9fcbdb4b3b 100644
--- a/packages/database/supabase/functions/post-receipt/index.ts
+++ b/packages/database/supabase/functions/post-receipt/index.ts
@@ -13,10 +13,7 @@ import {
TrackedEntityAttributes,
} from "../lib/utils.ts";
import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
-import {
- getInventoryPostingGroup,
- getPurchasingPostingGroup,
-} from "../shared/get-posting-group.ts";
+import { getDefaultPostingGroup } from "../shared/get-posting-group.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -327,96 +324,17 @@ serve(async (req: Request) => {
return acc;
}, {});
- // save the posting groups in memory to avoid unnecessary queries
- const inventoryPostingGroups: Record<
- string,
- Database["public"]["Tables"]["postingGroupInventory"]["Row"] | null
- > = {};
+ // Get account defaults (once for all lines)
+ const accountDefaults = await getDefaultPostingGroup(client, companyId);
+ if (accountDefaults.error || !accountDefaults.data) {
+ throw new Error("Error getting account defaults");
+ }
for await (const receiptLine of receiptLines.data) {
- let postingGroupInventory:
- | Database["public"]["Tables"]["postingGroupInventory"]["Row"]
- | null = null;
-
const itemTrackingType =
items.data.find((item) => item.id === receiptLine.itemId)
?.itemTrackingType ?? "Inventory";
- const itemPostingGroupId =
- itemCosts.data.find((item) => item.itemId === receiptLine.itemId)
- ?.itemPostingGroupId ?? null;
-
- const locationId = receiptLine.locationId ?? null;
- const supplierTypeId: string | null =
- supplier.data.supplierTypeId ?? null;
-
- // inventory posting group
- if (`${itemPostingGroupId}-${locationId}` in inventoryPostingGroups) {
- postingGroupInventory =
- inventoryPostingGroups[`${itemPostingGroupId}-${locationId}`];
- } else {
- const inventoryPostingGroup = await getInventoryPostingGroup(
- client,
- companyId,
- {
- itemPostingGroupId,
- locationId,
- }
- );
-
- if (inventoryPostingGroup.error || !inventoryPostingGroup.data) {
- throw new Error("Error getting inventory posting group");
- }
-
- postingGroupInventory = inventoryPostingGroup.data ?? null;
- inventoryPostingGroups[`${itemPostingGroupId}-${locationId}`] =
- postingGroupInventory;
- }
-
- if (!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 (
- `${itemPostingGroupId}-${supplierTypeId}` in purchasingPostingGroups
- ) {
- postingGroupPurchasing =
- purchasingPostingGroups[
- `${itemPostingGroupId}-${supplierTypeId}`
- ];
- } else {
- const purchasingPostingGroup = await getPurchasingPostingGroup(
- client,
- companyId,
- {
- itemPostingGroupId,
- supplierTypeId,
- }
- );
-
- if (purchasingPostingGroup.error || !purchasingPostingGroup.data) {
- throw new Error("Error getting purchasing posting group");
- }
-
- postingGroupPurchasing = purchasingPostingGroup.data ?? null;
- purchasingPostingGroups[`${itemPostingGroupId}-${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] ?? []
@@ -581,8 +499,8 @@ serve(async (req: Request) => {
// debit the inventory account
journalLineInserts.push({
accountNumber: isOutsideProcessing
- ? postingGroupInventory.workInProgressAccount
- : postingGroupInventory.inventoryAccount,
+ ? accountDefaults.data.workInProgressAccount
+ : accountDefaults.data.inventoryAccount,
description: isOutsideProcessing
? "WIP Account"
: "Inventory Account",
@@ -600,7 +518,7 @@ serve(async (req: Request) => {
// credit the direct cost applied account
journalLineInserts.push({
- accountNumber: postingGroupInventory.directCostAppliedAccount,
+ accountNumber: accountDefaults.data.directCostAppliedAccount,
description: "Direct Cost Applied",
amount: credit("expense", reversedValue),
quantity: quantityToReverse,
@@ -616,7 +534,7 @@ serve(async (req: Request) => {
} else {
// debit the overhead account
journalLineInserts.push({
- accountNumber: postingGroupInventory.overheadAccount,
+ accountNumber: accountDefaults.data.overheadAccount,
description: "Overhead Account",
amount: debit("asset", reversedValue),
quantity: quantityToReverse,
@@ -632,7 +550,7 @@ serve(async (req: Request) => {
// credit the overhead cost applied account
journalLineInserts.push({
- accountNumber: postingGroupInventory.overheadCostAppliedAccount,
+ accountNumber: accountDefaults.data.overheadCostAppliedAccount,
description: "Overhead Cost Applied",
amount: credit("expense", reversedValue),
quantity: quantityToReverse,
@@ -651,7 +569,7 @@ serve(async (req: Request) => {
// debit the purchase account
journalLineInserts.push({
- accountNumber: postingGroupPurchasing.purchaseAccount,
+ accountNumber: accountDefaults.data.purchaseAccount,
description: "Purchase Account",
amount: debit("expense", reversedValue),
quantity: quantityToReverse,
@@ -667,7 +585,7 @@ serve(async (req: Request) => {
// credit the accounts payable account
journalLineInserts.push({
- accountNumber: postingGroupPurchasing.payablesAccount,
+ accountNumber: accountDefaults.data.payablesAccount,
description: "Accounts Payable",
amount: credit("liability", reversedValue),
quantity: quantityToReverse,
@@ -710,7 +628,7 @@ serve(async (req: Request) => {
if (isNegativeReceipt) {
journalLineInserts.push({
accountNumber:
- postingGroupInventory.inventoryInterimAccrualAccount,
+ accountDefaults.data.inventoryInterimAccrualAccount,
description: "Interim Inventory Accrual",
accrual: true,
amount: credit("asset", expectedValueWithShipping),
@@ -726,7 +644,7 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountNumber:
- postingGroupInventory.inventoryReceivedNotInvoicedAccount,
+ accountDefaults.data.inventoryReceivedNotInvoicedAccount,
description: "Inventory Received Not Invoiced",
accrual: true,
amount: debit("liability", expectedValueWithShipping),
@@ -742,7 +660,7 @@ serve(async (req: Request) => {
} else {
journalLineInserts.push({
accountNumber:
- postingGroupInventory.inventoryInterimAccrualAccount,
+ accountDefaults.data.inventoryInterimAccrualAccount,
description: "Interim Inventory Accrual",
accrual: true,
amount: debit("asset", expectedValueWithShipping),
@@ -758,7 +676,7 @@ serve(async (req: Request) => {
journalLineInserts.push({
accountNumber:
- postingGroupInventory.inventoryReceivedNotInvoicedAccount,
+ accountDefaults.data.inventoryReceivedNotInvoicedAccount,
description: "Inventory Received Not Invoiced",
accrual: true,
amount: credit("liability", expectedValueWithShipping),
@@ -1076,11 +994,11 @@ serve(async (req: Request) => {
Database["public"]["Tables"]["warehouseTransferLine"]["Update"]
> = {};
- // Cache for inventory posting groups to avoid repeated queries
- const inventoryPostingGroups: Record<
- string,
- Database["public"]["Tables"]["postingGroupInventory"]["Row"] | null
- > = {};
+ // Get account defaults (once for all lines)
+ const accountDefaults = await getDefaultPostingGroup(client, companyId);
+ if (accountDefaults.error || !accountDefaults.data) {
+ throw new Error("Error getting account defaults");
+ }
// Process each receipt line
for await (const receiptLine of receiptLines.data) {
@@ -1128,75 +1046,36 @@ serve(async (req: Request) => {
});
// Create journal entries for inventory movement if there's value
- if (totalValue > 0 && itemCost?.itemPostingGroupId) {
- const fromLocationId = warehouseTransferLine.fromLocationId;
- const toLocationId = receiptLine.locationId;
-
- // Get inventory posting groups for both locations
- const fromGroupKey = `${itemCost.itemPostingGroupId}-${fromLocationId}`;
- const toGroupKey = `${itemCost.itemPostingGroupId}-${toLocationId}`;
-
- // Fetch from location posting group if not cached
- if (!(fromGroupKey in inventoryPostingGroups)) {
- const fromPostingGroup = await getInventoryPostingGroup(
- client,
- companyId,
- {
- itemPostingGroupId: itemCost.itemPostingGroupId,
- locationId: fromLocationId,
- }
- );
- inventoryPostingGroups[fromGroupKey] =
- fromPostingGroup.data ?? null;
- }
-
- // Fetch to location posting group if not cached
- if (!(toGroupKey in inventoryPostingGroups)) {
- const toPostingGroup = await getInventoryPostingGroup(
- client,
- companyId,
- {
- itemPostingGroupId: itemCost.itemPostingGroupId,
- locationId: toLocationId,
- }
- );
- inventoryPostingGroups[toGroupKey] = toPostingGroup.data ?? null;
- }
-
- const fromPostingGroup = inventoryPostingGroups[fromGroupKey];
- const toPostingGroup = inventoryPostingGroups[toGroupKey];
-
- if (fromPostingGroup && toPostingGroup) {
- const journalLineReference = nanoid();
+ if (totalValue > 0) {
+ const journalLineReference = nanoid();
- // Credit (subtract) inventory from source location
- journalLineInserts.push({
- accountNumber: fromPostingGroup.inventoryAccount,
- description: `Transfer Out - ${warehouseTransfer.data?.transferId}`,
- amount: credit("asset", totalValue),
- quantity: Math.abs(receivedQuantity),
- documentType: "Receipt",
- documentId: receipt.data?.id,
- externalDocumentId: warehouseTransfer.data?.transferId,
- documentLineReference: `transfer-receipt:${receiptLine.lineId}`,
- journalLineReference,
- companyId,
- });
+ // Credit (subtract) inventory from source location
+ journalLineInserts.push({
+ accountNumber: accountDefaults.data.inventoryAccount,
+ description: `Transfer Out - ${warehouseTransfer.data?.transferId}`,
+ amount: credit("asset", totalValue),
+ quantity: Math.abs(receivedQuantity),
+ documentType: "Receipt",
+ documentId: receipt.data?.id,
+ externalDocumentId: warehouseTransfer.data?.transferId,
+ documentLineReference: `transfer-receipt:${receiptLine.lineId}`,
+ journalLineReference,
+ companyId,
+ });
- // Debit (add) inventory to destination location
- journalLineInserts.push({
- accountNumber: toPostingGroup.inventoryAccount,
- description: `Transfer In - ${warehouseTransfer.data?.transferId}`,
- amount: debit("asset", totalValue),
- quantity: Math.abs(receivedQuantity),
- documentType: "Receipt",
- documentId: receipt.data?.id,
- externalDocumentId: warehouseTransfer.data?.transferId,
- documentLineReference: `transfer-receipt:${receiptLine.lineId}`,
- journalLineReference,
- companyId,
- });
- }
+ // Debit (add) inventory to destination location
+ journalLineInserts.push({
+ accountNumber: accountDefaults.data.inventoryAccount,
+ description: `Transfer In - ${warehouseTransfer.data?.transferId}`,
+ amount: debit("asset", totalValue),
+ quantity: Math.abs(receivedQuantity),
+ documentType: "Receipt",
+ documentId: receipt.data?.id,
+ externalDocumentId: warehouseTransfer.data?.transferId,
+ documentLineReference: `transfer-receipt:${receiptLine.lineId}`,
+ journalLineReference,
+ companyId,
+ });
}
}
diff --git a/packages/database/supabase/functions/post-sales-invoice/index.ts b/packages/database/supabase/functions/post-sales-invoice/index.ts
index e451862106..1e8cf93bfe 100644
--- a/packages/database/supabase/functions/post-sales-invoice/index.ts
+++ b/packages/database/supabase/functions/post-sales-invoice/index.ts
@@ -9,10 +9,7 @@ import type { Database } from "../lib/types.ts";
import { credit, debit, journalReference } from "../lib/utils.ts";
import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
import { getNextSequence } from "../shared/get-next-sequence.ts";
-import {
- getInventoryPostingGroup,
- getSalesPostingGroup,
-} from "../shared/get-posting-group.ts";
+import { getDefaultPostingGroup } from "../shared/get-posting-group.ts";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -214,17 +211,11 @@ serve(async (req: Request) => {
return acc;
}, {});
- // save the posting groups in memory to avoid unnecessary queries
- const inventoryPostingGroups: Record<
- string,
- Database["public"]["Tables"]["postingGroupInventory"]["Row"] | null
- > = {};
-
- // sales posting group
- const salesPostingGroups: Record<
- string,
- Database["public"]["Tables"]["postingGroupSales"]["Row"] | null
- > = {};
+ // Get account defaults (once for all lines)
+ const accountDefaults = await getDefaultPostingGroup(client, companyId);
+ if (accountDefaults.error || !accountDefaults.data) {
+ throw new Error("Error getting account defaults");
+ }
for await (const invoiceLine of salesInvoiceLines.data) {
const invoiceLineQuantityInInventoryUnit = invoiceLine.quantity;
@@ -245,22 +236,6 @@ serve(async (req: Request) => {
const invoiceLineUnitCostInInventoryUnit =
totalLineCostWithWeightedShipping / invoiceLine.quantity;
- // declaring shared variables between part and service cases
- // outside of the switch case to avoid redeclaring them
- let postingGroupInventory:
- | Database["public"]["Tables"]["postingGroupInventory"]["Row"]
- | null = null;
-
- let itemPostingGroupId: string | null = null;
-
- let postingGroupSales:
- | Database["public"]["Tables"]["postingGroupSales"]["Row"]
- | null = null;
-
- const locationId = invoiceLine.locationId ?? null;
- const customerTypeId: string | null =
- customer.data.customerTypeId ?? null;
-
let journalLineReference: string;
switch (invoiceLine.invoiceLineType) {
@@ -275,79 +250,6 @@ serve(async (req: Request) => {
items.data.find((item) => item.id === invoiceLine.itemId)
?.itemTrackingType ?? "Inventory";
- itemPostingGroupId =
- itemCosts.data.find(
- (item) => item.itemId === invoiceLine.itemId
- )?.itemPostingGroupId ?? null;
-
- // inventory posting group
- if (
- `${itemPostingGroupId}-${locationId}` in
- inventoryPostingGroups
- ) {
- postingGroupInventory =
- inventoryPostingGroups[
- `${itemPostingGroupId}-${locationId}`
- ];
- } else {
- const inventoryPostingGroup = await getInventoryPostingGroup(
- client,
- companyId,
- {
- itemPostingGroupId,
- locationId,
- }
- );
-
- if (
- inventoryPostingGroup.error ||
- !inventoryPostingGroup.data
- ) {
- throw new Error("Error getting inventory posting group");
- }
-
- postingGroupInventory = inventoryPostingGroup.data ?? null;
- inventoryPostingGroups[
- `${itemPostingGroupId}-${locationId}`
- ] = postingGroupInventory;
- }
-
- if (!postingGroupInventory) {
- throw new Error("No inventory posting group found");
- }
-
- if (
- `${itemPostingGroupId}-${customerTypeId}` in
- salesPostingGroups
- ) {
- postingGroupSales =
- salesPostingGroups[
- `${itemPostingGroupId}-${customerTypeId}`
- ];
- } else {
- const salesPostingGroup = await getSalesPostingGroup(
- client,
- companyId,
- {
- itemPostingGroupId,
- customerTypeId,
- }
- );
-
- if (salesPostingGroup.error || !salesPostingGroup.data) {
- throw new Error("Error getting sales posting group");
- }
-
- postingGroupSales = salesPostingGroup.data ?? null;
- salesPostingGroups[
- `${itemPostingGroupId}-${customerTypeId}`
- ] = postingGroupSales;
- }
-
- if (!postingGroupSales) {
- throw new Error("No sales posting group found");
- }
-
// if the sales order line is null, we ship the part, do the normal entries and do not use accrual/reversing
if (
invoiceLine.salesOrderLineId === null &&
@@ -393,7 +295,7 @@ serve(async (req: Request) => {
if (itemTrackingType === "Inventory") {
// debit the inventory account
journalLineInserts.push({
- accountNumber: postingGroupInventory.inventoryAccount,
+ accountNumber: accountDefaults.data.inventoryAccount,
description: "Inventory Account",
amount: credit(
"asset",
@@ -410,7 +312,7 @@ serve(async (req: Request) => {
// creidt the cost of goods sold account
journalLineInserts.push({
accountNumber:
- postingGroupInventory.costOfGoodsSoldAccount,
+ accountDefaults.data.costOfGoodsSoldAccount,
description: "Cost of Goods Sold",
amount: debit(
"expense",
@@ -429,7 +331,7 @@ serve(async (req: Request) => {
// credit the sales account
journalLineInserts.push({
- accountNumber: postingGroupSales.salesAccount,
+ accountNumber: accountDefaults.data.salesAccount,
description: "Sales Account",
amount: credit(
"revenue",
@@ -448,7 +350,7 @@ serve(async (req: Request) => {
// debit the accounts receivable account
journalLineInserts.push({
- accountNumber: postingGroupSales.receivablesAccount,
+ accountNumber: accountDefaults.data.receivablesAccount,
description: "Accounts Receivable",
amount: debit("asset", totalLineCostWithWeightedShipping),
quantity: invoiceLineQuantityInInventoryUnit,
@@ -468,7 +370,7 @@ serve(async (req: Request) => {
// Credit the sales account
journalLineInserts.push({
- accountNumber: postingGroupSales.salesAccount,
+ accountNumber: accountDefaults.data.salesAccount,
description: "Sales Account",
amount: credit(
"revenue",
@@ -489,7 +391,7 @@ serve(async (req: Request) => {
// Debit the accounts receivable account
journalLineInserts.push({
- accountNumber: postingGroupSales.receivablesAccount,
+ accountNumber: accountDefaults.data.receivablesAccount,
description: "Accounts Receivable",
amount: debit("asset", totalLineCostWithWeightedShipping),
quantity: invoiceLineQuantityInInventoryUnit,
@@ -512,7 +414,7 @@ serve(async (req: Request) => {
// Debit cost of goods sold
journalLineInserts.push({
accountNumber:
- postingGroupInventory.costOfGoodsSoldAccount,
+ accountDefaults.data.costOfGoodsSoldAccount,
description: "Cost of Goods Sold",
amount: debit(
"expense",
@@ -534,7 +436,7 @@ serve(async (req: Request) => {
// Credit inventory account
journalLineInserts.push({
- accountNumber: postingGroupInventory.inventoryAccount,
+ accountNumber: accountDefaults.data.inventoryAccount,
description: "Inventory Account",
amount: credit(
"asset",
diff --git a/packages/database/supabase/functions/shared/get-posting-group.ts b/packages/database/supabase/functions/shared/get-posting-group.ts
index 922667ceb0..6a3db25aa1 100644
--- a/packages/database/supabase/functions/shared/get-posting-group.ts
+++ b/packages/database/supabase/functions/shared/get-posting-group.ts
@@ -1,86 +1,13 @@
import { SupabaseClient } from "https://esm.sh/@supabase/[email protected]";
import { Database } from "../lib/types.ts";
-export async function getInventoryPostingGroup(
+export async function getDefaultPostingGroup(
client: SupabaseClient<Database>,
- companyId: string,
- args: {
- itemPostingGroupId: string | null;
- locationId: string | null;
- }
+ companyId: string
) {
- let query = client
- .from("postingGroupInventory")
+ return await client
+ .from("accountDefault")
.select("*")
- .eq("companyId", companyId);
-
- if (args.itemPostingGroupId === null) {
- query = query.is("itemPostingGroupId", null);
- } else {
- query = query.eq("itemPostingGroupId", args.itemPostingGroupId);
- }
-
- 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>,
- companyId: string,
- args: {
- itemPostingGroupId: string | null;
- supplierTypeId: string | null;
- }
-) {
- let query = client
- .from("postingGroupPurchasing")
- .select("*")
- .eq("companyId", companyId);
-
- if (args.itemPostingGroupId === null) {
- query = query.is("itemPostingGroupId", null);
- } else {
- query = query.eq("itemPostingGroupId", args.itemPostingGroupId);
- }
-
- if (args.supplierTypeId === null) {
- query = query.is("supplierTypeId", null);
- } else {
- query = query.eq("supplierTypeId", args.supplierTypeId);
- }
-
- return await query.single();
-}
-
-export async function getSalesPostingGroup(
- client: SupabaseClient<Database>,
- companyId: string,
- args: {
- itemPostingGroupId: string | null;
- customerTypeId: string | null;
- }
-) {
- let query = client
- .from("postingGroupSales")
- .select("*")
- .eq("companyId", companyId);
-
- if (args.itemPostingGroupId === null) {
- query = query.is("itemPostingGroupId", null);
- } else {
- query = query.eq("itemPostingGroupId", args.itemPostingGroupId);
- }
-
- if (args.customerTypeId === null) {
- query = query.is("customerTypeId", null);
- } else {
- query = query.eq("customerTypeId", args.customerTypeId);
- }
-
- return await query.single();
+ .eq("companyId", companyId)
+ .single();
}