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.

20.5 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 } from "@carbon/api/carbon.server";
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import {
  getLegacyDocumentCounts,
  hasLegacyDocuments
} from "@carbon/database/accounting-cutover-reads";
import { ValidatedForm, validator } from "@carbon/form";
import { useAction } from "@carbon/query";
import {
  Alert,
  AlertDescription,
  Button,
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
  HStack,
  ScrollArea,
  Switch,
  toast,
  VStack
} from "@carbon/react";
import { INPUT_FORMAT, INPUT_STEP, redirect } from "@carbon/utils";
import { msg } from "@lingui/core/macro";
import { Plural, Trans, useLingui } from "@lingui/react/macro";
import { useCallback } from "react";
import { LuTriangleAlert } from "react-icons/lu";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { Link, useLoaderData } from "react-router";
import { z } from "zod";
import { zfd } from "zod-form-data";
import {
  Account,
  Boolean as BooleanInput,
  Hidden,
  Number as NumberInput,
  Submit
} from "~/components/Form";
import { SettingsPage, SettingsPageHeading } from "~/components/SettingsPage";
import { useDateFormatter, usePermissions } from "~/hooks";
import { useResolved } from "~/hooks/useResolved";
import { getDefaultAccounts } from "~/modules/accounting/accounting.service";
import { hasAccountingCutover } from "~/modules/accounting/accounting.utils";
import { settingsToggle } from "~/modules/settings/settings.models";
import { getCompanySettings } from "~/modules/settings/settings.service";
import { getDatabaseClient } from "~/services/database.server";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";

const JOURNAL_LEGACY_INTENT = "journal-legacy";

const taxDepreciationSettingsValidator = z.object({
  intent: z.literal("assetTaxDepreciation"),
  assetTaxRate: zfd.numeric(z.number().min(0).max(100)),
  deferredTaxLiabilityAccountId: z.string().min(1, {
    message: "Deferred tax liability account is required"
  }),
  deferredTaxExpenseAccountId: z.string().min(1, {
    message: "Deferred tax expense account is required"
  })
});

const leasePolicySettingsValidator = z.object({
  intent: z.literal("leasePolicy"),
  leaseMajorPartThresholdPercent: zfd.numeric(
    z
      .number()
      .gt(0, { message: "Threshold must be above 0" })
      .max(100, { message: "Threshold cannot exceed 100" })
  ),
  leaseSubstantiallyAllThresholdPercent: zfd.numeric(
    z
      .number()
      .gt(0, { message: "Threshold must be above 0" })
      .max(100, { message: "Threshold cannot exceed 100" })
  ),
  leaseDefaultDiscountRate: zfd.numeric(
    z.number().min(0, { message: "Discount rate cannot be negative" })
  ),
  leaseIncrementalBorrowingRate: zfd.numeric(
    z.number().min(0, { message: "Borrowing rate cannot be negative" })
  ),
  leaseShortTermExpedient: zfd.checkbox(),
  leaseReminderDays: zfd.numeric(
    z
      .number()
      .int({ message: "Reminder days must be a whole number" })
      .min(0, { message: "Reminder days cannot be negative" })
  )
});

export const handle: Handle = {
  breadcrumb: msg`Accounting`,
  to: path.to.accountingSettings
};

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

  const [companySettings, accountDefaults] = await Promise.all([
    getCompanySettings(client, companyId),
    getDefaultAccounts(client, companyId)
  ]);

  if (!companySettings.data)
    throw redirect(
      path.to.settings,
      await flash(
        request,
        error(companySettings.error, "Failed to get company settings")
      )
    );

  // Documents posted on or after the cutover with no journal: a company
  // enabled before the enable wrote them. Whether there are any is awaited:
  // it decides whether the repair alert exists, and an alert that arrives
  // after the first paint pushes the cards below it down. The count only
  // fills in the alert's text, so it is streamed.
  const cutoverDate = companySettings.data.accountingCutoverDate;
  const db = getDatabaseClient();
  const hasLegacy = cutoverDate
    ? await hasLegacyDocuments(db, { companyId, cutoverDate })
    : false;

  return {
    companySettings: companySettings.data,
    accountDefaults: accountDefaults.data,
    legacyDocumentsExist: hasLegacy,
    legacyDocumentCount:
      hasLegacy && cutoverDate
        ? getLegacyDocumentCounts(db, { companyId, cutoverDate }).then(
            (counts) =>
              Object.values(counts).reduce((sum, count) => sum + count, 0)
          )
        : null
  };
}

