@12-apps/tenant 0.0.0-stage → 1.0.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/ADOPTING.md +128 -0
- package/README.md +65 -2
- package/package.json +77 -4
- package/prisma/migrations/20261126120000_tenant_closings_and_exports/migration.sql +56 -0
- package/prisma/tenant.prisma +88 -0
- package/scripts/sync-tenant-schema.mjs +73 -0
- package/src/config.ts +314 -0
- package/src/core.ts +65 -0
- package/src/hono/index.ts +17 -0
- package/src/index.ts +25 -0
- package/src/manifest/index.ts +19 -0
- package/src/port.ts +71 -0
- package/src/react/index.ts +28 -0
- package/src/server/index.ts +80 -0
- package/src/validate.ts +204 -0
package/ADOPTING.md
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
# Adopting @12-apps/tenant
|
|
2
|
+
|
|
3
|
+
Two halves, one factory each, one config object each. Nothing is optional.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
// backend
|
|
7
|
+
import { createApiTenant } from '@12-apps/tenant/server';
|
|
8
|
+
import { mountTenant } from '@12-apps/tenant/hono';
|
|
9
|
+
|
|
10
|
+
const tenant = createApiTenant({ statuses, ids, copy, port });
|
|
11
|
+
mountTenant(app, tenant); // mounts nothing yet: the routes arrive with the lifecycle
|
|
12
|
+
|
|
13
|
+
// frontend
|
|
14
|
+
import { createWebTenant } from '@12-apps/tenant/react';
|
|
15
|
+
|
|
16
|
+
const tenantUi = createWebTenant({ statuses, ids, copy });
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Both keep a deep-frozen COPY of the data parts (statuses, ids, copy): your own
|
|
20
|
+
objects are never frozen, and changing them after startup changes nothing.
|
|
21
|
+
Both throw a `TenantConfigError` at startup when a piece is missing or bad. Its
|
|
22
|
+
`key` is the dotted path (`ids.refusals.gone`, `copy.locales.pt-BR.closeWarning`,
|
|
23
|
+
`port.timeZone`), and its message says what is wrong with it.
|
|
24
|
+
|
|
25
|
+
## 1.0 — the contract, the port and the tables
|
|
26
|
+
|
|
27
|
+
Adopting this release changes no behaviour: the factories validate and hand back
|
|
28
|
+
readings, and the two new tables are created empty and read by nothing.
|
|
29
|
+
|
|
30
|
+
### The status set
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
const statuses = {
|
|
34
|
+
all: ['ACTIVE', 'CLOSING', 'CLOSED', 'SUSPENDED', 'PENDING'], // every value your row may hold
|
|
35
|
+
active: 'ACTIVE',
|
|
36
|
+
closing: 'CLOSING',
|
|
37
|
+
closed: 'CLOSED',
|
|
38
|
+
closableFrom: ['ACTIVE', 'SUSPENDED'], // the statuses a close may start from
|
|
39
|
+
};
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`all` lists every status, not only the ones the package acts on: the package
|
|
43
|
+
leaves any other status alone and never assumes there are none. The three roles
|
|
44
|
+
must be distinct and listed in `all`. `closableFrom` is non-empty, listed in
|
|
45
|
+
`all`, and never names `closing` or `closed`; a close records the status it
|
|
46
|
+
started from (`prior_status`) and a reopen restores it.
|
|
47
|
+
|
|
48
|
+
### The ids
|
|
49
|
+
|
|
50
|
+
Pass the ids your clients and your audit trail already use; the package never
|
|
51
|
+
makes one up, and two acts in one group may not share an id.
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
const ids = {
|
|
55
|
+
refusals: {
|
|
56
|
+
closing, closed, readOnly, gone, // a closing or closed tenant keeps a request out
|
|
57
|
+
reasonTooShort, nameMismatch, alreadyClosing, notActive, // a close refused
|
|
58
|
+
closingBlocked, purged, notClosing, // ...and a reopen refused
|
|
59
|
+
exportNeedsPerson, exportNotFound, exportExpired, // the data export refused
|
|
60
|
+
},
|
|
61
|
+
audit: { closeScheduled, closeReopened, closePurged, afterCloseFailed, exportRequested, exportDownloaded },
|
|
62
|
+
notifications: { closingScheduled, closingWeek, closingDay, reopened, exportReady }, // a failed export rides on exportReady
|
|
63
|
+
permissions: { close },
|
|
64
|
+
};
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### The copy packs
|
|
68
|
+
|
|
69
|
+
One pack per locale (`TenantCopyPack`), every key of `TENANT_COPY_SHAPE`, each
|
|
70
|
+
a whole sentence in your own vocabulary:
|
|
71
|
+
|
|
72
|
+
- **notices** (inbox and e-mail; the title is the subject): a title and a body
|
|
73
|
+
for scheduled, a week left, a day left, reopened, export ready and export
|
|
74
|
+
failed;
|
|
75
|
+
- **refusals**: one sentence per refusal code (`refusalBlocked(count)` writes
|
|
76
|
+
its own plural);
|
|
77
|
+
- **the close page, the banner and the refusal screens**: titles, buttons,
|
|
78
|
+
warnings and notes, with `blocker(kind, count)` and `shortcut(kind)` for your
|
|
79
|
+
own blocker kinds;
|
|
80
|
+
- **the platform's view**: `platformCancelClosing`, `platformClosingNote`.
|
|
81
|
+
|
|
82
|
+
A `text` key is a non-empty string; a `sentence` key is a function that returns
|
|
83
|
+
the whole sentence from the values it is given (a name, a count, a day already
|
|
84
|
+
formatted for the locale in the tenant's time zone). `defaultLocale` must be one
|
|
85
|
+
of the packs; `copyFor(locale)` answers it when the asked locale has no pack.
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
const copy = { locales: { 'pt-BR': ptBR, 'en-US': enUS }, defaultLocale: 'pt-BR' };
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### The tenant port (backend only)
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
const port: TenantPort<Status, Tx> = {
|
|
95
|
+
bySlug: (slug) => …, // the CURRENT slug only: { id, slug, status } | null
|
|
96
|
+
byId: (id, tx) => …, // on tx when given: { id, slug, status } | null
|
|
97
|
+
setStatusIf: (id, from, to, tx) => …, // compare-and-set ON tx: true only when the row moved
|
|
98
|
+
clearProfile: (tx, id) => …, // erase the row's profile, on tx
|
|
99
|
+
timeZone: (id) => …, // IANA zone
|
|
100
|
+
};
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
- **Run every write on the `tx` you are given**, never on a client of your own.
|
|
104
|
+
A close flips the status, recounts your blockers, writes its own row and the
|
|
105
|
+
audit line in ONE transaction: a blocker found after the flip rolls the flip
|
|
106
|
+
back only if the flip ran on that transaction.
|
|
107
|
+
- **`setStatusIf` is a real compare-and-set** (`UPDATE … SET status = $to WHERE
|
|
108
|
+
id = $id AND status = $from` on `tx`, answering whether a row changed): the
|
|
109
|
+
lifecycle relies on it to make each step happen once.
|
|
110
|
+
- **`byId` reads on `tx` when one is given**, so a refusal inside the
|
|
111
|
+
transaction sees the status the transaction sees.
|
|
112
|
+
- **`bySlug` resolves the tenant's current slug only.** A former slug you keep
|
|
113
|
+
for redirects is not answered here.
|
|
114
|
+
|
|
115
|
+
### The schema and the migration
|
|
116
|
+
|
|
117
|
+
- Copy the partial into your schema folder with
|
|
118
|
+
`pnpm --filter @12-apps/tenant prisma:sync` (`prisma:sync:check` fails on
|
|
119
|
+
drift). It is COPIED, never symlinked.
|
|
120
|
+
- The migration (`prisma/migrations/20261126120000_tenant_closings_and_exports`)
|
|
121
|
+
is discovered from the installed package like every other `@12-apps/*`
|
|
122
|
+
migration. It is additive: two new tables, no foreign key into yours.
|
|
123
|
+
- Moving existing closing or export rows into these tables is your own
|
|
124
|
+
expand-and-contract: copy and dual-write from the release that first writes
|
|
125
|
+
them, and drop your old tables only in a later release.
|
|
126
|
+
- **The tables have no foreign key, so nothing cascades.** A host that
|
|
127
|
+
hard-deletes a tenant row deletes that tenant's `tenant_closings` and
|
|
128
|
+
`tenant_data_exports` rows itself (or adds its own FK in a host migration).
|
package/README.md
CHANGED
|
@@ -1,3 +1,66 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @12-apps/tenant
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Domain-agnostic tenant behaviours. A tenant may be a shop, a hospital, a clinic
|
|
4
|
+
or anything else: the package knows only "tenant", and each host configures it
|
|
5
|
+
with its own vocabulary, ids, copy and a port onto its own tenant row.
|
|
6
|
+
|
|
7
|
+
This first release ships the **contract** every later behaviour extends:
|
|
8
|
+
|
|
9
|
+
- the config types: the host's full status set (with the statuses a close may
|
|
10
|
+
start from), the id set (refusal codes, audit action ids, notification type
|
|
11
|
+
ids, permission ids) and whole-sentence copy packs per locale. Every id and
|
|
12
|
+
sentence the later behaviours need is required already, so a later release
|
|
13
|
+
never adds a required piece to a host's config;
|
|
14
|
+
- the **tenant port** the package reaches the host's tenant row through:
|
|
15
|
+
`bySlug`, `byId(id, tx?)`, `setStatusIf(id, from, to, tx)`,
|
|
16
|
+
`clearProfile(tx, id)`, `timeZone(id)`. Its writes run on the caller's
|
|
17
|
+
transaction;
|
|
18
|
+
- `createApiTenant` and `createWebTenant`, which validate all of it at startup
|
|
19
|
+
and keep a deep-frozen copy of the data;
|
|
20
|
+
- the package's own tables, `tenant_closings` and `tenant_data_exports`, as a
|
|
21
|
+
Prisma partial with its own migration.
|
|
22
|
+
|
|
23
|
+
The lifecycle (close, reopen, the sweep), the purge and the data export arrive
|
|
24
|
+
in later releases on top of the same config. How to adopt it: [ADOPTING.md](./ADOPTING.md).
|
|
25
|
+
|
|
26
|
+
## Entry points
|
|
27
|
+
|
|
28
|
+
| Import | What | Needs |
|
|
29
|
+
|---|---|---|
|
|
30
|
+
| `@12-apps/tenant` | config types, `TenantPort`, `TenantConfigError`, the validators | nothing |
|
|
31
|
+
| `@12-apps/tenant/server` | `createApiTenant` | nothing |
|
|
32
|
+
| `@12-apps/tenant/hono` | `mountTenant(app, tenant)` | `hono` |
|
|
33
|
+
| `@12-apps/tenant/react` | `createWebTenant` | nothing yet |
|
|
34
|
+
| `@12-apps/tenant/manifest` | the wiring manifest (`db`) | `@12-apps/wiring` (types) |
|
|
35
|
+
|
|
36
|
+
## Rules the package keeps
|
|
37
|
+
|
|
38
|
+
- **Domain-agnostic.** `src/__tests__/domain-agnostic.test.ts` searches every
|
|
39
|
+
source file, as whole words and ignoring case, for the vocabulary of the host
|
|
40
|
+
the package was extracted from, and must find nothing.
|
|
41
|
+
- **Copy is config, as whole sentences.** No copy ships with the package. A noun
|
|
42
|
+
alone is not enough: in a gendered language the noun changes the rest of the
|
|
43
|
+
sentence. A sentence that carries a value (a count, a name, a day) is a
|
|
44
|
+
function the host writes, so plurals and word order stay the host's.
|
|
45
|
+
- **Ids are config.** Refusal codes, audit action ids, notification type ids and
|
|
46
|
+
permission ids are the host's, so its clients and its stored rows never change.
|
|
47
|
+
- **Required config, never defaults.** A missing piece throws a
|
|
48
|
+
`TenantConfigError` naming the key, at startup.
|
|
49
|
+
- **The tenant row stays the host's.** The package never maps it; its own tables
|
|
50
|
+
are keyed by an opaque `tenant_id` with no foreign key. `bySlug` resolves the
|
|
51
|
+
tenant's CURRENT slug only; former slugs a host keeps are the address
|
|
52
|
+
behaviour's, through a port of its own.
|
|
53
|
+
|
|
54
|
+
## Tables
|
|
55
|
+
|
|
56
|
+
| Table | Rows |
|
|
57
|
+
|---|---|
|
|
58
|
+
| `tenant_closings` | one per tenant while it is closing, kept once purged; reopening deletes it |
|
|
59
|
+
| `tenant_data_exports` | one per export request; at most one `PREPARING` per tenant |
|
|
60
|
+
|
|
61
|
+
`tenant_closings.prior_status` records the host status a close started from (a
|
|
62
|
+
suspended tenant may be closed by the platform), so a reopen restores it. The
|
|
63
|
+
actor is `requested_by_id`: a user id, or null for a platform actor with no user
|
|
64
|
+
row, so no separate actor column exists. `after_close_done_at` /
|
|
65
|
+
`after_close_failed_at` record the host's after-close hook (a billing cancel, for
|
|
66
|
+
instance), which the package retries but never names.
|
package/package.json
CHANGED
|
@@ -1,6 +1,79 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@12-apps/tenant",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"sideEffects": false,
|
|
7
|
+
"description": "Domain-agnostic tenant behaviours: the lifecycle of a tenant (closing, reopening, the purge and the data export), configured by each host with its own status set, ids, copy packs and a required tenant port. The tenant row stays the host's: the package reads and writes it only through the port, and owns two tables of its own (tenant_closings, tenant_data_exports) keyed by an opaque tenant id with no foreign key. Backend factory (./server), Hono mount (./hono), frontend factory (./react) and the package-owned Prisma partial + migrations. Adoption contract in ADOPTING.md.",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./src/index.ts",
|
|
10
|
+
"./server": "./src/server/index.ts",
|
|
11
|
+
"./hono": "./src/hono/index.ts",
|
|
12
|
+
"./react": "./src/react/index.ts",
|
|
13
|
+
"./manifest": "./src/manifest/index.ts",
|
|
14
|
+
"./package.json": "./package.json"
|
|
15
|
+
},
|
|
16
|
+
"scripts": {
|
|
17
|
+
"lint": "eslint src --max-warnings 0",
|
|
18
|
+
"check-types": "tsc --noEmit",
|
|
19
|
+
"typecheck": "tsc --noEmit",
|
|
20
|
+
"test": "node ../../scripts/vitest-with-teardown.mjs run",
|
|
21
|
+
"test:watch": "vitest watch",
|
|
22
|
+
"prisma:sync": "node scripts/sync-tenant-schema.mjs",
|
|
23
|
+
"prisma:sync:check": "node scripts/sync-tenant-schema.mjs --check",
|
|
24
|
+
"clean": "rm -rf node_modules coverage dist"
|
|
25
|
+
},
|
|
26
|
+
"peerDependencies": {
|
|
27
|
+
"@12-apps/wiring": ">=1.3.0",
|
|
28
|
+
"hono": ">=4.0.0"
|
|
29
|
+
},
|
|
30
|
+
"peerDependenciesMeta": {
|
|
31
|
+
"@12-apps/wiring": {
|
|
32
|
+
"optional": true
|
|
33
|
+
},
|
|
34
|
+
"hono": {
|
|
35
|
+
"optional": true
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@12-apps/eslint-config": "^1.22.0",
|
|
40
|
+
"@12-apps/typescript-config": "^1.21.0",
|
|
41
|
+
"@12-apps/wiring": "^1.17.0",
|
|
42
|
+
"@electric-sql/pglite": "^0.2.17",
|
|
43
|
+
"@types/node": "^22.15.3",
|
|
44
|
+
"eslint": "^9.39.1",
|
|
45
|
+
"eslint-plugin-test-flakiness": "^1.4.0",
|
|
46
|
+
"hono": "^4.6.0",
|
|
47
|
+
"typescript": "^5.9.2",
|
|
48
|
+
"vitest": "^3.2.4"
|
|
49
|
+
},
|
|
50
|
+
"engines": {
|
|
51
|
+
"node": ">=22.0.0"
|
|
52
|
+
},
|
|
53
|
+
"publishConfig": {
|
|
54
|
+
"registry": "https://registry.npmjs.org",
|
|
55
|
+
"access": "public"
|
|
56
|
+
},
|
|
57
|
+
"repository": {
|
|
58
|
+
"type": "git",
|
|
59
|
+
"url": "git+https://github.com/12-apps/shared-packages.git",
|
|
60
|
+
"directory": "packages/tenant"
|
|
61
|
+
},
|
|
62
|
+
"files": [
|
|
63
|
+
"src",
|
|
64
|
+
"prisma",
|
|
65
|
+
"scripts",
|
|
66
|
+
"*.md",
|
|
67
|
+
"!eslint.config.js",
|
|
68
|
+
"!**/__tests__/**",
|
|
69
|
+
"!**/tests/**",
|
|
70
|
+
"!**/*.test.*",
|
|
71
|
+
"!**/*.spec.*"
|
|
72
|
+
],
|
|
73
|
+
"wiring": {
|
|
74
|
+
"db": {
|
|
75
|
+
"partial": "prisma/tenant.prisma",
|
|
76
|
+
"migrations": "prisma/migrations"
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
-- The tenant lifecycle's own tables. Two new tables, so additive: the previous
|
|
2
|
+
-- release never reads them, and nothing reads them until a host wires the
|
|
3
|
+
-- lifecycle. Keyed by an opaque `tenant_id` with NO foreign key: the tenant row
|
|
4
|
+
-- is the host's.
|
|
5
|
+
--
|
|
6
|
+
-- `tenant_closings`: one row per tenant while it is closing — when, by whom,
|
|
7
|
+
-- why, the status it started from, when it is purged, the two reminder stamps,
|
|
8
|
+
-- the after-close hook's outcome, and the storage keys the purge still owes.
|
|
9
|
+
--
|
|
10
|
+
-- `tenant_data_exports`: one row per export request — its state
|
|
11
|
+
-- (PREPARING | READY | FAILED), where the private archive is stored, when its
|
|
12
|
+
-- link expires, and whether it was mailed. At most ONE PREPARING row per
|
|
13
|
+
-- tenant (the partial unique index).
|
|
14
|
+
|
|
15
|
+
CREATE TABLE "tenant_closings" (
|
|
16
|
+
"tenant_id" TEXT NOT NULL,
|
|
17
|
+
"requested_at" TIMESTAMP(3) NOT NULL,
|
|
18
|
+
"requested_by_id" TEXT,
|
|
19
|
+
"reason" TEXT NOT NULL,
|
|
20
|
+
"prior_status" TEXT,
|
|
21
|
+
"purge_at" TIMESTAMP(3) NOT NULL,
|
|
22
|
+
"reminded_week_at" TIMESTAMP(3),
|
|
23
|
+
"reminded_day_at" TIMESTAMP(3),
|
|
24
|
+
"purged_at" TIMESTAMP(3),
|
|
25
|
+
"after_close_done_at" TIMESTAMP(3),
|
|
26
|
+
"after_close_failed_at" TIMESTAMP(3),
|
|
27
|
+
"image_keys_owed" TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[],
|
|
28
|
+
"images_erased_at" TIMESTAMP(3),
|
|
29
|
+
|
|
30
|
+
CONSTRAINT "tenant_closings_pkey" PRIMARY KEY ("tenant_id")
|
|
31
|
+
);
|
|
32
|
+
|
|
33
|
+
CREATE INDEX "tenant_closings_purge_at_idx" ON "tenant_closings"("purge_at");
|
|
34
|
+
|
|
35
|
+
CREATE TABLE "tenant_data_exports" (
|
|
36
|
+
"id" TEXT NOT NULL,
|
|
37
|
+
"tenant_id" TEXT NOT NULL,
|
|
38
|
+
"requested_by_id" TEXT NOT NULL,
|
|
39
|
+
"status" TEXT NOT NULL,
|
|
40
|
+
"requested_at" TIMESTAMP(3) NOT NULL,
|
|
41
|
+
"started_at" TIMESTAMP(3),
|
|
42
|
+
"ready_at" TIMESTAMP(3),
|
|
43
|
+
"expires_at" TIMESTAMP(3),
|
|
44
|
+
"storage_key" TEXT,
|
|
45
|
+
"size_bytes" INTEGER,
|
|
46
|
+
"attempts" INTEGER NOT NULL DEFAULT 0,
|
|
47
|
+
"notified_at" TIMESTAMP(3),
|
|
48
|
+
"deleted_at" TIMESTAMP(3),
|
|
49
|
+
|
|
50
|
+
CONSTRAINT "tenant_data_exports_pkey" PRIMARY KEY ("id"),
|
|
51
|
+
CONSTRAINT "tenant_data_exports_status_check" CHECK ("status" IN ('PREPARING', 'READY', 'FAILED'))
|
|
52
|
+
);
|
|
53
|
+
|
|
54
|
+
CREATE INDEX "tenant_data_exports_tenant_id_requested_at_idx" ON "tenant_data_exports"("tenant_id", "requested_at");
|
|
55
|
+
CREATE INDEX "tenant_data_exports_status_requested_at_idx" ON "tenant_data_exports"("status", "requested_at");
|
|
56
|
+
CREATE UNIQUE INDEX "tenant_data_exports_one_preparing_key" ON "tenant_data_exports"("tenant_id") WHERE "status" = 'PREPARING';
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
2
|
+
// OWNED BY @12-apps/tenant — the host's multi-file schema folder holds a COPY of
|
|
3
|
+
// this file, written by `pnpm --filter @12-apps/tenant prisma:sync`.
|
|
4
|
+
//
|
|
5
|
+
// COPIED, never symlinked (the entity-lifecycle doctrine): `npm pack` silently
|
|
6
|
+
// drops symlinked entries, `turbo prune` dangles a link whose owner is not a
|
|
7
|
+
// declared dependency, and Prisma silently SKIPS a symlinked migration
|
|
8
|
+
// directory — a green deploy that applied no schema.
|
|
9
|
+
//
|
|
10
|
+
// Deliberately self-contained (the @12-apps/auth doctrine): every tenant
|
|
11
|
+
// reference is a `tenant_id` String column — NO foreign key into any host table
|
|
12
|
+
// — so these models work in a repo whose tenant table is called anything, or
|
|
13
|
+
// is in another database. The tenant row itself, its slugs and its domains
|
|
14
|
+
// stay the host's: Prisma refuses two models on one table, so the package
|
|
15
|
+
// reaches the row only through the tenant port (`TenantPort`).
|
|
16
|
+
//
|
|
17
|
+
// Statuses are Strings + DB CHECK (the house style), never a Prisma enum.
|
|
18
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
19
|
+
|
|
20
|
+
/// A tenant's close: one row while the tenant is closing, kept once the purge
|
|
21
|
+
/// ran (`purged_at`). When it was confirmed and by whom, the reason the person
|
|
22
|
+
/// typed, the status the close started from, when the data is purged, the two
|
|
23
|
+
/// reminder stamps the sweep writes only AFTER the notice is recorded (so
|
|
24
|
+
/// neither reminder is sent twice), and the host's after-close hook's outcome.
|
|
25
|
+
/// Reopening deletes the row.
|
|
26
|
+
model TenantClosing {
|
|
27
|
+
/// The host's tenant id, opaque. See the header — no FK.
|
|
28
|
+
tenantId String @id @map("tenant_id")
|
|
29
|
+
requestedAt DateTime @map("requested_at")
|
|
30
|
+
/// Who confirmed, the host's user id; null for a platform actor with no user
|
|
31
|
+
/// row. That null IS the platform actor: no separate actor column. No FK.
|
|
32
|
+
requestedById String? @map("requested_by_id")
|
|
33
|
+
reason String
|
|
34
|
+
/// The host status the close started from (any value of its status set, a
|
|
35
|
+
/// suspended one included); reopening restores it. Null on a row copied
|
|
36
|
+
/// from before this column existed, which reopens to the active status.
|
|
37
|
+
priorStatus String? @map("prior_status")
|
|
38
|
+
purgeAt DateTime @map("purge_at")
|
|
39
|
+
remindedWeekAt DateTime? @map("reminded_week_at")
|
|
40
|
+
remindedDayAt DateTime? @map("reminded_day_at")
|
|
41
|
+
purgedAt DateTime? @map("purged_at")
|
|
42
|
+
/// The host's after-close hook went through (a billing cancel, say); null
|
|
43
|
+
/// until then, and the sweep retries it.
|
|
44
|
+
afterCloseDoneAt DateTime? @map("after_close_done_at")
|
|
45
|
+
/// The last time the after-close hook threw: the retry is due, and the
|
|
46
|
+
/// failure is audited.
|
|
47
|
+
afterCloseFailedAt DateTime? @map("after_close_failed_at")
|
|
48
|
+
/// Object-storage keys the purge still has to delete: recorded before the
|
|
49
|
+
/// rows naming them go, emptied as each set is confirmed gone; the sweep
|
|
50
|
+
/// retries what is left.
|
|
51
|
+
imageKeysOwed String[] @default([]) @map("image_keys_owed")
|
|
52
|
+
/// The pass that emptied `image_keys_owed`.
|
|
53
|
+
imagesErasedAt DateTime? @map("images_erased_at")
|
|
54
|
+
|
|
55
|
+
@@index([purgeAt])
|
|
56
|
+
@@map("tenant_closings")
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/// One data export: the archive a person with the close permission asks for,
|
|
60
|
+
/// built by a job, kept PRIVATE in storage under `storageKey`, and handed out
|
|
61
|
+
/// until `expiresAt`. At most one PREPARING row per tenant (a partial unique
|
|
62
|
+
/// index, in the migration): a second request answers the running one.
|
|
63
|
+
model TenantDataExport {
|
|
64
|
+
id String @id
|
|
65
|
+
/// The host's tenant id, opaque. See the header — no FK.
|
|
66
|
+
tenantId String @map("tenant_id")
|
|
67
|
+
/// Who asked, and whom the link is mailed to. No FK.
|
|
68
|
+
requestedById String @map("requested_by_id")
|
|
69
|
+
/// PREPARING | READY | FAILED (CHECK).
|
|
70
|
+
status String
|
|
71
|
+
requestedAt DateTime @map("requested_at")
|
|
72
|
+
/// When a build last started: the sweep re-runs a PREPARING row whose build
|
|
73
|
+
/// went quiet.
|
|
74
|
+
startedAt DateTime? @map("started_at")
|
|
75
|
+
readyAt DateTime? @map("ready_at")
|
|
76
|
+
expiresAt DateTime? @map("expires_at")
|
|
77
|
+
storageKey String? @map("storage_key")
|
|
78
|
+
sizeBytes Int? @map("size_bytes")
|
|
79
|
+
attempts Int @default(0)
|
|
80
|
+
/// The link was mailed.
|
|
81
|
+
notifiedAt DateTime? @map("notified_at")
|
|
82
|
+
/// The stored archive was deleted after `expiresAt`.
|
|
83
|
+
deletedAt DateTime? @map("deleted_at")
|
|
84
|
+
|
|
85
|
+
@@index([tenantId, requestedAt])
|
|
86
|
+
@@index([status, requestedAt])
|
|
87
|
+
@@map("tenant_data_exports")
|
|
88
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/* global process */
|
|
3
|
+
/**
|
|
4
|
+
* Copy this package's Prisma model PARTIAL into the host's schema folder.
|
|
5
|
+
*
|
|
6
|
+
* node scripts/sync-tenant-schema.mjs [--check] [<host-schema-dir>]
|
|
7
|
+
*
|
|
8
|
+
* The partial is COPIED, never symlinked (the entity-lifecycle doctrine, and
|
|
9
|
+
* the prisma-partials-are-copied-never-symlinked memory): `turbo prune` copies
|
|
10
|
+
* only what the dependency graph reaches, so a committed symlink dangles the
|
|
11
|
+
* moment the owning package is not a declared workspace dependency; `npm pack`
|
|
12
|
+
* SILENTLY DROPS symlinked entries from the tarball, so a linked partial ships
|
|
13
|
+
* a published schema folder with the model missing; and a SYMLINKED MIGRATION
|
|
14
|
+
* is silently skipped by Prisma (`readdir` + `isDirectory()` is false for a
|
|
15
|
+
* link), so a green deploy applies no schema. @12-apps/auth's copy of this
|
|
16
|
+
* script once CREATED the link and its `--check` demanded one — following its
|
|
17
|
+
* own failure message reintroduced all three (#153).
|
|
18
|
+
*
|
|
19
|
+
* Only the schema partial. MIGRATIONS ARE NOT HANDLED HERE — the host
|
|
20
|
+
* discovers and copies them structurally, by looking for a `prisma/migrations`
|
|
21
|
+
* directory inside every installed `@12-apps/*` package (see
|
|
22
|
+
* packages/prisma/scripts/sync-prisma-plugins.mjs).
|
|
23
|
+
*
|
|
24
|
+
* The host package that owns the schema folder MUST also declare this package
|
|
25
|
+
* as a dependency, so the source of the copy is present in every build
|
|
26
|
+
* context.
|
|
27
|
+
*
|
|
28
|
+
* Default host path follows the origin host layout
|
|
29
|
+
* (`packages/prisma/prisma/schema/`); another repo passes its own schema
|
|
30
|
+
* folder as the positional argument, or sets TENANT_HOST_SCHEMA_DIR.
|
|
31
|
+
*/
|
|
32
|
+
import { copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
|
|
33
|
+
import { dirname, join } from 'node:path';
|
|
34
|
+
import { fileURLToPath } from 'node:url';
|
|
35
|
+
|
|
36
|
+
const LABEL = '[tenant-schema]';
|
|
37
|
+
const RESYNC = 'pnpm --filter @12-apps/tenant prisma:sync';
|
|
38
|
+
|
|
39
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
40
|
+
const SOURCE = join(HERE, '../prisma/tenant.prisma');
|
|
41
|
+
|
|
42
|
+
const args = process.argv.slice(2).filter((arg) => arg !== '--check');
|
|
43
|
+
const check = process.argv.includes('--check');
|
|
44
|
+
const hostSchemaDir =
|
|
45
|
+
args[0] ??
|
|
46
|
+
process.env.TENANT_HOST_SCHEMA_DIR ??
|
|
47
|
+
join(HERE, '../../prisma/prisma/schema');
|
|
48
|
+
const TARGET = join(hostSchemaDir, 'tenant.prisma');
|
|
49
|
+
|
|
50
|
+
const source = readFileSync(SOURCE, 'utf8');
|
|
51
|
+
// `lstat` first: a leftover symlink from the pre-#153 script must be REPLACED,
|
|
52
|
+
// not read through. Reading through it would report "in sync" for a link whose
|
|
53
|
+
// bytes match — and a link is exactly what `npm pack` drops.
|
|
54
|
+
const stat = existsSync(TARGET) ? lstatSync(TARGET) : null;
|
|
55
|
+
const isPlainCopy = stat !== null && stat.isFile() && !stat.isSymbolicLink();
|
|
56
|
+
const target = isPlainCopy ? readFileSync(TARGET, 'utf8') : null;
|
|
57
|
+
|
|
58
|
+
if (source === target) {
|
|
59
|
+
console.log(`${LABEL} in sync.`);
|
|
60
|
+
} else if (check) {
|
|
61
|
+
console.error(
|
|
62
|
+
`${LABEL} DRIFT: ${TARGET} is not a byte-identical COPY of the ` +
|
|
63
|
+
`@12-apps/tenant partial. Run "${RESYNC}" and commit the result.`,
|
|
64
|
+
);
|
|
65
|
+
process.exit(1);
|
|
66
|
+
} else {
|
|
67
|
+
mkdirSync(hostSchemaDir, { recursive: true });
|
|
68
|
+
// Unconditional: a DANGLING symlink reports existsSync=false, and copying
|
|
69
|
+
// through a live one would land the bytes at the link's target instead.
|
|
70
|
+
rmSync(TARGET, { force: true });
|
|
71
|
+
copyFileSync(SOURCE, TARGET);
|
|
72
|
+
console.log(`${LABEL} copied ${SOURCE} -> ${TARGET}.`);
|
|
73
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The configuration every `@12-apps/tenant` factory takes, and every later
|
|
3
|
+
* slice extends.
|
|
4
|
+
*
|
|
5
|
+
* The package knows only "tenant". What a tenant IS (a shop, a hospital, a
|
|
6
|
+
* clinic), what its statuses are called, which ids the host's clients and
|
|
7
|
+
* audit trail already read, and every sentence a person sees are the host's,
|
|
8
|
+
* and arrive here. Nothing below has a default: a missing piece fails at
|
|
9
|
+
* startup (`validate.ts`), it never silently adopts another host's values.
|
|
10
|
+
*
|
|
11
|
+
* Every id and sentence the lifecycle, the purge and the export will need is
|
|
12
|
+
* required NOW, in 1.0: a required piece added later would break every host's
|
|
13
|
+
* config, so the set is complete from the first release.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The host's full status set for its tenant row.
|
|
18
|
+
*
|
|
19
|
+
* `all` is every value the host's row may hold, the closing three included.
|
|
20
|
+
* The package acts ONLY on `active`, `closing`, `closed` and the statuses in
|
|
21
|
+
* `closableFrom`, and never assumes there are no others: a tenant in any other
|
|
22
|
+
* status (a pending one, say) is left alone. A close records the status it
|
|
23
|
+
* started from (`TenantClosing.priorStatus`) so a reopen can restore it.
|
|
24
|
+
*/
|
|
25
|
+
export interface TenantStatusSet<S extends string = string> {
|
|
26
|
+
/** Every status the host's tenant row may hold. Non-empty, no duplicates. */
|
|
27
|
+
all: readonly S[];
|
|
28
|
+
/** The tenant is live. */
|
|
29
|
+
active: S;
|
|
30
|
+
/** A close is scheduled: read-only, the purge is pending, it can reopen. */
|
|
31
|
+
closing: S;
|
|
32
|
+
/** The purge ran. The row stays, for good. */
|
|
33
|
+
closed: S;
|
|
34
|
+
/**
|
|
35
|
+
* The statuses a close may start from: `active`, and any other the host
|
|
36
|
+
* allows (a platform may close a suspended tenant). Non-empty, each listed
|
|
37
|
+
* in `all`, never `closing` or `closed`.
|
|
38
|
+
*/
|
|
39
|
+
closableFrom: readonly S[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The refusal codes an API answers when the lifecycle refuses a request.
|
|
44
|
+
* Clients read these, so the host keeps whatever values its clients already
|
|
45
|
+
* understand. Two refusals may not share a code.
|
|
46
|
+
*/
|
|
47
|
+
export interface TenantRefusalCodes {
|
|
48
|
+
/** The tenant is closing: someone without the close permission is kept out. */
|
|
49
|
+
closing: string;
|
|
50
|
+
/** The tenant is closed: nothing is served any more. */
|
|
51
|
+
closed: string;
|
|
52
|
+
/** A write at a closing tenant by someone who may only read it. */
|
|
53
|
+
readOnly: string;
|
|
54
|
+
/** A public request (a checkout, say) reaching a tenant that closed. */
|
|
55
|
+
gone: string;
|
|
56
|
+
/** The close's reason is too short. */
|
|
57
|
+
reasonTooShort: string;
|
|
58
|
+
/** The name typed to confirm the close is not the tenant's. */
|
|
59
|
+
nameMismatch: string;
|
|
60
|
+
/** Closing a tenant that is already closing or closed. */
|
|
61
|
+
alreadyClosing: string;
|
|
62
|
+
/** Closing a tenant whose status is not in `closableFrom`. */
|
|
63
|
+
notActive: string;
|
|
64
|
+
/** Something still blocks the close (the host's blockers). */
|
|
65
|
+
closingBlocked: string;
|
|
66
|
+
/** Reopening after the purge: nothing is left to restore. */
|
|
67
|
+
purged: string;
|
|
68
|
+
/** Reopening a tenant that is not closing. */
|
|
69
|
+
notClosing: string;
|
|
70
|
+
/** A data export asked by an account with no person behind it: nobody to mail the link to. */
|
|
71
|
+
exportNeedsPerson: string;
|
|
72
|
+
/** The export's link names no export of this tenant, or one not built yet. */
|
|
73
|
+
exportNotFound: string;
|
|
74
|
+
/** The export's link is past its expiry. */
|
|
75
|
+
exportExpired: string;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The audit action ids the package records. Each is the host's own id. */
|
|
79
|
+
export interface TenantAuditActionIds {
|
|
80
|
+
/** A close was confirmed and scheduled. */
|
|
81
|
+
closeScheduled: string;
|
|
82
|
+
/** A pending close was undone. */
|
|
83
|
+
closeReopened: string;
|
|
84
|
+
/** The purge ran. */
|
|
85
|
+
closePurged: string;
|
|
86
|
+
/** The host's after-close hook failed; the sweep retries it. */
|
|
87
|
+
afterCloseFailed: string;
|
|
88
|
+
/** A data export was requested. */
|
|
89
|
+
exportRequested: string;
|
|
90
|
+
/** A data export was downloaded. */
|
|
91
|
+
exportDownloaded: string;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The notification type ids the package raises. Each is the host's own id. */
|
|
95
|
+
export interface TenantNotificationTypeIds {
|
|
96
|
+
/** A close was scheduled. */
|
|
97
|
+
closingScheduled: string;
|
|
98
|
+
/** The purge is a week away. */
|
|
99
|
+
closingWeek: string;
|
|
100
|
+
/** The purge is a day away. */
|
|
101
|
+
closingDay: string;
|
|
102
|
+
/** A pending close was undone. */
|
|
103
|
+
reopened: string;
|
|
104
|
+
/** A data export finished: ready to download, or failed (the payload says which). */
|
|
105
|
+
exportReady: string;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The permission ids that gate the package's acts. Each is the host's own id. */
|
|
109
|
+
export interface TenantPermissionIds {
|
|
110
|
+
/** Close and reopen the tenant, and take its data export. */
|
|
111
|
+
close: string;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Every id the package uses. The package never makes one up. */
|
|
115
|
+
export interface TenantIds {
|
|
116
|
+
refusals: TenantRefusalCodes;
|
|
117
|
+
audit: TenantAuditActionIds;
|
|
118
|
+
notifications: TenantNotificationTypeIds;
|
|
119
|
+
permissions: TenantPermissionIds;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Every sentence the package shows or sends, by key: what a copy pack holds.
|
|
124
|
+
*
|
|
125
|
+
* WHOLE SENTENCES, never a noun to slot in: the tenant's noun changes the rest
|
|
126
|
+
* of the sentence in gendered languages ("sua clínica será encerrada" / "seu
|
|
127
|
+
* hospital será encerrado"), so only the host can write it. A sentence that
|
|
128
|
+
* carries a value is a FUNCTION the host writes, so it also owns plurals
|
|
129
|
+
* (`count`) and word order. `name` is the tenant's name; a `day` is already
|
|
130
|
+
* formatted for the pack's locale, in the tenant's time zone.
|
|
131
|
+
*
|
|
132
|
+
* `text` keys are non-empty strings; `sentence` keys are functions.
|
|
133
|
+
*/
|
|
134
|
+
export const TENANT_COPY_SHAPE = {
|
|
135
|
+
// Notices, in the inbox and by e-mail (the title is the e-mail's subject).
|
|
136
|
+
noticeScheduledTitle: 'sentence',
|
|
137
|
+
noticeScheduledBody: 'sentence',
|
|
138
|
+
noticeWeekTitle: 'sentence',
|
|
139
|
+
noticeWeekBody: 'sentence',
|
|
140
|
+
noticeDayTitle: 'sentence',
|
|
141
|
+
noticeDayBody: 'sentence',
|
|
142
|
+
noticeReopenedTitle: 'sentence',
|
|
143
|
+
noticeReopenedBody: 'sentence',
|
|
144
|
+
noticeExportReadyTitle: 'sentence',
|
|
145
|
+
noticeExportReadyBody: 'sentence',
|
|
146
|
+
noticeExportFailedTitle: 'sentence',
|
|
147
|
+
noticeExportFailedBody: 'sentence',
|
|
148
|
+
// Refusals, as a person reads them: one per refusal code.
|
|
149
|
+
refusalClosing: 'text',
|
|
150
|
+
refusalClosed: 'text',
|
|
151
|
+
refusalReadOnly: 'text',
|
|
152
|
+
refusalGone: 'text',
|
|
153
|
+
refusalReasonTooShort: 'text',
|
|
154
|
+
refusalNameMismatch: 'text',
|
|
155
|
+
refusalAlreadyClosing: 'text',
|
|
156
|
+
refusalNotActive: 'text',
|
|
157
|
+
refusalBlocked: 'sentence',
|
|
158
|
+
refusalPurged: 'text',
|
|
159
|
+
refusalNotClosing: 'text',
|
|
160
|
+
refusalExportNeedsPerson: 'text',
|
|
161
|
+
refusalExportNotFound: 'text',
|
|
162
|
+
refusalExportExpired: 'text',
|
|
163
|
+
// The close page: its three steps (blockers, data, close) and the popup.
|
|
164
|
+
pendingTitle: 'text',
|
|
165
|
+
pendingNone: 'text',
|
|
166
|
+
blocker: 'sentence',
|
|
167
|
+
shortcut: 'sentence',
|
|
168
|
+
dataTitle: 'text',
|
|
169
|
+
dataTitlePlain: 'text',
|
|
170
|
+
dataNote: 'text',
|
|
171
|
+
dataAction: 'text',
|
|
172
|
+
dataPreparing: 'text',
|
|
173
|
+
dataOffline: 'text',
|
|
174
|
+
closeTitle: 'text',
|
|
175
|
+
closeExplain: 'text',
|
|
176
|
+
closeAction: 'text',
|
|
177
|
+
missing: 'sentence',
|
|
178
|
+
dialogTitle: 'text',
|
|
179
|
+
dialogBody: 'sentence',
|
|
180
|
+
dialogUndo: 'text',
|
|
181
|
+
nameLabel: 'text',
|
|
182
|
+
nameHint: 'sentence',
|
|
183
|
+
nameMismatch: 'text',
|
|
184
|
+
reasonLabel: 'text',
|
|
185
|
+
reasonPlaceholder: 'text',
|
|
186
|
+
cancel: 'text',
|
|
187
|
+
actFailed: 'text',
|
|
188
|
+
loadFailed: 'text',
|
|
189
|
+
retry: 'text',
|
|
190
|
+
// The close page while closing, and once closed.
|
|
191
|
+
closingTitle: 'text',
|
|
192
|
+
closingBody: 'sentence',
|
|
193
|
+
reopen: 'text',
|
|
194
|
+
reopened: 'text',
|
|
195
|
+
reopenNote: 'text',
|
|
196
|
+
closedTitle: 'text',
|
|
197
|
+
closedBody: 'text',
|
|
198
|
+
// The banner every screen shows to whoever holds the close permission.
|
|
199
|
+
bannerTitle: 'text',
|
|
200
|
+
bannerBody: 'sentence',
|
|
201
|
+
bannerReadOnly: 'text',
|
|
202
|
+
// The refusal screen of a member a closing or closed tenant keeps out.
|
|
203
|
+
refusedClosingTitle: 'text',
|
|
204
|
+
refusedClosingBody: 'text',
|
|
205
|
+
refusedClosedTitle: 'text',
|
|
206
|
+
refusedClosedBody: 'text',
|
|
207
|
+
switchTenant: 'text',
|
|
208
|
+
signOut: 'text',
|
|
209
|
+
seeClosing: 'text',
|
|
210
|
+
// The platform's view of a closing tenant.
|
|
211
|
+
platformCancelClosing: 'text',
|
|
212
|
+
platformClosingNote: 'sentence',
|
|
213
|
+
} as const satisfies Record<string, 'text' | 'sentence'>;
|
|
214
|
+
|
|
215
|
+
export type TenantCopyKey = keyof typeof TENANT_COPY_SHAPE;
|
|
216
|
+
|
|
217
|
+
/** One locale's full copy pack: every key, typed. */
|
|
218
|
+
export interface TenantCopyPack {
|
|
219
|
+
readonly noticeScheduledTitle: (name: string) => string;
|
|
220
|
+
readonly noticeScheduledBody: (name: string, purgeDay: string) => string;
|
|
221
|
+
readonly noticeWeekTitle: (name: string) => string;
|
|
222
|
+
readonly noticeWeekBody: (name: string, purgeDay: string) => string;
|
|
223
|
+
readonly noticeDayTitle: (name: string) => string;
|
|
224
|
+
readonly noticeDayBody: (name: string) => string;
|
|
225
|
+
readonly noticeReopenedTitle: (name: string) => string;
|
|
226
|
+
readonly noticeReopenedBody: (name: string) => string;
|
|
227
|
+
readonly noticeExportReadyTitle: (name: string) => string;
|
|
228
|
+
readonly noticeExportReadyBody: (name: string, expiresDay: string) => string;
|
|
229
|
+
readonly noticeExportFailedTitle: (name: string) => string;
|
|
230
|
+
readonly noticeExportFailedBody: (name: string) => string;
|
|
231
|
+
readonly refusalClosing: string;
|
|
232
|
+
readonly refusalClosed: string;
|
|
233
|
+
readonly refusalReadOnly: string;
|
|
234
|
+
readonly refusalGone: string;
|
|
235
|
+
readonly refusalReasonTooShort: string;
|
|
236
|
+
readonly refusalNameMismatch: string;
|
|
237
|
+
readonly refusalAlreadyClosing: string;
|
|
238
|
+
readonly refusalNotActive: string;
|
|
239
|
+
/** `count` items still block the close. */
|
|
240
|
+
readonly refusalBlocked: (count: number) => string;
|
|
241
|
+
readonly refusalPurged: string;
|
|
242
|
+
readonly refusalNotClosing: string;
|
|
243
|
+
readonly refusalExportNeedsPerson: string;
|
|
244
|
+
readonly refusalExportNotFound: string;
|
|
245
|
+
readonly refusalExportExpired: string;
|
|
246
|
+
readonly pendingTitle: string;
|
|
247
|
+
readonly pendingNone: string;
|
|
248
|
+
/** One line per kind of blocker; `kind` is one of the host's own blocker kinds. */
|
|
249
|
+
readonly blocker: (kind: string, count: number) => string;
|
|
250
|
+
/** The shortcut that resolves a blocker of that kind. */
|
|
251
|
+
readonly shortcut: (kind: string) => string;
|
|
252
|
+
readonly dataTitle: string;
|
|
253
|
+
readonly dataTitlePlain: string;
|
|
254
|
+
readonly dataNote: string;
|
|
255
|
+
readonly dataAction: string;
|
|
256
|
+
readonly dataPreparing: string;
|
|
257
|
+
readonly dataOffline: string;
|
|
258
|
+
readonly closeTitle: string;
|
|
259
|
+
readonly closeExplain: string;
|
|
260
|
+
readonly closeAction: string;
|
|
261
|
+
/** `count` blockers are left. */
|
|
262
|
+
readonly missing: (count: number) => string;
|
|
263
|
+
readonly dialogTitle: string;
|
|
264
|
+
readonly dialogBody: (name: string) => string;
|
|
265
|
+
readonly dialogUndo: string;
|
|
266
|
+
readonly nameLabel: string;
|
|
267
|
+
readonly nameHint: (name: string) => string;
|
|
268
|
+
readonly nameMismatch: string;
|
|
269
|
+
readonly reasonLabel: string;
|
|
270
|
+
readonly reasonPlaceholder: string;
|
|
271
|
+
readonly cancel: string;
|
|
272
|
+
readonly actFailed: string;
|
|
273
|
+
readonly loadFailed: string;
|
|
274
|
+
readonly retry: string;
|
|
275
|
+
readonly closingTitle: string;
|
|
276
|
+
readonly closingBody: (sinceDay: string, purgeDay: string) => string;
|
|
277
|
+
readonly reopen: string;
|
|
278
|
+
readonly reopened: string;
|
|
279
|
+
readonly reopenNote: string;
|
|
280
|
+
readonly closedTitle: string;
|
|
281
|
+
readonly closedBody: string;
|
|
282
|
+
readonly bannerTitle: string;
|
|
283
|
+
readonly bannerBody: (sinceDay: string, purgeDay: string) => string;
|
|
284
|
+
readonly bannerReadOnly: string;
|
|
285
|
+
readonly refusedClosingTitle: string;
|
|
286
|
+
readonly refusedClosingBody: string;
|
|
287
|
+
readonly refusedClosedTitle: string;
|
|
288
|
+
readonly refusedClosedBody: string;
|
|
289
|
+
readonly switchTenant: string;
|
|
290
|
+
readonly signOut: string;
|
|
291
|
+
readonly seeClosing: string;
|
|
292
|
+
readonly platformCancelClosing: string;
|
|
293
|
+
readonly platformClosingNote: (closedDay: string, purgeDay: string) => string;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** The keys of a copy pack, in a fixed order. */
|
|
297
|
+
export const TENANT_COPY_KEYS = Object.keys(TENANT_COPY_SHAPE) as readonly TenantCopyKey[];
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* The copy packs by locale tag (`pt-BR`, `en-US`). No pack ships with the
|
|
301
|
+
* package. `defaultLocale` names the pack a request with no matching locale
|
|
302
|
+
* reads, and must itself be one of the packs.
|
|
303
|
+
*/
|
|
304
|
+
export interface TenantCopyConfig {
|
|
305
|
+
locales: Readonly<Record<string, TenantCopyPack>>;
|
|
306
|
+
defaultLocale: string;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** What both halves (`createApiTenant`, `createWebTenant`) are configured with. */
|
|
310
|
+
export interface TenantCoreConfig<S extends string = string> {
|
|
311
|
+
statuses: TenantStatusSet<S>;
|
|
312
|
+
ids: TenantIds;
|
|
313
|
+
copy: TenantCopyConfig;
|
|
314
|
+
}
|
package/src/core.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The pure readings both halves answer from a validated config, and the
|
|
3
|
+
* deep freeze both apply to it.
|
|
4
|
+
*/
|
|
5
|
+
import type { TenantCopyPack, TenantCoreConfig, TenantRefusalCodes } from './config';
|
|
6
|
+
|
|
7
|
+
/** Which refusal a code is, by the host's own codes. */
|
|
8
|
+
export type TenantRefusalKind = keyof TenantRefusalCodes;
|
|
9
|
+
|
|
10
|
+
/** `T` with every nested object and array read-only; functions are left as they are. */
|
|
11
|
+
export type DeepReadonly<T> = T extends (...args: never[]) => unknown
|
|
12
|
+
? T
|
|
13
|
+
: T extends readonly (infer E)[]
|
|
14
|
+
? readonly DeepReadonly<E>[]
|
|
15
|
+
: T extends object
|
|
16
|
+
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
|
|
17
|
+
: T;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* A frozen COPY of the plain data in `value`: objects and arrays are copied
|
|
21
|
+
* and frozen at every depth, functions are kept as they are. The host's own
|
|
22
|
+
* objects are never frozen in place, and a change it makes to them after
|
|
23
|
+
* startup does not reach the validated config.
|
|
24
|
+
*/
|
|
25
|
+
export function frozenCopy<T>(value: T): DeepReadonly<T> {
|
|
26
|
+
if (Array.isArray(value)) return Object.freeze(value.map((item: unknown) => frozenCopy(item))) as DeepReadonly<T>;
|
|
27
|
+
if (typeof value !== 'object' || value === null) return value as DeepReadonly<T>;
|
|
28
|
+
const copy = Object.fromEntries(
|
|
29
|
+
Object.entries(value).map(([key, child]: [string, unknown]) => [key, frozenCopy(child)]),
|
|
30
|
+
);
|
|
31
|
+
return Object.freeze(copy) as DeepReadonly<T>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** What both factories hand back on top of their own half. */
|
|
35
|
+
export interface TenantReadings<S extends string> {
|
|
36
|
+
/** True only for the statuses the package acts on: active, closing, closed and `closableFrom`. */
|
|
37
|
+
isLifecycleStatus(status: string): status is S;
|
|
38
|
+
/** True when a close may start from `status` (`statuses.closableFrom`). */
|
|
39
|
+
isClosableFrom(status: string): status is S;
|
|
40
|
+
/** The copy pack for a locale tag, or the default locale's when none matches. */
|
|
41
|
+
copyFor(locale: string | null | undefined): TenantCopyPack;
|
|
42
|
+
/** Which refusal a code from the API is, or null when it is none of the package's. */
|
|
43
|
+
refusalKind(code: string): TenantRefusalKind | null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function createReadings<S extends string>(
|
|
47
|
+
config: DeepReadonly<TenantCoreConfig<S>>,
|
|
48
|
+
): TenantReadings<S> {
|
|
49
|
+
const { statuses } = config;
|
|
50
|
+
const closable = new Set<string>(statuses.closableFrom);
|
|
51
|
+
const lifecycle = new Set<string>([statuses.active, statuses.closing, statuses.closed, ...closable]);
|
|
52
|
+
const byCode = new Map<string, TenantRefusalKind>(
|
|
53
|
+
(Object.entries(config.ids.refusals) as [TenantRefusalKind, string][]).map(([kind, code]) => [code, kind]),
|
|
54
|
+
);
|
|
55
|
+
const { locales, defaultLocale } = config.copy;
|
|
56
|
+
return {
|
|
57
|
+
isLifecycleStatus: (status: string): status is S => lifecycle.has(status),
|
|
58
|
+
isClosableFrom: (status: string): status is S => closable.has(status),
|
|
59
|
+
copyFor: (locale) =>
|
|
60
|
+
(locale !== null && locale !== undefined && Object.hasOwn(locales, locale)
|
|
61
|
+
? locales[locale]
|
|
62
|
+
: locales[defaultLocale]) as TenantCopyPack,
|
|
63
|
+
refusalKind: (code) => byCode.get(code) ?? null,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@12-apps/tenant/hono` — mounts `createApiTenant`'s descriptors on a Hono app.
|
|
3
|
+
*
|
|
4
|
+
* Hono is an optional peer and is only TYPE-imported here: the adapter calls
|
|
5
|
+
* `app.on(method, path, handler)` on whatever app the host passes.
|
|
6
|
+
*/
|
|
7
|
+
import type { Hono } from 'hono';
|
|
8
|
+
|
|
9
|
+
import type { ApiTenant } from '../server';
|
|
10
|
+
|
|
11
|
+
/** Mount every route of `tenant` on `app`, in order. Returns `app`. */
|
|
12
|
+
export function mountTenant<A extends Pick<Hono, 'on'>>(app: A, tenant: Pick<ApiTenant, 'routes'>): A {
|
|
13
|
+
for (const route of tenant.routes) {
|
|
14
|
+
app.on(route.method, route.path, (context) => route.handler(context.req.raw));
|
|
15
|
+
}
|
|
16
|
+
return app;
|
|
17
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@12-apps/tenant` — the shared, runtime-free half: the config types every
|
|
3
|
+
* factory takes, the tenant port's shape, and the startup validation.
|
|
4
|
+
*
|
|
5
|
+
* Backend: `@12-apps/tenant/server` (`createApiTenant`). Hono mount:
|
|
6
|
+
* `@12-apps/tenant/hono`. Frontend: `@12-apps/tenant/react`
|
|
7
|
+
* (`createWebTenant`). Adoption contract: ADOPTING.md.
|
|
8
|
+
*/
|
|
9
|
+
export {
|
|
10
|
+
TENANT_COPY_KEYS,
|
|
11
|
+
TENANT_COPY_SHAPE,
|
|
12
|
+
type TenantAuditActionIds,
|
|
13
|
+
type TenantCopyConfig,
|
|
14
|
+
type TenantCopyKey,
|
|
15
|
+
type TenantCopyPack,
|
|
16
|
+
type TenantCoreConfig,
|
|
17
|
+
type TenantIds,
|
|
18
|
+
type TenantNotificationTypeIds,
|
|
19
|
+
type TenantPermissionIds,
|
|
20
|
+
type TenantRefusalCodes,
|
|
21
|
+
type TenantStatusSet,
|
|
22
|
+
} from './config';
|
|
23
|
+
export { TENANT_PORT_METHODS, type TenantPort, type TenantRecord } from './port';
|
|
24
|
+
export { TenantConfigError, validateCoreConfig, validatePort } from './validate';
|
|
25
|
+
export type { DeepReadonly, TenantReadings, TenantRefusalKind } from './core';
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@12-apps/tenant/manifest` — the SHARED wiring manifest.
|
|
3
|
+
*
|
|
4
|
+
* - `db` — the partial names no host table (the tenant id is an opaque
|
|
5
|
+
* string, no foreign key), so it composes into any host's schema folder.
|
|
6
|
+
*
|
|
7
|
+
* Every other capability is declined for now, each with its argument in
|
|
8
|
+
* `.wiring-conformance.json`: the routes, jobs, mail, notifications,
|
|
9
|
+
* permissions and screens arrive with the slices that add them.
|
|
10
|
+
*
|
|
11
|
+
* `@12-apps/wiring` is a TYPE-ONLY dependency here.
|
|
12
|
+
*/
|
|
13
|
+
import type { PackageManifest } from '@12-apps/wiring';
|
|
14
|
+
|
|
15
|
+
export const tenantManifest = {
|
|
16
|
+
name: '@12-apps/tenant',
|
|
17
|
+
contract: 1,
|
|
18
|
+
db: { partial: 'prisma/tenant.prisma', migrations: 'prisma/migrations' },
|
|
19
|
+
} as const satisfies PackageManifest;
|
package/src/port.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The tenant port: the ONLY way the package reaches the host's tenant row.
|
|
3
|
+
*
|
|
4
|
+
* The tenant row, its slugs and its domains stay the host's. The package never
|
|
5
|
+
* maps them (Prisma refuses two models on one table, and a shared partial has
|
|
6
|
+
* no foreign key into a host table), so it asks the host through these five
|
|
7
|
+
* functions instead. Every one is required.
|
|
8
|
+
*
|
|
9
|
+
* TRANSACTIONS. Every lifecycle step changes the tenant row and the package's
|
|
10
|
+
* own rows together: a close flips the status, recounts the blockers (one
|
|
11
|
+
* found rolls the flip back), replaces the closing row and writes the audit
|
|
12
|
+
* line, all in ONE transaction the package opens through the host. So every
|
|
13
|
+
* write takes the caller's transaction `tx` and must run on it, never on a
|
|
14
|
+
* client of its own; `byId` takes it too, so a refusal reads the status the
|
|
15
|
+
* transaction sees.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** What the package needs to know about one tenant. */
|
|
19
|
+
export interface TenantRecord<S extends string = string> {
|
|
20
|
+
/** The host's tenant id, opaque to the package. */
|
|
21
|
+
id: string;
|
|
22
|
+
/** The tenant's CURRENT slug (never a former one the host keeps). */
|
|
23
|
+
slug: string;
|
|
24
|
+
/** The tenant row's current status: any value of the host's status set. */
|
|
25
|
+
status: S;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* `Tx` is the host's transaction client. The package never opens one itself:
|
|
30
|
+
* it hands back whatever the host gave it, so the host's own writes and the
|
|
31
|
+
* package's land in the same transaction.
|
|
32
|
+
*/
|
|
33
|
+
export interface TenantPort<S extends string = string, Tx = unknown> {
|
|
34
|
+
/**
|
|
35
|
+
* The tenant whose CURRENT slug is `slug`, or null when none is. A former
|
|
36
|
+
* slug the host still keeps for redirects does not resolve here: kept slugs
|
|
37
|
+
* are the address slice's, through a port of their own.
|
|
38
|
+
*/
|
|
39
|
+
bySlug(slug: string): Promise<TenantRecord<S> | null>;
|
|
40
|
+
/**
|
|
41
|
+
* The tenant with this id, or null when none exists. Read on `tx` when one
|
|
42
|
+
* is given, so a step inside a transaction sees that transaction's row.
|
|
43
|
+
*/
|
|
44
|
+
byId(id: string, tx?: Tx): Promise<TenantRecord<S> | null>;
|
|
45
|
+
/**
|
|
46
|
+
* Compare-and-set the tenant's status, ON `tx`: move it to `to` ONLY while
|
|
47
|
+
* it is still `from` (`UPDATE … SET status = to WHERE id = id AND status =
|
|
48
|
+
* from`). Resolves true when the row moved, false when it was not in `from`
|
|
49
|
+
* (another request got there first). The package relies on that answer to
|
|
50
|
+
* make every lifecycle step happen once, and on `tx` to roll the move back
|
|
51
|
+
* when a later step of the same transaction refuses.
|
|
52
|
+
*/
|
|
53
|
+
setStatusIf(id: string, from: S, to: S, tx: Tx): Promise<boolean>;
|
|
54
|
+
/**
|
|
55
|
+
* Erase the tenant row's own profile (name, contact, address, whatever the
|
|
56
|
+
* host keeps on it) ON `tx`, inside the purge's transaction. The row itself
|
|
57
|
+
* stays.
|
|
58
|
+
*/
|
|
59
|
+
clearProfile(tx: Tx, id: string): Promise<void>;
|
|
60
|
+
/** The tenant's IANA time zone (`America/Sao_Paulo`): reminders and purge dates are computed in it. */
|
|
61
|
+
timeZone(id: string): Promise<string>;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The port's members, in a fixed order: what startup validation checks. */
|
|
65
|
+
export const TENANT_PORT_METHODS = [
|
|
66
|
+
'bySlug',
|
|
67
|
+
'byId',
|
|
68
|
+
'setStatusIf',
|
|
69
|
+
'clearProfile',
|
|
70
|
+
'timeZone',
|
|
71
|
+
] as const satisfies readonly (keyof TenantPort)[];
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@12-apps/tenant/react` — the frontend factory.
|
|
3
|
+
*
|
|
4
|
+
* `createWebTenant` takes the half of the config a browser needs (the status
|
|
5
|
+
* set, the ids, the copy packs) and validates it at startup exactly as the
|
|
6
|
+
* backend does. The tenant port is the server's and never reaches a browser.
|
|
7
|
+
* This slice ships the readings a screen needs (which pack to show, which
|
|
8
|
+
* refusal an answer is); the screens arrive with the lifecycle slice.
|
|
9
|
+
*/
|
|
10
|
+
import type { TenantCoreConfig } from '../config';
|
|
11
|
+
import { createReadings, frozenCopy, type DeepReadonly, type TenantReadings } from '../core';
|
|
12
|
+
import { validateCoreConfig } from '../validate';
|
|
13
|
+
|
|
14
|
+
export { TenantConfigError } from '../validate';
|
|
15
|
+
|
|
16
|
+
/** Everything `createWebTenant` needs. Nothing is optional. */
|
|
17
|
+
export type TenantWebConfig<S extends string = string> = TenantCoreConfig<S>;
|
|
18
|
+
|
|
19
|
+
export interface WebTenant<S extends string = string> extends TenantReadings<S> {
|
|
20
|
+
/** The validated config, a deep-frozen copy. */
|
|
21
|
+
config: DeepReadonly<TenantWebConfig<S>>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function createWebTenant<S extends string>(config: TenantWebConfig<S>): WebTenant<S> {
|
|
25
|
+
validateCoreConfig(config);
|
|
26
|
+
const data = frozenCopy({ statuses: config.statuses, ids: config.ids, copy: config.copy });
|
|
27
|
+
return { ...createReadings(data), config: data };
|
|
28
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@12-apps/tenant/server` — the backend factory.
|
|
3
|
+
*
|
|
4
|
+
* `createApiTenant` takes the WHOLE config: the status set, the ids, the copy
|
|
5
|
+
* packs and the tenant port, every one required. It validates them before it
|
|
6
|
+
* returns, so a host missing a piece fails when it boots, with the missing key
|
|
7
|
+
* named (`TenantConfigError`), instead of adopting somebody else's values.
|
|
8
|
+
*
|
|
9
|
+
* Framework-neutral, the report-builder doctrine: routes are plain
|
|
10
|
+
* descriptors and `@12-apps/tenant/hono` mounts them. This slice ships the
|
|
11
|
+
* shape, the validation, the readings and the transaction-bound status move;
|
|
12
|
+
* the lifecycle, the purge and the export add their routes and behaviour on
|
|
13
|
+
* top of the same config.
|
|
14
|
+
*/
|
|
15
|
+
import type { TenantCoreConfig } from '../config';
|
|
16
|
+
import { createReadings, frozenCopy, type DeepReadonly, type TenantReadings } from '../core';
|
|
17
|
+
import type { TenantPort, TenantRecord } from '../port';
|
|
18
|
+
import { validateCoreConfig, validatePort } from '../validate';
|
|
19
|
+
|
|
20
|
+
export { TenantConfigError } from '../validate';
|
|
21
|
+
|
|
22
|
+
/** A framework-neutral route: the Hono adapter mounts each one as given. */
|
|
23
|
+
export interface TenantRoute {
|
|
24
|
+
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
25
|
+
/** Relative to wherever the host mounts the package. */
|
|
26
|
+
path: string;
|
|
27
|
+
handler(request: Request): Promise<Response>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Everything `createApiTenant` needs. Nothing is optional. */
|
|
31
|
+
export interface TenantServerConfig<S extends string = string, Tx = unknown>
|
|
32
|
+
extends TenantCoreConfig<S> {
|
|
33
|
+
/** The host's tenant row, reached only through this port. */
|
|
34
|
+
port: TenantPort<S, Tx>;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface ApiTenant<S extends string = string, Tx = unknown> extends TenantReadings<S> {
|
|
38
|
+
/** The validated config's data parts (statuses, ids, copy), deep-frozen copies. */
|
|
39
|
+
config: DeepReadonly<TenantCoreConfig<S>>;
|
|
40
|
+
/** The host's tenant port, as given. */
|
|
41
|
+
port: TenantPort<S, Tx>;
|
|
42
|
+
/** The package's routes, in mount order. None yet: the lifecycle slice adds them. */
|
|
43
|
+
routes: readonly TenantRoute[];
|
|
44
|
+
/** The tenant, read through the port, on `tx` when given. */
|
|
45
|
+
byId(id: string, tx?: Tx): Promise<TenantRecord<S> | null>;
|
|
46
|
+
/**
|
|
47
|
+
* Move the tenant's status from `from` to `to` on the CALLER's transaction:
|
|
48
|
+
* true when it moved. Both must be statuses of the host's set; the port's
|
|
49
|
+
* compare-and-set runs on `tx`, so a later refusal in the same transaction
|
|
50
|
+
* rolls the move back.
|
|
51
|
+
*/
|
|
52
|
+
setStatusIf(id: string, from: S, to: S, tx: Tx): Promise<boolean>;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function createApiTenant<S extends string, Tx = unknown>(
|
|
56
|
+
config: TenantServerConfig<S, Tx>,
|
|
57
|
+
): ApiTenant<S, Tx> {
|
|
58
|
+
validateCoreConfig(config);
|
|
59
|
+
validatePort((config as { port?: unknown }).port);
|
|
60
|
+
const data = frozenCopy({ statuses: config.statuses, ids: config.ids, copy: config.copy });
|
|
61
|
+
const known = new Set<string>(data.statuses.all);
|
|
62
|
+
const { port } = config;
|
|
63
|
+
return {
|
|
64
|
+
...createReadings(data),
|
|
65
|
+
config: data,
|
|
66
|
+
port,
|
|
67
|
+
routes: Object.freeze([]),
|
|
68
|
+
byId: (id, tx) => port.byId(id, tx),
|
|
69
|
+
setStatusIf: (id, from, to, tx) => {
|
|
70
|
+
for (const [key, status] of [['from', from], ['to', to]] as const) {
|
|
71
|
+
if (!known.has(status)) {
|
|
72
|
+
return Promise.reject(
|
|
73
|
+
new RangeError(`@12-apps/tenant: setStatusIf "${key}" is "${status}", which statuses.all does not list.`),
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return port.setStatusIf(id, from, to, tx);
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|
package/src/validate.ts
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Startup validation: every factory runs these before it returns, so a host
|
|
3
|
+
* that forgot a piece of config fails when it boots, with the missing key
|
|
4
|
+
* named, rather than on the first request that needed it.
|
|
5
|
+
*
|
|
6
|
+
* The checks read the config as `unknown` on purpose: a host written in plain
|
|
7
|
+
* JavaScript, or one that casts, gets the same answer as a typed one.
|
|
8
|
+
*/
|
|
9
|
+
import {
|
|
10
|
+
TENANT_COPY_SHAPE,
|
|
11
|
+
type TenantCoreConfig,
|
|
12
|
+
type TenantIds,
|
|
13
|
+
} from './config';
|
|
14
|
+
import { TENANT_PORT_METHODS, type TenantPort } from './port';
|
|
15
|
+
|
|
16
|
+
/** Thrown at startup when the config is missing a piece or carries a bad one. */
|
|
17
|
+
export class TenantConfigError extends Error {
|
|
18
|
+
/** The dotted path of the offending key (`ids.refusals.gone`). */
|
|
19
|
+
readonly key: string;
|
|
20
|
+
|
|
21
|
+
constructor(key: string, problem: string) {
|
|
22
|
+
super(`@12-apps/tenant: config "${key}" ${problem}.`);
|
|
23
|
+
this.name = 'TenantConfigError';
|
|
24
|
+
this.key = key;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
type Bag = Record<string, unknown>;
|
|
29
|
+
|
|
30
|
+
function isBag(value: unknown): value is Bag {
|
|
31
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function requireBag(value: unknown, key: string): Bag {
|
|
35
|
+
if (value === undefined || value === null) {
|
|
36
|
+
throw new TenantConfigError(key, 'is required and missing');
|
|
37
|
+
}
|
|
38
|
+
if (!isBag(value)) throw new TenantConfigError(key, 'must be an object');
|
|
39
|
+
return value;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function requireString(value: unknown, key: string): string {
|
|
43
|
+
if (value === undefined || value === null) {
|
|
44
|
+
throw new TenantConfigError(key, 'is required and missing');
|
|
45
|
+
}
|
|
46
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
47
|
+
throw new TenantConfigError(key, 'must be a non-empty string');
|
|
48
|
+
}
|
|
49
|
+
return value;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function requireDistinct(values: Record<string, string>, key: string): void {
|
|
53
|
+
const seen = new Map<string, string>();
|
|
54
|
+
for (const [name, value] of Object.entries(values)) {
|
|
55
|
+
const first = seen.get(value);
|
|
56
|
+
if (first !== undefined) {
|
|
57
|
+
throw new TenantConfigError(
|
|
58
|
+
`${key}.${name}`,
|
|
59
|
+
`repeats the value "${value}" already given to ${key}.${first}`,
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
seen.set(value, name);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** A non-empty list of distinct non-empty strings, as a set. */
|
|
67
|
+
function requireStatusList(value: unknown, key: string): Set<string> {
|
|
68
|
+
if (value === undefined || value === null) {
|
|
69
|
+
throw new TenantConfigError(key, 'is required and missing');
|
|
70
|
+
}
|
|
71
|
+
if (!Array.isArray(value) || value.length === 0) {
|
|
72
|
+
throw new TenantConfigError(key, 'must be a non-empty array');
|
|
73
|
+
}
|
|
74
|
+
const seen = new Set<string>();
|
|
75
|
+
value.forEach((status, index) => {
|
|
76
|
+
const name = requireString(status, `${key}[${index}]`);
|
|
77
|
+
if (seen.has(name)) throw new TenantConfigError(`${key}[${index}]`, `repeats "${name}"`);
|
|
78
|
+
seen.add(name);
|
|
79
|
+
});
|
|
80
|
+
return seen;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function validateClosableFrom(value: unknown, known: Set<string>, named: Record<string, string>): void {
|
|
84
|
+
const closable = requireStatusList(value, 'statuses.closableFrom');
|
|
85
|
+
for (const name of closable) {
|
|
86
|
+
if (!known.has(name)) {
|
|
87
|
+
throw new TenantConfigError('statuses.closableFrom', `names "${name}", which statuses.all does not list`);
|
|
88
|
+
}
|
|
89
|
+
if (name === named.closing || name === named.closed) {
|
|
90
|
+
throw new TenantConfigError('statuses.closableFrom', `names "${name}", a status a close cannot start from`);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function validateStatuses(value: unknown): void {
|
|
96
|
+
const statuses = requireBag(value, 'statuses');
|
|
97
|
+
const known = requireStatusList(statuses.all, 'statuses.all');
|
|
98
|
+
const named: Record<string, string> = {};
|
|
99
|
+
for (const role of ['active', 'closing', 'closed'] as const) {
|
|
100
|
+
const name = requireString(statuses[role], `statuses.${role}`);
|
|
101
|
+
if (!known.has(name)) {
|
|
102
|
+
throw new TenantConfigError(`statuses.${role}`, `names "${name}", which statuses.all does not list`);
|
|
103
|
+
}
|
|
104
|
+
named[role] = name;
|
|
105
|
+
}
|
|
106
|
+
requireDistinct(named, 'statuses');
|
|
107
|
+
validateClosableFrom(statuses.closableFrom, known, named);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const ID_GROUPS = {
|
|
111
|
+
refusals: [
|
|
112
|
+
'closing',
|
|
113
|
+
'closed',
|
|
114
|
+
'readOnly',
|
|
115
|
+
'gone',
|
|
116
|
+
'reasonTooShort',
|
|
117
|
+
'nameMismatch',
|
|
118
|
+
'alreadyClosing',
|
|
119
|
+
'notActive',
|
|
120
|
+
'closingBlocked',
|
|
121
|
+
'purged',
|
|
122
|
+
'notClosing',
|
|
123
|
+
'exportNeedsPerson',
|
|
124
|
+
'exportNotFound',
|
|
125
|
+
'exportExpired',
|
|
126
|
+
],
|
|
127
|
+
audit: [
|
|
128
|
+
'closeScheduled',
|
|
129
|
+
'closeReopened',
|
|
130
|
+
'closePurged',
|
|
131
|
+
'afterCloseFailed',
|
|
132
|
+
'exportRequested',
|
|
133
|
+
'exportDownloaded',
|
|
134
|
+
],
|
|
135
|
+
notifications: ['closingScheduled', 'closingWeek', 'closingDay', 'reopened', 'exportReady'],
|
|
136
|
+
permissions: ['close'],
|
|
137
|
+
} as const satisfies { [G in keyof TenantIds]: readonly (keyof TenantIds[G])[] };
|
|
138
|
+
|
|
139
|
+
function validateIdGroup(value: unknown, group: string, names: readonly string[]): void {
|
|
140
|
+
const bag = requireBag(value, `ids.${group}`);
|
|
141
|
+
const values = Object.fromEntries(
|
|
142
|
+
names.map((name) => [name, requireString(bag[name], `ids.${group}.${name}`)]),
|
|
143
|
+
);
|
|
144
|
+
// Two acts sharing one id would be indistinguishable to whoever reads it.
|
|
145
|
+
requireDistinct(values, `ids.${group}`);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function validateIds(value: unknown): void {
|
|
149
|
+
const ids = requireBag(value, 'ids');
|
|
150
|
+
for (const [group, names] of Object.entries(ID_GROUPS)) validateIdGroup(ids[group], group, names);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function requireSentence(value: unknown, key: string): void {
|
|
154
|
+
if (value === undefined || value === null) {
|
|
155
|
+
throw new TenantConfigError(key, 'is required and missing');
|
|
156
|
+
}
|
|
157
|
+
if (typeof value !== 'function') {
|
|
158
|
+
throw new TenantConfigError(key, 'must be a function that writes the whole sentence');
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function validatePack(value: unknown, tag: string): void {
|
|
163
|
+
const pack = requireBag(value, `copy.locales.${tag}`);
|
|
164
|
+
for (const [copyKey, kind] of Object.entries(TENANT_COPY_SHAPE)) {
|
|
165
|
+
const key = `copy.locales.${tag}.${copyKey}`;
|
|
166
|
+
if (kind === 'text') requireString(pack[copyKey], key);
|
|
167
|
+
else requireSentence(pack[copyKey], key);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function validateCopy(value: unknown): void {
|
|
172
|
+
const copy = requireBag(value, 'copy');
|
|
173
|
+
const locales = requireBag(copy.locales, 'copy.locales');
|
|
174
|
+
const tags = Object.keys(locales);
|
|
175
|
+
if (tags.length === 0) {
|
|
176
|
+
throw new TenantConfigError('copy.locales', 'must hold at least one locale pack');
|
|
177
|
+
}
|
|
178
|
+
for (const tag of tags) validatePack(locales[tag], tag);
|
|
179
|
+
const fallback = requireString(copy.defaultLocale, 'copy.defaultLocale');
|
|
180
|
+
if (!tags.includes(fallback)) {
|
|
181
|
+
throw new TenantConfigError('copy.defaultLocale', `names "${fallback}", which copy.locales does not hold`);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Validate what both halves share. Throws {@link TenantConfigError}. */
|
|
186
|
+
export function validateCoreConfig(config: unknown): asserts config is TenantCoreConfig {
|
|
187
|
+
const bag = requireBag(config, 'config');
|
|
188
|
+
validateStatuses(bag.statuses);
|
|
189
|
+
validateIds(bag.ids);
|
|
190
|
+
validateCopy(bag.copy);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Validate the tenant port: every member present and a function. */
|
|
194
|
+
export function validatePort(value: unknown): asserts value is TenantPort {
|
|
195
|
+
const port = requireBag(value, 'port');
|
|
196
|
+
for (const method of TENANT_PORT_METHODS) {
|
|
197
|
+
if (port[method] === undefined || port[method] === null) {
|
|
198
|
+
throw new TenantConfigError(`port.${method}`, 'is required and missing');
|
|
199
|
+
}
|
|
200
|
+
if (typeof port[method] !== 'function') {
|
|
201
|
+
throw new TenantConfigError(`port.${method}`, 'must be a function');
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|