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: serial/batch rework flow and missing rework changes (#841)

Brad Barbin9bd9bc8f3967
diff --git a/apps/erp/app/components/Form/StorageUnit.tsx b/apps/erp/app/components/Form/StorageUnit.tsx
index 8a64be98c8..a856edcc01 100644
--- a/apps/erp/app/components/Form/StorageUnit.tsx
+++ b/apps/erp/app/components/Form/StorageUnit.tsx
@@ -21,7 +21,6 @@ type StorageUnitSelectProps = Omit<
locationId?: string;
/** Kept for API compat; the drill picker doesn't display per-item qty. */
itemId?: string;
- /** No-op in the drill picker — table inline preview no longer supported. */
inline?: boolean;
onChange?: (storageUnit: ListItem | null) => void;
/**
@@ -38,6 +37,7 @@ const StorageUnit = forwardRef<HTMLDivElement, StorageUnitSelectProps>(
const {
name,
label,
+ inline,
locationId,
isReadOnly,
isOptional,
@@ -57,6 +57,7 @@ const StorageUnit = forwardRef<HTMLDivElement, StorageUnitSelectProps>(
<StorageUnitDrillSelectField
name={name}
label={typeof label === "string" ? label : undefined}
+ inline={inline}
helperText={
typeof rest.helperText === "string" ? rest.helperText : undefined
}
diff --git a/apps/erp/app/components/Form/StorageUnitDrillSelect.tsx b/apps/erp/app/components/Form/StorageUnitDrillSelect.tsx
index ea36ddfea1..9ff08e04f7 100644
--- a/apps/erp/app/components/Form/StorageUnitDrillSelect.tsx
+++ b/apps/erp/app/components/Form/StorageUnitDrillSelect.tsx
@@ -15,14 +15,24 @@ import {
FormErrorMessage,
FormHelperText,
FormLabel,
+ HStack,
+ IconButton,
Input,
Popover,
PopoverContent,
PopoverTrigger,
- useDisclosure
+ useDisclosure,
+ VStack
} from "@carbon/react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { LuChevronDown, LuChevronRight, LuMapPin, LuX } from "react-icons/lu";
+import {
+ LuChevronDown,
+ LuChevronRight,
+ LuMapPin,
+ LuPlus,
+ LuSettings2,
+ LuX
+} from "react-icons/lu";
import { useFetcher } from "react-router";
import StorageUnitForm from "~/modules/inventory/ui/StorageUnits/StorageUnitForm";
import { path } from "~/utils/path";
@@ -411,6 +421,7 @@ export function useExcludedDescendantIds(rootId?: string): Set<string> {
type StorageUnitDrillSelectFieldProps = {
name: string;
label?: string;
+ inline?: boolean;
helperText?: string;
locationId: string | null | undefined;
isReadOnly?: boolean;
@@ -430,6 +441,7 @@ type StorageUnitDrillSelectFieldProps = {
export function StorageUnitDrillSelectField({
name,
label,
+ inline = false,
helperText,
locationId,
isReadOnly,
@@ -442,6 +454,35 @@ export function StorageUnitDrillSelectField({
}: StorageUnitDrillSelectFieldProps) {
const { error, getInputProps, isOptional: fieldIsOptional } = useField(name);
const [value, setValue] = useControlField<string | undefined>(name);
+ const [inlineMode, setInlineMode] = useState(inline);
+ const rows = useStorageUnitsTree(locationId);
+ const displayName = rows.find((r) => r.id === value)?.name ?? "";
+
+ if (inlineMode) {
+ return (
+ <VStack spacing={0}>
+ {label && (
+ <span className="text-xs text-muted-foreground">{label}</span>
+ )}
+ <input type="hidden" name={name} value={value ?? ""} />
+ <HStack spacing={0} className="w-full justify-between">
+ {displayName && (
+ <span className="flex-grow text-sm line-clamp-1">
+ {displayName}
+ </span>
+ )}
+ <IconButton
+ icon={displayName ? <LuSettings2 /> : <LuPlus />}
+ aria-label={displayName ? "Edit" : "Add"}
+ size="sm"
+ variant="secondary"
+ isDisabled={isReadOnly}
+ onClick={() => setInlineMode(false)}
+ />
+ </HStack>
+ </VStack>
+ );
+ }
return (
<FormControl isInvalid={!!error}>
@@ -450,7 +491,6 @@ export function StorageUnitDrillSelectField({
{label}
</FormLabel>
)}
- {/* Hidden input so the form serialises the chosen id on submit. */}
<input
{...getInputProps({ id: name, type: "hidden" })}
name={name}
@@ -462,6 +502,7 @@ export function StorageUnitDrillSelectField({
onChange={(next, row) => {
setValue(next || undefined);
onChange?.(next ? (row ?? null) : null);
+ if (inline) setInlineMode(true);
}}
isReadOnly={isReadOnly}
allowCreate={allowCreate}
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
index a98978f2ee..16569d1f14 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
@@ -165,6 +165,7 @@ export type Operation = z.infer<typeof jobOperationValidator> & {
status: JobOperation["status"];
tags: string[] | null;
workInstruction: JSONContent | null;
+ reworkId: string | null;
};
type ItemWithData = Item & {
@@ -219,9 +220,12 @@ function makeItem(
id: operation.id!,
title: (
<VStack spacing={0}>
- <h3 className="font-semibold truncate cursor-pointer">
- {operation.description}
- </h3>
+ <HStack spacing={2}>
+ <h3 className="font-semibold truncate cursor-pointer">
+ {operation.description}
+ </h3>
+ {operation.reworkId && <Badge variant="red">Rework</Badge>}
+ </HStack>
{operation.operationType === "Outside" && (
<SupplierProcessPreview
processId={operation.processId}
@@ -350,6 +354,7 @@ const initialOperation: Omit<
overheadRate: 0,
processId: "",
procedureId: "",
+ reworkId: null,
setupTime: 0,
setupUnit: "Total Minutes",
status: "Todo",
@@ -470,6 +475,7 @@ const JobBillOfProcess = ({
operationsById.set("temporary", {
...pendingOperation,
assignee: null,
+ reworkId: null,
status: "Todo",
workInstruction: {},
jobOperationTool: [],
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobDag.tsx b/apps/erp/app/modules/production/ui/Jobs/JobDag.tsx
index a434e63dcc..c1c79df149 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobDag.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobDag.tsx
@@ -98,6 +98,7 @@ function computeLayout(
status: op.status ?? "Todo",
quantityComplete: Number(op.quantityComplete ?? 0),
targetQuantity: Number(op.targetQuantity ?? 0),
+ quantityReworked: Number(op.quantityReworked ?? 0),
quantityScrapped: Number(op.quantityScrapped ?? 0),
direction
},
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobEstimatesVsActuals.tsx b/apps/erp/app/modules/production/ui/Jobs/JobEstimatesVsActuals.tsx
index a3f114de62..400a7d186e 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobEstimatesVsActuals.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobEstimatesVsActuals.tsx
@@ -1,6 +1,7 @@
import { useCarbon } from "@carbon/auth";
import type { Database } from "@carbon/database";
import {
+ Badge,
Card,
CardAction,
CardContent,
@@ -60,6 +61,7 @@ type Operation = z.infer<typeof jobOperationValidator> & {
status: JobOperation["status"];
operationQuantity: number | null;
targetQuantity: number | null;
+ reworkId: string | null;
};
type JobMaterial = NonNullable<
@@ -300,7 +302,12 @@ const JobEstimatesVsActuals = ({
<Tr key={operation.id} className="border-b border-border">
<Td className="border-r border-border px-2">
<HStack className="w-full justify-between ">
- <span>{operation.description}</span>
+ <HStack spacing={2}>
+ <span>{operation.description}</span>
+ {operation.reworkId && (
+ <Badge variant="red">Rework</Badge>
+ )}
+ </HStack>
<JobOperationStatus operation={operation} />
</HStack>
</Td>
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobOperationNode.tsx b/apps/erp/app/modules/production/ui/Jobs/JobOperationNode.tsx
index 69031c03b6..704a1acb47 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobOperationNode.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobOperationNode.tsx
@@ -8,6 +8,7 @@ type JobOperationNodeData = {
status: string;
quantityComplete: number;
targetQuantity: number;
+ quantityReworked: number;
quantityScrapped: number;
direction: "LR" | "TB";
};
@@ -49,10 +50,14 @@ function JobOperationNodeImpl({ data }: NodeProps) {
{d.description}
</div>
<BarProgress
+ segments={[
+ { value: d.quantityComplete, className: "bg-emerald-500" },
+ { value: d.quantityReworked, className: "bg-yellow-500" },
+ { value: d.quantityScrapped, className: "bg-red-500" }
+ ]}
progress={d.quantityComplete}
max={d.targetQuantity || 1}
value={`${d.quantityComplete}/${d.targetQuantity}`}
- activeClassName={colors.bar}
className="mt-1"
/>
{d.quantityScrapped > 0 && (
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobProperties.tsx b/apps/erp/app/modules/production/ui/Jobs/JobProperties.tsx
index 27031198ca..2789593a26 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobProperties.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobProperties.tsx
@@ -283,14 +283,16 @@ const JobProperties = () => {
}}
</Await>
</Suspense>
+ </VStack>
- <span className="text-xs text-muted-foreground">
- <Trans>Target</Trans>
- </span>
- {routeData?.job?.customerId &&
- routeData?.job?.salesOrderId &&
- routeData?.job?.salesOrderLineId ? (
- <HStack className="group" spacing={1}>
+ {routeData?.job?.customerId &&
+ routeData?.job?.salesOrderId &&
+ routeData?.job?.salesOrderLineId ? (
+ <VStack spacing={0}>
+ <span className="text-xs text-muted-foreground">
+ <Trans>Target</Trans>
+ </span>
+ <HStack className="group w-full justify-between" spacing={0}>
<Hyperlink
to={path.to.salesOrderLine(
routeData.job.salesOrderId,
@@ -312,29 +314,29 @@ const JobProperties = () => {
Unlink
</Button>
</HStack>
- ) : (
- <ValidatedForm
- defaultValues={{
- storageUnitId: routeData?.job?.storageUnitId ?? undefined
+ </VStack>
+ ) : (
+ <ValidatedForm
+ defaultValues={{
+ storageUnitId: routeData?.job?.storageUnitId ?? undefined
+ }}
+ validator={z.object({
+ storageUnitId: zfd.text(z.string().optional())
+ })}
+ className="w-full"
+ >
+ <StorageUnit
+ label={t`Target`}
+ name="storageUnitId"
+ inline
+ locationId={routeData?.job?.locationId ?? undefined}
+ isReadOnly={isDisabled}
+ onChange={(value) => {
+ onUpdate("storageUnitId", value?.id ?? null);
}}
- validator={z.object({
- storageUnitId: zfd.text(z.string().optional())
- })}
- className="w-full"
- >
- <StorageUnit
- label=""
- name="storageUnitId"
- inline
- locationId={routeData?.job?.locationId ?? undefined}
- isReadOnly={isDisabled}
- onChange={(value) => {
- onUpdate("storageUnitId", value?.id ?? null);
- }}
- />
- </ValidatedForm>
- )}
- </VStack>
+ />
+ </ValidatedForm>
+ )}
<Assignee
id={jobId}
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx
index ddac96886a..2ed4fd1b90 100644
--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx
@@ -1,5 +1,6 @@
import { ValidatedForm } from "@carbon/form";
import {
+ Badge,
BarProgress,
Card,
CardContent,
@@ -248,6 +249,18 @@ export function ItemCard({ item, isOverlay, progressByItemId }: ItemCardProps) {
Number(item.targetQuantity ?? item.quantity) > 0 && (
<HStack>
<BarProgress
+ segments={[
+ {
+ value: item.quantityCompleted ?? 0,
+ className: "bg-emerald-500"
+ },
+ {
+ value: item.quantityReworked ?? 0,
+ className: "bg-yellow-500"
+ },
+ { value: item.quantityScrapped ?? 0, className: "bg-red-500" }
+ ]}
+ max={(item.targetQuantity ?? item.quantity) || 1}
progress={
item.quantityCompleted &&
(item.targetQuantity ?? item.quantity)
@@ -275,6 +288,7 @@ export function ItemCard({ item, isOverlay, progressByItemId }: ItemCardProps) {
<HStack className="justify-start space-x-2">
<LuCirclePlay className="text-muted-foreground" />
<span className="text-sm line-clamp-1">{item.title}</span>
+ {item.reworkId && <Badge variant="red">Rework</Badge>}
</HStack>
{displaySettings.showDescription && item.description && (
<HStack className="justify-start space-x-2">
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/types.ts b/apps/erp/app/modules/production/ui/Schedule/Kanban/types.ts
index 80e0bf0a2a..4016992150 100644
--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/types.ts
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/types.ts
@@ -62,9 +62,11 @@ const baseItemValidator = z.object({
link: z.string().optional(),
priority: z.number(),
progress: z.number().optional(), // miliseconds
+ reworkId: z.string().nullable().optional(),
targetQuantity: z.number().optional(),
quantity: z.number().optional(),
quantityCompleted: z.number().optional(),
+ quantityReworked: z.number().optional(),
quantityScrapped: z.number().optional(),
salesOrderId: z.string().optional(),
salesOrderLineId: z.string().optional(),
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineJobs.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineJobs.tsx
index c82036f2a3..8c4899e1e5 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineJobs.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderLineJobs.tsx
@@ -477,6 +477,25 @@ function JobDetails({ job }: { job: Job }) {
) : (
<div className="py-2 w-full">
<BarProgress
+ segments={[
+ {
+ value: operation.quantityComplete ?? 0,
+ className: "bg-emerald-500"
+ },
+ {
+ value: operation.quantityReworked ?? 0,
+ className: "bg-yellow-500"
+ },
+ {
+ value: operation.quantityScrapped ?? 0,
+ className: "bg-red-500"
+ }
+ ]}
+ max={
+ (operation.targetQuantity ??
+ operation.operationQuantity) ||
+ 1
+ }
progress={Math.min(
((operation.quantityComplete ?? 0) /
(operation.targetQuantity ??
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 8ffbdbef0a..ac1fe4ea50 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-05-29T14:16:09.146Z",
+ "generated": "2026-05-31T04:59:48.395Z",
"totalTools": 1083,
"modules": 15,
"tools": [
diff --git a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx
index 2e745af4c7..8cbeb98156 100644
--- a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx
@@ -120,15 +120,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
];
- if (validation.data.jobOperationId) {
- promises.push(
- recalculateJobOperationDependencies(serviceRole, {
- jobId,
- companyId,
- userId
- })
- );
- }
+ promises.push(
+ recalculateJobOperationDependencies(serviceRole, {
+ jobId,
+ companyId,
+ userId
+ })
+ );
const [recalculateResult, recalculateDependencies] =
await Promise.all(promises);
diff --git a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx b/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
index b20a0aa197..faff965798 100644
--- a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
@@ -434,22 +434,8 @@ export async function action({ request }: ActionFunctionArgs) {
}
if (allSupplyForecasts.length > 0) {
- // Group supply forecasts by unique key to avoid duplicate conflicts
- const forecastMap = new Map<string, (typeof allSupplyForecasts)[0]>();
-
- for (const forecast of allSupplyForecasts) {
- const key = `${forecast.itemId}-${forecast.locationId}-${forecast.periodId}`;
- const existing = forecastMap.get(key);
-
- if (existing) {
- // Combine quantities for the same key
- existing.forecastQuantity += forecast.forecastQuantity;
- } else {
- forecastMap.set(key, { ...forecast });
- }
- }
-
- const uniqueSupplyForecasts = Array.from(forecastMap.values());
+ const uniqueSupplyForecasts =
+ deduplicateForecasts(allSupplyForecasts);
const insertForecasts = await client
.from("supplyForecast")
@@ -519,3 +505,24 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
}
+
+function deduplicateForecasts<
+ T extends {
+ itemId: string;
+ locationId: string;
+ periodId: string;
+ forecastQuantity: number;
+ }
+>(forecasts: T[]): T[] {
+ const map = new Map<string, T>();
+ for (const forecast of forecasts) {
+ const key = `${forecast.itemId}-${forecast.locationId}-${forecast.periodId}`;
+ const existing = map.get(key);
+ if (existing) {
+ existing.forecastQuantity += forecast.forecastQuantity;
+ } else {
+ map.set(key, { ...forecast });
+ }
+ }
+ return Array.from(map.values());
+}
diff --git a/apps/erp/app/routes/x+/schedule+/operations.tsx b/apps/erp/app/routes/x+/schedule+/operations.tsx
index b618769739..c55a2a6492 100644
--- a/apps/erp/app/routes/x+/schedule+/operations.tsx
+++ b/apps/erp/app/routes/x+/schedule+/operations.tsx
@@ -268,7 +268,9 @@ export async function loader({ request }: LoaderFunctionArgs) {
targetQuantity: op.targetQuantity,
quantity: op.operationQuantity,
quantityCompleted: op.quantityComplete,
+ quantityReworked: op.quantityReworked,
quantityScrapped: op.quantityScrapped,
+ reworkId: op.reworkId,
salesOrderReadableId: op.salesOrderReadableId,
salesOrderId: op.salesOrderId,
salesOrderLineId: op.salesOrderLineId,
diff --git a/apps/mes/app/components/JobDag/JobDag.tsx b/apps/mes/app/components/JobDag/JobDag.tsx
index 565a6c781c..fe5287c394 100644
--- a/apps/mes/app/components/JobDag/JobDag.tsx
+++ b/apps/mes/app/components/JobDag/JobDag.tsx
@@ -53,7 +53,9 @@ type Operation = {
status: string | null;
quantityComplete: number | null;
targetQuantity: number | null;
+ quantityReworked: number | null;
quantityScrapped: number | null;
+ reworkId: string | null;
jobMakeMethod: {
item: { readableIdWithRevision: string | null } | null;
} | null;
@@ -110,7 +112,9 @@ function computeLayout(
status: op.status ?? "Todo",
quantityComplete: Number(op.quantityComplete ?? 0),
targetQuantity: Number(op.targetQuantity ?? 0),
+ quantityReworked: Number(op.quantityReworked ?? 0),
quantityScrapped: Number(op.quantityScrapped ?? 0),
+ isRework: !!op.reworkId,
direction
},
sourcePosition: isHorizontal ? Position.Right : Position.Bottom,
diff --git a/apps/mes/app/components/JobDag/JobOperationNode.tsx b/apps/mes/app/components/JobDag/JobOperationNode.tsx
index 80009255a4..657ddbfba3 100644
--- a/apps/mes/app/components/JobDag/JobOperationNode.tsx
+++ b/apps/mes/app/components/JobDag/JobOperationNode.tsx
@@ -11,7 +11,9 @@ type JobOperationNodeData = {
status: string;
quantityComplete: number;
targetQuantity: number;
+ quantityReworked: number;
quantityScrapped: number;
+ isRework: boolean;
direction: "LR" | "TB";
};
@@ -55,14 +57,25 @@ function JobOperationNodeImpl({ data }: NodeProps) {
{d.itemId}
</div>
)}
- <div className="truncate text-sm font-medium leading-tight">
- {d.description}
+ <div className="flex items-center gap-1.5">
+ <span className="truncate text-sm font-medium leading-tight">
+ {d.description}
+ </span>
+ {d.isRework && (
+ <span className="shrink-0 text-[10px] font-semibold text-red-600 bg-red-100 rounded px-1">
+ Rework
+ </span>
+ )}
</div>
<BarProgress
+ segments={[
+ { value: d.quantityComplete, className: "bg-emerald-500" },
+ { value: d.quantityReworked, className: "bg-yellow-500" },
+ { value: d.quantityScrapped, className: "bg-red-500" }
+ ]}
progress={d.quantityComplete}
max={d.targetQuantity || 1}
value={`${d.quantityComplete}/${d.targetQuantity}`}
- activeClassName={colors.bar}
className="mt-1"
/>
{d.quantityScrapped > 0 && (
diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsx
index 283813b4ac..b510c2b8de 100644
--- a/apps/mes/app/components/JobOperation/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx
@@ -601,9 +601,12 @@ export const JobOperation = ({
<ItemThumbnail thumbnailPath={thumbnailPath} size="xl" />
)}
<div className="flex flex-col flex-grow">
- <Heading size="h3" className="line-clamp-1">
- {operation.description}
- </Heading>
+ <HStack spacing={2}>
+ <Heading size="h3" className="line-clamp-1">
+ {operation.description}
+ </Heading>
+ {operation.reworkId && <Badge variant="red">Rework</Badge>}
+ </HStack>
<p className="text-muted-foreground line-clamp-1">
{operation.itemDescription}{" "}
</p>
@@ -2223,12 +2226,21 @@ export const JobOperation = ({
{operation.quantityComplete}/{operation.targetQuantity}
</span>
<BarProgress
- activeClassName={
- operation.operationStatus === "Paused" &&
- operation.quantityComplete < operation.targetQuantity
- ? "bg-yellow-500"
- : "bg-emerald-500"
- }
+ segments={[
+ {
+ value: operation.quantityComplete,
+ className: "bg-emerald-500"
+ },
+ {
+ value: operation.quantityReworked ?? 0,
+ className: "bg-yellow-500"
+ },
+ {
+ value: operation.quantityScrapped ?? 0,
+ className: "bg-red-500"
+ }
+ ]}
+ max={operation.targetQuantity || 1}
progress={
(operation.quantityComplete / operation.targetQuantity) *
100
@@ -2333,6 +2345,9 @@ export const JobOperation = ({
jobId={job.id!}
isOpen={reworkModal.isOpen}
onClose={reworkModal.onClose}
+ trackedEntities={trackedEntities}
+ parentIsSerial={parentIsSerial}
+ parentIsBatch={parentIsBatch}
/>
)}
{scrapModal.isOpen && (
diff --git a/apps/mes/app/components/JobOperation/components/ReworkModal.tsx b/apps/mes/app/components/JobOperation/components/ReworkModal.tsx
index a73f1510e8..bea144ca36 100644
--- a/apps/mes/app/components/JobOperation/components/ReworkModal.tsx
+++ b/apps/mes/app/components/JobOperation/components/ReworkModal.tsx
@@ -1,4 +1,5 @@
import type { Result } from "@carbon/auth";
+import type { Database } from "@carbon/database";
import {
Hidden,
NumberControlled,
@@ -8,7 +9,9 @@ import {
} from "@carbon/form";
import {
Button,
+ Checkbox,
HStack,
+ Input,
Modal,
ModalBody,
ModalContent,
@@ -20,7 +23,7 @@ import {
VStack
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
-import { useEffect, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import { useFetcher } from "react-router";
import { triggerReworkValidator } from "~/services/models";
import type { OperationWithDetails } from "~/services/types";
@@ -32,42 +35,126 @@ type UpstreamOperation = {
description: string | null;
order: number;
status: string;
+ jobMakeMethod: {
+ item: { name: string | null } | null;
+ } | null;
};
+type TrackedEntity = Database["public"]["Tables"]["trackedEntity"]["Row"];
+
export function ReworkModal({
operation,
jobId,
isOpen,
- onClose
+ onClose,
+ trackedEntities = [],
+ parentIsSerial,
+ parentIsBatch
}: {
operation: OperationWithDetails;
jobId: string;
isOpen: boolean;
onClose: () => void;
+ trackedEntities?: TrackedEntity[];
+ parentIsSerial?: boolean;
+ parentIsBatch?: boolean;
}) {
const { t } = useLingui();
const fetcher = useFetcher<Result>();
const targetsFetcher = useFetcher<{
operations: UpstreamOperation[];
}>();
- const [quantity, setQuantity] = useState(1);
+
+ const maxQuantity = operation.operationQuantity ?? 0;
+ const defaultQuantity = Math.max(
+ maxQuantity -
+ (operation.quantityComplete ?? 0) -
+ (operation.quantityScrapped ?? 0),
+ 1
+ );
+ const [quantity, setQuantity] = useState(defaultQuantity);
+ const [selectedEntityIds, setSelectedEntityIds] = useState<Set<string>>(
+ new Set()
+ );
+ const [scanInput, setScanInput] = useState("");
+ const [selectedBatchId, setSelectedBatchId] = useState<string>("");
const targets = targetsFetcher.data?.operations ?? [];
useEffect(() => {
if (isOpen) {
targetsFetcher.load(path.to.reworkTargets(operation.id));
+ setSelectedEntityIds(
+ parentIsSerial && trackedEntities.length === 1
+ ? new Set([trackedEntities[0].id])
+ : new Set()
+ );
+ setScanInput("");
+ setSelectedBatchId(
+ parentIsBatch && trackedEntities.length === 1
+ ? trackedEntities[0].id
+ : ""
+ );
}
- // biome-ignore lint/correctness/useExhaustiveDependencies: ignore
- }, [isOpen]);
+ }, [
+ isOpen,
+ operation.id,
+ parentIsSerial,
+ parentIsBatch,
+ trackedEntities,
+ targetsFetcher.load
+ ]);
useEffect(() => {
if (fetcher.state === "idle" && fetcher.data?.success) {
toast.success(t`Rework created successfully`);
onClose();
}
- // biome-ignore lint/correctness/useExhaustiveDependencies: ignore
- }, [fetcher.state, fetcher.data]);
+ }, [fetcher.state, fetcher.data, onClose, t]);
+
+ const filteredEntities = useMemo(() => {
+ if (!scanInput) return trackedEntities;
+ const search = scanInput.toLowerCase();
+ return trackedEntities.filter(
+ (e) =>
+ e.id.toLowerCase().includes(search) ||
+ e.readableId?.toLowerCase().includes(search)
+ );
+ }, [trackedEntities, scanInput]);
+
+ const toggleEntity = (id: string) => {
+ setSelectedEntityIds((prev) => {
+ const next = new Set(prev);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ return next;
+ });
+ };
+
+ const handleScanKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ const match = trackedEntities.find(
+ (entity) => entity.id === scanInput || entity.readableId === scanInput
+ );
+ if (match) {
+ setSelectedEntityIds((prev) => new Set(prev).add(match.id));
+ setScanInput("");
+ }
+ }
+ };
+
+ const serialQuantity = selectedEntityIds.size;
+ const selectedBatch = trackedEntities.find((e) => e.id === selectedBatchId);
+ const batchMaxQuantity = selectedBatch
+ ? Number(selectedBatch.quantity)
+ : maxQuantity;
+
+ const trackedEntityIdsValue = parentIsSerial
+ ? JSON.stringify(Array.from(selectedEntityIds))
+ : parentIsBatch && selectedBatchId
+ ? JSON.stringify([selectedBatchId])
+ : undefined;
if (!isOpen) return null;
@@ -88,7 +175,7 @@ export function ReworkModal({
triggeredAtJobOperationId: operation.id,
targetJobOperationId: "",
reason: "",
- quantity: 1
+ quantity: defaultQuantity
}}
fetcher={fetcher}
>
@@ -106,24 +193,123 @@ export function ReworkModal({
<ModalBody>
<Hidden name="jobId" value={jobId} />
<Hidden name="triggeredAtJobOperationId" value={operation.id} />
- <VStack spacing={4}>
+ {trackedEntityIdsValue && (
+ <Hidden name="trackedEntityIds" value={trackedEntityIdsValue} />
+ )}
+ <VStack spacing={0}>
<Select
name="targetJobOperationId"
label={t`Go back to operation`}
size="lg"
options={targets.map((op) => ({
value: op.id,
- label: op.description || op.processId
+ label: op.jobMakeMethod?.item?.name ? (
+ <span>
+ {op.description || op.processId}
+ <span className="text-muted-foreground text-xs ml-2">
+ {op.jobMakeMethod.item.name}
+ </span>
+ </span>
+ ) : (
+ op.description || op.processId
+ )
}))}
/>
- <NumberControlled
- name="quantity"
- label={t`Quantity`}
- value={quantity}
- onChange={setQuantity}
- minValue={1}
- size="lg"
- />
+
+ {parentIsSerial ? (
+ <>
+ <Hidden name="quantity" value={String(serialQuantity || 1)} />
+ <div className="w-full mb-2 space-y-2">
+ <label className="text-xs font-medium text-muted-foreground">
+ <Trans>Serial numbers</Trans>
+ {serialQuantity > 0 && (
+ <span className="ml-1.5">
+ ({serialQuantity} selected)
+ </span>
+ )}
+ </label>
+ <Input
+ value={scanInput}
+ onChange={(e) => setScanInput(e.target.value)}
+ onKeyDown={handleScanKeyDown}
+ placeholder={t`Scan or search serial number...`}
+ size="lg"
+ />
+ <div className="max-h-48 overflow-y-auto rounded-lg border">
+ {filteredEntities.length === 0 ? (
+ <div className="py-6 text-center text-sm text-muted-foreground">
+ <Trans>No serial numbers found</Trans>
+ </div>
+ ) : (
+ filteredEntities.map((entity) => (
+ <label
+ key={entity.id}
+ className="flex items-center gap-3 px-3 py-2.5 cursor-pointer transition-colors hover:bg-muted/50 border-b last:border-b-0"
+ >
+ <Checkbox
+ isChecked={selectedEntityIds.has(entity.id)}
+ onCheckedChange={() => toggleEntity(entity.id)}
+ aria-label={entity.readableId || entity.id}
+ />
+ <div className="flex flex-col min-w-0">
+ {entity.readableId ? (
+ <>
+ <span className="text-sm font-medium truncate">
+ {entity.readableId}
+ </span>
+ <span className="text-xs text-muted-foreground font-mono truncate">
+ {entity.id}
+ </span>
+ </>
+ ) : (
+ <span className="text-xs text-muted-foreground font-mono truncate">
+ {entity.id}
+ </span>
+ )}
+ </div>
+ </label>
+ ))
+ )}
+ </div>
+ </div>
+ </>
+ ) : parentIsBatch ? (
+ <>
+ <Select
+ name="_batchSelect"
+ label={t`Batch`}
+ size="lg"
+ options={trackedEntities.map((entity) => ({
+ value: entity.id,
+ label: `${entity.readableId || entity.id} (qty: ${entity.quantity})`
+ }))}
+ onChange={(option) => {
+ setSelectedBatchId(option?.value ?? "");
+ setQuantity(1);
+ }}
+ />
+ <NumberControlled
+ name="quantity"
+ label={t`Quantity`}
+ value={quantity}
+ onChange={setQuantity}
+ minValue={1}
+ maxValue={batchMaxQuantity}
+ size="lg"
+ />
+ </>
+ ) : (
+ <NumberControlled
+ name="quantity"
+ label={t`Quantity`}
+ value={quantity}
+ onChange={setQuantity}
+ minValue={1}
+ maxValue={maxQuantity}
+ size="lg"
+ />
+ )}
+
<TextArea
name="reason"
label={t`Reason for rework`}
@@ -140,7 +326,11 @@ export function ReworkModal({
<Button
type="submit"
size="lg"
- isDisabled={fetcher.state !== "idle"}
+ isDisabled={
+ fetcher.state !== "idle" ||
+ (parentIsSerial && serialQuantity === 0)
+ }
+ isLoading={fetcher.state !== "idle"}
>
<Trans>Create Rework</Trans>
</Button>
diff --git a/apps/mes/app/components/JobOperation/components/SerialSelectorModal.tsx b/apps/mes/app/components/JobOperation/components/SerialSelectorModal.tsx
index 484f4be39d..1d9784ce51 100644
--- a/apps/mes/app/components/JobOperation/components/SerialSelectorModal.tsx
+++ b/apps/mes/app/components/JobOperation/components/SerialSelectorModal.tsx
@@ -83,11 +83,24 @@ export function SerialSelectorModal({
key={entity.id}
className="w-full justify-between p-4 border rounded-md"
>
- <VStack spacing={1} className="w-full items-start">
- <p className="text-sm">{entity.id}</p>
+ <VStack spacing={0} className="w-full items-start">
+ {entity.readableId ? (
+ <>
+ <p className="text-sm font-medium">
+ {entity.readableId}
+ </p>
+ <p className="text-xs text-muted-foreground font-mono">
+ {entity.id}
+ </p>
+ </>
+ ) : (
+ <p className="text-xs text-muted-foreground font-mono">
+ {entity.id}
+ </p>
+ )}
</VStack>
<Button
- size="sm"
+ size="lg"
variant="secondary"
onClick={() => onSelect(entity)}
>
@@ -105,11 +118,14 @@ export function SerialSelectorModal({
<InputGroup>
<Input
autoFocus
+ size="lg"
placeholder={t`Scan or enter serial number`}
onKeyDown={(e) => {
if (e.key === "Enter") {
+ const val = e.currentTarget.value;
const entity = availableEntities.find(
- (entity) => entity.id === e.currentTarget.value
+ (entity) =>
+ entity.id === val || entity.readableId === val
);
if (entity) {
onSelect(entity);
@@ -122,7 +138,8 @@ export function SerialSelectorModal({
<InputRightElement>
{serial &&
(availableEntities.some(
- (entity) => entity.id === serial
+ (entity) =>
+ entity.id === serial || entity.readableId === serial
) ? (
<LuCheck className="text-green-500" />
) : (
@@ -135,7 +152,7 @@ export function SerialSelectorModal({
</Tabs>
</ModalBody>
<ModalFooter>
- <Button variant="secondary" onClick={onCancel}>
+ <Button variant="secondary" size="lg" onClick={onCancel}>
<Trans>Cancel</Trans>
</Button>
</ModalFooter>
diff --git a/apps/mes/app/components/Kanban/components/ItemCard.tsx b/apps/mes/app/components/Kanban/components/ItemCard.tsx
index fc7cf02a9d..b43557920f 100644
--- a/apps/mes/app/components/Kanban/components/ItemCard.tsx
+++ b/apps/mes/app/components/Kanban/components/ItemCard.tsx
@@ -126,11 +126,11 @@ export function ItemCard({
{item.itemReadableId}
</span>
)}
- <span className="mr-auto font-semibold line-clamp-2 leading-tight">
+ <span className="mr-auto font-semibold line-clamp-2 leading-tight text-foreground">
{item.itemDescription || item.itemReadableId}
</span>
</div>
- <Heading size="h4" className="text-muted-foreground/70">
+ <Heading size="h4" className="text-foreground">
{item.targetQuantity}
</Heading>
</div>
@@ -166,6 +166,21 @@ export function ItemCard({
Number(item.quantity) > 0 && (
<HStack className="mt-2">
<BarProgress
+ segments={[
+ {
+ value: item.quantityCompleted ?? 0,
+ className: "bg-emerald-500"
+ },
+ {
+ value: item.quantityReworked ?? 0,
+ className: "bg-yellow-500"
+ },
+ {
+ value: item.quantityScrapped ?? 0,
+ className: "bg-red-500"
+ }
+ ]}
+ max={item.targetQuantity || 1}
progress={
item.quantityCompleted && item.targetQuantity
? (item.quantityCompleted / item.targetQuantity) * 100
@@ -190,6 +205,7 @@ export function ItemCard({
<HStack className="justify-start space-x-2">
<LuCirclePlay className="text-muted-foreground" />
<span className="text-sm line-clamp-1">{item.title}</span>
+ {item.reworkId && <Badge variant="red">Rework</Badge>}
</HStack>
{showDescription && item.description && (
diff --git a/apps/mes/app/components/Kanban/types.ts b/apps/mes/app/components/Kanban/types.ts
index 98d8d111e5..450e4d1438 100644
--- a/apps/mes/app/components/Kanban/types.ts
+++ b/apps/mes/app/components/Kanban/types.ts
@@ -56,10 +56,12 @@ const itemValidator = z.object({
progress: z.number().optional(), // miliseconds
quantity: z.number().optional(),
quantityCompleted: z.number().optional(),
+ quantityReworked: z.number().optional(),
quantityScrapped: z.number().optional(),
setupDuration: z.number().optional(), // milliseconds
laborDuration: z.number().optional(), // milliseconds
machineDuration: z.number().optional(), // milliseconds
+ reworkId: z.string().nullable().optional(),
status: z.enum(jobOperationStatus).optional(),
salesOrderReadableId: z.string().optional(),
salesOrderId: z.string().optional(),
diff --git a/apps/mes/app/routes/x+/complete.tsx b/apps/mes/app/routes/x+/complete.tsx
index 70e4f6f452..58bb4c37c2 100644
--- a/apps/mes/app/routes/x+/complete.tsx
+++ b/apps/mes/app/routes/x+/complete.tsx
@@ -28,18 +28,11 @@ export async function action({ request }: ActionFunctionArgs) {
const serviceRole = await getCarbonServiceRole();
// Get current job operation and production quantities to check if operation will be finished
- const [jobOperation, productionQuantities] = await Promise.all([
- serviceRole
- .from("jobOperation")
- .select("*")
- .eq("id", validation.data.jobOperationId)
- .maybeSingle(),
- serviceRole
- .from("productionQuantity")
- .select("*")
- .eq("type", "Production")
- .eq("jobOperationId", validation.data.jobOperationId)
- ]);
+ const jobOperation = await serviceRole
+ .from("jobOperation")
+ .select("*")
+ .eq("id", validation.data.jobOperationId)
+ .maybeSingle();
if (jobOperation.error || !jobOperation.data) {
return data(
@@ -51,12 +44,14 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
- const currentQuantity =
- productionQuantities.data?.reduce((acc, curr) => acc + curr.quantity, 0) ??
- 0;
+ const totalAccountedQuantity =
+ (jobOperation.data.quantityComplete ?? 0) +
+ (jobOperation.data.quantityReworked ?? 0) +
+ (jobOperation.data.quantityScrapped ?? 0) +
+ validation.data.quantity;
const willBeFinished =
- validation.data.quantity + currentQuantity >=
+ totalAccountedQuantity >=
(jobOperation.data.targetQuantity ??
jobOperation.data.operationQuantity ??
0);
@@ -71,6 +66,16 @@ export async function action({ request }: ActionFunctionArgs) {
}
});
+ if (response.error) {
+ return data(
+ {},
+ await flash(request, {
+ ...error(response.error, "Failed to complete job operation"),
+ flash: "error"
+ })
+ );
+ }
+
const trackedEntityId = response.data?.newTrackedEntityId;
if (willBeFinished) {
diff --git a/apps/mes/app/routes/x+/operations.tsx b/apps/mes/app/routes/x+/operations.tsx
index cf8a43d160..f8467d36f7 100644
--- a/apps/mes/app/routes/x+/operations.tsx
+++ b/apps/mes/app/routes/x+/operations.tsx
@@ -264,7 +264,9 @@ export async function loader({ context, request }: LoaderFunctionArgs) {
thumbnailPath: op.thumbnailPath,
quantity: op.operationQuantity,
quantityCompleted: op.quantityComplete,
+ quantityReworked: op.quantityReworked,
quantityScrapped: op.quantityScrapped,
+ reworkId: op.reworkId,
setupDuration: operation.setupDuration,
laborDuration: operation.laborDuration,
machineDuration: operation.machineDuration
diff --git a/apps/mes/app/routes/x+/trigger-rework.tsx b/apps/mes/app/routes/x+/trigger-rework.tsx
index e6357ebc54..c302a39995 100644
--- a/apps/mes/app/routes/x+/trigger-rework.tsx
+++ b/apps/mes/app/routes/x+/trigger-rework.tsx
@@ -20,9 +20,16 @@ export async function action({ request }: ActionFunctionArgs) {
const serviceRole = getCarbonServiceRole();
+ const { trackedEntityIds: trackedEntityIdsJson, ...reworkData } =
+ validation.data;
+ const trackedEntityIds = trackedEntityIdsJson
+ ? JSON.parse(trackedEntityIdsJson)
+ : undefined;
+
const result = await serviceRole.functions.invoke("trigger-rework", {
body: {
- ...validation.data,
+ ...reworkData,
+ trackedEntityIds,
companyId,
userId
}
diff --git a/apps/mes/app/services/models.ts b/apps/mes/app/services/models.ts
index b2086ff00a..f8f222cdbd 100644
--- a/apps/mes/app/services/models.ts
+++ b/apps/mes/app/services/models.ts
@@ -173,7 +173,7 @@ export const triggerReworkValidator = z.object({
quantity: zfd.numeric(
z.number().positive({ message: "Quantity must be greater than 0" })
),
- trackedEntityId: zfd.text(z.string().optional())
+ trackedEntityIds: zfd.text(z.string().optional())
});
export const maintenanceDispatchValidator = z.object({
diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.ts
index 69dc770914..00b72cf03b 100644
--- a/apps/mes/app/services/operations.service.ts
+++ b/apps/mes/app/services/operations.service.ts
@@ -125,9 +125,10 @@ export async function getUpstreamOperations(
return client
.from("jobOperation")
- .select("id, processId, description, order, status, reworkId")
+ .select(
+ "id, processId, description, order, status, reworkId, jobMakeMethod(item(name))"
+ )
.in("id", Array.from(ancestors))
- .is("reworkId", null)
.order("order", { ascending: true });
}
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 03961351eb..0b9013a60e 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -16125,6 +16125,7 @@ export type Database = {
quantityComplete: number | null
quantityReworked: number | null
quantityScrapped: number | null
+ reworkId: string | null
setupTime: number
setupUnit: Database["public"]["Enums"]["factor"]
startDate: string | null
@@ -16171,6 +16172,7 @@ export type Database = {
quantityComplete?: number | null
quantityReworked?: number | null
quantityScrapped?: number | null
+ reworkId?: string | null
setupTime?: number
setupUnit?: Database["public"]["Enums"]["factor"]
startDate?: string | null
@@ -16217,6 +16219,7 @@ export type Database = {
quantityComplete?: number | null
quantityReworked?: number | null
quantityScrapped?: number | null
+ reworkId?: string | null
setupTime?: number
setupUnit?: Database["public"]["Enums"]["factor"]
startDate?: string | null
@@ -51587,6 +51590,7 @@ export type Database = {
quantityComplete: number | null
quantityReworked: number | null
quantityScrapped: number | null
+ reworkId: string | null
setupTime: number | null
setupUnit: Database["public"]["Enums"]["factor"] | null
startDate: string | null
@@ -51632,6 +51636,7 @@ export type Database = {
quantityComplete?: number | null
quantityReworked?: number | null
quantityScrapped?: number | null
+ reworkId?: string | null
setupTime?: number | null
setupUnit?: Database["public"]["Enums"]["factor"] | null
startDate?: string | null
@@ -51677,6 +51682,7 @@ export type Database = {
quantityComplete?: number | null
quantityReworked?: number | null
quantityScrapped?: number | null
+ reworkId?: string | null
setupTime?: number | null
setupUnit?: Database["public"]["Enums"]["factor"] | null
startDate?: string | null
@@ -51956,6 +51962,7 @@ export type Database = {
quantityComplete: number | null
quantityReworked: number | null
quantityScrapped: number | null
+ reworkId: string | null
setupTime: number | null
setupUnit: Database["public"]["Enums"]["factor"] | null
status: Database["public"]["Enums"]["jobOperationStatus"] | null
@@ -63272,7 +63279,9 @@ export type Database = {
priority: number
processId: string
quantityComplete: number
+ quantityReworked: number
quantityScrapped: number
+ reworkId: string
salesOrderId: string
salesOrderLineId: string
salesOrderReadableId: string
@@ -63748,6 +63757,7 @@ export type Database = {
quantityComplete: number
quantityReworked: number
quantityScrapped: number
+ reworkId: string
setupTime: number
setupUnit: Database["public"]["Enums"]["factor"]
targetQuantity: number
diff --git a/packages/database/supabase/functions/lib/mrp-engine.ts b/packages/database/supabase/functions/lib/mrp-engine.ts
new file mode 100644
index 0000000000..482c52fc7d
--- /dev/null
+++ b/packages/database/supabase/functions/lib/mrp-engine.ts
@@ -0,0 +1,214 @@
+// Pure MRP engine functions shared across Supabase edge functions.
+// The same algorithm is independently available (with unit tests) at
+// packages/mrp/src/engine.ts.
+
+export type MethodType =
+ | "Make to Order"
+ | "Pull from Inventory"
+ | "Purchase to Order";
+
+export type ReplenishmentSystem = "Buy" | "Make" | "Buy and Make";
+
+export type BomChild = {
+ itemId: string;
+ quantity: number;
+ methodType: MethodType;
+};
+
+export type DemandContributor =
+ | {
+ sourceType: "Job Material";
+ jobId: string;
+ parentItemId: string;
+ quantity: number;
+ }
+ | {
+ sourceType: "Sales Order";
+ salesOrderLineId: string;
+ parentItemId: string;
+ quantity: number;
+ }
+ | {
+ sourceType: "Demand Projection";
+ demandProjectionId: string;
+ parentItemId: string;
+ quantity: number;
+ };
+
+export type BomExplosionInput = {
+ grossDemand: Map<string, number>;
+ bomByItem: Map<string, BomChild[]>;
+ replenishmentSystemByItem: Map<string, ReplenishmentSystem>;
+ leadTimeByItem: Map<string, number>;
+ periods: { id: string }[];
+ onHandByLocationItem: Map<string, number>;
+ jobSupplyByLocationPeriodItem: Map<string, number>;
+ topLevelContributors: Map<string, DemandContributor[]>;
+};
+
+export type BomExplosionOutput = {
+ grossDemand: Map<string, number>;
+ bomDerivedDemand: Map<string, number>;
+ demandContributors: Map<string, DemandContributor[]>;
+};
+
+export function splitKey(key: string): [string, string, string] {
+ const parts = key.split("-");
+ return [parts[0]!, parts[1]!, parts.slice(2).join("-")];
+}
+
+export function makeKey(
+ locationId: string,
+ periodId: string,
+ itemId: string
+): string {
+ return `${locationId}-${periodId}-${itemId}`;
+}
+
+function effectiveReplenishment(
+ repSys: ReplenishmentSystem | undefined
+): "Buy" | "Make" | undefined {
+ return repSys === "Buy and Make"
+ ? "Buy"
+ : (repSys as "Buy" | "Make" | undefined);
+}
+
+export function computeLowLevelCodes(
+ bomByItem: Map<string, BomChild[]>
+): Map<string, number> {
+ const llc = new Map<string, number>();
+
+ function assignLevel(
+ itemId: string,
+ level: number,
+ visited: Set<string>
+ ): void {
+ if (visited.has(itemId)) return;
+ visited.add(itemId);
+
+ const currentLLC = llc.get(itemId) ?? -1;
+ if (level > currentLLC) {
+ llc.set(itemId, level);
+ }
+
+ const children = bomByItem.get(itemId) ?? [];
+ for (const child of children) {
+ assignLevel(child.itemId, level + 1, new Set(visited));
+ }
+ }
+
+ for (const itemId of bomByItem.keys()) {
+ assignLevel(itemId, 0, new Set());
+ }
+
+ return llc;
+}
+
+export function explodeBom(input: BomExplosionInput): BomExplosionOutput {
+ const {
+ bomByItem,
+ replenishmentSystemByItem,
+ leadTimeByItem,
+ periods,
+ topLevelContributors,
+ } = input;
+
+ const grossDemand = new Map(input.grossDemand);
+ const onHandByLocationItem = new Map(input.onHandByLocationItem);
+ const jobSupply = input.jobSupplyByLocationPeriodItem;
+
+ const bomDerivedDemand = new Map<string, number>();
+ const demandContributors = new Map<string, DemandContributor[]>();
+
+ const llc = computeLowLevelCodes(bomByItem);
+ const maxLevel = llc.size > 0 ? Math.max(...llc.values()) : 0;
+
+ for (let level = 0; level <= maxLevel; level++) {
+ const keysAtLevel: string[] = [];
+ for (const [key, qty] of grossDemand) {
+ if (qty <= 0) continue;
+ const [, , itemId] = splitKey(key);
+ if ((llc.get(itemId) ?? 0) === level) {
+ keysAtLevel.push(key);
+ }
+ }
+
+ for (const key of keysAtLevel) {
+ const grossQty = grossDemand.get(key) ?? 0;
+ if (grossQty <= 0) continue;
+
+ const [locationId, periodId, itemId] = splitKey(key);
+ const effRepSys = effectiveReplenishment(
+ replenishmentSystemByItem.get(itemId)
+ );
+
+ const invKey = `${locationId}-${itemId}`;
+ const onHand = onHandByLocationItem.get(invKey) ?? 0;
+ const productionSupply = jobSupply.get(key) ?? 0;
+ const netRequirement = Math.max(
+ 0,
+ grossQty - Math.max(0, onHand) - productionSupply
+ );
+
+ if (onHand > 0) {
+ onHandByLocationItem.set(invKey, Math.max(0, onHand - grossQty));
+ }
+
+ if (netRequirement > 0 && effRepSys === "Make") {
+ const children = bomByItem.get(itemId) ?? [];
+ for (const child of children) {
+ const childEffRepSys = effectiveReplenishment(
+ replenishmentSystemByItem.get(child.itemId)
+ );
+
+ const isInlineProduction =
+ child.methodType === "Make to Order" && childEffRepSys === "Make";
+
+ const childQty = child.quantity * netRequirement;
+ const childLeadTimeDays = leadTimeByItem.get(child.itemId) ?? 7;
+ const childLeadTimeWeeks = Math.ceil(childLeadTimeDays / 7);
+
+ const currentPeriodIndex = periods.findIndex(
+ (p) => p.id === periodId
+ );
+ const targetPeriodIndex = Math.max(
+ 0,
+ currentPeriodIndex - childLeadTimeWeeks
+ );
+ const targetPeriod = periods[targetPeriodIndex];
+
+ if (targetPeriod) {
+ const childKey = makeKey(locationId, targetPeriod.id, child.itemId);
+ grossDemand.set(
+ childKey,
+ (grossDemand.get(childKey) ?? 0) + childQty
+ );
+ if (!isInlineProduction) {
+ bomDerivedDemand.set(
+ childKey,
+ (bomDerivedDemand.get(childKey) ?? 0) + childQty
+ );
+ }
+
+ const parentContributors = [
+ ...(demandContributors.get(key) ?? []),
+ ...(topLevelContributors.get(key) ?? []),
+ ];
+ if (parentContributors.length > 0) {
+ const childContributors = demandContributors.get(childKey) ?? [];
+ for (const pc of parentContributors) {
+ childContributors.push({
+ ...pc,
+ quantity: pc.quantity * child.quantity,
+ });
+ }
+ demandContributors.set(childKey, childContributors);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return { grossDemand, bomDerivedDemand, demandContributors };
+}
diff --git a/packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts b/packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts
index ea5915ffd6..cbc2793650 100644
--- a/packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts
+++ b/packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts
@@ -164,13 +164,17 @@ export class SchedulingEngine {
}
/**
- * Create operation dependencies based on assembly structure
- * Only called in initial scheduling mode
+ * Create operation dependencies based on assembly structure.
+ * Loads ALL operations (including Done) to build the complete DAG.
*/
async createDependencies(): Promise<void> {
- if (this.mode !== "initial") {
- return;
- }
+ // Load all operations for dependency building (not just active ones)
+ const allOperations = (await this.db
+ .selectFrom("jobOperation")
+ .selectAll()
+ .where("jobId", "=", this.jobId)
+ .orderBy("order")
+ .execute()) as BaseOperation[];
// Build assembly tree
const assemblyTree = await this.assemblyHandler.buildAssemblyTree(
@@ -201,10 +205,10 @@ export class SchedulingEngine {
}
}
- // Group operations by jobMakeMethodId
+ // Group non-rework operations by jobMakeMethodId
const operationsByMethod = new Map<string, BaseOperation[]>();
- for (const op of this.operations) {
- if (op.jobMakeMethodId) {
+ for (const op of allOperations) {
+ if (op.jobMakeMethodId && !op.reworkId) {
if (!operationsByMethod.has(op.jobMakeMethodId)) {
operationsByMethod.set(op.jobMakeMethodId, []);
}
@@ -218,9 +222,9 @@ export class SchedulingEngine {
// Build operation dependencies
const allDependencies = new Map<string, Set<string>>();
- // Initialize all operations
- for (const op of this.operations) {
- if (op.id) {
+ // Initialize all non-rework operations
+ for (const op of allOperations) {
+ if (op.id && !op.reworkId) {
allDependencies.set(op.id, new Set());
}
}
@@ -237,7 +241,17 @@ export class SchedulingEngine {
// If this method has a parent, link last op to parent's consuming operation
if (methodDep.id && methodDep.parentId !== null) {
- const parentOperation = jobMakeMethodToOperationId[methodDep.id];
+ let parentOperation = jobMakeMethodToOperationId[methodDep.id];
+
+ // If no specific operation was set, default to the first operation of the parent
+ if (!parentOperation && methodDep.parentId) {
+ const parentOps = operationsByMethod.get(methodDep.parentId) ?? [];
+ const sortedParentOps = [...parentOps].sort(
+ (a, b) => (a.order ?? 0) - (b.order ?? 0)
+ );
+ parentOperation = sortedParentOps[0]?.id ?? null;
+ }
+
if (parentOperation && lastOperation?.id) {
const deps = allDependencies.get(parentOperation);
if (deps) {
@@ -258,11 +272,22 @@ export class SchedulingEngine {
}
}
- // Delete existing dependencies
- await this.db
+ // Delete existing dependencies, preserving rework operation dependencies
+ const reworkOpIds = allOperations
+ .filter((op) => op.reworkId)
+ .map((op) => op.id!);
+
+ let deleteQuery = this.db
.deleteFrom("jobOperationDependency")
- .where("jobId", "=", this.jobId)
- .execute();
+ .where("jobId", "=", this.jobId);
+
+ if (reworkOpIds.length > 0) {
+ deleteQuery = deleteQuery
+ .where("operationId", "not in", reworkOpIds)
+ .where("dependsOnId", "not in", reworkOpIds);
+ }
+
+ await deleteQuery.execute();
// Insert new dependencies
const records = dependenciesToRecords(
@@ -291,12 +316,35 @@ export class SchedulingEngine {
}
}
- // Store dependencies for date calculation
+ // Store dependencies for date calculation (non-rework edges rebuilt above)
this.dependencies = records.map((r) => ({
operationId: r.operationId,
dependsOnId: r.dependsOnId,
jobId: r.jobId,
}));
+
+ // Append rework dependency edges so rework ops are correctly scheduled
+ if (reworkOpIds.length > 0) {
+ const reworkDeps = await this.db
+ .selectFrom("jobOperationDependency")
+ .selectAll()
+ .where("jobId", "=", this.jobId)
+ .where((eb) =>
+ eb.or([
+ eb("operationId", "in", reworkOpIds),
+ eb("dependsOnId", "in", reworkOpIds),
+ ])
+ )
+ .execute();
+
+ for (const d of reworkDeps) {
+ this.dependencies.push({
+ operationId: d.operationId,
+ dependsOnId: d.dependsOnId,
+ jobId: d.jobId,
+ });
+ }
+ }
}
/**
@@ -460,12 +508,16 @@ export class SchedulingEngine {
}
/**
- * Assign materials to operations (initial scheduling only)
+ * Assign unlinked materials to the first operation of their make method
*/
async assignMaterials(): Promise<void> {
- if (this.mode !== "initial") {
- return;
- }
+ // Load all operations (including Done) to find first ops correctly
+ const allOperations = (await this.db
+ .selectFrom("jobOperation")
+ .selectAll()
+ .where("jobId", "=", this.jobId)
+ .orderBy("order")
+ .execute()) as BaseOperation[];
// Build assembly tree
const assemblyTree = await this.assemblyHandler.buildAssemblyTree(
@@ -488,10 +540,10 @@ export class SchedulingEngine {
.where("jobOperationId", "is", null)
.execute();
- // Group operations by jobMakeMethodId
+ // Group non-rework operations by jobMakeMethodId
const operationsByMethod = new Map<string, BaseOperation[]>();
- for (const op of this.operations) {
- if (op.jobMakeMethodId) {
+ for (const op of allOperations) {
+ if (op.jobMakeMethodId && !op.reworkId) {
if (!operationsByMethod.has(op.jobMakeMethodId)) {
operationsByMethod.set(op.jobMakeMethodId, []);
}
@@ -588,13 +640,11 @@ export class SchedulingEngine {
async run(): Promise<SchedulingResult> {
await this.initialize();
- if (this.mode === "initial") {
- // Assign materials BEFORE creating dependencies
- // Dependencies require jobMaterial.jobOperationId to be set
- // to link subassembly operations to parent operations
- await this.assignMaterials();
- await this.createDependencies();
- }
+ // Assign materials BEFORE creating dependencies
+ // Dependencies require jobMaterial.jobOperationId to be set
+ // to link subassembly operations to parent operations
+ await this.assignMaterials();
+ await this.createDependencies();
await this.calculateDates();
await this.selectWorkCenters();
diff --git a/packages/database/supabase/functions/lib/scheduling/types.ts b/packages/database/supabase/functions/lib/scheduling/types.ts
index 07dfa3c8bb..bcb92442e1 100644
--- a/packages/database/supabase/functions/lib/scheduling/types.ts
+++ b/packages/database/supabase/functions/lib/scheduling/types.ts
@@ -40,6 +40,7 @@ export type BaseOperation = {
processId: string | null;
setupTime?: number;
setupUnit?: FactorUnit;
+ reworkId?: string | null;
status?: JobOperationStatus;
order?: number;
workCenterId?: string | null;
diff --git a/packages/database/supabase/functions/mrp/index.ts b/packages/database/supabase/functions/mrp/index.ts
index d0fc85f864..fde8487e4a 100644
--- a/packages/database/supabase/functions/mrp/index.ts
+++ b/packages/database/supabase/functions/mrp/index.ts
@@ -7,6 +7,14 @@ import {
type CalendarDate,
} from "npm:@internationalized/date";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
+import {
+ explodeBom,
+ splitKey,
+ type BomChild,
+ type DemandContributor,
+ type MethodType,
+ type ReplenishmentSystem,
+} from "../lib/mrp-engine.ts";
import { Kysely, sql } from "npm:kysely";
import z from "npm:zod@^3.24.1";
@@ -24,15 +32,6 @@ type DemandPeriod = Omit<
"createdAt"
>;
-type MethodType = Database["public"]["Enums"]["methodType"];
-type ReplenishmentSystem = Database["public"]["Enums"]["itemReplenishmentSystem"];
-
-type BomChild = {
- itemId: string;
- quantity: number;
- methodType: MethodType;
-};
-
const payloadValidator = z.discriminatedUnion("type", [
z.object({
type: z.literal("company"),
@@ -252,13 +251,6 @@ serve(async (req: Request) => {
}
}
- // ──────────────────────────────────────────────────────────────
- // PHASE 2: Compute Low Level Codes
- // ──────────────────────────────────────────────────────────────
-
- const llc = computeLowLevelCodes(bomByItem);
- const maxLevel = llc.size > 0 ? Math.max(...llc.values()) : 0;
-
// ──────────────────────────────────────────────────────────────
// PHASE 3: Collect supply from open orders
// ──────────────────────────────────────────────────────────────
@@ -317,15 +309,6 @@ serve(async (req: Request) => {
const salesDemandByKey = new Map<string, number>();
const jobMaterialDemandByKey = new Map<string, number>();
- // Per-source attribution of BOM-derived demand. Mirrors bomDerivedDemand
- // but tracks which parent job / sales order line each chunk of quantity
- // came from. Written to demandForecastSource alongside demandForecast.
- type DemandContributor =
- | { sourceType: "Job Material"; jobId: string; parentItemId: string; quantity: number }
- | { sourceType: "Sales Order"; salesOrderLineId: string; parentItemId: string; quantity: number }
- | { sourceType: "Demand Projection"; demandProjectionId: string; parentItemId: string; quantity: number };
- const demandContributors = new Map<string, DemandContributor[]>();
-
// Top-level contributors (from sales orders and job materials) — keyed by
// grossDemand key. Used as the starting contributor set when BOM explosion
// first reaches a level-0 Make item.
@@ -425,19 +408,19 @@ serve(async (req: Request) => {
}
// ──────────────────────────────────────────────────────────────
- // PHASE 5: Level-by-level processing with inventory netting
+ // PHASE 5: Level-by-level BOM explosion with inventory netting
// ──────────────────────────────────────────────────────────────
- // On-hand inventory only (no scheduled supply — planning views
- // handle time-phased supply/demand projection). Mutable: consumed
- // as demands are netted to prevent the same stock from covering
- // multiple items.
- const onHandByLocationItem = new Map(baseInventoryByLocationItem);
-
- // BOM-derived demand only — this is what gets written to demandForecast.
- // Independent demand (sales orders, job materials) is already in demandActual
- // and must NOT be duplicated here.
- const bomDerivedDemand = new Map<string, number>();
+ const { bomDerivedDemand, demandContributors } = explodeBom({
+ grossDemand,
+ bomByItem,
+ replenishmentSystemByItem,
+ leadTimeByItem,
+ periods: periods.map((p) => ({ id: p.id ?? "" })),
+ onHandByLocationItem: new Map(baseInventoryByLocationItem),
+ jobSupplyByLocationPeriodItem,
+ topLevelContributors,
+ });
// demandForecast output: Map<"itemId-locationId-periodId", record>
const demandForecastMap = new Map<
@@ -445,109 +428,6 @@ serve(async (req: Request) => {
Database["public"]["Tables"]["demandForecast"]["Insert"]
>();
- for (let level = 0; level <= maxLevel; level++) {
- // Collect all demand keys at this level
- const keysAtLevel: string[] = [];
- for (const [key, qty] of grossDemand) {
- if (qty <= 0) continue;
- const [, , itemId] = splitKey(key);
- if ((llc.get(itemId) ?? 0) === level) {
- keysAtLevel.push(key);
- }
- }
-
- for (const key of keysAtLevel) {
- const grossQty = grossDemand.get(key) ?? 0;
- if (grossQty <= 0) continue;
-
- const [locationId, periodId, itemId] = splitKey(key);
- const repSys = replenishmentSystemByItem.get(itemId);
- const effectiveRepSys =
- repSys === "Buy and Make" ? "Buy" : (repSys as "Buy" | "Make" | undefined);
-
- // ── Inventory + Supply Netting ──
- const invKey = `${locationId}-${itemId}`;
- const onHand = onHandByLocationItem.get(invKey) ?? 0;
- const productionSupply = jobSupplyByLocationPeriodItem.get(key) ?? 0;
- const netRequirement = Math.max(
- 0,
- grossQty - Math.max(0, onHand) - productionSupply
- );
-
- // Consume on-hand inventory
- if (onHand > 0) {
- onHandByLocationItem.set(invKey, Math.max(0, onHand - grossQty));
- }
-
- // ── Dependent Demand Propagation ──
- // Only explode BOM if there's a net requirement AND item is Make type
- if (netRequirement > 0 && effectiveRepSys === "Make") {
- const children = bomByItem.get(itemId) ?? [];
- for (const child of children) {
- const childRepSys = replenishmentSystemByItem.get(child.itemId);
- const childEffRepSys =
- childRepSys === "Buy and Make"
- ? "Buy"
- : (childRepSys as "Buy" | "Make" | undefined);
-
- // Make+Make to Order = produced in-line, not independently planned.
- // Still propagate to grossDemand so children get exploded.
- const isInlineProduction =
- child.methodType === "Make to Order" &&
- childEffRepSys === "Make";
-
- const childQty = child.quantity * netRequirement;
- const childLeadTimeDays = leadTimeByItem.get(child.itemId) ?? 7;
- const childLeadTimeWeeks = Math.ceil(childLeadTimeDays / 7);
-
- // Offset to earlier period based on child's lead time
- const currentPeriodIndex = periods.findIndex(
- (p: DemandPeriod) => (p.id ?? "") === periodId
- );
- const targetPeriodIndex = Math.max(
- 0,
- currentPeriodIndex - childLeadTimeWeeks
- );
- const targetPeriod = periods[targetPeriodIndex];
-
- if (targetPeriod) {
- const childKey = `${locationId}-${targetPeriod.id}-${child.itemId}`;
- grossDemand.set(
- childKey,
- (grossDemand.get(childKey) ?? 0) + childQty
- );
- if (!isInlineProduction) {
- bomDerivedDemand.set(
- childKey,
- (bomDerivedDemand.get(childKey) ?? 0) + childQty
- );
- }
-
- // Inherit contributors from this level's key (= the parent item's
- // grossDemand key for this period) and scale by child.quantity.
- // Level-0 keys read from topLevelContributors (seeded above);
- // deeper levels read from demandContributors accumulated during
- // prior explosions of this same parent key at an earlier level.
- const parentContributors = [
- ...(demandContributors.get(key) ?? []),
- ...(topLevelContributors.get(key) ?? []),
- ];
- if (parentContributors.length > 0) {
- const childContributors = demandContributors.get(childKey) ?? [];
- for (const pc of parentContributors) {
- childContributors.push({
- ...pc,
- quantity: pc.quantity * child.quantity,
- });
- }
- demandContributors.set(childKey, childContributors);
- }
- }
- }
- }
- }
- }
-
// Write BOM-derived demand to demandForecast.
// The demand is already at the correct period (lead-time-offset
// was applied during propagation), so no further offset needed.
@@ -883,12 +763,6 @@ serve(async (req: Request) => {
// Helper functions
// ──────────────────────────────────────────────────────────────
-function splitKey(key: string): [string, string, string] {
- const parts = key.split("-");
- // Keys are "locationId-periodId-itemId" where each ID contains no hyphens (xid format)
- return [parts[0], parts[1], parts.slice(2).join("-")];
-}
-
function findPeriod(
date: CalendarDate,
today: CalendarDate,
@@ -902,37 +776,6 @@ function findPeriod(
);
}
-function computeLowLevelCodes(
- bomByItem: Map<string, BomChild[]>
-): Map<string, number> {
- const llc = new Map<string, number>();
-
- function assignLevel(
- itemId: string,
- level: number,
- visited: Set<string>
- ): void {
- if (visited.has(itemId)) return;
- visited.add(itemId);
-
- const currentLLC = llc.get(itemId) ?? -1;
- if (level > currentLLC) {
- llc.set(itemId, level);
- }
-
- const children = bomByItem.get(itemId) ?? [];
- for (const child of children) {
- assignLevel(child.itemId, level + 1, new Set(visited));
- }
- }
-
- for (const itemId of bomByItem.keys()) {
- assignLevel(itemId, 0, new Set());
- }
-
- return llc;
-}
-
function getStartAndEndDates(
today: CalendarDate,
groupBy: "Week" | "Day" | "Month"
diff --git a/packages/database/supabase/functions/recalculate/index.ts b/packages/database/supabase/functions/recalculate/index.ts
index 55709974dc..310113a9b5 100644
--- a/packages/database/supabase/functions/recalculate/index.ts
+++ b/packages/database/supabase/functions/recalculate/index.ts
@@ -279,6 +279,7 @@ const updateJobQuantities = async (
operationQuantity: totalWithScrap,
})
.where("jobMakeMethodId", "=", tree.data.jobMaterialMakeMethodId)
+ .where("reworkId", "is", null)
.execute(),
]);
diff --git a/packages/database/supabase/functions/trigger-rework/index.ts b/packages/database/supabase/functions/trigger-rework/index.ts
index 7d7d1e620e..fcf1b14430 100644
--- a/packages/database/supabase/functions/trigger-rework/index.ts
+++ b/packages/database/supabase/functions/trigger-rework/index.ts
@@ -1,5 +1,7 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import type { Transaction } from "kysely";
+import { nanoid } from "https://deno.land/x/[email protected]/nanoid.ts";
+import z from "npm:zod@^3.24.1";
import { getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import { corsHeaders } from "../lib/headers.ts";
import type { DB } from "../lib/types.ts";
@@ -13,7 +15,7 @@ interface TriggerReworkRequest {
targetJobOperationId: string;
reason: string;
quantity: number;
- trackedEntityId?: string;
+ trackedEntityIds?: string[];
companyId: string;
userId: string;
}
@@ -90,7 +92,7 @@ async function triggerRework(
targetJobOperationId,
reason,
quantity,
- trackedEntityId,
+ trackedEntityIds,
companyId,
userId,
} = body;
@@ -117,13 +119,49 @@ async function triggerRework(
targetJobOperationId,
reason,
quantity,
- trackedEntityId: trackedEntityId ?? null,
requestedById: userId,
companyId,
})
.returning(["id"])
.execute();
+ // 2b. Create tracked activity for traceability
+ if (trackedEntityIds && trackedEntityIds.length > 0) {
+ const activityId = nanoid();
+ await trx
+ .insertInto("trackedActivity")
+ .values({
+ id: activityId,
+ type: "Rework",
+ sourceDocument: "Rework",
+ sourceDocumentId: rework.id,
+ attributes: {
+ Job: jobId,
+ "Triggered At": triggeredAtJobOperationId,
+ Target: targetJobOperationId,
+ Reason: reason,
+ Quantity: quantity,
+ },
+ companyId,
+ createdBy: userId,
+ })
+ .execute();
+
+ const isSerial = trackedEntityIds.length > 1 || quantity === 1;
+ for (const entityId of trackedEntityIds) {
+ await trx
+ .insertInto("trackedActivityInput")
+ .values({
+ trackedActivityId: activityId,
+ trackedEntityId: entityId,
+ quantity: isSerial ? 1 : quantity,
+ companyId,
+ createdBy: userId,
+ })
+ .execute();
+ }
+ }
+
// 3. Fetch the source operations to clone
const sourceOperations = await trx
.selectFrom("jobOperation")
@@ -137,17 +175,44 @@ async function triggerRework(
(a, b) => (pathIndex.get(a.id) ?? 0) - (pathIndex.get(b.id) ?? 0)
);
- // 4. Clone operations
- const clonedOperationIds: string[] = [];
- const sourceToCloneMap = new Map<string, string>();
-
- for (const sourceOp of sourceOperations) {
- const [clonedOp] = await trx
- .insertInto("jobOperation")
- .values({
+ // 4. Compute sort order: place rework ops after the triggering operation
+ // "With Previous" on the first rework op lets it run in parallel with
+ // the triggering operation's successors until the DAG converges.
+ const [triggerOp, nextOp] = await Promise.all([
+ trx
+ .selectFrom("jobOperation")
+ .select("order")
+ .where("id", "=", triggeredAtJobOperationId)
+ .executeTakeFirstOrThrow(),
+ trx
+ .selectFrom("jobOperation")
+ .select("order")
+ .where("jobId", "=", jobId)
+ .where(
+ "order",
+ ">",
+ trx
+ .selectFrom("jobOperation")
+ .select("order")
+ .where("id", "=", triggeredAtJobOperationId)
+ )
+ .orderBy("order", "asc")
+ .executeTakeFirst(),
+ ]);
+
+ const triggerOrder = Number(triggerOp.order);
+ const upperBound = nextOp?.order ? Number(nextOp.order) : triggerOrder + 1;
+ const gap = upperBound - triggerOrder;
+ const increment = gap / (sourceOperations.length + 1);
+
+ // 5. Clone operations (batch insert)
+ const clonedOps = await trx
+ .insertInto("jobOperation")
+ .values(
+ sourceOperations.map((sourceOp, i) => ({
jobId: sourceOp.jobId,
jobMakeMethodId: sourceOp.jobMakeMethodId,
- order: sourceOp.order,
+ order: triggerOrder + increment * (i + 1),
processId: sourceOp.processId,
workCenterId: sourceOp.workCenterId,
description: sourceOp.description,
@@ -157,7 +222,7 @@ async function triggerRework(
laborUnit: sourceOp.laborUnit,
machineTime: sourceOp.machineTime,
machineUnit: sourceOp.machineUnit,
- operationOrder: sourceOp.operationOrder,
+ operationOrder: i === 0 ? "With Previous" : sourceOp.operationOrder,
laborRate: sourceOp.laborRate,
overheadRate: sourceOp.overheadRate,
machineRate: sourceOp.machineRate,
@@ -169,131 +234,114 @@ async function triggerRework(
workInstruction: sourceOp.workInstruction,
procedureId: sourceOp.procedureId,
operationQuantity: quantity,
+ targetQuantity: quantity,
tags: sourceOp.tags,
companyId,
createdBy: userId,
// @ts-expect-error - reworkId not in generated types until migration is applied
reworkId: rework.id,
- status: "Waiting",
+ status: i === 0 ? "Ready" : "Waiting",
customFields: sourceOp.customFields,
- })
- .returning(["id"])
- .execute();
+ }))
+ )
+ .returning(["id"])
+ .execute();
- clonedOperationIds.push(clonedOp.id);
- sourceToCloneMap.set(sourceOp.id, clonedOp.id);
- }
+ const clonedOperationIds = clonedOps.map((op) => op.id);
+ const sourceToCloneMap = new Map<string, string>();
+ sourceOperations.forEach((sourceOp, i) => {
+ sourceToCloneMap.set(sourceOp.id, clonedOps[i].id);
+ });
console.info(`🔧 Cloned ${clonedOperationIds.length} operations`);
- // 5. Clone steps, tools, and parameters for each operation
- for (const sourceOp of sourceOperations) {
- const cloneId = sourceToCloneMap.get(sourceOp.id)!;
-
- // Clone steps
- const steps = await trx
+ // 6. Clone steps, tools, and parameters (batch fetch + batch insert)
+ const [allSteps, allTools, allParams] = await Promise.all([
+ trx
.selectFrom("jobOperationStep")
.selectAll()
- .where("operationId", "=", sourceOp.id)
- .execute();
-
- if (steps.length > 0) {
- await trx
- .insertInto("jobOperationStep")
- .values(
- steps.map(
- ({
- id: _id,
- operationId: _opId,
- createdAt: _ca,
- updatedAt: _ua,
- updatedBy: _ub,
- ...step
- }) => ({
- ...step,
- operationId: cloneId,
- createdBy: userId,
- })
- )
- )
- .execute();
- }
-
- // Clone tools
- const tools = await trx
+ .where("operationId", "in", operationPath)
+ .execute(),
+ trx
.selectFrom("jobOperationTool")
.selectAll()
- .where("operationId", "=", sourceOp.id)
- .execute();
-
- if (tools.length > 0) {
- await trx
- .insertInto("jobOperationTool")
- .values(
- tools.map((tool) => ({
- toolId: tool.toolId,
- quantity: tool.quantity,
- operationId: cloneId,
- companyId,
- createdBy: userId,
- }))
- )
- .execute();
- }
-
- // Clone parameters
- const params = await trx
+ .where("operationId", "in", operationPath)
+ .execute(),
+ trx
.selectFrom("jobOperationParameter")
.selectAll()
- .where("operationId", "=", sourceOp.id)
- .execute();
-
- if (params.length > 0) {
- await trx
- .insertInto("jobOperationParameter")
- .values(
- params.map((param) => ({
- key: param.key,
- value: param.value,
- operationId: cloneId,
- companyId,
- createdBy: userId,
- }))
- )
- .execute();
- }
- }
+ .where("operationId", "in", operationPath)
+ .execute(),
+ ]);
+
+ const stepValues = allSteps.map(
+ ({
+ id: _id,
+ operationId,
+ createdAt: _ca,
+ updatedAt: _ua,
+ updatedBy: _ub,
+ ...step
+ }) => ({
+ ...step,
+ operationId: sourceToCloneMap.get(operationId)!,
+ createdBy: userId,
+ })
+ );
- // 6. Wire the rework operations into the DAG
+ const toolValues = allTools.map((tool) => ({
+ toolId: tool.toolId,
+ quantity: tool.quantity,
+ operationId: sourceToCloneMap.get(tool.operationId)!,
+ companyId,
+ createdBy: userId,
+ }));
- // 6a. First rework op depends on the trigger operation
- await trx
- .insertInto("jobOperationDependency")
- .values({
- operationId: clonedOperationIds[0],
- dependsOnId: triggeredAtJobOperationId,
+ const paramValues = allParams.map((param) => ({
+ key: param.key,
+ value: param.value,
+ operationId: sourceToCloneMap.get(param.operationId)!,
+ companyId,
+ createdBy: userId,
+ }));
+
+ await Promise.all([
+ stepValues.length > 0
+ ? trx.insertInto("jobOperationStep").values(stepValues).execute()
+ : null,
+ toolValues.length > 0
+ ? trx.insertInto("jobOperationTool").values(toolValues).execute()
+ : null,
+ paramValues.length > 0
+ ? trx.insertInto("jobOperationParameter").values(paramValues).execute()
+ : null,
+ ]);
+
+ // 7. Wire the rework operations into the DAG
+ // First rework op has no dependencies — it's an independent parallel branch.
+ // Traceability is captured via the rework record, not DAG edges.
+ const dagEdges: Array<{
+ operationId: string;
+ dependsOnId: string;
+ jobId: string;
+ companyId: string;
+ }> = [];
+
+ // 7a. Each subsequent rework op depends on the previous
+ for (let i = 1; i < clonedOperationIds.length; i++) {
+ dagEdges.push({
+ operationId: clonedOperationIds[i],
+ dependsOnId: clonedOperationIds[i - 1],
jobId,
companyId,
- })
- .execute();
-
- // 6b. Each subsequent rework op depends on the previous
- for (let i = 1; i < clonedOperationIds.length; i++) {
- await trx
- .insertInto("jobOperationDependency")
- .values({
- operationId: clonedOperationIds[i],
- dependsOnId: clonedOperationIds[i - 1],
- jobId,
- companyId,
- })
- .execute();
+ });
}
- // 6c. Rewire downstream operations
+ // 7b. Convergence: downstream ops that depended on triggeredAt also depend
+ // on the last rework op so the DAG merges back.
const downstreamDeps = await trx
.selectFrom("jobOperationDependency")
- .select(["operationId", "dependsOnId"])
+ .select(["operationId"])
.where("dependsOnId", "=", triggeredAtJobOperationId)
.where("operationId", "not in", clonedOperationIds)
.execute();
@@ -301,26 +349,24 @@ async function triggerRework(
const lastReworkOpId = clonedOperationIds[clonedOperationIds.length - 1];
for (const dep of downstreamDeps) {
- await trx
- .deleteFrom("jobOperationDependency")
- .where("operationId", "=", dep.operationId)
- .where("dependsOnId", "=", triggeredAtJobOperationId)
- .execute();
+ dagEdges.push({
+ operationId: dep.operationId,
+ dependsOnId: lastReworkOpId,
+ jobId,
+ companyId,
+ });
+ }
+ if (dagEdges.length > 0) {
await trx
.insertInto("jobOperationDependency")
- .values({
- operationId: dep.operationId,
- dependsOnId: lastReworkOpId,
- jobId,
- companyId,
- })
+ .values(dagEdges)
.execute();
}
console.info(`🔗 DAG wired with ${downstreamDeps.length} downstream deps rewired`);
- // 7. Record a productionQuantity entry for the rework
+ // 8. Record a productionQuantity entry for the rework
await trx
.insertInto("productionQuantity")
.values({
@@ -346,7 +392,34 @@ serve(async (req) => {
}
try {
- const body: TriggerReworkRequest = await req.json();
+ const raw = await req.json();
+ const parsed = z
+ .object({
+ jobId: z.string().min(1),
+ triggeredAtJobOperationId: z.string().min(1),
+ targetJobOperationId: z.string().min(1),
+ reason: z.string().min(1),
+ quantity: z.number().positive(),
+ trackedEntityIds: z.array(z.string()).optional(),
+ companyId: z.string().min(1),
+ userId: z.string().min(1),
+ })
+ .safeParse(raw);
+
+ if (!parsed.success) {
+ return new Response(
+ JSON.stringify({
+ success: false,
+ message: `Invalid request: ${parsed.error.issues.map((i) => i.message).join(", ")}`,
+ }),
+ {
+ status: 400,
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ }
+ );
+ }
+
+ const body = parsed.data;
console.info(
`🔰 Starting rework for job ${body.jobId}: go back to ${body.targetJobOperationId} from ${body.triggeredAtJobOperationId}`
diff --git a/packages/database/supabase/migrations/20260531084723_rework-serial-flow.sql b/packages/database/supabase/migrations/20260531084723_rework-serial-flow.sql
new file mode 100644
index 0000000000..f0cc38317b
--- /dev/null
+++ b/packages/database/supabase/migrations/20260531084723_rework-serial-flow.sql
@@ -0,0 +1,413 @@
+-- 1. Drop trackedEntityId from rework (serial tracking is now per-entity, not per-rework)
+ALTER TABLE "rework" DROP CONSTRAINT IF EXISTS "rework_trackedEntityId_fkey";
+ALTER TABLE "rework" DROP COLUMN IF EXISTS "trackedEntityId";
+
+-- 2. Change jobOperation.reworkId FK to CASCADE (deleting a rework should delete its operations)
+ALTER TABLE "jobOperation" DROP CONSTRAINT IF EXISTS "jobOperation_reworkId_fkey";
+ALTER TABLE "jobOperation" ADD CONSTRAINT "jobOperation_reworkId_fkey"
+ FOREIGN KEY ("reworkId") REFERENCES "rework"("id") ON DELETE CASCADE;
+
+-- 3. Add reworkId to get_job_operation_by_id
+DROP FUNCTION IF EXISTS get_job_operation_by_id(TEXT);
+CREATE OR REPLACE FUNCTION get_job_operation_by_id(operation_id TEXT)
+RETURNS TABLE (
+ id TEXT,
+ "jobId" TEXT,
+ "jobMakeMethodId" TEXT,
+ "operationOrder" DOUBLE PRECISION,
+ "processId" TEXT,
+ "workCenterId" TEXT,
+ description TEXT,
+ "setupTime" NUMERIC,
+ "setupUnit" factor,
+ "laborTime" NUMERIC,
+ "laborUnit" factor,
+ "machineTime" NUMERIC,
+ "machineUnit" factor,
+ "operationOrderType" "methodOperationOrder",
+ "jobReadableId" TEXT,
+ "jobStatus" "jobStatus",
+ "jobDueDate" DATE,
+ "jobDeadlineType" "deadlineType",
+ "parentMaterialId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "itemDescription" TEXT,
+ "itemUnitOfMeasure" TEXT,
+ "itemModelPath" TEXT,
+ "itemModelId" TEXT,
+ "itemModelName" TEXT,
+ "itemModelSize" BIGINT,
+ "operationStatus" "jobOperationStatus",
+ "targetQuantity" NUMERIC,
+ "operationQuantity" NUMERIC,
+ "quantityComplete" NUMERIC,
+ "quantityReworked" NUMERIC,
+ "quantityScrapped" NUMERIC,
+ "workInstruction" JSON,
+ "operationDueDate" DATE,
+ "reworkId" TEXT
+) AS $$
+BEGIN
+ RETURN QUERY
+ SELECT
+ jo."id",
+ jo."jobId",
+ jo."jobMakeMethodId",
+ jo."order" AS "operationOrder",
+ jo."processId",
+ jo."workCenterId",
+ jo."description",
+ jo."setupTime",
+ jo."setupUnit",
+ jo."laborTime",
+ jo."laborUnit",
+ jo."machineTime",
+ jo."machineUnit",
+ jo."operationOrder" AS "operationOrderType",
+ j."jobId" AS "jobReadableId",
+ j."status" AS "jobStatus",
+ j."dueDate"::DATE AS "jobDueDate",
+ j."deadlineType" AS "jobDeadlineType",
+ jmm."parentMaterialId",
+ i."id" as "itemId",
+ i."readableIdWithRevision" as "itemReadableId",
+ i."name" as "itemDescription",
+ uom."name" as "itemUnitOfMeasure",
+ m."modelPath" as "itemModelPath",
+ m."id" as "itemModelId",
+ m."name" as "itemModelName",
+ m."size" as "itemModelSize",
+ jo."status" AS "operationStatus",
+ jo."targetQuantity"::NUMERIC,
+ jo."operationQuantity",
+ jo."quantityComplete",
+ jo."quantityReworked",
+ jo."quantityScrapped",
+ jo."workInstruction",
+ jo."dueDate" AS "operationDueDate",
+ jo."reworkId"
+ FROM "jobOperation" jo
+ JOIN "job" j ON j.id = jo."jobId"
+ LEFT JOIN "jobMakeMethod" jmm ON jo."jobMakeMethodId" = jmm.id
+ LEFT JOIN "item" i ON jmm."itemId" = i.id
+ LEFT JOIN "unitOfMeasure" uom ON i."unitOfMeasureCode" = uom."code" AND i."companyId" = uom."companyId"
+ LEFT JOIN "modelUpload" m ON i."modelUploadId" = m.id
+ WHERE jo.id = operation_id
+ LIMIT 1;
+END;
+$$ LANGUAGE plpgsql;
+
+-- 4. Add reworkId to get_active_job_operations_by_location
+DROP FUNCTION IF EXISTS get_active_job_operations_by_location;
+CREATE OR REPLACE FUNCTION get_active_job_operations_by_location(
+ location_id TEXT,
+ work_center_ids TEXT[]
+)
+RETURNS TABLE (
+ "id" TEXT,
+ "jobId" TEXT,
+ "jobMakeMethodId" TEXT,
+ "operationOrder" DOUBLE PRECISION,
+ "priority" DOUBLE PRECISION,
+ "processId" TEXT,
+ "workCenterId" TEXT,
+ "description" TEXT,
+ "setupTime" NUMERIC,
+ "setupUnit" factor,
+ "laborTime" NUMERIC,
+ "laborUnit" factor,
+ "machineTime" NUMERIC,
+ "machineUnit" factor,
+ "operationOrderType" "methodOperationOrder",
+ "jobReadableId" TEXT,
+ "jobStatus" "jobStatus",
+ "jobDueDate" DATE,
+ "jobDeadlineType" "deadlineType",
+ "jobCustomerId" TEXT,
+ "customerName" TEXT,
+ "parentMaterialId" TEXT,
+ "itemReadableId" TEXT,
+ "itemDescription" TEXT,
+ "operationStatus" "jobOperationStatus",
+ "targetQuantity" NUMERIC,
+ "operationQuantity" NUMERIC,
+ "quantityComplete" NUMERIC,
+ "quantityReworked" NUMERIC,
+ "quantityScrapped" NUMERIC,
+ "salesOrderId" TEXT,
+ "salesOrderLineId" TEXT,
+ "salesOrderReadableId" TEXT,
+ "assignee" TEXT,
+ "tags" TEXT[],
+ "thumbnailPath" TEXT,
+ "operationDueDate" DATE,
+ "reworkId" TEXT
+)
+SECURITY INVOKER
+AS $$
+BEGIN
+ RETURN QUERY
+ WITH relevant_jobs AS (
+ SELECT *
+ FROM "job"
+ WHERE "locationId" = location_id
+ AND ("status" = 'Ready' OR "status" = 'In Progress' OR "status" = 'Paused')
+ )
+ SELECT
+ jo."id",
+ jo."jobId",
+ jo."jobMakeMethodId",
+ jo."order" AS "operationOrder",
+ jo."priority",
+ jo."processId",
+ jo."workCenterId",
+ jo."description",
+ jo."setupTime",
+ jo."setupUnit",
+ jo."laborTime",
+ jo."laborUnit",
+ jo."machineTime",
+ jo."machineUnit",
+ jo."operationOrder" AS "operationOrderType",
+ rj."jobId" AS "jobReadableId",
+ rj."status" AS "jobStatus",
+ rj."dueDate" AS "jobDueDate",
+ rj."deadlineType" AS "jobDeadlineType",
+ rj."customerId" AS "jobCustomerId",
+ c."name" AS "customerName",
+ jmm."parentMaterialId",
+ i."readableId" as "itemReadableId",
+ i."name" as "itemDescription",
+ CASE
+ WHEN rj."status" = 'Paused' THEN 'Paused'
+ ELSE jo."status"
+ END AS "operationStatus",
+ jo."targetQuantity"::NUMERIC,
+ jo."operationQuantity",
+ jo."quantityComplete",
+ jo."quantityReworked",
+ jo."quantityScrapped",
+ rj."salesOrderId",
+ rj."salesOrderLineId",
+ so."salesOrderId" as "salesOrderReadableId",
+ jo."assignee",
+ jo."tags",
+ COALESCE(mu."thumbnailPath", i."thumbnailPath") as "thumbnailPath",
+ jo."dueDate" AS "operationDueDate",
+ jo."reworkId"
+ FROM "jobOperation" jo
+ JOIN relevant_jobs rj ON rj.id = jo."jobId"
+ LEFT JOIN "jobMakeMethod" jmm ON jo."jobMakeMethodId" = jmm.id
+ LEFT JOIN "item" i ON jmm."itemId" = i.id
+ LEFT JOIN "customer" c ON rj."customerId" = c.id
+ LEFT JOIN "salesOrder" so ON rj."salesOrderId" = so.id
+ LEFT JOIN "modelUpload" mu ON i."modelUploadId" = mu.id
+ WHERE CASE
+ WHEN array_length(work_center_ids, 1) > 0 THEN
+ jo."workCenterId" = ANY(work_center_ids) AND jo."status" != 'Done' AND jo."status" != 'Canceled'
+ ELSE jo."status" != 'Done' AND jo."status" != 'Canceled'
+ END
+ ORDER BY jo."startDate", jo."priority";
+
+END;
+$$ LANGUAGE plpgsql;
+
+-- 5. Update sync_update_job_operation_quantities to sum across all terminal operations
+CREATE OR REPLACE FUNCTION sync_update_job_operation_quantities(
+ p_table TEXT,
+ p_operation TEXT,
+ p_new JSONB,
+ p_old JSONB
+)
+RETURNS VOID
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+DECLARE
+ v_job_operation_id TEXT;
+ v_job_id TEXT;
+ v_is_last_top_level_operation BOOLEAN := FALSE;
+BEGIN
+ IF p_operation = 'INSERT' THEN
+ v_job_operation_id := p_new->>'jobOperationId';
+
+ UPDATE "jobOperation"
+ SET
+ "quantityComplete" = "quantityComplete" +
+ CASE WHEN (p_new->>'type') = 'Production' THEN (p_new->>'quantity')::numeric ELSE 0 END,
+ "quantityReworked" = "quantityReworked" +
+ CASE WHEN (p_new->>'type') = 'Rework' THEN (p_new->>'quantity')::numeric ELSE 0 END,
+ "quantityScrapped" = "quantityScrapped" +
+ CASE WHEN (p_new->>'type') = 'Scrap' THEN (p_new->>'quantity')::numeric ELSE 0 END
+ WHERE id = v_job_operation_id;
+
+ ELSIF p_operation = 'UPDATE' THEN
+ v_job_operation_id := p_new->>'jobOperationId';
+
+ UPDATE "jobOperation"
+ SET
+ "quantityComplete" = "quantityComplete"
+ - CASE WHEN (p_old->>'type') = 'Production' THEN (p_old->>'quantity')::numeric ELSE 0 END
+ + CASE WHEN (p_new->>'type') = 'Production' THEN (p_new->>'quantity')::numeric ELSE 0 END,
+ "quantityReworked" = "quantityReworked"
+ - CASE WHEN (p_old->>'type') = 'Rework' THEN (p_old->>'quantity')::numeric ELSE 0 END
+ + CASE WHEN (p_new->>'type') = 'Rework' THEN (p_new->>'quantity')::numeric ELSE 0 END,
+ "quantityScrapped" = "quantityScrapped"
+ - CASE WHEN (p_old->>'type') = 'Scrap' THEN (p_old->>'quantity')::numeric ELSE 0 END
+ + CASE WHEN (p_new->>'type') = 'Scrap' THEN (p_new->>'quantity')::numeric ELSE 0 END
+ WHERE id = v_job_operation_id;
+
+ ELSIF p_operation = 'DELETE' THEN
+ v_job_operation_id := p_old->>'jobOperationId';
+
+ UPDATE "jobOperation"
+ SET
+ "quantityComplete" = "quantityComplete" -
+ CASE WHEN (p_old->>'type') = 'Production' THEN (p_old->>'quantity')::numeric ELSE 0 END,
+ "quantityReworked" = "quantityReworked" -
+ CASE WHEN (p_old->>'type') = 'Rework' THEN (p_old->>'quantity')::numeric ELSE 0 END,
+ "quantityScrapped" = "quantityScrapped" -
+ CASE WHEN (p_old->>'type') = 'Scrap' THEN (p_old->>'quantity')::numeric ELSE 0 END
+ WHERE id = v_job_operation_id;
+ END IF;
+
+ UPDATE "jobOperation"
+ SET "status" = 'Done'
+ WHERE id = v_job_operation_id
+ AND "status" NOT IN ('Done', 'Canceled')
+ AND "targetQuantity" > 0
+ AND ("quantityComplete" + "quantityReworked" + "quantityScrapped") >= "targetQuantity";
+
+ SELECT jo."jobId" INTO v_job_id
+ FROM "jobOperation" jo
+ WHERE jo.id = v_job_operation_id;
+
+ SELECT EXISTS (
+ SELECT 1
+ FROM "jobOperation" jo
+ INNER JOIN "jobMakeMethod" jmm ON jmm.id = jo."jobMakeMethodId"
+ WHERE jo.id = v_job_operation_id
+ AND jmm."parentMaterialId" IS NULL
+ AND NOT EXISTS (
+ SELECT 1
+ FROM "jobOperationDependency" dep
+ INNER JOIN "jobOperation" child_jo ON child_jo.id = dep."operationId"
+ INNER JOIN "jobMakeMethod" child_jmm ON child_jmm.id = child_jo."jobMakeMethodId"
+ WHERE dep."dependsOnId" = jo.id
+ AND child_jmm."parentMaterialId" IS NULL
+ )
+ ) INTO v_is_last_top_level_operation;
+
+ IF v_job_id IS NOT NULL AND v_is_last_top_level_operation THEN
+ UPDATE "job"
+ SET "quantityComplete" = (
+ SELECT COALESCE(SUM(terminal_jo."quantityComplete"), 0)
+ FROM "jobOperation" terminal_jo
+ INNER JOIN "jobMakeMethod" terminal_jmm ON terminal_jmm.id = terminal_jo."jobMakeMethodId"
+ WHERE terminal_jo."jobId" = v_job_id
+ AND terminal_jmm."parentMaterialId" IS NULL
+ AND NOT EXISTS (
+ SELECT 1
+ FROM "jobOperationDependency" dep
+ INNER JOIN "jobOperation" child_jo ON child_jo.id = dep."operationId"
+ INNER JOIN "jobMakeMethod" child_jmm ON child_jmm.id = child_jo."jobMakeMethodId"
+ WHERE dep."dependsOnId" = terminal_jo.id
+ AND child_jmm."parentMaterialId" IS NULL
+ )
+ )
+ WHERE id = v_job_id
+ AND status NOT IN ('Completed', 'Cancelled');
+ END IF;
+END;
+$$;
+
+-- 6. Update sync_finish_job_operation to sum across all terminal operations
+CREATE OR REPLACE FUNCTION sync_finish_job_operation(
+ p_table TEXT,
+ p_operation TEXT,
+ p_new JSONB,
+ p_old JSONB
+)
+RETURNS VOID
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+DECLARE
+ v_job_location_id TEXT;
+ v_job_storage_unit_id TEXT;
+ v_job_quantity NUMERIC;
+ v_sales_order_id TEXT;
+ v_quantity_complete NUMERIC;
+ v_job_status TEXT;
+BEGIN
+ IF p_operation != 'UPDATE' THEN RETURN; END IF;
+ IF (p_new->>'status') != 'Done' OR (p_old->>'status') = 'Done' THEN RETURN; END IF;
+
+ UPDATE "productionEvent"
+ SET "endTime" = NOW()
+ WHERE "jobOperationId" = p_new->>'id'
+ AND "endTime" IS NULL;
+
+ UPDATE "jobOperation" op
+ SET status = 'Ready'
+ WHERE EXISTS (
+ SELECT 1
+ FROM "jobOperationDependency" dep
+ WHERE dep."operationId" = op.id
+ AND dep."dependsOnId" = p_new->>'id'
+ AND op.status = 'Waiting'
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM "jobOperationDependency" dep2
+ JOIN "jobOperation" jo2 ON jo2.id = dep2."dependsOnId"
+ WHERE dep2."operationId" = op.id
+ AND jo2.status != 'Done'
+ AND jo2.id != p_new->>'id'
+ );
+
+ SELECT status INTO v_job_status FROM "job" WHERE id = p_new->>'jobId';
+ IF v_job_status NOT IN ('Ready', 'In Progress', 'Paused') THEN
+ RETURN;
+ END IF;
+
+ IF is_last_job_operation(p_new->>'id') THEN
+ SELECT "locationId", "storageUnitId", quantity, "salesOrderId"
+ INTO v_job_location_id, v_job_storage_unit_id, v_job_quantity, v_sales_order_id
+ FROM "job"
+ WHERE id = p_new->>'jobId';
+
+ v_quantity_complete := (
+ SELECT COALESCE(SUM(terminal_jo."quantityComplete"), 0)
+ FROM "jobOperation" terminal_jo
+ INNER JOIN "jobMakeMethod" terminal_jmm ON terminal_jmm.id = terminal_jo."jobMakeMethodId"
+ WHERE terminal_jo."jobId" = p_new->>'jobId'
+ AND terminal_jmm."parentMaterialId" IS NULL
+ AND NOT EXISTS (
+ SELECT 1
+ FROM "jobOperationDependency" dep
+ INNER JOIN "jobOperation" child_jo ON child_jo.id = dep."operationId"
+ INNER JOIN "jobMakeMethod" child_jmm ON child_jmm.id = child_jo."jobMakeMethodId"
+ WHERE dep."dependsOnId" = terminal_jo.id
+ AND child_jmm."parentMaterialId" IS NULL
+ )
+ );
+
+ IF COALESCE(v_quantity_complete, 0) = 0 THEN
+ v_quantity_complete := v_job_quantity;
+ END IF;
+
+ PERFORM complete_job_to_inventory(
+ p_job_id := p_new->>'jobId',
+ p_quantity_complete := v_quantity_complete,
+ p_storage_unit_id := v_job_storage_unit_id,
+ p_location_id := v_job_location_id,
+ p_company_id := p_new->>'companyId',
+ p_user_id := p_new->>'updatedBy'
+ );
+ END IF;
+END;
+$$;
diff --git a/packages/form/src/components/Select.tsx b/packages/form/src/components/Select.tsx
index 265ab73ea9..4181e65261 100644
--- a/packages/form/src/components/Select.tsx
+++ b/packages/form/src/components/Select.tsx
@@ -217,11 +217,17 @@ export const SelectBase = forwardRef<HTMLButtonElement, SelectBaseProps>(
)}
</SelectTrigger>
<SelectContent>
- {options.map((option) => (
- <SelectItem key={option.value} value={option.value}>
- {option.label}
- </SelectItem>
- ))}
+ {options.length === 0 ? (
+ <div className="py-6 text-center text-sm text-muted-foreground">
+ No options available
+ </div>
+ ) : (
+ options.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))
+ )}
</SelectContent>
</CarbonSelect>
{isClearable && !isNonInteractive && value && (
diff --git a/packages/locale/locales/de/mes.po b/packages/locale/locales/de/mes.po
index 21b116a566..471ff502f4 100644
--- a/packages/locale/locales/de/mes.po
+++ b/packages/locale/locales/de/mes.po
@@ -103,6 +103,9 @@ msgstr "Datei anhängen"
msgid "Authentication Error"
msgstr "Authentifizierungsfehler"
+msgid "Batch"
+msgstr ""
+
#. placeholder {0}: batch.readableId
#. placeholder {1}: batch.quantity
msgid "Batch {0} ({1} available)"
@@ -276,9 +279,9 @@ msgstr "Datei hierher ziehen oder klicken, um eine Datei auszuwählen"
msgid "Dragging {0} cancelled."
msgstr "Ziehen von {0} abgebrochen."
-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )
msgid "Due {0}"
msgstr "Fällig {0}"
@@ -595,6 +598,9 @@ msgstr "Keine geplante Zeit"
msgid "No serial numbers"
msgstr "Keine Seriennummern"
+msgid "No serial numbers found"
+msgstr ""
+
msgid "No spare parts added yet"
msgstr "Noch keine Ersatzteile hinzugefügt"
@@ -750,6 +756,9 @@ msgstr "Scannen"
msgid "Scan or enter serial number"
msgstr "Seriennummer scannen oder eingeben"
+msgid "Scan or search serial number..."
+msgstr ""
+
msgid "Schedule"
msgstr "Zeitplan"
@@ -829,6 +838,9 @@ msgstr "Seriennummer ist nicht verfügbar"
msgid "Serial number is required"
msgstr "Seriennummer ist erforderlich"
+msgid "Serial numbers"
+msgstr ""
+
msgid "Serial Numbers"
msgstr "Seriennummern"
diff --git a/packages/locale/locales/en/mes.po b/packages/locale/locales/en/mes.po
index 1fa4d8893e..b84654316b 100644
--- a/packages/locale/locales/en/mes.po
+++ b/packages/locale/locales/en/mes.po
@@ -103,6 +103,9 @@ msgstr "Attach File"
msgid "Authentication Error"
msgstr "Authentication Error"
+msgid "Batch"
+msgstr "Batch"
+
#. placeholder {0}: batch.readableId
#. placeholder {1}: batch.quantity
msgid "Batch {0} ({1} available)"
@@ -276,9 +279,9 @@ msgstr "Drag and drop a file here, or click to select a file"
msgid "Dragging {0} cancelled."
msgstr "Dragging {0} cancelled."
-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )
msgid "Due {0}"
msgstr "Due {0}"
@@ -595,6 +598,9 @@ msgstr "No scheduled time"
msgid "No serial numbers"
msgstr "No serial numbers"
+msgid "No serial numbers found"
+msgstr "No serial numbers found"
+
msgid "No spare parts added yet"
msgstr "No spare parts added yet"
@@ -750,6 +756,9 @@ msgstr "Scan"
msgid "Scan or enter serial number"
msgstr "Scan or enter serial number"
+msgid "Scan or search serial number..."
+msgstr "Scan or search serial number..."
+
msgid "Schedule"
msgstr "Schedule"
@@ -829,6 +838,9 @@ msgstr "Serial number is not available"
msgid "Serial number is required"
msgstr "Serial number is required"
+msgid "Serial numbers"
+msgstr "Serial numbers"
+
msgid "Serial Numbers"
msgstr "Serial Numbers"
diff --git a/packages/locale/locales/es/mes.po b/packages/locale/locales/es/mes.po
index 88f514c79a..7732a43b5f 100644
--- a/packages/locale/locales/es/mes.po
+++ b/packages/locale/locales/es/mes.po
@@ -103,6 +103,9 @@ msgstr "Adjuntar archivo"
msgid "Authentication Error"
msgstr "Error de autenticación"
+msgid "Batch"
+msgstr ""
+
#. placeholder {0}: batch.readableId
#. placeholder {1}: batch.quantity
msgid "Batch {0} ({1} available)"
@@ -276,9 +279,9 @@ msgstr "Arrastre y suelte un archivo aquí, o haga clic para seleccionar un arch
msgid "Dragging {0} cancelled."
msgstr "Se canceló el arrastre de {0}."
-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )
msgid "Due {0}"
msgstr "Vence {0}"
@@ -595,6 +598,9 @@ msgstr "Sin tiempo programado"
msgid "No serial numbers"
msgstr "Sin números de serie"
+msgid "No serial numbers found"
+msgstr ""
+
msgid "No spare parts added yet"
msgstr "Aún no se han agregado repuestos"
@@ -750,6 +756,9 @@ msgstr "Escanear"
msgid "Scan or enter serial number"
msgstr "Escanee o ingrese el número de serie"
+msgid "Scan or search serial number..."
+msgstr ""
+
msgid "Schedule"
msgstr "Programación"
@@ -829,6 +838,9 @@ msgstr "El número de serie no está disponible"
msgid "Serial number is required"
msgstr "El número de serie es obligatorio"
+msgid "Serial numbers"
+msgstr ""
+
msgid "Serial Numbers"
msgstr "Números de serie"
diff --git a/packages/locale/locales/fr/mes.po b/packages/locale/locales/fr/mes.po
index 6cbf54d203..b501f6cfc4 100644
--- a/packages/locale/locales/fr/mes.po
+++ b/packages/locale/locales/fr/mes.po
@@ -103,6 +103,9 @@ msgstr "Joindre un fichier"
msgid "Authentication Error"
msgstr "Erreur d'authentification"
+msgid "Batch"
+msgstr ""
+
#. placeholder {0}: batch.readableId
#. placeholder {1}: batch.quantity
msgid "Batch {0} ({1} available)"
@@ -276,9 +279,9 @@ msgstr "Glissez-déposez un fichier ici, ou cliquez pour sélectionner un fichie
msgid "Dragging {0} cancelled."
msgstr "Déplacement de {0} annulé."
-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )
msgid "Due {0}"
msgstr "Échéance {0}"
@@ -595,6 +598,9 @@ msgstr "Aucun horaire planifié"
msgid "No serial numbers"
msgstr "Aucun numéro de série"
+msgid "No serial numbers found"
+msgstr ""
+
msgid "No spare parts added yet"
msgstr "Aucune pièce de rechange ajoutée"
@@ -750,6 +756,9 @@ msgstr "Scanner"
msgid "Scan or enter serial number"
msgstr "Scanner ou saisir le numéro de série"
+msgid "Scan or search serial number..."
+msgstr ""
+
msgid "Schedule"
msgstr "Planification"
@@ -829,6 +838,9 @@ msgstr "Le numéro de série n'est pas disponible"
msgid "Serial number is required"
msgstr "Le numéro de série est requis"
+msgid "Serial numbers"
+msgstr ""
+
msgid "Serial Numbers"
msgstr "Numéros de série"
diff --git a/packages/locale/locales/hi/mes.po b/packages/locale/locales/hi/mes.po
index 15939de6b6..70dc4f5b3a 100644
--- a/packages/locale/locales/hi/mes.po
+++ b/packages/locale/locales/hi/mes.po
@@ -103,6 +103,9 @@ msgstr "फ़ाइल संलग्न करें"
msgid "Authentication Error"
msgstr "प्रमाणीकरण त्रुटि"
+msgid "Batch"
+msgstr ""
+
#. placeholder {0}: batch.readableId
#. placeholder {1}: batch.quantity
msgid "Batch {0} ({1} available)"
@@ -276,9 +279,9 @@ msgstr "यहाँ एक फ़ाइल को ड्रैग और ड्
msgid "Dragging {0} cancelled."
msgstr "\"{0}\" को ड्रैग करना रद्द किया गया।"
-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )
msgid "Due {0}"
msgstr "Due {0} के लिए"
@@ -595,6 +598,9 @@ msgstr "कोई निर्धारित समय नहीं"
msgid "No serial numbers"
msgstr "कोई सीरियल नंबर नहीं"
+msgid "No serial numbers found"
+msgstr ""
+
msgid "No spare parts added yet"
msgstr "अभी तक कोई स्पेयर पार्ट्स नहीं जोड़े गए हैं"
@@ -750,6 +756,9 @@ msgstr "स्कैन करें"
msgid "Scan or enter serial number"
msgstr "स्कैन करें या सीरियल नंबर दर्ज करें"
+msgid "Scan or search serial number..."
+msgstr ""
+
msgid "Schedule"
msgstr "शेड्यूल"
@@ -829,6 +838,9 @@ msgstr "सीरियल नंबर उपलब्ध नहीं है"
msgid "Serial number is required"
msgstr "सीरियल नंबर आवश्यक है"
+msgid "Serial numbers"
+msgstr ""
+
msgid "Serial Numbers"
msgstr "सीरियल नंबर"
diff --git a/packages/locale/locales/it/mes.po b/packages/locale/locales/it/mes.po
index 46e101f1e5..e8f7290c2d 100644
--- a/packages/locale/locales/it/mes.po
+++ b/packages/locale/locales/it/mes.po
@@ -103,6 +103,9 @@ msgstr "Allega File"
msgid "Authentication Error"
msgstr "Errore di Autenticazione"
+msgid "Batch"
+msgstr ""
+
#. placeholder {0}: batch.readableId
#. placeholder {1}: batch.quantity
msgid "Batch {0} ({1} available)"
@@ -276,9 +279,9 @@ msgstr "Trascina e rilascia un file qui, o clicca per selezionare un file"
msgid "Dragging {0} cancelled."
msgstr "Trascinamento di {0} annullato."
-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )
msgid "Due {0}"
msgstr "Scadenza {0}"
@@ -595,6 +598,9 @@ msgstr "Nessun orario programmato"
msgid "No serial numbers"
msgstr "Nessun numero di serie"
+msgid "No serial numbers found"
+msgstr ""
+
msgid "No spare parts added yet"
msgstr "Nessun ricambio ancora aggiunto"
@@ -750,6 +756,9 @@ msgstr "Scansiona"
msgid "Scan or enter serial number"
msgstr "Scansiona o inserisci il numero di serie"
+msgid "Scan or search serial number..."
+msgstr ""
+
msgid "Schedule"
msgstr "Pianificazione"
@@ -829,6 +838,9 @@ msgstr "Numero di serie non disponibile"
msgid "Serial number is required"
msgstr "Il numero di serie è obbligatorio"
+msgid "Serial numbers"
+msgstr ""
+
msgid "Serial Numbers"
msgstr "Numeri di Serie"
diff --git a/packages/locale/locales/ja/mes.po b/packages/locale/locales/ja/mes.po
index 921d18dfb9..f195f9e078 100644
--- a/packages/locale/locales/ja/mes.po
+++ b/packages/locale/locales/ja/mes.po
@@ -103,6 +103,9 @@ msgstr "ファイルを添付"
msgid "Authentication Error"
msgstr "認証エラー"
+msgid "Batch"
+msgstr ""
+
#. placeholder {0}: batch.readableId
#. placeholder {1}: batch.quantity
msgid "Batch {0} ({1} available)"
@@ -276,9 +279,9 @@ msgstr "ファイルをここにドラッグ&ドロップするか、クリッ
msgid "Dragging {0} cancelled."
msgstr "{0} のドラッグがキャンセルされました。"
-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )
msgid "Due {0}"
msgstr "期限 {0}"
@@ -595,6 +598,9 @@ msgstr "予定時間なし"
msgid "No serial numbers"
msgstr "シリアル番号なし"
+msgid "No serial numbers found"
+msgstr ""
+
msgid "No spare parts added yet"
msgstr "スペアパーツはまだ追加されていません"
@@ -750,6 +756,9 @@ msgstr "スキャン"
msgid "Scan or enter serial number"
msgstr "シリアル番号をスキャンまたは入力"
+msgid "Scan or search serial number..."
+msgstr ""
+
msgid "Schedule"
msgstr "スケジュール"
@@ -829,6 +838,9 @@ msgstr "シリアル番号は利用できません"
msgid "Serial number is required"
msgstr "シリアル番号は必須です"
+msgid "Serial numbers"
+msgstr ""
+
msgid "Serial Numbers"
msgstr "シリアル番号"
diff --git a/packages/locale/locales/pl/mes.po b/packages/locale/locales/pl/mes.po
index d55fff9997..7f5a6353ab 100644
--- a/packages/locale/locales/pl/mes.po
+++ b/packages/locale/locales/pl/mes.po
@@ -103,6 +103,9 @@ msgstr "Załącz plik"
msgid "Authentication Error"
msgstr "Błąd uwierzytelniania"
+msgid "Batch"
+msgstr ""
+
#. placeholder {0}: batch.readableId
#. placeholder {1}: batch.quantity
msgid "Batch {0} ({1} available)"
@@ -276,9 +279,9 @@ msgstr "Przeciągnij i upuść plik tutaj lub kliknij, aby wybrać plik"
msgid "Dragging {0} cancelled."
msgstr "Przeciąganie {0} anulowane."
-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )
msgid "Due {0}"
msgstr "Termin {0}"
@@ -595,6 +598,9 @@ msgstr "Brak zaplanowanego czasu"
msgid "No serial numbers"
msgstr "Brak numerów seryjnych"
+msgid "No serial numbers found"
+msgstr ""
+
msgid "No spare parts added yet"
msgstr "Nie dodano jeszcze części zamiennych"
@@ -750,6 +756,9 @@ msgstr "Skanuj"
msgid "Scan or enter serial number"
msgstr "Skanuj lub wprowadź numer seryjny"
+msgid "Scan or search serial number..."
+msgstr ""
+
msgid "Schedule"
msgstr "Harmonogram"
@@ -829,6 +838,9 @@ msgstr "Numer seryjny jest niedostępny"
msgid "Serial number is required"
msgstr "Numer seryjny jest wymagany"
+msgid "Serial numbers"
+msgstr ""
+
msgid "Serial Numbers"
msgstr "Numery seryjne"
diff --git a/packages/locale/locales/pt/mes.po b/packages/locale/locales/pt/mes.po
index 7dcec73cbc..65fd90b24c 100644
--- a/packages/locale/locales/pt/mes.po
+++ b/packages/locale/locales/pt/mes.po
@@ -103,6 +103,9 @@ msgstr "Anexar Arquivo"
msgid "Authentication Error"
msgstr "Erro de Autenticação"
+msgid "Batch"
+msgstr ""
+
#. placeholder {0}: batch.readableId
#. placeholder {1}: batch.quantity
msgid "Batch {0} ({1} available)"
@@ -276,9 +279,9 @@ msgstr "Arraste e solte um arquivo aqui ou clique para selecionar um arquivo"
msgid "Dragging {0} cancelled."
msgstr "Arraste de {0} cancelado."
-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )
msgid "Due {0}"
msgstr "Vencimento {0}"
@@ -595,6 +598,9 @@ msgstr "Nenhum horário programado"
msgid "No serial numbers"
msgstr "Nenhum número de série"
+msgid "No serial numbers found"
+msgstr ""
+
msgid "No spare parts added yet"
msgstr "Nenhuma peça sobressalente adicionada ainda"
@@ -750,6 +756,9 @@ msgstr "Escanear"
msgid "Scan or enter serial number"
msgstr "Escanear ou inserir número de série"
+msgid "Scan or search serial number..."
+msgstr ""
+
msgid "Schedule"
msgstr "Cronograma"
@@ -829,6 +838,9 @@ msgstr "Número de série não disponível"
msgid "Serial number is required"
msgstr "Número de série é obrigatório"
+msgid "Serial numbers"
+msgstr ""
+
msgid "Serial Numbers"
msgstr "Números de Série"
diff --git a/packages/locale/locales/ru/mes.po b/packages/locale/locales/ru/mes.po
index a275d3892b..6bd7232723 100644
--- a/packages/locale/locales/ru/mes.po
+++ b/packages/locale/locales/ru/mes.po
@@ -103,6 +103,9 @@ msgstr "Прикрепить файл"
msgid "Authentication Error"
msgstr "Ошибка аутентификации"
+msgid "Batch"
+msgstr ""
+
#. placeholder {0}: batch.readableId
#. placeholder {1}: batch.quantity
msgid "Batch {0} ({1} available)"
@@ -276,9 +279,9 @@ msgstr "Перетащите файл сюда или нажмите для вы
msgid "Dragging {0} cancelled."
msgstr "Перетаскивание {0} отменено."
-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )
msgid "Due {0}"
msgstr "Срок {0}"
@@ -595,6 +598,9 @@ msgstr "Нет запланированного времени"
msgid "No serial numbers"
msgstr "Нет серийных номеров"
+msgid "No serial numbers found"
+msgstr ""
+
msgid "No spare parts added yet"
msgstr "Запасные части ещё не добавлены"
@@ -750,6 +756,9 @@ msgstr "Сканировать"
msgid "Scan or enter serial number"
msgstr "Сканируйте или введите серийный номер"
+msgid "Scan or search serial number..."
+msgstr ""
+
msgid "Schedule"
msgstr "Расписание"
@@ -829,6 +838,9 @@ msgstr "Серийный номер недоступен"
msgid "Serial number is required"
msgstr "Серийный номер обязателен"
+msgid "Serial numbers"
+msgstr ""
+
msgid "Serial Numbers"
msgstr "Серийные номера"
diff --git a/packages/locale/locales/zh/mes.po b/packages/locale/locales/zh/mes.po
index 6e3c703d67..07ee99e537 100644
--- a/packages/locale/locales/zh/mes.po
+++ b/packages/locale/locales/zh/mes.po
@@ -103,6 +103,9 @@ msgstr "附加文件"
msgid "Authentication Error"
msgstr "认证错误"
+msgid "Batch"
+msgstr ""
+
#. placeholder {0}: batch.readableId
#. placeholder {1}: batch.quantity
msgid "Batch {0} ({1} available)"
@@ -276,9 +279,9 @@ msgstr "拖放文件到此处,或点击选择文件"
msgid "Dragging {0} cancelled."
msgstr "拖拽 {0} 已取消。"
-#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString( operation.operationDueDate ) )
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(operation.jobDueDate) )
+#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(item.dueDate) )
msgid "Due {0}"
msgstr "截止 {0}"
@@ -595,6 +598,9 @@ msgstr "无排定时间"
msgid "No serial numbers"
msgstr "无序列号"
+msgid "No serial numbers found"
+msgstr ""
+
msgid "No spare parts added yet"
msgstr "尚未添加备件"
@@ -750,6 +756,9 @@ msgstr "扫描"
msgid "Scan or enter serial number"
msgstr "扫描或输入序列号"
+msgid "Scan or search serial number..."
+msgstr ""
+
msgid "Schedule"
msgstr "排程"
@@ -829,6 +838,9 @@ msgstr "序列号不可用"
msgid "Serial number is required"
msgstr "序列号为必填项"
+msgid "Serial numbers"
+msgstr ""
+
msgid "Serial Numbers"
msgstr "序列号"
diff --git a/packages/react/src/BarProgress.tsx b/packages/react/src/BarProgress.tsx
index 7d65a954fd..9301582a77 100644
--- a/packages/react/src/BarProgress.tsx
+++ b/packages/react/src/BarProgress.tsx
@@ -53,6 +53,11 @@ function getGradientColor(ratio: number, stops: GradientStop[]): string {
return lerpColor(stops[0]!.color, stops[0]!.color, 0);
}
+type Segment = {
+ value: number;
+ className: string;
+};
+
interface BarProgressProps {
/** Numeric progress value */
progress: number;
@@ -66,6 +71,8 @@ interface BarProgressProps {
gradient?: boolean;
/** Invert the gradient to green-yellow-red */
invertGradient?: boolean;
+ /** Multi-segment progress (renders segments in order, ignores progress/gradient/activeClassName) */
+ segments?: Segment[];
/** Additional class names for the outer wrapper */
className?: string;
/** Class name for the active (filled) bars (ignored when gradient is true) */
@@ -81,6 +88,7 @@ export function BarProgress({
value,
gradient = false,
invertGradient = false,
+ segments,
className,
activeClassName = "bg-emerald-500",
inactiveClassName = "bg-muted"
@@ -91,10 +99,6 @@ export function BarProgress({
const calculateBars = useCallback(() => {
if (!containerRef.current) return;
const width = containerRef.current.clientWidth;
- // Total width per bar = BAR_WIDTH + BAR_GAP, minus one trailing gap
- // width = bars * BAR_WIDTH + (bars - 1) * BAR_GAP
- // width = bars * (BAR_WIDTH + BAR_GAP) - BAR_GAP
- // bars = floor((width + BAR_GAP) / (BAR_WIDTH + BAR_GAP))
const count = Math.floor((width + BAR_GAP) / (BAR_WIDTH + BAR_GAP));
setBarCount(Math.max(count, 1));
}, []);
@@ -116,6 +120,37 @@ export function BarProgress({
const hasHeader = label || value;
+ const getBarClassName = (i: number): string => {
+ if (segments && barCount > 0) {
+ let cumulative = 0;
+ for (const seg of segments) {
+ const segBars = Math.round((seg.value / max) * barCount);
+ cumulative += segBars;
+ if (i < cumulative) return seg.className;
+ }
+ return inactiveClassName;
+ }
+
+ const isActive = i < activeBars;
+ if (gradient && isActive) return "";
+ if (isActive) return activeClassName;
+ return inactiveClassName;
+ };
+
+ const getBarStyle = (i: number): React.CSSProperties | undefined => {
+ if (segments) return undefined;
+ const isActive = i < activeBars;
+ if (isActive && gradient && barCount > 0) {
+ return {
+ backgroundColor: getGradientColor(
+ i / (barCount - 1 || 1),
+ invertGradient ? GRADIENT_STOPS_INVERTED : GRADIENT_STOPS
+ )
+ };
+ }
+ return undefined;
+ };
+
return (
<div className={cn("w-full", className)}>
{hasHeader && (
@@ -142,35 +177,21 @@ export function BarProgress({
className="flex w-full items-center gap-[3px]"
>
{barCount > 0 &&
- Array.from({ length: barCount }, (_, i) => {
- const isActive = i < activeBars;
- const gradientStyle =
- isActive && gradient && barCount > 0
- ? {
- backgroundColor: getGradientColor(
- i / (barCount - 1 || 1),
- invertGradient ? GRADIENT_STOPS_INVERTED : GRADIENT_STOPS
- )
- }
- : undefined;
-
- return (
- <span
- key={i}
- aria-hidden="true"
- className={cn(
- "shrink-0 rounded-[2px] transition-colors duration-200",
- !gradient && isActive && activeClassName,
- !isActive && inactiveClassName
- )}
- style={{
- width: BAR_WIDTH,
- height: BAR_HEIGHT,
- ...gradientStyle
- }}
- />
- );
- })}
+ Array.from({ length: barCount }, (_, i) => (
+ <span
+ key={i}
+ aria-hidden="true"
+ className={cn(
+ "shrink-0 rounded-[2px] transition-colors duration-200",
+ getBarClassName(i)
+ )}
+ style={{
+ width: BAR_WIDTH,
+ height: BAR_HEIGHT,
+ ...getBarStyle(i)
+ }}
+ />
+ ))}
<span className="sr-only">{Math.round(percentage)}%</span>
</div>
</div>
diff --git a/packages/react/src/Combobox.tsx b/packages/react/src/Combobox.tsx
index 78d94104cf..2bad7ce1dd 100644
--- a/packages/react/src/Combobox.tsx
+++ b/packages/react/src/Combobox.tsx
@@ -5,6 +5,7 @@ import { forwardRef, useMemo, useRef, useState } from "react";
import { LuCheck, LuPlus, LuSettings2, LuX } from "react-icons/lu";
import {
Command,
+ CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
@@ -235,6 +236,7 @@ function VirtualizedCommand({
placeholder={t`Search...`}
className="h-9"
/>
+ <CommandEmpty>{t`No option found.`}</CommandEmpty>
<div
ref={parentRef}
className="overflow-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent pt-1"
diff --git a/packages/react/src/Select.tsx b/packages/react/src/Select.tsx
index f093dc2f15..6e79028315 100644
--- a/packages/react/src/Select.tsx
+++ b/packages/react/src/Select.tsx
@@ -21,7 +21,7 @@ const SelectGroup = SelectPrimitive.Group;
const SelectValue = SelectPrimitive.Value;
const selectTriggerVariants = cva(
- "bg-transparent text-foreground flex w-full items-center justify-between whitespace-nowrap rounded-md border border-input shadow-xs transition-[color,box-shadow] data-[placeholder]:text-muted-foreground outline-none focus:border-ring focus:ring-[3px] focus:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:ring-destructive/40 [&>span]:line-clamp-1",
+ "bg-transparent text-foreground flex w-full items-center justify-between whitespace-nowrap rounded-md border border-input shadow-xs transition-[color,box-shadow] data-[placeholder]:text-muted-foreground outline-none focus:border-ring focus:ring-[3px] focus:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>span]:line-clamp-1",
{
variants: {
size: {
diff --git a/scripts/pr-complexity/index.ts b/scripts/pr-complexity/index.ts
index 9b84f881ea..08d171ed65 100644
--- a/scripts/pr-complexity/index.ts
+++ b/scripts/pr-complexity/index.ts
@@ -127,6 +127,9 @@ async function ensureLabel(name: string, color: string, description: string) {
});
return;
}
+ if (isOctokitError(error, 403)) {
+ return;
+ }
throw error;
}
}