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.

reafactor: add companyId to edge functions

Brad Barbinf0abd473454d
diff --git a/apps/carbon/app/modules/invoicing/invoicing.server.ts b/apps/carbon/app/modules/invoicing/invoicing.server.ts
index e65b6410e9..ceebefdb6a 100644
--- a/apps/carbon/app/modules/invoicing/invoicing.server.ts
+++ b/apps/carbon/app/modules/invoicing/invoicing.server.ts
@@ -2,6 +2,7 @@ import { getSupabaseServiceRole } from "~/lib/supabase";
export async function createPurchaseInvoiceFromPurchaseOrder(
purchaseOrderId: string,
+ companyId: number,
userId: string
) {
const client = getSupabaseServiceRole();
@@ -10,7 +11,8 @@ export async function createPurchaseInvoiceFromPurchaseOrder(
{
body: {
id: purchaseOrderId,
- userId: userId,
+ companyId,
+ userId,
},
}
);
diff --git a/apps/carbon/app/modules/resources/ui/People/PeopleTable.tsx b/apps/carbon/app/modules/resources/ui/People/PeopleTable.tsx
index c4256aa9ef..863a1f9ea9 100644
--- a/apps/carbon/app/modules/resources/ui/People/PeopleTable.tsx
+++ b/apps/carbon/app/modules/resources/ui/People/PeopleTable.tsx
@@ -29,6 +29,18 @@ const PeopleTable = memo(
const permissions = usePermissions();
const [params] = useUrlParams();
+ const employeeTypesById = useMemo(
+ () =>
+ employeeTypes.reduce<Record<string, Partial<EmployeeType>>>(
+ (acc, type) => {
+ if (type.id) acc[type.id] = type;
+ return acc;
+ },
+ {}
+ ),
+ [employeeTypes]
+ );
+
const renderGenericAttribute = useCallback(
(
value?: string | number | boolean,
@@ -76,74 +88,60 @@ const PeopleTable = memo(
[]
);
- const rows = useMemo(
- () =>
- data.map((d) => {
- // we should only have one user and employee per employee id
- if (
- d.user === null ||
- d.employeeType === null ||
- Array.isArray(d.user) ||
- Array.isArray(d.employeeType)
- ) {
- throw new Error("Expected user and employee type to be objects");
- }
-
- return d;
- }),
- [data]
- );
-
- const columns = useMemo<ColumnDef<(typeof rows)[number]>[]>(() => {
- const defaultColumns: ColumnDef<(typeof rows)[number]>[] = [
+ const columns = useMemo<ColumnDef<(typeof data)[number]>[]>(() => {
+ const defaultColumns: ColumnDef<(typeof data)[number]>[] = [
{
header: "User",
cell: ({ row }) => (
<HStack>
<Avatar
size="sm"
- name={row.original.user?.fullName!}
- path={row.original.user?.avatarUrl!}
+ name={row.original.name ?? undefined}
+ path={row.original.avatarUrl ?? undefined}
/>
- <Hyperlink to={path.to.personDetails(row?.original.user?.id!)}>
- {row.original.user?.fullName}
+ <Hyperlink to={path.to.personDetails(row?.original.id!)}>
+ {row.original.fullName}
</Hyperlink>
</HStack>
),
},
{
- accessorKey: "user.firstName",
+ accessorKey: "firstName",
header: "First Name",
cell: (item) => item.getValue(),
},
{
- accessorKey: "user.lastName",
+ accessorKey: "lastName",
header: "Last Name",
cell: (item) => item.getValue(),
},
{
- accessorKey: "user.email",
+ accessorKey: "email",
header: "Email",
cell: (item) => item.getValue(),
},
{
- accessorKey: "employeeType.name",
+ id: "employeeTypeId",
header: "Employee Type",
- cell: (item) => <Enumerable value={item.getValue<string>()} />,
+ cell: ({ row }) => (
+ <Enumerable
+ value={employeeTypesById[row.original.employeeTypeId].name}
+ />
+ ),
meta: {
filter: {
type: "static",
options: employeeTypes.map((type) => ({
- value: type.name!,
+ value: type.id!,
label: <Enumerable value={type.name!} />,
})),
},
},
},
{
- accessorKey: "user.active",
+ accessorKey: "active",
header: "Active",
cell: (item) => <Checkbox isChecked={item.getValue<boolean>()} />,
meta: {
@@ -158,7 +156,7 @@ const PeopleTable = memo(
},
];
- const additionalColumns: ColumnDef<(typeof rows)[number]>[] = [];
+ const additionalColumns: ColumnDef<(typeof data)[number]>[] = [];
attributeCategories.forEach((category) => {
if (category.userAttribute && Array.isArray(category.userAttribute)) {
@@ -178,11 +176,16 @@ const PeopleTable = memo(
});
return [...defaultColumns, ...additionalColumns];
- }, [attributeCategories, employeeTypes, renderGenericAttribute]);
+ }, [
+ attributeCategories,
+ employeeTypes,
+ employeeTypesById,
+ renderGenericAttribute,
+ ]);
const renderContextMenu = useMemo(() => {
return permissions.can("update", "resources")
- ? (row: (typeof rows)[number]) => {
+ ? (row: (typeof data)[number]) => {
return (
<MenuItem
onClick={() =>
@@ -203,11 +206,11 @@ const PeopleTable = memo(
return (
<>
- <Table<(typeof rows)[number]>
+ <Table<(typeof data)[number]>
// actions={actions}
count={count}
columns={columns}
- data={rows}
+ data={data}
defaultColumnPinning={{
left: ["Select", "User"],
}}
diff --git a/apps/carbon/app/modules/users/ui/Employees/EmployeesTable.tsx b/apps/carbon/app/modules/users/ui/Employees/EmployeesTable.tsx
index 29c0334759..63c012ab18 100644
--- a/apps/carbon/app/modules/users/ui/Employees/EmployeesTable.tsx
+++ b/apps/carbon/app/modules/users/ui/Employees/EmployeesTable.tsx
@@ -39,6 +39,15 @@ const EmployeesTable = memo(
const permissions = usePermissions();
const [params] = useUrlParams();
+ const employeeTypesById = useMemo(
+ () =>
+ employeeTypes.reduce<Record<string, ListItem>>((acc, type) => {
+ acc[type.id] = type;
+ return acc;
+ }, {}),
+ [employeeTypes]
+ );
+
const [selectedUserIds, setSelectedUserIds] = useState<string[]>([]);
const bulkEditDrawer = useDisclosure();
@@ -88,11 +97,10 @@ const EmployeesTable = memo(
{
id: "employeeTypeId",
header: "Employee Type",
- cell: (item) => (
+ cell: ({ row }) => (
<Enumerable
value={
- employeeTypes.find((et) => et.id === item.getValue<string>())
- ?.name ?? null
+ employeeTypesById[row.original.employeeTypeId!]?.name ?? ""
}
/>
),
diff --git a/apps/carbon/app/routes/x+/purchase-invoice+/new.tsx b/apps/carbon/app/routes/x+/purchase-invoice+/new.tsx
index 402255b00d..2ab9b61f22 100644
--- a/apps/carbon/app/routes/x+/purchase-invoice+/new.tsx
+++ b/apps/carbon/app/routes/x+/purchase-invoice+/new.tsx
@@ -21,7 +21,7 @@ import { error } from "~/utils/result";
export async function loader({ request }: LoaderFunctionArgs) {
// we don't use the client here -- if they have this permission, we'll upgrade to a service role if needed
- const { userId } = await requirePermissions(request, {
+ const { companyId, userId } = await requirePermissions(request, {
create: "invoicing",
});
@@ -36,6 +36,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
if (!sourceDocumentId) throw new Error("Missing sourceDocumentId");
result = await createPurchaseInvoiceFromPurchaseOrder(
sourceDocumentId,
+ companyId,
userId
);
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.ts
index e4639a05b9..856d98caec 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
@@ -13,10 +13,11 @@ serve(async (req: Request) => {
if (req.method === "OPTIONS") {
return new Response("ok", { headers: corsHeaders });
}
- const { id: purchaseOrderId, userId } = await req.json();
+ const { id: purchaseOrderId, companyId, userId } = await req.json();
try {
if (!purchaseOrderId) throw new Error("Payload is missing id");
+ if (!companyId) throw new Error("Payload is missing companyId");
if (!userId) throw new Error("Payload is missing userId");
const client = getSupabaseServiceRole(req.headers.get("Authorization"));
@@ -70,7 +71,11 @@ serve(async (req: Request) => {
let purchaseInvoiceId = "";
await db.transaction().execute(async (trx) => {
- purchaseInvoiceId = await getNextSequence(trx, "purchaseInvoice");
+ purchaseInvoiceId = await getNextSequence(
+ trx,
+ "purchaseInvoice",
+ companyId
+ );
const purchaseInvoice = await trx
.insertInto("purchaseInvoice")
@@ -92,6 +97,7 @@ serve(async (req: Request) => {
totalAmount: uninvoicedSubtotal,
totalTax: 0,
balance: uninvoicedSubtotal,
+ companyId,
createdBy: userId,
})
.returning(["id"])
@@ -128,6 +134,7 @@ serve(async (req: Request) => {
// TODO: currency code and exchange rate
currencyCode: "USD",
exchangeRate: 1,
+ companyId,
createdBy: userId,
});
}
diff --git a/packages/database/supabase/functions/create-receipt-default/index.ts b/packages/database/supabase/functions/create-receipt-default/index.ts
index 16a23b7c86..f106dbad0c 100644
--- a/packages/database/supabase/functions/create-receipt-default/index.ts
+++ b/packages/database/supabase/functions/create-receipt-default/index.ts
@@ -25,7 +25,7 @@ serve(async (req: Request) => {
if (!companyId) throw new Error("Payload is missing companyId");
await db.transaction().execute(async (trx) => {
- receiptId = await getNextSequence(trx, "receipt");
+ receiptId = await getNextSequence(trx, "receipt", companyId);
const newReceipt = await trx
.insertInto("receipt")
.values({
diff --git a/packages/database/supabase/functions/create-receipt-from-purchase-order/index.ts b/packages/database/supabase/functions/create-receipt-from-purchase-order/index.ts
index 34d349e950..52b31e8ce7 100644
--- a/packages/database/supabase/functions/create-receipt-from-purchase-order/index.ts
+++ b/packages/database/supabase/functions/create-receipt-from-purchase-order/index.ts
@@ -123,7 +123,7 @@ serve(async (req: Request) => {
.where("receiptId", "=", receiptId)
.execute();
} else {
- receiptIdReadable = await getNextSequence(trx, "receipt");
+ receiptIdReadable = await getNextSequence(trx, "receipt", companyId);
const newReceipt = await trx
.insertInto("receipt")
.values({
diff --git a/packages/database/supabase/functions/post-purchase-invoice/index.ts b/packages/database/supabase/functions/post-purchase-invoice/index.ts
index 37a3715699..84931a1445 100644
--- a/packages/database/supabase/functions/post-purchase-invoice/index.ts
+++ b/packages/database/supabase/functions/post-purchase-invoice/index.ts
@@ -40,6 +40,8 @@ serve(async (req: Request) => {
if (purchaseInvoiceLines.error)
throw new Error("Failed to fetch receipt lines");
+ const companyId = purchaseInvoice.data.companyId;
+
const [parts, services, purchaseOrderLines, supplier] = await Promise.all([
client
.from("part")
@@ -52,7 +54,8 @@ serve(async (req: Request) => {
}
return acc;
}, [])
- ),
+ )
+ .eq("companyId", companyId),
client
.from("service")
.select("id, partGroupId")
@@ -64,7 +67,8 @@ serve(async (req: Request) => {
}
return acc;
}, [])
- ),
+ )
+ .eq("companyId", companyId),
client
.from("purchaseOrderLine")
.select("*")
@@ -84,6 +88,7 @@ serve(async (req: Request) => {
.from("supplier")
.select("*")
.eq("id", purchaseInvoice.data.supplierId ?? "")
+ .eq("companyId", companyId)
.single(),
]);
if (parts.error) throw new Error("Failed to fetch part groups");
@@ -106,7 +111,9 @@ serve(async (req: Request) => {
}
return acc;
}, [])
- );
+ )
+ .eq("companyId", companyId);
+
if (purchaseOrders.error)
throw new Error("Failed to fetch purchase orders");
@@ -189,7 +196,8 @@ serve(async (req: Request) => {
}
return acc;
}, [])
- );
+ )
+ .eq("companyId", companyId);
if (journalLines.error) {
throw new Error("Failed to fetch journal entries to reverse");
}
@@ -257,12 +265,14 @@ serve(async (req: Request) => {
.from("accounts")
.select("name, number, directPosting")
.eq("number", invoiceLine.accountNumber ?? "")
+ .eq("companyId", companyId)
.single(),
client
.from("accountDefault")
.select(
"overheadCostAppliedAccount, payablesAccount, purchaseAccount"
)
+ .eq("companyId", companyId)
.single(),
]);
if (account.error || !account.data)
@@ -292,6 +302,7 @@ serve(async (req: Request) => {
invoiceLine.purchaseOrderLineId!
),
journalLineReference,
+ companyId,
});
// credit the direct cost applied account
@@ -310,6 +321,7 @@ serve(async (req: Request) => {
invoiceLine.purchaseOrderLineId!
),
journalLineReference,
+ companyId,
});
journalLineReference = nanoid();
@@ -330,6 +342,7 @@ serve(async (req: Request) => {
invoiceLine.purchaseOrderLineId!
),
journalLineReference,
+ companyId,
});
// credit the accounts payable account
@@ -348,6 +361,7 @@ serve(async (req: Request) => {
invoiceLine.purchaseOrderLineId!
),
journalLineReference,
+ companyId,
});
break;
case "Service":
@@ -438,6 +452,7 @@ serve(async (req: Request) => {
documentId: purchaseInvoice.data?.id,
externalDocumentId: purchaseInvoice.data?.supplierReference,
journalLineReference,
+ companyId,
});
// creidt the direct cost applied account
@@ -453,6 +468,7 @@ serve(async (req: Request) => {
documentId: purchaseInvoice.data?.id,
externalDocumentId: purchaseInvoice.data?.supplierReference,
journalLineReference,
+ companyId,
});
journalLineReference = nanoid();
@@ -473,6 +489,7 @@ serve(async (req: Request) => {
invoiceLine.purchaseOrderLineId!
),
journalLineReference,
+ companyId,
});
// credit the accounts payable account
@@ -491,6 +508,7 @@ serve(async (req: Request) => {
invoiceLine.purchaseOrderLineId!
),
journalLineReference,
+ companyId,
});
break;
@@ -568,6 +586,7 @@ serve(async (req: Request) => {
unitOfMeasure: invoiceLine.inventoryUnitOfMeasureCode ?? "EA",
unitPrice: invoiceLine.unitPrice,
createdBy: invoiceLine.createdBy,
+ companyId,
});
if (partType === "Inventory") {
@@ -583,6 +602,7 @@ serve(async (req: Request) => {
documentId: purchaseInvoice.data?.id ?? undefined,
externalDocumentId:
purchaseInvoice.data?.supplierReference ?? undefined,
+ companyId,
});
}
@@ -599,6 +619,7 @@ serve(async (req: Request) => {
quantity: invoiceLineQuantityInInventoryUnit,
cost: invoiceLine.quantity * invoiceLine.unitPrice,
costPostedToGL: invoiceLine.quantity * invoiceLine.unitPrice,
+ companyId,
});
// create the normal GL entries for a part
@@ -619,6 +640,7 @@ serve(async (req: Request) => {
documentId: purchaseInvoice.data?.id,
externalDocumentId: purchaseInvoice.data?.supplierReference,
journalLineReference,
+ companyId,
});
// creidt the direct cost applied account
@@ -634,6 +656,7 @@ serve(async (req: Request) => {
documentId: purchaseInvoice.data?.id,
externalDocumentId: purchaseInvoice.data?.supplierReference,
journalLineReference,
+ companyId,
});
} else {
// debit the overhead account
@@ -649,6 +672,7 @@ serve(async (req: Request) => {
documentId: purchaseInvoice.data?.id,
externalDocumentId: purchaseInvoice.data?.supplierReference,
journalLineReference,
+ companyId,
});
// creidt the overhead cost applied account
@@ -664,6 +688,7 @@ serve(async (req: Request) => {
documentId: purchaseInvoice.data?.id,
externalDocumentId: purchaseInvoice.data?.supplierReference,
journalLineReference,
+ companyId,
});
}
@@ -685,6 +710,7 @@ serve(async (req: Request) => {
invoiceLine.purchaseOrderLineId!
),
journalLineReference,
+ companyId,
});
// credit the accounts payable account
@@ -703,6 +729,7 @@ serve(async (req: Request) => {
invoiceLine.purchaseOrderLineId!
),
journalLineReference,
+ companyId,
});
} // if the line is associated with a purchase order line, we do accrual/reversing
else {
@@ -820,6 +847,7 @@ serve(async (req: Request) => {
)
: null,
journalLineReference,
+ companyId,
});
journalLineInserts.push({
@@ -845,6 +873,7 @@ serve(async (req: Request) => {
invoiceLine.purchaseOrderLineId!
),
journalLineReference,
+ companyId,
});
}
@@ -867,6 +896,7 @@ serve(async (req: Request) => {
cost: quantityToReverse * invoiceLineUnitPriceInInventoryUnit,
costPostedToGL:
quantityToReverse * invoiceLineUnitPriceInInventoryUnit,
+ companyId,
});
// create the normal GL entries for a part
@@ -890,6 +920,7 @@ serve(async (req: Request) => {
invoiceLine.purchaseOrderLineId!
),
journalLineReference,
+ companyId,
});
// creidt the direct cost applied account
@@ -908,6 +939,7 @@ serve(async (req: Request) => {
invoiceLine.purchaseOrderLineId!
),
journalLineReference,
+ companyId,
});
} else {
// debit the overhead account
@@ -926,6 +958,7 @@ serve(async (req: Request) => {
invoiceLine.purchaseOrderLineId!
),
journalLineReference,
+ companyId,
});
// creidt the overhead cost applied account
@@ -945,6 +978,7 @@ serve(async (req: Request) => {
invoiceLine.purchaseOrderLineId!
),
journalLineReference,
+ companyId,
});
}
@@ -966,6 +1000,7 @@ serve(async (req: Request) => {
invoiceLine.purchaseOrderLineId!
),
journalLineReference,
+ companyId,
});
// credit the accounts payable account
@@ -984,6 +1019,7 @@ serve(async (req: Request) => {
invoiceLine.purchaseOrderLineId!
),
journalLineReference,
+ companyId,
});
}
@@ -1014,6 +1050,7 @@ serve(async (req: Request) => {
)
: null,
journalLineReference,
+ companyId,
});
// credit the inventory interim accrual account
@@ -1036,6 +1073,7 @@ serve(async (req: Request) => {
)
: null,
journalLineReference,
+ companyId,
});
}
}
@@ -1076,7 +1114,11 @@ serve(async (req: Request) => {
for await (const [locationId, receiptLines] of Object.entries(
receiptLinesGroupedByLocationId
)) {
- const readableReceiptId = await getNextSequence(trx, "receipt");
+ const readableReceiptId = await getNextSequence(
+ trx,
+ "receipt",
+ companyId
+ );
const receipt = await trx
.insertInto("receipt")
.values({
@@ -1090,6 +1132,7 @@ serve(async (req: Request) => {
status: "Posted",
postingDate: today,
invoiced: true,
+ companyId,
createdBy: purchaseInvoice.data.createdBy,
})
.returning(["id"])
@@ -1178,6 +1221,7 @@ serve(async (req: Request) => {
accountingPeriodId,
description: `Purchase Invoice ${purchaseInvoice.data?.invoiceId}`,
postingDate: today,
+ companyId,
})
.returning(["id"])
.execute();
diff --git a/packages/database/supabase/functions/post-receipt/index.ts b/packages/database/supabase/functions/post-receipt/index.ts
index 1a97c80f51..deca79b0d5 100644
--- a/packages/database/supabase/functions/post-receipt/index.ts
+++ b/packages/database/supabase/functions/post-receipt/index.ts
@@ -36,6 +36,8 @@ serve(async (req: Request) => {
if (receipt.error) throw new Error("Failed to fetch receipt");
if (receiptLines.error) throw new Error("Failed to fetch receipt lines");
+ const companyId = receipt.data?.companyId;
+
const parts = await client
.from("part")
.select("id, partGroupId, partType")
@@ -47,7 +49,8 @@ serve(async (req: Request) => {
}
return acc;
}, [])
- );
+ )
+ .eq("companyId", companyId);
if (parts.error) throw new Error("Failed to fetch part groups");
switch (receipt.data?.sourceDocument) {
@@ -75,6 +78,7 @@ serve(async (req: Request) => {
.from("supplier")
.select("*")
.eq("id", purchaseOrder.data.supplierId)
+ .eq("companyId", companyId)
.single();
if (supplier.error) throw new Error("Failed to fetch supplier");
@@ -379,6 +383,7 @@ serve(async (req: Request) => {
receiptLine.lineId!
),
journalLineReference,
+ companyId,
});
journalLineInserts.push({
accountNumber: entry[1].accountNumber!,
@@ -401,6 +406,7 @@ serve(async (req: Request) => {
receiptLine.lineId!
),
journalLineReference,
+ companyId,
});
}
@@ -422,6 +428,7 @@ serve(async (req: Request) => {
quantity: quantityToReverse,
cost: reversedValue,
costPostedToGL: reversedValue,
+ companyId,
});
// create the normal GL entries
@@ -442,6 +449,7 @@ serve(async (req: Request) => {
receiptLine.lineId!
),
journalLineReference,
+ companyId,
});
// creidt the direct cost applied account
@@ -457,6 +465,7 @@ serve(async (req: Request) => {
receiptLine.lineId!
),
journalLineReference,
+ companyId,
});
} else {
// debit the overhead account
@@ -472,6 +481,7 @@ serve(async (req: Request) => {
receiptLine.lineId!
),
journalLineReference,
+ companyId,
});
// creidt the overhead cost applied account
@@ -487,6 +497,7 @@ serve(async (req: Request) => {
receiptLine.lineId!
),
journalLineReference,
+ companyId,
});
}
@@ -505,6 +516,7 @@ serve(async (req: Request) => {
receiptLine.lineId!
),
journalLineReference,
+ companyId,
});
// credit the accounts payable account
@@ -520,6 +532,7 @@ serve(async (req: Request) => {
receiptLine.lineId!
),
journalLineReference,
+ companyId,
});
}
@@ -547,6 +560,7 @@ serve(async (req: Request) => {
purchaseOrder.data?.supplierReference ?? undefined,
documentLineReference: `receipt:${receiptLine.lineId}`,
journalLineReference,
+ companyId,
});
journalLineInserts.push({
@@ -562,6 +576,7 @@ serve(async (req: Request) => {
purchaseOrder.data?.supplierReference ?? undefined,
documentLineReference: `receipt:${receiptLine.lineId}`,
journalLineReference,
+ companyId,
});
}
@@ -576,6 +591,7 @@ serve(async (req: Request) => {
documentType: "Purchase Receipt",
documentId: receipt.data?.id ?? undefined,
externalDocumentId: receipt.data?.externalDocumentId ?? undefined,
+ companyId,
});
}
}
@@ -651,6 +667,7 @@ serve(async (req: Request) => {
accountingPeriodId,
description: `Purchase Receipt ${receipt.data.receiptId}`,
postingDate: today,
+ companyId,
})
.returning(["id"])
.execute();
diff --git a/packages/database/supabase/functions/shared/get-accounting-period.ts b/packages/database/supabase/functions/shared/get-accounting-period.ts
index 93c443c59c..d2ee51becd 100644
--- a/packages/database/supabase/functions/shared/get-accounting-period.ts
+++ b/packages/database/supabase/functions/shared/get-accounting-period.ts
@@ -116,6 +116,7 @@ export async function getCurrentAccountingPeriod<T>(
// .lte("endDate", d.toString())
.gte("endDate", d)
.lte("startDate", d)
+ .eq("companyId", companyId)
.single();
if (currentAccountingPeriod.error || !currentAccountingPeriod.data) {
diff --git a/packages/database/supabase/functions/shared/get-next-sequence.ts b/packages/database/supabase/functions/shared/get-next-sequence.ts
index c2fbea619c..bc6f8187c3 100644
--- a/packages/database/supabase/functions/shared/get-next-sequence.ts
+++ b/packages/database/supabase/functions/shared/get-next-sequence.ts
@@ -2,12 +2,17 @@ import { Transaction } from "https://esm.sh/[email protected]";
import { DB } from "../lib/database.ts";
import { interpolateSequenceDate } from "../lib/utils.ts";
-export async function getNextSequence(trx: Transaction<DB>, tableName: string) {
+export async function getNextSequence(
+ trx: Transaction<DB>,
+ tableName: string,
+ companyId: number
+) {
// get current purchase invoice sequence number
const sequence = await trx
.selectFrom("sequence")
.selectAll()
.where("table", "=", tableName)
+ .where("companyId", "=", companyId)
.executeTakeFirstOrThrow();
const { prefix, suffix, next, size, step } = sequence;
@@ -27,6 +32,7 @@ export async function getNextSequence(trx: Transaction<DB>, tableName: string) {
updatedBy: "system",
})
.where("table", "=", tableName)
+ .where("companyId", "=", companyId)
.execute();
return `${derivedPrefix}${nextSequence}${derivedSuffix}`;
diff --git a/packages/database/supabase/functions/update-purchased-prices/index.ts b/packages/database/supabase/functions/update-purchased-prices/index.ts
index 222afdcbbf..87959e0489 100644
--- a/packages/database/supabase/functions/update-purchased-prices/index.ts
+++ b/packages/database/supabase/functions/update-purchased-prices/index.ts
@@ -40,17 +40,21 @@ serve(async (req: Request) => {
"yyyy-MM-dd"
);
+ const companyId = purchaseInvoice.data.companyId;
+
const [costLedgers, partSuppliers] = await Promise.all([
client
.from("costLedger")
.select("*")
.in("partId", partIds)
+ .eq("companyId", companyId)
.gte("postingDate", dateOneYearAgo),
client
.from("partSupplier")
.select("*")
.eq("supplierId", purchaseInvoice.data?.supplierId ?? "")
- .in("partId", partIds),
+ .in("partId", partIds)
+ .eq("companyId", companyId),
]);
const partCostUpdates: Database["public"]["Tables"]["partCost"]["Update"][] =
@@ -111,6 +115,7 @@ serve(async (req: Request) => {
conversionFactor: line.conversionFactor ?? 1,
supplierUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,
createdBy: "system",
+ companyId,
});
}
}
@@ -123,6 +128,7 @@ serve(async (req: Request) => {
.updateTable("partCost")
.set(partCostUpdate)
.where("partId", "=", partCostUpdate.partId!)
+ .where("companyId", "=", companyId)
.execute();
}
}