shutro 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +99 -2
- package/dist/audit/index.d.ts +59 -0
- package/dist/audit/index.js +96 -0
- package/dist/cli/bin.d.ts +2 -0
- package/dist/cli/bin.js +11 -0
- package/dist/cli/cli.d.ts +10 -0
- package/dist/cli/cli.js +164 -0
- package/dist/cli/config.d.ts +18 -0
- package/dist/cli/config.js +49 -0
- package/dist/cli/errors.d.ts +16 -0
- package/dist/cli/errors.js +23 -0
- package/dist/cli/generate/generate.d.ts +33 -0
- package/dist/cli/generate/generate.js +84 -0
- package/dist/cli/generate/render.d.ts +23 -0
- package/dist/cli/generate/render.js +249 -0
- package/dist/cli/index.d.ts +12 -0
- package/dist/cli/index.js +12 -0
- package/dist/cli/init.d.ts +2 -0
- package/dist/cli/init.js +65 -0
- package/dist/cli/inspect.d.ts +10 -0
- package/dist/cli/inspect.js +82 -0
- package/dist/cli/packages.d.ts +6 -0
- package/dist/cli/packages.js +6 -0
- package/dist/cli/project.d.ts +18 -0
- package/dist/cli/project.js +39 -0
- package/dist/cli/resolve.d.ts +2 -0
- package/dist/cli/resolve.js +28 -0
- package/dist/core/compute/graph.d.ts +52 -0
- package/dist/core/compute/graph.js +162 -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 +468 -0
- package/dist/core/env/env.js +916 -0
- package/dist/core/env/identity.d.ts +43 -0
- package/dist/core/env/identity.js +65 -0
- package/dist/core/env/inspector.d.ts +55 -0
- package/dist/core/env/inspector.js +85 -0
- package/dist/core/env/time.d.ts +12 -0
- package/dist/core/env/time.js +38 -0
- package/dist/core/errors.d.ts +256 -0
- package/dist/core/errors.js +360 -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 +51 -0
- package/dist/core/index.js +42 -0
- package/dist/core/model/company.d.ts +6 -0
- package/dist/core/model/company.js +31 -0
- package/dist/core/model/faces.d.ts +42 -0
- package/dist/core/model/faces.js +1 -0
- package/dist/core/model/field.d.ts +479 -0
- package/dist/core/model/field.js +461 -0
- package/dist/core/model/generated.d.ts +77 -0
- package/dist/core/model/generated.js +1 -0
- package/dist/core/model/id.d.ts +33 -0
- package/dist/core/model/id.js +4 -0
- package/dist/core/model/model.d.ts +387 -0
- package/dist/core/model/model.js +566 -0
- package/dist/core/model/partition.d.ts +31 -0
- package/dist/core/model/partition.js +71 -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/currency.d.ts +39 -0
- package/dist/core/money/currency.js +37 -0
- package/dist/core/money/decimal.d.ts +26 -0
- package/dist/core/money/decimal.js +51 -0
- package/dist/core/money/fx.d.ts +68 -0
- package/dist/core/money/fx.js +124 -0
- package/dist/core/money/money.d.ts +84 -0
- package/dist/core/money/money.js +173 -0
- package/dist/core/money/quantity.d.ts +67 -0
- package/dist/core/money/quantity.js +108 -0
- package/dist/core/money/rounding.d.ts +11 -0
- package/dist/core/money/rounding.js +12 -0
- package/dist/core/recordset/aggregate.d.ts +22 -0
- package/dist/core/recordset/aggregate.js +258 -0
- package/dist/core/recordset/audit.d.ts +33 -0
- package/dist/core/recordset/audit.js +262 -0
- package/dist/core/recordset/compute.d.ts +36 -0
- package/dist/core/recordset/compute.js +414 -0
- package/dist/core/recordset/constraints.d.ts +9 -0
- package/dist/core/recordset/constraints.js +61 -0
- package/dist/core/recordset/domain.d.ts +31 -0
- package/dist/core/recordset/domain.js +300 -0
- package/dist/core/recordset/onchange.d.ts +43 -0
- package/dist/core/recordset/onchange.js +240 -0
- package/dist/core/recordset/recordset.d.ts +110 -0
- package/dist/core/recordset/recordset.js +789 -0
- package/dist/core/recordset/relations.d.ts +15 -0
- package/dist/core/recordset/relations.js +13 -0
- package/dist/core/recordset/rls.d.ts +15 -0
- package/dist/core/recordset/rls.js +108 -0
- package/dist/core/recordset/security.d.ts +56 -0
- package/dist/core/recordset/security.js +269 -0
- package/dist/core/recordset/sequences.d.ts +31 -0
- package/dist/core/recordset/sequences.js +154 -0
- package/dist/core/recordset/source.d.ts +9 -0
- package/dist/core/recordset/source.js +19 -0
- package/dist/core/recordset/sqlErrors.d.ts +6 -0
- package/dist/core/recordset/sqlErrors.js +39 -0
- package/dist/core/recordset/transitions.d.ts +10 -0
- package/dist/core/recordset/transitions.js +80 -0
- package/dist/core/recordset/types.d.ts +415 -0
- package/dist/core/recordset/types.js +8 -0
- package/dist/core/recordset/values.d.ts +33 -0
- package/dist/core/recordset/values.js +177 -0
- package/dist/core/recordset/writes.d.ts +42 -0
- package/dist/core/recordset/writes.js +786 -0
- package/dist/core/registry/ddl.d.ts +31 -0
- package/dist/core/registry/ddl.js +174 -0
- package/dist/core/registry/extension.d.ts +94 -0
- package/dist/core/registry/extension.js +90 -0
- package/dist/core/registry/module.d.ts +89 -0
- package/dist/core/registry/module.js +98 -0
- package/dist/core/registry/registry.d.ts +130 -0
- package/dist/core/registry/registry.js +591 -0
- package/dist/core/security/runtime.d.ts +102 -0
- package/dist/core/security/runtime.js +232 -0
- package/dist/driver-pg/driver.d.ts +88 -0
- package/dist/driver-pg/driver.js +177 -0
- package/dist/driver-pg/errors.d.ts +72 -0
- package/dist/driver-pg/errors.js +182 -0
- package/dist/driver-pg/index.d.ts +7 -0
- package/dist/driver-pg/index.js +7 -0
- package/dist/i18n/index.d.ts +25 -0
- package/dist/i18n/index.js +51 -0
- package/dist/migrate/apply.d.ts +78 -0
- package/dist/migrate/apply.js +167 -0
- package/dist/migrate/catalog.d.ts +10 -0
- package/dist/migrate/catalog.js +122 -0
- package/dist/migrate/diff.d.ts +98 -0
- package/dist/migrate/diff.js +160 -0
- package/dist/migrate/errors.d.ts +21 -0
- package/dist/migrate/errors.js +31 -0
- package/dist/migrate/index.d.ts +18 -0
- package/dist/migrate/index.js +18 -0
- package/dist/migrate/render.d.ts +5 -0
- package/dist/migrate/render.js +101 -0
- package/dist/migrate/schema.d.ts +61 -0
- package/dist/migrate/schema.js +233 -0
- package/dist/security/index.d.ts +147 -0
- package/dist/security/index.js +278 -0
- package/dist/sequence/index.d.ts +63 -0
- package/dist/sequence/index.js +106 -0
- package/dist/sql/ast.d.ts +49 -0
- package/dist/sql/ast.js +47 -0
- package/dist/sql/builder/builder.d.ts +215 -0
- package/dist/sql/builder/builder.js +308 -0
- package/dist/sql/builder/expression.d.ts +80 -0
- package/dist/sql/builder/expression.js +126 -0
- package/dist/sql/compile.d.ts +18 -0
- package/dist/sql/compile.js +41 -0
- package/dist/sql/errors.d.ts +13 -0
- package/dist/sql/errors.js +16 -0
- package/dist/sql/index.d.ts +19 -0
- package/dist/sql/index.js +19 -0
- package/dist/sql/tag.d.ts +47 -0
- package/dist/sql/tag.js +123 -0
- package/package.json +82 -4
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Naming of many2many junction tables (RFC 0001 §7.3: derived deterministically).
|
|
3
|
+
*/
|
|
4
|
+
import type { Field } from '../model/field.js';
|
|
5
|
+
import type { AnyModel } from '../model/model.js';
|
|
6
|
+
/** A many2many junction table and its two columns. */
|
|
7
|
+
export interface JunctionTable {
|
|
8
|
+
readonly table: string;
|
|
9
|
+
readonly sourceTable: string;
|
|
10
|
+
readonly sourceColumn: string;
|
|
11
|
+
readonly targetTable: string;
|
|
12
|
+
readonly targetColumn: string;
|
|
13
|
+
}
|
|
14
|
+
/** `sale_order` ⟷ `sale_tag` → table `sale_order_sale_tag_rel` with `sale_order_id`, `sale_tag_id`. */
|
|
15
|
+
export declare function junctionTable(source: AnyModel, field: Field, target: AnyModel): JunctionTable;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** `sale_order` ⟷ `sale_tag` → table `sale_order_sale_tag_rel` with `sale_order_id`, `sale_tag_id`. */
|
|
2
|
+
export function junctionTable(source, field, target) {
|
|
3
|
+
const relation = field.relation;
|
|
4
|
+
const sourceColumn = `${source.table}_id`;
|
|
5
|
+
const targetColumn = source.table === target.table ? `${target.table}_other_id` : `${target.table}_id`;
|
|
6
|
+
return {
|
|
7
|
+
table: relation ?? `${source.table}_${target.table}_rel`,
|
|
8
|
+
sourceTable: source.table,
|
|
9
|
+
sourceColumn,
|
|
10
|
+
targetTable: target.table,
|
|
11
|
+
targetColumn,
|
|
12
|
+
};
|
|
13
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PostgreSQL row-level security generated from record rules (RFC 0014 §7.5): one permissive policy per group rule,
|
|
3
|
+
* one restrictive policy per global rule, and the "no applicable group rule" and superuser escapes, all reading the
|
|
4
|
+
* session settings `shutro.run()` pushes.
|
|
5
|
+
*/
|
|
6
|
+
import { type PolicyInput } from '../../security/index.js';
|
|
7
|
+
import type { AnyModel } from '../model/model.js';
|
|
8
|
+
import type { Registry } from '../registry/registry.js';
|
|
9
|
+
import { type ModelResolver } from './domain.js';
|
|
10
|
+
/** A rule domain as a boolean SQL expression over the table's columns and the session settings. */
|
|
11
|
+
export declare function ruleCondition(model: AnyModel, domain: Readonly<Record<string, unknown>>, resolve?: ModelResolver): string;
|
|
12
|
+
/** The policies of one model, or `[]` when it has no rules. */
|
|
13
|
+
export declare function modelPolicies(model: AnyModel, resolve?: ModelResolver): PolicyInput[];
|
|
14
|
+
/** Every statement that enables RLS for the models with record rules. Run them through `@shutro/migrate` or directly. */
|
|
15
|
+
export declare function rlsStatements(registry: Registry): string[];
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PostgreSQL row-level security generated from record rules (RFC 0014 §7.5): one permissive policy per group rule,
|
|
3
|
+
* one restrictive policy per global rule, and the "no applicable group rule" and superuser escapes, all reading the
|
|
4
|
+
* session settings `shutro.run()` pushes.
|
|
5
|
+
*/
|
|
6
|
+
import { rlsStatements as policyStatements, RLS_PLACEHOLDERS, RLS_SU, resolvePlaceholders, rlsGroupCondition, } from '../../security/index.js';
|
|
7
|
+
import { compile, sql } from '../../sql/index.js';
|
|
8
|
+
import { compileDomain } from './domain.js';
|
|
9
|
+
const MARK = '\u0000$env:';
|
|
10
|
+
const SENTINEL = { uid: Number.NaN, companyId: Number.NaN, companyIds: [] };
|
|
11
|
+
const COMMANDS = {
|
|
12
|
+
read: 'SELECT',
|
|
13
|
+
write: 'UPDATE',
|
|
14
|
+
create: 'INSERT',
|
|
15
|
+
unlink: 'DELETE',
|
|
16
|
+
};
|
|
17
|
+
function literal(value) {
|
|
18
|
+
if (typeof value === 'string') {
|
|
19
|
+
if (value === `${MARK}uid`)
|
|
20
|
+
return RLS_PLACEHOLDERS.uid;
|
|
21
|
+
if (value === `${MARK}companyId`)
|
|
22
|
+
return RLS_PLACEHOLDERS.companyId;
|
|
23
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
24
|
+
}
|
|
25
|
+
if (typeof value === 'number' || typeof value === 'bigint')
|
|
26
|
+
return String(value);
|
|
27
|
+
if (typeof value === 'boolean')
|
|
28
|
+
return value ? 'true' : 'false';
|
|
29
|
+
if (value === null || value === undefined)
|
|
30
|
+
return 'NULL';
|
|
31
|
+
if (Array.isArray(value)) {
|
|
32
|
+
if (value.length === 1 && value[0] === `${MARK}companyIds`)
|
|
33
|
+
return RLS_PLACEHOLDERS.companyIds;
|
|
34
|
+
return `ARRAY[${value.map(literal).join(', ')}]`;
|
|
35
|
+
}
|
|
36
|
+
if (value instanceof Date)
|
|
37
|
+
return `'${value.toISOString()}'::timestamptz`;
|
|
38
|
+
return `'${JSON.stringify(value).replaceAll("'", "''")}'::jsonb`;
|
|
39
|
+
}
|
|
40
|
+
/** A rule domain as a boolean SQL expression over the table's columns and the session settings. */
|
|
41
|
+
export function ruleCondition(model, domain, resolve) {
|
|
42
|
+
// Placeholders become markers that survive compilation as parameters, then turn into current_setting() reads.
|
|
43
|
+
const marked = resolvePlaceholders(domain, {
|
|
44
|
+
uid: `${MARK}uid`,
|
|
45
|
+
companyId: `${MARK}companyId`,
|
|
46
|
+
companyIds: [`${MARK}companyIds`],
|
|
47
|
+
});
|
|
48
|
+
void SENTINEL;
|
|
49
|
+
const conditions = compileDomain(model, marked, undefined, resolve);
|
|
50
|
+
if (conditions.length === 0)
|
|
51
|
+
return 'true';
|
|
52
|
+
const { text, params } = compile(sql.join(conditions, sql ` AND `));
|
|
53
|
+
return text.replace(/\$(\d+)/g, (_, n) => literal(params[Number(n) - 1]));
|
|
54
|
+
}
|
|
55
|
+
/** The policies of one model, or `[]` when it has no rules. */
|
|
56
|
+
export function modelPolicies(model, resolve) {
|
|
57
|
+
const policies = [];
|
|
58
|
+
const perms = ['read', 'write', 'create', 'unlink'];
|
|
59
|
+
for (const perm of perms) {
|
|
60
|
+
const command = COMMANDS[perm];
|
|
61
|
+
const rules = Object.entries(model.rules).filter(([, r]) => r.perms.includes(perm));
|
|
62
|
+
if (rules.length === 0)
|
|
63
|
+
continue;
|
|
64
|
+
const groupCodes = new Set();
|
|
65
|
+
for (const [key, rule] of rules) {
|
|
66
|
+
const name = `${model.table}_${key}_${perm}`.slice(0, 63);
|
|
67
|
+
if (rule.groups === 'global') {
|
|
68
|
+
policies.push({
|
|
69
|
+
table: model.table,
|
|
70
|
+
name,
|
|
71
|
+
command,
|
|
72
|
+
permissive: false,
|
|
73
|
+
condition: `${RLS_SU} OR (${ruleCondition(model, rule.domain, resolve)})`,
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
for (const g of rule.groups)
|
|
78
|
+
groupCodes.add(g);
|
|
79
|
+
policies.push({
|
|
80
|
+
table: model.table,
|
|
81
|
+
name,
|
|
82
|
+
command,
|
|
83
|
+
permissive: true,
|
|
84
|
+
condition: `${RLS_SU} OR (${rlsGroupCondition(rule.groups)} AND (${ruleCondition(model, rule.domain, resolve)}))`,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
// Users none of whose groups a rule names are unrestricted by group rules; without any group rule, everyone is.
|
|
89
|
+
policies.push({
|
|
90
|
+
table: model.table,
|
|
91
|
+
name: `${model.table}_nogroup_${perm}`.slice(0, 63),
|
|
92
|
+
command,
|
|
93
|
+
permissive: true,
|
|
94
|
+
condition: groupCodes.size === 0 ? 'true' : `${RLS_SU} OR NOT (${rlsGroupCondition([...groupCodes])})`,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
return policies;
|
|
98
|
+
}
|
|
99
|
+
/** Every statement that enables RLS for the models with record rules. Run them through `@shutro/migrate` or directly. */
|
|
100
|
+
export function rlsStatements(registry) {
|
|
101
|
+
const out = [];
|
|
102
|
+
for (const { model } of registry.models.values()) {
|
|
103
|
+
const policies = modelPolicies(model, (n) => registry.get(n).model);
|
|
104
|
+
if (policies.length > 0)
|
|
105
|
+
out.push(...policyStatements(model.table, policies));
|
|
106
|
+
}
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Access control at runtime (RFC 0014): model ACL checks, field-level groups, record rules compiled into WHERE
|
|
3
|
+
* fragments, per-record checks for writes and deletes, and encryption of stored values. Superuser scopes bypass
|
|
4
|
+
* the checks; multi-company consistency does not live here (RFC 0003 §7.4).
|
|
5
|
+
*/
|
|
6
|
+
import { type FieldGroups, type Perm, type RulePerm } from '../../security/index.js';
|
|
7
|
+
import { type SqlFragment } from '../../sql/index.js';
|
|
8
|
+
import type { ScopeInternals } from '../env/env.js';
|
|
9
|
+
import type { Field } from '../model/field.js';
|
|
10
|
+
import type { AnyModel } from '../model/model.js';
|
|
11
|
+
/** True when the environment may perform `perm` on the model (ACL, RFC 0014 §7.2). */
|
|
12
|
+
export declare function canAccess(internals: ScopeInternals, model: AnyModel, perm: Perm): boolean;
|
|
13
|
+
/** @throws {AccessError} unless {@link canAccess}. */
|
|
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;
|
|
29
|
+
/** True when the field may be read / written by the environment. */
|
|
30
|
+
export declare function canField(internals: ScopeInternals, model: AnyModel, key: string, kind: 'read' | 'write'): boolean;
|
|
31
|
+
/** @throws {AccessError} naming the first field the environment may not read / write. */
|
|
32
|
+
export declare function assertFields(internals: ScopeInternals, model: AnyModel, keys: Iterable<string>, kind: 'read' | 'write'): void;
|
|
33
|
+
/** The keys of `keys` the environment may read (restricted fields are left out of default projections). */
|
|
34
|
+
export declare function readableKeys(internals: ScopeInternals, model: AnyModel, keys: Iterable<string>): string[];
|
|
35
|
+
/**
|
|
36
|
+
* Checks that every field a domain mentions is readable, following relation paths and `any` / `none` into the
|
|
37
|
+
* related models: a filter on a hidden field would leak it through which records match (RFC 0014 §7.4).
|
|
38
|
+
*/
|
|
39
|
+
export declare function assertDomainFields(internals: ScopeInternals, model: AnyModel, domain: unknown): void;
|
|
40
|
+
/** The field keys a domain mentions (through `or` / `and` / `not`). */
|
|
41
|
+
export declare function domainKeys(domain: unknown, out?: Set<string>): Set<string>;
|
|
42
|
+
/** Record-rule conditions for `perm` (RFC 0014 §7.3): globals ANDed, applicable group rules ORed. Empty under `su`. */
|
|
43
|
+
export declare function ruleConditions(internals: ScopeInternals, model: AnyModel, perm: RulePerm): SqlFragment[];
|
|
44
|
+
/** True when `perm` has rules for the model that apply to this environment. */
|
|
45
|
+
export declare function hasRules(internals: ScopeInternals, model: AnyModel, perm: RulePerm): boolean;
|
|
46
|
+
/**
|
|
47
|
+
* Checks that every id passes the rules for `perm` (RFC 0014 §7.3). Ids that exist but are out of scope are an
|
|
48
|
+
* {@link AccessError}; ids that do not exist are a {@link MissingRecordError}.
|
|
49
|
+
*/
|
|
50
|
+
export declare function assertRecords(internals: ScopeInternals, model: AnyModel, ids: readonly number[], perm: RulePerm): Promise<void>;
|
|
51
|
+
/** Distinguishes missing records from records out of the rules' scope, and throws accordingly. */
|
|
52
|
+
export declare function explainDenied(internals: ScopeInternals, model: AnyModel, denied: readonly number[], perm: RulePerm): Promise<never>;
|
|
53
|
+
/** The value bound for a stored column: encrypted fields are encrypted with the current key (RFC 0014 §7.6). */
|
|
54
|
+
export declare function storedValue(internals: ScopeInternals, field: Field, value: unknown): unknown;
|
|
55
|
+
/** The plaintext of a loaded encrypted value. */
|
|
56
|
+
export declare function loadedValue(internals: ScopeInternals, field: Field, value: unknown): unknown;
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Access control at runtime (RFC 0014): model ACL checks, field-level groups, record rules compiled into WHERE
|
|
3
|
+
* fragments, per-record checks for writes and deletes, and encryption of stored values. Superuser scopes bypass
|
|
4
|
+
* the checks; multi-company consistency does not live here (RFC 0003 §7.4).
|
|
5
|
+
*/
|
|
6
|
+
import { allowed, applicableRules, decrypt, EncryptionError, encrypt, fieldAllowed, resolvePlaceholders, SecurityDefinitionError, } from '../../security/index.js';
|
|
7
|
+
import { compile, sql } from '../../sql/index.js';
|
|
8
|
+
import { calendarDateIn } from '../env/time.js';
|
|
9
|
+
import { AccessError, MissingRecordError } from '../errors.js';
|
|
10
|
+
import { effectiveFieldGroups } from '../security/runtime.js';
|
|
11
|
+
import { compileDomain } from './domain.js';
|
|
12
|
+
import { sourceOf } from './source.js';
|
|
13
|
+
import { bindValue } from './values.js';
|
|
14
|
+
const HINT = 'Ask an administrator for a group that grants it, or run the task inside env.asSuperuser({ reason }).';
|
|
15
|
+
/** True when the environment may perform `perm` on the model (ACL, RFC 0014 §7.2). */
|
|
16
|
+
export function canAccess(internals, model, perm) {
|
|
17
|
+
if (internals.env.su || internals.env.administrator || !internals.registry.security.enforce)
|
|
18
|
+
return true;
|
|
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;
|
|
30
|
+
}
|
|
31
|
+
/** @throws {AccessError} unless {@link canAccess}. */
|
|
32
|
+
export function assertAccess(internals, model, perm) {
|
|
33
|
+
if (canAccess(internals, model, perm))
|
|
34
|
+
return;
|
|
35
|
+
throw new AccessError(model.name, perm, {
|
|
36
|
+
problem: `${perm} access to ${model.name} is denied.`,
|
|
37
|
+
hint: HINT,
|
|
38
|
+
});
|
|
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
|
+
}
|
|
104
|
+
/** True when the field may be read / written by the environment. */
|
|
105
|
+
export function canField(internals, model, key, kind) {
|
|
106
|
+
const field = model.fields[key];
|
|
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))
|
|
113
|
+
return true;
|
|
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;
|
|
118
|
+
}
|
|
119
|
+
/** @throws {AccessError} naming the first field the environment may not read / write. */
|
|
120
|
+
export function assertFields(internals, model, keys, kind) {
|
|
121
|
+
for (const key of keys) {
|
|
122
|
+
if (canField(internals, model, key, kind))
|
|
123
|
+
continue;
|
|
124
|
+
throw new AccessError(model.name, kind, {
|
|
125
|
+
field: key,
|
|
126
|
+
problem: `field '${key}' of ${model.name} is restricted to groups ${fieldGroupsOf(internals, model, key)[kind].join(', ')}.`,
|
|
127
|
+
hint: HINT,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/** The keys of `keys` the environment may read (restricted fields are left out of default projections). */
|
|
132
|
+
export function readableKeys(internals, model, keys) {
|
|
133
|
+
return [...keys].filter((k) => canField(internals, model, k, 'read'));
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Checks that every field a domain mentions is readable, following relation paths and `any` / `none` into the
|
|
137
|
+
* related models: a filter on a hidden field would leak it through which records match (RFC 0014 §7.4).
|
|
138
|
+
*/
|
|
139
|
+
export function assertDomainFields(internals, model, domain) {
|
|
140
|
+
if (Array.isArray(domain)) {
|
|
141
|
+
for (const d of domain)
|
|
142
|
+
assertDomainFields(internals, model, d);
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
if (typeof domain !== 'object' || domain === null)
|
|
146
|
+
return;
|
|
147
|
+
for (const [key, value] of Object.entries(domain)) {
|
|
148
|
+
if (key === 'or' || key === 'and' || key === 'not') {
|
|
149
|
+
assertDomainFields(internals, model, value);
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
const [head = '', ...rest] = key.split('.');
|
|
153
|
+
assertFields(internals, model, [head], 'read');
|
|
154
|
+
const field = model.fields[head];
|
|
155
|
+
const target = field?.target;
|
|
156
|
+
if (target === undefined)
|
|
157
|
+
continue;
|
|
158
|
+
const targetModel = internals.registry.get(target).model;
|
|
159
|
+
assertAccess(internals, targetModel, 'read');
|
|
160
|
+
if (rest.length > 0)
|
|
161
|
+
assertDomainFields(internals, targetModel, { [rest.join('.')]: value });
|
|
162
|
+
else if (typeof value === 'object' && value !== null) {
|
|
163
|
+
const v = value;
|
|
164
|
+
if (v.any !== undefined)
|
|
165
|
+
assertDomainFields(internals, targetModel, v.any);
|
|
166
|
+
if (v.none !== undefined)
|
|
167
|
+
assertDomainFields(internals, targetModel, v.none);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
/** The field keys a domain mentions (through `or` / `and` / `not`). */
|
|
172
|
+
export function domainKeys(domain, out = new Set()) {
|
|
173
|
+
if (Array.isArray(domain)) {
|
|
174
|
+
for (const d of domain)
|
|
175
|
+
domainKeys(d, out);
|
|
176
|
+
return out;
|
|
177
|
+
}
|
|
178
|
+
if (typeof domain !== 'object' || domain === null)
|
|
179
|
+
return out;
|
|
180
|
+
for (const [key, value] of Object.entries(domain)) {
|
|
181
|
+
if (key === 'or' || key === 'and' || key === 'not')
|
|
182
|
+
domainKeys(value, out);
|
|
183
|
+
else
|
|
184
|
+
out.add(key);
|
|
185
|
+
}
|
|
186
|
+
return out;
|
|
187
|
+
}
|
|
188
|
+
/** Record-rule conditions for `perm` (RFC 0014 §7.3): globals ANDed, applicable group rules ORed. Empty under `su`. */
|
|
189
|
+
export function ruleConditions(internals, model, perm) {
|
|
190
|
+
const { env } = internals;
|
|
191
|
+
if (env.su || env.administrator || !internals.registry.security.enforce)
|
|
192
|
+
return [];
|
|
193
|
+
const { globals, groupRules, hasGroupRules } = applicableRules({ ...model.rules, ...(internals.overlay?.rules.get(model.name) ?? {}) }, env.groups, perm);
|
|
194
|
+
const placeholders = { uid: env.uid, companyId: env.companyId, companyIds: env.companyIds };
|
|
195
|
+
const out = [];
|
|
196
|
+
for (const rule of globals) {
|
|
197
|
+
const conditions = compileDomain(model, resolvePlaceholders(rule.domain, placeholders), undefined, (n) => internals.registry.get(n).model);
|
|
198
|
+
if (conditions.length > 0)
|
|
199
|
+
out.push(sql `(${sql.join(conditions, sql ` AND `)})`);
|
|
200
|
+
}
|
|
201
|
+
if (hasGroupRules) {
|
|
202
|
+
if (groupRules.length === 0)
|
|
203
|
+
return out; // no group rule names the user's groups: unrestricted by group rules (Odoo semantics)
|
|
204
|
+
const alternatives = [];
|
|
205
|
+
for (const rule of groupRules) {
|
|
206
|
+
const conditions = compileDomain(model, resolvePlaceholders(rule.domain, placeholders), undefined, (n) => internals.registry.get(n).model);
|
|
207
|
+
if (conditions.length === 0)
|
|
208
|
+
return out; // an unconditional group rule grants everything the globals allow
|
|
209
|
+
alternatives.push(sql `(${sql.join(conditions, sql ` AND `)})`);
|
|
210
|
+
}
|
|
211
|
+
out.push(sql `(${sql.join(alternatives, sql ` OR `)})`);
|
|
212
|
+
}
|
|
213
|
+
return out;
|
|
214
|
+
}
|
|
215
|
+
/** True when `perm` has rules for the model that apply to this environment. */
|
|
216
|
+
export function hasRules(internals, model, perm) {
|
|
217
|
+
return ruleConditions(internals, model, perm).length > 0;
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Checks that every id passes the rules for `perm` (RFC 0014 §7.3). Ids that exist but are out of scope are an
|
|
221
|
+
* {@link AccessError}; ids that do not exist are a {@link MissingRecordError}.
|
|
222
|
+
*/
|
|
223
|
+
export async function assertRecords(internals, model, ids, perm) {
|
|
224
|
+
const real = ids.filter((id) => id > 0);
|
|
225
|
+
if (real.length === 0)
|
|
226
|
+
return;
|
|
227
|
+
const conditions = ruleConditions(internals, model, perm);
|
|
228
|
+
if (conditions.length === 0)
|
|
229
|
+
return;
|
|
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 `)}`));
|
|
231
|
+
const passed = new Set(rows.map((r) => Number(r.id)));
|
|
232
|
+
const denied = real.filter((id) => !passed.has(id));
|
|
233
|
+
if (denied.length === 0)
|
|
234
|
+
return;
|
|
235
|
+
await explainDenied(internals, model, denied, perm);
|
|
236
|
+
}
|
|
237
|
+
/** Distinguishes missing records from records out of the rules' scope, and throws accordingly. */
|
|
238
|
+
export async function explainDenied(internals, model, denied, perm) {
|
|
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')})`));
|
|
240
|
+
const found = new Set(existing.map((r) => Number(r.id)));
|
|
241
|
+
const missing = denied.filter((id) => !found.has(id));
|
|
242
|
+
if (missing.length > 0 && found.size === 0)
|
|
243
|
+
throw new MissingRecordError(model.name, missing);
|
|
244
|
+
throw new AccessError(model.name, perm, {
|
|
245
|
+
records: denied.filter((id) => found.has(id)),
|
|
246
|
+
problem: `record rules deny ${perm} on ${model.name} record(s) ${denied.filter((id) => found.has(id)).join(', ')}.`,
|
|
247
|
+
hint: 'The records exist but are outside the rules that apply to this user (RFC 0014 §7.3).',
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
/** The value bound for a stored column: encrypted fields are encrypted with the current key (RFC 0014 §7.6). */
|
|
251
|
+
export function storedValue(internals, field, value) {
|
|
252
|
+
if (!field.encrypted || value === null || value === undefined)
|
|
253
|
+
return bindValue(field, value);
|
|
254
|
+
const ring = internals.keys;
|
|
255
|
+
if (ring === undefined) {
|
|
256
|
+
throw new EncryptionError('No encryption keys are configured.', 'Pass keys: createKeyRing({ current, keys }) to createShutro() before writing encrypted fields.');
|
|
257
|
+
}
|
|
258
|
+
return encrypt(ring, String(value));
|
|
259
|
+
}
|
|
260
|
+
/** The plaintext of a loaded encrypted value. */
|
|
261
|
+
export function loadedValue(internals, field, value) {
|
|
262
|
+
if (!field.encrypted || value === null || value === undefined)
|
|
263
|
+
return value;
|
|
264
|
+
const ring = internals.keys;
|
|
265
|
+
if (ring === undefined) {
|
|
266
|
+
throw new EncryptionError('No encryption keys are configured.', 'Pass keys: createKeyRing({ current, keys }) to createShutro() to read encrypted fields.');
|
|
267
|
+
}
|
|
268
|
+
return decrypt(ring, String(value));
|
|
269
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Document numbering at runtime (RFC 0012 §7.2–7.4): range allocation per (company, period) group, in the business
|
|
3
|
+
* transaction for gapless sequences or in a short autonomous one otherwise; filling sequence fields at create time;
|
|
4
|
+
* `records.assignNumber()` for manual numbering.
|
|
5
|
+
*/
|
|
6
|
+
import { type SequenceDefinition } from '../../sequence/index.js';
|
|
7
|
+
import type { ScopeInternals } from '../env/env.js';
|
|
8
|
+
import type { Field } from '../model/field.js';
|
|
9
|
+
import type { AnyModel } from '../model/model.js';
|
|
10
|
+
import type { ComputeHost } from './compute.js';
|
|
11
|
+
/** The placeholder of a manually numbered document (RFC 0012 §7.4). */
|
|
12
|
+
export declare const UNNUMBERED = "/";
|
|
13
|
+
/** Allocates one formatted number per request, in one statement per (company, period) group. */
|
|
14
|
+
export declare function allocateNumbers(internals: ScopeInternals, definition: SequenceDefinition, requests: readonly {
|
|
15
|
+
readonly company: number | null;
|
|
16
|
+
readonly date: string;
|
|
17
|
+
}[]): Promise<string[]>;
|
|
18
|
+
/** Sequence fields of a model with their options. */
|
|
19
|
+
export declare function sequenceFields(model: AnyModel): {
|
|
20
|
+
readonly key: string;
|
|
21
|
+
readonly field: Field;
|
|
22
|
+
readonly options: NonNullable<Field['sequence']>;
|
|
23
|
+
}[];
|
|
24
|
+
/** Fills the `on: 'create'` sequence fields of rows that have no value (RFC 0012 §7.4). */
|
|
25
|
+
export declare function fillSequences(internals: ScopeInternals, model: AnyModel, rows: readonly {
|
|
26
|
+
readonly stored: Map<string, unknown>;
|
|
27
|
+
}[]): Promise<void>;
|
|
28
|
+
/** `records.assignNumber(key, { date })`: numbers unnumbered records through the unit of work. */
|
|
29
|
+
export declare function assignNumbers(host: ComputeHost, model: AnyModel, ids: readonly number[], key: string, options: {
|
|
30
|
+
readonly date?: string | undefined;
|
|
31
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Document numbering at runtime (RFC 0012 §7.2–7.4): range allocation per (company, period) group, in the business
|
|
3
|
+
* transaction for gapless sequences or in a short autonomous one otherwise; filling sequence fields at create time;
|
|
4
|
+
* `records.assignNumber()` for manual numbering.
|
|
5
|
+
*/
|
|
6
|
+
import { allocateStatement, formatNumber, numbersFrom, periodKey, SEQUENCE_TABLE, sequenceTableStatements, } from '../../sequence/index.js';
|
|
7
|
+
import { UnknownSequenceError, ValidationError } from '../errors.js';
|
|
8
|
+
import { trackChange } from './audit.js';
|
|
9
|
+
/** The placeholder of a manually numbered document (RFC 0012 §7.4). */
|
|
10
|
+
export const UNNUMBERED = '/';
|
|
11
|
+
const ensured = new WeakSet();
|
|
12
|
+
async function ensureTable(driver) {
|
|
13
|
+
if (ensured.has(driver))
|
|
14
|
+
return;
|
|
15
|
+
const [row] = await driver.query({
|
|
16
|
+
text: `SELECT to_regclass('${SEQUENCE_TABLE}') IS NOT NULL AS present`,
|
|
17
|
+
params: [],
|
|
18
|
+
});
|
|
19
|
+
if (row?.present !== true)
|
|
20
|
+
for (const statement of sequenceTableStatements())
|
|
21
|
+
await driver.query(statement);
|
|
22
|
+
ensured.add(driver);
|
|
23
|
+
}
|
|
24
|
+
function groupRequests(definition, requests) {
|
|
25
|
+
const groups = new Map();
|
|
26
|
+
requests.forEach((request, i) => {
|
|
27
|
+
const company = definition.perCompany ? (request.company ?? 0) : 0;
|
|
28
|
+
const period = periodKey(definition, request.date);
|
|
29
|
+
const key = `${company}|${period}`;
|
|
30
|
+
let group = groups.get(key);
|
|
31
|
+
if (group === undefined) {
|
|
32
|
+
group = { company, period, date: request.date, members: [] };
|
|
33
|
+
groups.set(key, group);
|
|
34
|
+
}
|
|
35
|
+
group.members.push(i);
|
|
36
|
+
});
|
|
37
|
+
return [...groups.values()];
|
|
38
|
+
}
|
|
39
|
+
/** Allocates one formatted number per request, in one statement per (company, period) group. */
|
|
40
|
+
export async function allocateNumbers(internals, definition, requests) {
|
|
41
|
+
const out = new Array(requests.length);
|
|
42
|
+
if (requests.length === 0)
|
|
43
|
+
return out;
|
|
44
|
+
await ensureTable(internals.driver);
|
|
45
|
+
for (const group of groupRequests(definition, requests)) {
|
|
46
|
+
const statement = allocateStatement(definition, group.company, group.period, group.members.length);
|
|
47
|
+
const rows = definition.gapless
|
|
48
|
+
? await internals.query(statement) // row lock held until commit: no gaps
|
|
49
|
+
: await internals.driver.transaction({ isolation: 'read committed' }, (conn) => conn.query(statement)); // committed at once: no blocking, gaps on rollback
|
|
50
|
+
const first = Number(rows[0]?.first);
|
|
51
|
+
const numbers = numbersFrom(definition, first, group.members.length);
|
|
52
|
+
group.members.forEach((index, i) => {
|
|
53
|
+
out[index] = formatNumber(definition, numbers[i], requests[index]?.date ?? group.date);
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
/** Sequence fields of a model with their options. */
|
|
59
|
+
export function sequenceFields(model) {
|
|
60
|
+
return Object.entries(model.fields)
|
|
61
|
+
.filter(([, f]) => f.sequence !== undefined)
|
|
62
|
+
.map(([key, field]) => ({
|
|
63
|
+
key,
|
|
64
|
+
field,
|
|
65
|
+
options: field.sequence,
|
|
66
|
+
}));
|
|
67
|
+
}
|
|
68
|
+
function definitionOf(internals, model, key, code) {
|
|
69
|
+
const definition = internals.registry.sequences.get(code);
|
|
70
|
+
if (definition === undefined)
|
|
71
|
+
throw new UnknownSequenceError(code, `${model.name}.${key}`);
|
|
72
|
+
return definition;
|
|
73
|
+
}
|
|
74
|
+
function companyOf(model, values, internals) {
|
|
75
|
+
if (model.companyScoped === undefined)
|
|
76
|
+
return internals.env.companyId;
|
|
77
|
+
const company = values.get('company');
|
|
78
|
+
return typeof company === 'number' ? company : null;
|
|
79
|
+
}
|
|
80
|
+
function dateOf(values, dateField, fallback) {
|
|
81
|
+
const value = dateField === undefined ? undefined : values.get(dateField);
|
|
82
|
+
if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}/.test(value))
|
|
83
|
+
return value.slice(0, 10);
|
|
84
|
+
if (value instanceof Date)
|
|
85
|
+
return value.toISOString().slice(0, 10);
|
|
86
|
+
return fallback;
|
|
87
|
+
}
|
|
88
|
+
/** Fills the `on: 'create'` sequence fields of rows that have no value (RFC 0012 §7.4). */
|
|
89
|
+
export async function fillSequences(internals, model, rows) {
|
|
90
|
+
for (const { key, options } of sequenceFields(model)) {
|
|
91
|
+
if (options.on === 'manual')
|
|
92
|
+
continue;
|
|
93
|
+
const definition = definitionOf(internals, model, key, options.code);
|
|
94
|
+
const pending = rows.filter((r) => r.stored.get(key) === null || r.stored.get(key) === undefined);
|
|
95
|
+
if (pending.length === 0)
|
|
96
|
+
continue;
|
|
97
|
+
const today = internals.env.today();
|
|
98
|
+
const numbers = await allocateNumbers(internals, definition, pending.map((r) => ({
|
|
99
|
+
company: companyOf(model, r.stored, internals),
|
|
100
|
+
date: dateOf(r.stored, options.dateField, today),
|
|
101
|
+
})));
|
|
102
|
+
pending.forEach((r, i) => {
|
|
103
|
+
r.stored.set(key, numbers[i]);
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** `records.assignNumber(key, { date })`: numbers unnumbered records through the unit of work. */
|
|
108
|
+
export async function assignNumbers(host, model, ids, key, options) {
|
|
109
|
+
const { internals } = host;
|
|
110
|
+
const field = model.fields[key];
|
|
111
|
+
if (field === undefined || field.sequence === undefined) {
|
|
112
|
+
throw new ValidationError(model.name, [key], `'${key}' is not a sequence field.`, "Declare it with f.char({ sequence: { code, on: 'manual' } }).");
|
|
113
|
+
}
|
|
114
|
+
if (ids.length === 0)
|
|
115
|
+
return;
|
|
116
|
+
const definition = definitionOf(internals, model, key, field.sequence.code);
|
|
117
|
+
const needed = new Set(['id', key]);
|
|
118
|
+
if (model.companyScoped !== undefined)
|
|
119
|
+
needed.add('company');
|
|
120
|
+
if (field.sequence.dateField !== undefined)
|
|
121
|
+
needed.add(field.sequence.dateField);
|
|
122
|
+
await host.load(model, ids, { fields: needed, relations: new Map() });
|
|
123
|
+
const numbered = ids.filter((id) => {
|
|
124
|
+
const current = host.values(model.name, id)?.get(key);
|
|
125
|
+
return current !== null && current !== undefined && current !== UNNUMBERED;
|
|
126
|
+
});
|
|
127
|
+
if (numbered.length > 0) {
|
|
128
|
+
throw new ValidationError(model.name, [key], `record(s) ${numbered.join(', ')} already have a number.`, 'A document is numbered once; assignNumber() only takes unnumbered records.');
|
|
129
|
+
}
|
|
130
|
+
const today = internals.env.today();
|
|
131
|
+
const numbers = await allocateNumbers(internals, definition, ids.map((id) => {
|
|
132
|
+
const values = host.values(model.name, id, true);
|
|
133
|
+
return {
|
|
134
|
+
company: companyOf(model, values, internals),
|
|
135
|
+
date: options.date ?? dateOf(values, field.sequence?.dateField, today),
|
|
136
|
+
};
|
|
137
|
+
}));
|
|
138
|
+
ids.forEach((id, i) => {
|
|
139
|
+
const values = host.values(model.name, id, true);
|
|
140
|
+
internals.journal({
|
|
141
|
+
kind: 'value',
|
|
142
|
+
model: model.name,
|
|
143
|
+
id,
|
|
144
|
+
key,
|
|
145
|
+
had: values.has(key),
|
|
146
|
+
prev: values.get(key),
|
|
147
|
+
wasDirty: internals.isDirty(model.name, id, key),
|
|
148
|
+
});
|
|
149
|
+
trackChange(internals, model, id, key, values.get(key), numbers[i], (k) => values.get(k));
|
|
150
|
+
values.set(key, numbers[i]);
|
|
151
|
+
internals.markDirty(model.name, id, key);
|
|
152
|
+
});
|
|
153
|
+
internals.trigger(model.name, key, ids);
|
|
154
|
+
}
|