fix: complete InvesteMoz validation and error corrections

This commit is contained in:
2026-10-29 21:47:33 +02:00
parent 63147312e2
commit daf8623441
718 changed files with 127308 additions and 20959 deletions
@@ -1,4 +1,10 @@
import {ProactiveInvestmentEditor,newProactive,type ProactiveAnalysis,type ProactiveOptions} from '@/components/proactive-investment';
import { inputText } from '../../lib/input-text.ts';
import {
ProactiveInvestmentEditor,
newProactive,
type ProactiveAnalysis,
type ProactiveOptions,
} from '@/components/proactive-investment';
import { ClassificationReview } from '@/components/opportunity-classification';
import { createOperationKey } from '@/lib/operation-key';
import { valueText } from '@/lib/value-text';
@@ -42,7 +48,13 @@ export default function OpportunityDraft({
}: {
record: Entry | null;
proactiveOptions?: ProactiveOptions;
proactiveHistory?: {version:number;at:string;state:string;problem:string;confirmation:string}[];
proactiveHistory?: {
version: number;
at: string;
state: string;
problem: string;
confirmation: string;
}[];
values: Values;
etag: string | null;
readOnly: boolean;
@@ -140,11 +152,20 @@ export default function OpportunityDraft({
auth: { user: { id: number } };
canEditDraft?: boolean;
}>().props;
const proactiveEntryUrl=usePage().url;
const uniquePromoterContext=profileAccess?.contexts.length===1?profileAccess.contexts[0]:undefined;
const proactiveEntryUrl = usePage().url;
const uniquePromoterContext =
profileAccess?.contexts.length === 1
? profileAccess.contexts[0]
: undefined;
const [data, setData] = useState<Values>({
...values,
...(!record && !values.proactive && new URLSearchParams(proactiveEntryUrl.split('?')[1]??'').get('analysis')==='proactive' ? {proactive:newProactive()} : {}),
...(!record &&
!values.proactive &&
new URLSearchParams(proactiveEntryUrl.split('?')[1] ?? '').get(
'analysis',
) === 'proactive'
? { proactive: newProactive() }
: {}),
...(profileMode
? {
organization_id: record
@@ -174,11 +195,18 @@ export default function OpportunityDraft({
const unavailable = Boolean(
record?.deleted_at || record?.status === 'archived',
);
const hasCanonicalPreparation = profileMode && canonicalOptions && Boolean(data.opportunity_category) && !data.proactive;
const hasCanonicalPreparation =
profileMode &&
canonicalOptions &&
Boolean(data.opportunity_category) &&
!data.proactive;
const archiveAvailable = Boolean(usePage().props.opportunityManagement);
const set = (key: string, value: string) =>
setData((d) => ({ ...d, [key]: value }));
async function send(action: 'save' | 'delete' | 'archive' | 'restore', resourcesGroup?: string) {
async function send(
action: 'save' | 'delete' | 'archive' | 'restore',
resourcesGroup?: string,
) {
if (busy) return;
setBusy(true);
setErrors({});
@@ -226,10 +254,25 @@ export default function OpportunityDraft({
}
setMessage(result.message);
if (result.etag) setToken(result.etag);
if (resourcesGroup) router.visit(`${basePath}/${record?.id ?? result.id}/resources?return_group=${encodeURIComponent(resourcesGroup)}`);
else if (!record) router.visit(`${basePath}/${result.id}/edit${window.location.hash.startsWith('#fill-') ? window.location.hash : ''}`);
if (resourcesGroup)
router.visit(
`${basePath}/${record?.id ?? result.id}/resources?return_group=${encodeURIComponent(resourcesGroup)}`,
);
else if (!record)
router.visit(
`${basePath}/${result.id}/edit${window.location.hash.startsWith('#fill-') ? window.location.hash : ''}`,
);
else if (action !== 'save') router.reload();
else if (profileMode) router.reload({only:['canonicalResponse','etag','history','workflowState','profileContext']});
else if (profileMode)
router.reload({
only: [
'canonicalResponse',
'etag',
'history',
'workflowState',
'profileContext',
],
});
} catch {
setMessage(
'Resposta indisponível. Os dados foram preservados; confira o registo no servidor antes de repetir.',
@@ -242,7 +285,10 @@ export default function OpportunityDraft({
'[data-association-index][aria-invalid="true"]',
);
if (invalidAssociation) invalidAssociation.focus();
else document.getElementById('opportunity-result')?.focus({preventScroll:true});
else
document
.getElementById('opportunity-result')
?.focus({ preventScroll: true });
});
}
}
@@ -255,13 +301,42 @@ export default function OpportunityDraft({
}
>
{!profileMode && <Link href={basePath}>Voltar à gestão</Link>}
{promotionHref && <Link className="ml-3 underline" href={promotionHref}>Divulgação promocional — Em preparação</Link>}
{promotionHref && (
<Link className="ml-3 underline" href={promotionHref}>
Divulgação promocional — Em preparação
</Link>
)}
{!!profileContext?.corridor_agribusiness && (
<section className="my-4 space-y-2 rounded border p-4">
<h2 className="font-semibold">Origem e enquadramento da oportunidade</h2>
<p>{valueText((profileContext.corridor_agribusiness as Record<string, unknown>).corridor)}</p>
<p>Fonte: {valueText((profileContext.corridor_agribusiness as Record<string, unknown>).source)}</p>
<p>Em preparação. O corredor indicado na fonte não confirma implantação, promotor, viabilidade ou financiamento. Complete a ficha e reveja a prévia antes de divulgar.</p>
<h2 className="font-semibold">
Origem e enquadramento da oportunidade
</h2>
<p>
{valueText(
(
profileContext.corridor_agribusiness as Record<
string,
unknown
>
).corridor,
)}
</p>
<p>
Fonte:{' '}
{valueText(
(
profileContext.corridor_agribusiness as Record<
string,
unknown
>
).source,
)}
</p>
<p>
Em preparação. O corredor indicado na fonte não confirma
implantação, promotor, viabilidade ou financiamento.
Complete a ficha e reveja a prévia antes de divulgar.
</p>
</section>
)}
{record && (
@@ -277,7 +352,9 @@ export default function OpportunityDraft({
aria-label="Disponibilidade por modalidade"
className="rounded border p-3"
>
<summary className="cursor-pointer font-medium">Modalidades disponíveis e condições de submissão</summary>
<summary className="cursor-pointer font-medium">
Modalidades disponíveis e condições de submissão
</summary>
<p>
Seis categorias base: projeto de investimento,
imobiliário, fundiário, venda de negócio, parceria e
@@ -336,7 +413,8 @@ export default function OpportunityDraft({
}));
}}
>
{(profileAccess?.internalPromoter || !uniquePromoterContext) && (
{(profileAccess?.internalPromoter ||
!uniquePromoterContext) && (
<option value="|">
Selecionar o promotor real da oportunidade
</option>
@@ -481,13 +559,132 @@ export default function OpportunityDraft({
void send('save');
}}
>
{profileMode&&Boolean(data.proactive)&&<fieldset disabled={busy||readOnly||unavailable} className="space-y-3 rounded border p-4"><legend>Contexto existente da análise</legend>
<Field label="Título da análise"><input aria-label="Título da análise" className={control} value={String((data.canonical as Record<string,unknown>|undefined)?.official_title??data.title??'')} onChange={e=>{const title=e.target.value;setData(d=>({...d,title,...(d.canonical&&Object.prototype.hasOwnProperty.call(d.canonical,'official_title')?{canonical:{...(d.canonical as Record<string,unknown>),official_title:title}}:{})}));}}/></Field>
<Field label="Sector da análise"><select aria-label="Sector da análise" className={control} value={String(data.sector_id??'')} onChange={e=>setData(d=>({...d,sector_id:e.target.value,...(d.canonical?{canonical:{...(d.canonical as Record<string,unknown>),sector_id:Number(e.target.value)||null}}:{})}))}><option value="">Por determinar</option>{sectors.map(s=><option key={s.id} value={s.id}>{s.name}</option>)}</select></Field>
<p>Seleccione apenas o nível territorial conhecido; não exige coordenadas, montante ou promotor.</p>
{(['province_id','district_id','admin_post_id','locality_id']as const).map((key,index)=><TerritoryLevel key={`proactive-${key}-${path[index-1]?.id??''}`} index={index} parent={path[index-1]?.id??''} selected={path[index]} endpoint="/minhas-oportunidades/territory-options" fieldError={errors[key]} onChange={value=>{const next=[...path.slice(0,index),...(value?[value]:[])];setPath(next);setData(d=>({...d,province_id:next[0]?.id??'',district_id:next[1]?.id??'',admin_post_id:next[2]?.id??'',locality_id:next[3]?.id??''}));}}/>)}
</fieldset>}
<fieldset disabled={busy || readOnly || unavailable}><ProactiveInvestmentEditor value={data.proactive as ProactiveAnalysis|undefined} onChange={v=>setData(d=>({...d,proactive:v}))} options={proactiveOptions} history={proactiveHistory} territoryId={path.at(-1)?.id} recordId={record?.id}/></fieldset>
{profileMode && Boolean(data.proactive) && (
<fieldset
disabled={busy || readOnly || unavailable}
className="space-y-3 rounded border p-4"
>
<legend>Contexto existente da análise</legend>
<Field label="Título da análise">
<input
aria-label="Título da análise"
className={control}
value={inputText(
(
data.canonical as
| Record<string, unknown>
| undefined
)?.official_title ??
data.title ??
'',
)}
onChange={(e) => {
const title = e.target.value;
setData((d) => ({
...d,
title,
...(d.canonical &&
Object.prototype.hasOwnProperty.call(
d.canonical,
'official_title',
)
? {
canonical: {
...(d.canonical as Record<
string,
unknown
>),
official_title: title,
},
}
: {}),
}));
}}
/>
</Field>
<Field label="Sector da análise">
<select
aria-label="Sector da análise"
className={control}
value={inputText(data.sector_id ?? '')}
onChange={(e) =>
setData((d) => ({
...d,
sector_id: e.target.value,
...(d.canonical
? {
canonical: {
...(d.canonical as Record<
string,
unknown
>),
sector_id:
Number(
e.target.value,
) || null,
},
}
: {}),
}))
}
>
<option value="">Por determinar</option>
{sectors.map((s) => (
<option key={s.id} value={s.id}>
{s.name}
</option>
))}
</select>
</Field>
<p>
Seleccione apenas o nível territorial conhecido; não
exige coordenadas, montante ou promotor.
</p>
{(
[
'province_id',
'district_id',
'admin_post_id',
'locality_id',
] as const
).map((key, index) => (
<TerritoryLevel
key={`proactive-${key}-${path[index - 1]?.id ?? ''}`}
index={index}
parent={path[index - 1]?.id ?? ''}
selected={path[index]}
endpoint="/minhas-oportunidades/territory-options"
fieldError={errors[key]}
onChange={(value) => {
const next = [
...path.slice(0, index),
...(value ? [value] : []),
];
setPath(next);
setData((d) => ({
...d,
province_id: next[0]?.id ?? '',
district_id: next[1]?.id ?? '',
admin_post_id: next[2]?.id ?? '',
locality_id: next[3]?.id ?? '',
}));
}}
/>
))}
</fieldset>
)}
<fieldset disabled={busy || readOnly || unavailable}>
<ProactiveInvestmentEditor
value={data.proactive as ProactiveAnalysis | undefined}
onChange={(v) =>
setData((d) => ({ ...d, proactive: v }))
}
options={proactiveOptions}
history={proactiveHistory}
territoryId={path.at(-1)?.id}
recordId={record?.id}
/>
</fieldset>
{!profileMode && (
<fieldset
disabled={busy || readOnly || unavailable}
@@ -823,18 +1020,20 @@ export default function OpportunityDraft({
)}
{!readOnly && (
<>
{!hasCanonicalPreparation && <Field
label="Motivo da alteração"
error={errors.reason}
>
<textarea
className={control}
value={reason}
onChange={(e) => setReason(e.target.value)}
minLength={20}
maxLength={1000}
/>
</Field>}
{!hasCanonicalPreparation && (
<Field
label="Motivo da alteração"
error={errors.reason}
>
<textarea
className={control}
value={reason}
onChange={(e) => setReason(e.target.value)}
minLength={20}
maxLength={1000}
/>
</Field>
)}
{!unavailable && !hasCanonicalPreparation && (
<button className={button} disabled={busy}>
Guardar rascunho
@@ -893,110 +1092,153 @@ export default function OpportunityDraft({
</>
)}
</form>
{record && (!profileMode || readOnly || unavailable || !canonicalOptions || !data.opportunity_category) && (
<Link
href={
resourcesInstalled
? `${basePath}/${record.id}/resources`
: '/management/opportunity-resources-install'
}
>
{resourcesInstalled
? 'Imagens, documentos e localizações'
: 'Plano de ativação de imagens, documentos e localizações'}
</Link>
)}
{record &&
(!profileMode ||
readOnly ||
unavailable ||
!canonicalOptions ||
!data.opportunity_category) && (
<Link
href={
resourcesInstalled
? `${basePath}/${record.id}/resources`
: '/management/opportunity-resources-install'
}
>
{resourcesInstalled
? 'Imagens, documentos e localizações'
: 'Plano de ativação de imagens, documentos e localizações'}
</Link>
)}
{record && !profileMode && (
<Link href={`${basePath}/${record.id}/context`}>
Associações territoriais e produtivas existentes
</Link>
)}
{profileMode && canonicalOptions && Boolean(data.opportunity_category) && (
<section>
{record && !readOnly && !unavailable && (
<details><summary className="cursor-pointer font-medium">Acrescentar um contacto à oportunidade</summary><OpportunityContactForm
id={record.id}
etag={token ?? ''}
{profileMode &&
canonicalOptions &&
Boolean(data.opportunity_category) && (
<section>
{record && !readOnly && !unavailable && (
<details>
<summary className="cursor-pointer font-medium">
Acrescentar um contacto à oportunidade
</summary>
<OpportunityContactForm
id={record.id}
etag={token ?? ''}
organization={
(data.organization_id ?? null) as
| string
| null
}
investors={
canonicalOptions.contactInvestors ?? []
}
disabled={busy || !token}
onSaved={(contact) => {
setSavedContacts((prior) => [
...prior.filter(
(row) => row.id !== contact.id,
),
contact,
]);
setData((prior) => ({
...prior,
canonical: {
...(prior.canonical as Record<
string,
unknown
>),
internal_contact_id: contact.id,
},
}));
}}
/>
</details>
)}
<OpportunityCanonicalFields
value={
(data.canonical ?? {}) as Record<
string,
unknown
>
}
onChange={(v) =>
setData((d) => ({ ...d, canonical: v }))
}
options={{
...canonicalOptions,
contacts: [
...canonicalOptions.contacts.filter(
(row) =>
!savedContacts.some(
(saved) => saved.id === row.id,
),
),
...savedContacts,
],
}}
errors={errors}
missingPaths={
canonicalResponse?.completion.missing_paths
}
category={valueText(
data.opportunity_category ?? '',
)}
organization={
(data.organization_id ?? null) as string | null
}
investors={canonicalOptions.contactInvestors ?? []}
disabled={busy || !token}
onSaved={(contact) => {
setSavedContacts((prior) => [
...prior.filter(
(row) => row.id !== contact.id,
),
contact,
]);
setData((prior) => ({
...prior,
canonical: {
...(prior.canonical as Record<
string,
unknown
>),
internal_contact_id: contact.id,
},
}));
}}
/></details>
)}
<OpportunityCanonicalFields
value={
(data.canonical ?? {}) as Record<string, unknown>
}
onChange={(v) =>
setData((d) => ({ ...d, canonical: v }))
}
options={{
...canonicalOptions,
contacts: [
...canonicalOptions.contacts.filter(
(row) =>
!savedContacts.some(
(saved) => saved.id === row.id,
),
),
...savedContacts,
],
}}
errors={errors}
missingPaths={canonicalResponse?.completion.missing_paths}
category={valueText(data.opportunity_category ?? '')}
organization={
(data.organization_id ?? null) as string | null
}
actorId={auth.user.id}
sectors={sectors}
disabled={busy || readOnly || unavailable}
onOpenResources={!readOnly && !unavailable && resourcesInstalled ? (group) => void send('save',group) : undefined}
/>
{!readOnly && !unavailable && hasCanonicalPreparation && (
<div className="sticky bottom-0 space-y-3 rounded border bg-background p-4 shadow-sm">
<Field label="O que alterou nesta preparação" error={errors.reason}>
<textarea className={control} value={reason} onChange={(event) => setReason(event.target.value)} minLength={20} maxLength={1000} />
</Field>
<button
type="button"
className={button}
disabled={busy}
onClick={() => void send('save')}
>
Guardar preparação
</button>
<p className="text-sm">Pode guardar incompleto e continuar mais tarde em Minhas oportunidades.</p>
</div>
)}
{Object.entries(errors)
.filter(([key]) => key.startsWith('canonical'))
.map(([key, msg]) => (
<p key={key} role="alert">
{key}: {msg}
</p>
))}
</section>
)}
actorId={auth.user.id}
sectors={sectors}
disabled={busy || readOnly || unavailable}
onOpenResources={
!readOnly && !unavailable && resourcesInstalled
? (group) => void send('save', group)
: undefined
}
/>
{!readOnly &&
!unavailable &&
hasCanonicalPreparation && (
<div className="bg-background sticky bottom-0 space-y-3 rounded border p-4 shadow-sm">
<Field
label="O que alterou nesta preparação"
error={errors.reason}
>
<textarea
className={control}
value={reason}
onChange={(event) =>
setReason(event.target.value)
}
minLength={20}
maxLength={1000}
/>
</Field>
<button
type="button"
className={button}
disabled={busy}
onClick={() => void send('save')}
>
Guardar preparação
</button>
<p className="text-sm">
Pode guardar incompleto e continuar mais
tarde em Minhas oportunidades.
</p>
</div>
)}
{Object.entries(errors)
.filter(([key]) => key.startsWith('canonical'))
.map(([key, msg]) => (
<p key={key} role="alert">
{key}: {msg}
</p>
))}
</section>
)}
{profileMode && record && profileActions.includes('publish') && (
<section className="rounded border p-3">
<h2>Pré-visualização da publicação</h2>