from pathlib import Path import shutil root=Path.cwd();out=Path(__file__).resolve().parent;qa=Path('C:/Users/macbook/.config/investmoz/documentos-publicos-QA-20261018/source') assert (out/'QA-ISOLAMENTO.json').exists() paths=['app/Http/Controllers/PortalServicesController.php','resources/js/pages/portal/services.tsx','resources/js/pages/portal/document.tsx','resources/js/components/simulation-form.tsx'] for name in paths: p=out/'antes'/name;p.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(qa/name,p) service=r''' ['href' => '/simulador-fiscal', 'label' => 'Abrir simulador fiscal'], 'procedures' => ['href' => '/como-investir', 'label' => 'Consultar como investir'], 'investment' => ['href' => '/oportunidades', 'label' => 'Consultar oportunidades'], 'zones' => ['href' => '/zonas', 'label' => 'Consultar zonas e parques'], 'education' => ['href' => '/educacao', 'label' => 'Consultar educação e competências'], 'business' => ['href' => '/negocios', 'label' => 'Consultar negócios'], 'land' => ['href' => '/investidor/terra-duat', 'label' => 'Consultar Terra e DUAT'], ]; private function text(?string $value): ?string { if ($value === null) return null; // Imported descriptions can contain implementation notes. Never mutate the original. $sentences = preg_split('/(?<=[.!?])\s+|[\r\n]+/u', strip_tags($value)); $safe = array_filter($sentences, fn ($text) => !preg_match('~(?:\b(?:supports|cites|evidence)\b|\btheme\s*:|\bfiscal\.[\w.]+|\b(?:SHA-?256|hash|preflight|repositório)\b|\b[0-9a-f]{40,64}\b|(?:^|\s)(?:[A-Z]:[\\/]|(?:docs|outputs|resources|storage|app)/))~iu', $text)); $result = trim(implode(' ', $safe)); return $result !== '' ? $result : null; } public function resource(object $row): array { $r=(array)$row; $public = array_intersect_key($r, array_flip(['id','document_type','document_date','applicable_from','applicable_until','language','territorial_scope','territory_name','source_confirmation','legal_status','size_bytes'])); foreach (['title','description','issuer','document_number','category','topic','version_label'] as $key) $public[$key]=$this->text($r[$key]??null); $public['title'] ??= 'Documento'; $url=$r['source_url']??null; $public['source_url']=is_string($url)&&filter_var($url,FILTER_VALIDATE_URL)&&in_array(strtolower(parse_url($url,PHP_URL_SCHEME)??''),['https','http'],true)?$url:null; $public['download_url']=route('services.download',['id'=>$r['id']]); $public['view_url']=in_array($r['media_type']??null,['application/pdf','image/jpeg','image/png','image/webp'],true)?route('services.document.view',['id'=>$r['id']]):null; $public['usage_notice']=in_array($r['document_type']??'', ['legislation','procedure','official_form','digital_adaptation','guidance_template'],true) ? 'Confirme no documento ou junto da entidade competente as condições aplicáveis ao seu caso. A consulta não garante benefícios nem aplicação fiscal.' : null; $keys=DB::table('portal_resource_links')->where('resource_id',$r['id'])->where('target_type','module')->pluck('target_key'); $public['context_actions']=$keys->filter(fn($key)=>isset(self::ACTIONS[$key]))->map(fn($key)=>self::ACTIONS[$key])->unique('href')->values()->all(); return $public; } } ''' (qa/'app/Services/PublicDocumentPresentation.php').write_text(service,'utf-8') p=qa/paths[0];s=p.read_text('utf-8');a=s.index(' $pageResult->getCollection()->transform(');b=s.index(" $props['resources']",a) s=s[:a]+" $pageResult->getCollection()->transform(fn ($resource) => app(\\App\\Services\\PublicDocumentPresentation::class)->resource($resource));\n"+s[b:] a=s.index(' $resources->transform(function ($resource) use ($matches)');b=s.index("\n return response()->json(['data' => $resources]);",a) s=s[:a]+" $resources->transform(fn ($resource) => app(\\App\\Services\\PublicDocumentPresentation::class)->resource($resource));\n"+s[b:] # Include ordinary public metadata in recommendations, not technical evidence. s=s.replace("->get(['r.id', 'r.title', 'r.description', 'r.document_type', 'r.legal_status', 'r.source_confirmation', 'r.source_url', 'r.source_reference']);", "->get(['r.id', 'r.title', 'r.description', 'r.document_type', 'r.document_date', 'r.document_number', 'r.applicable_from', 'r.applicable_until', 'r.language', 'r.territorial_scope', 'r.legal_status', 'r.source_confirmation', 'r.source_url', 'd.issuer', 'd.media_type', 'd.size_bytes']);") a=s.index(" $resource->links =",s.index(' public function showDocument'));b=s.index(' $back =',a) s=s[:a]+" $resource->territory_name = $resource->territory_id\n ? DB::table('geo_locations')->where('id', $resource->territory_id)->value('name') : null;\n $resource = app(\\App\\Services\\PublicDocumentPresentation::class)->resource($resource);\n"+s[b:] p.write_text(s,'utf-8') # Shared public card with only the public contract. component='''import { Link } from '@inertiajs/react'; export type PublicDocument = { id: number; title: string; description: string | null; issuer: string | null; document_number: string | null; document_date: string | null; applicable_from: string | null; applicable_until: string | null; source_url: string | null; source_confirmation: string; usage_notice: string | null; view_url: string | null; download_url: string; context_actions: { href: string; label: string }[]; }; export function PublicDocumentContent({ resource: r, detail = false, back = '/documentos' }: { resource: PublicDocument; detail?: boolean; back?: string }) { return <> {detail ?

