shutro 0.1.0 → 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 (74) hide show
  1. package/README.md +12 -2
  2. package/dist/audit/index.d.ts +3 -1
  3. package/dist/audit/index.js +2 -0
  4. package/dist/cli/cli.js +17 -2
  5. package/dist/cli/config.js +2 -0
  6. package/dist/cli/generate/generate.js +2 -0
  7. package/dist/cli/generate/render.js +57 -8
  8. package/dist/cli/init.js +4 -4
  9. package/dist/cli/resolve.d.ts +2 -0
  10. package/dist/cli/resolve.js +28 -0
  11. package/dist/core/data/data.d.ts +59 -0
  12. package/dist/core/data/data.js +119 -0
  13. package/dist/core/data/load.d.ts +37 -0
  14. package/dist/core/data/load.js +236 -0
  15. package/dist/core/env/env.d.ts +175 -2
  16. package/dist/core/env/env.js +304 -19
  17. package/dist/core/env/identity.d.ts +10 -0
  18. package/dist/core/env/identity.js +16 -0
  19. package/dist/core/errors.d.ts +15 -1
  20. package/dist/core/errors.js +21 -0
  21. package/dist/core/events/events.d.ts +44 -0
  22. package/dist/core/events/events.js +58 -0
  23. package/dist/core/events/workers.d.ts +56 -0
  24. package/dist/core/events/workers.js +155 -0
  25. package/dist/core/index.d.ts +17 -9
  26. package/dist/core/index.js +11 -3
  27. package/dist/core/model/field.d.ts +33 -0
  28. package/dist/core/model/field.js +64 -1
  29. package/dist/core/model/generated.d.ts +4 -2
  30. package/dist/core/model/model.d.ts +40 -0
  31. package/dist/core/model/model.js +28 -0
  32. package/dist/core/model/related.d.ts +17 -0
  33. package/dist/core/model/related.js +60 -0
  34. package/dist/core/model/typed.d.ts +107 -0
  35. package/dist/core/model/typed.js +46 -0
  36. package/dist/core/money/fx.d.ts +10 -2
  37. package/dist/core/money/fx.js +17 -2
  38. package/dist/core/recordset/aggregate.d.ts +22 -0
  39. package/dist/core/recordset/aggregate.js +258 -0
  40. package/dist/core/recordset/audit.d.ts +9 -1
  41. package/dist/core/recordset/audit.js +59 -2
  42. package/dist/core/recordset/compute.d.ts +2 -0
  43. package/dist/core/recordset/compute.js +11 -2
  44. package/dist/core/recordset/domain.d.ts +4 -0
  45. package/dist/core/recordset/domain.js +74 -2
  46. package/dist/core/recordset/onchange.js +70 -37
  47. package/dist/core/recordset/recordset.d.ts +10 -1
  48. package/dist/core/recordset/recordset.js +80 -14
  49. package/dist/core/recordset/security.d.ts +15 -1
  50. package/dist/core/recordset/security.js +95 -10
  51. package/dist/core/recordset/source.d.ts +9 -0
  52. package/dist/core/recordset/source.js +19 -0
  53. package/dist/core/recordset/transitions.js +4 -1
  54. package/dist/core/recordset/types.d.ts +131 -12
  55. package/dist/core/recordset/values.d.ts +6 -0
  56. package/dist/core/recordset/values.js +34 -4
  57. package/dist/core/recordset/writes.d.ts +6 -1
  58. package/dist/core/recordset/writes.js +217 -12
  59. package/dist/core/registry/ddl.d.ts +9 -0
  60. package/dist/core/registry/ddl.js +49 -2
  61. package/dist/core/registry/module.d.ts +10 -1
  62. package/dist/core/registry/module.js +2 -0
  63. package/dist/core/registry/registry.d.ts +29 -4
  64. package/dist/core/registry/registry.js +100 -5
  65. package/dist/core/security/runtime.d.ts +102 -0
  66. package/dist/core/security/runtime.js +232 -0
  67. package/dist/driver-pg/driver.d.ts +2 -0
  68. package/dist/driver-pg/driver.js +1 -0
  69. package/dist/migrate/schema.js +40 -2
  70. package/dist/security/index.d.ts +24 -0
  71. package/dist/security/index.js +16 -0
  72. package/dist/sql/tag.d.ts +5 -0
  73. package/dist/sql/tag.js +29 -1
  74. package/package.json +1 -1
