@12-apps/tenant 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ADOPTING.md ADDED
@@ -0,0 +1,195 @@
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 tenant tree (opt-in)
116
+
117
+ A tenant may sit under another (ownership only, any depth: a company above its
118
+ units, a unit above its venues). **The tree is optional.** A host with no tree
119
+ passes no `tree` and gets no `tenant.tree` (`createApiTenant` leaves the key
120
+ out); a host written for a release before the tree boots unchanged, since none
121
+ of the tree's methods is on the tenant port. A host that wants it passes its
122
+ own port as `tree`, and then all four members are required and checked at
123
+ startup (`TenantConfigError`, key `tree.<method>`):
124
+
125
+ ```ts
126
+ const tree: TenantTreePort<Tx> = {
127
+ treeNode: (id, tx) => …, // on tx when given: { id, parentId, path } | null — one read
128
+ treeAncestors: (id, tx) => …, // on tx when given: the node and every node above it — one read
129
+ treeDescendants: (id, tx) => …, // on tx when given: the node and every node below it — one read
130
+ moveSubtree: (move, tx) => …, // a planned move ON tx — lock, then ONE rewrite; rows written
131
+ };
132
+ const tenant = createApiTenant({ ...config, port, tree });
133
+ ```
134
+
135
+ Store three columns on your tenant row: the parent's id (NULL for a standalone
136
+ tenant), the **materialized path** and, if you want one, your own unit code.
137
+ The package computes and validates every path; you store it and apply what it
138
+ plans.
139
+
140
+ - **The path** is `/<root id>/…/<own id>/`; a standalone tenant's is
141
+ `/<own id>/`, so backfilling an existing table makes every row a root.
142
+ Ids must not contain `/`.
143
+ - **`treeAncestors(id)`**: ONE read of the rows whose ids are the segments of
144
+ the tenant's own path (a primary-key read; nothing recurses).
145
+ - **`treeDescendants(id)`**: ONE read of the rows whose path starts with the
146
+ tenant's own, served by an index on the path. With a byte-ordered collation
147
+ (Postgres `COLLATE "C"`) the prefix is exactly the range
148
+ `path >= p AND path < p-minus-its-last-"/" || '0'`.
149
+ - **`moveSubtree(move, tx)`**, on the caller's transaction:
150
+ 1. **Lock** every row of the subtree AND the new parent `FOR UPDATE`, in ONE
151
+ global order that never changes (by id). Two crossing moves (A under B
152
+ while B goes under A) then wait on each other instead of deadlocking.
153
+ 2. **Rewrite** in ONE statement: replace the prefix `move.fromPath` with
154
+ `move.toPath` on every row under it and re-point the row `move.id` at
155
+ `move.parentId`, ONLY while that row's path is still `fromPath` and the
156
+ parent's is still `parentPath`. Answer the rows written; 0 tells the
157
+ package the tree moved under its plan, and it refuses the move by name
158
+ (`moved`).
159
+ - **A new unit reads its parent's path `FOR SHARE`** (an insert trigger, or
160
+ your writer). With the move's lock above, an insert under a moving tenant
161
+ either waits for the move and takes the moved path, or commits first and the
162
+ move's rewrite (a later statement) moves it too. Without both locks a unit
163
+ can keep a stale prefix, and a stale prefix names the wrong ancestors.
164
+ - **Hold the row to its path** in the database too: a path that names the row
165
+ once and last, and is `/<own id>/` exactly when there is no parent, so no
166
+ writer can store a cycle. Such a check does not hold the path's PREFIX to
167
+ the parent's path; only the port's writes keep that true, so write the tree
168
+ through them.
169
+
170
+ `tenant.tree` answers `parentOf`, `rootOf`, `ancestorsOf`, `descendantsOf` (one
171
+ port call each, at any depth; each takes your transaction optionally) and
172
+ `move(id, parentId, tx)`, which runs its reads and its write in your
173
+ transaction (required) and refuses a cycle (`TenantTreeError`, code `cycle`)
174
+ before anything is written.
175
+
176
+ A grant across a tree is your authorization's business, not the package's.
177
+ Keep it distinguishable from a grant on the parent tenant itself: a scope that
178
+ names "the tenants below X" must never be the same string as X's own. And
179
+ wherever you gather the holders of grants by scope, gather the WHOLE chain
180
+ above a tenant, not only its parent.
181
+
182
+ ### The schema and the migration
183
+
184
+ - Copy the partial into your schema folder with
185
+ `pnpm --filter @12-apps/tenant prisma:sync` (`prisma:sync:check` fails on
186
+ drift). It is COPIED, never symlinked.
187
+ - The migration (`prisma/migrations/20261126120000_tenant_closings_and_exports`)
188
+ is discovered from the installed package like every other `@12-apps/*`
189
+ migration. It is additive: two new tables, no foreign key into yours.
190
+ - Moving existing closing or export rows into these tables is your own
191
+ expand-and-contract: copy and dual-write from the release that first writes
192
+ them, and drop your old tables only in a later release.
193
+ - **The tables have no foreign key, so nothing cascades.** A host that
194
+ hard-deletes a tenant row deletes that tenant's `tenant_closings` and
195
+ `tenant_data_exports` rows itself (or adds its own FK in a host migration).
package/README.md CHANGED
@@ -1,3 +1,72 @@
1
- # Temporary Holding Version
1
+ # @12-apps/tenant
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 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
+ - the **tenant tree**, OPT-IN: a tenant under a parent, any depth, on a
19
+ materialized path the package computes and validates, through a `tree` port
20
+ of its own (`treeNode`, `treeAncestors`, `treeDescendants`,
21
+ `moveSubtree(move, tx)`); `parentOf`, `rootOf`, `ancestorsOf`, `descendantsOf`
22
+ (one port call each) and a subtree `move` that refuses a cycle. A host that
23
+ passes no `tree` gets no `tenant.tree`;
24
+ - `createApiTenant` and `createWebTenant`, which validate all of it at startup
25
+ and keep a deep-frozen copy of the data;
26
+ - the package's own tables, `tenant_closings` and `tenant_data_exports`, as a
27
+ Prisma partial with its own migration.
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).
31
+
32
+ ## Entry points
33
+
34
+ | Import | What | Needs |
35
+ |---|---|---|
36
+ | `@12-apps/tenant` | config types, `TenantPort`, `TenantConfigError`, the validators, the tree (`createTenantTree`, the path helpers, `TenantTreeError`) | nothing |
37
+ | `@12-apps/tenant/server` | `createApiTenant` (with `tenant.tree` when a `tree` port is given) | nothing |
38
+ | `@12-apps/tenant/hono` | `mountTenant(app, tenant)` | `hono` |
39
+ | `@12-apps/tenant/react` | `createWebTenant` | nothing yet |
40
+ | `@12-apps/tenant/manifest` | the wiring manifest (`db`) | `@12-apps/wiring` (types) |
41
+
42
+ ## Rules the package keeps
43
+
44
+ - **Domain-agnostic.** `src/__tests__/domain-agnostic.test.ts` searches every
45
+ source file, as whole words and ignoring case, for the vocabulary of the host
46
+ the package was extracted from, and must find nothing.
47
+ - **Copy is config, as whole sentences.** No copy ships with the package. A noun
48
+ alone is not enough: in a gendered language the noun changes the rest of the
49
+ sentence. A sentence that carries a value (a count, a name, a day) is a
50
+ function the host writes, so plurals and word order stay the host's.
51
+ - **Ids are config.** Refusal codes, audit action ids, notification type ids and
52
+ permission ids are the host's, so its clients and its stored rows never change.
53
+ - **Required config, never defaults.** A missing piece throws a
54
+ `TenantConfigError` naming the key, at startup.
55
+ - **The tenant row stays the host's.** The package never maps it; its own tables
56
+ are keyed by an opaque `tenant_id` with no foreign key. `bySlug` resolves the
57
+ tenant's CURRENT slug only; former slugs a host keeps are the address
58
+ behaviour's, through a port of its own.
59
+
60
+ ## Tables
61
+
62
+ | Table | Rows |
63
+ |---|---|
64
+ | `tenant_closings` | one per tenant while it is closing, kept once purged; reopening deletes it |
65
+ | `tenant_data_exports` | one per export request; at most one `PREPARING` per tenant |
66
+
67
+ `tenant_closings.prior_status` records the host status a close started from (a
68
+ suspended tenant may be closed by the platform), so a reopen restores it. The
69
+ actor is `requested_by_id`: a user id, or null for a platform actor with no user
70
+ row, so no separate actor column exists. `after_close_done_at` /
71
+ `after_close_failed_at` record the host's after-close hook (a billing cancel, for
72
+ 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": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.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
+ }