novas funcionalidades dos formulario
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-02 11:13:37 +02:00
parent a6afb4e97a
commit 4f35313d06
104 changed files with 7653 additions and 178 deletions
@@ -1,5 +1,6 @@
import { useEffect, useId, useState } from "react";
import { api } from "@/pages/investment/shared";
import { replaceTerritoryPath } from "@/lib/territory-path.js";
export type TerritoryOption = {
id: string;
@@ -18,7 +19,7 @@ const emptyTerritoryPath: TerritoryOption[] = [];
export function ProvinceSelect({
value,
onChange,
endpoint = "/api/v1/investment/territory-options",
endpoint = "/api/v1/catalogs/jurisdictions",
placeholder = "Seleccione uma província",
className = control,
label = "Província",
@@ -94,7 +95,7 @@ export function ProvinceSelect({
export function TerritoryFields({
initial = emptyTerritoryPath,
onChange,
endpoint = "/api/v1/investment/territory-options",
endpoint = "/api/v1/catalogs/jurisdictions",
}: {
initial?: TerritoryOption[];
onChange?: (path: TerritoryOption[]) => void;
@@ -114,7 +115,7 @@ export function TerritoryFields({
selected={path[index]}
endpoint={endpoint}
onChange={(value) => {
const next = [...path.slice(0, index), ...(value ? [value] : [])];
const next = replaceTerritoryPath(path, index, value);
setPath(next);
onChange?.(next);
}}
@@ -285,7 +286,7 @@ export default function InvestmentTerritory({ kind, id }: { kind: string; id: st
parent={path[index - 1]?.id ?? ""}
selected={path[index]}
onChange={(value) => {
setPath([...path.slice(0, index), ...(value ? [value] : [])]);
setPath(replaceTerritoryPath(path, index, value));
setMessage("");
}}
/>
+447
View File
@@ -0,0 +1,447 @@
import { useEffect, useId, useMemo, useRef, useState } from "react";
import {
getAutosaveSnapshot,
partitionSimulationDraft,
restoreSimulationDraft,
replaceSimulationValue,
simulationFieldGroups,
simulationDraftFingerprint,
simulationOptions,
simulationSections,
validateSimulationDraft,
type SimulationDraft,
} from "@/lib/simulation-form";
type Choice = { id: string; label: string };
const draftKey = "investmoz-simulation-draft-v1";
const tokenKey = "investmoz-simulation-token-v1";
const idempotencyStorageKey = "investmoz-simulation-idempotency-v1";
const draftCreateKey = "investmoz-simulation-draft-create-key-v1";
const draftIdKey = "investmoz-simulation-draft-id-v1";
const idempotencyKey = () => crypto.randomUUID();
function getSimulationToken(): string {
let token = sessionStorage.getItem(tokenKey);
if (!token) {
token = crypto.randomUUID().replaceAll("-", "") + crypto.randomUUID().replaceAll("-", "");
sessionStorage.setItem(tokenKey, token);
}
return token;
}
function csrfToken(): string {
return decodeURIComponent(document.cookie.split("; ").find(cookie => cookie.startsWith("XSRF-TOKEN="))?.slice(11) ?? "");
}
function labelFor(value: string): string {
const words: Record<string, string> = {
simulate_only: "Apenas simular", own_investment: "Investimento próprio", seek_investor: "Procurar investidor",
seek_partner: "Procurar parceiro", present_opportunity: "Apresentar oportunidade", request_facilitation: "Solicitar facilitação",
investment: "Investimento", business: "Negócio", singular: "Pessoa singular", collective: "Pessoa colectiva",
sole_trader: "Empresário em nome individual", consortium: "Consórcio", national: "Nacional", foreign: "Estrangeiro",
mixed: "Misto", existing: "Existente", being_formed: "Em constituição", "pt-MZ": "Português (Moçambique)", en: "English",
portal: "Portal", email: "Correio electrónico", phone: "Telefone", new: "Novo projecto", expansion: "Expansão",
acquisition: "Aquisição", partnership: "Parceria", concession: "Concessão", supplier: "Fornecedor", buyer: "Comprador",
other: "Outro", idea: "Ideia", concept: "Conceito", pre_feasibility: "Pré-viabilidade", feasibility: "Viabilidade",
financing: "Financiamento", implementation: "Implementação", operation: "Operação", owned: "Propriedade",
duat: "DUAT", leased: "Arrendado", requested: "Solicitado", unknown: "Por determinar", MZN: "MZN", USD: "USD",
EUR: "EUR", ZAR: "ZAR", A: "Categoria A", B: "Categoria B", C: "Categoria C", por_determinar: "Por determinar",
offer: "Oferta", demand: "Procura", both: "Oferta e procura", capital: "Capital", partner: "Parceiro",
land: "Terreno", technology: "Tecnologia", licence: "Licença", services: "Serviços", public: "Público",
registered_users: "Utilizadores registados", restricted: "Restrito", confidential: "Confidencial", yes: "Sim", no: "Não",
energy: "Energia",
};
return words[value] ?? value.replaceAll("_", " ");
}
function useChoices(source: string | undefined, query: string, parent: string, enabled: boolean) {
const [choices, setChoices] = useState<Choice[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const staticChoices = useMemo(() => {
if (source === "currency") {
const intl = Intl as unknown as { supportedValuesOf?: (key: string) => string[] };
return (intl.supportedValuesOf?.("currency") ?? []).map(code => ({ id: code, label: code }));
}
if (!source || ["country", "province", "district", "admin_post", "locality", "sector", "activity"].includes(source)) return [];
return (simulationOptions[source] ?? []).map(value => ({ id: value, label: labelFor(value) }));
}, [source]);
useEffect(() => {
if (!enabled || !source || !["country", "province", "district", "admin_post", "locality", "sector", "activity"].includes(source)) {
setChoices(staticChoices);
setError("");
return;
}
if (["district", "admin_post", "locality", "activity"].includes(source) && !parent) {
setChoices([]);
return;
}
const controller = new AbortController();
const timer = window.setTimeout(async () => {
setLoading(true);
setError("");
try {
let url: URL;
if (source === "sector") {
url = new URL("/api/v1/sectors", window.location.origin);
} else {
url = new URL("/api/v1/catalogs/" + (source === "activity" ? "economic-activities" : "jurisdictions"), window.location.origin);
url.searchParams.set("q", query);
url.searchParams.set("per_page", "50");
if (source === "activity") url.searchParams.set("sector_id", parent);
else {
url.searchParams.set("type", source === "country" ? "country" : source);
if (parent) url.searchParams.set("parent_id", parent);
}
}
const response = await fetch(url, { signal: controller.signal, headers: { Accept: "application/json" }, credentials: "same-origin" });
if (!response.ok) throw new Error("Não foi possível carregar as opções. Tente novamente.");
const payload = await response.json();
const rows = payload.data ?? [];
setChoices(rows.map((row: Record<string, unknown>) => ({
id: String(row.id ?? row.value ?? ""),
label: String(row.label ?? row.name ?? ""),
})).filter((row: Choice) => row.id && row.label));
} catch (cause) {
if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : "Erro ao carregar opções.");
} finally {
if (!controller.signal.aborted) setLoading(false);
}
}, 180);
return () => { window.clearTimeout(timer); controller.abort(); };
}, [source, query, parent, enabled, staticChoices]);
return { choices, loading, error, retry: () => setError("") };
}
function SearchChoice({
label, source, parent = "", value, selectedLabel, multiple, disabled, error, required, onChange,
}: {
label: string; source?: string; parent?: string; value: string | string[]; selectedLabel?: string | string[];
multiple?: boolean; disabled?: boolean; error?: string; required?: boolean; onChange: (value: string | string[], text?: string | string[]) => void;
}) {
const generated = useId();
const inputId = `choice-${generated}`;
const listId = `${inputId}-options`;
const [query, setQuery] = useState("");
const [open, setOpen] = useState(false);
const [active, setActive] = useState(-1);
const { choices, loading, error: loadError } = useChoices(source, query, parent, !disabled && open);
const chosen = Array.isArray(value) ? value : value ? [value] : [];
const filtered = choices.filter(option => option.label.toLocaleLowerCase().includes(query.toLocaleLowerCase()) || option.id.toLocaleLowerCase().includes(query.toLocaleLowerCase()));
const describedBy = [error ? `${inputId}-error` : "", loadError ? `${inputId}-load-error` : ""].filter(Boolean).join(" ") || undefined;
return <div className="space-y-1">
<label htmlFor={inputId} className="block text-sm font-medium">{label}</label>
<input id={inputId} role="combobox" aria-autocomplete="list" aria-expanded={open} aria-controls={listId}
aria-activedescendant={open && filtered[active] ? `${listId}-${active}` : undefined}
aria-invalid={Boolean(error || loadError)} aria-required={required || undefined} aria-describedby={describedBy} autoComplete="off"
className="w-full rounded-lg border border-slate-300 bg-white p-3 text-slate-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-700 disabled:bg-slate-100"
value={open ? query : multiple ? "" : selectedLabel || (chosen[0] ? choices.find(o => o.id === chosen[0])?.label ?? chosen[0] : "")}
placeholder={disabled ? "Seleccione primeiro o campo anterior" : "Pesquisar opções…"} disabled={disabled}
onFocus={() => { setOpen(true); setQuery(""); }}
onBlur={() => { window.setTimeout(() => setOpen(false), 120); }}
onChange={event => { setQuery(event.target.value); setActive(0); setOpen(true); }}
onKeyDown={event => {
if (event.key === "ArrowDown") { event.preventDefault(); setOpen(true); setActive(i => Math.min(i + 1, filtered.length - 1)); }
if (event.key === "ArrowUp") { event.preventDefault(); setActive(i => Math.max(0, i - 1)); }
if (event.key === "Enter" && open && filtered[active]) { event.preventDefault(); const option = filtered[active]; if (multiple) { if (!chosen.includes(option.id)) onChange([...chosen, option.id], [...(Array.isArray(selectedLabel) ? selectedLabel : []), option.label]); setQuery(""); } else { onChange(option.id, option.label); setQuery(""); setOpen(false); } }
if (event.key === "Escape") { setOpen(false); setQuery(""); }
if (event.key === "Backspace" && multiple && query === "" && chosen.length) onChange(chosen.slice(0, -1), Array.isArray(selectedLabel) ? selectedLabel.slice(0, -1) : []);
}} />
{multiple && chosen.length > 0 && <ul aria-label={`Opções seleccionadas: ${label}`} className="flex flex-wrap gap-2">
{chosen.map((item, index) => { const text = Array.isArray(selectedLabel) ? selectedLabel[index] : choices.find(option => option.id === item)?.label ?? item; return <li key={item} className="flex items-center gap-1 rounded bg-emerald-50 px-2 py-1 text-sm">
{text}
<button type="button" aria-label={`Remover ${text}`} onClick={() => onChange(chosen.filter((_, i) => i !== index), Array.isArray(selectedLabel) ? selectedLabel.filter((_, i) => i !== index) : [])} className="rounded px-1 focus-visible:outline-2">×</button>
</li>; })}
</ul>}
{open && !disabled && <ul id={listId} role="listbox" aria-label={label} aria-multiselectable={multiple || undefined} className="max-h-56 overflow-auto rounded border bg-white shadow-lg">
{loading && <li role="status" className="p-3 text-sm">A carregar opções…</li>}
{!loading && filtered.map((option, index) => <li id={`${listId}-${index}`} key={option.id} role="option" aria-selected={chosen.includes(option.id)}
className={`cursor-pointer p-3 text-sm hover:bg-emerald-50 ${active === index ? "bg-emerald-50" : ""}`}
onMouseEnter={() => setActive(index)} onMouseDown={event => event.preventDefault()}
onClick={() => { if (multiple) { if (!chosen.includes(option.id)) onChange([...chosen, option.id], [...(Array.isArray(selectedLabel) ? selectedLabel : []), option.label]); setQuery(""); } else { onChange(option.id, option.label); setQuery(""); setOpen(false); } }}>
{option.label}{chosen.includes(option.id) ? " ✓" : ""}
</li>)}
{!loading && filtered.length === 0 && <li className="p-3 text-sm">Sem opções correspondentes.</li>}
</ul>}
{loadError && <p id={`${inputId}-load-error`} role="alert" className="text-sm text-red-800">{loadError}</p>}
{error && <p id={`${inputId}-error`} role="alert" className="text-sm text-red-800">{error}</p>}
</div>;
}
export function SimulationForm() {
const [draft, setDraft] = useState<SimulationDraft>({});
const [ready, setReady] = useState(false);
const [step, setStep] = useState(0);
const [errors, setErrors] = useState<Record<string, string>>({});
const [saveStatus, setSaveStatus] = useState("Rascunho ainda não guardado.");
const [serverError, setServerError] = useState("");
const [isCalculating, setIsCalculating] = useState(false);
const [hasSaveConflict, setHasSaveConflict] = useState(false);
const [result, setResult] = useState<Record<string, unknown> | null>(null);
const calculationInFlightRef = useRef(false);
const draftIdRef = useRef<string | null>(null);
const draftEtagRef = useRef<string | null>(null);
const lastSavedFingerprintRef = useRef<string | null>(null);
const saveQueueRef = useRef<Promise<void>>(Promise.resolve());
const saveConflictRef = useRef(false);
const current = simulationSections[step];
const fields = (simulationFieldGroups[current.id] ?? []).filter(field => !field.showWhen || field.showWhen(draft));
useEffect(() => {
let cancelled = false;
void (async () => {
let local: SimulationDraft = {};
try {
const stored = sessionStorage.getItem(draftKey);
if (stored) local = JSON.parse(stored) as SimulationDraft;
} catch { setSaveStatus("Não foi possível recuperar o rascunho desta sessão."); }
try {
const response = await fetch("/api/v1/simulation-drafts/current", {
credentials: "same-origin", headers: { Accept: "application/json", "X-Simulation-Token": getSimulationToken() },
});
if (response.ok) {
const payload = await response.json();
if (payload.data) {
draftIdRef.current = payload.data.id;
draftEtagRef.current = response.headers.get("ETag");
sessionStorage.setItem(draftIdKey, payload.data.id);
const restored = restoreSimulationDraft(payload.data.economic_snapshot, payload.data.personal_snapshot);
lastSavedFingerprintRef.current = simulationDraftFingerprint(restored);
setDraft({ ...restored, ...local });
setSaveStatus("Rascunho recuperado do servidor.");
} else if (Object.keys(local).length) {
const storedId = sessionStorage.getItem(draftIdKey);
if (storedId) sessionStorage.removeItem(draftIdKey);
setDraft(local);
}
} else if (Object.keys(local).length) setDraft(local);
} catch {
if (Object.keys(local).length) setDraft(local);
setSaveStatus("Sem ligação ao servidor; o rascunho desta sessão será mantido localmente.");
}
if (!cancelled) setReady(true);
})();
return () => { cancelled = true; };
}, []);
useEffect(() => {
if (!ready || !draft.purpose) return;
const timer = window.setTimeout(() => {
try {
sessionStorage.setItem(draftKey, JSON.stringify(getAutosaveSnapshot(draft)));
}
catch { setSaveStatus("Não foi possível guardar o rascunho neste navegador."); }
if (saveConflictRef.current) return;
const snapshots = partitionSimulationDraft(draft);
const fingerprint = simulationDraftFingerprint(draft);
if (fingerprint === lastSavedFingerprintRef.current) return;
setSaveStatus("A guardar o rascunho no servidor…");
saveQueueRef.current = saveQueueRef.current.then(async () => {
const token = getSimulationToken();
const headers = { Accept: "application/json", "Content-Type": "application/json", "X-XSRF-TOKEN": csrfToken(), "X-Simulation-Token": token };
if (!draftIdRef.current) {
const currentResponse = await fetch("/api/v1/simulation-drafts/current", { credentials: "same-origin", headers: { Accept: "application/json", "X-Simulation-Token": token } });
const currentPayload = currentResponse.ok ? await currentResponse.json() : { data: null };
if (currentPayload.data) {
draftIdRef.current = currentPayload.data.id;
draftEtagRef.current = currentResponse.headers.get("ETag");
sessionStorage.setItem(draftIdKey, currentPayload.data.id);
}
}
let response: Response;
if (draftIdRef.current && draftEtagRef.current) {
response = await fetch(`/api/v1/simulation-drafts/${draftIdRef.current}`, {
method: "PUT", credentials: "same-origin", headers: { ...headers, "If-Match": draftEtagRef.current }, body: JSON.stringify(snapshots),
});
} else {
let key = sessionStorage.getItem(draftCreateKey);
if (!key) { key = idempotencyKey(); sessionStorage.setItem(draftCreateKey, key); }
response = await fetch("/api/v1/simulation-drafts", {
method: "POST", credentials: "same-origin", headers: { ...headers, "Idempotency-Key": key }, body: JSON.stringify(snapshots),
});
}
if (response.status === 412 || response.status === 428) {
saveConflictRef.current = true;
setHasSaveConflict(true);
setSaveStatus("O rascunho mudou noutro separador. Recarregue para rever a versão mais recente.");
return;
}
const payload = await response.json();
if (!response.ok) throw new Error(payload.message ?? "Não foi possível guardar o rascunho no servidor.");
draftIdRef.current = payload.data.id;
draftEtagRef.current = response.headers.get("ETag");
lastSavedFingerprintRef.current = fingerprint;
sessionStorage.setItem(draftIdKey, payload.data.id);
sessionStorage.removeItem(draftCreateKey);
setSaveStatus(`Rascunho guardado no servidor às ${new Intl.DateTimeFormat("pt-MZ", { timeStyle: "short" }).format(new Date())}.`);
}).catch(cause => {
setSaveStatus(cause instanceof Error ? cause.message : "Erro ao guardar o rascunho no servidor.");
});
}, 450);
return () => window.clearTimeout(timer);
}, [draft, ready]);
function change(key: string, value: string | string[], label?: string | string[]) {
setDraft(currentDraft => {
const next = replaceSimulationValue(currentDraft, key, value);
if (label) next[`${key}_label`] = label;
return next;
});
setErrors(current => { const next = { ...current }; delete next[key]; return next; });
setResult(null);
}
async function clearDraft() {
await saveQueueRef.current;
if (draftIdRef.current && draftEtagRef.current) {
const response = await fetch(`/api/v1/simulation-drafts/${draftIdRef.current}`, {
method: "DELETE", credentials: "same-origin",
headers: { Accept: "application/json", "X-XSRF-TOKEN": csrfToken(), "X-Simulation-Token": getSimulationToken(), "If-Match": draftEtagRef.current },
});
if (!response.ok) { setSaveStatus("Não foi possível remover o rascunho do servidor. Recarregue e tente novamente."); return; }
}
for (const key of [draftKey, draftIdKey, draftCreateKey, idempotencyStorageKey, tokenKey]) sessionStorage.removeItem(key);
draftIdRef.current = null;
draftEtagRef.current = null;
lastSavedFingerprintRef.current = null;
saveConflictRef.current = false;
setHasSaveConflict(false);
setDraft({});
setResult(null);
setErrors({});
setStep(0);
setSaveStatus("Rascunho removido do servidor e desta sessão.");
}
function navigate(nextStep: number) {
if (nextStep > step) {
for (let index = step; index < nextStep; index++) {
const validation = validateSimulationDraft(draft, simulationSections[index].id);
if (Object.keys(validation).length) {
setStep(index);
setErrors(validation);
window.requestAnimationFrame(() => document.getElementById(`field-${Object.keys(validation)[0]}`)?.focus());
return;
}
}
}
setStep(nextStep);
setErrors({});
document.getElementById("simulator-step-title")?.focus();
}
async function runSimulation() {
if (calculationInFlightRef.current) return;
const validation = validateSimulationDraft(draft, "tax");
setErrors(validation);
setServerError("");
if (draft.tax_calculation !== "yes") return;
if (Object.keys(validation).length) { document.getElementById(`field-${Object.keys(validation)[0]}`)?.focus(); return; }
calculationInFlightRef.current = true;
setIsCalculating(true);
try {
const token = getSimulationToken();
const xsrf = csrfToken();
const body = { base: draft.base, rate: draft.rate, reduction: draft.reduction };
const serialized = JSON.stringify(body);
const previous = sessionStorage.getItem(idempotencyStorageKey);
let key = "";
if (previous) {
try { const saved = JSON.parse(previous) as { payload?: string; key?: string }; if (saved.payload === serialized && saved.key) key = saved.key; } catch { /* replace malformed local state */ }
}
if (!key) { key = idempotencyKey(); sessionStorage.setItem(idempotencyStorageKey, JSON.stringify({ payload: serialized, key })); }
const response = await fetch("/api/v1/simulations", {
method: "POST", credentials: "same-origin",
headers: { "Accept": "application/json", "Content-Type": "application/json", "X-XSRF-TOKEN": xsrf, "Idempotency-Key": key, "X-Simulation-Token": token },
body: serialized,
});
const payload = await response.json();
if (!response.ok) {
if (response.status === 429) {
const retryAfter = Number(response.headers.get("Retry-After") ?? 60);
throw new Error(`Demasiadas tentativas. Aguarde ${retryAfter} segundos antes de voltar a calcular.`);
}
const serverErrors = payload.errors ? Object.values(payload.errors).flat().join(" ") : payload.message;
throw new Error(typeof serverErrors === "string" ? serverErrors : "Não foi possível validar o cenário no servidor.");
}
const simulationId = payload.data?.id;
let simulation = payload.data;
if (simulationId && simulation?.status !== "completed" && simulation?.status !== "failed") {
setSaveStatus("Cenário enviado. A aguardar o cálculo…");
for (let attempt = 0; attempt < 12; attempt++) {
await new Promise(resolve => window.setTimeout(resolve, 1000));
const poll = await fetch(`/api/v1/simulations/${simulationId}`, { credentials: "same-origin", headers: { Accept: "application/json", "X-Simulation-Token": token } });
if (!poll.ok) break;
const pollPayload = await poll.json();
simulation = pollPayload.data;
if (simulation?.status === "completed" || simulation?.status === "failed") break;
}
}
if (JSON.stringify({ base: draft.base, rate: draft.rate, reduction: draft.reduction }) === serialized) setResult(simulation ?? null);
sessionStorage.removeItem(idempotencyStorageKey);
} catch (cause) { setServerError(cause instanceof Error ? cause.message : "Erro de ligação. Tente novamente."); }
finally { calculationInFlightRef.current = false; setIsCalculating(false); }
}
return <section className="space-y-6 rounded-xl border bg-white p-4 sm:p-6" aria-labelledby="simulator-step-title">
<div className="flex flex-wrap items-start justify-between gap-3">
<div><h2 id="simulator-step-title" tabIndex={-1} className="text-xl font-bold outline-none">Formulário de simulação e manifestação</h2>
<p className="mt-1 text-sm text-slate-700">Simulação informativa. Nenhuma taxa legal, elegibilidade ou moeda é presumida.</p></div>
<p role="status" aria-live="polite" className="text-sm">{saveStatus}</p>
</div>
<nav aria-label="Etapas do formulário" className="overflow-x-auto">
<ol className="flex min-w-max gap-2">
{simulationSections.map((section, index) => <li key={section.id}><button type="button" aria-current={step === index ? "step" : undefined}
onClick={() => navigate(index)} className={`rounded-full border px-3 py-2 text-sm focus-visible:outline-2 ${step === index ? "border-emerald-800 bg-emerald-800 text-white" : "bg-white"}`}>
{index + 1}. {section.title}
</button></li>)}
</ol>
</nav>
<div className="h-2 overflow-hidden rounded bg-slate-200" role="progressbar" aria-label="Progresso do formulário" aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(((step + 1) / simulationSections.length) * 100)}>
<div className="h-full bg-emerald-800" style={{ width: `${((step + 1) / simulationSections.length) * 100}%` }} />
</div>
<h3 className="text-lg font-semibold">{current.title}</h3>
<div className="grid gap-4 sm:grid-cols-2">
{fields.map(field => {
const fieldError = errors[field.key];
if (field.options) {
const parentKey = field.key === "district_id" ? "province_id" : field.key === "admin_post_id" ? "district_id" : field.key === "locality_id" ? "admin_post_id" : field.key === "activity_id" ? "sector_id" : "";
return <div key={field.key} id={`field-${field.key}`} tabIndex={-1}>
<SearchChoice label={`${field.label}${field.required ? " (obrigatório)" : ""}`} source={field.options} parent={parentKey ? String(draft[parentKey] ?? "") : ""}
value={draft[field.key] ?? (field.multiple ? [] : "")} selectedLabel={draft[`${field.key}_label`] as string | string[] | undefined} multiple={field.multiple}
disabled={Boolean(parentKey && !draft[parentKey])} error={fieldError} required={field.required}
onChange={(value, text) => change(field.key, value, text)} />
</div>;
}
const isArea = ["area_required"].includes(field.key);
return <div key={field.key}>
<label htmlFor={`field-${field.key}`} className="mb-1 block text-sm font-medium">{field.label}{field.required ? " (obrigatório)" : ""}</label>
{field.type === "textarea" ? <textarea id={`field-${field.key}`} className="min-h-28 w-full rounded-lg border border-slate-300 p-3 focus-visible:outline-2 focus-visible:outline-emerald-700" value={String(draft[field.key] ?? "")} onChange={e => change(field.key, e.target.value)} aria-invalid={Boolean(fieldError)} aria-required={field.required || undefined} aria-describedby={fieldError ? `error-${field.key}` : undefined} />
: <input id={`field-${field.key}`} type={field.type ?? (isArea ? "number" : "text")} min={field.type === "number" ? "0" : undefined} step={field.type === "number" ? "any" : undefined} className="w-full rounded-lg border border-slate-300 p-3 focus-visible:outline-2 focus-visible:outline-emerald-700" value={String(draft[field.key] ?? "")} onChange={e => change(field.key, e.target.value)} aria-invalid={Boolean(fieldError)} aria-required={field.required || undefined} aria-describedby={fieldError ? `error-${field.key}` : undefined} />}
{fieldError && <p id={`error-${field.key}`} role="alert" className="mt-1 text-sm text-red-800">{fieldError}</p>}
{field.key === "reduction" && <p className="mt-1 text-sm text-slate-600">Hipótese sua, não representa um benefício fiscal aprovado.</p>}
</div>;
})}
</div>
{current.id === "financial" && <p className="rounded bg-amber-50 p-3 text-sm">Os montantes são introduzidos pelo utilizador. Confirme que capital, dívida e subvenções reconciliam com o investimento total.</p>}
{current.id === "tax" && <div className="space-y-3 border-t pt-4">
<h4 className="font-semibold">Executar cenário aritmético</h4>
{draft.tax_calculation === "yes" && <button type="button" disabled={isCalculating} aria-busy={isCalculating} className="rounded-lg bg-emerald-800 px-4 py-3 font-semibold text-white focus-visible:outline-2 disabled:cursor-wait disabled:opacity-60" onClick={() => void runSimulation()}>{isCalculating ? "A calcular…" : "Validar e calcular no servidor"}</button>}
{serverError && <p role="alert" className="text-red-800">{serverError}</p>}
{result && <div role="status" className="rounded bg-emerald-50 p-4"><p>Simulação {String(result.status ?? "recebida")}.</p>
{result.status === "completed" && <p>Resultado aritmético indicativo: <strong>{String((result.result_snapshot as Record<string, unknown> | undefined)?.indicative_total ?? "disponível no relatório")}</strong></p>}
{result.status === "failed" && <p role="alert">O cálculo não foi concluído. Reveja os valores e tente novamente.</p>}
{result.status === "queued" || result.status === "running" ? <p className="text-sm">O cálculo continua pendente. Pode consultar o histórico quando estiver disponível.</p> : null}
<p className="text-sm">O resultado é indicativo e não determina taxas legais, elegibilidade ou obrigação fiscal.</p></div>}
</div>}
{hasSaveConflict && <p role="alert" className="rounded border border-amber-700 bg-amber-50 p-3">Este rascunho foi alterado noutro separador. <button type="button" className="font-semibold underline" onClick={() => window.location.reload()}>Recarregar a versão mais recente</button></p>}
<div className="flex flex-wrap justify-between gap-3 border-t pt-4">
<button type="button" disabled={step === 0} onClick={() => navigate(Math.max(0, step - 1))} className="rounded border px-4 py-3 disabled:opacity-50 focus-visible:outline-2">Anterior</button>
{step < simulationSections.length - 1
? <button type="button" onClick={() => navigate(step + 1)} className="rounded-lg bg-emerald-800 px-5 py-3 font-semibold text-white focus-visible:outline-2">Guardar e continuar</button>
: <button type="button" onClick={() => void clearDraft()} className="rounded border px-4 py-3 focus-visible:outline-2">Limpar este rascunho</button>}
</div>
<p className="text-xs text-slate-600">O rascunho é cifrado e guardado no servidor. O navegador mantém apenas o token temporário e os dados não identificativos necessários à recuperação da sessão. A submissão formal ainda não está disponível neste formulário.</p>
</section>;
}
+276
View File
@@ -0,0 +1,276 @@
export type SimulationDraft = Record<string, string | string[]>;
export const simulationSections = [
{ id: "purpose", title: "Finalidade" },
{ id: "promoter", title: "Perfil do promotor" },
{ id: "identity", title: "Identificação e contactos" },
{ id: "project", title: "Projecto ou negócio" },
{ id: "location", title: "Localização" },
{ id: "financial", title: "Estrutura financeira" },
{ id: "impact", title: "Emprego e impacto" },
{ id: "tax", title: "Operação fiscal" },
{ id: "opportunity", title: "Necessidade de negócio" },
{ id: "documents", title: "Documentos" },
{ id: "review", title: "Revisão" },
] as const;
export const simulationOptions: Record<string, string[]> = {
purpose: ["simulate_only", "own_investment", "seek_investor", "seek_partner", "present_opportunity", "request_facilitation"],
manifestation_type: ["investment", "business"],
person_type: ["singular", "collective", "sole_trader", "consortium"],
investor_origin: ["national", "foreign", "mixed"],
entity_stage: ["existing", "being_formed"],
preferred_language: ["pt-MZ", "en"],
preferred_channel: ["portal", "email", "phone"],
project_type: ["new", "expansion", "acquisition", "partnership", "concession", "supplier", "buyer", "other"],
maturity_stage: ["idea", "concept", "pre_feasibility", "feasibility", "financing", "implementation", "operation"],
land_status: ["owned", "duat", "leased", "requested", "unknown"],
environmental_category: ["A", "B", "C", "por_determinar"],
offer_or_demand: ["offer", "demand", "both"],
opportunity_type: ["capital", "partner", "buyer", "supplier", "land", "technology", "licence", "services", "other"],
confidentiality: ["public", "registered_users", "restricted", "confidential"],
preferred_publication: ["yes", "no"],
residency_status: ["resident", "non_resident"],
tax_calculation: ["yes", "no"],
document_types: ["identity_document", "company_registration", "nuit_certificate", "company_profile", "business_plan", "feasibility_study", "proof_of_funds", "special_zone_certificate", "licence", "site_map"],
area_unit: ["m2", "ha", "km2"],
};
export const simulationFieldGroups: Record<string, { key: string; label: string; type?: "number" | "date" | "email" | "textarea"; required?: boolean; options?: string; multiple?: boolean; showWhen?: (draft: SimulationDraft) => boolean }[]> = {
purpose: [
{ key: "purpose", label: "O que pretende fazer?", options: "purpose", required: true },
{ key: "manifestation_type", label: "Tipo de manifestação", options: "manifestation_type", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "preferred_language", label: "Idioma preferido", options: "preferred_language", required: true },
],
promoter: [
{ key: "person_type", label: "Tipo de pessoa", options: "person_type", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "investor_origin", label: "Origem do investidor", options: "investor_origin", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "tax_residency_country", label: "País de residência fiscal", options: "country", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "entity_stage", label: "Situação da entidade", options: "entity_stage", required: true, showWhen: d => d.purpose !== "simulate_only" && ["collective", "consortium"].includes(String(d.person_type)) },
{ key: "legal_form", label: "Forma jurídica (conforme o registo)", required: true, showWhen: d => d.purpose !== "simulate_only" && d.entity_stage === "existing" },
{ key: "nuit", label: "NUIT", showWhen: d => d.purpose !== "simulate_only" },
],
identity: [
{ key: "legal_name", label: "Nome / denominação", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "commercial_name", label: "Nome comercial", showWhen: d => d.purpose !== "simulate_only" },
{ key: "registration_number", label: "Número de registo", required: true, showWhen: d => d.entity_stage === "existing" && d.purpose !== "simulate_only" },
{ key: "representative_name", label: "Nome do representante", required: true, showWhen: d => ["collective", "consortium"].includes(String(d.person_type)) && d.purpose !== "simulate_only" },
{ key: "email", label: "Correio electrónico", type: "email", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "phone", label: "Telefone", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "address", label: "Endereço", type: "textarea", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "preferred_channel", label: "Canal de contacto", options: "preferred_channel", required: true, showWhen: d => d.purpose !== "simulate_only" },
],
project: [
{ key: "project_title", label: "Título do projecto", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "project_summary", label: "Resumo executivo", type: "textarea", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "project_type", label: "Tipo de projecto", options: "project_type", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "project_type_other", label: "Especifique o tipo de projecto", required: true, showWhen: d => d.purpose !== "simulate_only" && d.project_type === "other" },
{ key: "sector_id", label: "Sector de actividade", options: "sector", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "activity_id", label: "Actividade económica", options: "activity", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "products_services", label: "Produtos e serviços", type: "textarea", showWhen: d => d.purpose !== "simulate_only" },
{ key: "maturity_stage", label: "Fase de maturidade", options: "maturity_stage", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "expected_start_date", label: "Data prevista de início", type: "date", showWhen: d => d.purpose !== "simulate_only" },
{ key: "project_duration_years", label: "Duração prevista (anos)", type: "number", showWhen: d => d.purpose !== "simulate_only" },
{ key: "existing_project_id", label: "Referência do projecto existente", showWhen: d => d.project_type === "expansion" },
],
location: [
{ key: "province_id", label: "Província", options: "province", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "district_id", label: "Distrito", options: "district", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "admin_post_id", label: "Posto administrativo", options: "admin_post", showWhen: d => d.purpose !== "simulate_only" },
{ key: "locality_id", label: "Localidade", options: "locality", showWhen: d => d.purpose !== "simulate_only" },
{ key: "site_known", label: "Local conhecido?", options: "yes_no", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "land_status", label: "Situação do terreno", options: "land_status", showWhen: d => d.purpose !== "simulate_only" },
{ key: "area_required", label: "Área necessária", type: "number", showWhen: d => d.purpose !== "simulate_only" },
{ key: "area_unit", label: "Unidade da área", options: "area_unit", showWhen: d => d.purpose !== "simulate_only" },
{ key: "latitude", label: "Latitude", type: "number", showWhen: d => d.site_known === "yes" },
{ key: "longitude", label: "Longitude", type: "number", showWhen: d => d.site_known === "yes" },
{ key: "special_zone_id", label: "Zona especial ZEE/ZFI", showWhen: d => d.purpose !== "simulate_only" },
{ key: "infrastructure_needs", label: "Necessidades de infra-estrutura", options: "infrastructure", multiple: true, showWhen: d => d.purpose !== "simulate_only" },
],
financial: [
{ key: "currency", label: "Moeda", options: "currency", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "total_investment", label: "Investimento total", type: "number", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "own_capital", label: "Capital próprio", type: "number", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "domestic_debt", label: "Financiamento interno", type: "number", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "foreign_debt", label: "Financiamento externo", type: "number", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "grants", label: "Subvenções", type: "number", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "secured_amount", label: "Montante mobilizado", type: "number", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "sought_amount", label: "Montante procurado", type: "number", showWhen: d => d.purpose !== "simulate_only" },
{ key: "annual_revenue", label: "Receitas anuais estimadas", type: "number", showWhen: d => d.purpose !== "simulate_only" },
{ key: "annual_operating_costs", label: "Custos operacionais anuais", type: "number", showWhen: d => d.purpose !== "simulate_only" },
{ key: "expected_profit", label: "Lucro esperado", type: "number", showWhen: d => d.purpose !== "simulate_only" },
{ key: "financing_term_months", label: "Prazo de financiamento (meses)", type: "number", showWhen: d => Number(d.domestic_debt) + Number(d.foreign_debt) > 0 },
{ key: "funds_origin_countries", label: "Países de origem dos fundos", options: "country", multiple: true, showWhen: d => Number(d.foreign_debt) > 0 },
],
impact: [
{ key: "direct_jobs", label: "Empregos directos", type: "number", showWhen: d => d.purpose !== "simulate_only" },
{ key: "indirect_jobs", label: "Empregos indirectos", type: "number", showWhen: d => d.purpose !== "simulate_only" },
{ key: "national_jobs", label: "Empregos nacionais", type: "number", showWhen: d => d.purpose !== "simulate_only" },
{ key: "foreign_jobs", label: "Empregos estrangeiros", type: "number", showWhen: d => d.purpose !== "simulate_only" },
{ key: "exports_value", label: "Exportações estimadas", type: "number" },
{ key: "import_substitution_value", label: "Substituição de importações estimada", type: "number" },
{ key: "skills_needed", label: "Qualificações/competências necessárias", type: "textarea" },
{ key: "local_content_percentage", label: "Conteúdo local (%)", type: "number" },
{ key: "environmental_category", label: "Categoria ambiental", options: "environmental_category" },
{ key: "community_benefits", label: "Benefícios comunitários", type: "textarea" },
],
tax: [
{ key: "tax_calculation", label: "Pretende calcular um cenário aritmético?", options: "tax_calculation", required: true },
{ key: "base", label: "Base para o cenário", type: "number", required: true, showWhen: d => d.tax_calculation === "yes" },
{ key: "rate", label: "Taxa hipotética do cenário (%)", type: "number", required: true, showWhen: d => d.tax_calculation === "yes" },
{ key: "reduction", label: "Redução hipotética (%)", type: "number", required: true, showWhen: d => d.tax_calculation === "yes" },
{ key: "sales_taxable", label: "Vendas tributadas", type: "number", showWhen: d => d.purpose !== "simulate_only" },
{ key: "sales_exempt", label: "Vendas isentas", type: "number", showWhen: d => d.purpose !== "simulate_only" },
{ key: "sales_zero_rate", label: "Vendas à taxa zero", type: "number", showWhen: d => d.purpose !== "simulate_only" },
{ key: "exports", label: "Exportações", type: "number", showWhen: d => d.purpose !== "simulate_only" },
{ key: "deductible_costs", label: "Custos dedutíveis", type: "number", showWhen: d => d.purpose !== "simulate_only" },
{ key: "non_deductible_costs", label: "Custos não dedutíveis", type: "number", showWhen: d => d.purpose !== "simulate_only" },
{ key: "carried_losses", label: "Prejuízos transitados", type: "number", showWhen: d => d.purpose !== "simulate_only" },
{ key: "payroll", label: "Dados de remunerações (estrutura prevista)", type: "textarea", showWhen: d => d.purpose !== "simulate_only" },
{ key: "outbound_payments", label: "Pagamentos ao exterior (estrutura prevista)", type: "textarea", showWhen: d => d.purpose !== "simulate_only" },
{ key: "imports", label: "Importações (estrutura prevista)", type: "textarea", showWhen: d => d.purpose !== "simulate_only" },
{ key: "claimed_benefits", label: "Benefícios alegados para validação", type: "textarea", showWhen: d => d.purpose !== "simulate_only" },
{ key: "reference_date", label: "Data de referência", type: "date", required: true, showWhen: d => d.purpose !== "simulate_only" },
],
opportunity: [
{ key: "offer_or_demand", label: "Oferta ou procura", options: "offer_or_demand", showWhen: d => d.manifestation_type === "business" },
{ key: "opportunity_type", label: "Necessidade de negócio", options: "opportunity_type", showWhen: d => d.manifestation_type === "business" },
{ key: "opportunity_type_other", label: "Especifique a necessidade", required: true, showWhen: d => d.manifestation_type === "business" && d.opportunity_type === "other" },
{ key: "opportunity_description", label: "Descrição da necessidade", type: "textarea", showWhen: d => d.manifestation_type === "business" },
{ key: "opportunity_value", label: "Valor da oportunidade", type: "number", showWhen: d => d.manifestation_type === "business" },
{ key: "opportunity_currency", label: "Moeda da oportunidade", options: "currency", showWhen: d => d.manifestation_type === "business" && Boolean(d.opportunity_value) },
{ key: "opportunity_conditions", label: "Condições da oportunidade", type: "textarea", showWhen: d => d.manifestation_type === "business" },
{ key: "opportunity_deadline", label: "Prazo da oportunidade", type: "date", showWhen: d => d.manifestation_type === "business" },
{ key: "confidentiality", label: "Confidencialidade", options: "confidentiality", showWhen: d => d.manifestation_type === "business" },
{ key: "publish_requested", label: "Pretende pedir publicação?", options: "preferred_publication", showWhen: d => d.manifestation_type === "business" },
],
documents: [
{ key: "required_documents", label: "Documentos aplicáveis a preparar", options: "document_types", multiple: true, showWhen: d => d.purpose !== "simulate_only" },
],
review: [
{ key: "terms_accepted", label: "Aceito os termos de utilização", options: "yes_no", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "truth_declaration", label: "Declaro que as informações são verdadeiras", options: "yes_no", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "reuse_simulation", label: "Autorizo reutilizar os dados da simulação", options: "yes_no", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "contact_authorisation", label: "Autorizo contacto para acompanhamento", options: "yes_no", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "publication_authorisation", label: "Autorizo a publicação solicitada", options: "yes_no", required: true, showWhen: d => d.publish_requested === "yes" },
{ key: "public_fields_confirmation", label: "Confirmo os campos propostos para publicação", options: "yes_no", required: true, showWhen: d => d.publish_requested === "yes" },
{ key: "validation_acknowledged", label: "Confirmo que li os avisos de validação", options: "yes_no", required: true, showWhen: d => d.purpose !== "simulate_only" },
{ key: "final_declaration_name", label: "Nome para a declaração final", required: true, showWhen: d => d.purpose !== "simulate_only" },
],
};
simulationOptions.yes_no = ["yes", "no"];
simulationOptions.infrastructure = ["energia", "água", "estrada", "porto", "ferrovia", "telecomunicações", "armazenamento"];
export function replaceSimulationValue(draft: SimulationDraft, key: string, value: string | string[]): SimulationDraft {
const next = { ...draft, [key]: value };
const dependencies: Record<string, string[]> = {
province_id: ["district_id", "admin_post_id", "locality_id"],
district_id: ["admin_post_id", "locality_id"],
admin_post_id: ["locality_id"],
sector_id: ["activity_id"],
site_known: ["latitude", "longitude"],
project_type: ["project_type_other"],
opportunity_type: ["opportunity_type_other"],
foreign_debt: ["funds_origin_countries"],
tax_calculation: ["base", "rate", "reduction"],
};
const clearChildren = key === "foreign_debt" && Number(value) > 0 && Number(draft[key] ?? 0) > 0 ? [] : (dependencies[key] ?? []);
for (const child of clearChildren) {
delete next[child];
delete next[`${child}_label`];
}
if (key === "purpose" && value === "simulate_only") {
for (const fields of Object.values(simulationFieldGroups)) for (const field of fields) {
if (["purpose", "preferred_language"].includes(field.key)) continue;
delete next[field.key];
delete next[`${field.key}_label`];
}
}
if (key === "manifestation_type" && value !== "business") {
for (const field of simulationFieldGroups.opportunity) { delete next[field.key]; delete next[`${field.key}_label`]; }
}
return next;
}
const privateDraftKeys = new Set([
"person_type", "investor_origin", "tax_residency_country", "entity_stage", "legal_form", "nuit",
"investor_profile_id", "profile_confirmation", "legal_name", "commercial_name", "registration_number",
"representative_name", "representative_capacity", "email", "phone", "address", "contact_country",
"contact_province", "contact_district", "preferred_channel",
]);
export function getAutosaveSnapshot(draft: SimulationDraft): SimulationDraft {
return Object.fromEntries(Object.entries(draft).filter(([key]) => {
const field = key.replace(/_label$/, "");
return !privateDraftKeys.has(field);
}));
}
export function partitionSimulationDraft(draft: SimulationDraft): {
personal_snapshot: Record<string, unknown>;
economic_snapshot: Record<string, unknown>;
} {
const personal_snapshot: Record<string, unknown> = {};
const economic_snapshot: Record<string, unknown> = {};
const personal_labels: Record<string, string | string[]> = {};
const economic_labels: Record<string, string | string[]> = {};
for (const [key, value] of Object.entries(draft)) {
if (key.endsWith("_label")) {
const target = privateDraftKeys.has(key.slice(0, -6)) ? personal_labels : economic_labels;
target[key.slice(0, -6)] = value;
continue;
}
(privateDraftKeys.has(key) ? personal_snapshot : economic_snapshot)[key] = value;
}
if (Object.keys(personal_labels).length) personal_snapshot.selection_labels = personal_labels;
if (Object.keys(economic_labels).length) economic_snapshot.selection_labels = economic_labels;
return { personal_snapshot, economic_snapshot };
}
export function restoreSimulationDraft(economic: Record<string, unknown>, personal: Record<string, unknown>): SimulationDraft {
const draft = { ...economic, ...personal } as Record<string, unknown>;
const labels = { ...(economic.selection_labels as Record<string, unknown> | undefined), ...(personal.selection_labels as Record<string, unknown> | undefined) };
delete draft.selection_labels;
delete draft.personal_snapshot;
if (labels && typeof labels === "object") {
for (const [key, value] of Object.entries(labels)) {
if (typeof value === "string" || (Array.isArray(value) && value.every(item => typeof item === "string"))) {
draft[`${key}_label`] = Array.isArray(draft[key]) ? value : Array.isArray(value) ? value[0] : value;
}
}
}
return draft as SimulationDraft;
}
export function simulationDraftFingerprint(draft: SimulationDraft): string {
const sort = (value: unknown): unknown => {
if (Array.isArray(value)) return value.map(sort);
if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, entry]) => [key, sort(entry)]));
return value;
};
return JSON.stringify(sort(partitionSimulationDraft(draft)));
}
export function validateSimulationDraft(draft: SimulationDraft, sectionId: string): Record<string, string> {
const errors: Record<string, string> = {};
for (const field of simulationFieldGroups[sectionId] ?? []) {
if (field.showWhen && !field.showWhen(draft)) continue;
const value = draft[field.key];
const empty = value === undefined || value === "" || (Array.isArray(value) && value.length === 0);
if (field.required && empty) errors[field.key] = "Este campo é obrigatório.";
if (field.type === "number" && value !== undefined && value !== "") {
const number = Number(value);
if (!Number.isFinite(number) || number < 0) errors[field.key] = "Introduza um número igual ou superior a zero.";
}
if (["rate", "reduction", "local_content_percentage"].includes(field.key) && value !== undefined && value !== "") {
if (Number(value) > 100) errors[field.key] = "O valor não pode exceder 100.";
}
if (field.key === "email" && typeof value === "string" && value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) errors[field.key] = "Introduza um endereço de correio electrónico válido.";
}
if (sectionId === "financial" && ["own_capital", "domestic_debt", "foreign_debt", "grants", "total_investment"].every(key => draft[key] !== undefined && draft[key] !== "")) {
const total = ["own_capital", "domestic_debt", "foreign_debt", "grants"].reduce((sum, key) => sum + Number(draft[key]), 0);
if (Math.abs(total - Number(draft.total_investment)) > 0.01) errors.total_investment = "A soma do capital, dívida e subvenções deve corresponder ao investimento total.";
}
return errors;
}
+5
View File
@@ -0,0 +1,5 @@
export declare function replaceTerritoryPath<T>(
path: readonly T[],
index: number,
selected?: T | null,
): T[];
+3
View File
@@ -0,0 +1,3 @@
export function replaceTerritoryPath(path, index, selected = null) {
return [...path.slice(0, index), ...(selected ? [selected] : [])];
}
@@ -0,0 +1,61 @@
import { useRef, useState } from "react";
import type { FormEvent } from "react";
import { newSubmissionKey } from "@/lib/portal-api";
import { Frame, Field, button, card, input } from "./shared";
type Opportunity = { id: string; slug: string; title: string; sector?: { name: string } | null };
type Props = { record: Opportunity; modalities: string[] };
type Form = {
fullName: string; email: string; phone: string; investorType: string; country: string;
sectorInterest: string; modality: string; investmentRange: string; message: string; privacyConsent: boolean; shareWithProponent: boolean;
};
export default function BusinessInterest({ record, modalities }: Props) {
const [form, setForm] = useState<Form>({ fullName: "", email: "", phone: "", investorType: "empresa", country: "MZ", sectorInterest: record.sector?.name ?? "", modality: modalities[0] ?? "", investmentRange: "", message: "", privacyConsent: false, shareWithProponent: false });
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [receipt, setReceipt] = useState("");
const key = useRef(newSubmissionKey());
const update = <K extends keyof Form>(field: K, value: Form[K]) => setForm((current) => ({ ...current, [field]: value }));
const submit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!form.privacyConsent) { setError("Aceite o tratamento de dados para enviar o pedido."); return; }
setBusy(true); setError("");
const xsrf = decodeURIComponent(document.cookie.split("; ").find((cookie) => cookie.startsWith("XSRF-TOKEN="))?.slice(11) ?? "");
try {
const response = await fetch("/api/v1/interest-requests", {
method: "POST", credentials: "same-origin",
headers: { Accept: "application/json", "Content-Type": "application/json", "X-XSRF-TOKEN": xsrf, "Idempotency-Key": key.current },
body: JSON.stringify({ ...form, existingBusinessId: record.id }),
});
const data = await response.json();
if (!response.ok) throw new Error(data.message ?? "Não foi possível enviar a manifestação.");
setReceipt(data.data.reference);
key.current = newSubmissionKey();
} catch (cause) {
setError(cause instanceof Error ? cause.message : "Não foi possível enviar a manifestação.");
} finally { setBusy(false); }
};
return (
<Frame title="Manifestar interesse">
<p>Oportunidade: <strong>{record.title}</strong></p>
{receipt ? <section className={card} role="status"><h2 className="text-xl font-bold">Pedido recebido</h2><p>Referência: {receipt}</p><p>A equipa fará a triagem antes de qualquer partilha com o proponente.</p></section> : (
<form className={`${card} space-y-4`} onSubmit={submit}>
<Field label="Nome ou denominação"><input className={input} required minLength={3} maxLength={150} value={form.fullName} onChange={(e) => update("fullName", e.target.value)} /></Field>
<Field label="Email"><input className={input} type="email" required maxLength={150} value={form.email} onChange={(e) => update("email", e.target.value)} /></Field>
<Field label="Telefone"><input className={input} type="tel" maxLength={30} value={form.phone} onChange={(e) => update("phone", e.target.value)} /></Field>
<Field label="Tipo de investidor"><select className={input} value={form.investorType} onChange={(e) => update("investorType", e.target.value)}><option value="empresa">Empresa</option><option value="individual">Pessoa singular</option><option value="fundo">Fundo</option><option value="entidade_publica">Entidade pública</option><option value="outro">Outro</option></select></Field>
<Field label="País"><input className={input} required maxLength={100} value={form.country} onChange={(e) => update("country", e.target.value)} /></Field>
<Field label="Sector de interesse"><input className={input} required maxLength={150} value={form.sectorInterest} onChange={(e) => update("sectorInterest", e.target.value)} /></Field>
<Field label="Modalidade pretendida"><select className={input} required value={form.modality} onChange={(e) => update("modality", e.target.value)}>{modalities.map((modality) => <option key={modality} value={modality}>{modality.replaceAll("_", " ")}</option>)}</select></Field>
<Field label="Intervalo de investimento"><input className={input} maxLength={80} value={form.investmentRange} onChange={(e) => update("investmentRange", e.target.value)} /></Field>
<Field label="Motivação e pedido"><textarea className={input} required minLength={20} maxLength={2000} rows={5} value={form.message} onChange={(e) => update("message", e.target.value)} /></Field>
<label className="flex items-start gap-3"><input type="checkbox" required checked={form.privacyConsent} onChange={(e) => update("privacyConsent", e.target.checked)} /><span>Autorizo o tratamento destes dados para responder a esta manifestação. O envio não confirma elegibilidade nem permite partilha automática com o proponente.</span></label>
<label className="flex items-start gap-3"><input type="checkbox" checked={form.shareWithProponent} onChange={(e) => update("shareWithProponent", e.target.checked)} /><span>Autorizo, se necessário para avaliar esta manifestação, a partilha do meu nome, email, telefone e mensagem com o proponente. Esta autorização é opcional e pode ser retirada junto da equipa.</span></label>
{error && <p role="alert">{error}</p>}
<button className={button} disabled={busy}>{busy ? "A enviar…" : "Enviar manifestação"}</button>
</form>
)}
</Frame>
);
}
@@ -0,0 +1,41 @@
import { Link, router } from "@inertiajs/react";
import { useState } from "react";
import { Frame, button, card, input } from "./shared";
type PublicBusiness = {
id: string; slug: string; title: string; objective?: string | null; stage?: string | null;
amount_min?: string | null; amount_max?: string | null; currency?: string | null;
sector?: { name: string; slug: string } | null; province?: string | null;
};
type Props = { results: { data: PublicBusiness[]; links: { url: string | null; label: string; active: boolean }[] }; filters: { q?: string } };
export default function BusinessMarketplace({ results, filters }: Props) {
const [query, setQuery] = useState(filters.q ?? "");
return (
<Frame title="Oportunidades de negócio">
<p>Explore oportunidades aprovadas para publicação. A informação está sujeita a diligência independente.</p>
<form className="flex flex-wrap gap-3" onSubmit={(event) => {
event.preventDefault();
router.get("/negocios", { q: query || undefined }, { preserveState: true, preserveScroll: true });
}}>
<label className="sr-only" htmlFor="business-search">Pesquisar negócios</label>
<input id="business-search" className={input} value={query} maxLength={120} onChange={(event) => setQuery(event.target.value)} />
<button className={button}>Pesquisar</button>
</form>
{!results.data.length && <p role="status">Não existem oportunidades publicadas com estes critérios.</p>}
<ul className="grid gap-4 md:grid-cols-2">
{results.data.map((record) => (
<li className={card} key={record.id}>
<h2 className="text-xl font-bold"><Link className="underline" href={`/negocios/${record.slug}`}>{record.title}</Link></h2>
<p>{[record.sector?.name, record.province, record.stage].filter(Boolean).join(" · ")}</p>
{(record.amount_min || record.amount_max) && <p>{record.amount_min ?? "—"} – {record.amount_max ?? "—"} {record.currency}</p>}
{record.objective && <p className="mt-3 line-clamp-3">{record.objective}</p>}
</li>
))}
</ul>
<nav aria-label="Paginação das oportunidades" className="flex flex-wrap gap-3">
{results.links.map((link) => link.url ? <Link key={link.label} href={link.url} className={link.active ? "font-bold underline" : "underline"} dangerouslySetInnerHTML={{ __html: link.label }} /> : null)}
</nav>
</Frame>
);
}
@@ -0,0 +1,25 @@
import { Link } from "@inertiajs/react";
import { Frame, button, card } from "./shared";
type Business = {
slug: string; title: string; objective?: string | null; stage?: string | null; activity_code?: string | null;
amount_min?: string | null; amount_max?: string | null; available_percentage?: string | null; currency?: string | null;
province?: string | null; district?: string | null; locality?: string | null; sector?: { name: string; slug: string } | null;
};
export default function BusinessOpportunity({ record }: { record: Business }) {
return (
<Frame title={record.title}>
<Link href="/negocios" className="underline">Voltar às oportunidades</Link>
<section className={`${card} space-y-4`}>
<p>{[record.sector?.name, record.stage, record.activity_code].filter(Boolean).join(" · ")}</p>
{(record.province || record.district || record.locality) && <p>{[record.locality, record.district, record.province].filter(Boolean).join(", ")}</p>}
{(record.amount_min || record.amount_max) && <p>Montante indicativo: {record.amount_min ?? "—"} – {record.amount_max ?? "—"} {record.currency}</p>}
{record.available_percentage && <p>Participação indicada: {record.available_percentage}%</p>}
{record.objective && <div><h2 className="font-bold">Objectivo</h2><p className="whitespace-pre-wrap">{record.objective}</p></div>}
<p className="text-sm">A publicação não constitui garantia de titularidade, avaliação, transmissibilidade ou retorno.</p>
<Link className={button} href={`/negocios/${record.slug}/manifestar-interesse`}>Manifestar interesse</Link>
</section>
</Frame>
);
}
@@ -6,6 +6,21 @@ export type Business = {
classification: string;
version_no: number;
sector_id?: number | null;
public_title?: string | null;
activity_code?: string | null;
stage?: string | null;
objective?: string | null;
currency?: string | null;
amount_min?: string | null;
amount_max?: string | null;
available_percentage?: string | null;
funds_use?: string | null;
submitted_at?: string | null;
published_at?: string | null;
expires_at?: string | null;
next_action?: string | null;
next_action_due_at?: string | null;
assigned_to?: number | null;
payload: {
[key: string]: string | undefined;
title: string;
@@ -21,6 +36,17 @@ export const businessStates: Record<string, string> = {
in_review: "Em revisão",
needs_information: "Pendente de informação",
withdrawn: "Retirado",
triage: "Triagem",
information_pending: "Informação pendente",
review: "Em revisão",
approval_l1: "Aprovação nível 1",
approval_l2: "Aprovação nível 2",
approved: "Aprovado",
published: "Publicado",
suspended: "Suspenso",
rejected: "Rejeitado",
cancelled: "Cancelado",
archived: "Arquivado",
};
export const businessModalities: Record<string, string> = {
company_sale: "Venda da empresa",
@@ -52,6 +52,7 @@ export default function BusinessWizard({
});
const [modality, setModality] = useState(record.modality);
const [sectorId, setSectorId] = useState(record.sector_id ?? null);
const [publicTitle, setPublicTitle] = useState(record.public_title ?? "");
const [version, setVersion] = useState(record.version_no);
const versionRef = useRef(record.version_no);
const saved = useRef(
@@ -59,6 +60,7 @@ export default function BusinessWizard({
payload: record.payload,
modality: record.modality,
sectorId: record.sector_id ?? null,
publicTitle: record.public_title ?? "",
}),
);
const inFlight = useRef(false);
@@ -68,7 +70,7 @@ export default function BusinessWizard({
const [confirmation, setConfirmation] = useState("");
const heading = useRef<HTMLHeadingElement>(null);
const step = Math.max(1, Math.min(8, Number(payload.wizard_step ?? 1)));
const serialized = JSON.stringify({ payload, modality, sectorId });
const serialized = JSON.stringify({ payload, modality, sectorId, publicTitle });
const dirty = serialized !== saved.current;
const save = useCallback(async () => {
if (inFlight.current) return false;
@@ -82,6 +84,7 @@ export default function BusinessWizard({
payload,
modality,
sector_id: sectorId,
public_title: publicTitle || null,
classification: record.classification,
reason: "Gravação do formulário privado por etapas",
version_no: versionRef.current,
@@ -97,7 +100,7 @@ export default function BusinessWizard({
inFlight.current = false;
setBusy(false);
}
}, [serialized, payload, modality, sectorId, record.id, record.classification]);
}, [serialized, payload, modality, sectorId, publicTitle, record.id, record.classification]);
useEffect(() => {
if (!dirty || busy || error) return;
@@ -201,6 +204,20 @@ export default function BusinessWizard({
>
<fieldset className="space-y-4">
<legend className="sr-only">{steps[step - 1][english ? 1 : 0]}</legend>
{step === 3 && (
<Field label={t("Título público proposto", "Proposed public title")}>
<input
className={input}
value={publicTitle}
maxLength={180}
onChange={(event) => setPublicTitle(event.target.value)}
aria-describedby="public-title-help"
/>
<span id="public-title-help" className="text-sm">
{t("Será revisto antes de qualquer publicação.", "Reviewed before any publication.")}
</span>
</Field>
)}
{step === 3 && (
<Field label={t("Sector", "Sector")}>
<select
@@ -294,6 +311,10 @@ export default function BusinessWizard({
)}
{step === 8 && (
<dl className="space-y-3 break-words">
<div>
<dt className="font-semibold">{t("Título público proposto", "Proposed public title")}</dt>
<dd>{publicTitle || "—"}</dd>
</div>
{Object.entries(formSchema).map(([key, field]) => (
<div key={key}>
<dt className="font-semibold">
@@ -17,6 +17,10 @@ type Props = {
canEdit: boolean;
owner: boolean;
canReview: boolean;
canTriage: boolean;
canApproveLevelOne: boolean;
canApproveLevelTwo: boolean;
canPublish: boolean;
modalities: string[];
objects: BusinessObject[];
objectKinds: string[];
@@ -34,6 +38,10 @@ function Editor({
canEdit,
owner,
canReview,
canTriage,
canApproveLevelOne,
canApproveLevelTwo,
canPublish,
modalities,
history,
objects,
@@ -235,6 +243,51 @@ function Editor({
Pedir informação
</button>
)}
{canTriage && record.status === "submitted" && (
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("triage")}>
Iniciar triagem
</button>
)}
{canReview && record.status === "triage" && (
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("in_review")}>
Encaminhar para revisão
</button>
)}
{canReview && record.status === "in_review" && (
<>
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("approval_l1")}>
Enviar para aprovação nível 1
</button>
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("rejected")}>
Rejeitar
</button>
</>
)}
{canApproveLevelOne && record.status === "approval_l1" && (
<>
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("approval_l2")}>
Aprovar nível 1 e enviar ao nível 2
</button>
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("rejected")}>
Rejeitar
</button>
</>
)}
{canApproveLevelTwo && record.status === "approval_l2" && (
<>
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("approved")}>
Aprovar nível 2
</button>
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("rejected")}>
Rejeitar
</button>
</>
)}
{canPublish && record.status === "approved" && (
<button className={button} disabled={busy || note.trim().length < 10} onClick={() => void run("published")}>
Publicar
</button>
)}
{owner && record.status !== "withdrawn" && (
<button
className={button}
+1 -1
View File
@@ -311,7 +311,7 @@ export default function Catalogue({
index={index}
parent={territoryPath[index - 1]?.id ?? ""}
selected={territoryPath[index]}
endpoint="/api/v1/investment/territory-options"
endpoint="/api/v1/catalogs/jurisdictions"
onChange={(value) => {
const path = [
...territoryPath.slice(0, index),
+61 -3
View File
@@ -14,6 +14,11 @@ type Interest = {
investment_range: string | null;
message: string;
status: string;
existing_business_id: string | null;
modality: string | null;
assigned_to: number | null;
next_action: string | null;
next_action_due_at: string | null;
consented_at: string | null;
reviewed_at: string | null;
reviewed_by: number | null;
@@ -34,8 +39,13 @@ function dateTime(value: string | null) {
timeZone: "Africa/Maputo",
}).format(new Date(value));
}
export default function InterestDetail({ interest }: { interest: Interest }) {
const form = useForm({ status: interest.status });
type Transition = { from_status: string | null; to_status: string; actor_id: number | null; note: string | null; created_at: string };
type Assignee = { id: number; name: string };
type Consent = { purpose: string; policy_version: string | null; status: string; granted_at: string | null; withdrawn_at: string | null };
export default function InterestDetail({ interest, history = [], assignees = [], consents = [] }: { interest: Interest; history?: Transition[]; assignees?: Assignee[]; consents?: Consent[] }) {
const form = useForm({ status: interest.status, note: "", next_action: interest.next_action ?? "", next_action_due_at: interest.next_action_due_at?.slice(0, 10) ?? "", assigned_to: interest.assigned_to?.toString() ?? "" });
const consentForm = useForm({ reason: "" });
const rows: [string, string | number | null][] = [
["Nome", interest.full_name],
["Email", interest.email],
@@ -44,6 +54,8 @@ export default function InterestDetail({ interest }: { interest: Interest }) {
["País", interest.country],
["Sector", interest.sector_interest],
["Oportunidade", interest.opportunity_reference],
["Negócio publicado", interest.existing_business_id],
["Modalidade", interest.modality],
["Faixa de investimento", interest.investment_range],
["Recebido em (Maputo)", dateTime(interest.created_at)],
["Consentimento em (Maputo)", dateTime(interest.consented_at)],
@@ -90,6 +102,27 @@ export default function InterestDetail({ interest }: { interest: Interest }) {
<h2 className="font-semibold">Mensagem</h2>
<p className="mt-2 break-words whitespace-pre-wrap">{interest.message}</p>
</section>
<section className="space-y-3">
<h2 className="font-semibold">Consentimentos e versões</h2>
{consents.map((consent, index) => (
<article key={`${consent.purpose}-${index}`} className="rounded border p-3">
<p>{consent.purpose}: {consent.status}</p>
<p className="text-sm">Política {consent.policy_version ?? "—"} · concedido {dateTime(consent.granted_at)}</p>
{consent.withdrawn_at && <p className="text-sm">Revogado {dateTime(consent.withdrawn_at)}</p>}
</article>
))}
{consents.some((consent) => consent.purpose === "share_contact_with_proponent" && consent.status === "granted") && (
<form className="max-w-sm space-y-3" onSubmit={(event) => {
event.preventDefault();
consentForm.patch(`/management/interests/${interest.id}/consent/proponent`);
}}>
<Field label="Motivo do pedido de revogação" error={consentForm.errors.reason}>
<textarea className={control} minLength={10} maxLength={2000} required rows={3} value={consentForm.data.reason} onChange={(event) => consentForm.setData("reason", event.target.value)} />
</Field>
<button className={button} disabled={consentForm.processing}>Revogar autorização de partilha</button>
</form>
)}
</section>
<form
className="max-w-sm space-y-4"
onSubmit={(e) => {
@@ -103,17 +136,42 @@ export default function InterestDetail({ interest }: { interest: Interest }) {
value={form.data.status}
onChange={(e) => form.setData("status", e.target.value)}
>
{["received", "in_review", "contacted", "closed"].map((key) => (
{["received", "submitted", "in_review", "reviewed", "qualification", "qualified", "contacted", "contact_accepted", "referred", "due_diligence", "negotiation", "pending", "refused", "converted", "cancelled", "closed"].map((key) => (
<option key={key} value={key}>
{states[key]}
</option>
))}
</select>
</Field>
<Field label="Nota de acompanhamento" error={form.errors.note}>
<textarea className={control} rows={3} value={form.data.note} onChange={(e) => form.setData("note", e.target.value)} />
</Field>
<Field label="Próxima acção" error={form.errors.next_action}>
<input className={control} value={form.data.next_action} onChange={(e) => form.setData("next_action", e.target.value)} />
</Field>
<Field label="Prazo da próxima acção" error={form.errors.next_action_due_at}>
<input type="date" className={control} value={form.data.next_action_due_at} onChange={(e) => form.setData("next_action_due_at", e.target.value)} />
</Field>
<Field label="Responsável" error={form.errors.assigned_to}>
<select className={control} value={form.data.assigned_to} onChange={(e) => form.setData("assigned_to", e.target.value)}>
<option value="">Sem responsável</option>
{assignees.map((assignee) => <option key={assignee.id} value={assignee.id}>{assignee.name}</option>)}
</select>
</Field>
<button className={button} disabled={form.processing}>
{form.processing ? "A guardar…" : "Guardar estado"}
</button>
</form>
<section className="space-y-3">
<h2 className="font-semibold">Histórico do fluxo</h2>
{!history.length && <p>Sem alterações de estado registadas.</p>}
{history.map((entry, index) => (
<article key={`${entry.created_at}-${index}`} className="rounded border p-3">
<p>{entry.from_status ? `${states[entry.from_status] ?? entry.from_status} → ` : ""}{states[entry.to_status] ?? entry.to_status} · {dateTime(entry.created_at)}</p>
{entry.note && <p className="mt-1 whitespace-pre-wrap">{entry.note}</p>}
</article>
))}
</section>
</Management>
);
}
+27 -3
View File
@@ -9,6 +9,11 @@ type Interest = {
full_name: string;
email: string;
sector_interest: string;
existing_business_id: string | null;
modality: string | null;
assignee: { id: number; name: string } | null;
next_action: string | null;
next_action_due_at: string | null;
status: string;
};
export default function Interests({
@@ -16,17 +21,18 @@ export default function Interests({
filters,
}: {
requests: Paginated<Interest>;
filters: { q?: string; status?: string };
filters: { q?: string; status?: string; follow_up?: string };
}) {
const [q, setQ] = useState(filters.q ?? '');
const [status, setStatus] = useState(filters.status ?? '');
const [followUp, setFollowUp] = useState(filters.follow_up ?? '');
return (
<Management title="Manifestações de interesse">
<form
className="flex flex-wrap gap-3"
onSubmit={(e) => {
e.preventDefault();
router.get('/management/interests', { q, status });
router.get('/management/interests', { q, status, follow_up: followUp });
}}
>
<input
@@ -43,7 +49,7 @@ export default function Interests({
onChange={(e) => setStatus(e.target.value)}
>
<option value="">Todos os estados</option>
{['received', 'in_review', 'contacted', 'closed'].map(
{Object.keys(states).filter((key) => ['received', 'submitted', 'in_review', 'reviewed', 'qualification', 'qualified', 'contacted', 'contact_accepted', 'referred', 'due_diligence', 'negotiation', 'pending', 'refused', 'converted', 'cancelled', 'closed'].includes(key)).map(
(key) => (
<option key={key} value={key}>
{states[key]}
@@ -51,6 +57,12 @@ export default function Interests({
),
)}
</select>
<select aria-label="Acompanhamento" className={`${control} max-w-xs`} value={followUp} onChange={(e) => setFollowUp(e.target.value)}>
<option value="">Todos os acompanhamentos</option>
<option value="overdue">Acções atrasadas</option>
<option value="upcoming">Acções por vencer</option>
<option value="unassigned">Sem responsável</option>
</select>
<button className={button}>Pesquisar</button>
</form>
<div className="overflow-x-auto">
@@ -62,6 +74,10 @@ export default function Interests({
'Nome',
'Email',
'Sector',
'Modalidade',
'Responsável',
'Próxima acção',
'Prazo',
'Estado',
].map((label) => (
<th key={label} className="border-b p-3">
@@ -88,6 +104,14 @@ export default function Interests({
<td className="border-b p-3">
{item.sector_interest}
</td>
<td className="border-b p-3">
{item.modality ?? (item.existing_business_id ? 'Negócio' : '—')}
</td>
<td className="border-b p-3">{item.assignee?.name ?? '—'}</td>
<td className="border-b p-3">{item.next_action ?? '—'}</td>
<td className={`border-b p-3 ${item.next_action_due_at && new Date(item.next_action_due_at) < new Date() ? 'font-semibold text-red-700' : ''}`}>
{item.next_action_due_at ? `${new Date(item.next_action_due_at) < new Date() ? 'Atrasada · ' : ''}${new Intl.DateTimeFormat('pt-MZ', { dateStyle: 'medium', timeZone: 'Africa/Maputo' }).format(new Date(item.next_action_due_at))}` : '—'}
</td>
<td className="border-b p-3">
{states[item.status] ?? item.status}
</td>
+12
View File
@@ -15,8 +15,20 @@ export const button =
"inline-flex items-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground disabled:opacity-50";
export const states: Record<string, string> = {
received: "Recebido",
submitted: "Submetido",
in_review: "Em análise",
contacted: "Contactado",
reviewed: "Revisto",
qualification: "Em qualificação",
qualified: "Qualificado",
contact_accepted: "Contacto aceite",
referred: "Encaminhado",
due_diligence: "Diligência devida",
negotiation: "Em negociação",
pending: "Pendente",
refused: "Recusado",
converted: "Convertido",
cancelled: "Cancelado",
closed: "Encerrado",
draft: "Rascunho",
published: "Publicado",
+2 -99
View File
@@ -3,6 +3,7 @@ import { useState } from "react";
import { PortalMenu } from "@/layouts/portal-navigation";
import { newSubmissionKey } from "@/lib/portal-api";
import { ProvinceSelect } from "@/components/investment-territory";
import { SimulationForm } from "@/components/simulation-form";
const input = "w-full rounded-lg border border-slate-300 bg-white p-3 text-slate-900";
const button =
@@ -293,105 +294,7 @@ function PartnershipForm() {
}
function Simulator() {
const [base, setBase] = useState("");
const [rate, setRate] = useState("");
const [reduction, setReduction] = useState("0");
const [currency, setCurrency] = useState("MZN");
const valid =
base !== "" &&
rate !== "" &&
reduction !== "" &&
Number.isFinite(Number(base)) &&
Number(base) >= 0 &&
Number(base) <= 1e12 &&
Number(rate) >= 0 &&
Number(rate) <= 100 &&
Number(reduction) >= 0 &&
Number(reduction) <= 100;
const gross = (Number(base) * Number(rate)) / 100;
const net = gross * (1 - Number(reduction) / 100);
const format = (n: number) =>
new Intl.NumberFormat("pt-MZ", { style: "currency", currency }).format(n);
return (
<section className="max-w-2xl space-y-5 rounded-xl border bg-white p-6">
<h2 className="text-xl font-bold">Cenário com parâmetros próprios</h2>
<p>
Introduza uma base tributável e uma taxa que pretende comparar. Não existem taxas
legais ou incentivos automáticos neste cálculo; a redução é uma hipótese introduzida
por si.
</p>
<label className="block">
Moeda
<select
className={input}
value={currency}
onChange={(e) => setCurrency(e.target.value)}
>
{["MZN", "USD", "EUR", "ZAR"].map((c) => (
<option key={c}>{c}</option>
))}
</select>
</label>
<label className="block">
Base tributável
<input
className={input}
type="number"
min="0"
max="1000000000000"
step="0.01"
value={base}
onChange={(e) => setBase(e.target.value)}
/>
</label>
<label className="block">
Taxa a simular (%)
<input
className={input}
type="number"
min="0"
max="100"
step="0.01"
value={rate}
onChange={(e) => setRate(e.target.value)}
/>
</label>
<label className="block">
Redução hipotética do imposto (%)
<input
className={input}
type="number"
min="0"
max="100"
step="0.01"
value={reduction}
onChange={(e) => setReduction(e.target.value)}
/>
</label>
<div role="status" className="rounded bg-emerald-50 p-5">
{valid ? (
<>
<p>
Sem redução: <strong>{format(gross)}</strong>
</p>
<p>Redução simulada: {format(gross - net)}</p>
<p>
Total do cenário: <strong>{format(net)}</strong>
</p>
<p className="mt-3 text-sm">
Base × taxa ÷ 100 × (1 − redução ÷ 100). Não inclui outros impostos,
deduções, escalões ou regras sectoriais.
</p>
</>
) : (
<p>Preencha a base e uma taxa válida entre 0 e 100%.</p>
)}
</div>
<Link href="/apoio" className="underline">
Pedir esclarecimento sobre o enquadramento aplicável
</Link>
</section>
);
return <SimulationForm />;
}
export default function Services(p: Props) {