@nehorai/payments-drizzle 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1289 @@
1
+ // src/schema/payment-transactions.ts
2
+ import { pgTable, uuid, text, numeric, timestamp, jsonb, index, unique } from "drizzle-orm/pg-core";
3
+ var paymentTransactions = pgTable(
4
+ "payment_transactions",
5
+ {
6
+ id: uuid("id").defaultRandom().primaryKey(),
7
+ // Idempotency - prevents duplicate charges
8
+ internal_payment_id: text("internal_payment_id").notNull(),
9
+ idempotency_key: text("idempotency_key"),
10
+ // User association (FK configured at application level)
11
+ user_id: uuid("user_id").notNull(),
12
+ // Transaction classification
13
+ transaction_type: text("transaction_type").$type().notNull(),
14
+ status: text("status").$type().notNull().default("created"),
15
+ // Amounts in smallest currency unit (cents/agorot)
16
+ amount_minor: numeric("amount_minor").notNull(),
17
+ currency: text("currency").notNull().default("USD"),
18
+ // Original amount if currency converted
19
+ original_amount_minor: numeric("original_amount_minor"),
20
+ original_currency: text("original_currency"),
21
+ currency_conversion_rate: numeric("currency_conversion_rate"),
22
+ // Provider information
23
+ provider: text("provider").notNull(),
24
+ // stripe, hyp, cardcom
25
+ provider_transaction_id: text("provider_transaction_id"),
26
+ provider_authorization_code: text("provider_authorization_code"),
27
+ provider_metadata: jsonb("provider_metadata").$type(),
28
+ // Two-phase commit tracking (J5)
29
+ authorized_at: timestamp("authorized_at", { withTimezone: true }),
30
+ captured_at: timestamp("captured_at", { withTimezone: true }),
31
+ voided_at: timestamp("voided_at", { withTimezone: true }),
32
+ capture_deadline: timestamp("capture_deadline", { withTimezone: true }),
33
+ // Refund tracking
34
+ refunded_amount_minor: numeric("refunded_amount_minor").default("0"),
35
+ last_refund_at: timestamp("last_refund_at", { withTimezone: true }),
36
+ // Tax invoice (Israeli requirement)
37
+ tax_invoice_status: text("tax_invoice_status").$type().default("pending"),
38
+ tax_invoice_number: text("tax_invoice_number"),
39
+ tax_invoice_url: text("tax_invoice_url"),
40
+ // Error tracking
41
+ failure_code: text("failure_code"),
42
+ failure_message: text("failure_message"),
43
+ failure_details: jsonb("failure_details"),
44
+ // Application metadata
45
+ description: text("description"),
46
+ metadata: jsonb("metadata").$type(),
47
+ // Timestamps
48
+ created_at: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
49
+ updated_at: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow()
50
+ },
51
+ (table) => ({
52
+ // Performance indexes
53
+ userIdx: index("payment_transactions_user_idx").on(table.user_id),
54
+ statusIdx: index("payment_transactions_status_idx").on(table.status),
55
+ providerIdx: index("payment_transactions_provider_idx").on(table.provider),
56
+ providerTxIdx: index("payment_transactions_provider_tx_idx").on(table.provider_transaction_id),
57
+ createdAtIdx: index("payment_transactions_created_at_idx").on(table.created_at),
58
+ // Unique constraints for idempotency
59
+ internalIdUnique: unique("payment_transactions_internal_id_unique").on(
60
+ table.internal_payment_id
61
+ ),
62
+ idempotencyUnique: unique("payment_transactions_idempotency_unique").on(table.idempotency_key)
63
+ })
64
+ );
65
+
66
+ // src/schema/payment-methods.ts
67
+ import { pgTable as pgTable2, uuid as uuid2, text as text2, boolean, timestamp as timestamp2, jsonb as jsonb2, index as index2 } from "drizzle-orm/pg-core";
68
+ var paymentMethods = pgTable2(
69
+ "payment_methods",
70
+ {
71
+ id: uuid2("id").defaultRandom().primaryKey(),
72
+ // User association (FK configured at application level)
73
+ user_id: uuid2("user_id").notNull(),
74
+ // Method type
75
+ type: text2("type").$type().notNull(),
76
+ // Provider information
77
+ provider: text2("provider").notNull(),
78
+ // stripe, hyp, cardcom
79
+ provider_payment_method_id: text2("provider_payment_method_id").notNull(),
80
+ // Card details (tokenized, never full numbers)
81
+ card_brand: text2("card_brand").$type(),
82
+ card_last4: text2("card_last4"),
83
+ card_exp_month: text2("card_exp_month"),
84
+ card_exp_year: text2("card_exp_year"),
85
+ card_bin: text2("card_bin"),
86
+ // First 6-8 digits for routing
87
+ // State
88
+ is_default: boolean("is_default").default(false),
89
+ is_active: boolean("is_active").default(true),
90
+ // Provider-specific data
91
+ provider_metadata: jsonb2("provider_metadata").$type(),
92
+ // Timestamps
93
+ created_at: timestamp2("created_at", { withTimezone: true }).notNull().defaultNow(),
94
+ updated_at: timestamp2("updated_at", { withTimezone: true }).notNull().defaultNow(),
95
+ last_used_at: timestamp2("last_used_at", { withTimezone: true })
96
+ },
97
+ (table) => ({
98
+ // Performance indexes
99
+ userIdx: index2("payment_methods_user_idx").on(table.user_id),
100
+ userDefaultIdx: index2("payment_methods_user_default_idx").on(table.user_id, table.is_default),
101
+ providerIdx: index2("payment_methods_provider_idx").on(table.provider),
102
+ providerMethodIdx: index2("payment_methods_provider_method_idx").on(
103
+ table.provider_payment_method_id
104
+ ),
105
+ cardBinIdx: index2("payment_methods_card_bin_idx").on(table.card_bin)
106
+ })
107
+ );
108
+
109
+ // src/schema/webhook-events.ts
110
+ import {
111
+ pgTable as pgTable3,
112
+ uuid as uuid3,
113
+ text as text3,
114
+ timestamp as timestamp3,
115
+ jsonb as jsonb3,
116
+ index as index3,
117
+ unique as unique2
118
+ } from "drizzle-orm/pg-core";
119
+ var paymentWebhookEvents = pgTable3(
120
+ "payment_webhook_events",
121
+ {
122
+ id: uuid3("id").defaultRandom().primaryKey(),
123
+ // Event identification
124
+ provider: text3("provider").notNull(),
125
+ // stripe, hyp, cardcom
126
+ provider_event_id: text3("provider_event_id").notNull(),
127
+ event_type: text3("event_type").notNull(),
128
+ // Processing state
129
+ status: text3("status").$type().notNull().default("pending"),
130
+ attempts: text3("attempts").default("0"),
131
+ last_attempt_at: timestamp3("last_attempt_at", { withTimezone: true }),
132
+ // Linked transaction (if applicable)
133
+ transaction_id: uuid3("transaction_id"),
134
+ // Event payload (store for debugging and retry)
135
+ payload: jsonb3("payload").$type().notNull(),
136
+ signature: text3("signature"),
137
+ // Error tracking
138
+ error_message: text3("error_message"),
139
+ error_details: jsonb3("error_details"),
140
+ // Timestamps
141
+ received_at: timestamp3("received_at", { withTimezone: true }).notNull().defaultNow(),
142
+ processed_at: timestamp3("processed_at", { withTimezone: true }),
143
+ created_at: timestamp3("created_at", { withTimezone: true }).notNull().defaultNow()
144
+ },
145
+ (table) => ({
146
+ // Unique constraint for idempotency
147
+ providerEventUnique: unique2("webhook_events_provider_event_unique").on(
148
+ table.provider,
149
+ table.provider_event_id
150
+ ),
151
+ // Performance indexes
152
+ statusIdx: index3("webhook_events_status_idx").on(table.status),
153
+ transactionIdx: index3("webhook_events_transaction_idx").on(
154
+ table.transaction_id
155
+ ),
156
+ receivedAtIdx: index3("webhook_events_received_at_idx").on(table.received_at),
157
+ providerIdx: index3("webhook_events_provider_idx").on(table.provider),
158
+ eventTypeIdx: index3("webhook_events_event_type_idx").on(table.event_type)
159
+ })
160
+ );
161
+
162
+ // src/schema/payment-audit-log.ts
163
+ import {
164
+ pgTable as pgTable4,
165
+ uuid as uuid4,
166
+ text as text4,
167
+ timestamp as timestamp4,
168
+ jsonb as jsonb4,
169
+ index as index4
170
+ } from "drizzle-orm/pg-core";
171
+ var paymentAuditLog = pgTable4(
172
+ "payment_audit_log",
173
+ {
174
+ id: uuid4("id").defaultRandom().primaryKey(),
175
+ // What transaction was affected
176
+ transaction_id: uuid4("transaction_id").notNull(),
177
+ // What action occurred
178
+ action: text4("action").$type().notNull(),
179
+ // State before and after
180
+ previous_state: jsonb4("previous_state"),
181
+ new_state: jsonb4("new_state").notNull(),
182
+ // Who/what triggered this change
183
+ triggered_by: text4("triggered_by").$type().notNull(),
184
+ triggered_by_id: uuid4("triggered_by_id"),
185
+ // User ID if applicable
186
+ // Request context
187
+ ip_address: text4("ip_address"),
188
+ user_agent: text4("user_agent"),
189
+ // Correlation for distributed tracing
190
+ correlation_id: text4("correlation_id"),
191
+ // Additional context
192
+ metadata: jsonb4("metadata").$type(),
193
+ // Immutable timestamp (never updated)
194
+ created_at: timestamp4("created_at", { withTimezone: true }).notNull().defaultNow()
195
+ },
196
+ (table) => ({
197
+ // Performance indexes
198
+ transactionIdx: index4("payment_audit_log_transaction_idx").on(
199
+ table.transaction_id
200
+ ),
201
+ actionIdx: index4("payment_audit_log_action_idx").on(table.action),
202
+ correlationIdx: index4("payment_audit_log_correlation_idx").on(
203
+ table.correlation_id
204
+ ),
205
+ createdAtIdx: index4("payment_audit_log_created_at_idx").on(table.created_at),
206
+ triggeredByIdx: index4("payment_audit_log_triggered_by_idx").on(
207
+ table.triggered_by
208
+ )
209
+ })
210
+ );
211
+
212
+ // src/schema/provider-health.ts
213
+ import {
214
+ pgTable as pgTable5,
215
+ uuid as uuid5,
216
+ text as text5,
217
+ numeric as numeric2,
218
+ timestamp as timestamp5,
219
+ jsonb as jsonb5,
220
+ index as index5,
221
+ unique as unique3
222
+ } from "drizzle-orm/pg-core";
223
+ var providerHealth = pgTable5(
224
+ "payment_provider_health",
225
+ {
226
+ id: uuid5("id").defaultRandom().primaryKey(),
227
+ // Provider identification
228
+ provider: text5("provider").notNull(),
229
+ // stripe, hyp, cardcom
230
+ // Circuit breaker state
231
+ circuit_state: text5("circuit_state").$type().notNull().default("closed"),
232
+ // Failure tracking
233
+ failure_count: text5("failure_count").default("0"),
234
+ success_count: text5("success_count").default("0"),
235
+ last_failure_at: timestamp5("last_failure_at", { withTimezone: true }),
236
+ last_success_at: timestamp5("last_success_at", { withTimezone: true }),
237
+ // Circuit breaker timing
238
+ circuit_opened_at: timestamp5("circuit_opened_at", { withTimezone: true }),
239
+ next_retry_at: timestamp5("next_retry_at", { withTimezone: true }),
240
+ // Performance metrics
241
+ avg_latency_ms: numeric2("avg_latency_ms"),
242
+ error_rate: numeric2("error_rate"),
243
+ // 0-1
244
+ request_count_window: text5("request_count_window").default("0"),
245
+ // Health check results
246
+ last_health_check_at: timestamp5("last_health_check_at", { withTimezone: true }),
247
+ health_check_result: jsonb5("health_check_result").$type(),
248
+ // Timestamps
249
+ created_at: timestamp5("created_at", { withTimezone: true }).notNull().defaultNow(),
250
+ updated_at: timestamp5("updated_at", { withTimezone: true }).notNull().defaultNow()
251
+ },
252
+ (table) => ({
253
+ // One record per provider
254
+ providerUnique: unique3("provider_health_provider_unique").on(table.provider),
255
+ // Performance indexes
256
+ circuitStateIdx: index5("provider_health_circuit_state_idx").on(
257
+ table.circuit_state
258
+ ),
259
+ nextRetryIdx: index5("provider_health_next_retry_idx").on(table.next_retry_at)
260
+ })
261
+ );
262
+
263
+ // src/repositories/base-drizzle.repository.ts
264
+ function toCamelCase(row) {
265
+ const result = {};
266
+ for (const [key, value] of Object.entries(row)) {
267
+ const camelKey = key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
268
+ result[camelKey] = value;
269
+ }
270
+ return result;
271
+ }
272
+ function toSnakeCase(obj) {
273
+ const result = {};
274
+ for (const [key, value] of Object.entries(obj)) {
275
+ if (value === void 0) continue;
276
+ const snakeKey = key.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
277
+ result[snakeKey] = value;
278
+ }
279
+ return result;
280
+ }
281
+ function applyPagination(items, total, limit, offset) {
282
+ return {
283
+ data: items,
284
+ total,
285
+ limit,
286
+ offset,
287
+ hasMore: offset + items.length < total
288
+ };
289
+ }
290
+ function parseNumeric(value) {
291
+ if (value === null || value === void 0) return 0;
292
+ if (typeof value === "number") return value;
293
+ return parseFloat(value) || 0;
294
+ }
295
+ function normalizeArrayFilter(value) {
296
+ if (value === void 0) return void 0;
297
+ return Array.isArray(value) ? value : [value];
298
+ }
299
+
300
+ // src/repositories/transaction.drizzle-repository.ts
301
+ import { eq, and, gte, lte, inArray, sql, count } from "drizzle-orm";
302
+ function mapToTransaction(row) {
303
+ return {
304
+ id: row.id,
305
+ internalPaymentId: row.internal_payment_id,
306
+ idempotencyKey: row.idempotency_key,
307
+ userId: row.user_id,
308
+ transactionType: row.transaction_type,
309
+ status: row.status,
310
+ amountMinor: parseNumeric(row.amount_minor),
311
+ currency: row.currency,
312
+ originalAmountMinor: row.original_amount_minor ? parseNumeric(row.original_amount_minor) : null,
313
+ originalCurrency: row.original_currency,
314
+ currencyConversionRate: row.currency_conversion_rate ? parseNumeric(row.currency_conversion_rate) : null,
315
+ provider: row.provider,
316
+ providerTransactionId: row.provider_transaction_id,
317
+ providerAuthorizationCode: row.provider_authorization_code,
318
+ providerMetadata: row.provider_metadata,
319
+ authorizedAt: row.authorized_at,
320
+ capturedAt: row.captured_at,
321
+ voidedAt: row.voided_at,
322
+ captureDeadline: row.capture_deadline,
323
+ refundedAmountMinor: parseNumeric(row.refunded_amount_minor),
324
+ lastRefundAt: row.last_refund_at,
325
+ taxInvoiceStatus: row.tax_invoice_status ?? "pending",
326
+ taxInvoiceNumber: row.tax_invoice_number,
327
+ taxInvoiceUrl: row.tax_invoice_url,
328
+ failureCode: row.failure_code,
329
+ failureMessage: row.failure_message,
330
+ failureDetails: row.failure_details,
331
+ description: row.description,
332
+ metadata: row.metadata,
333
+ createdAt: row.created_at,
334
+ updatedAt: row.updated_at
335
+ };
336
+ }
337
+ var DrizzleTransactionRepository = class {
338
+ constructor(db) {
339
+ this.db = db;
340
+ }
341
+ async findById(id) {
342
+ const result = await this.db.select().from(paymentTransactions).where(eq(paymentTransactions.id, id)).limit(1);
343
+ return result[0] ? mapToTransaction(result[0]) : null;
344
+ }
345
+ async create(data) {
346
+ const result = await this.db.insert(paymentTransactions).values({
347
+ internal_payment_id: data.internalPaymentId,
348
+ idempotency_key: data.idempotencyKey,
349
+ user_id: data.userId,
350
+ transaction_type: data.transactionType,
351
+ status: data.status ?? "created",
352
+ amount_minor: String(data.amountMinor),
353
+ currency: data.currency,
354
+ provider: data.provider,
355
+ description: data.description,
356
+ metadata: data.metadata
357
+ }).returning();
358
+ return mapToTransaction(result[0]);
359
+ }
360
+ async update(id, data) {
361
+ const updateData = {
362
+ updated_at: /* @__PURE__ */ new Date()
363
+ };
364
+ if (data.status !== void 0) updateData.status = data.status;
365
+ if (data.providerTransactionId !== void 0)
366
+ updateData.provider_transaction_id = data.providerTransactionId;
367
+ if (data.providerAuthorizationCode !== void 0)
368
+ updateData.provider_authorization_code = data.providerAuthorizationCode;
369
+ if (data.providerMetadata !== void 0) updateData.provider_metadata = data.providerMetadata;
370
+ if (data.authorizedAt !== void 0) updateData.authorized_at = data.authorizedAt;
371
+ if (data.capturedAt !== void 0) updateData.captured_at = data.capturedAt;
372
+ if (data.voidedAt !== void 0) updateData.voided_at = data.voidedAt;
373
+ if (data.captureDeadline !== void 0) updateData.capture_deadline = data.captureDeadline;
374
+ if (data.refundedAmountMinor !== void 0)
375
+ updateData.refunded_amount_minor = String(data.refundedAmountMinor);
376
+ if (data.lastRefundAt !== void 0) updateData.last_refund_at = data.lastRefundAt;
377
+ if (data.taxInvoiceStatus !== void 0) updateData.tax_invoice_status = data.taxInvoiceStatus;
378
+ if (data.taxInvoiceNumber !== void 0) updateData.tax_invoice_number = data.taxInvoiceNumber;
379
+ if (data.taxInvoiceUrl !== void 0) updateData.tax_invoice_url = data.taxInvoiceUrl;
380
+ if (data.failureCode !== void 0) updateData.failure_code = data.failureCode;
381
+ if (data.failureMessage !== void 0) updateData.failure_message = data.failureMessage;
382
+ if (data.failureDetails !== void 0) updateData.failure_details = data.failureDetails;
383
+ const result = await this.db.update(paymentTransactions).set(updateData).where(eq(paymentTransactions.id, id)).returning();
384
+ return result[0] ? mapToTransaction(result[0]) : null;
385
+ }
386
+ async delete(id) {
387
+ const result = await this.db.delete(paymentTransactions).where(eq(paymentTransactions.id, id)).returning({ id: paymentTransactions.id });
388
+ return result.length > 0;
389
+ }
390
+ async findByInternalPaymentId(internalPaymentId) {
391
+ const result = await this.db.select().from(paymentTransactions).where(eq(paymentTransactions.internal_payment_id, internalPaymentId)).limit(1);
392
+ return result[0] ? mapToTransaction(result[0]) : null;
393
+ }
394
+ async findByIdempotencyKey(idempotencyKey) {
395
+ const result = await this.db.select().from(paymentTransactions).where(eq(paymentTransactions.idempotency_key, idempotencyKey)).limit(1);
396
+ return result[0] ? mapToTransaction(result[0]) : null;
397
+ }
398
+ async findByProviderTransactionId(provider, providerTransactionId) {
399
+ const result = await this.db.select().from(paymentTransactions).where(
400
+ and(
401
+ eq(paymentTransactions.provider, provider),
402
+ eq(paymentTransactions.provider_transaction_id, providerTransactionId)
403
+ )
404
+ ).limit(1);
405
+ return result[0] ? mapToTransaction(result[0]) : null;
406
+ }
407
+ async findMany(filter, pagination = {}) {
408
+ const { limit = 20, offset = 0 } = pagination;
409
+ const conditions = this.buildFilterConditions(filter);
410
+ const [rows, [countResult]] = await Promise.all([
411
+ this.db.select().from(paymentTransactions).where(conditions.length > 0 ? and(...conditions) : void 0).orderBy(sql`${paymentTransactions.created_at} DESC`).limit(limit).offset(offset),
412
+ this.db.select({ total: count() }).from(paymentTransactions).where(conditions.length > 0 ? and(...conditions) : void 0)
413
+ ]);
414
+ const transactions = rows.map(mapToTransaction);
415
+ return applyPagination(transactions, countResult?.total ?? 0, limit, offset);
416
+ }
417
+ async findByUserId(userId, pagination = {}) {
418
+ return this.findMany({ userId }, pagination);
419
+ }
420
+ async updateStatus(id, status, additionalData = {}) {
421
+ return this.update(id, { ...additionalData, status });
422
+ }
423
+ async incrementRefundedAmount(id, amountMinor) {
424
+ const result = await this.db.update(paymentTransactions).set({
425
+ refunded_amount_minor: sql`COALESCE(${paymentTransactions.refunded_amount_minor}, '0')::numeric + ${amountMinor}`,
426
+ last_refund_at: /* @__PURE__ */ new Date(),
427
+ updated_at: /* @__PURE__ */ new Date()
428
+ }).where(eq(paymentTransactions.id, id)).returning();
429
+ return result[0] ? mapToTransaction(result[0]) : null;
430
+ }
431
+ async findExpiredAuthorizations(beforeDate) {
432
+ const result = await this.db.select().from(paymentTransactions).where(
433
+ and(
434
+ eq(paymentTransactions.status, "authorized"),
435
+ lte(paymentTransactions.capture_deadline, beforeDate)
436
+ )
437
+ );
438
+ return result.map(mapToTransaction);
439
+ }
440
+ async countByStatus(filter = {}) {
441
+ const conditions = this.buildFilterConditions(filter);
442
+ const result = await this.db.select({
443
+ status: paymentTransactions.status,
444
+ count: count()
445
+ }).from(paymentTransactions).where(conditions.length > 0 ? and(...conditions) : void 0).groupBy(paymentTransactions.status);
446
+ const counts = {
447
+ created: 0,
448
+ pending_authorization: 0,
449
+ authorized: 0,
450
+ capturing: 0,
451
+ captured: 0,
452
+ voided: 0,
453
+ failed: 0,
454
+ expired: 0,
455
+ partially_refunded: 0,
456
+ fully_refunded: 0
457
+ };
458
+ for (const row of result) {
459
+ counts[row.status] = row.count;
460
+ }
461
+ return counts;
462
+ }
463
+ // ============================================================================
464
+ // Private Helpers
465
+ // ============================================================================
466
+ buildFilterConditions(filter) {
467
+ const conditions = [];
468
+ if (filter.userId) {
469
+ conditions.push(eq(paymentTransactions.user_id, filter.userId));
470
+ }
471
+ const statuses = normalizeArrayFilter(filter.status);
472
+ if (statuses && statuses.length > 0) {
473
+ if (statuses.length === 1) {
474
+ conditions.push(eq(paymentTransactions.status, statuses[0]));
475
+ } else {
476
+ conditions.push(inArray(paymentTransactions.status, statuses));
477
+ }
478
+ }
479
+ const providers = normalizeArrayFilter(filter.provider);
480
+ if (providers && providers.length > 0) {
481
+ if (providers.length === 1) {
482
+ conditions.push(eq(paymentTransactions.provider, providers[0]));
483
+ } else {
484
+ conditions.push(inArray(paymentTransactions.provider, providers));
485
+ }
486
+ }
487
+ const transactionTypes = normalizeArrayFilter(filter.transactionType);
488
+ if (transactionTypes && transactionTypes.length > 0) {
489
+ if (transactionTypes.length === 1) {
490
+ conditions.push(eq(paymentTransactions.transaction_type, transactionTypes[0]));
491
+ } else {
492
+ conditions.push(inArray(paymentTransactions.transaction_type, transactionTypes));
493
+ }
494
+ }
495
+ if (filter.dateRange?.from) {
496
+ conditions.push(gte(paymentTransactions.created_at, filter.dateRange.from));
497
+ }
498
+ if (filter.dateRange?.to) {
499
+ conditions.push(lte(paymentTransactions.created_at, filter.dateRange.to));
500
+ }
501
+ return conditions;
502
+ }
503
+ };
504
+
505
+ // src/repositories/payment-method.drizzle-repository.ts
506
+ import { eq as eq2, and as and2, inArray as inArray2, sql as sql2, count as count2 } from "drizzle-orm";
507
+ function mapToPaymentMethod(row) {
508
+ return {
509
+ id: row.id,
510
+ userId: row.user_id,
511
+ type: row.type,
512
+ provider: row.provider,
513
+ providerPaymentMethodId: row.provider_payment_method_id,
514
+ cardBrand: row.card_brand,
515
+ cardLast4: row.card_last4,
516
+ cardExpMonth: row.card_exp_month,
517
+ cardExpYear: row.card_exp_year,
518
+ cardBin: row.card_bin,
519
+ isDefault: row.is_default ?? false,
520
+ isActive: row.is_active ?? true,
521
+ providerMetadata: row.provider_metadata,
522
+ createdAt: row.created_at,
523
+ updatedAt: row.updated_at,
524
+ lastUsedAt: row.last_used_at
525
+ };
526
+ }
527
+ var DrizzlePaymentMethodRepository = class {
528
+ constructor(db) {
529
+ this.db = db;
530
+ }
531
+ async findById(id) {
532
+ const result = await this.db.select().from(paymentMethods).where(eq2(paymentMethods.id, id)).limit(1);
533
+ return result[0] ? mapToPaymentMethod(result[0]) : null;
534
+ }
535
+ async create(data) {
536
+ const result = await this.db.insert(paymentMethods).values({
537
+ user_id: data.userId,
538
+ type: data.type,
539
+ provider: data.provider,
540
+ provider_payment_method_id: data.providerPaymentMethodId,
541
+ card_brand: data.cardBrand,
542
+ card_last4: data.cardLast4,
543
+ card_exp_month: data.cardExpMonth,
544
+ card_exp_year: data.cardExpYear,
545
+ card_bin: data.cardBin,
546
+ is_default: data.isDefault ?? false,
547
+ provider_metadata: data.providerMetadata
548
+ }).returning();
549
+ return mapToPaymentMethod(result[0]);
550
+ }
551
+ async update(id, data) {
552
+ const updateData = {
553
+ updated_at: /* @__PURE__ */ new Date()
554
+ };
555
+ if (data.isDefault !== void 0) updateData.is_default = data.isDefault;
556
+ if (data.isActive !== void 0) updateData.is_active = data.isActive;
557
+ if (data.cardExpMonth !== void 0) updateData.card_exp_month = data.cardExpMonth;
558
+ if (data.cardExpYear !== void 0) updateData.card_exp_year = data.cardExpYear;
559
+ if (data.lastUsedAt !== void 0) updateData.last_used_at = data.lastUsedAt;
560
+ if (data.providerMetadata !== void 0) updateData.provider_metadata = data.providerMetadata;
561
+ const result = await this.db.update(paymentMethods).set(updateData).where(eq2(paymentMethods.id, id)).returning();
562
+ return result[0] ? mapToPaymentMethod(result[0]) : null;
563
+ }
564
+ async delete(id) {
565
+ const result = await this.db.delete(paymentMethods).where(eq2(paymentMethods.id, id)).returning({ id: paymentMethods.id });
566
+ return result.length > 0;
567
+ }
568
+ async findByProviderPaymentMethodId(provider, providerPaymentMethodId) {
569
+ const result = await this.db.select().from(paymentMethods).where(
570
+ and2(
571
+ eq2(paymentMethods.provider, provider),
572
+ eq2(paymentMethods.provider_payment_method_id, providerPaymentMethodId)
573
+ )
574
+ ).limit(1);
575
+ return result[0] ? mapToPaymentMethod(result[0]) : null;
576
+ }
577
+ async findByUserId(userId, filter = {}) {
578
+ const conditions = [eq2(paymentMethods.user_id, userId)];
579
+ if (filter.isActive !== void 0) {
580
+ conditions.push(eq2(paymentMethods.is_active, filter.isActive));
581
+ }
582
+ if (filter.isDefault !== void 0) {
583
+ conditions.push(eq2(paymentMethods.is_default, filter.isDefault));
584
+ }
585
+ const providers = normalizeArrayFilter(filter.provider);
586
+ if (providers && providers.length > 0) {
587
+ conditions.push(inArray2(paymentMethods.provider, providers));
588
+ }
589
+ const result = await this.db.select().from(paymentMethods).where(and2(...conditions)).orderBy(sql2`${paymentMethods.created_at} DESC`);
590
+ return result.map(mapToPaymentMethod);
591
+ }
592
+ async findDefaultForUser(userId) {
593
+ const result = await this.db.select().from(paymentMethods).where(
594
+ and2(
595
+ eq2(paymentMethods.user_id, userId),
596
+ eq2(paymentMethods.is_default, true),
597
+ eq2(paymentMethods.is_active, true)
598
+ )
599
+ ).limit(1);
600
+ return result[0] ? mapToPaymentMethod(result[0]) : null;
601
+ }
602
+ async findMany(filter, pagination = {}) {
603
+ const { limit = 20, offset = 0 } = pagination;
604
+ const conditions = this.buildFilterConditions(filter);
605
+ const [rows, [countResult]] = await Promise.all([
606
+ this.db.select().from(paymentMethods).where(conditions.length > 0 ? and2(...conditions) : void 0).orderBy(sql2`${paymentMethods.created_at} DESC`).limit(limit).offset(offset),
607
+ this.db.select({ total: count2() }).from(paymentMethods).where(conditions.length > 0 ? and2(...conditions) : void 0)
608
+ ]);
609
+ const methods = rows.map(mapToPaymentMethod);
610
+ return applyPagination(methods, countResult?.total ?? 0, limit, offset);
611
+ }
612
+ async setAsDefault(id, userId) {
613
+ await this.db.update(paymentMethods).set({ is_default: false, updated_at: /* @__PURE__ */ new Date() }).where(and2(eq2(paymentMethods.user_id, userId), eq2(paymentMethods.is_default, true)));
614
+ return this.update(id, { isDefault: true });
615
+ }
616
+ async deactivate(id) {
617
+ const result = await this.update(id, { isActive: false });
618
+ return result !== null;
619
+ }
620
+ async markAsUsed(id) {
621
+ return this.update(id, { lastUsedAt: /* @__PURE__ */ new Date() });
622
+ }
623
+ async findByCardBin(userId, cardBin) {
624
+ const result = await this.db.select().from(paymentMethods).where(
625
+ and2(
626
+ eq2(paymentMethods.user_id, userId),
627
+ eq2(paymentMethods.card_bin, cardBin),
628
+ eq2(paymentMethods.is_active, true)
629
+ )
630
+ );
631
+ return result.map(mapToPaymentMethod);
632
+ }
633
+ async countActiveForUser(userId) {
634
+ const result = await this.db.select({ count: count2() }).from(paymentMethods).where(and2(eq2(paymentMethods.user_id, userId), eq2(paymentMethods.is_active, true)));
635
+ return result[0]?.count ?? 0;
636
+ }
637
+ // ============================================================================
638
+ // Private Helpers
639
+ // ============================================================================
640
+ buildFilterConditions(filter) {
641
+ const conditions = [];
642
+ if (filter.userId) {
643
+ conditions.push(eq2(paymentMethods.user_id, filter.userId));
644
+ }
645
+ if (filter.isDefault !== void 0) {
646
+ conditions.push(eq2(paymentMethods.is_default, filter.isDefault));
647
+ }
648
+ if (filter.isActive !== void 0) {
649
+ conditions.push(eq2(paymentMethods.is_active, filter.isActive));
650
+ }
651
+ if (filter.cardBin) {
652
+ conditions.push(eq2(paymentMethods.card_bin, filter.cardBin));
653
+ }
654
+ const providers = normalizeArrayFilter(filter.provider);
655
+ if (providers && providers.length > 0) {
656
+ conditions.push(inArray2(paymentMethods.provider, providers));
657
+ }
658
+ const types = normalizeArrayFilter(filter.type);
659
+ if (types && types.length > 0) {
660
+ conditions.push(inArray2(paymentMethods.type, types));
661
+ }
662
+ return conditions;
663
+ }
664
+ };
665
+
666
+ // src/repositories/webhook-event.drizzle-repository.ts
667
+ import { eq as eq3, and as and3, gte as gte2, lte as lte2, inArray as inArray3, sql as sql3, count as count3, lt } from "drizzle-orm";
668
+ function mapToWebhookEvent(row) {
669
+ return {
670
+ id: row.id,
671
+ provider: row.provider,
672
+ providerEventId: row.provider_event_id,
673
+ eventType: row.event_type,
674
+ status: row.status,
675
+ attempts: parseInt(row.attempts ?? "0", 10),
676
+ lastAttemptAt: row.last_attempt_at,
677
+ transactionId: row.transaction_id,
678
+ payload: row.payload,
679
+ signature: row.signature,
680
+ errorMessage: row.error_message,
681
+ errorDetails: row.error_details,
682
+ receivedAt: row.received_at,
683
+ processedAt: row.processed_at,
684
+ createdAt: row.created_at
685
+ };
686
+ }
687
+ var DrizzleWebhookEventRepository = class {
688
+ constructor(db) {
689
+ this.db = db;
690
+ }
691
+ async findById(id) {
692
+ const result = await this.db.select().from(paymentWebhookEvents).where(eq3(paymentWebhookEvents.id, id)).limit(1);
693
+ return result[0] ? mapToWebhookEvent(result[0]) : null;
694
+ }
695
+ async create(data) {
696
+ const result = await this.db.insert(paymentWebhookEvents).values({
697
+ provider: data.provider,
698
+ provider_event_id: data.providerEventId,
699
+ event_type: data.eventType,
700
+ payload: data.payload,
701
+ signature: data.signature,
702
+ status: "pending"
703
+ }).returning();
704
+ return mapToWebhookEvent(result[0]);
705
+ }
706
+ async update(id, data) {
707
+ const updateData = {};
708
+ if (data.status !== void 0) updateData.status = data.status;
709
+ if (data.attempts !== void 0) updateData.attempts = String(data.attempts);
710
+ if (data.lastAttemptAt !== void 0) updateData.last_attempt_at = data.lastAttemptAt;
711
+ if (data.transactionId !== void 0) updateData.transaction_id = data.transactionId;
712
+ if (data.processedAt !== void 0) updateData.processed_at = data.processedAt;
713
+ if (data.errorMessage !== void 0) updateData.error_message = data.errorMessage;
714
+ if (data.errorDetails !== void 0) updateData.error_details = data.errorDetails;
715
+ const result = await this.db.update(paymentWebhookEvents).set(updateData).where(eq3(paymentWebhookEvents.id, id)).returning();
716
+ return result[0] ? mapToWebhookEvent(result[0]) : null;
717
+ }
718
+ async delete(id) {
719
+ const result = await this.db.delete(paymentWebhookEvents).where(eq3(paymentWebhookEvents.id, id)).returning({ id: paymentWebhookEvents.id });
720
+ return result.length > 0;
721
+ }
722
+ async findByProviderEventId(provider, providerEventId) {
723
+ const result = await this.db.select().from(paymentWebhookEvents).where(
724
+ and3(
725
+ eq3(paymentWebhookEvents.provider, provider),
726
+ eq3(paymentWebhookEvents.provider_event_id, providerEventId)
727
+ )
728
+ ).limit(1);
729
+ return result[0] ? mapToWebhookEvent(result[0]) : null;
730
+ }
731
+ async findByTransactionId(transactionId) {
732
+ const result = await this.db.select().from(paymentWebhookEvents).where(eq3(paymentWebhookEvents.transaction_id, transactionId)).orderBy(sql3`${paymentWebhookEvents.received_at} DESC`);
733
+ return result.map(mapToWebhookEvent);
734
+ }
735
+ async findMany(filter, pagination = {}) {
736
+ const { limit = 20, offset = 0 } = pagination;
737
+ const conditions = this.buildFilterConditions(filter);
738
+ const [rows, [countResult]] = await Promise.all([
739
+ this.db.select().from(paymentWebhookEvents).where(conditions.length > 0 ? and3(...conditions) : void 0).orderBy(sql3`${paymentWebhookEvents.received_at} DESC`).limit(limit).offset(offset),
740
+ this.db.select({ total: count3() }).from(paymentWebhookEvents).where(conditions.length > 0 ? and3(...conditions) : void 0)
741
+ ]);
742
+ const events = rows.map(mapToWebhookEvent);
743
+ return applyPagination(events, countResult?.total ?? 0, limit, offset);
744
+ }
745
+ async findFailedForRetry(maxAttempts, olderThan) {
746
+ const conditions = [
747
+ eq3(paymentWebhookEvents.status, "failed"),
748
+ lt(sql3`CAST(${paymentWebhookEvents.attempts} AS INTEGER)`, maxAttempts)
749
+ ];
750
+ if (olderThan) {
751
+ conditions.push(lt(paymentWebhookEvents.last_attempt_at, olderThan));
752
+ }
753
+ const result = await this.db.select().from(paymentWebhookEvents).where(and3(...conditions)).orderBy(sql3`${paymentWebhookEvents.last_attempt_at} ASC`).limit(100);
754
+ return result.map(mapToWebhookEvent);
755
+ }
756
+ async findPending(limit = 100) {
757
+ const result = await this.db.select().from(paymentWebhookEvents).where(eq3(paymentWebhookEvents.status, "pending")).orderBy(sql3`${paymentWebhookEvents.received_at} ASC`).limit(limit);
758
+ return result.map(mapToWebhookEvent);
759
+ }
760
+ async markAsProcessing(id) {
761
+ const result = await this.db.update(paymentWebhookEvents).set({
762
+ status: "processing",
763
+ last_attempt_at: /* @__PURE__ */ new Date(),
764
+ attempts: sql3`CAST(${paymentWebhookEvents.attempts} AS INTEGER) + 1`
765
+ }).where(and3(eq3(paymentWebhookEvents.id, id), eq3(paymentWebhookEvents.status, "pending"))).returning({ id: paymentWebhookEvents.id });
766
+ return result.length > 0;
767
+ }
768
+ async markAsProcessed(id, transactionId) {
769
+ return this.update(id, {
770
+ status: "processed",
771
+ processedAt: /* @__PURE__ */ new Date(),
772
+ transactionId
773
+ });
774
+ }
775
+ async markAsFailed(id, errorMessage, errorDetails) {
776
+ return this.update(id, {
777
+ status: "failed",
778
+ errorMessage,
779
+ errorDetails
780
+ });
781
+ }
782
+ async incrementAttempts(id) {
783
+ const result = await this.db.update(paymentWebhookEvents).set({
784
+ attempts: sql3`CAST(${paymentWebhookEvents.attempts} AS INTEGER) + 1`,
785
+ last_attempt_at: /* @__PURE__ */ new Date()
786
+ }).where(eq3(paymentWebhookEvents.id, id)).returning();
787
+ return result[0] ? mapToWebhookEvent(result[0]) : null;
788
+ }
789
+ async isAlreadyProcessed(provider, providerEventId) {
790
+ const result = await this.db.select({ status: paymentWebhookEvents.status }).from(paymentWebhookEvents).where(
791
+ and3(
792
+ eq3(paymentWebhookEvents.provider, provider),
793
+ eq3(paymentWebhookEvents.provider_event_id, providerEventId),
794
+ eq3(paymentWebhookEvents.status, "processed")
795
+ )
796
+ ).limit(1);
797
+ return result.length > 0;
798
+ }
799
+ async countByStatus(filter = {}) {
800
+ const conditions = this.buildFilterConditions(filter);
801
+ const result = await this.db.select({
802
+ status: paymentWebhookEvents.status,
803
+ count: count3()
804
+ }).from(paymentWebhookEvents).where(conditions.length > 0 ? and3(...conditions) : void 0).groupBy(paymentWebhookEvents.status);
805
+ const counts = {
806
+ pending: 0,
807
+ processing: 0,
808
+ processed: 0,
809
+ failed: 0,
810
+ ignored: 0
811
+ };
812
+ for (const row of result) {
813
+ counts[row.status] = row.count;
814
+ }
815
+ return counts;
816
+ }
817
+ // ============================================================================
818
+ // Private Helpers
819
+ // ============================================================================
820
+ buildFilterConditions(filter) {
821
+ const conditions = [];
822
+ const providers = normalizeArrayFilter(filter.provider);
823
+ if (providers && providers.length > 0) {
824
+ conditions.push(inArray3(paymentWebhookEvents.provider, providers));
825
+ }
826
+ const eventTypes = normalizeArrayFilter(filter.eventType);
827
+ if (eventTypes && eventTypes.length > 0) {
828
+ conditions.push(inArray3(paymentWebhookEvents.event_type, eventTypes));
829
+ }
830
+ const statuses = normalizeArrayFilter(filter.status);
831
+ if (statuses && statuses.length > 0) {
832
+ conditions.push(inArray3(paymentWebhookEvents.status, statuses));
833
+ }
834
+ if (filter.transactionId) {
835
+ conditions.push(eq3(paymentWebhookEvents.transaction_id, filter.transactionId));
836
+ }
837
+ if (filter.dateRange?.from) {
838
+ conditions.push(gte2(paymentWebhookEvents.received_at, filter.dateRange.from));
839
+ }
840
+ if (filter.dateRange?.to) {
841
+ conditions.push(lte2(paymentWebhookEvents.received_at, filter.dateRange.to));
842
+ }
843
+ return conditions;
844
+ }
845
+ };
846
+
847
+ // src/repositories/audit-log.drizzle-repository.ts
848
+ import { eq as eq4, and as and4, inArray as inArray4, sql as sql4, count as count4, gte as gte3, lte as lte3 } from "drizzle-orm";
849
+ function mapToAuditLogEntry(row) {
850
+ return {
851
+ id: row.id,
852
+ transactionId: row.transaction_id,
853
+ action: row.action,
854
+ previousState: row.previous_state,
855
+ newState: row.new_state,
856
+ triggeredBy: row.triggered_by,
857
+ triggeredById: row.triggered_by_id,
858
+ ipAddress: row.ip_address,
859
+ userAgent: row.user_agent,
860
+ correlationId: row.correlation_id,
861
+ metadata: row.metadata,
862
+ createdAt: row.created_at
863
+ };
864
+ }
865
+ var DrizzleAuditLogRepository = class {
866
+ constructor(db) {
867
+ this.db = db;
868
+ }
869
+ async findById(id) {
870
+ const result = await this.db.select().from(paymentAuditLog).where(eq4(paymentAuditLog.id, id)).limit(1);
871
+ return result[0] ? mapToAuditLogEntry(result[0]) : null;
872
+ }
873
+ async create(data) {
874
+ const result = await this.db.insert(paymentAuditLog).values({
875
+ transaction_id: data.transactionId,
876
+ action: data.action,
877
+ previous_state: data.previousState,
878
+ new_state: data.newState,
879
+ triggered_by: data.triggeredBy,
880
+ triggered_by_id: data.triggeredById,
881
+ ip_address: data.ipAddress,
882
+ user_agent: data.userAgent,
883
+ correlation_id: data.correlationId,
884
+ metadata: data.metadata
885
+ }).returning();
886
+ return mapToAuditLogEntry(result[0]);
887
+ }
888
+ async createMany(entries) {
889
+ if (entries.length === 0) return [];
890
+ const values = entries.map((data) => ({
891
+ transaction_id: data.transactionId,
892
+ action: data.action,
893
+ previous_state: data.previousState,
894
+ new_state: data.newState,
895
+ triggered_by: data.triggeredBy,
896
+ triggered_by_id: data.triggeredById,
897
+ ip_address: data.ipAddress,
898
+ user_agent: data.userAgent,
899
+ correlation_id: data.correlationId,
900
+ metadata: data.metadata
901
+ }));
902
+ const result = await this.db.insert(paymentAuditLog).values(values).returning();
903
+ return result.map(mapToAuditLogEntry);
904
+ }
905
+ async findByTransactionId(transactionId, pagination = {}) {
906
+ const { limit = 100, offset = 0 } = pagination;
907
+ const [rows, [countResult]] = await Promise.all([
908
+ this.db.select().from(paymentAuditLog).where(eq4(paymentAuditLog.transaction_id, transactionId)).orderBy(sql4`${paymentAuditLog.created_at} ASC`).limit(limit).offset(offset),
909
+ this.db.select({ total: count4() }).from(paymentAuditLog).where(eq4(paymentAuditLog.transaction_id, transactionId))
910
+ ]);
911
+ const entries = rows.map(mapToAuditLogEntry);
912
+ return applyPagination(entries, countResult?.total ?? 0, limit, offset);
913
+ }
914
+ async findMany(filter, pagination = {}) {
915
+ const { limit = 50, offset = 0 } = pagination;
916
+ const conditions = this.buildFilterConditions(filter);
917
+ const [rows, [countResult]] = await Promise.all([
918
+ this.db.select().from(paymentAuditLog).where(conditions.length > 0 ? and4(...conditions) : void 0).orderBy(sql4`${paymentAuditLog.created_at} DESC`).limit(limit).offset(offset),
919
+ this.db.select({ total: count4() }).from(paymentAuditLog).where(conditions.length > 0 ? and4(...conditions) : void 0)
920
+ ]);
921
+ const entries = rows.map(mapToAuditLogEntry);
922
+ return applyPagination(entries, countResult?.total ?? 0, limit, offset);
923
+ }
924
+ async findByCorrelationId(correlationId) {
925
+ const result = await this.db.select().from(paymentAuditLog).where(eq4(paymentAuditLog.correlation_id, correlationId)).orderBy(sql4`${paymentAuditLog.created_at} ASC`);
926
+ return result.map(mapToAuditLogEntry);
927
+ }
928
+ async getTransactionHistory(transactionId) {
929
+ const result = await this.db.select().from(paymentAuditLog).where(eq4(paymentAuditLog.transaction_id, transactionId)).orderBy(sql4`${paymentAuditLog.created_at} ASC`);
930
+ return result.map(mapToAuditLogEntry);
931
+ }
932
+ async countByAction(filter = {}) {
933
+ const conditions = this.buildFilterConditions(filter);
934
+ const result = await this.db.select({
935
+ action: paymentAuditLog.action,
936
+ count: count4()
937
+ }).from(paymentAuditLog).where(conditions.length > 0 ? and4(...conditions) : void 0).groupBy(paymentAuditLog.action);
938
+ const counts = {
939
+ created: 0,
940
+ status_changed: 0,
941
+ authorized: 0,
942
+ captured: 0,
943
+ voided: 0,
944
+ refund_initiated: 0,
945
+ refund_completed: 0,
946
+ webhook_received: 0,
947
+ webhook_processed: 0,
948
+ error_occurred: 0,
949
+ retry_attempted: 0,
950
+ manual_intervention: 0
951
+ };
952
+ for (const row of result) {
953
+ counts[row.action] = row.count;
954
+ }
955
+ return counts;
956
+ }
957
+ // ============================================================================
958
+ // Private Helpers
959
+ // ============================================================================
960
+ buildFilterConditions(filter) {
961
+ const conditions = [];
962
+ if (filter.transactionId) {
963
+ conditions.push(eq4(paymentAuditLog.transaction_id, filter.transactionId));
964
+ }
965
+ if (filter.correlationId) {
966
+ conditions.push(eq4(paymentAuditLog.correlation_id, filter.correlationId));
967
+ }
968
+ if (filter.triggeredById) {
969
+ conditions.push(eq4(paymentAuditLog.triggered_by_id, filter.triggeredById));
970
+ }
971
+ const actions = normalizeArrayFilter(filter.action);
972
+ if (actions && actions.length > 0) {
973
+ conditions.push(inArray4(paymentAuditLog.action, actions));
974
+ }
975
+ const triggers = normalizeArrayFilter(filter.triggeredBy);
976
+ if (triggers && triggers.length > 0) {
977
+ conditions.push(inArray4(paymentAuditLog.triggered_by, triggers));
978
+ }
979
+ if (filter.dateRange?.from) {
980
+ conditions.push(gte3(paymentAuditLog.created_at, filter.dateRange.from));
981
+ }
982
+ if (filter.dateRange?.to) {
983
+ conditions.push(lte3(paymentAuditLog.created_at, filter.dateRange.to));
984
+ }
985
+ return conditions;
986
+ }
987
+ };
988
+
989
+ // src/repositories/provider-health.drizzle-repository.ts
990
+ import { eq as eq5, or, sql as sql5 } from "drizzle-orm";
991
+ function mapToProviderHealth(row) {
992
+ return {
993
+ id: row.id,
994
+ provider: row.provider,
995
+ circuitState: row.circuit_state,
996
+ failureCount: parseInt(row.failure_count ?? "0", 10),
997
+ successCount: parseInt(row.success_count ?? "0", 10),
998
+ lastFailureAt: row.last_failure_at,
999
+ lastSuccessAt: row.last_success_at,
1000
+ circuitOpenedAt: row.circuit_opened_at,
1001
+ nextRetryAt: row.next_retry_at,
1002
+ avgLatencyMs: row.avg_latency_ms ? parseNumeric(row.avg_latency_ms) : null,
1003
+ errorRate: row.error_rate ? parseNumeric(row.error_rate) : null,
1004
+ requestCountWindow: parseInt(row.request_count_window ?? "0", 10),
1005
+ lastHealthCheckAt: row.last_health_check_at,
1006
+ healthCheckResult: row.health_check_result,
1007
+ createdAt: row.created_at,
1008
+ updatedAt: row.updated_at
1009
+ };
1010
+ }
1011
+ var DrizzleProviderHealthRepository = class {
1012
+ constructor(db) {
1013
+ this.db = db;
1014
+ }
1015
+ async findByProvider(provider) {
1016
+ const result = await this.db.select().from(providerHealth).where(eq5(providerHealth.provider, provider)).limit(1);
1017
+ return result[0] ? mapToProviderHealth(result[0]) : null;
1018
+ }
1019
+ async getOrCreate(provider) {
1020
+ const existing = await this.findByProvider(provider);
1021
+ if (existing) return existing;
1022
+ const result = await this.db.insert(providerHealth).values({
1023
+ provider,
1024
+ circuit_state: "closed"
1025
+ }).returning();
1026
+ return mapToProviderHealth(result[0]);
1027
+ }
1028
+ async update(provider, data) {
1029
+ const updateData = {
1030
+ updated_at: /* @__PURE__ */ new Date()
1031
+ };
1032
+ if (data.circuitState !== void 0) updateData.circuit_state = data.circuitState;
1033
+ if (data.failureCount !== void 0) updateData.failure_count = String(data.failureCount);
1034
+ if (data.successCount !== void 0) updateData.success_count = String(data.successCount);
1035
+ if (data.lastFailureAt !== void 0) updateData.last_failure_at = data.lastFailureAt;
1036
+ if (data.lastSuccessAt !== void 0) updateData.last_success_at = data.lastSuccessAt;
1037
+ if (data.circuitOpenedAt !== void 0) updateData.circuit_opened_at = data.circuitOpenedAt;
1038
+ if (data.nextRetryAt !== void 0) updateData.next_retry_at = data.nextRetryAt;
1039
+ if (data.avgLatencyMs !== void 0) updateData.avg_latency_ms = String(data.avgLatencyMs);
1040
+ if (data.errorRate !== void 0) updateData.error_rate = String(data.errorRate);
1041
+ if (data.requestCountWindow !== void 0)
1042
+ updateData.request_count_window = String(data.requestCountWindow);
1043
+ if (data.lastHealthCheckAt !== void 0)
1044
+ updateData.last_health_check_at = data.lastHealthCheckAt;
1045
+ if (data.healthCheckResult !== void 0)
1046
+ updateData.health_check_result = data.healthCheckResult;
1047
+ const result = await this.db.update(providerHealth).set(updateData).where(eq5(providerHealth.provider, provider)).returning();
1048
+ return result[0] ? mapToProviderHealth(result[0]) : null;
1049
+ }
1050
+ async findAll() {
1051
+ const result = await this.db.select().from(providerHealth).orderBy(sql5`${providerHealth.provider} ASC`);
1052
+ return result.map(mapToProviderHealth);
1053
+ }
1054
+ async recordSuccess(provider, latencyMs) {
1055
+ await this.getOrCreate(provider);
1056
+ await this.db.update(providerHealth).set({
1057
+ success_count: sql5`CAST(${providerHealth.success_count} AS INTEGER) + 1`,
1058
+ request_count_window: sql5`CAST(${providerHealth.request_count_window} AS INTEGER) + 1`,
1059
+ last_success_at: /* @__PURE__ */ new Date(),
1060
+ avg_latency_ms: sql5`CASE
1061
+ WHEN ${providerHealth.avg_latency_ms} IS NULL THEN ${latencyMs}
1062
+ ELSE (CAST(${providerHealth.avg_latency_ms} AS DECIMAL) * 0.9 + ${latencyMs} * 0.1)
1063
+ END`,
1064
+ updated_at: /* @__PURE__ */ new Date()
1065
+ }).where(eq5(providerHealth.provider, provider));
1066
+ }
1067
+ async recordFailure(provider, error) {
1068
+ await this.getOrCreate(provider);
1069
+ const updateData = {
1070
+ last_failure_at: /* @__PURE__ */ new Date(),
1071
+ updated_at: /* @__PURE__ */ new Date()
1072
+ };
1073
+ if (error) {
1074
+ updateData.health_check_result = { healthy: false, error };
1075
+ }
1076
+ await this.db.update(providerHealth).set({
1077
+ ...updateData,
1078
+ failure_count: sql5`CAST(${providerHealth.failure_count} AS INTEGER) + 1`,
1079
+ request_count_window: sql5`CAST(${providerHealth.request_count_window} AS INTEGER) + 1`
1080
+ }).where(eq5(providerHealth.provider, provider));
1081
+ }
1082
+ async openCircuit(provider, retryAfterMs) {
1083
+ const now = /* @__PURE__ */ new Date();
1084
+ const nextRetry = new Date(now.getTime() + retryAfterMs);
1085
+ await this.getOrCreate(provider);
1086
+ await this.db.update(providerHealth).set({
1087
+ circuit_state: "open",
1088
+ circuit_opened_at: now,
1089
+ next_retry_at: nextRetry,
1090
+ updated_at: now
1091
+ }).where(eq5(providerHealth.provider, provider));
1092
+ }
1093
+ async closeCircuit(provider) {
1094
+ await this.db.update(providerHealth).set({
1095
+ circuit_state: "closed",
1096
+ circuit_opened_at: null,
1097
+ next_retry_at: null,
1098
+ failure_count: "0",
1099
+ updated_at: /* @__PURE__ */ new Date()
1100
+ }).where(eq5(providerHealth.provider, provider));
1101
+ }
1102
+ async halfOpenCircuit(provider) {
1103
+ await this.db.update(providerHealth).set({
1104
+ circuit_state: "half_open",
1105
+ updated_at: /* @__PURE__ */ new Date()
1106
+ }).where(eq5(providerHealth.provider, provider));
1107
+ }
1108
+ async updateHealthCheck(provider, result) {
1109
+ await this.getOrCreate(provider);
1110
+ await this.db.update(providerHealth).set({
1111
+ last_health_check_at: /* @__PURE__ */ new Date(),
1112
+ health_check_result: result,
1113
+ updated_at: /* @__PURE__ */ new Date()
1114
+ }).where(eq5(providerHealth.provider, provider));
1115
+ }
1116
+ async findOpenCircuits() {
1117
+ const result = await this.db.select().from(providerHealth).where(eq5(providerHealth.circuit_state, "open"));
1118
+ return result.map(mapToProviderHealth);
1119
+ }
1120
+ async findReadyForRetry() {
1121
+ const now = /* @__PURE__ */ new Date();
1122
+ const result = await this.db.select().from(providerHealth).where(
1123
+ or(
1124
+ eq5(providerHealth.circuit_state, "half_open"),
1125
+ sql5`${providerHealth.circuit_state} = 'open' AND ${providerHealth.next_retry_at} <= ${now}`
1126
+ )
1127
+ );
1128
+ return result.map(mapToProviderHealth);
1129
+ }
1130
+ async resetStats(provider) {
1131
+ await this.db.update(providerHealth).set({
1132
+ failure_count: "0",
1133
+ success_count: "0",
1134
+ request_count_window: "0",
1135
+ avg_latency_ms: null,
1136
+ error_rate: null,
1137
+ updated_at: /* @__PURE__ */ new Date()
1138
+ }).where(eq5(providerHealth.provider, provider));
1139
+ }
1140
+ async updateErrorRate(provider) {
1141
+ const health = await this.findByProvider(provider);
1142
+ if (!health || health.requestCountWindow === 0) return 0;
1143
+ const errorRate = health.failureCount / health.requestCountWindow;
1144
+ await this.db.update(providerHealth).set({
1145
+ error_rate: String(errorRate),
1146
+ updated_at: /* @__PURE__ */ new Date()
1147
+ }).where(eq5(providerHealth.provider, provider));
1148
+ return errorRate;
1149
+ }
1150
+ };
1151
+
1152
+ // src/storage/drizzle-circuit-breaker-storage.ts
1153
+ var DrizzleCircuitBreakerStorage = class {
1154
+ repo;
1155
+ constructor(providerHealthRepository) {
1156
+ this.repo = providerHealthRepository;
1157
+ }
1158
+ async getState(provider) {
1159
+ try {
1160
+ const health = await this.repo.findByProvider(provider);
1161
+ if (!health) return null;
1162
+ return this.mapToStateRecord(provider, health);
1163
+ } catch (error) {
1164
+ console.error(`[DrizzleCircuitBreakerStorage] Failed to get state for ${provider}:`, error);
1165
+ return null;
1166
+ }
1167
+ }
1168
+ async setState(provider, state) {
1169
+ try {
1170
+ await this.repo.getOrCreate(provider);
1171
+ await this.repo.update(provider, {
1172
+ circuitState: state.state,
1173
+ failureCount: state.failureCount,
1174
+ successCount: state.successCount,
1175
+ lastFailureAt: state.lastFailure ?? void 0,
1176
+ circuitOpenedAt: state.openedAt ?? void 0,
1177
+ nextRetryAt: state.nextRetryAt ?? void 0
1178
+ });
1179
+ } catch (error) {
1180
+ console.error(`[DrizzleCircuitBreakerStorage] Failed to set state for ${provider}:`, error);
1181
+ throw error;
1182
+ }
1183
+ }
1184
+ async getAllStates() {
1185
+ try {
1186
+ const allHealth = await this.repo.findAll();
1187
+ const states = /* @__PURE__ */ new Map();
1188
+ for (const health of allHealth) {
1189
+ const provider = health.provider;
1190
+ states.set(provider, this.mapToStateRecord(provider, health));
1191
+ }
1192
+ return states;
1193
+ } catch (error) {
1194
+ console.error("[DrizzleCircuitBreakerStorage] Failed to get all states:", error);
1195
+ return /* @__PURE__ */ new Map();
1196
+ }
1197
+ }
1198
+ async deleteState(provider) {
1199
+ try {
1200
+ await this.repo.resetStats(provider);
1201
+ await this.repo.closeCircuit(provider);
1202
+ } catch (error) {
1203
+ console.error(`[DrizzleCircuitBreakerStorage] Failed to delete state for ${provider}:`, error);
1204
+ throw error;
1205
+ }
1206
+ }
1207
+ async getOpenCircuits() {
1208
+ try {
1209
+ const openHealth = await this.repo.findOpenCircuits();
1210
+ return openHealth.map((h) => h.provider);
1211
+ } catch (error) {
1212
+ console.error("[DrizzleCircuitBreakerStorage] Failed to get open circuits:", error);
1213
+ return [];
1214
+ }
1215
+ }
1216
+ async isHealthy() {
1217
+ try {
1218
+ await this.repo.findAll();
1219
+ return true;
1220
+ } catch (error) {
1221
+ console.error("[DrizzleCircuitBreakerStorage] Health check failed:", error);
1222
+ return false;
1223
+ }
1224
+ }
1225
+ // ==========================================================================
1226
+ // Helper Methods
1227
+ // ==========================================================================
1228
+ mapToStateRecord(provider, health) {
1229
+ return {
1230
+ provider,
1231
+ state: health.circuitState,
1232
+ failureCount: health.failureCount,
1233
+ successCount: health.successCount,
1234
+ lastFailure: health.lastFailureAt,
1235
+ openedAt: health.circuitOpenedAt,
1236
+ nextRetryAt: health.nextRetryAt
1237
+ };
1238
+ }
1239
+ };
1240
+ function createDrizzleCircuitBreakerStorage(providerHealthRepo) {
1241
+ return new DrizzleCircuitBreakerStorage(providerHealthRepo);
1242
+ }
1243
+
1244
+ // src/factory.ts
1245
+ import { createPaymentServices } from "@nehorai/payments/factory";
1246
+ function createDrizzleRepositories(db) {
1247
+ return {
1248
+ transactions: new DrizzleTransactionRepository(db),
1249
+ paymentMethods: new DrizzlePaymentMethodRepository(db),
1250
+ webhookEvents: new DrizzleWebhookEventRepository(db),
1251
+ auditLog: new DrizzleAuditLogRepository(db),
1252
+ providerHealth: new DrizzleProviderHealthRepository(db)
1253
+ };
1254
+ }
1255
+ function createDrizzlePaymentServices(db, options) {
1256
+ const repositories = createDrizzleRepositories(db);
1257
+ const circuitBreakerStorage = new DrizzleCircuitBreakerStorage(repositories.providerHealth);
1258
+ return createPaymentServices({
1259
+ config: options.config,
1260
+ providers: options.providers,
1261
+ webhookHandlers: options.webhookHandlers,
1262
+ repositories,
1263
+ circuitBreakerStorage,
1264
+ circuitBreaker: options.circuitBreaker,
1265
+ routingRules: options.routingRules
1266
+ });
1267
+ }
1268
+ export {
1269
+ DrizzleAuditLogRepository,
1270
+ DrizzleCircuitBreakerStorage,
1271
+ DrizzlePaymentMethodRepository,
1272
+ DrizzleProviderHealthRepository,
1273
+ DrizzleTransactionRepository,
1274
+ DrizzleWebhookEventRepository,
1275
+ applyPagination,
1276
+ createDrizzleCircuitBreakerStorage,
1277
+ createDrizzlePaymentServices,
1278
+ createDrizzleRepositories,
1279
+ normalizeArrayFilter,
1280
+ parseNumeric,
1281
+ paymentAuditLog,
1282
+ paymentMethods,
1283
+ paymentTransactions,
1284
+ paymentWebhookEvents,
1285
+ providerHealth,
1286
+ toCamelCase,
1287
+ toSnakeCase
1288
+ };
1289
+ //# sourceMappingURL=index.js.map