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') {
+11
View File
@@ -110,6 +110,17 @@ test('allocation enforces current Finance access and refuses unavailable or unau
expect(SupplyRecord::query()->where('kind', 'expense_allocation')->count())->toBe(0);
});
test('denied expense attribution provides a Portuguese return path without exposing the financial source or changing JSON refusals', function () {
$this->actingAs($this->f['issuer']);
$url = '/pagamentos/'.$this->payment->id.'/categorias';
$this->get($url)->assertForbidden()->assertSee('Acesso reservado')->assertSee('Voltar ao painel')
->assertSee('lang="pt-MZ"', false)->assertDontSee($this->f['invoice']->number)
->assertDontSee('TEST-PAY-ACCOUNT')->assertDontSee('TEST-EXT-01');
$this->getJson($url)->assertForbidden()->assertJsonStructure(['message'])
->assertDontSee('<!DOCTYPE html>', false)->assertDontSee('TEST-PAY-ACCOUNT');
expect(SupplyRecord::query()->where('kind', 'expense_allocation')->count())->toBe(0);
});
test('incomplete confirmation or missing allocation audit keeps analytical attribution indeterminate', function () {
$actor = $this->f['validator'];
$this->service->save($actor, $this->payment->id, $this->input);
@@ -59,6 +59,50 @@ test('unknown rates and missing bases never become zero while explicit non-appli
expect(fn () => $amounts->calculate([legalCharge(['rate_percent' => '10000'])], ['synthetic-duty' => ['value_minor' => 100000000000000, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic overflow boundary']]))->toThrow(ValidationException::class);
});
test('specific coefficients preserve fractional cents and round only the final exact charge', function () {
$amounts = app(ImportLegalAmounts::class);
$charge = legalCharge(['method' => 'specific', 'rate_percent' => null, 'specific_minor' => '1.33', 'quantity_unit' => 'g']);
// Synthetic quantity: 600 L * 10.6 g/100 ml * 10 = 63600 g.
// Coefficient0.0133 MZN/g corresponds exactly to1.33 cents/g.
$base = ['value_minor' => null, 'quantity' => '63600.000000', 'quantity_unit' => 'g', 'source' => 'Synthetic documented quantity and concentration; no implicit conversion'];
expect($amounts->definitions([$charge])[0]['specific_minor'])->toBe('1.33')
->and($amounts->calculate([$charge], ['synthetic-duty' => $base])['total_minor'])->toBe(84588)
->and($amounts->calculate([[...$charge, 'specific_minor' => '0.99']], ['synthetic-duty' => $base])['total_minor'])->toBe(62964);
foreach (['0.499999' => 0, '0.500000' => 1] as $coefficient => $expected) {
expect($amounts->calculate([[...$charge, 'specific_minor' => $coefficient]], ['synthetic-duty' => [...$base, 'quantity' => '1']])['total_minor'])->toBe($expected);
}
expect($amounts->definitions([[...$charge, 'specific_minor' => '125.000000']])[0]['specific_minor'])->toBe(125);
foreach (['0.0000001', '1e2', '-0.1', '100000000000000.000001', 0.99] as $invalid) {
expect(fn () => $amounts->definitions([[...$charge, 'specific_minor' => $invalid]]))->toThrow(ValidationException::class);
}
$maximum = [...$charge, 'method' => 'maximum', 'rate_percent' => '7.5', 'specific_minor' => '0.99'];
expect($amounts->calculate([$maximum], ['synthetic-duty' => [...$base, 'value_minor' => 10001, 'quantity' => '1000']])['total_minor'])->toBe(990);
});
test('native fractional specific estimates preserve the coefficient source and replay without financial effects', function () {
$rules = app(ImportLegalRules::class);
$charge = legalCharge(['method' => 'specific', 'rate_percent' => null, 'specific_minor' => '0.99', 'quantity_unit' => 'g']);
$draft = $rules->save($this->f['issuer'], importLegalQaInput(['charges' => [$charge]]), importLegalQaFile());
$rule = $rules->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key, 'version' => 1,
'action' => 'publish', 'reason' => 'Synthetic fractional coefficient verification, no real tax activation']);
$before = [];
foreach (['budget_entries', 'invoices', 'stock_movements'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'requisition_item_id' => $this->f['r']->items()->sole()->id,
'rule_id' => $rule->id, 'match_code' => '1234', 'origin' => 'Synthetic A', 'sector' => 'Synthetic sector', 'date' => '2026-11-27',
'bases' => ['synthetic-duty' => ['value_minor' => null, 'quantity' => '63600', 'quantity_unit' => 'g', 'source' => 'Synthetic explicit sugar mass']],
'reason' => 'Synthetic exact coefficient estimate without a budget or stock effect'];
$service = app(ImportLegalEstimates::class);
$record = $service->save($this->f['issuer'], $this->f['r'], $input);
expect($rule->data['charges'][0]['specific_minor'])->toBe('0.99')
->and($record->snapshot['result']['total_minor'])->toBe(62964)
->and($service->save($this->f['issuer'], $this->f['r'], $input)->id)->toBe($record->id);
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
});
test('native estimates freeze source bases and calculated results without reserving funds and reject stale versions', function () {
$rules = app(ImportLegalRules::class);
$draft = $rules->save($this->f['issuer'], importLegalQaInput(['charges' => [legalCharge()]]), importLegalQaFile());
@@ -1,6 +1,7 @@
<?php
use App\Models\SupplyRecord;
use App\Services\ImportLegalAmounts;
use App\Services\ImportLegalReferenceDrafts;
use App\Services\ImportLegalRules;
use Illuminate\Http\UploadedFile;
@@ -36,7 +37,7 @@ test('a supplied official edition offers exact documentary drafts without publis
new UploadedFile($path, basename($path), 'application/pdf', UPLOAD_ERR_OK, true));
$workspace = $service->workspace($this->f['issuer'], $this->f['r']);
$drafts = $workspace['referenceDrafts'];
expect($drafts)->toHaveCount(11)
expect($drafts)->toHaveCount(48)
->and(array_column($drafts, 'code'))->toContain('3506.91.20', '7604.10.10')
->and($drafts[0]['rate_percent'])->toBe('20')
->and($drafts[2]['rate_percent'])->toBe('7.5')
@@ -44,9 +45,28 @@ test('a supplied official edition offers exact documentary drafts without publis
->and($drafts[0]['citation'])->toContain('2180-(4)')
->and($drafts[0]['source_id'])->toBe($source->id)
->and($drafts[0]['charges'][0]['kind'])->toBe('duty')
->and($drafts[0]['charges'])->toHaveCount(4)
->and($workspace['referenceDraftWarnings'])->toBe([])
->and(SupplyRecord::query()->where('kind', 'import_legal_rule')->count())->toBe(0)
->and(json_encode($workspace['sources'], JSON_THROW_ON_ERROR))->not->toContain('import-legal/');
expect(array_unique(array_column($drafts, 'code')))->toHaveCount(48);
$capital = collect($drafts)->firstWhere('code', '8451.80.10');
$vehicle = collect($drafts)->firstWhere('code', '8704.21.10');
$last = collect($drafts)->firstWhere('code', '9507.90.90');
expect($capital['rate_percent'])->toBe('5')->and($capital['documentary_class'])->toBe('K')
->and($capital['obligations'])->toContain('não comprova elegibilidade')
->and($capital['citation'])->toContain('2180-(5)')
->and($vehicle['documentary_class'])->toBeNull()
->and($vehicle['obligations'])->toContain('bens de capital para investimento')
->and($last['citation'])->toContain('2180-(7)')
->and($last['rate_percent'])->toBe('5');
// A purely illustrative 100 MZN base is not a real import, debt or complete tax assessment.
$estimate = app(ImportLegalAmounts::class)->calculate($drafts[0]['charges'], ['general_duty' => [
'value_minor' => 10000, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Explicit synthetic 100 MZN unit-test base']]);
expect($estimate['known_subtotal_minor'])->toBe(2000)
->and($estimate['complete'])->toBeFalse()
->and($estimate['total_minor'])->toBeNull()
->and($estimate['financial_effects'])->toBeFalse();
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
@@ -157,3 +157,27 @@ test('private audit packages remain personal to their creator even within the sa
$this->withoutVite()->get('/auditoria/privada')->assertOk()->assertViewHas('page', fn (array $page) => $page['props']['exports']['data'] === []);
expect(PrivateAuditExport::query()->count())->toBe(1);
});
test('private audit detects a missing archive and accepts only the exact recovered private bytes without regenerating history', function () {
Storage::fake('audit_recovery');
$input = ['operation_key' => (string) Str::uuid(), 'families' => ['configuration']];
$service = app(PrivateAuditExporter::class);
$export = $service->generate($this->actor, $input);
$archive = Storage::disk('local')->get($export->path);
Storage::disk('audit_recovery')->put('original.zip', $archive);
$before = DB::table('private_audit_exports')->where('id', $export->id)->first();
$events = DB::table('audit_logs')->count();
// Remove only the known generated file in the disposable fake QA disk.
Storage::disk('local')->delete($export->path);
try {
$service->generate($this->actor, $input);
test()->fail('Missing historical packages must not be silently regenerated.');
} catch (HttpException $error) {
expect($error->getStatusCode())->toBe(409);
}
Storage::disk('local')->put($export->path, Storage::disk('audit_recovery')->get('original.zip'));
expect($service->generate($this->actor, $input)->id)->toBe($export->id)
->and(hash_file('sha256', $service->verifiedPath($this->actor, $export)))->toBe($export->sha256)
->and(DB::table('private_audit_exports')->where('id', $export->id)->first())->toEqual($before)
->and(DB::table('audit_logs')->count())->toBe($events);
});
@@ -511,6 +511,8 @@ test('native expiry returns the same request and preserves the approved stage be
->where('history.data.0.rules.first_limit_minor', 5000)->where('history.data.0.rules.approval_includes_tax', true)
->where('history.data.0.approval_amount_minor', 10000)->where('history.data.0.approval_uses_separate_basis', false)
->where('history.data.0.steps.0.approver_id', $head->id)->where('history.data.0.steps.0.comment', 'Conferência sintética do primeiro nível')
->where('history.data.0.steps.0.decided_at', CarbonImmutable::parse($approved['decided_at'], config('app.timezone'))->toIso8601String())
->where('history.data.0.steps.1.decided_at', null)
->missing('history.data.0.rules.timing')->missing('history.data.0.items.0.category_context'));
foreach ($beforeHistoryRead as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
+7 -2
View File
@@ -120,9 +120,14 @@ function landedQaReceiptsVerified(array $command, string $output): bool
&& $contains(fn ($row) => ($row['isolated_restore_removed'] ?? false) === true);
}
if (in_array($mode, ['legal-http', 'legal-review', 'expiry-review'], true)) {
if (in_array($mode, ['legal-http', 'legal-reference-http', 'legal-review', 'expiry-review'], true)) {
return $contains(fn ($row) => ($row['native_legal_http_login'] ?? false) === true && ($row['csrf_required'] ?? false) === true
&& ($row['large_multipart_upload_bytes'] ?? 0) > 2097152 && ($row['original_unchanged'] ?? false) === true
&& ($mode === 'legal-reference-http'
? (($row['large_multipart_upload_bytes'] ?? null) === 1002011
&& ($row['original_sha256'] ?? null) === 'a0110696253715567af39c159a21bacfebc32f944fa43a4efd18070d36959e50'
&& ($row['documentary_reference_drafts'] ?? null) === 48)
: ($row['large_multipart_upload_bytes'] ?? 0) > 2097152)
&& ($row['original_unchanged'] ?? false) === true
&& ($row['exact_native_download'] ?? false) === true && ($row['one_source_one_audit_after_replay'] ?? false) === true
&& ($row['guest_status'] ?? null) === 401 && ($row['revoked_status'] ?? null) === 403 && ($row['rules_published'] ?? null) === 0
&& ($row['financial_stock_unchanged'] ?? false) === true && ($row['global_php_config_unchanged'] ?? false) === true
@@ -5,6 +5,8 @@ use App\Http\Controllers\AuditMetadataController;
use App\Models\CostCenter;
use App\Models\User;
use App\Services\CommonBudget;
use App\Services\ImportLegalReferenceDrafts;
use App\Services\ImportLegalRules;
use App\Services\PrivateAuditAccess;
use App\Services\PurchaseControlPolicyWorkflow;
use App\Services\RequisitionAccountAssignments;
@@ -17,13 +19,14 @@ use App\Services\WarehouseRequests;
use Brick\Math\BigDecimal;
use Carbon\CarbonImmutable;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tempo\Finance\GeneralLedger\LedgerSchema;
/** Strictly guarded native synthetic composition; no real identities, source data or grants. */
function requisitionAccountsNativeReviewFixture(bool $integrated = false, bool $officeJourney = false): array
function requisitionAccountsNativeReviewFixture(bool $integrated = false, bool $officeJourney = false, bool $legalReference = false, bool $printPagination = false): array
{
LedgerSchema::install(DB::connection());
$composition = null;
@@ -33,7 +36,9 @@ function requisitionAccountsNativeReviewFixture(bool $integrated = false, bool $
} else {
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
}
$f = receiptFixture();
$f = receiptFixture(categories: $printPagination
? array_map(fn (int $line) => 'Categoria sintética de paginação '.str_pad((string) $line, 2, '0', STR_PAD_LEFT), range(1, 50))
: ['Material']);
$f['tenant']->update(['name' => 'QA isolada de Compras — contas e urgências']);
config(['requisition-expiry.qa_enabled' => true, 'urgent-reviews.qa_enabled' => true, 'requisition-accounts.qa_enabled' => true,
'agreement_order_limits.qa_enabled' => true, 'procurement_search.supply_metadata_enabled' => true,
@@ -43,6 +48,9 @@ function requisitionAccountsNativeReviewFixture(bool $integrated = false, bool $
$functions = ['reviewer' => ['admin', 'procurement', 'requester', 'supply_prepare', 'warehouse_request_prepare', 'audit_metadata_read'], 'requester' => ['requester'],
'head' => ['department_head', 'supply_review', 'warehouse_request_review'], 'finance' => ['finance'], 'auditor' => ['audit_metadata_read']];
$functions['private_auditor'] = array_column(PrivateAuditAccess::FAMILIES, 'permission');
if ($legalReference) {
$functions['reviewer'][] = 'import_customs';
}
if ($officeJourney) {
$functions += ['office_requester' => ['requester'], 'office_finance_reviewer' => ['finance'], 'office_warehouse' => ['warehouse'],
'office_procurement_reviewer' => ['procurement']];
@@ -249,7 +257,30 @@ function requisitionAccountsNativeReviewFixture(bool $integrated = false, bool $
}
}
$legalReferenceRoute = null;
if ($legalReference) {
$path = 'C:/Mac/Home/Documents/TEMPO/Portal Tempo/Legislacao/novas/BR_248_I_SERIE_SUPLEMENTO_2025.pdf';
if (! $integrated || ! is_file($path) || hash_file('sha256', $path) !== ImportLegalReferenceDrafts::EDITION_SHA256) {
throw new LogicException('The owned legal preview requires the exact supplied official edition and integrated synthetic schema.');
}
config(['import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true]);
auth()->guard()->setUser($people['reviewer']);
app(ImportLegalRules::class)->save($people['reviewer'], ['operation_key' => (string) Str::uuid(), 'action' => 'source', 'version' => 0,
'official_reference' => 'BR I Série 248, suplemento, 29/12/2025 — Lei 8/2025',
'reason' => 'Exemplar oficial partilhado para consulta e preparação em ambiente exclusivamente QA sintético; nenhuma regra publicada.'],
new UploadedFile($path, basename($path), 'application/pdf', UPLOAD_ERR_OK, true));
$legalReferenceRoute = '/requisicoes/'.$f['r']->id.'/base-legal';
if (getenv('RQ01_QA_SPECIFIC_RATE') === '1') {
require_once __DIR__.'/ImportLegalQaFixture.php';
app(ImportLegalRules::class)->save($people['reviewer'], ['operation_key' => (string) Str::uuid(), 'action' => 'source', 'version' => 0,
'official_reference' => 'Exemplar sintético QA — sem diploma ou validade fiscal',
'reason' => 'Fonte sintética separada, registada pelo serviço nativo apenas para conferir precisão decimal; nenhuma taxa publicada.'], importLegalQaFile());
}
}
return ['tenant_id' => $f['tenant']->id, 'synthetic_login' => $people['reviewer']->email,
'print_pagination' => $printPagination ? ['order_route' => '/ordens/'.$f['order']->id.'/imprimir', 'lines' => 50, 'total_minor' => 10000, 'fixture_only_not_native_issuance' => true] : null,
'legal_reference_route' => $legalReferenceRoute,
'office_journey' => $office,
'integrated_optional_schema' => $composition,
'synthetic_private_audit_login' => $people['private_auditor']->email, 'synthetic_metadata_login' => $people['auditor']->email, 'synthetic_requester_login' => $people['requester']->email,
@@ -44,5 +44,8 @@ $app->booted(function () use ($root, $database) {
config(['common-payables.enabled' => true, 'common-payables.source_instance' => 'native-http-office-qa',
'expense-allocations.qa_enabled' => true]);
}
if (getenv('RQ01_QA_LEGAL_REFERENCE') === '1') {
config(['import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true]);
}
});
$app->handleRequest(Request::capture());
+17
View File
@@ -217,6 +217,23 @@ test('legal contention and recovery require original source publication and froz
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
});
test('documentary reference HTTP receipts require the exact edition full draft count and native preservation', function () {
$command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'legal-reference-http'];
$row = ['native_legal_http_login' => true, 'csrf_required' => true, 'large_multipart_upload_bytes' => 1002011,
'original_sha256' => 'a0110696253715567af39c159a21bacfebc32f944fa43a4efd18070d36959e50', 'documentary_reference_drafts' => 48,
'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,
'global_php_config_unchanged' => true, 'private_http_server_stopped' => true, 'private_http_root_removed' => true];
expect(landedQaReceiptsVerified($command, json_encode($row, JSON_THROW_ON_ERROR)))->toBeTrue();
foreach (['original_sha256', 'documentary_reference_drafts', 'financial_stock_unchanged', 'rules_published', 'private_http_root_removed'] as $field) {
$incomplete = $row;
unset($incomplete[$field]);
expect(landedQaReceiptsVerified($command, json_encode($incomplete, JSON_THROW_ON_ERROR)))->toBeFalse();
}
$command[3] = 'legal-http';
expect(landedQaReceiptsVerified($command, json_encode($row, JSON_THROW_ON_ERROR)))->toBeFalse();
});
test('real corpus receipts require hashes verified native originals and no rule publication', function () {
$command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'corpus'];
$row = ['shared_corpus_files_inventoried' => 4, 'inventory_metadata_sha256' => str_repeat('a', 64),
@@ -0,0 +1,54 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import {
chargeDrafts,
LegalChargeSummary,
} from '@/components/import-legal-charges';
import {
specificRateLabel,
specificRateMinor,
specificRateMoney,
} from '@/lib/import-legal-specific-rate';
test.each([
['1.25', 125],
['1,25', 125],
['0.0099', '0.99'],
['0.0133', '1.33'],
['0.00000001', '0.000001'],
['000.00990000', '0.99'],
['0', 0],
] as const)(
'preserves exact documentary coefficient %s in minor units',
(input, minor) => {
expect(specificRateMinor(input)).toBe(minor);
expect(specificRateMinor(specificRateMoney(minor))).toBe(minor);
},
);
test.each(['', '-1', '1e2', '0.000000001', '10000000000000', '1.2.3', 'NaN'])(
'invalid MZN coefficient cannot be reinterpreted as a valid cent coefficient: %s',
(input) => expect(specificRateMinor(input)).toBeNull(),
);
test('fractional cent coefficients survive revision and remain visible without monetary rounding', () => {
const charge = {
key: 'synthetic-specific',
kind: 'ice',
label: 'Coeficiente documental sintético',
method: 'specific',
rate_percent: null,
specific_minor: '0.99',
quantity_unit: 'g',
basis_reference: 'Fonte sintética, sem activação fiscal',
};
expect(chargeDrafts([charge])[0].specific_amount).toBe('0.0099');
expect(specificRateLabel('0.99')).toBe('0,0099 MZN');
const html = renderToStaticMarkup(
<LegalChargeSummary charges={[charge]} />,
);
expect(html).toContain('0,0099 MZN');
expect(html).not.toContain('0,00 MZN');
expect(specificRateMoney(125)).toBe('1.25');
expect(specificRateMoney(null)).toBe('');
});
+41 -3
View File
@@ -1,7 +1,8 @@
import { App } from '@inertiajs/react';
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import { afterEach, expect, test, vi } from 'vitest';
import Legal from '../../resources/js/pages/supply/import-legal';
afterEach(() => vi.restoreAllMocks());
function renderLegal(
canManage: boolean,
@@ -108,12 +109,49 @@ test('official reference preparation is explicit and only available to the custo
expect(allowed).toContain('3506.91.20');
expect(allowed).toContain('taxa geral 20%');
expect(allowed).toContain('não é uma pauta consolidada');
expect(allowed).toContain('não substituir');
expect(allowed).toContain('Ainda não existem regras neste âmbito.');
expect(allowed).not.toContain('Ainda não existem fontes neste âmbito.');
const reader = renderLegal(false, false, false, true);
expect(reader).not.toContain('Preparar a partir do exemplar oficial');
expect(reader).not.toContain('Silicone para selagem');
});
test('remembered legal preparation is preserved and disables replacement by official reference drafts', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === 'legal-rule:1:1:1:data'
? {
operation_key: 'c1111111-1111-4111-8111-111111111111',
record_key: null,
version: 0,
action: 'save',
title: 'PRESERVED-DELIBERATE-TITLE',
official_reference: '',
official_url: '',
citation: '',
valid_from: '',
valid_until: '',
match_code: '',
suggested_code: '',
origin_country: '',
sector: '',
obligations: '',
document_types: [],
reason: '',
file: null,
source_id: '',
charges: [],
}
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = renderLegal(true, false, false, true);
expect(html).toContain('PRESERVED-DELIBERATE-TITLE');
expect(html).toContain('O preenchimento existente será conservado');
expect(html).toContain('Limpar preparação');
expect(html).toMatch(/<select[^>]*disabled[^>]*>/);
expect(post).not.toHaveBeenCalled();
});
test('legal consultation escapes titles preserves periods and offers verified-source downloads without management controls', () => {
const html = renderLegal(false);
expect(html).toContain('&lt;script&gt;synthetic rule&lt;/script&gt;');