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(maintenance): expense spare parts issued to maintenance dispatches (#1763)

Brad Barbinea9f4be1e579
diff --git a/apps/erp/app/components/Icons.tsx b/apps/erp/app/components/Icons.tsx
index 280038d922..dd5c87e66f 100644
--- a/apps/erp/app/components/Icons.tsx
+++ b/apps/erp/app/components/Icons.tsx
@@ -65,7 +65,8 @@ import {
LuTriangleAlert,
LuTruck,
LuUser,
- LuUsers
+ LuUsers,
+ LuWrench
} from "react-icons/lu";
import { RxCodesandboxLogo } from "react-icons/rx";
import { TbTargetOff } from "react-icons/tb";
@@ -633,6 +634,8 @@ export const JournalEntrySourceTypeIcon = ({
return <LuHardHat className={className} />;
case "Job Close":
return <LuCircleCheck className={className} />;
+ case "Maintenance Event":
+ return <LuWrench className={className} />;
case "Asset Depreciation":
return <LuClock className={className} />;
case "Asset Disposal":
diff --git a/apps/erp/app/modules/accounting/accounting.models.ts b/apps/erp/app/modules/accounting/accounting.models.ts
index 140dc8538d..8c43e6ad9f 100644
--- a/apps/erp/app/modules/accounting/accounting.models.ts
+++ b/apps/erp/app/modules/accounting/accounting.models.ts
@@ -753,6 +753,7 @@ export const journalEntrySourceTypes = [
"Job Receipt",
"Production Event",
"Job Close",
+ "Maintenance Event",
"Asset Depreciation",
"Asset Disposal",
"Payment",
diff --git a/apps/erp/app/modules/agent/kb/docs/integrations/project-management.md b/apps/erp/app/modules/agent/kb/docs/integrations/project-management.md
index c3fca675b0..5c16fa90b4 100644
--- a/apps/erp/app/modules/agent/kb/docs/integrations/project-management.md
+++ b/apps/erp/app/modules/agent/kb/docs/integrations/project-management.md
@@ -11,6 +11,19 @@ to an external issue and keep the two in step, status, assignee, and notes sync
Authenticate with a **Linear API key** (it begins with `lin_api`).
+ ### Create the webhook in Linear
+
+ In Linear's API settings, create a new webhook and paste the URL shown in Carbon's setup instructions
+ (`/api/webhook/linear/<your company id>`). This is how changes made in Linear reach Carbon.
+
+
+ ### Copy the signing secret
+
+ Linear shows a **signing secret** on the webhook's detail page. Paste it into **Webhook Signing Secret**.
+ With it saved, Carbon only accepts webhook requests Linear has signed, and rejects any that are more
+ than a minute old.
+
+
### Paste your Linear API key
Provide your Linear API key. Carbon checks the `lin_api` prefix.
@@ -24,15 +37,28 @@ Authenticate with a **Linear API key** (it begins with `lin_api`).
| Setting | What it controls |
| --- | --- |
| API key | Your Linear API key — Carbon checks the `lin_api` prefix. |
+| Webhook signing secret | Optional. When set, webhook requests without a valid Linear signature are rejected. |
+
+A Linear or Jira webhook with no secret saved in Carbon still works, so older setups keep syncing, but
+Carbon cannot tell its requests from forged ones. Add the secret to every webhook you create.
## Jira
-Connect over **OAuth**. There are no fields to fill in beyond authorizing Carbon.
+Connect over **OAuth**. The only setting is an optional webhook secret.
### Authorize over OAuth
- Authorize Carbon in Jira. There are no fields to fill in.
+ Authorize Carbon in Jira.
+
+
+ ### Create the webhook in Jira (optional)
+
+ For changes made in Jira to reach Carbon straight away, go to **System → WebHooks** in Jira and create a
+ webhook with the URL shown in Carbon's setup instructions (`/api/webhook/jira/<your company id>`),
+ subscribed to **Issue updated** and **Issue deleted**. Fill in the webhook's **Secret** field, and paste
+ the same value into **Webhook Secret** in Carbon. With it saved, Carbon only accepts webhook requests
+ Jira has signed.
### Link an action task
@@ -40,6 +66,10 @@ Connect over **OAuth**. There are no fields to fill in beyond authorizing Carbon
Once connected, you can link a nonconformance action task to a Jira issue, and status, assignee, and notes stay aligned in both directions.
+| Setting | What it controls |
+| --- | --- |
+| Webhook secret | Optional. When set, webhook requests without a valid Jira signature are rejected. |
+
Jira only appears when its OAuth client is configured server-side (`JIRA_CLIENT_ID`) — see
`docs/platform/self-hosting/environment-variables`.
diff --git a/apps/erp/app/modules/agent/kb/docs/reference/maintenance.md b/apps/erp/app/modules/agent/kb/docs/reference/maintenance.md
index 20e8049584..32643ed3c5 100644
--- a/apps/erp/app/modules/agent/kb/docs/reference/maintenance.md
+++ b/apps/erp/app/modules/agent/kb/docs/reference/maintenance.md
@@ -36,7 +36,9 @@ A dispatch marked **Down** or **Planned** blocks its work center: on the floor,
Parts used in maintenance are issued from inventory, drawing stock down through the item ledger as a *Maintenance Consumption* movement.
-Maintenance material is an **inventory movement only**. It posts to the item ledger but writes **no** general-ledger entry, regardless of whether accounting is enabled. It reduces what's on hand; it doesn't hit the books.
+Maintenance material is an **expense**. Issuing it relieves the part's cost at its costing method. With accounting enabled, it posts a journal that debits the **Maintenance** default account and credits inventory, tagged with the dispatch's work center. Unissuing a part reverses it at the cost the dispatch booked. A part issued before maintenance consumption was valued comes back as a stock movement only, because nothing was expensed for it.
+
+Maintenance time is an expense too. Each timecard on a dispatch is costed at its work center's **labor rate** (no overhead), and with accounting enabled posts a journal that debits the **Maintenance** default account and credits **Labor Absorption**, tagged with the employee, work center and location. It posts when the timecard ends (pausing or completing in MES, or saving a timecard with an end time in the back office). Editing a timecard posts the difference and deleting one reverses it.
## Related
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index 989d389d10..aa0d8ba6f5 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -80,9 +80,10 @@ export async function closePurchaseOrder(
return client
.from("purchaseOrder")
.update({
- closed: true,
+ status: "Closed",
closedAt: datetime.today(companyTz).toString(),
- closedBy: userId
+ closedBy: userId,
+ updatedBy: userId
})
.eq("id", purchaseOrderId)
.select("id")
diff --git a/apps/erp/app/modules/resources/resources.server.ts b/apps/erp/app/modules/resources/resources.server.ts
new file mode 100644
index 0000000000..276b1d44c1
--- /dev/null
+++ b/apps/erp/app/modules/resources/resources.server.ts
@@ -0,0 +1,33 @@
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { getLogger } from "@carbon/logger";
+
+const logger = getLogger("erp", "maintenance-labor");
+
+// Reconcile the dispatches' labor postings with their time entries (the
+// post-maintenance-event edge function — idempotent, so call it after ANY
+// change to a dispatch's entries or its completion). Returns an error message
+// for the caller's flash, or null. Service role: the caller has already
+// authorized the change, and a delete-only user must still reverse its cost.
+export async function postMaintenanceLabor(args: {
+ maintenanceDispatchIds: string[];
+ companyId: string;
+ userId: string;
+}): Promise<string | null> {
+ if (args.maintenanceDispatchIds.length === 0) return null;
+
+ const serviceRole = getCarbonServiceRole();
+ const posting = await serviceRole.functions.invoke<{
+ success: boolean;
+ error?: string;
+ }>("post-maintenance-event", { body: args });
+
+ if (posting.error) {
+ logger.error("Failed to post maintenance labor", {
+ companyId: args.companyId,
+ maintenanceDispatchIds: args.maintenanceDispatchIds,
+ error: posting.error
+ });
+ return posting.error.message;
+ }
+ return null;
+}
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index d8c8df99b9..22247c155a 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -194,9 +194,10 @@ export async function closeSalesOrder(
return client
.from("salesOrder")
.update({
- closed: true,
+ status: "Closed",
closedAt: datetime.today(companyTz).toString(),
- closedBy: userId
+ closedBy: userId,
+ updatedBy: userId
})
.eq("id", salesOrderId)
.select("id")
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index 38ded418d5..076866a558 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -22,7 +22,7 @@
{"name":"accounting_completeCloseTask","classification":"WRITE","paramCount":2,"schema":"5d2e9a90637b","response":"none","injectAuth":"companyId+userId","permission":"accounting:update","paginates":false},
{"name":"accounting_createFiscalYearPeriods","classification":"WRITE","paramCount":1,"schema":"de7d8726d5e4","response":"none","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"accounting:create","paginates":false},
{"name":"accounting_createIntercompanyTransaction","classification":"WRITE","paramCount":8,"schema":"9c3c11f4059c","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"accounting:create","paginates":false},
- {"name":"accounting_createJournalEntry","classification":"WRITE","paramCount":5,"schema":"ba535b9848f9","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create","paginates":false},
+ {"name":"accounting_createJournalEntry","classification":"WRITE","paramCount":5,"schema":"fee52842e3f3","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"accounting:create","paginates":false},
{"name":"accounting_createOpeningBalanceJournal","classification":"DESTRUCTIVE","paramCount":2,"schema":"827e7a256f6c","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"accounting:create","paginates":false},
{"name":"accounting_deleteAccount","classification":"DESTRUCTIVE","paramCount":1,"schema":"ecb746f60913","response":"bcde375ebd4c","injectAuth":"companyId","permission":"accounting:delete","paginates":false},
{"name":"accounting_deleteAccountingPeriod","classification":"DESTRUCTIVE","paramCount":1,"schema":"7e5905ac5974","response":"none","injectAuth":"companyId","permission":"accounting:delete","paginates":false},
@@ -45,7 +45,7 @@
{"name":"accounting_getAccountingPeriods","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"bd245bd0358c","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getAccountingSyncTieOut","classification":"READ","paramCount":3,"schema":"4feda8437359","response":"5483e69d7515","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getAccountingSyncTieOutCell","classification":"READ","paramCount":1,"schema":"1a84bfebf9e9","response":"a5febf12f4bd","injectAuth":"companyId","permission":"accounting:view","paginates":false},
- {"name":"accounting_getAccountLedger","classification":"READ","paramCount":6,"schema":"8ad7f551d78b","response":"10a5f4ede58e","injectAuth":"companyId","permission":"accounting:view","paginates":true},
+ {"name":"accounting_getAccountLedger","classification":"READ","paramCount":6,"schema":"8ad7f551d78b","response":"c4542e5ba373","injectAuth":"companyId","permission":"accounting:view","paginates":true},
{"name":"accounting_getAccountLedgerSummary","classification":"READ","paramCount":3,"schema":"aad65f7c3f63","response":"0a28a92b28ff","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getAccountPeriodSeries","classification":"READ","paramCount":2,"schema":"d5db2abee293","response":"2c75339d9fde","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getAccounts","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"84821cb96b68","injectAuth":"companyId","permission":"accounting:view","paginates":true},
@@ -96,9 +96,9 @@
{"name":"accounting_getGroupAccounts","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"a9a2c5be8164","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getIntercompanyBalance","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"f2f76b33a3df","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getIntercompanyEliminationLines","classification":"READ","paramCount":1,"schema":"b9efe4d053a7","response":"e23adccbd115","injectAuth":"companyId","permission":"accounting:view","paginates":false},
- {"name":"accounting_getIntercompanyTransactions","classification":"READ","paramCount":3,"schema":"5ba9d4ce2300","response":"3e02f7f76d3d","injectAuth":"companyId","permission":"accounting:view","paginates":true},
- {"name":"accounting_getJournalEntries","classification":"READ","paramCount":4,"schema":"099269e45600","response":"e132576e07ba","injectAuth":"companyId","permission":"accounting:view","paginates":true},
- {"name":"accounting_getJournalEntry","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"2a610ccbb4c2","injectAuth":"companyId","permission":"accounting:view","paginates":false},
+ {"name":"accounting_getIntercompanyTransactions","classification":"READ","paramCount":3,"schema":"5ba9d4ce2300","response":"05e10eb50000","injectAuth":"companyId","permission":"accounting:view","paginates":true},
+ {"name":"accounting_getJournalEntries","classification":"READ","paramCount":4,"schema":"099269e45600","response":"8e4e2a1e7612","injectAuth":"companyId","permission":"accounting:view","paginates":true},
+ {"name":"accounting_getJournalEntry","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"86eb1184c5df","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getJournalLineDimensions","classification":"READ","paramCount":1,"schema":"4a6413e2bb5a","response":"b731368c1d3c","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getJournalSyncCompleteness","classification":"READ","paramCount":3,"schema":"6eb0a36bbd4b","response":"58d45b19b00c","injectAuth":"companyId","permission":"accounting:view","paginates":false},
{"name":"accounting_getOrCreateAccountingPeriod","classification":"READ","paramCount":2,"schema":"7dd9558cffe4","response":"00404e686415","injectAuth":"companyId","permission":"accounting:view","paginates":false},
diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId.event.$eventId.delete.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId.event.$eventId.delete.tsx
index 8a9095ceea..d80448304f 100644
--- a/apps/erp/app/routes/x+/maintenance+/$dispatchId.event.$eventId.delete.tsx
+++ b/apps/erp/app/routes/x+/maintenance+/$dispatchId.event.$eventId.delete.tsx
@@ -8,12 +8,13 @@ import {
getMaintenanceDispatch,
isMaintenanceDispatchLocked
} from "~/modules/resources";
+import { postMaintenanceLabor } from "~/modules/resources/resources.server";
import { requireUnlocked } from "~/utils/lockedGuard.server";
import { path, requestReferrer } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
delete: "resources"
});
@@ -41,8 +42,23 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // Reverses the labor cost the deleted timecard posted.
+ const postingError = await postMaintenanceLabor({
+ maintenanceDispatchIds: [dispatchId],
+ companyId,
+ userId
+ });
+
throw redirect(
requestReferrer(request) ?? path.to.maintenanceDispatch(dispatchId),
- await flash(request, success("Timecard removed successfully"))
+ await flash(
+ request,
+ postingError
+ ? error(
+ postingError,
+ "Timecard removed, but its labor cost was not reversed"
+ )
+ : success("Timecard removed successfully")
+ )
);
}
diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId.event.$eventId.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId.event.$eventId.tsx
index ee7e0acfd0..19528db1eb 100644
--- a/apps/erp/app/routes/x+/maintenance+/$dispatchId.event.$eventId.tsx
+++ b/apps/erp/app/routes/x+/maintenance+/$dispatchId.event.$eventId.tsx
@@ -1,19 +1,22 @@
-import { assertIsPost } from "@carbon/auth";
+import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
import { validator } from "@carbon/form";
import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
import {
getMaintenanceDispatch,
isMaintenanceDispatchLocked,
maintenanceDispatchEventValidator,
upsertMaintenanceDispatchEvent
} from "~/modules/resources";
+import { postMaintenanceLabor } from "~/modules/resources/resources.server";
import { requireUnlocked } from "~/utils/lockedGuard.server";
import { path } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "resources"
});
@@ -65,5 +68,20 @@ export async function action({ request, params }: ActionFunctionArgs) {
};
}
+ const postingError = await postMaintenanceLabor({
+ maintenanceDispatchIds: [dispatchId],
+ companyId,
+ userId
+ });
+ if (postingError) {
+ return data(
+ { success: true },
+ await flash(
+ request,
+ error(postingError, "Timecard updated, but its labor cost did not post")
+ )
+ );
+ }
+
return { success: true };
}
diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId.event.new.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId.event.new.tsx
index e1d4fdcc01..4ec6d8ca82 100644
--- a/apps/erp/app/routes/x+/maintenance+/$dispatchId.event.new.tsx
+++ b/apps/erp/app/routes/x+/maintenance+/$dispatchId.event.new.tsx
@@ -1,13 +1,16 @@
-import { assertIsPost } from "@carbon/auth";
+import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
import { validator } from "@carbon/form";
import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
import {
getMaintenanceDispatch,
isMaintenanceDispatchLocked,
maintenanceDispatchEventValidator,
upsertMaintenanceDispatchEvent
} from "~/modules/resources";
+import { postMaintenanceLabor } from "~/modules/resources/resources.server";
import { requireUnlocked } from "~/utils/lockedGuard.server";
import { path } from "~/utils/path";
@@ -64,5 +67,20 @@ export async function action({ request, params }: ActionFunctionArgs) {
};
}
+ const postingError = await postMaintenanceLabor({
+ maintenanceDispatchIds: [dispatchId],
+ companyId,
+ userId
+ });
+ if (postingError) {
+ return data(
+ { success: true },
+ await flash(
+ request,
+ error(postingError, "Timecard added, but its labor cost did not post")
+ )
+ );
+ }
+
return { success: true };
}
diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId.events.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId.events.tsx
index 7c1339bf3b..13011981a8 100644
--- a/apps/erp/app/routes/x+/maintenance+/$dispatchId.events.tsx
+++ b/apps/erp/app/routes/x+/maintenance+/$dispatchId.events.tsx
@@ -19,6 +19,7 @@ import {
isMaintenanceDispatchLocked,
maintenanceDispatchEventValidator
} from "~/modules/resources";
+import { postMaintenanceLabor } from "~/modules/resources/resources.server";
import type { MaintenanceDispatchEvent } from "~/modules/resources/types";
import { requireUnlocked } from "~/utils/lockedGuard.server";
import { path } from "~/utils/path";
@@ -107,7 +108,24 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- return data({}, await flash(request, success("Event stopped")));
+ const postingError = await postMaintenanceLabor({
+ maintenanceDispatchIds: [dispatchId],
+ companyId,
+ userId
+ });
+
+ return data(
+ {},
+ await flash(
+ request,
+ postingError
+ ? error(
+ postingError,
+ "Event stopped, but its labor cost did not post"
+ )
+ : success("Event stopped")
+ )
+ );
}
const validation = await validator(
@@ -131,7 +149,21 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- return data({}, await flash(request, success("Event saved")));
+ const postingError = await postMaintenanceLabor({
+ maintenanceDispatchIds: [dispatchId],
+ companyId,
+ userId
+ });
+
+ return data(
+ {},
+ await flash(
+ request,
+ postingError
+ ? error(postingError, "Event saved, but its labor cost did not post")
+ : success("Event saved")
+ )
+ );
}
export default function MaintenanceDispatchEventsRoute() {
diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId.status.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId.status.tsx
index 2d073c7399..6433726e03 100644
--- a/apps/erp/app/routes/x+/maintenance+/$dispatchId.status.tsx
+++ b/apps/erp/app/routes/x+/maintenance+/$dispatchId.status.tsx
@@ -4,11 +4,12 @@ import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { maintenanceDispatchStatus } from "~/modules/resources";
+import { postMaintenanceLabor } from "~/modules/resources/resources.server";
import { path, requestReferrer } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "resources"
});
@@ -48,8 +49,27 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // Completing closes every open timecard (end_maintenance_events_on_complete)
+ // — post their labor.
+ const postingError =
+ status === "Completed"
+ ? await postMaintenanceLabor({
+ maintenanceDispatchIds: [dispatchId],
+ companyId,
+ userId
+ })
+ : null;
+
throw redirect(
requestReferrer(request) ?? path.to.maintenanceDispatch(dispatchId),
- await flash(request, success("Updated dispatch status"))
+ await flash(
+ request,
+ postingError
+ ? error(
+ postingError,
+ "Updated dispatch status, but its labor cost did not post"
+ )
+ : success("Updated dispatch status")
+ )
);
}
diff --git a/apps/erp/app/routes/x+/maintenance+/update.tsx b/apps/erp/app/routes/x+/maintenance+/update.tsx
index e42059f78d..38a1d907b7 100644
--- a/apps/erp/app/routes/x+/maintenance+/update.tsx
+++ b/apps/erp/app/routes/x+/maintenance+/update.tsx
@@ -5,6 +5,7 @@ import {
isMaintenanceDispatchLocked,
updateMaintenanceDispatch
} from "~/modules/resources";
+import { postMaintenanceLabor } from "~/modules/resources/resources.server";
import { requireUnlockedBulk } from "~/utils/lockedGuard.server";
// Field changes that can move a work center's downtime window.
@@ -124,5 +125,23 @@ export async function action({ request }: ActionFunctionArgs) {
}
}
+ // Completing closes every open timecard (end_maintenance_events_on_complete)
+ // — post their labor.
+ if (field === "status" && value === "Completed") {
+ const postingError = await postMaintenanceLabor({
+ maintenanceDispatchIds: ids as string[],
+ companyId,
+ userId
+ });
+ if (postingError) {
+ return {
+ error: {
+ message: `Updated, but labor cost did not post: ${postingError}`
+ },
+ data: results.map((result) => result.data)
+ };
+ }
+ }
+
return { data: results.map((result) => result.data) };
}
diff --git a/apps/mes/app/routes/x+/dispatch.$dispatchId.tsx b/apps/mes/app/routes/x+/dispatch.$dispatchId.tsx
index b583d39792..167d5c8776 100644
--- a/apps/mes/app/routes/x+/dispatch.$dispatchId.tsx
+++ b/apps/mes/app/routes/x+/dispatch.$dispatchId.tsx
@@ -49,7 +49,7 @@ import { useItems } from "~/stores";
import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client, userId } = await requirePermissions(request, {});
+ const { client, companyId, userId } = await requirePermissions(request, {});
const { dispatchId } = params;
if (!dispatchId) {
@@ -60,7 +60,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
getMaintenanceDispatch(client, dispatchId),
getMaintenanceDispatchEvents(client, dispatchId),
getMaintenanceDispatchItems(client, dispatchId),
- getActiveMaintenanceEventByEmployee(client, userId)
+ getActiveMaintenanceEventByEmployee(client, {
+ dispatchId,
+ employeeId: userId,
+ companyId
+ })
]);
// Fetch replacement parts for the work center if available
diff --git a/apps/mes/app/routes/x+/maintenance-event.tsx b/apps/mes/app/routes/x+/maintenance-event.tsx
index 5c180385a1..9dabe1cdc2 100644
--- a/apps/mes/app/routes/x+/maintenance-event.tsx
+++ b/apps/mes/app/routes/x+/maintenance-event.tsx
@@ -8,6 +8,8 @@ import type { ActionFunctionArgs } from "react-router";
import { data, redirect } from "react-router";
import {
endMaintenanceEvent,
+ getActiveMaintenanceEventByEmployee,
+ postMaintenanceLabor,
startMaintenanceEvent,
updateMaintenanceDispatchStatus
} from "~/services/maintenance.service";
@@ -24,7 +26,6 @@ export async function action({ request }: ActionFunctionArgs) {
const action = formData.get("action") as "Start" | "End" | "Complete";
const dispatchId = formData.get("dispatchId") as string;
const workCenterId = formData.get("workCenterId") as string;
- const eventId = formData.get("eventId") as string | undefined;
if (!dispatchId) {
return data({}, await flash(request, error("Dispatch ID is required")));
@@ -85,6 +86,20 @@ export async function action({ request }: ActionFunctionArgs) {
};
if (action === "Start") {
+ // A stale page or a double click can submit Start while an event is
+ // already open here — don't stack a second one.
+ const existing = await getActiveMaintenanceEventByEmployee(serviceRole, {
+ dispatchId,
+ employeeId: userId,
+ companyId
+ });
+ if (existing.data) {
+ return data(
+ { eventId: existing.data.id },
+ await flash(request, success("Maintenance started"))
+ );
+ }
+
// Start a new maintenance event
const startEvent = await startMaintenanceEvent(serviceRole, {
maintenanceDispatchId: dispatchId,
@@ -123,15 +138,9 @@ export async function action({ request }: ActionFunctionArgs) {
}
if (action === "End") {
- if (!eventId) {
- return data(
- {},
- await flash(request, error("Event ID is required to end"))
- );
- }
-
const endEvent = await endMaintenanceEvent(serviceRole, {
- eventId,
+ dispatchId,
+ employeeId: userId,
endTime: currentTime,
updatedBy: userId,
companyId
@@ -147,19 +156,41 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
+ const posting = await postMaintenanceLabor(serviceRole, {
+ maintenanceDispatchIds: [dispatchId],
+ companyId,
+ userId
+ });
+ if (posting.error) {
+ logger.error("Failed to post maintenance labor", {
+ companyId,
+ dispatchId,
+ error: posting.error
+ });
+ return data(
+ {},
+ await flash(
+ request,
+ error(
+ posting.error,
+ "Maintenance paused, but its labor cost did not post"
+ )
+ )
+ );
+ }
+
return data({}, await flash(request, success("Maintenance paused")));
}
if (action === "Complete") {
// End any active event first
- if (eventId) {
- await endMaintenanceEvent(serviceRole, {
- eventId,
- endTime: currentTime,
- updatedBy: userId,
- companyId
- });
- }
+ await endMaintenanceEvent(serviceRole, {
+ dispatchId,
+ employeeId: userId,
+ endTime: currentTime,
+ updatedBy: userId,
+ companyId
+ });
// Update dispatch status to Completed
const updateStatus = await updateMaintenanceDispatchStatus(serviceRole, {
@@ -183,9 +214,31 @@ export async function action({ request }: ActionFunctionArgs) {
await stampScheduleIfOffline();
+ // Completion closed every open event on the dispatch — post their labor.
+ const posting = await postMaintenanceLabor(serviceRole, {
+ maintenanceDispatchIds: [dispatchId],
+ companyId,
+ userId
+ });
+ if (posting.error) {
+ logger.error("Failed to post maintenance labor", {
+ companyId,
+ dispatchId,
+ error: posting.error
+ });
+ }
+
throw redirect(
path.to.maintenance,
- await flash(request, success("Maintenance completed"))
+ await flash(
+ request,
+ posting.error
+ ? error(
+ posting.error,
+ "Maintenance completed, but its labor cost did not post"
+ )
+ : success("Maintenance completed")
+ )
);
}
diff --git a/apps/mes/app/services/maintenance.service.ts b/apps/mes/app/services/maintenance.service.ts
index b98fbbb06a..302ae1bea3 100644
--- a/apps/mes/app/services/maintenance.service.ts
+++ b/apps/mes/app/services/maintenance.service.ts
@@ -70,9 +70,13 @@ export async function getMaintenanceDispatch(
.single();
}
+// The employee's open event on ONE dispatch. Scoped to the dispatch (an open
+// event elsewhere must not hide this one) and tolerant of duplicates: a bare
+// `.maybeSingle()` errored on a second open row, the page read "not working",
+// and every Play click stacked another open event.
export async function getActiveMaintenanceEventByEmployee(
client: SupabaseClient<Database>,
- employeeId: string
+ args: { dispatchId: string; employeeId: string; companyId: string }
) {
return client
.from("maintenanceDispatchEvent")
@@ -90,8 +94,12 @@ export async function getActiveMaintenanceEventByEmployee(
)
`
)
- .eq("employeeId", employeeId)
+ .eq("maintenanceDispatchId", args.dispatchId)
+ .eq("employeeId", args.employeeId)
+ .eq("companyId", args.companyId)
.is("endTime", null)
+ .order("startTime", { ascending: false })
+ .limit(1)
.maybeSingle();
}
@@ -132,10 +140,13 @@ export async function startMaintenanceEvent(
.single();
}
+// Ends every open event the employee has on the dispatch, not just one id, so
+// a pause also closes any duplicate an earlier double-start left open.
export async function endMaintenanceEvent(
client: SupabaseClient<Database>,
args: {
- eventId: string;
+ dispatchId: string;
+ employeeId: string;
endTime: string;
updatedBy: string;
companyId: string;
@@ -147,10 +158,24 @@ export async function endMaintenanceEvent(
endTime: args.endTime,
updatedBy: args.updatedBy
})
- .eq("id", args.eventId)
+ .eq("maintenanceDispatchId", args.dispatchId)
+ .eq("employeeId", args.employeeId)
.eq("companyId", args.companyId)
- .select("id")
- .single();
+ .is("endTime", null)
+ .select("id");
+}
+
+// Reconcile the dispatches' labor postings with their time entries (the
+// post-maintenance-event edge function — idempotent, so call it after any
+// entry ends or the dispatch completes).
+export async function postMaintenanceLabor(
+ client: SupabaseClient<Database>,
+ args: { maintenanceDispatchIds: string[]; companyId: string; userId: string }
+) {
+ return client.functions.invoke<{ success: boolean; error?: string }>(
+ "post-maintenance-event",
+ { body: args }
+ );
}
export async function updateMaintenanceDispatchStatus(
diff --git a/docs/content/docs/reference/maintenance.mdx b/docs/content/docs/reference/maintenance.mdx
index 93dc448b6c..02591259e4 100644
--- a/docs/content/docs/reference/maintenance.mdx
+++ b/docs/content/docs/reference/maintenance.mdx
@@ -44,7 +44,9 @@ A dispatch marked **Down** or **Planned** blocks its work center: on the floor,
Parts used in maintenance are issued from inventory, drawing stock down through the <Term id="item-ledger">item ledger</Term> as a *Maintenance Consumption* movement.
<Callout type="info">
-Maintenance material is an **inventory movement only**. It posts to the item ledger but writes **no** general-ledger entry, regardless of whether accounting is enabled. It reduces what's on hand; it doesn't hit the books.
+Maintenance material is an **expense**. Issuing it relieves the part's cost at its costing method. With accounting enabled, it posts a journal that debits the **Maintenance** default account and credits inventory, tagged with the dispatch's work center. Unissuing a part reverses it at the cost the dispatch booked. A part issued before maintenance consumption was valued comes back as a stock movement only, because nothing was expensed for it.
+
+Maintenance time is an expense too. Each timecard on a dispatch is costed at its work center's **labor rate** (no overhead), and with accounting enabled posts a journal that debits the **Maintenance** default account and credits **Labor Absorption**, tagged with the employee, work center and location. It posts when the timecard ends (pausing or completing in MES, or saving a timecard with an end time in the back office). Editing a timecard posts the difference and deleting one reverses it.
</Callout>
## Related
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index cfc8197e1c..406fed74ce 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -110903,7 +110903,8 @@ export default {
"Sales Return Shipment",
"Purchase Return Shipment",
"Charge",
- "Reimbursement"
+ "Reimbursement",
+ "Maintenance Event"
],
format: 'public."journalEntrySourceType"',
type: "string"
@@ -122934,7 +122935,8 @@ export default {
"Scrap",
"Batch Merge",
"Charge",
- "Reimbursement"
+ "Reimbursement",
+ "Maintenance Event"
],
format: 'public."journalLineDocumentType"',
type: "string"
@@ -123561,7 +123563,8 @@ export default {
"Sales Return Shipment",
"Purchase Return Shipment",
"Charge",
- "Reimbursement"
+ "Reimbursement",
+ "Maintenance Event"
],
format: 'public."journalEntrySourceType"',
type: "string"
@@ -136360,7 +136363,8 @@ export default {
"Scrap",
"Batch Merge",
"Charge",
- "Reimbursement"
+ "Reimbursement",
+ "Maintenance Event"
],
format: 'public."journalLineDocumentType"',
type: "string"
@@ -136474,7 +136478,8 @@ export default {
"Sales Return Shipment",
"Purchase Return Shipment",
"Charge",
- "Reimbursement"
+ "Reimbursement",
+ "Maintenance Event"
],
format: 'public."journalEntrySourceType"',
type: "string"
@@ -136549,7 +136554,8 @@ export default {
"Scrap",
"Batch Merge",
"Charge",
- "Reimbursement"
+ "Reimbursement",
+ "Maintenance Event"
],
format: 'public."journalLineDocumentType"',
type: "string"
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 5e069e4eb5..92030cd9a2 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -85818,6 +85818,7 @@ export type Database = {
| "Purchase Return Shipment"
| "Charge"
| "Reimbursement"
+ | "Maintenance Event"
journalEntryStatus: "Draft" | "Posted" | "Reversed"
journalLineDocumentType:
| "Receipt"
@@ -85845,6 +85846,7 @@ export type Database = {
| "Batch Merge"
| "Charge"
| "Reimbursement"
+ | "Maintenance Event"
kanbanOutput: "label" | "qrcode" | "url"
kanbanReplenishmentSystem: "Buy" | "Make" | "Transfer"
macrsConvention: "Half-Year" | "Mid-Quarter"
@@ -87250,6 +87252,7 @@ export const Constants = {
"Purchase Return Shipment",
"Charge",
"Reimbursement",
+ "Maintenance Event",
],
journalEntryStatus: ["Draft", "Posted", "Reversed"],
journalLineDocumentType: [
@@ -87278,6 +87281,7 @@ export const Constants = {
"Batch Merge",
"Charge",
"Reimbursement",
+ "Maintenance Event",
],
kanbanOutput: ["label", "qrcode", "url"],
kanbanReplenishmentSystem: ["Buy", "Make", "Transfer"],
diff --git a/packages/database/supabase/config.toml b/packages/database/supabase/config.toml
index c167b0d69f..6d00ec187c 100644
--- a/packages/database/supabase/config.toml
+++ b/packages/database/supabase/config.toml
@@ -189,6 +189,11 @@ entrypoint = "./functions/post-stock-transfer/index.ts"
# For example, if you want to serve static HTML pages in your function:
# static_files = [ "./functions/post-stock-transfer/*.html" ]
+[functions.post-maintenance-event]
+enabled = true
+verify_jwt = true
+entrypoint = "./functions/post-maintenance-event/index.ts"
+
[functions.post-picking]
enabled = true
verify_jwt = true
diff --git a/packages/database/supabase/functions/issue/index.ts b/packages/database/supabase/functions/issue/index.ts
index 408de288d6..dab02f5f93 100644
--- a/packages/database/supabase/functions/issue/index.ts
+++ b/packages/database/supabase/functions/issue/index.ts
@@ -23,8 +23,15 @@ import { buildBatchSplitRecords, isFullDraw } from "../shared/batch-split.ts";
import { buildBatchMergeRecords } from "../shared/batch-merge.ts";
import { round } from "../shared/precision.ts";
import { splitPickAcrossMembers } from "../shared/batch-pick-split.ts";
-import { getCurrentAccountingPeriod } from "../shared/get-accounting-period.ts";
-import { bookAdjustment } from "../shared/post-adjustment.ts";
+import {
+ getCurrentAccountingPeriod,
+ resolveAccountingPeriod,
+} from "../shared/get-accounting-period.ts";
+import {
+ bookAdjustment,
+ createAdjustmentJournal,
+ valueMovement,
+} from "../shared/post-adjustment.ts";
import { getNextSequence } from "../shared/get-next-sequence.ts";
import { applyScrapReplacement } from "./scrap-replacement.ts";
import { getNextSerialNumbers } from "../shared/get-next-serial-number.ts";
@@ -42,6 +49,7 @@ import {
type SharedTakes,
splitTakeByBin,
} from "../lib/picked-consumption.ts";
+import { resolveMaintenanceReturnCost } from "./maintenance-return-cost.ts";
import { resolveTrackedEntityBin } from "./resolve-tracked-entity-bin.ts";
type ExpiredEntityPolicy = "Warn" | "Block" | "BlockWithOverride";
@@ -1167,6 +1175,188 @@ async function loadConsumeAccountingContext(
return { accountingEnabled, accountDefaults, dimensionMap };
}
+// Spare parts issued to a maintenance dispatch are an expense the moment they
+// leave stock. The caller writes the item ledger rows; this values them: each
+// movement relieves (or, on a return, restores) the item's cost layers and,
+// with accounting enabled, posts Dr maintenanceAccount / Cr inventory through
+// the shared adjustment core — one journal per call, tagged with the dispatch's
+// work center. A return reverses at what the dispatch actually booked
+// (`resolveMaintenanceReturnCost`), so a part issued before maintenance
+// consumption carried value comes back with no value either.
+async function valueMaintenanceMovements(
+ trx: Transaction<DB>,
+ args: {
+ dispatch: {
+ id: string;
+ maintenanceDispatchId: string;
+ workCenterId: string | null;
+ locationId: string | null;
+ };
+ // SIGNED: < 0 issued to the dispatch, > 0 returned from it
+ movements: Array<{ itemId: string; quantity: number }>;
+ postingDate: string;
+ companyId: string;
+ userId: string;
+ }
+) {
+ const { dispatch, postingDate, companyId, userId } = args;
+ const movements = args.movements.filter((m) => Number(m.quantity) !== 0);
+ if (movements.length === 0) return;
+
+ const itemIds = [...new Set(movements.map((m) => m.itemId))];
+ const hasReturns = movements.some((m) => Number(m.quantity) > 0);
+
+ const [settings, items, itemCosts, bookedRows] = await Promise.all([
+ trx
+ .selectFrom("companySettings")
+ .select("accountingEnabled")
+ .where("id", "=", companyId)
+ .executeTakeFirst(),
+ trx
+ .selectFrom("item")
+ .select(["id", "itemTrackingType", "replenishmentSystem"])
+ .where("id", "in", itemIds)
+ .where("companyId", "=", companyId)
+ .execute(),
+ trx
+ .selectFrom("itemCost")
+ .select([
+ "itemId",
+ "costingMethod",
+ "unitCost",
+ "standardCost",
+ "itemPostingGroupId",
+ ])
+ .where("itemId", "in", itemIds)
+ .where("companyId", "=", companyId)
+ .execute(),
+ hasReturns
+ ? trx
+ .selectFrom("costLedger")
+ .select(["itemId", "quantity", "cost"])
+ .where("documentId", "=", dispatch.id)
+ .where("documentType", "=", "Maintenance Consumption")
+ .where("itemId", "in", itemIds)
+ .where("companyId", "=", companyId)
+ .execute()
+ : Promise.resolve([]),
+ ]);
+
+ const itemById = new Map(items.map((item) => [item.id, item]));
+ const itemCostById = new Map(itemCosts.map((cost) => [cost.itemId, cost]));
+ const bookedByItem = new Map<string, Array<{ quantity: number; cost: number }>>();
+ for (const row of bookedRows) {
+ const list = bookedByItem.get(row.itemId as string) ?? [];
+ list.push({ quantity: Number(row.quantity), cost: Number(row.cost) });
+ bookedByItem.set(row.itemId as string, list);
+ }
+
+ let accounting: Parameters<typeof valueMovement>[1]["accounting"] = null;
+ if (settings?.accountingEnabled) {
+ const accountDefaults = await trx
+ .selectFrom("accountDefault")
+ .selectAll()
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!accountDefaults) throw new Error("Error getting account defaults");
+
+ const dimensions = await trx
+ .selectFrom("dimension")
+ .innerJoin("company", "company.companyGroupId", "dimension.companyGroupId")
+ .select(["dimension.id", "dimension.entityType"])
+ .where("company.id", "=", companyId)
+ .where("dimension.active", "=", true)
+ .where("dimension.entityType", "in", [
+ "Item",
+ "ItemPostingGroup",
+ "Location",
+ "WorkCenter",
+ ])
+ .execute();
+
+ const accountingPeriodId = (
+ await resolveAccountingPeriod(trx, companyId, postingDate, "current")
+ ).id;
+ const description = `Maintenance Consumption ${dispatch.maintenanceDispatchId}`;
+ let journalId: string | null = null;
+
+ accounting = {
+ accountingPeriodId,
+ accountDefaults: {
+ rawMaterialsAccount: accountDefaults.rawMaterialsAccount,
+ finishedGoodsAccount: accountDefaults.finishedGoodsAccount,
+ inventoryAdjustmentVarianceAccount:
+ accountDefaults.inventoryAdjustmentVarianceAccount,
+ },
+ offsetAccount: accountDefaults.maintenanceAccount,
+ offsetDescription: "Maintenance Expense",
+ description,
+ userId,
+ dimensions: Object.fromEntries(
+ dimensions
+ .filter((dim) => dim.entityType)
+ .map((dim) => [dim.entityType as string, dim.id])
+ ),
+ extraDimensions: dispatch.workCenterId
+ ? [{ entityType: "WorkCenter", valueId: dispatch.workCenterId }]
+ : [],
+ getJournalId: async () => {
+ journalId ??= await createAdjustmentJournal(trx, {
+ companyId,
+ accountingPeriodId,
+ description,
+ postingDate,
+ userId,
+ });
+ return journalId;
+ },
+ };
+ }
+
+ for (const movement of movements) {
+ let quantity = Number(movement.quantity);
+ let fixedUnitCost: number | undefined;
+
+ if (quantity > 0) {
+ const booked = bookedByItem.get(movement.itemId) ?? [];
+ const reversal = resolveMaintenanceReturnCost(booked, quantity);
+ if (!reversal) continue;
+ quantity = reversal.quantity;
+ fixedUnitCost = reversal.unitCost;
+ // A later return of the same item in this call sees this one.
+ booked.push({ quantity, cost: quantity * fixedUnitCost });
+ bookedByItem.set(movement.itemId, booked);
+ }
+
+ const item = itemById.get(movement.itemId);
+ const itemCost = itemCostById.get(movement.itemId);
+ await valueMovement(trx, {
+ movement: {
+ postingDate,
+ itemId: movement.itemId,
+ quantity,
+ locationId: dispatch.locationId,
+ entryType: "Consumption",
+ documentType: "Maintenance Consumption",
+ documentId: dispatch.id,
+ companyId,
+ },
+ item: {
+ itemTrackingType: item?.itemTrackingType ?? null,
+ replenishmentSystem: item?.replenishmentSystem ?? null,
+ itemPostingGroupId: itemCost?.itemPostingGroupId ?? null,
+ },
+ itemCost: {
+ costingMethod: itemCost?.costingMethod ?? "Average",
+ unitCost: Number(itemCost?.unitCost ?? 0),
+ standardCost: Number(itemCost?.standardCost ?? 0),
+ },
+ accounting,
+ fixedUnitCost,
+ });
+ }
+}
+
// The per-operation tracked-consumption write sequence, extracted verbatim from
// the trackedEntitiesToOperation case so trackedEntitiesToBatch can run it once
// per member inside ONE transaction. Reads run against `trx`, so sequential
@@ -4552,6 +4742,10 @@ serve(async (req: Request) => {
// Kysely below bypasses RLS, so the caller must hold this permission in the company it names.
await requirePermissions(req, companyId, userId, { update: "resources" });
+ const postingDate = datetime
+ .today(await getCompanyTimeZone(db, companyId))
+ .toString();
+
await db.transaction().execute(async (trx) => {
// Get the maintenance dispatch to find the location
const dispatch = await trx
@@ -4612,6 +4806,14 @@ serve(async (req: Request) => {
})
.execute();
+ await valueMaintenanceMovements(trx, {
+ dispatch,
+ movements: [{ itemId, quantity: -quantity }],
+ postingDate,
+ companyId,
+ userId,
+ });
+
// Update pickMethod defaultStorageUnitId if needed
if (locationId) {
await updatePickMethodDefaultStorageUnitIfNeeded(
@@ -4954,6 +5156,18 @@ serve(async (req: Request) => {
.values(itemLedgerInserts)
.execute();
+ // Only the consumption rows carry value; batch-split legs move
+ // stock between entities at the same bin.
+ await valueMaintenanceMovements(trx, {
+ dispatch,
+ movements: itemLedgerInserts
+ .filter((l) => l.documentType === "Maintenance Consumption")
+ .map((l) => ({ itemId: l.itemId, quantity: Number(l.quantity) })),
+ postingDate: companyToday.toString(),
+ companyId,
+ userId,
+ });
+
// Update pickMethod defaultStorageUnitId if needed
for (const ledger of itemLedgerInserts) {
await updatePickMethodDefaultStorageUnitIfNeeded(
@@ -4988,6 +5202,10 @@ serve(async (req: Request) => {
throw new Error("At least one tracked entity is required");
}
+ const postingDate = datetime
+ .today(await getCompanyTimeZone(db, companyId))
+ .toString();
+
await db.transaction().execute(async (trx) => {
// Get the maintenance dispatch item with related data
const dispatchItem = await trx
@@ -5139,6 +5357,17 @@ serve(async (req: Request) => {
.values(itemLedgerInserts)
.execute();
+ await valueMaintenanceMovements(trx, {
+ dispatch,
+ movements: itemLedgerInserts.map((l) => ({
+ itemId: l.itemId,
+ quantity: Number(l.quantity),
+ })),
+ postingDate,
+ companyId,
+ userId,
+ });
+
// Update pickMethod defaultStorageUnitId if needed
for (const ledger of itemLedgerInserts) {
await updatePickMethodDefaultStorageUnitIfNeeded(
@@ -5184,6 +5413,10 @@ serve(async (req: Request) => {
// Kysely below bypasses RLS, so the caller must hold this permission in the company it names.
await requirePermissions(req, companyId, userId, { update: "resources" });
+ const postingDate = datetime
+ .today(await getCompanyTimeZone(db, companyId))
+ .toString();
+
await db.transaction().execute(async (trx) => {
// Get the maintenance dispatch item
const dispatchItem = await trx
@@ -5324,6 +5557,17 @@ serve(async (req: Request) => {
.insertInto("itemLedger")
.values(itemLedgerInserts)
.execute();
+
+ await valueMaintenanceMovements(trx, {
+ dispatch,
+ movements: itemLedgerInserts.map((l) => ({
+ itemId: l.itemId,
+ quantity: Number(l.quantity),
+ })),
+ postingDate,
+ companyId,
+ userId,
+ });
}
} else if (
item.itemTrackingType !== "Serial" &&
@@ -5357,6 +5601,14 @@ serve(async (req: Request) => {
createdBy: userId,
})
.execute();
+
+ await valueMaintenanceMovements(trx, {
+ dispatch,
+ movements: [{ itemId: dispatchItem.itemId, quantity }],
+ postingDate,
+ companyId,
+ userId,
+ });
}
}
diff --git a/packages/database/supabase/functions/issue/maintenance-return-cost.test.ts b/packages/database/supabase/functions/issue/maintenance-return-cost.test.ts
new file mode 100644
index 0000000000..bb28281af7
--- /dev/null
+++ b/packages/database/supabase/functions/issue/maintenance-return-cost.test.ts
@@ -0,0 +1,52 @@
+import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
+import { resolveMaintenanceReturnCost } from "./maintenance-return-cost.ts";
+
+Deno.test("a full return reverses at the issued unit cost", () => {
+ assertEquals(
+ resolveMaintenanceReturnCost([{ quantity: -4, cost: -30 }], 4),
+ { quantity: 4, unitCost: 7.5 }
+ );
+});
+
+Deno.test("two issues of the item blend into one unit cost", () => {
+ assertEquals(
+ resolveMaintenanceReturnCost(
+ [
+ { quantity: -2, cost: -10 },
+ { quantity: -2, cost: -14 },
+ ],
+ 1
+ ),
+ { quantity: 1, unitCost: 6 }
+ );
+});
+
+Deno.test("earlier returns reduce what is left to reverse", () => {
+ assertEquals(
+ resolveMaintenanceReturnCost(
+ [
+ { quantity: -5, cost: -50 },
+ { quantity: 3, cost: 30 },
+ ],
+ 5
+ ),
+ { quantity: 2, unitCost: 10 }
+ );
+});
+
+Deno.test("an issue with no cost row (posted before valuation) returns nothing", () => {
+ assertEquals(resolveMaintenanceReturnCost([], 3), null);
+});
+
+Deno.test("a fully returned issue has nothing left to reverse", () => {
+ assertEquals(
+ resolveMaintenanceReturnCost(
+ [
+ { quantity: -2, cost: -8 },
+ { quantity: 2, cost: 8 },
+ ],
+ 2
+ ),
+ null
+ );
+});
diff --git a/packages/database/supabase/functions/issue/maintenance-return-cost.ts b/packages/database/supabase/functions/issue/maintenance-return-cost.ts
new file mode 100644
index 0000000000..c066115711
--- /dev/null
+++ b/packages/database/supabase/functions/issue/maintenance-return-cost.ts
@@ -0,0 +1,38 @@
+// Pure resolver for a spare part returned from a maintenance dispatch: how much
+// of the return carries value, and at what unit cost.
+//
+// A return reverses what the dispatch actually expensed, so it reads the
+// dispatch's own 'Maintenance Consumption' cost-ledger rows for the item
+// (signed: issues negative, earlier returns positive) and books at their
+// blended issue cost — a round trip nets zero P&L. Only the quantity still
+// expensed (issued minus already returned) is valued: an issue posted before
+// maintenance consumption carried value has no cost row, so returning it must
+// not credit an expense that was never debited. Returns null when nothing is
+// left to reverse — the caller writes the ledger row alone. No imports so
+// `deno test` type-checks clean.
+
+const EPSILON = 1e-6;
+
+export function resolveMaintenanceReturnCost(
+ rows: Array<{ quantity: number; cost: number }>,
+ returnQuantity: number
+): { quantity: number; unitCost: number } | null {
+ let issuedQuantity = 0;
+ let issuedCost = 0;
+ let returnedQuantity = 0;
+ for (const row of rows) {
+ const quantity = Number(row.quantity) || 0;
+ if (quantity < 0) {
+ issuedQuantity += -quantity;
+ issuedCost += Math.abs(Number(row.cost) || 0);
+ } else {
+ returnedQuantity += quantity;
+ }
+ }
+
+ const outstanding = issuedQuantity - returnedQuantity;
+ const quantity = Math.min(Math.abs(returnQuantity), outstanding);
+ if (issuedQuantity < EPSILON || quantity < EPSILON) return null;
+
+ return { quantity, unitCost: issuedCost / issuedQuantity };
+}
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 5e069e4eb5..92030cd9a2 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -85818,6 +85818,7 @@ export type Database = {
| "Purchase Return Shipment"
| "Charge"
| "Reimbursement"
+ | "Maintenance Event"
journalEntryStatus: "Draft" | "Posted" | "Reversed"
journalLineDocumentType:
| "Receipt"
@@ -85845,6 +85846,7 @@ export type Database = {
| "Batch Merge"
| "Charge"
| "Reimbursement"
+ | "Maintenance Event"
kanbanOutput: "label" | "qrcode" | "url"
kanbanReplenishmentSystem: "Buy" | "Make" | "Transfer"
macrsConvention: "Half-Year" | "Mid-Quarter"
@@ -87250,6 +87252,7 @@ export const Constants = {
"Purchase Return Shipment",
"Charge",
"Reimbursement",
+ "Maintenance Event",
],
journalEntryStatus: ["Draft", "Posted", "Reversed"],
journalLineDocumentType: [
@@ -87278,6 +87281,7 @@ export const Constants = {
"Batch Merge",
"Charge",
"Reimbursement",
+ "Maintenance Event",
],
kanbanOutput: ["label", "qrcode", "url"],
kanbanReplenishmentSystem: ["Buy", "Make", "Transfer"],
diff --git a/packages/database/supabase/functions/lib/utils.ts b/packages/database/supabase/functions/lib/utils.ts
index f69475d67d..6e370c2cd3 100644
--- a/packages/database/supabase/functions/lib/utils.ts
+++ b/packages/database/supabase/functions/lib/utils.ts
@@ -183,5 +183,6 @@ export const journalReference = {
job: (id: string) => `job:${id}`,
materialIssue: (id: string) => `material-issue:${id}`,
productionEvent: (id: string) => `production-event:${id}`,
+ maintenanceEvent: (id: string) => `maintenance-event:${id}`,
},
};
diff --git a/packages/database/supabase/functions/post-maintenance-event/index.ts b/packages/database/supabase/functions/post-maintenance-event/index.ts
new file mode 100644
index 0000000000..882569d7c2
--- /dev/null
+++ b/packages/database/supabase/functions/post-maintenance-event/index.ts
@@ -0,0 +1,291 @@
+import { serve } from "https://deno.land/[email protected]/http/server.ts";
+import { nanoid } from "https://deno.land/x/[email protected]/mod.ts";
+import z from "npm:zod@^4.5.4";
+import { RecordNotFoundError } from "../lib/company-records.ts";
+import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
+import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";
+import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
+import { requirePermissions } from "../lib/supabase.ts";
+import { credit, debit, journalReference } from "../lib/utils.ts";
+import { resolveAccountingPeriod } from "../shared/get-accounting-period.ts";
+import { createAdjustmentJournal } from "../shared/post-adjustment.ts";
+import {
+ diffLaborGroups,
+ type LaborDimension,
+ type LaborGroup,
+ maintenanceLaborCost,
+} from "./plan.ts";
+
+const pool = getConnectionPool(1);
+const db = getDatabaseClient<DB>(pool);
+
+// Reconciles maintenance dispatches' labor postings with their time entries —
+// call it after an entry is ended, added, edited or deleted, or a dispatch is
+// completed. Time is expensed at the work center's labor rate (no overhead):
+// Dr maintenanceAccount / Cr laborAbsorptionAccount, one journal per dispatch
+// that changed. Idempotent: see ./plan.ts.
+const payloadValidator = z.object({
+ maintenanceDispatchIds: z.array(z.string()).min(1),
+ userId: z.string(),
+ companyId: z.string(),
+});
+
+serve(async (req: Request) => {
+ const preflight = corsPreflight(req);
+ if (preflight) return preflight;
+
+ try {
+ const { maintenanceDispatchIds, userId, companyId } =
+ payloadValidator.parse(await req.json());
+ const dispatchIds = [...new Set(maintenanceDispatchIds)];
+
+ // Kysely below bypasses RLS, so the caller must hold this permission in the company it names.
+ const client = await requirePermissions(req, companyId, userId, {
+ update: "resources",
+ });
+
+ const settings = await client
+ .from("companySettings")
+ .select("accountingEnabled")
+ .eq("id", companyId)
+ .single();
+ if (!settings.data?.accountingEnabled) {
+ return jsonResponse({ success: true, journalIds: [] });
+ }
+
+ const postingDate = datetime
+ .today(await getCompanyTimeZone(client, companyId))
+ .toString();
+
+ const journalIds = await db.transaction().execute(async (trx) => {
+ // Row locks: two reconciles of one dispatch must not both post the same
+ // difference.
+ const dispatches = await trx
+ .selectFrom("maintenanceDispatch")
+ .select(["id", "maintenanceDispatchId"])
+ .where("id", "in", dispatchIds)
+ .where("companyId", "=", companyId)
+ .forUpdate()
+ .execute();
+ if (dispatches.length !== dispatchIds.length) {
+ throw new RecordNotFoundError("Maintenance dispatch not found");
+ }
+
+ const [events, priorLines, accountDefaults, dimensions] =
+ await Promise.all([
+ trx
+ .selectFrom("maintenanceDispatchEvent")
+ .select([
+ "id",
+ "maintenanceDispatchId",
+ "endTime",
+ "duration",
+ "workCenterId",
+ "employeeId",
+ ])
+ .where("maintenanceDispatchId", "in", dispatchIds)
+ .where("companyId", "=", companyId)
+ .execute(),
+ trx
+ .selectFrom("journalLine")
+ .select([
+ "id",
+ "documentId",
+ "documentLineReference",
+ "accountId",
+ "amount",
+ ])
+ .where("documentType", "=", "Maintenance Event")
+ .where("documentId", "in", dispatchIds)
+ .where("companyId", "=", companyId)
+ .execute(),
+ trx
+ .selectFrom("accountDefault")
+ .select(["maintenanceAccount", "laborAbsorptionAccount"])
+ .where("companyId", "=", companyId)
+ .executeTakeFirst(),
+ trx
+ .selectFrom("dimension")
+ .innerJoin(
+ "company",
+ "company.companyGroupId",
+ "dimension.companyGroupId"
+ )
+ .select(["dimension.id", "dimension.entityType"])
+ .where("company.id", "=", companyId)
+ .where("dimension.active", "=", true)
+ .where("dimension.entityType", "in", [
+ "Employee",
+ "WorkCenter",
+ "Location",
+ ])
+ .execute(),
+ ]);
+ if (!accountDefaults) throw new Error("Error getting account defaults");
+
+ const ended = events.filter((e) => e.endTime && Number(e.duration) > 0);
+ const workCenterIds = [...new Set(ended.map((e) => e.workCenterId))];
+ const [workCenters, priorDimensions] = await Promise.all([
+ workCenterIds.length
+ ? trx
+ .selectFrom("workCenter")
+ .select(["id", "laborRate", "locationId"])
+ .where("id", "in", workCenterIds)
+ .where("companyId", "=", companyId)
+ .execute()
+ : Promise.resolve([]),
+ priorLines.length
+ ? trx
+ .selectFrom("journalLineDimension")
+ .select(["journalLineId", "dimensionId", "valueId"])
+ .where(
+ "journalLineId",
+ "in",
+ priorLines.map((l) => l.id)
+ )
+ .where("companyId", "=", companyId)
+ .execute()
+ : Promise.resolve([]),
+ ]);
+ const workCenterById = new Map(workCenters.map((wc) => [wc.id, wc]));
+
+ const dimensionIdByType = new Map(
+ dimensions
+ .filter((d) => d.entityType)
+ .map((d) => [d.entityType as string, d.id])
+ );
+ const tag = (entityType: string, valueId: string | null | undefined) =>
+ valueId && dimensionIdByType.has(entityType)
+ ? [{ dimensionId: dimensionIdByType.get(entityType)!, valueId }]
+ : [];
+
+ // What each dispatch's entries should have posted.
+ const desiredByDispatch = new Map<string, LaborGroup[]>();
+ for (const event of ended) {
+ const workCenter = workCenterById.get(event.workCenterId);
+ const cost = maintenanceLaborCost(event.duration, workCenter?.laborRate);
+ if (cost <= 0) continue;
+ if (!accountDefaults.laborAbsorptionAccount) {
+ throw new Error(
+ "laborAbsorptionAccount not configured in account defaults"
+ );
+ }
+ const reference = journalReference.to.maintenanceEvent(event.id);
+ const eventDimensions: LaborDimension[] = [
+ ...tag("Employee", event.employeeId),
+ ...tag("WorkCenter", event.workCenterId),
+ ...tag("Location", workCenter?.locationId),
+ ];
+ const list = desiredByDispatch.get(event.maintenanceDispatchId) ?? [];
+ list.push(
+ {
+ reference,
+ accountId: accountDefaults.maintenanceAccount,
+ dimensions: eventDimensions,
+ amount: debit("expense", cost),
+ },
+ {
+ reference,
+ accountId: accountDefaults.laborAbsorptionAccount,
+ dimensions: eventDimensions,
+ amount: credit("expense", cost),
+ }
+ );
+ desiredByDispatch.set(event.maintenanceDispatchId, list);
+ }
+
+ // What the journal already holds, with each line's own tags.
+ const dimensionsByLine = new Map<string, LaborDimension[]>();
+ for (const d of priorDimensions) {
+ const list = dimensionsByLine.get(d.journalLineId) ?? [];
+ list.push({ dimensionId: d.dimensionId, valueId: d.valueId });
+ dimensionsByLine.set(d.journalLineId, list);
+ }
+ const priorByDispatch = new Map<string, LaborGroup[]>();
+ for (const line of priorLines) {
+ const dispatchId = line.documentId ?? "";
+ const list = priorByDispatch.get(dispatchId) ?? [];
+ list.push({
+ reference: line.documentLineReference ?? "",
+ accountId: line.accountId ?? "",
+ dimensions: dimensionsByLine.get(line.id) ?? [],
+ amount: Number(line.amount),
+ });
+ priorByDispatch.set(dispatchId, list);
+ }
+
+ let accountingPeriodId: string | null = null;
+ const posted: string[] = [];
+
+ for (const dispatch of dispatches) {
+ const prior = priorByDispatch.get(dispatch.id) ?? [];
+ const delta = diffLaborGroups(
+ desiredByDispatch.get(dispatch.id) ?? [],
+ prior
+ );
+ if (delta.length === 0) continue;
+
+ accountingPeriodId ??= (
+ await resolveAccountingPeriod(trx, companyId, postingDate, "current")
+ ).id;
+ const journalId = await createAdjustmentJournal(trx, {
+ companyId,
+ accountingPeriodId,
+ description: `Maintenance Labor ${dispatch.maintenanceDispatchId}${
+ prior.length > 0 ? " (Adjustment)" : ""
+ }`,
+ postingDate,
+ userId,
+ sourceType: "Maintenance Event",
+ });
+
+ // One line per insert: each carries its own tags, and a multi-row
+ // RETURNING does not promise insert order.
+ const journalLineReference = nanoid();
+ for (const group of delta) {
+ const line = await trx
+ .insertInto("journalLine")
+ .values({
+ journalId,
+ accountId: group.accountId,
+ description:
+ group.accountId === accountDefaults.maintenanceAccount
+ ? "Maintenance Labor"
+ : "Labor Absorption",
+ amount: group.amount,
+ quantity: 1,
+ documentType: "Maintenance Event",
+ documentId: dispatch.id,
+ documentLineReference: group.reference,
+ journalLineReference,
+ companyId,
+ })
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+
+ if (group.dimensions.length > 0) {
+ await trx
+ .insertInto("journalLineDimension")
+ .values(
+ group.dimensions.map((d) => ({
+ journalLineId: line.id,
+ dimensionId: d.dimensionId,
+ valueId: d.valueId,
+ companyId,
+ }))
+ )
+ .execute();
+ }
+ }
+ posted.push(journalId);
+ }
+
+ return posted;
+ });
+
+ return jsonResponse({ success: true, journalIds });
+ } catch (err) {
+ console.error("Error in post-maintenance-event:", err);
+ return errorResponse(err, 500);
+ }
+});
diff --git a/packages/database/supabase/functions/post-maintenance-event/plan.test.ts b/packages/database/supabase/functions/post-maintenance-event/plan.test.ts
new file mode 100644
index 0000000000..4617b9a196
--- /dev/null
+++ b/packages/database/supabase/functions/post-maintenance-event/plan.test.ts
@@ -0,0 +1,84 @@
+import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
+import {
+ diffLaborGroups,
+ type LaborGroup,
+ maintenanceLaborCost,
+} from "./plan.ts";
+
+const WC_A = { dimensionId: "dim-wc", valueId: "wc-a" };
+const WC_B = { dimensionId: "dim-wc", valueId: "wc-b" };
+
+function posting(
+ reference: string,
+ cost: number,
+ dimensions = [WC_A]
+): LaborGroup[] {
+ return [
+ { reference, accountId: "6010", dimensions, amount: cost },
+ { reference, accountId: "5030", dimensions, amount: -cost },
+ ];
+}
+
+const sum = (groups: LaborGroup[]) =>
+ groups.reduce((total, g) => total + g.amount, 0);
+
+Deno.test("cost is hours at the labor rate, never negative", () => {
+ assertEquals(maintenanceLaborCost(5400, 40), 60);
+ assertEquals(maintenanceLaborCost(null, 40), 0);
+ assertEquals(maintenanceLaborCost(3600, 0), 0);
+});
+
+Deno.test("a new entry posts Dr maintenance / Cr labor absorption", () => {
+ const delta = diffLaborGroups(posting("e1", 60), []);
+ assertEquals(delta.length, 2);
+ assertEquals(sum(delta), 0);
+});
+
+Deno.test("posting an unchanged entry again is a no-op", () => {
+ assertEquals(diffLaborGroups(posting("e1", 60), posting("e1", 60)), []);
+});
+
+Deno.test("an edited duration posts only the adjustment", () => {
+ const delta = diffLaborGroups(posting("e1", 80), posting("e1", 60));
+ assertEquals(
+ delta.map((g) => [g.accountId, g.amount]),
+ [
+ ["6010", 20],
+ ["5030", -20],
+ ]
+ );
+});
+
+Deno.test("a deleted entry reverses what it posted", () => {
+ const delta = diffLaborGroups([], posting("e1", 60));
+ assertEquals(
+ delta.map((g) => [g.accountId, g.amount]),
+ [
+ ["6010", -60],
+ ["5030", 60],
+ ]
+ );
+});
+
+Deno.test("a changed work center reverses the old tags and posts the new", () => {
+ const delta = diffLaborGroups(
+ posting("e1", 60, [WC_B]),
+ posting("e1", 60, [WC_A])
+ );
+ assertEquals(delta.length, 4);
+ assertEquals(sum(delta), 0);
+ assertEquals(
+ delta
+ .filter((g) => g.dimensions[0].valueId === "wc-a")
+ .map((g) => g.amount),
+ [-60, 60]
+ );
+});
+
+Deno.test("a posting later reversed nets to nothing to undo", () => {
+ const prior = [
+ ...posting("e1", 60),
+ ...posting("e1", 60).map((g) => ({ ...g, amount: -g.amount })),
+ ];
+ assertEquals(diffLaborGroups([], prior), []);
+});
diff --git a/packages/database/supabase/functions/post-maintenance-event/plan.ts b/packages/database/supabase/functions/post-maintenance-event/plan.ts
new file mode 100644
index 0000000000..4f27808cf1
--- /dev/null
+++ b/packages/database/supabase/functions/post-maintenance-event/plan.ts
@@ -0,0 +1,80 @@
+// Pure planner for maintenance labor postings. A dispatch's time entries are
+// expensed at their work center's labor rate: Dr maintenanceAccount /
+// Cr laborAbsorptionAccount. Rather than tracking a posted flag, every call
+// reconciles: it builds what the entries SHOULD have posted, subtracts what the
+// journal already holds, and posts only the difference. So posting twice is a
+// no-op, an edit posts an adjustment, a deleted entry reverses to zero, and a
+// change of work center or employee reverses the old tags and posts the new.
+//
+// A group is one (entry, account, dimension tags) bucket — the grain at which
+// both sides are compared, so a reversal always carries the tags it reverses.
+
+import { EPSILON, round } from "../shared/precision.ts";
+
+export interface LaborDimension {
+ dimensionId: string;
+ valueId: string;
+}
+
+export interface LaborGroup {
+ reference: string; // journalLine.documentLineReference
+ accountId: string;
+ dimensions: LaborDimension[];
+ amount: number; // signed, journalLine convention
+}
+
+export function maintenanceLaborCost(
+ durationSeconds: number | null | undefined,
+ laborRate: number | null | undefined
+): number {
+ const hours = Number(durationSeconds ?? 0) / 3600;
+ const cost = round(hours * Number(laborRate ?? 0));
+ return cost > 0 ? cost : 0;
+}
+
+export function laborGroupKey(
+ group: Pick<LaborGroup, "reference" | "accountId" | "dimensions">
+): string {
+ const dims = group.dimensions
+ .map((d) => `${d.dimensionId}=${d.valueId}`)
+ .sort()
+ .join(",");
+ return `${group.reference}|${group.accountId}|${dims}`;
+}
+
+// Sum signed amounts per group key (several postings of one entry collapse to
+// their net).
+export function netLaborGroups(groups: LaborGroup[]): Map<string, LaborGroup> {
+ const net = new Map<string, LaborGroup>();
+ for (const group of groups) {
+ const key = laborGroupKey(group);
+ const existing = net.get(key);
+ if (existing) {
+ existing.amount += group.amount;
+ } else {
+ net.set(key, { ...group, dimensions: [...group.dimensions] });
+ }
+ }
+ return net;
+}
+
+// desired − prior, per group. Both sides balance, so the result does too.
+export function diffLaborGroups(
+ desired: LaborGroup[],
+ prior: LaborGroup[]
+): LaborGroup[] {
+ const want = netLaborGroups(desired);
+ const have = netLaborGroups(prior);
+ const keys = new Set([...want.keys(), ...have.keys()]);
+
+ const delta: LaborGroup[] = [];
+ for (const key of keys) {
+ const target = want.get(key);
+ const current = have.get(key);
+ const amount = round((target?.amount ?? 0) - (current?.amount ?? 0));
+ if (Math.abs(amount) < EPSILON) continue;
+ const base = (target ?? current)!;
+ delta.push({ ...base, amount });
+ }
+ return delta;
+}
diff --git a/packages/database/supabase/functions/post-sales-invoice/index.ts b/packages/database/supabase/functions/post-sales-invoice/index.ts
index 35f876b3f0..e597cb792d 100644
--- a/packages/database/supabase/functions/post-sales-invoice/index.ts
+++ b/packages/database/supabase/functions/post-sales-invoice/index.ts
@@ -784,7 +784,9 @@ serve(async (req: Request) => {
}
let journalLineResults: { id: string }[] = [];
- if (accountingEnabled) {
+ // A zero-value invoice has no lines to post; an empty header would
+ // still consume a journal entry number.
+ if (accountingEnabled && journalLineInserts.length > 0) {
const journalEntryId = await getNextSequence(
trx,
"journalEntry",
@@ -808,18 +810,16 @@ serve(async (req: Request) => {
.returning(["id"])
.executeTakeFirstOrThrow();
- if (journalLineInserts.length > 0) {
- journalLineResults = await trx
- .insertInto("journalLine")
- .values(
- journalLineInserts.map((line) => ({
- ...line,
- journalId: journalResult.id,
- }))
- )
- .returning(["id"])
- .execute();
- }
+ journalLineResults = await trx
+ .insertInto("journalLine")
+ .values(
+ journalLineInserts.map((line) => ({
+ ...line,
+ journalId: journalResult.id,
+ }))
+ )
+ .returning(["id"])
+ .execute();
if (dimensionMap.size > 0) {
const journalLineDimensionInserts: {
@@ -1265,7 +1265,8 @@ serve(async (req: Request) => {
.execute();
}
- if (accountingEnabled) {
+ // Nothing to reverse for a zero-value invoice — no empty VOID header.
+ if (accountingEnabled && reversingJournalEntries.length > 0) {
const voidJournalEntryId = await getNextSequence(
trx,
"journalEntry",
@@ -1289,18 +1290,16 @@ serve(async (req: Request) => {
.returning(["id"])
.executeTakeFirstOrThrow();
- if (reversingJournalEntries.length > 0) {
- await trx
- .insertInto("journalLine")
- .values(
- reversingJournalEntries.map((line) => ({
- ...line,
- journalId: voidJournalResult.id,
- }))
- )
- .returning(["id"])
- .execute();
- }
+ await trx
+ .insertInto("journalLine")
+ .values(
+ reversingJournalEntries.map((line) => ({
+ ...line,
+ journalId: voidJournalResult.id,
+ }))
+ )
+ .returning(["id"])
+ .execute();
}
// Insert reversing item ledger entries
diff --git a/packages/database/supabase/functions/post-shipment/index.ts b/packages/database/supabase/functions/post-shipment/index.ts
index 099b9b0ef9..aff5bbefb4 100644
--- a/packages/database/supabase/functions/post-shipment/index.ts
+++ b/packages/database/supabase/functions/post-shipment/index.ts
@@ -220,6 +220,7 @@ serve(async (req: Request) => {
itemId: string | null;
itemPostingGroupId: string | null;
locationId: string | null;
+ // Always null: salesOrderLine has no cost center column.
costCenterId: string | null;
fixedAssetClassId: string | null;
}[] = [];
@@ -484,7 +485,7 @@ serve(async (req: Request) => {
itemId: shipmentLine.itemId ?? null,
itemPostingGroupId,
locationId: shipmentLine.locationId ?? locationId ?? null,
- costCenterId: salesOrderLine?.costCenterId ?? null,
+ costCenterId: null,
fixedAssetClassId: null,
});
}
@@ -623,7 +624,7 @@ serve(async (req: Request) => {
itemId: null,
itemPostingGroupId: null,
locationId: locationId ?? assetRecord.data.locationId ?? null,
- costCenterId: faSoLine.costCenterId ?? null,
+ costCenterId: null,
fixedAssetClassId: assetRecord.data.fixedAssetClassId ?? null,
});
}
@@ -655,7 +656,7 @@ serve(async (req: Request) => {
itemId: null,
itemPostingGroupId: null,
locationId: locationId ?? assetRecord.data.locationId ?? null,
- costCenterId: faSoLine.costCenterId ?? null,
+ costCenterId: null,
fixedAssetClassId: assetRecord.data.fixedAssetClassId ?? null,
});
}
@@ -682,7 +683,7 @@ serve(async (req: Request) => {
itemId: null,
itemPostingGroupId: null,
locationId: locationId ?? assetRecord.data.locationId ?? null,
- costCenterId: faSoLine.costCenterId ?? null,
+ costCenterId: null,
fixedAssetClassId: assetRecord.data.fixedAssetClassId ?? null,
});
diff --git a/packages/database/supabase/functions/shared/post-adjustment.ts b/packages/database/supabase/functions/shared/post-adjustment.ts
index e6666c433b..6ab35c508f 100644
--- a/packages/database/supabase/functions/shared/post-adjustment.ts
+++ b/packages/database/supabase/functions/shared/post-adjustment.ts
@@ -9,6 +9,7 @@ import {
buildCostLedgerRow,
buildItemLedgerRow,
buildJournalLineDimensions,
+ carriesAdjustmentValue,
} from "./plan-adjustment.ts";
import {
AdjustmentItemCost,
@@ -228,17 +229,13 @@ export async function loadOpenCostLayers(
}
// Book one adjustment movement inside the caller's transaction: the item
-// ledger row, cost-layer maintenance (consume via calculateCOGS on decreases,
-// create a layer at current cost on increases), and — when accounting is
-// enabled and the movement carries value — a balanced journal against the
-// inventory adjustment variance account. Tracked-entity mutations are the
-// caller's responsibility.
+// ledger row, then its valuation (`valueMovement`). Tracked-entity mutations
+// are the caller's responsibility.
export async function bookAdjustment(
trx: Transaction<DB>,
args: BookAdjustmentArgs
): Promise<BookAdjustmentResult> {
const { ledger, item, itemCost, accounting, skipValuation } = args;
- const { companyId } = ledger;
const inserted = await trx
.insertInto("itemLedger")
@@ -256,30 +253,84 @@ export async function bookAdjustment(
quantity: ledger.quantity,
comment: ledger.comment,
scrapReasonId: ledger.scrapReasonId,
- companyId,
+ companyId: ledger.companyId,
createdBy: ledger.createdBy,
})
)
.returning(["id"])
.executeTakeFirstOrThrow();
- if (
- skipValuation ||
- item.itemTrackingType === "Non-Inventory" ||
- ledger.quantity === 0
- ) {
+ if (skipValuation) {
return { itemLedgerId: inserted.id, journalId: null, cost: 0 };
}
- const absQuantity = Math.abs(ledger.quantity);
- const documentId = ledger.documentId ?? inserted.id;
+ const { journalId, cost } = await valueMovement(trx, {
+ movement: {
+ postingDate: ledger.postingDate,
+ itemId: ledger.itemId,
+ quantity: ledger.quantity,
+ locationId: ledger.locationId,
+ entryType: ledger.entryType,
+ documentType: ledger.documentType,
+ documentId: ledger.documentId ?? inserted.id,
+ companyId: ledger.companyId,
+ },
+ item,
+ itemCost,
+ accounting,
+ fixedUnitCost: args.fixedUnitCost,
+ });
+
+ return { itemLedgerId: inserted.id, journalId, cost };
+}
+
+export interface ValueMovementArgs {
+ movement: {
+ postingDate: string; // yyyy-MM-dd
+ itemId: string;
+ // SIGNED: < 0 relieves cost layers, > 0 opens one
+ quantity: number;
+ locationId: string | null;
+ entryType: Database["public"]["Enums"]["itemLedgerType"];
+ documentType?:
+ | Database["public"]["Enums"]["itemLedgerDocumentType"]
+ | null;
+ // costLedger.documentId and journalLine.documentId
+ documentId: string;
+ companyId: string;
+ };
+ item: BookAdjustmentArgs["item"];
+ itemCost: AdjustmentItemCost;
+ accounting: BookAdjustmentArgs["accounting"];
+ fixedUnitCost?: number;
+}
+
+// Value a stock movement whose item ledger row the caller has already written:
+// cost-layer maintenance (consume via calculateCOGS on decreases, open a layer
+// at current cost — or `fixedUnitCost` — on increases) and, when accounting is
+// enabled and the movement carries value, a balanced journal of the inventory
+// account against the offset account. `bookAdjustment` is this plus the ledger
+// row; maintenance consumption calls it directly because its ledger rows are
+// written alongside tracked-entity splits.
+export async function valueMovement(
+ trx: Transaction<DB>,
+ args: ValueMovementArgs
+): Promise<{ journalId: string | null; cost: number }> {
+ const { movement, item, itemCost, accounting } = args;
+ const { companyId, documentId } = movement;
+
+ if (!carriesAdjustmentValue(movement.quantity, item.itemTrackingType)) {
+ return { journalId: null, cost: 0 };
+ }
+
+ const absQuantity = Math.abs(movement.quantity);
let cost = 0;
- if (ledger.quantity < 0) {
+ if (movement.quantity < 0) {
// Decrease: relieve carrying value exactly as shipments do — consume
// layers (FIFO/LIFO) / current cost (Average/Standard).
const cogs = await calculateCOGS(trx, {
- itemId: ledger.itemId,
+ itemId: movement.itemId,
quantity: absQuantity,
companyId,
});
@@ -289,13 +340,13 @@ export async function bookAdjustment(
.insertInto("costLedger")
.values(
buildCostLedgerRow({
- entryType: ledger.entryType,
- documentType: ledger.documentType,
+ entryType: movement.entryType,
+ documentType: movement.documentType,
documentId,
- itemId: ledger.itemId,
+ itemId: movement.itemId,
quantity: -absQuantity,
cost: -cogs.totalCost,
- postingDate: ledger.postingDate,
+ postingDate: movement.postingDate,
companyId,
})
)
@@ -309,13 +360,13 @@ export async function bookAdjustment(
.insertInto("costLedger")
.values(
buildCostLedgerRow({
- entryType: ledger.entryType,
- documentType: ledger.documentType,
+ entryType: movement.entryType,
+ documentType: movement.documentType,
documentId,
- itemId: ledger.itemId,
+ itemId: movement.itemId,
quantity: absQuantity,
cost,
- postingDate: ledger.postingDate,
+ postingDate: movement.postingDate,
companyId,
})
)
@@ -323,12 +374,12 @@ export async function bookAdjustment(
} else {
// Increase: create a layer at the item's current carrying cost.
const openLayers = await loadOpenCostLayers(trx, {
- itemIds: [ledger.itemId],
+ itemIds: [movement.itemId],
companyId,
});
const unitCost = computeCurrentUnitCost(
itemCost,
- openLayers.get(ledger.itemId) ?? []
+ openLayers.get(movement.itemId) ?? []
);
cost = absQuantity * unitCost;
@@ -336,13 +387,13 @@ export async function bookAdjustment(
.insertInto("costLedger")
.values(
buildCostLedgerRow({
- entryType: ledger.entryType,
- documentType: ledger.documentType,
+ entryType: movement.entryType,
+ documentType: movement.documentType,
documentId,
- itemId: ledger.itemId,
+ itemId: movement.itemId,
quantity: absQuantity,
cost,
- postingDate: ledger.postingDate,
+ postingDate: movement.postingDate,
companyId,
})
)
@@ -352,7 +403,7 @@ export async function bookAdjustment(
// A zero-value movement posts no journal (nothing to tie out; a $0-net
// entry is noise).
if (!accounting || cost === 0) {
- return { itemLedgerId: inserted.id, journalId: null, cost };
+ return { journalId: null, cost };
}
const journalId = accounting.getJournalId
@@ -361,7 +412,7 @@ export async function bookAdjustment(
companyId,
accountingPeriodId: accounting.accountingPeriodId,
description: accounting.description,
- postingDate: ledger.postingDate,
+ postingDate: movement.postingDate,
userId: accounting.userId,
sourceType: accounting.sourceType,
});
@@ -372,9 +423,9 @@ export async function bookAdjustment(
buildAdjustmentJournalLines({
journalId,
documentId,
- documentType: ledger.documentType,
+ documentType: movement.documentType,
journalLineReference: nanoid(),
- isGain: ledger.quantity > 0,
+ isGain: movement.quantity > 0,
cost,
quantity: absQuantity,
replenishmentSystem: item.replenishmentSystem,
@@ -390,9 +441,9 @@ export async function bookAdjustment(
const journalLineDimensionInserts = buildJournalLineDimensions({
journalLineIds: journalLines.map((line) => line.id),
dimensions: accounting.dimensions ?? {},
- itemId: ledger.itemId,
+ itemId: movement.itemId,
itemPostingGroupId: item.itemPostingGroupId,
- locationId: ledger.locationId,
+ locationId: movement.locationId,
extraDimensions: accounting.extraDimensions,
companyId,
});
@@ -403,5 +454,5 @@ export async function bookAdjustment(
.execute();
}
- return { itemLedgerId: inserted.id, journalId, cost };
+ return { journalId, cost };
}
diff --git a/packages/database/supabase/migrations/20260929181534_maintenance-labor-journal.sql b/packages/database/supabase/migrations/20260929181534_maintenance-labor-journal.sql
new file mode 100644
index 0000000000..b3cb75f4b4
--- /dev/null
+++ b/packages/database/supabase/migrations/20260929181534_maintenance-labor-journal.sql
@@ -0,0 +1,7 @@
+-- Maintenance labor: time on a maintenance dispatch is expensed at the work
+-- center's labor rate (Dr maintenanceAccount / Cr laborAbsorptionAccount) by
+-- the post-maintenance-event edge function. Its journals and lines need their
+-- own source/document type — "Production Event" lines carry a job id and
+-- "Maintenance Consumption" is spare parts.
+ALTER TYPE "journalEntrySourceType" ADD VALUE IF NOT EXISTS 'Maintenance Event';
+ALTER TYPE "journalLineDocumentType" ADD VALUE IF NOT EXISTS 'Maintenance Event';
diff --git a/packages/ee/src/accounting/core/models.ts b/packages/ee/src/accounting/core/models.ts
index 1ce2a0f38e..722b0523b0 100644
--- a/packages/ee/src/accounting/core/models.ts
+++ b/packages/ee/src/accounting/core/models.ts
@@ -515,6 +515,12 @@ export const POSTING_POLICY: Record<
defaultEnabled: true,
defaultGranularity: "individual"
},
+ // Maintenance labor, like production time, posts often and in small amounts.
+ "Maintenance Event": {
+ representation: "journal",
+ defaultEnabled: true,
+ defaultGranularity: "daily-summary"
+ },
"Asset Depreciation": {
representation: "journal",
defaultEnabled: true,
diff --git a/packages/ee/src/accounting/core/posting-policy.test.ts b/packages/ee/src/accounting/core/posting-policy.test.ts
index 663e54659c..c093069688 100644
--- a/packages/ee/src/accounting/core/posting-policy.test.ts
+++ b/packages/ee/src/accounting/core/posting-policy.test.ts
@@ -70,7 +70,10 @@ describe("POSTING_POLICY", () => {
// Added post-v2 with the Ramp integration: charge journals
// (Dr expense / Cr card liability) push to the provider like any other
// automated internal posting — no document representation exists.
- "Charge"
+ "Charge",
+ // Added post-v2 with maintenance labor: time on a maintenance dispatch
+ // posts Dr maintenance / Cr labor absorption, like Production Event.
+ "Maintenance Event"
].sort()
);
diff --git a/packages/react/src/Number.tsx b/packages/react/src/Number.tsx
index 529257f008..d025a2daeb 100644
--- a/packages/react/src/Number.tsx
+++ b/packages/react/src/Number.tsx
@@ -54,8 +54,19 @@ const NumberField = ({
);
};
-const NumberInputGroup = (props: ReactAria.GroupProps) => {
- return <ReactAria.Group {...props} />;
+// `relative` anchors the absolutely positioned NumberInputStepper to the input;
+// without it the arrows attach to the nearest positioned ancestor (e.g. a modal).
+const NumberInputGroup = ({ className, ...props }: ReactAria.GroupProps) => {
+ return (
+ <ReactAria.Group
+ className={
+ typeof className === "function"
+ ? (values) => cn("relative", className(values))
+ : cn("relative", className)
+ }
+ {...props}
+ />
+ );
};
const NumberInputStepper = ({