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.

Purchasing Planning 2.0 (#836)

Naveen Kashyapbb6fc676a2f0
diff --git a/.github/labeler.yml b/.github/labeler.yml
new file mode 100644
index 0000000000..88f339b796
--- /dev/null
+++ b/.github/labeler.yml
@@ -0,0 +1,47 @@
+erp:
+ - changed-files:
+ - any-glob-to-any-file: 'apps/erp/**'
+
+mes:
+ - changed-files:
+ - any-glob-to-any-file: 'apps/mes/**'
+
+academy:
+ - changed-files:
+ - any-glob-to-any-file: 'apps/academy/**'
+
+database:
+ - changed-files:
+ - any-glob-to-any-file:
+ - 'packages/database/**'
+
+migrations:
+ - changed-files:
+ - any-glob-to-any-file: 'packages/database/supabase/migrations/**'
+
+functions:
+ - changed-files:
+ - any-glob-to-any-file: 'packages/database/supabase/functions/**'
+
+design-system:
+ - changed-files:
+ - any-glob-to-any-file: 'packages/react/**'
+
+auth:
+ - changed-files:
+ - any-glob-to-any-file: 'packages/auth/**'
+
+jobs:
+ - changed-files:
+ - any-glob-to-any-file: 'packages/jobs/**'
+
+ci:
+ - changed-files:
+ - any-glob-to-any-file:
+ - '.github/**'
+
+dependencies:
+ - changed-files:
+ - any-glob-to-any-file:
+ - '**/package.json'
+ - 'pnpm-lock.yaml'
diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml
index 1845233b54..fa6fdf7846 100644
--- a/.github/workflows/check.yml
+++ b/.github/workflows/check.yml
@@ -101,6 +101,28 @@ jobs:
- run: pnpm run lingui:check
+ test:
+ name: Test
+ needs: install
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: pnpm/action-setup@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 22
+ cache: pnpm
+
+ - uses: actions/cache@v4
+ with:
+ path: |
+ node_modules
+ apps/*/node_modules
+ packages/*/node_modules
+ key: node-modules-${{ hashFiles('pnpm-lock.yaml') }}
+
+ - run: pnpm test
+
audit:
name: Audit
runs-on: ubuntu-latest
diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml
new file mode 100644
index 0000000000..1bbefe63f6
--- /dev/null
+++ b/.github/workflows/labeler.yml
@@ -0,0 +1,23 @@
+name: Labeler
+
+permissions:
+ contents: read
+ pull-requests: write
+
+on:
+ - pull_request_target
+
+jobs:
+ labeler:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout Repo
+ uses: actions/checkout@v5
+ with:
+ fetch-depth: 1
+ fetch-tags: false
+ filter: 'blob:none'
+ show-progress: false
+ - uses: actions/labeler@v6
+ with:
+ sync-labels: true
diff --git a/.github/workflows/pr-checks-label.yml b/.github/workflows/pr-checks-label.yml
new file mode 100644
index 0000000000..8a15d1f24b
--- /dev/null
+++ b/.github/workflows/pr-checks-label.yml
@@ -0,0 +1,39 @@
+name: PR Checks Label
+
+on:
+ workflow_run:
+ workflows:
+ - Check Lint and Types
+ types:
+ - completed
+
+permissions:
+ contents: read
+ pull-requests: write
+
+jobs:
+ label:
+ if: >-
+ github.event.workflow_run.event == 'pull_request' &&
+ github.event.workflow_run.pull_requests[0].number != null
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ GH_REPO: ${{ github.repository }}
+ PR_NUMBER: ${{ github.event.workflow_run.pull_requests[0].number }}
+ steps:
+ - name: Ensure labels exist
+ run: |
+ gh label create "checks: passing" --color "0e8a16" --description "CI checks passed" --force
+ gh label create "checks: failing" --color "b60205" --description "CI checks failed" --force
+
+ - name: Apply checks label
+ run: |
+ if [ "${{ github.event.workflow_run.conclusion }}" = "success" ]; then
+ gh pr edit "$PR_NUMBER" --remove-label "checks: failing" 2>/dev/null || true
+ gh pr edit "$PR_NUMBER" --add-label "checks: passing"
+ else
+ gh pr edit "$PR_NUMBER" --remove-label "checks: passing" 2>/dev/null || true
+ gh pr edit "$PR_NUMBER" --add-label "checks: failing"
+ fi
diff --git a/.github/workflows/pr-complexity.yml b/.github/workflows/pr-complexity.yml
new file mode 100644
index 0000000000..e2e2cf484e
--- /dev/null
+++ b/.github/workflows/pr-complexity.yml
@@ -0,0 +1,44 @@
+name: PR Complexity
+
+on:
+ pull_request:
+ types: [opened, synchronize, reopened]
+ branches: [main]
+
+permissions:
+ contents: read
+ pull-requests: write
+
+concurrency:
+ group: pr-complexity-${{ github.event.pull_request.number }}
+ cancel-in-progress: true
+
+jobs:
+ complexity:
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ steps:
+ - name: Checkout scripts
+ uses: actions/checkout@v4
+ with:
+ sparse-checkout: scripts/pr-complexity
+ sparse-checkout-cone-mode: true
+
+ - uses: pnpm/action-setup@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 22
+
+ - name: Install dependencies
+ run: pnpm install --ignore-workspace --ignore-scripts
+ working-directory: scripts/pr-complexity
+
+ - name: Score PR complexity
+ run: npx tsx index.ts
+ working-directory: scripts/pr-complexity
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ OWNER: ${{ github.repository_owner }}
+ REPO: ${{ github.event.repository.name }}
+ PR_NUMBER: ${{ github.event.pull_request.number }}
+ PR_AUTHOR: ${{ github.event.pull_request.user.login }}
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index 44db116015..fed4bbef75 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -531,6 +531,99 @@ export async function getItemDemand(
};
}
+export type DemandForecastSourceRow = {
+ itemId: string;
+ locationId: string | null;
+ periodId: string;
+ sourceType: "Job Material" | "Sales Order" | "Demand Projection";
+ quantity: number;
+ jobId: string | null;
+ salesOrderLineId: string | null;
+ demandProjectionId: string | null;
+ parentItemId: string;
+ parentItem: { id: string; readableId: string; name: string } | null;
+ job: {
+ id: string;
+ jobId: string;
+ dueDate: string | null;
+ status: string | null;
+ } | null;
+ salesOrderLine: {
+ id: string;
+ salesOrderId: string;
+ promisedDate: string | null;
+ salesOrder: { id: string; salesOrderId: string } | null;
+ } | null;
+ demandProjection: {
+ id: string;
+ forecastQuantity: number;
+ forecastMethod: string | null;
+ confidence: number | null;
+ notes: string | null;
+ createdBy: string;
+ createdAt: string;
+ period: { startDate: string } | null;
+ } | null;
+};
+
+export async function getDemandForecastSources(
+ client: SupabaseClient<Database>,
+ {
+ itemId,
+ locationId,
+ periods,
+ companyId
+ }: {
+ itemId: string;
+ locationId: string;
+ periods: string[];
+ companyId: string;
+ }
+) {
+ const result = await client
+ .from("demandForecastSource")
+ .select(
+ `
+ itemId,
+ locationId,
+ periodId,
+ sourceType,
+ quantity,
+ jobId,
+ salesOrderLineId,
+ demandProjectionId,
+ parentItemId,
+ parentItem:item!demandForecastSource_parentItemId_fkey(id, readableId, name),
+ job:job!demandForecastSource_jobId_fkey(id, jobId, dueDate, status),
+ salesOrderLine:salesOrderLine!demandForecastSource_salesOrderLineId_fkey(
+ id,
+ salesOrderId,
+ promisedDate,
+ salesOrder:salesOrder(id, salesOrderId)
+ ),
+ demandProjection:demandProjection!demandForecastSource_demandProjectionId_fkey(
+ id,
+ forecastQuantity,
+ forecastMethod,
+ confidence,
+ notes,
+ period(startDate),
+ createdBy,
+ createdAt
+ )
+ `
+ )
+ .eq("itemId", itemId)
+ .eq("locationId", locationId)
+ .eq("companyId", companyId)
+ .in("periodId", periods);
+
+ return {
+ data: result.data ?? [],
+ error: result.error
+ };
+}
+
export async function getItemFiles(
client: SupabaseClient<Database>,
itemId: string,
@@ -706,6 +799,39 @@ export async function getItemUnitSalePrice(
.single();
}
+export async function getJobMaterialUsageForItem(
+ client: SupabaseClient<Database>,
+ { itemId, companyId }: { itemId: string; companyId: string }
+): Promise<{
+ byMaterialId: Record<string, number>;
+ byJobId: Record<string, number>;
+}> {
+ const [materials, jobs] = await Promise.all([
+ client
+ .from("jobMaterial")
+ .select("id, estimatedQuantity")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId),
+ client
+ .from("job")
+ .select("id, quantity")
+ .eq("itemId", itemId)
+ .eq("companyId", companyId)
+ ]);
+
+ const byMaterialId: Record<string, number> = {};
+ for (const row of materials.data ?? []) {
+ if (row.id) byMaterialId[row.id] = row.estimatedQuantity ?? 0;
+ }
+
+ const byJobId: Record<string, number> = {};
+ for (const row of jobs.data ?? []) {
+ if (row.id) byJobId[row.id] = row.quantity ?? 0;
+ }
+
+ return { byMaterialId, byJobId };
+}
+
export async function getMaterialUsedIn(
client: SupabaseClient<Database>,
itemId: string,
@@ -721,7 +847,8 @@ export async function getMaterialUsedIn(
quoteMaterials,
salesOrderLines,
shipmentLines,
- supplierQuotes
+ supplierQuotes,
+ jobMaterialUsage
] = await Promise.all([
client
.from("nonConformanceItem")
@@ -803,7 +930,8 @@ export async function getMaterialUsedIn(
)
.eq("itemId", itemId)
.eq("companyId", companyId)
- .limit(100)
+ .limit(100),
+ getJobMaterialUsageForItem(client, { itemId, companyId })
]);
return {
@@ -816,7 +944,8 @@ export async function getMaterialUsedIn(
quoteMaterials: quoteMaterials.data ?? [],
salesOrderLines: salesOrderLines.data ?? [],
shipmentLines: shipmentLines.data ?? [],
- supplierQuotes: supplierQuotes.data ?? []
+ supplierQuotes: supplierQuotes.data ?? [],
+ jobMaterialUsage
};
}
@@ -1441,7 +1570,8 @@ export async function getPartUsedIn(
quoteMaterials,
salesOrderLines,
shipmentLines,
- supplierQuotes
+ supplierQuotes,
+ jobMaterialUsage
] = await Promise.all([
client
.from("nonConformanceItem")
@@ -1541,7 +1671,8 @@ export async function getPartUsedIn(
)
.eq("itemId", itemId)
.eq("companyId", companyId)
- .limit(100)
+ .limit(100),
+ getJobMaterialUsageForItem(client, { itemId, companyId })
]);
return {
@@ -1556,7 +1687,8 @@ export async function getPartUsedIn(
quoteMaterials: quoteMaterials.data ?? [],
salesOrderLines: salesOrderLines.data ?? [],
shipmentLines: shipmentLines.data ?? [],
- supplierQuotes: supplierQuotes.data ?? []
+ supplierQuotes: supplierQuotes.data ?? [],
+ jobMaterialUsage
};
}
diff --git a/apps/erp/app/modules/items/ui/Item/DemandForecastSourcesPopover.tsx b/apps/erp/app/modules/items/ui/Item/DemandForecastSourcesPopover.tsx
new file mode 100644
index 0000000000..c161f5a4f6
--- /dev/null
+++ b/apps/erp/app/modules/items/ui/Item/DemandForecastSourcesPopover.tsx
@@ -0,0 +1,210 @@
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+ Table,
+ Tbody,
+ Td,
+ Th,
+ Thead,
+ Tr
+} from "@carbon/react";
+import { Trans } from "@lingui/react/macro";
+import { useNumberFormatter } from "@react-aria/i18n";
+import type { ReactNode } from "react";
+import { Link } from "react-router";
+import { useDateFormatter } from "~/hooks";
+import type { DemandForecastSourceRow } from "~/modules/items/items.service";
+import { path } from "~/utils/path";
+
+type Props = {
+ sources: DemandForecastSourceRow[];
+ forecastQuantity: number;
+ forecastMethod: string | null;
+ children: ReactNode;
+};
+
+export function DemandForecastSourcesPopover({
+ sources,
+ forecastQuantity,
+ forecastMethod,
+ children
+}: Props) {
+ const numberFormatter = useNumberFormatter();
+ const { formatDate } = useDateFormatter();
+
+ // Non-MRP forecasts (manual / statistical / ml) have no traceable sources.
+ if (forecastMethod !== "mrp") {
+ return (
+ <Popover>
+ <PopoverTrigger asChild>{children}</PopoverTrigger>
+ <PopoverContent className="w-80">
+ <div className="flex flex-col gap-2 p-2">
+ <div className="text-sm font-medium">
+ <Trans>Demand Forecast</Trans>
+ </div>
+ <div className="text-xs text-muted-foreground">
+ <Trans>
+ Forecast method:{" "}
+ <span className="font-mono">{forecastMethod ?? "unknown"}</span>
+ . This row was not derived from active jobs, so no parent
+ sources are available.
+ </Trans>
+ </div>
+ <div className="text-sm">
+ <Trans>
+ Quantity: {numberFormatter.format(forecastQuantity)}
+ </Trans>
+ </div>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+ }
+
+ if (sources.length === 0) {
+ return (
+ <Popover>
+ <PopoverTrigger asChild>{children}</PopoverTrigger>
+ <PopoverContent className="w-80">
+ <div className="flex flex-col gap-2 p-2">
+ <div className="text-sm font-medium">
+ <Trans>Demand Forecast</Trans>
+ </div>
+ <div className="text-xs text-muted-foreground">
+ <Trans>
+ No parent sources recorded yet. Click Recalculate on the
+ planning page to refresh attribution.
+ </Trans>
+ </div>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+ }
+
+ return (
+ <Popover>
+ <PopoverTrigger asChild>{children}</PopoverTrigger>
+ <PopoverContent className="w-xl max-h-112 overflow-y-auto">
+ <div className="flex flex-col gap-2 p-2">
+ <div className="text-sm font-medium">
+ <Trans>Demand Forecast — Driven by</Trans>
+ </div>
+ <div className="text-xs text-muted-foreground">
+ <Trans>
+ Demand forecast = BOM-exploded demand from open sales orders,
+ active jobs, and production projections.
+ </Trans>
+ </div>
+ <Table>
+ <Thead>
+ <Tr>
+ <Th>
+ <Trans>Source</Trans>
+ </Th>
+ <Th>
+ <Trans>Parent Item</Trans>
+ </Th>
+ <Th>
+ <Trans>Due</Trans>
+ </Th>
+ <Th className="text-right">
+ <Trans>Qty</Trans>
+ </Th>
+ </Tr>
+ </Thead>
+ <Tbody>
+ {sources.map((s, i) => {
+ // Pick the date that matters for each source type:
+ // Job Material → the job's due date
+ // Sales Order → the SO line's promised date
+ // Demand Projection → the projection's period start
+ const sourceDate =
+ s.sourceType === "Job Material"
+ ? s.job?.dueDate
+ : s.sourceType === "Sales Order"
+ ? s.salesOrderLine?.promisedDate
+ : s.sourceType === "Demand Projection"
+ ? s.demandProjection?.period?.startDate
+ : null;
+ return (
+ <Tr key={i}>
+ <Td>
+ {s.sourceType === "Job Material" && s.job ? (
+ <Link
+ to={path.to.job(s.job.id)}
+ className="text-primary hover:underline"
+ >
+ {s.job.jobId}
+ </Link>
+ ) : s.sourceType === "Sales Order" &&
+ s.salesOrderLine?.salesOrder ? (
+ <Link
+ to={path.to.salesOrder(
+ s.salesOrderLine.salesOrder.id
+ )}
+ className="text-primary hover:underline"
+ >
+ {s.salesOrderLine.salesOrder.salesOrderId}
+ </Link>
+ ) : s.sourceType === "Demand Projection" &&
+ s.demandProjection ? (
+ s.parentItemId && s.locationId ? (
+ <Link
+ to={path.to.demandProjection(
+ s.parentItemId,
+ s.locationId
+ )}
+ className="text-primary hover:underline"
+ title={s.demandProjection.notes ?? undefined}
+ >
+ <Trans>Projection</Trans>
+ {/* <span className="ml-1 text-xs text-muted-foreground font-mono">
+ {s.demandProjection.forecastMethod ?? "manual"}
+ </span> */}
+ </Link>
+ ) : (
+ <span
+ className="text-sm text-foreground"
+ title={s.demandProjection.notes ?? undefined}
+ >
+ <Trans>Projection</Trans>
+ <span className="ml-1 text-xs text-muted-foreground font-mono">
+ {s.demandProjection.forecastMethod ?? "manual"}
+ </span>
+ </span>
+ )
+ ) : (
+ <span className="text-muted-foreground">—</span>
+ )}
+ </Td>
+ <Td>
+ {s.parentItem ? (
+ <span title={s.parentItem.name}>
+ {s.parentItem.readableId}
+ </span>
+ ) : (
+ <span className="text-muted-foreground">—</span>
+ )}
+ </Td>
+ <Td>
+ {sourceDate ? (
+ formatDate(sourceDate)
+ ) : (
+ <span className="text-muted-foreground">—</span>
+ )}
+ </Td>
+ <Td className="text-right">
+ {numberFormatter.format(s.quantity)}
+ </Td>
+ </Tr>
+ );
+ })}
+ </Tbody>
+ </Table>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx b/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx
index 4b1b2a75ce..c6b9e33a8a 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx
@@ -50,9 +50,12 @@ import {
} from "recharts";
import { Empty, Hyperlink } from "~/components";
import { useDateFormatter as useDateFormat } from "~/hooks";
+import type { DemandForecastSourceRow } from "~/modules/items/items.service";
import type { loader as forecastLoader } from "~/routes/api+/items.$id.$locationId.forecast";
import { path } from "~/utils/path";
import type { PlannedOrder } from "../../../purchasing/purchasing.models";
+import { DemandForecastSourcesPopover } from "./DemandForecastSourcesPopover";
+import { PlannedOrderDetailsPopover } from "./PlannedOrderDetailsPopover";
const supplySourceTypes = ["Purchase Order", "Production Order"] as const;
const demandSourceTypes = ["Sales Order", "Job Material"] as const;
@@ -260,13 +263,24 @@ export const ItemPlanningChart = ({
})),
...(forecastFetcher.data?.demandForecast ?? []).map((forecast) => {
const period = periods.find((p) => p.id === forecast.periodId);
+ const sources = (
+ (forecastFetcher.data?.demandForecastSources ??
+ []) as DemandForecastSourceRow[]
+ ).filter(
+ (s) =>
+ s.itemId === forecast.itemId &&
+ s.periodId === forecast.periodId &&
+ (s.locationId ?? null) === (forecast.locationId ?? null)
+ );
return {
id: null,
sourceType: "Demand Forecast" as SourceType,
quantity: forecast.forecastQuantity ?? 0,
dueDate: period?.startDate ?? null,
documentReadableId: "Demand Forecast",
- documentId: null
+ documentId: null,
+ forecastMethod: forecast.forecastMethod ?? null,
+ forecastSources: sources
};
})
];
@@ -301,7 +315,8 @@ export const ItemPlanningChart = ({
quantity: (order.quantity ?? 0) * conversionFactor,
documentReadableId: "Planned",
documentId: null,
- id: null
+ id: null,
+ plannedOrder: order
}))
]
.sort((a, b) => (a.dueDate ?? "").localeCompare(b.dueDate ?? ""))
@@ -560,12 +575,18 @@ export const ItemPlanningChart = ({
</div>
<TabsContent value="all" className="border rounded-lg">
+ <SupplyDemandPlanningHeader />
{combinedSupplyAndDemand.map((item, index) => (
- <SupplyDemandPlanningItem key={index} item={item} />
+ <SupplyDemandPlanningItem
+ key={index}
+ item={item}
+ conversionFactor={conversionFactor}
+ />
))}
</TabsContent>
<TabsContent value="supply" className="border rounded-lg">
+ <SupplyDemandPlanningHeader />
{combinedSupplyAndDemand
.filter((item) =>
supplySourceTypes.includes(
@@ -573,11 +594,16 @@ export const ItemPlanningChart = ({
)
)
.map((item, index) => (
- <SupplyDemandPlanningItem key={index} item={item} />
+ <SupplyDemandPlanningItem
+ key={index}
+ item={item}
+ conversionFactor={conversionFactor}
+ />
))}
</TabsContent>
<TabsContent value="demand" className="border rounded-lg">
+ <SupplyDemandPlanningHeader />
{combinedSupplyAndDemand
.filter(
(item) =>
@@ -586,7 +612,11 @@ export const ItemPlanningChart = ({
) || item.sourceType === "Demand Forecast"
)
.map((item, index) => (
- <SupplyDemandPlanningItem key={index} item={item} />
+ <SupplyDemandPlanningItem
+ key={index}
+ item={item}
+ conversionFactor={conversionFactor}
+ />
))}
</TabsContent>
</CardContent>
@@ -608,6 +638,12 @@ interface PlanningItem {
jobId?: string | null;
jobMakeMethodId?: string | null;
existingOrderReadableId?: string | null;
+ forecastMethod?: string | null;
+ forecastSources?: DemandForecastSourceRow[];
+ // Planned-row metadata (only set on rows with sourceType === "Planned").
+ // Carries enough info for PlannedOrderDetailsPopover to render order facts,
+ // policy reasoning, and the linked PO section.
+ plannedOrder?: PlannedOrder;
}
const sourceTypeIcons: Record<SourceType, JSX.Element> = {
@@ -619,7 +655,32 @@ const sourceTypeIcons: Record<SourceType, JSX.Element> = {
"Demand Forecast": <LuChartLine className="size-4 text-cyan-500" />
};
-function SupplyDemandPlanningItem({ item }: { item: PlanningItem }) {
+function SupplyDemandPlanningHeader() {
+ return (
+ <div className="flex flex-1 justify-between items-center w-full px-4 py-2 border-b bg-muted/40 text-xs font-medium uppercase tracking-wide text-muted-foreground">
+ <HStack spacing={4} className="w-1/2">
+ <HStack spacing={4} className="flex-1">
+ <div className="size-8 shrink-0" aria-hidden />
+ <VStack spacing={0} className="flex-1">
+ <Trans>Source</Trans>
+ </VStack>
+ <div className="text-right">
+ <Trans>Quantity</Trans>
+ </div>
+ </HStack>
+ </HStack>
+ <Trans>On Hand</Trans>
+ </div>
+ );
+}
+
+function SupplyDemandPlanningItem({
+ item,
+ conversionFactor
+}: {
+ item: PlanningItem;
+ conversionFactor: number;
+}) {
const { t } = useLingui();
const numberFormatter = useNumberFormatter();
const { formatDate } = useDateFormat();
@@ -632,12 +693,39 @@ function SupplyDemandPlanningItem({ item }: { item: PlanningItem }) {
{sourceTypeIcons[item.sourceType]}
</div>
<VStack spacing={0}>
- <Hyperlink
- to={getPathToDocument(item)}
- className="text-sm font-medium"
- >
- {item.documentReadableId}
- </Hyperlink>
+ {item.sourceType === "Demand Forecast" ? (
+ <DemandForecastSourcesPopover
+ sources={item.forecastSources ?? []}
+ forecastQuantity={item.quantity}
+ forecastMethod={item.forecastMethod ?? null}
+ >
+ <button
+ type="button"
+ className="text-sm font-medium text-left hover:underline"
+ >
+ {item.documentReadableId}
+ </button>
+ </DemandForecastSourcesPopover>
+ ) : item.sourceType === "Planned" && item.plannedOrder ? (
+ <PlannedOrderDetailsPopover
+ order={item.plannedOrder}
+ conversionFactor={conversionFactor}
+ >
+ <button
+ type="button"
+ className="text-sm font-medium text-left hover:underline"
+ >
+ {item.documentReadableId}
+ </button>
+ </PlannedOrderDetailsPopover>
+ ) : (
+ <Hyperlink
+ to={getPathToDocument(item)}
+ className="text-sm font-medium"
+ >
+ {item.documentReadableId}
+ </Hyperlink>
+ )}
<span className="text-xs text-muted-foreground">
{item.dueDate ? formatDate(item.dueDate) : t`No due date`}
</span>
diff --git a/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx b/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx
index 35b3439d5b..0832d56320 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemReorderPolicy.tsx
@@ -111,6 +111,15 @@ function calculateOrders({ itemPlanning, periods }: BaseOrderParams): {
quantity: number;
periodId: string;
isASAP: boolean;
+ policyName?: string;
+ triggerValues?: {
+ projectedStock?: number;
+ safetyStock?: number;
+ reorderPoint?: number;
+ reorderQuantity?: number;
+ lotSize?: number;
+ leadTime?: number;
+ };
}[] {
// Check cache first
const cacheKey = getCacheKey(itemPlanning, periods);
@@ -125,6 +134,15 @@ function calculateOrders({ itemPlanning, periods }: BaseOrderParams): {
quantity: number;
periodId: string;
isASAP: boolean;
+ policyName?: string;
+ triggerValues?: {
+ projectedStock?: number;
+ safetyStock?: number;
+ reorderPoint?: number;
+ reorderQuantity?: number;
+ lotSize?: number;
+ leadTime?: number;
+ };
}[] = [];
ordersCache.set(cacheKey, emptyOrders);
return emptyOrders;
@@ -136,6 +154,15 @@ function calculateOrders({ itemPlanning, periods }: BaseOrderParams): {
quantity: number;
periodId: string;
isASAP: boolean;
+ policyName?: string;
+ triggerValues?: {
+ projectedStock?: number;
+ safetyStock?: number;
+ reorderPoint?: number;
+ reorderQuantity?: number;
+ lotSize?: number;
+ leadTime?: number;
+ };
}[] = [];
const {
@@ -156,26 +183,56 @@ function calculateOrders({ itemPlanning, periods }: BaseOrderParams): {
switch (itemPlanning.reorderingPolicy) {
case "Demand-Based Reorder":
- // Process periods in chunks of demandAccumulationPeriod
+ // Process periods in chunks of demandAccumulationPeriod.
+ //
+ // For each window we want two things:
+ // 1. Trigger date = the FIRST period in the window where the running
+ // projected balance dips below safety stock. The order has to
+ // arrive by then.
+ // 2. Order size = enough to lift the WORST dip (the minimum balance
+ // anywhere in the window) back to safety stock. Sizing against
+ // end-of-window alone is incorrect when demand is lumpy and the
+ // balance dips mid-window but recovers via scheduled supply.
+ //
+ // If no period in the window dips below safety stock, skip the window
+ // entirely (no order needed).
for (let i = 0; i < periods.length; i += demandAccumulationPeriod) {
- const currentPeriod = periods[i];
-
- // Calculate total demand for accumulation period
- let projectedStock = 0;
- for (
- let j = i;
- j < Math.min(i + demandAccumulationPeriod, periods.length);
- j++
- ) {
+ const windowEnd = Math.min(
+ i + demandAccumulationPeriod,
+ periods.length
+ );
+
+ let firstDipIndex = -1;
+ let minProjection = Number.POSITIVE_INFINITY;
+
+ for (let j = i; j < windowEnd; j++) {
const periodKey = `week${j + 1}` as "week1";
const periodProjection = (itemPlanning[periodKey] as number) || 0;
- projectedStock = periodProjection + orderedQuantity;
+ if (
+ firstDipIndex === -1 &&
+ periodProjection + orderedQuantity < demandAccumulationSafetyStock
+ ) {
+ firstDipIndex = j;
+ }
+ if (periodProjection < minProjection) {
+ minProjection = periodProjection;
+ }
}
- // If projected stock is below safety stock, create order
- if (projectedStock < demandAccumulationSafetyStock) {
- let totalOrderQuantity =
- demandAccumulationSafetyStock - projectedStock;
+ // Window is fully safe — no period dips below safety stock.
+ if (firstDipIndex === -1) continue;
+
+ const currentPeriod = periods[firstDipIndex];
+ const effectiveMinBalance = minProjection + orderedQuantity;
+
+ // Size so the worst dip in the window is brought up to safety stock.
+ // Clamp to >= 0 — if effectiveMinBalance happens to already be at
+ // safety stock (edge case), no qty needed before MOQ kicks in.
+ {
+ let totalOrderQuantity = Math.max(
+ 0,
+ demandAccumulationSafetyStock - effectiveMinBalance
+ );
// Apply lot sizing rules
if (maximumOrderQuantity > 0) {
@@ -219,7 +276,14 @@ function calculateOrders({ itemPlanning, periods }: BaseOrderParams): {
dueDate: dueDate.toString(),
quantity: batchQuantity,
periodId: currentPeriod.id,
- isASAP: startDate.compare(todaysDate) < 0
+ isASAP: startDate.compare(todaysDate) < 0,
+ policyName: "Demand-Based Reorder",
+ triggerValues: {
+ projectedStock: effectiveMinBalance,
+ safetyStock: demandAccumulationSafetyStock,
+ lotSize,
+ leadTime
+ }
});
}
} else {
@@ -237,7 +301,14 @@ function calculateOrders({ itemPlanning, periods }: BaseOrderParams): {
dueDate: dueDate.toString(),
quantity: orderQuantity,
periodId: currentPeriod.id,
- isASAP: startDate.compare(todaysDate) < 0
+ isASAP: startDate.compare(todaysDate) < 0,
+ policyName: "Demand-Based Reorder",
+ triggerValues: {
+ projectedStock: effectiveMinBalance,
+ safetyStock: demandAccumulationSafetyStock,
+ lotSize,
+ leadTime
+ }
});
}
@@ -274,7 +345,14 @@ function calculateOrders({ itemPlanning, periods }: BaseOrderParams): {
dueDate: dueDate.toString(),
quantity: orderQuantity,
periodId: period.id,
- isASAP: startDate.compare(todaysDate) < 0
+ isASAP: startDate.compare(todaysDate) < 0,
+ policyName: "Fixed Reorder Quantity",
+ triggerValues: {
+ projectedStock: projectedQuantity + orderedQuantity,
+ reorderPoint,
+ reorderQuantity,
+ leadTime
+ }
});
day++;
orderedQuantity += orderQuantity;
@@ -341,7 +419,14 @@ function calculateOrders({ itemPlanning, periods }: BaseOrderParams): {
periodId: period.id,
isASAP:
startDate.compare(todaysDate) < 0 &&
- projectedQuantity + orderedQuantity < 0
+ projectedQuantity + orderedQuantity < 0,
+ policyName: "Maximum Quantity",
+ triggerValues: {
+ projectedStock: projectedQuantity + orderedQuantity,
+ reorderPoint,
+ leadTime,
+ reorderQuantity
+ }
});
day++;
orderedQuantity += orderQuantity;
diff --git a/apps/erp/app/modules/items/ui/Item/PlannedOrderDetailsPopover.tsx b/apps/erp/app/modules/items/ui/Item/PlannedOrderDetailsPopover.tsx
new file mode 100644
index 0000000000..a03beac200
--- /dev/null
+++ b/apps/erp/app/modules/items/ui/Item/PlannedOrderDetailsPopover.tsx
@@ -0,0 +1,260 @@
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@carbon/react";
+import { Trans } from "@lingui/react/macro";
+import { useNumberFormatter } from "@react-aria/i18n";
+import type { ReactNode } from "react";
+import { LuInfo } from "react-icons/lu";
+import { Link } from "react-router";
+import { useCurrencyFormatter, useDateFormatter } from "~/hooks";
+import type { PlannedOrder } from "~/modules/purchasing/purchasing.models";
+import { useSuppliers } from "~/stores";
+import { path } from "~/utils/path";
+import { ItemReorderPolicy } from "./ItemReorderPolicy";
+
+type Props = {
+ order: PlannedOrder;
+ conversionFactor: number;
+ children: ReactNode;
+};
+
+export function PlannedOrderDetailsPopover({
+ order,
+ conversionFactor,
+ children
+}: Props) {
+ const numberFormatter = useNumberFormatter();
+ const { formatDate } = useDateFormatter();
+ const currencyFormatter = useCurrencyFormatter();
+ const [suppliers] = useSuppliers();
+
+ const supplierLabel = order.supplierId
+ ? (suppliers.find((s) => s.id === order.supplierId)?.name ?? null)
+ : null;
+
+ const hasPolicy = !!order.policyName;
+ const hasLinkedPo = !!order.existingLineId;
+ const inventoryQty = (order.quantity ?? 0) * conversionFactor;
+ const isAsap = (order as { isASAP?: boolean }).isASAP === true;
+
+ return (
+ <Popover>
+ <PopoverTrigger asChild>{children}</PopoverTrigger>
+ <PopoverContent className="w-md max-h-112 overflow-y-auto">
+ <div className="flex flex-col gap-3 p-2">
+ {/* Section A — Order facts */}
+ <div className="flex flex-col gap-1">
+ <div className="text-sm font-medium">
+ <Trans>Planned Order</Trans>
+ </div>
+ <div className="text-xs text-muted-foreground">
+ <Trans>
+ Planned order = MRP suggestion to cover projected demand based
+ on the item's reorder policy (or manually added).
+ </Trans>
+ </div>
+ <dl className="grid grid-cols-[max-content_1fr] gap-x-3 gap-y-1 text-sm">
+ <dt className="text-muted-foreground">
+ <Trans>Supplier</Trans>
+ </dt>
+ <dd>
+ {supplierLabel ?? (
+ <span className="text-muted-foreground">—</span>
+ )}
+ </dd>
+
+ <dt className="text-muted-foreground">
+ <Trans>Quantity</Trans>
+ </dt>
+ <dd>
+ {numberFormatter.format(order.quantity ?? 0)}
+ {conversionFactor !== 1 && (
+ <span className="ml-1 text-xs text-muted-foreground">
+ ({numberFormatter.format(inventoryQty)} <Trans>inv</Trans>)
+ </span>
+ )}
+ </dd>
+
+ {order.startDate && (
+ <>
+ <dt className="text-muted-foreground inline-flex items-center gap-1">
+ <Trans>Order by</Trans>
+ <Tooltip>
+ <TooltipTrigger tabIndex={-1}>
+ <LuInfo
+ className="size-3 cursor-help"
+ aria-label="info"
+ />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-xs">
+ <Trans>
+ The latest date to place this PO so it arrives by the
+ need-by date, given the supplier's lead time.
+ </Trans>
+ </TooltipContent>
+ </Tooltip>
+ </dt>
+ <dd>{formatDate(order.startDate)}</dd>
+ </>
+ )}
+
+ {order.dueDate && (
+ <>
+ <dt className="text-muted-foreground inline-flex items-center gap-1">
+ <Trans>Need by</Trans>
+ <Tooltip>
+ <TooltipTrigger tabIndex={-1}>
+ <LuInfo
+ className="size-3 cursor-help"
+ aria-label="info"
+ />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-xs">
+ <Trans>
+ The date the item is required on-site to cover the
+ period's projected demand.
+ </Trans>
+ </TooltipContent>
+ </Tooltip>
+ </dt>
+ <dd>
+ {formatDate(order.dueDate)}
+ {isAsap && (
+ <span className="ml-2 text-xs text-red-500 font-medium uppercase">
+ ASAP
+ </span>
+ )}
+ </dd>
+ </>
+ )}
+
+ {order.unitPrice != null && (
+ <>
+ <dt className="text-muted-foreground">
+ <Trans>Unit price</Trans>
+ </dt>
+ <dd>{currencyFormatter.format(order.unitPrice)}</dd>
+ </>
+ )}
+ </dl>
+ </div>
+
+ {/* Section B — Why suggested */}
+ {hasPolicy && (
+ <div className="flex flex-col gap-1 border-t pt-2">
+ <div className="text-sm font-medium">
+ <Trans>Why is this included?</Trans>
+ </div>
+ <dl className="grid grid-cols-[max-content_1fr] gap-x-3 gap-y-1 text-sm">
+ <dt className="text-muted-foreground">
+ <Trans>Policy</Trans>
+ </dt>
+ <dd>
+ {order.policyName && (
+ <ItemReorderPolicy
+ reorderingPolicy={
+ order.policyName as
+ | "Demand-Based Reorder"
+ | "Fixed Reorder Quantity"
+ | "Manual Reorder"
+ | "Maximum Quantity"
+ }
+ />
+ )}
+ </dd>
+
+ {order.triggerValues?.projectedStock != null && (
+ <>
+ <dt className="text-muted-foreground">
+ <Trans>Projected stock</Trans>
+ </dt>
+ <dd>
+ {numberFormatter.format(
+ order.triggerValues.projectedStock
+ )}
+ </dd>
+ </>
+ )}
+
+ {order.triggerValues?.safetyStock != null && (
+ <>
+ <dt className="text-muted-foreground">
+ <Trans>Safety stock</Trans>
+ </dt>
+ <dd>
+ {numberFormatter.format(order.triggerValues.safetyStock)}
+ </dd>
+ </>
+ )}
+
+ {order.triggerValues?.lotSize != null && (
+ <>
+ <dt className="text-muted-foreground">
+ <Trans>Lot size</Trans>
+ </dt>
+ <dd>
+ {numberFormatter.format(order.triggerValues.lotSize)}
+ </dd>
+ </>
+ )}
+
+ {order.triggerValues?.leadTime != null && (
+ <>
+ <dt className="text-muted-foreground">
+ <Trans>Lead time (days)</Trans>
+ </dt>
+ <dd>
+ {numberFormatter.format(order.triggerValues.leadTime)}
+ </dd>
+ </>
+ )}
+ </dl>
+ </div>
+ )}
+
+ {/* Section C — Linked PO */}
+ {hasLinkedPo && (
+ <div className="flex flex-col gap-1 border-t pt-2">
+ <div className="text-sm font-medium">
+ <Trans>Linked PO</Trans>
+ </div>
+ <dl className="grid grid-cols-[max-content_1fr] gap-x-3 gap-y-1 text-sm">
+ <dt className="text-muted-foreground">
+ <Trans>PO</Trans>
+ </dt>
+ <dd>
+ {order.existingId ? (
+ <Link
+ to={path.to.purchaseOrder(order.existingId)}
+ className="text-primary hover:underline"
+ >
+ {order.existingReadableId ?? order.existingId}
+ </Link>
+ ) : (
+ (order.existingReadableId ?? "—")
+ )}
+ </dd>
+
+ {order.existingStatus && (
+ <>
+ <dt className="text-muted-foreground">
+ <Trans>Status</Trans>
+ </dt>
+ <dd className="font-mono text-xs">
+ {order.existingStatus}
+ </dd>
+ </>
+ )}
+ </dl>
+ </div>
+ )}
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/apps/erp/app/modules/items/ui/Item/SupplierPartForm.tsx b/apps/erp/app/modules/items/ui/Item/SupplierPartForm.tsx
index 9da303cf6c..e4d4fd3c3f 100644
--- a/apps/erp/app/modules/items/ui/Item/SupplierPartForm.tsx
+++ b/apps/erp/app/modules/items/ui/Item/SupplierPartForm.tsx
@@ -140,13 +140,15 @@ const SupplierPartForm = ({
const action = getAction(isEditing, type, itemId, initialValues.id);
const fetcher = useFetcher<{ success: boolean; message: string }>();
+ // biome-ignore lint/correctness/useExhaustiveDependencies: onClose must be excluded — it is a new ref each render in route components, which would cause an infinite re-fire loop
useEffect(() => {
if (fetcher.data?.success) {
+ if (fetcher.data?.message) toast.success(fetcher.data.message);
onClose();
} else if (fetcher.data?.message) {
toast.error(fetcher.data.message);
}
- }, [fetcher.data?.success, fetcher.data?.message, onClose]);
+ }, [fetcher.data?.success, fetcher.data?.message]);
return (
<Drawer
diff --git a/apps/erp/app/modules/items/ui/Item/UsedIn.tsx b/apps/erp/app/modules/items/ui/Item/UsedIn.tsx
index e496905892..e47999719f 100644
--- a/apps/erp/app/modules/items/ui/Item/UsedIn.tsx
+++ b/apps/erp/app/modules/items/ui/Item/UsedIn.tsx
@@ -14,6 +14,9 @@ import {
InputGroup,
InputLeftElement,
Skeleton,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
useDisclosure,
VStack
} from "@carbon/react";
@@ -93,11 +96,17 @@ const revisionValidator = z.array(
})
);
+export type JobMaterialUsage = {
+ byMaterialId: Record<string, number>;
+ byJobId: Record<string, number>;
+};
+
export function UsedInTree({
tree,
revisions: revisionsJson,
itemReadableId,
itemReadableIdWithRevision,
+ jobMaterialUsage,
hasSizesInsteadOfRevisions = false,
filterText: filterTextProp,
hideSearch
@@ -106,6 +115,7 @@ export function UsedInTree({
revisions?: Json;
itemReadableId: string;
itemReadableIdWithRevision: string;
+ jobMaterialUsage?: JobMaterialUsage;
hasSizesInsteadOfRevisions?: boolean;
filterText?: string;
hideSearch?: boolean;
@@ -114,6 +124,9 @@ export function UsedInTree({
const [filterTextInternal, setFilterTextInternal] = useState("");
const filterText = filterTextProp ?? filterTextInternal;
+ const jobMaterialQuantities = jobMaterialUsage?.byMaterialId ?? {};
+ const jobQuantities = jobMaterialUsage?.byJobId ?? {};
+
const revisions = (
revisionValidator.safeParse(revisionsJson)?.data ?? []
)?.map((r) => ({
@@ -128,7 +141,7 @@ export function UsedInTree({
<VStack className="w-full p-2">
{!hideSearch && (
<HStack className="w-full py">
- <InputGroup size="sm" className="flex flex-grow">
+ <InputGroup size="sm" className="flex grow">
<InputLeftElement>
<LuSearch className="h-4 w-4" />
</InputLeftElement>
@@ -158,6 +171,8 @@ export function UsedInTree({
filterText={filterText}
node={node}
itemReadableIdWithRevision={itemReadableIdWithRevision}
+ jobMaterialQuantities={jobMaterialQuantities}
+ jobQuantities={jobQuantities}
/>
))}
</VStack>
@@ -379,11 +394,15 @@ function getNextRevision(maxRevision: string) {
export function UsedInItem({
node,
itemReadableIdWithRevision,
- filterText
+ filterText,
+ jobMaterialQuantities,
+ jobQuantities
}: {
node: UsedInNode;
filterText: string;
itemReadableIdWithRevision: string;
+ jobMaterialQuantities?: Record<string, number>;
+ jobQuantities?: Record<string, number>;
}) {
const { t } = useLingui();
const [isExpanded, setIsExpanded] = useState(
@@ -446,6 +465,34 @@ export function UsedInItem({
/>
)}
<span className="truncate">{child.documentReadableId}</span>
+ {node.key === "jobMaterials" &&
+ jobMaterialQuantities &&
+ child.id in jobMaterialQuantities && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge variant="outline" className="ml-2">
+ {jobMaterialQuantities[child.id]}
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent>
+ Estimated quantity required for this job material
+ </TooltipContent>
+ </Tooltip>
+ )}
+ {node.key === "jobs" &&
+ jobQuantities &&
+ child.id in jobQuantities && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge variant="outline" className="ml-2">
+ {jobQuantities[child.id]}
+ </Badge>
+ </TooltipTrigger>
+ <TooltipContent>
+ Production quantity for this job
+ </TooltipContent>
+ </Tooltip>
+ )}
{child.version && (
<Badge variant="outline" className="ml-2">
V{child.version}
diff --git a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningOrderDrawer.tsx b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningOrderDrawer.tsx
index a4ebef1c80..fe72d03c8a 100644
--- a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningOrderDrawer.tsx
+++ b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningOrderDrawer.tsx
@@ -497,10 +497,11 @@ export const ProductionPlanningOrderDrawer = memo(
<Button
variant="primary"
onClick={() => onSubmit(row.id, orders)}
+ disabled={fetcher.state !== "idle"}
isDisabled={fetcher.state !== "idle"}
isLoading={fetcher.state !== "idle"}
>
- Order
+ Make
</Button>
</DrawerFooter>
</DrawerContent>
diff --git a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx
index 909589a52e..4b096f5023 100644
--- a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx
+++ b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx
@@ -401,10 +401,10 @@ const ProductionPlanningTable = ({
) : hasOrders ? (
<HStack>
<PulsingDot />
- <span>Order {orderQuantity}</span>
+ <span>Make {orderQuantity}</span>
</HStack>
) : (
- "Order"
+ "Make"
)}
</Button>
</div>
diff --git a/apps/erp/app/modules/purchasing/purchasing.models.ts b/apps/erp/app/modules/purchasing/purchasing.models.ts
index 9151d16d38..81e85559a0 100644
--- a/apps/erp/app/modules/purchasing/purchasing.models.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.models.ts
@@ -106,7 +106,21 @@ export const plannedOrderValidator = z.object({
supplierId: zfd.text(z.string().optional()),
itemReadableId: zfd.text(z.string().optional()),
unitPrice: zfd.numeric(z.number().optional()),
- unitOfMeasureCode: zfd.text(z.string().optional())
+ unitOfMeasureCode: zfd.text(z.string().optional()),
+ // ── Reorder-policy attribution (populated by calculateOrders for
+ // MRP-suggested orders; absent for user-added "Add Order" rows). ──
+ policyName: zfd.text(z.string().optional()),
+ reason: zfd.text(z.string().optional()),
+ triggerValues: z
+ .object({
+ projectedStock: z.number().optional(),
+ safetyStock: z.number().optional(),
+ reorderPoint: z.number().optional(),
+ reorderQuantity: z.number().optional(),
+ lotSize: z.number().optional(),
+ leadTime: z.number().optional()
+ })
+ .optional()
});
export type PlannedOrder = z.infer<typeof plannedOrderValidator>;
diff --git a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningOrderDrawer.tsx b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningOrderDrawer.tsx
index 1d6d8369ce..3b763185fb 100644
--- a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningOrderDrawer.tsx
+++ b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningOrderDrawer.tsx
@@ -106,13 +106,20 @@ export const PurchasingPlanningOrderDrawer = memo(
?.from("openPurchaseOrderLines")
.select("*")
.eq("itemId", selectedItem.id)
- .in("status", ["Draft", "Planned"]);
+ .in("status", [
+ "To Review",
+ "Needs Approval",
+ "Planned",
+ "To Receive",
+ "To Receive and Invoice",
+ "To Invoice"
+ ]);
if (existingOrderData) {
const existingOrders: PlannedOrder[] = existingOrderData
.filter(
(order) =>
- !orders.some((existing) => existing.existingId === order.id)
+ !orders.some((existing) => existing.existingLineId === order.id)
)
.map((order) => {
const dueDate = order.dueDate;
@@ -228,7 +235,17 @@ export const PurchasingPlanningOrderDrawer = memo(
const onSubmit = useCallback(
(id: string, orders: PlannedOrder[]) => {
- const ordersWithPeriods = orders.map((order) => {
+ // Skip existing PO lines that are past the Planned stage — their
+ // quantity/due-date inputs are disabled in the UI, so the user can't
+ // have edited them, and we don't want the action to issue UPDATEs
+ // against already-shipped lines.
+ const editableOrders = orders.filter(
+ (order) =>
+ !order.existingLineId ||
+ order.existingStatus === "Draft" ||
+ order.existingStatus === "Planned"
+ );
+ const ordersWithPeriods = editableOrders.map((order) => {
if (
!order.dueDate ||
parseDate(order.dueDate) < parseDate(periods[0].startDate)
@@ -643,9 +660,20 @@ export const PurchasingPlanningOrderDrawer = memo(
</Thead>
<Tbody>
{orders.map((order, index) => {
+ // Lock the row when (a) the selected supplier differs
+ // from the order's supplier, or (b) the existing PO
+ // line is past the Planned stage (already shipped /
+ // being received / being invoiced). Once committed
+ // to the supplier, mutating quantity or due date
+ // would desync the receiving workflow.
+ const isPostPlannedExisting =
+ !!order.existingLineId &&
+ order.existingStatus !== "Draft" &&
+ order.existingStatus !== "Planned";
const isDisabled =
- selectedSupplier !== order.supplierId &&
- !!order.existingId;
+ (selectedSupplier !== order.supplierId &&
+ !!order.existingId) ||
+ isPostPlannedExisting;
return (
<Tr key={index}>
@@ -704,6 +732,7 @@ export const PurchasingPlanningOrderDrawer = memo(
? parseDate(order.dueDate)
: null
}
+ isDisabled={isDisabled}
onChange={(date) => {
onOrderUpdate(index, {
dueDate: date ? date.toString() : null
@@ -770,6 +799,7 @@ export const PurchasingPlanningOrderDrawer = memo(
}
onSubmit(selectedItem.id, orders);
}}
+ disabled={fetcher.state !== "idle"}
isDisabled={fetcher.state !== "idle"}
isLoading={fetcher.state !== "idle"}
>
diff --git a/apps/erp/app/modules/sales/ui/Pricing/PriceTracePopover.tsx b/apps/erp/app/modules/sales/ui/Pricing/PriceTracePopover.tsx
index e6415706ad..349341a40d 100644
--- a/apps/erp/app/modules/sales/ui/Pricing/PriceTracePopover.tsx
+++ b/apps/erp/app/modules/sales/ui/Pricing/PriceTracePopover.tsx
@@ -8,6 +8,9 @@ import {
Td,
Th,
Thead,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
Tr
} from "@carbon/react";
import { Trans } from "@lingui/react/macro";
@@ -63,6 +66,7 @@ export function PriceTracePopover({
) : (
<button
type="button"
+ aria-label="How this price was calculated"
className="text-xxs text-muted-foreground hover:text-foreground inline-flex items-center gap-0.5"
>
<LuCalculator className="size-3" />
@@ -71,7 +75,18 @@ export function PriceTracePopover({
return (
<Popover>
- <PopoverTrigger asChild>{trigger}</PopoverTrigger>
+ {children ? (
+ <PopoverTrigger asChild>{trigger}</PopoverTrigger>
+ ) : (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <PopoverTrigger asChild>{trigger}</PopoverTrigger>
+ </TooltipTrigger>
+ <TooltipContent>
+ <Trans>How this price was calculated</Trans>
+ </TooltipContent>
+ </Tooltip>
+ )}
<PopoverContent align="end" sideOffset={8} className="max-w-[800px] p-0">
<div className="px-4 py-3 border-b border-border">
<p className="text-sm font-semibold">
diff --git a/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts b/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts
index cb812853c1..517a1fea4c 100644
--- a/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts
+++ b/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts
@@ -5,6 +5,7 @@ import { getLocalTimeZone, today } from "@internationalized/date";
import type { LoaderFunctionArgs } from "react-router";
import { data } from "react-router";
import {
+ getDemandForecastSources,
getItemDemand,
getItemQuantities,
getItemSupply,
@@ -18,6 +19,7 @@ import { getOrCreatePeriods } from "~/modules/shared/shared.server";
const defaultResponse = {
demand: [],
demandForecast: [],
+ demandForecastSources: [],
supply: [],
periods: [],
quantityOnHand: 0,
@@ -50,7 +52,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
openSalesOrderLines,
openJobMaterials,
openProductionOrders,
- openPurchaseOrderLines
+ openPurchaseOrderLines,
+ demandForecastSources
] = await Promise.all([
getItemDemand(client, {
itemId,
@@ -68,7 +71,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
getOpenSalesOrderLines(client, { itemId, companyId, locationId }),
getOpenJobMaterials(client, { itemId, companyId, locationId }),
getOpenProductionOrders(client, { itemId, companyId, locationId }),
- getOpenPurchaseOrderLines(client, { itemId, companyId, locationId })
+ getOpenPurchaseOrderLines(client, { itemId, companyId, locationId }),
+ getDemandForecastSources(client, {
+ itemId,
+ locationId,
+ periods: periods.map((p) => p.id ?? ""),
+ companyId
+ })
]);
if (demand.actuals.length === 0 && demand.forecasts.length === 0) {
@@ -81,6 +90,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return {
demand: demand.actuals,
demandForecast: demand.forecasts,
+ demandForecastSources: demandForecastSources.data ?? [],
supply: [
...supply.actuals,
...supply.forecasts.map((f) => ({
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 c6e5d073ef..7a3ee51ae7 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-27T14:05:32.644Z",
+ "generated": "2026-05-28T18:11:04.093Z",
"totalTools": 1083,
"modules": 15,
"tools": [
diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.new.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.new.tsx
index a229bdb8d9..be3ecac4f1 100644
--- a/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.new.tsx
+++ b/apps/erp/app/routes/x+/consumable+/$itemId.purchasing.new.tsx
@@ -1,10 +1,9 @@
-import { assertIsPost, success } from "@carbon/auth";
+import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
import { useRouteData } from "@carbon/react";
import type { ActionFunctionArgs } from "react-router";
-import { redirect, useNavigate, useParams } from "react-router";
+import { useNavigate, useParams } from "react-router";
import type { ConsumableSummary } from "~/modules/items";
import { supplierPartValidator, upsertSupplierPart } from "~/modules/items";
import { SupplierPartForm } from "~/modules/items/ui/Item";
@@ -68,10 +67,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
}
- throw redirect(
- path.to.consumablePurchasing(itemId),
- await flash(request, success("Consumable supplier created"))
- );
+ return { success: true, message: "Consumable supplier created" };
}
export default function NewConsumableSupplierRoute() {
diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.tsx
index 0ece83e530..af82e5e8dd 100644
--- a/apps/erp/app/routes/x+/consumable+/$itemId.tsx
+++ b/apps/erp/app/routes/x+/consumable+/$itemId.tsx
@@ -107,7 +107,8 @@ export default function ConsumableRoute() {
quoteMaterials,
salesOrderLines,
shipmentLines,
- supplierQuotes
+ supplierQuotes,
+ jobMaterialUsage
} = resolvedUsedIn;
const tree: UsedInNode[] = [
@@ -198,6 +199,7 @@ export default function ConsumableRoute() {
consumableData.consumableSummary
?.readableIdWithRevision ?? ""
}
+ jobMaterialUsage={jobMaterialUsage}
/>
);
}}
diff --git a/apps/erp/app/routes/x+/job+/$jobId.make.$methodId.tsx b/apps/erp/app/routes/x+/job+/$jobId.make.$methodId.tsx
index f22aab2388..94530ee0d8 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.make.$methodId.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.make.$methodId.tsx
@@ -140,77 +140,79 @@ export default function JobMakeMethodRoute() {
});
return (
- <VStack spacing={2} className="p-2">
- <JobMakeMethodTools makeMethod={makeMethod} />
+ <div className="h-full w-full items-start overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">
+ <VStack spacing={2} className="p-2">
+ <JobMakeMethodTools makeMethod={makeMethod} />
- <JobBillOfMaterial
- key={`bom:${methodId}`}
- jobMakeMethodId={methodId}
- // @ts-expect-error TS2322 - TODO: fix type
- materials={materials}
- // @ts-expect-error
- operations={operations}
- />
- <JobBillOfProcess
- key={`bop:${methodId}`}
- jobMakeMethodId={methodId}
- materials={materials}
- // @ts-expect-error
- operations={operations}
- locationId={routeData?.job?.locationId ?? ""}
- tags={tags}
- itemId={makeMethod.itemId}
- salesOrderLineId={job.salesOrderLineId ?? ""}
- customerId={job.customerId ?? ""}
- />
- <Suspense
- fallback={
- <div className="flex w-full h-full rounded bg-gradient-to-tr from-background to-card items-center justify-center min-h-[200px]">
- <Spinner className="h-10 w-10" />
- </div>
- }
- >
- <Await resolve={productionData}>
- {(resolvedProductionData) => (
- <JobEstimatesVsActuals
- materials={materials ?? []}
- // @ts-expect-error
- operations={operations}
- productionEvents={resolvedProductionData.events}
- productionQuantities={resolvedProductionData.quantities}
- notes={resolvedProductionData.notes}
+ <JobBillOfMaterial
+ key={`bom:${methodId}`}
+ jobMakeMethodId={methodId}
+ // @ts-expect-error TS2322 - TODO: fix type
+ materials={materials}
+ // @ts-expect-error
+ operations={operations}
+ />
+ <JobBillOfProcess
+ key={`bop:${methodId}`}
+ jobMakeMethodId={methodId}
+ materials={materials}
+ // @ts-expect-error
+ operations={operations}
+ locationId={routeData?.job?.locationId ?? ""}
+ tags={tags}
+ itemId={makeMethod.itemId}
+ salesOrderLineId={job.salesOrderLineId ?? ""}
+ customerId={job.customerId ?? ""}
+ />
+ <Suspense
+ fallback={
+ <div className="flex w-full h-full rounded bg-gradient-to-tr from-background to-card items-center justify-center min-h-[200px]">
+ <Spinner className="h-10 w-10" />
+ </div>
+ }
+ >
+ <Await resolve={productionData}>
+ {(resolvedProductionData) => (
+ <JobEstimatesVsActuals
+ materials={materials ?? []}
+ // @ts-expect-error
+ operations={operations}
+ productionEvents={resolvedProductionData.events}
+ productionQuantities={resolvedProductionData.quantities}
+ notes={resolvedProductionData.notes}
+ />
+ )}
+ </Await>
+ </Suspense>
+ <DeferredFiles resolve={files}>
+ {(files) => (
+ <JobDocuments
+ files={files}
+ jobId={jobId}
+ bucket="parts"
+ itemId={makeMethod.itemId}
+ modelUpload={{ ...job }}
/>
)}
- </Await>
- </Suspense>
- <DeferredFiles resolve={files}>
- {(files) => (
- <JobDocuments
- files={files}
- jobId={jobId}
- bucket="parts"
- itemId={makeMethod.itemId}
- modelUpload={{ ...job }}
- />
- )}
- </DeferredFiles>
- <Suspense fallback={null}>
- <Await resolve={loaderData.model}>
- {(model) => (
- <CadModel
- key={`cad:${model.itemId}`}
- isReadOnly={!permissions.can("update", "sales")}
- metadata={{
- itemId: model?.itemId ?? undefined
- }}
- modelPath={model?.modelPath ?? null}
- title="CAD Model"
- uploadClassName="aspect-square min-h-[420px] max-h-[70vh]"
- viewerClassName="aspect-square min-h-[420px] max-h-[70vh]"
- />
- )}
- </Await>
- </Suspense>
- </VStack>
+ </DeferredFiles>
+ <Suspense fallback={null}>
+ <Await resolve={loaderData.model}>
+ {(model) => (
+ <CadModel
+ key={`cad:${model.itemId}`}
+ isReadOnly={!permissions.can("update", "sales")}
+ metadata={{
+ itemId: model?.itemId ?? undefined
+ }}
+ modelPath={model?.modelPath ?? null}
+ title="CAD Model"
+ uploadClassName="aspect-square min-h-[420px] max-h-[70vh]"
+ viewerClassName="aspect-square min-h-[420px] max-h-[70vh]"
+ />
+ )}
+ </Await>
+ </Suspense>
+ </VStack>
+ </div>
);
}
diff --git a/apps/erp/app/routes/x+/material+/$itemId.purchasing.new.tsx b/apps/erp/app/routes/x+/material+/$itemId.purchasing.new.tsx
index dc7a8b0d26..4d1047c0c3 100644
--- a/apps/erp/app/routes/x+/material+/$itemId.purchasing.new.tsx
+++ b/apps/erp/app/routes/x+/material+/$itemId.purchasing.new.tsx
@@ -1,10 +1,9 @@
-import { assertIsPost, success } from "@carbon/auth";
+import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
import { useRouteData } from "@carbon/react";
import type { ActionFunctionArgs } from "react-router";
-import { redirect, useNavigate, useParams } from "react-router";
+import { useNavigate, useParams } from "react-router";
import type { MaterialSummary } from "~/modules/items";
import { supplierPartValidator, upsertSupplierPart } from "~/modules/items";
import { SupplierPartForm } from "~/modules/items/ui/Item";
@@ -68,10 +67,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
}
- throw redirect(
- path.to.materialPurchasing(itemId),
- await flash(request, success("Material supplier created"))
- );
+ return { success: true, message: "Material supplier created" };
}
export default function NewMaterialSupplierRoute() {
diff --git a/apps/erp/app/routes/x+/material+/$itemId.tsx b/apps/erp/app/routes/x+/material+/$itemId.tsx
index c915bf0db2..d418add01f 100644
--- a/apps/erp/app/routes/x+/material+/$itemId.tsx
+++ b/apps/erp/app/routes/x+/material+/$itemId.tsx
@@ -110,7 +110,8 @@ export default function MaterialRoute() {
quoteMaterials,
salesOrderLines,
shipmentLines,
- supplierQuotes
+ supplierQuotes,
+ jobMaterialUsage
} = resolvedUsedIn;
const tree: UsedInNode[] = [
@@ -202,6 +203,7 @@ export default function MaterialRoute() {
materialData.materialSummary
?.readableIdWithRevision ?? ""
}
+ jobMaterialUsage={jobMaterialUsage}
/>
);
}}
diff --git a/apps/erp/app/routes/x+/part+/$itemId.purchasing.new.tsx b/apps/erp/app/routes/x+/part+/$itemId.purchasing.new.tsx
index 4b082c23b3..54466fae7a 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.purchasing.new.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.purchasing.new.tsx
@@ -1,10 +1,9 @@
-import { assertIsPost, success } from "@carbon/auth";
+import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
import { validator } from "@carbon/form";
import { useRouteData } from "@carbon/react";
import type { ActionFunctionArgs } from "react-router";
-import { redirect, useNavigate, useParams } from "react-router";
+import { useNavigate, useParams } from "react-router";
import type { PartSummary } from "~/modules/items";
import { supplierPartValidator, upsertSupplierPart } from "~/modules/items";
import { SupplierPartForm } from "~/modules/items/ui/Item";
@@ -71,10 +70,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
}
- throw redirect(
- path.to.partPurchasing(itemId),
- await flash(request, success("Part supplier created"))
- );
+ return { success: true, message: "Part supplier created" };
}
export default function NewPartSupplierRoute() {
diff --git a/apps/erp/app/routes/x+/part+/$itemId.tsx b/apps/erp/app/routes/x+/part+/$itemId.tsx
index af8f738047..0fe22dca9a 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.tsx
@@ -234,7 +234,8 @@ export default function PartRoute() {
quoteMaterials,
salesOrderLines,
shipmentLines,
- supplierQuotes
+ supplierQuotes,
+ jobMaterialUsage
} = resolvedUsedIn;
const tree: UsedInNode[] = [
@@ -340,6 +341,7 @@ export default function PartRoute() {
partData.partSummary
?.readableIdWithRevision ?? ""
}
+ jobMaterialUsage={jobMaterialUsage}
filterText={filterText}
hideSearch
/>
@@ -380,7 +382,8 @@ export default function PartRoute() {
quoteMaterials,
salesOrderLines,
shipmentLines,
- supplierQuotes
+ supplierQuotes,
+ jobMaterialUsage
} = resolvedUsedIn;
const tree: UsedInNode[] = [
@@ -486,6 +489,7 @@ export default function PartRoute() {
partData.partSummary
?.readableIdWithRevision ?? ""
}
+ jobMaterialUsage={jobMaterialUsage}
filterText={filterText}
hideSearch
/>
diff --git a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx b/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
index 81586dcfe7..b20a0aa197 100644
--- a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
@@ -5,7 +5,6 @@ import { z } from "zod";
import { getCurrencyByCode } from "~/modules/accounting/accounting.service";
import {
plannedOrderValidator,
- updatePurchaseOrder,
upsertPurchaseOrder,
upsertPurchaseOrderLine
} from "~/modules/purchasing";
@@ -117,31 +116,33 @@ export async function action({ request }: ActionFunctionArgs) {
updatedBy: string;
}> = [];
- // Group items and orders by supplier
- const ordersBySupplier: Map<
- string,
- Array<{
- itemId: string;
- order: (typeof itemsToOrder)[0]["orders"][0];
- }>
- > = new Map();
+ // Separate existing-line updates from new orders, and group new
+ // orders by supplier+period so each period gets its own PO.
+ type OrderEntry = {
+ itemId: string;
+ order: (typeof itemsToOrder)[0]["orders"][0];
+ };
+ const existingLineUpdates: OrderEntry[] = [];
+ const ordersBySupplierPeriod = new Map<string, OrderEntry[]>();
for (const item of itemsToOrder) {
itemIds.add(item.id);
for (const order of item.orders) {
- if (order.supplierId) {
- supplierIds.add(order.supplierId);
- if (!ordersBySupplier.has(order.supplierId)) {
- ordersBySupplier.set(order.supplierId, []);
+ if (order.supplierId) supplierIds.add(order.supplierId);
+ if (order.periodId) periodIds.add(order.periodId);
+
+ if (order.existingLineId) {
+ existingLineUpdates.push({ itemId: item.id, order });
+ } else if (order.supplierId && order.periodId) {
+ const key = `${order.supplierId}::${order.periodId}`;
+ if (!ordersBySupplierPeriod.has(key)) {
+ ordersBySupplierPeriod.set(key, []);
}
- ordersBySupplier.get(order.supplierId)!.push({
+ ordersBySupplierPeriod.get(key)!.push({
itemId: item.id,
order
});
}
- if (order.periodId) {
- periodIds.add(order.periodId);
- }
}
}
@@ -216,52 +217,72 @@ export async function action({ request }: ActionFunctionArgs) {
let processedItems = 0;
let errors: string[] = [];
- // Process orders grouped by supplier
- for (const [supplierId, ordersForSupplier] of ordersBySupplier) {
+ // ── UPDATE existing draft/planned lines ──
+ for (const { order } of existingLineUpdates) {
+ const updateLine = await client
+ .from("purchaseOrderLine")
+ .update({
+ purchaseQuantity: order.quantity,
+ requiredDate: order.dueDate ?? null,
+ updatedBy: userId
+ })
+ .eq("id", order.existingLineId!);
+ if (updateLine.error) {
+ errors.push(
+ `Failed to update existing PO line ${order.existingLineId}: ${updateLine.error.message}`
+ );
+ }
+ }
+
+ // ── CREATE new PO lines, one PO per supplier+period ──
+ // Cache created POs so multiple items in the same supplier+period
+ // share one PO.
+ const poCache = new Map<string, string>(); // key → purchaseOrderId
+
+ for (const [key, ordersInGroup] of ordersBySupplierPeriod) {
+ const [supplierId, periodId] = key.split("::");
const supplier = suppliersById.get(supplierId);
if (!supplier) {
- const errorMsg = `Supplier ${supplierId} not found`;
- console.error(errorMsg);
- errors.push(errorMsg);
+ errors.push(`Supplier ${supplierId} not found`);
continue;
}
- // Get existing purchase orders for this supplier
- const { data: existingPurchaseOrders, error: poError } = await client
- .from("purchaseOrder")
- .select("id, purchaseOrderId, status")
- .eq("supplierId", supplierId)
- .in("status", ["Draft", "Planned"]);
+ // Find or create a PO for this supplier+period
+ let purchaseOrderId = poCache.get(key);
- if (poError) {
- const errorMsg = `Failed to retrieve existing purchase orders for supplier ${supplierId}: ${poError.message}`;
- console.error(errorMsg);
- errors.push(errorMsg);
- continue;
+ if (!purchaseOrderId) {
+ const period = periods.data?.find((p) => p.id === periodId);
+
+ if (period) {
+ // Find an existing PO line in this period for this supplier,
+ // then use its parent PO.
+ const { data: matchingLines } = await client
+ .from("purchaseOrderLine")
+ .select(
+ "purchaseOrderId, purchaseOrder!inner(supplierId, status)"
+ )
+ .gte("requiredDate", period.startDate)
+ .lte("requiredDate", period.endDate)
+ .eq("purchaseOrder.supplierId", supplierId)
+ .in("purchaseOrder.status", ["Draft", "Planned"])
+ .limit(1);
+
+ if (matchingLines?.[0]) {
+ purchaseOrderId = matchingLines[0].purchaseOrderId;
+ }
+ }
}
- // Use the first existing Draft/Planned PO, or create a new one
- let purchaseOrderId = existingPurchaseOrders?.[0]?.id;
- let createdNewPO = false;
-
if (!purchaseOrderId) {
const nextSequence = await getNextSequence(
client,
"purchaseOrder",
companyId
);
- if (nextSequence.error) {
- const errorMsg = `Failed to generate purchase order sequence for supplier ${supplierId}: ${nextSequence.error.message}`;
- console.error(errorMsg);
- errors.push(errorMsg);
- continue;
- }
-
- const purchaseOrderIdValue = nextSequence.data;
- if (!purchaseOrderIdValue) {
- const errorMsg = `Failed to generate purchase order ID for supplier ${supplierId}`;
- console.error(errorMsg);
- errors.push(errorMsg);
+ if (nextSequence.error || !nextSequence.data) {
+ errors.push(
+ `Failed to generate PO sequence for supplier ${supplierId}`
+ );
continue;
}
@@ -272,28 +293,20 @@ export async function action({ request }: ActionFunctionArgs) {
companyGroupId,
supplier.currencyCode ?? baseCurrencyCode
);
-
- if (currency.error) {
- const errorMsg = `Failed to retrieve exchange rate for currency ${supplier.currencyCode}: ${currency.error.message}`;
- console.error(errorMsg);
- errors.push(errorMsg);
- continue;
- }
-
- if (currency.data) {
+ if (!currency.error && currency.data) {
exchangeRate = currency.data.exchangeRate ?? 1;
}
}
- const createPurchaseOrder = await upsertPurchaseOrder(
+ const createPO = await upsertPurchaseOrder(
client,
{
- purchaseOrderId: purchaseOrderIdValue,
+ purchaseOrderId: nextSequence.data,
status: "Planned" as const,
supplierId,
purchaseOrderType: "Purchase",
currencyCode: supplier.currencyCode ?? baseCurrencyCode,
- exchangeRate: exchangeRate,
+ exchangeRate,
companyId,
companyGroupId,
createdBy: userId
@@ -301,46 +314,20 @@ export async function action({ request }: ActionFunctionArgs) {
undefined
);
- if (createPurchaseOrder.error) {
- const errorMsg = `Failed to create purchase order for supplier ${supplierId}: ${createPurchaseOrder.error.message}`;
- console.error(errorMsg);
- errors.push(errorMsg);
- continue;
- }
-
- const purchaseOrder = createPurchaseOrder.data?.[0];
- if (!purchaseOrder) {
- const errorMsg = `Purchase order was not returned after creation for supplier ${supplierId}`;
- console.error(errorMsg);
- errors.push(errorMsg);
+ if (createPO.error || !createPO.data?.[0]) {
+ errors.push(
+ `Failed to create PO for supplier ${supplierId}: ${createPO.error?.message ?? "no data returned"}`
+ );
continue;
}
- purchaseOrderId = purchaseOrder.id;
- createdNewPO = true;
+ purchaseOrderId = createPO.data[0].id;
}
- // Group orders by itemId to consolidate into single lines
- const ordersByItem = new Map<
- string,
- Array<{
- order: (typeof ordersForSupplier)[0]["order"];
- periodId: string;
- }>
- >();
-
- for (const { itemId, order } of ordersForSupplier) {
- if (!ordersByItem.has(itemId)) {
- ordersByItem.set(itemId, []);
- }
- ordersByItem.get(itemId)!.push({
- order,
- periodId: order.periodId
- });
- }
+ poCache.set(key, purchaseOrderId);
- // Now create one line per item (consolidating all orders for that item)
- for (const [itemId, itemOrders] of ordersByItem) {
+ // Create one line per item in this supplier+period group
+ for (const { itemId, order } of ordersInGroup) {
const supplierPart = supplierParts?.data?.find(
(sp) => sp.itemId === itemId && sp.supplierId === supplierId
);
@@ -352,32 +339,20 @@ export async function action({ request }: ActionFunctionArgs) {
.single();
if (purchasing.error) {
- const errorMsg = `Failed to retrieve purchasing data for item ${itemId}: ${purchasing.error.message}`;
- console.error(errorMsg);
- errors.push(errorMsg);
+ errors.push(
+ `Failed to retrieve purchasing data for item ${itemId}: ${purchasing.error.message}`
+ );
continue;
}
if (purchasing.data?.purchasingBlocked) {
- const errorMsg = `Purchasing is blocked for item ${itemId}`;
- console.error(errorMsg);
- errors.push(errorMsg);
+ errors.push(`Purchasing is blocked for item ${itemId}`);
continue;
}
- // Sum up all quantities for this item
- const totalQuantity = itemOrders.reduce(
- (sum, { order }) => sum + order.quantity,
- 0
- );
-
- // Apply minimum order quantity
const minimumOrderQuantity =
supplierPart?.minimumOrderQuantity ?? 0;
-
- let adjustedQuantity = totalQuantity;
-
- // Apply minimum order quantity
+ let adjustedQuantity = order.quantity;
if (
minimumOrderQuantity > 0 &&
adjustedQuantity < minimumOrderQuantity
@@ -385,28 +360,42 @@ export async function action({ request }: ActionFunctionArgs) {
adjustedQuantity = minimumOrderQuantity;
}
- // Use the earliest due date from all orders for this item
- const earliestDueDate = itemOrders.reduce((earliest, { order }) => {
- if (!earliest) return order.dueDate;
- if (!order.dueDate) return earliest;
- return order.dueDate < earliest ? order.dueDate : earliest;
- }, itemOrders[0].order.dueDate);
-
- // Use the first order's description
- const description = itemOrders[0].order.description;
- const unitOfMeasureCode = itemOrders[0].order.unitOfMeasureCode;
-
- const createPurchaseOrderLine = await upsertPurchaseOrderLine(
- client,
- {
- purchaseOrderId: purchaseOrderId!,
- itemId: itemId,
- description: description,
+ // Check if this PO already has a line for the same item
+ const { data: existingLines } = await client
+ .from("purchaseOrderLine")
+ .select("id, purchaseQuantity")
+ .eq("purchaseOrderId", purchaseOrderId)
+ .eq("itemId", itemId)
+ .limit(1);
+
+ if (existingLines?.[0]) {
+ const existing = existingLines[0];
+ const updateLine = await client
+ .from("purchaseOrderLine")
+ .update({
+ purchaseQuantity:
+ (existing.purchaseQuantity ?? 0) + adjustedQuantity,
+ updatedBy: userId
+ })
+ .eq("id", existing.id);
+
+ if (updateLine.error) {
+ errors.push(
+ `Failed to update PO line for item ${itemId}: ${updateLine.error.message}`
+ );
+ continue;
+ }
+ } else {
+ const createLine = await upsertPurchaseOrderLine(client, {
+ purchaseOrderId,
+ itemId,
+ description: order.description,
purchaseOrderLineType: "Part",
purchaseQuantity: adjustedQuantity,
purchaseUnitOfMeasureCode:
- supplierPart?.supplierUnitOfMeasureCode ?? unitOfMeasureCode,
- inventoryUnitOfMeasureCode: unitOfMeasureCode,
+ supplierPart?.supplierUnitOfMeasureCode ??
+ order.unitOfMeasureCode,
+ inventoryUnitOfMeasureCode: order.unitOfMeasureCode,
conversionFactor: supplierPart?.conversionFactor ?? 1,
supplierUnitPrice: supplierPart?.unitPrice ?? 0,
supplierTaxAmount:
@@ -414,60 +403,33 @@ export async function action({ request }: ActionFunctionArgs) {
(supplier.taxPercent ?? 0)) /
100,
supplierShippingCost: 0,
- requiredDate: earliestDueDate ?? undefined,
+ requiredDate: order.dueDate ?? undefined,
locationId,
companyId,
createdBy: userId
- }
- );
+ });
- if (createPurchaseOrderLine.error) {
- const errorMsg = `Failed to create purchase order line for item ${itemId}: ${createPurchaseOrderLine.error.message}`;
- console.error(errorMsg);
- errors.push(errorMsg);
- continue;
+ if (createLine.error) {
+ errors.push(
+ `Failed to create PO line for item ${itemId}: ${createLine.error.message}`
+ );
+ continue;
+ }
}
processedItems++;
- // Add supply forecasts for each period this item appears in
const conversionFactor = supplierPart?.conversionFactor ?? 1;
- const periodQuantities = new Map<string, number>();
-
- for (const { order, periodId } of itemOrders) {
- const currentPeriodQty = periodQuantities.get(periodId) || 0;
- periodQuantities.set(periodId, currentPeriodQty + order.quantity);
- }
-
- for (const [periodId, quantity] of periodQuantities) {
- const inventoryQuantityDelta = quantity * conversionFactor;
-
- allSupplyForecasts.push({
- itemId: itemId,
- locationId,
- sourceType: "Purchase Order" as const,
- forecastQuantity: inventoryQuantityDelta,
- periodId,
- companyId,
- createdBy: userId,
- updatedBy: userId
- });
- }
- }
-
- // Update PO status if we added to an existing PO
- if (!createdNewPO && purchaseOrderId) {
- const updateResult = await updatePurchaseOrder(client, {
- id: purchaseOrderId,
- status: "Planned" as const,
+ allSupplyForecasts.push({
+ itemId,
+ locationId,
+ sourceType: "Purchase Order" as const,
+ forecastQuantity: order.quantity * conversionFactor,
+ periodId,
+ companyId,
+ createdBy: userId,
updatedBy: userId
});
-
- if (updateResult.error) {
- const errorMsg = `Failed to update purchase order status for supplier ${supplierId}: ${updateResult.error.message}`;
- console.error(errorMsg);
- errors.push(errorMsg);
- }
}
}
diff --git a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.new.tsx b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.new.tsx
index b4a15f6c8f..bead3d560b 100644
--- a/apps/erp/app/routes/x+/tool+/$itemId.purchasing.new.tsx
+++ b/apps/erp/app/routes/x+/tool+/$itemId.purchasing.new.tsx
@@ -1,10 +1,9 @@
-import { assertIsPost, success } from "@carbon/auth";
+import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
import { validator } from "@carbon/form";
import { useRouteData } from "@carbon/react";
import type { ActionFunctionArgs } from "react-router";
-import { redirect, useNavigate, useParams } from "react-router";
+import { useNavigate, useParams } from "react-router";
import type { ToolSummary } from "~/modules/items";
import { supplierPartValidator, upsertSupplierPart } from "~/modules/items";
import { SupplierPartForm } from "~/modules/items/ui/Item";
@@ -71,10 +70,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
}
- throw redirect(
- path.to.toolPurchasing(itemId),
- await flash(request, success("Tool supplier created"))
- );
+ return { success: true, message: "Tool supplier created" };
}
export default function NewToolSupplierRoute() {
diff --git a/apps/erp/app/routes/x+/tool+/$itemId.tsx b/apps/erp/app/routes/x+/tool+/$itemId.tsx
index 44ace58d12..ac99ef57d5 100644
--- a/apps/erp/app/routes/x+/tool+/$itemId.tsx
+++ b/apps/erp/app/routes/x+/tool+/$itemId.tsx
@@ -230,7 +230,8 @@ export default function ToolRoute() {
quoteMaterials,
salesOrderLines,
shipmentLines,
- supplierQuotes
+ supplierQuotes,
+ jobMaterialUsage
} = resolvedUsedIn;
const tree: UsedInNode[] = [
@@ -336,6 +337,7 @@ export default function ToolRoute() {
toolData.toolSummary
?.readableIdWithRevision ?? ""
}
+ jobMaterialUsage={jobMaterialUsage}
filterText={filterText}
hideSearch
/>
@@ -376,7 +378,8 @@ export default function ToolRoute() {
quoteMaterials,
salesOrderLines,
shipmentLines,
- supplierQuotes
+ supplierQuotes,
+ jobMaterialUsage
} = resolvedUsedIn;
const tree: UsedInNode[] = [
@@ -482,6 +485,7 @@ export default function ToolRoute() {
toolData.toolSummary
?.readableIdWithRevision ?? ""
}
+ jobMaterialUsage={jobMaterialUsage}
filterText={filterText}
hideSearch
/>
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index b5b4b3fd2e..03961351eb 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -7521,6 +7521,227 @@ export type Database = {
},
]
}
+ demandForecastSource: {
+ Row: {
+ companyId: string
+ createdAt: string
+ demandProjectionId: string | null
+ id: string
+ itemId: string
+ jobId: string | null
+ locationId: string | null
+ parentItemId: string
+ periodId: string
+ quantity: number
+ salesOrderLineId: string | null
+ sourceType: Database["public"]["Enums"]["demandForecastSourceType"]
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ demandProjectionId?: string | null
+ id?: string
+ itemId: string
+ jobId?: string | null
+ locationId?: string | null
+ parentItemId: string
+ periodId: string
+ quantity: number
+ salesOrderLineId?: string | null
+ sourceType: Database["public"]["Enums"]["demandForecastSourceType"]
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ demandProjectionId?: string | null
+ id?: string
+ itemId?: string
+ jobId?: string | null
+ locationId?: string | null
+ parentItemId?: string
+ periodId?: string
+ quantity?: number
+ salesOrderLineId?: string | null
+ sourceType?: Database["public"]["Enums"]["demandForecastSourceType"]
+ }
+ Relationships: [
+ {
+ foreignKeyName: "demandForecastSource_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_demandProjectionId_fkey"
+ columns: ["demandProjectionId"]
+ isOneToOne: false
+ referencedRelation: "demandProjection"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "job"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "openProductionOrders"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_locationId_fkey"
+ columns: ["locationId"]
+ isOneToOne: false
+ referencedRelation: "location"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_parentItemId_fkey"
+ columns: ["parentItemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_parentItemId_fkey"
+ columns: ["parentItemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_parentItemId_fkey"
+ columns: ["parentItemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_parentItemId_fkey"
+ columns: ["parentItemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_parentItemId_fkey"
+ columns: ["parentItemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_parentItemId_fkey"
+ columns: ["parentItemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_periodId_fkey"
+ columns: ["periodId"]
+ isOneToOne: false
+ referencedRelation: "period"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_salesOrderLineId_fkey"
+ columns: ["salesOrderLineId"]
+ isOneToOne: false
+ referencedRelation: "openSalesOrderLines"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_salesOrderLineId_fkey"
+ columns: ["salesOrderLineId"]
+ isOneToOne: false
+ referencedRelation: "salesOrderLine"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_salesOrderLineId_fkey"
+ columns: ["salesOrderLineId"]
+ isOneToOne: false
+ referencedRelation: "salesOrderLines"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
demandProjection: {
Row: {
companyId: string
@@ -7529,6 +7750,7 @@ export type Database = {
createdBy: string
forecastMethod: string | null
forecastQuantity: number
+ id: string
itemId: string
locationId: string
notes: string | null
@@ -7543,6 +7765,7 @@ export type Database = {
createdBy: string
forecastMethod?: string | null
forecastQuantity?: number
+ id?: string
itemId: string
locationId: string
notes?: string | null
@@ -7557,6 +7780,7 @@ export type Database = {
createdBy?: string
forecastMethod?: string | null
forecastQuantity?: number
+ id?: string
itemId?: string
locationId?: string
notes?: string | null
@@ -38290,7 +38514,49 @@ export type Database = {
},
]
}
- searchIndex_LPwQiGPcoBnievXwSmP5Nz: {
+ searchIndex_PAoZnxZFhuiaaU6EsvyrVS: {
+ Row: {
+ createdAt: string
+ description: string | null
+ entityId: string
+ entityType: string
+ id: number
+ link: string
+ metadata: Json | null
+ searchVector: unknown
+ tags: string[] | null
+ title: string
+ updatedAt: string | null
+ }
+ Insert: {
+ createdAt?: string
+ description?: string | null
+ entityId: string
+ entityType: string
+ id?: number
+ link: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title: string
+ updatedAt?: string | null
+ }
+ Update: {
+ createdAt?: string
+ description?: string | null
+ entityId?: string
+ entityType?: string
+ id?: number
+ link?: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title?: string
+ updatedAt?: string | null
+ }
+ Relationships: []
+ }
+ searchIndex_WbvVgr1aYFZjGDegRYLAqe: {
Row: {
createdAt: string
description: string | null
@@ -55414,14 +55680,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -58847,7 +59113,7 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -58861,7 +59127,7 @@ export type Database = {
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -64933,6 +65199,10 @@ export type Database = {
| "Total"
customRuleTargetType: "item" | "storageUnit" | "workCenter"
deadlineType: "No Deadline" | "ASAP" | "Soft Deadline" | "Hard Deadline"
+ demandForecastSourceType:
+ | "Job Material"
+ | "Sales Order"
+ | "Demand Projection"
demandSourceType: "Sales Order" | "Job Material"
depreciationMethod:
| "Straight Line"
@@ -66201,6 +66471,11 @@ export const Constants = {
],
customRuleTargetType: ["item", "storageUnit", "workCenter"],
deadlineType: ["No Deadline", "ASAP", "Soft Deadline", "Hard Deadline"],
+ demandForecastSourceType: [
+ "Job Material",
+ "Sales Order",
+ "Demand Projection",
+ ],
demandSourceType: ["Sales Order", "Job Material"],
depreciationMethod: [
"Straight Line",
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index b5b4b3fd2e..03961351eb 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -7521,6 +7521,227 @@ export type Database = {
},
]
}
+ demandForecastSource: {
+ Row: {
+ companyId: string
+ createdAt: string
+ demandProjectionId: string | null
+ id: string
+ itemId: string
+ jobId: string | null
+ locationId: string | null
+ parentItemId: string
+ periodId: string
+ quantity: number
+ salesOrderLineId: string | null
+ sourceType: Database["public"]["Enums"]["demandForecastSourceType"]
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ demandProjectionId?: string | null
+ id?: string
+ itemId: string
+ jobId?: string | null
+ locationId?: string | null
+ parentItemId: string
+ periodId: string
+ quantity: number
+ salesOrderLineId?: string | null
+ sourceType: Database["public"]["Enums"]["demandForecastSourceType"]
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ demandProjectionId?: string | null
+ id?: string
+ itemId?: string
+ jobId?: string | null
+ locationId?: string | null
+ parentItemId?: string
+ periodId?: string
+ quantity?: number
+ salesOrderLineId?: string | null
+ sourceType?: Database["public"]["Enums"]["demandForecastSourceType"]
+ }
+ Relationships: [
+ {
+ foreignKeyName: "demandForecastSource_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_demandProjectionId_fkey"
+ columns: ["demandProjectionId"]
+ isOneToOne: false
+ referencedRelation: "demandProjection"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "job"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "openProductionOrders"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_locationId_fkey"
+ columns: ["locationId"]
+ isOneToOne: false
+ referencedRelation: "location"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_parentItemId_fkey"
+ columns: ["parentItemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_parentItemId_fkey"
+ columns: ["parentItemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_parentItemId_fkey"
+ columns: ["parentItemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_parentItemId_fkey"
+ columns: ["parentItemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_parentItemId_fkey"
+ columns: ["parentItemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_parentItemId_fkey"
+ columns: ["parentItemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_periodId_fkey"
+ columns: ["periodId"]
+ isOneToOne: false
+ referencedRelation: "period"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_salesOrderLineId_fkey"
+ columns: ["salesOrderLineId"]
+ isOneToOne: false
+ referencedRelation: "openSalesOrderLines"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_salesOrderLineId_fkey"
+ columns: ["salesOrderLineId"]
+ isOneToOne: false
+ referencedRelation: "salesOrderLine"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandForecastSource_salesOrderLineId_fkey"
+ columns: ["salesOrderLineId"]
+ isOneToOne: false
+ referencedRelation: "salesOrderLines"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
demandProjection: {
Row: {
companyId: string
@@ -7529,6 +7750,7 @@ export type Database = {
createdBy: string
forecastMethod: string | null
forecastQuantity: number
+ id: string
itemId: string
locationId: string
notes: string | null
@@ -7543,6 +7765,7 @@ export type Database = {
createdBy: string
forecastMethod?: string | null
forecastQuantity?: number
+ id?: string
itemId: string
locationId: string
notes?: string | null
@@ -7557,6 +7780,7 @@ export type Database = {
createdBy?: string
forecastMethod?: string | null
forecastQuantity?: number
+ id?: string
itemId?: string
locationId?: string
notes?: string | null
@@ -38290,7 +38514,49 @@ export type Database = {
},
]
}
- searchIndex_LPwQiGPcoBnievXwSmP5Nz: {
+ searchIndex_PAoZnxZFhuiaaU6EsvyrVS: {
+ Row: {
+ createdAt: string
+ description: string | null
+ entityId: string
+ entityType: string
+ id: number
+ link: string
+ metadata: Json | null
+ searchVector: unknown
+ tags: string[] | null
+ title: string
+ updatedAt: string | null
+ }
+ Insert: {
+ createdAt?: string
+ description?: string | null
+ entityId: string
+ entityType: string
+ id?: number
+ link: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title: string
+ updatedAt?: string | null
+ }
+ Update: {
+ createdAt?: string
+ description?: string | null
+ entityId?: string
+ entityType?: string
+ id?: number
+ link?: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title?: string
+ updatedAt?: string | null
+ }
+ Relationships: []
+ }
+ searchIndex_WbvVgr1aYFZjGDegRYLAqe: {
Row: {
createdAt: string
description: string | null
@@ -55414,14 +55680,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -58847,7 +59113,7 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -58861,7 +59127,7 @@ export type Database = {
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -64933,6 +65199,10 @@ export type Database = {
| "Total"
customRuleTargetType: "item" | "storageUnit" | "workCenter"
deadlineType: "No Deadline" | "ASAP" | "Soft Deadline" | "Hard Deadline"
+ demandForecastSourceType:
+ | "Job Material"
+ | "Sales Order"
+ | "Demand Projection"
demandSourceType: "Sales Order" | "Job Material"
depreciationMethod:
| "Straight Line"
@@ -66201,6 +66471,11 @@ export const Constants = {
],
customRuleTargetType: ["item", "storageUnit", "workCenter"],
deadlineType: ["No Deadline", "ASAP", "Soft Deadline", "Hard Deadline"],
+ demandForecastSourceType: [
+ "Job Material",
+ "Sales Order",
+ "Demand Projection",
+ ],
demandSourceType: ["Sales Order", "Job Material"],
depreciationMethod: [
"Straight Line",
diff --git a/packages/database/supabase/functions/mrp/index.ts b/packages/database/supabase/functions/mrp/index.ts
index f37950a53c..d0fc85f864 100644
--- a/packages/database/supabase/functions/mrp/index.ts
+++ b/packages/database/supabase/functions/mrp/index.ts
@@ -256,7 +256,7 @@ serve(async (req: Request) => {
// PHASE 2: Compute Low Level Codes
// ──────────────────────────────────────────────────────────────
- const llc = computeLowLevelCodes(bomByItem, replenishmentSystemByItem);
+ const llc = computeLowLevelCodes(bomByItem);
const maxLevel = llc.size > 0 ? Math.max(...llc.values()) : 0;
// ──────────────────────────────────────────────────────────────
@@ -317,6 +317,23 @@ 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.
+ const topLevelContributors = new Map<string, DemandContributor[]>();
+
+ type DemandForecastSourceInsert =
+ Database["public"]["Tables"]["demandForecastSource"]["Insert"];
+
// Demand projections (netted against production supply)
for (const projection of demandProjections.data) {
if (!projection.itemId || !projection.forecastQuantity) continue;
@@ -329,6 +346,20 @@ serve(async (req: Request) => {
if (netDemand > 0) {
const key = `${projection.locationId ?? ""}-${projection.periodId}-${projection.itemId}`;
grossDemand.set(key, (grossDemand.get(key) ?? 0) + netDemand);
+
+ // Seed top-level contributor for this projection. Use the projection's
+ // surrogate id (added in 20260527115843_demand-projection-source.sql).
+ const projectionId = projection.id;
+ if (projectionId && projection.itemId) {
+ const contributors = topLevelContributors.get(key) ?? [];
+ contributors.push({
+ sourceType: "Demand Projection",
+ demandProjectionId: projectionId,
+ parentItemId: projection.itemId,
+ quantity: netDemand,
+ });
+ topLevelContributors.set(key, contributors);
+ }
}
}
@@ -350,6 +381,17 @@ serve(async (req: Request) => {
actualKey,
(salesDemandByKey.get(actualKey) ?? 0) + line.quantityToSend
);
+
+ if (line.id && line.itemId) {
+ const contributors = topLevelContributors.get(key) ?? [];
+ contributors.push({
+ sourceType: "Sales Order",
+ salesOrderLineId: line.id,
+ parentItemId: line.itemId,
+ quantity: line.quantityToSend,
+ });
+ topLevelContributors.set(key, contributors);
+ }
}
// Job material lines
@@ -369,6 +411,17 @@ serve(async (req: Request) => {
actualKey,
(jobMaterialDemandByKey.get(actualKey) ?? 0) + line.quantityToIssue
);
+
+ if (line.jobId && line.itemId) {
+ const contributors = topLevelContributors.get(key) ?? [];
+ contributors.push({
+ sourceType: "Job Material",
+ jobId: line.jobId,
+ parentItemId: line.itemId,
+ quantity: line.quantityToIssue,
+ });
+ topLevelContributors.set(key, contributors);
+ }
}
// ──────────────────────────────────────────────────────────────
@@ -412,10 +465,14 @@ serve(async (req: Request) => {
const effectiveRepSys =
repSys === "Buy and Make" ? "Buy" : (repSys as "Buy" | "Make" | undefined);
- // ── Inventory Netting ──
+ // ── Inventory + Supply Netting ──
const invKey = `${locationId}-${itemId}`;
const onHand = onHandByLocationItem.get(invKey) ?? 0;
- const netRequirement = Math.max(0, grossQty - Math.max(0, onHand));
+ const productionSupply = jobSupplyByLocationPeriodItem.get(key) ?? 0;
+ const netRequirement = Math.max(
+ 0,
+ grossQty - Math.max(0, onHand) - productionSupply
+ );
// Consume on-hand inventory
if (onHand > 0) {
@@ -433,13 +490,11 @@ serve(async (req: Request) => {
? "Buy"
: (childRepSys as "Buy" | "Make" | undefined);
- // Skip Make+Make (produced in-line, not independently planned)
- if (
+ // 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"
- ) {
- continue;
- }
+ childEffRepSys === "Make";
const childQty = child.quantity * netRequirement;
const childLeadTimeDays = leadTimeByItem.get(child.itemId) ?? 7;
@@ -447,7 +502,7 @@ serve(async (req: Request) => {
// Offset to earlier period based on child's lead time
const currentPeriodIndex = periods.findIndex(
- (p: DemandPeriod) => p.id ?? "" === periodId
+ (p: DemandPeriod) => (p.id ?? "") === periodId
);
const targetPeriodIndex = Math.max(
0,
@@ -461,10 +516,32 @@ serve(async (req: Request) => {
childKey,
(grossDemand.get(childKey) ?? 0) + childQty
);
- bomDerivedDemand.set(
- childKey,
- (bomDerivedDemand.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);
+ }
}
}
}
@@ -474,6 +551,7 @@ serve(async (req: Request) => {
// 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.
+ const demandForecastSourceInserts: DemandForecastSourceInsert[] = [];
for (const [key, qty] of bomDerivedDemand) {
if (qty <= 0) continue;
const [locationId, periodId, itemId] = splitKey(key);
@@ -494,6 +572,52 @@ serve(async (req: Request) => {
updatedBy: userId,
});
}
+
+ const contributors = demandContributors.get(key) ?? [];
+ for (const c of contributors) {
+ if (c.quantity <= 0) continue;
+ if (c.sourceType === "Job Material") {
+ demandForecastSourceInserts.push({
+ itemId,
+ locationId,
+ periodId,
+ sourceType: "Job Material",
+ jobId: c.jobId,
+ salesOrderLineId: null,
+ demandProjectionId: null,
+ parentItemId: c.parentItemId,
+ quantity: c.quantity,
+ companyId,
+ });
+ } else if (c.sourceType === "Sales Order") {
+ demandForecastSourceInserts.push({
+ itemId,
+ locationId,
+ periodId,
+ sourceType: "Sales Order",
+ jobId: null,
+ salesOrderLineId: c.salesOrderLineId,
+ demandProjectionId: null,
+ parentItemId: c.parentItemId,
+ quantity: c.quantity,
+ companyId,
+ });
+ } else {
+ // sourceType === "Demand Projection"
+ demandForecastSourceInserts.push({
+ itemId,
+ locationId,
+ periodId,
+ sourceType: "Demand Projection",
+ jobId: null,
+ salesOrderLineId: null,
+ demandProjectionId: c.demandProjectionId,
+ parentItemId: c.parentItemId,
+ quantity: c.quantity,
+ companyId,
+ });
+ }
+ }
}
// ──────────────────────────────────────────────────────────────
@@ -654,6 +778,14 @@ serve(async (req: Request) => {
.where("forecastMethod", "=", "mrp")
.execute();
+ // Delete existing MRP forecast source rows. The demandForecast delete
+ // above removes the parent rows; this removes their attribution rows.
+ // demandForecastSource only ever holds MRP-derived rows.
+ await db
+ .deleteFrom("demandForecastSource")
+ .where("companyId", "=", companyId)
+ .execute();
+
await db
.deleteFrom("supplyForecast")
.where(
@@ -681,6 +813,16 @@ serve(async (req: Request) => {
.execute();
}
+ // Insert demand forecast source rows in batches. No onConflict — the
+ // upstream delete guarantees no key collisions.
+ for (let i = 0; i < demandForecastSourceInserts.length; i += BATCH_SIZE) {
+ const batch = demandForecastSourceInserts.slice(i, i + BATCH_SIZE);
+ await db
+ .insertInto("demandForecastSource")
+ .values(batch)
+ .execute();
+ }
+
// Insert demand actuals in batches
for (let i = 0; i < demandActualUpserts.length; i += BATCH_SIZE) {
const batch = demandActualUpserts.slice(i, i + BATCH_SIZE);
@@ -761,8 +903,7 @@ function findPeriod(
}
function computeLowLevelCodes(
- bomByItem: Map<string, BomChild[]>,
- replenishmentSystemByItem: Map<string, ReplenishmentSystem>
+ bomByItem: Map<string, BomChild[]>
): Map<string, number> {
const llc = new Map<string, number>();
@@ -781,15 +922,6 @@ function computeLowLevelCodes(
const children = bomByItem.get(itemId) ?? [];
for (const child of children) {
- const childRepSys = replenishmentSystemByItem.get(child.itemId);
- const childEffRepSys =
- childRepSys === "Buy and Make" ? "Buy" : childRepSys;
-
- // Skip Make+Make (produced in-line)
- if (child.methodType === "Make to Order" && childEffRepSys === "Make") {
- continue;
- }
-
assignLevel(child.itemId, level + 1, new Set(visited));
}
}
diff --git a/packages/database/supabase/migrations/20260527110002_demand-forecast-source.sql b/packages/database/supabase/migrations/20260527110002_demand-forecast-source.sql
new file mode 100644
index 0000000000..9f764d6d57
--- /dev/null
+++ b/packages/database/supabase/migrations/20260527110002_demand-forecast-source.sql
@@ -0,0 +1,128 @@
+-- demandForecastSource: associates BOM-derived demandForecast rows with the
+-- parent demand sources (jobs / sales orders / production projections) that
+-- produced them via MRP. Populated by the MRP edge function whenever it
+-- writes demandForecast rows with forecastMethod = 'mrp'. Manual /
+-- statistical / ml forecasts have no traceable parent sources and do not
+-- write rows here.
+--
+-- This migration also adds a surrogate `id` column to demandProjection so
+-- demandForecastSource can FK to a specific projection (the existing
+-- composite PK doesn't qualify as an FK target on its own).
+
+-- ── 1. Surrogate id on demandProjection (needed for the FK below) ───
+ALTER TABLE "demandProjection"
+ ADD COLUMN "id" TEXT NOT NULL DEFAULT id();
+
+ALTER TABLE "demandProjection"
+ ADD CONSTRAINT "demandProjection_id_key" UNIQUE ("id");
+
+-- ── 2. demandForecastSourceType enum (all three values from the start
+-- so the CHECK constraint below works in this same transaction; ALTER
+-- TYPE ADD VALUE can't be used in the same transaction that consumes
+-- the value) ─────────────────────────────────────────────────────────
+CREATE TYPE "demandForecastSourceType" AS ENUM (
+ 'Job Material',
+ 'Sales Order',
+ 'Demand Projection'
+);
+
+-- ── 3. demandForecastSource table ───────────────────────────────────
+CREATE TABLE "demandForecastSource" (
+ "id" TEXT NOT NULL DEFAULT id(),
+ "itemId" TEXT NOT NULL,
+ "locationId" TEXT,
+ "periodId" TEXT NOT NULL,
+ "sourceType" "demandForecastSourceType" NOT NULL,
+ "jobId" TEXT,
+ "salesOrderLineId" TEXT,
+ "demandProjectionId" TEXT,
+ "parentItemId" TEXT NOT NULL,
+ "quantity" NUMERIC NOT NULL,
+ "companyId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+
+ -- Surrogate PK because the natural key contains nullable columns
+ -- (locationId, jobId, salesOrderLineId, demandProjectionId) which
+ -- PostgreSQL forbids in a PRIMARY KEY. MRP fully rewrites these rows
+ -- per company on each run (see mrp/index.ts), so no UNIQUE on the
+ -- natural key is needed.
+ CONSTRAINT "demandForecastSource_pkey" PRIMARY KEY ("id"),
+
+ CONSTRAINT "demandForecastSource_itemId_fkey"
+ FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE CASCADE,
+ CONSTRAINT "demandForecastSource_locationId_fkey"
+ FOREIGN KEY ("locationId") REFERENCES "location"("id") ON DELETE CASCADE,
+ CONSTRAINT "demandForecastSource_periodId_fkey"
+ FOREIGN KEY ("periodId") REFERENCES "period"("id") ON DELETE CASCADE,
+ CONSTRAINT "demandForecastSource_jobId_fkey"
+ FOREIGN KEY ("jobId") REFERENCES "job"("id") ON DELETE CASCADE,
+ CONSTRAINT "demandForecastSource_salesOrderLineId_fkey"
+ FOREIGN KEY ("salesOrderLineId") REFERENCES "salesOrderLine"("id") ON DELETE CASCADE,
+ CONSTRAINT "demandForecastSource_demandProjectionId_fkey"
+ FOREIGN KEY ("demandProjectionId") REFERENCES "demandProjection"("id") ON DELETE CASCADE,
+ CONSTRAINT "demandForecastSource_parentItemId_fkey"
+ FOREIGN KEY ("parentItemId") REFERENCES "item"("id") ON DELETE CASCADE,
+ CONSTRAINT "demandForecastSource_companyId_fkey"
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
+
+ -- Exactly one of jobId / salesOrderLineId / demandProjectionId must
+ -- be set, matching the sourceType.
+ CONSTRAINT "demandForecastSource_source_check"
+ CHECK (
+ ("sourceType" = 'Job Material'
+ AND "jobId" IS NOT NULL
+ AND "salesOrderLineId" IS NULL
+ AND "demandProjectionId" IS NULL)
+ OR
+ ("sourceType" = 'Sales Order'
+ AND "salesOrderLineId" IS NOT NULL
+ AND "jobId" IS NULL
+ AND "demandProjectionId" IS NULL)
+ OR
+ ("sourceType" = 'Demand Projection'
+ AND "demandProjectionId" IS NOT NULL
+ AND "jobId" IS NULL
+ AND "salesOrderLineId" IS NULL)
+ )
+);
+
+ALTER TABLE "demandForecastSource" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees with inventory_view can view demandForecastSource"
+ ON "demandForecastSource"
+ FOR SELECT
+ USING (
+ "companyId" = ANY(get_companies_with_permission('inventory_view')::text[])
+ );
+
+CREATE POLICY "Employees with inventory_create can insert demandForecastSource"
+ ON "demandForecastSource"
+ FOR INSERT
+ WITH CHECK (
+ "companyId" = ANY(get_companies_with_employee_permission('inventory_create')::text[])
+ );
+
+CREATE POLICY "Employees with inventory_update can update demandForecastSource"
+ ON "demandForecastSource"
+ FOR UPDATE
+ USING (
+ "companyId" = ANY(get_companies_with_employee_permission('inventory_update')::text[])
+ );
+
+CREATE POLICY "Employees with inventory_delete can delete demandForecastSource"
+ ON "demandForecastSource"
+ FOR DELETE
+ USING (
+ "companyId" = ANY(get_companies_with_employee_permission('inventory_delete')::text[])
+ );
+
+CREATE INDEX "demandForecastSource_itemId_locationId_periodId_idx"
+ ON "demandForecastSource" ("itemId", "locationId", "periodId");
+CREATE INDEX "demandForecastSource_companyId_idx"
+ ON "demandForecastSource" ("companyId");
+CREATE INDEX "demandForecastSource_jobId_idx"
+ ON "demandForecastSource" ("jobId");
+CREATE INDEX "demandForecastSource_salesOrderLineId_idx"
+ ON "demandForecastSource" ("salesOrderLineId");
+CREATE INDEX "demandForecastSource_demandProjectionId_idx"
+ ON "demandForecastSource" ("demandProjectionId");
diff --git a/packages/database/supabase/migrations/20260529074512_open-po-lines-required-date.sql b/packages/database/supabase/migrations/20260529074512_open-po-lines-required-date.sql
new file mode 100644
index 0000000000..98089ef721
--- /dev/null
+++ b/packages/database/supabase/migrations/20260529074512_open-po-lines-required-date.sql
@@ -0,0 +1,28 @@
+CREATE OR REPLACE VIEW "openPurchaseOrderLines" WITH (security_invoker=true) AS (
+ SELECT
+ pol."id",
+ pol."purchaseOrderId",
+ po."purchaseOrderId" as "purchaseOrderReadableId",
+ po."supplierId",
+ pol."itemId",
+ pol."quantityToReceive" * pol."conversionFactor" AS "quantityToReceive",
+ i."unitOfMeasureCode",
+ pol."purchaseOrderLineType",
+ pol."requiredDate" AS "dueDate",
+ pol."companyId",
+ pol."locationId",
+ po."orderDate",
+ po."status",
+ COALESCE(pol."promisedDate", pod."receiptPromisedDate") AS "promisedDate",
+ i."replenishmentSystem",
+ i."itemTrackingType",
+ ir."leadTime" AS "leadTime"
+ FROM "purchaseOrderLine" pol
+ INNER JOIN "purchaseOrder" po ON pol."purchaseOrderId" = po."id"
+ INNER JOIN "purchaseOrderDelivery" pod ON pod."id" = po."id"
+ INNER JOIN "item" i ON pol."itemId" = i."id"
+ INNER JOIN "itemReplenishment" ir ON i."id" = ir."itemId"
+ WHERE
+ pol."purchaseOrderLineType" != 'Service'
+ AND po."status" IN ('To Receive', 'To Receive and Invoice', 'Planned')
+);
diff --git a/packages/dev/src/env.test.ts b/packages/dev/src/env.test.ts
index fad4070a5d..34983f4d2c 100644
--- a/packages/dev/src/env.test.ts
+++ b/packages/dev/src/env.test.ts
@@ -98,9 +98,9 @@ describe("renderEnv (portless enabled)", () => {
branchPrefix: "feat-x"
});
expect(out).toContain("CARBON_WORKTREE=feat-x");
- expect(out).toContain("ERP_URL=https://feat-x.erp.dev");
- expect(out).toContain("MES_URL=https://feat-x.mes.dev");
- expect(out).toContain("SUPABASE_URL=https://feat-x.api.dev");
+ expect(out).toContain("ERP_URL=https://erp.feat-x.dev");
+ expect(out).toContain("MES_URL=https://mes.feat-x.dev");
+ expect(out).toContain("SUPABASE_URL=https://api.feat-x.dev");
expect(out).toContain("PORTLESS_TLD=dev");
});
diff --git a/packages/dev/vitest.config.ts b/packages/dev/vitest.config.ts
new file mode 100644
index 0000000000..9a3c27eaed
--- /dev/null
+++ b/packages/dev/vitest.config.ts
@@ -0,0 +1 @@
+export { default } from "@carbon/config/vitest";
diff --git a/packages/ee/src/paperless-parts/lib/utils.test.ts b/packages/ee/src/paperless-parts/lib/utils.test.ts
index 9f77022fd8..0abfd981af 100644
--- a/packages/ee/src/paperless-parts/lib/utils.test.ts
+++ b/packages/ee/src/paperless-parts/lib/utils.test.ts
@@ -82,7 +82,6 @@ describe("calculatePromisedDate", () => {
const result = calculatePromisedDate(leadTime, holidays);
const resultDate = new Date(result);
- // Expected: September 4, 2024 (Wednesday)
// Start: Aug 29 (Thu) before cutoff
// Add 3 business days: Aug 30 (Fri) +1, Aug 31-Sep 1 (weekend skip),
// Sep 2 (Mon holiday skip), Sep 3 (Tue) +2, Sep 4 (Wed) +3
@@ -115,8 +114,8 @@ describe("calculatePromisedDate", () => {
});
it("should handle multiple holidays correctly", () => {
- // Mock date: August 29, 2024 at 8:00 AM
- const mockDate = new Date("2024-08-29T08:00:00");
+ // Mock date: August 29, 2024 before cutoff
+ const mockDate = new Date("2024-08-29T07:00:00");
vi.useFakeTimers();
vi.setSystemTime(mockDate);
diff --git a/packages/ee/src/paperless-parts/lib/utils.ts b/packages/ee/src/paperless-parts/lib/utils.ts
index acde8e89f1..0c51926616 100644
--- a/packages/ee/src/paperless-parts/lib/utils.ts
+++ b/packages/ee/src/paperless-parts/lib/utils.ts
@@ -17,12 +17,8 @@ export function calculatePromisedDate(
const holidayDates = new Set(
holidays.map((holiday) => {
- const holidayDate = new Date(holiday.date);
- return new CalendarDate(
- holidayDate.getFullYear(),
- holidayDate.getMonth() + 1,
- holidayDate.getDate()
- ).toString();
+ const parts = holiday.date.split("-").map(Number);
+ return new CalendarDate(parts[0]!, parts[1]!, parts[2]!).toString();
})
);
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 9d66da1b29..0e50ad84f1 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -2473,6 +2473,12 @@ msgstr "Nachfrage"
msgid "Demand Forecast"
msgstr "Nachfrageprognose"
+msgid "Demand Forecast — Driven by"
+msgstr "Nachfragevorhersage — Angetrieben durch"
+
+msgid "Demand forecast = BOM-exploded demand from open sales orders, active jobs, and production projections."
+msgstr "Bedarfsprognose = BOM-explodierter Bedarf aus offenen Verkaufsaufträgen, aktiven Aufträgen und Produktionsprognosen."
+
msgid "Demand Projections"
msgstr "Nachfrageprojektionen"
@@ -2632,6 +2638,9 @@ msgstr "Drop-Shipment-Status"
msgid "Drop your file here, or click to browse."
msgstr "Datei hier ablegen oder zum Durchsuchen klicken."
+msgid "Due"
+msgstr "Fällig"
+
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(dueDate) )
msgid "Due {0}"
msgstr "Fällig {0}"
@@ -3679,6 +3688,10 @@ msgstr "Für wachsende Unternehmen, die Unterstützung benötigen"
msgid "For US companies handling ITAR data"
msgstr "Für US-Unternehmen, die ITAR-Daten verarbeiten"
+#. placeholder {0}: forecastMethod ?? "unknown"
+msgid "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."
+msgstr "Prognosemethode: <0>{0}</0>. Diese Zeile wurde nicht aus aktiven Aufträgen abgeleitet, daher sind keine übergeordneten Quellen verfügbar."
+
msgid "Forgot to Clock Out?"
msgstr "Vergessen auszustempeln?"
@@ -3820,6 +3833,9 @@ msgstr "Stunden/Stück"
msgid "How the resolved price was calculated."
msgstr "Wie der aufgelöste Preis berechnet wurde."
+msgid "How this price was calculated"
+msgstr "Wie dieser Preis berechnet wurde"
+
msgid "Humidity"
msgstr "Luftfeuchtigkeit"
@@ -3985,6 +4001,9 @@ msgstr "Intern"
msgid "Internal Notes"
msgstr "Interne Notizen"
+msgid "inv"
+msgstr "Inv"
+
msgid "Invalid Invite"
msgstr "Ungültige Einladung"
@@ -4264,6 +4283,9 @@ msgstr "Zuletzt aktualisiert: {formattedDate}"
msgid "Lead Time"
msgstr "Lieferzeit"
+msgid "Lead time (days)"
+msgstr "Lieferzeit (Tage)"
+
msgid "Lead Time (Days)"
msgstr "Lieferzeit (Tage)"
@@ -4344,6 +4366,9 @@ msgstr "Linear-Problem verknüpfen"
msgid "Linked entity quantity ({0}) does not match row quantity ({1})."
msgstr "Verknüpfte Entitätsmenge ({0}) stimmt nicht mit der Zeilenmenge ({1}) überein."
+msgid "Linked PO"
+msgstr "Verknüpfte Bestellung"
+
msgid "List Options"
msgstr "Listenoptionen"
@@ -4411,6 +4436,9 @@ msgstr "Verloren"
msgid "Lot"
msgstr "Charge"
+msgid "Lot size"
+msgstr "Losgröße"
+
msgid "Lot Size"
msgstr "Losgröße"
@@ -4814,6 +4842,9 @@ msgstr "Navigieren"
msgid "NCRs by Type"
msgstr "NCRs nach Typ"
+msgid "Need by"
+msgstr "Benötigt bis"
+
msgid "Negative Adjustment"
msgstr "Negative Anpassung"
@@ -5224,6 +5255,9 @@ msgstr "Keine ausstehenden Schulungen"
msgid "No overtime scheduled"
msgstr "Keine Überstunden geplant"
+msgid "No parent sources recorded yet. Click Recalculate on the planning page to refresh attribution."
+msgstr "Noch keine übergeordneten Quellen aufgezeichnet. Klicken Sie auf der Planungsseite auf Neu berechnen, um die Zuordnung zu aktualisieren."
+
msgid "No part ID"
msgstr "Keine Teile-ID"
@@ -5473,6 +5507,9 @@ msgstr "Optionen"
msgid "Order"
msgstr "Bestellung"
+msgid "Order by"
+msgstr "Bestellung bis"
+
msgid "Order Date"
msgstr "Bestelldatum"
@@ -5578,6 +5615,9 @@ msgstr "Übergeordnete Abteilung"
msgid "Parent Group"
msgstr "Übergeordnete Gruppe"
+msgid "Parent Item"
+msgstr "Übergeordneter Artikel"
+
msgid "Parent Storage Unit"
msgstr "Übergeordnete Lagereinheit"
@@ -5719,6 +5759,12 @@ msgstr "Geplantes Ende"
msgid "Planned End Time"
msgstr "Geplante Endzeit"
+msgid "Planned Order"
+msgstr "Geplante Bestellung"
+
+msgid "Planned order = MRP suggestion to cover projected demand based on the item's reorder policy (or manually added)."
+msgstr "Geplante Bestellung = MRP-Vorschlag zur Deckung der prognostizierten Nachfrage basierend auf der Nachbestellungsrichtlinie des Artikels (oder manuell hinzugefügt)."
+
msgid "Planned Start"
msgstr "Geplanter Start"
@@ -5764,6 +5810,9 @@ msgstr "Bestellnummer"
msgid "PO PDF"
msgstr "PO PDF"
+msgid "Policy"
+msgstr "Richtlinie"
+
msgid "Policy & Procedure"
msgstr "Richtlinie & Verfahren"
@@ -5932,6 +5981,12 @@ msgstr "Fortschritt"
msgid "Project"
msgstr "Projekt"
+msgid "Projected stock"
+msgstr "Geplanter Bestand"
+
+msgid "Projection"
+msgstr "Projektion"
+
msgid "Projections"
msgstr "Prognosen"
@@ -6038,6 +6093,9 @@ msgstr "QR-Code zum Erstellen eines {0} für diesen Kanban"
msgid "QR Code to start the next operation for this kanban"
msgstr "QR-Code zum Starten des nächsten Vorgangs für diesen Kanban"
+msgid "Qty"
+msgstr "Menge"
+
msgid "Qty to Order"
msgstr "Bestellmenge"
@@ -6101,6 +6159,10 @@ msgstr "Menge pro Übergeordnete"
msgid "Quantity Type"
msgstr "Mengentyp"
+#. placeholder {0}: numberFormatter.format(forecastQuantity)
+msgid "Quantity: {0}"
+msgstr "Menge: {0}"
+
msgid "Question"
msgstr "Frage"
@@ -6568,6 +6630,9 @@ msgstr "Test ausführen"
msgid "Running Total"
msgstr "Laufender Gesamtbetrag"
+msgid "Safety stock"
+msgstr "Sicherheitsbestand"
+
msgid "Safety Stock"
msgstr "Sicherheitsbestand"
@@ -7653,6 +7718,9 @@ msgstr "Die Rechnungsadresse, die auf Angeboten, Aufträgen, Rechnungen und ande
msgid "The date the customer expects to receive the goods"
msgstr "Das Datum, an dem der Kunde die Waren erhalten soll"
+msgid "The date the item is required on-site to cover the period's projected demand."
+msgstr "Das Datum, an dem der Artikel vor Ort erforderlich ist, um die prognostizierte Nachfrage des Zeitraums zu decken."
+
msgid "The endpoint that receives a POST request with the updated data when the table is updated"
msgstr "Der Endpunkt, der eine POST-Anfrage mit den aktualisierten Daten empfängt, wenn die Tabelle aktualisiert wird"
@@ -7662,6 +7730,9 @@ msgstr "Die folgenden Baugruppen haben keine Operationen. Bitte weisen Sie jeder
msgid "The following line items are missing prices or lead times:"
msgstr "Die folgenden Positionen haben keine Preise oder Lieferzeiten:"
+msgid "The latest date to place this PO so it arrives by the need-by date, given the supplier's lead time."
+msgstr "Das späteste Datum, um diese Bestellung aufzugeben, damit sie bis zum erforderlichen Datum ankommt, unter Berücksichtigung der Lieferzeit des Lieferanten."
+
msgid "The lot will still be rejected, but an NCR cannot be auto-created until at least one Issue Type is configured."
msgstr "Das Los wird weiterhin abgelehnt, aber ein NCR kann nicht automatisch erstellt werden, bis mindestens ein Problemtyp konfiguriert ist."
@@ -8067,6 +8138,9 @@ msgstr "Maßeinheit"
msgid "Unit of Measures"
msgstr "Maßeinheiten"
+msgid "Unit price"
+msgstr "Stückpreis"
+
msgid "Unit Price"
msgstr "Stückpreis"
@@ -8574,6 +8648,9 @@ msgstr "Wer sollte Benachrichtigungen erhalten, wenn ein Bestandsverwaltungsauft
msgid "Why is the expiration being changed?"
msgstr "Warum wird das Ablaufdatum geändert?"
+msgid "Why is this included?"
+msgstr "Warum ist dies enthalten?"
+
msgid "WIP"
msgstr "WIP"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 9a91ff308f..6e554f1079 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -2473,6 +2473,12 @@ msgstr "Demand"
msgid "Demand Forecast"
msgstr "Demand Forecast"
+msgid "Demand Forecast — Driven by"
+msgstr "Demand Forecast — Driven by"
+
+msgid "Demand forecast = BOM-exploded demand from open sales orders, active jobs, and production projections."
+msgstr "Demand forecast = BOM-exploded demand from open sales orders, active jobs, and production projections."
+
msgid "Demand Projections"
msgstr "Demand Projections"
@@ -2632,6 +2638,9 @@ msgstr "Drop Shipment Statuses"
msgid "Drop your file here, or click to browse."
msgstr "Drop your file here, or click to browse."
+msgid "Due"
+msgstr "Due"
+
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(dueDate) )
msgid "Due {0}"
msgstr "Due {0}"
@@ -3679,6 +3688,10 @@ msgstr "For growing businesses that need support"
msgid "For US companies handling ITAR data"
msgstr "For US companies handling ITAR data"
+#. placeholder {0}: forecastMethod ?? "unknown"
+msgid "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."
+msgstr "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."
+
msgid "Forgot to Clock Out?"
msgstr "Forgot to Clock Out?"
@@ -3820,6 +3833,9 @@ msgstr "Hours/Piece"
msgid "How the resolved price was calculated."
msgstr "How the resolved price was calculated."
+msgid "How this price was calculated"
+msgstr "How this price was calculated"
+
msgid "Humidity"
msgstr "Humidity"
@@ -3985,6 +4001,9 @@ msgstr "Internal"
msgid "Internal Notes"
msgstr "Internal Notes"
+msgid "inv"
+msgstr "inv"
+
msgid "Invalid Invite"
msgstr "Invalid Invite"
@@ -4264,6 +4283,9 @@ msgstr "Last updated: {formattedDate}"
msgid "Lead Time"
msgstr "Lead Time"
+msgid "Lead time (days)"
+msgstr "Lead time (days)"
+
msgid "Lead Time (Days)"
msgstr "Lead Time (Days)"
@@ -4344,6 +4366,9 @@ msgstr "Link Linear Issue"
msgid "Linked entity quantity ({0}) does not match row quantity ({1})."
msgstr "Linked entity quantity ({0}) does not match row quantity ({1})."
+msgid "Linked PO"
+msgstr "Linked PO"
+
msgid "List Options"
msgstr "List Options"
@@ -4411,6 +4436,9 @@ msgstr "Lost"
msgid "Lot"
msgstr "Lot"
+msgid "Lot size"
+msgstr "Lot size"
+
msgid "Lot Size"
msgstr "Lot Size"
@@ -4814,6 +4842,9 @@ msgstr "Navigate"
msgid "NCRs by Type"
msgstr "NCRs by Type"
+msgid "Need by"
+msgstr "Need by"
+
msgid "Negative Adjustment"
msgstr "Negative Adjustment"
@@ -5224,6 +5255,9 @@ msgstr "No outstanding trainings"
msgid "No overtime scheduled"
msgstr "No overtime scheduled"
+msgid "No parent sources recorded yet. Click Recalculate on the planning page to refresh attribution."
+msgstr "No parent sources recorded yet. Click Recalculate on the planning page to refresh attribution."
+
msgid "No part ID"
msgstr "No part ID"
@@ -5473,6 +5507,9 @@ msgstr "Options"
msgid "Order"
msgstr "Order"
+msgid "Order by"
+msgstr "Order by"
+
msgid "Order Date"
msgstr "Order Date"
@@ -5578,6 +5615,9 @@ msgstr "Parent Department"
msgid "Parent Group"
msgstr "Parent Group"
+msgid "Parent Item"
+msgstr "Parent Item"
+
msgid "Parent Storage Unit"
msgstr "Parent Storage Unit"
@@ -5719,6 +5759,12 @@ msgstr "Planned End"
msgid "Planned End Time"
msgstr "Planned End Time"
+msgid "Planned Order"
+msgstr "Planned Order"
+
+msgid "Planned order = MRP suggestion to cover projected demand based on the item's reorder policy (or manually added)."
+msgstr "Planned order = MRP suggestion to cover projected demand based on the item's reorder policy (or manually added)."
+
msgid "Planned Start"
msgstr "Planned Start"
@@ -5764,6 +5810,9 @@ msgstr "PO Number"
msgid "PO PDF"
msgstr "PO PDF"
+msgid "Policy"
+msgstr "Policy"
+
msgid "Policy & Procedure"
msgstr "Policy & Procedure"
@@ -5932,6 +5981,12 @@ msgstr "Progress"
msgid "Project"
msgstr "Project"
+msgid "Projected stock"
+msgstr "Projected stock"
+
+msgid "Projection"
+msgstr "Projection"
+
msgid "Projections"
msgstr "Projections"
@@ -6038,6 +6093,9 @@ msgstr "QR Code to create a {0} for this kanban"
msgid "QR Code to start the next operation for this kanban"
msgstr "QR Code to start the next operation for this kanban"
+msgid "Qty"
+msgstr "Qty"
+
msgid "Qty to Order"
msgstr "Qty to Order"
@@ -6101,6 +6159,10 @@ msgstr "Quantity per Parent"
msgid "Quantity Type"
msgstr "Quantity Type"
+#. placeholder {0}: numberFormatter.format(forecastQuantity)
+msgid "Quantity: {0}"
+msgstr "Quantity: {0}"
+
msgid "Question"
msgstr "Question"
@@ -6568,6 +6630,9 @@ msgstr "Run Test"
msgid "Running Total"
msgstr "Running Total"
+msgid "Safety stock"
+msgstr "Safety stock"
+
msgid "Safety Stock"
msgstr "Safety Stock"
@@ -7653,6 +7718,9 @@ msgstr "The billing address used on quotes, sales orders, invoices, and other sa
msgid "The date the customer expects to receive the goods"
msgstr "The date the customer expects to receive the goods"
+msgid "The date the item is required on-site to cover the period's projected demand."
+msgstr "The date the item is required on-site to cover the period's projected demand."
+
msgid "The endpoint that receives a POST request with the updated data when the table is updated"
msgstr "The endpoint that receives a POST request with the updated data when the table is updated"
@@ -7662,6 +7730,9 @@ msgstr "The following assemblies have no operations. Please assign an operation
msgid "The following line items are missing prices or lead times:"
msgstr "The following line items are missing prices or lead times:"
+msgid "The latest date to place this PO so it arrives by the need-by date, given the supplier's lead time."
+msgstr "The latest date to place this PO so it arrives by the need-by date, given the supplier's lead time."
+
msgid "The lot will still be rejected, but an NCR cannot be auto-created until at least one Issue Type is configured."
msgstr "The lot will still be rejected, but an NCR cannot be auto-created until at least one Issue Type is configured."
@@ -8067,6 +8138,9 @@ msgstr "Unit of Measure"
msgid "Unit of Measures"
msgstr "Unit of Measures"
+msgid "Unit price"
+msgstr "Unit price"
+
msgid "Unit Price"
msgstr "Unit Price"
@@ -8574,6 +8648,9 @@ msgstr "Who should receive notifications when an inventory job is completed?"
msgid "Why is the expiration being changed?"
msgstr "Why is the expiration being changed?"
+msgid "Why is this included?"
+msgstr "Why is this included?"
+
msgid "WIP"
msgstr "WIP"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 9e672994df..143a1a843b 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -2473,6 +2473,12 @@ msgstr "Demanda"
msgid "Demand Forecast"
msgstr "Pronóstico de Demanda"
+msgid "Demand Forecast — Driven by"
+msgstr "Pronóstico de Demanda — Impulsado por"
+
+msgid "Demand forecast = BOM-exploded demand from open sales orders, active jobs, and production projections."
+msgstr "Pronóstico de demanda = demanda desglosada por BOM de pedidos de venta abiertos, trabajos activos y proyecciones de producción."
+
msgid "Demand Projections"
msgstr "Proyecciones de Demanda"
@@ -2632,6 +2638,9 @@ msgstr "Estados de Envío Directo"
msgid "Drop your file here, or click to browse."
msgstr "Suelta tu archivo aquí, o haz clic para examinar."
+msgid "Due"
+msgstr "Vencimiento"
+
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(dueDate) )
msgid "Due {0}"
msgstr "Vencimiento {0}"
@@ -3679,6 +3688,10 @@ msgstr "Para empresas en crecimiento que necesitan soporte"
msgid "For US companies handling ITAR data"
msgstr "Para empresas estadounidenses que manejan datos ITAR"
+#. placeholder {0}: forecastMethod ?? "unknown"
+msgid "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."
+msgstr "Método de pronóstico: <0>{0}</0>. Esta fila no se derivó de trabajos activos, por lo que no hay fuentes principales disponibles."
+
msgid "Forgot to Clock Out?"
msgstr "¿Olvidaste marcar la salida?"
@@ -3820,6 +3833,9 @@ msgstr "Horas/Pieza"
msgid "How the resolved price was calculated."
msgstr "Cómo se calculó el precio resuelto."
+msgid "How this price was calculated"
+msgstr "Cómo se calculó este precio"
+
msgid "Humidity"
msgstr "Humedad"
@@ -3985,6 +4001,9 @@ msgstr "Interno"
msgid "Internal Notes"
msgstr "Notas Internas"
+msgid "inv"
+msgstr "inv"
+
msgid "Invalid Invite"
msgstr "Invitación Inválida"
@@ -4264,6 +4283,9 @@ msgstr "Última actualización: {formattedDate}"
msgid "Lead Time"
msgstr "Tiempo de Entrega"
+msgid "Lead time (days)"
+msgstr "Tiempo de entrega (días)"
+
msgid "Lead Time (Days)"
msgstr "Tiempo de Entrega (Días)"
@@ -4344,6 +4366,9 @@ msgstr "Vincular problema de Linear"
msgid "Linked entity quantity ({0}) does not match row quantity ({1})."
msgstr "La cantidad de entidad vinculada ({0}) no coincide con la cantidad de fila ({1})."
+msgid "Linked PO"
+msgstr "PO vinculada"
+
msgid "List Options"
msgstr "Opciones de lista"
@@ -4411,6 +4436,9 @@ msgstr "Perdido"
msgid "Lot"
msgstr "Lote"
+msgid "Lot size"
+msgstr "Tamaño de lote"
+
msgid "Lot Size"
msgstr "Tamaño de Lote"
@@ -4814,6 +4842,9 @@ msgstr "Navegar"
msgid "NCRs by Type"
msgstr "NCR por Tipo"
+msgid "Need by"
+msgstr "Necesario por"
+
msgid "Negative Adjustment"
msgstr "Ajuste Negativo"
@@ -5224,6 +5255,9 @@ msgstr "No hay capacitaciones pendientes"
msgid "No overtime scheduled"
msgstr "Sin horas extra programadas"
+msgid "No parent sources recorded yet. Click Recalculate on the planning page to refresh attribution."
+msgstr "No hay fuentes principales registradas aún. Haz clic en Recalcular en la página de planificación para actualizar la atribución."
+
msgid "No part ID"
msgstr "Sin ID de pieza"
@@ -5473,6 +5507,9 @@ msgstr "Opciones"
msgid "Order"
msgstr "Pedido"
+msgid "Order by"
+msgstr "Ordenar por"
+
msgid "Order Date"
msgstr "Fecha de Pedido"
@@ -5578,6 +5615,9 @@ msgstr "Departamento Principal"
msgid "Parent Group"
msgstr "Grupo Principal"
+msgid "Parent Item"
+msgstr "Artículo Principal"
+
msgid "Parent Storage Unit"
msgstr "Unidad de Almacenamiento Principal"
@@ -5719,6 +5759,12 @@ msgstr "Fin Planificada"
msgid "Planned End Time"
msgstr "Hora de finalización planeada"
+msgid "Planned Order"
+msgstr "Orden Planificada"
+
+msgid "Planned order = MRP suggestion to cover projected demand based on the item's reorder policy (or manually added)."
+msgstr "Orden planificada = sugerencia de MRP para cubrir la demanda proyectada basada en la política de reorden del artículo (o agregada manualmente)."
+
msgid "Planned Start"
msgstr "Inicio Planificado"
@@ -5764,6 +5810,9 @@ msgstr "Número de OC"
msgid "PO PDF"
msgstr "PDF de PO"
+msgid "Policy"
+msgstr "Política"
+
msgid "Policy & Procedure"
msgstr "Política y Procedimiento"
@@ -5932,6 +5981,12 @@ msgstr "Progreso"
msgid "Project"
msgstr "Proyecto"
+msgid "Projected stock"
+msgstr "Stock proyectado"
+
+msgid "Projection"
+msgstr "Proyección"
+
msgid "Projections"
msgstr "Proyecciones"
@@ -6038,6 +6093,9 @@ msgstr "Código QR para crear un {0} para este kanban"
msgid "QR Code to start the next operation for this kanban"
msgstr "Código QR para iniciar la siguiente operación para este kanban"
+msgid "Qty"
+msgstr "Cant."
+
msgid "Qty to Order"
msgstr "Cantidad a Pedir"
@@ -6101,6 +6159,10 @@ msgstr "Cantidad por Padre"
msgid "Quantity Type"
msgstr "Tipo de Cantidad"
+#. placeholder {0}: numberFormatter.format(forecastQuantity)
+msgid "Quantity: {0}"
+msgstr "Cantidad: {0}"
+
msgid "Question"
msgstr "Pregunta"
@@ -6568,6 +6630,9 @@ msgstr "Ejecutar Prueba"
msgid "Running Total"
msgstr "Total Acumulado"
+msgid "Safety stock"
+msgstr "Stock de seguridad"
+
msgid "Safety Stock"
msgstr "Stock de Seguridad"
@@ -7653,6 +7718,9 @@ msgstr "La dirección de facturación utilizada en cotizaciones, órdenes de ven
msgid "The date the customer expects to receive the goods"
msgstr "La fecha en que el cliente espera recibir los bienes"
+msgid "The date the item is required on-site to cover the period's projected demand."
+msgstr "La fecha en que se requiere el artículo en el sitio para cubrir la demanda proyectada del período."
+
msgid "The endpoint that receives a POST request with the updated data when the table is updated"
msgstr "El endpoint que recibe una solicitud POST con los datos actualizados cuando la tabla se actualiza"
@@ -7662,6 +7730,9 @@ msgstr "Los siguientes conjuntos no tienen operaciones. Por favor, asigne una op
msgid "The following line items are missing prices or lead times:"
msgstr "Los siguientes artículos de línea no tienen precios ni tiempos de entrega:"
+msgid "The latest date to place this PO so it arrives by the need-by date, given the supplier's lead time."
+msgstr "La fecha más reciente para realizar este PO de modo que llegue en la fecha requerida, considerando el tiempo de entrega del proveedor."
+
msgid "The lot will still be rejected, but an NCR cannot be auto-created until at least one Issue Type is configured."
msgstr "El lote seguirá siendo rechazado, pero no se puede crear automáticamente un NCR hasta que se configure al menos un tipo de problema."
@@ -8067,6 +8138,9 @@ msgstr "Unidad de Medida"
msgid "Unit of Measures"
msgstr "Unidades de Medida"
+msgid "Unit price"
+msgstr "Precio unitario"
+
msgid "Unit Price"
msgstr "Precio Unitario"
@@ -8574,6 +8648,9 @@ msgstr "¿Quién debe recibir notificaciones cuando se completa un trabajo de in
msgid "Why is the expiration being changed?"
msgstr "¿Por qué se está cambiando la fecha de vencimiento?"
+msgid "Why is this included?"
+msgstr "¿Por qué se incluye esto?"
+
msgid "WIP"
msgstr "WIP"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index b3ccd16ddd..cc9d4e346f 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -2473,6 +2473,12 @@ msgstr "Demande"
msgid "Demand Forecast"
msgstr "Prévision de la demande"
+msgid "Demand Forecast — Driven by"
+msgstr "Prévision de la demande — Pilotée par"
+
+msgid "Demand forecast = BOM-exploded demand from open sales orders, active jobs, and production projections."
+msgstr "Prévision de la demande = demande éclatée par nomenclature provenant des commandes client ouvertes, des travaux actifs et des projections de production."
+
msgid "Demand Projections"
msgstr "Projections de la demande"
@@ -2632,6 +2638,9 @@ msgstr "Statuts de livraison directe"
msgid "Drop your file here, or click to browse."
msgstr "Déposez votre fichier ici, ou cliquez pour parcourir."
+msgid "Due"
+msgstr "Échéance"
+
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(dueDate) )
msgid "Due {0}"
msgstr "Échéance {0}"
@@ -3679,6 +3688,10 @@ msgstr "Pour les entreprises en croissance qui ont besoin de support"
msgid "For US companies handling ITAR data"
msgstr "Pour les entreprises américaines traitant des données ITAR"
+#. placeholder {0}: forecastMethod ?? "unknown"
+msgid "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."
+msgstr "Méthode de prévision : <0>{0}</0>. Cette ligne n'a pas été dérivée de tâches actives, donc aucune source parent n'est disponible."
+
msgid "Forgot to Clock Out?"
msgstr "Oublié de pointer la sortie ?"
@@ -3820,6 +3833,9 @@ msgstr "Heures/Pièce"
msgid "How the resolved price was calculated."
msgstr "Comment le prix résolu a été calculé."
+msgid "How this price was calculated"
+msgstr "Comment ce prix a été calculé"
+
msgid "Humidity"
msgstr "Humidité"
@@ -3985,6 +4001,9 @@ msgstr "Interne"
msgid "Internal Notes"
msgstr "Notes internes"
+msgid "inv"
+msgstr "inv"
+
msgid "Invalid Invite"
msgstr "Invitation invalide"
@@ -4264,6 +4283,9 @@ msgstr "Dernière mise à jour : {formattedDate}"
msgid "Lead Time"
msgstr "Délai de livraison"
+msgid "Lead time (days)"
+msgstr "Délai de livraison (jours)"
+
msgid "Lead Time (Days)"
msgstr "Délai de livraison (jours)"
@@ -4344,6 +4366,9 @@ msgstr "Lier un problème Linear"
msgid "Linked entity quantity ({0}) does not match row quantity ({1})."
msgstr "La quantité d'entité liée ({0}) ne correspond pas à la quantité de ligne ({1})."
+msgid "Linked PO"
+msgstr "Bon de commande lié"
+
msgid "List Options"
msgstr "Options de liste"
@@ -4411,6 +4436,9 @@ msgstr "Perdu"
msgid "Lot"
msgstr "Lot"
+msgid "Lot size"
+msgstr "Taille de lot"
+
msgid "Lot Size"
msgstr "Taille du lot"
@@ -4814,6 +4842,9 @@ msgstr "Naviguer"
msgid "NCRs by Type"
msgstr "NCRs par type"
+msgid "Need by"
+msgstr "Requis le"
+
msgid "Negative Adjustment"
msgstr "Ajustement Négatif"
@@ -5224,6 +5255,9 @@ msgstr "Aucune formation en attente"
msgid "No overtime scheduled"
msgstr "Aucune heure supplémentaire prévue"
+msgid "No parent sources recorded yet. Click Recalculate on the planning page to refresh attribution."
+msgstr "Aucune source parent enregistrée pour le moment. Cliquez sur Recalculer sur la page de planification pour actualiser l'attribution."
+
msgid "No part ID"
msgstr "Aucun ID de pièce"
@@ -5473,6 +5507,9 @@ msgstr "Options"
msgid "Order"
msgstr "Commande"
+msgid "Order by"
+msgstr "Commander par"
+
msgid "Order Date"
msgstr "Date de commande"
@@ -5578,6 +5615,9 @@ msgstr "Département Parent"
msgid "Parent Group"
msgstr "Groupe parent"
+msgid "Parent Item"
+msgstr "Article parent"
+
msgid "Parent Storage Unit"
msgstr "Unité de stockage parent"
@@ -5719,6 +5759,12 @@ msgstr "Fin prévue"
msgid "Planned End Time"
msgstr "Heure de fin prévue"
+msgid "Planned Order"
+msgstr "Commande planifiée"
+
+msgid "Planned order = MRP suggestion to cover projected demand based on the item's reorder policy (or manually added)."
+msgstr "Commande planifiée = suggestion MRP pour couvrir la demande projetée en fonction de la politique de réapprovisionnement de l'article (ou ajoutée manuellement)."
+
msgid "Planned Start"
msgstr "Début Prévu"
@@ -5764,6 +5810,9 @@ msgstr "Numéro de BC"
msgid "PO PDF"
msgstr "PDF BC"
+msgid "Policy"
+msgstr "Politique"
+
msgid "Policy & Procedure"
msgstr "Politique et Procédure"
@@ -5932,6 +5981,12 @@ msgstr "Progression"
msgid "Project"
msgstr "Projet"
+msgid "Projected stock"
+msgstr "Stock projeté"
+
+msgid "Projection"
+msgstr "Projection"
+
msgid "Projections"
msgstr "Projections"
@@ -6038,6 +6093,9 @@ msgstr "Code QR pour créer un {0} pour ce kanban"
msgid "QR Code to start the next operation for this kanban"
msgstr "Code QR pour démarrer l'opération suivante pour ce kanban"
+msgid "Qty"
+msgstr "Qté"
+
msgid "Qty to Order"
msgstr "Qté à commander"
@@ -6101,6 +6159,10 @@ msgstr "Quantité par Parent"
msgid "Quantity Type"
msgstr "Type de quantité"
+#. placeholder {0}: numberFormatter.format(forecastQuantity)
+msgid "Quantity: {0}"
+msgstr "Quantité : {0}"
+
msgid "Question"
msgstr "Question"
@@ -6568,6 +6630,9 @@ msgstr "Exécuter le test"
msgid "Running Total"
msgstr "Total cumulé"
+msgid "Safety stock"
+msgstr "Stock de sécurité"
+
msgid "Safety Stock"
msgstr "Stock de sécurité"
@@ -7653,6 +7718,9 @@ msgstr "L'adresse de facturation utilisée sur les devis, les commandes de vente
msgid "The date the customer expects to receive the goods"
msgstr "La date à laquelle le client s'attend à recevoir les marchandises"
+msgid "The date the item is required on-site to cover the period's projected demand."
+msgstr "La date à laquelle l'article doit être disponible sur site pour couvrir la demande projetée de la période."
+
msgid "The endpoint that receives a POST request with the updated data when the table is updated"
msgstr "Le point de terminaison qui reçoit une requête POST avec les données mises à jour lorsque la table est mise à jour"
@@ -7662,6 +7730,9 @@ msgstr "Les assemblages suivants n'ont pas d'opérations. Veuillez assigner une
msgid "The following line items are missing prices or lead times:"
msgstr "Les articles de ligne suivants n'ont pas de prix ou de délais de livraison :"
+msgid "The latest date to place this PO so it arrives by the need-by date, given the supplier's lead time."
+msgstr "La date limite pour passer cette commande afin qu'elle arrive à la date requise, compte tenu du délai de livraison du fournisseur."
+
msgid "The lot will still be rejected, but an NCR cannot be auto-created until at least one Issue Type is configured."
msgstr "Le lot sera toujours rejeté, mais une NCR ne peut pas être créée automatiquement tant qu'au moins un type de problème n'est pas configuré."
@@ -8067,6 +8138,9 @@ msgstr "Unité de mesure"
msgid "Unit of Measures"
msgstr "Unités de mesure"
+msgid "Unit price"
+msgstr "Prix unitaire"
+
msgid "Unit Price"
msgstr "Prix unitaire"
@@ -8574,6 +8648,9 @@ msgstr "Qui devrait recevoir des notifications lorsqu'une tâche d'inventaire es
msgid "Why is the expiration being changed?"
msgstr "Pourquoi la date d'expiration est-elle modifiée ?"
+msgid "Why is this included?"
+msgstr "Pourquoi est-ce inclus ?"
+
msgid "WIP"
msgstr "TEC"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 6a27f68f6c..a24c75cd76 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -2473,6 +2473,12 @@ msgstr "मांग"
msgid "Demand Forecast"
msgstr "मांग पूर्वानुमान"
+msgid "Demand Forecast — Driven by"
+msgstr "मांग पूर्वानुमान — द्वारा संचालित"
+
+msgid "Demand forecast = BOM-exploded demand from open sales orders, active jobs, and production projections."
+msgstr "मांग पूर्वानुमान = खुले बिक्रय आदेशों, सक्रिय कार्यों और उत्पादन प्रक्षेपणों से BOM-विस्फोटित मांग।"
+
msgid "Demand Projections"
msgstr "मांग प्रक्षेपण"
@@ -2632,6 +2638,9 @@ msgstr "ड्रॉप शिपमेंट स्थितियाँ"
msgid "Drop your file here, or click to browse."
msgstr "अपनी फ़ाइल यहाँ ड्रॉप करें, या ब्राउज़ करने के लिए क्लिक करें।"
+msgid "Due"
+msgstr "देय"
+
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(dueDate) )
msgid "Due {0}"
msgstr "Due {0}"
@@ -3679,6 +3688,10 @@ msgstr "बढ़ते हुए व्यवसायों के लिए
msgid "For US companies handling ITAR data"
msgstr "ITAR डेटा संभालने वाली US कंपनियों के लिए"
+#. placeholder {0}: forecastMethod ?? "unknown"
+msgid "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."
+msgstr "पूर्वानुमान विधि: <0>{0}</0>. यह पंक्ति सक्रिय कार्यों से प्राप्त नहीं की गई थी, इसलिए कोई मूल स्रोत उपलब्ध नहीं हैं।"
+
msgid "Forgot to Clock Out?"
msgstr "क्या आप क्लॉक आउट करना भूल गए?"
@@ -3820,6 +3833,9 @@ msgstr "घंटे/टुकड़ा"
msgid "How the resolved price was calculated."
msgstr "हल की गई कीमत की गणना कैसे की गई।"
+msgid "How this price was calculated"
+msgstr "इस कीमत की गणना कैसे की गई"
+
msgid "Humidity"
msgstr "आर्द्रता"
@@ -3985,6 +4001,9 @@ msgstr "आंतरिक"
msgid "Internal Notes"
msgstr "आंतरिक नोट्स"
+msgid "inv"
+msgstr "इन्व"
+
msgid "Invalid Invite"
msgstr "अमान्य निमंत्रण"
@@ -4264,6 +4283,9 @@ msgstr "अंतिम अपडेट: {formattedDate}"
msgid "Lead Time"
msgstr "लीड टाइम"
+msgid "Lead time (days)"
+msgstr "लीड समय (दिन)"
+
msgid "Lead Time (Days)"
msgstr "लीड टाइम (दिन)"
@@ -4344,6 +4366,9 @@ msgstr "Linear समस्या को लिंक करें"
msgid "Linked entity quantity ({0}) does not match row quantity ({1})."
msgstr "लिंक किया गया इकाई मात्रा ({0}) पंक्ति मात्रा ({1}) से मेल नहीं खाती।"
+msgid "Linked PO"
+msgstr "लिंक्ड PO"
+
msgid "List Options"
msgstr "सूची विकल्प"
@@ -4411,6 +4436,9 @@ msgstr "खो गया"
msgid "Lot"
msgstr "लॉट"
+msgid "Lot size"
+msgstr "लॉट आकार"
+
msgid "Lot Size"
msgstr "लॉट आकार"
@@ -4814,6 +4842,9 @@ msgstr "नेविगेट करें"
msgid "NCRs by Type"
msgstr "प्रकार के अनुसार NCR"
+msgid "Need by"
+msgstr "आवश्यकता की तारीख"
+
msgid "Negative Adjustment"
msgstr "नकारात्मक समायोजन"
@@ -5224,6 +5255,9 @@ msgstr "कोई बकाया प्रशिक्षण नहीं"
msgid "No overtime scheduled"
msgstr "कोई ओवरटाइम शेड्यूल नहीं है"
+msgid "No parent sources recorded yet. Click Recalculate on the planning page to refresh attribution."
+msgstr "अभी तक कोई मूल स्रोत दर्ज नहीं किया गया है। एट्रिब्यूशन को रीफ्रेश करने के लिए योजना पृष्ठ पर पुनः गणना करें पर क्लिक करें।"
+
msgid "No part ID"
msgstr "कोई भाग ID नहीं"
@@ -5473,6 +5507,9 @@ msgstr "विकल्प"
msgid "Order"
msgstr "आदेश"
+msgid "Order by"
+msgstr "आदेश दें"
+
msgid "Order Date"
msgstr "ऑर्डर तारीख"
@@ -5578,6 +5615,9 @@ msgstr "मूल विभाग"
msgid "Parent Group"
msgstr "मूल समूह"
+msgid "Parent Item"
+msgstr "मूल आइटम"
+
msgid "Parent Storage Unit"
msgstr "पैरेंट स्टोरेज यूनिट"
@@ -5719,6 +5759,12 @@ msgstr "नियोजित अंत"
msgid "Planned End Time"
msgstr "नियोजित समाप्ति समय"
+msgid "Planned Order"
+msgstr "नियोजित आदेश"
+
+msgid "Planned order = MRP suggestion to cover projected demand based on the item's reorder policy (or manually added)."
+msgstr "नियोजित आदेश = अनुमानित मांग को कवर करने के लिए MRP सुझाव आइटम की पुनः आदेश नीति के आधार पर (या मैन्युअल रूप से जोड़ा गया)।"
+
msgid "Planned Start"
msgstr "नियोजित प्रारंभ"
@@ -5764,6 +5810,9 @@ msgstr "PO संख्या"
msgid "PO PDF"
msgstr "पीओ पीडीएफ"
+msgid "Policy"
+msgstr "नीति"
+
msgid "Policy & Procedure"
msgstr "नीति और प्रक्रिया"
@@ -5932,6 +5981,12 @@ msgstr "प्रगति"
msgid "Project"
msgstr "प्रोजेक्ट"
+msgid "Projected stock"
+msgstr "अनुमानित स्टॉक"
+
+msgid "Projection"
+msgstr "प्रक्षेपण"
+
msgid "Projections"
msgstr "अनुमान"
@@ -6038,6 +6093,9 @@ msgstr "इस कनबन के लिए {0} बनाने के लि
msgid "QR Code to start the next operation for this kanban"
msgstr "इस कनबन के लिए अगली ऑपरेशन शुरू करने के लिए QR कोड"
+msgid "Qty"
+msgstr "मात्रा"
+
msgid "Qty to Order"
msgstr "ऑर्डर करने की मात्रा"
@@ -6101,6 +6159,10 @@ msgstr "प्रति पैरेंट मात्रा"
msgid "Quantity Type"
msgstr "मात्रा प्रकार"
+#. placeholder {0}: numberFormatter.format(forecastQuantity)
+msgid "Quantity: {0}"
+msgstr "मात्रा: {0}"
+
msgid "Question"
msgstr "प्रश्न"
@@ -6568,6 +6630,9 @@ msgstr "टेस्ट चलाएं"
msgid "Running Total"
msgstr "कुल चल रहा है"
+msgid "Safety stock"
+msgstr "सुरक्षा स्टॉक"
+
msgid "Safety Stock"
msgstr "सुरक्षा स्टॉक"
@@ -7653,6 +7718,9 @@ msgstr "उद्धरण, बिक्री आदेश, चालान औ
msgid "The date the customer expects to receive the goods"
msgstr "वह तारीख जिस दिन ग्राहक को सामान प्राप्त होने की उम्मीद है"
+msgid "The date the item is required on-site to cover the period's projected demand."
+msgstr "वह तारीख जिस दिन आइटम साइट पर आवश्यक है ताकि अवधि की अनुमानित मांग को पूरा किया जा सके।"
+
msgid "The endpoint that receives a POST request with the updated data when the table is updated"
msgstr "वह एंडपॉइंट जो तालिका अपडेट होने पर अपडेट किए गए डेटा के साथ POST अनुरोध प्राप्त करता है"
@@ -7662,6 +7730,9 @@ msgstr "निम्नलिखित असेंबलियों के प
msgid "The following line items are missing prices or lead times:"
msgstr "निम्नलिखित लाइन आइटम कीमतें या लीड समय गायब हैं:"
+msgid "The latest date to place this PO so it arrives by the need-by date, given the supplier's lead time."
+msgstr "इस PO को रखने की नवीनतम तारीख ताकि यह आवश्यकता की तारीख तक पहुंचे, आपूर्तिकर्ता के लीड समय को देखते हुए।"
+
msgid "The lot will still be rejected, but an NCR cannot be auto-created until at least one Issue Type is configured."
msgstr "लॉट अभी भी अस्वीकार कर दिया जाएगा, लेकिन कम से कम एक Issue Type कॉन्फ़िगर होने तक NCR स्वचालित रूप से नहीं बनाया जा सकता।"
@@ -8067,6 +8138,9 @@ msgstr "माप की इकाई"
msgid "Unit of Measures"
msgstr "माप की इकाइयाँ"
+msgid "Unit price"
+msgstr "इकाई मूल्य"
+
msgid "Unit Price"
msgstr "यूनिट मूल्य"
@@ -8574,6 +8648,9 @@ msgstr "इन्वेंटरी जॉब पूरा होने पर
msgid "Why is the expiration being changed?"
msgstr "समाप्ति क्यों बदली जा रही है?"
+msgid "Why is this included?"
+msgstr "यह क्यों शामिल है?"
+
msgid "WIP"
msgstr "WIP"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 98f838151b..97c2edf1ec 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -2473,6 +2473,12 @@ msgstr "Domanda"
msgid "Demand Forecast"
msgstr "Previsione della Domanda"
+msgid "Demand Forecast — Driven by"
+msgstr "Previsione della domanda — Guidata da"
+
+msgid "Demand forecast = BOM-exploded demand from open sales orders, active jobs, and production projections."
+msgstr "Previsione della domanda = domanda esplosa da BOM da ordini di vendita aperti, lavori attivi e proiezioni di produzione."
+
msgid "Demand Projections"
msgstr "Proiezioni della Domanda"
@@ -2632,6 +2638,9 @@ msgstr "Stati Spedizione Diretta"
msgid "Drop your file here, or click to browse."
msgstr "Rilascia il tuo file qui, oppure fai clic per sfogliare."
+msgid "Due"
+msgstr "Scadenza"
+
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(dueDate) )
msgid "Due {0}"
msgstr "Scadenza {0}"
@@ -3679,6 +3688,10 @@ msgstr "Per le aziende in crescita che hanno bisogno di supporto"
msgid "For US companies handling ITAR data"
msgstr "Per le aziende statunitensi che gestiscono dati ITAR"
+#. placeholder {0}: forecastMethod ?? "unknown"
+msgid "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."
+msgstr "Metodo di previsione: <0>{0}</0>. Questa riga non è stata derivata da lavori attivi, quindi nessuna fonte padre è disponibile."
+
msgid "Forgot to Clock Out?"
msgstr "Hai dimenticato di timbrare l'uscita?"
@@ -3820,6 +3833,9 @@ msgstr "Ore/Pezzo"
msgid "How the resolved price was calculated."
msgstr "Come è stato calcolato il prezzo risolto."
+msgid "How this price was calculated"
+msgstr "Come è stato calcolato questo prezzo"
+
msgid "Humidity"
msgstr "Umidità"
@@ -3985,6 +4001,9 @@ msgstr "Interno"
msgid "Internal Notes"
msgstr "Note Interne"
+msgid "inv"
+msgstr "inv"
+
msgid "Invalid Invite"
msgstr "Invito Non Valido"
@@ -4264,6 +4283,9 @@ msgstr "Ultimo aggiornamento: {formattedDate}"
msgid "Lead Time"
msgstr "Tempo di consegna"
+msgid "Lead time (days)"
+msgstr "Tempo di consegna (giorni)"
+
msgid "Lead Time (Days)"
msgstr "Tempo di consegna (Giorni)"
@@ -4344,6 +4366,9 @@ msgstr "Collega problema Linear"
msgid "Linked entity quantity ({0}) does not match row quantity ({1})."
msgstr "La quantità dell'entità collegata ({0}) non corrisponde alla quantità della riga ({1})."
+msgid "Linked PO"
+msgstr "PO collegato"
+
msgid "List Options"
msgstr "Opzioni Elenco"
@@ -4411,6 +4436,9 @@ msgstr "Perso"
msgid "Lot"
msgstr "Lotto"
+msgid "Lot size"
+msgstr "Dimensione lotto"
+
msgid "Lot Size"
msgstr "Dimensione Lotto"
@@ -4814,6 +4842,9 @@ msgstr "Naviga"
msgid "NCRs by Type"
msgstr "NCR per tipo"
+msgid "Need by"
+msgstr "Necessario entro"
+
msgid "Negative Adjustment"
msgstr "Rettifica Negativa"
@@ -5224,6 +5255,9 @@ msgstr "Nessun corso di formazione in sospeso"
msgid "No overtime scheduled"
msgstr "Nessun straordinario programmato"
+msgid "No parent sources recorded yet. Click Recalculate on the planning page to refresh attribution."
+msgstr "Nessuna fonte padre registrata ancora. Fai clic su Ricalcola nella pagina di pianificazione per aggiornare l'attribuzione."
+
msgid "No part ID"
msgstr "Nessun ID parte"
@@ -5473,6 +5507,9 @@ msgstr "Opzioni"
msgid "Order"
msgstr "Ordine"
+msgid "Order by"
+msgstr "Ordina entro"
+
msgid "Order Date"
msgstr "Data dell'ordine"
@@ -5578,6 +5615,9 @@ msgstr "Dipartimento Principale"
msgid "Parent Group"
msgstr "Gruppo Padre"
+msgid "Parent Item"
+msgstr "Articolo Padre"
+
msgid "Parent Storage Unit"
msgstr "Unità di Archiviazione Principale"
@@ -5719,6 +5759,12 @@ msgstr "Fine pianificata"
msgid "Planned End Time"
msgstr "Ora di fine pianificata"
+msgid "Planned Order"
+msgstr "Ordine Pianificato"
+
+msgid "Planned order = MRP suggestion to cover projected demand based on the item's reorder policy (or manually added)."
+msgstr "Ordine pianificato = suggerimento MRP per coprire la domanda prevista in base alla politica di riordino dell'articolo (o aggiunto manualmente)."
+
msgid "Planned Start"
msgstr "Inizio Pianificato"
@@ -5764,6 +5810,9 @@ msgstr "Numero OD"
msgid "PO PDF"
msgstr "PDF OdA"
+msgid "Policy"
+msgstr "Politica"
+
msgid "Policy & Procedure"
msgstr "Politica e Procedura"
@@ -5932,6 +5981,12 @@ msgstr "Progresso"
msgid "Project"
msgstr "Progetto"
+msgid "Projected stock"
+msgstr "Stock previsto"
+
+msgid "Projection"
+msgstr "Proiezione"
+
msgid "Projections"
msgstr "Proiezioni"
@@ -6038,6 +6093,9 @@ msgstr "Codice QR per creare un {0} per questo kanban"
msgid "QR Code to start the next operation for this kanban"
msgstr "Codice QR per avviare l'operazione successiva per questo kanban"
+msgid "Qty"
+msgstr "Qtà"
+
msgid "Qty to Order"
msgstr "Qtà da ordinare"
@@ -6101,6 +6159,10 @@ msgstr "Quantità per Genitore"
msgid "Quantity Type"
msgstr "Tipo di Quantità"
+#. placeholder {0}: numberFormatter.format(forecastQuantity)
+msgid "Quantity: {0}"
+msgstr "Quantità: {0}"
+
msgid "Question"
msgstr "Domanda"
@@ -6568,6 +6630,9 @@ msgstr "Esegui Test"
msgid "Running Total"
msgstr "Totale Progressivo"
+msgid "Safety stock"
+msgstr "Stock di sicurezza"
+
msgid "Safety Stock"
msgstr "Stock di Sicurezza"
@@ -7653,6 +7718,9 @@ msgstr "L'indirizzo di fatturazione utilizzato su preventivi, ordini di vendita,
msgid "The date the customer expects to receive the goods"
msgstr "La data in cui il cliente si aspetta di ricevere la merce"
+msgid "The date the item is required on-site to cover the period's projected demand."
+msgstr "La data in cui l'articolo è richiesto in loco per coprire la domanda prevista del periodo."
+
msgid "The endpoint that receives a POST request with the updated data when the table is updated"
msgstr "L'endpoint che riceve una richiesta POST con i dati aggiornati quando la tabella viene aggiornata"
@@ -7662,6 +7730,9 @@ msgstr "I seguenti assiemi non hanno operazioni. Assegnare un'operazione a ciasc
msgid "The following line items are missing prices or lead times:"
msgstr "I seguenti articoli di riga non hanno prezzi o tempi di consegna:"
+msgid "The latest date to place this PO so it arrives by the need-by date, given the supplier's lead time."
+msgstr "La data più recente per effettuare questo ordine in modo che arrivi entro la data richiesta, considerando il lead time del fornitore."
+
msgid "The lot will still be rejected, but an NCR cannot be auto-created until at least one Issue Type is configured."
msgstr "Il lotto sarà comunque rifiutato, ma un NCR non può essere creato automaticamente fino a quando non è configurato almeno un tipo di problema."
@@ -8067,6 +8138,9 @@ msgstr "Unità di Misura"
msgid "Unit of Measures"
msgstr "Unità di Misura"
+msgid "Unit price"
+msgstr "Prezzo unitario"
+
msgid "Unit Price"
msgstr "Prezzo Unitario"
@@ -8574,6 +8648,9 @@ msgstr "Chi dovrebbe ricevere notifiche quando un lavoro di inventario è comple
msgid "Why is the expiration being changed?"
msgstr "Perché la data di scadenza viene modificata?"
+msgid "Why is this included?"
+msgstr "Perché è incluso?"
+
msgid "WIP"
msgstr "WIP"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 61a484d16f..76203d918c 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -2473,6 +2473,12 @@ msgstr "需要"
msgid "Demand Forecast"
msgstr "需要予測"
+msgid "Demand Forecast — Driven by"
+msgstr "需要予測 — 駆動元"
+
+msgid "Demand forecast = BOM-exploded demand from open sales orders, active jobs, and production projections."
+msgstr "需要予測 = BOM展開需要(オープン販売注文、アクティブなジョブ、および生産予測から)"
+
msgid "Demand Projections"
msgstr "需要予測"
@@ -2632,6 +2638,9 @@ msgstr "ドロップシップメントステータス"
msgid "Drop your file here, or click to browse."
msgstr "ファイルをここにドラッグするか、クリックして参照してください。"
+msgid "Due"
+msgstr "期限"
+
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(dueDate) )
msgid "Due {0}"
msgstr "期限 {0}"
@@ -3679,6 +3688,10 @@ msgstr "成長中のビジネスをサポートするために"
msgid "For US companies handling ITAR data"
msgstr "ITAR データを扱う米国企業向け"
+#. placeholder {0}: forecastMethod ?? "unknown"
+msgid "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."
+msgstr "予測方法: <0>{0}</0>。この行はアクティブなジョブから派生していないため、親ソースは利用できません。"
+
msgid "Forgot to Clock Out?"
msgstr "時刻記録を忘れましたか?"
@@ -3820,6 +3833,9 @@ msgstr "時間/個"
msgid "How the resolved price was calculated."
msgstr "解決された価格がどのように計算されたかを示します。"
+msgid "How this price was calculated"
+msgstr "この価格がどのように計算されたか"
+
msgid "Humidity"
msgstr "湿度"
@@ -3985,6 +4001,9 @@ msgstr "内部"
msgid "Internal Notes"
msgstr "内部メモ"
+msgid "inv"
+msgstr "在庫"
+
msgid "Invalid Invite"
msgstr "無効な招待"
@@ -4264,6 +4283,9 @@ msgstr "最終更新: {formattedDate}"
msgid "Lead Time"
msgstr "リードタイム"
+msgid "Lead time (days)"
+msgstr "リードタイム(日数)"
+
msgid "Lead Time (Days)"
msgstr "リードタイム(日数)"
@@ -4344,6 +4366,9 @@ msgstr "Linear イシューをリンク"
msgid "Linked entity quantity ({0}) does not match row quantity ({1})."
msgstr "リンクされたエンティティの数量({0})が行の数量({1})と一致しません。"
+msgid "Linked PO"
+msgstr "リンク済みPO"
+
msgid "List Options"
msgstr "リストオプション"
@@ -4411,6 +4436,9 @@ msgstr "失った"
msgid "Lot"
msgstr "ロット"
+msgid "Lot size"
+msgstr "ロットサイズ"
+
msgid "Lot Size"
msgstr "ロットサイズ"
@@ -4814,6 +4842,9 @@ msgstr "ナビゲート"
msgid "NCRs by Type"
msgstr "タイプ別NCR"
+msgid "Need by"
+msgstr "必要日"
+
msgid "Negative Adjustment"
msgstr "負の調整"
@@ -5224,6 +5255,9 @@ msgstr "未処理のトレーニングはありません"
msgid "No overtime scheduled"
msgstr "残業予定なし"
+msgid "No parent sources recorded yet. Click Recalculate on the planning page to refresh attribution."
+msgstr "親ソースはまだ記録されていません。計画ページの「再計算」をクリックして属性を更新してください。"
+
msgid "No part ID"
msgstr "パーツIDなし"
@@ -5473,6 +5507,9 @@ msgstr "オプション"
msgid "Order"
msgstr "注文"
+msgid "Order by"
+msgstr "注文日"
+
msgid "Order Date"
msgstr "注文日"
@@ -5578,6 +5615,9 @@ msgstr "親部門"
msgid "Parent Group"
msgstr "親グループ"
+msgid "Parent Item"
+msgstr "親アイテム"
+
msgid "Parent Storage Unit"
msgstr "親保管ユニット"
@@ -5719,6 +5759,12 @@ msgstr "計画終了"
msgid "Planned End Time"
msgstr "計画終了時刻"
+msgid "Planned Order"
+msgstr "計画注文"
+
+msgid "Planned order = MRP suggestion to cover projected demand based on the item's reorder policy (or manually added)."
+msgstr "計画注文 = 品目の発注ポリシー(または手動で追加)に基づいて予測需要をカバーするためのMRP提案。"
+
msgid "Planned Start"
msgstr "計画開始"
@@ -5764,6 +5810,9 @@ msgstr "発注番号"
msgid "PO PDF"
msgstr "PO PDF"
+msgid "Policy"
+msgstr "ポリシー"
+
msgid "Policy & Procedure"
msgstr "ポリシーと手順"
@@ -5932,6 +5981,12 @@ msgstr "進捗"
msgid "Project"
msgstr "プロジェクト"
+msgid "Projected stock"
+msgstr "予測在庫"
+
+msgid "Projection"
+msgstr "予測"
+
msgid "Projections"
msgstr "予測"
@@ -6038,6 +6093,9 @@ msgstr "このカンバンの{0}を作成するためのQRコード"
msgid "QR Code to start the next operation for this kanban"
msgstr "このカンバンの次の操作を開始するためのQRコード"
+msgid "Qty"
+msgstr "数量"
+
msgid "Qty to Order"
msgstr "注文数量"
@@ -6101,6 +6159,10 @@ msgstr "親あたりの数量"
msgid "Quantity Type"
msgstr "数量タイプ"
+#. placeholder {0}: numberFormatter.format(forecastQuantity)
+msgid "Quantity: {0}"
+msgstr "数量: {0}"
+
msgid "Question"
msgstr "質問"
@@ -6568,6 +6630,9 @@ msgstr "テストを実行"
msgid "Running Total"
msgstr "実行中の合計"
+msgid "Safety stock"
+msgstr "安全在庫"
+
msgid "Safety Stock"
msgstr "安全在庫"
@@ -7653,6 +7718,9 @@ msgstr "見積書、販売注文書、請求書、およびその他の販売文
msgid "The date the customer expects to receive the goods"
msgstr "顧客が商品を受け取ることを期待する日付"
+msgid "The date the item is required on-site to cover the period's projected demand."
+msgstr "その期間の予想需要をカバーするために、アイテムがオンサイトで必要とされる日付。"
+
msgid "The endpoint that receives a POST request with the updated data when the table is updated"
msgstr "テーブルが更新されたときに、更新されたデータを含むPOSTリクエストを受け取るエンドポイント"
@@ -7662,6 +7730,9 @@ msgstr "以下のアセンブリには操作がありません。リリースす
msgid "The following line items are missing prices or lead times:"
msgstr "以下の行項目は価格またはリードタイムが不足しています:"
+msgid "The latest date to place this PO so it arrives by the need-by date, given the supplier's lead time."
+msgstr "このPOを発注して、サプライヤーのリードタイムを考慮した上で、必要日までに到着するための最遅発注日です。"
+
msgid "The lot will still be rejected, but an NCR cannot be auto-created until at least one Issue Type is configured."
msgstr "ロットは引き続き却下されますが、少なくとも1つの問題タイプが設定されるまでNCRは自動作成できません。"
@@ -8067,6 +8138,9 @@ msgstr "測定単位"
msgid "Unit of Measures"
msgstr "測定単位"
+msgid "Unit price"
+msgstr "単価"
+
msgid "Unit Price"
msgstr "単価"
@@ -8574,6 +8648,9 @@ msgstr "在库存工作完成时,谁应该收到通知?"
msgid "Why is the expiration being changed?"
msgstr "有効期限が変更されるのはなぜですか?"
+msgid "Why is this included?"
+msgstr "なぜこれが含まれていますか?"
+
msgid "WIP"
msgstr "仕掛品"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 87fe908330..51779861ca 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -2473,6 +2473,12 @@ msgstr "Popyt"
msgid "Demand Forecast"
msgstr "Prognoza popytu"
+msgid "Demand Forecast — Driven by"
+msgstr "Prognoza popytu — Napędzane przez"
+
+msgid "Demand forecast = BOM-exploded demand from open sales orders, active jobs, and production projections."
+msgstr "Prognoza popytu = popyt wyeksplodowany z BOM z otwartych zamówień sprzedaży, aktywnych zleceń i prognoz produkcji."
+
msgid "Demand Projections"
msgstr "Prognozy popytu"
@@ -2632,6 +2638,9 @@ msgstr "Statusy wysyłki bezpośredniej"
msgid "Drop your file here, or click to browse."
msgstr "Upuść plik tutaj lub kliknij, aby przeglądać."
+msgid "Due"
+msgstr "Termin"
+
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(dueDate) )
msgid "Due {0}"
msgstr "Termin {0}"
@@ -3679,6 +3688,10 @@ msgstr "Dla rozwijających się firm, które potrzebują wsparcia"
msgid "For US companies handling ITAR data"
msgstr "Dla firm z USA obsługujących dane ITAR"
+#. placeholder {0}: forecastMethod ?? "unknown"
+msgid "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."
+msgstr "Metoda prognozy: <0>{0}</0>. Ten wiersz nie pochodzi z aktywnych zadań, dlatego nie są dostępne żadne źródła nadrzędne."
+
msgid "Forgot to Clock Out?"
msgstr "Zapomniałeś wylogować się z zegara?"
@@ -3820,6 +3833,9 @@ msgstr "Godziny/Sztuka"
msgid "How the resolved price was calculated."
msgstr "Jak została obliczona ostateczna cena."
+msgid "How this price was calculated"
+msgstr "Jak ta cena została obliczona"
+
msgid "Humidity"
msgstr "Wilgotność"
@@ -3985,6 +4001,9 @@ msgstr "Wewnętrzne"
msgid "Internal Notes"
msgstr "Notatki wewnętrzne"
+msgid "inv"
+msgstr "inv"
+
msgid "Invalid Invite"
msgstr "Nieprawidłowe zaproszenie"
@@ -4264,6 +4283,9 @@ msgstr "Ostatnia aktualizacja: {formattedDate}"
msgid "Lead Time"
msgstr "Czas dostawy"
+msgid "Lead time (days)"
+msgstr "Czas dostawy (dni)"
+
msgid "Lead Time (Days)"
msgstr "Czas realizacji (dni)"
@@ -4344,6 +4366,9 @@ msgstr "Połącz problem Linear"
msgid "Linked entity quantity ({0}) does not match row quantity ({1})."
msgstr "Ilość połączonej jednostki ({0}) nie odpowiada ilości wiersza ({1})."
+msgid "Linked PO"
+msgstr "Powiązane PO"
+
msgid "List Options"
msgstr "Opcje listy"
@@ -4411,6 +4436,9 @@ msgstr "Utracone"
msgid "Lot"
msgstr "Partia"
+msgid "Lot size"
+msgstr "Wielkość partii"
+
msgid "Lot Size"
msgstr "Rozmiar partii"
@@ -4814,6 +4842,9 @@ msgstr "Nawiguj"
msgid "NCRs by Type"
msgstr "NCRy wg typu"
+msgid "Need by"
+msgstr "Potrzebne do"
+
msgid "Negative Adjustment"
msgstr "Ujemna Korekta"
@@ -5224,6 +5255,9 @@ msgstr "Brak zaległych szkoleń"
msgid "No overtime scheduled"
msgstr "Brak zaplanowanych nadgodzin"
+msgid "No parent sources recorded yet. Click Recalculate on the planning page to refresh attribution."
+msgstr "Brak zarejestrowanych źródeł nadrzędnych. Kliknij Przelicz na stronie planowania, aby odświeżyć przypisanie."
+
msgid "No part ID"
msgstr "Brak identyfikatora części"
@@ -5473,6 +5507,9 @@ msgstr "Opcje"
msgid "Order"
msgstr "Zamówienie"
+msgid "Order by"
+msgstr "Zamów do"
+
msgid "Order Date"
msgstr "Data zamówienia"
@@ -5578,6 +5615,9 @@ msgstr "Dział Nadrzędny"
msgid "Parent Group"
msgstr "Grupa nadrzędna"
+msgid "Parent Item"
+msgstr "Element nadrzędny"
+
msgid "Parent Storage Unit"
msgstr "Nadrzędna jednostka magazynowa"
@@ -5719,6 +5759,12 @@ msgstr "Planowany koniec"
msgid "Planned End Time"
msgstr "Planowany czas zakończenia"
+msgid "Planned Order"
+msgstr "Zaplanowane Zamówienie"
+
+msgid "Planned order = MRP suggestion to cover projected demand based on the item's reorder policy (or manually added)."
+msgstr "Planowane zamówienie = sugestia MRP pokrywająca prognozowany popyt na podstawie polityki zamawiania pozycji (lub dodane ręcznie)."
+
msgid "Planned Start"
msgstr "Planowany początek"
@@ -5764,6 +5810,9 @@ msgstr "Numer PZ"
msgid "PO PDF"
msgstr "PDF PO"
+msgid "Policy"
+msgstr "Polityka"
+
msgid "Policy & Procedure"
msgstr "Polityka i procedura"
@@ -5932,6 +5981,12 @@ msgstr "Postęp"
msgid "Project"
msgstr "Projekt"
+msgid "Projected stock"
+msgstr "Prognozowany zapas"
+
+msgid "Projection"
+msgstr "Projekcja"
+
msgid "Projections"
msgstr "Prognozy"
@@ -6038,6 +6093,9 @@ msgstr "Kod QR do utworzenia {0} dla tego kanbanu"
msgid "QR Code to start the next operation for this kanban"
msgstr "Kod QR do rozpoczęcia następnej operacji dla tego kanbanu"
+msgid "Qty"
+msgstr "Ilość"
+
msgid "Qty to Order"
msgstr "Ilość do zamówienia"
@@ -6101,6 +6159,10 @@ msgstr "Ilość na jednostkę nadrzędną"
msgid "Quantity Type"
msgstr "Typ ilości"
+#. placeholder {0}: numberFormatter.format(forecastQuantity)
+msgid "Quantity: {0}"
+msgstr "Ilość: {0}"
+
msgid "Question"
msgstr "Pytanie"
@@ -6568,6 +6630,9 @@ msgstr "Uruchom Test"
msgid "Running Total"
msgstr "Suma bieżąca"
+msgid "Safety stock"
+msgstr "Zapas bezpieczeństwa"
+
msgid "Safety Stock"
msgstr "Zapas bezpieczeństwa"
@@ -7653,6 +7718,9 @@ msgstr "Adres rozliczeniowy używany na ofertach, zamówieniach sprzedaży, fakt
msgid "The date the customer expects to receive the goods"
msgstr "Data, w której klient spodziewa się otrzymać towary"
+msgid "The date the item is required on-site to cover the period's projected demand."
+msgstr "Data, do której towar musi być dostępny na miejscu, aby pokryć prognozowany popyt w danym okresie."
+
msgid "The endpoint that receives a POST request with the updated data when the table is updated"
msgstr "Punkt końcowy, który odbiera żądanie POST z zaktualizowanymi danymi, gdy tabela jest aktualizowana"
@@ -7662,6 +7730,9 @@ msgstr "Następujące zespoły nie mają operacji. Proszę przypisać operację
msgid "The following line items are missing prices or lead times:"
msgstr "Następujące pozycje linii nie mają cen lub czasów realizacji:"
+msgid "The latest date to place this PO so it arrives by the need-by date, given the supplier's lead time."
+msgstr "Najnowsza data złożenia tego zamówienia, aby dotarło do daty wymaganej, biorąc pod uwagę czas realizacji dostawcy."
+
msgid "The lot will still be rejected, but an NCR cannot be auto-created until at least one Issue Type is configured."
msgstr "Partia będzie nadal odrzucona, ale NCR nie może być automatycznie utworzony, dopóki nie zostanie skonfigurowany co najmniej jeden typ problemu."
@@ -8067,6 +8138,9 @@ msgstr "Jednostka miary"
msgid "Unit of Measures"
msgstr "Jednostki miary"
+msgid "Unit price"
+msgstr "Cena jednostkowa"
+
msgid "Unit Price"
msgstr "Cena jednostkowa"
@@ -8574,6 +8648,9 @@ msgstr "Kto powinien otrzymywać powiadomienia po zakończeniu zadania inwentary
msgid "Why is the expiration being changed?"
msgstr "Dlaczego data wygaśnięcia jest zmieniana?"
+msgid "Why is this included?"
+msgstr "Dlaczego to jest uwzględnione?"
+
msgid "WIP"
msgstr "WIP"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index d1513d79cf..22962e0b69 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -2473,6 +2473,12 @@ msgstr "Demanda"
msgid "Demand Forecast"
msgstr "Previsão de Demanda"
+msgid "Demand Forecast — Driven by"
+msgstr "Previsão de Demanda — Impulsionada por"
+
+msgid "Demand forecast = BOM-exploded demand from open sales orders, active jobs, and production projections."
+msgstr "Previsão de demanda = demanda explodida por BOM de pedidos de vendas abertos, trabalhos ativos e projeções de produção."
+
msgid "Demand Projections"
msgstr "Projeções de Demanda"
@@ -2632,6 +2638,9 @@ msgstr "Estados de Envio Direto"
msgid "Drop your file here, or click to browse."
msgstr "Solte seu arquivo aqui ou clique para procurar."
+msgid "Due"
+msgstr "Vencimento"
+
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(dueDate) )
msgid "Due {0}"
msgstr "Vencimento {0}"
@@ -3679,6 +3688,10 @@ msgstr "Para empresas em crescimento que precisam de suporte"
msgid "For US companies handling ITAR data"
msgstr "Para empresas dos EUA que lidam com dados ITAR"
+#. placeholder {0}: forecastMethod ?? "unknown"
+msgid "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."
+msgstr "Método de previsão: <0>{0}</0>. Esta linha não foi derivada de trabalhos ativos, portanto nenhuma fonte pai está disponível."
+
msgid "Forgot to Clock Out?"
msgstr "Esqueceu de Registrar a Saída?"
@@ -3820,6 +3833,9 @@ msgstr "Horas/Peça"
msgid "How the resolved price was calculated."
msgstr "Como o preço resolvido foi calculado."
+msgid "How this price was calculated"
+msgstr "Como este preço foi calculado"
+
msgid "Humidity"
msgstr "Umidade"
@@ -3985,6 +4001,9 @@ msgstr "Interno"
msgid "Internal Notes"
msgstr "Notas Internas"
+msgid "inv"
+msgstr "inv"
+
msgid "Invalid Invite"
msgstr "Convite Inválido"
@@ -4264,6 +4283,9 @@ msgstr "Última atualização: {formattedDate}"
msgid "Lead Time"
msgstr "Tempo de Entrega"
+msgid "Lead time (days)"
+msgstr "Tempo de entrega (dias)"
+
msgid "Lead Time (Days)"
msgstr "Tempo de Entrega (Dias)"
@@ -4344,6 +4366,9 @@ msgstr "Vincular Problema Linear"
msgid "Linked entity quantity ({0}) does not match row quantity ({1})."
msgstr "Quantidade de entidade vinculada ({0}) não corresponde à quantidade da linha ({1})."
+msgid "Linked PO"
+msgstr "PO Vinculada"
+
msgid "List Options"
msgstr "Opções de Lista"
@@ -4411,6 +4436,9 @@ msgstr "Perdido"
msgid "Lot"
msgstr "Lote"
+msgid "Lot size"
+msgstr "Tamanho do lote"
+
msgid "Lot Size"
msgstr "Tamanho do Lote"
@@ -4814,6 +4842,9 @@ msgstr "Navegar"
msgid "NCRs by Type"
msgstr "NCRs por Tipo"
+msgid "Need by"
+msgstr "Necessário até"
+
msgid "Negative Adjustment"
msgstr "Ajuste Negativo"
@@ -5224,6 +5255,9 @@ msgstr "Nenhum treinamento pendente"
msgid "No overtime scheduled"
msgstr "Nenhuma hora extra agendada"
+msgid "No parent sources recorded yet. Click Recalculate on the planning page to refresh attribution."
+msgstr "Nenhuma fonte pai registrada ainda. Clique em Recalcular na página de planejamento para atualizar a atribuição."
+
msgid "No part ID"
msgstr "Sem ID de peça"
@@ -5473,6 +5507,9 @@ msgstr "Opções"
msgid "Order"
msgstr "Pedido"
+msgid "Order by"
+msgstr "Encomendar até"
+
msgid "Order Date"
msgstr "Data do Pedido"
@@ -5578,6 +5615,9 @@ msgstr "Departamento Pai"
msgid "Parent Group"
msgstr "Grupo Pai"
+msgid "Parent Item"
+msgstr "Item Pai"
+
msgid "Parent Storage Unit"
msgstr "Unidade de Armazenamento Pai"
@@ -5719,6 +5759,12 @@ msgstr "Fim Planejado"
msgid "Planned End Time"
msgstr "Hora de Término Planejada"
+msgid "Planned Order"
+msgstr "Ordem Planejada"
+
+msgid "Planned order = MRP suggestion to cover projected demand based on the item's reorder policy (or manually added)."
+msgstr "Ordem planejada = sugestão de MRP para cobrir a demanda projetada com base na política de reabastecimento do item (ou adicionada manualmente)."
+
msgid "Planned Start"
msgstr "Início Planejado"
@@ -5764,6 +5810,9 @@ msgstr "Número da PO"
msgid "PO PDF"
msgstr "PDF da PO"
+msgid "Policy"
+msgstr "Política"
+
msgid "Policy & Procedure"
msgstr "Política e Procedimento"
@@ -5932,6 +5981,12 @@ msgstr "Progresso"
msgid "Project"
msgstr "Projeto"
+msgid "Projected stock"
+msgstr "Stock projetado"
+
+msgid "Projection"
+msgstr "Projeção"
+
msgid "Projections"
msgstr "Projeções"
@@ -6038,6 +6093,9 @@ msgstr "Código QR para criar um {0} para este kanban"
msgid "QR Code to start the next operation for this kanban"
msgstr "Código QR para iniciar a próxima operação para este kanban"
+msgid "Qty"
+msgstr "Qtd"
+
msgid "Qty to Order"
msgstr "Qtd a Encomendar"
@@ -6101,6 +6159,10 @@ msgstr "Quantidade por Pai"
msgid "Quantity Type"
msgstr "Tipo de Quantidade"
+#. placeholder {0}: numberFormatter.format(forecastQuantity)
+msgid "Quantity: {0}"
+msgstr "Quantidade: {0}"
+
msgid "Question"
msgstr "Pergunta"
@@ -6568,6 +6630,9 @@ msgstr "Executar Teste"
msgid "Running Total"
msgstr "Total em Execução"
+msgid "Safety stock"
+msgstr "Stock de segurança"
+
msgid "Safety Stock"
msgstr "Stock de Segurança"
@@ -7653,6 +7718,9 @@ msgstr "O endereço de cobrança usado em orçamentos, pedidos de venda, faturas
msgid "The date the customer expects to receive the goods"
msgstr "A data em que o cliente espera receber os bens"
+msgid "The date the item is required on-site to cover the period's projected demand."
+msgstr "A data em que o item é necessário no local para cobrir a demanda projetada do período."
+
msgid "The endpoint that receives a POST request with the updated data when the table is updated"
msgstr "O endpoint que recebe uma solicitação POST com os dados atualizados quando a tabela é atualizada"
@@ -7662,6 +7730,9 @@ msgstr "Os seguintes conjuntos não têm operações. Atribua uma operação a c
msgid "The following line items are missing prices or lead times:"
msgstr "Os seguintes itens de linha estão faltando preços ou prazos de entrega:"
+msgid "The latest date to place this PO so it arrives by the need-by date, given the supplier's lead time."
+msgstr "A data mais tardia para fazer este PO para que chegue até a data de necessidade, considerando o prazo de entrega do fornecedor."
+
msgid "The lot will still be rejected, but an NCR cannot be auto-created until at least one Issue Type is configured."
msgstr "O lote ainda será rejeitado, mas um NCR não pode ser criado automaticamente até que pelo menos um Tipo de Problema seja configurado."
@@ -8067,6 +8138,9 @@ msgstr "Unidade de Medida"
msgid "Unit of Measures"
msgstr "Unidades de Medida"
+msgid "Unit price"
+msgstr "Preço unitário"
+
msgid "Unit Price"
msgstr "Preço Unitário"
@@ -8574,6 +8648,9 @@ msgstr "Quem deve receber notificações quando um trabalho de inventário é co
msgid "Why is the expiration being changed?"
msgstr "Por que a expiração está sendo alterada?"
+msgid "Why is this included?"
+msgstr "Por que isto está incluído?"
+
msgid "WIP"
msgstr "WIP"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 2992aa8b4c..c285f86111 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -2473,6 +2473,12 @@ msgstr "Спрос"
msgid "Demand Forecast"
msgstr "Прогноз спроса"
+msgid "Demand Forecast — Driven by"
+msgstr "Прогноз спроса — Обусловлено"
+
+msgid "Demand forecast = BOM-exploded demand from open sales orders, active jobs, and production projections."
+msgstr "Прогноз спроса = спрос, разложенный по BOM, из открытых заказов на продажу, активных работ и прогнозов производства."
+
msgid "Demand Projections"
msgstr "Прогнозы спроса"
@@ -2632,6 +2638,9 @@ msgstr "Статусы прямой доставки"
msgid "Drop your file here, or click to browse."
msgstr "Перетащите файл сюда или нажмите для обзора."
+msgid "Due"
+msgstr "Срок"
+
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(dueDate) )
msgid "Due {0}"
msgstr "Срок {0}"
@@ -3679,6 +3688,10 @@ msgstr "Для растущих компаний, нуждающихся в по
msgid "For US companies handling ITAR data"
msgstr "Для компаний США, работающих с данными ITAR"
+#. placeholder {0}: forecastMethod ?? "unknown"
+msgid "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."
+msgstr "Метод прогнозирования: <0>{0}</0>. Эта строка не была получена из активных заданий, поэтому родительские источники недоступны."
+
msgid "Forgot to Clock Out?"
msgstr "Забыли отметить уход?"
@@ -3820,6 +3833,9 @@ msgstr "Часов/Деталь"
msgid "How the resolved price was calculated."
msgstr "Как была рассчитана окончательная цена."
+msgid "How this price was calculated"
+msgstr "Как была рассчитана эта цена"
+
msgid "Humidity"
msgstr "Влажность"
@@ -3985,6 +4001,9 @@ msgstr "Внутренние"
msgid "Internal Notes"
msgstr "Внутренние примечания"
+msgid "inv"
+msgstr "инв"
+
msgid "Invalid Invite"
msgstr "Недействительное приглашение"
@@ -4264,6 +4283,9 @@ msgstr "Последнее обновление: {formattedDate}"
msgid "Lead Time"
msgstr "Время поставки"
+msgid "Lead time (days)"
+msgstr "Время доставки (дни)"
+
msgid "Lead Time (Days)"
msgstr "Время выполнения (дни)"
@@ -4344,6 +4366,9 @@ msgstr "Связать проблему Linear"
msgid "Linked entity quantity ({0}) does not match row quantity ({1})."
msgstr "Количество связанной сущности ({0}) не совпадает с количеством строки ({1})."
+msgid "Linked PO"
+msgstr "Связанный ПО"
+
msgid "List Options"
msgstr "Параметры списка"
@@ -4411,6 +4436,9 @@ msgstr "Потеряно"
msgid "Lot"
msgstr "Партия"
+msgid "Lot size"
+msgstr "Размер партии"
+
msgid "Lot Size"
msgstr "Размер партии"
@@ -4814,6 +4842,9 @@ msgstr "Навигация"
msgid "NCRs by Type"
msgstr "NCRs по типам"
+msgid "Need by"
+msgstr "Требуется к"
+
msgid "Negative Adjustment"
msgstr "Отрицательная корректировка"
@@ -5224,6 +5255,9 @@ msgstr "Нет невыполненных обучений"
msgid "No overtime scheduled"
msgstr "Нет запланированных переработок"
+msgid "No parent sources recorded yet. Click Recalculate on the planning page to refresh attribution."
+msgstr "Родительские источники еще не записаны. Нажмите \"Пересчитать\" на странице планирования, чтобы обновить атрибуцию."
+
msgid "No part ID"
msgstr "Нет ID детали"
@@ -5473,6 +5507,9 @@ msgstr "Параметры"
msgid "Order"
msgstr "Заказ"
+msgid "Order by"
+msgstr "Заказать до"
+
msgid "Order Date"
msgstr "Дата заказа"
@@ -5578,6 +5615,9 @@ msgstr "Родительский отдел"
msgid "Parent Group"
msgstr "Родительская группа"
+msgid "Parent Item"
+msgstr "Родительский товар"
+
msgid "Parent Storage Unit"
msgstr "Родительское хранилище"
@@ -5719,6 +5759,12 @@ msgstr "Запланированное окончание"
msgid "Planned End Time"
msgstr "Запланированное время окончания"
+msgid "Planned Order"
+msgstr "Плановый заказ"
+
+msgid "Planned order = MRP suggestion to cover projected demand based on the item's reorder policy (or manually added)."
+msgstr "Плановый заказ = предложение MRP для покрытия прогнозируемого спроса на основе политики переупорядочения товара (или добавлено вручную)."
+
msgid "Planned Start"
msgstr "Запланированное начало"
@@ -5764,6 +5810,9 @@ msgstr "Номер ПО"
msgid "PO PDF"
msgstr "ПО PDF"
+msgid "Policy"
+msgstr "Политика"
+
msgid "Policy & Procedure"
msgstr "Политика и процедура"
@@ -5932,6 +5981,12 @@ msgstr "Прогресс"
msgid "Project"
msgstr "Проект"
+msgid "Projected stock"
+msgstr "Прогнозируемый запас"
+
+msgid "Projection"
+msgstr "Прогноз"
+
msgid "Projections"
msgstr "Прогнозы"
@@ -6038,6 +6093,9 @@ msgstr "QR-код для создания {0} для этого канбана"
msgid "QR Code to start the next operation for this kanban"
msgstr "QR-код для начала следующей операции для этого канбана"
+msgid "Qty"
+msgstr "Кол-во"
+
msgid "Qty to Order"
msgstr "Кол-во для заказа"
@@ -6101,6 +6159,10 @@ msgstr "Количество на родителя"
msgid "Quantity Type"
msgstr "Тип количества"
+#. placeholder {0}: numberFormatter.format(forecastQuantity)
+msgid "Quantity: {0}"
+msgstr "Количество: {0}"
+
msgid "Question"
msgstr "Вопрос"
@@ -6568,6 +6630,9 @@ msgstr "Запустить тест"
msgid "Running Total"
msgstr "Итоговая сумма"
+msgid "Safety stock"
+msgstr "Страховой запас"
+
msgid "Safety Stock"
msgstr "Страховой запас"
@@ -7653,6 +7718,9 @@ msgstr "Адрес выставления счета, используемый
msgid "The date the customer expects to receive the goods"
msgstr "Дата, когда клиент ожидает получить товары"
+msgid "The date the item is required on-site to cover the period's projected demand."
+msgstr "Дата, когда товар должен быть доставлен на объект для покрытия прогнозируемого спроса за период."
+
msgid "The endpoint that receives a POST request with the updated data when the table is updated"
msgstr "Конечная точка, которая получает POST-запрос с обновленными данными при обновлении таблицы"
@@ -7662,6 +7730,9 @@ msgstr "Следующие сборки не имеют операций. Пож
msgid "The following line items are missing prices or lead times:"
msgstr "Следующие позиции отсутствуют цены или сроки поставки:"
+msgid "The latest date to place this PO so it arrives by the need-by date, given the supplier's lead time."
+msgstr "Последняя дата размещения этого заказа, чтобы он прибыл к требуемой дате, учитывая время доставки поставщика."
+
msgid "The lot will still be rejected, but an NCR cannot be auto-created until at least one Issue Type is configured."
msgstr "Партия все еще будет отклонена, но NCR не может быть автоматически создана до тех пор, пока не будет настроен хотя бы один тип проблемы."
@@ -8067,6 +8138,9 @@ msgstr "Единица измерения"
msgid "Unit of Measures"
msgstr "Единицы измерения"
+msgid "Unit price"
+msgstr "Цена за единицу"
+
msgid "Unit Price"
msgstr "Цена за единицу"
@@ -8574,6 +8648,9 @@ msgstr "Кто должен получать уведомления при за
msgid "Why is the expiration being changed?"
msgstr "Почему истекает срок действия?"
+msgid "Why is this included?"
+msgstr "Почему это включено?"
+
msgid "WIP"
msgstr "НЗП"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 98625df15b..859820cc2f 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -2473,6 +2473,12 @@ msgstr "需求"
msgid "Demand Forecast"
msgstr "需求预测"
+msgid "Demand Forecast — Driven by"
+msgstr "需求预测 — 驱动因素"
+
+msgid "Demand forecast = BOM-exploded demand from open sales orders, active jobs, and production projections."
+msgstr "需求预测 = 来自未结销售订单、活跃工作和生产预测的物料清单展开需求。"
+
msgid "Demand Projections"
msgstr "需求预测"
@@ -2632,6 +2638,9 @@ msgstr "直运状态"
msgid "Drop your file here, or click to browse."
msgstr "将文件拖放到此处,或点击浏览。"
+msgid "Due"
+msgstr "到期"
+
#. placeholder {0}: formatRelativeTime( convertDateStringToIsoString(dueDate) )
msgid "Due {0}"
msgstr "截止日期 {0}"
@@ -3679,6 +3688,10 @@ msgstr "适合需要支持的成长型企业"
msgid "For US companies handling ITAR data"
msgstr "适用于处理ITAR数据的美国公司"
+#. placeholder {0}: forecastMethod ?? "unknown"
+msgid "Forecast method: <0>{0}</0>. This row was not derived from active jobs, so no parent sources are available."
+msgstr "预测方法:<0>{0}</0>。此行不是从活跃工作派生的,因此没有可用的父源。"
+
msgid "Forgot to Clock Out?"
msgstr "忘记打卡下班了?"
@@ -3820,6 +3833,9 @@ msgstr "小时/件"
msgid "How the resolved price was calculated."
msgstr "已解决价格的计算方式。"
+msgid "How this price was calculated"
+msgstr "此价格是如何计算的"
+
msgid "Humidity"
msgstr "湿度"
@@ -3985,6 +4001,9 @@ msgstr "内部"
msgid "Internal Notes"
msgstr "内部备注"
+msgid "inv"
+msgstr "库存"
+
msgid "Invalid Invite"
msgstr "无效邀请"
@@ -4264,6 +4283,9 @@ msgstr "最后更新: {formattedDate}"
msgid "Lead Time"
msgstr "提前期"
+msgid "Lead time (days)"
+msgstr "提前期(天)"
+
msgid "Lead Time (Days)"
msgstr "交期(天)"
@@ -4344,6 +4366,9 @@ msgstr "关联 Linear 问题"
msgid "Linked entity quantity ({0}) does not match row quantity ({1})."
msgstr "关联实体数量 ({0}) 与行数量 ({1}) 不匹配。"
+msgid "Linked PO"
+msgstr "关联采购订单"
+
msgid "List Options"
msgstr "列表选项"
@@ -4411,6 +4436,9 @@ msgstr "已失败"
msgid "Lot"
msgstr "批次"
+msgid "Lot size"
+msgstr "批量大小"
+
msgid "Lot Size"
msgstr "批量大小"
@@ -4814,6 +4842,9 @@ msgstr "导航"
msgid "NCRs by Type"
msgstr "按类型分类的不符合项"
+msgid "Need by"
+msgstr "需要日期"
+
msgid "Negative Adjustment"
msgstr "负调整"
@@ -5224,6 +5255,9 @@ msgstr "没有未完成的培训"
msgid "No overtime scheduled"
msgstr "没有安排加班"
+msgid "No parent sources recorded yet. Click Recalculate on the planning page to refresh attribution."
+msgstr "尚未记录任何父源。点击计划页面上的\"重新计算\"以刷新归因。"
+
msgid "No part ID"
msgstr "无零件ID"
@@ -5473,6 +5507,9 @@ msgstr "选项"
msgid "Order"
msgstr "订单"
+msgid "Order by"
+msgstr "订购截止日期"
+
msgid "Order Date"
msgstr "订单日期"
@@ -5578,6 +5615,9 @@ msgstr "上级部门"
msgid "Parent Group"
msgstr "上级组"
+msgid "Parent Item"
+msgstr "父项目"
+
msgid "Parent Storage Unit"
msgstr "父存储单元"
@@ -5719,6 +5759,12 @@ msgstr "计划结束"
msgid "Planned End Time"
msgstr "计划结束时间"
+msgid "Planned Order"
+msgstr "计划订单"
+
+msgid "Planned order = MRP suggestion to cover projected demand based on the item's reorder policy (or manually added)."
+msgstr "计划订单 = MRP 建议,用于根据物品的重新订购政策(或手动添加)覆盖预计需求。"
+
msgid "Planned Start"
msgstr "计划开始"
@@ -5764,6 +5810,9 @@ msgstr "采购订单号"
msgid "PO PDF"
msgstr "采购订单 PDF"
+msgid "Policy"
+msgstr "政策"
+
msgid "Policy & Procedure"
msgstr "政策与程序"
@@ -5932,6 +5981,12 @@ msgstr "进度"
msgid "Project"
msgstr "项目"
+msgid "Projected stock"
+msgstr "预计库存"
+
+msgid "Projection"
+msgstr "预测"
+
msgid "Projections"
msgstr "预测"
@@ -6038,6 +6093,9 @@ msgstr "二维码以为此看板创建{0}"
msgid "QR Code to start the next operation for this kanban"
msgstr "二维码用于启动此看板的下一个操作"
+msgid "Qty"
+msgstr "数量"
+
msgid "Qty to Order"
msgstr "订购数量"
@@ -6101,6 +6159,10 @@ msgstr "每个父项的数量"
msgid "Quantity Type"
msgstr "数量类型"
+#. placeholder {0}: numberFormatter.format(forecastQuantity)
+msgid "Quantity: {0}"
+msgstr "数量:{0}"
+
msgid "Question"
msgstr "问题"
@@ -6568,6 +6630,9 @@ msgstr "运行测试"
msgid "Running Total"
msgstr "运行总计"
+msgid "Safety stock"
+msgstr "安全库存"
+
msgid "Safety Stock"
msgstr "安全库存"
@@ -7653,6 +7718,9 @@ msgstr "用于报价单、销售订单、发票和其他销售文件的账单地
msgid "The date the customer expects to receive the goods"
msgstr "客户期望收到货物的日期"
+msgid "The date the item is required on-site to cover the period's projected demand."
+msgstr "该项目需要在现场到达的日期,以满足该期间的预计需求。"
+
msgid "The endpoint that receives a POST request with the updated data when the table is updated"
msgstr "接收表格更新时包含更新数据的POST请求的端点"
@@ -7662,6 +7730,9 @@ msgstr "以下装配体没有操作。请在发布前为每个装配体分配一
msgid "The following line items are missing prices or lead times:"
msgstr "以下行项目缺少价格或交货期:"
+msgid "The latest date to place this PO so it arrives by the need-by date, given the supplier's lead time."
+msgstr "最迟下达此采购订单的日期,以便在考虑供应商交货期的情况下按需求日期前送达。"
+
msgid "The lot will still be rejected, but an NCR cannot be auto-created until at least one Issue Type is configured."
msgstr "该批次仍将被拒收,但在至少配置一个问题类型之前,无法自动创建NCR。"
@@ -8067,6 +8138,9 @@ msgstr "计量单位"
msgid "Unit of Measures"
msgstr "计量单位"
+msgid "Unit price"
+msgstr "单价"
+
msgid "Unit Price"
msgstr "单价"
@@ -8574,6 +8648,9 @@ msgstr "当库存工作完成时,谁应该收到通知?"
msgid "Why is the expiration being changed?"
msgstr "为什么要更改过期日期?"
+msgid "Why is this included?"
+msgstr "为什么包括这个?"
+
msgid "WIP"
msgstr "在制品"
diff --git a/packages/locale/vitest.config.ts b/packages/locale/vitest.config.ts
new file mode 100644
index 0000000000..9a3c27eaed
--- /dev/null
+++ b/packages/locale/vitest.config.ts
@@ -0,0 +1 @@
+export { default } from "@carbon/config/vitest";
diff --git a/packages/mrp/package.json b/packages/mrp/package.json
new file mode 100644
index 0000000000..352995ceee
--- /dev/null
+++ b/packages/mrp/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "@carbon/mrp",
+ "version": "0.0.0",
+ "private": true,
+ "sideEffects": false,
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "scripts": {
+ "clean": "rimraf .turbo node_modules dist",
+ "lint": "biome lint --write",
+ "test": "vitest run",
+ "typecheck": "tsgo --noEmit"
+ },
+ "devDependencies": {
+ "@carbon/config": "workspace:*",
+ "typescript": "catalog:",
+ "vitest": "catalog:"
+ }
+}
diff --git a/packages/mrp/src/engine.test.ts b/packages/mrp/src/engine.test.ts
new file mode 100644
index 0000000000..e8399f9dab
--- /dev/null
+++ b/packages/mrp/src/engine.test.ts
@@ -0,0 +1,443 @@
+import { describe, expect, it } from "vitest";
+import {
+ type BomChild,
+ type BomExplosionInput,
+ computeLowLevelCodes,
+ type DemandContributor,
+ type DemandPeriod,
+ explodeBom,
+ makeKey,
+ type ReplenishmentSystem,
+ splitKey
+} from "./engine";
+
+// ─── Test BOM structure ─────────────────────────────────────────────
+//
+// M000000001 (Manufactured, Make)
+// ├── P000000001 (Level 1 Purchased, Buy, Pull from Inventory, qty 2)
+// └── L000000001 (Level 1 Made, Make, Pull from Inventory, qty 2)
+// ├── P000000002 (Level 2 Purchase, Buy, Purchase to Order, qty 2)
+// └── P000000003 (Level 2 Made, Make, Make to Order, qty 2)
+// └── P000000004 (Level 3 Purchased, Buy, Pull from Inventory, qty 2)
+
+const M = "M000000001";
+const P1 = "P000000001";
+const L1 = "L000000001";
+const P2 = "P000000002";
+const P3 = "P000000003";
+const P4 = "P000000004";
+
+const LOC = "loc1";
+const PER1 = "per1";
+
+function buildBom(): Map<string, BomChild[]> {
+ return new Map([
+ [
+ M,
+ [
+ { itemId: P1, quantity: 2, methodType: "Pull from Inventory" },
+ { itemId: L1, quantity: 2, methodType: "Pull from Inventory" }
+ ]
+ ],
+ [
+ L1,
+ [
+ { itemId: P2, quantity: 2, methodType: "Purchase to Order" },
+ { itemId: P3, quantity: 2, methodType: "Make to Order" }
+ ]
+ ],
+ [P3, [{ itemId: P4, quantity: 2, methodType: "Pull from Inventory" }]]
+ ]);
+}
+
+function buildReplenishment(): Map<string, ReplenishmentSystem> {
+ return new Map<string, ReplenishmentSystem>([
+ [M, "Make"],
+ [P1, "Buy"],
+ [L1, "Make"],
+ [P2, "Buy"],
+ [P3, "Make"],
+ [P4, "Buy"]
+ ]);
+}
+
+function buildLeadTimes(): Map<string, number> {
+ return new Map([
+ [M, 7],
+ [P1, 7],
+ [L1, 7],
+ [P2, 7],
+ [P3, 7],
+ [P4, 7]
+ ]);
+}
+
+function buildPeriods(): DemandPeriod[] {
+ return [
+ { id: PER1, startDate: "2026-05-25", endDate: "2026-05-31" },
+ { id: "per2", startDate: "2026-06-01", endDate: "2026-06-07" },
+ { id: "per3", startDate: "2026-06-08", endDate: "2026-06-14" }
+ ];
+}
+
+function baseInput(overrides?: Partial<BomExplosionInput>): BomExplosionInput {
+ return {
+ grossDemand: overrides?.grossDemand ?? new Map(),
+ bomByItem: overrides?.bomByItem ?? buildBom(),
+ replenishmentSystemByItem:
+ overrides?.replenishmentSystemByItem ?? buildReplenishment(),
+ leadTimeByItem: overrides?.leadTimeByItem ?? buildLeadTimes(),
+ periods: overrides?.periods ?? buildPeriods(),
+ onHandByLocationItem: overrides?.onHandByLocationItem ?? new Map(),
+ jobSupplyByLocationPeriodItem:
+ overrides?.jobSupplyByLocationPeriodItem ?? new Map(),
+ topLevelContributors: overrides?.topLevelContributors ?? new Map()
+ };
+}
+
+// ─── Helpers ────────────────────────────────────────────────────────
+
+describe("splitKey", () => {
+ it("splits a standard three-part key", () => {
+ expect(splitKey("loc1-per1-item1")).toEqual(["loc1", "per1", "item1"]);
+ });
+
+ it("handles item IDs that contain hyphens", () => {
+ expect(splitKey("loc1-per1-item-with-hyphens")).toEqual([
+ "loc1",
+ "per1",
+ "item-with-hyphens"
+ ]);
+ });
+});
+
+describe("makeKey", () => {
+ it("creates a key from location, period, and item", () => {
+ expect(makeKey("loc1", "per1", "item1")).toBe("loc1-per1-item1");
+ });
+});
+
+// ─── Low-Level Codes ────────────────────────────────────────────────
+
+describe("computeLowLevelCodes", () => {
+ it("assigns level 0 to a top-level item with no parents", () => {
+ const llc = computeLowLevelCodes(buildBom());
+ expect(llc.get(M)).toBe(0);
+ });
+
+ it("assigns increasing levels down the BOM tree", () => {
+ const llc = computeLowLevelCodes(buildBom());
+ expect(llc.get(P1)).toBe(1);
+ expect(llc.get(L1)).toBe(1);
+ expect(llc.get(P2)).toBe(2);
+ expect(llc.get(P3)).toBe(2);
+ expect(llc.get(P4)).toBe(3);
+ });
+
+ it("traverses through Make-to-Order/Make items", () => {
+ const llc = computeLowLevelCodes(buildBom());
+ // P3 is Make-to-Order + Make. Previously skipped, leaving P4 at level 0.
+ expect(llc.get(P3)).toBe(2);
+ expect(llc.get(P4)).toBe(3);
+ });
+
+ it("uses the deepest level when an item appears at multiple BOM levels", () => {
+ const bom = new Map<string, BomChild[]>([
+ [
+ "A",
+ [
+ { itemId: "B", quantity: 1, methodType: "Pull from Inventory" },
+ { itemId: "C", quantity: 1, methodType: "Pull from Inventory" }
+ ]
+ ],
+ ["B", [{ itemId: "C", quantity: 1, methodType: "Pull from Inventory" }]]
+ ]);
+ const llc = computeLowLevelCodes(bom);
+ // C appears at level 1 (child of A) and level 2 (child of B)
+ expect(llc.get("C")).toBe(2);
+ });
+
+ it("handles circular references without infinite loop", () => {
+ const bom = new Map<string, BomChild[]>([
+ ["A", [{ itemId: "B", quantity: 1, methodType: "Pull from Inventory" }]],
+ ["B", [{ itemId: "A", quantity: 1, methodType: "Pull from Inventory" }]]
+ ]);
+ const llc = computeLowLevelCodes(bom);
+ expect(llc.get("A")).toBeDefined();
+ expect(llc.get("B")).toBeDefined();
+ });
+});
+
+// ─── BOM Explosion ──────────────────────────────────────────────────
+
+describe("explodeBom", () => {
+ describe("basic demand propagation", () => {
+ it("propagates demand from a Make item to its Buy children", () => {
+ const grossDemand = new Map([[makeKey(LOC, PER1, M), 1]]);
+ const result = explodeBom(baseInput({ grossDemand }));
+
+ expect(result.bomDerivedDemand.get(makeKey(LOC, PER1, P1))).toBe(2);
+ expect(result.bomDerivedDemand.get(makeKey(LOC, PER1, L1))).toBe(2);
+ });
+
+ it("does not explode BOM for Buy items", () => {
+ const grossDemand = new Map([[makeKey(LOC, PER1, P1), 10]]);
+ const result = explodeBom(baseInput({ grossDemand }));
+ expect(result.bomDerivedDemand.size).toBe(0);
+ });
+
+ it("cascades demand through multiple BOM levels", () => {
+ const grossDemand = new Map([[makeKey(LOC, PER1, M), 1]]);
+ const result = explodeBom(baseInput({ grossDemand }));
+
+ // M→L1 (qty 2) → P2 (qty 2) = 4
+ expect(result.bomDerivedDemand.get(makeKey(LOC, PER1, P2))).toBe(4);
+ });
+ });
+
+ describe("inline production (Make-to-Order + Make)", () => {
+ it("propagates demand through Make-to-Order/Make items to their children", () => {
+ const grossDemand = new Map([[makeKey(LOC, PER1, M), 1]]);
+ const result = explodeBom(baseInput({ grossDemand }));
+
+ // M→L1 (2) → P3 (2) → P4 (2) = 8
+ expect(result.grossDemand.get(makeKey(LOC, PER1, P4))).toBe(8);
+ expect(result.bomDerivedDemand.get(makeKey(LOC, PER1, P4))).toBe(8);
+ });
+
+ it("does not create bomDerivedDemand for the inline production item itself", () => {
+ const grossDemand = new Map([[makeKey(LOC, PER1, M), 1]]);
+ const result = explodeBom(baseInput({ grossDemand }));
+
+ // P3 is Make-to-Order + Make — should be in grossDemand but NOT bomDerivedDemand
+ expect(result.grossDemand.get(makeKey(LOC, PER1, P3))).toBe(4);
+ expect(
+ result.bomDerivedDemand.get(makeKey(LOC, PER1, P3))
+ ).toBeUndefined();
+ });
+ });
+
+ describe("inventory netting", () => {
+ it("reduces net requirement by on-hand inventory", () => {
+ const grossDemand = new Map([[makeKey(LOC, PER1, M), 3]]);
+ const onHand = new Map([[`${LOC}-${M}`, 1]]);
+ const result = explodeBom(
+ baseInput({ grossDemand, onHandByLocationItem: onHand })
+ );
+
+ // netRequirement = 3 - 1 = 2, so children get 2 × childQty
+ expect(result.bomDerivedDemand.get(makeKey(LOC, PER1, P1))).toBe(4);
+ expect(result.bomDerivedDemand.get(makeKey(LOC, PER1, L1))).toBe(4);
+ });
+
+ it("does not explode BOM when on-hand covers all demand", () => {
+ const grossDemand = new Map([[makeKey(LOC, PER1, M), 2]]);
+ const onHand = new Map([[`${LOC}-${M}`, 5]]);
+ const result = explodeBom(
+ baseInput({ grossDemand, onHandByLocationItem: onHand })
+ );
+
+ expect(result.bomDerivedDemand.size).toBe(0);
+ });
+ });
+
+ describe("production supply netting", () => {
+ it("reduces net requirement by production order supply", () => {
+ const key = makeKey(LOC, PER1, M);
+ const grossDemand = new Map([[key, 2]]);
+ const jobSupply = new Map([[key, 1]]);
+ const result = explodeBom(
+ baseInput({
+ grossDemand,
+ jobSupplyByLocationPeriodItem: jobSupply
+ })
+ );
+
+ // netRequirement = 2 - 0 (onHand) - 1 (supply) = 1
+ expect(result.bomDerivedDemand.get(makeKey(LOC, PER1, P1))).toBe(2);
+ expect(result.bomDerivedDemand.get(makeKey(LOC, PER1, L1))).toBe(2);
+ });
+
+ it("does not explode BOM when production supply covers all demand", () => {
+ const key = makeKey(LOC, PER1, M);
+ const grossDemand = new Map([[key, 2]]);
+ const jobSupply = new Map([[key, 2]]);
+ const result = explodeBom(
+ baseInput({
+ grossDemand,
+ jobSupplyByLocationPeriodItem: jobSupply
+ })
+ );
+
+ expect(result.bomDerivedDemand.size).toBe(0);
+ });
+
+ it("prevents double-counting when jobs exist alongside BOM-derived demand", () => {
+ // Sales order creates demand for M, job covers half.
+ // Job materials for P1 and L1 are added separately to grossDemand.
+ // BOM explosion should only cover the uncovered half.
+ const soKey = makeKey(LOC, PER1, M);
+ const jobMaterialP1Key = makeKey(LOC, PER1, P1);
+ const jobMaterialL1Key = makeKey(LOC, PER1, L1);
+
+ const grossDemand = new Map([
+ [soKey, 2], // 2 from sales order
+ [jobMaterialP1Key, 2], // 2 P1 from job (1 M × 2 per BOM)
+ [jobMaterialL1Key, 2] // 2 L1 from job
+ ]);
+ const jobSupply = new Map([[soKey, 1]]); // 1 production order for M
+
+ const result = explodeBom(
+ baseInput({
+ grossDemand,
+ jobSupplyByLocationPeriodItem: jobSupply
+ })
+ );
+
+ // BOM explosion of M: net = 2 - 1 = 1 → P1 += 2, L1 += 2
+ // Total P1 grossDemand = 2 (job) + 2 (BOM) = 4
+ expect(result.grossDemand.get(jobMaterialP1Key)).toBe(4);
+ // bomDerivedDemand only has the BOM-exploded portion
+ expect(result.bomDerivedDemand.get(jobMaterialP1Key)).toBe(2);
+
+ // Total L1 grossDemand = 2 (job) + 2 (BOM) = 4
+ expect(result.grossDemand.get(jobMaterialL1Key)).toBe(4);
+
+ // L1 cascades to children: grossDemand for L1 = 4, no production supply
+ // → P2 = 4 × 2 = 8, P4 = 4 × 2 × 2 = 16
+ expect(result.grossDemand.get(makeKey(LOC, PER1, P4))).toBe(16);
+ });
+ });
+
+ describe("contributor propagation", () => {
+ it("propagates sales order contributors through BOM levels", () => {
+ const soKey = makeKey(LOC, PER1, M);
+ const grossDemand = new Map([[soKey, 1]]);
+ const topLevelContributors = new Map<string, DemandContributor[]>([
+ [
+ soKey,
+ [
+ {
+ sourceType: "Sales Order",
+ salesOrderLineId: "sol1",
+ parentItemId: M,
+ quantity: 1
+ }
+ ]
+ ]
+ ]);
+
+ const result = explodeBom(
+ baseInput({ grossDemand, topLevelContributors })
+ );
+
+ const p1Contributors = result.demandContributors.get(
+ makeKey(LOC, PER1, P1)
+ );
+ expect(p1Contributors).toHaveLength(1);
+ expect(p1Contributors![0]).toMatchObject({
+ sourceType: "Sales Order",
+ salesOrderLineId: "sol1",
+ quantity: 2 // scaled by child.quantity
+ });
+ });
+
+ it("merges BOM-derived and top-level contributors for the same item", () => {
+ // L1 has demand from both BOM explosion (SO) and job materials.
+ // Contributors from both sources should propagate to L1's children.
+ const soKey = makeKey(LOC, PER1, M);
+ const l1Key = makeKey(LOC, PER1, L1);
+
+ const grossDemand = new Map([
+ [soKey, 1],
+ [l1Key, 2] // job material demand
+ ]);
+ const topLevelContributors = new Map<string, DemandContributor[]>([
+ [
+ soKey,
+ [
+ {
+ sourceType: "Sales Order",
+ salesOrderLineId: "sol1",
+ parentItemId: M,
+ quantity: 1
+ }
+ ]
+ ],
+ [
+ l1Key,
+ [
+ {
+ sourceType: "Job Material",
+ jobId: "job1",
+ parentItemId: L1,
+ quantity: 2
+ }
+ ]
+ ]
+ ]);
+
+ const result = explodeBom(
+ baseInput({ grossDemand, topLevelContributors })
+ );
+
+ const p2Contributors = result.demandContributors.get(
+ makeKey(LOC, PER1, P2)
+ );
+ expect(p2Contributors).toBeDefined();
+
+ const sourceTypes = p2Contributors!.map((c) => c.sourceType);
+ expect(sourceTypes).toContain("Sales Order");
+ expect(sourceTypes).toContain("Job Material");
+ });
+
+ it("propagates contributors through inline production items", () => {
+ const soKey = makeKey(LOC, PER1, M);
+ const grossDemand = new Map([[soKey, 1]]);
+ const topLevelContributors = new Map<string, DemandContributor[]>([
+ [
+ soKey,
+ [
+ {
+ sourceType: "Sales Order",
+ salesOrderLineId: "sol1",
+ parentItemId: M,
+ quantity: 1
+ }
+ ]
+ ]
+ ]);
+
+ const result = explodeBom(
+ baseInput({ grossDemand, topLevelContributors })
+ );
+
+ // P4 is behind P3 (inline production). Contributors should still flow.
+ const p4Contributors = result.demandContributors.get(
+ makeKey(LOC, PER1, P4)
+ );
+ expect(p4Contributors).toHaveLength(1);
+ expect(p4Contributors![0]).toMatchObject({
+ sourceType: "Sales Order",
+ salesOrderLineId: "sol1",
+ // 1 (SO) × 2 (M→L1) × 2 (L1→P3) × 2 (P3→P4) = 8
+ quantity: 8
+ });
+ });
+ });
+
+ describe("Buy and Make coercion", () => {
+ it("treats Buy and Make items as Buy for BOM explosion", () => {
+ const replenishment = buildReplenishment();
+ replenishment.set(P1, "Buy and Make");
+
+ const grossDemand = new Map([[makeKey(LOC, PER1, M), 1]]);
+ const result = explodeBom(
+ baseInput({ grossDemand, replenishmentSystemByItem: replenishment })
+ );
+
+ // P1 is Buy and Make → treated as Buy → gets bomDerivedDemand
+ expect(result.bomDerivedDemand.get(makeKey(LOC, PER1, P1))).toBe(2);
+ });
+ });
+});
diff --git a/packages/mrp/src/engine.ts b/packages/mrp/src/engine.ts
new file mode 100644
index 0000000000..52686eee2c
--- /dev/null
+++ b/packages/mrp/src/engine.ts
@@ -0,0 +1,215 @@
+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 DemandPeriod = {
+ id: string;
+ startDate: string;
+ endDate: string;
+};
+
+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: DemandPeriod[];
+ 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/mrp/src/index.ts b/packages/mrp/src/index.ts
new file mode 100644
index 0000000000..a5810b8c2c
--- /dev/null
+++ b/packages/mrp/src/index.ts
@@ -0,0 +1,15 @@
+export type {
+ BomChild,
+ BomExplosionInput,
+ BomExplosionOutput,
+ DemandContributor,
+ DemandPeriod,
+ MethodType,
+ ReplenishmentSystem
+} from "./engine";
+export {
+ computeLowLevelCodes,
+ explodeBom,
+ makeKey,
+ splitKey
+} from "./engine";
diff --git a/packages/mrp/tsconfig.json b/packages/mrp/tsconfig.json
new file mode 100644
index 0000000000..ac4c7690df
--- /dev/null
+++ b/packages/mrp/tsconfig.json
@@ -0,0 +1,8 @@
+{
+ "extends": "@carbon/config/tsconfig/base.json",
+ "include": ["src"],
+ "exclude": ["node_modules"],
+ "compilerOptions": {
+ "types": ["node"]
+ }
+}
diff --git a/packages/mrp/vitest.config.ts b/packages/mrp/vitest.config.ts
new file mode 100644
index 0000000000..af7eaf6762
--- /dev/null
+++ b/packages/mrp/vitest.config.ts
@@ -0,0 +1,10 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ globals: false,
+ environment: "node",
+ passWithNoTests: true,
+ include: ["src/**/*.test.ts"],
+ },
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 0e62be9b3b..8cc46bfb93 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -288,7 +288,7 @@ importers:
version: 1.40.0
'@react-router/remix-routes-option-adapter':
specifier: 'catalog:'
cookie:
specifier: 'catalog:'
version: 1.1.1
@@ -325,7 +325,7 @@ importers:
'@react-router/dev':
specifier: 'catalog:'
'@types/aws-lambda':
specifier: 8.10.152
version: 8.10.152
@@ -370,7 +370,7 @@ importers:
version: 5.8.3
vite-plugin-babel-macros:
specifier: 'catalog:'
optionalDependencies:
'@rollup/rollup-linux-x64-gnu':
specifier: 4.60.1
@@ -645,7 +645,7 @@ importers:
version: 3.4.5([email protected])
'@react-router/remix-routes-option-adapter':
specifier: 'catalog:'
'@react-router/serve':
specifier: 'catalog:'
@@ -690,7 +690,7 @@ importers:
'@vercel/react-router':
specifier: 'catalog:'
'@visx/responsive':
specifier: 2.17.0
version: 2.17.0([email protected])
@@ -916,16 +916,16 @@ importers:
'@lingui/vite-plugin':
specifier: 'catalog:'
'@react-router/dev':
specifier: 'catalog:'
'@tailwindcss/typography':
specifier: 'catalog:'
version: 0.5.19([email protected])
'@tailwindcss/vite':
specifier: 'catalog:'
'@types/d3':
specifier: 7.4.3
version: 7.4.3
@@ -982,13 +982,13 @@ importers:
version: 5.8.3
vite:
specifier: 'catalog:'
vite-plugin-babel-macros:
specifier: 'catalog:'
vitest:
specifier: 'catalog:'
apps/mes:
dependencies:
@@ -2372,6 +2372,18 @@ importers:
specifier: 'catalog:'
+ packages/mrp:
+ devDependencies:
+ '@carbon/config':
+ specifier: workspace:*
+ version: link:../config
+ typescript:
+ specifier: 'catalog:'
+ version: 5.8.3
+ vitest:
+ specifier: 'catalog:'
+
packages/notifications:
devDependencies:
'@carbon/config':
@@ -12087,11 +12099,6 @@ packages:
resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==}
hasBin: true
- resolution: {integrity: sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==}
- engines: {node: '>=10'}
- hasBin: true
-
resolution: {integrity: sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==}
engines: {node: '>=10'}
@@ -14601,16 +14608,6 @@ snapshots:
'@lingui/babel-plugin-lingui-macro': 5.9.4([email protected])([email protected])
babel-plugin-macros: 3.1.0
- dependencies:
- '@lingui/cli': 5.9.4([email protected])([email protected])
- '@lingui/conf': 5.9.4([email protected])
- transitivePeerDependencies:
- - babel-plugin-macros
- - supports-color
- - typescript
-
dependencies:
'@lingui/cli': 5.9.4([email protected])([email protected])
@@ -18703,13 +18700,6 @@ snapshots:
postcss-selector-parser: 6.0.10
tailwindcss: 4.3.0
- dependencies:
- '@tailwindcss/node': 4.3.0
- '@tailwindcss/oxide': 4.3.0
- tailwindcss: 4.3.0
-
dependencies:
'@tailwindcss/node': 4.3.0
@@ -19505,16 +19495,6 @@ snapshots:
'@vercel/[email protected]': {}
- dependencies:
- '@vercel/static-config': 3.2.0
- isbot: 5.1.37
- react: 18.3.1
- react-dom: 18.3.1([email protected])
- ts-morph: 12.0.0
-
dependencies:
@@ -19645,14 +19625,6 @@ snapshots:
optionalDependencies:
- dependencies:
- '@vitest/spy': 4.1.6
- estree-walker: 3.0.3
- magic-string: 0.30.21
- optionalDependencies:
-
dependencies:
'@vitest/spy': 4.1.6
@@ -24081,9 +24053,6 @@ snapshots:
- optional: true
-
@@ -24170,7 +24139,7 @@ snapshots:
dependencies:
'@img/colour': 1.1.0
detect-libc: 2.1.2
- semver: 7.7.3
+ semver: 7.7.4
optionalDependencies:
'@img/sharp-darwin-arm64': 0.34.5
'@img/sharp-darwin-x64': 0.34.5
@@ -25218,34 +25187,6 @@ snapshots:
transitivePeerDependencies:
- msw
- dependencies:
- '@vitest/expect': 4.1.6
- '@vitest/pretty-format': 4.1.6
- '@vitest/runner': 4.1.6
- '@vitest/snapshot': 4.1.6
- '@vitest/spy': 4.1.6
- '@vitest/utils': 4.1.6
- es-module-lexer: 2.0.0
- expect-type: 1.3.0
- magic-string: 0.30.21
- obug: 2.1.1
- pathe: 2.0.3
- picomatch: 4.0.4
- std-env: 4.0.0
- tinybench: 2.9.0
- tinyexec: 1.1.1
- tinyglobby: 0.2.16
- tinyrainbow: 3.1.0
- why-is-node-running: 2.3.0
- optionalDependencies:
- '@opentelemetry/api': 1.9.0
- '@types/node': 24.12.2
- transitivePeerDependencies:
- - msw
-
dependencies:
'@vitest/expect': 4.1.6
diff --git a/scripts/pr-complexity/index.ts b/scripts/pr-complexity/index.ts
new file mode 100644
index 0000000000..9b84f881ea
--- /dev/null
+++ b/scripts/pr-complexity/index.ts
@@ -0,0 +1,209 @@
+import { Octokit } from "octokit";
+
+const OWNER = requireEnv("OWNER");
+const REPO = requireEnv("REPO");
+const PR_NUMBER = Number(requireEnv("PR_NUMBER"));
+const PR_AUTHOR = requireEnv("PR_AUTHOR");
+const GITHUB_TOKEN = requireEnv("GITHUB_TOKEN");
+
+const COMPLEXITY_LABELS = [
+ {
+ name: "complexity: low",
+ color: "0e8a16",
+ description: "Low-complexity PR",
+ },
+ {
+ name: "complexity: medium",
+ color: "fbca04",
+ description: "Medium-complexity PR",
+ },
+ {
+ name: "complexity: high",
+ color: "e4691a",
+ description: "High-complexity PR",
+ },
+ {
+ name: "complexity: critical",
+ color: "b60205",
+ description: "Critical-complexity PR",
+ },
+];
+
+const FILE_SCORE_WEIGHT = 2;
+const FILE_SCORE_CAP = 30;
+const LINE_SCORE_BUCKET_SIZE = 50;
+const LINE_SCORE_WEIGHT = 3;
+const LINE_SCORE_BUCKET_CAP = 20;
+const EXPERIENCE_DISCOUNT_CAP = 20;
+const TEST_COVERAGE_BONUS = 10;
+
+const octokit = new Octokit({ auth: GITHUB_TOKEN });
+
+type PullFile = {
+ filename: string;
+ additions: number;
+ deletions: number;
+ changes: number;
+};
+
+async function main() {
+ if (!Number.isInteger(PR_NUMBER) || PR_NUMBER < 1) {
+ throw new Error("PR_NUMBER must be a positive integer");
+ }
+
+ const files = await listPullFiles();
+ const fileCount = files.length;
+ const linesChanged = files.reduce((sum, file) => sum + file.changes, 0);
+ const hasTests = files.some((file) => isTestFile(file.filename));
+ const authorMergedPRCount = await getAuthorMergedPRCount();
+
+ const fileScore = Math.min(fileCount, FILE_SCORE_CAP) * FILE_SCORE_WEIGHT;
+ const lineScore =
+ Math.min(
+ Math.floor(linesChanged / LINE_SCORE_BUCKET_SIZE),
+ LINE_SCORE_BUCKET_CAP
+ ) * LINE_SCORE_WEIGHT;
+ const experienceDiscount = Math.min(
+ authorMergedPRCount,
+ EXPERIENCE_DISCOUNT_CAP
+ );
+ const testBonus = hasTests ? TEST_COVERAGE_BONUS : 0;
+ const score = fileScore + lineScore - experienceDiscount - testBonus;
+ const label = labelForScore(score);
+
+ await ensureComplexityLabels();
+ await replaceComplexityLabel(label.name);
+
+ console.log(`Applied ${label.name} to #${PR_NUMBER} (score: ${score})`);
+ console.log(
+ ` files: ${fileCount} (+${fileScore}), lines: ${linesChanged} (+${lineScore})`
+ );
+ console.log(
+ ` experience: ${authorMergedPRCount} (-${experienceDiscount}), tests: ${hasTests} (-${testBonus})`
+ );
+}
+
+async function listPullFiles(): Promise<PullFile[]> {
+ return octokit.paginate(octokit.rest.pulls.listFiles, {
+ owner: OWNER,
+ repo: REPO,
+ pull_number: PR_NUMBER,
+ per_page: 100,
+ });
+}
+
+async function getAuthorMergedPRCount(): Promise<number> {
+ const query = `repo:${OWNER}/${REPO} is:pr is:merged author:${PR_AUTHOR}`;
+ const { data } = await octokit.rest.search.issuesAndPullRequests({
+ q: query,
+ per_page: 1,
+ });
+ return data.total_count;
+}
+
+async function ensureComplexityLabels() {
+ await Promise.all(
+ COMPLEXITY_LABELS.map((l) => ensureLabel(l.name, l.color, l.description))
+ );
+}
+
+async function ensureLabel(name: string, color: string, description: string) {
+ try {
+ await octokit.rest.issues.createLabel({
+ owner: OWNER,
+ repo: REPO,
+ name,
+ color,
+ description,
+ });
+ } catch (error) {
+ if (isOctokitError(error, 422)) {
+ await octokit.rest.issues.updateLabel({
+ owner: OWNER,
+ repo: REPO,
+ name,
+ color,
+ description,
+ });
+ return;
+ }
+ throw error;
+ }
+}
+
+async function replaceComplexityLabel(nextLabel: string) {
+ const { data: issue } = await octokit.rest.issues.get({
+ owner: OWNER,
+ repo: REPO,
+ issue_number: PR_NUMBER,
+ });
+ const labels = issue.labels
+ .map((label) => (typeof label === "string" ? label : label.name))
+ .filter((name): name is string => Boolean(name));
+
+ await Promise.all(
+ labels
+ .filter((label) => label.startsWith("complexity:") && label !== nextLabel)
+ .map((label) => removeLabelIfPresent(label))
+ );
+
+ if (!labels.includes(nextLabel)) {
+ await octokit.rest.issues.addLabels({
+ owner: OWNER,
+ repo: REPO,
+ issue_number: PR_NUMBER,
+ labels: [nextLabel],
+ });
+ }
+}
+
+async function removeLabelIfPresent(label: string) {
+ try {
+ await octokit.rest.issues.removeLabel({
+ owner: OWNER,
+ repo: REPO,
+ issue_number: PR_NUMBER,
+ name: label,
+ });
+ } catch (error) {
+ if (!isOctokitError(error, 404)) {
+ throw error;
+ }
+ }
+}
+
+function labelForScore(score: number) {
+ if (score < 15) return COMPLEXITY_LABELS[0];
+ if (score < 35) return COMPLEXITY_LABELS[1];
+ if (score < 60) return COMPLEXITY_LABELS[2];
+ return COMPLEXITY_LABELS[3];
+}
+
+function isTestFile(filename: string): boolean {
+ return (
+ /(^|\/)(test|tests|__tests__)\//.test(filename) ||
+ /\.(test|spec)\.(ts|tsx|js|jsx|mjs|cjs)$/.test(filename)
+ );
+}
+
+function requireEnv(name: string): string {
+ const value = process.env[name];
+ if (!value) {
+ throw new Error(`${name} is required`);
+ }
+ return value;
+}
+
+function isOctokitError(error: unknown, status: number): boolean {
+ return (
+ typeof error === "object" &&
+ error !== null &&
+ "status" in error &&
+ error.status === status
+ );
+}
+
+main().catch((error) => {
+ console.error(error);
+ process.exit(1);
+});
diff --git a/scripts/pr-complexity/package.json b/scripts/pr-complexity/package.json
new file mode 100644
index 0000000000..6ceb215caf
--- /dev/null
+++ b/scripts/pr-complexity/package.json
@@ -0,0 +1,14 @@
+{
+ "name": "pr-complexity",
+ "version": "1.0.0",
+ "private": true,
+ "type": "module",
+ "dependencies": {
+ "octokit": "^5.0.5"
+ },
+ "devDependencies": {
+ "@types/node": "^22.0.0",
+ "tsx": "^4.21.0",
+ "typescript": "^5.9.0"
+ }
+}
diff --git a/turbo.json b/turbo.json
index 148ee7a329..88a3a47652 100644
--- a/turbo.json
+++ b/turbo.json
@@ -25,7 +25,7 @@
},
"test": {
"cache": false,
- "dependsOn": []
+ "dependsOn": ["^build"]
},
"typecheck": {
"cache": false,