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.

1.8 KB
Raw Blame
// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
// Carbon Enterprise file, licensed only under the Carbon Commercial License
// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.

import { round } from "@carbon/utils";

// Xero's API rounds/validates decimal places per field class. These constants
// are the boundary's external contract (not internal scale choices): monetary
// line/total/payment fields carry two decimals, per-unit amounts allow four,
// and exchange rates allow six. Document replay validates exact representability
// before writing; it must never round away Carbon document principal.
export const XERO_MONEY_DECIMALS = 2;
export const XERO_UNIT_AMOUNT_DECIMALS = 4;
export const XERO_QUANTITY_DECIMALS = 4;
export const XERO_CURRENCY_RATE_DECIMALS = 6;

export const xeroMoney = (value: number) => round(value, XERO_MONEY_DECIMALS);

export const xeroUnitAmount = (value: number) =>
  round(value, XERO_UNIT_AMOUNT_DECIMALS);

/** Xero recomputes LineAmount as Quantity x UnitAmount, so the quantity we send
 *  has to be the same one the extension is derived from — round it once, here,
 *  and build the line off the result. */
export const xeroQuantity = (value: number) =>
  round(value, XERO_QUANTITY_DECIMALS);

export const xeroCurrencyRate = (value: number) =>
  round(value, XERO_CURRENCY_RATE_DECIMALS);

/** Refuse unsupported principal instead of letting Xero silently round it. */
export function assertXeroMoneyPrecision(...values: number[]): void {
  if (
    values.some(
      (value) => !Number.isFinite(value) || xeroMoney(value) !== value
    )
  ) {
    throw new Error(
      "Xero document monetary precision is limited to two decimal places; this document cannot be represented without changing its amounts"
    );
  }
}