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.
- package/README.md +12 -2
- package/dist/audit/index.d.ts +3 -1
- package/dist/audit/index.js +2 -0
- package/dist/cli/cli.js +17 -2
- package/dist/cli/config.js +2 -0
- package/dist/cli/generate/generate.js +2 -0
- package/dist/cli/generate/render.js +57 -8
- package/dist/cli/init.js +4 -4
- package/dist/cli/resolve.d.ts +2 -0
- package/dist/cli/resolve.js +28 -0
- package/dist/core/data/data.d.ts +59 -0
- package/dist/core/data/data.js +119 -0
- package/dist/core/data/load.d.ts +37 -0
- package/dist/core/data/load.js +236 -0
- package/dist/core/env/env.d.ts +175 -2
- package/dist/core/env/env.js +304 -19
- package/dist/core/env/identity.d.ts +10 -0
- package/dist/core/env/identity.js +16 -0
- package/dist/core/errors.d.ts +15 -1
- package/dist/core/errors.js +21 -0
- package/dist/core/events/events.d.ts +44 -0
- package/dist/core/events/events.js +58 -0
- package/dist/core/events/workers.d.ts +56 -0
- package/dist/core/events/workers.js +155 -0
- package/dist/core/index.d.ts +17 -9
- package/dist/core/index.js +11 -3
- package/dist/core/model/field.d.ts +33 -0
- package/dist/core/model/field.js +64 -1
- package/dist/core/model/generated.d.ts +4 -2
- package/dist/core/model/model.d.ts +40 -0
- package/dist/core/model/model.js +28 -0
- package/dist/core/model/related.d.ts +17 -0
- package/dist/core/model/related.js +60 -0
- package/dist/core/model/typed.d.ts +107 -0
- package/dist/core/model/typed.js +46 -0
- package/dist/core/money/fx.d.ts +10 -2
- package/dist/core/money/fx.js +17 -2
- package/dist/core/recordset/aggregate.d.ts +22 -0
- package/dist/core/recordset/aggregate.js +258 -0
- package/dist/core/recordset/audit.d.ts +9 -1
- package/dist/core/recordset/audit.js +59 -2
- package/dist/core/recordset/compute.d.ts +2 -0
- package/dist/core/recordset/compute.js +11 -2
- package/dist/core/recordset/domain.d.ts +4 -0
- package/dist/core/recordset/domain.js +74 -2
- package/dist/core/recordset/onchange.js +70 -37
- package/dist/core/recordset/recordset.d.ts +10 -1
- package/dist/core/recordset/recordset.js +80 -14
- package/dist/core/recordset/security.d.ts +15 -1
- package/dist/core/recordset/security.js +95 -10
- package/dist/core/recordset/source.d.ts +9 -0
- package/dist/core/recordset/source.js +19 -0
- package/dist/core/recordset/transitions.js +4 -1
- package/dist/core/recordset/types.d.ts +131 -12
- package/dist/core/recordset/values.d.ts +6 -0
- package/dist/core/recordset/values.js +34 -4
- package/dist/core/recordset/writes.d.ts +6 -1
- package/dist/core/recordset/writes.js +217 -12
- package/dist/core/registry/ddl.d.ts +9 -0
- package/dist/core/registry/ddl.js +49 -2
- package/dist/core/registry/module.d.ts +10 -1
- package/dist/core/registry/module.js +2 -0
- package/dist/core/registry/registry.d.ts +29 -4
- package/dist/core/registry/registry.js +100 -5
- package/dist/core/security/runtime.d.ts +102 -0
- package/dist/core/security/runtime.js +232 -0
- package/dist/driver-pg/driver.d.ts +2 -0
- package/dist/driver-pg/driver.js +1 -0
- package/dist/migrate/apply.d.ts +5 -1
- package/dist/migrate/apply.js +20 -2
- package/dist/migrate/schema.js +40 -2
- package/dist/security/index.d.ts +24 -0
- package/dist/security/index.js +16 -0
- package/dist/sql/tag.d.ts +5 -0
- package/dist/sql/tag.js +29 -1
- package/package.json +1 -1
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
import { AUDIT_TABLE, auditTableStatements, insertAuditStatement, readTrail, } from '../../audit/index.js';
|
|
6
6
|
import { Decimal as DecimalJs } from 'decimal.js';
|
|
7
7
|
import { Money } from '../money/money.js';
|
|
8
|
+
import { canField } from './security.js';
|
|
8
9
|
const ensured = new WeakSet();
|
|
9
10
|
async function ensureTable(driver) {
|
|
10
11
|
if (ensured.has(driver))
|
|
@@ -135,6 +136,38 @@ export function trackSuperuser(internals, reason) {
|
|
|
135
136
|
new: null,
|
|
136
137
|
});
|
|
137
138
|
}
|
|
139
|
+
/** Records a scoped elevation (`env.withGrants`, elevated methods): which grants, and why (RFC 0014 §7.9). */
|
|
140
|
+
export function trackElevation(internals, grants, reason) {
|
|
141
|
+
if (!internals.env.flags.tracking)
|
|
142
|
+
return;
|
|
143
|
+
internals.auditRows.push({
|
|
144
|
+
...base(internals),
|
|
145
|
+
su: false,
|
|
146
|
+
reason,
|
|
147
|
+
action: 'elevate',
|
|
148
|
+
model: null,
|
|
149
|
+
recordId: null,
|
|
150
|
+
field: null,
|
|
151
|
+
old: null,
|
|
152
|
+
new: [...grants],
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
/** Records a runtime security change (RFC 0014 §7.10). */
|
|
156
|
+
export function trackSecurityChange(internals, change) {
|
|
157
|
+
if (!internals.env.flags.tracking)
|
|
158
|
+
return;
|
|
159
|
+
internals.auditRows.push({
|
|
160
|
+
...base(internals),
|
|
161
|
+
su: internals.env.su,
|
|
162
|
+
reason: null,
|
|
163
|
+
action: 'security',
|
|
164
|
+
model: null,
|
|
165
|
+
recordId: null,
|
|
166
|
+
field: null,
|
|
167
|
+
old: null,
|
|
168
|
+
new: change,
|
|
169
|
+
});
|
|
170
|
+
}
|
|
138
171
|
function same(a, b) {
|
|
139
172
|
return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
|
|
140
173
|
}
|
|
@@ -198,8 +231,32 @@ export async function flushAudit(internals, model) {
|
|
|
198
231
|
await ensureTable(internals.driver);
|
|
199
232
|
await internals.query(insertAuditStatement(coalesced));
|
|
200
233
|
}
|
|
201
|
-
/**
|
|
234
|
+
/**
|
|
235
|
+
* `records.trail()`: the rows of these records, newest first, after a flush. Field security applies: rows of fields
|
|
236
|
+
* the scope may not read are left out, and such fields are removed from create / delete snapshots. `limit` counts
|
|
237
|
+
* the rows returned (more are read when some are left out), so a page shorter than `limit` is the last one.
|
|
238
|
+
*/
|
|
202
239
|
export async function trailOf(internals, model, ids, filter) {
|
|
203
240
|
await internals.flush();
|
|
204
|
-
|
|
241
|
+
const limit = filter.limit ?? 100;
|
|
242
|
+
const readable = (key) => canField(internals, model, key, 'read');
|
|
243
|
+
const strip = (snapshot) => snapshot !== null && typeof snapshot === 'object' && !Array.isArray(snapshot)
|
|
244
|
+
? Object.fromEntries(Object.entries(snapshot).filter(([key]) => readable(key)))
|
|
245
|
+
: snapshot;
|
|
246
|
+
const out = [];
|
|
247
|
+
let before = filter.before;
|
|
248
|
+
for (;;) {
|
|
249
|
+
const rows = await readTrail({ query: (q) => internals.query(q) }, { ...filter, model: model.name, recordIds: ids, limit, before });
|
|
250
|
+
for (const row of rows) {
|
|
251
|
+
if (row.field === null)
|
|
252
|
+
out.push({ ...row, old: strip(row.old), new: strip(row.new) });
|
|
253
|
+
else if (readable(row.field))
|
|
254
|
+
out.push(row);
|
|
255
|
+
if (out.length === limit)
|
|
256
|
+
return out;
|
|
257
|
+
}
|
|
258
|
+
if (rows.length < limit)
|
|
259
|
+
return out;
|
|
260
|
+
before = rows[rows.length - 1]?.id;
|
|
261
|
+
}
|
|
205
262
|
}
|
|
@@ -15,6 +15,8 @@ export interface ComputeSpec {
|
|
|
15
15
|
export interface ComputeHost {
|
|
16
16
|
readonly internals: ScopeInternals;
|
|
17
17
|
load(model: AnyModel, ids: readonly number[], spec: ComputeSpec): Promise<void>;
|
|
18
|
+
/** Loads the `Currency` / `Uom` objects the monetary / quantity `fields` of the records refer to. */
|
|
19
|
+
valueObjects(model: AnyModel, ids: readonly number[], fields: ReadonlySet<string>): Promise<void>;
|
|
18
20
|
values(model: string, id: number, create?: boolean): Map<string, unknown> | undefined;
|
|
19
21
|
/** A recordset of `ids` (one prefetch group) to pass to compute functions. */
|
|
20
22
|
recordset(model: AnyModel, ids: readonly number[]): unknown;
|
|
@@ -269,7 +269,15 @@ export async function computeFields(host, model, ids, fields) {
|
|
|
269
269
|
const { internals } = host;
|
|
270
270
|
for (const group of groupByCompute(fields)) {
|
|
271
271
|
const all = sharing(internals, group[0]);
|
|
272
|
-
|
|
272
|
+
// The assigned fields' currency / unit siblings and their objects too: a compute can then total into the
|
|
273
|
+
// record's currency (`lines.sum('subtotal', o.currency)`) even when there is nothing to sum.
|
|
274
|
+
const spec = dependsSpec(internals, model, all);
|
|
275
|
+
const siblings = all.flatMap((f) => {
|
|
276
|
+
const field = model.fields[f.key];
|
|
277
|
+
return [field?.currencyField, field?.uomField].filter((k) => k !== undefined);
|
|
278
|
+
});
|
|
279
|
+
await host.load(model, ids, { ...spec, fields: new Set([...spec.fields, ...siblings]) });
|
|
280
|
+
await host.valueObjects(model, ids, new Set(all.map((f) => f.key)));
|
|
273
281
|
const names = all.map(name);
|
|
274
282
|
for (const n of names) {
|
|
275
283
|
internals.compute.computing.add(n);
|
|
@@ -289,7 +297,8 @@ export async function computeFields(host, model, ids, fields) {
|
|
|
289
297
|
else {
|
|
290
298
|
const records = host.recordset(model, ids);
|
|
291
299
|
const fn = typeof compute === 'string' ? model.methods[compute] : compute;
|
|
292
|
-
|
|
300
|
+
// The keys this compute fills come second, for generic computes such as related fields.
|
|
301
|
+
await fn.call(records, records, all.map((f) => f.key));
|
|
293
302
|
}
|
|
294
303
|
}
|
|
295
304
|
finally {
|
|
@@ -18,6 +18,10 @@ export type TargetScope = (target: AnyModel) => SqlFragment[];
|
|
|
18
18
|
export interface TranslationScope {
|
|
19
19
|
readonly lang: string;
|
|
20
20
|
readonly source: string;
|
|
21
|
+
/** The current company, for company-dependent fields. */
|
|
22
|
+
readonly company?: number;
|
|
23
|
+
/** The relation a model is read from (the past in `env.asOf` scopes); the table by default. */
|
|
24
|
+
readonly from?: (model: AnyModel) => SqlFragment;
|
|
21
25
|
}
|
|
22
26
|
/** Compiles the user's domain into conditions (ANDed). */
|
|
23
27
|
export declare function compileDomain(model: AnyModel, where: Readonly<Record<string, unknown>> | undefined, translation?: TranslationScope, resolve?: ModelResolver, scope?: TargetScope): SqlFragment[];
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import { sql } from '../../sql/index.js';
|
|
8
8
|
import { Decimal as DecimalJs } from 'decimal.js';
|
|
9
9
|
import { InvalidDomainError } from '../errors.js';
|
|
10
|
+
import { relatedPath } from '../model/related.js';
|
|
10
11
|
import { junctionTable } from './relations.js';
|
|
11
12
|
const OPERATORS = new Set([
|
|
12
13
|
'eq',
|
|
@@ -20,6 +21,8 @@ const OPERATORS = new Set([
|
|
|
20
21
|
'isNull',
|
|
21
22
|
'like',
|
|
22
23
|
'ilike',
|
|
24
|
+
'childOf',
|
|
25
|
+
'parentOf',
|
|
23
26
|
]);
|
|
24
27
|
function bind(value) {
|
|
25
28
|
if (DecimalJs.isDecimal(value))
|
|
@@ -38,6 +41,19 @@ function column(model, key, translation) {
|
|
|
38
41
|
if (col === undefined) {
|
|
39
42
|
throw new InvalidDomainError(`'${key}' of ${model.name} is a ${field.kind} field and cannot be filtered on directly.`, 'Filter x2many relations with any / all / none (full domain compiler), and non-stored computes in memory.');
|
|
40
43
|
}
|
|
44
|
+
if (field.companyDependent) {
|
|
45
|
+
// The current company's value, else the default: what readers see (RFC 0005 §7.4).
|
|
46
|
+
if (translation?.company === undefined)
|
|
47
|
+
throw new InvalidDomainError(`'${key}' is company-dependent and needs the current company.`, 'Search inside shutro.run({ company }).');
|
|
48
|
+
const literal = typeof field.default === 'function' ? null : (field.default ?? null);
|
|
49
|
+
const value = sql `(${sql.id(col)}->>${String(translation.company)})`;
|
|
50
|
+
return {
|
|
51
|
+
field,
|
|
52
|
+
column: literal === null
|
|
53
|
+
? sql.cast(value, field.valueType)
|
|
54
|
+
: sql `COALESCE(${sql.cast(value, field.valueType)}, ${sql.param(bind(literal), field.valueType)})`,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
41
57
|
if (field.translate && translation !== undefined) {
|
|
42
58
|
// COALESCE(col->>lang, col->>source): what readers see, so filters and sorts match reads (RFC 0005 §7.4).
|
|
43
59
|
return {
|
|
@@ -131,6 +147,25 @@ export function compileDomain(model, where, translation, resolve, scope) {
|
|
|
131
147
|
}
|
|
132
148
|
continue;
|
|
133
149
|
}
|
|
150
|
+
// A non-stored computed field with a search function filters through the domain it returns.
|
|
151
|
+
const searchFn = model.columns[key] === undefined ? model.fields[key]?.search : undefined;
|
|
152
|
+
if (searchFn !== undefined) {
|
|
153
|
+
const terms = isOperators(value) ? Object.entries(value) : [['eq', value]];
|
|
154
|
+
for (const [op, operand] of terms) {
|
|
155
|
+
if (operand === undefined)
|
|
156
|
+
continue;
|
|
157
|
+
const inner = compileDomain(model, searchFn(op, operand), translation, resolve, scope);
|
|
158
|
+
conditions.push(inner.length === 0 ? sql `TRUE` : sql `(${sql.join(inner, sql ` AND `)})`);
|
|
159
|
+
}
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
// A non-stored related field (delegation included) filters through its path.
|
|
163
|
+
const mirrored = model.columns[key] === undefined ? relatedPath(model.fields[key]?.compute) : undefined;
|
|
164
|
+
if (mirrored !== undefined) {
|
|
165
|
+
const dot = mirrored.indexOf('.');
|
|
166
|
+
conditions.push(relation(model, mirrored.slice(0, dot), { [mirrored.slice(dot + 1)]: value }, 'any', translation, resolve, scope));
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
134
169
|
const { column: col } = column(model, key, translation);
|
|
135
170
|
if (isOperators(value)) {
|
|
136
171
|
for (const [op, operand] of Object.entries(value)) {
|
|
@@ -139,6 +174,10 @@ export function compileDomain(model, where, translation, resolve, scope) {
|
|
|
139
174
|
if (!OPERATORS.has(op)) {
|
|
140
175
|
throw new InvalidDomainError(`'${op}' is not a domain operator (field '${key}').`, `Use one of: ${[...OPERATORS].join(', ')}.`);
|
|
141
176
|
}
|
|
177
|
+
if (op === 'childOf' || op === 'parentOf') {
|
|
178
|
+
conditions.push(hierarchyCondition(model, key, op, operand, resolve));
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
142
181
|
conditions.push(condition(col, op, operand, key));
|
|
143
182
|
}
|
|
144
183
|
}
|
|
@@ -148,6 +187,38 @@ export function compileDomain(model, where, translation, resolve, scope) {
|
|
|
148
187
|
}
|
|
149
188
|
return conditions;
|
|
150
189
|
}
|
|
190
|
+
/**
|
|
191
|
+
* `childOf` / `parentOf` on `id` of a hierarchical model, or on a many2one to one: records in the subtrees of the
|
|
192
|
+
* given ids (themselves included) / their ancestors (themselves included), as prefix matches on the path column.
|
|
193
|
+
*/
|
|
194
|
+
function hierarchyCondition(model, key, op, operand, resolve) {
|
|
195
|
+
const field = model.fields[key];
|
|
196
|
+
const tree = key === 'id'
|
|
197
|
+
? model
|
|
198
|
+
: field?.kind === 'many2one'
|
|
199
|
+
? resolve?.(field.target ?? '')
|
|
200
|
+
: undefined;
|
|
201
|
+
const spec = tree?.hierarchy;
|
|
202
|
+
if (tree === undefined || spec === undefined)
|
|
203
|
+
throw new InvalidDomainError(`'${op}' needs a hierarchy: '${key}' of ${model.name} is not the id of, or a many2one to, a model with hierarchy.`, "Declare hierarchy: { parent: 'parent', path: 'parentPath' } on the tree model.");
|
|
204
|
+
const ids = (Array.isArray(operand) ? operand : [operand]).map((v) => {
|
|
205
|
+
if (typeof v !== 'number' || !Number.isSafeInteger(v))
|
|
206
|
+
throw new InvalidDomainError(`'${op}' takes ids, got ${JSON.stringify(v)}.`, `E.g. { ${key}: { ${op}: [5, 9] } }.`);
|
|
207
|
+
return v;
|
|
208
|
+
});
|
|
209
|
+
const t = sql.id(tree.table);
|
|
210
|
+
const path = sql.id(tree.columns[spec.path] ?? '');
|
|
211
|
+
const h = sql.id('h');
|
|
212
|
+
const c = sql.id('c');
|
|
213
|
+
const given = sql `${h}.${sql.id('id')} = ANY(${sql.array(ids, 'bigint')})`;
|
|
214
|
+
const match = (node) => op === 'childOf'
|
|
215
|
+
? sql `${node}.${path} LIKE ANY (SELECT ${h}.${path} || '%' FROM ${t} AS ${h} WHERE ${given})`
|
|
216
|
+
: sql `EXISTS (SELECT 1 FROM ${t} AS ${h} WHERE ${given} AND ${h}.${path} LIKE ${node}.${path} || '%')`;
|
|
217
|
+
if (key === 'id')
|
|
218
|
+
return match(t);
|
|
219
|
+
const col = sql.id(model.columns[key] ?? '');
|
|
220
|
+
return sql `${col} IN (SELECT ${c}.${sql.id('id')} FROM ${t} AS ${c} WHERE ${match(c)})`;
|
|
221
|
+
}
|
|
151
222
|
/**
|
|
152
223
|
* A condition through relation `key`: records related to at least one (`any`) or no (`none`) record of the target
|
|
153
224
|
* matching `inner`.
|
|
@@ -167,7 +238,8 @@ function relation(model, key, inner, mode, translation, resolve, scope) {
|
|
|
167
238
|
...(scope?.(target) ?? []),
|
|
168
239
|
];
|
|
169
240
|
const where = conditions.length === 0 ? sql.empty : sql ` WHERE ${sql.join(conditions, sql ` AND `)}`;
|
|
170
|
-
const
|
|
241
|
+
const from = translation?.from?.(target) ?? sql.id(target.table);
|
|
242
|
+
const targets = sql `SELECT ${sql.id('id')} FROM ${from}${where}`;
|
|
171
243
|
let match;
|
|
172
244
|
if (field.kind === 'many2one') {
|
|
173
245
|
const col = sql.id(model.columns[key] ?? '');
|
|
@@ -178,7 +250,7 @@ function relation(model, key, inner, mode, translation, resolve, scope) {
|
|
|
178
250
|
if (field.kind === 'one2many') {
|
|
179
251
|
const inverse = sql.id(target.columns[field.inverseField ?? ''] ?? '');
|
|
180
252
|
const and = conditions.length === 0 ? sql.empty : sql ` AND ${sql.join(conditions, sql ` AND `)}`;
|
|
181
|
-
match = sql `SELECT ${inverse} FROM ${
|
|
253
|
+
match = sql `SELECT ${inverse} FROM ${from} WHERE ${inverse} IS NOT NULL${and}`;
|
|
182
254
|
}
|
|
183
255
|
else {
|
|
184
256
|
const j = junctionTable(model, field, target);
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* records are purged afterwards.
|
|
5
5
|
*/
|
|
6
6
|
import { computeFields } from './compute.js';
|
|
7
|
-
import { assertAccess } from './security.js';
|
|
7
|
+
import { assertAccess, canField } from './security.js';
|
|
8
8
|
import { fail, normalize } from './values.js';
|
|
9
9
|
function translationOf(host) {
|
|
10
10
|
return { lang: host.internals.env.lang, source: host.internals.sourceLang };
|
|
@@ -111,13 +111,69 @@ async function computeAll(host, model, ids) {
|
|
|
111
111
|
if (done.has(f.compute))
|
|
112
112
|
continue;
|
|
113
113
|
done.add(f.compute);
|
|
114
|
-
|
|
114
|
+
// A draft may not have a required relation yet (a new line without its order): skip the compute for those
|
|
115
|
+
// records, so inside a compute a required many2one in `depends` is always set (feedback #4). The field stays
|
|
116
|
+
// empty in the draft until the relation is given.
|
|
117
|
+
const ready = ids.filter((id) => {
|
|
118
|
+
const values = host.values(model.name, id);
|
|
119
|
+
return f.paths.every((path) => {
|
|
120
|
+
const first = path[0];
|
|
121
|
+
if (first === undefined || path.length < 2 || first.kind !== 'many2one')
|
|
122
|
+
return true;
|
|
123
|
+
if (model.fields[first.key]?.required !== true)
|
|
124
|
+
return true;
|
|
125
|
+
const value = values?.get(first.key);
|
|
126
|
+
return value !== null && value !== undefined;
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
await computeFields(host, model, ready, [f]);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/** Runs `model`'s onchange handlers on the virtual record `vid` for `changed`, cascading once per key. */
|
|
133
|
+
async function runHandlers(host, model, vid, id, changed, warnings) {
|
|
134
|
+
const { internals } = host;
|
|
135
|
+
const values = host.values(model.name, vid);
|
|
136
|
+
const queue = [...changed];
|
|
137
|
+
const done = new Set();
|
|
138
|
+
const draft = {
|
|
139
|
+
id,
|
|
140
|
+
env: internals.env,
|
|
141
|
+
get: (key) => values.get(key),
|
|
142
|
+
set(key, value) {
|
|
143
|
+
setDraftValue(model, values, key, value, translationOf(host));
|
|
144
|
+
if (!done.has(key) && !queue.includes(key))
|
|
145
|
+
queue.push(key);
|
|
146
|
+
},
|
|
147
|
+
async record(key) {
|
|
148
|
+
const field = model.fields[key];
|
|
149
|
+
const target = field?.target;
|
|
150
|
+
const related = values.get(key);
|
|
151
|
+
if (field?.kind !== 'many2one' || target === undefined || typeof related !== 'number')
|
|
152
|
+
return null;
|
|
153
|
+
const set = await host.recordset(internals.registry.get(target).model, [related]).load();
|
|
154
|
+
return set.first();
|
|
155
|
+
},
|
|
156
|
+
warn: (message) => {
|
|
157
|
+
warnings.push(message);
|
|
158
|
+
},
|
|
159
|
+
};
|
|
160
|
+
while (queue.length > 0) {
|
|
161
|
+
const key = queue.shift();
|
|
162
|
+
if (done.has(key))
|
|
163
|
+
continue;
|
|
164
|
+
done.add(key);
|
|
165
|
+
const fn = model.onchange[key];
|
|
166
|
+
if (fn !== undefined)
|
|
167
|
+
await fn(draft, internals.env);
|
|
115
168
|
}
|
|
116
169
|
}
|
|
117
170
|
/** `env.model(M).onchange(input)`. */
|
|
118
171
|
export async function runOnchange(host, model, input) {
|
|
119
172
|
const { internals } = host;
|
|
173
|
+
// Form assistance for a record being created (no id) or edited: the same access as saving it would need, so a
|
|
174
|
+
// reader cannot run a model's onchange logic (and see its results) on records they could never save.
|
|
120
175
|
assertAccess(internals, model, 'read');
|
|
176
|
+
assertAccess(internals, model, input.id === undefined || input.id === null ? 'create' : 'write');
|
|
121
177
|
const warnings = [];
|
|
122
178
|
const childIds = new Map();
|
|
123
179
|
const wasRecomputing = internals.compute.recomputing;
|
|
@@ -132,46 +188,23 @@ export async function runOnchange(host, model, input) {
|
|
|
132
188
|
created.push({ model: target, id });
|
|
133
189
|
}
|
|
134
190
|
const values = host.values(model.name, vid);
|
|
135
|
-
|
|
191
|
+
// Only fields the user may read come back (and are compared): restricted ones stay out of the draft's result.
|
|
192
|
+
const keys = scalarKeys(model).filter((k) => k !== 'id' && canField(internals, model, k, 'read'));
|
|
136
193
|
// Loads nothing (every column is in the cache) but brings the currency / unit objects the reads need.
|
|
137
194
|
await host.load(model, [vid], {
|
|
138
195
|
fields: new Set(keys.filter((k) => model.columns[k] !== undefined)),
|
|
139
196
|
relations: new Map(),
|
|
140
197
|
});
|
|
141
198
|
const [beforeRow] = host.read(model, [vid], keys.filter((k) => values.has(k)));
|
|
142
|
-
// Handlers, cascading once per key
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
const
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
if (!done.has(key) && !queue.includes(key))
|
|
152
|
-
queue.push(key);
|
|
153
|
-
},
|
|
154
|
-
async record(key) {
|
|
155
|
-
const field = model.fields[key];
|
|
156
|
-
const target = field?.target;
|
|
157
|
-
const id = values.get(key);
|
|
158
|
-
if (field?.kind !== 'many2one' || target === undefined || typeof id !== 'number')
|
|
159
|
-
return null;
|
|
160
|
-
const set = await host.recordset(internals.registry.get(target).model, [id]).load();
|
|
161
|
-
return set.first();
|
|
162
|
-
},
|
|
163
|
-
warn: (message) => {
|
|
164
|
-
warnings.push(message);
|
|
165
|
-
},
|
|
166
|
-
};
|
|
167
|
-
while (queue.length > 0) {
|
|
168
|
-
const key = queue.shift();
|
|
169
|
-
if (done.has(key))
|
|
170
|
-
continue;
|
|
171
|
-
done.add(key);
|
|
172
|
-
const fn = model.onchange[key];
|
|
173
|
-
if (fn !== undefined)
|
|
174
|
-
await fn(draft, internals.env);
|
|
199
|
+
// Handlers, cascading once per key: the draft's, then each new child row's for the fields it was given
|
|
200
|
+
// (feedback #10), so a line's product handler runs inside the order being edited and sees its values.
|
|
201
|
+
await runHandlers(host, model, vid, input.id ?? null, input.changed, warnings);
|
|
202
|
+
for (const [key, ids] of childIds) {
|
|
203
|
+
const field = model.fields[key];
|
|
204
|
+
const target = internals.registry.get(field.target ?? '').model;
|
|
205
|
+
const rows = (input.values[key]?.create ?? []);
|
|
206
|
+
for (const [i, cid] of ids.entries())
|
|
207
|
+
await runHandlers(host, target, cid, null, Object.keys(rows[i] ?? {}), warnings);
|
|
175
208
|
}
|
|
176
209
|
// Computes: children first, then the draft.
|
|
177
210
|
for (const [key, ids] of childIds) {
|
|
@@ -193,7 +226,7 @@ export async function runOnchange(host, model, input) {
|
|
|
193
226
|
const children = {};
|
|
194
227
|
for (const [key, ids] of childIds) {
|
|
195
228
|
const target = internals.registry.get(model.fields[key].target ?? '').model;
|
|
196
|
-
const childKeys = scalarKeys(target).filter((k) => k !== 'id');
|
|
229
|
+
const childKeys = scalarKeys(target).filter((k) => k !== 'id' && canField(internals, target, k, 'read'));
|
|
197
230
|
await host.load(target, ids, { fields: columnsOf(target, childKeys), relations: new Map() });
|
|
198
231
|
children[key] = host.read(target, ids, childKeys).map(({ id: _id, ...rest }) => rest);
|
|
199
232
|
}
|
|
@@ -9,6 +9,7 @@ import type { AnyModel } from '../model/model.js';
|
|
|
9
9
|
import { type Currency } from '../money/currency.js';
|
|
10
10
|
import { type Uom } from '../money/quantity.js';
|
|
11
11
|
import type { RegisteredModel } from '../registry/registry.js';
|
|
12
|
+
import { type AggregateQueryRaw } from './aggregate.js';
|
|
12
13
|
import { type OnchangeInputRaw, type OnchangeResultRaw } from './onchange.js';
|
|
13
14
|
/** Field values of one record. Scalars as values, many2one as id | null, x2many as id arrays. */
|
|
14
15
|
type Values = Map<string, unknown>;
|
|
@@ -53,9 +54,14 @@ export declare class RecordSetImpl {
|
|
|
53
54
|
map<T>(fn: (record: never, index: number) => T): T[];
|
|
54
55
|
filter(fn: (record: never, index: number) => boolean): RecordSetImpl;
|
|
55
56
|
mapped(key: string): unknown[];
|
|
57
|
+
sum(key: string, currency?: Currency | {
|
|
58
|
+
readonly id: number;
|
|
59
|
+
} | number): unknown;
|
|
56
60
|
load(spec?: unknown): Promise<RecordSetImpl>;
|
|
57
61
|
/** Updates the records in the cache now; flushed at the next flush point. */
|
|
58
|
-
write(values: Readonly<Record<string, unknown
|
|
62
|
+
write(values: Readonly<Record<string, unknown>>, options?: {
|
|
63
|
+
readonly expect?: Readonly<Record<string, unknown>>;
|
|
64
|
+
}): Promise<void>;
|
|
59
65
|
/** Deletes the records now. */
|
|
60
66
|
unlink(): Promise<void>;
|
|
61
67
|
/** Ids of a pending x2many set, loading them if needed. */
|
|
@@ -69,6 +75,8 @@ export declare class RecordSetImpl {
|
|
|
69
75
|
readonly field?: string;
|
|
70
76
|
readonly limit?: number;
|
|
71
77
|
readonly action?: AuditEntry['action'];
|
|
78
|
+
/** Rows older than this row id (pagination: the last `id` of the previous page). */
|
|
79
|
+
readonly before?: number;
|
|
72
80
|
}): Promise<AuditEntry[]>;
|
|
73
81
|
/** Numbers unnumbered records of a manual sequence field (RFC 0012 §7.4). */
|
|
74
82
|
assignNumber(key: string, options?: {
|
|
@@ -97,5 +105,6 @@ export declare function modelRef(env: Env, name: string): {
|
|
|
97
105
|
browse(ids: readonly number[]): RecordSetImpl;
|
|
98
106
|
onchange(input: OnchangeInputRaw): Promise<OnchangeResultRaw>;
|
|
99
107
|
copy(rows: readonly Readonly<Record<string, unknown>>[]): Promise<RecordSetImpl>;
|
|
108
|
+
aggregate(query: AggregateQueryRaw): Promise<Record<string, unknown>[]>;
|
|
100
109
|
};
|
|
101
110
|
export {};
|
|
@@ -6,21 +6,24 @@ import { resolveTranslation } from '../../i18n/index.js';
|
|
|
6
6
|
import { compile, sql } from '../../sql/index.js';
|
|
7
7
|
import { Decimal as DecimalJs } from 'decimal.js';
|
|
8
8
|
import { internalsOf } from '../env/env.js';
|
|
9
|
-
import { FieldNotLoadedError, MissingRecordError, SingletonError } from '../errors.js';
|
|
9
|
+
import { FieldNotLoadedError, InvalidFieldError, MissingRecordError, SingletonError, } from '../errors.js';
|
|
10
10
|
import { defineCurrency } from '../money/currency.js';
|
|
11
11
|
import { Money } from '../money/money.js';
|
|
12
12
|
import { defineUom, Quantity } from '../money/quantity.js';
|
|
13
13
|
import { targetOf } from '../registry/registry.js';
|
|
14
|
+
import { runAggregate } from './aggregate.js';
|
|
14
15
|
import { flushAudit, trailOf } from './audit.js';
|
|
15
16
|
import { assignComputed, computeFields, recompute, } from './compute.js';
|
|
16
17
|
import { checkConstraints } from './constraints.js';
|
|
17
18
|
import { compileDomain, compileOrder, scopingConditions } from './domain.js';
|
|
18
19
|
import { runOnchange, } from './onchange.js';
|
|
19
20
|
import { junctionTable } from './relations.js';
|
|
20
|
-
import { assertAccess, assertDomainFields, assertFields, explainDenied, loadedValue, readableKeys, ruleConditions, } from './security.js';
|
|
21
|
+
import { assertAccess, assertDomainFields, assertFields, explainDenied, fieldGroupsOf, loadedValue, readableKeys, ruleConditions, } from './security.js';
|
|
21
22
|
import { assignNumbers } from './sequences.js';
|
|
23
|
+
import { sourceOf } from './source.js';
|
|
22
24
|
import { availableTransitions, runTransition } from './transitions.js';
|
|
23
|
-
import {
|
|
25
|
+
import { companyValue } from './values.js';
|
|
26
|
+
import { assertExpected, createRecords, flushDirty, unlinkRecords, writeRecords, } from './writes.js';
|
|
24
27
|
const CHUNK = 1000;
|
|
25
28
|
/** @internal */
|
|
26
29
|
export function createRecordCache() {
|
|
@@ -124,7 +127,7 @@ async function fetchMissing(loader, model, ids, fields, user = false) {
|
|
|
124
127
|
const seen = new Set();
|
|
125
128
|
for (let i = 0; i < missing.length; i += CHUNK) {
|
|
126
129
|
const chunk = missing.slice(i, i + CHUNK);
|
|
127
|
-
const rows = await loader.internals.query(compile(sql `SELECT ${columns} FROM ${
|
|
130
|
+
const rows = await loader.internals.query(compile(sql `SELECT ${columns} FROM ${sourceOf(loader.internals, model)} WHERE ${sql.id('id')} = ANY(${chunk})${scope}`));
|
|
128
131
|
for (const row of rows)
|
|
129
132
|
seen.add(hydrate(loader, model, row, wanted));
|
|
130
133
|
}
|
|
@@ -139,7 +142,7 @@ async function fetchMissing(loader, model, ids, fields, user = false) {
|
|
|
139
142
|
await ensureValueObjects(loader, model, ids, fields);
|
|
140
143
|
}
|
|
141
144
|
async function assertExist(loader, model, ids, scope = sql.empty) {
|
|
142
|
-
const rows = await loader.internals.query(compile(sql `SELECT ${sql.id('id')} FROM ${
|
|
145
|
+
const rows = await loader.internals.query(compile(sql `SELECT ${sql.id('id')} FROM ${sourceOf(loader.internals, model)} WHERE ${sql.id('id')} = ANY(${[...ids]})${scope}`));
|
|
143
146
|
const found = new Set(rows.map((r) => Number(r.id)));
|
|
144
147
|
const absent = ids.filter((id) => !found.has(id));
|
|
145
148
|
if (absent.length > 0) {
|
|
@@ -237,7 +240,7 @@ async function fetchX2Many(loader, model, key, parents, sub, user = false) {
|
|
|
237
240
|
let rows;
|
|
238
241
|
if (field.kind === 'one2many') {
|
|
239
242
|
const inverse = sql.id(target.columns[field.inverseField ?? ''] ?? '');
|
|
240
|
-
rows = await loader.internals.query(compile(sql `SELECT ${t}.${inverse} AS ${sql.id('parent_id')}, ${columns} FROM ${
|
|
243
|
+
rows = await loader.internals.query(compile(sql `SELECT ${t}.${inverse} AS ${sql.id('parent_id')}, ${columns} FROM ${sourceOf(loader.internals, target)} AS ${t} WHERE ${t}.${inverse} = ANY(${chunk})${scope} ORDER BY ${order}`));
|
|
241
244
|
}
|
|
242
245
|
else {
|
|
243
246
|
const j = junctionTable(model, field, target);
|
|
@@ -379,9 +382,32 @@ export class RecordSetImpl {
|
|
|
379
382
|
const kept = [...this].filter((r, i) => fn(r, i)).map((r) => r.ids[0]);
|
|
380
383
|
return new (recordClass(this.model))(this.env, this.registered, kept, this.#group, undefined);
|
|
381
384
|
}
|
|
385
|
+
/** A `Currency` from a currency, a record reference or an id (loaded with the records' monetary fields). */
|
|
386
|
+
#currencyOf(currency) {
|
|
387
|
+
if (currency === undefined)
|
|
388
|
+
return undefined;
|
|
389
|
+
if (typeof currency === 'object' && 'code' in currency)
|
|
390
|
+
return currency;
|
|
391
|
+
const id = typeof currency === 'number' ? currency : currency.id;
|
|
392
|
+
const found = this.#loader.internals.cache.currencies.get(id);
|
|
393
|
+
if (found === undefined)
|
|
394
|
+
throw new FieldNotLoadedError(this.model.name, 'currency', `Currency ${id} is not loaded: pass a Currency, or sum records whose monetary fields are loaded in it.`);
|
|
395
|
+
return found;
|
|
396
|
+
}
|
|
382
397
|
mapped(key) {
|
|
383
398
|
return [...this].map((r) => r[key]);
|
|
384
399
|
}
|
|
400
|
+
sum(key, currency) {
|
|
401
|
+
const kind = this.model.fields[key]?.kind;
|
|
402
|
+
const values = this.mapped(key).filter((v) => v !== null && v !== undefined);
|
|
403
|
+
if (kind === 'monetary')
|
|
404
|
+
return Money.sum(values, this.#currencyOf(currency));
|
|
405
|
+
if (kind === 'decimal')
|
|
406
|
+
return values.reduce((total, v) => total.plus(v), new DecimalJs(0));
|
|
407
|
+
if (kind === 'integer' || kind === 'float')
|
|
408
|
+
return values.reduce((total, v) => total + v, 0);
|
|
409
|
+
throw new InvalidFieldError(`${this.model.name}.sum() needs an integer, float, decimal or monetary field; '${key}' is ${kind ?? 'not a field'}.`, 'Sum a numeric field, or use mapped() and reduce the values yourself.');
|
|
410
|
+
}
|
|
385
411
|
async load(spec) {
|
|
386
412
|
const loader = this.#loader;
|
|
387
413
|
const normalized = normalizeSpec(loader, this.model, spec);
|
|
@@ -405,8 +431,11 @@ export class RecordSetImpl {
|
|
|
405
431
|
return writeHost(this.#loader);
|
|
406
432
|
}
|
|
407
433
|
/** Updates the records in the cache now; flushed at the next flush point. */
|
|
408
|
-
async write(values) {
|
|
409
|
-
|
|
434
|
+
async write(values, options = {}) {
|
|
435
|
+
const ids = await this.resolveIds();
|
|
436
|
+
if (options.expect !== undefined)
|
|
437
|
+
await assertExpected(this.#loader.internals, this.model, ids, options.expect);
|
|
438
|
+
await writeRecords(this.#host(), this.model, ids, values);
|
|
410
439
|
}
|
|
411
440
|
/** Deletes the records now. */
|
|
412
441
|
async unlink() {
|
|
@@ -422,7 +451,8 @@ export class RecordSetImpl {
|
|
|
422
451
|
return [...this].map((r) => {
|
|
423
452
|
const row = { id: r.ids[0] };
|
|
424
453
|
for (const key of keys)
|
|
425
|
-
|
|
454
|
+
if (key !== 'id')
|
|
455
|
+
row[key] = plain(r.fieldValue(key), this.model.fields[key]); // id is always there
|
|
426
456
|
return row;
|
|
427
457
|
});
|
|
428
458
|
}
|
|
@@ -475,7 +505,7 @@ export class RecordSetImpl {
|
|
|
475
505
|
if (id === undefined || field === undefined)
|
|
476
506
|
throw new FieldNotLoadedError(this.modelName, key, `'${key}' is not a field of ${this.modelName}.`);
|
|
477
507
|
const internals = internalsOf(this.env);
|
|
478
|
-
if (
|
|
508
|
+
if (fieldGroupsOf(internals, this.model, key).read.length > 0)
|
|
479
509
|
assertFields(internals, this.model, [key], 'read');
|
|
480
510
|
const { cache } = internals;
|
|
481
511
|
const values = valuesOf(cache, this.modelName, id);
|
|
@@ -502,7 +532,9 @@ export class RecordSetImpl {
|
|
|
502
532
|
: `Load it first: await records.load(['${key}'])${field.kind === 'many2one' ? ` or load({ ${key}: true }) for the related record` : ''}.`;
|
|
503
533
|
throw new FieldNotLoadedError(this.modelName, key, hint);
|
|
504
534
|
}
|
|
505
|
-
const raw =
|
|
535
|
+
const raw = field.companyDependent
|
|
536
|
+
? companyValue(field, values.get(key), this.env.companyId)
|
|
537
|
+
: values.get(key);
|
|
506
538
|
if (field.translate) {
|
|
507
539
|
return resolveTranslation(raw, this.env.lang, internalsOf(this.env).sourceLang);
|
|
508
540
|
}
|
|
@@ -597,6 +629,7 @@ function computeHost(loader) {
|
|
|
597
629
|
return {
|
|
598
630
|
internals: loader.internals,
|
|
599
631
|
load: (model, ids, spec) => loadInto(loader, model, ids, spec),
|
|
632
|
+
valueObjects: (model, ids, fields) => ensureValueObjects(loader, model, ids, fields),
|
|
600
633
|
values: (model, id, create) => valuesOf(loader.internals.cache, model, id, create),
|
|
601
634
|
recordset: (model, ids) => recordsetOf(loader, model, ids),
|
|
602
635
|
};
|
|
@@ -630,8 +663,35 @@ function writeHost(loader) {
|
|
|
630
663
|
recordset: (model, ids) => recordsetOf(loader, model, ids),
|
|
631
664
|
};
|
|
632
665
|
}
|
|
666
|
+
/** True when the domain has a relation path or an x2many `any` / `none` (it reads other models' tables). */
|
|
667
|
+
function followsRelations(model, where) {
|
|
668
|
+
for (const [key, value] of Object.entries(where ?? {})) {
|
|
669
|
+
if (key === 'or' || key === 'and') {
|
|
670
|
+
if (Array.isArray(value) &&
|
|
671
|
+
value.some((d) => followsRelations(model, d)))
|
|
672
|
+
return true;
|
|
673
|
+
}
|
|
674
|
+
else if (key === 'not') {
|
|
675
|
+
if (followsRelations(model, value))
|
|
676
|
+
return true;
|
|
677
|
+
}
|
|
678
|
+
else if (key.includes('.'))
|
|
679
|
+
return true;
|
|
680
|
+
else {
|
|
681
|
+
const kind = model.fields[key]?.kind;
|
|
682
|
+
if (kind === 'one2many' || kind === 'many2many')
|
|
683
|
+
return true;
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
return false;
|
|
687
|
+
}
|
|
633
688
|
function translationScope(internals) {
|
|
634
|
-
return {
|
|
689
|
+
return {
|
|
690
|
+
lang: internals.env.lang,
|
|
691
|
+
source: internals.sourceLang,
|
|
692
|
+
company: internals.env.companyId,
|
|
693
|
+
...(internals.asOf === undefined ? {} : { from: (m) => sourceOf(internals, m) }),
|
|
694
|
+
};
|
|
635
695
|
}
|
|
636
696
|
/** @internal The currency value object of a `res.currency` id, loaded through the cache. */
|
|
637
697
|
export async function currencyById(internals, id) {
|
|
@@ -690,7 +750,8 @@ export function modelRef(env, name) {
|
|
|
690
750
|
assertAccess(internals, model, 'read');
|
|
691
751
|
assertDomainFields(internals, model, query.where);
|
|
692
752
|
assertFields(internals, model, (query.order ?? []).map((o) => o.split(' ')[0] ?? ''), 'read');
|
|
693
|
-
|
|
753
|
+
// The search must see pending writes (and computes): of every model when a relation path reaches others.
|
|
754
|
+
await internals.flush(followsRelations(model, query.where) ? undefined : model.name);
|
|
694
755
|
const fields = new Set(readableKeys(internals, model, withSiblings(model, defaultKeys(model))));
|
|
695
756
|
const wanted = [...fields].filter((k) => k !== 'id' && model.columns[k] !== undefined);
|
|
696
757
|
const columns = sql.join([
|
|
@@ -706,7 +767,7 @@ export function modelRef(env, name) {
|
|
|
706
767
|
const where = conditions.length === 0 ? sql.empty : sql ` WHERE ${sql.join(conditions, sql ` AND `)}`;
|
|
707
768
|
const limit = query.limit === undefined ? sql.empty : sql ` LIMIT ${query.limit}`;
|
|
708
769
|
const offset = query.offset === undefined ? sql.empty : sql ` OFFSET ${query.offset}`;
|
|
709
|
-
const rows = await internals.query(compile(sql `SELECT ${columns} FROM ${
|
|
770
|
+
const rows = await internals.query(compile(sql `SELECT ${columns} FROM ${sourceOf(internals, model)}${where} ORDER BY ${compileOrder(model, query.order, translation)}${limit}${offset}`));
|
|
710
771
|
const ids = rows.map((row) => hydrate(loader, model, row, wanted));
|
|
711
772
|
await ensureValueObjects(loader, model, ids, fields);
|
|
712
773
|
return new (recordClass(model))(env, registered, ids, { ids }, undefined);
|
|
@@ -719,5 +780,10 @@ export function modelRef(env, name) {
|
|
|
719
780
|
const ids = await createRecords(writeHost(loader), model, rows, { copy: true });
|
|
720
781
|
return new (recordClass(model))(env, registered, ids, { ids }, undefined);
|
|
721
782
|
},
|
|
783
|
+
aggregate: (query) => runAggregate({
|
|
784
|
+
internals,
|
|
785
|
+
translation: translationScope(internals),
|
|
786
|
+
currency: (id) => currencyById(internals, id),
|
|
787
|
+
}, model, query),
|
|
722
788
|
};
|
|
723
789
|
}
|