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
@@ -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);