Scope parks and downstream investment requests to the treated opportunity
This commit is contained in:
@@ -234,13 +234,16 @@ export function NavigationContextSummary() {
|
||||
return null;
|
||||
const saved = view?.investment_context;
|
||||
const ref = saved?.selection;
|
||||
const params = new URLSearchParams(url.split('?')[1] ?? '');
|
||||
const scopedChoice = saved?.opportunity_choices?.find(c=>c.opportunity.key===params.get('opportunity'));
|
||||
const multiple = (saved?.opportunity_choices?.length ?? 0)>1;
|
||||
const currentStep = view?.steps.find((s) => s.code === step);
|
||||
const sector =
|
||||
const sector = scopedChoice ? scopedChoice.opportunity.fields.sector || 'Não indicado' :
|
||||
ref?.sector?.title ||
|
||||
saved?.fields.sector ||
|
||||
view?.sector_contexts.map((s) => s.name).join(' · ') ||
|
||||
'Não indicado';
|
||||
const location =
|
||||
const location = scopedChoice ? scopedChoice.territory?.title || 'Por definir' : multiple ? 'Consulte a localização de cada oportunidade' :
|
||||
saved?.fields.location ||
|
||||
ref?.territory?.title ||
|
||||
ref?.park?.title ||
|
||||
@@ -260,7 +263,7 @@ export function NavigationContextSummary() {
|
||||
view?.case.title ||
|
||||
'Selecione um dossier',
|
||||
Oportunidade:
|
||||
ref?.opportunity?.title || 'Sem oportunidade associada',
|
||||
scopedChoice?.opportunity.title || (multiple ? 'Várias — oportunidade em tratamento no formulário' : ref?.opportunity?.title || 'Sem oportunidade associada'),
|
||||
Sector: sector,
|
||||
Localização: location,
|
||||
'Etapa atual': currentStep
|
||||
|
||||
@@ -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}>
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
export function InvestmentConsumerIdentity({raw}:{raw:unknown}) {
|
||||
if (typeof raw !== 'string' || !raw) return null;
|
||||
try {
|
||||
const saved=JSON.parse(raw);
|
||||
const c=saved.choice;
|
||||
if (!c?.opportunity?.key) return null;
|
||||
const states:Record<string,string>={selected:'Localização escolhida',missing:'Informação em falta',conditional:'Conforme as condições do projecto',declared:'Actividades declaradas',undetermined:'Por determinar'};
|
||||
return <section aria-label="Oportunidade associada ao pedido" className="my-3 rounded border p-3">
|
||||
<h2 className="font-semibold">Oportunidade associada ao pedido</h2>
|
||||
<p>{c.opportunity.title} · {c.opportunity.key}</p>
|
||||
<p>Localização guardada: {c.territory?.title??'Por definir'} · Corredor: {c.corridor_name??'Por definir'}</p>
|
||||
<p>Zona/parque: {c.park?.title??'Sem selecção'} · Revisão do dossier: {saved.revision}</p>
|
||||
{(saved.requirements?.requirements??[]).map((r:{code:string;title:string;state:string})=><p key={r.code}>{r.title} · {states[r.state]??'Por determinar'}</p>)}
|
||||
</section>;
|
||||
} catch {return null;}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { contextApi, type ContextReference } from '@/lib/investor-context';
|
||||
import { TerritoryFields } from './investment-territory';
|
||||
import type { OpportunityChoice } from '@/lib/investor-context';
|
||||
import { card, input } from '@/pages/investment/shared';
|
||||
@@ -7,8 +8,11 @@ import type { TerritoryOption } from './investment-territory';
|
||||
|
||||
export type CorridorOption = {key:string;name:string;provinces:TerritoryOption[]};
|
||||
|
||||
function ChoiceCard({c,i,corridors,disabled,update,remove}:{c:OpportunityChoice;i:number;corridors:CorridorOption[];disabled:boolean;update:(change:Partial<OpportunityChoice>)=>void;remove?:()=>void}) {
|
||||
function ChoiceCard({c,i,corridors,disabled,update,remove,contextId}:{c:OpportunityChoice;i:number;corridors:CorridorOption[];disabled:boolean;update:(change:Partial<OpportunityChoice>)=>void;remove?:()=>void;contextId?:string}) {
|
||||
const [notice,setNotice]=useState('');
|
||||
const [parks,setParks]=useState<{id:string;name:string;version_no:number}[]>([]);
|
||||
const [parkError,setParkError]=useState('');
|
||||
const [parkLoading,setParkLoading]=useState(false);
|
||||
const corridor=corridors.find(r=>r.key===c.corridor_key)||corridors.find(r=>r.name===c.coverage);
|
||||
const path=c.territory_path??[];
|
||||
function location(next:TerritoryOption[], key=corridor?.key) {
|
||||
@@ -21,8 +25,18 @@ function ChoiceCard({c,i,corridors,disabled,update,remove}:{c:OpportunityChoice;
|
||||
location(corridor.provinces.length===1?corridor.provinces:[]);
|
||||
} else if (!path.length && corridor.provinces.length===1) {setNotice('Província seleccionada automaticamente: '+corridor.provinces[0].name+'.');location(corridor.provinces);}
|
||||
},[corridor?.key,JSON.stringify(corridor?.provinces),path[0]?.id,!!remove]);
|
||||
useEffect(()=>{
|
||||
if (!remove || !corridor?.key) return;
|
||||
let active=true; setParkLoading(true);setParkError('');
|
||||
const params=new URLSearchParams(); if(corridor?.key)params.set('corridor',corridor.key);if(c.territory?.id)params.set('territory',c.territory.id);
|
||||
void contextApi<{parks:{id:string;name:string;version_no:number}[]}>('/investimentos/opcoes-corredor?'+params).then(data=>{
|
||||
if(!active)return;setParks(data.parks);
|
||||
if(c.park&&!data.parks.some(p=>'park:'+p.id===c.park?.key)) {update({park:null});setNotice('A zona ou parque desta oportunidade foi retirado por incompatibilidade com a localização escolhida. As restantes oportunidades conservaram-se.');}
|
||||
}).catch(e=>{if(active)setParkError(e.message)}).finally(()=>{if(active)setParkLoading(false)});
|
||||
return()=>{active=false};
|
||||
},[corridor?.key,c.territory?.id,!!remove]);
|
||||
return <article className={card+' space-y-3'}>
|
||||
<h3 className="font-semibold"><Link className="underline" href={c.opportunity.href}>{i+1}. {c.opportunity.title}</Link></h3>
|
||||
<h3 className="font-semibold"><Link className="underline" href={contextId ? `${c.opportunity.href}${c.opportunity.href.includes('?')?'&':'?'}context=${contextId}&opportunity=${encodeURIComponent(c.opportunity.key)}` : c.opportunity.href}>{i+1}. {c.opportunity.title}</Link></h3>
|
||||
{remove && <label className="block">Corredor para este investimento<select className={input} disabled={disabled||!corridors.length} value={corridor?.key??''} onChange={e=>{
|
||||
const next=corridors.find(r=>r.key===e.target.value);
|
||||
if(!next)return;
|
||||
@@ -31,11 +45,19 @@ function ChoiceCard({c,i,corridors,disabled,update,remove}:{c:OpportunityChoice;
|
||||
location(kept.length?kept:next.provinces.length===1?next.provinces:[],next.key);
|
||||
setNotice(!path.length?(next.provinces.length===1?'Província seleccionada automaticamente: '+next.provinces[0].name+'.':'Escolha uma das províncias deste corredor.'):compatible?'A localização compatível foi conservada.':'A província e os níveis territoriais incompatíveis foram retirados.');
|
||||
}}><option value="">Seleccione um corredor</option>{corridors.map(r=><option key={r.key} value={r.key}>{r.name}</option>)}</select></label>}
|
||||
{!remove&&c.coverage&&<p>Abrangência: {c.coverage}</p>}
|
||||
{!remove&&<p>Corredor escolhido: {c.corridor_name??'Por definir'}</p>}
|
||||
{!remove&&c.coverage&&c.coverage!==c.corridor_name&&<p>Referência documental de origem: {c.coverage}</p>}
|
||||
{notice&&<p role="status">{notice}</p>}
|
||||
<p>Localização: {c.territory?.title??'Por escolher'}</p>
|
||||
{!!c.portfolio_origins?.length && <section aria-label="Associações escolhidas"><h4 className="font-semibold">Associações escolhidas</h4><ul>{c.portfolio_origins.map(origin=><li key={origin.id}><Link className="underline" href={origin.href}>{origin.title}</Link>{remove&&<button type="button" className="ml-3 underline" disabled={disabled} onClick={()=>update({portfolio_origins:c.portfolio_origins?.filter(r=>r.id!==origin.id)})}>Retirar associação</button>}</li>)}</ul></section>}
|
||||
{c.park && !remove && <p>Zona/parque: <Link className="underline" href={c.park.href}>{c.park.title}</Link></p>}
|
||||
{remove&&<>
|
||||
<label className="block">Zona ou parque desta oportunidade<select className={input} disabled={disabled||parkLoading||!!parkError||!c.territory} value={c.park?.key??''} onChange={e=>{
|
||||
const p=parks.find(p=>'park:'+p.id===e.target.value);
|
||||
update({park:p?{key:'park:'+p.id,kind:'park',id:p.id,title:p.name,href:'/zonas/'+p.id,version:p.version_no,sha256:'',fields:{}} as ContextReference:null});
|
||||
}}><option value="">Sem zona ou parque seleccionado</option>{parks.map(p=><option key={p.id} value={'park:'+p.id}>{p.name}</option>)}</select></label>
|
||||
{parkError&&<p role="alert">{parkError}</p>}
|
||||
{!parkLoading&&!parkError&&<p>{!c.territory?'Escolha a localização desta oportunidade.':parks.length?'A consulta não confirma disponibilidade, admissão ou incentivos.':'Sem zona ou parque com enquadramento documentado nesta localização.'}</p>}
|
||||
<fieldset disabled={disabled}><legend>Actividades que pretende realizar nesta oportunidade</legend>{Object.entries({production:'Produção agrícola',processing:'Transformação agroindustrial',trade:'Comercialização e exportação',transport:'Transporte e logística',water:'Captação/utilização de água',forestry:'Actividade florestal',animal:'Produção/serviços pecuários'}).map(([key,label])=><label key={key} className="mr-4 inline-block"><input type="checkbox" checked={c.activities?.includes(key)??false} onChange={e=>update({activities:e.target.checked?[...(c.activities??[]),key]:(c.activities??[]).filter(x=>x!==key)})}/>{label}</label>)}</fieldset>
|
||||
<TerritoryFields initial={c.territory_path} corridor={corridor?.key} disabled={disabled} onChange={next=>location(next)}/>
|
||||
<label className="block">Motivo da alternativa territorial<textarea className={input} disabled={disabled} value={c.location_reason} onChange={e=>update({location_reason:e.target.value})}/></label>
|
||||
@@ -45,11 +67,11 @@ function ChoiceCard({c,i,corridors,disabled,update,remove}:{c:OpportunityChoice;
|
||||
</article>;
|
||||
}
|
||||
|
||||
export default function OpportunityChoices({choices, onChange, disabled = false, corridors=[]}: {choices: OpportunityChoice[]; onChange?: (choices: OpportunityChoice[]) => void; disabled?: boolean;corridors?:CorridorOption[]}) {
|
||||
export default function OpportunityChoices({choices, onChange, disabled = false, corridors=[], contextId}: {choices: OpportunityChoice[]; onChange?: (choices: OpportunityChoice[]) => void; disabled?: boolean;corridors?:CorridorOption[];contextId?:string}) {
|
||||
const update = (index: number, change: Partial<OpportunityChoice>) => onChange?.(choices.map((c,i) => i === index ? {...c,...change} : c));
|
||||
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)=><ChoiceCard 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}/>)}
|
||||
{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>)}
|
||||
</section>;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user