Add stock items, groups and movements at a moving average cost
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
<?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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user