shutro 0.1.0 → 0.2.1

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 (76) 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/apply.d.ts +5 -1
  70. package/dist/migrate/apply.js +20 -2
  71. package/dist/migrate/schema.js +40 -2
  72. package/dist/security/index.d.ts +24 -0
  73. package/dist/security/index.js +16 -0
  74. package/dist/sql/tag.d.ts +5 -0
  75. package/dist/sql/tag.js +29 -1
  76. package/package.json +1 -1
@@ -3,7 +3,7 @@
3
3
  * fragments, per-record checks for writes and deletes, and encryption of stored values. Superuser scopes bypass
4
4
  * the checks; multi-company consistency does not live here (RFC 0003 §7.4).
5
5
  */
6
- import { type Perm, type RulePerm } from '../../security/index.js';
6
+ import { type FieldGroups, type Perm, type RulePerm } from '../../security/index.js';
7
7
  import { type SqlFragment } from '../../sql/index.js';
8
8
  import type { ScopeInternals } from '../env/env.js';
9
9
  import type { Field } from '../model/field.js';
@@ -12,6 +12,20 @@ import type { AnyModel } from '../model/model.js';
12
12
  export declare function canAccess(internals: ScopeInternals, model: AnyModel, perm: Perm): boolean;
13
13
  /** @throws {AccessError} unless {@link canAccess}. */
14
14
  export declare function assertAccess(internals: ScopeInternals, model: AnyModel, perm: Perm): void;
15
+ /**
16
+ * True when the environment has the feature permission `code` (RFC 0014 §7.9): one of its groups grants it, or it
17
+ * is an administrator / superuser. @throws {SecurityDefinitionError} for a code no module declares (a typo).
18
+ */
19
+ export declare function hasPermission(internals: ScopeInternals, code: string): boolean;
20
+ /** @throws {AccessError} unless {@link hasPermission}. */
21
+ export declare function assertPermission(internals: ScopeInternals, code: string): void;
22
+ /**
23
+ * Back-dated entries (RFC 0014 §7.9): `dates` (values of the model's `backdate.field`) before today minus the grace
24
+ * days need the model's back-date permission. @throws {AccessError}
25
+ */
26
+ export declare function assertBackdate(internals: ScopeInternals, model: AnyModel, dates: Iterable<unknown>): void;
27
+ /** The groups of a field: its code groups plus the runtime field security (RFC 0014 §7.10). */
28
+ export declare function fieldGroupsOf(internals: ScopeInternals, model: AnyModel, key: string): FieldGroups;
15
29
  /** True when the field may be read / written by the environment. */
16
30
  export declare function canField(internals: ScopeInternals, model: AnyModel, key: string, kind: 'read' | 'write'): boolean;
17
31
  /** @throws {AccessError} naming the first field the environment may not read / write. */
@@ -3,17 +3,30 @@
3
3
  * fragments, per-record checks for writes and deletes, and encryption of stored values. Superuser scopes bypass
4
4
  * the checks; multi-company consistency does not live here (RFC 0003 §7.4).
5
5
  */
6
- import { allowed, applicableRules, decrypt, EncryptionError, encrypt, fieldAllowed, resolvePlaceholders, } from '../../security/index.js';
6
+ import { allowed, applicableRules, decrypt, EncryptionError, encrypt, fieldAllowed, resolvePlaceholders, SecurityDefinitionError, } from '../../security/index.js';
7
7
  import { compile, sql } from '../../sql/index.js';
8
+ import { calendarDateIn } from '../env/time.js';
8
9
  import { AccessError, MissingRecordError } from '../errors.js';
10
+ import { effectiveFieldGroups } from '../security/runtime.js';
9
11
  import { compileDomain } from './domain.js';
12
+ import { sourceOf } from './source.js';
10
13
  import { bindValue } from './values.js';
11
14
  const HINT = 'Ask an administrator for a group that grants it, or run the task inside env.asSuperuser({ reason }).';
12
15
  /** True when the environment may perform `perm` on the model (ACL, RFC 0014 §7.2). */
13
16
  export function canAccess(internals, model, perm) {
14
- if (internals.env.su || !internals.registry.security.enforce)
17
+ if (internals.env.su || internals.env.administrator || !internals.registry.security.enforce)
15
18
  return true;
16
- return allowed(model.access, internals.env.groups, perm);
19
+ if (allowed(model.access, internals.env.groups, perm))
20
+ return true;
21
+ if (internals.env.grants.has(`${model.name}:${perm}`))
22
+ return true; // a special permission of this user
23
+ for (const [role, perms] of internals.overlay?.access.get(model.name) ?? [])
24
+ if (perms.has(perm) && internals.env.groups.has(role))
25
+ return true; // a runtime grant (RFC 0014 §7.10)
26
+ if (internals.registry.security.mode !== 'warn')
27
+ return false;
28
+ internals.registry.security.denied(`[enforce: 'warn'] ${perm} access to ${model.name} would be denied for groups ${[...internals.env.groups].join(', ') || '(none)'}: add it to the model's access.`);
29
+ return true;
17
30
  }
