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: assign materials to the first available operation

Brad Barbincbf129f09d13
diff --git a/packages/database/supabase/functions/lib/scheduling/material-manager.ts b/packages/database/supabase/functions/lib/scheduling/material-manager.ts
index 69ea20954c..4d3a655acf 100644
--- a/packages/database/supabase/functions/lib/scheduling/material-manager.ts
+++ b/packages/database/supabase/functions/lib/scheduling/material-manager.ts
@@ -1,37 +1,77 @@
import { Kysely } from "https://esm.sh/[email protected]";
import { DB } from "../database.ts";
+import { BaseOperation } from "./types.ts";
class MaterialManager {
private db: Kysely<DB>;
private companyId: string;
+ private materialsWithoutOperations: {
+ id: string;
+ jobMakeMethodId: string;
+ }[] = [];
constructor(db: Kysely<DB>, companyId: string) {
this.db = db;
this.companyId = companyId;
+ this.materialsWithoutOperations = [];
}
async initialize(jobId: string) {
- if (!this.db) {
- throw new Error("Database connection is not initialized");
+ const materialsWithoutOperations = await this.db
+ .selectFrom("jobMaterial")
+ .select(["id", "jobMakeMethodId"])
+ .where("jobId", "=", jobId)
+ .where("jobOperationId", "is", null)
+ .execute();
+
+ this.materialsWithoutOperations = materialsWithoutOperations.reduce<
+ { id: string; jobMakeMethodId: string }[]
+ >((acc, material) => {
+ if (material.id) {
+ acc.push({
+ id: material.id,
+ jobMakeMethodId: material.jobMakeMethodId,
+ });
+ }
+ return acc;
+ }, []);
+ }
+
+ async assignOperationsToMaterials(
+ validMaterialIds: string[],
+ operationsByJobMakeMethodId: Record<string, BaseOperation[]>
+ ) {
+ const updates: { materialId: string; operationId: string }[] = [];
+
+ for await (const material of this.materialsWithoutOperations) {
+ if (!validMaterialIds.includes(material.id)) {
+ continue;
+ }
+
+ const operations =
+ operationsByJobMakeMethodId[material.jobMakeMethodId] || [];
+ const firstOperation = operations[0];
+
+ if (firstOperation?.id) {
+ updates.push({
+ materialId: material.id,
+ operationId: firstOperation.id,
+ });
+ }
}
- const [materialToAssign, jobOperations] = await Promise.all([
- this.db
- .selectFrom("jobMaterial")
- .selectAll()
- .where("jobId", "=", jobId)
- .where("jobOperationId", "is", null)
- .where("companyId", "=", this.companyId)
- .execute(),
- this.db
- .selectFrom("jobOperation")
- .selectAll()
- .where("jobId", "=", jobId)
- .execute(),
- ]);
-
- console.log({ materialToAssign, jobOperations });
+ if (updates.length > 0) {
+ for await (const update of updates) {
+ await this.db
+ .updateTable("jobMaterial")
+ .set({
+ jobOperationId: update.operationId,
+ })
+ .where("id", "=", update.materialId)
+ .execute();
+ }
+ }
}
}
diff --git a/packages/database/supabase/functions/lib/scheduling/engine.ts b/packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts
similarity index 87%
rename from packages/database/supabase/functions/lib/scheduling/engine.ts
rename to packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts
index 375a5e36e0..afaf27a106 100644
--- a/packages/database/supabase/functions/lib/scheduling/engine.ts
+++ b/packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts
@@ -12,6 +12,9 @@ class SchedulingEngine {
private db: Kysely<DB>;
private jobId: string;
private operationsToSchedule: BaseOperation[];
+ private operationsByJobMakeMethodId: Record<string, BaseOperation[]>;
+ private validMaterialIds: string[];
+
private resourceManager: ResourceManager;
private materialManager: MaterialManager;
@@ -28,10 +31,14 @@ class SchedulingEngine {
}) {
this.db = db;
this.client = client;
+
this.jobId = jobId;
this.operationsToSchedule = [];
- this.resourceManager = new ResourceManager(db, companyId);
+ this.operationsByJobMakeMethodId = {};
+ this.validMaterialIds = [];
+
this.materialManager = new MaterialManager(db, companyId);
+ this.resourceManager = new ResourceManager(db, companyId);
}
async initialize(): Promise<void> {
@@ -41,10 +48,17 @@ class SchedulingEngine {
await Promise.all([
this.resourceManager.initialize(this.jobId),
this.materialManager.initialize(this.jobId),
- this.getOperationsToSchedule(),
+ this.getOperationsAndMaterialsToSchedule(),
]);
}
+ async assign() {
+ await this.materialManager.assignOperationsToMaterials(
+ this.validMaterialIds,
+ this.operationsByJobMakeMethodId
+ );
+ }
+
async prioritize(
strategy: SchedulingStrategy = SchedulingStrategy.LeastTime
): Promise<void> {
@@ -121,7 +135,7 @@ class SchedulingEngine {
}
}
- async getOperationsToSchedule() {
+ async getOperationsAndMaterialsToSchedule() {
if (!this.db) {
throw new Error("Database connection is not initialized");
}
@@ -138,6 +152,7 @@ class SchedulingEngine {
.where("jobId", "=", this.jobId)
.where("status", "not in", ["Done", "Canceled"])
.where("operationType", "not in", ["Outside"])
+ .orderBy("order")
.execute(),
]);
@@ -152,6 +167,8 @@ class SchedulingEngine {
return acc;
}, {});
+ this.operationsByJobMakeMethodId = operationsByJobMakeMethodId;
+
if (!jobMakeMethod?.id) {
throw new Error("Job make method not found");
}
@@ -168,6 +185,7 @@ class SchedulingEngine {
const operationsToSchedule: BaseOperation[] = [];
const queue: JobMethodTreeItem[] = [jobMethodTree];
+ const validMaterialIds: string[] = [];
while (queue.length > 0) {
const currentNode = queue.shift();
@@ -178,10 +196,15 @@ class SchedulingEngine {
[];
operationsToSchedule.unshift(...operations);
+ if (!currentNode.data.isRoot && currentNode.data.methodMaterialId) {
+ validMaterialIds.push(currentNode.data.methodMaterialId);
+ }
+
queue.push(...currentNode.children);
}
this.operationsToSchedule = operationsToSchedule;
+ this.validMaterialIds = validMaterialIds;
}
}
diff --git a/packages/database/supabase/functions/scheduler/index.ts b/packages/database/supabase/functions/scheduler/index.ts
index 4f197d490d..f1b611a127 100644
--- a/packages/database/supabase/functions/scheduler/index.ts
+++ b/packages/database/supabase/functions/scheduler/index.ts
@@ -3,7 +3,8 @@ 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 { SchedulingEngine } from "../lib/scheduling/engine.ts";
+import { SchedulingEngine } from "../lib/scheduling/scheduling-engine.ts";
+import { SchedulingStrategy } from "../lib/scheduling/types.ts";
import { getSupabaseServiceRoleFromAuthorizationHeader } from "../lib/supabase.ts";
const pool = getConnectionPool(1);
@@ -39,7 +40,10 @@ serve(async (req: Request) => {
const engine = new SchedulingEngine({ client, db, jobId, companyId });
await engine.initialize();
- // await engine.prioritize(SchedulingStrategy.LeastTime);
+ await Promise.all([
+ engine.prioritize(SchedulingStrategy.LeastTime),
+ engine.assign(),
+ ]);
return new Response(
JSON.stringify({