shutro 0.0.0-stage → 0.2.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.
Files changed (165) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +99 -2
  3. package/dist/audit/index.d.ts +59 -0
  4. package/dist/audit/index.js +96 -0
  5. package/dist/cli/bin.d.ts +2 -0
  6. package/dist/cli/bin.js +11 -0
  7. package/dist/cli/cli.d.ts +10 -0
  8. package/dist/cli/cli.js +164 -0
  9. package/dist/cli/config.d.ts +18 -0
  10. package/dist/cli/config.js +49 -0
  11. package/dist/cli/errors.d.ts +16 -0
  12. package/dist/cli/errors.js +23 -0
  13. package/dist/cli/generate/generate.d.ts +33 -0
  14. package/dist/cli/generate/generate.js +84 -0
  15. package/dist/cli/generate/render.d.ts +23 -0
  16. package/dist/cli/generate/render.js +249 -0
  17. package/dist/cli/index.d.ts +12 -0
  18. package/dist/cli/index.js +12 -0
  19. package/dist/cli/init.d.ts +2 -0
  20. package/dist/cli/init.js +65 -0
  21. package/dist/cli/inspect.d.ts +10 -0
  22. package/dist/cli/inspect.js +82 -0
  23. package/dist/cli/packages.d.ts +6 -0
  24. package/dist/cli/packages.js +6 -0
  25. package/dist/cli/project.d.ts +18 -0
  26. package/dist/cli/project.js +39 -0
  27. package/dist/cli/resolve.d.ts +2 -0
  28. package/dist/cli/resolve.js +28 -0
  29. package/dist/core/compute/graph.d.ts +52 -0
  30. package/dist/core/compute/graph.js +162 -0
  31. package/dist/core/data/data.d.ts +59 -0
  32. package/dist/core/data/data.js +119 -0
  33. package/dist/core/data/load.d.ts +37 -0
  34. package/dist/core/data/load.js +236 -0
  35. package/dist/core/env/env.d.ts +468 -0
  36. package/dist/core/env/env.js +916 -0
  37. package/dist/core/env/identity.d.ts +43 -0
  38. package/dist/core/env/identity.js +65 -0
  39. package/dist/core/env/inspector.d.ts +55 -0
  40. package/dist/core/env/inspector.js +85 -0
  41. package/dist/core/env/time.d.ts +12 -0
  42. package/dist/core/env/time.js +38 -0
  43. package/dist/core/errors.d.ts +256 -0
  44. package/dist/core/errors.js +360 -0
  45. package/dist/core/events/events.d.ts +44 -0
  46. package/dist/core/events/events.js +58 -0
  47. package/dist/core/events/workers.d.ts +56 -0
  48. package/dist/core/events/workers.js +155 -0
  49. package/dist/core/index.d.ts +51 -0
  50. package/dist/core/index.js +42 -0
  51. package/dist/core/model/company.d.ts +6 -0
  52. package/dist/core/model/company.js +31 -0
  53. package/dist/core/model/faces.d.ts +42 -0
  54. package/dist/core/model/faces.js +1 -0
  55. package/dist/core/model/field.d.ts +479 -0
  56. package/dist/core/model/field.js +461 -0
  57. package/dist/core/model/generated.d.ts +77 -0
  58. package/dist/core/model/generated.js +1 -0
  59. package/dist/core/model/id.d.ts +33 -0
  60. package/dist/core/model/id.js +4 -0
  61. package/dist/core/model/model.d.ts +387 -0
  62. package/dist/core/model/model.js +566 -0
  63. package/dist/core/model/partition.d.ts +31 -0
  64. package/dist/core/model/partition.js +71 -0
  65. package/dist/core/model/related.d.ts +17 -0
  66. package/dist/core/model/related.js +60 -0
  67. package/dist/core/model/typed.d.ts +107 -0
  68. package/dist/core/model/typed.js +46 -0
  69. package/dist/core/money/currency.d.ts +39 -0
  70. package/dist/core/money/currency.js +37 -0
  71. package/dist/core/money/decimal.d.ts +26 -0
  72. package/dist/core/money/decimal.js +51 -0
  73. package/dist/core/money/fx.d.ts +68 -0
  74. package/dist/core/money/fx.js +124 -0
  75. package/dist/core/money/money.d.ts +84 -0
  76. package/dist/core/money/money.js +173 -0
  77. package/dist/core/money/quantity.d.ts +67 -0
  78. package/dist/core/money/quantity.js +108 -0
  79. package/dist/core/money/rounding.d.ts +11 -0
  80. package/dist/core/money/rounding.js +12 -0
  81. package/dist/core/recordset/aggregate.d.ts +22 -0
  82. package/dist/core/recordset/aggregate.js +258 -0
  83. package/dist/core/recordset/audit.d.ts +33 -0
  84. package/dist/core/recordset/audit.js +262 -0
  85. package/dist/core/recordset/compute.d.ts +36 -0
  86. package/dist/core/recordset/compute.js +414 -0
  87. package/dist/core/recordset/constraints.d.ts +9 -0
  88. package/dist/core/recordset/constraints.js +61 -0
  89. package/dist/core/recordset/domain.d.ts +31 -0
  90. package/dist/core/recordset/domain.js +300 -0
  91. package/dist/core/recordset/onchange.d.ts +43 -0
  92. package/dist/core/recordset/onchange.js +240 -0
  93. package/dist/core/recordset/recordset.d.ts +110 -0
  94. package/dist/core/recordset/recordset.js +789 -0
  95. package/dist/core/recordset/relations.d.ts +15 -0
  96. package/dist/core/recordset/relations.js +13 -0
  97. package/dist/core/recordset/rls.d.ts +15 -0
  98. package/dist/core/recordset/rls.js +108 -0
  99. package/dist/core/recordset/security.d.ts +56 -0
  100. package/dist/core/recordset/security.js +269 -0
  101. package/dist/core/recordset/sequences.d.ts +31 -0
  102. package/dist/core/recordset/sequences.js +154 -0
  103. package/dist/core/recordset/source.d.ts +9 -0
  104. package/dist/core/recordset/source.js +19 -0
  105. package/dist/core/recordset/sqlErrors.d.ts +6 -0
  106. package/dist/core/recordset/sqlErrors.js +39 -0
  107. package/dist/core/recordset/transitions.d.ts +10 -0
  108. package/dist/core/recordset/transitions.js +80 -0
  109. package/dist/core/recordset/types.d.ts +415 -0
  110. package/dist/core/recordset/types.js +8 -0
  111. package/dist/core/recordset/values.d.ts +33 -0
  112. package/dist/core/recordset/values.js +177 -0
  113. package/dist/core/recordset/writes.d.ts +42 -0
  114. package/dist/core/recordset/writes.js +786 -0
  115. package/dist/core/registry/ddl.d.ts +31 -0
  116. package/dist/core/registry/ddl.js +174 -0
  117. package/dist/core/registry/extension.d.ts +94 -0
  118. package/dist/core/registry/extension.js +90 -0
  119. package/dist/core/registry/module.d.ts +89 -0
  120. package/dist/core/registry/module.js +98 -0
  121. package/dist/core/registry/registry.d.ts +130 -0
  122. package/dist/core/registry/registry.js +591 -0
  123. package/dist/core/security/runtime.d.ts +102 -0
  124. package/dist/core/security/runtime.js +232 -0
  125. package/dist/driver-pg/driver.d.ts +88 -0
  126. package/dist/driver-pg/driver.js +177 -0
  127. package/dist/driver-pg/errors.d.ts +72 -0
  128. package/dist/driver-pg/errors.js +182 -0
  129. package/dist/driver-pg/index.d.ts +7 -0
  130. package/dist/driver-pg/index.js +7 -0
  131. package/dist/i18n/index.d.ts +25 -0
  132. package/dist/i18n/index.js +51 -0
  133. package/dist/migrate/apply.d.ts +78 -0
  134. package/dist/migrate/apply.js +167 -0
  135. package/dist/migrate/catalog.d.ts +10 -0
  136. package/dist/migrate/catalog.js +122 -0
  137. package/dist/migrate/diff.d.ts +98 -0
  138. package/dist/migrate/diff.js +160 -0
  139. package/dist/migrate/errors.d.ts +21 -0
  140. package/dist/migrate/errors.js +31 -0
  141. package/dist/migrate/index.d.ts +18 -0
  142. package/dist/migrate/index.js +18 -0
  143. package/dist/migrate/render.d.ts +5 -0
  144. package/dist/migrate/render.js +101 -0
  145. package/dist/migrate/schema.d.ts +61 -0
  146. package/dist/migrate/schema.js +233 -0
  147. package/dist/security/index.d.ts +147 -0
  148. package/dist/security/index.js +278 -0
  149. package/dist/sequence/index.d.ts +63 -0
  150. package/dist/sequence/index.js +106 -0
  151. package/dist/sql/ast.d.ts +49 -0
  152. package/dist/sql/ast.js +47 -0
  153. package/dist/sql/builder/builder.d.ts +215 -0
  154. package/dist/sql/builder/builder.js +308 -0
  155. package/dist/sql/builder/expression.d.ts +80 -0
  156. package/dist/sql/builder/expression.js +126 -0
  157. package/dist/sql/compile.d.ts +18 -0
  158. package/dist/sql/compile.js +41 -0
  159. package/dist/sql/errors.d.ts +13 -0
  160. package/dist/sql/errors.js +16 -0
  161. package/dist/sql/index.d.ts +19 -0
  162. package/dist/sql/index.js +19 -0
  163. package/dist/sql/tag.d.ts +47 -0
  164. package/dist/sql/tag.js +123 -0
  165. package/package.json +82 -4
