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