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
+80 -4
View File
@@ -2,25 +2,101 @@
use App\Models\PurchaseOrder;
use App\Models\User;
use App\Services\OrderCancellationWorkflow;
use App\Services\ReceiptWorkflow;
use App\Services\SupplierPayables;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\Process\Process;
require __DIR__.'/../../vendor/autoload.php';
$database = $argv[1] ?? '';
$operational = getenv('COMPRAS_STANDALONE_CONVERSION_QA') === '1';
$app = require __DIR__.'/../../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database
if (! $app->environment($operational ? ['testing', 'standalone-qa'] : ['testing']) || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)) {
throw new LogicException('Worker de conversão fora de QA.');
}
config(['inventory_conversion.qa_enabled' => true]);
if (($argv[2] ?? '') === 'prepare') {
if ($operational && (DB::connection()->getConfig('host') !== '127.0.0.1' || (string) DB::connection()->getConfig('port') !== '55439'
|| DB::selectOne("select current_setting('cluster_name') as name")->name !== 'sgf_modular_regression_'.substr($database, -12))) {
throw new LogicException('Owned standalone conversion cluster required.');
}
if (($argv[2] ?? '') === 'prepare-runtime' && $operational) {
require __DIR__.'/../Support/StandaloneCompositionFixture.php';
prepareSyntheticStandaloneRuntime();
echo 'synthetic_standalone_inventory_prepared';
exit;
}
config(['inventory_conversion.qa_enabled' => ! $operational, 'inventory_conversion.enabled' => $operational]);
if (($argv[2] ?? '') === 'prepare-analytics-preview' && $operational) {
require __DIR__.'/../Support/PaymentFixture.php';
$f = paymentFixture(['Material', 'Serviços']);
$payables = app(SupplierPayables::class);
foreach ([$f['author'], $f['validator']] as $actor) {
foreach (['view', 'prepare', 'validate', 'payments_view', 'payment_prepare', 'payment_confirm', 'allocation_prepare', 'allocation_confirm'] as $action) {
DB::table('pa_access')->insert(['tenant_id' => $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0,
'user_id' => $actor->id, 'person' => 'synthetic-analytics-finance-'.$actor->id, 'action' => $action]);
}
}
auth()->guard()->setUser($f['author']);
$proposal = $payables->engine($f['author'])->command('prepare', $f['invoice']->id, 'Synthetic analytics invoice', (string) Str::uuid());
auth()->guard()->setUser($f['validator']);
$recognised = $payables->engine($f['validator'])->command('validate', $proposal['proposal_id'], 'Independent synthetic invoice recognition', (string) Str::uuid());
$run = static function (User $actor, string $action, array $data) use ($payables): array {
auth()->guard()->setUser($actor);
return $payables->settlements($actor)->command($action, $data, (string) Str::uuid());
};
$payment = $run($f['author'], 'payment-prepare', ['obligation_id' => $recognised['obligation_id'],
'source_revision' => $recognised['source_revision'], 'amount' => '40.00', 'currency' => 'MZN', 'paid_on' => today()->toDateString(),
'fact_reference' => 'DOC-ANALYTICS-SYNTHETIC', 'evidence_reference' => 'DOC-ANALYTICS-EVIDENCE', 'reason' => 'Explicit synthetic payment fact for analytical review']);
$run($f['validator'], 'payment-decide', ['payment_id' => $payment['payment_id'], 'decision' => 'confirmed',
'evidence_reference' => 'DOC-ANALYTICS-CONFIRMED', 'reason' => 'Independent synthetic payment confirmation']);
$allocation = $run($f['author'], 'allocation-prepare', ['payment_id' => $payment['payment_id'], 'reference' => 'DOC-ANALYTICS-ALLOCATION',
'allocations' => [['obligation_id' => $recognised['obligation_id'], 'source_revision' => $recognised['source_revision'], 'amount' => '40.00']],
'reason' => 'Explicit synthetic invoice allocation']);
$run($f['validator'], 'allocation-decide', ['proposal_id' => $allocation['proposal_id'], 'decision' => 'confirmed',
'reason' => 'Independent synthetic allocation confirmation']);
$allocationId = (int) DB::table('ps_allocations')->where('payment_id', $payment['payment_id'])->value('id');
$f['validator']->update(['email' => 'analytics-finance@example.test', 'name' => 'Finance synthetic analytics review']);
echo json_encode(['actor_email' => $f['validator']->email, 'tenant_id' => $f['tenant']->id,
'order_id' => $f['order']->id, 'allocation_id' => $allocationId, 'payment_amount_minor' => 4000,
'attribution_route' => '/afectacoes-fornecedores/'.$allocationId.'/imputacao', 'report_route' => '/relatorios'], JSON_THROW_ON_ERROR);
exit;
}
if (($argv[2] ?? '') === 'prepare-cancellation-preview' && $operational) {
require __DIR__.'/../Support/IssuedOrderCancellationFixture.php';
config(['order_cancellation.enabled' => true]);
$fixture = new class extends stdClass
{
public function actingAs(User $actor): void
{
auth()->guard()->setUser($actor);
}
};
issuedOrderCancellationFixture($fixture, 2);
$workflow = app(OrderCancellationWorkflow::class);
$fixture->actingAs($fixture->buyer);
$record = $workflow->request($fixture->buyer, $fixture->f['order'], $fixture->data);
$fixture->actingAs($fixture->finance);
$workflow->decide($fixture->finance, $record, 'approved', 'Independent synthetic cycle-aware cancellation preview');
$fixture->finance->update(['email' => 'cancellation-finance@example.test', 'name' => 'Finance synthetic cancellation review']);
echo json_encode(['actor_email' => $fixture->finance->email, 'tenant_id' => $fixture->f['tenant']->id,
'order_id' => $fixture->f['order']->id, 'cancellation_id' => $record->id, 'source_cycle' => 2, 'state' => 'approved'], JSON_THROW_ON_ERROR);
exit;
}
if (in_array($argv[2] ?? '', ['prepare', 'prepare-preview'], true)) {
require __DIR__.'/../Support/ReceiptFixture.php';
$f = receiptFixture();
$f['stock']->update(['unit' => 'un']);
if (($argv[2] ?? '') === 'prepare-preview' && $operational) {
$f['receiver']->update(['email' => 'conversion-warehouse@example.test', 'name' => 'Warehouse synthetic conversion review']);
echo json_encode(['actor_email' => $f['receiver']->email, 'tenant_id' => $f['tenant']->id, 'order_id' => $f['order']->id], JSON_THROW_ON_ERROR);
exit;
}
$body = receiptPayload($f, '1.000');
$body['items'][0]['conversion'] = ['numerator' => '12', 'denominator' => '1', 'source' => 'Embalagem sintética de corrida', 'version' => 'QA-RACE-1'];
echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $f['receiver']->id, 'order' => $f['order']->id, 'body' => $body], JSON_THROW_ON_ERROR);
@@ -43,7 +119,7 @@ if (($argv[2] ?? '') !== 'race') {
throw new InvalidArgumentException('Modo de worker inválido.');
}
foreach (['same_body', 'conflicting_body'] as $scenario) {
$prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
$prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), $operational ? ['APP_ENV' => 'testing'] : null, timeout: 30);
$prepare->mustRun();
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$workers = [];
@@ -10,6 +10,7 @@ use App\Models\StockMovement;
use App\Models\User;
use App\Services\AgreementOrderLimits;
use App\Services\ConflictGuard;
use App\Services\InventoryConversionRuntime;
use App\Services\InventoryDispositions;
use App\Services\InventoryLots;
use App\Services\InventoryReversals;
@@ -17,17 +18,27 @@ use App\Services\InvoiceWorkflow;
use App\Services\ReceiptStockMovement;
use App\Services\ReceiptWorkflow;
use App\Services\RequisitionWorkflow;
use App\Services\StandaloneArtifact;
use App\Services\StandaloneRuntime;
use App\Services\StockWorkflow;
use App\Services\SupplyCoordination;
use App\Services\SupplyPlanning;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
require_once __DIR__.'/../Support/StandaloneCompositionFixture.php';
beforeEach(function () {
config(['inventory_conversion.qa_enabled' => true]);
$this->operationalConversion = getenv('COMPRAS_STANDALONE_CONVERSION_QA') === '1';
if ($this->operationalConversion) {
prepareSyntheticStandaloneRuntime();
}
config(['inventory_conversion.qa_enabled' => ! $this->operationalConversion,
'inventory_conversion.enabled' => $this->operationalConversion]);
$this->f = receiptFixture();
// New consistent synthetic process: 2 boxes x 100 MZN = 200 MZN. Original fixture is untouched.
$request = $this->f['r']->replicate();
@@ -55,6 +66,7 @@ beforeEach(function () {
});
test('two boxes retain two documentary units and 200 MZN while crediting exactly 24 physical units once', function () {
$this->get($this->url)->assertOk()->assertInertia(fn (Assert $page) => $page->component('receipts/order')->where('conversionQaEnabled', true));
$id = $this->postJson($this->url, $this->body)->assertCreated()->json('id');
$this->postJson($this->url, $this->body)->assertOk()->assertJsonPath('id', $id);
$line = GoodsReceipt::query()->findOrFail($id)->items()->sole();
@@ -112,11 +124,53 @@ test('missing source factor and nonrepresentable physical quantities never creat
});
test('conversion is not enabled by its presence in a request and cannot escape the QA guard', function () {
config(['inventory_conversion.qa_enabled' => false]);
config(['inventory_conversion.qa_enabled' => false, 'inventory_conversion.enabled' => false]);
$this->postJson($this->url, $this->body)->assertUnprocessable();
expect(StockMovement::query()->count())->toBe(0);
});
test('a frozen conversion refuses fallback to the legacy inventory writer when the component is disabled', function () {
$this->postJson($this->url, $this->body)->assertCreated();
config(['inventory_conversion.qa_enabled' => false, 'inventory_conversion.enabled' => false]);
expect(fn () => app(ReceiptStockMovement::class)->load())->toThrow(LogicException::class, 'COMPRAS_INVENTORY_DOWNGRADE_REFUSED');
expect(StockMovement::query()->sole()->quantity_milli)->toBe(24000);
});
test('an interrupted outer transaction rolls back the converted receipt and retries once with the same physical quantity', function () {
expect(fn () => DB::transaction(function () {
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], $this->body);
throw new RuntimeException('synthetic interruption after movement');
}))->toThrow(RuntimeException::class, 'synthetic interruption after movement');
expect(GoodsReceipt::query()->count())->toBe(0)->and(StockMovement::query()->count())->toBe(0);
$this->postJson($this->url, $this->body)->assertCreated();
$this->postJson($this->url, $this->body)->assertOk();
expect(StockMovement::query()->sole()->quantity_milli)->toBe(24000);
});
test('operational conversion refuses an unbound installation and mixed QA configuration before stock effects', function () {
if (! $this->operationalConversion) {
$this->markTestSkipped('Operational installation checks run with the owned PostgreSQL standalone runner.');
}
$runtime = app(InventoryConversionRuntime::class);
config(['inventory_conversion.qa_enabled' => true]);
expect(fn () => $runtime->root())->toThrow(LogicException::class, 'COMPRAS_INVENTORY_CONFIGURATION');
config(['inventory_conversion.qa_enabled' => false]);
$settings = config('standalone-runtime');
$settings['installation_id'] = (string) Str::uuid();
app()->instance(StandaloneRuntime::class, new StandaloneRuntime($settings, new StandaloneArtifact));
expect(fn () => $runtime->root())->toThrow(LogicException::class, 'COMPRAS_RUNTIME_INSTALLATION_MISMATCH');
expect(StockMovement::query()->count())->toBe(0)->and(GoodsReceipt::query()->count())->toBe(0);
});
test('operational conversion refuses an incomplete inventory schema before loading a writer', function () {
if (! $this->operationalConversion) {
$this->markTestSkipped('Operational schema checks run with the owned PostgreSQL standalone runner.');
}
DB::statement('ALTER TABLE goods_receipt_items DROP COLUMN notes');
expect(fn () => app(InventoryConversionRuntime::class)->root())->toThrow(LogicException::class, 'COMPRAS_INVENTORY_SCHEMA');
expect(StockMovement::query()->count())->toBe(0);
});
test('legacy receipt facts retain the exact v1 hash and compatible replay without a conversion basis', function () {
$this->f['stock']->update(['unit' => 'cx']);
$body = $this->body;
+9
View File
@@ -12,6 +12,7 @@ use App\Services\ReceiptWorkflow;
use App\Services\RequisitionWorkflow;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
use Tempo\Inventory\ReceiptMovementWriter;
require_once __DIR__.'/../Support/ReceiptFixture.php';
@@ -28,6 +29,14 @@ test('receipt preparation uses encrypted history without registering a receipt o
expect(GoodsReceipt::query()->count())->toBe(0)->and(StockMovement::query()->count())->toBe(0);
});
test('legacy receipts remain usable after agreement conversion arithmetic is loaded without selecting another stock writer', function () {
require_once base_path('packages/inventory-write/development/src/QuantityConversion.php');
$this->postJson($this->url, $this->payload)->assertCreated();
expect(StockMovement::query()->sole()->quantity_milli)->toBe(600);
$writer = new ReflectionClass(ReceiptMovementWriter::class);
expect(realpath($writer->getFileName()))->toBe(realpath(base_path('packages/inventory-write/releases/0.1.0/src/ReceiptMovementWriter.php')));
});
test('partial then total receipts preserve pending quantities and credit only accepted stock', function () {
$this->postJson($this->url, receiptPayload($this->f, '0.400'))->assertCreated()->assertJsonPath('status', 'partial');
$first = GoodsReceipt::query()->firstOrFail();
@@ -12,6 +12,8 @@ use App\Services\CommonPaymentFacts;
use App\Services\ExpenseAllocations;
use App\Services\GeneralLedger;
use App\Services\InvoiceWorkflow;
use App\Services\OrderCancellationRuntime;
use App\Services\OrderCancellationWorkflow;
use App\Services\ProcurementPaymentInsights;
use App\Services\RequisitionAccountAssignments;
use App\Services\RequisitionExpiry;
@@ -27,10 +29,13 @@ use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Tempo\Finance\Budget\BudgetContext;
use Tempo\Finance\Budget\BudgetFailure;
use Tempo\Finance\OrderCancellation\CommitmentReversal;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/PaymentFixture.php';
require_once __DIR__.'/../Support/IssuedOrderCancellationFixture.php';
beforeEach(function () {
if (getenv('COMPRAS_STANDALONE_BUSINESS_QA') !== '1') {
@@ -84,6 +89,38 @@ test('standalone candidate preserves explicit line account attribution without a
expect(DB::table('supply_records')->where('kind', 'req_account')->count())->toBe(1);
});
test('issued order cancellation reverses the current resubmission cycle and preserves the closed reservation history', function (int $cycle) {
issuedOrderCancellationFixture($this, $cycle);
$origin = $this->f['r']->id;
$first = DB::table('budget_entries')->where('requisition_id', $origin)->where('requisition_cycle', '<', $cycle)->orderBy('id')->get()->toJson();
$workflow = app(OrderCancellationWorkflow::class);
$this->actingAs($this->buyer);
$record = $workflow->request($this->buyer, $this->f['order'], $this->data);
$this->actingAs($this->finance);
$workflow->decide($this->finance, $record, 'approved', 'Independent synthetic cancellation after request resubmission');
$workflow->decide($this->finance, $record, 'approved', 'Independent synthetic cancellation after request resubmission');
$reversal = DB::table('budget_entries')->where('requisition_id', $origin)->where('kind', 'order-cancel-'.$this->f['order']->id)->sole();
expect((int) $reversal->requisition_cycle)->toBe($cycle)
->and(DB::table('budget_entries')->where('requisition_id', $origin)->where('requisition_cycle', '<', $cycle)->orderBy('id')->get()->toJson())->toBe($first)
->and((int) DB::table('budget_entries')->where('requisition_id', $origin)->where('requisition_cycle', $cycle)->sum('committed_minor'))->toBe(0)
->and($this->f['r']->fresh()->status)->toBe('cancelled');
})->with([1, 2]);
test('cycle-aware cancellation refuses a stale or missing cycle map without appending a reversal', function () {
issuedOrderCancellationFixture($this, 2);
$origin = $this->f['r']->id;
$before = DB::table('budget_entries')->orderBy('id')->get()->toJson();
app(OrderCancellationRuntime::class)->load($origin);
foreach ([[], [$origin => 1]] as $cycles) {
$context = (new ReflectionClass(BudgetContext::class))->newInstanceArgs([
$this->finance->id, ['tenant_id' => $this->finance->tenant_id], (int) now()->year, 'MZN', $cycles,
]);
expect(fn () => DB::transaction(fn () => (new CommitmentReversal)->reverse(DB::connection(), $context, $origin, $this->f['order']->id)))->toThrow(LogicException::class);
}
expect(DB::table('budget_entries')->orderBy('id')->get()->toJson())->toBe($before)
->and($this->f['r']->fresh()->status)->toBe('approved');
});
test('standalone candidate closes an old reservation cycle and reserves a revised amount once without rewriting history', function () {
$finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id,
'purchasing_role' => PurchasingRole::Finance]);
@@ -4,13 +4,14 @@ use App\Enums\PurchasingRole;
use App\Models\Budget;
use App\Models\User;
use App\Services\BudgetWorkflow;
use App\Services\CommonBudget;
use App\Services\OrderCancellationPolicyWorkflow;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
require_once __DIR__.'/../Support/ReceiptFixture.php';
function issuedOrderCancellationFixture(object $test): void
function issuedOrderCancellationFixture(object $test, int $cycle = 1): void
{
config(['order_cancellation.enabled' => true]);
$test->f = receiptFixture();
@@ -33,7 +34,19 @@ function issuedOrderCancellationFixture(object $test): void
$test->budget = Budget::query()->create(['tenant_id' => $test->f['tenant']->id, 'cost_center_id' => $test->f['r']->cost_center_id, 'year' => now()->year,
'amount_minor' => 20000, 'includes_tax' => true, 'reason' => 'Dotação fictícia para ensaio da reversão.', 'created_by' => $test->finance->id,
'approved_by' => $test->admins[0]->id, 'approved_at' => now()]);
DB::transaction(function () use ($test) {
DB::transaction(function () use ($test, $cycle) {
if ($cycle === 2) {
$origin = $test->f['r']->id;
$adapter = app(CommonBudget::class);
$first = $adapter->for($test->finance, [$origin => 1]);
$first->beginRequisitionCycle($origin, 1, (string) Str::uuid());
$first->record($origin, $test->f['r']->cost_center_id, 'operating', 'reserve', 10000, 10000);
$first->record($origin, $test->f['r']->cost_center_id, 'operating', 'release');
$first->closeRequisitionCycle($origin, 1, (string) Str::uuid());
$second = $adapter->for($test->finance, [$origin => 2]);
$second->beginRequisitionCycle($origin, 2, (string) Str::uuid());
$test->f['r']->forceFill(['approval_cycle' => 2])->save();
}
foreach (['reserve', 'award', 'commit'] as $kind) {
app(BudgetWorkflow::class)->record($test->finance, $test->f['r'], $kind, 10000, 10000);
}
@@ -0,0 +1,33 @@
<?php
use App\Services\StandaloneArtifact;
use App\Services\StandaloneRuntime;
use Illuminate\Support\Facades\DB;
/** Own PostgreSQL QA database only; no active installation or business fixture. */
function prepareSyntheticStandaloneRuntime(): void
{
if (getenv('COMPRAS_STANDALONE_BUSINESS_QA') !== '1' || ! app()->environment('testing') || DB::getDriverName() !== 'pgsql'
|| DB::connection()->getConfig('host') !== '127.0.0.1'
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName())) {
throw new LogicException('Synthetic standalone business database required.');
}
$settings = config('standalone-runtime');
$settings['enabled'] = true;
$settings['prepare_only'] = false;
$settings['features'] = array_fill_keys(StandaloneRuntime::FEATURES, true);
config(['standalone-runtime' => [...$settings, 'enabled' => false], 'common-payables.source_instance' => 'standalone-business-synthetic']);
$runtime = new StandaloneRuntime($settings, new StandaloneArtifact);
$runtime->artifact();
(require base_path('database/standalone-migrations/2026_11_29_000001_create_runtime_installations.php'))->up();
DB::table('compras_runtime_installations')->insert(['id' => $settings['installation_id'], 'product' => 'compras',
'contract' => StandaloneArtifact::CONTRACT, 'manifest_sha256' => $settings['manifest_sha256'],
'database_binding_sha256' => StandaloneRuntime::databaseBinding(DB::connection()),
'recorded_by' => 'Synthetic standalone business regression', 'reason' => 'Authorised isolated candidate verification', 'installed_at' => now()]);
(require base_path('database/standalone-migrations/2026_11_29_000002_install_standalone_extensions.php'))->up();
config(['standalone-runtime' => $settings]);
app()->instance(StandaloneRuntime::class, $runtime);
$paths = $runtime->configure(DB::connection());
config(['general-ledger.path' => $paths['general-ledger']]);
$runtime->assertLoadedPackages();
}
@@ -0,0 +1,34 @@
<?php
// Synthetic owned loopback only. Normal authentication and all product middleware remain enabled.
use Illuminate\Http\Request;
$root = realpath(getenv('SGC_STANDALONE_QA_ROOT') ?: '');
$database = getenv('DB_DATABASE') ?: '';
if (getenv('APP_ENV') !== 'standalone-qa' || getenv('COMPRAS_RUNTIME_ENABLED') !== 'true'
|| getenv('COMPRAS_RUNTIME_PREPARE_ONLY') !== 'false' || getenv('COMPRAS_RUNTIME_SYNTHETIC_ONLY') !== 'true'
|| getenv('COMPRAS_INVENTORY_CONVERSION_ENABLED') !== 'true'
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $database, $matches)
|| getenv('DB_USERNAME') !== 'payable_history_native_'.$matches[1]
|| getenv('DB_HOST') !== '127.0.0.1' || getenv('DB_PORT') !== '55439'
|| ($_SERVER['REMOTE_ADDR'] ?? '') !== '127.0.0.1' || ($_SERVER['SERVER_PORT'] ?? '') != getenv('SGC_STANDALONE_QA_PORT')
|| $root === false || dirname($root) !== realpath(__DIR__.'/../../storage/framework/testing')
|| basename($root) !== 'rq01-ledger-qa-'.$matches[1]) {
http_response_code(503);
exit;
}
require __DIR__.'/../../vendor/autoload.php';
$public = $root.'/public';
$requestPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$asset = realpath($public.'/'.ltrim(rawurldecode($requestPath), '/'));
$types = ['js' => 'text/javascript', 'css' => 'text/css', 'svg' => 'image/svg+xml', 'png' => 'image/png', 'ico' => 'image/x-icon', 'woff' => 'font/woff', 'woff2' => 'font/woff2'];
if ($asset !== false && is_file($asset) && str_starts_with(str_replace('\\', '/', $asset), str_replace('\\', '/', $public).'/')
&& isset($types[pathinfo($asset, PATHINFO_EXTENSION)])) {
header('Content-Type: '.$types[pathinfo($asset, PATHINFO_EXTENSION)]);
readfile($asset);
exit;
}
$app = require __DIR__.'/../../bootstrap/app.php';
$app->useStoragePath($root.'/storage');
$app->usePublicPath($public);
$app->handleRequest(Request::capture());
@@ -0,0 +1,118 @@
<?php
use App\Models\GoodsReceiptItem;
use App\Models\OrderCancellation;
use App\Models\User;
use App\Services\ConflictGuard;
use App\Services\InventoryConversionRuntime;
use App\Services\OrderCancellationRuntime;
use App\Services\OrderCancellationWorkflow;
use App\Services\ReceiptQuantityConversion;
use App\Services\ReceiptStockMovement;
use App\Services\StandaloneInstallation;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
require dirname(__DIR__, 2).'/vendor/autoload.php';
$database = $argv[1] ?? '';
$mode = $argv[2] ?? '';
$root = realpath(getenv('SGC_STANDALONE_QA_ROOT') ?: '');
if (! preg_match('/^compras_receipts_test_([a-f0-9]{12})(_restored)?$/D', $database, $match)
|| getenv('DB_DATABASE') !== $database || getenv('DB_HOST') !== '127.0.0.1' || getenv('DB_PORT') !== '55439'
|| getenv('DB_USERNAME') !== 'payable_history_native_'.$match[1].($match[2] ?? '')
|| getenv('APP_ENV') !== 'standalone-qa' || getenv('COMPRAS_STANDALONE_CONVERSION_QA') !== '1'
|| $root === false || dirname($root) !== realpath(dirname(__DIR__, 2).'/storage/framework/testing')
|| basename($root) !== 'rq01-ledger-qa-'.$match[1] || ! in_array($mode, ['read', 'read-cancellation', 'reject-restore', 'rebind'], true)) {
throw new LogicException('Owned synthetic inventory recovery required.');
}
$app = require dirname(__DIR__, 2).'/bootstrap/app.php';
$app->useStoragePath($root.'/recovery-storage');
try {
$app->make(Kernel::class)->bootstrap();
} catch (LogicException $e) {
if ($mode !== 'reject-restore' || $e->getMessage() !== 'COMPRAS_RUNTIME_INSTALLATION_MISMATCH') {
throw $e;
}
echo json_encode(['rejected' => true, 'reason' => $e->getMessage()], JSON_THROW_ON_ERROR);
exit;
}
if ($mode === 'reject-restore') {
throw new LogicException('Restored database started with the original binding.');
}
if (DB::selectOne("select current_setting('cluster_name') as name")->name !== 'sgf_modular_regression_'.$match[1]) {
throw new LogicException('Owned recovery cluster required.');
}
if ($mode === 'rebind') {
$result = app(StandaloneInstallation::class)->prepare($database, getenv('DB_USERNAME'), 'Synthetic inventory recovery',
'Authorised isolated backup restoration', apply: true, rebind: true);
if ($result['state'] !== 'rebound') {
throw new LogicException('Recovery binding not recorded.');
}
echo json_encode(['state' => 'rebound'], JSON_THROW_ON_ERROR);
exit;
}
if (! app(InventoryConversionRuntime::class)->available() || config('inventory_conversion.qa_enabled') !== false) {
throw new LogicException('Operational inventory component required.');
}
$frames = static function (): array {
$hashes = [];
foreach (DB::select("select tablename from pg_tables where schemaname='public' order by tablename") as $table) {
if ($table->tablename === 'compras_runtime_installations') {
continue;
}
$rows = DB::table($table->tablename)->get()->map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR))->all();
sort($rows, SORT_STRING);
$hashes[$table->tablename] = hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR));
}
return $hashes;
};
$hashes = $frames();
$cancellation = $mode === 'read-cancellation';
if ($cancellation) {
app(OrderCancellationRuntime::class)->assertReady();
$record = DB::table('order_cancellations')->sole();
$actor = User::query()->findOrFail($record->reviewed_by);
auth()->guard()->setUser($actor);
$model = OrderCancellation::query()->findOrFail($record->id);
app(OrderCancellationWorkflow::class)->decide($actor, $model, 'approved', $record->review_reason);
$order = DB::table('purchase_orders')->where('id', $record->purchase_order_id)->firstOrFail();
$reversal = DB::table('budget_entries')->where('requisition_id', $order->requisition_id)->where('kind', 'order-cancel-'.$order->id)->sole();
if ((int) $reversal->requisition_cycle !== 2 || $record->status !== 'approved'
|| (int) DB::table('budget_entries')->where('requisition_id', $order->requisition_id)->where('requisition_cycle', 2)->sum('committed_minor') !== 0) {
throw new LogicException('Recovered cancellation cycle or balance changed.');
}
} else {
$movements = DB::table('stock_movements')->whereNotNull('snapshot->quantity_conversion')->get();
if ($movements->count() !== 2) {
throw new LogicException('Both synthetic contention scenarios must survive recovery.');
}
foreach ($movements as $movement) {
$snapshot = json_decode($movement->snapshot, true, 512, JSON_THROW_ON_ERROR);
$actor = User::query()->findOrFail($movement->moved_by);
auth()->guard()->setUser($actor);
$line = GoodsReceiptItem::query()->findOrFail($movement->goods_receipt_item_id);
if (app(ReceiptQuantityConversion::class)->documentary($line, (int) $movement->quantity_milli) !== 1000) {
throw new LogicException('Restored documentary equivalence changed.');
}
$result = DB::transaction(function () use ($actor, $movement, $snapshot) {
app(ConflictGuard::class)->lockCompany($actor);
return app(ReceiptStockMovement::class)->for($actor)->write($movement->goods_receipt_item_id, $snapshot['inventory_source_hash']);
});
if ($result['replayed'] !== true || (int) $result['movement_id'] !== (int) $movement->id) {
throw new LogicException('Restored movement was not replayed exactly.');
}
}
}
$original = DB::table('compras_runtime_installations')->where('id', getenv('COMPRAS_QA_ORIGINAL_INSTALLATION_ID'))->first();
if ($original === null) {
throw new LogicException('Original immutable installation history lost.');
}
if ($frames() !== $hashes) {
throw new LogicException('Replay changed synthetic business data.');
}
echo json_encode(['business_tables' => count($hashes), 'business_sha256' => hash('sha256', json_encode($hashes, JSON_THROW_ON_ERROR)),
'original_installation_sha256' => hash('sha256', json_encode($original, JSON_THROW_ON_ERROR)),
...($cancellation ? ['approved_cancellations' => 1, 'source_cycle' => 2, 'exact_replays' => 1]
: ['converted_movements' => 2, 'exact_replays' => 2])], JSON_THROW_ON_ERROR);
+28
View File
@@ -0,0 +1,28 @@
<?php
use App\Services\DeadlineTaskGuiAction;
function syntheticDeadlineGuiXml(): string
{
return '<Task xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>'
.'<ExecutionTimeLimit>PT1M</ExecutionTimeLimit></Settings><Actions><Exec><Command>C:/synthetic/php.exe</Command>'
.'<Arguments>"C:/synthetic/deadlines.php" --once</Arguments><WorkingDirectory>C:/synthetic</WorkingDirectory></Exec></Actions></Task>';
}
test('silent deadline correction preserves arguments working directory overlap and limits', function () {
$xml = syntheticDeadlineGuiXml();
$after = DeadlineTaskGuiAction::replacement($xml, 'C:/synthetic/php.exe', 'C:/synthetic/php-win.exe');
expect($after)->toContain('php-win.exe')->toContain('"C:/synthetic/deadlines.php" --once')->toContain('IgnoreNew')->toContain('PT1M');
DeadlineTaskGuiAction::assertConserved($xml, $after, 'C:/synthetic/php.exe', 'C:/synthetic/php-win.exe');
DeadlineTaskGuiAction::assertConserved($xml, str_replace('><', ">\r\n <", $after), 'C:/synthetic/php.exe', 'C:/synthetic/php-win.exe');
expect(DeadlineTaskGuiAction::canonical(str_replace('><', ">\r\n <", $xml)))->toBe(DeadlineTaskGuiAction::canonical($xml));
expect(fn () => DeadlineTaskGuiAction::assertConserved($xml, str_replace('PT1M', 'PT5M', $after), 'C:/synthetic/php.exe', 'C:/synthetic/php-win.exe'))
->toThrow(LogicException::class, 'DEADLINE_TASK_GUI_UNRELATED_DEFINITION_CHANGE');
});
test('silent deadline correction refuses another executable directory or multiple actions', function () {
$xml = syntheticDeadlineGuiXml();
expect(fn () => DeadlineTaskGuiAction::replacement($xml, 'C:/synthetic/php.exe', 'C:/other/php-win.exe'))->toThrow(LogicException::class, 'DEADLINE_TASK_GUI_EXECUTABLE_PAIR');
expect(fn () => DeadlineTaskGuiAction::replacement(str_replace('</Actions>', '<Exec><Command>other</Command></Exec></Actions>', $xml), 'C:/synthetic/php.exe', 'C:/synthetic/php-win.exe'))
->toThrow(LogicException::class, 'DEADLINE_TASK_GUI_ACTION_MISMATCH');
});
@@ -0,0 +1,53 @@
<?php
use App\Services\InventoryConversionRuntime;
test('inventory archive validates exact entry names independently of insertion order', function () {
$path = sys_get_temp_dir().'/compras-inventory-entries-'.bin2hex(random_bytes(8)).'.zip';
$zip = new ZipArchive;
try {
expect($zip->open($path, ZipArchive::CREATE | ZipArchive::EXCL))->toBeTrue();
foreach (['src/ReceiptMovementWriter.php', 'src/QuantityConversion.php', 'bootstrap.php', 'manifest.json'] as $name) {
$zip->addFromString($name, 'synthetic archive entry');
}
$zip->close();
$zip->open($path);
InventoryConversionRuntime::assertArchiveEntries($zip);
expect($zip->numFiles)->toBe(4);
$zip->addFromString('../unexpected.php', 'synthetic forbidden entry');
expect(fn () => InventoryConversionRuntime::assertArchiveEntries($zip))->toThrow(LogicException::class, 'COMPRAS_INVENTORY_ARCHIVE_ENTRIES');
$zip->deleteName('../unexpected.php');
$zip->deleteName('bootstrap.php');
expect(fn () => InventoryConversionRuntime::assertArchiveEntries($zip))->toThrow(LogicException::class, 'COMPRAS_INVENTORY_ARCHIVE_ENTRIES');
} finally {
$zip->close();
if (is_file($path)) {
unlink($path);
}
}
});
test('inventory candidate rejects changed component bytes and manifests before loading PHP', function () {
$source = dirname(__DIR__, 2).'/packages/inventory-write/releases/0.2.0-rc.1';
$root = sys_get_temp_dir().'/compras-inventory-artifact-'.bin2hex(random_bytes(8));
mkdir($root.'/src', 0700, true);
$files = ['manifest.json', 'bootstrap.php', 'src/QuantityConversion.php', 'src/ReceiptMovementWriter.php'];
try {
foreach ($files as $file) {
copy($source.'/'.$file, $root.'/'.$file);
}
InventoryConversionRuntime::verifyArtifact($root);
expect(hash_file('sha256', $root.'/manifest.json'))->toBe(InventoryConversionRuntime::MANIFEST_SHA256);
file_put_contents($root.'/src/QuantityConversion.php', "\n// altered", FILE_APPEND);
expect(fn () => InventoryConversionRuntime::verifyArtifact($root))->toThrow(LogicException::class, 'COMPRAS_INVENTORY_FILE:src/QuantityConversion.php');
copy($source.'/src/QuantityConversion.php', $root.'/src/QuantityConversion.php');
file_put_contents($root.'/manifest.json', "\n", FILE_APPEND);
expect(fn () => InventoryConversionRuntime::verifyArtifact($root))->toThrow(LogicException::class, 'COMPRAS_INVENTORY_MANIFEST');
} finally {
foreach ($files as $file) {
unlink($root.'/'.$file);
}
rmdir($root.'/src');
rmdir($root);
}
});
@@ -0,0 +1,13 @@
<?php
use App\Services\ReplenishmentTaskDefinition;
test('native omitted limited run level remains equivalent but elevation and frequency changes are refused', function () {
$xml = '<Task xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><Triggers><TimeTrigger><Repetition><Interval>PT1M</Interval></Repetition></TimeTrigger><LogonTrigger><UserId>S-1-5-21-1</UserId></LogonTrigger></Triggers><Principals><Principal><UserId>S-1-5-21-1</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals><Actions><Exec><Command>C:/synthetic/php-win.exe</Command></Exec></Actions></Task>';
$xml = str_replace('<Actions>', '<Settings><AllowHardTerminate>true</AllowHardTerminate></Settings><Actions>', $xml);
ReplenishmentTaskDefinition::assertMatches($xml, str_replace(['<RunLevel>LeastPrivilege</RunLevel>', '<AllowHardTerminate>true</AllowHardTerminate>'], '', $xml));
expect(true)->toBeTrue();
foreach ([str_replace('LeastPrivilege', 'HighestAvailable', $xml), str_replace('PT1M', 'PT5M', $xml), str_replace('S-1-5-21-1', 'S-1-5-18', $xml), str_replace('<AllowHardTerminate>true', '<AllowHardTerminate>false', $xml)] as $changed) {
expect(fn () => ReplenishmentTaskDefinition::assertMatches($xml, $changed))->toThrow(LogicException::class);
}
});
@@ -12,6 +12,43 @@ import {
searchProcurementMenu,
} from '@/lib/procurement-menu-search';
test('common payment attribution retains its existing authorised finance menu entry', () => {
const path = '/afectacoes-fornecedores/12/imputacao';
expect(
activeProcurementEntry(
procurementNavigation(
['finance'],
true,
undefined,
false,
false,
false,
false,
{ payments: true },
),
path,
),
).toBe('supplier_settlements');
expect(
activeProcurementEntry(procurementNavigation(['finance'], true), path),
).toBeUndefined();
expect(
activeProcurementEntry(
procurementNavigation(
['requester'],
false,
undefined,
false,
false,
false,
false,
{ payments: true },
),
path,
),
).toBeUndefined();
});
test.each([
'/compras/fornecimento',
'/compras/fornecimento?view=agreements&record_id=12',
@@ -3,6 +3,27 @@ import { describe, expect, it } from 'vitest';
import { ProcurementPaymentInsights } from '../../resources/js/components/procurement-payment-insights';
describe('confirmed payment expense', () => {
it('describes one confirmed payment in the singular without changing the exact amount', () => {
const html = renderToStaticMarkup(
<ProcurementPaymentInsights
data={{
from: null,
to: null,
coverage: {
invoices: 1,
indeterminate: 0,
confirmed_payments: 1,
},
currencies: [
{ currency: 'MZN', count: 1, amount_minor: '4000' },
],
}}
/>,
);
expect(html).toContain('1 pagamento confirmado.');
expect(html).toContain('40,00 MZN');
expect(html).not.toContain('1 pagamentos');
});
it('shows supplier identity with exact totals and preserves filters in its independent pagination', () => {
const html = renderToStaticMarkup(
<ProcurementPaymentInsights