@@ -0,0 +1,17 @@
1
+ import type { ComputeFn, InverseFn } from './field.js';
2
+ /** The path a compute function mirrors, when it is a {@link related} compute. */
3
+ export declare function relatedPath(fn: unknown): string | undefined;
4
+ /** Field options mirroring `path`; spread them into the field. @throws {InvalidFieldError} for a malformed path. */
5
+ export declare function related(path: string, options: {
6
+ readonly writable: true;
7
+ }): {
8
+ readonly depends: readonly [string];
9
+ readonly compute: ComputeFn;
10
+ readonly inverse: InverseFn;
11
+ };
12
+ export declare function related(path: string, options?: {
13
+ readonly writable?: false;
14
+ }): {
15
+ readonly depends: readonly [string];
16
+ readonly compute: ComputeFn;
17
+ };
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Related fields: a field that mirrors a field of a related record through many2one steps (`'partner.country.code'`),
3
+ * built on the compute engine, so stored related fields get dependency tracking, batching and audit like any
4
+ * stored compute. With `writable: true`, writing the field writes the related record.
5
+ *
6
+ * ```ts
7
+ * partnerEmail: f.char({ ...related('partner.email') }), // read-only, computed on load
8
+ * currency: f.many2one('res.currency', { store: true, ...related('order.currency') }),
9
+ * ```
10
+ */
11
+ import { InvalidFieldError } from '../errors.js';
12
+ const RELATED = Symbol.for('shutro.related');
13
+ const PATH = /^[a-z][A-Za-z0-9]*(\.[a-z][A-Za-z0-9]*)+$/;
14
+ /** The path a compute function mirrors, when it is a {@link related} compute. */
15
+ export function relatedPath(fn) {
16
+ return typeof fn === 'function' ? fn[RELATED] : undefined;
17
+ }
18
+ function idOf(value) {
19
+ // The last step of a many2one path is a record: store its id.
20
+ if (typeof value === 'object' && value !== null && 'ids' in value && 'modelName' in value)
21
+ return value.ids[0] ?? null;
22
+ return value;
23
+ }
24
+ export function related(path, options = {}) {
25
+ if (!PATH.test(path))
26
+ throw new InvalidFieldError(`${JSON.stringify(path)} is not a related path.`, "Use many2one steps then a field: related('partner.email'), related('order.partner.country').");
27
+ const steps = path.split('.');
28
+ const last = steps.at(-1);
29
+ const parent = (record) => {
30
+ let current = record;
31
+ for (const step of steps.slice(0, -1)) {
32
+ current = current?.[step] ?? null;
33
+ if (current === null)
34
+ return null;
35
+ }
36
+ return current;
37
+ };
38
+ const compute = (records, keys) => {
39
+ for (const r of records) {
40
+ const from = parent(r);
41
+ const value = from === null ? null : idOf(from[last]);
42
+ for (const key of keys)
43
+ r[key] = value;
44
+ }
45
+ };
46
+ Object.defineProperty(compute, RELATED, { value: path });
47
+ const inverse = async (records, key) => {
48
+ for (const r of records) {
49
+ const target = parent(r);
50
+ if (target === null)
51
+ throw new InvalidFieldError(`Cannot write '${key}': the related record along '${path}' is empty.`, `Set ${steps.slice(0, -1).join('.')} first.`);
52
+ await target.write({ [last]: idOf(r[key]) });
53
+ }
54
+ };
55
+ return Object.freeze({
56
+ depends: Object.freeze([path]),
57
+ compute: compute,
58
+ ...(options.writable === true ? { inverse: inverse } : {}),
59
+ });
60
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Typed definition callbacks (feedback #1, #2). `defineModel` cannot type its own callbacks against the schema it is
3
+ * part of (the schema is inferred from the definitions, TS7022). The generated per-module view (`shutro generate`,
4
+ * RFC 0002 §7.7) is a declared interface, so callbacks typed against it break the cycle:
5
+ *
6
+ * ```ts
7
+ * // modules/sale/.shutro/bindings.ts (generated) exports these helpers bound to the module's view.
8
+ * import { compute, defineModel, f } from './.shutro/bindings.ts';
9
+ *
10
+ * amountTotal: f.monetary({
11
+ * currency: 'currency',
12
+ * store: true,
13
+ * ...compute('sale.order', 'amountTotal', ['lines.subtotal', 'taxRate'], (orders) => {
14
+ * for (const o of orders) o.amountTotal = o.lines.sum('subtotal', o.currency).times(o.taxRate.plus(1));
15
+ * }),
16
+ * }),
17
+ * ```
18
+ *
19
+ * At runtime the helpers return their callbacks unchanged; only the types differ.
20
+ */
21
+ import { type DataRecord } from '../data/data.js';
22
+ import type { Env } from '../env/env.js';
23
+ import type { ComputedKeys, ComputeSet, CreateValues, DefaultLoaded, Draft, Merge, ModelName, RecordSet, RelKeys, Target, WriteValues } from '../recordset/types.js';
24
+ import type { ComputeFn } from './field.js';
25
+ import type { Id } from './id.js';
26
+ import type { OnchangeFn } from './model.js';
27
+ type NoRels = Record<never, never>;
28
+ /** The loaded shape one `depends` path guarantees: `'lines.subtotal'` loads `lines` with `subtotal`. */
29
+ export type PathLoaded<S, M extends ModelName<S>, P extends string> = P extends `${infer H}.${infer R}` ? H extends RelKeys<S, M> ? {
30
+ readonly s: 'id';
31
+ readonly r: {
32
+ readonly [K in H]: PathLoaded<S, Target<S, M, K> & ModelName<S>, R>;
33
+ };
34
+ } : {
35
+ readonly s: 'id';
36
+ readonly r: NoRels;
37
+ } : P extends RelKeys<S, M> ? {
38
+ readonly s: 'id';
39
+ readonly r: {
40
+ readonly [K in P]: DefaultLoaded<S, Target<S, M, K> & ModelName<S>>;
41
+ };
42
+ } : {
43
+ readonly s: P | 'id';
44
+ readonly r: NoRels;
45
+ };
46
+ /** The records' loaded shape from their `depends` paths: the defaults plus every path. */
47
+ export type LoadedFrom<S, M extends ModelName<S>, D extends readonly string[], Acc = DefaultLoaded<S, M>> = D extends readonly [infer H extends string, ...infer T extends readonly string[]] ? LoadedFrom<S, M, T, Merge<Acc, PathLoaded<S, M, H>>> : Acc;
48
+ type NoMethods = Record<never, never>;
49
+ /**
50
+ * `S` with every model's methods left out. The generated view takes methods from the module's own type, so callback
51
+ * records that carried methods would make each definition depend on itself (TS7022). Recordsets in callbacks
52
+ * therefore have fields and the recordset API but not the model's methods; `method()` bodies have them.
53
+ */
54
+ export type PlainView<S> = {
55
+ readonly [M in keyof S]: Omit<S[M], 'methods'> & {
56
+ readonly methods: NoMethods;
57
+ };
58
+ };
59
+ type Records<S, M extends ModelName<S>, L = DefaultLoaded<S, M>> = RecordSet<S, M, L>;
60
+ /** The helpers `definitions<View>()` returns; generated bindings export them bound to the module's view. */
61
+ export interface DefinitionHelpers<S, P = PlainView<S>> {
62
+ /**
63
+ * A compute: the records are loaded along `depends`, and only the `assigns` fields are writable (other computed
64
+ * fields read with their read type). Spread the result into the field options.
65
+ */
66
+ compute<const M extends ModelName<S> & ModelName<P>, const A extends ComputedKeys<P, M>, const D extends readonly string[]>(model: M, assigns: A | readonly A[], depends: D, fn: (records: ComputeSet<P, M, LoadedFrom<P, M, D>, A>) => void | Promise<void>): {
67
+ readonly depends: D;
68
+ readonly compute: ComputeFn;
69
+ };
70
+ /** A constraint check: returns the failing records. Spread the result into the constraint, next to `message`. */
71
+ check<const M extends ModelName<S> & ModelName<P>, const D extends readonly string[]>(model: M, depends: D, fn: (records: Records<P, M, LoadedFrom<P, M, D>>) => unknown): {
72
+ readonly depends: D;
73
+ readonly check: (records: never) => unknown;
74
+ };
75
+ /** An onchange handler with a typed draft. */
76
+ onchange<const M extends ModelName<S> & ModelName<P>>(model: M, fn: (draft: Draft<P, M>, env: Env<P>) => void | Promise<void>): OnchangeFn;
77
+ /** A records callback: transition guards and events, constraint messages. */
78
+ records<const M extends ModelName<S> & ModelName<P>>(model: M, fn: (records: Records<P, M>) => unknown): (records: never) => unknown;
79
+ /** A data record the module ships (RFC 0017), typed like a create. */
80
+ record<const M extends ModelName<S> & ModelName<P>>(model: M, name: string, values: CreateValues<P, M>, options?: {
81
+ readonly noupdate?: boolean;
82
+ }): DataRecord;
83
+ /** Updates a dependency's data record (`'base.main_company'`), typed like a write. */
84
+ override<const M extends ModelName<S> & ModelName<P>>(model: M, id: string, values: WriteValues<P, M>): DataRecord;
85
+ /** A reference to a data record: an id of `model` in data values. */
86
+ ref<const M extends ModelName<S>>(model: M, id: string): Id<M>;
87
+ /**
88
+ * A model method: `this` is the recordset it is called on, with the model's methods. Annotate the return type
89
+ * (TypeScript must not infer it from the body, which would need the methods' own types).
90
+ */
91
+ method<const M extends ModelName<S>, A extends unknown[], R>(model: M, fn: (this: Records<S, M>, ...args: A) => R): (this: unknown, ...args: A) => R;
92
+ /**
93
+ * A model method that runs with extra grants (RFC 0014 §7.9): what it touches beyond the caller's rights is
94
+ * declared here, and each call is audited (`elevate`). `reason` defaults to `'<model>.<method>'`.
95
+ *
96
+ * ```ts
97
+ * createInvoices: method('sale.order', { elevate: ['sale.order.line:read'] }, async function (): Promise<...> { ... }),
98
+ * ```
99
+ */
100
+ method<const M extends ModelName<S>, A extends unknown[], R>(model: M, options: {
101
+ readonly elevate: readonly string[];
102
+ readonly reason?: string;
103
+ }, fn: (this: Records<S, M>, ...args: A) => Promise<R>): (this: unknown, ...args: A) => Promise<R>;
104
+ }
105
+ /** Helpers that type definition callbacks against a schema view (normally the generated one). */
106
+ export declare function definitions<S>(): DefinitionHelpers<S>;
107
+ export {};
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Typed definition callbacks (feedback #1, #2). `defineModel` cannot type its own callbacks against the schema it is
3
+ * part of (the schema is inferred from the definitions, TS7022). The generated per-module view (`shutro generate`,
4
+ * RFC 0002 §7.7) is a declared interface, so callbacks typed against it break the cycle:
5
+ *
6
+ * ```ts
7
+ * // modules/sale/.shutro/bindings.ts (generated) exports these helpers bound to the module's view.
8
+ * import { compute, defineModel, f } from './.shutro/bindings.ts';
9
+ *
10
+ * amountTotal: f.monetary({
11
+ * currency: 'currency',
12
+ * store: true,
13
+ * ...compute('sale.order', 'amountTotal', ['lines.subtotal', 'taxRate'], (orders) => {
14
+ * for (const o of orders) o.amountTotal = o.lines.sum('subtotal', o.currency).times(o.taxRate.plus(1));
15
+ * }),
16
+ * }),
17
+ * ```
18
+ *
19
+ * At runtime the helpers return their callbacks unchanged; only the types differ.
20
+ */
21
+ import { override, record, ref } from '../data/data.js';
22
+ /** Helpers that type definition callbacks against a schema view (normally the generated one). */
23
+ export function definitions() {
24
+ return {
25
+ compute: (_model, _assigns, depends, fn) => ({ depends, compute: fn }),
26
+ check: (_model, depends, fn) => ({
27
+ depends,
28
+ check: fn,
29
+ }),
30
+ onchange: (_model, fn) => fn,
31
+ record: (model, name, values, options) => record(model, name, values, options),
32
+ override: (model, id, values) => override(model, id, values),
33
+ ref: (model, id) => ref(model, id),
34
+ records: (_model, fn) => fn,
35
+ method: ((model, second, third) => {
36
+ if (typeof second === 'function')
37
+ return second;
38
+ const { elevate, reason } = second;
39
+ const fn = third;
40
+ return async function (...args) {
41
+ const records = this;
42
+ return records.env.withGrants({ grants: elevate, reason: reason ?? `${model}.${fn.name || 'method'}` }, (env) => fn.call(env.model(model).browse(records.ids), ...args));
43
+ };
44
+ }),
45
+ };
46
+ }
@@ -0,0 +1,39 @@
1
+ import { type Decimal, type DecimalInput } from './decimal.js';
2
+ import type { RoundingMethod } from './rounding.js';
3
+ /**
4
+ * The rounding-relevant attributes of a currency (a snapshot of a `res.currency` record, RFC 0006 §7.2).
5
+ * Immutable. Two currencies are the same when their ISO codes match (and their ids, when both have one).
6
+ */
7
+ export interface Currency {
8
+ /** ISO 4217 code, e.g. `'BDT'`. */
9
+ readonly code: string;
10
+ /** Database id of the `res.currency` record, when known. */
11
+ readonly id: number | undefined;
12
+ /** Smallest unit amounts are rounded to: `0.01`, `1` (JPY), `0.05` (cash rounding). */
13
+ readonly rounding: Decimal;
14
+ /** Digits shown after the decimal point; at least the digits of `rounding`. */
15
+ readonly decimalPlaces: number;
16
+ /** Default rounding method. */
17
+ readonly roundingMethod: RoundingMethod;
18
+ }
19
+ /** Input of {@link defineCurrency}. */
20
+ export interface CurrencyInput {
21
+ readonly code: string;
22
+ readonly rounding: DecimalInput;
23
+ readonly roundingMethod?: RoundingMethod;
24
+ readonly decimalPlaces?: number;
25
+ readonly id?: number;
26
+ }
27
+ /**
28
+ * Creates a {@link Currency}. `decimalPlaces` defaults to the digits of `rounding`, `roundingMethod` to `half-up`.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * const BDT = defineCurrency({ code: 'BDT', rounding: '0.01' });
33
+ * const CHF_CASH = defineCurrency({ code: 'CHF', rounding: '0.05' });
34
+ * ```
35
+ * @throws {InvalidCurrencyError} for a code that isn't 3 upper-case letters, a non-positive rounding, or too few decimal places.
36
+ */
37
+ export declare function defineCurrency(input: CurrencyInput): Currency;
38
+ /** True when `a` and `b` denote the same currency. */
39
+ export declare function sameCurrency(a: Currency, b: Currency): boolean;
@@ -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,68 @@
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 company's currency (the rate base). */
34
+ readonly companyCurrency: Currency;
35
+ /**
36
+ * A currency these rates were prepared for (or the company currency), by id: synchronous.
37
+ * @throws {MissingRateError} for an id that was not prepared.
38
+ */
39
+ currency(id: number): Currency;
40
+ /** The rate of a currency relative to the company currency (units per one unit of the company currency). */
41
+ rate(currency: Currency | number): {
42
+ readonly rate: Decimal;
43
+ readonly date: string | null;
44
+ };
45
+ /** Converts with the prepared rates; `to` may be a prepared currency id. */
46
+ convert(money: Money, to: Currency | number, options?: {
47
+ readonly round?: boolean;
48
+ }): Conversion;
49
+ }
50
+ /** `env.fx`. */
51
+ export interface Fx {
52
+ /** Converts one amount. @throws {MissingRateError} when no rate exists on or before the date. */
53
+ convert(money: Money, to: Currency | number, options: ConvertOptions): Promise<Conversion>;
54
+ /** Loads the rates of several currencies in one query. */
55
+ prepare(options: {
56
+ readonly date: string;
57
+ readonly currencies: readonly (Currency | number)[];
58
+ readonly company?: number | undefined;
59
+ }): Promise<PreparedRates>;
60
+ }
61
+ /** What the fx engine needs from the environment. */
62
+ export interface FxHost {
63
+ readonly internals: ScopeInternals;
64
+ currency(id: number): Promise<Currency>;
65
+ companyCurrency(company: number): Promise<Currency>;
66
+ }
67
+ /** Creates `env.fx` for a scope. */
68
+ export declare function createFx(host: FxHost): Fx;
@@ -0,0 +1,124 @@
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 byId = new Map();
58
+ for (const c of [companyCurrency, ...wanted])
59
+ if (c.id !== undefined)
60
+ byId.set(c.id, c);
61
+ const currencyOf = (id) => {
62
+ const found = byId.get(id);
63
+ if (found !== undefined)
64
+ return found;
65
+ throw new MissingRateError(`Currency ${id} was not prepared for ${options.date}.`, 'Pass it in prepare({ currencies }), or use env.fx.convert() for a one-off conversion.');
66
+ };
67
+ const asCurrency = (c) => typeof c === 'number' ? currencyOf(c) : c;
68
+ const rateOf = (wantedCurrency) => {
69
+ const currency = asCurrency(wantedCurrency);
70
+ if (currency.id !== undefined) {
71
+ const found = rates.get(currency.id);
72
+ if (found !== undefined)
73
+ return found;
74
+ }
75
+ if (currency.code === companyCurrency.code)
76
+ return { rate: toDecimal(1), date: null };
77
+ 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.`);
78
+ };
79
+ return {
80
+ date: options.date,
81
+ company,
82
+ companyCurrency,
83
+ currency: currencyOf,
84
+ rate: rateOf,
85
+ convert(money, toCurrency, opts = {}) {
86
+ const to = asCurrency(toCurrency);
87
+ const from = money.currency;
88
+ if (from.code === to.code) {
89
+ return {
90
+ money: Money.of(money.amount, to),
91
+ from,
92
+ to,
93
+ rate: toDecimal(1),
94
+ rateDate: null,
95
+ };
96
+ }
97
+ const source = rateOf(from);
98
+ const target = rateOf(to);
99
+ const rate = target.rate.div(source.rate);
100
+ const amount = money.amount.times(rate);
101
+ const result = Money.of(amount, to);
102
+ return {
103
+ money: opts.round === false ? result : result.round(),
104
+ from,
105
+ to,
106
+ rate,
107
+ rateDate: source.date ?? target.date,
108
+ };
109
+ },
110
+ };
111
+ }
112
+ return {
113
+ async convert(money, to, options) {
114
+ const target = await resolve(to);
115
+ const prepared = await prepare({
116
+ date: options.date,
117
+ currencies: [money.currency, target],
118
+ company: options.company,
119
+ });
120
+ return prepared.convert(money, target, { round: options.round ?? true });
121
+ },
122
+ prepare,
123
+ };
124
+ }