45 lines
1.0 KiB
PHP
45 lines
1.0 KiB
PHP
<?php
|
|
|
|
namespace App\Support;
|
|
|
|
use App\Models\Invoice;
|
|
|
|
class VatCalculator
|
|
{
|
|
public static function refresh(Invoice $invoice): Invoice
|
|
{
|
|
if ($invoice->vat_number) {
|
|
return $invoice;
|
|
}
|
|
|
|
$tax = self::taxFor($invoice);
|
|
|
|
if ((int) $invoice->tax !== $tax) {
|
|
$invoice->forceFill(['tax' => $tax])->saveQuietly();
|
|
}
|
|
|
|
return $invoice;
|
|
}
|
|
|
|
public static function taxFor(Invoice $invoice): int
|
|
{
|
|
$items = $invoice->invoiceItems()->with('product:id,product_type')->get();
|
|
$gross = (int) $items->sum('total_price');
|
|
|
|
if ($gross <= 0) {
|
|
return 0;
|
|
}
|
|
|
|
$payable = min((int) $invoice->total, $gross);
|
|
$tax = 0.0;
|
|
|
|
foreach ($items as $item) {
|
|
$rate = VatSettings::rateFor($item->product?->product_type);
|
|
$share = $payable * ((int) $item->total_price / $gross);
|
|
$tax += $share * $rate / (100 + $rate);
|
|
}
|
|
|
|
return (int) round($tax);
|
|
}
|
|
}
|