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.

1.9 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.

import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { runLocationSchedule } from "@carbon/planning";
import type { ActionFunctionArgs } from "react-router";
import { requireCompanyRecord } from "~/modules/shared/shared.service";
import { getDatabaseClient } from "~/services/database.server";

export async function action({ request }: ActionFunctionArgs) {
  assertIsPost(request);

  const url = new URL(request.url);
  const locationId = url.searchParams.get("location");

  const { companyId, userId } = await requirePermissions(request, {
    update: "production"
  });

  if (!locationId) {
    return { success: false, error: "A location is required to regenerate" };
  }

  // The location id comes from the query string and the run below is
  // privileged (Kysely + service role), so prove it is this company's first.
  await requireCompanyRecord(getCarbonServiceRole(), "location", companyId, {
    id: locationId
  });

  // Regenerate the whole location's forecast IN-PROCESS (Node). Awaited before
  // we return, so the fetcher's revalidation reads fully-committed
  // reservations. Service-role client for the privileged execution; the route's
  // requirePermissions is the gate.
  try {
    const result = await runLocationSchedule({
      db: getDatabaseClient(),
      client: getCarbonServiceRole(),
      locationId,
      companyId,
      userId
    });
    return { success: true, error: null, ...result };
  } catch (err) {
    return {
      success: false,
      error:
        err instanceof Error ? err.message : "Failed to regenerate schedule"
    };
  }
}