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: add edge function for recalculating job quantities

Brad Barbin711c630cb97d
diff --git a/apps/carbon/app/modules/production/production.service.ts b/apps/carbon/app/modules/production/production.service.ts
index 4ba1c1bbb2..a2e78d6267 100644
--- a/apps/carbon/app/modules/production/production.service.ts
+++ b/apps/carbon/app/modules/production/production.service.ts
@@ -220,6 +220,22 @@ export async function getJobOperationsByMethodId(
.order("order", { ascending: true });
}
+export async function recalculateJobRequirements(
+ client: SupabaseClient<Database>,
+ params: {
+ id: string;
+ companyId: string;
+ userId: string;
+ }
+) {
+ return client.functions.invoke("recalculate", {
+ body: {
+ type: "jobRequirements",
+ ...params,
+ },
+ });
+}
+
export async function updateJobMaterialOrder(
client: SupabaseClient<Database>,
updates: {
diff --git a/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.method.tsx b/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.method.tsx
index a7366328cd..52c4ea5381 100644
--- a/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.method.tsx
+++ b/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.method.tsx
@@ -27,13 +27,13 @@ export default function MakeMethodRoute() {
<VStack spacing={2} className="p-2">
<MakeMethodBreadcrumbs itemId={itemId} type="Fixture" />
<BillOfProcess
- key={JSON.stringify(manufacturingRouteData?.methodOperations ?? [])}
+ key={JSON.stringify(manufacturingRouteData?.methodOperations)}
makeMethodId={makeMethodId}
// @ts-ignore
- operations={manufacturingRouteData?.methodOperations ?? []}
+ operations={manufacturingRouteData?.methodOperations}
/>
<BillOfMaterial
- key={JSON.stringify(manufacturingRouteData?.methodMaterials ?? [])}
+ key={JSON.stringify(manufacturingRouteData?.methodMaterials)}
makeMethodId={makeMethodId}
// @ts-ignore
materials={manufacturingRouteData?.methodMaterials ?? []}
diff --git a/apps/carbon/app/routes/x+/job+/$jobId.tsx b/apps/carbon/app/routes/x+/job+/$jobId.tsx
index 283c276f7b..70df290082 100644
--- a/apps/carbon/app/routes/x+/job+/$jobId.tsx
+++ b/apps/carbon/app/routes/x+/job+/$jobId.tsx
@@ -57,12 +57,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const files = await getJobDocuments(client, companyId, job.data);
- const methodPromise = getJobMethodTree(client, jobId);
-
return defer({
job: job.data,
files,
- method: methodPromise,
+ method: getJobMethodTree(client, jobId), // returns a promise
});
}
diff --git a/apps/carbon/app/routes/x+/job+/new.tsx b/apps/carbon/app/routes/x+/job+/new.tsx
index 83879ffb1a..8c21f05296 100644
--- a/apps/carbon/app/routes/x+/job+/new.tsx
+++ b/apps/carbon/app/routes/x+/job+/new.tsx
@@ -6,6 +6,7 @@ import { getSupabaseServiceRole } from "~/lib/supabase";
import {
JobForm,
jobValidator,
+ recalculateJobRequirements,
upsertJob,
upsertJobMethod,
} from "~/modules/production";
@@ -92,6 +93,24 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
+ const calculateQuantities = await recalculateJobRequirements(serviceRole, {
+ id,
+ companyId,
+ userId,
+ });
+ if (calculateQuantities.error) {
+ throw redirect(
+ path.to.job(id),
+ await flash(
+ request,
+ error(
+ calculateQuantities.error,
+ "Failed to calculate job requirements."
+ )
+ )
+ );
+ }
+
throw redirect(path.to.job(id));
}
diff --git a/apps/carbon/app/routes/x+/settings+/terms.tsx b/apps/carbon/app/routes/x+/settings+/terms.tsx
index 26db18c3a2..9057c9cf8b 100644
--- a/apps/carbon/app/routes/x+/settings+/terms.tsx
+++ b/apps/carbon/app/routes/x+/settings+/terms.tsx
@@ -113,7 +113,7 @@ export default function Terms() {
<Card>
<HStack className="justify-between items-start">
<CardHeader>
- <CardTitle>Terms &amp; Conditions (Purchasing)</CardTitle>
+ <CardTitle>Purchasing Terms &amp; Conditions</CardTitle>
<CardDescription>
Define the terms and conditions for purchase orders
</CardDescription>
@@ -146,7 +146,7 @@ export default function Terms() {
<Card>
<HStack className="justify-between items-start">
<CardHeader>
- <CardTitle>Terms &amp; Conditions (Sales)</CardTitle>
+ <CardTitle>Sales Terms &amp; Conditions</CardTitle>
<CardDescription>
Define the terms and conditions for quotes and sales orders
</CardDescription>
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 236fc71bef..9c5493e80d 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -4497,6 +4497,15 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperation.customFields",
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.operationQuantity",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.quantityComplete",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.quantityScrapped",
+ },
{
$ref: "#/parameters/select",
},
@@ -4643,6 +4652,15 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperation.customFields",
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.operationQuantity",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.quantityComplete",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.quantityScrapped",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -4743,6 +4761,15 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperation.customFields",
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.operationQuantity",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.quantityComplete",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.quantityScrapped",
+ },
{
$ref: "#/parameters/body.jobOperation",
},
@@ -9951,9 +9978,6 @@ export default {
{
$ref: "#/parameters/rowFilter.jobMaterial.scrapQuantity",
},
- {
- $ref: "#/parameters/rowFilter.jobMaterial.productionQuantity",
- },
{
$ref: "#/parameters/rowFilter.jobMaterial.unitOfMeasureCode",
},
@@ -9984,6 +10008,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobMaterial.jobOperationId",
},
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.estimatedQuantity",
+ },
{
$ref: "#/parameters/select",
},
@@ -10073,9 +10100,6 @@ export default {
{
$ref: "#/parameters/rowFilter.jobMaterial.scrapQuantity",
},
- {
- $ref: "#/parameters/rowFilter.jobMaterial.productionQuantity",
- },
{
$ref: "#/parameters/rowFilter.jobMaterial.unitOfMeasureCode",
},
@@ -10106,6 +10130,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobMaterial.jobOperationId",
},
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.estimatedQuantity",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -10149,9 +10176,6 @@ export default {
{
$ref: "#/parameters/rowFilter.jobMaterial.scrapQuantity",
},
- {
- $ref: "#/parameters/rowFilter.jobMaterial.productionQuantity",
- },
{
$ref: "#/parameters/rowFilter.jobMaterial.unitOfMeasureCode",
},
@@ -10182,6 +10206,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobMaterial.jobOperationId",
},
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.estimatedQuantity",
+ },
{
$ref: "#/parameters/body.jobMaterial",
},
@@ -30600,9 +30627,6 @@ export default {
{
$ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.scrapQuantity",
},
- {
- $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.productionQuantity",
- },
{
$ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.unitOfMeasureCode",
},
@@ -30633,6 +30657,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.jobOperationId",
},
+ {
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.estimatedQuantity",
+ },
{
$ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.jobMaterialMakeMethodId",
},
@@ -36891,6 +36918,21 @@ export default {
customFields: {
format: "jsonb",
},
+ operationQuantity: {
+ default: 0,
+ format: "numeric",
+ type: "number",
+ },
+ quantityComplete: {
+ default: 0,
+ format: "numeric",
+ type: "number",
+ },
+ quantityScrapped: {
+ default: 0,
+ format: "numeric",
+ type: "number",
+ },
},
type: "object",
},
@@ -39332,10 +39374,6 @@ export default {
format: "numeric",
type: "number",
},
- productionQuantity: {
- format: "numeric",
- type: "number",
- },
unitOfMeasureCode: {
format: "text",
type: "string",
@@ -39387,6 +39425,11 @@ export default {
format: "text",
type: "string",
},
+ estimatedQuantity: {
+ default: 0,
+ format: "numeric",
+ type: "number",
+ },
},
type: "object",
},
@@ -48849,10 +48892,6 @@ export default {
format: "numeric",
type: "number",
},
- productionQuantity: {
- format: "numeric",
- type: "number",
- },
unitOfMeasureCode: {
format: "text",
type: "string",
@@ -48902,6 +48941,10 @@ export default {
format: "text",
type: "string",
},
+ estimatedQuantity: {
+ format: "numeric",
+ type: "number",
+ },
jobMaterialMakeMethodId: {
description: "Note:\nThis is a Primary Key.<pk/>",
format: "text",
@@ -52653,6 +52696,27 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.jobOperation.operationQuantity": {
+ name: "operationQuantity",
+ required: false,
+ format: "numeric",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobOperation.quantityComplete": {
+ name: "quantityComplete",
+ required: false,
+ format: "numeric",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobOperation.quantityScrapped": {
+ name: "quantityScrapped",
+ required: false,
+ format: "numeric",
+ in: "query",
+ type: "string",
+ },
"body.journalLine": {
name: "journalLine",
description: "journalLine",
@@ -55806,13 +55870,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.jobMaterial.productionQuantity": {
- name: "productionQuantity",
- required: false,
- format: "numeric",
- in: "query",
- type: "string",
- },
"rowFilter.jobMaterial.unitOfMeasureCode": {
name: "unitOfMeasureCode",
required: false,
@@ -55883,6 +55940,13 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.jobMaterial.estimatedQuantity": {
+ name: "estimatedQuantity",
+ required: false,
+ format: "numeric",
+ in: "query",
+ type: "string",
+ },
"body.purchaseOrderSuppliers": {
name: "purchaseOrderSuppliers",
description: "purchaseOrderSuppliers",
@@ -68320,13 +68384,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.jobMaterialWithMakeMethodId.productionQuantity": {
- name: "productionQuantity",
- required: false,
- format: "numeric",
- in: "query",
- type: "string",
- },
"rowFilter.jobMaterialWithMakeMethodId.unitOfMeasureCode": {
name: "unitOfMeasureCode",
required: false,
@@ -68397,6 +68454,13 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.jobMaterialWithMakeMethodId.estimatedQuantity": {
+ name: "estimatedQuantity",
+ required: false,
+ format: "numeric",
+ in: "query",
+ type: "string",
+ },
"rowFilter.jobMaterialWithMakeMethodId.jobMaterialMakeMethodId": {
name: "jobMaterialMakeMethodId",
required: false,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 2a5c1d1532..1270b64af2 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -7476,6 +7476,7 @@ export type Database = {
createdBy: string
customFields: Json | null
description: string
+ estimatedQuantity: number | null
id: string
itemId: string
itemReadableId: string
@@ -7485,7 +7486,6 @@ export type Database = {
jobOperationId: string | null
methodType: Database["public"]["Enums"]["methodType"]
order: number
- productionQuantity: number | null
quantity: number
scrapQuantity: number
unitCost: number
@@ -7499,6 +7499,7 @@ export type Database = {
createdBy: string
customFields?: Json | null
description: string
+ estimatedQuantity?: number | null
id?: string
itemId: string
itemReadableId: string
@@ -7508,7 +7509,6 @@ export type Database = {
jobOperationId?: string | null
methodType?: Database["public"]["Enums"]["methodType"]
order?: number
- productionQuantity?: number | null
quantity?: number
scrapQuantity?: number
unitCost?: number
@@ -7522,6 +7522,7 @@ export type Database = {
createdBy?: string
customFields?: Json | null
description?: string
+ estimatedQuantity?: number | null
id?: string
itemId?: string
itemReadableId?: string
@@ -7531,7 +7532,6 @@ export type Database = {
jobOperationId?: string | null
methodType?: Database["public"]["Enums"]["methodType"]
order?: number
- productionQuantity?: number | null
quantity?: number
scrapQuantity?: number
unitCost?: number
@@ -7722,12 +7722,15 @@ export type Database = {
operationLeadTime: number
operationMinimumCost: number
operationOrder: Database["public"]["Enums"]["methodOperationOrder"]
+ operationQuantity: number | null
operationSupplierProcessId: string | null
operationType: Database["public"]["Enums"]["operationType"]
operationUnitCost: number
order: number
overheadRate: number
processId: string
+ quantityComplete: number | null
+ quantityScrapped: number | null
setupTime: number
setupUnit: Database["public"]["Enums"]["factor"]
updatedAt: string | null
@@ -7753,12 +7756,15 @@ export type Database = {
operationLeadTime?: number
operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
+ operationQuantity?: number | null
operationSupplierProcessId?: string | null
operationType?: Database["public"]["Enums"]["operationType"]
operationUnitCost?: number
order?: number
overheadRate?: number
processId: string
+ quantityComplete?: number | null
+ quantityScrapped?: number | null
setupTime?: number
setupUnit?: Database["public"]["Enums"]["factor"]
updatedAt?: string | null
@@ -7784,12 +7790,15 @@ export type Database = {
operationLeadTime?: number
operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
+ operationQuantity?: number | null
operationSupplierProcessId?: string | null
operationType?: Database["public"]["Enums"]["operationType"]
operationUnitCost?: number
order?: number
overheadRate?: number
processId?: string
+ quantityComplete?: number | null
+ quantityScrapped?: number | null
setupTime?: number
setupUnit?: Database["public"]["Enums"]["factor"]
updatedAt?: string | null
@@ -23385,6 +23394,7 @@ export type Database = {
createdBy: string | null
customFields: Json | null
description: string | null
+ estimatedQuantity: number | null
id: string | null
itemId: string | null
itemReadableId: string | null
@@ -23395,7 +23405,6 @@ export type Database = {
jobOperationId: string | null
methodType: Database["public"]["Enums"]["methodType"] | null
order: number | null
- productionQuantity: number | null
quantity: number | null
scrapQuantity: number | null
unitCost: number | null
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index 4d1d3f6152..128c181f8c 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -11,6 +11,13 @@ import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import type { Database } from "../lib/types.ts";
import { corsHeaders } from "../lib/headers.ts";
+import {
+ getJobMethodTree,
+ getRatesFromSupplierProcesses,
+ getRatesFromWorkCenters,
+ JobMethodTreeItem,
+ traverseJobMethod,
+} from "../lib/methods.ts";
import { getSupabaseServiceRole } from "../lib/supabase.ts";
const pool = getConnectionPool(1);
@@ -2033,214 +2040,3 @@ async function traverseQuoteMethod(
}
}
}
-
-type JobMethod = NonNullable<
- Awaited<ReturnType<typeof getJobMethodTreeArray>>["data"]
->[number];
-type JobMethodTreeItem = {
- id: string;
- data: JobMethod;
- children: JobMethodTreeItem[];
-};
-
-export async function getJobMethodTree(
- client: SupabaseClient<Database>,
- methodId: string
-) {
- const items = await getJobMethodTreeArray(client, methodId);
- if (items.error) return items;
-
- const tree = getJobMethodTreeArrayToTree(items.data);
-
- return {
- data: tree,
- error: null,
- };
-}
-
-export function getJobMethodTreeArray(
- client: SupabaseClient<Database>,
- methodId: string
-) {
- return client.rpc("get_job_methods_by_method_id", {
- mid: methodId,
- });
-}
-
-function getJobMethodTreeArrayToTree(items: JobMethod[]): JobMethodTreeItem[] {
- // function traverseAndRenameIds(node: JobMethodTreeItem) {
- // const clone = structuredClone(node);
- // clone.id = `node-${Math.random().toString(16).slice(2)}`;
- // clone.children = clone.children.map((n) => traverseAndRenameIds(n));
- // return clone;
- // }
-
- const rootItems: JobMethodTreeItem[] = [];
- const lookup: { [id: string]: JobMethodTreeItem } = {};
-
- for (const item of items) {
- const itemId = item.methodMaterialId;
- const parentId = item.parentMaterialId;
-
- if (!Object.prototype.hasOwnProperty.call(lookup, itemId)) {
- // @ts-ignore - we don't add data here
- lookup[itemId] = { id: itemId, children: [] };
- }
-
- lookup[itemId]["data"] = item;
-
- const treeItem = lookup[itemId];
-
- if (parentId === null || parentId === undefined) {
- rootItems.push(treeItem);
- } else {
- if (!Object.prototype.hasOwnProperty.call(lookup, parentId)) {
- // @ts-ignore - we don't add data here
- lookup[parentId] = { id: parentId, children: [] };
- }
-
- lookup[parentId]["children"].push(treeItem);
- }
- }
- return rootItems;
-}
-
-function traverseJobMethod(
- node: JobMethodTreeItem,
- callback: (node: JobMethodTreeItem) => void
-) {
- callback(node);
-
- if (node.children) {
- for (const child of node.children) {
- traverseJobMethod(child, callback);
- }
- }
-}
-
-const getRatesFromWorkCenters =
- (workCenters: Database["public"]["Views"]["workCenters"]["Row"][] | null) =>
- (
- processId: string,
- workCenterId: string | null
- ): { overheadRate: number; laborRate: number; machineRate: number } => {
- if (!workCenters) {
- return {
- laborRate: 0,
- machineRate: 0,
- overheadRate: 0,
- };
- }
-
- if (workCenterId) {
- const workCenter = workCenters?.find(
- (wc) => wc.id === workCenterId && wc.active
- );
-
- if (workCenter) {
- return {
- laborRate: workCenter.laborRate ?? 0,
- machineRate: workCenter.machineRate ?? 0,
- overheadRate: workCenter.overheadRate ?? 0,
- };
- }
- }
-
- const relatedWorkCenters = workCenters.filter((wc) => {
- const processes = (wc.processes ?? []) as { id: string }[];
- return wc.active && processes.some((p) => p.id === processId);
- });
-
- if (relatedWorkCenters.length > 0) {
- const laborRate =
- relatedWorkCenters.reduce((acc, workCenter) => {
- return (acc += workCenter.laborRate ?? 0);
- }, 0) / relatedWorkCenters.length;
-
- const machineRate =
- relatedWorkCenters.reduce((acc, workCenter) => {
- return (acc += workCenter.machineRate ?? 0);
- }, 0) / relatedWorkCenters.length;
-
- const overheadRate =
- relatedWorkCenters.reduce((acc, workCenter) => {
- return (acc += workCenter.overheadRate ?? 0);
- }, 0) / relatedWorkCenters.length;
-
- return {
- laborRate,
- machineRate,
- overheadRate,
- };
- }
-
- return {
- laborRate: 0,
- machineRate: 0,
- overheadRate: 0,
- };
- };
-
-const getRatesFromSupplierProcesses =
- (
- processes: Database["public"]["Tables"]["supplierProcess"]["Row"][] | null
- ) =>
- (
- processId: string,
- supplierProcessId: string | null
- ): {
- operationMinimumCost: number;
- operationUnitCost: number;
- operationLeadTime: number;
- } => {
- if (!processes) {
- return {
- operationMinimumCost: 0,
- operationUnitCost: 0,
- operationLeadTime: 0,
- };
- }
-
- if (supplierProcessId) {
- const supplierProcess = processes?.find(
- (sp) => sp.id === supplierProcessId
- );
-
- if (supplierProcess) {
- return {
- operationMinimumCost: supplierProcess.minimumCost,
- operationUnitCost: supplierProcess.unitCost,
- operationLeadTime: supplierProcess.leadTime,
- };
- }
- }
-
- const relatedProcesses = processes.filter((p) => p.processId === processId);
-
- if (relatedProcesses.length > 0) {
- const operationMinimumCost =
- relatedProcesses.reduce((acc, process) => {
- return (acc += process.minimumCost ?? 0);
- }, 0) / relatedProcesses.length;
- const operationUnitCost =
- relatedProcesses.reduce((acc, process) => {
- return (acc += process.unitCost ?? 0);
- }, 0) / relatedProcesses.length;
- const operationLeadTime =
- relatedProcesses.reduce((acc, process) => {
- return (acc += process.leadTime ?? 0);
- }, 0) / relatedProcesses.length;
-
- return {
- operationMinimumCost,
- operationUnitCost,
- operationLeadTime,
- };
- }
-
- return {
- operationMinimumCost: 0,
- operationUnitCost: 0,
- operationLeadTime: 0,
- };
- };
diff --git a/packages/database/supabase/functions/lib/methods.ts b/packages/database/supabase/functions/lib/methods.ts
new file mode 100644
index 0000000000..ca42c12828
--- /dev/null
+++ b/packages/database/supabase/functions/lib/methods.ts
@@ -0,0 +1,214 @@
+import SupabaseClient from "https://esm.sh/v135/@supabase/[email protected]/dist/module/SupabaseClient.d.ts";
+import { Database } from "./types.ts";
+
+export type JobMethod = NonNullable<
+ Awaited<ReturnType<typeof getJobMethodTreeArray>>["data"]
+>[number];
+
+export type JobMethodTreeItem = {
+ id: string;
+ data: JobMethod;
+ children: JobMethodTreeItem[];
+};
+
+export async function getJobMethodTree(
+ client: SupabaseClient<Database>,
+ methodId: string
+) {
+ const items = await getJobMethodTreeArray(client, methodId);
+ if (items.error) return items;
+
+ const tree = getJobMethodTreeArrayToTree(items.data);
+
+ return {
+ data: tree,
+ error: null,
+ };
+}
+
+export function getJobMethodTreeArray(
+ client: SupabaseClient<Database>,
+ methodId: string
+) {
+ return client.rpc("get_job_methods_by_method_id", {
+ mid: methodId,
+ });
+}
+
+function getJobMethodTreeArrayToTree(items: JobMethod[]): JobMethodTreeItem[] {
+ // function traverseAndRenameIds(node: JobMethodTreeItem) {
+ // const clone = structuredClone(node);
+ // clone.id = `node-${Math.random().toString(16).slice(2)}`;
+ // clone.children = clone.children.map((n) => traverseAndRenameIds(n));
+ // return clone;
+ // }
+
+ const rootItems: JobMethodTreeItem[] = [];
+ const lookup: { [id: string]: JobMethodTreeItem } = {};
+
+ for (const item of items) {
+ const itemId = item.methodMaterialId;
+ const parentId = item.parentMaterialId;
+
+ if (!Object.prototype.hasOwnProperty.call(lookup, itemId)) {
+ // @ts-ignore - we don't add data here
+ lookup[itemId] = { id: itemId, children: [] };
+ }
+
+ lookup[itemId]["data"] = item;
+
+ const treeItem = lookup[itemId];
+
+ if (parentId === null || parentId === undefined) {
+ rootItems.push(treeItem);
+ } else {
+ if (!Object.prototype.hasOwnProperty.call(lookup, parentId)) {
+ // @ts-ignore - we don't add data here
+ lookup[parentId] = { id: parentId, children: [] };
+ }
+
+ lookup[parentId]["children"].push(treeItem);
+ }
+ }
+ return rootItems;
+}
+
+export function traverseJobMethod(
+ node: JobMethodTreeItem,
+ callback: (node: JobMethodTreeItem) => void
+) {
+ callback(node);
+
+ if (node.children) {
+ for (const child of node.children) {
+ traverseJobMethod(child, callback);
+ }
+ }
+}
+
+export const getRatesFromWorkCenters =
+ (workCenters: Database["public"]["Views"]["workCenters"]["Row"][] | null) =>
+ (
+ processId: string,
+ workCenterId: string | null
+ ): { overheadRate: number; laborRate: number; machineRate: number } => {
+ if (!workCenters) {
+ return {
+ laborRate: 0,
+ machineRate: 0,
+ overheadRate: 0,
+ };
+ }
+
+ if (workCenterId) {
+ const workCenter = workCenters?.find(
+ (wc) => wc.id === workCenterId && wc.active
+ );
+
+ if (workCenter) {
+ return {
+ laborRate: workCenter.laborRate ?? 0,
+ machineRate: workCenter.machineRate ?? 0,
+ overheadRate: workCenter.overheadRate ?? 0,
+ };
+ }
+ }
+
+ const relatedWorkCenters = workCenters.filter((wc) => {
+ const processes = (wc.processes ?? []) as { id: string }[];
+ return wc.active && processes.some((p) => p.id === processId);
+ });
+
+ if (relatedWorkCenters.length > 0) {
+ const laborRate =
+ relatedWorkCenters.reduce((acc, workCenter) => {
+ return (acc += workCenter.laborRate ?? 0);
+ }, 0) / relatedWorkCenters.length;
+
+ const machineRate =
+ relatedWorkCenters.reduce((acc, workCenter) => {
+ return (acc += workCenter.machineRate ?? 0);
+ }, 0) / relatedWorkCenters.length;
+
+ const overheadRate =
+ relatedWorkCenters.reduce((acc, workCenter) => {
+ return (acc += workCenter.overheadRate ?? 0);
+ }, 0) / relatedWorkCenters.length;
+
+ return {
+ laborRate,
+ machineRate,
+ overheadRate,
+ };
+ }
+
+ return {
+ laborRate: 0,
+ machineRate: 0,
+ overheadRate: 0,
+ };
+ };
+
+export const getRatesFromSupplierProcesses =
+ (
+ processes: Database["public"]["Tables"]["supplierProcess"]["Row"][] | null
+ ) =>
+ (
+ processId: string,
+ supplierProcessId: string | null
+ ): {
+ operationMinimumCost: number;
+ operationUnitCost: number;
+ operationLeadTime: number;
+ } => {
+ if (!processes) {
+ return {
+ operationMinimumCost: 0,
+ operationUnitCost: 0,
+ operationLeadTime: 0,
+ };
+ }
+
+ if (supplierProcessId) {
+ const supplierProcess = processes?.find(
+ (sp) => sp.id === supplierProcessId
+ );
+
+ if (supplierProcess) {
+ return {
+ operationMinimumCost: supplierProcess.minimumCost,
+ operationUnitCost: supplierProcess.unitCost,
+ operationLeadTime: supplierProcess.leadTime,
+ };
+ }
+ }
+
+ const relatedProcesses = processes.filter((p) => p.processId === processId);
+
+ if (relatedProcesses.length > 0) {
+ const operationMinimumCost =
+ relatedProcesses.reduce((acc, process) => {
+ return (acc += process.minimumCost ?? 0);
+ }, 0) / relatedProcesses.length;
+ const operationUnitCost =
+ relatedProcesses.reduce((acc, process) => {
+ return (acc += process.unitCost ?? 0);
+ }, 0) / relatedProcesses.length;
+ const operationLeadTime =
+ relatedProcesses.reduce((acc, process) => {
+ return (acc += process.leadTime ?? 0);
+ }, 0) / relatedProcesses.length;
+
+ return {
+ operationMinimumCost,
+ operationUnitCost,
+ operationLeadTime,
+ };
+ }
+
+ return {
+ operationMinimumCost: 0,
+ operationUnitCost: 0,
+ operationLeadTime: 0,
+ };
+ };
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 2a5c1d1532..1270b64af2 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -7476,6 +7476,7 @@ export type Database = {
createdBy: string
customFields: Json | null
description: string
+ estimatedQuantity: number | null
id: string
itemId: string
itemReadableId: string
@@ -7485,7 +7486,6 @@ export type Database = {
jobOperationId: string | null
methodType: Database["public"]["Enums"]["methodType"]
order: number
- productionQuantity: number | null
quantity: number
scrapQuantity: number
unitCost: number
@@ -7499,6 +7499,7 @@ export type Database = {
createdBy: string
customFields?: Json | null
description: string
+ estimatedQuantity?: number | null
id?: string
itemId: string
itemReadableId: string
@@ -7508,7 +7509,6 @@ export type Database = {
jobOperationId?: string | null
methodType?: Database["public"]["Enums"]["methodType"]
order?: number
- productionQuantity?: number | null
quantity?: number
scrapQuantity?: number
unitCost?: number
@@ -7522,6 +7522,7 @@ export type Database = {
createdBy?: string
customFields?: Json | null
description?: string
+ estimatedQuantity?: number | null
id?: string
itemId?: string
itemReadableId?: string
@@ -7531,7 +7532,6 @@ export type Database = {
jobOperationId?: string | null
methodType?: Database["public"]["Enums"]["methodType"]
order?: number
- productionQuantity?: number | null
quantity?: number
scrapQuantity?: number
unitCost?: number
@@ -7722,12 +7722,15 @@ export type Database = {
operationLeadTime: number
operationMinimumCost: number
operationOrder: Database["public"]["Enums"]["methodOperationOrder"]
+ operationQuantity: number | null
operationSupplierProcessId: string | null
operationType: Database["public"]["Enums"]["operationType"]
operationUnitCost: number
order: number
overheadRate: number
processId: string
+ quantityComplete: number | null
+ quantityScrapped: number | null
setupTime: number
setupUnit: Database["public"]["Enums"]["factor"]
updatedAt: string | null
@@ -7753,12 +7756,15 @@ export type Database = {
operationLeadTime?: number
operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
+ operationQuantity?: number | null
operationSupplierProcessId?: string | null
operationType?: Database["public"]["Enums"]["operationType"]
operationUnitCost?: number
order?: number
overheadRate?: number
processId: string
+ quantityComplete?: number | null
+ quantityScrapped?: number | null
setupTime?: number
setupUnit?: Database["public"]["Enums"]["factor"]
updatedAt?: string | null
@@ -7784,12 +7790,15 @@ export type Database = {
operationLeadTime?: number
operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
+ operationQuantity?: number | null
operationSupplierProcessId?: string | null
operationType?: Database["public"]["Enums"]["operationType"]
operationUnitCost?: number
order?: number
overheadRate?: number
processId?: string
+ quantityComplete?: number | null
+ quantityScrapped?: number | null
setupTime?: number
setupUnit?: Database["public"]["Enums"]["factor"]
updatedAt?: string | null
@@ -23385,6 +23394,7 @@ export type Database = {
createdBy: string | null
customFields: Json | null
description: string | null
+ estimatedQuantity: number | null
id: string | null
itemId: string | null
itemReadableId: string | null
@@ -23395,7 +23405,6 @@ export type Database = {
jobOperationId: string | null
methodType: Database["public"]["Enums"]["methodType"] | null
order: number | null
- productionQuantity: number | null
quantity: number | null
scrapQuantity: number | null
unitCost: number | null
diff --git a/packages/database/supabase/functions/recalculate/index.ts b/packages/database/supabase/functions/recalculate/index.ts
new file mode 100644
index 0000000000..f2dfcdc3c2
--- /dev/null
+++ b/packages/database/supabase/functions/recalculate/index.ts
@@ -0,0 +1,128 @@
+import { serve } from "https://deno.land/[email protected]/http/server.ts";
+import { z } from "https://deno.land/x/[email protected]/mod.ts";
+
+import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
+
+import { corsHeaders } from "../lib/headers.ts";
+import { getJobMethodTree, JobMethodTreeItem } from "../lib/methods.ts";
+import { getSupabaseServiceRole } from "../lib/supabase.ts";
+
+const pool = getConnectionPool(1);
+const db = getDatabaseClient<DB>(pool);
+
+const payloadValidator = z.object({
+ type: z.enum(["jobRequirements"]),
+ id: z.string(),
+ companyId: z.string(),
+ userId: z.string(),
+});
+
+serve(async (req: Request) => {
+ if (req.method === "OPTIONS") {
+ return new Response("ok", { headers: corsHeaders });
+ }
+ const payload = await req.json();
+
+ try {
+ const { type, id, companyId, userId } = payloadValidator.parse(payload);
+
+ console.log({
+ function: "recalculate",
+ type,
+ id,
+ companyId,
+ userId,
+ });
+
+ const client = getSupabaseServiceRole(req.headers.get("Authorization"));
+
+ switch (type) {
+ case "jobRequirements": {
+ const jobId = id;
+ const [job, jobMakeMethod] = await Promise.all([
+ client.from("job").select("*").eq("id", jobId).single(),
+ client
+ .from("jobMakeMethod")
+ .select("*")
+ .eq("jobId", jobId)
+ .is("parentMaterialId", null)
+ .single(),
+ ]);
+
+ if (jobMakeMethod.error) {
+ throw new Error(
+ `Failed to get job make method: ${jobMakeMethod.error.message}`
+ );
+ }
+
+ const [jobMethodTrees] = await Promise.all([
+ getJobMethodTree(client, jobMakeMethod.data.id),
+ ]);
+
+ if (jobMethodTrees.error) {
+ throw new Error(
+ `Failed to get method tree: ${jobMethodTrees.error.message}`
+ );
+ }
+
+ const jobMethodTree = jobMethodTrees.data?.[0] as JobMethodTreeItem;
+ if (!jobMethodTree) {
+ throw new Error("Method tree not found");
+ }
+
+ await db.transaction().execute(async (trx) => {
+ const updateQuantities = async (
+ tree: JobMethodTreeItem,
+ parentQuantity: number = 1
+ ) => {
+ const currentQuantity = tree.data.quantity * parentQuantity;
+
+ // Update jobMaterial
+ await trx
+ .updateTable("jobMaterial")
+ .set({ estimatedQuantity: currentQuantity })
+ .where("id", "=", tree.id)
+ .execute();
+
+ // Update jobOperation
+ await trx
+ .updateTable("jobOperation")
+ .set({ operationQuantity: currentQuantity })
+ .where("jobMakeMethodId", "=", tree.data.jobMakeMethodId)
+ .execute();
+
+ // Recursively update children
+ if (tree.children) {
+ for (const child of tree.children) {
+ await updateQuantities(child, currentQuantity);
+ }
+ }
+ };
+
+ await updateQuantities(jobMethodTree, job.data?.quantity);
+ });
+
+ break;
+ }
+
+ default:
+ throw new Error(`Invalid type ${type}`);
+ }
+
+ return new Response(
+ JSON.stringify({
+ success: true,
+ }),
+ {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 200,
+ }
+ );
+ } catch (err) {
+ console.error(err);
+ return new Response(JSON.stringify(err), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 500,
+ });
+ }
+});
diff --git a/packages/database/supabase/migrations/20240920171731_job-requirements.sql b/packages/database/supabase/migrations/20240920171731_job-requirements.sql
new file mode 100644
index 0000000000..1de6567615
--- /dev/null
+++ b/packages/database/supabase/migrations/20240920171731_job-requirements.sql
@@ -0,0 +1,17 @@
+DROP VIEW "jobMaterialWithMakeMethodId";
+ALTER TABLE "jobMaterial"
+ DROP COLUMN "productionQuantity",
+ ADD COLUMN "estimatedQuantity" NUMERIC(10,4) DEFAULT 0;
+
+CREATE OR REPLACE VIEW "jobMaterialWithMakeMethodId" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ jm.*,
+ jmm."id" AS "jobMaterialMakeMethodId"
+ FROM "jobMaterial" jm
+ LEFT JOIN "jobMakeMethod" jmm
+ ON jmm."parentMaterialId" = jm."id";
+
+ALTER TABLE "jobOperation"
+ ADD COLUMN "operationQuantity" NUMERIC(10,4) DEFAULT 0,
+ ADD COLUMN "quantityComplete" NUMERIC(10,4) DEFAULT 0,
+ ADD COLUMN "quantityScrapped" NUMERIC(10,4) DEFAULT 0;
\ No newline at end of file