Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat: create demand periods dynamically

Brad Barbina2e0c9e55535
diff --git a/packages/database/supabase/functions/demand-forecast/index.ts b/packages/database/supabase/functions/demand-forecast/index.ts
index dd19238ece..b0d7814164 100644
--- a/packages/database/supabase/functions/demand-forecast/index.ts
+++ b/packages/database/supabase/functions/demand-forecast/index.ts
@@ -1,5 +1,4 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts";
-import { Kysely } from "https://esm.sh/[email protected]";
import {
getLocalTimeZone,
today as getToday,
@@ -8,6 +7,7 @@ import {
} from "npm:@internationalized/date";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
+import { Kysely } from "https://esm.sh/v135/[email protected]/dist/cjs/kysely.d.ts";
import z from "npm:zod@^3.24.1";
import { corsHeaders } from "../lib/headers.ts";
import { Database } from "../lib/types.ts";
@@ -48,10 +48,11 @@ serve(async (req: Request) => {
const payload = await req.json();
const { type, companyId, userId } = payloadValidator.parse(payload);
- const today = getToday(getLocalTimeZone());
- const startDate = startOfWeek(today, "en-US");
- const endDate = startDate.add({ weeks: WEEKS_TO_FORECAST });
- const periods = await getOrCreateDemandPeriods(db, startDate, endDate);
+ const today = getToday(getLocalTimeZone()).add({ months: -2 });
+ const periods = getStartAndEndDates(today, "Week");
+ const demandPeriods = await getOrCreateDemandPeriods(db, periods, "Week");
+
+ console.log({ demandPeriods: demandPeriods.length });
try {
switch (type) {
@@ -86,16 +87,93 @@ serve(async (req: Request) => {
}
});
-const demandPeriodValidator = z.object({
- id: z.string(),
- startDate: z.string(),
- endDate: z.string(),
- periodType: z.enum(["Week", "Day", "Month"]),
- createdAt: z.string(),
-});
+function getStartAndEndDates(
+ today: CalendarDate,
+ groupBy: "Week" | "Day" | "Month"
+): { startDate: string; endDate: string }[] {
+ const periods: { startDate: string; endDate: string }[] = [];
+ const start = startOfWeek(today, "en-US");
+ const end = start.add({ weeks: WEEKS_TO_FORECAST });
+
+ switch (groupBy) {
+ case "Week": {
+ let currentStart = start;
+ while (currentStart.compare(end) < 0) {
+ const periodEnd = currentStart.add({ days: 6 });
+ periods.push({
+ startDate: currentStart.toString(),
+ endDate: periodEnd.toString(),
+ });
+ currentStart = periodEnd.add({ days: 1 });
+ }
-async function getDemandPeriods(
+ return periods;
+ }
+ case "Month": {
+ throw new Error("Not implemented");
+ }
+ case "Day": {
+ throw new Error("Not implemented");
+ }
+ default: {
+ throw new Error("Invalid groupBy");
+ }
+ }
+}
+async function getOrCreateDemandPeriods(
db: Kysely<DB>,
- startDate: CalendarDate,
- endDate: CalendarDate
-): { startDate: string; endDate: string }[] {}
+ periods: { startDate: string; endDate: string }[],
+ periodType: "Week" | "Day" | "Month"
+) {
+ // Get all existing periods for these dates
+ const existingPeriods = await db
+ .selectFrom("demandPeriod")
+ .selectAll()
+ .where(
+ "startDate",
+ "in",
+ periods.map((p) => p.startDate)
+ )
+ .where("periodType", "=", periodType)
+ .execute();
+
+ console.log({
+ existingPeriods: existingPeriods.length,
+ periods: periods.length,
+ });
+
+ // If we found all periods, return them
+ if (existingPeriods.length === periods.length) {
+ return existingPeriods;
+ }
+
+ // Create map of existing periods by start date
+ const existingPeriodMap = new Map(
+ // @ts-ignore - we are getting Date objects here
+ existingPeriods.map((p) => [p.startDate?.toISOString().split("T")[0], p])
+ );
+
+ // Find which periods need to be created
+ const periodsToCreate = periods.filter(
+ (period) => !existingPeriodMap.has(period.startDate)
+ );
+
+ // Create missing periods in a transaction
+ const created = await db.transaction().execute(async (trx) => {
+ return trx
+ .insertInto("demandPeriod")
+ .values(
+ periodsToCreate.map((period) => ({
+ startDate: period.startDate,
+ endDate: period.endDate,
+ periodType,
+ createdAt: new Date().toISOString(),
+ }))
+ )
+ .returningAll()
+ .execute();
+ });
+
+ // Return all periods (existing + newly created)
+ return [...existingPeriods, ...created];
+}