@djangocfg/ext-payments 1.0.19 → 1.0.21

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.
@@ -0,0 +1,1681 @@
1
+ import useSWR, { useSWRConfig } from 'swr';
2
+ import { createConsola, consola } from 'consola';
3
+ import { z } from 'zod';
4
+ import pRetry, { AbortError } from 'p-retry';
5
+
6
+ var BalanceSchema = z.object({
7
+ balance_usd: z.string(),
8
+ balance_display: z.string(),
9
+ total_deposited: z.string(),
10
+ total_withdrawn: z.string(),
11
+ last_transaction_at: z.string().datetime({ offset: true }).nullable()
12
+ });
13
+
14
+ // src/api/generated/ext_payments/enums.ts
15
+ var PaymentDetailStatus = /* @__PURE__ */ ((PaymentDetailStatus2) => {
16
+ PaymentDetailStatus2["PENDING"] = "pending";
17
+ PaymentDetailStatus2["CONFIRMING"] = "confirming";
18
+ PaymentDetailStatus2["CONFIRMED"] = "confirmed";
19
+ PaymentDetailStatus2["COMPLETED"] = "completed";
20
+ PaymentDetailStatus2["PARTIALLY_PAID"] = "partially_paid";
21
+ PaymentDetailStatus2["FAILED"] = "failed";
22
+ PaymentDetailStatus2["EXPIRED"] = "expired";
23
+ PaymentDetailStatus2["CANCELLED"] = "cancelled";
24
+ return PaymentDetailStatus2;
25
+ })(PaymentDetailStatus || {});
26
+ var PaymentListStatus = /* @__PURE__ */ ((PaymentListStatus2) => {
27
+ PaymentListStatus2["PENDING"] = "pending";
28
+ PaymentListStatus2["CONFIRMING"] = "confirming";
29
+ PaymentListStatus2["CONFIRMED"] = "confirmed";
30
+ PaymentListStatus2["COMPLETED"] = "completed";
31
+ PaymentListStatus2["PARTIALLY_PAID"] = "partially_paid";
32
+ PaymentListStatus2["FAILED"] = "failed";
33
+ PaymentListStatus2["EXPIRED"] = "expired";
34
+ PaymentListStatus2["CANCELLED"] = "cancelled";
35
+ return PaymentListStatus2;
36
+ })(PaymentListStatus || {});
37
+ var TransactionTransactionType = /* @__PURE__ */ ((TransactionTransactionType2) => {
38
+ TransactionTransactionType2["DEPOSIT"] = "deposit";
39
+ TransactionTransactionType2["WITHDRAWAL"] = "withdrawal";
40
+ TransactionTransactionType2["PAYMENT"] = "payment";
41
+ TransactionTransactionType2["REFUND"] = "refund";
42
+ TransactionTransactionType2["FEE"] = "fee";
43
+ TransactionTransactionType2["BONUS"] = "bonus";
44
+ TransactionTransactionType2["ADJUSTMENT"] = "adjustment";
45
+ return TransactionTransactionType2;
46
+ })(TransactionTransactionType || {});
47
+ var WithdrawalDetailStatus = /* @__PURE__ */ ((WithdrawalDetailStatus2) => {
48
+ WithdrawalDetailStatus2["PENDING"] = "pending";
49
+ WithdrawalDetailStatus2["APPROVED"] = "approved";
50
+ WithdrawalDetailStatus2["PROCESSING"] = "processing";
51
+ WithdrawalDetailStatus2["COMPLETED"] = "completed";
52
+ WithdrawalDetailStatus2["REJECTED"] = "rejected";
53
+ WithdrawalDetailStatus2["CANCELLED"] = "cancelled";
54
+ return WithdrawalDetailStatus2;
55
+ })(WithdrawalDetailStatus || {});
56
+ var WithdrawalListStatus = /* @__PURE__ */ ((WithdrawalListStatus2) => {
57
+ WithdrawalListStatus2["PENDING"] = "pending";
58
+ WithdrawalListStatus2["APPROVED"] = "approved";
59
+ WithdrawalListStatus2["PROCESSING"] = "processing";
60
+ WithdrawalListStatus2["COMPLETED"] = "completed";
61
+ WithdrawalListStatus2["REJECTED"] = "rejected";
62
+ WithdrawalListStatus2["CANCELLED"] = "cancelled";
63
+ return WithdrawalListStatus2;
64
+ })(WithdrawalListStatus || {});
65
+
66
+ // src/api/generated/ext_payments/_utils/schemas/PaymentList.schema.ts
67
+ var PaymentListSchema = z.object({
68
+ id: z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),
69
+ internal_payment_id: z.string(),
70
+ amount_usd: z.string(),
71
+ currency_code: z.string(),
72
+ currency_token: z.string(),
73
+ status: z.nativeEnum(PaymentListStatus),
74
+ status_display: z.string(),
75
+ created_at: z.string().datetime({ offset: true }),
76
+ completed_at: z.string().datetime({ offset: true }).nullable()
77
+ });
78
+
79
+ // src/api/generated/ext_payments/_utils/schemas/PaginatedPaymentListList.schema.ts
80
+ var PaginatedPaymentListListSchema = z.object({
81
+ count: z.int(),
82
+ page: z.int(),
83
+ pages: z.int(),
84
+ page_size: z.int(),
85
+ has_next: z.boolean(),
86
+ has_previous: z.boolean(),
87
+ next_page: z.int().nullable().optional(),
88
+ previous_page: z.int().nullable().optional(),
89
+ results: z.array(PaymentListSchema)
90
+ });
91
+ var WithdrawalListSchema = z.object({
92
+ id: z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),
93
+ internal_withdrawal_id: z.string(),
94
+ amount_usd: z.string(),
95
+ final_amount_usd: z.string(),
96
+ currency_code: z.string(),
97
+ currency_token: z.string(),
98
+ status: z.nativeEnum(WithdrawalListStatus),
99
+ status_display: z.string(),
100
+ created_at: z.string().datetime({ offset: true }),
101
+ completed_at: z.string().datetime({ offset: true }).nullable()
102
+ });
103
+
104
+ // src/api/generated/ext_payments/_utils/schemas/PaginatedWithdrawalListList.schema.ts
105
+ var PaginatedWithdrawalListListSchema = z.object({
106
+ count: z.int(),
107
+ page: z.int(),
108
+ pages: z.int(),
109
+ page_size: z.int(),
110
+ has_next: z.boolean(),
111
+ has_previous: z.boolean(),
112
+ next_page: z.int().nullable().optional(),
113
+ previous_page: z.int().nullable().optional(),
114
+ results: z.array(WithdrawalListSchema)
115
+ });
116
+ var PaymentDetailSchema = z.object({
117
+ id: z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),
118
+ internal_payment_id: z.string(),
119
+ amount_usd: z.string(),
120
+ currency_code: z.string(),
121
+ currency_name: z.string(),
122
+ currency_token: z.string(),
123
+ currency_network: z.string(),
124
+ pay_amount: z.string().nullable(),
125
+ actual_amount: z.string().nullable(),
126
+ actual_amount_usd: z.string().nullable(),
127
+ status: z.nativeEnum(PaymentDetailStatus),
128
+ status_display: z.string(),
129
+ pay_address: z.string().nullable(),
130
+ qr_code_url: z.string().nullable(),
131
+ payment_url: z.union([z.url(), z.literal("")]).nullable(),
132
+ transaction_hash: z.string().nullable(),
133
+ explorer_link: z.string().nullable(),
134
+ confirmations_count: z.int(),
135
+ expires_at: z.string().datetime({ offset: true }).nullable(),
136
+ completed_at: z.string().datetime({ offset: true }).nullable(),
137
+ created_at: z.string().datetime({ offset: true }),
138
+ is_completed: z.boolean(),
139
+ is_failed: z.boolean(),
140
+ is_expired: z.boolean(),
141
+ description: z.string()
142
+ });
143
+
144
+ // src/api/generated/ext_payments/_utils/schemas/PaymentCreateResponse.schema.ts
145
+ var PaymentCreateResponseSchema = z.object({
146
+ success: z.boolean(),
147
+ payment: PaymentDetailSchema,
148
+ qr_code_url: z.union([z.url(), z.literal("")]).nullable()
149
+ });
150
+ var WithdrawalDetailSchema = z.object({
151
+ id: z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),
152
+ internal_withdrawal_id: z.string(),
153
+ amount_usd: z.string(),
154
+ currency_code: z.string(),
155
+ currency_name: z.string(),
156
+ currency_token: z.string(),
157
+ currency_network: z.string(),
158
+ wallet_address: z.string(),
159
+ network_fee_usd: z.string(),
160
+ service_fee_usd: z.string(),
161
+ total_fee_usd: z.string(),
162
+ final_amount_usd: z.string(),
163
+ crypto_amount: z.string().nullable(),
164
+ status: z.nativeEnum(WithdrawalDetailStatus),
165
+ status_display: z.string(),
166
+ transaction_hash: z.string().nullable(),
167
+ explorer_link: z.string().nullable(),
168
+ admin_notes: z.string(),
169
+ created_at: z.string().datetime({ offset: true }),
170
+ approved_at: z.string().datetime({ offset: true }).nullable(),
171
+ completed_at: z.string().datetime({ offset: true }).nullable(),
172
+ rejected_at: z.string().datetime({ offset: true }).nullable(),
173
+ cancelled_at: z.string().datetime({ offset: true }).nullable()
174
+ });
175
+
176
+ // src/api/generated/ext_payments/_utils/schemas/WithdrawalCancelResponse.schema.ts
177
+ var WithdrawalCancelResponseSchema = z.object({
178
+ success: z.boolean(),
179
+ withdrawal: WithdrawalDetailSchema,
180
+ message: z.string()
181
+ });
182
+ var WithdrawalCreateResponseSchema = z.object({
183
+ success: z.boolean(),
184
+ withdrawal: WithdrawalDetailSchema,
185
+ message: z.string()
186
+ });
187
+
188
+ // src/api/generated/ext_payments/ext_payments__payments/client.ts
189
+ var ExtPaymentsPayments = class {
190
+ client;
191
+ constructor(client) {
192
+ this.client = client;
193
+ }
194
+ /**
195
+ * Get user balance
196
+ *
197
+ * Get current user balance and transaction statistics
198
+ */
199
+ async balanceRetrieve() {
200
+ const response = await this.client.request("GET", "/cfg/payments/balance/");
201
+ return response;
202
+ }
203
+ /**
204
+ * Get available currencies
205
+ *
206
+ * Returns list of available currencies with token+network info, popular
207
+ * first
208
+ */
209
+ async currenciesList() {
210
+ const response = await this.client.request("GET", "/cfg/payments/currencies/");
211
+ return response;
212
+ }
213
+ /**
214
+ * Get currency estimate
215
+ *
216
+ * Get estimated crypto amount for a given USD amount, including min amount
217
+ */
218
+ async currenciesEstimateRetrieve(...args) {
219
+ const code = args[0];
220
+ const isParamsObject = args.length === 2 && typeof args[1] === "object" && args[1] !== null && !Array.isArray(args[1]);
221
+ let params;
222
+ if (isParamsObject) {
223
+ params = args[1];
224
+ } else {
225
+ params = { amount: args[1] };
226
+ }
227
+ const response = await this.client.request("GET", `/cfg/payments/currencies/${code}/estimate/`, { params });
228
+ return response;
229
+ }
230
+ /**
231
+ * Get withdrawal estimate
232
+ *
233
+ * Get estimated crypto amount for withdrawal with fee breakdown
234
+ */
235
+ async currenciesWithdrawalEstimateRetrieve(...args) {
236
+ const code = args[0];
237
+ const isParamsObject = args.length === 2 && typeof args[1] === "object" && args[1] !== null && !Array.isArray(args[1]);
238
+ let params;
239
+ if (isParamsObject) {
240
+ params = args[1];
241
+ } else {
242
+ params = { amount: args[1] };
243
+ }
244
+ const response = await this.client.request("GET", `/cfg/payments/currencies/${code}/withdrawal-estimate/`, { params });
245
+ return response;
246
+ }
247
+ /**
248
+ * ViewSet for payment operations. Endpoints: - GET /payments/ - List
249
+ * user's payments - GET /payments/{id}/ - Get payment details - POST
250
+ * /payments/create/ - Create new payment - GET /payments/{id}/status/ -
251
+ * Check payment status - POST /payments/{id}/confirm/ - Confirm payment
252
+ */
253
+ async paymentsList(...args) {
254
+ const isParamsObject = args.length === 1 && typeof args[0] === "object" && args[0] !== null && !Array.isArray(args[0]);
255
+ let params;
256
+ if (isParamsObject) {
257
+ params = args[0];
258
+ } else {
259
+ params = { page: args[0], page_size: args[1] };
260
+ }
261
+ const response = await this.client.request("GET", "/cfg/payments/payments/", { params });
262
+ return response;
263
+ }
264
+ /**
265
+ * ViewSet for payment operations. Endpoints: - GET /payments/ - List
266
+ * user's payments - GET /payments/{id}/ - Get payment details - POST
267
+ * /payments/create/ - Create new payment - GET /payments/{id}/status/ -
268
+ * Check payment status - POST /payments/{id}/confirm/ - Confirm payment
269
+ */
270
+ async paymentsRetrieve(id) {
271
+ const response = await this.client.request("GET", `/cfg/payments/payments/${id}/`);
272
+ return response;
273
+ }
274
+ /**
275
+ * POST /api/v1/payments/{id}/confirm/ Confirm payment (user clicked "I
276
+ * have paid"). Checks status with provider and creates transaction if
277
+ * completed.
278
+ */
279
+ async paymentsConfirmCreate(id) {
280
+ const response = await this.client.request("POST", `/cfg/payments/payments/${id}/confirm/`);
281
+ return response;
282
+ }
283
+ /**
284
+ * GET /api/v1/payments/{id}/status/?refresh=true Check payment status
285
+ * (with optional refresh from provider). Query params: - refresh: boolean
286
+ * (default: false) - Force refresh from provider
287
+ */
288
+ async paymentsStatusRetrieve(id) {
289
+ const response = await this.client.request("GET", `/cfg/payments/payments/${id}/status/`);
290
+ return response.results || response;
291
+ }
292
+ /**
293
+ * Create payment
294
+ *
295
+ * Create a new payment with specified amount and currency
296
+ */
297
+ async paymentsCreateCreate(data) {
298
+ const response = await this.client.request("POST", "/cfg/payments/payments/create/", { body: data });
299
+ return response;
300
+ }
301
+ /**
302
+ * Get user transactions
303
+ *
304
+ * Get user transactions with pagination and filtering
305
+ */
306
+ async transactionsList(...args) {
307
+ const isParamsObject = args.length === 1 && typeof args[0] === "object" && args[0] !== null && !Array.isArray(args[0]);
308
+ let params;
309
+ if (isParamsObject) {
310
+ params = args[0];
311
+ } else {
312
+ params = { limit: args[0], offset: args[1], type: args[2] };
313
+ }
314
+ const response = await this.client.request("GET", "/cfg/payments/transactions/", { params });
315
+ return response;
316
+ }
317
+ /**
318
+ * ViewSet for withdrawal operations. Endpoints: - GET /withdrawals/ - List
319
+ * user's withdrawal requests - GET /withdrawals/{id}/ - Get withdrawal
320
+ * details - POST /withdrawals/create/ - Create withdrawal request - POST
321
+ * /withdrawals/{id}/cancel/ - Cancel pending withdrawal
322
+ */
323
+ async withdrawalsList(...args) {
324
+ const isParamsObject = args.length === 1 && typeof args[0] === "object" && args[0] !== null && !Array.isArray(args[0]);
325
+ let params;
326
+ if (isParamsObject) {
327
+ params = args[0];
328
+ } else {
329
+ params = { page: args[0], page_size: args[1] };
330
+ }
331
+ const response = await this.client.request("GET", "/cfg/payments/withdrawals/", { params });
332
+ return response;
333
+ }
334
+ /**
335
+ * ViewSet for withdrawal operations. Endpoints: - GET /withdrawals/ - List
336
+ * user's withdrawal requests - GET /withdrawals/{id}/ - Get withdrawal
337
+ * details - POST /withdrawals/create/ - Create withdrawal request - POST
338
+ * /withdrawals/{id}/cancel/ - Cancel pending withdrawal
339
+ */
340
+ async withdrawalsRetrieve(id) {
341
+ const response = await this.client.request("GET", `/cfg/payments/withdrawals/${id}/`);
342
+ return response;
343
+ }
344
+ /**
345
+ * Cancel withdrawal request
346
+ *
347
+ * Cancel a pending withdrawal request
348
+ */
349
+ async withdrawalsCancelCreate(id) {
350
+ const response = await this.client.request("POST", `/cfg/payments/withdrawals/${id}/cancel/`);
351
+ return response;
352
+ }
353
+ /**
354
+ * Create withdrawal request
355
+ *
356
+ * Create a new withdrawal request (requires admin approval)
357
+ */
358
+ async withdrawalsCreateCreate(data) {
359
+ const response = await this.client.request("POST", "/cfg/payments/withdrawals/create/", { body: data });
360
+ return response;
361
+ }
362
+ };
363
+
364
+ // src/api/generated/ext_payments/http.ts
365
+ var FetchAdapter = class {
366
+ async request(request) {
367
+ const { method, url, headers, body, params, formData, binaryBody } = request;
368
+ let finalUrl = url;
369
+ if (params) {
370
+ const searchParams = new URLSearchParams();
371
+ Object.entries(params).forEach(([key, value]) => {
372
+ if (value !== null && value !== void 0) {
373
+ searchParams.append(key, String(value));
374
+ }
375
+ });
376
+ const queryString = searchParams.toString();
377
+ if (queryString) {
378
+ finalUrl = url.includes("?") ? `${url}&${queryString}` : `${url}?${queryString}`;
379
+ }
380
+ }
381
+ const finalHeaders = { ...headers };
382
+ let requestBody;
383
+ if (formData) {
384
+ requestBody = formData;
385
+ } else if (binaryBody) {
386
+ finalHeaders["Content-Type"] = "application/octet-stream";
387
+ requestBody = binaryBody;
388
+ } else if (body) {
389
+ finalHeaders["Content-Type"] = "application/json";
390
+ requestBody = JSON.stringify(body);
391
+ }
392
+ const response = await fetch(finalUrl, {
393
+ method,
394
+ headers: finalHeaders,
395
+ body: requestBody,
396
+ credentials: "include"
397
+ // Include Django session cookies
398
+ });
399
+ let data = null;
400
+ const contentType = response.headers.get("content-type");
401
+ if (response.status !== 204 && contentType?.includes("application/json")) {
402
+ data = await response.json();
403
+ } else if (response.status !== 204) {
404
+ data = await response.text();
405
+ }
406
+ const responseHeaders = {};
407
+ response.headers.forEach((value, key) => {
408
+ responseHeaders[key] = value;
409
+ });
410
+ return {
411
+ data,
412
+ status: response.status,
413
+ statusText: response.statusText,
414
+ headers: responseHeaders
415
+ };
416
+ }
417
+ };
418
+
419
+ // src/api/generated/ext_payments/errors.ts
420
+ var APIError = class extends Error {
421
+ constructor(statusCode, statusText, response, url, message) {
422
+ super(message || `HTTP ${statusCode}: ${statusText}`);
423
+ this.statusCode = statusCode;
424
+ this.statusText = statusText;
425
+ this.response = response;
426
+ this.url = url;
427
+ this.name = "APIError";
428
+ }
429
+ /**
430
+ * Get error details from response.
431
+ * DRF typically returns: { "detail": "Error message" } or { "field": ["error1", "error2"] }
432
+ */
433
+ get details() {
434
+ if (typeof this.response === "object" && this.response !== null) {
435
+ return this.response;
436
+ }
437
+ return null;
438
+ }
439
+ /**
440
+ * Get field-specific validation errors from DRF.
441
+ * Returns: { "field_name": ["error1", "error2"], ... }
442
+ */
443
+ get fieldErrors() {
444
+ const details = this.details;
445
+ if (!details) return null;
446
+ const fieldErrors = {};
447
+ for (const [key, value] of Object.entries(details)) {
448
+ if (Array.isArray(value)) {
449
+ fieldErrors[key] = value;
450
+ }
451
+ }
452
+ return Object.keys(fieldErrors).length > 0 ? fieldErrors : null;
453
+ }
454
+ /**
455
+ * Get single error message from DRF.
456
+ * Checks for "detail", "message", or first field error.
457
+ */
458
+ get errorMessage() {
459
+ const details = this.details;
460
+ if (!details) return this.message;
461
+ if (details.detail) {
462
+ return Array.isArray(details.detail) ? details.detail.join(", ") : String(details.detail);
463
+ }
464
+ if (details.message) {
465
+ return String(details.message);
466
+ }
467
+ const fieldErrors = this.fieldErrors;
468
+ if (fieldErrors) {
469
+ const firstField = Object.keys(fieldErrors)[0];
470
+ if (firstField) {
471
+ return `${firstField}: ${fieldErrors[firstField]?.join(", ")}`;
472
+ }
473
+ }
474
+ return this.message;
475
+ }
476
+ // Helper methods for common HTTP status codes
477
+ get isValidationError() {
478
+ return this.statusCode === 400;
479
+ }
480
+ get isAuthError() {
481
+ return this.statusCode === 401;
482
+ }
483
+ get isPermissionError() {
484
+ return this.statusCode === 403;
485
+ }
486
+ get isNotFoundError() {
487
+ return this.statusCode === 404;
488
+ }
489
+ get isServerError() {
490
+ return this.statusCode >= 500 && this.statusCode < 600;
491
+ }
492
+ };
493
+ var NetworkError = class extends Error {
494
+ constructor(message, url, originalError) {
495
+ super(message);
496
+ this.url = url;
497
+ this.originalError = originalError;
498
+ this.name = "NetworkError";
499
+ }
500
+ };
501
+ var DEFAULT_CONFIG = {
502
+ enabled: process.env.NODE_ENV !== "production",
503
+ logRequests: true,
504
+ logResponses: true,
505
+ logErrors: true,
506
+ logBodies: true,
507
+ logHeaders: false
508
+ };
509
+ var SENSITIVE_HEADERS = [
510
+ "authorization",
511
+ "cookie",
512
+ "set-cookie",
513
+ "x-api-key",
514
+ "x-csrf-token"
515
+ ];
516
+ var APILogger = class {
517
+ config;
518
+ consola;
519
+ constructor(config = {}) {
520
+ this.config = { ...DEFAULT_CONFIG, ...config };
521
+ this.consola = config.consola || createConsola({
522
+ level: this.config.enabled ? 4 : 0
523
+ });
524
+ }
525
+ /**
526
+ * Enable logging
527
+ */
528
+ enable() {
529
+ this.config.enabled = true;
530
+ }
531
+ /**
532
+ * Disable logging
533
+ */
534
+ disable() {
535
+ this.config.enabled = false;
536
+ }
537
+ /**
538
+ * Update configuration
539
+ */
540
+ setConfig(config) {
541
+ this.config = { ...this.config, ...config };
542
+ }
543
+ /**
544
+ * Filter sensitive headers
545
+ */
546
+ filterHeaders(headers) {
547
+ if (!headers) return {};
548
+ const filtered = {};
549
+ Object.keys(headers).forEach((key) => {
550
+ const lowerKey = key.toLowerCase();
551
+ if (SENSITIVE_HEADERS.includes(lowerKey)) {
552
+ filtered[key] = "***";
553
+ } else {
554
+ filtered[key] = headers[key] || "";
555
+ }
556
+ });
557
+ return filtered;
558
+ }
559
+ /**
560
+ * Log request
561
+ */
562
+ logRequest(request) {
563
+ if (!this.config.enabled || !this.config.logRequests) return;
564
+ const { method, url, headers, body } = request;
565
+ this.consola.start(`${method} ${url}`);
566
+ if (this.config.logHeaders && headers) {
567
+ this.consola.debug("Headers:", this.filterHeaders(headers));
568
+ }
569
+ if (this.config.logBodies && body) {
570
+ this.consola.debug("Body:", body);
571
+ }
572
+ }
573
+ /**
574
+ * Log response
575
+ */
576
+ logResponse(request, response) {
577
+ if (!this.config.enabled || !this.config.logResponses) return;
578
+ const { method, url } = request;
579
+ const { status, statusText, data, duration } = response;
580
+ this.consola.success(
581
+ `${method} ${url} ${status} ${statusText} (${duration}ms)`
582
+ );
583
+ if (this.config.logBodies && data) {
584
+ this.consola.debug("Response:", data);
585
+ }
586
+ }
587
+ /**
588
+ * Log error
589
+ */
590
+ logError(request, error) {
591
+ if (!this.config.enabled || !this.config.logErrors) return;
592
+ const { method, url } = request;
593
+ const { message, statusCode, fieldErrors, duration } = error;
594
+ this.consola.error(
595
+ `${method} ${url} ${statusCode || "Network"} Error (${duration}ms)`
596
+ );
597
+ this.consola.error("Message:", message);
598
+ if (fieldErrors && Object.keys(fieldErrors).length > 0) {
599
+ this.consola.error("Field Errors:");
600
+ Object.entries(fieldErrors).forEach(([field, errors]) => {
601
+ errors.forEach((err) => {
602
+ this.consola.error(` \u2022 ${field}: ${err}`);
603
+ });
604
+ });
605
+ }
606
+ }
607
+ /**
608
+ * Log general info
609
+ */
610
+ info(message, ...args) {
611
+ if (!this.config.enabled) return;
612
+ this.consola.info(message, ...args);
613
+ }
614
+ /**
615
+ * Log warning
616
+ */
617
+ warn(message, ...args) {
618
+ if (!this.config.enabled) return;
619
+ this.consola.warn(message, ...args);
620
+ }
621
+ /**
622
+ * Log error
623
+ */
624
+ error(message, ...args) {
625
+ if (!this.config.enabled) return;
626
+ this.consola.error(message, ...args);
627
+ }
628
+ /**
629
+ * Log debug
630
+ */
631
+ debug(message, ...args) {
632
+ if (!this.config.enabled) return;
633
+ this.consola.debug(message, ...args);
634
+ }
635
+ /**
636
+ * Log success
637
+ */
638
+ success(message, ...args) {
639
+ if (!this.config.enabled) return;
640
+ this.consola.success(message, ...args);
641
+ }
642
+ /**
643
+ * Create a sub-logger with prefix
644
+ */
645
+ withTag(tag) {
646
+ return this.consola.withTag(tag);
647
+ }
648
+ };
649
+ new APILogger();
650
+ var DEFAULT_RETRY_CONFIG = {
651
+ retries: 3,
652
+ factor: 2,
653
+ minTimeout: 1e3,
654
+ maxTimeout: 6e4,
655
+ randomize: true,
656
+ onFailedAttempt: () => {
657
+ }
658
+ };
659
+ function shouldRetry(error) {
660
+ if (error instanceof NetworkError) {
661
+ return true;
662
+ }
663
+ if (error instanceof APIError) {
664
+ const status = error.statusCode;
665
+ if (status >= 500 && status < 600) {
666
+ return true;
667
+ }
668
+ if (status === 429) {
669
+ return true;
670
+ }
671
+ return false;
672
+ }
673
+ return true;
674
+ }
675
+ async function withRetry(fn, config) {
676
+ const finalConfig = { ...DEFAULT_RETRY_CONFIG, ...config };
677
+ return pRetry(
678
+ async () => {
679
+ try {
680
+ return await fn();
681
+ } catch (error) {
682
+ if (!shouldRetry(error)) {
683
+ throw new AbortError(error);
684
+ }
685
+ throw error;
686
+ }
687
+ },
688
+ {
689
+ retries: finalConfig.retries,
690
+ factor: finalConfig.factor,
691
+ minTimeout: finalConfig.minTimeout,
692
+ maxTimeout: finalConfig.maxTimeout,
693
+ randomize: finalConfig.randomize,
694
+ onFailedAttempt: finalConfig.onFailedAttempt ? (error) => {
695
+ const pRetryError = error;
696
+ finalConfig.onFailedAttempt({
697
+ error: pRetryError,
698
+ attemptNumber: pRetryError.attemptNumber,
699
+ retriesLeft: pRetryError.retriesLeft
700
+ });
701
+ } : void 0
702
+ }
703
+ );
704
+ }
705
+
706
+ // src/api/generated/ext_payments/client.ts
707
+ var APIClient = class {
708
+ baseUrl;
709
+ httpClient;
710
+ logger = null;
711
+ retryConfig = null;
712
+ tokenGetter = null;
713
+ // Sub-clients
714
+ ext_payments_payments;
715
+ constructor(baseUrl, options) {
716
+ this.baseUrl = baseUrl.replace(/\/$/, "");
717
+ this.httpClient = options?.httpClient || new FetchAdapter();
718
+ this.tokenGetter = options?.tokenGetter || null;
719
+ if (options?.loggerConfig !== void 0) {
720
+ this.logger = new APILogger(options.loggerConfig);
721
+ }
722
+ if (options?.retryConfig !== void 0) {
723
+ this.retryConfig = options.retryConfig;
724
+ }
725
+ this.ext_payments_payments = new ExtPaymentsPayments(this);
726
+ }
727
+ /**
728
+ * Get CSRF token from cookies (for SessionAuthentication).
729
+ *
730
+ * Returns null if cookie doesn't exist (JWT-only auth).
731
+ */
732
+ getCsrfToken() {
733
+ const name = "csrftoken";
734
+ const value = `; ${document.cookie}`;
735
+ const parts = value.split(`; ${name}=`);
736
+ if (parts.length === 2) {
737
+ return parts.pop()?.split(";").shift() || null;
738
+ }
739
+ return null;
740
+ }
741
+ /**
742
+ * Get the base URL for building streaming/download URLs.
743
+ */
744
+ getBaseUrl() {
745
+ return this.baseUrl;
746
+ }
747
+ /**
748
+ * Get JWT token for URL authentication (used in streaming endpoints).
749
+ * Returns null if no token getter is configured or no token is available.
750
+ */
751
+ getToken() {
752
+ return this.tokenGetter ? this.tokenGetter() : null;
753
+ }
754
+ /**
755
+ * Make HTTP request with Django CSRF and session handling.
756
+ * Automatically retries on network errors and 5xx server errors.
757
+ */
758
+ async request(method, path, options) {
759
+ if (this.retryConfig) {
760
+ return withRetry(() => this._makeRequest(method, path, options), {
761
+ ...this.retryConfig,
762
+ onFailedAttempt: (info) => {
763
+ if (this.logger) {
764
+ this.logger.warn(
765
+ `Retry attempt ${info.attemptNumber}/${info.retriesLeft + info.attemptNumber} for ${method} ${path}: ${info.error.message}`
766
+ );
767
+ }
768
+ this.retryConfig?.onFailedAttempt?.(info);
769
+ }
770
+ });
771
+ }
772
+ return this._makeRequest(method, path, options);
773
+ }
774
+ /**
775
+ * Internal request method (without retry wrapper).
776
+ * Used by request() method with optional retry logic.
777
+ */
778
+ async _makeRequest(method, path, options) {
779
+ const url = this.baseUrl ? `${this.baseUrl}${path}` : path;
780
+ const startTime = Date.now();
781
+ const headers = {
782
+ ...options?.headers || {}
783
+ };
784
+ if (!options?.formData && !options?.binaryBody && !headers["Content-Type"]) {
785
+ headers["Content-Type"] = "application/json";
786
+ }
787
+ if (this.logger) {
788
+ this.logger.logRequest({
789
+ method,
790
+ url,
791
+ headers,
792
+ body: options?.formData || options?.body,
793
+ timestamp: startTime
794
+ });
795
+ }
796
+ try {
797
+ const response = await this.httpClient.request({
798
+ method,
799
+ url,
800
+ headers,
801
+ params: options?.params,
802
+ body: options?.body,
803
+ formData: options?.formData,
804
+ binaryBody: options?.binaryBody
805
+ });
806
+ const duration = Date.now() - startTime;
807
+ if (response.status >= 400) {
808
+ const error = new APIError(
809
+ response.status,
810
+ response.statusText,
811
+ response.data,
812
+ url
813
+ );
814
+ if (this.logger) {
815
+ this.logger.logError(
816
+ {
817
+ method,
818
+ url,
819
+ headers,
820
+ body: options?.formData || options?.body,
821
+ timestamp: startTime
822
+ },
823
+ {
824
+ message: error.message,
825
+ statusCode: response.status,
826
+ duration,
827
+ timestamp: Date.now()
828
+ }
829
+ );
830
+ }
831
+ throw error;
832
+ }
833
+ if (this.logger) {
834
+ this.logger.logResponse(
835
+ {
836
+ method,
837
+ url,
838
+ headers,
839
+ body: options?.formData || options?.body,
840
+ timestamp: startTime
841
+ },
842
+ {
843
+ status: response.status,
844
+ statusText: response.statusText,
845
+ data: response.data,
846
+ duration,
847
+ timestamp: Date.now()
848
+ }
849
+ );
850
+ }
851
+ return response.data;
852
+ } catch (error) {
853
+ const duration = Date.now() - startTime;
854
+ if (error instanceof APIError) {
855
+ throw error;
856
+ }
857
+ const isCORSError = error instanceof TypeError && (error.message.toLowerCase().includes("cors") || error.message.toLowerCase().includes("failed to fetch") || error.message.toLowerCase().includes("network request failed"));
858
+ if (this.logger) {
859
+ if (isCORSError) {
860
+ this.logger.error(`\u{1F6AB} CORS Error: ${method} ${url}`);
861
+ this.logger.error(` \u2192 ${error instanceof Error ? error.message : String(error)}`);
862
+ this.logger.error(` \u2192 Configure security_domains parameter on the server`);
863
+ } else {
864
+ this.logger.error(`\u26A0\uFE0F Network Error: ${method} ${url}`);
865
+ this.logger.error(` \u2192 ${error instanceof Error ? error.message : String(error)}`);
866
+ }
867
+ }
868
+ if (typeof window !== "undefined") {
869
+ try {
870
+ if (isCORSError) {
871
+ window.dispatchEvent(new CustomEvent("cors-error", {
872
+ detail: {
873
+ url,
874
+ method,
875
+ error: error instanceof Error ? error.message : String(error),
876
+ timestamp: /* @__PURE__ */ new Date()
877
+ },
878
+ bubbles: true,
879
+ cancelable: false
880
+ }));
881
+ } else {
882
+ window.dispatchEvent(new CustomEvent("network-error", {
883
+ detail: {
884
+ url,
885
+ method,
886
+ error: error instanceof Error ? error.message : String(error),
887
+ timestamp: /* @__PURE__ */ new Date()
888
+ },
889
+ bubbles: true,
890
+ cancelable: false
891
+ }));
892
+ }
893
+ } catch (eventError) {
894
+ }
895
+ }
896
+ const networkError = error instanceof Error ? new NetworkError(error.message, url, error) : new NetworkError("Unknown error", url);
897
+ if (this.logger) {
898
+ this.logger.logError(
899
+ {
900
+ method,
901
+ url,
902
+ headers,
903
+ body: options?.formData || options?.body,
904
+ timestamp: startTime
905
+ },
906
+ {
907
+ message: networkError.message,
908
+ duration,
909
+ timestamp: Date.now()
910
+ }
911
+ );
912
+ }
913
+ throw networkError;
914
+ }
915
+ }
916
+ };
917
+
918
+ // src/api/generated/ext_payments/storage.ts
919
+ var LocalStorageAdapter = class {
920
+ logger;
921
+ constructor(logger) {
922
+ this.logger = logger;
923
+ }
924
+ getItem(key) {
925
+ try {
926
+ if (typeof window !== "undefined" && window.localStorage) {
927
+ const value = localStorage.getItem(key);
928
+ this.logger?.debug(`LocalStorage.getItem("${key}"): ${value ? "found" : "not found"}`);
929
+ return value;
930
+ }
931
+ this.logger?.warn("LocalStorage not available: window.localStorage is undefined");
932
+ } catch (error) {
933
+ this.logger?.error("LocalStorage.getItem failed:", error);
934
+ }
935
+ return null;
936
+ }
937
+ setItem(key, value) {
938
+ try {
939
+ if (typeof window !== "undefined" && window.localStorage) {
940
+ localStorage.setItem(key, value);
941
+ this.logger?.debug(`LocalStorage.setItem("${key}"): success`);
942
+ } else {
943
+ this.logger?.warn("LocalStorage not available: window.localStorage is undefined");
944
+ }
945
+ } catch (error) {
946
+ this.logger?.error("LocalStorage.setItem failed:", error);
947
+ }
948
+ }
949
+ removeItem(key) {
950
+ try {
951
+ if (typeof window !== "undefined" && window.localStorage) {
952
+ localStorage.removeItem(key);
953
+ this.logger?.debug(`LocalStorage.removeItem("${key}"): success`);
954
+ } else {
955
+ this.logger?.warn("LocalStorage not available: window.localStorage is undefined");
956
+ }
957
+ } catch (error) {
958
+ this.logger?.error("LocalStorage.removeItem failed:", error);
959
+ }
960
+ }
961
+ };
962
+ z.object({
963
+ code: z.string(),
964
+ name: z.string(),
965
+ token: z.string(),
966
+ network: z.string().nullable(),
967
+ display_name: z.string(),
968
+ symbol: z.string(),
969
+ decimal_places: z.int(),
970
+ is_active: z.boolean(),
971
+ min_amount_usd: z.string(),
972
+ sort_order: z.int()
973
+ });
974
+ z.object({
975
+ amount_usd: z.string(),
976
+ currency_code: z.string().min(1).max(20),
977
+ description: z.string().max(500).optional()
978
+ });
979
+ z.object({
980
+ id: z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),
981
+ transaction_type: z.nativeEnum(TransactionTransactionType),
982
+ type_display: z.string(),
983
+ amount_usd: z.string(),
984
+ amount_display: z.string(),
985
+ balance_after: z.string(),
986
+ payment_id: z.string().nullable(),
987
+ description: z.string(),
988
+ created_at: z.string().datetime({ offset: true })
989
+ });
990
+ z.object({
991
+ amount_usd: z.string(),
992
+ currency_code: z.string().min(1).max(20),
993
+ wallet_address: z.string().min(1).max(255)
994
+ });
995
+
996
+ // src/api/generated/ext_payments/index.ts
997
+ var TOKEN_KEY = "auth_token";
998
+ var REFRESH_TOKEN_KEY = "refresh_token";
999
+ var API = class {
1000
+ baseUrl;
1001
+ _client;
1002
+ _token = null;
1003
+ _refreshToken = null;
1004
+ storage;
1005
+ options;
1006
+ // Sub-clients
1007
+ ext_payments_payments;
1008
+ constructor(baseUrl, options) {
1009
+ this.baseUrl = baseUrl;
1010
+ this.options = options;
1011
+ const logger = options?.loggerConfig ? new APILogger(options.loggerConfig) : void 0;
1012
+ this.storage = options?.storage || new LocalStorageAdapter(logger);
1013
+ this._loadTokensFromStorage();
1014
+ this._client = new APIClient(this.baseUrl, {
1015
+ retryConfig: this.options?.retryConfig,
1016
+ loggerConfig: this.options?.loggerConfig,
1017
+ tokenGetter: () => this.getToken()
1018
+ });
1019
+ this._injectAuthHeader();
1020
+ this.ext_payments_payments = this._client.ext_payments_payments;
1021
+ }
1022
+ _loadTokensFromStorage() {
1023
+ this._token = this.storage.getItem(TOKEN_KEY);
1024
+ this._refreshToken = this.storage.getItem(REFRESH_TOKEN_KEY);
1025
+ }
1026
+ _reinitClients() {
1027
+ this._client = new APIClient(this.baseUrl, {
1028
+ retryConfig: this.options?.retryConfig,
1029
+ loggerConfig: this.options?.loggerConfig,
1030
+ tokenGetter: () => this.getToken()
1031
+ });
1032
+ this._injectAuthHeader();
1033
+ this.ext_payments_payments = this._client.ext_payments_payments;
1034
+ }
1035
+ _injectAuthHeader() {
1036
+ const originalRequest = this._client.request.bind(this._client);
1037
+ this._client.request = async (method, path, options) => {
1038
+ const token = this.getToken();
1039
+ const mergedOptions = {
1040
+ ...options,
1041
+ headers: {
1042
+ ...options?.headers || {},
1043
+ ...token ? { "Authorization": `Bearer ${token}` } : {}
1044
+ }
1045
+ };
1046
+ return originalRequest(method, path, mergedOptions);
1047
+ };
1048
+ }
1049
+ /**
1050
+ * Get current JWT token
1051
+ */
1052
+ getToken() {
1053
+ return this.storage.getItem(TOKEN_KEY);
1054
+ }
1055
+ /**
1056
+ * Get current refresh token
1057
+ */
1058
+ getRefreshToken() {
1059
+ return this.storage.getItem(REFRESH_TOKEN_KEY);
1060
+ }
1061
+ /**
1062
+ * Set JWT token and refresh token
1063
+ * @param token - JWT access token
1064
+ * @param refreshToken - JWT refresh token (optional)
1065
+ */
1066
+ setToken(token, refreshToken) {
1067
+ this._token = token;
1068
+ this.storage.setItem(TOKEN_KEY, token);
1069
+ if (refreshToken) {
1070
+ this._refreshToken = refreshToken;
1071
+ this.storage.setItem(REFRESH_TOKEN_KEY, refreshToken);
1072
+ }
1073
+ this._reinitClients();
1074
+ }
1075
+ /**
1076
+ * Clear all tokens
1077
+ */
1078
+ clearTokens() {
1079
+ this._token = null;
1080
+ this._refreshToken = null;
1081
+ this.storage.removeItem(TOKEN_KEY);
1082
+ this.storage.removeItem(REFRESH_TOKEN_KEY);
1083
+ this._reinitClients();
1084
+ }
1085
+ /**
1086
+ * Check if user is authenticated
1087
+ */
1088
+ isAuthenticated() {
1089
+ return !!this.getToken();
1090
+ }
1091
+ /**
1092
+ * Update base URL and reinitialize clients
1093
+ * @param url - New base URL
1094
+ */
1095
+ setBaseUrl(url) {
1096
+ this.baseUrl = url;
1097
+ this._reinitClients();
1098
+ }
1099
+ /**
1100
+ * Get current base URL
1101
+ */
1102
+ getBaseUrl() {
1103
+ return this.baseUrl;
1104
+ }
1105
+ /**
1106
+ * Get OpenAPI schema path
1107
+ * @returns Path to the OpenAPI schema JSON file
1108
+ *
1109
+ * Note: The OpenAPI schema is available in the schema.json file.
1110
+ * You can load it dynamically using:
1111
+ * ```typescript
1112
+ * const schema = await fetch('./schema.json').then(r => r.json());
1113
+ * // or using fs in Node.js:
1114
+ * // const schema = JSON.parse(fs.readFileSync('./schema.json', 'utf-8'));
1115
+ * ```
1116
+ */
1117
+ getSchemaPath() {
1118
+ return "./schema.json";
1119
+ }
1120
+ };
1121
+
1122
+ // src/api/generated/ext_payments/api-instance.ts
1123
+ var globalAPI = null;
1124
+ var autoConfigAttempted = false;
1125
+ function tryAutoConfigureFromEnv() {
1126
+ if (autoConfigAttempted) return;
1127
+ autoConfigAttempted = true;
1128
+ if (globalAPI) return;
1129
+ if (typeof process === "undefined" || !process.env) return;
1130
+ const baseUrl = process.env.NEXT_PUBLIC_API_URL || process.env.VITE_API_URL || process.env.REACT_APP_API_URL || process.env.API_URL;
1131
+ if (baseUrl) {
1132
+ globalAPI = new API(baseUrl);
1133
+ }
1134
+ }
1135
+ function getAPIInstance() {
1136
+ tryAutoConfigureFromEnv();
1137
+ if (!globalAPI) {
1138
+ throw new Error(
1139
+ 'API not configured. Call configureAPI() with your base URL before using fetchers or hooks.\n\nExample:\n import { configureAPI } from "./api-instance"\n configureAPI({ baseUrl: "https://api.example.com" })\n\nOr set environment variable: NEXT_PUBLIC_API_URL, VITE_API_URL, or REACT_APP_API_URL'
1140
+ );
1141
+ }
1142
+ return globalAPI;
1143
+ }
1144
+
1145
+ // src/api/generated/ext_payments/_utils/fetchers/ext_payments__payments.ts
1146
+ async function getPaymentsBalanceRetrieve(client) {
1147
+ const api = client || getAPIInstance();
1148
+ const response = await api.ext_payments_payments.balanceRetrieve();
1149
+ try {
1150
+ return BalanceSchema.parse(response);
1151
+ } catch (error) {
1152
+ consola.error("\u274C Zod Validation Failed");
1153
+ consola.box(`getPaymentsBalanceRetrieve
1154
+ Path: /cfg/payments/balance/
1155
+ Method: GET`);
1156
+ if (error instanceof Error && "issues" in error && Array.isArray(error.issues)) {
1157
+ consola.error("Validation Issues:");
1158
+ error.issues.forEach((issue, index) => {
1159
+ consola.error(` ${index + 1}. ${issue.path.join(".") || "root"}`);
1160
+ consola.error(` \u251C\u2500 Message: ${issue.message}`);
1161
+ if (issue.expected) consola.error(` \u251C\u2500 Expected: ${issue.expected}`);
1162
+ if (issue.received) consola.error(` \u2514\u2500 Received: ${issue.received}`);
1163
+ });
1164
+ }
1165
+ consola.error("Response data:", response);
1166
+ if (typeof window !== "undefined" && error instanceof Error && "issues" in error) {
1167
+ try {
1168
+ const event = new CustomEvent("zod-validation-error", {
1169
+ detail: {
1170
+ operation: "getPaymentsBalanceRetrieve",
1171
+ path: "/cfg/payments/balance/",
1172
+ method: "GET",
1173
+ error,
1174
+ response,
1175
+ timestamp: /* @__PURE__ */ new Date()
1176
+ },
1177
+ bubbles: true,
1178
+ cancelable: false
1179
+ });
1180
+ window.dispatchEvent(event);
1181
+ } catch (eventError) {
1182
+ consola.warn("Failed to dispatch validation error event:", eventError);
1183
+ }
1184
+ }
1185
+ throw error;
1186
+ }
1187
+ }
1188
+ async function getPaymentsCurrenciesList(client) {
1189
+ const api = client || getAPIInstance();
1190
+ const response = await api.ext_payments_payments.currenciesList();
1191
+ return response;
1192
+ }
1193
+ async function getPaymentsCurrenciesEstimateRetrieve(code, params, client) {
1194
+ const api = client || getAPIInstance();
1195
+ const response = await api.ext_payments_payments.currenciesEstimateRetrieve(code, params?.amount);
1196
+ return response;
1197
+ }
1198
+ async function getPaymentsCurrenciesWithdrawalEstimateRetrieve(code, params, client) {
1199
+ const api = client || getAPIInstance();
1200
+ const response = await api.ext_payments_payments.currenciesWithdrawalEstimateRetrieve(code, params?.amount);
1201
+ return response;
1202
+ }
1203
+ async function getPaymentsPaymentsList(params, client) {
1204
+ const api = client || getAPIInstance();
1205
+ const response = await api.ext_payments_payments.paymentsList(params?.page, params?.page_size);
1206
+ try {
1207
+ return PaginatedPaymentListListSchema.parse(response);
1208
+ } catch (error) {
1209
+ consola.error("\u274C Zod Validation Failed");
1210
+ consola.box(`getPaymentsPaymentsList
1211
+ Path: /cfg/payments/payments/
1212
+ Method: GET`);
1213
+ if (error instanceof Error && "issues" in error && Array.isArray(error.issues)) {
1214
+ consola.error("Validation Issues:");
1215
+ error.issues.forEach((issue, index) => {
1216
+ consola.error(` ${index + 1}. ${issue.path.join(".") || "root"}`);
1217
+ consola.error(` \u251C\u2500 Message: ${issue.message}`);
1218
+ if (issue.expected) consola.error(` \u251C\u2500 Expected: ${issue.expected}`);
1219
+ if (issue.received) consola.error(` \u2514\u2500 Received: ${issue.received}`);
1220
+ });
1221
+ }
1222
+ consola.error("Response data:", response);
1223
+ if (typeof window !== "undefined" && error instanceof Error && "issues" in error) {
1224
+ try {
1225
+ const event = new CustomEvent("zod-validation-error", {
1226
+ detail: {
1227
+ operation: "getPaymentsPaymentsList",
1228
+ path: "/cfg/payments/payments/",
1229
+ method: "GET",
1230
+ error,
1231
+ response,
1232
+ timestamp: /* @__PURE__ */ new Date()
1233
+ },
1234
+ bubbles: true,
1235
+ cancelable: false
1236
+ });
1237
+ window.dispatchEvent(event);
1238
+ } catch (eventError) {
1239
+ consola.warn("Failed to dispatch validation error event:", eventError);
1240
+ }
1241
+ }
1242
+ throw error;
1243
+ }
1244
+ }
1245
+ async function getPaymentsPaymentsRetrieve(id, client) {
1246
+ const api = client || getAPIInstance();
1247
+ const response = await api.ext_payments_payments.paymentsRetrieve(id);
1248
+ try {
1249
+ return PaymentDetailSchema.parse(response);
1250
+ } catch (error) {
1251
+ consola.error("\u274C Zod Validation Failed");
1252
+ consola.box(`getPaymentsPaymentsRetrieve
1253
+ Path: /cfg/payments/payments/{id}/
1254
+ Method: GET`);
1255
+ if (error instanceof Error && "issues" in error && Array.isArray(error.issues)) {
1256
+ consola.error("Validation Issues:");
1257
+ error.issues.forEach((issue, index) => {
1258
+ consola.error(` ${index + 1}. ${issue.path.join(".") || "root"}`);
1259
+ consola.error(` \u251C\u2500 Message: ${issue.message}`);
1260
+ if (issue.expected) consola.error(` \u251C\u2500 Expected: ${issue.expected}`);
1261
+ if (issue.received) consola.error(` \u2514\u2500 Received: ${issue.received}`);
1262
+ });
1263
+ }
1264
+ consola.error("Response data:", response);
1265
+ if (typeof window !== "undefined" && error instanceof Error && "issues" in error) {
1266
+ try {
1267
+ const event = new CustomEvent("zod-validation-error", {
1268
+ detail: {
1269
+ operation: "getPaymentsPaymentsRetrieve",
1270
+ path: "/cfg/payments/payments/{id}/",
1271
+ method: "GET",
1272
+ error,
1273
+ response,
1274
+ timestamp: /* @__PURE__ */ new Date()
1275
+ },
1276
+ bubbles: true,
1277
+ cancelable: false
1278
+ });
1279
+ window.dispatchEvent(event);
1280
+ } catch (eventError) {
1281
+ consola.warn("Failed to dispatch validation error event:", eventError);
1282
+ }
1283
+ }
1284
+ throw error;
1285
+ }
1286
+ }
1287
+ async function createPaymentsPaymentsConfirmCreate(id, client) {
1288
+ const api = client || getAPIInstance();
1289
+ const response = await api.ext_payments_payments.paymentsConfirmCreate(id);
1290
+ try {
1291
+ return PaymentListSchema.parse(response);
1292
+ } catch (error) {
1293
+ consola.error("\u274C Zod Validation Failed");
1294
+ consola.box(`createPaymentsPaymentsConfirmCreate
1295
+ Path: /cfg/payments/payments/{id}/confirm/
1296
+ Method: POST`);
1297
+ if (error instanceof Error && "issues" in error && Array.isArray(error.issues)) {
1298
+ consola.error("Validation Issues:");
1299
+ error.issues.forEach((issue, index) => {
1300
+ consola.error(` ${index + 1}. ${issue.path.join(".") || "root"}`);
1301
+ consola.error(` \u251C\u2500 Message: ${issue.message}`);
1302
+ if (issue.expected) consola.error(` \u251C\u2500 Expected: ${issue.expected}`);
1303
+ if (issue.received) consola.error(` \u2514\u2500 Received: ${issue.received}`);
1304
+ });
1305
+ }
1306
+ consola.error("Response data:", response);
1307
+ if (typeof window !== "undefined" && error instanceof Error && "issues" in error) {
1308
+ try {
1309
+ const event = new CustomEvent("zod-validation-error", {
1310
+ detail: {
1311
+ operation: "createPaymentsPaymentsConfirmCreate",
1312
+ path: "/cfg/payments/payments/{id}/confirm/",
1313
+ method: "POST",
1314
+ error,
1315
+ response,
1316
+ timestamp: /* @__PURE__ */ new Date()
1317
+ },
1318
+ bubbles: true,
1319
+ cancelable: false
1320
+ });
1321
+ window.dispatchEvent(event);
1322
+ } catch (eventError) {
1323
+ consola.warn("Failed to dispatch validation error event:", eventError);
1324
+ }
1325
+ }
1326
+ throw error;
1327
+ }
1328
+ }
1329
+ async function getPaymentsPaymentsStatusRetrieve(id, client) {
1330
+ const api = client || getAPIInstance();
1331
+ const response = await api.ext_payments_payments.paymentsStatusRetrieve(id);
1332
+ try {
1333
+ return PaymentListSchema.parse(response);
1334
+ } catch (error) {
1335
+ consola.error("\u274C Zod Validation Failed");
1336
+ consola.box(`getPaymentsPaymentsStatusRetrieve
1337
+ Path: /cfg/payments/payments/{id}/status/
1338
+ Method: GET`);
1339
+ if (error instanceof Error && "issues" in error && Array.isArray(error.issues)) {
1340
+ consola.error("Validation Issues:");
1341
+ error.issues.forEach((issue, index) => {
1342
+ consola.error(` ${index + 1}. ${issue.path.join(".") || "root"}`);
1343
+ consola.error(` \u251C\u2500 Message: ${issue.message}`);
1344
+ if (issue.expected) consola.error(` \u251C\u2500 Expected: ${issue.expected}`);
1345
+ if (issue.received) consola.error(` \u2514\u2500 Received: ${issue.received}`);
1346
+ });
1347
+ }
1348
+ consola.error("Response data:", response);
1349
+ if (typeof window !== "undefined" && error instanceof Error && "issues" in error) {
1350
+ try {
1351
+ const event = new CustomEvent("zod-validation-error", {
1352
+ detail: {
1353
+ operation: "getPaymentsPaymentsStatusRetrieve",
1354
+ path: "/cfg/payments/payments/{id}/status/",
1355
+ method: "GET",
1356
+ error,
1357
+ response,
1358
+ timestamp: /* @__PURE__ */ new Date()
1359
+ },
1360
+ bubbles: true,
1361
+ cancelable: false
1362
+ });
1363
+ window.dispatchEvent(event);
1364
+ } catch (eventError) {
1365
+ consola.warn("Failed to dispatch validation error event:", eventError);
1366
+ }
1367
+ }
1368
+ throw error;
1369
+ }
1370
+ }
1371
+ async function createPaymentsPaymentsCreateCreate(data, client) {
1372
+ const api = client || getAPIInstance();
1373
+ const response = await api.ext_payments_payments.paymentsCreateCreate(data);
1374
+ try {
1375
+ return PaymentCreateResponseSchema.parse(response);
1376
+ } catch (error) {
1377
+ consola.error("\u274C Zod Validation Failed");
1378
+ consola.box(`createPaymentsPaymentsCreateCreate
1379
+ Path: /cfg/payments/payments/create/
1380
+ Method: POST`);
1381
+ if (error instanceof Error && "issues" in error && Array.isArray(error.issues)) {
1382
+ consola.error("Validation Issues:");
1383
+ error.issues.forEach((issue, index) => {
1384
+ consola.error(` ${index + 1}. ${issue.path.join(".") || "root"}`);
1385
+ consola.error(` \u251C\u2500 Message: ${issue.message}`);
1386
+ if (issue.expected) consola.error(` \u251C\u2500 Expected: ${issue.expected}`);
1387
+ if (issue.received) consola.error(` \u2514\u2500 Received: ${issue.received}`);
1388
+ });
1389
+ }
1390
+ consola.error("Response data:", response);
1391
+ if (typeof window !== "undefined" && error instanceof Error && "issues" in error) {
1392
+ try {
1393
+ const event = new CustomEvent("zod-validation-error", {
1394
+ detail: {
1395
+ operation: "createPaymentsPaymentsCreateCreate",
1396
+ path: "/cfg/payments/payments/create/",
1397
+ method: "POST",
1398
+ error,
1399
+ response,
1400
+ timestamp: /* @__PURE__ */ new Date()
1401
+ },
1402
+ bubbles: true,
1403
+ cancelable: false
1404
+ });
1405
+ window.dispatchEvent(event);
1406
+ } catch (eventError) {
1407
+ consola.warn("Failed to dispatch validation error event:", eventError);
1408
+ }
1409
+ }
1410
+ throw error;
1411
+ }
1412
+ }
1413
+ async function getPaymentsTransactionsList(params, client) {
1414
+ const api = client || getAPIInstance();
1415
+ const response = await api.ext_payments_payments.transactionsList(params?.limit, params?.offset, params?.type);
1416
+ return response;
1417
+ }
1418
+ async function getPaymentsWithdrawalsList(params, client) {
1419
+ const api = client || getAPIInstance();
1420
+ const response = await api.ext_payments_payments.withdrawalsList(params?.page, params?.page_size);
1421
+ try {
1422
+ return PaginatedWithdrawalListListSchema.parse(response);
1423
+ } catch (error) {
1424
+ consola.error("\u274C Zod Validation Failed");
1425
+ consola.box(`getPaymentsWithdrawalsList
1426
+ Path: /cfg/payments/withdrawals/
1427
+ Method: GET`);
1428
+ if (error instanceof Error && "issues" in error && Array.isArray(error.issues)) {
1429
+ consola.error("Validation Issues:");
1430
+ error.issues.forEach((issue, index) => {
1431
+ consola.error(` ${index + 1}. ${issue.path.join(".") || "root"}`);
1432
+ consola.error(` \u251C\u2500 Message: ${issue.message}`);
1433
+ if (issue.expected) consola.error(` \u251C\u2500 Expected: ${issue.expected}`);
1434
+ if (issue.received) consola.error(` \u2514\u2500 Received: ${issue.received}`);
1435
+ });
1436
+ }
1437
+ consola.error("Response data:", response);
1438
+ if (typeof window !== "undefined" && error instanceof Error && "issues" in error) {
1439
+ try {
1440
+ const event = new CustomEvent("zod-validation-error", {
1441
+ detail: {
1442
+ operation: "getPaymentsWithdrawalsList",
1443
+ path: "/cfg/payments/withdrawals/",
1444
+ method: "GET",
1445
+ error,
1446
+ response,
1447
+ timestamp: /* @__PURE__ */ new Date()
1448
+ },
1449
+ bubbles: true,
1450
+ cancelable: false
1451
+ });
1452
+ window.dispatchEvent(event);
1453
+ } catch (eventError) {
1454
+ consola.warn("Failed to dispatch validation error event:", eventError);
1455
+ }
1456
+ }
1457
+ throw error;
1458
+ }
1459
+ }
1460
+ async function getPaymentsWithdrawalsRetrieve(id, client) {
1461
+ const api = client || getAPIInstance();
1462
+ const response = await api.ext_payments_payments.withdrawalsRetrieve(id);
1463
+ try {
1464
+ return WithdrawalDetailSchema.parse(response);
1465
+ } catch (error) {
1466
+ consola.error("\u274C Zod Validation Failed");
1467
+ consola.box(`getPaymentsWithdrawalsRetrieve
1468
+ Path: /cfg/payments/withdrawals/{id}/
1469
+ Method: GET`);
1470
+ if (error instanceof Error && "issues" in error && Array.isArray(error.issues)) {
1471
+ consola.error("Validation Issues:");
1472
+ error.issues.forEach((issue, index) => {
1473
+ consola.error(` ${index + 1}. ${issue.path.join(".") || "root"}`);
1474
+ consola.error(` \u251C\u2500 Message: ${issue.message}`);
1475
+ if (issue.expected) consola.error(` \u251C\u2500 Expected: ${issue.expected}`);
1476
+ if (issue.received) consola.error(` \u2514\u2500 Received: ${issue.received}`);
1477
+ });
1478
+ }
1479
+ consola.error("Response data:", response);
1480
+ if (typeof window !== "undefined" && error instanceof Error && "issues" in error) {
1481
+ try {
1482
+ const event = new CustomEvent("zod-validation-error", {
1483
+ detail: {
1484
+ operation: "getPaymentsWithdrawalsRetrieve",
1485
+ path: "/cfg/payments/withdrawals/{id}/",
1486
+ method: "GET",
1487
+ error,
1488
+ response,
1489
+ timestamp: /* @__PURE__ */ new Date()
1490
+ },
1491
+ bubbles: true,
1492
+ cancelable: false
1493
+ });
1494
+ window.dispatchEvent(event);
1495
+ } catch (eventError) {
1496
+ consola.warn("Failed to dispatch validation error event:", eventError);
1497
+ }
1498
+ }
1499
+ throw error;
1500
+ }
1501
+ }
1502
+ async function createPaymentsWithdrawalsCancelCreate(id, client) {
1503
+ const api = client || getAPIInstance();
1504
+ const response = await api.ext_payments_payments.withdrawalsCancelCreate(id);
1505
+ try {
1506
+ return WithdrawalCancelResponseSchema.parse(response);
1507
+ } catch (error) {
1508
+ consola.error("\u274C Zod Validation Failed");
1509
+ consola.box(`createPaymentsWithdrawalsCancelCreate
1510
+ Path: /cfg/payments/withdrawals/{id}/cancel/
1511
+ Method: POST`);
1512
+ if (error instanceof Error && "issues" in error && Array.isArray(error.issues)) {
1513
+ consola.error("Validation Issues:");
1514
+ error.issues.forEach((issue, index) => {
1515
+ consola.error(` ${index + 1}. ${issue.path.join(".") || "root"}`);
1516
+ consola.error(` \u251C\u2500 Message: ${issue.message}`);
1517
+ if (issue.expected) consola.error(` \u251C\u2500 Expected: ${issue.expected}`);
1518
+ if (issue.received) consola.error(` \u2514\u2500 Received: ${issue.received}`);
1519
+ });
1520
+ }
1521
+ consola.error("Response data:", response);
1522
+ if (typeof window !== "undefined" && error instanceof Error && "issues" in error) {
1523
+ try {
1524
+ const event = new CustomEvent("zod-validation-error", {
1525
+ detail: {
1526
+ operation: "createPaymentsWithdrawalsCancelCreate",
1527
+ path: "/cfg/payments/withdrawals/{id}/cancel/",
1528
+ method: "POST",
1529
+ error,
1530
+ response,
1531
+ timestamp: /* @__PURE__ */ new Date()
1532
+ },
1533
+ bubbles: true,
1534
+ cancelable: false
1535
+ });
1536
+ window.dispatchEvent(event);
1537
+ } catch (eventError) {
1538
+ consola.warn("Failed to dispatch validation error event:", eventError);
1539
+ }
1540
+ }
1541
+ throw error;
1542
+ }
1543
+ }
1544
+ async function createPaymentsWithdrawalsCreateCreate(data, client) {
1545
+ const api = client || getAPIInstance();
1546
+ const response = await api.ext_payments_payments.withdrawalsCreateCreate(data);
1547
+ try {
1548
+ return WithdrawalCreateResponseSchema.parse(response);
1549
+ } catch (error) {
1550
+ consola.error("\u274C Zod Validation Failed");
1551
+ consola.box(`createPaymentsWithdrawalsCreateCreate
1552
+ Path: /cfg/payments/withdrawals/create/
1553
+ Method: POST`);
1554
+ if (error instanceof Error && "issues" in error && Array.isArray(error.issues)) {
1555
+ consola.error("Validation Issues:");
1556
+ error.issues.forEach((issue, index) => {
1557
+ consola.error(` ${index + 1}. ${issue.path.join(".") || "root"}`);
1558
+ consola.error(` \u251C\u2500 Message: ${issue.message}`);
1559
+ if (issue.expected) consola.error(` \u251C\u2500 Expected: ${issue.expected}`);
1560
+ if (issue.received) consola.error(` \u2514\u2500 Received: ${issue.received}`);
1561
+ });
1562
+ }
1563
+ consola.error("Response data:", response);
1564
+ if (typeof window !== "undefined" && error instanceof Error && "issues" in error) {
1565
+ try {
1566
+ const event = new CustomEvent("zod-validation-error", {
1567
+ detail: {
1568
+ operation: "createPaymentsWithdrawalsCreateCreate",
1569
+ path: "/cfg/payments/withdrawals/create/",
1570
+ method: "POST",
1571
+ error,
1572
+ response,
1573
+ timestamp: /* @__PURE__ */ new Date()
1574
+ },
1575
+ bubbles: true,
1576
+ cancelable: false
1577
+ });
1578
+ window.dispatchEvent(event);
1579
+ } catch (eventError) {
1580
+ consola.warn("Failed to dispatch validation error event:", eventError);
1581
+ }
1582
+ }
1583
+ throw error;
1584
+ }
1585
+ }
1586
+
1587
+ // src/api/generated/ext_payments/_utils/hooks/ext_payments__payments.ts
1588
+ function usePaymentsBalanceRetrieve(client) {
1589
+ return useSWR(
1590
+ "cfg-payments-balance",
1591
+ () => getPaymentsBalanceRetrieve(client)
1592
+ );
1593
+ }
1594
+ function usePaymentsCurrenciesList(client) {
1595
+ return useSWR(
1596
+ "cfg-payments-currencies",
1597
+ () => getPaymentsCurrenciesList(client)
1598
+ );
1599
+ }
1600
+ function usePaymentsCurrenciesEstimateRetrieve(code, params, client) {
1601
+ return useSWR(
1602
+ ["cfg-payments-currencies-estimate", code],
1603
+ () => getPaymentsCurrenciesEstimateRetrieve(code, params, client)
1604
+ );
1605
+ }
1606
+ function usePaymentsCurrenciesWithdrawalEstimateRetrieve(code, params, client) {
1607
+ return useSWR(
1608
+ ["cfg-payments-currencies-withdrawal-estimate", code],
1609
+ () => getPaymentsCurrenciesWithdrawalEstimateRetrieve(code, params, client)
1610
+ );
1611
+ }
1612
+ function usePaymentsPaymentsList(params, client) {
1613
+ return useSWR(
1614
+ params ? ["cfg-payments-payments", params] : "cfg-payments-payments",
1615
+ () => getPaymentsPaymentsList(params, client)
1616
+ );
1617
+ }
1618
+ function usePaymentsPaymentsRetrieve(id, client) {
1619
+ return useSWR(
1620
+ ["cfg-payments-payment", id],
1621
+ () => getPaymentsPaymentsRetrieve(id, client)
1622
+ );
1623
+ }
1624
+ function useCreatePaymentsPaymentsConfirmCreate() {
1625
+ const { mutate } = useSWRConfig();
1626
+ return async (id, client) => {
1627
+ const result = await createPaymentsPaymentsConfirmCreate(id, client);
1628
+ mutate("cfg-payments-payments-confirm");
1629
+ return result;
1630
+ };
1631
+ }
1632
+ function usePaymentsPaymentsStatusRetrieve(id, client) {
1633
+ return useSWR(
1634
+ ["cfg-payments-payments-statu", id],
1635
+ () => getPaymentsPaymentsStatusRetrieve(id, client)
1636
+ );
1637
+ }
1638
+ function useCreatePaymentsPaymentsCreateCreate() {
1639
+ const { mutate } = useSWRConfig();
1640
+ return async (data, client) => {
1641
+ const result = await createPaymentsPaymentsCreateCreate(data, client);
1642
+ mutate("cfg-payments-payments");
1643
+ return result;
1644
+ };
1645
+ }
1646
+ function usePaymentsTransactionsList(params, client) {
1647
+ return useSWR(
1648
+ params ? ["cfg-payments-transactions", params] : "cfg-payments-transactions",
1649
+ () => getPaymentsTransactionsList(params, client)
1650
+ );
1651
+ }
1652
+ function usePaymentsWithdrawalsList(params, client) {
1653
+ return useSWR(
1654
+ params ? ["cfg-payments-withdrawals", params] : "cfg-payments-withdrawals",
1655
+ () => getPaymentsWithdrawalsList(params, client)
1656
+ );
1657
+ }
1658
+ function usePaymentsWithdrawalsRetrieve(id, client) {
1659
+ return useSWR(
1660
+ ["cfg-payments-withdrawal", id],
1661
+ () => getPaymentsWithdrawalsRetrieve(id, client)
1662
+ );
1663
+ }
1664
+ function useCreatePaymentsWithdrawalsCancelCreate() {
1665
+ const { mutate } = useSWRConfig();
1666
+ return async (id, client) => {
1667
+ const result = await createPaymentsWithdrawalsCancelCreate(id, client);
1668
+ mutate("cfg-payments-withdrawals-cancel");
1669
+ return result;
1670
+ };
1671
+ }
1672
+ function useCreatePaymentsWithdrawalsCreateCreate() {
1673
+ const { mutate } = useSWRConfig();
1674
+ return async (data, client) => {
1675
+ const result = await createPaymentsWithdrawalsCreateCreate(data, client);
1676
+ mutate("cfg-payments-withdrawals");
1677
+ return result;
1678
+ };
1679
+ }
1680
+
1681
+ export { useCreatePaymentsPaymentsConfirmCreate, useCreatePaymentsPaymentsCreateCreate, useCreatePaymentsWithdrawalsCancelCreate, useCreatePaymentsWithdrawalsCreateCreate, usePaymentsBalanceRetrieve, usePaymentsCurrenciesEstimateRetrieve, usePaymentsCurrenciesList, usePaymentsCurrenciesWithdrawalEstimateRetrieve, usePaymentsPaymentsList, usePaymentsPaymentsRetrieve, usePaymentsPaymentsStatusRetrieve, usePaymentsTransactionsList, usePaymentsWithdrawalsList, usePaymentsWithdrawalsRetrieve };