Files
Investidor-V2/outputs/investmoz-documentos-publicos-QA-20261018/implement.py
T
nala cf003c8623
tests / ci (push) Canceled after 0s
versao nrgocios 4
2026-10-18 15:57:06 +02:00

134 lines
11 KiB
Python

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'''<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
/** Public projection only. Management retains the complete stored records and links. */
final class PublicDocumentPresentation
{
private const ACTIONS = [
'simulator' => ['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 ? <h1 className="text-3xl font-bold break-words">{r.title}</h1> : <h2 className="text-xl font-bold break-words">{r.title}</h2>}
{r.description && <p className="whitespace-pre-line">{r.description}</p>}
<dl className="grid gap-3 text-sm sm:grid-cols-2">
<div><dt className="font-semibold">Entidade emissora / autor</dt><dd>{r.issuer ?? 'Não indicada'}</dd></div>
{r.document_number && <div><dt className="font-semibold">Número</dt><dd>{r.document_number}</dd></div>}
{r.document_date && <div><dt className="font-semibold">Data do documento</dt><dd>{r.document_date}</dd></div>}
{r.applicable_from && <div><dt className="font-semibold">Data de início indicada no registo</dt><dd>{r.applicable_from}</dd></div>}
{r.applicable_until && <div><dt className="font-semibold">Data final indicada no registo</dt><dd>{r.applicable_until}</dd></div>}
<div><dt className="font-semibold">Fonte</dt><dd>{r.source_confirmation === 'official_confirmed' ? 'Fonte oficial' : r.source_url ? 'Fonte identificada' : 'Não indicada'}</dd></div>
</dl>
{r.usage_notice && <p role="note" className="rounded border border-amber-200 bg-amber-50 p-3 text-sm">{r.usage_notice}</p>}
<div className="flex flex-wrap gap-4 pt-2">
{!detail && <Link className="underline" href={`/documentos/${r.id}?${new URLSearchParams({ back }).toString()}`}>Consultar ficha</Link>}
{r.view_url && <a className="underline" href={r.view_url} target="_blank" rel="noreferrer">Consultar ficheiro</a>}
<a className="underline" href={r.download_url}>Descarregar documento</a>
{r.source_url && <a className="underline" href={r.source_url} target="_blank" rel="noreferrer">{r.source_confirmation === 'official_confirmed' ? 'Abrir fonte oficial' : 'Abrir fonte'}</a>}
{r.context_actions.map(action => <Link key={action.href} className="underline" href={action.href}>{action.label}</Link>)}
</div>
</>;
}
'''
(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(' <h2 className="text-xl font-bold break-words">',s.index('{p.resources?.data.map'));b=s.index(' </article>',a)
s=s[:a]+' <PublicDocumentContent resource={r} back={currentUrl} />\n'+s[b:]
# Keep one useful limitation per document, not repeated editorial/technical notices.
a=s.index(' <p>\n Biblioteca documental única.');b=s.index(' <form',a);s=s[:a]+s[b:]
a=s.index(' <p className="text-sm">\n Documentos nacionais',s.index('{activeFilters.length')) if ' <p className="text-sm">\n Documentos nacionais' in s else -1
if a>=0:
b=s.index(' </p>',a)+len(' </p>');s=s[:a]+s[b:]
# module filter values remain stable public query parameters; label them for visitors.
s=s.replace('<span>{module}</span>',"<span>{{ 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'}</span>")
s=s.replace('<option key={status}>{status}</option>','<option key={status} value={status}>{legalStatusLabels[status] ?? "Por confirmar"}</option>')
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 <div className="min-h-screen bg-slate-50 text-slate-900">
<Head title={resource.title} /><PortalMenu />
<main className="mx-auto max-w-4xl space-y-6 px-5 py-10">
<Link className="underline" href={backUrl}>← Voltar à pesquisa</Link>
<article className="space-y-5 rounded-xl border bg-white p-5 sm:p-8"><PublicDocumentContent resource={resource} detail /></article>
</main>
</div>;
}
''','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<PublicDocument[]>([]);\n"+s[b:]
a=s.index(' <h4 className="font-semibold">',s.index('{documentRecommendations.map'));b=s.index(' </li>',s.index('Descarregar documento',a))
s=s[:a]+' <PublicDocumentContent resource={document} />\n'+s[b:];p.write_text(s,'utf-8')
print('QA public projection, shared content and three consumers updated; management unchanged')