fix: share selected opportunity across simulator stages and land shortcuts
This commit is contained in:
@@ -153,7 +153,7 @@ export function NavigationContextProvider({
|
||||
}
|
||||
const view = focus
|
||||
? await contextApi<NavigationView>(
|
||||
`/investimentos/${focus.case_id}`,
|
||||
`/investimentos/${focus.case_id}${direct===focus.case_id && new URL(url,'https://context.invalid').searchParams.get('opportunity') ? '?opportunity='+encodeURIComponent(new URL(url,'https://context.invalid').searchParams.get('opportunity')!) : ''}`,
|
||||
)
|
||||
: null;
|
||||
if (!stopped) {
|
||||
@@ -285,7 +285,7 @@ export function NavigationContextSummary() {
|
||||
{view && (
|
||||
<Link
|
||||
className="font-semibold underline"
|
||||
href={`/investimentos/${active}`}
|
||||
href={`/investimentos/${active}${scopedChoice ? '?opportunity='+encodeURIComponent(scopedChoice.opportunity.key) : ''}`}
|
||||
>
|
||||
Abrir dossier atual
|
||||
</Link>
|
||||
@@ -293,7 +293,7 @@ export function NavigationContextSummary() {
|
||||
{view?.next && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/investimentos/${active}#${view.next.code}`}
|
||||
href={`/investimentos/${active}${scopedChoice ? '?opportunity='+encodeURIComponent(scopedChoice.opportunity.key) : ''}#${view.next.code}`}
|
||||
>
|
||||
Preparar {view.next.code}
|
||||
</Link>
|
||||
|
||||
@@ -32,6 +32,10 @@ const empty = (v: unknown) =>
|
||||
(Array.isArray(v) && v.length === 0);
|
||||
const text = (v: unknown) =>
|
||||
typeof v === 'string' ? v : JSON.stringify(v ?? '');
|
||||
function savedOpportunity(values: Record<string, unknown>): string {
|
||||
if (values.context_opportunity) return String(values.context_opportunity);
|
||||
try { return JSON.parse(String(values.context_applicability_snapshot ?? '')).consumer_opportunity ?? ''; } catch { return ''; }
|
||||
}
|
||||
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')
|
||||
@@ -52,7 +56,11 @@ 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 userChose = useRef(false);
|
||||
const [opportunity, setOpportunity] = useState(() => String(props.initialOpportunity || (typeof window !== 'undefined' ? new URLSearchParams(window.location.search).get('opportunity') || '' : '') || savedOpportunity(props.values)));
|
||||
useEffect(() => {
|
||||
if (!userChose.current && !opportunity && enabled) { const saved = savedOpportunity(props.values); if (saved) setOpportunity(saved); }
|
||||
}, [enabled, props.values, opportunity]);
|
||||
const loadedOpportunity = useRef('');
|
||||
useEffect(() => {
|
||||
if (!contextId) return;
|
||||
@@ -80,7 +88,7 @@ export function DossierPrefill(props: Props) {
|
||||
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);
|
||||
if ((chosen || consumer === 'simulator') && 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.
|
||||
@@ -139,19 +147,19 @@ export function DossierPrefill(props: Props) {
|
||||
<p>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/investimentos/${contextId}`}
|
||||
href={`/investimentos/${contextId}${chosenKey ? '?opportunity='+encodeURIComponent(chosenKey) : ''}`}
|
||||
>
|
||||
{view.case.title}
|
||||
</Link>
|
||||
{' · '}<Link className="underline" href={`/investimentos/${contextId}`}>Voltar ao dossier</Link>
|
||||
{' · '}<Link className="underline" href={`/investimentos/${contextId}${chosenKey ? '?opportunity='+encodeURIComponent(chosenKey) : ''}`}>Voltar ao dossier</Link>
|
||||
</p>
|
||||
{(consumer==='simulator'||opportunity||view.context.opportunity_choices?.length===1)&&<InvestmentContextAssessment contextId={contextId} raw={view.prefill.simulator?.context_applicability_snapshot} />}
|
||||
{(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
|
||||
{contextId&&<InvestmentRequirements contextId={contextId} excludedSteps={view.steps.filter(step=>step.state==='dispensed').map(step=>step.code)} assessment={view.context.requirements_assessment ? {...view.context.requirements_assessment,requirements:view.context.requirements_assessment.requirements.filter(r=>r.opportunity_key===chosenKey)} : null}/>}
|
||||
{!!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);
|
||||
const key=e.target.value; userChose.current=true; setOpportunity(key); setSelected([]);setReviewed(false);
|
||||
if (consumer !== 'simulator') 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>}
|
||||
@@ -166,7 +174,7 @@ export function DossierPrefill(props: Props) {
|
||||
</p>
|
||||
)}
|
||||
{message && <p role="status">{message}</p>}
|
||||
{!!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)}/>}
|
||||
{!!chosenChoice && <OpportunityChoices 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)
|
||||
|
||||
@@ -72,6 +72,6 @@ export default function OpportunityChoices({choices, onChange, disabled = false,
|
||||
return <section className="space-y-4" aria-label="Oportunidades e respectivas localizações">
|
||||
<h2 className="text-xl font-bold">Oportunidades escolhidas e localização de cada ficha</h2>
|
||||
<p>{onChange?'Escolha o corredor e confirme onde pretende realizar o investimento.':'Escolhas guardadas no dossier; cada oportunidade conserva a sua localização e associações.'}</p>
|
||||
{choices.map((c,i)=><div key={c.opportunity.key}>{contextId&&!onChange&&<nav aria-label={"Preparar "+c.opportunity.title} className="flex gap-4"><Link className="underline" href={`/investidor/terra-duat/novo?context=${contextId}&opportunity=${encodeURIComponent(c.opportunity.key)}`}>Terra/DUAT desta oportunidade</Link><Link className="underline" href={`/balcao-virtual/dossiers/${contextId}?opportunity=${encodeURIComponent(c.opportunity.key)}`}>Balcão desta oportunidade</Link></nav>}<ChoiceCard contextId={contextId} key={c.opportunity.key} c={c} i={i} corridors={corridors} disabled={disabled} update={change=>update(i,change)} remove={onChange?()=>onChange(choices.filter((_,index)=>index!==i)):undefined}/></div>)}
|
||||
{choices.map((c,i)=><div key={c.opportunity.key}>{contextId&&!onChange&&<nav aria-label={"Preparar "+c.opportunity.title} className="flex gap-4"><Link className="underline" href={`/simulador-fiscal?context=${contextId}&opportunity=${encodeURIComponent(c.opportunity.key)}`}>Simular esta oportunidade</Link><Link className="underline" href={`/investimentos/${contextId}?opportunity=${encodeURIComponent(c.opportunity.key)}`}>Etapas e pedidos desta oportunidade</Link><Link className="underline" href={`/investidor/terra-duat/novo?context=${contextId}&opportunity=${encodeURIComponent(c.opportunity.key)}`}>Terra/DUAT desta oportunidade</Link><Link className="underline" href={`/balcao-virtual/dossiers/${contextId}?opportunity=${encodeURIComponent(c.opportunity.key)}`}>Balcão desta oportunidade</Link></nav>}<ChoiceCard contextId={contextId} key={c.opportunity.key} c={c} i={i} corridors={corridors} disabled={disabled} update={change=>update(i,change)} remove={onChange?()=>onChange(choices.filter((_,index)=>index!==i)):undefined}/></div>)}
|
||||
</section>;
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ export default function InvestmentRequirements({assessment, contextId, excludedS
|
||||
{[...groups.entries()].map(([key, rows])=><details key={key} className={card}><summary className="cursor-pointer font-semibold">{rows[0].opportunity_title} · {rows.length} aspectos a conferir</summary>{rows.map(r=><article key={r.opportunity_key+':'+r.code} className="my-3 space-y-2 border-t pt-3">
|
||||
<h3 className="font-semibold">{r.title} — {r.opportunity_title}</h3><p>{labels[r.state] ?? r.state}</p><p>Entidade: {r.authority}</p><p>{r.basis}</p>
|
||||
<ul className="list-disc pl-5">{r.documents.map(d=><li key={d}>{d}</li>)}</ul>
|
||||
<a className="underline" href={r.source_url}>Consultar fundamento e procedimento</a>{' · '}<Link className="underline" href={`/investimentos/${contextId}#${r.step}`}>Preparar e acompanhar em {r.step}</Link>
|
||||
<a className="underline" href={r.source_url}>Consultar fundamento e procedimento</a>{' · '}<Link className="underline" href={`/investimentos/${contextId}?opportunity=${encodeURIComponent(r.opportunity_key)}#${r.step}`}>Preparar e acompanhar em {r.step}</Link>
|
||||
<p>{r.decision}</p>
|
||||
</article>)}</details>)}
|
||||
</section>;
|
||||
|
||||
@@ -1564,7 +1564,7 @@ export function SimulationForm() {
|
||||
'Não foi possível devolver as entradas financeiras guardadas ao dossier.',
|
||||
);
|
||||
}
|
||||
window.location.assign(`/investimentos/${contextId}`);
|
||||
window.location.assign(`/investimentos/${contextId}${draft.context_opportunity ? "?opportunity="+encodeURIComponent(String(draft.context_opportunity)) : ""}`);
|
||||
} catch (cause) {
|
||||
setContinuityError(
|
||||
cause instanceof Error
|
||||
@@ -2522,7 +2522,7 @@ export function SimulationForm() {
|
||||
)}
|
||||
<a
|
||||
className="ml-3 underline"
|
||||
href={`/investimentos/${contextId}`}
|
||||
href={`/investimentos/${contextId}${draft.context_opportunity ? "?opportunity="+encodeURIComponent(String(draft.context_opportunity)) : ""}`}
|
||||
>
|
||||
Ver dossier
|
||||
</a>
|
||||
@@ -3292,7 +3292,7 @@ export function SimulationForm() {
|
||||
: investmentLandPreparation(draft.context_applicability_snapshot).need === 'yes'
|
||||
? 'Precisa de terra neste investimento. Reveja a situação do terreno já preenchida ou indique-a quando disponível.'
|
||||
: 'Falta definir se precisa de terra. Pode guardar o rascunho e continuar sem preencher a situação do terreno.'}</p>
|
||||
<a className="underline" href={`/investimentos/${contextId}`}>Rever a necessidade de terra no dossier</a>
|
||||
<a className="underline" href={`/investimentos/${contextId}${draft.context_opportunity ? "?opportunity="+encodeURIComponent(String(draft.context_opportunity)) : ""}`}>Rever a necessidade de terra no dossier</a>
|
||||
</aside>
|
||||
)}
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
|
||||
@@ -19,6 +19,7 @@ export const pathStates: Record<string, string> = {
|
||||
expired: 'Acto externo expirado',
|
||||
};
|
||||
export type PathResult = {
|
||||
context_opportunity?: string | null;
|
||||
id: string;
|
||||
financial_snapshot: string;
|
||||
currency: string | null;
|
||||
|
||||
@@ -284,6 +284,11 @@ function makeSections(
|
||||
);
|
||||
if (context.version === 1) {
|
||||
const section = sections.get('sources');
|
||||
if (context.consumer_opportunity) section?.rows.push({field:'Oportunidade em tratamento', value:context.consumer_opportunity, origin:context.opportunity_choices?.[0]?.opportunity?.title ?? 'Escolha guardada no dossier', classification:'Âmbito desta análise'});
|
||||
for (const step of context.path?.steps ?? []) {
|
||||
if (step.applicability === 'not_needed_for_preparation') section?.paragraphs.push(`${step.code} — preparação não necessária neste âmbito: ${step.reason || 'Decisão guardada do promotor'}. Histórico conservado; não constitui dispensa legal.`);
|
||||
else section?.rows.push({field:`Etapa ${step.code}: ${step.title}`,value:step.applicability === 'undetermined' ? 'Aplicabilidade por determinar' : step.state,origin:context.consumer_opportunity ?? 'Contexto comum do dossier',classification:'Preparação no âmbito seleccionado'});
|
||||
}
|
||||
const zone = context.zone;
|
||||
section?.rows.push({
|
||||
field: 'Contexto do investimento',
|
||||
|
||||
@@ -45,6 +45,8 @@ export default function Detail({
|
||||
</Link>
|
||||
<PartnershipSourceLinks type="investment" id={r.id} />
|
||||
{auth.user&&dossierContext&&<nav aria-label="Preparar esta oportunidade" className="flex flex-wrap gap-4">
|
||||
<Link className="underline" href={`/simulador-fiscal?context=${encodeURIComponent(dossierContext)}&opportunity=opportunity%3A${r.id}`}>Simular esta oportunidade</Link>
|
||||
<Link className="underline" href={`/investimentos/${encodeURIComponent(dossierContext)}?opportunity=opportunity%3A${r.id}`}>Etapas e pedidos desta oportunidade</Link>
|
||||
<Link className="underline" href={`/investidor/terra-duat/novo?context=${encodeURIComponent(dossierContext)}&opportunity=opportunity%3A${r.id}`}>Terra/DUAT desta oportunidade</Link>
|
||||
<Link className="underline" href={`/balcao-virtual/dossiers/${encodeURIComponent(dossierContext)}?opportunity=opportunity%3A${r.id}`}>Balcão desta oportunidade</Link>
|
||||
</nav>}
|
||||
|
||||
@@ -34,6 +34,8 @@ type Step = {
|
||||
source_paragraph: number;
|
||||
};
|
||||
type Path = {
|
||||
context_opportunity: string | null;
|
||||
opportunity_options: NonNullable<DossierContext['opportunity_choices']>;
|
||||
private_investment?: Preparation | null;
|
||||
fintech: FintechView | null;
|
||||
investment_context: DossierContext | null;
|
||||
@@ -94,6 +96,7 @@ function Result({ result }: { result: PathResult }) {
|
||||
const values = recoverPathResult(result);
|
||||
return (
|
||||
<li className="space-y-1 rounded border p-3">
|
||||
{result.context_opportunity && <p>Oportunidade desta análise: {result.context_opportunity}</p>}
|
||||
{result.context_state === 'review_required' && (
|
||||
<p
|
||||
role="status"
|
||||
@@ -139,6 +142,7 @@ function Result({ result }: { result: PathResult }) {
|
||||
function Stage({ step, path }: { step: Step; path: Path }) {
|
||||
const form = useForm({
|
||||
version: path.case.version,
|
||||
context_opportunity: path.context_opportunity,
|
||||
context_revision: path.investment_context?.revision ?? 0,
|
||||
context_reviewed: false,
|
||||
state: path.canWrite ? 'preparing' : 'reviewing',
|
||||
@@ -411,6 +415,7 @@ export default function InvestmentPath(path: Path) {
|
||||
}>().props;
|
||||
const facts = useForm({
|
||||
version: path.case.version,
|
||||
context_opportunity: path.context_opportunity,
|
||||
...path.facts,
|
||||
reason: '',
|
||||
});
|
||||
@@ -439,6 +444,13 @@ export default function InvestmentPath(path: Path) {
|
||||
Os meus investimentos
|
||||
</Link>
|
||||
<h1 className="text-2xl font-semibold">{path.case.title}</h1>
|
||||
{!!path.opportunity_options?.length && <label className="block rounded border p-4">Oportunidade em tratamento
|
||||
<select className="ml-2 rounded border p-2" value={path.context_opportunity ?? ''} onChange={event => router.get(`/investimentos/${path.case.id}`, event.target.value ? {opportunity:event.target.value} : {}, {preserveState:false})}>
|
||||
<option value="">Escolha a oportunidade</option>
|
||||
{path.opportunity_options.map(choice => <option key={choice.opportunity.key} value={choice.opportunity.key}>{choice.opportunity.title} — {choice.territory?.title ?? 'Localização por definir'}</option>)}
|
||||
</select>
|
||||
{!path.context_opportunity && path.opportunity_options.length > 1 && <p>Escolha para consultar as etapas, os requisitos e o pedido de terra correspondentes. Os dados comuns conservam-se.</p>}
|
||||
</label>}
|
||||
<ContextDocuments
|
||||
source={path.investment_context?.selection.opportunity}
|
||||
/>
|
||||
|
||||
Reference in New Issue
Block a user