Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

InvoiceTotalViewModel.php 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. namespace App\View\Models;
  3. use App\Models\Accounting\Adjustment;
  4. use App\Models\Accounting\Document;
  5. use App\Utilities\Currency\CurrencyConverter;
  6. class InvoiceTotalViewModel
  7. {
  8. public function __construct(
  9. public ?Document $invoice,
  10. public ?array $data = null
  11. ) {}
  12. public function buildViewData(): array
  13. {
  14. $lineItems = collect($this->data['lineItems'] ?? []);
  15. $subtotal = $lineItems->sum(fn ($item) => ($item['quantity'] ?? 0) * ($item['unit_price'] ?? 0));
  16. $taxTotal = $lineItems->reduce(function ($carry, $item) {
  17. $quantity = $item['quantity'] ?? 0;
  18. $unitPrice = $item['unit_price'] ?? 0;
  19. $salesTaxes = $item['salesTaxes'] ?? [];
  20. $lineTotal = $quantity * $unitPrice;
  21. $taxAmount = Adjustment::whereIn('id', $salesTaxes)
  22. ->pluck('rate')
  23. ->sum(fn ($rate) => $lineTotal * ($rate / 100));
  24. return $carry + $taxAmount;
  25. }, 0);
  26. $discountTotal = $lineItems->reduce(function ($carry, $item) {
  27. $quantity = $item['quantity'] ?? 0;
  28. $unitPrice = $item['unit_price'] ?? 0;
  29. $salesDiscounts = $item['salesDiscounts'] ?? [];
  30. $lineTotal = $quantity * $unitPrice;
  31. $discountAmount = Adjustment::whereIn('id', $salesDiscounts)
  32. ->pluck('rate')
  33. ->sum(fn ($rate) => $lineTotal * ($rate / 100));
  34. return $carry + $discountAmount;
  35. }, 0);
  36. $grandTotal = $subtotal + ($taxTotal - $discountTotal);
  37. $subTotalFormatted = CurrencyConverter::formatToMoney($subtotal);
  38. $taxTotalFormatted = CurrencyConverter::formatToMoney($taxTotal);
  39. $discountTotalFormatted = CurrencyConverter::formatToMoney($discountTotal);
  40. $grandTotalFormatted = CurrencyConverter::formatToMoney($grandTotal);
  41. return [
  42. 'subtotal' => $subTotalFormatted,
  43. 'taxTotal' => $taxTotalFormatted,
  44. 'discountTotal' => $discountTotalFormatted,
  45. 'grandTotal' => $grandTotalFormatted,
  46. ];
  47. }
  48. }