@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.
- package/CHANGELOG.md +172 -0
- package/README.md +450 -2
- package/assets/visit.js +86 -0
- package/index.js +19 -0
- package/lib/access/audit.js +58 -0
- package/lib/access/index.js +30 -0
- package/lib/access/kinds.js +61 -0
- package/lib/access/rules.js +176 -0
- package/lib/access/store.js +601 -0
- package/lib/access/tables.js +176 -0
- 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 +37 -4
- package/views/customer-visit-banner.ejs +20 -0
- package/views/customer-visit-ended.ejs +11 -0
|
@@ -0,0 +1,601 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* createAccessStore: the reads and writes of support access over the five tables of tables.js, as ONE model an app
|
|
3
|
+
* registers in its db worker (the pattern of @aria-framework/tenancy's createPartnerStore: a factory the app calls once
|
|
4
|
+
* with its own driver getter and settings, returning a plain object whose methods are its own properties, so the
|
|
5
|
+
* customer-safe list can name them):
|
|
6
|
+
*
|
|
7
|
+
* // models/CustomerAccess.js (worker side)
|
|
8
|
+
* module.exports = createAccessStore({ driver: () => database.driver(), kinds: KINDS, mayManage });
|
|
9
|
+
* // the worker's customer scope
|
|
10
|
+
* createCustomerScope({ safe: { ...APP_SAFE, CustomerAccess: ACCESS_CUSTOMER_SAFE }, models })
|
|
11
|
+
*
|
|
12
|
+
* WHO CALLS WHAT
|
|
13
|
+
* under the CUSTOMER'S PIN (ACCESS_CUSTOMER_SAFE; each reads the customer and its partner from the PIN, never from an
|
|
14
|
+
* argument, and refuses without one):
|
|
15
|
+
* the customer's own people (the pin carries their contact): state, openRequests; and, for a contact the app's
|
|
16
|
+
* `mayManage` says may change support access: setSettings, grant, endGrant, answer, unmanage
|
|
17
|
+
* a helper deciding entry (a pin with NO contact): decide, ask, cancel
|
|
18
|
+
* at a PARTNER's scope (that partner's staff; the house only while working in the partner), never under a pin:
|
|
19
|
+
* listStates, partnerDefaults, setPartnerDefault, partnerCustomers, setManaged, partnerRequests
|
|
20
|
+
* at PLATFORM scope: the same READS for one stated partner (fleet view: read only, CD-42), every write refused; and
|
|
21
|
+
* (the store cannot tell whether fleet view is on: the APP refuses listStates, partnerCustomers and partnerRequests at
|
|
22
|
+
* platform scope outside it; partnerDefaults may be read as a platform page)
|
|
23
|
+
* sweep (platform scope only).
|
|
24
|
+
*
|
|
25
|
+
* EVERY QUERY STATES ITS PARTNER (CD-43): the pin's, the partner scope's, or the one a platform read names. Row-level
|
|
26
|
+
* security bounds every table on Postgres either way; this is the model's own half, and the only half on SQLite.
|
|
27
|
+
*
|
|
28
|
+
* THE DRIVER IS A GETTER, read at every call (a handle captured at require time binds to the first driver in the
|
|
29
|
+
* process). Times are the clock's (`clock`, default Date.now) as UTC 'YYYY-MM-DD HH:MM:SS'; a starting value's save
|
|
30
|
+
* time and a customer's receipt are the DATABASE's own clock (both columns' defaults), compared as text.
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
'use strict';
|
|
34
|
+
|
|
35
|
+
const { currentTenant, currentPin, sql } = require('@aria-framework/db-worker');
|
|
36
|
+
const R = require('./rules');
|
|
37
|
+
const { defineKinds } = require('./kinds');
|
|
38
|
+
|
|
39
|
+
const LIST_MAX = 200;
|
|
40
|
+
/** The methods the customer's own people and a pinned helper call: what the app adds to its customer-safe list. */
|
|
41
|
+
const ACCESS_CUSTOMER_SAFE = Object.freeze(['state', 'openRequests', 'setSettings', 'grant', 'endGrant', 'answer', 'unmanage', 'decide', 'ask', 'cancel']);
|
|
42
|
+
/** The methods that refuse under a pin (staff and the scheduler): never on the customer-safe list. */
|
|
43
|
+
const ACCESS_STAFF = Object.freeze(['listStates', 'partnerDefaults', 'setPartnerDefault', 'partnerCustomers', 'setManaged', 'partnerRequests', 'sweep']);
|
|
44
|
+
|
|
45
|
+
const STATUS = { ACCESS_REFUSED: 403, ACCESS_INVALID: 400, ACCESS_BUSY: 409, ACCESS_SETTLED: 409, ACCESS_REQUEST_OPEN: 409, ACCESS_UNKNOWN_KIND: 400 };
|
|
46
|
+
/** A typed refusal: `code` and `status` survive the worker's thread boundary. */
|
|
47
|
+
function refused(code, message) {
|
|
48
|
+
return Object.assign(new Error(message), { code, status: STATUS[code] || 400 });
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
52
|
+
const isId = (v) => typeof v === 'string' && ID.test(v);
|
|
53
|
+
const posInt = (v) => { const n = Number(v); return Number.isSafeInteger(n) && n > 0 ? n : null; };
|
|
54
|
+
|
|
55
|
+
function fail(message) { throw new Error(`createAccessStore: ${message}`); }
|
|
56
|
+
|
|
57
|
+
function createAccessStore(options) {
|
|
58
|
+
if (!options || typeof options !== 'object') fail('pass { driver, kinds, mayManage, clock? }');
|
|
59
|
+
for (const k of Object.keys(options)) if (!['driver', 'kinds', 'mayManage', 'clock'].includes(k)) fail(`unknown option "${k}"`);
|
|
60
|
+
const { driver, mayManage } = options;
|
|
61
|
+
if (typeof driver !== 'function') fail('driver must be a getter, () => database.driver(), read at call time');
|
|
62
|
+
if (typeof mayManage !== 'function') {
|
|
63
|
+
fail('mayManage is required, with no default: async ({ partnerId, customerId, contactId }) => true when that person of the customer may change its support access');
|
|
64
|
+
}
|
|
65
|
+
const clock = options.clock == null ? Date.now : options.clock;
|
|
66
|
+
if (typeof clock !== 'function') fail('clock must be a function () => milliseconds');
|
|
67
|
+
const kinds = defineKinds(options.kinds);
|
|
68
|
+
|
|
69
|
+
const d = () => {
|
|
70
|
+
const h = driver();
|
|
71
|
+
if (!h) throw new Error('createAccessStore: the driver getter returned nothing (called before the database opened?)');
|
|
72
|
+
return h;
|
|
73
|
+
};
|
|
74
|
+
const nowMs = () => { const n = Number(clock()); if (!Number.isFinite(n)) throw new Error('createAccessStore: the clock gave no time'); return n; };
|
|
75
|
+
const ret = (h) => h.dialect.returning('id');
|
|
76
|
+
|
|
77
|
+
// ── scopes ─────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
78
|
+
|
|
79
|
+
/** The pinned customer, its partner and contact; refused without a pin. */
|
|
80
|
+
function pinned() {
|
|
81
|
+
const pin = currentPin();
|
|
82
|
+
if (!pin || !isId(pin.customerId) || !posInt(pin.partnerId)) throw refused('ACCESS_REFUSED', 'support access is read and set for one customer at a time (no customer pin)');
|
|
83
|
+
return { cus: pin.customerId, pid: Number(pin.partnerId), contactId: pin.contactId || null };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The partner a staff method works for. Never under a pin. Partner scope: that partner, reads and writes (the house
|
|
88
|
+
* writes a partner's settings only while working in it, CD-42, CD-63). Platform scope: reads only, for the partner
|
|
89
|
+
* `forPartner` names (fleet view); a write is refused whatever the route.
|
|
90
|
+
*/
|
|
91
|
+
function staffScope({ write = false, forPartner = null } = {}) {
|
|
92
|
+
if (currentPin()) throw refused('ACCESS_REFUSED', 'not from a pinned session');
|
|
93
|
+
const t = currentTenant();
|
|
94
|
+
if (!t) throw refused('ACCESS_REFUSED', 'no scope');
|
|
95
|
+
const platform = t.scope === 'platform';
|
|
96
|
+
if (platform && write) throw refused('ACCESS_REFUSED', 'support access is written only at a partner\'s own scope (the house: while working in that partner)');
|
|
97
|
+
const pid = platform ? posInt(forPartner) : posInt(t.partnerId);
|
|
98
|
+
if (!pid) throw refused('ACCESS_REFUSED', 'support access is read for one partner');
|
|
99
|
+
if (!platform && forPartner != null && posInt(forPartner) !== pid) throw refused('ACCESS_REFUSED', 'another partner\'s support access');
|
|
100
|
+
return { pid, platform };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// ── reads ──────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
104
|
+
|
|
105
|
+
function kindOf(key) {
|
|
106
|
+
const k = kinds.byKey(key);
|
|
107
|
+
if (!k) throw refused('ACCESS_UNKNOWN_KIND', `"${key}" is not one of this app's kinds of data (${kinds.keys.join(', ')})`);
|
|
108
|
+
return k;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* A stored row whose kind the app's list no longer has is an error, never skipped: the app must deal with it. It is
|
|
112
|
+
* the server's own data being wrong, not the caller's request, so its status is 500 (an unknown kind PASSED by a
|
|
113
|
+
* caller, kindOf above, stays 400).
|
|
114
|
+
*/
|
|
115
|
+
function knownRows(rows, table) {
|
|
116
|
+
for (const r of rows) {
|
|
117
|
+
if (!kinds.byKey(r.kind)) throw Object.assign(refused('ACCESS_UNKNOWN_KIND', `${table} holds kind "${r.kind}", which is not one of this app's kinds of data (${kinds.keys.join(', ')})`), { status: 500 });
|
|
118
|
+
}
|
|
119
|
+
return rows;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function customerRow(h, cus, pid) {
|
|
123
|
+
const c = await h.get('SELECT id, name, status, partner_id, created_at FROM customers WHERE id = ? AND partner_id = ?', [cus, pid]);
|
|
124
|
+
return c ? { id: c.id, name: c.name, status: c.status, partner_id: Number(c.partner_id), created_at: c.created_at } : null;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* THE PARTNER'S STARTING VALUES IN FORCE WHEN A CUSTOMER WAS RECEIVED: per kind, the latest row saved STRICTLY BEFORE
|
|
129
|
+
* `receivedAt` (both stamps the database's clock, to the second; a value saved in the same second as the customer
|
|
130
|
+
* arrived, or after, does not apply to it). Append-only, so no later save changes a customer the partner already has.
|
|
131
|
+
*/
|
|
132
|
+
function startsAt(defaults, receivedAt) {
|
|
133
|
+
const out = {};
|
|
134
|
+
for (const r of defaults) { // newest first
|
|
135
|
+
if (out[r.kind] || !receivedAt || !(String(r.created_at) < String(receivedAt))) continue;
|
|
136
|
+
out[r.kind] = { mode: r.mode, level: r.level || null };
|
|
137
|
+
}
|
|
138
|
+
return out;
|
|
139
|
+
}
|
|
140
|
+
async function partnerDefaultRows(h, pid) {
|
|
141
|
+
return knownRows(await h.all('SELECT id, kind, mode, level, set_by_name, created_at FROM customer_access_defaults WHERE partner_id = ? ORDER BY id DESC', [pid]), 'customer_access_defaults');
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** `{ [kind]: setting }` for one customer: its stored rows, else the starting values (rules.settingOf). */
|
|
145
|
+
function settingsFrom(stored, starts) {
|
|
146
|
+
const out = {};
|
|
147
|
+
for (const k of kinds.list) {
|
|
148
|
+
const s = stored.find((x) => x.kind === k.key) || null;
|
|
149
|
+
const setting = R.settingOf(k, s, starts[k.key] || null);
|
|
150
|
+
out[k.key] = { ...setting, set_by_name: s ? s.set_by_name : null, updated_at: s ? s.updated_at : null };
|
|
151
|
+
}
|
|
152
|
+
return out;
|
|
153
|
+
}
|
|
154
|
+
async function settingsOf(h, c) {
|
|
155
|
+
const stored = knownRows(await h.all('SELECT kind, mode, level, set_by_name, updated_at FROM customer_access_settings WHERE customer_id = ? AND partner_id = ?', [c.id, c.partner_id]), 'customer_access_settings');
|
|
156
|
+
return settingsFrom(stored, startsAt(await partnerDefaultRows(h, c.partner_id), c.created_at));
|
|
157
|
+
}
|
|
158
|
+
const settingList = (settings) => kinds.keys.map((k) => settings[k]);
|
|
159
|
+
|
|
160
|
+
async function liveGrant(h, cus, pid, nowText) {
|
|
161
|
+
return (await h.get('SELECT * FROM customer_access_grants WHERE customer_id = ? AND partner_id = ? AND ended_at IS NULL AND (ends_at IS NULL OR ends_at > ?) ORDER BY id DESC LIMIT 1',
|
|
162
|
+
[cus, pid, nowText])) || null;
|
|
163
|
+
}
|
|
164
|
+
async function managedRow(h, cus, pid) {
|
|
165
|
+
const m = await h.get('SELECT id, customer_id, partner_id, set_by_name, set_by_user, created_at FROM customer_access_managed WHERE customer_id = ? AND partner_id = ? LIMIT 1', [cus, pid]);
|
|
166
|
+
return m ? { ...m, id: Number(m.id), partner_id: Number(m.partner_id) } : null;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** The pin's contact may change support access: a contact of the pinned customer, and the app says so. → its name. */
|
|
170
|
+
async function adminCaller(h, cus, pid, contactId) {
|
|
171
|
+
const no = () => refused('ACCESS_REFUSED', 'only the customer\'s own people who manage support access change who may come in');
|
|
172
|
+
if (!isId(contactId)) throw no();
|
|
173
|
+
const k = await h.get('SELECT id, name FROM customer_contacts WHERE id = ? AND customer_id = ? AND partner_id = ?', [contactId, cus, pid]);
|
|
174
|
+
if (!k) throw no();
|
|
175
|
+
if ((await mayManage({ partnerId: pid, customerId: cus, contactId })) !== true) throw no();
|
|
176
|
+
return String(k.name || contactId).slice(0, 200);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async function activeCustomer(h, cus, pid) {
|
|
180
|
+
const c = await customerRow(h, cus, pid);
|
|
181
|
+
if (!c || c.status !== 'active') throw refused('ACCESS_REFUSED', 'this customer is not active');
|
|
182
|
+
return c;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// ── writes ─────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
186
|
+
|
|
187
|
+
/** End the customer's live grants: those past their end as `lapsed` (at their end), the rest as `how`. → the rows. */
|
|
188
|
+
async function endLive(h, cus, pid, how, byName, nowText) {
|
|
189
|
+
const live = await h.all('SELECT * FROM customer_access_grants WHERE customer_id = ? AND partner_id = ? AND ended_at IS NULL', [cus, pid]);
|
|
190
|
+
const out = [];
|
|
191
|
+
for (const g of live) {
|
|
192
|
+
const lapsed = g.ends_at != null && g.ends_at <= nowText;
|
|
193
|
+
await h.run('UPDATE customer_access_grants SET ended_at = ?, ended_how = ?, ended_by_name = ? WHERE id = ? AND customer_id = ? AND partner_id = ? AND ended_at IS NULL',
|
|
194
|
+
[lapsed ? g.ends_at : nowText, lapsed ? 'lapsed' : how, lapsed ? null : byName, g.id, cus, pid]);
|
|
195
|
+
out.push({ ...g, id: Number(g.id), ended_how: lapsed ? 'lapsed' : how });
|
|
196
|
+
}
|
|
197
|
+
return out;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Give the customer's partner a grant, ending any live one first. → `{ grant, ended }`. */
|
|
201
|
+
async function giveGrant(h, cus, pid, { duration, level, byName, byContact, requestId = null }) {
|
|
202
|
+
const now = nowMs();
|
|
203
|
+
const ended = await endLive(h, cus, pid, 'replaced', byName, R.stamp(now));
|
|
204
|
+
const ms = R.GRANT_FOR[duration];
|
|
205
|
+
const endsAt = ms == null ? null : R.stamp(now + ms);
|
|
206
|
+
const r = await h.run(`INSERT INTO customer_access_grants (customer_id, partner_id, level, ends_at, given_by_name, given_by_contact, request_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)${ret(h)}`,
|
|
207
|
+
[cus, pid, level, endsAt, byName, byContact || null, requestId, R.stamp(now)]);
|
|
208
|
+
return { grant: { id: Number(r.lastId), customer_id: cus, partner_id: pid, level, ends_at: endsAt, given_by_name: byName, request_id: requestId }, ended };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** A typed refusal for a unique-index race (two answers, two saves at the same moment). */
|
|
212
|
+
async function guarded(fn) {
|
|
213
|
+
try { return await fn(); } catch (e) {
|
|
214
|
+
if (sql.isUniqueViolation(e)) throw refused('ACCESS_BUSY', 'someone else changed this at the same moment; try again');
|
|
215
|
+
throw e;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const answersOf = (settings, grant, now) => kinds.list.map((k) => ({ kind: k.key, setting: settings[k.key], allowance: R.allowance(settings[k.key], grant, now) }));
|
|
220
|
+
const byKind = (list) => Object.fromEntries(list.map((a) => [a.kind, a]));
|
|
221
|
+
const n = (r) => (r ? { ...r, id: Number(r.id) } : r);
|
|
222
|
+
|
|
223
|
+
const store = {
|
|
224
|
+
// ── the customer's own people, and a pinned helper ───────────────────────────────────────────────────────────
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* THE PORTAL'S PAGE (pinned): `{ customer, settings: { [kind]: setting }, grant, requests, managed, managedInForce }`;
|
|
228
|
+
* requests are the waiting ones and those answered in the last 24 hours. Null when the pin's scope does not hold
|
|
229
|
+
* the customer.
|
|
230
|
+
*/
|
|
231
|
+
async state() {
|
|
232
|
+
const { cus, pid } = pinned();
|
|
233
|
+
const h = d();
|
|
234
|
+
const c = await customerRow(h, cus, pid);
|
|
235
|
+
if (!c) return null;
|
|
236
|
+
const now = nowMs();
|
|
237
|
+
const settings = await settingsOf(h, c);
|
|
238
|
+
const requests = await h.all("SELECT * FROM customer_access_requests WHERE customer_id = ? AND partner_id = ? AND ((state = 'waiting' AND expires_at > ?) OR (answered_at IS NOT NULL AND answered_at > ?)) ORDER BY id DESC LIMIT 50",
|
|
239
|
+
[cus, pid, R.stamp(now), R.stamp(now - R.REQUEST_LIVES_MS)]);
|
|
240
|
+
const managed = await managedRow(h, cus, pid);
|
|
241
|
+
return { customer: c, settings, grant: n(await liveGrant(h, cus, pid, R.stamp(now))), requests: requests.map(n), managed,
|
|
242
|
+
managedInForce: R.managedInForce(settingList(settings), managed) };
|
|
243
|
+
},
|
|
244
|
+
|
|
245
|
+
/** The waiting requests of the pinned customer, for a person who manages support access (the request banner). Others: []. */
|
|
246
|
+
async openRequests() {
|
|
247
|
+
const { cus, pid, contactId } = pinned();
|
|
248
|
+
const h = d();
|
|
249
|
+
if (!isId(contactId)) return [];
|
|
250
|
+
try { await adminCaller(h, cus, pid, contactId); } catch (e) { if (e.code === 'ACCESS_REFUSED') return []; throw e; }
|
|
251
|
+
const rows = await h.all("SELECT id, user_id, user_name, company, reason, duration, level, created_at, expires_at FROM customer_access_requests WHERE customer_id = ? AND partner_id = ? AND state = 'waiting' AND expires_at > ? ORDER BY id LIMIT 10",
|
|
252
|
+
[cus, pid, R.stamp(nowMs())]);
|
|
253
|
+
return rows.map(n);
|
|
254
|
+
},
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* SAVE "WHO MAY COME IN" (pinned; a person who manages support access): `changes` { [kind]: { mode, level } }. Each
|
|
258
|
+
* kind must be one of the app's and each setting valid; one equal to what is in force is not written. When the save
|
|
259
|
+
* leaves EVERY kind at Never, the customer is closed (CD-35): the live grant ends (reported 'closed') and the waiting
|
|
260
|
+
* requests are cancelled, in this same transaction. One kind set to Never closes that kind only: the grant still
|
|
261
|
+
* opens the others (D-0013 answer 2).
|
|
262
|
+
* → `{ changes: [{ kind, before, after }], ended: [grant rows], cancelled: [request rows] }`.
|
|
263
|
+
*/
|
|
264
|
+
async setSettings(changes) {
|
|
265
|
+
const { cus, pid, contactId } = pinned();
|
|
266
|
+
if (!changes || typeof changes !== 'object' || Array.isArray(changes)) throw refused('ACCESS_INVALID', 'pass { kind: { mode, level } }');
|
|
267
|
+
const entries = Object.entries(changes).map(([key, s]) => {
|
|
268
|
+
const k = kindOf(key);
|
|
269
|
+
const next = { mode: s && s.mode, level: s && s.mode === 'open' ? s.level : null };
|
|
270
|
+
if (!R.validSetting(next)) throw refused('ACCESS_INVALID', `choose who may come in for ${k.label}`);
|
|
271
|
+
return [k, next];
|
|
272
|
+
});
|
|
273
|
+
const h = d();
|
|
274
|
+
const c = await activeCustomer(h, cus, pid);
|
|
275
|
+
const byName = await adminCaller(h, cus, pid, contactId);
|
|
276
|
+
const before = await settingsOf(h, c);
|
|
277
|
+
const now = R.stamp(nowMs());
|
|
278
|
+
const out = [];
|
|
279
|
+
for (const [k, next] of entries) {
|
|
280
|
+
const b = before[k.key];
|
|
281
|
+
if (b.mode === next.mode && (b.level || null) === next.level) continue;
|
|
282
|
+
await guarded(async () => {
|
|
283
|
+
const r = await h.run('UPDATE customer_access_settings SET mode = ?, level = ?, set_by_name = ?, set_by_contact = ?, updated_at = ? WHERE customer_id = ? AND partner_id = ? AND kind = ?',
|
|
284
|
+
[next.mode, next.level, byName, contactId, now, cus, pid, k.key]);
|
|
285
|
+
if (!(Number(r.changes) > 0)) {
|
|
286
|
+
await h.run('INSERT INTO customer_access_settings (customer_id, partner_id, kind, mode, level, set_by_name, set_by_contact, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
|
|
287
|
+
[cus, pid, k.key, next.mode, next.level, byName, contactId, now]);
|
|
288
|
+
}
|
|
289
|
+
});
|
|
290
|
+
out.push({ kind: k.key, before: { mode: b.mode, level: b.level || null }, after: next });
|
|
291
|
+
}
|
|
292
|
+
const ended = [];
|
|
293
|
+
const cancelled = [];
|
|
294
|
+
if (out.length && R.allClosed(settingList(await settingsOf(h, c)))) {
|
|
295
|
+
for (const g of await endLive(h, cus, pid, 'ended', byName, now)) ended.push({ ...g, ended_how: g.ended_how === 'lapsed' ? 'lapsed' : 'closed' });
|
|
296
|
+
const waiting = await h.all("SELECT * FROM customer_access_requests WHERE customer_id = ? AND partner_id = ? AND state = 'waiting'", [cus, pid]);
|
|
297
|
+
for (const r of waiting) {
|
|
298
|
+
await h.run("UPDATE customer_access_requests SET state = 'cancelled', answered_at = ?, answered_by_name = ?, answered_by_contact = ? WHERE id = ? AND customer_id = ? AND partner_id = ? AND state = 'waiting'",
|
|
299
|
+
[now, byName, contactId, r.id, cus, pid]);
|
|
300
|
+
cancelled.push(n(r));
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
return { changes: out, ended, cancelled };
|
|
304
|
+
},
|
|
305
|
+
|
|
306
|
+
/** "LET THEM IN NOW" (pinned; a person who manages support access): `{ duration: 1h | 24h | 7d | off, level }`. → `{ grant, ended }`. */
|
|
307
|
+
async grant({ duration, level } = {}) {
|
|
308
|
+
const { cus, pid, contactId } = pinned();
|
|
309
|
+
if (!R.has(R.GRANT_FOR, duration)) throw refused('ACCESS_INVALID', 'choose for how long');
|
|
310
|
+
if (!R.LEVELS.includes(level)) throw refused('ACCESS_INVALID', 'choose look only or make changes');
|
|
311
|
+
const h = d();
|
|
312
|
+
const c = await activeCustomer(h, cus, pid);
|
|
313
|
+
const byName = await adminCaller(h, cus, pid, contactId);
|
|
314
|
+
if (R.allClosed(settingList(await settingsOf(h, c)))) throw refused('ACCESS_REFUSED', 'every kind of data is set to Never; change the setting first to let them in');
|
|
315
|
+
return guarded(() => giveGrant(h, cus, pid, { duration, level, byName, byContact: contactId }));
|
|
316
|
+
},
|
|
317
|
+
|
|
318
|
+
/** "END NOW" (pinned; a person who manages support access): the live grant `id` ends. → the ended rows (empty when it had ended). */
|
|
319
|
+
async endGrant(id) {
|
|
320
|
+
const { cus, pid, contactId } = pinned();
|
|
321
|
+
const h = d();
|
|
322
|
+
const byName = await adminCaller(h, cus, pid, contactId);
|
|
323
|
+
const g = await h.get('SELECT id FROM customer_access_grants WHERE id = ? AND customer_id = ? AND partner_id = ? AND ended_at IS NULL', [Number(id), cus, pid]);
|
|
324
|
+
if (!g) return [];
|
|
325
|
+
return (await endLive(h, cus, pid, 'ended', byName, R.stamp(nowMs()))).filter((x) => x.id === Number(g.id) || x.ended_how === 'lapsed');
|
|
326
|
+
},
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* ANSWER A REQUEST (pinned; a person who manages support access): `how` allow | allow_look | decline. THE FIRST
|
|
330
|
+
* ANSWER SETTLES IT: the update is conditional on the request still waiting and inside its 24 hours, so a second
|
|
331
|
+
* answer (or one after the lapse) is refused ACCESS_SETTLED. Allowing gives a grant for the time asked (look only for
|
|
332
|
+
* allow_look); refused while every kind is Never. → `{ request, grant, ended }`.
|
|
333
|
+
*/
|
|
334
|
+
async answer(id, how) {
|
|
335
|
+
const { cus, pid, contactId } = pinned();
|
|
336
|
+
if (!R.ANSWERS.includes(how)) throw refused('ACCESS_INVALID', 'allow, allow look only, or decline');
|
|
337
|
+
const h = d();
|
|
338
|
+
const byName = await adminCaller(h, cus, pid, contactId);
|
|
339
|
+
const r = await h.get('SELECT * FROM customer_access_requests WHERE id = ? AND customer_id = ? AND partner_id = ?', [Number(id), cus, pid]);
|
|
340
|
+
if (!r) throw refused('ACCESS_SETTLED', 'that request is not this customer\'s');
|
|
341
|
+
const now = R.stamp(nowMs());
|
|
342
|
+
const granted = how === 'decline' ? null : (how === 'allow_look' ? 'look' : r.level);
|
|
343
|
+
if (granted) {
|
|
344
|
+
const c = await customerRow(h, cus, pid);
|
|
345
|
+
if (c && R.allClosed(settingList(await settingsOf(h, c)))) throw refused('ACCESS_REFUSED', 'every kind of data is set to Never; change the setting first to let them in');
|
|
346
|
+
}
|
|
347
|
+
const u = await h.run("UPDATE customer_access_requests SET state = ?, answered_at = ?, answered_by_name = ?, answered_by_contact = ?, granted_level = ? WHERE id = ? AND customer_id = ? AND partner_id = ? AND state = 'waiting' AND expires_at > ?",
|
|
348
|
+
[granted ? 'allowed' : 'declined', now, byName, contactId, granted, r.id, cus, pid, now]);
|
|
349
|
+
if (!(Number(u.changes) > 0)) {
|
|
350
|
+
const cur = await h.get('SELECT state, answered_by_name FROM customer_access_requests WHERE id = ? AND customer_id = ? AND partner_id = ?', [r.id, cus, pid]);
|
|
351
|
+
throw refused('ACCESS_SETTLED', cur && cur.answered_by_name ? `already answered by ${cur.answered_by_name}` : 'that request has ended');
|
|
352
|
+
}
|
|
353
|
+
let out = { grant: null, ended: [] };
|
|
354
|
+
if (granted) {
|
|
355
|
+
out = await guarded(() => giveGrant(h, cus, pid, { duration: r.duration, level: granted, byName, byContact: contactId, requestId: Number(r.id) }));
|
|
356
|
+
await h.run('UPDATE customer_access_requests SET grant_id = ? WHERE id = ? AND customer_id = ? AND partner_id = ?', [out.grant.id, r.id, cus, pid]);
|
|
357
|
+
}
|
|
358
|
+
return { request: { ...n(r), state: granted ? 'allowed' : 'declined', granted_level: granted, answered_by_name: byName }, ...out };
|
|
359
|
+
},
|
|
360
|
+
|
|
361
|
+
/** THE CUSTOMER SWITCHES THE MANAGED MARK OFF (pinned; a person who manages support access). → the removed row, or null. */
|
|
362
|
+
async unmanage() {
|
|
363
|
+
const { cus, pid, contactId } = pinned();
|
|
364
|
+
const h = d();
|
|
365
|
+
const byName = await adminCaller(h, cus, pid, contactId);
|
|
366
|
+
const row = await managedRow(h, cus, pid);
|
|
367
|
+
if (!row) return null;
|
|
368
|
+
const r = await h.run('DELETE FROM customer_access_managed WHERE id = ? AND customer_id = ? AND partner_id = ?', [row.id, cus, pid]);
|
|
369
|
+
return Number(r.changes) > 0 ? { ...row, cleared_by_name: byName } : null;
|
|
370
|
+
},
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* A HELPER DECIDING ENTRY (pinned, no contact): `{ customer, kinds: { [kind]: { kind, setting, allowance } }, grant,
|
|
374
|
+
* request, managed, managedInForce, closed }`. Each kind's answer is read from that kind's own rows and the grant
|
|
375
|
+
* only. `request` is `userId`'s latest (waiting, or made in the last 24 hours). Null when the pin's scope does not
|
|
376
|
+
* hold the customer. The visit itself (levels, the role, the reason) is the visits part's.
|
|
377
|
+
*/
|
|
378
|
+
async decide(userId) {
|
|
379
|
+
const { cus, pid } = pinned();
|
|
380
|
+
const h = d();
|
|
381
|
+
const c = await customerRow(h, cus, pid);
|
|
382
|
+
if (!c) return null;
|
|
383
|
+
const now = nowMs();
|
|
384
|
+
const settings = await settingsOf(h, c);
|
|
385
|
+
const grant = n(await liveGrant(h, cus, pid, R.stamp(now)));
|
|
386
|
+
const uid = posInt(userId);
|
|
387
|
+
const request = uid ? await h.get("SELECT * FROM customer_access_requests WHERE customer_id = ? AND partner_id = ? AND user_id = ? AND (state = 'waiting' OR created_at > ?) ORDER BY id DESC LIMIT 1",
|
|
388
|
+
[cus, pid, uid, R.stamp(now - R.REQUEST_LIVES_MS)]) : null;
|
|
389
|
+
const managed = await managedRow(h, cus, pid);
|
|
390
|
+
const list = settingList(settings);
|
|
391
|
+
return { customer: c, kinds: byKind(answersOf(settings, grant, now)), grant, request: n(request) || null, managed,
|
|
392
|
+
managedInForce: R.managedInForce(list, managed), closed: R.allClosed(list) };
|
|
393
|
+
},
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* ASK TO COME IN (a helper, pinned, no contact): `{ userId, userPartnerId, userName, company, reason, duration (1h |
|
|
397
|
+
* 24h | 7d), level }`. Refused when every kind is Never, when every kind not set to Never already allows that level,
|
|
398
|
+
* and while this helper already has a request waiting here (one per helper per customer; the partial unique index
|
|
399
|
+
* holds it in a race). The helper's own waiting request past its 24 hours is lapsed first. → `{ request, lapsed, customer }`.
|
|
400
|
+
*/
|
|
401
|
+
async ask(o = {}) {
|
|
402
|
+
const { cus, pid, contactId } = pinned();
|
|
403
|
+
if (contactId) throw refused('ACCESS_REFUSED', 'the customer\'s own people do not ask to come in');
|
|
404
|
+
const reason = typeof o.reason === 'string' ? o.reason.trim().replace(/\s+/g, ' ') : '';
|
|
405
|
+
if (!reason) throw refused('ACCESS_INVALID', 'Give a reason for asking to come in.');
|
|
406
|
+
if (reason.length > R.REASON_MAX) throw refused('ACCESS_INVALID', `The reason is too long: at most ${R.REASON_MAX} characters.`);
|
|
407
|
+
if (!R.REQUEST_FOR.includes(o.duration)) throw refused('ACCESS_INVALID', 'Choose for how long: 1 hour, 24 hours or 7 days.');
|
|
408
|
+
if (!R.LEVELS.includes(o.level)) throw refused('ACCESS_INVALID', 'Choose look only or make changes.');
|
|
409
|
+
const userId = posInt(o.userId);
|
|
410
|
+
const userPartnerId = posInt(o.userPartnerId);
|
|
411
|
+
if (!userId || !userPartnerId) throw refused('ACCESS_INVALID', 'no helper');
|
|
412
|
+
const h = d();
|
|
413
|
+
const c = await activeCustomer(h, cus, pid);
|
|
414
|
+
const settings = await settingsOf(h, c);
|
|
415
|
+
const now = nowMs();
|
|
416
|
+
const why = R.askRefusal(answersOf(settings, await liveGrant(h, cus, pid, R.stamp(now)), now), o.level);
|
|
417
|
+
if (why === 'closed') throw refused('ACCESS_REFUSED', 'This customer has closed support access to you; only its people can change that.');
|
|
418
|
+
if (why === 'already') throw refused('ACCESS_REFUSED', 'You may come in already.');
|
|
419
|
+
const lapsed = await h.all("SELECT * FROM customer_access_requests WHERE customer_id = ? AND partner_id = ? AND user_id = ? AND state = 'waiting' AND expires_at <= ?", [cus, pid, userId, R.stamp(now)]);
|
|
420
|
+
for (const x of lapsed) await h.run("UPDATE customer_access_requests SET state = 'lapsed' WHERE id = ? AND customer_id = ? AND partner_id = ? AND state = 'waiting'", [x.id, cus, pid]);
|
|
421
|
+
const open = await h.get("SELECT id FROM customer_access_requests WHERE customer_id = ? AND partner_id = ? AND user_id = ? AND state = 'waiting'", [cus, pid, userId]);
|
|
422
|
+
const busy = () => refused('ACCESS_REQUEST_OPEN', 'You have asked already: wait for the answer, or cancel the request.');
|
|
423
|
+
if (open) throw busy();
|
|
424
|
+
const r = await h.run(`INSERT INTO customer_access_requests (customer_id, partner_id, user_id, user_partner_id, user_name, company, reason, duration, level, state, expires_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'waiting', ?, ?)${ret(h)}`,
|
|
425
|
+
[cus, pid, userId, userPartnerId, String(o.userName || userId).slice(0, 200), String(o.company || '-').slice(0, 200), reason, o.duration, o.level,
|
|
426
|
+
R.stamp(now + R.REQUEST_LIVES_MS), R.stamp(now)]).catch((e) => { if (sql.isUniqueViolation(e)) throw busy(); throw e; });
|
|
427
|
+
return { request: { id: Number(r.lastId), customer_id: cus, partner_id: pid, user_id: userId, reason, duration: o.duration, level: o.level }, lapsed: lapsed.map(n), customer: c };
|
|
428
|
+
},
|
|
429
|
+
|
|
430
|
+
/** CANCEL a waiting request (its helper, pinned, no contact). → the row, or null when it was not waiting. */
|
|
431
|
+
async cancel(id, userId) {
|
|
432
|
+
const { cus, pid, contactId } = pinned();
|
|
433
|
+
if (contactId) throw refused('ACCESS_REFUSED', 'not the helper\'s');
|
|
434
|
+
const h = d();
|
|
435
|
+
const r = await h.get("SELECT * FROM customer_access_requests WHERE id = ? AND customer_id = ? AND partner_id = ? AND user_id = ? AND state = 'waiting'", [Number(id), cus, pid, Number(userId)]);
|
|
436
|
+
if (!r) return null;
|
|
437
|
+
const u = await h.run("UPDATE customer_access_requests SET state = 'cancelled', answered_at = ? WHERE id = ? AND customer_id = ? AND partner_id = ? AND state = 'waiting'", [R.stamp(nowMs()), r.id, cus, pid]);
|
|
438
|
+
return Number(u.changes) > 0 ? n(r) : null;
|
|
439
|
+
},
|
|
440
|
+
|
|
441
|
+
// ── staff: a partner's own scope (reads and writes), platform scope (reads for one partner) ───────────────────
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* THE CUSTOMERS LIST'S ACCESS COLUMN: `customers` [{ id }] of the partner in scope (at platform scope, fleet view:
|
|
445
|
+
* of `forPartner`) → { [id]: { kinds: { [kind]: { setting, columnState } }, grant, request, managed, managedInForce } }.
|
|
446
|
+
* `userId`: whose requests (the viewer's own). A customer the scope does not hold is left out, never answered
|
|
447
|
+
* with a starting value.
|
|
448
|
+
*/
|
|
449
|
+
async listStates(userId, customers = [], forPartner = null) {
|
|
450
|
+
const { pid } = staffScope({ forPartner });
|
|
451
|
+
const ids = [...new Set((customers || []).map((c) => (c && typeof c === 'object' ? c.id : c)).filter(isId))];
|
|
452
|
+
const out = {};
|
|
453
|
+
if (!ids.length) return out;
|
|
454
|
+
if (ids.length > LIST_MAX) throw refused('ACCESS_INVALID', `at most ${LIST_MAX} customers at a time`);
|
|
455
|
+
const h = d();
|
|
456
|
+
const inList = ids.map(() => '?').join(', ');
|
|
457
|
+
const now = nowMs();
|
|
458
|
+
const rows = await h.all(`SELECT id, name, status, partner_id, created_at FROM customers WHERE partner_id = ? AND id IN (${inList})`, [pid, ...ids]);
|
|
459
|
+
const stored = knownRows(await h.all(`SELECT customer_id, kind, mode, level, set_by_name, updated_at FROM customer_access_settings WHERE partner_id = ? AND customer_id IN (${inList})`, [pid, ...ids]), 'customer_access_settings');
|
|
460
|
+
const defaults = await partnerDefaultRows(h, pid);
|
|
461
|
+
const grants = await h.all(`SELECT * FROM customer_access_grants WHERE partner_id = ? AND ended_at IS NULL AND (ends_at IS NULL OR ends_at > ?) AND customer_id IN (${inList})`, [pid, R.stamp(now), ...ids]);
|
|
462
|
+
const requests = await h.all(`SELECT * FROM customer_access_requests WHERE partner_id = ? AND user_id = ? AND (state = 'waiting' OR created_at > ?) AND customer_id IN (${inList}) ORDER BY id DESC`,
|
|
463
|
+
[pid, posInt(userId) || 0, R.stamp(now - R.REQUEST_LIVES_MS), ...ids]);
|
|
464
|
+
const managed = await h.all(`SELECT customer_id, set_by_name, created_at FROM customer_access_managed WHERE partner_id = ? AND customer_id IN (${inList})`, [pid, ...ids]);
|
|
465
|
+
for (const c of rows) {
|
|
466
|
+
const settings = settingsFrom(stored.filter((s) => s.customer_id === c.id), startsAt(defaults, c.created_at));
|
|
467
|
+
const grant = n(grants.find((g) => g.customer_id === c.id) || null);
|
|
468
|
+
const request = n(requests.find((r) => r.customer_id === c.id) || null);
|
|
469
|
+
const m = managed.find((x) => x.customer_id === c.id) || null;
|
|
470
|
+
const kindsOut = {};
|
|
471
|
+
for (const a of answersOf(settings, grant, now)) kindsOut[a.kind] = { setting: a.setting, columnState: R.columnState(a, request, now) };
|
|
472
|
+
out[c.id] = { kinds: kindsOut, grant, request, managed: m, managedInForce: R.managedInForce(settingList(settings), m) };
|
|
473
|
+
}
|
|
474
|
+
return out;
|
|
475
|
+
},
|
|
476
|
+
|
|
477
|
+
/** THE PARTNER'S STARTING VALUES: { [kind]: { settable, current: row | null, effective: { mode, level } } }. */
|
|
478
|
+
async partnerDefaults(forPartner = null) {
|
|
479
|
+
const { pid } = staffScope({ forPartner });
|
|
480
|
+
const rows = await partnerDefaultRows(d(), pid);
|
|
481
|
+
const out = {};
|
|
482
|
+
for (const k of kinds.list) {
|
|
483
|
+
const r = k.partnerMaySetStart ? rows.find((x) => x.kind === k.key) || null : null;
|
|
484
|
+
const cur = r ? { id: Number(r.id), mode: r.mode, level: r.level || null, set_by_name: r.set_by_name, created_at: r.created_at } : null;
|
|
485
|
+
const e = R.startOf(k, cur);
|
|
486
|
+
out[k.key] = { settable: k.partnerMaySetStart, current: cur, effective: { mode: e.mode, level: e.level } };
|
|
487
|
+
}
|
|
488
|
+
return out;
|
|
489
|
+
},
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* SAVE THE STARTING VALUE FOR NEW CUSTOMERS, for one kind (CD-39): `{ mode, level }`, May come in with a level or
|
|
493
|
+
* Only when we let them in. Refused for a kind the app does not let the partner set, and at platform scope.
|
|
494
|
+
* Appended, stamped by the DATABASE's clock. The same value as now is not written. → `{ changed, kind, before, after, firstSave }`.
|
|
495
|
+
*/
|
|
496
|
+
async setPartnerDefault(kind, next, by = {}) {
|
|
497
|
+
const { pid } = staffScope({ write: true });
|
|
498
|
+
const k = kindOf(kind);
|
|
499
|
+
if (!k.partnerMaySetStart) throw refused('ACCESS_REFUSED', `${k.label}: only the customer opens this kind of data; a partner sets no starting value for it`);
|
|
500
|
+
const after = { mode: next && next.mode, level: next && next.mode === 'open' ? next.level : null };
|
|
501
|
+
if (!R.validStart(after)) throw refused('ACCESS_INVALID', 'Choose May come in (look only or make changes) or Only when we let them in.');
|
|
502
|
+
const h = d();
|
|
503
|
+
const cur = (await partnerDefaultRows(h, pid)).find((x) => x.kind === k.key) || null;
|
|
504
|
+
const b = R.startOf(k, cur);
|
|
505
|
+
const before = { mode: b.mode, level: b.level };
|
|
506
|
+
if (cur && cur.mode === after.mode && (cur.level || null) === after.level) return { changed: false, kind: k.key, before, after };
|
|
507
|
+
const name = String(by.name || by.userId || 'partner admin').slice(0, 200);
|
|
508
|
+
await h.run('INSERT INTO customer_access_defaults (partner_id, kind, mode, level, set_by_name, set_by_user) VALUES (?, ?, ?, ?, ?, ?)',
|
|
509
|
+
[pid, k.key, after.mode, after.level, name, posInt(by.userId)]);
|
|
510
|
+
return { changed: true, kind: k.key, before, after, firstSave: !cur };
|
|
511
|
+
},
|
|
512
|
+
|
|
513
|
+
/**
|
|
514
|
+
* THE PARTNER'S CUSTOMERS AND WHAT EACH ALLOWS IT (the partner page): every customer of the partner with its
|
|
515
|
+
* settings per kind, live grant, managed mark, whether the mark is in force and may be set, and its staff's waiting
|
|
516
|
+
* requests there.
|
|
517
|
+
*/
|
|
518
|
+
async partnerCustomers(forPartner = null) {
|
|
519
|
+
const { pid } = staffScope({ forPartner });
|
|
520
|
+
const h = d();
|
|
521
|
+
const now = nowMs();
|
|
522
|
+
const rows = await h.all('SELECT id, name, status, partner_id, created_at FROM customers WHERE partner_id = ? ORDER BY name, id', [pid]);
|
|
523
|
+
const stored = knownRows(await h.all('SELECT customer_id, kind, mode, level, set_by_name, updated_at FROM customer_access_settings WHERE partner_id = ?', [pid]), 'customer_access_settings');
|
|
524
|
+
const defaults = await partnerDefaultRows(h, pid);
|
|
525
|
+
const grants = await h.all('SELECT * FROM customer_access_grants WHERE partner_id = ? AND ended_at IS NULL AND (ends_at IS NULL OR ends_at > ?)', [pid, R.stamp(now)]);
|
|
526
|
+
const managed = await h.all('SELECT customer_id, set_by_name, created_at FROM customer_access_managed WHERE partner_id = ?', [pid]);
|
|
527
|
+
const waiting = await h.all("SELECT customer_id, COUNT(*) AS n FROM customer_access_requests WHERE partner_id = ? AND state = 'waiting' AND expires_at > ? GROUP BY customer_id", [pid, R.stamp(now)]);
|
|
528
|
+
return rows.map((c) => {
|
|
529
|
+
const settings = settingsFrom(stored.filter((s) => s.customer_id === c.id), startsAt(defaults, c.created_at));
|
|
530
|
+
const list = settingList(settings);
|
|
531
|
+
const m = managed.find((x) => x.customer_id === c.id) || null;
|
|
532
|
+
const w = waiting.find((x) => x.customer_id === c.id);
|
|
533
|
+
return { id: c.id, name: c.name, status: c.status, created_at: c.created_at, settings,
|
|
534
|
+
grant: n(grants.find((g) => g.customer_id === c.id) || null), managed: m, managedInForce: R.managedInForce(list, m),
|
|
535
|
+
mayMark: c.status === 'active' && R.managedInForce(list, true), waiting: w ? Number(w.n) : 0 };
|
|
536
|
+
});
|
|
537
|
+
},
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* MARK / UNMARK "WE MANAGE THIS CUSTOMER" (the partner, at its own scope): `cus` one of its customers. Marking needs
|
|
541
|
+
* the customer active and every kind not set to Never at May come in (D-0014 answer 9); unmarking always works.
|
|
542
|
+
* → `{ changed, row }`.
|
|
543
|
+
*/
|
|
544
|
+
async setManaged(cus, on, by = {}) {
|
|
545
|
+
const { pid } = staffScope({ write: true });
|
|
546
|
+
if (!isId(cus)) throw refused('ACCESS_INVALID', 'not a customer');
|
|
547
|
+
const h = d();
|
|
548
|
+
const c = await customerRow(h, cus, pid);
|
|
549
|
+
if (!c) throw refused('ACCESS_REFUSED', 'not one of your customers');
|
|
550
|
+
const row = await managedRow(h, cus, pid);
|
|
551
|
+
if (!on) {
|
|
552
|
+
if (!row) return { changed: false, row: null };
|
|
553
|
+
const r = await h.run('DELETE FROM customer_access_managed WHERE id = ? AND customer_id = ? AND partner_id = ?', [row.id, cus, pid]);
|
|
554
|
+
return { changed: Number(r.changes) > 0, row };
|
|
555
|
+
}
|
|
556
|
+
if (row) return { changed: false, row };
|
|
557
|
+
if (c.status !== 'active') throw refused('ACCESS_REFUSED', 'this customer is not active');
|
|
558
|
+
if (!R.managedInForce(settingList(await settingsOf(h, c)), true)) {
|
|
559
|
+
throw refused('ACCESS_REFUSED', `${c.name} does not let you come in without asking (every kind it has not closed must be May come in); only its people can change that.`);
|
|
560
|
+
}
|
|
561
|
+
const name = String(by.name || by.userId || 'partner admin').slice(0, 200);
|
|
562
|
+
await guarded(() => h.run('INSERT INTO customer_access_managed (customer_id, partner_id, set_by_name, set_by_user) VALUES (?, ?, ?, ?)', [cus, pid, name, posInt(by.userId)]));
|
|
563
|
+
return { changed: true, row: await managedRow(h, cus, pid) };
|
|
564
|
+
},
|
|
565
|
+
|
|
566
|
+
/** The partner's staff's waiting requests at its customers, inside their 24 hours, newest first. */
|
|
567
|
+
async partnerRequests(forPartner = null, { limit = 50 } = {}) {
|
|
568
|
+
const { pid } = staffScope({ forPartner });
|
|
569
|
+
const rows = await d().all(`SELECT r.id, r.customer_id, r.user_id, r.user_name, r.reason, r.duration, r.level, r.created_at, r.expires_at, c.name AS customer_name
|
|
570
|
+
FROM customer_access_requests r JOIN customers c ON c.id = r.customer_id AND c.partner_id = r.partner_id
|
|
571
|
+
WHERE r.partner_id = ? AND r.state = 'waiting' AND r.expires_at > ? ORDER BY r.id DESC LIMIT ?`,
|
|
572
|
+
[pid, R.stamp(nowMs()), Math.min(Math.max(Number(limit) || 50, 1), LIST_MAX)]);
|
|
573
|
+
return rows.map((r) => ({ ...r, id: Number(r.id), user_id: Number(r.user_id) }));
|
|
574
|
+
},
|
|
575
|
+
|
|
576
|
+
/**
|
|
577
|
+
* THE SWEEP (the app's scheduler, every few minutes; PLATFORM scope only, never under a pin): grants past their end
|
|
578
|
+
* become `lapsed` (ended at their end), requests past their 24 hours `lapsed`. At most 500 of each per run.
|
|
579
|
+
* → `{ grants, requests }`, the rows lapsed with their partner and customer (audit.sweepAudit makes their rows).
|
|
580
|
+
*/
|
|
581
|
+
async sweep() {
|
|
582
|
+
const t = currentTenant();
|
|
583
|
+
if (!t || t.scope !== 'platform' || currentPin()) throw refused('ACCESS_REFUSED', 'the sweep runs at platform scope only');
|
|
584
|
+
const h = d();
|
|
585
|
+
const now = R.stamp(nowMs());
|
|
586
|
+
const grants = await h.all('SELECT id, partner_id, customer_id, level, ends_at FROM customer_access_grants WHERE ended_at IS NULL AND ends_at IS NOT NULL AND ends_at <= ? ORDER BY id LIMIT 500', [now]);
|
|
587
|
+
for (const g of grants) await h.run("UPDATE customer_access_grants SET ended_at = ends_at, ended_how = 'lapsed' WHERE id = ? AND partner_id = ? AND ended_at IS NULL", [g.id, g.partner_id]);
|
|
588
|
+
const requests = await h.all("SELECT id, partner_id, customer_id, user_id, user_partner_id, user_name, company, reason FROM customer_access_requests WHERE state = 'waiting' AND expires_at <= ? ORDER BY id LIMIT 500", [now]);
|
|
589
|
+
for (const r of requests) await h.run("UPDATE customer_access_requests SET state = 'lapsed' WHERE id = ? AND partner_id = ? AND state = 'waiting'", [r.id, r.partner_id]);
|
|
590
|
+
const out = (rows) => rows.map((r) => ({ ...r, id: Number(r.id), partner_id: Number(r.partner_id) }));
|
|
591
|
+
return { grants: out(grants), requests: out(requests) };
|
|
592
|
+
}
|
|
593
|
+
};
|
|
594
|
+
|
|
595
|
+
const own = Object.keys(store).sort();
|
|
596
|
+
const listed = [...ACCESS_CUSTOMER_SAFE, ...ACCESS_STAFF].sort();
|
|
597
|
+
if (own.join() !== listed.join()) throw new Error(`createAccessStore: internal: the methods (${own.join(', ')}) and the two lists (${listed.join(', ')}) disagree`);
|
|
598
|
+
return store;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
module.exports = { createAccessStore, ACCESS_CUSTOMER_SAFE, ACCESS_STAFF, refused };
|