@@ -1,10 +1,11 @@
|
||||
import { Link, router } from "@inertiajs/react";
|
||||
import { useState, useEffect } from "react";
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import TerritoryGeometryPreview from '@/components/territory-geometry-preview';
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
TerritoryLevel,
|
||||
type TerritoryOption,
|
||||
} from "@/components/investment-territory";
|
||||
import { Management, Field, button, control } from "./shared";
|
||||
} from '@/components/investment-territory';
|
||||
import { Management, Field, button, control } from './shared';
|
||||
type Values = Record<string, string | number | null>;
|
||||
type Entry = {
|
||||
id: number;
|
||||
@@ -25,6 +26,7 @@ export default function OpportunityDraft({
|
||||
history,
|
||||
territoryPath,
|
||||
resourcesInstalled = false,
|
||||
maturityCatalogue,
|
||||
}: {
|
||||
record: Entry | null;
|
||||
values: Values;
|
||||
@@ -36,6 +38,12 @@ export default function OpportunityDraft({
|
||||
categories: string[];
|
||||
territoryPath: TerritoryOption[];
|
||||
resourcesInstalled?: boolean;
|
||||
maturityCatalogue: {
|
||||
version: string;
|
||||
stages: Record<string, string>;
|
||||
legacyVersion: string;
|
||||
legacyLabels: Record<string, string>;
|
||||
};
|
||||
history: {
|
||||
id: string;
|
||||
action: string;
|
||||
@@ -49,43 +57,43 @@ export default function OpportunityDraft({
|
||||
});
|
||||
const [busy, setBusy] = useState(false),
|
||||
[errors, setErrors] = useState<Record<string, string>>({}),
|
||||
[message, setMessage] = useState(""),
|
||||
[reason, setReason] = useState(""),
|
||||
[message, setMessage] = useState(''),
|
||||
[reason, setReason] = useState(''),
|
||||
[confirm, setConfirm] = useState(false),
|
||||
[token, setToken] = useState(etag);
|
||||
useEffect(() => setToken(etag), [etag]);
|
||||
const [path, setPath] = useState(territoryPath);
|
||||
const unavailable = Boolean(
|
||||
record?.deleted_at || record?.status === "archived",
|
||||
record?.deleted_at || record?.status === 'archived',
|
||||
);
|
||||
const set = (key: string, value: string) =>
|
||||
setData((d) => ({ ...d, [key]: value }));
|
||||
async function send(action: "save" | "delete" | "restore") {
|
||||
async function send(action: 'save' | 'delete' | 'restore') {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
setErrors({});
|
||||
setMessage("");
|
||||
setMessage('');
|
||||
try {
|
||||
const cookie = document.cookie
|
||||
.split("; ")
|
||||
.find((c) => c.startsWith("XSRF-TOKEN="));
|
||||
.split('; ')
|
||||
.find((c) => c.startsWith('XSRF-TOKEN='));
|
||||
const url =
|
||||
action === "save"
|
||||
action === 'save'
|
||||
? record
|
||||
? `/management/opportunities/${record.id}/draft`
|
||||
: "/management/opportunities/drafts"
|
||||
: '/management/opportunities/drafts'
|
||||
: `/management/opportunities/${record!.id}/lifecycle`;
|
||||
const response = await fetch(url, {
|
||||
method: action === "save" && record ? "PUT" : "POST",
|
||||
method: action === 'save' && record ? 'PUT' : 'POST',
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
"X-XSRF-TOKEN": cookie
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-XSRF-TOKEN': cookie
|
||||
? decodeURIComponent(cookie.slice(11))
|
||||
: "",
|
||||
: '',
|
||||
},
|
||||
body: JSON.stringify(
|
||||
action === "save"
|
||||
action === 'save'
|
||||
? { ...data, etag: token, reason }
|
||||
: { etag: token, action, reason, confirm },
|
||||
),
|
||||
@@ -96,13 +104,13 @@ export default function OpportunityDraft({
|
||||
Object.fromEntries(
|
||||
Object.entries(result.errors ?? {}).map(([k, v]) => [
|
||||
k,
|
||||
Array.isArray(v) ? v.join(" ") : String(v),
|
||||
Array.isArray(v) ? v.join(' ') : String(v),
|
||||
]),
|
||||
),
|
||||
);
|
||||
setMessage(
|
||||
result.message ??
|
||||
"Operação falhou; os dados preenchidos foram preservados.",
|
||||
'Operação falhou; os dados preenchidos foram preservados.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -110,15 +118,15 @@ export default function OpportunityDraft({
|
||||
if (result.etag) setToken(result.etag);
|
||||
if (!record)
|
||||
router.visit(`/management/opportunities/${result.id}/edit`);
|
||||
else if (action !== "save") router.reload();
|
||||
else if (action !== 'save') router.reload();
|
||||
} catch {
|
||||
setMessage(
|
||||
"Resposta indisponível. Os dados foram preservados; confira o registo no servidor antes de repetir.",
|
||||
'Resposta indisponível. Os dados foram preservados; confira o registo no servidor antes de repetir.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
requestAnimationFrame(() =>
|
||||
document.getElementById("opportunity-result")?.focus(),
|
||||
document.getElementById('opportunity-result')?.focus(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -126,8 +134,8 @@ export default function OpportunityDraft({
|
||||
<Management
|
||||
title={
|
||||
record
|
||||
? `${readOnly ? "Ver" : "Editar"} oportunidade ${record.reference}`
|
||||
: "Nova oportunidade"
|
||||
? `${readOnly ? 'Ver' : 'Editar'} oportunidade ${record.reference}`
|
||||
: 'Nova oportunidade'
|
||||
}
|
||||
>
|
||||
<Link href="/management/opportunities">Voltar à gestão</Link>
|
||||
@@ -145,13 +153,13 @@ export default function OpportunityDraft({
|
||||
<div
|
||||
id="opportunity-result"
|
||||
tabIndex={-1}
|
||||
role={Object.keys(errors).length ? "alert" : "status"}
|
||||
role={Object.keys(errors).length ? 'alert' : 'status'}
|
||||
className="rounded border p-3"
|
||||
>
|
||||
{message}
|
||||
{errors.etag && (
|
||||
<p>
|
||||
{errors.etag}{" "}
|
||||
{errors.etag}{' '}
|
||||
<a
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
@@ -166,7 +174,7 @@ export default function OpportunityDraft({
|
||||
className="max-w-3xl space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void send("save");
|
||||
void send('save');
|
||||
}}
|
||||
>
|
||||
<fieldset
|
||||
@@ -174,6 +182,10 @@ export default function OpportunityDraft({
|
||||
className="space-y-4"
|
||||
>
|
||||
<section aria-label="Localização registada">
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={path.at(-1)?.id}
|
||||
management
|
||||
/>
|
||||
<p>
|
||||
Hierarquia do cadastro territorial existente.
|
||||
Alterar esta seleção não cria relações com
|
||||
@@ -181,16 +193,16 @@ export default function OpportunityDraft({
|
||||
</p>
|
||||
{(
|
||||
[
|
||||
"province_id",
|
||||
"district_id",
|
||||
"admin_post_id",
|
||||
"locality_id",
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
] as const
|
||||
).map((key, index) => (
|
||||
<TerritoryLevel
|
||||
key={`${key}-${path[index - 1]?.id ?? ""}`}
|
||||
key={`${key}-${path[index - 1]?.id ?? ''}`}
|
||||
index={index}
|
||||
parent={path[index - 1]?.id ?? ""}
|
||||
parent={path[index - 1]?.id ?? ''}
|
||||
selected={path[index]}
|
||||
endpoint="/management/territory-options"
|
||||
fieldError={errors[key]}
|
||||
@@ -202,10 +214,10 @@ export default function OpportunityDraft({
|
||||
setPath(next);
|
||||
setData((previous) => ({
|
||||
...previous,
|
||||
province_id: next[0]?.id ?? "",
|
||||
district_id: next[1]?.id ?? "",
|
||||
admin_post_id: next[2]?.id ?? "",
|
||||
locality_id: next[3]?.id ?? "",
|
||||
province_id: next[0]?.id ?? '',
|
||||
district_id: next[1]?.id ?? '',
|
||||
admin_post_id: next[2]?.id ?? '',
|
||||
locality_id: next[3]?.id ?? '',
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
@@ -217,9 +229,9 @@ export default function OpportunityDraft({
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={String(data.opportunity_category ?? "")}
|
||||
value={String(data.opportunity_category ?? '')}
|
||||
onChange={(e) =>
|
||||
set("opportunity_category", e.target.value)
|
||||
set('opportunity_category', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
@@ -229,22 +241,22 @@ export default function OpportunityDraft({
|
||||
</select>
|
||||
</Field>
|
||||
{Object.entries({
|
||||
title: "Título oficial",
|
||||
summary: "Resumo",
|
||||
description: "Descrição",
|
||||
promoter_name: "Promotor",
|
||||
title: 'Título oficial',
|
||||
summary: 'Resumo',
|
||||
description: 'Descrição',
|
||||
promoter_name: 'Promotor',
|
||||
}).map(([key, label]) => (
|
||||
<Field key={key} label={label} error={errors[key]}>
|
||||
{key === "description" || key === "summary" ? (
|
||||
{key === 'description' || key === 'summary' ? (
|
||||
<textarea
|
||||
className={control}
|
||||
value={String(data[key] ?? "")}
|
||||
value={String(data[key] ?? '')}
|
||||
onChange={(e) => set(key, e.target.value)}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
className={control}
|
||||
value={String(data[key] ?? "")}
|
||||
value={String(data[key] ?? '')}
|
||||
onChange={(e) => set(key, e.target.value)}
|
||||
/>
|
||||
)}
|
||||
@@ -253,8 +265,8 @@ export default function OpportunityDraft({
|
||||
<Field label="Sector" error={errors.sector_id}>
|
||||
<select
|
||||
className={control}
|
||||
value={String(data.sector_id ?? "")}
|
||||
onChange={(e) => set("sector_id", e.target.value)}
|
||||
value={String(data.sector_id ?? '')}
|
||||
onChange={(e) => set('sector_id', e.target.value)}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{sectors.map((s) => (
|
||||
@@ -270,21 +282,21 @@ export default function OpportunityDraft({
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={String(data.promoter_type ?? "")}
|
||||
value={String(data.promoter_type ?? '')}
|
||||
onChange={(e) =>
|
||||
set("promoter_type", e.target.value)
|
||||
set('promoter_type', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{values.promoter_type &&
|
||||
![
|
||||
"public",
|
||||
"private",
|
||||
"ppp",
|
||||
"cooperative",
|
||||
"association",
|
||||
"community",
|
||||
"other",
|
||||
'public',
|
||||
'private',
|
||||
'ppp',
|
||||
'cooperative',
|
||||
'association',
|
||||
'community',
|
||||
'other',
|
||||
].includes(String(values.promoter_type)) && (
|
||||
<option
|
||||
value={String(values.promoter_type)}
|
||||
@@ -294,43 +306,85 @@ export default function OpportunityDraft({
|
||||
</option>
|
||||
)}
|
||||
{[
|
||||
"public",
|
||||
"private",
|
||||
"ppp",
|
||||
"cooperative",
|
||||
"association",
|
||||
"community",
|
||||
"other",
|
||||
'public',
|
||||
'private',
|
||||
'ppp',
|
||||
'cooperative',
|
||||
'association',
|
||||
'community',
|
||||
'other',
|
||||
].map((c) => (
|
||||
<option key={c}>{c}</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field
|
||||
label="Maturidade existente"
|
||||
error={errors.maturity_level}
|
||||
label="Etapa de maturidade"
|
||||
error={errors.maturity_stage ?? errors.maturity_level}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={String(data.maturity_level ?? "")}
|
||||
onChange={(e) =>
|
||||
set("maturity_level", e.target.value)
|
||||
value={
|
||||
data.maturity_catalogue_version ===
|
||||
maturityCatalogue.version
|
||||
? String(data.maturity_stage ?? '')
|
||||
: data.maturity_level
|
||||
? `legacy:${data.maturity_level}`
|
||||
: ''
|
||||
}
|
||||
onChange={(e) => {
|
||||
const stage = e.target.value;
|
||||
if (stage.startsWith('legacy:')) {
|
||||
setData((d) => ({
|
||||
...d,
|
||||
maturity_catalogue_version:
|
||||
maturityCatalogue.legacyVersion,
|
||||
maturity_level: Number(stage.slice(7)),
|
||||
maturity_stage: null,
|
||||
}));
|
||||
} else {
|
||||
setData((d) => ({
|
||||
...d,
|
||||
maturity_catalogue_version:
|
||||
maturityCatalogue.version,
|
||||
maturity_stage: stage || null,
|
||||
maturity_level: stage
|
||||
? Object.keys(
|
||||
maturityCatalogue.stages,
|
||||
).indexOf(stage) + 1
|
||||
: null,
|
||||
}));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{[
|
||||
"Ideia identificada",
|
||||
"Pré-estudo disponível",
|
||||
"Estudo de viabilidade em curso",
|
||||
"Projecto estruturado",
|
||||
"Pronto para investimento",
|
||||
"Em negociação ou implementação",
|
||||
].map((c, index) => (
|
||||
<option key={c} value={index + 1}>
|
||||
{c}
|
||||
</option>
|
||||
))}
|
||||
{values.maturity_level &&
|
||||
values.maturity_catalogue_version !==
|
||||
maturityCatalogue.version && (
|
||||
<option
|
||||
value={`legacy:${values.maturity_level}`}
|
||||
>
|
||||
{
|
||||
maturityCatalogue.legacyLabels[
|
||||
String(values.maturity_level)
|
||||
]
|
||||
}{' '}
|
||||
(catálogo histórico; sem conversão)
|
||||
</option>
|
||||
)}
|
||||
{Object.entries(maturityCatalogue.stages).map(
|
||||
([code, label], index) => (
|
||||
<option key={code} value={code}>
|
||||
{index + 1}. {label}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
<p>
|
||||
O catálogo de oito etapas é guardado com a sua
|
||||
versão. Os valores históricos conservam o
|
||||
significado anterior.
|
||||
</p>
|
||||
</Field>
|
||||
<Field
|
||||
label="Modalidade de financiamento existente"
|
||||
@@ -338,9 +392,9 @@ export default function OpportunityDraft({
|
||||
>
|
||||
<input
|
||||
className={control}
|
||||
value={String(data.financing_modality ?? "")}
|
||||
value={String(data.financing_modality ?? '')}
|
||||
onChange={(e) =>
|
||||
set("financing_modality", e.target.value)
|
||||
set('financing_modality', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
@@ -350,13 +404,13 @@ export default function OpportunityDraft({
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
value={String(data.expected_impact ?? "")}
|
||||
value={String(data.expected_impact ?? '')}
|
||||
onChange={(e) =>
|
||||
set("expected_impact", e.target.value)
|
||||
set('expected_impact', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{(data.opportunity_category === "investment_project" ||
|
||||
{(data.opportunity_category === 'investment_project' ||
|
||||
(!data.opportunity_category &&
|
||||
data.estimated_investment_amount != null)) && (
|
||||
<>
|
||||
@@ -367,11 +421,11 @@ export default function OpportunityDraft({
|
||||
<input
|
||||
className={control}
|
||||
value={String(
|
||||
data.estimated_investment_amount ?? "",
|
||||
data.estimated_investment_amount ?? '',
|
||||
)}
|
||||
onChange={(e) =>
|
||||
set(
|
||||
"estimated_investment_amount",
|
||||
'estimated_investment_amount',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
@@ -385,17 +439,17 @@ export default function OpportunityDraft({
|
||||
className={control}
|
||||
value={String(
|
||||
data.estimated_investment_currency ??
|
||||
"",
|
||||
'',
|
||||
)}
|
||||
onChange={(e) =>
|
||||
set(
|
||||
"estimated_investment_currency",
|
||||
'estimated_investment_currency',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{["MZN", "USD", "EUR", "ZAR"].map((c) => (
|
||||
{['MZN', 'USD', 'EUR', 'ZAR'].map((c) => (
|
||||
<option key={c}>{c}</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -403,7 +457,7 @@ export default function OpportunityDraft({
|
||||
</>
|
||||
)}
|
||||
{data.opportunity_category &&
|
||||
data.opportunity_category !== "investment_project" && (
|
||||
data.opportunity_category !== 'investment_project' && (
|
||||
<p>
|
||||
O módulo especializado desta categoria permanece
|
||||
pendente. Pode guardar a identificação
|
||||
@@ -439,11 +493,11 @@ export default function OpportunityDraft({
|
||||
onChange={(e) =>
|
||||
setConfirm(e.target.checked)
|
||||
}
|
||||
/>{" "}
|
||||
Confirmo a{" "}
|
||||
/>{' '}
|
||||
Confirmo a{' '}
|
||||
{unavailable
|
||||
? "restauração"
|
||||
: "exclusão lógica/arquivo"}
|
||||
? 'restauração'
|
||||
: 'exclusão lógica/arquivo'}
|
||||
, preservando histórico e relações
|
||||
</label>
|
||||
<button
|
||||
@@ -452,15 +506,15 @@ export default function OpportunityDraft({
|
||||
disabled={busy || !confirm}
|
||||
onClick={() =>
|
||||
void send(
|
||||
unavailable ? "restore" : "delete",
|
||||
unavailable ? 'restore' : 'delete',
|
||||
)
|
||||
}
|
||||
>
|
||||
{unavailable
|
||||
? "Restaurar"
|
||||
? 'Restaurar'
|
||||
: closedVersion
|
||||
? "Arquivar"
|
||||
: "Excluir rascunho"}
|
||||
? 'Arquivar'
|
||||
: 'Excluir rascunho'}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
@@ -472,12 +526,12 @@ export default function OpportunityDraft({
|
||||
href={
|
||||
resourcesInstalled
|
||||
? `/management/opportunities/${record.id}/resources`
|
||||
: "/management/opportunity-resources-install"
|
||||
: '/management/opportunity-resources-install'
|
||||
}
|
||||
>
|
||||
{resourcesInstalled
|
||||
? "Imagens, documentos e localizações"
|
||||
: "Plano de ativação de imagens, documentos e localizações"}
|
||||
? 'Imagens, documentos e localizações'
|
||||
: 'Plano de ativação de imagens, documentos e localizações'}
|
||||
</Link>
|
||||
)}
|
||||
{record && (
|
||||
@@ -490,7 +544,7 @@ export default function OpportunityDraft({
|
||||
{history.length ? (
|
||||
history.map((e) => (
|
||||
<p key={e.id}>
|
||||
{e.action} · conta {e.actor_user_id} ·{" "}
|
||||
{e.action} · conta {e.actor_user_id} ·{' '}
|
||||
{e.occurred_at}
|
||||
</p>
|
||||
))
|
||||
|
||||
Reference in New Issue
Block a user