@@ -0,0 +1,3 @@
|
||||
<?php
|
||||
require_once __DIR__.'/src/QuantityConversion.php';
|
||||
require_once __DIR__.'/src/ReceiptMovementWriter.php';
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"id": "tempo-inventory-receipt-write",
|
||||
"version": "0.2.0-rc.1",
|
||||
"contract": "COMPRAS-INVENTORY-CONVERSION-v1",
|
||||
"quantity_contract": "inventory.quantity.v1",
|
||||
"files": {
|
||||
"bootstrap.php": "e5fa526dfe94b4661031f1b03e54b6cbf43595782bdce222adb014519de43166",
|
||||
"src/ReceiptMovementWriter.php": "846528475b27aac95a087bb945597371f2189919b1306af7191648486515e47e",
|
||||
"src/QuantityConversion.php": "1b60cff2da44bcf35e863eabc1fa7ed0127625d9311785cf9c62a3e4bf3369b8"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace Tempo\Inventory;
|
||||
|
||||
use Brick\Math\BigInteger;
|
||||
use InvalidArgumentException;
|
||||
|
||||
/** Exact physical quantities; never prices or implicit unit assumptions. */
|
||||
final class QuantityConversion
|
||||
{
|
||||
public static function toBase(string $quantityMilli, string $numerator, string $denominator): string
|
||||
{
|
||||
foreach ([$quantityMilli, $numerator, $denominator] as $value) {
|
||||
if (!preg_match('/^\d{1,19}$/D', $value)) {
|
||||
throw new InvalidArgumentException('A quantidade e os termos do factor devem ser inteiros explícitos.');
|
||||
}
|
||||
}
|
||||
$quantity = BigInteger::of($quantityMilli);
|
||||
$top = BigInteger::of($numerator);
|
||||
$bottom = BigInteger::of($denominator);
|
||||
if ($top->isZero() || $bottom->isZero() || $quantity->isGreaterThan(PHP_INT_MAX)) {
|
||||
throw new InvalidArgumentException('Factor positivo e quantidade inteira suportada obrigatórios.');
|
||||
}
|
||||
[$converted, $remainder] = $quantity->multipliedBy($top)->quotientAndRemainder($bottom);
|
||||
if (!$remainder->isZero() || $converted->isGreaterThan(PHP_INT_MAX)) {
|
||||
throw new InvalidArgumentException('Quantidade física não representável em milésimos sem arredondamento.');
|
||||
}
|
||||
return (string)$converted;
|
||||
}
|
||||
|
||||
public static function fromBase(string $quantityMilli, string $numerator, string $denominator): string
|
||||
{
|
||||
return self::toBase($quantityMilli, $denominator, $numerator);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
namespace Tempo\Inventory;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
|
||||
/** Receipt effects only. Host owns receipt eligibility, company lock, lots and audit transaction. */
|
||||
final class ReceiptMovementWriter
|
||||
{
|
||||
public function __construct(private ConnectionInterface $db, private string $schema, private int $tenant, private int $actor, private Closure $authorize)
|
||||
{
|
||||
if(!preg_match('/^[a-z][a-z0-9_]{0,62}$/D',$schema)||$tenant<1||$actor<1)throw new \InvalidArgumentException('Invalid inventory context');
|
||||
}
|
||||
|
||||
public function preview(int $lineId): array
|
||||
{
|
||||
$this->checkHost();$facts=$this->facts($lineId,false);
|
||||
return ['source_hash'=>$this->hash($facts),'receipt_item_id'=>$lineId,'accepted_milli'=>(string)$facts['accepted_milli'],
|
||||
'stock_item_id'=>(int)$facts['stock_item_id'],'warehouse_id'=>(int)$facts['warehouse_id']];
|
||||
}
|
||||
|
||||
public function write(int $lineId, string $expectedHash): array
|
||||
{
|
||||
$this->checkHost();$facts=$this->facts($lineId,true);$hash=$this->hash($facts);
|
||||
abort_unless(hash_equals($hash,$expectedHash),409,'A origem da recepção mudou. Faça nova conferência.');
|
||||
$existing=$this->db->table($this->schema.'.stock_movements')->where(['tenant_id'=>$this->tenant,'goods_receipt_item_id'=>$lineId])->first();
|
||||
$stockQuantity=$this->stockQuantity($facts);
|
||||
if($existing){
|
||||
$snapshot=json_decode($existing->snapshot,true,512,JSON_THROW_ON_ERROR);
|
||||
abort_unless(($snapshot['inventory_source_hash']??null)===$hash && (string)$existing->quantity_milli===$stockQuantity
|
||||
&& (int)$existing->stock_item_id===(int)$facts['stock_item_id'] && (int)$existing->warehouse_id===(int)$facts['warehouse_id'],409,'A origem já tem movimento incompatível ou histórico não reconciliado.');
|
||||
return ['movement_id'=>(int)$existing->id,'source_hash'=>$hash,'replayed'=>true];
|
||||
}
|
||||
$lineSnapshot=json_decode($facts['line_snapshot'],true,512,JSON_THROW_ON_ERROR);
|
||||
$receiptSnapshot=json_decode($facts['receipt_snapshot'],true,512,JSON_THROW_ON_ERROR);
|
||||
$snapshot=[...$lineSnapshot,'receipt_id'=>(int)$facts['receipt_id'],'order_number'=>$receiptSnapshot['order']['number']??null,
|
||||
'delivery_note'=>$facts['delivery_note'],'reference'=>$facts['delivery_note'],'inventory_source_hash'=>$hash];
|
||||
$id=$this->db->table($this->schema.'.stock_movements')->insertGetId([
|
||||
'tenant_id'=>$this->tenant,'goods_receipt_item_id'=>$lineId,'stock_item_id'=>$facts['stock_item_id'],'warehouse_id'=>$facts['warehouse_id'],
|
||||
'moved_by'=>$this->actor,'quantity_milli'=>$stockQuantity,'movement_type'=>'receipt_in','moved_at'=>now(),
|
||||
'equipment_id'=>$lineSnapshot['equipment_id']??null,'spare_part_id'=>$lineSnapshot['spare_part_id']??null,
|
||||
'snapshot'=>json_encode($snapshot,JSON_THROW_ON_ERROR),
|
||||
]);
|
||||
return ['movement_id'=>(int)$id,'source_hash'=>$hash,'replayed'=>false];
|
||||
}
|
||||
|
||||
/** Legacy facts/hash are unchanged. Converted facts carry their entire frozen basis in line_snapshot. */
|
||||
private function stockQuantity(array $facts): string
|
||||
{
|
||||
$snapshot=json_decode($facts['line_snapshot'],true,512,JSON_THROW_ON_ERROR);
|
||||
if(!array_key_exists('quantity_conversion',$snapshot))return (string)$facts['accepted_milli'];
|
||||
$basis=$snapshot['quantity_conversion'];
|
||||
abort_unless(is_array($basis) && ($basis['schema']??null)==='inventory.quantity.v1'
|
||||
&& ($basis['stock_item_id']??null)===(int)$facts['stock_item_id']
|
||||
&& ($basis['document_unit']??null)===($snapshot['order_item']['unit']??null)
|
||||
&& ($basis['stock_unit']??null)===($snapshot['stock_item']['unit']??null)
|
||||
&& is_string($basis['numerator']??null) && is_string($basis['denominator']??null)
|
||||
&& is_string($basis['source']??null) && trim($basis['source'])!==''
|
||||
&& is_string($basis['version']??null) && trim($basis['version'])!=='',409,'Base de conversão incompleta ou incompatível.');
|
||||
$converted=QuantityConversion::toBase((string)$facts['accepted_milli'],$basis['numerator'],$basis['denominator']);
|
||||
abort_unless(($basis['accepted_document_milli']??null)===(string)$facts['accepted_milli']
|
||||
&& ($basis['accepted_stock_milli']??null)===$converted,409,'Quantidade física divergente da conversão congelada.');
|
||||
return $converted;
|
||||
}
|
||||
|
||||
private function checkHost(): void
|
||||
{
|
||||
if($this->db->transactionLevel()<1)throw new \LogicException('Receipt movement requires the host atomic transaction');
|
||||
($this->authorize)();
|
||||
}
|
||||
|
||||
private function facts(int $lineId,bool $lock): array
|
||||
{
|
||||
$q=$this->db->table($this->schema.'.goods_receipt_items AS l')
|
||||
->join($this->schema.'.goods_receipts AS r',fn($j)=>$j->on('r.id','=','l.goods_receipt_id')->on('r.tenant_id','=','l.tenant_id'))
|
||||
->where('l.tenant_id',$this->tenant)->where('l.id',$lineId)
|
||||
->select(['l.id','l.tenant_id','l.stock_item_id','l.received_milli','l.accepted_milli','l.rejected_milli','l.quality_status','l.notes',
|
||||
'l.snapshot AS line_snapshot','r.id AS receipt_id','r.purchase_order_id','r.received_by','r.warehouse_id','r.delivery_note','r.received_on','r.confirmed_at','r.snapshot AS receipt_snapshot']);
|
||||
if($lock)$q->lockForUpdate();
|
||||
$row=$q->first();abort_unless($row,403,'Origem fora do âmbito autorizado.');$facts=(array)$row;
|
||||
$snapshot=json_decode($facts['line_snapshot'],true,512,JSON_THROW_ON_ERROR);
|
||||
abort_unless((int)$facts['received_by']===$this->actor,403,'A origem não pertence ao recebedor desta confirmação.');
|
||||
abort_unless($facts['confirmed_at']!==null && ($snapshot['physical']??false)===true && (int)$facts['accepted_milli']>0
|
||||
&& $facts['stock_item_id']!==null && $facts['warehouse_id']!==null,409,'A origem não comprova quantidade física aceite.');
|
||||
return $facts;
|
||||
}
|
||||
|
||||
private function hash(array $facts): string
|
||||
{
|
||||
// Parent status/number are intentionally absent: finalisation occurs later in the same transaction.
|
||||
return hash('sha256',json_encode($facts,JSON_THROW_ON_ERROR));
|
||||
}
|
||||
}
|
||||
@@ -4,4 +4,6 @@ Additive local development capability for integral issued-order cancellation. Do
|
||||
|
||||
The host must hold its company lock, authenticate an independent finance actor, validate the published policy, confirm absence of receipts/invoices/payments and open the encompassing transaction. The writer appends a reversal of the original wholly available commitment in the canonical budget_entries ledger. The host binds the reversal entry to its decision in the same transaction and audit.
|
||||
|
||||
MZN only. Verify source SHA-256 against config/order_cancellation.php before execution. No transport, bank operations, invoice cancellation, partial cancellation, activation or grants. The capability is disabled in the local pilot; validation uses disposable databases.
|
||||
MZN only. The frozen legacy writer remains in `src`. The cycle-aware writer is versioned in `releases/0.2.0-rc.1`; `OrderCancellationRuntime` verifies its manifest, installation, schema and loaded class location before use. It reverses only the current open requisition cycle and preserves earlier cycles.
|
||||
|
||||
The versioned component is installed and explicitly enabled in the Compras local pilot under the owner's installation authorization of 29/11/2026. The original four-package financial installation is unchanged. No company cancellation policy, grant or business cancellation was created by installation. Native review and recovery use disposable synthetic databases. See `docs/proofs/order-cancellation-pilot-installation.json` and `order-cancellation-pilot-native-review.json`. No SGF installation, transport, bank operations or invoice cancellation is included.
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"id": "tempo-order-cancellation",
|
||||
"version": "0.2.0-rc.1",
|
||||
"contract": "COMPRAS-ORDER-CANCELLATION-CYCLES-v1",
|
||||
"legacy_source_sha256": "5471d9f826f47012415bf9a7086d4d7316ab8550b58e497f7432b94514a18bfa",
|
||||
"files": {
|
||||
"src/CommitmentReversal.php": "ecf0028a57b0280cf3a889da29a6e528c7eaa6a876e700b32ff59ac3b3eeb069"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace Tempo\Finance\OrderCancellation;
|
||||
|
||||
use Brick\Math\BigDecimal;
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
use LogicException;
|
||||
use Tempo\Finance\Budget\BudgetContext;
|
||||
|
||||
/** Additive finance capability: the original commitment is never changed. */
|
||||
final class CommitmentReversal
|
||||
{
|
||||
public function reverse(ConnectionInterface $db, BudgetContext $context, int $origin, int $order): ?int
|
||||
{
|
||||
if ($db->transactionLevel() < 1) {
|
||||
throw new LogicException('Reversal requires the host transaction and company lock.');
|
||||
}
|
||||
$hasCycles = $db->getSchemaBuilder()->hasTable('budget_requisition_cycles');
|
||||
if ($hasCycles !== $db->getSchemaBuilder()->hasColumn('budget_entries', 'requisition_cycle')) {
|
||||
throw new LogicException('Incomplete budget cycle schema.');
|
||||
}
|
||||
$cycle = $context->requisitionCycles[$origin] ?? null;
|
||||
if ($hasCycles) {
|
||||
if ($cycle === null) {
|
||||
throw new LogicException('Explicit order source cycle required.');
|
||||
}
|
||||
$head = $db->table('budget_requisition_cycles')->where($context->scope)->where('requisition_id', $origin)
|
||||
->orderByDesc('cycle')->lockForUpdate()->first();
|
||||
if (($head === null && $cycle !== 1) || ($head !== null && ((int) $head->cycle !== $cycle || $head->state !== 'open'))) {
|
||||
throw new LogicException('Only the current open order source cycle can be reversed.');
|
||||
}
|
||||
} elseif (($cycle ?? 1) !== 1) {
|
||||
throw new LogicException('Budget cycle schema required for resubmitted orders.');
|
||||
}
|
||||
$entries = $db->table('budget_entries')->where($context->scope)->where('requisition_id', $origin)
|
||||
->when($hasCycles, fn ($query) => $query->where('requisition_cycle', $cycle))->orderBy('id')->lockForUpdate()->get();
|
||||
if ($entries->isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
$commit = $entries->where('kind', 'commit');
|
||||
if ($commit->count() !== 1) {
|
||||
throw new LogicException('Exactly one original commitment required.');
|
||||
}
|
||||
$source = $commit->first();
|
||||
$amount = BigDecimal::of((string) $source->committed_minor)->toInt();
|
||||
$kind = 'order-cancel-'.$order;
|
||||
$old = $entries->firstWhere('kind', $kind);
|
||||
if ($old) {
|
||||
if ((int) $old->committed_minor !== -$amount || (int) $old->reserved_minor !== 0 || $old->budget_id !== $source->budget_id) {
|
||||
throw new LogicException('Invalid prior reversal.');
|
||||
}
|
||||
|
||||
return (int) $old->id;
|
||||
}
|
||||
$budget = $db->table('budgets')->where($context->scope)->where('id', $source->budget_id)->lockForUpdate()->first();
|
||||
if (! $budget || ! $budget->approved_by || $amount <= 0 || $entries->contains(fn ($e) => $e->budget_id !== $source->budget_id)
|
||||
|| BigDecimal::of((string) $entries->sum('reserved_minor'))->toInt() !== 0
|
||||
|| BigDecimal::of((string) $entries->sum('committed_minor'))->toInt() !== $amount) {
|
||||
throw new LogicException('Commitment is not wholly available for reversal.');
|
||||
}
|
||||
|
||||
return $db->table('budget_entries')->insertGetId([...$context->scope, ...($hasCycles ? ['requisition_cycle' => $cycle] : []), 'budget_id' => $source->budget_id, 'requisition_id' => $origin,
|
||||
'created_by' => $context->actorId, 'kind' => $kind, 'reserved_minor' => 0, 'committed_minor' => -$amount, 'created_at' => now()]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user