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: add backflush job materials migration and update order line pricing

Brad Barbin716521c281a7
diff --git a/.gitignore b/.gitignore
index cdaacc524a..2e5134264b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -52,4 +52,5 @@ packages/database/supabase/seed.sql
# C++ (cad-engine)
**/build/
!**/build/.gitkeep
-.orcka
\ No newline at end of file
+.orcka
+.superpowers
\ No newline at end of file
diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.ts
index 43e1793ad7..83ed7d0274 100644
--- a/apps/erp/app/modules/invoicing/invoicing.service.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts
@@ -384,6 +384,7 @@ export async function upsertPurchaseInvoice(
| (Omit<z.infer<typeof purchaseInvoiceValidator>, "id" | "invoiceId"> & {
invoiceId: string;
companyId: string;
+ companyGroupId: string;
createdBy: string;
customFields?: Json;
})
@@ -433,7 +434,7 @@ export async function upsertPurchaseInvoice(
if (purchaseInvoice.currencyCode) {
const currency = await getCurrencyByCode(
client,
- purchaseInvoice.companyId,
+ purchaseInvoice.companyGroupId,
purchaseInvoice.currencyCode
);
if (currency.data) {
@@ -448,11 +449,14 @@ export async function upsertPurchaseInvoice(
const locationId =
purchaseInvoice.locationId ?? purchaser?.data?.locationId ?? null;
+ const { companyGroupId: _companyGroupId, ...purchaseInvoiceData } =
+ purchaseInvoice;
+
const invoice = await client
.from("purchaseInvoice")
.insert([
{
- ...purchaseInvoice,
+ ...purchaseInvoiceData,
invoiceSupplierId: invoiceSupplierId ?? purchaseInvoice.supplierId,
supplierInteractionId: supplierInteraction.data?.id,
currencyCode: purchaseInvoice.currencyCode ?? "USD",
@@ -550,6 +554,7 @@ export async function upsertSalesInvoice(
| (Omit<z.infer<typeof salesInvoiceValidator>, "id" | "invoiceId"> & {
invoiceId: string;
companyId: string;
+ companyGroupId: string;
createdBy: string;
customFields?: Json;
})
@@ -599,7 +604,7 @@ export async function upsertSalesInvoice(
if (salesInvoice.currencyCode) {
const currency = await getCurrencyByCode(
client,
- salesInvoice.companyId,
+ salesInvoice.companyGroupId,
salesInvoice.currencyCode
);
if (currency.data) {
@@ -614,11 +619,13 @@ export async function upsertSalesInvoice(
const locationId =
salesInvoice.locationId ?? salesPerson?.data?.locationId ?? null;
+ const { companyGroupId: _companyGroupId, ...salesInvoiceData } = salesInvoice;
+
const invoice = await client
.from("salesInvoice")
.insert([
{
- ...salesInvoice,
+ ...salesInvoiceData,
invoiceCustomerId: invoiceCustomerId ?? salesInvoice.customerId,
opportunityId: opportunity.data?.id,
currencyCode: salesInvoice.currencyCode ?? "USD",
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index 154e444ace..55d4a90004 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -1289,6 +1289,7 @@ export async function upsertPurchaseOrder(
purchaseOrderId: string;
status?: (typeof purchaseOrderStatusType)[number];
companyId: string;
+ companyGroupId: string;
createdBy: string;
customFields?: Json;
})
@@ -1340,7 +1341,7 @@ export async function upsertPurchaseOrder(
if (purchaseOrder.currencyCode) {
const currency = await getCurrencyByCode(
client,
- purchaseOrder.companyId,
+ purchaseOrder.companyGroupId,
purchaseOrder.currencyCode
);
if (currency.data) {
@@ -1356,7 +1357,11 @@ export async function upsertPurchaseOrder(
purchaseOrder.locationId ?? purchaser?.data?.locationId ?? null;
// locationId is not a column on purchaseOrder -- it belongs on the delivery record
- const { locationId: _locationId, ...purchaseOrderData } = purchaseOrder;
+ const {
+ locationId: _locationId,
+ companyGroupId: _companyGroupId,
+ ...purchaseOrderData
+ } = purchaseOrder;
const order = await client
.from("purchaseOrder")
@@ -1566,6 +1571,7 @@ export async function upsertSupplierQuote(
> & {
supplierQuoteId: string;
companyId: string;
+ companyGroupId: string;
createdBy: string;
customFields?: Json;
})
@@ -1575,6 +1581,7 @@ export async function upsertSupplierQuote(
> & {
id: string;
supplierQuoteId: string;
+ companyGroupId: string;
updatedBy: string;
customFields?: Json;
})
@@ -1583,7 +1590,7 @@ export async function upsertSupplierQuote(
if (supplierQuote.currencyCode) {
const currency = await getCurrencyByCode(
client,
- supplierQuote.companyId,
+ supplierQuote.companyGroupId,
supplierQuote.currencyCode
);
if (currency.data) {
@@ -1603,12 +1610,14 @@ export async function upsertSupplierQuote(
if (supplierInteraction.error) return supplierInteraction;
+ const { companyGroupId: _companyGroupId, ...supplierQuoteData } =
+ supplierQuote;
const insert = await client
.from("supplierQuote")
.insert([
{
- ...supplierQuote,
- status: supplierQuote.status ?? "Draft",
+ ...supplierQuoteData,
+ status: supplierQuoteData.status ?? "Draft",
supplierInteractionId: supplierInteraction.data?.id
}
])
@@ -1649,17 +1658,13 @@ export async function upsertSupplierQuote(
// Only update the exchange rate if the currency code has changed
const existingQuote = await client
.from("supplierQuote")
- .select("companyId, currencyCode, status")
+ .select("currencyCode, status")
.eq("id", supplierQuote.id)
.single();
if (existingQuote.error) return existingQuote;
- const {
- companyId,
- currencyCode,
- status: existingStatus
- } = existingQuote.data;
+ const { currencyCode, status: existingStatus } = existingQuote.data;
if (
supplierQuote.currencyCode &&
@@ -1667,7 +1672,7 @@ export async function upsertSupplierQuote(
) {
const currency = await getCurrencyByCode(
client,
- companyId,
+ supplierQuote.companyGroupId,
supplierQuote.currencyCode
);
if (currency.data) {
@@ -1675,10 +1680,12 @@ export async function upsertSupplierQuote(
supplierQuote.exchangeRateUpdatedAt = new Date().toISOString();
}
}
+ const { companyGroupId: _companyGroupId2, ...supplierQuoteUpdateData } =
+ supplierQuote;
return client
.from("supplierQuote")
.update({
- ...sanitize(supplierQuote),
+ ...sanitize(supplierQuoteUpdateData),
status:
supplierQuote.expirationDate &&
today(getLocalTimeZone()).toString() > supplierQuote.expirationDate
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index 7b307c8921..514de51692 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -3314,12 +3314,14 @@ export async function upsertQuote(
| (Omit<z.infer<typeof quoteValidator>, "id" | "quoteId"> & {
quoteId: string;
companyId: string;
+ companyGroupId: string;
createdBy: string;
customFields?: Json;
})
| (Omit<z.infer<typeof quoteValidator>, "id" | "quoteId"> & {
id: string;
quoteId: string;
+ companyGroupId: string;
updatedBy: string;
customFields?: Json;
})
@@ -3355,7 +3357,7 @@ export async function upsertQuote(
if (quote.currencyCode) {
const currency = await getCurrencyByCode(
client,
- quote.companyId,
+ quote.companyGroupId,
quote.currencyCode
);
if (currency.data) {
@@ -3368,11 +3370,12 @@ export async function upsertQuote(
}
const locationId = employee?.data?.locationId ?? null;
+ const { companyGroupId: _companyGroupId, ...quoteData } = quote;
const insert = await client
.from("quote")
.insert([
{
- ...quote,
+ ...quoteData,
opportunityId: opportunity.data?.id
}
])
@@ -3445,12 +3448,12 @@ export async function upsertQuote(
if (existingQuote.error) return existingQuote;
- const { companyId, currencyCode, opportunityId } = existingQuote.data;
+ const { currencyCode, opportunityId } = existingQuote.data;
if (quote.currencyCode && currencyCode !== quote.currencyCode) {
const currency = await getCurrencyByCode(
client,
- companyId,
+ quote.companyGroupId,
quote.currencyCode
);
if (currency.data) {
@@ -3467,10 +3470,11 @@ export async function upsertQuote(
.eq("id", opportunityId);
}
+ const { companyGroupId: _cgId, ...quoteUpdateData } = quote;
return client
.from("quote")
.update({
- ...sanitize(quote),
+ ...sanitize(quoteUpdateData),
updatedAt: today(getLocalTimeZone()).toString()
})
.eq("id", quote.id);
@@ -4625,12 +4629,14 @@ export async function upsertSalesOrder(
| (Omit<z.infer<typeof salesOrderValidator>, "id" | "salesOrderId"> & {
salesOrderId: string;
companyId: string;
+ companyGroupId: string;
createdBy: string;
customFields?: Json;
})
| (Omit<z.infer<typeof salesOrderValidator>, "id" | "salesOrderId"> & {
id: string;
salesOrderId: string;
+ companyGroupId: string;
updatedBy: string;
customFields?: Json;
})
@@ -4645,12 +4651,12 @@ export async function upsertSalesOrder(
if (existingSalesOrder.error) return existingSalesOrder;
- const { companyId, currencyCode, opportunityId } = existingSalesOrder.data;
+ const { currencyCode, opportunityId } = existingSalesOrder.data;
if (salesOrder.currencyCode && currencyCode !== salesOrder.currencyCode) {
const currency = await getCurrencyByCode(
client,
- companyId,
+ salesOrder.companyGroupId,
salesOrder.currencyCode
);
if (currency.data) {
@@ -4667,9 +4673,10 @@ export async function upsertSalesOrder(
.eq("id", opportunityId);
}
+ const { companyGroupId: _cgId, ...salesOrderUpdateData } = salesOrder;
return client
.from("salesOrder")
- .update(sanitize(salesOrder))
+ .update(sanitize(salesOrderUpdateData))
.eq("id", salesOrder.id)
.select("id, salesOrderId");
}
@@ -4709,7 +4716,7 @@ export async function upsertSalesOrder(
if (salesOrder.currencyCode) {
const currency = await getCurrencyByCode(
client,
- salesOrder.companyId,
+ salesOrder.companyGroupId,
salesOrder.currencyCode
);
if (currency.data) {
@@ -4721,7 +4728,12 @@ export async function upsertSalesOrder(
salesOrder.exchangeRateUpdatedAt = new Date().toISOString();
}
- const { requestedDate, promisedDate, ...orderData } = salesOrder;
+ const {
+ requestedDate,
+ promisedDate,
+ companyGroupId: _companyGroupId,
+ ...orderData
+ } = salesOrder;
const order = await client
.from("salesOrder")
diff --git a/apps/erp/app/routes/api+/ai+/chat+/_index.ts b/apps/erp/app/routes/api+/ai+/chat+/_index.ts
index 814240ff2a..9a97d53517 100644
--- a/apps/erp/app/routes/api+/ai+/chat+/_index.ts
+++ b/apps/erp/app/routes/api+/ai+/chat+/_index.ts
@@ -5,7 +5,8 @@ import { orchestrationAgent } from "./agents/orchestration-agent";
import { createChatContext } from "./agents/shared/context";
export async function action({ request }: ActionFunctionArgs) {
- const { client, userId, companyId } = await requirePermissions(request, {});
+ const { client, userId, companyId, companyGroupId } =
+ await requirePermissions(request, {});
const payload = await request.json();
@@ -26,6 +27,7 @@ export async function action({ request }: ActionFunctionArgs) {
const context = createChatContext({
userId,
companyId,
+ companyGroupId,
client,
fullName,
companyName,
diff --git a/apps/erp/app/routes/api+/ai+/chat+/agents/shared/context.ts b/apps/erp/app/routes/api+/ai+/chat+/agents/shared/context.ts
index 436b9191db..f80551ed88 100644
--- a/apps/erp/app/routes/api+/ai+/chat+/agents/shared/context.ts
+++ b/apps/erp/app/routes/api+/ai+/chat+/agents/shared/context.ts
@@ -5,6 +5,7 @@ export interface ChatContext {
client: SupabaseClient<Database>;
userId: string;
companyId: string;
+ companyGroupId: string;
fullName: string;
companyName: string;
baseCurrency: string;
@@ -21,6 +22,7 @@ export interface ChatContext {
export function createChatContext(params: {
userId: string;
companyId: string;
+ companyGroupId: string;
client: SupabaseClient<Database>;
fullName: string;
companyName: string;
@@ -34,6 +36,7 @@ export function createChatContext(params: {
return {
userId: params.userId,
companyId: params.companyId,
+ companyGroupId: params.companyGroupId,
client: params.client,
fullName: params.fullName,
companyName: params.companyName,
diff --git a/apps/erp/app/routes/api+/ai+/chat+/tools/create-purchase-order.server.ts b/apps/erp/app/routes/api+/ai+/chat+/tools/create-purchase-order.server.ts
index 4a5c50a3bd..edbe47a088 100644
--- a/apps/erp/app/routes/api+/ai+/chat+/tools/create-purchase-order.server.ts
+++ b/apps/erp/app/routes/api+/ai+/chat+/tools/create-purchase-order.server.ts
@@ -94,7 +94,7 @@ export const createPurchaseOrderTool = tool({
if (supplier.data?.currencyCode) {
const currency = await getCurrencyByCode(
context.client,
- context.companyId,
+ context.companyGroupId,
supplier.data?.currencyCode ?? ""
);
if (currency.data) {
diff --git a/apps/erp/app/routes/api+/kanban.$id.tsx b/apps/erp/app/routes/api+/kanban.$id.tsx
index 0354876505..79563369ff 100644
--- a/apps/erp/app/routes/api+/kanban.$id.tsx
+++ b/apps/erp/app/routes/api+/kanban.$id.tsx
@@ -30,11 +30,13 @@ import { path } from "~/utils/path";
async function handleKanban({
client,
companyId,
+ companyGroupId,
userId,
id
}: {
client: SupabaseClient<Database>;
companyId: string;
+ companyGroupId: string;
userId: string;
id: string;
}): Promise<{ data: string; error: null } | { data: null; error: string }> {
@@ -262,6 +264,7 @@ async function handleKanban({
status: "Draft",
purchaseOrderType: "Purchase",
companyId,
+ companyGroupId,
createdBy: userId
});
@@ -361,12 +364,13 @@ async function handleKanban({
}
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client, companyId, userId } = await requirePermissions(request, {});
+ const { client, companyId, companyGroupId, userId } =
+ await requirePermissions(request, {});
const { id } = params;
if (!id) throw notFound("id not found");
- return await handleKanban({ client, companyId, userId, id });
+ return await handleKanban({ client, companyId, companyGroupId, userId, id });
}
export default function KanbanRedirectRoute() {
diff --git a/apps/erp/app/routes/api+/mcp+/_index.ts b/apps/erp/app/routes/api+/mcp+/_index.ts
index eb5e74bd8c..02ce0fe282 100644
--- a/apps/erp/app/routes/api+/mcp+/_index.ts
+++ b/apps/erp/app/routes/api+/mcp+/_index.ts
@@ -21,10 +21,11 @@ export async function action({ request }: ActionFunctionArgs) {
console.log("[MCP] Added carbon-key header from Bearer token");
}
- const { client, companyId, userId } = await requirePermissions(request, {});
+ const { client, companyId, companyGroupId, userId } =
+ await requirePermissions(request, {});
console.log("[MCP] Auth successful:", { companyId, userId });
- const server = createMcpServer({ client, companyId, userId });
+ const server = createMcpServer({ client, companyId, companyGroupId, userId });
const transport = new WebStandardStreamableHTTPServerTransport({
sessionIdGenerator: undefined,
enableJsonResponse: true
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index dd51c60133..d8e858de61 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,5 +1,5 @@
{
- "generated": "2026-05-11T11:51:41.247Z",
+ "generated": "2026-05-11T16:43:57.748Z",
"totalTools": 1075,
"modules": 15,
"tools": [
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tools/invoicing.ts b/apps/erp/app/routes/api+/mcp+/lib/tools/invoicing.ts
index 8da9fab367..abe65a02bd 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tools/invoicing.ts
+++ b/apps/erp/app/routes/api+/mcp+/lib/tools/invoicing.ts
@@ -413,7 +413,7 @@ export const registerInvoicingTools: RegisterTools = (server, ctx) => {
annotations: WRITE_ANNOTATIONS,
},
withErrorHandling(async (params) => {
- const result = await upsertPurchaseInvoice(ctx.client, { ...params.purchaseInvoice, companyId: ctx.companyId, createdBy: ctx.userId, updatedBy: ctx.userId });
+ const result = await upsertPurchaseInvoice(ctx.client, { ...params.purchaseInvoice, companyId: ctx.companyId, companyGroupId: ctx.companyGroupId, createdBy: ctx.userId, updatedBy: ctx.userId });
return toMcpResult(result);
}, "Failed: invoicing_upsertPurchaseInvoice"),
);
@@ -458,7 +458,7 @@ export const registerInvoicingTools: RegisterTools = (server, ctx) => {
annotations: WRITE_ANNOTATIONS,
},
withErrorHandling(async (params) => {
- const result = await upsertSalesInvoice(ctx.client, { ...params.salesInvoice, companyId: ctx.companyId, createdBy: ctx.userId, updatedBy: ctx.userId });
+ const result = await upsertSalesInvoice(ctx.client, { ...params.salesInvoice, companyId: ctx.companyId, companyGroupId: ctx.companyGroupId, createdBy: ctx.userId, updatedBy: ctx.userId });
return toMcpResult(result);
}, "Failed: invoicing_upsertSalesInvoice"),
);
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tools/purchasing.ts b/apps/erp/app/routes/api+/mcp+/lib/tools/purchasing.ts
index c3c28adcf6..557fc9a7e7 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tools/purchasing.ts
+++ b/apps/erp/app/routes/api+/mcp+/lib/tools/purchasing.ts
@@ -1266,7 +1266,7 @@ export const registerPurchasingTools: RegisterTools = (server, ctx) => {
annotations: WRITE_ANNOTATIONS,
},
withErrorHandling(async (params) => {
- const result = await upsertPurchaseOrder(ctx.client, { ...params.purchaseOrder, companyId: ctx.companyId, createdBy: ctx.userId, updatedBy: ctx.userId }, params.receiptRequestedDate);
+ const result = await upsertPurchaseOrder(ctx.client, { ...params.purchaseOrder, companyId: ctx.companyId, companyGroupId: ctx.companyGroupId, createdBy: ctx.userId, updatedBy: ctx.userId }, params.receiptRequestedDate);
return toMcpResult(result);
}, "Failed: purchasing_upsertPurchaseOrder"),
);
@@ -1356,7 +1356,7 @@ export const registerPurchasingTools: RegisterTools = (server, ctx) => {
annotations: WRITE_ANNOTATIONS,
},
withErrorHandling(async (params) => {
- const result = await upsertSupplierQuote(ctx.client, { ...params.supplierQuote, companyId: ctx.companyId, createdBy: ctx.userId, updatedBy: ctx.userId });
+ const result = await upsertSupplierQuote(ctx.client, { ...params.supplierQuote, companyId: ctx.companyId, companyGroupId: ctx.companyGroupId, createdBy: ctx.userId, updatedBy: ctx.userId });
return toMcpResult(result);
}, "Failed: purchasing_upsertSupplierQuote"),
);
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tools/sales.ts b/apps/erp/app/routes/api+/mcp+/lib/tools/sales.ts
index 09afed5294..b93639bd86 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tools/sales.ts
+++ b/apps/erp/app/routes/api+/mcp+/lib/tools/sales.ts
@@ -2235,7 +2235,7 @@ export const registerSalesTools: RegisterTools = (server, ctx) => {
annotations: WRITE_ANNOTATIONS,
},
withErrorHandling(async (params) => {
- const result = await upsertQuote(ctx.client, { ...params.quote, companyId: ctx.companyId, createdBy: ctx.userId, updatedBy: ctx.userId });
+ const result = await upsertQuote(ctx.client, { ...params.quote, companyId: ctx.companyId, companyGroupId: ctx.companyGroupId, createdBy: ctx.userId, updatedBy: ctx.userId });
return toMcpResult(result);
}, "Failed: sales_upsertQuote"),
);
@@ -2533,7 +2533,7 @@ export const registerSalesTools: RegisterTools = (server, ctx) => {
annotations: WRITE_ANNOTATIONS,
},
withErrorHandling(async (params) => {
- const result = await upsertSalesOrder(ctx.client, { ...params.salesOrder, companyId: ctx.companyId, createdBy: ctx.userId, updatedBy: ctx.userId });
+ const result = await upsertSalesOrder(ctx.client, { ...params.salesOrder, companyId: ctx.companyId, companyGroupId: ctx.companyGroupId, createdBy: ctx.userId, updatedBy: ctx.userId });
return toMcpResult(result);
}, "Failed: sales_upsertSalesOrder"),
);
diff --git a/apps/erp/app/routes/api+/mcp+/lib/types.ts b/apps/erp/app/routes/api+/mcp+/lib/types.ts
index 5f7dc14d17..6cc80888ff 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/types.ts
+++ b/apps/erp/app/routes/api+/mcp+/lib/types.ts
@@ -5,6 +5,7 @@ import type { SupabaseClient } from "@supabase/supabase-js";
export interface McpContext {
client: SupabaseClient<Database>;
companyId: string;
+ companyGroupId: string;
userId: string;
}
diff --git a/apps/erp/app/routes/file+/quote+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/quote+/$id[.]pdf.tsx
index e291e084a3..3a928a9a04 100644
--- a/apps/erp/app/routes/file+/quote+/$id[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/quote+/$id[.]pdf.tsx
@@ -23,9 +23,12 @@ import {
import { getBase64ImageFromSupabase } from "~/modules/shared";
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {
- view: "sales"
- });
+ const { client, companyId, companyGroupId } = await requirePermissions(
+ request,
+ {
+ view: "sales"
+ }
+ );
const { id } = params;
if (!id) throw new Error("Could not find id");
@@ -125,7 +128,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
if (quote.data?.currencyCode) {
const currency = await getCurrencyByCode(
client,
- companyId,
+ companyGroupId,
quote.data.currencyCode
);
if (currency.data?.exchangeRate) {
diff --git a/apps/erp/app/routes/x+/job+/$jobId.complete.tsx b/apps/erp/app/routes/x+/job+/$jobId.complete.tsx
index e02082f138..a857b80f02 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.complete.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.complete.tsx
@@ -111,6 +111,24 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // Backflush unissued materials
+ const backflush = await client.rpc("backflush_job_materials", {
+ p_job_id: jobId,
+ p_quantity_complete: quantityComplete,
+ p_company_id: companyId,
+ p_user_id: userId
+ });
+
+ if (backflush.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.job(jobId),
+ await flash(
+ request,
+ error(backflush.error, "Failed to backflush materials")
+ )
+ );
+ }
+
// If we need to receive leftovers to inventory
if (quantityToReceiveToInventory > 0) {
const rpc = await client.rpc("complete_job_to_inventory", {
diff --git a/apps/erp/app/routes/x+/purchase-invoice+/new.tsx b/apps/erp/app/routes/x+/purchase-invoice+/new.tsx
index 292b2dedce..652b5ee1a2 100644
--- a/apps/erp/app/routes/x+/purchase-invoice+/new.tsx
+++ b/apps/erp/app/routes/x+/purchase-invoice+/new.tsx
@@ -67,9 +67,10 @@ export async function loader({ request }: LoaderFunctionArgs) {
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- create: "invoicing"
- });
+ const { client, companyId, companyGroupId, userId } =
+ await requirePermissions(request, {
+ create: "invoicing"
+ });
const formData = await request.formData();
const validation = await validator(purchaseInvoiceValidator).validate(
@@ -109,6 +110,7 @@ export async function action({ request }: ActionFunctionArgs) {
...d,
invoiceId,
companyId,
+ companyGroupId,
createdBy: userId,
customFields: setCustomFields(formData)
});
diff --git a/apps/erp/app/routes/x+/purchase-invoice+/update.tsx b/apps/erp/app/routes/x+/purchase-invoice+/update.tsx
index 2ed0b45173..32a7664540 100644
--- a/apps/erp/app/routes/x+/purchase-invoice+/update.tsx
+++ b/apps/erp/app/routes/x+/purchase-invoice+/update.tsx
@@ -6,7 +6,7 @@ import { isPurchaseInvoiceLocked } from "~/modules/invoicing";
import { requireUnlockedBulk } from "~/utils/lockedGuard.server";
export async function action({ request }: ActionFunctionArgs) {
- const { client, companyId, userId } = await requirePermissions(request, {
+ const { client, companyGroupId, userId } = await requirePermissions(request, {
update: "sales"
});
@@ -52,7 +52,7 @@ export async function action({ request }: ActionFunctionArgs) {
currencyCode = supplier.data.currencyCode;
const currency = await getCurrencyByCode(
client,
- companyId,
+ companyGroupId,
currencyCode
);
return await client
@@ -114,7 +114,7 @@ export async function action({ request }: ActionFunctionArgs) {
if (value) {
const currency = await getCurrencyByCode(
client,
- companyId,
+ companyGroupId,
value as string
);
if (currency.data) {
diff --git a/apps/erp/app/routes/x+/purchase-order+/new.tsx b/apps/erp/app/routes/x+/purchase-order+/new.tsx
index 633b17eb3b..54cea5019a 100644
--- a/apps/erp/app/routes/x+/purchase-order+/new.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/new.tsx
@@ -30,10 +30,11 @@ export const handle: Handle = {
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- create: "purchasing",
- bypassRls: true
- });
+ const { client, companyId, companyGroupId, userId } =
+ await requirePermissions(request, {
+ create: "purchasing",
+ bypassRls: true
+ });
const formData = await request.formData();
const validation = await validator(newPurchaseOrderValidator).validate(
@@ -71,6 +72,7 @@ export async function action({ request }: ActionFunctionArgs) {
...validation.data,
purchaseOrderId,
companyId,
+ companyGroupId,
createdBy: userId,
customFields: setCustomFields(formData)
});
diff --git a/apps/erp/app/routes/x+/purchase-order+/update.tsx b/apps/erp/app/routes/x+/purchase-order+/update.tsx
index eb9e31c549..0a3f0b6b9d 100644
--- a/apps/erp/app/routes/x+/purchase-order+/update.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/update.tsx
@@ -5,7 +5,7 @@ import { isPurchaseOrderLocked } from "~/modules/purchasing";
import { requireUnlockedBulk } from "~/utils/lockedGuard.server";
export async function action({ request }: ActionFunctionArgs) {
- const { client, companyId, userId } = await requirePermissions(request, {
+ const { client, companyGroupId, userId } = await requirePermissions(request, {
update: "purchasing"
});
@@ -59,7 +59,7 @@ export async function action({ request }: ActionFunctionArgs) {
currencyCode = supplier.data.currencyCode;
const currency = await getCurrencyByCode(
client,
- companyId,
+ companyGroupId,
currencyCode
);
return await client
@@ -121,7 +121,7 @@ export async function action({ request }: ActionFunctionArgs) {
if (value) {
const currency = await getCurrencyByCode(
client,
- companyId,
+ companyGroupId,
value as string
);
if (currency.data) {
diff --git a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx b/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
index ce112da180..81586dcfe7 100644
--- a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
@@ -19,11 +19,12 @@ const itemsValidator = z
.array();
export async function action({ request }: ActionFunctionArgs) {
- const { client, companyId, userId } = await requirePermissions(request, {
- create: "purchasing",
- role: "employee",
- bypassRls: true
- });
+ const { client, companyId, companyGroupId, userId } =
+ await requirePermissions(request, {
+ create: "purchasing",
+ role: "employee",
+ bypassRls: true
+ });
const { items, action, locationId } = await request.json();
@@ -268,7 +269,7 @@ export async function action({ request }: ActionFunctionArgs) {
if (supplier.currencyCode !== baseCurrencyCode) {
const currency = await getCurrencyByCode(
client,
- companyId,
+ companyGroupId,
supplier.currencyCode ?? baseCurrencyCode
);
@@ -294,6 +295,7 @@ export async function action({ request }: ActionFunctionArgs) {
currencyCode: supplier.currencyCode ?? baseCurrencyCode,
exchangeRate: exchangeRate,
companyId,
+ companyGroupId,
createdBy: userId
},
undefined
diff --git a/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.convert.tsx b/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.convert.tsx
index 792bedd865..5ba7b3a549 100644
--- a/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.convert.tsx
+++ b/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.convert.tsx
@@ -16,9 +16,10 @@ import { path } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- create: "purchasing"
- });
+ const { client, companyId, companyGroupId, userId } =
+ await requirePermissions(request, {
+ create: "purchasing"
+ });
const { rfqId } = params;
if (!rfqId) throw new Error("Could not find rfqId");
@@ -92,6 +93,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
supplierId,
quotedDate: new Date().toISOString().split("T")[0],
companyId,
+ companyGroupId,
createdBy: userId
});
diff --git a/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.finalize.tsx b/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.finalize.tsx
index 0cc34099e3..0b95e63340 100644
--- a/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.finalize.tsx
+++ b/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.finalize.tsx
@@ -26,11 +26,12 @@ import { path } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- create: "purchasing",
- role: "employee",
- bypassRls: true
- });
+ const { client, companyId, companyGroupId, userId } =
+ await requirePermissions(request, {
+ create: "purchasing",
+ role: "employee",
+ bypassRls: true
+ });
const { rfqId } = params;
if (!rfqId) throw new Error("Could not find rfqId");
@@ -132,6 +133,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
supplierId,
quotedDate: new Date().toISOString().split("T")[0],
companyId,
+ companyGroupId,
createdBy: userId
});
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.details.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.details.tsx
index 6a337ff5a9..c57bfa569d 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.details.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.details.tsx
@@ -61,7 +61,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyGroupId, userId } = await requirePermissions(request, {
update: "sales"
});
@@ -93,6 +93,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
id,
quoteId,
...d,
+ companyGroupId,
customFields: setCustomFields(formData),
updatedBy: userId
});
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.tsx
index 4bf99ad214..a5c1424023 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.tsx
@@ -48,10 +48,13 @@ export const handle: Handle = {
};
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {
- view: "sales",
- bypassRls: true
- });
+ const { client, companyId, companyGroupId } = await requirePermissions(
+ request,
+ {
+ view: "sales",
+ bypassRls: true
+ }
+ );
const { quoteId } = params;
if (!quoteId) throw new Error("Could not find quoteId");
@@ -118,7 +121,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
if (quote.data?.currencyCode) {
const presentationCurrency = await getCurrencyByCode(
client,
- companyId,
+ companyGroupId,
quote.data.currencyCode
);
if (presentationCurrency.data?.exchangeRate) {
diff --git a/apps/erp/app/routes/x+/quote+/new.tsx b/apps/erp/app/routes/x+/quote+/new.tsx
index 512c7f2a81..a9e15b455b 100644
--- a/apps/erp/app/routes/x+/quote+/new.tsx
+++ b/apps/erp/app/routes/x+/quote+/new.tsx
@@ -23,10 +23,11 @@ export const handle: Handle = {
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- create: "sales",
- bypassRls: true
- });
+ const { client, companyId, companyGroupId, userId } =
+ await requirePermissions(request, {
+ create: "sales",
+ bypassRls: true
+ });
const formData = await request.formData();
const validation = await validator(quoteValidator).validate(formData);
@@ -58,6 +59,7 @@ export async function action({ request }: ActionFunctionArgs) {
...validation.data,
quoteId,
companyId,
+ companyGroupId,
createdBy: userId,
customFields: setCustomFields(formData)
});
diff --git a/apps/erp/app/routes/x+/quote+/update.tsx b/apps/erp/app/routes/x+/quote+/update.tsx
index e2c213b804..198ef4eb42 100644
--- a/apps/erp/app/routes/x+/quote+/update.tsx
+++ b/apps/erp/app/routes/x+/quote+/update.tsx
@@ -5,7 +5,7 @@ import { isQuoteLocked } from "~/modules/sales";
import { requireUnlockedBulk } from "~/utils/lockedGuard.server";
export async function action({ request }: ActionFunctionArgs) {
- const { client, companyId, userId } = await requirePermissions(request, {
+ const { client, companyGroupId, userId } = await requirePermissions(request, {
update: "sales"
});
@@ -69,7 +69,7 @@ export async function action({ request }: ActionFunctionArgs) {
case "currencyCode":
const currency = await getCurrencyByCode(
client,
- companyId,
+ companyGroupId,
value as string
);
if (currency.data) {
diff --git a/apps/erp/app/routes/x+/sales-invoice+/new.tsx b/apps/erp/app/routes/x+/sales-invoice+/new.tsx
index 6175a17189..8cf62f86a0 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/new.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/new.tsx
@@ -90,9 +90,10 @@ export async function loader({ request }: LoaderFunctionArgs) {
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- create: "invoicing"
- });
+ const { client, companyId, companyGroupId, userId } =
+ await requirePermissions(request, {
+ create: "invoicing"
+ });
const formData = await request.formData();
const validation = await validator(salesInvoiceValidator).validate(formData);
@@ -130,6 +131,7 @@ export async function action({ request }: ActionFunctionArgs) {
...d,
invoiceId,
companyId,
+ companyGroupId,
createdBy: userId,
customFields: setCustomFields(formData)
});
diff --git a/apps/erp/app/routes/x+/sales-invoice+/update.tsx b/apps/erp/app/routes/x+/sales-invoice+/update.tsx
index 9879e10242..6413ef21f7 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/update.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/update.tsx
@@ -6,7 +6,7 @@ import { isSalesInvoiceLocked } from "~/modules/invoicing";
import { requireUnlockedBulk } from "~/utils/lockedGuard.server";
export async function action({ request }: ActionFunctionArgs) {
- const { client, companyId, userId } = await requirePermissions(request, {
+ const { client, companyGroupId, userId } = await requirePermissions(request, {
update: "sales"
});
@@ -51,7 +51,7 @@ export async function action({ request }: ActionFunctionArgs) {
currencyCode = customer.data.currencyCode;
const currency = await getCurrencyByCode(
client,
- companyId,
+ companyGroupId,
currencyCode
);
return await client
@@ -113,7 +113,7 @@ export async function action({ request }: ActionFunctionArgs) {
if (value) {
const currency = await getCurrencyByCode(
client,
- companyId,
+ companyGroupId,
value as string
);
if (currency.data) {
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.details.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.details.tsx
index 9e5da22337..306682df2e 100644
--- a/apps/erp/app/routes/x+/sales-order+/$orderId.details.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.details.tsx
@@ -107,7 +107,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
message: "Cannot modify a locked sales order. Reopen it first."
});
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyGroupId, userId } = await requirePermissions(request, {
update: "sales"
});
@@ -125,6 +125,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
id,
salesOrderId,
...d,
+ companyGroupId,
customFields: setCustomFields(formData),
updatedBy: userId
});
diff --git a/apps/erp/app/routes/x+/sales-order+/new.tsx b/apps/erp/app/routes/x+/sales-order+/new.tsx
index 00e76b3d51..e0d0d32246 100644
--- a/apps/erp/app/routes/x+/sales-order+/new.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/new.tsx
@@ -20,10 +20,11 @@ export const handle: Handle = {
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- create: "sales",
- bypassRls: true
- });
+ const { client, companyId, companyGroupId, userId } =
+ await requirePermissions(request, {
+ create: "sales",
+ bypassRls: true
+ });
const formData = await request.formData();
const validation = await validator(salesOrderValidator).validate(formData);
@@ -57,6 +58,7 @@ export async function action({ request }: ActionFunctionArgs) {
...d,
salesOrderId,
companyId,
+ companyGroupId,
createdBy: userId,
customFields: setCustomFields(formData)
});
diff --git a/apps/erp/app/routes/x+/sales-order+/update.tsx b/apps/erp/app/routes/x+/sales-order+/update.tsx
index ac0269f877..2b8e955014 100644
--- a/apps/erp/app/routes/x+/sales-order+/update.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/update.tsx
@@ -5,7 +5,7 @@ import { isSalesOrderLocked } from "~/modules/sales";
import { requireUnlockedBulk } from "~/utils/lockedGuard.server";
export async function action({ request }: ActionFunctionArgs) {
- const { client, companyId, userId } = await requirePermissions(request, {
+ const { client, companyGroupId, userId } = await requirePermissions(request, {
update: "sales"
});
@@ -48,7 +48,7 @@ export async function action({ request }: ActionFunctionArgs) {
currencyCode = customer.data.currencyCode;
const currency = await getCurrencyByCode(
client,
- companyId,
+ companyGroupId,
currencyCode
);
return await client
@@ -76,7 +76,7 @@ export async function action({ request }: ActionFunctionArgs) {
if (value) {
const currency = await getCurrencyByCode(
client,
- companyId,
+ companyGroupId,
value as string
);
if (currency.data) {
diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.details.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.details.tsx
index 607f0305e1..09b0ff88f7 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/$id.details.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.details.tsx
@@ -52,7 +52,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyGroupId, userId } = await requirePermissions(request, {
update: "purchasing"
});
@@ -84,6 +84,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
id,
supplierQuoteId,
...d,
+ companyGroupId,
customFields: setCustomFields(formData),
updatedBy: userId
});
diff --git a/apps/erp/app/routes/x+/supplier-quote+/new.tsx b/apps/erp/app/routes/x+/supplier-quote+/new.tsx
index e79d2823b7..1acfd85b98 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/new.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/new.tsx
@@ -25,10 +25,11 @@ export const handle: Handle = {
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- create: "purchasing",
- bypassRls: true
- });
+ const { client, companyId, companyGroupId, userId } =
+ await requirePermissions(request, {
+ create: "purchasing",
+ bypassRls: true
+ });
const formData = await request.formData();
const validation = await validator(supplierQuoteValidator).validate(formData);
@@ -64,6 +65,7 @@ export async function action({ request }: ActionFunctionArgs) {
...validation.data,
supplierQuoteId,
companyId,
+ companyGroupId,
createdBy: userId,
customFields: setCustomFields(formData)
});
diff --git a/apps/erp/app/routes/x+/supplier-quote+/update.tsx b/apps/erp/app/routes/x+/supplier-quote+/update.tsx
index 5f648cbc92..5aed60a92d 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/update.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/update.tsx
@@ -6,7 +6,7 @@ import { isSupplierQuoteLocked } from "~/modules/purchasing";
import { requireUnlockedBulk } from "~/utils/lockedGuard.server";
export async function action({ request }: ActionFunctionArgs) {
- const { client, companyId, userId } = await requirePermissions(request, {
+ const { client, companyGroupId, userId } = await requirePermissions(request, {
update: "purchasing"
});
@@ -70,7 +70,7 @@ export async function action({ request }: ActionFunctionArgs) {
case "currencyCode":
const currency = await getCurrencyByCode(
client,
- companyId,
+ companyGroupId,
value as string
);
if (currency.data) {
diff --git a/docs/superpowers/specs/2026-05-11-mto-backflush-design.md b/docs/superpowers/specs/2026-05-11-mto-backflush-design.md
new file mode 100644
index 0000000000..db27ba5ab5
--- /dev/null
+++ b/docs/superpowers/specs/2026-05-11-mto-backflush-design.md
@@ -0,0 +1,83 @@
+# MTO Material Backflush Design
+
+## Problem
+
+When a make-to-order (MTO) job completes, unissued materials are not backflushed from inventory. Make-to-stock (MTS) jobs handle this via `complete_job_to_inventory`, but MTO jobs skip that function entirely — the trigger just updates job status, and the ERP route only calls it for leftover inventory receipt.
+
+Materials may be partially issued during production via the MES `issue` edge function (proportionally per operation completion), but if any remain unissued at job completion, nothing catches them.
+
+## Solution
+
+Extract the backflush logic from `complete_job_to_inventory` into a reusable `backflush_job_materials` function. Call it from both MTO and MTS completion paths.
+
+## New Function
+
+```sql
+backflush_job_materials(
+ p_job_id TEXT,
+ p_quantity_complete NUMERIC,
+ p_company_id TEXT,
+ p_user_id TEXT
+)
+```
+
+### Logic
+
+1. Look up `job.quantity` (original job quantity) and `job.locationId`
+2. Loop through unissued non-tracked materials:
+ - Filter: `jobMaterial` where `jobId = p_job_id`, `itemType IN ('Material', 'Part', 'Consumable')`, `methodType != 'Make to Order'`, `requiresBatchTracking = false`, `requiresSerialTracking = false`, `quantityToIssue > 0`
+3. For each material, prorate based on actual completion:
+ - `target = estimatedQuantity * (p_quantity_complete / job.quantity)`
+ - `to_backflush = GREATEST(target - quantityIssued, 0)`
+ - Skip if `to_backflush <= 0`
+4. Resolve storage unit: explicit on jobMaterial -> pickMethod default -> largest inventory bucket at job location
+5. Create negative `itemLedger` consumption entry
+6. Update `jobMaterial.quantityIssued`
+7. If accounting enabled:
+ - Calculate COGS per costing method (Standard/Average/FIFO/LIFO with cost layer consumption)
+ - Post journal entry: DR WIP / CR Inventory
+ - Create costLedger consumption entry
+ - Attach dimensions (ItemPostingGroup, Location)
+
+### Idempotency
+
+Safe to call even if all materials are fully issued — `quantityToIssue` will be 0 and the loop won't execute. Also safe if `p_quantity_complete` produces a target less than or equal to what's already issued.
+
+## Refactor `complete_job_to_inventory`
+
+Replace the inline backflush block (lines 193-593) with:
+
+```sql
+PERFORM backflush_job_materials(p_job_id, p_quantity_complete, p_company_id, p_user_id);
+```
+
+No behavior change for MTS jobs. Labor/machine absorption, WIP discharge, output itemLedger, and cost updates remain in `complete_job_to_inventory`.
+
+## MTO Completion Paths
+
+### Trigger (`sync_finish_job_operation`)
+
+In the MTO branch (where `v_sales_order_id IS NOT NULL`), add after the job status update:
+
+```sql
+PERFORM backflush_job_materials(p_new->>'jobId', v_quantity_complete, p_new->>'companyId', p_new->>'updatedBy');
+```
+
+### ERP Route (`$jobId.complete.tsx`)
+
+In the MTO branch, add after the job status update:
+
+```typescript
+await client.rpc("backflush_job_materials", {
+ p_job_id: jobId,
+ p_quantity_complete: quantityComplete,
+ p_company_id: companyId,
+ p_user_id: userId,
+});
+```
+
+## Out of Scope
+
+- Labor/machine absorption posting for MTO (stays in `complete_job_to_inventory`)
+- WIP discharge at shipment (separate flow)
+- Tracked material (batch/serial) backflushing
diff --git a/llm/tasks/todo.md b/llm/tasks/todo.md
index 2b1289e1e0..74b01dcc5f 100644
--- a/llm/tasks/todo.md
+++ b/llm/tasks/todo.md
@@ -1,120 +1,18 @@
-# Refactor: Configurable Upgrade Overlay System
+# MTO Material Backflush
-## Context
+## Plan
-3 near-duplicate overlay components exist (ApiKeysUpgradeOverlay,
-WebhooksUpgradeOverlay, AuditLogUpgradeOverlay) plus an inline
-upgrade-restricted block inside `AuditLogDrawer.tsx`. Server gate is
-`requireBusinessPlan` (currently buggy: `return true;` short-circuits all
-logic). `audit-logs.tsx` action duplicates the gate inline. Client-side
-gate pattern `isCloud && plan === Plan.Starter` is repeated across 6+
-files.
+- [x] Write design spec
+- [x] Step 1: Create `backflush_job_materials` function in a new migration
+- [x] Step 2: Refactor `complete_job_to_inventory` to call `backflush_job_materials`
+- [x] Step 3: Update `sync_finish_job_operation` to call `backflush_job_materials` for MTO
+- [x] Step 4: Update ERP route `$jobId.complete.tsx` to call `backflush_job_materials` for MTO
+- [x] Step 5: Verify — read all changed files and confirm correctness
-Goal: shared, composable upgrade-overlay system + generic plan-gate
-hook + generic server-side `requirePlan`.
+## Notes
-## Design (compound components, avoid boolean props)
-
-### `UpgradeOverlay` — compound component
-
-```tsx
-<UpgradeOverlay>
- <UpgradeOverlay.Preview>
- <ApiKeysTable data={mockApiKeys} count={mockApiKeys.length} />
- </UpgradeOverlay.Preview>
- <UpgradeOverlay.Card>
- <UpgradeOverlay.Icon><LuKeyRound /></UpgradeOverlay.Icon>
- <UpgradeOverlay.Title>API Keys</UpgradeOverlay.Title>
- <UpgradeOverlay.Description>...</UpgradeOverlay.Description>
- <UpgradeOverlay.Actions>
- <UpgradeOverlay.UpgradeButton />
- </UpgradeOverlay.Actions>
- </UpgradeOverlay.Card>
-</UpgradeOverlay>
-```
-
-Inline variant for non-overlay contexts (e.g. drawer panel — no preview,
-no absolute positioning, no card chrome):
-
-```tsx
-<UpgradeOverlay.Inline>
- <UpgradeOverlay.Icon>...</UpgradeOverlay.Icon>
- <UpgradeOverlay.Title>...</UpgradeOverlay.Title>
- <UpgradeOverlay.Description>...</UpgradeOverlay.Description>
- <UpgradeOverlay.Actions>...</UpgradeOverlay.Actions>
-</UpgradeOverlay.Inline>
-```
-
-Layout pieces (`UpgradeOverlay`, `Preview`, `Card`, `Inline`) provide
-positioning. Content pieces (`Icon`, `Title`, `Description`, `Actions`,
-`UpgradeButton`) are reusable across both layouts. No boolean variant
-props — composition decides shape.
-
-### `usePlanGate` hook
-
-```tsx
-const { isGated } = usePlanGate({ requiredPlan: Plan.Business });
-if (isGated) return <UpgradeOverlay>...</UpgradeOverlay>;
-```
-
-Default `requiredPlan = Plan.Business`. Internally uses `usePlan()` +
-`useFlags()`. Returns `{ isGated, plan, requiredPlan }`.
-
-### Server `requirePlan`
-
-```ts
-await requirePlan({
- request,
- client,
- companyId,
- redirectTo: path.to.auditLog,
- requiredPlan: Plan.Business,
- message: "Upgrade to enable audit logging",
-});
-```
-
-Replaces `requireBusinessPlan`. Adds `Edition.Cloud` check (currently
-missing — non-cloud installs should never gate). Removes the `return
-true;` bug.
-
-## Files
-
-### New
-
-- [ ] `apps/erp/app/components/UpgradeOverlay/UpgradeOverlay.tsx`
-- [ ] `apps/erp/app/components/UpgradeOverlay/index.ts`
-- [ ] `apps/erp/app/hooks/usePlanGate.ts`
-- [ ] `apps/erp/app/utils/planGate.ts` — shared `planMeetsRequirement`
-
-### Modify
-
-- [ ] `apps/erp/app/utils/planGate.server.ts` — replace
- `requireBusinessPlan` with generic `requirePlan`. Add Cloud check.
- Remove dead code.
-- [ ] `apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysUpgradeOverlay.tsx`
- — re-implement as composition over `<UpgradeOverlay>`.
-- [ ] `apps/erp/app/modules/settings/ui/Webhooks/WebhooksUpgradeOverlay.tsx`
-- [ ] `apps/erp/app/modules/settings/ui/AuditLog/AuditLogUpgradeOverlay.tsx`
-- [ ] `apps/erp/app/components/AuditLog/AuditLogDrawer.tsx` — replace
- inline `planRestricted` block with `<UpgradeOverlay.Inline>`.
-- [ ] Routes calling `requireBusinessPlan` — change to `requirePlan`:
- - `api-keys.$id.tsx`, `api-keys.delete.$id.tsx`, `api-keys.new.tsx`
- - `webhooks.$id.tsx`, `webhooks.delete.$id.tsx`, `webhooks.new.tsx`
- - `integrations.$id.tsx`, `integrations.deactivate.$id.tsx`
-- [ ] `audit-logs.tsx` — replace inline action plan check with
- `requirePlan`. Replace `isStarterTeaser` with `usePlanGate`.
-- [ ] `api-keys.tsx`, `webhooks.tsx` — fix `if (true)` bug → use
- `usePlanGate` and check `isGated`.
-- [ ] `useAuditLog.tsx`, `IntegrationCard.tsx` — replace ad-hoc
- `isCloud && plan === Plan.Starter` with `usePlanGate`.
-
-## Verification
-
-- `npm run typecheck` passes.
-- `npm run lingui:compile` passes.
-- Spot-check routes (api-keys, webhooks, audit-logs) on Starter +
- Business cloud users.
-
-## Review
-
-(filled in after implementation)
+- Spec: `docs/superpowers/specs/2026-05-11-mto-backflush-design.md`
+- Migration file: `packages/database/supabase/migrations/20260508120000_complete-job-to-inventory.sql`
+- ERP route: `apps/erp/app/routes/x+/job+/$jobId.complete.tsx`
+- The backflush logic to extract is lines 193-593 of the migration
+- Prorate formula: `target = estimatedQuantity * (p_quantity_complete / job.quantity)`, `to_backflush = GREATEST(target - quantityIssued, 0)`
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index a5f97e95d3..53250bd6e7 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -72662,6 +72662,58 @@ export default {
tags: ["(rpc) create_rfq_from_model_v1"]
}
},
+ "/rpc/backflush_job_materials": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_company_id: {
+ format: "text",
+ type: "string"
+ },
+ p_job_id: {
+ format: "text",
+ type: "string"
+ },
+ p_quantity_complete: {
+ format: "numeric",
+ type: "number"
+ },
+ p_user_id: {
+ format: "text",
+ type: "string"
+ }
+ },
+ required: [
+ "p_job_id",
+ "p_quantity_complete",
+ "p_company_id",
+ "p_user_id"
+ ],
+ type: "object"
+ }
+ },
+ {
+ $ref: "#/parameters/preferParams"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) backflush_job_materials"]
+ }
+ },
"/rpc/get_company_id_from_api_key": {
post: {
parameters: [
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 819d29c440..bd259d3717 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -36086,48 +36086,6 @@ export type Database = {
},
]
}
- searchIndex_WBammHTt6NdE6hCgdhZbWC: {
- Row: {
- createdAt: string
- description: string | null
- entityId: string
- entityType: string
- id: number
- link: string
- metadata: Json | null
- searchVector: unknown
- tags: string[] | null
- title: string
- updatedAt: string | null
- }
- Insert: {
- createdAt?: string
- description?: string | null
- entityId: string
- entityType: string
- id?: number
- link: string
- metadata?: Json | null
- searchVector?: unknown
- tags?: string[] | null
- title: string
- updatedAt?: string | null
- }
- Update: {
- createdAt?: string
- description?: string | null
- entityId?: string
- entityType?: string
- id?: number
- link?: string
- metadata?: Json | null
- searchVector?: unknown
- tags?: string[] | null
- title?: string
- updatedAt?: string | null
- }
- Relationships: []
- }
searchIndexRegistry: {
Row: {
companyId: string
@@ -59904,6 +59862,15 @@ export type Database = {
}
Returns: undefined
}
+ backflush_job_materials: {
+ Args: {
+ p_company_id: string
+ p_job_id: string
+ p_quantity_complete: number
+ p_user_id: string
+ }
+ Returns: undefined
+ }
calculate_quantity_to_order: {
Args: {
p_demand_accumulation_period: number
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 819d29c440..bd259d3717 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -36086,48 +36086,6 @@ export type Database = {
},
]
}
- searchIndex_WBammHTt6NdE6hCgdhZbWC: {
- Row: {
- createdAt: string
- description: string | null
- entityId: string
- entityType: string
- id: number
- link: string
- metadata: Json | null
- searchVector: unknown
- tags: string[] | null
- title: string
- updatedAt: string | null
- }
- Insert: {
- createdAt?: string
- description?: string | null
- entityId: string
- entityType: string
- id?: number
- link: string
- metadata?: Json | null
- searchVector?: unknown
- tags?: string[] | null
- title: string
- updatedAt?: string | null
- }
- Update: {
- createdAt?: string
- description?: string | null
- entityId?: string
- entityType?: string
- id?: number
- link?: string
- metadata?: Json | null
- searchVector?: unknown
- tags?: string[] | null
- title?: string
- updatedAt?: string | null
- }
- Relationships: []
- }
searchIndexRegistry: {
Row: {
companyId: string
@@ -59904,6 +59862,15 @@ export type Database = {
}
Returns: undefined
}
+ backflush_job_materials: {
+ Args: {
+ p_company_id: string
+ p_job_id: string
+ p_quantity_complete: number
+ p_user_id: string
+ }
+ Returns: undefined
+ }
calculate_quantity_to_order: {
Args: {
p_demand_accumulation_period: number
diff --git a/packages/database/supabase/migrations/20260511120000_backflush-job-materials.sql b/packages/database/supabase/migrations/20260511120000_backflush-job-materials.sql
new file mode 100644
index 0000000000..cfa3b37eb3
--- /dev/null
+++ b/packages/database/supabase/migrations/20260511120000_backflush-job-materials.sql
@@ -0,0 +1,935 @@
+CREATE OR REPLACE FUNCTION backflush_job_materials(
+ p_job_id TEXT,
+ p_quantity_complete NUMERIC,
+ p_company_id TEXT,
+ p_user_id TEXT
+)
+RETURNS VOID
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+DECLARE
+ v_job_quantity NUMERIC;
+ v_job_location_id TEXT;
+ v_job_id_readable TEXT;
+ v_ratio NUMERIC;
+ v_target NUMERIC;
+ v_material RECORD;
+ v_material_qty_to_issue NUMERIC;
+ v_material_storage_unit_id TEXT;
+ v_material_costing_method TEXT;
+ v_material_standard_cost NUMERIC;
+ v_material_unit_cost NUMERIC;
+ v_material_item_posting_group_id TEXT;
+ v_material_cogs_total NUMERIC;
+ v_cost_layer RECORD;
+ v_remaining_to_consume NUMERIC;
+ v_layer_unit_cost NUMERIC;
+ v_quantity_from_layer NUMERIC;
+ v_accounting_enabled BOOLEAN;
+ v_company_group_id TEXT;
+ v_inventory_account TEXT;
+ v_wip_account TEXT;
+ v_dimension_item_posting_group TEXT;
+ v_dimension_location TEXT;
+ v_bf_item_ids TEXT[] := '{}';
+ v_bf_quantities NUMERIC[] := '{}';
+ v_bf_storage_unit_ids TEXT[] := '{}';
+ v_bf_journal_id TEXT;
+ v_bf_journal_entry_id TEXT;
+ v_bf_accounting_period_id TEXT;
+ v_bf_journal_line_ref TEXT;
+ v_bf_jl_id TEXT;
+ v_bf_jl_ids TEXT[];
+ v_bf_posting_group_ids TEXT[];
+BEGIN
+ -- Fetch job details
+ SELECT quantity, "locationId", "jobId"
+ INTO STRICT v_job_quantity, v_job_location_id, v_job_id_readable
+ FROM "job"
+ WHERE id = p_job_id;
+
+ IF v_job_quantity IS NULL OR v_job_quantity <= 0 THEN
+ RETURN;
+ END IF;
+
+ v_ratio := p_quantity_complete / v_job_quantity;
+
+ -- Backflush non-tracked materials
+ FOR v_material IN
+ SELECT jm.id, jm."itemId", jm."quantityToIssue", jm."quantityIssued",
+ jm."estimatedQuantity", jm."storageUnitId", jm."defaultStorageUnit"
+ FROM "jobMaterial" jm
+ WHERE jm."jobId" = p_job_id
+ AND jm."itemType" IN ('Material', 'Part', 'Consumable')
+ AND jm."methodType" != 'Make to Order'
+ AND jm."requiresBatchTracking" = false
+ AND jm."requiresSerialTracking" = false
+ AND jm."quantityToIssue" > 0
+ LOOP
+ -- Prorate: only issue what's needed for the completed quantity
+ v_target := v_material."estimatedQuantity" * v_ratio;
+ v_material_qty_to_issue := GREATEST(v_target - COALESCE(v_material."quantityIssued", 0), 0);
+
+ IF v_material_qty_to_issue <= 0 THEN
+ CONTINUE;
+ END IF;
+
+ -- Resolve storage unit
+ v_material_storage_unit_id := v_material."storageUnitId";
+
+ IF v_material_storage_unit_id IS NULL AND v_material."defaultStorageUnit" THEN
+ SELECT "defaultStorageUnitId" INTO v_material_storage_unit_id
+ FROM "pickMethod"
+ WHERE "itemId" = v_material."itemId"
+ AND "locationId" = v_job_location_id
+ AND "companyId" = p_company_id;
+ END IF;
+
+ IF v_material_storage_unit_id IS NULL THEN
+ SELECT "storageUnitId" INTO v_material_storage_unit_id
+ FROM "itemLedger"
+ WHERE "itemId" = v_material."itemId"
+ AND "locationId" = v_job_location_id
+ AND "storageUnitId" IS NOT NULL
+ GROUP BY "storageUnitId"
+ HAVING SUM(quantity) > 0
+ ORDER BY SUM(quantity) DESC
+ LIMIT 1;
+ END IF;
+
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId", "createdBy"
+ ) VALUES (
+ 'Consumption', 'Job Consumption', p_job_id, p_company_id,
+ v_material."itemId", -v_material_qty_to_issue,
+ v_job_location_id, v_material_storage_unit_id, p_user_id
+ );
+
+ UPDATE "jobMaterial"
+ SET "quantityIssued" = COALESCE("quantityIssued", 0) + v_material_qty_to_issue
+ WHERE id = v_material.id;
+
+ v_bf_item_ids := v_bf_item_ids || v_material."itemId";
+ v_bf_quantities := v_bf_quantities || v_material_qty_to_issue;
+ v_bf_storage_unit_ids := v_bf_storage_unit_ids || COALESCE(v_material_storage_unit_id, '');
+ END LOOP;
+
+ -- Check if accounting is enabled
+ SELECT "accountingEnabled"
+ INTO v_accounting_enabled
+ FROM "companySettings"
+ WHERE id = p_company_id;
+
+ v_accounting_enabled := COALESCE(v_accounting_enabled, false);
+
+ IF NOT v_accounting_enabled THEN
+ RETURN;
+ END IF;
+
+ IF array_length(v_bf_item_ids, 1) IS NULL OR array_length(v_bf_item_ids, 1) = 0 THEN
+ RETURN;
+ END IF;
+
+ -- Fetch company group
+ SELECT "companyGroupId"
+ INTO STRICT v_company_group_id
+ FROM company
+ WHERE id = p_company_id;
+
+ -- Fetch account defaults
+ SELECT "inventoryAccount", "workInProgressAccount"
+ INTO STRICT v_inventory_account, v_wip_account
+ FROM "accountDefault"
+ WHERE "companyId" = p_company_id;
+
+ -- Fetch dimension IDs
+ SELECT
+ MAX(CASE WHEN "entityType" = 'ItemPostingGroup' THEN id END),
+ MAX(CASE WHEN "entityType" = 'Location' THEN id END)
+ INTO v_dimension_item_posting_group, v_dimension_location
+ FROM dimension
+ WHERE "companyGroupId" = v_company_group_id
+ AND active = true
+ AND "entityType" IN ('ItemPostingGroup', 'Location');
+
+ -- Get accounting period
+ SELECT id INTO v_bf_accounting_period_id
+ FROM "accountingPeriod"
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= CURRENT_DATE
+ AND "endDate" >= CURRENT_DATE
+ AND status = 'Active'
+ LIMIT 1;
+
+ IF v_bf_accounting_period_id IS NULL THEN
+ UPDATE "accountingPeriod"
+ SET status = 'Inactive'
+ WHERE status = 'Active' AND "companyId" = p_company_id;
+
+ UPDATE "accountingPeriod"
+ SET status = 'Active'
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= CURRENT_DATE
+ AND "endDate" >= CURRENT_DATE
+ RETURNING id INTO v_bf_accounting_period_id;
+
+ IF v_bf_accounting_period_id IS NULL THEN
+ INSERT INTO "accountingPeriod" (
+ "startDate", "endDate", "companyId", status, "createdBy"
+ ) VALUES (
+ date_trunc('month', CURRENT_DATE)::DATE,
+ (date_trunc('month', CURRENT_DATE) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,
+ p_company_id, 'Active', 'system'
+ )
+ RETURNING id INTO v_bf_accounting_period_id;
+ END IF;
+ END IF;
+
+ v_bf_journal_entry_id := get_next_sequence('journalEntry', p_company_id);
+
+ INSERT INTO journal (
+ "journalEntryId", "accountingPeriodId", description,
+ "postingDate", "companyId", "sourceType", status,
+ "postedAt", "postedBy", "createdBy"
+ ) VALUES (
+ v_bf_journal_entry_id, v_bf_accounting_period_id,
+ 'Material Issue — Job ' || v_job_id_readable,
+ CURRENT_DATE, p_company_id, 'Job Consumption', 'Posted',
+ NOW(), p_user_id, p_user_id
+ )
+ RETURNING id INTO v_bf_journal_id;
+
+ v_bf_jl_ids := '{}';
+ v_bf_posting_group_ids := '{}';
+
+ FOR i IN 1..array_length(v_bf_item_ids, 1)
+ LOOP
+ -- Get itemCost for COGS calculation
+ SELECT "costingMethod", "standardCost", "unitCost", "itemPostingGroupId"
+ INTO v_material_costing_method, v_material_standard_cost, v_material_unit_cost, v_material_item_posting_group_id
+ FROM "itemCost"
+ WHERE "itemId" = v_bf_item_ids[i]
+ AND "companyId" = p_company_id;
+
+ IF v_material_costing_method IS NULL THEN
+ CONTINUE;
+ END IF;
+
+ -- Calculate COGS based on costing method
+ v_material_cogs_total := 0;
+
+ IF v_material_costing_method = 'Standard' THEN
+ v_material_cogs_total := COALESCE(v_material_standard_cost, 0) * v_bf_quantities[i];
+
+ ELSIF v_material_costing_method = 'Average' THEN
+ v_material_cogs_total := COALESCE(v_material_unit_cost, 0) * v_bf_quantities[i];
+
+ ELSIF v_material_costing_method IN ('FIFO', 'LIFO') THEN
+ v_remaining_to_consume := v_bf_quantities[i];
+
+ FOR v_cost_layer IN
+ SELECT id, quantity, cost, "remainingQuantity"
+ FROM "costLedger"
+ WHERE "itemId" = v_bf_item_ids[i]
+ AND "companyId" = p_company_id
+ AND "remainingQuantity" > 0
+ ORDER BY
+ CASE WHEN v_material_costing_method = 'FIFO' THEN "postingDate" END ASC,
+ CASE WHEN v_material_costing_method = 'LIFO' THEN "postingDate" END DESC,
+ CASE WHEN v_material_costing_method = 'FIFO' THEN "createdAt" END ASC,
+ CASE WHEN v_material_costing_method = 'LIFO' THEN "createdAt" END DESC
+ LOOP
+ EXIT WHEN v_remaining_to_consume <= 0;
+
+ v_layer_unit_cost := CASE
+ WHEN v_cost_layer.quantity > 0 THEN v_cost_layer.cost / v_cost_layer.quantity
+ ELSE 0
+ END;
+
+ v_quantity_from_layer := LEAST(v_remaining_to_consume, v_cost_layer."remainingQuantity");
+ v_material_cogs_total := v_material_cogs_total + v_quantity_from_layer * v_layer_unit_cost;
+ v_remaining_to_consume := v_remaining_to_consume - v_quantity_from_layer;
+
+ UPDATE "costLedger"
+ SET "remainingQuantity" = "remainingQuantity" - v_quantity_from_layer
+ WHERE id = v_cost_layer.id;
+ END LOOP;
+
+ -- Fallback for negative inventory
+ IF v_remaining_to_consume > 0 THEN
+ v_material_cogs_total := v_material_cogs_total + v_remaining_to_consume * COALESCE(v_material_unit_cost, 0);
+ END IF;
+ END IF;
+
+ IF v_material_cogs_total <= 0 THEN
+ CONTINUE;
+ END IF;
+
+ v_bf_journal_line_ref := nanoid();
+
+ -- DR WIP
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_bf_journal_id, v_wip_account, 'WIP Account',
+ v_material_cogs_total, v_bf_quantities[i],
+ 'Job Consumption', p_job_id, 'job:' || p_job_id,
+ v_bf_journal_line_ref, p_company_id
+ )
+ RETURNING id INTO v_bf_jl_id;
+
+ v_bf_jl_ids := v_bf_jl_ids || v_bf_jl_id;
+ v_bf_posting_group_ids := v_bf_posting_group_ids || COALESCE(v_material_item_posting_group_id, '');
+
+ -- CR Inventory
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_bf_journal_id, v_inventory_account, 'Inventory Account',
+ -v_material_cogs_total, v_bf_quantities[i],
+ 'Job Consumption', p_job_id, 'job:' || p_job_id,
+ v_bf_journal_line_ref, p_company_id
+ )
+ RETURNING id INTO v_bf_jl_id;
+
+ v_bf_jl_ids := v_bf_jl_ids || v_bf_jl_id;
+ v_bf_posting_group_ids := v_bf_posting_group_ids || COALESCE(v_material_item_posting_group_id, '');
+
+ -- Cost ledger entry for consumption
+ INSERT INTO "costLedger" (
+ "itemLedgerType", "costLedgerType", adjustment,
+ "documentType", "documentId", "itemId",
+ quantity, cost, "remainingQuantity", "companyId"
+ ) VALUES (
+ 'Consumption', 'Direct Cost', false,
+ 'Job Consumption', p_job_id, v_bf_item_ids[i],
+ -v_bf_quantities[i], -v_material_cogs_total,
+ 0, p_company_id
+ );
+ END LOOP;
+
+ -- Dimensions for material consumption journal lines
+ IF array_length(v_bf_jl_ids, 1) IS NOT NULL THEN
+ FOR i IN 1..array_length(v_bf_jl_ids, 1)
+ LOOP
+ IF v_bf_posting_group_ids[i] != '' AND v_dimension_item_posting_group IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_bf_jl_ids[i], v_dimension_item_posting_group, v_bf_posting_group_ids[i], p_company_id
+ );
+ END IF;
+
+ IF v_job_location_id IS NOT NULL AND v_dimension_location IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_bf_jl_ids[i], v_dimension_location, v_job_location_id, p_company_id
+ );
+ END IF;
+ END LOOP;
+ END IF;
+END;
+$$;
+
+-- Refactor complete_job_to_inventory to delegate backflush to the new function
+CREATE OR REPLACE FUNCTION complete_job_to_inventory(
+ p_job_id TEXT,
+ p_quantity_complete NUMERIC,
+ p_storage_unit_id TEXT DEFAULT NULL,
+ p_location_id TEXT DEFAULT NULL,
+ p_company_id TEXT DEFAULT NULL,
+ p_user_id TEXT DEFAULT NULL
+)
+RETURNS VOID
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+DECLARE
+ v_item_id TEXT;
+ v_quantity_received_to_inventory NUMERIC;
+ v_job_id_readable TEXT;
+ v_job_make_method RECORD;
+ v_tracked_entity RECORD;
+ v_accounting_enabled BOOLEAN;
+ v_company_group_id TEXT;
+ v_inventory_account TEXT;
+ v_wip_account TEXT;
+ v_labor_absorption_account TEXT;
+ v_dimension_item_posting_group TEXT;
+ v_dimension_location TEXT;
+ v_dimension_cost_center TEXT;
+ v_dimension_employee TEXT;
+ v_event RECORD;
+ v_duration_hours NUMERIC;
+ v_rate NUMERIC;
+ v_labor_cost NUMERIC;
+ v_labor_journal_line_reference TEXT;
+ v_labor_accounting_period_id TEXT;
+ v_labor_journal_entry_id TEXT;
+ v_labor_journal_id TEXT;
+ v_labor_jl_id TEXT;
+ v_accumulated_wip_cost NUMERIC;
+ v_today DATE;
+ v_journal_line_reference TEXT;
+ v_accounting_period_id TEXT;
+ v_journal_entry_id TEXT;
+ v_journal_id TEXT;
+ v_jl_ids TEXT[];
+ v_new_per_unit_cost NUMERIC;
+ v_costing_method TEXT;
+ v_existing_unit_cost NUMERIC;
+ v_item_posting_group_id TEXT;
+ v_job_location_id TEXT;
+ v_total_qty_on_hand NUMERIC;
+ v_prior_qty NUMERIC;
+ v_prior_value NUMERIC;
+ v_new_unit_cost NUMERIC;
+BEGIN
+ -- Fetch job details
+ SELECT "itemId", "quantityReceivedToInventory", "jobId", "locationId"
+ INTO STRICT v_item_id, v_quantity_received_to_inventory, v_job_id_readable, v_job_location_id
+ FROM "job"
+ WHERE id = p_job_id;
+
+ v_quantity_received_to_inventory := p_quantity_complete - COALESCE(v_quantity_received_to_inventory, 0);
+
+ -- Fetch jobMakeMethod for the top-level (no parentMaterialId)
+ SELECT *
+ INTO STRICT v_job_make_method
+ FROM "jobMakeMethod"
+ WHERE "jobId" = p_job_id
+ AND "parentMaterialId" IS NULL;
+
+ -- Update job status
+ UPDATE "job"
+ SET status = 'Completed',
+ "completedDate" = NOW(),
+ "quantityComplete" = p_quantity_complete,
+ "quantityReceivedToInventory" = v_quantity_received_to_inventory,
+ "updatedAt" = NOW(),
+ "updatedBy" = p_user_id
+ WHERE id = p_job_id;
+
+ -- Insert itemLedger entries based on tracking type
+ IF v_job_make_method."requiresBatchTracking" THEN
+ SELECT *
+ INTO v_tracked_entity
+ FROM "trackedEntity"
+ WHERE attributes->>'Job Make Method' = v_job_make_method.id
+ AND status != 'Consumed'
+ ORDER BY "createdAt" DESC
+ LIMIT 1;
+
+ IF v_tracked_entity.id IS NULL THEN
+ RAISE EXCEPTION 'Tracked entity not found';
+ END IF;
+
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId",
+ "trackedEntityId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,
+ v_tracked_entity.id, p_user_id
+ );
+
+ ELSIF v_job_make_method."requiresSerialTracking" THEN
+ FOR v_tracked_entity IN
+ SELECT *
+ FROM "trackedEntity"
+ WHERE attributes->>'Job Make Method' = v_job_make_method.id
+ AND status != 'Consumed'
+ LOOP
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId",
+ "trackedEntityId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, 1, p_location_id, p_storage_unit_id,
+ v_tracked_entity.id, p_user_id
+ );
+ END LOOP;
+
+ UPDATE "trackedEntity"
+ SET status = 'Available'
+ WHERE attributes->>'Job Make Method' = v_job_make_method.id
+ AND status != 'Consumed';
+
+ ELSE
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,
+ p_user_id
+ );
+ END IF;
+
+ -- Update pickMethod defaultStorageUnitId if needed
+ IF p_storage_unit_id IS NOT NULL AND p_location_id IS NOT NULL THEN
+ IF NOT EXISTS (
+ SELECT 1 FROM "itemLedger"
+ WHERE "itemId" = v_item_id
+ AND "locationId" = p_location_id
+ AND "storageUnitId" IS NOT NULL
+ AND "storageUnitId" != p_storage_unit_id
+ LIMIT 1
+ ) THEN
+ IF EXISTS (
+ SELECT 1 FROM "pickMethod"
+ WHERE "itemId" = v_item_id AND "locationId" = p_location_id
+ ) THEN
+ UPDATE "pickMethod"
+ SET "defaultStorageUnitId" = p_storage_unit_id,
+ "updatedBy" = p_user_id,
+ "updatedAt" = NOW()
+ WHERE "itemId" = v_item_id
+ AND "locationId" = p_location_id;
+ ELSE
+ INSERT INTO "pickMethod" (
+ "itemId", "locationId", "defaultStorageUnitId",
+ "companyId", "createdBy", "createdAt"
+ ) VALUES (
+ v_item_id, p_location_id, p_storage_unit_id,
+ p_company_id, p_user_id, NOW()
+ );
+ END IF;
+ END IF;
+ END IF;
+
+ -- Backflush unissued materials (delegated to shared function)
+ PERFORM backflush_job_materials(p_job_id, p_quantity_complete, p_company_id, p_user_id);
+
+ -- Check if accounting is enabled
+ SELECT "accountingEnabled"
+ INTO v_accounting_enabled
+ FROM "companySettings"
+ WHERE id = p_company_id;
+
+ v_accounting_enabled := COALESCE(v_accounting_enabled, false);
+
+ IF NOT v_accounting_enabled THEN
+ RETURN;
+ END IF;
+
+ -- Fetch company group
+ SELECT "companyGroupId"
+ INTO STRICT v_company_group_id
+ FROM company
+ WHERE id = p_company_id;
+
+ -- Fetch account defaults
+ SELECT "inventoryAccount", "workInProgressAccount", "laborAbsorptionAccount"
+ INTO STRICT v_inventory_account, v_wip_account, v_labor_absorption_account
+ FROM "accountDefault"
+ WHERE "companyId" = p_company_id;
+
+ -- Fetch dimension IDs
+ SELECT
+ MAX(CASE WHEN "entityType" = 'ItemPostingGroup' THEN id END),
+ MAX(CASE WHEN "entityType" = 'Location' THEN id END),
+ MAX(CASE WHEN "entityType" = 'CostCenter' THEN id END),
+ MAX(CASE WHEN "entityType" = 'Employee' THEN id END)
+ INTO v_dimension_item_posting_group, v_dimension_location,
+ v_dimension_cost_center, v_dimension_employee
+ FROM dimension
+ WHERE "companyGroupId" = v_company_group_id
+ AND active = true
+ AND "entityType" IN ('ItemPostingGroup', 'Location', 'CostCenter', 'Employee');
+
+ -- Post unposted production events as labor/machine absorption JEs
+ FOR v_event IN
+ SELECT
+ pe.id,
+ pe.duration,
+ pe.type,
+ pe."employeeId",
+ wc."laborRate",
+ wc."machineRate"
+ FROM "productionEvent" pe
+ INNER JOIN "jobOperation" jo ON jo.id = pe."jobOperationId"
+ INNER JOIN "workCenter" wc ON wc.id = pe."workCenterId"
+ WHERE jo."jobId" = p_job_id
+ AND pe."endTime" IS NOT NULL
+ AND pe."postedToGL" = false
+ AND pe.duration > 0
+ LOOP
+ v_duration_hours := v_event.duration::NUMERIC / 3600;
+ v_rate := CASE
+ WHEN v_event.type = 'Machine' THEN COALESCE(v_event."machineRate", 0)
+ ELSE COALESCE(v_event."laborRate", 0)
+ END;
+ v_labor_cost := v_duration_hours * v_rate;
+
+ IF v_labor_cost > 0 AND v_labor_absorption_account IS NOT NULL THEN
+ v_labor_journal_line_reference := nanoid();
+
+ -- Get current accounting period
+ SELECT id INTO v_labor_accounting_period_id
+ FROM "accountingPeriod"
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= CURRENT_DATE
+ AND "endDate" >= CURRENT_DATE
+ AND status = 'Active'
+ LIMIT 1;
+
+ IF v_labor_accounting_period_id IS NULL THEN
+ UPDATE "accountingPeriod"
+ SET status = 'Inactive'
+ WHERE status = 'Active' AND "companyId" = p_company_id;
+
+ UPDATE "accountingPeriod"
+ SET status = 'Active'
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= CURRENT_DATE
+ AND "endDate" >= CURRENT_DATE
+ RETURNING id INTO v_labor_accounting_period_id;
+
+ IF v_labor_accounting_period_id IS NULL THEN
+ INSERT INTO "accountingPeriod" (
+ "startDate", "endDate", "companyId", status, "createdBy"
+ ) VALUES (
+ date_trunc('month', CURRENT_DATE)::DATE,
+ (date_trunc('month', CURRENT_DATE) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,
+ p_company_id, 'Active', 'system'
+ )
+ RETURNING id INTO v_labor_accounting_period_id;
+ END IF;
+ END IF;
+
+ v_labor_journal_entry_id := get_next_sequence('journalEntry', p_company_id);
+
+ INSERT INTO journal (
+ "journalEntryId", "accountingPeriodId", description,
+ "postingDate", "companyId", "sourceType", status,
+ "postedAt", "postedBy", "createdBy"
+ ) VALUES (
+ v_labor_journal_entry_id, v_labor_accounting_period_id,
+ v_event.type || ' Time — Job ' || v_job_id_readable,
+ CURRENT_DATE, p_company_id, 'Production Event', 'Posted',
+ NOW(), p_user_id, p_user_id
+ )
+ RETURNING id INTO v_labor_journal_id;
+
+ -- DR WIP
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_wip_account, 'WIP Account',
+ v_labor_cost, 1,
+ 'Production Event', p_job_id, 'job:' || p_job_id,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on WIP line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- CR Labor/Machine Absorption
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_labor_absorption_account, 'Labor/Machine Absorption',
+ -v_labor_cost, 1,
+ 'Production Event', p_job_id, 'job:' || p_job_id,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on absorption line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+ END IF;
+
+ UPDATE "productionEvent"
+ SET "postedToGL" = true
+ WHERE id = v_event.id;
+ END LOOP;
+
+ -- Calculate accumulated WIP cost for this job
+ SELECT COALESCE(ABS(SUM(jl.amount)), 0)
+ INTO v_accumulated_wip_cost
+ FROM "journalLine" jl
+ INNER JOIN journal j ON j.id = jl."journalId"
+ WHERE jl."accountId" = v_wip_account
+ AND jl."documentId" = p_job_id
+ AND j."companyId" = p_company_id;
+
+ IF v_accumulated_wip_cost <= 0 THEN
+ RETURN;
+ END IF;
+
+ v_today := CURRENT_DATE;
+ v_journal_line_reference := nanoid();
+
+ -- Get accounting period for WIP discharge
+ SELECT id INTO v_accounting_period_id
+ FROM "accountingPeriod"
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_today
+ AND "endDate" >= v_today
+ AND status = 'Active'
+ LIMIT 1;
+
+ IF v_accounting_period_id IS NULL THEN
+ UPDATE "accountingPeriod"
+ SET status = 'Inactive'
+ WHERE status = 'Active' AND "companyId" = p_company_id;
+
+ UPDATE "accountingPeriod"
+ SET status = 'Active'
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_today
+ AND "endDate" >= v_today
+ RETURNING id INTO v_accounting_period_id;
+
+ IF v_accounting_period_id IS NULL THEN
+ INSERT INTO "accountingPeriod" (
+ "startDate", "endDate", "companyId", status, "createdBy"
+ ) VALUES (
+ date_trunc('month', v_today)::DATE,
+ (date_trunc('month', v_today) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,
+ p_company_id, 'Active', 'system'
+ )
+ RETURNING id INTO v_accounting_period_id;
+ END IF;
+ END IF;
+
+ v_journal_entry_id := get_next_sequence('journalEntry', p_company_id);
+
+ INSERT INTO journal (
+ "journalEntryId", "accountingPeriodId", description,
+ "postingDate", "companyId", "sourceType", status,
+ "postedAt", "postedBy", "createdBy"
+ ) VALUES (
+ v_journal_entry_id, v_accounting_period_id,
+ 'Job Completion ' || v_job_id_readable,
+ v_today, p_company_id, 'Job Receipt', 'Posted',
+ NOW(), p_user_id, p_user_id
+ )
+ RETURNING id INTO v_journal_id;
+
+ -- DR FG Inventory
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_journal_id, v_inventory_account, 'Finished Goods Inventory',
+ v_accumulated_wip_cost, v_quantity_received_to_inventory,
+ 'Job Receipt', p_job_id, 'job:' || p_job_id,
+ v_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ v_jl_ids := ARRAY[v_labor_jl_id];
+
+ -- CR WIP
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_journal_id, v_wip_account, 'WIP Account',
+ -v_accumulated_wip_cost, v_quantity_received_to_inventory,
+ 'Job Receipt', p_job_id, 'job:' || p_job_id,
+ v_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ v_jl_ids := v_jl_ids || v_labor_jl_id;
+
+ -- Write costLedger entry for finished good
+ INSERT INTO "costLedger" (
+ "itemLedgerType", "costLedgerType", adjustment,
+ "documentType", "documentId", "itemId",
+ quantity, cost, "remainingQuantity", "companyId"
+ ) VALUES (
+ 'Output', 'Direct Cost', false,
+ 'Job Receipt', p_job_id, v_item_id,
+ v_quantity_received_to_inventory, v_accumulated_wip_cost,
+ v_quantity_received_to_inventory, p_company_id
+ );
+
+ -- Update item cost
+ SELECT "costingMethod", "unitCost", "itemPostingGroupId"
+ INTO v_costing_method, v_existing_unit_cost, v_item_posting_group_id
+ FROM "itemCost"
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+
+ v_new_per_unit_cost := v_accumulated_wip_cost / v_quantity_received_to_inventory;
+
+ IF v_costing_method = 'Average' THEN
+ SELECT COALESCE(SUM(quantity), 0)
+ INTO v_total_qty_on_hand
+ FROM "itemLedger"
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+
+ v_prior_qty := v_total_qty_on_hand - v_quantity_received_to_inventory;
+ v_prior_value := v_prior_qty * COALESCE(v_existing_unit_cost, 0);
+
+ IF v_total_qty_on_hand > 0 THEN
+ v_new_unit_cost := (v_prior_value + v_accumulated_wip_cost) / v_total_qty_on_hand;
+ UPDATE "itemCost"
+ SET "unitCost" = v_new_unit_cost
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+ END IF;
+
+ ELSIF v_costing_method IN ('FIFO', 'LIFO') THEN
+ UPDATE "itemCost"
+ SET "unitCost" = v_new_per_unit_cost
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+ END IF;
+
+ -- Insert dimensions on WIP discharge journal lines
+ IF v_jl_ids IS NOT NULL AND array_length(v_jl_ids, 1) > 0 THEN
+ FOR i IN 1..array_length(v_jl_ids, 1)
+ LOOP
+ IF v_item_posting_group_id IS NOT NULL AND v_dimension_item_posting_group IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_item_posting_group, v_item_posting_group_id, p_company_id
+ );
+ END IF;
+
+ IF v_job_location_id IS NOT NULL AND v_dimension_location IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_location, v_job_location_id, p_company_id
+ );
+ END IF;
+ END LOOP;
+ END IF;
+END;
+$$;
+
+-- Update sync_finish_job_operation to backflush materials for MTO jobs
+CREATE OR REPLACE FUNCTION sync_finish_job_operation(
+ p_table TEXT,
+ p_operation TEXT,
+ p_new JSONB,
+ p_old JSONB
+)
+RETURNS VOID
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+DECLARE
+ v_job_status TEXT;
+ v_job_location_id TEXT;
+ v_job_storage_unit_id TEXT;
+ v_job_quantity NUMERIC;
+ v_sales_order_id TEXT;
+ v_quantity_complete NUMERIC;
+BEGIN
+ -- Only fire when status transitions to 'Done'
+ IF p_operation != 'UPDATE' THEN RETURN; END IF;
+ IF (p_new->>'status') != 'Done' OR (p_old->>'status') = 'Done' THEN RETURN; END IF;
+
+ -- Close all open production events for this operation
+ UPDATE "productionEvent"
+ SET "endTime" = NOW()
+ WHERE "jobOperationId" = p_new->>'id'
+ AND "endTime" IS NULL;
+
+ -- Unlock dependent operations whose dependencies are now all done
+ UPDATE "jobOperation" op
+ SET status = 'Ready'
+ WHERE EXISTS (
+ SELECT 1
+ FROM "jobOperationDependency" dep
+ WHERE dep."operationId" = op.id
+ AND dep."dependsOnId" = p_new->>'id'
+ AND op.status = 'Waiting'
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM "jobOperationDependency" dep2
+ JOIN "jobOperation" jo2 ON jo2.id = dep2."dependsOnId"
+ WHERE dep2."operationId" = op.id
+ AND jo2.status != 'Done'
+ AND jo2.id != p_new->>'id'
+ );
+
+ -- Only complete the job if it is in an active state (has been released/started)
+ SELECT status INTO v_job_status FROM "job" WHERE id = p_new->>'jobId';
+ IF v_job_status NOT IN ('Ready', 'In Progress', 'Paused') THEN
+ RETURN;
+ END IF;
+
+ -- If this is the last operation, mark the job as Completed
+ IF is_last_job_operation(p_new->>'id') THEN
+ SELECT "locationId", "storageUnitId", quantity, "salesOrderId"
+ INTO v_job_location_id, v_job_storage_unit_id, v_job_quantity, v_sales_order_id
+ FROM "job"
+ WHERE id = p_new->>'jobId';
+
+ v_quantity_complete := CASE
+ WHEN COALESCE((p_new->>'quantityComplete')::NUMERIC, 0) = 0 THEN v_job_quantity
+ ELSE (p_new->>'quantityComplete')::NUMERIC
+ END;
+
+ IF v_sales_order_id IS NOT NULL THEN
+ -- Make-to-order: update job status and backflush materials
+ UPDATE "job"
+ SET status = 'Completed',
+ "completedDate" = NOW(),
+ "quantityComplete" = v_quantity_complete,
+ "updatedAt" = NOW(),
+ "updatedBy" = p_new->>'updatedBy'
+ WHERE id = p_new->>'jobId';
+
+ PERFORM backflush_job_materials(
+ p_job_id := p_new->>'jobId',
+ p_quantity_complete := v_quantity_complete,
+ p_company_id := p_new->>'companyId',
+ p_user_id := p_new->>'updatedBy'
+ );
+ ELSE
+ -- Make-to-stock: call PL/pgSQL function directly
+ PERFORM complete_job_to_inventory(
+ p_job_id := p_new->>'jobId',
+ p_quantity_complete := v_quantity_complete,
+ p_storage_unit_id := v_job_storage_unit_id,
+ p_location_id := v_job_location_id,
+ p_company_id := p_new->>'companyId',
+ p_user_id := p_new->>'updatedBy'
+ );
+ END IF;
+ END IF;
+END;
+$$;
diff --git a/packages/database/supabase/snippets/Untitled query 159.sql b/packages/database/supabase/snippets/Untitled query 159.sql
new file mode 100644
index 0000000000..cfa3b37eb3
--- /dev/null
+++ b/packages/database/supabase/snippets/Untitled query 159.sql
@@ -0,0 +1,935 @@
+CREATE OR REPLACE FUNCTION backflush_job_materials(
+ p_job_id TEXT,
+ p_quantity_complete NUMERIC,
+ p_company_id TEXT,
+ p_user_id TEXT
+)
+RETURNS VOID
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+DECLARE
+ v_job_quantity NUMERIC;
+ v_job_location_id TEXT;
+ v_job_id_readable TEXT;
+ v_ratio NUMERIC;
+ v_target NUMERIC;
+ v_material RECORD;
+ v_material_qty_to_issue NUMERIC;
+ v_material_storage_unit_id TEXT;
+ v_material_costing_method TEXT;
+ v_material_standard_cost NUMERIC;
+ v_material_unit_cost NUMERIC;
+ v_material_item_posting_group_id TEXT;
+ v_material_cogs_total NUMERIC;
+ v_cost_layer RECORD;
+ v_remaining_to_consume NUMERIC;
+ v_layer_unit_cost NUMERIC;
+ v_quantity_from_layer NUMERIC;
+ v_accounting_enabled BOOLEAN;
+ v_company_group_id TEXT;
+ v_inventory_account TEXT;
+ v_wip_account TEXT;
+ v_dimension_item_posting_group TEXT;
+ v_dimension_location TEXT;
+ v_bf_item_ids TEXT[] := '{}';
+ v_bf_quantities NUMERIC[] := '{}';
+ v_bf_storage_unit_ids TEXT[] := '{}';
+ v_bf_journal_id TEXT;
+ v_bf_journal_entry_id TEXT;
+ v_bf_accounting_period_id TEXT;
+ v_bf_journal_line_ref TEXT;
+ v_bf_jl_id TEXT;
+ v_bf_jl_ids TEXT[];
+ v_bf_posting_group_ids TEXT[];
+BEGIN
+ -- Fetch job details
+ SELECT quantity, "locationId", "jobId"
+ INTO STRICT v_job_quantity, v_job_location_id, v_job_id_readable
+ FROM "job"
+ WHERE id = p_job_id;
+
+ IF v_job_quantity IS NULL OR v_job_quantity <= 0 THEN
+ RETURN;
+ END IF;
+
+ v_ratio := p_quantity_complete / v_job_quantity;
+
+ -- Backflush non-tracked materials
+ FOR v_material IN
+ SELECT jm.id, jm."itemId", jm."quantityToIssue", jm."quantityIssued",
+ jm."estimatedQuantity", jm."storageUnitId", jm."defaultStorageUnit"
+ FROM "jobMaterial" jm
+ WHERE jm."jobId" = p_job_id
+ AND jm."itemType" IN ('Material', 'Part', 'Consumable')
+ AND jm."methodType" != 'Make to Order'
+ AND jm."requiresBatchTracking" = false
+ AND jm."requiresSerialTracking" = false
+ AND jm."quantityToIssue" > 0
+ LOOP
+ -- Prorate: only issue what's needed for the completed quantity
+ v_target := v_material."estimatedQuantity" * v_ratio;
+ v_material_qty_to_issue := GREATEST(v_target - COALESCE(v_material."quantityIssued", 0), 0);
+
+ IF v_material_qty_to_issue <= 0 THEN
+ CONTINUE;
+ END IF;
+
+ -- Resolve storage unit
+ v_material_storage_unit_id := v_material."storageUnitId";
+
+ IF v_material_storage_unit_id IS NULL AND v_material."defaultStorageUnit" THEN
+ SELECT "defaultStorageUnitId" INTO v_material_storage_unit_id
+ FROM "pickMethod"
+ WHERE "itemId" = v_material."itemId"
+ AND "locationId" = v_job_location_id
+ AND "companyId" = p_company_id;
+ END IF;
+
+ IF v_material_storage_unit_id IS NULL THEN
+ SELECT "storageUnitId" INTO v_material_storage_unit_id
+ FROM "itemLedger"
+ WHERE "itemId" = v_material."itemId"
+ AND "locationId" = v_job_location_id
+ AND "storageUnitId" IS NOT NULL
+ GROUP BY "storageUnitId"
+ HAVING SUM(quantity) > 0
+ ORDER BY SUM(quantity) DESC
+ LIMIT 1;
+ END IF;
+
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId", "createdBy"
+ ) VALUES (
+ 'Consumption', 'Job Consumption', p_job_id, p_company_id,
+ v_material."itemId", -v_material_qty_to_issue,
+ v_job_location_id, v_material_storage_unit_id, p_user_id
+ );
+
+ UPDATE "jobMaterial"
+ SET "quantityIssued" = COALESCE("quantityIssued", 0) + v_material_qty_to_issue
+ WHERE id = v_material.id;
+
+ v_bf_item_ids := v_bf_item_ids || v_material."itemId";
+ v_bf_quantities := v_bf_quantities || v_material_qty_to_issue;
+ v_bf_storage_unit_ids := v_bf_storage_unit_ids || COALESCE(v_material_storage_unit_id, '');
+ END LOOP;
+
+ -- Check if accounting is enabled
+ SELECT "accountingEnabled"
+ INTO v_accounting_enabled
+ FROM "companySettings"
+ WHERE id = p_company_id;
+
+ v_accounting_enabled := COALESCE(v_accounting_enabled, false);
+
+ IF NOT v_accounting_enabled THEN
+ RETURN;
+ END IF;
+
+ IF array_length(v_bf_item_ids, 1) IS NULL OR array_length(v_bf_item_ids, 1) = 0 THEN
+ RETURN;
+ END IF;
+
+ -- Fetch company group
+ SELECT "companyGroupId"
+ INTO STRICT v_company_group_id
+ FROM company
+ WHERE id = p_company_id;
+
+ -- Fetch account defaults
+ SELECT "inventoryAccount", "workInProgressAccount"
+ INTO STRICT v_inventory_account, v_wip_account
+ FROM "accountDefault"
+ WHERE "companyId" = p_company_id;
+
+ -- Fetch dimension IDs
+ SELECT
+ MAX(CASE WHEN "entityType" = 'ItemPostingGroup' THEN id END),
+ MAX(CASE WHEN "entityType" = 'Location' THEN id END)
+ INTO v_dimension_item_posting_group, v_dimension_location
+ FROM dimension
+ WHERE "companyGroupId" = v_company_group_id
+ AND active = true
+ AND "entityType" IN ('ItemPostingGroup', 'Location');
+
+ -- Get accounting period
+ SELECT id INTO v_bf_accounting_period_id
+ FROM "accountingPeriod"
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= CURRENT_DATE
+ AND "endDate" >= CURRENT_DATE
+ AND status = 'Active'
+ LIMIT 1;
+
+ IF v_bf_accounting_period_id IS NULL THEN
+ UPDATE "accountingPeriod"
+ SET status = 'Inactive'
+ WHERE status = 'Active' AND "companyId" = p_company_id;
+
+ UPDATE "accountingPeriod"
+ SET status = 'Active'
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= CURRENT_DATE
+ AND "endDate" >= CURRENT_DATE
+ RETURNING id INTO v_bf_accounting_period_id;
+
+ IF v_bf_accounting_period_id IS NULL THEN
+ INSERT INTO "accountingPeriod" (
+ "startDate", "endDate", "companyId", status, "createdBy"
+ ) VALUES (
+ date_trunc('month', CURRENT_DATE)::DATE,
+ (date_trunc('month', CURRENT_DATE) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,
+ p_company_id, 'Active', 'system'
+ )
+ RETURNING id INTO v_bf_accounting_period_id;
+ END IF;
+ END IF;
+
+ v_bf_journal_entry_id := get_next_sequence('journalEntry', p_company_id);
+
+ INSERT INTO journal (
+ "journalEntryId", "accountingPeriodId", description,
+ "postingDate", "companyId", "sourceType", status,
+ "postedAt", "postedBy", "createdBy"
+ ) VALUES (
+ v_bf_journal_entry_id, v_bf_accounting_period_id,
+ 'Material Issue — Job ' || v_job_id_readable,
+ CURRENT_DATE, p_company_id, 'Job Consumption', 'Posted',
+ NOW(), p_user_id, p_user_id
+ )
+ RETURNING id INTO v_bf_journal_id;
+
+ v_bf_jl_ids := '{}';
+ v_bf_posting_group_ids := '{}';
+
+ FOR i IN 1..array_length(v_bf_item_ids, 1)
+ LOOP
+ -- Get itemCost for COGS calculation
+ SELECT "costingMethod", "standardCost", "unitCost", "itemPostingGroupId"
+ INTO v_material_costing_method, v_material_standard_cost, v_material_unit_cost, v_material_item_posting_group_id
+ FROM "itemCost"
+ WHERE "itemId" = v_bf_item_ids[i]
+ AND "companyId" = p_company_id;
+
+ IF v_material_costing_method IS NULL THEN
+ CONTINUE;
+ END IF;
+
+ -- Calculate COGS based on costing method
+ v_material_cogs_total := 0;
+
+ IF v_material_costing_method = 'Standard' THEN
+ v_material_cogs_total := COALESCE(v_material_standard_cost, 0) * v_bf_quantities[i];
+
+ ELSIF v_material_costing_method = 'Average' THEN
+ v_material_cogs_total := COALESCE(v_material_unit_cost, 0) * v_bf_quantities[i];
+
+ ELSIF v_material_costing_method IN ('FIFO', 'LIFO') THEN
+ v_remaining_to_consume := v_bf_quantities[i];
+
+ FOR v_cost_layer IN
+ SELECT id, quantity, cost, "remainingQuantity"
+ FROM "costLedger"
+ WHERE "itemId" = v_bf_item_ids[i]
+ AND "companyId" = p_company_id
+ AND "remainingQuantity" > 0
+ ORDER BY
+ CASE WHEN v_material_costing_method = 'FIFO' THEN "postingDate" END ASC,
+ CASE WHEN v_material_costing_method = 'LIFO' THEN "postingDate" END DESC,
+ CASE WHEN v_material_costing_method = 'FIFO' THEN "createdAt" END ASC,
+ CASE WHEN v_material_costing_method = 'LIFO' THEN "createdAt" END DESC
+ LOOP
+ EXIT WHEN v_remaining_to_consume <= 0;
+
+ v_layer_unit_cost := CASE
+ WHEN v_cost_layer.quantity > 0 THEN v_cost_layer.cost / v_cost_layer.quantity
+ ELSE 0
+ END;
+
+ v_quantity_from_layer := LEAST(v_remaining_to_consume, v_cost_layer."remainingQuantity");
+ v_material_cogs_total := v_material_cogs_total + v_quantity_from_layer * v_layer_unit_cost;
+ v_remaining_to_consume := v_remaining_to_consume - v_quantity_from_layer;
+
+ UPDATE "costLedger"
+ SET "remainingQuantity" = "remainingQuantity" - v_quantity_from_layer
+ WHERE id = v_cost_layer.id;
+ END LOOP;
+
+ -- Fallback for negative inventory
+ IF v_remaining_to_consume > 0 THEN
+ v_material_cogs_total := v_material_cogs_total + v_remaining_to_consume * COALESCE(v_material_unit_cost, 0);
+ END IF;
+ END IF;
+
+ IF v_material_cogs_total <= 0 THEN
+ CONTINUE;
+ END IF;
+
+ v_bf_journal_line_ref := nanoid();
+
+ -- DR WIP
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_bf_journal_id, v_wip_account, 'WIP Account',
+ v_material_cogs_total, v_bf_quantities[i],
+ 'Job Consumption', p_job_id, 'job:' || p_job_id,
+ v_bf_journal_line_ref, p_company_id
+ )
+ RETURNING id INTO v_bf_jl_id;
+
+ v_bf_jl_ids := v_bf_jl_ids || v_bf_jl_id;
+ v_bf_posting_group_ids := v_bf_posting_group_ids || COALESCE(v_material_item_posting_group_id, '');
+
+ -- CR Inventory
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_bf_journal_id, v_inventory_account, 'Inventory Account',
+ -v_material_cogs_total, v_bf_quantities[i],
+ 'Job Consumption', p_job_id, 'job:' || p_job_id,
+ v_bf_journal_line_ref, p_company_id
+ )
+ RETURNING id INTO v_bf_jl_id;
+
+ v_bf_jl_ids := v_bf_jl_ids || v_bf_jl_id;
+ v_bf_posting_group_ids := v_bf_posting_group_ids || COALESCE(v_material_item_posting_group_id, '');
+
+ -- Cost ledger entry for consumption
+ INSERT INTO "costLedger" (
+ "itemLedgerType", "costLedgerType", adjustment,
+ "documentType", "documentId", "itemId",
+ quantity, cost, "remainingQuantity", "companyId"
+ ) VALUES (
+ 'Consumption', 'Direct Cost', false,
+ 'Job Consumption', p_job_id, v_bf_item_ids[i],
+ -v_bf_quantities[i], -v_material_cogs_total,
+ 0, p_company_id
+ );
+ END LOOP;
+
+ -- Dimensions for material consumption journal lines
+ IF array_length(v_bf_jl_ids, 1) IS NOT NULL THEN
+ FOR i IN 1..array_length(v_bf_jl_ids, 1)
+ LOOP
+ IF v_bf_posting_group_ids[i] != '' AND v_dimension_item_posting_group IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_bf_jl_ids[i], v_dimension_item_posting_group, v_bf_posting_group_ids[i], p_company_id
+ );
+ END IF;
+
+ IF v_job_location_id IS NOT NULL AND v_dimension_location IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_bf_jl_ids[i], v_dimension_location, v_job_location_id, p_company_id
+ );
+ END IF;
+ END LOOP;
+ END IF;
+END;
+$$;
+
+-- Refactor complete_job_to_inventory to delegate backflush to the new function
+CREATE OR REPLACE FUNCTION complete_job_to_inventory(
+ p_job_id TEXT,
+ p_quantity_complete NUMERIC,
+ p_storage_unit_id TEXT DEFAULT NULL,
+ p_location_id TEXT DEFAULT NULL,
+ p_company_id TEXT DEFAULT NULL,
+ p_user_id TEXT DEFAULT NULL
+)
+RETURNS VOID
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+DECLARE
+ v_item_id TEXT;
+ v_quantity_received_to_inventory NUMERIC;
+ v_job_id_readable TEXT;
+ v_job_make_method RECORD;
+ v_tracked_entity RECORD;
+ v_accounting_enabled BOOLEAN;
+ v_company_group_id TEXT;
+ v_inventory_account TEXT;
+ v_wip_account TEXT;
+ v_labor_absorption_account TEXT;
+ v_dimension_item_posting_group TEXT;
+ v_dimension_location TEXT;
+ v_dimension_cost_center TEXT;
+ v_dimension_employee TEXT;
+ v_event RECORD;
+ v_duration_hours NUMERIC;
+ v_rate NUMERIC;
+ v_labor_cost NUMERIC;
+ v_labor_journal_line_reference TEXT;
+ v_labor_accounting_period_id TEXT;
+ v_labor_journal_entry_id TEXT;
+ v_labor_journal_id TEXT;
+ v_labor_jl_id TEXT;
+ v_accumulated_wip_cost NUMERIC;
+ v_today DATE;
+ v_journal_line_reference TEXT;
+ v_accounting_period_id TEXT;
+ v_journal_entry_id TEXT;
+ v_journal_id TEXT;
+ v_jl_ids TEXT[];
+ v_new_per_unit_cost NUMERIC;
+ v_costing_method TEXT;
+ v_existing_unit_cost NUMERIC;
+ v_item_posting_group_id TEXT;
+ v_job_location_id TEXT;
+ v_total_qty_on_hand NUMERIC;
+ v_prior_qty NUMERIC;
+ v_prior_value NUMERIC;
+ v_new_unit_cost NUMERIC;
+BEGIN
+ -- Fetch job details
+ SELECT "itemId", "quantityReceivedToInventory", "jobId", "locationId"
+ INTO STRICT v_item_id, v_quantity_received_to_inventory, v_job_id_readable, v_job_location_id
+ FROM "job"
+ WHERE id = p_job_id;
+
+ v_quantity_received_to_inventory := p_quantity_complete - COALESCE(v_quantity_received_to_inventory, 0);
+
+ -- Fetch jobMakeMethod for the top-level (no parentMaterialId)
+ SELECT *
+ INTO STRICT v_job_make_method
+ FROM "jobMakeMethod"
+ WHERE "jobId" = p_job_id
+ AND "parentMaterialId" IS NULL;
+
+ -- Update job status
+ UPDATE "job"
+ SET status = 'Completed',
+ "completedDate" = NOW(),
+ "quantityComplete" = p_quantity_complete,
+ "quantityReceivedToInventory" = v_quantity_received_to_inventory,
+ "updatedAt" = NOW(),
+ "updatedBy" = p_user_id
+ WHERE id = p_job_id;
+
+ -- Insert itemLedger entries based on tracking type
+ IF v_job_make_method."requiresBatchTracking" THEN
+ SELECT *
+ INTO v_tracked_entity
+ FROM "trackedEntity"
+ WHERE attributes->>'Job Make Method' = v_job_make_method.id
+ AND status != 'Consumed'
+ ORDER BY "createdAt" DESC
+ LIMIT 1;
+
+ IF v_tracked_entity.id IS NULL THEN
+ RAISE EXCEPTION 'Tracked entity not found';
+ END IF;
+
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId",
+ "trackedEntityId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,
+ v_tracked_entity.id, p_user_id
+ );
+
+ ELSIF v_job_make_method."requiresSerialTracking" THEN
+ FOR v_tracked_entity IN
+ SELECT *
+ FROM "trackedEntity"
+ WHERE attributes->>'Job Make Method' = v_job_make_method.id
+ AND status != 'Consumed'
+ LOOP
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId",
+ "trackedEntityId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, 1, p_location_id, p_storage_unit_id,
+ v_tracked_entity.id, p_user_id
+ );
+ END LOOP;
+
+ UPDATE "trackedEntity"
+ SET status = 'Available'
+ WHERE attributes->>'Job Make Method' = v_job_make_method.id
+ AND status != 'Consumed';
+
+ ELSE
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,
+ p_user_id
+ );
+ END IF;
+
+ -- Update pickMethod defaultStorageUnitId if needed
+ IF p_storage_unit_id IS NOT NULL AND p_location_id IS NOT NULL THEN
+ IF NOT EXISTS (
+ SELECT 1 FROM "itemLedger"
+ WHERE "itemId" = v_item_id
+ AND "locationId" = p_location_id
+ AND "storageUnitId" IS NOT NULL
+ AND "storageUnitId" != p_storage_unit_id
+ LIMIT 1
+ ) THEN
+ IF EXISTS (
+ SELECT 1 FROM "pickMethod"
+ WHERE "itemId" = v_item_id AND "locationId" = p_location_id
+ ) THEN
+ UPDATE "pickMethod"
+ SET "defaultStorageUnitId" = p_storage_unit_id,
+ "updatedBy" = p_user_id,
+ "updatedAt" = NOW()
+ WHERE "itemId" = v_item_id
+ AND "locationId" = p_location_id;
+ ELSE
+ INSERT INTO "pickMethod" (
+ "itemId", "locationId", "defaultStorageUnitId",
+ "companyId", "createdBy", "createdAt"
+ ) VALUES (
+ v_item_id, p_location_id, p_storage_unit_id,
+ p_company_id, p_user_id, NOW()
+ );
+ END IF;
+ END IF;
+ END IF;
+
+ -- Backflush unissued materials (delegated to shared function)
+ PERFORM backflush_job_materials(p_job_id, p_quantity_complete, p_company_id, p_user_id);
+
+ -- Check if accounting is enabled
+ SELECT "accountingEnabled"
+ INTO v_accounting_enabled
+ FROM "companySettings"
+ WHERE id = p_company_id;
+
+ v_accounting_enabled := COALESCE(v_accounting_enabled, false);
+
+ IF NOT v_accounting_enabled THEN
+ RETURN;
+ END IF;
+
+ -- Fetch company group
+ SELECT "companyGroupId"
+ INTO STRICT v_company_group_id
+ FROM company
+ WHERE id = p_company_id;
+
+ -- Fetch account defaults
+ SELECT "inventoryAccount", "workInProgressAccount", "laborAbsorptionAccount"
+ INTO STRICT v_inventory_account, v_wip_account, v_labor_absorption_account
+ FROM "accountDefault"
+ WHERE "companyId" = p_company_id;
+
+ -- Fetch dimension IDs
+ SELECT
+ MAX(CASE WHEN "entityType" = 'ItemPostingGroup' THEN id END),
+ MAX(CASE WHEN "entityType" = 'Location' THEN id END),
+ MAX(CASE WHEN "entityType" = 'CostCenter' THEN id END),
+ MAX(CASE WHEN "entityType" = 'Employee' THEN id END)
+ INTO v_dimension_item_posting_group, v_dimension_location,
+ v_dimension_cost_center, v_dimension_employee
+ FROM dimension
+ WHERE "companyGroupId" = v_company_group_id
+ AND active = true
+ AND "entityType" IN ('ItemPostingGroup', 'Location', 'CostCenter', 'Employee');
+
+ -- Post unposted production events as labor/machine absorption JEs
+ FOR v_event IN
+ SELECT
+ pe.id,
+ pe.duration,
+ pe.type,
+ pe."employeeId",
+ wc."laborRate",
+ wc."machineRate"
+ FROM "productionEvent" pe
+ INNER JOIN "jobOperation" jo ON jo.id = pe."jobOperationId"
+ INNER JOIN "workCenter" wc ON wc.id = pe."workCenterId"
+ WHERE jo."jobId" = p_job_id
+ AND pe."endTime" IS NOT NULL
+ AND pe."postedToGL" = false
+ AND pe.duration > 0
+ LOOP
+ v_duration_hours := v_event.duration::NUMERIC / 3600;
+ v_rate := CASE
+ WHEN v_event.type = 'Machine' THEN COALESCE(v_event."machineRate", 0)
+ ELSE COALESCE(v_event."laborRate", 0)
+ END;
+ v_labor_cost := v_duration_hours * v_rate;
+
+ IF v_labor_cost > 0 AND v_labor_absorption_account IS NOT NULL THEN
+ v_labor_journal_line_reference := nanoid();
+
+ -- Get current accounting period
+ SELECT id INTO v_labor_accounting_period_id
+ FROM "accountingPeriod"
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= CURRENT_DATE
+ AND "endDate" >= CURRENT_DATE
+ AND status = 'Active'
+ LIMIT 1;
+
+ IF v_labor_accounting_period_id IS NULL THEN
+ UPDATE "accountingPeriod"
+ SET status = 'Inactive'
+ WHERE status = 'Active' AND "companyId" = p_company_id;
+
+ UPDATE "accountingPeriod"
+ SET status = 'Active'
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= CURRENT_DATE
+ AND "endDate" >= CURRENT_DATE
+ RETURNING id INTO v_labor_accounting_period_id;
+
+ IF v_labor_accounting_period_id IS NULL THEN
+ INSERT INTO "accountingPeriod" (
+ "startDate", "endDate", "companyId", status, "createdBy"
+ ) VALUES (
+ date_trunc('month', CURRENT_DATE)::DATE,
+ (date_trunc('month', CURRENT_DATE) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,
+ p_company_id, 'Active', 'system'
+ )
+ RETURNING id INTO v_labor_accounting_period_id;
+ END IF;
+ END IF;
+
+ v_labor_journal_entry_id := get_next_sequence('journalEntry', p_company_id);
+
+ INSERT INTO journal (
+ "journalEntryId", "accountingPeriodId", description,
+ "postingDate", "companyId", "sourceType", status,
+ "postedAt", "postedBy", "createdBy"
+ ) VALUES (
+ v_labor_journal_entry_id, v_labor_accounting_period_id,
+ v_event.type || ' Time — Job ' || v_job_id_readable,
+ CURRENT_DATE, p_company_id, 'Production Event', 'Posted',
+ NOW(), p_user_id, p_user_id
+ )
+ RETURNING id INTO v_labor_journal_id;
+
+ -- DR WIP
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_wip_account, 'WIP Account',
+ v_labor_cost, 1,
+ 'Production Event', p_job_id, 'job:' || p_job_id,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on WIP line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- CR Labor/Machine Absorption
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_labor_absorption_account, 'Labor/Machine Absorption',
+ -v_labor_cost, 1,
+ 'Production Event', p_job_id, 'job:' || p_job_id,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on absorption line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+ END IF;
+
+ UPDATE "productionEvent"
+ SET "postedToGL" = true
+ WHERE id = v_event.id;
+ END LOOP;
+
+ -- Calculate accumulated WIP cost for this job
+ SELECT COALESCE(ABS(SUM(jl.amount)), 0)
+ INTO v_accumulated_wip_cost
+ FROM "journalLine" jl
+ INNER JOIN journal j ON j.id = jl."journalId"
+ WHERE jl."accountId" = v_wip_account
+ AND jl."documentId" = p_job_id
+ AND j."companyId" = p_company_id;
+
+ IF v_accumulated_wip_cost <= 0 THEN
+ RETURN;
+ END IF;
+
+ v_today := CURRENT_DATE;
+ v_journal_line_reference := nanoid();
+
+ -- Get accounting period for WIP discharge
+ SELECT id INTO v_accounting_period_id
+ FROM "accountingPeriod"
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_today
+ AND "endDate" >= v_today
+ AND status = 'Active'
+ LIMIT 1;
+
+ IF v_accounting_period_id IS NULL THEN
+ UPDATE "accountingPeriod"
+ SET status = 'Inactive'
+ WHERE status = 'Active' AND "companyId" = p_company_id;
+
+ UPDATE "accountingPeriod"
+ SET status = 'Active'
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_today
+ AND "endDate" >= v_today
+ RETURNING id INTO v_accounting_period_id;
+
+ IF v_accounting_period_id IS NULL THEN
+ INSERT INTO "accountingPeriod" (
+ "startDate", "endDate", "companyId", status, "createdBy"
+ ) VALUES (
+ date_trunc('month', v_today)::DATE,
+ (date_trunc('month', v_today) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,
+ p_company_id, 'Active', 'system'
+ )
+ RETURNING id INTO v_accounting_period_id;
+ END IF;
+ END IF;
+
+ v_journal_entry_id := get_next_sequence('journalEntry', p_company_id);
+
+ INSERT INTO journal (
+ "journalEntryId", "accountingPeriodId", description,
+ "postingDate", "companyId", "sourceType", status,
+ "postedAt", "postedBy", "createdBy"
+ ) VALUES (
+ v_journal_entry_id, v_accounting_period_id,
+ 'Job Completion ' || v_job_id_readable,
+ v_today, p_company_id, 'Job Receipt', 'Posted',
+ NOW(), p_user_id, p_user_id
+ )
+ RETURNING id INTO v_journal_id;
+
+ -- DR FG Inventory
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_journal_id, v_inventory_account, 'Finished Goods Inventory',
+ v_accumulated_wip_cost, v_quantity_received_to_inventory,
+ 'Job Receipt', p_job_id, 'job:' || p_job_id,
+ v_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ v_jl_ids := ARRAY[v_labor_jl_id];
+
+ -- CR WIP
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_journal_id, v_wip_account, 'WIP Account',
+ -v_accumulated_wip_cost, v_quantity_received_to_inventory,
+ 'Job Receipt', p_job_id, 'job:' || p_job_id,
+ v_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ v_jl_ids := v_jl_ids || v_labor_jl_id;
+
+ -- Write costLedger entry for finished good
+ INSERT INTO "costLedger" (
+ "itemLedgerType", "costLedgerType", adjustment,
+ "documentType", "documentId", "itemId",
+ quantity, cost, "remainingQuantity", "companyId"
+ ) VALUES (
+ 'Output', 'Direct Cost', false,
+ 'Job Receipt', p_job_id, v_item_id,
+ v_quantity_received_to_inventory, v_accumulated_wip_cost,
+ v_quantity_received_to_inventory, p_company_id
+ );
+
+ -- Update item cost
+ SELECT "costingMethod", "unitCost", "itemPostingGroupId"
+ INTO v_costing_method, v_existing_unit_cost, v_item_posting_group_id
+ FROM "itemCost"
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+
+ v_new_per_unit_cost := v_accumulated_wip_cost / v_quantity_received_to_inventory;
+
+ IF v_costing_method = 'Average' THEN
+ SELECT COALESCE(SUM(quantity), 0)
+ INTO v_total_qty_on_hand
+ FROM "itemLedger"
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+
+ v_prior_qty := v_total_qty_on_hand - v_quantity_received_to_inventory;
+ v_prior_value := v_prior_qty * COALESCE(v_existing_unit_cost, 0);
+
+ IF v_total_qty_on_hand > 0 THEN
+ v_new_unit_cost := (v_prior_value + v_accumulated_wip_cost) / v_total_qty_on_hand;
+ UPDATE "itemCost"
+ SET "unitCost" = v_new_unit_cost
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+ END IF;
+
+ ELSIF v_costing_method IN ('FIFO', 'LIFO') THEN
+ UPDATE "itemCost"
+ SET "unitCost" = v_new_per_unit_cost
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+ END IF;
+
+ -- Insert dimensions on WIP discharge journal lines
+ IF v_jl_ids IS NOT NULL AND array_length(v_jl_ids, 1) > 0 THEN
+ FOR i IN 1..array_length(v_jl_ids, 1)
+ LOOP
+ IF v_item_posting_group_id IS NOT NULL AND v_dimension_item_posting_group IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_item_posting_group, v_item_posting_group_id, p_company_id
+ );
+ END IF;
+
+ IF v_job_location_id IS NOT NULL AND v_dimension_location IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_location, v_job_location_id, p_company_id
+ );
+ END IF;
+ END LOOP;
+ END IF;
+END;
+$$;
+
+-- Update sync_finish_job_operation to backflush materials for MTO jobs
+CREATE OR REPLACE FUNCTION sync_finish_job_operation(
+ p_table TEXT,
+ p_operation TEXT,
+ p_new JSONB,
+ p_old JSONB
+)
+RETURNS VOID
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+DECLARE
+ v_job_status TEXT;
+ v_job_location_id TEXT;
+ v_job_storage_unit_id TEXT;
+ v_job_quantity NUMERIC;
+ v_sales_order_id TEXT;
+ v_quantity_complete NUMERIC;
+BEGIN
+ -- Only fire when status transitions to 'Done'
+ IF p_operation != 'UPDATE' THEN RETURN; END IF;
+ IF (p_new->>'status') != 'Done' OR (p_old->>'status') = 'Done' THEN RETURN; END IF;
+
+ -- Close all open production events for this operation
+ UPDATE "productionEvent"
+ SET "endTime" = NOW()
+ WHERE "jobOperationId" = p_new->>'id'
+ AND "endTime" IS NULL;
+
+ -- Unlock dependent operations whose dependencies are now all done
+ UPDATE "jobOperation" op
+ SET status = 'Ready'
+ WHERE EXISTS (
+ SELECT 1
+ FROM "jobOperationDependency" dep
+ WHERE dep."operationId" = op.id
+ AND dep."dependsOnId" = p_new->>'id'
+ AND op.status = 'Waiting'
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM "jobOperationDependency" dep2
+ JOIN "jobOperation" jo2 ON jo2.id = dep2."dependsOnId"
+ WHERE dep2."operationId" = op.id
+ AND jo2.status != 'Done'
+ AND jo2.id != p_new->>'id'
+ );
+
+ -- Only complete the job if it is in an active state (has been released/started)
+ SELECT status INTO v_job_status FROM "job" WHERE id = p_new->>'jobId';
+ IF v_job_status NOT IN ('Ready', 'In Progress', 'Paused') THEN
+ RETURN;
+ END IF;
+
+ -- If this is the last operation, mark the job as Completed
+ IF is_last_job_operation(p_new->>'id') THEN
+ SELECT "locationId", "storageUnitId", quantity, "salesOrderId"
+ INTO v_job_location_id, v_job_storage_unit_id, v_job_quantity, v_sales_order_id
+ FROM "job"
+ WHERE id = p_new->>'jobId';
+
+ v_quantity_complete := CASE
+ WHEN COALESCE((p_new->>'quantityComplete')::NUMERIC, 0) = 0 THEN v_job_quantity
+ ELSE (p_new->>'quantityComplete')::NUMERIC
+ END;
+
+ IF v_sales_order_id IS NOT NULL THEN
+ -- Make-to-order: update job status and backflush materials
+ UPDATE "job"
+ SET status = 'Completed',
+ "completedDate" = NOW(),
+ "quantityComplete" = v_quantity_complete,
+ "updatedAt" = NOW(),
+ "updatedBy" = p_new->>'updatedBy'
+ WHERE id = p_new->>'jobId';
+
+ PERFORM backflush_job_materials(
+ p_job_id := p_new->>'jobId',
+ p_quantity_complete := v_quantity_complete,
+ p_company_id := p_new->>'companyId',
+ p_user_id := p_new->>'updatedBy'
+ );
+ ELSE
+ -- Make-to-stock: call PL/pgSQL function directly
+ PERFORM complete_job_to_inventory(
+ p_job_id := p_new->>'jobId',
+ p_quantity_complete := v_quantity_complete,
+ p_storage_unit_id := v_job_storage_unit_id,
+ p_location_id := v_job_location_id,
+ p_company_id := p_new->>'companyId',
+ p_user_id := p_new->>'updatedBy'
+ );
+ END IF;
+ END IF;
+END;
+$$;