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.4 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, notFound, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { redirect } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import {
  deleteRentalAgreementLine,
  getRentalAgreement,
  getRentalAgreementLine
} from "~/modules/sales/sales.service";
import { path, requestReferrer } from "~/utils/path";

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

  const { id, lineId } = params;
  if (!id) throw notFound("id not found");
  if (!lineId) throw notFound("lineId not found");

  const [agreement, line] = await Promise.all([
    getRentalAgreement(client, id, companyId),
    getRentalAgreementLine(client, lineId, companyId)
  ]);

  if (
    agreement.error ||
    agreement.data?.companyId !== companyId ||
    !line.data ||
    line.data.rentalAgreementId !== id
  ) {
    throw redirect(
      path.to.rentalAgreementDetails(id),
      await flash(
        request,
        error(null, "This unit does not belong to this rental agreement")
      )
    );
  }

  // An activated line has billing periods behind it — return the unit or
  // cancel the agreement instead.
  if (agreement.data.status !== "Draft") {
    throw redirect(
      path.to.rentalAgreementDetails(id),
      await flash(
        request,
        error(null, "Units can only be removed from a Draft rental agreement")
      )
    );
  }

  const result = await deleteRentalAgreementLine(client, lineId, companyId);
  if (result.error) {
    throw redirect(
      path.to.rentalAgreementDetails(id),
      await flash(request, error(result.error, "Failed to remove unit"))
    );
  }

  // Back where the unit was removed from (the setup wizard's Units step),
  // unless that was the removed unit's own page.
  const referrer = requestReferrer(request);
  throw redirect(
    referrer && !referrer.includes(lineId)
      ? referrer
      : path.to.rentalAgreementDetails(id),
    await flash(request, success("Removed unit from the agreement"))
  );
}