// One form per card, told apart by its intent: each becomes the fields of
// `updateAccountingSettings` it saves (the operation drops `intent`), or the
// missing-journals repair.
const accountingSettingsForm = z.discriminatedUnion("intent", [
  z
    .object({ intent: z.literal(JOURNAL_LEGACY_INTENT) })
    .transform(() => ({ writeMissingJournals: true as const })),
  settingsToggle("showCurrencyTrailingZeros", "showCurrencyTrailingZeros"),
  settingsToggle(
    "assetTaxDepreciationEnabled",
    "assetTaxDepreciationEnabled"
  ).transform(({ assetTaxDepreciationEnabled }) => ({
    assetTaxDepreciationEnabled,
    assetTaxRate: null
  })),
  leasePolicySettingsValidator,
  taxDepreciationSettingsValidator.transform(({ intent: _, ...tax }) => ({
    ...tax,
    assetTaxDepreciationEnabled: true
  }))
]);

export async function action(args: ActionFunctionArgs) {
  const input = await validator(accountingSettingsForm).request(args);
  if ("invalid" in input) return input.invalid;
  const api = await carbon(args.request);
  if ("writeMissingJournals" in input.data) {
    return api.settings.writeMissingJournals({});
  }
  return api.settings.updateAccountingSettings(input.data);
}

