commit SGF2311
This commit is contained in:
@@ -1,5 +1,13 @@
|
||||
# Receipt movement writer
|
||||
|
||||
## Development extension authorised on 21 November 2026
|
||||
|
||||
The owner authorised preparing unit conversion in development/QA only. The working source now recognises an optional `quantity_conversion` receipt-line snapshot (`inventory.quantity.v1`): documentary/base units, explicit positive rational factor, source/version, original article and both accepted quantities in integer millesimals. The same writer validates the exact conversion and writes/replays one physical movement. Without that snapshot, the facts, source hash and receipt quantity are unchanged. Published `releases/0.1.0` is untouched.
|
||||
|
||||
`QuantityConversion` is the sole exact arithmetic implementation; it rejects nonrepresentable quantities and integer overflow. It never converts prices. The host still validates/freezes the basis, unit mapping and actor under its company lock, and retains original order/receipt/invoice quantities and prices. The prepared Compras adaptation freezes the basis on the first accepted receipt for an order line/article, then requires it on subsequent portions; lots/issues use base units and supplier returns preserve the exact documentary equivalent.
|
||||
|
||||
Compras holds a hash-pinned **development artifact**, not a published release. Its loader refuses this artifact outside `testing` and a guarded disposable database; default configuration remains off. No installation, activation or operational change in SGF or the pilot is authorised or performed. Different writer versions require separate kernels. Test results and remaining criteria are recorded in the existing Compras delivery trackers.
|
||||
|
||||
`ReceiptMovementWriter` is the single extracted writer for a new accepted physical receipt line. Source code comes from the former insert in Purchasing `ReceiptWorkflow`; versioned artifacts are distributed locally, verified by manifest and never replaced with different contents.
|
||||
|
||||
The host owns the company lock, current actor/policy/conflict checks, order eligibility, quantities/units/quality, explicit warehouse/item mapping, lots, downstream signals and audit. It must call the writer within that same transaction, with an authorisation callback. The writer is not a public receipt intake API and must not be used to reconstruct/backfill historical effects or bypass `ReceiptWorkflow`.
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
<?php
|
||||
require_once __DIR__.'/src/QuantityConversion.php';
|
||||
require_once __DIR__.'/src/ReceiptMovementWriter.php';
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -25,9 +25,10 @@ final class ReceiptMovementWriter
|
||||
$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===(string)$facts['accepted_milli']
|
||||
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];
|
||||
}
|
||||
@@ -37,13 +38,32 @@ final class ReceiptMovementWriter
|
||||
'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'=>$facts['accepted_milli'],'movement_type'=>'receipt_in','moved_at'=>now(),
|
||||
'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');
|
||||
|
||||
Reference in New Issue
Block a user