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.

refactor: use demand projections table for storing projections

Brad Barbinb9daa714ba89
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.ts
index cbe54e3d42..4a2f732a2c 100644
--- a/apps/erp/app/modules/production/production.models.ts
+++ b/apps/erp/app/modules/production/production.models.ts
@@ -842,7 +842,7 @@ export const scrapReasonValidator = z.object({
name: z.string().min(1, { message: "Name is required" }),
});
-export const demandForecastsValidator = z.object({
+export const demandProjectionValidator = z.object({
itemId: z.string().min(1, { message: "Item is required" }),
locationId: z.string().min(1, { message: "Location is required" }),
periods: z.array(z.string()).optional(),
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 1898c2cc9d..ac09dc17bb 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -288,6 +288,56 @@ export async function convertSalesOrderLinesToJobs(
return salesOrder;
}
+export async function deleteDemandForecasts(
+ client: SupabaseClient<Database>,
+ params: {
+ itemId: string;
+ locationId: string;
+ companyId: string;
+ futurePeriodIds: string[];
+ }
+) {
+ const { itemId, locationId, companyId, futurePeriodIds } = params;
+
+ const result = await client
+ .from("demandForecast")
+ .delete()
+ .eq("itemId", itemId)
+ .eq("locationId", locationId)
+ .eq("companyId", companyId)
+ .in("periodId", futurePeriodIds);
+
+ return {
+ data: result.data,
+ error: result.error,
+ };
+}
+
+export async function deleteDemandProjections(
+ client: SupabaseClient<Database>,
+ params: {
+ itemId: string;
+ locationId: string;
+ companyId: string;
+ futurePeriodIds: string[];
+ }
+) {
+ const { itemId, locationId, companyId, futurePeriodIds } = params;
+
+ const result = await client
+ .from("demandProjection")
+ .delete()
+ .eq("itemId", itemId)
+ .eq("locationId", locationId)
+ .eq("companyId", companyId)
+ .in("periodId", futurePeriodIds);
+
+ return {
+ data: result.data,
+ error: result.error,
+ };
+}
+
export async function deleteJob(
client: SupabaseClient<Database>,
jobId: string
@@ -447,6 +497,42 @@ export async function deleteScrapReason(
return client.from("scrapReason").delete().eq("id", scrapReasonId);
}
+export async function getDemandForecasts(
+ client: SupabaseClient<Database>,
+ params: {
+ itemId: string;
+ locationId: string;
+ companyId: string;
+ periodIds: string[];
+ }
+) {
+ return client
+ .from("demandForecast")
+ .select("*")
+ .eq("itemId", params.itemId)
+ .eq("locationId", params.locationId)
+ .eq("companyId", params.companyId)
+ .in("periodId", params.periodIds);
+}
+
+export async function getDemandProjections(
+ client: SupabaseClient<Database>,
+ params: {
+ itemId: string;
+ locationId: string;
+ companyId: string;
+ periodIds: string[];
+ }
+) {
+ return client
+ .from("demandProjection")
+ .select("*")
+ .eq("itemId", params.itemId)
+ .eq("locationId", params.locationId)
+ .eq("companyId", params.companyId)
+ .in("periodId", params.periodIds);
+}
+
export async function getJobDocuments(
client: SupabaseClient<Database>,
companyId: string,
@@ -2124,24 +2210,6 @@ export async function upsertScrapReason(
}
}
-export async function getDemandForecasts(
- client: SupabaseClient<Database>,
- params: {
- itemId: string;
- locationId: string;
- companyId: string;
- periodIds: string[];
- }
-) {
- return client
- .from("demandForecast")
- .select("*")
- .eq("itemId", params.itemId)
- .eq("locationId", params.locationId)
- .eq("companyId", params.companyId)
- .in("periodId", params.periodIds);
-}
-
export async function upsertDemandForecasts(
client: SupabaseClient<Database>,
forecasts: Array<{
@@ -2198,27 +2266,58 @@ export async function upsertDemandForecasts(
};
}
-export async function deleteFutureDemandForecasts(
+export async function upsertDemandProjections(
client: SupabaseClient<Database>,
- params: {
+ forecasts: Array<{
itemId: string;
locationId: string;
+ periodId: string;
+ forecastQuantity: number;
companyId: string;
- futurePeriodIds: string[];
- }
+ createdBy: string;
+ updatedBy?: string;
+ }>
) {
- const { itemId, locationId, companyId, futurePeriodIds } = params;
+ // Delete existing forecasts with 0 quantity, upsert others
+ const toDelete = forecasts.filter((f) => f.forecastQuantity === 0);
+ const toUpsert = forecasts.filter((f) => f.forecastQuantity > 0);
- const result = await client
- .from("demandForecast")
- .delete()
- .eq("itemId", itemId)
- .eq("locationId", locationId)
- .eq("companyId", companyId)
- .in("periodId", futurePeriodIds);
+ const promises = [];
+
+ if (toDelete.length > 0) {
+ for (const forecast of toDelete) {
+ promises.push(
+ client
+ .from("demandProjection")
+ .delete()
+ .eq("itemId", forecast.itemId)
+ .eq("locationId", forecast.locationId)
+ .eq("periodId", forecast.periodId)
+ .eq("companyId", forecast.companyId)
+ );
+ }
+ }
+
+ if (toUpsert.length > 0) {
+ promises.push(
+ client.from("demandProjection").upsert(
+ toUpsert.map((f) => ({
+ ...f,
+ updatedBy: f.updatedBy ?? f.createdBy ?? "system",
+ updatedAt: new Date().toISOString(),
+ })),
+ {
+ onConflict: "itemId,locationId,periodId,companyId",
+ }
+ )
+ );
+ }
+
+ const results = await Promise.all(promises);
+ const hasError = results.some((r) => r.error);
return {
- data: result.data,
- error: result.error,
+ data: hasError ? null : toUpsert,
+ error: hasError ? results.find((r) => r.error)?.error : null,
};
}
diff --git a/apps/erp/app/modules/production/types.ts b/apps/erp/app/modules/production/types.ts
index 2341634ffd..a0330fd2b8 100644
--- a/apps/erp/app/modules/production/types.ts
+++ b/apps/erp/app/modules/production/types.ts
@@ -21,7 +21,7 @@ export type ActiveProductionEvent = NonNullable<
Awaited<ReturnType<typeof getActiveProductionEvents>>["data"]
>[number];
-export type DemandForecast = NonNullable<
+export type DemandProjection = NonNullable<
Awaited<ReturnType<typeof getProductionProjections>>["data"]
>[number];
diff --git a/apps/erp/app/modules/production/ui/Forecast/index.ts b/apps/erp/app/modules/production/ui/Forecast/index.ts
deleted file mode 100644
index c9207cc359..0000000000
--- a/apps/erp/app/modules/production/ui/Forecast/index.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-import DemandForecastForm from "./DemandForecastForm";
-import DemandForecastTable from "./DemandForecastTable";
-
-export { DemandForecastForm, DemandForecastTable };
diff --git a/apps/erp/app/modules/production/ui/Forecast/DemandForecastForm.tsx b/apps/erp/app/modules/production/ui/Projection/DemandProjectionForm.tsx
similarity index 87%
rename from apps/erp/app/modules/production/ui/Forecast/DemandForecastForm.tsx
rename to apps/erp/app/modules/production/ui/Projection/DemandProjectionForm.tsx
index 3307940412..6d62fc2877 100644
--- a/apps/erp/app/modules/production/ui/Forecast/DemandForecastForm.tsx
+++ b/apps/erp/app/modules/production/ui/Projection/DemandProjectionForm.tsx
@@ -16,24 +16,24 @@ import type { z } from "zod";
import { Hidden, Item, Location, Number, Submit } from "~/components/Form";
import { usePermissions } from "~/hooks";
import { path } from "~/utils/path";
-import { demandForecastsValidator } from "../../production.models";
+import { demandProjectionValidator } from "../../production.models";
type LoaderData = {
periods?: Array<{ id: string; name: string }>;
- initialValues?: z.infer<typeof demandForecastsValidator>;
+ initialValues?: z.infer<typeof demandProjectionValidator>;
};
-type DemandForecastsFormProps = {
- initialValues?: z.infer<typeof demandForecastsValidator>;
+type DemandProjectionsFormProps = {
+ initialValues?: z.infer<typeof demandProjectionValidator>;
isEditing?: boolean;
onClose: () => void;
};
-const DemandForecastsForm = ({
+const DemandProjectionsForm = ({
initialValues: propInitialValues,
isEditing = false,
onClose,
-}: DemandForecastsFormProps) => {
+}: DemandProjectionsFormProps) => {
const permissions = usePermissions();
const fetcher = useFetcher<{ id: string }>();
const loaderData = useLoaderData<LoaderData>();
@@ -67,15 +67,15 @@ const DemandForecastsForm = ({
>
<DrawerContent>
<ValidatedForm
- validator={demandForecastsValidator}
+ validator={demandProjectionValidator}
method="post"
action={
isEditing
- ? path.to.demandForecast(
+ ? path.to.demandProjection(
initialValues.itemId!,
initialValues.locationId!
)
- : path.to.newDemandForecast
+ : path.to.newDemandProjection
}
defaultValues={initialValues}
fetcher={fetcher}
@@ -86,7 +86,7 @@ const DemandForecastsForm = ({
{isEditing ? "Edit" : "New"} Production Projection
</CardTitle>
<CardDescription>
- Set demand forecast values for each week
+ Set demand projection values for each week
</CardDescription>
</DrawerHeader>
<DrawerBody>
@@ -141,4 +141,4 @@ const DemandForecastsForm = ({
);
};
-export default DemandForecastsForm;
+export default DemandProjectionsForm;
diff --git a/apps/erp/app/modules/production/ui/Forecast/DemandForecastTable.tsx b/apps/erp/app/modules/production/ui/Projection/DemandProjectionTable.tsx
similarity index 83%
rename from apps/erp/app/modules/production/ui/Forecast/DemandForecastTable.tsx
rename to apps/erp/app/modules/production/ui/Projection/DemandProjectionTable.tsx
index 34e40623e8..9ac70fd5d5 100644
--- a/apps/erp/app/modules/production/ui/Forecast/DemandForecastTable.tsx
+++ b/apps/erp/app/modules/production/ui/Projection/DemandProjectionTable.tsx
@@ -28,10 +28,10 @@ import ItemThumbnail from "~/components/ItemThumbnail";
import { ConfirmDelete } from "~/components/Modals";
import { usePermissions } from "~/hooks";
import { path } from "~/utils/path";
-import type { DemandForecast } from "../../types";
+import type { DemandProjection } from "../../types";
-type DemandForecastsTableProps = {
- data: DemandForecast[];
+type DemandProjectionsTableProps = {
+ data: DemandProjection[];
count: number;
locationId: string;
periods: { id: string; startDate: string; endDate: string }[];
@@ -42,8 +42,8 @@ const defaultColumnPinning = {
right: ["actions"],
};
-const DemandForecastsTable = memo(
- ({ data, count, locationId, periods }: DemandForecastsTableProps) => {
+const DemandProjectionsTable = memo(
+ ({ data, count, locationId, periods }: DemandProjectionsTableProps) => {
const numberFormatter = useNumberFormatter();
const dateFormatter = useDateFormatter({
month: "short",
@@ -52,16 +52,16 @@ const DemandForecastsTable = memo(
const [params] = useUrlParams();
const permissions = usePermissions();
const locations = useLocations();
- const [selectedItem, setSelectedItem] = useState<DemandForecast | null>(
+ const [selectedItem, setSelectedItem] = useState<DemandProjection | null>(
null
);
- const columns = useMemo<ColumnDef<DemandForecast>[]>(() => {
- const periodColumns: ColumnDef<DemandForecast>[] = periods.map(
+ const columns = useMemo<ColumnDef<DemandProjection>[]>(() => {
+ const periodColumns: ColumnDef<DemandProjection>[] = periods.map(
(period, index) => {
const isCurrentWeek = index === 0;
const weekNumber = index + 1;
- const weekKey = `week${weekNumber}` as keyof DemandForecast;
+ const weekKey = `week${weekNumber}` as keyof DemandProjection;
const startDate = parseDate(period.startDate).toDate(
getLocalTimeZone()
);
@@ -96,7 +96,7 @@ const DemandForecastsTable = memo(
header: "Part ID",
cell: ({ row }) => (
<Hyperlink
- to={path.to.demandForecast(row.original.id!, locationId)}
+ to={path.to.demandProjection(row.original.id!, locationId)}
>
<HStack className="py-1 cursor-pointer">
<ItemThumbnail
@@ -140,7 +140,7 @@ const DemandForecastsTable = memo(
<DropdownMenuContent align="end">
<DropdownMenuItem asChild>
<Link
- to={path.to.demandForecast(
+ to={path.to.demandProjection(
row.original.id!,
locationId
)}
@@ -167,12 +167,12 @@ const DemandForecastsTable = memo(
return (
<>
- <Table<DemandForecast>
+ <Table<DemandProjection>
data={data}
columns={columns}
count={count}
defaultColumnPinning={defaultColumnPinning}
- title="Demand Forecasts"
+ title="Demand Projections"
table="production-planning"
withSavedView
withSelectableRows
@@ -198,9 +198,12 @@ const DemandForecastsTable = memo(
{selectedItem && (
<ConfirmDelete
- action={path.to.deleteDemandForecasts(selectedItem.id!, locationId)}
- name={`${selectedItem.readableIdWithRevision} forecasts`}
- text={`Are you sure you want to delete all forecasts for ${selectedItem.readableIdWithRevision}? This action cannot be undone.`}
+ action={path.to.deleteDemandProjections(
+ selectedItem.id!,
+ locationId
+ )}
+ name={`${selectedItem.readableIdWithRevision} projections`}
+ text={`Are you sure you want to delete all projections for ${selectedItem.readableIdWithRevision}? This action cannot be undone.`}
onCancel={() => setSelectedItem(null)}
onSubmit={() => setSelectedItem(null)}
/>
@@ -210,9 +213,9 @@ const DemandForecastsTable = memo(
}
);
-DemandForecastsTable.displayName = "DemandForecastsTable";
-export default DemandForecastsTable;
+DemandProjectionsTable.displayName = "DemandProjectionsTable";
+export default DemandProjectionsTable;
function getLocationPath(locationId: string) {
- return `${path.to.demandForecasts}?location=${locationId}`;
+ return `${path.to.demandProjections}?location=${locationId}`;
}
diff --git a/apps/erp/app/modules/production/ui/Projection/index.ts b/apps/erp/app/modules/production/ui/Projection/index.ts
new file mode 100644
index 0000000000..d26013adc3
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Projection/index.ts
@@ -0,0 +1,4 @@
+import DemandProjectionForm from "./DemandProjectionForm";
+import DemandProjectionTable from "./DemandProjectionTable";
+
+export { DemandProjectionForm, DemandProjectionTable };
diff --git a/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx b/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx
index 8a2cd60ec5..ab83833450 100644
--- a/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx
+++ b/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx
@@ -26,19 +26,18 @@ const productionRoutes: AuthenticatedRouteGroup[] = [
{
name: "Plan",
routes: [
- {
- name: "Forecasts",
- to: path.to.demandForecasts,
- icon: <LuChartLine />,
- table: "demand-forecast",
- },
{
name: "Planning",
to: path.to.productionPlanning,
icon: <LuSquareChartGantt />,
table: "production-planning",
},
-
+ {
+ name: "Projections",
+ to: path.to.demandProjections,
+ icon: <LuChartLine />,
+ table: "demand-projection",
+ },
{
name: "Schedule",
to: path.to.schedule,
diff --git a/apps/erp/app/routes/x+/production+/forecasts.delete.$itemId.locationId.tsx b/apps/erp/app/routes/x+/production+/forecasts.delete.$itemId.locationId.tsx
deleted file mode 100644
index 79ed70bc1e..0000000000
--- a/apps/erp/app/routes/x+/production+/forecasts.delete.$itemId.locationId.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-import { assertIsPost, error, success } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import { getLocalTimeZone, startOfWeek, today } from "@internationalized/date";
-import type { ActionFunctionArgs } from "@vercel/remix";
-import { json, redirect } from "@vercel/remix";
-import { deleteFutureDemandForecasts } from "~/modules/production/production.service";
-import { getPeriods } from "~/modules/shared/shared.service";
-import { path } from "~/utils/path";
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client, companyId } = await requirePermissions(request, {
- delete: "production",
- });
-
- const { itemId, locationId } = params;
- if (!itemId || !locationId) {
- throw new Error("Item ID and Location ID are required");
- }
-
- // Get current date to determine future periods
- const startDate = startOfWeek(today(getLocalTimeZone()), "en-US");
- const endDate = startDate.add({ weeks: 52 });
- const periods = await getPeriods(client, {
- startDate: startDate.toString(),
- endDate: endDate.toString(),
- });
-
- if (periods.error) {
- return json(
- {},
- await flash(request, error(periods.error, "Failed to load periods"))
- );
- }
-
- // Only delete forecasts for future periods (current week and beyond)
- const futurePeriodIds = periods.data?.map((p) => p.id) ?? [];
-
- const deleteDemand = await deleteFutureDemandForecasts(client, {
- itemId,
- locationId,
- companyId,
- futurePeriodIds,
- });
-
- if (deleteDemand.error) {
- return json(
- {
- success: false,
- },
- await flash(
- request,
- error(deleteDemand.error, "Failed to delete demand forecasts")
- )
- );
- }
-
- return redirect(
- path.to.demandForecasts + `?location=${locationId}`,
- await flash(request, success("Demand forecasts deleted successfully"))
- );
-}
diff --git a/apps/erp/app/routes/x+/production+/forecasts.$itemId.$locationId.tsx b/apps/erp/app/routes/x+/production+/projections.$itemId.$locationId.tsx
similarity index 83%
rename from apps/erp/app/routes/x+/production+/forecasts.$itemId.$locationId.tsx
rename to apps/erp/app/routes/x+/production+/projections.$itemId.$locationId.tsx
index 322dfc3fa5..fbaa5094e8 100644
--- a/apps/erp/app/routes/x+/production+/forecasts.$itemId.$locationId.tsx
+++ b/apps/erp/app/routes/x+/production+/projections.$itemId.$locationId.tsx
@@ -6,12 +6,12 @@ import { getLocalTimeZone, startOfWeek, today } from "@internationalized/date";
import { useLoaderData, useNavigate } from "@remix-run/react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
-import { demandForecastsValidator } from "~/modules/production/production.models";
+import { demandProjectionValidator } from "~/modules/production/production.models";
import {
- getDemandForecasts,
- upsertDemandForecasts,
+ getDemandProjections,
+ upsertDemandProjections,
} from "~/modules/production/production.service";
-import DemandForecastsForm from "~/modules/production/ui/Forecast/DemandForecastForm";
+import DemandProjectionsForm from "~/modules/production/ui/Projection/DemandProjectionForm";
import { getPeriods } from "~/modules/shared/shared.service";
import { path } from "~/utils/path";
@@ -40,7 +40,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
// Load existing demand forecasts for this item and location
- const existingForecasts = await getDemandForecasts(client, {
+ const existingProjections = await getDemandProjections(client, {
itemId,
locationId,
companyId,
@@ -49,9 +49,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
// Map existing forecasts to week fields
const weekValues: Record<string, number> = {};
- if (existingForecasts.data && periods.data) {
+ if (existingProjections.data && periods.data) {
periods.data.forEach((period, index) => {
- const forecast = existingForecasts.data?.find(
+ const forecast = existingProjections.data?.find(
(f) => f.periodId === period.id
);
weekValues[`week${index}`] = forecast?.forecastQuantity ?? 0;
@@ -83,7 +83,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
const formData = await request.formData();
- const validation = await validator(demandForecastsValidator).validate(
+ const validation = await validator(demandProjectionValidator).validate(
formData
);
@@ -94,7 +94,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { periods, ...weekData } = validation.data;
// Extract week values and create/update demand forecast records
- const demandForecasts = [];
+ const demandProjections = [];
for (let i = 0; i < 52; i++) {
const weekKey = `week${i}` as keyof typeof weekData;
@@ -102,7 +102,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (periods?.[i]) {
// Include all periods, even with 0 quantity (to handle deletions)
- demandForecasts.push({
+ demandProjections.push({
itemId: routeItemId,
locationId: routeLocationId,
periodId: periods[i],
@@ -114,7 +114,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
}
- const result = await upsertDemandForecasts(client, demandForecasts);
+ const result = await upsertDemandProjections(client, demandProjections);
if (result.error) {
return json(
@@ -127,7 +127,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
return redirect(
- path.to.demandForecasts + `?location=${routeLocationId}`,
+ path.to.demandProjections + `?location=${routeLocationId}`,
await flash(request, success("Demand forecasts updated successfully"))
);
}
@@ -138,7 +138,7 @@ export default function EditProjectionRoute() {
const navigate = useNavigate();
return (
- <DemandForecastsForm
+ <DemandProjectionsForm
initialValues={initialValues}
isEditing
onClose={() => navigate(-1)}
diff --git a/apps/erp/app/routes/x+/production+/forecasts.delete.$itemId.$locationId.tsx b/apps/erp/app/routes/x+/production+/projections.delete.$itemId.$locationId.tsx
similarity index 79%
rename from apps/erp/app/routes/x+/production+/forecasts.delete.$itemId.$locationId.tsx
rename to apps/erp/app/routes/x+/production+/projections.delete.$itemId.$locationId.tsx
index 40cafcbfd2..ddfcaef44c 100644
--- a/apps/erp/app/routes/x+/production+/forecasts.delete.$itemId.$locationId.tsx
+++ b/apps/erp/app/routes/x+/production+/projections.delete.$itemId.$locationId.tsx
@@ -4,7 +4,7 @@ import { flash } from "@carbon/auth/session.server";
import { getLocalTimeZone, startOfWeek, today } from "@internationalized/date";
import type { ActionFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
-import { deleteFutureDemandForecasts } from "~/modules/production/production.service";
+import { deleteDemandProjections } from "~/modules/production/production.service";
import { getPeriods } from "~/modules/shared/shared.service";
import { path } from "~/utils/path";
@@ -41,10 +41,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- // Only delete forecasts for future periods (current week and beyond)
+ // Only delete projections for future periods (current week and beyond)
const futurePeriodIds = periods.data?.map((p) => p.id) ?? [];
- const result = await deleteFutureDemandForecasts(client, {
+ const result = await deleteDemandProjections(client, {
itemId,
locationId,
companyId,
@@ -56,13 +56,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
{},
await flash(
request,
- error("Failed to delete demand forecasts", "Delete failed")
+ error("Failed to delete demand projections", "Delete failed")
)
);
}
return redirect(
- path.to.demandForecasts + `?location=${locationId}`,
- await flash(request, success("Demand forecasts deleted successfully"))
+ path.to.demandProjections + `?location=${locationId}`,
+ await flash(request, success("Demand projections deleted successfully"))
);
}
diff --git a/apps/erp/app/routes/x+/production+/forecasts.new.tsx b/apps/erp/app/routes/x+/production+/projections.new.tsx
similarity index 82%
rename from apps/erp/app/routes/x+/production+/forecasts.new.tsx
rename to apps/erp/app/routes/x+/production+/projections.new.tsx
index 153387165b..2b9322e4ec 100644
--- a/apps/erp/app/routes/x+/production+/forecasts.new.tsx
+++ b/apps/erp/app/routes/x+/production+/projections.new.tsx
@@ -7,9 +7,9 @@ import { getLocalTimeZone, startOfWeek, today } from "@internationalized/date";
import { useNavigate } from "@remix-run/react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
-import { demandForecastsValidator } from "~/modules/production/production.models";
-import { upsertDemandForecasts } from "~/modules/production/production.service";
-import DemandForecastForm from "~/modules/production/ui/Forecast/DemandForecastForm";
+import { demandProjectionValidator } from "~/modules/production/production.models";
+import { upsertDemandProjections } from "~/modules/production/production.service";
+import DemandProjectionForm from "~/modules/production/ui/Projection/DemandProjectionForm";
import { getPeriods } from "~/modules/shared/shared.service";
import { path } from "~/utils/path";
@@ -41,7 +41,7 @@ export async function action({ request }: ActionFunctionArgs) {
});
const formData = await request.formData();
- const validation = await validator(demandForecastsValidator).validate(
+ const validation = await validator(demandProjectionValidator).validate(
formData
);
@@ -52,7 +52,7 @@ export async function action({ request }: ActionFunctionArgs) {
const { itemId, locationId, periods, ...weekData } = validation.data;
// Extract week values and create demand forecast records
- const demandForecasts = [];
+ const demandProjections = [];
for (let i = 0; i < 52; i++) {
const weekKey = `week${i}` as keyof typeof weekData;
@@ -64,7 +64,7 @@ export async function action({ request }: ActionFunctionArgs) {
quantity > 0 &&
periods?.[i]
) {
- demandForecasts.push({
+ demandProjections.push({
itemId,
locationId,
periodId: periods[i],
@@ -75,14 +75,14 @@ export async function action({ request }: ActionFunctionArgs) {
}
}
- if (demandForecasts.length === 0) {
+ if (demandProjections.length === 0) {
return json(
{},
await flash(request, error(null, "No forecast quantities provided"))
);
}
- const result = await upsertDemandForecasts(client, demandForecasts);
+ const result = await upsertDemandProjections(client, demandProjections);
if (result.error) {
return json(
@@ -95,7 +95,7 @@ export async function action({ request }: ActionFunctionArgs) {
}
return redirect(
- path.to.demandForecasts + `?location=${locationId}`,
+ path.to.demandProjections + `?location=${locationId}`,
await flash(request, success("Demand forecasts created successfully"))
);
}
@@ -104,7 +104,7 @@ export default function NewProjectionRoute() {
const navigate = useNavigate();
const routeData = useRouteData<{
locationId: string;
- }>(path.to.demandForecasts);
+ }>(path.to.demandProjections);
const initialValues = {
itemId: "",
@@ -115,7 +115,7 @@ export default function NewProjectionRoute() {
};
return (
- <DemandForecastForm
+ <DemandProjectionForm
onClose={() => navigate(-1)}
initialValues={initialValues}
/>
diff --git a/apps/erp/app/routes/x+/production+/forecasts.tsx b/apps/erp/app/routes/x+/production+/projections.tsx
similarity index 93%
rename from apps/erp/app/routes/x+/production+/forecasts.tsx
rename to apps/erp/app/routes/x+/production+/projections.tsx
index 89be52d8df..7d98c6ca13 100644
--- a/apps/erp/app/routes/x+/production+/forecasts.tsx
+++ b/apps/erp/app/routes/x+/production+/projections.tsx
@@ -7,7 +7,7 @@ import { Outlet, useLoaderData } from "@remix-run/react";
import type { LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
import { getProductionProjections } from "~/modules/production";
-import DemandForecastsTable from "~/modules/production/ui/Forecast/DemandForecastTable";
+import DemandProjectionsTable from "~/modules/production/ui/Projection/DemandProjectionTable";
import { getLocationsList } from "~/modules/resources";
import { getPeriods } from "~/modules/shared/shared.service";
@@ -18,8 +18,8 @@ import { path } from "~/utils/path";
import { getGenericQueryFilters } from "~/utils/query";
export const handle: Handle = {
- breadcrumb: "Forecasts",
- to: path.to.demandForecasts,
+ breadcrumb: "Projections",
+ to: path.to.demandProjections,
};
export const WEEKS_TO_PROJECT = 12 * 4;
@@ -114,13 +114,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
});
}
-export default function DemandForecastsRoute() {
+export default function DemandProjectionsRoute() {
const { projections, count, locationId, periods } =
useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <DemandForecastsTable
+ <DemandProjectionsTable
data={projections}
count={count}
locationId={locationId}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 7c5641833d..57d4e1534c 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -607,8 +607,10 @@ export const path = {
generatePath(`${x}/job/methods/event/delete/${id}`),
deleteProductionQuantity: (id: string) =>
generatePath(`${x}/job/methods/quantity/delete/${id}`),
- deleteDemandForecasts: (itemId: string, locationId: string) =>
- generatePath(`${x}/production/forecasts/delete/${itemId}/${locationId}`),
+ deleteDemandProjections: (itemId: string, locationId: string) =>
+ generatePath(
+ `${x}/production/projections/delete/${itemId}/${locationId}`
+ ),
deletePurchaseInvoice: (id: string) =>
generatePath(`${x}/purchase-invoice/${id}/delete`),
deletePurchaseInvoiceLine: (invoiceId: string, lineId: string) =>
@@ -680,9 +682,9 @@ export const path = {
generatePath(`${x}/settings/webhooks/delete/${id}`),
deleteWorkCenter: (id: string) =>
generatePath(`${x}/resources/work-centers/delete/${id}`),
- demandForecast: (itemId: string, locationId: string) =>
- generatePath(`${x}/production/forecasts/${itemId}/${locationId}`),
- demandForecasts: `${x}/production/forecasts`,
+ demandProjection: (itemId: string, locationId: string) =>
+ generatePath(`${x}/production/projections/${itemId}/${locationId}`),
+ demandProjections: `${x}/production/projections`,
department: (id: string) => generatePath(`${x}/people/departments/${id}`),
departments: `${x}/people/departments`,
document: (id: string) => generatePath(`${x}/documents/search/${id}`),
@@ -895,7 +897,7 @@ export const path = {
generatePath(`${x}/settings/custom-fields/${tableId}/new`),
newCustomerPart: (id: string) =>
generatePath(`${x}/part/${id}/view/sales/customer-parts/new`),
- newDemandForecast: `${x}/production/forecasts/new`,
+ newDemandProjection: `${x}/production/projections/new`,
newDepartment: `${x}/people/departments/new`,
newDocument: `${x}/documents/new`,
newEmployee: `${x}/users/employees/new`,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index d1d1c9de76..e16f5253e6 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -5369,6 +5369,199 @@ export type Database = {
},
]
}
+ demandProjection: {
+ Row: {
+ companyId: string
+ confidence: number | null
+ createdAt: string
+ createdBy: string
+ forecastMethod: string | null
+ forecastQuantity: number
+ itemId: string
+ locationId: string
+ notes: string | null
+ periodId: string
+ updatedAt: string
+ updatedBy: string
+ }
+ Insert: {
+ companyId: string
+ confidence?: number | null
+ createdAt?: string
+ createdBy: string
+ forecastMethod?: string | null
+ forecastQuantity?: number
+ itemId: string
+ locationId: string
+ notes?: string | null
+ periodId: string
+ updatedAt?: string
+ updatedBy: string
+ }
+ Update: {
+ companyId?: string
+ confidence?: number | null
+ createdAt?: string
+ createdBy?: string
+ forecastMethod?: string | null
+ forecastQuantity?: number
+ itemId?: string
+ locationId?: string
+ notes?: string | null
+ periodId?: string
+ updatedAt?: string
+ updatedBy?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "demandProjection_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "demandProjection_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "demandProjection_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "demandProjection_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_locationId_fkey"
+ columns: ["locationId"]
+ isOneToOne: false
+ referencedRelation: "location"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_periodId_fkey"
+ columns: ["periodId"]
+ isOneToOne: false
+ referencedRelation: "period"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
department: {
Row: {
companyId: string
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index d1d1c9de76..e16f5253e6 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -5369,6 +5369,199 @@ export type Database = {
},
]
}
+ demandProjection: {
+ Row: {
+ companyId: string
+ confidence: number | null
+ createdAt: string
+ createdBy: string
+ forecastMethod: string | null
+ forecastQuantity: number
+ itemId: string
+ locationId: string
+ notes: string | null
+ periodId: string
+ updatedAt: string
+ updatedBy: string
+ }
+ Insert: {
+ companyId: string
+ confidence?: number | null
+ createdAt?: string
+ createdBy: string
+ forecastMethod?: string | null
+ forecastQuantity?: number
+ itemId: string
+ locationId: string
+ notes?: string | null
+ periodId: string
+ updatedAt?: string
+ updatedBy: string
+ }
+ Update: {
+ companyId?: string
+ confidence?: number | null
+ createdAt?: string
+ createdBy?: string
+ forecastMethod?: string | null
+ forecastQuantity?: number
+ itemId?: string
+ locationId?: string
+ notes?: string | null
+ periodId?: string
+ updatedAt?: string
+ updatedBy?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "demandProjection_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "demandProjection_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "demandProjection_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "demandProjection_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "consumables"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "materials"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "parts"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "tools"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_locationId_fkey"
+ columns: ["locationId"]
+ isOneToOne: false
+ referencedRelation: "location"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_periodId_fkey"
+ columns: ["periodId"]
+ isOneToOne: false
+ referencedRelation: "period"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "demandProjection_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
department: {
Row: {
companyId: string
diff --git a/packages/database/supabase/migrations/20251020183630_mrp-projections.sql b/packages/database/supabase/migrations/20251020183630_mrp-projections.sql
new file mode 100644
index 0000000000..ea4f5d95b3
--- /dev/null
+++ b/packages/database/supabase/migrations/20251020183630_mrp-projections.sql
@@ -0,0 +1,298 @@
+
+-- Demand forecasts table for estimates
+CREATE TABLE "demandProjection" (
+ "itemId" TEXT NOT NULL,
+ "locationId" TEXT,
+ "periodId" TEXT NOT NULL,
+ "forecastQuantity" NUMERIC NOT NULL DEFAULT 0,
+ "forecastMethod" TEXT, -- 'manual', 'statistical', 'ml', etc.
+ "confidence" NUMERIC(3,2), -- 0.00 to 1.00
+ "notes" TEXT,
+ "companyId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT NOT NULL,
+
+ CONSTRAINT "demandProjection_pkey" PRIMARY KEY ("itemId", "locationId", "periodId"),
+ CONSTRAINT "demandProjection_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "item"("id") ON DELETE CASCADE,
+ CONSTRAINT "demandProjection_itemId_locationId_periodId_companyId_key" UNIQUE ("itemId", "locationId", "periodId", "companyId"),
+ CONSTRAINT "demandProjection_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "location"("id") ON DELETE CASCADE,
+ CONSTRAINT "demandProjection_periodId_fkey" FOREIGN KEY ("periodId") REFERENCES "period"("id") ON DELETE CASCADE,
+ CONSTRAINT "demandProjection_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
+ CONSTRAINT "demandProjection_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE RESTRICT,
+ CONSTRAINT "demandProjection_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON DELETE RESTRICT
+);
+
+ALTER TABLE "demandProjection" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "SELECT" ON "public"."demandProjection"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_permission ('inventory_view')
+ )::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."demandProjection"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission ('inventory_create')
+ )::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."demandProjection"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission ('inventory_update')
+ )::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."demandProjection"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission ('inventory_delete')
+ )::text[]
+ )
+);
+
+-- Migrate data from demandForecast to demandProjection
+INSERT INTO "demandProjection" (
+ "itemId",
+ "locationId",
+ "periodId",
+ "forecastQuantity",
+ "forecastMethod",
+ "confidence",
+ "notes",
+ "companyId",
+ "createdBy",
+ "createdAt",
+ "updatedAt",
+ "updatedBy"
+)
+SELECT
+ "itemId",
+ "locationId",
+ "periodId",
+ "forecastQuantity",
+ "forecastMethod",
+ "confidence",
+ "notes",
+ "companyId",
+ "createdBy",
+ "createdAt",
+ "updatedAt",
+ "updatedBy"
+FROM "demandForecast";
+
+DELETE FROM "demandForecast";
+
+DROP FUNCTION IF EXISTS get_production_projections;
+CREATE OR REPLACE FUNCTION get_production_projections(company_id TEXT, location_id TEXT, periods TEXT[])
+ RETURNS TABLE (
+ "id" TEXT,
+ "readableIdWithRevision" TEXT,
+ "name" TEXT,
+ "active" BOOLEAN,
+ "type" "itemType",
+ "itemTrackingType" "itemTrackingType",
+ "replenishmentSystem" "itemReplenishmentSystem",
+ "thumbnailPath" TEXT,
+ "unitOfMeasureCode" TEXT,
+ "leadTime" INTEGER,
+ "manufacturingBlocked" BOOLEAN,
+ "lotSize" INTEGER,
+ "reorderingPolicy" "itemReorderingPolicy",
+ "demandAccumulationPeriod" INTEGER,
+ "demandAccumulationSafetyStock" NUMERIC,
+ "reorderPoint" INTEGER,
+ "reorderQuantity" INTEGER,
+ "minimumOrderQuantity" INTEGER,
+ "maximumOrderQuantity" INTEGER,
+ "orderMultiple" INTEGER,
+ "quantityOnHand" NUMERIC,
+ "maximumInventoryQuantity" NUMERIC,
+ "week1" NUMERIC,
+ "week2" NUMERIC,
+ "week3" NUMERIC,
+ "week4" NUMERIC,
+ "week5" NUMERIC,
+ "week6" NUMERIC,
+ "week7" NUMERIC,
+ "week8" NUMERIC,
+ "week9" NUMERIC,
+ "week10" NUMERIC,
+ "week11" NUMERIC,
+ "week12" NUMERIC,
+ "week13" NUMERIC,
+ "week14" NUMERIC,
+ "week15" NUMERIC,
+ "week16" NUMERIC,
+ "week17" NUMERIC,
+ "week18" NUMERIC,
+ "week19" NUMERIC,
+ "week20" NUMERIC,
+ "week21" NUMERIC,
+ "week22" NUMERIC,
+ "week23" NUMERIC,
+ "week24" NUMERIC,
+ "week25" NUMERIC,
+ "week26" NUMERIC,
+ "week27" NUMERIC,
+ "week28" NUMERIC,
+ "week29" NUMERIC,
+ "week30" NUMERIC,
+ "week31" NUMERIC,
+ "week32" NUMERIC,
+ "week33" NUMERIC,
+ "week34" NUMERIC,
+ "week35" NUMERIC,
+ "week36" NUMERIC,
+ "week37" NUMERIC,
+ "week38" NUMERIC,
+ "week39" NUMERIC,
+ "week40" NUMERIC,
+ "week41" NUMERIC,
+ "week42" NUMERIC,
+ "week43" NUMERIC,
+ "week44" NUMERIC,
+ "week45" NUMERIC,
+ "week46" NUMERIC,
+ "week47" NUMERIC,
+ "week48" NUMERIC,
+ "week49" NUMERIC,
+ "week50" NUMERIC,
+ "week51" NUMERIC,
+ "week52" NUMERIC
+ ) AS $$
+ SELECT
+ i."id",
+ i."readableIdWithRevision",
+ i."name",
+ i."active",
+ i."type",
+ i."itemTrackingType",
+ i."replenishmentSystem",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ i."unitOfMeasureCode",
+ ir."leadTime",
+ ir."manufacturingBlocked",
+ ir."lotSize",
+ ip."reorderingPolicy",
+ ip."demandAccumulationPeriod",
+ ip."demandAccumulationSafetyStock",
+ ip."reorderPoint",
+ ip."reorderQuantity",
+ ip."minimumOrderQuantity",
+ ip."maximumOrderQuantity",
+ ip."orderMultiple",
+ COALESCE((
+ SELECT SUM("quantity")
+ FROM "itemLedger"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "itemId" = i."id"
+ ), 0) AS "quantityOnHand",
+ ip."maximumInventoryQuantity",
+ MAX(CASE WHEN df."periodId" = periods[1] THEN df."forecastQuantity" END) AS "week1",
+ MAX(CASE WHEN df."periodId" = periods[2] THEN df."forecastQuantity" END) AS "week2",
+ MAX(CASE WHEN df."periodId" = periods[3] THEN df."forecastQuantity" END) AS "week3",
+ MAX(CASE WHEN df."periodId" = periods[4] THEN df."forecastQuantity" END) AS "week4",
+ MAX(CASE WHEN df."periodId" = periods[5] THEN df."forecastQuantity" END) AS "week5",
+ MAX(CASE WHEN df."periodId" = periods[6] THEN df."forecastQuantity" END) AS "week6",
+ MAX(CASE WHEN df."periodId" = periods[7] THEN df."forecastQuantity" END) AS "week7",
+ MAX(CASE WHEN df."periodId" = periods[8] THEN df."forecastQuantity" END) AS "week8",
+ MAX(CASE WHEN df."periodId" = periods[9] THEN df."forecastQuantity" END) AS "week9",
+ MAX(CASE WHEN df."periodId" = periods[10] THEN df."forecastQuantity" END) AS "week10",
+ MAX(CASE WHEN df."periodId" = periods[11] THEN df."forecastQuantity" END) AS "week11",
+ MAX(CASE WHEN df."periodId" = periods[12] THEN df."forecastQuantity" END) AS "week12",
+ MAX(CASE WHEN df."periodId" = periods[13] THEN df."forecastQuantity" END) AS "week13",
+ MAX(CASE WHEN df."periodId" = periods[14] THEN df."forecastQuantity" END) AS "week14",
+ MAX(CASE WHEN df."periodId" = periods[15] THEN df."forecastQuantity" END) AS "week15",
+ MAX(CASE WHEN df."periodId" = periods[16] THEN df."forecastQuantity" END) AS "week16",
+ MAX(CASE WHEN df."periodId" = periods[17] THEN df."forecastQuantity" END) AS "week17",
+ MAX(CASE WHEN df."periodId" = periods[18] THEN df."forecastQuantity" END) AS "week18",
+ MAX(CASE WHEN df."periodId" = periods[19] THEN df."forecastQuantity" END) AS "week19",
+ MAX(CASE WHEN df."periodId" = periods[20] THEN df."forecastQuantity" END) AS "week20",
+ MAX(CASE WHEN df."periodId" = periods[21] THEN df."forecastQuantity" END) AS "week21",
+ MAX(CASE WHEN df."periodId" = periods[22] THEN df."forecastQuantity" END) AS "week22",
+ MAX(CASE WHEN df."periodId" = periods[23] THEN df."forecastQuantity" END) AS "week23",
+ MAX(CASE WHEN df."periodId" = periods[24] THEN df."forecastQuantity" END) AS "week24",
+ MAX(CASE WHEN df."periodId" = periods[25] THEN df."forecastQuantity" END) AS "week25",
+ MAX(CASE WHEN df."periodId" = periods[26] THEN df."forecastQuantity" END) AS "week26",
+ MAX(CASE WHEN df."periodId" = periods[27] THEN df."forecastQuantity" END) AS "week27",
+ MAX(CASE WHEN df."periodId" = periods[28] THEN df."forecastQuantity" END) AS "week28",
+ MAX(CASE WHEN df."periodId" = periods[29] THEN df."forecastQuantity" END) AS "week29",
+ MAX(CASE WHEN df."periodId" = periods[30] THEN df."forecastQuantity" END) AS "week30",
+ MAX(CASE WHEN df."periodId" = periods[31] THEN df."forecastQuantity" END) AS "week31",
+ MAX(CASE WHEN df."periodId" = periods[32] THEN df."forecastQuantity" END) AS "week32",
+ MAX(CASE WHEN df."periodId" = periods[33] THEN df."forecastQuantity" END) AS "week33",
+ MAX(CASE WHEN df."periodId" = periods[34] THEN df."forecastQuantity" END) AS "week34",
+ MAX(CASE WHEN df."periodId" = periods[35] THEN df."forecastQuantity" END) AS "week35",
+ MAX(CASE WHEN df."periodId" = periods[36] THEN df."forecastQuantity" END) AS "week36",
+ MAX(CASE WHEN df."periodId" = periods[37] THEN df."forecastQuantity" END) AS "week37",
+ MAX(CASE WHEN df."periodId" = periods[38] THEN df."forecastQuantity" END) AS "week38",
+ MAX(CASE WHEN df."periodId" = periods[39] THEN df."forecastQuantity" END) AS "week39",
+ MAX(CASE WHEN df."periodId" = periods[40] THEN df."forecastQuantity" END) AS "week40",
+ MAX(CASE WHEN df."periodId" = periods[41] THEN df."forecastQuantity" END) AS "week41",
+ MAX(CASE WHEN df."periodId" = periods[42] THEN df."forecastQuantity" END) AS "week42",
+ MAX(CASE WHEN df."periodId" = periods[43] THEN df."forecastQuantity" END) AS "week43",
+ MAX(CASE WHEN df."periodId" = periods[44] THEN df."forecastQuantity" END) AS "week44",
+ MAX(CASE WHEN df."periodId" = periods[45] THEN df."forecastQuantity" END) AS "week45",
+ MAX(CASE WHEN df."periodId" = periods[46] THEN df."forecastQuantity" END) AS "week46",
+ MAX(CASE WHEN df."periodId" = periods[47] THEN df."forecastQuantity" END) AS "week47",
+ MAX(CASE WHEN df."periodId" = periods[48] THEN df."forecastQuantity" END) AS "week48",
+ MAX(CASE WHEN df."periodId" = periods[49] THEN df."forecastQuantity" END) AS "week49",
+ MAX(CASE WHEN df."periodId" = periods[50] THEN df."forecastQuantity" END) AS "week50",
+ MAX(CASE WHEN df."periodId" = periods[51] THEN df."forecastQuantity" END) AS "week51",
+ MAX(CASE WHEN df."periodId" = periods[52] THEN df."forecastQuantity" END) AS "week52"
+ FROM "item" i
+ INNER JOIN "itemReplenishment" ir ON i."id" = ir."itemId"
+ INNER JOIN "itemPlanning" ip ON i."id" = ip."itemId" AND ip."locationId" = location_id
+ LEFT JOIN "modelUpload" mu ON mu."id" = i."modelUploadId"
+ INNER JOIN "demandProjection" df ON df."itemId" = i."id"
+ AND df."companyId" = company_id
+ AND df."locationId" = location_id
+ AND df."periodId" = ANY(periods)
+ WHERE i."companyId" = company_id
+ AND i."replenishmentSystem" = 'Make'
+ AND i."itemTrackingType" != 'Non-Inventory'
+ AND i."active" = TRUE
+ GROUP BY
+ i."id",
+ i."readableIdWithRevision",
+ i."name",
+ i."active",
+ i."type",
+ i."itemTrackingType",
+ i."replenishmentSystem",
+ i."thumbnailPath",
+ mu."thumbnailPath",
+ i."unitOfMeasureCode",
+ ir."leadTime",
+ ir."manufacturingBlocked",
+ ir."lotSize",
+ ip."reorderingPolicy",
+ ip."demandAccumulationPeriod",
+ ip."demandAccumulationSafetyStock",
+ ip."reorderPoint",
+ ip."reorderQuantity",
+ ip."minimumOrderQuantity",
+ ip."maximumOrderQuantity",
+ ip."orderMultiple",
+ ip."maximumInventoryQuantity";
+$$ LANGUAGE sql SECURITY DEFINER;
\ No newline at end of file