Files
compras/tests/Feature/ImportLegalReferenceDraftsTest.php
T
nala 448948a487
tests / ci (push) Waiting to run
commit compras1 2911
2026-11-29 05:28:30 +02:00

181 lines
13 KiB
PHP

<?php
use App\Models\SupplyRecord;
use App\Services\ImportLegalAmounts;
use App\Services\ImportLegalReferenceDrafts;
use App\Services\ImportLegalRules;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
beforeEach(function () {
config(['import-tariffs.qa_enabled' => true, 'import-legal.qa_enabled' => true]);
Storage::fake('local');
$this->f = receiptFixture();
supplyGrant($this->f['issuer'], ['procurement', 'import_customs']);
$this->actingAs($this->f['issuer']);
});
test('a supplied official edition offers exact documentary drafts without publishing rules or changing financial facts', function () {
$path = 'C:/Mac/Home/Documents/TEMPO/Portal Tempo/Legislacao/novas/BR_248_I_SERIE_SUPLEMENTO_2025.pdf';
if (! is_file($path)) {
test()->markTestSkipped('The owner supplied original is required for this real-source integration.');
}
expect(hash_file('sha256', $path))->toBe(ImportLegalReferenceDrafts::EDITION_SHA256);
$before = [];
foreach (['budget_entries', 'stock_movements', 'purchase_orders', 'invoices'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$service = app(ImportLegalRules::class);
$source = $service->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'action' => 'source', 'version' => 0,
'official_reference' => 'BR I Série 248, suplemento, 29/12/2025; Lei 8/2025',
'reason' => 'Actual supplied official original copied only to synthetic isolated QA; no rule publication.'],
new UploadedFile($path, basename($path), 'application/pdf', UPLOAD_ERR_OK, true));
$workspace = $service->workspace($this->f['issuer'], $this->f['r']);
$drafts = $workspace['referenceDrafts'];
expect($drafts)->toHaveCount(48)
->and(array_column($drafts, 'code'))->toContain('3506.91.20', '7604.10.10')
->and($drafts[0]['rate_percent'])->toBe('20')
->and($drafts[2]['rate_percent'])->toBe('7.5')
->and($drafts[0]['valid_from'])->toBe('2026-01-01')
->and($drafts[0]['citation'])->toContain('2180-(4)')
->and($drafts[0]['source_id'])->toBe($source->id)
->and($drafts[0]['charges'][0]['kind'])->toBe('duty')
->and($drafts[0]['charges'])->toHaveCount(4)
->and($workspace['referenceDraftWarnings'])->toBe([])
->and(SupplyRecord::query()->where('kind', 'import_legal_rule')->count())->toBe(0)
->and(json_encode($workspace['sources'], JSON_THROW_ON_ERROR))->not->toContain('import-legal/');
expect(array_unique(array_column($drafts, 'code')))->toHaveCount(48);
$capital = collect($drafts)->firstWhere('code', '8451.80.10');
$vehicle = collect($drafts)->firstWhere('code', '8704.21.10');
$last = collect($drafts)->firstWhere('code', '9507.90.90');
expect($capital['rate_percent'])->toBe('5')->and($capital['documentary_class'])->toBe('K')
->and($capital['obligations'])->toContain('não comprova elegibilidade')
->and($capital['citation'])->toContain('2180-(5)')
->and($vehicle['documentary_class'])->toBeNull()
->and($vehicle['obligations'])->toContain('bens de capital para investimento')
->and($last['citation'])->toContain('2180-(7)')
->and($last['rate_percent'])->toBe('5');
// A purely illustrative 100 MZN base is not a real import, debt or complete tax assessment.
$estimate = app(ImportLegalAmounts::class)->calculate($drafts[0]['charges'], ['general_duty' => [
'value_minor' => 10000, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Explicit synthetic 100 MZN unit-test base']]);
expect($estimate['known_subtotal_minor'])->toBe(2000)
->and($estimate['complete'])->toBeFalse()
->and($estimate['total_minor'])->toBeNull()
->and($estimate['financial_effects'])->toBeFalse();
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
Storage::disk('local')->put($source->snapshot['evidence']['path'], 'ALTERED-SYNTHETIC-COPY');
$workspace = $service->workspace($this->f['issuer'], $this->f['r']);
expect($workspace['referenceDrafts'])->toBe([])
->and($workspace['referenceDraftWarnings'])->toHaveCount(1)
->and($workspace['referenceDraftWarnings'][0]['source_id'])->toBe($source->id)
->and(hash_file('sha256', $path))->toBe(ImportLegalReferenceDrafts::EDITION_SHA256);
});
test('an unknown edition never inherits parameters from its title or citation', function () {
$source = new SupplyRecord(['kind' => 'import_legal_source', 'data' => ['official_reference' => 'Lei 8/2025'],
'snapshot' => ['evidence' => ['sha256' => hash('sha256', 'different edition')]]]);
expect(app(ImportLegalReferenceDrafts::class)->forSource($source))->toBe([]);
});
test('the documentary VAT rate requires explicit classification and valuation before a draft can be saved', function () {
$path = 'C:/Mac/Home/Documents/TEMPO/Portal Tempo/Legislacao/alteracao CIVA 2023.pdf';
if (! is_file($path)) {
test()->markTestSkipped('The supplied BR250 edition is required for this real-source integration.');
}
expect(hash_file('sha256', $path))->toBe(ImportLegalReferenceDrafts::VAT_EDITION_SHA256);
$before = [];
foreach (['budget_entries', 'stock_movements', 'purchase_orders', 'invoices'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$service = app(ImportLegalRules::class);
$source = $service->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'action' => 'source', 'version' => 0,
'official_reference' => 'Lei 22/2022; BR I Série250, 28/12/2022, exemplar partilhado',
'reason' => 'Exemplar partilhado copiado apenas para QA sintético, sem publicação de taxa.'],
new UploadedFile($path, basename($path), 'application/pdf', UPLOAD_ERR_OK, true));
$drafts = $service->workspace($this->f['issuer'], $this->f['r'])['referenceDrafts'];
expect($drafts)->toHaveCount(1);
$draft = $drafts[0];
expect($draft['match_code'])->toBe('')->and($draft['suggested_code'])->toBe('')
->and($draft['valid_from'])->toBe('2023-01-01')->and($draft['valid_until'])->toBeNull()
->and($draft['citation'])->toContain('2238', '2239')->and($draft['charges'][0]['kind'])->toBe('vat')
->and($draft['charges'][0]['rate_percent'])->toBe('16')->and($draft['charges'][0]['basis_reference'])->toBe('')
->and(array_column(array_slice($draft['charges'], 1), 'method'))->toBe(['unknown', 'unknown', 'unknown']);
$input = [...array_intersect_key($draft, array_flip(['source_id', 'title', 'official_reference', 'official_url', 'citation', 'valid_from', 'valid_until', 'obligations', 'charges', 'match_code', 'suggested_code'])),
'operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'action' => 'save',
'document_types' => [], 'reason' => 'Preparação exclusivamente sintética para conferir os parâmetros explícitos.'];
expect(fn () => $service->save($this->f['issuer'], $input))->toThrow(ValidationException::class);
$input['match_code'] = $input['suggested_code'] = 'SYNTHETIC-VAT-QA';
expect(fn () => $service->save($this->f['issuer'], $input))->toThrow(ValidationException::class);
expect(SupplyRecord::query()->where('kind', 'import_legal_rule')->count())->toBe(0);
$input['charges'][0]['basis_reference'] = 'Base declarada exclusivamente sintética de100MZN; não representa valoração de uma importação real.';
$saved = $service->save($this->f['issuer'], $input);
expect($saved->state)->toBe('draft')->and($saved->data['charges'][0]['rate_percent'])->toBe('16.000000')
->and($saved->data['match_code'])->toBe('SYNTHETIC-VAT-QA');
$estimate = app(ImportLegalAmounts::class)->calculate($saved->data['charges'], ['vat_normal_documentary' => [
'value_minor' => 10000, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic illustrative base, not a real assessment']]);
expect($estimate['known_subtotal_minor'])->toBe(1600)->and($estimate['complete'])->toBeFalse()
->and($estimate['total_minor'])->toBeNull()->and($estimate['financial_effects'])->toBeFalse();
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
Storage::disk('local')->put($source->snapshot['evidence']['path'], 'ALTERED-QA-VAT-COPY');
$workspace = $service->workspace($this->f['issuer'], $this->f['r']);
expect($workspace['referenceDrafts'])->toBe([])->and($workspace['referenceDraftWarnings'])->toHaveCount(1)
->and(hash_file('sha256', $path))->toBe(ImportLegalReferenceDrafts::VAT_EDITION_SHA256);
});
test('the official second supplement supplies only its eleven ICE positions and explicit two-year period', function () {
$path = base_path('tmp/pdfs/import-legal-source-review-20261128/law7-2025-official-second-supplement.pdf');
if (! is_file($path)) {
test()->markTestSkipped('The separately retained official second supplement is required.');
}
expect(hash_file('sha256', $path))->toBe(ImportLegalReferenceDrafts::ICE_EDITION_SHA256);
$service = app(ImportLegalRules::class);
$source = $service->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'action' => 'source', 'version' => 0,
'official_reference' => 'Lei 7/2025, BR I Série 248, 2.º suplemento, 2180-(21 a 22)',
'reason' => 'Official original used only in disposable synthetic QA; no rule activation.'],
new UploadedFile($path, basename($path), 'application/pdf', UPLOAD_ERR_OK, true));
$before = [];
foreach (['budget_entries', 'stock_movements', 'purchase_orders', 'invoices'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$drafts = $service->workspace($this->f['issuer'], $this->f['r'])['referenceDrafts'];
$expected = ['8702.10.10' => '20', '8702.10.20' => '25', '8702.20.00' => '20', '8702.30.00' => '20',
'8702.40.10' => '0', '8702.40.20' => '0', '8702.90.10' => '20', '8702.90.20' => '25', '8702.90.90' => '0',
'8703.80.10' => '5', '8703.80.20' => '15'];
expect(array_column($drafts, 'rate_percent', 'code'))->toBe($expected);
foreach ($drafts as $draft) {
expect($draft['valid_from'])->toBe('2026-01-01')->and($draft['valid_until'])->toBe('2027-12-31')
->and($draft['source_id'])->toBe($source->id)->and($draft['source_sha256'])->toBe(ImportLegalReferenceDrafts::ICE_EDITION_SHA256)
->and($draft['citation'])->toContain('2.º suplemento', '2180-(22)', $draft['code'])
->and($draft['charges'][0]['kind'])->toBe('ice')->and($draft['charges'][0]['rate_percent'])->toBe($expected[$draft['code']])
->and(array_column(array_slice($draft['charges'], 1), 'method'))->toBe(['unknown', 'unknown', 'unknown']);
$estimate = app(ImportLegalAmounts::class)->calculate($draft['charges'], ['ice_documentary' => [
'value_minor' => 10000, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic 100 MZN illustrative base only']]);
expect($estimate['known_subtotal_minor'])->toBe(((int) $expected[$draft['code']]) * 100)
->and($estimate['complete'])->toBeFalse()->and($estimate['total_minor'])->toBeNull()->and($estimate['financial_effects'])->toBeFalse();
}
expect(SupplyRecord::query()->where('kind', 'import_legal_rule')->count())->toBe(0);
$draft = collect($drafts)->firstWhere('code', '8703.80.10');
$saved = $service->save($this->f['issuer'], [...array_intersect_key($draft, array_flip(['source_id', 'title', 'official_reference', 'official_url', 'citation', 'valid_from', 'valid_until', 'obligations', 'charges'])),
'operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'action' => 'save',
'match_code' => $draft['code'], 'suggested_code' => $draft['code'], 'document_types' => [],
'reason' => 'Explicit synthetic QA preparation of documentary ICE; not publication.']);
expect($saved->state)->toBe('draft')->and($saved->data['valid_until'])->toBe('2027-12-31')
->and($saved->data['charges'][0]['rate_percent'])->toBe('5.000000');
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
Storage::disk('local')->put($source->snapshot['evidence']['path'], 'ALTERED-QA-SECOND-SUPPLEMENT');
$workspace = $service->workspace($this->f['issuer'], $this->f['r']);
expect($workspace['referenceDrafts'])->toBe([])->and($workspace['referenceDraftWarnings'])->toHaveCount(1);
});