@ordinatio/entities 1.5.0 → 1.6.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/README.md CHANGED
@@ -203,6 +203,22 @@ Pure, zero-dependency helpers for companies, on their own subpath so a browser c
203
203
 
204
204
  Pure, zero-dependency helpers for tags, on their own subpath so a browser component can import them without pulling in the rest of the package (no Prisma, zod or Node modules): `tagNameKey` / `cleanTagName` / `checkTagName` (the case-insensitive identity of a name; **pinned to its first shipped behaviour** because apps store the key in a unique column), `TAG_COLORS` / `isTagColor` / `resolveTagColor`, `DEFAULT_TAG_LIMITS` (name length 40, 50 changes per save, 15 pinned, 500 per workspace: defaults, a store takes them as arguments), and the picker helpers `describeTagChanges`, `tagSetKey`, `rebaseSelection`, `mergeTagOptions`. The `./schemas` and `./errors` subpaths exist only in the workspace (source) exports map and are not part of the published package yet. On the separate server entry `@ordinatio/entities/tags/server` (EXPERIMENTAL until a second product has used it): the `TagStore` interface (built per workspace, so the package never sees a tenant id; atomic, typed, limit-aware operations), `createTagService(store, limits?)` (the tag rules over any store: validate and clean names and colours, create and find-or-create, rename/recolour/pin, remove, apply only the changes a user made to one item's tags, and read tags back sorted; every outcome a user can cause is a typed `{ ok: false, reason, ... }` result with the context an app needs for its message, and a store result it does not know throws; a store that throws is not caught, so an app that must never fail a page, such as a sidebar of pinned tags, wraps that one call itself; `pinned()` asks the store for the first `maxPinned` pinned tags, so make `listPinned` return them in a stable order such as by name), `planTagChanges`, an in-memory reference store (`createMemoryTagWorld`, `createMemoryTagHarness`) and the store contract suite `defineTagStoreContract` that any storage adapter must pass (framework-agnostic: pass your runner's `describe`/`it`/`expect`). On a further entry, `@ordinatio/entities/tags/prisma` (also EXPERIMENTAL): `createPrismaTagStore(config)`, a ready-made `TagStore` for a Prisma client on Postgres, so an app writes configuration instead of storage code. It holds the generic storage rules: a per-workspace advisory lock around the two limits (the lock key prefix is configurable, so an app can keep an older key), lock waits that THROW on timeout in create, pin and update (a remove and a link write start no explicit lock of their own, so they wait only on locks other transactions hold, bounded only if those transactions are), `FOR UPDATE` on the tag row in an update (which briefly serialises with the key-share lock a concurrent link insert takes on the same tag), `createManyAndReturn` and `DELETE ... RETURNING` so `added` and `removed` come from rows really written, and foreign-key-abort handling (a link to a tag or item deleted a moment ago becomes `tagGone` or `targetGone`, decided by a fresh read after the aborted transaction). The configuration names your client (as a getter, called each time the store needs the client), the tag model and table, the workspace column, and per taggable kind the join model, table and columns and the item model; every name that reaches SQL is checked once and double-quoted, values are always bound. It needs Prisma 5.14 or later and unique and foreign-key constraints in your database (listed at the top of its `types.ts`) and does not import `@prisma/client`. **Prove it on YOUR database** by running `defineTagStoreContract` against it with a harness of your own (with at least ten connections available): the contract, not the unit tests of this package, is what shows the SQL, the locks and the foreign keys behave. Pin this package's exact version while the server entry is experimental: adding a required store method or a contract rule can break an adapter that passed before. The concurrency tests are meaningful only against a real store: run them against your database with a connection pool of at least 10. **Adapters and mappers must treat an unknown result `kind` or reason as an error**, never as success: adding a kind is a breaking change for an exhaustive switch.
205
205
 
206
+ ### Soft delete (Trash), 1.6.0
207
+
208
+ Three OPT-IN options, all off by default: a consumer that sets none of them gets exactly the queries and SQL of 1.5.0 (pinned by the snapshot tests `src/companies/prisma/off-baseline.test.ts`, `src/tags/prisma/off-baseline.test.ts` and `src/entity-notes/prisma/off-baseline.test.ts`, which were recorded on 1.5.0 before any change). Every column name is checked like every other name that reaches SQL.
209
+
210
+ 1. **Companies** (`createPrismaCompanyStore`): `softDelete: { column, byColumn, updatedAtColumn? }` on the company table, and `personSoftDeleteColumn` on the person table. With `softDelete` set the store is a `TrashableCompanyStore` (the overloads type it so: pass the config as an inline object literal, or cast the result; a config held in a variable typed `PrismaCompanyStoreConfig` has `softDelete` optional, so TypeScript picks the plain `CompanyStore` overload even though the trash methods exist at run time) with `trash(id, actorId)`, `restore(id)`, `listTrashed()` and `getAny(id)`. All plain reads and writes (`list`, `get`, `getMany`, `findByKey`, `findByDomain`, `update`, the member methods, `memberCounts`) see LIVE companies only; the create-time limit counts trashed companies too. `trash` and `restore` run in one transaction with a bounded lock wait, take the company row `FOR UPDATE` (so they also wait for and block `setRole` and `removeMember`), then compare-and-set on the column: `trashed` / `restored` with `before` and `after`, or `notFound`, `alreadyTrashed`, `notTrashed`. `updatedAtColumn`, when set, is written back to its existing value so an `@updatedAt` cannot move it. `personSoftDeleteColumn` makes `personExists`, the `addMember` person check and its `FOR KEY SHARE` SQL, `members()` and `memberCounts` ignore trashed people.
211
+ 2. **Tags** (`PrismaTagTarget`): `softDeleteColumn` per target kind. A trashed item counts as gone (`targetGone`) for tagging and untagging; counts and tag lists are not filtered.
212
+ 3. **Notes** (`createPrismaNoteStore` parents): `softDeleteColumn` per parent kind. A trashed parent is `parentGone` for a new note.
213
+
214
+ **Results and failures.** `CompanyCreateResult` and `CompanyUpdateResult` gain `{ kind: 'inTrash'; id }`: the unique index is NOT made partial, so a trashed company keeps its name key, and a create or rename onto it reports `inTrash` with that company's id (a live holder is still `duplicate`; the unique-violation race path re-reads the key with the live term off and reports the same). `findByKey` stays live-only, so `findOrCreate` falls through to `create` and returns `inTrash`, never the trashed row as found. The service maps it to `{ ok: false, reason: 'in-trash', id }` in `create`, `update` and `findOrCreate`; its `trash(id, actorId)`, `restore(id)`, `listTrashed()` and `getAny(id)` return `already-trashed`, `not-trashed` or `not-found` as needed, and `{ ok: false, reason: 'unsupported' }` WITHOUT touching the store when the store has no `trash` function (a plain 1.5.0 `CompanyStore` keeps working). A new result kind can break a consumer's exhaustive `switch`: re-run your type check when you upgrade.
215
+
216
+ **`remove` is still the hard delete**, of a live or a trashed company (the purge path); it takes no live term.
217
+
218
+ **Locks.** Company trash uses `FOR UPDATE`. For a person or a note parent this package only filters on the column: a plain `UPDATE ... SET deletedAt` takes `FOR NO KEY UPDATE`, which does not conflict with the `FOR KEY SHARE` that `addMember` and note creation take, so a race can leave a membership or note on a freshly trashed row (benign: it shows after Restore). Callers that trash a person or a note parent should take `SELECT ... FOR UPDATE` on the row first.
219
+
220
+ **Contract suite and in-memory store.** `createMemoryCompanyHarness({ softDelete: true })` gives a Trash-capable reference store and sets the harness flag `supportsTrash`; `defineCompanyStoreContract` runs its Trash rules (hiding, `alreadyTrashed` / `notTrashed`, `inTrash` versus `duplicate`, `remove` as hard delete, tenancy, ten simultaneous trashes give one `trashed`, ten restores one `restored`) only for a harness that sets `supportsTrash: true`; existing harnesses are unchanged.
221
+
206
222
  ### Contacts Module
207
223
 
208
224
  | Function | Type | Description |
@@ -1,4 +1,4 @@
1
- import { C as CompanyRecord, a as CompanyStore } from '../../types-CbfseUAS.mjs';
1
+ import { C as CompanyRecord, T as TrashableCompanyStore, a as CompanyStore } from '../../types-BJl_PZDf.mjs';
2
2
 
