fix: complete InvesteMoz validation and error corrections
This commit is contained in:
@@ -1,9 +1,16 @@
|
||||
import ContextDocuments from '@/components/context-documents';
|
||||
import { SelectedComplements, type Complement } from '@/components/investment-complements';
|
||||
import {
|
||||
SelectedComplements,
|
||||
type Complement,
|
||||
} from '@/components/investment-complements';
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { Frame, card, input, button } from '@/pages/investment/shared';
|
||||
import { contextApi, type ContextReference, type OpportunityChoice } from '@/lib/investor-context';
|
||||
import {
|
||||
contextApi,
|
||||
type ContextReference,
|
||||
type OpportunityChoice,
|
||||
} from '@/lib/investor-context';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
export default function ContextStart({
|
||||
contexts,
|
||||
@@ -20,27 +27,96 @@ export default function ContextStart({
|
||||
step?: string | null;
|
||||
entryQuery?: Record<string, string>;
|
||||
entryComplements?: Complement[];
|
||||
entrySubmission?: {id:string;version:number} | null;
|
||||
entrySubmission?: { id: string; version: number } | null;
|
||||
}) {
|
||||
const [chosen, setChosen] = useState('');
|
||||
const [title, setTitle] = useState(entryComplements[0]?.kind === 'need' ? `Preparação de ${entryComplements[0].title} — ${entryComplements[0].origin.title}`.slice(0,200) : source?.title ?? opportunityChoices[0]?.opportunity.title ?? '');
|
||||
const [title, setTitle] = useState(
|
||||
entryComplements[0]?.kind === 'need'
|
||||
? `Preparação de ${entryComplements[0].title} — ${entryComplements[0].origin.title}`.slice(
|
||||
0,
|
||||
200,
|
||||
)
|
||||
: (source?.title ?? opportunityChoices[0]?.opportunity.title ?? ''),
|
||||
);
|
||||
const [consent, setConsent] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [key] = useState(createOperationKey);
|
||||
const sourceSuffix = opportunityChoices.length ? '?' + opportunityChoices.map(c => `opportunities[]=${encodeURIComponent(c.opportunity.id)}`).join('&') : source ? '?source=' + encodeURIComponent(source.key) : '';
|
||||
const suffix = sourceSuffix || Object.keys(entryQuery).length ? (sourceSuffix || '?')+(sourceSuffix ? '&' : '')+'selection_key='+encodeURIComponent(key)+'&'+new URLSearchParams(entryQuery).toString() : '';
|
||||
const sourceSuffix = opportunityChoices.length
|
||||
? '?' +
|
||||
opportunityChoices
|
||||
.map(
|
||||
(c) =>
|
||||
`opportunities[]=${encodeURIComponent(c.opportunity.id)}`,
|
||||
)
|
||||
.join('&')
|
||||
: source
|
||||
? '?source=' + encodeURIComponent(source.key)
|
||||
: '';
|
||||
const suffix =
|
||||
sourceSuffix || Object.keys(entryQuery).length
|
||||
? (sourceSuffix || '?') +
|
||||
(sourceSuffix ? '&' : '') +
|
||||
'selection_key=' +
|
||||
encodeURIComponent(key) +
|
||||
'&' +
|
||||
new URLSearchParams(entryQuery).toString()
|
||||
: '';
|
||||
const continueIn = async (id: string) => {
|
||||
if (entrySubmission) {
|
||||
const view = await contextApi<{case:{version:number}}>(`/investimentos/${id}/contexto`);
|
||||
await contextApi(`/investidor/manifestacoes/${entrySubmission.id}/contexto`, {case_id:id,case_version:view.case.version,version:entrySubmission.version});
|
||||
const view = await contextApi<{ case: { version: number } }>(
|
||||
`/investimentos/${id}/contexto`,
|
||||
);
|
||||
await contextApi(
|
||||
`/investidor/manifestacoes/${entrySubmission.id}/contexto`,
|
||||
{
|
||||
case_id: id,
|
||||
case_version: view.case.version,
|
||||
version: entrySubmission.version,
|
||||
},
|
||||
);
|
||||
}
|
||||
window.location.assign(`/investimentos/${id}/contexto/editar${suffix}`);
|
||||
};
|
||||
return (
|
||||
<Frame title="Iniciar ou continuar um investimento">
|
||||
<SelectedComplements items={entryComplements}/>
|
||||
{!!opportunityChoices.length && <section className={card}><h2 className="font-bold">Oportunidades escolhidas</h2><ul>{opportunityChoices.map(c => <li key={c.opportunity.key}><Link className="underline" href={c.opportunity.href}>{c.opportunity.title}</Link> · {c.territory?.title ?? 'Localização por escolher'}{c.portfolio_origins?.map(origin=><p key={origin.id}>Associação escolhida: <Link className="underline" href={origin.href}>{origin.title}</Link></p>)}</li>)}</ul><p>Confirme a localização de cada ficha na comparação do dossier. Ao continuar um dossier, as escolhas já guardadas conservam-se.</p></section>}
|
||||
<SelectedComplements items={entryComplements} />
|
||||
{!!opportunityChoices.length && (
|
||||
<section className={card}>
|
||||
<h2 className="font-bold">Oportunidades escolhidas</h2>
|
||||
<ul>
|
||||
{opportunityChoices.map((c) => (
|
||||
<li key={c.opportunity.key}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={c.opportunity.href}
|
||||
>
|
||||
{c.opportunity.title}
|
||||
</Link>{' '}
|
||||
·{' '}
|
||||
{c.territory?.title ??
|
||||
'Localização por escolher'}
|
||||
{c.portfolio_origins?.map((origin) => (
|
||||
<p key={origin.id}>
|
||||
Associação escolhida:{' '}
|
||||
<Link
|
||||
className="underline"
|
||||
href={origin.href}
|
||||
>
|
||||
{origin.title}
|
||||
</Link>
|
||||
</p>
|
||||
))}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p>
|
||||
Confirme a localização de cada ficha na comparação do
|
||||
dossier. Ao continuar um dossier, as escolhas já
|
||||
guardadas conservam-se.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
<p>
|
||||
Ideia, oportunidade, sector e localização convergem no mesmo
|
||||
dossier. A referência é para preparação e não confirma direitos
|
||||
@@ -53,11 +129,28 @@ export default function ContextStart({
|
||||
<Link className="underline" href={source.href}>
|
||||
{source.title}
|
||||
</Link>
|
||||
{source.kind === 'portfolio' && <p>Sector documentado: {source.analysis?.documented_sector ?? 'Por definir'}. Cobertura documental: {source.analysis?.documented_location ?? 'Por definir'}. Confirme o enquadramento e a localização do seu investimento no dossier.</p>}
|
||||
{source.kind === 'portfolio' && (
|
||||
<p>
|
||||
Sector documentado:{' '}
|
||||
{source.analysis?.documented_sector ??
|
||||
'Por definir'}
|
||||
. Cobertura documental:{' '}
|
||||
{source.analysis?.documented_location ??
|
||||
'Por definir'}
|
||||
. Confirme o enquadramento e a localização do seu
|
||||
investimento no dossier.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
<section className={card + ' space-y-3'}>
|
||||
{entrySubmission && <p>Ao continuar, esta manifestação será associada ao dossier escolhido, conservando a ficha de origem. Nenhum pedido será submetido.</p>}
|
||||
{entrySubmission && (
|
||||
<p>
|
||||
Ao continuar, esta manifestação será associada ao
|
||||
dossier escolhido, conservando a ficha de origem. Nenhum
|
||||
pedido será submetido.
|
||||
</p>
|
||||
)}
|
||||
<h2 className="text-xl font-bold">
|
||||
Continuar um dossier existente
|
||||
</h2>
|
||||
@@ -81,8 +174,18 @@ export default function ContextStart({
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
if (step && !source && !opportunityChoices.length) {window.location.assign(`/investimentos/${chosen}#${step}`);return;}
|
||||
setBusy(true);setError('');void continueIn(chosen).catch(e=>{setError(e.message);setBusy(false);});
|
||||
if (step && !source && !opportunityChoices.length) {
|
||||
window.location.assign(
|
||||
`/investimentos/${chosen}#${step}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError('');
|
||||
void continueIn(chosen).catch((e) => {
|
||||
setError(e.message);
|
||||
setBusy(false);
|
||||
});
|
||||
}}
|
||||
>
|
||||
{step && !source && !opportunityChoices.length
|
||||
@@ -90,9 +193,20 @@ export default function ContextStart({
|
||||
: 'Preparar neste dossier'}
|
||||
</button>
|
||||
)}
|
||||
{chosen && !entrySubmission && <Link className={button} href={step && !source && !opportunityChoices.length ? `/investimentos/${chosen}#${step}` : `/investimentos/${chosen}/contexto/editar${suffix}`}>
|
||||
{step && !source && !opportunityChoices.length ? 'Abrir ' + step + ' no mesmo dossier' : 'Preparar neste dossier'}
|
||||
</Link>}
|
||||
{chosen && !entrySubmission && (
|
||||
<Link
|
||||
className={button}
|
||||
href={
|
||||
step && !source && !opportunityChoices.length
|
||||
? `/investimentos/${chosen}#${step}`
|
||||
: `/investimentos/${chosen}/contexto/editar${suffix}`
|
||||
}
|
||||
>
|
||||
{step && !source && !opportunityChoices.length
|
||||
? 'Abrir ' + step + ' no mesmo dossier'
|
||||
: 'Preparar neste dossier'}
|
||||
</Link>
|
||||
)}
|
||||
<p>
|
||||
Se já preparou este investimento, continue nele. Não é
|
||||
necessário criar outro dossier.
|
||||
@@ -116,7 +230,8 @@ export default function ContextStart({
|
||||
>
|
||||
<h2 className="text-xl font-bold">Iniciar uma nova ideia</h2>
|
||||
<p>
|
||||
Organize a sua ideia e acompanhe a preparação do investimento.
|
||||
Organize a sua ideia e acompanhe a preparação do
|
||||
investimento.
|
||||
</p>
|
||||
<label className="grid gap-1">
|
||||
Título do investimento
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -18,7 +18,13 @@ export default function InvestmentContexts({
|
||||
}: {
|
||||
contexts: InvestmentContext[];
|
||||
contentSource?: LegacyArticle;
|
||||
zoneSource?: { zone_id: string; consulted_public_version: number; title: string; href: string; notice: string };
|
||||
zoneSource?: {
|
||||
zone_id: string;
|
||||
consulted_public_version: number;
|
||||
title: string;
|
||||
href: string;
|
||||
notice: string;
|
||||
};
|
||||
sectorSource?: { id: number; name: string; slug: string; href: string };
|
||||
}) {
|
||||
const [key] = useState(() => createOperationKey());
|
||||
@@ -36,7 +42,14 @@ export default function InvestmentContexts({
|
||||
<main className="mx-auto max-w-5xl space-y-6 p-4 md:p-8">
|
||||
<Head title="Os meus investimentos" />
|
||||
<h1 className="text-2xl font-semibold">Os meus investimentos</h1>
|
||||
{zoneSource && <section className="rounded border p-4"><h2>Parque escolhido: {zoneSource.title}</h2><Link className="underline" href={zoneSource.href}>Consultar parque</Link></section>}
|
||||
{zoneSource && (
|
||||
<section className="rounded border p-4">
|
||||
<h2>Parque escolhido: {zoneSource.title}</h2>
|
||||
<Link className="underline" href={zoneSource.href}>
|
||||
Consultar parque
|
||||
</Link>
|
||||
</section>
|
||||
)}
|
||||
{sectorSource && (
|
||||
<p>
|
||||
Preparar uma ideia em{' '}
|
||||
@@ -73,7 +86,26 @@ export default function InvestmentContexts({
|
||||
Guardado em{' '}
|
||||
{new Date(item.updated_at).toLocaleString('pt-MZ')}
|
||||
</p>
|
||||
{zoneSource && <button type="button" className="mt-3 rounded border p-2" onClick={()=>router.post(`/investimentos/${item.id}/parques`,{version:item.version,zone_id:zoneSource.zone_id,consulted_public_version:zoneSource.consulted_public_version,confirm:true})}>Confirmar referência neste dossier</button>}
|
||||
{zoneSource && (
|
||||
<button
|
||||
type="button"
|
||||
className="mt-3 rounded border p-2"
|
||||
onClick={() =>
|
||||
router.post(
|
||||
`/investimentos/${item.id}/parques`,
|
||||
{
|
||||
version: item.version,
|
||||
zone_id: zoneSource.zone_id,
|
||||
consulted_public_version:
|
||||
zoneSource.consulted_public_version,
|
||||
confirm: true,
|
||||
},
|
||||
)
|
||||
}
|
||||
>
|
||||
Confirmar referência neste dossier
|
||||
</button>
|
||||
)}
|
||||
{sectorSource && (
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import {ProactiveSummary,proactiveView} from '@/components/proactive-investment';
|
||||
import {
|
||||
ProactiveSummary,
|
||||
proactiveView,
|
||||
} from '@/components/proactive-investment';
|
||||
import {
|
||||
PreparationSummary,
|
||||
type Preparation,
|
||||
@@ -97,7 +100,11 @@ 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_opportunity && (
|
||||
<p>
|
||||
Oportunidade desta análise: {result.context_opportunity}
|
||||
</p>
|
||||
)}
|
||||
{result.context_state === 'review_required' && (
|
||||
<p
|
||||
role="status"
|
||||
@@ -124,8 +131,8 @@ function Result({ result }: { result: PathResult }) {
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
Estimativa recalculada pelas fórmulas da ferramenta a partir
|
||||
dos dados preenchidos. Não
|
||||
constitui decisão de financiamento.
|
||||
dos dados preenchidos. Não constitui decisão de
|
||||
financiamento.
|
||||
</p>
|
||||
</li>
|
||||
);
|
||||
@@ -171,8 +178,14 @@ function Stage({ step, path }: { step: Step; path: Path }) {
|
||||
];
|
||||
const states = path.canWrite ? ownerStates : reviewStates;
|
||||
return (
|
||||
<details id={step.code} open={path.next?.code===step.code} className="space-y-3 rounded-xl border p-4">
|
||||
<summary className="cursor-pointer font-semibold">{step.title} · {pathStates[step.state]}</summary>
|
||||
<details
|
||||
id={step.code}
|
||||
open={path.next?.code === step.code}
|
||||
className="space-y-3 rounded-xl border p-4"
|
||||
>
|
||||
<summary className="cursor-pointer font-semibold">
|
||||
{step.title} · {pathStates[step.state]}
|
||||
</summary>
|
||||
<p>{pathStates[step.state]}</p>
|
||||
{step.context_review_required && (
|
||||
<label className="block rounded border border-amber-600 bg-amber-50 p-3">
|
||||
@@ -233,18 +246,32 @@ function Stage({ step, path }: { step: Step; path: Path }) {
|
||||
: action === 'operate'
|
||||
? 'Operação'
|
||||
: 'Execução'}{' '}
|
||||
aguarda {gaps.map(code=>path.steps.find(item=>item.code===code)?.title??code).join(', ')}. Pode continuar a preparar.
|
||||
aguarda{' '}
|
||||
{gaps
|
||||
.map(
|
||||
(code) =>
|
||||
path.steps.find(
|
||||
(item) => item.code === code,
|
||||
)?.title ?? code,
|
||||
)
|
||||
.join(', ')}
|
||||
. Pode continuar a preparar.
|
||||
</p>
|
||||
))}
|
||||
<details className="text-xs"><summary className="cursor-pointer underline">Fonte e referência desta etapa</summary><p>
|
||||
Referência interna {step.code}.{' '}
|
||||
Documento original, parágrafo {step.source_paragraph}.{' '}
|
||||
{step.detail.scope === 'internal_validation'
|
||||
? 'Conferência interna; não equivale a decisão externa.'
|
||||
: step.detail.scope === 'external_document_recorded'
|
||||
? 'Acto externo registado a partir de documento.'
|
||||
: 'Preparação declarada pelo promotor.'}
|
||||
</p></details>
|
||||
<details className="text-xs">
|
||||
<summary className="cursor-pointer underline">
|
||||
Fonte e referência desta etapa
|
||||
</summary>
|
||||
<p>
|
||||
Referência interna {step.code}. Documento original,
|
||||
parágrafo {step.source_paragraph}.{' '}
|
||||
{step.detail.scope === 'internal_validation'
|
||||
? 'Conferência interna; não equivale a decisão externa.'
|
||||
: step.detail.scope === 'external_document_recorded'
|
||||
? 'Acto externo registado a partir de documento.'
|
||||
: 'Preparação declarada pelo promotor.'}
|
||||
</p>
|
||||
</details>
|
||||
{step.preparation_allowed && (path.canWrite || path.canReview) && (
|
||||
<details>
|
||||
<summary className="cursor-pointer underline">
|
||||
@@ -433,7 +460,13 @@ export default function InvestmentPath(path: Path) {
|
||||
function support() {
|
||||
router.post(
|
||||
`/balcao-virtual/dossiers/${path.case.id}/pedidos`,
|
||||
{ service_version_id: service, client_key: requestKey, opportunity: new URLSearchParams(window.location.search).get('opportunity') },
|
||||
{
|
||||
service_version_id: service,
|
||||
client_key: requestKey,
|
||||
opportunity: new URLSearchParams(window.location.search).get(
|
||||
'opportunity',
|
||||
),
|
||||
},
|
||||
{ onError: (errors) => setError(Object.values(errors).join('; ')) },
|
||||
);
|
||||
}
|
||||
@@ -444,17 +477,56 @@ export default function InvestmentPath(path: Path) {
|
||||
Os meus investimentos
|
||||
</Link>
|
||||
<h1 className="text-2xl font-semibold">{path.case.title}</h1>
|
||||
{path.investment_context?.selection.portfolio && <p className="rounded border p-4">
|
||||
Origem documental: <Link className="underline" href={path.investment_context.selection.portfolio.href}>{path.investment_context.selection.portfolio.title}</Link>.
|
||||
{' '}A localização do investimento é escolhida no contexto.
|
||||
</p>}
|
||||
{!!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>}
|
||||
{path.investment_context?.selection.portfolio && (
|
||||
<p className="rounded border p-4">
|
||||
Origem documental:{' '}
|
||||
<Link
|
||||
className="underline"
|
||||
href={path.investment_context.selection.portfolio.href}
|
||||
>
|
||||
{path.investment_context.selection.portfolio.title}
|
||||
</Link>
|
||||
. A localização do investimento é escolhida no contexto.
|
||||
</p>
|
||||
)}
|
||||
{!!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}
|
||||
/>
|
||||
@@ -464,9 +536,7 @@ export default function InvestmentPath(path: Path) {
|
||||
/>
|
||||
{path.investment_context && (
|
||||
<section className="space-y-2 rounded border border-emerald-300 bg-emerald-50 p-4">
|
||||
<h2 className="font-semibold">
|
||||
As suas escolhas
|
||||
</h2>
|
||||
<h2 className="font-semibold">As suas escolhas</h2>
|
||||
{Object.values(path.investment_context.selection).map(
|
||||
(ref) => (
|
||||
<p key={ref.key}>
|
||||
@@ -503,9 +573,7 @@ export default function InvestmentPath(path: Path) {
|
||||
<Link className="underline" href={zone.href}>
|
||||
{zone.title}
|
||||
</Link>
|
||||
<p>
|
||||
{zone.selected_at}
|
||||
</p>
|
||||
<p>{zone.selected_at}</p>
|
||||
<p>{zone.notice}</p>
|
||||
</article>
|
||||
))}
|
||||
@@ -547,11 +615,38 @@ export default function InvestmentPath(path: Path) {
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{!!path.investment_context?.opportunity_choices?.length && <OpportunityChoices contextId={path.case.id} choices={path.investment_context.opportunity_choices}/>}
|
||||
{path.investment_context?.opportunity_choices?.map(choice=><ProactiveSummary key={choice.opportunity.key} value={proactiveView(choice.opportunity.analysis?.proactive)}/>)}
|
||||
{!path.investment_context?.opportunity_choices?.length&&<ProactiveSummary value={proactiveView(path.investment_context?.selection.opportunity?.analysis?.proactive)}/>}
|
||||
<SelectedComplements items={path.investment_context?.complements ?? []}/>
|
||||
<InvestmentRequirements assessment={path.investment_context?.requirements_assessment} contextId={path.case.id} excludedSteps={path.steps.filter((step) => !step.preparation_allowed).map((step) => step.code)}/>
|
||||
{!!path.investment_context?.opportunity_choices?.length && (
|
||||
<OpportunityChoices
|
||||
contextId={path.case.id}
|
||||
choices={path.investment_context.opportunity_choices}
|
||||
/>
|
||||
)}
|
||||
{path.investment_context?.opportunity_choices?.map((choice) => (
|
||||
<ProactiveSummary
|
||||
key={choice.opportunity.key}
|
||||
value={proactiveView(
|
||||
choice.opportunity.analysis?.proactive,
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
{!path.investment_context?.opportunity_choices?.length && (
|
||||
<ProactiveSummary
|
||||
value={proactiveView(
|
||||
path.investment_context?.selection.opportunity?.analysis
|
||||
?.proactive,
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<SelectedComplements
|
||||
items={path.investment_context?.complements ?? []}
|
||||
/>
|
||||
<InvestmentRequirements
|
||||
assessment={path.investment_context?.requirements_assessment}
|
||||
contextId={path.case.id}
|
||||
excludedSteps={path.steps
|
||||
.filter((step) => !step.preparation_allowed)
|
||||
.map((step) => step.code)}
|
||||
/>
|
||||
{!!path.content_sources?.length && (
|
||||
<section
|
||||
className="space-y-2 rounded-xl border p-4"
|
||||
@@ -706,34 +801,68 @@ export default function InvestmentPath(path: Path) {
|
||||
</form>
|
||||
)}
|
||||
{path.steps.some((step) => !step.preparation_allowed) && (
|
||||
<section className="rounded-xl border p-4" aria-label="Etapas sem aplicação">
|
||||
<h2 className="font-semibold">Não precisa de preparar neste contexto</h2>
|
||||
<section
|
||||
className="rounded-xl border p-4"
|
||||
aria-label="Etapas sem aplicação"
|
||||
>
|
||||
<h2 className="font-semibold">
|
||||
Não precisa de preparar neste contexto
|
||||
</h2>
|
||||
<ul>
|
||||
{path.steps.filter((step) => !step.preparation_allowed).map((step) => (
|
||||
<li key={step.code}>{step.title}: {step.reason || 'Conforme as escolhas guardadas.'}</li>
|
||||
))}
|
||||
{path.steps
|
||||
.filter((step) => !step.preparation_allowed)
|
||||
.map((step) => (
|
||||
<li key={step.code}>
|
||||
{step.title}:{' '}
|
||||
{step.reason ||
|
||||
'Conforme as escolhas guardadas.'}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="text-sm">Pode rever estas escolhas acima. Os dados e o histórico destas etapas ficam conservados.</p>
|
||||
<p className="text-sm">
|
||||
Pode rever estas escolhas acima. Os dados e o histórico
|
||||
destas etapas ficam conservados.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
{Object.entries(path.phases).filter(([number]) => path.steps.some((step) => step.phase === Number(number) && step.preparation_allowed)).map(([number, label]) => (
|
||||
<details open={path.steps.some(step=>step.phase===Number(number)&&step.code===path.next?.code)} className="space-y-3 rounded border p-4" key={number}>
|
||||
<summary className="cursor-pointer text-lg font-semibold">
|
||||
Fase {number} · {label}
|
||||
</summary>
|
||||
<div className="grid items-start gap-3 md:grid-cols-2">
|
||||
{path.steps
|
||||
.filter((step) => step.phase === Number(number) && step.preparation_allowed)
|
||||
.map((step) => (
|
||||
<Stage
|
||||
key={step.code}
|
||||
step={step}
|
||||
path={path}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
))}
|
||||
{Object.entries(path.phases)
|
||||
.filter(([number]) =>
|
||||
path.steps.some(
|
||||
(step) =>
|
||||
step.phase === Number(number) &&
|
||||
step.preparation_allowed,
|
||||
),
|
||||
)
|
||||
.map(([number, label]) => (
|
||||
<details
|
||||
open={path.steps.some(
|
||||
(step) =>
|
||||
step.phase === Number(number) &&
|
||||
step.code === path.next?.code,
|
||||
)}
|
||||
className="space-y-3 rounded border p-4"
|
||||
key={number}
|
||||
>
|
||||
<summary className="cursor-pointer text-lg font-semibold">
|
||||
Fase {number} · {label}
|
||||
</summary>
|
||||
<div className="grid items-start gap-3 md:grid-cols-2">
|
||||
{path.steps
|
||||
.filter(
|
||||
(step) =>
|
||||
step.phase === Number(number) &&
|
||||
step.preparation_allowed,
|
||||
)
|
||||
.map((step) => (
|
||||
<Stage
|
||||
key={step.code}
|
||||
step={step}
|
||||
path={path}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
))}
|
||||
<section className="space-y-3">
|
||||
<h2 className="text-lg font-semibold">
|
||||
Resultados devolvidos ao dossier
|
||||
|
||||
Reference in New Issue
Block a user