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: trigger mrp from background job and on events

Brad Barbin30dc4bd439b2
diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
index 5f61ef3343..6f1ca74f10 100644
--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
@@ -1,17 +1,27 @@
-import { Checkbox, Combobox, HStack, VStack } from "@carbon/react";
+import {
+ Button,
+ Checkbox,
+ Combobox,
+ HStack,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+ VStack,
+} from "@carbon/react";
+import { useFetcher } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useMemo } from "react";
import {
LuBookMarked,
LuBox,
LuCheck,
- LuFactory,
+ LuCirclePlay,
LuGlassWater,
+ LuMoveDown,
+ LuMoveUp,
LuPackage,
LuRuler,
LuShapes,
- LuShoppingBag,
- LuShoppingCart,
} from "react-icons/lu";
import {
Hyperlink,
@@ -23,6 +33,7 @@ import { Enumerable } from "~/components/Enumerable";
import { useLocations } from "~/components/Form/Location";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
import { useUrlParams } from "~/hooks";
+import type { action as mrpAction } from "~/routes/api+/mrp";
import type { ListItem } from "~/types";
import { path } from "~/utils/path";
import { itemTypes } from "../../inventory.models";
@@ -88,7 +99,7 @@ const InventoryTable = memo(
header: "On Purchase Order",
cell: ({ row }) => row.original.quantityOnPurchaseOrder,
meta: {
- icon: <LuShoppingCart />,
+ icon: <LuMoveUp className="text-emerald-500" />,
},
},
{
@@ -96,7 +107,15 @@ const InventoryTable = memo(
header: "On Jobs",
cell: ({ row }) => row.original.quantityOnProductionOrder,
meta: {
- icon: <LuFactory />,
+ icon: <LuMoveUp className="text-emerald-500" />,
+ },
+ },
+ {
+ accessorKey: "quantityOnProductionDemand",
+ header: "On Jobs",
+ cell: ({ row }) => row.original.quantityOnProductionDemand,
+ meta: {
+ icon: <LuMoveDown className="text-red-500" />,
},
},
{
@@ -104,7 +123,7 @@ const InventoryTable = memo(
header: "On Sales Order",
cell: ({ row }) => row.original.quantityOnSalesOrder,
meta: {
- icon: <LuShoppingBag />,
+ icon: <LuMoveDown className="text-red-500" />,
},
},
{
@@ -218,6 +237,8 @@ const InventoryTable = memo(
left: ["readableIdWithRevision"],
};
+ const mrpFetcher = useFetcher<typeof mrpAction>();
+
return (
<Table<InventoryItem>
count={count}
@@ -226,17 +247,37 @@ const InventoryTable = memo(
defaultColumnVisibility={defaultColumnVisibility}
defaultColumnPinning={defaultColumnPinning}
primaryAction={
- <Combobox
- asButton
- size="sm"
- value={locationId}
- options={locations}
- onChange={(selected) => {
- // hard refresh because initialValues update has no effect otherwise
- window.location.href = getLocationPath(selected);
- }}
- className="w-64"
- />
+ <div className="flex items-center gap-2">
+ <Combobox
+ asButton
+ size="sm"
+ value={locationId}
+ options={locations}
+ onChange={(selected) => {
+ // hard refresh because initialValues update has no effect otherwise
+ window.location.href = getLocationPath(selected);
+ }}
+ />
+ <mrpFetcher.Form method="post" action={path.to.api.mrp}>
+ <Tooltip>
+ <TooltipTrigger>
+ <Button
+ type="submit"
+ variant="secondary"
+ rightIcon={<LuCirclePlay />}
+ isDisabled={mrpFetcher.state !== "idle"}
+ isLoading={mrpFetcher.state !== "idle"}
+ >
+ MRP
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ MRP runs automatically every 3 hours, but you can run it
+ manually here.
+ </TooltipContent>
+ </Tooltip>
+ </mrpFetcher.Form>
+ </div>
}
title="Inventory"
table="inventory"
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index cbbceea7a7..e17854498d 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -816,12 +816,22 @@ export async function recalculateJobRequirements(
userId: string;
}
) {
- return client.functions.invoke("recalculate", {
+ const recalculateResult = await client.functions.invoke("recalculate", {
body: {
type: "jobRequirements",
...params,
},
});
+ if (recalculateResult.error) {
+ return recalculateResult;
+ }
+
+ return runMRP(client, {
+ type: "job",
+ id: params.id,
+ companyId: params.companyId,
+ userId: params.userId,
+ });
}
export async function recalculateJobMakeMethodRequirements(
@@ -840,6 +850,22 @@ export async function recalculateJobMakeMethodRequirements(
});
}
+export async function runMRP(
+ client: SupabaseClient<Database>,
+ params: {
+ type: "company" | "job" | "salesOrder";
+ id: string;
+ companyId: string;
+ userId: string;
+ }
+) {
+ return client.functions.invoke("mrp", {
+ body: {
+ ...params,
+ },
+ });
+}
+
export async function updateJobBatchNumber(
client: SupabaseClient<Database>,
trackedEntityId: string,
@@ -1235,12 +1261,20 @@ export async function upsertJobMethod(
configuration?: any;
}
) {
- return client.functions.invoke("get-method", {
+ const getMethodResult = await client.functions.invoke("get-method", {
body: {
type,
...jobMethod,
},
});
+ if (getMethodResult.error) {
+ return getMethodResult;
+ }
+ return recalculateJobRequirements(client, {
+ id: jobMethod.targetId,
+ companyId: jobMethod.companyId,
+ userId: jobMethod.userId,
+ });
}
export async function upsertJobMaterialMakeMethod(
diff --git a/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx b/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx
index 92d6b314d9..ff2d6ba4d2 100644
--- a/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx
+++ b/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx
@@ -19,13 +19,6 @@ const productionRoutes: AuthenticatedRouteGroup[] = [
icon: <LuHardHat />,
table: "job",
},
- {
- name: "Procedures",
- to: path.to.procedures,
- icon: <LuWaypoints />,
- table: "procedure",
- role: "employee",
- },
{
name: "Schedule",
to: path.to.schedule,
@@ -36,6 +29,13 @@ const productionRoutes: AuthenticatedRouteGroup[] = [
{
name: "Configure",
routes: [
+ {
+ name: "Procedures",
+ to: path.to.procedures,
+ icon: <LuWaypoints />,
+ table: "procedure",
+ role: "employee",
+ },
{
name: "Scrap Reasons",
to: path.to.scrapReasons,
diff --git a/apps/erp/app/routes/api+/mrp.ts b/apps/erp/app/routes/api+/mrp.ts
new file mode 100644
index 0000000000..8baf5b9d25
--- /dev/null
+++ b/apps/erp/app/routes/api+/mrp.ts
@@ -0,0 +1,22 @@
+import { assertIsPost, getCarbonServiceRole } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { ActionFunctionArgs } from "@vercel/remix";
+import { json } from "@vercel/remix";
+import { runMRP } from "~/modules/production/production.service";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+
+ const { companyId, userId } = await requirePermissions(request, {
+ update: "inventory",
+ });
+
+ const result = await runMRP(getCarbonServiceRole(), {
+ type: "company",
+ id: companyId,
+ companyId,
+ userId,
+ });
+
+ return json(result);
+}
diff --git a/apps/erp/app/routes/x+/_index.tsx b/apps/erp/app/routes/x+/_index.tsx
index 3144da266b..b290017745 100644
--- a/apps/erp/app/routes/x+/_index.tsx
+++ b/apps/erp/app/routes/x+/_index.tsx
@@ -1,31 +1,12 @@
-import { getCarbonServiceRole } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
import { Heading, cn } from "@carbon/react";
import { getLocalTimeZone } from "@internationalized/date";
import { useLocale } from "@react-aria/i18n";
import { Link } from "@remix-run/react";
-import type { LoaderFunctionArgs } from "@vercel/remix";
import { useMemo, type ComponentProps } from "react";
import { LuHardHat } from "react-icons/lu";
import { useModules, useUser } from "~/hooks";
import type { Authenticated, NavItem } from "~/types";
-export async function loader({ request }: LoaderFunctionArgs) {
- const { companyId, userId } = await requirePermissions(request, {});
- const serviceRole = getCarbonServiceRole();
-
- const result = await serviceRole.functions.invoke("demand-forecast", {
- body: {
- type: "company",
- companyId,
- userId,
- },
- });
-
- console.log(result);
- return null;
-}
-
export default function AppIndexRoute() {
const user = useUser();
// const permissions = usePermissions();
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.tsx
index 4dbd3309c1..a569246326 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
@@ -115,6 +115,28 @@ export async function action({ request, params }: ActionFunctionArgs) {
)
);
}
+ } else {
+ const recalculateResult = await recalculateJobMakeMethodRequirements(
+ client,
+ {
+ id: validation.data.jobMakeMethodId,
+ companyId,
+ userId,
+ }
+ );
+
+ if (recalculateResult.error) {
+ return json(
+ { id: jobMaterialId },
+ await flash(
+ request,
+ error(
+ recalculateResult.error,
+ "Failed to recalculate job make method requirements"
+ )
+ )
+ );
+ }
}
return json({
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx
index c3ac4f7d90..f19d077964 100644
--- a/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx
@@ -9,6 +9,7 @@ import { json, type ActionFunctionArgs } from "@vercel/remix";
import { parseAcceptLanguage } from "intl-parse-accept-language";
import { getPaymentTermsList } from "~/modules/accounting";
import { upsertDocument } from "~/modules/documents";
+import { runMRP } from "~/modules/production/production.service";
import {
getCustomerContact,
getSalesOrder,
@@ -283,6 +284,13 @@ export async function action(args: ActionFunctionArgs) {
});
}
+ await runMRP(getCarbonServiceRole(), {
+ type: "salesOrder",
+ id: orderId,
+ companyId: companyId,
+ userId: userId,
+ });
+
return json({
success: true,
message: "Sales order confirmed",
diff --git a/apps/erp/app/trigger/mrp.ts b/apps/erp/app/trigger/mrp.ts
new file mode 100644
index 0000000000..cc4e21cf47
--- /dev/null
+++ b/apps/erp/app/trigger/mrp.ts
@@ -0,0 +1,55 @@
+import { getCarbonServiceRole } from "@carbon/auth";
+import { schedules } from "@trigger.dev/sdk/v3";
+import { runMRP } from "~/modules/production/production.service";
+
+const serviceRole = getCarbonServiceRole();
+
+export const mrp = schedules.task({
+ id: "mrp",
+ // Run every 3 hours
+ cron: "0 */3 * * *",
+ run: async () => {
+ console.log(
+ `🕒 Scheduled MRP Calculation Started: ${new Date().toISOString()}`
+ );
+
+ const companies = await serviceRole.from("company").select("id, name");
+ if (companies.error) {
+ console.error(
+ `❌ Failed to get companies: ${
+ companies.error instanceof Error
+ ? companies.error.message
+ : String(companies.error)
+ }`
+ );
+ return;
+ }
+ for await (const company of companies.data) {
+ try {
+ const result = await runMRP(serviceRole, {
+ type: "company",
+ id: company.id,
+ companyId: company.id,
+ userId: "system",
+ });
+ if (result.error) {
+ console.error(
+ `❌ Failed to run MRP for company ${company.id}: ${
+ result.error instanceof Error
+ ? result.error.message
+ : String(result.error)
+ }`
+ );
+ } else {
+ console.log(`✅ Successfully ran MRP for company ${company.name}`);
+ }
+ } catch (error) {
+ console.error(
+ `Unexpected error in MRP run task: ${
+ error instanceof Error ? error.message : String(error)
+ }`
+ );
+ }
+ }
+ },
+});
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 3d86f88aeb..2aadf2221e 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -63,6 +63,7 @@ export const path = {
materialForms: `${api}/items/forms`,
materialSubstances: `${api}/items/substances`,
messagingNotify: `${api}/messaging/notify`,
+ mrp: `${api}/mrp`,
modelUpload: `${api}/model/upload`,
onShapeBom: (documentId: string, versionId: string, elementId: string) =>
generatePath(
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index d968c46b15..77208022d5 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -15903,6 +15903,81 @@ export default {
tags: ["methodOperationParameter"],
},
},
+ "/openJobMaterialLines": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.jobId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.itemId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.quantityToIssue",
+ },
+ {
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.unitOfMeasureCode",
+ },
+ {
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.replenishmentSystem",
+ },
+ {
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.itemTrackingType",
+ },
+ {
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.leadTime",
+ },
+ {
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.locationId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.openJobMaterialLines.dueDate",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/order",
+ },
+ {
+ $ref: "#/parameters/range",
+ },
+ {
+ $ref: "#/parameters/rangeUnit",
+ },
+ {
+ $ref: "#/parameters/offset",
+ },
+ {
+ $ref: "#/parameters/limit",
+ },
+ {
+ $ref: "#/parameters/preferCount",
+ },
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/openJobMaterialLines",
+ },
+ type: "array",
+ },
+ },
+ "206": {
+ description: "Partial Content",
+ },
+ },
+ tags: ["openJobMaterialLines"],
+ },
+ },
"/sequence": {
get: {
parameters: [
@@ -23757,6 +23832,12 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperation.procedureId",
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.startDate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.dueDate",
+ },
{
$ref: "#/parameters/select",
},
@@ -23930,6 +24011,12 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperation.procedureId",
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.startDate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.dueDate",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -24057,6 +24144,12 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperation.procedureId",
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.startDate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.dueDate",
+ },
{
$ref: "#/parameters/body.jobOperation",
},
@@ -34212,9 +34305,6 @@ export default {
{
$ref: "#/parameters/rowFilter.itemReplenishment.preferredSupplierId",
},
- {
- $ref: "#/parameters/rowFilter.itemReplenishment.purchasingLeadTime",
- },
{
$ref: "#/parameters/rowFilter.itemReplenishment.purchasingUnitOfMeasureCode",
},
@@ -34257,6 +34347,9 @@ export default {
{
$ref: "#/parameters/rowFilter.itemReplenishment.tags",
},
+ {
+ $ref: "#/parameters/rowFilter.itemReplenishment.leadTime",
+ },
{
$ref: "#/parameters/select",
},
@@ -34322,9 +34415,6 @@ export default {
{
$ref: "#/parameters/rowFilter.itemReplenishment.preferredSupplierId",
},
- {
- $ref: "#/parameters/rowFilter.itemReplenishment.purchasingLeadTime",
- },
{
$ref: "#/parameters/rowFilter.itemReplenishment.purchasingUnitOfMeasureCode",
},
@@ -34367,6 +34457,9 @@ export default {
{
$ref: "#/parameters/rowFilter.itemReplenishment.tags",
},
+ {
+ $ref: "#/parameters/rowFilter.itemReplenishment.leadTime",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -34386,9 +34479,6 @@ export default {
{
$ref: "#/parameters/rowFilter.itemReplenishment.preferredSupplierId",
},
- {
- $ref: "#/parameters/rowFilter.itemReplenishment.purchasingLeadTime",
- },
{
$ref: "#/parameters/rowFilter.itemReplenishment.purchasingUnitOfMeasureCode",
},
@@ -34431,6 +34521,9 @@ export default {
{
$ref: "#/parameters/rowFilter.itemReplenishment.tags",
},
+ {
+ $ref: "#/parameters/rowFilter.itemReplenishment.leadTime",
+ },
{
$ref: "#/parameters/body.itemReplenishment",
},
@@ -45423,6 +45516,9 @@ export default {
{
$ref: "#/parameters/rowFilter.openSalesOrderLines.itemTrackingType",
},
+ {
+ $ref: "#/parameters/rowFilter.openSalesOrderLines.leadTime",
+ },
{
$ref: "#/parameters/select",
},
@@ -63251,6 +63347,66 @@ export default {
},
type: "object",
},
+ openJobMaterialLines: {
+ properties: {
+ id: {
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string",
+ },
+ jobId: {
+ description:
+ "Note:\nThis is a Foreign Key to `job.id`.<fk table='job' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ itemId: {
+ description:
+ "Note:\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ quantityToIssue: {
+ format: "numeric",
+ type: "number",
+ },
+ unitOfMeasureCode: {
+ format: "text",
+ type: "string",
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ replenishmentSystem: {
+ enum: ["Buy", "Make", "Buy and Make"],
+ format: 'public."itemReplenishmentSystem"',
+ type: "string",
+ },
+ itemTrackingType: {
+ enum: ["Inventory", "Non-Inventory", "Serial", "Batch"],
+ format: 'public."itemTrackingType"',
+ type: "string",
+ },
+ leadTime: {
+ format: "integer",
+ type: "integer",
+ },
+ locationId: {
+ description:
+ "Note:\nThis is a Foreign Key to `location.id`.<fk table='location' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ dueDate: {
+ format: "date",
+ type: "string",
+ },
+ },
+ type: "object",
+ },
sequence: {
required: ["id", "table", "name", "next", "size", "step", "companyId"],
properties: {
@@ -66715,6 +66871,14 @@ export default {
format: "text",
type: "string",
},
+ startDate: {
+ format: "date",
+ type: "string",
+ },
+ dueDate: {
+ format: "date",
+ type: "string",
+ },
},
type: "object",
},
@@ -71500,7 +71664,6 @@ export default {
itemReplenishment: {
required: [
"itemId",
- "purchasingLeadTime",
"conversionFactor",
"purchasingBlocked",
"manufacturingBlocked",
@@ -71509,6 +71672,7 @@ export default {
"createdBy",
"createdAt",
"scrapPercentage",
+ "leadTime",
],
properties: {
itemId: {
@@ -71523,11 +71687,6 @@ export default {
format: "text",
type: "string",
},
- purchasingLeadTime: {
- default: 0,
- format: "integer",
- type: "integer",
- },
purchasingUnitOfMeasureCode: {
format: "text",
type: "string",
@@ -71599,6 +71758,11 @@ export default {
},
type: "array",
},
+ leadTime: {
+ default: 7,
+ format: "integer",
+ type: "integer",
+ },
},
type: "object",
},
@@ -77029,6 +77193,10 @@ export default {
format: 'public."itemTrackingType"',
type: "string",
},
+ leadTime: {
+ format: "integer",
+ type: "integer",
+ },
},
type: "object",
},
@@ -88232,6 +88400,81 @@ export default {
in: "query",
type: "string",
},
+ "body.openJobMaterialLines": {
+ name: "openJobMaterialLines",
+ description: "openJobMaterialLines",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/openJobMaterialLines",
+ },
+ },
+ "rowFilter.openJobMaterialLines.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.openJobMaterialLines.jobId": {
+ name: "jobId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.openJobMaterialLines.itemId": {
+ name: "itemId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.openJobMaterialLines.quantityToIssue": {
+ name: "quantityToIssue",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.openJobMaterialLines.unitOfMeasureCode": {
+ name: "unitOfMeasureCode",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.openJobMaterialLines.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.openJobMaterialLines.replenishmentSystem": {
+ name: "replenishmentSystem",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.openJobMaterialLines.itemTrackingType": {
+ name: "itemTrackingType",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.openJobMaterialLines.leadTime": {
+ name: "leadTime",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.openJobMaterialLines.locationId": {
+ name: "locationId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.openJobMaterialLines.dueDate": {
+ name: "dueDate",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.sequence": {
name: "sequence",
description: "sequence",
@@ -92069,6 +92312,18 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.jobOperation.startDate": {
+ name: "startDate",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobOperation.dueDate": {
+ name: "dueDate",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.userAttributeCategory": {
name: "userAttributeCategory",
description: "userAttributeCategory",
@@ -97673,12 +97928,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.itemReplenishment.purchasingLeadTime": {
- name: "purchasingLeadTime",
- required: false,
- in: "query",
- type: "string",
- },
"rowFilter.itemReplenishment.purchasingUnitOfMeasureCode": {
name: "purchasingUnitOfMeasureCode",
required: false,
@@ -97763,6 +98012,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.itemReplenishment.leadTime": {
+ name: "leadTime",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.methodOperationAttribute": {
name: "methodOperationAttribute",
description: "methodOperationAttribute",
@@ -103868,6 +104123,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.openSalesOrderLines.leadTime": {
+ name: "leadTime",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.supplier": {
name: "supplier",
description: "supplier",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 2e073ff116..d657aa498d 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -37322,14 +37322,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"]
@@ -38653,14 +38653,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -41431,14 +41431,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -44003,6 +44003,7 @@ export type Database = {
quantityOnSalesOrder: number
quantityOnPurchaseOrder: number
quantityOnProductionOrder: number
+ quantityOnProductionDemand: number
}[]
}
get_item_quantities_by_tracking_id: {
diff --git a/packages/database/supabase/config.toml b/packages/database/supabase/config.toml
index 6937c27d2c..7a2c9e37a5 100644
--- a/packages/database/supabase/config.toml
+++ b/packages/database/supabase/config.toml
@@ -140,7 +140,7 @@ verify_jwt = true
# static_files = [ "./functions/post-sales-invoice/*.html" ]
-[functions.demand-forecast]
+[functions.mrp]
enabled = true
verify_jwt = true
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 2e073ff116..d657aa498d 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -37322,14 +37322,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"]
@@ -38653,14 +38653,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -41431,14 +41431,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -44003,6 +44003,7 @@ export type Database = {
quantityOnSalesOrder: number
quantityOnPurchaseOrder: number
quantityOnProductionOrder: number
+ quantityOnProductionDemand: number
}[]
}
get_item_quantities_by_tracking_id: {
diff --git a/packages/database/supabase/functions/demand-forecast/index.ts b/packages/database/supabase/functions/mrp/index.ts
similarity index 56%
rename from packages/database/supabase/functions/demand-forecast/index.ts
rename to packages/database/supabase/functions/mrp/index.ts
index 08ba89889e..9a4766fffe 100644
--- a/packages/database/supabase/functions/demand-forecast/index.ts
+++ b/packages/database/supabase/functions/mrp/index.ts
@@ -31,13 +31,19 @@ const payloadValidator = z.discriminatedUnion("type", [
userId: z.string(),
}),
z.object({
- type: z.literal("salesOrder"),
+ type: z.literal("job"),
id: z.string(),
companyId: z.string(),
userId: z.string(),
}),
z.object({
- type: z.literal("job"),
+ type: z.literal("purchaseOrder"),
+ id: z.string(),
+ companyId: z.string(),
+ userId: z.string(),
+ }),
+ z.object({
+ type: z.literal("salesOrder"),
id: z.string(),
companyId: z.string(),
userId: z.string(),
@@ -50,10 +56,11 @@ serve(async (req: Request) => {
}
const payload = await req.json();
- const { type, companyId, userId } = payloadValidator.parse(payload);
+ const parsedPayload = payloadValidator.parse(payload);
+ const { type, companyId, userId } = parsedPayload;
console.log({
- function: "demand-forecast",
+ function: "mrp",
type,
companyId,
userId,
@@ -124,19 +131,6 @@ serve(async (req: Request) => {
try {
switch (type) {
case "company": {
- // Get existing demand actuals
- const { data: existingDemandActuals, error: demandActualsError } =
- await client
- .from("demandActual")
- .select("*")
-
- .in(
- "demandPeriodId",
- demandPeriods.map((p) => p.id ?? "")
- );
-
- if (demandActualsError) throw demandActualsError;
-
const [salesOrderLines, jobMaterialLines] = await Promise.all([
client
.from("openSalesOrderLines")
@@ -245,6 +239,19 @@ serve(async (req: Request) => {
Database["public"]["Tables"]["demandActual"]["Insert"]
>();
+ // Get existing demand actuals
+ const { data: existingDemandActuals, error: demandActualsError } =
+ await client
+ .from("demandActual")
+ .select("*")
+
+ .in(
+ "demandPeriodId",
+ demandPeriods.map((p) => p.id ?? "")
+ );
+
+ if (demandActualsError) throw demandActualsError;
+
// First add all existing records with quantity 0
if (existingDemandActuals) {
for (const existing of existingDemandActuals) {
@@ -344,16 +351,323 @@ serve(async (req: Request) => {
}
}
case "salesOrder": {
- return new Response(JSON.stringify({ success: true }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 201,
- });
+ const { id } = parsedPayload;
+
+ const [salesOrderLines] = await Promise.all([
+ client
+ .from("openSalesOrderLines")
+ .select("*")
+ .eq("salesOrderId", id)
+ .eq("companyId", companyId),
+ ]);
+
+ if (salesOrderLines.error) {
+ throw new Error("No sales order lines found");
+ }
+
+ // Group sales order lines into demand periods
+ for (const line of salesOrderLines.data) {
+ if (!line.itemId || !line.quantityToSend) continue;
+
+ const promiseDate = line.promisedDate
+ ? parseDate(line.promisedDate)
+ : today;
+ const requiredDate = promiseDate.add({
+ days: -(line?.leadTime ?? 7),
+ });
+
+ // If promised date is before today, use first period
+ let period;
+ if (requiredDate.compare(today) < 0) {
+ period = demandPeriods[0];
+ } else {
+ // Find matching period for promised date
+ period = demandPeriods.find((p) => {
+ return (
+ p.startDate?.compare(requiredDate) <= 0 &&
+ p.endDate?.compare(requiredDate) >= 0
+ );
+ });
+ }
+
+ if (period) {
+ const locationDemand = salesDemandByLocationAndPeriod.get(
+ line.locationId ?? ""
+ );
+ if (locationDemand) {
+ const periodDemand = locationDemand.get(period.id ?? "");
+ if (periodDemand) {
+ const currentDemand = periodDemand.get(line.itemId) ?? 0;
+ periodDemand.set(
+ line.itemId,
+ currentDemand + line.quantityToSend
+ );
+ }
+ }
+ }
+ }
+
+ const demandActualUpserts: Database["public"]["Tables"]["demandActual"]["Insert"][] =
+ [];
+
+ // Create a Map to store unique demand actuals by composite key
+ const demandActualsMap = new Map<
+ string,
+ Database["public"]["Tables"]["demandActual"]["Insert"]
+ >();
+
+ // Get existing demand actuals
+ const { data: existingDemandActuals, error: demandActualsError } =
+ await client
+ .from("demandActual")
+ .select("*")
+ .in(
+ "itemId",
+ salesOrderLines.data.map((line) => line.itemId)
+ )
+ .in(
+ "demandPeriodId",
+ demandPeriods.map((p) => p.id ?? "")
+ );
+
+ if (demandActualsError) throw demandActualsError;
+
+ // First add all existing records with quantity 0
+ if (existingDemandActuals) {
+ for (const existing of existingDemandActuals) {
+ const key = `${existing.itemId}-${existing.locationId}-${existing.demandPeriodId}-${existing.sourceType}`;
+ demandActualsMap.set(key, {
+ itemId: existing.itemId,
+ locationId: existing.locationId,
+ demandPeriodId: existing.demandPeriodId,
+ actualQuantity: 0,
+ sourceType: existing.sourceType,
+ createdBy: userId,
+ updatedBy: userId,
+ });
+ }
+ }
+
+ // Then add/update current demand for sales order lines
+ for (const [locationId, periodMap] of salesDemandByLocationAndPeriod) {
+ for (const [periodId, itemMap] of periodMap) {
+ for (const [itemId, quantity] of itemMap) {
+ if (quantity > 0) {
+ const key = `${itemId}-${locationId}-${periodId}-Sales Order`;
+ demandActualsMap.set(key, {
+ itemId,
+ locationId,
+ demandPeriodId: periodId,
+ actualQuantity: quantity,
+ sourceType: "Sales Order",
+ createdBy: userId,
+ updatedBy: userId,
+ });
+ }
+ }
+ }
+ }
+
+ // Convert Map values to array for upsert
+ demandActualUpserts.push(...demandActualsMap.values());
+
+ try {
+ await db.transaction().execute(async (trx) => {
+ if (demandActualUpserts.length > 0) {
+ await trx
+ .insertInto("demandActual")
+ .values(demandActualUpserts)
+ .onConflict((oc) =>
+ oc
+ .columns([
+ "itemId",
+ "locationId",
+ "demandPeriodId",
+ "sourceType",
+ ])
+ .doUpdateSet({
+ actualQuantity: (eb) => eb.ref("excluded.actualQuantity"),
+ updatedAt: new Date().toISOString(),
+ updatedBy: userId,
+ })
+ )
+ .execute();
+ }
+ });
+ return new Response(JSON.stringify({ success: true }), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 201,
+ });
+ } catch (err) {
+ console.error(err);
+ return new Response(JSON.stringify(err), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ });
+ }
}
case "job": {
- return new Response(JSON.stringify({ success: true }), {
- headers: { ...corsHeaders, "Content-Type": "application/json" },
- status: 201,
- });
+ const { id } = parsedPayload;
+
+ const [job, jobMaterialLines] = await Promise.all([
+ client
+ .from("job")
+ .select("itemId")
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .single(),
+ client
+ .from("openJobMaterialLines")
+ .select("*")
+ .eq("jobId", id)
+ .eq("companyId", companyId),
+ ]);
+
+ if (job.error) {
+ throw new Error("No job found");
+ }
+
+ if (jobMaterialLines.error) {
+ throw new Error("No job material lines found");
+ }
+
+ // Group job material lines into demand periods
+ for (const line of jobMaterialLines.data) {
+ if (!line.itemId || !line.quantityToIssue) continue;
+
+ const dueDate = line.dueDate ? parseDate(line.dueDate) : today;
+ const requiredDate = dueDate.add({ days: -(line.leadTime ?? 7) });
+
+ // If required date is before today, use first period
+ let period;
+ if (requiredDate.compare(today) < 0) {
+ period = demandPeriods[0];
+ } else {
+ // Find matching period for required date
+ period = demandPeriods.find((p) => {
+ return (
+ p.startDate?.compare(requiredDate) <= 0 &&
+ p.endDate?.compare(requiredDate) >= 0
+ );
+ });
+ }
+
+ if (period) {
+ const locationDemand = jobMaterialDemandByLocationAndPeriod.get(
+ line.locationId ?? ""
+ );
+ if (locationDemand) {
+ const periodDemand = locationDemand.get(period.id ?? "");
+ if (periodDemand) {
+ const currentDemand = periodDemand.get(line.itemId) ?? 0;
+ periodDemand.set(
+ line.itemId,
+ currentDemand + line.quantityToIssue
+ );
+ }
+ }
+ }
+ }
+
+ const demandActualUpserts: Database["public"]["Tables"]["demandActual"]["Insert"][] =
+ [];
+
+ // Create a Map to store unique demand actuals by composite key
+ const demandActualsMap = new Map<
+ string,
+ Database["public"]["Tables"]["demandActual"]["Insert"]
+ >();
+
+ // Get existing demand actuals
+ const { data: existingDemandActuals, error: demandActualsError } =
+ await client
+ .from("demandActual")
+ .select("*")
+ .eq("itemId", job.data.itemId)
+ .in(
+ "demandPeriodId",
+ demandPeriods.map((p) => p.id ?? "")
+ );
+
+ if (demandActualsError) throw demandActualsError;
+
+ // First add all existing records with quantity 0
+ if (existingDemandActuals) {
+ for (const existing of existingDemandActuals) {
+ const key = `${existing.itemId}-${existing.locationId}-${existing.demandPeriodId}-${existing.sourceType}`;
+ demandActualsMap.set(key, {
+ itemId: existing.itemId,
+ locationId: existing.locationId,
+ demandPeriodId: existing.demandPeriodId,
+ actualQuantity: 0,
+ sourceType: existing.sourceType,
+ createdBy: userId,
+ updatedBy: userId,
+ });
+ }
+ }
+
+ // Then add/update current demand for job material lines
+ for (const [
+ locationId,
+ periodMap,
+ ] of jobMaterialDemandByLocationAndPeriod) {
+ for (const [periodId, itemMap] of periodMap) {
+ for (const [itemId, quantity] of itemMap) {
+ if (quantity > 0) {
+ const key = `${itemId}-${locationId}-${periodId}-Job Material`;
+ demandActualsMap.set(key, {
+ itemId,
+ locationId,
+ demandPeriodId: periodId,
+ actualQuantity: quantity,
+ sourceType: "Job Material",
+ createdBy: userId,
+ updatedBy: userId,
+ });
+ }
+ }
+ }
+ }
+
+ // Convert Map values to array for upsert
+ demandActualUpserts.push(...demandActualsMap.values());
+
+ try {
+ await db.transaction().execute(async (trx) => {
+ if (demandActualUpserts.length > 0) {
+ await trx
+ .insertInto("demandActual")
+ .values(demandActualUpserts)
+ .onConflict((oc) =>
+ oc
+ .columns([
+ "itemId",
+ "locationId",
+ "demandPeriodId",
+ "sourceType",
+ ])
+ .doUpdateSet({
+ actualQuantity: (eb) => eb.ref("excluded.actualQuantity"),
+ updatedAt: new Date().toISOString(),
+ updatedBy: userId,
+ })
+ )
+ .execute();
+ }
+ });
+
+ return new Response(JSON.stringify({ success: true }), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 201,
+ });
+ } catch (err) {
+ console.error(err);
+ return new Response(JSON.stringify(err), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ });
+ }
}
default: {
throw new Error("Invalid type");
diff --git a/packages/database/supabase/migrations/20250610000433_demand-planning.sql b/packages/database/supabase/migrations/20250610000433_demand-planning.sql
index 26a0d3c3aa..56f7211453 100644
--- a/packages/database/supabase/migrations/20250610000433_demand-planning.sql
+++ b/packages/database/supabase/migrations/20250610000433_demand-planning.sql
@@ -1,10 +1,7 @@
ALTER TABLE "jobOperation" ADD COLUMN "startDate" DATE;
ALTER TABLE "jobOperation" ADD COLUMN "dueDate" DATE;
-ALTER TABLE "itemReplenishment" ADD COLUMN "manufacturingLeadTime";
ALTER TABLE "itemReplenishment" ADD COLUMN "leadTime" INTEGER NOT NULL DEFAULT 7;
-
--- Migrate purchasingLeadTime values to leadTime column
UPDATE "itemReplenishment"
SET "leadTime" = "purchasingLeadTime"
WHERE "purchasingLeadTime" IS NOT NULL;
@@ -139,4 +136,138 @@ CREATE OR REPLACE VIEW "openJobMaterialLines" AS (
'Paused'
)
AND jm."methodType" != 'Make'
-);
\ No newline at end of file
+);
+
+
+DROP FUNCTION IF EXISTS get_inventory_quantities;
+CREATE OR REPLACE FUNCTION get_inventory_quantities(company_id TEXT, location_id TEXT)
+ RETURNS TABLE (
+ "id" TEXT,
+ "readableId" TEXT,
+ "readableIdWithRevision" TEXT,
+ "name" TEXT,
+ "active" BOOLEAN,
+ "type" "itemType",
+ "itemTrackingType" "itemTrackingType",
+ "replenishmentSystem" "itemReplenishmentSystem",
+ "materialSubstanceId" TEXT,
+ "materialFormId" TEXT,
+ "thumbnailPath" TEXT,
+ "unitOfMeasureCode" TEXT,
+ "quantityOnHand" NUMERIC,
+ "quantityOnSalesOrder" NUMERIC,
+ "quantityOnPurchaseOrder" NUMERIC,
+ "quantityOnProductionOrder" NUMERIC,
+ "quantityOnProductionDemand" NUMERIC
+ ) AS $$
+ BEGIN
+ RETURN QUERY
+
+WITH
+ open_purchase_orders AS (
+ SELECT
+ pol."itemId",
+ SUM(pol."quantityToReceive" * pol."conversionFactor") AS "quantityOnPurchaseOrder"
+ FROM
+ "purchaseOrder" po
+ INNER JOIN "purchaseOrderLine" pol
+ ON pol."purchaseOrderId" = po."id"
+ WHERE
+ po."status" IN (
+ 'To Receive',
+ 'To Receive and Invoice'
+ )
+ AND po."companyId" = company_id
+ AND pol."locationId" = location_id
+ GROUP BY pol."itemId"
+ ),
+ open_sales_orders AS (
+ SELECT
+ sol."itemId",
+ SUM(sol."quantityToSend") AS "quantityOnSalesOrder"
+ FROM
+ "salesOrder" so
+ INNER JOIN "salesOrderLine" sol
+ ON sol."salesOrderId" = so."id"
+ WHERE
+ so."status" IN (
+ 'Confirmed',
+ 'To Ship and Invoice',
+ 'To Ship',
+ 'To Invoice',
+ 'In Progress'
+ )
+ AND so."companyId" = company_id
+ AND sol."locationId" = location_id
+ GROUP BY sol."itemId"
+ ),
+ open_job_requirements AS (
+ SELECT
+ jm."itemId",
+ SUM(jm."quantityToIssue") AS "quantityOnProductionDemand"
+ FROM "jobMaterial" jm
+ INNER JOIN "job" j ON jm."jobId" = j."id"
+ WHERE j."status" IN (
+ 'Draft',
+ 'Ready',
+ 'In Progress',
+ 'Paused'
+ )
+ AND jm."methodType" != 'Make'
+ GROUP BY jm."itemId"
+ ),
+ open_jobs AS (
+ SELECT
+ j."itemId",
+ SUM(j."productionQuantity" + j."scrapQuantity" - j."quantityReceivedToInventory" - j."quantityShipped") AS "quantityOnProductionOrder"
+ FROM job j
+ WHERE j."status" IN (
+ 'Draft',
+ 'Ready',
+ 'In Progress',
+ 'Paused'
+ )
+ GROUP BY j."itemId"
+ ),
+ item_ledgers AS (
+ SELECT "itemId", SUM("quantity") AS "quantityOnHand"
+ FROM "itemLedger"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ GROUP BY "itemId"
+ )
+
+SELECT
+ i."id",
+ i."readableId",
+ i."readableIdWithRevision",
+ i."name",
+ i."active",
+ i."type",
+ i."itemTrackingType",
+ i."replenishmentSystem",
+ m."materialSubstanceId",
+ m."materialFormId",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ i."unitOfMeasureCode",
+ COALESCE(il."quantityOnHand", 0) AS "quantityOnHand",
+ COALESCE(so."quantityOnSalesOrder", 0) AS "quantityOnSalesOrder",
+ COALESCE(po."quantityOnPurchaseOrder", 0) AS "quantityOnPurchaseOrder",
+ COALESCE(jo."quantityOnProductionOrder", 0) AS "quantityOnProductionOrder",
+ COALESCE(jr."quantityOnProductionDemand", 0) AS "quantityOnProductionDemand"
+FROM
+ "item" i
+ LEFT JOIN item_ledgers il ON i."id" = il."itemId"
+ LEFT JOIN open_sales_orders so ON i."id" = so."itemId"
+ LEFT JOIN open_purchase_orders po ON i."id" = po."itemId"
+ LEFT JOIN open_jobs jo ON i."id" = jo."itemId"
+ LEFT JOIN open_job_requirements jr ON i."id" = jr."itemId"
+ LEFT JOIN material m ON i."readableId" = m."id"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+WHERE
+ i."itemTrackingType" <> 'Non-Inventory' AND i."companyId" = company_id;
+ END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;