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): show supersession lifecycle badge in the method column

Brad Barbin40c76b17d5cf
diff --git a/.claude/skills/test/playbooks/material-supersession.md b/.claude/skills/test/playbooks/material-supersession.md
new file mode 100644
index 0000000000..36a1311b35
--- /dev/null
+++ b/.claude/skills/test/playbooks/material-supersession.md
@@ -0,0 +1,67 @@
+# Material Supersession
+
+Last tested: 2026-06-24
+Routes: `/x/part/$itemId/planning` (config), `/x/purchasing/planning`, `/x/production/planning` (Recalculate)
+
+## What the feature does
+Redirects demand from a discontinued item to its successor during MRP, and swaps
+superseded components at job creation. Config lives on the Part → Planning tab
+(`ItemSupersessionForm`). Modes: `Consume First`, `Prefer New`, `Stock Only`, `No Stock`.
+Fields: supersessionMode, discontinuationDate, successorItemId, successorEffectivityDate,
+conversionFactor; `minimumReserveQuantity` lives on `itemPlanning` (per location).
+
+## ENVIRONMENT GOTCHAS (critical)
+- The **claude.ai Carbon MCP** server points at a hosted instance (company "Acme Inc.",
+ id SMBHQP55…) — NOT this branch's local DB. Do NOT use MCP `items_upsertPart` for
+ local browser testing; the parts land in the wrong database/company.
+- The **browser dev-bypass** (`[email protected]`) is an employee of local company
+ "Carbon Development" (id d8u703oeq0gg2jnc1k2g) only. Local DB: `localhost:<port>`
+ from `.env.local` SUPABASE_DB_URL.
+- The shared `agent-browser` is used by ALL worktree agents at once; another worktree
+ will hijack the active tab. Pin every command with `agent-browser tab <n>`.
+- Combobox/option refs re-render on async chart loads — snapshot+click must be in the
+ SAME bash command, or refs go stale ("Unknown ref").
+
+## Fast fixture setup (local DB, bypasses contended browser)
+Parts: insert `item` (type Part) + `part` rows directly — the `trg_event_after_sync_item`
+AFTER INSERT trigger auto-creates itemCost/itemReplenishment/itemPlanning/makeMethod.
+- itemSupersession: one row per old item (mode, successorItemId, discontinuationDate ≤ today,
+ successorEffectivityDate ≤ today, conversionFactor).
+- BOM: `methodMaterial` rows on the parent's makeMethod id (itemType 'Part', methodType
+ 'Purchase to Order'/'Pull from Inventory', effectiveFrom/effectiveTo for line effectivity).
+- On-hand: `itemLedger` (entryType 'Positive Adjmt.', itemId, locationId, quantity, companyId, createdBy).
+- Stock Only reserve: UPDATE itemPlanning SET reorderingPolicy='Fixed Reorder Quantity',
+ reorderPoint=1, minimumReserveQuantity=N.
+- Demand: `demandProjection` (itemId, locationId, periodId, forecastQuantity) on the current
+ week period. NOTE: independent (top-level) demand on a leaf Buy item does NOT surface in
+ planning output — only **BOM-derived** (dependent) demand does. To test redirection put the
+ old item in a parent's BOM.
+
+## Run MRP (= the Recalculate button)
+`POST https://api.<branch>.dev/functions/v1/mrp` with header
+`Authorization: Bearer <SUPABASE_SERVICE_ROLE_KEY>`, body
+`{"type":"company","id":"<companyId>","companyId":"<companyId>","userId":"<userId>"}`.
+First call also creates the weekly `period` rows. Returns `{"success":true}`.
+
+## Inspect / assert
+- `demandForecastSource` (cols: itemId=successor, redirectedFromItemId=old, parentItemId,
+ quantity in successor units) — the redirection lineage.
+- `get_purchasing_planning(company_id, location_id, periods[])` and
+ `get_production_planning(...)` — quantityToOrder, supersessionMode, minimumReserveQuantity.
+ periods[] = `select id from period where "periodType"='Week' order by "startDate" limit 18`.
+- Job substitution: insert a `public.job` row, invoke `get-method` body
+ `{"type":"itemToJob","sourceId":"<itemId>","targetId":"<jobId>","companyId":..,"userId":..}`,
+ then read `jobMaterial.substitutedFromItemId` / `substitutionFactor`.
+
+## Browser verification (after data is set up)
+- Purchasing/Production Planning tables show successors with "Order N"/"Make N"; old parts absent.
+- Recalculate button (top of planning page) disables while running, re-renders same results.
+- Part → Planning → Supersession shows mode + successor (with PHASE-OUT/OBSOLETE/SPARES-ONLY badge).
+- Chain: a part whose successor is itself superseded shows "Supersession chain detected: A → B → C".
+- Self-supersession: the successor picker excludes the part itself.
+
+## Expected results for the canonical fixture (FG BOM consumes OLD1×1, OLD2×2, CHAIN-A×1, M-OLD×1; FG demand 100)
+- NEW1 = 100 (Prefer New, factor 1) | NEW2 = 400 (Consume First, factor 2: 200×2)
+- CHAIN-C = 100 (chain A→B→C collapse) | M-NEW = 100 in production planning (Make→Make)
+- SPARE = 80 (reserve 100 − on-hand 20) | OLD1/OLD2/CHAIN-A/B/OBS/M-OLD excluded
+- BOM-line effectivity: a future effectiveFrom or past effectiveTo line is skipped (no demand).
diff --git a/apps/erp/app/components/Form/Item.tsx b/apps/erp/app/components/Form/Item.tsx
index 83e498e978..93e1d5cf4d 100644
--- a/apps/erp/app/components/Form/Item.tsx
+++ b/apps/erp/app/components/Form/Item.tsx
@@ -202,6 +202,22 @@ const Item = ({
? items.find((i) => i.id === selectedItem.successorItemId)
: null;
+ // Prefer an explicit label (e.g. "Successor Part") for the field label; fall
+ // back to the item-type name. Standard type-name labels are translated so the
+ // wording matches the type.
+ const fieldLabel =
+ label === "Item"
+ ? t`Item`
+ : label === "Part"
+ ? t`Part`
+ : label === "Material"
+ ? t`Material`
+ : label === "Tool"
+ ? t`Tool`
+ : label === "Consumable"
+ ? t`Consumable`
+ : (label ?? translateItemType(type));
+
return (
<>
<FormControl isInvalid={!!error} className="w-full">
@@ -212,7 +228,7 @@ const Item = ({
isOptional={resolvedIsOptional}
onConfigure={onConfigure}
>
- {translateItemType(type)}
+ {fieldLabel}
</FormLabel>
)}
<input
diff --git a/apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsx b/apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsx
index 5b51b643f4..14f84a2020 100644
--- a/apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsx
+++ b/apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsx
@@ -40,6 +40,7 @@ import { Link, useFetcher, useNavigate } from "react-router";
import {
EmployeeAvatar,
Hyperlink,
+ ItemLifecycleBadge,
ItemThumbnail,
MethodIcon,
New,
@@ -160,10 +161,26 @@ const ConsumablesTable = memo(
accessorKey: "defaultMethodType",
header: t`Default Method`,
cell: (item) => (
- <Badge variant="secondary">
- <MethodIcon type={item.getValue<string>()} className="mr-2" />
- <span>{translateMethodType(item.getValue<string>())}</span>
- </Badge>
+ <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: {
diff --git a/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx b/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx
index d09921f91d..bd537d796d 100644
--- a/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx
+++ b/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx
@@ -51,6 +51,7 @@ import { Link, useFetcher, useNavigate } from "react-router";
import {
EmployeeAvatar,
Hyperlink,
+ ItemLifecycleBadge,
ItemThumbnail,
MethodIcon,
New,
@@ -325,10 +326,26 @@ const MaterialsTable = memo(({ data, tags, count }: MaterialsTableProps) => {
accessorKey: "defaultMethodType",
header: t`Default Method`,
cell: (item) => (
- <Badge variant="secondary">
- <MethodIcon type={item.getValue<string>()} className="mr-2" />
- <span>{translateMethodType(item.getValue<string>())}</span>
- </Badge>
+ <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: {
diff --git a/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx b/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx
index 6218536602..1803ceb28b 100644
--- a/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx
+++ b/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx
@@ -132,20 +132,6 @@ const PartsTable = memo(({ data, tags, count }: PartsTableProps) => {
</div>
</VStack>
</Hyperlink>
- <ItemLifecycleBadge
- mode={
- (
- row.original as {
- supersessionMode?:
- | "Consume First"
- | "Prefer New"
- | "Stock Only"
- | "No Stock"
- | null;
- }
- ).supersessionMode
- }
- />
</HStack>
),
meta: {
@@ -219,10 +205,26 @@ const PartsTable = memo(({ data, tags, count }: PartsTableProps) => {
accessorKey: "defaultMethodType",
header: t`Default Method`,
cell: (item) => (
- <Badge variant="secondary">
- <MethodIcon type={item.getValue<string>()} className="mr-2" />
- <span>{translateMethodType(item.getValue<string>())}</span>
- </Badge>
+ <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: {
diff --git a/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx b/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx
index 58835d161b..55424db96e 100644
--- a/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx
+++ b/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx
@@ -45,6 +45,7 @@ import { Link, useFetcher, useNavigate } from "react-router";
import {
EmployeeAvatar,
Hyperlink,
+ ItemLifecycleBadge,
ItemThumbnail,
MethodIcon,
New,
@@ -204,10 +205,26 @@ const ToolsTable = memo(({ data, tags, count }: ToolsTableProps) => {
accessorKey: "defaultMethodType",
header: t`Default Method`,
cell: (item) => (
- <Badge variant="secondary">
- <MethodIcon type={item.getValue<string>()} className="mr-2" />
- <span>{translateMethodType(item.getValue<string>())}</span>
- </Badge>
+ <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: {
diff --git a/packages/database/supabase/migrations/20260624151847_supersession-mode-item-views.sql b/packages/database/supabase/migrations/20260624151847_supersession-mode-item-views.sql
new file mode 100644
index 0000000000..0b578c2c26
--- /dev/null
+++ b/packages/database/supabase/migrations/20260624151847_supersession-mode-item-views.sql
@@ -0,0 +1,327 @@
+-- Add supersession lifecycle (supersessionMode) to the materials, tools, and
+-- consumables list views so the phase-out/obsolete badge can render in their
+-- tables (the parts view already exposes it). Forked verbatim from the live
+-- view definitions with a LEFT JOIN to itemSupersession + the column appended.
+
+CREATE OR REPLACE VIEW "materials" WITH (security_invoker = true) AS
+ WITH latest_items AS (
+ SELECT DISTINCT ON (i_1."readableId", i_1."companyId") i_1.id,
+ i_1."readableId",
+ i_1.name,
+ i_1.description,
+ i_1.type,
+ i_1."replenishmentSystem",
+ i_1."defaultMethodType",
+ i_1."itemTrackingType",
+ i_1."unitOfMeasureCode",
+ i_1.active,
+ i_1."companyId",
+ i_1."createdBy",
+ i_1."createdAt",
+ i_1."updatedBy",
+ i_1."updatedAt",
+ i_1.assignee,
+ i_1."modelUploadId",
+ i_1."thumbnailPath",
+ i_1.notes,
+ i_1."trackingMethod",
+ i_1.embedding,
+ i_1.revision,
+ i_1."readableIdWithRevision",
+ i_1."requiresInspection",
+ mu_1."modelPath",
+ mu_1."thumbnailPath" AS "modelThumbnailPath",
+ mu_1.name AS "modelName",
+ mu_1.size AS "modelSize"
+ FROM item i_1
+ LEFT JOIN "modelUpload" mu_1 ON mu_1.id = i_1."modelUploadId"
+ WHERE i_1.type = 'Material'::"itemType"
+ ORDER BY i_1."readableId", i_1."companyId", (
+ CASE
+ WHEN i_1.revision = '0'::text OR i_1.revision = ''::text OR i_1.revision IS NULL THEN 0
+ ELSE 1
+ END) DESC, i_1."createdAt" DESC NULLS LAST
+ ), item_revisions AS (
+ SELECT i_1."readableId",
+ i_1."companyId",
+ json_agg(json_build_object('id', i_1.id, 'revision', i_1.revision, 'methodType', i_1."defaultMethodType", 'type', i_1.type) ORDER BY (
+ CASE
+ WHEN i_1.revision = '0'::text OR i_1.revision = ''::text OR i_1.revision IS NULL THEN 0
+ ELSE 1
+ END), i_1."createdAt") AS revisions
+ FROM item i_1
+ WHERE i_1.type = 'Material'::"itemType"
+ GROUP BY i_1."readableId", i_1."companyId"
+ )
+ SELECT i.active,
+ i.assignee,
+ i."defaultMethodType",
+ i.description,
+ i."itemTrackingType",
+ i.name,
+ i."replenishmentSystem",
+ i."unitOfMeasureCode",
+ i.notes,
+ i.revision,
+ i."readableId",
+ i."readableIdWithRevision",
+ i.id,
+ i."companyId",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND i."modelThumbnailPath" IS NOT NULL THEN i."modelThumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ i."modelUploadId",
+ i."modelPath",
+ i."modelName",
+ i."modelSize",
+ ps."supplierIds",
+ uom.name AS "unitOfMeasure",
+ ir.revisions,
+ mf.name AS "materialForm",
+ ms.name AS "materialSubstance",
+ md.name AS dimensions,
+ mfin.name AS finish,
+ mg.name AS grade,
+ mt.name AS "materialType",
+ m."materialSubstanceId",
+ m."materialFormId",
+ m."customFields",
+ m.tags,
+ ic."itemPostingGroupId",
+ ( SELECT COALESCE(jsonb_object_agg(eim.integration,
+ CASE
+ WHEN eim.metadata IS NOT NULL THEN eim.metadata
+ ELSE to_jsonb(eim."externalId")
+ END) FILTER (WHERE eim."externalId" IS NOT NULL OR eim.metadata IS NOT NULL), '{}'::jsonb) AS "coalesce"
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item'::text AND eim."entityId" = i.id) AS "externalId",
+ i."createdBy",
+ i."createdAt",
+ i."updatedBy",
+ i."updatedAt",
+ ss."supersessionMode"
+ FROM material m
+ JOIN latest_items i ON i."readableId" = m.id AND i."companyId" = m."companyId"
+ LEFT JOIN item_revisions ir ON ir."readableId" = m.id AND ir."companyId" = i."companyId"
+ LEFT JOIN ( SELECT ps_1."itemId",
+ ps_1."companyId",
+ string_agg(ps_1."supplierPartId", ','::text) AS "supplierIds"
+ FROM "supplierPart" ps_1
+ GROUP BY ps_1."itemId", ps_1."companyId") ps ON ps."itemId" = i.id AND ps."companyId" = i."companyId"
+ 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 "materialForm" mf ON mf.id = m."materialFormId"
+ LEFT JOIN "materialSubstance" ms ON ms.id = m."materialSubstanceId"
+ LEFT JOIN "materialDimension" md ON m."dimensionId" = md.id
+ LEFT JOIN "materialFinish" mfin ON m."finishId" = mfin.id
+ LEFT JOIN "materialGrade" mg ON m."gradeId" = mg.id
+ LEFT JOIN "materialType" mt ON m."materialTypeId" = mt.id
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id
+ LEFT JOIN "itemSupersession" ss ON ss."itemId" = i.id AND ss."companyId" = i."companyId";
+
+CREATE OR REPLACE VIEW "tools" WITH (security_invoker = true) AS
+ WITH latest_items AS (
+ SELECT DISTINCT ON (i."readableId", i."companyId") i.id,
+ i."readableId",
+ i.name,
+ i.description,
+ i.type,
+ i."replenishmentSystem",
+ i."defaultMethodType",
+ i."itemTrackingType",
+ i."unitOfMeasureCode",
+ i.active,
+ i."companyId",
+ i."createdBy",
+ i."createdAt",
+ i."updatedBy",
+ i."updatedAt",
+ i.assignee,
+ i."modelUploadId",
+ i."thumbnailPath",
+ i.notes,
+ i."trackingMethod",
+ i.embedding,
+ i.revision,
+ i."readableIdWithRevision",
+ i."requiresInspection",
+ i."sourcingType",
+ mu.id AS "modelUploadId",
+ mu."modelPath",
+ mu."thumbnailPath" AS "modelThumbnailPath",
+ mu.name AS "modelName",
+ mu.size AS "modelSize"
+ FROM item i
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ WHERE i.type = 'Tool'::"itemType"
+ ORDER BY i."readableId", i."companyId", (
+ CASE
+ WHEN i.revision = '0'::text OR i.revision = ''::text OR i.revision IS NULL THEN 0
+ ELSE 1
+ END) DESC, i."createdAt" DESC NULLS LAST
+ ), item_revisions AS (
+ SELECT i."readableId",
+ i."companyId",
+ json_agg(json_build_object('id', i.id, 'revision', i.revision, 'methodType', i."defaultMethodType", 'type', i.type) ORDER BY (
+ CASE
+ WHEN i.revision = '0'::text OR i.revision = ''::text OR i.revision IS NULL THEN 0
+ ELSE 1
+ END), i."createdAt") AS revisions
+ FROM item i
+ WHERE i.type = 'Tool'::"itemType"
+ GROUP BY i."readableId", i."companyId"
+ )
+ SELECT li.active,
+ li.assignee,
+ li."defaultMethodType",
+ li."sourcingType",
+ li.description,
+ li."itemTrackingType",
+ li.name,
+ li."replenishmentSystem",
+ li."unitOfMeasureCode",
+ li.notes,
+ li.revision,
+ li."readableId",
+ li."readableIdWithRevision",
+ li.id,
+ li."companyId",
+ CASE
+ WHEN li."thumbnailPath" IS NULL AND li."modelThumbnailPath" IS NOT NULL THEN li."modelThumbnailPath"
+ ELSE li."thumbnailPath"
+ END AS "thumbnailPath",
+ li."modelPath",
+ li."modelName",
+ li."modelSize",
+ ps."supplierIds",
+ uom.name AS "unitOfMeasure",
+ ir.revisions,
+ t."customFields",
+ t.tags,
+ ic."itemPostingGroupId",
+ ( SELECT COALESCE(jsonb_object_agg(eim.integration,
+ CASE
+ WHEN eim.metadata IS NOT NULL THEN eim.metadata
+ ELSE to_jsonb(eim."externalId")
+ END) FILTER (WHERE eim."externalId" IS NOT NULL OR eim.metadata IS NOT NULL), '{}'::jsonb) AS "coalesce"
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item'::text AND eim."entityId" = li.id) AS "externalId",
+ li."createdBy",
+ li."createdAt",
+ li."updatedBy",
+ li."updatedAt",
+ ss."supersessionMode"
+ FROM tool t
+ JOIN latest_items li(id, "readableId", name, description, type, "replenishmentSystem", "defaultMethodType", "itemTrackingType", "unitOfMeasureCode", active, "companyId", "createdBy", "createdAt", "updatedBy", "updatedAt", assignee, "modelUploadId", "thumbnailPath", notes, "trackingMethod", embedding, revision, "readableIdWithRevision", "requiresInspection", "sourcingType", "modelUploadId_1", "modelPath", "modelThumbnailPath", "modelName", "modelSize") ON li."readableId" = t.id AND li."companyId" = t."companyId"
+ LEFT JOIN item_revisions ir ON ir."readableId" = t.id AND ir."companyId" = li."companyId"
+ LEFT JOIN ( SELECT ps_1."itemId",
+ ps_1."companyId",
+ string_agg(ps_1."supplierPartId", ','::text) AS "supplierIds"
+ FROM "supplierPart" ps_1
+ GROUP BY ps_1."itemId", ps_1."companyId") ps ON ps."itemId" = li.id AND ps."companyId" = li."companyId"
+ LEFT JOIN "unitOfMeasure" uom ON uom.code = li."unitOfMeasureCode" AND uom."companyId" = li."companyId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = li.id
+ LEFT JOIN "itemSupersession" ss ON ss."itemId" = li.id AND ss."companyId" = li."companyId";
+
+CREATE OR REPLACE VIEW "consumables" WITH (security_invoker = true) AS
+ WITH latest_items AS (
+ SELECT DISTINCT ON (i."readableId", i."companyId") i.id,
+ i."readableId",
+ i.name,
+ i.description,
+ i.type,
+ i."replenishmentSystem",
+ i."defaultMethodType",
+ i."itemTrackingType",
+ i."unitOfMeasureCode",
+ i.active,
+ i."companyId",
+ i."createdBy",
+ i."createdAt",
+ i."updatedBy",
+ i."updatedAt",
+ i.assignee,
+ i."modelUploadId",
+ i."thumbnailPath",
+ i.notes,
+ i."trackingMethod",
+ i.embedding,
+ i.revision,
+ i."readableIdWithRevision",
+ i."requiresInspection",
+ mu."modelPath",
+ mu."thumbnailPath" AS "modelThumbnailPath",
+ mu.name AS "modelName",
+ mu.size AS "modelSize"
+ FROM item i
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ WHERE i.type = 'Consumable'::"itemType"
+ ORDER BY i."readableId", i."companyId", (
+ CASE
+ WHEN i.revision = '0'::text OR i.revision = ''::text OR i.revision IS NULL THEN 0
+ ELSE 1
+ END) DESC, i."createdAt" DESC NULLS LAST
+ ), item_revisions AS (
+ SELECT i."readableId",
+ i."companyId",
+ json_agg(json_build_object('id', i.id, 'revision', i.revision, 'methodType', i."defaultMethodType", 'type', i.type) ORDER BY (
+ CASE
+ WHEN i.revision = '0'::text OR i.revision = ''::text OR i.revision IS NULL THEN 0
+ ELSE 1
+ END), i."createdAt") AS revisions
+ FROM item i
+ WHERE i.type = 'Consumable'::"itemType"
+ GROUP BY i."readableId", i."companyId"
+ )
+ SELECT li.active,
+ li.assignee,
+ li."defaultMethodType",
+ li.description,
+ li."itemTrackingType",
+ li.name,
+ li."replenishmentSystem",
+ li."unitOfMeasureCode",
+ li.notes,
+ li.revision,
+ li."readableId",
+ li."readableIdWithRevision",
+ li.id,
+ li."companyId",
+ CASE
+ WHEN li."thumbnailPath" IS NULL AND li."modelThumbnailPath" IS NOT NULL THEN li."modelThumbnailPath"
+ ELSE li."thumbnailPath"
+ END AS "thumbnailPath",
+ li."modelUploadId",
+ li."modelPath",
+ li."modelName",
+ li."modelSize",
+ ps."supplierIds",
+ uom.name AS "unitOfMeasure",
+ ir.revisions,
+ c."customFields",
+ c.tags,
+ ic."itemPostingGroupId",
+ ( SELECT COALESCE(jsonb_object_agg(eim.integration,
+ CASE
+ WHEN eim.metadata IS NOT NULL THEN eim.metadata
+ ELSE to_jsonb(eim."externalId")
+ END) FILTER (WHERE eim."externalId" IS NOT NULL OR eim.metadata IS NOT NULL), '{}'::jsonb) AS "coalesce"
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item'::text AND eim."entityId" = li.id) AS "externalId",
+ li."createdBy",
+ li."createdAt",
+ li."updatedBy",
+ li."updatedAt",
+ ss."supersessionMode"
+ FROM consumable c
+ JOIN latest_items li ON li."readableId" = c.id AND li."companyId" = c."companyId"
+ LEFT JOIN item_revisions ir ON ir."readableId" = c.id AND ir."companyId" = li."companyId"
+ LEFT JOIN ( SELECT ps_1."itemId",
+ ps_1."companyId",
+ string_agg(ps_1."supplierPartId", ','::text) AS "supplierIds"
+ FROM "supplierPart" ps_1
+ GROUP BY ps_1."itemId", ps_1."companyId") ps ON ps."itemId" = li.id AND ps."companyId" = li."companyId"
+ LEFT JOIN "unitOfMeasure" uom ON uom.code = li."unitOfMeasureCode" AND uom."companyId" = li."companyId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = li.id
+ LEFT JOIN "itemSupersession" ss ON ss."itemId" = li.id AND ss."companyId" = li."companyId";