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:
2026-11-26 16:18:59 +02:00
co-authored by Claude Sonnet 5.5
parent 361a2974cf
commit 30132deb0e
81 changed files with 4968 additions and 115 deletions
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Domain\Services;
/**
* Matches stock items to a search typed on a keyboard or touch screen, or
* read by a barcode scanner: every word of the search must be found in the
* name or the code, regardless of case and of the dots of å, ä and ö
* (spec 19.6).
*/
final class StockSearch
{
public static function matches(string $search, string $name, ?string $code): bool
{
$words = preg_split('/\s+/u', self::normalize($search), -1, PREG_SPLIT_NO_EMPTY) ?: [];
$haystack = self::normalize($name.' '.($code ?? ''));
foreach ($words as $word) {
if (! str_contains($haystack, $word)) {
return false;
}
}
return true;
}
public static function normalize(string $value): string
{
return strtr(mb_strtolower(trim($value)), ['å' => 'a', 'ä' => 'a', 'ö' => 'o', 'é' => 'e', 'ü' => 'u']);
}
}
@@ -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);
}
}