@saasicat/adapter-prisma 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1441 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/prisma-client-token.ts
5
+ var PRISMA_CLIENT_TOKEN = /* @__PURE__ */ Symbol.for("saasicat/adapter-prisma/PrismaClient");
6
+
7
+ // src/async-local-rls-bypass.adapter.ts
8
+ import { Injectable } from "@nestjs/common";
9
+ import { AsyncLocalStorage } from "async_hooks";
10
+ function _ts_decorate(decorators, target, key, desc) {
11
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
12
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
13
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
14
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
15
+ }
16
+ __name(_ts_decorate, "_ts_decorate");
17
+ var AsyncLocalRlsBypassAdapter = class {
18
+ static {
19
+ __name(this, "AsyncLocalRlsBypassAdapter");
20
+ }
21
+ storage = new AsyncLocalStorage();
22
+ async runWithBypass(fn) {
23
+ return this.storage.run({
24
+ bypass: true
25
+ }, fn);
26
+ }
27
+ /**
28
+ * `true` during the execution of a `runWithBypass(...)` callback.
29
+ * Query this in the PrismaService or an interceptor.
30
+ */
31
+ isBypassActive() {
32
+ return this.storage.getStore()?.bypass === true;
33
+ }
34
+ };
35
+ AsyncLocalRlsBypassAdapter = _ts_decorate([
36
+ Injectable()
37
+ ], AsyncLocalRlsBypassAdapter);
38
+
39
+ // src/prisma-audit.adapter.ts
40
+ import { Inject, Injectable as Injectable2 } from "@nestjs/common";
41
+ function _ts_decorate2(decorators, target, key, desc) {
42
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
43
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
44
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
45
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
46
+ }
47
+ __name(_ts_decorate2, "_ts_decorate");
48
+ function _ts_metadata(k, v) {
49
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
50
+ }
51
+ __name(_ts_metadata, "_ts_metadata");
52
+ function _ts_param(paramIndex, decorator) {
53
+ return function(target, key) {
54
+ decorator(target, key, paramIndex);
55
+ };
56
+ }
57
+ __name(_ts_param, "_ts_param");
58
+ function buildActorTag(actor) {
59
+ return `${actor.source}:${actor.email}:${actor.context}`;
60
+ }
61
+ __name(buildActorTag, "buildActorTag");
62
+ var PrismaAuditAdapter = class {
63
+ static {
64
+ __name(this, "PrismaAuditAdapter");
65
+ }
66
+ prisma;
67
+ constructor(prisma) {
68
+ this.prisma = prisma;
69
+ }
70
+ async write(input) {
71
+ await this.prisma.auditLog.create({
72
+ data: {
73
+ tenantId: null,
74
+ userId: input.actor.userId,
75
+ entity: input.entity,
76
+ entityId: input.entityId,
77
+ action: input.action,
78
+ changes: input.changes ?? {},
79
+ actorTag: buildActorTag(input.actor)
80
+ }
81
+ });
82
+ }
83
+ };
84
+ PrismaAuditAdapter = _ts_decorate2([
85
+ Injectable2(),
86
+ _ts_param(0, Inject(PRISMA_CLIENT_TOKEN)),
87
+ _ts_metadata("design:type", Function),
88
+ _ts_metadata("design:paramtypes", [
89
+ typeof PrismaLike === "undefined" ? Object : PrismaLike
90
+ ])
91
+ ], PrismaAuditAdapter);
92
+
93
+ // src/prisma-audit-query.adapter.ts
94
+ import { Inject as Inject2, Injectable as Injectable3 } from "@nestjs/common";
95
+ function _ts_decorate3(decorators, target, key, desc) {
96
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
97
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
98
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
99
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
100
+ }
101
+ __name(_ts_decorate3, "_ts_decorate");
102
+ function _ts_metadata2(k, v) {
103
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
104
+ }
105
+ __name(_ts_metadata2, "_ts_metadata");
106
+ function _ts_param2(paramIndex, decorator) {
107
+ return function(target, key) {
108
+ decorator(target, key, paramIndex);
109
+ };
110
+ }
111
+ __name(_ts_param2, "_ts_param");
112
+ var DEFAULT_PAGE_SIZE = 50;
113
+ var MAX_PAGE_SIZE = 200;
114
+ var PrismaAuditQueryAdapter = class {
115
+ static {
116
+ __name(this, "PrismaAuditQueryAdapter");
117
+ }
118
+ prisma;
119
+ constructor(prisma) {
120
+ this.prisma = prisma;
121
+ }
122
+ async list(filter) {
123
+ const page = Math.max(filter.page ?? 1, 1);
124
+ const pageSize = Math.min(Math.max(filter.pageSize ?? DEFAULT_PAGE_SIZE, 1), MAX_PAGE_SIZE);
125
+ const rows = await this.prisma.auditLog.findMany({
126
+ where: {
127
+ tenantId: filter.tenantId,
128
+ userId: filter.userId,
129
+ entity: filter.entity,
130
+ entityId: filter.entityId,
131
+ action: filter.action,
132
+ actorTag: toActorTagFilter(filter.actorTag),
133
+ createdAt: filter.from || filter.to ? {
134
+ gte: filter.from ? new Date(filter.from) : void 0,
135
+ lte: filter.to ? new Date(filter.to) : void 0
136
+ } : void 0
137
+ },
138
+ orderBy: {
139
+ createdAt: "desc"
140
+ },
141
+ skip: (page - 1) * pageSize,
142
+ take: pageSize
143
+ });
144
+ return rows.map(toAuditEntry);
145
+ }
146
+ };
147
+ PrismaAuditQueryAdapter = _ts_decorate3([
148
+ Injectable3(),
149
+ _ts_param2(0, Inject2(PRISMA_CLIENT_TOKEN)),
150
+ _ts_metadata2("design:type", Function),
151
+ _ts_metadata2("design:paramtypes", [
152
+ typeof PrismaLike === "undefined" ? Object : PrismaLike
153
+ ])
154
+ ], PrismaAuditQueryAdapter);
155
+ function toActorTagFilter(actorTag) {
156
+ if (!actorTag) return void 0;
157
+ if (actorTag.endsWith("*")) return {
158
+ startsWith: actorTag.slice(0, -1)
159
+ };
160
+ return actorTag;
161
+ }
162
+ __name(toActorTagFilter, "toActorTagFilter");
163
+ function toAuditEntry(row) {
164
+ return {
165
+ id: row.id,
166
+ tenantId: row.tenantId,
167
+ userId: row.userId,
168
+ // The schema does not persist the email — the actorTag carries it.
169
+ userEmail: row.actorTag?.split(":")[1] ?? null,
170
+ entity: row.entity,
171
+ entityId: row.entityId,
172
+ action: row.action,
173
+ changes: row.changes ?? null,
174
+ actorTag: row.actorTag,
175
+ ipAddress: row.ipAddress,
176
+ userAgent: row.userAgent,
177
+ createdAt: row.createdAt.toISOString()
178
+ };
179
+ }
180
+ __name(toAuditEntry, "toAuditEntry");
181
+
182
+ // src/prisma-audit-stats.adapter.ts
183
+ import { Inject as Inject3, Injectable as Injectable4 } from "@nestjs/common";
184
+ function _ts_decorate4(decorators, target, key, desc) {
185
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
186
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
187
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
188
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
189
+ }
190
+ __name(_ts_decorate4, "_ts_decorate");
191
+ function _ts_metadata3(k, v) {
192
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
193
+ }
194
+ __name(_ts_metadata3, "_ts_metadata");
195
+ function _ts_param3(paramIndex, decorator) {
196
+ return function(target, key) {
197
+ decorator(target, key, paramIndex);
198
+ };
199
+ }
200
+ __name(_ts_param3, "_ts_param");
201
+ var PrismaAuditStatsAdapter = class {
202
+ static {
203
+ __name(this, "PrismaAuditStatsAdapter");
204
+ }
205
+ prisma;
206
+ constructor(prisma) {
207
+ this.prisma = prisma;
208
+ }
209
+ async countSince(since) {
210
+ return this.prisma.auditLog.count({
211
+ where: {
212
+ createdAt: {
213
+ gte: since
214
+ }
215
+ }
216
+ });
217
+ }
218
+ };
219
+ PrismaAuditStatsAdapter = _ts_decorate4([
220
+ Injectable4(),
221
+ _ts_param3(0, Inject3(PRISMA_CLIENT_TOKEN)),
222
+ _ts_metadata3("design:type", Function),
223
+ _ts_metadata3("design:paramtypes", [
224
+ typeof PrismaLike === "undefined" ? Object : PrismaLike
225
+ ])
226
+ ], PrismaAuditStatsAdapter);
227
+
228
+ // src/prisma-mfa.adapter.ts
229
+ import { Inject as Inject4, Injectable as Injectable5 } from "@nestjs/common";
230
+ function _ts_decorate5(decorators, target, key, desc) {
231
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
232
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
233
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
234
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
235
+ }
236
+ __name(_ts_decorate5, "_ts_decorate");
237
+ function _ts_metadata4(k, v) {
238
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
239
+ }
240
+ __name(_ts_metadata4, "_ts_metadata");
241
+ function _ts_param4(paramIndex, decorator) {
242
+ return function(target, key) {
243
+ decorator(target, key, paramIndex);
244
+ };
245
+ }
246
+ __name(_ts_param4, "_ts_param");
247
+ var PrismaMfaAdapter = class {
248
+ static {
249
+ __name(this, "PrismaMfaAdapter");
250
+ }
251
+ prisma;
252
+ constructor(prisma) {
253
+ this.prisma = prisma;
254
+ }
255
+ async getSecret(userId) {
256
+ const row = await this.prisma.superAdminMfa.findUnique({
257
+ where: {
258
+ userId
259
+ }
260
+ });
261
+ return row?.secret ?? null;
262
+ }
263
+ async setSecret(userId, secret) {
264
+ const enabledAt = secret ? /* @__PURE__ */ new Date() : null;
265
+ await this.prisma.superAdminMfa.upsert({
266
+ where: {
267
+ userId
268
+ },
269
+ create: {
270
+ userId,
271
+ secret,
272
+ enabledAt
273
+ },
274
+ update: {
275
+ secret,
276
+ enabledAt
277
+ }
278
+ });
279
+ }
280
+ async isEnabled(userId) {
281
+ const row = await this.prisma.superAdminMfa.findUnique({
282
+ where: {
283
+ userId
284
+ }
285
+ });
286
+ return !!row?.secret && !!row?.enabledAt;
287
+ }
288
+ };
289
+ PrismaMfaAdapter = _ts_decorate5([
290
+ Injectable5(),
291
+ _ts_param4(0, Inject4(PRISMA_CLIENT_TOKEN)),
292
+ _ts_metadata4("design:type", Function),
293
+ _ts_metadata4("design:paramtypes", [
294
+ typeof PrismaLike === "undefined" ? Object : PrismaLike
295
+ ])
296
+ ], PrismaMfaAdapter);
297
+
298
+ // src/prisma-plan-catalog-import-sink.ts
299
+ import { Inject as Inject5, Injectable as Injectable6 } from "@nestjs/common";
300
+ function _ts_decorate6(decorators, target, key, desc) {
301
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
302
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
303
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
304
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
305
+ }
306
+ __name(_ts_decorate6, "_ts_decorate");
307
+ function _ts_metadata5(k, v) {
308
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
309
+ }
310
+ __name(_ts_metadata5, "_ts_metadata");
311
+ function _ts_param5(paramIndex, decorator) {
312
+ return function(target, key) {
313
+ decorator(target, key, paramIndex);
314
+ };
315
+ }
316
+ __name(_ts_param5, "_ts_param");
317
+ var PrismaPlanCatalogImportSink = class {
318
+ static {
319
+ __name(this, "PrismaPlanCatalogImportSink");
320
+ }
321
+ prisma;
322
+ constructor(prisma) {
323
+ this.prisma = prisma;
324
+ }
325
+ async upsertPlan(input) {
326
+ const existing = await this.prisma.plan.findFirst({
327
+ where: {
328
+ projectKey: input.projectKey,
329
+ planKey: input.planKey
330
+ }
331
+ });
332
+ if (existing) return {
333
+ created: false,
334
+ skipReason: "exists"
335
+ };
336
+ await this.prisma.plan.create({
337
+ data: {
338
+ projectKey: input.projectKey,
339
+ planKey: input.planKey,
340
+ label: input.label,
341
+ description: input.description ?? null,
342
+ sortOrder: input.sortOrder ?? 0
343
+ }
344
+ });
345
+ return {
346
+ created: true
347
+ };
348
+ }
349
+ async upsertPlanVersion(input) {
350
+ const existing = await this.prisma.planVersion.findFirst({
351
+ where: {
352
+ planId: input.planKey,
353
+ version: input.version
354
+ }
355
+ });
356
+ if (existing) return {
357
+ created: false,
358
+ skipReason: "exists"
359
+ };
360
+ const now = /* @__PURE__ */ new Date();
361
+ if (input.publish) {
362
+ await this.prisma.planVersion.updateMany({
363
+ where: {
364
+ planId: input.planKey,
365
+ publishedAt: {
366
+ not: null
367
+ },
368
+ supersededAt: null,
369
+ version: {
370
+ lt: input.version
371
+ }
372
+ },
373
+ data: {
374
+ supersededAt: now
375
+ }
376
+ });
377
+ }
378
+ await this.prisma.planVersion.create({
379
+ data: {
380
+ planId: input.planKey,
381
+ version: input.version,
382
+ features: input.features,
383
+ quotas: input.quotas,
384
+ monthlyNet: input.monthlyNet,
385
+ yearlyNet: input.yearlyNet,
386
+ marketed: input.marketed,
387
+ publishedAt: input.publish ? now : null,
388
+ changeNote: input.changeNote
389
+ }
390
+ });
391
+ return {
392
+ created: true
393
+ };
394
+ }
395
+ async upsertFeatureCatalogEntry(input) {
396
+ const existing = await this.prisma.featureCatalogEntry.findFirst({
397
+ where: {
398
+ projectKey: input.projectKey,
399
+ featureKey: input.featureKey
400
+ }
401
+ });
402
+ if (existing) return {
403
+ created: false,
404
+ skipReason: "exists"
405
+ };
406
+ await this.prisma.featureCatalogEntry.create({
407
+ data: {
408
+ projectKey: input.projectKey,
409
+ featureKey: input.featureKey,
410
+ label: input.label ?? input.featureKey,
411
+ icon: input.icon ?? null,
412
+ tier: input.tier ?? null,
413
+ plannedOnly: input.plannedOnly ?? false,
414
+ core: input.core ?? false
415
+ }
416
+ });
417
+ return {
418
+ created: true
419
+ };
420
+ }
421
+ };
422
+ PrismaPlanCatalogImportSink = _ts_decorate6([
423
+ Injectable6(),
424
+ _ts_param5(0, Inject5(PRISMA_CLIENT_TOKEN)),
425
+ _ts_metadata5("design:type", Function),
426
+ _ts_metadata5("design:paramtypes", [
427
+ typeof PrismaLike === "undefined" ? Object : PrismaLike
428
+ ])
429
+ ], PrismaPlanCatalogImportSink);
430
+
431
+ // src/prisma-plan-catalog-read-sink.ts
432
+ import { Inject as Inject6, Injectable as Injectable7 } from "@nestjs/common";
433
+
434
+ // src/tx.ts
435
+ function resolveClient(client, tx) {
436
+ return tx ?? client;
437
+ }
438
+ __name(resolveClient, "resolveClient");
439
+ function toQuotaMap(value) {
440
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
441
+ return value;
442
+ }
443
+ return {};
444
+ }
445
+ __name(toQuotaMap, "toQuotaMap");
446
+ function toStringArray(value) {
447
+ return Array.isArray(value) ? value : [];
448
+ }
449
+ __name(toStringArray, "toStringArray");
450
+
451
+ // src/prisma-plan-catalog-read-sink.ts
452
+ function _ts_decorate7(decorators, target, key, desc) {
453
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
454
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
455
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
456
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
457
+ }
458
+ __name(_ts_decorate7, "_ts_decorate");
459
+ function _ts_metadata6(k, v) {
460
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
461
+ }
462
+ __name(_ts_metadata6, "_ts_metadata");
463
+ function _ts_param6(paramIndex, decorator) {
464
+ return function(target, key) {
465
+ decorator(target, key, paramIndex);
466
+ };
467
+ }
468
+ __name(_ts_param6, "_ts_param");
469
+ var PrismaPlanCatalogReadSink = class {
470
+ static {
471
+ __name(this, "PrismaPlanCatalogReadSink");
472
+ }
473
+ prisma;
474
+ constructor(prisma) {
475
+ this.prisma = prisma;
476
+ }
477
+ async loadSnapshot(projectKey) {
478
+ const plans = await this.prisma.plan.findMany({
479
+ where: {
480
+ projectKey,
481
+ deletedAt: null
482
+ },
483
+ orderBy: {
484
+ sortOrder: "asc"
485
+ }
486
+ });
487
+ const planKeys = plans.map((plan) => plan.planKey);
488
+ const livePlanVersions = planKeys.length === 0 ? [] : await this.prisma.planVersion.findMany({
489
+ where: {
490
+ planId: {
491
+ in: planKeys
492
+ },
493
+ publishedAt: {
494
+ not: null
495
+ },
496
+ supersededAt: null
497
+ }
498
+ });
499
+ const featureEntries = await this.prisma.featureCatalogEntry.findMany({
500
+ where: {
501
+ projectKey,
502
+ deletedAt: null
503
+ },
504
+ orderBy: {
505
+ sortOrder: "asc"
506
+ }
507
+ });
508
+ return {
509
+ plans: plans.map(toPlanRow),
510
+ livePlanVersions: livePlanVersions.map(toPlanVersionRow),
511
+ featureEntries: featureEntries.map(toFeatureCatalogEntryRow)
512
+ };
513
+ }
514
+ };
515
+ PrismaPlanCatalogReadSink = _ts_decorate7([
516
+ Injectable7(),
517
+ _ts_param6(0, Inject6(PRISMA_CLIENT_TOKEN)),
518
+ _ts_metadata6("design:type", Function),
519
+ _ts_metadata6("design:paramtypes", [
520
+ typeof PrismaLike === "undefined" ? Object : PrismaLike
521
+ ])
522
+ ], PrismaPlanCatalogReadSink);
523
+ function toPlanRow(row) {
524
+ return {
525
+ id: row.id,
526
+ projectKey: row.projectKey,
527
+ planKey: row.planKey,
528
+ label: row.label,
529
+ description: row.description,
530
+ icon: row.icon,
531
+ sortOrder: row.sortOrder,
532
+ createdAt: row.createdAt.toISOString(),
533
+ updatedAt: row.updatedAt.toISOString(),
534
+ deletedAt: row.deletedAt ? row.deletedAt.toISOString() : null
535
+ };
536
+ }
537
+ __name(toPlanRow, "toPlanRow");
538
+ function toPlanVersionRow(row) {
539
+ return {
540
+ id: row.id,
541
+ planId: row.planId,
542
+ version: row.version,
543
+ baseVersionId: row.baseVersionId,
544
+ publishedAt: row.publishedAt ? row.publishedAt.toISOString() : null,
545
+ supersededAt: row.supersededAt ? row.supersededAt.toISOString() : null,
546
+ publishedChanges: row.publishedChanges ?? null,
547
+ changeNote: row.changeNote,
548
+ nonRegressive: row.nonRegressive,
549
+ validFrom: null,
550
+ validUntil: null,
551
+ createdByUserId: row.createdByUserId,
552
+ publishedByUserId: row.publishedByUserId,
553
+ createdAt: row.createdAt.toISOString(),
554
+ updatedAt: row.updatedAt.toISOString(),
555
+ features: toStringArray(row.features),
556
+ quotas: toQuotaMap(row.quotas),
557
+ monthlyNet: String(row.monthlyNet),
558
+ yearlyNet: String(row.yearlyNet),
559
+ marketed: row.marketed
560
+ };
561
+ }
562
+ __name(toPlanVersionRow, "toPlanVersionRow");
563
+ function toFeatureCatalogEntryRow(row) {
564
+ return {
565
+ id: row.id,
566
+ projectKey: row.projectKey,
567
+ featureKey: row.featureKey,
568
+ label: row.label,
569
+ description: row.description,
570
+ marketingLabel: row.marketingLabel,
571
+ marketingDescription: row.marketingDescription,
572
+ icon: row.icon,
573
+ tier: row.tier,
574
+ discoveryStatus: row.discoveryStatus,
575
+ requires: row.requires,
576
+ replaces: row.replaces,
577
+ successorKey: row.successorKey,
578
+ approvedAt: row.approvedAt ? row.approvedAt.toISOString() : null,
579
+ approvedBy: row.approvedBy,
580
+ approvedSignature: row.approvedSignature,
581
+ plannedOnly: row.plannedOnly,
582
+ core: row.core,
583
+ i18n: row.i18n ?? {},
584
+ sortOrder: row.sortOrder,
585
+ createdAt: row.createdAt.toISOString(),
586
+ updatedAt: row.updatedAt.toISOString(),
587
+ deletedAt: row.deletedAt ? row.deletedAt.toISOString() : null
588
+ };
589
+ }
590
+ __name(toFeatureCatalogEntryRow, "toFeatureCatalogEntryRow");
591
+
592
+ // src/prisma-plan-version.repository.ts
593
+ import { Inject as Inject7, Injectable as Injectable8 } from "@nestjs/common";
594
+ function _ts_decorate8(decorators, target, key, desc) {
595
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
596
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
597
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
598
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
599
+ }
600
+ __name(_ts_decorate8, "_ts_decorate");
601
+ function _ts_metadata7(k, v) {
602
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
603
+ }
604
+ __name(_ts_metadata7, "_ts_metadata");
605
+ function _ts_param7(paramIndex, decorator) {
606
+ return function(target, key) {
607
+ decorator(target, key, paramIndex);
608
+ };
609
+ }
610
+ __name(_ts_param7, "_ts_param");
611
+ var PrismaPlanVersionRepository = class {
612
+ static {
613
+ __name(this, "PrismaPlanVersionRepository");
614
+ }
615
+ prisma;
616
+ constructor(prisma) {
617
+ this.prisma = prisma;
618
+ }
619
+ async findLatestLive(planId, tx) {
620
+ const db = resolveClient(this.prisma, tx);
621
+ const row = await db.planVersion.findFirst({
622
+ where: {
623
+ planId,
624
+ publishedAt: {
625
+ not: null
626
+ },
627
+ supersededAt: null
628
+ },
629
+ orderBy: {
630
+ version: "desc"
631
+ }
632
+ });
633
+ if (!row) return null;
634
+ return {
635
+ planId: row.planId,
636
+ quotas: toQuotaMap(row.quotas),
637
+ features: toStringArray(row.features)
638
+ };
639
+ }
640
+ };
641
+ PrismaPlanVersionRepository = _ts_decorate8([
642
+ Injectable8(),
643
+ _ts_param7(0, Inject7(PRISMA_CLIENT_TOKEN)),
644
+ _ts_metadata7("design:type", Function),
645
+ _ts_metadata7("design:paramtypes", [
646
+ typeof PrismaLike === "undefined" ? Object : PrismaLike
647
+ ])
648
+ ], PrismaPlanVersionRepository);
649
+
650
+ // src/prisma-promo-code-redemption.repository.ts
651
+ import { Inject as Inject8, Injectable as Injectable9 } from "@nestjs/common";
652
+ function _ts_decorate9(decorators, target, key, desc) {
653
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
654
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
655
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
656
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
657
+ }
658
+ __name(_ts_decorate9, "_ts_decorate");
659
+ function _ts_metadata8(k, v) {
660
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
661
+ }
662
+ __name(_ts_metadata8, "_ts_metadata");
663
+ function _ts_param8(paramIndex, decorator) {
664
+ return function(target, key) {
665
+ decorator(target, key, paramIndex);
666
+ };
667
+ }
668
+ __name(_ts_param8, "_ts_param");
669
+ var PrismaPromoCodeRedemptionRepository = class {
670
+ static {
671
+ __name(this, "PrismaPromoCodeRedemptionRepository");
672
+ }
673
+ prisma;
674
+ constructor(prisma) {
675
+ this.prisma = prisma;
676
+ }
677
+ async findBySubscription(subscriptionId, tx) {
678
+ const db = resolveClient(this.prisma, tx);
679
+ const row = await db.promoCodeRedemption.findUnique({
680
+ where: {
681
+ subscriptionId
682
+ }
683
+ });
684
+ return row ? toRecord(row) : null;
685
+ }
686
+ async create(data, tx) {
687
+ const db = resolveClient(this.prisma, tx);
688
+ const row = await db.promoCodeRedemption.create({
689
+ data: {
690
+ promoCodeId: data.promoCodeId,
691
+ subscriptionId: data.subscriptionId,
692
+ tenantId: data.tenantId,
693
+ appliedValueType: data.appliedValueType,
694
+ appliedValue: data.appliedValue,
695
+ appliedDurationType: data.appliedDurationType,
696
+ appliedDurationValue: data.appliedDurationValue,
697
+ startsAt: data.startsAt,
698
+ endsAt: data.endsAt
699
+ }
700
+ });
701
+ return toRecord(row);
702
+ }
703
+ async setReversed(id, tx) {
704
+ const db = resolveClient(this.prisma, tx);
705
+ const row = await db.promoCodeRedemption.update({
706
+ where: {
707
+ id
708
+ },
709
+ data: {
710
+ status: "REVERSED",
711
+ reversedAt: /* @__PURE__ */ new Date()
712
+ }
713
+ });
714
+ return toRecord(row);
715
+ }
716
+ async countByPromoCode(promoCodeId, status) {
717
+ return this.prisma.promoCodeRedemption.count({
718
+ where: {
719
+ promoCodeId,
720
+ status
721
+ }
722
+ });
723
+ }
724
+ async listByPromoCode(promoCodeId) {
725
+ const rows = await this.prisma.promoCodeRedemption.findMany({
726
+ where: {
727
+ promoCodeId
728
+ },
729
+ orderBy: {
730
+ redeemedAt: "desc"
731
+ }
732
+ });
733
+ return rows.map(toRecord);
734
+ }
735
+ async expireDueRedemptions(now) {
736
+ const result = await this.prisma.promoCodeRedemption.updateMany({
737
+ where: {
738
+ status: "ACTIVE",
739
+ endsAt: {
740
+ lt: now
741
+ }
742
+ },
743
+ data: {
744
+ status: "EXPIRED"
745
+ }
746
+ });
747
+ return result.count;
748
+ }
749
+ };
750
+ PrismaPromoCodeRedemptionRepository = _ts_decorate9([
751
+ Injectable9(),
752
+ _ts_param8(0, Inject8(PRISMA_CLIENT_TOKEN)),
753
+ _ts_metadata8("design:type", Function),
754
+ _ts_metadata8("design:paramtypes", [
755
+ typeof PrismaLike === "undefined" ? Object : PrismaLike
756
+ ])
757
+ ], PrismaPromoCodeRedemptionRepository);
758
+ function toRecord(row) {
759
+ return {
760
+ id: row.id,
761
+ promoCodeId: row.promoCodeId,
762
+ subscriptionId: row.subscriptionId,
763
+ tenantId: row.tenantId,
764
+ appliedValueType: row.appliedValueType,
765
+ appliedValue: String(row.appliedValue),
766
+ appliedDurationType: row.appliedDurationType,
767
+ appliedDurationValue: row.appliedDurationValue,
768
+ startsAt: row.startsAt,
769
+ endsAt: row.endsAt,
770
+ status: row.status,
771
+ redeemedAt: row.redeemedAt,
772
+ reversedAt: row.reversedAt
773
+ };
774
+ }
775
+ __name(toRecord, "toRecord");
776
+
777
+ // src/prisma-promo-code.repository.ts
778
+ import { Inject as Inject9, Injectable as Injectable10 } from "@nestjs/common";
779
+ function _ts_decorate10(decorators, target, key, desc) {
780
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
781
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
782
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
783
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
784
+ }
785
+ __name(_ts_decorate10, "_ts_decorate");
786
+ function _ts_metadata9(k, v) {
787
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
788
+ }
789
+ __name(_ts_metadata9, "_ts_metadata");
790
+ function _ts_param9(paramIndex, decorator) {
791
+ return function(target, key) {
792
+ decorator(target, key, paramIndex);
793
+ };
794
+ }
795
+ __name(_ts_param9, "_ts_param");
796
+ var PrismaPromoCodeRepository = class {
797
+ static {
798
+ __name(this, "PrismaPromoCodeRepository");
799
+ }
800
+ prisma;
801
+ constructor(prisma) {
802
+ this.prisma = prisma;
803
+ }
804
+ async findById(id) {
805
+ const row = await this.prisma.promoCode.findUnique({
806
+ where: {
807
+ id
808
+ }
809
+ });
810
+ return row ? toRecord2(row) : null;
811
+ }
812
+ async findByCode(code, tx) {
813
+ const db = resolveClient(this.prisma, tx);
814
+ const row = await db.promoCode.findUnique({
815
+ where: {
816
+ code: normalizeCode(code)
817
+ }
818
+ });
819
+ if (!row || row.deletedAt) return null;
820
+ return toRecord2(row);
821
+ }
822
+ async findMany(filter) {
823
+ const rows = await this.prisma.promoCode.findMany({
824
+ where: {
825
+ deletedAt: null,
826
+ status: filter.status,
827
+ campaignTag: filter.campaignTag,
828
+ code: filter.search ? {
829
+ contains: normalizeCode(filter.search)
830
+ } : void 0
831
+ },
832
+ orderBy: {
833
+ createdAt: "desc"
834
+ }
835
+ });
836
+ return rows.map(toRecord2);
837
+ }
838
+ async create(data) {
839
+ const row = await this.prisma.promoCode.create({
840
+ data: {
841
+ code: normalizeCode(data.code),
842
+ valueType: data.valueType,
843
+ value: data.value.toFixed(2),
844
+ durationType: data.durationType,
845
+ durationValue: data.durationValue ?? null,
846
+ validFrom: data.validFrom ?? null,
847
+ validUntil: data.validUntil ?? null,
848
+ maxRedemptions: data.maxRedemptions ?? null,
849
+ appliesToPlans: data.appliesToPlans ?? [],
850
+ appliesToBilling: data.appliesToBilling ?? null,
851
+ firstTimeCustomersOnly: data.firstTimeCustomersOnly ?? true,
852
+ minimumPlanAmountGross: data.minimumPlanAmountGross?.toFixed(2) ?? null,
853
+ allowZeroInvoice: data.allowZeroInvoice ?? false,
854
+ description: data.description ?? null,
855
+ campaignTag: data.campaignTag ?? null,
856
+ revenueDeductionAccount: data.revenueDeductionAccount ?? null,
857
+ createdById: data.createdById
858
+ }
859
+ });
860
+ return toRecord2(row);
861
+ }
862
+ async update(id, data) {
863
+ const row = await this.prisma.promoCode.update({
864
+ where: {
865
+ id
866
+ },
867
+ data: {
868
+ status: data.status,
869
+ description: data.description,
870
+ validUntil: data.validUntil,
871
+ maxRedemptions: data.maxRedemptions
872
+ }
873
+ });
874
+ return toRecord2(row);
875
+ }
876
+ async softDelete(id) {
877
+ await this.prisma.promoCode.update({
878
+ where: {
879
+ id
880
+ },
881
+ data: {
882
+ deletedAt: /* @__PURE__ */ new Date()
883
+ }
884
+ });
885
+ }
886
+ async claimSlot(id, tx) {
887
+ const db = resolveClient(this.prisma, tx);
888
+ const updated = await db.$executeRaw`
889
+ UPDATE promo_codes
890
+ SET "redemptionsCount" = "redemptionsCount" + 1, "updatedAt" = NOW()
891
+ WHERE id = ${id}
892
+ AND status = 'ACTIVE'
893
+ AND "deletedAt" IS NULL
894
+ AND ("maxRedemptions" IS NULL OR "redemptionsCount" < "maxRedemptions")`;
895
+ return updated === 1;
896
+ }
897
+ async markExhaustedIfFull(id, tx) {
898
+ const db = resolveClient(this.prisma, tx);
899
+ await db.$executeRaw`
900
+ UPDATE promo_codes
901
+ SET status = 'EXHAUSTED', "updatedAt" = NOW()
902
+ WHERE id = ${id}
903
+ AND status = 'ACTIVE'
904
+ AND "maxRedemptions" IS NOT NULL
905
+ AND "redemptionsCount" >= "maxRedemptions"`;
906
+ }
907
+ async releaseSlot(id, tx) {
908
+ const db = resolveClient(this.prisma, tx);
909
+ await db.$executeRaw`
910
+ UPDATE promo_codes
911
+ SET "redemptionsCount" = GREATEST("redemptionsCount" - 1, 0),
912
+ status = CASE WHEN status = 'EXHAUSTED' THEN 'ACTIVE' ELSE status END,
913
+ "updatedAt" = NOW()
914
+ WHERE id = ${id}`;
915
+ }
916
+ async expireDueCodes(now) {
917
+ const result = await this.prisma.promoCode.updateMany({
918
+ where: {
919
+ status: {
920
+ in: [
921
+ "ACTIVE",
922
+ "PAUSED"
923
+ ]
924
+ },
925
+ validUntil: {
926
+ lt: now
927
+ }
928
+ },
929
+ data: {
930
+ status: "EXPIRED"
931
+ }
932
+ });
933
+ return result.count;
934
+ }
935
+ };
936
+ PrismaPromoCodeRepository = _ts_decorate10([
937
+ Injectable10(),
938
+ _ts_param9(0, Inject9(PRISMA_CLIENT_TOKEN)),
939
+ _ts_metadata9("design:type", Function),
940
+ _ts_metadata9("design:paramtypes", [
941
+ typeof PrismaLike === "undefined" ? Object : PrismaLike
942
+ ])
943
+ ], PrismaPromoCodeRepository);
944
+ function normalizeCode(code) {
945
+ return code.trim().toUpperCase();
946
+ }
947
+ __name(normalizeCode, "normalizeCode");
948
+ function toRecord2(row) {
949
+ return {
950
+ id: row.id,
951
+ code: row.code,
952
+ valueType: row.valueType,
953
+ value: String(row.value),
954
+ durationType: row.durationType,
955
+ durationValue: row.durationValue,
956
+ validFrom: row.validFrom,
957
+ validUntil: row.validUntil,
958
+ maxRedemptions: row.maxRedemptions,
959
+ redemptionsCount: row.redemptionsCount,
960
+ appliesToPlans: row.appliesToPlans,
961
+ appliesToBilling: row.appliesToBilling ?? null,
962
+ firstTimeCustomersOnly: row.firstTimeCustomersOnly,
963
+ minimumPlanAmountGross: row.minimumPlanAmountGross === null ? null : String(row.minimumPlanAmountGross),
964
+ allowZeroInvoice: row.allowZeroInvoice,
965
+ status: row.status,
966
+ description: row.description,
967
+ campaignTag: row.campaignTag,
968
+ revenueDeductionAccount: row.revenueDeductionAccount,
969
+ createdById: row.createdById,
970
+ createdAt: row.createdAt,
971
+ updatedAt: row.updatedAt,
972
+ deletedAt: row.deletedAt
973
+ };
974
+ }
975
+ __name(toRecord2, "toRecord");
976
+
977
+ // src/prisma-promo-code-validation-log.repository.ts
978
+ import { Inject as Inject10, Injectable as Injectable11 } from "@nestjs/common";
979
+ function _ts_decorate11(decorators, target, key, desc) {
980
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
981
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
982
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
983
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
984
+ }
985
+ __name(_ts_decorate11, "_ts_decorate");
986
+ function _ts_metadata10(k, v) {
987
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
988
+ }
989
+ __name(_ts_metadata10, "_ts_metadata");
990
+ function _ts_param10(paramIndex, decorator) {
991
+ return function(target, key) {
992
+ decorator(target, key, paramIndex);
993
+ };
994
+ }
995
+ __name(_ts_param10, "_ts_param");
996
+ var PrismaPromoCodeValidationLogRepository = class {
997
+ static {
998
+ __name(this, "PrismaPromoCodeValidationLogRepository");
999
+ }
1000
+ prisma;
1001
+ constructor(prisma) {
1002
+ this.prisma = prisma;
1003
+ }
1004
+ async log(args) {
1005
+ await this.prisma.promoCodeValidationLog.create({
1006
+ data: {
1007
+ promoCodeId: args.promoCodeId,
1008
+ codeAttempt: args.codeAttempt.trim().toUpperCase(),
1009
+ result: args.result,
1010
+ ipHash: args.ipHash ?? null,
1011
+ sessionId: args.sessionId ?? null
1012
+ }
1013
+ });
1014
+ }
1015
+ async countValid(promoCodeId) {
1016
+ return this.prisma.promoCodeValidationLog.count({
1017
+ where: {
1018
+ promoCodeId,
1019
+ result: "VALID"
1020
+ }
1021
+ });
1022
+ }
1023
+ };
1024
+ PrismaPromoCodeValidationLogRepository = _ts_decorate11([
1025
+ Injectable11(),
1026
+ _ts_param10(0, Inject10(PRISMA_CLIENT_TOKEN)),
1027
+ _ts_metadata10("design:type", Function),
1028
+ _ts_metadata10("design:paramtypes", [
1029
+ typeof PrismaLike === "undefined" ? Object : PrismaLike
1030
+ ])
1031
+ ], PrismaPromoCodeValidationLogRepository);
1032
+
1033
+ // src/prisma-promo-subscription-lookup.ts
1034
+ import { Inject as Inject11, Injectable as Injectable12 } from "@nestjs/common";
1035
+ function _ts_decorate12(decorators, target, key, desc) {
1036
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1037
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1038
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1039
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1040
+ }
1041
+ __name(_ts_decorate12, "_ts_decorate");
1042
+ function _ts_metadata11(k, v) {
1043
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1044
+ }
1045
+ __name(_ts_metadata11, "_ts_metadata");
1046
+ function _ts_param11(paramIndex, decorator) {
1047
+ return function(target, key) {
1048
+ decorator(target, key, paramIndex);
1049
+ };
1050
+ }
1051
+ __name(_ts_param11, "_ts_param");
1052
+ var PrismaPromoSubscriptionLookup = class {
1053
+ static {
1054
+ __name(this, "PrismaPromoSubscriptionLookup");
1055
+ }
1056
+ prisma;
1057
+ constructor(prisma) {
1058
+ this.prisma = prisma;
1059
+ }
1060
+ async findById(subscriptionId, tx) {
1061
+ const db = resolveClient(this.prisma, tx);
1062
+ const row = await db.subscription.findUnique({
1063
+ where: {
1064
+ id: subscriptionId
1065
+ }
1066
+ });
1067
+ if (!row) return null;
1068
+ return {
1069
+ id: row.id,
1070
+ tenantId: row.tenantId,
1071
+ plan: row.plan,
1072
+ billingCycle: row.billingCycle,
1073
+ startedAt: row.startedAt
1074
+ };
1075
+ }
1076
+ };
1077
+ PrismaPromoSubscriptionLookup = _ts_decorate12([
1078
+ Injectable12(),
1079
+ _ts_param11(0, Inject11(PRISMA_CLIENT_TOKEN)),
1080
+ _ts_metadata11("design:type", Function),
1081
+ _ts_metadata11("design:paramtypes", [
1082
+ typeof PrismaLike === "undefined" ? Object : PrismaLike
1083
+ ])
1084
+ ], PrismaPromoSubscriptionLookup);
1085
+
1086
+ // src/prisma-subscription.repository.ts
1087
+ import { Inject as Inject12, Injectable as Injectable13 } from "@nestjs/common";
1088
+ function _ts_decorate13(decorators, target, key, desc) {
1089
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1090
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1091
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1092
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1093
+ }
1094
+ __name(_ts_decorate13, "_ts_decorate");
1095
+ function _ts_metadata12(k, v) {
1096
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1097
+ }
1098
+ __name(_ts_metadata12, "_ts_metadata");
1099
+ function _ts_param12(paramIndex, decorator) {
1100
+ return function(target, key) {
1101
+ decorator(target, key, paramIndex);
1102
+ };
1103
+ }
1104
+ __name(_ts_param12, "_ts_param");
1105
+ var ACTIVE_STATUSES = [
1106
+ "ACTIVE",
1107
+ "TRIAL"
1108
+ ];
1109
+ var PrismaSubscriptionRepository = class {
1110
+ static {
1111
+ __name(this, "PrismaSubscriptionRepository");
1112
+ }
1113
+ prisma;
1114
+ constructor(prisma) {
1115
+ this.prisma = prisma;
1116
+ }
1117
+ async findByTenantId(tenantId) {
1118
+ return this.loadByTenantId(this.prisma, tenantId);
1119
+ }
1120
+ async findByTenantIdLocked(tenantId, tx) {
1121
+ const db = resolveClient(this.prisma, tx);
1122
+ await db.$queryRaw`SELECT id FROM subscriptions WHERE "tenantId" = ${tenantId} FOR UPDATE`;
1123
+ return this.loadByTenantId(db, tenantId);
1124
+ }
1125
+ async countByPlanVersionId(planVersionId) {
1126
+ return this.prisma.subscription.count({
1127
+ where: {
1128
+ OR: [
1129
+ {
1130
+ planVersionId
1131
+ },
1132
+ {
1133
+ pendingPlanVersionId: planVersionId
1134
+ }
1135
+ ]
1136
+ }
1137
+ });
1138
+ }
1139
+ async countActiveByPlanKey(_projectKey) {
1140
+ const rows = await this.prisma.subscription.findMany({
1141
+ where: {
1142
+ status: {
1143
+ in: ACTIVE_STATUSES
1144
+ }
1145
+ }
1146
+ });
1147
+ const counts = {};
1148
+ for (const row of rows) {
1149
+ counts[row.plan] = (counts[row.plan] ?? 0) + 1;
1150
+ }
1151
+ return counts;
1152
+ }
1153
+ async loadByTenantId(db, tenantId) {
1154
+ const row = await db.subscription.findUnique({
1155
+ where: {
1156
+ tenantId
1157
+ }
1158
+ });
1159
+ if (!row) return null;
1160
+ return this.toRecord(db, row);
1161
+ }
1162
+ async toRecord(db, row) {
1163
+ if (!row.planVersionId) {
1164
+ throw new Error(`Subscription ${row.id} binds no planVersionId (businessType-only composition). The shipped @saasicat/adapter-prisma SubscriptionRepository does not support BusinessType aggregation \u2014 provide a custom SubscriptionRepository adapter.`);
1165
+ }
1166
+ const planVersion = await db.planVersion.findUnique({
1167
+ where: {
1168
+ id: row.planVersionId
1169
+ }
1170
+ });
1171
+ if (!planVersion) {
1172
+ throw new Error(`Subscription ${row.id} references missing PlanVersion ${row.planVersionId}.`);
1173
+ }
1174
+ return {
1175
+ id: row.id,
1176
+ tenantId: row.tenantId,
1177
+ plan: row.plan,
1178
+ status: row.status,
1179
+ isPilot: row.isPilot,
1180
+ trialEntitlementPlan: row.trialEntitlementPlan,
1181
+ pendingPlan: row.pendingPlan,
1182
+ pendingEffectiveAt: row.pendingEffectiveAt,
1183
+ customLimits: row.customLimits ?? null,
1184
+ planVersionId: row.planVersionId,
1185
+ planVersion: {
1186
+ planId: planVersion.planId,
1187
+ quotas: toQuotaMap(planVersion.quotas),
1188
+ features: toStringArray(planVersion.features)
1189
+ }
1190
+ };
1191
+ }
1192
+ };
1193
+ PrismaSubscriptionRepository = _ts_decorate13([
1194
+ Injectable13(),
1195
+ _ts_param12(0, Inject12(PRISMA_CLIENT_TOKEN)),
1196
+ _ts_metadata12("design:type", Function),
1197
+ _ts_metadata12("design:paramtypes", [
1198
+ typeof PrismaLike === "undefined" ? Object : PrismaLike
1199
+ ])
1200
+ ], PrismaSubscriptionRepository);
1201
+
1202
+ // src/prisma-super-admin-bootstrap.adapter.ts
1203
+ import { Inject as Inject13, Injectable as Injectable14 } from "@nestjs/common";
1204
+ import { PlatformUserExistsError } from "@saasicat/types";
1205
+ function _ts_decorate14(decorators, target, key, desc) {
1206
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1207
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1208
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1209
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1210
+ }
1211
+ __name(_ts_decorate14, "_ts_decorate");
1212
+ function _ts_metadata13(k, v) {
1213
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1214
+ }
1215
+ __name(_ts_metadata13, "_ts_metadata");
1216
+ function _ts_param13(paramIndex, decorator) {
1217
+ return function(target, key) {
1218
+ decorator(target, key, paramIndex);
1219
+ };
1220
+ }
1221
+ __name(_ts_param13, "_ts_param");
1222
+ var PASSWORD_HASHER_TOKEN = /* @__PURE__ */ Symbol.for("saasicat/adapter-prisma/PasswordHasher");
1223
+ var PrismaSuperAdminBootstrapAdapter = class {
1224
+ static {
1225
+ __name(this, "PrismaSuperAdminBootstrapAdapter");
1226
+ }
1227
+ prisma;
1228
+ passwordHasher;
1229
+ constructor(prisma, passwordHasher) {
1230
+ this.prisma = prisma;
1231
+ this.passwordHasher = passwordHasher;
1232
+ }
1233
+ async countSuperAdmins() {
1234
+ return this.prisma.superAdminUser.count({
1235
+ where: {
1236
+ isActive: true,
1237
+ deletedAt: null
1238
+ }
1239
+ });
1240
+ }
1241
+ async createSuperAdmin(input) {
1242
+ const email = input.email.trim().toLowerCase();
1243
+ const existing = await this.prisma.superAdminUser.findUnique({
1244
+ where: {
1245
+ email
1246
+ }
1247
+ });
1248
+ if (existing) {
1249
+ throw new PlatformUserExistsError(email, existing.platformRole);
1250
+ }
1251
+ const row = await this.prisma.superAdminUser.create({
1252
+ data: {
1253
+ email,
1254
+ passwordHash: await this.passwordHasher.hash(input.password),
1255
+ firstName: input.firstName ?? null,
1256
+ lastName: input.lastName ?? null
1257
+ }
1258
+ });
1259
+ return {
1260
+ id: row.id,
1261
+ email: row.email,
1262
+ firstName: row.firstName ?? void 0,
1263
+ lastName: row.lastName ?? void 0,
1264
+ platformRole: row.platformRole,
1265
+ isActive: row.isActive,
1266
+ lastLoginAt: null,
1267
+ deletedAt: null
1268
+ };
1269
+ }
1270
+ };
1271
+ PrismaSuperAdminBootstrapAdapter = _ts_decorate14([
1272
+ Injectable14(),
1273
+ _ts_param13(0, Inject13(PRISMA_CLIENT_TOKEN)),
1274
+ _ts_param13(1, Inject13(PASSWORD_HASHER_TOKEN)),
1275
+ _ts_metadata13("design:type", Function),
1276
+ _ts_metadata13("design:paramtypes", [
1277
+ typeof PrismaLike === "undefined" ? Object : PrismaLike,
1278
+ typeof PasswordHasher === "undefined" ? Object : PasswordHasher
1279
+ ])
1280
+ ], PrismaSuperAdminBootstrapAdapter);
1281
+
1282
+ // src/prisma-transaction-runner.ts
1283
+ import { Inject as Inject14, Injectable as Injectable15 } from "@nestjs/common";
1284
+ function _ts_decorate15(decorators, target, key, desc) {
1285
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1286
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1287
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1288
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1289
+ }
1290
+ __name(_ts_decorate15, "_ts_decorate");
1291
+ function _ts_metadata14(k, v) {
1292
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1293
+ }
1294
+ __name(_ts_metadata14, "_ts_metadata");
1295
+ function _ts_param14(paramIndex, decorator) {
1296
+ return function(target, key) {
1297
+ decorator(target, key, paramIndex);
1298
+ };
1299
+ }
1300
+ __name(_ts_param14, "_ts_param");
1301
+ var PrismaTransactionRunner = class {
1302
+ static {
1303
+ __name(this, "PrismaTransactionRunner");
1304
+ }
1305
+ prisma;
1306
+ constructor(prisma) {
1307
+ this.prisma = prisma;
1308
+ }
1309
+ async run(fn) {
1310
+ return this.prisma.$transaction((tx) => fn(tx));
1311
+ }
1312
+ };
1313
+ PrismaTransactionRunner = _ts_decorate15([
1314
+ Injectable15(),
1315
+ _ts_param14(0, Inject14(PRISMA_CLIENT_TOKEN)),
1316
+ _ts_metadata14("design:type", Function),
1317
+ _ts_metadata14("design:paramtypes", [
1318
+ typeof PrismaLike === "undefined" ? Object : PrismaLike
1319
+ ])
1320
+ ], PrismaTransactionRunner);
1321
+
1322
+ // src/zero-promo-revenue-aggregator.ts
1323
+ import { Injectable as Injectable16 } from "@nestjs/common";
1324
+ function _ts_decorate16(decorators, target, key, desc) {
1325
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1326
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
1327
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1328
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
1329
+ }
1330
+ __name(_ts_decorate16, "_ts_decorate");
1331
+ var ZeroPromoRevenueDeductionAggregator = class {
1332
+ static {
1333
+ __name(this, "ZeroPromoRevenueDeductionAggregator");
1334
+ }
1335
+ async sumGrossForPromoCode(_promoCodeId) {
1336
+ return "0.00";
1337
+ }
1338
+ };
1339
+ ZeroPromoRevenueDeductionAggregator = _ts_decorate16([
1340
+ Injectable16()
1341
+ ], ZeroPromoRevenueDeductionAggregator);
1342
+
1343
+ // src/prisma-persistence.ts
1344
+ function prismaPersistence(options) {
1345
+ const { client } = options;
1346
+ const provide = /* @__PURE__ */ __name((build) => isInjectionToken(client) ? {
1347
+ useFactory: /* @__PURE__ */ __name((prisma) => build(prisma), "useFactory"),
1348
+ inject: [
1349
+ client
1350
+ ]
1351
+ } : build(client), "provide");
1352
+ return {
1353
+ capabilities: {
1354
+ transactions: true,
1355
+ pessimisticLocking: true,
1356
+ rowLevelSecurity: options.rlsIntegration ?? false,
1357
+ advisoryLocks: false
1358
+ },
1359
+ core: {
1360
+ mfa: provide((prisma) => new PrismaMfaAdapter(prisma)),
1361
+ audit: provide((prisma) => new PrismaAuditAdapter(prisma)),
1362
+ rlsBypass: new AsyncLocalRlsBypassAdapter(),
1363
+ transactionRunner: provide((prisma) => new PrismaTransactionRunner(prisma)),
1364
+ auditQuery: provide((prisma) => new PrismaAuditQueryAdapter(prisma)),
1365
+ auditStats: provide((prisma) => new PrismaAuditStatsAdapter(prisma)),
1366
+ superAdminProvisioning: buildProvisioning(client, options.passwordHasher)
1367
+ },
1368
+ entitlement: {
1369
+ subscriptionRepository: provide((prisma) => new PrismaSubscriptionRepository(prisma)),
1370
+ planVersionRepository: provide((prisma) => new PrismaPlanVersionRepository(prisma))
1371
+ },
1372
+ promo: {
1373
+ promoCodeRepository: provide((prisma) => new PrismaPromoCodeRepository(prisma)),
1374
+ redemptionRepository: provide((prisma) => new PrismaPromoCodeRedemptionRepository(prisma)),
1375
+ validationLogRepository: provide((prisma) => new PrismaPromoCodeValidationLogRepository(prisma)),
1376
+ subscriptionLookup: provide((prisma) => new PrismaPromoSubscriptionLookup(prisma)),
1377
+ revenueAggregator: new ZeroPromoRevenueDeductionAggregator()
1378
+ },
1379
+ planCatalogReadSink: provide((prisma) => new PrismaPlanCatalogReadSink(prisma)),
1380
+ planCatalogImportSink: provide((prisma) => new PrismaPlanCatalogImportSink(prisma))
1381
+ };
1382
+ }
1383
+ __name(prismaPersistence, "prismaPersistence");
1384
+ function isInjectionToken(value) {
1385
+ return typeof value === "function" || typeof value === "symbol" || typeof value === "string";
1386
+ }
1387
+ __name(isInjectionToken, "isInjectionToken");
1388
+ function buildProvisioning(client, hasher) {
1389
+ if (hasher === void 0) return void 0;
1390
+ const clientIsToken = isInjectionToken(client);
1391
+ const hasherIsToken = isInjectionToken(hasher);
1392
+ if (clientIsToken && hasherIsToken) {
1393
+ return {
1394
+ useFactory: /* @__PURE__ */ __name((prisma, h) => new PrismaSuperAdminBootstrapAdapter(prisma, h), "useFactory"),
1395
+ inject: [
1396
+ client,
1397
+ hasher
1398
+ ]
1399
+ };
1400
+ }
1401
+ if (clientIsToken) {
1402
+ return {
1403
+ useFactory: /* @__PURE__ */ __name((prisma) => new PrismaSuperAdminBootstrapAdapter(prisma, hasher), "useFactory"),
1404
+ inject: [
1405
+ client
1406
+ ]
1407
+ };
1408
+ }
1409
+ if (hasherIsToken) {
1410
+ return {
1411
+ useFactory: /* @__PURE__ */ __name((h) => new PrismaSuperAdminBootstrapAdapter(client, h), "useFactory"),
1412
+ inject: [
1413
+ hasher
1414
+ ]
1415
+ };
1416
+ }
1417
+ return new PrismaSuperAdminBootstrapAdapter(client, hasher);
1418
+ }
1419
+ __name(buildProvisioning, "buildProvisioning");
1420
+ export {
1421
+ AsyncLocalRlsBypassAdapter,
1422
+ PASSWORD_HASHER_TOKEN,
1423
+ PRISMA_CLIENT_TOKEN,
1424
+ PrismaAuditAdapter,
1425
+ PrismaAuditQueryAdapter,
1426
+ PrismaAuditStatsAdapter,
1427
+ PrismaMfaAdapter,
1428
+ PrismaPlanCatalogImportSink,
1429
+ PrismaPlanCatalogReadSink,
1430
+ PrismaPlanVersionRepository,
1431
+ PrismaPromoCodeRedemptionRepository,
1432
+ PrismaPromoCodeRepository,
1433
+ PrismaPromoCodeValidationLogRepository,
1434
+ PrismaPromoSubscriptionLookup,
1435
+ PrismaSubscriptionRepository,
1436
+ PrismaSuperAdminBootstrapAdapter,
1437
+ PrismaTransactionRunner,
1438
+ ZeroPromoRevenueDeductionAggregator,
1439
+ buildActorTag,
1440
+ prismaPersistence
1441
+ };