Files
Toiminnanohjaus/app/Modules/Inventory/Domain/Services/StockValuation.php
2026-11-26 16:18:59 +02:00

58 lines
2.0 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Services;
/**
* Valuation of stock at a moving average cost (liukuva keskihinta, spec
* 19.2). Unit costs are in hundredths of a cent per whole unit, so that
* cheap units such as a millilitre of ink keep their precision; values
* are in cents, rounded half away from zero.
*/
final class StockValuation
{
/**
* The value of a quantity (in thousandths) at a unit cost.
*/
public static function valueCents(int $quantityMilli, int $unitCostHundredths): int
{
return self::divideRounded($quantityMilli * $unitCostHundredths, 100_000);
}
/**
* The unit cost of a purchase of a quantity for a total value.
*/
public static function unitCostOf(int $quantityMilli, int $valueCents): int
{
return $quantityMilli === 0 ? 0 : self::divideRounded($valueCents * 100_000, $quantityMilli);
}
/**
* The average unit cost after a purchase: (old balance × old average +
* purchase value) / new balance. When the stock before was empty or
* negative, or nothing is left after, the purchase's own unit cost.
*/
public static function averageAfterPurchase(int $balanceMilli, int $averageHundredths, int $purchasedMilli, int $purchaseValueCents): int
{
$newBalance = $balanceMilli + $purchasedMilli;
if ($balanceMilli <= 0 || $newBalance <= 0) {
return max(0, self::unitCostOf($purchasedMilli, $purchaseValueCents));
}
$oldValueHundredthsMilli = $balanceMilli * $averageHundredths;
return max(0, self::divideRounded($oldValueHundredthsMilli + $purchaseValueCents * 100_000, $newBalance));
}
private static function divideRounded(int $dividend, int $divisor): int
{
$sign = ($dividend < 0) !== ($divisor < 0) ? -1 : 1;
$dividend = abs($dividend);
$divisor = abs($divisor);
return $sign * intdiv($dividend + intdiv($divisor, 2), $divisor);
}
}