export default function AccountingSettingsRoute() {
  const {
    companySettings,
    accountDefaults,
    legacyDocumentsExist,
    legacyDocumentCount: legacyDocumentCountPromise
  } = useLoaderData<typeof loader>();
  const legacyDocumentCount = useResolved(legacyDocumentCountPromise, null);
  const permissions = usePermissions();
  const { t } = useLingui();
  const legacyFetcher = useAction<typeof action>({
    onSuccess: ({ data }) => {
      if (!data || !("documents" in data)) return;
      toast.success(
        data.documents === 1
          ? t`Wrote the missing journal of 1 document`
          : t`Wrote the missing journals of ${data.documents} documents`
      );
    }
  });
  const fetcher = useAction<typeof action>({
    onSuccess: ({ data }) => {
      if (!data || "documents" in data) return;
      toast.success(
        data.showCurrencyTrailingZeros !== undefined
          ? t`Currency display updated`
          : t`Fixed asset settings updated`
      );
    }
  });
  const taxFetcher = useAction<typeof action>({
    onSuccess: () => toast.success(t`Fixed asset settings updated`)
  });
  const leaseFetcher = useAction<typeof action>({
    onSuccess: () => toast.success(t`Lease policy updated`)
  });
  const { formatDate } = useDateFormatter();

  const taxEnabled = companySettings.assetTaxDepreciationEnabled ?? false;

  const accountingSetUp = hasAccountingCutover(companySettings);
  const cutoverDate = formatDate(companySettings.accountingCutoverDate);

  const handleTrailingZerosToggle = useCallback(
    (showTrailingZeros: boolean) => {
      fetcher.submit(
        {
          intent: "showCurrencyTrailingZeros",
          enabled: String(showTrailingZeros)
        },
        { method: "POST" }
      );
    },
    [fetcher]
  );

  const handleTaxDepreciationToggle = useCallback(
    (checked: boolean) => {
      fetcher.submit(
        { intent: "assetTaxDepreciationEnabled", enabled: String(checked) },
        { method: "POST" }
      );
    },
    [fetcher]
  );

  return (
    <ScrollArea className="w-full h-[calc(100dvh-var(--topbar-height)-var(--content-inset))]">
      <SettingsPage className="gap-4">
        <SettingsPageHeading>
          <Trans>Accounting</Trans>
        </SettingsPageHeading>

        <Card>
          <CardHeader>
            <CardTitle>
              <Trans>General Ledger</Trans>
            </CardTitle>
            <CardDescription>
              <Trans>
                Accrual accounting with journal entries, financial reports, and
                general ledger posting.
              </Trans>
            </CardDescription>
          </CardHeader>
          <CardContent>
            <HStack className="justify-between items-center">
              <VStack className="items-start" spacing={1}>
                <span className="font-medium">
                  {accountingSetUp ? (
                    <Trans>Accounting since {cutoverDate}</Trans>
                  ) : (
                    <Trans>Accounting is not set up</Trans>
                  )}
                </span>
                <span className="text-sm text-muted-foreground">
                  {accountingSetUp ? (
                    <Trans>
                      Transactions will create journal entries and update the
                      general ledger.
                    </Trans>
                  ) : (
                    <Trans>
                      Transactions post provisional journal entries until you
                      set up accounting.
                    </Trans>
                  )}
                </span>
              </VStack>
              {!accountingSetUp && (
                <Button asChild>
                  <Link to={path.to.accountingActivation}>
                    <Trans>Set up accounting</Trans>
                  </Link>
                </Button>
              )}
            </HStack>
            {accountingSetUp && legacyDocumentsExist && (
              // The icon keeps the Alert's icon column; the text and the
              // button share the description, one row centred on the icon.
              <Alert variant="warning" className="mt-4 items-center">
                <LuTriangleAlert />
                <AlertDescription className="flex items-center justify-between gap-4 text-sm">
                  <span>
                    {legacyDocumentCount === null ? (
                      <Trans>
                        Documents posted before Carbon kept journals have no
                        journal.
                      </Trans>
                    ) : (
                      <Plural
                        value={legacyDocumentCount}
                        one="# document posted before Carbon kept journals has no journal."
                        other="# documents posted before Carbon kept journals have no journal."
                      />
                    )}
                  </span>
                  <legacyFetcher.Form method="post" className="shrink-0">
                    <input
                      type="hidden"
                      name="intent"
                      value={JOURNAL_LEGACY_INTENT}
                    />
                    {/* A secondary button sets no text colour of its own, so
                        it would take the alert's amber. */}
                    <Button
                      type="submit"
                      variant="secondary"
                      className="text-foreground"
                      isLoading={legacyFetcher.state !== "idle"}
                      isDisabled={
                        legacyFetcher.state !== "idle" ||
                        !permissions.can("update", "settings") ||
                        !permissions.can("update", "accounting")
                      }
                    >
                      <Trans>Write missing journals</Trans>
                    </Button>
                  </legacyFetcher.Form>
                </AlertDescription>
              </Alert>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>
              <Trans>Show Trailing Zeros</Trans>
            </CardTitle>
            <CardDescription>
              <Trans>
                Pad amounts to their currency's decimal places, so 300 appears
                as 300.00 and columns of figures stay aligned. Turn this off to
                show only the digits that carry value. Printed documents and
                stored amounts are unaffected either way.
              </Trans>
            </CardDescription>
          </CardHeader>
          <CardContent>
            <HStack className="justify-between items-center">
              <VStack className="items-start" spacing={1}>
                <span className="font-medium">
                  {companySettings.showCurrencyTrailingZeros ? (
                    <Trans>Trailing zeros are shown</Trans>
                  ) : (
                    <Trans>Trailing zeros are hidden</Trans>
                  )}
                </span>
                <span className="text-sm text-muted-foreground">
                  {companySettings.showCurrencyTrailingZeros ? (
                    <Trans>
                      Amounts are padded to their currency's decimal places.
                    </Trans>
                  ) : (
                    <Trans>
                      Amounts show only the digits that carry value.
                    </Trans>
                  )}
                </span>
              </VStack>
              <Switch
                checked={companySettings.showCurrencyTrailingZeros}
                onCheckedChange={handleTrailingZerosToggle}
                disabled={fetcher.state !== "idle"}
              />
            </HStack>
          </CardContent>
        </Card>

        <ValidatedForm
          className="w-full"
          validator={leasePolicySettingsValidator}
          method="post"
          fetcher={leaseFetcher}
          defaultValues={{
            intent: "leasePolicy",
            leaseMajorPartThresholdPercent:
              companySettings.leaseMajorPartThresholdPercent,
            leaseSubstantiallyAllThresholdPercent:
              companySettings.leaseSubstantiallyAllThresholdPercent,
            leaseDefaultDiscountRate: companySettings.leaseDefaultDiscountRate,
            leaseIncrementalBorrowingRate:
              companySettings.leaseIncrementalBorrowingRate,
            leaseShortTermExpedient: companySettings.leaseShortTermExpedient,
            leaseReminderDays: companySettings.leaseReminderDays
          }}
        >
          {/* Linked from a lease that needs the short-term expedient. */}
          <Card id="lease-classification">
            <CardHeader>
              <CardTitle>
                <Trans>Lease Classification</Trans>
              </CardTitle>
              <CardDescription>
                <Trans>
                  A lease is a sales-type (lessor) or finance (lessee) lease
                  when any ASC 842 test is met. These thresholds set tests (c)
                  and (d). The lessor discount rate is the default for new
                  rental agreements; the incremental borrowing rate is the
                  default for new leases.
                </Trans>
              </CardDescription>
            </CardHeader>
            <CardContent>
              <Hidden name="intent" value="leasePolicy" />
              <div className="grid w-full grid-cols-1 gap-4 lg:grid-cols-3">
                <NumberInput
                  name="leaseMajorPartThresholdPercent"
                  label={t`Major Part of Economic Life (%)`}
                  minValue={0}
                  maxValue={100}
                  step={INPUT_STEP.percent}
                  formatOptions={INPUT_FORMAT.percentPoints}
                />
                <NumberInput
                  name="leaseSubstantiallyAllThresholdPercent"
                  label={t`Substantially All of Fair Value (%)`}
                  minValue={0}
                  maxValue={100}
                  step={INPUT_STEP.percent}
                  formatOptions={INPUT_FORMAT.percentPoints}
                />
                <NumberInput
                  name="leaseDefaultDiscountRate"
                  label={t`Lessor Discount Rate (%)`}
                  minValue={0}
                  step={INPUT_STEP.percent}
                  formatOptions={INPUT_FORMAT.percentPoints}
                />
                <NumberInput
                  name="leaseIncrementalBorrowingRate"
                  label={t`Incremental Borrowing Rate (%)`}
                  minValue={0}
                  step={INPUT_STEP.percent}
                  formatOptions={INPUT_FORMAT.percentPoints}
                />
                <NumberInput
                  name="leaseReminderDays"
                  label={t`Lease Reminder Days`}
                  minValue={0}
                  helperText={t`Days before a lease's notice or end date that its owner is reminded.`}
                />
                <BooleanInput
                  name="leaseShortTermExpedient"
                  label={t`Short-Term Lease Expedient`}
                  description={t`Leases of 12 months or less with no reasonably certain purchase option are expensed as paid.`}
                />
              </div>
            </CardContent>
            <CardFooter>
              <Submit isDisabled={leaseFetcher.state !== "idle"}>
                <Trans>Save</Trans>
              </Submit>
            </CardFooter>
          </Card>
        </ValidatedForm>

        <ValidatedForm
          className="w-full"
          validator={taxDepreciationSettingsValidator}
          method="post"
          fetcher={taxFetcher}
          defaultValues={{
            intent: "assetTaxDepreciation",
            // Already a NUMERIC column; the parseFloat this replaced only
            // worked because JS coerced the number back to a string first.
            assetTaxRate: companySettings.assetTaxRate ?? 0,
            deferredTaxLiabilityAccountId:
              (accountDefaults as any)?.deferredTaxLiabilityAccountId ?? "",
            deferredTaxExpenseAccountId:
              (accountDefaults as any)?.deferredTaxExpenseAccountId ?? ""
          }}
        >
          <Card>
            <CardHeader>
              <CardTitle>
                <Trans>Fixed Assets</Trans>
              </CardTitle>
              <CardDescription>
                <Trans>
                  Track tax depreciation separately from book depreciation and
                  automatically post deferred tax liability entries.
                </Trans>
              </CardDescription>
            </CardHeader>
            <CardContent>
              <VStack spacing={4}>
                <HStack className="w-full justify-between items-center">
                  <VStack className="items-start" spacing={1}>
                    <span className="font-medium">
                      <Trans>Track tax depreciation separately</Trans>
                    </span>
                    <span className="text-sm text-muted-foreground">
                      <Trans>
                        Enable to configure tax-specific depreciation methods on
                        asset classes (e.g., MACRS, accelerated).
                      </Trans>
                    </span>
                  </VStack>
                  <Switch
                    checked={taxEnabled}
                    onCheckedChange={handleTaxDepreciationToggle}
                  />
                </HStack>
                {taxEnabled && (
                  <VStack spacing={4} className="pt-4 border-t">
                    <Hidden name="intent" value="assetTaxDepreciation" />
                    <NumberInput
                      name="assetTaxRate"
                      label="Tax Rate (%)"
                      minValue={0}
                      maxValue={100}
                    />
                    <Account
                      name="deferredTaxLiabilityAccountId"
                      label="Deferred Tax Liability Account"
                      classes={["Liability"]}
                    />
                    <Account
                      name="deferredTaxExpenseAccountId"
                      label="Deferred Tax Expense Account"
                      classes={["Expense"]}
                    />
                  </VStack>
                )}
              </VStack>
            </CardContent>
            {taxEnabled && (
              <CardFooter>
                <Submit isDisabled={taxFetcher.state !== "idle"}>
                  <Trans>Save</Trans>
                </Submit>
              </CardFooter>
            )}
          </Card>
        </ValidatedForm>
      </SettingsPage>
    </ScrollArea>
  );
}