commit compras2 2711
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-27 18:11:02 +02:00
parent e709d900d1
commit 930064269e
74 changed files with 7506 additions and 40 deletions
@@ -2,14 +2,20 @@
use App\Enums\PurchasingRole;
use App\Models\PurchaseOrder;
use App\Models\Requisition;
use App\Models\Supplier;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\CommonBudget;
use App\Services\ImportBankSupport;
use App\Services\ImportCostDocumentHealth;
use App\Services\ImportDossier;
use App\Services\ImportEstimates;
use App\Services\ImportLandedCosts;
use App\Services\ImportLegalEstimates;
use App\Services\ImportLegalRules;
use App\Services\ImportParties;
use App\Services\ImportTariffCodes;
use App\Services\SupplyPlanning;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Database\Connection;
@@ -34,10 +40,15 @@ if (! $app->environment('testing') || $db->getDriverName() !== 'pgsql' || $db->g
}
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
require_once __DIR__.'/../Support/ImportBankQaFixture.php';
require_once __DIR__.'/../Support/ImportLegalQaFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
$orderPartsAmendment = ($argv[2] ?? '') === 'order-parts-amendment';
$orderParts = $orderPartsAmendment || ($argv[2] ?? '') === 'order-parts';
$importEstimates = ($argv[2] ?? '') === 'import-estimates';
$legalAmounts = ($argv[2] ?? '') === 'import-legal-amount';
$legalRules = $legalAmounts || ($argv[2] ?? '') === 'import-legal';
$bankSupport = $legalRules || ($argv[2] ?? '') === 'import-bank-support';
$importEstimates = $bankSupport || ($argv[2] ?? '') === 'import-estimates';
$landedCosts = $importEstimates || ($argv[2] ?? '') === 'landed-costs';
$f = receiptFixture();
$author = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
@@ -192,6 +203,51 @@ if ($landedCosts) {
app(ImportParties::class)->select($partyBuyer, $nativeImport, [...$partyInput, 'operation_key' => (string) Str::uuid(),
'version' => 1, 'instruction_document_id' => $instructionsCorrection->id]);
$nativeEvidenceRecords = [$nativeDoc, $correction, $typedFirst, $typedCorrection, $instructions, $instructionsCorrection];
if ($bankSupport) {
config(['import-bank-support.qa_enabled' => true]);
$bankFixture = importBankQaFixture($partyBuyer, $nativeImport);
$bankFirst = app(ImportBankSupport::class)->save($partyBuyer, $nativeImport, $bankFixture['input']);
$bankFinalInput = [...$bankFixture['input'], 'operation_key' => (string) Str::uuid(), 'record_key' => $bankFirst->record_key, 'version' => 1,
'submission_document_id' => $bankFixture['documents']['delivery']->id, 'submitted_on' => today()->toDateString(),
'submission_basis' => 'Synthetic bank delivery receipt recorded on the explicit due date'];
$bankFinal = app(ImportBankSupport::class)->save($partyBuyer, $nativeImport, $bankFinalInput);
$nativeEvidenceRecords = [...$nativeEvidenceRecords, ...array_values($bankFixture['documents'])];
}
if ($legalRules) {
config(['import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true]);
supplyGrant($partyBuyer, ['procurement', 'import_prepare', 'import_customs']);
$legalService = app(ImportLegalRules::class);
$legalDraft = $legalService->save($partyBuyer, importLegalQaInput($legalAmounts ? ['charges' => [importLegalQaCharge()]] : []), importLegalQaFile());
$legalPublishInput = ['operation_key' => (string) Str::uuid(), 'record_key' => $legalDraft->record_key, 'version' => 1,
'action' => 'publish', 'reason' => 'Synthetic customs publication for the native recovery fixture'];
$legalPublished = $legalService->save($partyBuyer, $legalPublishInput);
$legalProposal = app(ImportTariffCodes::class)->save($partyBuyer, $f['r'], ['operation_key' => (string) Str::uuid(), 'version' => 0,
'action' => 'propose', 'requisition_item_id' => $f['r']->items()->sole()->id,
'code' => '1234.56', 'source_reference' => $legalPublished->data['official_reference'].' — '.$legalPublished->data['citation'],
'legal_rule_id' => $legalPublished->id, 'legal_match_code' => '1234', 'legal_origin' => 'Synthetic A', 'legal_sector' => 'Synthetic sector',
'legal_date' => '2026-11-27', 'reason' => 'Synthetic documentary suggestion preserved for recovery']);
$nativeEvidenceRecords[] = $legalService->source($partyBuyer, $f['r'], $legalPublished->snapshot['source_id']);
if ($legalAmounts) {
config(['import-estimates.qa_enabled' => true]);
$legalPlanRequest = $f['r']->replicate();
$legalPlanRequest->fill(['number' => 'LEGAL-RECOVERY-'.Str::random(10), 'status' => 'draft']);
$legalPlanRequest->save();
$legalPlanItem = $f['r']->items()->sole()->replicate();
$legalPlanItem->requisition_id = $legalPlanRequest->id;
$legalPlanItem->save();
$legalAmountInput = importLegalQaAmountInput($legalPlanItem->id, $legalPublished->id);
$legalAmountInput['bases']['synthetic-duty']['value_minor'] = 10000;
$legalAmount = app(ImportLegalEstimates::class)->save($partyBuyer, $legalPlanRequest, $legalAmountInput);
$legalNativeInput = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'budget_id' => $budget,
'reason' => 'Synthetic native import preparation; only the documented duty applies in this isolated scenario',
'legal_sources' => ['duty' => ['estimate_id' => $legalAmount->id, 'charge_key' => 'synthetic-duty']],
'components' => array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => $kind === 'duty' ? 'known' : 'not_applicable',
'basis' => 'Explicit synthetic recovery assumptions, not a real import or legal exemption',
'subtotal_minor' => $kind === 'duty' ? 750 : null, 'tax_minor' => $kind === 'duty' ? 0 : null,
'total_minor' => $kind === 'duty' ? 750 : null], BudgetImportEstimate::KINDS)];
$legalNativePlan = app(ImportEstimates::class)->save($partyBuyer, $legalPlanRequest, $legalNativeInput);
}
}
$evidenceManifest = [];
foreach ($nativeEvidenceRecords as $record) {
$evidence = $record->snapshot['evidence'];
@@ -294,11 +350,54 @@ try {
if ($restoredParty->data['instruction_document_id'] !== $instructionsCorrection->id) {
throw new RuntimeException('Restored instruction identity differs: '.get_debug_type($restoredParty->data['instruction_document_id']).'/'.get_debug_type($instructionsCorrection->id));
}
if ($bankSupport) {
$bankService = app(ImportBankSupport::class);
$bankWorkspace = $bankService->workspace($restoredBuyer, $nativeImport);
$bankReplay = $bankService->save($restoredBuyer, $nativeImport, $bankFinalInput);
$restoredBank = $bankWorkspace['current']->items()[0];
if ($restoredBank['version'] !== 2 || $restoredBank['state'] !== 'documented' || $restoredBank['issues'] !== [] || $bankReplay->id !== $bankFinal->id
|| $restoredBank['data']['commitment_document_id'] !== $bankFixture['documents']['term']->id
|| $restoredBank['data']['declaration_document_id'] !== $bankFixture['documents']['declaration']->id
|| $restoredBank['data']['submission_document_id'] !== $bankFixture['documents']['delivery']->id) {
throw new RuntimeException('Bank support relationships, documentary status or original operation replay differ after restore.');
}
echo json_encode(['bank_support_versions_restored' => 2, 'bank_support_relationships_restored' => true,
'bank_support_replay_without_effects' => true], JSON_THROW_ON_ERROR).PHP_EOL;
}
if ($legalRules) {
$legalService = app(ImportLegalRules::class);
$legalSource = $legalService->source($restoredBuyer, $f['r'], $legalPublished->snapshot['source_id']);
$restoredProposal = SupplyRecord::query()->findOrFail($legalProposal->id);
$legalReplay = $legalService->save($restoredBuyer, $legalPublishInput);
$restoredFrozen = $legalService->freeze($legalPublished->id, '1234', 'Synthetic A', 'Synthetic sector', '2026-11-27');
if ($legalReplay->id !== $legalPublished->id || $restoredProposal->snapshot['legal_rule'] !== $restoredFrozen
|| $legalSource->snapshot['evidence']['sha256'] !== $restoredFrozen['source_sha256']) {
throw new RuntimeException('Legal source, publication replay or frozen buyer context differs after restore.');
}
echo json_encode(['legal_source_restored' => true, 'legal_published_version_restored' => true,
'legal_buyer_context_restored' => true, 'legal_replay_without_effects' => true], JSON_THROW_ON_ERROR).PHP_EOL;
if ($legalAmounts) {
$restoredRequest = Requisition::query()->findOrFail($legalPlanRequest->id);
$amountService = app(ImportLegalEstimates::class);
$restoredAmount = $amountService->forPlan($restoredRequest, $legalAmount->id);
$amountReplay = $amountService->save($restoredBuyer, $restoredRequest, $legalAmountInput);
$nativePlanReplay = app(ImportEstimates::class)->save($restoredBuyer, $restoredRequest, $legalNativeInput);
$nativeApproval = app(ImportEstimates::class)->approval($restoredRequest);
if ($restoredAmount->snapshot['result']['total_minor'] !== 750 || $amountReplay->id !== $legalAmount->id
|| $nativePlanReplay->id !== $legalNativePlan->id || $nativeApproval['plan']['budget_amount_minor'] !== 10750
|| $nativePlanReplay->snapshot['legal_sources']['duty']['estimate_id'] !== $legalAmount->id) {
throw new RuntimeException('Calculated legal amount, native cost plan, source provenance or replay differs after restore.');
}
echo json_encode(['legal_amount_minor_restored' => 750, 'legal_amount_replay_without_effects' => true,
'native_legal_plan_total_minor' => 10750, 'native_legal_plan_source_restored' => true,
'native_legal_plan_replay_without_effects' => true], JSON_THROW_ON_ERROR).PHP_EOL;
}
}
$readFingerprint = $fingerprint($restored, $afterColumns);
if ($readFingerprint !== $after) {
throw new RuntimeException('Native restored read changed tables: '.implode(',', array_keys(array_diff_assoc($readFingerprint, $after))));
}
echo json_encode(['private_original_versions_restored' => count($nativeEvidenceRecords), 'typed_dossier_versions_restored' => 4,
echo json_encode(['private_original_versions_restored' => count($nativeEvidenceRecords), 'typed_dossier_versions_restored' => count(array_filter($nativeEvidenceRecords, fn ($record) => $record->kind === 'import_document')),
'selected_party_versions_restored' => 2, 'source_loss_detected' => true,
'separate_private_root_restored' => true, 'native_authorized_evidence_resolved' => true,
'evidence_manifest_sha256' => hash('sha256', json_encode($evidenceManifest, JSON_THROW_ON_ERROR))], JSON_THROW_ON_ERROR).PHP_EOL;
+63 -14
View File
@@ -1,11 +1,16 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Requisition;
use App\Models\Supplier;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\CapitalRegister;
use App\Services\ImportBankSupport;
use App\Services\ImportDossier;
use App\Services\ImportEvidence;
use App\Services\ImportLegalEstimates;
use App\Services\ImportLegalRules;
use App\Services\ImportParties;
use App\Services\SupplyPlanning;
use Illuminate\Contracts\Console\Kernel;
@@ -24,15 +29,25 @@ if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::con
|| DB::connection()->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)) {
throw new LogicException('Dossier contention requires disposable local PostgreSQL QA.');
}
config(['import-dossier.qa_enabled' => true]);
config(['capital-register.qa_enabled' => true, 'import-dossier.qa_enabled' => true, 'import-bank-support.qa_enabled' => true, 'import-tariffs.qa_enabled' => true, 'import-legal.qa_enabled' => true]);
Storage::set('local', Storage::build(['driver' => 'local', 'root' => storage_path('framework/testing/dossier-contention-'.$database), 'throw' => true]));
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
require_once __DIR__.'/../Support/ImportBankQaFixture.php';
require_once __DIR__.'/../Support/ImportLegalQaFixture.php';
$file = static fn () => UploadedFile::fake()->createWithContent('packing.pdf', "%PDF-1.4\nSynthetic concurrent packing list\n%%EOF");
$partyMode = in_array($argv[2] ?? '', ['prepare-party', 'write-party', 'race-party'], true);
$recordKind = $partyMode ? 'import_party' : 'import_document';
$auditAction = $partyMode ? 'import.party_selected' : 'import.document_recorded';
if (in_array($argv[2] ?? '', ['prepare', 'prepare-party'], true)) {
$bankMode = in_array($argv[2] ?? '', ['prepare-bank', 'write-bank', 'race-bank'], true);
$legalMode = in_array($argv[2] ?? '', ['prepare-legal', 'write-legal', 'race-legal'], true);
$amountMode = in_array($argv[2] ?? '', ['prepare-amount', 'write-amount', 'race-legal-amount'], true);
$capitalMode = in_array($argv[2] ?? '', ['prepare-capital', 'write-capital', 'race-capital'], true);
$recordKind = $amountMode ? 'import_legal_amount' : ($legalMode ? 'import_legal_rule' : ($bankMode ? 'import_bank_support' : ($partyMode ? 'import_party' : 'import_document')));
$auditAction = $amountMode ? 'import.legal_estimate_recorded' : ($legalMode ? 'import.legal_save' : ($bankMode ? 'import.bank_support_recorded' : ($partyMode ? 'import.party_selected' : 'import.document_recorded')));
if ($capitalMode) {
$recordKind = 'capital_register';
$auditAction = 'capital.register_recorded';
}
if (in_array($argv[2] ?? '', ['prepare', 'prepare-party', 'prepare-bank', 'prepare-legal', 'prepare-amount', 'prepare-capital'], true)) {
$f = receiptFixture();
supplyGrant($f['issuer'], ['procurement', 'import_prepare']);
auth()->guard()->setUser($f['issuer']);
@@ -42,7 +57,38 @@ if (in_array($argv[2] ?? '', ['prepare', 'prepare-party'], true)) {
$data = ['operation_key' => (string) Str::uuid(), 'type' => 'packing_list', 'reference' => 'PACK-PARALLEL',
'issuer_reference' => 'Synthetic supplier', 'reason' => 'Synthetic concurrent original document registration.'];
$actor = $f['issuer'];
if ($partyMode) {
if ($capitalMode) {
$data = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'type' => 'project', 'code' => 'CONCURRENT-QA',
'name' => 'Projecto sintético concorrente', 'department_id' => $f['department']->id, 'equipment_id' => null,
'reference' => 'Documento sintético de concorrência', 'state' => 'active', 'reason' => 'Cadastro independente em concorrência real de testes'];
if (($argv[3] ?? '') === 'same_version') {
$old = app(CapitalRegister::class)->save($actor, $data);
$data = [...$data, 'operation_key' => (string) Str::uuid(), 'record_key' => $old->record_key, 'version' => 1];
}
} elseif ($amountMode) {
supplyGrant($actor, ['procurement', 'import_prepare', 'import_customs']);
$draft = app(ImportLegalRules::class)->save($actor, importLegalQaInput(['charges' => [importLegalQaCharge()]]), importLegalQaFile());
$rule = app(ImportLegalRules::class)->save($actor, ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key,
'version' => 1, 'action' => 'publish', 'reason' => 'Synthetic reviewed tax definition for concurrent estimates']);
$data = importLegalQaAmountInput($f['r']->items()->sole()->id, $rule->id);
if (($argv[3] ?? '') === 'same_version') {
app(ImportLegalEstimates::class)->save($actor, $f['r'], $data);
$data = [...$data, 'operation_key' => (string) Str::uuid(), 'version' => 1];
}
} elseif ($legalMode) {
supplyGrant($actor, ['procurement', 'import_prepare', 'import_customs']);
$data = importLegalQaInput();
if (($argv[3] ?? '') === 'same_version') {
$old = app(ImportLegalRules::class)->save($actor, $data, importLegalQaFile());
$data = [...$data, 'operation_key' => (string) Str::uuid(), 'record_key' => $old->record_key, 'version' => 1];
}
} elseif ($bankMode) {
$data = importBankQaFixture($actor, $import)['input'];
if (($argv[3] ?? '') === 'same_version') {
$old = app(ImportBankSupport::class)->save($actor, $import, $data);
$data = [...$data, 'operation_key' => (string) Str::uuid(), 'record_key' => $old->record_key, 'version' => 1];
}
} elseif ($partyMode) {
$actor = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Procurement]);
supplyGrant($actor, ['procurement', 'import_prepare']);
auth()->guard()->setUser($actor);
@@ -63,32 +109,35 @@ if (in_array($argv[2] ?? '', ['prepare', 'prepare-party'], true)) {
$data = [...$data, 'operation_key' => (string) Str::uuid(), 'record_key' => $old->record_key, 'version' => 1,
'reference' => 'PACK-CORRECTED'];
}
echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $actor->id, 'import' => $import->id, 'data' => $data,
echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $actor->id, 'import' => $import->id, 'request' => $f['r']->id, 'data' => $data,
'records_before' => SupplyRecord::query()->where('kind', $recordKind)->count(),
'audits_before' => DB::table('audit_logs')->where('tenant_id', $f['tenant']->id)->where('action', $auditAction)->count(),
'files_before' => count(Storage::disk('local')->allFiles())], JSON_THROW_ON_ERROR);
exit;
}
if (in_array($argv[2] ?? '', ['write', 'write-party'], true)) {
if (in_array($argv[2] ?? '', ['write', 'write-party', 'write-bank', 'write-legal', 'write-amount', 'write-capital'], true)) {
$input = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR);
DB::select('select set_config(?, ?, false)', ['application_name', 'sgc_dossier_write_'.getmypid()]);
$actor = User::query()->findOrFail($input['actor']);
auth()->guard()->setUser($actor);
try {
$import = SupplyRecord::query()->findOrFail($input['import']);
$record = $partyMode ? app(ImportParties::class)->select($actor, $import, $input['data'])
: app(ImportDossier::class)->record($actor, $import, $input['data'], $file());
$record = $capitalMode ? app(CapitalRegister::class)->save($actor, $input['data']) : ($amountMode ? app(ImportLegalEstimates::class)->save($actor, Requisition::query()->findOrFail($input['request']), $input['data']) : ($legalMode ? app(ImportLegalRules::class)->save($actor, $input['data'], importLegalQaFile()) : ($bankMode ? app(ImportBankSupport::class)->save($actor, $import, $input['data'])
: ($partyMode ? app(ImportParties::class)->select($actor, $import, $input['data'])
: app(ImportDossier::class)->record($actor, $import, $input['data'], $file())))));
echo json_encode(['status' => 200, 'id' => $record->id], JSON_THROW_ON_ERROR);
} catch (HttpExceptionInterface $error) {
echo json_encode(['status' => $error->getStatusCode()], JSON_THROW_ON_ERROR);
}
exit;
}
if (! in_array($argv[2] ?? '', ['race-dossier', 'race-party'], true)) {
if (! in_array($argv[2] ?? '', ['race-dossier', 'race-party', 'race-bank', 'race-legal', 'race-legal-amount', 'race-capital'], true)) {
throw new InvalidArgumentException('Unknown dossier worker mode.');
}
foreach (['same_operation', 'same_version'] as $scenario) {
$prepare = new Process([PHP_BINARY, __FILE__, $database, $partyMode ? 'prepare-party' : 'prepare', $scenario], dirname(__DIR__, 2), timeout: 30);
$prepareMode = $capitalMode ? 'prepare-capital' : ($amountMode ? 'prepare-amount' : ($legalMode ? 'prepare-legal' : ($bankMode ? 'prepare-bank' : ($partyMode ? 'prepare-party' : 'prepare'))));
$writeMode = $capitalMode ? 'write-capital' : ($amountMode ? 'write-amount' : ($legalMode ? 'write-legal' : ($bankMode ? 'write-bank' : ($partyMode ? 'write-party' : 'write'))));
$prepare = new Process([PHP_BINARY, __FILE__, $database, $prepareMode, $scenario], dirname(__DIR__, 2), timeout: 30);
$prepare->mustRun();
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$db = DB::connection();
@@ -101,7 +150,7 @@ foreach (['same_operation', 'same_version'] as $scenario) {
if ($scenario === 'same_version' && $index === 1) {
$workerInput['data']['operation_key'] = (string) Str::uuid();
}
$worker = new Process([PHP_BINARY, __FILE__, $database, $partyMode ? 'write-party' : 'write', json_encode($workerInput, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30);
$worker = new Process([PHP_BINARY, __FILE__, $database, $writeMode, json_encode($workerInput, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30);
$workers[] = $worker;
$worker->start();
}
@@ -131,11 +180,11 @@ foreach (['same_operation', 'same_version'] as $scenario) {
$records = DB::table('supply_records')->where('tenant_id', $input['tenant'])->where('kind', $recordKind)->count() - $input['records_before'];
$audits = DB::table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', $auditAction)->count() - $input['audits_before'];
$files = count(Storage::disk('local')->allFiles()) - $input['files_before'];
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $records !== 1 || $audits !== 1 || $files !== ($partyMode ? 0 : 1)) {
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $records !== 1 || $audits !== 1 || $files !== ($capitalMode || $partyMode || $bankMode || $amountMode ? 0 : 1)) {
throw new RuntimeException('Dossier contention must preserve one document version, one original and one audit.');
}
auth()->guard()->setUser(User::query()->findOrFail($input['actor']));
foreach (SupplyRecord::query()->where('kind', 'import_document')->get() as $record) {
foreach (SupplyRecord::query()->whereIn('kind', ['import_document', 'import_legal_source'])->get() as $record) {
app(ImportEvidence::class)->bytes($record);
}
echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
@@ -0,0 +1,79 @@
<?php
use App\Models\SupplyRecord;
use App\Services\ImportEvidence;
use App\Services\ImportLegalRules;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
require __DIR__.'/../../vendor/autoload.php';
$app = require __DIR__.'/../../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$database = $argv[1] ?? '';
$root = realpath($argv[3] ?? '');
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)
|| $root === false || ! is_dir($root)) {
throw new LogicException('Real-source preparation requires a supplied corpus and disposable local PostgreSQL QA.');
}
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
config(['import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true]);
$directory = storage_path('framework/testing/legal-corpus-'.$database);
Storage::set('local', Storage::build(['driver' => 'local', 'root' => $directory, 'throw' => true]));
$inventory = [];
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS)) as $entry) {
if ($entry->isFile()) {
$inventory[] = ['path' => str_replace('\\', '/', substr($entry->getPathname(), strlen($root) + 1)), 'bytes' => $entry->getSize()];
}
}
usort($inventory, fn ($a, $b) => strcmp($a['path'], $b['path']));
$patterns = [
'Legislacao/2022/12 Dezembro/series-i/br-series-i-29-12-2022-*.pdf' => 'BR I Série 251, 29/12/2022 — Leis 17/2022 e 19/2022, exemplar integral',
'novas/BR_248_I_SERIE_SUPLEMENTO_2025.pdf' => 'BR I Série 248, suplemento de 29/12/2025 — Leis 7/2025 a 12/2025',
'lei-nr-28-2022-de-29-de-dezembro-lei-cambial.pdf' => 'BR I Série 251, suplemento de 29/12/2022 — Lei 28/2022, Lei Cambial',
'Legislacao/2024/03 */series-i/br-series-i-20-03-2024-*.pdf' => 'BR I Série 57, 20/03/2024 — Aviso 3/GBM/2024, normas e procedimentos cambiais',
];
$f = receiptFixture();
supplyGrant($f['issuer'], ['procurement', 'import_customs']);
auth()->guard()->setUser($f['issuer']);
$fingerprint = fn () => [DB::table('budget_entries')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('stock_movements')->get()->toJson()];
$before = $fingerprint();
$sources = [];
try {
foreach ($patterns as $pattern => $reference) {
$matches = glob(str_replace('\\', '/', $root).'/'.$pattern);
if ($matches === false || count($matches) !== 1) {
throw new RuntimeException('The selected corpus reference is missing or ambiguous: '.$reference);
}
$path = $matches[0];
$checksum = hash_file('sha256', $path);
$input = ['operation_key' => (string) Str::uuid(), 'action' => 'source', 'version' => 0,
'official_reference' => $reference, 'reason' => 'Fonte oficial real partilhada pelo proprietário; preparação exclusivamente em empresa e base QA sintéticas, sem publicar regras'];
$file = new UploadedFile($path, basename($path), 'application/pdf', UPLOAD_ERR_OK, true);
$record = app(ImportLegalRules::class)->save($f['issuer'], $input, $file);
$resolved = app(ImportLegalRules::class)->source($f['issuer'], $f['r'], $record->id);
if (hash('sha256', app(ImportEvidence::class)->bytes($resolved)) !== $checksum || hash_file('sha256', $path) !== $checksum
|| app(ImportLegalRules::class)->save($f['issuer'], $input, $file)->id !== $record->id) {
throw new RuntimeException('The original, private source or idempotent replay differs.');
}
$sources[] = ['reference' => $reference, 'relative_path' => str_replace('\\', '/', substr($path, strlen($root) + 1)),
'bytes' => filesize($path), 'sha256' => $checksum, 'native_authorized_download_verified' => true];
}
if ($fingerprint() !== $before || SupplyRecord::query()->where('kind', 'import_legal_rule')->exists()) {
throw new RuntimeException('Registering sources must not publish rules or create financial/stock effects.');
}
echo json_encode(['shared_corpus_files_inventoried' => count($inventory), 'inventory_metadata_sha256' => hash('sha256', json_encode($inventory, JSON_THROW_ON_ERROR)),
'real_official_sources_prepared' => $sources, 'rules_published' => 0, 'originals_unchanged' => true,
'financial_and_stock_unchanged' => true, 'synthetic_qa_organization_only' => true], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR).PHP_EOL;
} finally {
$resolved = realpath($directory);
$boundary = realpath(storage_path('framework/testing'));
if ($resolved !== false && $boundary !== false && str_starts_with(str_replace('\\', '/', $resolved), str_replace('\\', '/', $boundary).'/legal-corpus-compras_receipts_test_')) {
File::deleteDirectory($resolved);
}
}
@@ -0,0 +1,216 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\CommonBudget;
use App\Services\ImportBankSupport;
use App\Services\ImportEstimates;
use App\Services\ImportLegalEstimates;
use App\Services\ImportLegalRules;
use App\Services\SupplyPlanning;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Exception\ConnectException;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Symfony\Component\Process\Process;
use Tempo\Finance\Budget\BudgetImportEstimate;
require __DIR__.'/../../vendor/autoload.php';
$app = require __DIR__.'/../../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$database = $argv[1] ?? '';
$corpus = realpath($argv[3] ?? '');
$candidateRelative = $argv[4] ?? '';
$candidateHash = $argv[5] ?? '';
$reviewMode = ($argv[2] ?? '') === 'legal-review';
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)
|| $corpus === false || ! preg_match('~^storage/framework/testing/[A-Za-z0-9_-]+$~D', $candidateRelative)
|| ! preg_match('/^[a-f0-9]{64}$/D', $candidateHash) || hash_file('sha256', base_path($candidateRelative.'/manifest.json')) !== $candidateHash) {
throw new LogicException('HTTP source review requires a supplied corpus, validated private candidate and disposable PostgreSQL.');
}
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) {
throw new LogicException('Select the complete shared official journal, not a small extracted example.');
}
$path = $files[0];
$originalHash = hash_file('sha256', $path);
$f = receiptFixture();
supplyGrant($f['issuer'], ['procurement', 'import_customs']);
auth()->guard()->setUser($f['issuer']);
$password = Str::random(48);
$f['issuer']->forceFill(['password' => Hash::make($password)])->save();
$fingerprint = fn () => [DB::table('budget_entries')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('stock_movements')->get()->toJson()];
$before = $fingerprint();
$directory = storage_path('framework/testing/legal-http-'.$database);
foreach (['public', 'storage/framework/sessions', 'storage/framework/views', 'storage/framework/cache/data', 'storage/logs', 'storage/app/private'] as $relative) {
File::ensureDirectoryExists($directory.'/'.$relative);
}
File::copyDirectory(base_path($candidateRelative), $directory.'/public/build');
$socket = stream_socket_server('tcp://127.0.0.1:0', $errorCode, $error);
if ($socket === false) {
throw new RuntimeException('Unable to reserve a loopback QA port.');
}
$address = stream_socket_get_name($socket, false);
fclose($socket);
$port = substr($address, strrpos($address, ':') + 1);
$url = 'http://'.($reviewMode ? 'localhost' : '127.0.0.1').':'.$port;
$server = new Process([PHP_BINARY, '-d', 'upload_max_filesize=64M', '-d', 'post_max_size=70M', '-S', '127.0.0.1:'.$port,
'tests/Support/import-legal-http-router.php'], base_path(), ['APP_ENV' => 'testing', 'APP_DEBUG' => 'false',
'APP_URL' => $url, 'ASSET_URL' => $url, 'SGC_LEGAL_HTTP_QA_ROOT' => $directory, 'SGC_LEGAL_HTTP_QA_PORT' => $port,
'SESSION_COOKIE' => 'sgc_legal_http_'.substr($database, -12), 'SESSION_DRIVER' => 'file'], timeout: null);
$client = new Client(['base_uri' => $url, 'cookies' => $cookies = new CookieJar, 'http_errors' => false, 'allow_redirects' => false,
'timeout' => 20, 'expect' => false]);
$result = null;
try {
$server->start();
$ready = false;
$deadline = microtime(true) + 10;
do {
try {
$ready = $client->get('/up')->getStatusCode() === 200;
} catch (ConnectException) {
usleep(50000);
}
} while (! $ready && $server->isRunning() && microtime(true) < $deadline);
if (! $ready || $client->get('/login')->getStatusCode() !== 200) {
throw new RuntimeException('Private native HTTP login page unavailable.');
}
$token = fn () => rawurldecode($cookies->getCookieByName('XSRF-TOKEN')?->getValue() ?? '');
if ($token() === '') {
throw new RuntimeException('Native session did not issue a CSRF cookie.');
}
$login = $client->post('/login', ['headers' => ['Accept' => 'application/json', 'X-XSRF-TOKEN' => $token()],
'form_params' => ['email' => $f['issuer']->email, 'password' => $password]]);
if (! in_array($login->getStatusCode(), [200, 302, 303], true)) {
throw new RuntimeException('Native synthetic Fortify login failed: '.$login->getStatusCode());
}
$route = '/requisicoes/'.$f['r']->id.'/base-legal';
$headers = ['Accept' => 'application/json', 'X-XSRF-TOKEN' => $token(), 'Referer' => $url.$route];
$negative = $client->post($route, ['headers' => ['Accept' => 'application/json'], 'json' => ['action' => 'source']]);
if ($negative->getStatusCode() !== 419) {
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',
'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));
$multipart[] = ['name' => 'file', 'contents' => fopen($path, 'rb'), 'filename' => basename($path), 'headers' => ['Content-Type' => 'application/pdf']];
$response = $client->post($route, ['headers' => $headers, 'multipart' => $multipart]);
if (! in_array($response->getStatusCode(), [302, 303], true)) {
throw new RuntimeException('Native large-source multipart upload failed: '.$response->getStatusCode());
}
}
$initial = $client->get($route);
if ($initial->getStatusCode() !== 200 || ! preg_match('~<script[^>]*data-page="[^"]+"[^>]*>(.*?)</script>~s', (string) $initial->getBody(), $initialData)) {
throw new RuntimeException('Native source page bootstrap unavailable: '.$initial->getStatusCode());
}
$initialPage = json_decode($initialData[1], true, 64, JSON_THROW_ON_ERROR);
$page = $client->get($route, ['headers' => ['X-Inertia' => 'true', 'X-Inertia-Version' => $initialPage['version'], 'Accept' => 'text/html, application/xhtml+xml']]);
if ($page->getStatusCode() !== 200 || ! str_contains($page->getHeaderLine('Content-Type'), 'application/json')) {
throw new RuntimeException('Native Inertia page did not accept its bootstrap version: '.$page->getStatusCode());
}
$props = json_decode((string) $page->getBody(), true, 64, JSON_THROW_ON_ERROR)['props'] ?? [];
$source = SupplyRecord::query()->where('kind', 'import_legal_source')->sole();
$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']]);
if ($page->getStatusCode() !== 200 || ($props['sources']['total'] ?? null) !== 1 || ($props['rules']['total'] ?? null) !== 0
|| $download->getStatusCode() !== 200 || hash('sha256', (string) $download->getBody()) !== $originalHash
|| hash_file('sha256', $path) !== $originalHash || $anonymous->getStatusCode() !== 401
|| DB::table('audit_logs')->where('tenant_id', $f['tenant']->id)->where('action', 'import.legal_source_recorded')->count() !== 1
|| $fingerprint() !== $before) {
throw new RuntimeException('Native source scope, large bytes, idempotence, authentication or financial preservation not demonstrated.');
}
DB::table('organization_memberships')->where('user_id', $f['issuer']->id)->delete();
$revoked = $client->get($route.'/fontes/'.$source->id, ['headers' => ['Accept' => 'application/json']]);
if ($revoked->getStatusCode() !== 403) {
throw new RuntimeException('Native download did not revalidate revoked QA authority.');
}
$result = ['native_legal_http_login' => true, 'csrf_required' => true, 'large_multipart_upload_bytes' => filesize($path),
'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];
if ($reviewMode) {
// Existing factory password is confined to guarded, disposable synthetic QA identities.
$reviewer = $f['otherReceiver'];
supplyGrant($reviewer, ['procurement', 'requester', 'import_read', 'import_prepare', 'import_customs']);
config(['import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true, 'import-estimates.qa_enabled' => true,
'import-dossier.qa_enabled' => true, 'import-bank-support.qa_enabled' => true, 'import-readiness.qa_enabled' => true]);
Storage::set('local', Storage::build(['driver' => 'local', 'root' => $directory.'/storage/app/private', 'throw' => true]));
$author = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Finance]);
$approver = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Finance]);
supplyGrant($author, ['finance']);
supplyGrant($approver, ['finance']);
auth()->guard()->setUser($author);
$budget = app(CommonBudget::class)->for($author)->create(['cost_center_id' => $f['r']->cost_center_id, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 1000000, 'reason' => 'Dotação estritamente sintética da revisão nativa']);
auth()->guard()->setUser($approver);
app(CommonBudget::class)->for($approver)->approve($budget);
auth()->guard()->setUser($reviewer);
$draftRequest = $f['r']->replicate();
$draftRequest->fill(['number' => 'VISUAL-LEGAL-'.Str::random(8), 'requester_id' => $reviewer->id, 'status' => 'draft']);
$draftRequest->save();
$draftItem = $f['r']->items()->sole()->replicate();
$draftItem->requisition_id = $draftRequest->id;
$draftItem->save();
$legalDraft = app(ImportLegalRules::class)->save($reviewer, importLegalQaInput(['title' => 'Regra de ensaio — dados fictícios', 'charges' => [importLegalQaCharge()]]), importLegalQaFile());
$legalRule = app(ImportLegalRules::class)->save($reviewer, ['operation_key' => (string) Str::uuid(), 'record_key' => $legalDraft->record_key,
'version' => 1, 'action' => 'publish', 'reason' => 'Publicação de dados estritamente fictícios para revisão nativa isolada']);
$amountInput = importLegalQaAmountInput($draftItem->id, $legalRule->id);
$amountInput['bases']['synthetic-duty']['value_minor'] = 10000;
$amount = app(ImportLegalEstimates::class)->save($reviewer, $draftRequest, $amountInput);
app(ImportEstimates::class)->save($reviewer, $draftRequest, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'budget_id' => $budget,
'reason' => 'Plano fictício apenas com direitos neste cenário; sem reserva ou submissão', 'legal_sources' => ['duty' => ['estimate_id' => $amount->id, 'charge_key' => 'synthetic-duty']],
'components' => array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => $kind === 'duty' ? 'known' : 'not_applicable',
'basis' => 'Pressuposto estritamente sintético desta revisão, não isenção real', 'subtotal_minor' => $kind === 'duty' ? 750 : null,
'tax_minor' => $kind === 'duty' ? 0 : null, 'total_minor' => $kind === 'duty' ? 750 : null], BudgetImportEstimate::KINDS)]);
$import = app(SupplyPlanning::class)->save($reviewer, 'import', supplyInput(['purchase_order_id' => $f['order']->id, 'purpose' => 'internal',
'jurisdiction' => 'Âmbito fictício QA', 'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Regime fictício QA']));
$bank = importBankQaFixture($reviewer, $import);
app(ImportBankSupport::class)->save($reviewer, $import, $bank['input']);
$stopFile = $directory.'/stop';
echo json_encode(['private_review_running' => true, 'url' => $url, 'stop_file' => $stopFile,
'synthetic_user' => $reviewer->email, 'draft_request' => $draftRequest->id, 'import' => $import->id,
'legal_url' => $url.'/requisicoes/'.$draftRequest->id.'/base-legal?'.http_build_query(['code' => '1234', 'origin' => 'Synthetic A', 'sector' => 'Synthetic sector', 'date' => '2026-11-27']),
'private_candidate_manifest' => $candidateHash, 'pilot_assets_changed' => false], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR).PHP_EOL;
$deadline = microtime(true) + 3600;
while (! is_file($stopFile) && microtime(true) < $deadline) {
if (! $server->isRunning()) {
throw new RuntimeException('Private native review server stopped unexpectedly.');
}
$server->getIncrementalOutput();
$server->getIncrementalErrorOutput();
usleep(100000);
}
$result['private_native_review_stopped'] = true;
}
} catch (Throwable $error) {
$summary = 'No native exception log.';
$log = $directory.'/storage/logs/laravel.log';
if (is_file($log) && preg_match_all('/testing\.ERROR: ([^\r\n]+)/', file_get_contents($log), $matches) && $matches[1] !== []) {
$summary = substr(str_replace($password, '[synthetic credential redacted]', end($matches[1])), 0, 300);
}
throw new RuntimeException($error->getMessage().' Native diagnostic: '.$summary);
} finally {
$server->stop();
$resolved = realpath($directory);
$boundary = realpath(storage_path('framework/testing'));
if ($resolved !== false && $boundary !== false && str_replace('\\', '/', $resolved) === str_replace('\\', '/', $boundary).'/legal-http-'.$database) {
File::deleteDirectory($resolved);
}
if ($result !== null) {
echo json_encode([...$result, 'private_http_server_stopped' => true, 'private_http_root_removed' => ! is_dir($directory)], JSON_THROW_ON_ERROR).PHP_EOL;
}
}