@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
package/README.md
CHANGED
|
@@ -1,3 +1,451 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @aria-framework/customer
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
What makes an app **customer-driven**: the customer's own people do the work in the app, and the partner that serves
|
|
4
|
+
the customer comes in to help only as far as the customer allows (the standard "Customer-driven apps"; part visits
|
|
5
|
+
follows its version 7).
|
|
6
|
+
|
|
7
|
+
This release, **0.2.0**, holds two parts. **Access** (0.1): the customer's support-access setting per kind of data,
|
|
8
|
+
grants and requests, the partner's starting value and its "we manage this customer" mark, the sweep, the audit action
|
|
9
|
+
names, and the five tables as data. **Visits** (0.2, below): working in one customer. People and roles are a later part.
|
|
10
|
+
|
|
11
|
+
Plain CommonJS, no build step. Peers: `@aria-framework/db-worker` 0.31.0 or later (the customer pin, table
|
|
12
|
+
definitions); `@aria-framework/tenancy` 0.5.0 or later (`asCustomer`, the session mode with `guardSave`); optional,
|
|
13
|
+
`express` 5 (the app passes its `Router`; the suites run Express 5.2).
|
|
14
|
+
|
|
15
|
+
## The model (version 2: no helper tier)
|
|
16
|
+
|
|
17
|
+
- A customer has **one helper, its partner**. The house is the partner of the customers it sells to directly and gets
|
|
18
|
+
exactly what any partner gets (its starting value, the managed mark); it is never named on another partner's
|
|
19
|
+
customer. House staff reach a partner's customer only by working in that partner (the visits part).
|
|
20
|
+
- For each **kind of data** the customer chooses **May come in** (look only or make changes), **Only when we let them
|
|
21
|
+
in**, or **Never**. No stored row is the starting value.
|
|
22
|
+
- **Let them in now** (a grant) is for the whole customer: it opens every kind not set to Never, at its level, for 1
|
|
23
|
+
hour, 24 hours, 7 days or until switched off. One live grant per customer; a new one replaces the old.
|
|
24
|
+
- A helper may **ask to come in** (a reason, a time, a level). One waiting request per helper per customer; it ends
|
|
25
|
+
after 24 hours; the first answer (allow, allow look only, decline) settles it.
|
|
26
|
+
- **Never means closed.** When every kind is Never there is no grant and no request; saving that ends the live grant
|
|
27
|
+
and cancels the waiting requests. One kind set to Never closes that kind only.
|
|
28
|
+
- A partner sets the **starting value for its new customers**, per kind it may set, as May come in with a level or Only
|
|
29
|
+
when we let them in. It applies to a customer received strictly after it was saved (both stamps the database's
|
|
30
|
+
clock); a customer the partner already has keeps what it started at.
|
|
31
|
+
- **We manage this customer** waives the reason only, and only while every kind not set to Never is May come in. It
|
|
32
|
+
lets nobody in.
|
|
33
|
+
|
|
34
|
+
## What the app passes
|
|
35
|
+
|
|
36
|
+
```js
|
|
37
|
+
const { defineKinds, createAccessStore, ACCESS_CUSTOMER_SAFE, accessTenancy, assertAccessSchema } = require('@aria-framework/customer');
|
|
38
|
+
|
|
39
|
+
// its kinds of data (CD-06): every field required
|
|
40
|
+
const KINDS = defineKinds([
|
|
41
|
+
{ key: 'content', label: 'Content', start: { mode: 'open', level: 'change' }, partnerMaySetStart: true },
|
|
42
|
+
{ key: 'quotes', label: 'Quotes', start: { mode: 'never', level: null }, partnerMaySetStart: false }
|
|
43
|
+
]);
|
|
44
|
+
|
|
45
|
+
// config/tenancy.js
|
|
46
|
+
module.exports = defineTenancy({ PARTNER: {...}, PLATFORM: {...}, CUSTOMER: {...}, ...accessTenancy() });
|
|
47
|
+
|
|
48
|
+
// the worker: models/CustomerAccess.js, and the customer-safe list
|
|
49
|
+
module.exports = createAccessStore({
|
|
50
|
+
driver: () => database.driver(), // a getter, read at every call
|
|
51
|
+
kinds: KINDS,
|
|
52
|
+
mayManage: async ({ partnerId, customerId, contactId }) => /* may this person change support access? */ false
|
|
53
|
+
});
|
|
54
|
+
createCustomerScope({ safe: { ...APP_SAFE, CustomerAccess: [...ACCESS_CUSTOMER_SAFE] }, models });
|
|
55
|
+
|
|
56
|
+
// at boot (after migrations), with the app's partner_id type
|
|
57
|
+
await assertAccessSchema(database.driver(), { partnerIdType: 'BIGINT' });
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Then `npx aria-tenancy new --definitions customer_access` writes the tables into the app's own migration pair, which
|
|
61
|
+
the app commits and never edits.
|
|
62
|
+
|
|
63
|
+
`mayManage` is the app's: which of the customer's people administer support access is a question of its people and
|
|
64
|
+
roles. The package also checks that the pin's contact is a contact of the pinned customer.
|
|
65
|
+
|
|
66
|
+
**Changing a kind later.** If an app changes a kind to `partnerMaySetStart: false`, its customers that had started at
|
|
67
|
+
their partner's value for that kind fall back to the kind's own starting value (the partner's rows for it are no longer
|
|
68
|
+
read). A customer's own stored setting is unchanged. Removing a kind from the list needs a migration first: see "A
|
|
69
|
+
retired kind" below.
|
|
70
|
+
|
|
71
|
+
## What it exports
|
|
72
|
+
|
|
73
|
+
| Export | What it is |
|
|
74
|
+
|---|---|
|
|
75
|
+
| `defineKinds(list)` | validates the app's kinds of data; frozen `{ list, keys, byKey }`. Refuses an empty list, a missing or unknown field, a key that is not a slug or is used twice, a start that is not a setting, a `partnerMaySetStart` that is not a boolean (`ACCESS_KINDS_REFUSED`) |
|
|
76
|
+
| `accessRules` | the pure rules: `allowance`, `answerFor`, `settingOf`, `startOf`, `managedInForce`, `allClosed`, `askRefusal`, `columnState`, `validSetting`, `validStart`, the words, `GRANT_FOR`, `REQUEST_FOR`, `REQUEST_LIVES_MS`, `REASON_MAX`, `ANSWERS`, `stamp`, `msOf`, `rank`, `lower`, `higher` |
|
|
77
|
+
| `createAccessStore({ driver, kinds, mayManage, clock? })` | the store, one model for the app's worker (below) |
|
|
78
|
+
| `ACCESS_CUSTOMER_SAFE` | the store's methods to add to the app's customer-safe list, as plain names. When db-worker later gives each customer-safe method a kind, a plain name will mean "of no kind": these methods are about the setting itself, not content of a kind, and stay callable whichever kinds are closed, so this list stays valid as it is |
|
|
79
|
+
| `ACCESS_STAFF` | the store's other methods; each refuses under a pin |
|
|
80
|
+
| `accessTables`, `ACCESS_TABLES` | the table definition set `customer_access` 1.0.0 and its table names |
|
|
81
|
+
| `accessTenancy()` | the manifest fragment to spread into `defineTenancy` |
|
|
82
|
+
| `checkAccessSchema(driver, { partnerIdType })`, `assertAccessSchema(...)` | the schema check: `{ problems, compared }`, or a throw `TABLE_DEFINITIONS_MISMATCH` |
|
|
83
|
+
| `ACCESS_ACTIONS`, `ACCESS_ACTION_LABELS`, `ACCESS_ACTIONS_ABOUT_CUSTOMER` | the audit action names and their words |
|
|
84
|
+
| `sweepAudit(result)` | the sweep's answer as the audit rows to write, each in its customer's partner |
|
|
85
|
+
|
|
86
|
+
## The store
|
|
87
|
+
|
|
88
|
+
| Called by | Methods |
|
|
89
|
+
|---|---|
|
|
90
|
+
| The customer's own people, pinned with their contact | `state()`, `openRequests()`; for a person `mayManage` accepts: `setSettings({ kind: { mode, level } })`, `grant({ duration, level })`, `endGrant(id)`, `answer(id, how)`, `unmanage()` |
|
|
91
|
+
| A helper, pinned with no contact | `decide(userId)`, `ask({ userId, userPartnerId, userName, company, reason, duration, level })`, `cancel(id, userId)` |
|
|
92
|
+
| The partner's staff at its own scope (the house: while working in that partner) | `listStates(userId, customers)`, `partnerDefaults()`, `setPartnerDefault(kind, { mode, level }, by)`, `partnerCustomers()`, `setManaged(customerId, on, by)`, `partnerRequests()` |
|
|
93
|
+
| Platform scope, reads only, for one stated partner. **The store cannot tell whether fleet view is on: the app must refuse the first three outside it** | `listStates(userId, customers, partnerId)`, `partnerCustomers(partnerId)`, `partnerRequests(partnerId)`: fleet view only (CD-42, CD-58). `partnerDefaults(partnerId)`: may be read as a platform page (CD-42) |
|
|
94
|
+
| The app's scheduler, platform scope only | `sweep()` |
|
|
95
|
+
|
|
96
|
+
**Platform reads and fleet view.** The store sees only the scope it runs in: a platform-scope call looks the same
|
|
97
|
+
whether the house is in fleet view or not. It refuses every write at platform scope, but it answers the reads for the
|
|
98
|
+
partner named. So the APP must refuse the platform-scope `listStates`, `partnerCustomers` and `partnerRequests` outside
|
|
99
|
+
fleet view: they list or name a partner's customers, and outside fleet view the house sees only its own customers
|
|
100
|
+
(CD-58; CD-42: another partner's Managed customers tab only in fleet view). `partnerDefaults` lists no customer and may
|
|
101
|
+
be read as a platform page (CD-42: a partner's Defaults shown to the house). At platform scope row-level security lets
|
|
102
|
+
every row through, so on Postgres the store's own `partner_id = ?` is the only bound on these reads (and on SQLite the
|
|
103
|
+
only bound at all); `test/store.pglite.js` holds each of their statements to it.
|
|
104
|
+
|
|
105
|
+
Every pinned method reads the customer and its partner from the pin, never from an argument. Every query states its
|
|
106
|
+
partner; at a partner's scope and under a pin, row-level security bounds every table on Postgres as well. Refusals
|
|
107
|
+
carry `code` and `status`: `ACCESS_REFUSED` (403), `ACCESS_INVALID` (400), `ACCESS_UNKNOWN_KIND` (400 for a kind the
|
|
108
|
+
caller names, 500 for a stored row, below), `ACCESS_BUSY`, `ACCESS_SETTLED`, `ACCESS_REQUEST_OPEN` (409). The store
|
|
109
|
+
writes no audit row: each method returns what changed, and the app writes the rows with its actor.
|
|
110
|
+
|
|
111
|
+
**A retired kind.** A stored row whose kind is not in the app's list is an error (`ACCESS_UNKNOWN_KIND`, status 500: the
|
|
112
|
+
server's own data is wrong), never skipped. What one such row blocks:
|
|
113
|
+
|
|
114
|
+
- a row in `customer_access_settings` blocks every method that reads that customer's settings: `state`, `decide`,
|
|
115
|
+
`setSettings`, `grant`, `answer` with allow or allow look only, `ask` and `setManaged` (marking); and the staff reads
|
|
116
|
+
that take in that customer's settings: `listStates` for any list naming that customer, and `partnerCustomers` for
|
|
117
|
+
the whole partner (it reads all of the partner's settings);
|
|
118
|
+
- a row in `customer_access_defaults` blocks the whole partner: the partner's starting-value rows are read for every
|
|
119
|
+
customer's settings (so every method above, for every customer of that partner), and by `listStates`,
|
|
120
|
+
`partnerCustomers`, `partnerDefaults` and `setPartnerDefault`.
|
|
121
|
+
|
|
122
|
+
Not blocked: `openRequests`, `endGrant`, `answer` with decline, `unmanage`, `cancel`, `setManaged` (unmarking),
|
|
123
|
+
`partnerRequests` and `sweep`. No method of the store clears such a row (a save naming a kind not in the list is
|
|
124
|
+
refused). The way out is a migration in the app that deletes the rows of a kind BEFORE the kind leaves the app's list.
|
|
125
|
+
|
|
126
|
+
## The tables
|
|
127
|
+
|
|
128
|
+
| Table | Tenancy | Keys |
|
|
129
|
+
|---|---|---|
|
|
130
|
+
| `customer_access_settings` | customer (`customer_id`) | unique (customer_id, partner_id, kind); `kind` NOT NULL |
|
|
131
|
+
| `customer_access_defaults` | partner (no customer column, no key into customers) | append-only; `kind` NOT NULL; index (partner_id, kind, created_at) |
|
|
132
|
+
| `customer_access_grants` | customer | one live grant per customer: unique (customer_id, partner_id) where `ended_at IS NULL` |
|
|
133
|
+
| `customer_access_requests` | customer | one waiting request per helper: unique (customer_id, partner_id, user_id) where `state = 'waiting'` |
|
|
134
|
+
| `customer_access_managed` | customer | one mark per customer: unique (customer_id, partner_id) |
|
|
135
|
+
|
|
136
|
+
Each customer table keys (customer_id, partner_id) to `customers (id, partner_id)` ON DELETE CASCADE ON UPDATE CASCADE
|
|
137
|
+
and carries the frozen customer policy; the partner table the partner policy. A user is a plain column with no key.
|
|
138
|
+
The names are new for version 2: an app holding the first app's version 1 tables creates these and drops those in one
|
|
139
|
+
migration.
|
|
140
|
+
|
|
141
|
+
**What the package needs of the app's own tables** (anchors; the schema check verifies them):
|
|
142
|
+
`customers (id TEXT, partner_id, name TEXT, status TEXT, created_at TEXT)` with a unique key on (id, partner_id), where
|
|
143
|
+
`status = 'active'` is active and `created_at` is UTC `YYYY-MM-DD HH:MM:SS` stamped by the database;
|
|
144
|
+
`customer_contacts (id TEXT, customer_id TEXT, partner_id, name TEXT)` with a unique key on (id, partner_id).
|
|
145
|
+
|
|
146
|
+
## What stays the app's
|
|
147
|
+
|
|
148
|
+
Its kinds of data and their starting values; who of the customer's people manages support access (`mayManage`); the
|
|
149
|
+
routes, pages and texts; the audit trail and its actor; the scheduler that calls `sweep()` and writes `sweepAudit`'s
|
|
150
|
+
rows; telling helpers and admins (email, notifications).
|
|
151
|
+
|
|
152
|
+
## Visits (0.2): working in one customer
|
|
153
|
+
|
|
154
|
+
A staff member steps into ONE customer of the partner they work for. Every request of the visit runs pinned to that
|
|
155
|
+
customer (the pin the customer's own portal uses, carrying no contact), at a level per kind of data, for a reason, for
|
|
156
|
+
at most four hours, re-checked on every request and live event, and recorded as two rows of the app's own audit trail
|
|
157
|
+
("Customer-driven apps" v7, CD-14 to CD-25, CD-44, CD-45, CD-50, CD-60).
|
|
158
|
+
|
|
159
|
+
### Wiring
|
|
160
|
+
|
|
161
|
+
```js
|
|
162
|
+
const { createVisits, viewsDir, assetsDir } = require('@aria-framework/customer');
|
|
163
|
+
|
|
164
|
+
const visits = createVisits({
|
|
165
|
+
tenancy, // what createTenancy returned
|
|
166
|
+
db, // the app's DbClient, built with { customerPin: true }
|
|
167
|
+
accessModel: 'CustomerAccess', // the model name createAccessStore is registered under
|
|
168
|
+
kinds: KINDS, // defineKinds()
|
|
169
|
+
levels: { // per kind: the permissions that look, and those that change
|
|
170
|
+
content: { look: ['notes.read'], change: ['notes.write', 'notes.drop'] },
|
|
171
|
+
quotes: { look: ['quotes.read'], change: ['quotes.write'] }
|
|
172
|
+
},
|
|
173
|
+
notCapped: ['bell.read'], // permissions a visit leaves to the role alone ([] for none)
|
|
174
|
+
permission: 'clients.enter', // the app's work-in permission
|
|
175
|
+
roleCan: (user, perm) => rbac.can(user.role, perm), // asked ONLY inside the user's HOME partner scope
|
|
176
|
+
requirePermission, // the app's own route guard (what visits.requirePermission is outside a visit)
|
|
177
|
+
partnerById: (id) => tenancy.asPlatform(() => db.invoke('Partner', 'byId', id)),
|
|
178
|
+
audit, // the app's audit helper (req, action, opts)
|
|
179
|
+
fleetView: fleet, // what createFleetView returned, or null
|
|
180
|
+
sessionEnding: (req) => idleOrVersionGone(req), // true when the app's own sign-in check is about to end this session
|
|
181
|
+
tellPartner: (facts) => notifyPartnerAdmins(facts), // CD-50, below
|
|
182
|
+
fitMemoMs: 5000, // 0 to 5000
|
|
183
|
+
mountPath: '/clients', // the Customers pages; the visit routes sit under it
|
|
184
|
+
mounts: [{ path: '/notes', kind: 'content' }, { path: '/quotes', kind: 'quotes' }],
|
|
185
|
+
outside: ['GET /notes/board', 'POST /notes/:id/clear'],
|
|
186
|
+
customerParams: { query: ['customer'], body: ['customer_id'] },
|
|
187
|
+
paths: { customers: '/clients', customer: (id) => `/clients/${id}`, landing: (visit) => '/notes' },
|
|
188
|
+
notPages: [/\/file$/, /\/thumb$/],
|
|
189
|
+
logger
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
app.use(session(/* … */));
|
|
193
|
+
app.use(fleet.loaded); app.use(visits.loaded); // directly after the session middleware
|
|
194
|
+
app.use(tenancy.requestScope()); app.use(canLocals);
|
|
195
|
+
app.use(fleet.middleware);
|
|
196
|
+
app.use(visits.track); // after the scope and fleet view's middleware,
|
|
197
|
+
app.use(fleet.routes(express.Router)); // BEFORE fleet view's routes and every router
|
|
198
|
+
app.post(STOP_ACTING_PATH, visits.endFirst('left')); // before the acting router
|
|
199
|
+
app.use(ACTING_MOUNT, actingRoutes({ /* … */ }));
|
|
200
|
+
app.use(visits.routes(express.Router)); // before the app's own Customers routes
|
|
201
|
+
app.use('/notes', visits.gate('content'), notesRouter); // each route guarded by visits.requirePermission(...)
|
|
202
|
+
app.use('/quotes', visits.gate('quotes'), quotesRouter);
|
|
203
|
+
app.set('views', [/* the app's */, viewsDir]);
|
|
204
|
+
app.use('/assets/customer', express.static(assetsDir)); // and <script src="/assets/customer/visit.js" defer>
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
The app's sign-out calls `await visits.end(req, 'signed_out')` before it destroys the session (and before fleet view's
|
|
208
|
+
`end`); a back-channel sign-out that deletes stored sessions calls `visits.recordEnded(storedSession)` for each; the
|
|
209
|
+
app's audit helper adds `visits.stampOf(req)` to every row; every write in the app that can narrow a customer's access
|
|
210
|
+
(its portal's setting, grant, End now and answer routes, the sweep) calls `visits.forget(customerId)` AFTER the write has
|
|
211
|
+
committed, and before it answers. Called before the write, a request landing between the two would keep the old answer
|
|
212
|
+
for `fitMemoMs`; a fit read already in flight when `forget()` runs is used by its own request only and never kept.
|
|
213
|
+
|
|
214
|
+
### What the app passes
|
|
215
|
+
|
|
216
|
+
Every option is required unless marked optional, and each is refused by name when missing or out of shape; an unknown
|
|
217
|
+
option is refused.
|
|
218
|
+
|
|
219
|
+
| Option | What it is |
|
|
220
|
+
|---|---|
|
|
221
|
+
| `tenancy` | createTenancy's object (`asCustomer`, `asPartner`, `contextFor`, `runWithTenant`) |
|
|
222
|
+
| `db` | the app's db client, built with `{ customerPin: true }` (else db-worker refuses the pinned reads) |
|
|
223
|
+
| `accessModel` | the model name of the app's `createAccessStore` (its `decide` must be on the customer-safe list, and so must the audit model's write) |
|
|
224
|
+
| `kinds` | what `defineKinds()` returned |
|
|
225
|
+
| `levels` | `{ [kind]: { look: [permission, …], change: [permission, …] } }` for every kind: `look` at least one; a permission in one kind and one level only |
|
|
226
|
+
| `notCapped` | the permissions a visit leaves to the role alone. Any other permission in no kind is refused inside a gated mount, and logged once |
|
|
227
|
+
| `permission` | the app's work-in permission (never in `levels`) |
|
|
228
|
+
| `roleCan(user, perm)` | the app's role check, synchronous, only `true` counts (a promise or a throw is refused and logged). Asked ONLY inside `runWithTenant({ scope: 'partner', partnerId: user.partner_id })`: a house person's role is judged at PARTNER scope at the house, so `permission`, `levels` and `notCapped` must name no platform-only permission (in the starter: email outbound, sign-in settings, partners, AI configuration, backup, secrets, debug, rate limits, fleet view). Pass `platformOnly` and the overlap is refused at construction |
|
|
229
|
+
| `requirePermission(...perms)` | the app's own route guard |
|
|
230
|
+
| `partnerById(id)` | a partner row `{ id, name }` (the start row's company; the partner's name for `tellPartner`) |
|
|
231
|
+
| `audit(req, action, opts)` | the app's audit helper; called inside the visit's partner's scope, given the request as the visit was MADE (its session acting as the visit's partner exactly when the visit was made so); it MUST return the promise of its write (an answer that is not a promise is an error naming `audit`, so a fire-and-forget helper stops every start); the start row's failure stops the start |
|
|
232
|
+
| `fleetView` | what tenancy 0.5.0's `createFleetView` returned, or `null`. `createVisits` registers a start check with it (`addStartCheck`), so fleet view's own start route refuses the switch during a visit, and asks its `inRow`. Its `readOnlyExcept` MUST list `POST <mountPath>/leave` (CD-21: Leave is never refused, and fleet view's read-only guard runs before every router): `createVisits` asks fleet view's own `classify` and refuses to build without it |
|
|
233
|
+
| `sessionEnding(req)` | true (or a promise of it) when the app's own sign-in check is about to end the session (its idle limit, a session version), so the stop row says `signed_out` before the session goes |
|
|
234
|
+
| `tellPartner(facts)` | CD-50: called (never awaited) when a house person, working in partner P, comes in to one of P's customers. `facts`: `{ partnerId, partnerName, customer: { id, name }, person: { id, name }, company: { id, name }, level, levels, reason, letIn, letInBy, visit, until }`. The app writes the notification to P's staff who hold its audit permission |
|
|
235
|
+
| `fitMemoMs` | 0 to 5000: how long an answer of the customer's setting is kept per visit (CD-22 allows five seconds) |
|
|
236
|
+
| `mountPath` | the full path of the Customers pages; the visit routes are `<mountPath>/:cus/work-in`, `<mountPath>/leave`, `<mountPath>/visit` |
|
|
237
|
+
| `mounts` | `[{ path, kind }]`: every gated mount (full paths) and its kind; none under another, none overlapping `mountPath` |
|
|
238
|
+
| `outside` | `"METHOD /path"` entries (fleet view's grammar; `GET` also lets `HEAD` through): the routes of a gated mount reachable outside a visit, each under a mount |
|
|
239
|
+
| `customerParams` | `{ query: [name], body: [name] }`: the parameters naming a customer, which a visit rewrites to its own (CD-25) |
|
|
240
|
+
| `paths` | `{ customers, customer(id), landing(visit) }`: local paths, checked when used |
|
|
241
|
+
| `notPages` | RegExps of full paths under a mount that are not pages (files, fragments): refused 403 outside a visit instead of sent to the Customers list |
|
|
242
|
+
| `logger` | `{ warn, error }` |
|
|
243
|
+
| `now` (optional) | the clock in ms (default `Date.now`) |
|
|
244
|
+
| `flash(req, res, kind, text)` (optional) | the app's flash (default `res.flash(kind, text, callback)`) |
|
|
245
|
+
| `wantsJson(req)`, `refusalView`, `messages` (optional) | as fleet view's: a refusal is JSON for a fetch, else `refusalView` (default `errors/generic`) with `{ title, message }`, else text. Each message is a non-empty sentence or a function returning one; `refusal` and `invalid` are objects of those by reason (checked at construction) |
|
|
246
|
+
| `caseSensitive` (optional) | `true` when the app set Express's "case sensitive routing": the mounts are then matched by case; default false, as Express's (a mount reached as `/NOTES` is the mount `/notes`). When it and the app's setting disagree, `track` says so once, at warn |
|
|
247
|
+
| `platformOnly` (optional) | the app's platform-only permissions: one named in `permission`, `levels` or `notCapped` is refused at construction |
|
|
248
|
+
|
|
249
|
+
### What it gives
|
|
250
|
+
|
|
251
|
+
| Member | What it does |
|
|
252
|
+
|---|---|
|
|
253
|
+
| `loaded` | keeps the session as loaded and guards its save (tenancy's session mode, `guardSave`), directly after the session; `track` refuses every request it did not see (500, `not-loaded`, logged) |
|
|
254
|
+
| `track` | every request: judges the visit, ends one that is over, sets `res.locals.visit`, `visitLocked`, `visitLockedText`, and `res.locals.fleetView.canStart = false` during a visit |
|
|
255
|
+
| `gate(kind)` | in front of each gated mount (below) |
|
|
256
|
+
| `requirePermission(...perms)` | the guard for the routes of a gated mount: in a pinned request the visit's `can`; elsewhere the app's own |
|
|
257
|
+
| `routes(Router)` | `POST <mountPath>/:cus/work-in` (body `level`, `reason`), `POST <mountPath>/leave`, `GET <mountPath>/visit` |
|
|
258
|
+
| `entry(req, customerId)` | the customer page's form: `{ customer, may, why, offered: { [kind]: level }, cappedBy: { [kind]: 'customer' \| 'role' }, reasonRequired, request, access, acting, partnerId }` |
|
|
259
|
+
| `end(req, 'left' \| 'signed_out')`, `endFirst(why)` | the app's own ends; `endFirst` is middleware |
|
|
260
|
+
| `recordEnded(session, why)` | the stop row of a session ended without a request |
|
|
261
|
+
| `stampOf(req)` | `{ working_in, visit }` in a request a gate pinned, else null (the audit helper's view of a request included) |
|
|
262
|
+
| `requestOf(req)` | the request behind the view the audit helper is given for a visit's own rows; any other value as given |
|
|
263
|
+
| `forStream(session)` | a live stream's visit (below) |
|
|
264
|
+
| `forget(customerId?)` | drop the kept answers of one customer (or all); call it after a narrowing write commits |
|
|
265
|
+
| `current(req)` | the visit in force for this request, or null |
|
|
266
|
+
| `classify(method, fullPath)` | `{ mount, kind, outside }`: what the gate does with a route, for the app's population tests |
|
|
267
|
+
| `isGate(fn)`, `isVisitGuard(fn)` | whether `fn` is a gate or a route guard this object made, for the app's wiring test over its route stacks (below) |
|
|
268
|
+
| `stats()` | `{ fitMemo, ended, fitMax, endedMax }`: how much this process holds (the fit memo at most 5000 answers; the visits it ended at most 10000, each kept at most four hours) |
|
|
269
|
+
| `VISIT_HOURS`, `VISIT_MS`, `VISIT_WORDS`, `VISIT_ENDINGS`, `VISIT_MARKER`, `VISIT_ACTIONS`, `VISIT_ACTION_LABELS`, `visitRules`, `viewsDir`, `assetsDir` | the constants, the pure rules, the two folders |
|
|
270
|
+
|
|
271
|
+
### The rules
|
|
272
|
+
|
|
273
|
+
- **The way in.** The visit's partner is the partner the request is in (`contextFor`): a partner's own staff at that
|
|
274
|
+
partner's customers; house staff not working in a partner at the house's own customers; house staff working in
|
|
275
|
+
partner P at P's customers, where they get exactly P's allowance. A house person not working in P who asks for P's
|
|
276
|
+
customer reads it under the house's own pin and gets 404 (`not-found`). Refused before anything is read: fleet view on
|
|
277
|
+
(`fleet-view`, CD-60), the HOME role without `permission` (`permission`). Then `inactive`, `closed` (every kind Never),
|
|
278
|
+
`role` (the customer lets the partner in somewhere the role, at home, gives nothing), `waiting` (the person's request
|
|
279
|
+
is out), `not-allowed` (ask to come in).
|
|
280
|
+
- **One at a time** (CD-21). Starting a visit while one is in force ends the first (`left`). Leave needs only a session.
|
|
281
|
+
The start writes the session only while the stored session holds no visit (a compare-and-write through the session
|
|
282
|
+
mode, guarded from before it sets the key, its notice flashed before the write), and once its write has landed reads
|
|
283
|
+
the row again (a CONFIRMING READ): two starts at once in two tabs leave one visit in force, and the other is refused
|
|
284
|
+
409 (`X-Work-In: busy`) with its start row paired by a stop row (`refused`, because `busy`) and its notice taken
|
|
285
|
+
back, so the trail never shows a visit that was not, except as below. The write and the confirming read also refuse a
|
|
286
|
+
row that no longer stands where the way in judged the start: fleet view switched on in another tab since (409
|
|
287
|
+
`fleet-view`, CD-60), or working in a partner started or stopped since (409 `acting` / `partner`); its start row is
|
|
288
|
+
paired (`refused`, because `fleet-view` / `acting` / `partner`), and a visit already stored there is ended through
|
|
289
|
+
the session mode (the start's own notice removed in that same write, another tab's kept). The place of a row is read
|
|
290
|
+
by tenancy's own `contextFor`, so with `actingRequiresActive` it follows tenancy's set of active partners: while that
|
|
291
|
+
set is unknown or stale (not loaded yet, failed, too old), a row working in a partner reads as NOT working in one.
|
|
292
|
+
That fails safe: a start judged not acting can then be written into such a row, and the confirming read (once the set
|
|
293
|
+
is known) or the next request's `track` (tenancy's `requestScope`, mounted before it, waits for the set on an acting
|
|
294
|
+
session) ends it, `refused`, `acting`. For a
|
|
295
|
+
partner KNOWN to be inactive, `contextFor` also deletes the acting keys from the row it is given, here the row the
|
|
296
|
+
start is about to write: the start's own save switches the person out of that partner, as tenancy would on their
|
|
297
|
+
next request. When the first visit's end did not land, the STORE decides, not the session in memory: another
|
|
298
|
+
visit in force → `busy`; signed out, or signed in again, in another tab → 409 `signed-out` (a start row already
|
|
299
|
+
written gets `signed_out`); no visit (left in another tab, with its own stop row) → the start goes on.
|
|
300
|
+
**What is left** (each allowed by `test/visitRaces.js` only where it is shown):
|
|
301
|
+
- two starts: a confirming read that answers BEFORE the other start's save lands sees this visit, so both starts
|
|
302
|
+
answer "started" and the earlier one's start row stays without a stop row (the check reads the store's timeline
|
|
303
|
+
and prints how many of its runs it was). Closing it needs an atomic compare-and-write in the session store. `track`
|
|
304
|
+
cannot write that missing row: the overwriting start read the row before this one landed, so nothing the session
|
|
305
|
+
holds afterwards names the overwritten visit, and the package keeps no record of its own (adding one is a new
|
|
306
|
+
store);
|
|
307
|
+
- any request that loaded the session BEFORE a start and saves it AFTER (a page in another tab that changed its
|
|
308
|
+
session, an activity stamp): its copy holds no visit and its save is not guarded (a session not in a visit is not),
|
|
309
|
+
so it overwrites the new visit, whose start row then has no stop row: the reader shows it as it shows an abandoned
|
|
310
|
+
visit ("at the latest", under "What is left, and the limits"). Guarding every request's save would close it, at
|
|
311
|
+
one store read per request; this release does not;
|
|
312
|
+
- a start and fleet view's switch whose writes cross within one store round trip: either the session is stored with
|
|
313
|
+
both, and the NEXT request's `track` ends the visit (`refused`, `fleet-view`) before anything else runs, so no
|
|
314
|
+
request runs in both; or fleet view's switch is lost (its start row written, the mode not stored).
|
|
315
|
+
- **The level** (CD-17, CD-19), per kind: the lowest of what was asked, the customer's allowance for that kind (its
|
|
316
|
+
setting, or the live grant), and the most the person's role allows for it (change when it holds any of the kind's
|
|
317
|
+
change permissions, look when it holds any of its look permissions), the role judged at the person's HOME partner.
|
|
318
|
+
A kind's level depends on that kind only. The visit exists while one kind has a level. The rows and the banner carry
|
|
319
|
+
`level`, the highest of the kinds' levels, beside `levels`.
|
|
320
|
+
- **The reason** (CD-15): required, trimmed, at most 300 characters; blank only at a customer whose managed mark is in
|
|
321
|
+
force, and only for the partner's own staff. A house person working in the partner always gives one.
|
|
322
|
+
- **Four hours** (CD-16): `until` is the sooner of `startedAt + VISIT_MS` and the end of the customer's grant when the
|
|
323
|
+
grant lets a kind in (the kind's setting alone would give less). `VISIT_WORDS` is the only text of that length.
|
|
324
|
+
- **Every request** (`track`, CD-22, CD-23), in this order: `sessionEnding` → `signed_out`; past `until` → `expired`; a
|
|
325
|
+
record out of shape → `refused` (`record`); another user or home partner (`user`); fleet view carried beside the
|
|
326
|
+
visit (fleet view's own `inRow`; CD-60's safety net, whatever race made it) → `refused` (`fleet-view`); started or stopped working in a
|
|
327
|
+
partner (`acting`), another partner in force (`partner`); the home role without `permission` (`role`); the fit read
|
|
328
|
+
under the pin: the customer active, at least one kind whose allowance and role maximum each still reach the visit's
|
|
329
|
+
level for it, and a reason-less visit's managed mark still in force (`setting`, or `role` when only the role falls
|
|
330
|
+
short). A throw from the app or the store ends it too (`error`). The end is written through the session mode, the
|
|
331
|
+
CD-23 sentence flashed before the write; the rest of the request is outside.
|
|
332
|
+
- **The gate** (`gate(kind)`). No visit: an `outside` entry passes; a page goes to `paths.customers`; anything else 403
|
|
333
|
+
(`outside`). In a visit: the kind not open → 403 (`closed`); look only and any method but GET, HEAD and OPTIONS → 403
|
|
334
|
+
(`look-only`, CD-18), before any route; else the `customerParams` the request names become the pin's customer
|
|
335
|
+
(CD-25), `res.locals.can` and `visits.requirePermission` become the visit's `can` (the kind open, the level, a change
|
|
336
|
+
permission only at make changes, the role at home; a permission in no kind refused unless not capped), and the rest
|
|
337
|
+
runs in `tenancy.asCustomer(partner, customer)` (CD-14). A session with no staff user is passed on to the app's own
|
|
338
|
+
sign-in gate. Every refusal the package makes carries `X-Work-In` (`outside`, `closed`, `look-only`, `permission`,
|
|
339
|
+
`no-gate`; from the start route `fleet-view`, `not-found`, …, `invalid`, `busy`, `signed-out`, `acting`, `partner`; from fleet view's start,
|
|
340
|
+
`leave-first`), and so does every wiring mistake it detects (500: `not-loaded` without `visits.loaded`, with it
|
|
341
|
+
mounted before the session middleware, or for a session holding a visit whose save tenancy's `isGuarded` says is not
|
|
342
|
+
guarded; `wiring` for a
|
|
343
|
+
gate in front of the wrong mount or a gate or status route with no `track` before it), each logged at error. A 403
|
|
344
|
+
from anything else carries none; an error the package did not detect (a store that throws) is the app's 500.
|
|
345
|
+
- **Fleet view** (CD-60): a visit cannot start in fleet view (the start route asks fleet view itself). While a session
|
|
346
|
+
holds a visit, fleet view's switch is refused, 403 "Leave <customer> first" (`leave-first`), by a check `createVisits`
|
|
347
|
+
registers with fleet view and fleet view's OWN start route asks (tenancy 0.5.0, `addStartCheck`), so every target
|
|
348
|
+
Express dispatches to that route is judged, whatever its spelling; a request `track` did not judge is refused too, and
|
|
349
|
+
logged. `res.locals.fleetView.canStart` is false. The visit is never ended by the switch. (The first build compared
|
|
350
|
+
the path in `track`, before the route, and `POST <startPath>#x` got through: see the CHANGELOG.) The check also reads
|
|
351
|
+
the stored row again when the session as loaded holds no visit (a visit started in another tab since is refused the
|
|
352
|
+
same way; a row it cannot read refuses the switch, logged), and from there guards fleet view's own save for the visit
|
|
353
|
+
key, so a visit that lands between that read and the save is kept, not wiped (the next request ends it, above).
|
|
354
|
+
Leave is never refused by fleet view (its `readOnlyExcept` lists `POST <mountPath>/leave`, required at construction).
|
|
355
|
+
- **Signing in again on a session that holds a visit.** The app's sign-in calls `visits.end(req, 'signed_out')` (or
|
|
356
|
+
`recordEnded` with the old session) BEFORE it calls `req.session.regenerate()`: regenerate drops the old session
|
|
357
|
+
with its visit, and nothing else writes that visit's stop row. A start in flight in another tab across the regenerate
|
|
358
|
+
is answered 409 `signed-out` ("You were signed out, or signed in again, in another tab").
|
|
359
|
+
- **The record** (CD-44, CD-45): `customer.work_in_start` (customer, visit, reason or `managed: true`, levels, level,
|
|
360
|
+
until, company: the person's home partner, `let_in` per kind, `grant` and `let_in_by` when a kind is let in by the
|
|
361
|
+
grant, `asked` when a kind got less than asked) and `customer.work_in_stop` (customer, visit, levels, level, ended,
|
|
362
|
+
`because` when refused, minutes, started_at), both in the trail of the partner the visit was made under. Version 2 of
|
|
363
|
+
the model has no helper tier, so neither row carries one (CD-44's "the tier" does not apply). Both rows carry
|
|
364
|
+
`acting_as_partner: <partner>` when the visit was MADE working in that partner, whatever the session says when the
|
|
365
|
+
row is written (a visit made working in A that ends after the person stopped, from another tab, still says so; a
|
|
366
|
+
house visit made at the house's own customer that ends after the person started working in A does not), and the
|
|
367
|
+
app's helper is given the request as the visit was made, so it stamps the same. Every other row of the visit is
|
|
368
|
+
stamped by `stampOf`. That request is a VIEW (a new object whose `session` says how the visit was made; every other
|
|
369
|
+
read passes through to the request): `stampOf` finds the request behind it, but a lookup of the helper's own keyed
|
|
370
|
+
by the request (a `WeakMap`) does not; `visits.requestOf(view)` gives the request itself (and any other value as
|
|
371
|
+
given).
|
|
372
|
+
- **Live streams** (CD-24): `await visits.forStream(storedSession)` per event → `null` (no visit, or one that is over:
|
|
373
|
+
the same judgement as `track`, without `sessionEnding`, since the stream's own session check stays the app's) or
|
|
374
|
+
`{ ctx, visit, can(perm), kindOpen(kind) }`. The stream's scope is `ctx` (the customer, no contact); an event of a kind
|
|
375
|
+
`kindOpen` refuses is not sent. It ends nothing: the session's next request does.
|
|
376
|
+
|
|
377
|
+
### The chrome
|
|
378
|
+
|
|
379
|
+
- `customer-visit-banner.ejs` (CD-20): "Working in <customer> · <level> · reason: '…' · ends <time>" (or "managed
|
|
380
|
+
customer, no reason asked"), class `alert-warning` for make changes and `alert-secondary` for look only, with Leave
|
|
381
|
+
and `data-work-in-banner`. Needs the app's `csrfToken()`. It uses the app's `formatDateTime` when there is one.
|
|
382
|
+
- `customer-visit-ended.ejs` (CD-23): the sentence it is given. `track` flashes the same sentence ("Your time in
|
|
383
|
+
<customer> has ended." or "You are no longer working in <customer>.", then "You are back on your own pages.") and sets
|
|
384
|
+
`res.locals.visitEnded` on the request that ended the visit.
|
|
385
|
+
- The menu: `res.locals.visit` has the facts (`customerName`, `customerPath`, `leavePath`, `level`, `levels`, `open`,
|
|
386
|
+
`reason`, `managed`, `until`, `acting`); the app draws its items (`data-work-in-menu`) and hides its admin doors.
|
|
387
|
+
- CD-18's disabled buttons: `res.locals.visitLocked(perm)` is true exactly for a change permission of an open kind
|
|
388
|
+
under look only that the role holds; draw that button disabled with `res.locals.visitLockedText` ("Look only: you
|
|
389
|
+
cannot make changes while working in <customer>").
|
|
390
|
+
- `assets/visit.js` (CD-23): on a page with the banner, every submit but Leave first asks `GET <mountPath>/visit`;
|
|
391
|
+
anything but `X-Work-In: live` cancels the submit, keeps the form under the notice and offers "Copy what you typed".
|
|
392
|
+
The server's gate stays the authority.
|
|
393
|
+
- No inline script, style or event handler in either partial; the CSS is the app's.
|
|
394
|
+
|
|
395
|
+
### What is left, and the limits
|
|
396
|
+
|
|
397
|
+
- **db-worker's kind locks are not in 0.2**: a closed kind is held by the gate and by `can()`, not yet by the worker or
|
|
398
|
+
a policy. A route outside every gated mount that reads a kind's data is not held at all: every content route belongs
|
|
399
|
+
under a gated mount.
|
|
400
|
+
- **The stop row, across processes**: each process ends a visit once; two processes ending the same visit at the same
|
|
401
|
+
moment can each write a stop row. The reader takes the earliest. A visit abandoned without another request has no
|
|
402
|
+
stop row until the session is read again (the reader says "at the latest").
|
|
403
|
+
- **The fit memo is per process**: `forget()` reaches this process only; another process's answer lands within
|
|
404
|
+
`fitMemoMs`.
|
|
405
|
+
- **What the save guard leaves** (tenancy's README): one store round trip between its read and its write.
|
|
406
|
+
- **What the rewrite does not reach** (CD-25). The gate rewrites only the `customerParams` names in `req.query` and in a
|
|
407
|
+
`req.body` already parsed when it runs. A body parsed AFTER the gate (a multipart upload, or any parser the app mounts
|
|
408
|
+
on the router itself) and a route's own params (`/x/:customer`) are never rewritten, and a name not listed (another
|
|
409
|
+
spelling, `customer[]` under the simple query parser) is not either. What still protects them: the pin, at the
|
|
410
|
+
database (row-level security's customer arm, and a model that names the pinned customer): a read finds no other
|
|
411
|
+
customer's rows, a write naming another customer is refused. What does NOT: anything that uses the named customer
|
|
412
|
+
without the database under the pin (a cache key, a file path, a call to another service, an email address looked up
|
|
413
|
+
elsewhere): such a route must take the customer from the visit (`visits.current(req)`), never from the request.
|
|
414
|
+
- **Routes in a gated mount must use `visits.requirePermission`**: the app's own guard judges the role in the request's
|
|
415
|
+
context, which in a visit by a house person is the partner's role of that name. A route under a mount listed in
|
|
416
|
+
`mounts` whose gate did not run (a gate the app forgot) is refused by `visits.requirePermission` (403, `no-gate`,
|
|
417
|
+
logged at error); a route there that carries no `visits.requirePermission` at all is not caught at run time. So an
|
|
418
|
+
app's wiring test walks each gated router's `stack` and asserts that every route either carries a handler for which
|
|
419
|
+
`visits.isVisitGuard(handler)` is true or is on its own short list of routes that need none, and that each gated
|
|
420
|
+
mount is `app.use(path, gateFn, router)` with `visits.isGate(gateFn)` (`test/visits.pglite.js` walks the fixture's
|
|
421
|
+
routers this way).
|
|
422
|
+
- The routes `<mountPath>/leave` and `<mountPath>/visit` sit beside the app's `<mountPath>/:id`: mount the package's
|
|
423
|
+
routes first, and use customer ids that can never be `leave` or `visit`.
|
|
424
|
+
|
|
425
|
+
## What 0.2 does not do yet
|
|
426
|
+
|
|
427
|
+
- **The record read back**: who came in and who decided (read from the app's audit trail).
|
|
428
|
+
- **People and roles** and the portal session.
|
|
429
|
+
- **Kind locks in db-worker**: a customer-safe method naming its kind, and the policy text for tables of a closable kind.
|
|
430
|
+
- **The hub**: nothing of support access crosses to the hub.
|
|
431
|
+
- **A known race.** A "let them in" and a save that closes every kind, made at the same moment by two of the customer's
|
|
432
|
+
people, can both commit: the save finds no live grant to end, the grant finds a kind still open. That leaves a live
|
|
433
|
+
grant under all-Never. It gives nothing while every kind is Never, but it would count again if a kind is opened later.
|
|
434
|
+
The source app has the same race. Not fixed in 0.1.
|
|
435
|
+
- How several kinds' states read as one cell of the Access column (decided with the first app that has several kinds);
|
|
436
|
+
`columnState` answers per kind.
|
|
437
|
+
|
|
438
|
+
## Tests
|
|
439
|
+
|
|
440
|
+
`npm test` runs `test/run.js`: the rules as truth tables written out by hand (`rules.js`); the tables, the generated
|
|
441
|
+
migration and the package's words in `lib/`, `views/`, `assets/` and this README (`tables.js`); the store through a real
|
|
442
|
+
worker on PGlite with real row-level security, as a role that owns no table, with two partners, several customers of
|
|
443
|
+
one partner and the same customer id under both (`store.pglite.js`); and the schema check, clean and with each kind of
|
|
444
|
+
difference planted (`schema.pglite.js`).
|
|
445
|
+
|
|
446
|
+
Visits: the rules as truth tables, the options, the two rows and a scan for a typed visit length (`visitRules.js`); a
|
|
447
|
+
real app (`visits-fixture.js`: express, express-session, tenancy's createTenancy, fleet view and acting routes, a role
|
|
448
|
+
table per partner where the house's and a partner's roles of the same name differ) over a real worker on PGlite with
|
|
449
|
+
row-level security (`visits.pglite.js`); the partials, the CSP scan and the asset on a hand-built DOM (`views.js`);
|
|
450
|
+
Leave, sign-out and another start across a slow request, each beside the twin without the save guard
|
|
451
|
+
(`visitRaces.js`).
|
package/assets/visit.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* @aria-framework/customer: THE TYPED-WORK NOTICE OF A VISIT (CD-23, owner's decision of 28 Nov 2026).
|
|
3
|
+
*
|
|
4
|
+
* When a visit ends while a helper is typing, the form stays where it is, under a notice, and what was typed can be
|
|
5
|
+
* copied. On a page that carries the visit banner ([data-work-in-banner]), every form submit except Leave first asks
|
|
6
|
+
* the visit's status route (the banner's data-work-in-status): X-Work-In "live" lets the form go as it was; anything
|
|
7
|
+
* else ("ended", "outside", an error) cancels the submit, puts the notice from the banner's template above the form
|
|
8
|
+
* (the server's sentence when it sends one), and its "Copy what you typed" button copies the form's typed fields.
|
|
9
|
+
*
|
|
10
|
+
* THE SERVER'S GATE STAYS THE AUTHORITY: this only keeps the typing. A submit that got through is judged there.
|
|
11
|
+
* Served by the app from the package's assetsDir and loaded with a script tag (src, defer); no inline script.
|
|
12
|
+
*/
|
|
13
|
+
(function () {
|
|
14
|
+
'use strict';
|
|
15
|
+
var doc = typeof document !== 'undefined' ? document : null;
|
|
16
|
+
if (!doc || typeof doc.addEventListener !== 'function') return;
|
|
17
|
+
var CHECKED = 'data-work-in-checked';
|
|
18
|
+
var TYPED = ['text', 'search', 'email', 'url', 'tel', 'number', ''];
|
|
19
|
+
|
|
20
|
+
/** The form's typed fields (text areas and text-like inputs), one after the other; never a hidden field. */
|
|
21
|
+
function typedOf(form) {
|
|
22
|
+
var out = [];
|
|
23
|
+
var els = form.elements || [];
|
|
24
|
+
for (var i = 0; i < els.length; i++) {
|
|
25
|
+
var el = els[i];
|
|
26
|
+
var tag = String(el.tagName || '').toUpperCase();
|
|
27
|
+
var type = String(el.type || '').toLowerCase();
|
|
28
|
+
if ((tag === 'TEXTAREA' || (tag === 'INPUT' && TYPED.indexOf(type) >= 0)) && el.value) out.push(String(el.value));
|
|
29
|
+
}
|
|
30
|
+
return out.join('\n\n');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Copy to the clipboard; without one (or refused), show the text in a box the person can copy from. */
|
|
34
|
+
function copy(notice, text) {
|
|
35
|
+
var shown = function () {
|
|
36
|
+
if (notice.querySelector('[data-work-in-typed]')) return;
|
|
37
|
+
var box = doc.createElement('textarea');
|
|
38
|
+
box.setAttribute('data-work-in-typed', '');
|
|
39
|
+
box.setAttribute('readonly', '');
|
|
40
|
+
box.value = text;
|
|
41
|
+
notice.appendChild(box);
|
|
42
|
+
};
|
|
43
|
+
var clip = typeof navigator !== 'undefined' && navigator.clipboard;
|
|
44
|
+
if (!clip || typeof clip.writeText !== 'function') return shown();
|
|
45
|
+
return clip.writeText(text).then(null, shown);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The notice above the form (one per form), with the server's sentence when there is one. */
|
|
49
|
+
function keep(form, text) {
|
|
50
|
+
var tpl = doc.querySelector('template[data-work-in-ended-template]');
|
|
51
|
+
if (!tpl || !tpl.content || !tpl.content.firstElementChild || !form.parentNode) return;
|
|
52
|
+
var prev = form.previousElementSibling;
|
|
53
|
+
if (prev && typeof prev.hasAttribute === 'function' && prev.hasAttribute('data-work-in-ended')) prev.parentNode.removeChild(prev);
|
|
54
|
+
var notice = tpl.content.firstElementChild.cloneNode(true);
|
|
55
|
+
var t = notice.querySelector('[data-work-in-ended-text]');
|
|
56
|
+
if (text && t) t.textContent = String(text);
|
|
57
|
+
var btn = notice.querySelector('[data-work-in-copy]');
|
|
58
|
+
if (btn) btn.addEventListener('click', function () { copy(notice, typedOf(form)); });
|
|
59
|
+
form.parentNode.insertBefore(notice, form);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
doc.addEventListener('submit', function (ev) {
|
|
63
|
+
var form = ev.target;
|
|
64
|
+
var banner = doc.querySelector('[data-work-in-banner]');
|
|
65
|
+
if (!banner || !form || String(form.tagName || '').toUpperCase() !== 'FORM') return;
|
|
66
|
+
if (form.hasAttribute('data-work-in-leave')) return;
|
|
67
|
+
if (form.getAttribute(CHECKED) === '1') { form.removeAttribute(CHECKED); return; }
|
|
68
|
+
var path = banner.getAttribute('data-work-in-status');
|
|
69
|
+
if (!path || typeof fetch !== 'function') return;
|
|
70
|
+
ev.preventDefault();
|
|
71
|
+
var submitter = ev.submitter || null;
|
|
72
|
+
fetch(path, { method: 'GET', credentials: 'same-origin', cache: 'no-store', headers: { Accept: 'application/json', 'X-Requested-With': 'fetch' } })
|
|
73
|
+
.then(function (r) {
|
|
74
|
+
var mark = r.headers.get('X-Work-In');
|
|
75
|
+
return r.json().then(function (body) { return { mark: mark, body: body }; }, function () { return { mark: mark, body: null }; });
|
|
76
|
+
})
|
|
77
|
+
.then(function (s) {
|
|
78
|
+
if (s.mark === 'live') {
|
|
79
|
+
form.setAttribute(CHECKED, '1');
|
|
80
|
+
if (typeof form.requestSubmit === 'function') { if (submitter) form.requestSubmit(submitter); else form.requestSubmit(); } else form.submit();
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
keep(form, s.body && s.body.text);
|
|
84
|
+
}, function () { keep(form, null); });
|
|
85
|
+
}, true);
|
|
86
|
+
}());
|
package/index.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @aria-framework/customer — what makes an app customer-driven: the customer's own people do the work, and the partner
|
|
3
|
+
* that serves them comes in only as far as the customer allows ("Customer-driven apps").
|
|
4
|
+
*
|
|
5
|
+
* lib/access 0.1: the customer's support-access setting per kind of data, grants, requests, the partner's starting
|
|
6
|
+
* value and managed mark, the sweep, the audit action names, the five tables as data
|
|
7
|
+
* lib/visits 0.2: working in one customer (a visit): the way in, the level per kind, the reason, four hours, the
|
|
8
|
+
* re-check on every request and live event, the gate, the two audit rows, the banner and the notices
|
|
9
|
+
*
|
|
10
|
+
* People and roles are a later part. The pin itself is @aria-framework/db-worker's; the session modes are
|
|
11
|
+
* @aria-framework/tenancy's. No permission name, route prefix or app word lives here: each is a setting the app passes.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
'use strict';
|
|
15
|
+
|
|
16
|
+
module.exports = {
|
|
17
|
+
...require('./lib/access'),
|
|
18
|
+
...require('./lib/visits')
|
|
19
|
+
};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE AUDIT ACTIONS OF SUPPORT ACCESS (CD-49): the customer's setting, grants, requests and the managed mark are audit
|
|
3
|
+
* rows about the customer, and the partner's starting value an audit row about the partner. The names are the ones the
|
|
4
|
+
* first app's trail already holds, so its rows read the same after it moves onto this package; the package writes no
|
|
5
|
+
* audit row itself (the trail, its actor and its catalogue are the app's): each store method returns what changed, and
|
|
6
|
+
* the app writes the rows with its own actor. `sweepAudit` turns the sweep's answer into the rows to write.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
'use strict';
|
|
10
|
+
|
|
11
|
+
const ACTIONS = Object.freeze({
|
|
12
|
+
settingChanged: 'support_access.setting_changed',
|
|
13
|
+
grantGiven: 'support_access.grant_given',
|
|
14
|
+
grantEnded: 'support_access.grant_ended',
|
|
15
|
+
grantLapsed: 'support_access.grant_lapsed',
|
|
16
|
+
requestMade: 'support_access.request_made',
|
|
17
|
+
requestAllowed: 'support_access.request_allowed',
|
|
18
|
+
requestDeclined: 'support_access.request_declined',
|
|
19
|
+
requestLapsed: 'support_access.request_lapsed',
|
|
20
|
+
requestCancelled: 'support_access.request_cancelled',
|
|
21
|
+
managedSet: 'support_access.managed_set',
|
|
22
|
+
managedCleared: 'support_access.managed_cleared',
|
|
23
|
+
partnerDefaultChanged: 'support_access.partner_default_changed'
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
/** The catalogue's words for each action (an app's audit catalogue spreads these). */
|
|
27
|
+
const ACTION_LABELS = Object.freeze({
|
|
28
|
+
[ACTIONS.settingChanged]: 'Support access setting changed',
|
|
29
|
+
[ACTIONS.grantGiven]: 'Helper let in',
|
|
30
|
+
[ACTIONS.grantEnded]: 'Let-in ended',
|
|
31
|
+
[ACTIONS.grantLapsed]: 'Let-in ran out',
|
|
32
|
+
[ACTIONS.requestMade]: 'Asked to come in',
|
|
33
|
+
[ACTIONS.requestAllowed]: 'Request to come in allowed',
|
|
34
|
+
[ACTIONS.requestDeclined]: 'Request to come in declined',
|
|
35
|
+
[ACTIONS.requestLapsed]: 'Request to come in ended unanswered',
|
|
36
|
+
[ACTIONS.requestCancelled]: 'Request to come in cancelled',
|
|
37
|
+
[ACTIONS.managedSet]: 'Marked as a customer we manage',
|
|
38
|
+
[ACTIONS.managedCleared]: 'No longer marked as a customer we manage',
|
|
39
|
+
[ACTIONS.partnerDefaultChanged]: 'Starting support access for new customers changed'
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
/** The actions about one customer (the customer's "who decided" list reads these), in a fixed order. */
|
|
43
|
+
const ACTIONS_ABOUT_CUSTOMER = Object.freeze(Object.values(ACTIONS).filter((a) => a !== ACTIONS.partnerDefaultChanged));
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* THE SWEEP'S AUDIT ROWS: the store's `sweep()` answer → `[{ partnerId, customerId, action, detail }]`, one per lapsed
|
|
47
|
+
* grant and lapsed request, each to be written in ITS customer's partner's trail by the system actor.
|
|
48
|
+
*/
|
|
49
|
+
function sweepAudit({ grants = [], requests = [] } = {}) {
|
|
50
|
+
return [
|
|
51
|
+
...grants.map((g) => ({ partnerId: Number(g.partner_id), customerId: g.customer_id, action: ACTIONS.grantLapsed,
|
|
52
|
+
detail: { customer: g.customer_id, grant: Number(g.id), level: g.level, until: g.ends_at } })),
|
|
53
|
+
...requests.map((r) => ({ partnerId: Number(r.partner_id), customerId: r.customer_id, action: ACTIONS.requestLapsed,
|
|
54
|
+
detail: { customer: r.customer_id, request: Number(r.id), helper: r.user_name, company: r.company } }))
|
|
55
|
+
];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
module.exports = { ACTIONS, ACTION_LABELS, ACTIONS_ABOUT_CUSTOMER, sweepAudit };
|