feat(iva): prepare five G8 service territoriality branches together in QA

This commit is contained in:
2026-10-24 23:38:14 +02:00
parent aac3f46306
commit ec33fb5be2
8 changed files with 209 additions and 0 deletions
@@ -0,0 +1,48 @@
<?php
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\TestCase;
final class IvaServiceLocationDraftTest extends TestCase
{
use DatabaseTransactions;
public function test_service_locations_recover_privately_preserving_all_delivered_books(): void
{
$target = DB::selectOne('select current_database() as name,inet_server_port() as port');
$this->assertSame('simulator_fiscal_delta_20261021_test', $target->name);
$this->assertSame(55441, (int) $target->port);
config(['investor-path.enabled' => true, 'suitecrm.enabled' => false]);
$this->actingAs(User::factory()->create(['email_verified_at' => now()]));
$draft = json_decode(file_get_contents(base_path('tests/frontend/fixtures/iva-g8-services.json')), true, flags: JSON_THROW_ON_ERROR);
$id = $this->postJson('/api/v1/simulation-drafts', ['personal_snapshot' => [], 'economic_snapshot' => $draft], ['Idempotency-Key' => (string) Str::uuid()])->assertCreated()->json('data.id');
$recovered = $this->getJson('/api/v1/simulation-drafts/'.$id)->assertOk()->json('data.economic_snapshot');
$this->assertSame($draft['modelo_a_snapshot'], $recovered['modelo_a_snapshot']);
$this->assertSame('opportunity:349', $recovered['context_opportunity']);
$this->assertSame('Manica', $recovered['selection_labels']['province_id']);
$store = json_decode($recovered['modelo_a_snapshot'], true, flags: JSON_THROW_ON_ERROR);
$book = $store['serviceLocations']['opportunity:349'];
$this->assertCount(10, $book['rows']);
$this->assertSame(['general_service','general_service','immovable_service','immovable_service','movable_work','movable_work','activity_service','activity_service','transport_service','transport_service'],array_column($book['rows'],'treatment'));
$this->assertSame(['national','outside','national','outside','national','outside','national','outside','national','outside'],array_column($book['result']['rows'],'territory'));
foreach ($book['result']['rows'] as $row) {
$this->assertNull($row['baseAmount']);$this->assertNull($row['vat']);$this->assertNull($row['rate']);
}
$this->assertSame($book['rows'], $book['result']['inputs']);
$this->assertCount(1, $book['history']);
$this->assertNull($book['history'][0]['rows'][0]['baseAmount']);
$frozen = json_decode(file_get_contents(base_path('tests/frontend/fixtures/iva-g8-services-preserved.json')), true, flags: JSON_THROW_ON_ERROR);
$prior = json_decode($frozen['modelo_a_snapshot'], true, flags: JSON_THROW_ON_ERROR);
$this->assertSame($prior, array_diff_key($store, ['serviceLocations' => true]));
$this->assertSame('1250.30', $store['publicAuthorityBases']['opportunity:339']['result']['rows'][1]['baseAmount']);
$this->assertNull($store['publicAuthorityBases']['opportunity:339']['result']['rows'][1]['vat']);
$this->assertSame('400.00', $store['importExemptions']['opportunity:338']['result']['rows'][1]['importVat']);
$this->assertNull($store['books']['opportunity:329']['result']['periods'][0]['fields']['11']);
file_put_contents(base_path('outputs/iva-l1-g8-services-20261024/recovered.json'), json_encode($recovered, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,37 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import {newServiceLocation,switchServiceTreatment,serviceLocationConditions,ownServiceConditions,serviceLocationTreatments,evaluateServiceLocation,recordServiceLocations,saveServiceLocationBook,serviceLocationBook,serviceLocationCurrent,serviceLocationReportRows} from '../../resources/js/lib/iva-service-location.ts';
const frozen=JSON.parse(fs.readFileSync('tests/frontend/fixtures/iva-g8-services-preserved.json','utf8'));
const draft={...frozen,context_opportunity:'opportunity:349',project_title:'SYNTHETIC QA — G8 services / Manica'};
function row(t,country='MZ') {return {...newServiceLocation(t+'-'+country),treatment:t,description:'SYNTHETIC QA serviço',period:'2026-12',origin:'projected',operationDate:'2026-12-12',operationRef:'SYNTHETIC QA operação',documentRef:'SYNTHETIC QA documento/pressuposto',documentDate:'2026-12-12',scope:'SYNTHETIC QA operação/serviço/dezembro2026',evidence:'SYNTHETIC QA pressupostos expressos',servicePlace:'SYNTHETIC QA local material',placeCountry:country,placeRef:'SYNTHETIC QA referência local',providerPlace:'SYNTHETIC QA estabelecimento prestador',providerCountry:country,providerRef:'SYNTHETIC QA referência estabelecimento',subjectRef:'SYNTHETIC QA imóvel/bens/actividade',totalDistance:'100.50',nationalDistance:country==='MZ'?'80.25':'0',departure:country,arrival:country,routeRef:'SYNTHETIC QA trajecto individual',conditions:Object.fromEntries([...serviceLocationConditions,...ownServiceConditions(t)].map(([key])=>[key,'yes']))};}
for(const treatment of serviceLocationTreatments)test(treatment.branch+' facts,own guards and territorial direction',()=>{
for(const country of ['MZ','foreign']){
const r=row(treatment.id,country);const expected=country==='MZ'?'national':'outside';assert.equal(evaluateServiceLocation(r).territory,expected);
assert.deepEqual(['baseAmount','vat','rate'].map(k=>evaluateServiceLocation(r)[k]),[null,null,null]);
if(treatment.id!=='general_service'){r.providerCountry=country==='MZ'?'foreign':'MZ';assert.equal(evaluateServiceLocation(r).territory,expected);}
for(const [key] of [...serviceLocationConditions,...ownServiceConditions(treatment.id)]){const missing=structuredClone(r);delete missing.conditions[key];assert.equal(evaluateServiceLocation(missing).status,'indeterminate');missing.conditions[key]='no';assert.equal(evaluateServiceLocation(missing).status,'not_applicable');assert.equal(evaluateServiceLocation(missing).territory,null);}
for(const field of ['operationRef','documentRef','scope','evidence',...(treatment.id==='general_service'?['providerPlace','providerCountry','providerRef']:treatment.id==='transport_service'?['routeRef','totalDistance','nationalDistance','departure','arrival']:['servicePlace','placeCountry','placeRef','subjectRef'])])assert.equal(evaluateServiceLocation({...r,[field]:''}).status,'indeterminate',field);
assert.equal(evaluateServiceLocation({...r,operationDate:'2026-11-12'}).status,'indeterminate');assert.equal(evaluateServiceLocation({...r,documentDate:'2026-02-30'}).status,'indeterminate');assert.equal(evaluateServiceLocation({...r,period:'2025-12'}).status,'indeterminate');
}
});
test('Four branches persist together,history,scope,hidden retention and previous books',()=>{
const rows=serviceLocationTreatments.flatMap(t=>['MZ','foreign'].map(c=>row(t.id,c)));
let book=recordServiceLocations(draft,{rows});book=recordServiceLocations(draft,book);assert.equal(book.history.length,1);
const next={...draft,modelo_a_snapshot:saveServiceLocationBook(draft,book)};assert.deepEqual(serviceLocationBook(next),book);assert.ok(serviceLocationCurrent(next,book));assert.equal(serviceLocationCurrent({...next,context_opportunity:'other'},book),false);
assert.equal(serviceLocationCurrent({...next,currency:'USD',customer_country:'foreign'},book),true);
assert.equal(serviceLocationReportRows(next).length,10);for(const t of serviceLocationTreatments)assert.ok(serviceLocationReportRows(next).some(r=>r[1].includes(t.branch)));
const store=JSON.parse(next.modelo_a_snapshot);delete store.serviceLocations;assert.deepEqual(store,JSON.parse(frozen.modelo_a_snapshot));
const switched=switchServiceTreatment(rows[0],'immovable_service');assert.equal(switched.providerRef,rows[0].providerRef);assert.equal(switched.servicePlace,rows[0].servicePlace);assert.equal(switched.conditions.propertyRelation,undefined);assert.equal(evaluateServiceLocation(switched).status,'indeterminate');
const corrupt={...next,modelo_a_snapshot:JSON.stringify({...JSON.parse(next.modelo_a_snapshot),serviceLocations:[]})};assert.throws(()=>serviceLocationBook(corrupt));assert.throws(()=>recordServiceLocations(next,{rows:[rows[0],rows[0]]}));
if(process.env.IVA_G8_SERVICES_FIXTURE)fs.writeFileSync(process.env.IVA_G8_SERVICES_FIXTURE,JSON.stringify(next,null,2)+'\n');
});
test('P110 domestic deemed distance,mixed route,zero,invalid and exact distances',()=>{
const r=row('transport_service');assert.equal(evaluateServiceLocation(r).territory,'national');
assert.equal(evaluateServiceLocation({...r,arrival:'foreign'}).territory,'partial');
assert.equal(evaluateServiceLocation({...r,arrival:'foreign',nationalDistance:'0'}).territory,'outside');
assert.equal(evaluateServiceLocation({...r,arrival:'foreign',nationalDistance:r.totalDistance}).territory,'national');
for(const patch of [{totalDistance:'0'},{nationalDistance:'101'},{nationalDistance:'-1'},{totalDistance:'1e3'},{totalDistance:'1,5'},{departure:''},{arrival:''}])assert.equal(evaluateServiceLocation({...r,...patch}).status,'indeterminate');
assert.equal(evaluateServiceLocation({...r,arrival:'foreign',nationalDistance:'0.000001',totalDistance:'999999999999999999.123456'}).territory,'partial');
assert.match(evaluateServiceLocation(r).reason,/08\/06\/2017/);assert.match(evaluateServiceLocation(r).reason,/Ida e volta/);
});