Scope parks and downstream investment requests to the treated opportunity

This commit is contained in:
2026-10-23 17:49:22 +02:00
parent ad4160f040
commit 4a01e9e2b7
25 changed files with 408 additions and 39 deletions
+28 -6
View File
@@ -1,3 +1,5 @@
import { InvestmentConsumerIdentity } from './investment-consumer-identity';
import InvestmentRequirements from './investment-requirements';
import { useEffect, useRef, useState } from 'react';
import { InvestmentContextAssessment } from './investment-context-assessment';
import { Link } from '@inertiajs/react';
@@ -18,6 +20,7 @@ type Props = {
allowedFields?: string[];
persistInheritance?: boolean;
boundRevision?: number;
initialOpportunity?: string;
onApply: (patch: Record<string, unknown>, replace: boolean) => void;
onReview?: (revision: number, reviewed: boolean) => void;
};
@@ -49,14 +52,17 @@ export function DossierPrefill(props: Props) {
const [selected, setSelected] = useState<string[]>([]);
const [reviewed, setReviewed] = useState(false);
const [message, setMessage] = useState('');
const [opportunity, setOpportunity] = useState(() => String(props.values.context_opportunity || props.initialOpportunity || (typeof window !== 'undefined' ? new URLSearchParams(window.location.search).get('opportunity') || '' : '')));
const loadedOpportunity = useRef('');
useEffect(() => {
if (!contextId) return;
let stopped = false;
setView(null);
setError('');
void contextApi<ContextView>(`/investimentos/${contextId}/contexto`)
void contextApi<ContextView>(`/investimentos/${contextId}/contexto${opportunity ? '?opportunity='+encodeURIComponent(opportunity) : ''}`)
.then((v) => {
if (!stopped) {
loadedOpportunity.current = opportunity;
setView(v);
setReviewed(false);
}
@@ -67,11 +73,14 @@ export function DossierPrefill(props: Props) {
return () => {
stopped = true;
};
}, [contextId, retry]);
}, [contextId, retry, opportunity]);
useEffect(() => {
if (!view || view.case.id !== contextId || !enabled || readOnly || !view.can_write) return;
if (!view || loadedOpportunity.current !== opportunity || view.case.id !== contextId || !enabled || readOnly || !view.can_write) return;
const choices = view.context.opportunity_choices ?? [];
const chosen = opportunity || (choices.length === 1 ? choices[0].opportunity.key : '');
const source = view.prefill[consumer] ?? {};
const now = latest.current;
if (consumer !== 'simulator' && chosen && now.values.context_opportunity !== chosen && (!now.allowedFields || now.allowedFields.includes('context_opportunity'))) now.onApply({context_opportunity:chosen},true);
const inherited = inheritCompatibleFields(`dossier:${contextId}:${consumer}`, now.values, source, now.values.context_reuse, now.allowedFields);
if (Object.keys(inherited.patch).length || (now.persistInheritance !== false && now.values.context_reuse !== inherited.metadata)) {
// The shared reconciliation has already selected safe fields; metadata travels with the same saved form.
@@ -109,6 +118,8 @@ export function DossierPrefill(props: Props) {
([k]) => !props.allowedFields || props.allowedFields.includes(k),
),
);
const chosenKey = opportunity || (view.context.opportunity_choices?.length===1 ? view.context.opportunity_choices[0].opportunity.key : '');
const chosenChoice = view.context.opportunity_choices?.find(c=>c.opportunity.key===chosenKey);
const differences = Object.keys(source).filter(
(k) => k !== 'context_applicability_snapshot' && !k.endsWith('_label') && text(props.values[k]) !== text(source[k]),
);
@@ -134,7 +145,17 @@ export function DossierPrefill(props: Props) {
</Link>
{' · '}<Link className="underline" href={`/investimentos/${contextId}`}>Voltar ao dossier</Link>
</p>
<InvestmentContextAssessment contextId={contextId} raw={view.prefill.simulator?.context_applicability_snapshot} />
{(consumer==='simulator'||opportunity||view.context.opportunity_choices?.length===1)&&<InvestmentContextAssessment contextId={contextId} raw={view.prefill.simulator?.context_applicability_snapshot} />}
<InvestmentConsumerIdentity raw={props.values.context_opportunity_snapshot}/>
{consumer!=='simulator'&&contextId&&<InvestmentRequirements contextId={contextId} assessment={view.context.requirements_assessment ? {...view.context.requirements_assessment,requirements:view.context.requirements_assessment.requirements.filter(r=>r.opportunity_key===(opportunity || (view.context.opportunity_choices?.length===1 ? view.context.opportunity_choices[0].opportunity.key : '')))} : null}/>}
{consumer !== 'simulator' && !!view.context.opportunity_choices?.length && <label className="block font-semibold">Oportunidade em tratamento
<select className="ml-2 rounded border bg-white p-2" disabled={readOnly || !view.can_write || (!!props.allowedFields&&!props.allowedFields.includes('context_opportunity'))} value={opportunity || (view.context.opportunity_choices.length===1 ? view.context.opportunity_choices[0].opportunity.key : '')} onChange={e=>{
const key=e.target.value; setOpportunity(key); setSelected([]);setReviewed(false);
props.onApply({context_opportunity:key},true);
props.onReview?.(view.context.revision,false);
}}><option value="">Escolha a oportunidade deste pedido</option>{view.context.opportunity_choices.map(c=><option key={c.opportunity.key} value={c.opportunity.key}>{c.opportunity.title} — {c.territory?.title??'Localização por definir'}</option>)}</select>
{!opportunity && view.context.opportunity_choices.length>1 && <p>Escolha a oportunidade para recuperar a localização e os requisitos específicos. Os dados comuns e as suas edições conservam-se.</p>}
</label>}
{stale && (
<p className="font-semibold" role="status">
{linkedRevision > 0
@@ -145,10 +166,11 @@ export function DossierPrefill(props: Props) {
</p>
)}
{message && <p role="status">{message}</p>}
{consumer === 'simulator' && !!view.context.opportunity_choices?.length && <OpportunityChoices choices={view.context.opportunity_choices}/>}
{!!view.context.opportunity_choices?.length && (consumer==='simulator'||!!chosenChoice) && <OpportunityChoices choices={consumer==='simulator' ? view.context.opportunity_choices : view.context.opportunity_choices.filter(c=>c.opportunity.key===chosenKey)}/>}
{consumer!=='simulator'&&chosenChoice?.opportunity.fields.sector&&<p>Sector desta oportunidade: {chosenChoice.opportunity.fields.sector}</p>}
<SelectedComplements items={view.context.complements ?? []}/>
{Object.entries(view.context.selection)
.filter(([slot]) => consumer !== 'simulator' || !view.context.opportunity_choices?.length || !['opportunity', 'territory'].includes(slot))
.filter(([slot]) => !view.context.opportunity_choices?.length || !['opportunity', 'territory', 'park', ...(consumer==='simulator'?[]:['sector'])].includes(slot))
.map(([, r]) =>
r && (
<p key={r.key}>