@aria-framework/customer 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,25 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ _(not yet released)_
6
+
7
+ New package, part **access** (step 2 of the plan for the shared customer-driven piece, Platform D-0013). Needs
8
+ `@aria-framework/db-worker` 0.31.0 or later.
9
+
10
+ - Rules, version 2 of the model: no helper tier (one helper per customer, its partner; the house is the partner of its
11
+ own direct customers); a setting per kind of data; a grant per customer opening every kind not set to Never; the
12
+ managed mark in force only while every kind not set to Never is May come in (D-0014 answer 9). Moved from the first
13
+ customer-driven app's rules with the tier list, its helper functions and the house's separate starting value removed.
14
+ - `defineKinds`: the app's kinds of data, every field required.
15
+ - `createAccessStore`: the reads and writes of the five tables as one worker model (the customer's people, a pinned
16
+ helper, the partner's staff, a platform read for one partner, the sweep), with `ACCESS_CUSTOMER_SAFE` for the app's
17
+ customer-safe list. Every query states its partner.
18
+ - The tables as a db-worker definition set, `customer_access` 1.0.0, with new names for version 2
19
+ (`customer_access_settings`, `_defaults`, `_grants`, `_requests`, `_managed`), the manifest fragment and the schema
20
+ check; the columns the package needs of the app's `customers` and `customer_contacts` stated as anchors.
21
+ - The audit action names and words, and `sweepAudit`.
22
+ - A stored row of a kind the app no longer has is an error with status 500 (a kind a caller names: 400). The README says
23
+ what such a row blocks, that the store cannot tell whether fleet view is on, and one known race (a grant and an
24
+ all-Never save at the same moment).
25
+ - Not yet: visits, the record read back, people and roles, the kind locks in db-worker.
package/README.md CHANGED
@@ -1,3 +1,170 @@
1
- # Temporary Holding Version
1
+ # @aria-framework/customer
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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 (standard "Customer-driven apps", version 3).
5
+
6
+ This release, **0.1.0**, holds the first part, **access**: the customer's support-access setting per kind of data,
7
+ grants and requests, the partner's starting value and its "we manage this customer" mark, the sweep, the audit action
8
+ names, and the five tables as data. Visits (working in a customer) and people and roles are later parts.
9
+
10
+ Plain CommonJS, no build step. Peer: `@aria-framework/db-worker` 0.31.0 or later (the customer pin, table definitions).
11
+
12
+ ## The model (version 2: no helper tier)
13
+
14
+ - A customer has **one helper, its partner**. The house is the partner of the customers it sells to directly and gets
15
+ exactly what any partner gets (its starting value, the managed mark); it is never named on another partner's
16
+ customer. House staff reach a partner's customer only by working in that partner (the visits part).
17
+ - For each **kind of data** the customer chooses **May come in** (look only or make changes), **Only when we let them
18
+ in**, or **Never**. No stored row is the starting value.
19
+ - **Let them in now** (a grant) is for the whole customer: it opens every kind not set to Never, at its level, for 1
20
+ hour, 24 hours, 7 days or until switched off. One live grant per customer; a new one replaces the old.
21
+ - A helper may **ask to come in** (a reason, a time, a level). One waiting request per helper per customer; it ends
22
+ after 24 hours; the first answer (allow, allow look only, decline) settles it.
23
+ - **Never means closed.** When every kind is Never there is no grant and no request; saving that ends the live grant
24
+ and cancels the waiting requests. One kind set to Never closes that kind only.
25
+ - A partner sets the **starting value for its new customers**, per kind it may set, as May come in with a level or Only
26
+ when we let them in. It applies to a customer received strictly after it was saved (both stamps the database's
27
+ clock); a customer the partner already has keeps what it started at.
28
+ - **We manage this customer** waives the reason only, and only while every kind not set to Never is May come in. It
29
+ lets nobody in.
30
+
31
+ ## What the app passes
32
+
33
+ ```js
34
+ const { defineKinds, createAccessStore, ACCESS_CUSTOMER_SAFE, accessTenancy, assertAccessSchema } = require('@aria-framework/customer');
35
+
36
+ // its kinds of data (CD-06): every field required
37
+ const KINDS = defineKinds([
38
+ { key: 'content', label: 'Content', start: { mode: 'open', level: 'change' }, partnerMaySetStart: true },
39
+ { key: 'quotes', label: 'Quotes', start: { mode: 'never', level: null }, partnerMaySetStart: false }
40
+ ]);
41
+
42
+ // config/tenancy.js
43
+ module.exports = defineTenancy({ PARTNER: {...}, PLATFORM: {...}, CUSTOMER: {...}, ...accessTenancy() });
44
+
45
+ // the worker: models/CustomerAccess.js, and the customer-safe list
46
+ module.exports = createAccessStore({
47
+ driver: () => database.driver(), // a getter, read at every call
48
+ kinds: KINDS,
49
+ mayManage: async ({ partnerId, customerId, contactId }) => /* may this person change support access? */ false
50
+ });
51
+ createCustomerScope({ safe: { ...APP_SAFE, CustomerAccess: [...ACCESS_CUSTOMER_SAFE] }, models });
52
+
53
+ // at boot (after migrations), with the app's partner_id type
54
+ await assertAccessSchema(database.driver(), { partnerIdType: 'BIGINT' });
55
+ ```
56
+
57
+ Then `npx aria-tenancy new --definitions customer_access` writes the tables into the app's own migration pair, which
58
+ the app commits and never edits.
59
+
60
+ `mayManage` is the app's: which of the customer's people administer support access is a question of its people and
61
+ roles. The package also checks that the pin's contact is a contact of the pinned customer.
62
+
63
+ **Changing a kind later.** If an app changes a kind to `partnerMaySetStart: false`, its customers that had started at
64
+ 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
65
+ read). A customer's own stored setting is unchanged. Removing a kind from the list needs a migration first: see "A
66
+ retired kind" below.
67
+
68
+ ## What it exports
69
+
70
+ | Export | What it is |
71
+ |---|---|
72
+ | `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`) |
73
+ | `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` |
74
+ | `createAccessStore({ driver, kinds, mayManage, clock? })` | the store, one model for the app's worker (below) |
75
+ | `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 |
76
+ | `ACCESS_STAFF` | the store's other methods; each refuses under a pin |
77
+ | `accessTables`, `ACCESS_TABLES` | the table definition set `customer_access` 1.0.0 and its table names |
78
+ | `accessTenancy()` | the manifest fragment to spread into `defineTenancy` |
79
+ | `checkAccessSchema(driver, { partnerIdType })`, `assertAccessSchema(...)` | the schema check: `{ problems, compared }`, or a throw `TABLE_DEFINITIONS_MISMATCH` |
80
+ | `ACCESS_ACTIONS`, `ACCESS_ACTION_LABELS`, `ACCESS_ACTIONS_ABOUT_CUSTOMER` | the audit action names and their words |
81
+ | `sweepAudit(result)` | the sweep's answer as the audit rows to write, each in its customer's partner |
82
+
83
+ ## The store
84
+
85
+ | Called by | Methods |
86
+ |---|---|
87
+ | 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()` |
88
+ | A helper, pinned with no contact | `decide(userId)`, `ask({ userId, userPartnerId, userName, company, reason, duration, level })`, `cancel(id, userId)` |
89
+ | 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()` |
90
+ | 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) |
91
+ | The app's scheduler, platform scope only | `sweep()` |
92
+
93
+ **Platform reads and fleet view.** The store sees only the scope it runs in: a platform-scope call looks the same
94
+ whether the house is in fleet view or not. It refuses every write at platform scope, but it answers the reads for the
95
+ partner named. So the APP must refuse the platform-scope `listStates`, `partnerCustomers` and `partnerRequests` outside
96
+ fleet view: they list or name a partner's customers, and outside fleet view the house sees only its own customers
97
+ (CD-58; CD-42: another partner's Managed customers tab only in fleet view). `partnerDefaults` lists no customer and may
98
+ be read as a platform page (CD-42: a partner's Defaults shown to the house). At platform scope row-level security lets
99
+ every row through, so on Postgres the store's own `partner_id = ?` is the only bound on these reads (and on SQLite the
100
+ only bound at all); `test/store.pglite.js` holds each of their statements to it.
101
+
102
+ Every pinned method reads the customer and its partner from the pin, never from an argument. Every query states its
103
+ partner; at a partner's scope and under a pin, row-level security bounds every table on Postgres as well. Refusals
104
+ carry `code` and `status`: `ACCESS_REFUSED` (403), `ACCESS_INVALID` (400), `ACCESS_UNKNOWN_KIND` (400 for a kind the
105
+ caller names, 500 for a stored row, below), `ACCESS_BUSY`, `ACCESS_SETTLED`, `ACCESS_REQUEST_OPEN` (409). The store
106
+ writes no audit row: each method returns what changed, and the app writes the rows with its actor.
107
+
108
+ **A retired kind.** A stored row whose kind is not in the app's list is an error (`ACCESS_UNKNOWN_KIND`, status 500: the
109
+ server's own data is wrong), never skipped. What one such row blocks:
110
+
111
+ - a row in `customer_access_settings` blocks every method that reads that customer's settings: `state`, `decide`,
112
+ `setSettings`, `grant`, `answer` with allow or allow look only, `ask` and `setManaged` (marking); and the staff reads
113
+ that take in that customer's settings: `listStates` for any list naming that customer, and `partnerCustomers` for
114
+ the whole partner (it reads all of the partner's settings);
115
+ - a row in `customer_access_defaults` blocks the whole partner: the partner's starting-value rows are read for every
116
+ customer's settings (so every method above, for every customer of that partner), and by `listStates`,
117
+ `partnerCustomers`, `partnerDefaults` and `setPartnerDefault`.
118
+
119
+ Not blocked: `openRequests`, `endGrant`, `answer` with decline, `unmanage`, `cancel`, `setManaged` (unmarking),
120
+ `partnerRequests` and `sweep`. No method of the store clears such a row (a save naming a kind not in the list is
121
+ 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.
122
+
123
+ ## The tables
124
+
125
+ | Table | Tenancy | Keys |
126
+ |---|---|---|
127
+ | `customer_access_settings` | customer (`customer_id`) | unique (customer_id, partner_id, kind); `kind` NOT NULL |
128
+ | `customer_access_defaults` | partner (no customer column, no key into customers) | append-only; `kind` NOT NULL; index (partner_id, kind, created_at) |
129
+ | `customer_access_grants` | customer | one live grant per customer: unique (customer_id, partner_id) where `ended_at IS NULL` |
130
+ | `customer_access_requests` | customer | one waiting request per helper: unique (customer_id, partner_id, user_id) where `state = 'waiting'` |
131
+ | `customer_access_managed` | customer | one mark per customer: unique (customer_id, partner_id) |
132
+
133
+ Each customer table keys (customer_id, partner_id) to `customers (id, partner_id)` ON DELETE CASCADE ON UPDATE CASCADE
134
+ and carries the frozen customer policy; the partner table the partner policy. A user is a plain column with no key.
135
+ The names are new for version 2: an app holding the first app's version 1 tables creates these and drops those in one
136
+ migration.
137
+
138
+ **What the package needs of the app's own tables** (anchors; the schema check verifies them):
139
+ `customers (id TEXT, partner_id, name TEXT, status TEXT, created_at TEXT)` with a unique key on (id, partner_id), where
140
+ `status = 'active'` is active and `created_at` is UTC `YYYY-MM-DD HH:MM:SS` stamped by the database;
141
+ `customer_contacts (id TEXT, customer_id TEXT, partner_id, name TEXT)` with a unique key on (id, partner_id).
142
+
143
+ ## What stays the app's
144
+
145
+ Its kinds of data and their starting values; who of the customer's people manages support access (`mayManage`); the
146
+ routes, pages and texts; the audit trail and its actor; the scheduler that calls `sweep()` and writes `sweepAudit`'s
147
+ rows; telling helpers and admins (email, notifications).
148
+
149
+ ## What 0.1 does not do yet
150
+
151
+ - **Visits**: working in a customer (the level as the lowest of asked, allowed and the role; four hours; the reason; the
152
+ managed waiver applied; re-checking on every request; the banner), house staff coming in as the partner. The store
153
+ gives what a visit needs (`decide`, the allowance per kind with its grant's end, `managedInForce`).
154
+ - **The record read back**: who came in and who decided (read from the app's audit trail).
155
+ - **People and roles** and the portal session.
156
+ - **Kind locks in db-worker**: a customer-safe method naming its kind, and the policy text for tables of a closable kind.
157
+ - **The hub**: nothing of support access crosses to the hub.
158
+ - **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
159
+ people, can both commit: the save finds no live grant to end, the grant finds a kind still open. That leaves a live
160
+ grant under all-Never. It gives nothing while every kind is Never, but it would count again if a kind is opened later.
161
+ The source app has the same race. Not fixed in 0.1.
162
+ - How several kinds' states read as one cell of the Access column (decided with the first app that has several kinds);
163
+ `columnState` answers per kind.
164
+
165
+ ## Tests
166
+
167
+ `npm test` runs `test/run.js`: the rules as truth tables written out by hand (`rules.js`); the tables, the generated
168
+ migration and the package's words (`tables.js`); the store through a real worker on PGlite with real row-level security,
169
+ as a role that owns no table, with two partners, several customers of one partner and the same customer id under both
170
+ (`store.pglite.js`); and the schema check, clean and with each kind of difference planted (`schema.pglite.js`).
package/index.js ADDED
@@ -0,0 +1,17 @@
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", version 3).
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
+ *
8
+ * Later parts (visits, people and roles) are not in this release. The pin itself is @aria-framework/db-worker's; the
9
+ * session modes are @aria-framework/tenancy's. No permission name, route prefix or app word lives here: each is a
10
+ * setting the app passes.
11
+ */
12
+
13
+ 'use strict';
14
+
15
+ module.exports = {
16
+ ...require('./lib/access')
17
+ };
@@ -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 };
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Part "access": the customer's support-access setting per kind of data, its grants and requests, the partner's
3
+ * starting value and managed mark, the sweep, the audit action names, and the five tables as data.
4
+ */
5
+
6
+ 'use strict';
7
+
8
+ const rules = require('./rules');
9
+ const { defineKinds, isKinds } = require('./kinds');
10
+ const { accessTables, accessTenancy, checkAccessSchema, assertAccessSchema, ACCESS_TABLES } = require('./tables');
11
+ const { createAccessStore, ACCESS_CUSTOMER_SAFE, ACCESS_STAFF } = require('./store');
12
+ const { ACTIONS, ACTION_LABELS, ACTIONS_ABOUT_CUSTOMER, sweepAudit } = require('./audit');
13
+
14
+ module.exports = {
15
+ accessRules: rules,
16
+ defineKinds,
17
+ isKinds,
18
+ accessTables,
19
+ accessTenancy,
20
+ checkAccessSchema,
21
+ assertAccessSchema,
22
+ ACCESS_TABLES,
23
+ createAccessStore,
24
+ ACCESS_CUSTOMER_SAFE,
25
+ ACCESS_STAFF,
26
+ ACCESS_ACTIONS: ACTIONS,
27
+ ACCESS_ACTION_LABELS: ACTION_LABELS,
28
+ ACCESS_ACTIONS_ABOUT_CUSTOMER: ACTIONS_ABOUT_CUSTOMER,
29
+ sweepAudit
30
+ };
@@ -0,0 +1,61 @@
1
+ /**
2
+ * THE APP'S KINDS OF DATA (CD-06, CD-27): a part of a customer's content with its own support-access setting.
3
+ *
4
+ * defineKinds([{ key, label, start: { mode, level }, partnerMaySetStart }, ...])
5
+ *
6
+ * key a slug stored in the `kind` column of the settings and starting-value tables
7
+ * label the words a page shows for it
8
+ * start what the partner starts at for this kind when nothing is stored and the partner has set no value
9
+ * of its own: open with a level, ask, or never (an app may start a kind closed: CD-27's quotes)
10
+ * partnerMaySetStart true: a partner may set its own starting value for this kind (CD-39); false: only the customer
11
+ * opens it, and a partner's save for it is refused
12
+ *
13
+ * Every field is required, with no default: a starting value that "looks right" is exactly what gets shipped unread.
14
+ * An app with one kind passes a list of one.
15
+ */
16
+
17
+ 'use strict';
18
+
19
+ const R = require('./rules');
20
+
21
+ const KEY = /^[a-z][a-z0-9_]{0,39}$/;
22
+ const FIELDS = ['key', 'label', 'start', 'partnerMaySetStart'];
23
+ const KINDS = Symbol('customer access kinds');
24
+
25
+ function fail(message) {
26
+ throw Object.assign(new Error(`customer access kinds: ${message}`), { code: 'ACCESS_KINDS_REFUSED' });
27
+ }
28
+
29
+ /** Validate the app's list and return a frozen copy: `{ list, keys, byKey(key) }`. */
30
+ function defineKinds(list) {
31
+ if (isKinds(list)) return list;
32
+ if (!Array.isArray(list) || list.length === 0) fail('pass the app\'s kinds of data: a non-empty list of { key, label, start, partnerMaySetStart }');
33
+ const out = [];
34
+ for (const [i, k] of list.entries()) {
35
+ const at = `kind ${i + 1}`;
36
+ if (!k || typeof k !== 'object' || Array.isArray(k)) fail(`${at} is not an object`);
37
+ for (const f of Object.keys(k)) if (!FIELDS.includes(f)) fail(`${at}: unknown field "${f}" (known: ${FIELDS.join(', ')})`);
38
+ for (const f of FIELDS) if (!R.has(k, f)) fail(`${at}: ${f} is required`);
39
+ if (typeof k.key !== 'string' || !KEY.test(k.key)) fail(`${at}: key ${JSON.stringify(k.key)} is not a slug (a lower-case letter, then letters, digits, _; at most 40)`);
40
+ if (out.some((x) => x.key === k.key)) fail(`${at}: key "${k.key}" is used twice`);
41
+ if (typeof k.label !== 'string' || !k.label.trim()) fail(`${k.key}: label is required`);
42
+ const s = k.start;
43
+ if (!s || typeof s !== 'object' || Object.keys(s).some((f) => f !== 'mode' && f !== 'level')) fail(`${k.key}: start is { mode, level }`);
44
+ const start = { mode: s.mode, level: s.mode === 'open' ? s.level : (s.level == null ? null : s.level) };
45
+ if (!R.validSetting(start)) fail(`${k.key}: start ${JSON.stringify(s)} is not a setting (open with look or change; ask or never with no level)`);
46
+ if (typeof k.partnerMaySetStart !== 'boolean') fail(`${k.key}: partnerMaySetStart is true or false`);
47
+ out.push(Object.freeze({ key: k.key, label: k.label, start: Object.freeze(start), partnerMaySetStart: k.partnerMaySetStart }));
48
+ }
49
+ const keys = Object.freeze(out.map((k) => k.key));
50
+ const kinds = {
51
+ list: Object.freeze(out),
52
+ keys,
53
+ byKey(key) { return out.find((k) => k.key === key) || null; },
54
+ [KINDS]: true
55
+ };
56
+ return Object.freeze(kinds);
57
+ }
58
+
59
+ const isKinds = (v) => !!v && v[KINDS] === true;
60
+
61
+ module.exports = { defineKinds, isKinds };
@@ -0,0 +1,176 @@
1
+ /**
2
+ * WHO MAY COME IN: THE RULES, VERSION 2 (pure: no database, no session, no clock of their own).
3
+ *
4
+ * Moved from the first customer-driven app's rules (its lib/supportAccess.js) and changed for version 2 of the model
5
+ * ("Customer-driven apps" version 3; Platform D-0013, D-0014):
6
+ *
7
+ * NO TIER. A customer has one helper, its partner. The house is the partner of the customers it sells to
8
+ * directly and gets exactly what any partner gets; it is never named on another partner's customer
9
+ * (CD-02, CD-29). The tier list, `tiersOf`, `tierFor` and the house arm of the starting value are gone.
10
+ * KINDS. The customer's setting is kept PER KIND OF DATA (CD-26, CD-27). The rules below are kind-free: the
11
+ * answer for one kind is a function of that kind's own setting, the partner's starting value for that
12
+ * kind, the kind's own starting value, and the customer's live grant (which is not per kind: a grant
13
+ * lets the partner into every kind not set to Never, D-0013 answer 2). Nothing else.
14
+ *
15
+ * A SETTING open ("May come in", with a level: look | change) / ask ("Only when we let them in") / never.
16
+ * No stored row is the STARTING VALUE: the partner's own value for that kind, in force when the
17
+ * customer was received, where the app lets the partner set that kind (partnerMaySetStart); else the
18
+ * kind's own starting value from the app's list (CD-37, CD-39).
19
+ * A GRANT "Let them in now": a level and an end (or none: until switched off). Never means closed: under
20
+ * Never a grant gives nothing, whatever it says (CD-35).
21
+ * ALLOWANCE what the partner may do in one kind NOW: nothing under Never; else the higher of the setting's level
22
+ * (open only) and a live grant's level, or nothing.
23
+ * MANAGED the partner's "we manage this customer" mark waives the reason only. It is in force only while every
24
+ * kind not set to Never is May come in (D-0014 answer 9, CD-40) and at least one kind is (a customer
25
+ * closed in every kind lets nobody in, so there is nothing to waive). It lets nobody in.
26
+ *
27
+ * What a visit does with these (the lowest of asked, allowed and the helper's role; four hours; re-checked on every
28
+ * request) is the visits part of this package, not here.
29
+ */
30
+
31
+ 'use strict';
32
+
33
+ const MODES = Object.freeze(['open', 'ask', 'never']);
34
+ const LEVELS = Object.freeze(['look', 'change']);
35
+ const MODE_WORDS = Object.freeze({ open: 'May come in', ask: 'Only when we let them in', never: 'Never' });
36
+ const LEVEL_WORDS = Object.freeze({ look: 'look only', change: 'make changes' });
37
+ /** "Let them in now" and a request's wanted time: key → milliseconds (null: until switched off, grants only). */
38
+ const GRANT_FOR = Object.freeze({ '1h': 3600000, '24h': 86400000, '7d': 7 * 86400000, off: null });
39
+ const GRANT_WORDS = Object.freeze({ '1h': '1 hour', '24h': '24 hours', '7d': '7 days', off: 'until switched off' });
40
+ const REQUEST_FOR = Object.freeze(['1h', '24h', '7d']);
41
+ /** A request nobody answers ends after this long (CD-32). */
42
+ const REQUEST_LIVES_MS = 24 * 3600000;
43
+ const REASON_MAX = 300;
44
+ /** The customer's answers to a request: allow what was asked, allow look only, decline (CD-32). */
45
+ const ANSWERS = Object.freeze(['allow', 'allow_look', 'decline']);
46
+
47
+ const has = (o, k) => o != null && Object.prototype.hasOwnProperty.call(o, k);
48
+ const rank = (level) => LEVELS.indexOf(level); // -1 for none
49
+ const lower = (a, b) => (rank(a) < 0 || rank(b) < 0 ? null : (rank(a) <= rank(b) ? a : b));
50
+ const higher = (a, b) => (rank(a) < 0 ? (rank(b) < 0 ? null : b) : rank(b) < 0 ? a : (rank(a) >= rank(b) ? a : b));
51
+
52
+ /** Is `s` a setting a customer may store for a kind: open with a level, or ask / never with none? */
53
+ function validSetting(s) {
54
+ if (!s || typeof s !== 'object' || !MODES.includes(s.mode)) return false;
55
+ return s.mode === 'open' ? LEVELS.includes(s.level) : s.level == null;
56
+ }
57
+
58
+ /** Is `s` a starting value a partner may set for its new customers: open with a level, or ask (never Never, CD-39)? */
59
+ function validStart(s) {
60
+ if (!s || typeof s !== 'object') return false;
61
+ return s.mode === 'open' ? LEVELS.includes(s.level) : s.mode === 'ask' && s.level == null;
62
+ }
63
+
64
+ /** `{ mode, level }` with level null unless open. */
65
+ const plain = (s) => ({ mode: s.mode, level: s.mode === 'open' ? s.level : null });
66
+
67
+ /**
68
+ * THE STARTING VALUE of one kind for one customer: the partner's own value for this kind (`partnerStart`, the one in
69
+ * force when the customer was received; the store reads it) when the app lets the partner set this kind, else the
70
+ * kind's own. → `{ mode, level, byPartner }`. A partner value that is not a valid starting value throws: a stored row
71
+ * the rules cannot read is an error, never a default.
72
+ */
73
+ function startOf(kind, partnerStart = null) {
74
+ if (partnerStart != null && kind.partnerMaySetStart === true) {
75
+ if (!validStart({ mode: partnerStart.mode, level: partnerStart.level == null ? null : partnerStart.level })) {
76
+ throw new Error(`customer access: ${JSON.stringify(partnerStart)} is not a starting value a partner may set`);
77
+ }
78
+ return { ...plain(partnerStart), byPartner: true };
79
+ }
80
+ return { ...plain(kind.start), byPartner: false };
81
+ }
82
+
83
+ /** The setting in force for one kind: the stored row when there is one, else its starting value (CD-37). */
84
+ function settingOf(kind, stored, partnerStart = null) {
85
+ if (stored) {
86
+ if (!validSetting({ mode: stored.mode, level: stored.level == null ? null : stored.level })) {
87
+ throw new Error(`customer access: a stored setting ${JSON.stringify({ mode: stored.mode, level: stored.level })} for ${kind.key} is not a setting`);
88
+ }
89
+ return { ...plain({ mode: stored.mode, level: stored.level }), stored: true, byPartner: false };
90
+ }
91
+ return { ...startOf(kind, partnerStart), stored: false };
92
+ }
93
+
94
+ /** UTC 'YYYY-MM-DD HH:MM:SS' (the columns' form) ↔ ms. */
95
+ const stamp = (ms) => new Date(ms).toISOString().slice(0, 19).replace('T', ' ');
96
+ const msOf = (text) => (text ? Date.parse(String(text).replace(' ', 'T') + 'Z') : NaN);
97
+
98
+ /** Is a stored grant row live at `nowMs`: not ended, and its end (if any) still ahead? */
99
+ const grantLive = (g, nowMs) => !!g && !g.ended_at && (g.ends_at == null || msOf(g.ends_at) > nowMs);
100
+ /** Is a stored request still waiting at `nowMs`: not answered, and its 24 hours not up? */
101
+ const requestWaiting = (r, nowMs) => !!r && r.state === 'waiting' && msOf(r.expires_at) > nowMs;
102
+
103
+ /**
104
+ * WHAT THE PARTNER MAY DO NOW IN ONE KIND: `{ level, basis, grant, until }`: level 'look' | 'change' | null; basis
105
+ * 'setting' | 'grant' (the grant when it gives more: its end then bounds a visit); until = the grant's end in ms (null:
106
+ * none). `setting` {mode, level}; `grant` the customer's stored grant row, or null.
107
+ */
108
+ function allowance(setting, grant, nowMs) {
109
+ if (!Number.isFinite(nowMs)) throw new Error('customer access: allowance needs the time (ms)');
110
+ const none = { level: null, basis: null, grant: null, until: null };
111
+ if (!setting || setting.mode === 'never') return none;
112
+ const bySetting = setting.mode === 'open' && LEVELS.includes(setting.level) ? setting.level : null;
113
+ const g = grantLive(grant, nowMs) && LEVELS.includes(grant.level) ? grant : null;
114
+ const level = higher(bySetting, g ? g.level : null);
115
+ if (!level) return none;
116
+ // the setting first when it gives as much: a visit under "May come in" is not bounded by a grant that ends sooner
117
+ if (bySetting && rank(bySetting) >= rank(level)) return { level, basis: 'setting', grant: null, until: null };
118
+ return { level, basis: 'grant', grant: g, until: g.ends_at == null ? null : msOf(g.ends_at) };
119
+ }
120
+
121
+ /**
122
+ * THE ANSWER FOR ONE KIND: `{ kind, setting, allowance }` from that kind's own rows only: its stored setting (or null),
123
+ * the partner's starting value for it in force when the customer was received (or null), and the customer's grant.
124
+ */
125
+ function answerFor(kind, { stored = null, partnerStart = null, grant = null } = {}, nowMs) {
126
+ const setting = settingOf(kind, stored, partnerStart);
127
+ return { kind: kind.key, setting, allowance: allowance(setting, grant, nowMs) };
128
+ }
129
+
130
+ /** Every kind set to Never: the customer is closed to its partner (CD-35, CD-36): no grant, no request, no visit. */
131
+ const allClosed = (settings) => settings.length > 0 && settings.every((s) => s.mode === 'never');
132
+
133
+ /**
134
+ * IS THE "WE MANAGE THIS CUSTOMER" MARK IN FORCE: a mark stored, every kind not set to Never is May come in (D-0014
135
+ * answer 9), and at least one kind is. `settings` the settings in force, one per kind.
136
+ */
137
+ function managedInForce(settings, managed) {
138
+ if (!managed || !Array.isArray(settings) || settings.length === 0) return false;
139
+ const open = settings.filter((s) => s.mode !== 'never');
140
+ return open.length > 0 && open.every((s) => s.mode === 'open' && LEVELS.includes(s.level));
141
+ }
142
+
143
+ /**
144
+ * MAY A HELPER ASK TO COME IN AT `level`: 'closed' when every kind is Never (no request under Never, CD-35);
145
+ * 'already' when every kind not set to Never already allows that level; else null (the request may be made).
146
+ * `answers` the kinds' answers (answerFor).
147
+ */
148
+ function askRefusal(answers, level) {
149
+ if (allClosed(answers.map((a) => a.setting))) return 'closed';
150
+ const open = answers.filter((a) => a.setting.mode !== 'never');
151
+ if (open.every((a) => a.allowance.level && rank(a.allowance.level) >= rank(level))) return 'already';
152
+ return null;
153
+ }
154
+
155
+ /**
156
+ * WHAT THE ACCESS COLUMN SAYS FOR ONE KIND: `{ state, may, level, until, askedAt, requestId }`:
157
+ * may the setting lets the partner in (`level`)
158
+ * let_in a grant lets it in, until `until` (null: until switched off)
159
+ * waiting the viewer's request is out
160
+ * ask Only when we let them in
161
+ * closed Never
162
+ * How several kinds' states make one cell is decided with the first app that has several (D-0014 answer 11).
163
+ */
164
+ function columnState(answer, request, nowMs) {
165
+ const a = answer.allowance;
166
+ if (a.level) return { state: a.basis === 'grant' ? 'let_in' : 'may', may: true, level: a.level, until: a.until == null ? null : stamp(a.until) };
167
+ if (answer.setting.mode === 'never') return { state: 'closed', may: false };
168
+ if (requestWaiting(request, nowMs)) return { state: 'waiting', may: false, askedAt: request.created_at, requestId: Number(request.id) };
169
+ return { state: 'ask', may: false };
170
+ }
171
+
172
+ module.exports = {
173
+ MODES, LEVELS, MODE_WORDS, LEVEL_WORDS, GRANT_FOR, GRANT_WORDS, REQUEST_FOR, REQUEST_LIVES_MS, REASON_MAX, ANSWERS,
174
+ has, rank, lower, higher, validSetting, validStart, startOf, settingOf, stamp, msOf, grantLive, requestWaiting,
175
+ allowance, answerFor, allClosed, managedInForce, askRefusal, columnState
176
+ };