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(items): add Service as a first-class item type (#1107)

Brad Barbin264232320a5b
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 25605b98f5..5eb2ef3712 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -348,3 +348,23 @@ Format: `Context → Problem → Rule → Applies to`
**Rule:** When a cache/snapshot is written inside a state-flip transaction and a concurrent writer keys off the *committed* state, make the writer take a lock that conflicts with the flip. Here: the posting guard reads the target `accountingPeriod` row `FOR SHARE` (migration `20260713235930`), which blocks behind the close's row lock — postings before the flip commit first (and land in the snapshot); postings after block, then see `Closed` and are rejected. `FOR SHARE` is shared, so normal concurrent postings don't block each other; only an in-flight close serializes them. Verify with two psql sessions + `lock_timeout`.
**Applies to:** `check_accounting_period_open`; `snapshotAccountingPeriodBalances` / `accountingPeriodBalance`; any close/snapshot-on-commit pattern.
+
+## Forking a SQL function migration silently drops sibling branches added since your fork base
+
+**Context:** `complete_job_to_inventory` gained a Non-Inventory branch in `20260707022142` (services post WIP→COGS, no inventory artifacts). Six days later, two migrations (`20260713190909` raw-materials split, `20260713222236` overhead fix) each forked the function from the older `20260630092517` baseline — silently deleting the Non-Inventory branch. Service job completions then posted phantom Finished Goods until the branch was restored in `20260714043017`.
+
+**Problem:** "Fork from the newest definition" fails when the author greps for the migration that matters to *their* change and misses intermediate redefinitions that added orthogonal branches. The dropped branch produces no error — the divergent behavior only surfaces when someone exercises the other feature.
+
+**Rule:** Before redefining a function, list EVERY migration that touches it (`grep -l '<fn_name>' migrations/*.sql | sort`), and fork from the last one — then diff your new body against that exact file (`diff <(sed -n 'a,bp' newest.sql) <(...)`) so the only hunks are your intended edits. If the timeline shows a branch you don't understand (an `itemTrackingType` guard, a feature flag), it is load-bearing — carry it forward, never re-derive the body from an older file or memory.
+
+**Applies to:** `packages/database/supabase/migrations/` — any `CREATE OR REPLACE FUNCTION` fork; reviews of migrations that redefine shared functions (`complete_job_to_inventory`, `backflush_job_materials`, `get_inventory_quantities`, sync interceptors).
+
+## Job-completion side effects must live in complete_job_to_inventory, not in route actions
+
+**Context:** Service-job fulfillment (advance the linked salesOrderLine on completion) was first implemented in the ERP `$jobId.complete.tsx` action after the RPC call. In e2e it never ran: the operator finished the last operation, and `sync_update_job_operation_quantities` → `sync_finish_job_operation` (DB interceptors) called `complete_job_to_inventory` directly — the ERP route was never involved.
+
+**Problem:** Job completion has multiple entry points — the ERP Complete button AND the interceptor cascade that auto-completes when the last operation flips to Done (fired from MES quantity recording or ERP production quantities). Any completion side effect hooked at the app layer silently misses the interceptor path.
+
+**Rule:** Side effects that must accompany job completion (fulfillment, status propagation, posting) go INSIDE `complete_job_to_inventory` — the single choke point every path crosses. Place them before the `accountingEnabled` / zero-WIP early returns if they must run unconditionally. App-layer completion hooks are only valid for effects the SQL function cannot perform (edge-function invocation — cf. `returnAllocatedRemaindersAtJobComplete`, orchestrated in TS for exactly that reason).
+
+**Applies to:** `complete_job_to_inventory`; `apps/erp/app/routes/x+/job+/$jobId.complete.tsx`; `sync_finish_job_operation`; any future completion-triggered behavior (rev-rec POC recognition events).
diff --git a/.ai/plans/2026-07-14-service-make-to-order-jobs.md b/.ai/plans/2026-07-14-service-make-to-order-jobs.md
new file mode 100644
index 0000000000..9745353345
--- /dev/null
+++ b/.ai/plans/2026-07-14-service-make-to-order-jobs.md
@@ -0,0 +1,473 @@
+# Service Make-to-Order Jobs — implementation plan
+
+**Spec:** .ai/specs/2026-07-14-service-make-to-order-jobs.md
+**Research:** .ai/research/service-make-to-order-jobs.md
+**Branch:** feat/service
+
+## Progress
+- [x] Task 1: Migration — restore the Non-Inventory branch in `complete_job_to_inventory` (commit d10c1d12e)
+- [x] Task 2: Confirm generated types are unaffected (do NOT regenerate) — verified untouched, no commit needed
+- [x] Task 3: Harden `convertSalesOrderLinesToJobs` for service lines (commit 00e75c435; pre-existing TS2589 in part+ delete route proven on clean tree, unrelated)
+- [x] Task 4: Fulfillment helper — service job completion advances the sales-order line (commit 501dfd657)
+- [x] Task 5: Validation gates — lint 32/32 PASS (13 pre-existing warnings); typecheck erp: only the pre-existing TS2589 (proven on clean tree)
+- [x] Task 6: Browser e2e — full service MTO flow, run by Brad 2026-07-14 (fixtures: process `proc_svc_e2e_assembly1`, work center `wc_svc_e2e_bench1` laborRate 50/overhead 10). Results: SO000001 / J000001 — labor+overhead accumulated Dr WIP 0.8333; completion posted exactly Dr COGS 0.8333 / Cr WIP 0.8333; zero itemLedger "Assembly Output" and zero costLedger rows for the job; SO line quantitySent 1 / sentComplete ✓ / sentDate 2026-07-14 (after Task 8 backfill). Findings spawned Tasks 7–9; zero-cost material issue confirmed as inherited behavior (documented in spec changelog).
+- [x] Task 7 (e2e finding, commit b68962287): show the "Jobs Required" card for all-service orders
+- [x] Task 9 (e2e finding, commit 29648a179): MES IssueMaterialModal — 'Non-Inventory' missing from its TrackingType union sent consumables/services into the Serial/Batch branch (no quantity field, unsubmittable); now routed through the untracked ValidatedForm branch
+- [x] Task 8 (e2e finding, commit 6c6565d0c): fulfillment moved INTO `complete_job_to_inventory` — completion is also reachable via the `sync_finish_job_operation` interceptor (auto-complete on last operation Done), which bypassed the route-level hook; the SQL function is the only choke point. TS helper + route hook removed; migration edited in place (never pushed) and re-applied; validation script extended with fulfillment assert (green); Brad's live line backfilled by idempotent re-run (no duplicate journal) — `getSalesOrderStatus` counts Service lines as shipped, so a service-only order confirms straight to "To Invoice" and `SalesOrderSummary`'s status gate `["To Ship and Invoice","To Ship"]` never matches. Fix: also render at "To Invoice" when a line is `salesOrderLineType === "Service" && methodType === "Make to Order"` (physical-order behavior unchanged). File: `apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx`. Verify: typecheck erp + Brad's browser session shows the card on SO000001.
+
+## Dependencies
+- Task 2 needs Task 1 (migration exists).
+- Tasks 3 and 4 are independent of each other and of Task 1 (may run in parallel).
+- Task 5 needs Tasks 3–4. Task 6 needs Tasks 1–5 (migration applied locally + code in tree).
+
+## Grounding notes for the executor (verified 2026-07-14 — trust these over older docs)
+
+- The NEWEST `complete_job_to_inventory` definition is in
+ `packages/database/supabase/migrations/20260713222236_fix-job-completion-overhead-absorption.sql`
+ (637 lines; `DROP FUNCTION IF EXISTS` at line 22, `CREATE OR REPLACE` at line 24). It has NO
+ `itemTrackingType` handling — that is the regression being fixed.
+- The dropped Non-Inventory branch template is
+ `packages/database/supabase/migrations/20260707022142_complete-job-to-inventory-non-inventory.sql`
+ (fork of an older baseline; use it as REFERENCE for guard placement only — never copy its body,
+ it predates the raw-materials/FG split and overhead absorption).
+- `sync_create_item_related_records` (newest: `20260501190700`) inserts `itemCost`,
+ `itemReplenishment`, `itemUnitSalePrice`, `itemPlanning` for EVERY item insert, ungated by type —
+ so services DO have `itemReplenishment` rows (with NULL lotSize/scrapPercentage). The converter's
+ `.single()` succeeds today and its error was never checked; Task 3 is hardening, not a hard-bug fix.
+- `getDefaultStorageUnitForJob` (`apps/erp/app/modules/inventory/inventory.service.ts:2679`) is
+ null-safe for services (maybeSingle + empty-list fallthrough). Skipping it for services is an
+ optimization + intent-clarity change.
+- The ERP app's package name is `erp` (`apps/erp/package.json`) — typecheck filter is `--filter=erp`.
+- **Do NOT run `pnpm run generate:types` / `db:types` and commit the result**: committed
+ `packages/database/src/types.ts` is generated from the CLOUD DB (contains per-company tables);
+ local regeneration produces a ~55k-line wrong diff. This migration changes no schema and no RPC
+ signature, so no type change is needed.
+- Local dev boots with plain `crbn up` (portless `*.dev`). After `crbn reset`, accounting is
+ DISABLED (`companySettings.accountingEnabled = false`) — enable it at `/x/settings/accounting`
+ before asserting journals.
+
+---
+
+## Task 1: Migration — restore the Non-Inventory branch in `complete_job_to_inventory`
+
+**Depends on:** none
+**Files:**
+- Create: `packages/database/supabase/migrations/<timestamp>_service-job-completion-cogs.sql`
+ (created via `pnpm db:migrate:new service-job-completion-cogs`; if the generated timestamp ends
+ in `000000`, rename the HHMMSS portion to a random value, e.g. `143752`)
+- Copy from (fork source): `packages/database/supabase/migrations/20260713222236_fix-job-completion-overhead-absorption.sql`
+- Copy from (guard reference only): `packages/database/supabase/migrations/20260707022142_complete-job-to-inventory-non-inventory.sql`
+
+**Steps:**
+
+1. Create the file: `pnpm db:migrate:new service-job-completion-cogs`.
+
+2. Extract the fork source body VERBATIM (per the `.ai/lessons.md` function-fork rule — sed, don't retype):
+ ```bash
+ sed -n '22,637p' packages/database/supabase/migrations/20260713222236_fix-job-completion-overhead-absorption.sql >> packages/database/supabase/migrations/<timestamp>_service-job-completion-cogs.sql
+ ```
+ This gives you `DROP FUNCTION IF EXISTS complete_job_to_inventory(TEXT, NUMERIC, TEXT, TEXT, TEXT, TEXT);`
+ followed by the full `CREATE OR REPLACE FUNCTION` — signature, `SECURITY DEFINER`,
+ `SET search_path = public` all preserved. Keep them EXACTLY as extracted.
+
+3. Prepend a header comment (above the DROP) explaining:
+ - Fork of `20260713222236` (the newest definition).
+ - Restores the Non-Inventory branch originally added in `20260707022142` and silently dropped
+ when the July-13 migrations forked from the older `20260630092517` baseline.
+ - Non-Inventory (Service) completions: WIP discharges to COGS, no inventory artifacts.
+ - Inventory items are byte-identical to `20260713222236`.
+
+4. Apply EXACTLY these edits to the extracted body (line references are to the fork source, i.e.
+ the extracted text before your edits):
+
+ a. **DECLARE block** (after line 38 `v_item_id TEXT;`): add two declarations:
+ ```sql
+ v_item_tracking_type "itemTrackingType";
+ v_cogs_account TEXT;
+ ```
+
+ b. **After the job-details fetch** (after line 92 `WHERE id = p_job_id;` of the first
+ `SELECT ... INTO STRICT`): add:
+ ```sql
+ -- Non-Inventory items (services) never enter inventory
+ SELECT "itemTrackingType"
+ INTO v_item_tracking_type
+ FROM "item"
+ WHERE id = v_item_id
+ AND "companyId" = p_company_id;
+ ```
+
+ c. **Guard the itemLedger block** (lines 113–169: the whole
+ `IF v_job_make_method."requiresBatchTracking" THEN ... ELSIF ... ELSE ... END IF;` that
+ inserts `'Assembly Output'` rows): wrap it in
+ ```sql
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' THEN
+ <existing batch/serial/else itemLedger block, unchanged>
+ END IF;
+ ```
+
+ d. **Guard the pickMethod block** (lines 171–201, `-- Update pickMethod defaultStorageUnitId if needed`):
+ change its outer condition from
+ `IF p_storage_unit_id IS NOT NULL AND p_location_id IS NOT NULL THEN` to
+ `IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' AND p_storage_unit_id IS NOT NULL AND p_location_id IS NOT NULL THEN`.
+
+ e. **Extend the accountDefault fetch** (lines 225–228): add `"costOfGoodsSoldAccount"` to the
+ SELECT list and `v_cogs_account` to the INTO list:
+ ```sql
+ SELECT "rawMaterialsAccount", "finishedGoodsAccount", "workInProgressAccount", "laborAbsorptionAccount", "overheadAbsorptionAccount", "costOfGoodsSoldAccount"
+ INTO STRICT v_raw_materials_account, v_finished_goods_account, v_wip_account, v_labor_absorption_account, v_overhead_absorption_account, v_cogs_account
+ FROM "accountDefault"
+ WHERE "companyId" = p_company_id;
+ ```
+
+ f. **Override the debit account for Non-Inventory** — immediately AFTER the RM/FG resolution
+ SELECT (lines 230–238, the `CASE WHEN i."replenishmentSystem" = 'Buy' ...` block), add:
+ ```sql
+ -- Non-Inventory (Service): the produced output is never stocked, so completion
+ -- relieves WIP straight to Cost of Goods Sold (Epicor "Make Direct" pattern).
+ -- >>> REV-REC SEAM (spec .ai/specs/2026-07-04-revenue-recognition.md, issue #1048):
+ -- when revenue recognition lands, Percent-of-Completion elements will gate THIS
+ -- branch off and post COGS as-incurred in the recognition run instead. <<<
+ IF v_item_tracking_type = 'Non-Inventory' THEN
+ v_item_inventory_account := v_cogs_account;
+ v_item_inventory_description := 'Cost of Goods Sold';
+ END IF;
+ ```
+ (The existing `-- DR Inventory ...` journalLine insert at lines 531–542 then posts
+ Dr COGS / Cr WIP for services with NO further changes — the journal insert itself is untouched.)
+
+ g. **Guard the costLedger insert** (lines 561–571, `-- Write costLedger entry for finished good`):
+ wrap in `IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' THEN ... END IF;`.
+
+ h. **Guard the itemCost update but KEEP the itemCost read** (lines 573–605): the
+ `SELECT "costingMethod", "unitCost", "itemPostingGroupId" INTO ...` (lines 574–578) must stay
+ UNGUARDED — `v_item_posting_group_id` feeds the dimension inserts at lines 607–635 and the
+ division below it would be reached otherwise. Wrap ONLY from
+ `v_new_per_unit_cost := v_accumulated_wip_cost / v_quantity_received_to_inventory;` (line 580)
+ through the end of the `ELSIF v_costing_method IN ('FIFO', 'LIFO') ... END IF;` block (line 605) in
+ `IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' THEN ... END IF;`.
+ (This also protects the service path from a divide-by-zero when
+ `v_quantity_received_to_inventory` is 0 on a re-completion.)
+
+ i. Make NO other edits. In particular: the job-status UPDATE, backflush PERFORM, the
+ production-event catch-up loop (lines 254–466), the WIP-accumulation query, the journal/journalLine
+ inserts, and the dimension loop all stay byte-identical.
+
+5. Apply locally: `pnpm db:migrate` (requires the local stack from `crbn up`; if the DB is
+ unreachable, STOP and report — do not attempt `db:build`, it does not exist, and never rebuild
+ the DB yourself).
+
+**Verify:**
+```bash
+# 1. Structural check — the new definition has the branch and kept the July-13 logic:
+psql "$SUPABASE_DB_URL_LOCAL" -c "SELECT pg_get_functiondef('complete_job_to_inventory(text,numeric,text,text,text,text)'::regprocedure);" | grep -cE "Non-Inventory|costOfGoodsSoldAccount|overheadRate|rawMaterialsAccount"
+# Expected: >= 4 lines matched (all four markers present: the new branch AND the preserved
+# overhead + RM/FG logic). Get the local DB URL from .env.local (SUPABASE_DB_URL / PORT_DB).
+
+# 2. Idempotency — re-apply the file over the applied state:
+psql "$SUPABASE_DB_URL_LOCAL" -v ON_ERROR_STOP=1 -f packages/database/supabase/migrations/<timestamp>_service-job-completion-cogs.sql
+# Expected: exit 0 (DROP IF EXISTS + CREATE OR REPLACE is safely re-runnable).
+
+# 3. Rolled-back behavioral validation (the memory-approved pattern: BEGIN/asserts/ROLLBACK as
+# supabase_admin). Write a scratch script .ai/scratch/validate-service-completion.sql that:
+# BEGIN;
+# -- fixture: pick an existing company with accountingEnabled=true (or set it),
+# -- one Non-Inventory item (a Service) + one Inventory 'Make' item (a Part),
+# -- insert a job + jobMakeMethod row for each, insert one posted WIP journalLine
+# -- (accountId = accountDefault."workInProgressAccount", documentId = job id, amount 100);
+# -- run: SELECT complete_job_to_inventory('<service-job>', 1, NULL, NULL, '<companyId>', '<userId>');
+# -- assert (each via SELECT ... ; \gset + \if or just visual DO $$ RAISE EXCEPTION):
+# -- A. journalLine exists: accountId = accountDefault."costOfGoodsSoldAccount",
+# -- amount = 100, documentType 'Job Receipt', documentId = <service-job>;
+# -- B. NO itemLedger row with documentId = <service-job>;
+# -- C. NO costLedger row with documentId = <service-job>;
+# -- run: SELECT complete_job_to_inventory('<part-job>', 1, NULL, '<locationId>', '<companyId>', '<userId>');
+# -- assert: D. journalLine debit hits accountDefault."finishedGoodsAccount" and an
+# -- itemLedger 'Assembly Output' row EXISTS for <part-job>;
+# ROLLBACK;
+# Expected: all asserts pass, transaction rolls back leaving no residue.
+```
+
+**Out of scope:** Do NOT touch `backflush_job_materials`, `close-job`, `post-shipment`, or any
+applied migration file (everything on main is applied — fix forward only). Do NOT add
+rev-rec columns/enums (spec OQ-2). If the fork source file's content differs from the line
+references above (e.g. the branch has moved on), STOP and report — do not improvise the merge.
+
+---
+
+## Task 2: Confirm generated types are unaffected (do NOT regenerate)
+
+**Depends on:** Task 1
+**Files:**
+- None modified. (Guard task.)
+
+**Steps:**
+1. The migration redefines one SQL function with an UNCHANGED signature and touches no
+ table/column/enum, so `packages/database/src/types.ts` needs no change.
+2. Per the types-are-cloud-generated rule (grounding notes), do NOT run `pnpm run generate:types`
+ and commit its output — it would produce a huge wrong diff from the local DB.
+
+**Verify:**
+```bash
+git status --porcelain packages/database/src/types.ts
+# Expected: empty output (file untouched).
+grep -n "complete_job_to_inventory" packages/database/src/types.ts | head -2
+# Expected: the existing RPC entry with Args p_job_id/p_quantity_complete/... — unchanged.
+```
+
+**Out of scope:** Committing any regenerated types.ts.
+
+---
+
+## Task 3: Harden `convertSalesOrderLinesToJobs` for service lines
+
+**Depends on:** none (parallel with Tasks 1, 4)
+**Files:**
+- Modify: `apps/erp/app/modules/production/production.service.ts` — `convertSalesOrderLinesToJobs`
+ (function starts at line 85; the loop body at lines 138–221)
+
+**Steps:**
+1. At lines 140–145, change the `itemReplenishment` read from `.single()` to `.maybeSingle()`
+ (services get an auto-created row via the item interceptor, but with `.single()` any
+ future missing-row case surfaces as an unchecked error object; `.maybeSingle()` states the
+ intent and matches `insertJob`'s own read at line ~2673). The existing
+ `manufacturing.data?.lotSize ?? 0` / `?.scrapPercentage ?? 0` / `?.leadTime ?? 7` defaults
+ already handle NULLs — leave them.
+2. Guard the storage-unit resolution (lines 190–195): services are Non-Inventory and never have
+ storage units. Replace with:
+ ```ts
+ const storageUnitId =
+ line.salesOrderLineType === "Service"
+ ? null
+ : await getDefaultStorageUnitForJob(client, line.itemId, locationId!, companyId);
+ ```
+ (`salesOrderLineType` mirrors the item's type on the `salesOrderLines` view; a Service item's
+ line carries `"Service"`.)
+3. Make no other changes to the function — the `methodType === "Make to Order"` filter (line 139),
+ lot-splitting, priority, `get-method` invocation, and `recalculate` calls are correct for
+ services as-is.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exits 0, "Tasks: 1 successful" (or cached equivalents); no new type errors.
+```
+
+**Out of scope:** `insertJob` (already uses `maybeSingle`), the per-line `$orderId.$lineId.job.tsx`
+route, scrap logic for inventory items, and any UI file.
+
+---
+
+## Task 4: Fulfillment helper — service job completion advances the sales-order line
+
+**Depends on:** none (parallel with Tasks 1, 3)
+**Files:**
+- Modify: `apps/erp/app/modules/production/production.service.ts` — add `advanceServiceLineFulfillment`
+- Modify: `apps/erp/app/routes/x+/job+/$jobId.complete.tsx` — call it after the RPC succeeds
+- Copy from (precedent for the update shape): `packages/database/supabase/functions/post-shipment/index.ts`
+ lines 494–546 (`quantitySent` accumulate → `sentComplete` → `sentDate` only when newly complete)
+
+**Steps:**
+1. In `production.service.ts`, add (near `insertJob`, keeping one service file per module):
+ ```ts
+ /**
+ * Services never ship, so job completion is the fulfillment event: advance the
+ * linked sales-order line the way post-shipment does for physical lines.
+ * Recomputes quantitySent from ALL jobs on the line (idempotent; supports
+ * multiple lot-split jobs and repeated completions).
+ */
+ export async function advanceServiceLineFulfillment(
+ client: SupabaseClient<Database>,
+ {
+ jobId,
+ companyId,
+ userId
+ }: { jobId: string; companyId: string; userId: string }
+ ) {
+ const job = await client
+ .from("job")
+ .select("id, itemId, salesOrderLineId, quantityComplete")
+ .eq("id", jobId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ if (job.error || !job.data?.salesOrderLineId || !job.data.itemId) {
+ return { data: null, error: job.error };
+ }
+
+ const item = await client
+ .from("item")
+ .select("itemTrackingType")
+ .eq("id", job.data.itemId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ if (item.error || item.data?.itemTrackingType !== "Non-Inventory") {
+ return { data: null, error: item.error };
+ }
+
+ const [line, jobs] = await Promise.all([
+ client
+ .from("salesOrderLine")
+ .select("id, saleQuantity, quantitySent, sentComplete, sentDate")
+ .eq("id", job.data.salesOrderLineId)
+ .eq("companyId", companyId)
+ .single(),
+ client
+ .from("job")
+ .select("quantityComplete")
+ .eq("salesOrderLineId", job.data.salesOrderLineId)
+ .eq("companyId", companyId)
+ ]);
+ if (line.error) return line;
+ if (jobs.error) return jobs;
+
+ const quantitySent = (jobs.data ?? []).reduce(
+ (sum, j) => sum + (j.quantityComplete ?? 0),
+ 0
+ );
+ const saleQuantity = line.data.saleQuantity ?? 0;
+ const sentComplete = saleQuantity > 0 && quantitySent >= saleQuantity;
+
+ return client
+ .from("salesOrderLine")
+ .update({
+ quantitySent,
+ sentComplete,
+ ...(sentComplete && !line.data.sentDate
+ ? { sentDate: today(getLocalTimeZone()).toString() }
+ : {}),
+ updatedBy: userId,
+ updatedAt: today(getLocalTimeZone()).toString()
+ })
+ .eq("id", line.data.id)
+ .eq("companyId", companyId)
+ .select("id")
+ .single();
+ }
+ ```
+ `today`/`getLocalTimeZone` are already imported in `production.service.ts` from
+ `@internationalized/date` (used by `insertJob`'s date math via `parseDate`; add
+ `today, getLocalTimeZone` to that import if not present).
+2. In `$jobId.complete.tsx`, after the successful RPC (line 56, before the success redirect):
+ ```ts
+ const fulfillment = await advanceServiceLineFulfillment(client, {
+ jobId,
+ companyId,
+ userId
+ });
+ if (fulfillment.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.job(jobId),
+ await flash(
+ request,
+ error(
+ fulfillment.error,
+ "Job completed, but failed to update the sales order line"
+ )
+ )
+ );
+ }
+ ```
+ Import `advanceServiceLineFulfillment` from `~/modules/production`.
+3. Confirm the export flows through the module barrel (`apps/erp/app/modules/production/index.ts`
+ re-exports `./production.service` — verify, add if missing).
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exits 0; no new type errors.
+grep -n "advanceServiceLineFulfillment" apps/erp/app/routes/x+/job+/\$jobId.complete.tsx apps/erp/app/modules/production/production.service.ts
+# Expected: definition in production.service.ts + one call site in the route.
+```
+
+**Out of scope:** Do NOT write `job.quantityShipped` (the route's comment at lines 36–41 explains
+why — it zeroes the shipment builder for physical jobs). Do NOT touch `post-shipment`. Do NOT
+advance fulfillment for Inventory items (shipments own that).
+
+---
+
+## Task 5: Validation gates — lint + scoped typecheck
+
+**Depends on:** Tasks 3, 4
+**Files:** none (gate)
+
+**Steps:**
+1. Run the repo lint and the scoped typecheck.
+
+**Verify:**
+```bash
+pnpm run lint
+# Expected: exits 0 (Biome; no new errors — warnings pre-existing on the branch are acceptable).
+pnpm exec turbo run typecheck --filter=erp
+# Expected: exits 0.
+```
+
+**Out of scope:** whole-repo typecheck (OOMs — never run `tsc --noEmit` at the root),
+`pnpm run build`, unit-test suites (no unit-testable surface changed; the SQL behavior is
+covered by Task 1's rolled-back validation and Task 6's e2e).
+
+---
+
+## Task 6: Browser e2e — full service MTO flow with GL/psql assertions
+
+**Depends on:** Tasks 1–5 (migration applied locally, code in tree)
+**Files:** none (verification; playbook may be cached to `.ai/playbooks/` by /test)
+
+**Steps:**
+1. Ensure the local stack is up: `crbn up` (plain, portless — the app lands on `erp.<worktree>.dev`).
+ If the stack cannot boot, the task is BLOCKED, not done — report it.
+2. Enable accounting for the dev company if disabled: log in (use the `/auth` skill), visit
+ `/x/settings/accounting`, toggle accounting on. (Fresh/reset stacks seed it off; without it no
+ journals post and every GL assert fails vacuously.)
+3. Invoke the `/test` skill with this scenario (it uses agent-browser; RVF forms submit via
+ `requestSubmit`, blur react-aria number fields to commit values):
+ a. Create a work center with `laborRate > 0` (or reuse an existing one that has a rate).
+ b. Create a new **Service** item with Replenishment = **Make** (verify the form shows
+ `defaultMethodType` locked to Make to Order). On its Details page add one BOM routing
+ operation using that work center.
+ c. Create a sales order for any customer; add a line with type **Service** selecting the new
+ item; verify the line's Method shows **Make to Order** and save.
+ d. On the order summary, click **Create Jobs** (or use the line-detail "Make to Order" button);
+ verify a job is created and linked to the line without an error toast.
+ e. Open the job, release it, and record a production event (labor time) against its operation
+ so the job accumulates WIP cost.
+ f. Complete the job (quantity = the line quantity).
+ g. Verify in the UI: the job shows Completed; the sales order line shows fulfilled/delivered
+ state; the sales order is not blocked from invoicing.
+4. Assert the GL + ledger state via psql (get the DB URL/port from `.env.local`):
+ ```sql
+ -- the job id:
+ SELECT id FROM "job" WHERE "jobId" = '<readable job id from UI>';
+ -- A. WIP accumulated from the labor event (Dr WIP, documentId = job id):
+ SELECT COUNT(*) FROM "journalLine" WHERE "documentId" = '<job id>' AND amount > 0 AND description LIKE 'WIP%';
+ -- Expected: >= 1
+ -- B. Completion posted Dr COGS / Cr WIP and NOT Finished Goods:
+ SELECT jl.description, jl.amount FROM "journalLine" jl WHERE jl."documentId" = '<job id>' AND jl."documentType" = 'Job Receipt';
+ -- Expected: exactly two rows — 'Cost of Goods Sold' (+N) and 'WIP Account' (−N); NO 'Finished Goods Account' row.
+ -- C. No inventory artifacts:
+ SELECT COUNT(*) FROM "itemLedger" WHERE "documentId" = '<job id>'; -- Expected: 0
+ SELECT COUNT(*) FROM "costLedger" WHERE "documentId" = '<job id>'; -- Expected: 0
+ -- D. Line fulfillment advanced:
+ SELECT "quantitySent", "sentComplete", "sentDate" FROM "salesOrderLine" WHERE id = '<line id>';
+ -- Expected: quantitySent = completed qty, sentComplete = true, sentDate = today.
+ ```
+5. **Regression guard (Parts still post to Finished Goods):** complete a Make-to-Order **Part**
+ job (create a minimal Part + SO line + job the same way, or reuse an existing draft job in the
+ seed data), then:
+ ```sql
+ SELECT jl.description FROM "journalLine" jl WHERE jl."documentId" = '<part job id>' AND jl."documentType" = 'Job Receipt';
+ -- Expected: 'Finished Goods Account' (+) and 'WIP Account' (−).
+ SELECT COUNT(*) FROM "itemLedger" WHERE "documentId" = '<part job id>' AND "entryType" = 'Assembly Output';
+ -- Expected: 1 (or the tracked-entity count for batch/serial items).
+ ```
+6. Capture screenshots of: the service line's Jobs card, the completed job, the fulfilled SO line
+ (for the PR per the surface-designs-with-screenshots convention).
+
+**Verify:**
+```bash
+# The /test run's transcript + the psql outputs above ARE the verification.
+# Expected: every assert in steps 4–5 matches; screenshots saved.
+```
+
+**Out of scope:** invoicing/AR assertions beyond "not blocked" (revenue posting is unchanged),
+MES flows, performance, and any cleanup migration for pre-fix phantom FG rows (documented
+limitation in the spec).
diff --git a/.ai/research/service-make-to-order-jobs.md b/.ai/research/service-make-to-order-jobs.md
new file mode 100644
index 0000000000..ddf4d22e8f
--- /dev/null
+++ b/.ai/research/service-make-to-order-jobs.md
@@ -0,0 +1,297 @@
+# Service Make-to-Order Jobs Research: Best Practices Survey
+
+## Summary
+
+How should a **made-to-order service** — sold on a sales order line, produced by a
+job, but never stocked as a finished good — be fulfilled and posted to the GL?
+Surveyed SAP S/4HANA, Oracle NetSuite, Epicor Kinetic, Microsoft Dynamics 365
+Business Central, and Odoo, plus standard cost-accounting references. **Consensus is
+unambiguous: a service output is never a finished-goods inventory asset, so its cost
+flows WIP → COGS directly (or is expensed on delivery) with no Finished-Goods leg and
+no inventory shipment.** The cleanest fit for Carbon (which already has a job/WIP model
+and a shipment-posting step) is **Epicor's "Make Direct" pattern**: keep the job and
+its WIP accumulation, but relieve **WIP → COGS at fulfillment with no stock movement**;
+mark the sales line fulfilled by job/service completion rather than a goods issue; sweep
+any residual WIP to a variance account at job close. Revenue-recognition timing reduces
+to a small enum (completed-contract / percent-of-completion / as-billed), not a config
+matrix. In-house vs subcontracted service differ only at the *cost origin* (internal
+labor absorption vs a vendor bill), never in the downstream WIP→COGS treatment.
+
+## Competitors Surveyed
+
+- **SAP S/4HANA** — enterprise reference for cost-object controlling, WIP, results
+ analysis / event-based revenue recognition, and resource-related billing of services.
+- **Oracle NetSuite** — clearest item-type model (Service vs Inventory/Assembly) and the
+ "services bill directly, no fulfillment, no COGS from the item" pattern; steers
+ cost-matched service deliverables to Projects/job costing.
+- **Epicor Kinetic** — the "Make Direct" make-to-order pattern that ships a job straight
+ from WIP to COGS with no inventory leg — the closest match to Carbon's existing model.
+- **Microsoft Dynamics 365 Business Central** — item types (Inventory / Non-Inventory /
+ Service) and the Projects (Jobs) WIP-recognition engine (five WIP methods).
+- **Odoo** — service product fulfillment via timesheets/milestones + invoicing policy
+ (ordered vs delivered); no WIP for services; subcontracting-as-purchase contrast.
+
+## Key Consensus Patterns
+
+### 1. A service output is never a finished-goods inventory asset
+
+- **SAP**: made-to-order services use **non-valuated sales-order stock** — *no* GL posting
+ at "receipt to stock" and *no* goods issue; the order/WBS is the cost object and cost
+ settles WIP → COGS.
+- **NetSuite**: a Service-for-sale item carries **only an Income account** (plus optional
+ Deferred Revenue) — **no Asset and no COGS account**. A work order/assembly build *must*
+ land its completion in an inventory Asset account, so a WO literally **cannot output a
+ service**.
+- **BC**: Non-Inventory and Service item types track **no inventory**, post **no COGS
+ offset**, and create **no shipment**; Production Orders require inventory items.
+- **Epicor**: a service is a **non-stock part + job**; shipping relieves **WIP, not
+ on-hand**.
+- **Odoo**: Service products generate **no stock moves**; MRP does not "produce" a service.
+- **Rationale**: you can only capitalize an asset you can measure and hold. A delivered
+ service has no unit of stock to value, so there is nothing to sit in Finished Goods —
+ cost is matched to revenue directly as WIP → COGS (or expensed on delivery).
+
+### 2. Fulfillment is decoupled from inventory shipment
+
+- **Epicor**: a **customer shipment document (packing slip) still exists**, but it relieves
+ **WIP instead of inventory** and posts a single **MFG-CUS (WIP → COGS)** entry. This is
+ the "make-to-order direct-to-COGS" pattern.
+- **NetSuite/BC**: service lines are flagged **not fulfillable** and are **billed directly
+ off the order** — invoice alone completes the line, no fulfillment record.
+- **Odoo**: the SO line's **delivered quantity** is driven by **timesheets / milestones /
+ manual**, never a delivery order.
+- **SAP**: no goods issue; billability is driven by **order status (TECO/complete) +
+ accumulated cost**, invoiced via **Resource-Related Billing** (actuals) or **milestone
+ billing** (fixed price).
+- **Rationale**: "fulfilled" for a service means *the work was performed*, signalled by
+ job/service completion — not a stock movement.
+
+### 3. Cost flows WIP → COGS (job/WIP is the only "inventory" a service has)
+
+- **Job/WO WIP** accumulates labor + overhead (+ any consumed materials).
+- On completion/fulfillment, **WIP is relieved directly to COGS** (Epicor MFG-CUS; SAP
+ settlement on non-valuated stock; BC Recognized Cost via Calculate WIP).
+- **NetSuite** takes the alternate route: no item-level WIP for services — cost is
+ accumulated on a **Project (job costing)** container instead, recognized by a billing
+ schedule. The project *is* the WIP container.
+
+### 4. Revenue recognition timing is a small enum, not a matrix
+
+Every system exposes the same three shapes:
+- **Completed contract** — recognize cost + revenue at completion (SAP RA method 15; BC
+ Completed Contract).
+- **Percentage-of-completion (cost-based)** — recognize proportional to cost incurred vs
+ budget (SAP method 03; BC Percentage of Completion).
+- **As-billed / T&M** — recognize as invoiced; billing itself is the progress measure (SAP
+ method 07 / resource-related billing; NetSuite T&M; BC Cost Value / Sales Value; Odoo
+ "invoice what is delivered").
+- The balance-sheet plug between recognized revenue and billed amount is **unbilled
+ receivable** (cost/revenue > billed) or **deferred revenue** (billed > earned).
+
+### 5. No standard finished-good cost ⇒ no production variance; sweep residual WIP
+
+- **SAP**: non-valuated stock has no material-master standard, so there is **no
+ target-vs-actual production variance** — profit/loss is simply recognized revenue minus
+ recognized actual cost in CO-PA.
+- **Epicor**: at job close, **Capture COS/WIP** marks the job WIP-cleared and **purges any
+ residual WIP to a manufacturing variance (MFG-VAR)** account.
+- **Rationale**: a service job's "variance" is just leftover WIP that never became COGS; it
+ must be swept to a variance/adjustment account so WIP ties out.
+
+### 6. In-house vs subcontracted service differ only at the cost origin
+
+- **In-house labor**: internal **activity absorption** — confirmed hours × labor rate
+ debit the job/WIP; the offset **credits a labor/cost-center account** (SAP secondary cost
+ element; no vendor, no AP). Odoo routes this to an **analytic account** via timesheets.
+- **Subcontracted / outside processing**: a **purchased service** — a **PO → receipt/service
+ entry → vendor bill (three-way match)** debits the job/WIP, credits **GR/IR clearing**
+ then **AP**. (SAP external-service PO item category D / ML81N; SyteLine "receipt posts the
+ vendor's processing cost to the job's WIP"; D365 "subcontracted cost is the purchase
+ price of the service").
+- **Both** land in the same job/WIP bucket and flow **WIP → COGS** for a service output.
+ The three-way match to AP is the *tell* for subcontracting; time entry with an applied
+ rate is the tell for in-house.
+
+## Answers to Research Questions
+
+1. **How is an MTO service SO line marked fulfilled with no inventory shipment?** — By
+ **job/service completion**, not a goods issue. Epicor keeps a *shipment document* that
+ relieves WIP (not stock); NetSuite/BC **bill the line directly** (no fulfillment record);
+ Odoo sets **delivered qty from timesheets/milestones**; SAP bills from **accumulated
+ cost + TECO status** via resource-related billing. All four avoid an inventory movement.
+
+2. **Does service-job WIP go WIP → COGS directly, or WIP → deferred/service asset → COGS at
+ invoice?** — **WIP → COGS directly**, with **no Finished-Goods / service-inventory asset
+ leg** (Epicor MFG-CUS; SAP settlement on non-valuated stock; BC Recognized Cost).
+ Deferral, when used, is a **revenue-recognition** choice (deferred *revenue*), not a
+ deferred *cost asset*. NetSuite's variant keeps cost on a **Project** container rather
+ than item WIP, but still never creates a finished-good asset.
+
+3. **Revenue recognition timing for MTO services?** — Configurable per line/contract:
+ **completed-contract** (on completion), **percent-of-completion** (cost-based), or
+ **as-billed/T&M**. Default for a simple shop: recognize at completion / on invoice.
+
+4. **Variance treatment with no standard finished-good cost?** — There is **no production
+ variance** in the standard-cost sense; instead, **residual WIP at job close is swept to a
+ variance/adjustment account** (Epicor Capture COS/WIP → MFG-VAR). Margin = recognized
+ revenue − recognized actual cost.
+
+5. **How are service/non-stock work orders closed vs physical ones?** — Same WIP
+ accumulation, but the **completion posts WIP → COGS instead of WIP → Finished Goods**,
+ and closing sweeps leftover WIP to variance rather than reconciling to a stocked
+ standard cost. No receipt-to-inventory step.
+
+6. **Where does accounting differ for subcontracted vs in-house service?** — Only at the
+ **cost origin**: subcontracted = **vendor bill via PO/receipt/3-way match → GR/IR → AP**;
+ in-house = **internal labor absorption at a rate (no AP document)**. Downstream WIP→COGS
+ is identical, so model **one WIP path with two cost sources**.
+
+## Competitor-Specific Details
+
+### SAP S/4HANA
+- Cost object = service order / WBS / **sales order with account-assignment category E**
+ (sales-order controlling on) and **non-valuated stock** (no FG postings).
+- **Resource-Related Billing (RRB)** via a **DIP profile** turns accumulated actual cost
+ into a billing request (`DP90/DP91`) — bill from actuals, no delivery.
+- **Results Analysis (classic)** or **Event-Based Revenue Recognition (S/4HANA, real-time,
+ posts WIP/COGS/deferred revenue at each source document)** — EBRR is the simpler model to
+ emulate.
+- In-house labor = **activity confirmation** (secondary cost element credits cost center,
+ debits order). External service = **service PO (item cat D) + ML81N service entry** (Dr
+ expense/order, Cr GR/IR).
+
+### Oracle NetSuite
+- **Service for sale** item = **Income account only**; no Asset/COGS. Set **"Can Be
+ Fulfilled/Received" = off** → line **skips fulfillment, bills directly** (DR AR / CR
+ Income; CR Deferred Revenue if ARM on).
+- A **Work Order builds an assembly into inventory** — it **cannot output a service**.
+- Made-to-order services with cost-vs-revenue matching go to **Projects / job costing**:
+ costs accumulate on the job; revenue via billing schedule (T&M, milestone/%-complete,
+ fixed interval, charge rules). The project *is* the WIP container.
+
+### Epicor Kinetic ← closest to Carbon
+- **Make Direct** = demand link from an SO release to a job; ships **straight from WIP**,
+ no stock. Auto-triggered for **non-stock parts** / engineered-from-quote parts, or a
+ manual "Make Direct" checkbox.
+- Shipment posts **MFG-CUS: WIP → COGS** (no Finished Goods). Fulfillment is still a
+ **customer shipment / packing slip**, just with **no inventory relief**.
+- **Capture COS/WIP** batch closes jobs and **purges residual WIP to MFG-VAR**.
+- Edge cases to design for: **partial-shipment** cost can strand in WIP; **zero-dollar
+ MFG-CUS posts no GL**.
+- Minimal account set: **WIP, COGS, Sales, Variance/Adjustment**.
+
+### Dynamics 365 Business Central
+- Item **Type**: Inventory / Non-Inventory / Service. Non-Inventory & Service post **no
+ COGS offset, no shipment**; invoice alone books revenue.
+- Production Orders need inventory items; service/made-to-order deliverables go to
+ **Projects (Jobs)** with a **WIP engine**: five methods (Cost Value, Cost of Sales, Sales
+ Value, Percentage of Completion, Completed Contract) posting **WIP Costs → Recognized
+ Costs** and **WIP Sales → Recognized Sales** via the Calculate WIP batch. Only needed if
+ you want deferred/percent-complete recognition; a simple ship-to-COGS service doesn't.
+
+### Odoo
+- **Service** product + invoicing policy (**Ordered / Delivered / Timesheets /
+ Milestones**). Timesheets on the linked project task drive **delivered qty**; **no WIP**
+ for services — cost/revenue tracked via **analytic accounting** (project profitability).
+- **Subcontracting** = a **BoM of type "Subcontracting"** + subcontractor-as-vendor; it's a
+ **purchase flow** (PO → receipt → vendor bill), and the output is a **storable good** (so
+ *that* gets a FG leg) — distinct from selling a bare service.
+
+## Recommended Approach for Carbon
+
+Carbon already models jobs with real WIP and posts a Make-to-Order job as
+**WIP → Finished Goods → COGS on shipment**. The service path should reuse that machinery
+minus the inventory legs — i.e., **adopt Epicor's "Make Direct" pattern**:
+
+1. **Keep the job as the cost object.** A service MTO line still creates a job that
+ accumulates **labor + overhead (+ any consumed materials)** as WIP, exactly like a
+ physical job. This is what the user wants ("create a service job"), and it preserves
+ job costing.
+
+2. **Fulfill by completion, not by goods issue.** Mark the sales order line fulfilled when
+ the **service job completes** (or via a lightweight "service completion" analogous to a
+ shipment with **no inventory movement**). Do **not** post a finished-goods receipt and do
+ **not** relieve on-hand inventory. (Mirrors the branch's existing decision to hide
+ Shipments for service SO lines.)
+
+3. **Post WIP → COGS directly at fulfillment/completion.** Replace the
+ **WIP → Finished Goods → COGS-on-shipment** chain with a single **WIP → COGS** relief for
+ service jobs. No Finished-Goods (or Raw-Materials-as-FG) account is touched. This is the
+ only accounting change of real substance and is the crux of the user's "accounting
+ transactions will need work" instinct.
+
+4. **Recognize revenue on the sales invoice** as today (DR AR / CR service revenue). Start
+ with the simplest timing — **recognize at completion / on invoice** — and leave
+ percent-of-completion / deferred revenue as a future enhancement (the small enum from
+ Pattern 4). A service item should carry a **revenue account** and a **COGS account** but
+ **no inventory/asset account** (NetSuite's rule).
+
+5. **Sweep residual WIP to a variance/adjustment account at job close.** Reuse Carbon's
+ existing manufacturing-variance handling; there is **no standard-cost production variance**
+ for services, so leftover WIP (over/under-absorbed labor/overhead) is booked to variance
+ — don't try to reconcile it to a stocked standard cost.
+
+6. **One WIP path, two cost sources.** In-house labor (production events / activity at a
+ labor rate) and subcontracted/outside operations (PO receipt → vendor bill) both debit
+ the same job WIP — Carbon already supports outside operations on jobs, so no new branch
+ is needed beyond ensuring both feed the service job's WIP and then WIP → COGS.
+
+**What to explicitly *not* build:** a finished-goods/service-inventory asset leg, an
+inventory shipment/goods-issue for services, or a standard-cost variance against a
+non-existent stocked cost. **Deferred-cost assets are out** — deferral, if ever added, is a
+revenue-recognition concern (deferred *revenue*), not a cost asset.
+
+**Open questions to carry into the spec** (`/spec-writing`):
+- Is fulfillment marked by **job completion** directly, or by a distinct **service-completion
+ document** (Epicor keeps a shipment doc; NetSuite/BC bill directly)? Recommend: job
+ completion drives line fulfillment, no separate doc.
+- Does the service item require a **COGS account** (job/WIP path, recommended) or should a
+ pure service **bill directly with no COGS** (NetSuite simplest path)? The user's "create a
+ service job" framing points to the **WIP → COGS job path**.
+- **Revenue timing**: completion/on-invoice only for v1 (recommended), or expose the
+ percent-of-completion enum now?
+- Does Carbon post service **labor to WIP in real time** (production events) or only settle
+ at completion? Recommend: accumulate as events post (matches physical jobs), relieve to
+ COGS at completion.
+
+## Sources
+
+**SAP**
+- https://sapinsider.org/make-to-order-wip-and-cost-of-sales-you-have-three-not-two/
+- https://learning.sap.com/courses/project-financials-control-in-sap-s-4hana/performing-resource-related-billing
+- https://learning.sap.com/courses/cost-object-controlling-in-sap-s-4hana/calculating-work-in-process-wip
+- https://help.sap.com/docs/SAP_S4HANA_ON-PREMISE/c9b5e9de6e674fb99fff88d72c352291/ec1c1e42ce614499a93790c213fbecab.html
+- https://community.sap.com/t5/enterprise-resource-planning-blog-posts-by-sap/cost-of-goods-sold-split-in-make-to-order-scenario-mto-with-sap-s-4hana/ba-p/13475148
+- https://community.sap.com/t5/financial-management-blog-posts-by-sap/supported-revenue-recognition-methods-in-sap-s-4hana-service-including-sap/ba-p/14248039
+- https://help.sap.com/docs/SAP_S4HANA_CLOUD/89d896ca9cd64318b1667df5ec00e4b2/7fd9ad1108b94403a2871cf348d4b891.html (Event-Based Revenue Recognition)
+- https://community.sap.com/t5/supply-chain-management-blog-posts-by-members/the-ultimate-guide-to-subcontracting-in-sap-s-4hana/ba-p/14223371
+
+**NetSuite**
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_1536275392.html (Items for Revenue and Expense)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2172688.html (Account Information about Items)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/chapter_N2328390.html (Assembly Work Orders)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2337938.html (Using WIP on Work Orders)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N1204906.html (Project Billing)
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/chapter_N1678106.html (Using Revenue Recognition)
+
+**Epicor**
+- https://www.epiusers.help/t/is-it-ok-to-receive-a-make-to-order-job-to-inventory/132874
+- https://www.epiusers.help/t/possible-reasons-for-make-direct/124197
+- https://www.epiusers.help/t/make-direct-and-shipping-from-inventory/59242
+- https://www.epiusers.help/t/packing-slip-from-shipment-did-not-trigger-wip-release-to-cogs/68707
+- https://scaledsolutionsgroup.com/how-to-use-epicor-kinetic-for-accurate-job-costing-and-margin-analysis/
+
+**Dynamics 365 Business Central**
+- https://learn.microsoft.com/en-us/dynamics365/business-central/projects-understanding-wip
+- https://learn.microsoft.com/en-us/dynamics365/business-central/inventory-about-item-types
+- https://learn.microsoft.com/en-ca/dynamics365/business-central/walkthrough-calculating-work-in-process-for-a-job
+
+**Odoo + industry accounting**
+- https://www.odoo.com/documentation/18.0/applications/sales/sales/invoicing/invoicing_policy.html
+- https://www.odoo.com/documentation/18.0/applications/sales/sales/invoicing/time_materials.html
+- https://www.odoo.com/documentation/18.0/applications/inventory_and_mrp/inventory/warehouses_storage/replenishment/mto.html
+- https://www.odoo.com/documentation/18.0/applications/inventory_and_mrp/manufacturing/subcontracting.html
+- https://learn.microsoft.com/en-us/dynamics365/supply-chain/production-control/manage-subcontract-work-production
+- https://www.netray.co/resources/how-to-configure-syteline-outside-processing
+- https://www.accountingtools.com/articles/work-in-process-accounting
+- https://accountingforeveryone.com/explain-the-revenue-recognition-and-matching-principle/
diff --git a/.ai/specs/2026-07-13-raw-materials-finished-goods-accounts.md b/.ai/specs/2026-07-13-raw-materials-finished-goods-accounts.md
index 2c6fce8e1a..2e781121e2 100644
--- a/.ai/specs/2026-07-13-raw-materials-finished-goods-accounts.md
+++ b/.ai/specs/2026-07-13-raw-materials-finished-goods-accounts.md
@@ -55,6 +55,7 @@ Unchanged branches: Non-Inventory → `indirectCostAccount`; outside processing
| Purchase invoice (Inventory item, no receipt) | RM or FG by item rule | Payables |
| Material issue / backflush | WIP | RM or FG by consumed item (Make subassembly credits FG) |
| Job completion | RM or FG by job item (normally FG) | WIP |
+| Job completion (Non-Inventory item, e.g. Service) | COGS — no inventory leg, no itemLedger/costLedger (see `2026-07-14-service-make-to-order-jobs.md`, migration `20260714043017`) | WIP |
| Shipment | COGS | RM or FG by shipped item |
| Sales invoice (no prior shipment) | COGS | RM or FG by invoiced item |
diff --git a/.ai/specs/2026-07-14-service-make-to-order-jobs.md b/.ai/specs/2026-07-14-service-make-to-order-jobs.md
new file mode 100644
index 0000000000..6184d17796
--- /dev/null
+++ b/.ai/specs/2026-07-14-service-make-to-order-jobs.md
@@ -0,0 +1,182 @@
+# Service Make-to-Order Jobs
+
+> Status: implemented (on feat/service; move to implemented/ after merge)
+> Author: Claude (with Brad Barbin)
+> Date: 2026-07-14
+> Branch: feat/service
+> Research: `.ai/research/service-make-to-order-jobs.md`
+> Related: `.ai/specs/2026-07-04-revenue-recognition.md` (issue #1048 — the incoming rev-rec workstream this spec leaves seams for), `.ai/specs/2026-07-13-raw-materials-finished-goods-accounts.md` (the account split whose latest `complete_job_to_inventory` this spec forks)
+
+## TLDR
+
+Let a **Service** item (now a first-class item type, `itemTrackingType = 'Non-Inventory'`) be sold Make-to-Order on a sales order line and produced by a job — with accounting that reflects that a service is never stocked and never shipped from inventory. Adopting the Epicor "Make Direct" pattern from research, a service job accumulates labor + overhead (+ any consumed materials) as **WIP exactly like a physical job** (already true — `issue` and `post-production-event` post to `workInProgressAccount` keyed by `documentId = jobId`, with no item-type branch), but on **job completion** its cost posts **`Dr costOfGoodsSoldAccount` / `Cr workInProgressAccount` directly — no Finished-Goods leg, no `itemLedger`/`costLedger`, no on-hand quantity** — and the linked sales-order line is marked **fulfilled by completion**, not by a shipment. **This COGS diversion applies only to Non-Inventory items (Services); every inventory-tracked item — including a `Make` Part — still completes to the Finished Goods account exactly as it does today.** The change is strictly additive to a new branch; the inventory path is byte-identical to the current definition. The core accounting change is a one-function migration that **restores a Non-Inventory branch to `complete_job_to_inventory`** that previously existed (`20260707022142`) but was silently dropped when the July‑13 raw-materials/FG and overhead migrations forked from an older baseline — so today a service job completion wrongly posts `Dr Finished Goods / Cr WIP` and creates phantom finished-goods inventory. The sales/methodType side already mostly works (a `Make` service defaults to `defaultMethodType = 'Make to Order'`, auto-gets a `makeMethod`, and the Jobs card renders); the remaining plumbing is making the job-*creation* body service-aware (it currently `.single()`s `itemReplenishment`, which services lack). GL accounts resolve from the existing **company-level `accountDefault`** (no per-item accounts); revenue posts on the sales invoice as today. **No new tables, columns, or enums** — the spec is a completion-posting fix + fulfillment hook + job-creation hardening, deliberately leaving revenue-recognition schema to spec #1048 and only preserving the seams it needs (the WIP-by-`jobId` subledger and a single interceptable COGS-at-completion branch).
+
+## Problem Statement
+
+A Service is now a first-class item type on `feat/service` (`serviceReplenishmentSystems = ['Buy','Make']`, `itemTrackingType = 'Non-Inventory'`, auto-created `makeMethod`, BOM+routing UI). Selling one Make-to-Order and producing it is *partially* wired but broken in three places:
+
+1. **Job creation breaks for services.** `convertSalesOrderLinesToJobs` (`apps/erp/app/modules/production/production.service.ts:139`) filters correctly on `methodType === "Make to Order"` (no item-type exclusion), and a `Make` service line inherits that methodType from `item.defaultMethodType`. But the loop body is inventory-shaped: it does `.single()` on `itemReplenishment` (`production.service.ts:140-145`) — a row `upsertService` never creates — and resolves a storage unit / scrap %, all inventory concepts. So the bulk "Create Jobs" affordance (`SalesOrderSummary.tsx:126-167`, gated on `hasMakeItems`) picks up a service line and then errors or misbehaves.
+
+2. **Service job completion posts the wrong journal (latent regression).** A Non-Inventory branch for `complete_job_to_inventory` existed in `20260707022142_complete-job-to-inventory-non-inventory.sql` — it posted `Dr costOfGoodsSoldAccount / Cr workInProgressAccount` and suppressed the `itemLedger` "Assembly Output" row, `pickMethod` update, `costLedger` "Output" layer, and `itemCost` update for Non-Inventory items. The two 2026-07-13 migrations (`…190909` raw-materials/FG split, `…222236` overhead-absorption fix) each `CREATE OR REPLACE`d `complete_job_to_inventory` **forked from the older `20260630092517` baseline** and silently dropped that branch. The current newest definition (`20260713222236`) has **zero** `Non-Inventory`/`itemTrackingType` references (verified by grep) — so a service job completion unconditionally debits Finished Goods and writes a phantom `itemLedger` "Assembly Output" row + `costLedger` "Output" layer + `itemCost` update. This misstates the balance sheet (WIP relieved into FG for a good that will never exist) and leaves orphan finished-goods on-hand.
+
+3. **Nothing marks a service SO line fulfilled.** `post-shipment` already excludes Non-Inventory from COGS (`post-shipment/index.ts:423`) and treats `salesOrderLineType === "Service"` as always-shipped for SO-status rollup (`:805-810`) — good, services don't block order completion and don't post shipment COGS. But since a service never enters the shipment builder, **no path advances the service SO line's own `quantitySent`/`sentComplete`/`sentDate`**, so the line never shows a truthful "delivered" state.
+
+What already works and must be preserved: WIP accumulation for a service job (`issue/index.ts:386-412` material → WIP; `post-production-event/index.ts:250-301` labor/machine/overhead → WIP), all keyed by `documentId = jobId` with no item-type branch; `close-job` (`close-job/index.ts:115-140`) sweeping residual WIP to `materialVarianceAccount`; the `get-method` `itemToJob` copy that builds the job's operations/materials from the service's make method (no item-type filter).
+
+## Proposed Solution
+
+Reuse Carbon's existing job/WIP machinery minus the inventory legs — Epicor "Make Direct" (research §Recommended Approach). Four surfaces change; none introduces a new table, column, or enum.
+
+### 1. Accounting — restore the Non-Inventory branch in `complete_job_to_inventory` (the core change)
+
+One forward migration redefines `complete_job_to_inventory`, **forked from the newest definition (`20260713222236`)** per the function-redefinition lesson (`DROP FUNCTION IF EXISTS` first, signature and all July‑13 overhead/RM logic preserved), re-adding the Non-Inventory branch from `20260707022142`:
+
+- Resolve `v_cogs_account := accountDefault."costOfGoodsSoldAccount"` alongside the existing RM/FG resolution.
+- When `item."itemTrackingType" = 'Non-Inventory'`:
+ - Post `Dr v_cogs_account / Cr workInProgressAccount` for `v_accumulated_wip_cost` (the same accumulated-WIP amount the FG path uses; `documentType 'Job Receipt'`, `documentLineReference = job:<id>`), **instead of** `Dr inventory / Cr WIP`.
+ - **Suppress** the `itemLedger` "Assembly Output" insert, the `pickMethod` update, the `costLedger` "Output" layer insert, and the `itemCost` update (all guarded `IF item."itemTrackingType" IS DISTINCT FROM 'Non-Inventory'`) — a service creates no on-hand quantity and no cost layer.
+- Inventory items are byte-identical to `20260713222236` (RM/FG CASE on `replenishmentSystem`, overhead absorption, itemLedger/costLedger unchanged).
+
+**Completion posting by item classification** (the only classifier is `itemTrackingType`, then `replenishmentSystem` for the inventory split — no per-item accounts, no matrix config):
+
+| Item at completion | `itemTrackingType` | Debit | Credit | itemLedger / costLedger / itemCost |
+|---|---|---|---|---|
+| `Make` Part / Material / Tool (stocked) | Inventory / Serial / Batch | **Finished Goods** (`finishedGoodsAccount`) | WIP | written (unchanged) |
+| `Buy` inventory item completed from a job (rare) | Inventory / Serial / Batch | Raw Materials (`rawMaterialsAccount`) | WIP | written (unchanged) |
+| **Service** (or any Non-Inventory item) | **Non-Inventory** | **COGS** (`costOfGoodsSoldAccount`) | WIP | **suppressed** |
+
+So a finished good that is a Part **always** posts to the Finished Goods account — the service COGS branch is entered *only* when the item is Non-Inventory, which a Part never is. The service divergence cannot touch the Part/inventory path.
+
+This is a **correctness fix, not flag-gated** — the prior (correct) behavior is being restored for *all* Non-Inventory job completions (services today; any future Non-Inventory make). `close-job`'s residual-WIP → `materialVarianceAccount` sweep is item-type-agnostic and needs no change (it becomes a near-no-op once completion relieves WIP; a service job with over/under-absorbed labor still sweeps the remainder to variance — research Pattern 5, "no standard-cost production variance for services; sweep residual WIP").
+
+**Accounts (resolved OQ‑1):** revenue and COGS resolve from **company-level `accountDefault`** — `salesAccount` (revenue, on the sales invoice, unchanged) and `costOfGoodsSoldAccount` (COGS, at completion). No per-item accounts (posting groups are dropped; nothing on `item` carries accounts). A service carries **no inventory/asset account** because it is Non-Inventory. This matches the just-approved raw-materials/FG spec and the no-matrix-config rule.
+
+### 2. Fulfillment — job completion advances the sales-order line (resolved OQ‑3)
+
+On successful completion of a service job (`job."salesOrderLineId"` set AND the job's item is `Non-Inventory`), advance the linked `salesOrderLine`'s fulfillment to mirror what `post-shipment` does for a physical line (`post-shipment/index.ts:494-546`): `quantitySent` (recomputed from ALL jobs on the line — idempotent, lot-split safe), `sentComplete = quantitySent >= saleQuantity`, `sentDate = today` on first completion. **Implemented inside `complete_job_to_inventory` itself (revised 2026-07-14 during e2e):** the original design put this in TypeScript in the `$jobId.complete.tsx` action, but completion has multiple entry points — the ERP route AND the `sync_finish_job_operation` DB interceptor that auto-completes the job when its last operation finishes — so the SQL function is the only choke point that covers every path. The block runs before the accounting-enabled / zero-WIP early returns. Fulfillment = work done; invoicing follows as today. (The SO-status rollup already treats service lines as shipped, so this write is about the line's own truthful delivered state and UI, not unblocking order completion.)
+
+### 3. Sales / job creation — make the job-creation body service-aware
+
+- `convertSalesOrderLinesToJobs` (`production.service.ts:139`) and the per-line `salesOrderLineToJob` path: read `itemReplenishment` with `.maybeSingle()` (not `.single()`) and default absent values (`lotSize = null`, `scrapPercentage = 0`, `leadTime = 7`) — `insertJob` already uses `maybeSingle` (`production.service.ts:2673`), so the fix is the bulk converter matching it. Skip storage-unit resolution for Non-Inventory items (`getDefaultStorageUnitForJob` returns null for a service anyway; guard to avoid a needless query). No scrap for services.
+- No change to the methodType/UI side: a `Make` service already defaults `defaultMethodType = 'Make to Order'` (`ServiceForm.tsx:76-77`), the Jobs card already renders when `line.methodType === 'Make to Order'` (`$orderId.$lineId.details.tsx:216`), and `SalesOrderSummary`'s "Create Jobs" already includes service lines. The `get-method` `itemToJob` copy already builds the job from the service's make method (operations → labor WIP, materials → material WIP).
+
+**In-house vs subcontracted falls out of `replenishmentSystem` for free** (research §6): a **`Make` service** = in-house labor job (WIP from operations); a **`Buy` service** = subcontracted/purchased, `defaultMethodType = 'Purchase to Order'`, invoiced via a PO/vendor bill with no job. A `Make` service that has an *outside operation* is the in-house-job-with-subcontracted-step case — one WIP path, two cost sources — already supported (outside operations post to WIP). No new branch needed.
+
+### 4. Revenue-recognition seams (resolved OQ‑2 — seams only, no new schema)
+
+Spec #1048 already owns the rev-rec schema (`item.revenueRecognitionMethod`, `accountDefault.deferredRevenueAccount`/`contractAssetAccount`, `revenueArrangement`/`revenueElement`/`revenueRecognitionSchedule`) and its cost-to-cost POC reads **job WIP debit inflows by `documentId = jobId`** over an EAC from `jobMaterial`/`jobOperation`. This spec therefore adds **no** rev-rec schema (avoiding a migration collision) and instead guarantees the two seams #1048 needs:
+
+- **Seam A — POC cost basis, already free.** A service job's WIP accumulates by `documentId = jobId` (unchanged), so a service MTO line is a first-class POC cost basis the moment #1048 lands. Its EAC inputs already exist (`jobOperation` setup/labor/machine times × `laborRate`/`machineRate` + `overheadRate`; `jobMaterial.estimatedQuantity × unitCost`), surfaced today by `JobEstimatesVsActuals.tsx`.
+- **Seam B — one interceptable COGS-at-completion branch.** The Non-Inventory `Dr COGS / Cr WIP` post lives in a single branch of `complete_job_to_inventory`. #1048's resolved OQ‑N1 (post COGS **as-incurred** in the recognition run and **skip COGS at completion/shipment for POC elements**) extends exactly this branch with one guard — `AND NOT (revenueRecognitionEnabled AND element.method = 'Percent of Completion' for this salesOrderLineId)`. v1 always posts COGS at completion (rev-rec off, the only state today); #1048 adds the guard additively, no restructuring. This is documented in the migration as the extension point.
+
+### Design Decisions
+
+| # | Heuristic | Decision | Rationale |
+|---|-----------|----------|-----------|
+| 1 | Multi-tenancy | **No new tables/columns/enums.** All touched tables (`job`, `salesOrderLine`, `journalLine`) are already `companyId`-scoped composite-PK tables. The migration only redefines a function. | Minimal footprint; the feature is a posting fix + hooks, not new entities. |
+| 2 | Service shape | New/changed logic in **`production.service.ts`** (`convertSalesOrderLinesToJobs` service-awareness; a fulfillment helper), `(client, …) → {data, error}`, never throws. Accounting change is the `complete_job_to_inventory` SQL function. | One `{module}.service.ts` per module; production owns jobs + fulfillment-from-completion. |
+| 3 | RLS | No new tables; existing `job`/`salesOrderLine`/`journalLine` policies apply. Completion runs service-role in the RPC (as today). | No surface added. |
+| 4 | Permissions | Job creation `create: "production"` (unchanged); completion `update: "production"` (unchanged); the SO-line fulfillment advance happens inside the completion action under production perms. | Matches existing job/completion routes. |
+| 5 | Forms | No new forms. The service line already uses `ValidatedForm` + `salesOrderLineValidator`; methodType wiring is existing. | Nothing to add. |
+| 6 | Module layout | production (`production.service.ts`), accounting (SQL migration under `packages/database/supabase/migrations/`); items/sales unchanged except the converter fix. No new module. | House layout. |
+| 7 | Backward compatibility | The `complete_job_to_inventory` change **restores** the prior Non-Inventory behavior (regression fix) — inventory-item completions are byte-identical to `20260713222236`; only Non-Inventory completions change (and their current behavior is buggy). Historical journals untouched. Not flag-gated. Rev-rec stays additive via Seam B. | A correctness fix that narrows to the buggy branch; no frozen inventory-item posting surface changes. |
+
+## Data Model Changes
+
+**One migration** (`pnpm db:migrate:new service-make-to-order-completion`, randomized HHMMSS per the timestamp lesson), redefining a single function. **No table/column/enum changes**, so `pnpm run generate:types` is a no-op for TS types (the RPC signature is preserved) — run it anyway to confirm no diff.
+
+```sql
+-- Fork complete_job_to_inventory from the NEWEST definition (20260713222236),
+-- preserving its full signature + all overhead/RM-FG logic, and re-add the
+-- Non-Inventory branch dropped when the July-13 migrations forked from an older
+-- baseline (template: 20260707022142_complete-job-to-inventory-non-inventory.sql).
+DROP FUNCTION IF EXISTS complete_job_to_inventory(TEXT, NUMERIC, TEXT, TEXT, TEXT, TEXT);
+CREATE OR REPLACE FUNCTION complete_job_to_inventory(
+ p_job_id TEXT, p_quantity_complete NUMERIC, p_storage_unit_id TEXT,
+ p_location_id TEXT, p_company_id TEXT, p_user_id TEXT
+) RETURNS ... AS $$
+DECLARE
+ -- ...existing declares from 20260713222236...
+ v_cogs_account TEXT; -- re-added: accountDefault."costOfGoodsSoldAccount"
+BEGIN
+ -- ...existing item/accountDefault fetch (add costOfGoodsSoldAccount to the select)...
+
+ IF v_item_tracking_type = 'Non-Inventory' THEN
+ -- Service / Non-Inventory: relieve WIP straight to COGS, no inventory leg.
+ -- Dr costOfGoodsSoldAccount / Cr workInProgressAccount (v_accumulated_wip_cost)
+ -- documentType 'Job Receipt', documentLineReference 'job:'||p_job_id
+ -- >>> REV-REC SEAM B: a future revenue-recognition build gates THIS post off
+ -- for Percent-of-Completion elements (COGS then posts as-incurred in the
+ -- recognition run). v1 always posts here. <<<
+ -- NO itemLedger 'Assembly Output', NO pickMethod update,
+ -- NO costLedger 'Output' layer, NO itemCost update.
+ ELSE
+ -- Inventory: unchanged from 20260713222236 (RM/FG CASE on replenishmentSystem,
+ -- overhead absorption, itemLedger 'Assembly Output', costLedger 'Output', itemCost).
+ END IF;
+END; $$ LANGUAGE plpgsql SECURITY DEFINER;
+```
+
+No views select the changed function's output columns; nothing to redefine. (Verify at implementation; DROP/recreate with `SELECT *` if any view is found to depend on a touched column — none expected.)
+
+## API / Service Changes
+
+`apps/erp/app/modules/production/production.service.ts`:
+
+- **`convertSalesOrderLinesToJobs`** — `itemReplenishment` via `.maybeSingle()` + defaults (`lotSize: null`, `scrapPercentage: 0`, `leadTime: 7`); skip storage-unit resolution when the item is `Non-Inventory`. (The per-line `insertJob` path already uses `maybeSingle` — align the bulk converter.)
+- **No new TypeScript fulfillment helper.** (An `advanceServiceLineFulfillment` route hook was originally specified here, implemented, then removed during e2e — see §Fulfillment and Changelog.) Fulfillment lives ONLY inside `complete_job_to_inventory`'s Non-Inventory branch: it recomputes `quantitySent` from ALL non-cancelled jobs on the line (idempotent, lot-split safe), sets `sentComplete`/`sentDate`, and runs before the accounting-enabled / zero-WIP early returns, so every completion entry point (the ERP route AND the `sync_finish_job_operation` interceptor) crosses the single SQL path. Do not add an app-level fulfillment hook — it would double-write `quantitySent`.
+
+Callers/hooks:
+- **`apps/erp/app/routes/x+/job+/$jobId.complete.tsx`** — unchanged behavior; carries a comment pointing at the SQL fulfillment path.
+- **`complete_job_to_inventory`** (SQL) — Non-Inventory branch (§Data Model), including the SO-line fulfillment.
+
+Unchanged and relied upon: `issue` / `post-production-event` (WIP by `documentId = jobId`), `close-job` (residual WIP → `materialVarianceAccount`), `post-shipment` (Non-Inventory COGS exclusion + service-line always-shipped rollup), `get-method` `itemToJob` (make-method copy), `post-sales-invoice` (revenue `Dr AR / Cr salesAccount`).
+
+## UI Changes
+
+Minimal — the surfaces already render; the fixes make them function:
+
+- **Sales order line detail** (`$orderId.$lineId.details.tsx`): the "Jobs / Make to Order" card already renders for `methodType === 'Make to Order'`; no change. A `Make` service line reaches it.
+- **Sales order summary** (`SalesOrderSummary.tsx`): "Create Jobs" already includes service lines; the converter fix makes it succeed.
+- **Job page**: a service job shows operations (labor) and materials from the make method; completion marks the job Completed. Consider showing "Completed" rather than a `0/n` shipped count for a Non-Inventory job (cosmetic; `SalesOrderJobItem` shows shipped/quantity — a completed service job has `quantityShipped = 0` by design). Optional polish, not required for correctness.
+- Flash messages on job creation/completion per `.ai/rules/flash-system.md` (existing).
+
+## Acceptance Criteria
+
+- [ ] A `Make` service item created via `ServiceForm` has `replenishmentSystem = 'Make'`, `defaultMethodType = 'Make to Order'`, `itemTrackingType = 'Non-Inventory'`, and an auto-created `makeMethod`; adding a routing operation + BOM material to it persists.
+- [ ] Adding that service to a sales order line seeds `methodType = 'Make to Order'`; the line-detail "Jobs / Make to Order" card renders, and the order-summary "Create Jobs" affordance appears.
+- [ ] Clicking "Create Jobs" (bulk) and per-line "Make to Order" both create a job for the service line **without erroring** on the missing `itemReplenishment` row; the job's operations/materials are copied from the service's make method.
+- [ ] Reporting a production event (labor) and issuing a material against the service job posts `Dr workInProgressAccount / Cr laborAbsorptionAccount` (labor) and `Dr workInProgressAccount / Cr <inventory>` (material), both with `documentId = jobId`.
+- [ ] **Completing the service job posts exactly `Dr costOfGoodsSoldAccount / Cr workInProgressAccount` for the accumulated WIP, and creates NO `itemLedger` "Assembly Output" row, NO `costLedger` "Output" layer, and NO `itemCost` update** (verify by query). A `Make` **inventory** (Part) job completion is unchanged: `Dr finishedGoodsAccount / Cr WIP` + itemLedger/costLedger as before.
+- [ ] Completing the service job advances the linked sales-order line: `quantitySent` increases by the completed quantity, `sentComplete` flips true when fully completed, `sentDate` set — with no shipment record created and no inventory relieved.
+- [ ] `post-shipment` is never invoked for the service line (no shipment builder entry), and the sales order can still reach its completed/invoiceable status (service line counts as shipped in the rollup).
+- [ ] Invoicing the service order line posts revenue `Dr receivablesAccount / Cr salesAccount` on the sales invoice as today, with no COGS on the invoice (COGS already posted at completion).
+- [ ] `close-job` on the completed service job finds ~zero residual WIP and posts nothing; a service job closed with un-relieved WIP (e.g. over-absorbed labor) sweeps the remainder to `materialVarianceAccount`.
+- [ ] A `Buy` service line defaults to `Purchase to Order`, shows **no** Jobs card, and is unaffected by this spec.
+- [ ] The migration applies idempotently twice and passes a rolled-back psql validation: `complete_job_to_inventory` references `costOfGoodsSoldAccount` and branches on `itemTrackingType = 'Non-Inventory'`; inventory-item completion output is EXCEPT-equivalent to `20260713222236`.
+- [ ] `pnpm run generate:types` produces no type diff; scoped `typecheck` (erp) and `pnpm run lint` pass.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|------|----------|------------|
+| The migration forks `complete_job_to_inventory` from the wrong (older) baseline again, re-dropping July‑13 overhead/RM logic | High | Fork explicitly from `20260713222236`; rolled-back psql validation asserts inventory-item output is EXCEPT-equivalent to the current definition; only the Non-Inventory branch differs. |
+| Between migration and edge-function/app rollout, in-flight Non-Inventory completions post the old (buggy) way | Low | Function-only change; the RPC is redefined atomically. No edge-function rollout coupling. Inngest/route retries self-heal. |
+| Existing service jobs completed BEFORE this fix left phantom FG `itemLedger`/`costLedger` rows | Med | Documented limitation; a one-off cleanup/reclass is out of scope (mirrors the raw-materials/FG spec's pre-split-stock caveat). Note in release notes. |
+| Partial completion of a service job posts all accumulated WIP-to-date at the first completion (no per-unit cost layer for Non-Inventory) | Med | Acceptable v1 (services are typically completed whole); document. If per-completion cost splitting is needed, revisit with the inventory-valuation workstream. |
+| Fulfillment advance (TS) succeeds/fails independently of the completion RPC | Low | Call it immediately after RPC success in the same action; idempotent (re-running clamps at `saleQuantity`). |
+| Rev-rec (#1048) later needs COGS-at-completion suppressed for POC service elements | Low (by design) | Seam B: the single Non-Inventory COGS branch is the documented extension point; #1048 adds one guard, no restructuring. |
+
+## Open Questions
+
+> Resolved before writing (Step 5 / Step 7). All boxes checked — audit trail below.
+
+- [x] **OQ‑1: Where do service revenue/COGS accounts resolve — per-item accounts (research rec) or company-level `accountDefault`?** — **Answer (Brad, 2026-07-14):** Company-level `accountDefault` (`salesAccount` for revenue, `costOfGoodsSoldAccount` for COGS); no per-item accounts. Carbon has no per-item account fields (posting groups dropped), and the just-approved raw-materials/FG spec + the no-matrix-config rule both point to company defaults. Supersedes the research summary's "service item carries a revenue + COGS account" phrasing (Carbon-consistent implementation of the same intent).
+- [x] **OQ‑2: How much revenue-recognition scaffolding to pre-build now (rev-rec "coming very soon")?** — **Answer (Brad, 2026-07-14):** Seams only, no new schema. Spec #1048 owns the rev-rec tables/columns; adding them here risks a migration collision. Preserve the two seams #1048 needs: the WIP-by-`documentId=jobId` subledger (already free) and a single interceptable COGS-at-completion branch (Seam B).
+- [x] **OQ‑3: How does a service SO line show fulfilled with no shipment?** — **Answer (Brad, 2026-07-14):** Job completion advances the SO line (`quantitySent`/`sentComplete`/`sentDate`), mirroring how a shipment advances a physical line. Fulfillment = work done; invoicing follows as today.
+- [x] **Accepted from research (pre-resolved by "go with the recommendations"):** service job accumulates WIP like a physical job (2); fulfillment by completion not goods issue (3); WIP→COGS directly at completion, no FG leg, no inventory account on the service (4); revenue on the sales invoice, v1 timing = completion/on-invoice (5); residual WIP swept to variance at close (6); one WIP path, two cost sources — `Make` service = in-house job, `Buy` service = subcontracted PO (7).
+
+## Changelog
+
+- 2026-07-14 (e2e revisions): (1) Fulfillment moved from the TS completion route into `complete_job_to_inventory` — the `sync_finish_job_operation` interceptor auto-completes jobs at the DB level, bypassing any app-level hook (commit 6c6565d0c). (2) "Jobs Required" card now also renders at status "To Invoice" when a Make-to-Order Service line exists — `getSalesOrderStatus` counts Service lines as shipped, so an all-service order skips the "To Ship" states the card gated on (commit b68962287). (3) Confirmed inherited zero-cost edge during e2e: issuing an item with no cost layers/unit cost posts no Job Consumption journal and no costLedger (`issue/index.ts` `if (cost <= 0) continue`) — pre-existing, applies to physical jobs equally, documented not changed.
+- 2026-07-14: Created. Grounded in `.ai/research/service-make-to-order-jobs.md` (Epicor Make Direct), the in-flight revenue-recognition spec (`2026-07-04`, issue #1048), and codebase tracing of the live posting path (`complete_job_to_inventory` newest def `20260713222236`; dropped Non-Inventory branch `20260707022142`; WIP accumulation `issue`/`post-production-event`; `close-job` variance sweep; `post-shipment` Non-Inventory/service handling; `convertSalesOrderLinesToJobs` converter; service item wiring `serviceReplenishmentSystems`/`ServiceForm`/`20260707022141`). Three grounding-surfaced questions (OQ‑1 accounts, OQ‑2 rev-rec stubs, OQ‑3 fulfillment) resolved with Brad before writing.
diff --git a/apps/erp/app/components/Form/Item.tsx b/apps/erp/app/components/Form/Item.tsx
index 58d3057024..fa4a71c324 100644
--- a/apps/erp/app/components/Form/Item.tsx
+++ b/apps/erp/app/components/Form/Item.tsx
@@ -33,9 +33,10 @@ import { useFetcher } from "react-router";
import ConsumableForm from "~/modules/items/ui/Consumables/ConsumableForm";
import MaterialForm from "~/modules/items/ui/Materials/MaterialForm";
import PartForm from "~/modules/items/ui/Parts/PartForm";
+import ServiceForm from "~/modules/items/ui/Services/ServiceForm";
import ToolForm from "~/modules/items/ui/Tools/ToolForm";
-import type { MethodItemType } from "~/modules/shared";
-import { methodItemType } from "~/modules/shared";
+import type { ItemType, MethodItemType } from "~/modules/shared";
+import { itemType, methodItemType } from "~/modules/shared";
import { useItems } from "~/stores";
import { path } from "~/utils/path";
import { MethodItemTypeIcon } from "../Icons";
@@ -51,11 +52,15 @@ type ItemSelectProps = Omit<ComboboxProps, "options" | "type" | "inline"> & {
isConfigured?: boolean;
locationId?: string;
replenishmentSystem?: "Buy" | "Make";
- type: MethodItemType | "Item";
+ type: ItemType | "Item";
typeFieldName?: string;
- validItemTypes?: MethodItemType[];
+ validItemTypes?: ItemType[];
whitelist?: string[];
onConfigure?: () => void;
+ // Narrower than `type`/`validItemTypes` on purpose: BOM/method callers pass a
+ // MethodItemType handler, and order-line callers pass a wider handler that is
+ // still assignable here (contravariance). The dropdown's emit is cast, so it
+ // can still surface "Service" when validItemTypes includes it.
onTypeChange?: (type: MethodItemType | "Item") => void;
};
@@ -70,7 +75,7 @@ const ItemPreview = (
const useTranslatedItemType = () => {
const { t } = useLingui();
- return (type: MethodItemType | "Item") => {
+ return (type: ItemType | "Item") => {
switch (type) {
case "Item":
return t`Item`;
@@ -82,6 +87,8 @@ const useTranslatedItemType = () => {
return t`Tool`;
case "Consumable":
return t`Consumable`;
+ case "Service":
+ return t`Service`;
default:
return type;
}
@@ -354,21 +361,23 @@ const Item = ({
<Trans>All Items</Trans>
</span>
</DropdownMenuRadioItem>
- {Object.values(methodItemType)
- .filter(
- (itemType) =>
- validItemTypes === undefined ||
- (Array.isArray(validItemTypes) &&
- validItemTypes.includes(itemType))
+ {itemType
+ .filter((option) =>
+ // Default to methodItemType so BOM/method pickers never
+ // surface Service; order-line forms opt in by passing
+ // validItemTypes that include it.
+ (validItemTypes ?? methodItemType).some(
+ (t) => t === option
+ )
)
- .map((itemType) => (
+ .map((option) => (
<DropdownMenuRadioItem
- key={itemType}
- value={itemType}
+ key={option}
+ value={option}
className="flex items-center gap-2"
>
- <MethodItemTypeIcon type={itemType} />
- <span>{translateItemType(itemType)}</span>
+ <MethodItemTypeIcon type={option} />
+ <span>{translateItemType(option)}</span>
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
@@ -434,24 +443,32 @@ const Item = ({
</ModalTitle>
</ModalHeader>
<ModalBody>
- <div className="grid grid-cols-2 gap-4">
- {Object.values(methodItemType).map((itemType) => (
- <Button
- key={itemType}
- leftIcon={<MethodItemTypeIcon type={itemType} />}
- className="flex w-full"
- variant={type === itemType ? "primary" : "secondary"}
- size="lg"
- onClick={() => {
- onTypeChange?.(itemType);
- setTimeout(() => {
- submitRef.current?.focus();
- }, 0);
- }}
- >
- {translateItemType(itemType)}
- </Button>
- ))}
+ <div className="grid grid-cols-1 gap-4">
+ {itemType
+ .filter((option) =>
+ // Same narrowing as the dropdown above: BOM/method pickers
+ // never surface Tool or Service; order-line forms opt in
+ // via validItemTypes.
+ (validItemTypes ?? methodItemType).some((t) => t === option)
+ )
+ .map((option) => (
+ <Button
+ key={option}
+ leftIcon={<MethodItemTypeIcon type={option} />}
+ className="flex w-full"
+ variant={type === option ? "primary" : "secondary"}
+ size="lg"
+ onClick={() => {
+ // Same contravariance cast as the dropdown emit above.
+ onTypeChange?.(option as MethodItemType);
+ setTimeout(() => {
+ submitRef.current?.focus();
+ }, 0);
+ }}
+ >
+ {translateItemType(option)}
+ </Button>
+ ))}
</div>
</ModalBody>
<ModalFooter>
@@ -550,7 +567,32 @@ const Item = ({
}}
/>
)}
- {/* TODO: Add service */}
+ {type === "Service" && newItemsModal.isOpen && (
+ <ServiceForm
+ type="modal"
+ onClose={() => {
+ setCreated("");
+ newItemsModal.onClose();
+ triggerRef.current?.click();
+ }}
+ initialValues={{
+ id: "",
+ revision: "0",
+ name: created,
+ description: "",
+ itemTrackingType: "Non-Inventory",
+ unitOfMeasureCode: "EA",
+ replenishmentSystem: props?.replenishmentSystem ?? "Buy",
+ defaultMethodType:
+ props?.replenishmentSystem === "Make"
+ ? "Make to Order"
+ : "Purchase to Order",
+ unitCost: 0,
+ shelfLifeCalculateFromBom: false,
+ tags: []
+ }}
+ />
+ )}
{type === "Tool" && newItemsModal.isOpen && (
<ToolForm
type="modal"
diff --git a/apps/erp/app/components/Form/Items.tsx b/apps/erp/app/components/Form/Items.tsx
index fc9c3d14b4..ad80bab370 100644
--- a/apps/erp/app/components/Form/Items.tsx
+++ b/apps/erp/app/components/Form/Items.tsx
@@ -15,9 +15,10 @@ import { useMemo, useRef, useState } from "react";
import ConsumableForm from "~/modules/items/ui/Consumables/ConsumableForm";
import MaterialForm from "~/modules/items/ui/Materials/MaterialForm";
import PartForm from "~/modules/items/ui/Parts/PartForm";
+import ServiceForm from "~/modules/items/ui/Services/ServiceForm";
import ToolForm from "~/modules/items/ui/Tools/ToolForm";
-import type { MethodItemType } from "~/modules/shared";
-import { methodItemType } from "~/modules/shared";
+import type { ItemType } from "~/modules/shared";
+import { itemType } from "~/modules/shared";
import { useItems } from "~/stores";
import { MethodItemTypeIcon } from "../Icons";
import { useEmptyState } from "./emptyStates";
@@ -26,7 +27,7 @@ type ItemsSelectProps = Omit<CreatableMultiSelectProps, "options">;
const Items = (props: ItemsSelectProps) => {
const { t } = useLingui();
- const translateType = (type: MethodItemType) => {
+ const translateType = (type: ItemType) => {
switch (type) {
case "Part":
return t`Part`;
@@ -36,6 +37,8 @@ const Items = (props: ItemsSelectProps) => {
return t`Tool`;
case "Consumable":
return t`Consumable`;
+ case "Service":
+ return t`Service`;
default:
return type;
}
@@ -44,7 +47,7 @@ const Items = (props: ItemsSelectProps) => {
const selectTypeModal = useDisclosure();
const newItemsModal = useDisclosure();
const [created, setCreated] = useState<string>("");
- const [type, setType] = useState<MethodItemType>("Part");
+ const [type, setType] = useState<ItemType>("Part");
const triggerRef = useRef<HTMLButtonElement>(null);
const options = useMemo(
@@ -101,17 +104,17 @@ const Items = (props: ItemsSelectProps) => {
</ModalTitle>
</ModalHeader>
<ModalBody>
- <div className="grid grid-cols-2 gap-4">
- {Object.values(methodItemType).map((itemType) => (
+ <div className="grid grid-cols-1 gap-4">
+ {itemType.map((option) => (
<Button
- key={itemType}
- leftIcon={<MethodItemTypeIcon type={itemType} />}
+ key={option}
+ leftIcon={<MethodItemTypeIcon type={option} />}
className="flex w-full"
- variant={type === itemType ? "primary" : "secondary"}
+ variant={type === option ? "primary" : "secondary"}
size="lg"
- onClick={() => setType(itemType)}
+ onClick={() => setType(option)}
>
- {translateType(itemType)}
+ {translateType(option)}
</Button>
))}
</div>
@@ -213,6 +216,25 @@ const Items = (props: ItemsSelectProps) => {
}}
/>
)}
+ {type === "Service" && newItemsModal.isOpen && (
+ <ServiceForm
+ type="modal"
+ onClose={handleCreateClose}
+ initialValues={{
+ id: "",
+ revision: "0",
+ name: created,
+ description: "",
+ itemTrackingType: "Non-Inventory",
+ unitOfMeasureCode: "EA",
+ replenishmentSystem: "Buy",
+ defaultMethodType: "Purchase to Order",
+ unitCost: 0,
+ shelfLifeCalculateFromBom: false,
+ tags: []
+ }}
+ />
+ )}
</>
);
};
diff --git a/apps/erp/app/components/Form/Service.tsx b/apps/erp/app/components/Form/Service.tsx
index a82d476d7e..8cf1a4cfeb 100644
--- a/apps/erp/app/components/Form/Service.tsx
+++ b/apps/erp/app/components/Form/Service.tsx
@@ -1,15 +1,12 @@
import type { ComboboxProps } from "@carbon/form";
import { Combobox } from "@carbon/form";
import { useMemo } from "react";
-import type { ServiceType } from "~/modules/items";
import { useServices } from "~/stores";
import { useEmptyState } from "./emptyStates";
-type ServiceSelectProps = Omit<ComboboxProps, "options"> & {
- serviceType?: ServiceType;
-};
+type ServiceSelectProps = Omit<ComboboxProps, "options">;
-const Service = ({ serviceType, ...props }: ServiceSelectProps) => {
+const Service = (props: ServiceSelectProps) => {
const services = useServices();
const options = useMemo(
() =>
diff --git a/apps/erp/app/components/ItemThumbnail.tsx b/apps/erp/app/components/ItemThumbnail.tsx
index 00a0aea27f..754ea21d6a 100644
--- a/apps/erp/app/components/ItemThumbnail.tsx
+++ b/apps/erp/app/components/ItemThumbnail.tsx
@@ -1,13 +1,13 @@
import { cn } from "@carbon/react";
import { cva } from "class-variance-authority";
import { LuBlocks } from "react-icons/lu";
-import type { MethodItemType } from "~/modules/shared";
+import type { ItemType } from "~/modules/shared";
import { getPrivateUrl } from "~/utils/path";
import { MethodItemTypeIcon } from "./Icons";
interface ItemThumbnailProps {
thumbnailPath?: string | null;
- type?: MethodItemType;
+ type?: ItemType;
size?: "sm" | "md" | "lg" | "xl";
}
diff --git a/apps/erp/app/components/Selectors/UserSelect/components/TreeSelect.tsx b/apps/erp/app/components/Selectors/UserSelect/components/TreeSelect.tsx
index 34f5e2c134..98b091d324 100644
--- a/apps/erp/app/components/Selectors/UserSelect/components/TreeSelect.tsx
+++ b/apps/erp/app/components/Selectors/UserSelect/components/TreeSelect.tsx
@@ -97,7 +97,14 @@ const SentinelRow = ({
* A group at any depth: the row selects the group (when groups are
* selectable); the chevron expands/collapses; hovering prefetches members.
*/
-const GroupRow = ({ node }: { node: GroupNode }) => {
+const GroupRow = ({
+ node,
+ inheritedSelected = false
+}: {
+ node: GroupNode;
+ /** True when an ancestor group is selected — forces this row checked + locked. */
+ inheritedSelected?: boolean;
+}) => {
const {
innerProps: { alwaysSelected, usersOnly },
focusedId,
@@ -112,9 +119,15 @@ const GroupRow = ({ node }: { node: GroupNode }) => {
const { group, uid, expanded, loading, members } = node;
const isFocused = uid === focusedId;
- const isSelected = group.id in selectionItemsById;
- const isDisabled = alwaysSelected?.includes(group.id) ?? false;
- const canExpand = group.userCount + group.groupCount > 0;
+ // Selected directly, or implicitly because an ancestor group is selected.
+ const isSelected = inheritedSelected || group.id in selectionItemsById;
+ // Locked when an ancestor is selected (included via that ancestor, can't be
+ // toggled off) or when force-selected via alwaysSelected.
+ const isDisabled =
+ inheritedSelected || (alwaysSelected?.includes(group.id) ?? false);
+ // The seeded roots ("All Employees/Customers/Suppliers") are select-all
+ // targets, not folders — never expandable; their members are top-level siblings.
+ const canExpand = !group.isRoot && group.userCount + group.groupCount > 0;
const isOpen = expanded && members !== null;
const isEmpty =
members !== null &&
@@ -206,13 +219,15 @@ const GroupRow = ({ node }: { node: GroupNode }) => {
<ul role="group" className="flex flex-col gap-0.5 py-1 pl-2">
{members.groups.map((child) => (
<li key={child.uid}>
- <GroupRow node={child} />
+ <GroupRow node={child} inheritedSelected={isSelected} />
</li>
))}
{members.users.map((item) => {
- const itemIsDisabled = alwaysSelected?.includes(item.id) ?? false;
const itemIsFocused = item.uid === focusedId;
- const itemIsSelected = item.id in selectionItemsById;
+ // A selected group implicitly includes (and locks) all its members.
+ const itemIsSelected = isSelected || item.id in selectionItemsById;
+ const itemIsDisabled =
+ isSelected || (alwaysSelected?.includes(item.id) ?? false);
return (
<Option
diff --git a/apps/erp/app/modules/documents/documents.models.ts b/apps/erp/app/modules/documents/documents.models.ts
index 1be61be0bd..1bbd239ec2 100644
--- a/apps/erp/app/modules/documents/documents.models.ts
+++ b/apps/erp/app/modules/documents/documents.models.ts
@@ -2,7 +2,7 @@ import type { Database } from "@carbon/database";
import { getLogger } from "@carbon/logger";
import type { SupabaseClient } from "@supabase/supabase-js";
import { z } from "zod";
-import { methodItemType } from "~/modules/shared";
+import { itemType } from "~/modules/shared";
const logger = getLogger("erp", "documents-models");
@@ -19,7 +19,7 @@ export const documentSourceTypes = [
"Sales Order",
"Sales Invoice",
"Shipment",
- ...methodItemType
+ ...itemType
] as const;
export const documentValidator = z.object({
diff --git a/apps/erp/app/modules/documents/ui/Documents/DocumentsTable.tsx b/apps/erp/app/modules/documents/ui/Documents/DocumentsTable.tsx
index 0156f7277d..f340aa8614 100644
--- a/apps/erp/app/modules/documents/ui/Documents/DocumentsTable.tsx
+++ b/apps/erp/app/modules/documents/ui/Documents/DocumentsTable.tsx
@@ -646,8 +646,8 @@ function getDocumentLocation(
return path.to.gaugeCalibrationRecord(sourceDocumentId);
case "Job":
return path.to.job(sourceDocumentId);
- // case "Service":
- // return path.to.service(sourceDocumentId);
+ case "Service":
+ return path.to.service(sourceDocumentId);
case "Purchase Order":
return path.to.purchaseOrder(sourceDocumentId);
case "Purchasing Request for Quote":
diff --git a/apps/erp/app/modules/inventory/inventory.models.ts b/apps/erp/app/modules/inventory/inventory.models.ts
index 3f20a8c8f0..e34026b6d6 100644
--- a/apps/erp/app/modules/inventory/inventory.models.ts
+++ b/apps/erp/app/modules/inventory/inventory.models.ts
@@ -5,12 +5,14 @@ import { batchPropertyDataTypes } from "../items/items.models";
export const demandPeriodTypes = ["Week", "Day", "Month"] as const;
export const demandSourceTypes = ["Sales Order", "Job Material"] as const;
-export const itemTypes = [
+// Stockable item types — the subset of the shared `itemType` list that can
+// hold inventory. Services are Non-Inventory (never stocked, counted, planned,
+// or storage-ruled), so they are deliberately excluded here.
+export const inventoryItemTypes = [
"Part",
"Material",
"Tool",
"Consumable"
- // "Service",
] as const;
export const itemLedgerTypes = [
@@ -132,7 +134,7 @@ export const inventoryCountValidator = z.object({
isBlind: zfd.checkbox(),
notes: zfd.text(z.string().optional()),
storageUnitIds: zfd.repeatableOfType(z.string()).optional(),
- itemType: zfd.text(z.enum(itemTypes).optional())
+ itemType: zfd.text(z.enum(inventoryItemTypes).optional())
});
// Per-line count entry. A blank `countedQuantity` (undefined) means "not counted"
diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
index 69c216e632..dba3f1a2f8 100644
--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
@@ -62,7 +62,7 @@ import {
import type { action as mrpAction } from "~/routes/api+/mrp";
import type { ListItem } from "~/types";
import { path } from "~/utils/path";
-import { itemTypes } from "../../inventory.models";
+import { inventoryItemTypes } from "../../inventory.models";
import type { InventoryItem } from "../../types";
type InventoryTableProps = {
@@ -439,7 +439,7 @@ const InventoryTable = memo(
meta: {
filter: {
type: "static",
- options: itemTypes.map((type) => ({
+ options: inventoryItemTypes.map((type) => ({
label: (
<HStack spacing={2}>
<MethodItemTypeIcon type={type} />
diff --git a/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountForm.tsx b/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountForm.tsx
index a889ef4ec1..f6b9b31acf 100644
--- a/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountForm.tsx
+++ b/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountForm.tsx
@@ -24,7 +24,10 @@ import {
TextArea
} from "~/components/Form";
import { usePermissions } from "~/hooks";
-import { inventoryCountValidator, itemTypes } from "~/modules/inventory";
+import {
+ inventoryCountValidator,
+ inventoryItemTypes
+} from "~/modules/inventory";
import { path } from "~/utils/path";
type InventoryCountFormProps = {
@@ -42,7 +45,7 @@ const InventoryCountForm = ({
const [locationId, setLocationId] = useState(initialValues.locationId ?? "");
- const itemTypeOptions = itemTypes.map((type) => ({
+ const itemTypeOptions = inventoryItemTypes.map((type) => ({
label: type,
value: type
}));
diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLineForm.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLineForm.tsx
index 0ae924be3b..451d66a5e2 100644
--- a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLineForm.tsx
+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLineForm.tsx
@@ -19,11 +19,12 @@ import type { z } from "zod";
import { Hidden, Item, Number, StorageUnit, Submit } from "~/components/Form";
import { usePermissions, useRouteData } from "~/hooks";
import {
+ inventoryItemTypes,
isStockTransferLocked,
type StockTransfer,
stockTransferLineValidator
} from "~/modules/inventory";
-import type { MethodItemType } from "~/modules/shared/types";
+import type { ItemType } from "~/modules/shared/types";
import { useItems } from "~/stores/items";
import { path } from "~/utils/path";
@@ -56,11 +57,11 @@ const StockTransferLineForm = ({
initialValues.itemId ?? null
);
- const [itemType, setItemType] = useState<MethodItemType | "Item">(() => {
+ const [itemType, setItemType] = useState<ItemType | "Item">(() => {
if (initialValues.itemId) {
return (
(items.find((item) => item.id === initialValues.itemId)
- ?.type as MethodItemType) ?? "Item"
+ ?.type as ItemType) ?? "Item"
);
}
return "Item";
@@ -78,7 +79,7 @@ const StockTransferLineForm = ({
}
);
- const onTypeChange = (t: MethodItemType | "Item") => {
+ const onTypeChange = (t: ItemType | "Item") => {
setItemType(t);
setItemId(null);
};
@@ -86,7 +87,7 @@ const StockTransferLineForm = ({
const onItemChange = (itemId: string) => {
setItemId(itemId);
const item = items.find((item) => item.id === itemId);
- const itemType = (item?.type as MethodItemType) ?? "Item";
+ const itemType = (item?.type as ItemType) ?? "Item";
const trackingType = item?.itemTrackingType ?? null;
setItemType(itemType);
setItemTrackingType(trackingType);
@@ -166,6 +167,9 @@ const StockTransferLineForm = ({
}
// @ts-ignore
type={itemType}
+ // Only stockable types can be transferred — Services are
+ // Non-Inventory and must not be selectable here.
+ validItemTypes={[...inventoryItemTypes]}
locationId={locationId}
onTypeChange={onTypeChange}
onChange={(value) => {
diff --git a/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx b/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx
index 1780ea0283..22c7e1f578 100644
--- a/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx
+++ b/apps/erp/app/modules/inventory/ui/useInventorySubmodules.tsx
@@ -29,6 +29,12 @@ export default function useInventorySubmodules() {
{
name: t`Manage`,
routes: [
+ {
+ name: t`Inventory Count`,
+ to: path.to.inventoryCounts,
+ icon: <LuClipboardCheck />,
+ table: "inventoryCount"
+ },
{
name: t`Picking Lists`,
to: path.to.pickingLists,
@@ -57,12 +63,6 @@ export default function useInventorySubmodules() {
to: path.to.warehouseTransfers,
icon: <LuArrowRightLeft />,
table: "warehouseTransfer"
- },
- {
- name: t`Inventory Count`,
- to: path.to.inventoryCounts,
- icon: <LuClipboardCheck />,
- table: "inventoryCount"
}
]
},
diff --git a/apps/erp/app/modules/invoicing/invoicing.models.ts b/apps/erp/app/modules/invoicing/invoicing.models.ts
index c833963e7d..c17dbcc1aa 100644
--- a/apps/erp/app/modules/invoicing/invoicing.models.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.models.ts
@@ -3,11 +3,11 @@ import { zfd } from "zod-form-data";
// Import the constants from the models file directly (not the `../shared` barrel),
// which also re-exports shared.service/shared.server — those transitively pull in
// `@carbon/auth`'s Lingui-macro glossary and break plain unit tests of this module.
-import { incoterms, methodItemType, methodType } from "../shared/shared.models";
+import { incoterms, itemType, methodType } from "../shared/shared.models";
export const purchaseInvoiceLineType = [
"Part",
- // "Service",
+ "Service",
"Material",
"Tool",
"Consumable",
@@ -41,7 +41,7 @@ export function isPurchaseInvoiceLocked(
export const salesInvoiceLineType = [
"Part",
- // "Service",
+ "Service",
"Material",
"Tool",
"Consumable",
@@ -106,14 +106,7 @@ export const purchaseInvoiceLineValidator = z
id: zfd.text(z.string().optional()),
invoiceId: z.string().min(1, { message: "Invoice is required" }),
invoiceLineType: z.enum(
- [
- ...methodItemType,
- "Service",
- "Fixture",
- "G/L Account",
- "Fixed Asset",
- "Comment"
- ],
+ [...itemType, "Fixture", "G/L Account", "Fixed Asset", "Comment"],
{
errorMap: (issue, ctx) => ({
@@ -235,14 +228,11 @@ export const salesInvoiceLineValidator = z
.object({
id: zfd.text(z.string().optional()),
invoiceId: z.string().min(1, { message: "Invoice is required" }),
- invoiceLineType: z.enum(
- [...methodItemType, "Service", "Fixture", "Fixed Asset"],
- {
- errorMap: (issue, ctx) => ({
- message: "Type is required"
- })
- }
- ),
+ invoiceLineType: z.enum([...itemType, "Fixture", "Fixed Asset"], {
+ errorMap: (issue, ctx) => ({
+ message: "Type is required"
+ })
+ }),
methodType: z
.enum(methodType, {
errorMap: (issue, ctx) => ({
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceExplorer.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceExplorer.tsx
index f1fbfc96ec..943fc954e4 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceExplorer.tsx
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceExplorer.tsx
@@ -46,8 +46,8 @@ import {
} from "~/hooks";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
import type { Supplier } from "~/modules/purchasing/types";
-import type { MethodItemType } from "~/modules/shared";
-import { methodItemType } from "~/modules/shared";
+import type { ItemType } from "~/modules/shared";
+import { itemType } from "~/modules/shared";
import { useItems } from "~/stores";
import { path } from "~/utils/path";
import type { PurchaseInvoice, PurchaseInvoiceLine } from "../../types";
@@ -69,7 +69,7 @@ export default function PurchaseInvoiceExplorer() {
const purchaseInvoiceLineInitialValues = {
invoiceId: invoiceId,
- invoiceLineType: "Item" as MethodItemType,
+ invoiceLineType: "Item" as ItemType,
purchaseQuantity: 1,
locationId:
purchaseInvoiceData?.purchaseInvoice?.locationId ??
@@ -374,14 +374,14 @@ function PurchaseInvoiceLineItem({
<Trans>Delete Line</Trans>
</DropdownMenuItem>
{/* @ts-expect-error */}
- {methodItemType.includes(line.invoiceLineType ?? "") && (
+ {itemType.includes(line.invoiceLineType ?? "") && (
<DropdownMenuItem
asChild
onClick={(e) => e.stopPropagation()}
>
<Link
to={getLinkToItemDetails(
- line.invoiceLineType as MethodItemType,
+ line.invoiceLineType as ItemType,
line.itemId!
)}
>
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx
index 72e27045e4..14f5f5fe25 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx
@@ -174,12 +174,13 @@ const PurchaseInvoiceHeader = () => {
.from("purchaseInvoiceLine")
.select("itemId, description, quantity, conversionFactor")
.eq("invoiceId", invoiceId)
+ // Services are never received, so they never generate a receipt — mirror
+ // the post-purchase-invoice edge function and exclude them here.
.in("invoiceLineType", [
"Part",
"Material",
"Tool",
"Consumable",
- "Service",
"Fixture"
])
.is("purchaseOrderLineId", null);
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx
index 0740744c32..3c1d6a5ca1 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceLineForm.tsx
@@ -60,7 +60,11 @@ import {
import type { PurchaseInvoice } from "~/modules/invoicing";
import { purchaseInvoiceLineValidator } from "~/modules/invoicing";
import { getSupplierPartPriceBreaks } from "~/modules/items";
-import { type MethodItemType, resolveSupplierPrice } from "~/modules/shared";
+import {
+ type ItemType,
+ itemType,
+ resolveSupplierPrice
+} from "~/modules/shared";
import { useItems } from "~/stores";
import { path } from "~/utils/path";
@@ -97,8 +101,8 @@ const PurchaseInvoiceLineForm = ({
routeData?.purchaseInvoice?.status ?? ""
);
- const [itemType, setItemType] = useState<MethodItemType>(
- initialValues.invoiceLineType as MethodItemType
+ const [lineType, setLineType] = useState<ItemType>(
+ initialValues.invoiceLineType as ItemType
);
const [locationId, setLocationId] = useState(defaults.locationId ?? "");
const [itemData, setItemData] = useState<{
@@ -272,9 +276,9 @@ const PurchaseInvoiceLineForm = ({
const currencyFormatter = useCurrencyFormatter();
const percentFormatter = usePercentFormatter();
- const onTypeChange = (t: MethodItemType | "Item") => {
- if (t === itemType) return;
- setItemType(t as MethodItemType);
+ const onTypeChange = (t: ItemType | "Item") => {
+ if (t === lineType) return;
+ setLineType(t as ItemType);
setItemData({
itemId: "",
description: "",
@@ -295,14 +299,13 @@ const PurchaseInvoiceLineForm = ({
const onItemChange = async (itemId: string) => {
if (!carbon) throw new Error("Carbon client not found");
- switch (itemType) {
+ switch (lineType) {
// @ts-expect-error
case "Item":
case "Consumable":
case "Material":
case "Part":
case "Tool":
- // @ts-expect-error
case "Service":
// @ts-expect-error
case "Fixture":
@@ -375,13 +378,13 @@ const PurchaseInvoiceLineForm = ({
});
if (item.data?.type) {
- setItemType(item.data.type as MethodItemType);
+ setLineType(item.data.type as ItemType);
}
break;
default:
throw new Error(
- `Invalid invoice line type: ${itemType} is not implemented`
+ `Invalid invoice line type: ${lineType} is not implemented`
);
}
};
@@ -525,7 +528,7 @@ const PurchaseInvoiceLineForm = ({
/>
<TabsContent value="item">
- <Hidden name="invoiceLineType" value={itemType} />
+ <Hidden name="invoiceLineType" value={lineType} />
{activeTab === "item" && (
<Hidden name="description" value={itemData.description} />
)}
@@ -537,9 +540,9 @@ const PurchaseInvoiceLineForm = ({
<div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
<Item
name="itemId"
- label={itemType}
- // @ts-ignore
- type={itemType}
+ label={lineType}
+ type={lineType}
+ validItemTypes={[...itemType]}
locationId={locationId}
replenishmentSystem="Buy"
onChange={(value) => {
@@ -571,7 +574,7 @@ const PurchaseInvoiceLineForm = ({
"Consumable",
"Service",
"Fixture"
- ].includes(itemType) && (
+ ].includes(lineType) && (
<>
<NumberControlled
minValue={itemData.minimumOrderQuantity}
@@ -644,20 +647,22 @@ const PurchaseInvoiceLineForm = ({
value={locationId}
onChange={onLocationChange}
/>
- <StorageUnit
- name="storageUnitId"
- label={t`Storage Unit`}
- locationId={locationId}
- value={itemData.storageUnitId ?? undefined}
- onChange={(newValue) => {
- if (newValue) {
- setItemData((d) => ({
- ...d,
- storageUnitId: newValue?.id
- }));
- }
- }}
- />
+ {lineType !== "Service" && (
+ <StorageUnit
+ name="storageUnitId"
+ label={t`Storage Unit`}
+ locationId={locationId}
+ value={itemData.storageUnitId ?? undefined}
+ onChange={(newValue) => {
+ if (newValue) {
+ setItemData((d) => ({
+ ...d,
+ storageUnitId: newValue?.id
+ }));
+ }
+ }}
+ />
+ )}
</>
)}
<CustomFormFields table="purchaseInvoiceLine" />
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer.tsx
index 5a34ea95ba..c0e46ba65e 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceExplorer.tsx
@@ -43,8 +43,8 @@ import {
} from "~/hooks";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
import type { Supplier } from "~/modules/purchasing/types";
-import type { MethodItemType } from "~/modules/shared";
-import { methodItemType } from "~/modules/shared";
+import type { ItemType } from "~/modules/shared";
+import { itemType } from "~/modules/shared";
import { useItems } from "~/stores";
import { path } from "~/utils/path";
import { isSalesInvoiceLocked } from "../../invoicing.models";
@@ -66,7 +66,7 @@ export default function SalesInvoiceExplorer() {
const salesInvoiceLineInitialValues = {
invoiceId: invoiceId,
- invoiceLineType: "Item" as MethodItemType,
+ invoiceLineType: "Item" as ItemType,
quantity: 1,
locationId:
salesInvoiceData?.salesInvoice?.locationId ?? defaults.locationId ?? "",
@@ -324,14 +324,14 @@ function SalesInvoiceLineItem({
<Trans>Delete Line</Trans>
</DropdownMenuItem>
{/* @ts-expect-error */}
- {methodItemType.includes(line.invoiceLineType ?? "") && (
+ {itemType.includes(line.invoiceLineType ?? "") && (
<DropdownMenuItem
asChild
onClick={(e) => e.stopPropagation()}
>
<Link
to={getLinkToItemDetails(
- line.invoiceLineType as MethodItemType,
+ line.invoiceLineType as ItemType,
line.itemId!
)}
>
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsx
index 3b1268f8f0..a7f4cd8693 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceLineForm.tsx
@@ -62,8 +62,7 @@ import {
} from "~/hooks";
import type { SalesInvoice } from "~/modules/invoicing";
import { salesInvoiceLineValidator } from "~/modules/invoicing";
-import type { MethodItemType } from "~/modules/shared";
-import { methodType } from "~/modules/shared";
+import { type ItemType, itemType, methodType } from "~/modules/shared";
import { useItems } from "~/stores";
import { path } from "~/utils/path";
import { isSalesInvoiceLocked } from "../../invoicing.models";
@@ -102,8 +101,8 @@ const SalesInvoiceLineForm = ({
const isLocked = isSalesInvoiceLocked(routeData?.salesInvoice?.status);
const isEditable = !isLocked;
- const [itemType, setItemType] = useState<MethodItemType>(
- initialValues.invoiceLineType as MethodItemType
+ const [lineType, setLineType] = useState<ItemType>(
+ initialValues.invoiceLineType as ItemType
);
const [locationId, setLocationId] = useState(defaults.locationId ?? "");
const [itemData, setItemData] = useState<{
@@ -226,9 +225,9 @@ const SalesInvoiceLineForm = ({
? !permissions.can("update", "purchasing")
: !permissions.can("create", "purchasing");
- const onTypeChange = (t: MethodItemType | "Item") => {
- if (t === itemType) return;
- setItemType(t as MethodItemType);
+ const onTypeChange = (t: ItemType | "Item") => {
+ if (t === lineType) return;
+ setLineType(t as ItemType);
setItemData({
itemId: "",
methodType: "",
@@ -245,14 +244,13 @@ const SalesInvoiceLineForm = ({
const onItemChange = async (itemId: string) => {
if (!carbon) throw new Error("Carbon client not found");
- switch (itemType) {
+ switch (lineType) {
// @ts-expect-error
case "Item":
case "Consumable":
case "Material":
case "Part":
case "Tool":
- // @ts-expect-error
case "Service":
// @ts-expect-error
case "Fixture":
@@ -315,13 +313,13 @@ const SalesInvoiceLineForm = ({
}));
if (item.data?.type) {
- setItemType(item.data.type as MethodItemType);
+ setLineType(item.data.type as ItemType);
}
break;
default:
throw new Error(
- `Invalid invoice line type: ${itemType} is not implemented`
+ `Invalid invoice line type: ${lineType} is not implemented`
);
}
};
@@ -469,7 +467,7 @@ const SalesInvoiceLineForm = ({
/>
<TabsContent value="item">
- <Hidden name="invoiceLineType" value={itemType} />
+ <Hidden name="invoiceLineType" value={lineType} />
<Hidden name="description" value={itemData.description} />
<Hidden
name="unitOfMeasureCode"
@@ -491,9 +489,9 @@ const SalesInvoiceLineForm = ({
<div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
<Item
name="itemId"
- label={itemType}
- // @ts-ignore
- type={itemType}
+ label={lineType}
+ type={lineType}
+ validItemTypes={[...itemType]}
locationId={locationId}
onChange={(value) => {
onItemChange(value?.value as string);
@@ -524,7 +522,7 @@ const SalesInvoiceLineForm = ({
"Consumable",
"Service",
"Fixture"
- ].includes(itemType) && (
+ ].includes(lineType) && (
<>
<div className="space-y-2">
<SelectControlled
@@ -586,20 +584,22 @@ const SalesInvoiceLineForm = ({
value={locationId}
onChange={onLocationChange}
/>
- <StorageUnit
- name="storageUnitId"
- label={t`Storage Unit`}
- locationId={locationId}
- value={itemData.storageUnitId ?? undefined}
- onChange={(newValue) => {
- if (newValue) {
- setItemData((d) => ({
- ...d,
- storageUnitId: newValue?.id
- }));
- }
- }}
- />
+ {lineType !== "Service" && (
+ <StorageUnit
+ name="storageUnitId"
+ label={t`Storage Unit`}
+ locationId={locationId}
+ value={itemData.storageUnitId ?? undefined}
+ onChange={(newValue) => {
+ if (newValue) {
+ setItemData((d) => ({
+ ...d,
+ storageUnitId: newValue?.id
+ }));
+ }
+ }}
+ />
+ )}
</>
)}
<CustomFormFields table="salesInvoiceLine" />
@@ -613,7 +613,7 @@ const SalesInvoiceLineForm = ({
"Consumable",
"Service",
"Fixture"
- ].includes(itemType) && (
+ ].includes(lineType) && (
<div className="w-full">
<div className="w-full border border-border rounded-md shadow-sm p-4 flex flex-col gap-4 mt-4">
<HStack
diff --git a/apps/erp/app/modules/items/AGENTS.md b/apps/erp/app/modules/items/AGENTS.md
index 1e578607e2..04c930fafc 100644
--- a/apps/erp/app/modules/items/AGENTS.md
+++ b/apps/erp/app/modules/items/AGENTS.md
@@ -59,7 +59,8 @@ pnpm --filter @carbon/erp test
## Key Service Functions
-- `getItem` / `getPart` / `getMaterial` / `getConsumable` / `getTool` — item reads by type (RPCs `get_part_details`, `get_material_details`, etc.)
+- `getItem` / `getPart` / `getMaterial` / `getConsumable` / `getTool` / `getService` — item reads by type (RPCs `get_part_details`, `get_material_details`, `get_service_details`, etc.)
+- `upsertService` — creates/updates a Service item; always `itemTrackingType = 'Non-Inventory'` (never shipped/received/stocked), replenishment `Buy` or `Make` only. The `service` row is keyed by `item.readableId` (like tool/material). Legacy `service.serviceType` is defaulted and no longer read.
- `upsertMaterial` — creates/updates material with taxonomy FKs and `item`/`material` linkage
- `getMakeMethods` / `getMethodMaterials` / `getMethodOperations` / `getMethodTreeArray` — BOM/routing reads
- `copyItem` / `copyMakeMethod` — duplicates via edge function
diff --git a/apps/erp/app/modules/items/items.models.ts b/apps/erp/app/modules/items/items.models.ts
index c88b5646cc..a56f7a7730 100644
--- a/apps/erp/app/modules/items/items.models.ts
+++ b/apps/erp/app/modules/items/items.models.ts
@@ -73,7 +73,9 @@ export const partManufacturingPolicies = [
"Make to Order"
] as const;
-export const serviceType = ["Internal", "External"] as const;
+// Services are Buy or Make only — never "Buy and Make", and never stocked
+// ("Pull from Inventory" is not a valid method for a Non-Inventory item).
+export const serviceReplenishmentSystems = ["Buy", "Make"] as const;
export const supplierPartPriceSourceTypes = [
"Quote",
@@ -800,11 +802,17 @@ export const serviceValidator = applyStorageAndShelfLifeRefines(
itemValidator.merge(
z.object({
id: z.string().min(1, { message: "Service ID is required" }).max(255),
- serviceType: z.enum(serviceType, {
+ revision: z.string().min(1, { message: "Revision is required" }),
+ unitOfMeasureCode: z
+ .string()
+ .min(1, { message: "Unit of Measure is required" }),
+ replenishmentSystem: z.enum(serviceReplenishmentSystems, {
errorMap: (issue, ctx) => ({
- message: "Service type is required"
+ message: "Replenishment system is required"
})
- })
+ }),
+ // Services can never be shipped, received, or stocked
+ itemTrackingType: z.literal("Non-Inventory")
})
)
);
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index 3011849e5b..795958cc4a 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -1878,13 +1878,12 @@ export async function getServices(
companyId: string,
args: GenericQueryFilters & {
search: string | null;
- type: string | null;
group: string | null;
supplierId: string | null;
}
) {
let query = client
- .from("service")
+ .from("services")
.select("*", {
count: "exact"
})
@@ -1892,14 +1891,7 @@ export async function getServices(
if (args.search) {
query = query.or(
- `readableIdWithRevision.ilike.%${args.search}%,name.ilike.%${args.search}%,description.ilike.%${args.search}%`
- );
- }
-
- if (args.type) {
- query = query.eq(
- "serviceType",
- args.type as NonNullable<"Internal" | "External">
+ `readableIdWithRevision.ilike.%${args.search}%,name.ilike.%${args.search}%,description.ilike.%${args.search}%,supplierIds.ilike.%${args.search}%`
);
}
@@ -1922,11 +1914,14 @@ export async function getService(
itemId: string,
companyId: string
) {
+ // get_service_details returns the same shape as get_tool_details. The RPC only
+ // enters the committed (cloud-sourced) types once the migration is applied to
+ // the cloud DB, so until then we borrow the tool-details typing while calling
+ // the real RPC. Drop the cast after the next cloud type regeneration.
return client
- .from("service")
- .select("*")
- .eq("itemId", itemId)
- .eq("companyId", companyId)
+ .rpc("get_service_details" as unknown as "get_tool_details", {
+ item_id: itemId
+ })
.single();
}
@@ -1937,7 +1932,8 @@ export async function getServicesList(
return fetchAllFromTable<{
id: string;
name: string;
- }>(client, "item", "id, name", (query) =>
+ readableIdWithRevision: string;
+ }>(client, "item", "id, name, readableIdWithRevision", (query) =>
query
.eq("type", "Service")
.eq("companyId", companyId)
@@ -3647,6 +3643,7 @@ export async function upsertSupplierPart(
})
| (Omit<z.infer<typeof supplierPartValidator>, "id"> & {
id: string;
+ companyId: string;
updatedBy: string;
customFields?: Json;
})
@@ -3662,6 +3659,7 @@ export async function upsertSupplierPart(
.from("supplierPart")
.update(sanitize(supplierPart))
.eq("id", supplierPart.id)
+ .eq("companyId", supplierPart.companyId)
.select("id")
.single();
}
@@ -4437,8 +4435,7 @@ export async function upsertService(
createdBy: string;
customFields?: Json;
})
- | (Omit<z.infer<typeof serviceValidator>, "id"> & {
- id: string;
+ | (z.infer<typeof serviceValidator> & {
updatedBy: string;
customFields?: Json;
})
@@ -4448,16 +4445,15 @@ export async function upsertService(
.from("item")
.insert({
readableId: service.id,
+ revision: service.revision ?? "0",
name: service.name,
+ description: service.description,
type: "Service",
- replenishmentSystem:
- service.serviceType === "External" ? "Buy" : "Make",
- defaultMethodType:
- service.serviceType === "External"
- ? "Purchase to Order"
- : "Make to Order",
- itemTrackingType: service.itemTrackingType,
- unitOfMeasureCode: "EA",
+ replenishmentSystem: service.replenishmentSystem,
+ defaultMethodType: service.defaultMethodType,
+ // Services can never be shipped, received, or stocked
+ itemTrackingType: "Non-Inventory",
+ unitOfMeasureCode: service.unitOfMeasureCode,
active: true,
companyId: service.companyId,
createdBy: service.createdBy
@@ -4467,54 +4463,61 @@ export async function upsertService(
if (itemInsert.error) return itemInsert;
const itemId = itemInsert.data?.id;
- const serviceInsert = await client
- .from("service")
- .insert({
+ const [serviceInsert, itemCostUpdate] = await Promise.all([
+ client.from("service").upsert({
id: service.id,
- serviceType: service.serviceType,
+ // Legacy column, no longer surfaced in the UI; the migration adds a
+ // DB-level default of "External". Passed explicitly until the committed
+ // (cloud-sourced) types pick up that default and make it optional.
+ serviceType: "External",
companyId: service.companyId,
createdBy: service.createdBy,
customFields: service.customFields
- })
- .select("*")
- .single();
+ }),
+ client
+ .from("itemCost")
+ .update(
+ sanitize({
+ itemPostingGroupId: service.postingGroupId,
+ unitCost: service.unitCost
+ })
+ )
+ .eq("itemId", itemId)
+ ]);
if (serviceInsert.error) return serviceInsert;
-
- const costUpdate = await client
- .from("itemCost")
- .update({ unitCost: service.unitCost })
- .eq("itemId", itemId)
- .select("*")
- .single();
-
- if (costUpdate.error) return costUpdate;
+ if (itemCostUpdate.error) return itemCostUpdate;
const newService = await client
- .from("service")
+ .from("services")
.select("*")
.eq("readableId", service.id)
+ .eq("companyId", service.companyId)
.single();
return newService;
}
+
+ const item = await client
+ .from("item")
+ .select("readableId, companyId")
+ .eq("id", service.id)
+ .single();
+ if (item.error) return item;
+
const itemUpdate = {
id: service.id,
name: service.name,
description: service.description,
- replenishmentSystem:
- service.serviceType === "External" ? "Buy" : ("Make" as "Buy"),
- defaultMethodType:
- service.serviceType === "External"
- ? "Purchase to Order"
- : ("Make to Order" as "Purchase to Order"),
- itemTrackingType: service.itemTrackingType,
- unitOfMeasureCode: null,
+ replenishmentSystem: service.replenishmentSystem,
+ defaultMethodType: service.defaultMethodType,
+ itemTrackingType: "Non-Inventory" as const,
+ unitOfMeasureCode: service.unitOfMeasureCode,
active: true
};
const serviceUpdate = {
- serviceType: service.serviceType
+ customFields: service.customFields
};
const [updateItem, updateService] = await Promise.all([
@@ -4525,13 +4528,15 @@ export async function upsertService(
updatedAt: today(getLocalTimeZone()).toString()
})
.eq("id", service.id),
+ // service.id is the item uuid; the service row is keyed by readableId
client
.from("service")
.update({
...sanitize(serviceUpdate),
updatedAt: today(getLocalTimeZone()).toString()
})
- .eq("itemId", service.id)
+ .eq("id", item.data.readableId ?? "")
+ .eq("companyId", item.data.companyId ?? "")
]);
if (updateItem.error) return updateItem;
diff --git a/apps/erp/app/modules/items/types.ts b/apps/erp/app/modules/items/types.ts
index d7abb4bbf7..9c1a7e0b62 100644
--- a/apps/erp/app/modules/items/types.ts
+++ b/apps/erp/app/modules/items/types.ts
@@ -27,6 +27,7 @@ import type {
getPart,
getParts,
getPickMethods,
+ getService,
getServices,
getSupplierParts,
getTool,
@@ -171,7 +172,9 @@ export type Service = NonNullable<
Awaited<ReturnType<typeof getServices>>["data"]
>[number];
-export type ServiceType = Database["public"]["Enums"]["serviceType"];
+export type ServiceSummary = NonNullable<
+ Awaited<ReturnType<typeof getService>>
+>["data"];
export type Substance = NonNullable<
Awaited<ReturnType<typeof getMaterialSubstances>>["data"]
diff --git a/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx b/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx
index f774d08fba..2c041a1b68 100644
--- a/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx
@@ -44,14 +44,14 @@ import { OnshapeSync } from "~/components/OnshapeSync";
import type { FlatTreeItem } from "~/components/TreeView";
import { LevelLine, TreeView, useTree } from "~/components/TreeView";
import { useIntegrations } from "~/hooks/useIntegrations";
-import type { MethodItemType } from "~/modules/shared";
+import type { ItemType } from "~/modules/shared";
import { generateBomIds } from "~/utils/bom";
import { path } from "~/utils/path";
import type { MakeMethod, Method, MethodOperation } from "../../types";
import { getLinkToItemDetails } from "./ItemForm";
type BoMExplorerProps = {
- itemType: MethodItemType;
+ itemType: ItemType;
makeMethod: MakeMethod;
methods: FlatTreeItem<Method>[];
methodId?: string;
@@ -643,23 +643,21 @@ function NodePreview({ node }: { node: FlatTreeItem<Method> }) {
);
}
-function getRootLink(
- itemType: MethodItemType,
- itemId: string,
- methodId: string
-) {
+function getRootLink(itemType: ItemType, itemId: string, methodId: string) {
switch (itemType) {
case "Part":
return `${path.to.partDetails(itemId)}?methodId=${methodId}`;
case "Tool":
return `${path.to.toolDetails(itemId)}?methodId=${methodId}`;
+ case "Service":
+ return `${path.to.serviceDetails(itemId)}?methodId=${methodId}`;
default:
throw new Error(`Unimplemented BoMExplorer itemType: ${itemType}`);
}
}
function getMaterialLink(
- itemType: MethodItemType,
+ itemType: ItemType,
itemId: string,
methodId: string,
makeMethodId: string,
@@ -670,6 +668,8 @@ function getMaterialLink(
return `${path.to.partMake(itemId, makeMethodId)}?methodId=${methodId}`;
case "Tool":
return `${path.to.toolMake(itemId, makeMethodId)}?methodId=${methodId}`;
+ case "Service":
+ return `${path.to.serviceMake(itemId, makeMethodId)}?methodId=${methodId}`;
default:
throw new Error(`Unimplemented BoMExplorer itemType: ${itemType}`);
}
diff --git a/apps/erp/app/modules/items/ui/Item/FileBadge.tsx b/apps/erp/app/modules/items/ui/Item/FileBadge.tsx
index e14e7a27be..4769517158 100644
--- a/apps/erp/app/modules/items/ui/Item/FileBadge.tsx
+++ b/apps/erp/app/modules/items/ui/Item/FileBadge.tsx
@@ -2,7 +2,7 @@ import { Badge, cn, HStack } from "@carbon/react";
import { LuDownload } from "react-icons/lu";
import { DocumentPreview } from "~/components";
import DocumentIcon from "~/components/DocumentIcon";
-import type { MethodItemType } from "~/modules/shared";
+import type { ItemType } from "~/modules/shared";
import { getDocumentType } from "~/modules/shared";
import type { ItemFile } from "../../types";
import { useItemDocuments } from "./ItemDocuments";
@@ -10,7 +10,7 @@ import { useItemDocuments } from "./ItemDocuments";
type FileBadgeProps = {
file: ItemFile;
itemId: string;
- itemType: MethodItemType;
+ itemType: ItemType;
className?: string;
};
diff --git a/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx b/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx
index 98190d5e3d..a6242df8b5 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx
@@ -31,7 +31,7 @@ import { Link, useFetchers, useRevalidator, useSubmit } from "react-router";
import { DocumentPreview, FileDropzone, Hyperlink } from "~/components";
import DocumentIcon from "~/components/DocumentIcon";
import { useDateFormatter, usePermissions, useUser } from "~/hooks";
-import type { MethodItemType, OptimisticFileObject } from "~/modules/shared";
+import type { ItemType, OptimisticFileObject } from "~/modules/shared";
import { getDocumentType } from "~/modules/shared";
import type { ModelUpload } from "~/types";
import { path } from "~/utils/path";
@@ -44,7 +44,7 @@ type ItemDocumentsProps = {
files: ItemFile[];
itemId: string;
modelUpload?: ModelUpload;
- type: MethodItemType;
+ type: ItemType;
};
const ItemDocuments = ({
@@ -266,7 +266,7 @@ export default ItemDocuments;
type ItemDocumentFormProps = {
itemId: string;
- type: MethodItemType;
+ type: ItemType;
};
const ItemDocumentForm = ({ itemId, type }: ItemDocumentFormProps) => {
@@ -293,7 +293,7 @@ const ItemDocumentForm = ({ itemId, type }: ItemDocumentFormProps) => {
type Props = {
itemId: string;
- type: MethodItemType;
+ type: ItemType;
};
export const useItemDocuments = ({ itemId, type }: Props) => {
diff --git a/apps/erp/app/modules/items/ui/Item/ItemForm.tsx b/apps/erp/app/modules/items/ui/Item/ItemForm.tsx
index b98c18c25a..5f29a3e536 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemForm.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemForm.tsx
@@ -35,7 +35,7 @@ import {
import { itemTypeIdLabel } from "~/components/Form/itemTypeLabel";
import { ReplenishmentSystemIcon } from "~/components/Icons";
import { usePermissions } from "~/hooks";
-import type { MethodItemType } from "~/modules/shared";
+import type { ItemType } from "~/modules/shared";
import { path } from "~/utils/path";
import {
itemReplenishmentSystems,
@@ -197,7 +197,7 @@ const ItemForm = ({ initialValues, type }: ItemFormProps) => {
export default ItemForm;
-export function getLinkToItemDetails(type: MethodItemType, id: string) {
+export function getLinkToItemDetails(type: ItemType, id: string) {
switch (type) {
case "Part":
return path.to.partDetails(id);
@@ -207,25 +207,27 @@ export function getLinkToItemDetails(type: MethodItemType, id: string) {
return path.to.toolDetails(id);
case "Consumable":
return path.to.consumableDetails(id);
- // case "Service":
- // return path.to.serviceDetails(id);
+ case "Service":
+ return path.to.serviceDetails(id);
default:
throw new Error("Invalid type");
}
}
-export function getLinkToItemManufacturing(type: MethodItemType, id: string) {
+export function getLinkToItemManufacturing(type: ItemType, id: string) {
switch (type) {
case "Part":
return path.to.partDetails(id);
case "Tool":
return path.to.toolDetails(id);
+ case "Service":
+ return path.to.serviceDetails(id);
default:
return getLinkToItemDetails(type, id);
}
}
-export function getLinkToItemPlanning(type: MethodItemType, id: string) {
+export function getLinkToItemPlanning(type: ItemType, id: string) {
switch (type) {
case "Part":
return path.to.partPlanning(id);
@@ -235,8 +237,7 @@ export function getLinkToItemPlanning(type: MethodItemType, id: string) {
return path.to.toolPlanning(id);
case "Consumable":
return path.to.consumablePlanning(id);
- // case "Service":
- // return path.to.serviceDetails(id);
+ // Services are Non-Inventory and never planned — no planning page.
default:
throw new Error("Invalid type");
}
diff --git a/apps/erp/app/modules/items/ui/Item/MakeMethodTools.tsx b/apps/erp/app/modules/items/ui/Item/MakeMethodTools.tsx
index ad402ea213..eebb160ca4 100644
--- a/apps/erp/app/modules/items/ui/Item/MakeMethodTools.tsx
+++ b/apps/erp/app/modules/items/ui/Item/MakeMethodTools.tsx
@@ -53,7 +53,7 @@ import { Link, useFetcher, useParams } from "react-router";
import { Hidden, Item, useConfigurableItems } from "~/components/Form";
import { Confirm } from "~/components/Modals";
import { usePermissions, useUser } from "~/hooks";
-import type { MethodItemType } from "~/modules/shared";
+import type { ItemType } from "~/modules/shared";
import { path } from "~/utils/path";
import {
getMethodValidator,
@@ -66,7 +66,7 @@ import MakeMethodVersionStatus from "./MakeMethodVersionStatus";
type MakeMethodToolsProps = {
itemId: string;
- type: MethodItemType;
+ type: ItemType;
makeMethods: MakeMethod[];
currentMethodId?: string;
};
diff --git a/apps/erp/app/modules/items/ui/Item/UsedIn.tsx b/apps/erp/app/modules/items/ui/Item/UsedIn.tsx
index 046729d41f..95de8026be 100644
--- a/apps/erp/app/modules/items/ui/Item/UsedIn.tsx
+++ b/apps/erp/app/modules/items/ui/Item/UsedIn.tsx
@@ -39,7 +39,7 @@ import { Hyperlink, MethodIcon } from "~/components";
import { Confirm } from "~/components/Modals";
import { LevelLine } from "~/components/TreeView";
import { usePermissions } from "~/hooks";
-import type { MethodItemType } from "~/modules/shared";
+import type { ItemType } from "~/modules/shared";
import { path } from "~/utils/path";
import { getReadableIdWithRevision } from "~/utils/string";
import { getPathToMakeMethod } from "../Methods/utils";
@@ -81,7 +81,7 @@ export type UsedInNode = {
documentReadableId: string;
documentId?: string;
documentParentId?: string;
- itemType?: MethodItemType;
+ itemType?: ItemType;
methodType?: string;
revision?: string;
version?: number;
diff --git a/apps/erp/app/modules/items/ui/Methods/utils.ts b/apps/erp/app/modules/items/ui/Methods/utils.ts
index e482c3dad1..e2cee894c9 100644
--- a/apps/erp/app/modules/items/ui/Methods/utils.ts
+++ b/apps/erp/app/modules/items/ui/Methods/utils.ts
@@ -1,8 +1,8 @@
-import type { MethodItemType } from "~/modules/shared";
+import type { ItemType } from "~/modules/shared";
import { path } from "~/utils/path";
export function getPathToMakeMethod(
- type: MethodItemType,
+ type: ItemType,
id: string,
methodId: string
) {
@@ -11,6 +11,8 @@ export function getPathToMakeMethod(
return `${path.to.partDetails(id)}?methodId=${methodId}`;
case "Tool":
return `${path.to.toolDetails(id)}?methodId=${methodId}`;
+ case "Service":
+ return `${path.to.serviceDetails(id)}?methodId=${methodId}`;
default:
return "#";
}
diff --git a/apps/erp/app/modules/items/ui/Services/ServiceForm.tsx b/apps/erp/app/modules/items/ui/Services/ServiceForm.tsx
new file mode 100644
index 0000000000..1d233135f9
--- /dev/null
+++ b/apps/erp/app/modules/items/ui/Services/ServiceForm.tsx
@@ -0,0 +1,199 @@
+import { ValidatedForm } from "@carbon/form";
+import {
+ cn,
+ ModalCard,
+ ModalCardBody,
+ ModalCardContent,
+ ModalCardDescription,
+ ModalCardFooter,
+ ModalCardHeader,
+ ModalCardProvider,
+ ModalCardTitle,
+ toast
+} from "@carbon/react";
+import { Trans, useLingui } from "@lingui/react/macro";
+import type { PostgrestResponse } from "@supabase/supabase-js";
+import { useEffect, useState } from "react";
+import { useFetcher } from "react-router";
+import type { z } from "zod";
+import {
+ CustomFormFields,
+ Hidden,
+ Input,
+ InputControlled,
+ ItemPostingGroup,
+ Select,
+ Submit,
+ TextArea,
+ UnitOfMeasure
+} from "~/components/Form";
+import { ReplenishmentSystemIcon } from "~/components/Icons";
+import { useNextItemId, usePermissions } from "~/hooks";
+import { path } from "~/utils/path";
+import {
+ serviceReplenishmentSystems,
+ serviceValidator
+} from "../../items.models";
+
+type ServiceFormProps = {
+ initialValues: z.infer<typeof serviceValidator> & { tags: string[] };
+ type?: "card" | "modal";
+ onClose?: () => void;
+};
+
+function startsWithLetter(value: string) {
+ return /^[A-Za-z]/.test(value);
+}
+
+const ServiceForm = ({
+ initialValues,
+ type = "card",
+ onClose
+}: ServiceFormProps) => {
+ const fetcher = useFetcher<PostgrestResponse<{ id: string }>>();
+ const { t } = useLingui();
+
+ useEffect(() => {
+ if (type !== "modal") return;
+
+ if (fetcher.state === "loading" && fetcher.data?.data) {
+ onClose?.();
+ toast.success(t`Created service`);
+ } else if (fetcher.state === "idle" && fetcher.data?.error) {
+ toast.error(t`Failed to create service: ${fetcher.data.error.message}`);
+ }
+ }, [fetcher.data, fetcher.state, onClose, type, t]);
+
+ const { id, onIdChange, loading } = useNextItemId("Service");
+ const permissions = usePermissions();
+ const isEditing = !!initialValues.id;
+
+ const [replenishmentSystem, setReplenishmentSystem] = useState<string>(
+ initialValues.replenishmentSystem ?? "Buy"
+ );
+ // Services are Non-Inventory, so the method type is fully determined by the
+ // replenishment system — never "Pull from Inventory".
+ const defaultMethodType =
+ replenishmentSystem === "Make" ? "Make to Order" : "Purchase to Order";
+
+ const itemReplenishmentSystemOptions = serviceReplenishmentSystems.map(
+ (itemReplenishmentSystem) => ({
+ label: (
+ <span className="flex items-center gap-2">
+ <ReplenishmentSystemIcon type={itemReplenishmentSystem} />
+ {itemReplenishmentSystem === "Buy" ? t`Buy` : t`Make`}
+ </span>
+ ),
+ value: itemReplenishmentSystem
+ })
+ );
+
+ return (
+ <ModalCardProvider type={type}>
+ <ModalCard onClose={onClose}>
+ <ModalCardContent>
+ <ValidatedForm
+ action={isEditing ? undefined : path.to.newService}
+ method="post"
+ validator={serviceValidator}
+ defaultValues={initialValues}
+ fetcher={fetcher}
+ >
+ <ModalCardHeader>
+ <ModalCardTitle>
+ {isEditing ? t`Service Details` : t`New Service`}
+ </ModalCardTitle>
+ {!isEditing && (
+ <ModalCardDescription>
+ {t`A service is a billable activity that is bought or performed — it is never shipped, received, or stocked`}
+ </ModalCardDescription>
+ )}
+ </ModalCardHeader>
+ <ModalCardBody>
+ <Hidden name="type" value={type} />
+ <Hidden name="itemTrackingType" value="Non-Inventory" />
+ <Hidden name="defaultMethodType" value={defaultMethodType} />
+ <div
+ className={cn(
+ "grid w-full gap-x-8 gap-y-4",
+ isEditing
+ ? "grid-cols-1 md:grid-cols-3"
+ : "grid-cols-1 md:grid-cols-2"
+ )}
+ >
+ {isEditing ? (
+ <Input name="id" label={t`Service ID`} isReadOnly />
+ ) : (
+ <InputControlled
+ name="id"
+ label={t`Service ID`}
+ helperText={
+ startsWithLetter(id)
+ ? t`Use ... to get the next service ID`
+ : undefined
+ }
+ value={id}
+ onChange={onIdChange}
+ isDisabled={loading}
+ isUppercase
+ autoFocus
+ />
+ )}
+ <Input
+ name="revision"
+ label={t`Revision`}
+ isReadOnly={isEditing}
+ />
+
+ <Input
+ name="name"
+ label={t`Short Description`}
+ characterLimit={40}
+ />
+ <Select
+ name="replenishmentSystem"
+ label={t`Replenishment System`}
+ termId="replenishment-system"
+ options={itemReplenishmentSystemOptions}
+ onChange={(newValue) =>
+ setReplenishmentSystem(newValue?.value ?? "Buy")
+ }
+ />
+ <UnitOfMeasure
+ name="unitOfMeasureCode"
+ label={t`Unit of Measure`}
+ />
+ {!isEditing && (
+ <ItemPostingGroup
+ name="postingGroupId"
+ label={t`Item Group`}
+ termId="item-group"
+ isClearable
+ />
+ )}
+ <CustomFormFields table="service" tags={initialValues.tags} />
+ </div>
+ <div className="mt-4 w-full">
+ <TextArea name="description" label={t`Long Description`} />
+ </div>
+ </ModalCardBody>
+ <ModalCardFooter>
+ <Submit
+ isLoading={fetcher.state !== "idle"}
+ isDisabled={
+ isEditing
+ ? !permissions.can("update", "parts")
+ : !permissions.can("create", "parts")
+ }
+ >
+ <Trans>Save</Trans>
+ </Submit>
+ </ModalCardFooter>
+ </ValidatedForm>
+ </ModalCardContent>
+ </ModalCard>
+ </ModalCardProvider>
+ );
+};
+
+export default ServiceForm;
diff --git a/apps/erp/app/modules/items/ui/Services/ServiceHeader.tsx b/apps/erp/app/modules/items/ui/Services/ServiceHeader.tsx
new file mode 100644
index 0000000000..220b1cfcdc
--- /dev/null
+++ b/apps/erp/app/modules/items/ui/Services/ServiceHeader.tsx
@@ -0,0 +1,129 @@
+import {
+ Copy,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ Heading,
+ HStack,
+ IconButton,
+ Status,
+ useDisclosure,
+ VStack
+} from "@carbon/react";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { LuEllipsisVertical, LuTrash } from "react-icons/lu";
+import { Link, useParams } from "react-router";
+import { useAuditLog } from "~/components/AuditLog";
+import { DetailsTopbar } from "~/components/Layout";
+import ConfirmDelete from "~/components/Modals/ConfirmDelete";
+import { usePermissions, useRouteData, useUser } from "~/hooks";
+import { path } from "~/utils/path";
+import type { Service } from "../../types";
+import { getItemLifecycleStatus } from "../Item/ItemSupersessionForm";
+import { useServiceNavigation } from "./useServiceNavigation";
+
+const ServiceHeader = () => {
+ const { t } = useLingui();
+ const links = useServiceNavigation();
+ const { itemId } = useParams();
+ if (!itemId) throw new Error("itemId not found");
+
+ const { company } = useUser();
+ const permissions = usePermissions();
+ const deleteModal = useDisclosure();
+ const { trigger: auditLogTrigger, drawer: auditLogDrawer } = useAuditLog({
+ entityType: "item",
+ entityId: itemId,
+ companyId: company.id,
+ variant: "dropdown"
+ });
+
+ const routeData = useRouteData<{
+ serviceSummary: Service;
+ supersession: {
+ supersessionMode:
+ | "Consume First"
+ | "Prefer New"
+ | "Stock Only"
+ | "No Stock";
+ } | null;
+ }>(path.to.service(itemId));
+
+ const lifecycleStatus = getItemLifecycleStatus(
+ routeData?.supersession?.supersessionMode
+ );
+
+ return (
+ <>
+ <div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border h-[50px] overflow-x-auto scrollbar-hide dark:border-none dark:shadow-[inset_0_0_1px_rgb(255_255_255_/_0.24),_0_0_0_0.5px_rgb(0,0,0,1),0px_0px_4px_rgba(0,_0,_0,_0.08)]">
+ <VStack spacing={0} className="flex-grow">
+ <HStack>
+ <Link to={path.to.serviceDetails(itemId)}>
+ <Heading size="h4" className="flex items-center gap-2">
+ <span>{routeData?.serviceSummary?.readableIdWithRevision}</span>
+ </Heading>
+ </Link>
+ <Copy
+ text={routeData?.serviceSummary?.readableIdWithRevision ?? ""}
+ />
+ {lifecycleStatus && (
+ <Status color={lifecycleStatus.color}>
+ {lifecycleStatus.label}
+ </Status>
+ )}
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label={t`More options`}
+ icon={<LuEllipsisVertical />}
+ variant="secondary"
+ size="sm"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ {auditLogTrigger}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ disabled={
+ !permissions.can("delete", "parts") ||
+ !permissions.is("employee")
+ }
+ destructive
+ onClick={deleteModal.onOpen}
+ >
+ <DropdownMenuIcon icon={<LuTrash />} />
+ <Trans>Delete Service</Trans>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </HStack>
+ </VStack>
+ <VStack spacing={0} className="flex-shrink justify-center items-end">
+ <DetailsTopbar links={links} />
+ </VStack>
+ {deleteModal.isOpen && (
+ <ConfirmDelete
+ action={path.to.deleteItem(itemId)}
+ isOpen={deleteModal.isOpen}
+ name={
+ routeData?.serviceSummary?.readableIdWithRevision ?? "service"
+ }
+ text={t`Are you sure you want to delete ${routeData?.serviceSummary?.readableIdWithRevision}? This cannot be undone.`}
+ onCancel={() => {
+ deleteModal.onClose();
+ }}
+ onSubmit={() => {
+ deleteModal.onClose();
+ }}
+ />
+ )}
+ </div>
+ {auditLogDrawer}
+ </>
+ );
+};
+
+export default ServiceHeader;
diff --git a/apps/erp/app/modules/items/ui/Services/ServiceProperties.tsx b/apps/erp/app/modules/items/ui/Services/ServiceProperties.tsx
new file mode 100644
index 0000000000..ca82b4c5b1
--- /dev/null
+++ b/apps/erp/app/modules/items/ui/Services/ServiceProperties.tsx
@@ -0,0 +1,561 @@
+import type { Json } from "@carbon/database";
+import { InputControlled, Select, ValidatedForm } from "@carbon/form";
+import {
+ Badge,
+ Button,
+ HStack,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+ toast,
+ VStack
+} from "@carbon/react";
+import { Trans, useLingui } from "@lingui/react/macro";
+import type { PostgrestResponse } from "@supabase/supabase-js";
+import { Suspense, useCallback, useEffect } from "react";
+import { LuCopy, LuKeySquare, LuLink } from "react-icons/lu";
+import { Await, Link, useFetcher, useParams } from "react-router";
+import { z } from "zod";
+import { zfd } from "zod-form-data";
+import { MethodBadge, MethodIcon } from "~/components";
+import { Boolean, ItemPostingGroup, Tags } from "~/components/Form";
+import CustomFormInlineFields from "~/components/Form/CustomFormInlineFields";
+import { ReplenishmentSystemIcon } from "~/components/Icons";
+import { ItemThumbnailUpload } from "~/components/ItemThumnailUpload";
+import { useRouteData } from "~/hooks";
+import { methodType } from "~/modules/shared";
+import type { action } from "~/routes/x+/items+/update";
+import { useSuppliers } from "~/stores";
+import { path } from "~/utils/path";
+import { copyToClipboard } from "~/utils/string";
+import { serviceReplenishmentSystems } from "../../items.models";
+import type { ItemFile, MakeMethod, Service, SupplierPart } from "../../types";
+import { FileBadge, ItemDescription } from "../Item";
+
+type ServicePropertiesProps = {
+ data?: {
+ itemId: string;
+ serviceSummary: Service;
+ files: Promise<ItemFile[]>;
+ supplierParts: SupplierPart[];
+ makeMethods: Promise<PostgrestResponse<MakeMethod>>;
+ tags: { name: string }[];
+ };
+};
+
+const ServiceProperties = ({ data }: ServicePropertiesProps) => {
+ const { t } = useLingui();
+ const params = useParams();
+ const itemId = data?.itemId ?? params.itemId;
+ if (!itemId) throw new Error("itemId not found");
+
+ // When `data` is injected, this hook won't match a route and returns
+ // undefined — harmless, hooks must be called unconditionally.
+ const routeDataFromRoute = useRouteData<{
+ serviceSummary: Service;
+ files: Promise<ItemFile[]>;
+ supplierParts: SupplierPart[];
+ makeMethods: Promise<PostgrestResponse<MakeMethod>>;
+ tags: { name: string }[];
+ supersession?: {
+ successorItemId: string | null;
+ successorEffectivityDate: string | null;
+ successor: {
+ id: string;
+ readableIdWithRevision: string;
+ name: string;
+ } | null;
+ } | null;
+ supersededBy?: Array<{
+ predecessor: {
+ id: string;
+ readableIdWithRevision: string;
+ name: string;
+ } | null;
+ }>;
+ }>(path.to.service(itemId));
+ const routeData = data ?? routeDataFromRoute;
+
+ const supplierParts = routeData?.supplierParts ?? [];
+
+ const fetcher = useFetcher<typeof action>();
+ useEffect(() => {
+ if (fetcher.data?.error) {
+ toast.error(fetcher.data.error.message);
+ }
+ }, [fetcher.data]);
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
+ const onUpdate = useCallback(
+ (
+ field:
+ | "name"
+ | "description"
+ | "replenishmentSystem"
+ | "defaultMethodType"
+ | "itemPostingGroupId"
+ | "serviceId"
+ | "active",
+ value: string | null
+ ) => {
+ const formData = new FormData();
+
+ formData.append("items", itemId);
+ formData.append("field", field);
+ formData.append("value", value?.toString() ?? "");
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.bulkUpdateItems
+ });
+ },
+
+ [itemId]
+ );
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
+ const onUpdateTags = useCallback(
+ (value: string[]) => {
+ const formData = new FormData();
+
+ formData.append("ids", routeData?.serviceSummary?.readableId ?? "");
+ formData.append("table", "service");
+ value.forEach((v) => {
+ formData.append("value", v);
+ });
+
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.tags
+ });
+ },
+
+ [routeData?.serviceSummary?.readableId]
+ );
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
+ const onUpdateCustomFields = useCallback(
+ (value: string) => {
+ const formData = new FormData();
+
+ formData.append("ids", routeData?.serviceSummary?.readableId ?? "");
+ formData.append("table", "service");
+ formData.append("value", value);
+
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.customFields
+ });
+ },
+
+ [routeData?.serviceSummary?.readableId]
+ );
+
+ const [suppliers] = useSuppliers();
+
+ return (
+ <VStack
+ spacing={4}
+ className="w-96 bg-card h-full overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent border-l border-border px-4 py-2 text-sm"
+ >
+ <VStack spacing={2}>
+ <HStack className="w-full justify-between">
+ <h3 className="text-xxs text-foreground/70 uppercase font-light tracking-wide">
+ <Trans>Properties</Trans>
+ </h3>
+ <HStack spacing={1}>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ aria-label={t`Link`}
+ size="sm"
+ className="p-1"
+ onClick={() =>
+ copyToClipboard(
+ window.location.origin + path.to.service(itemId)
+ )
+ }
+ >
+ <LuLink className="w-3 h-3" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <span>
+ <Trans>Copy link to service</Trans>
+ </span>
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ aria-label={t`Copy`}
+ size="sm"
+ className="p-1"
+ onClick={() =>
+ copyToClipboard(routeData?.serviceSummary?.id ?? "")
+ }
+ >
+ <LuKeySquare className="w-3 h-3" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <span>
+ <Trans>Copy service unique identifier</Trans>
+ </span>
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ aria-label={t`Copy`}
+ size="sm"
+ className="p-1"
+ onClick={() =>
+ copyToClipboard(
+ routeData?.serviceSummary?.readableIdWithRevision ?? ""
+ )
+ }
+ >
+ <LuCopy className="w-3 h-3" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <span>
+ <Trans>Copy service number</Trans>
+ </span>
+ </TooltipContent>
+ </Tooltip>
+ </HStack>
+ </HStack>
+ <VStack spacing={1} className="pt-2">
+ <ValidatedForm
+ defaultValues={{
+ serviceId:
+ routeData?.serviceSummary?.readableIdWithRevision ?? undefined
+ }}
+ validator={z.object({
+ serviceId: z.string()
+ })}
+ className="w-full -mt-2"
+ >
+ <span className="text-sm">
+ <InputControlled
+ label=""
+ name="serviceId"
+ inline
+ size="sm"
+ value={routeData?.serviceSummary?.readableId ?? ""}
+ onBlur={(e) => {
+ onUpdate("serviceId", e.target.value ?? null);
+ }}
+ className="text-muted-foreground"
+ />
+ </span>
+ </ValidatedForm>
+ <ValidatedForm
+ defaultValues={{
+ name: routeData?.serviceSummary?.name ?? undefined
+ }}
+ validator={z.object({
+ name: z.string()
+ })}
+ className="w-full -mt-2"
+ >
+ <span className="text-xs text-muted-foreground">
+ <InputControlled
+ label=""
+ name="name"
+ inline
+ size="sm"
+ characterLimit={40}
+ value={routeData?.serviceSummary?.name ?? ""}
+ onBlur={(e) => {
+ onUpdate("name", e.target.value ?? null);
+ }}
+ className="text-muted-foreground"
+ />
+ </span>
+ </ValidatedForm>
+ </VStack>
+ <ItemThumbnailUpload
+ path={routeData?.serviceSummary?.thumbnailPath}
+ itemId={itemId}
+ />
+ </VStack>
+
+ <ValidatedForm
+ defaultValues={{
+ itemPostingGroupId:
+ routeData?.serviceSummary?.itemPostingGroupId ?? undefined
+ }}
+ validator={z.object({
+ itemPostingGroupId: z.string().nullable().optional()
+ })}
+ className="w-full"
+ >
+ <ItemPostingGroup
+ label={t`Item Group`}
+ name="itemPostingGroupId"
+ inline
+ isClearable
+ onChange={(value) => {
+ onUpdate("itemPostingGroupId", value?.value ?? null);
+ }}
+ />
+ </ValidatedForm>
+
+ <ValidatedForm
+ defaultValues={{
+ replenishmentSystem:
+ routeData?.serviceSummary?.replenishmentSystem ?? undefined
+ }}
+ validator={z.object({
+ replenishmentSystem: z.string()
+ })}
+ className="w-full"
+ >
+ <Select
+ name="replenishmentSystem"
+ label={t`Replenishment`}
+ termId="replenishment-system"
+ inline={(value) => (
+ <Badge variant="secondary">
+ <ReplenishmentSystemIcon type={value} className="mr-2" />
+ <span>{value === "Buy" ? t`Buy` : t`Make`}</span>
+ </Badge>
+ )}
+ options={serviceReplenishmentSystems.map((system) => ({
+ value: system,
+ label: (
+ <span className="flex items-center gap-2">
+ <ReplenishmentSystemIcon type={system} />
+ {system === "Buy" ? t`Buy` : t`Make`}
+ </span>
+ )
+ }))}
+ onChange={(value) => {
+ onUpdate("replenishmentSystem", value?.value ?? null);
+ }}
+ />
+ </ValidatedForm>
+
+ <ValidatedForm
+ defaultValues={{
+ defaultMethodType:
+ routeData?.serviceSummary?.defaultMethodType ?? undefined
+ }}
+ validator={z.object({
+ defaultMethodType: z.string()
+ })}
+ className="w-full"
+ >
+ <Select
+ name="defaultMethodType"
+ label={t`Default Method Type`}
+ termId="item-default-method-type"
+ inline={(value) => (
+ <Badge variant="secondary">
+ <MethodIcon type={value} className="mr-2" />
+ <span>
+ {value === "Purchase to Order"
+ ? t`Purchase to Order`
+ : t`Make to Order`}
+ </span>
+ </Badge>
+ )}
+ options={methodType
+ .filter((type) => {
+ const replenishment =
+ routeData?.serviceSummary?.replenishmentSystem;
+ if (replenishment === "Buy") return type === "Purchase to Order";
+ if (replenishment === "Make") return type === "Make to Order";
+ return type !== "Pull from Inventory";
+ })
+ .map((type) => ({
+ value: type,
+ label: (
+ <span className="flex items-center gap-2">
+ <MethodIcon type={type} />
+ {type === "Purchase to Order"
+ ? t`Purchase to Order`
+ : t`Make to Order`}
+ </span>
+ )
+ }))}
+ onChange={(value) => {
+ onUpdate("defaultMethodType", value?.value ?? null);
+ }}
+ />
+ </ValidatedForm>
+
+ <VStack spacing={2}>
+ <h3 className="text-xs text-muted-foreground">
+ <Trans>Unit of Measure</Trans>
+ </h3>
+ {routeData?.serviceSummary?.unitOfMeasure && (
+ <Badge variant="secondary">
+ {routeData.serviceSummary.unitOfMeasure}
+ </Badge>
+ )}
+ </VStack>
+
+ <ItemDescription
+ value={routeData?.serviceSummary?.description ?? ""}
+ onChange={(value) => onUpdate("description", value)}
+ />
+
+ <VStack spacing={2}>
+ <HStack className="w-full justify-between">
+ <h3 className="text-xs text-muted-foreground">
+ <Trans>Methods</Trans>
+ </h3>
+ </HStack>
+ {routeData?.serviceSummary?.replenishmentSystem?.includes("Make") && (
+ <Suspense fallback={null}>
+ <Await resolve={routeData?.makeMethods}>
+ {(makeMethods) =>
+ makeMethods.data
+ ?.sort((a, b) => b.version - a.version)
+ .map((method) => {
+ return (
+ <MethodBadge
+ key={method.id}
+ type="Make to Order"
+ text={`Version ${method.version}`}
+ to={`${path.to.serviceDetails(itemId)}?methodId=${method.id}`}
+ />
+ );
+ })
+ }
+ </Await>
+ </Suspense>
+ )}
+ {routeData?.serviceSummary?.replenishmentSystem?.includes("Buy") &&
+ supplierParts.map((method) => (
+ <MethodBadge
+ key={method.id}
+ type="Purchase to Order"
+ text={
+ suppliers.find((s) => s.id === method.supplierId)?.name ?? ""
+ }
+ to={path.to.servicePurchasing(itemId)}
+ />
+ ))}
+ </VStack>
+ <ValidatedForm
+ defaultValues={{
+ active: routeData?.serviceSummary?.active ?? undefined
+ }}
+ validator={z.object({
+ active: zfd.checkbox()
+ })}
+ className="w-full"
+ >
+ <Boolean
+ label={t`Active`}
+ name="active"
+ variant="small"
+ onChange={(value) => {
+ onUpdate("active", value ? "on" : "off");
+ }}
+ />
+ </ValidatedForm>
+ {routeDataFromRoute?.supersession?.successor && (
+ <div className="w-full">
+ <h3 className="text-xs text-muted-foreground mb-1">
+ <Trans>Superseded By</Trans>
+ </h3>
+ <Link
+ to={path.to.service(routeDataFromRoute.supersession.successor.id)}
+ className="text-sm text-primary hover:underline"
+ >
+ {routeDataFromRoute.supersession.successor.readableIdWithRevision}
+ </Link>
+ {routeDataFromRoute.supersession.successorEffectivityDate && (
+ <p className="text-xs text-muted-foreground">
+ <Trans>
+ From {routeDataFromRoute.supersession.successorEffectivityDate}
+ </Trans>
+ </p>
+ )}
+ </div>
+ )}
+ {(routeDataFromRoute?.supersededBy?.length ?? 0) > 0 && (
+ <div className="w-full">
+ <h3 className="text-xs text-muted-foreground mb-1">
+ <Trans>Supersedes</Trans>
+ </h3>
+ {routeDataFromRoute?.supersededBy?.map(
+ (ref) =>
+ ref.predecessor && (
+ <Link
+ key={ref.predecessor.id}
+ to={path.to.service(ref.predecessor.id)}
+ className="block text-sm text-primary hover:underline"
+ >
+ {ref.predecessor.readableIdWithRevision}
+ </Link>
+ )
+ )}
+ </div>
+ )}
+ <ValidatedForm
+ defaultValues={{
+ tags: routeData?.serviceSummary?.tags ?? []
+ }}
+ validator={z.object({
+ tags: z.array(z.string()).optional()
+ })}
+ className="w-full"
+ >
+ <Tags
+ label={t`Tags`}
+ name="tags"
+ availableTags={routeData?.tags ?? []}
+ table="service"
+ inline
+ onChange={onUpdateTags}
+ />
+ </ValidatedForm>
+
+ <CustomFormInlineFields
+ customFields={
+ (routeData?.serviceSummary?.customFields ?? {}) as Record<
+ string,
+ Json
+ >
+ }
+ table="service"
+ tags={routeData?.serviceSummary?.tags ?? []}
+ onUpdate={onUpdateCustomFields}
+ />
+
+ <VStack spacing={2}>
+ <HStack className="w-full justify-between">
+ <h3 className="text-xs text-muted-foreground">
+ <Trans>Files</Trans>
+ </h3>
+ </HStack>
+
+ <Suspense fallback={null}>
+ <Await resolve={routeData?.files}>
+ {(files) =>
+ files?.map((file) => (
+ <FileBadge
+ key={file.id}
+ file={file}
+ itemId={itemId}
+ itemType="Service"
+ />
+ ))
+ }
+ </Await>
+ </Suspense>
+ </VStack>
+ </VStack>
+ );
+};
+
+export default ServiceProperties;
diff --git a/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx b/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx
new file mode 100644
index 0000000000..cef924dab6
--- /dev/null
+++ b/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx
@@ -0,0 +1,546 @@
+import {
+ Badge,
+ Button,
+ Checkbox,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuPortal,
+ DropdownMenuSeparator,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ HStack,
+ MenuIcon,
+ MenuItem,
+ MenuSub,
+ MenuSubContent,
+ MenuSubTrigger,
+ toast,
+ useDisclosure,
+ VStack
+} from "@carbon/react";
+
+import { Trans, useLingui } from "@lingui/react/macro";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useCallback, useEffect, useMemo, useState } from "react";
+import {
+ LuAlignJustify,
+ LuBookMarked,
+ LuCalendar,
+ LuCheck,
+ LuGitPullRequestArrow,
+ LuGroup,
+ LuLoaderCircle,
+ LuPencil,
+ LuTag,
+ LuTrash,
+ LuTruck,
+ LuUser
+} from "react-icons/lu";
+import { RxCodesandboxLogo } from "react-icons/rx";
+import { Link, useFetcher, useNavigate } from "react-router";
+import {
+ EmployeeAvatar,
+ Hyperlink,
+ ItemLifecycleBadge,
+ ItemThumbnail,
+ MethodIcon,
+ New,
+ Table
+} from "~/components";
+import { useItemPostingGroups } from "~/components/Form/ItemPostingGroup";
+import { ReplenishmentSystemIcon } from "~/components/Icons";
+import { ConfirmDelete } from "~/components/Modals";
+import { useDateFormatter, usePermissions } from "~/hooks";
+import { useCustomColumns } from "~/hooks/useCustomColumns";
+import { methodType } from "~/modules/shared";
+import type { action } from "~/routes/x+/items+/update";
+import { usePeople } from "~/stores";
+import { path } from "~/utils/path";
+import { serviceReplenishmentSystems } from "../../items.models";
+import type { Service } from "../../types";
+
+type ServicesTableProps = {
+ data: Service[];
+ tags: { name: string }[];
+ count: number;
+};
+
+// Services are Non-Inventory, so "Pull from Inventory" is never valid.
+const serviceMethodTypes = methodType.filter(
+ (type) => type !== "Pull from Inventory"
+);
+
+const ServicesTable = memo(({ data, tags, count }: ServicesTableProps) => {
+ const { t } = useLingui();
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+ const { formatDate } = useDateFormatter();
+
+ const translateReplenishment = useCallback(
+ (v: string) => (v === "Buy" ? t`Buy` : t`Make`),
+ [t]
+ );
+ const translateMethodType = useCallback(
+ (v: string) =>
+ v === "Purchase to Order" ? t`Purchase to Order` : t`Make to Order`,
+ [t]
+ );
+
+ const deleteItemModal = useDisclosure();
+ const [selectedItem, setSelectedItem] = useState<Service | null>(null);
+
+ const [people] = usePeople();
+ const itemPostingGroups = useItemPostingGroups();
+ const customColumns = useCustomColumns<Service>("service");
+
+ const columns = useMemo<ColumnDef<Service>[]>(() => {
+ const defaultColumns: ColumnDef<Service>[] = [
+ {
+ accessorKey: "id",
+ header: t`Service ID`,
+ cell: ({ row }) => (
+ <HStack className="py-1 min-w-[200px] truncate">
+ <ItemThumbnail
+ size="md"
+ thumbnailPath={row.original.thumbnailPath}
+ type="Service"
+ />
+ <Hyperlink to={path.to.serviceDetails(row.original.id!)}>
+ <VStack spacing={0}>
+ {row.original.readableIdWithRevision}
+ <div className="w-full truncate text-muted-foreground text-xs">
+ {row.original.name}
+ </div>
+ </VStack>
+ </Hyperlink>
+ </HStack>
+ ),
+ meta: {
+ icon: <LuBookMarked />
+ }
+ },
+ {
+ accessorKey: "description",
+ header: t`Description`,
+ cell: (item) => (
+ <div className="max-w-[320px] truncate">
+ {item.getValue<string>()}
+ </div>
+ ),
+ meta: {
+ icon: <LuAlignJustify />
+ }
+ },
+ {
+ accessorKey: "itemPostingGroupId",
+ header: t`Item Group`,
+ cell: (item) => {
+ const itemPostingGroupId = item.getValue<string>();
+ const itemPostingGroup = itemPostingGroups.find(
+ (group) => group.value === itemPostingGroupId
+ );
+ const label = itemPostingGroup?.label;
+ return label ? <Badge variant="secondary">{label}</Badge> : null;
+ },
+ meta: {
+ filter: {
+ type: "static",
+ options: itemPostingGroups.map((group) => ({
+ value: group.value,
+ label: <Badge variant="secondary">{group.label}</Badge>
+ }))
+ },
+ icon: <LuGroup />
+ }
+ },
+
+ {
+ accessorKey: "replenishmentSystem",
+ header: t`Replenishment`,
+ cell: (item) => (
+ <Badge variant="secondary">
+ <ReplenishmentSystemIcon
+ type={item.getValue<string>()}
+ className="mr-2"
+ />
+ <span>{translateReplenishment(item.getValue<string>())}</span>
+ </Badge>
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ options: serviceReplenishmentSystems.map((type) => ({
+ value: type,
+ label: (
+ <Badge variant="secondary">
+ <ReplenishmentSystemIcon type={type} className="mr-2" />
+ <span>{translateReplenishment(type)}</span>
+ </Badge>
+ )
+ }))
+ },
+ icon: <LuLoaderCircle />
+ }
+ },
+ {
+ accessorKey: "defaultMethodType",
+ header: t`Default Method`,
+ cell: (item) => (
+ <VStack spacing={1}>
+ <Badge variant="secondary">
+ <MethodIcon type={item.getValue<string>()} className="mr-2" />
+ <span>{translateMethodType(item.getValue<string>())}</span>
+ </Badge>
+ <ItemLifecycleBadge
+ mode={
+ (
+ item.row.original as {
+ supersessionMode?:
+ | "Consume First"
+ | "Prefer New"
+ | "Stock Only"
+ | "No Stock"
+ | null;
+ }
+ ).supersessionMode
+ }
+ />
+ </VStack>
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ options: serviceMethodTypes.map((value) => ({
+ value,
+ label: (
+ <Badge variant="secondary">
+ <MethodIcon type={value} className="mr-2" />
+ <span>{translateMethodType(value)}</span>
+ </Badge>
+ )
+ }))
+ },
+ icon: <RxCodesandboxLogo />
+ }
+ },
+ {
+ accessorKey: "tags",
+ header: t`Tags`,
+ cell: ({ row }) => (
+ <HStack spacing={0} className="gap-1">
+ {row.original.tags?.map((tag) => (
+ <Badge key={tag} variant="secondary">
+ {tag}
+ </Badge>
+ ))}
+ </HStack>
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ options: tags?.map((tag) => ({
+ value: tag.name,
+ label: <Badge variant="secondary">{tag.name}</Badge>
+ })),
+ isArray: true
+ },
+ icon: <LuTag />
+ }
+ },
+ {
+ accessorKey: "supplierIds",
+ header: t`Supplier Part Numbers`,
+ cell: ({ row }) => (
+ <HStack spacing={0} className="gap-1">
+ {row.original.supplierIds
+ ?.split(",")
+ .filter(Boolean)
+ .map((supplierPartId) => (
+ <Badge key={supplierPartId} variant="secondary">
+ {supplierPartId}
+ </Badge>
+ ))}
+ </HStack>
+ ),
+ meta: {
+ icon: <LuTruck />
+ }
+ },
+ {
+ accessorKey: "active",
+ header: t`Active`,
+ cell: (item) => <Checkbox isChecked={item.getValue<boolean>()} />,
+ meta: {
+ filter: {
+ type: "static",
+ options: [
+ { value: "true", label: t`Active` },
+ { value: "false", label: t`Inactive` }
+ ]
+ },
+ pluralHeader: t`Active Statuses`,
+ icon: <LuCheck />
+ }
+ },
+ {
+ id: "createdBy",
+ header: t`Created By`,
+ cell: ({ row }) => (
+ <EmployeeAvatar employeeId={row.original.createdBy} />
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ options: people.map((employee) => ({
+ value: employee.id,
+ label: employee.name
+ }))
+ },
+ icon: <LuUser />
+ }
+ },
+ {
+ accessorKey: "createdAt",
+ header: t`Created At`,
+ cell: (item) => formatDate(item.getValue<string>()),
+ meta: {
+ icon: <LuCalendar />
+ }
+ },
+ {
+ id: "updatedBy",
+ header: t`Updated By`,
+ cell: ({ row }) => (
+ <EmployeeAvatar employeeId={row.original.updatedBy} />
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ options: people.map((employee) => ({
+ value: employee.id,
+ label: employee.name
+ }))
+ },
+ icon: <LuUser />
+ }
+ },
+ {
+ accessorKey: "updatedAt",
+ header: t`Updated At`,
+ cell: (item) => formatDate(item.getValue<string>()),
+ meta: {
+ icon: <LuCalendar />
+ }
+ }
+ ];
+ return [...defaultColumns, ...customColumns];
+ }, [
+ customColumns,
+ people,
+ tags,
+ itemPostingGroups,
+ t,
+ translateMethodType,
+ translateReplenishment,
+ formatDate
+ ]);
+
+ const fetcher = useFetcher<typeof action>();
+ useEffect(() => {
+ if (fetcher.data?.error) {
+ toast.error(fetcher.data.error.message);
+ }
+ }, [fetcher.data]);
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
+ const onBulkUpdate = useCallback(
+ (
+ selectedRows: typeof data,
+ field: "replenishmentSystem" | "defaultMethodType" | "itemPostingGroupId",
+ value: string
+ ) => {
+ const formData = new FormData();
+ selectedRows.forEach((row) => {
+ if (row.id) formData.append("items", row.id);
+ });
+ formData.append("field", field);
+ formData.append("value", value);
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.bulkUpdateItems
+ });
+ },
+
+ []
+ );
+
+ const renderActions = useCallback(
+ (selectedRows: typeof data) => {
+ return (
+ <DropdownMenuContent align="end" className="min-w-[200px]">
+ <DropdownMenuLabel>
+ <Trans>Update</Trans>
+ </DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ <DropdownMenuGroup>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <Trans>Item Group</Trans>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuSubContent>
+ {itemPostingGroups.map((group) => (
+ <DropdownMenuItem
+ key={group.value}
+ onClick={() =>
+ onBulkUpdate(
+ selectedRows,
+ "itemPostingGroupId",
+ group.value
+ )
+ }
+ >
+ <span>{group.label}</span>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuPortal>
+ </DropdownMenuSub>
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <Trans>Default Method Type</Trans>
+ </DropdownMenuSubTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuSubContent>
+ {serviceMethodTypes.map((type) => (
+ <DropdownMenuItem
+ key={type}
+ onClick={() =>
+ onBulkUpdate(selectedRows, "defaultMethodType", type)
+ }
+ >
+ <DropdownMenuIcon icon={<MethodIcon type={type} />} />
+ <span>{translateMethodType(type)}</span>
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuPortal>
+ </DropdownMenuSub>
+ </DropdownMenuGroup>
+ </DropdownMenuContent>
+ );
+ },
+ [onBulkUpdate, itemPostingGroups, translateMethodType]
+ );
+
+ const renderContextMenu = useMemo(() => {
+ return (row: Service) => {
+ const revisions =
+ (row.revisions as {
+ id: string;
+ revision: number;
+ }[]) ?? [];
+ return (
+ <>
+ <MenuItem onClick={() => navigate(path.to.service(row.id!))}>
+ <MenuIcon icon={<LuPencil />} />
+ <Trans>Edit Service</Trans>
+ </MenuItem>
+ {revisions && revisions.length > 1 && (
+ <MenuSub>
+ <MenuSubTrigger>
+ <MenuIcon icon={<LuGitPullRequestArrow />} />
+ <Trans>Versions</Trans>
+ </MenuSubTrigger>
+ <MenuSubContent>
+ {revisions.map((revision) => (
+ <MenuItem
+ key={revision.id}
+ onClick={() => navigate(path.to.service(revision.id))}
+ >
+ <MenuIcon icon={<LuTag />} />
+ {t`Revision ${revision.revision}`}
+ </MenuItem>
+ ))}
+ </MenuSubContent>
+ </MenuSub>
+ )}
+ <MenuItem
+ destructive
+ disabled={!permissions.can("delete", "parts")}
+ onClick={() => {
+ setSelectedItem(row);
+ deleteItemModal.onOpen();
+ }}
+ >
+ <MenuIcon icon={<LuTrash />} />
+ <Trans>Delete Service</Trans>
+ </MenuItem>
+ </>
+ );
+ };
+ }, [deleteItemModal, navigate, permissions, t]);
+
+ return (
+ <>
+ <Table<Service>
+ count={count}
+ columns={columns}
+ data={data}
+ defaultColumnPinning={{
+ left: ["id"]
+ }}
+ defaultColumnVisibility={{
+ description: false,
+ active: false,
+ createdBy: false,
+ createdAt: false,
+ updatedBy: false,
+ updatedAt: false
+ }}
+ primaryAction={
+ permissions.can("create", "parts") && (
+ <div className="flex items-center gap-2">
+ <Button variant="secondary" leftIcon={<LuGroup />} asChild>
+ <Link to={path.to.itemPostingGroups}>
+ <Trans>Item Groups</Trans>
+ </Link>
+ </Button>
+ <New label={t`Service`} to={path.to.newService} />
+ </div>
+ )
+ }
+ renderActions={renderActions}
+ renderContextMenu={renderContextMenu}
+ title={t`Services`}
+ table="service"
+ withSavedView
+ withSelectableRows
+ />
+ {selectedItem && selectedItem.id && (
+ <ConfirmDelete
+ action={path.to.deleteItem(selectedItem.id!)}
+ isOpen={deleteItemModal.isOpen}
+ name={selectedItem.readableIdWithRevision!}
+ text={t`Are you sure you want to delete ${selectedItem.readableIdWithRevision!}? This cannot be undone.`}
+ onCancel={() => {
+ deleteItemModal.onClose();
+ setSelectedItem(null);
+ }}
+ onSubmit={() => {
+ deleteItemModal.onClose();
+ setSelectedItem(null);
+ }}
+ />
+ )}
+ </>
+ );
+});
+
+ServicesTable.displayName = "ServicesTable";
+
+export default ServicesTable;
diff --git a/apps/erp/app/modules/items/ui/Services/index.ts b/apps/erp/app/modules/items/ui/Services/index.ts
new file mode 100644
index 0000000000..6f7f5bd211
--- /dev/null
+++ b/apps/erp/app/modules/items/ui/Services/index.ts
@@ -0,0 +1,6 @@
+import ServiceForm from "./ServiceForm";
+import ServiceHeader from "./ServiceHeader";
+import ServiceProperties from "./ServiceProperties";
+import ServicesTable from "./ServicesTable";
+
+export { ServiceForm, ServiceHeader, ServiceProperties, ServicesTable };
diff --git a/apps/erp/app/modules/items/ui/Services/useServiceNavigation.tsx b/apps/erp/app/modules/items/ui/Services/useServiceNavigation.tsx
new file mode 100644
index 0000000000..2818373277
--- /dev/null
+++ b/apps/erp/app/modules/items/ui/Services/useServiceNavigation.tsx
@@ -0,0 +1,77 @@
+import { useLingui } from "@lingui/react/macro";
+import {
+ LuClipboardCheck,
+ LuFileText,
+ LuReceipt,
+ LuShoppingCart,
+ LuTags
+} from "react-icons/lu";
+import { useParams } from "react-router";
+import { usePermissions, useRouteData } from "~/hooks";
+import type { Role } from "~/types";
+import { path } from "~/utils/path";
+import type { ServiceSummary } from "../../types";
+
+export function useServiceNavigation() {
+ const { t } = useLingui();
+ const permissions = usePermissions();
+ const { itemId } = useParams();
+ if (!itemId) throw new Error("itemId not found");
+
+ const routeData = useRouteData<{
+ serviceSummary: ServiceSummary;
+ }>(path.to.service(itemId));
+ if (!routeData?.serviceSummary?.replenishmentSystem)
+ throw new Error("Could not find replenishmentSystem in routeData");
+
+ const replenishment = routeData.serviceSummary.replenishmentSystem;
+
+ return [
+ {
+ name: t`Details`,
+ to: path.to.serviceDetails(itemId),
+ icon: LuFileText,
+ shortcut: "Command+Shift+d"
+ },
+ {
+ name: t`Purchasing`,
+ to: path.to.servicePurchasing(itemId),
+ isDisabled: replenishment === "Make",
+ role: ["employee", "supplier"],
+ permission: "purchasing",
+ icon: LuShoppingCart,
+ shortcut: "Command+Shift+p"
+ },
+ {
+ name: t`Sales`,
+ to: path.to.serviceSales(itemId),
+ role: ["employee", "customer"],
+ icon: LuReceipt,
+ shortcut: "Command+Shift+x"
+ },
+ {
+ name: t`Accounting`,
+ to: path.to.serviceCosting(itemId),
+ role: ["employee"],
+ permission: "purchasing",
+ icon: LuTags,
+ shortcut: "Command+Shift+a"
+ },
+ {
+ name: t`Quality`,
+ to: path.to.serviceQuality(itemId),
+ isDisabled: !routeData?.serviceSummary?.requiresInspection,
+ role: ["employee"],
+ permission: "quality",
+ icon: LuClipboardCheck,
+ shortcut: "Command+Shift+q"
+ }
+ ].filter(
+ (item) =>
+ !item.isDisabled &&
+ (item.role === undefined ||
+ item.role.some((role) => permissions.is(role as Role))) &&
+ (item.permission === undefined ||
+ permissions.can("view", item.permission))
+ );
+}
diff --git a/apps/erp/app/modules/items/ui/useItemsSubmodules.tsx b/apps/erp/app/modules/items/ui/useItemsSubmodules.tsx
index 9d0beed466..0ee673f335 100644
--- a/apps/erp/app/modules/items/ui/useItemsSubmodules.tsx
+++ b/apps/erp/app/modules/items/ui/useItemsSubmodules.tsx
@@ -8,6 +8,7 @@ import {
LuGlassWater,
LuGroup,
LuHammer,
+ LuHeadphones,
LuPizza,
LuPuzzle,
LuRuler,
@@ -49,6 +50,12 @@ export default function useItemsSubmodules() {
to: path.to.consumables,
icon: <LuPizza />,
table: "consumable"
+ },
+ {
+ name: t`Services`,
+ to: path.to.services,
+ icon: <LuHeadphones />,
+ table: "service"
}
]
},
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.ts
index afb6ddb754..dfb362af2a 100644
--- a/apps/erp/app/modules/production/production.models.ts
+++ b/apps/erp/app/modules/production/production.models.ts
@@ -709,18 +709,6 @@ export const jobMaterialValidator = baseMaterialValidator
path: ["itemId"]
}
)
- .refine(
- (data) => {
- if (data.itemType === "Tool") {
- return !!data.itemId;
- }
- return true;
- },
- {
- message: "Tool ID is required",
- path: ["itemId"]
- }
- )
.refine(
(data) => {
if (data.itemType === "Consumable") {
@@ -762,18 +750,6 @@ export const jobMaterialValidatorForReleasedJob = baseMaterialValidator
path: ["itemId"]
}
)
- .refine(
- (data) => {
- if (data.itemType === "Tool") {
- return !!data.itemId;
- }
- return true;
- },
- {
- message: "Tool ID is required",
- path: ["itemId"]
- }
- )
.refine(
(data) => {
if (data.itemType === "Consumable") {
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 2ff20391d1..3ebdb27c70 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -142,7 +142,7 @@ export async function convertSalesOrderLinesToJobs(
.select("*")
.eq("itemId", line.itemId)
.eq("companyId", companyId)
- .single();
+ .maybeSingle();
const lotSize = manufacturing.data?.lotSize ?? 0;
const totalQuantity = line.saleQuantity ?? 0;
@@ -187,12 +187,16 @@ export async function convertSalesOrderLinesToJobs(
}
}
- const storageUnitId = await getDefaultStorageUnitForJob(
- client,
- line.itemId,
- locationId!,
- companyId
- );
+ // Services are Non-Inventory and never have storage units
+ const storageUnitId =
+ line.salesOrderLineType === "Service"
+ ? null
+ : await getDefaultStorageUnitForJob(
+ client,
+ line.itemId,
+ locationId!,
+ companyId
+ );
// Calculate scrap quantity based on item's scrap percentage
const scrapPercentage = manufacturing.data?.scrapPercentage ?? 0;
diff --git a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx
index 82cc689642..ce3f749108 100644
--- a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx
+++ b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx
@@ -40,7 +40,7 @@ import { Enumerable } from "~/components/Enumerable";
import { useLocations } from "~/components/Form/Location";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
import { usePermissions } from "~/hooks";
-import { itemTypes } from "~/modules/inventory/inventory.models";
+import { inventoryItemTypes } from "~/modules/inventory/inventory.models";
import { itemReorderingPolicies } from "~/modules/items/items.models";
import {
clearOrdersCache,
@@ -372,7 +372,7 @@ const ProductionPlanningTable = ({
meta: {
filter: {
type: "static",
- options: itemTypes
+ options: inventoryItemTypes
.filter((t) => ["Part", "Tool"].includes(t))
.map((type) => ({
label: (
diff --git a/apps/erp/app/modules/purchasing/purchasing.models.ts b/apps/erp/app/modules/purchasing/purchasing.models.ts
index daa43368d3..d1a27b25af 100644
--- a/apps/erp/app/modules/purchasing/purchasing.models.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.models.ts
@@ -2,7 +2,7 @@ import { getLocalTimeZone, today } from "@internationalized/date";
import { z } from "zod";
import { zfd } from "zod-form-data";
import { address, contact } from "~/types/validators";
-import { incoterms, methodItemType, taxExemptionReasons } from "../shared";
+import { incoterms, itemType, taxExemptionReasons } from "../shared";
export const KPIs = [
{
@@ -33,7 +33,7 @@ export const KPIs = [
export const purchaseOrderLineType = [
"Part",
- // "Service",
+ "Service",
"Material",
"Tool",
"Consumable",
@@ -207,7 +207,7 @@ export const purchaseOrderLineValidator = z
id: zfd.text(z.string().optional()),
purchaseOrderId: z.string().min(1, { message: "Order is required" }),
purchaseOrderLineType: z.enum(
- [...methodItemType, "Service", "Fixture", "G/L Account", "Fixed Asset"],
+ [...itemType, "Fixture", "G/L Account", "Fixed Asset"],
{
errorMap: (issue, ctx) => ({
message: "Type is required"
@@ -475,7 +475,7 @@ export const supplierQuoteLineValidator = z
.object({
id: zfd.text(z.string().optional()),
supplierQuoteId: z.string(),
- supplierQuoteLineType: z.enum([...methodItemType, "G/L Account"], {
+ supplierQuoteLineType: z.enum([...itemType, "G/L Account"], {
errorMap: () => ({ message: "Type is required" })
}),
itemId: zfd.text(z.string().optional()),
diff --git a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
index 6e2e541c06..925a776632 100644
--- a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
+++ b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx
@@ -49,7 +49,7 @@ import { Enumerable } from "~/components/Enumerable";
import { useLocations } from "~/components/Form/Location";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
import { usePermissions } from "~/hooks";
-import { itemTypes } from "~/modules/inventory/inventory.models";
+import { inventoryItemTypes } from "~/modules/inventory/inventory.models";
import { itemReorderingPolicies } from "~/modules/items/items.models";
import type { SupplierPart } from "~/modules/items/types";
import {
@@ -507,7 +507,7 @@ const PlanningTable = memo(
meta: {
filter: {
type: "static",
- options: itemTypes
+ options: inventoryItemTypes
.filter((t) => ["Part", "Tool"].includes(t))
.map((type) => ({
label: (
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx
index 2f75fa3cdd..153cb4a010 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx
@@ -43,8 +43,8 @@ import {
useUser
} from "~/hooks";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
-import type { MethodItemType } from "~/modules/shared";
-import { methodItemType } from "~/modules/shared";
+import type { ItemType } from "~/modules/shared";
+import { itemType } from "~/modules/shared";
import { useItems } from "~/stores";
import { path } from "~/utils/path";
import { isPurchaseOrderLocked } from "../../purchasing.models";
@@ -66,7 +66,7 @@ export default function PurchaseOrderExplorer() {
const purchaseOrderLineInitialValues = {
purchaseOrderId: orderId,
- purchaseOrderLineType: "Item" as MethodItemType,
+ purchaseOrderLineType: "Item" as ItemType,
purchaseQuantity: 1,
supplierUnitPrice: 0,
locationId:
@@ -349,12 +349,13 @@ function PurchaseOrderLineItem({
<DropdownMenuIcon icon={<LuTrash />} />
<Trans>Delete Line</Trans>
</DropdownMenuItem>
- {/* @ts-expect-error */}
- {methodItemType.includes(line?.purchaseOrderLineType ?? "") && (
+ {(itemType as readonly string[]).includes(
+ line?.purchaseOrderLineType ?? ""
+ ) && (
<DropdownMenuItem asChild>
<Link
to={getLinkToItemDetails(
- line.purchaseOrderLineType as MethodItemType,
+ line.purchaseOrderLineType as ItemType,
line.itemId!
)}
>
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx
index 70e970b85f..c6310381f9 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx
@@ -67,7 +67,11 @@ import {
isPurchaseOrderLocked,
purchaseOrderLineValidator
} from "~/modules/purchasing";
-import { type MethodItemType, resolveSupplierPrice } from "~/modules/shared";
+import {
+ type ItemType,
+ itemType,
+ resolveSupplierPrice
+} from "~/modules/shared";
import type { action } from "~/routes/x+/purchase-order+/$orderId.$lineId.details";
import { useItems } from "~/stores";
import { path } from "~/utils/path";
@@ -121,8 +125,8 @@ const PurchaseOrderLineForm = ({
routeData?.purchaseOrder?.purchaseOrderType === "Outside Processing";
const isLocked = isPurchaseOrderLocked(routeData?.purchaseOrder?.status);
- const [itemType, setItemType] = useState<MethodItemType>(
- initialValues.purchaseOrderLineType as MethodItemType
+ const [lineType, setLineType] = useState<ItemType>(
+ initialValues.purchaseOrderLineType as ItemType
);
const [locationId, setLocationId] = useState(initialValues.locationId);
const [itemData, setItemData] = useState<{
@@ -315,9 +319,9 @@ const PurchaseOrderLineForm = ({
const currencyFormatter = useCurrencyFormatter();
const percentFormatter = usePercentFormatter();
- const onTypeChange = (t: MethodItemType | "Item") => {
- if (t === itemType) return;
- setItemType(t as MethodItemType);
+ const onTypeChange = (t: ItemType | "Item") => {
+ if (t === lineType) return;
+ setLineType(t as ItemType);
setItemData({
itemId: "",
conversionFactor: 1,
@@ -340,14 +344,13 @@ const PurchaseOrderLineForm = ({
const onItemChange = async (itemId: string) => {
if (!carbon) throw new Error("Carbon client not found");
- switch (itemType) {
+ switch (lineType) {
// @ts-expect-error
case "Item":
case "Consumable":
case "Material":
case "Part":
case "Tool":
- // @ts-expect-error
case "Service":
// @ts-expect-error
case "Fixture":
@@ -426,13 +429,13 @@ const PurchaseOrderLineForm = ({
});
if (item.data?.type) {
- setItemType(item.data.type as MethodItemType);
+ setLineType(item.data.type as ItemType);
}
break;
default:
throw new Error(
- `Invalid purchase order line type: ${itemType} is not implemented`
+ `Invalid purchase order line type: ${lineType} is not implemented`
);
}
};
@@ -599,7 +602,7 @@ const PurchaseOrderLineForm = ({
/>
<TabsContent value="item">
- <Hidden name="purchaseOrderLineType" value={itemType} />
+ <Hidden name="purchaseOrderLineType" value={lineType} />
<Hidden
name="inventoryUnitOfMeasureCode"
value={itemData?.inventoryUom}
@@ -608,8 +611,9 @@ const PurchaseOrderLineForm = ({
<div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
<Item
name="itemId"
- label={i18n._(itemTypeLabel(itemType))}
- type={itemType}
+ label={i18n._(itemTypeLabel(lineType))}
+ type={lineType}
+ validItemTypes={[...itemType]}
locationId={locationId}
replenishmentSystem={
isOutsideProcessing ? undefined : "Buy"
@@ -686,7 +690,7 @@ const PurchaseOrderLineForm = ({
"Tool",
"Service",
"Fixture"
- ].includes(itemType) && (
+ ].includes(lineType) && (
<>
<UnitOfMeasure
name="purchaseUnitOfMeasureCode"
@@ -741,7 +745,7 @@ const PurchaseOrderLineForm = ({
"Tool",
"Consumable",
"Fixture"
- ].includes(itemType) &&
+ ].includes(lineType) &&
!isOutsideProcessing && (
<Location
name="locationId"
@@ -754,12 +758,11 @@ const PurchaseOrderLineForm = ({
{[
"Item",
"Part",
- "Service",
"Material",
"Tool",
"Consumable",
"Fixture"
- ].includes(itemType) &&
+ ].includes(lineType) &&
!isOutsideProcessing && (
<StorageUnit
name="storageUnitId"
diff --git a/apps/erp/app/modules/purchasing/ui/PurchasingRfq/PurchasingRFQLineForm.tsx b/apps/erp/app/modules/purchasing/ui/PurchasingRfq/PurchasingRFQLineForm.tsx
index 1e4b735da5..03d52a7a75 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchasingRfq/PurchasingRFQLineForm.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchasingRfq/PurchasingRFQLineForm.tsx
@@ -39,7 +39,7 @@ import {
UnitOfMeasure
} from "~/components/Form";
import { usePermissions, useRouteData, useUser } from "~/hooks";
-import type { MethodItemType } from "~/modules/shared/types";
+import type { ItemType } from "~/modules/shared/types";
import { path } from "~/utils/path";
import {
isRfqLocked,
@@ -50,7 +50,7 @@ import DeletePurchasingRFQLine from "./DeletePurchasingRFQLine";
type PurchasingRFQLineFormProps = {
initialValues: z.infer<typeof purchasingRfqLineValidator> & {
- itemType: MethodItemType;
+ itemType: ItemType;
};
type?: "card" | "modal";
onClose?: () => void;
@@ -78,9 +78,7 @@ const PurchasingRFQLineForm = ({
const isEditing = initialValues.id !== undefined;
- const [itemType, setItemType] = useState<MethodItemType>(
- initialValues.itemType
- );
+ const [itemType, setItemType] = useState<ItemType>(initialValues.itemType);
const [itemData, setItemData] = useState<{
itemId: string;
itemReadableId: string;
@@ -124,7 +122,7 @@ const PurchasingRFQLineForm = ({
setItemData(newItemData);
if (item.data?.type) {
- setItemType(item.data.type as MethodItemType);
+ setItemType(item.data.type as ItemType);
}
};
@@ -225,7 +223,7 @@ const PurchasingRFQLineForm = ({
onItemChange(value?.value as string);
}}
onTypeChange={(type) => {
- setItemType(type as MethodItemType);
+ setItemType(type as ItemType);
setItemData({
...itemData,
itemId: "",
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteExplorer.tsx b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteExplorer.tsx
index fce69b4f28..5a6c49a5ed 100644
--- a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteExplorer.tsx
+++ b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteExplorer.tsx
@@ -38,8 +38,8 @@ import {
} from "~/components/LineReorder";
import { useOptimisticLocation, usePermissions, useRouteData } from "~/hooks";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
-import type { MethodItemType } from "~/modules/shared";
-import { methodItemType } from "~/modules/shared";
+import type { ItemType } from "~/modules/shared";
+import { itemType } from "~/modules/shared";
import { useItems } from "~/stores";
import { path } from "~/utils/path";
import { isSupplierQuoteLocked } from "../../purchasing.models";
@@ -262,7 +262,7 @@ function SupplierQuoteLineItem({
const { id, lineId } = useParams();
if (!id) throw new Error("Could not find id");
const [items] = useItems();
- const itemType = items.find((i) => i.id === line.itemId)?.type;
+ const lineItemType = items.find((i) => i.id === line.itemId)?.type;
const permissions = usePermissions();
const disclosure = useDisclosure();
const location = useOptimisticLocation();
@@ -332,22 +332,22 @@ function SupplierQuoteLineItem({
<Trans>Delete Line</Trans>
</DropdownMenuItem>
- {itemType &&
- methodItemType.includes(itemType as MethodItemType) && (
+ {lineItemType &&
+ itemType.includes(lineItemType as ItemType) && (
<DropdownMenuItem
asChild
onClick={(e) => e.stopPropagation()}
>
<Link
to={getLinkToItemDetails(
- itemType as MethodItemType,
+ lineItemType as ItemType,
line.itemId!
)}
>
<DropdownMenuIcon
icon={
<MethodItemTypeIcon
- type={itemType as MethodItemType}
+ type={lineItemType as ItemType}
/>
}
/>
diff --git a/apps/erp/app/modules/sales/sales.models.ts b/apps/erp/app/modules/sales/sales.models.ts
index ec4e22317d..1bbdb3652a 100644
--- a/apps/erp/app/modules/sales/sales.models.ts
+++ b/apps/erp/app/modules/sales/sales.models.ts
@@ -4,6 +4,7 @@ import { address, contact } from "~/types/validators";
import { currencyCodes } from "../accounting";
import {
incoterms,
+ itemType,
methodItemType,
methodOperationOrders,
methodType,
@@ -326,6 +327,7 @@ export const quoteLineCategoryMarkupsValidator = z
export const quoteLineValidator = z.object({
id: zfd.text(z.string().optional()),
quoteId: z.string(),
+ itemType: z.enum(itemType).optional(),
itemId: z.string().min(1, { message: "Part is required" }),
status: z.enum(quoteLineStatusType, {
errorMap: () => ({ message: "Status is required" })
@@ -403,18 +405,6 @@ export const quoteMaterialValidator = z
path: ["itemId"]
}
)
- .refine(
- (data) => {
- if (data.itemType === "Tool") {
- return !!data.itemId;
- }
- return true;
- },
- {
- message: "Tool ID is required",
- path: ["itemId"]
- }
- )
.refine(
(data) => {
if (data.itemType === "Consumable") {
@@ -656,7 +646,7 @@ export const quoteShipmentValidator = z.object({
export const salesOrderLineType = [
"Part",
- // "Service",
+ "Service",
"Material",
"Tool",
"Consumable",
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteLineForm.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
index b02b7aadde..1992536eb3 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
@@ -43,6 +43,7 @@ import {
SelectControlled,
Submit
} from "~/components/Form";
+import { itemTypeLabel } from "~/components/Form/itemTypeLabel";
import { QuoteLineStatusIcon } from "~/components/Icons";
import {
usePercentFormatter,
@@ -55,7 +56,8 @@ import type {
ConfigurationParameterGroup
} from "~/modules/items/types";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
-import { methodType } from "~/modules/shared";
+import type { ItemType } from "~/modules/shared";
+import { itemType, methodType } from "~/modules/shared";
import type { action } from "~/routes/x+/quote+/$quoteId.new";
import { useItems } from "~/stores";
import { path } from "~/utils/path";
@@ -78,7 +80,7 @@ const QuoteLineForm = ({
type,
onClose
}: QuoteLineFormProps) => {
- const { t } = useLingui();
+ const { t, i18n } = useLingui();
const fetcher = useFetcher<typeof action>();
const permissions = usePermissions();
const { company } = useUser();
@@ -116,6 +118,35 @@ const QuoteLineForm = ({
modelUploadId: initialValues.modelUploadId ?? null
});
+ const [lineType, setLineType] = useState<ItemType>(
+ (initialValues.itemType as ItemType) ?? "Part"
+ );
+
+ const onTypeChange = (t: ItemType | "Item") => {
+ if (t === "Item") return;
+ setLineType(t);
+ if (itemData.itemId) {
+ const currentType = items.find((i) => i.id === itemData.itemId)?.type;
+ if (currentType === t) return;
+ setItemData({
+ customerPartId: "",
+ customerPartRevision: "",
+ itemId: "",
+ description: "",
+ methodType: "",
+ uom: "EA",
+ modelUploadId: null
+ });
+ // Clearing the item must also clear its configuration — otherwise a
+ // configured Part's stale parameters/values remain submittable after
+ // switching to a different item type.
+ setRequiresConfiguration(false);
+ setIsConfigured(false);
+ setConfigurationParameters(null);
+ setConfigurationValues("");
+ }
+ };
+
const configurationDisclosure = useDisclosure();
const [requiresConfiguration, setRequiresConfiguration] = useState(false);
const [isConfigured, setIsConfigured] = useState(false);
@@ -338,10 +369,13 @@ const QuoteLineForm = ({
)}
<DropdownMenuItem asChild>
<Link
- to={getLinkToItemDetails("Part", itemData.itemId!)}
+ to={getLinkToItemDetails(
+ lineType,
+ itemData.itemId!
+ )}
>
<DropdownMenuIcon
- icon={<MethodItemTypeIcon type="Part" />}
+ icon={<MethodItemTypeIcon type={lineType} />}
/>
<Trans>View Item Master</Trans>
</Link>
@@ -371,14 +405,17 @@ const QuoteLineForm = ({
<Item
autoFocus
name="itemId"
- label={t`Part`}
- type="Part"
+ label={i18n._(itemTypeLabel(lineType))}
+ type={lineType}
+ typeFieldName="itemType"
+ validItemTypes={[...itemType]}
value={itemData.itemId}
includeInactive
locationId={routeData?.quote?.locationId ?? undefined}
onChange={(value) => {
onItemChange(value?.value as string);
}}
+ onTypeChange={onTypeChange}
/>
<InputControlled
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx
index a185a8639e..112f325a9d 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderExplorer.tsx
@@ -59,8 +59,8 @@ import {
useUser
} from "~/hooks";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
-import type { MethodItemType } from "~/modules/shared";
-import { methodItemType } from "~/modules/shared";
+import type { ItemType } from "~/modules/shared";
+import { itemType } from "~/modules/shared";
import { useItems } from "~/stores/items";
import { path } from "~/utils/path";
import { isSalesOrderLocked } from "../../sales.models";
@@ -431,14 +431,14 @@ function SalesOrderLineItem({
<Trans>Delete Line</Trans>
</DropdownMenuItem>
{/* @ts-expect-error */}
- {methodItemType.includes(line?.salesOrderLineType ?? "") && (
+ {itemType.includes(line?.salesOrderLineType ?? "") && (
<DropdownMenuItem
asChild
onClick={(e) => e.stopPropagation()}
>
<Link
to={getLinkToItemDetails(
- line.salesOrderLineType as MethodItemType,
+ line.salesOrderLineType as ItemType,
line.itemId!
)}
>
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
index 31752bc959..21d33e118e 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineForm.tsx
@@ -76,7 +76,7 @@ import {
useUser
} from "~/hooks";
import { getDefaultStorageUnitForJob } from "~/modules/inventory/inventory.service";
-import { methodType } from "~/modules/shared";
+import { itemType, methodType } from "~/modules/shared";
import { useItems } from "~/stores";
import { path } from "~/utils/path";
import {
@@ -579,6 +579,7 @@ const SalesOrderLineForm = ({
name="itemId"
label={i18n._(itemTypeLabel(lineType as "Part"))}
type={lineType as "Part"}
+ validItemTypes={[...itemType]}
typeFieldName="salesOrderLineType"
value={itemData.itemId}
locationId={locationId}
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx
index 6c0011f64e..700ebaf81e 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderSummary.tsx
@@ -128,11 +128,26 @@ const SalesOrderSummary = ({
routeData?.lines?.some((line) => line.methodType === "Make to Order") ??
false;
+ // Services never ship, so an all-service order confirms straight to
+ // "To Invoice" (getSalesOrderStatus counts Service lines as shipped) and
+ // never passes through the "To Ship" states — but its Make to Order
+ // service lines still need jobs.
+ const hasMakeServiceItems =
+ routeData?.lines?.some(
+ (line) =>
+ line.methodType === "Make to Order" &&
+ line.salesOrderLineType === "Service"
+ ) ?? false;
+
+ const jobsCardStatusMatches =
+ ["To Ship and Invoice", "To Ship"].includes(
+ routeData?.salesOrder?.status ?? ""
+ ) ||
+ (routeData?.salesOrder?.status === "To Invoice" && hasMakeServiceItems);
+
return (
<>
- {["To Ship and Invoice", "To Ship"].includes(
- routeData?.salesOrder?.status ?? ""
- ) &&
+ {jobsCardStatusMatches &&
permissions.can("create", "production") &&
permissions.is("employee") &&
!routeData?.salesOrder?.jobs &&
diff --git a/apps/erp/app/modules/shared/shared.models.ts b/apps/erp/app/modules/shared/shared.models.ts
index 38238acee4..fb86e849bf 100644
--- a/apps/erp/app/modules/shared/shared.models.ts
+++ b/apps/erp/app/modules/shared/shared.models.ts
@@ -114,16 +114,26 @@ export const tablesWithTags = [
"job",
"material",
"part",
+ "service",
"suggestion",
"tool"
];
-export const methodItemType = [
+// Item types that can appear as a BOM/method material component. Tool and
+// Service are intentionally excluded — tools attach to operations
+// (methodOperationTool) and services are billable activities bought or
+// performed; neither is ever consumed as a component.
+export const methodItemType = ["Part", "Material", "Consumable"] as const;
+
+// Item types that can appear as a top-level quote/sales-order/purchase-order/
+// invoice line. Tools and services are bought and sold even though neither is
+// a method component, so this is wider than methodItemType.
+export const itemType = [
"Part",
"Material",
"Tool",
- "Consumable"
- // "Service",
+ "Consumable",
+ "Service"
] as const;
export const months = [
diff --git a/apps/erp/app/modules/shared/types.ts b/apps/erp/app/modules/shared/types.ts
index 641955b07c..ae36943ece 100644
--- a/apps/erp/app/modules/shared/types.ts
+++ b/apps/erp/app/modules/shared/types.ts
@@ -6,6 +6,7 @@ import type {
ApprovalDocumentType,
approvalRequestValidator,
approvalRuleValidator,
+ itemType,
methodItemType,
methodType,
operationParameterValidator,
@@ -92,6 +93,8 @@ export enum DataType {
}
export type MethodItemType = (typeof methodItemType)[number];
+
+export type ItemType = (typeof itemType)[number];
export type MethodType = (typeof methodType)[number];
export type SourcingType = (typeof sourcingType)[number];
diff --git a/apps/erp/app/modules/storage-rules/ui/ItemFilterSelector.tsx b/apps/erp/app/modules/storage-rules/ui/ItemFilterSelector.tsx
index 7fa473431e..4dfbf5d47f 100644
--- a/apps/erp/app/modules/storage-rules/ui/ItemFilterSelector.tsx
+++ b/apps/erp/app/modules/storage-rules/ui/ItemFilterSelector.tsx
@@ -14,20 +14,23 @@ import { AnimatePresence, motion } from "framer-motion";
import { LuBox, LuDroplet, LuFilter, LuLayers, LuWrench } from "react-icons/lu";
import { MultiSelect } from "~/components/Form";
import { useItemPostingGroups } from "~/components/Form/ItemPostingGroup";
-import { itemTypes } from "~/modules/inventory/inventory.models";
-
-const ITEM_TYPE_ICON: Record<(typeof itemTypes)[number], JSX.Element> = {
- Part: <LuBox />,
- Material: <LuLayers />,
- Tool: <LuWrench />,
- Consumable: <LuDroplet />
-};
-
-const ITEM_TYPE_OPTIONS: ChoiceSelectOption<string>[] = itemTypes.map((t) => ({
- value: t,
- title: t,
- icon: ITEM_TYPE_ICON[t]
-}));
+import { inventoryItemTypes } from "~/modules/inventory/inventory.models";
+
+const ITEM_TYPE_ICON: Record<(typeof inventoryItemTypes)[number], JSX.Element> =
+ {
+ Part: <LuBox />,
+ Material: <LuLayers />,
+ Tool: <LuWrench />,
+ Consumable: <LuDroplet />
+ };
+
+const ITEM_TYPE_OPTIONS: ChoiceSelectOption<string>[] = inventoryItemTypes.map(
+ (t) => ({
+ value: t,
+ title: t,
+ icon: ITEM_TYPE_ICON[t]
+ })
+);
function ItemTypesField() {
const { t } = useLingui();
diff --git a/apps/erp/app/modules/storage-rules/ui/useValueOptions.ts b/apps/erp/app/modules/storage-rules/ui/useValueOptions.ts
index 3296031190..c019bd4a29 100644
--- a/apps/erp/app/modules/storage-rules/ui/useValueOptions.ts
+++ b/apps/erp/app/modules/storage-rules/ui/useValueOptions.ts
@@ -3,7 +3,7 @@ import { useMemo } from "react";
import { useItemPostingGroups } from "~/components/Form/ItemPostingGroup";
import { useLocations } from "~/components/Form/Location";
import { useStorageTypes } from "~/components/Form/StorageTypes";
-import { itemTypes } from "~/modules/inventory/inventory.models";
+import { inventoryItemTypes } from "~/modules/inventory/inventory.models";
import {
itemReplenishmentSystems,
itemTrackingTypes
@@ -21,8 +21,10 @@ export type ValueOptionsByLoader = Partial<
const enumOptions = (arr: readonly string[]): ValueOption[] =>
arr.map((v) => ({ value: v, label: v }));
-// Module-level constants — stable refs, never re-allocated.
-const ITEM_TYPES_OPTIONS = enumOptions(itemTypes);
+// Module-level constants — stable refs, never re-allocated. (The `itemTypes`
+// key returned below is the persisted field-registry loader name from
+// @carbon/utils ValueOptionsLoader — only the option SOURCE is renamed.)
+const ITEM_TYPES_OPTIONS = enumOptions(inventoryItemTypes);
const ITEM_TRACKING_TYPES_OPTIONS = enumOptions(itemTrackingTypes);
const REPLENISHMENT_SYSTEMS_OPTIONS = enumOptions(itemReplenishmentSystems);
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index bedb749e7a..c48a40ca58 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,5 +1,5 @@
{
- "generated": "2026-07-14T22:27:32.390Z",
+ "generated": "2026-07-15T00:11:05.860Z",
"totalTools": 1331,
"modules": 15,
"tools": [
@@ -12506,7 +12506,7 @@
"module": "items",
"classification": "READ",
"description": "get services",
- "paramCount": 6,
+ "paramCount": 5,
"serviceParams": [
"client",
"companyId",
@@ -12535,12 +12535,6 @@
"null"
]
},
- "type": {
- "type": [
- "string",
- "null"
- ]
- },
"group": {
"type": [
"string",
@@ -35311,7 +35305,7 @@
"module": "sales",
"classification": "WRITE",
"description": "upsert quote line",
- "paramCount": 4,
+ "paramCount": 5,
"serviceParams": [
"client",
"quotationLine"
@@ -35330,6 +35324,9 @@
"quoteId": {
"type": "string"
},
+ "itemType": {
+ "type": "string"
+ },
"itemId": {
"type": "string"
},
diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.$supplierPartId.tsx
index afd9e267d4..07ab4d0011 100644
--- a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.$supplierPartId.tsx
+++ b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.$supplierPartId.tsx
@@ -80,6 +80,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const updatedSupplierPart = await upsertSupplierPart(client, {
id: supplierPartId,
...d,
+ companyId,
updatedBy: userId,
customFields: setCustomFields(formData)
});
diff --git a/apps/erp/app/routes/x+/items+/$itemId.properties.tsx b/apps/erp/app/routes/x+/items+/$itemId.properties.tsx
index ae62c7acad..75aa56b6ca 100644
--- a/apps/erp/app/routes/x+/items+/$itemId.properties.tsx
+++ b/apps/erp/app/routes/x+/items+/$itemId.properties.tsx
@@ -21,7 +21,7 @@ import {
getTool
} from "~/modules/items";
import { getLocationsList } from "~/modules/resources";
-import { getTagsList, methodItemType } from "~/modules/shared";
+import { getTagsList } from "~/modules/shared";
import type { ListItem } from "~/types";
type CommonFields = {
@@ -59,9 +59,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const url = new URL(request.url);
const typeParam = url.searchParams.get("type");
- const type = (methodItemType as readonly string[]).includes(typeParam ?? "")
- ? (typeParam as (typeof methodItemType)[number])
- : "Part";
+ // Own-key check: `in` also accepts inherited keys, so e.g. ?type=toString
+ // would pass and crash on the destructure below.
+ const type =
+ typeParam && Object.prototype.hasOwnProperty.call(typeConfig, typeParam)
+ ? (typeParam as keyof typeof typeConfig)
+ : "Part";
const { tagTable, getSummary } = typeConfig[type];
const needsMakeMethods = type === "Part" || type === "Tool";
diff --git a/apps/erp/app/routes/x+/items+/services.tsx b/apps/erp/app/routes/x+/items+/services.tsx
new file mode 100644
index 0000000000..2e9603051b
--- /dev/null
+++ b/apps/erp/app/routes/x+/items+/services.tsx
@@ -0,0 +1,71 @@
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { VStack } from "@carbon/react";
+import { msg } from "@lingui/core/macro";
+import type { LoaderFunctionArgs } from "react-router";
+import { Outlet, redirect, useLoaderData } from "react-router";
+import { getServices } from "~/modules/items";
+import { ServicesTable } from "~/modules/items/ui/Services";
+import { getTagsList } from "~/modules/shared";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export const handle: Handle = {
+ breadcrumb: msg`Services`,
+ to: path.to.services
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "parts",
+ bypassRls: true
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+ const supplierId = searchParams.get("supplierId");
+ const group = searchParams.get("group");
+
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ const [services, tags] = await Promise.all([
+ getServices(client, companyId, {
+ search,
+ supplierId,
+ group,
+ limit,
+ offset,
+ sorts,
+ filters
+ }),
+ getTagsList(client, companyId, "service")
+ ]);
+
+ if (services.error) {
+ throw redirect(
+ path.to.authenticatedRoot,
+ await flash(request, error(services.error, "Failed to fetch services"))
+ );
+ }
+
+ return {
+ count: services.count ?? 0,
+ services: services.data ?? [],
+ tags: tags.data ?? []
+ };
+}
+
+export default function ServicesSearchRoute() {
+ const { count, services, tags } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack spacing={0} className="h-full">
+ <ServicesTable data={services} count={count} tags={tags} />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/routes/x+/items+/update.tsx b/apps/erp/app/routes/x+/items+/update.tsx
index 9efd84be25..55a79745ca 100644
--- a/apps/erp/app/routes/x+/items+/update.tsx
+++ b/apps/erp/app/routes/x+/items+/update.tsx
@@ -715,6 +715,68 @@ export async function action({ request }: ActionFunctionArgs) {
return toolItemUpdates;
}
+ case "serviceId":
+ if (items.length > 1) {
+ return {
+ error: { message: "Cannot update multiple items" },
+ data: null
+ };
+ }
+ const [serviceItem] = items as string[];
+ const serviceData = await client
+ .from("item")
+ .select("readableId, type")
+ .eq("id", serviceItem)
+ .eq("type", "Service")
+ .eq("companyId", companyId)
+ .single();
+
+ if (serviceData.error) {
+ return serviceData;
+ }
+ if (serviceData.data?.type !== "Service") {
+ return { error: { message: "Item is not a service" }, data: null };
+ }
+
+ const currentServiceId = serviceData.data?.readableId;
+
+ const relatedServices = await client
+ .from("item")
+ .select("id")
+ .eq("readableId", currentServiceId)
+ .eq("type", "Service")
+ .eq("companyId", companyId);
+ if (relatedServices.error) {
+ return relatedServices;
+ }
+ const relatedServiceIds = relatedServices.data?.map((item) => item.id);
+ if (relatedServiceIds) {
+ const [serviceItemUpdates, serviceUpdate] = await Promise.all([
+ client
+ .from("item")
+ .update({
+ readableId: value as string,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString()
+ })
+ .in("id", relatedServiceIds as string[])
+ .eq("companyId", companyId),
+ client
+ .from("service")
+ .update({
+ id: value,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", currentServiceId)
+ .eq("companyId", companyId)
+ ]);
+ if (serviceUpdate.error) {
+ return serviceUpdate;
+ }
+
+ return serviceItemUpdates;
+ }
default:
return { error: { message: "Invalid field" }, data: null };
}
diff --git a/apps/erp/app/routes/x+/job+/$jobId.complete.tsx b/apps/erp/app/routes/x+/job+/$jobId.complete.tsx
index 05a40a72f5..edaf0a2318 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.complete.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.complete.tsx
@@ -55,6 +55,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // Note: for Non-Inventory (Service) jobs, complete_job_to_inventory itself
+ // fulfills the linked sales-order line — completion is also reachable via
+ // the sync_finish_job_operation interceptor, so the SQL function is the
+ // single choke point for fulfillment.
+
throw redirect(
requestReferrer(request) ?? path.to.job(jobId),
await flash(request, success("Job completed successfully"))
diff --git a/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.tsx
index 97122183fc..fb41c96ece 100644
--- a/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.tsx
+++ b/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.tsx
@@ -80,6 +80,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const updatedSupplierPart = await upsertSupplierPart(client, {
id: supplierPartId,
...d,
+ companyId,
updatedBy: userId,
customFields: setCustomFields(formData)
});
diff --git a/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.delete.tsx b/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.delete.tsx
index 0f4bcb07d7..5098767695 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.delete.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.delete.tsx
@@ -16,6 +16,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { supplierPartId } = params;
if (!supplierPartId) throw notFound("supplierPartId not found");
+ // @ts-ignore TS2589 — supabase embedded-select inference exceeds the depth
+ // limit on this branch; the query is unchanged from main where it checks fine
const result = await client
.from("supplierPart")
.select("id, supplierId, supplier(name)")
diff --git a/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsx
index d29ef898d8..54d57bd760 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.purchasing.$supplierPartId.tsx
@@ -80,6 +80,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const updatedSupplierPart = await upsertSupplierPart(client, {
id: supplierPartId,
...d,
+ companyId,
updatedBy: userId,
customFields: setCustomFields(formData)
});
diff --git a/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.convert.tsx b/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.convert.tsx
index 3005c9063a..e1ffaae0ea 100644
--- a/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.convert.tsx
+++ b/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.convert.tsx
@@ -12,8 +12,8 @@ import {
updatePurchasingRFQStatus,
upsertSupplierQuoteLine
} from "~/modules/purchasing";
-import type { MethodItemType } from "~/modules/shared";
-import { methodItemType } from "~/modules/shared";
+import type { ItemType } from "~/modules/shared";
+import { itemType } from "~/modules/shared";
import { path } from "~/utils/path";
const logger = getLogger("erp", "rfqid-convert");
@@ -114,10 +114,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
await upsertSupplierQuoteLine(client, {
supplierQuoteId,
- supplierQuoteLineType: methodItemType.includes(
- line.itemType as MethodItemType
- )
- ? (line.itemType as MethodItemType)
+ supplierQuoteLineType: itemType.includes(line.itemType as ItemType)
+ ? (line.itemType as ItemType)
: "Part",
itemId: line.itemId,
description: line.description ?? "",
diff --git a/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.finalize.tsx b/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.finalize.tsx
index 3abd0817e8..8cc1797992 100644
--- a/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.finalize.tsx
+++ b/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.finalize.tsx
@@ -21,8 +21,8 @@ import {
upsertSupplierQuoteLine
} from "~/modules/purchasing";
import { getCompany } from "~/modules/settings";
-import type { MethodItemType } from "~/modules/shared";
-import { methodItemType, upsertExternalLink } from "~/modules/shared";
+import type { ItemType } from "~/modules/shared";
+import { itemType, upsertExternalLink } from "~/modules/shared";
import { getUser } from "~/modules/users/users.server";
import { path } from "~/utils/path";
@@ -153,10 +153,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
await upsertSupplierQuoteLine(client, {
supplierQuoteId,
- supplierQuoteLineType: methodItemType.includes(
- line.itemType as MethodItemType
- )
- ? (line.itemType as MethodItemType)
+ supplierQuoteLineType: itemType.includes(line.itemType as ItemType)
+ ? (line.itemType as ItemType)
: "Part",
itemId: line.itemId,
description: line.description ?? "",
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
index 38d69e5372..5545c190fc 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
@@ -312,6 +312,7 @@ export default function QuoteLine() {
const initialValues = {
...line,
id: line.id ?? undefined,
+ itemType: (line.itemType as "Part") ?? undefined,
quoteId: line.quoteId ?? "",
customerPartId: line.customerPartId ?? "",
customerPartRevision: line.customerPartRevision ?? "",
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.details.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.details.tsx
index 662ffa79e9..5e4ba30e8a 100644
--- a/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.details.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.$lineId.details.tsx
@@ -251,12 +251,14 @@ export default function EditSalesOrderLineRoute() {
</Suspense>
)}
- <SalesOrderLineShipments
- salesOrder={orderData.salesOrder}
- line={line}
- opportunity={orderData.opportunity}
- shipments={shipments}
- />
+ {line.salesOrderLineType !== "Service" && (
+ <SalesOrderLineShipments
+ salesOrder={orderData.salesOrder}
+ line={line}
+ opportunity={orderData.opportunity}
+ shipments={shipments}
+ />
+ )}
<DeferredFiles resolve={files}>
{(resolvedFiles) => (
diff --git a/apps/erp/app/routes/x+/service+/$itemId._index.tsx b/apps/erp/app/routes/x+/service+/$itemId._index.tsx
new file mode 100644
index 0000000000..c498cd2d6c
--- /dev/null
+++ b/apps/erp/app/routes/x+/service+/$itemId._index.tsx
@@ -0,0 +1,9 @@
+import type { LoaderFunctionArgs } from "react-router";
+import { redirect } from "react-router";
+import { path } from "~/utils/path";
+
+export async function loader({ params }: LoaderFunctionArgs) {
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+ throw redirect(path.to.serviceDetails(itemId));
+}
diff --git a/apps/erp/app/routes/x+/service+/$itemId.costing.tsx b/apps/erp/app/routes/x+/service+/$itemId.costing.tsx
new file mode 100644
index 0000000000..805da8f42a
--- /dev/null
+++ b/apps/erp/app/routes/x+/service+/$itemId.costing.tsx
@@ -0,0 +1,106 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import { VStack } from "@carbon/react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { redirect, useLoaderData } from "react-router";
+import {
+ getItemCost,
+ getItemCostHistory,
+ itemCostValidator,
+ upsertItemCost
+} from "~/modules/items";
+import { ItemCostingForm } from "~/modules/items/ui/Item";
+import { ItemCostHistoryChart } from "~/modules/items/ui/Item/ItemCostHistoryChart";
+import { getCustomFields, setCustomFields } from "~/utils/form";
+import { path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "parts"
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const [itemCost, itemCostHistory] = await Promise.all([
+ getItemCost(client, itemId, companyId),
+ getItemCostHistory(client, itemId, companyId)
+ ]);
+
+ if (itemCost.error) {
+ throw redirect(
+ path.to.items,
+ await flash(
+ request,
+ error(itemCost.error, "Failed to load service costing")
+ )
+ );
+ }
+
+ return {
+ itemCost: itemCost.data,
+ itemCostHistory: itemCostHistory.data ?? []
+ };
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "parts"
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const formData = await request.formData();
+ const validation = await validator(itemCostValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const updateItemCost = await upsertItemCost(client, {
+ ...validation.data,
+ itemId,
+ updatedBy: userId,
+ customFields: setCustomFields(formData)
+ });
+ if (updateItemCost.error) {
+ throw redirect(
+ path.to.service(itemId),
+ await flash(
+ request,
+ error(updateItemCost.error, "Failed to update service costing")
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.serviceCosting(itemId),
+ await flash(request, success("Updated service costing"))
+ );
+}
+
+export default function ServiceCostingRoute() {
+ const { itemCost, itemCostHistory } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack spacing={2} className="p-2">
+ <ItemCostingForm
+ key={itemCost.itemId}
+ // @ts-expect-error TS2322 - TODO: fix type
+ initialValues={{
+ ...itemCost,
+ itemPostingGroupId: itemCost.itemPostingGroupId ?? undefined,
+ ...getCustomFields(itemCost.customFields)
+ }}
+ />
+ <ItemCostHistoryChart
+ readableId={itemCost.readableIdWithRevision ?? ""}
+ itemCostHistory={itemCostHistory}
+ />
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/routes/x+/service+/$itemId.details.tsx b/apps/erp/app/routes/x+/service+/$itemId.details.tsx
new file mode 100644
index 0000000000..a5072a109b
--- /dev/null
+++ b/apps/erp/app/routes/x+/service+/$itemId.details.tsx
@@ -0,0 +1,211 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { JSONContent } from "@carbon/react";
+import { Menubar, VStack } from "@carbon/react";
+import type { PostgrestResponse } from "@supabase/supabase-js";
+import { Suspense } from "react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { Await, redirect, useLoaderData, useParams } from "react-router";
+import { DeferredFiles } from "~/components";
+import { usePermissions, useRouteData } from "~/hooks";
+import type { ItemFile, MakeMethod, ServiceSummary } from "~/modules/items";
+import {
+ getMakeMethodById,
+ getMakeMethods,
+ getMethodMaterialsByMakeMethod,
+ getMethodOperationsByMakeMethodId,
+ serviceValidator,
+ upsertService
+} from "~/modules/items";
+import {
+ BillOfMaterial,
+ BillOfProcess,
+ ItemDocuments,
+ ItemNotes,
+ ItemRiskRegister,
+ MakeMethodTools
+} from "~/modules/items/ui/Item";
+import type { MethodItemType, MethodType } from "~/modules/shared";
+import { getTagsList } from "~/modules/shared";
+import { setCustomFields } from "~/utils/form";
+import { path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "parts",
+ bypassRls: true
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const url = new URL(request.url);
+ const requestedMethodId = url.searchParams.get("methodId");
+
+ const makeMethods = await getMakeMethods(client, itemId, companyId);
+ const makeMethod = requestedMethodId
+ ? (makeMethods.data?.find((m) => m.id === requestedMethodId) ??
+ makeMethods.data?.find((m) => m.status === "Active") ??
+ makeMethods.data?.[0])
+ : (makeMethods.data?.find((m) => m.status === "Active") ??
+ makeMethods.data?.[0]);
+
+ if (!makeMethod) {
+ return { methodData: null, tags: [] };
+ }
+
+ const fullMethod = await getMakeMethodById(client, makeMethod.id, companyId);
+ if (fullMethod.error || !fullMethod.data) {
+ return { methodData: null, tags: [] };
+ }
+
+ const [methodMaterials, methodOperations, tags] = await Promise.all([
+ getMethodMaterialsByMakeMethod(client, fullMethod.data.id),
+ getMethodOperationsByMakeMethodId(client, fullMethod.data.id),
+ getTagsList(client, companyId, "operation")
+ ]);
+
+ return {
+ methodData: {
+ makeMethod: fullMethod.data,
+ methodMaterials:
+ methodMaterials.data?.map((m) => ({
+ ...m,
+ description: m.item?.name ?? "",
+ methodType: m.methodType as MethodType,
+ itemType: m.itemType as MethodItemType
+ })) ?? [],
+ methodOperations:
+ methodOperations.data?.map((operation) => ({
+ ...operation,
+ workCenterId: operation.workCenterId ?? undefined,
+ operationSupplierProcessId:
+ operation.operationSupplierProcessId ?? undefined,
+ workInstruction: operation.workInstruction as JSONContent | null
+ })) ?? []
+ },
+ tags: tags.data ?? []
+ };
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "parts"
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const formData = await request.formData();
+
+ const validation = await validator(serviceValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const updateService = await upsertService(client, {
+ ...validation.data,
+ id: itemId,
+ customFields: setCustomFields(formData),
+ updatedBy: userId
+ });
+ if (updateService.error) {
+ throw redirect(
+ path.to.service(itemId),
+ await flash(
+ request,
+ error(updateService.error, "Failed to update service")
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.service(itemId),
+ await flash(request, success("Updated service"))
+ );
+}
+
+export default function ServiceDetailsRoute() {
+ const { itemId } = useParams();
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const permissions = usePermissions();
+ const { methodData, tags } = useLoaderData<typeof loader>();
+
+ const serviceData = useRouteData<{
+ serviceSummary: ServiceSummary;
+ files: Promise<ItemFile[]>;
+ makeMethods: Promise<PostgrestResponse<MakeMethod>>;
+ }>(path.to.service(itemId));
+
+ if (!serviceData) throw new Error("Could not find service data");
+
+ return (
+ <VStack spacing={2} className="p-2">
+ {permissions.is("employee") && methodData && (
+ <>
+ <Suspense fallback={<Menubar />}>
+ <Await resolve={serviceData?.makeMethods}>
+ {(makeMethods) => (
+ <MakeMethodTools
+ itemId={methodData.makeMethod.itemId}
+ makeMethods={makeMethods?.data ?? []}
+ type="Service"
+ currentMethodId={methodData.makeMethod.id}
+ />
+ )}
+ </Await>
+ </Suspense>
+
+ <ItemNotes
+ id={serviceData.serviceSummary?.id ?? null}
+ title={serviceData.serviceSummary?.name ?? ""}
+ subTitle={serviceData.serviceSummary?.readableIdWithRevision ?? ""}
+ notes={serviceData.serviceSummary?.notes as JSONContent}
+ />
+ {serviceData.serviceSummary?.replenishmentSystem === "Make" && (
+ <>
+ <BillOfMaterial
+ key={`bom:${itemId}`}
+ makeMethod={methodData.makeMethod}
+ // @ts-ignore
+ materials={methodData.methodMaterials ?? []}
+ // @ts-ignore
+ operations={methodData.methodOperations}
+ replenishmentSystem={
+ serviceData.serviceSummary?.replenishmentSystem
+ }
+ />
+ <BillOfProcess
+ key={`bop:${itemId}`}
+ makeMethod={methodData.makeMethod}
+ // @ts-ignore
+ operations={methodData.methodOperations ?? []}
+ tags={tags}
+ />
+ </>
+ )}
+ </>
+ )}
+ {permissions.is("employee") && (
+ <>
+ <DeferredFiles resolve={serviceData?.files}>
+ {(resolvedFiles) => (
+ <ItemDocuments
+ files={resolvedFiles}
+ itemId={itemId}
+ type="Service"
+ />
+ )}
+ </DeferredFiles>
+
+ <ItemRiskRegister itemId={itemId} />
+ </>
+ )}
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/routes/x+/service+/$itemId.make.$makeMethodId.tsx b/apps/erp/app/routes/x+/service+/$itemId.make.$makeMethodId.tsx
new file mode 100644
index 0000000000..9e988c8eab
--- /dev/null
+++ b/apps/erp/app/routes/x+/service+/$itemId.make.$makeMethodId.tsx
@@ -0,0 +1,147 @@
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { JSONContent } from "@carbon/react";
+import { Menubar, VStack } from "@carbon/react";
+import { Suspense } from "react";
+import type { LoaderFunctionArgs } from "react-router";
+import { Await, redirect, useLoaderData, useParams } from "react-router";
+import { useRouteData } from "~/hooks";
+import type { ServiceSummary } from "~/modules/items";
+import {
+ getMakeMethodById,
+ getMakeMethods,
+ getMethodMaterialsByMakeMethod,
+ getMethodOperationsByMakeMethodId
+} from "~/modules/items";
+import {
+ BillOfMaterial,
+ BillOfProcess,
+ MakeMethodTools
+} from "~/modules/items/ui/Item";
+import type { MethodItemType, MethodType } from "~/modules/shared";
+import { getTagsList } from "~/modules/shared";
+import { path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "parts"
+ });
+
+ const { itemId, makeMethodId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+ if (!makeMethodId) throw new Error("Could not find makeMethodId");
+
+ const [makeMethod, methodMaterials, methodOperations, tags] =
+ await Promise.all([
+ getMakeMethodById(client, makeMethodId, companyId),
+ getMethodMaterialsByMakeMethod(client, makeMethodId),
+ getMethodOperationsByMakeMethodId(client, makeMethodId),
+ getTagsList(client, companyId, "operation")
+ ]);
+
+ if (makeMethod.error) {
+ throw redirect(
+ path.to.serviceDetails(itemId),
+ await flash(
+ request,
+ error(makeMethod.error, "Failed to load make method")
+ )
+ );
+ }
+
+ if (methodOperations.error) {
+ throw redirect(
+ path.to.serviceDetails(itemId),
+ await flash(
+ request,
+ error(methodOperations.error, "Failed to load method operations")
+ )
+ );
+ }
+ if (methodMaterials.error) {
+ throw redirect(
+ path.to.serviceDetails(itemId),
+ await flash(
+ request,
+ error(methodMaterials.error, "Failed to load method materials")
+ )
+ );
+ }
+
+ return {
+ makeMethod: makeMethod.data,
+ methodMaterials:
+ methodMaterials.data?.map((m) => ({
+ ...m,
+ description: m.item?.name ?? "",
+ methodOperationId: m.methodOperationId ?? undefined,
+ methodType: m.methodType as MethodType,
+ itemType: m.itemType as MethodItemType
+ })) ?? [],
+ methodOperations:
+ methodOperations.data?.map((operation) => ({
+ ...operation,
+ description: operation.description ?? "",
+ procedureId: operation.procedureId ?? undefined,
+ operationSupplierProcessId:
+ operation.operationSupplierProcessId ?? undefined,
+ operationMinimumCost: operation.operationMinimumCost ?? 0,
+ operationLeadTime: operation.operationLeadTime ?? 0,
+ operationUnitCost: operation.operationUnitCost ?? 0,
+ tags: operation.tags ?? [],
+ workCenterId: operation.workCenterId ?? undefined,
+ workInstruction: operation.workInstruction as JSONContent | null
+ })) ?? [],
+ makeMethods: getMakeMethods(client, makeMethod.data.itemId, companyId),
+ tags: tags.data ?? []
+ };
+}
+
+export default function ServiceMakeMethodPage() {
+ const loaderData = useLoaderData<typeof loader>();
+ const { makeMethod, makeMethods, methodMaterials, methodOperations, tags } =
+ loaderData;
+
+ const { itemId, makeMethodId } = useParams();
+ if (!itemId) throw new Error("Could not find itemId");
+ if (!makeMethodId) throw new Error("Could not find makeMethodId");
+
+ const serviceData = useRouteData<{
+ serviceSummary: ServiceSummary;
+ }>(path.to.service(itemId));
+
+ return (
+ <VStack spacing={2} className="p-2">
+ <Suspense fallback={<Menubar />}>
+ <Await resolve={makeMethods}>
+ {(makeMethods) => (
+ <MakeMethodTools
+ itemId={makeMethod.itemId}
+ makeMethods={makeMethods.data ?? []}
+ type="Service"
+ currentMethodId={makeMethod.id}
+ />
+ )}
+ </Await>
+ </Suspense>
+
+ <BillOfMaterial
+ key={`bom:${makeMethodId}`}
+ makeMethod={makeMethod}
+ // @ts-expect-error TS2322 - TODO: fix type
+ materials={methodMaterials}
+ operations={methodOperations}
+ replenishmentSystem={serviceData?.serviceSummary?.replenishmentSystem}
+ />
+ <BillOfProcess
+ key={`bop:${makeMethodId}`}
+ makeMethod={makeMethod}
+ materials={methodMaterials}
+ // @ts-expect-error
+ operations={methodOperations}
+ tags={tags}
+ />
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/routes/x+/service+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/service+/$itemId.purchasing.$supplierPartId.tsx
new file mode 100644
index 0000000000..3c45911554
--- /dev/null
+++ b/apps/erp/app/routes/x+/service+/$itemId.purchasing.$supplierPartId.tsx
@@ -0,0 +1,167 @@
+import { assertIsPost, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validator } from "@carbon/form";
+import { useRouteData } from "@carbon/react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { redirect, useLoaderData, useNavigate, useParams } from "react-router";
+import type { ServiceSummary } from "~/modules/items";
+import { supplierPartValidator, upsertSupplierPart } from "~/modules/items";
+import { SupplierPartForm } from "~/modules/items/ui/Item";
+import { getDatabaseClient } from "~/services/database.server";
+import { setCustomFields } from "~/utils/form";
+import { path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "parts"
+ });
+
+ const { supplierPartId } = params;
+ if (!supplierPartId) throw new Error("Could not find supplierPartId");
+
+ const [supplierPartResult, priceBreaksResult] = await Promise.all([
+ client
+ .from("supplierPart")
+ .select("*")
+ .eq("id", supplierPartId)
+ .eq("companyId", companyId)
+ .single(),
+ client
+ .from("supplierPartPrice")
+ .select("quantity, unitPrice, sourceType, sourceDocumentId, createdAt")
+ .eq("supplierPartId", supplierPartId)
+ .order("quantity", { ascending: true })
+ ]);
+
+ if (!supplierPartResult?.data)
+ throw new Error("Could not find supplier part");
+
+ const supplierPart = supplierPartResult.data;
+
+ const purchasingHistory = await client
+ .from("purchaseOrderLine")
+ .select(
+ "id, purchaseQuantity, unitPrice, purchaseOrderId, purchaseOrder!inner(purchaseOrderId, supplierId, orderDate)"
+ )
+ .eq("itemId", supplierPart.itemId)
+ .eq("purchaseOrder.supplierId", supplierPart.supplierId)
+ .order("createdAt", { ascending: false })
+ .limit(10);
+
+ return {
+ supplierPart,
+ priceBreaks: priceBreaksResult.data ?? [],
+ purchasingHistory: purchasingHistory.data ?? []
+ };
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId, companyId } = await requirePermissions(request, {
+ update: "parts"
+ });
+
+ const { itemId, supplierPartId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+ if (!supplierPartId) throw new Error("Could not find supplierPartId");
+
+ const formData = await request.formData();
+
+ const validation = await validator(supplierPartValidator).validate(formData);
+
+ if (validation.error) {
+ return { success: false, message: "Invalid form data" };
+ }
+
+ // biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
+ const { id, ...d } = validation.data;
+
+ const updatedSupplierPart = await upsertSupplierPart(client, {
+ id: supplierPartId,
+ ...d,
+ companyId,
+ updatedBy: userId,
+ customFields: setCustomFields(formData)
+ });
+
+ if (updatedSupplierPart.error) {
+ return { success: false, message: "Failed to update supplier part" };
+ }
+
+ const priceBreaksRaw = formData.get("priceBreaks");
+ if (priceBreaksRaw) {
+ const priceBreaks = JSON.parse(priceBreaksRaw as string) as {
+ quantity: number;
+ unitPrice: number;
+ leadTime: number;
+ }[];
+ const db = getDatabaseClient();
+ await db.transaction().execute(async (trx) => {
+ await trx
+ .deleteFrom("supplierPartPrice")
+ .where("supplierPartId", "=", supplierPartId)
+ .execute();
+ if (priceBreaks.length > 0) {
+ await trx
+ .insertInto("supplierPartPrice")
+ .values(
+ priceBreaks.map((pb) => ({
+ supplierPartId,
+ quantity: pb.quantity,
+ unitPrice: pb.unitPrice,
+ leadTime: pb.leadTime ?? 0,
+ sourceType: "Manual Entry" as const,
+ companyId,
+ createdBy: userId,
+ updatedBy: userId
+ }))
+ )
+ .execute();
+ }
+ });
+ }
+
+ throw redirect(
+ path.to.servicePurchasing(itemId),
+ await flash(request, success("Supplier part updated"))
+ );
+}
+
+export default function EditServiceSupplierRoute() {
+ const { itemId } = useParams();
+ const { supplierPart, priceBreaks, purchasingHistory } =
+ useLoaderData<typeof loader>();
+
+ if (!itemId) throw new Error("itemId not found");
+
+ const routeData = useRouteData<{ serviceSummary: ServiceSummary }>(
+ path.to.service(itemId)
+ );
+
+ const navigate = useNavigate();
+ const onClose = () => navigate(path.to.servicePurchasing(itemId));
+
+ const initialValues = {
+ id: supplierPart.id,
+ itemId: supplierPart.itemId,
+ supplierId: supplierPart.supplierId,
+ supplierPartId: supplierPart.supplierPartId ?? "",
+ unitPrice: supplierPart.unitPrice ?? 0,
+ supplierUnitOfMeasureCode: supplierPart.supplierUnitOfMeasureCode ?? "EA",
+ minimumOrderQuantity: supplierPart.minimumOrderQuantity ?? 1,
+ orderMultiple: supplierPart.orderMultiple ?? 1,
+ conversionFactor: supplierPart.conversionFactor ?? 1
+ };
+
+ return (
+ <SupplierPartForm
+ type="Service"
+ initialValues={initialValues}
+ unitOfMeasureCode={routeData?.serviceSummary?.unitOfMeasureCode ?? ""}
+ priceBreaks={priceBreaks}
+ purchasingHistory={purchasingHistory}
+ onClose={onClose}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/service+/$itemId.purchasing.new.tsx b/apps/erp/app/routes/x+/service+/$itemId.purchasing.new.tsx
new file mode 100644
index 0000000000..dc4527e354
--- /dev/null
+++ b/apps/erp/app/routes/x+/service+/$itemId.purchasing.new.tsx
@@ -0,0 +1,107 @@
+import { assertIsPost } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { validator } from "@carbon/form";
+import { useRouteData } from "@carbon/react";
+import type { ActionFunctionArgs } from "react-router";
+import { useNavigate, useParams } from "react-router";
+import type { ServiceSummary } from "~/modules/items";
+import { supplierPartValidator, upsertSupplierPart } from "~/modules/items";
+import { SupplierPartForm } from "~/modules/items/ui/Item";
+import { setCustomFields } from "~/utils/form";
+import { path } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "parts"
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const formData = await request.formData();
+ const validation = await validator(supplierPartValidator).validate(formData);
+
+ if (validation.error) {
+ return {
+ success: false,
+ message: "Invalid form data"
+ };
+ }
+
+ // biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
+ const { id, ...d } = validation.data;
+
+ const createServiceSupplier = await upsertSupplierPart(client, {
+ ...d,
+ companyId,
+ createdBy: userId,
+ customFields: setCustomFields(formData)
+ });
+
+ if (createServiceSupplier.error) {
+ return {
+ success: false,
+ message: "Failed to create service supplier"
+ };
+ }
+
+ const newSupplierPartId = createServiceSupplier.data?.id;
+ const priceBreaksRaw = formData.get("priceBreaks");
+ if (newSupplierPartId && priceBreaksRaw) {
+ const priceBreaks = JSON.parse(priceBreaksRaw as string) as {
+ quantity: number;
+ unitPrice: number;
+ leadTime: number;
+ }[];
+ if (priceBreaks.length > 0) {
+ await client.from("supplierPartPrice").insert(
+ priceBreaks.map((pb) => ({
+ supplierPartId: newSupplierPartId,
+ quantity: pb.quantity,
+ unitPrice: pb.unitPrice,
+ leadTime: pb.leadTime ?? 0,
+ sourceType: "Manual Entry" as const,
+ companyId,
+ createdBy: userId,
+ updatedBy: userId
+ }))
+ );
+ }
+ }
+
+ return { success: true, message: "Service supplier created" };
+}
+
+export default function NewServiceSupplierRoute() {
+ const { itemId } = useParams();
+
+ if (!itemId) throw new Error("itemId not found");
+
+ const routeData = useRouteData<{ serviceSummary: ServiceSummary }>(
+ path.to.service(itemId)
+ );
+
+ const navigate = useNavigate();
+ const onClose = () => navigate(path.to.servicePurchasing(itemId));
+
+ const initialValues = {
+ itemId: itemId,
+ supplierId: "",
+ supplierPartId: "",
+ unitPrice: 0,
+ supplierUnitOfMeasureCode: "EA",
+ minimumOrderQuantity: 1,
+ orderMultiple: 1,
+ conversionFactor: 1
+ };
+
+ return (
+ <SupplierPartForm
+ type="Service"
+ initialValues={initialValues}
+ unitOfMeasureCode={routeData?.serviceSummary?.unitOfMeasureCode ?? ""}
+ onClose={onClose}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/service+/$itemId.purchasing.tsx b/apps/erp/app/routes/x+/service+/$itemId.purchasing.tsx
new file mode 100644
index 0000000000..06deb2dfb9
--- /dev/null
+++ b/apps/erp/app/routes/x+/service+/$itemId.purchasing.tsx
@@ -0,0 +1,133 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import { VStack } from "@carbon/react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { redirect, useLoaderData, useParams } from "react-router";
+import { useRouteData } from "~/hooks";
+import type { SupplierPart } from "~/modules/items";
+import {
+ getItemCostHistory,
+ getItemReplenishment,
+ itemPurchasingValidator,
+ upsertItemPurchasing
+} from "~/modules/items";
+import { ItemPurchasingForm, SupplierParts } from "~/modules/items/ui/Item";
+import { ItemCostHistoryChart } from "~/modules/items/ui/Item/ItemCostHistoryChart";
+import { path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "parts"
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const [servicePurchasingResult, itemCostHistory] = await Promise.all([
+ getItemReplenishment(client, itemId, companyId),
+ getItemCostHistory(client, itemId, companyId)
+ ]);
+
+ if (servicePurchasingResult.error) {
+ throw redirect(
+ path.to.items,
+ await flash(
+ request,
+ error(
+ servicePurchasingResult.error,
+ "Failed to load service purchasing"
+ )
+ )
+ );
+ }
+
+ return {
+ servicePurchasing: servicePurchasingResult.data,
+ itemCostHistory: itemCostHistory.data ?? []
+ };
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "parts"
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const validation = await validator(itemPurchasingValidator).validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const updateServicePurchasing = await upsertItemPurchasing(client, {
+ ...validation.data,
+ itemId,
+ updatedBy: userId
+ });
+ if (updateServicePurchasing.error) {
+ throw redirect(
+ path.to.service(itemId),
+ await flash(
+ request,
+ error(
+ updateServicePurchasing.error,
+ "Failed to update service purchasing"
+ )
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.servicePurchasing(itemId),
+ await flash(request, success("Updated service purchasing"))
+ );
+}
+
+export default function ServicePurchasingRoute() {
+ const { servicePurchasing, itemCostHistory } = useLoaderData<typeof loader>();
+
+ const { itemId } = useParams();
+ if (!itemId) throw new Error("Could not find itemId");
+ const routeData = useRouteData<{ supplierParts: SupplierPart[] }>(
+ path.to.service(itemId)
+ );
+ const supplierParts = routeData?.supplierParts ?? [];
+
+ const serviceData = useRouteData<{
+ serviceSummary: { readableIdWithRevision?: string };
+ }>(path.to.service(itemId));
+
+ const initialValues = {
+ ...servicePurchasing,
+ preferredSupplierId: servicePurchasing?.preferredSupplierId ?? undefined,
+ leadTime: servicePurchasing?.leadTime ?? "",
+ purchasingBlocked: servicePurchasing?.purchasingBlocked ?? false,
+ purchasingUnitOfMeasureCode:
+ servicePurchasing?.purchasingUnitOfMeasureCode ?? "",
+ conversionFactor: servicePurchasing?.conversionFactor ?? 1
+ };
+
+ return (
+ <VStack spacing={2} className="p-2">
+ <ItemPurchasingForm
+ key={initialValues.itemId}
+ initialValues={initialValues}
+ allowedSuppliers={
+ supplierParts.map((s) => s.supplierId).filter(Boolean) as string[]
+ }
+ />
+ <SupplierParts supplierParts={supplierParts} />
+ <ItemCostHistoryChart
+ readableId={serviceData?.serviceSummary?.readableIdWithRevision ?? ""}
+ itemCostHistory={itemCostHistory}
+ />
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/routes/x+/service+/$itemId.quality.tsx b/apps/erp/app/routes/x+/service+/$itemId.quality.tsx
new file mode 100644
index 0000000000..df883d6985
--- /dev/null
+++ b/apps/erp/app/routes/x+/service+/$itemId.quality.tsx
@@ -0,0 +1,84 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { data, redirect, useLoaderData, useParams } from "react-router";
+import invariant from "tiny-invariant";
+import {
+ getItemSamplingPlan,
+ itemSamplingPlanValidator,
+ upsertItemSamplingPlan
+} from "~/modules/quality";
+import SamplingPlanForm from "~/modules/quality/ui/SamplingPlan/SamplingPlanForm";
+import { getCompanySettings } from "~/modules/settings";
+import { path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "parts"
+ });
+ const { itemId } = params;
+ invariant(itemId, "itemId is required");
+
+ const [plan, settings] = await Promise.all([
+ getItemSamplingPlan(client, itemId, companyId),
+ getCompanySettings(client, companyId)
+ ]);
+
+ return data({
+ plan: plan.data,
+ samplingStandard:
+ ((settings.data as any)?.samplingStandard as
+ | "ANSI_Z1_4"
+ | "ISO_2859_1") ?? "ANSI_Z1_4"
+ });
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "quality"
+ });
+ const { itemId } = params;
+ invariant(itemId, "itemId is required");
+
+ const formData = await request.formData();
+ const validation = await validator(itemSamplingPlanValidator).validate(
+ formData
+ );
+ if (validation.error) return validationError(validation.error);
+
+ const result = await upsertItemSamplingPlan(client, {
+ ...validation.data,
+ companyId,
+ updatedBy: userId
+ });
+ if (result.error) {
+ throw redirect(
+ path.to.serviceQuality(itemId),
+ await flash(request, error(result.error, "Failed to save sampling plan"))
+ );
+ }
+
+ throw redirect(
+ path.to.serviceQuality(itemId),
+ await flash(request, success("Sampling plan updated"))
+ );
+}
+
+export default function ServiceQualityRoute() {
+ const { plan, samplingStandard } = useLoaderData<typeof loader>();
+ const { itemId } = useParams();
+ if (!itemId) throw new Error("itemId is required");
+ return (
+ <div className="p-4">
+ <SamplingPlanForm
+ action={path.to.serviceQuality(itemId)}
+ itemId={itemId}
+ standard={samplingStandard}
+ initial={plan ?? undefined}
+ />
+ </div>
+ );
+}
diff --git a/apps/erp/app/routes/x+/service+/$itemId.sales.tsx b/apps/erp/app/routes/x+/service+/$itemId.sales.tsx
new file mode 100644
index 0000000000..2744298beb
--- /dev/null
+++ b/apps/erp/app/routes/x+/service+/$itemId.sales.tsx
@@ -0,0 +1,112 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import { VStack } from "@carbon/react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { redirect, useLoaderData } from "react-router";
+import {
+ getItemUnitSalePrice,
+ itemUnitSalePriceValidator,
+ upsertItemUnitSalePrice
+} from "~/modules/items";
+import { ItemSalePriceForm } from "~/modules/items/ui/Item";
+import { getCustomFields, setCustomFields } from "~/utils/form";
+import { path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "parts",
+ role: "employee"
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const serviceUnitSalePrice = await getItemUnitSalePrice(
+ client,
+ itemId,
+ companyId
+ );
+
+ if (serviceUnitSalePrice.error) {
+ throw redirect(
+ path.to.items,
+ await flash(
+ request,
+ error(
+ serviceUnitSalePrice.error,
+ "Failed to load service unit sale price"
+ )
+ )
+ );
+ }
+
+ return {
+ serviceUnitSalePrice: serviceUnitSalePrice.data,
+ itemId
+ };
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "parts"
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const formData = await request.formData();
+ const validation = await validator(itemUnitSalePriceValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const updateServiceUnitSalePrice = await upsertItemUnitSalePrice(client, {
+ ...validation.data,
+ itemId,
+ updatedBy: userId,
+ customFields: setCustomFields(formData)
+ });
+ if (updateServiceUnitSalePrice.error) {
+ throw redirect(
+ path.to.service(itemId),
+ await flash(
+ request,
+ error(
+ updateServiceUnitSalePrice.error,
+ "Failed to update service sale price"
+ )
+ )
+ );
+ }
+
+ throw redirect(
+ path.to.serviceSales(itemId),
+ await flash(request, success("Updated service sale price"))
+ );
+}
+
+export default function ServiceSalesRoute() {
+ const { serviceUnitSalePrice, itemId } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ ...serviceUnitSalePrice,
+ salesUnitOfMeasureCode: serviceUnitSalePrice?.salesUnitOfMeasureCode ?? "",
+ ...getCustomFields(serviceUnitSalePrice.customFields),
+ itemId: itemId
+ };
+
+ return (
+ <VStack spacing={2} className="p-2">
+ <ItemSalePriceForm
+ key={initialValues.itemId}
+ initialValues={initialValues}
+ />
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/routes/x+/service+/$itemId.tsx b/apps/erp/app/routes/x+/service+/$itemId.tsx
new file mode 100644
index 0000000000..8c8fbbaa75
--- /dev/null
+++ b/apps/erp/app/routes/x+/service+/$itemId.tsx
@@ -0,0 +1,334 @@
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import {
+ HStack,
+ Input,
+ InputGroup,
+ InputLeftElement,
+ Spinner,
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+ useRouteData
+} from "@carbon/react";
+import { msg } from "@lingui/core/macro";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { Suspense, useState } from "react";
+import { LuSearch } from "react-icons/lu";
+import type { LoaderFunctionArgs } from "react-router";
+import {
+ Await,
+ Outlet,
+ redirect,
+ useLoaderData,
+ useParams
+} from "react-router";
+import { ResizablePanels } from "~/components/Layout";
+import { flattenTree } from "~/components/TreeView";
+import type { ItemFile, ServiceSummary } from "~/modules/items";
+import {
+ getItemFiles,
+ getItemSupersededBy,
+ getItemSupersession,
+ getMakeMethodById,
+ getMakeMethods,
+ getMethodTree,
+ getPartUsedIn,
+ getService,
+ getSupplierParts
+} from "~/modules/items";
+import { BoMActions, BoMExplorer } from "~/modules/items/ui/Item";
+import type { UsedInNode } from "~/modules/items/ui/Item/UsedIn";
+import { UsedInSkeleton, UsedInTree } from "~/modules/items/ui/Item/UsedIn";
+import { ServiceHeader, ServiceProperties } from "~/modules/items/ui/Services";
+import { getTagsList } from "~/modules/shared";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: msg`Services`,
+ to: path.to.services,
+ module: "items"
+};
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "parts",
+ bypassRls: true
+ });
+
+ const { itemId } = params;
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const [serviceSummary, supplierParts, tags, supersession, supersededBy] =
+ await Promise.all([
+ getService(client, itemId, companyId),
+ getSupplierParts(client, itemId, companyId),
+ getTagsList(client, companyId, "service"),
+ getItemSupersession(client, itemId, companyId),
+ getItemSupersededBy(client, itemId, companyId)
+ ]);
+
+ if (serviceSummary.error) {
+ throw redirect(
+ path.to.items,
+ await flash(
+ request,
+ error(serviceSummary.error, "Failed to load service summary")
+ )
+ );
+ }
+
+ const url = new URL(request.url);
+ const requestedMethodId = url.searchParams.get("methodId");
+
+ const methodTree = getMakeMethods(client, itemId, companyId).then(
+ async (makeMethods) => {
+ const makeMethod = requestedMethodId
+ ? (makeMethods.data?.find((m) => m.id === requestedMethodId) ??
+ makeMethods.data?.find((m) => m.status === "Active") ??
+ makeMethods.data?.[0])
+ : (makeMethods.data?.find((m) => m.status === "Active") ??
+ makeMethods.data?.[0]);
+ if (!makeMethod) return null;
+
+ const fullMethod = await getMakeMethodById(
+ client,
+ makeMethod.id,
+ companyId
+ );
+ if (fullMethod.error || !fullMethod.data) return null;
+
+ const tree = await getMethodTree(client, fullMethod.data.id);
+ if (tree.error) return null;
+
+ const methods = tree.data.length > 0 ? flattenTree(tree.data[0]) : [];
+
+ return {
+ makeMethod: fullMethod.data,
+ methods
+ };
+ }
+ );
+
+ return {
+ serviceSummary: serviceSummary.data,
+ supersession: supersession.data,
+ supersededBy: supersededBy.data ?? [],
+ files: getItemFiles(client, itemId, companyId),
+ supplierParts: supplierParts.data ?? [],
+ makeMethods: getMakeMethods(client, itemId, companyId),
+ tags: tags.data ?? [],
+ usedIn: getPartUsedIn(client, itemId, companyId),
+ methodTree
+ };
+}
+
+export default function ServiceRoute() {
+ const { t } = useLingui();
+ const { itemId } = useParams();
+ if (!itemId) throw new Error("Could not find itemId");
+
+ const serviceData = useRouteData<{
+ serviceSummary: ServiceSummary;
+ files: Promise<ItemFile[]>;
+ }>(path.to.service(itemId));
+
+ if (!serviceData) throw new Error("Could not find service data");
+
+ const { usedIn, methodTree } = useLoaderData<typeof loader>();
+
+ const isManufactured =
+ serviceData.serviceSummary?.replenishmentSystem !== "Buy";
+
+ const [filterText, setFilterText] = useState("");
+
+ const renderUsedInTree = (resolvedUsedIn: Awaited<typeof usedIn>) => {
+ const {
+ issues,
+ jobs,
+ purchaseOrderLines,
+ quoteLines,
+ salesOrderLines,
+ supplierQuotes,
+ jobMaterialUsage
+ } = resolvedUsedIn;
+
+ const tree: UsedInNode[] = [
+ {
+ key: "issues",
+ name: t`Issues`,
+ module: "quality",
+ children: issues
+ },
+ {
+ key: "jobs",
+ name: t`Jobs`,
+ module: "production",
+ children: jobs.map((job) => ({
+ ...job,
+ methodType: "Make to Order"
+ }))
+ },
+ {
+ key: "purchaseOrderLines",
+ name: t`Purchase Orders`,
+ module: "purchasing",
+ children: purchaseOrderLines.map((po) => ({
+ ...po,
+ methodType: "Purchase to Order"
+ }))
+ },
+ {
+ key: "quoteLines",
+ name: t`Quotes`,
+ module: "sales",
+ children: quoteLines
+ },
+ {
+ key: "salesOrderLines",
+ name: t`Sales Orders`,
+ module: "sales",
+ children: salesOrderLines
+ },
+ {
+ key: "supplierQuotes",
+ name: t`Supplier Quotes`,
+ module: "purchasing",
+ children: supplierQuotes
+ }
+ ];
+
+ return (
+ <UsedInTree
+ tree={tree}
+ revisions={serviceData.serviceSummary?.revisions}
+ itemReadableId={serviceData.serviceSummary?.readableId ?? ""}
+ itemReadableIdWithRevision={
+ serviceData.serviceSummary?.readableIdWithRevision ?? ""
+ }
+ jobMaterialUsage={jobMaterialUsage}
+ filterText={filterText}
+ hideSearch
+ />
+ );
+ };
+
+ return (
+ <div className="flex flex-col h-[calc(100dvh-49px)] overflow-hidden w-full">
+ <ServiceHeader />
+ <div className="flex h-[calc(100dvh-99px)] overflow-hidden w-full">
+ <div className="flex flex-grow overflow-hidden">
+ <ResizablePanels
+ explorer={
+ <div className="flex flex-col h-full">
+ {isManufactured ? (
+ <Tabs
+ defaultValue="manufacturing"
+ className="flex flex-col h-full"
+ >
+ <div className="px-2 pt-2 flex-shrink-0">
+ <TabsList className="grid grid-cols-2 w-full">
+ <TabsTrigger value="manufacturing">
+ <Trans>Manufacturing</Trans>
+ </TabsTrigger>
+ <TabsTrigger value="used-in">
+ <Trans>Used In</Trans>
+ </TabsTrigger>
+ </TabsList>
+ </div>
+ <HStack className="w-full justify-between flex-shrink-0 p-2 pb-0">
+ <InputGroup size="sm" className="flex flex-grow">
+ <InputLeftElement>
+ <LuSearch className="h-4 w-4" />
+ </InputLeftElement>
+ <Input
+ placeholder={t`Search...`}
+ value={filterText}
+ onChange={(e) => setFilterText(e.target.value)}
+ />
+ </InputGroup>
+ <Suspense fallback={null}>
+ <Await resolve={methodTree}>
+ {(resolved) =>
+ resolved ? (
+ <BoMActions
+ makeMethodId={resolved.makeMethod.id}
+ />
+ ) : null
+ }
+ </Await>
+ </Suspense>
+ </HStack>
+ <div className="flex-1 overflow-y-auto">
+ <TabsContent value="manufacturing">
+ <Suspense
+ fallback={
+ <div className="flex w-full items-center justify-center p-4">
+ <Spinner className="h-6 w-6" />
+ </div>
+ }
+ >
+ <Await resolve={methodTree}>
+ {(resolved) =>
+ resolved ? (
+ <div className="w-full p-2">
+ <BoMExplorer
+ itemType="Service"
+ makeMethod={resolved.makeMethod}
+ // @ts-ignore
+ methods={resolved.methods}
+ methodId={resolved.makeMethod.id}
+ filterText={filterText}
+ hideSearch
+ />
+ </div>
+ ) : null
+ }
+ </Await>
+ </Suspense>
+ </TabsContent>
+ <TabsContent value="used-in">
+ <Suspense fallback={<UsedInSkeleton />}>
+ <Await resolve={usedIn}>{renderUsedInTree}</Await>
+ </Suspense>
+ </TabsContent>
+ </div>
+ </Tabs>
+ ) : (
+ <>
+ <HStack className="w-full justify-between flex-shrink-0 p-2 pb-0">
+ <InputGroup size="sm" className="flex flex-grow">
+ <InputLeftElement>
+ <LuSearch className="h-4 w-4" />
+ </InputLeftElement>
+ <Input
+ placeholder={t`Search...`}
+ value={filterText}
+ onChange={(e) => setFilterText(e.target.value)}
+ />
+ </InputGroup>
+ </HStack>
+ <div className="flex-1 overflow-y-auto">
+ <Suspense fallback={<UsedInSkeleton />}>
+ <Await resolve={usedIn}>{renderUsedInTree}</Await>
+ </Suspense>
+ </div>
+ </>
+ )}
+ </div>
+ }
+ content={
+ <div className="h-[calc(100dvh-99px)] overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent w-full">
+ <Outlet />
+ </div>
+ }
+ properties={<ServiceProperties key={itemId} />}
+ />
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/erp/app/routes/x+/service+/_layout.tsx b/apps/erp/app/routes/x+/service+/_layout.tsx
new file mode 100644
index 0000000000..8804b92e3c
--- /dev/null
+++ b/apps/erp/app/routes/x+/service+/_layout.tsx
@@ -0,0 +1,33 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { msg } from "@lingui/core/macro";
+import type { LoaderFunctionArgs, MetaFunction } from "react-router";
+import { Outlet } from "react-router";
+import { getUnitOfMeasuresList } from "~/modules/items";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Services" }];
+};
+
+export const handle: Handle = {
+ breadcrumb: msg`Items`,
+ to: path.to.items,
+ module: "items"
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "parts"
+ });
+
+ const unitOfMeasures = await getUnitOfMeasuresList(client, companyId);
+
+ return {
+ unitOfMeasures: unitOfMeasures?.data ?? []
+ };
+}
+
+export default function ServiceRoute() {
+ return <Outlet />;
+}
diff --git a/apps/erp/app/routes/x+/service+/new.tsx b/apps/erp/app/routes/x+/service+/new.tsx
new file mode 100644
index 0000000000..46aa7fb135
--- /dev/null
+++ b/apps/erp/app/routes/x+/service+/new.tsx
@@ -0,0 +1,88 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import { msg } from "@lingui/core/macro";
+import type { ActionFunctionArgs } from "react-router";
+import { data, redirect } from "react-router";
+import { serviceValidator, upsertService } from "~/modules/items";
+import { ServiceForm } from "~/modules/items/ui/Services";
+import { setCustomFields } from "~/utils/form";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: msg`Services`,
+ to: path.to.services,
+ module: "items"
+};
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "parts"
+ });
+
+ const formData = await request.formData();
+ const modal = formData.get("type") === "modal";
+
+ const validation = await validator(serviceValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const createService = await upsertService(client, {
+ ...validation.data,
+ companyId,
+ customFields: setCustomFields(formData),
+ createdBy: userId
+ });
+ if (createService.error) {
+ return modal
+ ? data(
+ createService,
+ await flash(
+ request,
+ error(createService.error, "Failed to insert service")
+ )
+ )
+ : redirect(
+ path.to.services,
+ await flash(
+ request,
+ error(createService.error, "Failed to insert service")
+ )
+ );
+ }
+
+ const itemId = createService.data?.id;
+ if (!itemId) throw new Error("Service ID not found");
+
+ return modal
+ ? data(createService, { status: 201 })
+ : redirect(path.to.service(itemId));
+}
+
+export default function ServicesNewRoute() {
+ const initialValues = {
+ id: "",
+ revision: "0",
+ name: "",
+ description: "",
+ replenishmentSystem: "Buy" as const,
+ defaultMethodType: "Purchase to Order" as const,
+ itemTrackingType: "Non-Inventory" as const,
+ unitOfMeasureCode: "EA",
+ unitCost: 0,
+ active: true,
+ shelfLifeCalculateFromBom: false,
+ tags: []
+ };
+
+ return (
+ <div className="max-w-4xl w-full p-2 sm:p-0 mx-auto mt-0 md:mt-8">
+ <ServiceForm initialValues={initialValues} />
+ </div>
+ );
+}
diff --git a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.$supplierPartId.tsx b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.$supplierPartId.tsx
index eac1915460..30d14f4365 100644
--- a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.$supplierPartId.tsx
+++ b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.$supplierPartId.tsx
@@ -80,6 +80,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const updatedSupplierPart = await upsertSupplierPart(client, {
id: supplierPartId,
...d,
+ companyId,
updatedBy: userId,
customFields: setCustomFields(formData)
});
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 8bef89b08e..e639490371 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -1839,14 +1839,17 @@ export const path = {
generatePath(`${x}/inventory/serial-numbers/${id}`),
service: (id: string) => generatePath(`${x}/service/${id}`),
services: `${x}/items/services`,
+ serviceCosting: (id: string) => generatePath(`${x}/service/${id}/costing`),
serviceDetails: (id: string) => `${x}/service/${id}/details`,
+ serviceMake: (id: string, makeMethodId: string) =>
+ generatePath(`${x}/service/${id}/make/${makeMethodId}`),
+ serviceQuality: (id: string) => generatePath(`${x}/service/${id}/quality`),
serviceRoot: `${x}/service`,
+ serviceSales: (id: string) => generatePath(`${x}/service/${id}/sales`),
servicePurchasing: (id: string) =>
generatePath(`${x}/service/${id}/purchasing`),
serviceSupplier: (serviceId: string, id: string) =>
generatePath(`${x}/service/${serviceId}/purchasing/${id}`),
- serviceSuppliers: (id: string) =>
- generatePath(`${x}/service/${id}/suppliers`),
settings: `${x}/settings`,
sequences: `${x}/settings/sequences`,
storageUnit: (id: string) =>
diff --git a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
index 81904006e0..b4b7b91e95 100644
--- a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
+++ b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
@@ -73,7 +73,7 @@ import type { JobMaterial, TrackedInput } from "~/services/types";
import { useItems } from "~/stores";
import { path } from "~/utils/path";
-type TrackingType = "Serial" | "Batch" | "Inventory" | null;
+type TrackingType = "Serial" | "Batch" | "Inventory" | "Non-Inventory" | null;
interface ItemDetails {
id: string;
@@ -1033,8 +1033,12 @@ export function IssueMaterialModal({
</AlertDescription>
</Alert>
</ModalBody>
- ) : trackingType === "Inventory" || trackingType === null ? (
- // Inventory item - use ValidatedForm
+ ) : trackingType === "Inventory" ||
+ trackingType === "Non-Inventory" ||
+ trackingType === null ? (
+ // Untracked item (Inventory or Non-Inventory, e.g. consumables and
+ // services) - use ValidatedForm; the issue edge function skips the
+ // itemLedger for Non-Inventory items but still posts the WIP cost
<ValidatedForm
method="post"
action={path.to.issue}
@@ -1094,32 +1098,34 @@ export function IssueMaterialModal({
</div>
)}
- {showContent && trackingType === "Inventory" && (
- <>
- {!material?.id && (
- <div>
- <label className="block text-sm font-medium mb-1">
- Adjustment Type
- </label>
- <Select
- name="adjustmentType"
- defaultValue="Negative Adjmt."
- >
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="Positive Adjmt.">
- Add to Inventory
- </SelectItem>
- <SelectItem value="Negative Adjmt.">
- Pull from Inventory
- </SelectItem>
- </SelectContent>
- </Select>
- </div>
- )}
- {/*
+ {showContent &&
+ (trackingType === "Inventory" ||
+ trackingType === "Non-Inventory") && (
+ <>
+ {!material?.id && (
+ <div>
+ <label className="block text-sm font-medium mb-1">
+ Adjustment Type
+ </label>
+ <Select
+ name="adjustmentType"
+ defaultValue="Negative Adjmt."
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="Positive Adjmt.">
+ Add to Inventory
+ </SelectItem>
+ <SelectItem value="Negative Adjmt.">
+ Pull from Inventory
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ )}
+ {/*
Use the form-aware `<Number>` (FormNumberInput) so
`name="quantity"` lands on react-aria's NumberField
and a hidden form input is rendered with the numeric
@@ -1129,13 +1135,13 @@ export function IssueMaterialModal({
the server's zod schema rejected it, and the action
returned a 400 the modal silently swallowed.
*/}
- <FormNumberInput
- name="quantity"
- label="Quantity"
- minValue={0.01}
- />
- </>
- )}
+ <FormNumberInput
+ name="quantity"
+ label="Quantity"
+ minValue={0.01}
+ />
+ </>
+ )}
</div>
</ModalBody>
<ModalFooter>
diff --git a/packages/database/supabase/functions/convert/index.ts b/packages/database/supabase/functions/convert/index.ts
index 51bfe44204..bfe7773e37 100644
--- a/packages/database/supabase/functions/convert/index.ts
+++ b/packages/database/supabase/functions/convert/index.ts
@@ -544,7 +544,23 @@ serve(async (req: Request) => {
selectedLines[line.id].quantity === 0
);
- const salesOrderStatus = "To Ship and Invoice";
+ // Only the selected lines become sales order lines below.
+ const selectedQuoteLines = quoteLines.data.filter(
+ (line) =>
+ line.id &&
+ selectedLines &&
+ line.id in selectedLines &&
+ selectedLines[line.id].quantity > 0
+ );
+
+ // Services are never shipped — a service-only order goes straight to
+ // "To Invoice" so it isn't stuck waiting on a shipment that can't happen.
+ const hasShippableLine = selectedQuoteLines.some(
+ (line) => line.itemType !== "Service"
+ );
+ const salesOrderStatus = hasShippableLine
+ ? "To Ship and Invoice"
+ : "To Invoice";
const salesOrder = await trx
.insertInto("salesOrder")
@@ -602,14 +618,6 @@ serve(async (req: Request) => {
})
.execute();
- const selectedQuoteLines = quoteLines.data.filter(
- (line) =>
- line.id &&
- selectedLines &&
- line.id in selectedLines &&
- selectedLines[line.id].quantity > 0
- );
-
const pickMethodDefaultsByLineId = new Map<string, string | null>();
await Promise.all(
selectedQuoteLines.map(async (line) => {
diff --git a/packages/database/supabase/functions/create/index.ts b/packages/database/supabase/functions/create/index.ts
index cfefd21a59..03389b58cd 100644
--- a/packages/database/supabase/functions/create/index.ts
+++ b/packages/database/supabase/functions/create/index.ts
@@ -2347,6 +2347,9 @@ serve(async (req: Request) => {
if (!salesOrderLine.data || !salesOrderLine.data.itemId)
throw new Error("Sales order line not found");
+ // Services are never shipped
+ if (salesOrderLine.data.salesOrderLineType === "Service")
+ throw new Error("Service lines cannot be shipped");
const salesOrderId = salesOrderLine.data.salesOrderId;
const [salesOrder, salesOrderShipment, shipment, jobs] =
diff --git a/packages/database/supabase/functions/post-purchase-invoice/index.ts b/packages/database/supabase/functions/post-purchase-invoice/index.ts
index 3655542250..51450f46df 100644
--- a/packages/database/supabase/functions/post-purchase-invoice/index.ts
+++ b/packages/database/supabase/functions/post-purchase-invoice/index.ts
@@ -230,7 +230,7 @@ serve(async (req: Request) => {
});
const areAllLinesReceivedProjected = projectedLines.every((line) => {
- if (line.purchaseOrderLineType === "Comment" || line.purchaseOrderLineType === "G/L Account") return true;
+ if (line.purchaseOrderLineType === "Comment" || line.purchaseOrderLineType === "G/L Account" || line.purchaseOrderLineType === "Service") return true;
const target = line.purchaseQuantity ?? 0;
if (target <= 0) return true;
return (line.quantityReceived ?? 0) >= target;
@@ -843,22 +843,26 @@ serve(async (req: Request) => {
// if the purchase order line is null, we receive the part, do the normal entries and do not use accrual/reversing
if (invoiceLine.purchaseOrderLineId === null) {
- // create the receipt line
- receiptLineInserts.push({
- itemId: invoiceLine.itemId!,
- lineId: invoiceLine.id,
- orderQuantity: invoiceLineQuantityInInventoryUnit,
- outstandingQuantity: invoiceLineQuantityInInventoryUnit,
- receivedQuantity: invoiceLineQuantityInInventoryUnit,
- locationId: invoiceLine.locationId,
- storageUnitId: invoiceLine.storageUnitId,
- unitOfMeasure: invoiceLine.inventoryUnitOfMeasureCode ?? "EA",
- unitPrice: invoiceLine.unitPrice ?? 0,
- requiresSerialTracking: itemTrackingType === "Serial",
- requiresBatchTracking: itemTrackingType === "Batch",
- createdBy: invoiceLine.createdBy,
- companyId,
- });
+ // Services are never received, so they must not materialize a
+ // receipt document — only the expense + AP entries below.
+ if (invoiceLine.invoiceLineType !== "Service") {
+ // create the receipt line
+ receiptLineInserts.push({
+ itemId: invoiceLine.itemId!,
+ lineId: invoiceLine.id,
+ orderQuantity: invoiceLineQuantityInInventoryUnit,
+ outstandingQuantity: invoiceLineQuantityInInventoryUnit,
+ receivedQuantity: invoiceLineQuantityInInventoryUnit,
+ locationId: invoiceLine.locationId,
+ storageUnitId: invoiceLine.storageUnitId,
+ unitOfMeasure: invoiceLine.inventoryUnitOfMeasureCode ?? "EA",
+ unitPrice: invoiceLine.unitPrice ?? 0,
+ requiresSerialTracking: itemTrackingType === "Serial",
+ requiresBatchTracking: itemTrackingType === "Batch",
+ createdBy: invoiceLine.createdBy,
+ companyId,
+ });
+ }
// Only create item ledger entries if the receipt is being posted
// (not when skipReceiptPost is true, as entries will be created when the receipt is posted later)
@@ -880,24 +884,28 @@ serve(async (req: Request) => {
});
}
- // create the cost ledger line
- costLedgerInserts.push({
- itemLedgerType: "Purchase",
- costLedgerType: "Direct Cost",
- adjustment: false,
- documentType: "Purchase Invoice",
- documentId: purchaseInvoice.data?.id ?? undefined,
- externalDocumentId:
- purchaseInvoice.data?.supplierReference ?? undefined,
- itemId: invoiceLine.itemId,
- quantity: invoiceLineQuantityInInventoryUnit,
- nominalCost:
- invoiceLine.quantity * (invoiceLine.unitPrice ?? 0),
- cost: totalLineCostWithWeightedShipping,
- remainingQuantity: invoiceLineQuantityInInventoryUnit,
- supplierId: purchaseInvoice.data?.supplierId,
- companyId,
- });
+ // Services are never stocked — a cost ledger layer would pollute
+ // inventory valuation, so only the journal entries below apply.
+ if (invoiceLine.invoiceLineType !== "Service") {
+ // create the cost ledger line
+ costLedgerInserts.push({
+ itemLedgerType: "Purchase",
+ costLedgerType: "Direct Cost",
+ adjustment: false,
+ documentType: "Purchase Invoice",
+ documentId: purchaseInvoice.data?.id ?? undefined,
+ externalDocumentId:
+ purchaseInvoice.data?.supplierReference ?? undefined,
+ itemId: invoiceLine.itemId,
+ quantity: invoiceLineQuantityInInventoryUnit,
+ nominalCost:
+ invoiceLine.quantity * (invoiceLine.unitPrice ?? 0),
+ cost: totalLineCostWithWeightedShipping,
+ remainingQuantity: invoiceLineQuantityInInventoryUnit,
+ supplierId: purchaseInvoice.data?.supplierId,
+ companyId,
+ });
+ }
// create the GL entries for a direct invoice (no PO)
if (accountingEnabled && accountDefaults?.data) {
@@ -1345,31 +1353,55 @@ serve(async (req: Request) => {
journalLineReference = nanoid();
- // DR GR/IR Clearing — debit balance represents goods invoiced but not received
- journalLineInserts.push({
- accountId:
- accountDefaults.data.goodsReceivedNotInvoicedAccount,
- description: "GR/IR Clearing",
- accrual: true,
- amount: debit("liability", accrualCost),
- quantity: quantityToAccrue,
- documentType: "Invoice",
- documentId: purchaseInvoice.data?.id,
- externalDocumentId: purchaseInvoice.data?.supplierReference,
- documentLineReference: invoiceLine.purchaseOrderLineId
- ? journalReference.to.purchaseInvoice(
- invoiceLine.purchaseOrderLineId
- )
- : null,
- journalLineReference,
- companyId,
- });
+ // Services are never received, so there is no GR/IR accrual to
+ // clear — expense the cost directly to indirect cost instead.
+ const isService = invoiceLine.invoiceLineType === "Service";
+
+ if (isService) {
+ // DR Indirect Cost Account
+ journalLineInserts.push({
+ accountId: accountDefaults.data.indirectCostAccount,
+ description: "Indirect Cost Account",
+ amount: debit("asset", accrualCost),
+ quantity: quantityToAccrue,
+ documentType: "Invoice",
+ documentId: purchaseInvoice.data?.id,
+ externalDocumentId: purchaseInvoice.data?.supplierReference,
+ documentLineReference: invoiceLine.purchaseOrderLineId
+ ? journalReference.to.purchaseInvoice(
+ invoiceLine.purchaseOrderLineId
+ )
+ : null,
+ journalLineReference,
+ companyId,
+ });
+ } else {
+ // DR GR/IR Clearing — debit balance represents goods invoiced but not received
+ journalLineInserts.push({
+ accountId:
+ accountDefaults.data.goodsReceivedNotInvoicedAccount,
+ description: "GR/IR Clearing",
+ accrual: true,
+ amount: debit("liability", accrualCost),
+ quantity: quantityToAccrue,
+ documentType: "Invoice",
+ documentId: purchaseInvoice.data?.id,
+ externalDocumentId: purchaseInvoice.data?.supplierReference,
+ documentLineReference: invoiceLine.purchaseOrderLineId
+ ? journalReference.to.purchaseInvoice(
+ invoiceLine.purchaseOrderLineId
+ )
+ : null,
+ journalLineReference,
+ companyId,
+ });
+ }
// CR Accounts Payable
journalLineInserts.push({
accountId: accountDefaults.data.payablesAccount,
description: "Accounts Payable",
- accrual: true,
+ accrual: isService ? undefined : true,
amount: credit("liability", accrualCost),
quantity: quantityToAccrue,
documentType: "Invoice",
@@ -1805,6 +1837,7 @@ serve(async (req: Request) => {
(line) =>
line.purchaseOrderLineType === "Comment" ||
line.purchaseOrderLineType === "G/L Account" ||
+ line.purchaseOrderLineType === "Service" ||
line.receivedComplete
);
diff --git a/packages/database/supabase/functions/post-receipt/index.ts b/packages/database/supabase/functions/post-receipt/index.ts
index 925ca83698..7515bbdb2b 100644
--- a/packages/database/supabase/functions/post-receipt/index.ts
+++ b/packages/database/supabase/functions/post-receipt/index.ts
@@ -370,7 +370,8 @@ serve(async (req: Request) => {
(line) => {
if (
line.purchaseOrderLineType === "Comment" ||
- line.purchaseOrderLineType === "G/L Account"
+ line.purchaseOrderLineType === "G/L Account" ||
+ line.purchaseOrderLineType === "Service"
)
return true;
const target = line.purchaseQuantity ?? 0;
@@ -1587,6 +1588,7 @@ serve(async (req: Request) => {
(line) =>
line.purchaseOrderLineType === "Comment" ||
line.purchaseOrderLineType === "G/L Account" ||
+ line.purchaseOrderLineType === "Service" ||
line.receivedComplete
);
diff --git a/packages/database/supabase/functions/post-sales-invoice/index.ts b/packages/database/supabase/functions/post-sales-invoice/index.ts
index 753a6c94ad..26ea7ca209 100644
--- a/packages/database/supabase/functions/post-sales-invoice/index.ts
+++ b/packages/database/supabase/functions/post-sales-invoice/index.ts
@@ -361,20 +361,24 @@ serve(async (req: Request) => {
invoiceLine.salesOrderLineId === null &&
invoiceLine.methodType !== "Make to Order"
) {
- // create the shipment line
- shipmentLineInserts.push({
- itemId: invoiceLine.itemId!,
- lineId: invoiceLine.id,
- orderQuantity: invoiceLineQuantityInInventoryUnit,
- outstandingQuantity: invoiceLineQuantityInInventoryUnit,
- shippedQuantity: invoiceLineQuantityInInventoryUnit,
- locationId: invoiceLine.locationId,
- storageUnitId: invoiceLine.storageUnitId,
- unitOfMeasure: invoiceLine.unitOfMeasureCode ?? "EA",
- unitPrice: invoiceLine.unitPrice ?? 0,
- createdBy: invoiceLine.createdBy,
- companyId,
- });
+ // Services are never shipped, so they must not materialize a
+ // shipment document — only the revenue + AR entries below.
+ if (invoiceLine.invoiceLineType !== "Service") {
+ // create the shipment line
+ shipmentLineInserts.push({
+ itemId: invoiceLine.itemId!,
+ lineId: invoiceLine.id,
+ orderQuantity: invoiceLineQuantityInInventoryUnit,
+ outstandingQuantity: invoiceLineQuantityInInventoryUnit,
+ shippedQuantity: invoiceLineQuantityInInventoryUnit,
+ locationId: invoiceLine.locationId,
+ storageUnitId: invoiceLine.storageUnitId,
+ unitOfMeasure: invoiceLine.unitOfMeasureCode ?? "EA",
+ unitPrice: invoiceLine.unitPrice ?? 0,
+ createdBy: invoiceLine.createdBy,
+ companyId,
+ });
+ }
if (itemTrackingType === "Inventory") {
// create the part ledger line
@@ -968,7 +972,9 @@ serve(async (req: Request) => {
const areAllLinesShipped = salesOrderLines.every(
(line) =>
- line.salesOrderLineType === "Comment" || line.sentComplete
+ line.salesOrderLineType === "Comment" ||
+ line.salesOrderLineType === "Service" ||
+ line.sentComplete
);
let status: Database["public"]["Tables"]["salesOrder"]["Row"]["status"] =
@@ -1381,7 +1387,9 @@ serve(async (req: Request) => {
const areAllLinesShipped = salesOrderLines.every(
(line) =>
- line.salesOrderLineType === "Comment" || line.sentComplete
+ line.salesOrderLineType === "Comment" ||
+ line.salesOrderLineType === "Service" ||
+ line.sentComplete
);
let status: Database["public"]["Tables"]["salesOrder"]["Row"]["status"] =
diff --git a/packages/database/supabase/functions/post-shipment/index.ts b/packages/database/supabase/functions/post-shipment/index.ts
index ac96c0f29b..9d269f223b 100644
--- a/packages/database/supabase/functions/post-shipment/index.ts
+++ b/packages/database/supabase/functions/post-shipment/index.ts
@@ -804,7 +804,9 @@ serve(async (req: Request) => {
const areAllLinesShipped = salesOrderLines.every(
(line) =>
- line.salesOrderLineType === "Comment" || line.sentComplete
+ line.salesOrderLineType === "Comment" ||
+ line.salesOrderLineType === "Service" ||
+ line.sentComplete
);
let status: Database["public"]["Tables"]["salesOrder"]["Row"]["status"] =
@@ -2246,7 +2248,9 @@ serve(async (req: Request) => {
const areAllLinesShipped = salesOrderLines.every(
(line) =>
- line.salesOrderLineType === "Comment" || line.sentComplete
+ line.salesOrderLineType === "Comment" ||
+ line.salesOrderLineType === "Service" ||
+ line.sentComplete
);
let status: Database["public"]["Tables"]["salesOrder"]["Row"]["status"] =
diff --git a/packages/database/supabase/migrations/20260707022141_service-item-type.sql b/packages/database/supabase/migrations/20260707022141_service-item-type.sql
new file mode 100644
index 0000000000..bc18e88717
--- /dev/null
+++ b/packages/database/supabase/migrations/20260707022141_service-item-type.sql
@@ -0,0 +1,159 @@
+-- =============================================================================
+-- Service as a first-class item type.
+--
+-- The legacy "service" table (20230412120726) predates the modern per-type
+-- table pattern (typeTable.id = item.readableId, see 20250519122022). The app
+-- now derives Buy/Make from itemReplenishment.replenishmentSystem, so the
+-- legacy "serviceType" column is defaulted and no longer written.
+-- =============================================================================
+
+-- The column is NOT NULL with no default; the app stops writing it.
+ALTER TABLE "service" ALTER COLUMN "serviceType" SET DEFAULT 'External';
+
+-- Vestigial linkage: part/material/tool/consumable dropped "itemId" in
+-- 20250519122022, but "service" was skipped. The current "services" view
+-- (20260419130000) joins item."readableId" = service."id" and never reads it.
+ALTER TABLE "service" DROP COLUMN IF EXISTS "itemId";
+
+
+-- =============================================================================
+-- get_service_details
+-- Body copied from get_tool_details (20260629142317) with tool -> service.
+-- =============================================================================
+DROP FUNCTION IF EXISTS get_service_details(TEXT);
+CREATE OR REPLACE FUNCTION get_service_details(item_id TEXT)
+RETURNS TABLE (
+ "active" BOOLEAN,
+ "assignee" TEXT,
+ "defaultMethodType" "methodType",
+ "sourcingType" "sourcingType",
+ "description" TEXT,
+ "itemTrackingType" "itemTrackingType",
+ "requiresInspection" BOOLEAN,
+ "name" TEXT,
+ "replenishmentSystem" "itemReplenishmentSystem",
+ "unitOfMeasureCode" TEXT,
+ "notes" JSONB,
+ "thumbnailPath" TEXT,
+ "modelId" TEXT,
+ "modelPath" TEXT,
+ "modelName" TEXT,
+ "modelSize" BIGINT,
+ "id" TEXT,
+ "companyId" TEXT,
+ "unitOfMeasure" TEXT,
+ "readableId" TEXT,
+ "revision" TEXT,
+ "readableIdWithRevision" TEXT,
+ "revisions" JSON,
+ "customFields" JSONB,
+ "tags" TEXT[],
+ "itemPostingGroupId" TEXT,
+ "createdBy" TEXT,
+ "createdAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "mpn" TEXT
+) AS $$
+DECLARE
+ v_readable_id TEXT;
+ v_company_id TEXT;
+BEGIN
+ SELECT i."readableId", i."companyId" INTO v_readable_id, v_company_id
+ FROM "item" i
+ WHERE i.id = item_id;
+
+ RETURN QUERY
+ WITH item_revisions AS (
+ SELECT
+ json_agg(
+ json_build_object(
+ 'id', i.id,
+ 'revision', i."revision",
+ 'methodType', i."defaultMethodType",
+ 'type', i."type"
+ ) ORDER BY
+ i."createdAt" DESC
+ ) as "revisions"
+ FROM "item" i
+ WHERE i."readableId" = v_readable_id
+ AND i."companyId" = v_company_id
+ AND i."type" = 'Service'
+ )
+ SELECT
+ i."active",
+ i."assignee",
+ i."defaultMethodType",
+ i."sourcingType",
+ i."description",
+ i."itemTrackingType",
+ i."requiresInspection",
+ i."name",
+ i."replenishmentSystem",
+ i."unitOfMeasureCode",
+ i."notes",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END as "thumbnailPath",
+ mu.id as "modelId",
+ mu."modelPath",
+ mu."name" as "modelName",
+ mu."size" as "modelSize",
+ i."id",
+ i."companyId",
+ uom.name as "unitOfMeasure",
+ i."readableId",
+ i."revision",
+ i."readableIdWithRevision",
+ ir."revisions",
+ s."customFields",
+ s."tags",
+ ic."itemPostingGroupId",
+ i."createdBy",
+ i."createdAt",
+ i."updatedBy",
+ i."updatedAt",
+ i."mpn"
+ FROM "service" s
+ LEFT JOIN "item" i ON i."readableId" = s."id" AND i."companyId" = s."companyId"
+ LEFT JOIN item_revisions ir ON true
+ LEFT JOIN (
+ SELECT
+ ps."itemId",
+ string_agg(ps."supplierPartId", ',') AS "supplierIds"
+ FROM "supplierPart" ps
+ GROUP BY ps."itemId"
+ ) ps ON ps."itemId" = i.id
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN "unitOfMeasure" uom ON uom.code = i."unitOfMeasureCode" AND uom."companyId" = i."companyId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ WHERE i."id" = item_id;
+END;
+$$ LANGUAGE plpgsql;
+
+
+-- =============================================================================
+-- Make services get a makeMethod like Parts and Tools.
+-- Body unchanged from 20260410031802 aside from adding 'Service'.
+-- The event trigger already calls this function by name; no re-attach needed.
+-- =============================================================================
+CREATE OR REPLACE FUNCTION sync_create_make_method_related_records(
+ p_table TEXT,
+ p_operation TEXT,
+ p_new JSONB,
+ p_old JSONB
+)
+RETURNS VOID
+LANGUAGE plpgsql
+SECURITY DEFINER
+AS $$
+BEGIN
+ IF p_operation != 'INSERT' THEN RETURN; END IF;
+
+ IF (p_new->>'type') IN ('Part', 'Tool', 'Service') THEN
+ INSERT INTO "makeMethod"("itemId", "createdBy", "companyId")
+ VALUES (p_new->>'id', p_new->>'createdBy', p_new->>'companyId');
+ END IF;
+END;
+$$;
diff --git a/packages/database/supabase/migrations/20260707022142_complete-job-to-inventory-non-inventory.sql b/packages/database/supabase/migrations/20260707022142_complete-job-to-inventory-non-inventory.sql
new file mode 100644
index 0000000000..d37f93cb5f
--- /dev/null
+++ b/packages/database/supabase/migrations/20260707022142_complete-job-to-inventory-non-inventory.sql
@@ -0,0 +1,569 @@
+-- =============================================================================
+-- complete_job_to_inventory: handle Non-Inventory items (e.g. Service items).
+--
+-- Body forked verbatim from 20260630092517_job-costing-item-dimension.sql with
+-- one addition: when the job's item is Non-Inventory, completion must not touch
+-- inventory. Specifically:
+-- - no 'Assembly Output' / 'Job Receipt' itemLedger entries
+-- - no pickMethod default-storage-unit update
+-- - no costLedger 'Output' layer and no itemCost.unitCost update
+-- - WIP discharges to Cost of Goods Sold instead of FG Inventory. Services
+-- never ship, so completion is the only event that can relieve WIP.
+-- Labor/machine absorption journals and the material backflush are unchanged.
+-- =============================================================================
+CREATE OR REPLACE FUNCTION complete_job_to_inventory(
+ p_job_id TEXT,
+ p_quantity_complete NUMERIC,
+ p_storage_unit_id TEXT DEFAULT NULL,
+ p_location_id TEXT DEFAULT NULL,
+ p_company_id TEXT DEFAULT NULL,
+ p_user_id TEXT DEFAULT NULL
+)
+RETURNS VOID
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+DECLARE
+ v_item_id TEXT;
+ v_item_tracking_type "itemTrackingType";
+ v_quantity_received_to_inventory NUMERIC;
+ v_job_id_readable TEXT;
+ v_job_make_method RECORD;
+ v_tracked_entity RECORD;
+ v_accounting_enabled BOOLEAN;
+ v_company_group_id TEXT;
+ v_inventory_account TEXT;
+ v_wip_account TEXT;
+ v_labor_absorption_account TEXT;
+ v_cogs_account TEXT;
+ v_dimension_item_posting_group TEXT;
+ v_dimension_item TEXT;
+ v_dimension_location TEXT;
+ v_dimension_cost_center TEXT;
+ v_dimension_employee TEXT;
+ v_event RECORD;
+ v_duration_hours NUMERIC;
+ v_rate NUMERIC;
+ v_labor_cost NUMERIC;
+ v_labor_journal_line_reference TEXT;
+ v_labor_accounting_period_id TEXT;
+ v_labor_journal_entry_id TEXT;
+ v_labor_journal_id TEXT;
+ v_labor_jl_id TEXT;
+ v_accumulated_wip_cost NUMERIC;
+ v_today DATE;
+ v_journal_line_reference TEXT;
+ v_accounting_period_id TEXT;
+ v_journal_entry_id TEXT;
+ v_journal_id TEXT;
+ v_jl_ids TEXT[];
+ v_new_per_unit_cost NUMERIC;
+ v_costing_method TEXT;
+ v_existing_unit_cost NUMERIC;
+ v_item_posting_group_id TEXT;
+ v_job_location_id TEXT;
+ v_total_qty_on_hand NUMERIC;
+ v_prior_qty NUMERIC;
+ v_prior_value NUMERIC;
+ v_new_unit_cost NUMERIC;
+BEGIN
+ -- Fetch job details
+ SELECT "itemId", "quantityReceivedToInventory", "jobId", "locationId"
+ INTO STRICT v_item_id, v_quantity_received_to_inventory, v_job_id_readable, v_job_location_id
+ FROM "job"
+ WHERE id = p_job_id;
+
+ SELECT "itemTrackingType"
+ INTO v_item_tracking_type
+ FROM "item"
+ WHERE id = v_item_id;
+
+ v_quantity_received_to_inventory := p_quantity_complete - COALESCE(v_quantity_received_to_inventory, 0);
+
+ -- Fetch jobMakeMethod for the top-level (no parentMaterialId)
+ SELECT *
+ INTO STRICT v_job_make_method
+ FROM "jobMakeMethod"
+ WHERE "jobId" = p_job_id
+ AND "parentMaterialId" IS NULL;
+
+ -- Update job status
+ UPDATE "job"
+ SET status = 'Completed',
+ "completedDate" = NOW(),
+ "quantityComplete" = p_quantity_complete,
+ "quantityReceivedToInventory" = v_quantity_received_to_inventory,
+ "updatedAt" = NOW(),
+ "updatedBy" = p_user_id
+ WHERE id = p_job_id;
+
+ -- Insert itemLedger entries based on tracking type.
+ -- Non-Inventory items (services) never enter inventory.
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' THEN
+ IF v_job_make_method."requiresBatchTracking" THEN
+ SELECT *
+ INTO v_tracked_entity
+ FROM "trackedEntity"
+ WHERE attributes->>'Job Make Method' = v_job_make_method.id
+ AND status != 'Consumed'
+ ORDER BY "createdAt" DESC
+ LIMIT 1;
+
+ IF v_tracked_entity.id IS NULL THEN
+ RAISE EXCEPTION 'Tracked entity not found';
+ END IF;
+
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId",
+ "trackedEntityId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,
+ v_tracked_entity.id, p_user_id
+ );
+
+ ELSIF v_job_make_method."requiresSerialTracking" THEN
+ FOR v_tracked_entity IN
+ SELECT *
+ FROM "trackedEntity"
+ WHERE attributes->>'Job Make Method' = v_job_make_method.id
+ AND status != 'Consumed'
+ LOOP
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId",
+ "trackedEntityId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, 1, p_location_id, p_storage_unit_id,
+ v_tracked_entity.id, p_user_id
+ );
+ END LOOP;
+
+ UPDATE "trackedEntity"
+ SET status = 'Available'
+ WHERE attributes->>'Job Make Method' = v_job_make_method.id
+ AND status != 'Consumed';
+
+ ELSE
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,
+ p_user_id
+ );
+ END IF;
+
+ -- Update pickMethod defaultStorageUnitId if needed
+ IF p_storage_unit_id IS NOT NULL AND p_location_id IS NOT NULL THEN
+ IF NOT EXISTS (
+ SELECT 1 FROM "itemLedger"
+ WHERE "itemId" = v_item_id
+ AND "locationId" = p_location_id
+ AND "storageUnitId" IS NOT NULL
+ AND "storageUnitId" != p_storage_unit_id
+ LIMIT 1
+ ) THEN
+ IF EXISTS (
+ SELECT 1 FROM "pickMethod"
+ WHERE "itemId" = v_item_id AND "locationId" = p_location_id
+ ) THEN
+ UPDATE "pickMethod"
+ SET "defaultStorageUnitId" = p_storage_unit_id,
+ "updatedBy" = p_user_id,
+ "updatedAt" = NOW()
+ WHERE "itemId" = v_item_id
+ AND "locationId" = p_location_id;
+ ELSE
+ INSERT INTO "pickMethod" (
+ "itemId", "locationId", "defaultStorageUnitId",
+ "companyId", "createdBy", "createdAt"
+ ) VALUES (
+ v_item_id, p_location_id, p_storage_unit_id,
+ p_company_id, p_user_id, NOW()
+ );
+ END IF;
+ END IF;
+ END IF;
+ END IF;
+
+ -- Backflush unissued materials (delegated to shared function)
+ PERFORM backflush_job_materials(p_job_id, p_quantity_complete, p_company_id, p_user_id);
+
+ -- Check if accounting is enabled
+ SELECT "accountingEnabled"
+ INTO v_accounting_enabled
+ FROM "companySettings"
+ WHERE id = p_company_id;
+
+ v_accounting_enabled := COALESCE(v_accounting_enabled, false);
+
+ IF NOT v_accounting_enabled THEN
+ RETURN;
+ END IF;
+
+ -- Fetch company group
+ SELECT "companyGroupId"
+ INTO STRICT v_company_group_id
+ FROM company
+ WHERE id = p_company_id;
+
+ -- Fetch account defaults
+ SELECT "inventoryAccount", "workInProgressAccount", "laborAbsorptionAccount", "costOfGoodsSoldAccount"
+ INTO STRICT v_inventory_account, v_wip_account, v_labor_absorption_account, v_cogs_account
+ FROM "accountDefault"
+ WHERE "companyId" = p_company_id;
+
+ -- Fetch dimension IDs
+ SELECT
+ MAX(CASE WHEN "entityType" = 'ItemPostingGroup' THEN id END),
+ MAX(CASE WHEN "entityType" = 'Item' THEN "id" END),
+ MAX(CASE WHEN "entityType" = 'Location' THEN id END),
+ MAX(CASE WHEN "entityType" = 'CostCenter' THEN id END),
+ MAX(CASE WHEN "entityType" = 'Employee' THEN id END)
+ INTO v_dimension_item_posting_group, v_dimension_item, v_dimension_location,
+ v_dimension_cost_center, v_dimension_employee
+ FROM dimension
+ WHERE "companyGroupId" = v_company_group_id
+ AND active = true
+ AND "entityType" IN ('ItemPostingGroup', 'Item', 'Location', 'CostCenter', 'Employee');
+
+ -- Post unposted production events as labor/machine absorption JEs
+ FOR v_event IN
+ SELECT
+ pe.id,
+ pe.duration,
+ pe.type,
+ pe."employeeId",
+ wc."laborRate",
+ wc."machineRate"
+ FROM "productionEvent" pe
+ INNER JOIN "jobOperation" jo ON jo.id = pe."jobOperationId"
+ INNER JOIN "workCenter" wc ON wc.id = pe."workCenterId"
+ WHERE jo."jobId" = p_job_id
+ AND pe."endTime" IS NOT NULL
+ AND pe."postedToGL" = false
+ AND pe.duration > 0
+ LOOP
+ v_duration_hours := v_event.duration::NUMERIC / 3600;
+ v_rate := CASE
+ WHEN v_event.type = 'Machine' THEN COALESCE(v_event."machineRate", 0)
+ ELSE COALESCE(v_event."laborRate", 0)
+ END;
+ v_labor_cost := v_duration_hours * v_rate;
+
+ IF v_labor_cost > 0 AND v_labor_absorption_account IS NOT NULL THEN
+ v_labor_journal_line_reference := nanoid();
+
+ -- Get current accounting period
+ SELECT id INTO v_labor_accounting_period_id
+ FROM "accountingPeriod"
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= CURRENT_DATE
+ AND "endDate" >= CURRENT_DATE
+ AND status = 'Active'
+ LIMIT 1;
+
+ IF v_labor_accounting_period_id IS NULL THEN
+ UPDATE "accountingPeriod"
+ SET status = 'Inactive'
+ WHERE status = 'Active' AND "companyId" = p_company_id;
+
+ UPDATE "accountingPeriod"
+ SET status = 'Active'
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= CURRENT_DATE
+ AND "endDate" >= CURRENT_DATE
+ RETURNING id INTO v_labor_accounting_period_id;
+
+ IF v_labor_accounting_period_id IS NULL THEN
+ INSERT INTO "accountingPeriod" (
+ "startDate", "endDate", "companyId", status, "createdBy"
+ ) VALUES (
+ date_trunc('month', CURRENT_DATE)::DATE,
+ (date_trunc('month', CURRENT_DATE) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,
+ p_company_id, 'Active', 'system'
+ )
+ RETURNING id INTO v_labor_accounting_period_id;
+ END IF;
+ END IF;
+
+ v_labor_journal_entry_id := get_next_sequence('journalEntry', p_company_id);
+
+ INSERT INTO journal (
+ "journalEntryId", "accountingPeriodId", description,
+ "postingDate", "companyId", "sourceType", status,
+ "postedAt", "postedBy", "createdBy"
+ ) VALUES (
+ v_labor_journal_entry_id, v_labor_accounting_period_id,
+ v_event.type || ' Time — Job ' || v_job_id_readable,
+ CURRENT_DATE, p_company_id, 'Production Event', 'Posted',
+ NOW(), p_user_id, p_user_id
+ )
+ RETURNING id INTO v_labor_journal_id;
+
+ -- DR WIP
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_wip_account, 'WIP Account',
+ v_labor_cost, 1,
+ 'Production Event', p_job_id, 'job:' || p_job_id,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on WIP line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on WIP line (the finished good this labor rolls into)
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+
+ -- CR Labor/Machine Absorption
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_labor_absorption_account, 'Labor/Machine Absorption',
+ -v_labor_cost, 1,
+ 'Production Event', p_job_id, 'job:' || p_job_id,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on absorption line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on absorption line
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+ END IF;
+
+ UPDATE "productionEvent"
+ SET "postedToGL" = true
+ WHERE id = v_event.id;
+ END LOOP;
+
+ -- Calculate accumulated WIP cost for this job
+ SELECT COALESCE(ABS(SUM(jl.amount)), 0)
+ INTO v_accumulated_wip_cost
+ FROM "journalLine" jl
+ INNER JOIN journal j ON j.id = jl."journalId"
+ WHERE jl."accountId" = v_wip_account
+ AND jl."documentId" = p_job_id
+ AND j."companyId" = p_company_id;
+
+ IF v_accumulated_wip_cost <= 0 THEN
+ RETURN;
+ END IF;
+
+ v_today := CURRENT_DATE;
+ v_journal_line_reference := nanoid();
+
+ -- Get accounting period for WIP discharge
+ SELECT id INTO v_accounting_period_id
+ FROM "accountingPeriod"
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_today
+ AND "endDate" >= v_today
+ AND status = 'Active'
+ LIMIT 1;
+
+ IF v_accounting_period_id IS NULL THEN
+ UPDATE "accountingPeriod"
+ SET status = 'Inactive'
+ WHERE status = 'Active' AND "companyId" = p_company_id;
+
+ UPDATE "accountingPeriod"
+ SET status = 'Active'
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_today
+ AND "endDate" >= v_today
+ RETURNING id INTO v_accounting_period_id;
+
+ IF v_accounting_period_id IS NULL THEN
+ INSERT INTO "accountingPeriod" (
+ "startDate", "endDate", "companyId", status, "createdBy"
+ ) VALUES (
+ date_trunc('month', v_today)::DATE,
+ (date_trunc('month', v_today) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,
+ p_company_id, 'Active', 'system'
+ )
+ RETURNING id INTO v_accounting_period_id;
+ END IF;
+ END IF;
+
+ v_journal_entry_id := get_next_sequence('journalEntry', p_company_id);
+
+ INSERT INTO journal (
+ "journalEntryId", "accountingPeriodId", description,
+ "postingDate", "companyId", "sourceType", status,
+ "postedAt", "postedBy", "createdBy"
+ ) VALUES (
+ v_journal_entry_id, v_accounting_period_id,
+ 'Job Completion ' || v_job_id_readable,
+ v_today, p_company_id, 'Job Receipt', 'Posted',
+ NOW(), p_user_id, p_user_id
+ )
+ RETURNING id INTO v_journal_id;
+
+ -- DR FG Inventory — or COGS for Non-Inventory items, which never ship
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' THEN
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_journal_id, v_inventory_account, 'Finished Goods Inventory',
+ v_accumulated_wip_cost, v_quantity_received_to_inventory,
+ 'Job Receipt', p_job_id, 'job:' || p_job_id,
+ v_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+ ELSE
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_journal_id, v_cogs_account, 'Cost of Goods Sold',
+ v_accumulated_wip_cost, v_quantity_received_to_inventory,
+ 'Job Receipt', p_job_id, 'job:' || p_job_id,
+ v_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+ END IF;
+
+ v_jl_ids := ARRAY[v_labor_jl_id];
+
+ -- CR WIP
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_journal_id, v_wip_account, 'WIP Account',
+ -v_accumulated_wip_cost, v_quantity_received_to_inventory,
+ 'Job Receipt', p_job_id, 'job:' || p_job_id,
+ v_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ v_jl_ids := v_jl_ids || v_labor_jl_id;
+
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' THEN
+ -- Write costLedger entry for finished good
+ INSERT INTO "costLedger" (
+ "itemLedgerType", "costLedgerType", adjustment,
+ "documentType", "documentId", "itemId",
+ quantity, cost, "remainingQuantity", "companyId"
+ ) VALUES (
+ 'Output', 'Direct Cost', false,
+ 'Job Receipt', p_job_id, v_item_id,
+ v_quantity_received_to_inventory, v_accumulated_wip_cost,
+ v_quantity_received_to_inventory, p_company_id
+ );
+
+ -- Update item cost
+ SELECT "costingMethod", "unitCost", "itemPostingGroupId"
+ INTO v_costing_method, v_existing_unit_cost, v_item_posting_group_id
+ FROM "itemCost"
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+
+ v_new_per_unit_cost := v_accumulated_wip_cost / v_quantity_received_to_inventory;
+
+ IF v_costing_method = 'Average' THEN
+ SELECT COALESCE(SUM(quantity), 0)
+ INTO v_total_qty_on_hand
+ FROM "itemLedger"
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+
+ v_prior_qty := v_total_qty_on_hand - v_quantity_received_to_inventory;
+ v_prior_value := v_prior_qty * COALESCE(v_existing_unit_cost, 0);
+
+ IF v_total_qty_on_hand > 0 THEN
+ v_new_unit_cost := (v_prior_value + v_accumulated_wip_cost) / v_total_qty_on_hand;
+ UPDATE "itemCost"
+ SET "unitCost" = v_new_unit_cost
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+ END IF;
+
+ ELSIF v_costing_method IN ('FIFO', 'LIFO') THEN
+ UPDATE "itemCost"
+ SET "unitCost" = v_new_per_unit_cost
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+ END IF;
+ ELSE
+ -- Dimensions on the WIP discharge lines still want the posting group
+ SELECT "itemPostingGroupId"
+ INTO v_item_posting_group_id
+ FROM "itemCost"
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+ END IF;
+
+ -- Insert dimensions on WIP discharge journal lines
+ IF v_jl_ids IS NOT NULL AND array_length(v_jl_ids, 1) > 0 THEN
+ FOR i IN 1..array_length(v_jl_ids, 1)
+ LOOP
+ IF v_item_posting_group_id IS NOT NULL AND v_dimension_item_posting_group IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_item_posting_group, v_item_posting_group_id, p_company_id
+ );
+ END IF;
+
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+
+ IF v_job_location_id IS NOT NULL AND v_dimension_location IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_location, v_job_location_id, p_company_id
+ );
+ END IF;
+ END LOOP;
+ END IF;
+END;
+$$;
diff --git a/packages/database/supabase/migrations/20260714043017_service-job-completion-cogs.sql b/packages/database/supabase/migrations/20260714043017_service-job-completion-cogs.sql
new file mode 100644
index 0000000000..216f6d07b1
--- /dev/null
+++ b/packages/database/supabase/migrations/20260714043017_service-job-completion-cogs.sql
@@ -0,0 +1,730 @@
+-- =============================================================================
+-- complete_job_to_inventory: restore the Non-Inventory (Service) branch.
+--
+-- Fork of the NEWEST definition (20260713222236_fix-job-completion-overhead-
+-- absorption.sql). Restores the Non-Inventory handling originally added in
+-- 20260707022142_complete-job-to-inventory-non-inventory.sql, which was
+-- silently dropped when the July-13 migrations (20260713190909 raw-materials/
+-- finished-goods split, 20260713222236 overhead fix) forked from the older
+-- 20260630092517 baseline.
+--
+-- Non-Inventory items (Services) are never stocked and never shipped, so job
+-- completion is the only event that can relieve WIP:
+-- - WIP discharges to Cost of Goods Sold instead of Raw Materials/Finished
+-- Goods (Epicor "Make Direct" pattern; spec
+-- .ai/specs/2026-07-14-service-make-to-order-jobs.md)
+-- - no 'Assembly Output' itemLedger entries, no pickMethod update,
+-- no costLedger 'Output' layer, no itemCost.unitCost update
+-- - the linked sales-order line is fulfilled here (quantitySent/sentComplete/
+-- sentDate) — completion is also reachable via the
+-- sync_finish_job_operation interceptor, so app-level hooks cannot cover
+-- every path; this function is the single choke point
+--
+-- Inventory-tracked items keep the 20260713222236 posting behavior: Buy items
+-- debit Raw Materials, Make items debit Finished Goods, with the full
+-- itemLedger/costLedger/itemCost flow unchanged.
+--
+-- Hardening (PR #1107 review):
+-- - the call is bound to the job's own company (SECURITY DEFINER bypasses
+-- RLS, so p_company_id must match job.companyId before any write)
+-- - job.quantityReceivedToInventory now stores the CUMULATIVE received
+-- quantity; re-completions previously overwrote it with the delta, which
+-- corrupted get_inventory_quantities' on-production supply calculation
+-- =============================================================================
+DROP FUNCTION IF EXISTS complete_job_to_inventory(TEXT, NUMERIC, TEXT, TEXT, TEXT, TEXT);
+
+CREATE OR REPLACE FUNCTION complete_job_to_inventory(
+ p_job_id TEXT,
+ p_quantity_complete NUMERIC,
+ p_storage_unit_id TEXT DEFAULT NULL,
+ p_location_id TEXT DEFAULT NULL,
+ p_company_id TEXT DEFAULT NULL,
+ p_user_id TEXT DEFAULT NULL
+)
+RETURNS VOID
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+DECLARE
+ v_item_id TEXT;
+ v_item_tracking_type "itemTrackingType";
+ v_cogs_account TEXT;
+ v_sales_order_line_id TEXT;
+ v_line_quantity_complete NUMERIC;
+ v_job_company_id TEXT;
+ v_prior_quantity_received NUMERIC;
+ v_quantity_received_to_inventory NUMERIC;
+ v_job_id_readable TEXT;
+ v_job_make_method RECORD;
+ v_tracked_entity RECORD;
+ v_accounting_enabled BOOLEAN;
+ v_company_group_id TEXT;
+ v_raw_materials_account TEXT;
+ v_finished_goods_account TEXT;
+ v_item_inventory_account TEXT;
+ v_item_inventory_description TEXT;
+ v_wip_account TEXT;
+ v_labor_absorption_account TEXT;
+ v_overhead_absorption_account TEXT;
+ v_dimension_item_posting_group TEXT;
+ v_dimension_item TEXT;
+ v_dimension_location TEXT;
+ v_dimension_cost_center TEXT;
+ v_dimension_employee TEXT;
+ v_event RECORD;
+ v_duration_hours NUMERIC;
+ v_rate NUMERIC;
+ v_labor_cost NUMERIC;
+ v_overhead_cost NUMERIC;
+ v_event_reference TEXT;
+ v_labor_journal_line_reference TEXT;
+ v_labor_accounting_period_id TEXT;
+ v_labor_journal_entry_id TEXT;
+ v_labor_journal_id TEXT;
+ v_labor_jl_id TEXT;
+ v_accumulated_wip_cost NUMERIC;
+ v_today DATE;
+ v_journal_line_reference TEXT;
+ v_accounting_period_id TEXT;
+ v_journal_entry_id TEXT;
+ v_journal_id TEXT;
+ v_jl_ids TEXT[];
+ v_new_per_unit_cost NUMERIC;
+ v_costing_method TEXT;
+ v_existing_unit_cost NUMERIC;
+ v_item_posting_group_id TEXT;
+ v_job_location_id TEXT;
+ v_total_qty_on_hand NUMERIC;
+ v_prior_qty NUMERIC;
+ v_prior_value NUMERIC;
+ v_new_unit_cost NUMERIC;
+BEGIN
+ -- Never let a NULL user reach NOT NULL audit columns; fall back to the job creator
+ p_user_id := COALESCE(p_user_id, (SELECT "createdBy" FROM "job" WHERE id = p_job_id));
+
+ -- Fetch job details
+ SELECT "itemId", "quantityReceivedToInventory", "jobId", "locationId", "salesOrderLineId", "companyId"
+ INTO STRICT v_item_id, v_prior_quantity_received, v_job_id_readable, v_job_location_id, v_sales_order_line_id, v_job_company_id
+ FROM "job"
+ WHERE id = p_job_id;
+
+ -- SECURITY DEFINER bypasses RLS: bind the call to the job's own company so a
+ -- caller can never complete another tenant's job or post into a mismatched
+ -- company's ledger/journal.
+ IF p_company_id IS NULL OR v_job_company_id IS DISTINCT FROM p_company_id THEN
+ RAISE EXCEPTION 'Job % does not belong to company %', p_job_id, COALESCE(p_company_id, '<null>');
+ END IF;
+
+ -- Non-Inventory items (services) never enter inventory
+ SELECT "itemTrackingType"
+ INTO v_item_tracking_type
+ FROM "item"
+ WHERE id = v_item_id
+ AND "companyId" = p_company_id;
+
+ -- Delta for this completion: drives the itemLedger/costLedger quantities and
+ -- the WIP-discharge journal. The job column itself stores the CUMULATIVE
+ -- quantity (get_inventory_quantities computes on-production supply as
+ -- production + scrap - received - shipped, which requires cumulative).
+ v_quantity_received_to_inventory := p_quantity_complete - COALESCE(v_prior_quantity_received, 0);
+
+ -- Fetch jobMakeMethod for the top-level (no parentMaterialId)
+ SELECT *
+ INTO STRICT v_job_make_method
+ FROM "jobMakeMethod"
+ WHERE "jobId" = p_job_id
+ AND "parentMaterialId" IS NULL;
+
+ -- Update job status. quantityReceivedToInventory is CUMULATIVE (not the
+ -- delta): re-completions previously overwrote it with the delta, corrupting
+ -- get_inventory_quantities' on-production supply math. Non-Inventory items
+ -- never receive to inventory, so their value is left unchanged.
+ UPDATE "job"
+ SET status = 'Completed',
+ "completedDate" = NOW(),
+ "quantityComplete" = p_quantity_complete,
+ "quantityReceivedToInventory" = CASE
+ WHEN v_item_tracking_type = 'Non-Inventory' THEN v_prior_quantity_received
+ ELSE p_quantity_complete
+ END,
+ "updatedAt" = NOW(),
+ "updatedBy" = p_user_id
+ WHERE id = p_job_id;
+
+ -- Services never ship, so job completion is the fulfillment event: advance
+ -- the linked sales-order line the way post-shipment does for physical lines.
+ -- Lives HERE (not in app code) because completion has multiple entry points —
+ -- the ERP complete route AND the sync_finish_job_operation interceptor that
+ -- auto-completes when the last operation finishes. Recomputed from ALL jobs
+ -- on the line, so it is idempotent and lot-split safe. Runs before the
+ -- accounting-enabled / zero-WIP early returns.
+ IF v_item_tracking_type = 'Non-Inventory' AND v_sales_order_line_id IS NOT NULL THEN
+ SELECT COALESCE(SUM("quantityComplete"), 0)
+ INTO v_line_quantity_complete
+ FROM "job"
+ WHERE "salesOrderLineId" = v_sales_order_line_id
+ AND "companyId" = p_company_id
+ AND status != 'Cancelled';
+
+ UPDATE "salesOrderLine" sol
+ SET "quantitySent" = v_line_quantity_complete,
+ "sentComplete" = (COALESCE(sol."saleQuantity", 0) > 0 AND v_line_quantity_complete >= sol."saleQuantity"),
+ "sentDate" = CASE
+ WHEN COALESCE(sol."saleQuantity", 0) > 0
+ AND v_line_quantity_complete >= sol."saleQuantity"
+ AND sol."sentDate" IS NULL
+ THEN CURRENT_DATE
+ ELSE sol."sentDate"
+ END,
+ "updatedBy" = p_user_id,
+ "updatedAt" = NOW()
+ WHERE sol.id = v_sales_order_line_id
+ AND sol."companyId" = p_company_id;
+ END IF;
+
+ -- Insert itemLedger entries based on tracking type.
+ -- Non-Inventory items (services) never enter inventory.
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' THEN
+ IF v_job_make_method."requiresBatchTracking" THEN
+ SELECT *
+ INTO v_tracked_entity
+ FROM "trackedEntity"
+ WHERE attributes->>'Job Make Method' = v_job_make_method.id
+ AND status != 'Consumed'
+ ORDER BY "createdAt" DESC
+ LIMIT 1;
+
+ IF v_tracked_entity.id IS NULL THEN
+ RAISE EXCEPTION 'Tracked entity not found';
+ END IF;
+
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId",
+ "trackedEntityId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,
+ v_tracked_entity.id, p_user_id
+ );
+
+ ELSIF v_job_make_method."requiresSerialTracking" THEN
+ FOR v_tracked_entity IN
+ SELECT *
+ FROM "trackedEntity"
+ WHERE attributes->>'Job Make Method' = v_job_make_method.id
+ AND status != 'Consumed'
+ LOOP
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId",
+ "trackedEntityId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, 1, p_location_id, p_storage_unit_id,
+ v_tracked_entity.id, p_user_id
+ );
+ END LOOP;
+
+ UPDATE "trackedEntity"
+ SET status = 'Available'
+ WHERE attributes->>'Job Make Method' = v_job_make_method.id
+ AND status != 'Consumed';
+
+ ELSE
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,
+ p_user_id
+ );
+ END IF;
+ END IF;
+
+ -- Update pickMethod defaultStorageUnitId if needed
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' AND p_storage_unit_id IS NOT NULL AND p_location_id IS NOT NULL THEN
+ IF NOT EXISTS (
+ SELECT 1 FROM "itemLedger"
+ WHERE "itemId" = v_item_id
+ AND "locationId" = p_location_id
+ AND "storageUnitId" IS NOT NULL
+ AND "storageUnitId" != p_storage_unit_id
+ LIMIT 1
+ ) THEN
+ IF EXISTS (
+ SELECT 1 FROM "pickMethod"
+ WHERE "itemId" = v_item_id AND "locationId" = p_location_id
+ ) THEN
+ UPDATE "pickMethod"
+ SET "defaultStorageUnitId" = p_storage_unit_id,
+ "updatedBy" = p_user_id,
+ "updatedAt" = NOW()
+ WHERE "itemId" = v_item_id
+ AND "locationId" = p_location_id;
+ ELSE
+ INSERT INTO "pickMethod" (
+ "itemId", "locationId", "defaultStorageUnitId",
+ "companyId", "createdBy", "createdAt"
+ ) VALUES (
+ v_item_id, p_location_id, p_storage_unit_id,
+ p_company_id, p_user_id, NOW()
+ );
+ END IF;
+ END IF;
+ END IF;
+
+ -- Backflush unissued materials (delegated to shared function)
+ PERFORM backflush_job_materials(p_job_id, p_quantity_complete, p_company_id, p_user_id);
+
+ -- Check if accounting is enabled
+ SELECT "accountingEnabled"
+ INTO v_accounting_enabled
+ FROM "companySettings"
+ WHERE id = p_company_id;
+
+ v_accounting_enabled := COALESCE(v_accounting_enabled, false);
+
+ IF NOT v_accounting_enabled THEN
+ RETURN;
+ END IF;
+
+ -- Fetch company group
+ SELECT "companyGroupId"
+ INTO STRICT v_company_group_id
+ FROM company
+ WHERE id = p_company_id;
+
+ -- Fetch account defaults
+ SELECT "rawMaterialsAccount", "finishedGoodsAccount", "workInProgressAccount", "laborAbsorptionAccount", "overheadAbsorptionAccount", "costOfGoodsSoldAccount"
+ INTO STRICT v_raw_materials_account, v_finished_goods_account, v_wip_account, v_labor_absorption_account, v_overhead_absorption_account, v_cogs_account
+ FROM "accountDefault"
+ WHERE "companyId" = p_company_id;
+
+ -- Resolve Raw Materials vs Finished Goods from the produced item:
+ -- Buy → Raw Materials; Make / Buy and Make → Finished Goods.
+ SELECT
+ CASE WHEN i."replenishmentSystem" = 'Buy' THEN v_raw_materials_account ELSE v_finished_goods_account END,
+ CASE WHEN i."replenishmentSystem" = 'Buy' THEN 'Raw Materials Account' ELSE 'Finished Goods Account' END
+ INTO v_item_inventory_account, v_item_inventory_description
+ FROM "item" i
+ WHERE i."id" = v_item_id
+ AND i."companyId" = p_company_id;
+
+ -- Non-Inventory (Service): the produced output is never stocked, so completion
+ -- relieves WIP straight to Cost of Goods Sold (Epicor "Make Direct" pattern).
+ -- >>> REV-REC SEAM (spec .ai/specs/2026-07-04-revenue-recognition.md, issue #1048):
+ -- when revenue recognition lands, Percent-of-Completion elements will gate THIS
+ -- branch off and post COGS as-incurred in the recognition run instead. <<<
+ IF v_item_tracking_type = 'Non-Inventory' THEN
+ v_item_inventory_account := v_cogs_account;
+ v_item_inventory_description := 'Cost of Goods Sold';
+ END IF;
+
+ -- Fetch dimension IDs
+ SELECT
+ MAX(CASE WHEN "entityType" = 'ItemPostingGroup' THEN id END),
+ MAX(CASE WHEN "entityType" = 'Item' THEN "id" END),
+ MAX(CASE WHEN "entityType" = 'Location' THEN id END),
+ MAX(CASE WHEN "entityType" = 'CostCenter' THEN id END),
+ MAX(CASE WHEN "entityType" = 'Employee' THEN id END)
+ INTO v_dimension_item_posting_group, v_dimension_item, v_dimension_location,
+ v_dimension_cost_center, v_dimension_employee
+ FROM dimension
+ WHERE "companyGroupId" = v_company_group_id
+ AND active = true
+ AND "entityType" IN ('ItemPostingGroup', 'Item', 'Location', 'CostCenter', 'Employee');
+
+ -- Post unposted production events as labor/machine + overhead absorption JEs
+ -- (mirrors post-production-event; this is the catch-up path for events that
+ -- were never posted individually)
+ FOR v_event IN
+ SELECT
+ pe.id,
+ pe.duration,
+ pe.type,
+ pe."employeeId",
+ wc."laborRate",
+ wc."machineRate",
+ wc."overheadRate"
+ FROM "productionEvent" pe
+ INNER JOIN "jobOperation" jo ON jo.id = pe."jobOperationId"
+ INNER JOIN "workCenter" wc ON wc.id = pe."workCenterId"
+ WHERE jo."jobId" = p_job_id
+ AND pe."endTime" IS NOT NULL
+ AND pe."postedToGL" = false
+ AND pe.duration > 0
+ LOOP
+ v_duration_hours := v_event.duration::NUMERIC / 3600;
+ v_rate := CASE
+ WHEN v_event.type = 'Machine' THEN COALESCE(v_event."machineRate", 0)
+ ELSE COALESCE(v_event."laborRate", 0)
+ END;
+ v_labor_cost := v_duration_hours * v_rate;
+ v_overhead_cost := v_duration_hours * COALESCE(v_event."overheadRate", 0);
+ v_event_reference := 'production-event:' || v_event.id;
+
+ IF (v_labor_cost > 0 AND v_labor_absorption_account IS NOT NULL)
+ OR (v_overhead_cost > 0 AND v_overhead_absorption_account IS NOT NULL) THEN
+ v_labor_journal_line_reference := nanoid();
+
+ -- Get current accounting period
+ SELECT id INTO v_labor_accounting_period_id
+ FROM "accountingPeriod"
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= CURRENT_DATE
+ AND "endDate" >= CURRENT_DATE
+ AND status = 'Active'
+ LIMIT 1;
+
+ IF v_labor_accounting_period_id IS NULL THEN
+ UPDATE "accountingPeriod"
+ SET status = 'Inactive'
+ WHERE status = 'Active' AND "companyId" = p_company_id;
+
+ UPDATE "accountingPeriod"
+ SET status = 'Active'
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= CURRENT_DATE
+ AND "endDate" >= CURRENT_DATE
+ RETURNING id INTO v_labor_accounting_period_id;
+
+ IF v_labor_accounting_period_id IS NULL THEN
+ INSERT INTO "accountingPeriod" (
+ "startDate", "endDate", "companyId", status, "createdBy"
+ ) VALUES (
+ date_trunc('month', CURRENT_DATE)::DATE,
+ (date_trunc('month', CURRENT_DATE) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,
+ p_company_id, 'Active', 'system'
+ )
+ RETURNING id INTO v_labor_accounting_period_id;
+ END IF;
+ END IF;
+
+ v_labor_journal_entry_id := get_next_sequence('journalEntry', p_company_id);
+
+ INSERT INTO journal (
+ "journalEntryId", "accountingPeriodId", description,
+ "postingDate", "companyId", "sourceType", status,
+ "postedAt", "postedBy", "createdBy"
+ ) VALUES (
+ v_labor_journal_entry_id, v_labor_accounting_period_id,
+ v_event.type || ' Time — Job ' || v_job_id_readable,
+ CURRENT_DATE, p_company_id, 'Production Event', 'Posted',
+ NOW(), p_user_id, p_user_id
+ )
+ RETURNING id INTO v_labor_journal_id;
+
+ IF v_labor_cost > 0 AND v_labor_absorption_account IS NOT NULL THEN
+ -- DR WIP (labor/machine)
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_wip_account, 'WIP Account',
+ v_labor_cost, 1,
+ 'Production Event', p_job_id, v_event_reference,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on WIP line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on WIP line (the finished good this labor rolls into)
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+
+ -- CR Labor/Machine Absorption
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_labor_absorption_account, 'Labor/Machine Absorption',
+ -v_labor_cost, 1,
+ 'Production Event', p_job_id, v_event_reference,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on absorption line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on absorption line
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+ END IF;
+
+ IF v_overhead_cost > 0 AND v_overhead_absorption_account IS NOT NULL THEN
+ -- DR WIP (overhead)
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_wip_account, 'WIP Account (Overhead)',
+ v_overhead_cost, 1,
+ 'Production Event', p_job_id, v_event_reference,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on WIP overhead line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on WIP overhead line
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+
+ -- CR Overhead Absorption
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_overhead_absorption_account, 'Overhead Absorption',
+ -v_overhead_cost, 1,
+ 'Production Event', p_job_id, v_event_reference,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on overhead absorption line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on overhead absorption line
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+ END IF;
+ END IF;
+
+ UPDATE "productionEvent"
+ SET "postedToGL" = true
+ WHERE id = v_event.id;
+ END LOOP;
+
+ -- Calculate accumulated WIP cost for this job
+ SELECT COALESCE(ABS(SUM(jl.amount)), 0)
+ INTO v_accumulated_wip_cost
+ FROM "journalLine" jl
+ INNER JOIN journal j ON j.id = jl."journalId"
+ WHERE jl."accountId" = v_wip_account
+ AND jl."documentId" = p_job_id
+ AND j."companyId" = p_company_id;
+
+ IF v_accumulated_wip_cost <= 0 THEN
+ RETURN;
+ END IF;
+
+ v_today := CURRENT_DATE;
+ v_journal_line_reference := nanoid();
+
+ -- Get accounting period for WIP discharge
+ SELECT id INTO v_accounting_period_id
+ FROM "accountingPeriod"
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_today
+ AND "endDate" >= v_today
+ AND status = 'Active'
+ LIMIT 1;
+
+ IF v_accounting_period_id IS NULL THEN
+ UPDATE "accountingPeriod"
+ SET status = 'Inactive'
+ WHERE status = 'Active' AND "companyId" = p_company_id;
+
+ UPDATE "accountingPeriod"
+ SET status = 'Active'
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_today
+ AND "endDate" >= v_today
+ RETURNING id INTO v_accounting_period_id;
+
+ IF v_accounting_period_id IS NULL THEN
+ INSERT INTO "accountingPeriod" (
+ "startDate", "endDate", "companyId", status, "createdBy"
+ ) VALUES (
+ date_trunc('month', v_today)::DATE,
+ (date_trunc('month', v_today) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,
+ p_company_id, 'Active', 'system'
+ )
+ RETURNING id INTO v_accounting_period_id;
+ END IF;
+ END IF;
+
+ v_journal_entry_id := get_next_sequence('journalEntry', p_company_id);
+
+ INSERT INTO journal (
+ "journalEntryId", "accountingPeriodId", description,
+ "postingDate", "companyId", "sourceType", status,
+ "postedAt", "postedBy", "createdBy"
+ ) VALUES (
+ v_journal_entry_id, v_accounting_period_id,
+ 'Job Completion ' || v_job_id_readable,
+ v_today, p_company_id, 'Job Receipt', 'Posted',
+ NOW(), p_user_id, p_user_id
+ )
+ RETURNING id INTO v_journal_id;
+
+ -- DR Inventory (Raw Materials or Finished Goods by item)
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_journal_id, v_item_inventory_account, v_item_inventory_description,
+ v_accumulated_wip_cost, v_quantity_received_to_inventory,
+ 'Job Receipt', p_job_id, 'job:' || p_job_id,
+ v_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ v_jl_ids := ARRAY[v_labor_jl_id];
+
+ -- CR WIP
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_journal_id, v_wip_account, 'WIP Account',
+ -v_accumulated_wip_cost, v_quantity_received_to_inventory,
+ 'Job Receipt', p_job_id, 'job:' || p_job_id,
+ v_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ v_jl_ids := v_jl_ids || v_labor_jl_id;
+
+ -- Write costLedger entry for finished good (skipped for Non-Inventory: no
+ -- output layer exists for a service — its cost went straight to COGS above)
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' THEN
+ INSERT INTO "costLedger" (
+ "itemLedgerType", "costLedgerType", adjustment,
+ "documentType", "documentId", "itemId",
+ quantity, cost, "remainingQuantity", "companyId"
+ ) VALUES (
+ 'Output', 'Direct Cost', false,
+ 'Job Receipt', p_job_id, v_item_id,
+ v_quantity_received_to_inventory, v_accumulated_wip_cost,
+ v_quantity_received_to_inventory, p_company_id
+ );
+ END IF;
+
+ -- Update item cost
+ SELECT "costingMethod", "unitCost", "itemPostingGroupId"
+ INTO v_costing_method, v_existing_unit_cost, v_item_posting_group_id
+ FROM "itemCost"
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+
+ -- Update itemCost.unitCost (skipped for Non-Inventory: a service has no
+ -- stocked unit cost; the read above still feeds the dimension inserts below)
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' THEN
+ v_new_per_unit_cost := v_accumulated_wip_cost / v_quantity_received_to_inventory;
+
+ IF v_costing_method = 'Average' THEN
+ SELECT COALESCE(SUM(quantity), 0)
+ INTO v_total_qty_on_hand
+ FROM "itemLedger"
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+
+ v_prior_qty := v_total_qty_on_hand - v_quantity_received_to_inventory;
+ v_prior_value := v_prior_qty * COALESCE(v_existing_unit_cost, 0);
+
+ IF v_total_qty_on_hand > 0 THEN
+ v_new_unit_cost := (v_prior_value + v_accumulated_wip_cost) / v_total_qty_on_hand;
+ UPDATE "itemCost"
+ SET "unitCost" = v_new_unit_cost
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+ END IF;
+
+ ELSIF v_costing_method IN ('FIFO', 'LIFO') THEN
+ UPDATE "itemCost"
+ SET "unitCost" = v_new_per_unit_cost
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+ END IF;
+ END IF;
+
+ -- Insert dimensions on WIP discharge journal lines
+ IF v_jl_ids IS NOT NULL AND array_length(v_jl_ids, 1) > 0 THEN
+ FOR i IN 1..array_length(v_jl_ids, 1)
+ LOOP
+ IF v_item_posting_group_id IS NOT NULL AND v_dimension_item_posting_group IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_item_posting_group, v_item_posting_group_id, p_company_id
+ );
+ END IF;
+
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+
+ IF v_job_location_id IS NOT NULL AND v_dimension_location IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_location, v_job_location_id, p_company_id
+ );
+ END IF;
+ END LOOP;
+ END IF;
+END;
+$$;
diff --git a/packages/ee/src/accounting/core/models.ts b/packages/ee/src/accounting/core/models.ts
index a2a49fc982..f0856a18b8 100644
--- a/packages/ee/src/accounting/core/models.ts
+++ b/packages/ee/src/accounting/core/models.ts
@@ -503,7 +503,14 @@ export const ItemSchema = z.object({
name: z.string(),
description: withNullable(z.string()),
companyId: z.string(),
- type: z.enum(["Part", "Material", "Tool", "Consumable", "Fixture"]),
+ type: z.enum([
+ "Part",
+ "Material",
+ "Tool",
+ "Consumable",
+ "Fixture",
+ "Service"
+ ]),
unitOfMeasureCode: withNullable(z.string()),
unitCost: z.number(),
unitSalePrice: z.number(),
diff --git a/packages/ee/src/accounting/providers/xero/entities/item.ts b/packages/ee/src/accounting/providers/xero/entities/item.ts
index 2f48719751..743bb60792 100644
--- a/packages/ee/src/accounting/providers/xero/entities/item.ts
+++ b/packages/ee/src/accounting/providers/xero/entities/item.ts
@@ -11,7 +11,7 @@ type ItemRow = {
name: string;
description: string | null;
companyId: string | null;
- type: "Part" | "Material" | "Tool" | "Consumable" | "Fixture";
+ type: "Part" | "Material" | "Tool" | "Consumable" | "Fixture" | "Service";
unitOfMeasureCode: string | null;
replenishmentSystem: "Buy" | "Make" | "Buy and Make";
itemTrackingType: string;
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 4379e57189..dbd4ec5fd1 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -334,6 +334,9 @@ msgstr "Ein Verkaufs-RFQ (ein Kunde bittet Sie zu zitieren) oder ein Einkaufs-RF
msgid "A separate schedule for tax reporting when tax rules require a method different from book depreciation."
msgstr "Ein separater Zeitplan für die Steuererklärung, wenn die Steuervorschriften eine andere Methode als die Buchabschreibung erfordern."
+msgid "A service is a billable activity that is bought or performed — it is never shipped, received, or stocked"
+msgstr "Eine Dienstleistung ist eine abrechenbare Tätigkeit, die gekauft oder erbracht wird – sie wird nie versandt, empfangen oder gelagert"
+
msgid "A set of companies under one owner that share group-scoped configuration — the chart of accounts, currencies, and dimensions — so the same accounting setup spans every company in the group."
msgstr "Eine Gruppe von Unternehmen unter einem Eigentümer, die gruppenweite Konfigurationen teilen – den Kontenplan, Währungen und Dimensionen –, sodass dieselbe Buchhaltungseinrichtung für jedes Unternehmen der Gruppe gilt."
@@ -2639,6 +2642,9 @@ msgstr "Link zum Teil kopieren"
msgid "Copy link to procedure"
msgstr "Link zum Verfahren kopieren"
+msgid "Copy link to service"
+msgstr "Link zur Dienstleistung kopieren"
+
msgid "Copy link to tool"
msgstr "Link zum Werkzeug kopieren"
@@ -2687,6 +2693,12 @@ msgstr "Angebot kopieren"
msgid "Copy Quote number"
msgstr "Angebotsnummer kopieren"
+msgid "Copy service number"
+msgstr "Dienstleistungsnummer kopieren"
+
+msgid "Copy service unique identifier"
+msgstr "Eindeutige Kennung der Dienstleistung kopieren"
+
msgid "Copy this item's pricing to another scope."
msgstr "Kopieren Sie die Preisgestaltung dieses Artikels in einen anderen Bereich."
@@ -2984,6 +2996,9 @@ msgstr "Erforderliche Aktion erstellt"
msgid "Created scrap reason"
msgstr "Verschrottungsgrund erstellt"
+msgid "Created service"
+msgstr "Dienstleistung erstellt"
+
msgid "Created shipping method"
msgstr "Versandmethode erstellt"
@@ -3694,6 +3709,9 @@ msgstr "Verkaufsauftrag löschen"
msgid "Delete Schedule"
msgstr "Zeitplan löschen"
+msgid "Delete Service"
+msgstr "Dienstleistung löschen"
+
msgid "Delete Shift"
msgstr "Schicht löschen"
@@ -4370,6 +4388,9 @@ msgstr "Geplante Wartung bearbeiten"
msgid "Edit Sequence"
msgstr "Sequenz bearbeiten"
+msgid "Edit Service"
+msgstr "Dienstleistung bearbeiten"
+
msgid "Edit Shift"
msgstr "Schicht bearbeiten"
@@ -4991,6 +5012,10 @@ msgstr "Zahlungsbedingung konnte nicht erstellt werden: {0}"
msgid "Failed to create process: {0}"
msgstr "Fehler beim Erstellen des Prozesses: {0}"
+#. placeholder {0}: fetcher.data.error.message
+msgid "Failed to create service: {0}"
+msgstr "Fehler beim Erstellen der Dienstleistung: {0}"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create shipping method: {0}"
msgstr "Fehler beim Erstellen der Versandmethode: {0}"
@@ -7632,6 +7657,9 @@ msgstr "Neue Verkaufsauftragsposition"
msgid "New Scheduled Maintenance"
msgstr "Neue geplante Wartung"
+msgid "New Service"
+msgstr "Neue Dienstleistung"
+
msgid "New Shift"
msgstr "Neue Schicht"
@@ -10604,12 +10632,18 @@ msgstr "Servicegebühren"
msgid "Service Charges (default)"
msgstr "Servicegebühren (Standard)"
+msgid "Service Details"
+msgstr "Dienstleistungsdetails"
+
msgid "Service ID"
msgstr "Service-ID"
msgid "services"
msgstr "Dienstleistungen"
+msgid "Services"
+msgstr "Dienstleistungen"
+
msgid "Set a target"
msgstr "Ziel festlegen"
@@ -13008,6 +13042,9 @@ msgstr "Verwenden Sie ..., um die nächste Material-ID zu erhalten"
msgid "Use ... to get the next part ID"
msgstr "Verwenden Sie ..., um die nächste Teile-ID zu erhalten"
+msgid "Use ... to get the next service ID"
+msgstr "Verwenden Sie ..., um die nächste Dienstleistungs-ID zu erhalten"
+
msgid "Use ... to get the next tool ID"
msgstr "Verwenden Sie ..., um die nächste Werkzeug-ID zu erhalten"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 7760fe6312..4eeaf4f792 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -334,6 +334,9 @@ msgstr "A sales RFQ (a customer asks you to quote) or a purchasing RFQ (you ask
msgid "A separate schedule for tax reporting when tax rules require a method different from book depreciation."
msgstr "A separate schedule for tax reporting when tax rules require a method different from book depreciation."
+msgid "A service is a billable activity that is bought or performed — it is never shipped, received, or stocked"
+msgstr "A service is a billable activity that is bought or performed — it is never shipped, received, or stocked"
+
msgid "A set of companies under one owner that share group-scoped configuration — the chart of accounts, currencies, and dimensions — so the same accounting setup spans every company in the group."
msgstr "A set of companies under one owner that share group-scoped configuration — the chart of accounts, currencies, and dimensions — so the same accounting setup spans every company in the group."
@@ -2639,6 +2642,9 @@ msgstr "Copy link to part"
msgid "Copy link to procedure"
msgstr "Copy link to procedure"
+msgid "Copy link to service"
+msgstr "Copy link to service"
+
msgid "Copy link to tool"
msgstr "Copy link to tool"
@@ -2687,6 +2693,12 @@ msgstr "Copy Quote"
msgid "Copy Quote number"
msgstr "Copy Quote number"
+msgid "Copy service number"
+msgstr "Copy service number"
+
+msgid "Copy service unique identifier"
+msgstr "Copy service unique identifier"
+
msgid "Copy this item's pricing to another scope."
msgstr "Copy this item's pricing to another scope."
@@ -2984,6 +2996,9 @@ msgstr "Created required action"
msgid "Created scrap reason"
msgstr "Created scrap reason"
+msgid "Created service"
+msgstr "Created service"
+
msgid "Created shipping method"
msgstr "Created shipping method"
@@ -3694,6 +3709,9 @@ msgstr "Delete Sales Order"
msgid "Delete Schedule"
msgstr "Delete Schedule"
+msgid "Delete Service"
+msgstr "Delete Service"
+
msgid "Delete Shift"
msgstr "Delete Shift"
@@ -4370,6 +4388,9 @@ msgstr "Edit Scheduled Maintenance"
msgid "Edit Sequence"
msgstr "Edit Sequence"
+msgid "Edit Service"
+msgstr "Edit Service"
+
msgid "Edit Shift"
msgstr "Edit Shift"
@@ -4991,6 +5012,10 @@ msgstr "Failed to create payment term: {0}"
msgid "Failed to create process: {0}"
msgstr "Failed to create process: {0}"
+#. placeholder {0}: fetcher.data.error.message
+msgid "Failed to create service: {0}"
+msgstr "Failed to create service: {0}"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create shipping method: {0}"
msgstr "Failed to create shipping method: {0}"
@@ -7632,6 +7657,9 @@ msgstr "New Sales Order Line"
msgid "New Scheduled Maintenance"
msgstr "New Scheduled Maintenance"
+msgid "New Service"
+msgstr "New Service"
+
msgid "New Shift"
msgstr "New Shift"
@@ -10604,12 +10632,18 @@ msgstr "Service Charges"
msgid "Service Charges (default)"
msgstr "Service Charges (default)"
+msgid "Service Details"
+msgstr "Service Details"
+
msgid "Service ID"
msgstr "Service ID"
msgid "services"
msgstr "services"
+msgid "Services"
+msgstr "Services"
+
msgid "Set a target"
msgstr "Set a target"
@@ -13008,6 +13042,9 @@ msgstr "Use ... to get the next material ID"
msgid "Use ... to get the next part ID"
msgstr "Use ... to get the next part ID"
+msgid "Use ... to get the next service ID"
+msgstr "Use ... to get the next service ID"
+
msgid "Use ... to get the next tool ID"
msgstr "Use ... to get the next tool ID"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index af0c3b61c6..f9cb62a348 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -334,6 +334,9 @@ msgstr "Un RFQ de venta (un cliente te pide que cotices) o un RFQ de compra (tu
msgid "A separate schedule for tax reporting when tax rules require a method different from book depreciation."
msgstr "Un cronograma separado para la presentación de impuestos cuando las reglas fiscales requieren un método diferente a la depreciación de libros."
+msgid "A service is a billable activity that is bought or performed — it is never shipped, received, or stocked"
+msgstr "Un servicio es una actividad facturable que se compra o realiza; nunca se envía, recibe o almacena"
+
msgid "A set of companies under one owner that share group-scoped configuration — the chart of accounts, currencies, and dimensions — so the same accounting setup spans every company in the group."
msgstr "Un conjunto de empresas bajo un mismo propietario que comparten una configuración con alcance de grupo —el plan de cuentas, las monedas y las dimensiones— de modo que la misma configuración contable abarca todas las empresas del grupo."
@@ -2639,6 +2642,9 @@ msgstr "Copiar enlace a la pieza"
msgid "Copy link to procedure"
msgstr "Copiar enlace al procedimiento"
+msgid "Copy link to service"
+msgstr "Copiar enlace al servicio"
+
msgid "Copy link to tool"
msgstr "Copiar enlace a la herramienta"
@@ -2687,6 +2693,12 @@ msgstr "Copiar Presupuesto"
msgid "Copy Quote number"
msgstr "Copiar número de cotización"
+msgid "Copy service number"
+msgstr "Copiar número de servicio"
+
+msgid "Copy service unique identifier"
+msgstr "Copiar identificador único del servicio"
+
msgid "Copy this item's pricing to another scope."
msgstr "Copiar el precio de este artículo a otro ámbito."
@@ -2984,6 +2996,9 @@ msgstr "Acción requerida creada"
msgid "Created scrap reason"
msgstr "Razón de rechazo creada"
+msgid "Created service"
+msgstr "Servicio creado"
+
msgid "Created shipping method"
msgstr "Método de envío creado"
@@ -3694,6 +3709,9 @@ msgstr "Eliminar Orden de Venta"
msgid "Delete Schedule"
msgstr "Eliminar Programa"
+msgid "Delete Service"
+msgstr "Eliminar servicio"
+
msgid "Delete Shift"
msgstr "Eliminar Turno"
@@ -4370,6 +4388,9 @@ msgstr "Editar Mantenimiento Programado"
msgid "Edit Sequence"
msgstr "Editar Secuencia"
+msgid "Edit Service"
+msgstr "Editar servicio"
+
msgid "Edit Shift"
msgstr "Editar Turno"
@@ -4991,6 +5012,10 @@ msgstr "Error al crear el término de pago: {0}"
msgid "Failed to create process: {0}"
msgstr "Error al crear proceso: {0}"
+#. placeholder {0}: fetcher.data.error.message
+msgid "Failed to create service: {0}"
+msgstr "Error al crear el servicio: {0}"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create shipping method: {0}"
msgstr "Error al crear el método de envío: {0}"
@@ -7632,6 +7657,9 @@ msgstr "Nueva Línea de Orden de Venta"
msgid "New Scheduled Maintenance"
msgstr "Nuevo Mantenimiento Programado"
+msgid "New Service"
+msgstr "Nuevo servicio"
+
msgid "New Shift"
msgstr "Nuevo Turno"
@@ -10604,12 +10632,18 @@ msgstr "Cargos de servicio"
msgid "Service Charges (default)"
msgstr "Cargos de servicio (predeterminado)"
+msgid "Service Details"
+msgstr "Detalles del servicio"
+
msgid "Service ID"
msgstr "ID del Servicio"
msgid "services"
msgstr "servicios"
+msgid "Services"
+msgstr "Servicios"
+
msgid "Set a target"
msgstr "Establecer un objetivo"
@@ -13008,6 +13042,9 @@ msgstr "Utiliza ... para obtener el siguiente ID de material"
msgid "Use ... to get the next part ID"
msgstr "Usa ... para obtener el siguiente ID de parte"
+msgid "Use ... to get the next service ID"
+msgstr "Usa ... para obtener el siguiente ID de servicio"
+
msgid "Use ... to get the next tool ID"
msgstr "Usa ... para obtener el siguiente ID de herramienta"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index b31fa2c9fd..7406c5fabb 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -334,6 +334,9 @@ msgstr "Un RFQ de vente (un client vous demande de citer) ou un RFQ d'achat (vou
msgid "A separate schedule for tax reporting when tax rules require a method different from book depreciation."
msgstr "Un calendrier séparé pour la déclaration fiscale lorsque les règles fiscales exigent une méthode différente de l'amortissement comptable."
+msgid "A service is a billable activity that is bought or performed — it is never shipped, received, or stocked"
+msgstr "Un service est une activité facturable qui est achetée ou exécutée — il n'est jamais expédié, reçu ou stocké"
+
msgid "A set of companies under one owner that share group-scoped configuration — the chart of accounts, currencies, and dimensions — so the same accounting setup spans every company in the group."
msgstr "Un ensemble d'entreprises sous un même propriétaire qui partagent une configuration à l'échelle du groupe — le plan comptable, les devises et les dimensions — de sorte que la même configuration comptable s'applique à toutes les entreprises du groupe."
@@ -2639,6 +2642,9 @@ msgstr "Copier le lien vers la pièce"
msgid "Copy link to procedure"
msgstr "Copier le lien vers la procédure"
+msgid "Copy link to service"
+msgstr "Copier le lien vers le service"
+
msgid "Copy link to tool"
msgstr "Copier le lien de l'outil"
@@ -2687,6 +2693,12 @@ msgstr "Copier le devis"
msgid "Copy Quote number"
msgstr "Copier le numéro de devis"
+msgid "Copy service number"
+msgstr "Copier le numéro de service"
+
+msgid "Copy service unique identifier"
+msgstr "Copier l'identifiant unique du service"
+
msgid "Copy this item's pricing to another scope."
msgstr "Copiez la tarification de cet article vers une autre portée."
@@ -2984,6 +2996,9 @@ msgstr "Action requise créée"
msgid "Created scrap reason"
msgstr "Raison de rebut créée"
+msgid "Created service"
+msgstr "Service créé"
+
msgid "Created shipping method"
msgstr "Méthode d'expédition créée"
@@ -3694,6 +3709,9 @@ msgstr "Supprimer la commande client"
msgid "Delete Schedule"
msgstr "Supprimer le calendrier"
+msgid "Delete Service"
+msgstr "Supprimer le service"
+
msgid "Delete Shift"
msgstr "Supprimer le quart"
@@ -4370,6 +4388,9 @@ msgstr "Modifier la maintenance planifiée"
msgid "Edit Sequence"
msgstr "Modifier la séquence"
+msgid "Edit Service"
+msgstr "Modifier le service"
+
msgid "Edit Shift"
msgstr "Modifier le quart"
@@ -4991,6 +5012,10 @@ msgstr "Échec de la création du délai de paiement : {0}"
msgid "Failed to create process: {0}"
msgstr "Échec de la création du processus : {0}"
+#. placeholder {0}: fetcher.data.error.message
+msgid "Failed to create service: {0}"
+msgstr "Échec de la création du service : {0}"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create shipping method: {0}"
msgstr "Échec de la création de la méthode d'expédition : {0}"
@@ -7632,6 +7657,9 @@ msgstr "Nouvelle ligne de commande client"
msgid "New Scheduled Maintenance"
msgstr "Nouvelle Maintenance Planifiée"
+msgid "New Service"
+msgstr "Nouveau service"
+
msgid "New Shift"
msgstr "Nouveau Quart"
@@ -10604,12 +10632,18 @@ msgstr "Frais de service"
msgid "Service Charges (default)"
msgstr "Frais de service (défaut)"
+msgid "Service Details"
+msgstr "Détails du service"
+
msgid "Service ID"
msgstr "ID du Service"
msgid "services"
msgstr "services"
+msgid "Services"
+msgstr "Services"
+
msgid "Set a target"
msgstr "Définir un objectif"
@@ -13008,6 +13042,9 @@ msgstr "Utilisez ... pour obtenir l'ID de matériau suivant"
msgid "Use ... to get the next part ID"
msgstr "Utilisez ... pour obtenir l'ID de pièce suivant"
+msgid "Use ... to get the next service ID"
+msgstr "Utilisez ... pour obtenir le prochain ID de service"
+
msgid "Use ... to get the next tool ID"
msgstr "Utilisez ... pour obtenir l'ID d'outil suivant"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index de3c2e3177..c57c8b3297 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -334,6 +334,9 @@ msgstr "एक बिक्रय RFQ (एक ग्राहक आपको
msgid "A separate schedule for tax reporting when tax rules require a method different from book depreciation."
msgstr "कर रिपोर्टिंग के लिए एक अलग अनुसूची जब कर नियम पुस्तक मूल्यह्रास से अलग विधि की आवश्यकता होती है।"
+msgid "A service is a billable activity that is bought or performed — it is never shipped, received, or stocked"
+msgstr "एक सेवा एक बिलयोग्य गतिविधि है जो खरीदी या प्रदर्शन की जाती है — इसे कभी भेजा नहीं जाता, प्राप्त नहीं किया जाता, या स्टॉक नहीं किया जाता"
+
msgid "A set of companies under one owner that share group-scoped configuration — the chart of accounts, currencies, and dimensions — so the same accounting setup spans every company in the group."
msgstr "एक ही मालिक के अधीन कंपनियों का समूह जो समूह-स्तरीय कॉन्फ़िगरेशन साझा करती हैं — खातों का चार्ट, मुद्राएँ और आयाम — ताकि वही लेखांकन सेटअप समूह की हर कंपनी पर लागू हो।"
@@ -2639,6 +2642,9 @@ msgstr "भाग के लिए लिंक कॉपी करें"
msgid "Copy link to procedure"
msgstr "प्रक्रिया के लिए लिंक कॉपी करें"
+msgid "Copy link to service"
+msgstr "सेवा के लिए लिंक कॉपी करें"
+
msgid "Copy link to tool"
msgstr "टूल के लिए लिंक कॉपी करें"
@@ -2687,6 +2693,12 @@ msgstr "उद्धरण की प्रतिलिपि बनाएँ"
msgid "Copy Quote number"
msgstr "उद्धरण संख्या कॉपी करें"
+msgid "Copy service number"
+msgstr "सेवा संख्या कॉपी करें"
+
+msgid "Copy service unique identifier"
+msgstr "सेवा अनन्य पहचानकर्ता कॉपी करें"
+
msgid "Copy this item's pricing to another scope."
msgstr "इस आइटम की मूल्य निर्धारण को दूसरे स्कोप में कॉपी करें।"
@@ -2984,6 +2996,9 @@ msgstr "आवश्यक कार्रवाई बनाई गई"
msgid "Created scrap reason"
msgstr "स्क्रैप कारण बनाया गया"
+msgid "Created service"
+msgstr "सेवा बनाई गई"
+
msgid "Created shipping method"
msgstr "शिपिंग विधि बनाई गई"
@@ -3694,6 +3709,9 @@ msgstr "बिक्रय आदेश हटाएं"
msgid "Delete Schedule"
msgstr "शेड्यूल हटाएं"
+msgid "Delete Service"
+msgstr "सेवा हटाएं"
+
msgid "Delete Shift"
msgstr "शिफ्ट हटाएं"
@@ -4370,6 +4388,9 @@ msgstr "निर्धारित रखरखाव संपादित क
msgid "Edit Sequence"
msgstr "अनुक्रम संपादित करें"
+msgid "Edit Service"
+msgstr "सेवा संपादित करें"
+
msgid "Edit Shift"
msgstr "शिफ्ट संपादित करें"
@@ -4991,6 +5012,10 @@ msgstr "भुगतान शर्त बनाने में विफल:
msgid "Failed to create process: {0}"
msgstr "प्रक्रिया बनाने में विफल: {0}"
+#. placeholder {0}: fetcher.data.error.message
+msgid "Failed to create service: {0}"
+msgstr "सेवा बनाने में विफल: {0}"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create shipping method: {0}"
msgstr "शिपिंग विधि बनाने में विफल: {0}"
@@ -7632,6 +7657,9 @@ msgstr "नई बिक्रय आदेश पंक्ति"
msgid "New Scheduled Maintenance"
msgstr "नया निर्धारित रखरखाव"
+msgid "New Service"
+msgstr "नई सेवा"
+
msgid "New Shift"
msgstr "नई शिफ्ट"
@@ -10604,12 +10632,18 @@ msgstr "सेवा शुल्क"
msgid "Service Charges (default)"
msgstr "सेवा शुल्क (डिफ़ॉल्ट)"
+msgid "Service Details"
+msgstr "सेवा विवरण"
+
msgid "Service ID"
msgstr "सेवा ID"
msgid "services"
msgstr "सेवाएं"
+msgid "Services"
+msgstr "सेवाएं"
+
msgid "Set a target"
msgstr "लक्ष्य निर्धारित करें"
@@ -13008,6 +13042,9 @@ msgstr "अगली सामग्री ID प्राप्त करने
msgid "Use ... to get the next part ID"
msgstr "अगला पार्ट आईडी प्राप्त करने के लिए ... का उपयोग करें"
+msgid "Use ... to get the next service ID"
+msgstr "अगली सेवा ID प्राप्त करने के लिए ... का उपयोग करें"
+
msgid "Use ... to get the next tool ID"
msgstr "अगली टूल ID प्राप्त करने के लिए ... का उपयोग करें"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 733a493fd6..8dbdd81575 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -334,6 +334,9 @@ msgstr "Un RFQ di vendita (un cliente ti chiede di quotare) o un RFQ di acquisto
msgid "A separate schedule for tax reporting when tax rules require a method different from book depreciation."
msgstr "Un calendario separato per la dichiarazione dei redditi quando le regole fiscali richiedono un metodo diverso dall'ammortamento contabile."
+msgid "A service is a billable activity that is bought or performed — it is never shipped, received, or stocked"
+msgstr "Un servizio è un'attività fatturabile che viene acquistata o eseguita — non viene mai spedita, ricevuta o stoccata"
+
msgid "A set of companies under one owner that share group-scoped configuration — the chart of accounts, currencies, and dimensions — so the same accounting setup spans every company in the group."
msgstr "Un insieme di aziende sotto un unico proprietario che condividono una configurazione a livello di gruppo — il piano dei conti, le valute e le dimensioni — in modo che la stessa configurazione contabile si applichi a ogni azienda del gruppo."
@@ -2639,6 +2642,9 @@ msgstr "Copia il collegamento alla parte"
msgid "Copy link to procedure"
msgstr "Copia collegamento alla procedura"
+msgid "Copy link to service"
+msgstr "Copia link al servizio"
+
msgid "Copy link to tool"
msgstr "Copia il collegamento dello strumento"
@@ -2687,6 +2693,12 @@ msgstr "Copia Preventivo"
msgid "Copy Quote number"
msgstr "Copia numero preventivo"
+msgid "Copy service number"
+msgstr "Copia numero servizio"
+
+msgid "Copy service unique identifier"
+msgstr "Copia identificatore univoco del servizio"
+
msgid "Copy this item's pricing to another scope."
msgstr "Copia il prezzo di questo articolo in un altro ambito."
@@ -2984,6 +2996,9 @@ msgstr "Azione richiesta creata"
msgid "Created scrap reason"
msgstr "Motivo di scarto creato"
+msgid "Created service"
+msgstr "Servizio creato"
+
msgid "Created shipping method"
msgstr "Metodo di spedizione creato"
@@ -3694,6 +3709,9 @@ msgstr "Elimina Ordine di Vendita"
msgid "Delete Schedule"
msgstr "Elimina Pianificazione"
+msgid "Delete Service"
+msgstr "Elimina Servizio"
+
msgid "Delete Shift"
msgstr "Elimina Turno"
@@ -4370,6 +4388,9 @@ msgstr "Modifica Manutenzione Programmata"
msgid "Edit Sequence"
msgstr "Modifica Sequenza"
+msgid "Edit Service"
+msgstr "Modifica Servizio"
+
msgid "Edit Shift"
msgstr "Modifica Turno"
@@ -4991,6 +5012,10 @@ msgstr "Impossibile creare il termine di pagamento: {0}"
msgid "Failed to create process: {0}"
msgstr "Impossibile creare il processo: {0}"
+#. placeholder {0}: fetcher.data.error.message
+msgid "Failed to create service: {0}"
+msgstr "Impossibile creare il servizio: {0}"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create shipping method: {0}"
msgstr "Impossibile creare il metodo di spedizione: {0}"
@@ -7632,6 +7657,9 @@ msgstr "Nuova Riga Ordine Vendita"
msgid "New Scheduled Maintenance"
msgstr "Nuova Manutenzione Programmata"
+msgid "New Service"
+msgstr "Nuovo Servizio"
+
msgid "New Shift"
msgstr "Nuovo Turno"
@@ -10604,12 +10632,18 @@ msgstr "Spese di servizio"
msgid "Service Charges (default)"
msgstr "Spese di servizio (predefinito)"
+msgid "Service Details"
+msgstr "Dettagli Servizio"
+
msgid "Service ID"
msgstr "ID Servizio"
msgid "services"
msgstr "servizi"
+msgid "Services"
+msgstr "Servizi"
+
msgid "Set a target"
msgstr "Imposta un obiettivo"
@@ -13008,6 +13042,9 @@ msgstr "Usa ... per ottenere il prossimo ID materiale"
msgid "Use ... to get the next part ID"
msgstr "Usa ... per ottenere l'ID parte successivo"
+msgid "Use ... to get the next service ID"
+msgstr "Usa ... per ottenere il prossimo ID servizio"
+
msgid "Use ... to get the next tool ID"
msgstr "Usa ... per ottenere il prossimo ID strumento"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 45559321d6..413541364a 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -334,6 +334,9 @@ msgstr "販売RFQ(顧客が見積りを依頼)または購買RFQ(仕入先
msgid "A separate schedule for tax reporting when tax rules require a method different from book depreciation."
msgstr "税務規則が帳簿折旧と異なる方法を要求する場合の税務報告用の別個のスケジュール。"
+msgid "A service is a billable activity that is bought or performed — it is never shipped, received, or stocked"
+msgstr "サービスは、購入または実行される請求可能なアクティビティです。配送、受取、または在庫されることはありません"
+
msgid "A set of companies under one owner that share group-scoped configuration — the chart of accounts, currencies, and dimensions — so the same accounting setup spans every company in the group."
msgstr "同一の所有者の下にある会社の集合で、グループ単位の構成(勘定科目表、通貨、ディメンション)を共有し、同じ会計設定がグループ内のすべての会社に適用されます。"
@@ -2639,6 +2642,9 @@ msgstr "パーツへのリンクをコピー"
msgid "Copy link to procedure"
msgstr "プロシージャへのリンクをコピー"
+msgid "Copy link to service"
+msgstr "サービスへのリンクをコピー"
+
msgid "Copy link to tool"
msgstr "ツールへのリンクをコピー"
@@ -2687,6 +2693,12 @@ msgstr "見積書をコピー"
msgid "Copy Quote number"
msgstr "見積番号をコピー"
+msgid "Copy service number"
+msgstr "サービス番号をコピー"
+
+msgid "Copy service unique identifier"
+msgstr "サービスの一意な識別子をコピー"
+
msgid "Copy this item's pricing to another scope."
msgstr "このアイテムの価格設定を別のスコープにコピーします。"
@@ -2984,6 +2996,9 @@ msgstr "必須アクションを作成しました"
msgid "Created scrap reason"
msgstr "スクラップ理由を作成しました"
+msgid "Created service"
+msgstr "サービスを作成しました"
+
msgid "Created shipping method"
msgstr "配送方法を作成しました"
@@ -3694,6 +3709,9 @@ msgstr "販売注文を削除"
msgid "Delete Schedule"
msgstr "スケジュールを削除"
+msgid "Delete Service"
+msgstr "サービスを削除"
+
msgid "Delete Shift"
msgstr "シフトを削除"
@@ -4370,6 +4388,9 @@ msgstr "スケジュール済みメンテナンスを編集"
msgid "Edit Sequence"
msgstr "シーケンスを編集"
+msgid "Edit Service"
+msgstr "サービスを編集"
+
msgid "Edit Shift"
msgstr "シフトを編集"
@@ -4991,6 +5012,10 @@ msgstr "支払い条件の作成に失敗しました: {0}"
msgid "Failed to create process: {0}"
msgstr "プロセスの作成に失敗しました: {0}"
+#. placeholder {0}: fetcher.data.error.message
+msgid "Failed to create service: {0}"
+msgstr "サービスの作成に失敗しました: {0}"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create shipping method: {0}"
msgstr "配送方法の作成に失敗しました: {0}"
@@ -7632,6 +7657,9 @@ msgstr "新しい販売注文行"
msgid "New Scheduled Maintenance"
msgstr "新しいスケジュール済みメンテナンス"
+msgid "New Service"
+msgstr "新規サービス"
+
msgid "New Shift"
msgstr "新しいシフト"
@@ -10604,12 +10632,18 @@ msgstr "サービス料金"
msgid "Service Charges (default)"
msgstr "サービス料金 (既定)"
+msgid "Service Details"
+msgstr "サービス詳細"
+
msgid "Service ID"
msgstr "サービスID"
msgid "services"
msgstr "サービス"
+msgid "Services"
+msgstr "サービス"
+
msgid "Set a target"
msgstr "ターゲットを設定"
@@ -13008,6 +13042,9 @@ msgstr "「...」を使用して次の材料IDを取得します"
msgid "Use ... to get the next part ID"
msgstr "「...」を使用して次のパートIDを取得します"
+msgid "Use ... to get the next service ID"
+msgstr "... を使用して次のサービス ID を取得"
+
msgid "Use ... to get the next tool ID"
msgstr "「...」を使用して次のツールIDを取得します"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index eb3e5d2124..88fba511a0 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -334,6 +334,9 @@ msgstr "판매 RFQ(고객이 견적을 요청) 또는 구매 RFQ(귀사가 공
msgid "A separate schedule for tax reporting when tax rules require a method different from book depreciation."
msgstr "세무 신고용 별도 상각 스케줄로, 세법이 장부상 감가상각과 다른 방법을 요구할 때 사용합니다."
+msgid "A service is a billable activity that is bought or performed — it is never shipped, received, or stocked"
+msgstr "서비스는 구매하거나 수행되는 청구 가능한 활동이며, 절대 배송되거나 수령되거나 재고되지 않습니다"
+
msgid "A set of companies under one owner that share group-scoped configuration — the chart of accounts, currencies, and dimensions — so the same accounting setup spans every company in the group."
msgstr "하나의 소유주 아래 있는 여러 회사가 계정과목표, 통화, 차원 등 그룹 범위 설정을 공유하여, 그룹 내 모든 회사에 동일한 회계 설정이 적용되도록 합니다."
@@ -2639,6 +2642,9 @@ msgstr "품목 링크 복사"
msgid "Copy link to procedure"
msgstr "절차 링크 복사"
+msgid "Copy link to service"
+msgstr "서비스 링크 복사"
+
msgid "Copy link to tool"
msgstr "공구 링크 복사"
@@ -2687,6 +2693,12 @@ msgstr "견적 복사"
msgid "Copy Quote number"
msgstr "견적 번호 복사"
+msgid "Copy service number"
+msgstr "서비스 번호 복사"
+
+msgid "Copy service unique identifier"
+msgstr "서비스 고유 식별자 복사"
+
msgid "Copy this item's pricing to another scope."
msgstr "이 품목의 가격을 다른 범위로 복사합니다."
@@ -2984,6 +2996,9 @@ msgstr "필수 조치 생성됨"
msgid "Created scrap reason"
msgstr "스크랩 사유 생성됨"
+msgid "Created service"
+msgstr "서비스 생성됨"
+
msgid "Created shipping method"
msgstr "배송 방법 생성됨"
@@ -3694,6 +3709,9 @@ msgstr "판매주문 삭제"
msgid "Delete Schedule"
msgstr "일정 삭제"
+msgid "Delete Service"
+msgstr "서비스 삭제"
+
msgid "Delete Shift"
msgstr "교대 삭제"
@@ -4370,6 +4388,9 @@ msgstr "예정된 유지보수 수정"
msgid "Edit Sequence"
msgstr "순서 수정"
+msgid "Edit Service"
+msgstr "서비스 편집"
+
msgid "Edit Shift"
msgstr "교대 수정"
@@ -4991,6 +5012,10 @@ msgstr "결제조건 생성 실패: {0}"
msgid "Failed to create process: {0}"
msgstr "공정 생성 실패: {0}"
+#. placeholder {0}: fetcher.data.error.message
+msgid "Failed to create service: {0}"
+msgstr "서비스 생성 실패: {0}"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create shipping method: {0}"
msgstr "배송 방법 생성 실패: {0}"
@@ -7632,6 +7657,9 @@ msgstr "새 판매주문 라인"
msgid "New Scheduled Maintenance"
msgstr "새 예정된 유지보수"
+msgid "New Service"
+msgstr "새 서비스"
+
msgid "New Shift"
msgstr "새 교대"
@@ -10604,12 +10632,18 @@ msgstr "서비스 요금"
msgid "Service Charges (default)"
msgstr "서비스 요금(기본값)"
+msgid "Service Details"
+msgstr "서비스 상세정보"
+
msgid "Service ID"
msgstr "서비스 ID"
msgid "services"
msgstr "서비스"
+msgid "Services"
+msgstr "서비스"
+
msgid "Set a target"
msgstr "목표 설정"
@@ -13008,6 +13042,9 @@ msgstr "다음 자재 ID를 가져오려면 ...을(를) 사용하세요"
msgid "Use ... to get the next part ID"
msgstr "다음 품목 ID를 가져오려면 ...을(를) 사용하세요"
+msgid "Use ... to get the next service ID"
+msgstr "다음 서비스 ID를 얻으려면 ...을(를) 사용하세요"
+
msgid "Use ... to get the next tool ID"
msgstr "다음 공구 ID를 가져오려면 ...을(를) 사용하세요"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index dd8a531f1f..118d52f405 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -334,6 +334,9 @@ msgstr "RFQ sprzedażowy (klient prosi Cię o wycenę) lub RFQ zakupowy (pytasz
msgid "A separate schedule for tax reporting when tax rules require a method different from book depreciation."
msgstr "Osobny harmonogram dla sprawozdawczości podatkowej, gdy przepisy podatkowe wymagają metody innej niż amortyzacja księgowa."
+msgid "A service is a billable activity that is bought or performed — it is never shipped, received, or stocked"
+msgstr "Usługa to działalność podlegająca rozliczeniu, która jest kupowana lub wykonywana — nigdy nie jest wysyłana, odbierana ani magazynowana"
+
msgid "A set of companies under one owner that share group-scoped configuration — the chart of accounts, currencies, and dimensions — so the same accounting setup spans every company in the group."
msgstr "Zbiór firm pod jednym właścicielem, które współdzielą konfigurację na poziomie grupy — plan kont, waluty i wymiary — dzięki czemu ta sama konfiguracja księgowa obejmuje każdą firmę w grupie."
@@ -2639,6 +2642,9 @@ msgstr "Skopiuj link do części"
msgid "Copy link to procedure"
msgstr "Skopiuj link do procedury"
+msgid "Copy link to service"
+msgstr "Skopiuj link do usługi"
+
msgid "Copy link to tool"
msgstr "Skopiuj link do narzędzia"
@@ -2687,6 +2693,12 @@ msgstr "Skopiuj Ofertę"
msgid "Copy Quote number"
msgstr "Skopiuj numer oferty"
+msgid "Copy service number"
+msgstr "Skopiuj numer usługi"
+
+msgid "Copy service unique identifier"
+msgstr "Skopiuj unikalny identyfikator usługi"
+
msgid "Copy this item's pricing to another scope."
msgstr "Skopiuj ceny tego artykułu do innego zakresu."
@@ -2984,6 +2996,9 @@ msgstr "Utworzono wymaganą akcję"
msgid "Created scrap reason"
msgstr "Utworzono przyczynę złomu"
+msgid "Created service"
+msgstr "Utworzona usługa"
+
msgid "Created shipping method"
msgstr "Utworzono metodę wysyłki"
@@ -3694,6 +3709,9 @@ msgstr "Usuń Zamówienie Sprzedaży"
msgid "Delete Schedule"
msgstr "Usuń harmonogram"
+msgid "Delete Service"
+msgstr "Usuń usługę"
+
msgid "Delete Shift"
msgstr "Usuń zmianę"
@@ -4370,6 +4388,9 @@ msgstr "Edytuj zaplanowaną konserwację"
msgid "Edit Sequence"
msgstr "Edytuj sekwencję"
+msgid "Edit Service"
+msgstr "Edytuj usługę"
+
msgid "Edit Shift"
msgstr "Edytuj zmianę"
@@ -4991,6 +5012,10 @@ msgstr "Nie udało się utworzyć warunku płatności: {0}"
msgid "Failed to create process: {0}"
msgstr "Nie udało się utworzyć procesu: {0}"
+#. placeholder {0}: fetcher.data.error.message
+msgid "Failed to create service: {0}"
+msgstr "Nie udało się utworzyć usługi: {0}"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create shipping method: {0}"
msgstr "Nie udało się utworzyć metody wysyłki: {0}"
@@ -7632,6 +7657,9 @@ msgstr "Nowa linia zamówienia sprzedaży"
msgid "New Scheduled Maintenance"
msgstr "Nowa zaplanowana konserwacja"
+msgid "New Service"
+msgstr "Nowa usługa"
+
msgid "New Shift"
msgstr "Nowa zmiana"
@@ -10604,12 +10632,18 @@ msgstr "Opłaty za usługi"
msgid "Service Charges (default)"
msgstr "Opłaty za usługi (domyślnie)"
+msgid "Service Details"
+msgstr "Szczegóły usługi"
+
msgid "Service ID"
msgstr "Identyfikator Serwisu"
msgid "services"
msgstr "usługi"
+msgid "Services"
+msgstr "Usługi"
+
msgid "Set a target"
msgstr "Ustaw cel"
@@ -13008,6 +13042,9 @@ msgstr "Użyj ... aby uzyskać następny identyfikator materiału"
msgid "Use ... to get the next part ID"
msgstr "Użyj ... aby uzyskać następny identyfikator części"
+msgid "Use ... to get the next service ID"
+msgstr "Użyj ... aby uzyskać następny identyfikator usługi"
+
msgid "Use ... to get the next tool ID"
msgstr "Użyj ... aby uzyskać następny identyfikator narzędzia"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 066ac28790..30cdb54dae 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -334,6 +334,9 @@ msgstr "Um RFQ de venda (um cliente pede para você fazer uma cotação) ou um R
msgid "A separate schedule for tax reporting when tax rules require a method different from book depreciation."
msgstr "Um cronograma separado para fins de declaração de impostos quando as regras fiscais exigem um método diferente da depreciação contábil."
+msgid "A service is a billable activity that is bought or performed — it is never shipped, received, or stocked"
+msgstr "Um serviço é uma atividade faturável que é comprada ou realizada — nunca é enviada, recebida ou armazenada"
+
msgid "A set of companies under one owner that share group-scoped configuration — the chart of accounts, currencies, and dimensions — so the same accounting setup spans every company in the group."
msgstr "Um conjunto de empresas sob um mesmo proprietário que compartilham configuração com escopo de grupo — o plano de contas, as moedas e as dimensões — de modo que a mesma configuração contábil abrange todas as empresas do grupo."
@@ -2639,6 +2642,9 @@ msgstr "Copiar link da peça"
msgid "Copy link to procedure"
msgstr "Copiar link para procedimento"
+msgid "Copy link to service"
+msgstr "Copiar link para o serviço"
+
msgid "Copy link to tool"
msgstr "Copiar link da ferramenta"
@@ -2687,6 +2693,12 @@ msgstr "Copiar Cotação"
msgid "Copy Quote number"
msgstr "Copiar número da Cotação"
+msgid "Copy service number"
+msgstr "Copiar número do serviço"
+
+msgid "Copy service unique identifier"
+msgstr "Copiar identificador exclusivo do serviço"
+
msgid "Copy this item's pricing to another scope."
msgstr "Copie o preço deste item para outro escopo."
@@ -2984,6 +2996,9 @@ msgstr "Ação obrigatória criada"
msgid "Created scrap reason"
msgstr "Motivo de sucata criado"
+msgid "Created service"
+msgstr "Serviço criado"
+
msgid "Created shipping method"
msgstr "Método de envio criado"
@@ -3694,6 +3709,9 @@ msgstr "Eliminar Pedido de Venda"
msgid "Delete Schedule"
msgstr "Eliminar Cronograma"
+msgid "Delete Service"
+msgstr "Excluir Serviço"
+
msgid "Delete Shift"
msgstr "Eliminar Turno"
@@ -4370,6 +4388,9 @@ msgstr "Editar Manutenção Agendada"
msgid "Edit Sequence"
msgstr "Editar Sequência"
+msgid "Edit Service"
+msgstr "Editar Serviço"
+
msgid "Edit Shift"
msgstr "Editar Turno"
@@ -4991,6 +5012,10 @@ msgstr "Falha ao criar termo de pagamento: {0}"
msgid "Failed to create process: {0}"
msgstr "Falha ao criar processo: {0}"
+#. placeholder {0}: fetcher.data.error.message
+msgid "Failed to create service: {0}"
+msgstr "Falha ao criar serviço: {0}"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create shipping method: {0}"
msgstr "Falha ao criar método de envio: {0}"
@@ -7632,6 +7657,9 @@ msgstr "Nova Linha de Pedido de Venda"
msgid "New Scheduled Maintenance"
msgstr "Nova Manutenção Agendada"
+msgid "New Service"
+msgstr "Novo Serviço"
+
msgid "New Shift"
msgstr "Novo Turno"
@@ -10604,12 +10632,18 @@ msgstr "Taxas de serviço"
msgid "Service Charges (default)"
msgstr "Taxas de serviço (padrão)"
+msgid "Service Details"
+msgstr "Detalhes do Serviço"
+
msgid "Service ID"
msgstr "ID do Serviço"
msgid "services"
msgstr "serviços"
+msgid "Services"
+msgstr "Serviços"
+
msgid "Set a target"
msgstr "Defina uma meta"
@@ -13008,6 +13042,9 @@ msgstr "Use ... to get the next material ID"
msgid "Use ... to get the next part ID"
msgstr "Use ... to get the next part ID"
+msgid "Use ... to get the next service ID"
+msgstr "Use ... para obter o próximo ID do serviço"
+
msgid "Use ... to get the next tool ID"
msgstr "Use ... to get the next tool ID"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 0871ef9bbe..dec84f46e4 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -334,6 +334,9 @@ msgstr "Запрос коммерческого предложения прод
msgid "A separate schedule for tax reporting when tax rules require a method different from book depreciation."
msgstr "Отдельный график для налоговой отчетности, когда налоговые правила требуют метода, отличного от бухгалтерской амортизации."
+msgid "A service is a billable activity that is bought or performed — it is never shipped, received, or stocked"
+msgstr "Услуга — это платная деятельность, которая покупается или выполняется — она никогда не отправляется, не принимается и не хранится на складе"
+
msgid "A set of companies under one owner that share group-scoped configuration — the chart of accounts, currencies, and dimensions — so the same accounting setup spans every company in the group."
msgstr "Набор компаний под одним владельцем, которые совместно используют конфигурацию уровня группы — план счетов, валюты и аналитики — так что одна и та же настройка учёта распространяется на каждую компанию в группе."
@@ -2639,6 +2642,9 @@ msgstr "Скопировать ссылку на деталь"
msgid "Copy link to procedure"
msgstr "Скопировать ссылку на процедуру"
+msgid "Copy link to service"
+msgstr "Копировать ссылку на услугу"
+
msgid "Copy link to tool"
msgstr "Скопировать ссылку на инструмент"
@@ -2687,6 +2693,12 @@ msgstr "Копировать предложение"
msgid "Copy Quote number"
msgstr "Копировать номер предложения"
+msgid "Copy service number"
+msgstr "Копировать номер услуги"
+
+msgid "Copy service unique identifier"
+msgstr "Копировать уникальный идентификатор услуги"
+
msgid "Copy this item's pricing to another scope."
msgstr "Скопируйте цены этого товара в другую область."
@@ -2984,6 +2996,9 @@ msgstr "Требуемое действие создано"
msgid "Created scrap reason"
msgstr "Причина брака создана"
+msgid "Created service"
+msgstr "Услуга создана"
+
msgid "Created shipping method"
msgstr "Способ доставки создан"
@@ -3694,6 +3709,9 @@ msgstr "Удалить заказ продажи"
msgid "Delete Schedule"
msgstr "Удалить расписание"
+msgid "Delete Service"
+msgstr "Удалить услугу"
+
msgid "Delete Shift"
msgstr "Удалить смену"
@@ -4370,6 +4388,9 @@ msgstr "Редактировать плановое обслуживание"
msgid "Edit Sequence"
msgstr "Редактировать последовательность"
+msgid "Edit Service"
+msgstr "Редактировать услугу"
+
msgid "Edit Shift"
msgstr "Редактировать смену"
@@ -4991,6 +5012,10 @@ msgstr "Не удалось создать условие платежа: {0}"
msgid "Failed to create process: {0}"
msgstr "Ошибка при создании процесса: {0}"
+#. placeholder {0}: fetcher.data.error.message
+msgid "Failed to create service: {0}"
+msgstr "Ошибка при создании услуги: {0}"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create shipping method: {0}"
msgstr "Не удалось создать способ доставки: {0}"
@@ -7632,6 +7657,9 @@ msgstr "Новая строка заказа продажи"
msgid "New Scheduled Maintenance"
msgstr "Новое плановое обслуживание"
+msgid "New Service"
+msgstr "Новая услуга"
+
msgid "New Shift"
msgstr "Новая смена"
@@ -10604,12 +10632,18 @@ msgstr "Сборы за услуги"
msgid "Service Charges (default)"
msgstr "Сборы за услуги (по умолчанию)"
+msgid "Service Details"
+msgstr "Сведения об услуге"
+
msgid "Service ID"
msgstr "ID обслуживания"
msgid "services"
msgstr "услуги"
+msgid "Services"
+msgstr "Услуги"
+
msgid "Set a target"
msgstr "Установить цель"
@@ -13008,6 +13042,9 @@ msgstr "Используйте ... для получения следующег
msgid "Use ... to get the next part ID"
msgstr "Используйте ... для получения следующего ID детали"
+msgid "Use ... to get the next service ID"
+msgstr "Используйте ... для получения следующего ID услуги"
+
msgid "Use ... to get the next tool ID"
msgstr "Используйте ... для получения следующего ID инструмента"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index 5ff8f8947c..b83cfe0f93 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -334,6 +334,9 @@ msgstr "Bir satış RFQ (müşteri sizi alıntı yapmak için ister) veya satın
msgid "A separate schedule for tax reporting when tax rules require a method different from book depreciation."
msgstr "Vergi kuralları defter amortismanından farklı bir yöntem gerektirdiğinde vergi raporlaması için ayrı bir zaman çizelgesi."
+msgid "A service is a billable activity that is bought or performed — it is never shipped, received, or stocked"
+msgstr "Bir hizmet, satın alınan veya gerçekleştirilen faturalaştırılabilir bir etkinliktir — hiçbir zaman gönderilmez, alınmaz veya depolanmaz"
+
msgid "A set of companies under one owner that share group-scoped configuration — the chart of accounts, currencies, and dimensions — so the same accounting setup spans every company in the group."
msgstr "Tek bir sahip altında, grup kapsamlı yapılandırmayı — hesap planı, para birimleri ve boyutlar — paylaşan, böylece aynı muhasebe kurulumunun gruptaki her şirketi kapsadığı şirketler kümesi."
@@ -2639,6 +2642,9 @@ msgstr "Parça bağlantısını kopyala"
msgid "Copy link to procedure"
msgstr "Prosedüre bağlantısını kopyala"
+msgid "Copy link to service"
+msgstr "Hizmet bağlantısını kopyala"
+
msgid "Copy link to tool"
msgstr "Aleteye bağlantısını kopyala"
@@ -2687,6 +2693,12 @@ msgstr "Teklifi Kopyala"
msgid "Copy Quote number"
msgstr "Teklif numarasını kopyala"
+msgid "Copy service number"
+msgstr "Hizmet numarasını kopyala"
+
+msgid "Copy service unique identifier"
+msgstr "Hizmet benzersiz tanımlayıcısını kopyala"
+
msgid "Copy this item's pricing to another scope."
msgstr "Bu öğenin fiyatlandırmasını başka bir kapsamdaki konumlandırın."
@@ -2984,6 +2996,9 @@ msgstr "Gerekli eylem oluşturuldu"
msgid "Created scrap reason"
msgstr "Üretim sebebi oluşturuldu"
+msgid "Created service"
+msgstr "Hizmet oluşturuldu"
+
msgid "Created shipping method"
msgstr "Gönderi yöntemi oluşturuldu"
@@ -3694,6 +3709,9 @@ msgstr "Satış Siparişini Sil"
msgid "Delete Schedule"
msgstr "Programı Sil"
+msgid "Delete Service"
+msgstr "Hizmeti Sil"
+
msgid "Delete Shift"
msgstr "Vardaki Vardiyayı Sil"
@@ -4370,6 +4388,9 @@ msgstr "Planlanmış Bakımı Düzenle"
msgid "Edit Sequence"
msgstr "Sıralamayı Düzenle"
+msgid "Edit Service"
+msgstr "Hizmeti Düzenle"
+
msgid "Edit Shift"
msgstr "Vardiya Düzenle"
@@ -4991,6 +5012,10 @@ msgstr "Ödeme vadesi oluşturulamadı: {0}"
msgid "Failed to create process: {0}"
msgstr "İşlemi oluşturulamadı: {0}"
+#. placeholder {0}: fetcher.data.error.message
+msgid "Failed to create service: {0}"
+msgstr "Hizmet oluşturma başarısız: {0}"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create shipping method: {0}"
msgstr "Gönderi yöntemi oluşturulamadı: {0}"
@@ -7632,6 +7657,9 @@ msgstr "Yeni Satış Siparişi Kalemi"
msgid "New Scheduled Maintenance"
msgstr "Yeni Planlanmış Bakım"
+msgid "New Service"
+msgstr "Yeni Hizmet"
+
msgid "New Shift"
msgstr "Yeni Vardiya"
@@ -10604,12 +10632,18 @@ msgstr "Hizmet ücretleri"
msgid "Service Charges (default)"
msgstr "Hizmet ücretleri (varsayılan)"
+msgid "Service Details"
+msgstr "Hizmet Detayları"
+
msgid "Service ID"
msgstr "Hizmet Kimliği"
msgid "services"
msgstr "hizmetler"
+msgid "Services"
+msgstr "Hizmetler"
+
msgid "Set a target"
msgstr "Hedef belirle"
@@ -13008,6 +13042,9 @@ msgstr "Bir sonraki malzeme kimliğini almak için ... kullanın"
msgid "Use ... to get the next part ID"
msgstr "Bir sonraki parça kimliğini almak için ..."
+msgid "Use ... to get the next service ID"
+msgstr "Sonraki hizmet kimliğini almak için ... kullan"
+
msgid "Use ... to get the next tool ID"
msgstr "Sonraki araç kimliğini almak için ..."
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 8d86f5588d..27952dbff4 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -334,6 +334,9 @@ msgstr "销售RFQ(客户要求您报价)或采购RFQ(您要求供应商)
msgid "A separate schedule for tax reporting when tax rules require a method different from book depreciation."
msgstr "当税收规则要求与账面折旧不同的方法时,用于税务报告的单独时间表。"
+msgid "A service is a billable activity that is bought or performed — it is never shipped, received, or stocked"
+msgstr "服务是一种可计费活动,可以购买或执行——它从不被运送、接收或存储"
+
msgid "A set of companies under one owner that share group-scoped configuration — the chart of accounts, currencies, and dimensions — so the same accounting setup spans every company in the group."
msgstr "同一所有者下的一组公司,共享组范围的配置——会计科目表、币种和维度——因此同一套会计设置适用于组内的每家公司。"
@@ -2639,6 +2642,9 @@ msgstr "复制零件链接"
msgid "Copy link to procedure"
msgstr "复制程序链接"
+msgid "Copy link to service"
+msgstr "复制服务链接"
+
msgid "Copy link to tool"
msgstr "复制工具链接"
@@ -2687,6 +2693,12 @@ msgstr "复制报价"
msgid "Copy Quote number"
msgstr "复制报价单号"
+msgid "Copy service number"
+msgstr "复制服务编号"
+
+msgid "Copy service unique identifier"
+msgstr "复制服务唯一标识符"
+
msgid "Copy this item's pricing to another scope."
msgstr "将此项目的定价复制到另一个范围。"
@@ -2984,6 +2996,9 @@ msgstr "已创建必需操作"
msgid "Created scrap reason"
msgstr "已创建报废原因"
+msgid "Created service"
+msgstr "创建服务"
+
msgid "Created shipping method"
msgstr "已创建配送方式"
@@ -3694,6 +3709,9 @@ msgstr "删除销售订单"
msgid "Delete Schedule"
msgstr "删除计划"
+msgid "Delete Service"
+msgstr "删除服务"
+
msgid "Delete Shift"
msgstr "删除班次"
@@ -4370,6 +4388,9 @@ msgstr "编辑计划维护"
msgid "Edit Sequence"
msgstr "编辑序列"
+msgid "Edit Service"
+msgstr "编辑服务"
+
msgid "Edit Shift"
msgstr "编辑班次"
@@ -4991,6 +5012,10 @@ msgstr "创建付款条款失败:{0}"
msgid "Failed to create process: {0}"
msgstr "创建流程失败:{0}"
+#. placeholder {0}: fetcher.data.error.message
+msgid "Failed to create service: {0}"
+msgstr "创建服务失败:{0}"
+
#. placeholder {0}: fetcher.data.error.message
msgid "Failed to create shipping method: {0}"
msgstr "创建配送方式失败:{0}"
@@ -7632,6 +7657,9 @@ msgstr "新销售订单行"
msgid "New Scheduled Maintenance"
msgstr "新的定期维护"
+msgid "New Service"
+msgstr "新服务"
+
msgid "New Shift"
msgstr "新班次"
@@ -10604,12 +10632,18 @@ msgstr "服务费"
msgid "Service Charges (default)"
msgstr "服务费 (默认)"
+msgid "Service Details"
+msgstr "服务详情"
+
msgid "Service ID"
msgstr "服务ID"
msgid "services"
msgstr "服务"
+msgid "Services"
+msgstr "服务"
+
msgid "Set a target"
msgstr "设置目标"
@@ -13008,6 +13042,9 @@ msgstr "使用 ... 获取下一个物料 ID"
msgid "Use ... to get the next part ID"
msgstr "使用 ... 获取下一个零件 ID"
+msgid "Use ... to get the next service ID"
+msgstr "使用...获取下一个服务ID"
+
msgid "Use ... to get the next tool ID"
msgstr "使用 ... 获取下一个工具 ID"
diff --git a/packages/utils/src/status.ts b/packages/utils/src/status.ts
index 5a1a64a024..c40d8da69b 100644
--- a/packages/utils/src/status.ts
+++ b/packages/utils/src/status.ts
@@ -34,7 +34,11 @@ export const getSalesOrderStatus = (
);
const allShipped = lines.every(
- (line) => line.salesOrderLineType === "Comment" || line.sentComplete
+ (line) =>
+ line.salesOrderLineType === "Comment" ||
+ // Services are never shipped — they can't block shipping completeness
+ line.salesOrderLineType === "Service" ||
+ line.sentComplete
);
let status: Database["public"]["Tables"]["salesOrder"]["Row"]["status"] =
@@ -71,6 +75,8 @@ export const getPurchaseOrderStatus = (
(line) =>
line.purchaseOrderLineType === "Comment" ||
line.purchaseOrderLineType === "G/L Account" ||
+ // Services are never received — they can't block receipt completeness
+ line.purchaseOrderLineType === "Service" ||
line.receivedComplete
);