Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(sales, purchasing, mes): partial invoices bill flat charges once; MES timers start once (#2067)
Sid8140e987ac41
diff --git a/.claude/rules/oee-provider.md b/.claude/rules/oee-provider.mdindex b22567a524..2154ec81ee 100644--- a/.claude/rules/oee-provider.md+++ b/.claude/rules/oee-provider.md@@ -103,9 +103,10 @@ exposes the open row's operation as `loadedJobOperationId`.- **Older starts are refused.** A start earlier than the newest boundary inthe work center's history (the latest `loadedAt` or `unloadedAt`) writesnothing, so a late event never undoes a later load or unload. A reload of- the operation already loaded writes nothing. There is no status rule: a- starting event reopens a Done operation first- (`sync_set_job_operation_in_progress`, a BEFORE interceptor).+ the operation already loaded writes nothing. A Done or Canceled operation+ never loads: a starting event does not reopen it+ (`sync_set_job_operation_in_progress`), and its unload only runs on a status+ change, so that load would never close.- **Unload.** A `jobOperation` status change to `Done` or `Canceled` ends theoperation's open row, and so does deleting the operation or moving it toanother work center (the old work center unloads). An unload setsdiff --git a/apps/erp/app/modules/production/production.server.ts b/apps/erp/app/modules/production/production.server.tsindex 43381524db..0f08e3d29d 100644--- a/apps/erp/app/modules/production/production.server.ts+++ b/apps/erp/app/modules/production/production.server.ts@@ -1415,6 +1415,7 @@ export const moveScheduleJob = defineServiceFn({return { id };}});+/*** Record a production event (labor, machine or setup time) on a job operation.*@@ -1455,6 +1456,9 @@ export const createProductionEvent = defineServiceFn({createdBy: ctx.auditUserId});if (insert.error) {+ if (service.isSecondOpenTimer(insert.error)) {+ return ctx.error("rule", service.SECOND_OPEN_TIMER_MESSAGE);+ }return ctx.error("internal","Failed to insert production event",@@ -1493,6 +1497,9 @@ export const updateProductionEvent = defineServiceFn({updatedBy: ctx.auditUserId});if (update.error) {+ if (service.isSecondOpenTimer(update.error)) {+ return ctx.error("rule", service.SECOND_OPEN_TIMER_MESSAGE);+ }return ctx.error("internal","Failed to update production event",diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex 08da493fce..5b83818067 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -3531,6 +3531,17 @@ export async function updateProcedureStepOrder(return Promise.all(updatePromises);}+export const SECOND_OPEN_TIMER_MESSAGE =+ "This employee already has an open event of this type on this operation. End it before adding another.";++/** One open Setup or Labor event per employee per operation (productionEvent_one_open_per_operator_idx). */+export function isSecondOpenTimer(error: { code?: string; message?: string }) {+ return (+ error.code === "23505" &&+ (error.message ?? "").includes("productionEvent_one_open_per_operator_idx")+ );+}+/** The row write only; `createProductionEvent` / `updateProductionEvent` also post the time to the GL. */export async function upsertProductionEvent(client: SupabaseClient<Database>,diff --git a/apps/erp/app/modules/shared/flat-charge-share.test.ts b/apps/erp/app/modules/shared/flat-charge-share.test.tsnew file mode 100644index 0000000000..91bd6c74b1--- /dev/null+++ b/apps/erp/app/modules/shared/flat-charge-share.test.ts@@ -0,0 +1,83 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it, vi } from "vitest";++// shared.utils' graph loads @carbon/content/glossary, whose module-load Lingui+// `msg` macro is not transformed under plain vitest.+vi.mock("@carbon/content/glossary", () => ({+ terms: {},+ getEntry: vi.fn(),+ lookupEntry: vi.fn(),+ hasEntry: vi.fn(),+ termSlug: vi.fn()+}));++const { flatChargeShare } = await import("./shared.utils");++/** Bills `charge` over invoices of the given quantities, the way a conversion does. */+function billInParts(charge: number, ordered: number, parts: number[]) {+ let billed = 0;+ let invoiced = 0;+ return parts.map((quantity) => {+ const share = flatChargeShare({+ charge,+ billed,+ quantity,+ remainingQuantity: ordered - invoiced,+ orderedQuantity: ordered,+ decimals: 2+ });+ billed += share;+ invoiced += quantity;+ return share;+ });+}++describe("flatChargeShare", () => {+ it("bills a charge once across partial invoices", () => {+ expect(billInParts(50, 10, [4, 6])).toEqual([20, 30]);+ });++ it("rounds each share to the currency and gives the last the remainder", () => {+ const shares = billInParts(50, 3, [1, 1, 1]);+ expect(shares).toEqual([16.67, 16.67, 16.66]);+ expect(shares.reduce((a, b) => a + b, 0)).toBeCloseTo(50, 10);+ });++ it("bills the whole charge on a full invoice", () => {+ expect(billInParts(50, 10, [10])).toEqual([50]);+ });++ it("bills only what an earlier invoice left after it was edited", () => {+ // Invoice A billed all 50 for 10, then was edited down to 4; B bills 6.+ expect(+ flatChargeShare({+ charge: 50,+ billed: 50,+ quantity: 6,+ remainingQuantity: 6,+ orderedQuantity: 10,+ decimals: 2+ })+ ).toBe(0);+ });++ it("bills the whole charge when no quantity was ordered", () => {+ expect(+ flatChargeShare({+ charge: 50,+ billed: 0,+ quantity: 1,+ remainingQuantity: 0,+ orderedQuantity: 0,+ decimals: 2+ })+ ).toBe(50);+ });++ it("bills a negative charge (a credit) the same way", () => {+ expect(billInParts(-30, 3, [1, 2])).toEqual([-10, -20]);+ });+});diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.tsindex 0207c81815..0c0e44613a 100644--- a/apps/erp/app/modules/shared/shared.service.ts+++ b/apps/erp/app/modules/shared/shared.service.ts@@ -202,6 +202,7 @@ import {type standardFactorType,toTiptapDoc} from "./shared.models";+import { flatChargeShare } from "./shared.utils";import { assertMethodHasPullFrom, isStrictBackflush } from "./strict-backflush";import type { ItemModelUpload, MethodRowsAdded } from "./types";@@ -8865,6 +8866,154 @@ function orderShipToCustomerLocationId(: order.customerLocationId;}+/** Base-currency settlement decimals; sales line charges are stored in base. */+async function baseCurrencyDecimals(+ trx: Transaction<KyselyDatabase>,+ companyId: string+): Promise<number> {+ const company = await trx+ .selectFrom("company")+ .select("baseCurrencyCode")+ .where("id", "=", companyId)+ .executeTakeFirstOrThrow();+ return currencyDecimals(trx, companyId, company.baseCurrencyCode);+}++type BilledLineCharges = Map<string, Record<string, number>>;++function sumBilledLineCharges<Row extends { lineId: string | null }>(+ rows: Row[],+ fields: (keyof Row & string)[]+): BilledLineCharges {+ const byLine: BilledLineCharges = new Map();+ for (const row of rows) {+ if (!row.lineId) continue;+ const billed = byLine.get(row.lineId) ?? {};+ for (const field of fields) {+ billed[field] = (billed[field] ?? 0) + Number(row[field] ?? 0);+ }+ byLine.set(row.lineId, billed);+ }+ return byLine;+}++/**+ * What a sales order's non-voided invoices already bill of its flat charges:+ * the order's shipping, and each line's add-ons and shipping. Locks the order+ * row first, so two conversions of one order run one after the other and the+ * second sees what the first billed.+ */+async function billedSalesOrderCharges(+ trx: Transaction<KyselyDatabase>,+ companyId: string,+ salesOrderId: string+) {+ await trx+ .selectFrom("salesOrder")+ .select("id")+ .where("id", "=", salesOrderId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();++ const lines = await trx+ .selectFrom("salesInvoiceLine")+ .innerJoin("salesInvoice", "salesInvoice.id", "salesInvoiceLine.invoiceId")+ .select([+ "salesInvoiceLine.invoiceId",+ "salesInvoiceLine.salesOrderLineId as lineId",+ "salesInvoiceLine.addOnCost",+ "salesInvoiceLine.nonTaxableAddOnCost",+ "salesInvoiceLine.shippingCost"+ ])+ .where("salesInvoiceLine.salesOrderId", "=", salesOrderId)+ .where("salesInvoiceLine.companyId", "=", companyId)+ .where("salesInvoice.status", "!=", "Voided")+ .execute();++ const invoiceIds = [...new Set(lines.map((line) => line.invoiceId))];+ const shipping =+ invoiceIds.length > 0+ ? await trx+ .selectFrom("salesInvoiceShipment")+ .select("shippingCost")+ .where("id", "in", invoiceIds)+ .where("companyId", "=", companyId)+ .execute()+ : [];++ return {+ orderShipping: shipping.reduce(+ (sum, row) => sum + Number(row.shippingCost ?? 0),+ 0+ ),+ lines: sumBilledLineCharges(lines, [+ "addOnCost",+ "nonTaxableAddOnCost",+ "shippingCost"+ ])+ };+}++/**+ * What a purchase order's non-voided invoices already bill of its flat+ * charges: the supplier's shipping, and each line's shipping and tax. Locks+ * the order row first, like `billedSalesOrderCharges`.+ */+async function billedPurchaseOrderCharges(+ trx: Transaction<KyselyDatabase>,+ companyId: string,+ purchaseOrderId: string+) {+ await trx+ .selectFrom("purchaseOrder")+ .select("id")+ .where("id", "=", purchaseOrderId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();++ const lines = await trx+ .selectFrom("purchaseInvoiceLine")+ .innerJoin(+ "purchaseInvoice",+ "purchaseInvoice.id",+ "purchaseInvoiceLine.invoiceId"+ )+ .select([+ "purchaseInvoiceLine.invoiceId",+ "purchaseInvoiceLine.purchaseOrderLineId as lineId",+ "purchaseInvoiceLine.supplierShippingCost",+ "purchaseInvoiceLine.supplierTaxAmount"+ ])+ .where("purchaseInvoiceLine.purchaseOrderId", "=", purchaseOrderId)+ .where("purchaseInvoiceLine.companyId", "=", companyId)+ .where("purchaseInvoice.status", "!=", "Voided")+ .execute();++ const invoiceIds = [...new Set(lines.map((line) => line.invoiceId))];+ const shipping =+ invoiceIds.length > 0+ ? await trx+ .selectFrom("purchaseInvoiceDelivery")+ .select("supplierShippingCost")+ .where("id", "in", invoiceIds)+ .where("companyId", "=", companyId)+ .execute()+ : [];++ return {+ orderShipping: shipping.reduce(+ (sum, row) => sum + Number(row.supplierShippingCost ?? 0),+ 0+ ),+ lines: sumBilledLineCharges(lines, [+ "supplierShippingCost",+ "supplierTaxAmount"+ ])+ };+}+/** `id` for the three document-to-invoice conversions, `convertedId` for the rest. */export type ConvertResult = { id?: string; convertedId?: string };@@ -8898,8 +9047,6 @@ export async function convertDocument(convertDocumentLogger.info("convert", { type, id, companyId, userId });- const client = ctx.asSystem.supabase;-switch (payload.type) {case "methodVersionToActive": {const makeMethodId = id;@@ -9054,32 +9201,6 @@ export async function convertDocument(return acc;}, 0);- // Flat header/line amounts (shipping, tax) must not be duplicated- // when a PO is invoiced in multiple partial invoices: the header- // shipping goes on the first (non-voided) invoice only, and flat- // line amounts are prorated by the fraction being invoiced.- // Untyped client: this embedded select exceeds TypeScript's- // instantiation depth, and only the row count is read.- const priorInvoiceLines = await (client as unknown as SupabaseClient)- .from("purchaseInvoiceLine")- .select("id, purchaseInvoice!inner(status)")- .eq("purchaseOrderId", purchaseOrderId)- .eq("companyId", companyId)- .neq("purchaseInvoice.status", "Voided")- .limit(1);- const hasPriorInvoice = (priorInvoiceLines.data?.length ?? 0) > 0;-- const uninvoicedFraction = (line: {- purchaseQuantity: number | null;- quantityReceived: number | null;- quantityInvoiced: number | null;- receivedComplete: boolean | null;- }) => {- const ordered = line.purchaseQuantity ?? 0;- if (ordered <= 0) return 1;- return Math.min(getRemainingQuantityToInvoice(line) / ordered, 1);- };-let purchaseInvoiceId = "";await db.transaction().execute(async (trx) => {@@ -9088,6 +9209,18 @@ export async function convertDocument("purchaseInvoice",companyId);+ // Flat charges bill once across partial invoices (flatChargeShare).+ // Supplier amounts are in the order's currency.+ const billed = await billedPurchaseOrderCharges(+ trx,+ companyId,+ purchaseOrderId+ );+ const decimals = await currencyDecimals(+ trx,+ companyId,+ purchaseOrder.data!.currencyCode ?? "USD"+ );const purchaseInvoice = await trx.insertInto("purchaseInvoice")@@ -9128,9 +9261,14 @@ export async function convertDocument(.values({id: purchaseInvoiceId,locationId: purchaseOrderDelivery.data!.locationId,- supplierShippingCost: hasPriorInvoice- ? 0- : (purchaseOrderDelivery.data!.supplierShippingCost ?? 0),+ supplierShippingCost: flatChargeShare({+ charge: purchaseOrderDelivery.data!.supplierShippingCost ?? 0,+ billed: billed.orderShipping,+ quantity: 1,+ remainingQuantity: 1,+ orderedQuantity: 1,+ decimals+ }),shippingMethodId: purchaseOrderDelivery.data!.shippingMethodId,shippingTermId: purchaseOrderDelivery.data!.shippingTermId,incoterm: purchaseOrderDelivery.data!.incoterm,@@ -9141,35 +9279,53 @@ export async function convertDocument(.execute();const purchaseInvoiceLines: Database["public"]["Tables"]["purchaseInvoiceLine"]["Insert"][] =- uninvoicedLines.map((line) => ({- invoiceId: purchaseInvoiceId,- invoiceLineType: line.purchaseOrderLineType,- purchaseOrderId: line.purchaseOrderId,- purchaseOrderLineId: line.id,- itemId: line.itemId,- locationId: line.locationId,- storageUnitId: line.storageUnitId,- accountId: line.accountId,- costCenterId: line.costCenterId,- assetId: line.assetId,- description: line.description,- quantity: getRemainingQuantityToInvoice(line),- supplierUnitPrice: line.supplierUnitPrice ?? 0,- supplierShippingCost:- (line.supplierShippingCost ?? 0) * uninvoicedFraction(line),- supplierTaxAmount:- (line.supplierTaxAmount ?? 0) * uninvoicedFraction(line),- // The rate is invariant under proration; only the amount scales- taxPercent: line.taxPercent ?? 0,- purchaseUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,- inventoryUnitOfMeasureCode: line.inventoryUnitOfMeasureCode,- conversionFactor: line.conversionFactor,- exchangeRate: line.exchangeRate ?? 1,- jobOperationId: line.jobOperationId,- sortOrder: line.sortOrder ?? 1,- companyId,- createdBy: userId- }));+ uninvoicedLines.map((line) => {+ const lineBilled = billed.lines.get(line.id) ?? {};+ const quantity = getRemainingQuantityToInvoice(line);+ const share = (charge: number | null, field: string) =>+ flatChargeShare({+ charge: charge ?? 0,+ billed: lineBilled[field] ?? 0,+ quantity,+ remainingQuantity:+ (line.purchaseQuantity ?? 0) - (line.quantityInvoiced ?? 0),+ orderedQuantity: line.purchaseQuantity,+ decimals+ });+ return {+ invoiceId: purchaseInvoiceId,+ invoiceLineType: line.purchaseOrderLineType,+ purchaseOrderId: line.purchaseOrderId,+ purchaseOrderLineId: line.id,+ itemId: line.itemId,+ locationId: line.locationId,+ storageUnitId: line.storageUnitId,+ accountId: line.accountId,+ costCenterId: line.costCenterId,+ assetId: line.assetId,+ description: line.description,+ quantity,+ supplierUnitPrice: line.supplierUnitPrice ?? 0,+ supplierShippingCost: share(+ line.supplierShippingCost,+ "supplierShippingCost"+ ),+ supplierTaxAmount: share(+ line.supplierTaxAmount,+ "supplierTaxAmount"+ ),+ // The rate is invariant under proration; only the amount scales+ taxPercent: line.taxPercent ?? 0,+ purchaseUnitOfMeasureCode: line.purchaseUnitOfMeasureCode,+ inventoryUnitOfMeasureCode: line.inventoryUnitOfMeasureCode,+ conversionFactor: line.conversionFactor,+ exchangeRate: line.exchangeRate ?? 1,+ jobOperationId: line.jobOperationId,+ sortOrder: line.sortOrder ?? 1,+ companyId,+ createdBy: userId+ };+ });await trx.insertInto("purchaseInvoiceLine")@@ -9648,10 +9804,19 @@ export async function convertDocument(return acc;}, 0);+ if (!uninvoicedLines || uninvoicedLines.length === 0) {+ throw new Error(+ "No lines available to invoice. All lines may already be marked as invoiced complete."+ );+ }+let salesInvoiceId = "";await db.transaction().execute(async (trx) => {salesInvoiceId = await getNextSequence(trx, "salesInvoice", companyId);+ // Flat charges bill once across partial invoices (flatChargeShare).+ const billed = await billedSalesOrderCharges(trx, companyId, order.id);+ const decimals = await baseCurrencyDecimals(trx, companyId);const salesInvoice = await trx.insertInto("salesInvoice")@@ -9695,7 +9860,14 @@ export async function convertDocument(order,orderShipment),- shippingCost: orderShipment.shippingCost ?? 0,+ shippingCost: flatChargeShare({+ charge: orderShipment.shippingCost ?? 0,+ billed: billed.orderShipping,+ quantity: 1,+ remainingQuantity: 1,+ orderedQuantity: 1,+ decimals+ }),shippingMethodId: orderShipment.shippingMethodId,shippingTermId: orderShipment.shippingTermId,incoterm: orderShipment.incoterm,@@ -9713,6 +9885,17 @@ export async function convertDocument(line.quantityToInvoice > 0 &&!line.invoicedComplete) {+ const lineBilled = billed.lines.get(line.id) ?? {};+ const quantity = line.quantityToInvoice;+ const share = (charge: number | null, field: string) =>+ flatChargeShare({+ charge: charge ?? 0,+ billed: lineBilled[field] ?? 0,+ quantity,+ remainingQuantity: quantity,+ orderedQuantity: line.saleQuantity,+ decimals+ });acc.push({invoiceId: salesInvoiceId,invoiceLineType: line.salesOrderLineType,@@ -9727,9 +9910,12 @@ export async function convertDocument(description: line.description,quantity: line.quantityToInvoice,unitPrice: line.unitPrice ?? 0,- addOnCost: line.addOnCost ?? 0,- nonTaxableAddOnCost: line.nonTaxableAddOnCost ?? 0,- shippingCost: line.shippingCost ?? 0,+ addOnCost: share(line.addOnCost, "addOnCost"),+ nonTaxableAddOnCost: share(+ line.nonTaxableAddOnCost,+ "nonTaxableAddOnCost"+ ),+ shippingCost: share(line.shippingCost, "shippingCost"),taxPercent: line.taxPercent ?? 0,unitOfMeasureCode: line.unitOfMeasureCode ?? "EA",exchangeRate: line.exchangeRate ?? 1,@@ -10234,12 +10420,16 @@ export async function convertDocument(throw new NotFoundError("Sales order delivery details not found");const orderShipment = salesOrderShipment.data;+ // Each line's quantity no invoice bills yet, before it is narrowed to+ // what this shipment shipped.+ const remainingByLine = new Map<string, number>();const uninvoicedLines = salesOrderLines?.data?.reduce<(typeof salesOrderLines)["data"]>((acc, line) => {if (line.id in quantitiesByLine) {const shippedInThisShipment = quantitiesByLine[line.id]!;const remainingToInvoice = line.quantityToInvoice ?? 0;+ remainingByLine.set(line.id, remainingToInvoice);const quantityToInvoice = Math.min(shippedInThisShipment,remainingToInvoice@@ -10268,10 +10458,19 @@ export async function convertDocument(return acc;}, 0);+ if (!uninvoicedLines || uninvoicedLines.length === 0) {+ throw new Error(+ "No lines available to invoice. All lines may already be marked as invoiced complete."+ );+ }+let salesInvoiceId = "";await db.transaction().execute(async (trx) => {salesInvoiceId = await getNextSequence(trx, "salesInvoice", companyId);+ // Flat charges bill once across partial invoices (flatChargeShare).+ const billed = await billedSalesOrderCharges(trx, companyId, order.id);+ const decimals = await baseCurrencyDecimals(trx, companyId);const salesInvoice = await trx.insertInto("salesInvoice")@@ -10316,7 +10515,14 @@ export async function convertDocument(order,orderShipment),- shippingCost: orderShipment.shippingCost ?? 0,+ shippingCost: flatChargeShare({+ charge: orderShipment.shippingCost ?? 0,+ billed: billed.orderShipping,+ quantity: 1,+ remainingQuantity: 1,+ orderedQuantity: 1,+ decimals+ }),shippingMethodId: orderShipment.shippingMethodId,shippingTermId: orderShipment.shippingTermId,incoterm: orderShipment.incoterm,@@ -10334,6 +10540,17 @@ export async function convertDocument(line.quantityToInvoice > 0 &&!line.invoicedComplete) {+ const lineBilled = billed.lines.get(line.id) ?? {};+ const quantity = line.quantityToInvoice;+ const share = (charge: number | null, field: string) =>+ flatChargeShare({+ charge: charge ?? 0,+ billed: lineBilled[field] ?? 0,+ quantity,+ remainingQuantity: remainingByLine.get(line.id) ?? quantity,+ orderedQuantity: line.saleQuantity,+ decimals+ });acc.push({invoiceId: salesInvoiceId,invoiceLineType: line.salesOrderLineType,@@ -10348,9 +10565,12 @@ export async function convertDocument(description: line.description,quantity: line.quantityToInvoice,unitPrice: line.unitPrice ?? 0,- addOnCost: line.addOnCost ?? 0,- nonTaxableAddOnCost: line.nonTaxableAddOnCost ?? 0,- shippingCost: line.shippingCost ?? 0,+ addOnCost: share(line.addOnCost, "addOnCost"),+ nonTaxableAddOnCost: share(+ line.nonTaxableAddOnCost,+ "nonTaxableAddOnCost"+ ),+ shippingCost: share(line.shippingCost, "shippingCost"),taxPercent: line.taxPercent ?? 0,unitOfMeasureCode: line.unitOfMeasureCode ?? "EA",exchangeRate: line.exchangeRate ?? 1,diff --git a/apps/erp/app/modules/shared/shared.utils.ts b/apps/erp/app/modules/shared/shared.utils.tsindex 4279522395..86fc3748d9 100644--- a/apps/erp/app/modules/shared/shared.utils.ts+++ b/apps/erp/app/modules/shared/shared.utils.ts@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { round } from "@carbon/database/precision";import {type CurrencyRate,convertUnitPrice,@@ -105,3 +106,39 @@ export function resolveSupplierPrice(if (supplierPrice === null || !pricing) return documentFallbackPrice;return convertUnitPrice(supplierPrice, pricing.currency, document);}++/**+ * What one invoice bills of a flat charge (a line's add-ons or shipping, a+ * supplier's shipping or tax): its share of the ordered quantity, rounded to+ * the currency, and never more than earlier invoices left. The invoice that+ * bills the rest of the quantity bills the rest of the charge, so the invoices+ * add up to the charge exactly, even after a Draft invoice is edited or+ * deleted.+ */+export function flatChargeShare({+ charge,+ billed,+ quantity,+ remainingQuantity,+ orderedQuantity,+ decimals+}: {+ /** The whole charge on the order line. */+ charge: number;+ /** What non-voided invoices already bill of it. */+ billed: number;+ /** The quantity this invoice bills. */+ quantity: number;+ /** The quantity no invoice bills yet (ordered − invoiced). */+ remainingQuantity: number;+ orderedQuantity: number | null;+ /** The charge currency's settlement decimals. */+ decimals: number;+}): number {+ const left = round(charge - billed);+ if (left === 0 || Math.sign(left) !== Math.sign(charge)) return 0;+ const ordered = orderedQuantity ?? 0;+ if (ordered <= 0 || quantity >= remainingQuantity) return left;+ const share = round((charge * quantity) / ordered, decimals);+ return Math.abs(share) < Math.abs(left) ? share : left;+}diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.tsindex 7a056dbfce..b030fa781d 100644--- a/apps/mes/app/services/operations.service.ts+++ b/apps/mes/app/services/operations.service.ts@@ -77,6 +77,49 @@ function notFoundResponse(message: string) {};}+const UNIQUE_VIOLATION = "23505";++function conflictResponse(message: string) {+ return {+ data: null,+ error: {+ name: "PostgrestError",+ message,+ details: "",+ hint: "",+ code: "PGRST409"+ } as PostgrestError,+ count: null,+ status: 409,+ statusText: "Conflict"+ };+}++/** Whether a production event already records this serial (its tracked activity output). */+async function timerRecordsEntity(+ client: SupabaseClient<Database>,+ productionEventId: string,+ trackedEntityId: string,+ companyId: string+) {+ const activities = await client+ .from("trackedActivity")+ .select("id")+ .eq("sourceDocument", "Production Event")+ .eq("sourceDocumentId", productionEventId)+ .eq("companyId", companyId);+ const activityIds = activities.data?.map((activity) => activity.id) ?? [];+ if (activityIds.length === 0) return false;+ const output = await client+ .from("trackedActivityOutput")+ .select("trackedActivityId")+ .in("trackedActivityId", activityIds)+ .eq("trackedEntityId", trackedEntityId)+ .eq("companyId", companyId)+ .limit(1);+ return (output.data?.length ?? 0) > 0;+}+export async function getOpenJobs(client: SupabaseClient<Database>,args: { companyId: string; locationId: string }@@ -2731,6 +2774,47 @@ export async function startProductionEvent(});if (!refs.ok) return notFoundResponse(refs.message);+ // A Setup or Labor timer the operator already has running on this operation+ // is returned, not started again: a double-tap, or a second device, would+ // otherwise count the labor twice. The partial unique index on open events+ // refuses an insert that races past this read; that start returns the+ // running timer too.+ const isTimer = data.type === "Setup" || data.type === "Labor";+ const runningTimer = async () => {+ const running = await client+ .from("productionEvent")+ .select("*")+ .eq("jobOperationId", data.jobOperationId)+ .eq("type", data.type)+ .eq("employeeId", data.employeeId)+ .eq("companyId", data.companyId)+ .is("endTime", null)+ .limit(1);+ if (running.error) return { data: null, error: running.error };+ const row = running.data[0];+ if (!row) return null;+ if (!trackedEntityId) return { data: [row], error: null };+ // A serial start must record that serial; a timer running for another+ // unit is refused rather than reported as this unit's start.+ return (await timerRecordsEntity(+ client,+ row.id,+ trackedEntityId,+ data.companyId+ ))+ ? { data: { id: row.id }, error: null }+ : conflictResponse(+ `A ${data.type.toLowerCase()} timer is already running on this operation for another unit. Stop it before starting this one.`+ );+ };+ const raced = (error: PostgrestError | null) =>+ isTimer && error?.code === UNIQUE_VIOLATION;++ if (isTimer) {+ const running = await runningTimer();+ if (running) return running;+ }+// The tracked entity is the separate argument; productionEvent has no column for it.const { trackedEntityId: _trackedEntityId, ...event } = data;@@ -2747,7 +2831,11 @@ export async function startProductionEvent(.single()]);- if (eventInsert.error) return eventInsert;+ if (eventInsert.error) {+ if (raced(eventInsert.error))+ return (await runningTimer()) ?? eventInsert;+ return eventInsert;+ }if (operation.error) return operation;const trackedActivityInsert = await client@@ -2820,6 +2908,8 @@ export async function startProductionEvent(.insert(event).select("*");+ if (raced(eventInsert.error)) return (await runningTimer()) ?? eventInsert;+if (!eventInsert.error) {await autoStartJobAndOperation(client, {jobOperationId: data.jobOperationId,diff --git a/packages/database/src/event-system/handlers/sync_load_work_center_operation.sql b/packages/database/src/event-system/handlers/sync_load_work_center_operation.sqlindex cdc46d69bf..9c07e74e72 100644--- a/packages/database/src/event-system/handlers/sync_load_work_center_operation.sql+++ b/packages/database/src/event-system/handlers/sync_load_work_center_operation.sql@@ -22,14 +22,18 @@ BEGIN-- This runs as the owner (the dispatchers are SECURITY DEFINER), and the-- event's workCenterId and jobOperationId are single-column FKs: an event-- may only load its OWN company's operation onto its own company's work- -- center, or another company's sensor time would land on it. (A starting- -- event reopens a Done operation first: sync_set_job_operation_in_progress.)+ -- center, or another company's sensor time would land on it. A Done or+ -- Canceled operation never loads: a starting event does not reopen it+ -- (sync_set_job_operation_in_progress), and its unload only runs when the+ -- status changes, so the load would never close.IF NOT EXISTS (SELECT 1 FROM "workCenter"WHERE "id" = v_work_center_id AND "companyId" = v_company_id) OR NOT EXISTS (SELECT 1 FROM "jobOperation"- WHERE "id" = v_operation_id AND "companyId" = v_company_id+ WHERE "id" = v_operation_id+ AND "companyId" = v_company_id+ AND "status" NOT IN ('Done', 'Canceled')) THENRETURN;END IF;diff --git a/packages/database/src/event-system/handlers/sync_set_job_operation_in_progress.sql b/packages/database/src/event-system/handlers/sync_set_job_operation_in_progress.sqlindex 1126b00028..c5e3a932f1 100644--- a/packages/database/src/event-system/handlers/sync_set_job_operation_in_progress.sql+++ b/packages/database/src/event-system/handlers/sync_set_job_operation_in_progress.sql@@ -6,19 +6,28 @@ AS $function$BEGINIF p_operation != 'INSERT' THEN RETURN; END IF;- -- Only set to In Progress if endTime is NULL (event is starting, not already ended)+ -- Only set to In Progress if endTime is NULL (event is starting, not already ended).+ -- A Done or Canceled operation stays closed: an event logged against it+ -- (MES, or the ERP job Events tab) must not reopen it.IF (p_new->>'endTime') IS NULL THENUPDATE "jobOperation"SET "status" = 'In Progress'- WHERE id = p_new->>'jobOperationId';+ WHERE id = p_new->>'jobOperationId'+ AND "companyId" = p_new->>'companyId'+ AND "status" NOT IN ('Done', 'Canceled');END IF;- -- Set parent job to In Progress if it is still Ready+ -- Set parent job to In Progress if it is still Ready. Both updates stay in+ -- the event's own company: this runs as the owner, and jobOperationId is a+ -- single-column FK.UPDATE "job"SET "status" = 'In Progress'WHERE id = (- SELECT "jobId" FROM "jobOperation" WHERE id = p_new->>'jobOperationId'+ SELECT "jobId" FROM "jobOperation"+ WHERE id = p_new->>'jobOperationId'+ AND "companyId" = p_new->>'companyId')+ AND "companyId" = p_new->>'companyId'AND "status" = 'Ready';END;$function$;diff --git a/packages/database/supabase/migrations/20261028003852_one-open-production-event-per-operator.sql b/packages/database/supabase/migrations/20261028003852_one-open-production-event-per-operator.sqlnew file mode 100644index 0000000000..f581f35726--- /dev/null+++ b/packages/database/supabase/migrations/20261028003852_one-open-production-event-per-operator.sql@@ -0,0 +1,33 @@+-- One open Setup or Labor event per operator per operation. A double-tap, or+-- the same timer started from two devices, opened a second event and counted+-- the labor twice. Machine events are per operation and closed by+-- startMachineProductionEvent before it opens a new one, so they are not+-- covered here.++SET lock_timeout = '5s';++-- Close the duplicates this bug already left open, keeping the earliest. Each+-- later one ends at its own start, so it books no time. Events with no+-- employee are not duplicates under the index and are left alone.+UPDATE "productionEvent" pe+SET "endTime" = pe."startTime"+FROM (+ SELECT+ id,+ row_number() OVER (+ PARTITION BY "jobOperationId", "type", "employeeId"+ ORDER BY "startTime", id+ ) AS rn+ FROM "productionEvent"+ WHERE "endTime" IS NULL+ AND "type" IN ('Setup', 'Labor')+ AND "employeeId" IS NOT NULL+) dup+WHERE pe.id = dup.id+ AND dup.rn > 1;++CREATE UNIQUE INDEX IF NOT EXISTS "productionEvent_one_open_per_operator_idx"+ ON "productionEvent" ("jobOperationId", "type", "employeeId")+ WHERE "endTime" IS NULL AND "type" IN ('Setup', 'Labor');++RESET lock_timeout;diff --git a/packages/database/supabase/migrations/20261028012759_job-operation-stays-closed.sql b/packages/database/supabase/migrations/20261028012759_job-operation-stays-closed.sqlnew file mode 100644index 0000000000..60eef2ac5b--- /dev/null+++ b/packages/database/supabase/migrations/20261028012759_job-operation-stays-closed.sql@@ -0,0 +1,108 @@+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.++-- Ships these rules to databases where `authz sync` does not run after migrations yet.++CREATE OR REPLACE FUNCTION public.sync_load_work_center_operation(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+DECLARE+ v_work_center_id text := p_new->>'workCenterId';+ v_company_id text := p_new->>'companyId';+ v_operation_id text := p_new->>'jobOperationId';+ v_start timestamptz := (p_new->>'startTime')::timestamptz;+ v_boundary timestamptz;+ v_loaded text;+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ -- Only a starting event loads: an event inserted with an endTime (an ERP+ -- entry, an assigned interval, a closed sensor run) never does.+ IF (p_new->>'endTime') IS NOT NULL OR v_work_center_id IS NULL THEN+ RETURN;+ END IF;++ -- This runs as the owner (the dispatchers are SECURITY DEFINER), and the+ -- event's workCenterId and jobOperationId are single-column FKs: an event+ -- may only load its OWN company's operation onto its own company's work+ -- center, or another company's sensor time would land on it. A Done or+ -- Canceled operation never loads: a starting event does not reopen it+ -- (sync_set_job_operation_in_progress), and its unload only runs when the+ -- status changes, so the load would never close.+ IF NOT EXISTS (+ SELECT 1 FROM "workCenter"+ WHERE "id" = v_work_center_id AND "companyId" = v_company_id+ ) OR NOT EXISTS (+ SELECT 1 FROM "jobOperation"+ WHERE "id" = v_operation_id+ AND "companyId" = v_company_id+ AND "status" NOT IN ('Done', 'Canceled')+ ) THEN+ RETURN;+ END IF;++ -- One load at a time per work center.+ PERFORM pg_advisory_xact_lock(hashtextextended('workCenterLoad:' || v_work_center_id, 0));++ -- The open row is the load. A start older than the newest boundary in the+ -- history (a load or an unload) never loads: a late event must not undo a+ -- load or an unload that came after it.+ SELECT max(GREATEST("loadedAt", COALESCE("unloadedAt", "loadedAt")))+ INTO v_boundary+ FROM "workCenterLoad"+ WHERE "workCenterId" = v_work_center_id AND "companyId" = v_company_id;+ IF v_boundary IS NOT NULL AND v_start < v_boundary THEN RETURN; END IF;++ -- A reload of the operation already loaded writes nothing.+ SELECT "jobOperationId" INTO v_loaded+ FROM "workCenterLoad"+ WHERE "workCenterId" = v_work_center_id+ AND "companyId" = v_company_id+ AND "unloadedAt" IS NULL;+ IF v_loaded = v_operation_id THEN RETURN; END IF;++ UPDATE "workCenterLoad"+ SET "unloadedAt" = v_start+ WHERE "workCenterId" = v_work_center_id+ AND "companyId" = v_company_id+ AND "unloadedAt" IS NULL;++ INSERT INTO "workCenterLoad" ("companyId", "workCenterId", "jobOperationId", "loadedAt")+ VALUES (v_company_id, v_work_center_id, v_operation_id, v_start);+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_set_job_operation_in_progress(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ -- Only set to In Progress if endTime is NULL (event is starting, not already ended).+ -- A Done or Canceled operation stays closed: an event logged against it+ -- (MES, or the ERP job Events tab) must not reopen it.+ IF (p_new->>'endTime') IS NULL THEN+ UPDATE "jobOperation"+ SET "status" = 'In Progress'+ WHERE id = p_new->>'jobOperationId'+ AND "companyId" = p_new->>'companyId'+ AND "status" NOT IN ('Done', 'Canceled');+ END IF;++ -- Set parent job to In Progress if it is still Ready. Both updates stay in+ -- the event's own company: this runs as the owner, and jobOperationId is a+ -- single-column FK.+ UPDATE "job"+ SET "status" = 'In Progress'+ WHERE id = (+ SELECT "jobId" FROM "jobOperation"+ WHERE id = p_new->>'jobOperationId'+ AND "companyId" = p_new->>'companyId'+ )+ AND "companyId" = p_new->>'companyId'+ AND "status" = 'Ready';+END;+$function$;