18
31
  /** @throws {AccessError} unless {@link canAccess}. */
19
32
  export function assertAccess(internals, model, perm) {
@@ -24,12 +37,84 @@ export function assertAccess(internals, model, perm) {
24
37
  hint: HINT,
25
38
  });
26
39
  }
40
+ /**
41
+ * True when the environment has the feature permission `code` (RFC 0014 §7.9): one of its groups grants it, or it
42
+ * is an administrator / superuser. @throws {SecurityDefinitionError} for a code no module declares (a typo).
43
+ */
44
+ export function hasPermission(internals, code) {
45
+ const permission = internals.registry.security.permissions.get(code);
46
+ if (permission === undefined)
47
+ throw new SecurityDefinitionError(`The permission '${code}' is not declared by any installed module.`, 'Declare it with definePermission() in a module, or fix the code.');
48
+ const { env } = internals;
49
+ if (env.su || env.administrator || !internals.registry.security.enforce)
50
+ return true;
51
+ if (permission.groups.some((g) => env.groups.has(g)) || env.grants.has(code))
52
+ return true;
53
+ for (const role of internals.overlay?.permissions.get(code) ?? [])
54
+ if (env.groups.has(role))
55
+ return true;
56
+ if (internals.registry.security.mode !== 'warn')
57
+ return false;
58
+ internals.registry.security.denied(`[enforce: 'warn'] permission '${code}' would be denied for groups ${[...env.groups].join(', ') || '(none)'}.`);
59
+ return true;
60
+ }
61
+ /** @throws {AccessError} unless {@link hasPermission}. */
62
+ export function assertPermission(internals, code) {
63
+ if (hasPermission(internals, code))
64
+ return;
65
+ const groups = internals.registry.security.permissions.get(code)?.groups ?? [];
66
+ throw new AccessError('permission', code, {
67
+ problem: `the permission '${code}' is denied (granted to ${groups.join(', ') || 'no group'}).`,
68
+ hint: HINT,
69
+ });
70
+ }
71
+ /** `date` shifted by `days` (`'YYYY-MM-DD'`). */
72
+ function addDays(date, days) {
73
+ const [y, m, d] = date.split('-').map(Number);
74
+ return new Date(Date.UTC(y ?? 1970, (m ?? 1) - 1, (d ?? 1) + days)).toISOString().slice(0, 10);
75
+ }
76
+ /**
77
+ * Back-dated entries (RFC 0014 §7.9): `dates` (values of the model's `backdate.field`) before today minus the grace
78
+ * days need the model's back-date permission. @throws {AccessError}
79
+ */
80
+ export function assertBackdate(internals, model, dates) {
81
+ const spec = model.backdate;
82
+ if (spec === undefined)
83
+ return;
84
+ const { env } = internals;
85
+ const earliest = addDays(env.today(), -(spec.graceDays ?? 0));
86
+ const early = [...dates]
87
+ .map((v) => v instanceof Date ? calendarDateIn(v, env.tz) : typeof v === 'string' ? v.slice(0, 10) : null)
88
+ .filter((d) => d !== null && d < earliest)
89
+ .sort();
90
+ if (early.length === 0 || hasPermission(internals, spec.permission))
91
+ return;
92
+ throw new AccessError(model.name, 'backdate', {
93
+ field: spec.field,
94
+ problem: `${model.name} entries dated before ${earliest} (here ${early[0]}) need the permission '${spec.permission}'.`,
95
+ hint: 'Use a current date, or ask an administrator for the back-date permission (a role or a special grant).',
96
+ });
97
+ }
98
+ /** The groups of a field: its code groups plus the runtime field security (RFC 0014 §7.10). */
99
+ export function fieldGroupsOf(internals, model, key) {
100
+ const field = model.fields[key];
101
+ const code = field?.groups ?? { read: [], write: [] };
102
+ return effectiveFieldGroups(internals.overlay, model.name, key, code);
103
+ }
27
104
  /** True when the field may be read / written by the environment. */
28
105
  export function canField(internals, model, key, kind) {
29
106
  const field = model.fields[key];
30
- if (field === undefined || internals.env.su || !internals.registry.security.enforce)
107
+ if (field === undefined ||
108
+ internals.env.su ||
109
+ internals.env.administrator ||
110
+ !internals.registry.security.enforce)
111
+ return true;
112
+ if (fieldAllowed(fieldGroupsOf(internals, model, key), internals.env.groups, kind))
31
113
  return true;
32
- return fieldAllowed(field.groups, internals.env.groups, kind);
114
+ if (internals.registry.security.mode !== 'warn')
115
+ return false;
116
+ internals.registry.security.denied(`[enforce: 'warn'] ${kind} of ${model.name}.${key} would be denied for groups ${[...internals.env.groups].join(', ') || '(none)'}.`);
117
+ return true;
33
118
  }
