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