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.

2.2 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, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { deleteDemandProjections } from "@carbon/ee/forecast.server";
import { requireFeature } from "@carbon/ee/plan.server";
import { datetime, redirect } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import {
  getLocationTimeZone,
  getOrCreatePeriods
} from "~/modules/shared/shared.service";
import { getDatabaseClient } from "~/services/database.server";
import { path } from "~/utils/path";

export async function action({ request, params }: ActionFunctionArgs) {
  assertIsPost(request);
  const { client, companyId } = await requirePermissions(request, {
    delete: "production"
  });

  await requireFeature({
    request,
    client,
    companyId,
    feature: "FORECAST",
    redirectTo: path.to.demandProjections
  });

  const { itemId, locationId } = params;

  if (!itemId || !locationId) {
    return data(
      {},
      await flash(
        request,
        error("Item ID and Location ID are required", "Missing parameters")
      )
    );
  }

  // Get current date to determine future periods
  const periods = await getOrCreatePeriods(
    getDatabaseClient(),
    datetime.today(await getLocationTimeZone(client, locationId, companyId)),
    52
  );

  // Only delete projections for future periods (current week and beyond)
  const futurePeriodIds = periods.map((p) => p.id);

  const result = await deleteDemandProjections(client, {
    itemId,
    locationId,
    companyId,
    futurePeriodIds
  });

  if (result.error) {
    return data(
      {},
      await flash(
        request,
        error("Failed to delete demand projections", "Delete failed")
      )
    );
  }

  return redirect(
    path.to.demandProjections + `?location=${locationId}`,
    await flash(request, success("Demand projections deleted successfully"))
  );
}