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(jobs): the job page and jobs table offer Delete only for jobs it can delete (Draft or Planned)
aashu11124d52c434
diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.mdindex fad2c1684a..21b74e0225 100644--- a/apps/erp/app/modules/production/AGENTS.md+++ b/apps/erp/app/modules/production/AGENTS.md@@ -142,7 +142,7 @@ pnpm --filter erp test- `getProductionPlanning` — MRP-driven production planning (RPC `get_production_planning_grid`, latest migration `20261006205037`: wraps `get_production_planning` and adds the item group, the planning-horizon fence date, the first negative week, the latest order date and `orderQuantity` — the open Make actions inside the fence, which the default sort uses (the Order / Make button shows the quantity; there is no Qty to Order column), not the base RPC's `quantityToOrder`; `asOf` is the location's today, and `actionTypes` / `actionAssignees` filter on OPEN planning actions inside each item's fence, in the database)- `nextJobPriority(siblings, deadlineType)` — pure: a job's fractional priority among the jobs already on its date, by deadline type; `calculateJobPriority` reads the siblings and calls it, the planning date apply places a batch with it. `deadlineTypeForPlanningDate(deadlineType)` — the type a job carries once planning gives it a date (No Deadline → Soft Deadline)- **Job status** (`production.server.ts`, all published except `planDraftJob`) — the job header's buttons post to `x+/job+/$jobId.status.tsx`, which maps the status to one operation: Planned → `planDraftJob` (Draft only), Paused → `pauseJob` (from Ready / In Progress), Ready → `resumeJob` (from Paused; refuses blocked manufacturing and the Make to Asset rules, then recalculates and runs MRP), Draft / In Progress → `reopenJob` (Cancelled → Draft, Completed → In Progress), Closed → `closeJob` (from Completed, then `service.closeJob` writes the remaining WIP off as production variance), Cancelled → `cancelJob`. Each flip is guarded on its from-statuses (`moveJobStatus`). Complete is `completeJob` (`x+/job+/$jobId.complete.tsx`): `complete_job_to_inventory`, then the picked-material return (a failure there is a `warning`).-- **Job edits** (`production.server.ts`, published) — `updateJobDetails` (the details form), `configureJob`, `createJob` (`x+/job+/new.tsx`: the records must be the company's, refused for an item an unreleased change notice holds and for a Make to Asset item that cannot complete to an asset; the route shows those two on the item field), `createJobs` (`x+/job+/bulk.new.tsx`), `insertJob` (the API's and workflows' create: Draft or Planned only), `createSalesOrderLineJob` (unpublished, `x+/sales-order+/$orderId.$lineId.job.tsx`; the line must be on the order) and `convertSalesOrderLinesToJobs` (`$orderId.lines.jobs.tsx`). Every job creation goes through `jobCreationRefusal` (the records are the company's, no unreleased change notice holds the item, the Make to Asset rule); `orderPlannedJobs` skips an item a change notice holds. `deleteJobs` and the property panel's / jobs table's field writes through `x+/job+/update.tsx` — `setJobItem` (re-pulls the method), `setJobDeadline` (re-ranks priority, one read and one write for all jobs), `setJobQuantity` (recalculates), `setJobSalesOrderLine`, `setJobFields` — and `updateJobDetails` and `configureJob` refuse a locked job (`readUnlockedJobs` / `requireJob`).+- **Job edits** (`production.server.ts`, published) — `updateJobDetails` (the details form), `configureJob`, `createJob` (`x+/job+/new.tsx`: the records must be the company's, refused for an item an unreleased change notice holds and for a Make to Asset item that cannot complete to an asset; the route shows those two on the item field), `createJobs` (`x+/job+/bulk.new.tsx`), `insertJob` (the API's and workflows' create: Draft or Planned only), `createSalesOrderLineJob` (unpublished, `x+/sales-order+/$orderId.$lineId.job.tsx`; the line must be on the order) and `convertSalesOrderLinesToJobs` (`$orderId.lines.jobs.tsx`). Every job creation goes through `jobCreationRefusal` (the records are the company's, no unreleased change notice holds the item, the Make to Asset rule); `orderPlannedJobs` skips an item a change notice holds. `deleteJobs` deletes the jobs `isJobDeletable` allows (Draft, Planned, and the deprecated Due Today / Overdue), skips the rest, and is refused when it could delete none; the job page's and the jobs table's Delete menus use the same predicate. The property panel's / jobs table's field writes through `x+/job+/update.tsx` — `setJobItem` (re-pulls the method), `setJobDeadline` (re-ranks priority, one read and one write for all jobs), `setJobQuantity` (recalculates), `setJobSalesOrderLine`, `setJobFields` — and `updateJobDetails` and `configureJob` refuse a locked job (`readUnlockedJobs` / `requireJob`).- **Job method** (`production.server.ts`, published) — Get Method is `copyMethodToJob` (`upsertJobMethod`, then the job's requirements and dependencies) and `copyMethodToMaterial`; `createJobMaterial` / `updateJobMaterial` / `deleteJobMaterial` / `deleteJobMaterials` and `createJobOperation` / `updateJobOperation` / `deleteJobOperation` / `deleteJobOperations` (the plural two are unpublished: Delete Selected, one recalculation) / `reorderJobOperations` / `setJobOperationStatus` (a Done operation returns its unconsumed picks) / `setJobOperationDueDate` / `syncJobOperationProcedure` back the bill of material and bill of process routes under `x+/job+/methods+/`; Get Method and the material, operation and procedure writes refuse a locked job (`requireJob`). Save Method (`x+/job+/methods+/save.tsx`) is `upsertMakeMethodFromJob` / `upsertMakeMethodFromJobMethod`: parts update and the target method's revision lock, as the items' Save Method. `completeOperation` (published) reports a good quantity on an untracked operation: it records it, backflushes (`issue`), and at the target sets the operation Done, posts its ended events and returns its picks. `createProductionEvent` / `updateProductionEvent` save a production event and post an ended one to the GL (`post-production-event`; a skipped posting is returned as `postingError`). `createProductionQuantity` records a production quantity (refuses a locked job, keeps a scrap reason only on Scrap); `updateProductionQuantity` corrects one and needs accounting update, so it is not published. The procedure properties panel posts to `setProcedureFields`. The bare row writes (`upsertJobMaterial`, `upsertJobOperation`, `upsertJobMethod`, `upsertProductionEvent`, `updateJob`) are building blocks in `production.service.ts` and are never tools.- `cancelJob` (`production.server.ts`, published as `production_cancelJob`) — the one cancel path, used by the job page's Cancel (`x+/job+/$jobId.cancel.tsx`), the status route and planning's Cancel action: refuses another company's job (`notFound`), sets Cancelled and clears the assignee only while the job is in `fromStatuses` (default `CANCELLABLE_JOB_STATUSES`; a refusal is a `conflict` and changes nothing), then returns its unconsumed picked material (`post-picking` `returnJobRemainders`, which sweeps only a Completed or Cancelled job) and cancels its open picking-list lines; a failure of either is a `warning`, the job stays Cancelled. Pinned by `test/database/cancel-job.test.ts`. Planning edits a job only while `isJobEditableFromPlanning` (`production.models.ts`: Draft / Planned)- `getPlanningActions` / `getPlanningActionsByIds` — the persisted MRP worklist (`planningAction`, written by `generatePlanningActions` in `@carbon/planning` after every MRP run; statuses `Open` / `Dismissed` / `Actioned`). `dismissPlanningActions` / `reopenDismissedPlanningActions` (Dismissed ↔ Open; both return the ids they changed, which the routes report), `markPlanningActionsActioned` (the conditional Open → Actioned claim that is the apply path's lock — an empty result means another apply got there first; it returns the row's suggested quantity and date, which Apply writes instead of the page's possibly stale read) and `reopenPlanningActions` (its rollback, Actioned → Open), `assignPlanningActions` (sets the assignee and marks it overridden so the next MRP run keeps it; Open and Dismissed rows only, returning the ids it changed). `settleNewSupplyPlanningActions` is the page's Order button's settle: the suggested orders it submits carry no action id, so after the PO lines (`Order`) or jobs (`Make`) are created it flips the Open / Dismissed action of each ordered (item, week) pair at the location to Actioned — otherwise the suggestion stayed on the page beside its order until the next MRP run. An Apply reads its actions (`getPlanningActionsByIds`) and their jobs / PO lines in one statement each (Kysely, the ids as parameters — never a PostgREST URL), then applies set-based: `applyProductionPlanningDateActions(db, …)` moves every Expedite / Defer in one transaction (the claim, the jobs, the jobs already on the target dates, one UPDATE of due date + deadline type + priority via the pure `nextJobPriority` — a "No Deadline" job becomes `Soft Deadline`, `deadlineTypeForPlanningDate`, since the job form hides the due date for No Deadline), and the route sends one `schedule-inputs-changed` event for the batch; Increase / Decrease / Cancel call postings with their own transactions, so they run per job, three jobs at a time, each claimed right before its change. The transaction-scoped claim and release live in `planning-action-claims.ts` (`claimPlanningActions` / `releasePlanningActionClaims`), shared with purchasing's `applyPurchasingPlanningActions`. Bad input to either planning route answers 400, a failed read or write 500. `releasePlanningActionClaim` gives a failed per-job apply's claim back (deleting it instead when MRP has already written an Open row for the same need), and `updatePlanningJob` is planning's single-job write (the drawer's inline edit, and Increase / Decrease), guarded on Draft / Planned in the UPDATE itself; a quantity change restates `scrapQuantity` from the item's scrap rate. `planDraftJob` (`production.server.ts`) is the drawer's Plan on a Draft job (`planJob` intent), in `releaseJobs`' order: the requirements recalculation (a failure leaves the job Draft), the guarded Draft → Planned flip, then MRP, so the job counts as supply. It sends no scheduler notice — the scheduler places only released jobs. `replanAfterItemChange` (`production.server.ts`) runs MRP after an item's planning or manufacturing settings are saved, so the planning pages follow them at once. `planningAction` is read-only through the API; its writers use the service role. Applied from `x+/production+/planning.update.tsx` (one service-function call per `action`: `order` (`orderPlannedJobs`), `updateJob` (`updatePlannedJob`), `planJob` (`planJobFromPlanning`), `apply` and its typed aliases (`applyPlanningActions`), `dismiss` (`dismissProductionPlanningActions`), `reopen` (`reopenProductionPlanningActions`), `assign` (`assignProductionPlanningActions`); a dismiss / reopen / assign that changes nothing is a `conflict`) and `x+/purchasing+/planning.update.tsx`; `usePlanningActions` reads both routes' answers; UI in `ui/Planning/`: `ProductionPlanningTable` + `ProductionPlanningOrderDrawer`, `planningColumns.tsx` (the column set shared with purchasing: the Stock Availability week strip via `PlanningWeekStrip` + `planning-week-geometry.ts`, `LatestOrderDate`, `PlanningFence` + `planning-fence.ts`), `PlanningActionLines` (the expanded row), `PlanningOrderGrids` + `PlanningDrawerParts` (the drawer's suggested / open-order grids, `periodIdFor`, the "N More After" button), `usePlanningActions` (the dismiss / reopen / assign / apply fetcher), and `planning-action-scope.ts` (`resolvePlanningActionScope`, `actionsOfTypes`, `PLANNING_ACTIONS_COLUMN`, `PLANNING_ASSIGNEE_COLUMN`, `PLANNING_DRAWER_PARAM` — pure, re-exported from `production.models.ts` so vitest can import it), `planned-orders-from-actions.ts` (pure: the drawer's suggested orders, the row's Order / Make quantity and a bulk order are the item's open Order / Make actions — `openNewSupplyActions`, `plannedOrdersFromActions`, `productionOrdersFromActions`, `supplierConversionFactor` — never sized again on screen, so a shortfall MRP folded into an Increase is not offered twice), `planning-increase.ts` (pure: `chartedOrderQuantity` charts an order at its open Increase), and `planning-review.ts` (pure: `planningActionNeedsReview` — Review vs Apply from the order's LIVE status, `purchaseOrderStatus` / `jobStatus` from `getPlanningActions`, not MRP's run-time `requiresManualAction` stamp, so a PO reopened since applies at once; a date move on a supplier-promised line stays Review — and `purchaseOrderPlanningMenu`, which order commands a row's ⋯ offers; `PlanningActionHandlers.purchaseOrderMenuItems` carries them, purchasing only). Both planning grids put the open order drawer's item in the address (`?item=<itemId>`, `useLinkedDrawerItem` in `~/hooks/useDrawerItem`), so a link reopens it; the loader reads that row on its own (`drawerItem`) when it is not on the page. Tests: `apps/erp/test/apply-production-planning-date-actions.test.ts` (`nextJobPriority`, `planJobDateMoves`), `planning-action-scope.test.ts`, `planning-fence.test.ts`, `planning-increase.test.ts`, `planning-review.test.ts`, `planned-orders-from-actions.test.ts`, `planning-week-geometry.test.ts`diff --git a/apps/erp/app/modules/production/production.models.test.ts b/apps/erp/app/modules/production/production.models.test.tsindex 8689b53a25..d0558a9709 100644--- a/apps/erp/app/modules/production/production.models.test.ts+++ b/apps/erp/app/modules/production/production.models.test.ts@@ -7,16 +7,16 @@ import {assemblyInstructionStepValidator,isBatchDissolvable,isBatchReleasable,- isJobBulkDeletable,isJobBulkReleasable,+ isJobDeletable,jobStatus} from "./production.models";-describe("isJobBulkDeletable", () => {+describe("isJobDeletable", () => {it("accepts Draft, Planned and the 2 deprecated due statuses only", () => {- const deletable = jobStatus.filter(isJobBulkDeletable);+ const deletable = jobStatus.filter(isJobDeletable);expect(deletable).toEqual(["Draft", "Planned", "Overdue", "Due Today"]);- expect(isJobBulkDeletable(null)).toBe(false);+ expect(isJobDeletable(null)).toBe(false);});});diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.tsindex 99f17cc16d..6e7ccfbb98 100644--- a/apps/erp/app/modules/production/production.models.ts+++ b/apps/erp/app/modules/production/production.models.ts@@ -111,17 +111,18 @@ export function isJobEditableFromPlanning(// The one definition lives in @carbon/utils, shared with the OEE sync.export { isJobLocked, JOB_LOCKED_STATUSES } from "@carbon/utils";-/** The statuses the jobs table's bulk Delete acts on. "Due Today" and- * "Overdue" are deprecated statuses that old jobs can still hold. */-export const JOB_BULK_DELETABLE_STATUSES = [+/** The statuses a job can be deleted in (`deleteJobs`, and every Delete+ * menu). "Due Today" and "Overdue" are deprecated statuses that old jobs+ * can still hold. */+export const JOB_DELETABLE_STATUSES = ["Draft","Planned","Due Today","Overdue"] as const;-export function isJobBulkDeletable(status: string | null | undefined): boolean {- return JOB_BULK_DELETABLE_STATUSES.some((allowed) => allowed === status);+export function isJobDeletable(status: string | null | undefined): boolean {+ return JOB_DELETABLE_STATUSES.some((allowed) => allowed === status);}/** The statuses the jobs table's bulk Release acts on. */diff --git a/apps/erp/app/modules/production/production.server.ts b/apps/erp/app/modules/production/production.server.tsindex acf8ff5d0c..0302649dbf 100644--- a/apps/erp/app/modules/production/production.server.ts+++ b/apps/erp/app/modules/production/production.server.ts@@ -73,7 +73,7 @@ import {isJobBulkReleasable,isJobEditableFromPlanning,isJobLocked,- JOB_BULK_DELETABLE_STATUSES,+ JOB_DELETABLE_STATUSES,JOB_LOCKED_MESSAGE,JOB_LOCKED_STATUSES,jobOperationStatus,@@ -1505,7 +1505,7 @@ export const deleteJobs = defineServiceFn({.delete().in("id", chunk).eq("companyId", ctx.company.id)- .in("status", [...JOB_BULK_DELETABLE_STATUSES])+ .in("status", [...JOB_DELETABLE_STATUSES]).select("id");if (result.error) {return ctx.error("internal", "Failed to delete the jobs", result.error);diff --git a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsxindex 23a2218212..4577ee0d6e 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx@@ -94,7 +94,7 @@ import type { action as statusAction } from "~/routes/x+/job+/$jobId.status";import { useSuppliers } from "~/stores";import { generateBomIds } from "~/utils/bom";import { path } from "~/utils/path";-import { isJobLocked, jobCompleteValidator } from "../../production.models";+import { isJobDeletable, jobCompleteValidator } from "../../production.models";import { getJobMethodTree } from "../../production.utils";import type { Job } from "../../types";import JobStatus from "./JobStatus";@@ -290,7 +290,7 @@ const JobHeader = () => {disabled={!permissions.can("delete", "production") ||!permissions.is("employee") ||- isJobLocked(routeData?.job?.status)+ !isJobDeletable(routeData?.job?.status)}destructiveonClick={deleteJobModal.onOpen}diff --git a/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx b/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsxindex 59dc407f7e..8111a65e2e 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx@@ -79,8 +79,8 @@ import { path } from "~/utils/path";import { ALL_MATCHING_RELEASE_LIMIT } from "~/utils/table-jobs";import {deadlineTypes,- isJobBulkDeletable,isJobBulkReleasable,+ isJobDeletable,jobStatus} from "../../production.models";import type { Job } from "../../types";@@ -768,7 +768,7 @@ const JobsTable = memo((props: JobsTableProps) => {disabled={!permissions.can("delete", "production") ||(!allMatching &&- selectedRows.some((row) => !isJobBulkDeletable(row.status)))+ selectedRows.some((row) => !isJobDeletable(row.status)))}destructiveonClick={() =>@@ -801,7 +801,10 @@ const JobsTable = memo((props: JobsTableProps) => {<MenuItemshortcut={MENU_ITEM_SHORTCUTS.delete}destructive- disabled={!permissions.can("delete", "production")}+ disabled={+ !permissions.can("delete", "production") ||+ !isJobDeletable(row.status)+ }onClick={() => onDelete(row)}><MenuIcon icon={<LuTrash />} />