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.

feat: update purchased lead time with weighted yearly average (#623)

Siddharth Gaikwadff655604aedd
diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.ts
index cd4491d9ca..123ea0cf4b 100644
--- a/apps/erp/app/modules/settings/settings.models.ts
+++ b/apps/erp/app/modules/settings/settings.models.ts
@@ -118,6 +118,10 @@ export const purchasePriceUpdateTimingValidator = z.object({
purchasePriceUpdateTiming: z.enum(purchasePriceUpdateTimingTypes)
});
+export const updateLeadTimesOnReceiptValidator = z.object({
+ updateLeadTimesOnReceipt: zfd.checkbox()
+});
+
export const maintenanceSettingsValidator = z.object({
maintenanceGenerateInAdvance: zfd.checkbox(),
maintenanceAdvanceDays: zfd.numeric(z.number().min(1).max(90).default(7))
diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.ts
index bb26e0bc78..b35ad32c9d 100644
--- a/apps/erp/app/modules/settings/settings.service.ts
+++ b/apps/erp/app/modules/settings/settings.service.ts
@@ -889,6 +889,16 @@ export async function updatePurchasePriceUpdateTimingSetting(
.eq("id", companyId);
}
+export async function updateLeadTimesOnReceiptSetting(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ updateLeadTimesOnReceipt: boolean
+) {
+ return (client.from("companySettings") as any)
+ .update(sanitize({ updateLeadTimesOnReceipt }))
+ .eq("id", companyId);
+}
+
export async function updateSupplierApprovalSetting(
client: SupabaseClient<Database>,
companyId: string,
diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.post.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.post.tsx
index ab5daf2da2..1d8a683d9d 100644
--- a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.post.tsx
+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.post.tsx
@@ -73,7 +73,9 @@ export async function action({ request, params }: ActionFunctionArgs) {
body: {
invoiceId: invoiceId,
companyId: companyId,
- source: "purchaseInvoice"
+ source: "purchaseInvoice",
+ updatePrices: true,
+ updateLeadTimes: false
},
region: FunctionRegion.UsEast1
}
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.delete.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.delete.tsx
index 3dfad0ba81..0efb5c7cbb 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.delete.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.delete.tsx
@@ -123,6 +123,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
const remove = await deletePurchaseOrder(client, orderId);
if (remove.error) {
+ console.error("Failed to delete purchase order:", remove.error);
+
throw redirect(
path.to.purchaseOrders,
await flash(request, error(remove.error, remove.error.message))
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
index f02c5a9a8c..2e233077d9 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
@@ -186,7 +186,9 @@ export async function action(args: ActionFunctionArgs) {
body: {
purchaseOrderId: orderId,
companyId,
- source: "purchaseOrder"
+ source: "purchaseOrder",
+ updatePrices: true,
+ updateLeadTimes: false
},
region: FunctionRegion.UsEast1
}
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
index fead039dbc..e101401ac3 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx
@@ -292,7 +292,9 @@ export async function action(args: ActionFunctionArgs) {
body: {
purchaseOrderId: orderId,
companyId,
- source: "purchaseOrder"
+ source: "purchaseOrder",
+ updatePrices: true,
+ updateLeadTimes: false
},
region: FunctionRegion.UsEast1
}
diff --git a/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx b/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx
index 4c7492b721..90b187e0a9 100644
--- a/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx
+++ b/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx
@@ -34,6 +34,18 @@ export async function action({ request, params }: ActionFunctionArgs) {
try {
const serviceRole = await getCarbonServiceRole();
+
+ const receiptMetadata = await serviceRole
+ .from("receipt")
+ .select("sourceDocument,sourceDocumentId")
+ .eq("id", receiptId)
+ .single();
+
+ const companySettings = await (serviceRole.from("companySettings") as any)
+ .select("updateLeadTimesOnReceipt")
+ .eq("id", companyId)
+ .single();
+
const postReceipt = await serviceRole.functions.invoke("post-receipt", {
body: {
receiptId: receiptId,
@@ -56,6 +68,38 @@ export async function action({ request, params }: ActionFunctionArgs) {
await flash(request, error(postReceipt.error, "Failed to post receipt"))
);
}
+
+ const shouldUpdateLeadTimesOnReceipt = Boolean(
+ (companySettings.data as { updateLeadTimesOnReceipt?: boolean } | null)
+ ?.updateLeadTimesOnReceipt
+ );
+
+ if (
+ shouldUpdateLeadTimesOnReceipt &&
+ receiptMetadata.data?.sourceDocument === "Purchase Order" &&
+ receiptMetadata.data?.sourceDocumentId
+ ) {
+ const leadTimeUpdate = await serviceRole.functions.invoke(
+ "update-purchased-prices",
+ {
+ body: {
+ source: "purchaseOrder",
+ purchaseOrderId: receiptMetadata.data.sourceDocumentId,
+ companyId,
+ updatePrices: false,
+ updateLeadTimes: true
+ },
+ region: FunctionRegion.UsEast1
+ }
+ );
+
+ if (leadTimeUpdate.error) {
+ console.error(
+ "Failed to update lead time on receipt posting:",
+ leadTimeUpdate.error
+ );
+ }
+ }
// biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
} catch (error) {
await client
diff --git a/apps/erp/app/routes/x+/settings+/purchasing.tsx b/apps/erp/app/routes/x+/settings+/purchasing.tsx
index 7ceaeee2bb..47d5bfb5cf 100644
--- a/apps/erp/app/routes/x+/settings+/purchasing.tsx
+++ b/apps/erp/app/routes/x+/settings+/purchasing.tsx
@@ -43,6 +43,7 @@ import {
updateAccountsPayableAddressSetting,
updateAccountsPayableBillingAddress,
updateDefaultSupplierCc,
+ updateLeadTimesOnReceiptSetting,
updatePurchasePriceUpdateTimingSetting,
updatePurchasingPdfThumbnails,
updateSupplierApprovalSetting,
@@ -110,6 +111,10 @@ export async function action({ request }: ActionFunctionArgs) {
);
if (supplierApprovalResult.error) {
+ console.error(
+ "Failed to update supplier approval setting:",
+ supplierApprovalResult.error
+ );
return {
success: false,
message: supplierApprovalResult.error.message
@@ -129,7 +134,14 @@ export async function action({ request }: ActionFunctionArgs) {
apToggleEnabled
);
if (apToggleResult.error) {
- return { success: false, message: apToggleResult.error.message };
+ console.error(
+ "Failed to update accounts payable address toggle:",
+ apToggleResult.error
+ );
+ return {
+ success: false,
+ message: apToggleResult.error.message
+ };
}
return {
success: true,
@@ -152,7 +164,14 @@ export async function action({ request }: ActionFunctionArgs) {
);
if (result.error) {
- return { success: false, message: result.error.message };
+ console.error(
+ "Failed to update purchase price timing setting:",
+ result.error
+ );
+ return {
+ success: false,
+ message: result.error.message
+ };
}
return {
@@ -160,6 +179,30 @@ export async function action({ request }: ActionFunctionArgs) {
message: "Purchase price update timing updated"
};
+ case "updateLeadTimesOnReceipt":
+ const updateLeadTimesOnReceipt = formData.get("enabled") === "true";
+ const updateLeadTimesResult = await updateLeadTimesOnReceiptSetting(
+ client,
+ companyId,
+ updateLeadTimesOnReceipt
+ );
+
+ if (updateLeadTimesResult.error) {
+ console.error(
+ "Failed to update lead-time-on-receipt setting:",
+ updateLeadTimesResult.error
+ );
+ return {
+ success: false,
+ message: updateLeadTimesResult.error.message
+ };
+ }
+
+ return {
+ success: true,
+ message: `Lead time updates on receipt ${updateLeadTimesOnReceipt ? "enabled" : "disabled"}`
+ };
+
case "supplierQuoteNotification":
const supplierQuoteValidation = await validator(
supplierQuoteNotificationValidator
@@ -176,7 +219,14 @@ export async function action({ request }: ActionFunctionArgs) {
);
if (supplierQuoteResult.error) {
- return { success: false, message: supplierQuoteResult.error.message };
+ console.error(
+ "Failed to update supplier quote notification setting:",
+ supplierQuoteResult.error
+ );
+ return {
+ success: false,
+ message: supplierQuoteResult.error.message
+ };
}
return {
@@ -193,7 +243,10 @@ export async function action({ request }: ActionFunctionArgs) {
);
if (thumbnailsResult.error)
- return { success: false, message: thumbnailsResult.error.message };
+ return {
+ success: false,
+ message: thumbnailsResult.error.message
+ };
return { success: true, message: "PDF settings updated" };
}
@@ -215,7 +268,14 @@ export async function action({ request }: ActionFunctionArgs) {
);
if (apBillingResult.error) {
- return { success: false, message: apBillingResult.error.message };
+ console.error(
+ "Failed to update accounts payable billing address:",
+ apBillingResult.error
+ );
+ return {
+ success: false,
+ message: apBillingResult.error.message
+ };
}
return {
@@ -239,6 +299,10 @@ export async function action({ request }: ActionFunctionArgs) {
);
if (defaultSupplierCcResult.error) {
+ console.error(
+ "Failed to update default supplier CC:",
+ defaultSupplierCcResult.error
+ );
return {
success: false,
message: defaultSupplierCcResult.error.message
@@ -296,6 +360,11 @@ export default function PurchasingSettingsRoute() {
companySettings.accountsPayableAddress ?? false
);
+ const [leadTimesOnReceiptEnabled, setLeadTimesOnReceiptEnabled] = useState(
+ (companySettings as { updateLeadTimesOnReceipt?: boolean })
+ .updateLeadTimesOnReceipt ?? false
+ );
+
const handleApAddressToggle = useCallback(
(checked: boolean) => {
setApAddressEnabled(checked);
@@ -307,6 +376,20 @@ export default function PurchasingSettingsRoute() {
[toggleFetcher]
);
+ const handleLeadTimesOnReceiptToggle = useCallback(
+ (checked: boolean) => {
+ setLeadTimesOnReceiptEnabled(checked);
+ toggleFetcher.submit(
+ {
+ intent: "updateLeadTimesOnReceipt",
+ enabled: checked.toString()
+ },
+ { method: "POST" }
+ );
+ },
+ [toggleFetcher]
+ );
+
useEffect(() => {
if (toggleFetcher.data?.success === true && toggleFetcher?.data?.message) {
toast.success(toggleFetcher.data.message);
@@ -513,6 +596,23 @@ export default function PurchasingSettingsRoute() {
</CardFooter>
</ValidatedForm>
</Card>
+ <Card>
+ <CardHeader>
+ <HStack className="justify-between items-center">
+ <div>
+ <CardTitle>Lead Time Updates</CardTitle>
+ <CardDescription>
+ Update part lead times from posted purchase receipts.
+ </CardDescription>
+ </div>
+ <Switch
+ checked={leadTimesOnReceiptEnabled}
+ onCheckedChange={handleLeadTimesOnReceiptToggle}
+ disabled={toggleFetcher.state !== "idle"}
+ />
+ </HStack>
+ </CardHeader>
+ </Card>
<Card>
<CardHeader>
<HStack className="justify-between items-center">
diff --git a/packages/database/supabase/functions/update-purchased-prices/index.ts b/packages/database/supabase/functions/update-purchased-prices/index.ts
index 577a1aa0e3..6ca0d19bef 100644
--- a/packages/database/supabase/functions/update-purchased-prices/index.ts
+++ b/packages/database/supabase/functions/update-purchased-prices/index.ts
@@ -15,11 +15,15 @@ const payloadValidator = z.discriminatedUnion("source", [
source: z.literal("purchaseOrder"),
purchaseOrderId: z.string(),
companyId: z.string(),
+ updatePrices: z.boolean().optional(),
+ updateLeadTimes: z.boolean().optional(),
}),
z.object({
source: z.literal("purchaseInvoice"),
invoiceId: z.string(),
companyId: z.string(),
+ updatePrices: z.boolean().optional(),
+ updateLeadTimes: z.boolean().optional(),
}),
]);
@@ -32,18 +36,37 @@ interface PurchaseLineData {
purchaseUnitOfMeasureCode: string | null;
}
+const millisecondsInADay = 1000 * 60 * 60 * 24;
+
+const calculateLeadTimeInDays = (
+ orderDate: string,
+ deliveryDate: string
+): number => {
+ const orderDateTime = new Date(`${orderDate}T00:00:00Z`).getTime();
+ const deliveryDateTime = new Date(`${deliveryDate}T00:00:00Z`).getTime();
+
+ if (isNaN(orderDateTime) || isNaN(deliveryDateTime)) return 0;
+
+ return Math.max(0, (deliveryDateTime - orderDateTime) / millisecondsInADay);
+};
+
serve(async (req: Request) => {
if (req.method === "OPTIONS") {
return new Response("ok", { headers: corsHeaders });
}
const payload = await req.json();
- const { source, companyId } = payloadValidator.parse(payload);
+ const parsedPayload = payloadValidator.parse(payload);
+ const { source, companyId } = parsedPayload;
+ const shouldUpdatePrices = parsedPayload.updatePrices ?? true;
+ const shouldUpdateLeadTimes = parsedPayload.updateLeadTimes ?? false;
console.log({
function: "update-purchased-prices",
source,
companyId,
+ shouldUpdatePrices,
+ shouldUpdateLeadTimes,
});
try {
@@ -58,7 +81,7 @@ serve(async (req: Request) => {
switch (source) {
case "purchaseOrder": {
- const { purchaseOrderId } = payload;
+ const { purchaseOrderId } = parsedPayload;
console.log({
function: "update-purchased-prices",
@@ -96,41 +119,43 @@ serve(async (req: Request) => {
conversionFactor: line.conversionFactor,
purchaseUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,
}))
- .filter((line) => line.unitPrice !== 0 && line.quantity > 0);
-
- // Delete any existing cost ledger entries for this PO (handles re-finalization)
- await db
- .deleteFrom("costLedger")
- .where("documentType", "=", "Purchase Order")
- .where("documentId", "=", purchaseOrderId)
- .where("companyId", "=", companyId)
- .execute();
+ .filter((line) => line.quantity > 0);
+
+ if (shouldUpdatePrices) {
+ // Delete any existing cost ledger entries for this PO (handles re-finalization)
+ await db
+ .deleteFrom("costLedger")
+ .where("documentType", "=", "Purchase Order")
+ .where("documentId", "=", purchaseOrderId)
+ .where("companyId", "=", companyId)
+ .execute();
- // Create new cost ledger entries for each line item
- const costLedgerInserts = lines
- .filter((line) => line.itemId)
- .map((line) => ({
- itemLedgerType: "Purchase" as const,
- costLedgerType: "Direct Cost" as const,
- adjustment: false,
- documentType: "Purchase Order" as const,
- documentId: purchaseOrderId,
- itemId: line.itemId!,
- quantity: line.quantity,
- cost: line.quantity * line.unitPrice,
- supplierId,
- companyId,
- }));
-
- if (costLedgerInserts.length > 0) {
- await db.insertInto("costLedger").values(costLedgerInserts).execute();
+ // Create new cost ledger entries for each line item
+ const costLedgerInserts = lines
+ .filter((line) => line.itemId && line.unitPrice !== 0)
+ .map((line) => ({
+ itemLedgerType: "Purchase" as const,
+ costLedgerType: "Direct Cost" as const,
+ adjustment: false,
+ documentType: "Purchase Order" as const,
+ documentId: purchaseOrderId,
+ itemId: line.itemId!,
+ quantity: line.quantity,
+ cost: line.quantity * line.unitPrice,
+ supplierId,
+ companyId,
+ }));
+
+ if (costLedgerInserts.length > 0) {
+ await db.insertInto("costLedger").values(costLedgerInserts).execute();
+ }
}
break;
}
case "purchaseInvoice": {
- const { invoiceId } = payload;
+ const { invoiceId } = parsedPayload;
console.log({
function: "update-purchased-prices",
@@ -168,35 +193,24 @@ serve(async (req: Request) => {
conversionFactor: line.conversionFactor,
purchaseUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,
}))
- .filter((line) => line.unitPrice !== 0);
+ .filter((line) => line.quantity > 0);
break;
}
}
- const itemIds = lines
- .filter((line) => Boolean(line.itemId))
- .map((line) => line.itemId) as string[];
+ const itemIds = Array.from(
+ new Set(
+ lines
+ .filter((line) => Boolean(line.itemId))
+ .map((line) => line.itemId as string)
+ )
+ );
const dateOneYearAgo = format(
new Date(new Date().setFullYear(new Date().getFullYear() - 1)),
"yyyy-MM-dd"
);
- const [costLedgers, supplierParts] = await Promise.all([
- client
- .from("costLedger")
- .select("*")
- .in("itemId", itemIds)
- .eq("companyId", companyId)
- .gte("postingDate", dateOneYearAgo),
- client
- .from("supplierPart")
- .select("*")
- .eq("supplierId", supplierId)
- .in("itemId", itemIds)
- .eq("companyId", companyId),
- ]);
-
const itemCostUpdates: Database["public"]["Tables"]["itemCost"]["Update"][] =
[];
const itemReplenishmentUpdates: Database["public"]["Tables"]["itemReplenishment"]["Update"][] =
@@ -213,69 +227,220 @@ serve(async (req: Request) => {
string,
{ quantity: number; cost: number }
> = {};
+ const historicalPartLeadTimes: Record<
+ string,
+ { quantity: number; weightedLeadTime: number }
+ > = {};
+
+ let supplierPartRows: Database["public"]["Tables"]["supplierPart"]["Row"][] =
+ [];
+
+ if (shouldUpdatePrices && itemIds.length > 0) {
+ const [costLedgers, supplierParts] = await Promise.all([
+ client
+ .from("costLedger")
+ .select("*")
+ .in("itemId", itemIds)
+ .eq("companyId", companyId)
+ .gte("postingDate", dateOneYearAgo),
+ client
+ .from("supplierPart")
+ .select("*")
+ .eq("supplierId", supplierId)
+ .in("itemId", itemIds)
+ .eq("companyId", companyId),
+ ]);
+
+ if (costLedgers.error) {
+ throw new Error("Failed to fetch historical cost ledger entries");
+ }
+ if (supplierParts.error) {
+ throw new Error("Failed to fetch supplier parts");
+ }
- costLedgers.data?.forEach((ledger) => {
- if (ledger.itemId) {
- if (!historicalPartCosts[ledger.itemId]) {
- historicalPartCosts[ledger.itemId] = {
- quantity: 0,
- cost: 0,
- };
+ supplierPartRows = supplierParts.data ?? [];
+
+ costLedgers.data?.forEach((ledger) => {
+ if (ledger.itemId) {
+ if (!historicalPartCosts[ledger.itemId]) {
+ historicalPartCosts[ledger.itemId] = {
+ quantity: 0,
+ cost: 0,
+ };
+ }
+
+ historicalPartCosts[ledger.itemId].quantity += ledger.quantity;
+ historicalPartCosts[ledger.itemId].cost += ledger.cost;
}
+ });
+ }
- historicalPartCosts[ledger.itemId].quantity += ledger.quantity;
- historicalPartCosts[ledger.itemId].cost += ledger.cost;
+ if (shouldUpdateLeadTimes && itemIds.length > 0) {
+ const receipts = await client
+ .from("receipt")
+ .select("id,postingDate,sourceDocumentId")
+ .eq("companyId", companyId)
+ .eq("sourceDocument", "Purchase Order")
+ .not("postingDate", "is", null)
+ .gte("postingDate", dateOneYearAgo);
+
+ if (receipts.error) {
+ throw new Error("Failed to fetch historical receipts");
}
- });
- lines.forEach((line) => {
- if (
- line.itemId &&
- !line.jobOperationId &&
- historicalPartCosts[line.itemId]
- ) {
- itemCostUpdates.push({
- itemId: line.itemId,
- unitCost:
- historicalPartCosts[line.itemId].cost /
- historicalPartCosts[line.itemId].quantity,
- updatedBy: "system",
+ const receiptIds = receipts.data?.map((receipt) => receipt.id) ?? [];
+ const purchaseOrderIds = Array.from(
+ new Set(
+ (receipts.data ?? [])
+ .map((receipt) => receipt.sourceDocumentId)
+ .filter((id): id is string => Boolean(id))
+ )
+ );
+
+ if (receiptIds.length > 0 && purchaseOrderIds.length > 0) {
+ const [receiptLines, purchaseOrders] = await Promise.all([
+ client
+ .from("receiptLine")
+ .select("receiptId,itemId,receivedQuantity,conversionFactor")
+ .in("receiptId", receiptIds)
+ .in("itemId", itemIds)
+ .eq("companyId", companyId),
+ client
+ .from("purchaseOrder")
+ .select("id,orderDate")
+ .in("id", purchaseOrderIds)
+ .eq("companyId", companyId),
+ ]);
+
+ if (receiptLines.error) {
+ throw new Error("Failed to fetch historical receipt lines");
+ }
+ if (purchaseOrders.error) {
+ throw new Error("Failed to fetch historical purchase orders");
+ }
+
+ const receiptsById = (receipts.data ?? []).reduce<
+ Record<string, { postingDate: string; sourceDocumentId: string | null }>
+ >((acc, receipt) => {
+ if (receipt.postingDate) {
+ acc[receipt.id] = {
+ postingDate: receipt.postingDate,
+ sourceDocumentId: receipt.sourceDocumentId,
+ };
+ }
+ return acc;
+ }, {});
+
+ const purchaseOrdersById = purchaseOrders.data.reduce<
+ Record<string, { orderDate: string | null }>
+ >((acc, row) => {
+ acc[row.id] = { orderDate: row.orderDate };
+ return acc;
+ }, {});
+
+ receiptLines.data.forEach((line) => {
+ if (!line.itemId) return;
+
+ const receipt = receiptsById[line.receiptId];
+ if (!receipt?.sourceDocumentId) return;
+
+ const orderDate =
+ purchaseOrdersById[receipt.sourceDocumentId]?.orderDate;
+ if (!orderDate || !receipt.postingDate) return;
+
+ const safeConversionFactor =
+ line.conversionFactor && line.conversionFactor > 0
+ ? line.conversionFactor
+ : 1;
+ const quantity = Math.abs(
+ (line.receivedQuantity ?? 0) / safeConversionFactor
+ );
+ if (quantity <= 0) return;
+
+ const leadTimeInDays = calculateLeadTimeInDays(
+ orderDate,
+ receipt.postingDate
+ );
+
+ if (!historicalPartLeadTimes[line.itemId]) {
+ historicalPartLeadTimes[line.itemId] = {
+ quantity: 0,
+ weightedLeadTime: 0,
+ };
+ }
+
+ historicalPartLeadTimes[line.itemId].quantity += quantity;
+ historicalPartLeadTimes[line.itemId].weightedLeadTime +=
+ leadTimeInDays * quantity;
});
+ }
+ }
- const supplierPart = supplierParts.data?.find(
- (sp) => sp.itemId === line.itemId && sp.supplierId === supplierId
- );
+ lines.forEach((line) => {
+ if (line.itemId && !line.jobOperationId) {
+ const costHistory = historicalPartCosts[line.itemId];
+ const hasLeadTimeHistory =
+ (historicalPartLeadTimes[line.itemId]?.quantity ?? 0) > 0;
- if (supplierPart && supplierPart.id) {
- supplierPartUpdates.push({
- id: supplierPart.id,
- unitPrice: line.unitPrice,
- conversionFactor: line.conversionFactor ?? 1,
- supplierUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,
- updatedBy: "system",
- });
- } else {
- supplierPartInserts.push({
+ if (shouldUpdatePrices && line.unitPrice !== 0 && costHistory) {
+ itemCostUpdates.push({
itemId: line.itemId,
- supplierId: supplierId,
- unitPrice: line.unitPrice,
- conversionFactor: line.conversionFactor ?? 1,
- supplierUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,
- createdBy: "system",
- companyId,
+ unitCost: costHistory.cost / costHistory.quantity,
+ updatedBy: "system",
});
+
+ const supplierPart = supplierPartRows.find(
+ (sp) => sp.itemId === line.itemId && sp.supplierId === supplierId
+ );
+
+ if (supplierPart && supplierPart.id) {
+ supplierPartUpdates.push({
+ id: supplierPart.id,
+ unitPrice: line.unitPrice,
+ conversionFactor: line.conversionFactor ?? 1,
+ supplierUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,
+ updatedBy: "system",
+ });
+ } else {
+ supplierPartInserts.push({
+ itemId: line.itemId,
+ supplierId: supplierId,
+ unitPrice: line.unitPrice,
+ conversionFactor: line.conversionFactor ?? 1,
+ supplierUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,
+ createdBy: "system",
+ companyId,
+ });
+ }
}
- itemReplenishmentUpdates.push({
- itemId: line.itemId,
- preferredSupplierId: supplierId,
- purchasingUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,
- conversionFactor: line.conversionFactor ?? 1,
- updatedBy: "system",
- });
+ if (shouldUpdatePrices || (shouldUpdateLeadTimes && hasLeadTimeHistory)) {
+ const itemReplenishmentUpdate: Database["public"]["Tables"]["itemReplenishment"]["Update"] =
+ {
+ itemId: line.itemId,
+ updatedBy: "system",
+ };
+
+ if (shouldUpdatePrices) {
+ itemReplenishmentUpdate.preferredSupplierId = supplierId;
+ itemReplenishmentUpdate.purchasingUnitOfMeasureCode =
+ line.purchaseUnitOfMeasureCode;
+ itemReplenishmentUpdate.conversionFactor =
+ line.conversionFactor ?? 1;
+ }
+
+ if (shouldUpdateLeadTimes && hasLeadTimeHistory) {
+ itemReplenishmentUpdate.leadTime = Math.round(
+ historicalPartLeadTimes[line.itemId].weightedLeadTime /
+ historicalPartLeadTimes[line.itemId].quantity
+ );
+ }
+
+ itemReplenishmentUpdates.push(itemReplenishmentUpdate);
+ }
}
- if (line.jobOperationId) {
+ if (shouldUpdatePrices && line.jobOperationId && line.unitPrice !== 0) {
jobOperationUpdates.push({
id: line.jobOperationId,
operationMinimumCost: 0,
diff --git a/packages/database/supabase/migrations/20260401120000_lead-time-receipt-setting.sql b/packages/database/supabase/migrations/20260401120000_lead-time-receipt-setting.sql
new file mode 100644
index 0000000000..ce9ab9b033
--- /dev/null
+++ b/packages/database/supabase/migrations/20260401120000_lead-time-receipt-setting.sql
@@ -0,0 +1,2 @@
+ALTER TABLE "companySettings"
+ADD COLUMN IF NOT EXISTS "updateLeadTimesOnReceipt" BOOLEAN NOT NULL DEFAULT false;
\ No newline at end of file
diff --git a/packages/jobs/trigger/post-transaction.ts b/packages/jobs/trigger/post-transaction.ts
index c7a12198c4..daacd98588 100644
--- a/packages/jobs/trigger/post-transaction.ts
+++ b/packages/jobs/trigger/post-transaction.ts
@@ -82,6 +82,8 @@ export const postTransactionTask = task({
invoiceId: payload.documentId,
companyId: payload.companyId,
source: "purchaseInvoice",
+ updatePrices: true,
+ updateLeadTimes: false,
},
}
);