92 lines
14 KiB
Python
92 lines
14 KiB
Python
from pathlib import Path
|
|
import re
|
|
qa=Path('C:/Users/macbook/.config/investmoz/parques-QA-20261016/source')
|
|
def edit(name,old,new):
|
|
p=qa/name;s=p.read_text('utf-8');assert s.count(old)==1,(name,old[:80],s.count(old));p.write_text(s.replace(old,new),'utf-8')
|
|
z='resources/js/pages/investment/zone.tsx'
|
|
edit(z,'type Zone = {', '''type OperationalDetail = {
|
|
id?: string; name: string; status: string; source_reference?: string | null;
|
|
source_date?: string | null; kind?: string | null; scope?: string | null;
|
|
capacity_type?: string | null; capacity_value?: number | string | null; capacity_unit?: string | null;
|
|
focus?: string | null; economic_activity_id?: string | null; support_document_ids?: string[]; private_note?: string | null;
|
|
};
|
|
type Area = { type: string; value: number | string | null; unit: string; source_reference: string; source_date?: string | null; status: string };
|
|
const labels: Record<string,string> = { unknown:'Não informado', not_informed:'Não informado', unconfirmed:'Por confirmar', inside:'No parque', regional:'Proximidade regional', infrastructure:'Infraestrutura', service:'Serviço', access:'Acesso', potential:'Potencial', proposed:'Proposta', existing:'Existente segundo a fonte', planned:'Planeado', installed:'Instalada segundo a fonte', promotional:'Foco promocional', reported:'Declarado pela fonte', confirmed:'Confirmado no cadastro', disputed:'Divergente', total:'Total', legal:'Legal', developed:'Desenvolvida', pilot:'Piloto', available:'Disponível segundo a fonte', in_development:'Em desenvolvimento', reported_unverified:'Declarada, não confirmada', industrial_park:'Parque industrial', pending:'Por confirmar', general:'Geral', not_applicable:'Não aplicável', operational:'Operacional segundo o cadastro', suspended:'Suspenso', partially_operational:'Parcialmente operacional', announced:'Anunciado', unavailable:'Indisponível', economic_zone:'Zona económica', agro_industrial_park:'Parque agro-industrial', industrial_logistics_park:'Parque industrial e logístico' };
|
|
const label = (value?: string | null) => value ? (labels[value] ?? value) : 'Não informado';
|
|
type Zone = {''')
|
|
edit(z,' area_components?: unknown[];', ' area_components?: Area[];\n public_version_no?: number;\n base_public_version?: number;\n has_private_draft?: boolean;')
|
|
for field in ['activities','resources']:
|
|
p=qa/z;s=p.read_text('utf-8');s,n=re.subn(r' '+field+r'\?: \{.*?\n \}\[\];',' '+field+'?: OperationalDetail[];',s,count=1,flags=re.S);assert n==1;p.write_text(s,'utf-8')
|
|
p=qa/z;s=p.read_text('utf-8');s,n=re.subn(r' '+field+r': \{.*?\n \}\[\];',' '+field+': OperationalDetail[];',s,count=1,flags=re.S);assert n==1;p.write_text(s,'utf-8')
|
|
edit(z,' area_components_json: string;', ' area_components: Area[];')
|
|
edit(z,' area_components_json: JSON.stringify(z.area_components ?? [], null, 2),',' area_components: z.area_components ?? [],')
|
|
edit(z,' area_components_json,\n','')
|
|
edit(z,' area_components:\n JSON.parse(area_components_json),\n','')
|
|
edit(z,' zoneExtensionsAvailable?: boolean;', ''' zoneExtensionsAvailable?: boolean;
|
|
profileAvailable?: boolean;
|
|
zoneContext?: { zone_id: string; consulted_public_version: number; notice: string } | null;''')
|
|
edit(z,' zoneExtensionsAvailable = false,',' zoneExtensionsAvailable = false,\n profileAvailable = false,\n zoneContext,')
|
|
edit(z,' {management ? (', ''' {management && z.category === 'industrial_park' && <p role="status">Versão pública {z.public_version_no ?? z.version_no} · preparação privada {z.has_private_draft ? z.version_no : 'ainda não guardada'}. Guardar não altera a publicação. {!profileAvailable && 'A preparação requer a instalação nominal do esquema; a ficha pública foi preservada.'}</p>}
|
|
{!management && zoneContext && <section className={card}><h2 className="font-semibold">Preparar uma ideia com este parque como referência</h2><p>{zoneContext.notice}</p><Link className="underline" href={`/investimentos/a-partir-do-parque/${zoneContext.zone_id}?consulted_public_version=${zoneContext.consulted_public_version}`}>Iniciar ou continuar uma ideia</Link><p>Versão pública consultada: {zoneContext.consulted_public_version}</p></section>}
|
|
{management ? (''')
|
|
# Replace only the area JSON field, retaining the existing source-evidence editor.
|
|
p=qa/z;s=p.read_text('utf-8');pattern=r'<Field label="Áreas por âmbito.*?</Field>'
|
|
m=re.search(pattern,s,re.S)
|
|
if not m:
|
|
# Locate label exactly from the existing source without guessing the UI block boundary.
|
|
start=s.index('value={form.data.area_components_json}')
|
|
a=s.rfind('<Field',0,start);b=s.index('</Field>',start)+len('</Field>');mspan=(a,b)
|
|
else:mspan=m.span()
|
|
replacement='''<section className="space-y-3 md:col-span-2"><h2 className="font-semibold">Áreas por âmbito e fonte</h2><p>Não somar âmbitos nem inferir área livre.</p>{form.data.area_components.map((area,index)=><div key={index} className="grid gap-2 md:grid-cols-3">{(['type','value','unit','source_reference','source_date','status'] as const).map(key=><label key={key} className="grid gap-1">{{type:'Âmbito',value:'Valor (vazio se desconhecido)',unit:'Unidade',source_reference:'Fonte da área',source_date:'Data da fonte',status:'Estado'}[key]}<input className={input} type={key==='source_date'?'date':key==='value'?'number':'text'} value={area[key] ?? ''} onChange={e=>form.setData('area_components',form.data.area_components.map((item,i)=>i===index?{...item,[key]:key==='value'?(e.target.value===''?null:Number(e.target.value)):e.target.value}:item))}/></label>)}</div>)}<button type="button" className={button} onClick={()=>form.setData('area_components',[...form.data.area_components,{type:'total',value:null,unit:'ha',source_reference:'',source_date:null,status:'reported'}])}>Adicionar área documentada</button></section>'''
|
|
s=s[:mspan[0]]+replacement+s[mspan[1]:];p.write_text(s,'utf-8')
|
|
# Add optional structured fields to each existing detail, preserving old arrays and identifiers.
|
|
for field,singular in [('activities','activity'),('resources','resource')]:
|
|
old=f''' {{form.data.{field}.map(({singular}, index) => (
|
|
<p key={{`${{{singular}.name}}-${{index}}`}}>'''
|
|
new=f''' {{form.data.{field}.map(({singular}, index) => (
|
|
<div key={{{singular}.id ?? index}}><DetailFields detail={{{singular}}} kind="{field}" onChange={{next=>form.setData('{field}',form.data.{field}.map((item,i)=>i===index?next:item))}}/><p>'''
|
|
edit(z,old,new)
|
|
p=qa/z;s=p.read_text('utf-8');start=s.index(new);end=s.index(' </p>',start);s=s[:end]+s[end:].replace(' </p>',' </p></div>',1);p.write_text(s,'utf-8')
|
|
edit(z,'disabled={busy || form.isDirty}',"disabled={busy || form.isDirty || (z.category === 'industrial_park' && !profileAvailable)}")
|
|
edit(z,' Guardar rascunho'," {z.category === 'industrial_park' ? 'Guardar preparação privada' : 'Guardar rascunho'}")
|
|
edit(z,' <li key={index}>{JSON.stringify(area)}</li>', ''' <li key={index}>{label(area.type)}: {area.value ?? 'Não informado'} {area.value == null ? '' : area.unit} · {label(area.status)} · Fonte: {area.source_reference || 'Não informada'} · {area.source_date ?? 'Data não informada'}</li>''')
|
|
edit(z,"{z.physical_category ?? 'Por confirmar'}",'{label(z.physical_category)}')
|
|
edit(z,"{z.legal_regime ?? 'Por confirmar'}",'{label(z.legal_regime)}')
|
|
edit(z,"${z.development_status ?? 'Por confirmar'} · Disponibilidade: ${z.availability_status ?? 'Não informada'}",'${label(z.development_status)} · Disponibilidade: ${label(z.availability_status)}')
|
|
p=qa/z;s=p.read_text('utf-8');old=' {resource.name} · {resource.status}';at=s.rindex(old);s=s[:at]+s[at:].replace(old,' {resource.name} · {label(resource.status)} · {label(resource.kind)} · {label(resource.scope)} · Capacidade: {resource.capacity_value ?? \'Não informada\'} {resource.capacity_value == null ? \'\' : resource.capacity_unit} · {resource.source_date ?? \'Data não informada\'}',1);p.write_text(s,'utf-8')
|
|
edit(z," {z.resources?.length ? (", " {!z.activities?.length && <p>Atividades: não informadas.</p>}\n {!z.resources?.length && <p>Infraestruturas, serviços e acessos: não informados. Capacidades: não informadas.</p>}\n {!z.area_components?.length && <p>Áreas por âmbito: não informadas.</p>}\n {!related.length && <p>Sem relações publicadas com âncoras ou clusters.</p>}\n {z.resources?.length ? (")
|
|
edit(z,' {activity.source_reference\n'," {' · '}{label(activity.focus)} · {activity.source_date ?? 'Data não informada'}\n {activity.source_reference\n")
|
|
with (qa/z).open('a',encoding='utf-8') as f:f.write('''
|
|
function DetailFields({detail,kind,onChange}:{detail:OperationalDetail;kind:string;onChange:(next:OperationalDetail)=>void}) {
|
|
const select=(key:'kind'|'scope'|'focus',title:string,values:string[]) => <label className="grid gap-1">{title}<select className={input} value={detail[key] ?? ''} onChange={e=>onChange({...detail,[key]:e.target.value || null})}><option value="">Não informado</option>{values.map(value=><option key={value} value={value}>{label(value)}</option>)}</select></label>;
|
|
return <fieldset className="my-3 grid gap-2 rounded border p-3 md:grid-cols-3"><legend>{detail.name}</legend>
|
|
{kind==='resources' && <>{select('kind','Natureza',['infrastructure','service','access','other'])}{select('scope','Âmbito',['inside','regional','unknown'])}</>}
|
|
{kind==='activities' && select('focus','Foco (distinto de autorização legal)',['promotional','potential','installed','unknown'])}
|
|
<label className="grid gap-1">Data da fonte<input className={input} type="date" value={detail.source_date ?? ''} onChange={e=>onChange({...detail,source_date:e.target.value || null})}/></label>
|
|
{kind==='resources' && <><label className="grid gap-1">Tipo de capacidade<input className={input} value={detail.capacity_type ?? ''} onChange={e=>onChange({...detail,capacity_type:e.target.value || null})}/></label><label className="grid gap-1">Capacidade (vazio se desconhecida)<input className={input} type="number" min="0" step="any" value={detail.capacity_value ?? ''} onChange={e=>onChange({...detail,capacity_value:e.target.value===''?null:Number(e.target.value)})}/></label><label className="grid gap-1">Unidade<input className={input} value={detail.capacity_unit ?? ''} onChange={e=>onChange({...detail,capacity_unit:e.target.value || null})}/></label></>}
|
|
{kind==='activities' && <label className="grid gap-1">Referência CAE existente (UUID; só com correspondência fundamentada)<input className={input} value={detail.economic_activity_id ?? ''} onChange={e=>onChange({...detail,economic_activity_id:e.target.value || null})}/></label>}
|
|
<label className="grid gap-1">Nota privada (não divulgada)<input className={input} value={detail.private_note ?? ''} onChange={e=>onChange({...detail,private_note:e.target.value || null})}/></label>
|
|
</fieldset>;
|
|
}
|
|
''')
|
|
zone_list='resources/js/pages/investment/zones.tsx'
|
|
edit(zone_list,"import { Link, router }", "import InvestmentZoneInstallation, { type ParkInstallationPlan } from '@/components/investment-zone-installation';\nimport { Link, router }")
|
|
edit(zone_list,' records,\n',' installation,\n records,\n')
|
|
edit(zone_list,' records: {',' installation?: ParkInstallationPlan | null;\n records: {')
|
|
edit(zone_list,' <p>\n A informação territorial', ' {management && installation && <InvestmentZoneInstallation initial={installation} />}\n <p>\n A informação territorial')
|
|
p='resources/js/pages/investor-path/index.tsx'
|
|
edit(p,' sectorSource,',' sectorSource,\n zoneSource,')
|
|
edit(p,' sectorSource?: {',' zoneSource?: { zone_id: string; consulted_public_version: number; title: string; href: string; notice: string };\n sectorSource?: {')
|
|
edit(p,' title: \'\','," zone_id: zoneSource?.zone_id,\n consulted_public_version: zoneSource?.consulted_public_version,\n confirm: !!zoneSource,\n title: '',")
|
|
edit(p,'\n {sectorSource && (', '''
|
|
{zoneSource && <section className="rounded border p-4"><h2>Parque consultado: {zoneSource.title} · versão {zoneSource.consulted_public_version}</h2><p>{zoneSource.notice}</p><Link className="underline" href={zoneSource.href}>Voltar à ficha pública</Link></section>}
|
|
{sectorSource && (''')
|
|
edit(p,'\n {sectorSource && (', '''
|
|
{zoneSource && <button type="button" className="mt-3 rounded border p-2" onClick={()=>router.post(`/investimentos/${item.id}/parques`,{version:item.version,zone_id:zoneSource.zone_id,consulted_public_version:zoneSource.consulted_public_version,confirm:true})}>Confirmar referência neste dossier</button>}
|
|
{sectorSource && (''')
|
|
p='resources/js/pages/investor-path/show.tsx'
|
|
edit(p,' sector_contexts:'," zone_contexts?: { zone_id: string; consulted_public_version: number; title: string; href: string; notice: string; selected_at: string }[];\n sector_contexts:")
|
|
edit(p,' {!!path.sector_contexts?.length && (', ''' {!!path.zone_contexts?.length && <section className="space-y-3 rounded border p-4"><h2 className="font-semibold">Parques consultados</h2>{path.zone_contexts.map(zone=><article key={`${zone.zone_id}:${zone.consulted_public_version}`}><Link className="underline" href={zone.href}>{zone.title}</Link><p>UUID {zone.zone_id} · versão consultada {zone.consulted_public_version} · {zone.selected_at}</p><p>{zone.notice}</p><p>A ficha atual pode ter uma versão diferente; esta referência conserva a consulta registada.</p></article>)}</section>}
|
|
{!!path.sector_contexts?.length && (''')
|
|
print('Private UI adapted')
|