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
@@ -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),