3
3
  interface PrismaCompanyStoreConfig {
4
4
  /** Called each time the store needs the client (never at import), so a test can swap in a client with a bigger pool. */
@@ -38,6 +38,20 @@ interface PrismaCompanyStoreConfig {
38
38
  maxWait?: number;
39
39
  timeout?: number;
40
40
  };
41
+ /**
42
+ * OPTIONAL soft delete (the Trash) of companies. Names columns of the COMPANY table (plain identifiers, same name as the Prisma field): `column` is a nullable
43
+ * timestamp (NULL = live), `byColumn` a nullable text column for who trashed it, `updatedAtColumn` (optional) the model's `@updatedAt` column, which `trash` and
44
+ * `restore` write back to its existing value so the trash itself does not move it (when omitted the key is not written: a model with `@updatedAt` may bump it).
45
+ * When set: reads, `update` and the membership methods see LIVE companies only, name collisions with a trashed company are reported as `inTrash`, the store gains
46
+ * `trash`/`restore`/`listTrashed`/`getAny`, and `remove` stays a hard delete of a company in ANY state. When unset the store is exactly the 1.5.0 store.
47
+ */
48
+ softDelete?: {
49
+ column: string;
50
+ byColumn: string;
51
+ updatedAtColumn?: string;
52
+ };
53
+ /** OPTIONAL: the nullable timestamp column of the PERSON table that marks a trashed person. When set, `personExists`, `addMember`, `members` and `memberCounts` treat a trashed person as absent. */
54
+ personSoftDeleteColumn?: string;
41
55
  /** TEST ONLY: runs inside `addMember` after the existence checks and before the write, holding NO lock and no open transaction, so a test can delete a company or person there. */
42
56
  onBeforeMemberWrite?: () => Promise<void>;
43
57
  }
@@ -53,6 +67,10 @@ interface PrismaLikeClient extends PrismaLikeTx {
53
67
  }): Promise<R>;
54
68
  }
55
69
 
70
+ /** With `softDelete` configured the store also has `trash`, `restore`, `listTrashed` and `getAny`; without it the store is exactly the 1.5.0 `CompanyStore`. */
71
+ declare function createPrismaCompanyStore<T extends CompanyRecord = CompanyRecord>(config: PrismaCompanyStoreConfig & {
72
+ softDelete: NonNullable<PrismaCompanyStoreConfig['softDelete']>;
73
+ }): TrashableCompanyStore<T>;
56
74
  declare function createPrismaCompanyStore<T extends CompanyRecord = CompanyRecord>(config: PrismaCompanyStoreConfig): CompanyStore<T>;
57
75
 
58
76
  export { type PrismaCompanyStoreConfig, type PrismaLikeClient, type PrismaLikeTx, createPrismaCompanyStore };
