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;
}
}
+135
View File
@@ -0,0 +1,135 @@
<?php
use App\Models\CriticalityLevel;
use App\Models\Equipment;
use App\Models\SupplyRecord;
use App\Services\CapitalAssignments;
use App\Services\CapitalRegister;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Inertia\Testing\AssertableInertia as Assert;
use Symfony\Component\HttpKernel\Exception\HttpException;
require_once __DIR__.'/../Support/ReceiptFixture.php';
beforeEach(function () {
config(['capital-register.qa_enabled' => true]);
$this->withoutVite();
$this->f = receiptFixture();
$this->actingAs($this->f['issuer']);
$this->input = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0,
'type' => 'project', 'code' => 'PRJ-QA', 'name' => 'Projecto estritamente sintético',
'department_id' => $this->f['department']->id, 'equipment_id' => null,
'reference' => 'Documento fictício para cadastro independente de Compras', 'state' => 'active',
'reason' => 'Preparação de referência sintética para testes de compras'];
});
test('own project register versions preserves identity and replay without financial or stock effects', function () {
$service = app(CapitalRegister::class);
$before = [];
foreach (['budget_entries', 'stock_movements', 'invoices', 'purchase_orders'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$first = $service->save($this->f['issuer'], $this->input);
expect($first->version)->toBe(1)->and($first->snapshot['source_system'])->toBe('compras');
expect($service->save($this->f['issuer'], $this->input)->id)->toBe($first->id);
$archive = [...$this->input, 'operation_key' => (string) Str::uuid(), 'record_key' => $first->record_key, 'version' => 1, 'state' => 'archived'];
$second = $service->save($this->f['issuer'], $archive);
expect($second->version)->toBe(2)->and($second->state)->toBe('archived')
->and($first->fresh()->state)->toBe('active')->and(SupplyRecord::query()->where('kind', 'capital_register')->count())->toBe(2);
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
expect(fn () => $service->save($this->f['issuer'], [...$archive, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
expect(fn () => $service->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid()]))->toThrow(ValidationException::class);
});
test('register rejects reused operation content and renaming a permanent code', function () {
$service = app(CapitalRegister::class);
$first = $service->save($this->f['issuer'], $this->input);
expect(fn () => $service->save($this->f['issuer'], [...$this->input, 'name' => 'Conteúdo diferente']))->toThrow(HttpException::class);
expect(fn () => $service->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid(),
'record_key' => $first->record_key, 'version' => 1, 'code' => 'OUTRO']))->toThrow(ValidationException::class);
expect(SupplyRecord::query()->where('kind', 'capital_register')->count())->toBe(1);
});
test('asset references reuse a physical equipment identity and reject duplicate or removed links', function () {
$level = CriticalityLevel::query()->create(['tenant_id' => $this->f['tenant']->id, 'created_by' => $this->f['issuer']->id, 'created_at' => now(), 'code' => 'QA', 'name' => 'Ensaio', 'criteria' => 'Só fixture sintética', 'is_critical' => false]);
$equipment = Equipment::query()->create(['tenant_id' => $this->f['tenant']->id, 'created_by' => $this->f['issuer']->id, 'code' => 'EQ-QA', 'description' => 'Equipamento físico sintético',
'area' => 'Área sintética', 'status' => 'active', 'department_id' => $this->f['department']->id, 'criticality_level_id' => $level->id]);
$input = [...$this->input, 'type' => 'asset', 'code' => 'ASSET-QA', 'equipment_id' => $equipment->id];
$service = app(CapitalRegister::class);
$first = $service->save($this->f['issuer'], $input);
expect($first->snapshot['equipment']['id'])->toBe($equipment->id)->and(Equipment::query()->count())->toBe(1);
expect(fn () => $service->save($this->f['issuer'], [...$input, 'operation_key' => (string) Str::uuid(), 'code' => 'OTHER-QA']))->toThrow(ValidationException::class);
expect(fn () => $service->save($this->f['issuer'], [...$input, 'operation_key' => (string) Str::uuid(), 'record_key' => $first->record_key, 'version' => 1, 'equipment_id' => null]))->toThrow(ValidationException::class);
$this->get('/projectos-imobilizado?history='.$first->record_key)->assertOk()->assertInertia(fn (Assert $page) => $page->has('history.data', 1));
expect(fn () => $service->save($this->f['issuer'], [...$input, 'operation_key' => (string) Str::uuid(), 'code' => ['invalid']]))->toThrow(ValidationException::class);
});
test('native register page is encrypted private paginated and gated off outside QA', function () {
app(CapitalRegister::class)->save($this->f['issuer'], $this->input);
$this->get('/projectos-imobilizado')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true)
->assertInertia(fn (Assert $page) => $page->component('equipment/capital-register')
->has('records.data', 1)->where('records.data.0.data.code', 'PRJ-QA')->where('canManage', true));
config(['capital-register.qa_enabled' => false]);
$this->get('/projectos-imobilizado')->assertStatus(503);
});
test('native register revalidates operator and hides foreign department identity without creating versions', function () {
$service = app(CapitalRegister::class);
$first = $service->save($this->f['issuer'], $this->input);
$this->actingAs($this->f['receiver']);
expect(fn () => $service->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
$this->actingAs($this->f['issuer']);
$other = receiptFixture();
$this->actingAs($other['issuer']);
$this->get('/projectos-imobilizado')->assertOk()->assertInertia(fn (Assert $page) => $page->has('records.data', 0));
$this->post('/projectos-imobilizado', [...$this->input, 'operation_key' => (string) Str::uuid(), 'record_key' => $first->record_key, 'version' => 1])->assertNotFound();
$this->actingAs($this->f['issuer']);
expect(SupplyRecord::query()->where('kind', 'capital_register')->count())->toBe(1);
});
test('line destination freezes the chosen project version and preserves it after archival without financial effects', function () {
$register = app(CapitalRegister::class);
$source = $register->save($this->f['issuer'], $this->input);
$this->f['r']->update(['status' => 'draft']);
$item = $this->f['r']->items()->firstOrFail();
$input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $item->id,
'capital_id' => $source->id, 'reason' => 'Escolha de destino sintético da linha da requisição'];
$service = app(CapitalAssignments::class);
$first = $service->save($this->f['issuer'], $this->f['r'], $input);
expect($first->state)->toBe('linked')->and($service->save($this->f['issuer'], $this->f['r'], $input)->id)->toBe($first->id);
$register->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid(),
'record_key' => $source->record_key, 'version' => 1, 'state' => 'archived', 'name' => 'Designação posterior sintética']);
$frozen = $service->freezeForItems($this->f['issuer'], [$item->id]);
expect($frozen[$item->id]['snapshot']['source']['version'])->toBe(1)
->and($frozen[$item->id]['snapshot']['source']['data']['name'])->toBe($this->input['name']);
$this->get('/requisicoes/'.$this->f['r']->id.'/projectos-imobilizado')->assertOk()
->assertInertia(fn (Assert $page) => $page->component('requisitions/capital-assignments')->where('canWrite', true)->has('choices.data', 0)->has('current', 1));
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 1]))->toThrow(ModelNotFoundException::class);
expect(DB::table('budget_entries')->count())->toBe(0)->and(DB::table('stock_movements')->count())->toBe(0);
$item->update(['description' => 'Artigo alterado após a escolha']);
expect(fn () => $service->freezeForItems($this->f['issuer'], [$item->id]))->toThrow(HttpException::class);
$cleared = $service->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 1, 'capital_id' => null]);
expect($cleared->state)->toBe('cleared')->and($service->freezeForItems($this->f['issuer'], [$item->id]))->toBe([])
->and($first->fresh()->state)->toBe('linked');
});
test('submitted requisitions reject new line destinations and stale versions do not replace choices', function () {
$source = app(CapitalRegister::class)->save($this->f['issuer'], $this->input);
$item = $this->f['r']->items()->firstOrFail();
$input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $item->id, 'capital_id' => $source->id,
'reason' => 'Escolha documental sintética preservando decisões anteriores'];
$service = app(CapitalAssignments::class);
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], $input))->toThrow(HttpException::class);
$this->f['r']->update(['status' => 'draft']);
$service->save($this->f['issuer'], $this->f['r'], $input);
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid(), 'capital_id' => null]))->toThrow(HttpException::class);
config(['capital-register.qa_enabled' => false]);
expect(fn () => $service->freezeForItems($this->f['issuer'], [$item->id]))->toThrow(HttpException::class);
expect(SupplyRecord::query()->where('kind', 'capital_assignment')->count())->toBe(1);
});
+144
View File
@@ -0,0 +1,144 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\ImportBankSupport;
use App\Services\ImportDossier;
use App\Services\SupplyPlanning;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Inertia\Testing\AssertableInertia;
use Symfony\Component\HttpKernel\Exception\HttpException;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
function bankSupportOriginal(object $test, string $type, string $reference, ?SupplyRecord $previous = null): SupplyRecord
{
return app(ImportDossier::class)->record($test->f['issuer'], $test->import, ['operation_key' => (string) Str::uuid(), 'type' => $type,
'record_key' => $previous?->record_key, 'version' => $previous?->version ?? 0, 'reference' => $reference,
'issuer_reference' => 'Synthetic issuing entity', 'issued_on' => today()->toDateString(), 'notes' => 'Synthetic bank-support evidence only.',
'reason' => 'Preservar original sintético para o acompanhamento bancário'],
UploadedFile::fake()->createWithContent('bank-support.pdf', "%PDF-1.4\nSynthetic original ".$reference."\n%%EOF"));
}
beforeEach(function () {
config(['import-dossier.qa_enabled' => true, 'import-bank-support.qa_enabled' => true]);
Storage::fake('local');
$this->withoutVite();
$this->f = receiptFixture();
supplyGrant($this->f['issuer'], ['procurement', 'import_prepare']);
$this->actingAs($this->f['issuer']);
$this->import = app(SupplyPlanning::class)->save($this->f['issuer'], 'import', supplyInput([
'purchase_order_id' => $this->f['order']->id, 'purpose' => 'internal', 'jurisdiction' => 'Synthetic bank-support jurisdiction',
'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Synthetic documentary regime']));
$this->term = bankSupportOriginal($this, 'bank_commitment', 'BANK-TERM-QA');
$this->declaration = bankSupportOriginal($this, 'customs_declaration', 'DU-QA');
$this->invoice = bankSupportOriginal($this, 'commercial_invoice', 'INVOICE-QA-1');
$this->input = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0,
'commitment_document_id' => $this->term->id, 'declaration_document_id' => $this->declaration->id,
'support_document_ids' => [$this->invoice->id], 'requirements_known' => true,
'required_support_types' => ['commercial_invoice'], 'required_support_counts' => ['commercial_invoice' => 2],
'requirements_basis' => 'Synthetic bank request explicitly asks for two commercial invoices',
'submission_document_id' => null, 'submission_basis' => null, 'submitted_on' => null,
'due_on' => today()->subDay()->toDateString(), 'deadline_basis' => 'Explicit synthetic bank letter deadline, not a legal default',
'reason' => 'Acompanhamento estritamente documental e sintético'];
});
test('bank support preserves exact requested counts versions and original delivery evidence without payment or JUE effects', function () {
$service = app(ImportBankSupport::class);
$before = [DB::table('stock_movements')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('budget_entries')->get()->toJson(), $this->import->fresh()->getAttributes()];
$first = $service->save($this->f['issuer'], $this->import, $this->input);
expect($first->state)->toBe('tracking')->and($service->save($this->f['issuer'], $this->import, $this->input)->id)->toBe($first->id)
->and(implode(' ', $service->issues($first)))->toContain('Factura comercial (1)', 'Prazo documental ultrapassado', 'não demonstra a entrega');
expect(fn () => $service->save($this->f['issuer'], $this->import, [...$this->input, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
$invoice = bankSupportOriginal($this, 'commercial_invoice', 'INVOICE-QA-2');
$secondInput = [...$this->input, 'operation_key' => (string) Str::uuid(), 'record_key' => $first->record_key, 'version' => 1,
'support_document_ids' => [$this->invoice->id, $invoice->id]];
$ready = $service->save($this->f['issuer'], $this->import, $secondInput);
expect($ready->state)->toBe('ready')->and(implode(' ', $service->issues($ready)))->toContain('Prazo documental ultrapassado');
$delivery = bankSupportOriginal($this, 'bank_support', 'BANK-DELIVERY-QA-1');
$thirdInput = [...$secondInput, 'operation_key' => (string) Str::uuid(), 'version' => 2,
'submission_document_id' => $delivery->id, 'submission_basis' => 'Synthetic documentary delivery receipt; no live bank action', 'submitted_on' => today()->toDateString()];
$documented = $service->save($this->f['issuer'], $this->import, $thirdInput);
expect($documented->state)->toBe('documented')->and($service->issues($documented))->toBe(['Entrega documentada após o prazo indicado.'])
->and($documented->snapshot['bank_transfer_executed'])->toBeFalse()->and($documented->snapshot['jue_submission_executed'])->toBeFalse()
->and($documented->snapshot['bank_compliance_certified'])->toBeFalse();
$correction = bankSupportOriginal($this, 'bank_support', 'BANK-DELIVERY-QA-2', $delivery);
expect(implode(' ', $service->issues($documented)))->toContain('foi corrigido', 'Prazo documental ultrapassado');
$fourth = $service->save($this->f['issuer'], $this->import, [...$thirdInput, 'operation_key' => (string) Str::uuid(), 'version' => 3, 'submission_document_id' => $correction->id]);
expect($fourth->version)->toBe(4)->and($service->issues($fourth))->toBe(['Entrega documentada após o prazo indicado.'])->and($first->fresh()->state)->toBe('tracking')
->and([DB::table('stock_movements')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('budget_entries')->get()->toJson(), $this->import->fresh()->getAttributes()])->toBe($before);
});
test('unknown bank requirements and deadlines stay unknown and cannot silently become a completed or zero-day obligation', function () {
$record = app(ImportBankSupport::class)->save($this->f['issuer'], $this->import, [...$this->input,
'requirements_known' => false, 'required_support_types' => [], 'required_support_counts' => [], 'declaration_document_id' => null,
'due_on' => null, 'deadline_basis' => null]);
expect($record->state)->toBe('tracking')->and($record->data['due_on'])->toBeNull()
->and(implode(' ', app(ImportBankSupport::class)->issues($record)))->toContain('desconhecidos', 'Prazo documental ainda por indicar');
expect(fn () => app(ImportBankSupport::class)->save($this->f['issuer'], $this->import, [...$this->input, 'deadline_basis' => ' ']))->toThrow(HttpException::class);
expect(fn () => app(ImportBankSupport::class)->save($this->f['issuer'], $this->import, [...$this->input, 'required_support_counts' => []]))->toThrow(HttpException::class);
$delivery = bankSupportOriginal($this, 'bank_support', 'DELIVERY-UNKNOWN-DATE');
expect(fn () => app(ImportBankSupport::class)->save($this->f['issuer'], $this->import, [...$this->input,
'submission_document_id' => $delivery->id, 'submission_basis' => 'Synthetic delivery evidence with no event date']))->toThrow(HttpException::class);
expect(fn () => app(ImportBankSupport::class)->save($this->f['issuer'], $this->import, [...$this->input,
'submission_document_id' => $delivery->id, 'submission_basis' => 'Synthetic delivery cannot be recorded as already occurred tomorrow',
'submitted_on' => today()->addDay()->toDateString()]))->toThrow(ValidationException::class);
});
test('bank follow-up rejects foreign documents wrong types stale versions and withdrawn write authority', function () {
$service = app(ImportBankSupport::class);
expect(fn () => $service->save($this->f['issuer'], $this->import, [...$this->input, 'commitment_document_id' => $this->invoice->id]))->toThrow(HttpException::class);
$record = $service->save($this->f['issuer'], $this->import, $this->input);
expect(fn () => $service->save($this->f['issuer'], $this->import, [...$this->input, 'record_key' => $record->record_key, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
$other = receiptFixture();
supplyGrant($other['issuer'], ['procurement', 'import_prepare']);
$this->actingAs($other['issuer']);
$otherImport = app(SupplyPlanning::class)->save($other['issuer'], 'import', supplyInput([
'purchase_order_id' => $other['order']->id, 'purpose' => 'internal', 'jurisdiction' => 'Other synthetic jurisdiction',
'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Synthetic documentary regime']));
$otherDocument = bankSupportOriginal((object) ['f' => $other, 'import' => $otherImport], 'bank_commitment', 'OTHER-BANK-TERM');
expect(fn () => $service->save($other['issuer'], $this->import, $this->input))->toThrow(ModelNotFoundException::class);
$this->actingAs($this->f['issuer']);
expect(fn () => $service->save($this->f['issuer'], $this->import, [...$this->input, 'operation_key' => (string) Str::uuid(),
'commitment_document_id' => $otherDocument->id]))->toThrow(ModelNotFoundException::class);
DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->delete();
expect(fn () => $service->save($this->f['issuer'], $this->import, [...$this->input, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
});
test('native bank entry consultation and full-scope CSV share source data permissions and formula-safe references', function () {
$term = bankSupportOriginal($this, 'bank_commitment', '=SYNTHETIC-REFERENCE');
$input = [...$this->input, 'commitment_document_id' => $term->id];
$url = '/compras/importacoes/'.$this->import->id.'/suporte-bancario';
$this->post($url, $input)->assertRedirect();
$record = SupplyRecord::query()->where('kind', 'import_bank_support')->where('operation_key', $input['operation_key'])->firstOrFail();
$this->post($url, $input)->assertRedirect();
expect(SupplyRecord::query()->where('kind', 'import_bank_support')->count())->toBe(1);
$tables = ['users', 'supply_records', 'audit_logs', 'budget_entries', 'invoices', 'stock_movements'];
$before = [];
foreach ($tables as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$this->get($url)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
->assertInertia(fn (AssertableInertia $page) => $page->component('supply/import-bank-support')
->where('canWrite', true)->where('current.data.0.id', $record->id)->where('current.data.0.data.required_support_counts.commercial_invoice', 2)
->missing('current.data.0.snapshot.documents.0.path'));
$csv = $this->get($url.'.csv?bank_current_page=999999')->assertOk()->assertDownload();
expect($csv->streamedContent())->toContain("'=SYNTHETIC-REFERENCE", 'Factura comercial: 2', 'Prazo documental ultrapassado')
->not->toContain('import-dossier/', 'account_identifier');
foreach ($tables as $table) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($before[$table]);
}
$viewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
supplyGrant($viewer, ['finance']);
$this->actingAs($viewer)->get($url)->assertOk()->assertInertia(fn (AssertableInertia $page) => $page->where('canWrite', false));
$this->post($url, [...$input, 'operation_key' => (string) Str::uuid()])->assertForbidden();
config(['import-bank-support.qa_enabled' => false]);
$this->get($url)->assertStatus(503);
});
+55
View File
@@ -9,6 +9,8 @@ use App\Models\User;
use App\Services\CommonBudget;
use App\Services\ImportEstimates;
use App\Services\ImportLandedCosts;
use App\Services\ImportLegalEstimates;
use App\Services\ImportLegalRules;
use App\Services\ImportTariffCodes;
use App\Services\RequisitionWorkflow;
use App\Services\SupplyPlanning;
@@ -24,6 +26,7 @@ use Tempo\Finance\Budget\BudgetImportEstimate;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
require_once __DIR__.'/../Support/ImportLegalQaFixture.php';
beforeEach(function () {
if (! class_exists(BudgetImportEstimate::class)) {
@@ -54,6 +57,58 @@ beforeEach(function () {
'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS)];
});
test('native import cost assumptions reuse exact legal charges once with explicit tax split and immutable source provenance', function () {
config(['import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true]);
Storage::fake('local');
supplyGrant($this->f['issuer'], ['procurement', 'import_customs']);
$rules = app(ImportLegalRules::class);
$draft = $rules->save($this->f['issuer'], importLegalQaInput(['charges' => [[
'key' => 'synthetic-duty', 'kind' => 'duty', 'label' => 'Synthetic duty', 'method' => 'ad_valorem', 'rate_percent' => '7.5',
'specific_minor' => null, 'quantity_unit' => null, 'basis_reference' => 'Synthetic explicit customs-value basis',
]]]), importLegalQaFile());
$rule = $rules->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key,
'version' => 1, 'action' => 'publish', 'reason' => 'Synthetic rate publication for native estimate integration']);
$legal = app(ImportLegalEstimates::class)->save($this->f['issuer'], $this->draft, ['operation_key' => (string) Str::uuid(), 'version' => 0,
'requisition_item_id' => $this->draft->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' => 10000,
'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic declared customs valuation']], 'reason' => 'Synthetic exact charge adoption fixture']);
$input = $this->input;
foreach ($input['components'] as &$component) {
$component['status'] = $component['kind'] === 'duty' ? 'known' : 'not_applicable';
$component['basis'] = 'Explicit synthetic assumptions; other costs do not apply in this test';
if ($component['kind'] === 'duty') {
$component['subtotal_minor'] = 750;
$component['tax_minor'] = 0;
$component['total_minor'] = 750;
}
}
unset($component);
$input['legal_sources'] = ['duty' => ['estimate_id' => $legal->id, 'charge_key' => 'synthetic-duty']];
$native = app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $input);
expect($native->snapshot['plan']['budget_amount_minor'])->toBe(10750)
->and($native->snapshot['legal_sources']['duty']['estimate_id'])->toBe($legal->id)
->and($native->snapshot['legal_sources']['duty']['legal_rule']['id'])->toBe($rule->id)
->and(DB::table('budget_entries')->count())->toBe(0);
$changed = [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 1];
foreach ($changed['components'] as &$component) {
if ($component['kind'] === 'duty') {
$component['subtotal_minor'] = 751;
$component['total_minor'] = 751;
}
}
unset($component);
expect(fn () => app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $changed))->toThrow(HttpException::class);
$duplicate = [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 1];
$duty = array_values(array_filter($duplicate['components'], fn ($component) => $component['kind'] === 'duty'))[0];
$duplicate['components'][] = [...$duty, 'key' => 'duty-again'];
$duplicate['legal_sources']['duty-again'] = $duplicate['legal_sources']['duty'];
expect(fn () => app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $duplicate))->toThrow(HttpException::class);
$rules->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $rule->record_key,
'version' => 2, 'action' => 'withdraw', 'reason' => 'Synthetic withdrawal before native approval requires explicit review']);
expect(fn () => app(ImportEstimates::class)->approval($this->draft))->toThrow(HttpException::class);
expect(DB::table('budget_entries')->count())->toBe(0)->and($native->fresh()->snapshot['plan']['budget_amount_minor'])->toBe(10750);
});
test('native draft assumptions preserve unknowns originals and versions without financial or stock effects', function () {
$service = app(ImportEstimates::class);
$before = $this->draft->fresh()->getAttributes();
@@ -0,0 +1,84 @@
<?php
use App\Services\ImportLegalAmounts;
use App\Services\ImportLegalEstimates;
use App\Services\ImportLegalRules;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpException;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
require_once __DIR__.'/../Support/ImportLegalQaFixture.php';
function legalCharge(array $overrides = []): array
{
return [...['key' => 'synthetic-duty', 'kind' => 'duty', 'label' => 'Synthetic duty', 'method' => 'ad_valorem',
'rate_percent' => '7.5', 'specific_minor' => null, 'quantity_unit' => null,
'basis_reference' => 'Synthetic customs-value basis; not an approved real legal rule'], ...$overrides];
}
beforeEach(function () {
config(['import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true]);
Storage::fake('local');
$this->withoutVite();
$this->f = receiptFixture();
supplyGrant($this->f['issuer'], ['procurement', 'import_customs']);
$this->actingAs($this->f['issuer']);
});
test('ad valorem specific and the greater-value method use exact decimals and documented units', function () {
$amounts = app(ImportLegalAmounts::class);
$base = ['value_minor' => 10001, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic explicit customs valuation'];
$result = $amounts->calculate([legalCharge()], ['synthetic-duty' => $base]);
expect($result['total_minor'])->toBe(750)->and($result['financial_effects'])->toBeFalse();
$specific = legalCharge(['method' => 'specific', 'rate_percent' => null, 'specific_minor' => 125, 'quantity_unit' => 'KG']);
expect($amounts->calculate([$specific], ['synthetic-duty' => [...$base, 'value_minor' => null, 'quantity' => '1.500', 'quantity_unit' => 'KG']])['total_minor'])->toBe(188);
$maximum = legalCharge(['method' => 'maximum', 'specific_minor' => 1000, 'quantity_unit' => 'KG']);
expect($amounts->calculate([$maximum], ['synthetic-duty' => [...$base, 'quantity' => '1.500', 'quantity_unit' => 'KG']])['total_minor'])->toBe(1500);
expect($amounts->calculate([$maximum], ['synthetic-duty' => [...$base, 'quantity' => '0.100', 'quantity_unit' => 'KG']])['total_minor'])->toBe(750);
expect(fn () => $amounts->calculate([$maximum], ['synthetic-duty' => [...$base, 'quantity' => '1.5', 'quantity_unit' => 'BOX']]))->toThrow(ValidationException::class);
});
test('unknown rates and missing bases never become zero while explicit non-application and zero rates remain distinct', function () {
$amounts = app(ImportLegalAmounts::class);
$unknown = legalCharge(['key' => 'unknown', 'method' => 'unknown', 'rate_percent' => null]);
$zero = legalCharge(['key' => 'zero', 'rate_percent' => '0']);
$notApplicable = legalCharge(['key' => 'not-applicable', 'method' => 'not_applicable', 'rate_percent' => null]);
$result = $amounts->calculate([$unknown, $zero, $notApplicable], ['zero' => ['value_minor' => 10000, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic declared base'],
'not-applicable' => ['value_minor' => null, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic documentary proof that all non-application prerequisites are met']]);
expect($result['complete'])->toBeFalse()->and($result['total_minor'])->toBeNull()->and($result['known_subtotal_minor'])->toBe(0)
->and(array_column($result['lines'], 'amount_minor'))->toBe([null, 0, 0]);
expect($amounts->calculate([], [])['total_minor'])->toBeNull();
expect($amounts->calculate([$notApplicable], [])['total_minor'])->toBeNull();
expect($amounts->calculate([legalCharge()], [])['total_minor'])->toBeNull();
expect(fn () => $amounts->definitions([legalCharge(['method' => 'unknown'])]))->toThrow(ValidationException::class);
expect(fn () => $amounts->calculate([legalCharge()], ['synthetic-duty' => ['value_minor' => 10000, 'quantity' => null, 'quantity_unit' => null, 'source' => null]]))->toThrow(ValidationException::class);
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('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());
$rule = $rules->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key, 'version' => 1,
'action' => 'publish', 'reason' => 'Synthetic explicit customs rate review for estimates']);
$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' => 10001, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic exact customs valuation']],
'reason' => 'Synthetic estimate with explicit source and no financial effects'];
$before = [DB::table('budget_entries')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('stock_movements')->get()->toJson()];
$url = '/requisicoes/'.$this->f['r']->id.'/base-legal/estimativas';
$this->post($url, $input)->assertRedirect();
$service = app(ImportLegalEstimates::class);
$record = $service->save($this->f['issuer'], $this->f['r'], $input);
expect($record->snapshot['result']['total_minor'])->toBe(750)->and($record->snapshot['legal_rule']['id'])->toBe($rule->id)
->and($service->save($this->f['issuer'], $this->f['r'], $input)->id)->toBe($record->id);
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
$second = $service->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 1, 'bases' => []]);
expect($second->state)->toBe('indeterminate')->and($second->snapshot['result']['total_minor'])->toBeNull()
->and($record->fresh()->snapshot['result']['total_minor'])->toBe(750)
->and($service->forPlan($this->f['r'], $record->id)->id)->toBe($record->id)
->and([DB::table('budget_entries')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('stock_movements')->get()->toJson()])->toBe($before);
});
+183
View File
@@ -0,0 +1,183 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\ImportEvidence;
use App\Services\ImportLegalRules;
use App\Services\ImportTariffCodes;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpException;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
function legalRuleInput(array $overrides = []): array
{
return [...['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'action' => 'save',
'title' => 'Synthetic tariff rule', 'official_reference' => 'Synthetic official edition QA only',
'official_url' => 'https://example.test/official-qa.pdf', 'citation' => 'Synthetic article 1, page 2',
'valid_from' => '2026-01-01', 'valid_until' => '2026-12-31', 'match_code' => '1234', 'suggested_code' => '1234.56',
'origin_country' => 'Synthetic A', 'sector' => 'Synthetic sector', 'obligations' => 'Synthetic duty conditions; no real tax activated',
'document_types' => ['licence'], 'reason' => 'Synthetic legal configuration; not an approved real legal rule'], ...$overrides];
}
function legalRuleFile(): UploadedFile
{
return UploadedFile::fake()->createWithContent('source.pdf', "%PDF-1.4\nSynthetic official source for QA only\n%%EOF");
}
function publishLegalRule(User $actor, SupplyRecord $draft): SupplyRecord
{
return app(ImportLegalRules::class)->save($actor, ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key,
'version' => $draft->version, 'action' => 'publish', 'reason' => 'Synthetic customs review and publication of the prepared rule']);
}
beforeEach(function () {
config(['import-tariffs.qa_enabled' => true, 'import-legal.qa_enabled' => true]);
Storage::fake('local');
$this->withoutVite();
$this->f = receiptFixture();
supplyGrant($this->f['issuer'], ['procurement', 'import_customs']);
$this->actingAs($this->f['issuer']);
});
test('legal publication preserves sources versions periods scope and previous publication during a draft revision', function () {
$service = app(ImportLegalRules::class);
$before = [DB::table('budget_entries')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('stock_movements')->get()->toJson()];
$input = legalRuleInput();
$file = legalRuleFile();
$draft = $service->save($this->f['issuer'], $input, $file);
expect($service->save($this->f['issuer'], $input, $file)->id)->toBe($draft->id);
$find = fn ($origin = 'Synthetic A', $sector = 'Synthetic sector', $date = '2026-11-27') => $service->suggestions($this->f['issuer'], $this->f['r'], '1234', $origin, $sector, $date);
expect($find())->toBe([]);
$published = publishLegalRule($this->f['issuer'], $draft);
expect($find()[0]['id'])->toBe($published->id)->and($find(''))->toBe([])->and($find('Synthetic A', ''))->toBe([])
->and($find('Synthetic A', 'Synthetic sector', '2027-01-01'))->toBe([])
->and($find('Synthetic A', 'Synthetic sector', '2026-01-01'))->toHaveCount(1)
->and($find('Synthetic A', 'Synthetic sector', '2026-12-31'))->toHaveCount(1);
$frozen = $service->freeze($published->id, '1234', 'Synthetic A', 'Synthetic sector', '2026-11-27');
$next = $service->save($this->f['issuer'], legalRuleInput(['record_key' => $published->record_key, 'version' => 2, 'suggested_code' => '1234.57']));
expect($find()[0]['id'])->toBe($published->id)->and($service->changed($frozen))->toBeFalse();
$new = publishLegalRule($this->f['issuer'], $next);
expect($service->changed($frozen))->toBeTrue()->and($frozen['data']['suggested_code'])->toBe('1234.56')
->and($published->fresh()->data['suggested_code'])->toBe('1234.56');
$service->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $new->record_key, 'version' => 4,
'action' => 'withdraw', 'reason' => 'Synthetic withdrawal without deleting original sources or applied decisions']);
expect($find())->toBe([])->and(Storage::disk('local')->allFiles())->toHaveCount(1)
->and([DB::table('budget_entries')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('stock_movements')->get()->toJson()])->toBe($before);
});
test('buyer proposal freezes legal context and confirmation permits a reasoned deviation while changes require a current source', function () {
$service = app(ImportLegalRules::class);
$published = publishLegalRule($this->f['issuer'], $service->save($this->f['issuer'], legalRuleInput(), legalRuleFile()));
$tariffs = app(ImportTariffCodes::class);
$input = ['operation_key' => (string) Str::uuid(), 'action' => 'propose', 'version' => 0, 'requisition_item_id' => $this->f['r']->items()->sole()->id,
'code' => '1234.56', 'source_reference' => $published->data['official_reference'].' — '.$published->data['citation'], 'legal_rule_id' => $published->id,
'legal_match_code' => '1234', 'legal_origin' => 'Synthetic A', 'legal_sector' => 'Synthetic sector', 'legal_date' => '2026-11-27',
'reason' => 'Synthetic buyer selection of a documented suggestion'];
$proposal = $tariffs->save($this->f['issuer'], $this->f['r'], $input);
$confirmed = $tariffs->save($this->f['issuer'], $this->f['r'], ['operation_key' => (string) Str::uuid(), 'action' => 'confirm', 'version' => 1,
'requisition_item_id' => $input['requisition_item_id'], 'code' => '1234.59', 'source_reference' => 'Synthetic technical classification reference',
'reason' => 'Synthetic buyer explains the documented deviation from the suggested code']);
expect($confirmed->data['deviation'])->toBeTrue()->and($confirmed->snapshot['legal_rule']['id'])->toBe($published->id)
->and($confirmed->snapshot['calculations_activated'])->toBeFalse()->and($proposal->fresh()->state)->toBe('proposed');
expect($tariffs->freezeForItems($this->f['issuer'], [$input['requisition_item_id']])[$input['requisition_item_id']]['legal_rule'])->toBe($confirmed->snapshot['legal_rule']);
$tariffs->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 2]);
$draft = $service->save($this->f['issuer'], legalRuleInput(['record_key' => $published->record_key, 'version' => 2]));
publishLegalRule($this->f['issuer'], $draft);
expect(fn () => $tariffs->save($this->f['issuer'], $this->f['r'], ['operation_key' => (string) Str::uuid(), 'action' => 'confirm', 'version' => 3,
'requisition_item_id' => $input['requisition_item_id'], 'code' => '1234.56', 'source_reference' => 'Synthetic source', 'reason' => 'Synthetic obsolete-source confirmation must fail']))->toThrow(HttpException::class);
expect($tariffs->workspace($this->f['issuer'], $this->f['r'])['latest']->first()->legal_changed)->toBeTrue();
});
test('legal management rejects stale operations foreign access revoked permissions and missing or altered original bytes', function () {
$service = app(ImportLegalRules::class);
$input = legalRuleInput();
$draft = $service->save($this->f['issuer'], $input, legalRuleFile());
expect(fn () => $service->save($this->f['issuer'], [...$input, 'title' => 'Changed title'], legalRuleFile()))->toThrow(HttpException::class);
expect(fn () => $service->save($this->f['issuer'], legalRuleInput(['record_key' => $draft->record_key])))->toThrow(HttpException::class);
$viewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Procurement]);
supplyGrant($viewer, ['procurement']);
$this->actingAs($viewer);
expect(fn () => publishLegalRule($viewer, $draft))->toThrow(HttpException::class);
$foreign = receiptFixture();
supplyGrant($foreign['issuer'], ['procurement', 'import_customs']);
$this->actingAs($foreign['issuer']);
expect(fn () => $service->source($foreign['issuer'], $foreign['r'], $draft->snapshot['source_id']))->toThrow(ModelNotFoundException::class);
$this->actingAs($this->f['issuer']);
$source = $service->source($this->f['issuer'], $this->f['r'], $draft->snapshot['source_id']);
Storage::disk('local')->put($source->snapshot['evidence']['path'], 'altered');
expect(fn () => publishLegalRule($this->f['issuer'], $draft))->toThrow(HttpException::class);
DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->delete();
expect(fn () => $service->workspace($this->f['issuer'], $this->f['r']))->toThrow(HttpException::class);
});
test('native legal forms keep sources private and allow source download and explicit human publication only', function () {
$url = '/requisicoes/'.$this->f['r']->id.'/base-legal';
$this->post($url, [...legalRuleInput(), 'file' => legalRuleFile()])->assertRedirect();
$draft = SupplyRecord::query()->where('kind', 'import_legal_rule')->sole();
$this->get($url)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private');
$source = app(ImportLegalRules::class)->source($this->f['issuer'], $this->f['r'], $draft->snapshot['source_id']);
$download = $this->get($url.'/fontes/'.$source->id)->assertOk()->assertHeader('X-Content-Type-Options', 'nosniff');
expect($download->getContent())->toBe(app(ImportEvidence::class)->bytes($source));
$this->getJson($url.'?rules_page=0')->assertUnprocessable();
config(['import-legal.qa_enabled' => false]);
$this->get($url)->assertStatus(503);
});
test('missing source alerts an already applied rule and changed source metadata requires a new original', function () {
$service = app(ImportLegalRules::class);
$draft = $service->save($this->f['issuer'], legalRuleInput(), legalRuleFile());
$published = publishLegalRule($this->f['issuer'], $draft);
$frozen = $service->freeze($published->id, '1234', 'Synthetic A', 'Synthetic sector', '2026-11-27');
expect(fn () => $service->save($this->f['issuer'], legalRuleInput(['record_key' => $published->record_key, 'version' => 2,
'official_reference' => 'Different synthetic source without its original'])))->toThrow(HttpException::class);
$source = $service->source($this->f['issuer'], $this->f['r'], $frozen['source_id']);
Storage::disk('local')->delete($source->snapshot['evidence']['path']);
expect($service->changed($frozen))->toBeTrue();
expect(fn () => $service->freeze($published->id, '1234', 'Synthetic A', 'Synthetic sector', '2026-11-27'))->toThrow(HttpException::class);
});
test('an official source larger than a transactional attachment remains consultable without truncation', function () {
$bytes = "%PDF-1.4\n".str_repeat('Synthetic legal publication page bytes ', 70000)."\n%%EOF";
$service = app(ImportLegalRules::class);
$draft = $service->save($this->f['issuer'], legalRuleInput(), UploadedFile::fake()->createWithContent('large-source.pdf', $bytes));
$source = $service->source($this->f['issuer'], $this->f['r'], $draft->snapshot['source_id']);
expect(strlen($bytes))->toBeGreaterThan(2097152)->and(app(ImportEvidence::class)->bytes($source))->toBe($bytes);
expect(publishLegalRule($this->f['issuer'], $draft)->snapshot['source_sha256'])->toBe(hash('sha256', $bytes));
});
test('a shared official source is independently consultable and reused without inventing a code or publishing a rule', function () {
$service = app(ImportLegalRules::class);
$input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'action' => 'source',
'official_reference' => 'Synthetic complete official journal; no rule or inferred rate',
'reason' => 'Retain the synthetic official publication independently of its later use'];
$source = $service->save($this->f['issuer'], $input, legalRuleFile());
expect($service->save($this->f['issuer'], $input, legalRuleFile())->id)->toBe($source->id)
->and($source->kind)->toBe('import_legal_source')->and($source->data['official_url'])->toBeNull()
->and(SupplyRecord::query()->where('kind', 'import_legal_rule')->count())->toBe(0);
$rule = $service->save($this->f['issuer'], legalRuleInput(['source_id' => $source->id,
'official_reference' => $source->data['official_reference'], 'official_url' => null]));
expect($rule->snapshot['source_id'])->toBe($source->id)->and(Storage::disk('local')->allFiles())->toHaveCount(1)
->and($service->workspace($this->f['issuer'], $this->f['r'])['sources']->total())->toBe(1);
$other = $service->save($this->f['issuer'], [...$input, 'operation_key' => (string) Str::uuid(), 'official_reference' => 'Another synthetic official source'], legalRuleFile());
expect(fn () => $service->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $rule->record_key, 'version' => 1,
'action' => 'publish', 'source_id' => $other->id, 'reason' => 'A publication decision cannot silently replace the prepared original']))->toThrow(HttpException::class);
expect(publishLegalRule($this->f['issuer'], $rule)->snapshot['source_id'])->toBe($source->id);
});
test('publishing a future period preserves the earlier applicable period without resurrecting an expired replacement', function () {
$service = app(ImportLegalRules::class);
$first = publishLegalRule($this->f['issuer'], $service->save($this->f['issuer'], legalRuleInput(), legalRuleFile()));
$future = publishLegalRule($this->f['issuer'], $service->save($this->f['issuer'], legalRuleInput(['record_key' => $first->record_key, 'version' => 2,
'valid_from' => '2027-01-01', 'valid_until' => '2027-06-30', 'suggested_code' => '1234.57'])));
$find = fn ($date) => $service->suggestions($this->f['issuer'], $this->f['r'], '1234', 'Synthetic A', 'Synthetic sector', $date);
expect($find('2026-11-27')[0]['id'])->toBe($first->id)->and($find('2027-01-01')[0]['id'])->toBe($future->id)
->and($find('2027-07-01'))->toBe([])
->and($service->freeze($first->id, '1234', 'Synthetic A', 'Synthetic sector', '2026-11-27')['id'])->toBe($first->id);
});
+140
View File
@@ -0,0 +1,140 @@
<?php
use App\Models\SupplyRecord;
use App\Services\ImportBankSupport;
use App\Services\ImportDossier;
use App\Services\ImportLegalRules;
use App\Services\ImportReadiness;
use App\Services\InventoryLots;
use App\Services\ReceiptWorkflow;
use App\Services\SupplyPlanning;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
use Symfony\Component\HttpKernel\Exception\HttpException;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
require_once __DIR__.'/../Support/ImportLegalQaFixture.php';
require_once __DIR__.'/../Support/ImportBankQaFixture.php';
beforeEach(function () {
config(['import-readiness.qa_enabled' => true, 'import-dossier.qa_enabled' => true, 'import-bank-support.qa_enabled' => true,
'import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true]);
Storage::fake('local');
$this->withoutVite();
$this->f = receiptFixture();
supplyGrant($this->f['issuer'], ['procurement', 'import_prepare', 'import_customs']);
$this->actingAs($this->f['issuer']);
$this->import = app(SupplyPlanning::class)->save($this->f['issuer'], 'import', supplyInput([
'purchase_order_id' => $this->f['order']->id, 'purpose' => 'internal', 'jurisdiction' => 'Synthetic readiness jurisdiction',
'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Synthetic regime',
'expected_usable_on' => today()->subDay()->toDateString()]));
});
test('current import alerts distinguish unknown requirements and the expected receipt from customs release without side effects', function () {
$service = app(ImportReadiness::class);
$before = [];
foreach (['supply_records', 'audit_logs', 'budget_entries', 'stock_movements', 'invoices', 'workflow_notices'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$workspace = $service->workspace($this->f['issuer'], $this->import);
expect(array_column($workspace['alerts'], 'key'))->toContain('expected-due', 'classification-unknown', 'parties-unknown', 'bank-unknown')
->and($workspace['complete'])->toBeTrue()->and($workspace['financialEffects'])->toBeFalse()->and($workspace['automaticNotifications'])->toBeFalse();
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
$planning = app(SupplyPlanning::class);
$transit = $planning->save($this->f['issuer'], 'import', supplyInput(['evidence' => 'Synthetic transit', 'event_date' => today()->toDateString()], 'transit', $this->import));
$arrived = $planning->save($this->f['issuer'], 'import', supplyInput(['evidence' => 'Synthetic arrival', 'event_date' => today()->toDateString()], 'arrive', $transit));
expect(array_column($service->workspace($this->f['issuer'], $arrived)['alerts'], 'key'))->toContain('customs-pending');
supplyGrant($this->f['receiver'], ['warehouse', 'import_customs', 'import_read']);
$this->actingAs($this->f['receiver']);
$released = $planning->save($this->f['receiver'], 'import', supplyInput(['evidence' => 'Synthetic independent release', 'event_date' => today()->toDateString()], 'release', $arrived));
$this->actingAs($this->f['issuer']);
expect(array_column($service->workspace($this->f['issuer'], $released)['alerts'], 'key'))->toContain('expected-due')->not->toContain('customs-pending');
$this->actingAs($this->f['receiver']);
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f, '1.000'));
$this->actingAs($this->f['issuer']);
expect(array_column($service->workspace($this->f['issuer'], $released)['alerts'], 'key'))->not->toContain('expected-due');
});
test('document requirements come from the frozen rule and missing or altered evidence reopens the live alert', function () {
$legal = app(ImportLegalRules::class);
$draft = $legal->save($this->f['issuer'], importLegalQaInput(), importLegalQaFile());
$published = $legal->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key, 'version' => 1,
'action' => 'publish', 'reason' => 'Synthetic customs source publication for current alerts']);
$frozen = $legal->freeze($published->id, '1234', 'Synthetic A', 'Synthetic sector', '2026-11-27');
// Construct an issued-order fixture; no production order is rewritten.
DB::table('purchase_orders')->where('id', $this->f['order']->id)->update(['snapshot' => json_encode([...$this->f['order']->snapshot,
'import_tariffs' => [['record_id' => 999, 'item' => ['description' => 'Synthetic classified item'],
'data' => ['requisition_id' => $this->f['r']->id], 'legal_rule' => $frozen]]], JSON_THROW_ON_ERROR)]);
$service = app(ImportReadiness::class);
expect(array_column($service->workspace($this->f['issuer'], $this->import)['alerts'], 'key'))->toContain('required-licence');
$document = app(ImportDossier::class)->record($this->f['issuer'], $this->import, ['operation_key' => (string) Str::uuid(), 'type' => 'licence',
'reference' => 'LICENCE-QA', 'issuer_reference' => 'Synthetic issuer', 'reason' => 'Synthetic licence for documentary readiness'],
UploadedFile::fake()->createWithContent('licence.pdf', "%PDF-1.4\nSynthetic licence\n%%EOF"));
expect(array_column($service->workspace($this->f['issuer'], $this->import)['alerts'], 'key'))->not->toContain('required-licence');
Storage::disk('local')->put($document->snapshot['evidence']['path'], 'altered');
expect(array_column($service->workspace($this->f['issuer'], $this->import)['alerts'], 'key'))->toContain('required-licence', 'document-'.$document->id);
$legal->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $published->record_key, 'version' => 2,
'action' => 'withdraw', 'reason' => 'Synthetic withdrawal alerts the existing decision without deleting it']);
expect(array_column($service->workspace($this->f['issuer'], $this->import)['alerts'], 'key'))->toContain('legal-changed-999');
});
test('bank pending alerts reuse the native report and disappear after dated documentary delivery', function () {
$fixture = importBankQaFixture($this->f['issuer'], $this->import);
$bank = app(ImportBankSupport::class);
$first = $bank->save($this->f['issuer'], $this->import, $fixture['input']);
$service = app(ImportReadiness::class);
$bankAlerts = fn () => array_values(array_filter($service->workspace($this->f['issuer'], $this->import)['alerts'], fn ($alert) => $alert['category'] === 'Suporte bancário'));
expect($bankAlerts())->not->toBeEmpty();
$bank->save($this->f['issuer'], $this->import, [...$fixture['input'], 'operation_key' => (string) Str::uuid(),
'record_key' => $first->record_key, 'version' => 1, 'submission_document_id' => $fixture['documents']['delivery']->id,
'submitted_on' => today()->toDateString(), 'submission_basis' => 'Synthetic documentary delivery evidence']);
expect($bankAlerts())->toBe([]);
config(['import-bank-support.qa_enabled' => false]);
$workspace = $service->workspace($this->f['issuer'], $this->import);
expect($workspace['complete'])->toBeFalse()->and(array_column($workspace['alerts'], 'key'))->toContain('bank-unavailable');
});
test('native follow-up revalidates current identity company context versions and private response headers', function () {
$url = '/compras/importacoes/'.$this->import->id.'/acompanhamento';
$this->get($url)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
->assertInertia(fn (Assert $page) => $page->component('supply/import-readiness')->where('automaticNotifications', false));
$foreign = receiptFixture();
supplyGrant($foreign['issuer'], ['procurement', 'import_read']);
$this->actingAs($foreign['issuer'])->get($url)->assertNotFound();
$this->actingAs($this->f['issuer']);
DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->delete();
expect(fn () => app(ImportReadiness::class)->workspace($this->f['issuer'], $this->import))->toThrow(HttpException::class);
});
test('accepted receipt in quarantine remains an availability alert until native independent quality release', function () {
$planning = app(SupplyPlanning::class);
$transit = $planning->save($this->f['issuer'], 'import', supplyInput(['evidence' => 'Synthetic transit', 'event_date' => today()->toDateString()], 'transit', $this->import));
$arrived = $planning->save($this->f['issuer'], 'import', supplyInput(['evidence' => 'Synthetic arrival', 'event_date' => today()->toDateString()], 'arrive', $transit));
supplyGrant($this->f['issuer'], ['inventory_lot_prepare']);
$lots = app(InventoryLots::class);
$setup = $lots->save($this->f['issuer'], supplyInput(['stock_item_id' => $this->f['stock']->id, 'warehouse_id' => $this->f['warehouse']->id,
'requires_expiry' => false, 'minimum_remaining_days' => 0, 'lots' => [], 'quarantine_on_receipt' => true], 'prepare'));
supplyGrant($this->f['receiver'], ['warehouse', 'import_customs', 'inventory_lot_review']);
$this->actingAs($this->f['receiver']);
$lots->save($this->f['receiver'], supplyInput([], 'activate', $setup));
$released = $planning->save($this->f['receiver'], 'import', supplyInput(['evidence' => 'Synthetic independent release', 'event_date' => today()->toDateString()], 'release', $arrived));
$input = receiptPayload($this->f, '1.000');
$input['items'][0]['lots'] = [['code' => 'QA-LOT', 'no_expiry' => true]];
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], $input);
$lot = $lots->context($this->f['stock']->id, $this->f['warehouse']->id)['lots'][0];
$this->actingAs($this->f['issuer']);
$alerts = app(ImportReadiness::class)->workspace($this->f['issuer'], $released)['alerts'];
expect(array_column($alerts, 'key'))->toContain('stock-held-'.$lot['id'].'-'.$this->f['warehouse']->id);
supplyGrant($this->f['otherReceiver'], ['warehouse', 'inventory_lot_release']);
$this->actingAs($this->f['otherReceiver']);
$lots->save($this->f['otherReceiver'], supplyInput(['lot_id' => $lot['id'], 'warehouse_id' => $this->f['warehouse']->id,
'state_version' => $lot['state_version']], 'release', SupplyRecord::query()->findOrFail($lot['metadata_id'])));
$this->actingAs($this->f['issuer']);
expect(array_column(app(ImportReadiness::class)->workspace($this->f['issuer'], $released)['alerts'], 'key'))->not->toContain('stock-held-'.$lot['id'].'-'.$this->f['warehouse']->id);
});
+63
View File
@@ -31,6 +31,8 @@ use App\Models\User;
use App\Models\Warehouse;
use App\Services\AgreementOrderLimits;
use App\Services\BudgetWorkflow;
use App\Services\CapitalAssignments;
use App\Services\CapitalRegister;
use App\Services\CommonBudget;
use App\Services\ComparisonPolicy;
use App\Services\ConflictGuard;
@@ -71,6 +73,67 @@ require_once __DIR__.'/../Support/SupplyFixture.php';
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
function nativeCapitalAssignment(object $test): array
{
config(['capital-register.qa_enabled' => true]);
$test->actingAs($test->buyer);
$input = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'type' => 'project',
'code' => 'PRJ-NATIVE-QA', 'name' => 'Projecto sintético da ordem', 'department_id' => $test->department->id,
'equipment_id' => null, 'reference' => 'Documento sintético de investimento', 'state' => 'active', 'reason' => 'Cadastro estritamente sintético da ligação à ordem'];
$source = app(CapitalRegister::class)->save($test->buyer, $input);
// Extend the pre-approved synthetic fixture with a choice made while it was a draft.
$test->r->update(['status' => 'draft']);
$test->actingAs($test->owner);
$assignment = app(CapitalAssignments::class)->save($test->owner, $test->r, ['operation_key' => (string) Str::uuid(),
'version' => 0, 'item_id' => $test->item->id, 'capital_id' => $source->id, 'reason' => 'Destino documental escolhido pelo requisitante sintético']);
$test->r->update(['status' => 'approved']);
$test->actingAs($test->buyer);
return [$source, $assignment, $input];
}
test('native order preserves the capital destination and print after the independent register is archived', function () {
[$source, $assignment, $input] = nativeCapitalAssignment($this);
$award = selectPurchaseAward($this);
$order = issuePurchaseOrder($this, $award);
expect($order->snapshot['capital_assignments'][$this->item->id]['id'])->toBe($assignment->id)
->and($order->total_minor)->toBe($award->total_minor);
app(CapitalRegister::class)->save($this->buyer, [...$input, 'operation_key' => (string) Str::uuid(),
'record_key' => $source->record_key, 'version' => 1, 'name' => 'Nome posterior ao documento', 'state' => 'archived']);
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('PRJ-NATIVE-QA')->assertSee('Projecto sintético da ordem')->assertDontSee('Nome posterior ao documento');
expect($order->fresh()->snapshot['capital_assignments'][$this->item->id]['snapshot']['source']['version'])->toBe(1);
$this->withoutVite();
$this->get('/projectos-imobilizado?history='.$source->record_key)->assertOk()
->assertInertia(fn (Assert $page) => $page->has('trace.orders.data', 1)->where('trace.orders.data.0.order_number', $order->number)->has('trace.receipts.data', 0));
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
$this->actingAs($receiver);
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'CAPITAL-QA', 'name' => 'Armazém sintético']);
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'CAPITAL-QA', 'name' => 'Artigo sintético', 'unit' => 'un']);
$receipt = app(ReceiptWorkflow::class)->confirm($receiver, $order, ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'CAPITAL-NATIVE-RECEIPT',
'received_on' => today()->toDateString(), 'warehouse_id' => $warehouse->id,
'items' => [['purchase_order_item_id' => $order->items()->sole()->id, 'received_quantity' => '1.000', 'accepted_quantity' => '1.000', 'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]]);
$this->actingAs($this->buyer);
$before = DB::table('stock_movements')->get()->toJson();
$this->get('/projectos-imobilizado?history='.$source->record_key)->assertOk()
->assertInertia(fn (Assert $page) => $page->has('trace.receipts.data', 1)->where('trace.receipts.data.0.receipt_id', $receipt->id)
->where('trace.receipts.data.0.accepted_quantity', '1.000')->where('trace.receipts.data.0.returned_quantity', '0.000')->where('trace.receipts.data.0.reversed', false));
expect(DB::table('stock_movements')->get()->toJson())->toBe($before);
});
test('native partial order freezes the same explicit capital origin without changing its financial allocation', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Select the approved isolated-QA common source for native order parts.');
}
[, $assignment] = nativeCapitalAssignment($this);
$award = nativeOrderPartsAward($this);
$input = nativeOrderPartsInput($this, $award, '0.400', 0);
$this->actingAs($this->buyer);
$order = app(OrderPartsWorkflow::class)->issue($this->buyer, $input);
expect($order->snapshot['capital_assignments'][$this->item->id]['id'])->toBe($assignment->id)
->and($order->total_minor)->toBe(4000)->and(DB::table('budget_order_commands')->count())->toBe(1);
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('PRJ-NATIVE-QA');
});
test('confirmed import classifications freeze in a newly issued native order and survive later proposals', function () {
config(['import-tariffs.qa_enabled' => true]);
$tariffs = app(ImportTariffCodes::class);
+35
View File
@@ -0,0 +1,35 @@
<?php
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\ImportDossier;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
/** Synthetic originals only; caller supplies an authorised native import-preparation actor.
* @return array{documents:array<string,SupplyRecord>,input:array<string,mixed>}
*/
function importBankQaFixture(User $actor, SupplyRecord $import): array
{
$db = DB::connection();
if (! app()->environment('testing') || ! (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|| ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName())))) {
throw new LogicException('Bank evidence fixtures require isolated QA.');
}
$documents = [];
foreach (['term' => 'bank_commitment', 'declaration' => 'customs_declaration', 'invoice' => 'commercial_invoice', 'delivery' => 'bank_support'] as $key => $type) {
$reference = 'BANK-QA-'.$key.'-'.Str::random(8);
$documents[$key] = app(ImportDossier::class)->record($actor, $import, ['operation_key' => (string) Str::uuid(), 'type' => $type,
'reference' => $reference, 'issuer_reference' => 'Synthetic bank evidence issuer', 'issued_on' => today()->toDateString(),
'reason' => 'Original estritamente sintético de suporte documental bancário'],
UploadedFile::fake()->createWithContent('bank-'.$key.'.pdf', "%PDF-1.4\nSynthetic evidence ".$reference."\n%%EOF"));
}
return ['documents' => $documents, 'input' => ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0,
'commitment_document_id' => $documents['term']->id, 'declaration_document_id' => $documents['declaration']->id,
'support_document_ids' => [$documents['invoice']->id], 'requirements_known' => true, 'required_support_types' => ['commercial_invoice'],
'required_support_counts' => ['commercial_invoice' => 1], 'requirements_basis' => 'Explicit synthetic bank letter requests one invoice',
'submission_document_id' => null, 'submission_basis' => null, 'submitted_on' => null,
'due_on' => today()->toDateString(), 'deadline_basis' => 'Explicit synthetic bank letter deadline', 'reason' => 'Acompanhamento bancário exclusivamente sintético']];
}
+42
View File
@@ -0,0 +1,42 @@
<?php
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
/** Synthetic rules only. Never seed official rates or a customer's configuration. */
function importLegalQaInput(array $overrides = []): array
{
$db = DB::connection();
if (! app()->environment('testing') || ! (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|| ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName())))) {
throw new LogicException('Legal fixtures require isolated QA.');
}
return [...['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'action' => 'save',
'title' => 'Synthetic tariff rule', 'official_reference' => 'Synthetic official edition QA only',
'official_url' => 'https://example.test/official-qa.pdf', 'citation' => 'Synthetic article 1, page 2',
'valid_from' => '2026-01-01', 'valid_until' => '2026-12-31', 'match_code' => '1234', 'suggested_code' => '1234.56',
'origin_country' => 'Synthetic A', 'sector' => 'Synthetic sector', 'obligations' => 'Synthetic conditions only; no real tax activated',
'document_types' => ['licence'], 'reason' => 'Synthetic legal configuration; not an approved real legal rule'], ...$overrides];
}
function importLegalQaFile(): UploadedFile
{
return UploadedFile::fake()->createWithContent('source.pdf', "%PDF-1.4\nSynthetic official source for QA only\n%%EOF");
}
function importLegalQaCharge(): array
{
return ['key' => 'synthetic-duty', 'kind' => 'duty', 'label' => 'Synthetic duty', 'method' => 'ad_valorem',
'rate_percent' => '7.5', 'specific_minor' => null, 'quantity_unit' => null,
'basis_reference' => 'Synthetic explicit customs valuation; no real rate configured'];
}
function importLegalQaAmountInput(int $itemId, int $ruleId): array
{
return ['operation_key' => (string) Str::uuid(), 'version' => 0, 'requisition_item_id' => $itemId, 'rule_id' => $ruleId,
'match_code' => '1234', 'origin' => 'Synthetic A', 'sector' => 'Synthetic sector', 'date' => '2026-11-27',
'bases' => ['synthetic-duty' => ['value_minor' => 10001, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic exact declared valuation']],
'reason' => 'Synthetic legal charge estimate without financial or stock effects'];
}
+29 -5
View File
@@ -43,12 +43,12 @@ function landedQaReceiptsVerified(array $command, string $output): bool
&& (! in_array($mode, ['race-estimate', 'race-estimate-reconcile'], true) || $contains(fn ($row) => ($row['old_estimate_runtime_rejected'] ?? false) === true
&& ($row['runtime_landed_version'] ?? null) === 'COMMON-BUDGET-LANDED-COST-QA-v2' && ($row['status'] ?? null) === 503));
}
if (in_array($mode, ['race-dossier', 'race-party'], true)) {
if (in_array($mode, ['race-dossier', 'race-party', 'race-bank', 'race-legal', 'race-legal-amount', 'race-capital'], true)) {
foreach (['same_operation', 'same_version'] as $scenario) {
$matches = array_values(array_filter($records, fn ($row) => ($row['scenario'] ?? null) === $scenario));
if (count($matches) !== 1 || ($matches[0]['blocked_writers_observed'] ?? 0) < 2
|| ($matches[0]['documents_created'] ?? 0) !== 1 || ($matches[0]['audits'] ?? 0) !== 1
|| ($matches[0]['files_created'] ?? -1) !== ($mode === 'race-party' ? 0 : 1) || ($matches[0]['all_originals_verified'] ?? false) !== true
|| ($matches[0]['files_created'] ?? -1) !== (in_array($mode, ['race-party', 'race-bank', 'race-legal-amount', 'race-capital'], true) ? 0 : 1) || ($matches[0]['all_originals_verified'] ?? false) !== true
|| ($matches[0]['statuses'] ?? null) !== ($scenario === 'same_operation' ? [200, 200] : [200, 409])) {
return false;
}
@@ -56,17 +56,41 @@ function landedQaReceiptsVerified(array $command, string $output): bool
return true;
}
if (in_array($mode, ['landed-costs', 'import-estimates'], true)) {
return ($mode !== 'import-estimates' || $contains(fn ($row) => ($row['estimate_source_remainder_restored'] ?? null) === 1000 && ($row['estimate_original_replay_without_effects'] ?? false) === true))
if (in_array($mode, ['landed-costs', 'import-estimates', 'import-bank-support', 'import-legal', 'import-legal-amount'], true)) {
return ($mode === 'landed-costs' || $contains(fn ($row) => ($row['estimate_source_remainder_restored'] ?? null) === 1000 && ($row['estimate_original_replay_without_effects'] ?? false) === true))
&& ($mode !== 'import-legal-amount' || $contains(fn ($row) => ($row['legal_amount_minor_restored'] ?? null) === 750 && ($row['legal_amount_replay_without_effects'] ?? false) === true
&& ($row['native_legal_plan_total_minor'] ?? null) === 10750 && ($row['native_legal_plan_source_restored'] ?? false) === true && ($row['native_legal_plan_replay_without_effects'] ?? false) === true))
&& (! in_array($mode, ['import-legal', 'import-legal-amount'], true) || $contains(fn ($row) => ($row['legal_source_restored'] ?? false) === true && ($row['legal_published_version_restored'] ?? false) === true
&& ($row['legal_buyer_context_restored'] ?? false) === true && ($row['legal_replay_without_effects'] ?? false) === true))
&& (! in_array($mode, ['import-bank-support', 'import-legal', 'import-legal-amount'], true) || $contains(fn ($row) => ($row['bank_support_versions_restored'] ?? null) === 2
&& ($row['bank_support_relationships_restored'] ?? false) === true && ($row['bank_support_replay_without_effects'] ?? false) === true))
&& $contains(fn ($row) => ($row['post_extension_restore_all_tables_equal'] ?? false) === true
&& ($row['recovered_operation_replay_no_effects'] ?? false) === true && ($row['pre_extension_schema_data_balance_restored'] ?? false) === true)
&& $contains(fn ($row) => ($row['private_original_versions_restored'] ?? 0) === 6 && ($row['typed_dossier_versions_restored'] ?? 0) === 4
&& $contains(fn ($row) => ($row['private_original_versions_restored'] ?? 0) === (in_array($mode, ['import-legal', 'import-legal-amount'], true) ? 11 : ($mode === 'import-bank-support' ? 10 : 6)) && ($row['typed_dossier_versions_restored'] ?? 0) === (in_array($mode, ['import-bank-support', 'import-legal', 'import-legal-amount'], true) ? 8 : 4)
&& ($row['selected_party_versions_restored'] ?? 0) === 2
&& ($row['source_loss_detected'] ?? false) === true
&& ($row['separate_private_root_restored'] ?? false) === true && ($row['native_authorized_evidence_resolved'] ?? false) === true)
&& $contains(fn ($row) => ($row['isolated_restore_removed'] ?? false) === true);
}
if (in_array($mode, ['legal-http', 'legal-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
&& ($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
&& ($row['private_http_server_stopped'] ?? false) === true && ($row['private_http_root_removed'] ?? false) === true);
}
if ($mode === 'corpus') {
return $contains(fn ($row) => ($row['shared_corpus_files_inventoried'] ?? 0) > 0 && count($row['real_official_sources_prepared'] ?? []) === 4
&& is_string($row['inventory_metadata_sha256'] ?? null) && preg_match('/^[a-f0-9]{64}$/D', $row['inventory_metadata_sha256']) === 1
&& count(array_filter($row['real_official_sources_prepared'], fn ($source) => is_string($source['sha256'] ?? null)
&& preg_match('/^[a-f0-9]{64}$/D', $source['sha256']) === 1 && ($source['bytes'] ?? 0) > 0
&& ($source['native_authorized_download_verified'] ?? false) === true)) === 4
&& ($row['rules_published'] ?? null) === 0 && ($row['originals_unchanged'] ?? false) === true
&& ($row['financial_and_stock_unchanged'] ?? false) === true && ($row['synthetic_qa_organization_only'] ?? false) === true);
}
return $mode === 'pest' && $contains(fn ($row) => ($row['tool'] ?? null) === 'pest' && ($row['result'] ?? null) === 'passed'
&& ($row['tests'] ?? 0) > 0 && ($row['passed'] ?? 0) === $row['tests']);
}
@@ -0,0 +1,38 @@
<?php
use Illuminate\Http\Request;
// Private HTTP composition only. Real Fortify login and CSRF middleware remain in the native routes.
$root = realpath(getenv('SGC_LEGAL_HTTP_QA_ROOT') ?: '');
$database = getenv('DB_DATABASE') ?: '';
$boundary = realpath(__DIR__.'/../../storage/framework/testing');
if (getenv('APP_ENV') !== 'testing' || getenv('DB_HOST') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)
|| ($_SERVER['REMOTE_ADDR'] ?? '') !== '127.0.0.1' || ($_SERVER['SERVER_PORT'] ?? '') != getenv('SGC_LEGAL_HTTP_QA_PORT')
|| $root === false || $boundary === false || str_replace('\\', '/', $root) !== str_replace('\\', '/', $boundary).'/legal-http-'.$database) {
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($root.'/public');
$app->booted(function () use ($root, $database) {
if (config('database.default') !== 'pgsql' || config('database.connections.pgsql.database') !== $database) {
abort(503);
}
config(['capital-register.qa_enabled' => true, 'import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true,
'import-dossier.qa_enabled' => true, 'import-bank-support.qa_enabled' => true, 'import-readiness.qa_enabled' => true, 'import-estimates.qa_enabled' => true,
'session.driver' => 'file', 'session.files' => $root.'/storage/framework/sessions', 'session.domain' => null,
'session.secure' => false, 'cache.default' => 'array']);
});
$app->handleRequest(Request::capture());
+92
View File
@@ -1,5 +1,19 @@
<?php
test('capital register contention requires both actual lock receipts and one immutable version per scenario', function () {
$command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'race-capital'];
$rows = [];
foreach (['same_operation' => [200, 200], 'same_version' => [200, 409]] as $scenario => $statuses) {
$rows[] = ['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => 2, 'documents_created' => 1,
'audits' => 1, 'files_created' => 0, 'all_originals_verified' => true];
}
$output = implode("\n", array_map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR), $rows));
expect(landedQaReceiptsVerified($command, $output))->toBeTrue();
expect(landedQaReceiptsVerified($command, json_encode($rows[0], JSON_THROW_ON_ERROR)))->toBeFalse();
$rows[1]['documents_created'] = 2;
expect(landedQaReceiptsVerified($command, implode("\n", array_map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR), $rows))))->toBeFalse();
});
require_once __DIR__.'/../Support/LandedQaReceipts.php';
test('estimate contention receipts require all native uniqueness races and explicit estimate effects', function () {
@@ -74,6 +88,15 @@ test('restore completion requires the restored replay original snapshot and data
expect(landedQaReceiptsVerified($estimateCommand, $existingRecovery."\n".json_encode([
'estimate_source_remainder_restored' => 1000, 'estimate_original_replay_without_effects' => true,
], JSON_THROW_ON_ERROR)))->toBeTrue();
$bankCommand = [...array_slice($command, 0, 3), 'import-bank-support'];
$bankPrivate = [...$privateFiles, 'private_original_versions_restored' => 10, 'typed_dossier_versions_restored' => 8];
$bankOutput = $databaseOnly."\n".json_encode($bankPrivate, JSON_THROW_ON_ERROR)."\n".json_encode([
'estimate_source_remainder_restored' => 1000, 'estimate_original_replay_without_effects' => true,
], JSON_THROW_ON_ERROR);
expect(landedQaReceiptsVerified($bankCommand, $bankOutput))->toBeFalse();
expect(landedQaReceiptsVerified($bankCommand, $bankOutput."\n".json_encode([
'bank_support_versions_restored' => 2, 'bank_support_relationships_restored' => true, 'bank_support_replay_without_effects' => true,
], JSON_THROW_ON_ERROR)))->toBeTrue();
$missingTyped = $privateFiles;
unset($missingTyped['typed_dossier_versions_restored']);
expect(landedQaReceiptsVerified($command, $databaseOnly."\n".json_encode($missingTyped, JSON_THROW_ON_ERROR)))->toBeFalse();
@@ -101,6 +124,75 @@ test('dossier contention requires both races one original and verified bytes', f
}
unset($row);
expect(landedQaReceiptsVerified($partyCommand, $encode($rows)))->toBeTrue();
$bankCommand = [...array_slice($partyCommand, 0, 3), 'race-bank'];
expect(landedQaReceiptsVerified($bankCommand, $encode($rows)))->toBeTrue();
$rows[1]['files_created'] = 1;
expect(landedQaReceiptsVerified($partyCommand, $encode($rows)))->toBeFalse();
expect(landedQaReceiptsVerified($bankCommand, $encode($rows)))->toBeFalse();
});
test('legal contention and recovery require original source publication and frozen buyer context receipts', function () {
$command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'race-legal'];
$rows = [];
foreach (['same_operation', 'same_version'] as $scenario) {
$rows[] = ['scenario' => $scenario, 'statuses' => $scenario === 'same_operation' ? [200, 200] : [200, 409],
'blocked_writers_observed' => 2, 'documents_created' => 1, 'audits' => 1, 'files_created' => 1, 'all_originals_verified' => true];
}
$encode = fn ($records) => implode("\n", array_map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR), $records));
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeTrue();
$rows[1]['files_created'] = 0;
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
$command[3] = 'import-legal';
$rows = [['post_extension_restore_all_tables_equal' => true, 'recovered_operation_replay_no_effects' => true,
'pre_extension_schema_data_balance_restored' => true, 'isolated_restore_removed' => true,
'estimate_source_remainder_restored' => 1000, 'estimate_original_replay_without_effects' => true,
'bank_support_versions_restored' => 2, 'bank_support_relationships_restored' => true, 'bank_support_replay_without_effects' => true,
'private_original_versions_restored' => 11, 'typed_dossier_versions_restored' => 8, 'selected_party_versions_restored' => 2,
'source_loss_detected' => true, 'separate_private_root_restored' => true, 'native_authorized_evidence_resolved' => true]];
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
$rows[] = ['legal_source_restored' => true, 'legal_published_version_restored' => true, 'legal_buyer_context_restored' => true, 'legal_replay_without_effects' => true];
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeTrue();
unset($rows[1]['legal_buyer_context_restored']);
expect(landedQaReceiptsVerified($command, $encode($rows)))->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),
'real_official_sources_prepared' => array_fill(0, 4, ['sha256' => str_repeat('b', 64), 'bytes' => 100, 'native_authorized_download_verified' => true]),
'rules_published' => 0, 'originals_unchanged' => true, 'financial_and_stock_unchanged' => true, 'synthetic_qa_organization_only' => true];
$encode = fn ($value) => json_encode($value, JSON_THROW_ON_ERROR);
expect(landedQaReceiptsVerified($command, $encode($row)))->toBeTrue();
$row['real_official_sources_prepared'][0]['native_authorized_download_verified'] = false;
expect(landedQaReceiptsVerified($command, $encode($row)))->toBeFalse();
$row['real_official_sources_prepared'][0]['native_authorized_download_verified'] = true;
$row['rules_published'] = 1;
expect(landedQaReceiptsVerified($command, $encode($row)))->toBeFalse();
});
test('legal amount receipts require both contention cases and recovery of the exact native source-linked cost total', function () {
$command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'race-legal-amount'];
$rows = [];
foreach (['same_operation', 'same_version'] as $scenario) {
$rows[] = ['scenario' => $scenario, 'statuses' => $scenario === 'same_operation' ? [200, 200] : [200, 409],
'blocked_writers_observed' => 2, 'documents_created' => 1, 'audits' => 1, 'files_created' => 0, 'all_originals_verified' => true];
}
$encode = fn ($records) => implode("\n", array_map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR), $records));
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeTrue();
$rows[0]['files_created'] = 1;
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
$command[3] = 'import-legal-amount';
$rows = [['post_extension_restore_all_tables_equal' => true, 'recovered_operation_replay_no_effects' => true,
'pre_extension_schema_data_balance_restored' => true, 'isolated_restore_removed' => true,
'estimate_source_remainder_restored' => 1000, 'estimate_original_replay_without_effects' => true,
'bank_support_versions_restored' => 2, 'bank_support_relationships_restored' => true, 'bank_support_replay_without_effects' => true,
'private_original_versions_restored' => 11, 'typed_dossier_versions_restored' => 8, 'selected_party_versions_restored' => 2,
'source_loss_detected' => true, 'separate_private_root_restored' => true, 'native_authorized_evidence_resolved' => true,
'legal_source_restored' => true, 'legal_published_version_restored' => true, 'legal_buyer_context_restored' => true, 'legal_replay_without_effects' => true]];
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
$rows[] = ['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];
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeTrue();
$rows[1]['native_legal_plan_total_minor'] = 10751;
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
});
+89
View File
@@ -0,0 +1,89 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import CapitalRegister from '../../resources/js/pages/equipment/capital-register';
import CapitalAssignments from '../../resources/js/pages/requisitions/capital-assignments';
import CapitalAssignmentSummary from '../../resources/js/components/capital-assignment-summary';
const source = {
id: 2,
version: 3,
record_key: 'source',
state: 'archived',
reason: 'Synthetic archive reason',
data: {
type: 'project',
code: 'PRJ-QA',
name: '<script>QA</script>',
reference: 'Frozen documentary reference',
department_id: 1,
equipment_id: null,
},
};
const page = <T,>(data: T[]) => ({
data,
prev_page_url: null,
next_page_url: null,
});
const assignment = {
id: 5,
version: 1,
state: 'linked',
reason: 'Synthetic deliberate assignment',
data: { requisition_item_id: 1 },
snapshot: { item: { description: 'Synthetic item' }, source },
};
function render(
component: typeof CapitalRegister | typeof CapitalAssignments,
props: object,
) {
return renderToStaticMarkup(
<App
initialComponent={component}
initialPage={{
component: 'qa',
url: '/qa',
version: null,
clearHistory: false,
encryptHistory: true,
props: { errors: {}, ...props },
}}
/>,
);
}
test('read-only capital register preserves archived identity and history without management forms', () => {
const html = render(CapitalRegister, {
records: page([source]),
history: page([source]),
departments: [],
equipment: [],
canManage: false,
actorId: 1,
tenantId: 1,
});
expect(html).toContain('Arquivado');
expect(html).toContain('Histórico do registo');
expect(html).toContain('&lt;script&gt;QA&lt;/script&gt;');
expect(html).not.toContain('<form');
});
test('approved requisitions display the preserved source independently of available new choices', () => {
const html = render(CapitalAssignments, {
requisition: { id: 1, number: 'REQ-QA', status: 'approved' },
items: [],
current: [assignment],
choices: page([]),
history: page([assignment]),
canWrite: false,
actorId: 1,
tenantId: 1,
});
expect(html).toContain('PRJ-QA');
expect(html).toContain('versão 3');
expect(html).not.toContain('<form');
const frozen = renderToStaticMarkup(
<CapitalAssignmentSummary records={{ 1: assignment }} />,
);
expect(frozen).toContain('Frozen documentary reference');
expect(frozen).toContain('&lt;script&gt;QA&lt;/script&gt;');
expect(renderToStaticMarkup(<CapitalAssignmentSummary />)).toBe('');
});
+143
View File
@@ -0,0 +1,143 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import BankSupport from '@/pages/supply/import-bank-support';
function renderBankSupport(canWrite: boolean, dated = false) {
const record = {
id: 2,
record_key: 'synthetic-bank-key',
version: 1,
state: dated ? 'documented' : 'ready',
reason: 'Synthetic bank evidence',
data: {
commitment_document_id: 1,
declaration_document_id: 3,
support_document_ids: [4, 5],
submission_document_id: dated ? 6 : null,
submission_basis: dated
? 'Explicit synthetic delivery evidence'
: null,
submitted_on: dated ? '2026-11-26' : null,
requirements_known: true,
required_support_types: ['commercial_invoice'],
required_support_counts: { commercial_invoice: 2 },
requirements_basis: 'Explicit synthetic bank request',
due_on: dated ? '2026-11-27' : null,
deadline_basis: dated
? 'Explicit synthetic bank request deadline'
: null,
},
snapshot: {
documents: [
{
id: 1,
version: 1,
type: 'bank_commitment',
reference: '<script>private term</script>',
issuer_reference: 'Synthetic bank',
},
{
id: 3,
version: 1,
type: 'customs_declaration',
reference: 'DU-QA',
issuer_reference: 'Synthetic issuer',
},
{
id: 4,
version: 1,
type: 'commercial_invoice',
reference: 'INVOICE-QA-1',
issuer_reference: 'Synthetic supplier',
},
{
id: 5,
version: 1,
type: 'commercial_invoice',
reference: 'INVOICE-QA-2',
issuer_reference: 'Synthetic supplier',
},
...(dated
? [
{
id: 6,
version: 1,
type: 'bank_support',
reference: 'DELIVERY-QA',
issuer_reference: 'Synthetic bank',
},
]
: []),
],
},
issues: dated
? []
: [
'Falta o comprovativo de entrega ao banco.',
'Prazo documental ainda por indicar.',
],
};
const page = { data: [record], prev_page_url: null, next_page_url: null };
return renderToStaticMarkup(
<App
initialComponent={BankSupport}
initialPage={{
component: 'supply/import-bank-support',
url: '/qa',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
importRecord: {
id: 1,
record_key: 'synthetic-import-key',
version: 1,
},
order: { id: 1, number: 'QA' },
current: page,
history: page,
documents: {
data: [],
prev_page_url: null,
next_page_url: '/qa?bank_documents_page=2',
},
types: {
bank_commitment: 'Termo de compromisso',
commercial_invoice: 'Factura comercial',
bank_support: 'Suporte bancário',
},
canWrite,
actorId: 3,
tenantId: 2,
},
}}
/>,
);
}
test('bank consultation and report links preserve unknown deadlines requested counts and the delivery distinction', () => {
const html = renderBankSupport(false);
expect(html).toContain('Documentos reunidos; entrega por documentar');
expect(html).toContain('Factura comercial: 2');
expect(html).toContain('Prazo: Por indicar');
expect(html).toContain('suporte-bancario.csv');
expect(html).toContain('&lt;script&gt;private term&lt;/script&gt;');
expect(html).not.toContain('<form');
});
test('bank date presentation follows the shared local format and preserves the actual documentary delivery date', () => {
const html = renderBankSupport(false, true);
expect(html).toContain('Prazo: 27/11/2026');
expect(html).toContain('Entrega documentada: 26/11/2026');
expect(html).toContain('Comprovativo de entrega associado');
expect(html).not.toContain('entrega por documentar');
});
test('bank preparation reuses existing originals and does not apply a generic legal deadline', () => {
const html = renderBankSupport(true);
expect(html).toContain('Seleccione os originais já registados');
expect(html).toContain('Fonte dos requisitos ou informação ainda em falta');
expect(html).not.toContain('30 dias');
});
+113
View File
@@ -0,0 +1,113 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import ImportEstimate from '@/pages/supply/import-estimate';
function renderPlan(linked = false) {
const page = { data: [], prev_page_url: null, next_page_url: null };
const source = {
id: 4,
version: 2,
snapshot: {
item: { description: 'Synthetic valued item' },
legal_rule: {
data: { official_reference: 'Preserved official source' },
},
result: {
lines: [
{
key: 'duty-line',
kind: 'duty',
label: 'Synthetic documented duty',
method: 'ad_valorem',
amount_minor: 750,
},
],
},
},
};
return renderToStaticMarkup(
<App
initialComponent={ImportEstimate}
initialPage={{
component: 'supply/import-estimate',
url: '/qa',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
requisition: {
id: 1,
number: 'QA',
status: 'draft',
total_minor: 10000,
},
actorId: 2,
tenantId: 3,
canPrepare: true,
nativeChanged: false,
budgets: page,
history: page,
legalAmounts: [source],
latest: linked
? {
id: 5,
version: 1,
state: 'prepared',
reason: 'Synthetic scenario',
data: {
budget_id: 1,
components: [
{
key: 'duty',
kind: 'duty',
status: 'known',
basis: 'Preserved selected calculation',
subtotal_minor: 750,
tax_minor: 0,
total_minor: 750,
},
],
},
snapshot: {
plan: {
complete: true,
budget_amount_minor: 10750,
known_total_minor: 10750,
unknown: [],
},
legal_sources: {
duty: {
estimate_id: 4,
estimate_version: 2,
charge_key: 'duty-line',
},
},
},
}
: null,
},
}}
/>,
);
}
test('native import preparation offers legal source reuse and additional parcels without silently selecting a value', () => {
const html = renderPlan();
expect(html).toContain('Reutilizar uma imposição calculada');
expect(html).toContain('Synthetic valued item');
expect(html).toContain('7.50 MZN');
expect(html).toContain('Acrescentar parcela desta família');
expect(html).not.toContain('O total conserva a fonte seleccionada');
});
test('a preserved legal amount retains explicit budget tax treatment and a deliberate manual-detach action', () => {
const html = renderPlan(true);
expect(html).toContain('O total conserva a fonte seleccionada');
expect(html).toContain('divisão entre base e imposto');
expect(html).toContain('retirar ligação e conservar os valores');
expect(html.match(/<option[^>]*value="4:duty-line"[^>]*>/)?.[0]).toContain(
'selected=""',
);
});
+116
View File
@@ -0,0 +1,116 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Legal from '../../resources/js/pages/supply/import-legal';
function renderLegal(canManage: boolean, withRule = true, withCharges = false) {
const data = {
title: '<script>synthetic rule</script>',
official_reference: 'Synthetic official edition',
official_url: 'https://example.test/source.pdf',
citation: 'Article QA',
valid_from: '2026-01-01',
valid_until: null,
match_code: '1234',
suggested_code: '1234.56',
origin_country: null,
sector: null,
obligations: 'Synthetic conditions only',
document_types: ['licence'],
charges: withCharges
? [
{
key: 'synthetic-duty',
kind: 'duty',
label: 'Synthetic duty',
method: 'maximum',
rate_percent: '7.500000',
specific_minor: 125,
quantity_unit: 'KG',
basis_reference:
'Synthetic explicit valuation and quantity basis',
},
]
: [],
};
const rule = {
id: 1,
record_key: 'qa',
version: 2,
state: 'published',
data,
reason: 'Synthetic publication',
source_url: '/requisicoes/1/base-legal/fontes/1',
};
const page = {
data: withRule ? [rule] : [],
prev_page_url: null,
next_page_url: null,
};
return renderToStaticMarkup(
<App
initialComponent={Legal}
initialPage={{
component: 'supply/import-legal',
url: '/qa',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
requisition: { id: 1, number: 'QA' },
rules: page,
history: page,
suggestions: withRule
? [{ id: 1, version: 2, data, source_sha256: 'qa' }]
: [],
items: [{ id: 1, description: 'Synthetic item' }],
classifications: [],
canManage,
canPropose: canManage,
actorId: 1,
tenantId: 1,
types: { licence: 'Licença ou autorização' },
filters: { code: '1234', date: '2026-11-27' },
},
}}
/>,
);
}
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;');
expect(html).toContain('01/01/2026');
expect(html).toContain('sem termo final indicado');
expect(html).toContain('/base-legal/fontes/1');
expect(html).not.toContain('Guardar preparação para validação aduaneira');
expect(html).not.toContain('Preparar proposta com esta fonte');
});
test('legal preparation makes documentary scope and human publication explicit', () => {
const html = renderLegal(true);
expect(html).toContain('Preparar proposta com esta fonte');
expect(html).toContain('Preparar nova versão');
expect(html).toContain('Guardar preparação para validação aduaneira');
expect(html).toContain('Exemplar oficial');
expect(html).toContain('Licença ou autorização');
});
test('no matching rule never becomes an assumed zero tax or exemption', () => {
const html = renderLegal(false, false);
expect(html).toContain('Sem regra publicada correspondente');
expect(html).toContain('Não foram presumidos código, taxa ou isenção');
});
test('documented charges expose their methods rates units and input provenance before estimating', () => {
const html = renderLegal(true, true, true);
expect(html).toContain(
'Maior valor entre percentagem e montante por unidade',
);
expect(html).toContain('7.500000%');
expect(html).toContain('Taxa específica:');
expect(html).toContain('Quantidade em KG');
expect(html).toContain('Origem do valor ou da quantidade');
expect(html).toContain('Calcular e preservar estimativa');
});
+88
View File
@@ -0,0 +1,88 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Readiness from '../../resources/js/pages/supply/import-readiness';
import ImportTariffSummary from '../../resources/js/components/import-tariff-summary';
test('import follow-up preserves incomplete checks actionable links and unknown dates without rendering financial operations', () => {
const html = renderToStaticMarkup(
<App
initialComponent={Readiness}
initialPage={{
component: 'supply/import-readiness',
url: '/qa',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
importRecord: { id: 1, version: 2, state: 'arrived' },
order: { id: 1, number: 'QA' },
expectedUsableOn: null,
checkedAt: '2026-11-27',
complete: false,
alerts: [
{
key: 'missing',
category: 'Documentos',
text: '<script>Missing synthetic licence</script>',
href: '/compras/importacoes/1/documentos',
},
],
},
}}
/>,
);
expect(html).toContain('Verificação incompleta');
expect(html).toContain('Por indicar');
expect(html).toContain(
'&lt;script&gt;Missing synthetic licence&lt;/script&gt;',
);
expect(html).toContain('/compras/importacoes/1/documentos');
expect(html).not.toContain('<form');
});
test('issued classification displays the frozen legal citation and obligations rather than the current catalogue', () => {
const html = renderToStaticMarkup(
<ImportTariffSummary
records={{
1: {
record_id: 1,
version: 2,
item: {
description: 'Synthetic item',
quantity: '1',
unit: 'KG',
},
data: {
proposed_code: '1234',
confirmed_code: '1234',
source_reference: 'Source',
confirmation_source: 'Confirmed source',
deviation: false,
},
confirmed_by: { name: 'Synthetic buyer' },
reason: 'Synthetic decision',
legal_rule: {
version: 5,
data: {
official_reference: 'Preserved official edition',
citation: 'Article QA',
obligations: 'Preserved documentary conditions',
document_types: ['licence'],
},
context: {
date: '2026-11-27',
origin_country: 'Synthetic A',
sector: 'Synthetic sector',
},
},
},
}}
/>,
);
expect(html).toContain('Preserved official edition');
expect(html).toContain('Article QA');
expect(html).toContain('versão 5');
expect(html).toContain('Preserved documentary conditions');
});