@@ -2,22 +2,22 @@ import { useState } from 'react';
|
||||
import { api } from '@/pages/investment/shared';
|
||||
|
||||
export type ParkInstallationPlan = { installed: boolean; ready: boolean; hash: string; migration: string; reasons: string[]; target: { database: string; port: number } };
|
||||
export default function InvestmentZoneInstallation({ initial }: { initial: ParkInstallationPlan }) {
|
||||
export default function InvestmentZoneInstallation({ initial, endpoint = '/management/investment/zones/profile-install', title = 'Preparação privada da ficha de parques', summary = 'Uma coluna privada; sem importação ou publicação de dados.' }: { initial: ParkInstallationPlan; endpoint?: string; title?: string; summary?: string }) {
|
||||
const [plan, setPlan] = useState(initial);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
async function refresh() {
|
||||
const response = await fetch('/management/investment/zones/profile-install', { headers: { Accept: 'application/json' } });
|
||||
const response = await fetch(endpoint, { headers: { Accept: 'application/json' } });
|
||||
if (!response.ok) throw new Error('Não foi possível carregar a prévia da instalação.');
|
||||
const value = await response.json(); setPlan(value.plan); return value.plan as ParkInstallationPlan;
|
||||
}
|
||||
return <section className="space-y-3 rounded border p-4" aria-label="Instalação da ficha de parques">
|
||||
<h2 className="font-semibold">Preparação privada da ficha de parques</h2>
|
||||
<p>{plan.installed ? 'Esquema instalado. Não importa nem publica fichas.' : 'Uma coluna privada; sem importação ou publicação de dados.'}</p>
|
||||
<h2 className="font-semibold">{title}</h2>
|
||||
<p>{plan.installed ? 'Esquema instalado. Não importa nem publica fichas.' : summary}</p>
|
||||
<p>Alvo: {plan.target.database}:{plan.target.port} · {plan.migration}</p>
|
||||
{plan.reasons.map(reason => <p key={reason} role="status">{reason}</p>)}
|
||||
<button type="button" className="rounded border p-2" disabled={busy} onClick={async () => { setBusy(true); try { await refresh(); setMessage('Prévia atualizada, sem escrita.'); } catch (e) { setMessage(e instanceof Error ? e.message : 'Falha ao carregar.'); } finally { setBusy(false); } }}>Atualizar prévia</button>
|
||||
<button type="button" className="rounded border p-2" disabled={busy || !plan.ready || plan.installed} onClick={async () => { setBusy(true); try { await api('/management/investment/zones/profile-install', { hash: plan.hash, idempotency_key: crypto.randomUUID(), confirm: true }); await refresh(); setMessage('Instalação nominal verificada; nenhuma ficha publicada.'); } catch (e) { setMessage(e instanceof Error ? e.message : 'Falha ao instalar.'); } finally { setBusy(false); } }}>Instalar apenas o esquema indicado</button>
|
||||
<button type="button" className="rounded border p-2" disabled={busy || !plan.ready || plan.installed} onClick={async () => { setBusy(true); try { await api(endpoint, { hash: plan.hash, idempotency_key: crypto.randomUUID(), confirm: true }); await refresh(); setMessage('Instalação nominal verificada; nenhuma ficha publicada.'); } catch (e) { setMessage(e instanceof Error ? e.message : 'Falha ao instalar.'); } finally { setBusy(false); } }}>Instalar apenas o esquema indicado</button>
|
||||
{message && <p role="alert">{message}</p>}
|
||||
</section>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import { useRef } from 'react';
|
||||
import { Field, input, button, card } from '@/pages/investment/shared';
|
||||
|
||||
type Group = 'responsibilities' | 'conditions' | 'risks';
|
||||
export type ParkDetail = {
|
||||
id?: string; label: string; knowledge: 'unknown' | 'documented' | 'disputed'; disclosure: boolean;
|
||||
source_reference?: string | null; source_date?: string | null; scope?: string | null;
|
||||
private_note?: string | null; support_document_ids?: string[];
|
||||
role?: string; organization_id?: string | null; organization_name?: string; documentary_name?: string | null;
|
||||
private_contact?: string | null; public_contact?: string | null;
|
||||
value?: string | number | null; currency?: string | null; unit?: string | null; period?: string | null;
|
||||
valid_from?: string | null; valid_until?: string | null;
|
||||
declared_nature?: string | null; management_model?: string | null; modality?: string | null;
|
||||
risk_type?: string | null; mitigation?: string | null; responsible_role?: string | null; channel?: string | null; channel_owner?: string | null;
|
||||
};
|
||||
export type ParkReview = { source_reference?: string | null; source_date?: string | null; scope?: string | null; confidence?: string | null; last_reviewed_at?: string | null; next_review_at?: string | null; private_note?: string | null };
|
||||
export type ParkDetails = { schema_version: number; responsibilities: ParkDetail[]; conditions: ParkDetail[]; risks: ParkDetail[]; review: ParkReview; remove_ids?: Partial<Record<Group, string[]>> };
|
||||
export const emptyParkDetails = (): ParkDetails => ({ schema_version: 1, responsibilities: [], conditions: [], risks: [], review: {} });
|
||||
const groups: Record<Group, string> = { responsibilities: 'Entidades e funções', conditions: 'Condições e tarifas declaradas', risks: 'Riscos e canal de esclarecimento' };
|
||||
const roles: Record<string, string> = { owner: 'Proprietário', promoter: 'Promotor', operator: 'Operador', manager: 'Gestor' };
|
||||
const knowledge = { unknown: 'Não informado', documented: 'Documentado pela fonte', disputed: 'Divergente' };
|
||||
const reviewLabels: Record<keyof ParkReview, string> = { source_reference: 'Fonte da revisão', source_date: 'Data da fonte', scope: 'Âmbito da revisão', confidence: 'Qualidade documental', last_reviewed_at: 'Última revisão', next_review_at: 'Próxima revisão', private_note: 'Nota de revisão privada' };
|
||||
|
||||
export function ParkDetailsPublic({ value }: { value?: Partial<ParkDetails> }) {
|
||||
if (!value) return null;
|
||||
return <section className={card} aria-label="Detalhes operacionais publicados">
|
||||
<h2 className="font-semibold">Detalhes operacionais publicados</h2>
|
||||
<p>A informação não constitui reserva, disponibilidade confirmada ou autorização de instalação. Uma tarifa desconhecida não é gratuita.</p>
|
||||
{(Object.keys(groups) as Group[]).map(g => <section key={g} className="my-4 space-y-2"><h3 className="font-semibold">{groups[g]}</h3>
|
||||
{!value[g]?.length && <p>Não informado nesta versão.</p>}
|
||||
{value[g]?.map((item, index) => <article key={index} className="rounded border p-3">
|
||||
<p>{item.label} · {knowledge[item.knowledge]}</p>
|
||||
{g === 'responsibilities' && <p>{roles[item.role ?? ''] ?? 'Função não informada'}: {item.organization_name ?? 'Não informado'}{item.public_contact ? ` · ${item.public_contact}` : ''}</p>}
|
||||
{g === 'responsibilities' && <p>Natureza declarada: {item.declared_nature || 'Não informada'} · modelo de gestão: {item.management_model || 'Não informado'}</p>}
|
||||
{g === 'conditions' && <p>Valor: {item.value == null ? 'Não informado' : `${item.value} ${item.currency ?? ''} / ${item.unit ?? ''}`} · período: {item.period ?? 'Não informado'} · vigência: {item.valid_from ?? 'Não informada'} a {item.valid_until ?? 'Não informada'}</p>}
|
||||
{g === 'conditions' && <p>Modalidade de acesso declarada: {item.modality || 'Não informada'}</p>}
|
||||
{g === 'risks' && <><p>Tipo: {item.risk_type || 'Não informado'} · mitigação: {item.mitigation || 'Não informada'} · função responsável: {roles[item.responsible_role ?? ''] || 'Não informada'}</p><p>Canal: {item.channel_owner === 'tempo' ? <a className="underline" href="/apoio">Apoio da Tempo — não é a gestão do parque</a> : item.channel_owner === 'park' ? `${item.channel || 'Não informado'} (canal próprio do parque segundo a fonte)` : 'Não informado'}</p></>}
|
||||
<p>Fonte: {item.source_reference || 'Não informada'} · data: {item.source_date || 'Não informada'} · âmbito: {item.scope || 'Não informado'}</p>
|
||||
</article>)}
|
||||
</section>)}
|
||||
<h3 className="font-semibold">Revisão documental</h3>
|
||||
<dl>{(Object.keys(reviewLabels) as (keyof ParkReview)[]).filter(k => k !== 'private_note').map(k => <div key={k}><dt>{reviewLabels[k]}</dt><dd>{k === 'confidence' ? ({ unknown: 'Não informada', reported: 'Declarada', documented: 'Documentada', disputed: 'Divergente' }[value.review?.[k] ?? ''] ?? 'Não informada') : value.review?.[k] || 'Não informado'}</dd></div>)}</dl>
|
||||
</section>;
|
||||
}
|
||||
|
||||
export default function ParkDetailsEditor({ value, onChange, organizations, documents }: { value: ParkDetails; onChange: (next: ParkDetails) => void; organizations: { id: string; name: string }[]; documents: { id: string; title: string }[] }) {
|
||||
const persistedIds = useRef(new Set([...value.responsibilities, ...value.conditions, ...value.risks].flatMap(item => item.id ? [item.id] : [])));
|
||||
function update(g: Group, index: number, next: Partial<ParkDetail>) { onChange({ ...value, [g]: value[g].map((item, i) => i === index ? { ...item, ...next } : item) }); }
|
||||
function field(g: Group, index: number, item: ParkDetail, key: keyof ParkDetail, label: string, type = 'text') {
|
||||
return <Field key={key} label={label}><input className={input} type={type} step={type === 'number' ? 'any' : undefined} value={String(item[key] ?? '')} onChange={e => update(g, index, { [key]: key === 'value' && e.target.value === '' ? null : e.target.value })} /></Field>;
|
||||
}
|
||||
return <section className="space-y-4 md:col-span-2" aria-label="Complemento operacional L1">
|
||||
<h2 className="font-semibold">Complemento operacional</h2><p>Uma entidade pode exercer várias funções. Guardar prepara em privado; divulgar exige seleção por detalhe e publicação expressa. Contactos pessoais, notas e suporte permanecem privados.</p>
|
||||
{(Object.keys(groups) as Group[]).map(g => <fieldset key={g} className="space-y-3 rounded border p-3"><legend>{groups[g]}</legend>
|
||||
{value[g].map((item, index) => <div key={item.id ?? index} className="grid gap-3 rounded border p-3 md:grid-cols-2">
|
||||
{field(g, index, item, 'label', 'Descrição do detalhe')}
|
||||
<Field label="Situação da informação"><select className={input} value={item.knowledge} onChange={e => update(g, index, { knowledge: e.target.value as ParkDetail['knowledge'], ...(e.target.value === 'unknown' ? { value: null } : {}) })}>{Object.entries(knowledge).map(([k, v]) => <option key={k} value={k}>{v}</option>)}</select></Field>
|
||||
{g === 'responsibilities' && <>
|
||||
<Field label="Função"><select className={input} value={item.role ?? 'owner'} onChange={e => update(g, index, { role: e.target.value })}>{Object.entries(roles).map(([k, v]) => <option key={k} value={k}>{v}</option>)}</select></Field>
|
||||
<Field label="Entidade existente"><select className={input} value={item.organization_id ?? ''} onChange={e => update(g, index, { organization_id: e.target.value || null })}><option value="">Menção preliminar / não identificada</option>{organizations.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}</select></Field>
|
||||
{field(g, index, item, 'documentary_name', 'Menção documental por corresponder (privada)')}
|
||||
{field(g, index, item, 'private_contact', 'Contacto pessoal / focal (privado)')}
|
||||
{field(g, index, item, 'public_contact', 'Contacto institucional autorizado para divulgação')}
|
||||
{field(g, index, item, 'declared_nature', 'Natureza organizacional declarada pela fonte')}
|
||||
{field(g, index, item, 'management_model', 'Modelo de gestão declarado pela fonte')}
|
||||
</>}
|
||||
{g === 'conditions' && <>
|
||||
{field(g, index, item, 'modality', 'Modalidade de acesso declarada')}
|
||||
{field(g, index, item, 'value', 'Valor (vazio = desconhecido)', 'number')}{field(g, index, item, 'currency', 'Moeda (código de três letras, quando aplicável)')}
|
||||
{field(g, index, item, 'unit', 'Unidade / base de cobrança')}{field(g, index, item, 'period', 'Período de cobrança, quando aplicável')}
|
||||
{field(g, index, item, 'valid_from', 'Vigência desde, quando conhecida', 'date')}{field(g, index, item, 'valid_until', 'Vigência até, quando conhecida', 'date')}
|
||||
</>}
|
||||
{g === 'risks' && <>
|
||||
{field(g, index, item, 'risk_type', 'Tipo de risco segundo a fonte')}{field(g, index, item, 'mitigation', 'Mitigação declarada')}
|
||||
<Field label="Função responsável pela mitigação"><select className={input} value={item.responsible_role ?? 'unknown'} onChange={e => update(g, index, { responsible_role: e.target.value })}><option value="unknown">Não informada</option>{Object.entries(roles).map(([k, v]) => <option key={k} value={k}>{v}</option>)}</select></Field>
|
||||
<Field label="Origem do canal"><select className={input} value={item.channel_owner ?? 'unknown'} onChange={e => update(g, index, { channel_owner: e.target.value })}><option value="unknown">Não informada</option><option value="park">Canal próprio do parque, documentado</option><option value="tempo">Apoio da Tempo, distinto do gestor do parque</option></select></Field>
|
||||
{field(g, index, item, 'channel', 'Canal próprio declarado (se documentado)')}
|
||||
</>}
|
||||
{field(g, index, item, 'source_reference', 'Fonte / citação (vazio = desconhecida)')}{field(g, index, item, 'source_date', 'Data da fonte (vazio = desconhecida)', 'date')}{field(g, index, item, 'scope', 'Âmbito aplicável')}
|
||||
{field(g, index, item, 'private_note', 'Nota interna (privada)')}
|
||||
<Field label="Suporte privado já associado (não publica o anexo)"><select multiple className={input} value={item.support_document_ids ?? []} onChange={e => update(g, index, { support_document_ids: Array.from(e.target.selectedOptions, o => o.value) })}>{documents.map(d => <option key={d.id} value={d.id}>{d.title}</option>)}</select></Field>
|
||||
<label className="flex items-center gap-2"><input type="checkbox" checked={item.disclosure} onChange={e => update(g, index, { disclosure: e.target.checked })} />Incluir os campos públicos deste detalhe na próxima publicação expressa</label>
|
||||
<button className={button} type="button" onClick={() => onChange({ ...value, [g]: value[g].filter((_, i) => i !== index), remove_ids: { ...value.remove_ids, [g]: [...(value.remove_ids?.[g] ?? []), ...(item.id && persistedIds.current.has(item.id) ? [item.id] : [])] } })}>Remover este detalhe na próxima gravação</button>
|
||||
</div>)}
|
||||
<button type="button" className={button} onClick={() => onChange({ ...value, [g]: [...value[g], { id: crypto.randomUUID(), label: '', knowledge: 'unknown', disclosure: false, ...(g === 'responsibilities' ? { role: 'owner' } : {}) }] })}>Acrescentar {groups[g].toLocaleLowerCase()}</button>
|
||||
</fieldset>)}
|
||||
<fieldset className="grid gap-3 md:grid-cols-2"><legend>Qualidade e revisão documental</legend>{(Object.keys(reviewLabels) as (keyof ParkReview)[]).map(k => k === 'confidence' ? <Field key={k} label={reviewLabels[k]}><select className={input} value={value.review[k] ?? 'unknown'} onChange={e => onChange({ ...value, review: { ...value.review, [k]: e.target.value } })}>{Object.entries({ unknown: 'Não informada', reported: 'Declarada', documented: 'Documentada', disputed: 'Divergente' }).map(([v, t]) => <option key={v} value={v}>{t}</option>)}</select></Field> : <Field key={k} label={reviewLabels[k]}><input className={input} type={k.includes('date') || k.endsWith('_at') ? 'date' : 'text'} value={value.review[k] ?? ''} onChange={e => onChange({ ...value, review: { ...value.review, [k]: e.target.value || null } })} /></Field>)}</fieldset>
|
||||
</section>;
|
||||
}
|
||||
Reference in New Issue
Block a user