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.

Load Balancer (#83)

Brad Barbin4e2dd9fb5a95
diff --git a/apps/carbon/app/components/Form/WorkCenter.tsx b/apps/carbon/app/components/Form/WorkCenter.tsx
index 344933c8ec..24918de670 100644
--- a/apps/carbon/app/components/Form/WorkCenter.tsx
+++ b/apps/carbon/app/components/Form/WorkCenter.tsx
@@ -81,6 +81,14 @@ export const useWorkCenters = (args: {
workCenterFetcher.data?.data
? workCenterFetcher.data?.data
.filter((f) => {
+ if (processId && locationId) {
+ return (
+ // @ts-ignore
+ (f.processes ?? []).map((p) => p.id).includes(processId) &&
+ f.locationId === locationId
+ );
+ }
+
if (processId) {
// @ts-ignore
return (f.processes ?? []).map((p) => p.id).includes(processId);
diff --git a/apps/carbon/app/components/Layout/Topbar/Feedback.tsx b/apps/carbon/app/components/Layout/Topbar/Feedback.tsx
index 0033427a29..4ba8af368f 100644
--- a/apps/carbon/app/components/Layout/Topbar/Feedback.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/Feedback.tsx
@@ -123,7 +123,11 @@ const Feedback = () => {
<HStack className="w-full justify-between">
<Button
variant="secondary"
- onClick={() => popoverTriggerRef.current?.click()}
+ onClick={() => {
+ setFeedback("");
+ setAttachment(null);
+ popoverTriggerRef.current?.click();
+ }}
>
Cancel
</Button>
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
index 1eb54712a8..e0f9d952b2 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
@@ -69,6 +69,7 @@ type ItemWithData = Item & {
type JobBillOfProcessProps = {
jobMakeMethodId: string;
+ locationId: string;
operations: Operation[];
};
@@ -139,6 +140,7 @@ const initialOperation: Omit<Operation, "jobMakeMethodId" | "order"> = {
const JobBillOfProcess = ({
jobMakeMethodId,
+ locationId,
operations,
}: JobBillOfProcessProps) => {
const { carbon, accessToken } = useCarbon();
@@ -417,6 +419,7 @@ const JobBillOfProcess = ({
isDisabled={isDisabled}
setItems={setItems}
setSelectedItemId={setSelectedItemId}
+ locationId={locationId}
/>
</motion.div>
</div>
@@ -634,11 +637,13 @@ function OperationForm({
isDisabled,
setItems,
setSelectedItemId,
+ locationId,
}: {
item: ItemWithData;
isDisabled: boolean;
setItems: Dispatch<SetStateAction<ItemWithData[]>>;
setSelectedItemId: Dispatch<SetStateAction<string | null>>;
+ locationId: string;
}) {
const { jobId } = useParams();
const { id: userId, company } = useUser();
@@ -1004,6 +1009,7 @@ function OperationForm({
<WorkCenter
name="workCenterId"
label="Work Center"
+ locationId={locationId}
isOptional
processId={processData.processId}
onChange={(value) => {
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobForm.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobForm.tsx
index afae81bc37..79798ed589 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobForm.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobForm.tsx
@@ -109,18 +109,21 @@ const JobForm = ({ initialValues }: JobFormProps) => {
.single(),
]);
- setItemData({
+ setItemData((current) => ({
itemId,
description: item.data?.name ?? "",
uom: item.data?.unitOfMeasureCode ?? "EA",
- quantity: manufacturing?.data?.lotSize ?? 0,
+ quantity:
+ (manufacturing?.data?.lotSize ?? 0) === 0
+ ? current.quantity
+ : manufacturing?.data?.lotSize ?? 0,
modelUploadId: item.data?.modelUploadId ?? null,
scrapPercentage: manufacturing?.data?.scrapPercentage ?? 0,
scrapQuantity: Math.ceil(
(manufacturing?.data?.lotSize ?? 0) *
((manufacturing?.data?.scrapPercentage ?? 0) / 100)
),
- });
+ }));
};
return (
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobHeader.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobHeader.tsx
index 8b9a6c3360..c65aef8d63 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobHeader.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobHeader.tsx
@@ -371,7 +371,7 @@ function JobStartModal({
<fetcher.Form
onSubmit={onClose}
method="post"
- action={path.to.jobStatus(job.id!)}
+ action={`${path.to.jobStatus(job.id!)}?schedule=1`}
>
<input type="hidden" name="status" value="Ready" />
<Button type="submit">Start</Button>
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobsTable.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobsTable.tsx
index 6dc770721d..b204970579 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobsTable.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobsTable.tsx
@@ -98,6 +98,11 @@ const JobsTable = memo(({ data, count, locations }: JobsTableProps) => {
},
},
},
+ {
+ accessorKey: "quantity",
+ header: "Quantity",
+ cell: (item) => item.getValue<number>(),
+ },
{
id: "customerId",
header: "Customer",
diff --git a/apps/carbon/app/modules/resources/ui/Processes/ProcessesTable.tsx b/apps/carbon/app/modules/resources/ui/Processes/ProcessesTable.tsx
index e9b7d0caee..df7e70e1a0 100644
--- a/apps/carbon/app/modules/resources/ui/Processes/ProcessesTable.tsx
+++ b/apps/carbon/app/modules/resources/ui/Processes/ProcessesTable.tsx
@@ -4,13 +4,14 @@ import {
AvatarGroupList,
AvatarOverflowIndicator,
Badge,
+ HStack,
MenuIcon,
MenuItem,
} from "@carbon/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
-import { LuPencil, LuTrash } from "react-icons/lu";
+import { LuAlertTriangle, LuPencil, LuTrash } from "react-icons/lu";
import { EmployeeAvatar, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { usePermissions, useUrlParams } from "~/hooks";
@@ -45,13 +46,19 @@ const ProcessesTable = memo(({ data, count }: ProcessesTableProps) => {
{
accessorKey: "name",
header: "Process",
- cell: ({ row }) => (
- <Enumerable
- value={row.original.name}
- onClick={() => navigate(row.original.id!)}
- className="cursor-pointer"
- />
- ),
+ cell: ({ row }) =>
+ ((row.original.workCenters as any[]) ?? []).length > 0 ? (
+ <Enumerable
+ value={row.original.name}
+ onClick={() => navigate(row.original.id!)}
+ className="cursor-pointer"
+ />
+ ) : (
+ <HStack onClick={() => navigate(row.original.id!)} spacing={2}>
+ <LuAlertTriangle />
+ <span>{row.original.name}</span>
+ </HStack>
+ ),
},
{
accessorKey: "processType",
diff --git a/apps/carbon/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsx b/apps/carbon/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsx
index 076a85fd10..08da268e67 100644
--- a/apps/carbon/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsx
+++ b/apps/carbon/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsx
@@ -2,8 +2,12 @@ import { HStack, MenuIcon, MenuItem, useDisclosure } from "@carbon/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo, useState } from "react";
-import { BsFillCheckCircleFill } from "react-icons/bs";
-import { LuPencil, LuTrash } from "react-icons/lu";
+import {
+ LuAlertTriangle,
+ LuCheckCircle,
+ LuPencil,
+ LuTrash,
+} from "react-icons/lu";
import { EmployeeAvatar, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { ConfirmDelete } from "~/components/Modals";
@@ -59,14 +63,21 @@ const WorkCentersTable = memo(
header: "Work Center",
cell: ({ row }) => (
<HStack>
- <Enumerable
- value={row.original.name}
- onClick={() => navigate(row.original.id!)}
- className="cursor-pointer"
- />
+ {((row.original.processes as any[]) ?? []).length > 0 ? (
+ <Enumerable
+ value={row.original.name}
+ onClick={() => navigate(row.original.id!)}
+ className="cursor-pointer"
+ />
+ ) : (
+ <HStack onClick={() => navigate(row.original.id!)} spacing={2}>
+ <LuAlertTriangle />
+ <span>{row.original.name}</span>
+ </HStack>
+ )}
{row.original.requiredAbilityId && (
- <BsFillCheckCircleFill
+ <LuCheckCircle
className="text-emerald-500"
title="Requires ability"
/>
diff --git a/apps/carbon/app/routes/x+/_index.tsx b/apps/carbon/app/routes/x+/_index.tsx
index 0ada013d21..30aebeeb89 100644
--- a/apps/carbon/app/routes/x+/_index.tsx
+++ b/apps/carbon/app/routes/x+/_index.tsx
@@ -51,7 +51,7 @@ const ModuleCard = ({ module }: { module: Authenticated<NavItem> }) => (
<Link
to={module.to}
prefetch="intent"
- className="flex flex-col gap-6 items-center justify-center py-8 border border-border shadow-md dark:border-0 dark:shadow-[0px_1px_0px_0px_hsla(0,0%,100%,.03)_inset,0px_0px_0px_1px_hsla(0,0%,100%,.03)_inset,0px_0px_0px_1px_rgba(0,0,0,.1),0px_2px_2px_0px_rgba(0,0,0,.1),0px_4px_4px_0px_rgba(0,0,0,.1),0px_8px_8px_0px_rgba(0,0,0,.1)] bg-gradient-to-bl from-card to-background rounded-lg text-center group ring-2 ring-transparent hover:ring-white/10 cursor-pointer"
+ className="flex flex-col gap-6 items-center justify-center py-8 border border-border shadow-md dark:border-0 dark:shadow-[0px_1px_0px_0px_hsla(0,0%,100%,.03)_inset,0px_0px_0px_1px_hsla(0,0%,100%,.03)_inset,0px_0px_0px_1px_rgba(0,0,0,.1),0px_2px_2px_0px_rgba(0,0,0,.1),0px_4px_4px_0px_rgba(0,0,0,.1),0px_8px_8px_0px_rgba(0,0,0,.1)] bg-gradient-to-bl from-card from-50% to-background rounded-lg text-center group ring-2 ring-transparent hover:ring-white/10 cursor-pointer"
>
<module.icon className="text-2xl" />
<span className="text-sm py-1 px-4 border border-border rounded-full group-hover:bg-accent">
diff --git a/apps/carbon/app/routes/x+/job+/$jobId.make.$methodId.$materialId.tsx b/apps/carbon/app/routes/x+/job+/$jobId.make.$methodId.$materialId.tsx
index 6e12d1379d..41e540066f 100644
--- a/apps/carbon/app/routes/x+/job+/$jobId.make.$methodId.$materialId.tsx
+++ b/apps/carbon/app/routes/x+/job+/$jobId.make.$methodId.$materialId.tsx
@@ -6,6 +6,8 @@ import type { LoaderFunctionArgs } from "@vercel/remix";
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { useRouteData } from "~/hooks";
+import type { Job } from "~/modules/production";
import {
getJobMaterial,
getJobMaterialsByMethodId,
@@ -99,9 +101,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
export default function JobMakeMethodRoute() {
- const { methodId } = useParams();
+ const { methodId, jobId } = useParams();
if (!methodId) throw new Error("Could not find methodId");
-
+ if (!jobId) throw new Error("Could not find jobId");
+ const routeData = useRouteData<{ job: Job }>(path.to.job(jobId));
const loaderData = useLoaderData<typeof loader>();
const { material, materials, operations } = loaderData;
@@ -114,9 +117,10 @@ export default function JobMakeMethodRoute() {
operations={operations}
/>
<JobBillOfProcess
- key={`bop:${methodId}:${operations.length}`}
+ key={`bop:${methodId}:${operations.length}:${operations[0]?.workCenterId}`}
jobMakeMethodId={methodId}
operations={operations}
+ locationId={routeData?.job?.locationId ?? ""}
/>
<JobBillOfMaterial
key={`bom:${methodId}:${materials.length}`}
diff --git a/apps/carbon/app/routes/x+/job+/$jobId.method.$methodId.tsx b/apps/carbon/app/routes/x+/job+/$jobId.method.$methodId.tsx
index 7959e8c6d1..b4c11c4d25 100644
--- a/apps/carbon/app/routes/x+/job+/$jobId.method.$methodId.tsx
+++ b/apps/carbon/app/routes/x+/job+/$jobId.method.$methodId.tsx
@@ -6,6 +6,8 @@ import type { LoaderFunctionArgs } from "@vercel/remix";
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { useRouteData } from "~/hooks";
+import type { Job } from "~/modules/production";
import {
getJobMaterialsByMethodId,
getJobOperationsByMethodId,
@@ -72,8 +74,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
export default function JobMakeMethodRoute() {
- const { methodId } = useParams();
+ const { methodId, jobId } = useParams();
if (!methodId) throw new Error("Could not find methodId");
+ if (!jobId) throw new Error("Could not find jobId");
+ const routeData = useRouteData<{ job: Job }>(path.to.job(jobId));
const loaderData = useLoaderData<typeof loader>();
const { materials, operations } = loaderData;
@@ -82,9 +86,10 @@ export default function JobMakeMethodRoute() {
<VStack spacing={2} className="p-2">
<JobBreadcrumbs />
<JobBillOfProcess
- key={`bop:${methodId}:${operations.length}`}
+ key={`bop:${methodId}:${operations.length}:${operations[0]?.workCenterId}`}
jobMakeMethodId={methodId}
operations={operations}
+ locationId={routeData?.job?.locationId ?? ""}
/>
<JobBillOfMaterial
key={`bom:${methodId}:${materials.length}`}
diff --git a/apps/carbon/app/routes/x+/job+/$jobId.status.tsx b/apps/carbon/app/routes/x+/job+/$jobId.status.tsx
index ef194fab69..60bdaa047a 100644
--- a/apps/carbon/app/routes/x+/job+/$jobId.status.tsx
+++ b/apps/carbon/app/routes/x+/job+/$jobId.status.tsx
@@ -1,4 +1,9 @@
-import { assertIsPost, error, success } from "@carbon/auth";
+import {
+ assertIsPost,
+ error,
+ getCarbonServiceRole,
+ success,
+} from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "@vercel/remix";
@@ -8,13 +13,16 @@ import { path, requestReferrer } from "~/utils/path";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "production",
});
const { jobId: id } = params;
if (!id) throw new Error("Could not find id");
+ const url = new URL(request.url);
+ const shouldSchedule = url.searchParams.get("schedule") === "1";
+
const formData = await request.formData();
const status = formData.get("status") as (typeof jobStatus)[number];
@@ -40,6 +48,34 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
}
+ if (status === "Ready" && shouldSchedule) {
+ try {
+ const scheduler = await getCarbonServiceRole().functions.invoke(
+ "scheduler",
+ {
+ body: {
+ jobId: id,
+ companyId,
+ userId,
+ },
+ }
+ );
+
+ if (scheduler.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.job(id),
+ await flash(request, error(error, "Failed to schedule job"))
+ );
+ }
+ } catch (err) {
+ console.error(err);
+ throw redirect(
+ requestReferrer(request) ?? path.to.job(id),
+ await flash(request, error(err, "Failed to schedule job"))
+ );
+ }
+ }
+
const update = await updateJobStatus(client, {
id,
status,
diff --git a/packages/database/supabase/functions/import-csv/index.ts b/packages/database/supabase/functions/import-csv/index.ts
index 1cb1a2dcd8..55f9fef84d 100644
--- a/packages/database/supabase/functions/import-csv/index.ts
+++ b/packages/database/supabase/functions/import-csv/index.ts
@@ -73,8 +73,6 @@ serve(async (req: Request) => {
string
>[];
- console.log(columnMappings);
-
let mappedRecords = parsedCsv.map((row) => {
const record: Record<string, string> = {};
for (const [key, value] of Object.entries(columnMappings)) {
diff --git a/packages/database/supabase/functions/lib/scheduling/engine.ts b/packages/database/supabase/functions/lib/scheduling/engine.ts
new file mode 100644
index 0000000000..219df7872a
--- /dev/null
+++ b/packages/database/supabase/functions/lib/scheduling/engine.ts
@@ -0,0 +1,233 @@
+import { Kysely } from "https://esm.sh/[email protected]";
+import SupabaseClient from "https://esm.sh/v135/@supabase/[email protected]/dist/module/SupabaseClient.d.ts";
+import { DB } from "../database.ts";
+import { getJobMethodTree, JobMethodTreeItem } from "../methods.ts";
+import { Database } from "../types.ts";
+import { ResourceManager } from "./resource-manager.ts";
+import { BaseOperation, Operation, SchedulingStrategy } from "./types.ts";
+
+class SchedulingEngine {
+ private client: SupabaseClient<Database>;
+ private db: Kysely<DB>;
+ private jobId: string;
+ private operationsToSchedule: BaseOperation[];
+ private resourceManager: ResourceManager;
+
+ constructor({
+ client,
+ db,
+ jobId,
+ companyId,
+ }: {
+ client: SupabaseClient<Database>;
+ db: Kysely<DB>;
+ jobId: string;
+ companyId: string;
+ }) {
+ this.db = db;
+ this.client = client;
+ this.jobId = jobId;
+ this.operationsToSchedule = [];
+ this.resourceManager = new ResourceManager(db, companyId);
+ }
+
+ async initialize(): Promise<void> {
+ if (!this.db) {
+ throw new Error("Database connection is not initialized");
+ }
+ await Promise.all([
+ this.resourceManager.initialize(this.jobId),
+ this.getOperationsToSchedule(),
+ ]);
+ }
+
+ async prioritize(
+ strategy: SchedulingStrategy = SchedulingStrategy.LeastTime
+ ): Promise<void> {
+ switch (strategy) {
+ case SchedulingStrategy.LeastTime: {
+ const workCenterUpdates: Record<
+ string,
+ { workCenterId: string; priority: number }
+ > = {};
+
+ if (this.operationsToSchedule.length > 0) {
+ for (const operation of this.operationsToSchedule) {
+ if (!operation.processId || operation.operationType === "Outside") {
+ continue;
+ }
+
+ const result = operation.workCenterId
+ ? this.resourceManager.getPriorityByWorkCenterId(
+ operation.workCenterId
+ )
+ : this.resourceManager.getWorkCenterAndPriorityByProcessId(
+ operation.processId
+ );
+
+ console.log(
+ `Updating operation ${operation.id} with priority ${result.priority} and work center ${result.workCenter}`
+ );
+
+ if (!result.workCenter) {
+ console.error("No work center found for operation", operation);
+ continue;
+ }
+ workCenterUpdates[operation.id!] = {
+ workCenterId: result.workCenter,
+ priority: result.priority,
+ };
+
+ this.resourceManager.addOperationToWorkCenter(result.workCenter, {
+ ...operation,
+ priority: result.priority,
+ });
+ }
+ }
+
+ await this.db.transaction().execute(async (trx) => {
+ for await (const [id, { workCenterId, priority }] of Object.entries(
+ workCenterUpdates
+ )) {
+ await trx
+ .updateTable("jobOperation")
+ .set({
+ workCenterId,
+ priority,
+ })
+ .where("id", "=", id)
+ .execute();
+ }
+
+ trx
+ .updateTable("job")
+ .set({
+ status: "Ready",
+ })
+ .where("id", "=", this.jobId)
+ .execute();
+ });
+ break;
+ }
+ default: {
+ throw new Error(`Unsupported scheduling strategy: ${strategy}`);
+ }
+ }
+ }
+
+ async getOperationsToSchedule() {
+ if (!this.db) {
+ throw new Error("Database connection is not initialized");
+ }
+ const [jobMakeMethod, operations] = await Promise.all([
+ this.db
+ .selectFrom("jobMakeMethod")
+ .select(["id"])
+ .where("jobId", "=", this.jobId)
+ .where("parentMaterialId", "is", null)
+ .executeTakeFirst(),
+ this.db
+ .selectFrom("jobOperation")
+ .selectAll()
+ .where("jobId", "=", this.jobId)
+ .where("status", "not in", ["Done", "Canceled"])
+ .where("operationType", "not in", ["Outside"])
+ .execute(),
+ ]);
+
+ const operationsByJobMakeMethodId = operations.reduce<
+ Record<string, BaseOperation[]>
+ >((acc, operation) => {
+ if (!operation.jobMakeMethodId) return acc;
+ if (!acc[operation.jobMakeMethodId]) {
+ acc[operation.jobMakeMethodId] = [];
+ }
+ acc[operation.jobMakeMethodId].push(operation);
+ return acc;
+ }, {});
+
+ if (!jobMakeMethod?.id) {
+ throw new Error("Job make method not found");
+ }
+ const jobMethodTrees = await getJobMethodTree(
+ this.client,
+ jobMakeMethod.id
+ );
+ if (jobMethodTrees.error) {
+ throw new Error("Job method tree not found");
+ }
+
+ const jobMethodTree = jobMethodTrees.data?.[0] as JobMethodTreeItem;
+ if (!jobMethodTree) throw new Error("Method tree not found");
+
+ const operationsToSchedule: BaseOperation[] = [];
+ const queue: JobMethodTreeItem[] = [jobMethodTree];
+
+ while (queue.length > 0) {
+ const currentNode = queue.shift();
+ if (!currentNode) continue;
+
+ const operations =
+ operationsByJobMakeMethodId[currentNode.data.jobMaterialMakeMethodId] ||
+ [];
+ operationsToSchedule.unshift(...operations);
+
+ queue.push(...currentNode.children);
+ }
+
+ this.operationsToSchedule = operationsToSchedule;
+ }
+}
+
+export { SchedulingEngine };
+
+function sortOperations(operations: Operation[]) {
+ return operations.sort((a, b) => {
+ // First should come anything that's in progress
+ if (a.status === "In Progress" && b.status !== "In Progress") {
+ return -1;
+ } else if (a.status !== "In Progress" && b.status === "In Progress") {
+ return 1;
+ }
+ // Then anything that's paused
+ else if (a.status === "Paused" && b.status !== "Paused") {
+ return -1;
+ } else if (a.status !== "Paused" && b.status === "Paused") {
+ return 1;
+ }
+ // Then anything that's ASAP
+ else if (a.deadlineType === "ASAP" && b.deadlineType !== "ASAP") {
+ return -1;
+ } else if (a.deadlineType !== "ASAP" && b.deadlineType === "ASAP") {
+ return 1;
+ }
+ // Then we sort deadlines
+ else if (
+ a.deadlineType === "Hard Deadline" ||
+ a.deadlineType === "Soft Deadline"
+ ) {
+ if (
+ b.deadlineType === "Hard Deadline" ||
+ b.deadlineType === "Soft Deadline"
+ ) {
+ return a.dueDate?.localeCompare(b.dueDate ?? "") ?? 0;
+ } else {
+ return -1;
+ }
+ }
+ // Finally we add anything that has no deadline
+ else if (
+ a.deadlineType === "No Deadline" &&
+ b.deadlineType !== "No Deadline"
+ ) {
+ return 1;
+ } else if (
+ a.deadlineType === "No Deadline" &&
+ b.deadlineType === "No Deadline"
+ ) {
+ return a.dueDate?.localeCompare(b.dueDate ?? "") ?? 0;
+ } else {
+ return 0;
+ }
+ });
+}
diff --git a/packages/database/supabase/functions/lib/scheduling/resource-manager.ts b/packages/database/supabase/functions/lib/scheduling/resource-manager.ts
new file mode 100644
index 0000000000..eddbdb76ea
--- /dev/null
+++ b/packages/database/supabase/functions/lib/scheduling/resource-manager.ts
@@ -0,0 +1,523 @@
+import { Kysely } from "https://esm.sh/[email protected]";
+
+import { DB } from "../database.ts";
+import type { BaseOperation, Job, Operation } from "./types.ts";
+
+class ResourceManager {
+ private db: Kysely<DB>;
+ private companyId: string;
+ private job: Job | null;
+ private activeJobs: string[];
+ private operationsByWorkCenter: Map<string | null, Operation[]>;
+ private workCentersByProcess: Map<string, string[]>;
+ private durationsByWorkCenter: Map<string | null, number>;
+ constructor(db: Kysely<DB>, companyId: string) {
+ this.db = db;
+ this.companyId = companyId;
+ this.job = null;
+ this.activeJobs = [];
+ this.operationsByWorkCenter = new Map<string | null, Operation[]>();
+ this.workCentersByProcess = new Map<string, string[]>();
+ this.durationsByWorkCenter = new Map<string | null, number>();
+ }
+
+ async initialize(jobId: string) {
+ if (!this.db) {
+ throw new Error("Database connection is not initialized");
+ }
+
+ const [job, jobs] = await Promise.all([
+ this.db
+ .selectFrom("job")
+ .select(["id", "dueDate", "deadlineType", "locationId"])
+ .where("id", "=", jobId)
+ .executeTakeFirst(),
+ this.db
+ .selectFrom("job")
+ .select(["id", "dueDate", "deadlineType", "locationId"])
+ .where("companyId", "=", this.companyId)
+ .where("status", "in", ["Ready", "In Progress", "Paused"])
+ .where("id", "!=", jobId)
+ .execute(),
+ ]);
+
+ if (job) {
+ this.job = job;
+ }
+
+ // ignore jobs that aren't at the same location
+ this.activeJobs = jobs?.reduce<string[]>((acc, j) => {
+ if (j.id && j.locationId === this.job?.locationId) {
+ acc.push(j.id);
+ }
+ return acc;
+ }, []);
+
+ const [processes, workCenters] = await Promise.all([
+ this.db
+ .selectFrom("processes")
+ .select(["id", "workCenters"])
+ .where("companyId", "=", this.companyId)
+ .execute(),
+ this.db
+ .selectFrom("workCenter")
+ .select(["id", "locationId"])
+ .where("locationId", "=", this.job?.locationId)
+ .where("companyId", "=", this.companyId)
+ .execute(),
+ ]);
+
+ let operations: BaseOperation[] = [];
+ if (this.activeJobs.length > 0) {
+ operations = await this.db
+ .selectFrom("jobOperation")
+ .innerJoin("job", "jobOperation.jobId", "job.id")
+ .select([
+ "jobOperation.id",
+ "jobOperation.jobId",
+ "jobOperation.processId",
+ "jobOperation.workCenterId",
+ "jobOperation.status",
+ "jobOperation.laborTime",
+ "jobOperation.laborUnit",
+ "jobOperation.machineTime",
+ "jobOperation.machineUnit",
+ "jobOperation.setupTime",
+ "jobOperation.setupUnit",
+ "jobOperation.operationQuantity",
+ "jobOperation.priority",
+ "job.dueDate",
+ "job.deadlineType",
+ ])
+ .where("jobOperation.jobId", "in", this.activeJobs)
+ .where("job.companyId", "=", this.companyId)
+ .execute();
+ }
+
+ this.operationsByWorkCenter = new Map<string, Operation[]>();
+
+ operations
+ ?.map((op) => getDurations(op))
+ ?.forEach((operation) => {
+ if (!this.operationsByWorkCenter.has(operation.workCenterId ?? null)) {
+ this.operationsByWorkCenter.set(operation.workCenterId ?? null, []);
+ }
+ this.operationsByWorkCenter
+ .get(operation.workCenterId ?? null)
+ ?.push(operation);
+ });
+
+ // Sort each array in operationsByWorkCenter by priority
+ this.operationsByWorkCenter.forEach((operations, workCenterId) => {
+ this.operationsByWorkCenter.set(
+ workCenterId,
+ operations.sort(
+ (a, b) => Number(a.priority ?? 0) - Number(b.priority ?? 0)
+ )
+ );
+ });
+
+ // Initialize workCentersByProcess map
+ this.workCentersByProcess = new Map<string, string[]>();
+
+ // Populate workCentersByProcess map
+ processes?.forEach((process) => {
+ if (process.workCenters) {
+ // only consider work centers at this location
+ const workCenterIds = (process.workCenters as { id: string }[])
+ .map((wc: { id: string }) => wc.id)
+ .filter((wc) => workCenters?.some((w) => w.id === wc));
+ this.workCentersByProcess.set(process.id!, workCenterIds);
+ }
+ });
+ }
+
+ getJob(): Job | null {
+ return this.job;
+ }
+
+ getPriorityByWorkCenterId(workCenterId: string): {
+ workCenter: string;
+ priority: number;
+ } {
+ const deadlineType = this.job?.deadlineType ?? "No Deadline";
+ const dueDate = this.job?.dueDate ?? "";
+
+ const operations = this.operationsByWorkCenter.get(workCenterId) || [];
+
+ let priorityBefore = 0;
+ let priorityAfter: number | undefined;
+
+ if (operations.length === 0) {
+ // If there are no operations, set priorityBefore to 0 and priorityAfter to undefined
+ return { workCenter: workCenterId, priority: 1 };
+ }
+
+ // Iterate backwards over the operations until we find the first operation that matches the deadline type
+ for (let i = operations.length - 1; i >= 0; i--) {
+ const currentOp = operations[i];
+
+ if (deadlineType === "ASAP") {
+ if (currentOp.deadlineType === "ASAP") {
+ priorityBefore = Number(currentOp.priority ?? 0);
+ priorityAfter = Number(
+ operations[i + 1]?.priority ?? priorityBefore + 1
+ );
+
+ return {
+ workCenter: workCenterId,
+ priority: Number(priorityBefore + priorityAfter) / 2,
+ };
+ }
+ } else if (deadlineType === "Hard Deadline") {
+ if (
+ currentOp.deadlineType === "ASAP" ||
+ (currentOp.deadlineType === "Hard Deadline" &&
+ currentOp.dueDate &&
+ currentOp.dueDate <= dueDate) ||
+ (currentOp.deadlineType === "Soft Deadline" &&
+ currentOp.dueDate &&
+ currentOp.dueDate < dueDate)
+ ) {
+ priorityBefore = Number(currentOp.priority ?? 0);
+ priorityAfter = Number(
+ operations[i + 1]?.priority ?? priorityBefore + 1
+ );
+
+ return {
+ workCenter: workCenterId,
+ priority: Number(priorityBefore + priorityAfter) / 2,
+ };
+ }
+ } else if (deadlineType === "Soft Deadline") {
+ if (
+ currentOp.deadlineType === "ASAP" ||
+ (currentOp.deadlineType === "Hard Deadline" &&
+ currentOp.dueDate &&
+ currentOp.dueDate <= dueDate) ||
+ (currentOp.deadlineType === "Soft Deadline" &&
+ currentOp.dueDate &&
+ currentOp.dueDate <= dueDate)
+ ) {
+ priorityBefore = Number(currentOp.priority ?? 0);
+ priorityAfter = Number(
+ operations[i + 1]?.priority ?? priorityBefore + 1
+ );
+
+ return {
+ workCenter: workCenterId,
+ priority: Number(priorityBefore + priorityAfter) / 2,
+ };
+ }
+ } else if (deadlineType === "No Deadline") {
+ return {
+ workCenter: workCenterId,
+ priority:
+ Number(operations[operations.length - 1]?.priority ?? 0) + 1,
+ };
+ }
+ }
+
+ if (
+ priorityBefore === 0 &&
+ priorityAfter === undefined &&
+ deadlineType !== "ASAP"
+ ) {
+ console.error("No priority found for work center", workCenterId);
+ return {
+ workCenter: workCenterId,
+ priority: Number(operations[operations.length - 1]?.priority ?? 0) + 1,
+ };
+ }
+
+ return {
+ workCenter: workCenterId,
+ priority: 0,
+ };
+ }
+
+ getDurationByWorkCenterIdAndPriority(
+ workCenterId: string,
+ priority: number
+ ): number {
+ const operations = this.operationsByWorkCenter.get(workCenterId) || [];
+ let duration = 0;
+
+ operations.forEach((operation) => {
+ if (operation.priority && operation.priority < priority) {
+ duration += operation.duration;
+ } else {
+ return duration;
+ }
+ });
+
+ return duration;
+ }
+
+ getWorkCenterAndPriorityByProcessId(processId: string): {
+ workCenter: string | null;
+ priority: number;
+ } {
+ const workCenters = this.workCentersByProcess.get(processId) ?? [];
+ if (workCenters.length === 0) {
+ console.error("No work centers found for process", processId);
+ return {
+ workCenter: null,
+ priority: 0,
+ };
+ }
+
+ const priorityByWorkCenter: Map<string | null, number> = new Map();
+ workCenters.forEach((workCenter) => {
+ const { priority } = this.getPriorityByWorkCenterId(workCenter);
+ priorityByWorkCenter.set(workCenter, priority);
+ });
+
+ console.log({ workCenters });
+
+ // TODO: use cached durations if available
+ workCenters.forEach((workCenter) => {
+ const duration = this.getDurationByWorkCenterIdAndPriority(
+ workCenter,
+ priorityByWorkCenter.get(workCenter) ?? 0
+ );
+ this.durationsByWorkCenter.set(workCenter, duration);
+ });
+
+ let selectedWorkCenter: string | null = null;
+ let lowestDuration = Infinity;
+
+ for (const workCenter of workCenters) {
+ const duration = this.durationsByWorkCenter.get(workCenter) ?? 0;
+ if (duration < lowestDuration) {
+ lowestDuration = duration;
+ selectedWorkCenter = workCenter;
+ }
+ }
+
+ if (!selectedWorkCenter) {
+ console.error("No work center selected after evaluation");
+ return {
+ workCenter: null,
+ priority: 0,
+ };
+ }
+
+ return {
+ workCenter: selectedWorkCenter,
+ priority: priorityByWorkCenter.get(selectedWorkCenter) ?? 0,
+ };
+ }
+
+ addOperationToWorkCenter(workCenterId: string, operation: BaseOperation) {
+ if (!this.operationsByWorkCenter.has(workCenterId)) {
+ this.operationsByWorkCenter.set(workCenterId, []);
+ }
+
+ const operationWithDurations = getDurations({
+ ...operation,
+ deadlineType: this.job?.deadlineType ?? "No Deadline",
+ dueDate: this.job?.dueDate ?? "",
+ });
+
+ const operations = this.operationsByWorkCenter.get(workCenterId);
+ if (operations) {
+ operations.push(operationWithDurations);
+ operations.sort(
+ (a, b) => Number(a.priority ?? 0) - Number(b.priority ?? 0)
+ );
+ this.operationsByWorkCenter.set(workCenterId, operations);
+ }
+
+ // Update the duration for the work center
+ const currentDuration = this.durationsByWorkCenter.get(workCenterId) ?? 0;
+ const newDuration = currentDuration + operationWithDurations.duration;
+ this.durationsByWorkCenter.set(workCenterId, newDuration);
+ }
+}
+
+export { ResourceManager };
+
+function getDurations(operation: BaseOperation): Operation {
+ let setupDuration = 0;
+ let laborDuration = 0;
+ let machineDuration = 0;
+
+ if (!operation.operationQuantity) {
+ return {
+ ...operation,
+ setupTime: operation.setupTime ?? 0,
+ laborTime: operation.laborTime ?? 0 ?? 0,
+ machineTime: operation.machineTime ?? 0,
+ operationQuantity: 0,
+ duration: 0,
+ setupDuration: 0,
+ laborDuration: 0,
+ machineDuration: 0,
+ };
+ }
+
+ // Calculate setup duration
+ switch (operation.setupUnit) {
+ case "Total Hours":
+ setupDuration = (operation.setupTime ?? 0) * 3600000; // Convert hours to milliseconds
+ break;
+ case "Total Minutes":
+ setupDuration = (operation.setupTime ?? 0) * 60000; // Convert minutes to milliseconds
+ break;
+ case "Hours/Piece":
+ setupDuration =
+ (operation.setupTime ?? 0) * operation.operationQuantity * 3600000;
+ break;
+ case "Hours/100 Pieces":
+ setupDuration =
+ ((operation.setupTime ?? 0) / 100) *
+ operation.operationQuantity *
+ 3600000;
+ break;
+ case "Hours/1000 Pieces":
+ setupDuration =
+ ((operation.setupTime ?? 0) / 1000) *
+ operation.operationQuantity *
+ 3600000;
+ break;
+ case "Minutes/Piece":
+ setupDuration =
+ (operation.setupTime ?? 0) * operation.operationQuantity * 60000;
+ break;
+ case "Minutes/100 Pieces":
+ setupDuration =
+ ((operation.setupTime ?? 0) / 100) *
+ operation.operationQuantity *
+ 60000;
+ break;
+ case "Minutes/1000 Pieces":
+ setupDuration =
+ ((operation.setupTime ?? 0) / 1000) *
+ operation.operationQuantity *
+ 60000;
+ break;
+ case "Pieces/Hour":
+ setupDuration =
+ (operation.operationQuantity / (operation.setupTime ?? 0)) * 3600000;
+ break;
+ case "Pieces/Minute":
+ setupDuration =
+ (operation.operationQuantity / (operation.setupTime ?? 0)) * 60000;
+ break;
+ case "Seconds/Piece":
+ setupDuration =
+ (operation.setupTime ?? 0) * operation.operationQuantity * 1000;
+ break;
+ }
+
+ // Calculate labor duration
+ switch (operation.laborUnit) {
+ case "Hours/Piece":
+ laborDuration =
+ (operation.laborTime ?? 0) * operation.operationQuantity * 3600000 ?? 0;
+ break;
+ case "Hours/100 Pieces":
+ laborDuration =
+ ((operation.laborTime ?? 0) / 100) *
+ operation.operationQuantity *
+ 3600000 ?? 0;
+ break;
+ case "Hours/1000 Pieces":
+ laborDuration =
+ ((operation.laborTime ?? 0) / 1000) *
+ operation.operationQuantity *
+ 3600000 ?? 0;
+ break;
+ case "Minutes/Piece":
+ laborDuration =
+ (operation.laborTime ?? 0) * operation.operationQuantity * 60000 ?? 0;
+ break;
+ case "Minutes/100 Pieces":
+ laborDuration =
+ ((operation.laborTime ?? 0) / 100) *
+ operation.operationQuantity *
+ 60000 ?? 0;
+ break;
+ case "Minutes/1000 Pieces":
+ laborDuration =
+ ((operation.laborTime ?? 0) / 1000) *
+ operation.operationQuantity *
+ 60000 ?? 0;
+ break;
+ case "Pieces/Hour":
+ laborDuration =
+ (operation.operationQuantity / (operation.laborTime ?? 0)) * 3600000 ??
+ 0;
+ break;
+ case "Pieces/Minute":
+ laborDuration =
+ (operation.operationQuantity / (operation.laborTime ?? 0)) * 60000 ?? 0;
+ break;
+ case "Seconds/Piece":
+ laborDuration =
+ (operation.laborTime ?? 0) * operation.operationQuantity * 1000 ?? 0;
+ break;
+ }
+
+ // Calculate machine duration
+ switch (operation.machineUnit) {
+ case "Hours/Piece":
+ machineDuration =
+ (operation.machineTime ?? 0) * operation.operationQuantity * 3600000;
+ break;
+ case "Hours/100 Pieces":
+ machineDuration =
+ ((operation.machineTime ?? 0) / 100) *
+ operation.operationQuantity *
+ 3600000;
+ break;
+ case "Hours/1000 Pieces":
+ machineDuration =
+ ((operation.machineTime ?? 0) / 1000) *
+ operation.operationQuantity *
+ 3600000;
+ break;
+ case "Minutes/Piece":
+ machineDuration =
+ (operation.machineTime ?? 0) * operation.operationQuantity * 60000;
+ break;
+ case "Minutes/100 Pieces":
+ machineDuration =
+ ((operation.machineTime ?? 0) / 100) *
+ operation.operationQuantity *
+ 60000;
+ break;
+ case "Minutes/1000 Pieces":
+ machineDuration =
+ ((operation.machineTime ?? 0) / 1000) *
+ operation.operationQuantity *
+ 60000;
+ break;
+ case "Pieces/Hour":
+ machineDuration =
+ (operation.operationQuantity / (operation.machineTime ?? 0)) * 3600000;
+ break;
+ case "Pieces/Minute":
+ machineDuration =
+ (operation.operationQuantity / (operation.machineTime ?? 0)) * 60000;
+ break;
+ case "Seconds/Piece":
+ machineDuration =
+ (operation.machineTime ?? 0) * operation.operationQuantity * 1000;
+ break;
+ }
+
+ const totalDuration = setupDuration + laborDuration + machineDuration;
+
+ return {
+ ...operation,
+ setupTime: operation.setupTime ?? 0,
+ laborTime: operation.laborTime ?? 0,
+ machineTime: operation.machineTime ?? 0,
+ duration: totalDuration,
+ setupDuration,
+ laborDuration,
+ machineDuration,
+ };
+}
diff --git a/packages/database/supabase/functions/lib/scheduling/types.ts b/packages/database/supabase/functions/lib/scheduling/types.ts
new file mode 100644
index 0000000000..38c93ee6cc
--- /dev/null
+++ b/packages/database/supabase/functions/lib/scheduling/types.ts
@@ -0,0 +1,49 @@
+import type { Database } from "../types.ts";
+
+export type DeadlineType = Database["public"]["Enums"]["deadlineType"];
+
+export type BaseOperation = {
+ id?: string;
+ jobId: string;
+ deadlineType?: DeadlineType;
+ description?: string | null;
+ dueDate?: string | null;
+ laborTime?: number;
+ laborUnit?: Database["public"]["Enums"]["factor"];
+ machineTime?: number;
+ machineUnit?: Database["public"]["Enums"]["factor"];
+ operationQuantity?: number | null;
+ operationType?: Database["public"]["Enums"]["operationType"];
+ priority?: number;
+ processId: string | null;
+ setupTime?: number;
+ setupUnit?: Database["public"]["Enums"]["factor"];
+ status?: Database["public"]["Enums"]["jobOperationStatus"];
+ workCenterId?: string | null;
+};
+
+export type Operation = Omit<
+ BaseOperation,
+ "setupTime" | "laborTime" | "machineTime"
+> & {
+ duration: number;
+ laborDuration: number;
+ laborTime: number;
+ machineDuration: number;
+ machineTime: number;
+ setupDuration: number;
+ setupTime: number;
+};
+
+export type Job = {
+ id?: string;
+ dueDate?: string | null;
+ deadlineType?: Database["public"]["Enums"]["deadlineType"];
+ locationId?: string;
+};
+
+export enum SchedulingStrategy {
+ PriorityLeastTime,
+ LeastTime,
+ Random,
+}
diff --git a/packages/database/supabase/functions/post-receipt/index.ts b/packages/database/supabase/functions/post-receipt/index.ts
index ecc51d06cf..28ac51f48b 100644
--- a/packages/database/supabase/functions/post-receipt/index.ts
+++ b/packages/database/supabase/functions/post-receipt/index.ts
@@ -274,7 +274,6 @@ serve(async (req: Request) => {
`${itemPostingGroupId}-${supplierTypeId}`
];
} else {
- console.log({ itemPostingGroupId, supplierTypeId });
const purchasingPostingGroup = await getPurchasingPostingGroup(
client,
companyId,
diff --git a/packages/database/supabase/functions/scheduler/index.ts b/packages/database/supabase/functions/scheduler/index.ts
index af763136a0..ec80ed679d 100644
--- a/packages/database/supabase/functions/scheduler/index.ts
+++ b/packages/database/supabase/functions/scheduler/index.ts
@@ -1,57 +1,48 @@
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 { jobs, workCenters } from "./data.ts";
+import { SchedulingEngine } from "../lib/scheduling/engine.ts";
+import { SchedulingStrategy } from "../lib/scheduling/types.ts";
+import { getSupabaseServiceRole } from "../lib/supabase.ts";
+
+const pool = getConnectionPool(1);
+const db = getDatabaseClient<DB>(pool);
+
+const payloadValidator = z.object({
+ jobId: z.string(),
+ companyId: z.string(),
+ userId: z.string(),
+});
serve(async (req: Request) => {
if (req.method === "OPTIONS") {
return new Response("ok", { headers: corsHeaders });
}
-
- const loadBalancer = new LoadBalancer(workCenters);
+ const payload = await req.json();
try {
// const client = getSupabaseServiceRoleFromAuthorizationHeader(req.headers.get("Authorization"));
+ const { jobId, companyId, userId } = payloadValidator.parse(payload);
- const operationsByType = jobs.reduce((acc, job) => {
- job.operations.forEach((operation) => {
- if (operation.status === "DONE") return;
- acc[operation.workCenterType] = acc[operation.workCenterType] || [];
- acc[operation.workCenterType].push({
- ...operation,
- jobId: job.id,
- deadlineDate: job.deadlineDate,
- deadlineType: job.deadlineType,
- });
- });
- return acc;
- }, {} as Record<string, Operation[]>);
-
- const sortedOperationsByType = Object.entries(operationsByType).reduce(
- (acc, [workCenterType, operations]) => {
- acc[workCenterType] = sortOperations(operations);
- return acc;
- },
- {} as Record<string, Operation[]>
- );
+ console.log({
+ function: "scheduler",
+ jobId,
+ companyId,
+ userId,
+ });
- const operationsWithWorkCenter: OperationWithWorkCenter[] = Object.values(
- sortedOperationsByType
- ).flatMap((operations) =>
- operations.map((operation, index) => {
- const { workCenterType } = operation;
+ const client = getSupabaseServiceRole(req.headers.get("Authorization"));
- const workCenter = loadBalancer.get(workCenterType);
- loadBalancer.add(workCenterType, workCenter.id, operation.duration);
+ const engine = new SchedulingEngine({ client, db, jobId, companyId });
- return { ...operation, workCenterId: workCenter.id, order: index };
- })
- );
+ await engine.initialize();
+ await engine.prioritize(SchedulingStrategy.LeastTime);
return new Response(
JSON.stringify({
- operationsWithWorkCenter,
- workCenters,
+ success: true,
}),
{
headers: { ...corsHeaders, "Content-Type": "application/json" },
@@ -66,116 +57,3 @@ serve(async (req: Request) => {
});
}
});
-
-type WorkCenter = {
- id: string;
- name: string;
- workCenterType: string;
-};
-
-type Operation = {
- id: string;
- jobId: string;
- deadlineDate: string;
- deadlineType: string;
- duration: number;
- status: string;
- workCenterType: string;
- timecards?: {
- start: string;
- end?: string;
- machine?: string;
- }[];
-};
-
-type OperationWithWorkCenter = Operation & {
- workCenterId: string;
- order: number;
-};
-
-function sortOperations(operations: Operation[]) {
- return operations.sort((a, b) => {
- // First should come anything that's in progress
- if (a.status === "IN_PROGRESS" && b.status !== "IN_PROGRESS") {
- return -1;
- } else if (a.status !== "IN_PROGRESS" && b.status === "IN_PROGRESS") {
- return 1;
- }
- // Then anything that's paused
- else if (a.status === "PAUSED" && b.status !== "PAUSED") {
- return -1;
- } else if (a.status !== "PAUSED" && b.status === "PAUSED") {
- return 1;
- }
- // Then anything that's ASAP
- else if (a.deadlineType === "ASAP" && b.deadlineType !== "ASAP") {
- return -1;
- } else if (a.deadlineType !== "ASAP" && b.deadlineType === "ASAP") {
- return 1;
- }
- // Then we sort deadlines
- else if (
- a.deadlineType === "Hard Deadline" ||
- a.deadlineType === "Soft Deadline"
- ) {
- if (
- b.deadlineType === "Hard Deadline" ||
- b.deadlineType === "Soft Deadline"
- ) {
- return a.deadlineDate.localeCompare(b.deadlineDate);
- } else {
- return -1;
- }
- }
- // Finally we add anything that has no deadline
- else if (
- a.deadlineType === "No Deadline" &&
- b.deadlineType !== "No Deadline"
- ) {
- return 1;
- } else if (
- a.deadlineType === "No Deadline" &&
- b.deadlineType === "No Deadline"
- ) {
- return a.deadlineDate.localeCompare(b.deadlineDate);
- } else {
- return 0;
- }
- });
-}
-
-type WorkCenterWithDuration = WorkCenter & {
- duration: number;
-};
-
-class LoadBalancer {
- private workCentersByType: Record<string, WorkCenterWithDuration[]> = {};
-
- constructor(workCenters: WorkCenter[]) {
- this.workCentersByType = workCenters.reduce<
- Record<string, WorkCenterWithDuration[]>
- >((acc, machine) => {
- acc[machine.workCenterType] = acc[machine.workCenterType] || [];
- acc[machine.workCenterType].push({ ...machine, duration: 0 });
- return acc;
- }, {});
- }
-
- public get(workCenterType: string) {
- const workCenters = this.workCentersByType[workCenterType];
- return workCenters.reduce((minWorkCenter, workCenter) =>
- workCenter.duration < minWorkCenter.duration ? workCenter : minWorkCenter
- );
- }
-
- public add(workCenterType: string, workCenterId: string, duration: number) {
- this.workCentersByType[workCenterType] = this.workCentersByType[
- workCenterType
- ].map((workCenter) => {
- if (workCenter.id === workCenterId) {
- return { ...workCenter, duration: workCenter.duration + duration };
- }
- return workCenter;
- });
- }
-}
diff --git a/packages/database/supabase/migrations/20241019010616_operation-priority.sql b/packages/database/supabase/migrations/20241019010616_operation-priority.sql
new file mode 100644
index 0000000000..c4b50c1a4e
--- /dev/null
+++ b/packages/database/supabase/migrations/20241019010616_operation-priority.sql
@@ -0,0 +1,4 @@
+ALTER TABLE "jobOperation"
+ ADD COLUMN "priority" DOUBLE PRECISION NOT NULL DEFAULT 1;
+
+
diff --git a/packages/react/src/Alert.tsx b/packages/react/src/Alert.tsx
index f890e22561..f868827ae2 100644
--- a/packages/react/src/Alert.tsx
+++ b/packages/react/src/Alert.tsx
@@ -11,11 +11,11 @@ const alertVariants = cva(
variant: {
default: "bg-background text-foreground",
success:
- "bg-gradient-to-r dark:from-emerald-600/30 dark:via-card dark:to-card from-emerald-100 to-emerald-100 border-emerald-600 text-emerald-600 [&>svg]:text-emerald-600 dark:text-foreground dark:[&>svg]:text-foreground",
+ "bg-gradient-to-tl via-card to-card hover:to-muted/30 hover:via-muted/30 border-emerald-600/30 from-emerald-600/10 text-emerald-600 [&>svg]:text-emerald-600 dark:text-foreground dark:[&>svg]:text-foreground",
warning:
- "bg-gradient-to-r dark:from-yellow-700/30 dark:via-card dark:to-card from-yellow-100/10 to-yellow-100/10 border-yellow-700 text-yellow-800 [&>svg]:text-yellow-800 dark:text-foreground dark:[&>svg]:text-foreground",
+ "bg-gradient-to-tl via-card to-card hover:to-muted/30 hover:via-muted/30 border-yellow-500/30 from-yellow-500/10 text-yellow-800 [&>svg]:text-yellow-800 dark:text-foreground dark:[&>svg]:text-foreground",
destructive:
- "bg-gradient-to-r dark:from-destructive/30 dark:via-card dark:to-card from-destructive/10 to-destructive/10 border-destructive text-destructive [&>svg]:text-destructive dark:text-foreground dark:[&>svg]:text-foreground",
+ "bg-gradient-to-tl via-card to-card hover:to-muted/30 hover:via-muted/30 border-red-500/30 from-red-500/10 text-destructive [&>svg]:text-destructive dark:text-foreground dark:[&>svg]:text-foreground",
},
},
defaultVariants: {
diff --git a/packages/react/src/Card.tsx b/packages/react/src/Card.tsx
index fb44002bdb..9aed59cea5 100644
--- a/packages/react/src/Card.tsx
+++ b/packages/react/src/Card.tsx
@@ -31,7 +31,7 @@ const Card = forwardRef<HTMLDivElement, CardProps>(
<div
ref={ref}
className={cn(
- "relative flex flex-col rounded-lg border border-border dark:border-0 dark:shadow-[0px_1px_0px_0px_hsla(0,0%,100%,.03)_inset,0px_0px_0px_1px_hsla(0,0%,100%,.03)_inset,0px_0px_0px_1px_rgba(0,0,0,.1),0px_2px_2px_0px_rgba(0,0,0,.1),0px_4px_4px_0px_rgba(0,0,0,.1),0px_8px_8px_0px_rgba(0,0,0,.1)] bg-gradient-to-bl from-card via-card to-background text-card-foreground p-4 w-full",
+ "relative flex flex-col rounded-lg border border-border dark:border-0 dark:shadow-[0px_1px_0px_0px_hsla(0,0%,100%,.03)_inset,0px_0px_0px_1px_hsla(0,0%,100%,.03)_inset,0px_0px_0px_1px_rgba(0,0,0,.1),0px_2px_2px_0px_rgba(0,0,0,.1),0px_4px_4px_0px_rgba(0,0,0,.1),0px_8px_8px_0px_rgba(0,0,0,.1)] bg-gradient-to-bl from-card from-50% via-card to-background text-card-foreground p-4 w-full",
className
)}
{...props}