@12-apps/tenant 1.2.0 → 1.3.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 CHANGED
@@ -7,8 +7,8 @@ Two halves, one factory each, one config object each. Nothing is optional.
7
7
  import { createApiTenant } from '@12-apps/tenant/server';
8
8
  import { mountTenant } from '@12-apps/tenant/hono';
9
9
 
10
- const tenant = createApiTenant({ statuses, ids, copy, port });
11
- mountTenant(app, tenant); // mounts nothing yet: the routes arrive with the lifecycle
10
+ const tenant = createApiTenant({ statuses, ids, copy, port }); // + tree, slugs, lifecycle: each opt-in
11
+ mountTenant(app, tenant); // mounts nothing: hosts keep their own route modules
12
12
 
13
13
  // frontend
14
14
  import { createWebTenant } from '@12-apps/tenant/react';
@@ -92,8 +92,8 @@ const copy = { locales: { 'pt-BR': ptBR, 'en-US': enUS }, defaultLocale: 'pt-BR'
92
92
 
93
93
  ```ts
94
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
95
+ bySlug: (slug) => …, // the CURRENT slug only: { id, slug, status, name? } | null
96
+ byId: (id, tx) => …, // on tx when given: { id, slug, status, name? } | null
97
97
  setStatusIf: (id, from, to, tx) => …, // compare-and-set ON tx: true only when the row moved
98
98
  clearProfile: (tx, id) => …, // erase the row's profile, on tx
99
99
  timeZone: (id) => …, // IANA zone
@@ -248,6 +248,114 @@ two members and the memory are checked at startup (`slugs.port.current`,
248
248
  - **One memory per channel per process**, shared by everything that reads
249
249
  under that channel. Two memories on one channel each open a listener.
250
250
 
251
+ ### Lifecycle (opt-in): close, reopen, the sweep, the gates
252
+
253
+ Additive: a host that passes no `lifecycle` boots unchanged and gets no
254
+ `tenant.lifecycle`.
255
+
256
+ ```ts
257
+ const tenant = createApiTenant({
258
+ statuses, ids, copy, port, tree, // tree optional
259
+ lifecycle: {
260
+ graceDays: 30, reminderDays: { week: 7, day: 1 }, // integers, 0 < day < week < graceDays
261
+ minReasonLength: 3, nameLocale: 'pt-BR', sweepBatch: 200,
262
+ copy: { locales: { 'pt-BR': { noticePlatformScheduledTitle, noticePlatformScheduledBody,
263
+ noticePlatformScheduledBodyNoReason, noticeReopenedRestoredTitle, noticeReopenedRestoredBody }, … } },
264
+ db: { transaction: (run) => prisma.$transaction(run), table: (tx) => (tx ?? prisma).tenantClosing },
265
+ blockers: { kinds: [{ kind: 'patients', path: 'ward' }, …], read: (tenantId, { now, tx }) => … },
266
+ openDescendants: { kind: 'units', path: 'units' }, // REQUIRED with `tree`, refused without
267
+ confirmDangerousAct: (request, { tenantId, by }) => …, // throws to refuse (a PIN check)
268
+ afterClose: ({ tenant, node, now }) => …, // throws = failed: stamped, audited, retried by the sweep
269
+ invalidate: (tenantId) => …,
270
+ notify: (typeId, payload) => …, // resolves true only once RECORDED
271
+ onPurgeDue: (tenantId, { now }) => …, // 'purged' | 'already' | 'skipped'
272
+ audit: (tx, action, event) => …, // on tx; action = ids.audit[event.act]
273
+ locale: () => …, onError: (error, { act, tenantId }) => …,
274
+ mirror, // optional: an older table you are moving (below)
275
+ },
276
+ });
277
+ ```
278
+
279
+ - **Your port MUST return `name` from `bySlug` and `byId`** once the lifecycle
280
+ is wired. `TenantRecord.name` stays optional for hosts without it; with it, a
281
+ record that lacks a name is a programming error, thrown as a
282
+ `TenantConfigError` on `port.byId` the first time the lifecycle needs it
283
+ (never a notice with an empty name).
284
+ - **The lifecycle's own sentences are a copy extension**,
285
+ `lifecycle.copy.locales.<tag>`, required for every tag of `copy.locales`
286
+ and validated per key (`lifecycle.copy.locales.pt-BR.noticePlatformScheduledBody`):
287
+ the platform close's title and body (with its reason, and
288
+ `noticePlatformScheduledBodyNoReason` when the notice carries none), and
289
+ `noticeReopenedRestored*`, which a reopen notice reads when it restored a
290
+ status other than active (`payload.restored`): a tenant reopened to
291
+ suspended is not live again, and its notice must not say so.
292
+ The base pack (`TENANT_COPY_SHAPE`) is unchanged. `blocker(kind, count,
293
+ detail?)` takes the blocker's optional `detail` (an amount and a date).
294
+ - **Two entries into one flow.** `close({ by: 'member', typedName, … })`
295
+ starts from `statuses.active` only and checks the typed name in
296
+ `nameLocale`; `close({ by: 'platform', … })` starts from any of
297
+ `statuses.closableFrom`, asks no name, writes `requested_by_id` null (your
298
+ audit line says who) and hands the reason to the scheduled notice
299
+ (`payload.reason`, words from `noticePlatformScheduled*`). Both record
300
+ `prior_status`; `reopen` restores it (or `active` when it is null or not a
301
+ live status).
302
+ - **The order of a close**: `confirmDangerousAct`, the reason, the name, then
303
+ ONE transaction (`setStatusIf`, your blockers read again ON `tx` plus the
304
+ open-descendants count, the row replaced, `mirror.replaced`, `audit`). A
305
+ blocker found there rolls the move back (409 `closingBlocked`, `details:
306
+ { pending }`). After the commit, never inside it: `afterClose` (with the
307
+ tenant's tree node, so a unit can skip its root's billing), `invalidate`,
308
+ `notify`. A hook that throws goes to `onError` and never undoes the close.
309
+ - **Refusals** are `TenantLifecycleRefusal { kind, code, status, details }`,
310
+ `code` from your `ids.refusals`, the message from `copyFor(locale())`. The
311
+ statuses are fixed: 403 closing/readOnly/closed, 409 gone, alreadyClosing,
312
+ notActive, closingBlocked, purged, notClosing, 422 reasonTooShort,
313
+ nameMismatch.
314
+ - **Schedule `tenant.lifecycle.sweep(now)`** on your own job runner (hourly is
315
+ plenty). Per row: skip a tenant no longer closing or closed; retry
316
+ `afterClose` while it has not gone through; once due, `onPurgeDue` and stamp
317
+ `purged_at` on `purged` or `already`; before that, send the reminder due,
318
+ stamped only once `notify` answered true.
319
+ - **Statement budget.** `state()` reads nothing for a live tenant and one row
320
+ for a gone one. `blockers()` and the close add ONE `treeDescendants` read
321
+ when a tree is wired: with the lifecycle, that read MUST return each node's
322
+ `status` (`TenantTreeNode.status`), or the blocker throws a
323
+ `TenantConfigError` on `tree.treeDescendants`. The sweep reads one `byId`
324
+ per row and stamps in a transaction of its own.
325
+ - **Stale rows heal.** A closing row whose tenant is neither closing nor
326
+ closed (reopened by a release that wrote only your older table, say) is
327
+ deleted by the sweep, conditionally on its `requestedAt`, with
328
+ `mirror.deleted`, in one transaction. It takes no slot of `sweepBatch`:
329
+ the sweep pages on (keyset on `purgeAt`, `tenantId`) until `sweepBatch`
330
+ live tenants were swept or no row is left.
331
+ - **Gates**: `createTenantGates(tenant, { admin: { prefix, closingWrites },
332
+ public: { prefix, families }, lookup, holdsClose, locale })` and
333
+ `mountTenantGates(app, gates)` from `@12-apps/tenant/hono`. `lookup` is your
334
+ kept slug lookup (the status rides it: an open tenant pays nothing more); a
335
+ family's `fixedWords` are never looked up; `slugAfter` names words after
336
+ which the next segment is the slug. The middlewares are typed structurally
337
+ (`TenantGateMiddleware`), so they fit whatever Hono version you resolve.
338
+ - **Notice words without the hooks**: `createNoticeWords(tenant, { copy })`
339
+ answers `noticeWords` alone, for a notification registry that renders the
340
+ lifecycle's notices apart from the module that wires its hooks. It
341
+ validates the extension as the lifecycle does, and a locale without one
342
+ reads the default locale's.
343
+ - **`TenantTree.nodeOf` is optional on the type** (added in this minor, so a
344
+ host typing a tree of its own keeps compiling); `createTenantTree` always
345
+ provides it, and the lifecycle reads no node when it is absent.
346
+
347
+ #### Moving an older closing table (expand and contract)
348
+
349
+ Pass `mirror: { replaced, event, deleted }`: each runs on the package's own
350
+ transaction, so the two tables never disagree. `deleted(tx, tenantId, requestedAt?)`
351
+ hands you the deleted row's `requestedAt`: delete your old row only while it
352
+ is that same close, so a re-close your previous release wrote meanwhile
353
+ survives (absent when the package read no row: delete by tenant). Write each stamp where it is
354
+ still null, as the package does. Rows your PREVIOUS release wrote only into
355
+ the old table (during a rolling deploy) are not in `tenant_closings`: before
356
+ each sweep, catch them up with one upsert (`INSERT … SELECT … ON CONFLICT
357
+ (tenant_id) DO UPDATE`), and backfill once with a data-only migration.
358
+
251
359
  ### The schema and the migration
252
360
 
253
361
  - Copy the partial into your schema folder with
package/README.md CHANGED
@@ -26,16 +26,18 @@ This first release ships the **contract** every later behaviour extends:
26
26
  - the package's own tables, `tenant_closings` and `tenant_data_exports`, as a
27
27
  Prisma partial with its own migration.
28
28
 
29
- The lifecycle (close, reopen, the sweep), the purge and the data export arrive
30
- in later releases on top of the same config. How to adopt it: [ADOPTING.md](./ADOPTING.md).
29
+ The closing lifecycle (close and reopen as a dangerous act, the blockers, the
30
+ sweep that reminds and purges, and the admin and public gates) is opt-in:
31
+ `createApiTenant({ lifecycle })` and `createTenantGates`. The purge and the
32
+ data export arrive in later releases on top of the same config. How to adopt it: [ADOPTING.md](./ADOPTING.md).
31
33
 
32
34
  ## Entry points
33
35
 
34
36
  | Import | What | Needs |
35
37
  |---|---|---|
36
- | `@12-apps/tenant` | config types, `TenantPort`, `TenantConfigError`, the validators, the tree (`createTenantTree`, the path helpers, `TenantTreeError`), slug resolution (`createKeptMemory`, `createSlugResolver`, `createKeptSlugs`, `createTenantSlugs`, `TenantSlugPort`) | nothing |
37
- | `@12-apps/tenant/server` | `createApiTenant` (with `tenant.tree` when a `tree` port is given, `tenant.slugs` when `slugs` is), and the slug resolution exports | nothing |
38
- | `@12-apps/tenant/hono` | `mountTenant(app, tenant)` | `hono` |
38
+ | `@12-apps/tenant` | config types, the lifecycle's pure readings (`isTenantGone`, `sameTenantName`, `purgeAtFor`, `reminderDue`), `TenantPort`, `TenantConfigError`, the validators, the tree (`createTenantTree`, the path helpers, `TenantTreeError`), slug resolution (`createKeptMemory`, `createSlugResolver`, `createKeptSlugs`, `createTenantSlugs`, `TenantSlugPort`) | nothing |
39
+ | `@12-apps/tenant/server` | `createApiTenant` (with `tenant.tree` when a `tree` port is given, `tenant.slugs` when `slugs` is, `tenant.lifecycle` when `lifecycle` is), `createTenantLifecycle`, `createTenantGates`, `TenantLifecycleRefusal`, and the slug resolution exports | nothing |
40
+ | `@12-apps/tenant/hono` | `mountTenant(app, tenant)`, `mountTenantGates(app, gates)`, `tenantAdminGate`, `tenantPublicGate` | `hono` |
39
41
  | `@12-apps/tenant/react` | `createWebTenant` | nothing yet |
40
42
  | `@12-apps/tenant/manifest` | the wiring manifest (`db`) | `@12-apps/wiring` (types) |
41
43
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@12-apps/tenant",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "sideEffects": false,
package/src/config.ts CHANGED
@@ -245,8 +245,12 @@ export interface TenantCopyPack {
245
245
  readonly refusalExportExpired: string;
246
246
  readonly pendingTitle: string;
247
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;
248
+ /**
249
+ * One line per kind of blocker; `kind` is one of the host's own blocker
250
+ * kinds. `detail` is whatever the host's blocker read attached to it (an
251
+ * amount and a date, say), passed through as given.
252
+ */
253
+ readonly blocker: (kind: string, count: number, detail?: Readonly<Record<string, string | number>>) => string;
250
254
  /** The shortcut that resolves a blocker of that kind. */
251
255
  readonly shortcut: (kind: string) => string;
252
256
  readonly dataTitle: string;
package/src/hono/index.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import type { Hono } from 'hono';
8
8
 
9
+ import type { GateRefusal, TenantGates } from '../lifecycle';
9
10
  import type { ApiTenant } from '../server';
10
11
 
11
12
  /** Mount every route of `tenant` on `app`, in order. Returns `app`. */
@@ -15,3 +16,53 @@ export function mountTenant<A extends Pick<Hono, 'on'>>(app: A, tenant: Pick<Api
15
16
  }
16
17
  return app;
17
18
  }
19
+
20
+ /**
21
+ * A gate middleware, typed structurally (the request it reads and the `next`
22
+ * it calls), so it fits any Hono version the host resolves the optional peer to.
23
+ */
24
+ export type TenantGateMiddleware = (
25
+ context: { req: { raw: Request } },
26
+ next: () => Promise<void>,
27
+ ) => Promise<Response | undefined>;
28
+
29
+ /** The one member of a Hono app the gate mount calls. */
30
+ export interface TenantGateApp {
31
+ use(path: string, handler: TenantGateMiddleware): unknown;
32
+ }
33
+
34
+ /** A refusal as the response every gate renders: `{ error, code, details: {} }` with its status. */
35
+ function refused(refusal: GateRefusal): Response {
36
+ return Response.json({ error: refusal.message, code: refusal.code, details: {} }, { status: refusal.status });
37
+ }
38
+
39
+ /** The admin gate as a middleware: mount it on `<admin.prefix>/*`. */
40
+ export function tenantAdminGate(gates: Pick<TenantGates, 'adminRefusal'>): TenantGateMiddleware {
41
+ return async (context, next) => {
42
+ const refusal = await gates.adminRefusal(context.req.raw);
43
+ if (refusal !== null) return refused(refusal);
44
+ await next();
45
+ return undefined;
46
+ };
47
+ }
48
+
49
+ /** The public gate as a middleware: mount it on each `<public.prefix>/<family>/*`. */
50
+ export function tenantPublicGate(gates: Pick<TenantGates, 'publicRefusal'>): TenantGateMiddleware {
51
+ return async (context, next) => {
52
+ const refusal = await gates.publicRefusal(context.req.raw);
53
+ if (refusal !== null) return refused(refusal);
54
+ await next();
55
+ return undefined;
56
+ };
57
+ }
58
+
59
+ /** Mount both gates: `<admin.prefix>/*`, then `<public.prefix>/<family>/*` for each family. Returns `app`. */
60
+ export function mountTenantGates<A extends TenantGateApp>(
61
+ app: A,
62
+ gates: Pick<TenantGates, 'adminRefusal' | 'publicRefusal' | 'config'>,
63
+ ): A {
64
+ app.use(`${gates.config.admin.prefix}/*`, tenantAdminGate(gates));
65
+ const pub = tenantPublicGate(gates);
66
+ for (const family of Object.keys(gates.config.public.families)) app.use(`${gates.config.public.prefix}/${family}/*`, pub);
67
+ return app;
68
+ }
package/src/index.ts CHANGED
@@ -65,3 +65,23 @@ export {
65
65
  } from './slugs';
66
66
  export { TenantConfigError, validateCoreConfig, validatePort, validateSlugs, validateTreePort } from './validate';
67
67
  export type { DeepReadonly, TenantReadings, TenantRefusalKind } from './core';
68
+ export {
69
+ TENANT_LIFECYCLE_COPY_KEYS,
70
+ TENANT_REFUSAL_STATUS,
71
+ isTenantGone,
72
+ purgeAtFor,
73
+ reminderDue,
74
+ sameTenantName,
75
+ type GateRefusal,
76
+ type TenantAuditEvent,
77
+ type TenantBlocker,
78
+ type TenantBlockerCount,
79
+ type TenantBlockerKind,
80
+ type TenantCloseEntry,
81
+ type TenantClosingEvent,
82
+ type TenantClosingState,
83
+ type TenantLifecycleCopyPack,
84
+ type TenantLifecycleRefusalKind,
85
+ type TenantNoticePayload,
86
+ type TenantReminder,
87
+ } from './lifecycle';
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Closing a tenant and reopening it.
3
+ *
4
+ * **Close**, a dangerous act: the host's confirmation first, then the reason
5
+ * and (a member's close) the typed name, then ONE transaction: the
6
+ * conditional status move, the blockers counted AGAIN after it (anything
7
+ * found rolls the move back), the closing row replaced, the mirror, the audit
8
+ * line. After the commit, and never able to undo it: the after-close hook
9
+ * (stamped either way; a failure is audited and the sweep retries it), the
10
+ * cache invalidation and the notice.
11
+ *
12
+ * **Reopen**: the row read once, then ONE transaction: closing → the status
13
+ * the close started from (a valid one, else active), the row deleted, the
14
+ * mirror, the audit line. Then the invalidation and the notice.
15
+ */
16
+ import type { TenantStatusSet } from '../config';
17
+ import type { TenantRecord } from '../port';
18
+ import type { LifecycleContext } from './context';
19
+ import { purgeAtFor, sameTenantName } from './pure';
20
+ import type {
21
+ TenantCloseEntry,
22
+ TenantClosingCreate,
23
+ TenantClosingState,
24
+ TenantLifecycle,
25
+ TenantNoticePayload,
26
+ } from './types';
27
+
28
+ type CloseInput<S extends string> = Parameters<TenantLifecycle<S>['close']>[0];
29
+
30
+ export function payloadOf(
31
+ tenant: TenantRecord,
32
+ name: string,
33
+ purgeAt: Date,
34
+ by: TenantCloseEntry | null,
35
+ reason: string | null,
36
+ restored: string | null = null,
37
+ ): TenantNoticePayload {
38
+ return { tenantId: tenant.id, name, slug: tenant.slug, purgeAt: purgeAt.toISOString(), by, reason, restored };
39
+ }
40
+
41
+ /** Where `close` and `reopen` get their record: the caller, who read it through the port or its own lookup. */
42
+ const CALLER_RECORD = 'close/reopen tenant (the caller\'s record, port.bySlug/byId)';
43
+
44
+ /** The refusal for a tenant the close may not move, by the status the transaction reads. */
45
+ async function notClosable<S extends string, Tx>(context: LifecycleContext<S, Tx>, id: string, tx: Tx): Promise<Error> {
46
+ const current = await context.tenant.byId(id, tx);
47
+ return context.refuse(current !== null && context.isGone(current.status) ? 'alreadyClosing' : 'notActive');
48
+ }
49
+
50
+ /** The transaction: the move, the recount, the row, the mirror and the audit line. */
51
+ async function closeInTransaction<S extends string, Tx>(
52
+ context: LifecycleContext<S, Tx>,
53
+ input: CloseInput<S>,
54
+ row: TenantClosingCreate,
55
+ ): Promise<void> {
56
+ const { tenant, config } = context;
57
+ const { ids } = tenant.config;
58
+ const statuses = tenant.config.statuses as unknown as TenantStatusSet<S>;
59
+ const from: readonly string[] = input.by === 'member' ? [statuses.active] : statuses.closableFrom;
60
+ const id = input.tenant.id;
61
+ await config.db.transaction(async (tx) => {
62
+ if (!from.includes(input.tenant.status)) throw await notClosable(context, id, tx);
63
+ if (!(await tenant.setStatusIf(id, input.tenant.status, statuses.closing, tx))) throw await notClosable(context, id, tx);
64
+ // After the move, in the same transaction: what landed since the page's read is seen here, and rolls the move back.
65
+ const blockers = await context.blockersOf(id, row.requestedAt, tx);
66
+ if (blockers.length > 0) throw context.refuse('closingBlocked', { pending: blockers.length }, blockers.length);
67
+ const table = await context.table(tx);
68
+ // A row an earlier close left (reopened by the platform before a stamp cleared it) is replaced: fresh stamps.
69
+ await table.deleteMany({ where: { tenantId: id } });
70
+ await table.create({ data: row });
71
+ if (config.mirror !== undefined) await config.mirror.replaced(tx, row);
72
+ await config.audit(tx, ids.audit.closeScheduled, {
73
+ act: 'closeScheduled',
74
+ tenantId: id,
75
+ by: input.by,
76
+ reason: row.reason,
77
+ purgeAt: row.purgeAt,
78
+ priorStatus: input.tenant.status,
79
+ });
80
+ });
81
+ }
82
+
83
+ /** The after-close hook, stamped either way; a failure is audited with its stamp, in one transaction. */
84
+ export async function runAfterClose<S extends string, Tx>(
85
+ context: LifecycleContext<S, Tx>,
86
+ tenant: TenantRecord<S>,
87
+ now: Date,
88
+ ): Promise<boolean> {
89
+ const { config } = context;
90
+ try {
91
+ const node = (await context.tenant.tree?.nodeOf?.(tenant.id)) ?? null;
92
+ await config.afterClose({ tenant, node, now });
93
+ } catch (error) {
94
+ config.onError(error, { act: 'afterClose', tenantId: tenant.id });
95
+ const message = (error instanceof Error ? error.message : String(error)).slice(0, 200);
96
+ await context.quietly('afterCloseFailed', tenant.id, () =>
97
+ config.db.transaction(async (tx) => {
98
+ await (await context.table(tx)).updateMany({
99
+ where: { tenantId: tenant.id, afterCloseDoneAt: null },
100
+ data: { afterCloseFailedAt: now },
101
+ });
102
+ if (config.mirror !== undefined) await config.mirror.event(tx, tenant.id, { kind: 'afterClose', ok: false, at: now });
103
+ await config.audit(tx, context.tenant.config.ids.audit.afterCloseFailed, {
104
+ act: 'afterCloseFailed',
105
+ tenantId: tenant.id,
106
+ error: message,
107
+ });
108
+ }),
109
+ );
110
+ return false;
111
+ }
112
+ // The hook went through; a missed stamp only means the sweep runs it again, which the host's hook must tolerate.
113
+ await context.quietly('afterCloseStamp', tenant.id, () =>
114
+ context.stamp(tenant.id, 'afterCloseDoneAt', now, { kind: 'afterClose', ok: true, at: now }),
115
+ );
116
+ return true;
117
+ }
118
+
119
+ export async function closeTenant<S extends string, Tx>(
120
+ context: LifecycleContext<S, Tx>,
121
+ given: CloseInput<S>,
122
+ ): Promise<TenantClosingState<S>> {
123
+ // A snapshot: the status the close starts from is the one the caller read, whatever happens to its object.
124
+ const input = { ...given, tenant: { ...given.tenant } };
125
+ const { config } = context;
126
+ const { ids } = context.tenant.config;
127
+ const statuses = context.tenant.config.statuses as unknown as TenantStatusSet<S>;
128
+ const id = input.tenant.id;
129
+ await config.confirmDangerousAct(input.request, { tenantId: id, by: input.by });
130
+ const reason = input.reason.trim();
131
+ if (reason.length < config.minReasonLength) throw context.refuse('reasonTooShort');
132
+ const name = context.nameOf(input.tenant, CALLER_RECORD);
133
+ if (input.by === 'member' && !sameTenantName(input.typedName ?? '', name, config.nameLocale)) {
134
+ throw context.refuse('nameMismatch');
135
+ }
136
+ const now = input.now ?? new Date();
137
+ const purgeAt = purgeAtFor(now, config.graceDays);
138
+ const row: TenantClosingCreate = {
139
+ tenantId: id,
140
+ requestedAt: now,
141
+ requestedById: input.by === 'member' ? input.actorUserId : null,
142
+ reason,
143
+ priorStatus: input.tenant.status,
144
+ purgeAt,
145
+ };
146
+ await closeInTransaction(context, input, row);
147
+ await runAfterClose(context, input.tenant, now);
148
+ await context.quietly('invalidate', id, () => config.invalidate(id));
149
+ await context.quietly('notify', id, () =>
150
+ config.notify(
151
+ ids.notifications.closingScheduled,
152
+ payloadOf(input.tenant, name, purgeAt, input.by, input.by === 'platform' ? reason : null),
153
+ ),
154
+ );
155
+ return { status: statuses.closing, requestedAt: now.toISOString(), purgeAt: purgeAt.toISOString() };
156
+ }
157
+
158
+ export async function reopenTenant<S extends string, Tx>(
159
+ context: LifecycleContext<S, Tx>,
160
+ input: { tenant: TenantRecord<S>; by: TenantCloseEntry },
161
+ ): Promise<TenantClosingState<S>> {
162
+ const { config } = context;
163
+ const { ids } = context.tenant.config;
164
+ const statuses = context.tenant.config.statuses as unknown as TenantStatusSet<S>;
165
+ const id = input.tenant.id;
166
+ const name = context.nameOf(input.tenant, CALLER_RECORD);
167
+ const row = await (await context.table()).findUnique({ where: { tenantId: id } });
168
+ const prior = row?.priorStatus ?? null;
169
+ const target = (
170
+ prior !== null && (statuses.all as readonly string[]).includes(prior) && !context.isGone(prior) ? prior : statuses.active
171
+ ) as S;
172
+ await config.db.transaction(async (tx) => {
173
+ if (!(await context.tenant.setStatusIf(id, statuses.closing, target, tx))) {
174
+ throw context.refuse(row?.purgedAt ? 'purged' : 'notClosing');
175
+ }
176
+ await (await context.table(tx)).deleteMany({ where: { tenantId: id } });
177
+ if (config.mirror !== undefined) await config.mirror.deleted(tx, id, row?.requestedAt);
178
+ await config.audit(tx, ids.audit.closeReopened, {
179
+ act: 'closeReopened',
180
+ tenantId: id,
181
+ by: input.by,
182
+ purgeAt: row?.purgeAt ?? null,
183
+ restored: target,
184
+ });
185
+ });
186
+ await context.quietly('invalidate', id, () => config.invalidate(id));
187
+ await context.quietly('notify', id, () =>
188
+ config.notify(ids.notifications.reopened, payloadOf(input.tenant, name, row?.purgeAt ?? new Date(), null, null, target)),
189
+ );
190
+ return { status: target, requestedAt: null, purgeAt: null };
191
+ }
@@ -0,0 +1,126 @@
1
+ /**
2
+ * What every lifecycle step shares: the tenant's readings, the validated
3
+ * config, and the small helpers that keep each step's rules in one place.
4
+ */
5
+ import type { TenantCopyPack, TenantCoreConfig } from '../config';
6
+ import type { DeepReadonly } from '../core';
7
+ import type { TenantRecord } from '../port';
8
+ import type { TenantTree } from '../tree';
9
+ import { TenantConfigError } from '../validate';
10
+ import { TENANT_REFUSAL_STATUS, TenantLifecycleRefusal, refusalSentence, type TenantLifecycleRefusalKind } from './refusal';
11
+ import type { TenantBlocker, TenantClosingEvent, TenantClosingStamp, TenantClosingTable, TenantLifecycleConfig } from './types';
12
+
13
+ /** The slice of `ApiTenant` the lifecycle reads. */
14
+ export interface LifecycleTenant<S extends string, Tx> {
15
+ config: DeepReadonly<TenantCoreConfig<S>>;
16
+ copyFor(locale: string | null | undefined): TenantCopyPack;
17
+ byId(id: string, tx?: Tx): Promise<TenantRecord<S> | null>;
18
+ setStatusIf(id: string, from: S, to: S, tx: Tx): Promise<boolean>;
19
+ tree?: TenantTree<Tx>;
20
+ }
21
+
22
+ export interface LifecycleContext<S extends string, Tx> {
23
+ tenant: LifecycleTenant<S, Tx>;
24
+ config: TenantLifecycleConfig<S, Tx>;
25
+ /** The table on `tx`, or on the client. */
26
+ table(tx?: Tx): Promise<TenantClosingTable>;
27
+ /** A refusal of `kind`, in the current request's words. */
28
+ refuse(kind: TenantLifecycleRefusalKind, details?: Readonly<Record<string, number>>, count?: number): TenantLifecycleRefusal;
29
+ /** Run `step`; a throw goes to `onError` and never past it. */
30
+ quietly(act: string, tenantId: string, step: () => Promise<unknown>): Promise<void>;
31
+ /** Stamp `field` where still null, with the mirror's event, in one transaction. Answers the rows stamped. */
32
+ stamp(tenantId: string, field: TenantClosingStamp, at: Date, event: TenantClosingEvent): Promise<number>;
33
+ /** The record's name: a lifecycle host's port must return it. */
34
+ /** `source` names where the record came from, for the error a missing name throws. */
35
+ nameOf(record: TenantRecord<S>, source: string): string;
36
+ /** Whether `status` is closing or closed. */
37
+ isGone(status: string): boolean;
38
+ /** The tenant's open blockers, counted on `tx` when given. */
39
+ blockersOf(tenantId: string, now: Date, tx?: Tx): Promise<TenantBlocker[]>;
40
+ }
41
+
42
+ /** The tree's blocker: descendants other than the tenant that are neither closing nor closed. */
43
+ async function openDescendants<S extends string, Tx>(
44
+ context: Pick<LifecycleContext<S, Tx>, 'tenant' | 'isGone'>,
45
+ tenantId: string,
46
+ tx: Tx | undefined,
47
+ ): Promise<number> {
48
+ const { tree } = context.tenant;
49
+ if (tree === undefined) return 0;
50
+ // ONE read: the host's descendants read carries each node's status (required with the lifecycle).
51
+ const below = await tree.descendantsOf(tenantId, tx);
52
+ return below.filter((node) => {
53
+ if (typeof node.status !== 'string') {
54
+ throw new TenantConfigError(
55
+ 'tree.treeDescendants',
56
+ `returned tenant "${node.id}" with no status, which the lifecycle's open-descendants blocker needs`,
57
+ );
58
+ }
59
+ return !context.isGone(node.status);
60
+ }).length;
61
+ }
62
+
63
+ export function createContext<S extends string, Tx>(
64
+ tenant: LifecycleTenant<S, Tx>,
65
+ config: TenantLifecycleConfig<S, Tx>,
66
+ ): LifecycleContext<S, Tx> {
67
+ const { statuses, ids } = tenant.config;
68
+ const paths = new Map(config.blockers.kinds.map((entry) => [entry.kind, entry.path]));
69
+ const table = async (tx?: Tx) => config.db.table(tx);
70
+ const context: LifecycleContext<S, Tx> = {
71
+ tenant,
72
+ config,
73
+ table,
74
+ refuse: (kind, details = {}, count = 0) =>
75
+ new TenantLifecycleRefusal(
76
+ {
77
+ kind,
78
+ status: TENANT_REFUSAL_STATUS[kind],
79
+ code: ids.refusals[kind],
80
+ message: refusalSentence(tenant.copyFor(config.locale()), kind, count),
81
+ },
82
+ details,
83
+ ),
84
+ quietly: async (act, tenantId, step) => {
85
+ try {
86
+ await step();
87
+ } catch (error) {
88
+ config.onError(error, { act, tenantId });
89
+ }
90
+ },
91
+ stamp: (tenantId, field, at, event) =>
92
+ config.db.transaction(async (tx) => {
93
+ const { count } = await (await table(tx)).updateMany({
94
+ where: { tenantId, [field]: null },
95
+ data: { [field]: at },
96
+ });
97
+ if (count > 0 && config.mirror !== undefined) await config.mirror.event(tx, tenantId, event);
98
+ return count;
99
+ }),
100
+ nameOf: (record, source) => {
101
+ if (typeof record.name !== 'string') {
102
+ throw new TenantConfigError(source, `gave tenant "${record.id}" with no name, which the lifecycle needs`);
103
+ }
104
+ return record.name;
105
+ },
106
+ isGone: (status) => status === statuses.closing || status === statuses.closed,
107
+ blockersOf: async (tenantId, now, tx) => {
108
+ const counts = await config.blockers.read(tenantId, tx === undefined ? { now } : { now, tx });
109
+ const found: TenantBlocker[] = counts
110
+ .filter((entry) => entry.count > 0)
111
+ .map((entry) => {
112
+ const path = paths.get(entry.kind);
113
+ if (path === undefined) {
114
+ throw new TenantConfigError('lifecycle.blockers.kinds', `does not list "${entry.kind}", which blockers.read answered`);
115
+ }
116
+ return { ...entry, path };
117
+ });
118
+ const open = await openDescendants(context, tenantId, tx);
119
+ if (open > 0 && config.openDescendants !== undefined) {
120
+ found.push({ kind: config.openDescendants.kind, count: open, path: config.openDescendants.path });
121
+ }
122
+ return found;
123
+ },
124
+ };
125
+ return context;
126
+ }