@aria-framework/tenancy 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,216 @@
1
+ /**
2
+ * Working inside a partner: the act-as and stop routes, the locals the banner reads, and where the banner lives.
3
+ *
4
+ * router.use(actingRoutes({ Router: express.Router, tenancy, db, audit, requirePermission,
5
+ * permission: 'partners.manage', landing: '/', refuseInactive: true })); // BEFORE any /:id route
6
+ * app.use(actingLocals({ tenancy, readOnly: false }));
7
+ * app.set('views', [..., viewsDir]); then <%- include('acting-banner') %>
8
+ *
9
+ * A platform operator can READ every tenant (the policy's platform arm is `true`) and cannot WRITE into one, because
10
+ * every scoped table defaults partner_id to the operator's own partner, the house. This is the switch that lets them
11
+ * work there, and it is deliberately EXPLICIT: they say which tenant, and everything they do lands there until they say
12
+ * otherwise. IT NARROWS, IT NEVER WIDENS: while acting the scope is 'partner', so every platform-only permission is
13
+ * refused. The scope code (`contextFor`) re-checks at the point of use that only a platform user can be acting.
14
+ *
15
+ * Moved from the starter's two handlers and its banner block. No permission name lives here (`permission` is the
16
+ * app's), and whether a deactivated partner may be entered is the app's `refuseInactive`.
17
+ */
18
+
19
+ 'use strict';
20
+
21
+ const path = require('path');
22
+
23
+ function fail(message) { throw new Error(`actingRoutes: ${message}`); }
24
+
25
+ /** A local path only ("/x", never "//host" or "/\\host" or "http:"), or the redirect is an open one. */
26
+ function isLocalPath(p) {
27
+ return typeof p === 'string' && /^\/(?![/\\])/.test(p) && !/[\r\n]/.test(p);
28
+ }
29
+
30
+ const DEFAULT_MESSAGES = {
31
+ house: 'The House is the platform view — you are already in it.',
32
+ inactive: (name) => `"${name}" is deactivated. Reactivate it before working in it.`,
33
+ started: (name) => `You are now working inside "${name}". Everything you create lands there, and `
34
+ + 'platform-only settings are unavailable until you stop.',
35
+ notActing: 'You were not working inside a partner.',
36
+ stopped: 'Back to the platform view.',
37
+ // Absent: an unknown partner id answers the app's 404 page, as the starter does. A string: it is flashed instead.
38
+ unknown: null
39
+ };
40
+
41
+ const text = (m, ...a) => (typeof m === 'function' ? m(...a) : m);
42
+
43
+ function actingRoutes(options) {
44
+ const o = options || {};
45
+ if (typeof o.Router !== 'function') fail('Router is required (express.Router): this package does not load express itself');
46
+ if (!o.tenancy || typeof o.tenancy.contextFor !== 'function') fail('tenancy is required');
47
+ if (!o.db || typeof o.db.invoke !== 'function') fail('db is required (the app\'s db client)');
48
+ if (typeof o.audit !== 'function') fail('audit is required: (req, action, opts), the app\'s staff audit helper');
49
+ if (typeof o.requirePermission !== 'function') fail('requirePermission is required (the app\'s gate)');
50
+ if (typeof o.permission !== 'string' || !o.permission) fail('permission is required: the name of the app\'s partner-management permission');
51
+ if (!isLocalPath(o.landing)) fail('landing is required: a local path ("/" or "/dashboard") where the browser goes after a switch');
52
+ // NO DEFAULT: the apps answer this differently today, and an app that forgot must not silently get another's rule.
53
+ if (typeof o.refuseInactive !== 'boolean') fail('refuseInactive is required (true or false): may a house operator act inside a deactivated partner?');
54
+ if (o.back != null && !isLocalPath(o.back)) fail('back must be a local path');
55
+ if (o.flash != null && typeof o.flash !== 'function') fail('flash must be a function (req, res, type, message), which may return a promise');
56
+ if (o.notFound != null && typeof o.notFound !== 'function') fail('notFound must be a function (req, res)');
57
+ const messages = { ...DEFAULT_MESSAGES, ...(o.messages || {}) };
58
+ // WHERE THE TWO ROWS LAND (the owner's decision of 29 Nov 2026: the stop entry goes into both logs). REQUIRED, no
59
+ // default, so every existing app stays as it is until its own adoption: each passes { start: 'house', stop: 'partner' },
60
+ // what all six do today (the start row is written before the switch, in the operator's own scope; the stop row after
61
+ // the switch back, but still in the REQUEST's context, which the scope middleware fixed at the acting partner).
62
+ // start: 'house' | 'both' stop: 'partner' | 'house' | 'both'
63
+ // 'house' is the operator's own scope (contextFor once the acting keys are absent), 'partner' the partner acted in,
64
+ // 'both' one row in each: the same action and detail, built by the app's audit from the same request.
65
+ const sc = o.auditScopes;
66
+ if (!sc || typeof sc !== 'object' || !['house', 'both'].includes(sc.start) || !['partner', 'house', 'both'].includes(sc.stop)) {
67
+ fail("auditScopes is required, with no default: { start: 'house' | 'both', stop: 'partner' | 'house' | 'both' } (every existing app: { start: 'house', stop: 'partner' })");
68
+ }
69
+ if ((sc.start === 'both' || sc.stop !== 'partner') && typeof o.tenancy.run !== 'function') fail('tenancy.run is required for these auditScopes (the rows written in an explicit scope)');
70
+ if ((sc.start === 'both' || sc.stop === 'both') && (!o.logger || typeof o.logger.error !== 'function')) {
71
+ fail("logger is required (error) when an auditScopes value is 'both': the ADDED row's failure is logged, never thrown");
72
+ }
73
+ const { db, audit, landing, refuseInactive } = o;
74
+ /**
75
+ * The ADDED row of a 'both': written in `ctx`, and isolated: a throw or a rejection is logged at error and changes
76
+ * nothing else (no switch undone, no request failed). The row today's code writes keeps today's behaviour.
77
+ */
78
+ const addedRow = (ctx, req, action, opts) => {
79
+ const failed = (e) => { try { o.logger.error(`acting: the added "${action}" audit row (${ctx.scope} ${ctx.partnerId}) could not be written: ${(e && e.message) || e}`); } catch (_) { /* nothing more to do */ } };
80
+ try {
81
+ const r = o.tenancy.run(ctx, () => audit(req, action, opts));
82
+ if (r && typeof r.then === 'function') r.then(null, failed);
83
+ } catch (e) { failed(e); }
84
+ };
85
+ const partnerCtx = (id) => ({ scope: 'partner', partnerId: Number(id) });
86
+ const partnerModel = o.partnerModel || 'Partner';
87
+ // `back` when the app sets it; else the mount (`req.baseUrl`), CHECKED AT REQUEST TIME like every other redirect
88
+ // here (a mount the app did not mean, or none, is not trusted); else `landing`.
89
+ const backTo = (req) => o.back || (isLocalPath(req.baseUrl) ? req.baseUrl : landing);
90
+ // The 404 answer: by default the app's 'errors/404' view (which the app must have), or the app's own `notFound`.
91
+ const notFound = (req, res) => (o.notFound ? o.notFound(req, res) : res.status(404).render('errors/404', { title: 'Not found' }));
92
+ // A flash, then `then()`: by default the app's `res.flash(type, message, callback)` (connect-flash style WITH a
93
+ // callback; another shape answers a 500), or the app's own `flash(req, res, type, message)`, which may return a promise.
94
+ const flashThen = (req, res, next, type, message, then) => {
95
+ if (!o.flash) return res.flash(type, message, then);
96
+ let r;
97
+ try { r = o.flash(req, res, type, message); } catch (e) { return next(e); }
98
+ return Promise.resolve(r).then(() => then(), next);
99
+ };
100
+
101
+ const router = o.Router();
102
+ // A non-digit id is not this route's (the starter's numericParam): it falls through to the app's own routes or its
103
+ // 404, BEFORE the permission gate runs, rather than reaching Number().
104
+ router.param('id', (req, res, next, value) => (/^[0-9]+$/.test(String(value)) ? next() : next('route')));
105
+
106
+ // ── DECLARED BEFORE EVERY '/:id' ROUTE, AND THAT IS LOAD-BEARING ───────────────────────────────────────────────────
107
+ // Express matches in declaration order, so the app mounts this router before its own `/:id` routes. A param guard's
108
+ // fall-through for a non-numeric id would happen to make it work anyway; depending on that is a coincidence, not a
109
+ // design (an endpoint once never reached its handler that way and Express answered 404 with no log and no audit).
110
+
111
+ /**
112
+ * Stop working inside a partner.
113
+ *
114
+ * NOT BEHIND THE PERMISSION, deliberately: while acting the operator's scope is 'partner', and every platform-only
115
+ * permission, the partner-management one included, is refused. Gating the way OUT on a permission the act of acting
116
+ * removes would strand them. So the check is the fact acting does not change: is the signed-in user platform staff?
117
+ */
118
+ router.post('/stop-acting', (req, res, next) => {
119
+ const u = req.session && req.session.user;
120
+ // A partner-scoped user has nothing to stop, and should not learn that the mechanism exists.
121
+ if (!u || u.scope_kind !== 'platform') return notFound(req, res);
122
+ const was = req.session.actingPartnerId;
123
+ if (was == null) return flashThen(req, res, next, 'error', text(messages.notActing), () => res.redirect(landing));
124
+ delete req.session.actingPartnerId;
125
+ delete req.session.actingPartnerName;
126
+ req.session.save((err) => {
127
+ // next(err), NOT throw: this callback runs after the handler returned, so a throw here is an uncaught
128
+ // exception, and a session-store blip would take the process down instead of rendering an error page.
129
+ if (err) return next(err);
130
+ // Audited AFTER the switch back, the mirror of act-as: this row belongs in the operator's own scope, next to the
131
+ // one that opened the session.
132
+ const stopOpts = { entity_type: 'partner', entity_id: Number(was) };
133
+ if (sc.stop === 'house') {
134
+ // The one row, in the operator's own scope (the keys are gone, so contextFor answers it), not the request's.
135
+ o.tenancy.run(o.tenancy.contextFor(req), () => audit(req, 'partner.act_as_stop', stopOpts));
136
+ } else {
137
+ audit(req, 'partner.act_as_stop', stopOpts); // today's row: in the request's context, the partner acted in
138
+ if (sc.stop === 'both') addedRow(o.tenancy.contextFor(req), req, 'partner.act_as_stop', stopOpts);
139
+ }
140
+ return flashThen(req, res, next, 'success', text(messages.stopped), () => res.redirect(backTo(req)));
141
+ });
142
+ });
143
+
144
+ /** Work inside a partner. */
145
+ router.post('/:id/act-as', o.requirePermission(o.permission), (req, res, next) => {
146
+ (async () => {
147
+ const id = Number(req.params.id);
148
+ const partner = await db.invoke(partnerModel, 'byId', id);
149
+ if (!partner) {
150
+ if (messages.unknown) return flashThen(req, res, next, 'error', text(messages.unknown), () => res.redirect(backTo(req)));
151
+ return notFound(req, res);
152
+ }
153
+ if (Number(partner.is_house) === 1) {
154
+ return flashThen(req, res, next, 'error', text(messages.house), () => res.redirect(backTo(req)));
155
+ }
156
+ if (refuseInactive && !Number(partner.is_active)) {
157
+ return flashThen(req, res, next, 'error', text(messages.inactive, partner.name), () => res.redirect(backTo(req)));
158
+ }
159
+
160
+ // AUDITED BEFORE THE SWITCH, so the row lands in the operator's OWN scope (the house) where a platform reader
161
+ // will find it. Written after the switch it would land in the acted-upon tenant, the one place somebody auditing
162
+ // the operator would not think to look.
163
+ const startOpts = { entity_type: 'partner', entity_id: id, detail: { name: partner.name } };
164
+ // Today's row, in the request's context: before the switch that IS the operator's own scope. A throw here stops the
165
+ // switch, as in the source.
166
+ audit(req, 'partner.act_as_start', startOpts);
167
+ if (sc.start === 'both') addedRow(partnerCtx(id), req, 'partner.act_as_start', startOpts);
168
+
169
+ req.session.actingPartnerId = id;
170
+ req.session.actingPartnerName = partner.name;
171
+ return req.session.save((err) => {
172
+ if (err) return next(err); // next(err), NOT throw: see stop-acting
173
+ return flashThen(req, res, next, 'success', text(messages.started, partner.name), () => res.redirect(landing));
174
+ });
175
+ })().catch(next);
176
+ });
177
+
178
+ return router;
179
+ }
180
+
181
+ /**
182
+ * The locals the banner reads, on every page: `actingPartnerName` and `actingReadOnly`.
183
+ *
184
+ * THE BANNER DOES NOT TRUST THE SESSION'S STORED NAME ALONE. It is shown only when the request's scope has actually
185
+ * moved to that partner, asked of `tenancy.contextFor(req)`: a partner-scoped user with a stray acting flag (which the
186
+ * scope code ignores) would otherwise see "working inside P" while working in their own tenant. The name itself is the
187
+ * one the act-as route stored.
188
+ *
189
+ * `readOnly` is the app's write rule while acting (its write gate's `whileActing: 'readOnly'`), as a plain boolean:
190
+ * `actingReadOnly` is true only while the scope has moved. `note` replaces the banner's second sentence.
191
+ */
192
+ function actingLocals(options) {
193
+ const o = options || {};
194
+ if (!o.tenancy || typeof o.tenancy.contextFor !== 'function') throw new Error('actingLocals: tenancy is required');
195
+ if (typeof o.readOnly !== 'boolean') throw new Error('actingLocals: readOnly is required (true or false): is acting read-only in this app?');
196
+ if (o.stopPath != null && !isLocalPath(o.stopPath)) throw new Error('actingLocals: stopPath must be a local path');
197
+ const stopPath = o.stopPath || '/admin/partners/stop-acting';
198
+ const note = o.note || null;
199
+ return function actingLocalsMw(req, res, next) {
200
+ const s = req.session;
201
+ const u = s && s.user;
202
+ let moved = false;
203
+ if (u && s.actingPartnerId != null) {
204
+ const ctx = o.tenancy.contextFor(req);
205
+ moved = !!ctx && ctx.scope === 'partner' && Number(ctx.partnerId) === Number(s.actingPartnerId)
206
+ && Number(ctx.partnerId) !== Number(u.partner_id);
207
+ }
208
+ res.locals.actingPartnerName = moved ? (s.actingPartnerName || `partner ${Number(s.actingPartnerId)}`) : null;
209
+ res.locals.actingReadOnly = moved && o.readOnly;
210
+ res.locals.actingStopPath = stopPath;
211
+ res.locals.actingNote = note;
212
+ next();
213
+ };
214
+ }
215
+
216
+ module.exports = { actingRoutes, actingLocals, viewsDir: path.join(__dirname, '..', '..', 'views') };
@@ -0,0 +1,177 @@
1
+ /**
2
+ * WORKING IN A PARTNER ENDS AFTER A PERIOD WITHOUT ACTIVITY, when the app sets one (the owner's decision of 29 Nov 2026;
3
+ * 0, the default the apps pass, is today's behaviour: no idle end, and NOT ONE session write from this module).
4
+ *
5
+ * const actingIdle = createActingIdle({ idleMinutes, now, isBackground, audit, logger,
6
+ * auditScopes: { stop: 'partner' }, run });
7
+ * // EITHER with the app's own scope middleware (an app with its own acting code):
8
+ * app.use(session); app.use(actingIdle.before); app.use(appScopeMiddleware); app.use(actingIdle.after);
9
+ * // OR with this package's: app.use(tenancy.requestScope({ actingIdle })) (it runs the two halves itself)
10
+ *
11
+ * TWO HALVES, AND THE ORDER IS THE POINT. The end must happen BEFORE the scope middleware fixes the request's tenant:
12
+ * ended after it, the very request that found the period over would still run (and write) inside the partner. So
13
+ * `before` judges the period and clears the acting keys; the scope middleware then places the request in the
14
+ * operator's own scope; `after` writes the stop row where `auditScopes.stop` says (the same setting actingRoutes
15
+ * takes), tells the person once, and saves the session.
16
+ *
17
+ * The session keys are the ones every app uses: `actingPartnerId`, `actingPartnerName`. The activity clock is
18
+ * `actingIdleAt: { partnerId, at }`: started at the first request that sees a partner being worked in (a clock for
19
+ * another partner, or none, starts afresh), moved by a request that is not background when a stamp is due
20
+ * (idle.stampDue: at most once a minute), removed when the session is not acting. Every such write is saved at once,
21
+ * before the request goes on. At 0 minutes none of this happens. The rules are idle.js's, the ones fleet view uses.
22
+ * A throw from `idleMinutes()` ends the acting (reason 'error'), never keeps it unchecked.
23
+ */
24
+
25
+ 'use strict';
26
+
27
+ const idle = require('../scope/idle');
28
+
29
+ const isFn = (f) => typeof f === 'function';
30
+ function fail(message) { throw new Error(`createActingIdle: ${message}`); }
31
+
32
+ const STOPS = new Set(['partner', 'house', 'both']);
33
+ // A kind the framework's ui/flash partial renders, and one that stays until dismissed.
34
+ const NOTICE_KIND = 'warning';
35
+ const DEFAULT_MESSAGES = {
36
+ idle: (minutes, name) => `Working in ${name} ended after ${minutes} minute${minutes === 1 ? '' : 's'} without activity.`,
37
+ error: (name) => `Working in ${name} ended because it could not be checked. You can start it again.`
38
+ };
39
+ const ENDED = Symbol('actingIdle.ended');
40
+ const say = (m, ...a) => (isFn(m) ? m(...a) : m);
41
+
42
+ /**
43
+ * @param {object} o
44
+ * @param {() => number|Promise<number>} o.idleMinutes REQUIRED: the app's setting, a whole number; 0 = no idle end
45
+ * @param {() => number} o.now REQUIRED: the clock (ms)
46
+ * @param {(req) => boolean} o.isBackground REQUIRED: a request that does NOT count as activity
47
+ * @param {(req, action, opts) => any} o.audit REQUIRED: the app's audit helper (actingRoutes' shape)
48
+ * @param {{error: Function}} o.logger REQUIRED
49
+ * @param {{stop: 'partner'|'house'|'both'}} o.auditScopes REQUIRED, no default: where the stop row lands, as
50
+ * actingRoutes' auditScopes.stop (every existing app: 'partner'; a new app: 'both')
51
+ * @param {(ctx, fn) => any} [o.run] REQUIRED for 'partner' and 'both': the app's runner of `fn` in a tenant context
52
+ * (this package's tenancy.run), for the row written in the partner
53
+ * @param {(req, res, kind, text) => any} [o.flash] default res.flash(kind, text, callback)
54
+ * @param {object} [o.messages] idle(minutes, name), error(name)
55
+ */
56
+ function createActingIdle(options) {
57
+ const o = options || {};
58
+ for (const k of ['idleMinutes', 'now', 'isBackground', 'audit']) if (!isFn(o[k])) fail(`${k} is required (a function)`);
59
+ if (!o.logger || !isFn(o.logger.error)) fail('logger is required (error)');
60
+ const sc = o.auditScopes;
61
+ if (!sc || typeof sc !== 'object' || !STOPS.has(sc.stop)) {
62
+ fail("auditScopes is required, with no default: { stop: 'partner' | 'house' | 'both' }, the same value as actingRoutes' auditScopes.stop");
63
+ }
64
+ if (sc.stop !== 'house' && !isFn(o.run)) fail(`run is required for auditScopes.stop '${sc.stop}': (ctx, fn), the app's runner of fn in a tenant context (tenancy.run)`);
65
+ if (o.flash != null && !isFn(o.flash)) fail('flash must be a function (req, res, kind, text), which may return a promise');
66
+ const { idleMinutes, now, isBackground, audit, logger } = o;
67
+ const messages = { ...DEFAULT_MESSAGES, ...(o.messages || {}) };
68
+ const logged = (what) => (e) => { try { logger.error(`acting idle: ${what}: ${(e && e.message) || e}`); } catch (_) { /* nothing */ } };
69
+
70
+ /**
71
+ * An ordinary request's write (idle.writeMerged): the row read back, plus this request's own changes, plus this
72
+ * package's change, saved in the read's callback. Anything else writes nothing, is logged, and the session in memory is
73
+ * settled so express-session's own end-of-request save cannot bring acting back ('gone': signed out meanwhile;
74
+ * 'changed': acting was stopped or moved; 'unreadable': no store to ask, or it failed). The next request judges again.
75
+ */
76
+ const OWN_KEYS = ['actingPartnerId', 'actingPartnerName', 'actingIdleAt'];
77
+ async function written(req, stillOk, change, what, pre) {
78
+ let r;
79
+ try { r = await idle.writeMerged(req, stillOk, change); }
80
+ catch (e) { logged(`the session could not be saved after ${what}`)(e); return 'failed'; }
81
+ if (r.outcome !== 'saved') {
82
+ try { logger.error(`acting idle: ${what} not written: the session's row is ${r.outcome} (re-read before the save)`); } catch (_) { /* nothing */ }
83
+ idle.settleUnwritten(req, pre || idle.snapshot(req.session), r.row, OWN_KEYS, r.outcome);
84
+ }
85
+ return r.outcome;
86
+ }
87
+
88
+ /**
89
+ * Mounted DIRECTLY after the session middleware, when anything that changes the session (an auth middleware's
90
+ * lastActivity, for one) sits between the session and `before`: keeps the session as loaded (idle.markLoaded, the
91
+ * same as fleet view's `loaded`; either one serves both). `before` takes it itself when nothing is mounted between.
92
+ */
93
+ function loaded(req, res, next) { idle.markLoaded(req); next(); }
94
+
95
+ /** Mounted after the session (and `loaded`, if anything is between), BEFORE the scope middleware. */
96
+ function before(req, res, next) {
97
+ const s = req.session;
98
+ if (!s) return next();
99
+ idle.markLoaded(req); // the session as loaded: this is the place right after the session middleware
100
+ const acting = s.actingPartnerId != null;
101
+ return idle.readIdleMinutes(idleMinutes).then(async (minutes) => {
102
+ // 0 = no idle end: nothing is read from the session's clock and NOTHING is written, on any request.
103
+ if (minutes === 0) return next();
104
+ if (!acting) {
105
+ if (s.actingIdleAt === undefined) return next();
106
+ await written(req, (row) => row.actingPartnerId == null, (t) => { delete t.actingIdleAt; }, 'removing the clock');
107
+ return next();
108
+ }
109
+ const pid = Number(s.actingPartnerId);
110
+ const mark = s.actingIdleAt;
111
+ const stillActing = (row) => row.actingPartnerId != null && Number(row.actingPartnerId) === pid;
112
+ if (!mark || typeof mark !== 'object' || Number(mark.partnerId) !== pid || !Number.isFinite(mark.at)) {
113
+ const at = now(); // the clock starts at the first request that sees it
114
+ await written(req, stillActing, (t) => { t.actingIdleAt = { partnerId: pid, at }; }, 'starting the clock');
115
+ return next();
116
+ }
117
+ if (idle.idleEnded(mark.at, minutes, now())) return stop(req, 'idle', minutes, next);
118
+ if (!idle.isBackgroundSafe(isBackground, logger, req) && idle.stampDue(mark.at, minutes, now())) {
119
+ const at = now();
120
+ await written(req, stillActing, (t) => { t.actingIdleAt = { partnerId: pid, at }; }, 'the activity stamp');
121
+ }
122
+ return next();
123
+ }, (e) => {
124
+ if (!acting) { logged('the idle setting could not be read (not acting: nothing to end)')(e); return next(); }
125
+ logged(`the check failed; working in partner ${Number(s.actingPartnerId)} ends`)(e);
126
+ return stop(req, 'error', undefined, next);
127
+ }).catch(next);
128
+ }
129
+
130
+ // The keys are cleared HERE, before the scope is fixed (the request then runs in the operator's own scope); what the
131
+ // session held is kept, to settle the session with if the end cannot be written (after()).
132
+ function stop(req, reason, minutes, next) {
133
+ const s = req.session;
134
+ req[ENDED] = { partnerId: Number(s.actingPartnerId), name: s.actingPartnerName || `partner ${Number(s.actingPartnerId)}`, reason, minutes, snap: idle.snapshot(s) };
135
+ delete s.actingPartnerId;
136
+ delete s.actingPartnerName;
137
+ delete s.actingIdleAt;
138
+ return next();
139
+ }
140
+
141
+ /** Writes one stop row; isolated (a failure is logged, nothing else changes). */
142
+ function row(req, opts, partnerId) {
143
+ return Promise.resolve()
144
+ .then(() => (partnerId == null ? audit(req, 'partner.act_as_stop', opts)
145
+ : o.run({ scope: 'partner', partnerId }, () => audit(req, 'partner.act_as_stop', opts))))
146
+ .catch(logged(`the stop of partner ${opts.entity_id} could not be audited${partnerId == null ? '' : ' in the partner'}`));
147
+ }
148
+
149
+ /**
150
+ * Mounted right AFTER the scope middleware: the request now runs in the operator's own scope. The notice goes into
151
+ * the session in memory; the row is re-read and, if it is still working in that partner, the row plus this request's
152
+ * changes minus the acting keys is saved (in the read's callback); then the stop row lands where auditScopes.stop says
153
+ * ('house': here; 'partner': in the partner, through `run`; 'both': one in each). Otherwise nothing is written or
154
+ * audited (a sign-out or a stop that happened meanwhile stands) and the session in memory is settled. This request
155
+ * itself still runs in the operator's own scope.
156
+ */
157
+ function after(req, res, next) {
158
+ const ended = req[ENDED];
159
+ if (!ended) return next();
160
+ delete req[ENDED];
161
+ const detail = ended.minutes != null ? { reason: ended.reason, minutes: ended.minutes } : { reason: ended.reason };
162
+ const opts = { entity_type: 'partner', entity_id: ended.partnerId, detail };
163
+ return (async () => {
164
+ await idle.noticeOnce(o.flash, logger, req, res, NOTICE_KIND,
165
+ ended.reason === 'idle' ? say(messages.idle, ended.minutes, ended.name) : say(messages.error, ended.name));
166
+ const r = await written(req, (rw) => rw.actingPartnerId != null && Number(rw.actingPartnerId) === ended.partnerId,
167
+ (t) => { for (const k of OWN_KEYS) delete t[k]; }, 'the idle end', ended.snap);
168
+ if (r !== 'saved' && r !== 'failed') return;
169
+ if (sc.stop !== 'house') await row(req, opts, ended.partnerId);
170
+ if (sc.stop !== 'partner') await row(req, opts, null);
171
+ })().then(() => next(), next);
172
+ }
173
+
174
+ return { loaded, before, after };
175
+ }
176
+
177
+ module.exports = { createActingIdle };
@@ -0,0 +1,10 @@
1
+ 'use strict';
2
+
3
+ // The partners part: the partner store and provisioning (piece 10); the acting routes, locals and banner (piece 11);
4
+ // the idle end of working in a partner (createActingIdle).
5
+ const { createPartnerStore } = require('./store');
6
+ const { createProvisioner } = require('./provisioner');
7
+ const { actingRoutes, actingLocals, viewsDir } = require('./acting');
8
+ const { createActingIdle } = require('./actingIdle');
9
+
10
+ module.exports = { createPartnerStore, createProvisioner, actingRoutes, actingLocals, viewsDir, createActingIdle };