vrsao 2
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-08 14:02:01 +02:00
parent bdd766c68a
commit 1106509116
354 changed files with 48275 additions and 24635 deletions
+72 -35
View File
@@ -11,7 +11,12 @@ type Record = {
is_active?: boolean;
status?: string;
geography_scope?: string;
primary_territory?: { name: string; location_type: string; source_system?: string; source_code?: string | null } | null;
primary_territory?: {
name: string;
location_type: string;
source_system?: string;
source_code?: string | null;
} | null;
};
export default function Catalog({
resource,
@@ -22,7 +27,12 @@ export default function Catalog({
}: {
resource: 'sectors' | 'opportunities';
records: Paginated<Record>;
filters: { q?: string; status?: string; sector_id?: number | string; geography_scope?: string };
filters: {
q?: string;
status?: string;
sector_id?: number | string;
geography_scope?: string;
};
sectors: { id: number; name: string }[];
geographyReviewCount?: number;
}) {
@@ -41,7 +51,9 @@ export default function Catalog({
</Link>
{resource === 'opportunities' && (
<p role="status" className="my-3">
{geographyReviewCount} oportunidade(s) aguardam confirmação do âmbito geográfico. A lista não altera localizações; confirme apenas com fontes existentes.
{geographyReviewCount} oportunidade(s) aguardam confirmação
do âmbito geográfico. A lista não altera localizações;
confirme apenas com fontes existentes.
</p>
)}
<form
@@ -85,34 +97,47 @@ export default function Catalog({
</select>
{resource === 'opportunities' && (
<>
<select
aria-label="Sector"
className={`${control} max-w-xs`}
value={form.data.sector_id}
onChange={(event) =>
form.setData('sector_id', event.target.value)
}
>
<option value="">Todos os sectores</option>
{sectors.map((sector) => (
<option key={sector.id} value={sector.id}>
{sector.name}
<select
aria-label="Sector"
className={`${control} max-w-xs`}
value={form.data.sector_id}
onChange={(event) =>
form.setData('sector_id', event.target.value)
}
>
<option value="">Todos os sectores</option>
{sectors.map((sector) => (
<option key={sector.id} value={sector.id}>
{sector.name}
</option>
))}
</select>
<select
aria-label="Âmbito geográfico"
className={`${control} max-w-xs`}
value={form.data.geography_scope}
onChange={(event) =>
form.setData(
'geography_scope',
event.target.value,
)
}
>
<option value="">Todos os âmbitos</option>
<option value="unspecified">
Pendente de confirmação
</option>
))}
</select>
<select
aria-label="Âmbito geográfico"
className={`${control} max-w-xs`}
value={form.data.geography_scope}
onChange={(event) => form.setData('geography_scope', event.target.value)}
>
<option value="">Todos os âmbitos</option>
<option value="unspecified">Pendente de confirmação</option>
<option value="specific">Localização específica</option>
<option value="multiple">Várias localizações</option>
<option value="national">Âmbito nacional</option>
<option value="digital">Digital/sem instalação definida</option>
</select>
<option value="specific">
Localização específica
</option>
<option value="multiple">
Várias localizações
</option>
<option value="national">Âmbito nacional</option>
<option value="digital">
Digital/sem instalação definida
</option>
</select>
</>
)}
<button className={button} disabled={form.processing}>
@@ -148,11 +173,23 @@ export default function Catalog({
: 'Inactivo'
: states[record.status ?? 'draft']}
</p>
{resource === 'opportunities' && record.geography_scope === 'unspecified' && (
<p className="mt-1 text-sm">
Pendente de confirmação; território já registado: {record.primary_territory?.name ?? 'nenhum'}. Fonte do território: {record.primary_territory?.source_system ?? 'não indicada'}{record.primary_territory?.source_code ? `, código ${record.primary_territory.source_code}` : ''}. A classificação não é alterada automaticamente.
</p>
)}
{resource === 'opportunities' &&
record.geography_scope === 'unspecified' && (
<p className="mt-1 text-sm">
Pendente de confirmação; território já
registado:{' '}
{record.primary_territory?.name ??
'nenhum'}
. Fonte do território:{' '}
{record.primary_territory
?.source_system ?? 'não indicada'}
{record.primary_territory?.source_code
? `, código ${record.primary_territory.source_code}`
: ''}
. A classificação não é alterada
automaticamente.
</p>
)}
</div>
<Link
className="underline"
+168 -93
View File
@@ -1,38 +1,41 @@
import { Link, useForm } from "@inertiajs/react";
import InvestmentCoordinates from "@/components/investment-coordinates";
import { TerritoryLevel, type TerritoryOption } from "@/components/investment-territory";
import { useState } from "react";
import { Management, Field, button, control, states } from "./shared";
import { Link, useForm } from '@inertiajs/react';
import InvestmentCoordinates from '@/components/investment-coordinates';
import {
TerritoryLevel,
type TerritoryOption,
} from '@/components/investment-territory';
import { useState } from 'react';
import { Management, Field, button, control, states } from './shared';
type Values = Record<string, string | boolean>;
type Entry = Record<string, string | number | boolean | null> & { id: number };
const opportunityFields = {
reference: "Referência",
title: "Título",
slug: "Slug (endereço)",
summary: "Resumo",
description: "Descrição",
promoter_name: "Promotor",
promoter_type: "Tipo de promotor",
estimated_investment_amount: "Investimento estimado",
estimated_investment_currency: "Moeda (código de três letras)",
financing_modality: "Modalidade de financiamento",
expected_impact: "Impacto esperado",
reference: 'Referência',
title: 'Título',
slug: 'Slug (endereço)',
summary: 'Resumo',
description: 'Descrição',
promoter_name: 'Promotor',
promoter_type: 'Tipo de promotor',
estimated_investment_amount: 'Investimento estimado',
estimated_investment_currency: 'Moeda (código de três letras)',
financing_modality: 'Modalidade de financiamento',
expected_impact: 'Impacto esperado',
};
const sectorFields = {
name: "Nome",
slug: "Slug (endereço)",
short_description: "Descrição curta",
description: "Descrição",
sort_order: "Ordem de apresentação",
name: 'Nome',
slug: 'Slug (endereço)',
short_description: 'Descrição curta',
description: 'Descrição',
sort_order: 'Ordem de apresentação',
};
const maturities = [
"Ideia identificada",
"Pré-estudo disponível",
"Estudo de viabilidade em curso",
"Projecto estruturado",
"Pronto para investimento",
"Em negociação ou implementação",
'Ideia identificada',
'Pré-estudo disponível',
'Estudo de viabilidade em curso',
'Projecto estruturado',
'Pronto para investimento',
'Em negociação ou implementação',
];
export default function Editor({
@@ -41,54 +44,64 @@ export default function Editor({
sectors,
territoryPath = [],
}: {
resource: "sectors" | "opportunities";
resource: 'sectors' | 'opportunities';
record: Entry | null;
sectors: { id: number; name: string }[];
territoryPath?: TerritoryOption[];
}) {
const isSector = resource === "sectors";
const isSector = resource === 'sectors';
const fields = isSector ? sectorFields : opportunityFields;
const initial: Values = Object.fromEntries(
Object.keys(fields).map((key) => [
key,
String(
record?.[key] ??
(key === "estimated_investment_currency"
? "USD"
: key === "sort_order"
? "0"
: ""),
(key === 'estimated_investment_currency'
? 'USD'
: key === 'sort_order'
? '0'
: ''),
),
]),
);
if (isSector) initial.is_active = Boolean(record?.is_active ?? true);
else {
initial.sector_id = String(record?.sector_id ?? "");
initial.maturity_level = String(record?.maturity_level ?? "");
initial.status = String(record?.status ?? "draft");
initial.sector_id = String(record?.sector_id ?? '');
initial.maturity_level = String(record?.maturity_level ?? '');
initial.status = String(record?.status ?? 'draft');
initial.is_featured = Boolean(record?.is_featured ?? false);
initial.geography_scope = String(record?.geography_scope ?? "unspecified");
initial.geography_scope = String(
record?.geography_scope ?? 'unspecified',
);
initial.territory_version = String(record?.territory_version ?? 0);
["province_id", "district_id", "admin_post_id", "locality_id"].forEach((field, index) => {
initial[field] = territoryPath[index]?.id ?? "";
});
['province_id', 'district_id', 'admin_post_id', 'locality_id'].forEach(
(field, index) => {
initial[field] = territoryPath[index]?.id ?? '';
},
);
}
const form = useForm<Values>(initial);
const [creationPath, setCreationPath] = useState<TerritoryOption[]>(territoryPath);
const [creationPath, setCreationPath] =
useState<TerritoryOption[]>(territoryPath);
return (
<Management
title={`${record ? "Editar" : "Criar"} ${isSector ? "sector" : "oportunidade"}`}
title={`${record ? 'Editar' : 'Criar'} ${isSector ? 'sector' : 'oportunidade'}`}
>
{!isSector && record && (
<Link className="underline" href={`/management/opportunities/${record.id}/context`}>
Gerir clusters, corredores, projectos, educação e necessidades
<Link
className="underline"
href={`/management/opportunities/${record.id}/context`}
>
Gerir clusters, corredores, projectos, educação e
necessidades
</Link>
)}
<form
className="max-w-3xl space-y-5"
onSubmit={(event) => {
event.preventDefault();
if (record) form.put(`/management/${resource}/${record.id}`);
if (record)
form.put(`/management/${resource}/${record.id}`);
else form.post(`/management/${resource}`);
}}
>
@@ -97,16 +110,16 @@ export default function Editor({
<div className="grid gap-4 md:grid-cols-2">
{(
[
"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}-${creationPath[index - 1]?.id ?? ""}`}
key={`${key}-${creationPath[index - 1]?.id ?? ''}`}
index={index}
parent={creationPath[index - 1]?.id ?? ""}
parent={creationPath[index - 1]?.id ?? ''}
selected={creationPath[index]}
endpoint="/management/territory-options"
fieldError={form.errors[key]}
@@ -118,10 +131,10 @@ export default function Editor({
setCreationPath(path);
form.setData((data) => ({
...data,
province_id: path[0]?.id ?? "",
district_id: path[1]?.id ?? "",
admin_post_id: path[2]?.id ?? "",
locality_id: path[3]?.id ?? "",
province_id: path[0]?.id ?? '',
district_id: path[1]?.id ?? '',
admin_post_id: path[2]?.id ?? '',
locality_id: path[3]?.id ?? '',
}));
}}
/>
@@ -131,22 +144,26 @@ export default function Editor({
{Object.entries(fields).map(([key, label]) => (
<Field key={key} label={label} error={form.errors[key]}>
{[
"description",
"summary",
"short_description",
"expected_impact",
'description',
'summary',
'short_description',
'expected_impact',
].includes(key) ? (
<textarea
className={control}
rows={key === "description" ? 6 : 3}
rows={key === 'description' ? 6 : 3}
value={String(form.data[key])}
onChange={(e) => form.setData(key, e.target.value)}
onChange={(e) =>
form.setData(key, e.target.value)
}
/>
) : (
<input
className={control}
value={String(form.data[key])}
onChange={(e) => form.setData(key, e.target.value)}
onChange={(e) =>
form.setData(key, e.target.value)
}
/>
)}
</Field>
@@ -157,21 +174,37 @@ export default function Editor({
<select
className={control}
value={String(form.data.sector_id)}
onChange={(e) => form.setData("sector_id", e.target.value)}
onChange={(e) =>
form.setData(
'sector_id',
e.target.value,
)
}
>
<option value="">Seleccione</option>
{sectors.map((sector) => (
<option key={sector.id} value={sector.id}>
<option
key={sector.id}
value={sector.id}
>
{sector.name}
</option>
))}
</select>
</Field>
<Field label="Maturidade" error={form.errors.maturity_level}>
<Field
label="Maturidade"
error={form.errors.maturity_level}
>
<select
className={control}
value={String(form.data.maturity_level)}
onChange={(e) => form.setData("maturity_level", e.target.value)}
onChange={(e) =>
form.setData(
'maturity_level',
e.target.value,
)
}
>
<option value="">Por indicar</option>
{maturities.map((label, index) => (
@@ -181,47 +214,86 @@ export default function Editor({
))}
</select>
</Field>
<Field label="Âmbito geográfico" error={form.errors.geography_scope}>
<select className={control} value={String(form.data.geography_scope)} onChange={(e) => {
form.setData("geography_scope", e.target.value);
if (e.target.value === "national" || e.target.value === "digital") {
setCreationPath([]);
form.setData((data) => ({ ...data, geography_scope: e.target.value,
province_id: "", district_id: "", admin_post_id: "", locality_id: "" }));
}
}}>
<option value="unspecified">Não especificado</option>
<option value="specific">Localização específica</option>
<option value="multiple">Várias localizações</option>
<option value="national">Âmbito nacional</option>
<option value="digital">Digital/sem instalação definida</option>
<Field
label="Âmbito geográfico"
error={form.errors.geography_scope}
>
<select
className={control}
value={String(form.data.geography_scope)}
onChange={(e) => {
form.setData(
'geography_scope',
e.target.value,
);
if (
e.target.value === 'national' ||
e.target.value === 'digital'
) {
setCreationPath([]);
form.setData((data) => ({
...data,
geography_scope: e.target.value,
province_id: '',
district_id: '',
admin_post_id: '',
locality_id: '',
}));
}
}}
>
<option value="unspecified">
Não especificado
</option>
<option value="specific">
Localização específica
</option>
<option value="multiple">
Várias localizações
</option>
<option value="national">
Âmbito nacional
</option>
<option value="digital">
Digital/sem instalação definida
</option>
</select>
</Field>
<Field label="Estado" error={form.errors.status}>
<select
className={control}
value={String(form.data.status)}
onChange={(e) => form.setData("status", e.target.value)}
onChange={(e) =>
form.setData('status', e.target.value)
}
>
{["draft", "published", "archived"].map((key) => (
<option key={key} value={key}>
{states[key]}
</option>
))}
{['draft', 'published', 'archived'].map(
(key) => (
<option key={key} value={key}>
{states[key]}
</option>
),
)}
</select>
</Field>
</>
)}
<Field
label={isSector ? "Activo" : "Em destaque"}
error={form.errors[isSector ? "is_active" : "is_featured"]}
label={isSector ? 'Activo' : 'Em destaque'}
error={
form.errors[isSector ? 'is_active' : 'is_featured']
}
>
<input
type="checkbox"
checked={Boolean(form.data[isSector ? "is_active" : "is_featured"])}
checked={Boolean(
form.data[
isSector ? 'is_active' : 'is_featured'
],
)}
onChange={(e) =>
form.setData(
isSector ? "is_active" : "is_featured",
isSector ? 'is_active' : 'is_featured',
e.target.checked,
)
}
@@ -229,9 +301,12 @@ export default function Editor({
</Field>
<div className="flex gap-4">
<button className={button} disabled={form.processing}>
{form.processing ? "A guardar…" : "Guardar"}
{form.processing ? 'A guardar…' : 'Guardar'}
</button>
<Link className="p-2 underline" href={`/management/${resource}`}>
<Link
className="p-2 underline"
href={`/management/${resource}`}
>
Cancelar
</Link>
</div>
+235 -65
View File
@@ -1,5 +1,5 @@
import { Link, useForm } from "@inertiajs/react";
import { Management, Field, button, control, states } from "./shared";
import { Link, useForm } from '@inertiajs/react';
import { Management, Field, button, control, states } from './shared';
type Interest = {
id: number;
@@ -32,36 +32,64 @@ type Interest = {
};
};
function dateTime(value: string | null) {
if (!value) return "—";
return new Intl.DateTimeFormat("pt-MZ", {
dateStyle: "medium",
timeStyle: "short",
timeZone: "Africa/Maputo",
if (!value) return '—';
return new Intl.DateTimeFormat('pt-MZ', {
dateStyle: 'medium',
timeStyle: 'short',
timeZone: 'Africa/Maputo',
}).format(new Date(value));
}
type Transition = { from_status: string | null; to_status: string; actor_id: number | null; note: string | null; created_at: string };
type Transition = {
from_status: string | null;
to_status: string;
actor_id: number | null;
note: string | null;
created_at: string;
};
type Assignee = { id: number; name: string };
type Consent = { purpose: string; policy_version: string | null; status: string; granted_at: string | null; withdrawn_at: string | null };
type Consent = {
purpose: string;
policy_version: string | null;
status: string;
granted_at: string | null;
withdrawn_at: string | null;
};
export default function InterestDetail({ interest, history = [], assignees = [], consents = [] }: { interest: Interest; history?: Transition[]; assignees?: Assignee[]; consents?: Consent[] }) {
const form = useForm({ status: interest.status, note: "", next_action: interest.next_action ?? "", next_action_due_at: interest.next_action_due_at?.slice(0, 10) ?? "", assigned_to: interest.assigned_to?.toString() ?? "" });
const contactConsentForm = useForm({ reason: "" });
const sharingConsentForm = useForm({ reason: "" });
export default function InterestDetail({
interest,
history = [],
assignees = [],
consents = [],
}: {
interest: Interest;
history?: Transition[];
assignees?: Assignee[];
consents?: Consent[];
}) {
const form = useForm({
status: interest.status,
note: '',
next_action: interest.next_action ?? '',
next_action_due_at: interest.next_action_due_at?.slice(0, 10) ?? '',
assigned_to: interest.assigned_to?.toString() ?? '',
});
const contactConsentForm = useForm({ reason: '' });
const sharingConsentForm = useForm({ reason: '' });
const rows: [string, string | number | null][] = [
["Nome", interest.full_name],
["Email", interest.email],
["Telefone", interest.phone],
["Tipo de investidor", interest.investor_type],
["País", interest.country],
["Sector", interest.sector_interest],
["Oportunidade", interest.opportunity_reference],
["Negócio publicado", interest.existing_business_id],
["Modalidade", interest.modality],
["Faixa de investimento", interest.investment_range],
["Recebido em (Maputo)", dateTime(interest.created_at)],
["Consentimento em (Maputo)", dateTime(interest.consented_at)],
["Revisto em (Maputo)", dateTime(interest.reviewed_at)],
["Revisto pelo utilizador", interest.reviewed_by],
['Nome', interest.full_name],
['Email', interest.email],
['Telefone', interest.phone],
['Tipo de investidor', interest.investor_type],
['País', interest.country],
['Sector', interest.sector_interest],
['Oportunidade', interest.opportunity_reference],
['Negócio publicado', interest.existing_business_id],
['Modalidade', interest.modality],
['Faixa de investimento', interest.investment_range],
['Recebido em (Maputo)', dateTime(interest.created_at)],
['Consentimento em (Maputo)', dateTime(interest.consented_at)],
['Revisto em (Maputo)', dateTime(interest.reviewed_at)],
['Revisto pelo utilizador', interest.reviewed_by],
];
return (
<Management title={interest.reference}>
@@ -70,7 +98,8 @@ export default function InterestDetail({ interest, history = [], assignees = [],
className="underline"
href={`/investidor/manifestacoes/${interest.metadata.submission_id}`}
>
Consultar manifestação completa, necessidades e anexos privados
Consultar manifestação completa, necessidades e anexos
privados
</Link>
)}
{interest.metadata?.dossier_id && (
@@ -84,54 +113,134 @@ export default function InterestDetail({ interest, history = [], assignees = [],
</Link>
<p>Jornada: {interest.metadata.journey_id}</p>
<p>
Papel: {interest.metadata.role} · Horizonte: {interest.metadata.horizon}
Papel: {interest.metadata.role} · Horizonte:{' '}
{interest.metadata.horizon}
</p>
</section>
)}
<Link className={button} href={`/management/crm/convert/${interest.id}`}>
<Link
className={button}
href={`/management/crm/convert/${interest.id}`}
>
Encaminhar para o CRM
</Link>
<dl className="grid gap-4 sm:grid-cols-2">
{rows.map(([label, value]) => (
<div key={label}>
<dt className="text-muted-foreground text-sm">{label}</dt>
<dd className="break-words">{value ?? "—"}</dd>
<dt className="text-muted-foreground text-sm">
{label}
</dt>
<dd className="break-words">{value ?? '—'}</dd>
</div>
))}
</dl>
<section>
<h2 className="font-semibold">Mensagem</h2>
<p className="mt-2 break-words whitespace-pre-wrap">{interest.message}</p>
<p className="mt-2 break-words whitespace-pre-wrap">
{interest.message}
</p>
</section>
<section className="space-y-3">
<h2 className="font-semibold">Consentimentos e versões</h2>
{consents.map((consent, index) => (
<article key={`${consent.purpose}-${index}`} className="rounded border p-3">
<p>{consent.purpose}: {consent.status}</p>
<p className="text-sm">Política {consent.policy_version ?? "—"} · concedido {dateTime(consent.granted_at)}</p>
{consent.withdrawn_at && <p className="text-sm">Revogado {dateTime(consent.withdrawn_at)}</p>}
<article
key={`${consent.purpose}-${index}`}
className="rounded border p-3"
>
<p>
{consent.purpose}: {consent.status}
</p>
<p className="text-sm">
Política {consent.policy_version ?? '—'} · concedido{' '}
{dateTime(consent.granted_at)}
</p>
{consent.withdrawn_at && (
<p className="text-sm">
Revogado {dateTime(consent.withdrawn_at)}
</p>
)}
</article>
))}
{consents.some((consent) => consent.purpose === "respond_to_interest" && consent.status === "granted") && (
<form className="max-w-sm space-y-3" onSubmit={(event) => {
event.preventDefault();
contactConsentForm.patch(`/management/interests/${interest.id}/consent/contact`);
}}>
<Field label="Motivo do pedido de revogação" error={contactConsentForm.errors.reason}>
<textarea className={control} minLength={10} maxLength={2000} required rows={3} value={contactConsentForm.data.reason} onChange={(event) => contactConsentForm.setData("reason", event.target.value)} />
{consents.some(
(consent) =>
consent.purpose === 'respond_to_interest' &&
consent.status === 'granted',
) && (
<form
className="max-w-sm space-y-3"
onSubmit={(event) => {
event.preventDefault();
contactConsentForm.patch(
`/management/interests/${interest.id}/consent/contact`,
);
}}
>
<Field
label="Motivo do pedido de revogação"
error={contactConsentForm.errors.reason}
>
<textarea
className={control}
minLength={10}
maxLength={2000}
required
rows={3}
value={contactConsentForm.data.reason}
onChange={(event) =>
contactConsentForm.setData(
'reason',
event.target.value,
)
}
/>
</Field>
<button className={button} disabled={contactConsentForm.processing}>Revogar autorização de contacto</button>
<button
className={button}
disabled={contactConsentForm.processing}
>
Revogar autorização de contacto
</button>
</form>
)}
{consents.some((consent) => consent.purpose === "share_contact_with_proponent" && consent.status === "granted") && (
<form className="max-w-sm space-y-3" onSubmit={(event) => {
event.preventDefault();
sharingConsentForm.patch(`/management/interests/${interest.id}/consent/proponent`);
}}>
<Field label="Motivo do pedido de revogação" error={sharingConsentForm.errors.reason}>
<textarea className={control} minLength={10} maxLength={2000} required rows={3} value={sharingConsentForm.data.reason} onChange={(event) => sharingConsentForm.setData("reason", event.target.value)} />
{consents.some(
(consent) =>
consent.purpose === 'share_contact_with_proponent' &&
consent.status === 'granted',
) && (
<form
className="max-w-sm space-y-3"
onSubmit={(event) => {
event.preventDefault();
sharingConsentForm.patch(
`/management/interests/${interest.id}/consent/proponent`,
);
}}
>
<Field
label="Motivo do pedido de revogação"
error={sharingConsentForm.errors.reason}
>
<textarea
className={control}
minLength={10}
maxLength={2000}
required
rows={3}
value={sharingConsentForm.data.reason}
onChange={(event) =>
sharingConsentForm.setData(
'reason',
event.target.value,
)
}
/>
</Field>
<button className={button} disabled={sharingConsentForm.processing}>Revogar autorização de partilha</button>
<button
className={button}
disabled={sharingConsentForm.processing}
>
Revogar autorização de partilha
</button>
</form>
)}
</section>
@@ -146,9 +255,26 @@ export default function InterestDetail({ interest, history = [], assignees = [],
<select
className={control}
value={form.data.status}
onChange={(e) => form.setData("status", e.target.value)}
onChange={(e) => form.setData('status', e.target.value)}
>
{["received", "submitted", "in_review", "reviewed", "qualification", "qualified", "contacted", "contact_accepted", "referred", "due_diligence", "negotiation", "pending", "refused", "converted", "cancelled", "closed"].map((key) => (
{[
'received',
'submitted',
'in_review',
'reviewed',
'qualification',
'qualified',
'contacted',
'contact_accepted',
'referred',
'due_diligence',
'negotiation',
'pending',
'refused',
'converted',
'cancelled',
'closed',
].map((key) => (
<option key={key} value={key}>
{states[key]}
</option>
@@ -156,31 +282,75 @@ export default function InterestDetail({ interest, history = [], assignees = [],
</select>
</Field>
<Field label="Nota de acompanhamento" error={form.errors.note}>
<textarea className={control} rows={3} value={form.data.note} onChange={(e) => form.setData("note", e.target.value)} />
<textarea
className={control}
rows={3}
value={form.data.note}
onChange={(e) => form.setData('note', e.target.value)}
/>
</Field>
<Field label="Próxima acção" error={form.errors.next_action}>
<input className={control} value={form.data.next_action} onChange={(e) => form.setData("next_action", e.target.value)} />
<input
className={control}
value={form.data.next_action}
onChange={(e) =>
form.setData('next_action', e.target.value)
}
/>
</Field>
<Field label="Prazo da próxima acção" error={form.errors.next_action_due_at}>
<input type="date" className={control} value={form.data.next_action_due_at} onChange={(e) => form.setData("next_action_due_at", e.target.value)} />
<Field
label="Prazo da próxima acção"
error={form.errors.next_action_due_at}
>
<input
type="date"
className={control}
value={form.data.next_action_due_at}
onChange={(e) =>
form.setData('next_action_due_at', e.target.value)
}
/>
</Field>
<Field label="Responsável" error={form.errors.assigned_to}>
<select className={control} value={form.data.assigned_to} onChange={(e) => form.setData("assigned_to", e.target.value)}>
<select
className={control}
value={form.data.assigned_to}
onChange={(e) =>
form.setData('assigned_to', e.target.value)
}
>
<option value="">Sem responsável</option>
{assignees.map((assignee) => <option key={assignee.id} value={assignee.id}>{assignee.name}</option>)}
{assignees.map((assignee) => (
<option key={assignee.id} value={assignee.id}>
{assignee.name}
</option>
))}
</select>
</Field>
<button className={button} disabled={form.processing}>
{form.processing ? "A guardar…" : "Guardar estado"}
{form.processing ? 'A guardar…' : 'Guardar estado'}
</button>
</form>
<section className="space-y-3">
<h2 className="font-semibold">Histórico do fluxo</h2>
{!history.length && <p>Sem alterações de estado registadas.</p>}
{history.map((entry, index) => (
<article key={`${entry.created_at}-${index}`} className="rounded border p-3">
<p>{entry.from_status ? `${states[entry.from_status] ?? entry.from_status} → ` : ""}{states[entry.to_status] ?? entry.to_status} · {dateTime(entry.created_at)}</p>
{entry.note && <p className="mt-1 whitespace-pre-wrap">{entry.note}</p>}
<article
key={`${entry.created_at}-${index}`}
className="rounded border p-3"
>
<p>
{entry.from_status
? `${states[entry.from_status] ?? entry.from_status} → `
: ''}
{states[entry.to_status] ?? entry.to_status} ·{' '}
{dateTime(entry.created_at)}
</p>
{entry.note && (
<p className="mt-1 whitespace-pre-wrap">
{entry.note}
</p>
)}
</article>
))}
</section>
+50 -11
View File
@@ -32,7 +32,11 @@ export default function Interests({
className="flex flex-wrap gap-3"
onSubmit={(e) => {
e.preventDefault();
router.get('/management/interests', { q, status, follow_up: followUp });
router.get('/management/interests', {
q,
status,
follow_up: followUp,
});
}}
>
<input
@@ -49,15 +53,39 @@ export default function Interests({
onChange={(e) => setStatus(e.target.value)}
>
<option value="">Todos os estados</option>
{Object.keys(states).filter((key) => ['received', 'submitted', 'in_review', 'reviewed', 'qualification', 'qualified', 'contacted', 'contact_accepted', 'referred', 'due_diligence', 'negotiation', 'pending', 'refused', 'converted', 'cancelled', 'closed'].includes(key)).map(
(key) => (
{Object.keys(states)
.filter((key) =>
[
'received',
'submitted',
'in_review',
'reviewed',
'qualification',
'qualified',
'contacted',
'contact_accepted',
'referred',
'due_diligence',
'negotiation',
'pending',
'refused',
'converted',
'cancelled',
'closed',
].includes(key),
)
.map((key) => (
<option key={key} value={key}>
{states[key]}
</option>
),
)}
))}
</select>
<select aria-label="Acompanhamento" className={`${control} max-w-xs`} value={followUp} onChange={(e) => setFollowUp(e.target.value)}>
<select
aria-label="Acompanhamento"
className={`${control} max-w-xs`}
value={followUp}
onChange={(e) => setFollowUp(e.target.value)}
>
<option value="">Todos os acompanhamentos</option>
<option value="overdue">Acções atrasadas</option>
<option value="upcoming">Acções por vencer</option>
@@ -105,12 +133,23 @@ export default function Interests({
{item.sector_interest}
</td>
<td className="border-b p-3">
{item.modality ?? (item.existing_business_id ? 'Negócio' : '—')}
{item.modality ??
(item.existing_business_id
? 'Negócio'
: '—')}
</td>
<td className="border-b p-3">{item.assignee?.name ?? '—'}</td>
<td className="border-b p-3">{item.next_action ?? '—'}</td>
<td className={`border-b p-3 ${item.next_action_due_at && new Date(item.next_action_due_at) < new Date() ? 'font-semibold text-red-700' : ''}`}>
{item.next_action_due_at ? `${new Date(item.next_action_due_at) < new Date() ? 'Atrasada · ' : ''}${new Intl.DateTimeFormat('pt-MZ', { dateStyle: 'medium', timeZone: 'Africa/Maputo' }).format(new Date(item.next_action_due_at))}` : '—'}
<td className="border-b p-3">
{item.assignee?.name ?? '—'}
</td>
<td className="border-b p-3">
{item.next_action ?? '—'}
</td>
<td
className={`border-b p-3 ${item.next_action_due_at && new Date(item.next_action_due_at) < new Date() ? 'font-semibold text-red-700' : ''}`}
>
{item.next_action_due_at
? `${new Date(item.next_action_due_at) < new Date() ? 'Atrasada · ' : ''}${new Intl.DateTimeFormat('pt-MZ', { dateStyle: 'medium', timeZone: 'Africa/Maputo' }).format(new Date(item.next_action_due_at))}`
: '—'}
</td>
<td className="border-b p-3">
{states[item.status] ?? item.status}
@@ -1,5 +1,5 @@
import { Link, useForm } from "@inertiajs/react";
import { Management } from "./shared";
import { Link, useForm } from '@inertiajs/react';
import { Management } from './shared';
type Plan = {
target: { database: string; port: number };
@@ -35,7 +35,7 @@ type Plan = {
type Territory = {
row_id: string;
validation_hash: string;
status: "grounded" | "pending" | "contradictory";
status: 'grounded' | 'pending' | 'contradictory';
applied: boolean;
issues: string[];
warnings: string[];
@@ -71,23 +71,23 @@ type History = {
};
};
const roles: Record<string, string> = {
primary: "Principal",
secondary: "Secundária",
impact: "Área de impacto",
primary: 'Principal',
secondary: 'Secundária',
impact: 'Área de impacto',
};
const levels: Record<string, string> = {
country: "País",
province: "Província",
district: "Distrito",
admin_post: "Posto administrativo",
locality: "Localidade",
site: "Implantação",
country: 'País',
province: 'Província',
district: 'Distrito',
admin_post: 'Posto administrativo',
locality: 'Localidade',
site: 'Implantação',
};
function pathText(path: { name: string; type: string }[]) {
return (
path
.map((node) => `${levels[node.type] ?? node.type}: ${node.name}`)
.join(" → ") || "Hierarquia não indicada"
.join(' → ') || 'Hierarquia não indicada'
);
}
function IndividualAssociation({
@@ -111,7 +111,7 @@ function IndividualAssociation({
row_id: item.row_id,
validation_hash: item.validation_hash,
}));
form.post("/management/relationship-repair", {
form.post('/management/relationship-repair', {
preserveScroll: true,
});
}}
@@ -121,12 +121,12 @@ function IndividualAssociation({
disabled={
form.processing ||
item.applied ||
item.status !== "grounded"
item.status !== 'grounded'
}
>
{item.applied
? "Associação aplicada"
: "Aplicar esta associação"}
? 'Associação aplicada'
: 'Aplicar esta associação'}
</button>
{Object.values(form.errors).map((error) => (
<p key={error} role="alert">
@@ -172,7 +172,7 @@ export default function RelationshipRepair({
<form
onSubmit={(event) => {
event.preventDefault();
form.post("/management/relationship-repair");
form.post('/management/relationship-repair');
}}
>
<button
@@ -198,34 +198,34 @@ export default function RelationshipRepair({
localização não é deduzida de clusters ou da proximidade a
zonas.
</p>
{(["grounded", "pending", "contradictory"] as const).map(
{(['grounded', 'pending', 'contradictory'] as const).map(
(status) => (
<section
key={status}
className="space-y-4"
aria-label={
status === "grounded"
? "Associações fundamentadas"
: status === "pending"
? "Associações pendentes"
: "Associações contraditórias"
status === 'grounded'
? 'Associações fundamentadas'
: status === 'pending'
? 'Associações pendentes'
: 'Associações contraditórias'
}
>
<h3 className="text-lg font-bold">
{status === "grounded"
? "Fundamentadas"
: status === "pending"
? "Pendentes"
: "Contraditórias"}
:{" "}
{status === 'grounded'
? 'Fundamentadas'
: status === 'pending'
? 'Pendentes'
: 'Contraditórias'}
:{' '}
{territorial.filter(
(item) => item.status === status,
).length +
(status === "pending"
(status === 'pending'
? unproposed.length
: 0)}
</h3>
{status === "pending" &&
{status === 'pending' &&
unproposed.map((item) => (
<article
key={item.code}
@@ -236,23 +236,23 @@ export default function RelationshipRepair({
territorial individualizada
</h4>
<p>
Localização atual:{" "}
Localização atual:{' '}
{item.current
.map(
(location) =>
`${location.name} · ${roles[location.role]}`,
)
.join("; ") ||
"Sem localização cadastrada"}
.join('; ') ||
'Sem localização cadastrada'}
</p>
<p>
Localização documental proposta:{" "}
Localização documental proposta:{' '}
{item.location_text ??
"Não indicada"}
'Não indicada'}
</p>
<p>
Documento de origem:{" "}
{item.source ?? "Não indicado"}
Documento de origem:{' '}
{item.source ?? 'Não indicado'}
</p>
{item.reasons.map((reason) => (
<p key={reason}>{reason}</p>
@@ -267,8 +267,8 @@ export default function RelationshipRepair({
className="space-y-3 rounded border p-4"
>
<h4 className="font-bold">
{plan.locations[index].code} →{" "}
{validation.proposed.name} ·{" "}
{plan.locations[index].code} →{' '}
{validation.proposed.name} ·{' '}
{roles[validation.proposed.role] ??
validation.proposed.role}
</h4>
@@ -279,12 +279,12 @@ export default function RelationshipRepair({
{validation.current.map(
(current, i) => (
<li key={i}>
{current.name} ·{" "}
{current.name} ·{' '}
{roles[
current.role
] ??
current.role}{" "}
—{" "}
current.role}{' '}
—{' '}
{pathText(
current.path,
)}
@@ -301,12 +301,12 @@ export default function RelationshipRepair({
<p>
<strong>
Localização proposta:
</strong>{" "}
{pathText(validation.proposed.path)}{" "}
</strong>{' '}
{pathText(validation.proposed.path)}{' '}
· {roles[validation.proposed.role]}
</p>
<p>
Documento de origem:{" "}
Documento de origem:{' '}
{
plan.locations[index]
.source_reference
@@ -316,18 +316,18 @@ export default function RelationshipRepair({
{plan.locations[index].source_quote}
</blockquote>
<p>
Motivo:{" "}
Motivo:{' '}
{plan.locations[index].reason}
</p>
{validation.coordinates.map(
(point, i) => (
<p key={i}>
Coordenadas (longitude,
latitude):{" "}
latitude):{' '}
{point.coordinates.join(
", ",
)}{" "}
· SRID {point.srid} · Fonte:{" "}
', ',
)}{' '}
· SRID {point.srid} · Fonte:{' '}
{point.source}
</p>
),
@@ -336,9 +336,9 @@ export default function RelationshipRepair({
(check, i) => (
<p key={i}>
{check.compatible
? "Coordenadas compatíveis com o limite territorial"
: "Coordenadas incompatíveis com o limite territorial"}{" "}
· Fonte cartográfica:{" "}
? 'Coordenadas compatíveis com o limite territorial'
: 'Coordenadas incompatíveis com o limite territorial'}{' '}
· Fonte cartográfica:{' '}
{check.source}
</p>
),
@@ -371,12 +371,12 @@ export default function RelationshipRepair({
history.map((event) => (
<article key={event.id} className="rounded border p-4">
<p>
Autor: {event.actor ?? "Utilizador"} (ID{" "}
Autor: {event.actor ?? 'Utilizador'} (ID{' '}
{event.actor_id}) · Data: {event.date}
</p>
{event.data.sources?.map((source) => (
<p key={source.row_id}>
Fonte: {source.source_reference} · Motivo:{" "}
Fonte: {source.source_reference} · Motivo:{' '}
{source.reason}
</p>
))}
@@ -396,9 +396,9 @@ export default function RelationshipRepair({
{item.cluster_code} ↔ {item.project_code}
</h3>
<p>
{item.action === "present_existing"
? "Relação existente, agora apresentada como proposta documental pendente"
: "Relação ausente"}
{item.action === 'present_existing'
? 'Relação existente, agora apresentada como proposta documental pendente'
: 'Relação ausente'}
</p>
<p>Fonte: {item.source_reference}</p>
<blockquote>{item.source_quote}</blockquote>
@@ -407,7 +407,7 @@ export default function RelationshipRepair({
</section>
<section className="space-y-4">
<h2 className="text-xl font-bold">
Registos de oportunidades preparados:{" "}
Registos de oportunidades preparados:{' '}
{plan.prepared_opportunities.length}
</h2>
{plan.prepared_opportunities.map((item, index) => (
@@ -416,14 +416,14 @@ export default function RelationshipRepair({
{item.reference} · {item.title}
</summary>
<p>
Projecto:{" "}
Projecto:{' '}
{item.project_code ??
"Identidade em conflito; associação pendente"}
'Identidade em conflito; associação pendente'}
</p>
<p>{item.location_text}</p>
<p>Fonte: {item.source_reference}</p>
<p>{item.reason}</p>
<p>Dados por completar: {item.unknown.join(", ")}.</p>
<p>Dados por completar: {item.unknown.join(', ')}.</p>
</details>
))}
</section>
+81 -44
View File
@@ -1,6 +1,6 @@
import { Head, Link, usePage } from "@inertiajs/react";
import type { ReactNode } from "react";
import { cloneElement, isValidElement, useId } from "react";
import { Head, Link, usePage } from '@inertiajs/react';
import type { ReactNode } from 'react';
import { cloneElement, isValidElement, useId } from 'react';
export type Paginated<T> = {
data: T[];
@@ -10,32 +10,39 @@ export type Paginated<T> = {
prev_page_url: string | null;
next_page_url: string | null;
};
export const control = "w-full rounded-md border border-input bg-background p-2 text-foreground";
export const control =
'w-full rounded-md border border-input bg-background p-2 text-foreground';
export const button =
"inline-flex items-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground disabled:opacity-50";
'inline-flex items-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground disabled:opacity-50';
export const states: Record<string, string> = {
received: "Recebido",
submitted: "Submetido",
in_review: "Em análise",
contacted: "Contactado",
reviewed: "Revisto",
qualification: "Em qualificação",
qualified: "Qualificado",
contact_accepted: "Contacto aceite",
referred: "Encaminhado",
due_diligence: "Diligência devida",
negotiation: "Em negociação",
pending: "Pendente",
refused: "Recusado",
converted: "Convertido",
cancelled: "Cancelado",
closed: "Encerrado",
draft: "Rascunho",
published: "Publicado",
archived: "Arquivado",
received: 'Recebido',
submitted: 'Submetido',
in_review: 'Em análise',
contacted: 'Contactado',
reviewed: 'Revisto',
qualification: 'Em qualificação',
qualified: 'Qualificado',
contact_accepted: 'Contacto aceite',
referred: 'Encaminhado',
due_diligence: 'Diligência devida',
negotiation: 'Em negociação',
pending: 'Pendente',
refused: 'Recusado',
converted: 'Convertido',
cancelled: 'Cancelado',
closed: 'Encerrado',
draft: 'Rascunho',
published: 'Publicado',
archived: 'Arquivado',
};
export function Management({ title, children }: { title: string; children: ReactNode }) {
export function Management({
title,
children,
}: {
title: string;
children: ReactNode;
}) {
const { flash, educationEnabled, aiEnabled } = usePage<{
flash?: { success?: string };
educationEnabled?: boolean;
@@ -44,7 +51,10 @@ export function Management({ title, children }: { title: string; children: React
return (
<main className="space-y-6 p-4 md:p-8">
<Head title={title} />
<nav className="flex flex-wrap gap-4 text-sm underline" aria-label="Gestão do portal">
<nav
className="flex flex-wrap gap-4 text-sm underline"
aria-label="Gestão do portal"
>
<Link href="/management/interests">Pedidos de interesse</Link>
<Link href="/management/sectors">Sectores</Link>
<Link href="/management/opportunities">Oportunidades</Link>
@@ -53,25 +63,44 @@ export function Management({ title, children }: { title: string; children: React
<Link href="/management/crm/investors">Investidores</Link>
<Link href="/management/projects">Projectos</Link>
<Link href="/management/clusters">Clusters</Link>
<Link href="/management/relationship-repair">Revisão das associações documentadas</Link>
<Link href="/management/partnerships-install">Aplicação da Bolsa de Parcerias</Link>
<Link href="/management/relationship-repair">
Revisão das associações documentadas
</Link>
<Link href="/management/partnerships-install">
Aplicação da Bolsa de Parcerias
</Link>
<Link href="/management/corridors">Corredores</Link>
<Link href="/management/territory-associations">
Localizações dos investimentos
</Link>
<Link href="/management/investment/zones">ZEE, ZFI e parques</Link>
<Link href="/management/investment/zones">
ZEE, ZFI e parques
</Link>
{educationEnabled && (
<Link href="/management/education">Competências e formação</Link>
<Link href="/management/education">
Competências e formação
</Link>
)}
{aiEnabled && <Link href="/management/ai">Assistência e fontes</Link>}
<Link href="/management/portfolio">Corredores e matriz de investimento</Link>
<Link href="/management/portal-services">Documentos e parcerias</Link>
<Link href="/management/investment/references">Referências e formulários</Link>
{aiEnabled && (
<Link href="/management/ai">Assistência e fontes</Link>
)}
<Link href="/management/portfolio">
Corredores e matriz de investimento
</Link>
<Link href="/management/portal-services">
Documentos e parcerias
</Link>
<Link href="/management/investment/references">
Referências e formulários
</Link>
<a href="/">Portal público</a>
</nav>
<h1 className="text-2xl font-semibold break-words">{title}</h1>
{flash?.success && (
<p role="status" className="rounded border border-emerald-600 p-3">
<p
role="status"
className="rounded border border-emerald-600 p-3"
>
{flash.success}
</p>
)}
@@ -82,14 +111,18 @@ export function Management({ title, children }: { title: string; children: React
export function Pagination<T>({ page }: { page: Paginated<T> }) {
return (
<nav aria-label="Paginação" className="flex flex-wrap items-center gap-4">
<nav
aria-label="Paginação"
className="flex flex-wrap items-center gap-4"
>
{page.prev_page_url && (
<Link className={button} href={page.prev_page_url}>
Anterior
</Link>
)}
<span>
{page.total} registos · Página {page.current_page} de {page.last_page}
{page.total} registos · Página {page.current_page} de{' '}
{page.last_page}
</span>
{page.next_page_url && (
<Link className={button} href={page.next_page_url}>
@@ -116,18 +149,22 @@ export function Field({
{label}
</span>
{isValidElement<{
"aria-labelledby"?: string;
"aria-describedby"?: string;
"aria-invalid"?: boolean;
'aria-labelledby'?: string;
'aria-describedby'?: string;
'aria-invalid'?: boolean;
}>(children)
? cloneElement(children, {
"aria-labelledby": id,
"aria-describedby": error ? `${id}-error` : undefined,
"aria-invalid": Boolean(error),
'aria-labelledby': id,
'aria-describedby': error ? `${id}-error` : undefined,
'aria-invalid': Boolean(error),
})
: children}
{error && (
<span id={`${id}-error`} role="alert" className="block text-sm text-red-600">
<span
id={`${id}-error`}
role="alert"
className="block text-sm text-red-600"
>
{error}
</span>
)}
@@ -1,32 +1,44 @@
import { useEffect, useState } from "react";
import InvestmentTerritory from "@/components/investment-territory";
import { Management, Field, control } from "./shared";
import { useEffect, useState } from 'react';
import InvestmentTerritory from '@/components/investment-territory';
import { Management, Field, control } from './shared';
export default function TerritoryAssociations() {
const [kind, setKind] = useState("projects");
const [id, setId] = useState("");
const [q, setQ] = useState("");
const [kind, setKind] = useState('projects');
const [id, setId] = useState('');
const [q, setQ] = useState('');
const [page, setPage] = useState(1);
const [rows, setRows] = useState<{ id: string; name: string }[]>([]);
const [more, setMore] = useState(false);
const [error, setError] = useState("");
const [error, setError] = useState('');
useEffect(() => {
const controller = new AbortController();
const timer = setTimeout(async () => {
try {
const params = new URLSearchParams({ kind, q, page: String(page) });
const response = await fetch(`/management/territory-subjects?${params}`, {
signal: controller.signal,
headers: { Accept: "application/json" },
const params = new URLSearchParams({
kind,
q,
page: String(page),
});
if (!response.ok) throw new Error("Não foi possível carregar os investimentos.");
const response = await fetch(
`/management/territory-subjects?${params}`,
{
signal: controller.signal,
headers: { Accept: 'application/json' },
},
);
if (!response.ok)
throw new Error(
'Não foi possível carregar os investimentos.',
);
const data = await response.json();
setRows(data.data);
setMore(Boolean(data.next_page_url));
setError("");
setError('');
} catch (e) {
if (!controller.signal.aborted)
setError(e instanceof Error ? e.message : "Erro de ligação.");
setError(
e instanceof Error ? e.message : 'Erro de ligação.',
);
}
}, 250);
return () => {
@@ -42,16 +54,20 @@ export default function TerritoryAssociations() {
value={kind}
onChange={(e) => {
setKind(e.target.value);
setId("");
setId('');
setRows([]);
setQ("");
setQ('');
setPage(1);
}}
>
<option value="projects">Projectos / projectos âncora</option>
<option value="projects">
Projectos / projectos âncora
</option>
<option value="clusters">Clusters</option>
<option value="corridors">Corredores</option>
<option value="zones">ZEE / ZFI / parques industriais</option>
<option value="zones">
ZEE / ZFI / parques industriais
</option>
<option value="opportunities">Oportunidades</option>
</select>
</Field>
@@ -62,12 +78,16 @@ export default function TerritoryAssociations() {
onChange={(e) => {
setQ(e.target.value);
setPage(1);
setId("");
setId('');
}}
/>
</Field>
<Field label="Investimento">
<select className={control} value={id} onChange={(e) => setId(e.target.value)}>
<select
className={control}
value={id}
onChange={(e) => setId(e.target.value)}
>
<option value="">Seleccione</option>
{rows.map((row) => (
<option value={row.id} key={row.id}>
@@ -77,13 +97,15 @@ export default function TerritoryAssociations() {
</select>
</Field>
{error && <p role="alert">{error}</p>}
{!error && rows.length === 0 && <p>Sem registos para esta pesquisa.</p>}
{!error && rows.length === 0 && (
<p>Sem registos para esta pesquisa.</p>
)}
<div className="flex gap-4">
{page > 1 && (
<button
type="button"
onClick={() => {
setId("");
setId('');
setPage(page - 1);
}}
>
@@ -94,7 +116,7 @@ export default function TerritoryAssociations() {
<button
type="button"
onClick={() => {
setId("");
setId('');
setPage(page + 1);
}}
>
@@ -102,7 +124,13 @@ export default function TerritoryAssociations() {
</button>
)}
</div>
{id && <InvestmentTerritory key={`${kind}-${id}`} kind={kind} id={id} />}
{id && (
<InvestmentTerritory
key={`${kind}-${id}`}
kind={kind}
id={id}
/>
)}
</Management>
);
}