@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
namespace Tempo\Purchasing\Composition;
|
||||
|
||||
use Closure;
|
||||
use LogicException;
|
||||
|
||||
/** Transaction-scoped evidence supplied by the host runtime, never a permission grant. */
|
||||
final class ExecutionContext
|
||||
{
|
||||
public const CONTRACT = 'COMPRAS-SGF-EXECUTION-v1';
|
||||
|
||||
private ?array $frame = null;
|
||||
|
||||
public function within(array $declaration, object $connection, Closure $verify, Closure $work): mixed
|
||||
{
|
||||
if ($this->frame !== null) {
|
||||
throw new LogicException('COMPOSITION_NESTED_EXECUTION');
|
||||
}
|
||||
self::validate($declaration);
|
||||
$verify();
|
||||
$this->frame = [$declaration, $connection, $verify];
|
||||
try {
|
||||
return $work();
|
||||
} finally {
|
||||
$this->frame = null;
|
||||
}
|
||||
}
|
||||
|
||||
public function allows(string $feature, object $connection): bool
|
||||
{
|
||||
if ($this->frame === null || $this->frame[1] !== $connection) {
|
||||
return false;
|
||||
}
|
||||
($this->frame[2])(); // Re-read identity, context, permissions, pins and schema.
|
||||
|
||||
return array_key_exists($feature, $this->frame[0]['features']);
|
||||
}
|
||||
|
||||
public function component(string $feature, object $connection): array
|
||||
{
|
||||
if (! $this->allows($feature, $connection)) {
|
||||
throw new LogicException('COMPOSITION_CAPABILITY_ABSENT');
|
||||
}
|
||||
|
||||
return $this->frame[0]['features'][$feature];
|
||||
}
|
||||
|
||||
public function permits(string $operation, object $connection): bool
|
||||
{
|
||||
$feature = str_starts_with($operation, 'purchasing_conflicts.') ? 'conflict-release'
|
||||
: (str_starts_with($operation, 'purchasing_order_cancellations.') ? 'order-cancellation-cycles' : null);
|
||||
|
||||
return $feature !== null && $this->allows($feature, $connection) && $this->frame[0]['operation'] === $operation;
|
||||
}
|
||||
|
||||
private static function validate(array $declaration): void
|
||||
{
|
||||
$keys = array_keys($declaration);
|
||||
sort($keys);
|
||||
if ($keys !== ['actor', 'composition', 'contract', 'features', 'generation', 'operation', 'schema_sha256', 'scope', 'workflow_sha256']
|
||||
|| $declaration['contract'] !== self::CONTRACT
|
||||
|| ! is_string($declaration['composition']) || ! preg_match('/^[a-f0-9]{12}$/D', $declaration['composition'])) {
|
||||
throw new LogicException('COMPOSITION_CONTRACT');
|
||||
}
|
||||
if (! is_string($declaration['operation']) || ! preg_match('/^[a-z][a-z0-9_]*(?:\.[a-z0-9_]+)+$/D', $declaration['operation'])) {
|
||||
throw new LogicException('COMPOSITION_OPERATION');
|
||||
}
|
||||
foreach (['generation', 'schema_sha256', 'workflow_sha256'] as $field) {
|
||||
if (! is_string($declaration[$field]) || ! preg_match('/^[a-f0-9]{64}$/D', $declaration[$field])) {
|
||||
throw new LogicException('COMPOSITION_HASH');
|
||||
}
|
||||
}
|
||||
foreach (['scope' => ['tenant_id', 'company_id', 'unit_id'], 'actor' => ['host_id', 'native_id']] as $field => $expected) {
|
||||
if (! is_array($declaration[$field]) || count($declaration[$field]) !== count($expected)
|
||||
|| array_diff($expected, array_keys($declaration[$field]))) {
|
||||
throw new LogicException('COMPOSITION_SCOPE');
|
||||
}
|
||||
foreach ($declaration[$field] as $id) {
|
||||
if (! is_int($id) || $id < 1) {
|
||||
throw new LogicException('COMPOSITION_SCOPE');
|
||||
}
|
||||
}
|
||||
}
|
||||
if (! is_array($declaration['features']) || array_diff(array_keys($declaration['features']), ['conflict-release', 'order-cancellation-cycles'])) {
|
||||
throw new LogicException('COMPOSITION_FEATURE');
|
||||
}
|
||||
foreach ($declaration['features'] as $feature => $component) {
|
||||
if ($feature === 'conflict-release' && $component !== []) {
|
||||
if (! is_array($component) || array_keys($component) !== ['company_view', 'company_authorise']
|
||||
|| ! is_bool($component['company_view']) || ! is_bool($component['company_authorise'])) {
|
||||
throw new LogicException('COMPOSITION_FEATURE');
|
||||
}
|
||||
}
|
||||
if ($feature === 'order-cancellation-cycles'
|
||||
&& (! is_array($component) || array_keys($component) !== ['root', 'manifest_sha256']
|
||||
|| ! is_string($component['root']) || trim($component['root']) === ''
|
||||
|| ! is_string($component['manifest_sha256']) || ! preg_match('/^[a-f0-9]{64}$/D', $component['manifest_sha256']))) {
|
||||
throw new LogicException('COMPOSITION_COMPONENT');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -52,8 +52,9 @@ final class StockCosting
|
||||
throw new \DomainException('Opening value without stock is inconsistent.');
|
||||
}
|
||||
$layers = [];
|
||||
$origins = [];
|
||||
$head = 0;
|
||||
if ($method === 'fifo') {
|
||||
if ($method === 'fifo' || ($opening['layers'] ?? []) !== []) {
|
||||
$sumQuantity = 0;
|
||||
$sumValue = BigRational::of(0);
|
||||
foreach ($opening['layers'] ?? [] as $layer) {
|
||||
@@ -64,12 +65,22 @@ final class StockCosting
|
||||
}
|
||||
$sumQuantity += $q;
|
||||
$sumValue = $sumValue->plus($v);
|
||||
$layers[] = ['quantity_milli' => $q, 'value' => $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) {
|
||||
@@ -86,9 +97,50 @@ final class StockCosting
|
||||
}
|
||||
$quantity += $q;
|
||||
$value = $value->plus($amount);
|
||||
if ($method === 'fifo') {
|
||||
$layers[] = ['quantity_milli' => $q, 'value' => $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.');
|
||||
@@ -102,6 +154,9 @@ final class StockCosting
|
||||
} 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);
|
||||
@@ -122,10 +177,20 @@ final class StockCosting
|
||||
}
|
||||
$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,
|
||||
|
||||
Reference in New Issue
Block a user