Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import type { Json } from "@carbon/database";
import { InputControlled, Select, ValidatedForm } from "@carbon/form";
import { useAction } from "@carbon/query";
import {
Badge,
Button,
Copy,
HStack,
Subheading,
Tooltip,
TooltipContent,
TooltipTrigger,
toast,
VStack
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
import { Suspense, useCallback } from "react";
import { LuCopy, LuKeySquare, LuLink } from "react-icons/lu";
import { Await, Link, useParams } from "react-router";
import { z } from "zod";
import { zfd } from "zod-form-data";
import { MethodBadge, MethodIcon, TrackingTypeIcon } from "~/components";
import {
Boolean,
ItemPostingGroup,
Tags,
UnitOfMeasure
} from "~/components/Form";
import CustomFormInlineFields from "~/components/Form/CustomFormInlineFields";
import { ItemThumbnailUpload } from "~/components/ItemThumnailUpload";
import { useCompanySettings, useRouteData } from "~/hooks";
import { useResolved } from "~/hooks/useResolved";
import { methodType } from "~/modules/shared/shared.models";
import type { action } from "~/routes/x+/items+/update";
import { useSuppliers } from "~/stores";
import type { ListItem } from "~/types";
import { path } from "~/utils/path";
import { copyToClipboard } from "~/utils/string";
import { itemTrackingTypes } from "../../items.models";
import type {
Consumable,
ItemFile,
PickMethod,
SupplierPart
} from "../../types";
import { FileBadge, ItemDescription } from "../Item";
type ConsumablePropertiesProps = {
data?: {
itemId: string;
locations: ListItem[];
consumableSummary: Consumable;
files: Promise<ItemFile[]>;
supplierParts: SupplierPart[];
pickMethods: PickMethod[];
tags: { name: string }[];
};
};
const ConsumableProperties = ({ data }: ConsumablePropertiesProps) => {
const { t } = useLingui();
const translateMethodType = (v: string) =>
v === "Purchase to Order"
? t`Purchase to Order`
: v === "Pull from Inventory"
? t`Pull from Inventory`
: t`Make to Order`;
const translateTrackingType = (v: string) =>
v === "Inventory"
? t`Inventory`
: v === "Non-Inventory"
? t`Non-Inventory`
: v === "Serial"
? t`Serial`
: t`Batch`;
const params = useParams();
const allowLowercaseItemIds =
useCompanySettings()?.allowLowercaseItemIds === true;
const itemId = data?.itemId ?? params.itemId;
if (!itemId) throw new Error("itemId not found");
const sharedConsumablesData = useRouteData<{ locations: ListItem[] }>(
path.to.consumableRoot
);
// When `data` is injected (subassembly context), this hook won't match a
// route and returns undefined — harmless, hooks must be called unconditionally.
const routeDataFromRoute = useRouteData<{
consumableSummary: Consumable;
files: Promise<ItemFile[]>;
supplierParts: SupplierPart[];
pickMethods: PickMethod[];
tags: { name: string }[];
supersession?: Promise<{
successorItemId: string | null;
successorEffectivityDate: string | null;
successor: {
id: string;
readableIdWithRevision: string;
name: string;
} | null;
} | null>;
supersededBy?: Promise<
Array<{
predecessor: {
id: string;
readableIdWithRevision: string;
name: string;
} | null;
}>
>;
}>(path.to.consumable(itemId));
const supersession = useResolved(
routeDataFromRoute?.supersession,
null,
itemId
);
const supersededBy = useResolved(
routeDataFromRoute?.supersededBy,
null,
itemId
);
const routeData = data ?? routeDataFromRoute;
const locations = data?.locations ?? sharedConsumablesData?.locations ?? [];
const supplierParts = routeData?.supplierParts ?? [];
const pickMethods = routeData?.pickMethods ?? [];
// const optimisticAssignment = useOptimisticAssignment({
// id: itemId,
// table: "item",
// });
// const assignee =
// optimisticAssignment !== undefined
// ? optimisticAssignment
// : routeData?.consumableSummary?.assignee;
const fetcher = useAction<typeof action>({
onError: (data) => {
if (data?.error) {
toast.error(data.error.message);
}
}
});
// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
const onUpdate = useCallback(
(
field:
| "name"
| "description"
| "replenishmentSystem"
| "defaultMethodType"
| "itemTrackingType"
| "itemPostingGroupId"
| "consumableId"
| "active"
| "mpn"
| "unitOfMeasureCode",
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?.consumableSummary?.readableId ?? "");
formData.append("table", "consumable");
value.forEach((v) => {
formData.append("value", v);
});
fetcher.submit(formData, {
method: "post",
action: path.to.tags
});
},
[routeData?.consumableSummary?.readableId]
);
// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
const onUpdateCustomFields = useCallback(
(value: string) => {
const formData = new FormData();
formData.append("ids", routeData?.consumableSummary?.readableId ?? "");
formData.append("table", "consumable");
formData.append("value", value);
fetcher.submit(formData, {
method: "post",
action: path.to.customFields
});
},
[routeData?.consumableSummary?.readableId]
);
const [suppliers] = useSuppliers();
return (
<VStack
spacing={4}
className="w-96 bg-background/30 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">
<Subheading as="h3" variant="light">
<Trans>Properties</Trans>
</Subheading>
<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.consumable(itemId)
)
}
>
<LuLink className="w-3 h-3" />
</Button>
</TooltipTrigger>
<TooltipContent>
<span>
<Trans>Copy link to consumable</Trans>
</span>
</TooltipContent>
</Tooltip>
<Copy
text={itemId}
label={t`Copy consumable unique identifier`}
icon={<LuKeySquare className="size-3" />}
variant="ghost"
className="w-auto"
/>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
aria-label={t`Copy`}
size="sm"
className="p-1"
onClick={() =>
copyToClipboard(
routeData?.consumableSummary?.readableIdWithRevision ?? ""
)
}
>
<LuCopy className="w-3 h-3" />
</Button>
</TooltipTrigger>
<TooltipContent>
<span>
<Trans>Copy consumable number</Trans>
</span>
</TooltipContent>
</Tooltip>
</HStack>
</HStack>
<VStack spacing={1} className="pt-2">
<ValidatedForm
defaultValues={{
consumableId:
routeData?.consumableSummary?.readableIdWithRevision ??
undefined
}}
validator={z.object({
consumableId: z.string()
})}
className="w-full -mt-2"
>
<span className="text-sm">
<InputControlled
label=""
name="consumableId"
inline
size="sm"
isUppercase={!allowLowercaseItemIds}
value={routeData?.consumableSummary?.readableId ?? ""}
onBlur={(e) => {
onUpdate("consumableId", e.target.value ?? null);
}}
className="text-muted-foreground"
/>
</span>
</ValidatedForm>
<ValidatedForm
defaultValues={{
name: routeData?.consumableSummary?.name ?? undefined
}}
validator={z.object({
name: z.string()
})}
className="w-full"
>
<span className="text-xs text-muted-foreground">
<InputControlled
label=""
name="name"
inline
size="sm"
characterLimit={40}
value={routeData?.consumableSummary?.name ?? ""}
onBlur={(e) => {
onUpdate("name", e.target.value ?? null);
}}
className="text-muted-foreground"
/>
</span>
</ValidatedForm>
</VStack>
<ItemThumbnailUpload
path={routeData?.consumableSummary?.thumbnailPath}
itemId={itemId}
/>
</VStack>
{/* <VStack spacing={2}>
<h3 className="text-xs text-muted-foreground">Assignee</h3>
<Assignee
id={itemId}
table="item"
value={assignee ?? ""}
isReadOnly={!permissions.can("update", "parts")}
/>
</VStack> */}
<ValidatedForm
defaultValues={{
itemPostingGroupId:
routeData?.consumableSummary?.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={{
itemTrackingType:
routeData?.consumableSummary?.itemTrackingType ?? undefined
}}
validator={z.object({
itemTrackingType: z.string()
})}
className="w-full"
>
<Select
name="itemTrackingType"
label={t`Tracking Type`}
termId="item-tracking-type"
inline={(value) => (
<Badge variant="secondary">
<TrackingTypeIcon type={value} className="mr-2" />
<span>{translateTrackingType(value)}</span>
</Badge>
)}
options={itemTrackingTypes.map((type) => ({
value: type,
label: (
<span className="flex items-center gap-2">
<TrackingTypeIcon type={type} />
{translateTrackingType(type)}
</span>
)
}))}
onChange={(value) => {
onUpdate("itemTrackingType", value?.value ?? null);
}}
/>
</ValidatedForm>
<ValidatedForm
defaultValues={{
defaultMethodType:
routeData?.consumableSummary?.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>{translateMethodType(value)}</span>
</Badge>
)}
options={methodType
.filter((type) => type !== "Make to Order")
.map((type) => ({
value: type,
label: (
<span className="flex items-center gap-2">
<MethodIcon type={type} />
{translateMethodType(type)}
</span>
)
}))}
onChange={(value) => {
onUpdate("defaultMethodType", value?.value ?? null);
}}
/>
</ValidatedForm>
<ValidatedForm
defaultValues={{
unitOfMeasureCode:
routeData?.consumableSummary?.unitOfMeasureCode ?? undefined
}}
validator={z.object({
unitOfMeasureCode: z
.string()
.min(1, { message: "Unit of Measure is required" })
})}
className="w-full"
>
<UnitOfMeasure
label={t`Unit of Measure`}
name="unitOfMeasureCode"
inline
onChange={(value) => {
onUpdate("unitOfMeasureCode", value?.value ?? null);
}}
/>
</ValidatedForm>
<ItemDescription
value={routeData?.consumableSummary?.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?.consumableSummary?.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.consumablePurchasing(itemId)}
/>
))}
{pickMethods.map((method) => (
<MethodBadge
key={method.locationId}
type="Pull from Inventory"
text={locations.find((l) => l.id === method.locationId)?.name ?? ""}
to={path.to.consumableInventoryLocation(itemId, method.locationId)}
/>
))}
</VStack>
<ValidatedForm
defaultValues={{
active: routeData?.consumableSummary?.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>
{routeData?.consumableSummary?.replenishmentSystem?.includes("Buy") && (
<ValidatedForm
defaultValues={{
mpn: (routeData?.consumableSummary as any)?.mpn ?? undefined
}}
validator={z.object({
mpn: z.string().optional()
})}
className="w-full"
>
<InputControlled
label={t`Manufacturer Part Number`}
name="mpn"
inline
size="sm"
value={(routeData?.consumableSummary as any)?.mpn ?? ""}
onBlur={(e) => {
onUpdate("mpn", e.target.value ?? null);
}}
/>
</ValidatedForm>
)}
{supersession?.successor && (
<div className="w-full">
<h3 className="text-xs text-muted-foreground mb-1">
<Trans>Superseded By</Trans>
</h3>
<Link
to={path.to.consumable(supersession.successor.id)}
className="text-sm text-primary hover:underline"
>
{supersession.successor.readableIdWithRevision}
</Link>
{supersession.successorEffectivityDate && (
<p className="text-xs text-muted-foreground">
<Trans>From {supersession.successorEffectivityDate}</Trans>
</p>
)}
</div>
)}
{(supersededBy?.length ?? 0) > 0 && (
<div className="w-full">
<h3 className="text-xs text-muted-foreground mb-1">
<Trans>Supersedes</Trans>
</h3>
{supersededBy?.map(
(ref) =>
ref.predecessor && (
<Link
key={ref.predecessor.id}
to={path.to.consumable(ref.predecessor.id)}
className="block text-sm text-primary hover:underline"
>
{ref.predecessor.readableIdWithRevision}
</Link>
)
)}
</div>
)}
<ValidatedForm
defaultValues={{
tags: routeData?.consumableSummary?.tags ?? []
}}
validator={z.object({
tags: z.array(z.string()).optional()
})}
className="w-full"
>
<Tags
label={t`Tags`}
name="tags"
availableTags={routeData?.tags ?? []}
table="consumable"
inline
onChange={onUpdateTags}
/>
</ValidatedForm>
<CustomFormInlineFields
customFields={
(routeData?.consumableSummary?.customFields ?? {}) as Record<
string,
Json
>
}
table="consumable"
tags={routeData?.consumableSummary?.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="Consumable"
/>
))
}
</Await>
</Suspense>
</VStack>
</VStack>
);
};
export default ConsumableProperties;