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.

3.3 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 { validator } from "@carbon/form";
import { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs } from "react-router";
import { revisionValidator } from "~/modules/items/items.models";
import {
  createRevision,
  getItem,
  requireItemChangeNoticeUnlocked
} from "~/modules/items/items.service";
import { getDatabaseClient } from "~/services/database.server";
import { path } from "~/utils/path";

const logger = getLogger("erp", "items-revisions-new");

export async function action({ request }: ActionFunctionArgs) {
  assertIsPost(request);
  const { client, companyId, userId } = await requirePermissions(request, {
    create: "parts"
  });

  const formData = await request.formData();
  const validation = await validator(revisionValidator).validate(formData);

  if (validation.error) {
    return { success: false, message: "Invalid form data" };
  }

  if (!validation.data.copyFromId) {
    return {
      success: false,
      message: "Copy from ID is required for a new revision"
    };
  }

  const changeNoticeLock = await requireItemChangeNoticeUnlocked(client, {
    itemId: validation.data.copyFromId,
    companyId
  });

  if (changeNoticeLock) {
    return { success: false, message: changeNoticeLock.error.message };
  }

  const currentItem = await getItem(client, validation.data.copyFromId);

  if (currentItem.error) {
    return { success: false, message: "Failed to get current item" };
  }

  // createRevision writes through the service role with the SOURCE item's
  // companyId, and the RLS read above admits any company the user belongs to.
  if (currentItem.data.companyId !== companyId) {
    logger.error("Revision source item is not in the caller's company", {
      companyId,
      itemId: validation.data.copyFromId
    });
    return { success: false, message: "Failed to get current item" };
  }

  const result = await createRevision(
    getCarbonServiceRole(),
    getDatabaseClient(),
    {
      item: currentItem.data,
      revision: validation.data.revision,
      createdBy: userId
    }
  );

  if (result.error) {
    logger.error("Failed to create revision", {
      companyId,
      itemId: validation.data.copyFromId,
      error: result.error
    });
    return { success: false, message: "Failed to create revision" };
  }

  const link = (() => {
    switch (currentItem.data.type) {
      case "Part":
        return path.to.partDetails(result.data.id);
      case "Material":
        return path.to.materialDetails(result.data.id);
      case "Tool":
        return path.to.toolDetails(result.data.id);
      case "Consumable":
        return path.to.consumableDetails(result.data.id);
      case "Service":
        return path.to.serviceDetails(result.data.id);
      default:
        return path.to.items;
    }
  })();

  // newItemId lets the caller (e.g. the new-revision modal's "open change notice"
  // option) act on the created revision without parsing it out of `link`.
  return { success: true, link, newItemId: result.data.id };
}