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.

Promote sourcingType to item-level property (#903)

Brad Barbin6b5ac6e93a78
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index 465e8fd86c..b5a7c0c1b6 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -1,6 +1,11 @@
import type { Database, Json } from "@carbon/database";
import { fetchAllFromTable } from "@carbon/database";
-import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import type {
+ ExpressionBuilder,
+ Kysely,
+ KyselyDatabase,
+ KyselyTx
+} from "@carbon/database/client";
import { getLocalTimeZone, now, today } from "@internationalized/date";
import type { SupabaseClient } from "@supabase/supabase-js";
import { nanoid } from "nanoid";
@@ -15,7 +20,9 @@ import type {
} from "../shared";
import {
lookupBuyPriceFromMap,
+ type MethodType,
type PriceBreak,
+ type SourcingType,
type SupplierPriceMap
} from "../shared";
import {
@@ -1317,7 +1324,9 @@ export async function getMethodMaterialsByMakeMethod(
) {
return client
.from("methodMaterial")
- .select("*, item(name, itemTrackingType, replenishmentSystem)")
+ .select(
+ "*, item(name, itemTrackingType, replenishmentSystem, defaultMethodType, sourcingType)"
+ )
.eq("makeMethodId", makeMethodId)
.order("order", { ascending: true });
}
@@ -2724,6 +2733,131 @@ export async function cascadeItemTrackingType(
});
}
+/**
+ * Updates item-level method/sourcing columns and mirrors the change down to
+ * every methodMaterial that references the item — in a single transaction, so
+ * the item and its mirrors can never be left half-applied.
+ *
+ * sourcingType and defaultMethodType are item-level properties; method
+ * materials are read-only mirrors. Only mirrors on Draft make methods are
+ * touched — Active and Archived methods are frozen.
+ */
+export async function updateItemMethodAndSourcing(
+ db: Kysely<KyselyDatabase>,
+ args: {
+ itemIds: string[];
+ companyId: string;
+ userId: string;
+ itemUpdate: {
+ replenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"];
+ defaultMethodType?: MethodType;
+ sourcingType?: SourcingType;
+ };
+ cascade: {
+ sourcingType?: SourcingType;
+ methodType?: MethodType;
+ };
+ }
+) {
+ if (args.itemIds.length === 0) return;
+
+ const updatedAt = now(getLocalTimeZone()).toAbsoluteString();
+
+ return db.transaction().execute(async (trx) => {
+ await trx
+ .updateTable("item")
+ .set({ ...args.itemUpdate, updatedBy: args.userId, updatedAt })
+ .where("id", "in", args.itemIds)
+ .where("companyId", "=", args.companyId)
+ .execute();
+
+ await cascadeSourcingAndMethodTypeToMethodMaterials(trx, {
+ itemIds: args.itemIds,
+ companyId: args.companyId,
+ userId: args.userId,
+ newSourcingType: args.cascade.sourcingType,
+ newMethodType: args.cascade.methodType
+ });
+ });
+}
+
+/**
+ * Mirrors an item's sourcingType/methodType onto every methodMaterial that
+ * references it. Operates on a caller-supplied transaction so it composes with
+ * the item update above. Only method materials on Draft make methods are
+ * touched.
+ */
+async function cascadeSourcingAndMethodTypeToMethodMaterials(
+ trx: KyselyTx,
+ args: {
+ itemIds: string[];
+ companyId: string;
+ userId: string;
+ newSourcingType?: SourcingType;
+ newMethodType?: MethodType;
+ }
+) {
+ if (args.itemIds.length === 0) return;
+ if (!args.newSourcingType && !args.newMethodType) return;
+
+ const updatedAt = now(getLocalTimeZone()).toAbsoluteString();
+
+ // Restrict to method materials whose make method is still Draft.
+ const onDraftMakeMethod = (
+ eb: ExpressionBuilder<KyselyDatabase, "methodMaterial">
+ ) =>
+ eb(
+ "makeMethodId",
+ "in",
+ eb
+ .selectFrom("makeMethod")
+ .select("id")
+ .where("companyId", "=", args.companyId)
+ .where("status", "=", "Draft")
+ );
+
+ const baseSet: {
+ updatedBy: string;
+ updatedAt: string;
+ sourcingType?: SourcingType;
+ } = {
+ updatedBy: args.userId,
+ updatedAt
+ };
+ if (args.newSourcingType) baseSet.sourcingType = args.newSourcingType;
+
+ await trx
+ .updateTable("methodMaterial")
+ .set((eb) => ({
+ ...baseSet,
+ ...(args.newMethodType === "Make to Order"
+ ? {
+ methodType: "Make to Order" as const,
+ // materialMakeMethodId points at the component item's active make
+ // method (mirrors upsertMethodMaterial). Resolved with a correlated
+ // subquery so a single statement covers every item; null when the
+ // component has no active make method.
+ materialMakeMethodId: eb
+ .selectFrom("activeMakeMethods")
+ .select("id")
+ .whereRef(
+ "activeMakeMethods.itemId",
+ "=",
+ "methodMaterial.itemId"
+ )
+ .where("activeMakeMethods.companyId", "=", args.companyId)
+ .limit(1)
+ }
+ : args.newMethodType
+ ? { methodType: args.newMethodType, materialMakeMethodId: null }
+ : {})
+ }))
+ .where("itemId", "in", args.itemIds)
+ .where("companyId", "=", args.companyId)
+ .where(onDraftMakeMethod)
+ .execute();
+}
+
export async function upsertConsumable(
client: SupabaseClient<Database>,
consumable:
@@ -3317,6 +3451,23 @@ export async function upsertMethodMaterial(
customFields?: Json;
})
) {
+ // sourcingType and methodType are item-level properties (edited in the
+ // item's Properties sidebar). A methodMaterial is a read-only mirror of its
+ // component item, so derive both from the item rather than trusting the
+ // submitted form values.
+ if (methodMaterial.itemId) {
+ const item = await client
+ .from("item")
+ .select("defaultMethodType, sourcingType")
+ .eq("id", methodMaterial.itemId)
+ .single();
+
+ if (item.error) return item;
+ methodMaterial.methodType =
+ item.data.defaultMethodType ?? methodMaterial.methodType;
+ methodMaterial.sourcingType = item.data.sourcingType;
+ }
+
let materialMakeMethodId: string | null = null;
if (methodMaterial.methodType === "Make to Order") {
const makeMethod = await client
diff --git a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
index 6d8b3b0428..6b55be2bc8 100644
--- a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
@@ -108,6 +108,8 @@ type Material = z.infer<typeof methodMaterialValidator> & {
name: string;
itemTrackingType: Database["public"]["Enums"]["itemTrackingType"];
replenishmentSystem: string | null;
+ defaultMethodType: Database["public"]["Enums"]["methodType"];
+ sourcingType: Database["public"]["Enums"]["sourcingType"];
};
};
@@ -206,7 +208,10 @@ const BillOfMaterial = ({
item: {
name: "",
itemTrackingType: "Inventory",
- replenishmentSystem: "Buy and Make"
+ replenishmentSystem: "Buy and Make",
+ defaultMethodType:
+ pendingMaterial.methodType ?? "Pull from Inventory",
+ sourcingType: pendingMaterial.sourcingType ?? "Specified"
}
});
} else {
@@ -701,7 +706,7 @@ function MaterialForm({
const item = await carbon
.from("item")
.select(
- "name, readableIdWithRevision, type, unitOfMeasureCode, defaultMethodType, replenishmentSystem"
+ "name, readableIdWithRevision, type, unitOfMeasureCode, defaultMethodType, sourcingType, replenishmentSystem"
)
.eq("id", itemId)
.eq("companyId", company.id)
@@ -712,12 +717,15 @@ function MaterialForm({
return;
}
+ // Method type and sourcing are item-level properties; mirror them here so
+ // the read-only display matches the item the moment it's selected.
setItemData((d) => ({
...d,
itemId,
description: item.data?.name ?? "",
unitOfMeasureCode: item.data?.unitOfMeasureCode ?? "EA",
methodType: item.data?.defaultMethodType ?? "Pull from Inventory",
+ sourcingType: item.data?.sourcingType ?? "Specified",
kit: false,
itemReplenishmentSystem: item.data?.replenishmentSystem ?? "Buy"
}));
@@ -752,7 +760,7 @@ function MaterialForm({
name="storageUnitIds"
value={JSON.stringify(itemData.storageUnitIds)}
/>
- {replenishmentSystem !== "Buy and Make" && (
+ {itemData.itemReplenishmentSystem !== "Buy and Make" && (
<Hidden name="sourcingType" value={itemData.sourcingType} />
)}
</div>
@@ -832,7 +840,7 @@ function MaterialForm({
}
/>
</div>
- {replenishmentSystem === "Buy and Make" && (
+ {itemData.itemReplenishmentSystem === "Buy and Make" && (
<div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4 w-full">
<HStack
className="w-full justify-between cursor-pointer"
@@ -874,10 +882,13 @@ function MaterialForm({
sourcingDisclosure.isOpen ? "" : "hidden"
}`}
>
+ {/* Read-only: sourcing is set at the item level (Properties
+ sidebar) and mirrored here. */}
<Select
name="sourcingType"
label={t`Sourcing Type`}
value={itemData.sourcingType}
+ isReadOnly
options={sourcingType.map((s) => ({
value: s,
label: (
@@ -887,20 +898,6 @@ function MaterialForm({
</span>
)
}))}
- onChange={(value) => {
- const newSourcingType = value?.value as SourcingType;
- setItemData((d) => {
- const updates: Partial<typeof d> = {
- sourcingType: newSourcingType
- };
- if (newSourcingType === "Drop Ship") {
- updates.methodType = "Purchase to Order";
- } else if (newSourcingType === "Ship from Inventory") {
- updates.methodType = "Pull from Inventory";
- }
- return { ...d, ...updates };
- });
- }}
/>
</div>
</div>
@@ -970,16 +967,13 @@ function MaterialForm({
sourceDisclosure.isOpen ? "" : "hidden"
}`}
>
+ {/* Read-only: method type is the item's default method type
+ (Properties sidebar) and mirrored here. */}
<DefaultMethodType
name="methodType"
label={t`Method Type`}
value={itemData.methodType}
- onChange={(value) => {
- setItemData((d) => ({
- ...d,
- methodType: value?.value as MethodType
- }));
- }}
+ isReadOnly
isConfigured={rulesByField.has(key("methodType"))}
onConfigure={
configurable && !temporaryItems[item.id]
diff --git a/apps/erp/app/modules/items/ui/Item/SourcingTypeProperty.tsx b/apps/erp/app/modules/items/ui/Item/SourcingTypeProperty.tsx
new file mode 100644
index 0000000000..323209fa5a
--- /dev/null
+++ b/apps/erp/app/modules/items/ui/Item/SourcingTypeProperty.tsx
@@ -0,0 +1,58 @@
+import { Select, ValidatedForm } from "@carbon/form";
+import { Badge } from "@carbon/react";
+import { useLingui } from "@lingui/react/macro";
+import { z } from "zod";
+import { SourcingTypeIcon } from "~/components/Icons";
+import type { SourcingType } from "~/modules/shared";
+import { sourcingType } from "~/modules/shared";
+
+type SourcingTypePropertyProps = {
+ replenishmentSystem?: string | null;
+ value?: SourcingType | null;
+ onChange: (value: SourcingType | null) => void;
+};
+
+/**
+ * Item-level sourcing selector shown in the Part/Tool Properties sidebar.
+ * Sourcing only applies to "Buy and Make" items, so it renders nothing
+ * otherwise. Shared between PartProperties and ToolProperties — keep it here
+ * rather than duplicating the form block in each.
+ */
+export function SourcingTypeProperty({
+ replenishmentSystem,
+ value,
+ onChange
+}: SourcingTypePropertyProps) {
+ const { t } = useLingui();
+
+ if (replenishmentSystem !== "Buy and Make") return null;
+
+ return (
+ <ValidatedForm
+ defaultValues={{ sourcingType: value ?? undefined }}
+ validator={z.object({ sourcingType: z.enum(sourcingType) })}
+ className="w-full"
+ >
+ <Select
+ name="sourcingType"
+ label={t`Sourcing`}
+ inline={(value) => (
+ <Badge variant="secondary">
+ <SourcingTypeIcon type={value} className="mr-2" />
+ <span>{value}</span>
+ </Badge>
+ )}
+ options={sourcingType.map((type) => ({
+ value: type,
+ label: (
+ <span className="flex items-center gap-2">
+ <SourcingTypeIcon type={type} />
+ {type}
+ </span>
+ )
+ }))}
+ onChange={(value) => onChange((value?.value as SourcingType) ?? null)}
+ />
+ </ValidatedForm>
+ );
+}
diff --git a/apps/erp/app/modules/items/ui/Item/index.ts b/apps/erp/app/modules/items/ui/Item/index.ts
index a37b567a07..80b76bd446 100644
--- a/apps/erp/app/modules/items/ui/Item/index.ts
+++ b/apps/erp/app/modules/items/ui/Item/index.ts
@@ -14,6 +14,7 @@ import ItemSalePriceForm from "./ItemSalePriceForm";
import MakeMethodTools from "./MakeMethodTools";
import PickMethodForm from "./PickMethodForm";
import { SelectedItemProperties } from "./SelectedItemProperties";
+import { SourcingTypeProperty } from "./SourcingTypeProperty";
import SupplierPartForm from "./SupplierPartForm";
import SupplierParts from "./SupplierParts";
@@ -35,6 +36,7 @@ export {
MakeMethodTools,
PickMethodForm,
SelectedItemProperties,
+ SourcingTypeProperty,
SupplierPartForm,
SupplierParts
};
diff --git a/apps/erp/app/modules/items/ui/Parts/PartProperties.tsx b/apps/erp/app/modules/items/ui/Parts/PartProperties.tsx
index 28a38f5266..f903a20519 100644
--- a/apps/erp/app/modules/items/ui/Parts/PartProperties.tsx
+++ b/apps/erp/app/modules/items/ui/Parts/PartProperties.tsx
@@ -51,7 +51,7 @@ import type {
PickMethod,
SupplierPart
} from "../../types";
-import { FileBadge, ItemDescription } from "../Item";
+import { FileBadge, ItemDescription, SourcingTypeProperty } from "../Item";
type PartPropertiesProps = {
data?: {
@@ -113,6 +113,7 @@ const PartProperties = ({ data }: PartPropertiesProps) => {
field:
| "active"
| "defaultMethodType"
+ | "sourcingType"
| "itemTrackingType"
| "itemPostingGroupId"
| "partId"
@@ -484,6 +485,12 @@ const PartProperties = ({ data }: PartPropertiesProps) => {
/>
</ValidatedForm>
+ <SourcingTypeProperty
+ replenishmentSystem={routeData?.partSummary?.replenishmentSystem}
+ value={routeData?.partSummary?.sourcingType}
+ onChange={(value) => onUpdate("sourcingType", value)}
+ />
+
<ValidatedForm
defaultValues={{
unitOfMeasureCode:
diff --git a/apps/erp/app/modules/items/ui/Tools/ToolProperties.tsx b/apps/erp/app/modules/items/ui/Tools/ToolProperties.tsx
index 8662bc2423..60d89d8987 100644
--- a/apps/erp/app/modules/items/ui/Tools/ToolProperties.tsx
+++ b/apps/erp/app/modules/items/ui/Tools/ToolProperties.tsx
@@ -40,7 +40,7 @@ import type {
SupplierPart,
Tool
} from "../../types";
-import { FileBadge, ItemDescription } from "../Item";
+import { FileBadge, ItemDescription, SourcingTypeProperty } from "../Item";
type ToolPropertiesProps = {
data?: {
@@ -104,6 +104,7 @@ const ToolProperties = ({ data }: ToolPropertiesProps) => {
| "description"
| "replenishmentSystem"
| "defaultMethodType"
+ | "sourcingType"
| "itemTrackingType"
| "itemPostingGroupId"
| "toolId"
@@ -462,6 +463,12 @@ const ToolProperties = ({ data }: ToolPropertiesProps) => {
/>
</ValidatedForm>
+ <SourcingTypeProperty
+ replenishmentSystem={routeData?.toolSummary?.replenishmentSystem}
+ value={routeData?.toolSummary?.sourcingType}
+ onChange={(value) => onUpdate("sourcingType", value)}
+ />
+
<VStack spacing={2}>
<h3 className="text-xs text-muted-foreground">
<Trans>Unit of Measure</Trans>
diff --git a/apps/erp/app/routes/api+/kanban.$id.tsx b/apps/erp/app/routes/api+/kanban.$id.tsx
index 2add652fa9..a1455ba9b1 100644
--- a/apps/erp/app/routes/api+/kanban.$id.tsx
+++ b/apps/erp/app/routes/api+/kanban.$id.tsx
@@ -283,7 +283,6 @@ async function handleKanban({
const createPurchaseOrderLine = await upsertPurchaseOrderLine(client, {
purchaseOrderId: purchaseOrderId!,
- // @ts-expect-error
purchaseOrderLineType: item.data?.type,
itemId: kanban.data.itemId!,
purchaseQuantity: kanban.data.quantity!,
@@ -292,7 +291,6 @@ async function handleKanban({
supplierShippingCost: 0,
supplierTaxAmount: 0,
exchangeRate: 1,
- setupPrice: 0,
purchaseUnitOfMeasureCode: kanban.data.purchaseUnitOfMeasureCode!,
inventoryUnitOfMeasureCode:
item.data?.unitOfMeasureCode || kanban.data.purchaseUnitOfMeasureCode!,
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 544ac3d146..cf28ef8d78 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,6 +1,6 @@
{
- "generated": "2026-06-16T11:37:18.308Z",
- "totalTools": 1206,
+ "generated": "2026-06-16T19:30:33.494Z",
+ "totalTools": 1207,
"modules": 15,
"tools": [
{
@@ -11231,6 +11231,37 @@
]
}
},
+ {
+ "name": "items_updateItemMethodAndSourcing",
+ "module": "items",
+ "classification": "WRITE",
+ "description": "update item method and sourcing",
+ "paramCount": 3,
+ "serviceParams": [
+ "db",
+ "args"
+ ],
+ "injectAuth": [
+ "companyId",
+ "updatedBy"
+ ],
+ "schema": {
+ "type": "object",
+ "properties": {
+ "itemIds": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "itemUpdate: {\n replenishmentSystem": {},
+ "cascade: {\n sourcingType": {}
+ },
+ "required": [
+ "itemIds"
+ ]
+ }
+ },
{
"name": "items_upsertConsumable",
"module": "items",
diff --git a/apps/erp/app/routes/x+/items+/update.tsx b/apps/erp/app/routes/x+/items+/update.tsx
index 6274be19d9..5f36049b39 100644
--- a/apps/erp/app/routes/x+/items+/update.tsx
+++ b/apps/erp/app/routes/x+/items+/update.tsx
@@ -3,11 +3,94 @@ import type { Database } from "@carbon/database";
import { getMaterialDescription, getMaterialId } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import type { InventoryItemType } from "~/modules/items";
-
-import { cascadeItemTrackingType } from "~/modules/items/items.service";
+import {
+ cascadeItemTrackingType,
+ updateItemMethodAndSourcing
+} from "~/modules/items/items.service";
import { getCompanySettings } from "~/modules/settings";
+import type { MethodType, SourcingType } from "~/modules/shared";
import { getDatabaseClient } from "~/services/database.server";
+type ItemReplenishmentSystem =
+ Database["public"]["Enums"]["itemReplenishmentSystem"];
+
+/**
+ * Maps an inline edit of one of the three interlocked item-level fields
+ * (replenishmentSystem, defaultMethodType, sourcingType) to the columns that
+ * should be written on the item and the values that should be mirrored down to
+ * its method materials. Pure — no DB access — so the relationships between the
+ * fields live in one readable place instead of being scattered across branches.
+ */
+function deriveItemMethodUpdate(
+ field: "replenishmentSystem" | "defaultMethodType" | "sourcingType",
+ value: string
+): {
+ itemUpdate: {
+ replenishmentSystem?: ItemReplenishmentSystem;
+ defaultMethodType?: MethodType;
+ sourcingType?: SourcingType;
+ };
+ cascade: { sourcingType?: SourcingType; methodType?: MethodType };
+} {
+ switch (field) {
+ case "replenishmentSystem": {
+ const replenishmentSystem = value as ItemReplenishmentSystem;
+ // Picking a concrete replenishment system pins the default method type.
+ if (value !== "Buy and Make") {
+ const defaultMethodType: MethodType =
+ value === "Make"
+ ? "Make to Order"
+ : value === "Buy"
+ ? "Purchase to Order"
+ : "Pull from Inventory";
+ return {
+ itemUpdate: { replenishmentSystem, defaultMethodType },
+ cascade: { methodType: defaultMethodType }
+ };
+ }
+ return { itemUpdate: { replenishmentSystem }, cascade: {} };
+ }
+ case "defaultMethodType": {
+ const defaultMethodType = value as MethodType;
+ // A concrete method type pins the replenishment system to match.
+ if (value !== "Pull from Inventory") {
+ const replenishmentSystem: ItemReplenishmentSystem =
+ value === "Make to Order"
+ ? "Make"
+ : value === "Purchase to Order"
+ ? "Buy"
+ : "Buy and Make";
+ return {
+ itemUpdate: { defaultMethodType, replenishmentSystem },
+ cascade: { methodType: defaultMethodType }
+ };
+ }
+ return {
+ itemUpdate: { defaultMethodType },
+ cascade: { methodType: defaultMethodType }
+ };
+ }
+ case "sourcingType": {
+ const sourcingType = value as SourcingType;
+ // Sourcing drives method type: Drop Ship → Purchase to Order, Ship from
+ // Inventory → Pull from Inventory, Specified → leave method type as-is.
+ const methodType: MethodType | undefined =
+ value === "Drop Ship"
+ ? "Purchase to Order"
+ : value === "Ship from Inventory"
+ ? "Pull from Inventory"
+ : undefined;
+ return {
+ itemUpdate: {
+ sourcingType,
+ ...(methodType ? { defaultMethodType: methodType } : {})
+ },
+ cascade: { sourcingType, methodType }
+ };
+ }
+ }
+}
+
export async function action({ request }: ActionFunctionArgs) {
const { client, companyId, userId } = await requirePermissions(request, {
update: "parts"
@@ -55,47 +138,9 @@ export async function action({ request }: ActionFunctionArgs) {
return result;
}
- case "defaultMethodType":
case "name":
case "description":
- case "replenishmentSystem":
case "unitOfMeasureCode":
- if (field === "replenishmentSystem" && value !== "Buy and Make") {
- return await client
- .from("item")
- .update({
- // @ts-expect-error
- [field]: value,
- defaultMethodType:
- value === "Make"
- ? "Make to Order"
- : value === "Buy"
- ? "Purchase to Order"
- : "Pull from Inventory",
- updatedBy: userId,
- updatedAt: new Date().toISOString()
- })
- .in("id", items as string[])
- .eq("companyId", companyId);
- }
- if (field === "defaultMethodType" && value !== "Pull from Inventory") {
- return await client
- .from("item")
- .update({
- // @ts-expect-error - value is a valid method type
- defaultMethodType: value,
- replenishmentSystem:
- value === "Make to Order"
- ? "Make"
- : value === "Purchase to Order"
- ? "Buy"
- : "Buy and Make",
- updatedBy: userId,
- updatedAt: new Date().toISOString()
- })
- .in("id", items as string[])
- .eq("companyId", companyId);
- }
return await client
.from("item")
.update({
@@ -105,6 +150,27 @@ export async function action({ request }: ActionFunctionArgs) {
})
.in("id", items as string[])
.eq("companyId", companyId);
+ case "replenishmentSystem":
+ case "defaultMethodType":
+ case "sourcingType": {
+ // These three fields are interlocked and each mirror down to the item's
+ // method materials. updateItemMethodAndSourcing applies the item write
+ // and the cascade in one transaction, so they can't be left half-applied.
+ const { itemUpdate, cascade } = deriveItemMethodUpdate(field, value);
+ try {
+ await updateItemMethodAndSourcing(getDatabaseClient(), {
+ itemIds: items as string[],
+ companyId,
+ userId,
+ itemUpdate,
+ cascade
+ });
+ } catch (err) {
+ console.error(err);
+ return { error: { message: "Failed to update item" }, data: null };
+ }
+ return { data: null, error: null };
+ }
case "gradeId":
case "dimensionId":
case "finishId":
diff --git a/llm/cache/method-material-sourcing.md b/llm/cache/method-material-sourcing.md
new file mode 100644
index 0000000000..c0270fcde0
--- /dev/null
+++ b/llm/cache/method-material-sourcing.md
@@ -0,0 +1,53 @@
+# Method Material Sourcing & Method Type (item-level)
+
+`methodMaterial.sourcingType` and `methodMaterial.methodType` are **read-only
+mirrors** of the component item they reference (`methodMaterial.itemId`). They
+are NOT edited per-row in the Bill of Material editor. Instead they come from
+item-level properties:
+
+- `item.defaultMethodType` (enum `methodType`: `Purchase to Order` /
+ `Pull from Inventory` / `Make to Order`)
+- `item.sourcingType` (enum `sourcingType`: `Specified` / `Drop Ship` /
+ `Ship from Inventory`) — added in migration `20260615143722_item-sourcing-type.sql`.
+
+Both DB and UI method-type enums match (no translation). Enums live in
+`apps/erp/app/modules/shared/shared.models.ts`; types `MethodType` /
+`SourcingType` in `apps/erp/app/modules/shared/types.ts`.
+
+## Where it's edited
+- Part: `apps/erp/app/modules/items/ui/Parts/PartProperties.tsx` — "Default
+ Method Type" select; "Sourcing" select shown only when
+ `replenishmentSystem === "Buy and Make"`.
+- Tool: `apps/erp/app/modules/items/ui/Tools/ToolProperties.tsx` — same.
+- Both submit via `onUpdate(field, value)` → `path.to.bulkUpdateItems`
+ (`apps/erp/app/routes/x+/items+/update.tsx`).
+
+## Sourcing → method type mapping
+Applied server-side in `update.tsx` (`sourcingType` case) and historically in
+the BOM UI: `Drop Ship` → `Purchase to Order`, `Ship from Inventory` →
+`Pull from Inventory`, `Specified` → leave method type as-is.
+
+## Sync / cascade
+- New/edited method materials derive both fields from the item in
+ `upsertMethodMaterial` (`items.service.ts` ~3300) — form values are advisory.
+- `cascadeItemSourcingAndMethodType` (`items.service.ts`, modeled on
+ `cascadeItemTrackingType`) updates all `methodMaterial` rows referencing the
+ changed item when sourcing/method type changes at the item level. Scoped to
+ **Draft** make methods only (`makeMethod.status = 'Draft'`); Active/Archived
+ are frozen. Make-to-Order rows get `materialMakeMethodId` resolved per item
+ from `activeMakeMethods` (null if none). Wired into the `defaultMethodType`
+ and `sourcingType` cases of `update.tsx`.
+
+## BOM editor display
+`apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx`: Sourcing section +
+Method Type ("Pull From"/"Finish To") render read-only (`isReadOnly`), still
+submitting via hidden inputs. The Sourcing section is gated on the **component**
+item's replenishment (`itemData.itemReplenishmentSystem === "Buy and Make"`),
+not the parent's. `getMethodMaterialsByMakeMethod` selects
+`item(... defaultMethodType, sourcingType)`.
+
+## RPC note
+`item.sourcingType` is surfaced to the Part/Tool detail loaders by recreating
+`get_part_details` / `get_tool_details` (RETURNS TABLE + SELECT) in the same
+migration. `PartSummary`/`ToolSummary` types derive from these RPCs, so they
+pick up `sourcingType` after `db:types` regen.
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index e3f6775fe5..0ddacc00c7 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -13011,6 +13011,7 @@ export type Database = {
replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"]
requiresInspection: boolean
revision: string | null
+ sourcingType: Database["public"]["Enums"]["sourcingType"]
thumbnailPath: string | null
trackingMethod: string | null
type: Database["public"]["Enums"]["itemType"]
@@ -13037,6 +13038,7 @@ export type Database = {
replenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"]
requiresInspection?: boolean
revision?: string | null
+ sourcingType?: Database["public"]["Enums"]["sourcingType"]
thumbnailPath?: string | null
trackingMethod?: string | null
type: Database["public"]["Enums"]["itemType"]
@@ -13063,6 +13065,7 @@ export type Database = {
replenishmentSystem?: Database["public"]["Enums"]["itemReplenishmentSystem"]
requiresInspection?: boolean
revision?: string | null
+ sourcingType?: Database["public"]["Enums"]["sourcingType"]
thumbnailPath?: string | null
trackingMethod?: string | null
type?: Database["public"]["Enums"]["itemType"]
@@ -55468,6 +55471,7 @@ export type Database = {
| null
revision: string | null
revisions: Json | null
+ sourcingType: Database["public"]["Enums"]["sourcingType"] | null
supplierIds: string | null
tags: string[] | null
thumbnailPath: string | null
@@ -63791,6 +63795,7 @@ export type Database = {
| null
revision: string | null
revisions: Json | null
+ sourcingType: Database["public"]["Enums"]["sourcingType"] | null
supplierIds: string | null
tags: string[] | null
thumbnailPath: string | null
@@ -65495,6 +65500,7 @@ export type Database = {
requiresInspection: boolean
revision: string
revisions: Json
+ sourcingType: Database["public"]["Enums"]["sourcingType"]
tags: string[]
thumbnailPath: string
unitOfMeasure: string
@@ -66009,6 +66015,7 @@ export type Database = {
requiresInspection: boolean
revision: string
revisions: Json
+ sourcingType: Database["public"]["Enums"]["sourcingType"]
tags: string[]
thumbnailPath: string
unitOfMeasure: string
diff --git a/packages/database/supabase/functions/lib/postgres/index.ts b/packages/database/supabase/functions/lib/postgres/index.ts
index 86bac0aaca..8a83724032 100644
--- a/packages/database/supabase/functions/lib/postgres/index.ts
+++ b/packages/database/supabase/functions/lib/postgres/index.ts
@@ -16,7 +16,7 @@ export type KyselyDatabase = KyselifyDatabase<SupabaseDatabase>;
export type KyselyTx = Transaction<KyselyDatabase>;
export type KyselyDbTx = KyselyDatabase | KyselyTx;
-export type { Kysely } from "kysely";
+export type { ExpressionBuilder, Kysely } from "kysely";
export function getRuntime() {
if (typeof (globalThis as Record<string, unknown>).Deno !== "undefined") {
diff --git a/packages/database/supabase/migrations/20260615143722_item-sourcing-type.sql b/packages/database/supabase/migrations/20260615143722_item-sourcing-type.sql
new file mode 100644
index 0000000000..0f355c2746
--- /dev/null
+++ b/packages/database/supabase/migrations/20260615143722_item-sourcing-type.sql
@@ -0,0 +1,477 @@
+-- Item-level sourcing type.
+--
+-- Sourcing (sourcingType) was previously specified per-row on methodMaterial.
+-- We are promoting it to an item-level property (alongside defaultMethodType)
+-- so it can be edited once in the item's Properties sidebar and cascaded to
+-- every methodMaterial that references the item. This adds the column to
+-- "item" and surfaces it through the Part/Tool detail RPCs.
+--
+-- The "sourcingType" enum already exists (20260321230229_sourcing-types.sql).
+
+ALTER TABLE "item"
+ ADD COLUMN "sourcingType" "sourcingType" NOT NULL DEFAULT 'Specified';
+
+-- Backfill from the most common existing methodMaterial.sourcingType per item
+-- so existing BOMs keep their current sourcing instead of resetting to
+-- 'Specified'. defaultMethodType is already populated, so it needs no backfill.
+UPDATE "item" i
+SET "sourcingType" = sub."sourcingType"
+FROM (
+ SELECT
+ mm."itemId",
+ mm."companyId",
+ mode() WITHIN GROUP (ORDER BY mm."sourcingType") AS "sourcingType"
+ FROM "methodMaterial" mm
+ WHERE mm."itemId" IS NOT NULL
+ GROUP BY mm."itemId", mm."companyId"
+) sub
+WHERE i.id = sub."itemId" AND i."companyId" = sub."companyId";
+
+
+-- =============================================================================
+-- get_part_details (recreated to expose "sourcingType")
+-- Body unchanged from 20260515120000 aside from the new column.
+-- DROP first: adding a column to the RETURNS TABLE changes the function's
+-- result row type, which CREATE OR REPLACE cannot do (SQLSTATE 42P13).
+-- =============================================================================
+DROP FUNCTION IF EXISTS get_part_details(TEXT);
+CREATE OR REPLACE FUNCTION get_part_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
+) 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" = 'Part'
+ )
+ 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",
+ p."customFields",
+ p."tags",
+ ic."itemPostingGroupId",
+ i."createdBy",
+ i."createdAt",
+ i."updatedBy",
+ i."updatedAt"
+ FROM "part" p
+ LEFT JOIN "item" i ON i."readableId" = p."id" AND i."companyId" = p."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;
+
+
+-- =============================================================================
+-- get_tool_details (recreated to expose "sourcingType")
+-- Body unchanged from 20260515120000 aside from the new column.
+-- DROP first: adding a column to the RETURNS TABLE changes the function's
+-- result row type, which CREATE OR REPLACE cannot do (SQLSTATE 42P13).
+-- =============================================================================
+DROP FUNCTION IF EXISTS get_tool_details(TEXT);
+CREATE OR REPLACE FUNCTION get_tool_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
+) 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" = 'Tool'
+ )
+ 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",
+ t."customFields",
+ t."tags",
+ ic."itemPostingGroupId",
+ i."createdBy",
+ i."createdAt",
+ i."updatedBy",
+ i."updatedAt"
+ FROM "tool" t
+ LEFT JOIN "item" i ON i."readableId" = t."id" AND i."companyId" = t."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;
+
+
+-- =============================================================================
+-- tools (view) — recreated to expose "sourcingType".
+-- The Tool properties sidebar's `Tool` type derives from this view.
+-- Body unchanged from 20260419130000 aside from the new column.
+-- DROP first: "sourcingType" is inserted mid-list (after "defaultMethodType"),
+-- and CREATE OR REPLACE VIEW can only append columns at the end.
+-- =============================================================================
+DROP VIEW IF EXISTS "tools";
+CREATE VIEW "tools" WITH (SECURITY_INVOKER=true) AS
+WITH latest_items AS (
+ SELECT DISTINCT ON (i."readableId", i."companyId")
+ i.*,
+ 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'
+ ORDER BY i."readableId", i."companyId",
+ CASE WHEN i."revision" = '0' OR i."revision" = '' 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' OR i."revision" = '' OR i."revision" IS NULL THEN 0 ELSE 1 END,
+ i."createdAt"
+ ) as "revisions"
+ FROM "item" i
+ WHERE i."type" = 'Tool'
+ 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
+ )
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item' AND eim."entityId" = li.id
+ ) AS "externalId",
+ li."createdBy",
+ li."createdAt",
+ li."updatedBy",
+ li."updatedAt"
+FROM "tool" t
+ INNER JOIN latest_items li 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
+ "itemId",
+ "companyId",
+ string_agg(ps."supplierPartId", ',') AS "supplierIds"
+ FROM "supplierPart" ps
+ GROUP BY "itemId", "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;
+
+
+-- =============================================================================
+-- parts (view) — recreated to expose "sourcingType".
+-- Kept in lockstep with the "tools" view: both list views already carry
+-- "defaultMethodType", so "sourcingType" belongs on both.
+-- Body unchanged from 20260419130000 aside from the new column.
+-- DROP first: "sourcingType" is inserted mid-list (after "defaultMethodType"),
+-- and CREATE OR REPLACE VIEW can only append columns at the end.
+-- =============================================================================
+DROP VIEW IF EXISTS "parts";
+CREATE VIEW "parts" WITH (SECURITY_INVOKER=true) AS
+WITH latest_items AS (
+ SELECT DISTINCT ON (i."readableId", i."companyId")
+ i.*,
+ 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" = 'Part'
+ ORDER BY i."readableId", i."companyId",
+ CASE WHEN i."revision" = '0' OR i."revision" = '' 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",
+ 'name', i."name",
+ 'description', i."description",
+ 'active', i."active",
+ 'createdAt', i."createdAt"
+ ) ORDER BY
+ CASE WHEN i."revision" = '0' OR i."revision" = '' OR i."revision" IS NULL THEN 0 ELSE 1 END,
+ i."createdAt"
+ ) as "revisions"
+ FROM "item" i
+ WHERE i."type" = 'Part'
+ 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",
+ p."customFields",
+ p."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
+ )
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item' AND eim."entityId" = li.id
+ ) AS "externalId",
+ li."createdBy",
+ li."createdAt",
+ li."updatedBy",
+ li."updatedAt"
+FROM "part" p
+INNER JOIN latest_items li ON li."readableId" = p."id" AND li."companyId" = p."companyId"
+LEFT JOIN item_revisions ir ON ir."readableId" = p."id" AND ir."companyId" = p."companyId"
+LEFT JOIN (
+ SELECT
+ "itemId",
+ "companyId",
+ string_agg(ps."supplierPartId", ',') AS "supplierIds"
+ FROM "supplierPart" ps
+ GROUP BY "itemId", "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;
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index d9d6a2e696..52828632fa 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -7472,6 +7472,9 @@ msgstr "Quellmethode"
msgid "Source Version"
msgstr "Quellversion"
+msgid "Sourcing"
+msgstr "Beschaffung"
+
msgid "Sourcing Type"
msgstr "Beschaffungstyp"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 42b21d00fd..3b8c57d21e 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -7472,6 +7472,9 @@ msgstr "Source Method"
msgid "Source Version"
msgstr "Source Version"
+msgid "Sourcing"
+msgstr "Sourcing"
+
msgid "Sourcing Type"
msgstr "Sourcing Type"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 755b0b391f..643877a8c4 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -7472,6 +7472,9 @@ msgstr "Método de Origen"
msgid "Source Version"
msgstr "Versión de Origen"
+msgid "Sourcing"
+msgstr "Abastecimiento"
+
msgid "Sourcing Type"
msgstr "Tipo de Abastecimiento"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 28d6825a44..b5a90a5246 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -7472,6 +7472,9 @@ msgstr "Méthode source"
msgid "Source Version"
msgstr "Version source"
+msgid "Sourcing"
+msgstr "Approvisionnement"
+
msgid "Sourcing Type"
msgstr "Type d'approvisionnement"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index cd815fcf92..ecd1d895d2 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -7472,6 +7472,9 @@ msgstr "स्रोत विधि"
msgid "Source Version"
msgstr "स्रोत संस्करण"
+msgid "Sourcing"
+msgstr "सोर्सिंग"
+
msgid "Sourcing Type"
msgstr "सोर्सिंग प्रकार"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index a54fe7fa83..93a6c121af 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -7472,6 +7472,9 @@ msgstr "Metodo Sorgente"
msgid "Source Version"
msgstr "Versione Sorgente"
+msgid "Sourcing"
+msgstr "Approvvigionamento"
+
msgid "Sourcing Type"
msgstr "Tipo di approvvigionamento"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 911d30e219..de5a736578 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -7472,6 +7472,9 @@ msgstr "ソース方法"
msgid "Source Version"
msgstr "ソースバージョン"
+msgid "Sourcing"
+msgstr "ソーシング"
+
msgid "Sourcing Type"
msgstr "調達タイプ"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 9f958d80e1..f122113eb5 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -7472,6 +7472,9 @@ msgstr "Metoda źródłowa"
msgid "Source Version"
msgstr "Wersja źródłowa"
+msgid "Sourcing"
+msgstr "Pozyskiwanie"
+
msgid "Sourcing Type"
msgstr "Typ pozyskiwania"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 0275a8dbcb..ae3e2130d7 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -7472,6 +7472,9 @@ msgstr "Método de Origem"
msgid "Source Version"
msgstr "Versão de Origem"
+msgid "Sourcing"
+msgstr "Fornecimento"
+
msgid "Sourcing Type"
msgstr "Tipo de Fornecimento"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 1f9037454a..17387d4519 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -7472,6 +7472,9 @@ msgstr "Исходный метод"
msgid "Source Version"
msgstr "Исходная версия"
+msgid "Sourcing"
+msgstr "Источник"
+
msgid "Sourcing Type"
msgstr "Тип источника"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 05b9afa368..423a8c794f 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -7472,6 +7472,9 @@ msgstr "源方法"
msgid "Source Version"
msgstr "源版本"
+msgid "Sourcing"
+msgstr "采购"
+
msgid "Sourcing Type"
msgstr "采购类型"