@@ -1,76 +1,694 @@
|
||||
import { Head, Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import ProfileNavigation from '@/components/profile-navigation';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
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>
|
||||
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 };
|
||||
type OperatorOrganization = { id: string; name: string; nuit: string; contact: string; director: string };
|
||||
|
||||
function OperatorOrganizationForm() {
|
||||
const [operationKey] = useState(createOperationKey);
|
||||
const [name, setName] = useState('Tempo Lda');
|
||||
const [nuit, setNuit] = useState('400993114');
|
||||
const [contact, setContact] = useState('+258868010880');
|
||||
const [director, setDirector] = useState('Osmane Nala');
|
||||
const [source, setSource] = useState('Dados e designação interna confirmados pelo responsável da Tempo em 11/10/2026.');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
async function save() {
|
||||
setBusy(true);
|
||||
try {
|
||||
const result = await profileJson('/perfis/organizacao-operadora', { operation_key: operationKey, name, nuit, contact, director, function: 'portal_owner_operator', source_reference: source });
|
||||
setMessage(result.message); router.reload();
|
||||
} catch (error) { setMessage(error instanceof Error ? error.message : 'Resposta indisponível.'); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
return <section className="space-y-3" aria-label="Organização operadora">
|
||||
<h2 className="text-xl font-semibold">Organização proprietária e operadora</h2>
|
||||
<p>Reutiliza o cadastro mestre e conserva o histórico. Estes dados não atribuem representação empresarial nem papéis às contas.</p>
|
||||
<form className="max-w-2xl space-y-3" onSubmit={e => { e.preventDefault(); void save(); }}>
|
||||
<label className="block">Denominação<input required className={control} value={name} onChange={e => setName(e.target.value)} /></label>
|
||||
<label className="block">NUIT<input required className={control} value={nuit} onChange={e => setNuit(e.target.value)} pattern="[0-9]{9}" /></label>
|
||||
<label className="block">Contacto<input required type="tel" className={control} value={contact} onChange={e => setContact(e.target.value)} /></label>
|
||||
<label className="block">Director Geral<input required className={control} value={director} onChange={e => setDirector(e.target.value)} /></label>
|
||||
<label className="block">Origem dos dados<textarea aria-label="Origem dos dados" required minLength={20} maxLength={1000} className={control} value={source} onChange={e => setSource(e.target.value)} /></label>
|
||||
<button className={button} disabled={busy}>Guardar organização operadora</button>
|
||||
<p role="status">{message}</p>
|
||||
</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>;
|
||||
</section>;
|
||||
}
|
||||
function Decision({ entry }: {entry: Entry}) {
|
||||
const [reason, setReason] = useState(''); const [verified, setVerified] = useState(false); const [message, setMessage] = useState(''); const [busy, setBusy] = useState(false);
|
||||
|
||||
function InternalStaffGrant({ types, organizations, operators }: { types: string[]; organizations: { id: string; name: string }[]; operators: OperatorOrganization[] }) {
|
||||
const [operationKey, setOperationKey] = useState(createOperationKey);
|
||||
const [subject, setSubject] = useState('');
|
||||
const [role, setRole] = useState('promoter');
|
||||
const [operator, setOperator] = useState('');
|
||||
const [scope, setScope] = useState('');
|
||||
const [selected, setSelected] = useState<string[]>([]);
|
||||
const [confirmed, setConfirmed] = useState(false);
|
||||
const [reason, setReason] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
async function save() {
|
||||
setBusy(true);
|
||||
try {
|
||||
await profileJson('/perfis/atribuicoes', { internal_designation: true, operation_key: operationKey,
|
||||
user_id: Number(subject), role, operator_organization_id: operator,
|
||||
organization_id: role === 'promoter' ? operator : scope || null,
|
||||
opportunity_types: selected, responsibilities: [], reason, confirmed_internal_designation: confirmed });
|
||||
setMessage('Designação interna atribuída e auditada.'); router.reload();
|
||||
} catch (error) { setMessage(error instanceof Error ? error.message : 'Resposta indisponível.'); }
|
||||
finally { setBusy(false); }
|
||||
}
|
||||
return <section className="space-y-3" aria-label="Designação interna">
|
||||
<h2 className="text-xl font-semibold">Atribuir função interna do portal</h2>
|
||||
<p>A proprietária define as funções da sua equipa. Esta atribuição não exige comprovativos de Promotor externo nem concede gestão empresarial. Cada oportunidade conserva o promotor real e a autorização de divulgação.</p>
|
||||
<form className="max-w-2xl space-y-3" onSubmit={e => { e.preventDefault(); void save(); }}>
|
||||
<label className="block">Conta da pessoa designada<input required type="number" min={1} className={control} value={subject} onChange={e => setSubject(e.target.value)} /></label>
|
||||
<label className="block">Função interna<select aria-label="Função interna" required className={control} value={role} onChange={e => setRole(e.target.value)}>{['promoter', 'validator', 'publisher'].map(v => <option key={v} value={v}>{v === 'promoter' ? 'Promotor' : v === 'validator' ? 'Validador' : 'Publicador'}</option>)}</select></label>
|
||||
<label className="block">Vínculo à organização operadora<select aria-label="Vínculo à organização operadora" required className={control} value={operator} onChange={e => setOperator(e.target.value)}><option value="">Selecionar organização</option>{operators.map(o => <option key={o.id} value={o.id}>{o.name} — NUIT {o.nuit}</option>)}</select></label>
|
||||
{role !== 'promoter' && <label className="block">Âmbito da função interna<select aria-label="Âmbito da função interna" className={control} value={scope} onChange={e => setScope(e.target.value)}><option value="">Todas as organizações para as categorias selecionadas</option>{organizations.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}</select></label>}
|
||||
<fieldset><legend>Categorias da função interna</legend>{types.map(v => <label className="block" key={v}><input type="checkbox" checked={selected.includes(v)} onChange={() => setSelected(old => old.includes(v) ? old.filter(x => x !== v) : [...old, v])} /> {v}</label>)}</fieldset>
|
||||
<label className="block"><input type="checkbox" required checked={confirmed} onChange={e => setConfirmed(e.target.checked)} /> Confirmo a designação interna expressa pelo responsável da organização operadora.</label>
|
||||
<label className="block">Fundamento da designação interna<textarea aria-label="Fundamento da designação interna" required minLength={20} maxLength={1000} className={control} value={reason} onChange={e => setReason(e.target.value)} /></label>
|
||||
<button className={button} disabled={busy}>Atribuir função interna com auditoria</button>
|
||||
<button type="button" className={button} disabled={busy} onClick={() => { setOperationKey(createOperationKey()); setSubject(''); setConfirmed(false); setMessage('Nova atribuição preparada.'); }}>Preparar outra atribuição</button>
|
||||
<p role="status">{message}</p>
|
||||
</form>
|
||||
</section>;
|
||||
}
|
||||
|
||||
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 externo usa o pedido documental. Funções internas usam a designação da proprietária. 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
|
||||
aria-label="Papel"
|
||||
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
|
||||
aria-label="Âmbito organizacional"
|
||||
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)}
|
||||
>
|
||||
{[
|
||||
'view',
|
||||
'create',
|
||||
'edit',
|
||||
'validate',
|
||||
'publish',
|
||||
'archive',
|
||||
].map((v) => (
|
||||
<option key={v} value={v}>{v === 'view' ? 'Consultar dossier e anexos' : 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); }
|
||||
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>;
|
||||
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>;
|
||||
export default function Administration({
|
||||
requests,
|
||||
pair,
|
||||
assignments,
|
||||
securityAlerts,
|
||||
actorId,
|
||||
types,
|
||||
organizations,
|
||||
securityRequests,
|
||||
operatorOrganizations,
|
||||
internalTypes,
|
||||
}: {
|
||||
operatorOrganizations: OperatorOrganization[];
|
||||
internalTypes: string[];
|
||||
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>
|
||||
<OperatorOrganizationForm />
|
||||
<InternalStaffGrant types={internalTypes} organizations={organizations} operators={operatorOrganizations} />
|
||||
<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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,21 +1,120 @@
|
||||
import { Head, useForm } from '@inertiajs/react';
|
||||
import ProfileNavigation from '@/components/profile-navigation';
|
||||
import { button, control, Pagination, type Paginated } from '@/pages/management/shared';
|
||||
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 !== ''));
|
||||
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>;
|
||||
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,35 @@
|
||||
import { useState } from 'react';
|
||||
import { Management, button, control } from '@/pages/management/shared';
|
||||
import { profileJson } from '@/lib/profile-json';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
type Plan = {approval_id:string;requested_by:number;second_user_id:number;reason:string;expires_at:string;consumed:boolean;expired:boolean;code_current:boolean;can_confirm:boolean;mfa_confirmed_in_session:boolean;hash:string;target:{database:string;port:number}};
|
||||
export default function BootstrapConfirmation(plan:Plan) {
|
||||
const [key] = useState(createOperationKey);
|
||||
const [reason,setReason] = useState('');
|
||||
const [confirmed,setConfirmed] = useState(false);
|
||||
const [busy,setBusy] = useState(false);
|
||||
const [done,setDone] = useState(plan.consumed);
|
||||
const [message,setMessage] = useState('');
|
||||
async function confirm() {
|
||||
setBusy(true);setMessage('');
|
||||
try {
|
||||
await profileJson('/management/profile-install/bootstrap/'+plan.approval_id+'/confirm',{hash:plan.hash,confirm:confirmed,idempotency_key:key,reason});
|
||||
setDone(true);setMessage('Dupla inicializada por confirmação cruzada. Apenas estas duas contas foram designadas; nenhuma flag foi alterada. Inicie uma nova sessão.');
|
||||
} catch(error) {setMessage(error instanceof Error?error.message:'Resposta indisponível. Recupere este pedido antes de repetir.');}
|
||||
finally {setBusy(false);}
|
||||
}
|
||||
return <Management title="Confirmar os dois titulares">
|
||||
<p>Base {plan.target.database}:{plan.target.port}</p>
|
||||
<p>Pedido apresentado pela conta {plan.requested_by}; confirmação reservada à conta {plan.second_user_id}.</p>
|
||||
<p>Fundamento do pedido: {plan.reason}</p><p>Expira em {plan.expires_at}.</p>
|
||||
<p>O pedido não atribui privilégios. A confirmação é uma operação distinta, com MFA e auditoria. Não altera a regra de substituição posterior.</p>
|
||||
{plan.expired && <p role="alert">Pedido expirado. Prepare novo pedido autorizado.</p>}
|
||||
{!plan.code_current && <p role="alert">Revisão ou destino alterados. Este pedido não pode ser confirmado.</p>}
|
||||
{!plan.mfa_confirmed_in_session && <p role="alert">Conclua MFA nesta sessão antes de confirmar.</p>}
|
||||
{!plan.can_confirm && !done && <p>Esta conta pode consultar, mas não confirmar o pedido.</p>}
|
||||
<label className="block">Fundamento da confirmação<textarea className={control} minLength={20} maxLength={1000} value={reason} onChange={e=>setReason(e.target.value)}/></label>
|
||||
<label className="block"><input type="checkbox" checked={confirmed} onChange={e=>setConfirmed(e.target.checked)}/> Confirmo apenas estas duas contas e esta base</label>
|
||||
<button className={button} disabled={busy||done||!plan.can_confirm||!plan.mfa_confirmed_in_session||!confirmed||reason.length<20} onClick={()=>void confirm()}>Confirmar designação cruzada</button>
|
||||
<p role="status">{done?'Pedido consumido; não reinicializar. ':''}{message}</p>
|
||||
</Management>;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { useState } from 'react';
|
||||
import { Management, button, control } from '@/pages/management/shared';
|
||||
import { profileJson } from '@/lib/profile-json';
|
||||
@@ -17,6 +18,7 @@ type Plan = {
|
||||
holders: number[];
|
||||
version: number | null;
|
||||
rule: string;
|
||||
pending: {approval_id:string;confirmation_url:string;expires_at:string} | null;
|
||||
};
|
||||
};
|
||||
export default function Installation(initial: Plan) {
|
||||
@@ -27,6 +29,9 @@ export default function Installation(initial: Plan) {
|
||||
const [second, setSecond] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [confirmationUrl, setConfirmationUrl] = useState<string | null>(null);
|
||||
const [installationKey] = useState(createOperationKey);
|
||||
const [bootstrapKey] = useState(createOperationKey);
|
||||
async function run(bootstrap = false) {
|
||||
setBusy(true);
|
||||
setMessage('');
|
||||
@@ -37,7 +42,7 @@ export default function Installation(initial: Plan) {
|
||||
hash: plan.hash,
|
||||
confirm: confirmed,
|
||||
reason,
|
||||
idempotency_key: crypto.randomUUID(),
|
||||
idempotency_key: bootstrap ? bootstrapKey : installationKey,
|
||||
...(bootstrap
|
||||
? {
|
||||
first_user_id: Number(first),
|
||||
@@ -48,11 +53,12 @@ export default function Installation(initial: Plan) {
|
||||
);
|
||||
setMessage(
|
||||
bootstrap
|
||||
? 'Dupla inicializada. Inicie uma nova sessão como um dos titulares designados; MFA permanece obrigatório.'
|
||||
? 'Pedido registado, sem atribuir privilégios. O segundo titular deve autenticar-se com MFA e confirmar pelo endereço abaixo.'
|
||||
: 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) setConfirmationUrl(result.confirmation_url as string);
|
||||
if (!bootstrap)
|
||||
setPlan(
|
||||
(await profileJson(
|
||||
@@ -141,6 +147,7 @@ export default function Installation(initial: Plan) {
|
||||
<section className="space-y-3 rounded border p-4">
|
||||
<h2>Inicialização separada dos dois superutilizadores</h2>
|
||||
<p>{plan.bootstrap.rule}</p>
|
||||
{plan.bootstrap.pending && <p>Pedido pendente até {plan.bootstrap.pending.expires_at}. <a className="underline" href={plan.bootstrap.pending.confirmation_url}>Recuperar pedido de confirmação</a>. Nenhum privilégio foi atribuído pelo pedido.</p>}
|
||||
{plan.bootstrap.initialized ? (
|
||||
<p>
|
||||
Dupla já inicializada:{' '}
|
||||
@@ -176,6 +183,7 @@ export default function Installation(initial: Plan) {
|
||||
busy ||
|
||||
!confirmed ||
|
||||
!plan.installed ||
|
||||
!!plan.bootstrap.pending ||
|
||||
!first ||
|
||||
!second ||
|
||||
first === second ||
|
||||
@@ -183,12 +191,13 @@ export default function Installation(initial: Plan) {
|
||||
}
|
||||
onClick={() => void run(true)}
|
||||
>
|
||||
Inicializar apenas estas duas contas
|
||||
Pedir confirmação ao segundo titular
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
<p role="status">{message}</p>
|
||||
{confirmationUrl && <p>Endereço para o segundo titular: <a className="underline" href={confirmationUrl}>{confirmationUrl}</a>. O primeiro titular pode consultar, mas não confirmar.</p>}
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,48 +1,195 @@
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
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}[];
|
||||
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 [key, setKey] = useState(() => createOperationKey());
|
||||
const [message, setMessage] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
async function send() {
|
||||
setBusy(true); setMessage('');
|
||||
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 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(createOperationKey());
|
||||
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>;
|
||||
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