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.

llm: add basic infrastructure for backwards scheduling on reorder of job due dates

Brad Barbincf0c5a4da479
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 20aaf246a7..bd83b88af4 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -2459,3 +2459,21 @@ export async function upsertDemandProjections(
error: hasError ? results.find((r) => r.error)?.error : null,
};
}
+
+export async function triggerJobReschedule(
+ jobId: string,
+ companyId: string,
+ userId: string
+) {
+ const { rescheduleJob } = await import(
+ "@carbon/jobs/trigger/reschedule-job"
+ );
+
+ const handle = await rescheduleJob.trigger({
+ jobId,
+ companyId,
+ userId,
+ });
+
+ return { success: true, runId: handle.id };
+}
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/ScheuleNavigation.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/ScheuleNavigation.tsx
index 0747edf906..a076ab379f 100644
--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/ScheuleNavigation.tsx
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/ScheuleNavigation.tsx
@@ -15,6 +15,7 @@ import {
LuCalendar,
LuCalendarDays,
LuChevronDown,
+ LuCog,
LuList,
} from "react-icons/lu";
import { path } from "~/utils/path";
@@ -41,7 +42,7 @@ export function ScheduleNavigation() {
const getViewLabel = (option: string) => {
switch (option) {
case "operations":
- return "Operations";
+ return "Work Centers";
case "week":
return "Week";
case "month":
@@ -54,7 +55,7 @@ export function ScheduleNavigation() {
const getViewIcon = (option: string) => {
switch (option) {
case "operations":
- return <LuList />;
+ return <LuCog />;
case "week":
return <LuCalendarDays />;
case "month":
@@ -98,6 +99,7 @@ export function ScheduleNavigation() {
value={currentValue}
onValueChange={navigateToView}
>
+ <DropdownMenuLabel>Operations</DropdownMenuLabel>
<DropdownMenuRadioItem value="operations">
<DropdownMenuIcon icon={getViewIcon("operations")} />
{getViewLabel("operations")}
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/components/JobCard.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/JobCard.tsx
index 7df15fedd1..1006df2d75 100644
--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/components/JobCard.tsx
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/JobCard.tsx
@@ -28,6 +28,7 @@ import {
LuGripVertical,
LuPencil,
LuStar,
+ LuTriangleAlert,
LuUsers,
} from "react-icons/lu";
@@ -163,6 +164,7 @@ export function JobCard({ item, isOverlay, progressByItemId }: JobCardProps) {
style={style}
className={cn(
"max-w-[330px] shadow-sm dark:shadow-sm py-0",
+ item.hasConflict && "border-red-500 border-2",
cardVariants({
dragging: isOverlay ? "overlay" : isDragging ? "over" : undefined,
status: status,
@@ -184,12 +186,24 @@ export function JobCard({ item, isOverlay, progressByItemId }: JobCardProps) {
{item?.description || item.itemReadableId}
</span>
)}
- <Link
- to={item.link ?? path.to.job(item.jobId)}
- className="mr-auto font-semibold line-clamp-2 leading-tight"
- >
- {item.jobReadableId}
- </Link>
+ <HStack spacing={1} className="items-center">
+ <Link
+ to={item.link ?? path.to.job(item.jobId)}
+ className="mr-auto font-semibold line-clamp-2 leading-tight"
+ >
+ {item.jobReadableId}
+ </Link>
+ {item.hasConflict && (
+ <Tooltip>
+ <TooltipTrigger>
+ <LuTriangleAlert className="h-4 w-4 text-red-500 flex-shrink-0" />
+ </TooltipTrigger>
+ <TooltipContent>
+ Scheduling conflict: operations cannot meet due date
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </HStack>
{customer && displaySettings.showCustomer && (
<span className="text-xs text-muted-foreground line-clamp-1">
{customer.name}
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/types.ts b/apps/erp/app/modules/production/ui/Schedule/Kanban/types.ts
index 648f1a6d79..eb45d56d1f 100644
--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/types.ts
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/types.ts
@@ -83,6 +83,7 @@ const operationItemValidator = baseItemValidator.extend({
const jobItemValidator = baseItemValidator.extend({
status: z.enum(jobStatus).optional(),
completedDate: z.string().optional(),
+ hasConflict: z.boolean().optional(),
});
export type OperationItem = z.infer<typeof operationItemValidator>;
diff --git a/apps/erp/app/routes/api+/ai+/chat+/agents/purchasing-agent.ts b/apps/erp/app/routes/api+/ai+/chat+/agents/purchasing-agent.ts
index fa9329cabf..32eecdc4f0 100644
--- a/apps/erp/app/routes/api+/ai+/chat+/agents/purchasing-agent.ts
+++ b/apps/erp/app/routes/api+/ai+/chat+/agents/purchasing-agent.ts
@@ -22,9 +22,6 @@ export const purchasingAgent = createAgent({
ctx.companyName
}. Create purchase orders or get quotes from suppliers.
-Notes:
-- ALWAYS use the actual IDs when passing part IDs to tools.
-- ALWAYS show the readable ID when showing part details to the user.
When handling purchase order requests:
1. First identify the part details (including quantities and measurements)
@@ -64,6 +61,8 @@ ${COMMON_AGENT_RULES}
<guidelines>
- For direct queries: lead with results, add context
+- ALWAYS use the actual IDs when passing part IDs to tools.
+- ALWAYS show the readable ID when showing part details to the user.
</guidelines>`,
tools: {
getPart: getPartTool,
diff --git a/apps/erp/app/routes/onboarding+/_index.tsx b/apps/erp/app/routes/onboarding+/_index.tsx
index be15ac884e..a7a9c5f87b 100644
--- a/apps/erp/app/routes/onboarding+/_index.tsx
+++ b/apps/erp/app/routes/onboarding+/_index.tsx
@@ -40,7 +40,7 @@ export default function GetStarted() {
transition={{ duration: 1.2, ease: "easeInOut", delay: 1.7 }}
className="text-muted-foreground text-balance text-base pb-4"
>
- The new standard for tech-enabled manufacturing
+ The operating system for manufacturing
</motion.p>
<Button
diff --git a/apps/erp/app/routes/x+/schedule+/dates.tsx b/apps/erp/app/routes/x+/schedule+/dates.tsx
index d16b35aeb6..a6cd1638b2 100644
--- a/apps/erp/app/routes/x+/schedule+/dates.tsx
+++ b/apps/erp/app/routes/x+/schedule+/dates.tsx
@@ -40,7 +40,6 @@ import type { ColumnFilter } from "~/components/Table/components/Filter/types";
import { useUrlParams } from "~/hooks";
import { getJobsByDateRange } from "~/modules/production";
import type { Column, JobItem } from "~/modules/production/ui/Schedule";
-
import type { DisplaySettings } from "~/modules/production/ui/Schedule/Kanban";
import { DateKanban } from "~/modules/production/ui/Schedule/Kanban/DateKanban";
import { ScheduleNavigation } from "~/modules/production/ui/Schedule/Kanban/ScheuleNavigation";
@@ -351,6 +350,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
laborDuration: 0,
machineDuration: 0,
thumbnailPath: job.thumbnailPath,
+ hasConflict: job.hasConflict,
};
}) ?? []) satisfies JobItem[],
salesOrders: Object.entries(
diff --git a/apps/erp/app/routes/x+/schedule+/dates.update.tsx b/apps/erp/app/routes/x+/schedule+/dates.update.tsx
index 6d35bbcf68..9ff864306a 100644
--- a/apps/erp/app/routes/x+/schedule+/dates.update.tsx
+++ b/apps/erp/app/routes/x+/schedule+/dates.update.tsx
@@ -3,9 +3,10 @@ import { validator } from "@carbon/form";
import type { ActionFunctionArgs } from "@vercel/remix";
import { json } from "@vercel/remix";
import { scheduleJobUpdateValidator } from "~/modules/production/production.models";
+import { triggerJobReschedule } from "~/modules/production/production.service";
export async function action({ request }: ActionFunctionArgs) {
- const { client, userId } = await requirePermissions(request, {
+ const { client, userId, companyId } = await requirePermissions(request, {
update: "production",
});
@@ -49,5 +50,13 @@ export async function action({ request }: ActionFunctionArgs) {
return json({ success: false, message: error.message });
}
+ // Trigger background job rescheduling
+ try {
+ await triggerJobReschedule(validation.data.id, companyId, userId);
+ } catch (rescheduleError) {
+ // Log error but don't fail the request - reschedule can retry
+ console.error("Failed to trigger job reschedule:", rescheduleError);
+ }
+
return json({ success: true });
}
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 9a6cf6695a..4b9f5855a9 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -20799,6 +20799,9 @@ export default {
{
$ref: "#/parameters/rowFilter.job.shelfId",
},
+ {
+ $ref: "#/parameters/rowFilter.job.priority",
+ },
{
$ref: "#/parameters/select",
},
@@ -20969,6 +20972,9 @@ export default {
{
$ref: "#/parameters/rowFilter.job.shelfId",
},
+ {
+ $ref: "#/parameters/rowFilter.job.priority",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -21093,6 +21099,9 @@ export default {
{
$ref: "#/parameters/rowFilter.job.shelfId",
},
+ {
+ $ref: "#/parameters/rowFilter.job.priority",
+ },
{
$ref: "#/parameters/body.job",
},
@@ -26883,6 +26892,12 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperation.dueDate",
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.hasConflict",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.conflictReason",
+ },
{
$ref: "#/parameters/select",
},
@@ -27062,6 +27077,12 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperation.dueDate",
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.hasConflict",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.conflictReason",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -27195,6 +27216,12 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperation.dueDate",
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.hasConflict",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.conflictReason",
+ },
{
$ref: "#/parameters/body.jobOperation",
},
@@ -57151,6 +57178,49 @@ export default {
tags: ["(rpc) create_rfq_from_models_v1"],
},
},
+ "/rpc/get_jobs_by_date_range": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ end_date: {
+ format: "date",
+ type: "string",
+ },
+ location_id: {
+ format: "text",
+ type: "string",
+ },
+ start_date: {
+ format: "date",
+ type: "string",
+ },
+ },
+ required: ["location_id", "start_date", "end_date"],
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) get_jobs_by_date_range"],
+ },
+ },
"/rpc/get_companies_with_permission": {
post: {
parameters: [
@@ -69815,6 +69885,7 @@ export default {
"companyId",
"createdAt",
"createdBy",
+ "priority",
],
properties: {
id: {
@@ -70009,6 +70080,11 @@ export default {
format: "text",
type: "string",
},
+ priority: {
+ default: 1,
+ format: "double precision",
+ type: "number",
+ },
},
type: "object",
},
@@ -72828,6 +72904,18 @@ export default {
format: "date",
type: "string",
},
+ hasConflict: {
+ default: false,
+ description:
+ "Indicates if this operation has a scheduling conflict (e.g., start date in the past)",
+ format: "boolean",
+ type: "boolean",
+ },
+ conflictReason: {
+ description: "Human-readable explanation of the scheduling conflict",
+ format: "text",
+ type: "string",
+ },
},
type: "object",
},
@@ -98025,6 +98113,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.job.priority": {
+ name: "priority",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.contact": {
name: "contact",
description: "contact",
@@ -101157,6 +101251,21 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.jobOperation.hasConflict": {
+ name: "hasConflict",
+ description:
+ "Indicates if this operation has a scheduling conflict (e.g., start date in the past)",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobOperation.conflictReason": {
+ name: "conflictReason",
+ description: "Human-readable explanation of the scheduling conflict",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.userAttributeCategory": {
name: "userAttributeCategory",
description: "userAttributeCategory",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 2db23d6eca..d46e77b983 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -10523,11 +10523,13 @@ export type Database = {
Row: {
assignee: string | null
companyId: string
+ conflictReason: string | null
createdAt: string
createdBy: string
customFields: Json | null
description: string | null
dueDate: string | null
+ hasConflict: boolean | null
id: string
jobId: string
jobMakeMethodId: string | null
@@ -10565,11 +10567,13 @@ export type Database = {
Insert: {
assignee?: string | null
companyId: string
+ conflictReason?: string | null
createdAt?: string
createdBy: string
customFields?: Json | null
description?: string | null
dueDate?: string | null
+ hasConflict?: boolean | null
id?: string
jobId: string
jobMakeMethodId?: string | null
@@ -10607,11 +10611,13 @@ export type Database = {
Update: {
assignee?: string | null
companyId?: string
+ conflictReason?: string | null
createdAt?: string
createdBy?: string
customFields?: Json | null
description?: string | null
dueDate?: string | null
+ hasConflict?: boolean | null
id?: string
jobId?: string
jobMakeMethodId?: string | null
@@ -45703,14 +45709,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -49273,6 +49279,7 @@ export type Database = {
customerName: string
deadlineType: Database["public"]["Enums"]["deadlineType"]
dueDate: string
+ hasConflict: boolean
id: string
itemDescription: string
itemId: string
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 94a86d2c73..3005662aae 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -10523,11 +10523,13 @@ export type Database = {
Row: {
assignee: string | null
companyId: string
+ conflictReason: string | null
createdAt: string
createdBy: string
customFields: Json | null
description: string | null
dueDate: string | null
+ hasConflict: boolean | null
id: string
jobId: string
jobMakeMethodId: string | null
@@ -10565,11 +10567,13 @@ export type Database = {
Insert: {
assignee?: string | null
companyId: string
+ conflictReason?: string | null
createdAt?: string
createdBy: string
customFields?: Json | null
description?: string | null
dueDate?: string | null
+ hasConflict?: boolean | null
id?: string
jobId: string
jobMakeMethodId?: string | null
@@ -10607,11 +10611,13 @@ export type Database = {
Update: {
assignee?: string | null
companyId?: string
+ conflictReason?: string | null
createdAt?: string
createdBy?: string
customFields?: Json | null
description?: string | null
dueDate?: string | null
+ hasConflict?: boolean | null
id?: string
jobId?: string
jobMakeMethodId?: string | null
@@ -41809,14 +41815,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"]
@@ -43180,14 +43186,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"]
@@ -46242,14 +46248,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"]
@@ -48814,14 +48820,17 @@ export type Database = {
get_active_job_operations_by_location: {
Args: { location_id: string; work_center_ids: string[] }
Returns: {
+ assignee: string
customerName: string
description: string
id: string
+ itemDescription: string
itemReadableId: string
jobCustomerId: string
jobDeadlineType: Database["public"]["Enums"]["deadlineType"]
jobDueDate: string
jobId: string
+ jobMakeMethodId: string
jobReadableId: string
jobStatus: Database["public"]["Enums"]["jobStatus"]
laborTime: number
@@ -48837,8 +48846,13 @@ export type Database = {
processId: string
quantityComplete: number
quantityScrapped: number
+ salesOrderId: string
+ salesOrderLineId: string
+ salesOrderReadableId: string
setupTime: number
setupUnit: Database["public"]["Enums"]["factor"]
+ tags: string[]
+ thumbnailPath: string
workCenterId: string
}[]
}
@@ -49261,6 +49275,7 @@ export type Database = {
customerName: string
deadlineType: Database["public"]["Enums"]["deadlineType"]
dueDate: string
+ hasConflict: boolean
id: string
itemDescription: string
itemId: string
diff --git a/packages/database/supabase/functions/reschedule/index.ts b/packages/database/supabase/functions/reschedule/index.ts
new file mode 100644
index 0000000000..1552e2081f
--- /dev/null
+++ b/packages/database/supabase/functions/reschedule/index.ts
@@ -0,0 +1,481 @@
+import { serve } from "https://deno.land/[email protected]/http/server.ts";
+import type { Transaction } from "https://esm.sh/[email protected]";
+import { corsHeaders } from "../lib/headers.ts";
+import { getConnectionPool, getDatabaseClient } from "../lib/database.ts";
+import type { DB } from "../lib/types.ts";
+
+const pool = getConnectionPool(1);
+const db = getDatabaseClient<DB>(pool);
+
+// Types
+type JobOperation = {
+ id: string;
+ jobId: string;
+ workCenterId: string | null;
+ status: string;
+ priority: number | null;
+ dueDate: string | null;
+ startDate: string | null;
+ setupTime: number | null;
+ laborTime: number | null;
+ machineTime: number | null;
+ setupUnit: string | null;
+ laborUnit: string | null;
+ machineUnit: string | null;
+ operationQuantity: number | null;
+};
+
+type Job = {
+ id: string;
+ dueDate: string | null;
+ priority: number | null;
+ deadlineType: string | null;
+};
+
+type JobOperationDependency = {
+ operationId: string;
+ dependsOnId: string;
+ jobId: string;
+};
+
+type DependencyGraph = Map<
+ string,
+ {
+ dependsOn: string[];
+ requiredBy: string[];
+ }
+>;
+
+type ScheduledOperation = JobOperation & {
+ hasConflict: boolean;
+ conflictReason: string | null;
+};
+
+type OperationWithJobInfo = {
+ id: string;
+ dueDate: string | null;
+ priority: number | null;
+ deadlineType: string | null;
+ jobPriority: number | null;
+ workCenterId: string | null;
+};
+
+// Helper: Get job with operations and dependencies
+async function getJobWithOperations(trx: Transaction<DB>, jobId: string) {
+ const job = await trx
+ .selectFrom("job")
+ .select(["id", "dueDate", "priority", "deadlineType"])
+ .where("id", "=", jobId)
+ .executeTakeFirstOrThrow();
+
+ const operations = await trx
+ .selectFrom("jobOperation")
+ .selectAll()
+ .where("jobId", "=", jobId)
+ .where("status", "not in", ["Done", "Canceled"])
+ .execute();
+
+ const dependencies = await trx
+ .selectFrom("jobOperationDependency")
+ .selectAll()
+ .where("jobId", "=", jobId)
+ .execute();
+
+ return { job, operations, dependencies };
+}
+
+// Helper: Build dependency graph
+function buildDependencyGraph(
+ operations: JobOperation[],
+ dependencies: JobOperationDependency[]
+): DependencyGraph {
+ const graph = new Map<
+ string,
+ {
+ dependsOn: string[];
+ requiredBy: string[];
+ }
+ >();
+
+ // Initialize all operations
+ for (const op of operations) {
+ graph.set(op.id, { dependsOn: [], requiredBy: [] });
+ }
+
+ // Build edges
+ for (const dep of dependencies) {
+ const opNode = graph.get(dep.operationId);
+ const depNode = graph.get(dep.dependsOnId);
+
+ if (opNode) {
+ opNode.dependsOn.push(dep.dependsOnId);
+ }
+ if (depNode) {
+ depNode.requiredBy.push(dep.operationId);
+ }
+ }
+
+ return graph;
+}
+
+// Helper: Topological sort
+function topologicalSort(
+ operations: JobOperation[],
+ graph: DependencyGraph,
+ direction: "forward" | "reverse"
+): JobOperation[] {
+ const inDegree = new Map<string, number>();
+ const queue: string[] = [];
+ const result: JobOperation[] = [];
+
+ // Calculate in-degrees
+ for (const op of operations) {
+ const deps =
+ direction === "forward"
+ ? graph.get(op.id)?.dependsOn || []
+ : graph.get(op.id)?.requiredBy || [];
+ inDegree.set(op.id, deps.length);
+ if (deps.length === 0) queue.push(op.id);
+ }
+
+ // Process queue
+ while (queue.length > 0) {
+ const opId = queue.shift()!;
+ const op = operations.find((o) => o.id === opId)!;
+ result.push(op);
+
+ const neighbors =
+ direction === "forward"
+ ? graph.get(opId)?.requiredBy || []
+ : graph.get(opId)?.dependsOn || [];
+
+ for (const neighborId of neighbors) {
+ const degree = inDegree.get(neighborId)! - 1;
+ inDegree.set(neighborId, degree);
+ if (degree === 0) queue.push(neighborId);
+ }
+ }
+
+ return result;
+}
+
+// Helper: Calculate operation duration in days
+function calculateOperationDuration(op: JobOperation): number {
+ const quantity = op.operationQuantity || 1;
+
+ // Calculate total hours
+ let setupHours = 0;
+ let laborHours = 0;
+ let machineHours = 0;
+
+ if (op.setupTime) {
+ setupHours =
+ op.setupUnit === "Hours/Piece"
+ ? (op.setupTime * quantity)
+ : op.setupTime;
+ }
+
+ if (op.laborTime) {
+ laborHours =
+ op.laborUnit === "Hours/Piece"
+ ? (op.laborTime * quantity)
+ : op.laborTime;
+ }
+
+ if (op.machineTime) {
+ machineHours =
+ op.machineUnit === "Hours/Piece"
+ ? (op.machineTime * quantity)
+ : op.machineTime;
+ }
+
+ // Total hours (setup + max of labor/machine since they can overlap)
+ const totalHours = setupHours + Math.max(laborHours, machineHours);
+
+ // Convert to days (assuming 8-hour workday)
+ const days = totalHours / 8;
+
+ // Round up to at least 1 day
+ return Math.max(Math.ceil(days), 1);
+}
+
+// Helper: Backward schedule operations
+function backwardScheduleOperations(
+ operations: JobOperation[],
+ graph: DependencyGraph,
+ jobDueDate: string | null
+): ScheduledOperation[] {
+ const scheduled = new Map<string, ScheduledOperation>();
+ const today = new Date().toISOString().split("T")[0];
+
+ // Default to today if no due date
+ const finalDueDate = jobDueDate || today;
+
+ // Topological sort (reverse: final ops first)
+ const sorted = topologicalSort(operations, graph, "reverse");
+
+ for (const op of sorted) {
+ const deps = graph.get(op.id);
+ if (!deps) continue;
+
+ const totalDuration = calculateOperationDuration(op);
+
+ // Calculate due date
+ let dueDate: string;
+ if (deps.requiredBy.length === 0) {
+ // Leaf operation: use job due date
+ dueDate = finalDueDate;
+ } else {
+ // Has dependents: must finish before earliest dependent starts
+ const dependentStartDates = deps.requiredBy
+ .map((depId) => scheduled.get(depId)?.startDate)
+ .filter((date): date is string => date !== null && date !== undefined);
+
+ if (dependentStartDates.length === 0) {
+ dueDate = finalDueDate;
+ } else {
+ // Subtract 1 day buffer
+ const minDate = new Date(
+ Math.min(...dependentStartDates.map((d) => new Date(d).getTime()))
+ );
+ minDate.setDate(minDate.getDate() - 1);
+ dueDate = minDate.toISOString().split("T")[0];
+ }
+ }
+
+ // Calculate start date
+ const dueDateObj = new Date(dueDate);
+ dueDateObj.setDate(dueDateObj.getDate() - totalDuration);
+ const startDate = dueDateObj.toISOString().split("T")[0];
+
+ // Check for conflicts
+ const hasConflict = startDate < today;
+ const conflictReason = hasConflict
+ ? `Operation must start on ${startDate} but current date is ${today}`
+ : null;
+
+ scheduled.set(op.id, {
+ ...op,
+ startDate,
+ dueDate,
+ hasConflict,
+ conflictReason,
+ });
+ }
+
+ return Array.from(scheduled.values());
+}
+
+// Helper: Sort operations by priority criteria
+function sortOperationsByPriority(
+ operations: OperationWithJobInfo[]
+): OperationWithJobInfo[] {
+ const deadlineOrder: Record<string, number> = {
+ ASAP: 0,
+ "Hard Deadline": 1,
+ "Soft Deadline": 2,
+ "No Deadline": 3,
+ };
+
+ return operations.sort((a, b) => {
+ // 1. Deadline type
+ const aDeadline = a.deadlineType || "No Deadline";
+ const bDeadline = b.deadlineType || "No Deadline";
+ if (aDeadline !== bDeadline) {
+ return deadlineOrder[aDeadline] - deadlineOrder[bDeadline];
+ }
+
+ // 2. Due date (earliest first, nulls last)
+ if (a.dueDate && b.dueDate) {
+ const dateCompare =
+ new Date(a.dueDate).getTime() - new Date(b.dueDate).getTime();
+ if (dateCompare !== 0) return dateCompare;
+ } else if (a.dueDate) {
+ return -1;
+ } else if (b.dueDate) {
+ return 1;
+ }
+
+ // 3. Job priority
+ const aPriority = a.jobPriority || 0;
+ const bPriority = b.jobPriority || 0;
+ return aPriority - bPriority;
+ });
+}
+
+// Helper: Apply fractional priorities
+function applyFractionalPriorities(
+ sorted: OperationWithJobInfo[]
+): OperationWithJobInfo[] {
+ return sorted.map((op, index) => {
+ if (index === 0) {
+ op.priority = 0;
+ } else {
+ const prevPriority = sorted[index - 1].priority || 0;
+ op.priority = prevPriority + 1;
+ }
+ return op;
+ });
+}
+
+// Helper: Recalculate priorities by work center
+async function recalculatePriorities(
+ trx: Transaction<DB>,
+ scheduledOps: ScheduledOperation[],
+ workCenterIds: string[]
+): Promise<ScheduledOperation[]> {
+ const prioritizedOps = [...scheduledOps];
+
+ for (const wcId of workCenterIds) {
+ if (!wcId) continue;
+
+ // Get ALL active operations at this work center (not just from current job)
+ const allWcOps = await trx
+ .selectFrom("jobOperation as jo")
+ .innerJoin("job as j", "j.id", "jo.jobId")
+ .select([
+ "jo.id",
+ "jo.dueDate",
+ "jo.priority",
+ "j.deadlineType",
+ "j.priority as jobPriority",
+ "jo.workCenterId",
+ ])
+ .where("jo.workCenterId", "=", wcId)
+ .where("jo.status", "not in", ["Done", "Canceled"])
+ .execute();
+
+ // Merge with scheduled ops (use scheduled data if available)
+ const mergedOps = allWcOps.map((wcOp) => {
+ const scheduled = scheduledOps.find((s) => s.id === wcOp.id);
+ if (scheduled) {
+ return {
+ id: scheduled.id,
+ dueDate: scheduled.dueDate,
+ priority: scheduled.priority,
+ deadlineType: wcOp.deadlineType,
+ jobPriority: wcOp.jobPriority,
+ workCenterId: wcOp.workCenterId,
+ };
+ }
+ return wcOp;
+ });
+
+ // Sort by priority criteria
+ const sorted = sortOperationsByPriority(mergedOps);
+
+ // Apply fractional indexing
+ const prioritized = applyFractionalPriorities(sorted);
+
+ // Update prioritized ops
+ for (const op of prioritized) {
+ const idx = prioritizedOps.findIndex((p) => p.id === op.id);
+ if (idx >= 0) {
+ prioritizedOps[idx].priority = op.priority;
+ }
+ }
+ }
+
+ return prioritizedOps;
+}
+
+// Main handler
+serve(async (req) => {
+ if (req.method === "OPTIONS") {
+ return new Response("ok", { headers: corsHeaders });
+ }
+
+ try {
+ const { jobId, companyId, userId } = await req.json();
+
+ console.info(`🔰 Starting reschedule for job ${jobId}`);
+
+ const result = await db.transaction().execute(async (trx) => {
+ // 1. Get job and all its operations with dependencies
+ const { job, operations, dependencies } = await getJobWithOperations(
+ trx,
+ jobId
+ );
+
+ console.info(
+ `📊 Job has ${operations.length} operations, ${dependencies.length} dependencies`
+ );
+
+ // 2. Build dependency graph
+ const graph = buildDependencyGraph(operations, dependencies);
+
+ // 3. Backward schedule (calculate dates, flag conflicts)
+ const scheduledOps = backwardScheduleOperations(
+ operations,
+ graph,
+ job.dueDate
+ );
+
+ const conflicts = scheduledOps.filter((op) => op.hasConflict);
+ console.info(`⚠️ Detected ${conflicts.length} scheduling conflicts`);
+
+ // 4. Get affected work centers
+ const workCenterIds = [
+ ...new Set(
+ scheduledOps
+ .map((op) => op.workCenterId)
+ .filter((id): id is string => id !== null)
+ ),
+ ];
+
+ console.info(`🏭 Affected work centers: ${workCenterIds.length}`);
+
+ // 5. Recalculate priorities for each work center
+ const prioritizedOps = await recalculatePriorities(
+ trx,
+ scheduledOps,
+ workCenterIds
+ );
+
+ // 6. Batch update all operations
+ for (const op of prioritizedOps) {
+ await trx
+ .updateTable("jobOperation")
+ .set({
+ startDate: op.startDate,
+ dueDate: op.dueDate,
+ priority: op.priority,
+ hasConflict: op.hasConflict,
+ conflictReason: op.conflictReason,
+ updatedAt: new Date().toISOString(),
+ updatedBy: userId,
+ })
+ .where("id", "=", op.id)
+ .execute();
+ }
+
+ console.info(`✅ Updated ${prioritizedOps.length} operations`);
+
+ return {
+ operationsUpdated: prioritizedOps.length,
+ conflictsDetected: conflicts.length,
+ workCentersAffected: workCenterIds.length,
+ };
+ });
+
+ return new Response(JSON.stringify({ success: true, ...result }), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ });
+ } catch (error) {
+ console.error(
+ `❌ Reschedule failed: ${
+ error instanceof Error ? error.message : String(error)
+ }`
+ );
+ return new Response(
+ JSON.stringify({
+ success: false,
+ message: error instanceof Error ? error.message : String(error),
+ }),
+ {
+ status: 500,
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ }
+ );
+ }
+});
diff --git a/packages/database/supabase/migrations/20251122173055_schedule-jobs.sql b/packages/database/supabase/migrations/20251122173055_schedule-jobs.sql
index 0a75f8006b..c0dc454945 100644
--- a/packages/database/supabase/migrations/20251122173055_schedule-jobs.sql
+++ b/packages/database/supabase/migrations/20251122173055_schedule-jobs.sql
@@ -32,7 +32,8 @@ RETURNS TABLE (
"tags" TEXT[],
"thumbnailPath" TEXT,
"operationCount" INTEGER,
- "completedOperationCount" INTEGER
+ "completedOperationCount" INTEGER,
+ "hasConflict" BOOLEAN
)
SECURITY INVOKER
AS $$
@@ -80,7 +81,8 @@ BEGIN
SELECT
jo."jobId",
COUNT(*)::INTEGER AS "operationCount",
- COUNT(*) FILTER (WHERE jo."status" = 'Done')::INTEGER AS "completedOperationCount"
+ COUNT(*) FILTER (WHERE jo."status" = 'Done')::INTEGER AS "completedOperationCount",
+ BOOL_OR(COALESCE(jo."hasConflict", FALSE)) AS "hasConflict"
FROM "jobOperation" jo
GROUP BY jo."jobId"
)
@@ -107,7 +109,8 @@ BEGIN
rj."tags",
COALESCE(ji."itemThumbnailPath", ji."itemModelThumbnailPath", rj."thumbnailPath") AS "thumbnailPath",
COALESCE(os."operationCount", 0) AS "operationCount",
- COALESCE(os."completedOperationCount", 0) AS "completedOperationCount"
+ COALESCE(os."completedOperationCount", 0) AS "completedOperationCount",
+ COALESCE(os."hasConflict", FALSE) AS "hasConflict"
FROM relevant_jobs rj
LEFT JOIN "salesOrderLine" sol ON sol."id" = rj."salesOrderLineId"
LEFT JOIN "salesOrder" so ON so."id" = sol."salesOrderId"
diff --git a/packages/database/supabase/migrations/20251123000000_add-customer-name-to-operations.sql b/packages/database/supabase/migrations/20251123000000_add-customer-name-to-operations.sql
index 92d52eff62..faee24f589 100644
--- a/packages/database/supabase/migrations/20251123000000_add-customer-name-to-operations.sql
+++ b/packages/database/supabase/migrations/20251123000000_add-customer-name-to-operations.sql
@@ -1,5 +1,4 @@
-
--- Add customerName to get_active_job_operations_by_location function
+-- Fix salesOrderReadableId in get_active_job_operations_by_location function
DROP FUNCTION IF EXISTS get_active_job_operations_by_location;
CREATE OR REPLACE FUNCTION get_active_job_operations_by_location(
location_id TEXT,
@@ -85,7 +84,7 @@ BEGIN
jo."quantityScrapped",
rj."salesOrderId",
rj."salesOrderLineId",
- so."readableId" as "salesOrderReadableId",
+ so."salesOrderId" as "salesOrderReadableId",
jo."assignee",
jo."tags",
COALESCE(mu."thumbnailPath", i."thumbnailPath") as "thumbnailPath"
@@ -103,3 +102,4 @@ BEGIN
ORDER BY jo."priority";
END;
$$ LANGUAGE plpgsql;
+
diff --git a/packages/database/supabase/migrations/20251123000001_job-operation-conflicts.sql b/packages/database/supabase/migrations/20251123000001_job-operation-conflicts.sql
new file mode 100644
index 0000000000..81fbd877b0
--- /dev/null
+++ b/packages/database/supabase/migrations/20251123000001_job-operation-conflicts.sql
@@ -0,0 +1,13 @@
+-- Add conflict tracking fields to jobOperation table
+ALTER TABLE "jobOperation"
+ ADD COLUMN "hasConflict" BOOLEAN DEFAULT false,
+ ADD COLUMN "conflictReason" TEXT;
+
+-- Create index for work center priority queries (only active operations)
+CREATE INDEX "idx_job_operation_wc_priority"
+ ON "jobOperation"("workCenterId", "priority", "status")
+ WHERE "status" NOT IN ('Done', 'Canceled');
+
+-- Add comment for documentation
+COMMENT ON COLUMN "jobOperation"."hasConflict" IS 'Indicates if this operation has a scheduling conflict (e.g., start date in the past)';
+COMMENT ON COLUMN "jobOperation"."conflictReason" IS 'Human-readable explanation of the scheduling conflict';
diff --git a/packages/jobs/trigger/reschedule-job.ts b/packages/jobs/trigger/reschedule-job.ts
new file mode 100644
index 0000000000..74eead1cf9
--- /dev/null
+++ b/packages/jobs/trigger/reschedule-job.ts
@@ -0,0 +1,55 @@
+import { task } from "@trigger.dev/sdk";
+import { z } from "zod";
+import { getCarbonServiceRole } from "@carbon/auth";
+
+const serviceRole = getCarbonServiceRole();
+
+const rescheduleJobSchema = z.object({
+ jobId: z.string(),
+ companyId: z.string(),
+ userId: z.string(),
+});
+
+export const rescheduleJob = task({
+ id: "reschedule-job",
+ queue: {
+ name: "scheduling",
+ concurrencyLimit: 5,
+ },
+ run: async (payload: z.infer<typeof rescheduleJobSchema>) => {
+ console.info(`🔰 Rescheduling job ${payload.jobId}`);
+
+ try {
+ const { data, error } = await serviceRole.functions.invoke("reschedule", {
+ body: {
+ jobId: payload.jobId,
+ companyId: payload.companyId,
+ userId: payload.userId,
+ },
+ });
+
+ if (error) {
+ throw new Error(error.message || "Failed to reschedule job");
+ }
+
+ console.info(
+ `✅ Rescheduled: ${data.operationsUpdated} ops, ` +
+ `${data.workCentersAffected} WCs, ${data.conflictsDetected} conflicts`
+ );
+
+ return {
+ success: true,
+ operationsUpdated: data.operationsUpdated,
+ conflictsDetected: data.conflictsDetected,
+ workCentersAffected: data.workCentersAffected,
+ };
+ } catch (error) {
+ console.error(
+ `❌ Reschedule failed: ${
+ error instanceof Error ? error.message : String(error)
+ }`
+ );
+ throw error; // Let Trigger.dev handle retries
+ }
+ },
+});