@@ -63,10 +63,10 @@ import {
|
||||
} from '@/lib/simulation-api';
|
||||
|
||||
type Choice = { id: string; label: string };
|
||||
const draftKey = 'investmoz-simulation-draft-v1';
|
||||
const idempotencyStorageKey = 'investmoz-simulation-idempotency-v1';
|
||||
const draftCreateKey = 'investmoz-simulation-draft-create-key-v1';
|
||||
const draftIdKey = 'investmoz-simulation-draft-id-v1';
|
||||
const legacyDraftKey = 'investmoz-simulation-draft-v1';
|
||||
const legacyIdempotencyStorageKey = 'investmoz-simulation-idempotency-v1';
|
||||
const legacyDraftCreateKey = 'investmoz-simulation-draft-create-key-v1';
|
||||
const legacyDraftIdKey = 'investmoz-simulation-draft-id-v1';
|
||||
const idempotencyKey = () => crypto.randomUUID();
|
||||
|
||||
function csrfToken(): string {
|
||||
@@ -397,6 +397,26 @@ function useChoices(
|
||||
let url: URL;
|
||||
if (source === 'sector') {
|
||||
url = new URL('/api/v1/sectors', window.location.origin);
|
||||
} else if (source === 'country') {
|
||||
url = new URL(
|
||||
'/api/v1/catalogs/countries',
|
||||
window.location.origin,
|
||||
);
|
||||
url.searchParams.set('q', query);
|
||||
url.searchParams.set('per_page', '100');
|
||||
} else if (
|
||||
['province', 'district', 'admin_post', 'locality'].includes(
|
||||
source,
|
||||
)
|
||||
) {
|
||||
url = new URL(
|
||||
'/api/v1/investment/territory-options',
|
||||
window.location.origin,
|
||||
);
|
||||
url.searchParams.set('type', source);
|
||||
url.searchParams.set('q', query);
|
||||
if (source !== 'province')
|
||||
url.searchParams.set('parent_id', parent);
|
||||
} else {
|
||||
url = new URL(
|
||||
'/api/v1/catalogs/' +
|
||||
@@ -427,6 +447,7 @@ function useChoices(
|
||||
'Não foi possível carregar as opções. Tente novamente.',
|
||||
);
|
||||
const payload = await readSimulationApiJson(response);
|
||||
if (controller.signal.aborted) return;
|
||||
setChoices(simulationCatalogChoices(payload));
|
||||
} catch (cause) {
|
||||
if (!controller.signal.aborted)
|
||||
@@ -489,12 +510,15 @@ function SearchChoice({
|
||||
retry,
|
||||
} = useChoices(source, query, parent, !disabled && open);
|
||||
const chosen = Array.isArray(value) ? value : value ? [value] : [];
|
||||
const searchText = (text: string) =>
|
||||
text
|
||||
.normalize('NFD')
|
||||
.replace(/\p{Diacritic}/gu, '')
|
||||
.toLocaleLowerCase();
|
||||
const filtered = choices.filter(
|
||||
(option) =>
|
||||
option.label
|
||||
.toLocaleLowerCase()
|
||||
.includes(query.toLocaleLowerCase()) ||
|
||||
option.id.toLocaleLowerCase().includes(query.toLocaleLowerCase()),
|
||||
searchText(option.label).includes(searchText(query)) ||
|
||||
searchText(option.id).includes(searchText(query)),
|
||||
);
|
||||
useEffect(() => {
|
||||
if (open) activeOptionRef.current?.scrollIntoView({ block: 'nearest' });
|
||||
@@ -746,6 +770,28 @@ export function SimulationForm() {
|
||||
const { auth } = usePage<{
|
||||
auth: { user: { email_verified_at?: string | null } | null };
|
||||
}>().props;
|
||||
const pageUrl = usePage().url;
|
||||
const draftContext = useMemo(() => {
|
||||
const params = new URL(pageUrl, 'https://investmoz.invalid')
|
||||
.searchParams;
|
||||
return {
|
||||
context: params.get('context'),
|
||||
requestedDraft: params.get('draft'),
|
||||
};
|
||||
}, [pageUrl]);
|
||||
const contextId = draftContext.context;
|
||||
const storageScope = contextId
|
||||
? `:case:${contextId}`
|
||||
: draftContext.requestedDraft
|
||||
? `:draft:${draftContext.requestedDraft}`
|
||||
: '';
|
||||
const draftKey = legacyDraftKey + storageScope;
|
||||
const draftCreateKey = legacyDraftCreateKey + storageScope;
|
||||
const draftIdKey = legacyDraftIdKey + storageScope;
|
||||
const idempotencyStorageKey = legacyIdempotencyStorageKey + storageScope;
|
||||
const currentDraftUrl = contextId
|
||||
? `/api/v1/simulation-drafts/current?context=${encodeURIComponent(contextId)}`
|
||||
: '/api/v1/simulation-drafts/current';
|
||||
const canSavePersonalData = Boolean(auth?.user);
|
||||
const canAssociateDraft = Boolean(auth?.user?.email_verified_at);
|
||||
const [draft, setDraft] = useState<SimulationDraft>({});
|
||||
@@ -1123,9 +1169,9 @@ export function SimulationForm() {
|
||||
}
|
||||
try {
|
||||
const response = await fetch(
|
||||
requestedDraftId
|
||||
requestedDraftId && !contextId
|
||||
? `/api/v1/simulation-drafts/${encodeURIComponent(requestedDraftId)}`
|
||||
: '/api/v1/simulation-drafts/current',
|
||||
: currentDraftUrl,
|
||||
{
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
@@ -1140,7 +1186,7 @@ export function SimulationForm() {
|
||||
throw new Error(
|
||||
'O servidor devolveu um rascunho com formato inválido.',
|
||||
);
|
||||
if (canSavePersonalData) {
|
||||
if (canSavePersonalData && !contextId) {
|
||||
const [listResponse, previewResponse] =
|
||||
await Promise.all([
|
||||
fetch('/api/v1/simulation-drafts', {
|
||||
@@ -1222,9 +1268,19 @@ export function SimulationForm() {
|
||||
if (storedId) sessionStorage.removeItem(draftIdKey);
|
||||
setDraft(local);
|
||||
}
|
||||
} else if (contextId || requestedDraftId) {
|
||||
saveConflictRef.current = true;
|
||||
setHasSaveConflict(true);
|
||||
setSaveStatus(
|
||||
'Dossier indisponível para esta conta. Nenhum outro rascunho foi aberto.',
|
||||
);
|
||||
} else if (!canSavePersonalData && Object.keys(local).length)
|
||||
setDraft(local);
|
||||
} catch {
|
||||
if (contextId || requestedDraftId) {
|
||||
saveConflictRef.current = true;
|
||||
setHasSaveConflict(true);
|
||||
}
|
||||
if (!canSavePersonalData && Object.keys(local).length)
|
||||
setDraft(local);
|
||||
setSaveStatus(
|
||||
@@ -1236,7 +1292,7 @@ export function SimulationForm() {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [canSavePersonalData]);
|
||||
}, [canSavePersonalData, contextId, currentDraftUrl, draftIdKey, draftKey]);
|
||||
useEffect(() => {
|
||||
if (!ready || !draft.purpose) return;
|
||||
const timer = window.setTimeout(() => {
|
||||
@@ -1268,15 +1324,12 @@ export function SimulationForm() {
|
||||
'X-XSRF-TOKEN': csrfToken(),
|
||||
};
|
||||
if (!draftIdRef.current) {
|
||||
const currentResponse = await fetch(
|
||||
'/api/v1/simulation-drafts/current',
|
||||
{
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
},
|
||||
const currentResponse = await fetch(currentDraftUrl, {
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
},
|
||||
);
|
||||
});
|
||||
const currentPayload: unknown = currentResponse.ok
|
||||
? await readSimulationApiJson(currentResponse)
|
||||
: { data: null };
|
||||
@@ -1313,7 +1366,12 @@ export function SimulationForm() {
|
||||
...headers,
|
||||
'If-Match': draftEtagRef.current,
|
||||
},
|
||||
body: JSON.stringify(snapshots),
|
||||
body: JSON.stringify({
|
||||
...snapshots,
|
||||
...(contextId
|
||||
? { context: contextId }
|
||||
: {}),
|
||||
}),
|
||||
},
|
||||
);
|
||||
} else {
|
||||
@@ -1326,7 +1384,10 @@ export function SimulationForm() {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { ...headers, 'Idempotency-Key': key },
|
||||
body: JSON.stringify(snapshots),
|
||||
body: JSON.stringify({
|
||||
...snapshots,
|
||||
...(contextId ? { context: contextId } : {}),
|
||||
}),
|
||||
});
|
||||
}
|
||||
if (response.status === 412 || response.status === 428) {
|
||||
@@ -1401,7 +1462,87 @@ export function SimulationForm() {
|
||||
});
|
||||
}, 450);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [draft, ready, canSavePersonalData, accountDrafts]);
|
||||
}, [
|
||||
draft,
|
||||
ready,
|
||||
canSavePersonalData,
|
||||
accountDrafts,
|
||||
contextId,
|
||||
currentDraftUrl,
|
||||
draftCreateKey,
|
||||
draftIdKey,
|
||||
draftKey,
|
||||
]);
|
||||
|
||||
async function returnToInvestment() {
|
||||
if (!contextId || !draftIdRef.current) return;
|
||||
setContinuityError('');
|
||||
try {
|
||||
await saveQueueRef.current;
|
||||
const current = await fetch(
|
||||
`/api/v1/simulation-drafts/${draftIdRef.current}`,
|
||||
{
|
||||
headers: { Accept: 'application/json' },
|
||||
credentials: 'same-origin',
|
||||
},
|
||||
);
|
||||
const saved: unknown = await readSimulationApiJson(current);
|
||||
if (
|
||||
!current.ok ||
|
||||
!isApiSimulationDraftReadResponseV1(saved) ||
|
||||
!saved.data
|
||||
)
|
||||
throw new Error(
|
||||
'Não foi possível recuperar o rascunho guardado.',
|
||||
);
|
||||
if (
|
||||
saved.data.economic_snapshot.financial_tools_snapshot !==
|
||||
draft.financial_tools_snapshot
|
||||
)
|
||||
throw new Error(
|
||||
'Aguarde a gravação das entradas da ferramenta e tente novamente.',
|
||||
);
|
||||
const dossier = await fetch(`/investimentos/${contextId}`, {
|
||||
headers: { Accept: 'application/json' },
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
if (!dossier.ok)
|
||||
throw new Error('Dossier indisponível para esta conta.');
|
||||
const view = (await dossier.json()) as {
|
||||
case: { version: number };
|
||||
};
|
||||
const response = await fetch(
|
||||
`/investimentos/${contextId}/resultados`,
|
||||
{
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-XSRF-TOKEN': csrfToken(),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
version: view.case.version,
|
||||
draft_id: saved.data.id,
|
||||
draft_version: saved.data.version_no,
|
||||
}),
|
||||
},
|
||||
);
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
response.status === 409
|
||||
? 'O dossier mudou. Recupere a versão actual antes de devolver o resultado.'
|
||||
: 'Não foi possível devolver as entradas financeiras guardadas ao dossier.',
|
||||
);
|
||||
window.location.assign(`/investimentos/${contextId}`);
|
||||
} catch (cause) {
|
||||
setContinuityError(
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: 'Erro ao devolver o resultado.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function openOwnedDraft(id: string) {
|
||||
setContinuityError('');
|
||||
@@ -2264,6 +2405,32 @@ export function SimulationForm() {
|
||||
id={draftIdRef.current}
|
||||
/>
|
||||
)}
|
||||
{contextId && (
|
||||
<section
|
||||
className="rounded-lg border p-4"
|
||||
aria-label="Contexto do investimento"
|
||||
>
|
||||
<p>
|
||||
Ferramenta ligada ao dossier actual. As entradas são
|
||||
guardadas no rascunho deste investimento.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="mt-2 rounded border px-3 py-2"
|
||||
disabled={!ready || hasSaveConflict || !draftVersionNo}
|
||||
onClick={() => void returnToInvestment()}
|
||||
>
|
||||
Guardar resultado financeiro e voltar ao dossier
|
||||
</button>
|
||||
{continuityError && <p role="alert">{continuityError}</p>}
|
||||
<a
|
||||
className="ml-3 underline"
|
||||
href={`/investimentos/${contextId}`}
|
||||
>
|
||||
Ver dossier
|
||||
</a>
|
||||
</section>
|
||||
)}
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div>
|
||||
<h2
|
||||
@@ -2465,6 +2632,7 @@ export function SimulationForm() {
|
||||
</section>
|
||||
)}
|
||||
{canSavePersonalData &&
|
||||
!contextId &&
|
||||
!showDraftChoice &&
|
||||
accountDrafts.length > 0 && (
|
||||
<section
|
||||
|
||||
Reference in New Issue
Block a user