Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(production): copy a job's method from another job + source method version selection (#1553)
Naveen Kashyaped0bdebd958f
diff --git a/.claude/rules/supersession-system.md b/.claude/rules/supersession-system.mdindex 88eba5bb5e..55c32a35fc 100644--- a/.claude/rules/supersession-system.md+++ b/.claude/rules/supersession-system.md@@ -66,14 +66,14 @@ the factors.garbage. The walk builds into a SECOND map; mutating in place made the resultdepend on iteration order. Pinned by `lib/supersession-pick.test.ts`.-## get-method: three flows, one invariant+## get-method: four flows, one invariant-`itemToJob`, `itemToJobMakeMethod`, `quoteLineToJob` each build `jobMaterial`-rows independently. **Resolve the swap BEFORE any field derives from the item.**+`itemToJob`, `itemToJobMakeMethod`, `quoteLineToJob`, `jobToJob` each build+`jobMaterial` rows independently. **Resolve the swap BEFORE any field derives from the item.**Building the row first and patching it afterwards is how`itemScrapPercentage` was left on the predecessor for years: the patch list was-hand-written and the field was simply absent from it. All three now resolve+hand-written and the field was simply absent from it. All four now resolve`itemId` at the top of the row builder, so every derived field — scrap rate,bin, cost, tracking flags — follows automatically, including fields added later.@@ -86,7 +86,7 @@ there under-explodes the entire sub-tree — every row below looks individuallycorrect on a wrong base.`loadSupersessionRedirect` is loaded **once per request**, before the-transaction, in all three flows. It pages with `fetchAll` + `.order("itemId")`;+transaction, in all four flows. It pages with `fetchAll` + `.order("itemId")`;a bare select stops at PostgREST's 1000-row cap and would silently redirect adifferent subset than MRP.@@ -104,9 +104,10 @@ re-derives it when the stored value is NULL — which a NOT NULL column never is## Known gaps-- `quoteLineToJob` never swaps **made** sub-assemblies — documented as "a later- layer". Fail-safe (you get the quoted structure), but it disagrees with- MRP, which has already redirected that demand.+- `quoteLineToJob` and `jobToJob` never swap **made** sub-assemblies —+ documented as "a later layer". Fail-safe (you get the quoted/copied+ structure), but it disagrees with MRP, which has already redirected that+ demand.- A Make→Buy successor leaves the line on the predecessor, and that fallthroughis indistinguishable from "successor's make method isn't Active" or "item readfailed".diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.tsindex 76bb54164f..9045e58ef3 100644--- a/apps/erp/app/modules/production/production.models.ts+++ b/apps/erp/app/modules/production/production.models.ts@@ -867,6 +867,7 @@ export const jobMaterialValidatorForReleasedJob = baseMaterialValidatorexport const getJobMethodValidator = z.object({sourceId: z.string().min(1, { message: "Source ID is required" }),targetId: z.string().min(1, { message: "Please select a source method" }),+ versionId: zfd.text(z.string().optional()),billOfMaterial: zfd.checkbox(),billOfProcess: zfd.checkbox(),parameters: zfd.checkbox(),diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex d471ada48f..36c468fba5 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -28,6 +28,7 @@ import type { ExpressionBuilder } from "kysely";import { nanoid } from "nanoid";import type { z } from "zod";import type { StorageItem } from "~/types";+import { getEdgeFunctionErrorMessage } from "~/utils/error";import type { GenericQueryFilters } from "~/utils/query";import {getGenericFilter,@@ -1213,14 +1214,19 @@ export async function getJobsBySalesOrderLine(export async function getJobsList(client: SupabaseClient<Database>,- companyId: string+ companyId: string,+ statuses?: Database["public"]["Enums"]["jobStatus"][]) {return fetchAllFromTable<{id: string;jobId: string;- }>(client, "job", "id, jobId", (query) =>- query.eq("companyId", companyId).order("jobId")- );+ }>(client, "job", "id, jobId", (query) => {+ let filtered = query.eq("companyId", companyId);+ if (statuses && statuses.length > 0) {+ filtered = filtered.in("status", statuses);+ }+ return filtered.order("jobId");+ });}export async function getJobMakeMethodById(@@ -3928,13 +3934,14 @@ export async function setJobOperationToolStepLink(export async function upsertJobMethod(client: SupabaseClient<Database>,- type: "itemToJob" | "quoteLineToJob",+ type: "itemToJob" | "quoteLineToJob" | "jobToJob",jobMethod: {sourceId: string;targetId: string;companyId: string;userId: string;configuration?: Record<string, unknown>;+ versionId?: string;parts?: {billOfMaterial: boolean;billOfProcess: boolean;@@ -3946,12 +3953,13 @@ export async function upsertJobMethod(}) {const body: {- type: "itemToJob" | "quoteLineToJob";+ type: "itemToJob" | "quoteLineToJob" | "jobToJob";sourceId: string;targetId: string;companyId: string;userId: string;configuration?: Record<string, unknown>;+ versionId?: string;parts?: {billOfMaterial: boolean;billOfProcess: boolean;@@ -3973,6 +3981,11 @@ export async function upsertJobMethod(body.configuration = jobMethod.configuration;}+ // A specific source method version (itemToJob only); absent = active method+ if (jobMethod.versionId) {+ body.versionId = jobMethod.versionId;+ }+// Only add parts if it existsif (jobMethod.parts !== undefined) {body.parts = jobMethod.parts;@@ -3982,7 +3995,15 @@ export async function upsertJobMethod(body});if (getMethodResult.error) {- return getMethodResult;+ return {+ data: null,+ error: {+ message: await getEdgeFunctionErrorMessage(+ getMethodResult.error,+ "Failed to get job method"+ )+ } as PostgrestError+ };}return recalculateJobRequirements(client, {id: jobMethod.targetId,@@ -3999,6 +4020,7 @@ export async function upsertJobMaterialMakeMethod(companyId: string;userId: string;configuration?: Record<string, unknown>;+ versionId?: string;parts?: {billOfMaterial: boolean;billOfProcess: boolean;@@ -4016,6 +4038,7 @@ export async function upsertJobMaterialMakeMethod(companyId: string;userId: string;configuration?: Record<string, unknown>;+ versionId?: string;parts?: {billOfMaterial: boolean;billOfProcess: boolean;@@ -4037,6 +4060,11 @@ export async function upsertJobMaterialMakeMethod(body.configuration = jobMaterial.configuration;}+ // A specific source method version; absent = active method+ if (jobMaterial.versionId) {+ body.versionId = jobMaterial.versionId;+ }+// Only add parts if it existsif (jobMaterial.parts !== undefined) {body.parts = jobMaterial.parts;@@ -4049,7 +4077,12 @@ export async function upsertJobMaterialMakeMethod(if (error) {return {data: null,- error: { message: "Failed to pull method" } as PostgrestError+ error: {+ message: await getEdgeFunctionErrorMessage(+ error,+ "Failed to pull method"+ )+ } as PostgrestError};}diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsxindex da300c110f..923f5d9fc8 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx@@ -1,5 +1,5 @@import { useCarbon } from "@carbon/auth";-import { SelectControlled, ValidatedForm } from "@carbon/form";+import { ValidatedForm } from "@carbon/form";import {Alert,AlertTitle,@@ -30,10 +30,11 @@ import {VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { Fragment, useEffect, useState } from "react";+import { Fragment, useEffect, useMemo, useRef, useState } from "react";import {LuBlocks,LuChevronRight,+ LuCirclePlay,LuGitBranch,LuGitFork,LuGitMerge,@@ -44,7 +45,14 @@ import { RiProgress4Line } from "react-icons/ri";import { Link, useFetcher, useLocation, useParams } from "react-router";import { PrintButton } from "~/components";import { ConfiguratorModal } from "~/components/Configurator/ConfiguratorForm";-import { Hidden, Item, Submit, useConfigurableItems } from "~/components/Form";+import {+ Combobox,+ Hidden,+ Item,+ SelectControlled,+ Submit,+ useConfigurableItems+} from "~/components/Form";import type { Tree } from "~/components/TreeView";import { usePermissions, useRouteData, useUser } from "~/hooks";import {@@ -225,6 +233,67 @@ const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {}};+ // Source-method versions for the Get Method modal's item tab. Separate from+ // `makeMethods` above: Save Method lists Draft versions only (the writable+ // ones), while Get Method can read ANY version of the source item's method.+ const [sourceMakeMethods, setSourceMakeMethods] = useState<+ { label: JSX.Element; value: string }[]+ >([]);+ const [selectedSourceVersion, setSelectedSourceVersion] = useState<+ string | null+ >(null);++ const sourceVersionRequestRef = useRef(0);+ const getSourceMakeMethods = async (itemId: string | null) => {+ const requestId = ++sourceVersionRequestRef.current;+ setSourceMakeMethods([]);+ setSelectedSourceVersion(null);+ if (!itemId || !carbon) return;++ const [versions, activeVersion] = await Promise.all([+ carbon+ .from("makeMethod")+ .select("id, version, status")+ .eq("itemId", itemId)+ .eq("companyId", companyId)+ .order("version", { ascending: false }),+ // The default mirrors what get-method uses when no version is chosen:+ // the Active version, else the highest non-archived (which can be a+ // Draft). The view owns that ranking — don't re-derive it here.+ carbon+ .from("activeMakeMethods")+ .select("id")+ .eq("itemId", itemId)+ .eq("companyId", companyId)+ .maybeSingle()+ ]);++ // A newer selection superseded this load — drop it, or a slow item A's+ // versions could render (and submit a versionId) against item B's sourceId.+ if (requestId !== sourceVersionRequestRef.current) return;++ if (versions.error) {+ toast.error(versions.error.message);+ return;+ }++ setSourceMakeMethods(+ (versions.data ?? []).map(({ id, version, status }) => ({+ label: (+ <div className="flex items-center gap-2">+ <Badge variant="outline">V{version}</Badge>{" "}+ <MakeMethodVersionStatus status={status} />+ </div>+ ),+ value: id+ }))+ );++ if (activeVersion.data?.id) {+ setSelectedSourceVersion(activeVersion.data.id);+ }+ };+useMount(() => {if (isJobMethod && routeData?.job.itemId) {getMakeMethods(routeData.job.itemId);@@ -242,7 +311,13 @@ const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {isLoading={isGetMethodLoading}isDisabled={isDisabled || isGetMethodLoading}leftIcon={<LuGitBranch />}- onClick={getMethodModal.onOpen}+ onClick={() => {+ // The modal's Item picker opens empty — clear any versions+ // loaded on a previous open so the two can't disagree.+ setSourceMakeMethods([]);+ setSelectedSourceVersion(null);+ getMethodModal.onOpen();+ }}><Trans>Get Method</Trans></MenubarItem>@@ -302,300 +377,327 @@ const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {</HStack></Menubar>)}- {getMethodModal.isOpen && (- <Modal- open- onOpenChange={(open) => {- if (!open) {- getMethodModal.onClose();- }- }}- >- <ModalContent>- <ValidatedForm- method="post"- fetcher={fetcher}- action={path.to.jobMethodGet}- validator={getJobMethodValidator}- onSubmit={getMethodModal.onClose}- >- <ModalHeader>- <ModalTitle>- <Trans>Get Method</Trans>- </ModalTitle>- <ModalDescription>- Overwrite the job method with the source method- </ModalDescription>- </ModalHeader>- <ModalBody>- <Tabs defaultValue="item" className="w-full">- {isJobMethod && (- <TabsList className="grid w-full grid-cols-2 mb-4">- <TabsTrigger value="item">- <LuBlocks className="mr-2" /> Item- </TabsTrigger>- <TabsTrigger value="quote">- <RiProgress4Line className="mr-2" />- <Trans>Quote</Trans>- </TabsTrigger>- </TabsList>- )}- <TabsContent value="item">- {isJobMethod ? (- <>- <Hidden name="type" value="item" />- <Hidden name="targetId" value={jobId} />- </>- ) : (- <>- <Hidden name="type" value="method" />- <Hidden name="targetId" value={methodId!} />- </>- )}-- <VStack spacing={4}>- {hasMethods && (- <Alert variant="destructive">- <LuTriangleAlert className="h-4 w-4" />- <AlertTitle>- <Trans>- This will overwrite the existing job method- </Trans>- </AlertTitle>- </Alert>- )}- <Item- name="sourceId"- label={t`Source Method`}- termId="method"- type={(routeData?.job.itemType ?? "Part") as "Part"}- blacklist={configurableItemIds}- includeInactive={includeInactive === true}- locationId={routeData?.job?.locationId ?? undefined}- replenishmentSystem="Make"- />- <div className="flex items-center space-x-2">- <Checkbox- id="include-inactive"- checked={includeInactive}- onCheckedChange={setIncludeInactive}- />- <label- htmlFor="include-inactive"- className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"- >- <Trans>Include Inactive</Trans>- </label>- </div>-- <AdvancedSection onChange={setHasMethodParts} />- </VStack>- </TabsContent>- <TabsContent value="quote">- <Hidden name="type" value="quoteLine" />- <Hidden name="targetId" value={jobId} />- <VStack spacing={4}>- <QuoteLineMethodForm />- <AdvancedSection onChange={setHasMethodParts} />- </VStack>- </TabsContent>- </Tabs>- </ModalBody>- <ModalFooter>- <Button onClick={getMethodModal.onClose} variant="secondary">- <Trans>Cancel</Trans>- </Button>- <Submit- isDisabled={!hasMethodParts}- variant={hasMethods ? "destructive" : "primary"}- >- <Trans>Confirm</Trans>- </Submit>- </ModalFooter>- </ValidatedForm>- </ModalContent>- </Modal>- )}- {saveMethodModal.isOpen && (- <Modal- open- onOpenChange={(open) => {- if (!open) {- saveMethodModal.onClose();- }- }}- >- <ModalContent>- <ValidatedForm- method="post"- fetcher={fetcher}- action={path.to.jobMethodSave}- validator={getJobMethodValidator}- defaultValues={{- // @ts-expect-error- itemId: isJobMethod- ? (routeData?.job?.itemId ?? undefined)- : undefined- }}- onSubmit={saveMethodModal.onClose}- >- <ModalHeader>- <ModalTitle>- <Trans>Save Method</Trans>- </ModalTitle>- <ModalDescription>- Overwrite the target manufacturing method with the job method- </ModalDescription>- </ModalHeader>- <ModalBody>- {isJobMethod ? (- <>- <Hidden name="type" value="job" />- <Hidden name="sourceId" value={jobId} />- </>- ) : (- <>- <Hidden name="type" value="method" />- <Hidden name="sourceId" value={methodId!} />- </>+ <Modal+ open={getMethodModal.isOpen}+ onOpenChange={(open) => {+ if (!open) {+ getMethodModal.onClose();+ }+ }}+ >+ <ModalContent>+ <ValidatedForm+ method="post"+ fetcher={fetcher}+ action={path.to.jobMethodGet}+ validator={getJobMethodValidator}+ onSubmit={getMethodModal.onClose}+ >+ <ModalHeader>+ <ModalTitle>+ <Trans>Get Method</Trans>+ </ModalTitle>+ <ModalDescription>+ Overwrite the job method with the source method+ </ModalDescription>+ </ModalHeader>+ <ModalBody>+ <Tabs defaultValue="item" className="w-full">+ {isJobMethod && (+ <TabsList className="grid w-full grid-cols-3 mb-4">+ <TabsTrigger value="item">+ <LuBlocks className="mr-2" /> Item+ </TabsTrigger>+ <TabsTrigger value="quote">+ <RiProgress4Line className="mr-2" />+ <Trans>Quote</Trans>+ </TabsTrigger>+ <TabsTrigger value="job">+ <LuCirclePlay className="mr-2" />+ <Trans>Job</Trans>+ </TabsTrigger>+ </TabsList>)}+ <TabsContent value="item">+ {isJobMethod ? (+ <>+ <Hidden name="type" value="item" />+ <Hidden name="targetId" value={jobId} />+ </>+ ) : (+ <>+ <Hidden name="type" value="method" />+ <Hidden name="targetId" value={methodId!} />+ </>+ )}- <VStack spacing={4}>- <Alert variant="destructive">- <LuTriangleAlert className="h-4 w-4" />- <AlertTitle>- <Trans>- This will overwrite the existing manufacturing method- and the latest versions of all subassemblies.- </Trans>- </AlertTitle>- </Alert>- <Item- name="itemId"- label={t`Target Method`}- termId="method"- type={(routeData?.job?.itemType ?? "Part") as "Part"}- blacklist={configurableItemIds}- locationId={routeData?.job?.locationId ?? undefined}- onChange={(value) => {- if (value) {- getMakeMethods(value?.value);- } else {- setMakeMethods([]);- setSelectedMakeMethod(null);- }- }}- includeInactive={includeInactive === true}- replenishmentSystem="Make"- />- <SelectControlled- name="targetId"- options={makeMethods}- label={t`Version`}- value={selectedMakeMethod ?? undefined}- onChange={(value) => {- if (value) {- setSelectedMakeMethod(value?.value);- } else {- setSelectedMakeMethod(null);+ <VStack spacing={4}>+ {hasMethods && (+ <Alert variant="destructive">+ <LuTriangleAlert className="h-4 w-4" />+ <AlertTitle>+ <Trans>+ This will overwrite the existing job method+ </Trans>+ </AlertTitle>+ </Alert>+ )}+ <Item+ name="sourceId"+ label={t`Source Method`}+ termId="method"+ type={(routeData?.job.itemType ?? "Part") as "Part"}+ blacklist={configurableItemIds}+ includeInactive={includeInactive === true}+ locationId={routeData?.job?.locationId ?? undefined}+ replenishmentSystem="Make"+ onChange={(value) => {+ getSourceMakeMethods(value?.value ?? null);+ }}+ />+ <SelectControlled+ name="versionId"+ options={sourceMakeMethods}+ label={t`Version`}+ value={selectedSourceVersion ?? undefined}+ onChange={(value) => {+ if (value) {+ setSelectedSourceVersion(value?.value);+ } else {+ setSelectedSourceVersion(null);+ }+ }}+ placeholder={+ sourceMakeMethods.length === 0+ ? t`No versions available`+ : undefined}- }}- placeholder={- makeMethods.length === 0- ? t`No draft versions available`- : undefined- }- />- <div className="flex items-center space-x-2">- <Checkbox- id="include-inactive"- checked={includeInactive}- onCheckedChange={setIncludeInactive}/>- <label- htmlFor="include-inactive"- className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"- >- <Trans>Include Inactive</Trans>- </label>- </div>-- <AdvancedSection onChange={setHasMethodParts} />- </VStack>- </ModalBody>- <ModalFooter>- <Button onClick={saveMethodModal.onClose} variant="secondary">- <Trans>Cancel</Trans>- </Button>- <Submit- variant={hasMethods ? "destructive" : "primary"}- isDisabled={- !selectedMakeMethod ||- !permissions.can("update", "parts") ||- !hasMethodParts- }- >- <Trans>Confirm</Trans>- </Submit>- </ModalFooter>- </ValidatedForm>- </ModalContent>- </Modal>- )}- {configureSelectModal.isOpen && (- <Modal- open- onOpenChange={(open) => {- if (!open) {- configureSelectModal.onClose();- }- }}- >- <ModalContent>- <ValidatedForm validator={getJobMethodValidator}>- <ModalHeader>- <ModalTitle>- <Trans>Configure Item</Trans>- </ModalTitle>- <ModalDescription>- <Trans>Select an item to configure</Trans>- </ModalDescription>- </ModalHeader>- <ModalBody>+ <div className="flex items-center space-x-2">+ <Checkbox+ id="include-inactive"+ checked={includeInactive}+ onCheckedChange={setIncludeInactive}+ />+ <label+ htmlFor="include-inactive"+ className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"+ >+ <Trans>Include Inactive</Trans>+ </label>+ </div>++ <AdvancedSection onChange={setHasMethodParts} />+ </VStack>+ </TabsContent>+ <TabsContent value="quote">+ <Hidden name="type" value="quoteLine" />+ <Hidden name="targetId" value={jobId} />+ <VStack spacing={4}>+ <QuoteLineMethodForm />+ <AdvancedSection onChange={setHasMethodParts} />+ </VStack>+ </TabsContent>+ <TabsContent value="job">+ <Hidden name="type" value="job" />+ <Hidden name="targetId" value={jobId} />+ <VStack spacing={4}>+ <CompletedJobMethodForm currentJobId={jobId} />+ <AdvancedSection onChange={setHasMethodParts} />+ </VStack>+ </TabsContent>+ </Tabs>+ </ModalBody>+ <ModalFooter>+ <Button onClick={getMethodModal.onClose} variant="secondary">+ <Trans>Cancel</Trans>+ </Button>+ <Submit+ isDisabled={!hasMethodParts}+ variant={hasMethods ? "destructive" : "primary"}+ >+ <Trans>Confirm</Trans>+ </Submit>+ </ModalFooter>+ </ValidatedForm>+ </ModalContent>+ </Modal>+ <Modal+ open={saveMethodModal.isOpen}+ onOpenChange={(open) => {+ if (!open) {+ saveMethodModal.onClose();+ }+ }}+ >+ <ModalContent>+ <ValidatedForm+ method="post"+ fetcher={fetcher}+ action={path.to.jobMethodSave}+ validator={getJobMethodValidator}+ defaultValues={{+ // @ts-expect-error+ itemId: isJobMethod+ ? (routeData?.job?.itemId ?? undefined)+ : undefined+ }}+ onSubmit={saveMethodModal.onClose}+ >+ <ModalHeader>+ <ModalTitle>+ <Trans>Save Method</Trans>+ </ModalTitle>+ <ModalDescription>+ Overwrite the target manufacturing method with the job method+ </ModalDescription>+ </ModalHeader>+ <ModalBody>+ {isJobMethod ? (+ <>+ <Hidden name="type" value="job" />+ <Hidden name="sourceId" value={jobId} />+ </>+ ) : (+ <>+ <Hidden name="type" value="method" />+ <Hidden name="sourceId" value={methodId!} />+ </>+ )}++ <VStack spacing={4}>+ <Alert variant="destructive">+ <LuTriangleAlert className="h-4 w-4" />+ <AlertTitle>+ <Trans>+ This will overwrite the existing manufacturing method and+ the latest versions of all subassemblies.+ </Trans>+ </AlertTitle>+ </Alert><Item- name="sourceId"- label={t`Item`}- value={selectedConfigureItemId ?? undefined}+ name="itemId"+ label={t`Target Method`}+ termId="method"type={(routeData?.job?.itemType ?? "Part") as "Part"}- includeInactive={includeInactive === true}- whitelist={configurableItemIds}+ blacklist={configurableItemIds}locationId={routeData?.job?.locationId ?? undefined}- replenishmentSystem="Make"onChange={(value) => {- setSelectedConfigureItemId(value?.value ?? null);+ if (value) {+ getMakeMethods(value?.value);+ } else {+ setMakeMethods([]);+ setSelectedMakeMethod(null);+ }}}+ includeInactive={includeInactive === true}+ replenishmentSystem="Make"/>- </ModalBody>- <ModalFooter>- <Button- onClick={configureSelectModal.onClose}- variant="secondary"- >- <Trans>Cancel</Trans>- </Button>- <Button- isDisabled={!selectedConfigureItemId}- onClick={() =>- handleConfigureItemSelect(selectedConfigureItemId)+ <SelectControlled+ name="targetId"+ options={makeMethods}+ label={t`Version`}+ value={selectedMakeMethod ?? undefined}+ onChange={(value) => {+ if (value) {+ setSelectedMakeMethod(value?.value);+ } else {+ setSelectedMakeMethod(null);+ }+ }}+ placeholder={+ makeMethods.length === 0+ ? t`No draft versions available`+ : undefined}- >- <Trans>Next</Trans>- </Button>- </ModalFooter>- </ValidatedForm>- </ModalContent>- </Modal>- )}+ />+ <div className="flex items-center space-x-2">+ <Checkbox+ id="include-inactive"+ checked={includeInactive}+ onCheckedChange={setIncludeInactive}+ />+ <label+ htmlFor="include-inactive"+ className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"+ >+ <Trans>Include Inactive</Trans>+ </label>+ </div>++ <AdvancedSection onChange={setHasMethodParts} />+ </VStack>+ </ModalBody>+ <ModalFooter>+ <Button onClick={saveMethodModal.onClose} variant="secondary">+ <Trans>Cancel</Trans>+ </Button>+ <Submit+ variant={hasMethods ? "destructive" : "primary"}+ isDisabled={+ !selectedMakeMethod ||+ !permissions.can("update", "parts") ||+ !hasMethodParts+ }+ >+ <Trans>Confirm</Trans>+ </Submit>+ </ModalFooter>+ </ValidatedForm>+ </ModalContent>+ </Modal>+ <Modal+ open={configureSelectModal.isOpen}+ onOpenChange={(open) => {+ if (!open) {+ configureSelectModal.onClose();+ }+ }}+ >+ <ModalContent>+ <ValidatedForm validator={getJobMethodValidator}>+ <ModalHeader>+ <ModalTitle>+ <Trans>Configure Item</Trans>+ </ModalTitle>+ <ModalDescription>+ <Trans>Select an item to configure</Trans>+ </ModalDescription>+ </ModalHeader>+ <ModalBody>+ <Item+ name="sourceId"+ label={t`Item`}+ value={selectedConfigureItemId ?? undefined}+ type={(routeData?.job?.itemType ?? "Part") as "Part"}+ includeInactive={includeInactive === true}+ whitelist={configurableItemIds}+ locationId={routeData?.job?.locationId ?? undefined}+ replenishmentSystem="Make"+ onChange={(value) => {+ setSelectedConfigureItemId(value?.value ?? null);+ }}+ />+ </ModalBody>+ <ModalFooter>+ <Button+ onClick={configureSelectModal.onClose}+ variant="secondary"+ >+ <Trans>Cancel</Trans>+ </Button>+ <Button+ isDisabled={!selectedConfigureItemId}+ onClick={() =>+ handleConfigureItemSelect(selectedConfigureItemId)+ }+ >+ <Trans>Next</Trans>+ </Button>+ </ModalFooter>+ </ValidatedForm>+ </ModalContent>+ </Modal>{configuratorModal.isOpen && (<ConfiguratorModalopen@@ -621,6 +723,37 @@ const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {);};+function CompletedJobMethodForm({ currentJobId }: { currentJobId: string }) {+ const { t } = useLingui();+ const jobsFetcher = useFetcher<{+ data: { id: string; jobId: string }[] | null;+ }>();++ useMount(() => {+ jobsFetcher.load(`${path.to.api.jobs}?status=Completed&status=Closed`);+ });++ const jobOptions = useMemo(+ () =>+ jobsFetcher.data?.data+ ?.filter((job) => job.id !== currentJobId)+ .map((job) => ({+ label: job.jobId,+ value: job.id+ })) ?? [],+ [jobsFetcher.data, currentJobId]+ );++ return (+ <Combobox+ name="sourceId"+ label={t`Source Job`}+ options={jobOptions}+ placeholder={t`Select a completed job`}+ />+ );+}+function AdvancedSection({onChange}: {diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex 15a716430a..ab4bc07d94 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-09-01T10:00:04.633Z",+ "generated": "2026-09-02T18:59:20.006Z","totalTools": 1488,"modules": 15,"tools": [@@ -20754,17 +20754,23 @@"module": "production","classification": "READ","description": "get jobs list",- "paramCount": 0,+ "paramCount": 1,"serviceParams": ["client",- "companyId"+ "companyId",+ "statuses"],"injectAuth": ["companyId"],"schema": {"type": "object",- "properties": {}+ "properties": {+ "statuses": {+ "type": "array",+ "items": {}+ }+ }}},{@@ -23838,7 +23844,8 @@"type": "string","enum": ["itemToJob",- "quoteLineToJob"+ "quoteLineToJob",+ "jobToJob"]},"jobMethod": {@@ -23851,6 +23858,9 @@"type": "string"},"configuration": {},+ "versionId": {+ "type": "string"+ },"parts": {"type": "object","properties": {@@ -23900,7 +23910,7 @@"module": "production","classification": "WRITE","description": "upsert job material make method",- "paramCount": 4,+ "paramCount": 5,"serviceParams": ["client","jobMaterial"@@ -23920,6 +23930,9 @@"type": "string"},"configuration": {},+ "versionId": {+ "type": "string"+ },"parts": {"type": "object","properties": {diff --git a/apps/erp/app/routes/api+/production.jobs.ts b/apps/erp/app/routes/api+/production.jobs.tsindex 9a4611d0fc..8eaded38b2 100644--- a/apps/erp/app/routes/api+/production.jobs.ts+++ b/apps/erp/app/routes/api+/production.jobs.ts@@ -1,11 +1,19 @@import { requirePermissions } from "@carbon/auth/auth.server";+import type { Database } from "@carbon/database";import type { LoaderFunctionArgs } from "react-router";-import { getJobsList } from "~/modules/production";+import { getJobsList, jobStatus } from "~/modules/production";export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {view: "production"});- return await getJobsList(client, companyId);+ const url = new URL(request.url);+ const statuses = url.searchParams+ .getAll("status")+ .filter((status): status is Database["public"]["Enums"]["jobStatus"] =>+ jobStatus.includes(status as (typeof jobStatus)[number])+ );++ return await getJobsList(client, companyId, statuses);}diff --git a/apps/erp/app/routes/x+/job+/methods+/get.tsx b/apps/erp/app/routes/x+/job+/methods+/get.tsxindex de62a9fdf5..32453926ec 100644--- a/apps/erp/app/routes/x+/job+/methods+/get.tsx+++ b/apps/erp/app/routes/x+/job+/methods+/get.tsx@@ -32,7 +32,7 @@ export async function action({ request }: ActionFunctionArgs) {return validationError(validation.error);}- if (["item", "quoteLine"].includes(type)) {+ if (["item", "quoteLine", "job"].includes(type)) {const jobMethodPayload: any = {...validation.data,companyId,@@ -54,7 +54,11 @@ export async function action({ request }: ActionFunctionArgs) {const jobMethod = await upsertJobMethod(serviceRole,- type === "item" ? "itemToJob" : "quoteLineToJob",+ type === "item"+ ? "itemToJob"+ : type === "job"+ ? "jobToJob"+ : "quoteLineToJob",jobMethodPayload);@@ -84,7 +88,9 @@ export async function action({ request }: ActionFunctionArgs) {}return {- error: jobMethod.error ? "Failed to get job method" : null+ error: jobMethod.error+ ? (jobMethod.error.message ?? "Failed to get job method")+ : null};}@@ -116,7 +122,8 @@ export async function action({ request }: ActionFunctionArgs) {if (makeMethod.error) {return {error: makeMethod.error- ? "Failed to update method from job method"+ ? (makeMethod.error.message ??+ "Failed to update method from job method"): null};}diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.tsindex 8c6bd91265..8ceb8ed58c 100644--- a/packages/database/supabase/functions/get-method/index.ts+++ b/packages/database/supabase/functions/get-method/index.ts@@ -24,6 +24,7 @@ import {JobMethodTreeItem,QuoteMethodTreeItem,traverseJobMethod,+ traverseJobMethodAsync,traverseQuoteMethod,} from "../lib/methods.ts";import { KyselyDatabase } from "../lib/postgres/index.ts";@@ -157,6 +158,7 @@ const payloadValidator = z.object({"itemToQuoteMakeMethod","jobMakeMethodToItem","jobToItem",+ "jobToJob","makeMethodToMakeMethod","procedureToOperation","quoteLineToItem",@@ -171,6 +173,9 @@ const payloadValidator = z.object({userId: z.string(),configuration: z.record(z.unknown()).optional(),parts: partsValidator,+ // A specific source makeMethod version (itemToJob / itemToJobMakeMethod+ // only). Absent = the item's active method, as before.+ versionId: z.string().optional(),});serve(async (req: Request) => {@@ -179,8 +184,16 @@ serve(async (req: Request) => {const payload = await req.json();try {- const { type, sourceId, targetId, companyId, userId, configuration, parts } =- payloadValidator.parse(payload);+ const {+ type,+ sourceId,+ targetId,+ companyId,+ userId,+ configuration,+ parts,+ versionId,+ } = payloadValidator.parse(payload);console.log({function: "get-method",@@ -191,6 +204,7 @@ serve(async (req: Request) => {userId,parts,configuration,+ versionId,});const client = await requirePermissions(req, companyId, userId, { update: "production" });@@ -430,12 +444,23 @@ serve(async (req: Request) => {const [makeMethod, jobMakeMethod, workCenters, supplierProcesses, job] =await Promise.all([- client- .from("activeMakeMethods")- .select("*")- .eq("itemId", itemId)- .eq("companyId", companyId)- .single(),+ // A chosen version overrides the default active-method lookup; it+ // is re-read under itemId + companyId so a foreign or mismatched+ // makeMethod id can never be exploded.+ versionId+ ? client+ .from("makeMethod")+ .select("*")+ .eq("id", versionId)+ .eq("itemId", itemId)+ .eq("companyId", companyId)+ .single()+ : client+ .from("activeMakeMethods")+ .select("*")+ .eq("itemId", itemId)+ .eq("companyId", companyId)+ .single(),client.from("jobMakeMethod").select("*")@@ -1666,12 +1691,23 @@ serve(async (req: Request) => {const [makeMethod, jobMakeMethod, workCenters, supplierProcesses] =await Promise.all([- client- .from("activeMakeMethods")- .select("*")- .eq("itemId", itemId)- .eq("companyId", companyId)- .single(),+ // A chosen version overrides the default active-method lookup; it+ // is re-read under itemId + companyId so a foreign or mismatched+ // makeMethod id can never be exploded.+ versionId+ ? client+ .from("makeMethod")+ .select("*")+ .eq("id", versionId)+ .eq("itemId", itemId)+ .eq("companyId", companyId)+ .single()+ : client+ .from("activeMakeMethods")+ .select("*")+ .eq("itemId", itemId)+ .eq("companyId", companyId)+ .single(),client.from("jobMakeMethod").select("*")@@ -4115,6 +4151,757 @@ serve(async (req: Request) => {break;}+ case "jobToJob": {+ const sourceJobId = sourceId;+ const targetJobId = targetId;+ if (!sourceJobId || !targetJobId) {+ throw new Error("Invalid sourceId or targetId");+ }+ if (sourceJobId === targetJobId) {+ throw new Error("Cannot copy a job method onto itself");+ }++ // Assembly ops whose steps were materialized from an instruction —+ // material ↔ step links flush after the jobMaterial rows exist.+ const assemblyOperationsToLink: Array<{+ operationId: string;+ assemblyInstructionId: string;+ }> = [];++ // The embeds defeat the generated response types (as elsewhere in this+ // file), so the paged rows are typed explicitly.+ type SourceJobMaterialRow =+ Database["public"]["Tables"]["jobMaterial"]["Row"] & {+ jobMaterialStep: {+ jobOperationStepId: string | null;+ quantity: number | null;+ }[];+ };+ type SourceJobOperationRow =+ Database["public"]["Tables"]["jobOperation"]["Row"] & {+ jobOperationTool: (Database["public"]["Tables"]["jobOperationTool"]["Row"] & {+ jobOperationToolStep: { jobOperationStepId: string | null }[];+ })[];+ jobOperationParameter: Database["public"]["Tables"]["jobOperationParameter"]["Row"][];+ jobOperationStep: Database["public"]["Tables"]["jobOperationStep"]["Row"][];+ };++ // Paged: a bare select stops at PostgREST's 1000-row cap and would+ // silently copy a subset of a large job. The secondary `.order("id")`+ // makes paging stable across batches. Started here (not awaited) so the+ // reads below run concurrently with them.+ const sourceMaterialsPromise = fetchAll<SourceJobMaterialRow>(() =>+ client+ .from("jobMaterial")+ .select("*, jobMaterialStep(jobOperationStepId, quantity)")+ .eq("jobId", sourceJobId)+ .eq("companyId", companyId)+ .order("id")+ );+ const sourceOperationsPromise = fetchAll<SourceJobOperationRow>(() =>+ client+ .from("jobOperation")+ .select(+ "*, jobOperationTool(*, jobOperationToolStep(*)), jobOperationParameter(*), jobOperationStep(*)"+ )+ .eq("jobId", sourceJobId)+ .eq("companyId", companyId)+ .order("order", { ascending: true })+ .order("id")+ );++ const [+ targetJob,+ sourceJob,+ targetJobMakeMethod,+ sourceJobMakeMethod,+ ] = await Promise.all([+ client+ .from("job")+ .select("itemId, locationId, quantity, startDate, dueDate")+ .eq("id", targetJobId)+ .eq("companyId", companyId)+ .single(),+ // requirePermissions proved the CALLER may act in companyId; it proves+ // nothing about the record ids in the body. Re-read the source job+ // under companyId so a foreign job id can never be copied from.+ client+ .from("job")+ .select("id")+ .eq("id", sourceJobId)+ .eq("companyId", companyId)+ .single(),+ client+ .from("jobMakeMethod")+ .select("*")+ .eq("jobId", targetJobId)+ .is("parentMaterialId", null)+ .eq("companyId", companyId)+ .single(),+ client+ .from("jobMakeMethod")+ .select("*")+ .eq("jobId", sourceJobId)+ .is("parentMaterialId", null)+ .eq("companyId", companyId)+ .single(),+ ]);+ const [sourceMaterials, sourceOperations] = await Promise.all([+ sourceMaterialsPromise,+ sourceOperationsPromise,+ ]);++ if (targetJob.error) {+ throw new Error("Failed to get job");+ }+ if (sourceJob.error) {+ throw new Error("Failed to get source job");+ }+ if (targetJobMakeMethod.error || !targetJobMakeMethod.data) {+ throw new Error("Failed to get job make method");+ }+ if (sourceJobMakeMethod.error || !sourceJobMakeMethod.data) {+ throw new Error("Failed to get source job make method");+ }+ if (sourceMaterials.error) {+ throw new Error("Failed to get source job materials");+ }+ if (sourceOperations.error) {+ throw new Error("Failed to get source job operations");+ }++ const jobMethodTrees = await getJobMethodTree(+ client,+ sourceJobMakeMethod.data.id+ );+ if (jobMethodTrees.error) {+ throw new Error("Failed to get method tree");+ }+ const jobMethodTree = jobMethodTrees.data?.[0] as JobMethodTreeItem;+ if (!jobMethodTree) throw new Error("Method tree not found");++ // A process-only copy of a multi-level job cannot work: the sub-assembly+ // make methods only come into existence on the bill-of-material path, so+ // their operations would reference make methods that were never created+ // (jobOperation_jobMakeMethodId_fkey). Refuse with an authored message+ // instead of rolling back on the FK.+ if (!parts.billOfMaterial && parts.billOfProcess) {+ let hasSubAssemblies = false;+ traverseJobMethod(jobMethodTree, (node: JobMethodTreeItem) => {+ for (const child of node.children) {+ if (child.data.jobMaterialMakeMethodId) {+ hasSubAssemblies = true;+ }+ }+ });+ if (hasSubAssemblies) {+ throw new Error(+ "Copying only the bill of process from a job with sub-assemblies is not supported — include the bill of material as well"+ );+ }+ }++ // Loaded ONCE per request, before the transaction — as every *-ToJob+ // path does. The source job's rows were swapped live at ITS creation;+ // this re-resolves as-of the TARGET job's build date, so a supersession+ // that became effective since then still redirects the copy.+ const supersessionRedirect = await loadSupersessionRedirect(+ client,+ companyId,+ targetJob.data+ );++ let selfConsumedItem: string | null = null;+ traverseJobMethod(jobMethodTree, (node: JobMethodTreeItem) => {+ for (const child of node.children) {+ const resolvedItemId =+ child.data.methodType !== "Make to Order"+ ? (supersessionRedirect.get(child.data.itemId)?.to ??+ child.data.itemId)+ : child.data.itemId;+ if (resolvedItemId === targetJob.data.itemId) {+ selfConsumedItem = child.data.itemReadableId ?? resolvedItemId;+ }+ }+ });+ if (selfConsumedItem) {+ throw new Error(+ `The source job's method consumes ${selfConsumedItem}, which is the item this job produces — a job cannot consume its own output`+ );+ }++ const sourceMaterialRows = sourceMaterials.data ?? [];+ const sourceOperationRows = sourceOperations.data ?? [];++ const sourceMaterialById = new Map(+ sourceMaterialRows.map((m) => [m.id, m])+ );++ const sourceMaterialIdToJobMaterialId: Record<string, string> = {};+ const sourceMakeMethodIdToJobMakeMethodId: Record<string, string> = {};+ // Track estimated quantities for each SOURCE make method to set on operations+ const sourceMakeMethodIdToQuantities: Record<+ string,+ {+ targetQuantity: number;+ estimatedQuantity: number;+ totalWithScrap: number;+ }+ > = {};+ // Old job step id -> new job step id, for material/tool ↔ step links.+ const sourceStepsToJobSteps: Record<string, string> = {};+ const sourceOperationIdToJobOperationId: Record<string, string> = {};++ await db.transaction().execute(async (trx) => {+ // Delete existing jobMakeMethods, jobMaterials, and jobOperations for the target job+ await Promise.all([+ parts.billOfMaterial+ ? trx+ .deleteFrom("jobMakeMethod")+ .where((eb) =>+ eb.and([+ eb("jobId", "=", targetJobId),+ eb("parentMaterialId", "is not", null),+ ])+ )+ .execute()+ : Promise.resolve(),+ parts.billOfMaterial+ ? trx+ .deleteFrom("jobMaterial")+ .where("jobId", "=", targetJobId)+ .execute()+ : Promise.resolve(),+ // Prevent cascade deletion of materials when only replacing operations+ !parts.billOfMaterial && parts.billOfProcess+ ? trx+ .updateTable("jobMaterial")+ .set({ jobOperationId: null })+ .where("jobId", "=", targetJobId)+ .execute()+ : Promise.resolve(),+ parts.billOfProcess+ ? trx+ .deleteFrom("jobOperation")+ .where("jobId", "=", targetJobId)+ .execute()+ : Promise.resolve(),+ ]);++ await traverseJobMethodAsync(+ jobMethodTree,+ async (node: JobMethodTreeItem) => {+ const jobMaterialInserts: Database["public"]["Tables"]["jobMaterial"]["Insert"][] =+ [];+ const jobMakeMethodInserts: Database["public"]["Tables"]["jobMakeMethod"]["Insert"][] =+ [];++ // Get the total quantity for this node (parent level) to pass to children+ // This is estimated + scrap for Make parts (what children use for their target calculation)+ let nodeTotalForChildren: number;+ if (node.data.isRoot) {+ // Root: target = TARGET job quantity — the source job's own+ // quantity is irrelevant; the tree carries per-parent quantities.+ const rootItemReplenishment = await trx+ .selectFrom("itemReplenishment")+ .select("scrapPercentage")+ .where("itemId", "=", node.data.itemId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ const rootScrapPercentage = Number(+ rootItemReplenishment?.scrapPercentage ?? 0+ );+ const rootTarget = targetJob.data?.quantity ?? 1;+ // Scrap applies to every method type (mirrors itemToJob)+ const rootScrapQuantity = scrapAllowance(+ rootTarget,+ rootScrapPercentage+ );+ const rootTotalWithScrap = rootTarget + rootScrapQuantity;+ const rootEstimatedQuantity =+ node.data.methodType === "Make to Order"+ ? rootTarget+ : rootTotalWithScrap;++ nodeTotalForChildren = rootTotalWithScrap;++ sourceMakeMethodIdToQuantities[sourceJobMakeMethod.data.id] = {+ targetQuantity: rootTarget,+ estimatedQuantity: rootEstimatedQuantity,+ totalWithScrap: rootTotalWithScrap,+ };+ } else {+ // Non-root: get from stored quantities using parent's source jobMakeMethodId+ const parentSourceMakeMethodId =+ node.data.jobMaterialMakeMethodId;+ const parentQuantities =+ sourceMakeMethodIdToQuantities[parentSourceMakeMethodId ?? ""];+ // Children receive parent's total (estimated + scrap) for cascade+ nodeTotalForChildren = parentQuantities?.totalWithScrap ?? 1;+ }++ for await (const child of node.children) {+ const sourceMaterial = sourceMaterialById.get(child.id);+ const newMaterialId = nanoid();+ sourceMaterialIdToJobMaterialId[child.id] = newMaterialId;++ // Resolve the supersession FIRST — see the note in+ // itemToJobMakeMethod's mapper. Every field below derives from+ // the post-swap item, so a field added later follows+ // automatically. Buy/Pick only — made sub-assemblies keep the+ // source job's structure (their successors' methods would have+ // to be re-exploded from the item side).+ const supersession = await resolveJobMaterialSupersession(+ client,+ companyId,+ supersessionRedirect,+ {+ itemId: child.data.itemId,+ methodType: child.data.methodType,+ }+ );+ const itemId = supersession?.itemId ?? child.data.itemId;+ const quantityPerParent =+ (child.data.quantity ?? 1) * (supersession?.factor ?? 1);++ // Get scrap percentage for this item+ const itemReplenishment = await trx+ .selectFrom("itemReplenishment")+ .select("scrapPercentage")+ .where("itemId", "=", itemId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ const itemScrapPercentage = Number(+ itemReplenishment?.scrapPercentage ?? 0+ );++ // Calculate scrap quantities for this child material+ // Target = parent's total (including scrap) * quantity per parent+ const childTargetQuantity =+ nodeTotalForChildren * quantityPerParent;+ // Scrap applies to every method type (mirrors itemToJob)+ const childScrapQuantity = scrapAllowance(+ childTargetQuantity,+ itemScrapPercentage+ );+ const childTotalWithScrap =+ childTargetQuantity + childScrapQuantity;+ // For Make: estimatedQuantity is good quantity (without scrap)+ // For Buy/Pick: estimatedQuantity includes scrap since that's what we procure+ const childEstimatedQuantity =+ child.data.methodType === "Make to Order"+ ? childTargetQuantity+ : childTotalWithScrap;++ // Store quantities for this child's make method (if it has one)+ if (child.data.jobMaterialMakeMethodId) {+ sourceMakeMethodIdToQuantities[+ child.data.jobMaterialMakeMethodId+ ] = {+ targetQuantity: childTargetQuantity,+ estimatedQuantity: childEstimatedQuantity,+ totalWithScrap: childTotalWithScrap,+ };+ }++ jobMaterialInserts.push({+ id: newMaterialId,+ jobId: targetJobId,+ itemId,+ itemType: supersession?.itemType ?? child.data.itemType,+ kit: child.data.kit,+ methodType: child.data.methodType,+ order: child.data.order,+ description:+ supersession?.description ?? child.data.description,+ jobMakeMethodId:+ child.data.jobMakeMethodId === sourceJobMakeMethod.data.id+ ? targetJobMakeMethod.data.id+ : sourceMakeMethodIdToJobMakeMethodId[+ child.data.jobMakeMethodId+ ],+ quantity: quantityPerParent,+ scrapQuantity: childScrapQuantity,+ estimatedQuantity: childEstimatedQuantity,+ itemScrapPercentage,+ substitutedFromItemId:+ supersession?.substitutedFromItemId ?? null,+ substitutionFactor: supersession?.factor ?? null,+ // ALWAYS set, never conditionally spread — see the note in+ // quoteLineToJob: Kysely builds ONE column list per multi-row+ // insert, and `unitCost` is NOT NULL DEFAULT 0.+ unitCost: supersession+ ? (supersession.unitCost ?? 0)+ : (sourceMaterial?.unitCost ?? child.data.unitCost ?? 0),+ // The bin belongs to the post-swap item; an explicit bin on+ // the source job's line still wins.+ storageUnitId: await getStorageUnitId(+ trx,+ itemId,+ targetJob.data.locationId,+ child.data.storageUnitId ?? undefined+ ),+ requiresBatchTracking:+ supersession?.requiresBatchTracking ??+ sourceMaterial?.requiresBatchTracking ??+ false,+ requiresSerialTracking:+ supersession?.requiresSerialTracking ??+ sourceMaterial?.requiresSerialTracking ??+ false,+ unitOfMeasureCode: child.data.unitOfMeasureCode,+ companyId,+ createdBy: userId,+ customFields: {},+ });++ if (child.data.jobMaterialMakeMethodId) {+ const newMakeMethodId = nanoid();+ sourceMakeMethodIdToJobMakeMethodId[+ child.data.jobMaterialMakeMethodId+ ] = newMakeMethodId;+ jobMakeMethodInserts.push({+ id: newMakeMethodId,+ jobId: targetJobId,+ parentMaterialId: sourceMaterialIdToJobMaterialId[child.id],+ itemId: child.data.itemId,+ quantityPerParent: child.data.quantity,+ companyId,+ createdBy: userId,+ });+ }+ }++ if (parts.billOfMaterial && jobMaterialInserts.length > 0) {+ // The supersession swap happens where each row is built, before+ // any field derives from the item — there is deliberately no+ // second pass here.+ await trx+ .insertInto("jobMaterial")+ .values(jobMaterialInserts)+ .execute();+ }++ if (parts.billOfMaterial && jobMakeMethodInserts.length > 0) {+ for await (const insert of jobMakeMethodInserts) {+ await trx+ .updateTable("jobMakeMethod")+ .set({+ id: insert.id,+ quantityPerParent: insert.quantityPerParent,+ })+ .where("jobId", "=", targetJobId)+ .where("parentMaterialId", "=", insert.parentMaterialId!)+ .execute();+ }+ }+ }+ );++ if (parts.billOfProcess) {+ const jobOperationInserts: Database["public"]["Tables"]["jobOperation"]["Insert"][] =+ sourceOperationRows.map((op) => {+ // Get quantities for this operation's SOURCE make method+ const opQuantities =+ sourceMakeMethodIdToQuantities[op.jobMakeMethodId ?? ""];+ // The traversal stores quantities for every make method in the+ // tree, so a miss means the operation references an orphaned+ // make method. Fail the conversion (rolls back the transaction)+ // instead of silently inserting a zero-quantity operation with+ // a NULL jobMakeMethodId.+ if (!opQuantities) {+ throw new Error(+ `No quantities found for source job make method ${op.jobMakeMethodId} referenced by operation ${op.id} — the job method tree and its operations are out of sync`+ );+ }+ return {+ jobId: targetJobId,+ jobMakeMethodId:+ op.jobMakeMethodId === sourceJobMakeMethod.data.id+ ? targetJobMakeMethod.data.id+ : sourceMakeMethodIdToJobMakeMethodId[+ op.jobMakeMethodId!+ ],+ processId: op.processId,+ procedureId: op.procedureId,+ workCenterId: op.workCenterId,+ description: op.description,+ setupTime: op.setupTime,+ setupUnit: op.setupUnit,+ laborTime: op.laborTime,+ laborUnit: op.laborUnit,+ machineTime: op.machineTime,+ machineUnit: op.machineUnit,+ order: op.order,+ operationOrder: op.operationOrder,+ operationType: op.operationType,+ // Carry the Assembly → BOP sync link so the MES can drive the+ // animated instruction player on the copied job.+ assemblyInstructionId: op.assemblyInstructionId,+ inspectionDocumentId: op.inspectionDocumentId,+ operationSupplierProcessId: op.operationSupplierProcessId,+ operationMinimumCost: op.operationMinimumCost ?? 0,+ operationLeadTime: op.operationLeadTime ?? 0,+ operationUnitCost: op.operationUnitCost ?? 0,+ tags: op.tags ?? [],+ workInstruction: parts.workInstructions+ ? op.workInstruction+ : {},+ targetQuantity: opQuantities.targetQuantity,+ // Fractional targets flow through; the scrap allowance is already whole+ operationQuantity: opQuantities.totalWithScrap,+ companyId,+ createdBy: userId,+ customFields: {},+ };+ });++ if (jobOperationInserts.length > 0) {+ const operationIds = await trx+ .insertInto("jobOperation")+ .values(jobOperationInserts)+ .returning(["id"])+ .execute();++ for (const [index, operation] of sourceOperationRows.entries()) {+ const operationId = operationIds[index].id;+ if (operationId) {+ sourceOperationIdToJobOperationId[operation.id] = operationId;++ const {+ jobOperationTool,+ jobOperationParameter,+ jobOperationStep,+ procedureId,+ } = operation;++ // Tool ids the assembly-instruction copy inserts itself, so+ // the source job's copies of the same tools are skipped below.+ let assemblyToolIds = new Set<string>();++ if (procedureId) {+ await insertProcedureDataForJobOperation(trx, client, {+ operationId,+ procedureId,+ companyId,+ userId,+ });+ } else {+ if (+ parts.parameters &&+ Array.isArray(jobOperationParameter) &&+ jobOperationParameter.length > 0+ ) {+ await trx+ .insertInto("jobOperationParameter")+ .values(+ jobOperationParameter.map((param) => ({+ operationId,+ key: param.key,+ value: param.value,+ companyId,+ createdBy: userId,+ }))+ )+ .execute();+ }++ if (operation.assemblyInstructionId) {+ // Assembly ops inherit their steps from the linked+ // instruction (fresh from the live definition, as every+ // *-ToJob path does); material ↔ step links are flushed+ // after the jobMaterial rows exist.+ assemblyToolIds = await insertAssemblyDataForJobOperation(+ trx,+ client,+ {+ operationId,+ assemblyInstructionId:+ operation.assemblyInstructionId,+ companyId,+ userId,+ }+ );+ assemblyOperationsToLink.push({+ operationId,+ assemblyInstructionId: operation.assemblyInstructionId,+ });+ } else if (+ parts.steps &&+ Array.isArray(jobOperationStep) &&+ jobOperationStep.length > 0+ ) {+ const insertedSteps = await trx+ .insertInto("jobOperationStep")+ .values(+ jobOperationStep.map((step) => ({+ operationId,+ name: step.name,+ type: step.type,+ description: toTiptapDoc(step.description),+ required: step.required,+ sortOrder: step.sortOrder,+ unitOfMeasureCode: step.unitOfMeasureCode,+ minValue: step.minValue,+ maxValue: step.maxValue,+ listValues: step.listValues,+ fileTypes: step.fileTypes,+ companyId,+ createdBy: userId,+ }))+ )+ .returning(["id"])+ .execute();++ // Bulk insert preserves order, so insertedSteps[i] ↔+ // jobOperationStep[i]: record old step -> new step so+ // material/tool ↔ step links can be remapped below.+ jobOperationStep.forEach((s, i) => {+ const newStepId = insertedSteps[i]?.id;+ if (s?.id && newStepId) {+ sourceStepsToJobSteps[s.id] = newStepId;+ }+ });++ await copyStepSlides(+ trx,+ client,+ jobOperationStep,+ insertedSteps,+ "jobOperationStepSlide",+ "jobOperationStepSlide",+ companyId,+ userId,+ );+ }+ }++ // Tools after steps: the old-step -> new-step map is now+ // populated, so a tool scoped to steps carries those links via+ // jobOperationToolStep. Tools the assembly-instruction copy+ // already inserted are skipped (see above).+ const toolsToCopy = (+ Array.isArray(jobOperationTool) ? jobOperationTool : []+ ).filter((tool) => !assemblyToolIds.has(tool.toolId));+ if (parts.tools && toolsToCopy.length > 0) {+ const insertedTools = await trx+ .insertInto("jobOperationTool")+ .values(+ toolsToCopy.map((tool) => ({+ toolId: tool.toolId,+ quantity: tool.quantity,+ operationId,+ companyId,+ createdBy: userId,+ }))+ )+ .returning(["id"])+ .execute();++ // Tool ↔ step links. Bulk insert preserves order, so+ // insertedTools[i] ↔ toolsToCopy[i]. A tool with no links+ // applies to the whole operation.+ const toolStepRows = toolsToCopy.flatMap((tool, i) => {+ const jobOperationToolId = insertedTools[i]?.id;+ if (!jobOperationToolId) return [];+ const oldStepIds = (+ (tool.jobOperationToolStep ?? []) as Array<{+ jobOperationStepId: string | null;+ }>+ ).map((l) => l.jobOperationStepId);+ return remapStepIds(oldStepIds, sourceStepsToJobSteps).map(+ (jobOperationStepId) => ({+ jobOperationToolId,+ jobOperationStepId,+ })+ );+ });+ if (toolStepRows.length > 0) {+ await trx+ .insertInto("jobOperationToolStep")+ .values(toolStepRows)+ .execute();+ }+ }+ }+ }+ }+ } // end if (parts.billOfProcess)++ // The links between materials and operations/steps can only be+ // rebuilt when BOTH sides were copied in this run — otherwise one end+ // of each link points at rows this copy never created.+ if (parts.billOfMaterial && parts.billOfProcess) {+ // Material ↔ operation links (jobMaterial.jobOperationId): the+ // materials were inserted during the traversal, before the+ // operations existed, so the link is applied as a second pass —+ // batched as one UPDATE per operation rather than one per material.+ const materialIdsByOperationId = new Map<string, string[]>();+ for (const sourceMaterial of sourceMaterialRows) {+ const newMaterialId =+ sourceMaterialIdToJobMaterialId[sourceMaterial.id];+ const newOperationId = sourceMaterial.jobOperationId+ ? sourceOperationIdToJobOperationId[sourceMaterial.jobOperationId]+ : undefined;+ if (newMaterialId && newOperationId) {+ const ids = materialIdsByOperationId.get(newOperationId) ?? [];+ ids.push(newMaterialId);+ materialIdsByOperationId.set(newOperationId, ids);+ }+ }+ for (const [operationId, materialIds] of materialIdsByOperationId) {+ await trx+ .updateTable("jobMaterial")+ .set({ jobOperationId: operationId })+ .where("id", "in", materialIds)+ .execute();+ }++ // Material ↔ step links (jobMaterialStep), remapped onto the new+ // material and step ids. Links to procedure/assembly-materialized+ // steps drop out of the map (assembly links are rebuilt from the+ // instruction by linkAssemblyStepMaterialsForJobOperations below).+ const materialStepRows = sourceMaterialRows.flatMap(+ (sourceMaterial) => {+ const newMaterialId =+ sourceMaterialIdToJobMaterialId[sourceMaterial.id];+ if (!newMaterialId) return [];+ return (sourceMaterial.jobMaterialStep ?? []).flatMap((link) => {+ const newStepId = link.jobOperationStepId+ ? sourceStepsToJobSteps[link.jobOperationStepId]+ : undefined;+ return newStepId+ ? [+ {+ jobMaterialId: newMaterialId,+ jobOperationStepId: newStepId,+ quantity: link.quantity,+ },+ ]+ : [];+ });+ }+ );+ if (materialStepRows.length > 0) {+ await trx+ .insertInto("jobMaterialStep")+ .values(materialStepRows)+ .execute();+ }+ }++ // Materials were inserted before operations in this direction, so the+ // assembly material ↔ step links can flush immediately.+ await linkAssemblyStepMaterialsForJobOperations(+ trx,+ client,+ assemblyOperationsToLink,+ companyId+ );+ });++ break;+ }case "makeMethodToMakeMethod": {const [sourceMakeMethod, targetMakeMethod] = await Promise.all([clientdiff --git a/packages/database/supabase/functions/lib/methods.ts b/packages/database/supabase/functions/lib/methods.tsindex b3b6e8f6e3..87e7663de3 100644--- a/packages/database/supabase/functions/lib/methods.ts+++ b/packages/database/supabase/functions/lib/methods.ts@@ -91,6 +91,24 @@ export function traverseJobMethod(}}+// Async twin of traverseJobMethod, mirroring traverseQuoteMethod: each node's+// callback is awaited before its children are visited, so a parent's cascade+// state (quantities, id maps) is in place when a child reads it. The sync+// version cannot be reused — an async callback passed to it would fire+// unawaited and the parent-before-child ordering would be lost.+export async function traverseJobMethodAsync(+ node: JobMethodTreeItem,+ callback: (node: JobMethodTreeItem) => void | Promise<void>+) {+ await callback(node);++ if (node.children) {+ for (const child of node.children) {+ await traverseJobMethodAsync(child, callback);+ }+ }+}+export type QuoteMethod = NonNullable<Awaited<ReturnType<typeof getQuoteMethodTreeArray>>["data"]>[number];diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex ffce768653..d1d71214e4 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -10685,6 +10685,9 @@ msgstr "Keine Variable stimmt mit {query} überein"msgid "No variables available"msgstr "Keine Variablen verfügbar"+msgid "No versions available"+msgstr "Keine Versionen verfügbar"+msgid "No warehouse stock is on record for this item. You can still pick it — on-hand will go negative until the count is reconciled."msgstr "Kein Lagerbestand für diesen Artikel ist erfasst. Sie können ihn trotzdem kommissionieren — der verfügbare Bestand wird negativ, bis die Inventur abgestimmt ist."@@ -14041,6 +14044,9 @@ msgstr "Auswählen"msgid "Select a assignee"msgstr "Einen Bearbeiter auswählen"+msgid "Select a completed job"+msgstr "Wählen Sie einen fertiggestellten Fertigungsauftrag"+msgid "Select a default approver"msgstr "Wählen Sie einen Standard-Genehmiger"@@ -14834,6 +14840,9 @@ msgstr "Ursprungsbeleg lesbar"msgid "Source Item"msgstr "Quellartikel"+msgid "Source Job"+msgstr "Quell-Fertigungsauftrag"+msgid "Source list"msgstr "Quellenliste"@@ -16471,7 +16480,7 @@ msgid "These journal entries are still Draft, so their debits and credits aren'tmsgstr "Diese Buchungssätze sind noch Entwurf, sodass ihre Sollposten und Habenposten nicht im Sachkonto für diesen Zeitraum enthalten sind. Buchen Sie jeden einzelnen oder ändern Sie das Datum zu einem späteren offenen Zeitraum."msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."-msgstr ""+msgstr "Diese Zeilen verlinken auf Daten außerhalb dieses Unternehmens. Daher kann keine Sicherheitskopie Ihrer aktuellen Daten erstellt werden. Das Löschen kann nicht rückgängig gemacht werden. Sollten diese sich als gemeinsam mit anderen Unternehmen in dieser Gruppe herausstellen, wird nichts gelöscht und die Wiederherstellung wird nicht gestartet."msgid "These rows link to data outside this company, so they could never be restored. Everything else was backed up."msgstr "Diese Zeilen sind mit Daten außerhalb dieses Unternehmens verknüpft, daher könnten sie nie wiederhergestellt werden. Alles andere wurde gesichert."diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 5063707722..51809f174b 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -10685,6 +10685,9 @@ msgstr "No variable matches {query}"msgid "No variables available"msgstr "No variables available"+msgid "No versions available"+msgstr "No versions available"+msgid "No warehouse stock is on record for this item. You can still pick it — on-hand will go negative until the count is reconciled."msgstr "No warehouse stock is on record for this item. You can still pick it — on-hand will go negative until the count is reconciled."@@ -14041,6 +14044,9 @@ msgstr "Select"msgid "Select a assignee"msgstr "Select a assignee"+msgid "Select a completed job"+msgstr "Select a completed job"+msgid "Select a default approver"msgstr "Select a default approver"@@ -14834,6 +14840,9 @@ msgstr "Source document readable"msgid "Source Item"msgstr "Source Item"+msgid "Source Job"+msgstr "Source Job"+msgid "Source list"msgstr "Source list"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 1be23a7a59..be1c1495f9 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -10685,6 +10685,9 @@ msgstr "Ninguna variable coincide con {query}"msgid "No variables available"msgstr "No hay variables disponibles"+msgid "No versions available"+msgstr "No hay versiones disponibles"+msgid "No warehouse stock is on record for this item. You can still pick it — on-hand will go negative until the count is reconciled."msgstr "No hay stock de almacén registrado para este artículo. Aún puedes recogerlo — el disponible se volverá negativo hasta que se reconcilie el recuento."@@ -14041,6 +14044,9 @@ msgstr "Seleccionar"msgid "Select a assignee"msgstr "Seleccionar un asignado"+msgid "Select a completed job"+msgstr "Selecciona una orden de trabajo completada"+msgid "Select a default approver"msgstr "Selecciona un aprobador predeterminado"@@ -14834,6 +14840,9 @@ msgstr "Documento de origen legible"msgid "Source Item"msgstr "Artículo de origen"+msgid "Source Job"+msgstr "Orden de origen"+msgid "Source list"msgstr "Lista de origen"@@ -16471,7 +16480,7 @@ msgid "These journal entries are still Draft, so their debits and credits aren'tmsgstr "Estos asientos aún están en Borrador, por lo que sus debe y haber no están en el libro mayor para este período. Contabiliza cada uno, o cambia su fecha a un período abierto posterior."msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."-msgstr ""+msgstr "Estas filas contienen referencias a datos fuera de esta empresa, por lo que no se puede crear una copia de seguridad de los datos actuales. La eliminación de estas filas no se puede deshacer. Si se encuentran compartidas con otras empresas del grupo, nada se eliminará y la restauración no se iniciará."msgid "These rows link to data outside this company, so they could never be restored. Everything else was backed up."msgstr "Estas filas se vinculan a datos fuera de esta empresa, por lo que nunca podrían ser restauradas. Todo lo demás fue respaldado."diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex d5d1c7fdc4..e04a087486 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -10685,6 +10685,9 @@ msgstr "Aucune variable ne correspond à {query}"msgid "No variables available"msgstr "Aucune variable disponible"+msgid "No versions available"+msgstr "Aucune version disponible"+msgid "No warehouse stock is on record for this item. You can still pick it — on-hand will go negative until the count is reconciled."msgstr "Aucun stock d'entrepôt n'est enregistré pour cet article. Vous pouvez toujours le prélever — le stock disponible deviendra négatif jusqu'à ce que le décompte soit rapproché."@@ -14041,6 +14044,9 @@ msgstr "Sélectionner"msgid "Select a assignee"msgstr "Sélectionner un assigné"+msgid "Select a completed job"+msgstr "Sélectionner un ordre de fabrication terminé"+msgid "Select a default approver"msgstr "Sélectionner un approbateur par défaut"@@ -14834,6 +14840,9 @@ msgstr "document d'origine lisible"msgid "Source Item"msgstr "Élément source"+msgid "Source Job"+msgstr "Ordre de fabrication source"+msgid "Source list"msgstr "Liste source"@@ -16471,7 +16480,7 @@ msgid "These journal entries are still Draft, so their debits and credits aren'tmsgstr "Ces écritures de journal sont encore Brouillon, de sorte que leurs débits et crédits ne se trouvent pas dans le grand livre pour cette période. Comptabilisez chacune ou redatez-la à une période ouverte ultérieure."msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."-msgstr ""+msgstr "Ces lignes sont liées à des données en dehors de cette Société, c'est pourquoi une copie de sécurité de vos données actuelles ne peut pas être créée. La suppression de ces lignes ne peut pas être annulée. S'il s'avère qu'elles sont partagées avec d'autres Sociétés de ce groupe, rien n'est supprimé et la restauration ne démarre pas."msgid "These rows link to data outside this company, so they could never be restored. Everything else was backed up."msgstr "Ces lignes sont liées à des données en dehors de cette société, donc elles ne pourraient jamais être restaurées. Tout le reste a été sauvegardé."diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 217f70c45a..d0821b94f5 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -10685,6 +10685,9 @@ msgstr "कोई चर {query} से मेल नहीं खाता"msgid "No variables available"msgstr "कोई चर उपलब्ध नहीं"+msgid "No versions available"+msgstr "कोई संस्करण उपलब्ध नहीं है"+msgid "No warehouse stock is on record for this item. You can still pick it — on-hand will go negative until the count is reconciled."msgstr "इस आइटम के लिए कोई गोदाम स्टॉक रिकॉर्ड पर नहीं है। आप इसे अभी भी चुन सकते हैं — गणना के समाधान तक हाथ पर नकारात्मक हो जाएगा।"@@ -14041,6 +14044,9 @@ msgstr "चुनें"msgid "Select a assignee"msgstr "एक असाइनी चुनें"+msgid "Select a completed job"+msgstr "एक पूर्ण जॉब चुनें"+msgid "Select a default approver"msgstr "एक डिफ़ॉल्ट अनुमोदक चुनें"@@ -14834,6 +14840,9 @@ msgstr "स्रोत दस्तावेज़ पठनीय"msgid "Source Item"msgstr "स्रोत आइटम"+msgid "Source Job"+msgstr "स्रोत जॉब"+msgid "Source list"msgstr "स्रोत सूची"@@ -16471,7 +16480,7 @@ msgid "These journal entries are still Draft, so their debits and credits aren'tmsgstr "ये जर्नल प्रविष्टियां अभी भी ड्राफ्ट हैं, इसलिए उनके नामे और जमा इस अवधि के लिए खाता बही में नहीं हैं। प्रत्येक को पोस्ट करें, या इसे बाद की खुली अवधि में फिर से दिनांकित करें।"msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."-msgstr ""+msgstr "ये पंक्तियां इस कंपनी के बाहर के डेटा से जुड़ी हुई हैं, इसलिए आपके वर्तमान डेटा की सुरक्षा प्रति नहीं बनाई जा सकती। उन्हें हटाना पूर्ववत नहीं किया जा सकता। यदि वे इस समूह की अन्य कंपनियों के साथ साझा की जाती हैं, तो कुछ भी हटाया नहीं जाता है और पुनर्स्थापन शुरू नहीं होता है।"msgid "These rows link to data outside this company, so they could never be restored. Everything else was backed up."msgstr "ये पंक्तियां इस कंपनी के बाहर के डेटा से जुड़ी हुई हैं, इसलिए उन्हें कभी भी पुनर्स्थापित नहीं किया जा सकता। बाकी सब कुछ बैक अप किया गया था।"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex d747bd74d6..e2b3601561 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -10685,6 +10685,9 @@ msgstr "Nessuna variabile corrisponde a {query}"msgid "No variables available"msgstr "Nessuna variabile disponibile"+msgid "No versions available"+msgstr "Nessuna versione disponibile"+msgid "No warehouse stock is on record for this item. You can still pick it — on-hand will go negative until the count is reconciled."msgstr "Nessuna giacenza di magazzino è registrata per questo articolo. Puoi comunque prelevarlo — la giacenza disponibile diventerà negativa fino al riconciliamento del conteggio."@@ -14041,6 +14044,9 @@ msgstr "Seleziona"msgid "Select a assignee"msgstr "Seleziona un assegnatario"+msgid "Select a completed job"+msgstr "Seleziona un ordine di produzione completato"+msgid "Select a default approver"msgstr "Seleziona un approvatore predefinito"@@ -14834,6 +14840,9 @@ msgstr "Documento di origine leggibile"msgid "Source Item"msgstr "Articolo Sorgente"+msgid "Source Job"+msgstr "Ordine di produzione di origine"+msgid "Source list"msgstr "Elenco di origine"@@ -16471,7 +16480,7 @@ msgid "These journal entries are still Draft, so their debits and credits aren'tmsgstr "Queste voci di prima nota sono ancora Bozza, quindi i loro dare e avere non sono nel registro per questo periodo. Registra ognuno, o ri-datalo in un periodo aperto successivo."msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."-msgstr ""+msgstr "Queste righe sono collegate a dati esterni a questa azienda, pertanto non è possibile effettuare una copia di sicurezza dei dati attuali. La loro eliminazione non può essere annullata. Se risultano condivise con altre aziende del gruppo, nulla viene eliminato e il ripristino non si avvierà."msgid "These rows link to data outside this company, so they could never be restored. Everything else was backed up."msgstr "Queste righe collegano i dati al di fuori di questa azienda, quindi non potrebbero mai essere ripristinate. Tutto il resto è stato sottoposto a backup."diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 3477537897..790f616756 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -10685,6 +10685,9 @@ msgstr "{query}に一致する変数がありません"msgid "No variables available"msgstr "利用可能な変数がありません"+msgid "No versions available"+msgstr "利用可能なバージョンがありません"+msgid "No warehouse stock is on record for this item. You can still pick it — on-hand will go negative until the count is reconciled."msgstr "このアイテムの倉庫在庫は記録されていません。それでも選択できます。実在庫がマイナスになり、数量が調整されるまで続きます。"@@ -14041,6 +14044,9 @@ msgstr "選択"msgid "Select a assignee"msgstr "担当者を選択"+msgid "Select a completed job"+msgstr "完了した製造指図を選択してください"+msgid "Select a default approver"msgstr "デフォルト承認者を選択"@@ -14834,6 +14840,9 @@ msgstr "参照伝票判読可能"msgid "Source Item"msgstr "ソースアイテム"+msgid "Source Job"+msgstr "ソース製造指図"+msgid "Source list"msgstr "ソースリスト"@@ -16471,7 +16480,7 @@ msgid "These journal entries are still Draft, so their debits and credits aren'tmsgstr "これらの仕訳はまだ下書きであるため、それらの借方と貸方は当期の元帳に含まれていません。各仕訳を転記するか、後の開いている期間に再度日付を付け直してください。"msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."-msgstr ""+msgstr "これらの行はこの会社外のデータにリンクしているため、現在のデータのバックアップを作成できません。削除を元に戻すことはできません。このグループ内の他の会社と共有されていることが判明した場合、何も削除されず、復元は開始されません。"msgid "These rows link to data outside this company, so they could never be restored. Everything else was backed up."msgstr "これらの行は会社外のデータにリンクしているため、復元することはできません。その他すべてがバックアップされました。"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex ff1135b864..3681971e74 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -10685,6 +10685,9 @@ msgstr "{query}와 일치하는 변수가 없습니다"msgid "No variables available"msgstr "사용 가능한 변수가 없습니다."+msgid "No versions available"+msgstr "가용한 버전이 없습니다"+msgid "No warehouse stock is on record for this item. You can still pick it — on-hand will go negative until the count is reconciled."msgstr "이 품목에 대한 창고 재고 기록이 없습니다. 그래도 피킹할 수 있으며, 실사로 수량이 조정될 때까지 보유수량이 음수로 표시됩니다."@@ -14041,6 +14044,9 @@ msgstr "선택"msgid "Select a assignee"msgstr "담당자 선택"+msgid "Select a completed job"+msgstr "완료된 작업 지시를 선택하세요"+msgid "Select a default approver"msgstr "기본 승인자 선택"@@ -14834,6 +14840,9 @@ msgstr "원본 문서 읽기 가능"msgid "Source Item"msgstr "소스 품목"+msgid "Source Job"+msgstr "원본 작업 지시"+msgid "Source list"msgstr "원본 목록"@@ -16471,7 +16480,7 @@ msgid "These journal entries are still Draft, so their debits and credits aren'tmsgstr "이 전표들은 아직 초안 상태이므로 이 기간에 차변 및 대변이 원장에 없습니다. 각 전표를 전기하거나 이후 미결 기간으로 다시 날짜를 지정하십시오."msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."-msgstr ""+msgstr "이 행들은 이 회사 외부의 데이터와 연결되어 있으므로 현재 데이터의 안전한 사본을 만들 수 없습니다. 이들을 삭제하면 되돌릴 수 없습니다. 이들이 이 그룹의 다른 회사와 공유되는 경우, 아무것도 삭제되지 않고 복원이 시작되지 않습니다."msgid "These rows link to data outside this company, so they could never be restored. Everything else was backed up."msgstr "이 행들은 회사 외부의 데이터와 연결되어 있어 복원할 수 없습니다. 그 외 모든 것은 백업되었습니다."diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex e46f17f3af..af500148ce 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -10685,6 +10685,9 @@ msgstr "Żadna zmienna nie pasuje do {query}"msgid "No variables available"msgstr "Brak dostępnych zmiennych"+msgid "No versions available"+msgstr "Brak dostępnych wersji"+msgid "No warehouse stock is on record for this item. You can still pick it — on-hand will go negative until the count is reconciled."msgstr "Brak zapasu w magazynie dla tego artykułu. Możesz go mimo tego pobrać — dostępna ilość będzie ujemna do czasu uzgodnienia stanu."@@ -14041,6 +14044,9 @@ msgstr "Wybierz"msgid "Select a assignee"msgstr "Wybierz osobę przypisaną"+msgid "Select a completed job"+msgstr "Wybierz zakończone zlecenie produkcyjne"+msgid "Select a default approver"msgstr "Wybierz domyślnego zatwierdzającego"@@ -14834,6 +14840,9 @@ msgstr "Dokument źródłowy czytelny"msgid "Source Item"msgstr "Element źródłowy"+msgid "Source Job"+msgstr "Zlecenie źródłowe"+msgid "Source list"msgstr "Lista źródłowa"@@ -16471,7 +16480,7 @@ msgid "These journal entries are still Draft, so their debits and credits aren'tmsgstr "Te dowody księgowe są wciąż w wersji roboczej, dlatego ich wpisy Winien i Ma nie znajdują się w księdze dla tego okresu. Zaksięguj każdy z nich lub przesyć go do późniejszego otwartego okresu."msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."-msgstr ""+msgstr "Te wiersze łączą się z danymi spoza tej firmy, dlatego nie można wykonać bezpiecznej kopii bieżących danych. Usunięcie ich nie może być cofnięte. Jeśli okaże się, że są współdzielone z innymi firmami w tej grupie, nic nie zostanie usunięte i przywracanie nie zostanie uruchomione."msgid "These rows link to data outside this company, so they could never be restored. Everything else was backed up."msgstr "Te wiersze są połączone z danymi spoza tej firmy, dlatego nigdy nie mogły być przywrócone. Wszystko inne miało kopię zapasową."diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex a057c61b8b..bd2aa7aed2 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -10685,6 +10685,9 @@ msgstr "Nenhuma variável corresponde a {query}"msgid "No variables available"msgstr "Nenhuma variável disponível"+msgid "No versions available"+msgstr "Nenhuma versão disponível"+msgid "No warehouse stock is on record for this item. You can still pick it — on-hand will go negative until the count is reconciled."msgstr "Nenhum estoque de armazém está registrado para este item. Você ainda pode coletá-lo — o estoque disponível ficará negativo até que a contagem seja reconciliada."@@ -14041,6 +14044,9 @@ msgstr "Selecionar"msgid "Select a assignee"msgstr "Selecione um designado"+msgid "Select a completed job"+msgstr "Selecionar uma ordem de produção concluída"+msgid "Select a default approver"msgstr "Selecione um aprovador padrão"@@ -14834,6 +14840,9 @@ msgstr "Documento de origem legível"msgid "Source Item"msgstr "Item de Origem"+msgid "Source Job"+msgstr "Ordem de Origem"+msgid "Source list"msgstr "Lista de origem"@@ -16471,7 +16480,7 @@ msgid "These journal entries are still Draft, so their debits and credits aren'tmsgstr "Estes lançamentos de diário ainda estão em Rascunho, portanto seus débitos e créditos não estão no livro-razão para este período. Lance cada um, ou redatē-o para um período aberto posterior."msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."-msgstr ""+msgstr "Essas linhas estão vinculadas a dados fora desta empresa, portanto não é possível criar uma cópia de segurança dos seus dados atuais. A exclusão dessas linhas não pode ser desfeita. Se forem compartilhadas com outras empresas neste grupo, nada será excluído e a restauração não será iniciada."msgid "These rows link to data outside this company, so they could never be restored. Everything else was backed up."msgstr "Essas linhas estão vinculadas a dados fora desta empresa, portanto nunca poderiam ser restauradas. Tudo mais foi feito backup."diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex 7c4d228085..b831ef4b0e 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -10685,6 +10685,9 @@ msgstr "Нет переменных соответствующих {query}"msgid "No variables available"msgstr "Нет доступных переменных"+msgid "No versions available"+msgstr "Нет доступных версий"+msgid "No warehouse stock is on record for this item. You can still pick it — on-hand will go negative until the count is reconciled."msgstr "На складе нет записей о наличии этого товара. Вы все равно можете его отобрать — остаток на руках станет отрицательным до тех пор, пока инвентаризация не будет согласована."@@ -14041,6 +14044,9 @@ msgstr "Выбрать"msgid "Select a assignee"msgstr "Выберите исполнителя"+msgid "Select a completed job"+msgstr "Выберите завершённый производственный заказ"+msgid "Select a default approver"msgstr "Выберите утверждающего по умолчанию"@@ -14834,6 +14840,9 @@ msgstr "Читаемый документ-основание"msgid "Source Item"msgstr "Исходный элемент"+msgid "Source Job"+msgstr "Исходный производственный заказ"+msgid "Source list"msgstr "Список источников"@@ -16471,7 +16480,7 @@ msgid "These journal entries are still Draft, so their debits and credits aren'tmsgstr "Эти операции по-прежнему находятся в режиме Черновик, поэтому их дебеты и кредиты не включены в главную книгу для этого периода. Проведите каждый из них или переведите его в более поздний открытый период."msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."-msgstr ""+msgstr "Эти строки связаны с данными вне этой организации, поэтому не удаётся создать резервную копию текущих данных. Удаление их не может быть отменено. Если окажется, что они используются другими организациями в этой группе, ничего не удаляется и восстановление не начинается."msgid "These rows link to data outside this company, so they could never be restored. Everything else was backed up."msgstr "Эти строки ссылаются на данные вне этой организации, поэтому они не могут быть восстановлены. Всё остальное было сохранено в резервной копии."diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex bc39a379de..fc94cfc462 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -10685,6 +10685,9 @@ msgstr "Değişken {query} ile eşleşmiyor"msgid "No variables available"msgstr "Kullanılabilir değişken yok"+msgid "No versions available"+msgstr "Kullanılabilir sürüm yok"+msgid "No warehouse stock is on record for this item. You can still pick it — on-hand will go negative until the count is reconciled."msgstr "Bu ürün için depoda kayıtlı stok bulunmamaktadır. Sayım yeniden düzenlenene kadar eldeki stok negatif olacaktır, ancak yine de alabilirsiniz."@@ -14041,6 +14044,9 @@ msgstr "Seç"msgid "Select a assignee"msgstr "Bir atanan seçin"+msgid "Select a completed job"+msgstr "Tamamlanmış bir iş emri seçin"+msgid "Select a default approver"msgstr "Varsayılan onaylayıcı seçin"@@ -14834,6 +14840,9 @@ msgstr "Okunabilir kaynak belge"msgid "Source Item"msgstr "Kaynak Ürün"+msgid "Source Job"+msgstr "Kaynak İş Emri"+msgid "Source list"msgstr "Kaynak listesi"@@ -16471,7 +16480,7 @@ msgid "These journal entries are still Draft, so their debits and credits aren'tmsgstr "Bu muhasebe fişleri hala Taslak halinde olduğundan borç ve alacakları bu dönemin defterine girmedi. Her birini muhasebeleştir veya daha sonraki açık bir döneme yeniden tarihle."msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."-msgstr ""+msgstr "Bu satırlar bu Şirket dışındaki verilere bağlı olduğundan, mevcut verilerinizin bir güvenlik kopyası oluşturulamaz. Bu satırları silmek geri alınamaz. Bunların bu gruptaki diğer Şirketlerle paylaşıldığı anlaşılırsa, hiçbir şey silinmez ve geri yükleme başlamaz."msgid "These rows link to data outside this company, so they could never be restored. Everything else was backed up."msgstr "Bu satırlar bu şirket dışındaki verilere bağlantılı, bu nedenle bunlar hiçbir zaman geri yüklenemez. Diğer her şey yedeklendi."diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 0933aebf8f..cd7dc632d5 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -10685,6 +10685,9 @@ msgstr "没有变量匹配{query}"msgid "No variables available"msgstr "没有可用的变量"+msgid "No versions available"+msgstr "没有可用的版本"+msgid "No warehouse stock is on record for this item. You can still pick it — on-hand will go negative until the count is reconciled."msgstr "此物料的仓库库存无记录。您仍然可以拣货 — 在手库存将变为负数,直到盘点协调。"@@ -14041,6 +14044,9 @@ msgstr "选择"msgid "Select a assignee"msgstr "选择经办人"+msgid "Select a completed job"+msgstr "选择已完成的工单"+msgid "Select a default approver"msgstr "选择默认审批人"@@ -14834,6 +14840,9 @@ msgstr "源单据可读"msgid "Source Item"msgstr "源项目"+msgid "Source Job"+msgstr "源工单"+msgid "Source list"msgstr "源列表"@@ -16471,7 +16480,7 @@ msgid "These journal entries are still Draft, so their debits and credits aren'tmsgstr "这些凭证仍是草稿,所以其借方和贷方不在此期间的账簿中。过账每一个,或将其重新标注日期到更后的未结期间。"msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."-msgstr ""+msgstr "这些行链接到此公司外的数据,因此无法创建当前数据的安全备份。删除它们无法撤销。如果这些行实际上与此集团中的其他公司共享,则不删除任何行,且不启动还原。"msgid "These rows link to data outside this company, so they could never be restored. Everything else was backed up."msgstr "这些行链接到公司外的数据,因此无法恢复它们。其他所有内容都已备份。"diff --git a/packages/react/src/Modal.tsx b/packages/react/src/Modal.tsxindex c7702fb956..89421118f4 100644--- a/packages/react/src/Modal.tsx+++ b/packages/react/src/Modal.tsx@@ -32,7 +32,7 @@ const ModalOverlay = forwardRef<// 'z-50 fixed h-full w-full left-0 top-0',// 'bg-alternative/90 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',"bg-alternative/90 backdrop-blur-sm",- "z-50 fixed inset-0 grid place-items-center overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent data-open:animate-overlay-show data-closed:animate-overlay-hide",+ "z-50 fixed inset-0 grid place-items-center overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=closed]:animate-out data-[state=closed]:fade-out-0",className)}