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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
refactor: scheduling engine
Brad Barbin86d75bd514a0
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex bd83b88af4..8c086996bb 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -256,12 +256,13 @@ export async function convertSalesOrderLinesToJobs(},});- await serviceRole.functions.invoke("scheduler", {+ await serviceRole.functions.invoke("schedule", {body: {- type: "dependencies",- id: createJob.data.id,+ jobId: createJob.data.id,companyId,userId,+ mode: "initial",+ direction: "backward",},});@@ -1499,18 +1500,25 @@ export async function getTrackedEntitiesByJobId(.eq("companyId", jobMakeMethod.data.companyId);}+/**+ * Reschedule a job using the unified scheduling engine.+ * This recalculates dates, work centers, and priorities for all operations.+ */export async function recalculateJobOperationDependencies(client: SupabaseClient<Database>,params: {- jobId: string; // job operation id+ jobId: string;companyId: string;userId: string;}) {- return client.functions.invoke("scheduler", {+ return client.functions.invoke("schedule", {body: {- type: "dependencies",- ...params,+ jobId: params.jobId,+ companyId: params.companyId,+ userId: params.userId,+ mode: "reschedule",+ direction: "backward",},region: FunctionRegion.UsEast1,});@@ -2460,20 +2468,39 @@ export async function upsertDemandProjections(};}-export async function triggerJobReschedule(+/**+ * Trigger a job scheduling task via Trigger.dev.+ * Supports both initial scheduling and rescheduling.+ */+export async function triggerJobSchedule(jobId: string,companyId: string,- userId: string+ userId: string,+ mode: "initial" | "reschedule" = "reschedule",+ direction: "backward" | "forward" = "backward") {- const { rescheduleJob } = await import(+ const { scheduleJob } = await import("@carbon/jobs/trigger/reschedule-job");- const handle = await rescheduleJob.trigger({+ const handle = await scheduleJob.trigger({jobId,companyId,userId,+ mode,+ direction,});return { success: true, runId: handle.id };}++/**+ * @deprecated Use triggerJobSchedule with mode="reschedule" instead.+ */+export async function triggerJobReschedule(+ jobId: string,+ companyId: string,+ userId: string+) {+ return triggerJobSchedule(jobId, companyId, userId, "reschedule", "backward");+}diff --git a/apps/erp/app/routes/api+/kanban.$id.tsx b/apps/erp/app/routes/api+/kanban.$id.tsxindex b3a93bfed6..772dcf4ac5 100644--- a/apps/erp/app/routes/api+/kanban.$id.tsx+++ b/apps/erp/app/routes/api+/kanban.$id.tsx@@ -171,12 +171,13 @@ async function handleKanban({companyId,userId,}),- serviceRole.functions.invoke("scheduler", {+ serviceRole.functions.invoke("schedule", {body: {- type: "schedule",jobId: id,companyId,userId,+ mode: "initial",+ direction: "backward",},region: FunctionRegion.UsEast1,}),diff --git a/apps/erp/app/routes/x+/job+/$jobId.status.tsx b/apps/erp/app/routes/x+/job+/$jobId.status.tsxindex 0184355f64..fa5db7610b 100644--- a/apps/erp/app/routes/x+/job+/$jobId.status.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.status.tsx@@ -80,12 +80,13 @@ export async function action({ request, params }: ActionFunctionArgs) {const serviceRole = getCarbonServiceRole();const [scheduler] = await Promise.all([- serviceRole.functions.invoke("scheduler", {+ serviceRole.functions.invoke("schedule", {body: {- type: "schedule",jobId: id,companyId,userId,+ mode: "initial",+ direction: "backward",},region: FunctionRegion.UsEast1,}),diff --git a/deno.lock b/deno.locknew file mode 100644index 0000000000..c20802ec8f--- /dev/null+++ b/deno.lock@@ -0,0 +1,910 @@+{+ "version": "3",+ "packages": {+ "specifiers": {+ "npm:zod@^3.24.1": "npm:[email protected]"+ },+ "npm": {+ "[email protected]": {+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",+ "dependencies": {}+ }+ }+ },+ "remote": {+ "https://deno.land/[email protected]/_util/assert.ts": "e94f2eb37cebd7f199952e242c77654e43333c1ac4c5c700e929ea3aa5489f74",+ "https://deno.land/[email protected]/_util/os.ts": "8a33345f74990e627b9dfe2de9b040004b08ea5146c7c9e8fe9a29070d193934",+ "https://deno.land/[email protected]/async/abortable.ts": "87aa7230be8360c24ad437212311c9e8d4328854baec27b4c7abb26e85515c06",+ "https://deno.land/[email protected]/async/deadline.ts": "48ac998d7564969f3e6ec6b6f9bf0217ebd00239b1b2292feba61272d5dd58d0",+ "https://deno.land/[email protected]/async/debounce.ts": "dc8b92d4a4fe7eac32c924f2b8d3e62112530db70cadce27042689d82970b350",+ "https://deno.land/[email protected]/async/deferred.ts": "d8fb253ffde2a056e4889ef7e90f3928f28be9f9294b6505773d33f136aab4e6",+ "https://deno.land/[email protected]/async/delay.ts": "0419dfc993752849692d1f9647edf13407c7facc3509b099381be99ffbc9d699",+ "https://deno.land/[email protected]/async/mod.ts": "dd0a8ed4f3984ffabe2fcca7c9f466b7932d57b1864ffee148a5d5388316db6b",+ "https://deno.land/[email protected]/async/mux_async_iterator.ts": "3447b28a2a582224a3d4d3596bccbba6e85040da3b97ed64012f7decce98d093",+ "https://deno.land/[email protected]/async/pool.ts": "ef9eb97b388543acbf0ac32647121e4dbe629236899586c4d4311a8770fbb239",+ "https://deno.land/[email protected]/async/tee.ts": "9af3a3e7612af75861308b52249e167f5ebc3dcfc8a1a4d45462d96606ee2b70",+ "https://deno.land/[email protected]/bytes/bytes_list.ts": "aba5e2369e77d426b10af1de0dcc4531acecec27f9b9056f4f7bfbf8ac147ab4",+ "https://deno.land/[email protected]/bytes/equals.ts": "3c3558c3ae85526f84510aa2b48ab2ad7bdd899e2e0f5b7a8ffc85acb3a6043a",+ "https://deno.land/[email protected]/bytes/mod.ts": "b2e342fd3669176a27a4e15061e9d588b89c1aaf5008ab71766e23669565d179",+ "https://deno.land/[email protected]/crypto/_fnv/fnv32.ts": "aa9bddead8c6345087d3abd4ef35fb9655622afc333fc41fff382b36e64280b5",+ "https://deno.land/[email protected]/crypto/_fnv/fnv64.ts": "625d7e7505b6cb2e9801b5fd6ed0a89256bac12b2bbb3e4664b85a88b0ec5bef",+ "https://deno.land/[email protected]/crypto/_fnv/index.ts": "a8f6a361b4c6d54e5e89c16098f99b6962a1dd6ad1307dbc97fa1ecac5d7060a",+ "https://deno.land/[email protected]/crypto/_fnv/util.ts": "4848313bed7f00f55be3cb080aa0583fc007812ba965b03e4009665bde614ce3",+ "https://deno.land/[email protected]/crypto/_wasm_crypto/lib/deno_std_wasm_crypto.generated.mjs": "258b484c2da27578bec61c01d4b62c21f72268d928d03c968c4eb590cb3bd830",+ "https://deno.land/[email protected]/crypto/_wasm_crypto/mod.ts": "6c60d332716147ded0eece0861780678d51b560f533b27db2e15c64a4ef83665",+ "https://deno.land/[email protected]/crypto/keystack.ts": "e481eed28007395e554a435e880fee83a5c73b9259ed8a135a75e4b1e4f381f7",+ "https://deno.land/[email protected]/crypto/mod.ts": "fadedc013b4a86fda6305f1adc6d1c02225834d53cff5d95cc05f62b25127517",+ "https://deno.land/[email protected]/crypto/timing_safe_equal.ts": "82a29b737bc8932d75d7a20c404136089d5d23629e94ba14efa98a8cc066c73e",+ "https://deno.land/[email protected]/datetime/formatter.ts": "7c8e6d16a0950f400aef41b9f1eb9168249869776ec520265dfda785d746589e",+ "https://deno.land/[email protected]/datetime/mod.ts": "ea927ca96dfb28c7b9a5eed5bdc7ac46bb9db38038c4922631895cea342fea87",+ "https://deno.land/[email protected]/datetime/tokenizer.ts": "7381e28f6ab51cb504c7e132be31773d73ef2f3e1e50a812736962b9df1e8c47",+ "https://deno.land/[email protected]/encoding/base64.ts": "c57868ca7fa2fbe919f57f88a623ad34e3d970d675bdc1ff3a9d02bba7409db2",+ "https://deno.land/[email protected]/encoding/base64url.ts": "a5f82a9fa703bd85a5eb8e7c1296bc6529e601ebd9642cc2b5eaa6b38fa9e05a",+ "https://deno.land/[email protected]/encoding/hex.ts": "4cc5324417cbb4ac9b828453d35aed45b9cc29506fad658f1f138d981ae33795",+ "https://deno.land/[email protected]/fmt/colors.ts": "9e36a716611dcd2e4865adea9c4bec916b5c60caad4cdcdc630d4974e6bb8bd4",+ "https://deno.land/[email protected]/io/buffer.ts": "fae02290f52301c4e0188670e730cd902f9307fb732d79c4aa14ebdc82497289",+ "https://deno.land/[email protected]/path/_constants.ts": "df1db3ffa6dd6d1252cc9617e5d72165cd2483df90e93833e13580687b6083c3",+ "https://deno.land/[email protected]/path/_interface.ts": "ee3b431a336b80cf445441109d089b70d87d5e248f4f90ff906820889ecf8d09",+ "https://deno.land/[email protected]/path/_util.ts": "d16be2a16e1204b65f9d0dfc54a9bc472cafe5f4a190b3c8471ec2016ccd1677",+ "https://deno.land/[email protected]/path/common.ts": "bee563630abd2d97f99d83c96c2fa0cca7cee103e8cb4e7699ec4d5db7bd2633",+ "https://deno.land/[email protected]/path/glob.ts": "cb5255638de1048973c3e69e420c77dc04f75755524cb3b2e160fe9277d939ee",+ "https://deno.land/[email protected]/path/mod.ts": "56fec03ad0ebd61b6ab39ddb9b0ddb4c4a5c9f2f4f632e09dd37ec9ebfd722ac",+ "https://deno.land/[email protected]/path/posix.ts": "6b63de7097e68c8663c84ccedc0fd977656eb134432d818ecd3a4e122638ac24",+ "https://deno.land/[email protected]/path/separator.ts": "fe1816cb765a8068afb3e8f13ad272351c85cbc739af56dacfc7d93d710fe0f9",+ "https://deno.land/[email protected]/path/win32.ts": "ee8826dce087d31c5c81cd414714e677eb68febc40308de87a2ce4b40e10fb8d",+ "https://deno.land/[email protected]/testing/_diff.ts": "a23e7fc2b4d8daa3e158fa06856bedf5334ce2a2831e8bf9e509717f455adb2c",+ "https://deno.land/[email protected]/testing/_format.ts": "cd11136e1797791045e639e9f0f4640d5b4166148796cad37e6ef75f7d7f3832",+ "https://deno.land/[email protected]/testing/asserts.ts": "1e340c589853e82e0807629ba31a43c84ebdcdeca910c4a9705715dfdb0f5ce8",+ "https://deno.land/[email protected]/async/abortable.ts": "73acfb3ed7261ce0d930dbe89e43db8d34e017b063cf0eaa7d215477bf53442e",+ "https://deno.land/[email protected]/async/deadline.ts": "b98e50d2c42399af03ad13bbb8cf59dadb9f0cd5d70648cc0c3b9202d75ab565",+ "https://deno.land/[email protected]/async/debounce.ts": "adab11d04ca38d699444ac8a9d9856b4155e8dda2afd07ce78276c01ea5a4332",+ "https://deno.land/[email protected]/async/deferred.ts": "42790112f36a75a57db4a96d33974a936deb7b04d25c6084a9fa8a49f135def8",+ "https://deno.land/[email protected]/async/delay.ts": "73aa04cec034c84fc748c7be49bb15cac3dd43a57174bfdb7a4aec22c248f0dd",+ "https://deno.land/[email protected]/async/mod.ts": "f04344fa21738e5ad6bea37a6bfffd57c617c2d372bb9f9dcfd118a1b622e576",+ "https://deno.land/[email protected]/async/mux_async_iterator.ts": "70c7f2ee4e9466161350473ad61cac0b9f115cff4c552eaa7ef9d50c4cbb4cc9",+ "https://deno.land/[email protected]/async/pool.ts": "fd082bd4aaf26445909889435a5c74334c017847842ec035739b4ae637ae8260",+ "https://deno.land/[email protected]/async/retry.ts": "5efa3ba450ac0c07a40a82e2df296287b5013755d232049efd7ea2244f15b20f",+ "https://deno.land/[email protected]/async/tee.ts": "47e42d35f622650b02234d43803d0383a89eb4387e1b83b5a40106d18ae36757",+ "https://deno.land/[email protected]/http/server.ts": "cbb17b594651215ba95c01a395700684e569c165a567e4e04bba327f41197433",+ "https://deno.land/x/[email protected]/client.ts": "348779c9f6a1c75ef1336db662faf08dce7d2101ff72f0d1e341ba1505c8431d",+ "https://deno.land/x/[email protected]/client/error.ts": "0817583b666fd546664ed52c1d37beccc5a9eebcc6e3c2ead20ada99b681e5f7",+ "https://deno.land/x/[email protected]/connection/auth.ts": "1070125e2ac4ca4ade36d69a4222d37001903092826d313217987583edd61ce9",+ "https://deno.land/x/[email protected]/connection/connection.ts": "428ed3efa055870db505092b5d3545ef743497b7b4b72cf8f0593e7dd4788acd",+ "https://deno.land/x/[email protected]/connection/connection_params.ts": "52bfe90e8860f584b95b1b08c254dde97c3aa763c4b6bee0c80c5930e35459e0",+ "https://deno.land/x/[email protected]/connection/message.ts": "f9257948b7f87d58bfbfe3fc6e2e08f0de3ef885655904d56a5f73655cc22c5a",+ "https://deno.land/x/[email protected]/connection/message_code.ts": "466719008b298770c366c5c63f6cf8285b7f76514dadb4b11e7d9756a8a1ddbf",+ "https://deno.land/x/[email protected]/connection/packet.ts": "050aeff1fc13c9349e89451a155ffcd0b1343dc313a51f84439e3e45f64b56c8",+ "https://deno.land/x/[email protected]/connection/scram.ts": "0c7a2551fe7b1a1c62dd856b7714731a7e7534ccca10093336782d1bfc5b2bd2",+ "https://deno.land/x/[email protected]/deps.ts": "f47ccb41f7f97eaad455d94f407ef97146ae99443dbe782894422c869fbba69e",+ "https://deno.land/x/[email protected]/mod.ts": "a1e18fd9e6fedc8bc24e5aeec3ae6de45e2274be1411fb66e9081420c5e81d7d",+ "https://deno.land/x/[email protected]/pool.ts": "892db7b5e1787988babecc994a151ebbd7d017f080905cbe9c3d7b44a73032a9",+ "https://deno.land/x/[email protected]/query/array_parser.ts": "f8a229d82c3801de8266fa2cc4afe12e94fef8d0c479e73655c86ed3667ef33f",+ "https://deno.land/x/[email protected]/query/decode.ts": "44a4a6cbcf494ed91a4fecae38a57dce63a7b519166f02c702791d9717371419",+ "https://deno.land/x/[email protected]/query/decoders.ts": "16cb0e60227d86692931e315421b15768c78526e3aeb84e25fcc4111096de9fd",+ "https://deno.land/x/[email protected]/query/encode.ts": "5f1418a2932b7c2231556e4a5f5f56efef48728014070cfafe7656963f342933",+ "https://deno.land/x/[email protected]/query/oid.ts": "8c33e1325f34e4ca9f11a48b8066c8cfcace5f64bc1eb17ad7247af4936999e1",+ "https://deno.land/x/[email protected]/query/query.ts": "edb473cbcfeff2ee1c631272afb25d079d06b66b5853f42492725b03ffa742b6",+ "https://deno.land/x/[email protected]/query/transaction.ts": "8e75c3ce0aca97da7fe126e68f8e6c08d640e5c8d2016e62cee5c254bebe7fe8",+ "https://deno.land/x/[email protected]/query/types.ts": "a6dc8024867fe7ccb0ba4b4fa403ee5d474c7742174128c8e689c3b5e5eaa933",+ "https://deno.land/x/[email protected]/utils/deferred.ts": "dd94f2a57355355c47812b061a51b55263f72d24e9cb3fdb474c7519f4d61083",+ "https://deno.land/x/[email protected]/utils/utils.ts": "19c3527ddd5c6c4c49ae36397120274c7f41f9d3cbf479cb36065d23329e9f90",+ "https://esm.sh/@supabase/[email protected]": "b9e0e18dfb0bfd1078c05be3474a710abf913ddc5b47bcb92317fabc4c5445e0",+ "https://esm.sh/[email protected]": "179ded4b970c58f84ffe3f7b1e2c1c702e187a81e4198ee5e797d83d8e86025a",+ "https://esm.sh/[email protected]/dist/esm/util/object-utils.js": "7cda1a1311f1dce507a3a18022dcfff3c9e5811686bb54c300bcfd7db58e38fd",+ "https://esm.sh/[email protected]/dist/esm/util/stack-trace-utils.js": "d238f86ca3c5be219b106c604fd6840a324870689d3e1b006cfb16875964898e"+ },+ "workspace": {+ "packageJson": {+ "dependencies": [+ "npm:@types/[email protected]",+ "npm:csv-parse@^5.5.0",+ "npm:eslint-config-carbon",+ "npm:eslint@^8.23.1",+ "npm:husky@^8.0.3",+ "npm:lint-staged@^13.1.2",+ "npm:npm-run-all@^4.1.5",+ "npm:patch-package@^8.0.1",+ "npm:[email protected]",+ "npm:prettier@^2.8.0",+ "npm:rimraf@^5.0.5",+ "npm:[email protected]",+ "npm:[email protected]",+ "npm:ts-morph@^22.0.0",+ "npm:tsx@^4.13.2",+ "npm:turbo@^1.13.2"+ ]+ },+ "members": {+ "apps/academy": {+ "packageJson": {+ "dependencies": [+ "npm:@carbon/auth",+ "npm:@carbon/database",+ "npm:@carbon/documents",+ "npm:@carbon/form",+ "npm:@carbon/kv",+ "npm:@carbon/logger",+ "npm:@carbon/react",+ "npm:@carbon/tailwind",+ "npm:@carbon/tsconfig",+ "npm:@carbon/utils",+ "npm:@react-aria/i18n@^3.11.0",+ "npm:@remix-run/dev@~2.16.7",+ "npm:@remix-run/eslint-config@~2.16.7",+ "npm:@remix-run/react@~2.16.7",+ "npm:@remix-run/serve@~2.16.7",+ "npm:@supabase/[email protected]",+ "npm:@supabase/supabase-js@^2.40.0",+ "npm:@tailwindcss/container-queries@^0.1.1",+ "npm:@tailwindcss/forms@^0.5.7",+ "npm:@tailwindcss/line-clamp@^0.4.4",+ "npm:@tailwindcss/typography@^0.5.10",+ "npm:@types/react-dom@^18.2.24",+ "npm:@types/react@^18.2.74",+ "npm:@upstash/ratelimit@^2.0.5",+ "npm:@vercel/analytics@^1.2.2",+ "npm:@vercel/[email protected]",+ "npm:[email protected]",+ "npm:[email protected]",+ "npm:framer-motion@^11.1.7",+ "npm:[email protected]",+ "npm:nodemon@^3.0.1",+ "npm:non.geist@~1.0.3",+ "npm:npm-run-all@^4.1.5",+ "npm:postcss@^8.4.33",+ "npm:react-confetti-explosion@^3.0.3",+ "npm:react-dom@^18.3.1",+ "npm:react-dropzone@^14.2.3",+ "npm:react-hotkeys-hook@~4.5.0",+ "npm:react-icons@^5.4.0",+ "npm:react@^18.3.1",+ "npm:tailwind-merge@^2.2.1",+ "npm:tailwind-scrollbar-hide@^1.1.7",+ "npm:tailwind-scrollbar@^2.0.1",+ "npm:tailwindcss-animate@^1.0.7",+ "npm:[email protected]",+ "npm:typescript@^5.2.2",+ "npm:vite-tsconfig-paths@^4.3.2",+ "npm:vite@^5.3.3",+ "npm:[email protected]",+ "npm:[email protected]",+ "npm:zod@^3.25.76"+ ]+ }+ },+ "apps/erp": {+ "packageJson": {+ "dependencies": [+ "npm:@ai-sdk-tools/[email protected]",+ "npm:@ai-sdk-tools/[email protected]",+ "npm:@ai-sdk-tools/[email protected]",+ "npm:@ai-sdk-tools/[email protected]",+ "npm:@ai-sdk-tools/[email protected]",+ "npm:@ai-sdk-tools/[email protected]",+ "npm:@ai-sdk/anthropic@^2.0.41",+ "npm:@ai-sdk/openai@^2.0.60",+ "npm:@ai-sdk/react@^2.0.86",+ "npm:@carbon/auth",+ "npm:@carbon/database",+ "npm:@carbon/documents",+ "npm:@carbon/form",+ "npm:@carbon/jobs",+ "npm:@carbon/kv",+ "npm:@carbon/lib",+ "npm:@carbon/notifications",+ "npm:@carbon/react",+ "npm:@carbon/remix",+ "npm:@carbon/tailwind",+ "npm:@carbon/tsconfig",+ "npm:@carbon/utils",+ "npm:@dnd-kit/core@^6.1.0",+ "npm:@dnd-kit/sortable@^8.0.0",+ "npm:@epic-web/remember@^1.1.0",+ "npm:@internationalized/date@^3.5.2",+ "npm:@marsidev/react-turnstile@^1.1.0",+ "npm:@monaco-editor/react@^4.6.0",+ "npm:@nanostores/react@^0.7.1",+ "npm:@novu/framework@^2.3.0",+ "npm:@novu/headless@^2.0.0",+ "npm:@novu/node@^2.0.1",+ "npm:@react-aria/i18n@^3.11.0",+ "npm:@react-email/[email protected]",+ "npm:@remix-run/dev@~2.16.7",+ "npm:@remix-run/eslint-config@~2.16.7",+ "npm:@remix-run/react@~2.16.7",+ "npm:@remix-run/serve@~2.16.7",+ "npm:@supabase/[email protected]",+ "npm:@supabase/supabase-js@^2.40.0",+ "npm:@tailwindcss/container-queries@^0.1.1",+ "npm:@tailwindcss/forms@^0.5.7",+ "npm:@tailwindcss/line-clamp@^0.4.4",+ "npm:@tailwindcss/typography@^0.5.10",+ "npm:@tanstack/react-query@^5.62.0",+ "npm:@tanstack/react-table@^8.9.3",+ "npm:@tanstack/react-virtual@^3.5.0",+ "npm:@trigger.dev/[email protected]",+ "npm:@trigger.dev/[email protected]",+ "npm:@trigger.dev/[email protected]",+ "npm:@types/d3@^7.4.0",+ "npm:@types/nprogress@^0.2.0",+ "npm:@types/papaparse@^5.3.14",+ "npm:@types/react-csv@^1.1.10",+ "npm:@types/react-dom@^18.2.24",+ "npm:@types/react@^18.2.74",+ "npm:@upstash/ratelimit@^2.0.5",+ "npm:@vercel/analytics@^1.2.2",+ "npm:@vercel/[email protected]",+ "npm:@visx/responsive@^2.1.0",+ "npm:ai@^5.0.88",+ "npm:assert-never@^1.2.1",+ "npm:[email protected]",+ "npm:clsx@^2.1.0",+ "npm:cookie@^0.6.0",+ "npm:[email protected]",+ "npm:d3-array@^3.2.4",+ "npm:d3@^7.8.5",+ "npm:framer-motion@^11.1.7",+ "npm:[email protected]",+ "npm:json-2-csv@^5.5.10",+ "npm:localforage@^1.10.0",+ "npm:lodash.debounce@^4.0.8",+ "npm:lodash.words@^4.2.0",+ "npm:monaco-editor@^0.44.0",+ "npm:[email protected]",+ "npm:[email protected]",+ "npm:nanostores@^0.9.3",+ "npm:nodemon@^3.0.1",+ "npm:non.geist@~1.0.3",+ "npm:npm-run-all@^4.1.5",+ "npm:[email protected]",+ "npm:[email protected]",+ "npm:postcss@^8.4.33",+ "npm:posthog-js@^1.116.6",+ "npm:react-csv@^2.2.2",+ "npm:react-dom@^18.3.1",+ "npm:react-dropzone@^14.2.3",+ "npm:react-hotkeys-hook@~4.5.0",+ "npm:react-icons@^5.4.0",+ "npm:react-intersection-observer@^9.13.1",+ "npm:react-markdown@^9.0.1",+ "npm:react-pdf@^7.7.1",+ "npm:react-use-measure@^2.1.1",+ "npm:react@^18.3.1",+ "npm:recharts@^2.15.0",+ "npm:rehype-raw@^7.0.0",+ "npm:rehype-sanitize@^6.0.0",+ "npm:remark-gfm@^4.0.0",+ "npm:remix-flat-routes@^0.8.5",+ "npm:[email protected]",+ "npm:tailwind-merge@^2.2.1",+ "npm:tailwind-scrollbar-hide@^1.1.7",+ "npm:tailwind-scrollbar@^2.0.1",+ "npm:tailwindcss-animate@^1.0.7",+ "npm:[email protected]",+ "npm:typescript@^5.2.2",+ "npm:use-stick-to-bottom@^1.1.1",+ "npm:vite-tsconfig-paths@^4.3.2",+ "npm:vite@^5.3.3",+ "npm:[email protected]",+ "npm:zod-to-json-schema@^3.24.6",+ "npm:zod@^3.25.76",+ "npm:zustand@^5.0.8"+ ]+ }+ },+ "apps/mes": {+ "packageJson": {+ "dependencies": [+ "npm:@carbon/auth",+ "npm:@carbon/database",+ "npm:@carbon/documents",+ "npm:@carbon/form",+ "npm:@carbon/kv",+ "npm:@carbon/lib",+ "npm:@carbon/logger",+ "npm:@carbon/react",+ "npm:@carbon/remix",+ "npm:@carbon/tailwind",+ "npm:@carbon/tsconfig",+ "npm:@carbon/utils",+ "npm:@dnd-kit/core@^6.1.0",+ "npm:@dnd-kit/sortable@^8.0.0",+ "npm:@internationalized/date@^3.5.2",+ "npm:@react-aria/i18n@^3.11.0",+ "npm:@remix-run/dev@~2.16.7",+ "npm:@remix-run/eslint-config@~2.16.7",+ "npm:@remix-run/react@~2.16.7",+ "npm:@remix-run/serve@~2.16.7",+ "npm:@supabase/[email protected]",+ "npm:@supabase/supabase-js@^2.40.0",+ "npm:@tailwindcss/container-queries@^0.1.1",+ "npm:@tailwindcss/forms@^0.5.7",+ "npm:@tailwindcss/line-clamp@^0.4.4",+ "npm:@tailwindcss/typography@^0.5.10",+ "npm:@types/react-dom@^18.2.24",+ "npm:@types/react@^18.2.74",+ "npm:@upstash/ratelimit@^2.0.5",+ "npm:@vercel/analytics@^1.2.2",+ "npm:@vercel/[email protected]",+ "npm:[email protected]",+ "npm:[email protected]",+ "npm:[email protected]",+ "npm:framer-motion@^11.1.7",+ "npm:[email protected]",+ "npm:[email protected]",+ "npm:nodemon@^3.0.1",+ "npm:non.geist@~1.0.3",+ "npm:npm-run-all@^4.1.5",+ "npm:postcss@^8.4.33",+ "npm:react-dom@^18.3.1",+ "npm:react-dropzone@^14.2.3",+ "npm:react-hotkeys-hook@~4.5.0",+ "npm:react-icons@^5.4.0",+ "npm:react-router-dom@^6.23.1",+ "npm:react@^18.3.1",+ "npm:tailwind-merge@^2.2.1",+ "npm:tailwind-scrollbar-hide@^1.1.7",+ "npm:tailwind-scrollbar@^2.0.1",+ "npm:tailwindcss-animate@^1.0.7",+ "npm:[email protected]",+ "npm:typescript@^5.2.2",+ "npm:vite-tsconfig-paths@^4.3.2",+ "npm:vite@^5.3.3",+ "npm:[email protected]",+ "npm:[email protected]",+ "npm:zod@^3.25.76"+ ]+ }+ },+ "apps/starter": {+ "packageJson": {+ "dependencies": [+ "npm:@carbon/auth",+ "npm:@carbon/database",+ "npm:@carbon/documents",+ "npm:@carbon/form",+ "npm:@carbon/kv",+ "npm:@carbon/logger",+ "npm:@carbon/react",+ "npm:@carbon/tailwind",+ "npm:@carbon/tsconfig",+ "npm:@carbon/utils",+ "npm:@react-aria/i18n@^3.11.0",+ "npm:@remix-run/dev@~2.16.7",+ "npm:@remix-run/eslint-config@~2.16.7",+ "npm:@remix-run/react@~2.16.7",+ "npm:@remix-run/serve@~2.16.7",+ "npm:@supabase/[email protected]",+ "npm:@supabase/supabase-js@^2.40.0",+ "npm:@tailwindcss/container-queries@^0.1.1",+ "npm:@tailwindcss/forms@^0.5.7",+ "npm:@tailwindcss/line-clamp@^0.4.4",+ "npm:@tailwindcss/typography@^0.5.10",+ "npm:@types/react-dom@^18.2.24",+ "npm:@types/react@^18.2.74",+ "npm:@upstash/ratelimit@^2.0.5",+ "npm:@vercel/analytics@^1.2.2",+ "npm:@vercel/[email protected]",+ "npm:[email protected]",+ "npm:[email protected]",+ "npm:framer-motion@^11.1.7",+ "npm:[email protected]",+ "npm:nodemon@^3.0.1",+ "npm:non.geist@~1.0.3",+ "npm:npm-run-all@^4.1.5",+ "npm:postcss@^8.4.33",+ "npm:react-dom@^18.3.1",+ "npm:react-dropzone@^14.2.3",+ "npm:react-hotkeys-hook@~4.5.0",+ "npm:react-icons@^5.4.0",+ "npm:react@^18.3.1",+ "npm:tailwind-merge@^2.2.1",+ "npm:tailwind-scrollbar-hide@^1.1.7",+ "npm:tailwind-scrollbar@^2.0.1",+ "npm:tailwindcss-animate@^1.0.7",+ "npm:[email protected]",+ "npm:typescript@^5.2.2",+ "npm:vite-tsconfig-paths@^4.3.2",+ "npm:vite@^5.3.3",+ "npm:[email protected]",+ "npm:[email protected]",+ "npm:zod@^3.25.76"+ ]+ }+ },+ "ci": {+ "packageJson": {+ "dependencies": [+ "npm:@supabase/[email protected]",+ "npm:[email protected]"+ ]+ }+ },+ "examples/quote-configurator": {+ "packageJson": {+ "dependencies": [+ "npm:@carbon/form",+ "npm:@carbon/react",+ "npm:@carbon/utils",+ "npm:@remix-run/dev@~2.16.7",+ "npm:@remix-run/eslint-config@~2.16.7",+ "npm:@remix-run/react@~2.16.7",+ "npm:@remix-run/serve@~2.16.7",+ "npm:@supabase/[email protected]",+ "npm:@supabase/supabase-js@^2.40.0",+ "npm:@types/react-dom@^18.3.1",+ "npm:@types/react@^18.3.1",+ "npm:@vercel/remix@~2.16.7",+ "npm:[email protected]",+ "npm:[email protected]",+ "npm:nodemon@^3.0.1",+ "npm:non.geist@~1.0.3",+ "npm:postcss@^8.4.33",+ "npm:react-dom@^18.3.1",+ "npm:react-dropzone@^14.2.3",+ "npm:react-icons@^5.4.0",+ "npm:react@^18.3.1",+ "npm:[email protected]",+ "npm:typescript@^5.2.2",+ "npm:vite-tsconfig-paths@^4.3.2",+ "npm:vite@^5.3.3",+ "npm:[email protected]",+ "npm:zod@^3.25.76"+ ]+ }+ },+ "examples/upload-3d-model": {+ "packageJson": {+ "dependencies": [+ "npm:@carbon/react",+ "npm:@carbon/utils",+ "npm:@remix-run/dev@~2.16.7",+ "npm:@remix-run/eslint-config@~2.16.7",+ "npm:@remix-run/react@~2.16.7",+ "npm:@remix-run/serve@~2.16.7",+ "npm:@supabase/[email protected]",+ "npm:@supabase/supabase-js@^2.40.0",+ "npm:@types/react-dom@^18.3.1",+ "npm:@types/react@^18.3.1",+ "npm:@vercel/remix@~2.16.7",+ "npm:[email protected]",+ "npm:[email protected]",+ "npm:nodemon@^3.0.1",+ "npm:non.geist@~1.0.3",+ "npm:postcss@^8.4.33",+ "npm:react-dom@^18.3.1",+ "npm:react-dropzone@^14.2.3",+ "npm:react-icons@^5.4.0",+ "npm:react@^18.3.1",+ "npm:[email protected]",+ "npm:typescript@^5.2.2",+ "npm:vite-tsconfig-paths@^4.3.2",+ "npm:vite@^5.3.3"+ ]+ }+ },+ "packages/auth": {+ "packageJson": {+ "dependencies": [+ "npm:@carbon/tsconfig",+ "npm:@carbon/utils",+ "npm:@types/jest@^26.0.22",+ "npm:@types/react@^18.2.74",+ "npm:eslint-config-carbon",+ "npm:eslint@^8.23.1",+ "npm:jest@^26.6.3",+ "npm:tsup@^6.5.0",+ "npm:typescript@^5.2.2"+ ]+ }+ },+ "packages/database": {+ "packageJson": {+ "dependencies": [+ "npm:@carbon/tsconfig",+ "npm:@supabase/supabase-js@^2.40.0",+ "npm:@types/node@^20.12.5",+ "npm:@types/uuid@^8.3.4",+ "npm:[email protected]",+ "npm:eslint-config-carbon",+ "npm:eslint@^8.23.1",+ "npm:npm-run-all@^4.1.5",+ "npm:rimraf@^5.0.5",+ "npm:[email protected]",+ "npm:tsup@^6.5.0",+ "npm:tsx@^4.13.2",+ "npm:typescript@^5.2.2",+ "npm:[email protected]"+ ]+ }+ },+ "packages/documents": {+ "packageJson": {+ "dependencies": [+ "npm:@bwip-js/node@^4.5.1",+ "npm:@carbon/auth",+ "npm:@carbon/database",+ "npm:@carbon/jest",+ "npm:@carbon/tsconfig",+ "npm:@hookform/resolvers@^3.3.4",+ "npm:@internationalized/date@^3.5.2",+ "npm:@react-email/[email protected]",+ "npm:@react-pdf/renderer@^3.1.14",+ "npm:@testing-library/dom@^8.11.1",+ "npm:@types/dompurify@^2.4.0",+ "npm:@types/jest@^26.0.22",+ "npm:@types/react@^18.2.74",+ "npm:eslint-config-carbon",+ "npm:eslint@^8.23.1",+ "npm:jest@^26.6.3",+ "npm:react-icons@^5.4.0",+ "npm:react-pdf-tailwind@~2.3.0",+ "npm:react@^18.3.1",+ "npm:tsup@^6.5.0",+ "npm:typescript@^5.2.2"+ ]+ }+ },+ "packages/ee": {+ "packageJson": {+ "dependencies": [+ "npm:@ai-sdk/openai@^2.0.60",+ "npm:@carbon/auth",+ "npm:@carbon/react",+ "npm:@carbon/tsconfig",+ "npm:@carbon/utils",+ "npm:@slack/bolt@~4.4.0",+ "npm:@slack/oauth@~3.0.3",+ "npm:@slack/web-api@~7.10.0",+ "npm:@trigger.dev/[email protected]",+ "npm:ai@^5.0.88",+ "npm:typescript@^5.2.2",+ "npm:zod@^3.25.76"+ ]+ }+ },+ "packages/eslint-config-carbon": {+ "packageJson": {+ "dependencies": [+ "npm:@babel/[email protected]",+ "npm:@babel/[email protected]",+ "npm:@typescript-eslint/eslint-plugin@^5.38.0",+ "npm:@typescript-eslint/parser@^5.38.0",+ "npm:eslint-config-prettier@^8.5.0",+ "npm:[email protected]",+ "npm:eslint-import-resolver-typescript@^3.5.1"+ ]+ }+ },+ "packages/form": {+ "packageJson": {+ "dependencies": [+ "npm:@types/lodash.get@^4.4.7",+ "npm:@types/react@^18.2.74",+ "npm:fetch-blob@^3.1.3",+ "npm:immer@^9.0.12",+ "npm:lodash.get@^4.4.2",+ "npm:[email protected]",+ "npm:react-phone-number-input@^3.3.9",+ "npm:remeda@^1.2.0",+ "npm:tiny-invariant@^1.2.0",+ "npm:ts-toolbelt@^9.6.0",+ "npm:tsconfig",+ "npm:typescript@^5.2.2",+ "npm:zustand@^5.0.8"+ ]+ }+ },+ "packages/jest": {+ "packageJson": {+ "dependencies": [+ "npm:eslint-config-carbon",+ "npm:ts-jest@^26.5.0"+ ]+ }+ },+ "packages/jobs": {+ "packageJson": {+ "dependencies": [+ "npm:@ai-sdk/openai@^2.0.60",+ "npm:@carbon/auth",+ "npm:@carbon/database",+ "npm:@carbon/documents",+ "npm:@carbon/ee",+ "npm:@carbon/lib",+ "npm:@carbon/notifications",+ "npm:@carbon/tsconfig",+ "npm:@internationalized/date@^3.5.2",+ "npm:@novu/node@^2.0.1",+ "npm:@react-email/[email protected]",+ "npm:@slack/web-api@~7.10.0",+ "npm:@supabase/[email protected]",+ "npm:@supabase/supabase-js@^2.40.0",+ "npm:@trigger.dev/[email protected]",+ "npm:ai@^5.0.88",+ "npm:[email protected]",+ "npm:resend@^3.1.0",+ "npm:typescript@^5.2.2",+ "npm:zod@^3.25.76"+ ]+ }+ },+ "packages/kv": {+ "packageJson": {+ "dependencies": [+ "npm:@carbon/logger",+ "npm:@carbon/tsconfig",+ "npm:@types/node@^20.12.5",+ "npm:@upstash/[email protected]",+ "npm:[email protected]",+ "npm:eslint-config-carbon",+ "npm:eslint@^8.23.1",+ "npm:rimraf@^5.0.5",+ "npm:tsup@^6.5.0",+ "npm:tsx@^4.13.2",+ "npm:typescript@^5.2.2"+ ]+ }+ },+ "packages/lib": {+ "packageJson": {+ "dependencies": [+ "npm:@carbon/auth",+ "npm:@carbon/database",+ "npm:@carbon/kv",+ "npm:@carbon/logger",+ "npm:@carbon/tsconfig",+ "npm:@supabase/supabase-js@^2.40.0",+ "npm:@trigger.dev/[email protected]",+ "npm:@types/node@^20.12.5",+ "npm:[email protected]",+ "npm:eslint-config-carbon",+ "npm:eslint@^8.23.1",+ "npm:resend@^3.1.0",+ "npm:rimraf@^5.0.5",+ "npm:tsup@^6.5.0",+ "npm:tsx@^4.13.2",+ "npm:typescript@^5.2.2",+ "npm:zod@^3.25.76"+ ]+ }+ },+ "packages/logger": {+ "packageJson": {+ "dependencies": [+ "npm:@carbon/jest",+ "npm:@types/jest@^26.0.22",+ "npm:eslint-config-carbon",+ "npm:eslint@^8.23.1",+ "npm:jest@^26.6.3",+ "npm:tsup@^6.5.0",+ "npm:typescript@^5.2.2"+ ]+ }+ },+ "packages/notifications": {+ "packageJson": {+ "dependencies": [+ "npm:@carbon/tsconfig",+ "npm:@novu/node@^2.0.1",+ "npm:eslint-config-carbon",+ "npm:[email protected]",+ "npm:typescript@^5.2.2"+ ]+ }+ },+ "packages/react": {+ "packageJson": {+ "dependencies": [+ "npm:@carbon/jest",+ "npm:@carbon/tailwind",+ "npm:@carbon/tiptap",+ "npm:@carbon/tsconfig",+ "npm:@carbon/utils",+ "npm:@radix-ui/react-accordion@^1.2.0",+ "npm:@radix-ui/react-avatar@^1.0.3",+ "npm:@radix-ui/react-checkbox@^1.0.4",+ "npm:@radix-ui/[email protected]",+ "npm:@radix-ui/react-context-menu@^2.1.4",+ "npm:@radix-ui/react-dialog@^1.0.4",+ "npm:@radix-ui/react-dropdown-menu@^2.0.5",+ "npm:@radix-ui/react-hover-card@^1.0.6",+ "npm:@radix-ui/react-label@^2.0.2",+ "npm:@radix-ui/react-popover@^1.0.6",+ "npm:@radix-ui/react-progress@^1.0.3",+ "npm:@radix-ui/react-radio-group@^1.1.3",+ "npm:@radix-ui/react-scroll-area@^1.0.5",+ "npm:@radix-ui/react-select@^2.0.0",+ "npm:@radix-ui/react-separator@^1.0.3",+ "npm:@radix-ui/react-slider@^1.1.2",+ "npm:@radix-ui/react-slot@^1.0.2",+ "npm:@radix-ui/react-switch@^1.0.3",+ "npm:@radix-ui/react-tabs@^1.0.4",+ "npm:@radix-ui/react-toast@^1.1.4",+ "npm:@radix-ui/react-toggle-group@^1.0.4",+ "npm:@radix-ui/react-toggle@^1.0.3",+ "npm:@radix-ui/react-tooltip@^1.0.6",+ "npm:@react-aria/button@^3.8.0",+ "npm:@react-aria/calendar@^3.4.0",+ "npm:@react-aria/datepicker@^3.9.0",+ "npm:@react-stately/calendar@^3.3.0",+ "npm:@react-stately/datepicker@^3.9.0",+ "npm:@react-types/button@^3.7.3",+ "npm:@react-types/calendar@^3.3.0",+ "npm:@react-types/datepicker@^3.4.0",+ "npm:@tailwindcss/container-queries@^0.1.1",+ "npm:@tailwindcss/forms@^0.5.7",+ "npm:@tailwindcss/line-clamp@^0.4.4",+ "npm:@tailwindcss/typography@^0.5.10",+ "npm:@tanstack/react-table@^8.9.3",+ "npm:@tanstack/react-virtual@^3.5.0",+ "npm:@testing-library/dom@^8.11.1",+ "npm:@tiptap/extension-color@^2.0.4",+ "npm:@tiptap/extension-list-item@^2.0.4",+ "npm:@tiptap/extension-table-cell@^2.0.3",+ "npm:@tiptap/extension-table-header@^2.4.0",+ "npm:@tiptap/extension-table-row@^2.0.3",+ "npm:@tiptap/extension-table@^2.0.4",+ "npm:@tiptap/extension-text-style@^2.0.3",+ "npm:@tiptap/extension-youtube@^2.0.3",+ "npm:@tiptap/[email protected]",+ "npm:@tiptap/react@^2.0.4",+ "npm:@tiptap/starter-kit@^2.0.4",+ "npm:@types/dompurify@^2.4.0",+ "npm:@types/[email protected]",+ "npm:@types/jest@^26.0.22",+ "npm:@types/react-dom@^18.2.24",+ "npm:@types/react-window@^1.8.5",+ "npm:@types/react@^18.2.74",+ "npm:@visx/curve@^3.3.0",+ "npm:@visx/responsive@^2.10.0",+ "npm:@visx/scale@^3.3.0",+ "npm:@visx/shape@^2.12.2",+ "npm:@visx/text@^3.3.0",+ "npm:[email protected]",+ "npm:class-variance-authority@^0.7.0",+ "npm:clsx@^2.1.0",+ "npm:cmdk@^0.2.0",+ "npm:[email protected]",+ "npm:embla-carousel-react@~8.5.2",+ "npm:eslint-config-carbon",+ "npm:eslint@^8.23.1",+ "npm:input-otp@^1.4.2",+ "npm:intl-parse-accept-language@^1.0.0",+ "npm:is-hotkey@^0.2.0",+ "npm:jest@^26.6.3",+ "npm:[email protected]",+ "npm:prism-react-renderer@^2.3.1",+ "npm:[email protected]",+ "npm:react-colorful@^5.6.1",+ "npm:react-hotkeys-hook@~4.5.0",+ "npm:react-resizable-panels@^2.1.3",+ "npm:react@^18.3.1",+ "npm:[email protected]",+ "npm:tailwind-merge@^2.2.1",+ "npm:tailwindcss-animate@^1.0.7",+ "npm:tsup@^6.5.0",+ "npm:typescript@^5.2.2"+ ]+ }+ },+ "packages/remix": {+ "packageJson": {+ "dependencies": [+ "npm:@carbon/react",+ "npm:@carbon/tsconfig",+ "npm:@carbon/utils",+ "npm:@remix-run/react@^2.16.7",+ "npm:@types/jest@^26.0.22",+ "npm:@types/react@^18.2.74",+ "npm:eslint-config-carbon",+ "npm:eslint@^8.23.1",+ "npm:jest@^26.6.3",+ "npm:nprogress@^0.2.0",+ "npm:react-icons@^5.4.0",+ "npm:react@^18.3.1",+ "npm:tsup@^6.5.0",+ "npm:typescript@^5.2.2"+ ]+ }+ },+ "packages/stripe": {+ "packageJson": {+ "dependencies": [+ "npm:@carbon/auth",+ "npm:@carbon/database",+ "npm:@carbon/jobs",+ "npm:@carbon/kv",+ "npm:@carbon/lib",+ "npm:@carbon/logger",+ "npm:@carbon/tsconfig",+ "npm:@supabase/supabase-js@^2.40.0",+ "npm:@trigger.dev/[email protected]",+ "npm:@types/node@^20.12.5",+ "npm:[email protected]",+ "npm:eslint-config-carbon",+ "npm:eslint@^8.23.1",+ "npm:rimraf@^5.0.5",+ "npm:stripe@^18.3.0",+ "npm:tsup@^6.5.0",+ "npm:tsx@^4.13.2",+ "npm:typescript@^5.2.2",+ "npm:zod@^3.25.76"+ ]+ }+ },+ "packages/tiptap": {+ "packageJson": {+ "dependencies": [+ "npm:@carbon/jest",+ "npm:@carbon/tailwind",+ "npm:@carbon/tsconfig",+ "npm:@carbon/utils",+ "npm:@radix-ui/react-slot@^1.1.1",+ "npm:@testing-library/dom@^8.11.1",+ "npm:@tiptap/core@^2.11.2",+ "npm:@tiptap/extension-character-count@^2.11.2",+ "npm:@tiptap/extension-code-block-lowlight@^2.11.2",+ "npm:@tiptap/extension-color@^2.11.2",+ "npm:@tiptap/extension-highlight@^2.11.2",+ "npm:@tiptap/extension-horizontal-rule@^2.11.2",+ "npm:@tiptap/extension-image@^2.11.2",+ "npm:@tiptap/extension-link@^2.11.2",+ "npm:@tiptap/extension-placeholder@^2.11.2",+ "npm:@tiptap/extension-task-item@^2.11.2",+ "npm:@tiptap/extension-task-list@^2.11.2",+ "npm:@tiptap/extension-text-style@^2.11.2",+ "npm:@tiptap/extension-underline@^2.11.2",+ "npm:@tiptap/extension-youtube@^2.11.2",+ "npm:@tiptap/pm@^2.11.2",+ "npm:@tiptap/react@^2.11.2",+ "npm:@tiptap/starter-kit@^2.11.2",+ "npm:@tiptap/suggestion@^2.11.2",+ "npm:@types/dompurify@^2.4.0",+ "npm:@types/[email protected]",+ "npm:@types/jest@^26.0.22",+ "npm:@types/node@^22.10.6",+ "npm:@types/react-dom@^18.2.24",+ "npm:@types/react-window@^1.8.5",+ "npm:@types/react@^18.2.74",+ "npm:cmdk@^1.0.4",+ "npm:eslint-config-carbon",+ "npm:eslint@^8.23.1",+ "npm:jest@^26.6.3",+ "npm:jotai@^2.11.0",+ "npm:react-markdown@^9.0.3",+ "npm:react-moveable@^0.56.0",+ "npm:react@^18.3.1",+ "npm:tippy.js@^6.3.7",+ "npm:tiptap-extension-global-drag-handle@^0.1.16",+ "npm:tiptap-markdown@^0.8.10",+ "npm:tsup@^6.5.0",+ "npm:tunnel-rat@^0.1.2",+ "npm:typescript@^5.2.2"+ ]+ }+ },+ "packages/utils": {+ "packageJson": {+ "dependencies": [+ "npm:@carbon/jest",+ "npm:@carbon/tsconfig",+ "npm:@types/jest@^26.0.22",+ "npm:@types/[email protected]",+ "npm:@types/react-dom@^18.2.24",+ "npm:@types/react@^18.2.74",+ "npm:eslint-config-carbon",+ "npm:eslint@^8.23.1",+ "npm:humanize-duration@^3.32.0",+ "npm:jest@^26.6.3",+ "npm:lodash.template@^4.5.0",+ "npm:react@^18.3.1",+ "npm:tsup@^6.5.0",+ "npm:typescript@^5.2.2",+ "npm:zod@^3.25.76"+ ]+ }+ }+ }+ }+}diff --git a/packages/database/supabase/functions/lib/scheduling/assembly-handler.ts b/packages/database/supabase/functions/lib/scheduling/assembly-handler.tsnew file mode 100644index 0000000000..bea2117f37--- /dev/null+++ b/packages/database/supabase/functions/lib/scheduling/assembly-handler.ts@@ -0,0 +1,219 @@+import type SupabaseClient from "https://esm.sh/v135/@supabase/[email protected]/dist/module/SupabaseClient.d.ts";+import type { Kysely } from "https://esm.sh/[email protected]";+import type { Database } from "../types.ts";+import type { DB } from "../database.ts";+import { getJobMethodTree, type JobMethodTreeItem } from "../methods.ts";+import type { AssemblyNode, BaseOperation } from "./types.ts";++/**+ * Assembly Handler+ * Manages assembly hierarchy and transforms job method trees into scheduling structures+ */+export class AssemblyHandler {+ private client: SupabaseClient<Database>;+ private db: Kysely<DB>;+ private companyId: string;++ constructor(+ client: SupabaseClient<Database>,+ db: Kysely<DB>,+ companyId: string+ ) {+ this.client = client;+ this.db = db;+ this.companyId = companyId;+ }++ /**+ * Build assembly tree for a job+ */+ async buildAssemblyTree(jobId: string): Promise<AssemblyNode | null> {+ // Get the root job make method+ const rootMethod = await this.db+ .selectFrom("jobMakeMethod")+ .select(["id", "itemId"])+ .where("jobId", "=", jobId)+ .where("parentMaterialId", "is", null)+ .executeTakeFirst();++ if (!rootMethod?.id) {+ return null;+ }++ // Get the job method tree using the existing function+ const treeResult = await getJobMethodTree(this.client, rootMethod.id);+ if (treeResult.error || !treeResult.data || treeResult.data.length === 0) {+ return null;+ }++ // Get all operations for this job+ const operations = await this.db+ .selectFrom("jobOperation")+ .selectAll()+ .where("jobId", "=", jobId)+ .where("status", "not in", ["Done", "Canceled"])+ .orderBy("order")+ .execute();++ // Group operations by jobMakeMethodId+ const operationsByMethod = new Map<string, BaseOperation[]>();+ for (const op of operations) {+ if (op.jobMakeMethodId) {+ if (!operationsByMethod.has(op.jobMakeMethodId)) {+ operationsByMethod.set(op.jobMakeMethodId, []);+ }+ operationsByMethod.get(op.jobMakeMethodId)!.push(op as BaseOperation);+ }+ }++ // Transform the tree to AssemblyNode structure+ const rootItem = treeResult.data[0];+ return this.transformTreeItem(rootItem, operationsByMethod);+ }++ /**+ * Transform a JobMethodTreeItem to AssemblyNode+ */+ private transformTreeItem(+ item: JobMethodTreeItem,+ operationsByMethod: Map<string, BaseOperation[]>+ ): AssemblyNode {+ const jobMakeMethodId = item.data?.jobMaterialMakeMethodId || item.id;++ return {+ id: item.id,+ jobMakeMethodId,+ parentMaterialId: item.data?.parentMaterialId ?? null,+ itemId: item.data?.itemId ?? null,+ operations: operationsByMethod.get(jobMakeMethodId) ?? [],+ children: item.children.map((child) =>+ this.transformTreeItem(child, operationsByMethod)+ ),+ };+ }++ /**+ * Get assembly nodes in post-order traversal (children before parents)+ * This is the order in which assemblies should be scheduled for backward scheduling+ */+ getPostOrderTraversal(root: AssemblyNode): AssemblyNode[] {+ const result: AssemblyNode[] = [];++ function traverse(node: AssemblyNode) {+ // Process children first+ for (const child of node.children) {+ traverse(child);+ }+ // Then process current node+ result.push(node);+ }++ traverse(root);+ return result;+ }++ /**+ * Get assembly nodes in pre-order traversal (parents before children)+ * This is the order in which assemblies should be scheduled for forward scheduling+ */+ getPreOrderTraversal(root: AssemblyNode): AssemblyNode[] {+ const result: AssemblyNode[] = [];++ function traverse(node: AssemblyNode) {+ // Process current node first+ result.push(node);+ // Then process children+ for (const child of node.children) {+ traverse(child);+ }+ }++ traverse(root);+ return result;+ }++ /**+ * Get all operations from the assembly tree in scheduling order+ * For backward scheduling: children operations come first+ */+ getAllOperationsForBackwardScheduling(root: AssemblyNode): BaseOperation[] {+ const operations: BaseOperation[] = [];+ const traversal = this.getPostOrderTraversal(root);++ for (const node of traversal) {+ operations.push(...node.operations);+ }++ return operations;+ }++ /**+ * Get all operations from the assembly tree in scheduling order+ * For forward scheduling: parent operations come first+ */+ getAllOperationsForForwardScheduling(root: AssemblyNode): BaseOperation[] {+ const operations: BaseOperation[] = [];+ const traversal = this.getPreOrderTraversal(root);++ for (const node of traversal) {+ operations.push(...node.operations);+ }++ return operations;+ }++ /**+ * Calculate the maximum depth of the assembly tree+ */+ getAssemblyDepth(root: AssemblyNode): number {+ function getDepth(node: AssemblyNode): number {+ if (node.children.length === 0) {+ return 1;+ }+ return 1 + Math.max(...node.children.map(getDepth));+ }++ return getDepth(root);+ }++ /**+ * Get all jobMakeMethodIds in the assembly tree+ */+ getAllJobMakeMethodIds(root: AssemblyNode): string[] {+ const ids: string[] = [];++ function traverse(node: AssemblyNode) {+ ids.push(node.jobMakeMethodId);+ for (const child of node.children) {+ traverse(child);+ }+ }++ traverse(root);+ return ids;+ }+}++/**+ * Build make method dependencies for dependency creation+ * Returns tuples of [childMethodId, parentMethodId]+ */+export function buildMakeMethodDependencies(+ root: AssemblyNode+): { id: string; parentId: string | null }[] {+ const dependencies: { id: string; parentId: string | null }[] = [];++ function traverse(node: AssemblyNode, parentMethodId: string | null) {+ dependencies.push({+ id: node.jobMakeMethodId,+ parentId: parentMethodId,+ });++ for (const child of node.children) {+ traverse(child, node.jobMakeMethodId);+ }+ }++ traverse(root, null);+ return dependencies;+}diff --git a/packages/database/supabase/functions/lib/scheduling/date-calculator.ts b/packages/database/supabase/functions/lib/scheduling/date-calculator.tsnew file mode 100644index 0000000000..8687f3a372--- /dev/null+++ b/packages/database/supabase/functions/lib/scheduling/date-calculator.ts@@ -0,0 +1,330 @@+import {+ calculateDurationDays,+ calculateDurationHours,+} from "./duration-calculator.ts";+import type {+ BaseOperation,+ DependencyGraph,+ ScheduledOperation,+ SchedulingDirection,+} from "./types.ts";++/**+ * Subtract business days from a date (skips weekends)+ */+function subtractBusinessDays(date: Date, days: number): Date {+ const result = new Date(date);+ let remainingDays = days;++ while (remainingDays > 0) {+ result.setDate(result.getDate() - 1);+ // Skip weekends (0 = Sunday, 6 = Saturday)+ const dayOfWeek = result.getDay();+ if (dayOfWeek !== 0 && dayOfWeek !== 6) {+ remainingDays--;+ }+ }++ return result;+}++/**+ * Add business days to a date (skips weekends)+ */+function addBusinessDays(date: Date, days: number): Date {+ const result = new Date(date);+ let remainingDays = days;++ while (remainingDays > 0) {+ result.setDate(result.getDate() + 1);+ // Skip weekends (0 = Sunday, 6 = Saturday)+ const dayOfWeek = result.getDay();+ if (dayOfWeek !== 0 && dayOfWeek !== 6) {+ remainingDays--;+ }+ }++ return result;+}++/**+ * Format date to ISO date string (YYYY-MM-DD)+ */+function formatDate(date: Date): string {+ return date.toISOString().split("T")[0];+}++/**+ * Get today's date as ISO string+ */+function getTodayString(): string {+ return formatDate(new Date());+}++/**+ * Interface for scheduling strategy+ */+export interface SchedulingStrategy {+ calculateDates(+ operations: BaseOperation[],+ operationMap: Map<string, BaseOperation>,+ graph: DependencyGraph,+ anchorDate: string | null+ ): Map<string, ScheduledOperation>;+}++/**+ * Backward scheduling strategy - schedules from due date backward+ */+export class BackwardSchedulingStrategy implements SchedulingStrategy {+ calculateDates(+ _operations: BaseOperation[],+ operationMap: Map<string, BaseOperation>,+ graph: DependencyGraph,+ jobDueDate: string | null+ ): Map<string, ScheduledOperation> {+ const scheduled = new Map<string, ScheduledOperation>();+ const today = getTodayString();+ const finalDueDate = jobDueDate || today;++ // Topological sort in reverse order (leaf nodes first)+ const sortedIds = graph.topologicalSort("reverse");++ for (const opId of sortedIds) {+ const op = operationMap.get(opId);+ if (!op || !op.id) continue;++ const durationDays = calculateDurationDays(op);+ const durationHours = calculateDurationHours(op);++ // Calculate due date+ let dueDate: string;+ const dependents = graph.getDependents(opId);++ if (dependents.length === 0) {+ // Leaf operation: use job due date+ dueDate = finalDueDate;+ } else {+ // Has dependents: must finish before earliest dependent starts minus lead time+ const dependentConstraints = dependents+ .map((depId) => {+ const scheduledOp = scheduled.get(depId);+ const baseOp = operationMap.get(depId);+ if (!scheduledOp?.startDate) return null;++ // Subtract lead time from dependent's start date+ // Lead time represents how early the subassembly needs to be ready+ // before the parent operation starts+ const leadTimeDays = baseOp?.operationLeadTime ?? 0;+ if (leadTimeDays > 0) {+ const startDate = new Date(scheduledOp.startDate);+ return subtractBusinessDays(startDate, leadTimeDays);+ }+ return new Date(scheduledOp.startDate);+ })+ .filter((date): date is Date => date !== null);++ if (dependentConstraints.length === 0) {+ dueDate = finalDueDate;+ } else {+ // Use the earliest constraint date (start date minus lead time)+ const minDate = new Date(+ Math.min(...dependentConstraints.map((d) => d.getTime()))+ );+ dueDate = formatDate(minDate);+ }+ }++ // Handle "With Previous" operations - same dates as predecessor+ if (op.operationOrder === "With Previous") {+ const dependencies = graph.getDependencies(opId);+ if (dependencies.length > 0) {+ const predecessorId = dependencies[0];+ const predecessor = scheduled.get(predecessorId);+ if (predecessor) {+ const scheduledOp: ScheduledOperation = {+ ...op,+ id: op.id,+ startDate: predecessor.startDate,+ dueDate: predecessor.dueDate,+ priority: op.priority ?? 99,+ durationHours,+ durationDays,+ hasConflict: predecessor.hasConflict,+ conflictReason: predecessor.conflictReason,+ };+ scheduled.set(opId, scheduledOp);+ continue;+ }+ }+ }++ // Calculate start date by subtracting duration from due date+ const dueDateObj = new Date(dueDate);+ const startDateObj = subtractBusinessDays(dueDateObj, durationDays);+ const startDate = formatDate(startDateObj);++ // Check for conflicts (start date in the past)+ const hasConflict = startDate < today;+ const conflictReason = hasConflict+ ? `Operation must start on ${startDate} but current date is ${today}`+ : null;++ const scheduledOp: ScheduledOperation = {+ ...op,+ id: op.id,+ startDate,+ dueDate,+ priority: op.priority ?? 99,+ durationHours,+ durationDays,+ hasConflict,+ conflictReason,+ };++ scheduled.set(opId, scheduledOp);+ }++ return scheduled;+ }+}++/**+ * Forward scheduling strategy - schedules from start date forward+ * (Placeholder for future implementation)+ */+export class ForwardSchedulingStrategy implements SchedulingStrategy {+ calculateDates(+ _operations: BaseOperation[],+ operationMap: Map<string, BaseOperation>,+ graph: DependencyGraph,+ jobStartDate: string | null+ ): Map<string, ScheduledOperation> {+ const scheduled = new Map<string, ScheduledOperation>();+ const today = getTodayString();+ const startDate = jobStartDate || today;++ // Topological sort in forward order (root nodes first)+ const sortedIds = graph.topologicalSort("forward");++ for (const opId of sortedIds) {+ const op = operationMap.get(opId);+ if (!op || !op.id) continue;++ const durationDays = calculateDurationDays(op);+ const durationHours = calculateDurationHours(op);++ // Calculate start date+ let opStartDate: string;+ const dependencies = graph.getDependencies(opId);++ if (dependencies.length === 0) {+ // Root operation: use job start date+ opStartDate = startDate;+ } else {+ // Has dependencies: must start after latest dependency ends plus lead time+ const dependencyDueDates = dependencies+ .map((depId) => scheduled.get(depId)?.dueDate)+ .filter(+ (date): date is string => date !== null && date !== undefined+ );++ if (dependencyDueDates.length === 0) {+ opStartDate = startDate;+ } else {+ // Use the latest dependency due date+ const maxDate = new Date(+ Math.max(...dependencyDueDates.map((d) => new Date(d).getTime()))+ );+ // Add lead time of current operation (time needed after dependencies complete)+ const leadTimeDays = op.operationLeadTime ?? 0;+ if (leadTimeDays > 0) {+ opStartDate = formatDate(addBusinessDays(maxDate, leadTimeDays));+ } else {+ opStartDate = formatDate(maxDate);+ }+ }+ }++ // Handle "With Previous" operations - same dates as predecessor+ if (op.operationOrder === "With Previous" && dependencies.length > 0) {+ const predecessorId = dependencies[0];+ const predecessor = scheduled.get(predecessorId);+ if (predecessor) {+ const scheduledOp: ScheduledOperation = {+ ...op,+ id: op.id,+ startDate: predecessor.startDate,+ dueDate: predecessor.dueDate,+ priority: op.priority ?? 99,+ durationHours,+ durationDays,+ hasConflict: false,+ conflictReason: null,+ };+ scheduled.set(opId, scheduledOp);+ continue;+ }+ }++ // Calculate due date by adding duration to start date+ const startDateObj = new Date(opStartDate);+ const dueDateObj = addBusinessDays(startDateObj, durationDays);+ const dueDate = formatDate(dueDateObj);++ const scheduledOp: ScheduledOperation = {+ ...op,+ id: op.id,+ startDate: opStartDate,+ dueDate,+ priority: op.priority ?? 1,+ durationHours,+ durationDays,+ hasConflict: false,+ conflictReason: null,+ };++ scheduled.set(opId, scheduledOp);+ }++ return scheduled;+ }+}++/**+ * Factory function to get the appropriate scheduling strategy+ */+export function getSchedulingStrategy(+ direction: SchedulingDirection+): SchedulingStrategy {+ switch (direction) {+ case "forward":+ return new ForwardSchedulingStrategy();+ case "backward":+ default:+ return new BackwardSchedulingStrategy();+ }+}++/**+ * Main date calculation function+ */+export function calculateOperationDates(+ operations: BaseOperation[],+ graph: DependencyGraph,+ anchorDate: string | null,+ direction: SchedulingDirection = "backward"+): Map<string, ScheduledOperation> {+ // Build operation map for quick lookup+ const operationMap = new Map<string, BaseOperation>();+ for (const op of operations) {+ if (op.id) {+ operationMap.set(op.id, op);+ }+ }++ const strategy = getSchedulingStrategy(direction);+ return strategy.calculateDates(operations, operationMap, graph, anchorDate);+}++export { addBusinessDays, formatDate, getTodayString, subtractBusinessDays };diff --git a/packages/database/supabase/functions/lib/scheduling/dependency-manager.ts b/packages/database/supabase/functions/lib/scheduling/dependency-manager.tsnew file mode 100644index 0000000000..1ae4d651aa--- /dev/null+++ b/packages/database/supabase/functions/lib/scheduling/dependency-manager.ts@@ -0,0 +1,256 @@+import { Database } from "../types.ts";+import type {+ BaseOperation,+ DependencyGraph,+ DependencyNode,+ JobOperationDependency,+} from "./types.ts";++/**+ * Creates and manages a dependency graph for job operations+ */+export class DependencyGraphImpl implements DependencyGraph {+ nodes: Map<string, DependencyNode> = new Map();++ constructor(+ operations: BaseOperation[] = [],+ dependencies: JobOperationDependency[] = []+ ) {+ this.initializeFromOperations(operations, dependencies);+ }++ /**+ * Initialize the graph from operations and dependencies+ */+ private initializeFromOperations(+ operations: BaseOperation[],+ dependencies: JobOperationDependency[]+ ): void {+ // Initialize all operations as nodes+ for (const op of operations) {+ if (op.id) {+ this.nodes.set(op.id, {+ operationId: op.id,+ dependsOn: [],+ requiredBy: [],+ });+ }+ }++ // Build edges from dependencies+ for (const dep of dependencies) {+ this.addDependency(dep.operationId, dep.dependsOnId);+ }+ }++ /**+ * Get operations that this operation depends on+ */+ getDependencies(operationId: string): string[] {+ return this.nodes.get(operationId)?.dependsOn || [];+ }++ /**+ * Get operations that depend on this operation+ */+ getDependents(operationId: string): string[] {+ return this.nodes.get(operationId)?.requiredBy || [];+ }++ /**+ * Add a dependency relationship+ */+ addDependency(operationId: string, dependsOnId: string): void {+ const opNode = this.nodes.get(operationId);+ const depNode = this.nodes.get(dependsOnId);++ if (opNode && !opNode.dependsOn.includes(dependsOnId)) {+ opNode.dependsOn.push(dependsOnId);+ }+ if (depNode && !depNode.requiredBy.includes(operationId)) {+ depNode.requiredBy.push(operationId);+ }+ }++ /**+ * Check if an operation has any dependencies+ */+ hasDependencies(operationId: string): boolean {+ return this.getDependencies(operationId).length > 0;+ }++ /**+ * Check if an operation has any dependents+ */+ hasDependents(operationId: string): boolean {+ return this.getDependents(operationId).length > 0;+ }++ /**+ * Perform topological sort on the operations+ * @param direction "forward" starts with operations that have no dependencies (roots)+ * "reverse" starts with operations that have no dependents (leaves)+ */+ topologicalSort(direction: "forward" | "reverse"): string[] {+ const inDegree = new Map<string, number>();+ const queue: string[] = [];+ const result: string[] = [];++ // Calculate in-degrees based on direction+ for (const [opId, node] of this.nodes) {+ const deps = direction === "forward" ? node.dependsOn : node.requiredBy;+ inDegree.set(opId, deps.length);+ if (deps.length === 0) {+ queue.push(opId);+ }+ }++ // Process queue using BFS+ while (queue.length > 0) {+ const opId = queue.shift()!;+ result.push(opId);++ const node = this.nodes.get(opId);+ if (!node) continue;++ // Get neighbors based on direction+ const neighbors =+ direction === "forward" ? node.requiredBy : node.dependsOn;++ for (const neighborId of neighbors) {+ const degree = inDegree.get(neighborId)! - 1;+ inDegree.set(neighborId, degree);+ if (degree === 0) {+ queue.push(neighborId);+ }+ }+ }++ return result;+ }++ /**+ * Get all leaf operations (operations with no dependents)+ */+ getLeafOperations(): string[] {+ const leaves: string[] = [];+ for (const [opId, node] of this.nodes) {+ if (node.requiredBy.length === 0) {+ leaves.push(opId);+ }+ }+ return leaves;+ }++ /**+ * Get all root operations (operations with no dependencies)+ */+ getRootOperations(): string[] {+ const roots: string[] = [];+ for (const [opId, node] of this.nodes) {+ if (node.dependsOn.length === 0) {+ roots.push(opId);+ }+ }+ return roots;+ }+}++/**+ * Build dependencies for operations based on their order and operationOrder field+ * This handles "With Previous" parallel operations+ */+export function buildOperationDependencies(+ operations: BaseOperation[]+): Map<string, Set<string>> {+ const dependencies = new Map<string, Set<string>>();++ // Initialize all operations+ for (const op of operations) {+ if (op.id) {+ dependencies.set(op.id, new Set<string>());+ }+ }++ // Sort operations by order+ const sorted = [...operations].sort(+ (a, b) => (a.order ?? 0) - (b.order ?? 0)+ );++ // Calculate adjusted order for "With Previous" operations+ const adjustedOrders = new Map<string, number>();+ for (let i = 0; i < sorted.length; i++) {+ const op = sorted[i];+ if (!op.id) continue;++ if (op.operationOrder === "With Previous" && i > 0) {+ // Find the first operation before this that is NOT "With Previous"+ let adjustedOrder = i;+ for (let j = i - 1; j >= 0; j--) {+ if (sorted[j].operationOrder !== "With Previous") {+ adjustedOrder = j + 1;+ break;+ }+ if (j === 0) {+ adjustedOrder = 1;+ }+ }+ adjustedOrders.set(op.id, adjustedOrder);+ } else {+ adjustedOrders.set(op.id, i + 1);+ }+ }++ // Group operations by adjusted order+ const operationsByOrder = new Map<number, string[]>();+ for (const [opId, order] of adjustedOrders) {+ if (!operationsByOrder.has(order)) {+ operationsByOrder.set(order, []);+ }+ operationsByOrder.get(order)!.push(opId);+ }++ // Create dependencies between sequential groups+ const orderKeys = [...operationsByOrder.keys()].sort((a, b) => a - b);+ for (let i = 1; i < orderKeys.length; i++) {+ const currentOrderOps = operationsByOrder.get(orderKeys[i])!;+ const previousOrderOps = operationsByOrder.get(orderKeys[i - 1])!;++ // Each operation in current group depends on all operations in previous group+ for (const opId of currentOrderOps) {+ const deps = dependencies.get(opId);+ if (deps) {+ for (const prevOpId of previousOrderOps) {+ deps.add(prevOpId);+ }+ }+ }+ }++ return dependencies;+}++/**+ * Convert dependency map to array of JobOperationDependency records+ */+export function dependenciesToRecords(+ dependencies: Map<string, Set<string>>,+ jobId: string,+ companyId: string+): Database["public"]["Tables"]["jobOperationDependency"]["Insert"][] {+ const records: Database["public"]["Tables"]["jobOperationDependency"]["Insert"][] =+ [];++ for (const [operationId, deps] of dependencies) {+ for (const dependsOnId of deps) {+ records.push({+ jobId,+ operationId,+ dependsOnId,+ companyId,+ });+ }+ }++ return records;+}diff --git a/packages/database/supabase/functions/lib/scheduling/duration-calculator.ts b/packages/database/supabase/functions/lib/scheduling/duration-calculator.tsnew file mode 100644index 0000000000..e40a3576d1--- /dev/null+++ b/packages/database/supabase/functions/lib/scheduling/duration-calculator.ts@@ -0,0 +1,193 @@+import type { BaseOperation, FactorUnit } from "./types.ts";++const HOURS_PER_WORKDAY = 8;+const MS_PER_HOUR = 3600000;+const MS_PER_MINUTE = 60000;+const MS_PER_SECOND = 1000;++/**+ * Convert time value to hours based on the unit type+ */+function convertToHours(+ time: number | null | undefined,+ unit: FactorUnit | null | undefined,+ quantity: number+): number {+ if (!time || !unit) return 0;++ switch (unit) {+ case "Total Hours":+ return time;+ case "Total Minutes":+ return time / 60;+ case "Hours/Piece":+ return time * quantity;+ case "Hours/100 Pieces":+ return (time / 100) * quantity;+ case "Hours/1000 Pieces":+ return (time / 1000) * quantity;+ case "Minutes/Piece":+ return (time * quantity) / 60;+ case "Minutes/100 Pieces":+ return ((time / 100) * quantity) / 60;+ case "Minutes/1000 Pieces":+ return ((time / 1000) * quantity) / 60;+ case "Pieces/Hour":+ return time > 0 ? quantity / time : 0;+ case "Pieces/Minute":+ return time > 0 ? quantity / (time * 60) : 0;+ case "Seconds/Piece":+ return (time * quantity) / 3600;+ default:+ return 0;+ }+}++/**+ * Convert time value to milliseconds based on the unit type+ */+function convertToMilliseconds(+ time: number | null | undefined,+ unit: FactorUnit | null | undefined,+ quantity: number+): number {+ if (!time || !unit) return 0;++ switch (unit) {+ case "Total Hours":+ return time * MS_PER_HOUR;+ case "Total Minutes":+ return time * MS_PER_MINUTE;+ case "Hours/Piece":+ return time * quantity * MS_PER_HOUR;+ case "Hours/100 Pieces":+ return (time / 100) * quantity * MS_PER_HOUR;+ case "Hours/1000 Pieces":+ return (time / 1000) * quantity * MS_PER_HOUR;+ case "Minutes/Piece":+ return time * quantity * MS_PER_MINUTE;+ case "Minutes/100 Pieces":+ return (time / 100) * quantity * MS_PER_MINUTE;+ case "Minutes/1000 Pieces":+ return (time / 1000) * quantity * MS_PER_MINUTE;+ case "Pieces/Hour":+ return time > 0 ? (quantity / time) * MS_PER_HOUR : 0;+ case "Pieces/Minute":+ return time > 0 ? (quantity / time) * MS_PER_MINUTE : 0;+ case "Seconds/Piece":+ return time * quantity * MS_PER_SECOND;+ default:+ return 0;+ }+}++/**+ * Calculate the total duration of an operation in hours+ * Total = setup + max(labor, machine) since labor and machine can overlap+ */+export function calculateDurationHours(operation: BaseOperation): number {+ const quantity = operation.operationQuantity || 1;++ const setupHours = convertToHours(+ operation.setupTime,+ operation.setupUnit,+ quantity+ );+ const laborHours = convertToHours(+ operation.laborTime,+ operation.laborUnit,+ quantity+ );+ const machineHours = convertToHours(+ operation.machineTime,+ operation.machineUnit,+ quantity+ );++ // Total = setup + max(labor, machine) since labor and machine can overlap+ return setupHours + Math.max(laborHours, machineHours);+}++/**+ * Calculate the total duration of an operation in working days+ * Rounds up to at least 1 day+ */+export function calculateDurationDays(+ operation: BaseOperation,+ hoursPerDay: number = HOURS_PER_WORKDAY+): number {+ const hours = calculateDurationHours(operation);+ return Math.max(Math.ceil(hours / hoursPerDay), 1);+}++/**+ * Calculate the total duration of an operation in milliseconds+ * Used for load balancing calculations+ */+export function calculateDurationMs(operation: BaseOperation): number {+ const quantity = operation.operationQuantity || 1;++ const setupMs = convertToMilliseconds(+ operation.setupTime,+ operation.setupUnit,+ quantity+ );+ const laborMs = convertToMilliseconds(+ operation.laborTime,+ operation.laborUnit,+ quantity+ );+ const machineMs = convertToMilliseconds(+ operation.machineTime,+ operation.machineUnit,+ quantity+ );++ // Total = setup + max(labor, machine) since labor and machine can overlap+ return setupMs + Math.max(laborMs, machineMs);+}++/**+ * Calculate detailed duration breakdown for an operation+ */+export function calculateDurationBreakdown(operation: BaseOperation): {+ setupHours: number;+ laborHours: number;+ machineHours: number;+ totalHours: number;+ totalDays: number;+ totalMs: number;+} {+ const quantity = operation.operationQuantity || 1;++ const setupHours = convertToHours(+ operation.setupTime,+ operation.setupUnit,+ quantity+ );+ const laborHours = convertToHours(+ operation.laborTime,+ operation.laborUnit,+ quantity+ );+ const machineHours = convertToHours(+ operation.machineTime,+ operation.machineUnit,+ quantity+ );++ const totalHours = setupHours + Math.max(laborHours, machineHours);+ const totalDays = Math.max(Math.ceil(totalHours / HOURS_PER_WORKDAY), 1);+ const totalMs = totalHours * MS_PER_HOUR;++ return {+ setupHours,+ laborHours,+ machineHours,+ totalHours,+ totalDays,+ totalMs,+ };+}++export { convertToHours, convertToMilliseconds, HOURS_PER_WORKDAY };diff --git a/packages/database/supabase/functions/lib/scheduling/priority-calculator.ts b/packages/database/supabase/functions/lib/scheduling/priority-calculator.tsnew file mode 100644index 0000000000..6dba972f0b--- /dev/null+++ b/packages/database/supabase/functions/lib/scheduling/priority-calculator.ts@@ -0,0 +1,177 @@+import type {+ DeadlineType,+ OperationWithJobInfo,+ ScheduledOperation,+} from "./types.ts";++/**+ * Deadline type priority order (lower number = higher priority)+ */+const DEADLINE_PRIORITY: Record<string, number> = {+ "ASAP": 0,+ "Hard Deadline": 1,+ "Soft Deadline": 2,+ "No Deadline": 3,+};++/**+ * Get deadline priority value (for sorting)+ */+function getDeadlinePriority(deadlineType: DeadlineType | string | null | undefined): number {+ return DEADLINE_PRIORITY[deadlineType || "No Deadline"] ?? 3;+}++/**+ * Sort operations by priority criteria:+ * 1. Start Date (earliest first) - Primary+ * 2. Job Priority (lower number = higher priority) - Secondary+ * 3. Deadline Type (ASAP > Hard > Soft > No Deadline) - Tie-breaker+ */+export function sortOperationsByPriority<T extends OperationWithJobInfo>(+ operations: T[]+): T[] {+ return [...operations].sort((a, b) => {+ // 1. Start date (earliest first, nulls last)+ if (a.startDate && b.startDate) {+ const dateCompare =+ new Date(a.startDate).getTime() - new Date(b.startDate).getTime();+ if (dateCompare !== 0) return dateCompare;+ } else if (a.startDate) {+ return -1;+ } else if (b.startDate) {+ return 1;+ }++ // 2. Job priority (lower = higher priority)+ const aPriority = a.jobPriority ?? 0;+ const bPriority = b.jobPriority ?? 0;+ if (aPriority !== bPriority) {+ return aPriority - bPriority;+ }++ // 3. Deadline type (ASAP > Hard > Soft > No Deadline)+ const aDeadline = getDeadlinePriority(a.deadlineType);+ const bDeadline = getDeadlinePriority(b.deadlineType);+ return aDeadline - bDeadline;+ });+}++/**+ * Assign sequential integer priorities to sorted operations+ * Uses simple sequential numbering (1, 2, 3, ...)+ */+export function assignSequentialPriorities<T extends { id: string }>(+ sortedOperations: T[]+): Map<string, number> {+ const priorities = new Map<string, number>();++ sortedOperations.forEach((op, index) => {+ priorities.set(op.id, index + 1);+ });++ return priorities;+}++/**+ * Calculate fractional priority for inserting between two existing priorities+ * Used when inserting a new operation between existing ones+ */+export function calculateFractionalPriority(+ priorityBefore: number | null,+ priorityAfter: number | null+): number {+ const before = priorityBefore ?? 0;+ const after = priorityAfter ?? before + 2;++ return (before + after) / 2;+}++/**+ * Group operations by work center+ */+export function groupOperationsByWorkCenter<T extends { workCenterId: string | null }>(+ operations: T[]+): Map<string | null, T[]> {+ const groups = new Map<string | null, T[]>();++ for (const op of operations) {+ const wcId = op.workCenterId;+ if (!groups.has(wcId)) {+ groups.set(wcId, []);+ }+ groups.get(wcId)!.push(op);+ }++ return groups;+}++/**+ * Calculate priorities for all operations grouped by work center+ * Returns a map of operation ID to priority number+ */+export function calculatePrioritiesByWorkCenter(+ operations: OperationWithJobInfo[]+): Map<string, number> {+ const allPriorities = new Map<string, number>();++ // Group by work center+ const byWorkCenter = groupOperationsByWorkCenter(operations);++ // Calculate priorities for each work center independently+ for (const [_wcId, wcOperations] of byWorkCenter) {+ // Sort operations for this work center+ const sorted = sortOperationsByPriority(wcOperations);++ // Assign sequential priorities+ const priorities = assignSequentialPriorities(sorted);++ // Merge into all priorities+ for (const [opId, priority] of priorities) {+ allPriorities.set(opId, priority);+ }+ }++ return allPriorities;+}++/**+ * Convert scheduled operations to OperationWithJobInfo format+ * for priority calculation+ */+export function toOperationWithJobInfo(+ operation: ScheduledOperation,+ jobPriority: number | null,+ jobDeadlineType: DeadlineType | null+): OperationWithJobInfo {+ return {+ id: operation.id,+ dueDate: operation.dueDate,+ startDate: operation.startDate,+ priority: operation.priority,+ deadlineType: operation.deadlineType ?? jobDeadlineType,+ jobPriority,+ workCenterId: operation.workCenterId ?? null,+ };+}++/**+ * Apply calculated priorities to scheduled operations+ */+export function applyPriorities(+ operations: Map<string, ScheduledOperation>,+ priorities: Map<string, number>+): Map<string, ScheduledOperation> {+ const result = new Map<string, ScheduledOperation>();++ for (const [opId, op] of operations) {+ const priority = priorities.get(opId) ?? op.priority;+ result.set(opId, {+ ...op,+ priority,+ });+ }++ return result;+}++export { DEADLINE_PRIORITY, getDeadlinePriority };diff --git a/packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts b/packages/database/supabase/functions/lib/scheduling/scheduling-engine.tsindex 7af4c8f3e8..0fe2811b29 100644--- a/packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts+++ b/packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts@@ -1,378 +1,569 @@-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 type { Kysely } from "https://esm.sh/[email protected]";+import type SupabaseClient from "https://esm.sh/v135/@supabase/[email protected]/dist/module/SupabaseClient.d.ts";+import type { DB } from "../database.ts";+import type { Database } from "../types.ts";+import {+ AssemblyHandler,+ buildMakeMethodDependencies,+} from "./assembly-handler.ts";+import { calculateOperationDates } from "./date-calculator.ts";+import {+ buildOperationDependencies,+ dependenciesToRecords,+ DependencyGraphImpl,+} from "./dependency-manager.ts";import { MaterialManager } from "./material-manager.ts";-import { ResourceManager } from "./resource-manager.ts";-import { BaseOperation, SchedulingStrategy } from "./types.ts";--class SchedulingEngine {+import {+ applyPriorities,+ calculatePrioritiesByWorkCenter,+ toOperationWithJobInfo,+} from "./priority-calculator.ts";+import type {+ BaseOperation,+ Job,+ JobOperationDependency,+ OperationWithJobInfo,+ ScheduledOperation,+ SchedulingDirection,+ SchedulingMode,+ SchedulingOptions,+ SchedulingResult,+} from "./types.ts";+import {+ applyWorkCenterSelections,+ WorkCenterSelector,+} from "./work-center-selector.ts";++/**+ * Unified Scheduling Engine+ * Orchestrates all scheduling operations for both initial scheduling and rescheduling+ */+export 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: {- id: string;- parentId: string | null;- }[];- private validMaterialIds: string[];-- private resourceManager: ResourceManager;+ private userId: string;+ private direction: SchedulingDirection;+ private mode: SchedulingMode;++ private job: Job | null = null;+ private operations: BaseOperation[] = [];+ private dependencies: JobOperationDependency[] = [];+ private scheduledOperations: Map<string, ScheduledOperation> = new Map();+ private affectedWorkCenters: Set<string> = new Set();+ private assemblyDepth: number = 0;+ private conflictsDetected: number = 0;++ private assemblyHandler: AssemblyHandler;+ private workCenterSelector: WorkCenterSelector | null = null;private materialManager: MaterialManager;- constructor({- client,- db,- jobId,- companyId,- }: {- client: SupabaseClient<Database>;- db: Kysely<DB>;- jobId: string;- companyId: string;- }) {- this.db = db;- this.client = client;- this.companyId = companyId;- this.jobId = jobId;- this.operationsToSchedule = [];- this.operationsByJobMakeMethodId = {};- this.validMaterialIds = [];- this.makeMethodDependencies = [];-- this.materialManager = new MaterialManager(db, companyId);- this.resourceManager = new ResourceManager(db, companyId);+ constructor(+ options: SchedulingOptions & {+ client: SupabaseClient<Database>;+ db: Kysely<DB>;+ }+ ) {+ this.client = options.client;+ this.db = options.db;+ this.jobId = options.jobId;+ this.companyId = options.companyId;+ this.userId = options.userId;+ this.direction = options.direction;+ this.mode = options.mode;++ this.assemblyHandler = new AssemblyHandler(+ this.client,+ this.db,+ this.companyId+ );+ this.materialManager = new MaterialManager(this.db, this.companyId);}+ /**+ * Initialize the engine - load job, operations, and dependencies+ */async initialize(): Promise<void> {- if (!this.db) {- throw new Error("Database connection is not initialized");+ // Load job+ const job = await this.db+ .selectFrom("job")+ .select(["id", "dueDate", "deadlineType", "locationId", "priority"])+ .where("id", "=", this.jobId)+ .executeTakeFirst();++ if (!job) {+ throw new Error(`Job ${this.jobId} not found`);+ }++ this.job = job;++ // Initialize work center selector with location+ if (job.locationId) {+ this.workCenterSelector = new WorkCenterSelector(+ this.db,+ this.companyId,+ job.locationId+ );+ await this.workCenterSelector.initialize();+ }++ // Load operations+ this.operations = (await this.db+ .selectFrom("jobOperation")+ .selectAll()+ .where("jobId", "=", this.jobId)+ .where("status", "not in", ["Done", "Canceled"])+ .orderBy("order")+ .execute()) as BaseOperation[];++ // Load existing dependencies (for reschedule mode)+ if (this.mode === "reschedule") {+ const deps = await this.db+ .selectFrom("jobOperationDependency")+ .selectAll()+ .where("jobId", "=", this.jobId)+ .execute();++ this.dependencies = deps.map((d) => ({+ operationId: d.operationId,+ dependsOnId: d.dependsOnId,+ jobId: d.jobId,+ }));+ }++ // Initialize material manager+ await this.materialManager.initialize(this.jobId);++ // Build assembly tree and get depth+ const assemblyTree = await this.assemblyHandler.buildAssemblyTree(+ this.jobId+ );+ if (assemblyTree) {+ this.assemblyDepth = this.assemblyHandler.getAssemblyDepth(assemblyTree);}- await Promise.all([- this.resourceManager.initialize(this.jobId),- this.materialManager.initialize(this.jobId),- this.getOperationsAndMaterialsToSchedule(),- ]);}- async addDependencies(): Promise<void> {- const operationDependencies: Record<string, Set<string>> = {};- const makeMethodIds = [- ...new Set(this.makeMethodDependencies.map((m) => m.id)),- ];+ /**+ * Create operation dependencies based on assembly structure+ * Only called in initial scheduling mode+ */+ async createDependencies(): Promise<void> {+ if (this.mode !== "initial") {+ return;+ }++ // Build assembly tree+ const assemblyTree = await this.assemblyHandler.buildAssemblyTree(+ this.jobId+ );+ if (!assemblyTree) {+ console.warn("No assembly tree found for job", this.jobId);+ return;+ }++ // Get all jobMakeMethodIds+ const makeMethodIds =+ this.assemblyHandler.getAllJobMakeMethodIds(assemblyTree);++ // Get job materials for linkingconst jobMaterials = await this.db.selectFrom("jobMaterialWithMakeMethodId").selectAll().where("jobMakeMethodId", "in", makeMethodIds).execute();+ // Build map from make method to operationconst jobMakeMethodToOperationId: Record<string, string | null> = {};-- jobMaterials.forEach((m) => {+ for (const m of jobMaterials) {if (m.jobMaterialMakeMethodId) {jobMakeMethodToOperationId[m.jobMaterialMakeMethodId] =m.jobOperationId;}- });-- // Initialize dependencies for all operations- for (const operation of this.operationsToSchedule) {- if (!operation.id) continue;- operationDependencies[operation.id] = new Set<string>();}- for await (const makeMethod of this.makeMethodDependencies) {- const operations = this.operationsByJobMakeMethodId[makeMethod.id] ?? [];- const lastOperation = operations[operations.length - 1];+ // Group operations by jobMakeMethodId+ const operationsByMethod = new Map<string, BaseOperation[]>();+ for (const op of this.operations) {+ if (op.jobMakeMethodId) {+ if (!operationsByMethod.has(op.jobMakeMethodId)) {+ operationsByMethod.set(op.jobMakeMethodId, []);+ }+ operationsByMethod.get(op.jobMakeMethodId)!.push(op);+ }+ }- if (!lastOperation) continue;+ // Build make method dependencies+ const makeMethodDeps = buildMakeMethodDependencies(assemblyTree);- if (makeMethod.id) {- const parentOperation = jobMakeMethodToOperationId[makeMethod.id];+ // Build operation dependencies+ const allDependencies = new Map<string, Set<string>>();- if (parentOperation) {- operationDependencies[parentOperation].add(lastOperation.id!);- }+ // Initialize all operations+ for (const op of this.operations) {+ if (op.id) {+ allDependencies.set(op.id, new Set());}+ }- operations.forEach((op, index) => {- op.order = this.getParallelizedOrder(index, op, operations);- });- operations.sort((a, b) => (a?.order ?? 0) - (b?.order ?? 0));-- // Create a map of operations by order- const operationsByOrder: Record<number, string[]> = {};- operations.forEach((op) => {- if (!op.id) return;- const order = op.order ?? 0;- if (!operationsByOrder[order]) {- operationsByOrder[order] = [];+ // Process each make method's operations+ for (const methodDep of makeMethodDeps) {+ const methodOps = operationsByMethod.get(methodDep.id) ?? [];++ // Get last operation of this method+ const sortedOps = [...methodOps].sort(+ (a, b) => (a.order ?? 0) - (b.order ?? 0)+ );+ const lastOperation = sortedOps[sortedOps.length - 1];++ // If this method has a parent, link last op to parent's consuming operation+ if (methodDep.id && methodDep.parentId !== null) {+ const parentOperation = jobMakeMethodToOperationId[methodDep.id];+ if (parentOperation && lastOperation?.id) {+ const deps = allDependencies.get(parentOperation);+ if (deps) {+ deps.add(lastOperation.id);+ }}- operationsByOrder[order].push(op.id);- });+ }- // Create dependencies between sequential operations- const orderKeys = Object.keys(operationsByOrder)- .map(Number)- .sort((a, b) => a - b);- for (let i = 1; i < orderKeys.length; i++) {- const currentOrderOps = operationsByOrder[orderKeys[i]];- const previousOrderOps = operationsByOrder[orderKeys[i - 1]];-- // Add all previous order operations as dependencies for current order operations- currentOrderOps.forEach((opId) => {- if (!operationDependencies[opId]) {- operationDependencies[opId] = new Set<string>();+ // Build dependencies within this method (handling "With Previous")+ const methodDeps = buildOperationDependencies(methodOps);+ for (const [opId, deps] of methodDeps) {+ const existing = allDependencies.get(opId);+ if (existing) {+ for (const depId of deps) {+ existing.add(depId);}- previousOrderOps.forEach((prevOpId) => {- operationDependencies[opId].add(prevOpId);- });- });+ }}}+ // Delete existing dependenciesawait this.db.deleteFrom("jobOperationDependency").where("jobId", "=", this.jobId).execute();- if (Object.keys(operationDependencies).length > 0) {- for await (const [operationId, dependencies] of Object.entries(- operationDependencies- )) {- 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();- } else {- // these don't get handled by the trigger because the trigger- // is only fired when a dependency is added- await this.db- .updateTable("jobOperation")- .set({- status: "Ready",- })- .where("id", "=", operationId)- .execute();- }+ // Insert new dependencies+ const records = dependenciesToRecords(+ allDependencies,+ this.jobId,+ this.companyId+ );++ if (records.length > 0) {+ for (const record of records) {+ await this.db+ .insertInto("jobOperationDependency")+ .values(record)+ .execute();}}++ // Update operations with no dependencies to Ready status+ for (const [opId, deps] of allDependencies) {+ if (deps.size === 0) {+ await this.db+ .updateTable("jobOperation")+ .set({ status: "Ready" })+ .where("id", "=", opId)+ .execute();+ }+ }++ // Store dependencies for date calculation+ this.dependencies = records.map((r) => ({+ operationId: r.operationId,+ dependsOnId: r.dependsOnId,+ jobId: r.jobId,+ }));}- async assign() {- await this.materialManager.assignOperationsToMaterials(- this.validMaterialIds,- this.operationsByJobMakeMethodId+ /**+ * Calculate dates for all operations+ */+ async calculateDates(): Promise<void> {+ // Build dependency graph+ const graph = new DependencyGraphImpl(this.operations, this.dependencies);++ // Get anchor date based on direction+ const anchorDate =+ this.direction === "backward" ? this.job?.dueDate ?? null : null; // Forward scheduling would use start date++ // Calculate dates+ this.scheduledOperations = calculateOperationDates(+ this.operations,+ graph,+ anchorDate,+ this.direction);- }- getParallelizedOrder(index: number, op: BaseOperation, ops: BaseOperation[]) {- if (op?.operationOrder !== "With Previous") return index + 1;- // traverse backwards through the list of ops to find the first op that is not "With Previous" and return its index + 1- for (let i = index - 1; i >= 0; i--) {- if (ops[i].operationOrder !== "With Previous") {- return i + 1;+ // Count conflicts+ this.conflictsDetected = 0;+ for (const op of this.scheduledOperations.values()) {+ if (op.hasConflict) {+ this.conflictsDetected++;}}-- return 1;}- 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.hasWorkCenter(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,- });- }- }+ /**+ * Select work centers for all operations+ */+ async selectWorkCenters(): Promise<void> {+ if (!this.workCenterSelector) {+ console.warn("Work center selector not initialized");+ return;+ }- 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();- }+ const operations = Array.from(this.scheduledOperations.values());+ const selections =+ await this.workCenterSelector.selectWorkCentersForOperations(operations);- trx- .updateTable("job")- .set({- status: "Ready",- })- .where("id", "=", this.jobId)- .execute();- });- break;- }- default: {- throw new Error(`Unsupported scheduling strategy: ${strategy}`);+ // Apply selections+ this.scheduledOperations = applyWorkCenterSelections(+ this.scheduledOperations,+ selections+ );++ // Track affected work centers+ for (const selection of selections.values()) {+ if (selection.workCenterId) {+ this.affectedWorkCenters.add(selection.workCenterId);}}}- async getOperationsAndMaterialsToSchedule() {- if (!this.db) {- throw new Error("Database connection is not initialized");+ /**+ * Calculate priorities for all operations grouped by work center+ */+ async calculatePriorities(): Promise<void> {+ // Get all operations at affected work centers (not just from this job)+ const workCenterIds = Array.from(this.affectedWorkCenters);++ if (workCenterIds.length === 0) {+ // No work centers affected, just use job-level priorities+ const opsWithInfo: OperationWithJobInfo[] = [];+ for (const op of this.scheduledOperations.values()) {+ opsWithInfo.push(+ toOperationWithJobInfo(+ op,+ this.job?.priority ?? null,+ this.job?.deadlineType ?? null+ )+ );+ }++ const priorities = calculatePrioritiesByWorkCenter(opsWithInfo);+ this.scheduledOperations = applyPriorities(+ this.scheduledOperations,+ priorities+ );+ return;}- 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"])- .orderBy("order")- .execute(),- ]);-- const operationsByJobMakeMethodId = operations.reduce<- Record<string, BaseOperation[]>- >((acc, operation) => {- if (!operation.jobMakeMethodId) return acc;- if (!acc[operation.jobMakeMethodId]) {- acc[operation.jobMakeMethodId] = [];++ // Get all active operations at affected work centers from OTHER jobs+ // (current job's operations aren't in DB yet with their new work centers)+ const allWcOps = await this.db+ .selectFrom("jobOperation as jo")+ .innerJoin("job as j", "j.id", "jo.jobId")+ .select([+ "jo.id",+ "jo.dueDate",+ "jo.startDate",+ "jo.priority",+ "j.deadlineType",+ "j.priority as jobPriority",+ "jo.workCenterId",+ ])+ .where("jo.workCenterId", "in", workCenterIds)+ .where("jo.status", "not in", ["Done", "Canceled"])+ .execute();++ // Build a set of operation IDs from the database query+ const dbOpIds = new Set(allWcOps.map((op) => op.id).filter(Boolean));++ // Start with operations from DB (other jobs at same work centers)+ const mergedOps: OperationWithJobInfo[] = allWcOps+ .filter((wcOp) => wcOp.id)+ .map((wcOp) => {+ const scheduled = this.scheduledOperations.get(wcOp.id!);+ if (scheduled) {+ // This is an operation from current job that was already in DB+ // (reschedule case) - use the newly calculated dates+ return {+ id: scheduled.id,+ dueDate: scheduled.dueDate ?? null,+ startDate: scheduled.startDate ?? null,+ priority: scheduled.priority,+ deadlineType: wcOp.deadlineType ?? "No Deadline",+ jobPriority: wcOp.jobPriority ?? 99,+ workCenterId: scheduled.workCenterId ?? null,+ };+ }+ // Operation from another job - use DB data+ return {+ id: wcOp.id!,+ dueDate: wcOp.dueDate ?? null,+ startDate: wcOp.startDate ?? null,+ priority: wcOp.priority ?? 1,+ deadlineType: wcOp.deadlineType ?? "No Deadline",+ jobPriority: wcOp.jobPriority ?? 99,+ workCenterId: wcOp.workCenterId ?? null,+ };+ });++ // Add current job's scheduled operations that aren't in DB yet+ // (their workCenterId was just assigned in memory)+ for (const op of this.scheduledOperations.values()) {+ if (!dbOpIds.has(op.id) && op.workCenterId) {+ mergedOps.push({+ id: op.id,+ dueDate: op.dueDate ?? null,+ startDate: op.startDate ?? null,+ priority: op.priority,+ deadlineType: op.deadlineType ?? this.job?.deadlineType ?? "No Deadline",+ jobPriority: this.job?.priority ?? 99,+ workCenterId: op.workCenterId,+ });}- acc[operation.jobMakeMethodId].push(operation);- return acc;- }, {});+ }- this.operationsByJobMakeMethodId = operationsByJobMakeMethodId;+ // Calculate priorities+ const priorities = calculatePrioritiesByWorkCenter(mergedOps);- if (!jobMakeMethod?.id) {- throw new Error("Job make method not found");+ // Apply to our scheduled operations+ this.scheduledOperations = applyPriorities(+ this.scheduledOperations,+ priorities+ );+ }++ /**+ * Assign materials to operations (initial scheduling only)+ */+ async assignMaterials(): Promise<void> {+ if (this.mode !== "initial") {+ return;}- const jobMethodTrees = await getJobMethodTree(- this.client,- jobMakeMethod.id++ // Build assembly tree+ const assemblyTree = await this.assemblyHandler.buildAssemblyTree(+ this.jobId);- if (jobMethodTrees.error) {- throw new Error("Job method tree not found");+ if (!assemblyTree) {+ return;}- const jobMethodTree = jobMethodTrees.data?.[0] as JobMethodTreeItem;- if (!jobMethodTree) throw new Error("Method tree not found");-- const operationsToSchedule: BaseOperation[] = [];- const queue: JobMethodTreeItem[] = [jobMethodTree];- const validMaterialIds: string[] = [];- const makeMethodDependencies: {- id: string;- parentId: string | null;- }[] = [];-- while (queue.length > 0) {- const currentNode = queue.shift();- if (!currentNode) continue;-- const operations =- operationsByJobMakeMethodId[currentNode.data.jobMaterialMakeMethodId] ||- [];- operationsToSchedule.unshift(...operations);-- // Populate makeMethodDependencies- if (- currentNode.data.jobMakeMethodId !==- currentNode.data.jobMaterialMakeMethodId- ) {- // Check if this dependency already exists- const dependencyExists = makeMethodDependencies.some(- (dep) =>- dep.id === currentNode.data.jobMaterialMakeMethodId &&- dep.parentId === currentNode.data.jobMakeMethodId- );+ // Get all jobMakeMethodIds+ const makeMethodIds =+ this.assemblyHandler.getAllJobMakeMethodIds(assemblyTree);- if (!dependencyExists && currentNode.data.jobMaterialMakeMethodId) {- makeMethodDependencies.unshift({- id: currentNode.data.jobMaterialMakeMethodId,- parentId: currentNode.data.jobMakeMethodId,- });- }- } else {- const rootDependencyExists = makeMethodDependencies.some(- (dep) =>- dep.id === currentNode.data.jobMaterialMakeMethodId &&- dep.parentId === null- );+ // Get materials that need assignment+ const materials = await this.db+ .selectFrom("jobMaterial")+ .select(["id", "jobMakeMethodId"])+ .where("jobMakeMethodId", "in", makeMethodIds)+ .where("methodType", "=", "Make")+ .where("jobOperationId", "is", null)+ .execute();- if (!rootDependencyExists && currentNode.data.jobMaterialMakeMethodId) {- makeMethodDependencies.unshift({- id: currentNode.data.jobMaterialMakeMethodId,- parentId: null,- });+ // Group operations by jobMakeMethodId+ const operationsByMethod = new Map<string, BaseOperation[]>();+ for (const op of this.operations) {+ if (op.jobMakeMethodId) {+ if (!operationsByMethod.has(op.jobMakeMethodId)) {+ operationsByMethod.set(op.jobMakeMethodId, []);}+ operationsByMethod.get(op.jobMakeMethodId)!.push(op);}+ }- if (!currentNode.data.isRoot && currentNode.data.methodMaterialId) {- validMaterialIds.push(currentNode.data.methodMaterialId);+ // Assign first operation of each method to its materials+ for (const material of materials) {+ if (!material.jobMakeMethodId) continue;++ const methodOps = operationsByMethod.get(material.jobMakeMethodId) ?? [];+ const sortedOps = [...methodOps].sort(+ (a, b) => (a.order ?? 0) - (b.order ?? 0)+ );+ const firstOp = sortedOps[0];++ if (firstOp?.id) {+ await this.db+ .updateTable("jobMaterial")+ .set({ jobOperationId: firstOp.id })+ .where("id", "=", material.id)+ .execute();}+ }+ }- queue.push(...currentNode.children);+ /**+ * Persist all changes to the database+ */+ async persistChanges(): Promise<void> {+ for (const op of this.scheduledOperations.values()) {+ await this.db+ .updateTable("jobOperation")+ .set({+ startDate: op.startDate,+ dueDate: op.dueDate,+ priority: op.priority ?? undefined,+ workCenterId: op.workCenterId,+ hasConflict: op.hasConflict,+ conflictReason: op.conflictReason,+ updatedAt: new Date().toISOString(),+ updatedBy: this.userId,+ })+ .where("id", "=", op.id)+ .execute();}- this.operationsToSchedule = operationsToSchedule;- this.validMaterialIds = validMaterialIds;- this.makeMethodDependencies = makeMethodDependencies;+ // Update job status if initial scheduling+ if (this.mode === "initial") {+ await this.db+ .updateTable("job")+ .set({ status: "Ready" })+ .where("id", "=", this.jobId)+ .execute();+ }}-}-export { SchedulingEngine };+ /**+ * Get the scheduling result+ */+ getResult(): SchedulingResult {+ return {+ success: true,+ operationsScheduled: this.scheduledOperations.size,+ conflictsDetected: this.conflictsDetected,+ workCentersAffected: Array.from(this.affectedWorkCenters),+ assemblyDepth: this.assemblyDepth,+ };+ }++ /**+ * Run the full scheduling process+ */+ async run(): Promise<SchedulingResult> {+ await this.initialize();++ if (this.mode === "initial") {+ // Assign materials BEFORE creating dependencies+ // Dependencies require jobMaterial.jobOperationId to be set+ // to link subassembly operations to parent operations+ await this.assignMaterials();+ await this.createDependencies();+ }++ await this.calculateDates();+ await this.selectWorkCenters();+ await this.calculatePriorities();++ await this.persistChanges();++ return this.getResult();+ }+}diff --git a/packages/database/supabase/functions/lib/scheduling/types.ts b/packages/database/supabase/functions/lib/scheduling/types.tsindex ac034a0cf3..d048250fe8 100644--- a/packages/database/supabase/functions/lib/scheduling/types.ts+++ b/packages/database/supabase/functions/lib/scheduling/types.ts@@ -1,25 +1,45 @@import type { Database } from "../types.ts";export type DeadlineType = Database["public"]["Enums"]["deadlineType"];+export type FactorUnit = Database["public"]["Enums"]["factor"];+export type MethodOperationOrder =+ Database["public"]["Enums"]["methodOperationOrder"];+export type OperationType = Database["public"]["Enums"]["operationType"];+export type JobOperationStatus =+ Database["public"]["Enums"]["jobOperationStatus"];++// ============================================================================+// Scheduling Direction and Mode+// ============================================================================++export type SchedulingDirection = "backward" | "forward";+export type SchedulingMode = "initial" | "reschedule";++// ============================================================================+// Base Types (existing)+// ============================================================================export type BaseOperation = {id?: string;jobId: string;+ jobMakeMethodId?: string | null;deadlineType?: DeadlineType;description?: string | null;dueDate?: string | null;+ startDate?: string | null;laborTime?: number;- laborUnit?: Database["public"]["Enums"]["factor"];+ laborUnit?: FactorUnit;machineTime?: number;- machineUnit?: Database["public"]["Enums"]["factor"];- operationOrder?: Database["public"]["Enums"]["methodOperationOrder"];+ machineUnit?: FactorUnit;+ operationOrder?: MethodOperationOrder;operationQuantity?: number | null;- operationType?: Database["public"]["Enums"]["operationType"];+ operationType?: OperationType;+ operationLeadTime?: number;priority?: number;processId: string | null;setupTime?: number;- setupUnit?: Database["public"]["Enums"]["factor"];- status?: Database["public"]["Enums"]["jobOperationStatus"];+ setupUnit?: FactorUnit;+ status?: JobOperationStatus;order?: number;workCenterId?: string | null;};@@ -40,8 +60,9 @@ export type Operation = Omit<export type Job = {id?: string;dueDate?: string | null;- deadlineType?: Database["public"]["Enums"]["deadlineType"];+ deadlineType?: DeadlineType;locationId?: string;+ priority?: number;};export enum SchedulingStrategy {@@ -49,3 +70,107 @@ export enum SchedulingStrategy {LeastTime,Random,}++// ============================================================================+// Scheduled Operation (with calculated dates and conflict info)+// ============================================================================++export type ScheduledOperation = Omit<BaseOperation, "priority"> & {+ id: string;+ startDate: string | null;+ dueDate: string | null;+ priority: number | null;+ durationHours: number;+ durationDays: number;+ hasConflict: boolean;+ conflictReason: string | null;+};++// ============================================================================+// Dependency Graph Types+// ============================================================================++export type DependencyNode = {+ operationId: string;+ dependsOn: string[];+ requiredBy: string[];+};++export interface DependencyGraph {+ nodes: Map<string, DependencyNode>;+ getDependencies(operationId: string): string[];+ getDependents(operationId: string): string[];+ addDependency(operationId: string, dependsOnId: string): void;+ topologicalSort(direction: "forward" | "reverse"): string[];+}++export type JobOperationDependency = {+ operationId: string;+ dependsOnId: string;+ jobId: string;+};++// ============================================================================+// Assembly Types+// ============================================================================++export type AssemblyNode = {+ id: string;+ jobMakeMethodId: string;+ parentMaterialId: string | null;+ itemId: string | null;+ operations: BaseOperation[];+ children: AssemblyNode[];+ completionDate?: string | null;+};++// ============================================================================+// Work Center Types+// ============================================================================++export type WorkCenterLoad = {+ workCenterId: string;+ totalHours: number;+ operationCount: number;+};++export type WorkCenterSelection = {+ workCenterId: string | null;+ priority: number;+ load?: number;+ error?: string;+};++// ============================================================================+// Scheduling Engine Options and Results+// ============================================================================++export type SchedulingOptions = {+ jobId: string;+ companyId: string;+ userId: string;+ direction: SchedulingDirection;+ mode: SchedulingMode;+};++export type SchedulingResult = {+ success: boolean;+ operationsScheduled: number;+ conflictsDetected: number;+ workCentersAffected: string[];+ assemblyDepth: number;+};++// ============================================================================+// Operation with Job Info (for priority calculation)+// ============================================================================++export type OperationWithJobInfo = {+ id: string;+ dueDate: string | null;+ startDate: string | null;+ priority: number | null;+ deadlineType: DeadlineType | null;+ jobPriority: number | null;+ workCenterId: string | null;+};diff --git a/packages/database/supabase/functions/lib/scheduling/work-center-selector.ts b/packages/database/supabase/functions/lib/scheduling/work-center-selector.tsnew file mode 100644index 0000000000..e9c0add642--- /dev/null+++ b/packages/database/supabase/functions/lib/scheduling/work-center-selector.ts@@ -0,0 +1,309 @@+import type { Kysely } from "https://esm.sh/[email protected]";+import type { DB } from "../database.ts";+import type { ScheduledOperation, WorkCenterLoad, WorkCenterSelection } from "./types.ts";+import { calculateDurationHours } from "./duration-calculator.ts";++/**+ * Work Center Selector+ * Handles work center selection based on load balancing+ */+export class WorkCenterSelector {+ private db: Kysely<DB>;+ private companyId: string;+ private locationId: string;+ private workCentersByProcess: Map<string, string[]> = new Map();+ private activeWorkCenters: Set<string> = new Set();+ // Track in-memory load from operations assigned in current scheduling run+ private inMemoryLoadByWorkCenter: Map<string, number> = new Map();++ constructor(db: Kysely<DB>, companyId: string, locationId: string) {+ this.db = db;+ this.companyId = companyId;+ this.locationId = locationId;+ }++ /**+ * Add load for an operation assigned in memory (not yet persisted)+ */+ addInMemoryLoad(workCenterId: string, hours: number): void {+ const currentLoad = this.inMemoryLoadByWorkCenter.get(workCenterId) ?? 0;+ this.inMemoryLoadByWorkCenter.set(workCenterId, currentLoad + hours);+ }++ /**+ * Get total in-memory load for a work center+ */+ getInMemoryLoad(workCenterId: string): number {+ return this.inMemoryLoadByWorkCenter.get(workCenterId) ?? 0;+ }++ /**+ * Reset in-memory load tracking (call before a new scheduling run)+ */+ resetInMemoryLoad(): void {+ this.inMemoryLoadByWorkCenter.clear();+ }++ /**+ * Initialize work center data+ */+ async initialize(): Promise<void> {+ // Get processes and their work centers+ const processes = await this.db+ .selectFrom("processes")+ .select(["id", "workCenters"])+ .where("companyId", "=", this.companyId)+ .execute();++ // Get active work centers at this location+ const workCenters = await this.db+ .selectFrom("workCenter")+ .select(["id", "locationId"])+ .where("locationId", "=", this.locationId)+ .where("companyId", "=", this.companyId)+ .where("active", "=", true)+ .execute();++ // Build set of active work center IDs+ for (const wc of workCenters) {+ if (wc.id) {+ this.activeWorkCenters.add(wc.id);+ }+ }++ // Build process to work centers map (only include active work centers at this location)+ for (const process of processes) {+ if (process.workCenters && process.id) {+ const validWorkCenters = process.workCenters.filter((wcId) =>+ this.activeWorkCenters.has(wcId)+ );+ this.workCentersByProcess.set(process.id, validWorkCenters);+ }+ }+ }++ /**+ * Get work centers that support a given process+ */+ getWorkCentersForProcess(processId: string): string[] {+ return this.workCentersByProcess.get(processId) ?? [];+ }++ /**+ * Check if a work center is valid (exists and is active at this location)+ */+ isValidWorkCenter(workCenterId: string): boolean {+ return this.activeWorkCenters.has(workCenterId);+ }++ /**+ * Calculate total load (in hours) on a work center up to a given date+ */+ async calculateLoadBeforeDate(+ workCenterId: string,+ beforeDate: string+ ): Promise<number> {+ const operations = await this.db+ .selectFrom("jobOperation")+ .select([+ "setupTime",+ "setupUnit",+ "laborTime",+ "laborUnit",+ "machineTime",+ "machineUnit",+ "operationQuantity",+ ])+ .where("workCenterId", "=", workCenterId)+ .where("companyId", "=", this.companyId)+ .where("status", "not in", ["Done", "Canceled"])+ .where((eb) =>+ eb.or([+ eb("startDate", "<=", beforeDate),+ eb("startDate", "is", null),+ ])+ )+ .execute();++ let totalHours = 0;+ for (const op of operations) {+ totalHours += calculateDurationHours({+ jobId: "", // Not needed for duration calculation+ processId: null,+ setupTime: op.setupTime ?? undefined,+ setupUnit: op.setupUnit ?? undefined,+ laborTime: op.laborTime ?? undefined,+ laborUnit: op.laborUnit ?? undefined,+ machineTime: op.machineTime ?? undefined,+ machineUnit: op.machineUnit ?? undefined,+ operationQuantity: op.operationQuantity ?? undefined,+ });+ }++ return totalHours;+ }++ /**+ * Get load information for all work centers supporting a process+ */+ async getLoadForProcessWorkCenters(+ processId: string,+ beforeDate: string+ ): Promise<WorkCenterLoad[]> {+ const workCenters = this.getWorkCentersForProcess(processId);+ const loads: WorkCenterLoad[] = [];++ for (const wcId of workCenters) {+ const totalHours = await this.calculateLoadBeforeDate(wcId, beforeDate);+ const count = await this.db+ .selectFrom("jobOperation")+ .select((eb) => eb.fn.count<number>("id").as("count"))+ .where("workCenterId", "=", wcId)+ .where("companyId", "=", this.companyId)+ .where("status", "not in", ["Done", "Canceled"])+ .where((eb) =>+ eb.or([+ eb("startDate", "<=", beforeDate),+ eb("startDate", "is", null),+ ])+ )+ .executeTakeFirst();++ loads.push({+ workCenterId: wcId,+ totalHours,+ operationCount: count?.count ?? 0,+ });+ }++ return loads;+ }++ /**+ * Select the optimal work center for an operation based on load balancing+ * Selects the work center with the least load before the operation's start date+ * Includes both database load and in-memory load from current scheduling run+ */+ async selectWorkCenter(+ processId: string | null,+ scheduledStartDate: string | null+ ): Promise<WorkCenterSelection> {+ if (!processId) {+ return {+ workCenterId: null,+ priority: 0,+ error: "No process ID provided",+ };+ }++ const workCenters = this.getWorkCentersForProcess(processId);++ if (workCenters.length === 0) {+ return {+ workCenterId: null,+ priority: 0,+ error: `No work centers found for process ${processId}`,+ };+ }++ // Use today if no start date+ const beforeDate = scheduledStartDate || new Date().toISOString().split("T")[0];++ let selectedWorkCenter: string | null = null;+ let lowestLoad = Infinity;++ for (const wcId of workCenters) {+ // Get load from database (other jobs)+ const dbLoad = await this.calculateLoadBeforeDate(wcId, beforeDate);+ // Add in-memory load from current scheduling run+ const inMemoryLoad = this.getInMemoryLoad(wcId);+ const totalLoad = dbLoad + inMemoryLoad;++ if (totalLoad < lowestLoad) {+ lowestLoad = totalLoad;+ selectedWorkCenter = wcId;+ }+ }++ if (!selectedWorkCenter) {+ return {+ workCenterId: null,+ priority: 0,+ error: "No work center selected after evaluation",+ };+ }++ return {+ workCenterId: selectedWorkCenter,+ priority: 0, // Priority will be calculated separately+ load: lowestLoad,+ };+ }++ /**+ * Select work centers for multiple operations+ * Re-evaluates all work center assignments based on scheduled dates+ * Tracks in-memory load to ensure proper load balancing within same scheduling run+ */+ async selectWorkCentersForOperations(+ operations: ScheduledOperation[]+ ): Promise<Map<string, WorkCenterSelection>> {+ const selections = new Map<string, WorkCenterSelection>();++ // Reset in-memory load tracking for this scheduling run+ this.resetInMemoryLoad();++ // Sort by start date to process in order+ const sorted = [...operations].sort((a, b) => {+ if (!a.startDate && !b.startDate) return 0;+ if (!a.startDate) return 1;+ if (!b.startDate) return -1;+ return new Date(a.startDate).getTime() - new Date(b.startDate).getTime();+ });++ for (const op of sorted) {+ // Skip outside operations (they don't need work center assignment)+ if (op.operationType === "Outside") {+ continue;+ }++ const selection = await this.selectWorkCenter(+ op.processId,+ op.startDate+ );+ selections.set(op.id, selection);++ // Track this operation's load in memory for subsequent selections+ if (selection.workCenterId) {+ const opDuration = op.durationHours ?? calculateDurationHours(op);+ this.addInMemoryLoad(selection.workCenterId, opDuration);+ }+ }++ return selections;+ }+}++/**+ * Apply work center selections to scheduled operations+ */+export function applyWorkCenterSelections(+ operations: Map<string, ScheduledOperation>,+ selections: Map<string, WorkCenterSelection>+): Map<string, ScheduledOperation> {+ const result = new Map<string, ScheduledOperation>();++ for (const [opId, op] of operations) {+ const selection = selections.get(opId);+ if (selection?.workCenterId) {+ result.set(opId, {+ ...op,+ workCenterId: selection.workCenterId,+ });+ } else {+ result.set(opId, op);+ }+ }++ return result;+}diff --git a/packages/database/supabase/functions/schedule/index.ts b/packages/database/supabase/functions/schedule/index.tsnew file mode 100644index 0000000000..026f4f0c30--- /dev/null+++ b/packages/database/supabase/functions/schedule/index.ts@@ -0,0 +1,89 @@+import { serve } from "https://deno.land/[email protected]/http/server.ts";+import { z } from "npm:zod@^3.24.1";++import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { corsHeaders } from "../lib/headers.ts";+import { SchedulingEngine } from "../lib/scheduling/scheduling-engine.ts";+import type {+ SchedulingDirection,+ SchedulingMode,+} 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(),+ mode: z.enum(["initial", "reschedule"]).default("initial"),+ direction: z.enum(["backward", "forward"]).default("backward"),+});++serve(async (req: Request) => {+ if (req.method === "OPTIONS") {+ return new Response("ok", { headers: corsHeaders });+ }++ try {+ const payload = await req.json();+ const validatedPayload = payloadValidator.parse(payload);+ const { jobId, companyId, userId, mode, direction } = validatedPayload;++ console.info(`🔰 Starting ${mode} scheduling for job ${jobId}`);+ console.info(`📋 Direction: ${direction}`);++ const client = await getSupabaseServiceRole(+ req.headers.get("Authorization"),+ req.headers.get("carbon-key") ?? "",+ companyId+ );++ const engine = new SchedulingEngine({+ client,+ db,+ jobId,+ companyId,+ userId,+ mode: mode as SchedulingMode,+ direction: direction as SchedulingDirection,+ });++ const result = await engine.run();++ console.info(`✅ Scheduling complete:`);+ console.info(` Operations scheduled: ${result.operationsScheduled}`);+ console.info(` Conflicts detected: ${result.conflictsDetected}`);+ console.info(+ ` Work centers affected: ${result.workCentersAffected.length}`+ );+ console.info(` Assembly depth: ${result.assemblyDepth}`);++ return new Response(+ JSON.stringify({+ ...result,+ }),+ {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 200,+ }+ );+ } catch (error) {+ console.error(+ `❌ Scheduling 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/functions/scheduler/data.ts b/packages/database/supabase/functions/scheduler/data.tsdeleted file mode 100644index 4285dd22ec..0000000000--- a/packages/database/supabase/functions/scheduler/data.ts+++ /dev/null@@ -1,167 +0,0 @@-export const jobs = [- {- id: "10323",- deadlineDate: "2024-05-20",- deadlineType: "Soft Deadline",- operations: [- {- id: "operation0",- duration: 6 * 60 * 60 * 1000,- status: "DONE",- workCenterType: "cnc",- },- {- id: "operation1",- duration: 2 * 60 * 60 * 1000,- status: "IN_PROGRESS",- workCenterType: "assembly",- timecards: [- {- start: "2024-05-20T08:00:00",- end: "2024-05-20T9:00:00",- machine: "assembly1",- },- ],- },- {- id: "operation2",- duration: 4 * 60 * 60 * 1000,- status: "TODO",- workCenterType: "inspection",- },- ],- },- {- id: "10324",- deadlineDate: "2024-06-20",- deadlineType: "Hard Deadline",- operations: [- {- id: "operation3",- duration: 20 * 60 * 1000,- status: "WAITING",- workCenterType: "assembly",- },- {- id: "operation4",- duration: 10 * 60 * 1000,- status: "TODO",- workCenterType: "inspection",- },- ],- },- {- id: "10325",- deadlineDate: "2024-07-20",- deadlineType: "Soft Deadline",- operations: [- {- id: "operation5",- duration: 8 * 60 * 60 * 1000,- status: "PAUSED",- workCenterType: "cnc",- timecards: [- {- start: "2024-07-20T08:00:00",- end: "2024-07-20T10:00:00",- machine: "cnc1",- },- ],- },- {- id: "operation6",- duration: 3 * 60 * 60 * 1000,- status: "TODO",- workCenterType: "saw",- },- {- id: "operation7",- duration: 5 * 60 * 60 * 1000,- status: "TODO",- workCenterType: "assembly",- },- ],- },- {- id: "10326",- deadlineDate: "2024-08-20",- deadlineType: "Hard Deadline",- operations: [- {- id: "operation8",- duration: 15 * 60 * 1000,- status: "TODO",- workCenterType: "saw",- },- {- id: "operation9",- duration: 12 * 60 * 1000,- status: "TODO",- workCenterType: "inspection",- },- ],- },- {- id: "10327",- deadlineDate: "2024-09-20",- deadlineType: "Soft Deadline",- operations: [- {- id: "operation10",- duration: 10 * 60 * 60 * 1000,- status: "TODO",- workCenterType: "cnc",- },- {- id: "operation11",- duration: 4 * 60 * 60 * 1000,- status: "TODO",- workCenterType: "assembly",- },- {- id: "operation12",- duration: 6 * 60 * 60 * 1000,- status: "TODO",- workCenterType: "inspection",- },- ],- },-];--export const workCenters = [- {- id: "cnc1",- name: "CNC 1",- workCenterType: "cnc",- },- {- id: "cnc2",- name: "CNC 2",- workCenterType: "cnc",- },- {- id: "saw1",- name: "Saw 1",- workCenterType: "saw",- },- {- id: "saw2",- name: "Saw 2",- workCenterType: "saw",- },- {- id: "assembly1",- name: "Assembly 1",- workCenterType: "assembly",- },- {- id: "assembly2",- name: "Assembly 2",- workCenterType: "assembly",- },- {- id: "inspection1",- name: "Inspection 1",- workCenterType: "inspection",- },-];diff --git a/packages/database/supabase/functions/scheduler/index.ts b/packages/database/supabase/functions/scheduler/index.tsdeleted file mode 100644index 0feaa2d837..0000000000--- a/packages/database/supabase/functions/scheduler/index.ts+++ /dev/null@@ -1,99 +0,0 @@-import { serve } from "https://deno.land/[email protected]/http/server.ts";-import { z } from "npm:zod@^3.24.1";--import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";-import { corsHeaders } from "../lib/headers.ts";-import { SchedulingEngine } from "../lib/scheduling/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.discriminatedUnion("type", [- z.object({- type: z.literal("schedule"),- jobId: z.string(),- companyId: z.string(),- userId: z.string(),- }),- z.object({- type: z.literal("dependencies"),- jobId: z.string(),- companyId: z.string(),- userId: z.string(),- }),-]);-serve(async (req: Request) => {- if (req.method === "OPTIONS") {- return new Response("ok", { headers: corsHeaders });- }- const payload = await req.json();-- try {- const validatedPayload = payloadValidator.parse(payload);- const { type, companyId, userId, jobId } = validatedPayload;-- const client = await getSupabaseServiceRole(- req.headers.get("Authorization"),- req.headers.get("carbon-key") ?? "",- companyId- );-- switch (validatedPayload.type) {- case "schedule": {- console.log({- function: "scheduler",- type,- jobId,- companyId,- userId,- });- const engine = new SchedulingEngine({ client, db, jobId, companyId });-- await engine.initialize();- await Promise.all([- engine.prioritize(SchedulingStrategy.LeastTime),- engine.assign(),- ]);-- await engine.addDependencies();-- return new Response(- JSON.stringify({- success: true,- }),- {- headers: { ...corsHeaders, "Content-Type": "application/json" },- status: 200,- }- );- }- case "dependencies": {- const engine = new SchedulingEngine({ client, db, jobId, companyId });-- await engine.initialize();- await engine.addDependencies();-- return new Response(- JSON.stringify({- success: true,- }),- {- headers: { ...corsHeaders, "Content-Type": "application/json" },- status: 200,- }- );- }- default: {- throw new Error(`Unsupported operation type: ${type}`);- }- }- } catch (err) {- console.error(err);- return new Response(JSON.stringify(err), {- headers: { ...corsHeaders, "Content-Type": "application/json" },- status: 500,- });- }-});diff --git a/packages/database/supabase/migrations/20251123000000_add-customer-name-to-operations.sql b/packages/database/supabase/migrations/20251123000000_add-customer-name-to-operations.sqlindex faee24f589..27995a49bf 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@@ -95,11 +95,13 @@ BEGINLEFT JOIN "customer" c ON rj."customerId" = c.idLEFT JOIN "salesOrder" so ON rj."salesOrderId" = so.idLEFT JOIN "modelUpload" mu ON i."modelUploadId" = mu.id- WHERE CASE- WHEN array_length(work_center_ids, 1) > 0 THEN jo."workCenterId" = ANY(work_center_ids)- ELSE TRUE+ WHERE CASE+ WHEN array_length(work_center_ids, 1) > 0 THEN+ jo."workCenterId" = ANY(work_center_ids) AND jo."status" != 'Done' AND jo."status" != 'Canceled'+ ELSE jo."status" != 'Done' AND jo."status" != 'Canceled'END- ORDER BY jo."priority";+ ORDER BY jo."startDate", jo."priority";+END;$$ LANGUAGE plpgsql;diff --git a/packages/jobs/trigger/recalculate.ts b/packages/jobs/trigger/recalculate.tsindex 47a7424f30..b1858a914e 100644--- a/packages/jobs/trigger/recalculate.ts+++ b/packages/jobs/trigger/recalculate.ts@@ -1,5 +1,6 @@import { getCarbonServiceRole } from "@carbon/auth";import type { FunctionsResponse } from "@supabase/functions-js";+import { FunctionRegion } from "@supabase/supabase-js";import { task } from "@trigger.dev/sdk";import { z } from "zod/v3";@@ -95,10 +96,14 @@ async function recalculateJobMakeMethodRequirements(userId: string;}) {- return client.functions.invoke("scheduler", {+ return client.functions.invoke("schedule", {body: {- type: "make-method-requirements",- ...params,+ mode: "initial",+ direction: "backward",+ jobId: params.id,+ companyId: params.companyId,+ userId: params.userId,},+ region: FunctionRegion.UsEast1,});}diff --git a/packages/jobs/trigger/reschedule-job.ts b/packages/jobs/trigger/reschedule-job.tsindex 74eead1cf9..3fe74be9ce 100644--- a/packages/jobs/trigger/reschedule-job.ts+++ b/packages/jobs/trigger/reschedule-job.ts@@ -4,48 +4,62 @@ import { getCarbonServiceRole } from "@carbon/auth";const serviceRole = getCarbonServiceRole();-const rescheduleJobSchema = z.object({+const scheduleJobSchema = z.object({jobId: z.string(),companyId: z.string(),userId: z.string(),+ mode: z.enum(["initial", "reschedule"]).default("reschedule"),+ direction: z.enum(["backward", "forward"]).default("backward"),});-export const rescheduleJob = task({- id: "reschedule-job",+/**+ * Unified scheduling task that handles both initial scheduling and rescheduling.+ * Uses the new unified scheduling engine endpoint.+ */+export const scheduleJob = task({+ id: "schedule-job",queue: {name: "scheduling",concurrencyLimit: 5,},- run: async (payload: z.infer<typeof rescheduleJobSchema>) => {- console.info(`🔰 Rescheduling job ${payload.jobId}`);+ run: async (payload: z.infer<typeof scheduleJobSchema>) => {+ const { jobId, companyId, userId, mode, direction } = payload;+ console.info(+ `🔰 ${mode === "initial" ? "Scheduling" : "Rescheduling"} job ${jobId}`+ );try {- const { data, error } = await serviceRole.functions.invoke("reschedule", {+ const { data, error } = await serviceRole.functions.invoke("schedule", {body: {- jobId: payload.jobId,- companyId: payload.companyId,- userId: payload.userId,+ jobId,+ companyId,+ userId,+ mode,+ direction,},});if (error) {- throw new Error(error.message || "Failed to reschedule job");+ throw new Error(error.message || `Failed to ${mode} schedule job`);}console.info(- `✅ Rescheduled: ${data.operationsUpdated} ops, ` +- `${data.workCentersAffected} WCs, ${data.conflictsDetected} conflicts`+ `✅ ${mode === "initial" ? "Scheduled" : "Rescheduled"}: ` ++ `${data.operationsScheduled} ops, ` ++ `${data.workCentersAffected.length} WCs, ` ++ `${data.conflictsDetected} conflicts`);return {success: true,- operationsUpdated: data.operationsUpdated,+ operationsScheduled: data.operationsScheduled,conflictsDetected: data.conflictsDetected,workCentersAffected: data.workCentersAffected,+ assemblyDepth: data.assemblyDepth,};} catch (error) {console.error(- `❌ Reschedule failed: ${+ `❌ ${mode === "initial" ? "Scheduling" : "Rescheduling"} failed: ${error instanceof Error ? error.message : String(error)}`);diff --git a/scripts/generate-job-dependencies.ts b/scripts/generate-job-dependencies.tsindex 591c2e45e1..11729d0011 100644--- a/scripts/generate-job-dependencies.ts+++ b/scripts/generate-job-dependencies.ts@@ -31,9 +31,10 @@ const supabaseAdmin = createClient(if (!jobs) throw new Error("No jobs found");for await (const job of jobs) {- const result = await supabaseAdmin.functions.invoke("scheduler", {+ const result = await supabaseAdmin.functions.invoke("schedule", {body: {- type: "dependencies",+ mode: "initial",+ direction: "backward",jobId: job.id,companyId: COMPANY_ID,userId: USER_ID,