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

This commit is contained in:
2026-11-27 13:49:31 +02:00
parent dc73540558
commit e709d900d1
81 changed files with 5352 additions and 107 deletions
@@ -1,10 +1,15 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\PurchaseOrder;
use App\Models\Supplier;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\CommonBudget;
use App\Services\ImportCostDocumentHealth;
use App\Services\ImportDossier;
use App\Services\ImportLandedCosts;
use App\Services\ImportParties;
use App\Services\SupplyPlanning;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Database\Connection;
@@ -14,6 +19,9 @@ use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Symfony\Component\Process\Process;
use Tempo\Finance\Budget\BudgetImportEstimate;
require_once __DIR__.'/../Support/ImportQaIdentity.php';
require __DIR__.'/../../vendor/autoload.php';
$app = require __DIR__.'/../../bootstrap/app.php';
@@ -27,8 +35,10 @@ 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/BudgetDistributionSchema.php';
$orderParts = ($argv[2] ?? '') === 'order-parts';
$landedCosts = ($argv[2] ?? '') === 'landed-costs';
$orderPartsAmendment = ($argv[2] ?? '') === 'order-parts-amendment';
$orderParts = $orderPartsAmendment || ($argv[2] ?? '') === 'order-parts';
$importEstimates = ($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]);
$reviewer = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
@@ -86,16 +96,31 @@ $unexpectedEffects = $landedCosts
if ($fingerprint($db, $columns) !== $before || app(CommonBudget::class)->for($author)->balance($budget) !== $balanceBefore || $unexpectedEffects) {
throw new RuntimeException('Optional schema changed pre-existing data or native balances.');
}
$prepare = new Process([PHP_BINARY, __DIR__.($landedCosts ? '/budget-landed-cost-worker.php' : ($orderParts ? '/budget-order-parts-worker.php' : '/budget-distribution-worker.php')), $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
$prepare = new Process([PHP_BINARY, __DIR__.($landedCosts ? '/budget-landed-cost-worker.php' : ($orderParts ? '/budget-order-parts-worker.php' : '/budget-distribution-worker.php')), $database, $importEstimates ? 'prepare-estimate' : ($orderPartsAmendment ? 'prepare-amend' : 'prepare')], dirname(__DIR__, 2), timeout: 30);
$prepare->mustRun();
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$actor = User::query()->findOrFail($input['actor']);
auth()->guard()->setUser($actor);
$engine = app(CommonBudget::class)->for($actor);
if ($importEstimates) {
$estimateInput = $input;
$estimateComponents = array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => 'not_applicable', 'basis' => 'Synthetic recovery assumption',
'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS);
$estimateComponents[0] = [...$estimateComponents[0], 'status' => 'known', 'subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000];
$estimateApply = static fn ($engine) => $engine->reserveImportEstimate($estimateInput['plan'], 1, $estimateInput['budget'], $estimateInput['requisition'],
['subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000], $estimateComponents, $estimateInput['operation']);
$estimated = $estimateApply($engine);
$input['plan'] = (string) Str::uuid();
$input['operation'] = (string) Str::uuid();
$engine->reconcileImportEstimate($estimateInput['plan'], 1, $estimated['plan_hash'], 1, 1000, $input['plan'], 1, $input['budget'],
$input['components'], $input['documents'], (string) Str::uuid(), $input['operation']);
}
$apply = static fn ($engine) => $landedCosts
? $engine->reserveLandedCosts($input['plan'], $input['version'], $input['budget'], $input['components'], $input['documents'], $input['operation'])
: ($orderParts ? $engine->commitOrderParts($input['order'], $input['sources'], $input['operation'])
: $engine->amendDistribution($input['origin'], $input['plan'], $input['hash'], 'Explicit synthetic amendment preserved in backup.', $input['operation']));
? ($importEstimates ? $engine->landedCostState($input['plan'])['result']
: $engine->reserveLandedCosts($input['plan'], $input['version'], $input['budget'], $input['components'], $input['documents'], $input['operation']))
: ($orderPartsAmendment ? $engine->amendOrderParts($input['order'], $input['sources'], 'Explicit synthetic amendment preserved in backup.', $input['operation'])
: ($orderParts ? $engine->commitOrderParts($input['order'], $input['sources'], $input['operation'])
: $engine->amendDistribution($input['origin'], $input['plan'], $input['hash'], 'Explicit synthetic amendment preserved in backup.', $input['operation'])));
$applied = $apply($engine);
if ($landedCosts) {
foreach (['commit', 'consume'] as $kind) {
@@ -119,7 +144,7 @@ if ($landedCosts) {
$privateRestore = $directory.'/private-restored';
File::ensureDirectoryExists($privateLive);
Storage::set('local', Storage::build(['driver' => 'local', 'root' => $privateLive, 'throw' => true]));
config(['import-landed-costs.qa_enabled' => true]);
config(['import-landed-costs.qa_enabled' => true, 'import-dossier.qa_enabled' => true]);
supplyGrant($f['issuer'], ['procurement', 'import_prepare']);
supplyGrant($author, ['finance']);
auth()->guard()->setUser($f['issuer']);
@@ -138,8 +163,37 @@ if ($landedCosts) {
$correction = $costs->recordDocument($author, $nativeImport, [...$nativeData, 'operation_key' => (string) Str::uuid(),
'record_key' => $nativeDoc->record_key, 'version' => 1, 'subtotal_minor' => 2100, 'total_minor' => 2100],
UploadedFile::fake()->createWithContent('recovery-correction.pdf', "%PDF-1.4\nSynthetic corrected QA bytes\n%%EOF"));
auth()->guard()->setUser($f['issuer']);
$dossier = app(ImportDossier::class);
$typedInput = ['operation_key' => (string) Str::uuid(), 'type' => 'packing_list', 'reference' => 'PACK-RECOVERY-QA',
'issuer_reference' => 'Synthetic packing list issuer', 'reason' => 'Retain a synthetic private packing list for recovery.'];
$typedFirst = $dossier->record($f['issuer'], $nativeImport, $typedInput,
UploadedFile::fake()->createWithContent('packing.pdf', "%PDF-1.4\nSynthetic packing original\n%%EOF"));
$typedCorrection = $dossier->record($f['issuer'], $nativeImport, [...$typedInput, 'operation_key' => (string) Str::uuid(),
'record_key' => $typedFirst->record_key, 'version' => 1],
UploadedFile::fake()->createWithContent('packing-correction.pdf', "%PDF-1.4\nSynthetic packing correction\n%%EOF"));
$partyBuyer = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Procurement]);
supplyGrant($partyBuyer, ['procurement', 'import_prepare']);
auth()->guard()->setUser($partyBuyer);
$partySupplier = Supplier::query()->whereKey($f['order']->supplier_id)->firstOrFail()->replicate();
$partySupplier->name = 'Synthetic recovery broker';
$partySupplier->nuit = '987654321';
$partySupplier->save();
$instructionsInput = [...$typedInput, 'operation_key' => (string) Str::uuid(), 'type' => 'written_instructions', 'reference' => 'INSTRUCTIONS-RECOVERY-QA'];
$instructions = $dossier->record($partyBuyer, $nativeImport, $instructionsInput,
UploadedFile::fake()->createWithContent('instructions.pdf', "%PDF-1.4\nSynthetic recovery instructions\n%%EOF"));
$partyInput = ['operation_key' => (string) Str::uuid(), 'role' => 'broker', 'version' => 0, 'supplier_id' => $partySupplier->id,
'supplier_version' => $partySupplier->version, 'instruction_document_id' => $instructions->id, 'no_conflict' => true,
'reason' => 'Explicit synthetic broker and instructions for recovery.'];
$party = app(ImportParties::class)->select($partyBuyer, $nativeImport, $partyInput);
$instructionsCorrection = $dossier->record($partyBuyer, $nativeImport, [...$instructionsInput, 'operation_key' => (string) Str::uuid(),
'record_key' => $instructions->record_key, 'version' => 1],
UploadedFile::fake()->createWithContent('instructions-correction.pdf', "%PDF-1.4\nSynthetic revised recovery instructions\n%%EOF"));
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];
$evidenceManifest = [];
foreach ([$nativeDoc, $correction] as $record) {
foreach ($nativeEvidenceRecords as $record) {
$evidence = $record->snapshot['evidence'];
$evidenceManifest[$evidence['path']] = $evidence['sha256'];
}
@@ -152,9 +206,9 @@ if ($landedCosts) {
}
Storage::disk('local')->delete($path);
}
auth()->guard()->logout();
if (app(ImportCostDocumentHealth::class)->inspect()['missing'] !== 2) {
throw new RuntimeException('The recovery test must demonstrate actual loss of its two synthetic original files.');
clearImportQaIdentity();
if (app(ImportCostDocumentHealth::class)->inspect()['missing'] !== count($nativeEvidenceRecords)) {
throw new RuntimeException('The recovery test must demonstrate actual loss of its synthetic original files.');
}
}
auth()->guard()->setUser($author);
@@ -197,13 +251,22 @@ try {
if ($position['result']['consumed_minor'] !== 2000 || $position['result']['reserved_minor'] !== 500 || $position['result']['phase'] !== 'mixed') {
throw new RuntimeException('Restored per-origin positions do not match the preserved journal.');
}
if ($importEstimates) {
$restoredEngine = app(CommonBudget::class)->for($restoredActor);
$estimateState = $restoredEngine->landedCostState($estimateInput['plan']);
$estimateReplay = $estimateApply($restoredEngine);
if ($estimateState['result']['reserved_minor'] !== 1000 || ! $estimateReplay['replayed'] || $fingerprint($restored, $afterColumns) !== $after) {
throw new RuntimeException('The restored estimate remainder, original replay or complete SQL fingerprint differs.');
}
echo json_encode(['estimate_source_remainder_restored' => 1000, 'estimate_original_replay_without_effects' => true], JSON_THROW_ON_ERROR).PHP_EOL;
}
if (! File::copyDirectory($privateBackup, $privateRestore)) {
throw new RuntimeException('Unable to restore private evidence into the separate QA root.');
}
Storage::set('local', Storage::build(['driver' => 'local', 'root' => $privateRestore, 'throw' => true]));
auth()->guard()->logout();
clearImportQaIdentity();
$health = app(ImportCostDocumentHealth::class)->inspect();
if (! $health['ok'] || ! $health['complete'] || $health['documents_checked'] !== 2 || $health['files_checked'] !== 2) {
if (! $health['ok'] || ! $health['complete'] || $health['documents_checked'] !== count($nativeEvidenceRecords) || $health['files_checked'] !== count($nativeEvidenceRecords)) {
throw new RuntimeException('Restored native evidence did not match the restored SQL metadata.');
}
auth()->guard()->setUser(User::query()->findOrFail($author->id));
@@ -213,7 +276,30 @@ try {
throw new RuntimeException('Private native download no longer resolves the preserved original version.');
}
}
echo json_encode(['private_original_versions_restored' => 2, 'source_loss_detected' => true,
auth()->guard()->setUser(User::query()->findOrFail($f['issuer']->id));
foreach ([$typedFirst, $typedCorrection, $instructions, $instructionsCorrection] as $record) {
$recovered = $dossier->evidence(auth()->user(), $nativeImport, $record->id);
if ($recovered->snapshot['evidence']['sha256'] !== $evidenceManifest[$recovered->snapshot['evidence']['path']]) {
throw new RuntimeException('Restored typed dossier version lost its original evidence.');
}
}
$restoredBuyer = User::query()->findOrFail($partyBuyer->id);
auth()->guard()->setUser($restoredBuyer);
$restoredOrder = PurchaseOrder::query()->whereKey($f['order']->id)->firstOrFail();
app(ImportParties::class)->assertCurrent($restoredBuyer, $restoredOrder, $nativeImport->record_key);
$restoredParty = SupplyRecord::query()->where('kind', 'import_party')->where('record_key', $party->record_key)->latest('version')->firstOrFail();
if ($restoredParty->version !== 2) {
throw new RuntimeException('Restored broker version differs: '.get_debug_type($restoredParty->version).' '.json_encode($restoredParty->version));
}
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));
}
$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,
'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;
}
+55 -13
View File
@@ -10,6 +10,7 @@ use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\Process\Process;
use Tempo\Finance\Budget\BudgetControl;
use Tempo\Finance\Budget\BudgetFailure;
use Tempo\Finance\Budget\BudgetImportEstimate;
require __DIR__.'/../../vendor/autoload.php';
$database = $argv[1] ?? '';
@@ -21,22 +22,24 @@ if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::con
throw new LogicException('Landed-cost contention requires the approved common source and isolated local QA.');
}
require_once __DIR__.'/../Support/ReceiptFixture.php';
if (($argv[2] ?? '') === 'legacy') {
if (in_array($argv[2] ?? '', ['legacy', 'legacy-estimate'], true)) {
$legacyEstimate = ($argv[2] ?? '') === 'legacy-estimate';
$actor = User::query()->findOrFail((int) ($argv[3] ?? 0));
auth()->guard()->setUser($actor);
try {
app(CommonBudget::class)->for($actor);
throw new RuntimeException('The old runtime must refuse balances with landed-cost effects.');
} catch (HttpExceptionInterface $error) {
if ($error->getStatusCode() !== 503 || (defined(BudgetControl::class.'::LANDED_COSTS_VERSION') && BudgetControl::LANDED_COSTS_VERSION === CommonBudget::LANDED_COSTS_CONTRACT)) {
if ($error->getStatusCode() !== 503 || ($legacyEstimate ? defined(BudgetControl::class.'::IMPORT_ESTIMATE_VERSION')
: (defined(BudgetControl::class.'::LANDED_COSTS_VERSION') && BudgetControl::LANDED_COSTS_VERSION === CommonBudget::LANDED_COSTS_CONTRACT))) {
throw $error;
}
echo json_encode(['old_runtime_rejected_before_balance' => true, 'status' => 503,
echo json_encode(['old_runtime_rejected_before_balance' => true, 'old_estimate_runtime_rejected' => $legacyEstimate, 'status' => 503,
'runtime_landed_version' => defined(BudgetControl::class.'::LANDED_COSTS_VERSION') ? BudgetControl::LANDED_COSTS_VERSION : null], JSON_THROW_ON_ERROR).PHP_EOL;
}
exit;
}
if (($argv[2] ?? '') === 'prepare') {
if (in_array($argv[2] ?? '', ['prepare', 'prepare-estimate', 'prepare-reconcile'], true)) {
$f = receiptFixture();
$finance = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$reviewer = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
@@ -48,11 +51,22 @@ if (($argv[2] ?? '') === 'prepare') {
$money = ['subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000,
'reference_subtotal_minor' => 2000, 'reference_tax_minor' => 0, 'reference_total_minor' => 2000];
// Contract fixture, not a native document upload or statutory customs action.
echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $finance->id, 'budget' => $budget, 'plan' => (string) Str::uuid(),
$prepared = ['tenant' => $f['tenant']->id, 'actor' => $finance->id, 'budget' => $budget, 'plan' => (string) Str::uuid(),
'estimate' => in_array($argv[2] ?? '', ['prepare-estimate', 'prepare-reconcile'], true), 'reconciliation' => ($argv[2] ?? '') === 'prepare-reconcile', 'requisition' => $f['r']->id,
'version' => 1, 'operation' => (string) Str::uuid(),
'documents' => ['customs' => ['kind' => 'customs_assessment', 'id' => 1, 'source_key' => (string) Str::uuid(), 'source_version' => 1,
'creditor_key' => 'synthetic-authority', 'currency' => 'MZN', 'revision' => hash('sha256', 'Synthetic customs source'), ...$money]],
'components' => [['component_key' => 'duty', 'kind' => 'duty', 'origin' => 'customs', ...$money]]], JSON_THROW_ON_ERROR);
'components' => [['component_key' => 'duty', 'kind' => 'duty', 'origin' => 'customs', ...$money]]];
if ($prepared['reconciliation']) {
$components = array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => 'not_applicable', 'basis' => 'Synthetic contention assumption',
'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS);
$components[0] = [...$components[0], 'status' => 'known', 'subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000];
auth()->guard()->setUser($finance);
$estimate = app(CommonBudget::class)->for($finance)->reserveImportEstimate($prepared['plan'], 1, $budget, $f['r']->id,
['subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000], $components, (string) Str::uuid());
$prepared += ['estimate_hash' => $estimate['plan_hash'], 'actual_plan' => (string) Str::uuid(), 'actual_operation' => (string) Str::uuid()];
}
echo json_encode($prepared, JSON_THROW_ON_ERROR);
exit;
}
if (($argv[2] ?? '') === 'write') {
@@ -61,7 +75,19 @@ if (($argv[2] ?? '') === 'write') {
$actor = User::query()->findOrFail($input['actor']);
auth()->guard()->setUser($actor);
try {
$result = app(CommonBudget::class)->for($actor)->reserveLandedCosts($input['plan'], $input['version'], $input['budget'], $input['components'], $input['documents'], $input['operation']);
$engine = app(CommonBudget::class)->for($actor);
if ($input['reconciliation'] ?? false) {
$result = $engine->reconcileImportEstimate($input['plan'], $input['version'], $input['estimate_hash'], 1, 1000,
$input['actual_plan'], 1, $input['budget'], $input['components'], $input['documents'], $input['operation'], $input['actual_operation']);
} elseif ($input['estimate'] ?? false) {
$components = array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => 'not_applicable', 'basis' => 'Synthetic contention assumption',
'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS);
$components[0] = [...$components[0], 'status' => 'known', 'subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000];
$result = $engine->reserveImportEstimate($input['plan'], $input['version'], $input['budget'], $input['requisition'],
['subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000], $components, $input['operation']);
} else {
$result = $engine->reserveLandedCosts($input['plan'], $input['version'], $input['budget'], $input['components'], $input['documents'], $input['operation']);
}
echo json_encode(['status' => 200, 'replayed' => $result['replayed']], JSON_THROW_ON_ERROR);
} catch (BudgetFailure $error) {
echo json_encode(['status' => $error->status], JSON_THROW_ON_ERROR);
@@ -70,12 +96,15 @@ if (($argv[2] ?? '') === 'write') {
}
exit;
}
if (($argv[2] ?? '') !== 'race') {
if (! in_array($argv[2] ?? '', ['race', 'race-estimate', 'race-estimate-reconcile'], true)) {
throw new InvalidArgumentException('Invalid landed-cost worker mode.');
}
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
foreach (['same_operation', 'conflicting_plan_version', 'same_source_different_plan'] as $scenario) {
$prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
$prepareMode = match ($argv[2] ?? '') {
'race-estimate-reconcile' => 'prepare-reconcile', 'race-estimate' => 'prepare-estimate', default => 'prepare'
};
$prepare = new Process([PHP_BINARY, __FILE__, $database, $prepareMode], dirname(__DIR__, 2), timeout: 30);
$prepare->mustRun();
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$workers = [];
@@ -88,7 +117,7 @@ foreach (['same_operation', 'conflicting_plan_version', 'same_source_different_p
if ($index === 1 && $scenario !== 'same_operation') {
$contender['operation'] = (string) Str::uuid();
if ($scenario === 'same_source_different_plan') {
$contender['plan'] = (string) Str::uuid();
$contender[($input['reconciliation'] ?? false) ? 'actual_plan' : 'plan'] = (string) Str::uuid();
} else {
$contender['version'] = 2;
}
@@ -121,13 +150,13 @@ foreach (['same_operation', 'conflicting_plan_version', 'same_source_different_p
$statuses = array_column($results, 'status');
sort($statuses);
$commands = $db->table('budget_landed_commands')->where('tenant_id', $input['tenant'])->count();
$audits = $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', 'budget.landed_reserve')->count();
$audits = $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', ($input['reconciliation'] ?? false) ? 'budget.landed_estimate_reconcile' : (($input['estimate'] ?? false) ? 'budget.landed_estimate_reserve' : 'budget.landed_reserve'))->count();
$reserved = (int) $db->table('budget_landed_entries')->where('tenant_id', $input['tenant'])->sum('reserved_minor');
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $commands !== 1 || $audits !== 1 || $reserved !== 2000
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $commands !== (($input['reconciliation'] ?? false) ? 3 : 1) || $audits !== 1 || $reserved !== (($input['reconciliation'] ?? false) ? 3000 : 2000)
|| ($scenario === 'same_operation' && count(array_filter($results, fn ($result) => $result['replayed'])) !== 1)) {
throw new RuntimeException('Contention must retain exactly one source, budget effect and audit.');
}
echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
echo json_encode(['scenario' => $scenario, 'estimate' => $input['estimate'] ?? false, 'reconciliation' => $input['reconciliation'] ?? false, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
'commands' => $commands, 'audits' => $audits, 'reserved_minor' => $reserved], JSON_THROW_ON_ERROR).PHP_EOL;
if ($scenario === 'same_operation') {
$artifact = json_decode(file_get_contents(base_path('docs/proofs/rq01-distribution-artifact.json')), true, 32, JSON_THROW_ON_ERROR);
@@ -149,6 +178,19 @@ foreach (['same_operation', 'conflicting_plan_version', 'same_source_different_p
throw new RuntimeException('The earlier whole-command runtime must refuse the new per-origin data.');
}
echo $whole->getOutput();
if ($input['estimate'] ?? false) {
$prior = base_path('storage/framework/testing/budget-import-estimate-prior-qa-20261127');
if (hash_file('sha256', $prior.'/src/BudgetControl.php') !== 'd81f8fb172683727c221395224cecf9acb8285ab94e71e914141d41cf9e79efa') {
throw new RuntimeException('Preserve the private prior runtime used for estimate downgrade verification.');
}
$oldEstimate = new Process([PHP_BINARY, __FILE__, $database, 'legacy-estimate', (string) $input['actor']], dirname(__DIR__, 2), ['COMMON_BUDGET_PATH' => $prior], timeout: 30);
$oldEstimate->mustRun();
$receipt = json_decode($oldEstimate->getOutput(), true, 32, JSON_THROW_ON_ERROR);
if (($receipt['old_estimate_runtime_rejected'] ?? false) !== true || ($receipt['runtime_landed_version'] ?? null) !== CommonBudget::LANDED_COSTS_CONTRACT) {
throw new RuntimeException('The prior per-origin runtime must refuse estimate effects before balance access.');
}
echo $oldEstimate->getOutput();
}
}
} finally {
if ($db->transactionLevel() > 0) {
+36 -14
View File
@@ -23,6 +23,7 @@ if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::con
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
require_once __DIR__.'/../Support/BudgetOrderPartsFixture.php';
$amendmentMode = in_array($argv[2] ?? '', ['prepare-amend', 'write-amend', 'race-amend'], true);
if (($argv[2] ?? '') === 'legacy') {
$actor = User::query()->findOrFail((int) ($argv[3] ?? 0));
auth()->guard()->setUser($actor);
@@ -37,7 +38,7 @@ if (($argv[2] ?? '') === 'legacy') {
}
exit;
}
if (($argv[2] ?? '') === 'prepare') {
if (in_array($argv[2] ?? '', ['prepare', 'prepare-amend'], true)) {
$f = receiptFixture();
$source = unissuedOrderPartsSource($f, 10000);
$line = $source->items()->sole();
@@ -52,20 +53,36 @@ if (($argv[2] ?? '') === 'prepare') {
$engine = app(CommonBudget::class)->for($f['issuer']);
$lines = [$line->id => ['subtotal_minor' => 10000, 'total_minor' => 10000, 'required_kind' => 'operating']];
$plan = [['allocation_key' => 'synthetic', 'line_id' => $line->id, 'centre_id' => $f['r']->cost_center_id, 'subtotal_minor' => 10000, 'total_minor' => 10000]];
if ($amendmentMode) {
$plan = [[...$plan[0], 'allocation_key' => 'a', 'subtotal_minor' => 5000, 'total_minor' => 5000],
[...$plan[0], 'allocation_key' => 'b', 'subtotal_minor' => 5000, 'total_minor' => 5000]];
}
$engine->recordDistribution($source->id, 'reserve', $plan, $lines, str_repeat('a', 64), (string) Str::uuid());
$award = $engine->recordDistribution($source->id, 'award', $plan, $lines, str_repeat('b', 64), (string) Str::uuid());
echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $f['issuer']->id, 'budget' => $budget, 'source' => $award['distribution_id'],
$input = ['tenant' => $f['tenant']->id, 'actor' => $f['issuer']->id, 'budget' => $budget, 'source' => $award['distribution_id'],
'order' => (string) Str::uuid(), 'operation' => (string) Str::uuid(), 'sources' => [['origin' => $source->id, 'version' => 0,
'plan_hash' => $award['plan_hash'], 'allocations' => [['allocation_key' => 'synthetic', 'subtotal_minor' => 4000, 'total_minor' => 4000]]]]], JSON_THROW_ON_ERROR);
'plan_hash' => $award['plan_hash'], 'allocations' => [['allocation_key' => 'synthetic', 'subtotal_minor' => 4000, 'total_minor' => 4000]]]]];
if ($amendmentMode) {
$input['sources'][0]['allocations'] = [['allocation_key' => 'a', 'subtotal_minor' => 2000, 'total_minor' => 2000],
['allocation_key' => 'b', 'subtotal_minor' => 2000, 'total_minor' => 2000]];
$engine->commitOrderParts($input['order'], $input['sources'], (string) Str::uuid());
$input['actor'] = $finance->id;
$input['sources'][0]['version'] = 1;
$input['sources'][0]['allocations'][0]['subtotal_minor'] = $input['sources'][0]['allocations'][0]['total_minor'] = 1000;
$input['sources'][0]['allocations'][1]['subtotal_minor'] = $input['sources'][0]['allocations'][1]['total_minor'] = 3000;
}
echo json_encode($input, JSON_THROW_ON_ERROR);
exit;
}
if (($argv[2] ?? '') === 'write') {
if (in_array($argv[2] ?? '', ['write', 'write-amend'], true)) {
$input = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR);
DB::select('select set_config(?, ?, false)', ['application_name', 'sgc_order_parts_write_'.getmypid()]);
$actor = User::query()->findOrFail($input['actor']);
auth()->guard()->setUser($actor);
try {
$result = app(CommonBudget::class)->for($actor)->commitOrderParts($input['order'], $input['sources'], $input['operation']);
$engine = app(CommonBudget::class)->for($actor);
$result = $amendmentMode ? $engine->amendOrderParts($input['order'], $input['sources'], 'Explicit synthetic concurrent Finance amendment.', $input['operation'])
: $engine->commitOrderParts($input['order'], $input['sources'], $input['operation']);
echo json_encode(['status' => 200, 'replayed' => $result['replayed']], JSON_THROW_ON_ERROR);
} catch (BudgetFailure $error) {
echo json_encode(['status' => $error->status], JSON_THROW_ON_ERROR);
@@ -74,13 +91,13 @@ if (($argv[2] ?? '') === 'write') {
}
exit;
}
if (($argv[2] ?? '') !== 'race') {
if (! in_array($argv[2] ?? '', ['race', 'race-amend'], true)) {
throw new InvalidArgumentException('Invalid order-part worker mode.');
}
budgetDistributionFixtureSchema();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
foreach (['same_operation', 'conflicting_version'] as $scenario) {
$prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
$prepare = new Process([PHP_BINARY, __FILE__, $database, $amendmentMode ? 'prepare-amend' : 'prepare'], dirname(__DIR__, 2), timeout: 30);
$prepare->mustRun();
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$workers = [];
@@ -91,11 +108,16 @@ foreach (['same_operation', 'conflicting_version'] as $scenario) {
for ($index = 0; $index < 2; $index++) {
if ($index === 1 && $scenario === 'conflicting_version') {
$input['operation'] = (string) Str::uuid();
$input['order'] = (string) Str::uuid();
$input['sources'][0]['allocations'][0]['subtotal_minor'] = 6000;
$input['sources'][0]['allocations'][0]['total_minor'] = 6000;
if ($amendmentMode) {
$input['sources'][0]['allocations'][0]['subtotal_minor'] = $input['sources'][0]['allocations'][0]['total_minor'] = 1500;
$input['sources'][0]['allocations'][1]['subtotal_minor'] = $input['sources'][0]['allocations'][1]['total_minor'] = 2500;
} else {
$input['order'] = (string) Str::uuid();
$input['sources'][0]['allocations'][0]['subtotal_minor'] = 6000;
$input['sources'][0]['allocations'][0]['total_minor'] = 6000;
}
}
$worker = new Process([PHP_BINARY, __FILE__, $database, 'write', json_encode($input, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30);
$worker = new Process([PHP_BINARY, __FILE__, $database, $amendmentMode ? 'write-amend' : 'write', json_encode($input, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30);
$workers[] = $worker;
$worker->start();
}
@@ -125,14 +147,14 @@ foreach (['same_operation', 'conflicting_version'] as $scenario) {
$entries = $db->table('budget_distribution_entries')->where('distribution_id', $input['source']);
$reserved = (int) (clone $entries)->sum('reserved_minor');
$committed = (int) (clone $entries)->sum('committed_minor');
$commands = $db->table('budget_order_commands')->where('tenant_id', $input['tenant'])->count();
$audits = $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', 'budget.orders_committed')->count();
$commands = $db->table('budget_order_commands')->where('tenant_id', $input['tenant'])->where('kind', $amendmentMode ? 'amend' : 'commit')->count();
$audits = $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', $amendmentMode ? 'budget.order_parts_amended' : 'budget.orders_committed')->count();
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $commands !== 1 || $audits !== 1
|| $reserved + $committed !== 10000 || ! in_array($committed, [4000, 6000], true)
|| ($scenario === 'same_operation' && count(array_filter($results, fn ($result) => $result['replayed'])) !== 1)) {
throw new RuntimeException('Contention did not preserve one command, one audit and the exact original budget.');
}
echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
echo json_encode(['scenario' => $scenario, 'amendment' => $amendmentMode, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
'commands' => $commands, 'audits' => $audits, 'reserved_minor' => $reserved, 'committed_minor' => $committed], JSON_THROW_ON_ERROR).PHP_EOL;
if ($scenario === 'same_operation') {
$proof = json_decode(file_get_contents(base_path('docs/proofs/rq01-distribution-artifact.json')), true, 32, JSON_THROW_ON_ERROR);
+153
View File
@@ -0,0 +1,153 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Supplier;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\ImportDossier;
use App\Services\ImportEvidence;
use App\Services\ImportParties;
use App\Services\SupplyPlanning;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\Process\Process;
require __DIR__.'/../../vendor/autoload.php';
$database = $argv[1] ?? '';
$app = require __DIR__.'/../../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
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)) {
throw new LogicException('Dossier contention requires disposable local PostgreSQL QA.');
}
config(['import-dossier.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';
$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)) {
$f = receiptFixture();
supplyGrant($f['issuer'], ['procurement', 'import_prepare']);
auth()->guard()->setUser($f['issuer']);
$import = app(SupplyPlanning::class)->save($f['issuer'], 'import', supplyInput(['purchase_order_id' => $f['order']->id,
'purpose' => 'internal', 'jurisdiction' => 'Synthetic contention jurisdiction', 'origin_country' => 'Synthetic A',
'dispatch_country' => 'Synthetic B', 'regime' => 'Synthetic documentary regime']));
$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) {
$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);
$instructions = app(ImportDossier::class)->record($actor, $import, [...$data, 'type' => 'written_instructions'], $file());
$supplier = Supplier::query()->whereKey($f['order']->supplier_id)->firstOrFail()->replicate();
$supplier->name = 'Synthetic concurrent broker';
$supplier->nuit = '987654321';
$supplier->save();
$data = ['operation_key' => (string) Str::uuid(), 'role' => 'broker', 'version' => 0, 'supplier_id' => $supplier->id,
'supplier_version' => $supplier->version, 'instruction_document_id' => $instructions->id, 'no_conflict' => true,
'reason' => 'Explicit synthetic concurrent independent buyer selection.'];
if (($argv[3] ?? '') === 'same_version') {
app(ImportParties::class)->select($actor, $import, $data);
$data = [...$data, 'operation_key' => (string) Str::uuid(), 'version' => 1, 'role' => 'broker'];
}
} elseif (($argv[3] ?? '') === 'same_version') {
$old = app(ImportDossier::class)->record($f['issuer'], $import, $data, $file());
$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,
'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)) {
$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());
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)) {
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);
$prepare->mustRun();
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$db = DB::connection();
$workers = [];
$db->beginTransaction();
try {
$db->table('tenants')->where('id', $input['tenant'])->lockForUpdate()->firstOrFail();
for ($index = 0; $index < 2; $index++) {
$workerInput = $input;
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);
$workers[] = $worker;
$worker->start();
}
$deadline = microtime(true) + 10;
do {
$db->select('select pg_stat_clear_snapshot()');
$blocked = (int) $db->selectOne("select count(*) as n from pg_stat_activity where datname=? and application_name like 'sgc_dossier_write_%' and wait_event_type='Lock'", [$database])->n;
if ($blocked >= 2) {
break;
}
usleep(50000);
} while (microtime(true) < $deadline);
if ($blocked < 2) {
throw new RuntimeException('Both dossier writers must demonstrably wait on the company lock.');
}
$db->commit();
$results = [];
foreach ($workers as $worker) {
$worker->wait();
if (! $worker->isSuccessful()) {
throw new RuntimeException($worker->getErrorOutput());
}
$results[] = json_decode($worker->getOutput(), true, 32, JSON_THROW_ON_ERROR);
}
$statuses = array_column($results, 'status');
sort($statuses);
$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)) {
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) {
app(ImportEvidence::class)->bytes($record);
}
echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
'documents_created' => $records, 'audits' => $audits, 'files_created' => $files, 'all_originals_verified' => true], JSON_THROW_ON_ERROR).PHP_EOL;
} finally {
if ($db->transactionLevel() > 0) {
$db->rollBack();
}
foreach ($workers as $worker) {
if ($worker->isRunning()) {
$worker->stop();
}
}
}
}
@@ -10,6 +10,7 @@ use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tempo\Finance\Budget\BudgetControl;
use Tempo\Finance\Budget\BudgetFailure;
use Tempo\Finance\Budget\BudgetImportEstimate;
require_once __DIR__.'/../Support/ReceiptFixture.php';
@@ -58,6 +59,75 @@ test('landed reserve commit and consume affect only the additional native origin
->and(DB::table('invoices')->count())->toBe(0)->and(DB::table('budget_consumptions')->count())->toBe(0);
});
test('pre-document assumptions reserve only extras and reconcile atomically into actual origins without an invented principal', function () {
$components = array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => 'not_applicable', 'basis' => 'Pressuposto sintético explícito',
'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS);
$components[0] = [...$components[0], 'status' => 'known', 'subtotal_minor' => 1000, 'tax_minor' => 160, 'total_minor' => 1160];
$goods = ['subtotal_minor' => 10000, 'tax_minor' => 1600, 'total_minor' => 11600];
$operation = (string) Str::uuid();
$beforePrincipal = DB::table('invoices')->count();
$reserved = $this->engine->reserveImportEstimate($this->key, 1, $this->budget, $this->f['r']->id, $goods, $components, $operation);
expect($reserved['additional_amount_minor'])->toBe(1160)->and($reserved['total_reference_minor'])->toBe(12760)
->and($this->engine->balance($this->budget)['reserved_minor'])->toBe(1160)
->and($this->engine->reserveImportEstimate($this->key, 1, $this->budget, $this->f['r']->id, $goods, $components, $operation)['replayed'])->toBeTrue();
expect(fn () => $this->engine->reserveImportEstimate((string) Str::uuid(), 1, $this->budget, $this->f['r']->id, $goods, $components, (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect(fn () => $this->engine->reconcileImportEstimate($this->key, 1, $reserved['plan_hash'], 1, 1000,
(string) Str::uuid(), 1, $this->budget, $this->components, $this->documents, (string) Str::uuid(), $operation))->toThrow(BudgetFailure::class);
expect($this->engine->balance($this->budget)['reserved_minor'])->toBe(1160);
$this->engine->transitionLandedCosts($this->key, 1, $reserved['plan_hash'], 'commit', (string) Str::uuid());
expect(fn () => $this->engine->transitionLandedCosts($this->key, 1, $reserved['plan_hash'], 'consume', (string) Str::uuid()))->toThrow(BudgetFailure::class);
$actual = $this->engine->amendLandedCosts($this->key, 1, $reserved['plan_hash'], 2, $this->components, $this->documents, (string) Str::uuid());
expect($actual['additional_amount_minor'])->toBe(2000)->and($this->engine->balance($this->budget)['reserved_minor'])->toBe(2000)
->and($this->engine->balance($this->budget)['committed_minor'])->toBe(0)
->and(DB::table('invoices')->count())->toBe($beforePrincipal);
});
test('partial estimate reconciliation preserves its unallocated remainder and actual costs once with atomic failure', function () {
$components = array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => 'not_applicable', 'basis' => 'Pressuposto sintético explícito',
'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS);
$components[0] = [...$components[0], 'status' => 'known', 'subtotal_minor' => 3000, 'tax_minor' => 0, 'total_minor' => 3000];
$reserved = $this->engine->reserveImportEstimate($this->key, 1, $this->budget, $this->f['r']->id,
['subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000], $components, (string) Str::uuid());
$actualKey = (string) Str::uuid();
$operation = (string) Str::uuid();
$actualOperation = (string) Str::uuid();
$apply = fn () => $this->engine->reconcileImportEstimate($this->key, 1, $reserved['plan_hash'], 1, 1000,
$actualKey, 1, $this->budget, $this->components, $this->documents, $operation, $actualOperation);
$result = $apply();
expect($result['additional_amount_minor'])->toBe(2000)->and($result['estimate_reconciliation']['reserved_minor'])->toBe(2000)
->and($this->engine->balance($this->budget)['reserved_minor'])->toBe(4000)
->and($apply()['replayed'])->toBeTrue()->and(DB::table('budget_landed_commands')->count())->toBe(3);
$before = DB::table('budget_landed_entries')->orderBy('id')->get()->toJson();
expect(fn () => $this->engine->reconcileImportEstimate($this->key, 1, $reserved['plan_hash'], 2, 1000,
(string) Str::uuid(), 1, $this->budget, $this->components, $this->documents, (string) Str::uuid(), (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect(DB::table('budget_landed_entries')->orderBy('id')->get()->toJson())->toBe($before)
->and(DB::table('budget_landed_commands')->count())->toBe(3);
});
test('multiple approved-origin estimates reconcile to the same native invoice plan without another principal or repeated actual cost', function () {
$components = array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => 'not_applicable', 'basis' => 'Pressuposto sintético explícito',
'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS);
$components[0] = [...$components[0], 'status' => 'known', 'subtotal_minor' => 3000, 'tax_minor' => 0, 'total_minor' => 3000];
$goods = ['subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000];
$first = $this->engine->reserveImportEstimate($this->key, 1, $this->budget, $this->f['r']->id, $goods, $components, (string) Str::uuid());
$request = $this->f['r']->replicate();
$request->number = 'SECOND-ESTIMATE-'.Str::random(10);
$request->save();
$secondKey = (string) Str::uuid();
$second = $this->engine->reserveImportEstimate($secondKey, 1, $this->budget, $request->id, $goods, $components, (string) Str::uuid());
$documents = array_diff_key($this->documents, ['source-2' => true]);
$actualComponents = array_values(array_filter($this->components, fn ($row) => $row['kind'] !== 'duty'));
$actualKey = (string) Str::uuid();
$this->engine->reconcileImportEstimate($this->key, 1, $first['plan_hash'], 1, 1000, $actualKey, 1, $this->budget,
$actualComponents, $documents, (string) Str::uuid(), (string) Str::uuid());
$result = $this->engine->reconcileImportEstimate($secondKey, 1, $second['plan_hash'], 1, 2000, $actualKey, 1, $this->budget,
$actualComponents, $documents, (string) Str::uuid(), (string) Str::uuid());
expect($result['additional_amount_minor'])->toBe(0)->and($result['origins'])->toBe([])
->and($this->engine->balance($this->budget)['reserved_minor'])->toBe(3000)
->and($this->engine->landedCostState($actualKey)['result']['revision'])->toBe(2)
->and(DB::table('invoices')->count())->toBe(0)->and(DB::table('budget_consumptions')->count())->toBe(0);
});
test('landed operation mismatch stale versions and repeated transition fail without changing the balance', function () {
$operation = (string) Str::uuid();
$reserved = $this->engine->reserveLandedCosts($this->key, 2, $this->budget, $this->components, $this->documents, $operation);
@@ -1,6 +1,7 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\CostCenter;
use App\Models\Invoice;
use App\Models\PurchaseOrder;
use App\Models\Requisition;
@@ -76,6 +77,132 @@ function orderPartsBalance(object $test): array
return $balance;
}
function amendableOrderPartsSource(object $test): array
{
$centre = CostCenter::query()->create(['tenant_id' => $test->finance->tenant_id, 'department_id' => $test->f['department']->id,
'code' => 'PART-AMEND-'.Str::random(8), 'name' => 'Synthetic amendment centre']);
$test->actingAs($test->finance);
$test->secondBudget = app(CommonBudget::class)->for($test->finance)->create(['cost_center_id' => $centre->id,
'year' => (int) now()->year, 'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000,
'reason' => 'Synthetic second-centre amendment capacity.']);
$test->actingAs($test->reviewer);
app(CommonBudget::class)->for($test->reviewer)->approve($test->secondBudget);
$test->actingAs($test->f['issuer']);
$request = unissuedOrderPartsSource($test->f, 10000);
$line = $request->items()->sole();
$lines = [$line->id => ['subtotal_minor' => 10000, 'total_minor' => 10000, 'required_kind' => 'operating']];
$allocations = [
['allocation_key' => 'a', 'line_id' => $line->id, 'centre_id' => $request->cost_center_id, 'subtotal_minor' => 5000, 'total_minor' => 5000],
['allocation_key' => 'b', 'line_id' => $line->id, 'centre_id' => $centre->id, 'subtotal_minor' => 5000, 'total_minor' => 5000],
];
$engine = app(CommonBudget::class)->for($test->f['issuer']);
$engine->recordDistribution($request->id, 'reserve', $allocations, $lines, str_repeat('a', 64), (string) Str::uuid());
$result = $engine->recordDistribution($request->id, 'award', $allocations, $lines, str_repeat('b', 64), (string) Str::uuid());
return ['origin' => $request->id, 'version' => 0, 'plan_hash' => $result['plan_hash'],
'allocations' => [['allocation_key' => 'a', 'subtotal_minor' => 2000, 'total_minor' => 2000],
['allocation_key' => 'b', 'subtotal_minor' => 2000, 'total_minor' => 2000]]];
}
test('explicit Finance order amendment preserves unissued reserve original documents and replay', function () {
$source = amendableOrderPartsSource($this);
$order = (string) Str::uuid();
app(CommonBudget::class)->for($this->f['issuer'])->commitOrderParts($order, [$source], (string) Str::uuid());
$this->actingAs($this->finance);
$engine = app(CommonBudget::class)->for($this->finance);
$original = DB::table('budget_order_commands')->where('kind', 'commit')->first()->snapshot;
$source['version'] = 1;
$source['allocations'][0]['subtotal_minor'] = $source['allocations'][0]['total_minor'] = 1000;
$source['allocations'][1]['subtotal_minor'] = $source['allocations'][1]['total_minor'] = 3000;
$operation = (string) Str::uuid();
expect($engine->amendOrderParts($order, [$source], 'Explicit synthetic Finance reallocation.', $operation)['replayed'])->toBeFalse()
->and($engine->amendOrderParts($order, [$source], 'Explicit synthetic Finance reallocation.', $operation)['replayed'])->toBeTrue()
->and(DB::table('budget_order_commands')->where('kind', 'commit')->first()->snapshot)->toBe($original)
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(6000)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(4000)
->and($engine->balance($this->budget)['committed_minor'])->toBe(1000)
->and($engine->balance($this->secondBudget)['committed_minor'])->toBe(3000);
expect(fn () => $engine->amendOrderParts($order, [$source], 'Stale independent synthetic amendment.', (string) Str::uuid()))->toThrow(BudgetFailure::class);
$distribution = DB::table('budget_distributions')->where('requisition_id', $source['origin'])->first();
$source['version'] = 2;
$source['plan_hash'] = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR)['plan_hash'];
$engine->cancelOrderParts($order, [$source], (string) Str::uuid());
expect((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(0)
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(6000);
});
test('Finance amendment respects consumed floors authorisation atomicity and revised invoice capacity', function () {
$source = amendableOrderPartsSource($this);
$order = (string) Str::uuid();
$issuer = app(CommonBudget::class)->for($this->f['issuer']);
$issuer->commitOrderParts($order, [$source], (string) Str::uuid());
$source['version'] = 1;
$amended = $source;
$amended['allocations'][0]['subtotal_minor'] = $amended['allocations'][0]['total_minor'] = 1000;
$amended['allocations'][1]['subtotal_minor'] = $amended['allocations'][1]['total_minor'] = 3000;
expect(fn () => $issuer->amendOrderParts($order, [$amended], 'Procurement cannot amend Finance allocations.', (string) Str::uuid()))->toThrow(HttpException::class);
$this->actingAs($this->finance);
$engine = app(CommonBudget::class)->for($this->finance);
$invoice = orderPartsInvoice($this, 1500);
$consumption = $source;
$consumption['allocations'] = [['order_key' => $order, 'allocation_key' => 'a', 'subtotal_minor' => 1500, 'total_minor' => 1500]];
$engine->consumeOrderParts($invoice->id, [$consumption], (string) Str::uuid());
$amended['version'] = 2;
$before = [DB::table('budget_distribution_entries')->get()->toArray(), DB::table('budget_order_commands')->count()];
expect(fn () => $engine->amendOrderParts($order, [$amended], 'Cannot reduce the amount already consumed.', (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect([DB::table('budget_distribution_entries')->get()->toArray(), DB::table('budget_order_commands')->count()])->toEqual($before);
$amended['allocations'][0]['subtotal_minor'] = $amended['allocations'][0]['total_minor'] = 1500;
$amended['allocations'][1]['subtotal_minor'] = $amended['allocations'][1]['total_minor'] = 2500;
$engine->amendOrderParts($order, [$amended], 'Explicit amendment preserves the consumed floor.', (string) Str::uuid());
$distribution = DB::table('budget_distributions')->where('requisition_id', $source['origin'])->first();
$consumption = ['origin' => $source['origin'], 'version' => 3,
'plan_hash' => json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR)['plan_hash'],
'allocations' => [['order_key' => $order, 'allocation_key' => 'b', 'subtotal_minor' => 2500, 'total_minor' => 2500]]];
$engine->consumeOrderParts(orderPartsInvoice($this, 2500)->id, [$consumption], (string) Str::uuid());
expect((int) DB::table('budget_order_consumptions')->sum('amount_minor'))->toBe(4000)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(0)
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(6000);
});
test('one invalid origin rejects an entire consolidated Finance amendment without partial effects', function () {
$a = amendableOrderPartsSource($this);
$b = amendableOrderPartsSource($this);
$order = (string) Str::uuid();
app(CommonBudget::class)->for($this->f['issuer'])->commitOrderParts($order, [$a, $b], (string) Str::uuid());
$this->actingAs($this->finance);
$a['version'] = $b['version'] = 1;
$a['allocations'][0]['subtotal_minor'] = $a['allocations'][0]['total_minor'] = 1000;
$a['allocations'][1]['subtotal_minor'] = $a['allocations'][1]['total_minor'] = 3000;
$b['allocations'][1]['subtotal_minor'] = $b['allocations'][1]['total_minor'] = 3000;
$before = [DB::table('budget_distributions')->get()->toArray(), DB::table('budget_order_allocations')->get()->toArray(),
DB::table('budget_order_commands')->count(), DB::table('budget_distribution_entries')->get()->toArray()];
expect(fn () => app(CommonBudget::class)->for($this->finance)->amendOrderParts($order, [$a, $b],
'Second origin cannot change its original line totals.', (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect([DB::table('budget_distributions')->get()->toArray(), DB::table('budget_order_allocations')->get()->toArray(),
DB::table('budget_order_commands')->count(), DB::table('budget_distribution_entries')->get()->toArray()])->toEqual($before);
});
test('Finance amendment cannot transfer commitment into a centre with no available budget', function () {
$source = amendableOrderPartsSource($this);
$centre = DB::table('budgets')->where('id', $this->secondBudget)->value('cost_center_id');
$other = unissuedOrderPartsSource($this->f, 95000);
$line = $other->items()->sole();
$engine = app(CommonBudget::class)->for($this->f['issuer']);
$engine->recordDistribution($other->id, 'reserve', [['allocation_key' => 'other', 'line_id' => $line->id, 'centre_id' => $centre,
'subtotal_minor' => 95000, 'total_minor' => 95000]], [$line->id => ['subtotal_minor' => 95000, 'total_minor' => 95000, 'required_kind' => 'operating']],
str_repeat('c', 64), (string) Str::uuid());
$order = (string) Str::uuid();
$engine->commitOrderParts($order, [$source], (string) Str::uuid());
$this->actingAs($this->finance);
$source['version'] = 1;
$source['allocations'][0]['subtotal_minor'] = $source['allocations'][0]['total_minor'] = 1000;
$source['allocations'][1]['subtotal_minor'] = $source['allocations'][1]['total_minor'] = 3000;
expect(fn () => app(CommonBudget::class)->for($this->finance)->amendOrderParts($order, [$source],
'Insufficient destination capacity must reject this amendment.', (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect(DB::table('budget_order_commands')->where('kind', 'amend')->count())->toBe(0)
->and((int) DB::table('budget_distribution_entries')->where('kind', 'like', 'order-amend-%')->count())->toBe(0);
});
test('one approved synthetic source commits forty then sixty without committing the unissued portion', function () {
$source = orderPartsSource($this, 10000);
$order = (string) Str::uuid();
+239
View File
@@ -0,0 +1,239 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\ConflictDeclaration;
use App\Models\Supplier;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\ImportCostDocumentHealth;
use App\Services\ImportDossier;
use App\Services\ImportEvidence;
use App\Services\ImportParties;
use App\Services\RequisitionWorkflow;
use App\Services\SupplyPlanning;
use Illuminate\Database\QueryException;
use Illuminate\Filesystem\FilesystemAdapter;
use Illuminate\Http\UploadedFile;
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/ImportQaIdentity.php';
beforeEach(function () {
config(['import-dossier.qa_enabled' => true]);
Storage::fake('local');
$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 dossier jurisdiction',
'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Synthetic documentary regime',
]));
$this->input = ['operation_key' => (string) Str::uuid(), 'type' => 'packing_list', 'reference' => 'PACK-QA-1',
'issuer_reference' => 'Synthetic supplier', 'issued_on' => today()->toDateString(), 'notes' => 'Synthetic private original.',
'reason' => 'Retain the original synthetic packing list.'];
$this->bytes = "%PDF-1.4\nSynthetic packing list only\n%%EOF";
$this->file = UploadedFile::fake()->createWithContent('packing.pdf', $this->bytes);
});
test('typed import dossier retains originals corrections and replay without financial stock or customs effects', function () {
$service = app(ImportDossier::class);
$before = [DB::table('stock_movements')->count(), DB::table('invoices')->count(), DB::table('budget_entries')->get()->toArray(), $this->import->toArray()];
$first = $service->record($this->f['issuer'], $this->import, $this->input, $this->file);
expect($service->record($this->f['issuer'], $this->import, $this->input, $this->file)->id)->toBe($first->id)
->and($first->version)->toBe(1)->and($first->snapshot['financial_effects'])->toBeFalse()
->and($first->snapshot['external_submission'])->toBeFalse();
$correction = $service->record($this->f['issuer'], $this->import, [...$this->input, 'operation_key' => (string) Str::uuid(),
'record_key' => $first->record_key, 'version' => 1, 'reference' => 'PACK-QA-1-CORRECTED'],
UploadedFile::fake()->createWithContent('corrected.pdf', "%PDF-1.4\nSynthetic corrected packing list\n%%EOF"));
expect($correction->version)->toBe(2)->and($correction->snapshot['supersedes'])->toBe($first->id)
->and(app(ImportEvidence::class)->bytes($first))->toBe($this->bytes)
->and($service->record($this->f['issuer'], $this->import, $this->input, $this->file)->id)->toBe($first->id)
->and([DB::table('stock_movements')->count(), DB::table('invoices')->count(), DB::table('budget_entries')->get()->toArray(), $this->import->fresh()->toArray()])->toEqual($before);
$workspace = $service->workspace($this->f['issuer'], $this->import);
expect($workspace['documents']->items()[0]['current'])->toBeTrue()
->and($workspace['documents']->items()[1]['current'])->toBeFalse()
->and(json_encode($workspace, JSON_THROW_ON_ERROR))->not->toContain('import-dossier/'.$first->tenant_id.'/');
expect(fn () => $service->record($this->f['issuer'], $this->import, [...$this->input, 'operation_key' => (string) Str::uuid(),
'record_key' => $first->record_key, 'version' => 1], $this->file))->toThrow(HttpException::class);
expect(fn () => DB::transaction(fn () => DB::table('supply_records')->where('id', $first->id)->update(['state' => 'approved'])))->toThrow(QueryException::class);
});
test('typed dossier refuses duplicate identities type changes and storage changes', function () {
$service = app(ImportDossier::class);
$record = $service->record($this->f['issuer'], $this->import, $this->input, $this->file);
expect(fn () => $service->record($this->f['issuer'], $this->import, [...$this->input, 'operation_key' => (string) Str::uuid()], $this->file))->toThrow(HttpException::class);
expect(fn () => $service->record($this->f['issuer'], $this->import, [...$this->input, 'operation_key' => (string) Str::uuid(),
'record_key' => $record->record_key, 'version' => 1, 'type' => 'payment_evidence'], $this->file))->toThrow(HttpException::class);
$this->withoutVite();
$response = $this->get('/compras/importacoes/'.$this->import->id.'/documentos/'.$record->id)->assertOk()
->assertHeader('X-Content-Type-Options', 'nosniff');
expect($response->getContent())->toBe($this->bytes);
Storage::disk('local')->put($record->snapshot['evidence']['path'], str_repeat('X', strlen($this->bytes)));
expect($response->getContent())->toBe($this->bytes);
$this->get('/compras/importacoes/'.$this->import->id.'/documentos/'.$record->id)->assertConflict();
expect(SupplyRecord::query()->where('kind', 'import_document')->count())->toBe(1);
});
test('dossier read and write use current roles tenant isolation and the disabled capability guard', function () {
$service = app(ImportDossier::class);
$record = $service->record($this->f['issuer'], $this->import, $this->input, $this->file);
$finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
supplyGrant($finance, ['finance']);
$this->actingAs($finance);
expect($service->workspace($finance, $this->import)['canWrite'])->toBeFalse();
expect(fn () => $service->record($finance, $this->import, [...$this->input, 'operation_key' => (string) Str::uuid()], $this->file))->toThrow(HttpException::class);
$this->withoutVite();
$url = '/compras/importacoes/'.$this->import->id.'/documentos';
$this->get($url)->assertOk()->assertViewHas('page', fn ($page) => $page['component'] === 'supply/import-dossier' && $page['encryptHistory'] === true && $page['props']['canWrite'] === false);
$other = receiptFixture();
supplyGrant($other['issuer'], ['procurement', 'import_prepare']);
$this->actingAs($other['issuer'])->get($url.'/'.$record->id)->assertNotFound();
$this->actingAs($this->f['issuer']);
DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->update(['maintenance' => true, 'expires_at' => now()->addHour()]);
$this->get($url)->assertForbidden();
config(['import-dossier.qa_enabled' => false]);
expect($service->ready())->toBeFalse();
$this->get($url)->assertServiceUnavailable();
});
test('failed dossier audit removes only the new unconfirmed private file and preserves existing versions', function () {
$service = app(ImportDossier::class);
$record = $service->record($this->f['issuer'], $this->import, $this->input, $this->file);
$before = Storage::disk('local')->allFiles();
$this->mock(RequisitionWorkflow::class)->shouldReceive('audit')->andThrow(new RuntimeException('Synthetic audit failure'));
expect(fn () => $service->record($this->f['issuer'], $this->import, [...$this->input, 'operation_key' => (string) Str::uuid(),
'record_key' => $record->record_key, 'version' => 1], UploadedFile::fake()->createWithContent('next.pdf', "%PDF-1.4\nUnconfirmed QA version\n%%EOF")))->toThrow(RuntimeException::class);
expect(Storage::disk('local')->allFiles())->toEqual($before)
->and(app(ImportEvidence::class)->bytes($record))->toBe($this->bytes)
->and(SupplyRecord::query()->where('kind', 'import_document')->count())->toBe(1);
});
test('aggregate import inspection includes typed dossier originals without exposing or repairing them', function () {
$record = app(ImportDossier::class)->record($this->f['issuer'], $this->import, $this->input, $this->file);
$path = $record->snapshot['evidence']['path'];
auth()->logout();
$health = app(ImportCostDocumentHealth::class);
expect($health->inspect()['ok'])->toBeTrue();
Storage::disk('local')->put($path, str_repeat('Y', strlen($this->bytes)));
Storage::disk('local')->put('import-dossier/orphan.pdf', 'Synthetic unreferenced file.');
$result = $health->inspect();
expect($result['altered'])->toBe(1)->and($result['unreferenced'])->toBe(1)
->and(json_encode($result, JSON_THROW_ON_ERROR))->not->toContain($path, $this->input['reference']);
Storage::disk('local')->assertExists($path);
});
test('dossier rejects unsupported empty or oversized originals before storing any record', function () {
foreach ([UploadedFile::fake()->createWithContent('script.txt', 'Not an accepted original.'),
UploadedFile::fake()->create('oversized.pdf', 2049, 'application/pdf'),
UploadedFile::fake()->createWithContent('empty.pdf', '')] as $file) {
$this->postJson('/compras/importacoes/'.$this->import->id.'/documentos', [...$this->input, 'file' => $file])->assertUnprocessable();
}
expect(SupplyRecord::query()->where('kind', 'import_document')->count())->toBe(0)
->and(Storage::disk('local')->allFiles())->toBe([]);
});
function importDossierPartyFixture(object $test): array
{
$buyer = User::factory()->create(['tenant_id' => $test->f['tenant']->id, 'department_id' => $test->f['department']->id,
'purchasing_role' => PurchasingRole::Procurement]);
supplyGrant($buyer, ['procurement', 'import_prepare']);
$test->actingAs($buyer);
$supplier = Supplier::query()->whereKey($test->f['order']->supplier_id)->firstOrFail()->replicate();
$supplier->name = 'Despachante exclusivamente sintético';
$supplier->nuit = '987654321';
$supplier->save();
$instructions = app(ImportDossier::class)->record($buyer, $test->import, [...$test->input, 'operation_key' => (string) Str::uuid(),
'type' => 'written_instructions', 'reference' => 'INSTRUCTIONS-QA'], $test->file);
$data = ['operation_key' => (string) Str::uuid(), 'role' => 'broker', 'version' => 0, 'supplier_id' => $supplier->id,
'supplier_version' => $supplier->version, 'instruction_document_id' => $instructions->id,
'reason' => 'Explicit synthetic independent buyer selection.', 'no_conflict' => true];
return [$buyer, $supplier, $instructions, $data];
}
test('broker selection reuses eligible entity and current written instructions preserving history and requester segregation', function () {
[$buyer, $supplier, $instructions, $data] = importDossierPartyFixture($this);
$service = app(ImportParties::class);
$this->actingAs($this->f['issuer']);
expect($service->canSelect($this->f['issuer'], $this->f['order']))->toBeFalse();
expect(fn () => $service->select($this->f['issuer'], $this->import, $data))->toThrow(HttpException::class);
$this->actingAs($buyer);
expect($service->workspace($buyer, $this->import, 'despachante')['suppliers']->pluck('id')->all())->toContain($supplier->id);
$record = $service->select($buyer, $this->import, $data);
expect($record->snapshot['supplier']['id'])->toBe($supplier->id)
->and($record->data['instruction_document_id'])->toBe($instructions->id)
->and($record->snapshot['no_conflict'])->toBeTrue()
->and($service->select($buyer, $this->import, $data)->id)->toBe($record->id);
$this->withoutVite();
$this->get('/compras/importacoes/'.$this->import->id.'/documentos')->assertOk()
->assertViewHas('page', fn ($page) => $page['props']['parties']['canSelect'] === true);
$this->post('/compras/importacoes/'.$this->import->id.'/intervenientes', $data)
->assertRedirect('/compras/importacoes/'.$this->import->id.'/documentos');
$correction = app(ImportDossier::class)->record($buyer, $this->import, [...$this->input, 'operation_key' => (string) Str::uuid(),
'record_key' => $instructions->record_key, 'version' => 1, 'type' => 'written_instructions', 'reference' => 'INSTRUCTIONS-QA-2'],
UploadedFile::fake()->createWithContent('instructions.pdf', "%PDF-1.4\nNew synthetic instructions\n%%EOF"));
$transit = supplyInput(['event_date' => today()->toDateString(), 'evidence' => 'Synthetic transit evidence.'], 'transit', $this->import);
expect(fn () => app(SupplyPlanning::class)->save($buyer, 'import', $transit))->toThrow(HttpException::class);
$next = $service->select($buyer, $this->import, [...$data, 'operation_key' => (string) Str::uuid(), 'version' => 1,
'instruction_document_id' => $correction->id]);
expect($next->version)->toBe(2)->and($next->snapshot['supersedes'])->toBe($record->id)
->and(app(SupplyPlanning::class)->save($buyer, 'import', $transit)->state)->toBe('transit')
->and(SupplyRecord::query()->where('kind', 'import_party')->count())->toBe(2)
->and(DB::table('stock_movements')->count())->toBe(0);
});
test('broker selection refuses stale entity versions missing declarations and conflicts of earlier selectors', function () {
[$buyer, $supplier, $instructions, $data] = importDossierPartyFixture($this);
$service = app(ImportParties::class);
expect(fn () => $service->select($buyer, $this->import, [...$data, 'supplier_version' => $supplier->version + 1]))->toThrow(HttpException::class);
expect(fn () => $service->select($buyer, $this->import, [...$data, 'no_conflict' => false]))->toThrow(ValidationException::class);
$record = $service->select($buyer, $this->import, $data);
ConflictDeclaration::query()->create(['tenant_id' => $buyer->tenant_id, 'user_id' => $buyer->id, 'supplier_id' => $supplier->id,
'has_conflict' => true, 'known_since' => today(), 'declared_at' => now(), 'reason' => 'Synthetic declared broker relationship.']);
$other = User::factory()->create(['tenant_id' => $buyer->tenant_id, 'department_id' => $buyer->department_id, 'purchasing_role' => PurchasingRole::Procurement]);
supplyGrant($other, ['procurement', 'import_prepare']);
$this->actingAs($other);
expect(fn () => $service->select($other, $this->import, [...$data, 'operation_key' => (string) Str::uuid(), 'version' => 1]))->toThrow(ValidationException::class);
expect(fn () => app(SupplyPlanning::class)->save($other, 'import', supplyInput(['event_date' => today()->toDateString(),
'evidence' => 'Synthetic transit evidence.'], 'transit', $this->import)))->toThrow(HttpException::class);
$workspace = $service->workspace($other, $this->import);
expect($workspace['current'][0]['issues'])->not->toBeEmpty()
->and(SupplyRecord::query()->where('kind', 'import_party')->count())->toBe(1)
->and($record->fresh()->snapshot['supplier']['id'])->toBe($supplier->id);
});
test('a private original lost between metadata and byte reading is refused as a recoverable conflict', function () {
$record = app(ImportDossier::class)->record($this->f['issuer'], $this->import, $this->input, $this->file);
$disk = Mockery::mock(FilesystemAdapter::class);
$disk->shouldReceive('exists')->once()->andReturnTrue();
$disk->shouldReceive('size')->once()->andReturn(strlen($this->bytes));
$disk->shouldReceive('get')->once()->andReturnNull();
Storage::shouldReceive('disk')->with('local')->andReturn($disk);
try {
app(ImportEvidence::class)->bytes($record);
$this->fail('Missing private bytes must not be returned.');
} catch (HttpException $error) {
expect($error->getStatusCode())->toBe(409);
}
});
test('documentary date is preserved without inferring current validity or forbidding a future original date', function () {
$date = today()->addMonth()->toDateString();
$record = app(ImportDossier::class)->record($this->f['issuer'], $this->import, [...$this->input, 'issued_on' => $date], $this->file);
expect($record->data['issued_on'])->toBe($date)->and($record->state)->toBe('recorded')
->and($record->snapshot['external_submission'])->toBeFalse()->and($record->snapshot['financial_effects'])->toBeFalse();
});
test('sessionless QA actor reset permits inspection without changing any restored user fields', function () {
app(ImportDossier::class)->record($this->f['issuer'], $this->import, $this->input, $this->file);
$before = hash('sha256', DB::table('users')->orderBy('id')->get()->toJson());
clearImportQaIdentity();
expect(auth()->check())->toBeFalse()->and(app(ImportCostDocumentHealth::class)->inspect()['ok'])->toBeTrue()
->and(hash('sha256', DB::table('users')->orderBy('id')->get()->toJson()))->toBe($before);
});
+51
View File
@@ -0,0 +1,51 @@
<?php
use Tempo\Finance\Budget\BudgetFailure;
use Tempo\Finance\Budget\BudgetImportEstimate;
beforeEach(function () {
if (! class_exists(BudgetImportEstimate::class)) {
$this->markTestSkipped('Select the authorised unpublished common source for isolated QA.');
}
});
/** Synthetic assumptions only; no legal rate, exemption or real transaction. */
function importEstimateExample(): array
{
return array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => 'not_applicable', 'basis' => 'Hipótese sintética explícita',
'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS);
}
test('pre-document cost uses exact known assumptions and native goods without manufacturing documentary origins', function () {
$components = importEstimateExample();
$components[0] = [...$components[0], 'status' => 'known', 'subtotal_minor' => 1000, 'tax_minor' => 160, 'total_minor' => 1160];
$goods = ['subtotal_minor' => 10000, 'tax_minor' => 1600, 'total_minor' => 11600];
$gross = BudgetImportEstimate::reconcile($goods, $components, true);
$net = BudgetImportEstimate::reconcile($goods, $components, false);
expect($gross['budget_amount_minor'])->toBe(12760)->and($net['budget_amount_minor'])->toBe(11000)
->and($gross['additional_budget_minor'])->toBe(1160)->and($gross['goods'])->toBe($goods)
->and($gross['financial_effects'])->toBeFalse()->and($gross['complete'])->toBeTrue()
->and(BudgetImportEstimate::reconcile($goods, array_reverse($components), true)['fingerprint'])->toBe($gross['fingerprint']);
expect(BudgetImportEstimate::reconcile(array_reverse($goods, true), $components, true)['fingerprint'])->toBe($gross['fingerprint']);
});
test('unknown costs retain a partial known subtotal but prevent a determinate approval or reservation basis', function () {
$components = importEstimateExample();
$components[2]['status'] = 'unknown';
$plan = BudgetImportEstimate::reconcile(['subtotal_minor' => 100, 'tax_minor' => 0, 'total_minor' => 100], $components, true);
expect($plan['complete'])->toBeFalse()->and($plan['budget_amount_minor'])->toBeNull()
->and($plan['additional_budget_minor'])->toBeNull()->and($plan['reference_totals'])->toBeNull()
->and($plan['known_total_minor'])->toBe(100)->and($plan['unknown'])->toBe(['duty']);
});
test('missing families duplicate assumptions absent money and arbitrary balancing are rejected', function (string $error) {
$components = importEstimateExample();
match ($error) {
'missing' => array_pop($components),
'duplicate' => $components[] = $components[0],
'zero_unknown' => $components[0]['subtotal_minor'] = 0,
'unbalanced' => $components[0] = [...$components[0], 'status' => 'known', 'subtotal_minor' => 100, 'tax_minor' => 2, 'total_minor' => 101],
'missing_tax' => $components[0] = array_diff_key([...$components[0], 'status' => 'known', 'subtotal_minor' => 100, 'total_minor' => 100], ['tax_minor' => true]),
};
expect(fn () => BudgetImportEstimate::reconcile(['subtotal_minor' => 100, 'tax_minor' => 0, 'total_minor' => 100], $components, true))->toThrow(BudgetFailure::class);
})->with(['missing', 'duplicate', 'zero_unknown', 'unbalanced', 'missing_tax']);
+230
View File
@@ -0,0 +1,230 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Budget;
use App\Models\PurchaseAward;
use App\Models\Quotation;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\CommonBudget;
use App\Services\ImportEstimates;
use App\Services\ImportLandedCosts;
use App\Services\ImportTariffCodes;
use App\Services\RequisitionWorkflow;
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;
use Tempo\Finance\Budget\BudgetImportEstimate;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
beforeEach(function () {
if (! class_exists(BudgetImportEstimate::class)) {
$this->markTestSkipped('Select the authorised unpublished common source for isolated QA.');
}
config(['import-estimates.qa_enabled' => true]);
$this->withoutVite();
$this->f = receiptFixture();
$this->actingAs($this->f['issuer']);
$this->draft = $this->f['r']->replicate();
$this->draft->fill(['number' => 'ESTIMATE-'.Str::random(12), 'status' => 'draft']);
$this->draft->save();
$item = $this->f['r']->items()->sole()->replicate();
$item->requisition_id = $this->draft->id;
$item->save();
$budgetAuthor = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$budgetReviewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($budgetAuthor);
$budgetId = app(CommonBudget::class)->for($budgetAuthor)->create(['cost_center_id' => $this->draft->cost_center_id,
'year' => (int) now()->year, 'kind' => 'operating', 'amount_minor' => 100000, 'includes_tax' => true, 'reason' => 'Orçamento estritamente sintético']);
$this->actingAs($budgetReviewer);
app(CommonBudget::class)->for($budgetReviewer)->approve($budgetId);
$this->budget = Budget::query()->findOrFail($budgetId);
$this->actingAs($this->f['issuer']);
$this->input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'budget_id' => $this->budget->id,
'reason' => 'Preparação de pressupostos estritamente sintéticos',
'components' => array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => 'unknown', 'basis' => 'Valor ainda não disponível',
'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS)];
});
test('native draft assumptions preserve unknowns originals and versions without financial or stock effects', function () {
$service = app(ImportEstimates::class);
$before = $this->draft->fresh()->getAttributes();
$record = $service->save($this->f['issuer'], $this->draft, $this->input);
expect($record->state)->toBe('incomplete')->and($record->snapshot['plan']['budget_amount_minor'])->toBeNull()
->and($service->save($this->f['issuer'], $this->draft, $this->input)->id)->toBe($record->id)
->and($this->draft->fresh()->getAttributes())->toBe($before)->and(DB::table('budget_entries')->count())->toBe(0);
$next = [...$this->input, 'operation_key' => (string) Str::uuid(), 'version' => 1];
foreach ($next['components'] as &$component) {
$component['status'] = 'not_applicable';
$component['basis'] = 'Hipótese sintética sem esta componente';
}
unset($component);
$corrected = $service->save($this->f['issuer'], $this->draft, $next);
expect($corrected->version)->toBe(2)->and($corrected->state)->toBe('prepared')
->and($corrected->snapshot['plan']['budget_amount_minor'])->toBe(10000)
->and($record->fresh()->state)->toBe('incomplete');
$this->get('/requisicoes/'.$this->draft->id.'/estimativa-importacao')->assertOk()
->assertInertia(fn (AssertableInertia $page) => $page->component('supply/import-estimate')
->where('latest.version', 2)->where('canPrepare', true)->where('nativeChanged', false));
expect(fn () => $service->save($this->f['issuer'], $this->draft, [...$next, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
});
test('assumptions cannot rewrite a submitted request or bypass actor and feature isolation', function () {
$service = app(ImportEstimates::class);
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], $this->input))->toThrow(HttpException::class);
$this->actingAs($this->f['receiver']);
expect(fn () => $service->save($this->f['receiver'], $this->draft, $this->input))->toThrow(ModelNotFoundException::class);
$this->actingAs($this->f['issuer']);
config(['import-estimates.qa_enabled' => false]);
expect(fn () => $service->save($this->f['issuer'], $this->draft, $this->input))->toThrow(HttpException::class);
});
test('native submission approves the full estimate reserves goods and extras once and rejection releases both', function () {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
$this->f['tenant']->update(['first_limit_minor' => 10500, 'second_limit_minor' => 10800]);
$input = $this->input;
foreach ($input['components'] as &$component) {
$component['status'] = 'not_applicable';
}
unset($component);
$input['components'][0] = [...$input['components'][0], 'status' => 'known', 'subtotal_minor' => 1000, 'tax_minor' => 0, 'total_minor' => 1000];
$estimate = app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $input);
$workflow = app(RequisitionWorkflow::class);
$workflow->submit($this->f['issuer'], $this->draft);
$submitted = $this->draft->fresh();
expect($submitted->status)->toBe('pending')->and($submitted->total_minor)->toBe(10000)
->and($submitted->approval_snapshot['approval_basis']['total_minor'])->toBe(11000)
->and($submitted->steps()->orderBy('position')->pluck('role')->all())->toBe(['department_head', 'procurement', 'finance']);
$this->actingAs($this->f['issuer']);
$engine = app(CommonBudget::class)->for($this->f['issuer']);
expect((int) DB::table('budget_entries')->sum('reserved_minor'))->toBe(10000)
->and((int) DB::table('budget_landed_entries')->sum('reserved_minor'))->toBe(1000)
->and($estimate->fresh()->state)->toBe('prepared');
$head = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->draft->department_id,
'purchasing_role' => PurchasingRole::DepartmentHead]);
$this->actingAs($head);
$workflow->decide($head, $submitted, 'rejected', 'Rejeição sintética para conferir a libertação');
expect($this->draft->fresh()->status)->toBe('rejected')->and((int) DB::table('budget_entries')->sum('reserved_minor'))->toBe(0)
->and((int) DB::table('budget_landed_entries')->sum('reserved_minor'))->toBe(0);
});
test('unknown or stale estimate prevents native submission without partial reservations or approval steps', function () {
app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $this->input);
try {
app(RequisitionWorkflow::class)->submit($this->f['issuer'], $this->draft);
$this->fail('Unknown costs cannot be submitted as zero.');
} catch (HttpException $error) {
expect($error->getStatusCode())->toBe(422);
}
expect($this->draft->fresh()->status)->toBe('draft')->and($this->draft->steps()->count())->toBe(0)
->and(DB::table('budget_entries')->count())->toBe(0);
$this->draft->items()->firstOrFail()->update(['description' => 'Edição deliberada posterior']);
expect(fn () => app(ImportEstimates::class)->approval($this->draft->fresh()))->toThrow(HttpException::class);
});
test('identified imported articles require an estimate and insufficient extras roll back the native goods reservation', function () {
config(['import-tariffs.qa_enabled' => true]);
app(ImportTariffCodes::class)->save($this->f['issuer'], $this->draft, [
'operation_key' => (string) Str::uuid(), 'action' => 'propose', 'version' => 0,
'requisition_item_id' => $this->draft->items()->sole()->id, 'reason' => 'Identificação sintética do artigo importado']);
expect(fn () => app(RequisitionWorkflow::class)->submit($this->f['issuer'], $this->draft))->toThrow(HttpException::class);
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
$input = $this->input;
foreach ($input['components'] as &$component) {
$component['status'] = 'not_applicable';
}
unset($component);
$input['components'][0] = [...$input['components'][0], 'status' => 'known', 'subtotal_minor' => 200000, 'tax_minor' => 0, 'total_minor' => 200000];
app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $input);
expect(fn () => app(RequisitionWorkflow::class)->submit($this->f['issuer'], $this->draft))->toThrow(ValidationException::class);
expect($this->draft->fresh()->status)->toBe('draft')->and($this->draft->steps()->count())->toBe(0)
->and(DB::table('budget_entries')->count())->toBe(0)->and(DB::table('budget_landed_entries')->count())->toBe(0);
});
test('native independently reviewed documents reconcile an approved estimate portion and preserve the remaining orders capacity', function () {
config(['import-landed-costs.qa_enabled' => true]);
Storage::fake('local');
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
$input = $this->input;
foreach ($input['components'] as &$component) {
$component['status'] = 'not_applicable';
}
unset($component);
$input['components'][0] = [...$input['components'][0], 'status' => 'known', 'subtotal_minor' => 3000, 'tax_minor' => 0, 'total_minor' => 3000];
$estimate = app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $input);
app(RequisitionWorkflow::class)->submit($this->f['issuer'], $this->draft);
$head = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->draft->department_id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
$this->actingAs($head);
app(RequisitionWorkflow::class)->decide($head, $this->draft->fresh(), 'approved', 'Aprovação sintética do custo integral');
// Synthetic issued-order fixture, after actual native approval of this new source.
$award = PurchaseAward::query()->findOrFail($this->f['order']->purchase_award_id)->replicate();
$quote = Quotation::query()->findOrFail($award->quotation_id)->replicate();
$quote->fill(['requisition_id' => $this->draft->id, 'reference' => 'ESTIMATE-QUOTE-'.Str::random(10)]);
$quote->save();
$award->fill(['requisition_id' => $this->draft->id, 'quotation_id' => $quote->id]);
$award->save();
$order = $this->f['order']->replicate();
$order->fill(['number' => 'ESTIMATE-ORDER-'.Str::random(10), 'requisition_id' => $this->draft->id, 'purchase_award_id' => $award->id]);
$order->save();
$line = $this->f['line']->replicate();
$line->purchase_order_id = $order->id;
$line->save();
supplyGrant($this->f['issuer'], ['procurement', 'import_prepare', 'requester']);
$this->actingAs($this->f['issuer']);
$import = app(SupplyPlanning::class)->save($this->f['issuer'], 'import', supplyInput([
'purchase_order_id' => $order->id, 'purpose' => 'internal', 'jurisdiction' => 'Synthetic QA jurisdiction',
'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Explicit synthetic regime']));
$finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$reviewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
supplyGrant($finance, ['finance']);
supplyGrant($reviewer, ['finance']);
$this->actingAs($finance);
$service = app(ImportLandedCosts::class);
$document = $service->recordDocument($finance, $import, ['operation_key' => (string) Str::uuid(), 'kind' => 'customs_assessment',
'reference' => 'SYNTHETIC-ESTIMATE-ACTUAL', 'issued_on' => today()->toDateString(), 'creditor_reference' => 'Synthetic authority', 'currency' => 'MZN',
'subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000, 'exchange_basis' => null, 'reason' => 'Documento sintético, sem execução aduaneira'],
UploadedFile::fake()->createWithContent('estimate-actual.pdf', "%PDF-1.4\nSynthetic QA only\n%%EOF"));
$selection = ['budget_id' => $this->budget->id, 'documents' => [['origin' => 'customs', 'kind' => 'customs_assessment', 'id' => $document->id]],
'components' => [['component_key' => 'duty', 'kind' => 'duty', 'origin' => 'customs', 'subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000,
'reference_subtotal_minor' => 2000, 'reference_tax_minor' => 0, 'reference_total_minor' => 2000]]];
$prepared = $service->save($finance, $import, ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0,
'action' => 'save', 'reason' => 'Preparação documental sintética', 'data' => $selection]);
$this->actingAs($reviewer);
$approved = $service->save($reviewer, $import, ['operation_key' => (string) Str::uuid(), 'record_key' => $prepared->record_key, 'version' => 1,
'action' => 'approve', 'reason' => 'Conferência independente dos documentos sintéticos', 'data' => []]);
$this->actingAs($finance);
expect(fn () => $service->financial($finance, $import, $approved, ['operation_key' => (string) Str::uuid(), 'action' => 'reserve',
'financial_revision' => 0, 'reason' => 'Não duplicar a reserva estimada']))->toThrow(HttpException::class);
$this->post('/compras/importacoes/'.$import->id.'/custos/'.$approved->id.'/orcamento?estimates_page=999999',
['operation_key' => (string) Str::uuid(), 'action' => 'reserve', 'financial_revision' => 0, 'reason' => 'A paginação não altera a protecção financeira'])->assertStatus(409);
$command = ['operation_key' => (string) Str::uuid(), 'actual_operation_key' => (string) Str::uuid(), 'action' => 'reconcile_estimate',
'financial_revision' => 0, 'estimate_id' => $estimate->id, 'estimate_revision' => 1, 'estimate_release_minor' => 1000,
'reason' => 'Parcela sintética correspondente a esta ordem; diferença documentada de 1000 MZN centavos'];
$this->post('/compras/importacoes/'.$import->id.'/custos/'.$approved->id.'/orcamento', $command)->assertRedirect();
$result = SupplyRecord::query()->where('kind', 'import_cost_event')->where('operation_key', $command['operation_key'])->firstOrFail();
expect($result->snapshot['common_result']['estimate_reconciliation']['reserved_minor'])->toBe(2000)
->and($result->snapshot['common_result']['additional_amount_minor'])->toBe(2000)
->and($service->financial($finance, $import, $approved, $command)->id)->toBe($result->id)
->and((int) DB::table('budget_landed_entries')->sum('reserved_minor'))->toBe(4000)
->and(DB::table('invoices')->count())->toBe(0)->and(DB::table('stock_movements')->count())->toBe(0);
$this->get('/compras/importacoes/'.$import->id.'/custos')->assertOk()->assertInertia(fn (AssertableInertia $page) => $page
->where('estimateSources.data.0.reserved_minor', 2000)->where('estimateSources.data.0.revision', 2));
expect(fn () => $service->financial($finance, $import, $approved, [...$command, 'operation_key' => (string) Str::uuid(),
'actual_operation_key' => (string) Str::uuid(), 'financial_revision' => 1]))->toThrow(HttpException::class);
config(['import-estimates.qa_enabled' => false]);
try {
$service->financial($finance, $import, $approved, ['operation_key' => (string) Str::uuid(), 'action' => 'reserve',
'financial_revision' => 1, 'reason' => 'A capacidade desligada não permite ignorar a reserva anterior']);
$this->fail('The reserved estimate capability must remain available.');
} catch (HttpException $error) {
expect($error->getStatusCode())->toBe(503);
}
});
@@ -3,6 +3,7 @@
use App\Models\Requisition;
use App\Services\ExternalPaymentWorkflow;
use App\Services\ProcurementPayableInsights;
use App\Services\ProcurementPaymentInsights;
use App\Services\SupplierPayables;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
@@ -99,6 +100,45 @@ test('native imported history is counted once and pending payments do not reduce
expect($result['coverage']['recognised'])->toBe(1)->and($result['currencies'][0]['principal_minor'])->toBe('6000')
->and($result['currencies'][0]['confirmed_payments_minor'])->toBe('3000')->and($result['currencies'][0]['allocated_payments_minor'])->toBe('0')
->and($result['currencies'][0]['balance_minor'])->toBe('3000');
$confirmed = app(ProcurementPaymentInsights::class)->build($f['validator'], Requisition::query()->visibleTo($f['validator']), today()->format('Y-m-d'), today()->format('Y-m-d'));
expect($confirmed['coverage']['confirmed_payments'])->toBe(1)
->and($confirmed['currencies'])->toBe([['currency' => 'MZN', 'count' => 1, 'amount_minor' => '3000']]);
$outside = app(ProcurementPaymentInsights::class)->build($f['validator'], Requisition::query()->visibleTo($f['validator']), today()->subDay()->format('Y-m-d'), today()->subDay()->format('Y-m-d'));
expect($outside['currencies'])->toBe([]);
});
test('payment period follows confirmation instead of the original payment or requisition date and reports broken evidence', function () {
$f = paymentFixture();
foreach (['view', 'prepare', 'validate'] as $action) {
DB::table('pa_access')->insert(['tenant_id' => $f['validator']->tenant_id, 'company_id' => 0, 'unit_id' => 0,
'user_id' => $f['validator']->id, 'person' => 'period-person', 'action' => $action]);
}
$this->actingAs($f['author']);
$payment = app(ExternalPaymentWorkflow::class)->register($f['author'], $f['invoice'], $f['payment_data']);
$this->travel(1)->days();
$this->actingAs($f['validator']);
app(ExternalPaymentWorkflow::class)->review($f['validator'], $payment, 'confirmed', 'Conferência sintética independente');
$query = Requisition::query()->visibleTo($f['validator']);
$service = app(ProcurementPaymentInsights::class);
expect($service->build($f['validator'], clone $query, today()->format('Y-m-d'), today()->format('Y-m-d'))['currencies'][0]['amount_minor'])->toBe('4000')
->and($service->build($f['validator'], clone $query, today()->subDay()->format('Y-m-d'), today()->subDay()->format('Y-m-d'))['currencies'])->toBe([]);
if (DB::getDriverName() === 'pgsql') {
if (! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
throw new LogicException('Commit only the disposable report test fixture.');
}
DB::commit();
$this->committedInsightsFixture = true;
}
$this->get('/relatorios?from='.today()->format('Y-m-d').'&to='.today()->format('Y-m-d'))->assertOk()
->assertInertia(fn (Assert $page) => $page->where('records.total', 0)
->where('paymentInsights.coverage.confirmed_payments', 1)->where('paymentInsights.currencies.0.amount_minor', '4000'));
$csv = $this->get('/relatorios/despesa.csv?from='.today()->format('Y-m-d').'&to='.today()->format('Y-m-d'))->assertOk()->assertDownload();
expect($csv->streamedContent())->toContain('MZN;1;4000')->not->toContain('bank_snapshot')->not->toContain('account_identifier');
$this->actingAs($f['issuer'])->get('/relatorios/despesa.csv')->assertForbidden();
$this->actingAs($f['validator']);
DB::table('external_payments')->where('id', $payment->id)->update(['reviewed_at' => null]);
$broken = $service->build($f['validator'], clone $query, null, null);
expect($broken['coverage']['indeterminate'])->toBe(1)->and($broken['currencies'])->toBe([]);
});
test('read composition rejects commands and revalidates withdrawn native financial access', function () {
+238 -4
View File
@@ -41,6 +41,7 @@ use App\Services\ImportTariffCodes;
use App\Services\InvoiceWorkflow;
use App\Services\OrderCancellationPolicyWorkflow;
use App\Services\OrderCancellationWorkflow;
use App\Services\OrderPartsAmendments;
use App\Services\OrderPartsPreparation;
use App\Services\OrderPartsWorkflow;
use App\Services\ProcurementReviewCsv;
@@ -1490,7 +1491,7 @@ test('optional partial-order preparation consolidates two independently approved
});
/** Native adjudication/approval fixture; requisition approval itself is the existing synthetic source. */
function nativeOrderPartsAward(object $test, ?Requisition $request = null, ?Quotation $quote = null): PurchaseAward
function nativeOrderPartsAward(object $test, ?Requisition $request = null, ?Quotation $quote = null, ?int $secondCentre = null): PurchaseAward
{
$request ??= $test->r;
$quote ??= $test->quotes[0];
@@ -1508,15 +1509,30 @@ function nativeOrderPartsAward(object $test, ?Requisition $request = null, ?Quot
app(CommonBudget::class)->for($test->admin)->approve($id);
}
$host = app(RequisitionBudgetDistributions::class);
$allocations = $quote->items()->get()->map(fn ($line) => ['allocation_key' => (string) Str::uuid(),
'line_id' => $line->requisition_item_id, 'centre_id' => $request->cost_center_id,
$allocations = $request->items()->get()->map(fn ($line) => ['allocation_key' => (string) Str::uuid(),
'line_id' => $line->id, 'centre_id' => $request->cost_center_id,
'subtotal_minor' => $line->subtotal_minor, 'total_minor' => $line->total_minor])->all();
if ($secondCentre !== null) {
if (count($allocations) !== 1 || $allocations[0]['subtotal_minor'] !== 10000 || $allocations[0]['total_minor'] !== 10000) {
throw new LogicException('Explicit two-centre fixture requires a single synthetic 100 MZN line.');
}
$allocations[0]['subtotal_minor'] = $allocations[0]['total_minor'] = 5000;
$allocations[] = [...$allocations[0], 'allocation_key' => (string) Str::uuid(), 'centre_id' => $secondCentre];
}
$request->forceFill(['budget_distribution_preparation' => ['allocations' => $allocations,
'source_revision' => $host->revision($request, $host->requestLines($request)), 'prepared_by' => $test->owner->id,
'reason' => 'Explicit synthetic source allocation.']])->save();
$test->actingAs($test->finance);
DB::transaction(fn () => app(BudgetWorkflow::class)->record($test->finance, $request, 'reserve', $request->total_minor, $request->subtotal_minor));
$test->actingAs($test->buyer);
if ($quote->currency !== 'MZN') {
if (count($allocations) !== 1) {
throw new LogicException('Foreign synthetic fixture requires explicit single-line allocation.');
}
$reference = app(QuotationExchange::class)->amounts($quote);
$allocations[0]['subtotal_minor'] = $reference['subtotal_minor'];
$allocations[0]['total_minor'] = $reference['total_minor'];
}
$data = [...$test->selection, 'quotation_id' => $quote->id, 'reason' => 'Explicit native award distribution.',
'budget_distribution_preparation' => array_map(fn ($row) => ['allocation_key' => $row['allocation_key'], 'line_id' => $row['line_id'], 'centre_id' => $row['centre_id'],
'subtotal' => (string) BigDecimal::of($row['subtotal_minor'])->dividedBy(100, 2),
@@ -1535,13 +1551,186 @@ function nativeOrderPartsInput(object $test, PurchaseAward $award, string $quant
$prepared = app(OrderPartsPreparation::class)->prepare($test->buyer, $input);
$distribution = DB::table('budget_distributions')->where('requisition_id', $award->requisition_id)->first();
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
$line = $prepared['sources'][0]['items'][0];
$line = $prepared['sources'][0]['reference_amounts'] ?? $prepared['sources'][0]['items'][0];
return [...$input, 'order_key' => (string) Str::uuid(), 'operation_key' => (string) Str::uuid(), 'fingerprint' => $prepared['fingerprint'],
'budget_sources' => [['origin' => $award->requisition_id, 'version' => $version, 'plan_hash' => $snapshot['plan_hash'],
'allocations' => [['allocation_key' => $snapshot['allocations'][0]['allocation_key'], 'subtotal_minor' => $line['subtotal_minor'], 'total_minor' => $line['total_minor']]]]]];
}
test('native partial-order foreign receipts and invoices preserve origin rates and cumulative remainders', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
$this->actingAs($this->finance);
$exchange = app(QuotationExchange::class);
$exchange->record($this->finance, $this->r, ['operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => '1.5',
'quoted_on' => today()->toDateString(), 'source' => 'Synthetic origin-specific FX, not a market rate.']);
$quote = $this->quotes[0];
$quote->items()->update(['unit_price_minor' => 223, 'subtotal_minor' => 223, 'tax_minor' => 0, 'total_minor' => 223]);
$quote->update(['currency' => 'USD', 'subtotal_minor' => 223, 'tax_minor' => 0, 'total_minor' => 223,
'exchange_basis' => $exchange->basis($this->r, 'USD')]);
$award = nativeOrderPartsAward($this);
$flow = app(OrderPartsWorkflow::class);
$input = nativeOrderPartsInput($this, $award, '0.400', 0);
$first = $flow->issue($this->buyer, $input);
expect($first->currency)->toBe('USD')->and($first->total_minor)->toBe(89)
->and($exchange->orderAmounts($first, 89, 0)['total_minor'])->toBe(134)
->and($flow->issue($this->buyer, $input)->id)->toBe($first->id);
$this->withoutVite();
$this->get('/ordens/'.$first->id.'/imprimir')->assertOk()->assertSee('1.5000000000')->assertSee('Synthetic origin-specific FX');
$second = $flow->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.600', 1));
expect($second->total_minor)->toBe(134)->and($exchange->orderAmounts($second, 134, 0)['total_minor'])->toBe(201)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(335);
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
$reviewer = User::factory()->create(['tenant_id' => $this->tenant->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($receiver);
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'FX-PART', 'name' => 'Synthetic warehouse']);
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'FX-PART', 'name' => 'Synthetic material', 'unit' => 'un']);
$line = $first->items()->sole();
app(ReceiptWorkflow::class)->confirm($receiver, $first, ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'FX-PART',
'received_on' => today()->toDateString(), 'warehouse_id' => $warehouse->id,
'items' => [['purchase_order_item_id' => $line->id, 'received_quantity' => '0.400', 'accepted_quantity' => '0.400',
'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]]);
$key = $input['budget_sources'][0]['allocations'][0]['allocation_key'];
foreach ([['0.45', '0.68'], ['0.44', '0.66']] as $index => [$documentary, $reference]) {
$this->actingAs($this->finance);
$data = ['number' => 'FX-PART-'.$index, 'issued_on' => today()->toDateString(), 'subtotal' => $documentary,
'tax' => '0.00', 'total' => $documentary, 'items' => [['purchase_order_item_id' => $line->id, 'quantity' => '0.200']],
'reason' => 'Explicit Finance reference for a synthetic foreign partial invoice.',
'order_part_allocations' => [['origin' => $this->r->id, 'allocation_key' => $key, 'subtotal' => $reference, 'total' => $reference]]];
$bad = $data;
$bad['order_part_allocations'][0]['subtotal'] = $documentary;
$bad['order_part_allocations'][0]['total'] = $documentary;
expect(fn () => app(InvoiceWorkflow::class)->register($this->finance, $first, $bad))->toThrow(ValidationException::class);
$invoice = app(InvoiceWorkflow::class)->register($this->finance, $first, $data);
$this->actingAs($reviewer);
app(InvoiceWorkflow::class)->validate($reviewer, $invoice);
app(InvoiceWorkflow::class)->validate($reviewer, $invoice->fresh());
}
expect(Invoice::query()->count())->toBe(2)->and(StockMovement::query()->count())->toBe(1)
->and((int) DB::table('budget_order_consumptions')->sum('amount_minor'))->toBe(134)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(201)
->and($quote->fresh()->exchange_basis['rate'])->toBe('1.5000000000');
});
test('native consolidated order preserves two different foreign origin rates in the document and reference', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
[$request, $quotes] = secondNativeOrderPartsOrigin($this);
foreach ([[$this->r, $this->quotes[0], '1.5'], [$request, $quotes[0], '2']] as [$origin, $quote, $rate]) {
$this->actingAs($this->finance);
$exchange = app(QuotationExchange::class);
$exchange->record($this->finance, $origin, ['operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => $rate,
'quoted_on' => today()->toDateString(), 'source' => 'Synthetic separate origin rate '.$rate]);
$quote->items()->update(['unit_price_minor' => 100, 'subtotal_minor' => 100, 'tax_minor' => 0, 'total_minor' => 100]);
$quote->update(['currency' => 'USD', 'subtotal_minor' => 100, 'tax_minor' => 0, 'total_minor' => 100,
'exchange_basis' => $exchange->basis($origin, 'USD')]);
}
$first = nativeOrderPartsAward($this);
$second = nativeOrderPartsAward($this, $request, $quotes[0]);
$a = nativeOrderPartsInput($this, $first, '1.000', 0);
$b = nativeOrderPartsInput($this, $second, '1.000', 0);
$sources = [...$a['sources'], ...$b['sources']];
$flow = app(OrderPartsWorkflow::class);
$preview = $flow->preview($this->buyer, ['sources' => $sources]);
expect($preview['can_issue'])->toBeTrue();
$order = $flow->issue($this->buyer, [...$a, 'sources' => $sources, 'fingerprint' => $preview['prepared']['fingerprint'],
'budget_sources' => [...$a['budget_sources'], ...$b['budget_sources']]]);
expect($order->total_minor)->toBe(200)->and($order->snapshot['exchange_basis'])->toBeNull()
->and($exchange->orderAmounts($order, 200, 0)['total_minor'])->toBe(350)
->and(array_column(array_column($order->snapshot['exchange_sources'], 'exchange_basis'), 'rate'))->toBe(['1.5000000000', '2.0000000000']);
$this->withoutVite();
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('1.5000000000')->assertSee('2.0000000000');
expect(fn () => $exchange->orderAmounts($order, 100, 0))->toThrow(HttpException::class);
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
$reviewer = User::factory()->create(['tenant_id' => $this->tenant->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($receiver);
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'FX-CONSOL', 'name' => 'Synthetic warehouse']);
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'FX-CONSOL', 'name' => 'Synthetic material', 'unit' => 'un']);
$lines = $order->items()->orderBy('id')->get();
app(ReceiptWorkflow::class)->confirm($receiver, $order, ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'FX-CONSOL',
'received_on' => today()->toDateString(), 'warehouse_id' => $warehouse->id,
'items' => $lines->map(fn ($line) => ['purchase_order_item_id' => $line->id, 'received_quantity' => '1.000',
'accepted_quantity' => '1.000', 'quality_status' => 'compliant', 'stock_item_id' => $stock->id])->all()]);
$this->actingAs($this->finance);
$invoice = app(InvoiceWorkflow::class)->register($this->finance, $order, ['number' => 'FX-CONSOL', 'issued_on' => today()->toDateString(),
'subtotal' => '2.00', 'tax' => '0.00', 'total' => '2.00', 'reason' => 'Explicit Finance allocation preserving both source rates.',
'items' => $lines->map(fn ($line) => ['purchase_order_item_id' => $line->id, 'quantity' => '1.000'])->all(),
'order_part_allocations' => [
['origin' => $first->requisition_id, 'allocation_key' => $a['budget_sources'][0]['allocations'][0]['allocation_key'], 'subtotal' => '1.50', 'total' => '1.50'],
['origin' => $second->requisition_id, 'allocation_key' => $b['budget_sources'][0]['allocations'][0]['allocation_key'], 'subtotal' => '2.00', 'total' => '2.00']]]);
$this->actingAs($reviewer);
app(InvoiceWorkflow::class)->validate($reviewer, $invoice);
app(InvoiceWorkflow::class)->validate($reviewer, $invoice->fresh());
expect($invoice->fresh()->status)->toBe('validated')->and($invoice->fresh()->total_minor)->toBe(200)
->and(Invoice::query()->count())->toBe(1)->and(StockMovement::query()->count())->toBe(2)
->and((int) DB::table('budget_order_consumptions')->sum('amount_minor'))->toBe(350)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(0);
});
test('native partial-order postgres history refuses source line and header rewriting after issuance', function () {
if (DB::getDriverName() !== 'pgsql' || ! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('PostgreSQL isolated optional contract required.');
}
$award = nativeOrderPartsAward($this);
$order = app(OrderPartsWorkflow::class)->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.400', 0));
$before = [$order->toArray(), $order->items()->get()->toArray(), DB::table('purchase_order_sources')->get()->toArray()];
foreach ([
fn () => DB::table('purchase_orders')->where('id', $order->id)->update(['total_minor' => 1]),
fn () => DB::table('purchase_order_items')->where('purchase_order_id', $order->id)->update(['quantity_offset_milli' => 1]),
fn () => DB::table('purchase_order_sources')->where('purchase_order_id', $order->id)->update(['snapshot' => '{}']),
fn () => DB::table('purchase_order_sources')->where('purchase_order_id', $order->id)->delete(),
] as $mutation) {
expect(fn () => DB::transaction($mutation))->toThrow(QueryException::class);
}
expect([$order->fresh()->toArray(), $order->items()->get()->toArray(), DB::table('purchase_order_sources')->get()->toArray()])->toEqual($before);
});
test('native partial-order Finance amendment exposes a recoverable form and preserves original order and unissued reserve', function () {
if (! method_exists(BudgetControl::class, 'amendOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
$centre = CostCenter::query()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id,
'code' => 'NATIVE-AMEND', 'name' => 'Synthetic second centre']);
$this->actingAs($this->finance);
$budget = app(CommonBudget::class)->for($this->finance)->create(['cost_center_id' => $centre->id, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000, 'reason' => 'Synthetic native amendment capacity.']);
$this->actingAs($this->admin);
app(CommonBudget::class)->for($this->admin)->approve($budget);
$award = nativeOrderPartsAward($this, secondCentre: $centre->id);
$input = nativeOrderPartsInput($this, $award, '0.400', 0);
$distribution = DB::table('budget_distributions')->where('requisition_id', $this->r->id)->first();
$plan = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
$input['budget_sources'][0]['allocations'] = array_map(fn ($row) => ['allocation_key' => $row['allocation_key'],
'subtotal_minor' => 2000, 'total_minor' => 2000], $plan['allocations']);
$order = app(OrderPartsWorkflow::class)->issue($this->buyer, $input);
$original = $order->toArray();
$this->withoutVite();
$this->get('/ordens/'.$order->id.'/reafectacao')->assertForbidden();
$this->actingAs($this->finance);
$this->get('/ordens/'.$order->id)->assertOk()->assertViewHas('page', fn ($page) => $page['props']['canAmendOrderParts'] === true);
$this->get('/ordens/'.$order->id.'/reafectacao')->assertOk()->assertViewHas('page', fn ($page) => $page['component'] === 'purchases/order-parts-amendment' && $page['encryptHistory'] === true);
$service = app(OrderPartsAmendments::class);
$sources = $service->sources($this->finance, $order);
$data = ['operation_key' => (string) Str::uuid(), 'reason' => 'Explicit native independent Finance allocation.',
'sources' => array_map(fn ($source) => [...$source, 'allocations' => array_map(fn ($row, $index) => [
'allocation_key' => $row['allocation_key'], 'subtotal' => $index === 0 ? '10.00' : '30.00',
'total' => $index === 0 ? '10.00' : '30.00'], $source['allocations'], array_keys($source['allocations']))], $sources)];
$this->post('/ordens/'.$order->id.'/reafectacao', $data)->assertRedirect('/ordens/'.$order->id);
$this->post('/ordens/'.$order->id.'/reafectacao', $data)->assertRedirect('/ordens/'.$order->id);
expect($order->fresh()->toArray())->toEqual($original)
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(6000)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(4000)
->and(DB::table('budget_order_commands')->where('kind', 'amend')->count())->toBe(1)
->and(array_column($service->sources($this->finance, $order)[0]['allocations'], 'total'))->toBe(['10.00', '30.00']);
$this->get('/ordens/'.$order->id.'/reafectacao')->assertOk()->assertViewHas('page', fn ($page) => count($page['props']['history']) === 1);
$data['operation_key'] = (string) Str::uuid();
$data['reason'] = 'A different amendment cannot reuse a stale source version.';
$this->post('/ordens/'.$order->id.'/reafectacao', $data)->assertConflict();
});
test('native partial-order issuance commits only forty then sixty and preserves replay and quantity caps', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
@@ -1812,3 +2001,48 @@ test('native explicit adoption keeps the old reserve unchanged and supports repl
expect(DB::table('budget_order_commands')->where('kind', 'adopt')->count())->toBe(1)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(4000);
});
test('native explicit adoption of a foreign legacy award requires exact reference lines and preserves its original reserve history', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
budgetDistributionFixtureSchema();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000008_create_purchase_order_sources.php')->up();
config(['order-parts.qa_enabled' => true, 'budget-distributions.qa_enabled' => true]);
$this->actingAs($this->finance);
$id = app(CommonBudget::class)->for($this->finance)->create(['cost_center_id' => $this->r->cost_center_id, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000, 'reason' => 'Synthetic foreign legacy reserve.']);
$this->actingAs($this->admin);
app(CommonBudget::class)->for($this->admin)->approve($id);
$this->actingAs($this->finance);
DB::transaction(fn () => app(BudgetWorkflow::class)->record($this->finance, $this->r, 'reserve', 10000, 10000));
$exchange = app(QuotationExchange::class);
$exchange->record($this->finance, $this->r, ['operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => '1.5',
'quoted_on' => today()->toDateString(), 'source' => 'Synthetic explicit legacy origin rate.']);
$quote = $this->quotes[0];
$quote->items()->update(['unit_price_minor' => 223, 'subtotal_minor' => 223, 'tax_minor' => 0, 'total_minor' => 223]);
$quote->update(['currency' => 'USD', 'subtotal_minor' => 223, 'tax_minor' => 0, 'total_minor' => 223,
'exchange_basis' => $exchange->basis($this->r, 'USD')]);
$award = selectPurchaseAward($this);
approvePurchaseAward($this, $award);
$old = DB::table('budget_entries')->where('requisition_id', $this->r->id)->orderBy('id')->get()->toArray();
$this->actingAs($this->buyer);
$this->withoutVite();
$operation = (string) Str::uuid();
$url = '/adjudicacoes/'.$award->id.'/parcelas/adoptar';
$this->post($url, ['operation_key' => $operation])->assertSessionHasErrors('reference_lines');
$data = ['operation_key' => $operation, 'reference_lines' => [['line_id' => $this->item->id, 'subtotal' => '3.35', 'total' => '3.35']]];
$bad = $data;
$bad['reference_lines'][0]['total'] = '3.34';
$this->post($url, $bad)->assertSessionHasErrors('reference_lines');
expect(DB::table('budget_order_commands')->count())->toBe(0);
$this->post($url, $data)->assertRedirect('/ordens/preparar');
$order = app(OrderPartsWorkflow::class)->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.400', 0));
$this->post($url, $data)->assertRedirect('/ordens/preparar');
expect(DB::table('budget_entries')->where('requisition_id', $this->r->id)->orderBy('id')->limit(count($old))->get()->toArray())->toEqual($old)
->and($order->total_minor)->toBe(89)->and($order->snapshot['reference_amounts']['total_minor'])->toBe(134)
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(201)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(134)
->and(DB::table('budget_order_commands')->where('kind', 'adopt')->count())->toBe(1);
});
+18
View File
@@ -0,0 +1,18 @@
<?php
use Illuminate\Support\Facades\DB;
/** Clear a manually assigned CLI fixture actor without rotating a user's remember token. */
function clearImportQaIdentity(): void
{
$db = DB::connection();
$isolated = ($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|| ($db->getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName()));
if (! app()->environment('testing') || ! app()->runningInConsole() || ! $isolated || request()->hasSession()) {
throw new LogicException('Only a sessionless disposable CLI fixture actor may be cleared this way.');
}
auth()->forgetGuards();
if (auth()->check()) {
throw new LogicException('The synthetic inspection still has an authenticated actor.');
}
}
+26 -6
View File
@@ -27,22 +27,42 @@ function landedQaReceiptsVerified(array $command, string $output): bool
if ($mode === 'migrate') {
return $contains(fn ($row) => ($row['isolated_schema_prepared'] ?? false) === true);
}
if ($mode === 'race') {
if (in_array($mode, ['race', 'race-estimate', 'race-estimate-reconcile'], true)) {
foreach (['same_operation', 'conflicting_plan_version', 'same_source_different_plan'] 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]['commands'] ?? 0) !== 1 || ($matches[0]['audits'] ?? 0) !== 1
|| ($matches[0]['commands'] ?? 0) !== ($mode === 'race-estimate-reconcile' ? 3 : 1) || ($matches[0]['audits'] ?? 0) !== 1
|| ($mode === 'race-estimate' && (($matches[0]['estimate'] ?? false) !== true || ($matches[0]['reserved_minor'] ?? null) !== 2000))
|| ($mode === 'race-estimate-reconcile' && (($matches[0]['reconciliation'] ?? false) !== true || ($matches[0]['reserved_minor'] ?? null) !== 3000))
|| ($matches[0]['statuses'] ?? null) !== ($scenario === 'same_operation' ? [200, 200] : [200, 409])) {
return false;
}
}
return $contains(fn ($row) => ($row['old_runtime_rejected_before_balance'] ?? false) === true && ($row['status'] ?? 0) === 503);
return $contains(fn ($row) => ($row['old_runtime_rejected_before_balance'] ?? false) === true && ($row['status'] ?? 0) === 503)
&& (! 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 ($mode === 'landed-costs') {
return $contains(fn ($row) => ($row['post_extension_restore_all_tables_equal'] ?? false) === true
if (in_array($mode, ['race-dossier', 'race-party'], 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]['statuses'] ?? null) !== ($scenario === 'same_operation' ? [200, 200] : [200, 409])) {
return false;
}
}
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))
&& $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) === 2 && ($row['source_loss_detected'] ?? false) === true
&& $contains(fn ($row) => ($row['private_original_versions_restored'] ?? 0) === 6 && ($row['typed_dossier_versions_restored'] ?? 0) === 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);
}
+62 -1
View File
@@ -2,6 +2,33 @@
require_once __DIR__.'/../Support/LandedQaReceipts.php';
test('estimate contention receipts require all native uniqueness races and explicit estimate effects', function () {
$command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'race-estimate'];
$rows = [['old_runtime_rejected_before_balance' => true, 'old_estimate_runtime_rejected' => true,
'runtime_landed_version' => 'COMMON-BUDGET-LANDED-COST-QA-v2', 'status' => 503]];
foreach (['same_operation', 'conflicting_plan_version', 'same_source_different_plan'] as $scenario) {
$rows[] = ['scenario' => $scenario, 'estimate' => true, 'statuses' => $scenario === 'same_operation' ? [200, 200] : [200, 409],
'blocked_writers_observed' => 2, 'commands' => 1, 'audits' => 1, 'reserved_minor' => 2000];
}
$encode = fn ($records) => implode("\n", array_map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR), $records));
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeTrue();
$reconciliation = $rows;
foreach ($reconciliation as &$row) {
if (isset($row['scenario'])) {
$row['reconciliation'] = true;
$row['commands'] = 3;
$row['reserved_minor'] = 3000;
}
}
unset($row);
$reconcileCommand = [...array_slice($command, 0, 3), 'race-estimate-reconcile'];
expect(landedQaReceiptsVerified($reconcileCommand, $encode($reconciliation)))->toBeTrue();
$reconciliation[1]['reserved_minor'] = 2000;
expect(landedQaReceiptsVerified($reconcileCommand, $encode($reconciliation)))->toBeFalse();
unset($rows[2]['estimate']);
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
});
test('separate Pest kernels cannot reuse one disposable database with persistent migration functions', function () {
$pest = ['php', 'vendor/bin/pest', 'tests/Feature/ImportTariffCodesTest.php'];
expect(landedQaCommandIsolationVerified([$pest]))->toBeTrue();
@@ -38,8 +65,42 @@ test('restore completion requires the restored replay original snapshot and data
expect(landedQaReceiptsVerified($command, $proof))->toBeFalse();
$databaseOnly = $proof."\n".json_encode(['isolated_restore_removed' => true], JSON_THROW_ON_ERROR);
expect(landedQaReceiptsVerified($command, $databaseOnly))->toBeFalse();
$privateFiles = ['private_original_versions_restored' => 2, 'source_loss_detected' => true,
$privateFiles = ['private_original_versions_restored' => 6, 'typed_dossier_versions_restored' => 4, 'selected_party_versions_restored' => 2, 'source_loss_detected' => true,
'separate_private_root_restored' => true, 'native_authorized_evidence_resolved' => true];
expect(landedQaReceiptsVerified($command, $databaseOnly."\n".json_encode($privateFiles, JSON_THROW_ON_ERROR)))->toBeTrue();
$estimateCommand = [...array_slice($command, 0, 3), 'import-estimates'];
$existingRecovery = $databaseOnly."\n".json_encode($privateFiles, JSON_THROW_ON_ERROR);
expect(landedQaReceiptsVerified($estimateCommand, $existingRecovery))->toBeFalse();
expect(landedQaReceiptsVerified($estimateCommand, $existingRecovery."\n".json_encode([
'estimate_source_remainder_restored' => 1000, 'estimate_original_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();
$missingParty = $privateFiles;
unset($missingParty['selected_party_versions_restored']);
expect(landedQaReceiptsVerified($command, $databaseOnly."\n".json_encode($missingParty, JSON_THROW_ON_ERROR)))->toBeFalse();
expect(landedQaReceiptsVerified(['php', 'vendor/bin/pest', '--compact'], '{"tool":"pest","result":"passed","tests":1,"passed":0,"skipped":1}'))->toBeFalse();
});
test('dossier contention requires both races one original and verified bytes', function () {
$command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'race-dossier'];
$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();
expect(landedQaReceiptsVerified($command, $encode([$rows[0]])))->toBeFalse();
$rows[1]['files_created'] = 2;
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
$partyCommand = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'race-party'];
foreach ($rows as &$row) {
$row['files_created'] = 0;
}
unset($row);
expect(landedQaReceiptsVerified($partyCommand, $encode($rows)))->toBeTrue();
$rows[1]['files_created'] = 1;
expect(landedQaReceiptsVerified($partyCommand, $encode($rows)))->toBeFalse();
});
+32
View File
@@ -0,0 +1,32 @@
<?php
use App\Services\OrderPartsReference;
test('foreign partial orders retain the original origin rate and cumulative cent remainder', function () {
$first = OrderPartsReference::portion(0, 0, 1, 1, '1.5');
$second = OrderPartsReference::portion(1, 1, 1, 1, '1.5');
expect($first)->toBe(['subtotal_minor' => 2, 'tax_minor' => 2, 'total_minor' => 4])
->and($second)->toBe(['subtotal_minor' => 1, 'tax_minor' => 1, 'total_minor' => 2])
->and($first['total_minor'] + $second['total_minor'])->toBe(6);
});
test('consolidation preserves separate origin rates instead of averaging them', function () {
$a = OrderPartsReference::portion(0, 0, 100, 16, '63.25');
$b = OrderPartsReference::portion(0, 0, 200, 32, '64.75');
expect($a)->toBe(['subtotal_minor' => 6325, 'tax_minor' => 1012, 'total_minor' => 7337])
->and($b)->toBe(['subtotal_minor' => 12950, 'tax_minor' => 2072, 'total_minor' => 15022])
->and($a['total_minor'] + $b['total_minor'])->toBe(22359);
});
test('partial invoices within a partial order preserve the source offset', function () {
$order = OrderPartsReference::portion(1, 1, 3, 2, '1.5');
$first = OrderPartsReference::portion(1, 1, 1, 1, '1.5');
$second = OrderPartsReference::portion(2, 2, 2, 1, '1.5');
foreach (['subtotal_minor', 'tax_minor', 'total_minor'] as $field) {
expect($first[$field] + $second[$field])->toBe($order[$field]);
}
});
test('invalid reference bases are refused before arithmetic', function (int $before, int $net, string $rate) {
expect(fn () => OrderPartsReference::portion($before, 0, $net, 0, $rate))->toThrow(InvalidArgumentException::class);
})->with([[-1, 1, '1'], [0, -1, '1'], [PHP_INT_MAX, 1, '1'], [0, 1, '0'], [0, 1, '-1'], [0, 100000000000000, '2']]);
+87
View File
@@ -0,0 +1,87 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Dossier from '@/pages/supply/import-dossier';
function renderDossier(canWrite: boolean) {
const original = {
id: 1,
record_key: 'synthetic-key',
version: 1,
created_at: '2026-11-27',
created_by: 3,
current: false,
supersedes: null,
sha256: 'a'.repeat(64),
reason: 'Original synthetic document.',
data: {
type: 'packing_list',
reference: '<script>private reference</script>',
issuer_reference: 'Synthetic issuer',
issued_on: null,
notes: null,
},
};
return renderToStaticMarkup(
<App
initialComponent={Dossier}
initialPage={{
component: 'supply/import-dossier',
url: '/compras/importacoes/4/documentos',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
importRecord: {
id: 4,
record_key: 'import-key',
version: 2,
},
order: { id: 5, number: 'OC-QA' },
documents: {
data: [
{
...original,
id: 2,
version: 2,
current: true,
supersedes: 1,
},
original,
],
prev_page_url: null,
next_page_url:
'/compras/importacoes/4/documentos?page=2',
},
types: { packing_list: 'Lista de embalagem' },
canWrite,
actorId: 3,
tenantId: 2,
},
}}
/>,
);
}
test('dossier reader retains version downloads and context without advertising write authority', () => {
const html = renderDossier(false);
expect(html).toContain('Dossiê de importação');
expect(html).toContain('/compras/importacoes/4/documentos/1');
expect(html).toContain('/compras/importacoes/4/documentos/2');
expect(html).toContain('Histórica');
expect(html).not.toContain(
'Guardar documento privado',
'Preparar correcção',
);
expect(html).toContain('&lt;script&gt;private reference&lt;/script&gt;');
expect(html).not.toContain('<script>private reference');
});
test('dossier writer corrects only the current version and distinguishes evidence from execution', () => {
const html = renderDossier(true);
expect(html).toContain('Guardar documento privado');
expect(html.match(/Preparar correcção/g)).toHaveLength(1);
expect(html).toContain('não confirma pagamentos');
expect(html).toContain('volte a seleccionar o ficheiro');
});
@@ -0,0 +1,45 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Reconciliation from '@/components/import-estimate-reconciliation';
test('reconciliation exposes explicit source remainder and does not select a financial allocation automatically', () => {
const html = renderToStaticMarkup(
<App
initialComponent={Reconciliation}
initialPage={{
component: 'reconciliation',
url: '/qa',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
planId: 2,
url: '/compras/importacoes/1/custos',
historyKey: 'synthetic-private-key',
financialRevision: 1,
sources: {
data: [
{
id: 4,
version: 1,
requisition_id: 9,
budget_id: 6,
revision: 2,
reserved_minor: 12345,
committed_minor: 0,
},
],
prev_page_url: null,
next_page_url: null,
},
},
}}
/>,
);
expect(html).toContain('saldo 123.45 MZN');
expect(html).toContain('parcela que corresponde aos documentos conferidos');
expect(html).toContain('restantes ordens');
expect(html).toContain('disabled');
});
+72
View File
@@ -0,0 +1,72 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import ImportEstimate from '@/pages/supply/import-estimate';
import { estimateMinor, estimateMoney } from '@/lib/import-estimate-money';
test('estimate money input stays exact and invalid values reach server validation without rounding', () => {
expect(estimateMinor('999999999999,99')).toBe(99999999999999);
expect(estimateMinor('1.01')).toBe(101);
expect(estimateMinor('1000000000000.00')).toBe(100000000000000);
expect(estimateMinor('1.001')).toBe('1.001');
expect(estimateMinor('-1')).toBe('-1');
expect(estimateMoney(99999999999999)).toBe('999999999999.99');
expect(estimateMoney(null)).toBe('');
});
test('estimate readers see unknown cost coverage and preserved history without an editable form', () => {
const html = renderToStaticMarkup(
<App
initialComponent={ImportEstimate}
initialPage={{
component: 'supply/import-estimate',
url: '/requisicoes/1/estimativa-importacao',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
requisition: {
id: 1,
number: 'QA',
status: 'pending',
total_minor: 10000,
},
actorId: 2,
tenantId: 3,
canPrepare: false,
nativeChanged: true,
budgets: {
data: [],
prev_page_url: null,
next_page_url: null,
},
latest: {
id: 4,
version: 1,
state: 'incomplete',
reason: 'Synthetic',
data: { budget_id: 1, components: [] },
snapshot: {
plan: {
complete: false,
budget_amount_minor: null,
known_total_minor: 10000,
unknown: ['duty'],
},
},
},
history: {
data: [],
prev_page_url: null,
next_page_url: null,
},
},
}}
/>,
);
expect(html).toContain('total permanece indeterminado');
expect(html).toContain('requisição mudou');
expect(html).not.toContain('<form');
expect(html).not.toContain('Guardar estimativa');
});
@@ -0,0 +1,91 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import ImportPartySelection, {
type ImportPartyWorkspace,
} from '@/components/import-party-selection';
function renderParties(canSelect: boolean) {
const selected = {
id: 1,
version: 2,
data: { role: 'broker', supplier_id: 3, instruction_document_id: 4 },
snapshot: {
supplier: {
name: '<script>Broker QA</script>',
nuit: '123456789',
version: 1,
},
instructions: { data: { reference: 'INSTRUCTIONS-QA' } },
},
reason: 'Explicit synthetic selection.',
issues: [
'As instruções escritas têm uma versão diferente; confira a selecção.',
],
};
const workspace: ImportPartyWorkspace = {
roles: { broker: 'Despachante aduaneiro', forwarder: 'Transitário' },
canSelect,
search: '',
current: [selected],
history: { data: [selected], prev_page_url: null, next_page_url: null },
suppliers: {
data: [{ id: 3, name: 'Broker QA', nuit: '123456789', version: 1 }],
prev_page_url: null,
next_page_url: null,
},
instructions: {
data: [
{
id: 4,
version: 1,
data: {
reference: 'INSTRUCTIONS-QA',
issuer_reference: 'QA buyer',
},
},
],
prev_page_url: null,
next_page_url: null,
},
};
return renderToStaticMarkup(
<App
initialComponent={ImportPartySelection}
initialPage={{
component: 'supply/import-dossier',
url: '/compras/importacoes/5/documentos',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
workspace,
importId: 5,
importKey: 'synthetic-import',
actorId: 6,
tenantId: 7,
},
}}
/>,
);
}
test('party reader sees preserved selection instructions and pending issues without selection commands', () => {
const html = renderParties(false);
expect(html).toContain('INSTRUCTIONS-QA');
expect(html).toContain('uma versão diferente');
expect(html).toContain('/compras/importacoes/5/documentos/4');
expect(html).not.toContain('Confirmar entidade e instruções');
expect(html).toContain('&lt;script&gt;Broker QA&lt;/script&gt;');
expect(html).not.toContain('<script>Broker QA');
});
test('buyer selects existing sources and must personally confirm the conflict declaration', () => {
const html = renderParties(true);
expect(html).toContain('Escolher entidade');
expect(html).toContain('Escolher instruções');
expect(html).toContain('Confirmo a ausência de conflito');
expect(html).not.toMatch(/<input[^>]+type="checkbox"[^>]*checked/);
expect(html).toContain('Rever a selecção actual');
});
+85
View File
@@ -1,4 +1,7 @@
import { describe, expect, it } from 'vitest';
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import Parts from '@/pages/purchases/parts';
import {
orderPartDraftKey,
orderPartMinor,
@@ -52,3 +55,85 @@ describe('explicit order-part monetary input', () => {
},
);
});
it('foreign legacy adoption shows an unknown reference as pending instead of a zero amount', () => {
const html = renderToStaticMarkup(
<App
initialComponent={Parts}
initialPage={{
component: 'purchases/parts',
url: '/ordens/preparar',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
candidates: {
data: [],
prev_page_url: null,
next_page_url: null,
},
preview: {
selection: {
sources: [
{
award_id: 2,
items: [
{
quotation_item_id: 3,
quantity: '1.000',
},
],
},
],
},
can_issue: false,
financial: [
{
origin: 1,
award_id: 2,
requires_adoption: true,
allocations: [],
adoption_lines: [
{
line_id: 4,
description:
'Synthetic imported material',
subtotal_minor: 100,
total_minor: 100,
},
],
},
],
prepared: {
fingerprint: 'a'.repeat(64),
currency: 'USD',
subtotal_minor: 100,
total_minor: 100,
sources: [
{
requisition_id: 1,
award_id: 2,
currency: 'USD',
items: [
{
description:
'Synthetic imported material',
quotation_item_id: 3,
quantity_offset_milli: 0,
quantity_milli: 1000,
total_minor: 100,
},
],
},
],
},
},
},
}}
/>,
);
expect(html).toContain('Referência por conferir');
expect(html).toContain('todos os artigos da proposta');
expect(html).not.toContain('0,00');
});
@@ -0,0 +1,51 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it } from 'vitest';
import { ProcurementPaymentInsights } from '../../resources/js/components/procurement-payment-insights';
describe('confirmed payment expense', () => {
it('keeps currencies separate and formats amounts without floating point', () => {
const html = renderToStaticMarkup(
<ProcurementPaymentInsights
data={{
from: '2026-11-01',
to: '2026-11-27',
coverage: {
invoices: 3,
indeterminate: 1,
confirmed_payments: 2,
},
currencies: [
{
currency: 'MZN',
count: 1,
amount_minor: '9007199254740993',
},
{ currency: 'USD', count: 1, amount_minor: '1200' },
],
}}
/>,
);
expect(html).toContain('90071992547409,93 MZN');
expect(html).toContain('12,00 USD');
expect(html).toContain('valores apresentados são parciais');
expect(html).toContain('pela data de confirmação');
});
it('does not describe undetermined history as a zero expense', () => {
const html = renderToStaticMarkup(
<ProcurementPaymentInsights
data={{
from: null,
to: null,
coverage: {
invoices: 1,
indeterminate: 1,
confirmed_payments: 0,
},
currencies: [],
}}
/>,
);
expect(html).toContain('histórico indeterminado');
expect(html).not.toContain('0,00');
});
});