Files
Investidor-V2/resources/js/pages/investor-path/context.tsx
T

569 lines
26 KiB
TypeScript

import ContextDocuments from '@/components/context-documents';
import { Link } from '@inertiajs/react';
import { useState } from 'react';
import { Frame, button, card, input } from '@/pages/investment/shared';
import {
TerritoryFields,
type TerritoryOption,
} from '@/components/investment-territory';
import {
contextApi,
contextFieldNames,
type ContextView,
type ContextPlan,
type ContextReference,
} from '@/lib/investor-context';
import { useNavigationContext } from '@/components/navigation-context';
import { createOperationKey } from '@/lib/operation-key';
type Options = {
opportunities: { key: string; title: string; kind: string }[];
sectors: { id: number; name: string }[];
parks: { id: string; name: string; version_no: number }[];
search_limited: boolean;
};
type Slot = 'opportunity' | 'sector' | 'territory' | 'park';
export default function ContextEditor({
initial,
options: initialOptions,
source,
territorySelection = [],
}: {
initial: ContextView;
options: Options;
source: ContextReference | null;
territorySelection?: TerritoryOption[];
}) {
const navigation = useNavigationContext();
const [view, setView] = useState(initial);
const [options, setOptions] = useState(initialOptions);
const [query, setQuery] = useState('');
const [changes, setChanges] = useState<Partial<Record<Slot, string>>>(() =>
source
? {
[source.kind === 'business' ? 'opportunity' : source.kind]:
source.key,
}
: {},
);
const [declarations, setDeclarations] = useState<Record<string, string>>(
{},
);
const [replace, setReplace] = useState<string[]>([]);
const [plan, setPlan] = useState<ContextPlan | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [message, setMessage] = useState('');
const [operation, setOperation] = useState(createOperationKey);
const [requestBody, setRequestBody] = useState<Record<
string,
unknown
> | null>(null);
const selected = (slot: Slot) =>
Object.hasOwn(changes, slot)
? (changes[slot] ?? '')
: (view.context.selection[slot]?.key ?? '');
const change = (slot: Slot, value: string) => {
setChanges({ ...changes, [slot]: value });
setPlan(null);
setMessage('');
};
async function preview() {
setBusy(true);
setError('');
setMessage('');
const body = {
version: view.case.version,
selection: changes,
declarations,
replace_fields: replace,
};
try {
const result = await contextApi<ContextPlan>(
`/investimentos/${view.case.id}/contexto/previa`,
body,
);
setRequestBody(body);
setPlan(result);
} catch (e) {
setError(
e instanceof Error ? e.message : 'Não foi possível comparar.',
);
} finally {
setBusy(false);
}
}
async function confirm() {
if (!plan || !requestBody) return;
setBusy(true);
setError('');
try {
await contextApi(
`/investimentos/${view.case.id}/contexto/confirmar`,
{
...requestBody,
preview_hash: plan.preview_hash,
operation_key: operation,
confirm: true,
},
);
const next = await contextApi<ContextView>(
`/investimentos/${view.case.id}/contexto`,
);
setView(next);
navigation.refresh();
setChanges({});
setDeclarations({});
setReplace([]);
setPlan(null);
setOperation(createOperationKey());
setMessage(
'Contexto guardado no mesmo dossier. Resultados afetados identificados para revisão; conteúdo submetido e histórico preservados.',
);
} catch (e) {
setError(
e instanceof Error
? e.message
: 'Falha ao guardar; recupere antes de tentar novamente.',
);
} finally {
setBusy(false);
}
}
return (
<Frame title="Contexto do investimento">
<ContextDocuments source={view.context.selection.opportunity} />
<div className="space-y-5 [overflow-wrap:anywhere]">
<Link
className="underline"
href={`/investimentos/${view.case.id}`}
>
Voltar ao mesmo dossier
</Link>
<p>
{view.case.title} · UUID {view.case.id} · dossier v
{view.case.version} · contexto v{view.context.revision}
</p>
<p className="rounded border border-emerald-300 bg-emerald-50 p-3">
As referências apoiam a preparação. Associar uma
oportunidade, sector ou localização não confirma incentivos,
licença, terra disponível, reserva ou autorização.
</p>
{error && (
<div
role="alert"
className="rounded border border-red-400 p-3"
>
<p>{error}</p>
<button
type="button"
className="underline"
onClick={() => window.location.reload()}
>
Recuperar o dossier atual
</button>
</div>
)}
{message && <p role="status">{message}</p>}
<section className={card + ' space-y-4'}>
<h2 className="text-xl font-bold">
Escolher referências existentes
</h2>
<div className="flex flex-wrap gap-2">
<label className="min-w-0 flex-1">
Pesquisar oportunidades
<input
className={input}
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
</label>
<button
type="button"
className={button}
disabled={busy}
onClick={() => {
setBusy(true);
void contextApi<Options>(
'/investimentos/fontes-contexto?q=' +
encodeURIComponent(query),
)
.then(setOptions)
.catch((e) => setError(e.message))
.finally(() => setBusy(false));
}}
>
Pesquisar
</button>
</div>
<label className="grid min-w-0 gap-1">
Oportunidade
<select
className={input + ' max-w-full min-w-0'}
value={selected('opportunity')}
disabled={busy}
onChange={(e) =>
change('opportunity', e.target.value)
}
>
<option value="">Sem oportunidade associada</option>
{source &&
['opportunity', 'business'].includes(
source.kind,
) &&
!options.opportunities.some(
(x) => x.key === source.key,
) && (
<option value={source.key}>
{source.title}
</option>
)}
{view.context.selection.opportunity &&
!options.opportunities.some(
(x) =>
x.key ===
view.context.selection.opportunity!.key,
) && (
<option
value={
view.context.selection.opportunity
.key
}
>
{
view.context.selection.opportunity
.title
}{' '}
— referência guardada
</option>
)}
{options.opportunities.map((o) => (
<option key={o.key} value={o.key}>
{o.title} ·{' '}
{o.kind === 'business'
? 'Negócios'
: 'Catálogo'}
</option>
))}
</select>
</label>
{options.search_limited && (
<p>
Resultados limitados por página de pesquisa;
especifique o título para encontrar outras
oportunidades.
</p>
)}
<label className="grid min-w-0 gap-1">
Sector
<select
className={input + ' max-w-full min-w-0'}
disabled={busy}
value={selected('sector')}
onChange={(e) => change('sector', e.target.value)}
>
<option value="">Sem sector escolhido</option>
{view.context.selection.sector &&
!options.sectors.some(
(s) =>
'sector:' + s.id ===
view.context.selection.sector?.key,
) && (
<option
disabled
value={
view.context.selection.sector.key
}
>
{view.context.selection.sector.title} —
referência histórica mantida
</option>
)}
{options.sectors.map((s) => (
<option key={s.id} value={'sector:' + s.id}>
{s.name}
</option>
))}
</select>
</label>
<label className="grid min-w-0 gap-1">
Parque consultado
<select
className={input + ' max-w-full min-w-0'}
disabled={busy}
value={selected('park')}
onChange={(e) => change('park', e.target.value)}
>
<option value="">
Sem parque no contexto atual
</option>
{options.parks.map((p) => (
<option key={p.id} value={'park:' + p.id}>
{p.name} · v{p.version_no}
</option>
))}
</select>
</label>
<h3 className="font-semibold">
Localização — escolher até ao nível conhecido
</h3>
<TerritoryFields
initial={territorySelection}
disabled={busy}
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} · v
{view.context.selection.territory.version}.
</p>
)}
</section>
<section className={card + ' space-y-3'}>
<h2 className="text-xl font-bold">
Declarações deste investimento
</h2>
<p>
Estes campos pertencem ao processo. Alterá-los não muda
o cadastro da oportunidade nem o perfil da organização.
</p>
{['project_title', 'project_summary'].map((k) => (
<label className="grid gap-1" key={k}>
{contextFieldNames[k]}
<textarea
className={input}
value={
declarations[k] ??
view.context.fields[k] ??
''
}
disabled={busy}
maxLength={k === 'project_title' ? 200 : 5000}
onChange={(e) => {
setDeclarations({
...declarations,
[k]: e.target.value,
});
setPlan(null);
}}
/>
</label>
))}
<details>
<summary>
Substituições explícitas de declarações
</summary>
<p>
Por defeito, uma seleção conserva o título e as
declarações do utilizador. Autorize somente os
campos que pretende substituir pelo cadastro.
</p>
{['project_title', 'project_summary'].map((k) => (
<label className="block" key={k}>
<input
type="checkbox"
checked={replace.includes(k)}
onChange={(e) => {
setReplace(
e.target.checked
? [...replace, k]
: replace.filter(
(x) => x !== k,
),
);
setPlan(null);
}}
/>{' '}
Usar a fonte selecionada em{' '}
{contextFieldNames[k].toLowerCase()}
</label>
))}
</details>
<button
className={button}
type="button"
disabled={busy}
onClick={() => void preview()}
>
Comparar impacto antes de guardar
</button>
</section>
{plan && (
<section
className={card + ' space-y-4'}
aria-label="Impacto da mudança de contexto"
>
<h2 className="text-xl font-bold">
Comparação antes da confirmação
</h2>
<div className="overflow-x-auto">
<table className="w-full min-w-[36rem] table-fixed text-left">
<thead>
<tr>
<th className="w-44 p-2">Tratamento</th>
<th>Impacto concreto</th>
</tr>
</thead>
<tbody>
<tr>
<th className="p-2 align-top">
Mantido
</th>
<td className="p-2">
UUID, identidade e{' '}
{plan.documents_preserved}{' '}
documentos.{' '}
{plan.maintained.map((x) => (
<p key={x.field}>
{contextFieldNames[
x.field
] ?? x.field}
: conserva «{x.value}»; a
fonte propõe «{x.proposed}».
</p>
))}
</td>
</tr>
<tr>
<th className="p-2 align-top">
Atualizado pela nova seleção
</th>
<td className="p-2">
{plan.updated.map((x) => (
<p key={x.field}>
{contextFieldNames[
x.field
] ?? x.field}
:{' '}
{x.before ??
'não informado'}{' '}
→{' '}
{x.after ?? 'não informado'}
</p>
))}
{Object.values(plan.selection).map(
(r) =>
r && (
<p key={r.key}>
<Link
className="underline"
href={r.href}
>
{r.title}
</Link>{' '}
· {r.kind} · v
{r.version ??
'não exposta'}{' '}
· origem {r.key}
</p>
),
)}
</td>
</tr>
<tr>
<th className="p-2 align-top">
Precisa de revisão ou recálculo
</th>
<td className="p-2">
{plan.dependent_results.length}{' '}
resultados financeiros acessíveis
afetados:{' '}
{plan.dependent_results
.map((r) => r.id)
.join(', ') || 'nenhum'}
. Etapas:{' '}
{plan.review_steps.join(', ') ||
'nenhuma alteração de dependências'}
. Dados já preenchidos nos
formulários conservam-se até à sua
conferência.
</td>
</tr>
<tr>
<th className="p-2 align-top">
Preservado no histórico
</th>
<td className="p-2">
{plan.requests.length} pedidos e os
snapshots, decisões e resultados
anteriores.{' '}
{plan.requests.map((r) => (
<p key={r.id}>
{r.protocol || r.id} · v
{r.version} · {r.status}
</p>
))}
</td>
</tr>
</tbody>
</table>
</div>
<p>{plan.notice}</p>
<div className="flex flex-wrap gap-3">
<button
type="button"
className="rounded border px-4 py-2"
disabled={busy}
onClick={() => {
setPlan(null);
setRequestBody(null);
setMessage(
'Confirmação cancelada; as escolhas continuam apenas nesta página. Nenhuma associação, resultado ou submissão foi alterado.',
);
}}
>
Cancelar mudança
</button>
<button
type="button"
className={button}
disabled={busy}
onClick={() => void confirm()}
>
Confirmar e guardar o contexto
</button>
</div>
</section>
)}
<section className={card}>
<h2 className="text-xl font-bold">
Resultados e submissões conservados
</h2>
{view.results.map((r) => (
<p key={r.id}>
{r.id} · {r.engine} ·{' '}
{r.context_state === 'review_required'
? 'Desatualizado para o contexto atual — exige revisão/recálculo'
: 'Guardado para o contexto indicado no dossier'}
</p>
))}
{view.requests.map((r) => (
<p key={r.id}>
<Link
className="underline"
href={'/balcao-virtual/pedidos/' + r.id}
>
{r.protocol || r.id}
</Link>{' '}
· {r.status} ·{' '}
{r.context_state === 'historical_submission'
? 'Conteúdo enviado preservado; contexto posterior distinto'
: r.context_state === 'review_required'
? 'Rascunho precisa de conferência de contexto'
: 'Contexto conservado'}
</p>
))}
</section>
</div>
</Frame>
);
}