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
@@ -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);
});