@aria-framework/customer 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.
@@ -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
+ };