@@ -27,6 +27,12 @@ function createContext(config) {
27
27
  const personIdColumn = assertIdentifier(config.personIdColumn ?? "personId", "personIdColumn");
28
28
  const roleColumn = assertIdentifier(config.roleColumn ?? "role", "roleColumn");
29
29
  const addedByColumn = assertIdentifier(config.addedByColumn ?? "addedBy", "addedByColumn");
30
+ const softDelete = config.softDelete ? {
31
+ column: assertIdentifier(config.softDelete.column, "softDelete.column"),
32
+ byColumn: assertIdentifier(config.softDelete.byColumn, "softDelete.byColumn"),
33
+ updatedAtColumn: config.softDelete.updatedAtColumn === void 0 ? void 0 : assertIdentifier(config.softDelete.updatedAtColumn, "softDelete.updatedAtColumn")
34
+ } : void 0;
35
+ const personSoftDeleteColumn = config.personSoftDeleteColumn === void 0 ? void 0 : assertIdentifier(config.personSoftDeleteColumn, "personSoftDeleteColumn");
30
36
  const lockKeyPrefix = config.lockKeyPrefix ?? "companies:";
31
37
  const lockWaitMs = config.lockWaitMs ?? 5e3;
32
38
  if (!Number.isInteger(lockWaitMs) || lockWaitMs <= 0) throw new Error("createPrismaCompanyStore: lockWaitMs must be a positive integer");
@@ -46,6 +52,9 @@ function createContext(config) {
46
52
  addedByColumn,
47
53
  personWorkspaceColumn,
48
54
  sql: { companyTable: quote(companyTable), workspaceColumn: quote(workspaceColumn), memberTable: quote(memberTable), personTable: quote(personTable), personWorkspaceColumn: quote(personWorkspaceColumn) },
55
+ softDelete,
56
+ personSoftDeleteColumn,
57
+ liveSql: { company: softDelete ? ` AND ${quote(softDelete.column)} IS NULL` : "", person: personSoftDeleteColumn ? ` AND ${quote(personSoftDeleteColumn)} IS NULL` : "" },
49
58
  txOptions,
50
59
  beforeMemberWrite: config.onBeforeMemberWrite,
51
60
  client: config.client,
@@ -54,6 +63,8 @@ function createContext(config) {
54
63
  members: (client) => model(client, memberModel),
55
64
  people: (client) => model(client, personModel),
56
65
  companyWhere: (extra = {}) => ({ ...extra, [workspaceColumn]: config.workspaceId }),
66
+ companyWhereLive: (extra = {}) => ({ ...extra, [workspaceColumn]: config.workspaceId, ...softDelete ? { [softDelete.column]: null } : {} }),
67
+ companyWhereAny: (extra = {}) => ({ ...extra, [workspaceColumn]: config.workspaceId }),
57
68
  async limitLockWait(tx) {
58
69
  await tx.$executeRawUnsafe(`SELECT set_config('lock_timeout', $1, true)`, `${lockWaitMs}ms`);
59
70
  },
@@ -81,26 +92,26 @@ function chunksOf(items) {
81
92
  return pieces;
82
93
  }
83
94
  function createCompanyReads(context) {
84
- const { companyWhere } = context;
95
+ const { companyWhereLive } = context;
85
96
  const db = () => context.client();
86
97
  return {
87
98
  async list() {
88
- return await context.companies(db()).findMany({ where: companyWhere() });
99
+ return await context.companies(db()).findMany({ where: companyWhereLive() });
89
100
  },
90
101
  async getMany(ids) {
91
102
  const found = [];
92
- for (const piece of chunksOf([...new Set(ids)])) found.push(...await context.companies(db()).findMany({ where: companyWhere({ id: { in: piece } }) }));
103
+ for (const piece of chunksOf([...new Set(ids)])) found.push(...await context.companies(db()).findMany({ where: companyWhereLive({ id: { in: piece } }) }));
93
104
  return found;
94
105
  },
95
106
  async findByKey(nameKey) {
96
- return await context.companies(db()).findFirst({ where: companyWhere({ nameKey }) });
107
+ return await context.companies(db()).findFirst({ where: companyWhereLive({ nameKey }) });
97
108
  },
98
109
  async get(id) {
99
- return await context.companies(db()).findFirst({ where: companyWhere({ id }) });
110
+ return await context.companies(db()).findFirst({ where: companyWhereLive({ id }) });
100
111
  },
101
112
  async findByDomain(domain) {
102
113
  if (domain === "") return [];
103
- return await context.companies(db()).findMany({ where: companyWhere({ domain }) });
114
+ return await context.companies(db()).findMany({ where: companyWhereLive({ domain }) });
104
115
  }
105
116
  };
106
117
  }
@@ -114,9 +125,9 @@ function createCompanyMembers(context, getMany) {
114
125
  return { companyId: fields[context.companyIdColumn], personId: fields[context.personIdColumn], role: fields[context.roleColumn] ?? null };
115
126
  };
116
127
  const memberWhere = (companyId, personId) => ({ [context.companyIdColumn]: companyId, [context.personIdColumn]: personId });
117
- const companyExists = async (client, companyId) => await context.companies(client).findFirst({ where: context.companyWhere({ id: companyId }), select: { id: true } }) != null;
118
- const personExists = async (client, personId) => await context.people(client).findFirst({ where: { id: personId, [context.personWorkspaceColumn]: context.workspaceId }, select: { id: true } }) != null;
119
- const lockCompany = async (tx, companyId, mode) => (await tx.$queryRawUnsafe(`SELECT "id" FROM ${sql.companyTable} WHERE "id" = $1 AND ${sql.workspaceColumn} = $2 ${mode}`, companyId, context.workspaceId)).length > 0;
128
+ const companyExists = async (client, companyId) => await context.companies(client).findFirst({ where: context.companyWhereLive({ id: companyId }), select: { id: true } }) != null;
129
+ const personExists = async (client, personId) => await context.people(client).findFirst({ where: { id: personId, [context.personWorkspaceColumn]: context.workspaceId, ...context.personSoftDeleteColumn ? { [context.personSoftDeleteColumn]: null } : {} }, select: { id: true } }) != null;
130
+ const lockCompany = async (tx, companyId, mode) => (await tx.$queryRawUnsafe(`SELECT "id" FROM ${sql.companyTable} WHERE "id" = $1 AND ${sql.workspaceColumn} = $2${context.liveSql.company} ${mode}`, companyId, context.workspaceId)).length > 0;
120
131
  const lockMembership = async (tx, companyId, personId) => (await tx.$queryRawUnsafe(`SELECT 1 FROM ${sql.memberTable} WHERE ${quote(context.companyIdColumn)} = $1 AND ${quote(context.personIdColumn)} = $2 FOR UPDATE`, companyId, personId)).length > 0;
121
132
  return {
122
133
  personExists: (personId) => personExists(db(), personId),
@@ -128,7 +139,7 @@ function createCompanyMembers(context, getMany) {
128
139
  return await db().$transaction(async (tx) => {
129
140
  await context.limitLockWait(tx);
130
141
  if (!await lockCompany(tx, companyId, "FOR NO KEY UPDATE")) return { kind: "companyGone" };
131
- const person = await tx.$queryRawUnsafe(`SELECT "id" FROM ${sql.personTable} WHERE "id" = $1 AND ${sql.personWorkspaceColumn} = $2 FOR KEY SHARE`, personId, context.workspaceId);
142
+ const person = await tx.$queryRawUnsafe(`SELECT "id" FROM ${sql.personTable} WHERE "id" = $1 AND ${sql.personWorkspaceColumn} = $2${context.liveSql.person} FOR KEY SHARE`, personId, context.workspaceId);
132
143
  if (person.length === 0) return { kind: "personGone" };
133
144
  const members = context.members(tx);
134
145
  const existing = await members.findFirst({ where: memberWhere(companyId, personId) });
@@ -173,6 +184,15 @@ function createCompanyMembers(context, getMany) {
173
184
  },
174
185
  async members(companyId) {
175
186
  if (!await companyExists(db(), companyId)) return [];
187
+ if (context.personSoftDeleteColumn) {
188
+ const memberTable = sql.memberTable;
189
+ const rows = await db().$queryRawUnsafe(
190
+ `SELECT m.* FROM ${memberTable} m JOIN ${sql.personTable} p ON p."id" = m.${quote(context.personIdColumn)} AND p.${sql.personWorkspaceColumn} = $2 AND p.${quote(context.personSoftDeleteColumn)} IS NULL WHERE m.${quote(context.companyIdColumn)} = $1`,
191
+ companyId,
192
+ context.workspaceId
193
+ );
194
+ return rows.map(toMember);
195
+ }
176
196
  return (await context.members(db()).findMany({ where: { [context.companyIdColumn]: companyId } })).map(toMember);
177
197
  },
178
198
  async companiesForPeople(personIds) {
@@ -193,11 +213,20 @@ function createCompanyMembers(context, getMany) {
193
213
  },
194
214
  async memberCounts(ids) {
195
215
  const companyIds = [];
196
- const read = async (extra) => (await context.companies(db()).findMany({ where: context.companyWhere(extra), select: { id: true } })).map((row) => row.id);
216
+ const read = async (extra) => (await context.companies(db()).findMany({ where: context.companyWhereLive(extra), select: { id: true } })).map((row) => row.id);
197
217
  if (ids === void 0) companyIds.push(...await read({}));
198
218
  else for (const piece of chunksOf([...new Set(ids)])) companyIds.push(...await read({ id: { in: piece } }));
199
219
  const counts = new Map(companyIds.map((id) => [id, 0]));
200
220
  for (const piece of chunksOf(companyIds)) {
221
+ if (context.personSoftDeleteColumn) {
222
+ const rows = await db().$queryRawUnsafe(
223
+ `SELECT c."id" AS "companyId", COUNT(p."id")::int AS "n" FROM ${sql.companyTable} c LEFT JOIN ${sql.memberTable} m ON m.${quote(context.companyIdColumn)} = c."id" LEFT JOIN ${sql.personTable} p ON p."id" = m.${quote(context.personIdColumn)} AND p.${sql.personWorkspaceColumn} = $2 AND p.${quote(context.personSoftDeleteColumn)} IS NULL WHERE c."id" = ANY($1::text[]) AND c.${sql.workspaceColumn} = $2${context.softDelete ? ` AND c.${quote(context.softDelete.column)} IS NULL` : ""} GROUP BY c."id"`,
224
+ piece,
225
+ context.workspaceId
226
+ );
227
+ for (const row of rows) counts.set(row.companyId, Number(row.n));
228
+ continue;
229
+ }
201
230
  const grouped = await context.members(db()).groupBy({ by: [context.companyIdColumn], where: { [context.companyIdColumn]: { in: piece } }, _count: { _all: true } });
202
231
  for (const row of grouped) counts.set(row[context.companyIdColumn], row._count._all);
203
232
  }
@@ -206,9 +235,73 @@ function createCompanyMembers(context, getMany) {
206
235
  };
207
236
  }
208
237
 
238
+ // src/companies/prisma/trash.ts
239
+ function createCompanyTrash(context) {
240
+ const soft = context.softDelete;
241
+ if (!soft) throw new Error("createCompanyTrash: softDelete is not configured");
242
+ const { companyWhereAny } = context;
243
+ const db = () => context.client();
244
+ const lock = async (tx, id) => (await tx.$queryRawUnsafe(`SELECT "id" FROM ${context.sql.companyTable} WHERE "id" = $1 AND ${context.sql.workspaceColumn} = $2 FOR UPDATE`, id, context.workspaceId)).length > 0;
245
+ const read = async (tx, id) => await context.companies(tx).findFirst({ where: companyWhereAny({ id }) });
246
+ const isTrashed = (row) => row[soft.column] != null;
247
+ const keepUpdatedAt = (before) => soft.updatedAtColumn ? { [soft.updatedAtColumn]: before[soft.updatedAtColumn] } : {};
248
+ return {
249
+ async trash(id, actorId) {
250
+ return db().$transaction(async (tx) => {
251
+ await context.limitLockWait(tx);
252
+ if (!await lock(tx, id)) return { kind: "notFound" };
253
+ const before = await read(tx, id);
254
+ if (!before) return { kind: "notFound" };
255
+ if (isTrashed(before)) return { kind: "alreadyTrashed" };
256
+ const { count } = await context.companies(tx).updateMany({
257
+ where: companyWhereAny({ id, [soft.column]: null }),
258
+ data: { [soft.column]: /* @__PURE__ */ new Date(), [soft.byColumn]: actorId, ...keepUpdatedAt(before) }
259
+ });
260
+ const after = await read(tx, id);
261
+ if (count === 0 || !after) return after ? { kind: "alreadyTrashed" } : { kind: "notFound" };
262
+ return { kind: "trashed", before, after };
263
+ }, context.txOptions);
264
+ },
265
+ async restore(id) {
266
+ return db().$transaction(async (tx) => {
267
+ await context.limitLockWait(tx);
268
+ if (!await lock(tx, id)) return { kind: "notFound" };
269
+ const before = await read(tx, id);
270
+ if (!before) return { kind: "notFound" };
271
+ if (!isTrashed(before)) return { kind: "notTrashed" };
272
+ const { count } = await context.companies(tx).updateMany({
273
+ where: { ...companyWhereAny({ id }), NOT: { [soft.column]: null } },
274
+ data: { [soft.column]: null, [soft.byColumn]: null, ...keepUpdatedAt(before) }
275
+ });
276
+ const after = await read(tx, id);
277
+ if (count === 0 || !after) return after ? { kind: "notTrashed" } : { kind: "notFound" };
278
+ return { kind: "restored", before, after };
279
+ }, context.txOptions);
280
+ },
281
+ async listTrashed() {
282
+ return await context.companies(db()).findMany({ where: companyWhereAny({ [soft.column]: { not: null } }), orderBy: { [soft.column]: "desc" } });
283
+ },
284
+ async getAny(id) {
285
+ return await context.companies(db()).findFirst({ where: companyWhereAny({ id }) });
286
+ }
287
+ };
288
+ }
289
+
209
290
  // src/companies/prisma/writes.ts
210
291
  function createCompanyWrites(context) {
211
- const { companyWhere } = context;
292
+ const { companyWhereLive, companyWhereAny } = context;
293
+ const soft = context.softDelete;
294
+ const keySelect = soft ? { id: true, [soft.column]: true } : { id: true };
295
+ const collision = (owner) => {
296
+ if (!owner) return null;
297
+ const fields = owner;
298
+ return soft && fields[soft.column] != null ? { kind: "inTrash", id: fields.id } : { kind: "duplicate" };
299
+ };
300
+ const afterViolation = async (nameKey, exceptId) => {
301
+ if (!soft || nameKey === void 0) return { kind: "duplicate" };
302
+ const owner = await context.companies(db()).findFirst({ where: companyWhereAny(exceptId === void 0 ? { nameKey } : { nameKey, NOT: { id: exceptId } }), select: keySelect });
303
+ return collision(owner) ?? { kind: "duplicate" };
304
+ };
212
305
  const db = () => context.client();
213
306
  return {
214
307
  async create(input, limits) {
@@ -217,13 +310,14 @@ function createCompanyWrites(context) {
217
310
  await context.limitLockWait(tx);
218
311
  await context.lockWorkspace(tx);
219
312
  const companies = context.companies(tx);
220
- if (await companies.count({ where: companyWhere() }) >= limits.maxCompanies) return { kind: "limit" };
221
- if (await companies.findFirst({ where: companyWhere({ nameKey: input.nameKey }), select: { id: true } })) return { kind: "duplicate" };
222
- const company = await companies.create({ data: { ...companyWhere(), name: input.name, nameKey: input.nameKey, website: input.website, domain: input.domain } });
313
+ if (await companies.count({ where: companyWhereAny() }) >= limits.maxCompanies) return { kind: "limit" };
314
+ const taken = collision(await companies.findFirst({ where: companyWhereAny({ nameKey: input.nameKey }), select: keySelect }));
315
+ if (taken) return taken;
316
+ const company = await companies.create({ data: { ...companyWhereAny(), name: input.name, nameKey: input.nameKey, website: input.website, domain: input.domain } });
223
317
  return { kind: "created", company };
224
318
  }, context.txOptions);
225
319
  } catch (error) {
226
- if (isUniqueViolation(error)) return { kind: "duplicate" };
320
+ if (isUniqueViolation(error)) return afterViolation(input.nameKey);
227
321
  throw error;
228
322
  }
229
323
  },
@@ -231,21 +325,24 @@ function createCompanyWrites(context) {
231
325
  try {
232
326
  return await db().$transaction(async (tx) => {
233
327
  await context.limitLockWait(tx);
234
- const locked = await tx.$queryRawUnsafe(`SELECT "id" FROM ${context.sql.companyTable} WHERE "id" = $1 AND ${context.sql.workspaceColumn} = $2 FOR NO KEY UPDATE`, id, context.workspaceId);
328
+ const locked = await tx.$queryRawUnsafe(`SELECT "id" FROM ${context.sql.companyTable} WHERE "id" = $1 AND ${context.sql.workspaceColumn} = $2${context.liveSql.company} FOR NO KEY UPDATE`, id, context.workspaceId);
235
329
  const companies = context.companies(tx);
236
- const before = locked.length === 0 ? null : await companies.findFirst({ where: companyWhere({ id }) });
330
+ const before = locked.length === 0 ? null : await companies.findFirst({ where: companyWhereLive({ id }) });
237
331
  if (!before) return { kind: "notFound" };
238
332
  if (patch.rename === void 0 && patch.website === void 0) return { kind: "updated", before, after: { ...before } };
239
- if (patch.rename && await companies.findFirst({ where: companyWhere({ nameKey: patch.rename.nameKey, NOT: { id } }), select: { id: true } })) return { kind: "duplicate" };
333
+ if (patch.rename) {
334
+ const taken = collision(await companies.findFirst({ where: companyWhereAny({ nameKey: patch.rename.nameKey, NOT: { id } }), select: keySelect }));
335
+ if (taken) return taken;
336
+ }
240
337
  const data = {};
241
338
  if (patch.rename) Object.assign(data, { name: patch.rename.name, nameKey: patch.rename.nameKey });
242
339
  if (patch.website) Object.assign(data, { website: patch.website.website, domain: patch.website.domain });
243
- await companies.updateMany({ where: companyWhere({ id }), data });
244
- const after = await companies.findFirst({ where: companyWhere({ id }) });
340
+ await companies.updateMany({ where: companyWhereLive({ id }), data });
341
+ const after = await companies.findFirst({ where: companyWhereLive({ id }) });
245
342
  return { kind: "updated", before, after };
246
343
  }, context.txOptions);
247
344
  } catch (error) {
248
- if (isUniqueViolation(error)) return { kind: "duplicate" };
345
+ if (isUniqueViolation(error)) return afterViolation(patch.rename?.nameKey, id);
249
346
  throw error;
250
347
  }
251
348
  },
@@ -255,10 +352,10 @@ function createCompanyWrites(context) {
255
352
  const locked = await tx.$queryRawUnsafe(`SELECT "id" FROM ${context.sql.companyTable} WHERE "id" = $1 AND ${context.sql.workspaceColumn} = $2 FOR UPDATE`, id, context.workspaceId);
256
353
  if (locked.length === 0) return { kind: "notFound" };
257
354
  const companies = context.companies(tx);
258
- const company = await companies.findFirst({ where: companyWhere({ id }) });
355
+ const company = await companies.findFirst({ where: companyWhereAny({ id }) });
259
356
  if (!company) return { kind: "notFound" };
260
357
  const memberCount = await context.members(tx).count({ where: { [context.companyIdColumn]: id } });
261
- const { count } = await companies.deleteMany({ where: companyWhere({ id }) });
358
+ const { count } = await companies.deleteMany({ where: companyWhereAny({ id }) });
262
359
  return count === 0 ? { kind: "notFound" } : { kind: "removed", company, memberCount };
263
360
  }, context.txOptions);
264
361
  }
@@ -269,7 +366,8 @@ function createCompanyWrites(context) {
269
366
  function createPrismaCompanyStore(config) {
270
367
  const context = createContext(config);
271
368
  const reads = createCompanyReads(context);
272
- return { ...reads, ...createCompanyWrites(context), ...createCompanyMembers(context, reads.getMany) };
369
+ const store = { ...reads, ...createCompanyWrites(context), ...createCompanyMembers(context, reads.getMany) };
370
+ return context.softDelete ? { ...store, ...createCompanyTrash(context) } : store;
273
371
  }
274
372
  export {
275
373
  createPrismaCompanyStore
@@ -1,5 +1,5 @@
1
- import { C as CompanyRecord, b as CompanyMemberRecord, P as PersonCompany, a as CompanyStore } from '../../types-CbfseUAS.mjs';
2
- export { c as CompanyAddMemberResult, d as CompanyCreateLimits, e as CompanyCreateResult, f as CompanyMemberLimits, g as CompanyRemoveMemberResult, h as CompanyRemoveResult, i as CompanySetRoleResult, j as CompanyUpdatePatch, k as CompanyUpdateResult, l as CompanyWebsite } from '../../types-CbfseUAS.mjs';
1
+ import { C as CompanyRecord, b as CompanyMemberRecord, P as PersonCompany, a as CompanyStore } from '../../types-BJl_PZDf.mjs';
2
+ export { c as CompanyAddMemberResult, d as CompanyCreateLimits, e as CompanyCreateResult, f as CompanyMemberLimits, g as CompanyRemoveMemberResult, h as CompanyRemoveResult, i as CompanyRestoreResult, j as CompanySetRoleResult, k as CompanyTrashResult, l as CompanyUpdatePatch, m as CompanyUpdateResult, n as CompanyWebsite, T as TrashableCompanyStore } from '../../types-BJl_PZDf.mjs';
3
3
  import { C as CompanyLimits } from '../../constants-DV-gn6u8.mjs';
4
4
 
5
5
  /** Why a call did not do what was asked, with the context an app needs for its message. */
@@ -22,10 +22,27 @@ type CompanyFailure = {
22
22
  reason: 'member-limit';
23
23
  } | {
24
24
  reason: 'duplicate';
25
+ }
26
+ /** The name belongs to a company in the Trash (`id`); only with a soft-delete store. */
27
+ | {
28
+ reason: 'in-trash';
29
+ id: string;
25
30
  } | {
26
31
  reason: 'limit';
27
32
  } | {
28
33
  reason: 'not-found';
34
+ }
35
+ /** Trash only: the company is already in the Trash. */
36
+ | {
37
+ reason: 'already-trashed';
38
+ }
39
+ /** Restore only: the company is not in the Trash. */
40
+ | {
41
+ reason: 'not-trashed';
42
+ }
43
+ /** The store has no Trash (it is not a `TrashableCompanyStore`); nothing was asked of it. */
44
+ | {
45
+ reason: 'unsupported';
29
46
  };
30
47
  type CompanyResult<V> = ({
31
48
  ok: true;
@@ -69,6 +86,24 @@ interface CompanyService<T extends CompanyRecord> {
69
86
  company: T;
70
87
  memberCount: number;
71
88
  }>>;
89
+ /** Moves a company to the Trash. `unsupported` (and no store call) when the store has no Trash. `actorId` is stored with the trash. */
90
+ trash(id: string, actorId: string): Promise<CompanyResult<{
91
+ before: T;
92
+ after: T;
93
+ }>>;
94
+ /** Takes a company out of the Trash. `unsupported` when the store has no Trash. */
95
+ restore(id: string): Promise<CompanyResult<{
96
+ before: T;
97
+ after: T;
98
+ }>>;
99
+ /** The companies in the Trash, most recently trashed first. `unsupported` when the store has no Trash. */
100
+ listTrashed(): Promise<CompanyResult<{
101
+ companies: T[];
102
+ }>>;
103
+ /** A company in ANY state (live or trashed). `unsupported` when the store has no Trash. */
104
+ getAny(id: string): Promise<CompanyResult<{
105
+ company: T;
106
+ }>>;
72
107
  /**
73
108
  * Adds a person to a company. A person who is already a member is NOT an error: the result is `added: false` with the membership as it is
74
109
  * (its role is untouched: changing a role is `setRole`). An empty role means none.
@@ -136,6 +171,11 @@ interface CompanyStoreHarness {
136
171
  * not, they will run and fail, so supply the hook.
137
172
  */
138
173
  armBeforeMemberWrite?(hook: () => Promise<void>): void;
174
+ /**
175
+ * OPTIONAL. True when `storeFor` returns a `TrashableCompanyStore` (trash, restore, listTrashed, getAny; trashed companies hidden from reads, `inTrash` on name collisions,
176
+ * `remove` a hard delete in any state). Only then does the suite run its Trash rules; every existing harness leaves it out and sees no change.
177
+ */
178
+ supportsTrash?: boolean;
139
179
  /** Removes everything the tests created. */
140
180
  cleanup(): Promise<void>;
141
181
  }
@@ -143,6 +183,12 @@ interface CompanyStoreHarness {
143
183
  interface MemoryCompanyWorldOptions {
144
184
  /** Default true. False removes the one-at-a-time chain so races become visible (for proving that concurrency tests can fail). */
145
185
  serialise?: boolean;
186
+ /**
187
+ * Default false (the store is exactly the 1.5.0 one). True gives the stores of this world a Trash (they are `TrashableCompanyStore`s): trashed companies are hidden from
188
+ * every read and write except `getAny`, `listTrashed`, `trash`, `restore` and `remove`; a name taken by a trashed company is `inTrash` (create, update), by a live one `duplicate`;
189
+ * the limit on creates counts trashed companies too; `remove` stays a hard delete of a company in either state.
190
+ */
191
+ softDelete?: boolean;
146
192
  }
147
193
  interface MemoryCompanyWorld {
148
194
  store(workspace: string): CompanyStore<CompanyRecord>;
@@ -43,6 +43,7 @@ function createCompanyService(store, suppliedLimits = DEFAULT_COMPANY_LIMITS) {
43
43
  const result = await store.create({ name: name.name, nameKey: name.key, ...website.value }, { maxCompanies: limits.maxPerWorkspace });
44
44
  if (result.kind === "created") return { ok: true, company: result.company };
45
45
  if (result.kind === "duplicate") return fail({ reason: "duplicate" });
46
+ if (result.kind === "inTrash") return fail({ reason: "in-trash", id: result.id });
46
47
  if (result.kind === "limit") return fail({ reason: "limit" });
47
48
  return unknownKind("create", result);
48
49
  }
@@ -77,8 +78,10 @@ function createCompanyService(store, suppliedLimits = DEFAULT_COMPANY_LIMITS) {
77
78
  if (result.kind === "updated") return { ok: true, before: result.before, after: result.after };
78
79
  if (result.kind === "notFound") return fail({ reason: "not-found" });
79
80
  if (result.kind === "duplicate") return fail({ reason: "duplicate" });
81
+ if (result.kind === "inTrash") return fail({ reason: "in-trash", id: result.id });
80
82
  return unknownKind("update", result);
81
83
  }
84
+ const trashable = () => typeof store.trash === "function" ? store : null;
82
85
  return {
83
86
  async list() {
84
87
  return [...await store.list()].sort(byName);
@@ -99,6 +102,35 @@ function createCompanyService(store, suppliedLimits = DEFAULT_COMPANY_LIMITS) {
99
102
  if (result.kind === "notFound") return fail({ reason: "not-found" });
100
103
  return unknownKind("remove", result);
101
104
  },
105
+ async trash(id, actorId) {
106
+ const s = trashable();
107
+ if (!s) return fail({ reason: "unsupported" });
108
+ const result = await s.trash(id, actorId);
109
+ if (result.kind === "trashed") return { ok: true, before: result.before, after: result.after };
110
+ if (result.kind === "notFound") return fail({ reason: "not-found" });
111
+ if (result.kind === "alreadyTrashed") return fail({ reason: "already-trashed" });
112
+ return unknownKind("trash", result);
113
+ },
114
+ async restore(id) {
115
+ const s = trashable();
116
+ if (!s) return fail({ reason: "unsupported" });
117
+ const result = await s.restore(id);
118
+ if (result.kind === "restored") return { ok: true, before: result.before, after: result.after };
119
+ if (result.kind === "notFound") return fail({ reason: "not-found" });
120
+ if (result.kind === "notTrashed") return fail({ reason: "not-trashed" });
121
+ return unknownKind("restore", result);
122
+ },
123
+ async listTrashed() {
124
+ const s = trashable();
125
+ if (!s) return fail({ reason: "unsupported" });
126
+ return { ok: true, companies: [...await s.listTrashed()] };
127
+ },
128
+ async getAny(id) {
129
+ const s = trashable();
130
+ if (!s) return fail({ reason: "unsupported" });
131
+ const company = await s.getAny(id);
132
+ return company ? { ok: true, company } : fail({ reason: "not-found" });
133
+ },
102
134
  async addMember(companyId, personId, input, actorId) {
103
135
  if (!await store.get(companyId)) return fail({ reason: "not-found" });
104
136
  if (!await store.personExists(personId)) return fail({ reason: "person-gone" });
@@ -158,7 +190,9 @@ var memberKey = (companyId, personId) => `${companyId}\0${personId}`;
158
190
  var personKey = (workspace, id) => `${workspace}\0${id}`;
159
191
  function createMemoryCompanyWorld(options = {}) {
160
192
  const serialise = options.serialise ?? true;
193
+ const softDelete = options.softDelete === true;
161
194
  const companies = /* @__PURE__ */ new Map();
195
+ let trashSequence = 0;
162
196
  const people = /* @__PURE__ */ new Set();
163
197
  const memberships = /* @__PURE__ */ new Map();
164
198
  let sequence = 0;
@@ -174,10 +208,21 @@ function createMemoryCompanyWorld(options = {}) {
174
208
  const copy = (record) => ({ ...record });
175
209
  const copyMember = (record) => ({ ...record });
176
210
  function store(workspace) {
177
- const mine = () => [...companies.values()].filter((row) => row.workspace === workspace).map((row) => row.record);
178
- const own = (id) => {
211
+ const rowsAny = () => [...companies.values()].filter((row) => row.workspace === workspace);
212
+ const mine = () => rowsAny().filter((row) => !row.trashed).map((row) => row.record);
213
+ const ownRowAny = (id) => {
179
214
  const row = companies.get(id);
180
- return row && row.workspace === workspace ? row.record : void 0;
215
+ return row && row.workspace === workspace ? row : void 0;
216
+ };
217
+ const own = (id) => {
218
+ const row = ownRowAny(id);
219
+ return row && !row.trashed ? row.record : void 0;
220
+ };
221
+ const holderOf = (nameKey, exceptId) => rowsAny().find((row) => row.record.id !== exceptId && row.record.nameKey === nameKey);
222
+ const collision = (nameKey, exceptId) => {
223
+ const holder = holderOf(nameKey, exceptId);
224
+ if (!holder) return null;
225
+ return holder.trashed ? { kind: "inTrash", id: holder.record.id } : { kind: "duplicate" };
181
226
  };
182
227
  const personIsMine = (id) => people.has(personKey(workspace, id));
183
228
  const membersOfCompany = (companyId) => [...memberships.values()].filter((m) => m.workspace === workspace && m.record.companyId === companyId);
@@ -189,7 +234,7 @@ function createMemoryCompanyWorld(options = {}) {
189
234
  if (membersOfCompany(companyId).length >= limits.maxMembers) return { kind: "memberLimit" };
190
235
  return null;
191
236
  }
192
- return {
237
+ const base = {
193
238
  async list() {
194
239
  return mine().map(copy);
195
240
  },
@@ -207,8 +252,9 @@ function createMemoryCompanyWorld(options = {}) {
207
252
  },
208
253
  create(input, limits) {
209
254
  return exclusive(async () => {
210
- if (mine().length >= limits.maxCompanies) return { kind: "limit" };
211
- if (mine().some((company) => company.nameKey === input.nameKey)) return { kind: "duplicate" };
255
+ if (rowsAny().length >= limits.maxCompanies) return { kind: "limit" };
256
+ const taken = collision(input.nameKey);
257
+ if (taken) return taken;
212
258
  await tick();
213
259
  const record = { id: `company_${++sequence}`, name: input.name, nameKey: input.nameKey, website: input.website, domain: input.domain };
214
260
  companies.set(record.id, { workspace, record });
@@ -220,7 +266,8 @@ function createMemoryCompanyWorld(options = {}) {
220
266
  const current = own(id);
221
267
  if (!current) return { kind: "notFound" };
222
268
  const before = copy(current);
223
- if (patch.rename && mine().some((company) => company.id !== id && company.nameKey === patch.rename?.nameKey)) return { kind: "duplicate" };
269
+ const taken = patch.rename ? collision(patch.rename.nameKey, id) : null;
270
+ if (taken) return taken;
224
271
  await tick();
225
272
  if (patch.rename) {
226
273
  current.name = patch.rename.name;
@@ -235,7 +282,7 @@ function createMemoryCompanyWorld(options = {}) {
235
282
  },
236
283
  remove(id) {
237
284
  return exclusive(async () => {
238
- const current = own(id);
285
+ const current = ownRowAny(id)?.record;
239
286
  if (!current) return { kind: "notFound" };
240
287
  const memberCount = membersOfCompany(id).length;
241
288
  await tick();
@@ -311,6 +358,40 @@ function createMemoryCompanyWorld(options = {}) {
311
358
  return found;
312
359
  }
313
360
  };
361
+ if (!softDelete) return base;
362
+ const trashable = {
363
+ ...base,
364
+ trash(id, actorId) {
365
+ return exclusive(async () => {
366
+ const row = ownRowAny(id);
367
+ if (!row) return { kind: "notFound" };
368
+ if (row.trashed) return { kind: "alreadyTrashed" };
369
+ const before = copy(row.record);
370
+ await tick();
371
+ row.trashed = { at: ++trashSequence, by: actorId };
372
+ return { kind: "trashed", before, after: copy(row.record) };
373
+ });
374
+ },
375
+ restore(id) {
376
+ return exclusive(async () => {
377
+ const row = ownRowAny(id);
378
+ if (!row) return { kind: "notFound" };
379
+ if (!row.trashed) return { kind: "notTrashed" };
380
+ const before = copy(row.record);
381
+ await tick();
382
+ delete row.trashed;
383
+ return { kind: "restored", before, after: copy(row.record) };
384
+ });
385
+ },
386
+ async listTrashed() {
387
+ return rowsAny().filter((row) => row.trashed).sort((a, b) => b.trashed.at - a.trashed.at).map((row) => copy(row.record));
388
+ },
389
+ async getAny(id) {
390
+ const row = ownRowAny(id);
391
+ return row ? copy(row.record) : null;
392
+ }
393
+ };
394
+ return trashable;
314
395
  }
315
396
  return {
316
397
  store,
@@ -341,6 +422,7 @@ function createMemoryCompanyHarness(options = {}) {
341
422
  async newWorkspace() {
342
423
  return `workspace_${++workspaces}`;
343
424
  },
425
+ ...options.softDelete === true ? { supportsTrash: true } : {},
344
426
  storeFor: (workspace) => world.store(workspace),
345
427
  async addPerson(workspace) {
346
428
  return world.addPerson(workspace);
@@ -407,23 +489,23 @@ function defineCompanyStoreCompaniesContract(kit) {
407
489
  expect(ids(await store.getMany([taft.id, taft.id]))).toEqual([taft.id]);
408
490
  expect(ids(await store.getMany([unasked.id]))).toEqual([unasked.id]);
409
491
  expect(new Set(ids(await store.list())).size).toBe(3);
410
- const many3 = [taft, other, unasked];
492
+ const many4 = [taft, other, unasked];
411
493
  const bigLimits = { maxCompanies: 1e3 };
412
494
  for (let i = 0; i < 117; i++) {
413
495
  const result = await store.create({ name: `Company ${i}`, nameKey: `company ${i}`, ...site("shared.com") }, bigLimits);
414
496
  if (result.kind !== "created") throw new Error(`setup: could not create Company ${i}: ${result.kind}`);
415
- many3.push(result.company);
497
+ many4.push(result.company);
416
498
  }
417
499
  expect((await store.list()).length).toBe(120);
418
- expect(ids(await store.list())).toEqual(ids(many3));
419
- expect(ids(await store.getMany(many3.map((company) => company.id)))).toEqual(ids(many3));
420
- expect(ids(await store.findByDomain("shared.com"))).toEqual(ids(many3.slice(3)));
500
+ expect(ids(await store.list())).toEqual(ids(many4));
501
+ expect(ids(await store.getMany(many4.map((company) => company.id)))).toEqual(ids(many4));
502
+ expect(ids(await store.findByDomain("shared.com"))).toEqual(ids(many4.slice(3)));
421
503
  const everyCount = await store.memberCounts();
422
- expect([...everyCount.keys()].sort()).toEqual(ids(many3));
423
- expect([...everyCount.values()].every((count3) => count3 === 0)).toBe(true);
424
- const askedCount = await store.memberCounts(many3.map((company) => company.id));
425
- expect([...askedCount.keys()].sort()).toEqual(ids(many3));
426
- const last = many3[119];
504
+ expect([...everyCount.keys()].sort()).toEqual(ids(many4));
505
+ expect([...everyCount.values()].every((count4) => count4 === 0)).toBe(true);
506
+ const askedCount = await store.memberCounts(many4.map((company) => company.id));
507
+ expect([...askedCount.keys()].sort()).toEqual(ids(many4));
508
+ const last = many4[119];
427
509
  expect(core(await store.get(last.id))).toEqual(core(last));
428
510
  expect((await store.findByKey(last.nameKey))?.id).toBe(last.id);
429
511
  expect(await store.create({ name: "Copy", nameKey: last.nameKey, ...NO_SITE }, bigLimits)).toEqual({ kind: "duplicate" });
@@ -433,7 +515,7 @@ function defineCompanyStoreCompaniesContract(kit) {
433
515
  expect(removedLast.kind === "removed" && removedLast.company.nameKey).toBe("last renamed");
434
516
  expect((await store.list()).length).toBe(119);
435
517
  const fresh = await store.create({ name: "Fresh", nameKey: "fresh", ...NO_SITE }, bigLimits);
436
- expect(fresh.kind === "created" && fresh.company.id !== last.id && !ids(many3).includes(fresh.company.id)).toBe(true);
518
+ expect(fresh.kind === "created" && fresh.company.id !== last.id && !ids(many4).includes(fresh.company.id)).toBe(true);
437
519
  expect(await store.get(last.id)).toBeNull();
438
520
  });
439
521
  it("text comes back exactly as stored (accents, quotes, backslashes, percent and underscore signs, emoji, a name of the maximum length; given to create and to update), and a domain search is an exact value, never a pattern", async () => {
@@ -1082,7 +1164,7 @@ function defineCompanyStoreReadsContract(kit) {
1082
1164
  await join(b.id, q);
1083
1165
  await join(b.id, r);
1084
1166
  expect(await counts()).toEqual([[a.id, 2], [b.id, 3]].sort());
1085
- for (const [, count3] of await counts()) expect(typeof count3).toBe("number");
1167
+ for (const [, count4] of await counts()) expect(typeof count4).toBe("number");
1086
1168
  await store.addMember(a.id, p, "Again", ACTOR, MEMBER_LIMITS);
1087
1169
  expect(await counts(a.id)).toEqual([[a.id, 2]]);
1088
1170
  expect(await counts(a.id, "missing", "")).toEqual([[a.id, 2]]);
@@ -1553,6 +1635,135 @@ function defineCompanyStoreHooksContract(kit) {
1553
1635
  });
1554
1636
  }
1555
1637
 
1638
+ // src/companies/server/contract-trash.ts
1639
+ var many3 = (n, make) => Promise.all(Array.from({ length: n }, (_, i) => make(i)));
1640
+ var count3 = (results, kind) => results.filter((result) => result.kind === kind).length;
1641
+ function defineCompanyStoreTrashContract(kit) {
1642
+ const { describe, it, expect } = kit.api;
1643
+ async function trashSetup() {
1644
+ const base = await kit.setup();
1645
+ return { ...base, store: base.store };
1646
+ }
1647
+ describe("CompanyStore contract: the Trash", () => {
1648
+ it("trash hides a company from list, get, getMany, findByKey, findByDomain, memberCounts and members, and shows it in listTrashed and getAny; the others stay visible", async () => {
1649
+ const { store, make, person, join } = await trashSetup();
1650
+ const gone = await make(store, "Gone", site("gone.com"));
1651
+ const kept = await make(store, "Kept", site("kept.com"));
1652
+ await join(gone.id, await person());
1653
+ const trashed = await store.trash(gone.id, ACTOR);
1654
+ expect(trashed.kind).toBe("trashed");
1655
+ if (trashed.kind !== "trashed") return;
1656
+ expect(trashed.before.id).toBe(gone.id);
1657
+ expect(trashed.after.id).toBe(gone.id);
1658
+ expect(ids(await store.list())).toEqual([kept.id]);
1659
+ expect(await store.get(gone.id)).toBeNull();
1660
+ expect(ids(await store.getMany([gone.id, kept.id]))).toEqual([kept.id]);
1661
+ expect(await store.findByKey("gone")).toBeNull();
1662
+ expect((await store.findByKey("kept"))?.id).toBe(kept.id);
1663
+ expect(ids(await store.findByDomain("gone.com"))).toEqual([]);
1664
+ expect(ids(await store.findByDomain("kept.com"))).toEqual([kept.id]);
1665
+ expect([...(await store.memberCounts()).keys()]).toEqual([kept.id]);
1666
+ expect(await store.members(gone.id)).toEqual([]);
1667
+ expect(cores(await store.listTrashed())).toEqual(cores([gone]));
1668
+ expect((await store.getAny(gone.id))?.id).toBe(gone.id);
1669
+ expect((await store.getAny(kept.id))?.id).toBe(kept.id);
1670
+ expect(await store.getAny("missing")).toBeNull();
1671
+ });
1672
+ it("trashing twice gives alreadyTrashed, trashing a missing company gives notFound, and neither changes anything", async () => {
1673
+ const { store, make } = await trashSetup();
1674
+ const a = await make(store, "A");
1675
+ expect((await store.trash(a.id, ACTOR)).kind).toBe("trashed");
1676
+ expect((await store.trash(a.id, ACTOR)).kind).toBe("alreadyTrashed");
1677
+ expect((await store.trash("missing", ACTOR)).kind).toBe("notFound");
1678
+ expect(ids(await store.listTrashed())).toEqual([a.id]);
1679
+ });
1680
+ it("restore brings the company back everywhere with its members; restoring a live company gives notTrashed and a missing one notFound", async () => {
1681
+ const { store, make, person, join } = await trashSetup();
1682
+ const a = await make(store, "A", site("a.com"));
1683
+ await join(a.id, await person());
1684
+ await store.trash(a.id, ACTOR);
1685
+ const restored = await store.restore(a.id);
1686
+ expect(restored.kind).toBe("restored");
1687
+ expect(ids(await store.list())).toEqual([a.id]);
1688
+ expect((await store.get(a.id))?.id).toBe(a.id);
1689
+ expect((await store.findByKey("a"))?.id).toBe(a.id);
1690
+ expect(ids(await store.findByDomain("a.com"))).toEqual([a.id]);
1691
+ expect((await store.memberCounts([a.id])).get(a.id)).toBe(1);
1692
+ expect(await store.listTrashed()).toEqual([]);
1693
+ expect((await store.restore(a.id)).kind).toBe("notTrashed");
1694
+ expect((await store.restore("missing")).kind).toBe("notFound");
1695
+ });
1696
+ it("a name held by a trashed company is inTrash (with its id) on create and on update, a name held by a live company is duplicate, and nothing is created or renamed", async () => {
1697
+ const { store, make } = await trashSetup();
1698
+ const trashedOne = await make(store, "Taken");
1699
+ const live = await make(store, "Live");
1700
+ const other = await make(store, "Other");
1701
+ await store.trash(trashedOne.id, ACTOR);
1702
+ expect(await store.create({ name: "TAKEN", nameKey: "taken", ...NO_SITE }, LIMITS)).toEqual({ kind: "inTrash", id: trashedOne.id });
1703
+ expect(await store.create({ name: "Live", nameKey: "live", ...NO_SITE }, LIMITS)).toEqual({ kind: "duplicate" });
1704
+ expect(await store.update(other.id, { rename: { name: "Taken", nameKey: "taken" } })).toEqual({ kind: "inTrash", id: trashedOne.id });
1705
+ expect(await store.update(other.id, { rename: { name: "Live", nameKey: "live" } })).toEqual({ kind: "duplicate" });
1706
+ expect((await store.get(other.id))?.nameKey).toBe("other");
1707
+ expect(ids(await store.list())).toEqual([live.id, other.id].sort());
1708
+ });
1709
+ it("a trashed company cannot be updated (notFound), and a restore frees nothing: its name is taken again as a plain duplicate", async () => {
1710
+ const { store, make } = await trashSetup();
1711
+ const a = await make(store, "A");
1712
+ await store.trash(a.id, ACTOR);
1713
+ expect((await store.update(a.id, { website: { website: "https://a.com", domain: "a.com" } })).kind).toBe("notFound");
1714
+ await store.restore(a.id);
1715
+ expect(await store.create({ name: "A", nameKey: "a", ...NO_SITE }, LIMITS)).toEqual({ kind: "duplicate" });
1716
+ });
1717
+ it("remove stays a hard delete: it removes a live company and a trashed one for good (no listTrashed, no getAny afterwards, and the name is free)", async () => {
1718
+ const { store, make } = await trashSetup();
1719
+ const a = await make(store, "A");
1720
+ const b = await make(store, "B");
1721
+ await store.trash(b.id, ACTOR);
1722
+ expect((await store.remove(a.id)).kind).toBe("removed");
1723
+ expect((await store.remove(b.id)).kind).toBe("removed");
1724
+ expect(await store.getAny(a.id)).toBeNull();
1725
+ expect(await store.getAny(b.id)).toBeNull();
1726
+ expect(await store.listTrashed()).toEqual([]);
1727
+ expect((await store.remove(b.id)).kind).toBe("notFound");
1728
+ expect((await store.create({ name: "B", nameKey: "b", ...NO_SITE }, LIMITS)).kind).toBe("created");
1729
+ });
1730
+ it("a trashed company still counts against the create limit (a workspace at its cap stays at its cap until the company is removed for good)", async () => {
1731
+ const { store, make } = await trashSetup();
1732
+ const a = await make(store, "A");
1733
+ await store.trash(a.id, ACTOR);
1734
+ expect(await store.create({ name: "B", nameKey: "b", ...NO_SITE }, { maxCompanies: 1 })).toEqual({ kind: "limit" });
1735
+ await store.remove(a.id);
1736
+ expect((await store.create({ name: "B", nameKey: "b", ...NO_SITE }, { maxCompanies: 1 })).kind).toBe("created");
1737
+ });
1738
+ it("a workspace never sees, trashes or restores another workspace's companies", async () => {
1739
+ const mine = await trashSetup();
1740
+ const theirs = kit.harness.storeFor(await kit.harness.newWorkspace());
1741
+ const a = await mine.make(mine.store, "A");
1742
+ expect((await theirs.trash(a.id, ACTOR)).kind).toBe("notFound");
1743
+ await mine.store.trash(a.id, ACTOR);
1744
+ expect(await theirs.listTrashed()).toEqual([]);
1745
+ expect(await theirs.getAny(a.id)).toBeNull();
1746
+ expect((await theirs.restore(a.id)).kind).toBe("notFound");
1747
+ expect(ids(await mine.store.listTrashed())).toEqual([a.id]);
1748
+ });
1749
+ it("ten simultaneous trashes of one company give exactly one trashed and nine alreadyTrashed", async () => {
1750
+ const { store, make } = await trashSetup();
1751
+ const a = await make(store, "Racy");
1752
+ const results = await many3(10, () => store.trash(a.id, ACTOR));
1753
+ expect([count3(results, "trashed"), count3(results, "alreadyTrashed")]).toEqual([1, 9]);
1754
+ expect(ids(await store.listTrashed())).toEqual([a.id]);
1755
+ });
1756
+ it("ten simultaneous restores of one trashed company give exactly one restored and nine notTrashed, and it is live afterwards", async () => {
1757
+ const { store, make } = await trashSetup();
1758
+ const a = await make(store, "Racy");
1759
+ await store.trash(a.id, ACTOR);
1760
+ const results = await many3(10, () => store.restore(a.id));
1761
+ expect([count3(results, "restored"), count3(results, "notTrashed")]).toEqual([1, 9]);
1762
+ expect(ids(await store.list())).toEqual([a.id]);
1763
+ });
1764
+ });
1765
+ }
1766
+
1556
1767
  // src/companies/server/contract-tenancy.ts
1557
1768
  function defineCompanyStoreTenancyContract(kit) {
1558
1769
  const { describe, it, expect } = kit.api;
@@ -1567,10 +1778,10 @@ function defineCompanyStoreTenancyContract(kit) {
1567
1778
  if (result.kind !== "added") throw new Error(`setup: could not add a member in the second workspace: ${result.kind}`);
1568
1779
  return result.member;
1569
1780
  };
1570
- const crowdB = async (count3) => {
1781
+ const crowdB = async (count4) => {
1571
1782
  const pb = await personB();
1572
1783
  const companies = [];
1573
- for (let i = 0; i < count3; i++) {
1784
+ for (let i = 0; i < count4; i++) {
1574
1785
  const result = await storeB.create({ name: `B ${i}`, nameKey: `b ${i}`, ...site("b.com") }, { maxCompanies: 1e3 });
1575
1786
  if (result.kind !== "created") throw new Error(`setup: could not create B ${i}: ${result.kind}`);
1576
1787
  await joinB(result.company.id, pb, "B");
@@ -1813,6 +2024,7 @@ function defineCompanyStoreContract(api, harness) {
1813
2024
  defineCompanyStoreConcurrencyContract(kit);
1814
2025
  defineCompanyStoreMembersConcurrencyContract(kit);
1815
2026
  defineCompanyStoreHooksContract(kit);
2027
+ if (harness.supportsTrash === true) defineCompanyStoreTrashContract(kit);
1816
2028
  api.it("cleans up", async () => {
1817
2029
  await harness.cleanup();
1818
2030
  });
@@ -9,6 +9,11 @@ interface PrismaNoteParentConfig {
9
9
  table: string;
10
10
  /** The parent model's workspace column. Defaults to the note's. */
11
11
  workspaceColumn?: string;
12
+ /**
13
+ * OPTIONAL. The parent model's nullable "trashed at" column (e.g. `deletedAt`). When set, `create` treats a parent whose column is not NULL as gone (`parentGone`), in both the
14
+ * existence check and the share lock. Off by default: without it the queries are exactly those of 1.5.0.
15
+ */
16
+ softDeleteColumn?: string;
12
17
  }
13
18
  interface PrismaNoteStoreConfig {
14
19
  /** Called each time the store needs the client (never at import), so a test can swap in a client with a bigger pool. */
@@ -37,7 +37,12 @@ function createContext(config) {
37
37
  const model2 = assertIdentifier(parent.model, `parents.${kind}.model`);
38
38
  const table = assertIdentifier(parent.table, `parents.${kind}.table`);
39
39
  const parentWorkspace = assertIdentifier(parent.workspaceColumn ?? workspaceColumn, `parents.${kind}.workspaceColumn`);
40
- kinds.set(kind, { kind, noteColumn, model: model2, workspaceColumn: parentWorkspace, sqlTable: quote(table), sqlWorkspaceColumn: quote(parentWorkspace) });
40
+ const resolved = { kind, noteColumn, model: model2, workspaceColumn: parentWorkspace, sqlTable: quote(table), sqlWorkspaceColumn: quote(parentWorkspace) };
41
+ if (parent.softDeleteColumn !== void 0) {
42
+ resolved.softDeleteColumn = assertIdentifier(parent.softDeleteColumn, `parents.${kind}.softDeleteColumn`);
43
+ resolved.sqlSoftDeleteColumn = quote(resolved.softDeleteColumn);
44
+ }
45
+ kinds.set(kind, resolved);
41
46
  }
42
47
  if (kinds.size === 0) throw new Error("createPrismaNoteStore: parents must name at least one kind of parent");
43
48
  const model = (client, name) => {
@@ -198,13 +203,13 @@ function createNoteWrites(context) {
198
203
  async create(parent, body, authorId) {
199
204
  const kind = context.parent(parent.kind);
200
205
  if (!kind) return { kind: "parentGone" };
201
- const parentExists = async () => await context.model(db(), kind.model).findFirst({ where: { id: parent.id, [kind.workspaceColumn]: context.workspaceId }, select: { id: true } }) != null;
206
+ const parentExists = async () => await context.model(db(), kind.model).findFirst({ where: { id: parent.id, [kind.workspaceColumn]: context.workspaceId, ...kind.softDeleteColumn ? { [kind.softDeleteColumn]: null } : {} }, select: { id: true } }) != null;
202
207
  if (!await parentExists()) return { kind: "parentGone" };
203
208
  if (context.beforeNoteWrite) await context.beforeNoteWrite();
204
209
  try {
205
210
  return await db().$transaction(async (tx) => {
206
211
  await context.limitLockWait(tx);
207
- const locked = await tx.$queryRawUnsafe(`SELECT "id" FROM ${kind.sqlTable} WHERE "id" = $1 AND ${kind.sqlWorkspaceColumn} = $2 FOR KEY SHARE`, parent.id, context.workspaceId);
212
+ const locked = await tx.$queryRawUnsafe(`SELECT "id" FROM ${kind.sqlTable} WHERE "id" = $1 AND ${kind.sqlWorkspaceColumn} = $2${kind.sqlSoftDeleteColumn ? ` AND ${kind.sqlSoftDeleteColumn} IS NULL` : ""} FOR KEY SHARE`, parent.id, context.workspaceId);
208
213
  if (locked.length === 0) return { kind: "parentGone" };
209
214
  const stamp = /* @__PURE__ */ new Date();
210
215
  const row = await context.notes(tx).create({
@@ -12,6 +12,11 @@ interface PrismaTagTarget {
12
12
  targetModel: string;
13
13
  /** The item model's workspace column. Defaults to the tag's. */
14
14
  targetWorkspaceColumn?: string;
15
+ /**
16
+ * OPTIONAL. The item model's nullable "trashed at" column (e.g. `deletedAt`). When set, an item whose column is not NULL counts as gone for tagging and untagging
17
+ * (`targetGone`). Counts and the tag lists of items are NOT filtered by it. Off by default: without it the queries are exactly those of 1.5.0.
18
+ */
19
+ softDeleteColumn?: string;
15
20
  }
16
21
  interface PrismaTagStoreConfig<Target extends string> {
17
22
  /** Called each time the store needs the client (never at import), so a test can swap in a client with a bigger pool. */
@@ -14,13 +14,15 @@ function quote(identifier) {
14
14
  // src/tags/prisma/context.ts
15
15
  function resolveTarget(kind, target, defaultWorkspaceColumn) {
16
16
  const where = `targets.${kind}`;
17
- return {
17
+ const resolved = {
18
18
  linkModel: assertIdentifier(target.linkModel, `${where}.linkModel`),
19
19
  linkTable: assertIdentifier(target.linkTable, `${where}.linkTable`),
20
20
  targetColumn: assertIdentifier(target.targetColumn, `${where}.targetColumn`),
21
21
  targetModel: assertIdentifier(target.targetModel, `${where}.targetModel`),
22
22
  targetWorkspaceColumn: assertIdentifier(target.targetWorkspaceColumn ?? defaultWorkspaceColumn, `${where}.targetWorkspaceColumn`)
23
23
  };
24
+ if (target.softDeleteColumn !== void 0) resolved.softDeleteColumn = assertIdentifier(target.softDeleteColumn, `${where}.softDeleteColumn`);
25
+ return resolved;
24
26
  }
25
27
  function createContext(config) {
26
28
  if (typeof config.client !== "function") throw new Error("createPrismaTagStore: client must be a function that returns the Prisma client");
@@ -167,7 +169,7 @@ function createReads(context) {
167
169
  },
168
170
  async targetExists(kind, targetId) {
169
171
  const target = context.target(kind);
170
- const row = await context.model(db(), target.targetModel).findFirst({ where: { id: targetId, [target.targetWorkspaceColumn]: context.workspaceId }, select: { id: true } });
172
+ const row = await context.model(db(), target.targetModel).findFirst({ where: { id: targetId, [target.targetWorkspaceColumn]: context.workspaceId, ...target.softDeleteColumn ? { [target.softDeleteColumn]: null } : {} }, select: { id: true } });
171
173
  return row !== null && row !== void 0;
172
174
  },
173
175
  async counts(ids) {
@@ -21,11 +21,15 @@ type CompanyWebsite = {
21
21
  interface CompanyCreateLimits {
22
22
  maxCompanies: number;
23
23
  }
24
+ /** `inTrash`: the name belongs to a company that is in the Trash (only a store with soft-delete configured reports it), with that company's id. */
24
25
  type CompanyCreateResult<T extends CompanyRecord> = {
25
26
  kind: 'created';
26
27
  company: T;
27
28
  } | {
28
29
  kind: 'duplicate';
30
+ } | {
31
+ kind: 'inTrash';
32
+ id: string;
29
33
  } | {
30
34
  kind: 'limit';
31
35
  };
@@ -46,6 +50,29 @@ type CompanyUpdateResult<T extends CompanyRecord> = {
46
50
  kind: 'notFound';
47
51
  } | {
48
52
  kind: 'duplicate';
53
+ } | {
54
+ kind: 'inTrash';
55
+ id: string;
56
+ };
57
+ /** Moving a company to the Trash (`TrashableCompanyStore` only). `before` and `after` are the rows around the change. */
58
+ type CompanyTrashResult<T extends CompanyRecord> = {
59
+ kind: 'trashed';
60
+ before: T;
61
+ after: T;
62
+ } | {
63
+ kind: 'notFound';
64
+ } | {
65
+ kind: 'alreadyTrashed';
66
+ };
67
+ /** Taking a company out of the Trash. */
68
+ type CompanyRestoreResult<T extends CompanyRecord> = {
69
+ kind: 'restored';
70
+ before: T;
71
+ after: T;
72
+ } | {
73
+ kind: 'notFound';
74
+ } | {
75
+ kind: 'notTrashed';
49
76
  };
50
77
  /** `memberCount` is how many people were detached with it, counted in the same transaction as the delete (an app's Activity entry quotes it). */
51
78
  type CompanyRemoveResult<T extends CompanyRecord> = {
@@ -165,5 +192,19 @@ interface CompanyStore<T extends CompanyRecord = CompanyRecord> {
165
192
  */
166
193
  companiesForPeople(personIds: string[]): Promise<Map<string, Array<PersonCompany<T>>>>;
167
194
  }
195
+ /**
196
+ * A `CompanyStore` that can also move companies to the Trash and back. A SEPARATE interface so existing implementers of `CompanyStore` are unaffected.
197
+ * On a trashable store the plain reads (`list`, `get`, ...) and writes see LIVE companies only; `remove` stays a hard delete of a company in ANY state.
198
+ */
199
+ interface TrashableCompanyStore<T extends CompanyRecord = CompanyRecord> extends CompanyStore<T> {
200
+ /** Atomic and idempotent under races: ten simultaneous trashes give one `trashed` and nine `alreadyTrashed`. `actorId` is stored with the trash (opaque to this package). */
201
+ trash(id: string, actorId: string): Promise<CompanyTrashResult<T>>;
202
+ /** Atomic: ten simultaneous restores give one `restored`. */
203
+ restore(id: string): Promise<CompanyRestoreResult<T>>;
204
+ /** Only the trashed companies of the workspace, the most recently trashed first. */
205
+ listTrashed(): Promise<T[]>;
206
+ /** The company of this workspace in ANY state (live or trashed), or null. */
207
+ getAny(id: string): Promise<T | null>;
208
+ }
168
209
 
169
- export type { CompanyRecord as C, PersonCompany as P, CompanyStore as a, CompanyMemberRecord as b, CompanyAddMemberResult as c, CompanyCreateLimits as d, CompanyCreateResult as e, CompanyMemberLimits as f, CompanyRemoveMemberResult as g, CompanyRemoveResult as h, CompanySetRoleResult as i, CompanyUpdatePatch as j, CompanyUpdateResult as k, CompanyWebsite as l };
210
+ export type { CompanyRecord as C, PersonCompany as P, TrashableCompanyStore as T, CompanyStore as a, CompanyMemberRecord as b, CompanyAddMemberResult as c, CompanyCreateLimits as d, CompanyCreateResult as e, CompanyMemberLimits as f, CompanyRemoveMemberResult as g, CompanyRemoveResult as h, CompanyRestoreResult as i, CompanySetRoleResult as j, CompanyTrashResult as k, CompanyUpdatePatch as l, CompanyUpdateResult as m, CompanyWebsite as n };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ordinatio/entities",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "description": "Entity knowledge, agent intelligence, notes, and contacts",