444 lines
19 KiB
TypeScript
444 lines
19 KiB
TypeScript
import { Link } from '@inertiajs/react';
|
|
import { contextApi, type ContextReference } from '@/lib/investor-context';
|
|
import { TerritoryFields } from './investment-territory';
|
|
import type { OpportunityChoice } from '@/lib/investor-context';
|
|
import { card, input } from '@/pages/investment/shared';
|
|
import { useEffect, useState } from 'react';
|
|
import type { TerritoryOption } from './investment-territory';
|
|
|
|
export type CorridorOption = {
|
|
key: string;
|
|
name: string;
|
|
provinces: TerritoryOption[];
|
|
};
|
|
|
|
function ChoiceCard({
|
|
c,
|
|
i,
|
|
corridors,
|
|
disabled,
|
|
update,
|
|
remove,
|
|
contextId,
|
|
}: {
|
|
c: OpportunityChoice;
|
|
i: number;
|
|
corridors: CorridorOption[];
|
|
disabled: boolean;
|
|
update: (change: Partial<OpportunityChoice>) => void;
|
|
remove?: () => void;
|
|
contextId?: string;
|
|
}) {
|
|
const [notice, setNotice] = useState('');
|
|
const [parks, setParks] = useState<
|
|
{ id: string; name: string; version_no: number }[]
|
|
>([]);
|
|
const [parkError, setParkError] = useState('');
|
|
const [parkLoading, setParkLoading] = useState(false);
|
|
const corridor =
|
|
corridors.find((r) => r.key === c.corridor_key) ||
|
|
corridors.find((r) => r.name === c.coverage);
|
|
const path = c.territory_path ?? [];
|
|
function location(next: TerritoryOption[], key = corridor?.key) {
|
|
update({
|
|
corridor_key: key,
|
|
territory_path: next,
|
|
territory: next.length
|
|
? {
|
|
key: 'territory:' + next.at(-1)!.id,
|
|
kind: 'territory',
|
|
id: next.at(-1)!.id,
|
|
title: next.map((p) => p.name).join(' / '),
|
|
href: '/oportunidades',
|
|
version: null,
|
|
sha256: '',
|
|
fields: {},
|
|
}
|
|
: null,
|
|
});
|
|
}
|
|
useEffect(() => {
|
|
if (!remove || !corridor) return;
|
|
if (
|
|
path.length &&
|
|
!corridor.provinces.some((p) => p.id === path[0].id)
|
|
) {
|
|
setNotice(
|
|
'A localização anterior foi retirada porque não pertence ao corredor escolhido. Escolha uma localização compatível.',
|
|
);
|
|
location(corridor.provinces.length === 1 ? corridor.provinces : []);
|
|
} else if (!path.length && corridor.provinces.length === 1) {
|
|
setNotice(
|
|
'Província seleccionada automaticamente: ' +
|
|
corridor.provinces[0].name +
|
|
'.',
|
|
);
|
|
location(corridor.provinces);
|
|
}
|
|
}, [
|
|
corridor?.key,
|
|
JSON.stringify(corridor?.provinces),
|
|
path[0]?.id,
|
|
!!remove,
|
|
]);
|
|
useEffect(() => {
|
|
if (!remove || !corridor?.key) return;
|
|
let active = true;
|
|
setParkLoading(true);
|
|
setParkError('');
|
|
const params = new URLSearchParams();
|
|
if (corridor?.key) params.set('corridor', corridor.key);
|
|
if (c.territory?.id) params.set('territory', c.territory.id);
|
|
void contextApi<{
|
|
parks: { id: string; name: string; version_no: number }[];
|
|
}>('/investimentos/opcoes-corredor?' + params)
|
|
.then((data) => {
|
|
if (!active) return;
|
|
setParks(data.parks);
|
|
if (
|
|
c.park &&
|
|
!data.parks.some((p) => 'park:' + p.id === c.park?.key)
|
|
) {
|
|
update({ park: null });
|
|
setNotice(
|
|
'A zona ou parque desta oportunidade foi retirado por incompatibilidade com a localização escolhida. As restantes oportunidades conservaram-se.',
|
|
);
|
|
}
|
|
})
|
|
.catch((e) => {
|
|
if (active) setParkError(e.message);
|
|
})
|
|
.finally(() => {
|
|
if (active) setParkLoading(false);
|
|
});
|
|
return () => {
|
|
active = false;
|
|
};
|
|
}, [corridor?.key, c.territory?.id, !!remove]);
|
|
return (
|
|
<article className={card + ' space-y-3'}>
|
|
<h3 className="font-semibold">
|
|
<Link
|
|
className="underline"
|
|
href={
|
|
contextId
|
|
? `${c.opportunity.href}${c.opportunity.href.includes('?') ? '&' : '?'}context=${contextId}&opportunity=${encodeURIComponent(c.opportunity.key)}`
|
|
: c.opportunity.href
|
|
}
|
|
>
|
|
{i + 1}. {c.opportunity.title}
|
|
</Link>
|
|
</h3>
|
|
{remove && (
|
|
<label className="block">
|
|
Corredor para este investimento
|
|
<select
|
|
className={input}
|
|
disabled={disabled || !corridors.length}
|
|
value={corridor?.key ?? ''}
|
|
onChange={(e) => {
|
|
const next = corridors.find(
|
|
(r) => r.key === e.target.value,
|
|
);
|
|
if (!next) return;
|
|
const compatible =
|
|
!path.length ||
|
|
next.provinces.some((p) => p.id === path[0].id);
|
|
const kept = compatible ? path : [];
|
|
location(
|
|
kept.length
|
|
? kept
|
|
: next.provinces.length === 1
|
|
? next.provinces
|
|
: [],
|
|
next.key,
|
|
);
|
|
setNotice(
|
|
!path.length
|
|
? next.provinces.length === 1
|
|
? 'Província seleccionada automaticamente: ' +
|
|
next.provinces[0].name +
|
|
'.'
|
|
: 'Escolha uma das províncias deste corredor.'
|
|
: compatible
|
|
? 'A localização compatível foi conservada.'
|
|
: 'A província e os níveis territoriais incompatíveis foram retirados.',
|
|
);
|
|
}}
|
|
>
|
|
<option value="">Seleccione um corredor</option>
|
|
{corridors.map((r) => (
|
|
<option key={r.key} value={r.key}>
|
|
{r.name}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
)}
|
|
{!remove && (
|
|
<p>Corredor escolhido: {c.corridor_name ?? 'Por definir'}</p>
|
|
)}
|
|
{!remove && c.coverage && c.coverage !== c.corridor_name && (
|
|
<p>Referência documental de origem: {c.coverage}</p>
|
|
)}
|
|
{notice && <p role="status">{notice}</p>}
|
|
<p>Localização: {c.territory?.title ?? 'Por escolher'}</p>
|
|
{!!c.portfolio_origins?.length && (
|
|
<section aria-label="Associações escolhidas">
|
|
<h4 className="font-semibold">Associações escolhidas</h4>
|
|
<ul>
|
|
{c.portfolio_origins.map((origin) => (
|
|
<li key={origin.id}>
|
|
<Link className="underline" href={origin.href}>
|
|
{origin.title}
|
|
</Link>
|
|
{remove && (
|
|
<button
|
|
type="button"
|
|
className="ml-3 underline"
|
|
disabled={disabled}
|
|
onClick={() =>
|
|
update({
|
|
portfolio_origins:
|
|
c.portfolio_origins?.filter(
|
|
(r) =>
|
|
r.id !== origin.id,
|
|
),
|
|
})
|
|
}
|
|
>
|
|
Retirar associação
|
|
</button>
|
|
)}
|
|
</li>
|
|
))}
|
|
</ul>
|
|
</section>
|
|
)}
|
|
{c.park && !remove && (
|
|
<p>
|
|
Zona/parque:{' '}
|
|
<Link className="underline" href={c.park.href}>
|
|
{c.park.title}
|
|
</Link>
|
|
</p>
|
|
)}
|
|
{remove && (
|
|
<>
|
|
<label className="block">
|
|
Zona ou parque desta oportunidade
|
|
<select
|
|
className={input}
|
|
disabled={
|
|
disabled ||
|
|
parkLoading ||
|
|
!!parkError ||
|
|
!c.territory
|
|
}
|
|
value={c.park?.key ?? ''}
|
|
onChange={(e) => {
|
|
const p = parks.find(
|
|
(p) => 'park:' + p.id === e.target.value,
|
|
);
|
|
update({
|
|
park: p
|
|
? ({
|
|
key: 'park:' + p.id,
|
|
kind: 'park',
|
|
id: p.id,
|
|
title: p.name,
|
|
href: '/zonas/' + p.id,
|
|
version: p.version_no,
|
|
sha256: '',
|
|
fields: {},
|
|
} as ContextReference)
|
|
: null,
|
|
});
|
|
}}
|
|
>
|
|
<option value="">
|
|
Sem zona ou parque seleccionado
|
|
</option>
|
|
{parks.map((p) => (
|
|
<option key={p.id} value={'park:' + p.id}>
|
|
{p.name}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
{parkError && <p role="alert">{parkError}</p>}
|
|
{!parkLoading && !parkError && (
|
|
<p>
|
|
{!c.territory
|
|
? 'Escolha a localização desta oportunidade.'
|
|
: parks.length
|
|
? 'A consulta não confirma disponibilidade, admissão ou incentivos.'
|
|
: 'Sem zona ou parque com enquadramento documentado nesta localização.'}
|
|
</p>
|
|
)}
|
|
<fieldset disabled={disabled}>
|
|
<legend>
|
|
Actividades que pretende realizar nesta oportunidade
|
|
</legend>
|
|
{Object.entries({
|
|
production: 'Produção agrícola',
|
|
processing: 'Transformação agroindustrial',
|
|
trade: 'Comercialização e exportação',
|
|
transport: 'Transporte e logística',
|
|
water: 'Captação/utilização de água',
|
|
forestry: 'Actividade florestal',
|
|
animal: 'Produção/serviços pecuários',
|
|
}).map(([key, label]) => (
|
|
<label key={key} className="mr-4 inline-block">
|
|
<input
|
|
type="checkbox"
|
|
checked={
|
|
c.activities?.includes(key) ?? false
|
|
}
|
|
onChange={(e) =>
|
|
update({
|
|
activities: e.target.checked
|
|
? [...(c.activities ?? []), key]
|
|
: (c.activities ?? []).filter(
|
|
(x) => x !== key,
|
|
),
|
|
})
|
|
}
|
|
/>
|
|
{label}
|
|
</label>
|
|
))}
|
|
</fieldset>
|
|
<TerritoryFields
|
|
initial={c.territory_path}
|
|
corridor={corridor?.key}
|
|
disabled={disabled}
|
|
onChange={(next) => location(next)}
|
|
/>
|
|
<label className="block">
|
|
Motivo da alternativa territorial
|
|
<textarea
|
|
className={input}
|
|
disabled={disabled}
|
|
value={c.location_reason}
|
|
onChange={(e) =>
|
|
update({ location_reason: e.target.value })
|
|
}
|
|
/>
|
|
</label>
|
|
<label className="block">
|
|
<input
|
|
type="checkbox"
|
|
disabled={disabled}
|
|
checked={!!c.confirm_location_change}
|
|
onChange={(e) =>
|
|
update({
|
|
confirm_location_change: e.target.checked,
|
|
})
|
|
}
|
|
/>
|
|
Confirmo a alteração da localização anteriormente
|
|
confirmada, quando existir.
|
|
</label>
|
|
<button
|
|
type="button"
|
|
disabled={disabled}
|
|
className="underline"
|
|
onClick={remove}
|
|
>
|
|
Retirar esta ficha da escolha
|
|
</button>
|
|
</>
|
|
)}
|
|
</article>
|
|
);
|
|
}
|
|
|
|
export default function OpportunityChoices({
|
|
choices,
|
|
onChange,
|
|
disabled = false,
|
|
corridors = [],
|
|
contextId,
|
|
}: {
|
|
choices: OpportunityChoice[];
|
|
onChange?: (choices: OpportunityChoice[]) => void;
|
|
disabled?: boolean;
|
|
corridors?: CorridorOption[];
|
|
contextId?: string;
|
|
}) {
|
|
const update = (index: number, change: Partial<OpportunityChoice>) =>
|
|
onChange?.(
|
|
choices.map((c, i) => (i === index ? { ...c, ...change } : c)),
|
|
);
|
|
return (
|
|
<section
|
|
className="space-y-4"
|
|
aria-label="Oportunidades e respectivas localizações"
|
|
>
|
|
<h2 className="text-xl font-bold">
|
|
Oportunidades escolhidas e localização de cada ficha
|
|
</h2>
|
|
<p>
|
|
{onChange
|
|
? 'Escolha o corredor e confirme onde pretende realizar o investimento.'
|
|
: 'Escolhas guardadas no dossier; cada oportunidade conserva a sua localização e associações.'}
|
|
</p>
|
|
{choices.map((c, i) => (
|
|
<div key={c.opportunity.key}>
|
|
{contextId && !onChange && (
|
|
<nav
|
|
aria-label={'Preparar ' + c.opportunity.title}
|
|
className="flex gap-4"
|
|
>
|
|
<Link
|
|
className="underline"
|
|
href={`/simulador-fiscal?context=${contextId}&opportunity=${encodeURIComponent(c.opportunity.key)}`}
|
|
>
|
|
Simular esta oportunidade
|
|
</Link>
|
|
<Link
|
|
className="underline"
|
|
href={`/investimentos/${contextId}?opportunity=${encodeURIComponent(c.opportunity.key)}`}
|
|
>
|
|
Etapas e pedidos desta oportunidade
|
|
</Link>
|
|
<Link
|
|
className="underline"
|
|
href={`/investidor/terra-duat/novo?context=${contextId}&opportunity=${encodeURIComponent(c.opportunity.key)}`}
|
|
>
|
|
Terra/DUAT desta oportunidade
|
|
</Link>
|
|
<Link
|
|
className="underline"
|
|
href={`/balcao-virtual/dossiers/${contextId}?opportunity=${encodeURIComponent(c.opportunity.key)}`}
|
|
>
|
|
Balcão desta oportunidade
|
|
</Link>
|
|
</nav>
|
|
)}
|
|
<ChoiceCard
|
|
contextId={contextId}
|
|
key={c.opportunity.key}
|
|
c={c}
|
|
i={i}
|
|
corridors={corridors}
|
|
disabled={disabled}
|
|
update={(change) => update(i, change)}
|
|
remove={
|
|
onChange
|
|
? () =>
|
|
onChange(
|
|
choices.filter(
|
|
(_, index) => index !== i,
|
|
),
|
|
)
|
|
: undefined
|
|
}
|
|
/>
|
|
</div>
|
|
))}
|
|
</section>
|
|
);
|
|
}
|