@@ -249,6 +249,30 @@ export function defineModel(name, definition) {
249
249
  fields[recName]?.kind === 'many2many') {
250
250
  fail(name, `recName '${recName}' is not a scalar field.`, 'Choose a char/text field (or leave it to `name`).');
251
251
  }
252
+ const backdate = definition.backdate;
253
+ if (backdate !== undefined) {
254
+ const kind = fields[backdate.field]?.kind;
255
+ if (kind !== 'date' && kind !== 'datetime')
256
+ fail(name, `backdate.field '${backdate.field}' is not a date or datetime field.`, 'Point it at the document date, e.g. backdate: { field: "date", permission: "account.backdate" }.');
257
+ if (backdate.graceDays !== undefined &&
258
+ (!Number.isInteger(backdate.graceDays) || backdate.graceDays < 0))
259
+ fail(name, 'backdate.graceDays must be a non-negative integer.', 'Use 0 for "today only".');
260
+ }
261
+ const delegates = [...(definition.delegates ?? [])];
262
+ for (const key of delegates) {
263
+ const field = fields[key];
264
+ if (field?.kind !== 'many2one' || field.required !== true || field.ondelete !== 'cascade')
265
+ fail(name, `delegates '${key}' must be a required many2one with ondelete: 'cascade'.`, `Declare ${key}: f.many2one('<parent model>', { required: true, ondelete: 'cascade' }).`);
266
+ }
267
+ const hierarchy = definition.hierarchy;
268
+ if (hierarchy !== undefined) {
269
+ const parent = fields[hierarchy.parent];
270
+ if (parent?.kind !== 'many2one' || parent.target !== name)
271
+ fail(name, `hierarchy.parent '${hierarchy.parent}' is not a many2one to ${name}.`, `Declare ${hierarchy.parent}: f.many2one('${name}', { ondelete: 'cascade' }).`);
272
+ const path = fields[hierarchy.path];
273
+ if (path?.kind !== 'char' || !path.readonly || path.computed)
274
+ fail(name, `hierarchy.path '${hierarchy.path}' must be a readonly char field.`, `Declare ${hierarchy.path}: f.char({ readonly: true, index: true }); the engine fills it.`);
275
+ }
252
276
  const tracking = [...(definition.tracking ?? [])];
253
277
  for (const key of tracking)
254
278
  if (!has(key))
