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.

9.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 { carbon, respond } from "@carbon/api/carbon.server";
import { requirePermissions } from "@carbon/auth/auth.server";
import {
  dayBeforeCutover,
  isMigrationClearingZero
} from "@carbon/database/accounting-cutover";
import {
  getActivationReadiness,
  getLegacyDocumentCounts,
  getMigrationClearing,
  type LegacyDocumentFamily
} from "@carbon/database/accounting-cutover-reads";
import { ValidatedForm, validator } from "@carbon/form";
import { Alert, AlertDescription, AlertTitle } from "@carbon/react";
import type { MessageDescriptor } from "@lingui/core";
import { msg } from "@lingui/core/macro";
import { Trans, useLingui } from "@lingui/react/macro";
import { Fragment } from "react";
import { LuTriangleAlert } from "react-icons/lu";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { Link, useLoaderData } from "react-router";
import { Hidden, Input, Submit } from "~/components/Form";
import { SetupBody, SetupSection } from "~/components/Setup";
import {
  useCurrencyFormatter,
  useDateFormatter,
  usePermissions,
  useUser
} from "~/hooks";
import { activateAccountingValidator } from "~/modules/accounting/accounting.models";
import { getActivationCutover } from "~/modules/accounting/accounting.service";
import {
  ActivationFooter,
  activationStepPath
} from "~/modules/accounting/ui/Activation";
import { getDatabaseClient } from "~/services/database.server";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";

export const handle: Handle = {
  breadcrumb: msg`Enable`,
  to: path.to.accountingActivationStep("enable")
};

/** Opening items that are documents, not the inventory and asset totals. */
const AGGREGATE_ITEM_TYPES = new Set([
  "Inventory",
  "Fixed Asset Cost",
  "Accumulated Depreciation"
]);

/** A family of documents posted before Carbon kept journals. */
const LEGACY_FAMILY_LABELS: Record<LegacyDocumentFamily, MessageDescriptor> = {
  salesInvoices: msg`Sales invoices`,
  purchaseInvoices: msg`Purchase invoices`,
  memos: msg`Credit and debit memos`,
  charges: msg`Charges`,
  reimbursements: msg`Reimbursements`,
  payments: msg`Payments`,
  purchaseReceipts: msg`Purchase receipts`,
  salesReturnReceipts: msg`Sales return receipts`,
  salesShipments: msg`Sales shipments`,
  returnShipments: msg`Return shipments`,
  inventoryAdjustments: msg`Inventory adjustments and scrap`,
  inventoryCounts: msg`Inventory counts`,
  nonConformances: msg`Non-conformance and inspection scrap`,
  maintenanceConsumptions: msg`Maintenance parts`,
  jobConsumptions: msg`Job material issues`,
  jobOutputs: msg`Job completions`,
  depreciationRuns: msg`Depreciation runs`,
  assetDisposals: msg`Asset scrap disposals`,
  revenueRecognitionRuns: msg`Revenue recognition runs`
};

// Both summary lists share one fixed label column, so their values line up.
const SUMMARY_LIST_CLASS =
  "grid w-full max-w-xl grid-cols-[18rem_1fr] gap-x-8 gap-y-3 text-sm";

export async function loader({ request }: LoaderFunctionArgs) {
  const { client, companyId } = await requirePermissions(request, {
    view: "accounting"
  });
  const { cutoverDate } = await getActivationCutover(
    client,
    companyId,
    request
  );
  const db = getDatabaseClient();
  const [readiness, clearing, legacyCounts] = await Promise.all([
    getActivationReadiness(db, { companyId, cutoverDate }),
    getMigrationClearing(db, { companyId, cutoverDate }),
    getLegacyDocumentCounts(db, { companyId, cutoverDate })
  ]);
  return {
    cutoverDate,
    readinessPassed: readiness.passed,
    openItemCount: clearing.items.filter(
      (item) => !AGGREGATE_ITEM_TYPES.has(item.openItemType)
    ).length,
    migrationClearingTotal: clearing.total,
    // In the order the enable journals them.
    legacyDocuments: (
      Object.entries(legacyCounts) as [LegacyDocumentFamily, number][]
    )
      .filter(([, count]) => count > 0)
      .map(([family, count]) => ({ family, count }))
  };
}

