201 lines
10 KiB
PHP
201 lines
10 KiB
PHP
<?php
|
|
|
|
namespace Tempo\Purchasing\Inventory;
|
|
|
|
use Brick\Math\BigRational;
|
|
use Brick\Math\RoundingMode;
|
|
|
|
/** Exact calculation over qualified facts. No stock balance or financial writer. */
|
|
final class StockCosting
|
|
{
|
|
public const METHODS = ['fifo', 'weighted_average'];
|
|
|
|
private static function integer(mixed $value, bool $positive = false): int
|
|
{
|
|
if (! is_int($value) || $value < ($positive ? 1 : 0)) {
|
|
throw new \InvalidArgumentException('Qualified integer quantity/value required.');
|
|
}
|
|
|
|
return $value;
|
|
}
|
|
|
|
/** @return array{numerator:string,denominator:string,amount_minor:?string,rounding_required:bool} */
|
|
private static function amount(BigRational $value): array
|
|
{
|
|
$numerator = $value->getNumerator();
|
|
$denominator = $value->getDenominator();
|
|
$gcd = $numerator->gcd($denominator);
|
|
$numerator = $numerator->quotient($gcd);
|
|
$denominator = $denominator->quotient($gcd);
|
|
$exact = $denominator->isEqualTo(1);
|
|
|
|
return ['numerator' => (string) $numerator, 'denominator' => (string) $denominator,
|
|
'amount_minor' => $exact ? (string) $numerator : null, 'rounding_required' => ! $exact];
|
|
}
|
|
|
|
/**
|
|
* @param array<string,mixed> $opening
|
|
* @param list<array<string,mixed>> $movements
|
|
* @return array<string,mixed>
|
|
*/
|
|
public static function project(string $method, array $opening, array $movements, ?string $rounding = null): array
|
|
{
|
|
if ($rounding !== null && $rounding !== 'half_up_final_balance') {
|
|
throw new \InvalidArgumentException('Unknown stock rounding policy.');
|
|
}
|
|
if (! in_array($method, self::METHODS, true) || ! is_string($opening['reference'] ?? null) || trim($opening['reference']) === '') {
|
|
throw new \InvalidArgumentException('Explicit method and qualified opening reference required.');
|
|
}
|
|
$quantity = self::integer($opening['quantity_milli'] ?? null);
|
|
$value = BigRational::of(self::integer($opening['value_minor'] ?? null));
|
|
if ($quantity === 0 && ! $value->isZero()) {
|
|
throw new \DomainException('Opening value without stock is inconsistent.');
|
|
}
|
|
$layers = [];
|
|
$origins = [];
|
|
$head = 0;
|
|
if ($method === 'fifo' || ($opening['layers'] ?? []) !== []) {
|
|
$sumQuantity = 0;
|
|
$sumValue = BigRational::of(0);
|
|
foreach ($opening['layers'] ?? [] as $layer) {
|
|
$q = self::integer($layer['quantity_milli'] ?? null, true);
|
|
$v = BigRational::of(self::integer($layer['value_minor'] ?? null));
|
|
if ($q > PHP_INT_MAX - $sumQuantity) {
|
|
throw new \OverflowException('Opening quantity too large.');
|
|
}
|
|
$sumQuantity += $q;
|
|
$sumValue = $sumValue->plus($v);
|
|
$reference = $layer['reference'] ?? (count($opening['layers'] ?? []) === 1 ? $opening['reference'] : null);
|
|
$layers[] = ['quantity_milli' => $q, 'value' => $v, 'reference' => $reference];
|
|
if (is_string($reference) && trim($reference) !== '') {
|
|
if (isset($origins[$reference])) {
|
|
throw new \DomainException('Duplicate opening receipt reference.');
|
|
}
|
|
$origins[$reference] = ['available_milli' => $q, 'unit_value' => $v->dividedBy($q)];
|
|
}
|
|
}
|
|
if ($sumQuantity !== $quantity || ! $sumValue->isEqualTo($value)) {
|
|
throw new \DomainException('FIFO opening requires reconciled historical layers.');
|
|
}
|
|
}
|
|
if ($method === 'weighted_average' && $quantity > 0 && ($opening['layers'] ?? []) === []) {
|
|
$origins[$opening['reference']] = ['available_milli' => $quantity, 'unit_value' => $value->dividedBy($quantity)];
|
|
}
|
|
$last = 0;
|
|
$results = [];
|
|
foreach ($movements as $movement) {
|
|
$id = self::integer($movement['id'] ?? null, true);
|
|
$q = self::integer($movement['quantity_milli'] ?? null, true);
|
|
if ($id <= $last || ! is_string($movement['reference'] ?? null) || trim($movement['reference']) === '') {
|
|
throw new \DomainException('Movements require unique ascending IDs and source references.');
|
|
}
|
|
$last = $id;
|
|
if (($movement['kind'] ?? null) === 'receipt') {
|
|
$amount = BigRational::of(self::integer($movement['value_minor'] ?? null));
|
|
if ($q > PHP_INT_MAX - $quantity) {
|
|
throw new \OverflowException('Stock quantity too large.');
|
|
}
|
|
$quantity += $q;
|
|
$value = $value->plus($amount);
|
|
if (isset($origins[$movement['reference']])) {
|
|
throw new \DomainException('Duplicate receipt reference.');
|
|
}
|
|
$origins[$movement['reference']] = ['available_milli' => $q, 'unit_value' => $amount->dividedBy($q)];
|
|
if ($method === 'fifo') {
|
|
$layers[] = ['quantity_milli' => $q, 'value' => $amount, 'reference' => $movement['reference']];
|
|
}
|
|
} elseif (($movement['kind'] ?? null) === 'receipt_return') {
|
|
$reference = $movement['receipt_reference'] ?? null;
|
|
if (! is_string($reference) || ! isset($origins[$reference]) || $q > $quantity) {
|
|
throw new \DomainException('An identified original receipt and sufficient stock are required.');
|
|
}
|
|
$amount = $origins[$reference]['unit_value']->multipliedBy($q);
|
|
if ($method === 'fifo') {
|
|
$index = null;
|
|
foreach ($layers as $key => $layer) {
|
|
if ($layer['reference'] === $reference) {
|
|
$index = $key;
|
|
break;
|
|
}
|
|
}
|
|
if ($index === null || $layers[$index]['quantity_milli'] < $q) {
|
|
throw new \DomainException('Original receipt layer already consumed; independently reconciled opening required.');
|
|
}
|
|
$layers[$index]['quantity_milli'] -= $q;
|
|
$layers[$index]['value'] = $layers[$index]['value']->minus($amount);
|
|
if ($layers[$index]['quantity_milli'] === 0) {
|
|
unset($layers[$index]);
|
|
}
|
|
} elseif ($origins[$reference]['available_milli'] < $q) {
|
|
throw new \DomainException('Original receipt availability is not proven after prior issues; independent reconciliation required.');
|
|
}
|
|
if ($rounding === 'half_up_final_balance') {
|
|
$amount = $q === $quantity ? $value : $amount->toScale(0, RoundingMode::HalfUp)->toBigRational();
|
|
}
|
|
if ($amount->isGreaterThan($value)) {
|
|
throw new \DomainException('Return exceeds remaining stock value; independent reconciliation required.');
|
|
}
|
|
if (array_key_exists('value_minor', $movement) && ! $amount->isEqualTo(self::integer($movement['value_minor']))) {
|
|
throw new \DomainException('Posted return differs from its original receipt cost; never revalue prior journals.');
|
|
}
|
|
$origins[$reference]['available_milli'] -= $q;
|
|
$quantity -= $q;
|
|
$value = $value->minus($amount);
|
|
} elseif (($movement['kind'] ?? null) === 'issue') {
|
|
if (array_key_exists('value_minor', $movement)) {
|
|
throw new \InvalidArgumentException('An issue cannot override its calculated cost.');
|
|
}
|
|
if ($q > $quantity) {
|
|
throw new \DomainException('Incomplete receipts/opening or insufficient stock; do not assume zero cost.');
|
|
}
|
|
$amount = BigRational::of(0);
|
|
if ($method === 'weighted_average') {
|
|
$amount = $value->multipliedBy($q)->dividedBy($quantity);
|
|
} else {
|
|
$remaining = $q;
|
|
while ($remaining > 0) {
|
|
while (! isset($layers[$head])) {
|
|
$head++;
|
|
}
|
|
$take = min($remaining, $layers[$head]['quantity_milli']);
|
|
$part = $layers[$head]['value']->multipliedBy($take)->dividedBy($layers[$head]['quantity_milli']);
|
|
$amount = $amount->plus($part);
|
|
$layers[$head]['quantity_milli'] -= $take;
|
|
$layers[$head]['value'] = $layers[$head]['value']->minus($part);
|
|
$remaining -= $take;
|
|
if ($layers[$head]['quantity_milli'] === 0) {
|
|
unset($layers[$head]);
|
|
$head++;
|
|
}
|
|
}
|
|
}
|
|
if ($rounding === 'half_up_final_balance') {
|
|
$amount = $q === $quantity ? $value : $amount->toScale(0, RoundingMode::HalfUp)->toBigRational();
|
|
if ($amount->isGreaterThan($value)) {
|
|
throw new \DomainException('Rounded cost exceeds the remaining value; reconcile the cost before posting.');
|
|
}
|
|
}
|
|
$quantity -= $q;
|
|
$value = $value->minus($amount);
|
|
if ($method === 'weighted_average') {
|
|
// Without qualified lot allocations no receipt may claim units already issued.
|
|
foreach ($origins as &$origin) {
|
|
$origin['available_milli'] = max(0, $origin['available_milli'] - $q);
|
|
}
|
|
unset($origin);
|
|
}
|
|
} else {
|
|
throw new \InvalidArgumentException('Unknown qualified movement kind.');
|
|
}
|
|
$results[] = ['id' => $id, 'reference' => $movement['reference'], 'kind' => $movement['kind'], 'quantity_milli' => $q, 'value' => self::amount($amount)];
|
|
if ($movement['kind'] === 'receipt_return') {
|
|
$results[array_key_last($results)]['receipt_reference'] = $movement['receipt_reference'];
|
|
}
|
|
}
|
|
|
|
return ['method' => $method, 'opening_reference' => $opening['reference'], 'movements' => $results,
|
|
'closing' => ['quantity_milli' => $quantity, 'value' => self::amount($value)],
|
|
'stock_written' => false, 'journals_written' => false];
|
|
}
|
|
}
|