@@ -1,8 +1,11 @@
|
||||
import ProfileNavigation from '@/components/profile-navigation';
|
||||
import { Head, Link } from '@inertiajs/react';
|
||||
import { dashboard } from '@/routes';
|
||||
import type { InvestmentContext } from '@/pages/investor-path/index';
|
||||
import type { OpportunityManagementAccess } from '@/types/opportunity-management';
|
||||
|
||||
type Summary = {
|
||||
canCreateOpportunity?: boolean;
|
||||
requestsByStatus: Record<string, number>;
|
||||
publishedOpportunities: number;
|
||||
draftOpportunities: number;
|
||||
@@ -27,8 +30,10 @@ const card =
|
||||
export default function Dashboard({
|
||||
summary,
|
||||
investorPath,
|
||||
opportunityManagement,
|
||||
}: {
|
||||
summary: Summary | null;
|
||||
opportunityManagement?: OpportunityManagementAccess | null;
|
||||
investorPath?: {
|
||||
contexts: InvestmentContext[];
|
||||
current: {
|
||||
@@ -45,8 +50,53 @@ export default function Dashboard({
|
||||
<main className="space-y-8 p-4 md:p-8">
|
||||
<Head title="Painel" />
|
||||
<h1 className="text-2xl font-semibold">Painel do portal</h1>
|
||||
<ProfileNavigation />
|
||||
{summary ? (
|
||||
<>
|
||||
{opportunityManagement && (
|
||||
<section
|
||||
aria-label="Gestão de Oportunidades"
|
||||
className="space-y-4 rounded-xl border p-5"
|
||||
>
|
||||
<h2 className="text-lg font-semibold">
|
||||
Gestão de Oportunidades
|
||||
</h2>
|
||||
<nav
|
||||
aria-label="Ações de oportunidades"
|
||||
className="flex flex-wrap gap-3"
|
||||
>
|
||||
<Link
|
||||
className="rounded-lg border px-4 py-2 underline"
|
||||
href={opportunityManagement.manage.href}
|
||||
>
|
||||
{opportunityManagement.manage.label}
|
||||
</Link>
|
||||
{opportunityManagement.installed ? (
|
||||
<Link
|
||||
className="bg-primary text-primary-foreground rounded-lg px-4 py-2"
|
||||
href={opportunityManagement.create.href}
|
||||
>
|
||||
{opportunityManagement.create.label}
|
||||
</Link>
|
||||
) : (
|
||||
<Link
|
||||
className="underline"
|
||||
href={
|
||||
opportunityManagement.installationHref
|
||||
}
|
||||
>
|
||||
Preparar instalação da gestão de
|
||||
rascunhos
|
||||
</Link>
|
||||
)}
|
||||
</nav>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Os rascunhos de oportunidades não publicam o
|
||||
dossier privado do investidor. Publicação exige
|
||||
uma ação própria.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
<section className="space-y-4">
|
||||
<h2 className="text-lg font-semibold">
|
||||
Manifestações de interesse
|
||||
@@ -71,7 +121,9 @@ export default function Dashboard({
|
||||
<section className="space-y-4">
|
||||
<h2 className="text-lg font-semibold">
|
||||
<Link href="/management/opportunities">
|
||||
Gestão de Oportunidades
|
||||
{opportunityManagement
|
||||
? 'Indicadores de oportunidades'
|
||||
: 'Gestão de Oportunidades'}
|
||||
</Link>
|
||||
</h2>
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
@@ -163,12 +215,13 @@ export default function Dashboard({
|
||||
aria-label="Acções rápidas"
|
||||
className="flex flex-wrap gap-4"
|
||||
>
|
||||
<Link
|
||||
{summary.canCreateOpportunity !== false && <Link
|
||||
className="underline"
|
||||
href="/management/opportunities/create"
|
||||
>
|
||||
Criar oportunidade
|
||||
</Link>
|
||||
{opportunityManagement?.create.label ??
|
||||
'Criar oportunidade'}
|
||||
</Link>}
|
||||
<Link
|
||||
className="underline"
|
||||
href="/management/sectors/create"
|
||||
|
||||
@@ -16,6 +16,10 @@ type Entry = {
|
||||
opportunity_category: string | null;
|
||||
updated_at: string;
|
||||
deleted_at: string | null;
|
||||
can_edit?: boolean;
|
||||
working_status?: string;
|
||||
draft_title?: string;
|
||||
publication?: { scope: string; label: string; public_catalog: boolean };
|
||||
};
|
||||
export default function Opportunities({
|
||||
records,
|
||||
@@ -24,10 +28,13 @@ export default function Opportunities({
|
||||
categories,
|
||||
sectors,
|
||||
geographyReviewCount,
|
||||
basePath = '/management/opportunities',
|
||||
canCreate = true,
|
||||
}: {
|
||||
records: Paginated<Entry>;
|
||||
filters: {
|
||||
q?: string;
|
||||
queue?: string;
|
||||
status?: string;
|
||||
category?: string;
|
||||
deleted?: boolean;
|
||||
@@ -38,9 +45,12 @@ export default function Opportunities({
|
||||
categories: string[];
|
||||
sectors: { id: number; name: string }[];
|
||||
geographyReviewCount: number;
|
||||
basePath?: string;
|
||||
canCreate?: boolean;
|
||||
}) {
|
||||
const form = useForm({
|
||||
q: filters.q ?? '',
|
||||
queue: filters.queue ?? '',
|
||||
status: filters.status ?? '',
|
||||
category: filters.category ?? '',
|
||||
deleted: Boolean(filters.deleted),
|
||||
@@ -48,10 +58,18 @@ export default function Opportunities({
|
||||
geography_scope: filters.geography_scope ?? '',
|
||||
});
|
||||
return (
|
||||
<Management title="Gestão de Oportunidades">
|
||||
<Link className={button} href="/management/opportunities/create">
|
||||
Nova oportunidade
|
||||
</Link>
|
||||
<Management
|
||||
title={
|
||||
basePath === '/minhas-oportunidades'
|
||||
? 'Minhas oportunidades'
|
||||
: 'Gestão de Oportunidades'
|
||||
}
|
||||
>
|
||||
{canCreate && (
|
||||
<Link className={button} href={`${basePath}/create`}>
|
||||
Nova oportunidade
|
||||
</Link>
|
||||
)}
|
||||
<p>
|
||||
{geographyReviewCount} registos com âmbito por indicar;
|
||||
referências existentes permanecem aceites.
|
||||
@@ -72,7 +90,7 @@ export default function Opportunities({
|
||||
<Link
|
||||
className="rounded border p-3"
|
||||
key={s}
|
||||
href={`/management/opportunities?status=${s}`}
|
||||
href={`${basePath}?status=${s}`}
|
||||
>
|
||||
{states[s] ?? s}: {counts[s] ?? 0}
|
||||
</Link>
|
||||
@@ -82,9 +100,31 @@ export default function Opportunities({
|
||||
className="flex flex-wrap gap-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.get('/management/opportunities');
|
||||
form.get(basePath);
|
||||
}}
|
||||
>
|
||||
{basePath === '/minhas-oportunidades' && (
|
||||
<label>
|
||||
Fila
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.queue}
|
||||
onChange={(e) =>
|
||||
form.setData('queue', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Todas as autorizadas</option>
|
||||
<option value="assigned">Atribuídas a mim</option>
|
||||
<option value="review">
|
||||
Validação e pareceres
|
||||
</option>
|
||||
<option value="publication">
|
||||
Preparação editorial
|
||||
</option>
|
||||
<option value="appeal">Recursos pendentes</option>
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<input
|
||||
aria-label="Pesquisa global"
|
||||
placeholder="Título ou referência"
|
||||
@@ -166,7 +206,7 @@ export default function Opportunities({
|
||||
{records.data.map((r) => (
|
||||
<article key={r.id} className="rounded border p-4">
|
||||
<h2 className="font-semibold">
|
||||
{r.title ?? 'Rascunho sem título'}
|
||||
{r.draft_title ?? r.title ?? 'Rascunho sem título'}
|
||||
</h2>
|
||||
<p>
|
||||
ID {r.id} · {r.reference} ·{' '}
|
||||
@@ -174,24 +214,25 @@ export default function Opportunities({
|
||||
·{' '}
|
||||
{r.deleted_at
|
||||
? 'Eliminado logicamente'
|
||||
: (states[r.status] ?? r.status)}
|
||||
: (r.working_status ?? r.status) === 'published'
|
||||
? 'Versão disponibilizada'
|
||||
: (states[r.working_status ?? r.status] ??
|
||||
r.working_status ??
|
||||
r.status)}
|
||||
</p>
|
||||
{r.publication && <p>{r.publication.label}</p>}
|
||||
<p>Atualizado: {r.updated_at}</p>
|
||||
<div className="flex flex-wrap gap-4">
|
||||
<Link
|
||||
href={`/management/opportunities/${r.id}/view`}
|
||||
>
|
||||
Ver
|
||||
</Link>
|
||||
<Link
|
||||
href={`/management/opportunities/${r.id}/edit`}
|
||||
>
|
||||
{r.deleted_at || r.status === 'archived'
|
||||
? 'Restaurar'
|
||||
: r.status === 'draft'
|
||||
? 'Continuar preenchimento'
|
||||
: 'Editar nova versão'}
|
||||
</Link>
|
||||
<Link href={`${basePath}/${r.id}/view`}>Ver</Link>
|
||||
{r.can_edit !== false && (
|
||||
<Link href={`${basePath}/${r.id}/edit`}>
|
||||
{r.deleted_at || r.status === 'archived'
|
||||
? 'Restaurar'
|
||||
: r.status === 'draft'
|
||||
? 'Continuar preenchimento'
|
||||
: 'Editar nova versão'}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import OpportunityProfileActions from '@/components/opportunity-profile-actions';
|
||||
import OpportunityCanonicalFields, {
|
||||
type CanonicalOptions,
|
||||
} from '@/components/opportunity-canonical-fields';
|
||||
import { Link, router, usePage } 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';
|
||||
type Values = Record<string, string | number | null>;
|
||||
import { Management, Field, button, control, states } from './shared';
|
||||
type Values = Record<string, unknown>;
|
||||
type Entry = {
|
||||
id: number;
|
||||
reference: string;
|
||||
@@ -51,8 +55,74 @@ export default function OpportunityDraft({
|
||||
occurred_at: string;
|
||||
}[];
|
||||
}) {
|
||||
const {
|
||||
basePath = '/management/opportunities',
|
||||
profileMode = false,
|
||||
profileOrganization,
|
||||
profileContext,
|
||||
profileAccess,
|
||||
profileActions = [],
|
||||
canonicalOptions,
|
||||
workflowState,
|
||||
workflowTasks = [],
|
||||
workflowParticipants,
|
||||
publicationPreview,
|
||||
publicationState,
|
||||
auth,
|
||||
canEditDraft = false,
|
||||
} = usePage<{
|
||||
basePath?: string;
|
||||
profileMode?: boolean;
|
||||
profileOrganization?: string | null;
|
||||
profileActions?: string[];
|
||||
profileContext?: Record<string, unknown> | null;
|
||||
profileAccess?: {
|
||||
contexts: { organization_id: string | null; type: string }[];
|
||||
} | null;
|
||||
publicationPreview?: {
|
||||
title: string;
|
||||
summary: string;
|
||||
description: string;
|
||||
};
|
||||
workflowParticipants?: {
|
||||
publishers: { id: number; name: string }[];
|
||||
validators: {
|
||||
id: number;
|
||||
name: string;
|
||||
technical: boolean;
|
||||
legal: boolean;
|
||||
}[];
|
||||
};
|
||||
canonicalOptions?: CanonicalOptions;
|
||||
workflowState?: string;
|
||||
publicationState?: {
|
||||
scope: string;
|
||||
label: string;
|
||||
public_catalog: boolean;
|
||||
};
|
||||
workflowTasks?: {
|
||||
id: string;
|
||||
title: string;
|
||||
status: string;
|
||||
assignee_user_id: number | null;
|
||||
due_at: string | null;
|
||||
}[];
|
||||
auth: { user: { id: number } };
|
||||
canEditDraft?: boolean;
|
||||
}>().props;
|
||||
const [data, setData] = useState<Values>({
|
||||
...values,
|
||||
...(profileMode
|
||||
? {
|
||||
organization_id: record
|
||||
? (profileOrganization ?? null)
|
||||
: (profileAccess?.contexts[0]?.organization_id ?? null),
|
||||
opportunity_category:
|
||||
values.opportunity_category ??
|
||||
profileAccess?.contexts[0]?.type ??
|
||||
'',
|
||||
}
|
||||
: {}),
|
||||
creation_key: crypto.randomUUID(),
|
||||
});
|
||||
const [busy, setBusy] = useState(false),
|
||||
@@ -66,9 +136,10 @@ export default function OpportunityDraft({
|
||||
const unavailable = Boolean(
|
||||
record?.deleted_at || record?.status === 'archived',
|
||||
);
|
||||
const archiveAvailable = Boolean(usePage().props.opportunityManagement);
|
||||
const set = (key: string, value: string) =>
|
||||
setData((d) => ({ ...d, [key]: value }));
|
||||
async function send(action: 'save' | 'delete' | 'restore') {
|
||||
async function send(action: 'save' | 'delete' | 'archive' | 'restore') {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
setErrors({});
|
||||
@@ -80,9 +151,9 @@ export default function OpportunityDraft({
|
||||
const url =
|
||||
action === 'save'
|
||||
? record
|
||||
? `/management/opportunities/${record.id}/draft`
|
||||
: '/management/opportunities/drafts'
|
||||
: `/management/opportunities/${record!.id}/lifecycle`;
|
||||
? `${basePath}/${record.id}/draft`
|
||||
: `${basePath}/drafts`
|
||||
: `${basePath}/${record!.id}/lifecycle`;
|
||||
const response = await fetch(url, {
|
||||
method: action === 'save' && record ? 'PUT' : 'POST',
|
||||
headers: {
|
||||
@@ -116,8 +187,7 @@ export default function OpportunityDraft({
|
||||
}
|
||||
setMessage(result.message);
|
||||
if (result.etag) setToken(result.etag);
|
||||
if (!record)
|
||||
router.visit(`/management/opportunities/${result.id}/edit`);
|
||||
if (!record) router.visit(`${basePath}/${result.id}/edit`);
|
||||
else if (action !== 'save') router.reload();
|
||||
} catch {
|
||||
setMessage(
|
||||
@@ -138,7 +208,61 @@ export default function OpportunityDraft({
|
||||
: 'Nova oportunidade'
|
||||
}
|
||||
>
|
||||
<Link href="/management/opportunities">Voltar à gestão</Link>
|
||||
<Link href={basePath}>
|
||||
{profileMode ? 'Minhas oportunidades' : 'Voltar à gestão'}
|
||||
</Link>
|
||||
{profileMode && record && readOnly && canEditDraft && (
|
||||
<Link
|
||||
className="block underline"
|
||||
href={`${basePath}/${record.id}/edit`}
|
||||
>
|
||||
Editar proposta privada
|
||||
</Link>
|
||||
)}
|
||||
{profileMode && !record && (
|
||||
<label className="block">
|
||||
Organização e tipo autorizados
|
||||
<select
|
||||
className={control}
|
||||
value={`${String(data.organization_id ?? '')}|${String(data.opportunity_category ?? '')}`}
|
||||
onChange={(e) => {
|
||||
const [organization, type] =
|
||||
e.target.value.split('|');
|
||||
setData((d) => ({
|
||||
...d,
|
||||
organization_id: organization || null,
|
||||
opportunity_category: type,
|
||||
}));
|
||||
}}
|
||||
>
|
||||
{(profileAccess?.contexts ?? []).map((c) => (
|
||||
<option
|
||||
key={`${c.organization_id}|${c.type}`}
|
||||
value={`${c.organization_id ?? ''}|${c.type}`}
|
||||
>
|
||||
{c.organization_id ?? 'Âmbito individual'} —{' '}
|
||||
{c.type}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{profileMode && record && (
|
||||
<p>
|
||||
Estado da preparação:{' '}
|
||||
{(workflowState ?? record.status) === 'published'
|
||||
? 'Versão disponibilizada'
|
||||
: (states[workflowState ?? record.status] ??
|
||||
workflowState ??
|
||||
record.status)}
|
||||
. {publicationState?.label}.{' '}
|
||||
{profileContext?.request_archive
|
||||
? 'Pedido de arquivo registado; aguarda decisão independente.'
|
||||
: ''}{' '}
|
||||
O Promotor solicita arquivo; não elimina nem restaura
|
||||
oportunidades.
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
Classificação de origem: {classification}. Esta classificação
|
||||
não cria associações territoriais.
|
||||
@@ -147,7 +271,8 @@ export default function OpportunityDraft({
|
||||
<p>
|
||||
Versão anterior fechada. As alterações são guardadas numa
|
||||
nova versão de rascunho; a ficha publicada permanece
|
||||
intacta. Este incremento não submete, aprova ou publica.
|
||||
intacta. Guardar não submete: use as ações do workflow para
|
||||
revisão, aprovação e publicação independentes.
|
||||
</p>
|
||||
)}
|
||||
<div
|
||||
@@ -163,7 +288,7 @@ export default function OpportunityDraft({
|
||||
<a
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
href={`/management/opportunities/${record?.id}/view`}
|
||||
href={`${basePath}/${record?.id}/view`}
|
||||
>
|
||||
Abrir versão atual
|
||||
</a>
|
||||
@@ -177,119 +302,153 @@ export default function OpportunityDraft({
|
||||
void send('save');
|
||||
}}
|
||||
>
|
||||
<fieldset
|
||||
disabled={busy || readOnly || unavailable}
|
||||
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
|
||||
projetos/clusters.
|
||||
</p>
|
||||
{(
|
||||
[
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
] as const
|
||||
).map((key, index) => (
|
||||
<TerritoryLevel
|
||||
key={`${key}-${path[index - 1]?.id ?? ''}`}
|
||||
index={index}
|
||||
parent={path[index - 1]?.id ?? ''}
|
||||
selected={path[index]}
|
||||
endpoint="/management/territory-options"
|
||||
fieldError={errors[key]}
|
||||
onChange={(value) => {
|
||||
const next = [
|
||||
...path.slice(0, index),
|
||||
...(value ? [value] : []),
|
||||
];
|
||||
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 ?? '',
|
||||
}));
|
||||
}}
|
||||
{!profileMode && (
|
||||
<fieldset
|
||||
disabled={busy || readOnly || unavailable}
|
||||
className="space-y-4"
|
||||
>
|
||||
<section aria-label="Localização registada">
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={path.at(-1)?.id}
|
||||
management
|
||||
endpoint={
|
||||
profileMode
|
||||
? '/minhas-oportunidades/territory-geometries'
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
<Field
|
||||
label="Categoria"
|
||||
error={errors.opportunity_category}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={String(data.opportunity_category ?? '')}
|
||||
onChange={(e) =>
|
||||
set('opportunity_category', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{categories.map((c) => (
|
||||
<option key={c}>{c}</option>
|
||||
<p>
|
||||
Hierarquia do cadastro territorial existente.
|
||||
Alterar esta seleção não cria relações com
|
||||
projetos/clusters.
|
||||
</p>
|
||||
{(
|
||||
[
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
] as const
|
||||
).map((key, index) => (
|
||||
<TerritoryLevel
|
||||
key={`${key}-${path[index - 1]?.id ?? ''}`}
|
||||
index={index}
|
||||
parent={path[index - 1]?.id ?? ''}
|
||||
selected={path[index]}
|
||||
endpoint={
|
||||
profileMode
|
||||
? '/minhas-oportunidades/territory-options'
|
||||
: '/management/territory-options'
|
||||
}
|
||||
fieldError={errors[key]}
|
||||
onChange={(value) => {
|
||||
const next = [
|
||||
...path.slice(0, index),
|
||||
...(value ? [value] : []),
|
||||
];
|
||||
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 ?? '',
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
{Object.entries({
|
||||
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' ? (
|
||||
<textarea
|
||||
className={control}
|
||||
value={String(data[key] ?? '')}
|
||||
onChange={(e) => set(key, e.target.value)}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
className={control}
|
||||
value={String(data[key] ?? '')}
|
||||
onChange={(e) => set(key, e.target.value)}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
<Field
|
||||
label="Categoria"
|
||||
error={errors.opportunity_category}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={String(data.opportunity_category ?? '')}
|
||||
onChange={(e) =>
|
||||
set('opportunity_category', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{categories.map((c) => (
|
||||
<option key={c}>{c}</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
))}
|
||||
<Field label="Sector" error={errors.sector_id}>
|
||||
<select
|
||||
className={control}
|
||||
value={String(data.sector_id ?? '')}
|
||||
onChange={(e) => set('sector_id', e.target.value)}
|
||||
{Object.entries({
|
||||
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' ? (
|
||||
<textarea
|
||||
className={control}
|
||||
value={String(data[key] ?? '')}
|
||||
onChange={(e) =>
|
||||
set(key, e.target.value)
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
className={control}
|
||||
value={String(data[key] ?? '')}
|
||||
onChange={(e) =>
|
||||
set(key, e.target.value)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</Field>
|
||||
))}
|
||||
<Field label="Sector" error={errors.sector_id}>
|
||||
<select
|
||||
className={control}
|
||||
value={String(data.sector_id ?? '')}
|
||||
onChange={(e) =>
|
||||
set('sector_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{sectors.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field
|
||||
label="Tipo de promotor"
|
||||
error={errors.promoter_type}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{sectors.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field
|
||||
label="Tipo de promotor"
|
||||
error={errors.promoter_type}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={String(data.promoter_type ?? '')}
|
||||
onChange={(e) =>
|
||||
set('promoter_type', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{values.promoter_type &&
|
||||
![
|
||||
<select
|
||||
className={control}
|
||||
value={String(data.promoter_type ?? '')}
|
||||
onChange={(e) =>
|
||||
set('promoter_type', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{Boolean(values.promoter_type) &&
|
||||
![
|
||||
'public',
|
||||
'private',
|
||||
'ppp',
|
||||
'cooperative',
|
||||
'association',
|
||||
'community',
|
||||
'other',
|
||||
].includes(
|
||||
String(values.promoter_type),
|
||||
) && (
|
||||
<option
|
||||
value={String(values.promoter_type)}
|
||||
>
|
||||
{String(values.promoter_type)}{' '}
|
||||
(valor existente)
|
||||
</option>
|
||||
)}
|
||||
{[
|
||||
'public',
|
||||
'private',
|
||||
'ppp',
|
||||
@@ -297,174 +456,170 @@ export default function OpportunityDraft({
|
||||
'association',
|
||||
'community',
|
||||
'other',
|
||||
].includes(String(values.promoter_type)) && (
|
||||
<option
|
||||
value={String(values.promoter_type)}
|
||||
>
|
||||
{String(values.promoter_type)} (valor
|
||||
existente)
|
||||
</option>
|
||||
)}
|
||||
{[
|
||||
'public',
|
||||
'private',
|
||||
'ppp',
|
||||
'cooperative',
|
||||
'association',
|
||||
'community',
|
||||
'other',
|
||||
].map((c) => (
|
||||
<option key={c}>{c}</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field
|
||||
label="Etapa de maturidade"
|
||||
error={errors.maturity_stage ?? errors.maturity_level}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={
|
||||
data.maturity_catalogue_version ===
|
||||
maturityCatalogue.version
|
||||
? String(data.maturity_stage ?? '')
|
||||
: data.maturity_level
|
||||
? `legacy:${data.maturity_level}`
|
||||
: ''
|
||||
].map((c) => (
|
||||
<option key={c}>{c}</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field
|
||||
label="Etapa de maturidade"
|
||||
error={
|
||||
errors.maturity_stage ?? errors.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>
|
||||
{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>
|
||||
<select
|
||||
className={control}
|
||||
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>
|
||||
{Boolean(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>
|
||||
),
|
||||
)}
|
||||
{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"
|
||||
error={errors.financing_modality}
|
||||
>
|
||||
<input
|
||||
className={control}
|
||||
value={String(data.financing_modality ?? '')}
|
||||
onChange={(e) =>
|
||||
set('financing_modality', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label="Impacto esperado"
|
||||
error={errors.expected_impact}
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
value={String(data.expected_impact ?? '')}
|
||||
onChange={(e) =>
|
||||
set('expected_impact', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{(data.opportunity_category === 'investment_project' ||
|
||||
(!data.opportunity_category &&
|
||||
data.estimated_investment_amount != null)) && (
|
||||
<>
|
||||
<Field
|
||||
label="Investimento estimado"
|
||||
error={errors.estimated_investment_amount}
|
||||
>
|
||||
<input
|
||||
className={control}
|
||||
value={String(
|
||||
data.estimated_investment_amount ?? '',
|
||||
)}
|
||||
onChange={(e) =>
|
||||
set(
|
||||
'estimated_investment_amount',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label="Moeda"
|
||||
error={errors.estimated_investment_currency}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={String(
|
||||
data.estimated_investment_currency ??
|
||||
'',
|
||||
)}
|
||||
onChange={(e) =>
|
||||
set(
|
||||
'estimated_investment_currency',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{['MZN', 'USD', 'EUR', 'ZAR'].map((c) => (
|
||||
<option key={c}>{c}</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
</>
|
||||
)}
|
||||
{data.opportunity_category &&
|
||||
data.opportunity_category !== 'investment_project' && (
|
||||
</select>
|
||||
<p>
|
||||
O módulo especializado desta categoria permanece
|
||||
pendente. Pode guardar a identificação
|
||||
incompleta; não será submetida nem publicada.
|
||||
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"
|
||||
error={errors.financing_modality}
|
||||
>
|
||||
<input
|
||||
className={control}
|
||||
value={String(data.financing_modality ?? '')}
|
||||
onChange={(e) =>
|
||||
set('financing_modality', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label="Impacto esperado"
|
||||
error={errors.expected_impact}
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
value={String(data.expected_impact ?? '')}
|
||||
onChange={(e) =>
|
||||
set('expected_impact', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{(data.opportunity_category === 'investment_project' ||
|
||||
(!data.opportunity_category &&
|
||||
data.estimated_investment_amount != null)) && (
|
||||
<>
|
||||
<Field
|
||||
label="Investimento estimado"
|
||||
error={errors.estimated_investment_amount}
|
||||
>
|
||||
<input
|
||||
className={control}
|
||||
value={String(
|
||||
data.estimated_investment_amount ??
|
||||
'',
|
||||
)}
|
||||
onChange={(e) =>
|
||||
set(
|
||||
'estimated_investment_amount',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label="Moeda"
|
||||
error={errors.estimated_investment_currency}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={String(
|
||||
data.estimated_investment_currency ??
|
||||
'',
|
||||
)}
|
||||
onChange={(e) =>
|
||||
set(
|
||||
'estimated_investment_currency',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{['MZN', 'USD', 'EUR', 'ZAR'].map(
|
||||
(c) => (
|
||||
<option key={c}>{c}</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</Field>
|
||||
</>
|
||||
)}
|
||||
</fieldset>
|
||||
{Boolean(data.opportunity_category) &&
|
||||
data.opportunity_category !==
|
||||
'investment_project' && (
|
||||
<p>
|
||||
Guarde o rascunho incompleto e complete o
|
||||
contrato aplicável abaixo. Submissão e
|
||||
publicação exigem os documentos e as
|
||||
revisões desta categoria.
|
||||
</p>
|
||||
)}
|
||||
</fieldset>
|
||||
)}
|
||||
{!readOnly && (
|
||||
<>
|
||||
<Field
|
||||
@@ -484,7 +639,7 @@ export default function OpportunityDraft({
|
||||
Guardar rascunho
|
||||
</button>
|
||||
)}
|
||||
{record && (
|
||||
{record && !profileMode && (
|
||||
<>
|
||||
<label className="block">
|
||||
<input
|
||||
@@ -497,7 +652,7 @@ export default function OpportunityDraft({
|
||||
Confirmo a{' '}
|
||||
{unavailable
|
||||
? 'restauração'
|
||||
: 'exclusão lógica/arquivo'}
|
||||
: 'operação indicada, preservando o registo'}
|
||||
, preservando histórico e relações
|
||||
</label>
|
||||
<button
|
||||
@@ -506,16 +661,32 @@ export default function OpportunityDraft({
|
||||
disabled={busy || !confirm}
|
||||
onClick={() =>
|
||||
void send(
|
||||
unavailable ? 'restore' : 'delete',
|
||||
unavailable
|
||||
? 'restore'
|
||||
: archiveAvailable
|
||||
? 'archive'
|
||||
: 'delete',
|
||||
)
|
||||
}
|
||||
>
|
||||
{unavailable
|
||||
? 'Restaurar'
|
||||
: closedVersion
|
||||
: archiveAvailable || closedVersion
|
||||
? 'Arquivar'
|
||||
: 'Excluir rascunho'}
|
||||
</button>
|
||||
{archiveAvailable &&
|
||||
!unavailable &&
|
||||
!closedVersion && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy || !confirm}
|
||||
onClick={() => void send('delete')}
|
||||
>
|
||||
Excluir rascunho
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
@@ -525,7 +696,7 @@ export default function OpportunityDraft({
|
||||
<Link
|
||||
href={
|
||||
resourcesInstalled
|
||||
? `/management/opportunities/${record.id}/resources`
|
||||
? `${basePath}/${record.id}/resources`
|
||||
: '/management/opportunity-resources-install'
|
||||
}
|
||||
>
|
||||
@@ -534,11 +705,131 @@ export default function OpportunityDraft({
|
||||
: 'Plano de ativação de imagens, documentos e localizações'}
|
||||
</Link>
|
||||
)}
|
||||
{record && (
|
||||
<Link href={`/management/opportunities/${record.id}/context`}>
|
||||
{record && !profileMode && (
|
||||
<Link href={`${basePath}/${record.id}/context`}>
|
||||
Consultar projetos, clusters e relações existentes
|
||||
</Link>
|
||||
)}
|
||||
{profileMode && canonicalOptions && (
|
||||
<section>
|
||||
<OpportunityCanonicalFields
|
||||
value={
|
||||
(data.canonical ?? {}) as Record<string, unknown>
|
||||
}
|
||||
onChange={(v) =>
|
||||
setData((d) => ({ ...d, canonical: v }))
|
||||
}
|
||||
options={canonicalOptions}
|
||||
errors={errors}
|
||||
category={String(data.opportunity_category ?? '')}
|
||||
organization={
|
||||
(data.organization_id ?? null) as string | null
|
||||
}
|
||||
actorId={auth.user.id}
|
||||
sectors={sectors}
|
||||
disabled={busy || readOnly || unavailable}
|
||||
/>
|
||||
{!readOnly && !unavailable && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() => void send('save')}
|
||||
>
|
||||
Guardar contrato no rascunho
|
||||
</button>
|
||||
)}
|
||||
{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>
|
||||
<p>
|
||||
Âmbito solicitado:{' '}
|
||||
{(data.canonical as Record<string, unknown> | undefined)
|
||||
?.visibility === 'public'
|
||||
? 'Catálogo público, após ação do Publicador'
|
||||
: 'Acesso restrito aos perfis e à organização autorizados'}
|
||||
</p>
|
||||
<h3>{publicationPreview?.title}</h3>
|
||||
<p>{publicationPreview?.summary}</p>
|
||||
<p>{publicationPreview?.description}</p>
|
||||
<p>
|
||||
A ficha partilha apenas título, resumo, proposta, sector
|
||||
e território. Contactos, avaliações, evidências e
|
||||
originais conservam o acesso restrito.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
{profileMode && record && etag && (
|
||||
<OpportunityProfileActions
|
||||
participants={workflowParticipants?.validators}
|
||||
publishers={workflowParticipants?.publishers}
|
||||
opinions={Object.values(
|
||||
(profileContext?.opinions ?? {}) as Record<
|
||||
string,
|
||||
{
|
||||
id: string;
|
||||
gate: string;
|
||||
recipient_id: number;
|
||||
status: string;
|
||||
}
|
||||
>,
|
||||
)}
|
||||
onErrors={setErrors}
|
||||
id={record.id}
|
||||
etag={token ?? etag}
|
||||
actions={profileActions}
|
||||
publicationVisibility={String(
|
||||
(data.canonical as Record<string, unknown> | undefined)
|
||||
?.visibility ?? 'internal',
|
||||
)}
|
||||
gates={canonicalOptions?.gates ?? []}
|
||||
documents={(
|
||||
canonicalOptions?.resources.documents ?? []
|
||||
).map((d) => ({
|
||||
id: d.id,
|
||||
title: d.payload.title ?? d.file?.file_name ?? d.id,
|
||||
}))}
|
||||
approvalHash={
|
||||
(
|
||||
profileContext?.approval as
|
||||
| { hash?: string }
|
||||
| undefined
|
||||
)?.hash
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{profileMode && record && (
|
||||
<section className="space-y-2 rounded border p-3">
|
||||
<h2>
|
||||
Acompanhamento interno —{' '}
|
||||
{(workflowState ?? record.status) === 'published'
|
||||
? 'Versão disponibilizada'
|
||||
: (states[workflowState ?? record.status] ??
|
||||
workflowState ??
|
||||
record.status)}
|
||||
</h2>
|
||||
<p>
|
||||
SLA: sem política/prazo aprovado; as tarefas podem ser
|
||||
preparadas em paralelo.
|
||||
</p>
|
||||
{workflowTasks.map((t) => (
|
||||
<p key={t.id}>
|
||||
{t.title} — {t.status}; responsável:{' '}
|
||||
{t.assignee_user_id ?? 'por atribuir'}; prazo:{' '}
|
||||
{t.due_at ?? 'não definido'}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
<section aria-label="Histórico de gestão">
|
||||
<h2>Histórico</h2>
|
||||
{history.length ? (
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { Link, router, usePage } from '@inertiajs/react';
|
||||
import TerritoryGeometryPreview from '@/components/territory-geometry-preview';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
@@ -144,9 +144,10 @@ export default function OpportunityResources({
|
||||
assessment: string[];
|
||||
imageProcessingAvailable: boolean;
|
||||
}) {
|
||||
const { basePath = '/management/opportunities', readOnly = false, countries = [] } = usePage<{basePath?: string; readOnly?: boolean; countries?: {code:string;name:string}[]}>().props;
|
||||
const [kind, setKind] = useState<Kind>('locations');
|
||||
const [editing, setEditing] = useState<Resource | null>(null);
|
||||
const [payload, setPayload] = useState<Payload>({});
|
||||
const [payload, setPayload] = useState<Payload>({country_code:'MZ'});
|
||||
const [path, setPath] = useState<TerritoryOption[]>([]);
|
||||
const [geometry, setGeometry] = useState('');
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
@@ -161,7 +162,7 @@ export default function OpportunityResources({
|
||||
function select(nextKind: Kind, record: Resource | null = null) {
|
||||
setKind(nextKind);
|
||||
setEditing(record);
|
||||
setPayload(record?.payload ?? {});
|
||||
setPayload(record?.payload ?? (nextKind === 'locations' ? {country_code:'MZ'} : {}));
|
||||
setPath(record?.territoryPath ?? []);
|
||||
setGeometry(
|
||||
record?.payload.geometry
|
||||
@@ -174,7 +175,7 @@ export default function OpportunityResources({
|
||||
setErrors({});
|
||||
}
|
||||
async function execute(action: 'save' | 'delete' | 'restore' | 'prepare') {
|
||||
if (busy) return;
|
||||
if (busy || readOnly) return;
|
||||
setBusy(true);
|
||||
setErrors({});
|
||||
setMessage('');
|
||||
@@ -204,7 +205,7 @@ export default function OpportunityResources({
|
||||
form.set('action', action);
|
||||
form.set('confirm', confirm ? '1' : '0');
|
||||
}
|
||||
const url = `/management/opportunities/${opportunity.id}/resources/${kind}${editing ? `/${editing.id}` : ''}${action === 'save' ? '' : action === 'prepare' ? '/prepare' : '/lifecycle'}`;
|
||||
const url = `${basePath}/${opportunity.id}/resources/${kind}${editing ? `/${editing.id}` : ''}${action === 'save' ? '' : action === 'prepare' ? '/prepare' : '/lifecycle'}`;
|
||||
const csrf =
|
||||
document.cookie
|
||||
.split('; ')
|
||||
@@ -266,7 +267,7 @@ export default function OpportunityResources({
|
||||
!!opportunity.deleted_at || opportunity.status === 'archived';
|
||||
return (
|
||||
<Management title="Imagens, documentos e localizações">
|
||||
<Link href={`/management/opportunities/${opportunity.id}/edit`}>
|
||||
<Link href={`${basePath}/${opportunity.id}/edit`}>
|
||||
Regressar ao rascunho #{opportunity.id}
|
||||
</Link>
|
||||
<p>
|
||||
@@ -327,7 +328,7 @@ export default function OpportunityResources({
|
||||
<button
|
||||
className={button}
|
||||
key={k}
|
||||
disabled={busy}
|
||||
disabled={busy || readOnly}
|
||||
onClick={() => select(k)}
|
||||
>
|
||||
{k === 'locations'
|
||||
@@ -388,7 +389,7 @@ export default function OpportunityResources({
|
||||
{r.file?.malware_scan_status === 'clean' &&
|
||||
!r.deleted_at && (
|
||||
<a
|
||||
href={`/management/opportunities/${opportunity.id}/resources/${kind}/${r.id}/download`}
|
||||
href={`${basePath}/${opportunity.id}/resources/${kind}/${r.id}/download`}
|
||||
>
|
||||
Consultar original autorizado
|
||||
</a>
|
||||
@@ -410,9 +411,12 @@ export default function OpportunityResources({
|
||||
</h2>
|
||||
{kind === 'locations' && (
|
||||
<div>
|
||||
<Field label="País da localização" error={errors.country_code}><select className={control} disabled={readOnly} value={String(payload.country_code ?? '')} onChange={e=>set('country_code',e.target.value)}><option value="">Por indicar</option>{countries.map(c=><option key={c.code} value={c.code}>{c.name}</option>)}</select></Field>
|
||||
{payload.country_code !== 'MZ' && <p>A hierarquia abaixo corresponde a Moçambique. Uma localização noutro país requer o seu próprio cadastro; não use territórios moçambicanos para a representar.</p>}
|
||||
<TerritoryGeometryPreview
|
||||
territoryId={path.at(-1)?.id}
|
||||
management
|
||||
endpoint={basePath === '/minhas-oportunidades' ? '/minhas-oportunidades/territory-geometries' : undefined}
|
||||
/>
|
||||
{[0, 1, 2, 3].map((index) => (
|
||||
<TerritoryLevel
|
||||
@@ -420,6 +424,7 @@ export default function OpportunityResources({
|
||||
index={index}
|
||||
parent={path[index - 1]?.id ?? ''}
|
||||
selected={path[index]}
|
||||
endpoint={basePath === '/minhas-oportunidades' ? '/minhas-oportunidades/territory-options' : '/management/territory-options'}
|
||||
onChange={(value) =>
|
||||
setPath((previous) =>
|
||||
value
|
||||
@@ -638,7 +643,7 @@ export default function OpportunityResources({
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={
|
||||
busy || unavailable || !imageProcessingAvailable
|
||||
busy || readOnly || unavailable || !imageProcessingAvailable
|
||||
}
|
||||
onClick={() => void execute('prepare')}
|
||||
>
|
||||
@@ -647,7 +652,7 @@ export default function OpportunityResources({
|
||||
)}
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || unavailable || !!editing?.deleted_at}
|
||||
disabled={busy || readOnly || unavailable || !!editing?.deleted_at}
|
||||
>
|
||||
Guardar recurso
|
||||
</button>
|
||||
@@ -655,7 +660,7 @@ export default function OpportunityResources({
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy || unavailable}
|
||||
disabled={busy || readOnly || unavailable}
|
||||
onClick={() =>
|
||||
void execute(
|
||||
editing.deleted_at ? 'restore' : 'delete',
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import ProfileNavigation from '@/components/profile-navigation';
|
||||
import { Head, Link, usePage } from '@inertiajs/react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { cloneElement, isValidElement, useId } from 'react';
|
||||
@@ -46,7 +47,9 @@ export function Management({
|
||||
title: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const { flash, educationEnabled, aiEnabled } = usePage<{
|
||||
const { flash, educationEnabled, aiEnabled, auth, basePath } = usePage<{
|
||||
auth?: {canManagePortal?: boolean};
|
||||
basePath?: string;
|
||||
flash?: { success?: string };
|
||||
educationEnabled?: boolean;
|
||||
aiEnabled?: boolean;
|
||||
@@ -54,7 +57,7 @@ export function Management({
|
||||
return (
|
||||
<main className="space-y-6 p-4 md:p-8">
|
||||
<Head title={title} />
|
||||
<nav
|
||||
{auth?.canManagePortal && basePath !== '/minhas-oportunidades' ? <nav
|
||||
className="flex flex-wrap gap-4 text-sm underline"
|
||||
aria-label="Gestão do portal"
|
||||
>
|
||||
@@ -102,7 +105,7 @@ export function Management({
|
||||
Referências e formulários
|
||||
</Link>
|
||||
<a href="/">Portal público</a>
|
||||
</nav>
|
||||
</nav> : <ProfileNavigation />}
|
||||
<h1 className="text-2xl font-semibold break-words">{title}</h1>
|
||||
{flash?.success && (
|
||||
<p
|
||||
|
||||
@@ -10,12 +10,14 @@ type Plan = {
|
||||
hash: string;
|
||||
scan_ready: boolean;
|
||||
source_sha256: string;
|
||||
correspondence_version: string;
|
||||
rows: {
|
||||
external_id: string;
|
||||
name: string;
|
||||
parent_name: string | null;
|
||||
location_id: string | null;
|
||||
status: string;
|
||||
correspondence: { target_name: string; target_source_code: string; basis: string } | null;
|
||||
}[];
|
||||
};
|
||||
export default function GeometryImport({ plan }: { plan: Plan }) {
|
||||
@@ -73,7 +75,8 @@ export default function GeometryImport({ plan }: { plan: Plan }) {
|
||||
<Management title="Importação cartográfica">
|
||||
<p>
|
||||
Exemplar INE de 07/06/2019 aceite. Correspondência exata de nome
|
||||
e pai; sem alterações de classificações territoriais,
|
||||
e pai, ou correspondência explícita fundamentada abaixo;
|
||||
sem alterações de classificações territoriais,
|
||||
disponibilidade fundiária ou cálculos.
|
||||
</p>
|
||||
<Field label="Nível">
|
||||
@@ -105,6 +108,12 @@ export default function GeometryImport({ plan }: { plan: Plan }) {
|
||||
<p className="break-all">
|
||||
SHA-256 do original: {plan.source_sha256}
|
||||
</p>
|
||||
<p>Versão das correspondências: {plan.correspondence_version}.</p>
|
||||
<button className={button} disabled={busy} onClick={() => {
|
||||
setApplyKey(crypto.randomUUID());
|
||||
setConfirmed(false);
|
||||
router.reload({ only: ["plan"] });
|
||||
}}>Atualizar pré-visualização</button>
|
||||
<div className="overflow-x-auto">
|
||||
<table>
|
||||
<thead>
|
||||
@@ -113,6 +122,7 @@ export default function GeometryImport({ plan }: { plan: Plan }) {
|
||||
<th>Nome</th>
|
||||
<th>Pai</th>
|
||||
<th>Correspondência</th>
|
||||
<th>Fundamento</th>
|
||||
<th>Ação prevista</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -123,6 +133,10 @@ export default function GeometryImport({ plan }: { plan: Plan }) {
|
||||
<td>{r.name}</td>
|
||||
<td>{r.parent_name ?? "—"}</td>
|
||||
<td>{r.location_id ?? "Pendente"}</td>
|
||||
<td>{r.correspondence ? <>
|
||||
{r.correspondence.target_name} (código {r.correspondence.target_source_code})
|
||||
<p>{r.correspondence.basis}</p>
|
||||
</> : "Nome único sob o pai correspondido"}</td>
|
||||
<td>{r.status}</td>
|
||||
</tr>
|
||||
))}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { Head, Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import ProfileNavigation from '@/components/profile-navigation';
|
||||
import { profileJson } from '@/lib/profile-json';
|
||||
import { button, control } from '@/pages/management/shared';
|
||||
|
||||
type Entry = {id: string; user_id: number; status: string; version: number; opportunity_types: string; document_ids: string; reason: string};
|
||||
type SecurityEntry = {id: string; kind: string; requested_by: number; subject_user_id: number; scope: string; reason: string; approved_by: number | null; consumed_at: string | null; expires_at: string};
|
||||
type Pair = {first_user_id: number; second_user_id: number; version: number};
|
||||
function Grant({types, organizations}: {types: string[]; organizations: {id: string; name: string}[]}) {
|
||||
const [user, setUser] = useState(''); const [role, setRole] = useState('validator'); const [organization, setOrganization] = useState('');
|
||||
const [selected, setSelected] = useState<string[]>([]); const [responsibilities, setResponsibilities] = useState<string[]>([]);
|
||||
const [reason, setReason] = useState(''); const [expires, setExpires] = useState(''); const [message, setMessage] = useState(''); const [busy, setBusy] = useState(false);
|
||||
const available = role === 'validator' ? ['validation_coordinator','technical_reviewer','legal_reviewer','appeal_reviewer'] : role === 'publisher' ? ['publication_coordinator'] : [];
|
||||
const toggle = (values: string[], value: string) => values.includes(value) ? values.filter(v => v !== value) : [...values,value];
|
||||
async function send() { setBusy(true); try { await profileJson('/perfis/atribuicoes', {user_id: Number(user), role, organization_id: organization || null, opportunity_types: selected, responsibilities, expires_at: expires || null, reason}); setMessage('Atribuição registada.'); router.reload(); } catch(error) {setMessage(error instanceof Error ? error.message : 'Resposta indisponível.');} finally {setBusy(false);} }
|
||||
return <section className="space-y-3"><h2 className="text-xl font-semibold">Atribuir papel operacional</h2><p>Promotor exige pedido documental independente. Superutilizador é gerido pela dupla, sem terceira atribuição.</p>
|
||||
<form className="max-w-2xl space-y-3" onSubmit={e => {e.preventDefault(); void send();}}>
|
||||
<label className="block">ID da conta existente<input className={control} type="number" min={1} required value={user} onChange={e => setUser(e.target.value)} /></label>
|
||||
<label className="block">Papel<select className={control} value={role} onChange={e => {setRole(e.target.value); setResponsibilities([]);}}>{['validator','publisher','auditor'].map(v => <option key={v}>{v}</option>)}</select></label>
|
||||
<label className="block">Âmbito organizacional<select className={control} value={organization} onChange={e => setOrganization(e.target.value)}><option value="">Todos os âmbitos para os tipos selecionados</option>{organizations.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}</select></label>
|
||||
<fieldset><legend>Tipos autorizados</legend>{types.map(v => <label className="block" key={v}><input type="checkbox" checked={selected.includes(v)} onChange={() => setSelected(toggle(selected,v))} /> {v}</label>)}</fieldset>
|
||||
<fieldset><legend>Responsabilidades adicionais</legend>{available.map(v => <label className="block" key={v}><input type="checkbox" checked={responsibilities.includes(v)} onChange={() => setResponsibilities(toggle(responsibilities,v))} /> {v}</label>)}<p>Atribuir a responsabilidade não conclui filas, recursos ou escalamentos ainda em desenvolvimento.</p></fieldset>
|
||||
<label className="block">Validade opcional<input className={control} type="datetime-local" value={expires} onChange={e => setExpires(e.target.value)} /></label>
|
||||
<label className="block">Fundamento<textarea required className={control} minLength={20} maxLength={1000} value={reason} onChange={e => setReason(e.target.value)} /></label>
|
||||
<button className={button} disabled={busy}>Atribuir com auditoria</button><p role="status">{message}</p>
|
||||
</form></section>;
|
||||
}
|
||||
function Security({pair, entries, actorId}: {pair: Pair; entries: SecurityEntry[]; actorId: number}) {
|
||||
const [old, setOld] = useState(String(pair.second_user_id)); const [candidate, setCandidate] = useState(''); const [reason, setReason] = useState('');
|
||||
const [action, setAction] = useState('edit'); const [record, setRecord] = useState(''); const [message, setMessage] = useState(''); const [busy, setBusy] = useState(false);
|
||||
async function send(path: string, data: object) {setBusy(true); try {const result = await profileJson(path, data); setMessage(result.message ?? `Pedido registado: ${result.id}`); router.reload();} catch(error) {setMessage(error instanceof Error ? error.message : 'Resposta indisponível.');} finally {setBusy(false);}}
|
||||
return <section className="space-y-3"><h2 className="text-xl font-semibold">Operações críticas</h2>
|
||||
<label className="block">Fundamento<textarea className={control} minLength={20} maxLength={1000} value={reason} onChange={e => setReason(e.target.value)} /></label>
|
||||
<form className="max-w-2xl space-y-3" onSubmit={e => {e.preventDefault(); void send('/perfis/substituicoes', {old_user_id: Number(old), new_user_id: Number(candidate), reason});}}>
|
||||
<label className="block">Titular a substituir<select className={control} value={old} onChange={e => setOld(e.target.value)}>{[pair.first_user_id,pair.second_user_id].map(v => <option key={v}>{v}</option>)}</select></label>
|
||||
<label className="block">ID do candidato com MFA confirmado<input className={control} type="number" min={1} required value={candidate} onChange={e => setCandidate(e.target.value)} /></label><button className={button} disabled={busy}>Preparar substituição atómica</button>
|
||||
</form>
|
||||
<form className="max-w-2xl space-y-3" onSubmit={e => {e.preventDefault(); void send('/perfis/elevacoes', {action, record_id: record ? Number(record) : null, reason});}}>
|
||||
<label className="block">Operação a elevar<select className={control} value={action} onChange={e => setAction(e.target.value)}>{['create','edit','validate','publish','archive'].map(v => <option key={v}>{v}</option>)}</select></label>
|
||||
<label className="block">ID da oportunidade<input className={control} type="number" min={1} required={action !== 'create'} value={record} onChange={e => setRecord(e.target.value)} /></label><button className={button} disabled={busy}>Pedir elevação temporária</button><p>Exige aprovação do outro titular e papel operacional válido. Não remove impedimentos de autoria ou Auditor.</p>
|
||||
</form>
|
||||
{entries.map(entry => <article key={entry.id} className="space-y-2 border p-3"><p>{entry.kind} — {entry.id} — solicitante {entry.requested_by}, destinatário {entry.subject_user_id}</p><p>{entry.reason}; validade: {entry.expires_at}</p><p>Âmbito: {entry.scope}</p>
|
||||
{!entry.consumed_at && !entry.approved_by && entry.requested_by !== actorId && entry.subject_user_id !== actorId && <button disabled={busy} className={button} onClick={() => void send(`/perfis/seguranca/${entry.id}/aprovar`, {})}>Aprovar independentemente</button>}
|
||||
{!entry.consumed_at && entry.approved_by && entry.requested_by === actorId && entry.kind === 'replacement' && <button disabled={busy} className={button} onClick={() => void send(`/perfis/substituicoes/${entry.id}/aplicar`, {})}>Aplicar substituição aprovada</button>}
|
||||
<p>{entry.consumed_at ? 'Aplicado' : entry.approved_by ? `Aprovado pela conta ${entry.approved_by}` : 'Aguarda aprovação independente'}</p>
|
||||
</article>)}<p role="status">{message}</p></section>;
|
||||
}
|
||||
function Decision({ entry }: {entry: Entry}) {
|
||||
const [reason, setReason] = useState(''); const [verified, setVerified] = useState(false); const [message, setMessage] = useState(''); const [busy, setBusy] = useState(false);
|
||||
const types: string[] = JSON.parse(entry.opportunity_types);
|
||||
const [approved, setApproved] = useState<string[]>([]);
|
||||
async function send(decision: string) {
|
||||
setBusy(true); try { await profileJson(`/perfis/pedidos/${entry.id}/decisao`, {version: entry.version, decision, reason, approved_types: approved,
|
||||
verified_identity: verified, verified_representation: verified, verified_documents: verified}); router.reload(); }
|
||||
catch(error) { setMessage(error instanceof Error ? error.message : 'Resposta indisponível.'); } finally { setBusy(false); }
|
||||
}
|
||||
return <article className="space-y-2 rounded border p-4"><h3>Pedido {entry.id} — conta {entry.user_id} — {entry.status}</h3><p>{entry.reason}</p><p>Comprovativos canónicos: {(JSON.parse(entry.document_ids) as string[]).map(id => <Link className="mr-3 underline" key={id} href={`/perfis/pedidos/${entry.id}/documentos/${id}`} target="_blank">Consultar {id}</Link>)}</p>
|
||||
{entry.status === 'pending' && <><fieldset><legend>Tipos efetivamente aprovados</legend>{types.map(type => <label className="block" key={type}><input type="checkbox" checked={approved.includes(type)} onChange={() => setApproved(v => v.includes(type) ? v.filter(x => x !== type) : [...v,type])} /> {type}</label>)}</fieldset>
|
||||
<label className="block"><input type="checkbox" checked={verified} onChange={e => setVerified(e.target.checked)} /> Conferi identidade, representação e comprovativos; esta declaração fica auditada.</label>
|
||||
<label className="block">Fundamento<textarea className={control} minLength={20} maxLength={1000} value={reason} onChange={e => setReason(e.target.value)} /></label>
|
||||
<button className={button} disabled={busy} onClick={() => void send('approved')}>Aprovar tipos selecionados</button> <button className={button} disabled={busy} onClick={() => void send('rejected')}>Rejeitar pedido</button></>}
|
||||
<p role="status">{message}</p></article>;
|
||||
}
|
||||
export default function Administration({requests, pair, assignments, securityAlerts, actorId, types, organizations, securityRequests}: {actorId: number; types: string[]; organizations: {id: string; name: string}[]; securityRequests: SecurityEntry[]; securityAlerts: {id: string; action: string; actor_user_id: number; occurred_at: string}[]; requests: Entry[]; pair: Pair; assignments: {id: string; user_id: number; role: string; revoked_at: string | null}[]}) {
|
||||
const [message, setMessage] = useState(''); const [reason, setReason] = useState('');
|
||||
async function revoke(id: string) { try { await profileJson(`/perfis/atribuicoes/${id}/revogar`, {reason}); router.reload(); } catch(error) { setMessage(error instanceof Error ? error.message : 'Resposta indisponível.'); } }
|
||||
return <main className="space-y-6 p-6"><Head title="Gestão de perfis" /><ProfileNavigation /><h1 className="text-2xl font-semibold">Gestão de perfis</h1>
|
||||
<p>Dupla de superutilizadores: contas {pair.first_user_id} e {pair.second_user_id}; versão {pair.version}. Substituição exige operação atómica e aprovação independente. Não há remoção isolada.</p>
|
||||
<section aria-label="Alertas de segurança"><h2 className="text-xl font-semibold">Alertas de segurança</h2>{securityAlerts.map(a => <p key={a.id}>{a.occurred_at}: {a.action} — conta {a.actor_user_id}</p>)}</section>
|
||||
<section><h2 className="text-xl font-semibold">Pedidos de Promotor</h2>{requests.map(r => <Decision key={r.id} entry={r} />)}</section>
|
||||
<Grant types={types} organizations={organizations} /><Security pair={pair} entries={securityRequests} actorId={actorId} />
|
||||
<section><h2 className="text-xl font-semibold">Atribuições e revogação</h2><label>Motivo de revogação<textarea className={control} minLength={20} maxLength={1000} value={reason} onChange={e => setReason(e.target.value)} /></label>
|
||||
{assignments.map(a => <p key={a.id}>Conta {a.user_id}: {a.role} — {a.revoked_at ? 'revogado' : 'atribuído'} {!a.revoked_at && <button className={button} onClick={() => void revoke(a.id)}>Revogar e invalidar sessões</button>}</p>)}<p role="status">{message}</p></section>
|
||||
</main>;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Head, useForm } from '@inertiajs/react';
|
||||
import ProfileNavigation from '@/components/profile-navigation';
|
||||
import { button, control, Pagination, type Paginated } from '@/pages/management/shared';
|
||||
|
||||
type Event = {id: string; action: string; actor_user_id: number | null; entity_type: string; source_system: string; occurred_at: string};
|
||||
export default function Audit({records, filters}: {records: Paginated<Event>; filters: Record<string,string>}) {
|
||||
const form = useForm({actor_id: filters.actor_id ?? '', action: filters.action ?? '', record_id: filters.record_id ?? '', from: filters.from ?? '', until: filters.until ?? ''});
|
||||
const search = new URLSearchParams(Object.entries(form.data).filter(([,value]) => value !== ''));
|
||||
search.set('format', 'json');
|
||||
return <main className="space-y-6 p-6"><Head title="Auditoria de acessos" /><ProfileNavigation /><h1 className="text-2xl font-semibold">Auditoria de acessos e decisões</h1>
|
||||
<p>Consulta somente de leitura. A exportação contém metadados; não inclui credenciais, documentos nem snapshots privados decifrados. Cada exportação apresenta o limite aplicado.</p>
|
||||
<form className="grid gap-3 sm:grid-cols-3" onSubmit={e => {e.preventDefault(); form.get('/perfis/auditoria');}}>
|
||||
{(['actor_id','action','record_id','from','until'] as const).map(field => <label key={field}>{field}<input className={control} type={field === 'from' || field === 'until' ? 'datetime-local' : 'text'} value={form.data[field]} onChange={e => form.setData(field,e.target.value)} /></label>)}
|
||||
<button className={button}>Filtrar</button>
|
||||
</form>
|
||||
{Object.values(form.errors).map(error => <p role="alert" key={error}>{error}</p>)}
|
||||
<a className="underline" href={`/perfis/auditoria?${search}`}>Exportar metadados JSON, até 1.000 eventos</a>
|
||||
<div className="overflow-auto"><table className="w-full"><thead><tr><th>Data UTC</th><th>Conta</th><th>Ação</th><th>Recurso</th><th>Origem</th></tr></thead><tbody>{records.data.map(e => <tr key={e.id}><td>{e.occurred_at}</td><td>{e.actor_user_id}</td><td>{e.action}</td><td>{e.entity_type}</td><td>{e.source_system}</td></tr>)}</tbody></table></div>
|
||||
{!records.data.length && <p>Nenhum evento corresponde aos filtros.</p>}<Pagination page={records} />
|
||||
</main>;
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
import { useState } from 'react';
|
||||
import { Management, button, control } from '@/pages/management/shared';
|
||||
import { profileJson } from '@/lib/profile-json';
|
||||
|
||||
type Plan = {
|
||||
installed: boolean;
|
||||
consistent: boolean;
|
||||
ready: boolean;
|
||||
target: { database: string; port: number };
|
||||
hash: string;
|
||||
dependencies: Record<string, boolean>;
|
||||
changes: string[];
|
||||
backupDate: string | null;
|
||||
rollback: string;
|
||||
bootstrap: {
|
||||
initialized: boolean;
|
||||
holders: number[];
|
||||
version: number | null;
|
||||
rule: string;
|
||||
};
|
||||
};
|
||||
export default function Installation(initial: Plan) {
|
||||
const [plan, setPlan] = useState(initial);
|
||||
const [reason, setReason] = useState('');
|
||||
const [confirmed, setConfirmed] = useState(false);
|
||||
const [first, setFirst] = useState('');
|
||||
const [second, setSecond] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
async function run(bootstrap = false) {
|
||||
setBusy(true);
|
||||
setMessage('');
|
||||
try {
|
||||
const result = await profileJson(
|
||||
'/management/profile-install' + (bootstrap ? '/bootstrap' : ''),
|
||||
{
|
||||
hash: plan.hash,
|
||||
confirm: confirmed,
|
||||
reason,
|
||||
idempotency_key: crypto.randomUUID(),
|
||||
...(bootstrap
|
||||
? {
|
||||
first_user_id: Number(first),
|
||||
second_user_id: Number(second),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
);
|
||||
setMessage(
|
||||
bootstrap
|
||||
? 'Dupla inicializada. Inicie uma nova sessão como um dos titulares designados; MFA permanece obrigatório.'
|
||||
: result.changed
|
||||
? 'Schema instalado. Perfis ainda não disponibilizados; nenhuma conta ou atribuição criada.'
|
||||
: 'Schema já instalado. Nenhuma reinstalação ou duplicação.',
|
||||
);
|
||||
if (!bootstrap)
|
||||
setPlan(
|
||||
(await profileJson(
|
||||
'/management/profile-install',
|
||||
{},
|
||||
'GET',
|
||||
)) as Plan,
|
||||
);
|
||||
setConfirmed(false);
|
||||
} catch (error) {
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Resposta indisponível; consulte o estado antes de repetir.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Management title="Instalação dos perfis — 040000">
|
||||
<p>
|
||||
Base {plan.target.database}:{plan.target.port} ·{' '}
|
||||
{plan.installed ? 'Schema instalado' : 'Schema por instalar'}
|
||||
</p>
|
||||
<p>
|
||||
Preparação:{' '}
|
||||
{plan.ready
|
||||
? 'Provas atuais verificadas'
|
||||
: 'Dependências ou provas por completar'}
|
||||
. Preparação não significa instalação ou disponibilização dos
|
||||
perfis.
|
||||
</p>
|
||||
{!plan.consistent && (
|
||||
<p role="alert">
|
||||
Ledger e schema divergem. Recuperar a consistência antes de
|
||||
instalar.
|
||||
</p>
|
||||
)}
|
||||
<ul>
|
||||
{Object.entries(plan.dependencies).map(([key, ok]) => (
|
||||
<li key={key}>
|
||||
{key}: {ok ? 'presente' : 'pendente'}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<ul>
|
||||
{plan.changes.map((c) => (
|
||||
<li key={c}>{c}</li>
|
||||
))}
|
||||
</ul>
|
||||
<p>Backup/restauro: {plan.backupDate ?? 'Prova atual pendente'}</p>
|
||||
<p>{plan.rollback}</p>
|
||||
<label className="block">
|
||||
Fundamento
|
||||
<textarea
|
||||
className={control}
|
||||
value={reason}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={confirmed}
|
||||
onChange={(e) => setConfirmed(e.target.checked)}
|
||||
/>{' '}
|
||||
Confirmo exclusivamente a ação indicada nesta base
|
||||
</label>
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
busy ||
|
||||
!confirmed ||
|
||||
!plan.ready ||
|
||||
plan.installed ||
|
||||
!plan.consistent ||
|
||||
reason.length < 20
|
||||
}
|
||||
onClick={() => void run()}
|
||||
>
|
||||
Instalar schema 040000
|
||||
</button>
|
||||
<section className="space-y-3 rounded border p-4">
|
||||
<h2>Inicialização separada dos dois superutilizadores</h2>
|
||||
<p>{plan.bootstrap.rule}</p>
|
||||
{plan.bootstrap.initialized ? (
|
||||
<p>
|
||||
Dupla já inicializada:{' '}
|
||||
{plan.bootstrap.holders.join(' e ')}; versão{' '}
|
||||
{plan.bootstrap.version}. Use a substituição atómica
|
||||
autorizada; não reinicialize.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<label className="block">
|
||||
ID da primeira conta explicitamente designada
|
||||
<input
|
||||
className={control}
|
||||
type="number"
|
||||
min={1}
|
||||
value={first}
|
||||
onChange={(e) => setFirst(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
ID da segunda conta explicitamente designada
|
||||
<input
|
||||
className={control}
|
||||
type="number"
|
||||
min={1}
|
||||
value={second}
|
||||
onChange={(e) => setSecond(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
busy ||
|
||||
!confirmed ||
|
||||
!plan.installed ||
|
||||
!first ||
|
||||
!second ||
|
||||
first === second ||
|
||||
reason.length < 20
|
||||
}
|
||||
onClick={() => void run(true)}
|
||||
>
|
||||
Inicializar apenas estas duas contas
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
<p role="status">{message}</p>
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Head, Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import ProfileNavigation from '@/components/profile-navigation';
|
||||
import { profileJson } from '@/lib/profile-json';
|
||||
import { button, control } from '@/pages/management/shared';
|
||||
|
||||
type RequestEntry = { id: string; status: string; reason: string; decision_reason: string | null; created_at: string };
|
||||
export default function RequestProfile({ requests, types, organizations, documents }: {
|
||||
requests: RequestEntry[]; types: string[]; organizations: {id: string; name: string}[]; documents: {id: string; file_name: string}[];
|
||||
}) {
|
||||
const [representation, setRepresentation] = useState('individual');
|
||||
const [organization, setOrganization] = useState('');
|
||||
const [selected, setSelected] = useState<string[]>([]);
|
||||
const [proofs, setProofs] = useState<string[]>([]);
|
||||
const [reason, setReason] = useState('');
|
||||
const [key, setKey] = useState(() => crypto.randomUUID());
|
||||
const [message, setMessage] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
async function send() {
|
||||
setBusy(true); setMessage('');
|
||||
try {
|
||||
const result = await profileJson('/perfil/promotor', { creation_key: key, representation_type: representation, organization_id: representation === 'individual' ? null : organization,
|
||||
opportunity_types: selected, document_ids: proofs, reason });
|
||||
setMessage(result.message); setKey(crypto.randomUUID()); router.reload();
|
||||
} catch (error) { setMessage(error instanceof Error ? error.message : 'Resposta indisponível. Confira o acompanhamento antes de repetir.'); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
const toggle = (values: string[], id: string) => values.includes(id) ? values.filter(v => v !== id) : [...values, id];
|
||||
return <main className="space-y-6 p-6"><Head title="Perfil de Promotor" /><ProfileNavigation />
|
||||
<h1 className="text-2xl font-semibold">Solicitar perfil de Promotor</h1>
|
||||
<p>A aprovação confirma identidade, representação e comprovativos. Só os tipos aprovados ficam disponíveis; o pedido não ativa o perfil.</p>
|
||||
<form className="max-w-2xl space-y-4" onSubmit={e => { e.preventDefault(); void send(); }}>
|
||||
<label className="block">Representação<select className={control} value={representation} onChange={e => setRepresentation(e.target.value)}>
|
||||
{['individual','company','public_entity','association','partner'].map(v => <option key={v}>{v}</option>)}
|
||||
</select></label>
|
||||
{representation !== 'individual' && <label className="block">Organização representada<select required className={control} value={organization} onChange={e => setOrganization(e.target.value)}>
|
||||
<option value="">Selecionar</option>{organizations.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}
|
||||
</select></label>}
|
||||
<fieldset><legend>Tipos pretendidos</legend>{types.map(type => <label key={type} className="block"><input type="checkbox" checked={selected.includes(type)} onChange={() => setSelected(toggle(selected,type))} /> {type}</label>)}</fieldset>
|
||||
<fieldset><legend>Comprovativos próprios analisados</legend>{documents.map(d => <label key={d.id} className="block"><input type="checkbox" checked={proofs.includes(d.id)} onChange={() => setProofs(toggle(proofs,d.id))} /> {d.file_name}</label>)}</fieldset>
|
||||
{!documents.length && <p>Sem comprovativos próprios disponíveis. Pode anexar ao seu dossier no <Link className="underline" href="/balcao-virtual/painel">Balcão</Link>; o ficheiro precisa de análise antimalware concluída.</p>}
|
||||
<label className="block">Fundamentação<textarea required minLength={20} maxLength={1000} className={control} value={reason} onChange={e => setReason(e.target.value)} /></label>
|
||||
<button disabled={busy} className={button}>Submeter pedido de perfil</button>
|
||||
</form>
|
||||
<p role="status" aria-live="polite">{message}</p>
|
||||
<section><h2 className="text-xl font-semibold">Acompanhamento dos meus pedidos</h2>{requests.map(r => <article key={r.id} className="border-b py-3"><p>{r.id} — {r.status}</p><p>{r.decision_reason ?? 'Aguarda revisão independente.'}</p></article>)}{!requests.length && <p>Nenhum pedido recebido.</p>}</section>
|
||||
</main>;
|
||||
}
|
||||
Reference in New Issue
Block a user