commit compras5 2911
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-29 19:49:19 +02:00
parent a935499d64
commit 96b30368bc
96 changed files with 3397 additions and 111 deletions
@@ -12,6 +12,7 @@ use App\Models\StockItem;
use App\Models\StockMovement;
use App\Models\User;
use App\Models\Warehouse;
use App\Services\InventoryConversionRuntime;
use App\Services\InventoryLots;
use App\Services\InventoryReversals;
use App\Services\ReceiptDocuments;
@@ -72,7 +73,7 @@ class GoodsReceiptController extends Controller
'receipts' => GoodsReceipt::query()->where('purchase_order_id', $order->id)->latest('id')->get(),
'warehouses' => Warehouse::query()->orderBy('code')->get(['id', 'code', 'name']),
'stockItems' => StockItem::query()->orderBy('code')->get(['id', 'code', 'name', 'unit']),
'conversionQaEnabled' => app()->environment('testing') && config('inventory_conversion.qa_enabled') === true,
'conversionQaEnabled' => app(InventoryConversionRuntime::class)->available(),
'canConfirm' => $actor->can('create', [GoodsReceipt::class, $order]),
'lotScopes' => Schema::hasTable('inventory_lot_allocations')
? app(InventoryLots::class)->activeSetups()->get()->map(fn ($r) => ['stock_item_id' => $r->stock_item_id, 'warehouse_id' => $r->warehouse_id, 'quarantine_on_receipt' => $r->data['quarantine_on_receipt'] ?? true])->values()->all() : [],
@@ -8,6 +8,7 @@ use App\Models\PurchaseOrder;
use App\Models\Requisition;
use App\Models\User;
use App\Services\OrderCancellationPolicyWorkflow;
use App\Services\OrderCancellationRuntime;
use App\Services\OrderCancellationWorkflow;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
@@ -22,6 +23,7 @@ class OrderCancellationController extends Controller
$actor = $request->user('web');
abort_unless($actor instanceof User, 403);
abort_unless(config('order_cancellation.enabled') && Schema::hasTable('order_cancellations'), 503, 'Cancelamento de ordens não activado.');
app(OrderCancellationRuntime::class)->assertReady();
return $actor;
}
@@ -17,6 +17,7 @@ use App\Models\Warehouse;
use App\Services\AgreementOrderLimits;
use App\Services\ImportDossier;
use App\Services\ImportLandedCosts;
use App\Services\InventoryConversionRuntime;
use App\Services\InventoryReversals;
use App\Services\OrganizationAccess;
use App\Services\ReceiptWorkflow;
@@ -370,7 +371,7 @@ class SupplyPlanningController extends Controller
}
return Inertia::render('supply/coordination', ['kind' => $kind, 'ready' => $ready,
'conversionQaEnabled' => app()->environment('testing') && config('inventory_conversion.qa_enabled') === true,
'conversionQaEnabled' => app(InventoryConversionRuntime::class)->available(),
'recordFilters' => ['record_search' => trim($filters['record_search'] ?? ''), 'record_state' => $filters['record_state'] ?? ''],
'recordPagination' => $page === null ? null : ['current_page' => $page->currentPage(), 'last_page' => $page->lastPage(), 'total' => $page->total(),
'prev_page_url' => $page->previousPageUrl(), 'next_page_url' => $page->nextPageUrl()],
+8
View File
@@ -260,6 +260,11 @@ final class AgreementOrderLimits
private function loadArithmetic(): void
{
if (app(InventoryConversionRuntime::class)->enabled()) {
app(ReceiptStockMovement::class)->load();
return;
}
$root = base_path('packages/inventory-write/development');
$bytes = file_get_contents($root.'/manifest.json');
if ($bytes === false || ! hash_equals('90cf565537e7fd48eb54a87bcfd6d585cf53239f075764910047838b3b8b4c38', hash('sha256', $bytes))) {
@@ -271,6 +276,9 @@ final class AgreementOrderLimits
if (! is_string($hash) || ! hash_equals($manifest['files']['src/QuantityConversion.php'], $hash)) {
throw new \LogicException('Aritmética alterada.');
}
if (class_exists(QuantityConversion::class, false) && realpath((new \ReflectionClass(QuantityConversion::class))->getFileName() ?: '') !== realpath($file)) {
throw new \LogicException('COMPRAS_INVENTORY_ARITHMETIC_VERSION');
}
require_once $file;
}
+65
View File
@@ -0,0 +1,65 @@
<?php
namespace App\Services;
use DOMElement;
use DOMText;
use DOMXPath;
use LogicException;
/** Mechanical console-to-GUI executable correction; no scheduling or business-policy change. */
final class DeadlineTaskGuiAction
{
public static function replacement(string $xml, string $old, string $new): string
{
$normal = str_replace('\\', '/', $old);
if (! str_ends_with($normal, '/php.exe') || $new !== substr($normal, 0, -7).'php-win.exe') {
throw new LogicException('DEADLINE_TASK_GUI_EXECUTABLE_PAIR');
}
$document = WindowsTaskXml::parse($xml);
$xpath = new DOMXPath($document);
$xpath->registerNamespace('t', 'http://schemas.microsoft.com/windows/2004/02/mit/task');
$nodes = $xpath->query('/t:Task/t:Actions/t:Exec/t:Command');
$actions = $xpath->query('/t:Task/t:Actions/*');
$command = $nodes === false ? null : $nodes->item(0);
if ($actions === false || $nodes === false || $actions->length !== 1 || $nodes->length !== 1
|| ! $command instanceof DOMElement || $command->textContent !== $old) {
throw new LogicException('DEADLINE_TASK_GUI_ACTION_MISMATCH');
}
$command->nodeValue = $new;
$output = $document->saveXML();
if (! is_string($output)) {
throw new LogicException('DEADLINE_TASK_GUI_XML');
}
return $output;
}
public static function assertConserved(string $before, string $after, string $old, string $new): void
{
if (self::canonical(self::replacement($before, $old, $new)) !== self::canonical($after)) {
throw new LogicException('DEADLINE_TASK_GUI_UNRELATED_DEFINITION_CHANGE');
}
}
public static function canonical(string $xml): string
{
$document = WindowsTaskXml::parse($xml);
$xpath = new DOMXPath($document);
$blanks = $xpath->query('//text()[normalize-space(.)=""]');
if ($blanks === false) {
throw new LogicException('DEADLINE_TASK_GUI_XML');
}
foreach ($blanks as $blank) {
if ($blank instanceof DOMText && $blank->parentNode !== null) {
$blank->parentNode->removeChild($blank);
}
}
$canonical = $document->documentElement->C14N();
if (! is_string($canonical)) {
throw new LogicException('DEADLINE_TASK_GUI_XML');
}
return $canonical;
}
}
+101
View File
@@ -0,0 +1,101 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
use LogicException;
/** Optional inventory component; does not alter the four-package financial receipt. */
final class InventoryConversionRuntime
{
public const MANIFEST_SHA256 = '8608e6551dea6448983ead401ba900b440ffdeb1446ce52de6509d5eba0e87bd';
public function enabled(): bool
{
return config('inventory_conversion.enabled') === true;
}
public function available(): bool
{
if ($this->enabled()) {
$this->root();
return true;
}
return config('inventory_conversion.qa_enabled') === true && app()->environment('testing');
}
public function root(): string
{
if (! $this->enabled() || config('inventory_conversion.qa_enabled') === true) {
throw new LogicException('COMPRAS_INVENTORY_CONFIGURATION');
}
$runtime = app(StandaloneRuntime::class);
if (! $runtime->enabled()) {
throw new LogicException('COMPRAS_INVENTORY_INSTALLATION_REQUIRED');
}
$runtime->assertInstallation(DB::connection());
$runtime->assertLoadedPackages();
$root = config('inventory_conversion.root');
if (! is_string($root)) {
throw new LogicException('COMPRAS_INVENTORY_ROOT');
}
self::verifyArtifact($root);
foreach ([
'goods_receipt_items' => ['id', 'tenant_id', 'goods_receipt_id', 'stock_item_id', 'received_milli', 'accepted_milli', 'rejected_milli', 'quality_status', 'notes', 'snapshot'],
'goods_receipts' => ['id', 'tenant_id', 'purchase_order_id', 'received_by', 'warehouse_id', 'delivery_note', 'received_on', 'confirmed_at', 'snapshot'],
'stock_movements' => ['id', 'tenant_id', 'goods_receipt_item_id', 'stock_item_id', 'warehouse_id', 'moved_by', 'quantity_milli', 'movement_type', 'moved_at', 'equipment_id', 'spare_part_id', 'snapshot'],
] as $table => $columns) {
if (! DB::getSchemaBuilder()->hasColumns($table, $columns)) {
throw new LogicException('COMPRAS_INVENTORY_SCHEMA');
}
}
return $root;
}
/** No PHP from the component is executed during verification. */
public static function verifyArtifact(string $root): void
{
$boundary = realpath($root);
$manifest = $root.'/manifest.json';
$bytes = is_file($manifest) ? file_get_contents($manifest) : false;
if ($boundary === false || is_link($root) || is_link($manifest) || ! is_file($manifest)
|| ! is_string($bytes) || ! hash_equals(self::MANIFEST_SHA256, hash('sha256', $bytes))) {
throw new LogicException('COMPRAS_INVENTORY_MANIFEST');
}
$data = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
foreach ($data['files'] as $file => $hash) {
$path = $root.'/'.$file;
$actual = is_file($path) ? hash_file('sha256', $path) : false;
if (is_link($path) || ! is_file($path) || ! str_starts_with(realpath($path) ?: '', $boundary.DIRECTORY_SEPARATOR)
|| ! is_string($actual) || ! hash_equals($hash, $actual)) {
throw new LogicException('COMPRAS_INVENTORY_FILE:'.$file);
}
}
}
public static function assertArchiveEntries(\ZipArchive $archive): void
{
$expected = ['manifest.json', 'bootstrap.php', 'src/QuantityConversion.php', 'src/ReceiptMovementWriter.php'];
$actual = [];
for ($i = 0; $i < $archive->numFiles; $i++) {
$actual[] = $archive->getNameIndex($i);
}
sort($actual, SORT_STRING);
sort($expected, SORT_STRING);
if ($actual !== $expected) {
throw new LogicException('COMPRAS_INVENTORY_ARCHIVE_ENTRIES');
}
}
/** Disabling the component cannot silently select a writer unable to read frozen conversions. */
public function assertLegacyCompatible(): void
{
if (DB::table('goods_receipt_items')->whereNotNull('snapshot->quantity_conversion')->exists()
|| DB::table('supply_records')->whereNotNull('data->conversion_basis')->exists()) {
throw new LogicException('COMPRAS_INVENTORY_DOWNGRADE_REFUSED');
}
}
}
@@ -43,6 +43,7 @@ class OrderCancellationPolicyWorkflow extends PurchaseControlPolicyWorkflow
private function enabled(): void
{
abort_unless(config('order_cancellation.enabled') && Schema::hasTable('order_cancellation_policies'), 503, 'Cancelamento de ordens não activado.');
app(OrderCancellationRuntime::class)->assertReady();
}
public function propose(User $user, array $data): PurchaseControlPolicy
+78
View File
@@ -0,0 +1,78 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
use LogicException;
use Tempo\Finance\Budget\BudgetContext;
use Tempo\Finance\OrderCancellation\CommitmentReversal;
/** Version selection for the existing additive reversal writer, never another budget ledger. */
final class OrderCancellationRuntime
{
public const MANIFEST_SHA256 = '52df7927aa2689598ce1be92de1483694347a696245704abb9e3925db7abfc0f';
public function assertReady(): void
{
$runtime = app(StandaloneRuntime::class);
if (! $runtime->enabled()) {
return;
}
$runtime->assertInstallation(DB::connection());
$runtime->assertLoadedPackages();
if (! property_exists(BudgetContext::class, 'requisitionCycles')) {
throw new LogicException('COMPRAS_CANCELLATION_CYCLE_CONTEXT');
}
foreach (['order_cancellations' => ['operation_key', 'basis_hash', 'status'],
'order_cancellation_policies' => ['revision', 'status'], 'order_cancellation_policy_reviews' => ['reviewed_by'],
'budget_entries' => ['requisition_cycle'], 'budget_requisition_cycles' => ['cycle', 'state']] as $table => $columns) {
if (! DB::getSchemaBuilder()->hasColumns($table, $columns)) {
throw new LogicException('COMPRAS_CANCELLATION_SCHEMA');
}
}
$root = config('order_cancellation.root');
if (! is_string($root)) {
throw new LogicException('COMPRAS_CANCELLATION_ROOT');
}
self::verifyArtifact($root);
}
public static function verifyArtifact(string $root): void
{
$bytes = is_file($root.'/manifest.json') ? file_get_contents($root.'/manifest.json') : false;
$path = $root.'/src/CommitmentReversal.php';
$hash = is_file($path) ? hash_file('sha256', $path) : false;
if (! is_string($bytes) || ! hash_equals(self::MANIFEST_SHA256, hash('sha256', $bytes))
|| is_link($root) || is_link($root.'/manifest.json') || is_link($path)
|| ! str_starts_with(realpath($path) ?: '', (realpath($root) ?: '').DIRECTORY_SEPARATOR)) {
throw new LogicException('COMPRAS_CANCELLATION_MANIFEST');
}
$manifest = json_decode($bytes, true, 32, JSON_THROW_ON_ERROR);
if (! is_string($hash) || ! hash_equals($manifest['files']['src/CommitmentReversal.php'], $hash)) {
throw new LogicException('COMPRAS_CANCELLATION_FILE');
}
}
/** Returns whether the writer requires the explicit cycle map in its financial context. */
public function load(int $origin): bool
{
$operational = app(StandaloneRuntime::class)->enabled();
if ($operational) {
$this->assertReady();
$path = config('order_cancellation.root').'/src/CommitmentReversal.php';
} else {
abort_if(DB::getSchemaBuilder()->hasColumn('budget_entries', 'requisition_cycle')
&& DB::table('budget_entries')->where('requisition_id', $origin)->where('requisition_cycle', '>', 1)->exists(), 503,
'Preserve o componente compatível com os ciclos antes de cancelar esta ordem.');
$path = base_path('packages/order-cancellation/src/CommitmentReversal.php');
abort_unless(is_file($path) && hash_file('sha256', $path) === config('order_cancellation.reversal_sha256'), 503, 'Capacidade de reversão indisponível.');
}
if (class_exists(CommitmentReversal::class, false)
&& realpath((new \ReflectionClass(CommitmentReversal::class))->getFileName() ?: '') !== realpath($path)) {
throw new LogicException('COMPRAS_CANCELLATION_CLASS_LOCATION');
}
require_once $path;
return $operational;
}
}
+6 -4
View File
@@ -82,6 +82,7 @@ class OrderCancellationWorkflow
private function enabled(): void
{
abort_unless(config('order_cancellation.enabled') && Schema::hasTable('order_cancellations'), 503, 'Cancelamento de ordens não activado.');
app(OrderCancellationRuntime::class)->assertReady();
}
public function state(PurchaseOrder $order): string
@@ -198,11 +199,12 @@ class OrderCancellationWorkflow
if (! empty($order->snapshot['budget_control']) && ! DB::table('budget_entries')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $request->id)->exists()) {
throw ValidationException::withMessages(['budget' => 'A ordem indica controlo orçamental, mas o compromisso não está disponível.']);
}
$path = base_path('packages/order-cancellation/src/CommitmentReversal.php');
abort_unless(is_file($path) && hash_file('sha256', $path) === config('order_cancellation.reversal_sha256'), 503, 'Capacidade de reversão indisponível.');
require_once $path;
$cycles = app(OrderCancellationRuntime::class)->load($request->id);
$context = $cycles
? (new \ReflectionClass(BudgetContext::class))->newInstanceArgs([$actor->id, ['tenant_id' => (int) $actor->tenant_id], (int) now()->year, 'MZN', RequisitionExpiry::orderCycles($order)])
: new BudgetContext($actor->id, ['tenant_id' => (int) $actor->tenant_id], (int) now()->year, 'MZN');
try {
$entry = (new CommitmentReversal)->reverse(DB::connection(), new BudgetContext($actor->id, ['tenant_id' => (int) $actor->tenant_id], (int) now()->year, 'MZN'), $request->id, $order->id);
$entry = (new CommitmentReversal)->reverse(DB::connection(), $context, $request->id, $order->id);
} catch (\LogicException $error) {
throw ValidationException::withMessages(['budget' => 'O compromisso não está integralmente disponível para reversão ou a sua base é inconsistente. Reveja o controlo orçamental.']);
}
+3 -3
View File
@@ -32,8 +32,8 @@ final class ReceiptQuantityConversion
return null;
}
if (config('inventory_conversion.qa_enabled') !== true || ! app()->environment('testing')) {
throw ValidationException::withMessages(['items' => 'A conversão de unidades está preparada apenas para QA.']);
if (! app(InventoryConversionRuntime::class)->available()) {
throw ValidationException::withMessages(['items' => 'A conversão de unidades não está instalada e activada.']);
}
$v = Validator::make($input ?? [], [
'numerator' => ['required', 'string', 'regex:/^[1-9]\d{0,8}$/D'],
@@ -75,7 +75,7 @@ final class ReceiptQuantityConversion
if ($basis === null) {
return $physical;
}
abort_unless(config('inventory_conversion.qa_enabled') === true, 503, 'Conversão ainda não instalada.');
abort_unless(app(InventoryConversionRuntime::class)->available(), 503, 'Conversão ainda não instalada.');
app(ReceiptStockMovement::class)->load();
try {
return (int) QuantityConversion::fromBase((string) $physical, $basis['numerator'], $basis['denominator']);
+18 -4
View File
@@ -15,7 +15,12 @@ final class ReceiptStockMovement
$root = base_path('packages/inventory-write/releases/0.1.0');
$pin = 'f0b99e591f9a4df135e685f64ceffad77bed259222debe0f34c20f95e3cad800';
$files = ['bootstrap.php', 'src/ReceiptMovementWriter.php'];
if (config('inventory_conversion.qa_enabled') === true) {
$conversion = app(InventoryConversionRuntime::class);
if ($conversion->enabled()) {
$root = $conversion->root();
$pin = InventoryConversionRuntime::MANIFEST_SHA256;
$files[] = 'src/QuantityConversion.php';
} elseif (config('inventory_conversion.qa_enabled') === true) {
abort_unless(app()->environment('testing'), 503, 'Extensão de conversão limitada a QA.');
$connection = DB::connection();
abort_unless(($connection->getDriverName() === 'sqlite' && $connection->getDatabaseName() === ':memory:')
@@ -23,6 +28,8 @@ final class ReceiptStockMovement
$root = base_path('packages/inventory-write/development');
$pin = '90cf565537e7fd48eb54a87bcfd6d585cf53239f075764910047838b3b8b4c38';
$files[] = 'src/QuantityConversion.php';
} else {
$conversion->assertLegacyCompatible();
}
$bytes = is_file($root.'/manifest.json') ? file_get_contents($root.'/manifest.json') : false;
if (! is_string($bytes) || ! hash_equals($pin, hash('sha256', $bytes))) {
@@ -35,9 +42,16 @@ final class ReceiptStockMovement
throw new \LogicException('Pacote de recepção alterado.');
}
}
if (class_exists(ReceiptMovementWriter::class, false)) {
$loaded = (new \ReflectionClass(ReceiptMovementWriter::class))->getFileName();
if (! is_string($loaded) || realpath($loaded) !== realpath($root.'/src/ReceiptMovementWriter.php')) {
foreach (['ReceiptMovementWriter', 'QuantityConversion'] as $class) {
if ($class === 'QuantityConversion' && ! in_array('src/QuantityConversion.php', $files, true)) {
continue;
}
$name = 'Tempo\\Inventory\\'.$class;
if (! class_exists($name, false)) {
continue;
}
$loaded = (new \ReflectionClass($name))->getFileName();
if (! is_string($loaded) || realpath($loaded) !== realpath($root.'/src/'.$class.'.php')) {
throw new \LogicException('Escritor já carregado de outra versão; use um kernel QA separado.');
}
}
@@ -0,0 +1,67 @@
<?php
namespace App\Services;
use DOMXPath;
use LogicException;
use Symfony\Component\Process\Process;
final class ReplenishmentTaskDefinition
{
public static function assertMatches(string $requested, string $installed): void
{
$views = [];
foreach ([$requested, $installed] as $xml) {
$view = new DOMXPath(WindowsTaskXml::parse($xml));
$view->registerNamespace('t', 'http://schemas.microsoft.com/windows/2004/02/mit/task');
$actions = $view->query('//t:Exec');
$principals = $view->query('//t:Principal');
$triggers = $view->query('//t:Triggers/*');
if ($actions === false || $principals === false || $triggers === false
|| $actions->length !== 1 || $principals->length !== 1 || $triggers->length !== 2) {
throw new LogicException('REPLENISHMENT_TASK_STRUCTURE_DIFFERS');
}
$views[] = $view;
}
foreach (['Command', 'Arguments', 'WorkingDirectory', 'LogonType', 'RunLevel', 'MultipleInstancesPolicy', 'ExecutionTimeLimit',
'TimeTrigger/StartBoundary', 'TimeTrigger/Repetition/Interval', 'LogonTrigger/UserId', 'Principal/UserId',
'DisallowStartIfOnBatteries', 'StopIfGoingOnBatteries', 'AllowHardTerminate', 'StartWhenAvailable', 'Hidden'] as $path) {
$query = 'string(//t:'.str_replace('/', '/t:', $path).')';
$expected = $views[0]->evaluate($query);
$actual = $views[1]->evaluate($query);
if (in_array($path, ['LogonTrigger/UserId', 'Principal/UserId'], true) && is_string($actual) && is_string($expected)) {
$actual = self::currentIdentity($actual);
$expected = self::currentIdentity($expected);
}
// Task Scheduler exports the native Limited/0 default without a RunLevel element.
$levels = $views[1]->query('//t:RunLevel');
if ($path === 'RunLevel' && $actual === '' && $levels !== false && $levels->length === 0) {
$actual = 'LeastPrivilege';
}
$termination = $views[1]->query('//t:AllowHardTerminate');
if ($path === 'AllowHardTerminate' && $actual === '' && $termination !== false && $termination->length === 0) {
$actual = 'true';
}
if ($actual !== $expected) {
throw new LogicException('REPLENISHMENT_TASK_DEFINITION_DIFFERS:'.$path);
}
}
}
private static function currentIdentity(string $identity): string
{
if (preg_match('/^S-1-\d+(?:-\d+)+$/D', $identity)) {
return $identity;
}
// Native export can resolve the current SID to its account name in the logon trigger.
$process = new Process([getenv('SystemRoot').'/System32/whoami.exe', '/user', '/fo', 'csv', '/nh'], timeout: 10);
$process->run();
$record = str_getcsv(trim($process->getOutput()), escape: '');
if (! $process->isSuccessful() || count($record) !== 2 || strcasecmp($identity, $record[0]) !== 0
|| ! preg_match('/^S-1-\d+(?:-\d+)+$/D', $record[1])) {
throw new LogicException('REPLENISHMENT_TASK_CURRENT_IDENTITY_DIFFERS');
}
return $record[1];
}
}
+1 -1
View File
@@ -261,7 +261,7 @@ class SupplyCoordination
if ($basis === null) {
return $remaining;
}
abort_unless(config('inventory_conversion.qa_enabled') === true, 503, 'Conversão ainda não instalada.');
abort_unless(app(InventoryConversionRuntime::class)->available(), 503, 'Conversão ainda não instalada.');
app(ReceiptStockMovement::class)->load();
return (int) QuantityConversion::toBase((string) $remaining, $basis['numerator'], $basis['denominator']);