28 lines
1.2 KiB
PHP
28 lines
1.2 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use Brick\Math\BigDecimal;
|
|
use Brick\Math\RoundingMode;
|
|
|
|
/** Native cumulative price/VAT calculation shared by order preparation and invoice matching. */
|
|
final class PurchaseLineAmounts
|
|
{
|
|
/** @return array{subtotal_minor:int,tax_minor:int,total_minor:int} */
|
|
public static function portion(int $unitPrice, string $taxRate, int $beforeMilli, int $quantityMilli): array
|
|
{
|
|
if ($unitPrice < 0 || $beforeMilli < 0 || $quantityMilli < 1 || $beforeMilli > PHP_INT_MAX - $quantityMilli
|
|
|| BigDecimal::of($taxRate)->isNegative()) {
|
|
throw new \InvalidArgumentException('Base cumulativa da linha inválida.');
|
|
}
|
|
$subtotal = fn (int $milli) => BigDecimal::of($milli)->multipliedBy($unitPrice)->dividedBy(1000, 0, RoundingMode::HalfUp)->toInt();
|
|
$tax = fn (int $minor) => BigDecimal::of($minor)->multipliedBy($taxRate)->dividedBy(100, 0, RoundingMode::HalfUp)->toInt();
|
|
$before = $subtotal($beforeMilli);
|
|
$after = $subtotal($beforeMilli + $quantityMilli);
|
|
$net = $after - $before;
|
|
$vat = $tax($after) - $tax($before);
|
|
|
|
return ['subtotal_minor' => $net, 'tax_minor' => $vat, 'total_minor' => $net + $vat];
|
|
}
|
|
}
|