commit 30/9
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-09-30 09:05:43 +02:00
parent 67dad461d9
commit 3dc7c5c649
75 changed files with 4123 additions and 107 deletions
@@ -5,7 +5,9 @@ export type Business = {
status: string;
classification: string;
version_no: number;
sector_id?: number | null;
payload: {
[key: string]: string | undefined;
title: string;
description?: string;
declared_reason?: string;
@@ -0,0 +1,401 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { router } from "@inertiajs/react";
import { Frame, Field, input, button, card, api } from "./shared";
import type { Business } from "./business-types";
import { businessModalities } from "./business-types";
import BusinessObjects from "./business-objects";
import type { BusinessObject } from "./business-objects";
export type FormSchema = Record<
string,
{
step: number;
pt: string;
en: string;
type: string;
max: number;
options?: Record<string, string>;
}
>;
type Props = {
record: Business;
modalities: string[];
formSchema: FormSchema;
objects: BusinessObject[];
objectKinds: string[];
sectors: { id: number; name: string }[];
};
const steps = [
["Proponente", "Applicant"],
["Representação", "Representation"],
["Oportunidade", "Opportunity"],
["Valor", "Value"],
["Localização", "Location"],
["Activos e direitos", "Assets and rights"],
["Fontes", "Sources"],
["Resumo e confirmação", "Summary and confirmation"],
];
export default function BusinessWizard({
record,
modalities,
formSchema,
objects,
objectKinds,
sectors,
}: Props) {
const [english, setEnglish] = useState(false);
const t = (pt: string, en: string) => (english ? en : pt);
const [payload, setPayload] = useState<Business["payload"]>({
...record.payload,
wizard_version: "1",
});
const [modality, setModality] = useState(record.modality);
const [sectorId, setSectorId] = useState(record.sector_id ?? null);
const [version, setVersion] = useState(record.version_no);
const versionRef = useRef(record.version_no);
const saved = useRef(
JSON.stringify({
payload: record.payload,
modality: record.modality,
sectorId: record.sector_id ?? null,
}),
);
const inFlight = useRef(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [consent, setConsent] = useState(false);
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 dirty = serialized !== saved.current;
const save = useCallback(async () => {
if (inFlight.current) return false;
if (serialized === saved.current) return true;
inFlight.current = true;
setBusy(true);
setError("");
try {
const result: Business = await api(`/api/v1/existing-business/listings/${record.id}`, {
_method: "PUT",
payload,
modality,
sector_id: sectorId,
classification: record.classification,
reason: "Gravação do formulário privado por etapas",
version_no: versionRef.current,
});
versionRef.current = result.version_no;
saved.current = serialized;
setVersion(result.version_no);
return true;
} catch (e) {
setError(e instanceof Error ? e.message : "Não foi possível guardar / Save failed");
return false;
} finally {
inFlight.current = false;
setBusy(false);
}
}, [serialized, payload, modality, sectorId, record.id, record.classification]);
useEffect(() => {
if (!dirty || busy || error) return;
const timer = setTimeout(() => {
void save();
}, 3000);
return () => clearTimeout(timer);
}, [dirty, busy, error, save]);
useEffect(() => {
const protect = (event: BeforeUnloadEvent) => {
if (dirty || busy) {
event.preventDefault();
event.returnValue = "";
}
};
window.addEventListener("beforeunload", protect);
return () => window.removeEventListener("beforeunload", protect);
}, [dirty, busy]);
useEffect(() => {
heading.current?.focus();
}, [step]);
useEffect(
() =>
router.on("before", (event) => {
if (
serialized !== saved.current &&
!window.confirm(
"Existem alterações por guardar. Sair? / Unsaved changes. Leave?",
)
)
event.preventDefault();
}),
[serialized],
);
const update = (key: string, value: string) => {
setError("");
setPayload((current) => ({ ...current, [key]: value }));
};
const submit = async () => {
if (!consent || confirmation !== record.code || !(await save())) return;
setBusy(true);
try {
await api(`/api/v1/existing-business/listings/${record.id}/transitions`, {
action: "submitted",
version_no: versionRef.current,
review_consent: true,
confirmation_code: confirmation,
note: "Submissão confirmada do formulário privado por etapas",
});
router.reload();
} catch (e) {
setError(e instanceof Error ? e.message : "Falha na submissão / Submission failed");
setBusy(false);
}
};
return (
<Frame title={t("Preparar oportunidade de negócio", "Prepare business opportunity")}>
<div lang={english ? "en" : "pt"} className="space-y-5">
<button type="button" className="underline" onClick={() => setEnglish(!english)}>
{english ? "Português" : "English"}
</button>
<p>
{record.code} · {t("Versão", "Version")} {version}
</p>
<p>
{t(
"Área privada. Guardar ou submeter não publica a oportunidade nem confirma a titularidade ou a transmissibilidade.",
"Private area. Saving or submitting does not publish the opportunity or verify ownership or transferability.",
)}
</p>
<ol className="flex flex-wrap gap-3" aria-label={t("Etapas", "Steps")}>
{steps.map((labels, i) => (
<li key={labels[1]}>
<button
type="button"
className="rounded border px-3 py-2 focus-visible:outline-2"
aria-current={step === i + 1 ? "step" : undefined}
disabled={busy}
onClick={() => update("wizard_step", String(i + 1))}
>
{i + 1}. {labels[english ? 1 : 0]}
</button>
</li>
))}
</ol>
<progress
className="w-full"
max={8}
value={step}
aria-label={t("Progresso", "Progress")}
/>
<h2 ref={heading} tabIndex={-1} className="text-xl font-bold">
{step}/8 — {steps[step - 1][english ? 1 : 0]}
</h2>
<form
className={`${card} space-y-4`}
onSubmit={(event) => {
event.preventDefault();
void save();
}}
>
<fieldset className="space-y-4">
<legend className="sr-only">{steps[step - 1][english ? 1 : 0]}</legend>
{step === 3 && (
<Field label={t("Sector", "Sector")}>
<select
className={input}
value={sectorId ?? ""}
onChange={(e) =>
setSectorId(e.target.value ? Number(e.target.value) : null)
}
>
<option value="">{t("Seleccionar", "Select")}</option>
{sectors.map((sector) => (
<option key={sector.id} value={sector.id}>
{sector.name}
</option>
))}
</select>
</Field>
)}
{step === 3 && (
<Field label={t("Modalidade", "Modality")}>
<select
className={input}
value={modality}
onChange={(e) => setModality(e.target.value)}
>
{modalities.map((m) => (
<option key={m} value={m}>
{english
? m.replaceAll("_", " ")
: (businessModalities[m] ?? m)}
</option>
))}
</select>
</Field>
)}
{Object.entries(formSchema)
.filter(
([key, field]) =>
field.step === step &&
(!(
key === "mandate_reference" || key === "mandate_valid_until"
) ||
payload.acting_capacity === "representative"),
)
.map(([key, field]) => (
<Field key={key} label={english ? field.en : field.pt}>
{field.type === "select" ? (
<select
className={input}
value={payload[key] ?? ""}
onChange={(e) => update(key, e.target.value)}
>
<option value="">{t("Seleccionar", "Select")}</option>
{Object.entries(field.options ?? {}).map(
([value, label]) => (
<option key={value} value={value}>
{label}
</option>
),
)}
</select>
) : field.type === "textarea" ? (
<textarea
className={input}
rows={4}
maxLength={field.max}
value={payload[key] ?? ""}
onChange={(e) => update(key, e.target.value)}
/>
) : (
<input
className={input}
type={field.type === "decimal" ? "text" : field.type}
inputMode={
field.type === "decimal" ? "decimal" : undefined
}
maxLength={field.max}
value={payload[key] ?? ""}
onChange={(e) => update(key, e.target.value)}
/>
)}
</Field>
))}
{step === 7 && (
<p role="note">
{t(
"Este formulário regista referências. O envio de ficheiros com antivírus ainda não está disponível; não cole conteúdo reservado de documentos neste campo.",
"This form records references. File upload with antivirus is not available yet; do not paste confidential document content here.",
)}
</p>
)}
{step === 8 && (
<dl className="space-y-3 break-words">
{Object.entries(formSchema).map(([key, field]) => (
<div key={key}>
<dt className="font-semibold">
{english ? field.en : field.pt}
</dt>
<dd className="whitespace-pre-wrap">
{payload[key] || "—"}
</dd>
</div>
))}
</dl>
)}
</fieldset>
<p role="status" aria-live="polite">
{busy
? t("A guardar…", "Saving…")
: dirty
? t("Alterações por guardar", "Unsaved changes")
: t("Rascunho guardado no servidor", "Draft saved on server")}
</p>
{error && (
<p role="alert" className="text-red-700">
{error}
</p>
)}
<button className={button} disabled={busy}>
{t("Guardar agora", "Save now")}
</button>
</form>
{step === 6 && (
<BusinessObjects
businessId={record.id}
version={version}
editable={!dirty && !busy}
objects={objects}
objectKinds={objectKinds}
/>
)}
{step === 8 && (
<div className={`${card} space-y-4`}>
<label className="flex gap-3">
<input
type="checkbox"
checked={consent}
onChange={(e) => setConsent(e.target.checked)}
/>
{t(
"Confirmo a exactidão da declaração e autorizo a análise interna. Não autorizo publicação por esta acção.",
"I confirm this declaration and authorize internal review. This action does not authorize publication.",
)}
</label>
<Field
label={t(
"Digite o código acima para confirmar",
"Type the code above to confirm",
)}
>
<input
className={input}
autoComplete="off"
value={confirmation}
onChange={(e) => setConfirmation(e.target.value)}
/>
</Field>
<button
className={button}
disabled={busy || !consent || confirmation !== record.code}
onClick={() => void submit()}
>
{t(
"Confirmar e submeter para análise",
"Confirm and submit for review",
)}
</button>
</div>
)}
<div className="flex flex-wrap gap-4">
<button
className={button}
disabled={busy || step === 1}
onClick={() => update("wizard_step", String(step - 1))}
>
{t("Anterior", "Previous")}
</button>
<button
className={button}
disabled={busy || step === 8}
onClick={() => update("wizard_step", String(step + 1))}
>
{t("Seguinte", "Next")}
</button>
<button
className="underline"
disabled={busy}
onClick={async () => {
if (await save()) router.visit("/investidor/negocios");
}}
>
{t("Guardar e sair", "Save and exit")}
</button>
</div>
</div>
</Frame>
);
}
@@ -7,8 +7,12 @@ import BusinessObjects from "./business-objects";
import type { BusinessObject } from "./business-objects";
import BusinessVerifications from "./business-verifications";
import type { BusinessVerification } from "./business-verifications";
import BusinessWizard from "./business-wizard";
import type { FormSchema } from "./business-wizard";
type Props = {
formSchema: FormSchema;
sectors: { id: number; name: string }[];
record: Business;
canEdit: boolean;
owner: boolean;
@@ -21,6 +25,8 @@ type Props = {
history: { version_no: number; action: string; created_at: string; note: string }[];
};
export default function BusinessPage(props: Props) {
if (props.canEdit)
return <BusinessWizard key={props.record.id + ":" + props.record.version_no} {...props} />;
return <Editor key={`${props.record.id}:${props.record.version_no}`} {...props} />;
}
function Editor({
@@ -34,6 +40,8 @@ function Editor({
objectKinds,
verificationChecks,
verifications,
formSchema,
sectors,
}: Props) {
const [payload, setPayload] = useState(record.payload);
const [modality, setModality] = useState(record.modality);
@@ -86,6 +94,35 @@ function Editor({
Informação declarada, pendente de validação. Não constitui anúncio público,
certificação, avaliação ou autorização de transmissão.
</p>
{!canEdit && (
<dl className={`${card} space-y-3 break-words`}>
<div>
<dt className="font-bold">Sector</dt>
<dd>
{sectors.find((sector) => sector.id === record.sector_id)?.name ?? "—"}
</dd>
</div>
{Object.entries(formSchema)
.filter(
([key]) =>
![
"title",
"description",
"declared_reason",
"source_reference",
"valid_until",
].includes(key),
)
.map(([key, field]) => (
<div key={key}>
<dt className="font-bold">{field.pt}</dt>
<dd className="whitespace-pre-wrap">
{record.payload[key] || "—"}
</dd>
</div>
))}
</dl>
)}
<form
className={`${card} space-y-4`}
onSubmit={(e) => {
+1 -1
View File
@@ -35,7 +35,7 @@ export default function Businesses({
modality,
classification: "confidential",
reason: "Criação de rascunho pelo proprietário",
payload: { title },
payload: { title, wizard_version: "1", wizard_step: "1" },
});
router.visit(`/investidor/negocios/${result.id}`);
} catch (err) {