fix: complete InvesteMoz validation and error corrections
This commit is contained in:
@@ -3,7 +3,12 @@ import {
|
||||
PreparationImpact,
|
||||
} from '@/components/private-investment-preparation';
|
||||
import ContextDocuments from '@/components/context-documents';
|
||||
import InvestmentComplements, { SelectedComplements, complementInput, type Complement, type ComplementOption } from '@/components/investment-complements';
|
||||
import InvestmentComplements, {
|
||||
SelectedComplements,
|
||||
complementInput,
|
||||
type Complement,
|
||||
type ComplementOption,
|
||||
} from '@/components/investment-complements';
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Frame, button, card, input } from '@/pages/investment/shared';
|
||||
@@ -51,44 +56,119 @@ export default function ContextEditor({
|
||||
entrySources?: string[];
|
||||
entryComplements?: Complement[];
|
||||
entryTerritory?: ContextReference | null;
|
||||
entryLocationDifferences?: {title:string;saved:string;requested:string}[];
|
||||
draft?: {draft_sequence?:number;needs_review?:boolean;selection?:Partial<Record<Slot,string>>;declarations?:Record<string,string>;replace_fields?:string[];document_links?:Record<string,string|null>}|null;
|
||||
entryLocationDifferences?: {
|
||||
title: string;
|
||||
saved: string;
|
||||
requested: string;
|
||||
}[];
|
||||
draft?: {
|
||||
draft_sequence?: number;
|
||||
needs_review?: boolean;
|
||||
selection?: Partial<Record<Slot, string>>;
|
||||
declarations?: Record<string, string>;
|
||||
replace_fields?: string[];
|
||||
document_links?: Record<string, string | null>;
|
||||
} | null;
|
||||
}) {
|
||||
const navigation = useNavigationContext();
|
||||
const [complements, setComplements] = useState<Complement[]>(entryComplements);
|
||||
const [complementOptions, setComplementOptions] = useState<ComplementOption[]>([]);
|
||||
const [complements, setComplements] =
|
||||
useState<Complement[]>(entryComplements);
|
||||
const [complementOptions, setComplementOptions] = useState<
|
||||
ComplementOption[]
|
||||
>([]);
|
||||
const [complementError, setComplementError] = useState('');
|
||||
const [choices, setChoices] = useState<OpportunityChoice[]>(requestedChoices ?? initial.context.opportunity_choices ?? []);
|
||||
const [manageChoices, setManageChoices] = useState(requestedChoices !== null || !!initial.context.opportunity_choices?.length);
|
||||
const complementContexts = JSON.stringify([...choices.flatMap(c => [{origin:c.opportunity.key, territory_id:c.territory?.id ?? null}, ...(c.portfolio_origins ?? []).map(p => ({origin:'portfolio:'+p.id,territory_id:c.territory?.id ?? null}))]), ...complements.filter(c => c.origin.key.startsWith('portfolio:')).map(c => ({origin:c.origin.key,territory_id:c.territory_id}))].filter((c,i,all) => all.findIndex(other => other.origin === c.origin && other.territory_id === c.territory_id) === i));
|
||||
const [choices, setChoices] = useState<OpportunityChoice[]>(
|
||||
requestedChoices ?? initial.context.opportunity_choices ?? [],
|
||||
);
|
||||
const [manageChoices, setManageChoices] = useState(
|
||||
requestedChoices !== null ||
|
||||
!!initial.context.opportunity_choices?.length,
|
||||
);
|
||||
const complementContexts = JSON.stringify(
|
||||
[
|
||||
...choices.flatMap((c) => [
|
||||
{
|
||||
origin: c.opportunity.key,
|
||||
territory_id: c.territory?.id ?? null,
|
||||
},
|
||||
...(c.portfolio_origins ?? []).map((p) => ({
|
||||
origin: 'portfolio:' + p.id,
|
||||
territory_id: c.territory?.id ?? null,
|
||||
})),
|
||||
]),
|
||||
...complements
|
||||
.filter((c) => c.origin.key.startsWith('portfolio:'))
|
||||
.map((c) => ({
|
||||
origin: c.origin.key,
|
||||
territory_id: c.territory_id,
|
||||
})),
|
||||
].filter(
|
||||
(c, i, all) =>
|
||||
all.findIndex(
|
||||
(other) =>
|
||||
other.origin === c.origin &&
|
||||
other.territory_id === c.territory_id,
|
||||
) === i,
|
||||
),
|
||||
);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setComplementError(''); setComplementOptions([]);
|
||||
const contexts = JSON.parse(complementContexts) as {origin:string;territory_id:string|null}[];
|
||||
setComplementError('');
|
||||
setComplementOptions([]);
|
||||
const contexts = JSON.parse(complementContexts) as {
|
||||
origin: string;
|
||||
territory_id: string | null;
|
||||
}[];
|
||||
const load = async () => {
|
||||
const items: ComplementOption[] = [];
|
||||
const issues: string[] = [];
|
||||
for(let index=0;index<contexts.length;index+=100) {
|
||||
const result = await contextApi<{items:ComplementOption[];issues:{message:string}[]}>('/complementos-investimento', {contexts:contexts.slice(index,index+100)});
|
||||
items.push(...result.items);issues.push(...result.issues.map(issue => issue.message));
|
||||
if(!active) return;
|
||||
for (let index = 0; index < contexts.length; index += 100) {
|
||||
const result = await contextApi<{
|
||||
items: ComplementOption[];
|
||||
issues: { message: string }[];
|
||||
}>('/complementos-investimento', {
|
||||
contexts: contexts.slice(index, index + 100),
|
||||
});
|
||||
items.push(...result.items);
|
||||
issues.push(...result.issues.map((issue) => issue.message));
|
||||
if (!active) return;
|
||||
}
|
||||
if (active) {
|
||||
setComplementOptions(items);
|
||||
setComplementError([...new Set(issues)].join(' '));
|
||||
}
|
||||
if(active) {setComplementOptions(items);setComplementError([...new Set(issues)].join(' '));}
|
||||
};
|
||||
void load().catch(e => {if(active) setComplementError(e.message);});
|
||||
return () => {active=false;};
|
||||
void load().catch((e) => {
|
||||
if (active) setComplementError(e.message);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [complementContexts]);
|
||||
const [view, setView] = useState(initial);
|
||||
const [preparation, setPreparation] = useState(initial.private_investment);
|
||||
const [options, setOptions] = useState(initialOptions);
|
||||
const [query, setQuery] = useState('');
|
||||
const [changes, setChanges] = useState<Partial<Record<Slot, string>>>(() =>
|
||||
({...(draft?.selection ?? {}), ...(entryTerritory && !draft?.selection?.territory && !initial.context.selection.territory ? {territory: entryTerritory.key} : {}), ...(source?.kind === 'portfolio' ? {portfolio: source.key} : draft?.selection ? {} : source
|
||||
? {
|
||||
[source.kind === 'business' ? 'opportunity' : source.kind]:
|
||||
source.key,
|
||||
}
|
||||
: {})}),
|
||||
const [changes, setChanges] = useState<Partial<Record<Slot, string>>>(
|
||||
() => ({
|
||||
...draft?.selection,
|
||||
...(entryTerritory &&
|
||||
!draft?.selection?.territory &&
|
||||
!initial.context.selection.territory
|
||||
? { territory: entryTerritory.key }
|
||||
: {}),
|
||||
...(source?.kind === 'portfolio'
|
||||
? { portfolio: source.key }
|
||||
: draft?.selection
|
||||
? {}
|
||||
: source
|
||||
? {
|
||||
[source.kind === 'business'
|
||||
? 'opportunity'
|
||||
: source.kind]: source.key,
|
||||
}
|
||||
: {}),
|
||||
}),
|
||||
);
|
||||
const [declarations, setDeclarations] = useState<Record<string, string>>(
|
||||
draft?.declarations ?? {},
|
||||
@@ -96,58 +176,160 @@ export default function ContextEditor({
|
||||
const [documentLinks, setDocumentLinks] = useState<
|
||||
Record<string, string | null>
|
||||
>(draft?.document_links ?? {});
|
||||
const [replace, setReplace] = useState<string[]>(draft?.replace_fields ?? []);
|
||||
const [replace, setReplace] = useState<string[]>(
|
||||
draft?.replace_fields ?? [],
|
||||
);
|
||||
const [plan, setPlan] = useState<ContextPlan | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [message, setMessage] = useState('');
|
||||
const [corridors,setCorridors]=useState<CorridorOption[]>([]);
|
||||
const [parks,setParks]=useState<Options['parks']>([]);
|
||||
const [corridorLoading,setCorridorLoading]=useState(true);
|
||||
const [corridorError,setCorridorError]=useState('');
|
||||
const [corridorRetry,setCorridorRetry]=useState(0);
|
||||
const [draftStatus,setDraftStatus]=useState('');
|
||||
const [draftRetry,setDraftRetry]=useState(0);
|
||||
const queue=useRef<Promise<unknown>>(Promise.resolve());
|
||||
const firstCorridor=choices[0]?.corridor_key ?? corridors.find(c=>c.name===choices[0]?.coverage)?.key;
|
||||
const firstTerritory=choices[0]?.territory?.id;
|
||||
useEffect(()=>{
|
||||
let active=true;setCorridorLoading(true);setCorridorError('');
|
||||
const params=new URLSearchParams();if(firstCorridor)params.set('corridor',firstCorridor);if(firstTerritory)params.set('territory',firstTerritory);
|
||||
void contextApi<{corridors:CorridorOption[];parks:Options['parks']}>('/investimentos/opcoes-corredor?'+params).then(data=>{
|
||||
if(!active)return;setCorridors(data.corridors);setParks(data.parks);
|
||||
const park=Object.hasOwn(changes,'park')?changes.park:view.context.selection.park?.key;
|
||||
if(!manageChoices&&firstCorridor&&park&&!data.parks.some(p=>'park:'+p.id===park)){
|
||||
setChanges(old=>({...old,park:''}));setPlan(null);setMessage('A zona ou parque anterior foi retirado porque não tem enquadramento compatível com a localização escolhida.');
|
||||
}
|
||||
}).catch(e=>{if(active)setCorridorError(e.message)}).finally(()=>{if(active)setCorridorLoading(false)});
|
||||
return()=>{active=false};
|
||||
},[firstCorridor,firstTerritory,corridorRetry]);
|
||||
const draftBody=JSON.stringify({complements:complements.map(complementInput),entry_sources:entrySources,version:view.case.version,selection:changes,declarations,replace_fields:replace,document_links:documentLinks,
|
||||
...(manageChoices?{opportunity_choices:choices.map(c=>({source:c.opportunity.key,park:c.park?.key??null,portfolio_origins:(c.portfolio_origins??[]).map(r=>r.id),corridor_key:c.corridor_key,territory:c.territory?.key??null,location_reason:c.location_reason,confirm_location_change:!!c.confirm_location_change,activities:c.activities??[]}))}:{})});
|
||||
const latestDraft=useRef(draftBody);latestDraft.current=draftBody;
|
||||
const skipNextDraft=useRef(false);
|
||||
const confirmedDraftBody=useRef<string|null>(null);
|
||||
const sequence=useRef({body:'',value:Math.max(Date.now(),draft?.draft_sequence??0)});
|
||||
if(sequence.current.body!==draftBody)sequence.current={body:draftBody,value:Math.max(Date.now(),sequence.current.value+1)};
|
||||
useEffect(()=>{
|
||||
if(busy||corridorLoading||corridorError)return;
|
||||
if(skipNextDraft.current){skipNextDraft.current=false;confirmedDraftBody.current=draftBody;setDraftStatus('Dados confirmados.');return;}
|
||||
if(draftBody===confirmedDraftBody.current)return;
|
||||
const [corridors, setCorridors] = useState<CorridorOption[]>([]);
|
||||
const [parks, setParks] = useState<Options['parks']>([]);
|
||||
const [corridorLoading, setCorridorLoading] = useState(true);
|
||||
const [corridorError, setCorridorError] = useState('');
|
||||
const [corridorRetry, setCorridorRetry] = useState(0);
|
||||
const [draftStatus, setDraftStatus] = useState('');
|
||||
const [draftRetry, setDraftRetry] = useState(0);
|
||||
const queue = useRef<Promise<unknown>>(Promise.resolve());
|
||||
const firstCorridor =
|
||||
choices[0]?.corridor_key ??
|
||||
corridors.find((c) => c.name === choices[0]?.coverage)?.key;
|
||||
const firstTerritory = choices[0]?.territory?.id;
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setCorridorLoading(true);
|
||||
setCorridorError('');
|
||||
const params = new URLSearchParams();
|
||||
if (firstCorridor) params.set('corridor', firstCorridor);
|
||||
if (firstTerritory) params.set('territory', firstTerritory);
|
||||
void contextApi<{
|
||||
corridors: CorridorOption[];
|
||||
parks: Options['parks'];
|
||||
}>('/investimentos/opcoes-corredor?' + params)
|
||||
.then((data) => {
|
||||
if (!active) return;
|
||||
setCorridors(data.corridors);
|
||||
setParks(data.parks);
|
||||
const park = Object.hasOwn(changes, 'park')
|
||||
? changes.park
|
||||
: view.context.selection.park?.key;
|
||||
if (
|
||||
!manageChoices &&
|
||||
firstCorridor &&
|
||||
park &&
|
||||
!data.parks.some((p) => 'park:' + p.id === park)
|
||||
) {
|
||||
setChanges((old) => ({ ...old, park: '' }));
|
||||
setPlan(null);
|
||||
setMessage(
|
||||
'A zona ou parque anterior foi retirado porque não tem enquadramento compatível com a localização escolhida.',
|
||||
);
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
if (active) setCorridorError(e.message);
|
||||
})
|
||||
.finally(() => {
|
||||
if (active) setCorridorLoading(false);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [firstCorridor, firstTerritory, corridorRetry]);
|
||||
const draftBody = JSON.stringify({
|
||||
complements: complements.map(complementInput),
|
||||
entry_sources: entrySources,
|
||||
version: view.case.version,
|
||||
selection: changes,
|
||||
declarations,
|
||||
replace_fields: replace,
|
||||
document_links: documentLinks,
|
||||
...(manageChoices
|
||||
? {
|
||||
opportunity_choices: choices.map((c) => ({
|
||||
source: c.opportunity.key,
|
||||
park: c.park?.key ?? null,
|
||||
portfolio_origins: (c.portfolio_origins ?? []).map(
|
||||
(r) => r.id,
|
||||
),
|
||||
corridor_key: c.corridor_key,
|
||||
territory: c.territory?.key ?? null,
|
||||
location_reason: c.location_reason,
|
||||
confirm_location_change: !!c.confirm_location_change,
|
||||
activities: c.activities ?? [],
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
const latestDraft = useRef(draftBody);
|
||||
latestDraft.current = draftBody;
|
||||
const skipNextDraft = useRef(false);
|
||||
const confirmedDraftBody = useRef<string | null>(null);
|
||||
const sequence = useRef({
|
||||
body: '',
|
||||
value: Math.max(Date.now(), draft?.draft_sequence ?? 0),
|
||||
});
|
||||
if (sequence.current.body !== draftBody)
|
||||
sequence.current = {
|
||||
body: draftBody,
|
||||
value: Math.max(Date.now(), sequence.current.value + 1),
|
||||
};
|
||||
useEffect(() => {
|
||||
if (busy || corridorLoading || corridorError) return;
|
||||
if (skipNextDraft.current) {
|
||||
skipNextDraft.current = false;
|
||||
confirmedDraftBody.current = draftBody;
|
||||
setDraftStatus('Dados confirmados.');
|
||||
return;
|
||||
}
|
||||
if (draftBody === confirmedDraftBody.current) return;
|
||||
setDraftStatus('A guardar rascunho…');
|
||||
const timer=setTimeout(()=>{
|
||||
const savedSequence=sequence.current.value;
|
||||
queue.current=queue.current.catch(()=>{}).then(()=>contextApi('/investimentos/'+view.case.id+'/contexto/rascunho',{...JSON.parse(draftBody),draft_sequence:savedSequence},'POST',draftBody.length<60000))
|
||||
.then(()=>{if(latestDraft.current===draftBody)setDraftStatus('Rascunho guardado.');})
|
||||
.catch(e=>{if(latestDraft.current===draftBody)setDraftStatus('Rascunho não guardado: '+e.message)});
|
||||
},400);
|
||||
return()=>clearTimeout(timer);
|
||||
},[draftBody,busy,corridorLoading,corridorError,draftRetry]);
|
||||
useEffect(()=>{
|
||||
const flush=()=>{const body=latestDraft.current;if(body!==confirmedDraftBody.current&&body.length<60000)void contextApi('/investimentos/'+initial.case.id+'/contexto/rascunho',{...JSON.parse(body),draft_sequence:sequence.current.value},'POST',true).catch(()=>{});};
|
||||
window.addEventListener('pagehide',flush);
|
||||
return()=>{window.removeEventListener('pagehide',flush);flush();};
|
||||
},[initial.case.id]);
|
||||
const timer = setTimeout(() => {
|
||||
const savedSequence = sequence.current.value;
|
||||
queue.current = queue.current
|
||||
.catch(() => {})
|
||||
.then(() =>
|
||||
contextApi(
|
||||
'/investimentos/' + view.case.id + '/contexto/rascunho',
|
||||
{
|
||||
...JSON.parse(draftBody),
|
||||
draft_sequence: savedSequence,
|
||||
},
|
||||
'POST',
|
||||
draftBody.length < 60000,
|
||||
),
|
||||
)
|
||||
.then(() => {
|
||||
if (latestDraft.current === draftBody)
|
||||
setDraftStatus('Rascunho guardado.');
|
||||
})
|
||||
.catch((e) => {
|
||||
if (latestDraft.current === draftBody)
|
||||
setDraftStatus('Rascunho não guardado: ' + e.message);
|
||||
});
|
||||
}, 400);
|
||||
return () => clearTimeout(timer);
|
||||
}, [draftBody, busy, corridorLoading, corridorError, draftRetry]);
|
||||
useEffect(() => {
|
||||
const flush = () => {
|
||||
const body = latestDraft.current;
|
||||
if (body !== confirmedDraftBody.current && body.length < 60000)
|
||||
void contextApi(
|
||||
'/investimentos/' + initial.case.id + '/contexto/rascunho',
|
||||
{
|
||||
...JSON.parse(body),
|
||||
draft_sequence: sequence.current.value,
|
||||
},
|
||||
'POST',
|
||||
true,
|
||||
).catch(() => {});
|
||||
};
|
||||
window.addEventListener('pagehide', flush);
|
||||
return () => {
|
||||
window.removeEventListener('pagehide', flush);
|
||||
flush();
|
||||
};
|
||||
}, [initial.case.id]);
|
||||
const [operation, setOperation] = useState(createOperationKey);
|
||||
const [requestBody, setRequestBody] = useState<Record<
|
||||
string,
|
||||
@@ -194,7 +376,22 @@ export default function ContextEditor({
|
||||
setMessage('');
|
||||
const body = {
|
||||
complements: complements.map(complementInput),
|
||||
...(manageChoices ? {opportunity_choices: choices.map(c => ({source:c.opportunity.key,park:c.park?.key??null,portfolio_origins:(c.portfolio_origins??[]).map(r=>r.id),corridor_key:c.corridor_key,territory:c.territory?.key ?? null,location_reason:c.location_reason,confirm_location_change:!!c.confirm_location_change,activities:c.activities??[]}))} : {}),
|
||||
...(manageChoices
|
||||
? {
|
||||
opportunity_choices: choices.map((c) => ({
|
||||
source: c.opportunity.key,
|
||||
park: c.park?.key ?? null,
|
||||
portfolio_origins: (c.portfolio_origins ?? []).map(
|
||||
(r) => r.id,
|
||||
),
|
||||
corridor_key: c.corridor_key,
|
||||
territory: c.territory?.key ?? null,
|
||||
location_reason: c.location_reason,
|
||||
confirm_location_change: !!c.confirm_location_change,
|
||||
activities: c.activities ?? [],
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
version: view.case.version,
|
||||
selection: changes,
|
||||
declarations,
|
||||
@@ -222,7 +419,7 @@ export default function ContextEditor({
|
||||
async function confirm() {
|
||||
if (!plan || !requestBody) return;
|
||||
setBusy(true);
|
||||
await queue.current.catch(()=>{});
|
||||
await queue.current.catch(() => {});
|
||||
setError('');
|
||||
try {
|
||||
await contextApi(
|
||||
@@ -237,9 +434,13 @@ export default function ContextEditor({
|
||||
const next = await contextApi<ContextView>(
|
||||
`/investimentos/${view.case.id}/contexto`,
|
||||
);
|
||||
skipNextDraft.current=true;
|
||||
skipNextDraft.current = true;
|
||||
// The entry has been consumed: refreshing must recover saved choices, not reapply a removed association.
|
||||
window.history.replaceState(window.history.state, '', `/investimentos/${view.case.id}/contexto/editar${window.location.hash}`);
|
||||
window.history.replaceState(
|
||||
window.history.state,
|
||||
'',
|
||||
`/investimentos/${view.case.id}/contexto/editar${window.location.hash}`,
|
||||
);
|
||||
setView(next);
|
||||
setChoices(next.context.opportunity_choices ?? []);
|
||||
setComplements(next.context.complements ?? []);
|
||||
@@ -273,23 +474,76 @@ export default function ContextEditor({
|
||||
>
|
||||
Voltar ao dossier
|
||||
</Link>
|
||||
<p>{view.case.title}</p>
|
||||
<p>
|
||||
{view.case.title}
|
||||
Confirme as oportunidades e a localização, complete os dados
|
||||
disponíveis e reveja antes de guardar.
|
||||
</p>
|
||||
<p>Confirme as oportunidades e a localização, complete os dados disponíveis e reveja antes de guardar.</p>
|
||||
<SelectedComplements items={complements} onRemove={busy ? undefined : key => {setComplements(items => items.filter(item => item.key !== key));setPlan(null);}}/>
|
||||
{complementError && <p role="alert">{complementError} As escolhas anteriores foram conservadas.</p>}
|
||||
<InvestmentComplements items={complementOptions} dossierId={view.case.id} onNavigate={async href => {
|
||||
if(busy) return;
|
||||
setBusy(true);setError('');
|
||||
try {
|
||||
await queue.current.catch(()=>{});
|
||||
await contextApi('/investimentos/'+view.case.id+'/contexto/rascunho', {...JSON.parse(latestDraft.current), draft_sequence:++sequence.current.value}, 'POST');
|
||||
router.visit(href);
|
||||
} catch(e) {setError(e instanceof Error ? e.message : 'Não foi possível conservar as escolhas antes de abrir o complemento.');}
|
||||
finally {setBusy(false);}
|
||||
}}/>
|
||||
{!!entryLocationDifferences.length && <aside className="rounded border border-amber-500 p-3" aria-label="Localização anterior conservada">{entryLocationDifferences.map(row=><p key={row.title}>{row.title}: a localização recebida ({row.requested}) não substituiu a escolha guardada ({row.saved}). Pode rever a localização abaixo antes de confirmar.</p>)}</aside>}
|
||||
<SelectedComplements
|
||||
items={complements}
|
||||
onRemove={
|
||||
busy
|
||||
? undefined
|
||||
: (key) => {
|
||||
setComplements((items) =>
|
||||
items.filter((item) => item.key !== key),
|
||||
);
|
||||
setPlan(null);
|
||||
}
|
||||
}
|
||||
/>
|
||||
{complementError && (
|
||||
<p role="alert">
|
||||
{complementError} As escolhas anteriores foram
|
||||
conservadas.
|
||||
</p>
|
||||
)}
|
||||
<InvestmentComplements
|
||||
items={complementOptions}
|
||||
dossierId={view.case.id}
|
||||
onNavigate={async (href) => {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
await queue.current.catch(() => {});
|
||||
await contextApi(
|
||||
'/investimentos/' +
|
||||
view.case.id +
|
||||
'/contexto/rascunho',
|
||||
{
|
||||
...JSON.parse(latestDraft.current),
|
||||
draft_sequence: ++sequence.current.value,
|
||||
},
|
||||
'POST',
|
||||
);
|
||||
router.visit(href);
|
||||
} catch (e) {
|
||||
setError(
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Não foi possível conservar as escolhas antes de abrir o complemento.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{!!entryLocationDifferences.length && (
|
||||
<aside
|
||||
className="rounded border border-amber-500 p-3"
|
||||
aria-label="Localização anterior conservada"
|
||||
>
|
||||
{entryLocationDifferences.map((row) => (
|
||||
<p key={row.title}>
|
||||
{row.title}: a localização recebida (
|
||||
{row.requested}) não substituiu a escolha
|
||||
guardada ({row.saved}). Pode rever a localização
|
||||
abaixo antes de confirmar.
|
||||
</p>
|
||||
))}
|
||||
</aside>
|
||||
)}
|
||||
{error && (
|
||||
<div
|
||||
role="alert"
|
||||
@@ -307,23 +561,149 @@ export default function ContextEditor({
|
||||
)}
|
||||
{message && <p role="status">{message}</p>}
|
||||
<section className={card + ' space-y-4'}>
|
||||
{corridorError&&<p role="alert">{corridorError} <button className="underline" onClick={()=>setCorridorRetry(v=>v+1)}>Tentar novamente</button></p>}
|
||||
{corridorLoading&&<p role="status">A carregar opções do corredor…</p>}
|
||||
{corridorError && (
|
||||
<p role="alert">
|
||||
{corridorError}{' '}
|
||||
<button
|
||||
className="underline"
|
||||
onClick={() => setCorridorRetry((v) => v + 1)}
|
||||
>
|
||||
Tentar novamente
|
||||
</button>
|
||||
</p>
|
||||
)}
|
||||
{corridorLoading && (
|
||||
<p role="status">A carregar opções do corredor…</p>
|
||||
)}
|
||||
<p role="status">{draftStatus}</p>
|
||||
{draft?.needs_review&&<p role="status">O rascunho foi recuperado, mas o dossier recebeu outras alterações. Reveja os dados antes de confirmar.</p>}
|
||||
{draftStatus.startsWith('Rascunho não guardado')&&<button type="button" className="underline" onClick={()=>setDraftRetry(v=>v+1)}>Tentar guardar novamente</button>}
|
||||
<OpportunityChoices corridors={corridors} choices={choices} disabled={busy||corridorLoading||!!corridorError} onChange={next=>{setChoices(next);setManageChoices(true);setPlan(null);}}/>
|
||||
{(changes.portfolio || view.context.selection.portfolio) && <p className="rounded border p-3">
|
||||
Origem documental: <a className="underline" href={source?.kind === 'portfolio' ? source.href : view.context.selection.portfolio?.href}>{source?.kind === 'portfolio' ? source.title : view.context.selection.portfolio?.title}</a>.
|
||||
{' '}A ficha é conservada como origem. Escolha o sector e a localização do investimento abaixo; a cobertura documental não é uma implantação atribuída.
|
||||
</p>}
|
||||
{entryTerritory && view.context.selection.territory && entryTerritory.key !== view.context.selection.territory.key && <p role="status">A pesquisa indicava {entryTerritory.title}. Conservou-se a localização guardada, {view.context.selection.territory.title}; pode alterá-la explicitamente abaixo e conferir os impactos.</p>}
|
||||
<ContextDocuments source={source ?? view.context.selection.opportunity} />
|
||||
{view.context.revision > 0 && !Object.keys(changes).length && JSON.stringify(choices) === JSON.stringify(view.context.opportunity_choices ?? []) && <InvestmentRequirements assessment={view.context.requirements_assessment} contextId={view.case.id}/>}
|
||||
<label className="block">Acrescentar uma oportunidade à escolha<select className={input} value="" onChange={e=>{const o=options.opportunities.find(o=>o.key===e.target.value);if(o && !choices.some(c=>c.opportunity.key===o.key)){setChoices([...choices,{opportunity:{...o,id:o.key.split(':')[1],href:'/oportunidades',version:null,sha256:'',fields:{}},territory:null,location_reason:'',location_state:'undetermined'}]);setManageChoices(true);setPlan(null);}}}><option value="">Seleccionar ficha</option>{options.opportunities.filter(o=>o.kind==='opportunity'&&!choices.some(c=>c.opportunity.key===o.key)).map(o=><option key={o.key} value={o.key}>{o.title}</option>)}</select></label>
|
||||
<h2 className="text-xl font-bold">
|
||||
Dados do investimento
|
||||
</h2>
|
||||
{draft?.needs_review && (
|
||||
<p role="status">
|
||||
O rascunho foi recuperado, mas o dossier recebeu
|
||||
outras alterações. Reveja os dados antes de
|
||||
confirmar.
|
||||
</p>
|
||||
)}
|
||||
{draftStatus.startsWith('Rascunho não guardado') && (
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() => setDraftRetry((v) => v + 1)}
|
||||
>
|
||||
Tentar guardar novamente
|
||||
</button>
|
||||
)}
|
||||
<OpportunityChoices
|
||||
corridors={corridors}
|
||||
choices={choices}
|
||||
disabled={busy || corridorLoading || !!corridorError}
|
||||
onChange={(next) => {
|
||||
setChoices(next);
|
||||
setManageChoices(true);
|
||||
setPlan(null);
|
||||
}}
|
||||
/>
|
||||
{(changes.portfolio ||
|
||||
view.context.selection.portfolio) && (
|
||||
<p className="rounded border p-3">
|
||||
Origem documental:{' '}
|
||||
<a
|
||||
className="underline"
|
||||
href={
|
||||
source?.kind === 'portfolio'
|
||||
? source.href
|
||||
: view.context.selection.portfolio?.href
|
||||
}
|
||||
>
|
||||
{source?.kind === 'portfolio'
|
||||
? source.title
|
||||
: view.context.selection.portfolio?.title}
|
||||
</a>
|
||||
. A ficha é conservada como origem. Escolha o sector
|
||||
e a localização do investimento abaixo; a cobertura
|
||||
documental não é uma implantação atribuída.
|
||||
</p>
|
||||
)}
|
||||
{entryTerritory &&
|
||||
view.context.selection.territory &&
|
||||
entryTerritory.key !==
|
||||
view.context.selection.territory.key && (
|
||||
<p role="status">
|
||||
A pesquisa indicava {entryTerritory.title}.
|
||||
Conservou-se a localização guardada,{' '}
|
||||
{view.context.selection.territory.title}; pode
|
||||
alterá-la explicitamente abaixo e conferir os
|
||||
impactos.
|
||||
</p>
|
||||
)}
|
||||
<ContextDocuments
|
||||
source={source ?? view.context.selection.opportunity}
|
||||
/>
|
||||
{view.context.revision > 0 &&
|
||||
!Object.keys(changes).length &&
|
||||
JSON.stringify(choices) ===
|
||||
JSON.stringify(
|
||||
view.context.opportunity_choices ?? [],
|
||||
) && (
|
||||
<InvestmentRequirements
|
||||
assessment={
|
||||
view.context.requirements_assessment
|
||||
}
|
||||
contextId={view.case.id}
|
||||
/>
|
||||
)}
|
||||
<label className="block">
|
||||
Acrescentar uma oportunidade à escolha
|
||||
<select
|
||||
className={input}
|
||||
value=""
|
||||
onChange={(e) => {
|
||||
const o = options.opportunities.find(
|
||||
(o) => o.key === e.target.value,
|
||||
);
|
||||
if (
|
||||
o &&
|
||||
!choices.some(
|
||||
(c) => c.opportunity.key === o.key,
|
||||
)
|
||||
) {
|
||||
setChoices([
|
||||
...choices,
|
||||
{
|
||||
opportunity: {
|
||||
...o,
|
||||
id: o.key.split(':')[1],
|
||||
href: '/oportunidades',
|
||||
version: null,
|
||||
sha256: '',
|
||||
fields: {},
|
||||
},
|
||||
territory: null,
|
||||
location_reason: '',
|
||||
location_state: 'undetermined',
|
||||
},
|
||||
]);
|
||||
setManageChoices(true);
|
||||
setPlan(null);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="">Seleccionar ficha</option>
|
||||
{options.opportunities
|
||||
.filter(
|
||||
(o) =>
|
||||
o.kind === 'opportunity' &&
|
||||
!choices.some(
|
||||
(c) => c.opportunity.key === o.key,
|
||||
),
|
||||
)
|
||||
.map((o) => (
|
||||
<option key={o.key} value={o.key}>
|
||||
{o.title}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<h2 className="text-xl font-bold">Dados do investimento</h2>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<label className="min-w-0 flex-1">
|
||||
Pesquisar oportunidades
|
||||
@@ -441,49 +821,81 @@ export default function ContextEditor({
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{!manageChoices && <><label className="grid min-w-0 gap-1">
|
||||
{choices.length>1?'Zona ou parque da primeira oportunidade':'ZEE, ZFI ou parque consultado'}
|
||||
<select
|
||||
className={input + ' max-w-full min-w-0'}
|
||||
disabled={busy||corridorLoading||!!corridorError||(!!firstCorridor&&!firstTerritory)}
|
||||
value={selected('park')}
|
||||
onChange={(e) => change('park', e.target.value)}
|
||||
>
|
||||
<option value="">
|
||||
Sem ZEE, ZFI ou parque seleccionado
|
||||
</option>
|
||||
{(firstCorridor?parks:options.parks).map((p) => (
|
||||
<option key={p.id} value={'park:' + p.id}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{firstCorridor&&!corridorLoading&&!corridorError&&<p>{!firstTerritory?'Escolha a localização para consultar zonas e parques.':!parks.length?'Não existem zonas ou parques com enquadramento documentado compatível nesta localização.':'A consulta não confirma disponibilidade de lotes, admissão ou incentivos.'}</p>}
|
||||
</>}
|
||||
{!manageChoices&&<><h3 className="font-semibold">
|
||||
Localização — escolher até ao nível conhecido
|
||||
</h3>
|
||||
<TerritoryFields
|
||||
initial={territorySelection}
|
||||
disabled={busy || manageChoices}
|
||||
endpoint="/api/v1/investment/territory-options"
|
||||
onChange={(path) =>
|
||||
change(
|
||||
'territory',
|
||||
path.length
|
||||
? 'territory:' + path[path.length - 1].id
|
||||
: '',
|
||||
)
|
||||
}
|
||||
/>
|
||||
{view.context.selection.territory && (
|
||||
<p>
|
||||
Referência guardada:{' '}
|
||||
{view.context.selection.territory.title}
|
||||
</p>
|
||||
{!manageChoices && (
|
||||
<>
|
||||
<label className="grid min-w-0 gap-1">
|
||||
{choices.length > 1
|
||||
? 'Zona ou parque da primeira oportunidade'
|
||||
: 'ZEE, ZFI ou parque consultado'}
|
||||
<select
|
||||
className={input + ' max-w-full min-w-0'}
|
||||
disabled={
|
||||
busy ||
|
||||
corridorLoading ||
|
||||
!!corridorError ||
|
||||
(!!firstCorridor && !firstTerritory)
|
||||
}
|
||||
value={selected('park')}
|
||||
onChange={(e) =>
|
||||
change('park', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Sem ZEE, ZFI ou parque seleccionado
|
||||
</option>
|
||||
{(firstCorridor
|
||||
? parks
|
||||
: options.parks
|
||||
).map((p) => (
|
||||
<option
|
||||
key={p.id}
|
||||
value={'park:' + p.id}
|
||||
>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{firstCorridor &&
|
||||
!corridorLoading &&
|
||||
!corridorError && (
|
||||
<p>
|
||||
{!firstTerritory
|
||||
? 'Escolha a localização para consultar zonas e parques.'
|
||||
: !parks.length
|
||||
? 'Não existem zonas ou parques com enquadramento documentado compatível nesta localização.'
|
||||
: 'A consulta não confirma disponibilidade de lotes, admissão ou incentivos.'}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{!manageChoices && (
|
||||
<>
|
||||
<h3 className="font-semibold">
|
||||
Localização — escolher até ao nível conhecido
|
||||
</h3>
|
||||
<TerritoryFields
|
||||
initial={territorySelection}
|
||||
disabled={busy || manageChoices}
|
||||
endpoint="/api/v1/investment/territory-options"
|
||||
onChange={(path) =>
|
||||
change(
|
||||
'territory',
|
||||
path.length
|
||||
? 'territory:' +
|
||||
path[path.length - 1].id
|
||||
: '',
|
||||
)
|
||||
}
|
||||
/>
|
||||
{view.context.selection.territory && (
|
||||
<p>
|
||||
Referência guardada:{' '}
|
||||
{view.context.selection.territory.title}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>}
|
||||
</section>
|
||||
<section className={card + ' space-y-3'}>
|
||||
<h2 className="text-xl font-bold">
|
||||
@@ -687,9 +1099,16 @@ export default function ContextEditor({
|
||||
<h2 className="text-xl font-bold">
|
||||
Comparação antes da confirmação
|
||||
</h2>
|
||||
{!!plan.opportunity_choices?.length && <OpportunityChoices choices={plan.opportunity_choices}/>}
|
||||
<SelectedComplements items={plan.complements ?? []}/>
|
||||
<InvestmentRequirements assessment={plan.requirements_assessment} contextId={view.case.id}/>
|
||||
{!!plan.opportunity_choices?.length && (
|
||||
<OpportunityChoices
|
||||
choices={plan.opportunity_choices}
|
||||
/>
|
||||
)}
|
||||
<SelectedComplements items={plan.complements ?? []} />
|
||||
<InvestmentRequirements
|
||||
assessment={plan.requirements_assessment}
|
||||
contextId={view.case.id}
|
||||
/>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-[36rem] table-fixed text-left">
|
||||
<thead>
|
||||
@@ -706,15 +1125,23 @@ export default function ContextEditor({
|
||||
<td className="p-2">
|
||||
{plan.documents_preserved}{' '}
|
||||
documentos.{' '}
|
||||
{plan.maintained.filter(x=>!x.field.endsWith('_id')).map((x) => (
|
||||
<p key={x.field}>
|
||||
{contextFieldNames[
|
||||
x.field
|
||||
] ?? x.field}
|
||||
: conserva «{x.value}»; a
|
||||
fonte propõe «{x.proposed}».
|
||||
</p>
|
||||
))}
|
||||
{plan.maintained
|
||||
.filter(
|
||||
(x) =>
|
||||
!x.field.endsWith(
|
||||
'_id',
|
||||
),
|
||||
)
|
||||
.map((x) => (
|
||||
<p key={x.field}>
|
||||
{contextFieldNames[
|
||||
x.field
|
||||
] ?? x.field}
|
||||
: conserva «{x.value}»;
|
||||
a fonte propõe «
|
||||
{x.proposed}».
|
||||
</p>
|
||||
))}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
@@ -722,23 +1149,30 @@ export default function ContextEditor({
|
||||
Atualizado pela nova seleção
|
||||
</th>
|
||||
<td className="p-2">
|
||||
{plan.updated.filter(x=>!x.field.endsWith('_id')).map((x) => (
|
||||
<p key={x.field}>
|
||||
{contextFieldNames[
|
||||
x.field
|
||||
] ?? x.field}
|
||||
:{' '}
|
||||
{displayValue(
|
||||
x.field,
|
||||
x.before,
|
||||
)}{' '}
|
||||
→{' '}
|
||||
{displayValue(
|
||||
x.field,
|
||||
x.after,
|
||||
)}
|
||||
</p>
|
||||
))}
|
||||
{plan.updated
|
||||
.filter(
|
||||
(x) =>
|
||||
!x.field.endsWith(
|
||||
'_id',
|
||||
),
|
||||
)
|
||||
.map((x) => (
|
||||
<p key={x.field}>
|
||||
{contextFieldNames[
|
||||
x.field
|
||||
] ?? x.field}
|
||||
:{' '}
|
||||
{displayValue(
|
||||
x.field,
|
||||
x.before,
|
||||
)}{' '}
|
||||
→{' '}
|
||||
{displayValue(
|
||||
x.field,
|
||||
x.after,
|
||||
)}
|
||||
</p>
|
||||
))}
|
||||
{Object.values(plan.selection).map(
|
||||
(r) =>
|
||||
r && (
|
||||
@@ -760,10 +1194,11 @@ export default function ContextEditor({
|
||||
</th>
|
||||
<td className="p-2">
|
||||
{plan.dependent_results.length}{' '}
|
||||
resultados financeiros afectados. Etapas a rever: {plan.review_steps.length}
|
||||
. Dados já preenchidos nos
|
||||
formulários conservam-se até à sua
|
||||
conferência.
|
||||
resultados financeiros afectados.
|
||||
Etapas a rever:{' '}
|
||||
{plan.review_steps.length}. Dados já
|
||||
preenchidos nos formulários
|
||||
conservam-se até à sua conferência.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
@@ -776,7 +1211,8 @@ export default function ContextEditor({
|
||||
anteriores.{' '}
|
||||
{plan.requests.map((r) => (
|
||||
<p key={r.id}>
|
||||
{r.protocol || 'Pedido guardado'}
|
||||
{r.protocol ||
|
||||
'Pedido guardado'}
|
||||
</p>
|
||||
))}
|
||||
</td>
|
||||
|
||||
Reference in New Issue
Block a user