commit compras3 2811
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-28 18:16:04 +02:00
parent 060c119ba1
commit 1ddabbbdcc
41 changed files with 1341 additions and 138 deletions
+13 -5
View File
@@ -8,6 +8,8 @@ use App\Services\ImportBankSupport;
use App\Services\ImportEstimates;
use App\Services\ImportLegalEstimates;
use App\Services\ImportLegalRules;
use App\Services\RequisitionExpiry;
use App\Services\RequisitionWorkflow;
use App\Services\SupplyPlanning;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
@@ -29,6 +31,7 @@ $corpus = realpath($argv[3] ?? '');
$candidateRelative = $argv[4] ?? '';
$candidateHash = $argv[5] ?? '';
$expiryReview = ($argv[2] ?? '') === 'expiry-review';
$referenceHttp = ($argv[2] ?? '') === 'legal-reference-http';
$reviewMode = ($argv[2] ?? '') === 'legal-review' || $expiryReview;
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database
|| DB::connection()->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)
@@ -40,8 +43,9 @@ require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
require_once __DIR__.'/../Support/ImportLegalQaFixture.php';
require_once __DIR__.'/../Support/ImportBankQaFixture.php';
$files = glob(str_replace('\\', '/', $corpus).'/Legislacao/2022/12 Dezembro/series-i/br-series-i-29-12-2022-*.pdf');
if ($files === false || count($files) !== 1 || filesize($files[0]) <= 2097152) {
$files = $referenceHttp ? [$corpus.'/novas/BR_248_I_SERIE_SUPLEMENTO_2025.pdf']
: glob(str_replace('\\', '/', $corpus).'/Legislacao/2022/12 Dezembro/series-i/br-series-i-29-12-2022-*.pdf');
if ($files === false || count($files) !== 1 || ! is_file($files[0]) || filesize($files[0]) < 1 || (! $referenceHttp && filesize($files[0]) <= 2097152)) {
throw new LogicException('Select the complete shared official journal, not a small extracted example.');
}
$path = $files[0];
@@ -103,7 +107,7 @@ try {
throw new RuntimeException('Native HTTP source requests must require CSRF: '.$negative->getStatusCode());
}
$input = ['operation_key' => (string) Str::uuid(), 'action' => 'source', 'version' => '0',
'official_reference' => 'BR I Série 251 de 29/12/2022 — exemplar integral real partilhado',
'official_reference' => $referenceHttp ? 'BR I Série 248, suplemento, 29/12/2025 — exemplar integral real partilhado' : 'BR I Série 251 de 29/12/2022 — exemplar integral real partilhado',
'reason' => 'Ensaio HTTP estritamente QA com exemplar oficial real, empresa e conta sintéticas; sem publicar regras'];
foreach ([1, 2] as $attempt) {
$multipart = array_map(fn ($name) => ['name' => $name, 'contents' => $input[$name]], array_keys($input));
@@ -124,6 +128,9 @@ try {
}
$props = json_decode((string) $page->getBody(), true, 64, JSON_THROW_ON_ERROR)['props'] ?? [];
$source = SupplyRecord::query()->where('kind', 'import_legal_source')->sole();
if (count($props['referenceDrafts'] ?? []) !== ($referenceHttp ? 48 : 0) || ($props['referenceDraftWarnings'] ?? []) !== []) {
throw new RuntimeException('The native legal workspace did not preserve the edition-specific documentary draft scope.');
}
$download = $client->get($route.'/fontes/'.$source->id);
$guest = new Client(['base_uri' => $url, 'http_errors' => false, 'allow_redirects' => false, 'timeout' => 10]);
$anonymous = $guest->get($route.'/fontes/'.$source->id, ['headers' => ['Accept' => 'application/json']]);
@@ -143,6 +150,7 @@ try {
'original_sha256' => $originalHash, 'original_unchanged' => true, 'exact_native_download' => true, 'one_source_one_audit_after_replay' => true,
'guest_status' => 401, 'revoked_status' => 403, 'rules_published' => 0, 'financial_stock_unchanged' => true,
'private_upload_limit' => '64M', 'private_post_limit' => '70M', 'global_php_config_unchanged' => true];
$result['documentary_reference_drafts'] = count($props['referenceDrafts'] ?? []);
if ($reviewMode) {
// Existing factory password is confined to guarded, disposable synthetic QA identities.
$reviewer = $f['otherReceiver'];
@@ -188,10 +196,10 @@ try {
supplyGrant($reviewer, ['admin', 'procurement', 'requester', 'import_read', 'import_prepare', 'import_customs']);
$head = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
supplyGrant($head, ['department_head']);
app(\App\Services\RequisitionExpiry::class)->savePolicy($reviewer, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true,
app(RequisitionExpiry::class)->savePolicy($reviewer, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true,
'levels' => [['role' => 'department_head', 'expire_minutes' => 30, 'reminder_minutes' => 10, 'escalation_minutes' => null, 'profile_ids' => []]],
'reason' => 'Política estritamente sintética para revisão visual do ciclo']);
$workflow = app(\App\Services\RequisitionWorkflow::class);
$workflow = app(RequisitionWorkflow::class);
$expiryRequest = $workflow->save($reviewer, ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['r']->cost_center_id, 'priority' => 'normal',
'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Ensaio visual sintético da devolução e nova submissão',
'items' => [['description' => 'Material sintético do ciclo', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00']]]);
@@ -0,0 +1,130 @@
<?php
use App\Models\PrivateAuditExport;
use App\Models\SupplierDocument;
use App\Models\User;
use App\Services\PrivateAuditAccess;
use App\Services\PrivateAuditExporter;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Tempo\Finance\GeneralLedger\LedgerSchema;
require __DIR__.'/../../vendor/autoload.php';
$root = realpath(getenv('SGC_REQUISITION_QA_ROOT') ?: '');
$boundary = realpath(__DIR__.'/../../storage/framework/testing');
$mode = $argv[2] ?? '';
$database = $argv[1] ?? '';
if ($root === false || $boundary === false || dirname($root) !== $boundary
|| ! preg_match('/^rq01-ledger-qa-[a-f0-9]{12}$/D', basename($root))
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)
|| ! in_array($mode, ['prepare', 'verify'], true)) {
throw new LogicException('Owned private audit recovery root required.');
}
$app = require __DIR__.'/../../bootstrap/app.php';
$app->useStoragePath($root.'/audit-worker-storage');
$app->make(Kernel::class)->bootstrap();
if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql'
|| DB::connection()->getConfig('host') !== '127.0.0.1'
|| (string) DB::connection()->getConfig('port') !== '55439'
|| DB::connection()->getDatabaseName() !== $database) {
throw new LogicException('Only the owned synthetic PostgreSQL recovery is permitted.');
}
require_once __DIR__.'/../Support/RequisitionLedgerQaRuntime.php';
$source = requisitionLedgerQaSource();
if ($source === null || getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') !== '1') {
throw new LogicException('Complete private composition required.');
}
require_once $source.'/bootstrap.php';
LedgerSchema::assertSynthetic(DB::connection());
config(['private-audit.qa_enabled' => true]);
$files = $root.($mode === 'prepare' ? '/audit-source-files' : '/audit-restored-files');
foreach (['local', 'supplier_documents', 'receipt_documents'] as $disk) {
config(['filesystems.disks.'.$disk => ['driver' => 'local', 'root' => $files.'/'.$disk, 'throw' => true]]);
Storage::forgetDisk($disk);
}
$snapshot = static function (): array {
return DB::transaction(function () {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
$frames = [];
foreach (DB::select("select tablename from pg_tables where schemaname='public' order by tablename") as $table) {
$name = str_replace('"', '""', $table->tablename);
$rows = DB::select('select row_to_json(t)::text as row from "'.$name.'" t order by row_to_json(t)::text');
$frames[$table->tablename] = hash('sha256', json_encode([DB::getSchemaBuilder()->getColumnListing($table->tablename), array_column($rows, 'row')], JSON_THROW_ON_ERROR));
}
return $frames;
});
};
$service = app(PrivateAuditExporter::class);
if ($mode === 'prepare') {
LedgerSchema::install(DB::connection());
require_once __DIR__.'/../Support/IntegratedPurchasingQaSchema.php';
integratedPurchasingQaSchema();
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
$f = receiptFixture();
$actor = $f['issuer'];
auth()->guard()->setUser($actor);
supplyGrant($actor, array_column(PrivateAuditAccess::FAMILIES, 'permission'));
$bytes = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl6E4sAAAAASUVORK5CYII=');
$path = $actor->tenant_id.'/'.$f['order']->supplier_id.'/synthetic-recovery.png';
Storage::disk('supplier_documents')->put($path, $bytes);
$document = SupplierDocument::query()->create(['tenant_id' => $actor->tenant_id, 'supplier_id' => $f['order']->supplier_id,
'uploaded_by' => $actor->id, 'document_type' => 'other', 'original_name' => 'synthetic-recovery.png', 'path' => $path,
'mime_type' => 'image/png', 'size' => strlen($bytes), 'sha256' => hash('sha256', $bytes)]);
$input = ['operation_key' => (string) Str::uuid(), 'families' => array_keys(PrivateAuditAccess::FAMILIES), 'purpose' => 'Synthetic SQL and private files recovery verification'];
$export = $service->generate($actor, $input);
$service->verifiedPath($actor, $export);
echo json_encode(['actor' => $actor->id, 'export' => $export->id, 'input' => $input, 'sha256' => $export->sha256,
'size' => $export->size, 'document' => $document->id, 'source_sha256' => hash('sha256', $bytes), 'snapshot' => $snapshot()], JSON_THROW_ON_ERROR);
exit;
}
$fixture = json_decode($argv[3], true, 64, JSON_THROW_ON_ERROR);
if ($snapshot() !== $fixture['snapshot']) {
throw new RuntimeException('Restored audit database differs in tables, columns or rows.');
}
$actor = User::query()->findOrFail($fixture['actor']);
auth()->guard()->setUser($actor);
$export = PrivateAuditExport::query()->findOrFail($fixture['export']);
$path = $service->verifiedPath($actor, $export);
$document = SupplierDocument::query()->findOrFail($fixture['document']);
if (hash_file('sha256', $path) !== $fixture['sha256'] || filesize($path) !== $fixture['size']
|| hash('sha256', Storage::disk('supplier_documents')->get($document->path)) !== $fixture['source_sha256']
|| $service->generate($actor, $fixture['input'])->id !== $export->id) {
throw new RuntimeException('Restored archive, original or replay differs.');
}
$zip = new ZipArchive;
if ($zip->open($path, ZipArchive::RDONLY) !== true) {
throw new RuntimeException('Restored archive cannot be read.');
}
try {
if (hash('sha256', $zip->getFromName('originais/purchasing/supplier_documents/'.$document->id.'.png')) !== $fixture['source_sha256']) {
throw new RuntimeException('Original inside restored archive differs.');
}
} finally {
$zip->close();
}
DB::beginTransaction();
try {
DB::table('organization_memberships')->where('user_id', $actor->id)->update(['expires_at' => now()->subMinute()]);
try {
$service->verifiedPath($actor, $export);
throw new RuntimeException('Restored archive ignored current revoked authority.');
} catch (HttpExceptionInterface $error) {
if ($error->getStatusCode() !== 403) {
throw $error;
}
}
} finally {
DB::rollBack();
}
if ($snapshot() !== $fixture['snapshot']) {
throw new RuntimeException('Audit recovery verification changed restored facts.');
}
echo json_encode(['tables_equal' => count($fixture['snapshot']), 'archive_bytes_and_hash_equal' => true,
'original_file_and_archived_copy_equal' => true, 'replay_without_effects' => true,
'current_revocation_refused' => true, 'sql_and_separate_private_files_restored' => true,
'source_file_tree_absent_during_verification' => ! is_dir($root.'/audit-source-files'), 'operational_changes' => false], JSON_THROW_ON_ERROR).PHP_EOL;
@@ -39,7 +39,7 @@ config(['requisition-accounts.qa_enabled' => true]);
require_once __DIR__.'/../Support/ReceiptFixture.php';
if ($mode === 'prepare-native-review') {
require_once __DIR__.'/../Support/RequisitionAccountsNativeReview.php';
echo json_encode(requisitionAccountsNativeReviewFixture(getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1', getenv('RQ01_NATIVE_OFFICE_JOURNEY') === '1'), JSON_THROW_ON_ERROR);
echo json_encode(requisitionAccountsNativeReviewFixture(getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1', getenv('RQ01_NATIVE_OFFICE_JOURNEY') === '1', getenv('RQ01_QA_LEGAL_REFERENCE') === '1', getenv('RQ01_QA_PRINT_PAGINATION') === '1'), JSON_THROW_ON_ERROR);
exit;
}
if ($mode === 'describe-private-audit-schema') {