34
119
  /** @throws {AccessError} naming the first field the environment may not read / write. */
35
120
  export function assertFields(internals, model, keys, kind) {
@@ -38,7 +123,7 @@ export function assertFields(internals, model, keys, kind) {
38
123
  continue;
39
124
  throw new AccessError(model.name, kind, {
40
125
  field: key,
41
- problem: `field '${key}' of ${model.name} is restricted to groups ${(kind === 'read' ? model.fields[key]?.groups.read : model.fields[key]?.groups.write)?.join(', ') ?? ''}.`,
126
+ problem: `field '${key}' of ${model.name} is restricted to groups ${fieldGroupsOf(internals, model, key)[kind].join(', ')}.`,
42
127
  hint: HINT,
43
128
  });
44
129
  }
@@ -103,9 +188,9 @@ export function domainKeys(domain, out = new Set()) {
103
188
  /** Record-rule conditions for `perm` (RFC 0014 §7.3): globals ANDed, applicable group rules ORed. Empty under `su`. */
104
189
  export function ruleConditions(internals, model, perm) {
105
190
  const { env } = internals;
106
- if (env.su || !internals.registry.security.enforce)
191
+ if (env.su || env.administrator || !internals.registry.security.enforce)
107
192
  return [];
108
- const { globals, groupRules, hasGroupRules } = applicableRules(model.rules, env.groups, perm);
193
+ const { globals, groupRules, hasGroupRules } = applicableRules({ ...model.rules, ...(internals.overlay?.rules.get(model.name) ?? {}) }, env.groups, perm);
109
194
  const placeholders = { uid: env.uid, companyId: env.companyId, companyIds: env.companyIds };
110
195
  const out = [];
111
196
  for (const rule of globals) {
@@ -142,7 +227,7 @@ export async function assertRecords(internals, model, ids, perm) {
142
227
  const conditions = ruleConditions(internals, model, perm);
143
228
  if (conditions.length === 0)
144
229
  return;
145
- const rows = await internals.query(compile(sql `SELECT ${sql.id('id')} FROM ${sql.id(model.table)} WHERE ${sql.id('id')} = ANY(${sql.array(real, 'bigint')}) AND ${sql.join(conditions, sql ` AND `)}`));
230
+ const rows = await internals.query(compile(sql `SELECT ${sql.id('id')} FROM ${sourceOf(internals, model)} WHERE ${sql.id('id')} = ANY(${sql.array(real, 'bigint')}) AND ${sql.join(conditions, sql ` AND `)}`));
146
231
  const passed = new Set(rows.map((r) => Number(r.id)));
147
232
  const denied = real.filter((id) => !passed.has(id));
148
233
  if (denied.length === 0)
@@ -151,7 +236,7 @@ export async function assertRecords(internals, model, ids, perm) {
151
236
  }
152
237
  /** Distinguishes missing records from records out of the rules' scope, and throws accordingly. */
153
238
  export async function explainDenied(internals, model, denied, perm) {
154
- const existing = await internals.query(compile(sql `SELECT ${sql.id('id')} FROM ${sql.id(model.table)} WHERE ${sql.id('id')} = ANY(${sql.array([...denied], 'bigint')})`));
239
+ const existing = await internals.query(compile(sql `SELECT ${sql.id('id')} FROM ${sourceOf(internals, model)} WHERE ${sql.id('id')} = ANY(${sql.array([...denied], 'bigint')})`));
155
240
  const found = new Set(existing.map((r) => Number(r.id)));
156
241
  const missing = denied.filter((id) => !found.has(id));
157
242
  if (missing.length > 0 && found.size === 0)
@@ -0,0 +1,9 @@
1
+ /** Where reads come from: the table, or the past in `env.asOf` scopes (RFC 0018 §7.4). */
2
+ import { type SqlFragment } from '../../sql/index.js';
3
+ import type { ScopeInternals } from '../env/env.js';
4
+ import type { AnyModel } from '../model/model.js';
5
+ /**
6
+ * The relation `model` is read from: its table, or in `env.asOf` scopes and for models with history, the rows valid
7
+ * at that instant (current rows unchanged since, plus archived versions), aliased as the table.
8
+ */
9
+ export declare function sourceOf(internals: ScopeInternals, model: AnyModel): SqlFragment;
@@ -0,0 +1,19 @@
1
+ /** Where reads come from: the table, or the past in `env.asOf` scopes (RFC 0018 §7.4). */
2
+ import { sql } from '../../sql/index.js';
3
+ /**
4
+ * The relation `model` is read from: its table, or in `env.asOf` scopes and for models with history, the rows valid
5
+ * at that instant (current rows unchanged since, plus archived versions), aliased as the table.
6
+ */
7
+ export function sourceOf(internals, model) {
8
+ const at = internals.asOf;
9
+ if (at === undefined || !model.history)
10
+ return sql.id(model.table);
11
+ const columns = sql.join([
12
+ ...new Set([
13
+ 'id',
14
+ ...Object.values(model.columns).filter((c) => c !== undefined),
15
+ ]),
16
+ ].map((c) => sql.id(c)));
17
+ return sql `(SELECT ${columns} FROM ${sql.id(model.table)} WHERE ${sql.id('updated_at')} <= ${at}
18
+ UNION ALL SELECT ${columns} FROM ${sql.id(`${model.table}_history`.slice(0, 63))} WHERE ${sql.id('valid_from')} <= ${at} AND ${sql.id('valid_to')} > ${at}) AS ${sql.id(model.table)}`;
19
+ }
@@ -5,7 +5,7 @@
5
5
  import { InvalidTransitionError, TransitionGuardError } from '../errors.js';
6
6
  import { trackChange } from './audit.js';
7
7
  import { failingIds } from './constraints.js';
8
- import { assertAccess, assertRecords } from './security.js';
8
+ import { assertAccess, assertPermission, assertRecords } from './security.js';
9
9
  /** Runs transition `name` of state field `key` on `ids` of `model`. */
10
10
  export async function runTransition(host, model, ids, key, name) {
11
11
  if (ids.length === 0)
@@ -17,6 +17,9 @@ export async function runTransition(host, model, ids, key, name) {
17
17
  const transition = field.transitions[name];
18
18
  if (transition === undefined)
19
19
  throw new InvalidTransitionError(model.name, name, [], []);
20
+ const requires = transition.requires;
21
+ if (requires !== undefined)
22
+ assertPermission(internals, requires);
20
23
  await host.load(model, ids, { fields: new Set(['id', key]), relations: new Map() });
21
24
  const stateOf = (id) => String(host.values(model.name, id)?.get(key));
22
25
  const invalid = ids.filter((id) => !transition.from.includes(stateOf(id)));
@@ -10,8 +10,9 @@ import type { Translations } from '../../i18n/index.js';
10
10
  import type { Env } from '../env/env.js';
11
11
  import type { CreateOf, FlagsOfField, ReadValue, WriteOf, WriteType } from '../model/faces.js';
12
12
  import type { Id, X2ManyCommands } from '../model/id.js';
13
+ import type { Currency } from '../money/currency.js';
13
14
  import type { Decimal } from '../money/decimal.js';
14
- import type { MoneyJson } from '../money/money.js';
15
+ import type { Money, MoneyJson } from '../money/money.js';
15
16
  /** Model names of a schema view. */
16
17
  export type ModelName<S> = keyof S & string;
17
18
  /** Fields of model `M`. */
@@ -139,8 +140,25 @@ export interface RecordSetApi<S, M extends ModelName<S>, L> {
139
140
  filter(fn: (record: Rec<S, M, L>, index: number) => boolean): RecordSet<S, M, L>;
140
141
  /** The values of a loaded scalar field, in order. */
141
142
  mapped<K extends ScalarKeys<S, M> & SOf<L>>(key: K): ReadValue<FieldsOf<S, M>[K]>[];
143
+ /**
144
+ * Total of a loaded numeric field, `NULL`s skipped: `Money` for monetary fields (one currency, else
145
+ * `CurrencyMismatchError`; an empty set needs `currency`: a `Currency`, a record's `currency` or an id), `Decimal` for decimals, `number` for integers and floats.
146
+ *
147
+ * ```ts
148
+ * order.untaxed = order.lines.sum('subtotal', order.currency);
149
+ * ```
150
+ */
151
+ sum<K extends SummableKeys<S, M> & SOf<L>>(key: K, currency?: Currency | IdOnly<'res.currency'> | number): SumOf<FieldsOf<S, M>[K]>;
142
152
  /** Updates the records in the cache now; the database is updated at the next flush point (search, raw SQL, savepoint end, commit). */
143
- write(values: WriteValues<S, M>): Promise<void>;
153
+ write(values: WriteValues<S, M>, options?: {
154
+ /**
155
+ * Compare-and-set (RFC 0018 §7.1): the stored values these records must still have, typically the
156
+ * `updatedAt` read with them. Checked under a row lock. @throws {StaleRecordError} when someone saved first.
157
+ */
158
+ readonly expect?: {
159
+ readonly [K in Keys<S, M>]?: unknown;
160
+ };
161
+ }): Promise<void>;
144
162
  /** Deletes the records now (`ON DELETE` rules apply). */
145
163
  unlink(): Promise<void>;
146
164
  /** Plain JSON rows (ids for relations, `Money` / `Quantity` as objects, dates as ISO strings). */
@@ -150,6 +168,8 @@ export interface RecordSetApi<S, M extends ModelName<S>, L> {
150
168
  readonly field?: Keys<S, M>;
151
169
  readonly limit?: number;
152
170
  readonly action?: AuditAction;
171
+ /** Rows older than this row id: the next page after the last `id` of the previous one. */
172
+ readonly before?: number;
153
173
  }): Promise<readonly AuditEntry[]>;
154
174
  /** Numbers these records from their manual sequence (RFC 0012 §7.4); records with a number are refused. */
155
175
  assignNumber<K extends SequenceKeys<S, M>>(key: K, options?: {
@@ -161,6 +181,79 @@ export interface RecordSetApi<S, M extends ModelName<S>, L> {
161
181
  transitions(): readonly string[];
162
182
  toJSON(): readonly Id<M>[];
163
183
  }
184
+ /** Date buckets of {@link ModelRef.aggregate}: `'dateOrder:month'`. */
185
+ export type Granularity = 'day' | 'week' | 'month' | 'quarter' | 'year';
186
+ type KindKeys<S, M extends ModelName<S>, Kinds> = {
187
+ [K in keyof FieldsOf<S, M> & string]: FieldsOf<S, M>[K] extends {
188
+ readonly kind: Kinds;
189
+ } ? K : never;
190
+ }[keyof FieldsOf<S, M> & string];
191
+ /** What `aggregate()` can group by: plain fields, and dates with a granularity. */
192
+ export type GroupKey<S, M extends ModelName<S>> = Exclude<KindKeys<S, M, 'char' | 'selection' | 'state' | 'boolean' | 'integer' | 'date' | 'many2one'>, TranslatedKeys<S, M>> | `${KindKeys<S, M, 'date' | 'datetime'>}:${Granularity}`;
193
+ /** One measure of `aggregate()`: a row count, or a function of a numeric field. */
194
+ export type Measure<S, M extends ModelName<S>> = 'count' | {
195
+ readonly sum: SummableKeys<S, M>;
196
+ } | {
197
+ readonly avg: SummableKeys<S, M>;
198
+ } | {
199
+ readonly min: SummableKeys<S, M>;
200
+ } | {
201
+ readonly max: SummableKeys<S, M>;
202
+ };
203
+ /** The query of {@link ModelRef.aggregate}. */
204
+ export interface AggregateQuery<S, M extends ModelName<S>, G extends string, Ms> {
205
+ readonly where?: Domain<S, M>;
206
+ readonly groupBy?: readonly G[];
207
+ readonly measures: Ms;
208
+ /** Group or measure names, optionally followed by `asc` / `desc`. Defaults to the groups, ascending. */
209
+ readonly order?: readonly (G | (keyof Ms & string) | `${G | (keyof Ms & string)} ${'asc' | 'desc'}`)[];
210
+ readonly limit?: number;
211
+ /**
212
+ * Several groupings in one statement (`GROUP BY GROUPING SETS`, RFC 0016 amendment for Kosh pivots): each set is a
213
+ * subset of `groupBy`; `[]` is the grand total. Rows carry `$groups`, the names they are grouped by.
214
+ */
215
+ readonly groupingSets?: readonly (readonly G[])[];
216
+ /** Shorthand: every prefix of `groupBy`, down to the grand total (`ROLLUP`). */
217
+ readonly rollup?: boolean;
218
+ /** Shorthand: every subset of `groupBy` (`CUBE`, at most 6 groups). */
219
+ readonly cube?: boolean;
220
+ }
221
+ type GroupValue<S, M extends ModelName<S>, K> = K extends `${string}:${string}` ? string : K extends keyof FieldsOf<S, M> ? FieldsOf<S, M>[K] extends {
222
+ readonly kind: 'many2one';
223
+ } ? Id<Target<S, M, K>> | null : ReadValue<FieldsOf<S, M>[K]> | null : never;
224
+ type FieldOf<S, M extends ModelName<S>, K> = K extends keyof FieldsOf<S, M> ? FieldsOf<S, M>[K] : never;
225
+ type MeasureValue<S, M extends ModelName<S>, X> = X extends 'count' ? number : X extends {
226
+ readonly sum: infer K;
227
+ } ? SumOf<FieldOf<S, M, K>> : X extends {
228
+ readonly avg: infer K;
229
+ } ? (FieldOf<S, M, K> extends {
230
+ readonly kind: 'monetary';
231
+ } ? Money : Decimal) | null : X extends {
232
+ readonly min: infer K;
233
+ } | {
234
+ readonly max: infer K;
235
+ } ? SumOf<FieldOf<S, M, K>> | null : never;
236
+ /** A row of {@link ModelRef.aggregate}: the group values and the measures. */
237
+ export type AggregateRow<S, M extends ModelName<S>, G extends string, Ms> = {
238
+ readonly [K in G]: GroupValue<S, M, K>;
239
+ } & {
240
+ readonly [K in keyof Ms]: MeasureValue<S, M, Ms[K]>;
241
+ } & {
242
+ /** With grouping sets: the groups this row is grouped by (others are totals over them, not `null` values). */
243
+ readonly $groups?: readonly G[];
244
+ };
245
+ /** Fields {@link RecordSetApi.sum} accepts: integer, float, decimal and monetary. */
246
+ export type SummableKeys<S, M extends ModelName<S>> = {
247
+ [K in keyof FieldsOf<S, M> & string]: FieldsOf<S, M>[K] extends {
248
+ readonly kind: 'integer' | 'float' | 'decimal' | 'monetary';
249
+ } ? K : never;
250
+ }[keyof FieldsOf<S, M> & string];
251
+ /** What {@link RecordSetApi.sum} returns for field `F`. */
252
+ export type SumOf<F> = F extends {
253
+ readonly kind: 'monetary';
254
+ } ? Money : F extends {
255
+ readonly kind: 'decimal';
256
+ } ? Decimal : number;
164
257
  /** The model's methods (declared ones and generated transitions), callable on recordsets. */
165
258
  export type MethodsOf<S, M extends ModelName<S>> = S[M] extends {
166
259
  readonly methods: infer Ms;
@@ -180,6 +273,10 @@ type DomainOperators<V> = {
180
273
  readonly isNull?: boolean;
181
274
  readonly like?: string;
182
275
  readonly ilike?: string;
276
+ /** Hierarchies: the records in the subtrees of these ids (`id`, or a many2one to a model with `hierarchy`). */
277
+ readonly childOf?: V | readonly V[];
278
+ /** Hierarchies: the ancestors of these ids, themselves included. */
279
+ readonly parentOf?: V | readonly V[];
183
280
  };
184
281
  type DomainValue<F> = WriteType<F> extends never ? unknown : WriteType<F> | DomainOperators<WriteType<F>>;
185
282
  /** A search filter: field → value (equality) or operators. Keys are ANDed. Relation paths come with the domain compiler. */
@@ -218,8 +315,11 @@ export interface ModelRef<S, M extends ModelName<S>> {
218
315
  /** Inserts records (one statement per model) and returns them with their defaults loaded (RFC 0004 §7.6). */
219
316
  create(values: readonly CreateValues<S, M>[]): Promise<RecordSet<S, M, DefaultLoaded<S, M>>>;
220
317
  search(query?: SearchQuery<S, M>): Promise<RecordSet<S, M, DefaultLoaded<S, M>>>;
221
- /** A lazy recordset of these ids. Nothing is fetched until `load()`. */
222
- browse(ids: readonly number[]): PendingSet<S, M>;
318
+ /**
319
+ * The records with these ids, nothing loaded yet: `write`, `unlink` and methods work directly; `load()` fetches
320
+ * values (rules apply, missing ids are a `MissingRecordError`).
321
+ */
322
+ browse(ids: readonly number[]): RecordSet<S, M, ListLoaded<never>>;
223
323
  /** Form assist on an in-memory draft: derived values and warnings, nothing written (RFC 0009 §7.4). */
224
324
  onchange(input: OnchangeInput<S, M>): Promise<OnchangeResult<S, M>>;
225
325
  /**
@@ -228,6 +328,21 @@ export interface ModelRef<S, M extends ModelName<S>> {
228
328
  * permission. x2many commands are not accepted.
229
329
  */
230
330
  copy(values: readonly CreateValues<S, M>[]): Promise<RecordSet<S, M, DefaultLoaded<S, M>>>;
331
+ /**
332
+ * Grouped totals for reports (Odoo's `read_group`), in one `GROUP BY` statement with the read ACL, field groups,
333
+ * record rules and company scope of `search`. Monetary measures are also split by currency.
334
+ *
335
+ * ```ts
336
+ * const rows = await env.model('sale.order').aggregate({
337
+ * where: { state: 'sale' },
338
+ * groupBy: ['partner', 'dateOrder:month'],
339
+ * measures: { orders: 'count', total: { sum: 'amountTotal' } },
340
+ * order: ['total desc'],
341
+ * });
342
+ * rows[0].total; // Money
343
+ * ```
344
+ */
345
+ aggregate<const G extends GroupKey<S, M> = never, const Ms extends Readonly<Record<string, Measure<S, M>>> = Readonly<Record<string, Measure<S, M>>>>(query: AggregateQuery<S, M, G, Ms>): Promise<AggregateRow<S, M, G, Ms>[]>;
231
346
  }
232
347
  /** Keys of sequence-numbered fields. */
233
348
  export type SequenceKeys<S, M extends ModelName<S>> = {
@@ -241,15 +356,19 @@ export type TranslatedKeys<S, M extends ModelName<S>> = {
241
356
  export type ComputedKeys<S, M extends ModelName<S>> = {
242
357
  [K in Keys<S, M>]: FlagsOfField<FieldsOf<S, M>[K]>['computed'] extends true ? K : never;
243
358
  }[Keys<S, M>];
244
- /** A record inside a compute: computed keys are assignable (RFC 0008 §7.7). */
245
- export type ComputeRec<S, M extends ModelName<S>, L> = Omit<Rec<S, M, L>, ComputedKeys<S, M>> & {
246
- -readonly [K in ComputedKeys<S, M>]: FieldValue<S, M, K, FieldsOf<S, M>[K], L> | WriteType<FieldsOf<S, M>[K]>;
359
+ /**
360
+ * A record inside a compute: the `A` computed keys are assignable (RFC 0008 §7.7), other computed keys read with their
361
+ * read type. Built without `Omit` over the recordset (whose keys include the model's methods), so typing a compute
362
+ * against a generated view never needs the methods' types (feedback #1: no TS7022 cycle through the module).
363
+ */
364
+ export type ComputeRec<S, M extends ModelName<S>, L, A extends ComputedKeys<S, M> = ComputedKeys<S, M>, Ms = MethodsOf<S, M>> = RecordSetApi<S, M, L> & Ms & Omit<Access<S, M, L>, A> & {
365
+ -readonly [K in A]: FieldValue<S, M, K, FieldsOf<S, M>[K], L> | WriteType<FieldsOf<S, M>[K]>;
247
366
  };
248
- /** A recordset inside a compute: iteration yields {@link ComputeRec}. */
249
- export type ComputeSet<S, M extends ModelName<S>, L> = Omit<RecordSet<S, M, L>, typeof Symbol.iterator | 'first' | 'ensureOne'> & {
250
- [Symbol.iterator](): Iterator<ComputeRec<S, M, L>>;
251
- first(): ComputeRec<S, M, L>;
252
- ensureOne(): ComputeRec<S, M, L>;
367
+ /** A recordset inside a compute: iteration yields {@link ComputeRec} (these members come first, so they win). */
368
+ export type ComputeSet<S, M extends ModelName<S>, L, A extends ComputedKeys<S, M> = ComputedKeys<S, M>, Ms = MethodsOf<S, M>> = Omit<RecordSetApi<S, M, L>, typeof Symbol.iterator | 'first' | 'ensureOne'> & Ms & {
369
+ [Symbol.iterator](): Iterator<ComputeRec<S, M, L, A, Ms>>;
370
+ first(): ComputeRec<S, M, L, A, Ms>;
371
+ ensureOne(): ComputeRec<S, M, L, A, Ms>;
253
372
  };
254
373
  /** Many2one keys. */
255
374
  export type Many2oneKeys<S, M extends ModelName<S>> = {
@@ -7,7 +7,13 @@ import { type SqlFragment } from '../../sql/index.js';
7
7
  export interface TranslationContext {
8
8
  readonly lang: string;
9
9
  readonly source: string;
10
+ /** The current company: company-dependent values are read and written for it. */
11
+ readonly company?: number;
10
12
  }
13
+ /** A company-dependent value as stored: `{ "<companyId>": value }`. */
14
+ export type CompanyValues = Readonly<Record<string, unknown>>;
15
+ /** The value of a company-dependent field for `company` (the default when the company has none). */
16
+ export declare function companyValue(field: Field, stored: unknown, company: number): unknown;
11
17
  import type { Field } from '../model/field.js';
12
18
  import type { AnyModel } from '../model/model.js';
13
19
  /** Throws a {@link ValidationError} for `model`. */
@@ -5,6 +5,22 @@
5
5
  import { isTranslations, mergeTranslation } from '../../i18n/index.js';
6
6
  import { sql } from '../../sql/index.js';
7
7
  import { Decimal as DecimalJs } from 'decimal.js';
8
+ /** The value of a company-dependent field for `company` (the default when the company has none). */
9
+ export function companyValue(field, stored, company) {
10
+ const map = (stored ?? {});
11
+ const raw = Object.hasOwn(map, String(company))
12
+ ? map[String(company)]
13
+ : typeof field.default === 'function'
14
+ ? null
15
+ : (field.default ?? null);
16
+ if (raw === null || raw === undefined)
17
+ return null;
18
+ if (field.kind === 'decimal')
19
+ return new DecimalJs(String(raw));
20
+ if (field.kind === 'many2one' || field.kind === 'integer' || field.kind === 'float')
21
+ return Number(raw);
22
+ return raw;
23
+ }
8
24
  import { CurrencyMismatchError, UomMismatchError, ValidationError } from '../errors.js';
9
25
  import { toDecimal } from '../money/decimal.js';
10
26
  import { Money } from '../money/money.js';
@@ -16,16 +32,16 @@ export function fail(model, fields, problem, hint) {
16
32
  }
17
33
  /** The PostgreSQL array element type for a field (for `unnest($n::type[])`). */
18
34
  export function arrayType(field) {
19
- if (field.kind === 'many2one')
20
- return 'bigint';
21
35
  // JSON travels as text and is cast in SQL (columnCast): array parameters of jsonb would be re-encoded by the driver.
22
36
  if (columnCast(field) !== undefined)
23
37
  return 'text';
38
+ if (field.kind === 'many2one')
39
+ return 'bigint';
24
40
  return field.pgType;
25
41
  }
26
42
  /** The SQL cast applied to a bound value before it reaches the column (`jsonb` for json and translatable fields). */
27
43
  export function columnCast(field) {
28
- return field.kind === 'json' || field.translate ? 'jsonb' : undefined;
44
+ return field.kind === 'json' || field.translate || field.companyDependent ? 'jsonb' : undefined;
29
45
  }
30
46
  /** A reference to the bound value of `column` in the `v` row alias, cast when needed. */
31
47
  export function valueRef(field, column) {
@@ -41,7 +57,7 @@ export function bindValue(field, value) {
41
57
  // Inside arrays, postgres.js would type a Date as a scalar timestamptz; an ISO string lets the ::timestamptz[] cast apply.
42
58
  if (value instanceof Date)
43
59
  return value.toISOString();
44
- if (field.kind === 'json' || field.translate)
60
+ if (field.kind === 'json' || field.translate || field.companyDependent)
45
61
  return JSON.stringify(value);
46
62
  return value;
47
63
  }
@@ -50,6 +66,20 @@ export function bindValue(field, value) {
50
66
  * id for `Money` / `Quantity` checks.
51
67
  */
52
68
  export function normalize(model, key, field, value, siblings, translation) {
69
+ if (field.companyDependent) {
70
+ const company = translation?.company;
71
+ if (company === undefined)
72
+ fail(model, [key], 'is company-dependent but no company is known.', 'Write it inside shutro.run({ company }).');
73
+ const plain = value === null
74
+ ? null
75
+ : normalize(model, key, { ...field, companyDependent: false }, value, siblings, translation);
76
+ const existing = siblings(key);
77
+ const map = typeof existing === 'object' && existing !== null ? existing : {};
78
+ return Object.freeze({
79
+ ...map,
80
+ [String(company)]: DecimalJs.isDecimal(plain) ? plain.toFixed() : plain,
81
+ });
82
+ }
53
83
  const bad = (what, hint) => fail(model, [key], `field '${key}' ${what}.`, hint);
54
84
  if (value === null) {
55
85
  if (field.required)
@@ -5,6 +5,11 @@
5
5
  */
6
6
  import type { ScopeInternals } from '../env/env.js';
7
7
  import type { AnyModel } from '../model/model.js';
8
+ /**
9
+ * Compare-and-set (RFC 0018 §7.1): locks the records and checks their stored values against `expect` before a write.
10
+ * @throws {StaleRecordError} for records whose values differ (someone else saved first).
11
+ */
12
+ export declare function assertExpected(internals: ScopeInternals, model: AnyModel, ids: readonly number[], expect: Readonly<Record<string, unknown>>): Promise<void>;
8
13
  /** What the write runtime needs from the recordset runtime (passed in to avoid a module cycle). */
9
14
  export interface WriteHost {
10
15
  readonly internals: ScopeInternals;
@@ -23,7 +28,7 @@ export interface WriteHost {
23
28
  }
24
29
  type Row = Readonly<Record<string, unknown>>;
25
30
  /** Inserts `rows` and returns their ids in input order. Children and links are created too. */
26
- export declare function createRecords(host: WriteHost, model: AnyModel, rows: readonly Row[], options?: {
31
+ export declare function createRecords(host: WriteHost, model: AnyModel, input: readonly Row[], options?: {
27
32
  readonly copy?: boolean;
28
33
  }): Promise<number[]>;
29
34
  /** One value in COPY text format: \N for null, backslash escapes, bytea as hex (RFC 0015 §7.1). */