{r.title}

:

{r.title}

} {r.description &&

{r.description}

}
Entidade emissora / autor
{r.issuer ?? 'Não indicada'}
{r.document_number &&
Número
{r.document_number}
} {r.document_date &&
Data do documento
{r.document_date}
} {r.applicable_from &&
Data de início indicada no registo
{r.applicable_from}
} {r.applicable_until &&
Data final indicada no registo
{r.applicable_until}
}
Fonte
{r.source_confirmation === 'official_confirmed' ? 'Fonte oficial' : r.source_url ? 'Fonte identificada' : 'Não indicada'}
{r.usage_notice &&

{r.usage_notice}

}
{!detail && Consultar ficha} {r.view_url && Consultar ficheiro} Descarregar documento {r.source_url && {r.source_confirmation === 'official_confirmed' ? 'Abrir fonte oficial' : 'Abrir fonte'}} {r.context_actions.map(action => {action.label})}
; } ''' (qa/'resources/js/components/public-document-content.tsx').write_text(component,'utf-8') p=qa/paths[1];s=p.read_text('utf-8');s="import { PublicDocumentContent, type PublicDocument } from '@/components/public-document-content';\n"+s a=s.index('type Resource = {');b=s.index('type Partnership =',a);s=s[:a]+'type Resource = PublicDocument & { document_type: string };\n'+s[b:] a=s.index('const publicModulePaths:');b=s.index('function Pagination',a);s=s[:a]+s[b:] a=s.index('

',s.index('{p.resources?.data.map'));b=s.index(' ',a) s=s[:a]+' \n'+s[b:] # Keep one useful limitation per document, not repeated editorial/technical notices. a=s.index('

\n Biblioteca documental única.');b=s.index(' \n Documentos nacionais',s.index('{activeFilters.length')) if '

\n Documentos nacionais' in s else -1 if a>=0: b=s.index('

',a)+len('

');s=s[:a]+s[b:] # module filter values remain stable public query parameters; label them for visitors. s=s.replace('{module}',"{{ simulator: 'Simulador fiscal', procedures: 'Como investir', investment: 'Oportunidades', zones: 'Zonas e parques', education: 'Educação', business: 'Negócios', land: 'Terra e DUAT' }[module] ?? 'Documentos de apoio'}") s=s.replace('','') p.write_text(s,'utf-8') (qa/paths[2]).write_text('''import { Head, Link } from '@inertiajs/react'; import { PortalMenu } from '@/layouts/portal-navigation'; import { PublicDocumentContent, type PublicDocument } from '@/components/public-document-content'; export default function DocumentPage({ resource, backUrl }: { resource: PublicDocument; backUrl: string; downloadUrl: string }) { return
← Voltar à pesquisa
; } ''','utf-8') p=qa/paths[3];s=p.read_text('utf-8');s="import { PublicDocumentContent, type PublicDocument } from '@/components/public-document-content';\n"+s a=s.index(' const [documentRecommendations, setDocumentRecommendations]');b=s.index(' const [linkableBusinesses',a);s=s[:a]+" const [documentRecommendations, setDocumentRecommendations] = useState([]);\n"+s[b:] a=s.index('

',s.index('{documentRecommendations.map'));b=s.index(' ',s.index('Descarregar documento',a)) s=s[:a]+' \n'+s[b:];p.write_text(s,'utf-8') print('QA public projection, shared content and three consumers updated; management unchanged')