-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathInvoiceController.php
More file actions
726 lines (628 loc) · 30.3 KB
/
Copy pathInvoiceController.php
File metadata and controls
726 lines (628 loc) · 30.3 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
<?php
namespace Fleetbase\Ledger\Http\Controllers\Internal\v1;
use Fleetbase\Ledger\DTO\RefundRequest;
use Fleetbase\Ledger\Http\Controllers\LedgerResourceController;
use Fleetbase\Ledger\Http\Resources\v1\Invoice as InvoiceResource;
use Fleetbase\Ledger\Http\Resources\v1\Transaction as TransactionResource;
use Fleetbase\Ledger\Models\GatewayTransaction;
use Fleetbase\Ledger\Models\Invoice;
use Fleetbase\Ledger\Models\InvoiceItem;
use Fleetbase\Ledger\Models\Transaction;
use Fleetbase\Ledger\Notifications\RefundUriAvailable;
use Fleetbase\Ledger\Services\InvoiceService;
use Fleetbase\Ledger\Services\PaymentService;
use Fleetbase\Ledger\Services\TalerRefundVerificationService;
use Fleetbase\Services\TemplateRenderService;
use Fleetbase\Support\Utils;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
class InvoiceController extends LedgerResourceController
{
/**
* The resource to query.
*
* @var string
*/
public $resource = 'invoice';
// -------------------------------------------------------------------------
// Lifecycle hooks — called automatically by HasApiControllerBehavior
// -------------------------------------------------------------------------
/**
* Called after a new invoice record is persisted.
* Syncs the nested items array and recalculates totals.
*
* Signature expected by getControllerCallback(): ($request, $record, $input)
*/
public function onAfterCreate(Request $request, Invoice $record, array $input): void
{
$this->_syncItems($record, data_get($input, 'items', []));
$record->calculateTotals();
$record->save();
// Recognise revenue now that totals are finalised (Debit AR, Credit Revenue)
app(InvoiceService::class)->recogniseRevenue($record);
$record = app(InvoiceService::class)->autoSendOnCreation($record);
$record->load(['customer', 'items', 'template']);
}
/**
* Called after an existing invoice record is updated.
* Syncs the nested items array and recalculates totals.
*
* Signature expected by getControllerCallback(): ($request, $record, $input)
*/
public function onAfterUpdate(Request $request, Invoice $record, array $input): void
{
// Use $input (the extracted payload from the 'invoice' key) rather than
// $request->input('items') which looks at the top-level request body and
// returns null because items are nested under invoice.items.
$this->_syncItems($record, data_get($input, 'items', []));
$record->calculateTotals();
$record->save();
$record->load(['customer', 'items', 'template']);
}
// -------------------------------------------------------------------------
// Custom endpoints
// -------------------------------------------------------------------------
/**
* Create an invoice from an existing order.
*/
public function createFromOrder(Request $request): InvoiceResource
{
$request->validate([
'order_uuid' => 'required|string|exists:orders,uuid',
]);
$order = \Fleetbase\FleetOps\Models\Order::where('company_uuid', session('company'))
->where('uuid', $request->input('order_uuid'))
->firstOrFail();
$invoice = app(InvoiceService::class)->createFromOrder($order);
return new InvoiceResource($invoice->load(['customer', 'items', 'template']));
}
/**
* Record a payment against an invoice.
*/
public function recordPayment(string $id, Request $request): InvoiceResource
{
$request->validate([
'amount' => 'required|integer|min:1',
'payment_method' => 'nullable|string',
'reference' => 'nullable|string',
]);
$invoice = Invoice::where('company_uuid', session('company'))
->where(fn ($q) => $q->where('uuid', $id)->orWhere('public_id', $id))
->firstOrFail();
$invoice = app(InvoiceService::class)->recordPayment($invoice, $request->input('amount'), [
'payment_method' => $request->input('payment_method', 'manual'),
'reference' => $request->input('reference'),
]);
return new InvoiceResource($invoice->load(['customer', 'items', 'template']));
}
/**
* List transactions related to an invoice.
*/
public function transactions(string $id, Request $request)
{
$invoice = Invoice::where('company_uuid', session('company'))
->where(fn ($q) => $q->where('uuid', $id)->orWhere('public_id', $id))
->firstOrFail();
$transactions = Transaction::where('company_uuid', session('company'))
->where(function ($query) use ($invoice) {
$query->where('subject_uuid', $invoice->uuid)
->orWhere('context_uuid', $invoice->uuid);
if ($invoice->transaction_uuid) {
$query->orWhere('uuid', $invoice->transaction_uuid);
}
})
->with([
'items',
'journal.debitAccount',
'journal.creditAccount',
'subject',
'payer',
'payee',
'initiator',
'context',
])
->orderBy('created_at', $request->input('sort') === 'created_at' ? 'asc' : 'desc')
->paginate($request->integer('limit', 50));
TransactionResource::wrap('transactions');
return TransactionResource::collection($transactions);
}
/**
* Return gateway payments on this invoice that can still be refunded.
*/
public function refundOptions(string $id, Request $request): JsonResponse
{
$invoice = $this->resolveInvoice($id);
$options = $this->refundableGatewayTransactions($invoice);
return response()->json([
'invoice' => [
'id' => $invoice->public_id,
'uuid' => $invoice->uuid,
'number' => $invoice->number,
'currency' => $invoice->currency,
'total_amount' => (int) $invoice->total_amount,
'amount_paid' => (int) $invoice->amount_paid,
'refunded_amount' => $this->invoiceRefundedAmount($invoice),
'remaining_refundable_amount' => $this->invoiceRemainingRefundableAmount($invoice),
],
'options' => $options,
'refunds' => $this->refundGatewayTransactions($invoice),
]);
}
/**
* Issue a refund against a refundable gateway payment on this invoice.
*/
public function refund(string $id, Request $request, PaymentService $paymentService): JsonResponse
{
$invoice = $this->resolveInvoice($id);
$request->validate([
'gateway_transaction_id' => 'required|string',
'amount' => 'required|integer|min:1',
'reason' => 'nullable|string|max:500',
]);
$options = collect($this->refundableGatewayTransactions($invoice));
$selected = $options->firstWhere('gateway_transaction_id', $request->input('gateway_transaction_id'));
if (!$selected) {
return response()->json(['error' => 'The selected payment cannot be refunded.'], 422);
}
$amount = $request->integer('amount');
$remainingInvoiceAmount = $this->invoiceRemainingRefundableAmount($invoice);
$remainingPaymentAmount = (int) data_get($selected, 'refundable_amount', 0);
$maxRefundableAmount = min($remainingInvoiceAmount, $remainingPaymentAmount);
if ($amount > $maxRefundableAmount) {
return response()->json([
'error' => 'Refund amount exceeds the remaining refundable amount.',
'remaining_refundable_amount' => $maxRefundableAmount,
], 422);
}
$refundKind = $amount >= $remainingInvoiceAmount ? 'full' : 'partial';
$response = $paymentService->refund(data_get($selected, 'gateway.id'), new RefundRequest(
gatewayTransactionId: data_get($selected, 'gateway_transaction_id'),
amount: $amount,
currency: $invoice->currency ?? data_get($selected, 'currency', 'USD'),
reason: $request->input('reason'),
invoiceUuid: $invoice->uuid,
metadata: [
'refund_kind' => $refundKind,
'invoice_uuid' => $invoice->uuid,
'invoice_public_id' => $invoice->public_id,
],
));
return response()->json([
'status' => $response->status,
'successful' => $response->successful,
'gateway_transaction_id' => $response->gatewayTransactionId,
'message' => $response->message,
'data' => $response->data,
'refund_kind' => $refundKind,
'refund' => $this->latestRefundGatewayTransaction($invoice, $response->gatewayTransactionId),
'invoice' => (new InvoiceResource($invoice->fresh(['customer', 'items', 'template'])))->resolve(),
], $response->isSuccessful() ? 200 : 422);
}
/**
* Mark an invoice as sent (without dispatching a notification).
*/
public function markAsSent(string $id, Request $request): InvoiceResource
{
$invoice = Invoice::where('company_uuid', session('company'))
->where(fn ($q) => $q->where('uuid', $id)->orWhere('public_id', $id))
->firstOrFail();
$invoice->markAsSent();
return new InvoiceResource($invoice);
}
/**
* Send an invoice to the customer via email and mark it as sent.
*/
public function send(string $id, Request $request): InvoiceResource|JsonResponse
{
$invoice = Invoice::where('company_uuid', session('company'))
->where(fn ($q) => $q->where('uuid', $id)->orWhere('public_id', $id))
->with('customer')
->firstOrFail();
try {
$invoice = app(InvoiceService::class)->send($invoice);
} catch (\InvalidArgumentException $e) {
return response()->json(['error' => $e->getMessage()], 422);
}
return new InvoiceResource($invoice->load(['customer', 'items', 'template']));
}
/**
* Email a customer-facing refund URI for a gateway refund.
*/
public function sendRefundUri(string $id, string $gatewayTransactionId, Request $request): JsonResponse
{
$request->validate([
'email' => 'nullable|email',
]);
$invoice = $this->resolveInvoice($id);
$refund = $this->resolveRefundGatewayTransaction($invoice, $gatewayTransactionId);
$uri = $this->refundUri($refund);
if (!$uri) {
return response()->json(['error' => 'This refund does not have a customer refund URI.'], 422);
}
$email = $request->input('email') ?: $this->customerEmail($invoice);
if (!$email) {
return response()->json(['error' => 'Invoice customer does not have a valid email address.'], 422);
}
Notification::route('mail', $email)->notify(new RefundUriAvailable($invoice, $refund, $uri));
return response()->json([
'ok' => true,
'message' => 'Refund URI sent to customer.',
'sent_to' => $email,
'refund' => $this->serializeRefundGatewayTransaction($refund),
]);
}
/**
* Manually verify whether a Taler refund has been accepted by the wallet.
*/
public function verifyRefundStatus(string $id, string $gatewayTransactionId, TalerRefundVerificationService $verifier): JsonResponse
{
$invoice = $this->resolveInvoice($id);
$refund = $this->resolveRefundGatewayTransaction($invoice, $gatewayTransactionId);
$result = $verifier->verifyRefund($refund);
return response()->json([
'ok' => ($result['status'] ?? null) !== 'error',
'result' => $result,
'refund' => $this->serializeRefundGatewayTransaction($refund->fresh(['gateway'])),
'invoice' => (new InvoiceResource($invoice->fresh(['customer', 'items', 'template'])))->resolve(),
], ($result['status'] ?? null) === 'error' ? 422 : 200);
}
/**
* Render the invoice using its assigned template and return the HTML.
*
* POST /invoices/{id}/preview
*/
public function preview(string $id, Request $request): JsonResponse
{
$invoice = $this->resolveInvoice($id);
$template = $invoice->template;
if (!$template) {
return response()->json(['error' => 'Invoice has no template assigned.'], 422);
}
// Normalise the context_type to 'invoice' so that variable paths like
// {invoice.number} resolve correctly. Templates created before this fix
// may have context_type = 'ledger-invoice' stored in the database, which
// would cause TemplateRenderService::buildContext() to key the context
// array as 'ledger-invoice' instead of 'invoice', breaking substitution.
$template = $this->normaliseTemplateContextType($template);
$html = app(TemplateRenderService::class)->renderToHtml($template, $invoice);
return response()->json(['html' => $html]);
}
/**
* Render the invoice to a PDF and stream it as a download.
*
* POST /invoices/{id}/render-pdf
*/
public function renderPdf(string $id, Request $request): Response
{
$invoice = $this->resolveInvoice($id);
$template = $invoice->template;
if (!$template) {
abort(422, 'Invoice has no template assigned.');
}
$template = $this->normaliseTemplateContextType($template);
$filename = $request->input('filename', 'invoice-' . ($invoice->number ?? $invoice->id));
$pdf = app(TemplateRenderService::class)->renderToPdf($template, $invoice);
return $pdf->download($filename . '.pdf');
}
// -------------------------------------------------------------------------
// Private helpers
// -------------------------------------------------------------------------
/**
* Return a template instance whose context_type is normalised to 'invoice'.
*
* TemplateRenderService::buildContext() uses $template->context_type as the
* top-level key in the variable context array. Variable paths registered
* by the Ledger package all use the 'invoice' namespace (e.g. {invoice.number}).
* Templates stored in the DB before this normalisation may have
* context_type = 'ledger-invoice', which would prevent substitution.
*
* We clone the model in-memory (without persisting) so the DB record is
* not affected.
*/
private function normaliseTemplateContextType(\Fleetbase\Models\Template $template): \Fleetbase\Models\Template
{
if ($template->context_type === 'invoice') {
return $template;
}
// Clone without touching the DB
$clone = clone $template;
$clone->context_type = 'invoice';
return $clone;
}
/**
* Resolve an invoice by UUID or public_id, eager-loading all relations.
*/
private function resolveInvoice(string $id): Invoice
{
return Invoice::where('company_uuid', session('company'))
->where(fn ($q) => $q->where('uuid', $id)->orWhere('public_id', $id))
->with(['customer', 'items', 'template'])
->firstOrFail();
}
private function invoiceRefundedAmount(Invoice $invoice): int
{
return (int) data_get($invoice->meta, 'refunded_amount', 0);
}
private function invoiceRemainingRefundableAmount(Invoice $invoice): int
{
return max(0, (int) $invoice->amount_paid - $this->invoiceRefundedAmount($invoice));
}
private function refundGatewayTransactions(Invoice $invoice): array
{
$lastRefundUuid = data_get($invoice->meta, 'last_refund_gateway_transaction_uuid');
$paymentReferences = $this->invoicePaymentReferences($invoice);
$coreRefundReferences = Transaction::where('company_uuid', $invoice->company_uuid)
->where('context_uuid', $invoice->uuid)
->where('type', 'gateway_refund')
->whereNotNull('reference')
->pluck('reference')
->filter()
->values();
return GatewayTransaction::query()
->with('gateway')
->where('company_uuid', $invoice->company_uuid)
->where('type', 'refund')
->where(function ($query) use ($invoice, $lastRefundUuid, $paymentReferences, $coreRefundReferences) {
$query->where('raw_response->invoice_uuid', $invoice->uuid)
->orWhere('raw_response->data->invoice_uuid', $invoice->uuid)
->orWhere('raw_response->metadata->invoice_uuid', $invoice->uuid);
if ($lastRefundUuid) {
$query->orWhere('uuid', $lastRefundUuid);
}
if ($coreRefundReferences->isNotEmpty()) {
$query->orWhereIn('uuid', $coreRefundReferences->all())
->orWhereIn('public_id', $coreRefundReferences->all())
->orWhereIn('gateway_reference_id', $coreRefundReferences->all());
}
if ($paymentReferences->isNotEmpty()) {
$query->orWhereIn('raw_response->original_gateway_reference_id', $paymentReferences->all())
->orWhereIn('raw_response->order_id', $paymentReferences->all())
->orWhereIn('raw_response->data->order_id', $paymentReferences->all());
}
})
->orderByDesc('created_at')
->get()
->map(fn (GatewayTransaction $transaction) => $this->serializeRefundGatewayTransaction($transaction))
->values()
->all();
}
private function resolveRefundGatewayTransaction(Invoice $invoice, string $gatewayTransactionId): GatewayTransaction
{
return GatewayTransaction::query()
->with('gateway')
->where('company_uuid', $invoice->company_uuid)
->where('type', 'refund')
->where(function ($query) use ($gatewayTransactionId) {
$query->where('uuid', $gatewayTransactionId)
->orWhere('public_id', $gatewayTransactionId)
->orWhere('gateway_reference_id', $gatewayTransactionId)
->orWhere('raw_response->original_gateway_reference_id', $gatewayTransactionId);
})
->where(function ($query) use ($invoice) {
$query->where('raw_response->invoice_uuid', $invoice->uuid)
->orWhere('raw_response->data->invoice_uuid', $invoice->uuid)
->orWhere('raw_response->metadata->invoice_uuid', $invoice->uuid);
})
->firstOrFail();
}
private function latestRefundGatewayTransaction(Invoice $invoice, ?string $gatewayReferenceId = null): ?array
{
$transaction = GatewayTransaction::query()
->with('gateway')
->where('company_uuid', $invoice->company_uuid)
->where('type', 'refund')
->where(function ($query) use ($invoice) {
$query->where('raw_response->invoice_uuid', $invoice->uuid)
->orWhere('raw_response->data->invoice_uuid', $invoice->uuid)
->orWhere('raw_response->metadata->invoice_uuid', $invoice->uuid);
})
->when($gatewayReferenceId, function ($query) use ($gatewayReferenceId) {
$query->where(function ($q) use ($gatewayReferenceId) {
$q->where('gateway_reference_id', $gatewayReferenceId)
->orWhere('raw_response->original_gateway_reference_id', $gatewayReferenceId);
});
})
->orderByDesc('created_at')
->first();
return $transaction ? $this->serializeRefundGatewayTransaction($transaction) : null;
}
private function serializeRefundGatewayTransaction(GatewayTransaction $transaction): array
{
$refundUri = $this->refundUri($transaction);
$handoffUrl = $refundUri ? $this->refundHandoffUrl($transaction) : null;
return [
'id' => $transaction->public_id ?? $transaction->uuid,
'uuid' => $transaction->uuid,
'gateway_transaction_id' => $transaction->gateway_reference_id,
'amount' => (int) $transaction->amount,
'currency' => $transaction->currency,
'status' => $transaction->status,
'refund_status' => $transaction->refund_status ?? data_get($transaction->raw_response, 'data.refund_status'),
'wallet_status' => data_get($transaction->raw_response, 'data.wallet_status'),
'refund_url' => $handoffUrl,
'refund_handoff_url' => $handoffUrl,
'taler_refund_uri' => $refundUri,
'created_at' => optional($transaction->created_at)->toISOString(),
'processed_at' => optional($transaction->processed_at)->toISOString(),
'refund_accepted_at' => optional($transaction->refund_accepted_at)->toISOString(),
'refund_expires_at' => optional($transaction->refund_expires_at)->toISOString(),
'gateway' => $transaction->gateway ? [
'id' => $transaction->gateway->public_id ?? $transaction->gateway->uuid,
'uuid' => $transaction->gateway->uuid,
'public_id' => $transaction->gateway->public_id,
'name' => $transaction->gateway->name,
'driver' => $transaction->gateway->driver,
] : null,
];
}
private function refundUri(GatewayTransaction $transaction): ?string
{
return data_get($transaction->raw_response, 'data.taler_refund_uri')
?: data_get($transaction->raw_response, 'data.refund_url')
?: data_get($transaction->raw_response, 'taler_refund_uri')
?: data_get($transaction->raw_response, 'refund_url');
}
private function refundHandoffUrl(GatewayTransaction $transaction): string
{
return Utils::consoleUrl('~/taler-refund', [
'id' => $transaction->public_id ?? $transaction->uuid,
]);
}
private function customerEmail(Invoice $invoice): ?string
{
$invoice->loadMissing('customer');
$customer = $invoice->customer;
return $customer?->email
?? $customer?->contact_email
?? $customer?->billing_email
?? null;
}
private function refundableGatewayTransactions(Invoice $invoice): array
{
if (in_array($invoice->status, ['draft', 'void', 'cancelled', 'refunded'], true)) {
return [];
}
$remainingInvoiceAmount = $this->invoiceRemainingRefundableAmount($invoice);
if ($remainingInvoiceAmount <= 0) {
return [];
}
$paymentReferences = $this->invoicePaymentReferences($invoice);
$gatewayTransactions = GatewayTransaction::query()
->with('gateway')
->where('company_uuid', $invoice->company_uuid)
->whereIn('type', ['purchase', 'webhook_event'])
->whereIn('status', ['succeeded', 'refunded'])
->where(function ($query) use ($invoice, $paymentReferences) {
$query->where('raw_response->invoice_uuid', $invoice->uuid)
->orWhere('raw_response->data->invoice_uuid', $invoice->uuid)
->orWhere('raw_response->metadata->invoice_uuid', $invoice->uuid);
if ($paymentReferences->isNotEmpty()) {
$query->orWhereIn('gateway_reference_id', $paymentReferences->all());
}
})
->orderByDesc('created_at')
->get()
->unique(fn (GatewayTransaction $transaction) => $transaction->gateway_uuid . ':' . $transaction->gateway_reference_id)
->values();
return $gatewayTransactions
->map(function (GatewayTransaction $transaction) use ($invoice, $remainingInvoiceAmount) {
$paidAmount = (int) ($transaction->amount ?: $invoice->amount_paid);
$refundedAmount = (int) GatewayTransaction::where('company_uuid', $invoice->company_uuid)
->where('gateway_uuid', $transaction->gateway_uuid)
->where('type', 'refund')
->whereNotIn('status', ['failed'])
->where(function ($query) use ($transaction) {
$query->where('gateway_reference_id', $transaction->gateway_reference_id)
->orWhere('raw_response->original_gateway_reference_id', $transaction->gateway_reference_id)
->orWhere('raw_response->order_id', $transaction->gateway_reference_id)
->orWhere('raw_response->data->order_id', $transaction->gateway_reference_id);
})
->sum('amount');
$remainingPaymentAmount = max(0, $paidAmount - $refundedAmount);
$refundableAmount = min($remainingInvoiceAmount, $remainingPaymentAmount);
if (!$transaction->gateway || $refundableAmount <= 0) {
return null;
}
return [
'id' => $transaction->public_id,
'uuid' => $transaction->uuid,
'gateway_transaction_id' => $transaction->gateway_reference_id,
'amount' => $paidAmount,
'currency' => $transaction->currency ?? $invoice->currency,
'refunded_amount' => $refundedAmount,
'refundable_amount' => $refundableAmount,
'status' => $transaction->status,
'created_at' => optional($transaction->created_at)->toISOString(),
'requires_customer_action' => $transaction->gateway->driver === 'taler',
'gateway' => [
'id' => $transaction->gateway->public_id ?? $transaction->gateway->uuid,
'uuid' => $transaction->gateway->uuid,
'public_id' => $transaction->gateway->public_id,
'name' => $transaction->gateway->name,
'driver' => $transaction->gateway->driver,
],
];
})
->filter()
->values()
->all();
}
private function invoicePaymentReferences(Invoice $invoice)
{
return Transaction::where('company_uuid', $invoice->company_uuid)
->where('context_uuid', $invoice->uuid)
->where('type', 'invoice_payment')
->whereNotNull('reference')
->pluck('reference')
->filter()
->values();
}
// -------------------------------------------------------------------------
// Item sync helper
// -------------------------------------------------------------------------
/**
* Upsert the nested line items array onto the given invoice.
*
* Strategy:
* 1. Collect the UUIDs present in the incoming payload.
* 2. Delete any existing items NOT in that set (removed by the user).
* 3. For each incoming item: update if UUID exists, create if not.
* 4. Call calculateAmount() on each item before saving.
*/
protected function _syncItems(Invoice $invoice, mixed $items): void
{
if (!is_array($items)) {
return;
}
// Validate that every item has a description
foreach ($items as $index => $itemData) {
$description = trim((string) data_get($itemData, 'description', ''));
if ($description === '') {
$line = $index + 1;
abort(422, "Line item {$line} is missing a description.");
}
}
$incomingUuids = [];
foreach ($items as $itemData) {
$uuid = data_get($itemData, 'uuid');
// Normalise client-side temporary IDs to null
if ($uuid && (Str::startsWith($uuid, '_new_') || Str::startsWith($uuid, '_tmp_'))) {
$uuid = null;
}
if ($uuid) {
$existing = InvoiceItem::where('uuid', $uuid)
->where('invoice_uuid', $invoice->uuid)
->first();
if ($existing) {
$existing->fill([
'description' => data_get($itemData, 'description'),
'quantity' => (int) data_get($itemData, 'quantity', 1),
'unit_price' => data_get($itemData, 'unit_price', 0),
'tax_rate' => data_get($itemData, 'tax_rate', 0),
]);
$existing->calculateAmount();
$existing->save();
$incomingUuids[] = $uuid;
}
} else {
$item = new InvoiceItem([
'invoice_uuid' => $invoice->uuid,
'description' => data_get($itemData, 'description'),
'quantity' => (int) data_get($itemData, 'quantity', 1),
'unit_price' => data_get($itemData, 'unit_price', 0),
'tax_rate' => data_get($itemData, 'tax_rate', 0),
]);
$item->calculateAmount();
$item->save();
$incomingUuids[] = $item->uuid;
}
}
// Remove items that were deleted in the form
$invoice->items()
->whereNotIn('uuid', $incomingUuids)
->delete();
}
}