@@ -407,6 +431,10 @@ export function defineModel(name, definition) {
407
431
  ? undefined
408
432
  : Object.freeze({ ...definition.companyScoped }),
409
433
  tracking: Object.freeze(tracking),
434
+ backdate: backdate === undefined ? undefined : Object.freeze({ ...backdate }),
435
+ hierarchy: hierarchy === undefined ? undefined : Object.freeze({ ...hierarchy }),
436
+ delegates: Object.freeze(delegates),
437
+ history: definition.history === true,
410
438
  indexes: Object.freeze(indexes),
411
439
  sqlConstraints: Object.freeze(sqlConstraints),
412
440
  constraints: Object.freeze(constraints),
@@ -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
+ }
@@ -30,12 +30,20 @@ export interface Conversion {
30
30
  export interface PreparedRates {
31
31
  readonly date: string;
32
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;
33
40
  /** The rate of a currency relative to the company currency (units per one unit of the company currency). */
34
- rate(currency: Currency): {
41
+ rate(currency: Currency | number): {
35
42
  readonly rate: Decimal;
36
43
  readonly date: string | null;
37
44
  };
38
- convert(money: Money, to: Currency, options?: {
45
+ /** Converts with the prepared rates; `to` may be a prepared currency id. */
46
+ convert(money: Money, to: Currency | number, options?: {
39
47
  readonly round?: boolean;
40
48
  }): Conversion;
41
49
  }
@@ -54,7 +54,19 @@ export function createFx(host) {
54
54
  ...new Set(wanted.map((c) => c.id).filter((id) => id !== undefined)),
55
55
  ];
56
56
  const rates = await lookupRates(host.internals, ids, options.date, company);
57
- const rateOf = (currency) => {
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);
58
70
  if (currency.id !== undefined) {
59
71
  const found = rates.get(currency.id);
60
72
  if (found !== undefined)
@@ -67,8 +79,11 @@ export function createFx(host) {
67
79
  return {
68
80
  date: options.date,
69
81
  company,
82
+ companyCurrency,
83
+ currency: currencyOf,
70
84
  rate: rateOf,
71
- convert(money, to, opts = {}) {
85
+ convert(money, toCurrency, opts = {}) {
86
+ const to = asCurrency(toCurrency);
72
87
  const from = money.currency;
73
88
  if (from.code === to.code) {
74
89
  return {
@@ -0,0 +1,22 @@
1
+ import type { ScopeInternals } from '../env/env.js';
2
+ import type { AnyModel } from '../model/model.js';
3
+ import { type TranslationScope } from './domain.js';
4
+ /** The untyped query `aggregate()` receives (typed in `AggregateQuery`). */
5
+ export interface AggregateQueryRaw {
6
+ readonly where?: Readonly<Record<string, unknown>>;
7
+ readonly groupBy?: readonly string[];
8
+ readonly measures: Readonly<Record<string, unknown>>;
9
+ readonly order?: readonly string[];
10
+ readonly limit?: number;
11
+ readonly groupingSets?: readonly (readonly string[])[];
12
+ readonly rollup?: boolean;
13
+ readonly cube?: boolean;
14
+ }
15
+ /** What the aggregate runtime needs besides the scope. */
16
+ export interface AggregateHost {
17
+ readonly internals: ScopeInternals;
18
+ readonly translation: TranslationScope;
19
+ currency(id: number): Promise<import('../money/currency.js').Currency>;
20
+ }
21
+ /** Runs an aggregate query. @throws {AccessError} @throws {InvalidDomainError} */
22
+ export declare function runAggregate(host: AggregateHost, model: AnyModel, query: AggregateQueryRaw): Promise<Record<string, unknown>[]>;
@@ -0,0 +1,258 @@
1
+ /**
2
+ * `env.model(M).aggregate()` (feedback #13): grouped totals for reports, compiled to one `GROUP BY` statement with the
3
+ * same guarantees as `search`: read ACL, field groups on every grouped, measured and filtered field, record rules,
4
+ * archived / company scoping, relation paths with the targets' rules. Monetary measures are grouped by their currency
5
+ * as well, so a total is never a sum of two currencies.
6
+ */
7
+ import { compile, sql } from '../../sql/index.js';
8
+ import { Decimal as DecimalJs } from 'decimal.js';
9
+ import { InvalidDomainError } from '../errors.js';
10
+ import { Money } from '../money/money.js';
11
+ import { compileDomain, scopingConditions } from './domain.js';
12
+ import { assertAccess, assertDomainFields, assertFields, ruleConditions } from './security.js';
13
+ const GRANULARITIES = new Set(['day', 'week', 'month', 'quarter', 'year']);
14
+ const GROUPABLE = new Set([
15
+ 'char',
16
+ 'selection',
17
+ 'state',
18
+ 'boolean',
19
+ 'integer',
20
+ 'date',
21
+ 'datetime',
22
+ 'many2one',
23
+ ]);
24
+ const NUMERIC = new Set(['integer', 'float', 'decimal', 'monetary']);
25
+ const OPS = ['sum', 'avg', 'min', 'max'];
26
+ /** The grouping sets of a query (indexes into its groups), or `undefined` for a plain GROUP BY. */
27
+ function groupingSetsOf(query, groups) {
28
+ const modes = [
29
+ query.groupingSets !== undefined,
30
+ query.rollup === true,
31
+ query.cube === true,
32
+ ].filter(Boolean);
33
+ if (modes.length === 0)
34
+ return undefined;
35
+ if (modes.length > 1)
36
+ invalid('Give one of groupingSets, rollup and cube.', 'They are alternative ways to ask for subtotals.');
37
+ const all = groups.map((_, i) => i);
38
+ if (query.rollup === true)
39
+ return all.map((_, n) => all.slice(0, all.length - n)).concat([[]]);
40
+ if (query.cube === true) {
41
+ if (groups.length > 6)
42
+ invalid(`cube over ${groups.length} groups makes ${2 ** groups.length} groupings.`, 'Use at most 6 groups, or explicit groupingSets.');
43
+ return Array.from({ length: 2 ** groups.length }, (_, mask) => all.filter((i) => (mask & (1 << i)) !== 0)).sort((a, b) => b.length - a.length);
44
+ }
45
+ const sets = (query.groupingSets ?? []).map((set) => set.map((name) => {
46
+ const index = groups.findIndex((g) => g.name === name);
47
+ if (index < 0)
48
+ invalid(`The grouping set [${set.join(', ')}] names '${name}', which is not in groupBy.`, 'Each set is a subset of groupBy.');
49
+ return index;
50
+ }));
51
+ if (sets.length === 0)
52
+ invalid('groupingSets is empty.', 'Give at least one set; [] is the grand total.');
53
+ return sets;
54
+ }
55
+ function invalid(problem, hint) {
56
+ throw new InvalidDomainError(problem, hint);
57
+ }
58
+ function groupOf(host, model, name) {
59
+ const [key = '', granularity, extra] = name.split(':');
60
+ const field = model.fields[key];
61
+ if (field === undefined ||
62
+ extra !== undefined ||
63
+ !GROUPABLE.has(field.kind) ||
64
+ model.columns[key] === undefined)
65
+ invalid(`'${name}' cannot group ${model.name}.`, 'Group by a stored char, selection, state, boolean, integer, date, datetime or many2one field; dates take a granularity, e.g. dateOrder:month.');
66
+ if (field.translate || field.companyDependent)
67
+ invalid(`'${key}' is translated or company-dependent; grouping by it is not supported.`, 'Group by an untranslated field.');
68
+ const column = sql.id(model.columns[key] ?? '');
69
+ if (granularity !== undefined) {
70
+ if (!GRANULARITIES.has(granularity) || (field.kind !== 'date' && field.kind !== 'datetime'))
71
+ invalid(`'${name}': only date and datetime fields take a granularity, one of day, week, month, quarter, year.`, 'Write e.g. dateOrder:month.');
72
+ // Datetimes are bucketed in the environment's time zone: "October" is the user's October.
73
+ const local = field.kind === 'datetime' ? sql `(${column} AT TIME ZONE ${host.internals.env.tz})` : column;
74
+ // A date, not text: the driver reads dates as 'YYYY-MM-DD' strings, and this costs nothing per row.
75
+ return { name, key, field, expr: sql `date_trunc(${granularity}, ${local})::date` };
76
+ }
77
+ if (field.kind === 'datetime')
78
+ invalid(`'${key}' is a datetime: give a granularity.`, `Write e.g. ${key}:day or ${key}:month.`);
79
+ return { name, key, field, expr: column };
80
+ }
81
+ function measureOf(model, name, spec) {
82
+ if (spec === 'count')
83
+ return { name, op: 'count', key: undefined, field: undefined, expr: sql `count(*)` };
84
+ const entries = typeof spec === 'object' && spec !== null ? Object.entries(spec) : [];
85
+ const [op, key] = (entries[0] ?? []);
86
+ if (entries.length !== 1 || !OPS.includes(op) || typeof key !== 'string')
87
+ invalid(`Measure '${name}' must be 'count' or one of { sum | avg | min | max: field }.`, "Write e.g. measures: { orders: 'count', total: { sum: 'amountTotal' } }.");
88
+ const field = model.fields[key];
89
+ if (field === undefined || !NUMERIC.has(field.kind) || model.columns[key] === undefined)
90
+ invalid(`Measure '${name}': '${key}' is not a stored numeric field of ${model.name}.`, 'Measure an integer, float, decimal or monetary field.');
91
+ const column = sql.id(model.columns[key] ?? '');
92
+ const expr = op === 'sum'
93
+ ? sql `coalesce(sum(${column}), 0)`
94
+ : op === 'avg'
95
+ ? sql `avg(${column})`
96
+ : op === 'min'
97
+ ? sql `min(${column})`
98
+ : sql `max(${column})`;
99
+ return { name, op: op, key, field, expr };
100
+ }
101
+ /** The aggregate of a measure over `ref` (the column, or its alias in a grouping-sets subquery). */
102
+ function aggregateOf(measure, ref) {
103
+ switch (measure.op) {
104
+ case 'count':
105
+ return sql `count(*)`;
106
+ case 'sum':
107
+ return sql `coalesce(sum(${ref}), 0)`;
108
+ case 'avg':
109
+ return sql `avg(${ref})`;
110
+ case 'min':
111
+ return sql `min(${ref})`;
112
+ case 'max':
113
+ return sql `max(${ref})`;
114
+ }
115
+ }
116
+ function convert(measure, raw, currency) {
117
+ if (measure.op === 'count')
118
+ return Number(raw);
119
+ if (raw === null || raw === undefined)
120
+ return null;
121
+ const kind = measure.field?.kind;
122
+ if (kind === 'integer' || kind === 'float') {
123
+ if (measure.op === 'avg')
124
+ return new DecimalJs(String(raw));
125
+ return Number(raw);
126
+ }
127
+ const amount = new DecimalJs(String(raw));
128
+ if (kind === 'monetary')
129
+ return currency === undefined ? null : Money.of(amount, currency);
130
+ return amount;
131
+ }
132
+ /** Runs an aggregate query. @throws {AccessError} @throws {InvalidDomainError} */
133
+ export async function runAggregate(host, model, query) {
134
+ const { internals } = host;
135
+ assertAccess(internals, model, 'read');
136
+ assertDomainFields(internals, model, query.where);
137
+ const groups = (query.groupBy ?? []).map((name) => groupOf(host, model, name));
138
+ const measures = Object.entries(query.measures).map(([name, spec]) => measureOf(model, name, spec));
139
+ if (measures.length === 0)
140
+ invalid('aggregate() needs at least one measure.', "Add e.g. measures: { count: 'count' }.");
141
+ const names = new Set();
142
+ for (const n of [...groups.map((g) => g.name), ...measures.map((m) => m.name)]) {
143
+ if (names.has(n))
144
+ invalid(`'${n}' is both a group and a measure.`, 'Rename the measure.');
145
+ names.add(n);
146
+ }
147
+ assertFields(internals, model, [...groups.map((g) => g.key), ...measures.flatMap((m) => (m.key === undefined ? [] : [m.key]))], 'read');
148
+ // Each monetary measure is also grouped by its currency field (never a sum across currencies).
149
+ const currencyKeys = [
150
+ ...new Set(measures.flatMap((m) => m.field?.kind === 'monetary'
151
+ ? [m.field.currencyField]
152
+ : [])),
153
+ ];
154
+ for (const key of currencyKeys) {
155
+ if (model.columns[key] === undefined)
156
+ invalid(`The currency field '${key}' of ${model.name} is not stored, so monetary totals cannot be grouped by it.`, 'Store the currency field (store: true on a related currency).');
157
+ }
158
+ await internals.flush(); // the totals must see pending writes, including the targets of relation paths
159
+ const sets = groupingSetsOf(query, groups);
160
+ const conditions = [
161
+ ...compileDomain(model, query.where, host.translation, (n) => internals.registry.get(n).model, (target) => ruleConditions(internals, target, 'read')),
162
+ ...scopingConditions(model, internals.env),
163
+ ...ruleConditions(internals, model, 'read'),
164
+ ];
165
+ const where = conditions.length === 0 ? sql.empty : sql ` WHERE ${sql.join(conditions, sql ` AND `)}`;
166
+ const from = host.translation.from?.(model) ?? sql.id(model.table);
167
+ const limit = query.limit === undefined ? sql.empty : sql ` LIMIT ${query.limit}`;
168
+ let statement;
169
+ if (sets === undefined) {
170
+ const select = [
171
+ ...groups.map((g, i) => sql `${g.expr} AS ${sql.id(`g${i}`)}`),
172
+ ...currencyKeys.map((k, i) => sql `${sql.id(model.columns[k] ?? '')} AS ${sql.id(`c${i}`)}`),
173
+ ...measures.map((m, i) => sql `${m.expr} AS ${sql.id(`m${i}`)}`),
174
+ ];
175
+ const grouping = [
176
+ ...groups.map((_, i) => sql.id(`g${i}`)),
177
+ ...currencyKeys.map((_, i) => sql.id(`c${i}`)),
178
+ ];
179
+ const groupBy = grouping.length === 0 ? sql.empty : sql ` GROUP BY ${sql.join(grouping)}`;
180
+ const order = orderOf(query.order, groups, measures, grouping);
181
+ statement = sql `SELECT ${sql.join(select)} FROM ${from}${where}${groupBy}${order}${limit}`;
182
+ }
183
+ else {
184
+ // Grouping sets: an inner query computes each group expression and measure input once (bind parameters such as
185
+ // the granularity or time zone would otherwise make two copies of an expression differ), the outer one groups
186
+ // by their names. The currency stays in every set: a subtotal is never a sum of two currencies.
187
+ const inner = [
188
+ sql `1 AS ${sql.id('one')}`,
189
+ ...groups.map((g, i) => sql `${g.expr} AS ${sql.id(`g${i}`)}`),
190
+ ...currencyKeys.map((k, i) => sql `${sql.id(model.columns[k] ?? '')} AS ${sql.id(`c${i}`)}`),
191
+ ...measures.flatMap((m, i) => m.key === undefined
192
+ ? []
193
+ : [sql `${sql.id(model.columns[m.key] ?? '')} AS ${sql.id(`v${i}`)}`]),
194
+ ];
195
+ const currencies = currencyKeys.map((_, i) => sql.id(`c${i}`));
196
+ const select = [
197
+ ...groups.map((_, i) => sql `${sql.id(`g${i}`)}`),
198
+ ...currencies,
199
+ ...measures.map((m, i) => sql `${aggregateOf(m, sql.id(`v${i}`))} AS ${sql.id(`m${i}`)}`),
200
+ groups.length === 0
201
+ ? sql `0 AS ${sql.id('gl')}`
202
+ : sql `GROUPING(${sql.join(groups.map((_, i) => sql.id(`g${i}`)))}) AS ${sql.id('gl')}`,
203
+ ];
204
+ const groupingSets = sql `GROUPING SETS (${sql.join(sets.map((set) => sql `(${sql.join([...set.map((i) => sql.id(`g${i}`)), ...currencies])})`))})`;
205
+ // Leaves first, then each subtotal level, then the grand total.
206
+ const order = orderOf(query.order, groups, measures, [...groups.map((_, i) => sql.id(`g${i}`)), ...currencies], sql `${sql.id('gl')} ASC`);
207
+ statement = sql `SELECT ${sql.join(select)} FROM (SELECT ${sql.join(inner)} FROM ${from}${where}) AS ${sql.id('t')} GROUP BY ${groupingSets}${order}${limit}`;
208
+ }
209
+ const rows = await internals.query(compile(statement));
210
+ const out = [];
211
+ for (const row of rows) {
212
+ const result = {};
213
+ if (sets !== undefined) {
214
+ // GROUPING() sets bit (n - 1 - i) when group i is aggregated away in this row.
215
+ const mask = groups.length === 0 ? 0 : Number(row['gl']);
216
+ result['$groups'] = groups
217
+ .filter((_, i) => (mask & (1 << (groups.length - 1 - i))) === 0)
218
+ .map((g) => g.name);
219
+ }
220
+ groups.forEach((g, i) => {
221
+ const value = row[`g${i}`];
222
+ result[g.name] =
223
+ value === null || value === undefined
224
+ ? null
225
+ : g.field.kind === 'many2one' || g.field.kind === 'integer'
226
+ ? Number(value)
227
+ : value;
228
+ });
229
+ for (const [i, m] of measures.entries()) {
230
+ let currency;
231
+ if (m.field?.kind === 'monetary') {
232
+ const ci = currencyKeys.indexOf(m.field.currencyField);
233
+ const id = row[`c${ci}`];
234
+ currency = id === null || id === undefined ? undefined : await host.currency(Number(id));
235
+ }
236
+ result[m.name] = convert(m, row[`m${i}`], currency);
237
+ }
238
+ out.push(result);
239
+ }
240
+ return out;
241
+ }
242
+ function orderOf(order, groups, measures, grouping, first) {
243
+ const lead = first === undefined ? [] : [first];
244
+ if (order === undefined || order.length === 0)
245
+ return grouping.length === 0 && lead.length === 0
246
+ ? sql.empty
247
+ : sql ` ORDER BY ${sql.join([...lead, ...grouping.map((g) => sql `${g} ASC NULLS LAST`)])}`;
248
+ const terms = order.map((term) => {
249
+ const [name = '', direction = 'asc', extra] = term.trim().split(/\s+/);
250
+ const gi = groups.findIndex((g) => g.name === name);
251
+ const mi = measures.findIndex((m) => m.name === name);
252
+ if ((gi < 0 && mi < 0) || extra !== undefined || (direction !== 'asc' && direction !== 'desc'))
253
+ invalid(`Cannot order the aggregate by '${term}'.`, "Order by a group or a measure name, optionally followed by 'asc' or 'desc'.");
254
+ const alias = sql.id(gi >= 0 ? `g${gi}` : `m${mi}`);
255
+ return direction === 'desc' ? sql `${alias} DESC NULLS LAST` : sql `${alias} ASC NULLS LAST`;
256
+ });
257
+ return sql ` ORDER BY ${sql.join([...lead, ...terms])}`;
258
+ }
@@ -17,9 +17,17 @@ export declare function trackChange(internals: ScopeInternals, model: AnyModel,
17
17
  export declare function trackSnapshot(internals: ScopeInternals, model: AnyModel, id: number, action: 'create' | 'unlink', values: ReadonlyMap<string, unknown>): void;
18
18
  /** Records a superuser scope (RFC 0003 §7.6). */
19
19
  export declare function trackSuperuser(internals: ScopeInternals, reason: string): void;
20
+ /** Records a scoped elevation (`env.withGrants`, elevated methods): which grants, and why (RFC 0014 §7.9). */
21
+ export declare function trackElevation(internals: ScopeInternals, grants: readonly string[], reason: string): void;
22
+ /** Records a runtime security change (RFC 0014 §7.10). */
23
+ export declare function trackSecurityChange(internals: ScopeInternals, change: object): void;
20
24
  /** Coalesces `write` rows per (model, record, field): the first old, the last new; unchanged values are dropped. */
21
25
  export declare function coalesceAudit(rows: readonly AuditRowInput[]): AuditRowInput[];
22
26
  /** Writes the pending rows of `model` (or every row) in one statement. */
23
27
  export declare function flushAudit(internals: ScopeInternals, model?: string): Promise<void>;
24
- /** `records.trail()`: the rows of these records, newest first, after a flush. */
28
+ /**
29
+ * `records.trail()`: the rows of these records, newest first, after a flush. Field security applies: rows of fields
30
+ * the scope may not read are left out, and such fields are removed from create / delete snapshots. `limit` counts
31
+ * the rows returned (more are read when some are left out), so a page shorter than `limit` is the last one.
32
+ */
25
33
  export declare function trailOf(internals: ScopeInternals, model: AnyModel, ids: readonly number[], filter: Omit<TrailFilter, 'model' | 'recordIds'>): Promise<AuditEntry[]>;