-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreporting-service.php
More file actions
1133 lines (991 loc) · 39.9 KB
/
Copy pathreporting-service.php
File metadata and controls
1133 lines (991 loc) · 39.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
/**
* Global Payments Reporting Service
*
* This service class provides comprehensive reporting functionality for
* Global Payments transactions including search, filtering, and data export.
*
* PHP version 7.4 or higher
*
* @category Reporting
* @package GlobalPayments_Reporting
* @author Global Payments
* @license MIT License
* @link https://github.com/globalpayments
*/
require_once 'vendor/autoload.php';
require_once 'sdk-config.php';
use GlobalPayments\Api\Services\ReportingService;
use GlobalPayments\Api\Entities\Reporting\SearchCriteria;
use GlobalPayments\Api\Entities\Reporting\TransactionReportBuilder;
use GlobalPayments\Api\Entities\Enums\PaymentType;
use GlobalPayments\Api\Entities\Enums\TransactionStatus;
use GlobalPayments\Api\Entities\Exceptions\ApiException;
/**
* Global Payments Reporting Service Class
*
* Provides methods for transaction reporting, searching, and data export
* using the Global Payments SDK reporting capabilities.
*/
class GlobalPaymentsReportingService
{
/**
* @var bool Indicates if the SDK is configured
*/
private bool $isConfigured = false;
/**
* Constructor - Initialize and configure the SDK
*
* @throws \InvalidArgumentException If configuration fails
*/
public function __construct()
{
try {
configureGpApiSdk();
$this->isConfigured = true;
} catch (\Exception $e) {
throw new \InvalidArgumentException('Failed to configure SDK: ' . $e->getMessage());
}
}
/**
* Search transactions with filters and pagination
*
* @param array $filters Search filters and pagination parameters
* @return array Transaction search results
* @throws ApiException If the search request fails
*/
public function searchTransactions(array $filters = []): array
{
$this->ensureConfigured();
try {
$reportBuilder = ReportingService::findTransactionsPaged(
$filters['page'] ?? 1,
$filters['page_size'] ?? 10
);
// Apply date range filters
if (!empty($filters['start_date'])) {
$reportBuilder->withStartDate(\DateTime::createFromFormat('Y-m-d', $filters['start_date']));
}
if (!empty($filters['end_date'])) {
$reportBuilder->withEndDate(\DateTime::createFromFormat('Y-m-d', $filters['end_date']));
}
// Apply transaction ID filter
if (!empty($filters['transaction_id'])) {
$reportBuilder->withTransactionId($filters['transaction_id']);
}
// Apply payment type filter
if (!empty($filters['payment_type'])) {
$paymentType = $this->mapPaymentType($filters['payment_type']);
if ($paymentType) {
$reportBuilder->withPaymentType($paymentType);
}
}
// Apply status filter - let the SDK handle string status values
if (!empty($filters['status'])) {
// For now, we'll filter results after retrieval since SDK enum mapping is complex
// $reportBuilder->withTransactionStatus($filters['status']);
}
// Apply amount range filters
if (!empty($filters['amount_min'])) {
$reportBuilder->withAmount($filters['amount_min']);
}
if (!empty($filters['amount_max'])) {
$reportBuilder->withAmount($filters['amount_max']);
}
// Apply card number filter (last 4 digits)
if (!empty($filters['card_last_four'])) {
$reportBuilder->withCardNumberLastFour($filters['card_last_four']);
}
// Execute the search
$response = $reportBuilder->execute();
$transactions = $this->formatTransactionList($response->result ?? []);
// Apply client-side filtering for status if needed
if (!empty($filters['status'])) {
$statusFilter = strtoupper($filters['status']);
$transactions = array_filter($transactions, function($transaction) use ($statusFilter) {
return strtoupper($transaction['status']) === $statusFilter;
});
$transactions = array_values($transactions); // Re-index array
}
return [
'success' => true,
'data' => [
'transactions' => $transactions,
'pagination' => [
'page' => $filters['page'] ?? 1,
'page_size' => $filters['page_size'] ?? 10,
'total_count' => count($transactions),
'original_total_count' => $response->totalRecordCount ?? 0
]
],
'timestamp' => date('Y-m-d H:i:s')
];
} catch (ApiException $e) {
throw new ApiException('Transaction search failed: ' . $e->getMessage());
}
}
/**
* Get detailed information for a specific transaction
*
* @param string $transactionId The transaction ID to retrieve
* @return array Transaction details
* @throws ApiException If the transaction cannot be found
*/
public function getTransactionDetails(string $transactionId): array
{
$this->ensureConfigured();
try {
$reportBuilder = ReportingService::transactionDetail($transactionId);
$response = $reportBuilder->execute();
if (!$response) {
throw new ApiException('Transaction not found');
}
return [
'success' => true,
'data' => $this->formatTransactionDetails($response),
'timestamp' => date('Y-m-d H:i:s')
];
} catch (ApiException $e) {
throw new ApiException('Failed to retrieve transaction details: ' . $e->getMessage());
}
}
/**
* Generate settlement report for a date range
*
* @param array $params Report parameters
* @return array Settlement report data
* @throws ApiException If the report generation fails
*/
public function getSettlementReport(array $params = []): array
{
$this->ensureConfigured();
try {
$reportBuilder = ReportingService::findSettlementTransactionsPaged(
$params['page'] ?? 1,
$params['page_size'] ?? 50
);
// Apply date range
if (!empty($params['start_date'])) {
$reportBuilder->withStartDate(\DateTime::createFromFormat('Y-m-d', $params['start_date']));
}
if (!empty($params['end_date'])) {
$reportBuilder->withEndDate(\DateTime::createFromFormat('Y-m-d', $params['end_date']));
}
$response = $reportBuilder->execute();
return [
'success' => true,
'data' => [
'settlements' => $this->formatSettlementList($response->result ?? []),
'summary' => $this->generateSettlementSummary($response->result ?? []),
'pagination' => [
'page' => $params['page'] ?? 1,
'page_size' => $params['page_size'] ?? 50,
'total_count' => $response->totalRecordCount ?? 0
]
],
'timestamp' => date('Y-m-d H:i:s')
];
} catch (ApiException $e) {
throw new ApiException('Settlement report generation failed: ' . $e->getMessage());
}
}
/**
* Get dispute reports with filtering and pagination
*
* @param array $filters Dispute search filters and pagination
* @return array Dispute report results
* @throws ApiException If the dispute search fails
*/
public function getDisputeReport(array $filters = []): array
{
$this->ensureConfigured();
try {
$reportBuilder = ReportingService::findDisputesPaged(
$filters['page'] ?? 1,
$filters['page_size'] ?? 10
);
// Apply date range filters
if (!empty($filters['start_date'])) {
$reportBuilder->withStartDate(\DateTime::createFromFormat('Y-m-d', $filters['start_date']));
}
if (!empty($filters['end_date'])) {
$reportBuilder->withEndDate(\DateTime::createFromFormat('Y-m-d', $filters['end_date']));
}
// Apply dispute stage filter
if (!empty($filters['stage'])) {
$reportBuilder->withDisputeStage($filters['stage']);
}
// Apply dispute status filter
if (!empty($filters['status'])) {
$reportBuilder->withDisputeStatus($filters['status']);
}
// Execute the search
$response = $reportBuilder->execute();
return [
'success' => true,
'data' => [
'disputes' => $this->formatDisputeList($response->result ?? []),
'pagination' => [
'page' => $filters['page'] ?? 1,
'page_size' => $filters['page_size'] ?? 10,
'total_count' => $response->totalRecordCount ?? 0
]
],
'timestamp' => date('Y-m-d H:i:s')
];
} catch (ApiException $e) {
throw new ApiException('Dispute report generation failed: ' . $e->getMessage());
}
}
/**
* Get detailed information for a specific dispute
*
* @param string $disputeId The dispute ID to retrieve
* @return array Dispute details
* @throws ApiException If the dispute cannot be found
*/
public function getDisputeDetails(string $disputeId): array
{
$this->ensureConfigured();
try {
$reportBuilder = ReportingService::disputeDetail($disputeId);
$response = $reportBuilder->execute();
if (!$response) {
throw new ApiException('Dispute not found');
}
return [
'success' => true,
'data' => $this->formatDisputeDetails($response),
'timestamp' => date('Y-m-d H:i:s')
];
} catch (ApiException $e) {
throw new ApiException('Failed to retrieve dispute details: ' . $e->getMessage());
}
}
/**
* Get deposit reports with filtering and pagination
*
* @param array $filters Deposit search filters and pagination
* @return array Deposit report results
* @throws ApiException If the deposit search fails
*/
public function getDepositReport(array $filters = []): array
{
$this->ensureConfigured();
try {
$reportBuilder = ReportingService::findDepositsPaged(
$filters['page'] ?? 1,
$filters['page_size'] ?? 10
);
// Apply date range filters
if (!empty($filters['start_date'])) {
$reportBuilder->withStartDate(\DateTime::createFromFormat('Y-m-d', $filters['start_date']));
}
if (!empty($filters['end_date'])) {
$reportBuilder->withEndDate(\DateTime::createFromFormat('Y-m-d', $filters['end_date']));
}
// Apply deposit ID filter
if (!empty($filters['deposit_id'])) {
$reportBuilder->withDepositReference($filters['deposit_id']);
}
// Apply status filter
if (!empty($filters['status'])) {
$reportBuilder->withDepositStatus($filters['status']);
}
// Execute the search
$response = $reportBuilder->execute();
return [
'success' => true,
'data' => [
'deposits' => $this->formatDepositList($response->result ?? []),
'pagination' => [
'page' => $filters['page'] ?? 1,
'page_size' => $filters['page_size'] ?? 10,
'total_count' => $response->totalRecordCount ?? 0
]
],
'timestamp' => date('Y-m-d H:i:s')
];
} catch (ApiException $e) {
throw new ApiException('Deposit report generation failed: ' . $e->getMessage());
}
}
/**
* Get detailed information for a specific deposit
*
* @param string $depositId The deposit ID to retrieve
* @return array Deposit details
* @throws ApiException If the deposit cannot be found
*/
public function getDepositDetails(string $depositId): array
{
$this->ensureConfigured();
try {
$reportBuilder = ReportingService::depositDetail($depositId);
$response = $reportBuilder->execute();
if (!$response) {
throw new ApiException('Deposit not found');
}
return [
'success' => true,
'data' => $this->formatDepositDetails($response),
'timestamp' => date('Y-m-d H:i:s')
];
} catch (ApiException $e) {
throw new ApiException('Failed to retrieve deposit details: ' . $e->getMessage());
}
}
/**
* Get batch report with detailed transaction information
*
* @param array $filters Batch search filters
* @return array Batch report results
* @throws ApiException If the batch search fails
*/
public function getBatchReport(array $filters = []): array
{
$this->ensureConfigured();
try {
$reportBuilder = ReportingService::batchDetail();
// Apply date range filters
if (!empty($filters['start_date'])) {
$reportBuilder->withStartDate(\DateTime::createFromFormat('Y-m-d', $filters['start_date']));
}
if (!empty($filters['end_date'])) {
$reportBuilder->withEndDate(\DateTime::createFromFormat('Y-m-d', $filters['end_date']));
}
// Execute the search
$response = $reportBuilder->execute();
return [
'success' => true,
'data' => [
'batches' => $this->formatBatchList($response->result ?? []),
'summary' => $this->generateBatchSummary($response->result ?? [])
],
'timestamp' => date('Y-m-d H:i:s')
];
} catch (ApiException $e) {
throw new ApiException('Batch report generation failed: ' . $e->getMessage());
}
}
/**
* Get declined transactions report
*
* @param array $filters Decline search filters and pagination
* @return array Declined transactions report
* @throws ApiException If the search fails
*/
public function getDeclinedTransactionsReport(array $filters = []): array
{
$this->ensureConfigured();
try {
// Use transaction search with declined status filter
$declineFilters = array_merge($filters, ['status' => 'DECLINED']);
$result = $this->searchTransactions($declineFilters);
// Add decline analysis
if ($result['success']) {
$result['data']['decline_analysis'] = $this->analyzeDeclines($result['data']['transactions']);
}
return $result;
} catch (ApiException $e) {
throw new ApiException('Declined transactions report generation failed: ' . $e->getMessage());
}
}
/**
* Get comprehensive date range report across all transaction types
*
* @param array $params Date range and report parameters
* @return array Comprehensive date range report
*/
public function getDateRangeReport(array $params = []): array
{
$this->ensureConfigured();
try {
$startDate = $params['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
$endDate = $params['end_date'] ?? date('Y-m-d');
$report = [
'success' => true,
'data' => [
'period' => [
'start_date' => $startDate,
'end_date' => $endDate
],
'transactions' => [],
'settlements' => [],
'disputes' => [],
'deposits' => [],
'summary' => []
],
'timestamp' => date('Y-m-d H:i:s')
];
// Get transactions for the period
$transactionResult = $this->searchTransactions([
'start_date' => $startDate,
'end_date' => $endDate,
'page_size' => $params['transaction_limit'] ?? 100
]);
if ($transactionResult['success']) {
$report['data']['transactions'] = $transactionResult['data'];
}
// Get settlements for the period
$settlementResult = $this->getSettlementReport([
'start_date' => $startDate,
'end_date' => $endDate,
'page_size' => $params['settlement_limit'] ?? 50
]);
if ($settlementResult['success']) {
$report['data']['settlements'] = $settlementResult['data'];
}
// Get disputes for the period
try {
$disputeResult = $this->getDisputeReport([
'start_date' => $startDate,
'end_date' => $endDate,
'page_size' => $params['dispute_limit'] ?? 25
]);
if ($disputeResult['success']) {
$report['data']['disputes'] = $disputeResult['data'];
}
} catch (ApiException $e) {
$report['data']['disputes'] = ['error' => 'Disputes not available: ' . $e->getMessage()];
}
// Get deposits for the period
try {
$depositResult = $this->getDepositReport([
'start_date' => $startDate,
'end_date' => $endDate,
'page_size' => $params['deposit_limit'] ?? 25
]);
if ($depositResult['success']) {
$report['data']['deposits'] = $depositResult['data'];
}
} catch (ApiException $e) {
$report['data']['deposits'] = ['error' => 'Deposits not available: ' . $e->getMessage()];
}
// Generate comprehensive summary
$report['data']['summary'] = $this->generateComprehensiveSummary($report['data']);
return $report;
} catch (\Exception $e) {
return [
'success' => false,
'error' => 'Failed to generate date range report: ' . $e->getMessage(),
'timestamp' => date('Y-m-d H:i:s')
];
}
}
/**
* Export transaction data in specified format
*
* @param array $filters Search filters
* @param string $format Export format ('json' or 'csv')
* @return array Export data
* @throws ApiException If export fails
*/
public function exportTransactions(array $filters = [], string $format = 'json'): array
{
$this->ensureConfigured();
try {
// Get all transactions (remove pagination for export)
$exportFilters = $filters;
$exportFilters['page_size'] = 1000; // Increased limit for export
$transactions = $this->searchTransactions($exportFilters);
if ($format === 'csv') {
return $this->exportToCsv($transactions['data']['transactions']);
}
return [
'success' => true,
'data' => $transactions['data']['transactions'],
'format' => 'json',
'timestamp' => date('Y-m-d H:i:s')
];
} catch (ApiException $e) {
throw new ApiException('Export failed: ' . $e->getMessage());
}
}
/**
* Get reporting summary statistics
*
* @param array $params Summary parameters
* @return array Summary statistics
*/
public function getSummaryStats(array $params = []): array
{
$this->ensureConfigured();
try {
$startDate = $params['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
$endDate = $params['end_date'] ?? date('Y-m-d');
// Get transaction summary
$transactions = $this->searchTransactions([
'start_date' => $startDate,
'end_date' => $endDate,
'page_size' => 1000
]);
return [
'success' => true,
'data' => $this->calculateSummaryStats($transactions['data']['transactions']),
'period' => [
'start_date' => $startDate,
'end_date' => $endDate
],
'timestamp' => date('Y-m-d H:i:s')
];
} catch (\Exception $e) {
return [
'success' => false,
'error' => 'Failed to generate summary statistics: ' . $e->getMessage(),
'timestamp' => date('Y-m-d H:i:s')
];
}
}
/**
* Ensure SDK is properly configured
*
* @throws \RuntimeException If SDK is not configured
*/
private function ensureConfigured(): void
{
if (!$this->isConfigured) {
throw new \RuntimeException('SDK is not properly configured');
}
}
/**
* Map payment type string to PaymentType enum
*
* @param string $type Payment type string
* @return PaymentType|null Mapped payment type or null
*/
private function mapPaymentType(string $type): ?PaymentType
{
$mapping = [
'sale' => PaymentType::SALE,
'refund' => PaymentType::REFUND,
'authorize' => PaymentType::AUTH,
'capture' => PaymentType::CAPTURE
];
return $mapping[strtolower($type)] ?? null;
}
/**
* Map transaction status string to TransactionStatus enum
*
* @param string $status Status string
* @return TransactionStatus|null Mapped status or null
*/
private function mapTransactionStatus(string $status): ?TransactionStatus
{
// Don't map for now - the SDK may not have all these constants defined
// Let the SDK handle the status filtering internally
return null;
}
/**
* Format transaction list for API response
*
* @param array $transactions Raw transaction data
* @return array Formatted transaction list
*/
private function formatTransactionList(array $transactions): array
{
return array_map(function($transaction) {
return [
'transaction_id' => $transaction->transactionId ?? '',
'timestamp' => $transaction->transactionDate ?? '',
'amount' => $transaction->amount ?? 0,
'currency' => $transaction->currency ?? 'USD',
'status' => $transaction->transactionStatus ?? '',
'payment_method' => $transaction->paymentType ?? '',
'card_last_four' => $transaction->maskedCardNumber ?? '',
'auth_code' => $transaction->authCode ?? '',
'reference_number' => $transaction->referenceNumber ?? ''
];
}, $transactions);
}
/**
* Format detailed transaction information
*
* @param mixed $transaction Raw transaction detail data
* @return array Formatted transaction details
*/
private function formatTransactionDetails($transaction): array
{
return [
'transaction_id' => $transaction->transactionId ?? '',
'timestamp' => $transaction->transactionDate ?? '',
'amount' => $transaction->amount ?? 0,
'currency' => $transaction->currency ?? 'USD',
'status' => $transaction->transactionStatus ?? '',
'payment_method' => $transaction->paymentType ?? '',
'card_details' => [
'masked_number' => $transaction->maskedCardNumber ?? '',
'card_type' => $transaction->cardType ?? '',
'entry_mode' => $transaction->entryMode ?? ''
],
'auth_code' => $transaction->authCode ?? '',
'reference_number' => $transaction->referenceNumber ?? '',
'gateway_response_code' => $transaction->gatewayResponseCode ?? '',
'gateway_response_message' => $transaction->gatewayResponseMessage ?? ''
];
}
/**
* Format settlement list for API response
*
* @param array $settlements Raw settlement data
* @return array Formatted settlement list
*/
private function formatSettlementList(array $settlements): array
{
return array_map(function($settlement) {
return [
'settlement_id' => $settlement->settlementId ?? '',
'settlement_date' => $settlement->settlementDate ?? '',
'transaction_count' => $settlement->transactionCount ?? 0,
'total_amount' => $settlement->totalAmount ?? 0,
'currency' => $settlement->currency ?? 'USD',
'status' => $settlement->status ?? ''
];
}, $settlements);
}
/**
* Generate settlement summary statistics
*
* @param array $settlements Raw settlement data
* @return array Settlement summary
*/
private function generateSettlementSummary(array $settlements): array
{
$totalAmount = 0;
$totalTransactions = 0;
foreach ($settlements as $settlement) {
$totalAmount += $settlement->totalAmount ?? 0;
$totalTransactions += $settlement->transactionCount ?? 0;
}
return [
'total_settlements' => count($settlements),
'total_amount' => $totalAmount,
'total_transactions' => $totalTransactions,
'average_settlement_amount' => count($settlements) > 0 ? $totalAmount / count($settlements) : 0
];
}
/**
* Calculate summary statistics from transaction data
*
* @param array $transactions Transaction data
* @return array Summary statistics
*/
private function calculateSummaryStats(array $transactions): array
{
$totalAmount = 0;
$statusCounts = [];
$paymentTypeCounts = [];
foreach ($transactions as $transaction) {
$totalAmount += $transaction['amount'] ?? 0;
$status = $transaction['status'] ?? 'unknown';
$statusCounts[$status] = ($statusCounts[$status] ?? 0) + 1;
$paymentType = $transaction['payment_method'] ?? 'unknown';
$paymentTypeCounts[$paymentType] = ($paymentTypeCounts[$paymentType] ?? 0) + 1;
}
return [
'total_transactions' => count($transactions),
'total_amount' => $totalAmount,
'average_amount' => count($transactions) > 0 ? $totalAmount / count($transactions) : 0,
'status_breakdown' => $statusCounts,
'payment_type_breakdown' => $paymentTypeCounts
];
}
/**
* Export transaction data to CSV format
*
* @param array $transactions Transaction data
* @return array CSV export data
*/
private function exportToCsv(array $transactions): array
{
$csvData = "Transaction ID,Timestamp,Amount,Currency,Status,Payment Method,Card Last Four,Auth Code,Reference Number\n";
foreach ($transactions as $transaction) {
// Format timestamp for CSV export
$timestamp = $transaction['timestamp'] ?? '';
if (is_object($timestamp) && method_exists($timestamp, 'format')) {
$timestamp = $timestamp->format('Y-m-d H:i:s');
} elseif (is_array($timestamp) && isset($timestamp['date'])) {
$timestamp = $timestamp['date'];
}
$csvData .= sprintf(
"%s,%s,%s,%s,%s,%s,%s,%s,%s\n",
$transaction['transaction_id'] ?? '',
$timestamp,
$transaction['amount'] ?? '',
$transaction['currency'] ?? '',
$transaction['status'] ?? '',
$transaction['payment_method'] ?? '',
$transaction['card_last_four'] ?? '',
$transaction['auth_code'] ?? '',
$transaction['reference_number'] ?? ''
);
}
return [
'success' => true,
'data' => $csvData,
'format' => 'csv',
'filename' => 'transactions_' . date('Y-m-d_H-i-s') . '.csv',
'timestamp' => date('Y-m-d H:i:s')
];
}
/**
* Format dispute list for API response
*
* @param array $disputes Raw dispute data
* @return array Formatted dispute list
*/
private function formatDisputeList(array $disputes): array
{
return array_map(function($dispute) {
return [
'dispute_id' => $dispute->caseId ?? '',
'transaction_id' => $dispute->transactionId ?? '',
'case_number' => $dispute->caseNumber ?? '',
'dispute_stage' => $dispute->caseStage ?? '',
'dispute_status' => $dispute->caseStatus ?? '',
'case_amount' => $dispute->caseAmount ?? 0,
'currency' => $dispute->caseCurrency ?? 'USD',
'reason_code' => $dispute->reasonCode ?? '',
'reason_description' => $dispute->reason ?? '',
'case_time' => $dispute->caseTime ?? '',
'last_adjustment_time' => $dispute->lastAdjustmentTime ?? ''
];
}, $disputes);
}
/**
* Format detailed dispute information
*
* @param mixed $dispute Raw dispute detail data
* @return array Formatted dispute details
*/
private function formatDisputeDetails($dispute): array
{
return [
'dispute_id' => $dispute->caseId ?? '',
'transaction_id' => $dispute->transactionId ?? '',
'case_number' => $dispute->caseNumber ?? '',
'dispute_stage' => $dispute->caseStage ?? '',
'dispute_status' => $dispute->caseStatus ?? '',
'case_amount' => $dispute->caseAmount ?? 0,
'currency' => $dispute->caseCurrency ?? 'USD',
'reason_code' => $dispute->reasonCode ?? '',
'reason_description' => $dispute->reason ?? '',
'case_time' => $dispute->caseTime ?? '',
'last_adjustment_time' => $dispute->lastAdjustmentTime ?? '',
'case_description' => $dispute->caseDescription ?? '',
'documents' => $dispute->documents ?? [],
'transaction_details' => [
'amount' => $dispute->transactionAmount ?? 0,
'currency' => $dispute->transactionCurrency ?? 'USD',
'masked_card_number' => $dispute->transactionMaskedCardNumber ?? '',
'arn' => $dispute->transactionARN ?? ''
]
];
}
/**
* Format deposit list for API response
*
* @param array $deposits Raw deposit data
* @return array Formatted deposit list
*/
private function formatDepositList(array $deposits): array
{
return array_map(function($deposit) {
return [
'deposit_id' => $deposit->depositId ?? '',
'deposit_date' => $deposit->depositDate ?? '',
'deposit_reference' => $deposit->depositReference ?? '',
'deposit_status' => $deposit->status ?? '',
'deposit_amount' => $deposit->amount ?? 0,
'currency' => $deposit->currency ?? 'USD',
'merchant_number' => $deposit->merchantNumber ?? '',
'merchant_hierarchy' => $deposit->merchantHierarchy ?? '',
'sales_count' => $deposit->salesCount ?? 0,
'sales_amount' => $deposit->salesAmount ?? 0,
'refunds_count' => $deposit->refundsCount ?? 0,
'refunds_amount' => $deposit->refundsAmount ?? 0
];
}, $deposits);
}
/**
* Format detailed deposit information
*
* @param mixed $deposit Raw deposit detail data
* @return array Formatted deposit details
*/
private function formatDepositDetails($deposit): array
{
return [
'deposit_id' => $deposit->depositId ?? '',
'deposit_date' => $deposit->depositDate ?? '',
'deposit_reference' => $deposit->depositReference ?? '',
'deposit_status' => $deposit->status ?? '',
'deposit_amount' => $deposit->amount ?? 0,
'currency' => $deposit->currency ?? 'USD',
'merchant_number' => $deposit->merchantNumber ?? '',
'merchant_hierarchy' => $deposit->merchantHierarchy ?? '',
'bank_account' => [
'masked_account_number' => $deposit->maskedAccountNumber ?? '',
'bank_name' => $deposit->bankName ?? ''
],
'transaction_summary' => [
'sales_count' => $deposit->salesCount ?? 0,
'sales_amount' => $deposit->salesAmount ?? 0,
'refunds_count' => $deposit->refundsCount ?? 0,
'refunds_amount' => $deposit->refundsAmount ?? 0,
'chargebacks_count' => $deposit->chargebacksCount ?? 0,
'chargebacks_amount' => $deposit->chargebacksAmount ?? 0,
'adjustments_count' => $deposit->adjustmentsCount ?? 0,
'adjustments_amount' => $deposit->adjustmentsAmount ?? 0
]
];
}
/**
* Format batch list for API response
*
* @param array $batches Raw batch data
* @return array Formatted batch list
*/
private function formatBatchList(array $batches): array
{
return array_map(function($batch) {
return [
'batch_id' => $batch->batchId ?? '',
'sequence_number' => $batch->sequenceNumber ?? '',
'transaction_count' => $batch->transactionCount ?? 0,
'total_amount' => $batch->totalAmount ?? 0,
'currency' => $batch->currency ?? 'USD',
'batch_status' => $batch->batchStatus ?? '',
'close_time' => $batch->closeTime ?? '',
'open_time' => $batch->openTime ?? ''
];
}, $batches);
}
/**
* Generate batch summary statistics
*
* @param array $batches Raw batch data
* @return array Batch summary
*/
private function generateBatchSummary(array $batches): array
{
$totalAmount = 0;
$totalTransactions = 0;
$batchStatuses = [];
foreach ($batches as $batch) {