Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat: include projections in planning query

Brad Barbina5abe2dd498d
diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
index 34ced4ee7f..8271680ba0 100644
--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
@@ -258,7 +258,7 @@ const InventoryTable = memo(
window.location.href = getLocationPath(selected);
}}
/>
- <mrpFetcher.Form method="post" action={path.to.api.mrp}>
+ <mrpFetcher.Form method="post" action={path.to.api.mrp(locationId)}>
<Tooltip>
<TooltipTrigger>
<Button
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 5caebe9411..0a1791a37a 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -887,7 +887,13 @@ export async function recalculateJobMakeMethodRequirements(
export async function runMRP(
client: SupabaseClient<Database>,
params: {
- type: "company" | "job" | "salesOrder" | "item" | "purchaseOrder";
+ type:
+ | "company"
+ | "location"
+ | "job"
+ | "salesOrder"
+ | "item"
+ | "purchaseOrder";
id: string;
companyId: string;
userId: string;
diff --git a/apps/erp/app/modules/production/ui/Planning/PlanningTable.tsx b/apps/erp/app/modules/production/ui/Planning/PlanningTable.tsx
index 91e22a3d5d..36a50749b2 100644
--- a/apps/erp/app/modules/production/ui/Planning/PlanningTable.tsx
+++ b/apps/erp/app/modules/production/ui/Planning/PlanningTable.tsx
@@ -26,7 +26,9 @@ import {
MethodItemTypeIcon,
Table,
} from "~/components";
+import { Enumerable } from "~/components/Enumerable";
import { useLocations } from "~/components/Form/Location";
+import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
import { useUrlParams } from "~/hooks";
import { itemTypes } from "~/modules/inventory/inventory.models";
import type { action as mrpAction } from "~/routes/api+/mrp";
@@ -37,12 +39,7 @@ type PlanningTableProps = {
data: ProductionPlanningItem[];
count: number;
locationId: string;
- periods: { id: string; startDate: string }[];
-};
-
-type PeriodQuantity = {
- periodId: string;
- quantity: number;
+ periods: { id: string; startDate: string; endDate: string }[];
};
const PlanningTable = memo(
@@ -53,83 +50,44 @@ const PlanningTable = memo(
day: "numeric",
});
- console.log({ data });
-
const numberFormatter = useNumberFormatter();
-
const locations = useLocations();
-
- // Pre-calculate projections for each item
- const projectionsByItem = useMemo(() => {
- const projections = new Map<string, Map<string, number>>();
-
- data.forEach((item) => {
- const itemProjections = new Map<string, number>();
-
- // Convert arrays to maps for efficient lookups
- const demandActuals = new Map(
- ((item.demandActuals as PeriodQuantity[]) || []).map((d) => [
- d.periodId,
- d.quantity,
- ])
- );
- const supplyActuals = new Map(
- ((item.supplyActuals as PeriodQuantity[]) || []).map((s) => [
- s.periodId,
- s.quantity,
- ])
- );
- const demandForecasts = new Map(
- ((item.demandForecasts as PeriodQuantity[]) || []).map((d) => [
- d.periodId,
- d.quantity,
- ])
- );
- const supplyForecasts = new Map(
- ((item.supplyForecasts as PeriodQuantity[]) || []).map((s) => [
- s.periodId,
- s.quantity,
- ])
- );
-
- let runningProjection = item.quantityOnHand;
-
- periods.forEach((period) => {
- runningProjection +=
- (supplyActuals.get(period.id) || 0) +
- (supplyForecasts.get(period.id) || 0);
- runningProjection -=
- (demandActuals.get(period.id) || 0) +
- (demandForecasts.get(period.id) || 0);
- itemProjections.set(period.id, runningProjection);
- });
-
- projections.set(item.id!, itemProjections);
- });
-
- return projections;
- }, [data, periods]);
+ const unitOfMeasures = useUnitOfMeasure();
const columns = useMemo<ColumnDef<ProductionPlanningItem>[]>(() => {
const periodColumns: ColumnDef<ProductionPlanningItem>[] = periods.map(
(period, index) => {
const isCurrentWeek = index === 0;
- const header = isCurrentWeek
- ? "Present Week"
- : `Week of ${dateFormatter.format(
- parseDate(period.startDate).toDate(getLocalTimeZone())
- )}`;
+ const weekNumber = index + 1;
+ const weekKey = `week${weekNumber}` as keyof ProductionPlanningItem;
+ const startDate = parseDate(period.startDate).toDate(
+ getLocalTimeZone()
+ );
+ const endDate = parseDate(period.endDate).toDate(getLocalTimeZone());
return {
- accessorKey: `period.${period.id}`,
- header,
+ accessorKey: weekKey,
+ header: () => (
+ <VStack spacing={0}>
+ <div>
+ {isCurrentWeek ? "Present Week" : `Week ${weekNumber}`}
+ </div>
+ <div className="text-xs text-muted-foreground">
+ {dateFormatter.format(startDate)} -{" "}
+ {dateFormatter.format(endDate)}
+ </div>
+ </VStack>
+ ),
cell: ({ row }) => {
- const projection = projectionsByItem
- .get(row.original.id!)
- ?.get(period.id);
- return projection !== undefined
- ? numberFormatter.format(projection)
- : "-";
+ const value = row.getValue<number>(weekKey);
+ if (value === undefined) return "-";
+ return (
+ <span
+ className={value < 0 ? "text-red-500 font-bold" : undefined}
+ >
+ {numberFormatter.format(value)}
+ </span>
+ );
},
};
}
@@ -158,6 +116,13 @@ const PlanningTable = memo(
</div>
</VStack>
</Hyperlink>
+ <Enumerable
+ value={
+ unitOfMeasures.find(
+ (uom) => uom.value === row.original.unitOfMeasureCode
+ )?.label ?? null
+ }
+ />
</HStack>
),
meta: {
@@ -217,7 +182,7 @@ const PlanningTable = memo(
},
},
];
- }, [params, periods, dateFormatter, numberFormatter, projectionsByItem]);
+ }, [periods, dateFormatter, numberFormatter, params, unitOfMeasures]);
const defaultColumnVisibility = {
active: false,
@@ -249,7 +214,7 @@ const PlanningTable = memo(
window.location.href = getLocationPath(selected);
}}
/>
- <mrpFetcher.Form method="post" action={path.to.api.mrp}>
+ <mrpFetcher.Form method="post" action={path.to.api.mrp(locationId)}>
<Tooltip>
<TooltipTrigger>
<Button
@@ -283,5 +248,5 @@ PlanningTable.displayName = "PlanningTable";
export default PlanningTable;
function getLocationPath(locationId: string) {
- return `${path.to.inventory}?location=${locationId}`;
+ return `${path.to.productionPlanning}?location=${locationId}`;
}
diff --git a/apps/erp/app/routes/api+/mrp.ts b/apps/erp/app/routes/api+/mrp.ts
index 8baf5b9d25..fab9a5746e 100644
--- a/apps/erp/app/routes/api+/mrp.ts
+++ b/apps/erp/app/routes/api+/mrp.ts
@@ -7,13 +7,16 @@ import { runMRP } from "~/modules/production/production.service";
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
+ const url = new URL(request.url);
+ const locationId = url.searchParams.get("location");
+
const { companyId, userId } = await requirePermissions(request, {
update: "inventory",
});
const result = await runMRP(getCarbonServiceRole(), {
- type: "company",
- id: companyId,
+ type: locationId ? "location" : "company",
+ id: locationId ?? companyId,
companyId,
userId,
});
diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.view.planning.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.view.planning.tsx
index 79dbf4f5a5..2c8b6a5c0f 100644
--- a/apps/erp/app/routes/x+/consumable+/$itemId.view.planning.tsx
+++ b/apps/erp/app/routes/x+/consumable+/$itemId.view.planning.tsx
@@ -69,41 +69,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
if (consumablePlanning.error || !consumablePlanning.data) {
- const insertConsumablePlanning = await upsertItemPlanning(client, {
- itemId,
- companyId,
- locationId,
- createdBy: userId,
- });
-
- if (insertConsumablePlanning.error) {
- throw redirect(
- path.to.consumable(itemId),
- await flash(
- request,
- error(
- insertConsumablePlanning.error,
- "Failed to insert consumable planning"
- )
- )
- );
- }
-
- consumablePlanning = await getItemPlanning(
- client,
- itemId,
- companyId,
- locationId
+ throw redirect(
+ path.to.consumable(itemId),
+ await flash(
+ request,
+ error(consumablePlanning.error, "Failed to load consumable planning")
+ )
);
- if (consumablePlanning.error || !consumablePlanning.data) {
- throw redirect(
- path.to.consumable(itemId),
- await flash(
- request,
- error(consumablePlanning.error, "Failed to load consumable planning")
- )
- );
- }
}
return json({
diff --git a/apps/erp/app/routes/x+/material+/$itemId.view.planning.tsx b/apps/erp/app/routes/x+/material+/$itemId.view.planning.tsx
index 42e1c05a13..8728f654cf 100644
--- a/apps/erp/app/routes/x+/material+/$itemId.view.planning.tsx
+++ b/apps/erp/app/routes/x+/material+/$itemId.view.planning.tsx
@@ -69,41 +69,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
if (materialPlanning.error || !materialPlanning.data) {
- const insertMateriallanning = await upsertItemPlanning(client, {
- itemId,
- companyId,
- locationId,
- createdBy: userId,
- });
-
- if (insertMateriallanning.error) {
- throw redirect(
- path.to.material(itemId),
- await flash(
- request,
- error(
- insertMateriallanning.error,
- "Failed to insert material planning"
- )
- )
- );
- }
-
- materialPlanning = await getItemPlanning(
- client,
- itemId,
- companyId,
- locationId
+ throw redirect(
+ path.to.material(itemId),
+ await flash(
+ request,
+ error(materialPlanning.error, "Failed to load material planning")
+ )
);
- if (materialPlanning.error || !materialPlanning.data) {
- throw redirect(
- path.to.material(itemId),
- await flash(
- request,
- error(materialPlanning.error, "Failed to load material planning")
- )
- );
- }
}
return json({
diff --git a/apps/erp/app/routes/x+/part+/$itemId.view.planning.tsx b/apps/erp/app/routes/x+/part+/$itemId.view.planning.tsx
index 8b4a483d03..4cd5e4e34c 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.view.planning.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.view.planning.tsx
@@ -69,33 +69,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
if (partPlanning.error || !partPlanning.data) {
- const insertPartPlanning = await upsertItemPlanning(client, {
- itemId,
- companyId,
- locationId,
- createdBy: userId,
- });
-
- if (insertPartPlanning.error) {
- throw redirect(
- path.to.part(itemId),
- await flash(
- request,
- error(insertPartPlanning.error, "Failed to insert part planning")
- )
- );
- }
-
- partPlanning = await getItemPlanning(client, itemId, companyId, locationId);
- if (partPlanning.error || !partPlanning.data) {
- throw redirect(
- path.to.part(itemId),
- await flash(
- request,
- error(partPlanning.error, "Failed to load part planning")
- )
- );
- }
+ throw redirect(
+ path.to.part(itemId),
+ await flash(
+ request,
+ error(partPlanning.error, "Failed to load part planning")
+ )
+ );
}
return json({
diff --git a/apps/erp/app/routes/x+/production+/planning.tsx b/apps/erp/app/routes/x+/production+/planning.tsx
index 9c3fc706cf..6f3de81b80 100644
--- a/apps/erp/app/routes/x+/production+/planning.tsx
+++ b/apps/erp/app/routes/x+/production+/planning.tsx
@@ -12,11 +12,17 @@ import PlanningTable from "~/modules/production/ui/Planning/PlanningTable";
import { getLocationsList } from "~/modules/resources";
import { getPeriods } from "~/modules/shared/shared.service";
import { getUserDefaults } from "~/modules/users/users.server";
+import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
import { getGenericQueryFilters } from "~/utils/query";
const WEEKS_TO_PLAN = 12 * 4;
+export const handle: Handle = {
+ breadcrumb: "Planning",
+ to: path.to.productionPlanning,
+};
+
export async function loader({ request }: LoaderFunctionArgs) {
const { client, companyId, userId } = await requirePermissions(request, {
view: "production",
diff --git a/apps/erp/app/routes/x+/tool+/$itemId.view.planning.tsx b/apps/erp/app/routes/x+/tool+/$itemId.view.planning.tsx
index e49c82fea2..8f1361ac71 100644
--- a/apps/erp/app/routes/x+/tool+/$itemId.view.planning.tsx
+++ b/apps/erp/app/routes/x+/tool+/$itemId.view.planning.tsx
@@ -69,33 +69,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
if (toolPlanning.error || !toolPlanning.data) {
- const insertToolPlanning = await upsertItemPlanning(client, {
- itemId,
- companyId,
- locationId,
- createdBy: userId,
- });
-
- if (insertToolPlanning.error) {
- throw redirect(
- path.to.tool(itemId),
- await flash(
- request,
- error(insertToolPlanning.error, "Failed to insert tool planning")
- )
- );
- }
-
- toolPlanning = await getItemPlanning(client, itemId, companyId, locationId);
- if (toolPlanning.error || !toolPlanning.data) {
- throw redirect(
- path.to.tool(itemId),
- await flash(
- request,
- error(toolPlanning.error, "Failed to load tool planning")
- )
- );
- }
+ throw redirect(
+ path.to.tool(itemId),
+ await flash(
+ request,
+ error(toolPlanning.error, "Failed to load tool planning")
+ )
+ );
}
return json({
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index bfc281bfef..6d0d706414 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -68,7 +68,10 @@ export const path = {
materialForms: `${api}/items/forms`,
materialSubstances: `${api}/items/substances`,
messagingNotify: `${api}/messaging/notify`,
- mrp: `${api}/mrp`,
+ mrp: (locationId?: string) =>
+ generatePath(
+ `${api}/mrp${locationId ? `?location=${locationId}` : ""}`
+ ),
modelUpload: `${api}/model/upload`,
onShapeBom: (documentId: string, versionId: string, elementId: string) =>
generatePath(
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 3c5a63b6b0..623ff89329 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -38097,14 +38097,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey";
- columns: ["id"];
+ columns: ["supplierLocationId"];
isOneToOne: false;
referencedRelation: "supplierLocation";
referencedColumns: ["id"];
},
{
foreignKeyName: "partner_id_fkey";
- columns: ["supplierLocationId"];
+ columns: ["id"];
isOneToOne: false;
referencedRelation: "supplierLocation";
referencedColumns: ["id"];
@@ -45127,15 +45127,12 @@ export type Database = {
};
Returns: {
id: string;
- readableId: string;
readableIdWithRevision: string;
name: string;
active: boolean;
type: Database["public"]["Enums"]["itemType"];
itemTrackingType: Database["public"]["Enums"]["itemTrackingType"];
replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"];
- materialSubstanceId: string;
- materialFormId: string;
thumbnailPath: string;
unitOfMeasureCode: string;
leadTime: number;
@@ -45153,10 +45150,58 @@ export type Database = {
maximumOrderQuantity: number;
orderMultiple: number;
quantityOnHand: number;
- demandActuals: Json;
- supplyActuals: Json;
- demandForecasts: Json;
- supplyForecasts: Json;
+ week1: number;
+ week2: number;
+ week3: number;
+ week4: number;
+ week5: number;
+ week6: number;
+ week7: number;
+ week8: number;
+ week9: number;
+ week10: number;
+ week11: number;
+ week12: number;
+ week13: number;
+ week14: number;
+ week15: number;
+ week16: number;
+ week17: number;
+ week18: number;
+ week19: number;
+ week20: number;
+ week21: number;
+ week22: number;
+ week23: number;
+ week24: number;
+ week25: number;
+ week26: number;
+ week27: number;
+ week28: number;
+ week29: number;
+ week30: number;
+ week31: number;
+ week32: number;
+ week33: number;
+ week34: number;
+ week35: number;
+ week36: number;
+ week37: number;
+ week38: number;
+ week39: number;
+ week40: number;
+ week41: number;
+ week42: number;
+ week43: number;
+ week44: number;
+ week45: number;
+ week46: number;
+ week47: number;
+ week48: number;
+ week49: number;
+ week50: number;
+ week51: number;
+ week52: number;
}[];
};
get_quote_methods: {
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 3c5a63b6b0..623ff89329 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -38097,14 +38097,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey";
- columns: ["id"];
+ columns: ["supplierLocationId"];
isOneToOne: false;
referencedRelation: "supplierLocation";
referencedColumns: ["id"];
},
{
foreignKeyName: "partner_id_fkey";
- columns: ["supplierLocationId"];
+ columns: ["id"];
isOneToOne: false;
referencedRelation: "supplierLocation";
referencedColumns: ["id"];
@@ -45127,15 +45127,12 @@ export type Database = {
};
Returns: {
id: string;
- readableId: string;
readableIdWithRevision: string;
name: string;
active: boolean;
type: Database["public"]["Enums"]["itemType"];
itemTrackingType: Database["public"]["Enums"]["itemTrackingType"];
replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"];
- materialSubstanceId: string;
- materialFormId: string;
thumbnailPath: string;
unitOfMeasureCode: string;
leadTime: number;
@@ -45153,10 +45150,58 @@ export type Database = {
maximumOrderQuantity: number;
orderMultiple: number;
quantityOnHand: number;
- demandActuals: Json;
- supplyActuals: Json;
- demandForecasts: Json;
- supplyForecasts: Json;
+ week1: number;
+ week2: number;
+ week3: number;
+ week4: number;
+ week5: number;
+ week6: number;
+ week7: number;
+ week8: number;
+ week9: number;
+ week10: number;
+ week11: number;
+ week12: number;
+ week13: number;
+ week14: number;
+ week15: number;
+ week16: number;
+ week17: number;
+ week18: number;
+ week19: number;
+ week20: number;
+ week21: number;
+ week22: number;
+ week23: number;
+ week24: number;
+ week25: number;
+ week26: number;
+ week27: number;
+ week28: number;
+ week29: number;
+ week30: number;
+ week31: number;
+ week32: number;
+ week33: number;
+ week34: number;
+ week35: number;
+ week36: number;
+ week37: number;
+ week38: number;
+ week39: number;
+ week40: number;
+ week41: number;
+ week42: number;
+ week43: number;
+ week44: number;
+ week45: number;
+ week46: number;
+ week47: number;
+ week48: number;
+ week49: number;
+ week50: number;
+ week51: number;
+ week52: number;
}[];
};
get_quote_methods: {
diff --git a/packages/database/supabase/functions/mrp/index.ts b/packages/database/supabase/functions/mrp/index.ts
index 8c87f2bd31..8036c3a99e 100644
--- a/packages/database/supabase/functions/mrp/index.ts
+++ b/packages/database/supabase/functions/mrp/index.ts
@@ -30,6 +30,12 @@ const payloadValidator = z.discriminatedUnion("type", [
companyId: z.string(),
userId: z.string(),
}),
+ z.object({
+ type: z.literal("location"),
+ id: z.string(),
+ companyId: z.string(),
+ userId: z.string(),
+ }),
z.object({
type: z.literal("item"),
id: z.string(),
@@ -296,8 +302,8 @@ serve(async (req: Request) => {
const dueDate = line.dueDate
? parseDate(line.dueDate)
: line.deadlineType === "No Deadline"
- ? today
- : today.add({ days: 30 });
+ ? today.add({ days: 30 })
+ : today;
// If required date is before today, use first period
let period;
diff --git a/packages/database/supabase/migrations/20250616131548_production-planning.sql b/packages/database/supabase/migrations/20250616131548_production-planning.sql
index f6ddae2115..107bc3e52e 100644
--- a/packages/database/supabase/migrations/20250616131548_production-planning.sql
+++ b/packages/database/supabase/migrations/20250616131548_production-planning.sql
@@ -1,8 +1,14 @@
DROP FUNCTION IF EXISTS get_production_planning;
+
+-- Add indexes for supply and demand tables
+CREATE INDEX IF NOT EXISTS "supplyActual_companyId_locationId_idx" ON "supplyActual" ("companyId", "locationId");
+CREATE INDEX IF NOT EXISTS "supplyForecast_companyId_locationId_idx" ON "supplyForecast" ("companyId", "locationId");
+CREATE INDEX IF NOT EXISTS "demandActual_companyId_locationId_idx" ON "demandActual" ("companyId", "locationId");
+CREATE INDEX IF NOT EXISTS "demandForecast_companyId_locationId_idx" ON "demandForecast" ("companyId", "locationId");
+
CREATE OR REPLACE FUNCTION get_production_planning(company_id TEXT, location_id TEXT, periods TEXT[])
RETURNS TABLE (
"id" TEXT,
- "readableId" TEXT,
"readableIdWithRevision" TEXT,
"name" TEXT,
"active" BOOLEAN,
@@ -26,172 +32,489 @@ CREATE OR REPLACE FUNCTION get_production_planning(company_id TEXT, location_id
"maximumOrderQuantity" INTEGER,
"orderMultiple" INTEGER,
"quantityOnHand" NUMERIC,
- "demandActuals" JSONB,
- "supplyActuals" JSONB,
- "demandForecasts" JSONB,
- "supplyForecasts" JSONB
+ "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 $$
- BEGIN
- RETURN QUERY
-
-WITH
- demand_actuals_agg AS (
+ WITH RECURSIVE
+ -- Pre-aggregate supply and demand data
+ supply_data AS (
SELECT
"itemId",
"periodId",
- SUM("actualQuantity") AS "quantity"
- FROM
- "demandActual" da
- WHERE
- da."companyId" = company_id
- AND da."locationId" = location_id
- GROUP BY da."itemId", da."periodId"
- ),
- demand_actuals AS (
- SELECT
- "itemId",
- COALESCE(
- json_agg(
- json_build_object(
- 'periodId', "periodId",
- 'quantity', "quantity"
- )
- ) FILTER (WHERE "periodId" IS NOT NULL),
- '[]'
- )::jsonb AS "demandActuals"
- FROM demand_actuals_agg
- GROUP BY "itemId"
- ),
- demand_forecasts_agg AS (
- SELECT
- "itemId",
- "periodId",
- SUM("forecastQuantity") AS "quantity"
- FROM
- "demandForecast" df
- WHERE df."companyId" = company_id AND df."locationId" = location_id
- GROUP BY df."itemId", df."periodId"
- ),
- demand_forecasts AS (
- SELECT
- "itemId",
- COALESCE(
- json_agg(
- json_build_object(
- 'periodId', "periodId",
- 'quantity', "quantity"
- )
- ) FILTER (WHERE "periodId" IS NOT NULL),
- '[]'
- )::jsonb AS "demandForecasts"
- FROM demand_forecasts_agg
- GROUP BY "itemId"
+ 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"
),
- supply_actuals_agg AS (
+ demand_data AS (
SELECT
"itemId",
"periodId",
- SUM("actualQuantity") AS "quantity"
- FROM
- "supplyActual" sa
- WHERE
- sa."companyId" = company_id
- AND sa."locationId" = location_id
- GROUP BY sa."itemId", sa."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)
+ ) combined
+ GROUP BY "itemId", "periodId"
),
- supply_actuals AS (
+ -- Base data for items with early filtering
+ base_items AS (
SELECT
- "itemId",
- COALESCE(
- json_agg(
- json_build_object(
- 'periodId', "periodId",
- 'quantity', "quantity"
- )
- ) FILTER (WHERE "periodId" IS NOT NULL),
- '[]'
- )::jsonb AS "supplyActuals"
- FROM supply_actuals_agg
- GROUP BY "itemId"
+ 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."safetyStockQuantity",
+ ip."safetyStockLeadTime",
+ ip."demandAccumulationPeriod",
+ ip."demandAccumulationIncludesInventory",
+ ip."reorderPoint",
+ ip."reorderQuantity",
+ ip."reorderMaximumInventory",
+ 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"
+ FROM "item" i
+ INNER JOIN "itemReplenishment" ir ON i."id" = ir."itemId"
+ INNER JOIN "itemPlanning" ip ON i."id" = ip."itemId"
+ LEFT JOIN "modelUpload" mu ON mu."id" = i."modelUploadId"
+ WHERE i."companyId" = company_id
+ AND i."replenishmentSystem" = 'Make'
+ AND i."active" = TRUE
),
- supply_forecasts_agg AS (
+ -- Recursive calculation of projections with optimized joins
+ projections AS (
+ -- Base case: first period
SELECT
- "itemId",
- "periodId",
- SUM("forecastQuantity") AS "quantity"
- FROM
- "supplyForecast" sf
- WHERE sf."companyId" = company_id AND sf."locationId" = location_id
- GROUP BY sf."itemId", sf."periodId"
- ),
- supply_forecasts AS (
+ 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
+
+ -- Recursive case: subsequent periods
SELECT
- "itemId",
- COALESCE(
- json_agg(
- json_build_object(
- 'periodId', "periodId",
- 'quantity', "quantity"
- )
- ) FILTER (WHERE "periodId" IS NOT NULL),
- '[]'
- )::jsonb AS "supplyForecasts"
- FROM supply_forecasts_agg
- GROUP BY "itemId"
- ),
- item_ledgers AS (
- SELECT "itemId", SUM("quantity") AS "quantityOnHand"
- FROM "itemLedger"
- WHERE "companyId" = company_id
- AND "locationId" = location_id
- GROUP BY "itemId"
+ p."id",
+ p."readableIdWithRevision",
+ p."name",
+ p."active",
+ p."type",
+ p."itemTrackingType",
+ p."replenishmentSystem",
+ p."thumbnailPath",
+ p."unitOfMeasureCode",
+ p."leadTime",
+ p."manufacturingBlocked",
+ p."lotSize",
+ p."reorderingPolicy",
+ p."safetyStockQuantity",
+ p."safetyStockLeadTime",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationIncludesInventory",
+ p."reorderPoint",
+ p."reorderQuantity",
+ p."reorderMaximumInventory",
+ p."minimumOrderQuantity",
+ p."maximumOrderQuantity",
+ p."orderMultiple",
+ 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)
)
-
-SELECT
- i."id",
- i."readableId",
- 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."safetyStockQuantity",
- ip."safetyStockLeadTime",
- ip."demandAccumulationPeriod",
- ip."demandAccumulationIncludesInventory",
- ip."reorderPoint",
- ip."reorderQuantity",
- ip."reorderMaximumInventory",
- ip."minimumOrderQuantity",
- ip."maximumOrderQuantity",
- ip."orderMultiple",
- COALESCE(il."quantityOnHand", 0) AS "quantityOnHand",
- COALESCE(da."demandActuals", '[]'::jsonb) AS "demandActuals",
- COALESCE(sa."supplyActuals", '[]'::jsonb) AS "supplyActuals",
- COALESCE(df."demandForecasts", '[]'::jsonb) AS "demandForecasts",
- COALESCE(sf."supplyForecasts", '[]'::jsonb) AS "supplyForecasts"
-FROM
- "item" i
+ -- Final result with optimized pivot
+ SELECT
+ p."id",
+ p."readableIdWithRevision",
+ p."name",
+ p."active",
+ p."type",
+ p."itemTrackingType",
+ p."replenishmentSystem",
+ p."thumbnailPath",
+ p."unitOfMeasureCode",
+ p."leadTime",
+ p."manufacturingBlocked",
+ p."lotSize",
+ p."reorderingPolicy",
+ p."safetyStockQuantity",
+ p."safetyStockLeadTime",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationIncludesInventory",
+ p."reorderPoint",
+ p."reorderQuantity",
+ p."reorderMaximumInventory",
+ p."minimumOrderQuantity",
+ p."maximumOrderQuantity",
+ p."orderMultiple",
+ p."quantityOnHand",
+ 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
+ GROUP BY
+ p."id",
+ p."readableIdWithRevision",
+ p."name",
+ p."active",
+ p."type",
+ p."itemTrackingType",
+ p."replenishmentSystem",
+ p."thumbnailPath",
+ p."unitOfMeasureCode",
+ p."leadTime",
+ p."manufacturingBlocked",
+ p."lotSize",
+ p."reorderingPolicy",
+ p."safetyStockQuantity",
+ p."safetyStockLeadTime",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationIncludesInventory",
+ p."reorderPoint",
+ p."reorderQuantity",
+ p."reorderMaximumInventory",
+ p."minimumOrderQuantity",
+ p."maximumOrderQuantity",
+ p."orderMultiple",
+ p."quantityOnHand";
+$$ LANGUAGE sql SECURITY DEFINER;
+
+
+-- add deadlineType to openProductionOrders
+DROP VIEW IF EXISTS "openProductionOrders";
+CREATE OR REPLACE VIEW "openProductionOrders" AS (
+ SELECT
+ j."id",
+ j."itemId",
+ j."productionQuantity" - j."quantityReceivedToInventory" AS "quantityToReceive",
+ j."unitOfMeasureCode",
+ j."companyId",
+ i."replenishmentSystem",
+ i."itemTrackingType",
+ ir."leadTime" AS "leadTime",
+ j."locationId",
+ j."dueDate",
+ j."deadlineType"
+ FROM "job" j
+ INNER JOIN "item" i ON j."itemId" = i."id"
INNER JOIN "itemReplenishment" ir ON i."id" = ir."itemId"
- INNER JOIN "itemPlanning" ip ON i."id" = ip."itemId"
- LEFT JOIN item_ledgers il ON i."id" = il."itemId"
- LEFT JOIN demand_actuals da ON i."id" = da."itemId"
- LEFT JOIN demand_forecasts df ON i."id" = df."itemId"
- LEFT JOIN supply_actuals sa ON i."id" = sa."itemId"
- LEFT JOIN supply_forecasts sf ON i."id" = sf."itemId"
- LEFT JOIN "modelUpload" mu ON mu."id" = i."modelUploadId"
-WHERE i."companyId" = company_id
- AND i."replenishmentSystem" = 'Make'
- AND i."active" = TRUE;
- END;
+ WHERE j."status" IN (
+ 'Planned',
+ 'Ready',
+ 'In Progress',
+ 'Paused'
+ )
+ AND j."salesOrderId" IS NULL
+);
+
+
+
+
+
+CREATE OR REPLACE FUNCTION public.create_item_related_records()
+RETURNS TRIGGER AS $$
+BEGIN
+ INSERT INTO public."itemCost"("itemId", "costingMethod", "createdBy", "companyId")
+ VALUES (new.id, 'FIFO', new."createdBy", new."companyId");
+
+ INSERT INTO public."itemReplenishment"("itemId", "createdBy", "companyId")
+ VALUES (new.id, new."createdBy", new."companyId");
+
+ INSERT INTO public."itemUnitSalePrice"("itemId", "currencyCode", "createdBy", "companyId")
+ VALUES (new.id, 'USD', new."createdBy", new."companyId");
+
+ -- Insert itemPlanning records for each location
+ INSERT INTO public."itemPlanning"("itemId", "locationId", "createdBy", "companyId")
+ SELECT
+ new.id,
+ l.id,
+ new."createdBy",
+ new."companyId"
+ FROM public."location" l
+ WHERE l."companyId" = new."companyId";
+
+ RETURN new;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Insert missing itemPlanning records for existing items and locations
+INSERT INTO public."itemPlanning" ("itemId", "locationId", "createdBy", "companyId", "createdAt", "updatedAt")
+SELECT DISTINCT
+ i.id AS "itemId",
+ l.id AS "locationId",
+ i."createdBy",
+ i."companyId",
+ NOW(),
+ NOW()
+FROM public."item" i
+CROSS JOIN public."location" l
+WHERE
+ l."companyId" = i."companyId"
+ AND NOT EXISTS (
+ SELECT 1
+ FROM public."itemPlanning" ip
+ WHERE ip."itemId" = i.id
+ AND ip."locationId" = l.id
+ );
+
+
+
+DROP TRIGGER IF EXISTS create_location ON public."location";
+DROP FUNCTION IF EXISTS public.create_posting_groups_for_location;
+CREATE OR REPLACE FUNCTION public.create_related_records_for_location()
+RETURNS TRIGGER AS $$
+DECLARE
+ item_posting_group RECORD;
+ account_defaults RECORD;
+BEGIN
+ -- create itemPlanning records for the new location
+ INSERT INTO public."itemPlanning" ("itemId", "locationId", "createdBy", "companyId", "createdAt", "updatedAt")
+ SELECT
+ i.id AS "itemId",
+ new.id AS "locationId",
+ i."createdBy",
+ i."companyId",
+ NOW(),
+ NOW()
+ FROM public."item" i
+ WHERE i."companyId" = new."companyId";
+
+ SELECT * INTO account_defaults FROM "accountDefault" WHERE "companyId" = new."companyId";
+
+ FOR item_posting_group IN SELECT "id" FROM "itemPostingGroup"
+ LOOP
+ INSERT INTO "postingGroupInventory" (
+ "itemPostingGroupId",
+ "locationId",
+ "costOfGoodsSoldAccount",
+ "inventoryAccount",
+ "inventoryInterimAccrualAccount",
+ "inventoryReceivedNotInvoicedAccount",
+ "inventoryInvoicedNotReceivedAccount",
+ "inventoryShippedNotInvoicedAccount",
+ "workInProgressAccount",
+ "directCostAppliedAccount",
+ "overheadCostAppliedAccount",
+ "purchaseVarianceAccount",
+ "inventoryAdjustmentVarianceAccount",
+ "materialVarianceAccount",
+ "capacityVarianceAccount",
+ "overheadAccount",
+ "companyId",
+ "updatedBy"
+ ) VALUES (
+ item_posting_group."id",
+ new."id",
+ account_defaults."costOfGoodsSoldAccount",
+ account_defaults."inventoryAccount",
+ account_defaults."inventoryInterimAccrualAccount",
+ account_defaults."inventoryReceivedNotInvoicedAccount",
+ account_defaults."inventoryInvoicedNotReceivedAccount",
+ account_defaults."inventoryShippedNotInvoicedAccount",
+ account_defaults."workInProgressAccount",
+ account_defaults."directCostAppliedAccount",
+ account_defaults."overheadCostAppliedAccount",
+ account_defaults."purchaseVarianceAccount",
+ account_defaults."inventoryAdjustmentVarianceAccount",
+ account_defaults."materialVarianceAccount",
+ account_defaults."capacityVarianceAccount",
+ account_defaults."overheadAccount",
+ new."companyId",
+ new."createdBy"
+ );
+ END LOOP;
+
+ -- insert the null item group
+ INSERT INTO "postingGroupInventory" (
+ "itemPostingGroupId",
+ "locationId",
+ "costOfGoodsSoldAccount",
+ "inventoryAccount",
+ "inventoryInterimAccrualAccount",
+ "inventoryReceivedNotInvoicedAccount",
+ "inventoryInvoicedNotReceivedAccount",
+ "inventoryShippedNotInvoicedAccount",
+ "workInProgressAccount",
+ "directCostAppliedAccount",
+ "overheadCostAppliedAccount",
+ "purchaseVarianceAccount",
+ "inventoryAdjustmentVarianceAccount",
+ "materialVarianceAccount",
+ "capacityVarianceAccount",
+ "overheadAccount",
+ "companyId",
+ "updatedBy"
+ ) VALUES (
+ NULL,
+ new."id",
+ account_defaults."costOfGoodsSoldAccount",
+ account_defaults."inventoryAccount",
+ account_defaults."inventoryInterimAccrualAccount",
+ account_defaults."inventoryReceivedNotInvoicedAccount",
+ account_defaults."inventoryInvoicedNotReceivedAccount",
+ account_defaults."inventoryShippedNotInvoicedAccount",
+ account_defaults."workInProgressAccount",
+ account_defaults."directCostAppliedAccount",
+ account_defaults."overheadCostAppliedAccount",
+ account_defaults."purchaseVarianceAccount",
+ account_defaults."inventoryAdjustmentVarianceAccount",
+ account_defaults."materialVarianceAccount",
+ account_defaults."capacityVarianceAccount",
+ account_defaults."overheadAccount",
+ new."companyId",
+ new."createdBy"
+ );
+
+ RETURN new;
+END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+CREATE TRIGGER create_location
+ AFTER INSERT on public."location"
+ FOR EACH ROW EXECUTE PROCEDURE public.create_related_records_for_location();