@aria-framework/customer 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +149 -2
- package/README.md +292 -11
- package/assets/visit.js +86 -0
- package/index.js +7 -5
- package/lib/visits/index.js +28 -0
- package/lib/visits/options.js +183 -0
- package/lib/visits/record.js +76 -0
- package/lib/visits/rules.js +290 -0
- package/lib/visits/visits.js +1022 -0
- package/package.json +16 -4
- package/views/customer-visit-banner.ejs +20 -0
- package/views/customer-visit-ended.ejs +11 -0
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Part "visits" (0.2): working in one customer: the way in, the level per kind, the reason, four hours, the re-check on
|
|
3
|
+
* every request and live event, the gate in front of the app's content, the two audit rows, the banner and the ended
|
|
4
|
+
* notice, the typed-work notice.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
'use strict';
|
|
8
|
+
|
|
9
|
+
const path = require('path');
|
|
10
|
+
const rules = require('./rules');
|
|
11
|
+
const { createVisits } = require('./visits');
|
|
12
|
+
const { VISIT_ACTIONS, VISIT_ACTION_LABELS } = require('./record');
|
|
13
|
+
|
|
14
|
+
module.exports = {
|
|
15
|
+
createVisits,
|
|
16
|
+
visitRules: rules,
|
|
17
|
+
VISIT_HOURS: rules.VISIT_HOURS,
|
|
18
|
+
VISIT_MS: rules.VISIT_MS,
|
|
19
|
+
VISIT_WORDS: rules.VISIT_WORDS,
|
|
20
|
+
VISIT_ENDINGS: rules.VISIT_ENDINGS,
|
|
21
|
+
VISIT_MARKER: rules.VISIT_MARKER,
|
|
22
|
+
VISIT_ACTIONS,
|
|
23
|
+
VISIT_ACTION_LABELS,
|
|
24
|
+
/** The partials: customer-visit-banner.ejs and customer-visit-ended.ejs (add to the app's views). */
|
|
25
|
+
viewsDir: path.join(__dirname, '..', '..', 'views'),
|
|
26
|
+
/** The browser script: visit.js (the app serves it and loads it with a script tag). */
|
|
27
|
+
assetsDir: path.join(__dirname, '..', '..', 'assets')
|
|
28
|
+
};
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* createVisits' OPTIONS, checked once at construction: every required one is refused BY NAME when missing or out of
|
|
3
|
+
* shape, an unknown one is refused, and the app's lists are checked against each other (a permission in one kind and one
|
|
4
|
+
* level only; every kind has its permissions; every gated mount names a kind; every outside entry lies under a mount).
|
|
5
|
+
* Nothing here has a default that "looks right": the paths, the permission names and the lists are the app's.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
'use strict';
|
|
9
|
+
|
|
10
|
+
const { isKinds } = require('../access/kinds');
|
|
11
|
+
const R = require('./rules');
|
|
12
|
+
|
|
13
|
+
function fail(message) { throw new Error(`createVisits: ${message}`); }
|
|
14
|
+
|
|
15
|
+
const isFn = (f) => typeof f === 'function';
|
|
16
|
+
const READ = new Set(['GET', 'HEAD', 'OPTIONS']);
|
|
17
|
+
const SEG = /^[A-Za-z0-9_~-][A-Za-z0-9._~-]*$/;
|
|
18
|
+
const PARAM = /^:[A-Za-z_][A-Za-z0-9_]*$/;
|
|
19
|
+
const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
20
|
+
const PERM = /^[^\s]{1,120}$/;
|
|
21
|
+
|
|
22
|
+
/** A full mount path: "/" then literal segments (letters, digits, . _ ~ -), no trailing "/", no dot segment. */
|
|
23
|
+
function isMountPath(p) {
|
|
24
|
+
return typeof p === 'string' && p.length <= 1024 && /^(\/[A-Za-z0-9_~-][A-Za-z0-9._~-]*)+$/.test(p)
|
|
25
|
+
&& !p.split('/').some((s) => s === '.' || s === '..');
|
|
26
|
+
}
|
|
27
|
+
/** A local path this app may send the browser to (fleet view's rule): "/x" or "/x?y", never "//host", "/\host", a scheme, a space. */
|
|
28
|
+
function isLocalPath(p) {
|
|
29
|
+
return typeof p === 'string' && p.length <= 2048 && /^\/(?![/\\])/.test(p) && !/[\\\x00-\x20\x7f]/.test(p);
|
|
30
|
+
}
|
|
31
|
+
/** Is `p` the mount `m` or under it? */
|
|
32
|
+
const under = (p, m) => p === m || p.startsWith(`${m}/`);
|
|
33
|
+
|
|
34
|
+
/** One `outside` entry: "METHOD /literal/or/:name/segments" (fleet view's grammar; a read method is allowed here). */
|
|
35
|
+
function parseOutside(entry) {
|
|
36
|
+
const m = typeof entry === 'string' && entry.match(/^([A-Z]+) (\/[^ ]*)$/);
|
|
37
|
+
if (!m) fail(`outside: ${JSON.stringify(entry)} is not "METHOD /path"`);
|
|
38
|
+
const [, method, p] = m;
|
|
39
|
+
const segs = p.split('/');
|
|
40
|
+
const ok = p !== '/' && segs.slice(1).every((s) => (SEG.test(s) && s !== '.' && s !== '..') || PARAM.test(s));
|
|
41
|
+
if (!ok) fail(`outside: ${JSON.stringify(entry)}: the path must be literal segments (letters, digits, . _ ~ -) and :name segments, no query, wildcard, empty, dot or encoded segment`);
|
|
42
|
+
return Object.freeze({ entry, method, path: p, segs });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const MESSAGE_KEYS = ['outside', 'lookOnly', 'closed', 'permission', 'unlisted', 'leaveFirst', 'busy', 'signedOut', 'placeChanged', 'left',
|
|
46
|
+
'started', 'lowered', 'byGrant', 'refusal', 'invalid'];
|
|
47
|
+
const KNOWN = ['tenancy', 'db', 'accessModel', 'kinds', 'levels', 'notCapped', 'permission', 'roleCan', 'requirePermission', 'partnerById',
|
|
48
|
+
'audit', 'fleetView', 'sessionEnding', 'tellPartner', 'fitMemoMs', 'mountPath', 'mounts', 'outside', 'customerParams', 'paths',
|
|
49
|
+
'notPages', 'logger', 'now', 'flash', 'wantsJson', 'refusalView', 'messages', 'caseSensitive', 'platformOnly'];
|
|
50
|
+
// The words of the start route's refusals and invalid input (the `refusal` and `invalid` messages are objects of these).
|
|
51
|
+
const REFUSAL_KEYS = ['fleet-view', 'permission', 'not-found', 'inactive', 'closed', 'role', 'waiting', 'not-allowed'];
|
|
52
|
+
const INVALID_KEYS = ['reason', 'reason-long', 'level'];
|
|
53
|
+
const isText = (v) => (typeof v === 'string' && v.length > 0) || isFn(v);
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Check every option; → the configuration createVisits runs on (frozen lists, the permission index, parsed entries).
|
|
57
|
+
*/
|
|
58
|
+
function checkOptions(options) {
|
|
59
|
+
const o = options;
|
|
60
|
+
if (!o || typeof o !== 'object' || Array.isArray(o)) fail('pass the options object (see the README, "Visits")');
|
|
61
|
+
for (const k of Object.keys(o)) if (!KNOWN.includes(k)) fail(`unknown option "${k}"`);
|
|
62
|
+
|
|
63
|
+
const t = o.tenancy;
|
|
64
|
+
if (!t || !['asCustomer', 'asPartner', 'contextFor', 'runWithTenant'].every((f) => isFn(t[f]))) {
|
|
65
|
+
fail('tenancy is required: what @aria-framework/tenancy createTenancy returned (asCustomer, asPartner, contextFor, runWithTenant)');
|
|
66
|
+
}
|
|
67
|
+
if (!o.db || !isFn(o.db.invoke)) fail('db is required: the app\'s db client, built with { customerPin: true }');
|
|
68
|
+
if (typeof o.accessModel !== 'string' || !NAME.test(o.accessModel)) fail('accessModel is required: the model name the app registered createAccessStore under');
|
|
69
|
+
if (!isKinds(o.kinds)) fail('kinds is required: what defineKinds() returned');
|
|
70
|
+
const kinds = o.kinds.keys;
|
|
71
|
+
|
|
72
|
+
const lv = o.levels;
|
|
73
|
+
if (!lv || typeof lv !== 'object' || Array.isArray(lv)) fail('levels is required: { [kind]: { look: [permission], change: [permission] } }');
|
|
74
|
+
for (const k of Object.keys(lv)) if (!kinds.includes(k)) fail(`levels names "${k}", which is not one of the kinds (${kinds.join(', ')})`);
|
|
75
|
+
const levels = {};
|
|
76
|
+
for (const k of kinds) {
|
|
77
|
+
const e = lv[k];
|
|
78
|
+
if (!e || typeof e !== 'object' || Array.isArray(e) || Object.keys(e).some((x) => x !== 'look' && x !== 'change')) {
|
|
79
|
+
fail(`levels.${k} is required: { look: [permission, ...], change: [permission, ...] }`);
|
|
80
|
+
}
|
|
81
|
+
if (!Array.isArray(e.look) || e.look.length === 0) fail(`levels.${k}.look must list at least one permission (what lets a role look at ${k})`);
|
|
82
|
+
if (!Array.isArray(e.change)) fail(`levels.${k}.change must be a list of permissions (it may be empty)`);
|
|
83
|
+
for (const p of [...e.look, ...e.change]) if (typeof p !== 'string' || !PERM.test(p)) fail(`levels.${k}: ${JSON.stringify(p)} is not a permission name`);
|
|
84
|
+
levels[k] = Object.freeze({ look: Object.freeze([...e.look]), change: Object.freeze([...e.change]) });
|
|
85
|
+
}
|
|
86
|
+
const index = R.permissionIndex(levels); // throws on a permission named twice
|
|
87
|
+
if (!Array.isArray(o.notCapped)) fail('notCapped is required: the permissions a visit leaves to the role alone ([] for none)');
|
|
88
|
+
for (const p of o.notCapped) {
|
|
89
|
+
if (typeof p !== 'string' || !PERM.test(p)) fail(`notCapped: ${JSON.stringify(p)} is not a permission name`);
|
|
90
|
+
if (index.has(p)) fail(`notCapped: "${p}" is in levels (a permission is either a kind's or not capped)`);
|
|
91
|
+
}
|
|
92
|
+
if (typeof o.permission !== 'string' || !PERM.test(o.permission)) fail('permission is required: the name of the app\'s work-in permission');
|
|
93
|
+
if (index.has(o.permission)) fail(`permission "${o.permission}" is in levels: the work-in permission is not a kind's`);
|
|
94
|
+
|
|
95
|
+
for (const k of ['roleCan', 'requirePermission', 'partnerById', 'audit', 'sessionEnding', 'tellPartner']) {
|
|
96
|
+
if (!isFn(o[k])) fail(`${k} is required (a function; see the README, "Visits")`);
|
|
97
|
+
}
|
|
98
|
+
if (o.fleetView !== null && (!o.fleetView || typeof o.fleetView !== 'object' || !isLocalPath(o.fleetView.startPath) || !isFn(o.fleetView.isOn)
|
|
99
|
+
|| !isFn(o.fleetView.addStartCheck) || !isFn(o.fleetView.inRow) || !isFn(o.fleetView.classify))) {
|
|
100
|
+
fail('fleetView is required: what createFleetView of @aria-framework/tenancy 0.5.0 or later returned (with addStartCheck and inRow), or null for an app without fleet view');
|
|
101
|
+
}
|
|
102
|
+
if (!(Number.isInteger(o.fitMemoMs) && o.fitMemoMs >= 0 && o.fitMemoMs <= 5000)) fail('fitMemoMs is required: a whole number of milliseconds, 0 to 5000 (CD-22 allows five seconds)');
|
|
103
|
+
if (!isMountPath(o.mountPath)) fail('mountPath is required: the full path of the Customers pages the visit routes sit under ("/x"), literal segments, no trailing slash');
|
|
104
|
+
// CD-21 (review round 3): Leave needs only a session; fleet view's read-only guard runs before every router, so its
|
|
105
|
+
// readOnlyExcept must let Leave through (read through fleet view's own classify, the guard's question)
|
|
106
|
+
if (o.fleetView && o.fleetView.classify('POST', `${o.mountPath}/leave`) === 'refused') {
|
|
107
|
+
fail(`fleetView: its readOnlyExcept must list "POST ${o.mountPath}/leave" (CD-21: Leave is never refused, not even by fleet view's read-only guard)`);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (!Array.isArray(o.mounts) || o.mounts.length === 0) fail('mounts is required: [{ path, kind }], every gated mount with its kind (full paths)');
|
|
111
|
+
const mounts = o.mounts.map((m, i) => {
|
|
112
|
+
if (!m || typeof m !== 'object' || !isMountPath(m.path)) fail(`mounts[${i}]: path must be a full mount path ("/x")`);
|
|
113
|
+
if (!kinds.includes(m.kind)) fail(`mounts[${i}] (${m.path}): kind ${JSON.stringify(m.kind)} is not one of the kinds (${kinds.join(', ')})`);
|
|
114
|
+
if (Object.keys(m).some((k) => k !== 'path' && k !== 'kind')) fail(`mounts[${i}]: only { path, kind }`);
|
|
115
|
+
return Object.freeze({ path: m.path, kind: m.kind });
|
|
116
|
+
});
|
|
117
|
+
for (const a of mounts) {
|
|
118
|
+
for (const b of mounts) if (a !== b && under(b.path, a.path)) fail(`mounts: ${b.path} is ${a.path === b.path ? 'listed twice' : `under ${a.path}`} (one mount, one kind)`);
|
|
119
|
+
if (under(o.mountPath, a.path) || under(a.path, o.mountPath)) fail(`mounts: ${a.path} and mountPath ${o.mountPath} overlap (the visit routes are never gated)`);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
if (!Array.isArray(o.outside)) fail('outside is required: the "METHOD /path" requests a gated mount serves outside a visit ([] for none)');
|
|
123
|
+
const outside = o.outside.map(parseOutside);
|
|
124
|
+
for (const e of outside) {
|
|
125
|
+
if (!mounts.some((m) => under(e.path, m.path))) fail(`outside: ${e.entry} is under no gated mount`);
|
|
126
|
+
if (READ.has(e.method) && e.method !== 'GET') fail(`outside: ${e.entry}: list GET (it also lets HEAD through)`);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const cp = o.customerParams;
|
|
130
|
+
if (!cp || typeof cp !== 'object' || !Array.isArray(cp.query) || !Array.isArray(cp.body) || Object.keys(cp).some((k) => k !== 'query' && k !== 'body')) {
|
|
131
|
+
fail('customerParams is required: { query: [name], body: [name] }, the parameters naming a customer that a visit rewrites to its own (CD-25)');
|
|
132
|
+
}
|
|
133
|
+
for (const n of [...cp.query, ...cp.body]) if (typeof n !== 'string' || !NAME.test(n)) fail(`customerParams: ${JSON.stringify(n)} is not a parameter name`);
|
|
134
|
+
|
|
135
|
+
const p = o.paths;
|
|
136
|
+
if (!p || typeof p !== 'object' || !isLocalPath(p.customers) || !isFn(p.customer) || !isFn(p.landing)) {
|
|
137
|
+
fail('paths is required: { customers: "/x", customer(id) => path, landing(visit) => path }, local paths');
|
|
138
|
+
}
|
|
139
|
+
if (!Array.isArray(o.notPages) || !o.notPages.every((r) => r instanceof RegExp)) fail('notPages is required: RegExps of the full paths under a mount that are not pages (files, fragments) ([] for none)');
|
|
140
|
+
if (!o.logger || !isFn(o.logger.warn) || !isFn(o.logger.error)) fail('logger is required (warn and error)');
|
|
141
|
+
|
|
142
|
+
if (o.now != null && !isFn(o.now)) fail('now must be a function () => milliseconds');
|
|
143
|
+
if (o.flash != null && !isFn(o.flash)) fail('flash must be a function (req, res, kind, text), which may return a promise');
|
|
144
|
+
if (o.wantsJson != null && !isFn(o.wantsJson)) fail('wantsJson must be a function (req) => boolean');
|
|
145
|
+
if (o.refusalView != null && (typeof o.refusalView !== 'string' || !o.refusalView)) fail('refusalView must be a view name');
|
|
146
|
+
if (o.messages != null) {
|
|
147
|
+
if (typeof o.messages !== 'object' || Array.isArray(o.messages)) fail('messages must be an object');
|
|
148
|
+
for (const [k, v] of Object.entries(o.messages)) {
|
|
149
|
+
if (!MESSAGE_KEYS.includes(k)) fail(`messages: unknown message "${k}" (known: ${MESSAGE_KEYS.join(', ')})`);
|
|
150
|
+
if (k === 'refusal' || k === 'invalid') {
|
|
151
|
+
const known = k === 'refusal' ? REFUSAL_KEYS : INVALID_KEYS;
|
|
152
|
+
if (!v || typeof v !== 'object' || Array.isArray(v)) fail(`messages.${k} must be an object of { ${known.join(', ')} }`);
|
|
153
|
+
for (const [kk, vv] of Object.entries(v)) {
|
|
154
|
+
if (!known.includes(kk)) fail(`messages.${k}: unknown "${kk}" (known: ${known.join(', ')})`);
|
|
155
|
+
if (!isText(vv)) fail(`messages.${k}.${kk} must be a sentence (a non-empty string) or a function returning one`);
|
|
156
|
+
}
|
|
157
|
+
} else if (!isText(v)) fail(`messages.${k} must be a sentence (a non-empty string) or a function returning one`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
if (o.caseSensitive != null && typeof o.caseSensitive !== 'boolean') fail('caseSensitive must be true or false (Express\'s "case sensitive routing"; default false, as Express\'s)');
|
|
161
|
+
if (o.platformOnly != null) {
|
|
162
|
+
if (!Array.isArray(o.platformOnly) || !o.platformOnly.every((x) => typeof x === 'string')) fail('platformOnly must be a list of permission names (the app\'s platform-only permissions)');
|
|
163
|
+
// a person's role is judged at partner scope (at their home partner): a platform-only permission is never held there
|
|
164
|
+
const named = [o.permission, ...index.keys(), ...o.notCapped].filter((x) => o.platformOnly.includes(x));
|
|
165
|
+
if (named.length) fail(`platformOnly: ${named.join(', ')} ${named.length === 1 ? 'is' : 'are'} named in permission, levels or notCapped; a role is judged at partner scope, where a platform-only permission is never held`);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
return Object.freeze({
|
|
169
|
+
...o,
|
|
170
|
+
caseSensitive: o.caseSensitive === true,
|
|
171
|
+
kindKeys: Object.freeze([...kinds]),
|
|
172
|
+
levels: Object.freeze(levels),
|
|
173
|
+
index,
|
|
174
|
+
notCapped: new Set(o.notCapped),
|
|
175
|
+
mounts: Object.freeze(mounts),
|
|
176
|
+
outside: Object.freeze(outside),
|
|
177
|
+
customerParams: Object.freeze({ query: Object.freeze([...cp.query]), body: Object.freeze([...cp.body]) }),
|
|
178
|
+
notPages: Object.freeze([...o.notPages]),
|
|
179
|
+
now: o.now || Date.now
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
module.exports = { checkOptions, isLocalPath, isMountPath, under, MESSAGE_KEYS };
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A VISIT IS TWO ROWS OF THE APP'S OWN AUDIT TRAIL (CD-44, CD-45): a start and a stop, under the person's own name, in
|
|
3
|
+
* the trail of the partner the visit was made under (the house person who came in as a partner: that partner's trail).
|
|
4
|
+
* There is no separate log. The names are the first customer-driven app's, so its rows read the same after it moves
|
|
5
|
+
* onto this package. Both rows carry the visit's id, which pairs them; every other row written during the visit is
|
|
6
|
+
* stamped by the app's audit helper with `stampOf(req)` (`working_in`, `visit`).
|
|
7
|
+
*
|
|
8
|
+
* start customer, visit, reason (or managed: true), levels (per kind), level (the highest), until, company (the
|
|
9
|
+
* person's home partner), let_in per kind (setting | grant), grant and let_in_by when a kind is let in by the
|
|
10
|
+
* customer's grant, asked when some kind's level is lower than what was asked
|
|
11
|
+
* stop customer, visit, levels, level, ended (left | expired | signed_out | refused), because (refused only),
|
|
12
|
+
* minutes, started_at
|
|
13
|
+
*
|
|
14
|
+
* Version 2 of the model has no helper tier (Platform D-0013): neither row carries one. Both rows carry
|
|
15
|
+
* `acting_as_partner: <partner>` when the visit was MADE working in that partner (the record's `acting`), whatever the
|
|
16
|
+
* session says when the row is written (review round 1); the app's helper, given the request as the visit was made
|
|
17
|
+
* (visits.js asTheVisit), stamps the same.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
'use strict';
|
|
21
|
+
|
|
22
|
+
const R = require('./rules');
|
|
23
|
+
const A = require('../access/rules');
|
|
24
|
+
|
|
25
|
+
const VISIT_ACTIONS = Object.freeze({ start: 'customer.work_in_start', stop: 'customer.work_in_stop' });
|
|
26
|
+
const VISIT_ACTION_LABELS = Object.freeze({
|
|
27
|
+
[VISIT_ACTIONS.start]: 'Started working in a customer',
|
|
28
|
+
[VISIT_ACTIONS.stop]: 'Stopped working in a customer'
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
const iso = (ms) => (Number.isFinite(ms) ? new Date(ms).toISOString() : null);
|
|
32
|
+
|
|
33
|
+
/** The start row's detail. `letIn` and `grant` from rules.entryLevels; `company` the home partner's name. */
|
|
34
|
+
function startDetail(rec, { letIn, grant, company }) {
|
|
35
|
+
const d = { customer: rec.customerId, visit: rec.id };
|
|
36
|
+
if (rec.managed) d.managed = true; else d.reason = rec.reason;
|
|
37
|
+
d.levels = { ...rec.levels };
|
|
38
|
+
d.level = R.levelOf(rec.levels);
|
|
39
|
+
d.until = iso(rec.until);
|
|
40
|
+
d.company = company == null ? null : String(company).slice(0, 200);
|
|
41
|
+
d.let_in = { ...letIn };
|
|
42
|
+
if (Object.values(letIn).includes('grant') && grant) {
|
|
43
|
+
d.grant = Number(grant.id);
|
|
44
|
+
d.let_in_by = grant.given_by_name || null;
|
|
45
|
+
}
|
|
46
|
+
if (Object.values(rec.levels).some((l) => R.LEVELS.includes(l) && A.rank(l) < A.rank(rec.asked))) d.asked = rec.asked;
|
|
47
|
+
if (rec.acting === true) d.acting_as_partner = rec.partnerId;
|
|
48
|
+
return d;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The stop row's detail. `rec` may be a record out of shape (ended `refused` because `record`): every value is taken
|
|
53
|
+
* only when it has its shape, else null.
|
|
54
|
+
*/
|
|
55
|
+
function stopDetail(rec, ended, because, nowMs) {
|
|
56
|
+
const r = rec && typeof rec === 'object' ? rec : {};
|
|
57
|
+
const levels = r.levels && typeof r.levels === 'object' && !Array.isArray(r.levels)
|
|
58
|
+
? Object.fromEntries(Object.entries(r.levels).filter(([, l]) => l === null || R.LEVELS.includes(l))) : null;
|
|
59
|
+
const d = {
|
|
60
|
+
customer: typeof r.customerId === 'string' && R.CUSTOMER_ID.test(r.customerId) ? r.customerId : null,
|
|
61
|
+
visit: typeof r.id === 'string' && R.VISIT_ID.test(r.id) ? r.id : null,
|
|
62
|
+
levels,
|
|
63
|
+
level: levels ? R.levelOf(levels) : null,
|
|
64
|
+
ended,
|
|
65
|
+
minutes: Number.isFinite(r.startedAt) ? R.minutesOf(r, nowMs) : null,
|
|
66
|
+
started_at: iso(r.startedAt)
|
|
67
|
+
};
|
|
68
|
+
if (ended === 'refused') d.because = because || null;
|
|
69
|
+
if (r.acting === true && Number.isSafeInteger(r.partnerId) && r.partnerId > 0) d.acting_as_partner = r.partnerId;
|
|
70
|
+
return d;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** What the app's audit helper adds to a row written inside a visit (CD-45). */
|
|
74
|
+
const stampFor = (facts) => (facts ? { working_in: facts.customerId, visit: facts.id } : null);
|
|
75
|
+
|
|
76
|
+
module.exports = { VISIT_ACTIONS, VISIT_ACTION_LABELS, startDetail, stopDetail, stampFor };
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WORKING IN A CUSTOMER: THE RULES (pure: no database, no session store, no clock of their own).
|
|
3
|
+
*
|
|
4
|
+
* A staff member steps into ONE customer (a visit): the request runs pinned to that customer, at a level per kind of
|
|
5
|
+
* data, for a reason, for at most four hours, re-checked on every request ("Customer-driven apps" v7, CD-14 to CD-25).
|
|
6
|
+
* These functions decide each part from facts the caller hands them; createVisits (visits.js) reads the facts.
|
|
7
|
+
*
|
|
8
|
+
* THE RECORD session[VISIT_KEY] = { id, userId, homePartnerId, partnerId, acting, customerId, customerName,
|
|
9
|
+
* levels, asked, reason, managed, startedAt, until }: ids and facts, never a permission. A record with
|
|
10
|
+
* any other key, or a value out of shape, is over (`refused`, because `record`).
|
|
11
|
+
* THE LEVEL per kind: the lowest of what was asked, what the customer allows the partner for that kind now (its
|
|
12
|
+
* setting or a live grant: the access part's `allowance`), and the most the person's role allows for
|
|
13
|
+
* that kind, the role judged at the person's HOME partner (CD-17, CD-19). A kind's level depends only on
|
|
14
|
+
* that kind's answer and that kind's role maximum. The visit exists while at least one kind has one.
|
|
15
|
+
* FOUR HOURS until = the sooner of startedAt + VISIT_MS and the end of the grant that lets a kind in, when one does
|
|
16
|
+
* (a kind is let in by the grant when its setting alone would not give the visit's level for it).
|
|
17
|
+
* VISIT_WORDS is the only text of that length (CD-16).
|
|
18
|
+
* THE REASON required, trimmed, at most REASON_MAX; blank only at a customer whose managed mark is in force, and
|
|
19
|
+
* only for the partner's own staff: a person who came in as the partner (acting) always gives one (CD-15).
|
|
20
|
+
* THE FIT on every request: the customer active, at least one kind still open (the allowance and the role's most
|
|
21
|
+
* each at least the visit's level for it), and a reason-less visit's managed mark still in force (CD-22).
|
|
22
|
+
* THE CAP a permission of a kind is the visit's only when that kind is open, a change permission only at make
|
|
23
|
+
* changes; a permission in no kind is refused unless the app lists it as not capped (CD-17, CD-18).
|
|
24
|
+
*
|
|
25
|
+
* No permission name, route prefix or app word lives here.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
'use strict';
|
|
29
|
+
|
|
30
|
+
const A = require('../access/rules');
|
|
31
|
+
|
|
32
|
+
/** Owner, 27 Nov 2026: a visit lasts at most four hours. Every text of that length reads VISIT_WORDS (CD-16). */
|
|
33
|
+
const VISIT_HOURS = 4;
|
|
34
|
+
const VISIT_MS = VISIT_HOURS * 3600000;
|
|
35
|
+
const VISIT_WORDS = `${VISIT_HOURS} hour${VISIT_HOURS === 1 ? '' : 's'}`;
|
|
36
|
+
/** How a visit ended (CD-23). */
|
|
37
|
+
const VISIT_ENDINGS = Object.freeze(['left', 'expired', 'signed_out', 'refused']);
|
|
38
|
+
/**
|
|
39
|
+
* Why a visit ended `refused`, on its stop row (`busy`: its start lost to another start, its start row paired;
|
|
40
|
+
* `fleet-view`: the session carried fleet view beside it, CD-60).
|
|
41
|
+
*/
|
|
42
|
+
const VISIT_BECAUSE = Object.freeze(['record', 'user', 'acting', 'partner', 'role', 'setting', 'error', 'busy', 'fleet-view']);
|
|
43
|
+
/** The header every refusal of the visits part carries, and the status route's answer (CD-23). */
|
|
44
|
+
const VISIT_MARKER = 'X-Work-In';
|
|
45
|
+
/** The one session key a visit lives in. */
|
|
46
|
+
const VISIT_KEY = 'customerVisit';
|
|
47
|
+
const REASON_MAX = A.REASON_MAX;
|
|
48
|
+
const LEVELS = A.LEVELS;
|
|
49
|
+
const LEVEL_WORDS = A.LEVEL_WORDS;
|
|
50
|
+
/** A visit's own id: 16 hex, on its start and stop rows, so the reader pairs them. */
|
|
51
|
+
const VISIT_ID = /^[0-9a-f]{16}$/;
|
|
52
|
+
/** db-worker's customer pin id shape. */
|
|
53
|
+
const CUSTOMER_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
54
|
+
const RECORD_KEYS = Object.freeze(['id', 'userId', 'homePartnerId', 'partnerId', 'acting', 'customerId', 'customerName', 'levels',
|
|
55
|
+
'asked', 'reason', 'managed', 'startedAt', 'until']);
|
|
56
|
+
|
|
57
|
+
const isLevel = (l) => LEVELS.includes(l);
|
|
58
|
+
const posInt = (v) => Number.isSafeInteger(v) && v > 0;
|
|
59
|
+
const has = (o, k) => o != null && Object.prototype.hasOwnProperty.call(o, k);
|
|
60
|
+
|
|
61
|
+
/** A reason as stored: trimmed, inner whitespace one space; '' for anything that is not a string. */
|
|
62
|
+
function cleanReason(raw) {
|
|
63
|
+
return typeof raw === 'string' ? raw.trim().replace(/\s+/g, ' ') : '';
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** MAY THE REASON BE BLANK: the managed mark in force AND the partner's own staff (not acting) (CD-15, D-0013). */
|
|
67
|
+
const reasonMayBeBlank = ({ managedInForce, acting }) => managedInForce === true && acting === false;
|
|
68
|
+
|
|
69
|
+
/** What is wrong with a CLEANED reason: 'reason' (blank where one is required), 'reason-long', or null. */
|
|
70
|
+
function reasonProblem(reason, mayBeBlank) {
|
|
71
|
+
if (typeof reason !== 'string') return 'reason';
|
|
72
|
+
if (reason.length > REASON_MAX) return 'reason-long';
|
|
73
|
+
if (!reason && mayBeBlank !== true) return 'reason';
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* THE MOST A ROLE ALLOWS IN ONE KIND: 'change' when it holds any of the kind's change permissions, 'look' when it holds
|
|
79
|
+
* any of its look permissions, else null. `table` { look: [perm], change: [perm] }; `holds(perm)` the role's answer
|
|
80
|
+
* (only `true` counts), which the caller asks at the person's HOME partner.
|
|
81
|
+
*/
|
|
82
|
+
function roleMaxOf(table, holds) {
|
|
83
|
+
if (!table || typeof holds !== 'function') return null;
|
|
84
|
+
if ((table.change || []).some((p) => holds(p) === true)) return 'change';
|
|
85
|
+
if ((table.look || []).some((p) => holds(p) === true)) return 'look';
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The highest level among a visit's kinds (the banner's and the rows' `level`), or null. */
|
|
90
|
+
function levelOf(levels) {
|
|
91
|
+
let out = null;
|
|
92
|
+
for (const l of Object.values(levels || {})) if (isLevel(l) && (out === null || A.rank(l) > A.rank(out))) out = l;
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* WHAT EACH KIND OFFERS this person before they choose (the form's levels): the lower of the customer's allowance and
|
|
98
|
+
* the role's most, per kind. `answers` decide().kinds; `roleMax` { [kind]: level|null }.
|
|
99
|
+
*/
|
|
100
|
+
function offeredLevels(kinds, answers, roleMax) {
|
|
101
|
+
const out = {};
|
|
102
|
+
for (const k of kinds) {
|
|
103
|
+
const a = answers && answers[k] && answers[k].allowance;
|
|
104
|
+
out[k] = A.lower(a ? a.level : null, roleMax ? roleMax[k] : null) || null;
|
|
105
|
+
}
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* THE VISIT'S LEVEL PER KIND (CD-17): lower(asked, the kind's allowance, the role's most for the kind). Each kind's
|
|
111
|
+
* level depends on that kind's answer and that kind's role maximum only.
|
|
112
|
+
* → { levels: { [kind]: level|null }, letIn: { [kind]: 'setting'|'grant' } for the kinds with a level, grant: the grant
|
|
113
|
+
* row when it lets a kind in (else null), grantUntil: that grant's end in ms (null: none, or no end) }
|
|
114
|
+
*/
|
|
115
|
+
function entryLevels({ asked, kinds, answers, roleMax }) {
|
|
116
|
+
const levels = {};
|
|
117
|
+
const letIn = {};
|
|
118
|
+
let grant = null;
|
|
119
|
+
let grantUntil = null;
|
|
120
|
+
for (const k of kinds) {
|
|
121
|
+
const ans = answers && answers[k];
|
|
122
|
+
const a = ans && ans.allowance;
|
|
123
|
+
const lv = A.lower(A.lower(asked, a ? a.level : null), roleMax ? roleMax[k] : null) || null;
|
|
124
|
+
levels[k] = lv;
|
|
125
|
+
if (!lv) continue;
|
|
126
|
+
const s = ans.setting;
|
|
127
|
+
const bySetting = s && s.mode === 'open' && isLevel(s.level) ? s.level : null;
|
|
128
|
+
if (bySetting && A.rank(bySetting) >= A.rank(lv)) { letIn[k] = 'setting'; continue; }
|
|
129
|
+
// the setting alone does not give this level: the allowance came from the live grant (allowance's basis 'grant')
|
|
130
|
+
letIn[k] = 'grant';
|
|
131
|
+
grant = a.grant || grant;
|
|
132
|
+
if (a.until != null) grantUntil = grantUntil == null ? a.until : Math.min(grantUntil, a.until);
|
|
133
|
+
}
|
|
134
|
+
return { levels, letIn, grant, grantUntil };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** THE VISIT'S END: the sooner of four hours and the end of the grant that lets a kind in (CD-16). */
|
|
138
|
+
function untilOf(startedAt, grantUntil) {
|
|
139
|
+
if (!Number.isFinite(startedAt)) throw new Error('visits: untilOf needs the start (ms)');
|
|
140
|
+
const four = startedAt + VISIT_MS;
|
|
141
|
+
return grantUntil == null || !Number.isFinite(grantUntil) ? four : Math.min(four, grantUntil);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Is `r` a visit record of exactly this shape, for this app's kinds? */
|
|
145
|
+
function recordOk(r, kinds) {
|
|
146
|
+
if (!r || typeof r !== 'object' || Array.isArray(r)) return false;
|
|
147
|
+
const keys = Object.keys(r);
|
|
148
|
+
if (keys.length !== RECORD_KEYS.length || !RECORD_KEYS.every((k) => has(r, k))) return false;
|
|
149
|
+
if (typeof r.id !== 'string' || !VISIT_ID.test(r.id)) return false;
|
|
150
|
+
if (!posInt(r.userId) || !posInt(r.homePartnerId) || !posInt(r.partnerId) || typeof r.acting !== 'boolean') return false;
|
|
151
|
+
if (r.acting !== (r.partnerId !== r.homePartnerId)) return false;
|
|
152
|
+
if (typeof r.customerId !== 'string' || !CUSTOMER_ID.test(r.customerId)) return false;
|
|
153
|
+
if (typeof r.customerName !== 'string' || !r.customerName || r.customerName.length > 200) return false;
|
|
154
|
+
const lv = r.levels;
|
|
155
|
+
if (!lv || typeof lv !== 'object' || Array.isArray(lv)) return false;
|
|
156
|
+
const lk = Object.keys(lv);
|
|
157
|
+
if (lk.length !== kinds.length || !kinds.every((k) => has(lv, k) && (lv[k] === null || isLevel(lv[k])))) return false;
|
|
158
|
+
if (!levelOf(lv)) return false;
|
|
159
|
+
if (!isLevel(r.asked)) return false;
|
|
160
|
+
if (typeof r.reason !== 'string' || r.reason !== cleanReason(r.reason) || r.reason.length > REASON_MAX) return false;
|
|
161
|
+
if (typeof r.managed !== 'boolean' || r.managed !== (r.reason === '')) return false;
|
|
162
|
+
if (r.acting && r.managed) return false;
|
|
163
|
+
if (!Number.isFinite(r.startedAt) || !Number.isFinite(r.until) || !(r.until > r.startedAt) || r.until - r.startedAt > VISIT_MS) return false;
|
|
164
|
+
return true;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* THE SESSION'S VISIT, judged by the record and the clock alone: `{}` (none), `{ live }`, or `{ over, why, because }`:
|
|
169
|
+
* `refused` because `record` (out of shape), `expired` (at or past `until`), `refused` because `user` (another user,
|
|
170
|
+
* or the user's home partner changed). `kinds` the app's kind keys.
|
|
171
|
+
*/
|
|
172
|
+
function examine(session, nowMs, kinds) {
|
|
173
|
+
const rec = session ? session[VISIT_KEY] : undefined;
|
|
174
|
+
if (rec == null) return {};
|
|
175
|
+
if (!recordOk(rec, kinds)) return { over: rec, why: 'refused', because: 'record' };
|
|
176
|
+
if (!(nowMs < rec.until)) return { over: rec, why: 'expired', because: null };
|
|
177
|
+
const u = session.user;
|
|
178
|
+
if (!u || Number(u.id) !== rec.userId || Number(u.partner_id) !== rec.homePartnerId) return { over: rec, why: 'refused', because: 'user' };
|
|
179
|
+
return { live: rec };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Is this request's scope working in a partner? (a partner scope that is not the user's own partner) */
|
|
183
|
+
const actingIn = (ctx, user) => !!ctx && ctx.scope === 'partner' && Number(ctx.partnerId) !== Number(user && user.partner_id);
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* DOES THE REQUEST STILL STAND WHERE THE VISIT WAS MADE: the partner in force and whether the person is working in a
|
|
187
|
+
* partner, against the record. → null, 'acting' (started or stopped working in a partner since), 'partner' (another).
|
|
188
|
+
*/
|
|
189
|
+
function placeProblem(rec, ctx, user) {
|
|
190
|
+
if (!ctx || ctx.partnerId == null) return 'partner';
|
|
191
|
+
if (actingIn(ctx, user) !== rec.acting) return 'acting';
|
|
192
|
+
if (Number(ctx.partnerId) !== rec.partnerId) return 'partner';
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* DOES THE VISIT STILL FIT (CD-22). `decision` the access store's decide() read under the visit's pin now (null: the
|
|
198
|
+
* customer is not this partner's any more); `roleMax` { [kind]: level|null }, the role's most at HOME now.
|
|
199
|
+
* → { ok, open: { [kind]: boolean }, because: null | 'setting' | 'role' }. A kind is open when the customer's allowance
|
|
200
|
+
* and the role's most are each at least the visit's level for it. Not ok: every kind closed in `open`.
|
|
201
|
+
*/
|
|
202
|
+
function fitOf(rec, decision, roleMax) {
|
|
203
|
+
const closed = Object.fromEntries(Object.keys(rec.levels).map((k) => [k, false]));
|
|
204
|
+
const no = (because) => ({ ok: false, open: closed, because });
|
|
205
|
+
if (!decision || !decision.customer || decision.customer.status !== 'active') return no('setting');
|
|
206
|
+
if (rec.managed && decision.managedInForce !== true) return no('setting');
|
|
207
|
+
const open = { ...closed };
|
|
208
|
+
let customerSide = false;
|
|
209
|
+
let any = false;
|
|
210
|
+
for (const [k, lv] of Object.entries(rec.levels)) {
|
|
211
|
+
if (!lv) continue;
|
|
212
|
+
const ans = decision.kinds && decision.kinds[k];
|
|
213
|
+
const allowed = ans && ans.allowance ? ans.allowance.level : null;
|
|
214
|
+
const c = isLevel(allowed) && A.rank(allowed) >= A.rank(lv);
|
|
215
|
+
const r = !!roleMax && isLevel(roleMax[k]) && A.rank(roleMax[k]) >= A.rank(lv);
|
|
216
|
+
if (c) customerSide = true;
|
|
217
|
+
open[k] = c && r;
|
|
218
|
+
if (open[k]) any = true;
|
|
219
|
+
}
|
|
220
|
+
if (!any) return no(customerSide ? 'role' : 'setting');
|
|
221
|
+
return { ok: true, open, because: null };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* WHAT THE VISIT'S CAP SAYS OF ONE PERMISSION, before the role (CD-17, CD-18): 'yes' (the role decides), or why not:
|
|
226
|
+
* 'unlisted' (in no kind and not listed as not capped), 'closed' (its kind is not open, or has no level), 'look-only'
|
|
227
|
+
* (a change permission under look only). `index` permissionIndex(levels); `notCapped` a Set.
|
|
228
|
+
*/
|
|
229
|
+
function capOf(perm, { index, notCapped, levels, open }) {
|
|
230
|
+
const e = index.get(perm);
|
|
231
|
+
if (!e) return notCapped.has(perm) ? 'yes' : 'unlisted';
|
|
232
|
+
if (!open || open[e.kind] !== true || !levels[e.kind]) return 'closed';
|
|
233
|
+
if (e.level === 'change' && levels[e.kind] !== 'change') return 'look-only';
|
|
234
|
+
return 'yes';
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** The app's `levels` as a lookup: perm → { kind, level }. A permission named twice is refused. */
|
|
238
|
+
function permissionIndex(levels) {
|
|
239
|
+
const out = new Map();
|
|
240
|
+
for (const [kind, t] of Object.entries(levels)) {
|
|
241
|
+
for (const level of LEVELS) {
|
|
242
|
+
for (const p of t[level]) {
|
|
243
|
+
if (out.has(p)) throw new Error(`visits: the permission "${p}" is named twice in levels (${out.get(p).kind}.${out.get(p).level} and ${kind}.${level}); a permission belongs to one kind and one level`);
|
|
244
|
+
out.set(p, Object.freeze({ kind, level }));
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
return out;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* MAY THIS PERSON START A VISIT HERE (the way in). → null, or why not, in this order:
|
|
253
|
+
* 'fleet-view' fleet view is on (CD-60)
|
|
254
|
+
* 'permission' the HOME role lacks the app's work-in permission
|
|
255
|
+
* 'not-found' the customer is not the partner's in force (decision null; a house person not working in the
|
|
256
|
+
* customer's partner reads it under the house's own pin, where it is not)
|
|
257
|
+
* 'inactive' the customer is not active
|
|
258
|
+
* 'closed' every kind is Never (CD-35)
|
|
259
|
+
* 'role' the customer lets the partner into some kind, and the role (at home) gives no level in any of them
|
|
260
|
+
* 'waiting' nothing is offered and the person's request to come in is waiting
|
|
261
|
+
* 'not-allowed' nothing is offered: ask to come in
|
|
262
|
+
*/
|
|
263
|
+
function refusal({ fleetViewOn, mayWorkIn, decision, offered, nowMs }) {
|
|
264
|
+
if (fleetViewOn) return 'fleet-view';
|
|
265
|
+
if (!mayWorkIn) return 'permission';
|
|
266
|
+
if (!decision || !decision.customer) return 'not-found';
|
|
267
|
+
if (decision.customer.status !== 'active') return 'inactive';
|
|
268
|
+
if (decision.closed) return 'closed';
|
|
269
|
+
if (Object.values(offered || {}).some((l) => isLevel(l))) return null;
|
|
270
|
+
if (Object.values(decision.kinds || {}).some((a) => a && a.allowance && isLevel(a.allowance.level))) return 'role';
|
|
271
|
+
if (A.requestWaiting(decision.request, nowMs)) return 'waiting';
|
|
272
|
+
return 'not-allowed';
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** The CD-23 sentences for a visit that ended: how it ended, then where the person is. */
|
|
276
|
+
function endedText(customerName, ended) {
|
|
277
|
+
const name = customerName || 'the customer';
|
|
278
|
+
const first = ended === 'expired' ? `Your time in ${name} has ended.` : `You are no longer working in ${name}.`;
|
|
279
|
+
return `${first} You are back on your own pages.`;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** The visit's minutes, to its end or to now, whichever came first. */
|
|
283
|
+
const minutesOf = (rec, nowMs) => Math.max(0, Math.round((Math.min(nowMs, Number(rec.until) || nowMs) - (Number(rec.startedAt) || nowMs)) / 60000));
|
|
284
|
+
|
|
285
|
+
module.exports = {
|
|
286
|
+
VISIT_HOURS, VISIT_MS, VISIT_WORDS, VISIT_ENDINGS, VISIT_BECAUSE, VISIT_MARKER, VISIT_KEY, VISIT_ID, CUSTOMER_ID, RECORD_KEYS,
|
|
287
|
+
REASON_MAX, LEVELS, LEVEL_WORDS,
|
|
288
|
+
cleanReason, reasonMayBeBlank, reasonProblem, roleMaxOf, levelOf, offeredLevels, entryLevels, untilOf, recordOk, examine,
|
|
289
|
+
actingIn, placeProblem, fitOf, capOf, permissionIndex, refusal, endedText, minutesOf
|
|
290
|
+
};
|