Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(planning): read demand projections in purchasing planning; forbid DB clients in services (#1533)
Brad Barbind51cafd551c0
diff --git a/.claude/rules/conventions-services.md b/.claude/rules/conventions-services.mdindex 13b75de8ea..85f611b6c7 100644--- a/.claude/rules/conventions-services.md+++ b/.claude/rules/conventions-services.md@@ -175,6 +175,16 @@ export async function updateQuoteLineOrder(A single write is already atomic — don't reach for a transaction.+**Never construct the Kysely client (or a `pg` pool) inside the service.** The service+takes `db: Kysely<KyselyDatabase>` as an argument and nothing more — importing+`@carbon/database/client`'s `getPostgresConnectionPool`/`getPostgresClient` or `kysely`'s+`PostgresDriver` here (even behind a dynamic `import()`) pulls server-only code into the+browser bundle, because `{module}.service.ts` is re-exported through the module barrel that+client components import. Build the handle once in a `.server` file — `getDatabaseClient()`+from `~/services/database.server` — import it in the **route action**, and pass it in. This+is enforced by the `no-db-client-in-service` conformance check (`@carbon/checks`); the+route-wiring example is in [database-patterns.md](database-patterns.md#transactions-kysely).+## Calling out to other helpers- **Sequence numbers**: `getNextSequence(client, table, companyId)`diff --git a/AGENTS.md b/AGENTS.mdindex 854fa1e41f..46d9059c29 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -30,6 +30,7 @@ Carbon is a manufacturing ERP/MES/QMS. It contains apps for ERP, MES, academy, a- Never expose cross-tenant data or skip `companyId` scoping.- Never query inside a loop (N+1) — collect the ids and make one `.in()` call, an embed, or a view (see `.claude/rules/database-patterns.md`).- Never chain Supabase-client writes and call it a transaction — the client has none. Use a Kysely transaction, or an RPC when it must also be callable from an edge function.+- Never construct a DB connection/pool/Kysely client inside a `{module}.service.ts` — service files are re-exported through the module barrel that client components import, so they are bundled for the browser. Build the client in a `.server` file (`getDatabaseClient()` from `~/services/database.server`) and pass it into the service as a `db: Kysely<KyselyDatabase>` argument from the route action. Enforced by the `no-db-client-in-service` check (`@carbon/checks`).- Never hand-edit generated DB types (`@carbon/database` types).- Never scatter service/models files — one `{module}.service.ts` and one `{module}.models.ts` per module.- Never rebuild the database to test changes — wait for the user.diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.mdindex 0716d71b60..e179dd5779 100644--- a/apps/erp/app/modules/production/AGENTS.md+++ b/apps/erp/app/modules/production/AGENTS.md@@ -78,7 +78,7 @@ pnpm --filter @carbon/erp test- `recalculateJobRequirements` / `recalculateJobOperationDependencies` — recalculation after changes (`recalculateJobOperationDependencies` resolves the job's location and runs the whole-location schedule regen in-process via `runLocationSchedule` from `@carbon/ee/planning`)- `notifyScheduleInputsChanged(companyId, kind, reason, entityId?)` — thin emitter of `carbon/schedule.inputs.changed` (kinds: `ability`/`shift`/`employee-shift`/`work-center`/`location`/`reorder`/`people`); stamps affected jobs and the debounced replan wave regenerates each stale location- `getJobPromiseDate` — promise date = `job.projectedCompletionAt` (forward-ASAP forecast finish), null before the first regen (no operation-date fallback — `jobOperation.dueDate` is the backward need-by target, so max(op.dueDate) would just echo the job due date); returns the §7 `{ promiseDate, basis: "schedule", confidence }` contract (`confidence` "low" when the job has a conflicted op or a `scheduleOutdatedReason`, else "scheduled")-- `runMRP` — triggers Material Requirements Planning **in-process** via `runMrp` from `@carbon/ee/planning` (dynamic import + `getSchedulingDb()` Kysely handle; formerly the `mrp` Deno edge function); preserves the `{ data, error }` shape+- `runMRP(client, db, params)` — triggers Material Requirements Planning **in-process** via `runMrp` from `@carbon/ee/planning`; the route action passes the Kysely handle (`getDatabaseClient()` from `~/services/database.server`) — it is NEVER constructed in this service file (which is bundled for the browser via the module barrel; enforced by the `no-db-client-in-service` conformance check). `recalculateJobOperationDependencies(client, db, params)` and `getJobExpediteForecast(client, db, …)` take the handle the same way. Formerly the `mrp` Deno edge function; preserves the `{ data, error }` shape- `calculateJobPriority` — computes priority from deadline type and due date- `getActiveJobOperationsByLocation` — schedule board data (RPC `get_active_job_operations_by_location`)- `getPeopleAssignments` / `getPeopleAbsences` (single date) and `getPeopleAssignmentsRange` / `getPeopleAbsencesRange` (week) — people board/matrix reads; `upsertPeopleAssignment` (move semantics, optional partial-day `hours`) / `movePeopleAssignment` (station move with same-station merge, Kysely txn; returns `previousWorkCenterId` so `people.update.tsx` reschedules BOTH the source and destination work centers — otherwise the station the person LEFT keeps a stale booking) / `setPeopleAssignmentHours` (per-station hours; null = whole shift — lowering releases the remainder to the board's free-hours pool) / `setPeopleAssignmentOvertime` / `setPeopleOvertimeBulk` (one date or a `date`→`toDate` range — the board's Week horizon applies a whole week; optional department/shift scope, single UPDATE) / `deletePeopleAssignment` / `setPeopleAbsence` / `setPeopleAbsenceRange` (vacation as one action — a row per date, duplicates skipped) / `clearPeopleAbsence` / `copyPeopleBoard` (day; copies splits, not overtime) / `copyPeopleWeek` (whole Monday-start week, same skip rules) / `assignPeopleWeek` / `unassignPeopleWeek` / `movePeopleWeek` (week-basis manning for the Board's Week range: one row per working day from the shift's weekday flags, Mon–Fri fallback) / `setPeopleDay` (atomic reconciliation of a person's whole day — the `PeopleHoursModal` Working-hours editor's Save, also anchored on Matrix cells) — people mutationsdiff --git a/apps/erp/app/modules/production/production.mcp.server.ts b/apps/erp/app/modules/production/production.mcp.server.tsindex cf6796229d..178595ed76 100644--- a/apps/erp/app/modules/production/production.mcp.server.ts+++ b/apps/erp/app/modules/production/production.mcp.server.ts@@ -6,6 +6,7 @@ import {isBlocked} from "@carbon/ee/storage-rules.server";import type { SupabaseClient } from "@supabase/supabase-js";+import { getDatabaseClient } from "~/services/database.server";import { recalculateJobOperationDependencies } from "./production.service";// MCP-exposed production writes that depend on server-only modules@@ -167,7 +168,7 @@ export async function scheduleJob("You do not have permission to schedule jobs (production update).");}- return recalculateJobOperationDependencies(client, {+ return recalculateJobOperationDependencies(client, getDatabaseClient(), {jobId: args.jobId,companyId,userIddiff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex 5a092d31f1..d471ada48f 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -987,25 +987,11 @@ export async function getJob(client: SupabaseClient<Database>, id: string) {return client.from("jobs").select("*").eq("id", id).single();}-// Lazy Node Kysely handle for the IN-PROCESS scheduling engine. Built through a-// dynamic import so this module — which is ALSO bundled for the browser (it is-// imported by client components via the module barrel) — never STATICALLY pulls-// in `pg` or a `.server` module. Same tactic as notifyScheduleInputsChanged's-// `await import("@carbon/jobs")` below. A modest dedicated pool: a regen uses one-// connection at a time (sequential per job).-let schedulingDbPromise: Promise<Kysely<KyselyDatabase>> | undefined;-function getSchedulingDb(): Promise<Kysely<KyselyDatabase>> {- if (!schedulingDbPromise) {- schedulingDbPromise = (async () => {- const { getPostgresClient, getPostgresConnectionPool } = await import(- "@carbon/database/client"- );- const { PostgresDriver } = await import("kysely");- return getPostgresClient(getPostgresConnectionPool(5), PostgresDriver);- })();- }- return schedulingDbPromise;-}+// The IN-PROCESS scheduling/MRP engines need a Node Kysely handle. It is built+// in `~/services/database.server` (getDatabaseClient) and passed in as `db` by+// the route action — NEVER constructed here. This module is also bundled for the+// browser (imported by client components via the module barrel), so it must not+// pull in `pg`/`kysely`. Enforced by the no-db-client-in-service conformance check.// Read-only "best case" what-if: runs the job first in its location's schedule// IN-PROCESS (persists nothing) and returns the projected completion +@@ -1013,6 +999,7 @@ function getSchedulingDb(): Promise<Kysely<KyselyDatabase>> {// (e.g. not Ready/In Progress/Paused).export async function getJobExpediteForecast(client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,jobId: string,companyId: string,userId: string@@ -1032,7 +1019,7 @@ export async function getJobExpediteForecast(try {const { runExpediteWhatIf } = await import("@carbon/ee/planning");const expedite = await runExpediteWhatIf({- db: await getSchedulingDb(),+ db,client,locationId: job.locationId,companyId,@@ -2519,6 +2506,7 @@ export async function getTrackedEntitiesByJobId(*/export async function recalculateJobOperationDependencies(client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,params: {jobId: string;companyId: string;@@ -2543,7 +2531,7 @@ export async function recalculateJobOperationDependencies(try {const { runLocationSchedule } = await import("@carbon/ee/planning");const data = await runLocationSchedule({- db: await getSchedulingDb(),+ db,client,locationId: job.locationId,companyId: params.companyId,@@ -2591,6 +2579,7 @@ export async function recalculateJobMakeMethodRequirements(export async function runMRP(client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,params: {type:| "company"@@ -2610,7 +2599,7 @@ export async function runMRP(// pool. Preserves the `{ data, error }` shape the caller (api+/mrp.ts) returns.try {const { runMrp } = await import("@carbon/ee/planning");- const data = await runMrp(client, await getSchedulingDb(), params);+ const data = await runMrp(client, db, params);return { data, error: null };} catch (err) {return {diff --git a/apps/erp/app/routes/api+/kanban.$id.tsx b/apps/erp/app/routes/api+/kanban.$id.tsxindex 0ab8cb1f81..05ee09d76e 100644--- a/apps/erp/app/routes/api+/kanban.$id.tsx+++ b/apps/erp/app/routes/api+/kanban.$id.tsx@@ -164,7 +164,7 @@ async function handleKanban({companyId,userId}),- runMRP(serviceRole, {+ runMRP(serviceRole, getDatabaseClient(), {type: "job",id,companyId,diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex 03751f9eee..fef9ec353d 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-08-31T09:40:24.150Z",+ "generated": "2026-09-01T00:03:45.799Z","totalTools": 1488,"modules": 15,"tools": [@@ -20492,6 +20492,7 @@"paramCount": 1,"serviceParams": ["client",+ "db","jobId","companyId","userId"@@ -22332,6 +22333,7 @@"paramCount": 1,"serviceParams": ["client",+ "db","params"],"injectAuth": [@@ -22410,6 +22412,7 @@"paramCount": 2,"serviceParams": ["client",+ "db","params"],"injectAuth": [diff --git a/apps/erp/app/routes/api+/mrp.ts b/apps/erp/app/routes/api+/mrp.tsindex 8d7f1d69e8..bacb9d3102 100644--- a/apps/erp/app/routes/api+/mrp.ts+++ b/apps/erp/app/routes/api+/mrp.ts@@ -3,6 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import type { ActionFunctionArgs } from "react-router";import { runMRP } from "~/modules/production/production.service";+import { getDatabaseClient } from "~/services/database.server";export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);@@ -14,7 +15,7 @@ export async function action({ request }: ActionFunctionArgs) {update: "inventory"});- const result = await runMRP(getCarbonServiceRole(), {+ const result = await runMRP(getCarbonServiceRole(), getDatabaseClient(), {type: locationId ? "location" : "company",id: locationId ?? companyId,companyId,diff --git a/apps/erp/app/routes/x+/job+/$jobId.expedite.tsx b/apps/erp/app/routes/x+/job+/$jobId.expedite.tsxindex ef92faf923..2a53e3c8ab 100644--- a/apps/erp/app/routes/x+/job+/$jobId.expedite.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.expedite.tsx@@ -5,6 +5,7 @@ import { flash } from "@carbon/auth/session.server";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { getJobExpediteForecast } from "~/modules/production";+import { getDatabaseClient } from "~/services/database.server";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -18,6 +19,7 @@ export async function action({ request, params }: ActionFunctionArgs) {const expedite = await getJobExpediteForecast(getCarbonServiceRole(),+ getDatabaseClient(),jobId,companyId,userIddiff --git a/apps/erp/app/routes/x+/job+/$jobId.status.tsx b/apps/erp/app/routes/x+/job+/$jobId.status.tsxindex 5e6e73d375..de3a0f400c 100644--- a/apps/erp/app/routes/x+/job+/$jobId.status.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.status.tsx@@ -64,7 +64,7 @@ export async function action({ request, params }: ActionFunctionArgs) {companyId,userId});- await runMRP(getCarbonServiceRole(), {+ await runMRP(getCarbonServiceRole(), getDatabaseClient(), {type: "job",id,companyId,diff --git a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.$id.tsx b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.$id.tsxindex da22f7b237..984d471060 100644--- a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.$id.tsx+++ b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.$id.tsx@@ -11,6 +11,7 @@ import {recalculateJobOperationDependencies,upsertJobMaterial} from "~/modules/production";+import { getDatabaseClient } from "~/services/database.server";import { setCustomFields } from "~/utils/form";export async function action({ request, params }: ActionFunctionArgs) {@@ -125,7 +126,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (validation.data.jobOperationId) {promises.push(- recalculateJobOperationDependencies(client, {+ recalculateJobOperationDependencies(client, getDatabaseClient(), {jobId,companyId,userIddiff --git a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.delete.$id.tsx b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.delete.$id.tsxindex 3a32c50436..83821b74a0 100644--- a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.delete.$id.tsx+++ b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.delete.$id.tsx@@ -8,6 +8,7 @@ import {deleteJobMaterial,recalculateJobOperationDependencies} from "~/modules/production";+import { getDatabaseClient } from "~/services/database.server";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -39,6 +40,7 @@ export async function action({ request, params }: ActionFunctionArgs) {const recalculateResult = await recalculateJobOperationDependencies(getCarbonServiceRole(),+ getDatabaseClient(),{jobId,companyId,diff --git a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsxindex 34d5c7546a..ce7a9d5bac 100644--- a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx+++ b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx@@ -12,6 +12,7 @@ import {recalculateJobOperationDependencies,upsertJobMaterial} from "~/modules/production";+import { getDatabaseClient } from "~/services/database.server";import { setCustomFields } from "~/utils/form";export async function action({ request, params }: ActionFunctionArgs) {@@ -108,7 +109,7 @@ export async function action({ request, params }: ActionFunctionArgs) {];promises.push(- recalculateJobOperationDependencies(serviceRole, {+ recalculateJobOperationDependencies(serviceRole, getDatabaseClient(), {jobId,companyId,userIddiff --git a/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.delete.tsx b/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.delete.tsxindex 9d4dd90b97..915c05ce07 100644--- a/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.delete.tsx+++ b/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.delete.tsx@@ -4,6 +4,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { recalculateJobOperationDependencies } from "~/modules/production/production.service";+import { getDatabaseClient } from "~/services/database.server";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -67,6 +68,7 @@ export async function action({ request, params }: ActionFunctionArgs) {const recalculateResult = await recalculateJobOperationDependencies(getCarbonServiceRole(),+ getDatabaseClient(),{jobId,companyId,diff --git a/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.new.tsx b/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.new.tsxindex bc3c4a02b0..37ebab6fb2 100644--- a/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.new.tsx+++ b/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.new.tsx@@ -11,6 +11,7 @@ import {recalculateJobOperationDependencies,upsertJobOperation} from "~/modules/production";+import { getDatabaseClient } from "~/services/database.server";import { setCustomFields } from "~/utils/form";export async function action({ request, params }: ActionFunctionArgs) {@@ -72,7 +73,7 @@ export async function action({ request, params }: ActionFunctionArgs) {companyId,userId}),- recalculateJobOperationDependencies(serviceRole, {+ recalculateJobOperationDependencies(serviceRole, getDatabaseClient(), {jobId,companyId,userIddiff --git a/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.order.tsx b/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.order.tsxindex a0c85569a2..a4219ecde9 100644--- a/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.order.tsx+++ b/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.order.tsx@@ -8,6 +8,7 @@ import {recalculateJobOperationDependencies,updateJobOperationOrder} from "~/modules/production";+import { getDatabaseClient } from "~/services/database.server";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -54,6 +55,7 @@ export async function action({ request, params }: ActionFunctionArgs) {if (jobId) {const recalculateDependencies = await recalculateJobOperationDependencies(getCarbonServiceRole(),+ getDatabaseClient(),{jobId: jobId,companyId: companyId,diff --git a/apps/erp/app/routes/x+/job+/methods+/get.tsx b/apps/erp/app/routes/x+/job+/methods+/get.tsxindex ec78df2982..de62a9fdf5 100644--- a/apps/erp/app/routes/x+/job+/methods+/get.tsx+++ b/apps/erp/app/routes/x+/job+/methods+/get.tsx@@ -10,6 +10,7 @@ import {upsertJobMaterialMakeMethod,upsertJobMethod} from "~/modules/production";+import { getDatabaseClient } from "~/services/database.server";import { path, requestReferrer } from "~/utils/path";export async function action({ request }: ActionFunctionArgs) {@@ -63,7 +64,7 @@ export async function action({ request }: ActionFunctionArgs) {companyId: companyId,userId: userId}),- recalculateJobOperationDependencies(serviceRole, {+ recalculateJobOperationDependencies(serviceRole, getDatabaseClient(), {jobId: validation.data.targetId,companyId: companyId,userId: userIddiff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.status.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.status.tsxindex f4bad05c6d..a313d3ad3c 100644--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.status.tsx+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.status.tsx@@ -234,7 +234,7 @@ export async function action({ request, params }: ActionFunctionArgs) {}if (status === "Planned") {- await runMRP(serviceRole, {+ await runMRP(serviceRole, getDatabaseClient(), {type: "purchaseOrder",id,companyId,diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsxindex 3057b68ed5..52b3786e5b 100644--- a/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx@@ -18,6 +18,7 @@ import {} from "~/modules/shared/shared.server";import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import { loader as pdfLoader } from "~/routes/file+/sales-order+/$id[.]pdf";+import { getDatabaseClient } from "~/services/database.server";export async function action(args: ActionFunctionArgs) {const { request, params } = args;@@ -169,7 +170,7 @@ export async function action(args: ActionFunctionArgs) {};}- await runMRP(getCarbonServiceRole(), {+ await runMRP(getCarbonServiceRole(), getDatabaseClient(), {type: "salesOrder",id: orderId,companyId: companyId,diff --git a/packages/checks/src/conformance/no-db-client-in-service.test.ts b/packages/checks/src/conformance/no-db-client-in-service.test.tsnew file mode 100644index 0000000000..41148e5d10--- /dev/null+++ b/packages/checks/src/conformance/no-db-client-in-service.test.ts@@ -0,0 +1,82 @@+import { describe, expect, it } from "vitest";+import { noDbClientInService } from "./no-db-client-in-service";++const SERVICE = "apps/erp/app/modules/production/production.service.ts";++describe("noDbClientInService", () => {+ it("flags getPostgresConnectionPool() in a service file", () => {+ const ts = "const pool = getPostgresConnectionPool(5);";+ const v = noDbClientInService.scan(SERVICE, ts);+ expect(v).toHaveLength(1);+ expect(v[0]?.snippet).toBe("getPostgresConnectionPool(");+ });++ it("flags getPostgresClient() in a service file", () => {+ const ts = "return getPostgresClient(pool, PostgresDriver);";+ // getPostgresClient( and PostgresDriver both match+ const v = noDbClientInService.scan(SERVICE, ts);+ expect(v).toHaveLength(2);+ });++ it("flags a raw new Pool()", () => {+ const ts = "const pool = new Pool({ connectionString });";+ expect(noDbClientInService.scan(SERVICE, ts)).toHaveLength(1);+ });++ it("flags the dynamic-import construction workaround", () => {+ const ts = [+ 'const { getPostgresClient, getPostgresConnectionPool } = await import("@carbon/database/client");',+ 'const { PostgresDriver } = await import("kysely");',+ "return getPostgresClient(getPostgresConnectionPool(5), PostgresDriver);"+ ].join("\n");+ // We match construction CALLS, not the destructured import names: line 3's+ // getPostgresClient( + getPostgresConnectionPool( + PostgresDriver, plus the+ // PostgresDriver on line 2 = 4. The workaround is caught at the point of use.+ expect(noDbClientInService.scan(SERVICE, ts)).toHaveLength(4);+ });++ it("allows a type-only import of the Kysely types", () => {+ const ts =+ 'import type { Kysely, KyselyDatabase } from "@carbon/database/client";';+ expect(noDbClientInService.scan(SERVICE, ts)).toHaveLength(0);+ });++ it("allows importing the sql template from kysely", () => {+ const ts = 'import { sql } from "kysely";';+ expect(noDbClientInService.scan(SERVICE, ts)).toHaveLength(0);+ });++ it("allows a service that RECEIVES db and opens a transaction", () => {+ const ts = [+ "export async function updateOrder(db: Kysely<KyselyDatabase>, updates) {",+ " return db.transaction().execute(async (trx) => {});",+ "}"+ ].join("\n");+ expect(noDbClientInService.scan(SERVICE, ts)).toHaveLength(0);+ });++ it("does NOT scan .server.ts (the sanctioned home for a DB client)", () => {+ const ts =+ "const pool = getPostgresConnectionPool(10); getPostgresClient(pool, PostgresDriver);";+ expect(+ noDbClientInService.scan("apps/erp/app/services/database.server.ts", ts)+ ).toHaveLength(0);+ });++ it("does NOT scan route files (they legitimately call getDatabaseClient)", () => {+ const ts = "const result = await runMRP(client, getDatabaseClient(), {});";+ expect(+ noDbClientInService.scan("apps/erp/app/routes/api+/mrp.ts", ts)+ ).toHaveLength(0);+ });++ it("does not confuse *.service.test.ts for a service file", () => {+ const ts = "const pool = getPostgresConnectionPool(5);";+ expect(+ noDbClientInService.scan(+ "apps/erp/app/modules/production/production.service.test.ts",+ ts+ )+ ).toHaveLength(0);+ });+});diff --git a/packages/checks/src/conformance/no-db-client-in-service.ts b/packages/checks/src/conformance/no-db-client-in-service.tsnew file mode 100644index 0000000000..c4112f3cf2--- /dev/null+++ b/packages/checks/src/conformance/no-db-client-in-service.ts@@ -0,0 +1,59 @@+import type { ConformanceCheck, Violation } from "../check";++/**+ * A `*.service.ts` file must never CONSTRUCT a database connection, pool, or+ * Kysely client. Service files are re-exported through the module barrel that+ * client components value-import (see each module's `index.ts` barrel), so+ * anything a service statically pulls in is bundled for the BROWSER. A `pg`+ * pool / Kysely driver constructed there either leaks server-only code into the+ * client bundle or forces a dynamic-`import()` workaround to hide it — both are+ * a smell for the same missing seam.+ *+ * The seam: the Kysely handle is built ONCE in a `.server` file+ * (`getDatabaseClient()` in `~/services/database.server`), the route action+ * imports it, and it is PASSED INTO the service as a+ * `db: Kysely<KyselyDatabase>` argument — the same convention the multi-row+ * transaction helpers already follow (see `.claude/rules/database-patterns.md`+ * and `conventions-services.md`).+ *+ * We flag the CONSTRUCTION primitives, not imports: `import type { Kysely,+ * KyselyDatabase }` and `import { sql } from "kysely"` are ordinary, allowed+ * service-layer imports and must never trip this. `.server.ts` files (the+ * sanctioned home for a client) and route actions (which legitimately call+ * `getDatabaseClient()`) are out of scope — only `*.service.ts` is scanned.+ */+const MESSAGE =+ "A *.service.ts must not construct a DB pool/Kysely client — this file is bundled for the browser via the module barrel. Build it in a .server file (getDatabaseClient in ~/services/database.server) and pass it into the service as a `db: Kysely<KyselyDatabase>` argument from the route action.";++const BANNED = [+ { pattern: /getPostgresConnectionPool\s*\(/g, message: MESSAGE },+ { pattern: /getPostgresClient\s*\(/g, message: MESSAGE },+ { pattern: /new Pool\s*\(/g, message: MESSAGE },+ { pattern: /\bPostgresDriver\b/g, message: MESSAGE }+];++export const noDbClientInService: ConformanceCheck = {+ id: "no-db-client-in-service",+ description:+ "A *.service.ts never constructs a DB pool/Kysely client — the route action builds it (getDatabaseClient from ~/services/database.server) and passes it in as `db`.",+ provenance: {+ deprecates:+ "constructing a pg pool / Kysely client inside a client-reachable *.service.ts (e.g. the removed getSchedulingDb in production.service.ts)",+ replacedBy:+ "getDatabaseClient() from ~/services/database.server, passed into the service as a `db: Kysely<KyselyDatabase>` argument by the route action"+ },+ scan(file, contents) {+ // Only `*.service.ts`. A `.server.ts` is the sanctioned home for a DB+ // client, and route actions legitimately call `getDatabaseClient()`.+ if (!file.endsWith(".service.ts")) return [];+ const violations: Violation[] = [];+ contents.split("\n").forEach((text, i) => {+ for (const { pattern, message } of BANNED) {+ for (const m of text.matchAll(pattern)) {+ violations.push({ file, line: i + 1, snippet: m[0], message });+ }+ }+ });+ return violations;+ }+};diff --git a/packages/checks/src/index.ts b/packages/checks/src/index.tsindex 69a24524a1..04a50b7e8a 100644--- a/packages/checks/src/index.ts+++ b/packages/checks/src/index.ts@@ -7,6 +7,7 @@ export type {} from "./check";export { findClobbers, objectRefs } from "./clobber";export { moduleShape } from "./conformance/module-shape";+export { noDbClientInService } from "./conformance/no-db-client-in-service";export { noDerivedPercentColumn } from "./conformance/no-derived-percent-column";export { noInlineFractionDigits } from "./conformance/no-inline-fraction-digits";export { noLegacyRls } from "./conformance/no-legacy-rls";diff --git a/packages/checks/src/run.ts b/packages/checks/src/run.tsindex 990c030d9e..471da2e464 100644--- a/packages/checks/src/run.ts+++ b/packages/checks/src/run.ts@@ -7,6 +7,7 @@ import type {Violation} from "./check";import { moduleShape } from "./conformance/module-shape";+import { noDbClientInService } from "./conformance/no-db-client-in-service";import { noDerivedPercentColumn } from "./conformance/no-derived-percent-column";import { noInlineFractionDigits } from "./conformance/no-inline-fraction-digits";import { noLegacyRls } from "./conformance/no-legacy-rls";@@ -33,10 +34,11 @@ export const SERVER_CHECKS: ConformanceCheck[] = [noZeroConcurrency];-/** Numeric-precision checks that run over ALL app TS (client and server). */+/** Checks that run over ALL app + shared-package TS (client and server). */export const TS_CHECKS: ConformanceCheck[] = [noRawRounding,- noInlineFractionDigits+ noInlineFractionDigits,+ noDbClientInService];export const STRUCTURE_CHECKS: StructureCheck[] = [moduleShape];diff --git a/packages/database/supabase/migrations/20260831190142_purchasing-planning-reads-demand-projections.sql b/packages/database/supabase/migrations/20260831190142_purchasing-planning-reads-demand-projections.sqlnew file mode 100644index 0000000000..8d9083ef50--- /dev/null+++ b/packages/database/supabase/migrations/20260831190142_purchasing-planning-reads-demand-projections.sql@@ -0,0 +1,444 @@+-- get_purchasing_planning's demand_data union read only demandActual + demandForecast,+-- so a purchased item whose only demand is a planner-entered demandProjection+-- (the "Demand Forecast" drawer writes the demandProjection table) never appeared+-- in purchasing planning and never drove Qty to Order. The identical fix was+-- applied to get_production_planning in 20260715195226 but not to its purchasing+-- twin. Fork the current definition (20260618171234) verbatim and add the third+-- demandProjection arm to demand_data. Read-only function change; no schema/table+-- change. MRP recalc is NOT required for a forecast to appear once this lands.++CREATE OR REPLACE FUNCTION get_purchasing_planning(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,+ "purchasingBlocked" BOOLEAN,+ "lotSize" INTEGER,+ "reorderingPolicy" "itemReorderingPolicy",+ "demandAccumulationPeriod" INTEGER,+ "demandAccumulationSafetyStock" NUMERIC,+ "reorderPoint" INTEGER,+ "reorderQuantity" INTEGER,+ "minimumOrderQuantity" INTEGER,+ "maximumOrderQuantity" INTEGER,+ "orderMultiple" INTEGER,+ "quantityOnHand" NUMERIC,+ "maximumInventoryQuantity" NUMERIC,+ "suppliers" jsonb,+ "preferredSupplierId" TEXT,+ "purchasingUnitOfMeasureCode" TEXT,+ "conversionFactor" NUMERIC,+ "quantityToOrder" NUMERIC,+ "supersessionMode" TEXT,+ "minimumReserveQuantity" 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 $$+ WITH RECURSIVE+ supply_data AS (+ SELECT+ "itemId",+ "periodId",+ SUM(COALESCE("actualQuantity", 0) + COALESCE("forecastQuantity", 0)) AS "supply"+ FROM (+ SELECT "itemId", "periodId", "actualQuantity", NULL as "forecastQuantity"+ FROM "supplyActual"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "periodId" = ANY(periods)+ UNION ALL+ SELECT "itemId", "periodId", NULL as "actualQuantity", "forecastQuantity"+ FROM "supplyForecast"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "periodId" = ANY(periods)+ ) combined+ GROUP BY "itemId", "periodId"+ ),+ demand_data AS (+ SELECT+ "itemId",+ "periodId",+ SUM(COALESCE("actualQuantity", 0) + COALESCE("forecastQuantity", 0)) AS "demand"+ FROM (+ SELECT "itemId", "periodId", "actualQuantity", NULL as "forecastQuantity"+ FROM "demandActual"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "periodId" = ANY(periods)+ UNION ALL+ SELECT "itemId", "periodId", NULL as "actualQuantity", "forecastQuantity"+ FROM "demandForecast"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "periodId" = ANY(periods)+ UNION ALL+ -- Top-level manual projections. The "Demand Forecast" drawer writes the+ -- demandProjection table; MRP explodes these into child demand+ -- (demandForecast) but the projected item's OWN demand lives only here —+ -- without this arm a purchased item whose only demand is a projection never+ -- appears in purchasing planning and never drives a suggested order.+ SELECT "itemId", "periodId", NULL as "actualQuantity", "forecastQuantity"+ FROM "demandProjection"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "periodId" = ANY(periods)+ ) combined+ GROUP BY "itemId", "periodId"+ ),+ base_items AS (+ SELECT DISTINCT ON (i."id")+ 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."purchasingBlocked",+ ir."lotSize",+ ir."preferredSupplierId",+ ir."purchasingUnitOfMeasureCode",+ ir."conversionFactor",+ ip."reorderingPolicy",+ ip."demandAccumulationPeriod",+ ip."demandAccumulationSafetyStock",+ ip."reorderPoint",+ ip."reorderQuantity",+ ip."minimumOrderQuantity",+ ip."maximumOrderQuantity",+ ip."orderMultiple",+ ip."maximumInventoryQuantity",+ COALESCE(ps."suppliers", '[]'::jsonb) as "suppliers",+ COALESCE((+ SELECT SUM("quantity")+ FROM "itemLedger"+ WHERE "companyId" = company_id+ AND "locationId" = location_id+ AND "itemId" = i."id"+ ), 0) AS "quantityOnHand"+ 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"+ LEFT JOIN (+ SELECT+ ps."itemId",+ jsonb_agg(+ jsonb_build_object(+ 'id', ps."id",+ 'minimumOrderQuantity', ps."minimumOrderQuantity",+ 'supplierUnitOfMeasureCode', ps."supplierUnitOfMeasureCode",+ 'conversionFactor', ps."conversionFactor",+ 'unitPrice', ps."unitPrice",+ 'supplierId', ps."supplierId",+ 'supplierPartId', ps."supplierPartId"+ )+ ) AS "suppliers"+ FROM "supplierPart" ps+ WHERE ps."companyId" = company_id+ AND ps.active = true+ GROUP BY ps."itemId"+ ) ps ON ps."itemId" = i."id"+ WHERE i."companyId" = company_id+ AND i."replenishmentSystem" != 'Make'+ AND i."itemTrackingType" != 'Non-Inventory'+ AND i."active" = TRUE+ -- Supersession: drop obsolete items and items past their discontinuation+ -- date so no new orders are suggested.+ AND NOT EXISTS (+ SELECT 1 FROM "itemSupersession" ss+ WHERE ss."itemId" = i."id"+ AND (+ ss."supersessionMode" = 'No Stock'+ OR (+ -- date-based suppression applies only to the phase-out modes; Stock+ -- Only keeps replenishing to its reserve floor regardless of date.+ ss."supersessionMode" IN ('Consume First', 'Prefer New')+ AND ss."discontinuationDate" IS NOT NULL+ AND ss."discontinuationDate" <= CURRENT_DATE+ )+ )+ )+ AND (+ EXISTS (+ SELECT 1 FROM demand_data d+ WHERE d."itemId" = i."id"+ )+ OR (+ ip."reorderPoint" > 0+ AND ip."reorderingPolicy" IN ('Fixed Reorder Quantity', 'Maximum Quantity')+ )+ )+ ),+ projections AS (+ SELECT+ bi.*,+ periods[1] as "periodId",+ bi."quantityOnHand" + COALESCE(s."supply", 0) - COALESCE(d."demand", 0) AS "projection",+ 1 as period_index+ FROM base_items bi+ LEFT JOIN supply_data s ON bi."id" = s."itemId" AND s."periodId" = periods[1]+ LEFT JOIN demand_data d ON bi."id" = d."itemId" AND d."periodId" = periods[1]++ UNION ALL++ SELECT+ p."id",+ p."readableIdWithRevision",+ p."name",+ p."active",+ p."type",+ p."itemTrackingType",+ p."replenishmentSystem",+ p."thumbnailPath",+ p."unitOfMeasureCode",+ p."leadTime",+ p."purchasingBlocked",+ p."lotSize",+ p."preferredSupplierId",+ p."purchasingUnitOfMeasureCode",+ p."conversionFactor",+ p."reorderingPolicy",+ p."demandAccumulationPeriod",+ p."demandAccumulationSafetyStock",+ p."reorderPoint",+ p."reorderQuantity",+ p."minimumOrderQuantity",+ p."maximumOrderQuantity",+ p."orderMultiple",+ p."maximumInventoryQuantity",+ p."suppliers",+ p."quantityOnHand",+ periods[p.period_index + 1] as "periodId",+ p."projection" + COALESCE(s."supply", 0) - COALESCE(d."demand", 0) AS "projection",+ p.period_index + 1 as period_index+ FROM projections p+ LEFT JOIN supply_data s ON p."id" = s."itemId" AND s."periodId" = periods[p.period_index + 1]+ LEFT JOIN demand_data d ON p."id" = d."itemId" AND d."periodId" = periods[p.period_index + 1]+ WHERE p.period_index < array_length(periods, 1)+ ),+ order_quantities AS (+ SELECT+ p."id",+ calculate_quantity_to_order(+ p."reorderingPolicy",+ p."reorderPoint",+ p."reorderQuantity",+ p."minimumOrderQuantity",+ p."maximumOrderQuantity",+ p."orderMultiple",+ p."lotSize",+ p."maximumInventoryQuantity",+ p."demandAccumulationPeriod",+ p."demandAccumulationSafetyStock",+ array_agg(p."projection" ORDER BY p.period_index)+ ) AS "quantityToOrder"+ FROM projections p+ GROUP BY+ p."id",+ p."reorderingPolicy",+ p."reorderPoint",+ p."reorderQuantity",+ p."minimumOrderQuantity",+ p."maximumOrderQuantity",+ p."orderMultiple",+ p."lotSize",+ p."maximumInventoryQuantity",+ p."demandAccumulationPeriod",+ p."demandAccumulationSafetyStock"+ )+ SELECT DISTINCT ON (p."id")+ p."id",+ p."readableIdWithRevision",+ p."name",+ p."active",+ p."type",+ p."itemTrackingType",+ p."replenishmentSystem",+ p."thumbnailPath",+ p."unitOfMeasureCode",+ p."leadTime",+ p."purchasingBlocked",+ p."lotSize",+ p."reorderingPolicy",+ p."demandAccumulationPeriod",+ p."demandAccumulationSafetyStock",+ p."reorderPoint",+ p."reorderQuantity",+ p."minimumOrderQuantity",+ p."maximumOrderQuantity",+ p."orderMultiple",+ p."quantityOnHand",+ p."maximumInventoryQuantity",+ p."suppliers",+ p."preferredSupplierId",+ p."purchasingUnitOfMeasureCode",+ p."conversionFactor",+ CASE+ WHEN ss."supersessionMode" = 'Stock Only'+ THEN GREATEST(+ 0,+ COALESCE(rsv."minimumReserveQuantity", 0)+ - p."quantityOnHand"+ - COALESCE(sup."incomingSupply", 0)+ )+ ELSE COALESCE(oq."quantityToOrder", 0)+ END AS "quantityToOrder",+ ss."supersessionMode" AS "supersessionMode",+ COALESCE(rsv."minimumReserveQuantity", 0) AS "minimumReserveQuantity",+ MAX(CASE WHEN p."periodId" = periods[1] THEN p."projection" END) AS "week1",+ MAX(CASE WHEN p."periodId" = periods[2] THEN p."projection" END) AS "week2",+ MAX(CASE WHEN p."periodId" = periods[3] THEN p."projection" END) AS "week3",+ MAX(CASE WHEN p."periodId" = periods[4] THEN p."projection" END) AS "week4",+ MAX(CASE WHEN p."periodId" = periods[5] THEN p."projection" END) AS "week5",+ MAX(CASE WHEN p."periodId" = periods[6] THEN p."projection" END) AS "week6",+ MAX(CASE WHEN p."periodId" = periods[7] THEN p."projection" END) AS "week7",+ MAX(CASE WHEN p."periodId" = periods[8] THEN p."projection" END) AS "week8",+ MAX(CASE WHEN p."periodId" = periods[9] THEN p."projection" END) AS "week9",+ MAX(CASE WHEN p."periodId" = periods[10] THEN p."projection" END) AS "week10",+ MAX(CASE WHEN p."periodId" = periods[11] THEN p."projection" END) AS "week11",+ MAX(CASE WHEN p."periodId" = periods[12] THEN p."projection" END) AS "week12",+ MAX(CASE WHEN p."periodId" = periods[13] THEN p."projection" END) AS "week13",+ MAX(CASE WHEN p."periodId" = periods[14] THEN p."projection" END) AS "week14",+ MAX(CASE WHEN p."periodId" = periods[15] THEN p."projection" END) AS "week15",+ MAX(CASE WHEN p."periodId" = periods[16] THEN p."projection" END) AS "week16",+ MAX(CASE WHEN p."periodId" = periods[17] THEN p."projection" END) AS "week17",+ MAX(CASE WHEN p."periodId" = periods[18] THEN p."projection" END) AS "week18",+ MAX(CASE WHEN p."periodId" = periods[19] THEN p."projection" END) AS "week19",+ MAX(CASE WHEN p."periodId" = periods[20] THEN p."projection" END) AS "week20",+ MAX(CASE WHEN p."periodId" = periods[21] THEN p."projection" END) AS "week21",+ MAX(CASE WHEN p."periodId" = periods[22] THEN p."projection" END) AS "week22",+ MAX(CASE WHEN p."periodId" = periods[23] THEN p."projection" END) AS "week23",+ MAX(CASE WHEN p."periodId" = periods[24] THEN p."projection" END) AS "week24",+ MAX(CASE WHEN p."periodId" = periods[25] THEN p."projection" END) AS "week25",+ MAX(CASE WHEN p."periodId" = periods[26] THEN p."projection" END) AS "week26",+ MAX(CASE WHEN p."periodId" = periods[27] THEN p."projection" END) AS "week27",+ MAX(CASE WHEN p."periodId" = periods[28] THEN p."projection" END) AS "week28",+ MAX(CASE WHEN p."periodId" = periods[29] THEN p."projection" END) AS "week29",+ MAX(CASE WHEN p."periodId" = periods[30] THEN p."projection" END) AS "week30",+ MAX(CASE WHEN p."periodId" = periods[31] THEN p."projection" END) AS "week31",+ MAX(CASE WHEN p."periodId" = periods[32] THEN p."projection" END) AS "week32",+ MAX(CASE WHEN p."periodId" = periods[33] THEN p."projection" END) AS "week33",+ MAX(CASE WHEN p."periodId" = periods[34] THEN p."projection" END) AS "week34",+ MAX(CASE WHEN p."periodId" = periods[35] THEN p."projection" END) AS "week35",+ MAX(CASE WHEN p."periodId" = periods[36] THEN p."projection" END) AS "week36",+ MAX(CASE WHEN p."periodId" = periods[37] THEN p."projection" END) AS "week37",+ MAX(CASE WHEN p."periodId" = periods[38] THEN p."projection" END) AS "week38",+ MAX(CASE WHEN p."periodId" = periods[39] THEN p."projection" END) AS "week39",+ MAX(CASE WHEN p."periodId" = periods[40] THEN p."projection" END) AS "week40",+ MAX(CASE WHEN p."periodId" = periods[41] THEN p."projection" END) AS "week41",+ MAX(CASE WHEN p."periodId" = periods[42] THEN p."projection" END) AS "week42",+ MAX(CASE WHEN p."periodId" = periods[43] THEN p."projection" END) AS "week43",+ MAX(CASE WHEN p."periodId" = periods[44] THEN p."projection" END) AS "week44",+ MAX(CASE WHEN p."periodId" = periods[45] THEN p."projection" END) AS "week45",+ MAX(CASE WHEN p."periodId" = periods[46] THEN p."projection" END) AS "week46",+ MAX(CASE WHEN p."periodId" = periods[47] THEN p."projection" END) AS "week47",+ MAX(CASE WHEN p."periodId" = periods[48] THEN p."projection" END) AS "week48",+ MAX(CASE WHEN p."periodId" = periods[49] THEN p."projection" END) AS "week49",+ MAX(CASE WHEN p."periodId" = periods[50] THEN p."projection" END) AS "week50",+ MAX(CASE WHEN p."periodId" = periods[51] THEN p."projection" END) AS "week51",+ MAX(CASE WHEN p."periodId" = periods[52] THEN p."projection" END) AS "week52"+ FROM projections p+ LEFT JOIN order_quantities oq ON p."id" = oq."id"+ LEFT JOIN "itemSupersession" ss ON ss."itemId" = p."id"+ LEFT JOIN "itemPlanning" rsv ON rsv."itemId" = p."id" AND rsv."locationId" = location_id+ LEFT JOIN (+ SELECT "itemId", SUM("supply") AS "incomingSupply"+ FROM supply_data GROUP BY "itemId"+ ) sup ON sup."itemId" = p."id"+ GROUP BY+ p."id",+ p."readableIdWithRevision",+ p."name",+ p."active",+ p."type",+ p."itemTrackingType",+ p."replenishmentSystem",+ p."thumbnailPath",+ p."unitOfMeasureCode",+ p."leadTime",+ p."purchasingBlocked",+ p."lotSize",+ p."reorderingPolicy",+ p."demandAccumulationPeriod",+ p."demandAccumulationSafetyStock",+ p."reorderPoint",+ p."reorderQuantity",+ p."minimumOrderQuantity",+ p."maximumOrderQuantity",+ p."orderMultiple",+ p."quantityOnHand",+ p."maximumInventoryQuantity",+ p."suppliers",+ p."preferredSupplierId",+ p."purchasingUnitOfMeasureCode",+ p."conversionFactor",+ oq."quantityToOrder",+ ss."supersessionMode",+ rsv."minimumReserveQuantity",+ sup."incomingSupply";+$$ LANGUAGE sql SECURITY DEFINER;