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: separate dependencies into their own table

Brad Barbin1218776baf8c
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index c6dc6ef106..4751ebefc8 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -765,6 +765,21 @@ export async function getScrapReasons(
return query;
}
+export async function recalculateJobOperationDependencies(
+ client: SupabaseClient<Database>,
+ params: {
+ jobId: string; // job operation id
+ companyId: string;
+ userId: string;
+ }
+) {
+ return client.functions.invoke("scheduler", {
+ body: {
+ type: "dependencies",
+ ...params,
+ },
+ });
+}
export async function recalculateJobRequirements(
client: SupabaseClient<Database>,
params: {
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
index 8d2fb2ffd7..8e5457ae6c 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
@@ -462,7 +462,7 @@ const JobBillOfProcess = ({
{ id },
{
method: "post",
- action: path.to.jobOperationsDelete,
+ action: path.to.jobOperationsDelete(jobId),
}
);
}
@@ -503,7 +503,7 @@ const JobBillOfProcess = ({
formData.append("updates", JSON.stringify(updates));
sortOrderFetcher.submit(formData, {
method: "post",
- action: path.to.jobOperationsOrder,
+ action: path.to.jobOperationsOrder(jobId),
});
},
1000,
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 1ef29715b2..4dbd3309c1 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
@@ -6,6 +6,7 @@ import { json, type ActionFunctionArgs } from "@vercel/remix";
import {
jobMaterialValidator,
recalculateJobMakeMethodRequirements,
+ recalculateJobOperationDependencies,
upsertJobMaterial,
} from "~/modules/production";
import { setCustomFields } from "~/utils/form";
@@ -66,23 +67,54 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- const recalculateResult = await recalculateJobMakeMethodRequirements(client, {
- id: validation.data.jobMakeMethodId,
- companyId,
- userId,
- });
+ if (validation.data.methodType === "Make") {
+ const promises = [
+ 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"
- )
- )
+ if (validation.data.jobOperationId) {
+ promises.push(
+ recalculateJobOperationDependencies(client, {
+ jobId,
+ companyId,
+ userId,
+ })
+ );
+ }
+
+ const [recalculateResult, recalculateDependencies] = await Promise.all(
+ promises
);
+
+ if (recalculateResult.error) {
+ return json(
+ { id: jobMaterialId },
+ await flash(
+ request,
+ error(
+ recalculateResult.error,
+ "Failed to recalculate job make method requirements"
+ )
+ )
+ );
+ }
+
+ if (recalculateDependencies?.error) {
+ return json(
+ { id: jobMaterialId },
+ await flash(
+ request,
+ error(
+ recalculateDependencies.error,
+ "Failed to recalculate job operation dependencies"
+ )
+ )
+ );
+ }
}
return json({
diff --git a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.delete.$id.tsx b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.delete.$id.tsx
index 24519a8cf3..348e8d91a1 100644
--- a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.delete.$id.tsx
@@ -1,20 +1,27 @@
-import { assertIsPost, error } from "@carbon/auth";
+import { assertIsPost, error, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { json, type ActionFunctionArgs } from "@vercel/remix";
-import { deleteJobMaterial } from "~/modules/production";
+import {
+ deleteJobMaterial,
+ recalculateJobOperationDependencies,
+} from "~/modules/production";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
delete: "production",
});
- const { id } = params;
+ const { id, jobId } = params;
if (!id) {
throw new Error("id not found");
}
+ if (!jobId) {
+ throw new Error("jobId not found");
+ }
+
const deleteMaterial = await deleteJobMaterial(client, id);
if (deleteMaterial.error) {
return json(
@@ -28,6 +35,25 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ const recalculateResult = await recalculateJobOperationDependencies(
+ getCarbonServiceRole(),
+ {
+ jobId,
+ companyId,
+ userId,
+ }
+ );
+
+ if (recalculateResult?.error) {
+ return json(
+ {
+ success: false,
+ error: "Failed to recalculate job operation dependencies",
+ },
+ { status: 400 }
+ );
+ }
+
// TODO: if it is a make method -- we should get the tree from the jobMakeMethod with parentMaterialId = id, and delete everything that comes back
return json({});
diff --git a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx
index 385a203686..8587966672 100644
--- a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx
@@ -6,6 +6,7 @@ import { json, type ActionFunctionArgs } from "@vercel/remix";
import {
jobMaterialValidator,
recalculateJobMakeMethodRequirements,
+ recalculateJobOperationDependencies,
upsertJobMaterial,
upsertJobMaterialMakeMethod,
} from "~/modules/production";
@@ -99,28 +100,54 @@ export async function action({ request, params }: ActionFunctionArgs) {
)
);
}
- }
- const recalculateResult = await recalculateJobMakeMethodRequirements(
- serviceRole,
- {
- id: validation.data.jobMakeMethodId,
- companyId,
- userId,
+ const promises = [
+ recalculateJobMakeMethodRequirements(serviceRole, {
+ id: validation.data.jobMakeMethodId,
+ companyId,
+ userId,
+ }),
+ ];
+
+ if (validation.data.jobOperationId) {
+ promises.push(
+ recalculateJobOperationDependencies(serviceRole, {
+ jobId,
+ companyId,
+ userId,
+ })
+ );
}
- );
- if (recalculateResult.error) {
- return json(
- { id: jobMaterialId },
- await flash(
- request,
- error(
- recalculateResult.error,
- "Failed to recalculate job make method requirements"
- )
- )
+ const [recalculateResult, recalculateDependencies] = await Promise.all(
+ promises
);
+
+ if (recalculateResult.error) {
+ return json(
+ { id: jobMaterialId },
+ await flash(
+ request,
+ error(
+ recalculateResult.error,
+ "Failed to recalculate job make method requirements"
+ )
+ )
+ );
+ }
+
+ if (recalculateDependencies?.error) {
+ return json(
+ { id: jobMaterialId },
+ await flash(
+ request,
+ error(
+ recalculateDependencies.error,
+ "Failed to recalculate job operation dependencies"
+ )
+ )
+ );
+ }
}
return json({ id: jobMaterialId });
diff --git a/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.new.tsx b/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.new.tsx
index f1dede23b4..a3c869bf36 100644
--- a/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.new.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.new.tsx
@@ -6,6 +6,7 @@ import { json, type ActionFunctionArgs } from "@vercel/remix";
import {
jobOperationValidator,
recalculateJobMakeMethodRequirements,
+ recalculateJobOperationDependencies,
upsertJobOperation,
} from "~/modules/production";
import { setCustomFields } from "~/utils/form";
@@ -63,14 +64,18 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- const recalculateResult = await recalculateJobMakeMethodRequirements(
- serviceRole,
- {
+ const [recalculateResult, recalculateDependencies] = await Promise.all([
+ recalculateJobMakeMethodRequirements(serviceRole, {
id: validation.data.jobMakeMethodId,
companyId,
userId,
- }
- );
+ }),
+ recalculateJobOperationDependencies(serviceRole, {
+ jobId,
+ companyId,
+ userId,
+ }),
+ ]);
if (recalculateResult.error) {
return json(
@@ -85,5 +90,18 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ if (recalculateDependencies?.error) {
+ return json(
+ { id: jobOperationId },
+ await flash(
+ request,
+ error(
+ recalculateDependencies.error,
+ "Failed to recalculate job operation dependencies"
+ )
+ )
+ );
+ }
+
return json({ id: jobOperationId });
}
diff --git a/apps/erp/app/routes/x+/job+/methods+/get.tsx b/apps/erp/app/routes/x+/job+/methods+/get.tsx
index 507b1aabd1..735ebb288b 100644
--- a/apps/erp/app/routes/x+/job+/methods+/get.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/get.tsx
@@ -4,6 +4,7 @@ import { validationError, validator } from "@carbon/form";
import { json, redirect, type ActionFunctionArgs } from "@vercel/remix";
import {
getJobMethodValidator,
+ recalculateJobOperationDependencies,
recalculateJobRequirements,
upsertJobMaterialMakeMethod,
upsertJobMethod,
@@ -36,11 +37,18 @@ export async function action({ request }: ActionFunctionArgs) {
}
);
- const calculateQuantities = await recalculateJobRequirements(serviceRole, {
- id: validation.data.targetId,
- companyId: companyId,
- userId: userId,
- });
+ const [calculateQuantities, calculateDependencies] = await Promise.all([
+ recalculateJobRequirements(serviceRole, {
+ id: validation.data.targetId,
+ companyId: companyId,
+ userId: userId,
+ }),
+ recalculateJobOperationDependencies(serviceRole, {
+ jobId: validation.data.targetId,
+ companyId: companyId,
+ userId: userId,
+ }),
+ ]);
if (calculateQuantities.error) {
return json({
@@ -48,6 +56,12 @@ export async function action({ request }: ActionFunctionArgs) {
});
}
+ if (calculateDependencies.error) {
+ return json({
+ error: "Failed to calculate job dependencies",
+ });
+ }
+
return json({
error: jobMethod.error ? "Failed to get job method" : null,
});
diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.delete.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.delete.tsx
deleted file mode 100644
index ef273aadac..0000000000
--- a/apps/erp/app/routes/x+/job+/methods+/operation.delete.tsx
+++ /dev/null
@@ -1,34 +0,0 @@
-import { requirePermissions } from "@carbon/auth/auth.server";
-import type { ActionFunctionArgs } from "@vercel/remix";
-import { json } from "@vercel/remix";
-
-export async function action({ request }: ActionFunctionArgs) {
- const { client } = await requirePermissions(request, {
- delete: "production",
- });
-
- const formData = await request.formData();
- const id = formData.get("id") as string;
-
- if (!id) {
- return json(
- { error: "Operation ID is required" },
- {
- status: 400,
- }
- );
- }
-
- const { error } = await client.from("jobOperation").delete().eq("id", id);
-
- if (error) {
- return json(
- { success: false, error: error.message },
- {
- status: 400,
- }
- );
- }
-
- return json({ success: true });
-}
diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.order.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.order.tsx
deleted file mode 100644
index 63511225fa..0000000000
--- a/apps/erp/app/routes/x+/job+/methods+/operation.order.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-import { json, type ActionFunctionArgs } from "@vercel/remix";
-
-import { assertIsPost, error } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import { updateJobOperationOrder } from "~/modules/production";
-
-export async function action({ request }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
- update: "production",
- });
-
- const updateMap = (await request.formData()).get("updates") as string;
- if (!updateMap) {
- return json(
- {},
- await flash(request, error(null, "Failed to receive a new sort order"))
- );
- }
-
- const updates = Object.entries(JSON.parse(updateMap)).map(
- ([id, orderString]) => ({
- id,
- order: Number(orderString),
- updatedBy: userId,
- })
- );
-
- const updateSortOrders = await updateJobOperationOrder(client, updates);
- if (updateSortOrders.some((update) => update.error))
- return json(
- {},
- await flash(
- request,
- error(updateSortOrders, "Failed to update sort order")
- )
- );
-
- return null;
-}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 23ee7c5d5f..1f83480534 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -609,8 +609,10 @@ export const path = {
jobOperation: (jobId: string, id: string) =>
generatePath(`${x}/job/methods/${jobId}/operation/${id}`),
jobOperations: (id: string) => generatePath(`${x}/job/${id}/operations`),
- jobOperationsOrder: `${x}/job/methods/operation/order`,
- jobOperationsDelete: `${x}/job/methods/operation/delete`,
+ jobOperationsOrder: (jobId: string) =>
+ generatePath(`${x}/job/methods/${jobId}/operation/order`),
+ jobOperationsDelete: (jobId: string) =>
+ generatePath(`${x}/job/methods/${jobId}/operation/delete`),
jobOperationAttribute: (id: string) =>
generatePath(`${x}/job/methods/operation/attribute/${id}`),
jobOperationParameter: (id: string) =>
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index bebe845285..2d77261e97 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -17109,6 +17109,141 @@ export default {
tags: ["shifts"],
},
},
+ "/jobOperationDependency": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.jobOperationDependency.operationId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationDependency.dependsOnId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationDependency.jobId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationDependency.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationDependency.createdAt",
+ },
+ {
+ $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/jobOperationDependency",
+ },
+ type: "array",
+ },
+ },
+ "206": {
+ description: "Partial Content",
+ },
+ },
+ tags: ["jobOperationDependency"],
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.jobOperationDependency",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/preferPost",
+ },
+ ],
+ responses: {
+ "201": {
+ description: "Created",
+ },
+ },
+ tags: ["jobOperationDependency"],
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.jobOperationDependency.operationId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationDependency.dependsOnId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationDependency.jobId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationDependency.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationDependency.createdAt",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["jobOperationDependency"],
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.jobOperationDependency.operationId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationDependency.dependsOnId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationDependency.jobId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationDependency.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationDependency.createdAt",
+ },
+ {
+ $ref: "#/parameters/body.jobOperationDependency",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["jobOperationDependency"],
+ },
+ },
"/purchaseOrderStatusHistory": {
get: {
parameters: [
@@ -59478,6 +59613,47 @@ export default {
},
type: "object",
},
+ jobOperationDependency: {
+ required: [
+ "operationId",
+ "dependsOnId",
+ "jobId",
+ "companyId",
+ "createdAt",
+ ],
+ properties: {
+ operationId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `jobOperation.id`.<fk table='jobOperation' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ dependsOnId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `jobOperation.id`.<fk table='jobOperation' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ jobId: {
+ description:
+ "Note:\nThis is a Foreign Key to `job.id`.<fk table='job' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ },
+ type: "object",
+ },
purchaseOrderStatusHistory: {
required: ["id", "purchaseOrderId", "status", "createdAt", "createdBy"],
properties: {
@@ -82510,6 +82686,45 @@ export default {
in: "query",
type: "string",
},
+ "body.jobOperationDependency": {
+ name: "jobOperationDependency",
+ description: "jobOperationDependency",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/jobOperationDependency",
+ },
+ },
+ "rowFilter.jobOperationDependency.operationId": {
+ name: "operationId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobOperationDependency.dependsOnId": {
+ name: "dependsOnId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobOperationDependency.jobId": {
+ name: "jobId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobOperationDependency.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobOperationDependency.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.purchaseOrderStatusHistory": {
name: "purchaseOrderStatusHistory",
description: "purchaseOrderStatusHistory",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 40025f7175..b1de7cf8d7 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -8650,7 +8650,6 @@ export type Database = {
createdAt: string
createdBy: string
customFields: Json | null
- dependencies: string[] | null
description: string | null
id: string
jobId: string
@@ -8691,7 +8690,6 @@ export type Database = {
createdAt?: string
createdBy: string
customFields?: Json | null
- dependencies?: string[] | null
description?: string | null
id?: string
jobId: string
@@ -8732,7 +8730,6 @@ export type Database = {
createdAt?: string
createdBy?: string
customFields?: Json | null
- dependencies?: string[] | null
description?: string | null
id?: string
jobId?: string
@@ -9298,6 +9295,101 @@ export type Database = {
},
]
}
+ jobOperationDependency: {
+ Row: {
+ companyId: string
+ createdAt: string
+ dependsOnId: string
+ jobId: string
+ operationId: string
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ dependsOnId: string
+ jobId: string
+ operationId: string
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ dependsOnId?: string
+ jobId?: string
+ operationId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "jobOperationDependency_companyId_fk"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationDependency_companyId_fk"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationDependency_companyId_fk"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "jobOperationDependency_companyId_fk"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "jobOperationDependency_dependsOnId_fk"
+ columns: ["dependsOnId"]
+ isOneToOne: false
+ referencedRelation: "jobOperation"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationDependency_dependsOnId_fk"
+ columns: ["dependsOnId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationsWithMakeMethods"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationDependency_jobId_fk"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "job"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationDependency_jobId_fk"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationDependency_operationId_fk"
+ columns: ["operationId"]
+ isOneToOne: false
+ referencedRelation: "jobOperation"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationDependency_operationId_fk"
+ columns: ["operationId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationsWithMakeMethods"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
jobOperationNote: {
Row: {
companyId: string
@@ -33475,14 +33567,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -34810,14 +34902,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -36905,14 +36997,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
diff --git a/packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts b/packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts
index d11361c172..bf3effadaf 100644
--- a/packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts
+++ b/packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts
@@ -11,6 +11,7 @@ class SchedulingEngine {
private client: SupabaseClient<Database>;
private db: Kysely<DB>;
private jobId: string;
+ private companyId: string;
private operationsToSchedule: BaseOperation[];
private operationsByJobMakeMethodId: Record<string, BaseOperation[]>;
private makeMethodDependencies: {
@@ -35,7 +36,7 @@ class SchedulingEngine {
}) {
this.db = db;
this.client = client;
-
+ this.companyId = companyId;
this.jobId = jobId;
this.operationsToSchedule = [];
this.operationsByJobMakeMethodId = {};
@@ -70,7 +71,6 @@ class SchedulingEngine {
const jobMakeMethodToOperationId: Record<string, string | null> = {};
- console.log({ jobMaterials });
jobMaterials.forEach((m) => {
if (m.jobMaterialMakeMethodId) {
jobMakeMethodToOperationId[m.jobMaterialMakeMethodId] =
@@ -134,15 +134,30 @@ class SchedulingEngine {
}
}
+ console.log({ operationDependencies });
+
+ await this.db
+ .deleteFrom("jobOperationDependency")
+ .where("jobId", "=", this.jobId)
+ .execute();
+
if (Object.keys(operationDependencies).length > 0) {
for await (const [operationId, dependencies] of Object.entries(
operationDependencies
)) {
- await this.db
- .updateTable("jobOperation")
- .set({ dependencies: Array.from(dependencies) })
- .where("id", "=", operationId)
- .execute();
+ if (dependencies.size > 0) {
+ await this.db
+ .insertInto("jobOperationDependency")
+ .values(
+ Array.from(dependencies).map((dependency) => ({
+ jobId: this.jobId,
+ operationId,
+ dependsOnId: dependency,
+ companyId: this.companyId,
+ }))
+ )
+ .execute();
+ }
}
}
}
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 40025f7175..b1de7cf8d7 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -8650,7 +8650,6 @@ export type Database = {
createdAt: string
createdBy: string
customFields: Json | null
- dependencies: string[] | null
description: string | null
id: string
jobId: string
@@ -8691,7 +8690,6 @@ export type Database = {
createdAt?: string
createdBy: string
customFields?: Json | null
- dependencies?: string[] | null
description?: string | null
id?: string
jobId: string
@@ -8732,7 +8730,6 @@ export type Database = {
createdAt?: string
createdBy?: string
customFields?: Json | null
- dependencies?: string[] | null
description?: string | null
id?: string
jobId?: string
@@ -9298,6 +9295,101 @@ export type Database = {
},
]
}
+ jobOperationDependency: {
+ Row: {
+ companyId: string
+ createdAt: string
+ dependsOnId: string
+ jobId: string
+ operationId: string
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ dependsOnId: string
+ jobId: string
+ operationId: string
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ dependsOnId?: string
+ jobId?: string
+ operationId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "jobOperationDependency_companyId_fk"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationDependency_companyId_fk"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationDependency_companyId_fk"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "jobOperationDependency_companyId_fk"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "jobOperationDependency_dependsOnId_fk"
+ columns: ["dependsOnId"]
+ isOneToOne: false
+ referencedRelation: "jobOperation"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationDependency_dependsOnId_fk"
+ columns: ["dependsOnId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationsWithMakeMethods"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationDependency_jobId_fk"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "job"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationDependency_jobId_fk"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationDependency_operationId_fk"
+ columns: ["operationId"]
+ isOneToOne: false
+ referencedRelation: "jobOperation"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperationDependency_operationId_fk"
+ columns: ["operationId"]
+ isOneToOne: false
+ referencedRelation: "jobOperationsWithMakeMethods"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
jobOperationNote: {
Row: {
companyId: string
@@ -33475,14 +33567,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -34810,14 +34902,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -36905,14 +36997,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
diff --git a/packages/database/supabase/migrations/20250429130223_operation-dependencies.sql b/packages/database/supabase/migrations/20250429130223_operation-dependencies.sql
index dfc130af03..ec41d65cb7 100644
--- a/packages/database/supabase/migrations/20250429130223_operation-dependencies.sql
+++ b/packages/database/supabase/migrations/20250429130223_operation-dependencies.sql
@@ -1,2 +1,21 @@
-ALTER TABLE "jobOperation" ADD COLUMN "dependencies" TEXT[] DEFAULT '{}';
+-- Create a dedicated table for operation dependencies
+CREATE TABLE "jobOperationDependency" (
+ "operationId" TEXT NOT NULL,
+ "dependsOnId" TEXT NOT NULL,
+ "jobId" TEXT NOT NULL,
+ "companyId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+
+ CONSTRAINT "jobOperationDependency_pk" PRIMARY KEY ("operationId", "dependsOnId"),
+ CONSTRAINT "jobOperationDependency_operationId_fk" FOREIGN KEY ("operationId") REFERENCES "jobOperation"("id") ON DELETE CASCADE,
+ CONSTRAINT "jobOperationDependency_dependsOnId_fk" FOREIGN KEY ("dependsOnId") REFERENCES "jobOperation"("id") ON DELETE CASCADE,
+ CONSTRAINT "jobOperationDependency_jobId_fk" FOREIGN KEY ("jobId") REFERENCES "job"("id") ON DELETE CASCADE,
+ CONSTRAINT "jobOperationDependency_companyId_fk" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE,
+ CONSTRAINT "jobOperationDependency_no_self_dependency" CHECK ("operationId" != "dependsOnId")
+);
+
+
+-- Create an index to improve query performance on the dependency table
+CREATE INDEX "idx_jobOperationDependency_operationId" ON "jobOperationDependency" ("operationId");
+CREATE INDEX "idx_jobOperationDependency_jobId" ON "jobOperationDependency" ("jobId");