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.

fix(erp): respect the company's currency settings on the digital quote

Sidwebworksbedc3b50a493
diff --git a/.claude/rules/numeric-precision.md b/.claude/rules/numeric-precision.md
index 1266a983f5..98e200a056 100644
--- a/.claude/rules/numeric-precision.md
+++ b/.claude/rules/numeric-precision.md
@@ -117,7 +117,7 @@ is module-private so the two percent kinds can never drift apart):
| Quantity | min 0, max 5 | "3", "4.33333", "0.00125" — no "<0.01" placeholder |
| Money (settlement) | max = min = `currency.decimalPlaces` | "$300.00", "$3.50", "$0.00", "¥63", "BHD 0.563" — what someone PAYS: an invoice total, line amount, payment, tax amount. A currency cannot settle a fraction of its smallest unit, so its decimals are both floor and CEILING; a stored 300.33323 displays "$300.33" and storage keeps the rest. PADDED, because fixed-width money is the accounting convention |
| Rate (per-unit price/cost) | min = `currency.decimalPlaces`, max = `SCALE` | "$300.00", "$3.50" — pads exactly like money, so a price column stays aligned — but the currency's decimals are only its FLOOR. Above them it carries the storage scale: "$0.164", "$0.00123", "$12.34567". A price is what you MULTIPLY BY, not what you settle, and a 2-decimal ceiling silently turned a real $0.00123 fastener price into $0.00 ([#1203](https://github.com/crbnos/carbon/issues/1203)). Every ERP splits these — Xero settles at 2 and takes 4 on `UnitAmount` (opt-in `unitdp=4`), QuickBooks Desktop shows 5 in the Rate column, SAP reaches sub-cent prices with a price unit (per 100/1000) — and none of them widens settlement values. `INPUT_STEP.rate` is the scale step, since `money`'s cent step would snap away exactly the digits this keeps |
-| ↳ trailing-zero preference | min 0 when set | `companySettings.showCurrencyTrailingZeros` (default true) turned OFF drops the non-significant zeros — "$300", "$3.5". DISPLAY and IN-APP only, and it covers EDITABLE fields too: `useCurrencyFormatter` and `MotionMoney` read it once via `useCurrencyMinDecimals`, and `~/components/Form`'s `Number`/`NumberControlled` wrappers (`CurrencyNumber.tsx`) apply it to any `style: "currency"` `formatOptions` — never a call site, which is why the ~80 `INPUT_FORMAT.money/price(...)` calls still pass two arguments. Overriding the MINIMUM is safe on an input even though `formatOptions` is part of the storage round-trip: react-aria commits `parse(format(x))` and only the MAXIMUM can change that. Documents render through the pure `formatMoney` and stay padded — a customer-facing invoice is where fixed-width money matters most — and an unauthenticated context (the public quote share page) has no settings to read, so it pads too |
+| ↳ trailing-zero preference | min 0 when set | `companySettings.showCurrencyTrailingZeros` (default true) turned OFF drops the non-significant zeros — "$300", "$3.5". DISPLAY and IN-APP only, and it covers EDITABLE fields too: `useCurrencyFormatter` and `MotionMoney` read it once via `useCurrencyMinDecimals`, and `~/components/Form`'s `Number`/`NumberControlled` wrappers (`CurrencyNumber.tsx`) apply it to any `style: "currency"` `formatOptions` — never a call site, which is why the ~80 `INPUT_FORMAT.money/price(...)` calls still pass two arguments. Overriding the MINIMUM is safe on an input even though `formatOptions` is part of the storage round-trip: react-aria commits `parse(format(x))` and only the MAXIMUM can change that. Documents render through the pure `formatMoney` and stay padded — a customer-facing invoice is where fixed-width money matters most. A PUBLIC page is not automatically settings-free: `useCompanySettings` reads `useRouteData(authenticatedRoot)`, which matches on the PATHNAME `/x` and so returns nothing under `/share/**`, so the quote share page passes its own service-role `companySettings` down through `CompanySettingsProvider` (`useCompanySettings.tsx`). Any other public route that wants the preference must do the same — the fallback is silent, and reads as "padded on purpose" rather than "never wired up" |
| Editable currency (`INPUT_FORMAT.money` / `.rate`) | same as its kind above | an input formats with the SAME digits it displays with, padding included — an empty cost reads "$0.00". react-aria's blur commit is literally `setNumberValue(parse(format(x)))`, so this is not decoration — it is what a typed amount is STORED at. `.money` commits 300.22121 as 300.22 in USD and 63.4 as 63 in JPY; `.rate` commits 0.00123 as 0.00123, which is the whole point of the rate kind |
Call sites pick a kind (`formatMoney/Price/Percent/Quantity`, the
diff --git a/apps/erp/app/components/MotionMoney.tsx b/apps/erp/app/components/MotionMoney.tsx
index 20be9958fb..638ca9f060 100644
--- a/apps/erp/app/components/MotionMoney.tsx
+++ b/apps/erp/app/components/MotionMoney.tsx
@@ -1,6 +1,7 @@
import { moneyFormatOptions, SCALE } from "@carbon/utils";
import { useLocale } from "@react-aria/i18n";
import MotionNumber from "motion-number";
+import { useMemo } from "react";
import { useCurrencyMinDecimals } from "~/hooks/useCurrencies";
type MotionMoneyProps = {
@@ -35,17 +36,32 @@ const MotionMoney = ({
const { locale } = useLocale();
const minDecimals = useCurrencyMinDecimals();
+ // MotionNumber memoizes its formatted parts on `format` BY REFERENCE, so a
+ // fresh literal every render re-derives every digit and re-drives framer's
+ // layout projection on each one.
+ const format = useMemo(
+ () => ({
+ ...moneyFormatOptions(decimalPlaces, {
+ currency,
+ minDecimalPlaces: minDecimals,
+ maxDecimalPlaces: rate ? Math.max(decimalPlaces, SCALE) : undefined
+ }),
+ notation: "standard" as const
+ }),
+ [currency, decimalPlaces, minDecimals, rate]
+ );
+
return (
<MotionNumber
+ // MotionNumber animates a VALUE change; a FORMAT change is not one. Losing
+ // the trailing zeros drops three parts, and AnimatePresence's popLayout
+ // pulls them out absolutely-positioned over a one-second fade — the ".00"
+ // ghosting on top of the amount when the trailing-zeros setting is toggled.
+ // Keying on the format remounts instead, so re-formatting is instant and
+ // only real value changes animate.
+ key={`${locale}:${currency}:${decimalPlaces}:${minDecimals}:${rate}`}
value={value}
- format={{
- ...moneyFormatOptions(decimalPlaces, {
- currency,
- minDecimalPlaces: minDecimals,
- maxDecimalPlaces: rate ? Math.max(decimalPlaces, SCALE) : undefined
- }),
- notation: "standard" as const
- }}
+ format={format}
locales={locale}
className={className}
/>
diff --git a/apps/erp/app/hooks/index.ts b/apps/erp/app/hooks/index.ts
index a78991445b..4f56116599 100644
--- a/apps/erp/app/hooks/index.ts
+++ b/apps/erp/app/hooks/index.ts
@@ -5,9 +5,13 @@ import {
useRouteData,
useUrlParams
} from "@carbon/react";
-import { useCompanySettings } from "./useCompanySettings";
+import {
+ CompanySettingsProvider,
+ useCompanySettings
+} from "./useCompanySettings";
import { useCompanyTimeZone, useCompanyToday } from "./useCompanyTimeZone";
import {
+ CurrenciesProvider,
useCurrencies,
useCurrencyDecimals,
useCurrencyDecimalsLookup
@@ -36,6 +40,7 @@ import { useTrainingPanel } from "./useTrainingPanel";
import { useUser } from "./useUser";
export {
+ CompanySettingsProvider,
useCompanySettings,
useCompanyTimeZone,
useCompanyToday,
@@ -54,6 +59,7 @@ export {
useNotifications,
useOnboarding,
useOptimisticLocation,
+ CurrenciesProvider,
useCurrencies,
useCurrencyDecimals,
useCurrencyDecimalsLookup,
diff --git a/apps/erp/app/hooks/useCompanySettings.tsx b/apps/erp/app/hooks/useCompanySettings.tsx
index f5119a89ca..d8089ad33f 100644
--- a/apps/erp/app/hooks/useCompanySettings.tsx
+++ b/apps/erp/app/hooks/useCompanySettings.tsx
@@ -1,4 +1,5 @@
import { useRouteData } from "@carbon/react";
+import { createContext, useContext } from "react";
import { path } from "~/utils/path";
type CompanySettings = {
@@ -7,9 +8,21 @@ type CompanySettings = {
showCurrencyTrailingZeros?: boolean | null;
} & Record<string, unknown>;
+/** Set by a route that loaded the settings itself. `useRouteData` matches on the
+ * PATHNAME "/x", so it returns nothing outside the authenticated tree — the
+ * public share pages fetch companySettings in their own service-role loader and
+ * hand it down through here instead. Without it a customer-facing quote silently
+ * ignores every display preference the company set. */
+const CompanySettingsContext = createContext<CompanySettings | undefined>(
+ undefined
+);
+
+export const CompanySettingsProvider = CompanySettingsContext.Provider;
+
export function useCompanySettings(): CompanySettings | undefined {
+ const provided = useContext(CompanySettingsContext);
const data = useRouteData<{ companySettings?: CompanySettings }>(
path.to.authenticatedRoot
);
- return data?.companySettings;
+ return provided ?? data?.companySettings;
}
diff --git a/apps/erp/app/hooks/useCurrencies.ts b/apps/erp/app/hooks/useCurrencies.ts
index 1cab1f2310..9bb9bf899a 100644
--- a/apps/erp/app/hooks/useCurrencies.ts
+++ b/apps/erp/app/hooks/useCurrencies.ts
@@ -1,26 +1,41 @@
import { useMount } from "@carbon/react";
import { cldrCurrencyDecimals, DEFAULT_CURRENCY_DECIMALS } from "@carbon/utils";
-import { useMemo } from "react";
+import { createContext, useContext, useMemo } from "react";
import { useFetcher } from "react-router";
import type { getCurrenciesList } from "~/modules/accounting";
import { path } from "~/utils/path";
import { useCompanySettings } from "./useCompanySettings";
+type CurrencyList = NonNullable<
+ Awaited<ReturnType<typeof getCurrenciesList>>["data"]
+>;
+
+/** Set by a route that loaded the list itself. The currencies API is
+ * `requirePermissions`-gated, so the fetcher below returns nothing on a public
+ * page and every amount silently falls back to CLDR — which is the one thing
+ * the standard says is NOT authoritative. */
+const CurrenciesContext = createContext<CurrencyList | undefined>(undefined);
+
+export const CurrenciesProvider = CurrenciesContext.Provider;
+
/**
* The ISO currency list with the company group's configured `decimalPlaces`
* riding along (null for a currency the group hasn't set up). Served through
* the cached currencies clientLoader, so mounting this in many components
* costs one network round-trip per session, not per mount.
*/
-export function useCurrencies() {
+export function useCurrencies(): CurrencyList {
+ const provided = useContext(CurrenciesContext);
const currencyFetcher =
useFetcher<Awaited<ReturnType<typeof getCurrenciesList>>>();
useMount(() => {
- currencyFetcher.load(path.to.api.currencies);
+ // A provided list means the route already has it and the endpoint is not
+ // reachable anyway — asking would be a guaranteed 401 on every public view.
+ if (!provided) currencyFetcher.load(path.to.api.currencies);
});
- return currencyFetcher.data?.data ?? [];
+ return provided ?? currencyFetcher.data?.data ?? [];
}
/**
@@ -66,10 +81,11 @@ export function useCurrencyDecimals(
* `showCurrencyTrailingZeros` preference resolved to a number for
* `moneyFormatOptions`.
*
- * `undefined` means "pad to the currency's decimals", which is both the default
- * and what an UNAUTHENTICATED context gets: the public quote share page has no
- * company settings to read, and a customer-facing document should show money at
- * full width regardless of an internal display preference.
+ * `undefined` means "pad to the currency's decimals" — the default, and what any
+ * context without settings gets. A public page is NOT automatically one of those:
+ * the quote share page hands its own service-role copy down through
+ * `CompanySettingsProvider`, because the preference is how the company wants its
+ * money to read, and a customer looking at the quote is exactly who it is for.
*/
export function useCurrencyMinDecimals(): number | undefined {
const settings = useCompanySettings();
diff --git a/apps/erp/app/routes/share+/quote.$id.tsx b/apps/erp/app/routes/share+/quote.$id.tsx
index bceb5478bf..640d291f09 100644
--- a/apps/erp/app/routes/share+/quote.$id.tsx
+++ b/apps/erp/app/routes/share+/quote.$id.tsx
@@ -54,11 +54,13 @@ import type { LoaderFunctionArgs } from "react-router";
import { useFetcher, useLoaderData, useParams } from "react-router";
import { DateTime, MotionMoney } from "~/components";
import {
+ CompanySettingsProvider,
+ CurrenciesProvider,
useCurrencyDecimals,
useCurrencyFormatter,
usePercentFormatter
} from "~/hooks";
-import { getPaymentTermsList } from "~/modules/accounting";
+import { getCurrenciesList, getPaymentTermsList } from "~/modules/accounting";
import { getShippingMethodsList } from "~/modules/inventory";
import type {
QuotationLine,
@@ -149,6 +151,14 @@ export async function loader({ params, request }: LoaderFunctionArgs) {
getOpportunity(serviceRole, quote.data.opportunityId)
]);
+ // Started before the conditional await below so this costs no extra round trip.
+ // The group's configured currency.decimalPlaces is authoritative over CLDR, and
+ // useCurrencies' own fetcher is permission-gated, so a public page has to carry
+ // the list itself or every amount here silently falls back to CLDR.
+ const currenciesPromise = company.data?.companyGroupId
+ ? getCurrenciesList(serviceRole, company.data.companyGroupId)
+ : null;
+
let salesOrderLines: PostgrestResponse<SalesOrderLine> | null = null;
if (
opportunity.data?.salesOrders?.length &&
@@ -199,6 +209,7 @@ export async function loader({ params, request }: LoaderFunctionArgs) {
quote: quote.data,
company: company.data,
companySettings: companySettings.data,
+ currencies: (await currenciesPromise)?.data ?? [],
quoteLines:
quoteLines.data?.map(({ internalNotes, ...line }) => ({
...line
@@ -1579,7 +1590,16 @@ export default function ExternalQuote() {
switch (state) {
case QuoteState.Valid:
if (data) {
- return <Quote data={data as QuoteData} />;
+ // The authenticated route this would otherwise be read from isn't mounted
+ // here, so hand the loader's own copy down — otherwise the customer-facing
+ // quote ignores the company's currency display preferences.
+ return (
+ <CompanySettingsProvider value={data.companySettings ?? undefined}>
+ <CurrenciesProvider value={data.currencies ?? []}>
+ <Quote data={data as QuoteData} />
+ </CurrenciesProvider>
+ </CompanySettingsProvider>
+ );
}
return (
<ErrorMessage