/** Runs the one-way enable through the `activate-accounting` server function. */
export async function action(args: ActionFunctionArgs) {
  const input = await validator(activateAccountingValidator).request(args);
  if ("invalid" in input) return input.invalid;
  const api = await carbon(args.request);
  const result = await api.accounting.enableAccountingCutover(input.data);
  const { pathname, search } = new URL(args.request.url);
  return respond(args.request, result).redirect(path.to.accountingPeriods, {
    message: "Accounting is enabled",
    onError: `${pathname}${search}`
  });
}

/** Step 5: what the enable will do, and the one-way confirmation. */
export default function AccountingActivationEnableRoute() {
  const { t, i18n } = useLingui();
  const {
    cutoverDate,
    readinessPassed,
    openItemCount,
    migrationClearingTotal,
    legacyDocuments
  } = useLoaderData<typeof loader>();
  const { company } = useUser();
  const permissions = usePermissions();
  const formatter = useCurrencyFormatter();
  const { formatDate } = useDateFormatter();

  const isClearingZero = isMigrationClearingZero(migrationClearingTotal);
  const canEnable =
    readinessPassed &&
    isClearingZero &&
    permissions.can("update", "accounting");

  return (
    <>
      <SetupBody>
        <SetupSection title={<Trans>Summary</Trans>}>
          <dl className={SUMMARY_LIST_CLASS}>
            <dt className="text-muted-foreground">
              <Trans>Cutover date</Trans>
            </dt>
            <dd>{formatDate(cutoverDate)}</dd>
            <dt className="text-muted-foreground">
              <Trans>Opening balances as of</Trans>
            </dt>
            <dd>{formatDate(dayBeforeCutover(cutoverDate))}</dd>
            <dt className="text-muted-foreground">
              <Trans>Open items</Trans>
            </dt>
            <dd className="tabular-nums">{openItemCount}</dd>
            <dt className="text-muted-foreground">
              <Trans>Migration Clearing</Trans>
            </dt>
            <dd
              className={
                isClearingZero
                  ? "tabular-nums"
                  : "tabular-nums text-destructive"
              }
            >
              {formatter.format(migrationClearingTotal)}
            </dd>
          </dl>
          {!readinessPassed && (
            <p className="text-sm text-destructive">
              <Trans>
                A readiness check fails.{" "}
                <Link
                  to={activationStepPath("readiness", cutoverDate)}
                  className="underline"
                >
                  Go to Readiness
                </Link>
              </Trans>
            </p>
          )}
          {!isClearingZero && (
            <p className="text-sm text-destructive">
              <Trans>
                Migration Clearing must total zero.{" "}
                <Link
                  to={activationStepPath("trial-balance", cutoverDate)}
                  className="underline"
                >
                  Go to Trial Balance
                </Link>
              </Trans>
            </p>
          )}
        </SetupSection>

        {legacyDocuments.length > 0 && (
          <SetupSection
            title={<Trans>Documents Posted Before Carbon Kept Journals</Trans>}
            description={
              <Trans>
                Carbon writes their journals when you enable accounting, with
                today's accounts and costs.
              </Trans>
            }
          >
            <dl className={SUMMARY_LIST_CLASS}>
              {legacyDocuments.map(({ family, count }) => (
                <Fragment key={family}>
                  <dt className="text-muted-foreground">
                    {i18n._(LEGACY_FAMILY_LABELS[family])}
                  </dt>
                  <dd className="tabular-nums">{count}</dd>
                </Fragment>
              ))}
            </dl>
          </SetupSection>
        )}

        <SetupSection title={<Trans>Enable Accounting</Trans>}>
          <Alert variant="destructive" className="max-w-xl">
            <LuTriangleAlert className="h-4 w-4" />
            <AlertTitle>
              <Trans>This cannot be undone.</Trans>
            </AlertTitle>
            <AlertDescription>
              <Trans>
                Carbon posts the opening journal, posts every journal dated on
                or after the cutover date, and closes the periods before it.
              </Trans>
            </AlertDescription>
          </Alert>
          <ValidatedForm
            validator={activateAccountingValidator}
            method="post"
            action={activationStepPath("enable", cutoverDate)}
            defaultValues={{ cutoverDate, confirmation: "" }}
            className="flex w-full max-w-xl flex-col gap-4"
          >
            <Hidden name="cutoverDate" />
            <Input
              name="confirmation"
              label={t`Type ${company.name} to confirm`}
              autoComplete="off"
            />
            <div>
              <Submit isDisabled={!canEnable}>
                <Trans>Enable accounting</Trans>
              </Submit>
            </div>
          </ValidatedForm>
        </SetupSection>
      </SetupBody>
      <ActivationFooter step="enable" cutoverDate={cutoverDate} />
    </>
  );
}