shutro 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +89 -2
- package/dist/audit/index.d.ts +57 -0
- package/dist/audit/index.js +94 -0
- package/dist/cli/bin.d.ts +2 -0
- package/dist/cli/bin.js +11 -0
- package/dist/cli/cli.d.ts +10 -0
- package/dist/cli/cli.js +149 -0
- package/dist/cli/config.d.ts +18 -0
- package/dist/cli/config.js +47 -0
- package/dist/cli/errors.d.ts +16 -0
- package/dist/cli/errors.js +23 -0
- package/dist/cli/generate/generate.d.ts +33 -0
- package/dist/cli/generate/generate.js +82 -0
- package/dist/cli/generate/render.d.ts +23 -0
- package/dist/cli/generate/render.js +200 -0
- package/dist/cli/index.d.ts +12 -0
- package/dist/cli/index.js +12 -0
- package/dist/cli/init.d.ts +2 -0
- package/dist/cli/init.js +65 -0
- package/dist/cli/inspect.d.ts +10 -0
- package/dist/cli/inspect.js +82 -0
- package/dist/cli/packages.d.ts +6 -0
- package/dist/cli/packages.js +6 -0
- package/dist/cli/project.d.ts +18 -0
- package/dist/cli/project.js +39 -0
- package/dist/core/compute/graph.d.ts +52 -0
- package/dist/core/compute/graph.js +162 -0
- package/dist/core/env/env.d.ts +295 -0
- package/dist/core/env/env.js +631 -0
- package/dist/core/env/identity.d.ts +33 -0
- package/dist/core/env/identity.js +49 -0
- package/dist/core/env/inspector.d.ts +55 -0
- package/dist/core/env/inspector.js +85 -0
- package/dist/core/env/time.d.ts +12 -0
- package/dist/core/env/time.js +38 -0
- package/dist/core/errors.d.ts +242 -0
- package/dist/core/errors.js +339 -0
- package/dist/core/index.d.ts +43 -0
- package/dist/core/index.js +34 -0
- package/dist/core/model/company.d.ts +6 -0
- package/dist/core/model/company.js +31 -0
- package/dist/core/model/faces.d.ts +42 -0
- package/dist/core/model/faces.js +1 -0
- package/dist/core/model/field.d.ts +446 -0
- package/dist/core/model/field.js +398 -0
- package/dist/core/model/generated.d.ts +75 -0
- package/dist/core/model/generated.js +1 -0
- package/dist/core/model/id.d.ts +33 -0
- package/dist/core/model/id.js +4 -0
- package/dist/core/model/model.d.ts +347 -0
- package/dist/core/model/model.js +538 -0
- package/dist/core/model/partition.d.ts +31 -0
- package/dist/core/model/partition.js +71 -0
- package/dist/core/money/currency.d.ts +39 -0
- package/dist/core/money/currency.js +37 -0
- package/dist/core/money/decimal.d.ts +26 -0
- package/dist/core/money/decimal.js +51 -0
- package/dist/core/money/fx.d.ts +60 -0
- package/dist/core/money/fx.js +109 -0
- package/dist/core/money/money.d.ts +84 -0
- package/dist/core/money/money.js +173 -0
- package/dist/core/money/quantity.d.ts +67 -0
- package/dist/core/money/quantity.js +108 -0
- package/dist/core/money/rounding.d.ts +11 -0
- package/dist/core/money/rounding.js +12 -0
- package/dist/core/recordset/audit.d.ts +25 -0
- package/dist/core/recordset/audit.js +205 -0
- package/dist/core/recordset/compute.d.ts +34 -0
- package/dist/core/recordset/compute.js +405 -0
- package/dist/core/recordset/constraints.d.ts +9 -0
- package/dist/core/recordset/constraints.js +61 -0
- package/dist/core/recordset/domain.d.ts +27 -0
- package/dist/core/recordset/domain.js +228 -0
- package/dist/core/recordset/onchange.d.ts +43 -0
- package/dist/core/recordset/onchange.js +207 -0
- package/dist/core/recordset/recordset.d.ts +101 -0
- package/dist/core/recordset/recordset.js +723 -0
- package/dist/core/recordset/relations.d.ts +15 -0
- package/dist/core/recordset/relations.js +13 -0
- package/dist/core/recordset/rls.d.ts +15 -0
- package/dist/core/recordset/rls.js +108 -0
- package/dist/core/recordset/security.d.ts +42 -0
- package/dist/core/recordset/security.js +184 -0
- package/dist/core/recordset/sequences.d.ts +31 -0
- package/dist/core/recordset/sequences.js +154 -0
- package/dist/core/recordset/sqlErrors.d.ts +6 -0
- package/dist/core/recordset/sqlErrors.js +39 -0
- package/dist/core/recordset/transitions.d.ts +10 -0
- package/dist/core/recordset/transitions.js +77 -0
- package/dist/core/recordset/types.d.ts +296 -0
- package/dist/core/recordset/types.js +8 -0
- package/dist/core/recordset/values.d.ts +27 -0
- package/dist/core/recordset/values.js +147 -0
- package/dist/core/recordset/writes.d.ts +37 -0
- package/dist/core/recordset/writes.js +581 -0
- package/dist/core/registry/ddl.d.ts +22 -0
- package/dist/core/registry/ddl.js +127 -0
- package/dist/core/registry/extension.d.ts +94 -0
- package/dist/core/registry/extension.js +90 -0
- package/dist/core/registry/module.d.ts +80 -0
- package/dist/core/registry/module.js +96 -0
- package/dist/core/registry/registry.d.ts +105 -0
- package/dist/core/registry/registry.js +496 -0
- package/dist/driver-pg/driver.d.ts +86 -0
- package/dist/driver-pg/driver.js +176 -0
- package/dist/driver-pg/errors.d.ts +72 -0
- package/dist/driver-pg/errors.js +182 -0
- package/dist/driver-pg/index.d.ts +7 -0
- package/dist/driver-pg/index.js +7 -0
- package/dist/i18n/index.d.ts +25 -0
- package/dist/i18n/index.js +51 -0
- package/dist/migrate/apply.d.ts +78 -0
- package/dist/migrate/apply.js +167 -0
- package/dist/migrate/catalog.d.ts +10 -0
- package/dist/migrate/catalog.js +122 -0
- package/dist/migrate/diff.d.ts +98 -0
- package/dist/migrate/diff.js +160 -0
- package/dist/migrate/errors.d.ts +21 -0
- package/dist/migrate/errors.js +31 -0
- package/dist/migrate/index.d.ts +18 -0
- package/dist/migrate/index.js +18 -0
- package/dist/migrate/render.d.ts +5 -0
- package/dist/migrate/render.js +101 -0
- package/dist/migrate/schema.d.ts +61 -0
- package/dist/migrate/schema.js +195 -0
- package/dist/security/index.d.ts +123 -0
- package/dist/security/index.js +262 -0
- package/dist/sequence/index.d.ts +63 -0
- package/dist/sequence/index.js +106 -0
- package/dist/sql/ast.d.ts +49 -0
- package/dist/sql/ast.js +47 -0
- package/dist/sql/builder/builder.d.ts +215 -0
- package/dist/sql/builder/builder.js +308 -0
- package/dist/sql/builder/expression.d.ts +80 -0
- package/dist/sql/builder/expression.js +126 -0
- package/dist/sql/compile.d.ts +18 -0
- package/dist/sql/compile.js +41 -0
- package/dist/sql/errors.d.ts +13 -0
- package/dist/sql/errors.js +16 -0
- package/dist/sql/index.d.ts +19 -0
- package/dist/sql/index.js +19 -0
- package/dist/sql/tag.d.ts +42 -0
- package/dist/sql/tag.js +95 -0
- package/package.json +82 -4
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { InvalidCurrencyError } from '../errors.js';
|
|
2
|
+
import { toDecimal } from './decimal.js';
|
|
3
|
+
/**
|
|
4
|
+
* Creates a {@link Currency}. `decimalPlaces` defaults to the digits of `rounding`, `roundingMethod` to `half-up`.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```ts
|
|
8
|
+
* const BDT = defineCurrency({ code: 'BDT', rounding: '0.01' });
|
|
9
|
+
* const CHF_CASH = defineCurrency({ code: 'CHF', rounding: '0.05' });
|
|
10
|
+
* ```
|
|
11
|
+
* @throws {InvalidCurrencyError} for a code that isn't 3 upper-case letters, a non-positive rounding, or too few decimal places.
|
|
12
|
+
*/
|
|
13
|
+
export function defineCurrency(input) {
|
|
14
|
+
if (!/^[A-Z]{3}$/.test(input.code)) {
|
|
15
|
+
throw new InvalidCurrencyError(`${JSON.stringify(input.code)} is not an ISO 4217 currency code.`, "Use three upper-case letters, e.g. 'BDT', 'USD', 'EUR'.");
|
|
16
|
+
}
|
|
17
|
+
const rounding = toDecimal(input.rounding);
|
|
18
|
+
if (!rounding.isPositive() || rounding.isZero()) {
|
|
19
|
+
throw new InvalidCurrencyError(`Currency ${input.code} has rounding ${rounding.toFixed()}.`, "The rounding unit must be positive, e.g. '0.01' for cents or '1' for currencies without decimals.");
|
|
20
|
+
}
|
|
21
|
+
const minPlaces = rounding.decimalPlaces();
|
|
22
|
+
const decimalPlaces = input.decimalPlaces ?? minPlaces;
|
|
23
|
+
if (!Number.isInteger(decimalPlaces) || decimalPlaces < minPlaces) {
|
|
24
|
+
throw new InvalidCurrencyError(`Currency ${input.code} has ${decimalPlaces} decimal places but rounds to ${rounding.toFixed()}.`, `Use at least ${minPlaces} decimal places, or omit decimalPlaces to derive it from the rounding.`);
|
|
25
|
+
}
|
|
26
|
+
return Object.freeze({
|
|
27
|
+
code: input.code,
|
|
28
|
+
id: input.id,
|
|
29
|
+
rounding,
|
|
30
|
+
decimalPlaces,
|
|
31
|
+
roundingMethod: input.roundingMethod ?? 'half-up',
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
/** True when `a` and `b` denote the same currency. */
|
|
35
|
+
export function sameCurrency(a, b) {
|
|
36
|
+
return (a === b || (a.code === b.code && (a.id === undefined || b.id === undefined || a.id === b.id)));
|
|
37
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { Decimal as DecimalJs } from 'decimal.js';
|
|
2
|
+
/**
|
|
3
|
+
* Shutro's decimal type: an isolated decimal.js constructor with 64 significant digits and half-up rounding
|
|
4
|
+
* (RFC 0006 §6, precision amended by RFC 0007). The global decimal.js configuration is never touched.
|
|
5
|
+
*
|
|
6
|
+
* Instances are ordinary decimal.js `Decimal`s; prefer {@link toDecimal} for input validation.
|
|
7
|
+
*/
|
|
8
|
+
export declare const Decimal: typeof DecimalJs;
|
|
9
|
+
/** A decimal value (decimal.js instance). */
|
|
10
|
+
export type Decimal = DecimalJs;
|
|
11
|
+
/**
|
|
12
|
+
* Anything accepted where a decimal is expected: a `Decimal`, a decimal string (`'85000.00'`, `'1.5e-2'`), a
|
|
13
|
+
* `bigint`, or a **safe integer** `number`. Fractional numbers are rejected at runtime because they are already
|
|
14
|
+
* binary floating point (`0.1 + 0.2 !== 0.3`).
|
|
15
|
+
*/
|
|
16
|
+
export type DecimalInput = Decimal | string | bigint | number;
|
|
17
|
+
/**
|
|
18
|
+
* Converts input into a {@link Decimal} created with Shutro's constructor, so later arithmetic uses Shutro's precision
|
|
19
|
+
* even if the input came from another decimal.js configuration.
|
|
20
|
+
*
|
|
21
|
+
* @throws {NonIntegerNumberError} for numbers that aren't safe integers (e.g. `0.15`, `NaN`, `2 ** 53`).
|
|
22
|
+
* @throws {InvalidDecimalError} for strings that aren't plain decimals (`'NaN'`, `'0x10'`, `'1,000'`) and non-finite Decimals.
|
|
23
|
+
*/
|
|
24
|
+
export declare function toDecimal(input: DecimalInput): Decimal;
|
|
25
|
+
/** Removes the sign of a zero (`-0` → `0`), so serialized amounts never show `-0.00`. */
|
|
26
|
+
export declare function normalizeZero(value: Decimal): Decimal;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { Decimal as DecimalJs } from 'decimal.js';
|
|
2
|
+
import { InvalidDecimalError, NonIntegerNumberError } from '../errors.js';
|
|
3
|
+
/**
|
|
4
|
+
* Shutro's decimal type: an isolated decimal.js constructor with 64 significant digits and half-up rounding
|
|
5
|
+
* (RFC 0006 §6, precision amended by RFC 0007). The global decimal.js configuration is never touched.
|
|
6
|
+
*
|
|
7
|
+
* Instances are ordinary decimal.js `Decimal`s; prefer {@link toDecimal} for input validation.
|
|
8
|
+
*/
|
|
9
|
+
export const Decimal = DecimalJs.clone({
|
|
10
|
+
precision: 64,
|
|
11
|
+
rounding: DecimalJs.ROUND_HALF_UP,
|
|
12
|
+
toExpNeg: -100,
|
|
13
|
+
toExpPos: 100,
|
|
14
|
+
});
|
|
15
|
+
const PLAIN_DECIMAL = /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;
|
|
16
|
+
/**
|
|
17
|
+
* Converts input into a {@link Decimal} created with Shutro's constructor, so later arithmetic uses Shutro's precision
|
|
18
|
+
* even if the input came from another decimal.js configuration.
|
|
19
|
+
*
|
|
20
|
+
* @throws {NonIntegerNumberError} for numbers that aren't safe integers (e.g. `0.15`, `NaN`, `2 ** 53`).
|
|
21
|
+
* @throws {InvalidDecimalError} for strings that aren't plain decimals (`'NaN'`, `'0x10'`, `'1,000'`) and non-finite Decimals.
|
|
22
|
+
*/
|
|
23
|
+
export function toDecimal(input) {
|
|
24
|
+
if (typeof input === 'number') {
|
|
25
|
+
if (!Number.isSafeInteger(input)) {
|
|
26
|
+
throw new NonIntegerNumberError(Number.isFinite(input) && Number.isInteger(input)
|
|
27
|
+
? `${input} is beyond Number.MAX_SAFE_INTEGER, so it has already lost precision.`
|
|
28
|
+
: `${input} is a binary floating-point number, not an exact decimal.`, `Pass the value as a string ('${input}') or a Decimal; use bigint for large integers.`);
|
|
29
|
+
}
|
|
30
|
+
return new Decimal(input);
|
|
31
|
+
}
|
|
32
|
+
if (typeof input === 'bigint')
|
|
33
|
+
return new Decimal(input.toString());
|
|
34
|
+
if (typeof input === 'string') {
|
|
35
|
+
if (!PLAIN_DECIMAL.test(input)) {
|
|
36
|
+
throw new InvalidDecimalError(`${JSON.stringify(input)} is not a decimal number.`, "Use digits with an optional sign, decimal point and exponent, e.g. '85000.00', '-0.5', '1e3' (no thousands separators, currency symbols or spaces).");
|
|
37
|
+
}
|
|
38
|
+
return new Decimal(input);
|
|
39
|
+
}
|
|
40
|
+
if (DecimalJs.isDecimal(input)) {
|
|
41
|
+
if (!input.isFinite()) {
|
|
42
|
+
throw new InvalidDecimalError(`${input.toString()} is not a finite decimal.`, 'Business amounts must be finite: check for a division by zero or an invalid source value.');
|
|
43
|
+
}
|
|
44
|
+
return new Decimal(input);
|
|
45
|
+
}
|
|
46
|
+
throw new InvalidDecimalError(`A ${typeof input} was given where a decimal was expected.`, 'Pass a Decimal, a decimal string, a bigint or a safe integer.');
|
|
47
|
+
}
|
|
48
|
+
/** Removes the sign of a zero (`-0` → `0`), so serialized amounts never show `-0.00`. */
|
|
49
|
+
export function normalizeZero(value) {
|
|
50
|
+
return value.isZero() ? new Decimal(0) : value;
|
|
51
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dated, per-company currency conversion (RFC 0006 §7.6): rates live in `res.currency.rate`, lookups take the latest
|
|
3
|
+
* rate on or before the date (company-specific rows first, then shared ones), the company currency's rate is 1, and
|
|
4
|
+
* results carry the rate used.
|
|
5
|
+
*/
|
|
6
|
+
import type { ScopeInternals } from '../env/env.js';
|
|
7
|
+
import type { Currency } from './currency.js';
|
|
8
|
+
import { type Decimal } from './decimal.js';
|
|
9
|
+
import { Money } from './money.js';
|
|
10
|
+
/** Options of a one-off conversion. The date is mandatory (RFC 0006 §7.6). */
|
|
11
|
+
export interface ConvertOptions {
|
|
12
|
+
/** The document date (`'YYYY-MM-DD'`), never implicitly today. */
|
|
13
|
+
readonly date: string;
|
|
14
|
+
/** Company whose rates apply; defaults to the environment's company. */
|
|
15
|
+
readonly company?: number | undefined;
|
|
16
|
+
/** Round to the target currency (default `true`). */
|
|
17
|
+
readonly round?: boolean | undefined;
|
|
18
|
+
}
|
|
19
|
+
/** A conversion result: the amount plus what was used, for audit and exchange-difference entries. */
|
|
20
|
+
export interface Conversion {
|
|
21
|
+
readonly money: Money;
|
|
22
|
+
readonly from: Currency;
|
|
23
|
+
readonly to: Currency;
|
|
24
|
+
/** Target units per source unit. */
|
|
25
|
+
readonly rate: Decimal;
|
|
26
|
+
/** Date of the rate row used, `null` for an identity conversion. */
|
|
27
|
+
readonly rateDate: string | null;
|
|
28
|
+
}
|
|
29
|
+
/** Rates loaded once for a date and company; `convert` is then synchronous. */
|
|
30
|
+
export interface PreparedRates {
|
|
31
|
+
readonly date: string;
|
|
32
|
+
readonly company: number;
|
|
33
|
+
/** The rate of a currency relative to the company currency (units per one unit of the company currency). */
|
|
34
|
+
rate(currency: Currency): {
|
|
35
|
+
readonly rate: Decimal;
|
|
36
|
+
readonly date: string | null;
|
|
37
|
+
};
|
|
38
|
+
convert(money: Money, to: Currency, options?: {
|
|
39
|
+
readonly round?: boolean;
|
|
40
|
+
}): Conversion;
|
|
41
|
+
}
|
|
42
|
+
/** `env.fx`. */
|
|
43
|
+
export interface Fx {
|
|
44
|
+
/** Converts one amount. @throws {MissingRateError} when no rate exists on or before the date. */
|
|
45
|
+
convert(money: Money, to: Currency | number, options: ConvertOptions): Promise<Conversion>;
|
|
46
|
+
/** Loads the rates of several currencies in one query. */
|
|
47
|
+
prepare(options: {
|
|
48
|
+
readonly date: string;
|
|
49
|
+
readonly currencies: readonly (Currency | number)[];
|
|
50
|
+
readonly company?: number | undefined;
|
|
51
|
+
}): Promise<PreparedRates>;
|
|
52
|
+
}
|
|
53
|
+
/** What the fx engine needs from the environment. */
|
|
54
|
+
export interface FxHost {
|
|
55
|
+
readonly internals: ScopeInternals;
|
|
56
|
+
currency(id: number): Promise<Currency>;
|
|
57
|
+
companyCurrency(company: number): Promise<Currency>;
|
|
58
|
+
}
|
|
59
|
+
/** Creates `env.fx` for a scope. */
|
|
60
|
+
export declare function createFx(host: FxHost): Fx;
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dated, per-company currency conversion (RFC 0006 §7.6): rates live in `res.currency.rate`, lookups take the latest
|
|
3
|
+
* rate on or before the date (company-specific rows first, then shared ones), the company currency's rate is 1, and
|
|
4
|
+
* results carry the rate used.
|
|
5
|
+
*/
|
|
6
|
+
import { compile, sql } from '../../sql/index.js';
|
|
7
|
+
import { MissingRateError } from '../errors.js';
|
|
8
|
+
import { toDecimal } from './decimal.js';
|
|
9
|
+
import { Money } from './money.js';
|
|
10
|
+
const RATE_MODEL = 'res.currency.rate';
|
|
11
|
+
const DATE = /^\d{4}-\d{2}-\d{2}$/;
|
|
12
|
+
function dateString(value) {
|
|
13
|
+
return value instanceof Date ? value.toISOString().slice(0, 10) : String(value).slice(0, 10);
|
|
14
|
+
}
|
|
15
|
+
async function lookupRates(internals, currencies, date, company) {
|
|
16
|
+
const out = new Map();
|
|
17
|
+
if (currencies.length === 0)
|
|
18
|
+
return out;
|
|
19
|
+
if (!DATE.test(date)) {
|
|
20
|
+
throw new MissingRateError(`${JSON.stringify(date)} is not a calendar date.`, "Pass the document date as 'YYYY-MM-DD'.");
|
|
21
|
+
}
|
|
22
|
+
const model = internals.registry.get(RATE_MODEL).model;
|
|
23
|
+
const col = (key) => {
|
|
24
|
+
const column = model.columns[key];
|
|
25
|
+
if (column === undefined) {
|
|
26
|
+
throw new MissingRateError(`The model '${RATE_MODEL}' has no '${key}' field.`, 'Define res.currency.rate with currency (many2one res.currency), company (many2one res.company, optional), date (f.date) and rate (f.decimal).');
|
|
27
|
+
}
|
|
28
|
+
return column;
|
|
29
|
+
};
|
|
30
|
+
const [currency, companyCol, dateCol, rate] = [
|
|
31
|
+
col('currency'),
|
|
32
|
+
col('company'),
|
|
33
|
+
col('date'),
|
|
34
|
+
col('rate'),
|
|
35
|
+
];
|
|
36
|
+
await internals.flush(model.name);
|
|
37
|
+
const rows = await internals.query(compile(sql `SELECT DISTINCT ON (${sql.id(currency)}) ${sql.id(currency)} AS ${sql.id('currency')}, ${sql.id(rate)} AS ${sql.id('rate')}, ${sql.id(dateCol)} AS ${sql.id('date')}
|
|
38
|
+
FROM ${sql.id(model.table)}
|
|
39
|
+
WHERE ${sql.id(currency)} = ANY(${sql.array([...currencies], 'bigint')}) AND ${sql.id(dateCol)} <= ${date}
|
|
40
|
+
AND (${sql.id(companyCol)} = ${company} OR ${sql.id(companyCol)} IS NULL)
|
|
41
|
+
ORDER BY ${sql.id(currency)}, (${sql.id(companyCol)} IS NULL), ${sql.id(dateCol)} DESC`));
|
|
42
|
+
for (const row of rows)
|
|
43
|
+
out.set(Number(row.currency), { rate: toDecimal(row.rate), date: dateString(row.date) });
|
|
44
|
+
return out;
|
|
45
|
+
}
|
|
46
|
+
/** Creates `env.fx` for a scope. */
|
|
47
|
+
export function createFx(host) {
|
|
48
|
+
const resolve = async (c) => typeof c === 'number' ? host.currency(c) : c;
|
|
49
|
+
async function prepare(options) {
|
|
50
|
+
const company = options.company ?? host.internals.env.companyId;
|
|
51
|
+
const companyCurrency = await host.companyCurrency(company);
|
|
52
|
+
const wanted = await Promise.all(options.currencies.map(resolve));
|
|
53
|
+
const ids = [
|
|
54
|
+
...new Set(wanted.map((c) => c.id).filter((id) => id !== undefined)),
|
|
55
|
+
];
|
|
56
|
+
const rates = await lookupRates(host.internals, ids, options.date, company);
|
|
57
|
+
const rateOf = (currency) => {
|
|
58
|
+
if (currency.id !== undefined) {
|
|
59
|
+
const found = rates.get(currency.id);
|
|
60
|
+
if (found !== undefined)
|
|
61
|
+
return found;
|
|
62
|
+
}
|
|
63
|
+
if (currency.code === companyCurrency.code)
|
|
64
|
+
return { rate: toDecimal(1), date: null };
|
|
65
|
+
throw new MissingRateError(`No rate for ${currency.code} on or before ${options.date} for company ${company}.`, `Add a res.currency.rate row for ${currency.code} dated ${options.date} or earlier (company ${company} or shared), or prepare the currency.`);
|
|
66
|
+
};
|
|
67
|
+
return {
|
|
68
|
+
date: options.date,
|
|
69
|
+
company,
|
|
70
|
+
rate: rateOf,
|
|
71
|
+
convert(money, to, opts = {}) {
|
|
72
|
+
const from = money.currency;
|
|
73
|
+
if (from.code === to.code) {
|
|
74
|
+
return {
|
|
75
|
+
money: Money.of(money.amount, to),
|
|
76
|
+
from,
|
|
77
|
+
to,
|
|
78
|
+
rate: toDecimal(1),
|
|
79
|
+
rateDate: null,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
const source = rateOf(from);
|
|
83
|
+
const target = rateOf(to);
|
|
84
|
+
const rate = target.rate.div(source.rate);
|
|
85
|
+
const amount = money.amount.times(rate);
|
|
86
|
+
const result = Money.of(amount, to);
|
|
87
|
+
return {
|
|
88
|
+
money: opts.round === false ? result : result.round(),
|
|
89
|
+
from,
|
|
90
|
+
to,
|
|
91
|
+
rate,
|
|
92
|
+
rateDate: source.date ?? target.date,
|
|
93
|
+
};
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
return {
|
|
98
|
+
async convert(money, to, options) {
|
|
99
|
+
const target = await resolve(to);
|
|
100
|
+
const prepared = await prepare({
|
|
101
|
+
date: options.date,
|
|
102
|
+
currencies: [money.currency, target],
|
|
103
|
+
company: options.company,
|
|
104
|
+
});
|
|
105
|
+
return prepared.convert(money, target, { round: options.round ?? true });
|
|
106
|
+
},
|
|
107
|
+
prepare,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { type Currency } from './currency.js';
|
|
2
|
+
import { Decimal, type DecimalInput } from './decimal.js';
|
|
3
|
+
import { type RoundingMethod } from './rounding.js';
|
|
4
|
+
/** JSON form of {@link Money}: the amount as an exact decimal string. */
|
|
5
|
+
export interface MoneyJson {
|
|
6
|
+
readonly amount: string;
|
|
7
|
+
readonly currency: string;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* An immutable amount in one currency (RFC 0006 §7.3).
|
|
11
|
+
*
|
|
12
|
+
* - Arithmetic is exact and **unrounded**; call {@link Money.round} at the points where rounding is defined.
|
|
13
|
+
* - Combining or comparing amounts in different currencies throws {@link CurrencyMismatchError}. Conversion is a
|
|
14
|
+
* separate, dated operation.
|
|
15
|
+
* - `isZero`, `equals` and `compare` work at the currency's rounding precision (like Odoo's `float_is_zero`).
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```ts
|
|
19
|
+
* const price = Money.of('85000.00', BDT);
|
|
20
|
+
* price.times('0.15').round(); // BDT 12750.00
|
|
21
|
+
* Money.of('1000', BDT).allocate([1, 1, 1]); // 333.34, 333.33, 333.33
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
export declare class Money {
|
|
25
|
+
/** The exact amount. */
|
|
26
|
+
readonly amount: Decimal;
|
|
27
|
+
/** The currency. */
|
|
28
|
+
readonly currency: Currency;
|
|
29
|
+
private constructor();
|
|
30
|
+
/** An amount in `currency`. */
|
|
31
|
+
static of(amount: DecimalInput, currency: Currency): Money;
|
|
32
|
+
/** Zero in `currency`. */
|
|
33
|
+
static zero(currency: Currency): Money;
|
|
34
|
+
/**
|
|
35
|
+
* Sum of amounts in one currency. An empty list needs `currency` to know which zero to return.
|
|
36
|
+
* @throws {CurrencyMismatchError} if the amounts (or `currency`) differ.
|
|
37
|
+
* @throws {EmptyMoneySumError} for an empty list without `currency`.
|
|
38
|
+
*/
|
|
39
|
+
static sum(items: readonly Money[], currency?: Currency): Money;
|
|
40
|
+
/** `this + other`. @throws {CurrencyMismatchError} */
|
|
41
|
+
plus(other: Money): Money;
|
|
42
|
+
/** `this - other`. @throws {CurrencyMismatchError} */
|
|
43
|
+
minus(other: Money): Money;
|
|
44
|
+
/** `this × factor`, unrounded. */
|
|
45
|
+
times(factor: DecimalInput): Money;
|
|
46
|
+
/** `this ÷ divisor`, unrounded (64 significant digits). @throws {DivisionByZeroError} */
|
|
47
|
+
dividedBy(divisor: DecimalInput): Money;
|
|
48
|
+
/** `-this`. */
|
|
49
|
+
negated(): Money;
|
|
50
|
+
/** `|this|`. */
|
|
51
|
+
abs(): Money;
|
|
52
|
+
/** Rounded to the currency's rounding unit, with the currency's method unless `method` is given. */
|
|
53
|
+
round(method?: RoundingMethod): Money;
|
|
54
|
+
/** True when the amount rounds to zero in its currency. */
|
|
55
|
+
isZero(): boolean;
|
|
56
|
+
/** True when the amount rounds to more than zero. */
|
|
57
|
+
isPositive(): boolean;
|
|
58
|
+
/** True when the amount rounds to less than zero. */
|
|
59
|
+
isNegative(): boolean;
|
|
60
|
+
/** Equal at currency precision. @throws {CurrencyMismatchError} */
|
|
61
|
+
equals(other: Money): boolean;
|
|
62
|
+
/** Same currency and exactly the same amount (no rounding). Never throws. */
|
|
63
|
+
equalsExactly(other: Money): boolean;
|
|
64
|
+
/** -1, 0 or 1 at currency precision. @throws {CurrencyMismatchError} */
|
|
65
|
+
compare(other: Money): -1 | 0 | 1;
|
|
66
|
+
/**
|
|
67
|
+
* Splits the rounded amount by `ratios` with the largest-remainder method (RFC 0006 §7.6): every share is a
|
|
68
|
+
* multiple of the rounding unit, the shares add up **exactly** to `this.round()`, each is within one unit of its
|
|
69
|
+
* exact proportional value, and ties go to the earliest share.
|
|
70
|
+
*
|
|
71
|
+
* @throws {InvalidAllocationError} for an empty list, a negative ratio, or ratios that sum to zero.
|
|
72
|
+
*/
|
|
73
|
+
allocate(ratios: readonly DecimalInput[]): readonly Money[];
|
|
74
|
+
/** The exact amount as a Decimal. */
|
|
75
|
+
toDecimal(): Decimal;
|
|
76
|
+
/**
|
|
77
|
+
* `{ amount: '85000.00', currency: 'BDT' }`. The amount is exact: padded to the currency's decimal places, never
|
|
78
|
+
* truncated (an unrounded `1.2345` stays `'1.2345'`).
|
|
79
|
+
*/
|
|
80
|
+
toJSON(): MoneyJson;
|
|
81
|
+
/** `'BDT 85000.00'`. Locale-aware formatting is the job of `format(lang)` (later). */
|
|
82
|
+
toString(): string;
|
|
83
|
+
private assertSameCurrency;
|
|
84
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { CurrencyMismatchError, DivisionByZeroError, EmptyMoneySumError, InvalidAllocationError, } from '../errors.js';
|
|
2
|
+
import { sameCurrency } from './currency.js';
|
|
3
|
+
import { Decimal, normalizeZero, toDecimal } from './decimal.js';
|
|
4
|
+
import { roundToUnit } from './rounding.js';
|
|
5
|
+
/**
|
|
6
|
+
* An immutable amount in one currency (RFC 0006 §7.3).
|
|
7
|
+
*
|
|
8
|
+
* - Arithmetic is exact and **unrounded**; call {@link Money.round} at the points where rounding is defined.
|
|
9
|
+
* - Combining or comparing amounts in different currencies throws {@link CurrencyMismatchError}. Conversion is a
|
|
10
|
+
* separate, dated operation.
|
|
11
|
+
* - `isZero`, `equals` and `compare` work at the currency's rounding precision (like Odoo's `float_is_zero`).
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```ts
|
|
15
|
+
* const price = Money.of('85000.00', BDT);
|
|
16
|
+
* price.times('0.15').round(); // BDT 12750.00
|
|
17
|
+
* Money.of('1000', BDT).allocate([1, 1, 1]); // 333.34, 333.33, 333.33
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
export class Money {
|
|
21
|
+
/** The exact amount. */
|
|
22
|
+
amount;
|
|
23
|
+
/** The currency. */
|
|
24
|
+
currency;
|
|
25
|
+
constructor(amount, currency) {
|
|
26
|
+
this.amount = amount;
|
|
27
|
+
this.currency = currency;
|
|
28
|
+
Object.freeze(this);
|
|
29
|
+
}
|
|
30
|
+
/** An amount in `currency`. */
|
|
31
|
+
static of(amount, currency) {
|
|
32
|
+
return new Money(toDecimal(amount), currency);
|
|
33
|
+
}
|
|
34
|
+
/** Zero in `currency`. */
|
|
35
|
+
static zero(currency) {
|
|
36
|
+
return new Money(new Decimal(0), currency);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Sum of amounts in one currency. An empty list needs `currency` to know which zero to return.
|
|
40
|
+
* @throws {CurrencyMismatchError} if the amounts (or `currency`) differ.
|
|
41
|
+
* @throws {EmptyMoneySumError} for an empty list without `currency`.
|
|
42
|
+
*/
|
|
43
|
+
static sum(items, currency) {
|
|
44
|
+
const first = items[0];
|
|
45
|
+
const target = currency ?? first?.currency;
|
|
46
|
+
if (target === undefined) {
|
|
47
|
+
throw new EmptyMoneySumError('Money.sum() was given an empty list and no currency.', 'Pass the currency for the empty case: Money.sum(amounts, currency).');
|
|
48
|
+
}
|
|
49
|
+
let total = Money.zero(target);
|
|
50
|
+
for (const item of items)
|
|
51
|
+
total = total.plus(item);
|
|
52
|
+
return total;
|
|
53
|
+
}
|
|
54
|
+
/** `this + other`. @throws {CurrencyMismatchError} */
|
|
55
|
+
plus(other) {
|
|
56
|
+
this.assertSameCurrency(other, 'add');
|
|
57
|
+
return new Money(this.amount.plus(other.amount), this.currency);
|
|
58
|
+
}
|
|
59
|
+
/** `this - other`. @throws {CurrencyMismatchError} */
|
|
60
|
+
minus(other) {
|
|
61
|
+
this.assertSameCurrency(other, 'subtract');
|
|
62
|
+
return new Money(this.amount.minus(other.amount), this.currency);
|
|
63
|
+
}
|
|
64
|
+
/** `this × factor`, unrounded. */
|
|
65
|
+
times(factor) {
|
|
66
|
+
return new Money(this.amount.times(toDecimal(factor)), this.currency);
|
|
67
|
+
}
|
|
68
|
+
/** `this ÷ divisor`, unrounded (64 significant digits). @throws {DivisionByZeroError} */
|
|
69
|
+
dividedBy(divisor) {
|
|
70
|
+
const d = toDecimal(divisor);
|
|
71
|
+
if (d.isZero()) {
|
|
72
|
+
throw new DivisionByZeroError(`Cannot divide ${this.toString()} by zero.`, 'Check the divisor (quantity, ratio, number of installments) before dividing; use allocate() to split amounts.');
|
|
73
|
+
}
|
|
74
|
+
return new Money(this.amount.dividedBy(d), this.currency);
|
|
75
|
+
}
|
|
76
|
+
/** `-this`. */
|
|
77
|
+
negated() {
|
|
78
|
+
return new Money(normalizeZero(this.amount.negated()), this.currency);
|
|
79
|
+
}
|
|
80
|
+
/** `|this|`. */
|
|
81
|
+
abs() {
|
|
82
|
+
return new Money(this.amount.abs(), this.currency);
|
|
83
|
+
}
|
|
84
|
+
/** Rounded to the currency's rounding unit, with the currency's method unless `method` is given. */
|
|
85
|
+
round(method = this.currency.roundingMethod) {
|
|
86
|
+
return new Money(roundToUnit(this.amount, this.currency.rounding, method), this.currency);
|
|
87
|
+
}
|
|
88
|
+
/** True when the amount rounds to zero in its currency. */
|
|
89
|
+
isZero() {
|
|
90
|
+
return this.round().amount.isZero();
|
|
91
|
+
}
|
|
92
|
+
/** True when the amount rounds to more than zero. */
|
|
93
|
+
isPositive() {
|
|
94
|
+
return this.round().amount.gt(0);
|
|
95
|
+
}
|
|
96
|
+
/** True when the amount rounds to less than zero. */
|
|
97
|
+
isNegative() {
|
|
98
|
+
return this.round().amount.lt(0);
|
|
99
|
+
}
|
|
100
|
+
/** Equal at currency precision. @throws {CurrencyMismatchError} */
|
|
101
|
+
equals(other) {
|
|
102
|
+
return this.compare(other) === 0;
|
|
103
|
+
}
|
|
104
|
+
/** Same currency and exactly the same amount (no rounding). Never throws. */
|
|
105
|
+
equalsExactly(other) {
|
|
106
|
+
return sameCurrency(this.currency, other.currency) && this.amount.eq(other.amount);
|
|
107
|
+
}
|
|
108
|
+
/** -1, 0 or 1 at currency precision. @throws {CurrencyMismatchError} */
|
|
109
|
+
compare(other) {
|
|
110
|
+
this.assertSameCurrency(other, 'compare');
|
|
111
|
+
const c = this.round().amount.cmp(other.round().amount);
|
|
112
|
+
return c < 0 ? -1 : c > 0 ? 1 : 0;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Splits the rounded amount by `ratios` with the largest-remainder method (RFC 0006 §7.6): every share is a
|
|
116
|
+
* multiple of the rounding unit, the shares add up **exactly** to `this.round()`, each is within one unit of its
|
|
117
|
+
* exact proportional value, and ties go to the earliest share.
|
|
118
|
+
*
|
|
119
|
+
* @throws {InvalidAllocationError} for an empty list, a negative ratio, or ratios that sum to zero.
|
|
120
|
+
*/
|
|
121
|
+
allocate(ratios) {
|
|
122
|
+
const weights = ratios.map(toDecimal);
|
|
123
|
+
const totalWeight = weights.reduce((a, b) => a.plus(b), new Decimal(0));
|
|
124
|
+
if (weights.length === 0 ||
|
|
125
|
+
weights.some((w) => w.isNegative() && !w.isZero()) ||
|
|
126
|
+
totalWeight.isZero()) {
|
|
127
|
+
throw new InvalidAllocationError(`Cannot allocate ${this.toString()} by ratios [${weights.map((w) => w.toFixed()).join(', ')}].`, 'Pass at least one ratio; ratios must be zero or positive and not all zero.');
|
|
128
|
+
}
|
|
129
|
+
const unit = this.currency.rounding;
|
|
130
|
+
const totalUnits = this.round().amount.dividedBy(unit); // an integer
|
|
131
|
+
const units = totalUnits.abs();
|
|
132
|
+
// Exact integer arithmetic: scale ratios to integers, then share_i = floor(units·w_i / W) with an exact
|
|
133
|
+
// remainder. Comparing inexact quotients could floor a near-integer share the wrong way and break Σ = total.
|
|
134
|
+
const scale = new Decimal(10).pow(Math.max(...weights.map((w) => w.decimalPlaces())));
|
|
135
|
+
const ints = weights.map((w) => w.times(scale));
|
|
136
|
+
const sumInts = ints.reduce((a, b) => a.plus(b), new Decimal(0));
|
|
137
|
+
const counts = ints.map((w) => units.times(w).dividedToIntegerBy(sumInts));
|
|
138
|
+
const remainders = ints.map((w) => units.times(w).mod(sumInts));
|
|
139
|
+
let remaining = counts.reduce((a, b) => a.minus(b), units).toNumber();
|
|
140
|
+
const byRemainder = remainders
|
|
141
|
+
.map((r, i) => ({ i, r }))
|
|
142
|
+
.sort((a, b) => b.r.cmp(a.r) || a.i - b.i);
|
|
143
|
+
for (const { i } of byRemainder) {
|
|
144
|
+
if (remaining <= 0)
|
|
145
|
+
break;
|
|
146
|
+
counts[i] = (counts[i] ?? new Decimal(0)).plus(1);
|
|
147
|
+
remaining--;
|
|
148
|
+
}
|
|
149
|
+
const sign = totalUnits.isNegative() ? -1 : 1;
|
|
150
|
+
return Object.freeze(counts.map((count) => new Money(normalizeZero(count.times(unit).times(sign)), this.currency)));
|
|
151
|
+
}
|
|
152
|
+
/** The exact amount as a Decimal. */
|
|
153
|
+
toDecimal() {
|
|
154
|
+
return this.amount;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* `{ amount: '85000.00', currency: 'BDT' }`. The amount is exact: padded to the currency's decimal places, never
|
|
158
|
+
* truncated (an unrounded `1.2345` stays `'1.2345'`).
|
|
159
|
+
*/
|
|
160
|
+
toJSON() {
|
|
161
|
+
const places = Math.max(this.currency.decimalPlaces, this.amount.decimalPlaces());
|
|
162
|
+
return { amount: normalizeZero(this.amount).toFixed(places), currency: this.currency.code };
|
|
163
|
+
}
|
|
164
|
+
/** `'BDT 85000.00'`. Locale-aware formatting is the job of `format(lang)` (later). */
|
|
165
|
+
toString() {
|
|
166
|
+
return `${this.currency.code} ${this.toJSON().amount}`;
|
|
167
|
+
}
|
|
168
|
+
assertSameCurrency(other, operation) {
|
|
169
|
+
if (!sameCurrency(this.currency, other.currency)) {
|
|
170
|
+
throw new CurrencyMismatchError(`Cannot ${operation} ${this.toString()} and ${other.toString()}: they are in different currencies.`, 'Convert one amount first: await env.fx.convert(amount, currency, { date }), and use the date of the document (invoice date / accounting date), not today.');
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { type Decimal, type DecimalInput } from './decimal.js';
|
|
2
|
+
import { type RoundingMethod } from './rounding.js';
|
|
3
|
+
/** A unit of measure (a snapshot of a `uom.uom` record, RFC 0006 §7.4). */
|
|
4
|
+
export interface Uom {
|
|
5
|
+
readonly name: string;
|
|
6
|
+
/** Units convert only within a category ('Unit', 'Weight', 'Length', ...). */
|
|
7
|
+
readonly category: string;
|
|
8
|
+
/** How many of the category's reference unit one of this unit is (dozen: 12, gram: 0.001 when kg is the reference). */
|
|
9
|
+
readonly ratio: Decimal;
|
|
10
|
+
/** Smallest quantity in this unit (units: 1, kg: 0.001). */
|
|
11
|
+
readonly rounding: Decimal;
|
|
12
|
+
/** Database id of the `uom.uom` record, when known. */
|
|
13
|
+
readonly id: number | undefined;
|
|
14
|
+
}
|
|
15
|
+
/** Input of {@link defineUom}. */
|
|
16
|
+
export interface UomInput {
|
|
17
|
+
readonly name: string;
|
|
18
|
+
readonly category: string;
|
|
19
|
+
readonly ratio: DecimalInput;
|
|
20
|
+
readonly rounding: DecimalInput;
|
|
21
|
+
readonly id?: number;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Creates a {@link Uom}.
|
|
25
|
+
* @throws {InvalidUomError} for an empty name or category, or a non-positive ratio or rounding.
|
|
26
|
+
*/
|
|
27
|
+
export declare function defineUom(input: UomInput): Uom;
|
|
28
|
+
/**
|
|
29
|
+
* An immutable quantity in one unit of measure. Mixing units requires an explicit {@link Quantity.to}, and
|
|
30
|
+
* conversion is only possible within a category.
|
|
31
|
+
*/
|
|
32
|
+
export declare class Quantity {
|
|
33
|
+
/** The exact value. */
|
|
34
|
+
readonly value: Decimal;
|
|
35
|
+
/** The unit. */
|
|
36
|
+
readonly uom: Uom;
|
|
37
|
+
private constructor();
|
|
38
|
+
/** A quantity of `value` in `uom`. */
|
|
39
|
+
static of(value: DecimalInput, uom: Uom): Quantity;
|
|
40
|
+
/**
|
|
41
|
+
* The same quantity in `target` (exact, unrounded): `Quantity.of(3, dozen).to(unit)` → 36 units.
|
|
42
|
+
* @throws {IncompatibleUomCategoryError} when the categories differ.
|
|
43
|
+
*/
|
|
44
|
+
to(target: Uom): Quantity;
|
|
45
|
+
/** `this + other`, same unit. @throws {UomMismatchError} */
|
|
46
|
+
plus(other: Quantity): Quantity;
|
|
47
|
+
/** `this - other`, same unit. @throws {UomMismatchError} */
|
|
48
|
+
minus(other: Quantity): Quantity;
|
|
49
|
+
/** `this × factor`, unrounded. */
|
|
50
|
+
times(factor: DecimalInput): Quantity;
|
|
51
|
+
/** Rounded to the unit's rounding (`half-up` unless given; procurement typically uses `up`). */
|
|
52
|
+
round(method?: RoundingMethod): Quantity;
|
|
53
|
+
/** True when the quantity rounds to zero in its unit. */
|
|
54
|
+
isZero(): boolean;
|
|
55
|
+
/** -1, 0 or 1 at the unit's precision. @throws {UomMismatchError} */
|
|
56
|
+
compare(other: Quantity): -1 | 0 | 1;
|
|
57
|
+
/** Equal at the unit's precision. @throws {UomMismatchError} */
|
|
58
|
+
equals(other: Quantity): boolean;
|
|
59
|
+
/** `{ value: '2.5', uom: 'kg' }`. */
|
|
60
|
+
toJSON(): {
|
|
61
|
+
readonly value: string;
|
|
62
|
+
readonly uom: string;
|
|
63
|
+
};
|
|
64
|
+
/** `'2.5 kg'`. */
|
|
65
|
+
toString(): string;
|
|
66
|
+
private assertSameUom;
|
|
67
|
+
}
|