Reuse investment context as editable simulator summaries

This commit is contained in:
2026-10-23 14:03:37 +02:00
parent 7ca94967f3
commit f2150b1912
7 changed files with 148 additions and 18 deletions
+18 -16
View File
@@ -27,6 +27,10 @@ const empty = (v: unknown) =>
(Array.isArray(v) && v.length === 0);
const text = (v: unknown) =>
typeof v === 'string' ? v : JSON.stringify(v ?? '');
const displayField = (values: Record<string, unknown>, key: string) =>
key.endsWith('_id')
? text(values[`${key}_label`]) || (empty(values[key]) ? 'não informado' : 'Referência escolhida; designação por recuperar')
: text(values[key]) || 'não informado';
export function DossierPrefill(props: Props) {
const {
contextId,
@@ -104,7 +108,7 @@ export function DossierPrefill(props: Props) {
),
);
const differences = Object.keys(source).filter(
(k) => k !== 'context_applicability_snapshot' && text(props.values[k]) !== text(source[k]),
(k) => k !== 'context_applicability_snapshot' && !k.endsWith('_label') && text(props.values[k]) !== text(source[k]),
);
const linkedRevision =
consumer === 'simulator'
@@ -117,24 +121,22 @@ export function DossierPrefill(props: Props) {
aria-label="Dados do dossier neste formulário"
>
<h2 className="font-bold">
Mesmo investimento · contexto v{view.context.revision}
Dados do seu investimento
</h2>
<p>
UUID {contextId} ·{' '}
<Link
className="underline"
href={`/investimentos/${contextId}`}
>
recuperar dossier
{view.case.title}
</Link>
. Mestres, declarações deste formulário e conteúdo já submetido
mantêm-se separados.
{' · '}<Link className="underline" href={`/investimentos/${contextId}`}>Voltar ao dossier</Link>
</p>
<InvestmentContextAssessment contextId={contextId} raw={view.prefill.simulator?.context_applicability_snapshot} />
{stale && (
<p className="font-semibold" role="status">
{linkedRevision > 0
? `O contexto do dossier difere da revisão vinculada a este registo (v${linkedRevision}).`
? 'Os dados do dossier mudaram desde a última análise.'
: 'Confira os valores deste formulário para o contexto atual; não há uma revisão anterior vinculada a estas entradas.'}{' '}
Os valores e resultados anteriores permanecem guardados;
confira os pressupostos antes de os usar no cenário atual.
@@ -145,11 +147,9 @@ export function DossierPrefill(props: Props) {
(r) =>
r && (
<p key={r.key}>
Fonte disponível:{' '}
<Link className="underline" href={r.href}>
{r.title}
</Link>{' '}
· {r.kind} · v{r.version ?? 'não exposta'}. {r.key}
</Link>
</p>
),
)}
@@ -214,11 +214,10 @@ export function DossierPrefill(props: Props) {
</label>
</td>
<td className="p-2 [overflow-wrap:anywhere]">
{text(props.values[k]) ||
'não informado'}
{displayField(props.values, k)}
</td>
<td className="p-2 [overflow-wrap:anywhere]">
{text(source[k]) || 'não informado'}
{displayField(source, k)}
</td>
</tr>
))}
@@ -232,17 +231,20 @@ export function DossierPrefill(props: Props) {
onClick={() => {
const patch: Record<string, unknown> = {};
for (const k of selected)
{
patch[k] = source[k] ?? '';
if (`${k}_label` in source) patch[`${k}_label`] = source[`${k}_label`];
}
const scope = `dossier:${contextId}:${consumer}`;
let raw = String(props.values.context_reuse ?? '');
try {
const metadata = JSON.parse(raw);
if(metadata.scope === scope) {
for(const key of selected) delete metadata.inherited?.[key];
for(const key of Object.keys(patch)) delete metadata.inherited?.[key];
raw=JSON.stringify(metadata);
}
} catch { /* Legacy metadata does not grant ownership of other fields. */ }
const adopted=inheritCompatibleFields(scope,{...props.values,...Object.fromEntries(selected.map(key=>[key,undefined]))},patch,raw,props.allowedFields);
const adopted=inheritCompatibleFields(scope,{...props.values,...Object.fromEntries(Object.keys(patch).map(key=>[key,undefined]))},patch,raw,props.allowedFields);
props.onApply({...patch,...(props.persistInheritance === false ? {} : {context_reuse:adopted.metadata})}, true);
setSelected([]);
setReviewed(false);
@@ -256,7 +258,7 @@ export function DossierPrefill(props: Props) {
</button>
</details>
)}
{!readOnly && reviewed && <p>Contexto v{view.context.revision} recuperado neste formulário, sem nova confirmação dos dados compatíveis. As edições locais conservam-se; as declarações e submissões formais mantêm os seus controlos próprios.</p>}
{!readOnly && reviewed && <p>Os dados disponíveis foram recuperados. Preencha o que falta; as suas alterações conservam-se.</p>}
<p className="text-xs">
Associar uma referência não confirma incentivos, licenças, terra
disponível, reserva ou autorização.
+12 -1
View File
@@ -1,6 +1,6 @@
import { SimulationPublishedIva, type PublishedIvaInput } from './simulation-published-iva';
import { SimulationMonthlyIva } from './simulation-monthly-iva';
import { inheritSimulatorFields } from '@/lib/context-inheritance';
import { inheritSimulatorFields, reusedInvestmentValue } from '@/lib/context-inheritance';
import {
PublicDocumentContent,
type PublicDocument,
@@ -807,6 +807,7 @@ export function SimulationForm() {
const canSavePersonalData = Boolean(auth?.user);
const canAssociateDraft = Boolean(auth?.user?.email_verified_at);
const [draft, setDraft] = useState<SimulationDraft>({});
const [editingReused, setEditingReused] = useState<string[]>([]);
const [ready, setReady] = useState(false);
useEffect(() => { if (ready) setDraft(current => inheritSimulatorFields(current)); }, [draft, ready]);
const [contextReview, setContextReview] = useState({
@@ -3294,6 +3295,16 @@ export function SimulationForm() {
: Boolean(field.required);
const fieldError =
serverFieldErrors[field.key] ?? errors[field.key];
const reused = contextId && ready && !fieldError && !editingReused.includes(`${contextId}:${field.key}`)
? reusedInvestmentValue(`dossier:${contextId}:simulator`, field.key, draft) : null;
if (reused !== null) return (
<div key={field.key} id={`field-${field.key}`} className="rounded border bg-emerald-50 p-3">
<p className="font-semibold">{field.label}</p>
<p className="whitespace-pre-wrap [overflow-wrap:anywhere]">{reused}</p>
<p className="text-sm">Recuperado do dossier.</p>
<button type="button" className="underline" onClick={() => setEditingReused((keys) => [...keys, `${contextId}:${field.key}`])}>Alterar {field.label.toLocaleLowerCase('pt-MZ')}</button>
</div>
);
const ivaNotes = ivaIssues.filter((issue) => issue.field === field.key).map((issue, index) => <p key={index} role="note" className="mt-1 text-sm text-amber-950">{ivaIssueText(issue)}</p>);
if (field.options) {
const parentKey =
+24
View File
@@ -19,6 +19,16 @@ export function inheritCompatibleFields(scope:string, values:Record<string,unkno
const geoConflict=geo.some(key=>(!empty(values[key]) || key in previous) && signature(values[key])!==signature(source[key]) && previous[key]!==signature(values[key]));
for(const [key,value] of Object.entries(source)) {
if ((allowed && !allowed.includes(key)) || (empty(value) && !(key in previous))) continue;
if (key.endsWith('_label')) {
const base = key.slice(0, -6);
const baseOwned = previous[base] === signature(values[base]);
const baseVacant = empty(values[base]) && !(base in previous);
if (!(base in source) || (geo.includes(base) && geoConflict) || (!baseOwned && !baseVacant && signature(values[base]) !== signature(source[base]))) continue;
// A label describes its identifier; it must never lag behind an adopted identifier.
if (signature(values[key]) !== signature(value)) patch[key] = value;
next[key] = signature(value); inherited.push(key);
continue;
}
const current=values[key];
const track = (item:unknown) => key==='parcels' ? Object.fromEntries(geo.map(field=>[field,(item as Array<Record<string,unknown>>)?.[0]?.[field] ?? ''])) : item;
const owned=previous[key]===signature(track(current));
@@ -42,6 +52,20 @@ export function inheritCompatibleFields(scope:string, values:Record<string,unkno
return {patch,metadata:JSON.stringify({version:1,scope,inherited:next}),inherited,conflicts};
}
/** Presentation only: a saved, unedited inherited value can be shown without asking again. */
export function reusedInvestmentValue(scope: string, key: string, values: Record<string, unknown>): string | null {
if (!['journey_type', 'purpose', 'project_title', 'project_summary', 'sector_id', 'province_id', 'district_id', 'admin_post_id', 'locality_id'].includes(key)) return null;
try {
const metadata = JSON.parse(String(values.context_reuse ?? ''));
if (metadata.version !== 1 || metadata.scope !== scope || empty(values[key]) || metadata.inherited?.[key] !== signature(values[key])) return null;
if (key.endsWith('_id') || ['journey_type', 'purpose'].includes(key)) {
const label = values[`${key}_label`];
return typeof label === 'string' && label.trim() && metadata.inherited?.[`${key}_label`] === signature(label) ? label : null;
}
return typeof values[key] === 'string' ? values[key] : null;
} catch { return null; }
}
export function inheritSimulatorFields<T extends Record<string,unknown>>(draft:T): T {
const source:Record<string,unknown>={};
const plan=draft.business_plan_snapshot ? restoreBusinessPlanSnapshot(String(draft.business_plan_snapshot)) : null;