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.

4.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, error, notFound, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
import { datetime, getErrorMessage, redirect } from "@carbon/utils";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { useLoaderData, useNavigate } from "react-router";
import { fixedAssetCapitalizeCipValidator } from "~/modules/accounting/accounting.models";
import {
  getFixedAsset,
  getFixedAssetCipCosts,
  invokeAssetTransfer
} from "~/modules/accounting/accounting.service";
import { FixedAssetCapitalizeCipForm } from "~/modules/accounting/ui/FixedAssets";
import { getCompanyTimeZone } from "~/modules/shared/shared.service";
import { getDatabaseClient } from "~/services/database.server";
import { path } from "~/utils/path";

export async function loader({ request, params }: LoaderFunctionArgs) {
  const { client, companyId } = await requirePermissions(request, {
    view: "accounting"
  });

  const { fixedAssetId } = params;
  if (!fixedAssetId) throw notFound("fixedAssetId not found");

  const [asset, cipCosts, assetClasses, timeZone] = await Promise.all([
    getFixedAsset(client, fixedAssetId, companyId),
    getFixedAssetCipCosts(client, fixedAssetId, companyId),
    // The in-service classes an asset under construction can move into.
    // `getFixedAssetClassesList` does not select `isConstructionInProgress`,
    // so the filter is applied here (same select as `x+/job+/new.tsx`).
    client
      .from("fixedAssetClass")
      .select("id, name")
      .eq("companyId", companyId)
      .eq("isConstructionInProgress", false)
      .order("name"),
    getCompanyTimeZone(client, companyId)
  ]);

  if (asset.error) {
    throw redirect(
      path.to.fixedAssets,
      await flash(request, error(asset.error, "Failed to get fixed asset"))
    );
  }

  const assetClass = asset.data.fixedAssetClass as {
    name: string;
    isConstructionInProgress: boolean;
  } | null;

  if (
    !assetClass?.isConstructionInProgress ||
    asset.data.status !== "Under Construction"
  ) {
    throw redirect(
      path.to.fixedAsset(fixedAssetId),
      await flash(
        request,
        error(null, "Only an asset under construction can be capitalized")
      )
    );
  }

  const totalCost = (cipCosts.data ?? []).reduce(
    (sum, cost) => sum + Number(cost.amount),
    0
  );

  return {
    initialValues: {
      toClassId: "",
      inServiceDate: datetime.today(timeZone).toString()
    },
    assetClasses: assetClasses.data ?? [],
    totalCost,
    cipClassName: assetClass.name
  };
}

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

  const { fixedAssetId } = params;
  if (!fixedAssetId) throw notFound("fixedAssetId not found");

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

  if (validation.error) {
    return validationError(validation.error);
  }

  const result = await invokeAssetTransfer(client, getDatabaseClient(), {
    type: "capitalizeCip",
    companyId,
    userId,
    fixedAssetId,
    ...validation.data
  });

  if (result.error) {
    throw redirect(
      path.to.fixedAsset(fixedAssetId),
      await flash(
        request,
        error(
          result.error,
          getErrorMessage(result.error, "Failed to capitalize the asset")
        )
      )
    );
  }

  throw redirect(
    path.to.fixedAsset(fixedAssetId),
    await flash(request, success("Asset capitalized"))
  );
}

export default function CapitalizeCipFixedAssetRoute() {
  const { initialValues, assetClasses, totalCost, cipClassName } =
    useLoaderData<typeof loader>();
  const navigate = useNavigate();

  return (
    <FixedAssetCapitalizeCipForm
      initialValues={initialValues}
      assetClasses={assetClasses}
      totalCost={totalCost}
      cipClassName={cipClassName}
      onClose={() => navigate(-1)}
    />
  );
}