fix: complete InvesteMoz validation and error corrections
This commit is contained in:
@@ -3,40 +3,212 @@ import { Frame, card, button } from '@/pages/investment/shared';
|
||||
import { states } from './shared';
|
||||
|
||||
type Access = {
|
||||
procurement?: {index:string;create:string};
|
||||
opportunities?: {index: string; create: string | null; profileWorkflow: boolean};
|
||||
documents?: {index: string; edit: boolean};
|
||||
procurement?: { index: string; create: string };
|
||||
opportunities?: {
|
||||
index: string;
|
||||
create: string | null;
|
||||
profileWorkflow: boolean;
|
||||
};
|
||||
documents?: { index: string; edit: boolean };
|
||||
};
|
||||
export default function ContentHub({access, counts}: {access: Access; counts: Record<string, Record<string, number>>}) {
|
||||
return <Frame title="Gestão de conteúdos e oportunidades">
|
||||
<p>Use os cadastros e a biblioteca existentes. Guardar um rascunho, analisar um ficheiro e publicar são operações distintas. Cada acção respeita a sua autorização actual.</p>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{access.procurement && <section className={card}><h2 className="text-xl font-semibold">Concursos e anúncios</h2><p>Cadastre o procedimento e os lotes, guarde e recupere a preparação, reveja a prévia e publique os actos autorizados. Esclarecimentos, prorrogações, resultados e cancelamentos conservam versões e histórico. Divulgação de oportunidade e abertura de concurso são operações distintas.</p><Link className={button} href={access.procurement.create}>Novo concurso/anúncio</Link><Link className="block underline" href={access.procurement.index}>Gerir concursos e anúncios</Link><Link className="block underline" href="/concursos">Catálogo público</Link></section>}
|
||||
{access.opportunities && <section className={card}>
|
||||
<h2 className="text-xl font-semibold">Oportunidades</h2>
|
||||
<p>Escolha a modalidade, o sector e a localização; preencha, guarde o rascunho e siga as acções de submissão, revisão e publicação disponíveis no seu perfil.</p>
|
||||
<p>Sector económico e modalidade são escolhas distintas. Pode guardar preparação incompleta; o editor identifica os campos e variantes ainda sem suporte de submissão.</p>
|
||||
{access.opportunities.create && <Link className={button} href={access.opportunities.create}>Nova oportunidade</Link>}
|
||||
<Link className="block underline" href={access.opportunities.index}>Gerir oportunidades e histórico</Link>
|
||||
{access.opportunities.profileWorkflow && <Link className="block underline" href="/minhas-oportunidades/lotes/agronegocio">Rever o lote das 34 oportunidades de Agronegócio</Link>}
|
||||
<p>Para divulgar um resumo ainda em preparação, abra a ficha e escolha <strong>Divulgação promocional</strong>: prepare o texto público, reveja a prévia e confirme divulgar, actualizar ou retirar. Esta operação não conclui a validação do investimento.</p>
|
||||
<ul>{Object.entries(counts.opportunities ?? {}).map(([state, total]) => <li key={state}><Link className="underline" href={`${access.opportunities!.index}?status=${state}`}>{states[state] ?? state}: {total}</Link></li>)}</ul>
|
||||
<p className="text-sm">As etapas e a independência já definidas para oportunidades mantêm-se. Esta entrada não atribui autorização para rever ou publicar.</p>
|
||||
{!access.opportunities.profileWorkflow && <p>O seu acesso actual abre o cadastro legado de rascunhos. A submissão, revisão e publicação de novas oportunidades utilizam os perfis operacionais já existentes; a administração de conteúdos não substitui essa designação. Esta entrada não apresenta o rascunho legado como percurso completo de publicação.</p>}
|
||||
</section>}
|
||||
{access.documents && <section className={card}>
|
||||
<h2 className="text-xl font-semibold">Documentos e legislação</h2>
|
||||
<p>Carregue o original ou reutilize um ficheiro existente; acompanhe a análise, complete os metadados e associações e defina o acesso. Depois publique explicitamente, se autorizado.</p>
|
||||
<div className="flex flex-wrap gap-3"><Link className={button} href={`${access.documents.index}?intent=document#receber`}>Novo documento</Link>
|
||||
{access.documents.edit && <Link className={button} href={`${access.documents.index}?intent=legislation#receber`}>Nova legislação</Link>}</div>
|
||||
<Link className="block underline" href={`${access.documents.index}#conteudos`}>Gerir conteúdos, versões e histórico</Link>
|
||||
{!access.documents.edit && <p>O seu acesso permite carregar e analisar ficheiros próprios; não inclui cadastro editorial nem publicação.</p>}
|
||||
<p>Publicados: {counts.documents?.published ?? 0} · Não publicados: {counts.documents?.unpublished ?? 0}. A lista distingue rascunhos de conteúdos retirados através do histórico.</p>
|
||||
<p className="text-sm">Publicar legislação permite consultá-la. Não a activa como regra executável no simulador.</p>
|
||||
</section>}
|
||||
</div>
|
||||
<section className={card}><h2 className="font-semibold">Como concluir sem apoio técnico</h2>
|
||||
<ol className="list-decimal space-y-2 pl-5"><li>Abra a acção pretendida e use os campos do editor existente.</li><li>Guarde a preparação. As mensagens indicam o estado e o que precisa de corrigir.</li><li>Reabra pela gestão, pesquise o título e consulte o histórico.</li><li>Use as acções autorizadas de publicação ou retirada. Os originais e as revisões são preservados.</li></ol>
|
||||
</section>
|
||||
</Frame>;
|
||||
export default function ContentHub({
|
||||
access,
|
||||
counts,
|
||||
}: {
|
||||
access: Access;
|
||||
counts: Record<string, Record<string, number>>;
|
||||
}) {
|
||||
return (
|
||||
<Frame title="Gestão de conteúdos e oportunidades">
|
||||
<p>
|
||||
Use os cadastros e a biblioteca existentes. Guardar um rascunho,
|
||||
analisar um ficheiro e publicar são operações distintas. Cada
|
||||
acção respeita a sua autorização actual.
|
||||
</p>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{access.procurement && (
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Concursos e anúncios
|
||||
</h2>
|
||||
<p>
|
||||
Cadastre o procedimento e os lotes, guarde e
|
||||
recupere a preparação, reveja a prévia e publique os
|
||||
actos autorizados. Esclarecimentos, prorrogações,
|
||||
resultados e cancelamentos conservam versões e
|
||||
histórico. Divulgação de oportunidade e abertura de
|
||||
concurso são operações distintas.
|
||||
</p>
|
||||
<Link
|
||||
className={button}
|
||||
href={access.procurement.create}
|
||||
>
|
||||
Novo concurso/anúncio
|
||||
</Link>
|
||||
<Link
|
||||
className="block underline"
|
||||
href={access.procurement.index}
|
||||
>
|
||||
Gerir concursos e anúncios
|
||||
</Link>
|
||||
<Link className="block underline" href="/concursos">
|
||||
Catálogo público
|
||||
</Link>
|
||||
</section>
|
||||
)}
|
||||
{access.opportunities && (
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-semibold">Oportunidades</h2>
|
||||
<p>
|
||||
Escolha a modalidade, o sector e a localização;
|
||||
preencha, guarde o rascunho e siga as acções de
|
||||
submissão, revisão e publicação disponíveis no seu
|
||||
perfil.
|
||||
</p>
|
||||
<p>
|
||||
Sector económico e modalidade são escolhas
|
||||
distintas. Pode guardar preparação incompleta; o
|
||||
editor identifica os campos e variantes ainda sem
|
||||
suporte de submissão.
|
||||
</p>
|
||||
{access.opportunities.create && (
|
||||
<Link
|
||||
className={button}
|
||||
href={access.opportunities.create}
|
||||
>
|
||||
Nova oportunidade
|
||||
</Link>
|
||||
)}
|
||||
<Link
|
||||
className="block underline"
|
||||
href={access.opportunities.index}
|
||||
>
|
||||
Gerir oportunidades e histórico
|
||||
</Link>
|
||||
{access.opportunities.profileWorkflow && (
|
||||
<Link
|
||||
className="block underline"
|
||||
href="/minhas-oportunidades/lotes/agronegocio"
|
||||
>
|
||||
Rever o lote das 34 oportunidades de Agronegócio
|
||||
</Link>
|
||||
)}
|
||||
<p>
|
||||
Para divulgar um resumo ainda em preparação, abra a
|
||||
ficha e escolha{' '}
|
||||
<strong>Divulgação promocional</strong>: prepare o
|
||||
texto público, reveja a prévia e confirme divulgar,
|
||||
actualizar ou retirar. Esta operação não conclui a
|
||||
validação do investimento.
|
||||
</p>
|
||||
<ul>
|
||||
{Object.entries(counts.opportunities ?? {}).map(
|
||||
([state, total]) => (
|
||||
<li key={state}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`${access.opportunities!.index}?status=${state}`}
|
||||
>
|
||||
{states[state] ?? state}: {total}
|
||||
</Link>
|
||||
</li>
|
||||
),
|
||||
)}
|
||||
</ul>
|
||||
<p className="text-sm">
|
||||
As etapas e a independência já definidas para
|
||||
oportunidades mantêm-se. Esta entrada não atribui
|
||||
autorização para rever ou publicar.
|
||||
</p>
|
||||
{!access.opportunities.profileWorkflow && (
|
||||
<p>
|
||||
O seu acesso actual abre o cadastro legado de
|
||||
rascunhos. A submissão, revisão e publicação de
|
||||
novas oportunidades utilizam os perfis
|
||||
operacionais já existentes; a administração de
|
||||
conteúdos não substitui essa designação. Esta
|
||||
entrada não apresenta o rascunho legado como
|
||||
percurso completo de publicação.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
{access.documents && (
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Documentos e legislação
|
||||
</h2>
|
||||
<p>
|
||||
Carregue o original ou reutilize um ficheiro
|
||||
existente; acompanhe a análise, complete os
|
||||
metadados e associações e defina o acesso. Depois
|
||||
publique explicitamente, se autorizado.
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Link
|
||||
className={button}
|
||||
href={`${access.documents.index}?intent=document#receber`}
|
||||
>
|
||||
Novo documento
|
||||
</Link>
|
||||
{access.documents.edit && (
|
||||
<Link
|
||||
className={button}
|
||||
href={`${access.documents.index}?intent=legislation#receber`}
|
||||
>
|
||||
Nova legislação
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
<Link
|
||||
className="block underline"
|
||||
href={`${access.documents.index}#conteudos`}
|
||||
>
|
||||
Gerir conteúdos, versões e histórico
|
||||
</Link>
|
||||
{!access.documents.edit && (
|
||||
<p>
|
||||
O seu acesso permite carregar e analisar
|
||||
ficheiros próprios; não inclui cadastro
|
||||
editorial nem publicação.
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
Publicados: {counts.documents?.published ?? 0} · Não
|
||||
publicados: {counts.documents?.unpublished ?? 0}. A
|
||||
lista distingue rascunhos de conteúdos retirados
|
||||
através do histórico.
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
Publicar legislação permite consultá-la. Não a
|
||||
activa como regra executável no simulador.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
<section className={card}>
|
||||
<h2 className="font-semibold">
|
||||
Como concluir sem apoio técnico
|
||||
</h2>
|
||||
<ol className="list-decimal space-y-2 pl-5">
|
||||
<li>
|
||||
Abra a acção pretendida e use os campos do editor
|
||||
existente.
|
||||
</li>
|
||||
<li>
|
||||
Guarde a preparação. As mensagens indicam o estado e o
|
||||
que precisa de corrigir.
|
||||
</li>
|
||||
<li>
|
||||
Reabra pela gestão, pesquise o título e consulte o
|
||||
histórico.
|
||||
</li>
|
||||
<li>
|
||||
Use as acções autorizadas de publicação ou retirada. Os
|
||||
originais e as revisões são preservados.
|
||||
</li>
|
||||
</ol>
|
||||
</section>
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,22 +4,181 @@ import { profileJson } from '@/lib/profile-json';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { Management, button, control } from './shared';
|
||||
|
||||
type Entry = {key:string;id:number|null;title:string;summary:string;description:string;corridor:string;status:string|null;href:string|null};
|
||||
type Preview = {id:number;token:string;projection:{title:string;summary:string;description:string};operation_key:string};
|
||||
export default function AgribusinessBatch({entries,manifestHash,canRegister}:{entries:Entry[];manifestHash:string;canRegister:boolean}) {
|
||||
const [previews,setPreviews]=useState<Preview[]>([]); const [reason,setReason]=useState(''); const [confirmed,setConfirmed]=useState(false); const [busy,setBusy]=useState(false); const [message,setMessage]=useState('');
|
||||
const base='/minhas-oportunidades/lotes/agronegocio';
|
||||
async function run(action:'register'|'preview'|'disclose') {setBusy(true);setMessage('');try {
|
||||
if(action==='register'){await profileJson(base+'/cadastrar',{manifest_hash:manifestHash,confirm:true});router.reload();}
|
||||
if(action==='preview'){const result=await profileJson(base+'/previa',{}) as {previews:Preview[]};setPreviews(result.previews.map(p=>({...p,operation_key:createOperationKey()})));setConfirmed(false);}
|
||||
if(action==='disclose'){await profileJson(base+'/divulgar',{previews:previews.map(({id,token,operation_key})=>({id,token,operation_key})),reason,confirm:confirmed});setPreviews([]);setMessage('As 34 fichas foram divulgadas como Em preparação; a execução não foi autorizada.');router.reload();}
|
||||
}catch(e){setMessage(e instanceof Error?e.message:'Operação não concluída. A versão anterior foi preservada.');}finally{setBusy(false);}}
|
||||
return <Management title="Oportunidades de Agronegócio"><p>Reveja as oportunidades, complete a informação disponível e confira a prévia antes de divulgar.</p>
|
||||
<p>{entries.filter(e=>e.id).length} cadastradas · {entries.filter(e=>e.status==='published').length} divulgadas</p>
|
||||
{canRegister && <button className={button} disabled={busy} onClick={()=>void run('register')}>Cadastrar ou recuperar as 34 fichas privadamente</button>}
|
||||
{entries.every(e=>e.id) && <button className={button+' ml-3'} disabled={busy} onClick={()=>void run('preview')}>Pré-visualizar divulgação das 34 fichas</button>}
|
||||
<ul className="my-5 space-y-3">{entries.map(e=><li key={e.key} className="rounded border p-3"><h2>{e.title}</h2><p>{e.summary}</p><p>{e.corridor} · {e.status??'Por cadastrar'}</p>{e.id&&<Link className="underline" href={`/minhas-oportunidades/${e.id}/edit`}>Rever e editar a ficha</Link>}</li>)}</ul>
|
||||
{!!previews.length && <section aria-label="Prévia pública das 34 fichas"><h2>Conteúdo a divulgar — Em preparação</h2>{previews.map(p=><details key={p.id} className="my-3 rounded border p-3"><summary>{p.projection.title}</summary><p>{p.projection.summary}</p><p className="whitespace-pre-line">{p.projection.description}</p></details>)}<label className="block">Motivo<textarea className={control} value={reason} onChange={e=>setReason(e.target.value)}/></label><label className="block"><input type="checkbox" checked={confirmed} onChange={e=>setConfirmed(e.target.checked)}/>Confirmo a divulgação destes resumos em preparação; não é autorização de execução.</label><button className={button} disabled={busy||!confirmed||reason.trim().length<20} onClick={()=>void run('disclose')}>Divulgar as 34 oportunidades no catálogo</button></section>}
|
||||
{message&&<p role="status">{message}</p>}<Link className="block underline" href="/oportunidades?sector=agronegocio">Consultar catálogo de Agronegócio</Link>
|
||||
</Management>;
|
||||
type Entry = {
|
||||
key: string;
|
||||
id: number | null;
|
||||
title: string;
|
||||
summary: string;
|
||||
description: string;
|
||||
corridor: string;
|
||||
status: string | null;
|
||||
href: string | null;
|
||||
};
|
||||
type Preview = {
|
||||
id: number;
|
||||
token: string;
|
||||
projection: { title: string; summary: string; description: string };
|
||||
operation_key: string;
|
||||
};
|
||||
export default function AgribusinessBatch({
|
||||
entries,
|
||||
manifestHash,
|
||||
canRegister,
|
||||
}: {
|
||||
entries: Entry[];
|
||||
manifestHash: string;
|
||||
canRegister: boolean;
|
||||
}) {
|
||||
const [previews, setPreviews] = useState<Preview[]>([]);
|
||||
const [reason, setReason] = useState('');
|
||||
const [confirmed, setConfirmed] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const base = '/minhas-oportunidades/lotes/agronegocio';
|
||||
async function run(action: 'register' | 'preview' | 'disclose') {
|
||||
setBusy(true);
|
||||
setMessage('');
|
||||
try {
|
||||
if (action === 'register') {
|
||||
await profileJson(base + '/cadastrar', {
|
||||
manifest_hash: manifestHash,
|
||||
confirm: true,
|
||||
});
|
||||
router.reload();
|
||||
}
|
||||
if (action === 'preview') {
|
||||
const result = (await profileJson(base + '/previa', {})) as {
|
||||
previews: Preview[];
|
||||
};
|
||||
setPreviews(
|
||||
result.previews.map((p) => ({
|
||||
...p,
|
||||
operation_key: createOperationKey(),
|
||||
})),
|
||||
);
|
||||
setConfirmed(false);
|
||||
}
|
||||
if (action === 'disclose') {
|
||||
await profileJson(base + '/divulgar', {
|
||||
previews: previews.map(({ id, token, operation_key }) => ({
|
||||
id,
|
||||
token,
|
||||
operation_key,
|
||||
})),
|
||||
reason,
|
||||
confirm: confirmed,
|
||||
});
|
||||
setPreviews([]);
|
||||
setMessage(
|
||||
'As 34 fichas foram divulgadas como Em preparação; a execução não foi autorizada.',
|
||||
);
|
||||
router.reload();
|
||||
}
|
||||
} catch (e) {
|
||||
setMessage(
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Operação não concluída. A versão anterior foi preservada.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Management title="Oportunidades de Agronegócio">
|
||||
<p>
|
||||
Reveja as oportunidades, complete a informação disponível e
|
||||
confira a prévia antes de divulgar.
|
||||
</p>
|
||||
<p>
|
||||
{entries.filter((e) => e.id).length} cadastradas ·{' '}
|
||||
{entries.filter((e) => e.status === 'published').length}{' '}
|
||||
divulgadas
|
||||
</p>
|
||||
{canRegister && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() => void run('register')}
|
||||
>
|
||||
Cadastrar ou recuperar as 34 fichas privadamente
|
||||
</button>
|
||||
)}
|
||||
{entries.every((e) => e.id) && (
|
||||
<button
|
||||
className={button + ' ml-3'}
|
||||
disabled={busy}
|
||||
onClick={() => void run('preview')}
|
||||
>
|
||||
Pré-visualizar divulgação das 34 fichas
|
||||
</button>
|
||||
)}
|
||||
<ul className="my-5 space-y-3">
|
||||
{entries.map((e) => (
|
||||
<li key={e.key} className="rounded border p-3">
|
||||
<h2>{e.title}</h2>
|
||||
<p>{e.summary}</p>
|
||||
<p>
|
||||
{e.corridor} · {e.status ?? 'Por cadastrar'}
|
||||
</p>
|
||||
{e.id && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/minhas-oportunidades/${e.id}/edit`}
|
||||
>
|
||||
Rever e editar a ficha
|
||||
</Link>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{!!previews.length && (
|
||||
<section aria-label="Prévia pública das 34 fichas">
|
||||
<h2>Conteúdo a divulgar — Em preparação</h2>
|
||||
{previews.map((p) => (
|
||||
<details key={p.id} className="my-3 rounded border p-3">
|
||||
<summary>{p.projection.title}</summary>
|
||||
<p>{p.projection.summary}</p>
|
||||
<p className="whitespace-pre-line">
|
||||
{p.projection.description}
|
||||
</p>
|
||||
</details>
|
||||
))}
|
||||
<label className="block">
|
||||
Motivo
|
||||
<textarea
|
||||
className={control}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={confirmed}
|
||||
onChange={(e) => setConfirmed(e.target.checked)}
|
||||
/>
|
||||
Confirmo a divulgação destes resumos em preparação; não
|
||||
é autorização de execução.
|
||||
</label>
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
busy || !confirmed || reason.trim().length < 20
|
||||
}
|
||||
onClick={() => void run('disclose')}
|
||||
>
|
||||
Divulgar as 34 oportunidades no catálogo
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
{message && <p role="status">{message}</p>}
|
||||
<Link
|
||||
className="block underline"
|
||||
href="/oportunidades?sector=agronegocio"
|
||||
>
|
||||
Consultar catálogo de Agronegócio
|
||||
</Link>
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,15 +1,160 @@
|
||||
import { Head, router, usePage } from '@inertiajs/react';
|
||||
import { useRef, useState } from 'react';
|
||||
type Row={id:string;protocol:string;status:string;version:number;analyst_id:number|null;due_at:string|null;etag?:string};
|
||||
export default function DeskAssignments(){
|
||||
const {requests,analysts,kind,flash}=usePage<{requests:Row[];analysts:{id:number;name:string}[];kind?:'interest';flash?:{success?:string}}>().props;
|
||||
const alertRef=useRef<HTMLDivElement>(null);
|
||||
const stateNames:Record<string,string>={received:'Recebido',submitted:'Submetido',in_review:'Em revisão',reviewed:'Revisto',qualification:'Em qualificação',qualified:'Qualificado',contacted:'Contactado',contact_accepted:'Contacto aceite',referred:'Encaminhado',due_diligence:'Em diligência',negotiation:'Em negociação',pending:'Pendente',accepted:'Aceite',rejected:'Recusado',returned:'Devolvido',processing:'Em tratamento',draft:'Rascunho'};
|
||||
const title=kind==='interest'?'Atribuições de interesses':'Atribuições do Balcão';
|
||||
const [selected,setSelected]=useState<Record<string,string>>({});
|
||||
const [reason,setReason]=useState<Record<string,string>>({});
|
||||
const [errors,setErrors]=useState<Record<string,string>>({});
|
||||
const [busy,setBusy]=useState<string|null>(null);
|
||||
function assign(row:Row){setBusy(row.id);setErrors({});router.post(kind==='interest'?`/management/interests/${row.id}/responsavel`:`/balcao-virtual/pedidos/${row.id}/responsavel`,{...(kind==='interest'?{etag:row.etag}:{version:row.version}),analyst_id:selected[row.id]??String(row.analyst_id??''),reason:reason[row.id]??''},{preserveScroll:true,onError:e=>{setErrors(e);queueMicrotask(()=>alertRef.current?.focus());},onFinish:()=>setBusy(null)});}
|
||||
return <main className="mx-auto max-w-5xl space-y-6 p-6"><Head title={title}/><h1 className="text-2xl font-semibold">{title}</h1><p>Atribua o acompanhamento de um pedido. Esta lista não dá acesso ao conteúdo privado do dossier. O proponente não pode ser designado como analista do seu pedido.</p><a href={kind==='interest'?'/management/interests':'/balcao-virtual/painel'} className="underline">{kind==='interest'?'Interesses atribuídos':'Voltar ao Balcão'}</a><div ref={alertRef} role="alert" tabIndex={-1}>{Object.values(errors).join(' ')}</div>{flash?.success&&<p role="status">{flash.success}</p>}{requests.length===0?<p>Não há pedidos para atribuir.</p>:requests.map(row=><section key={row.id} className="space-y-3 rounded border p-4"><h2 className="font-semibold">{row.protocol||row.id}</h2><p>Estado: {stateNames[row.status]??'Por esclarecer'}</p><label className="block">Responsável<select className="ml-2 border p-2" value={selected[row.id]??String(row.analyst_id??'')} onChange={e=>setSelected({...selected,[row.id]:e.target.value})}><option value="">Seleccione</option>{analysts.map(a=><option key={a.id} value={a.id}>{a.name}</option>)}</select></label><label className="block">Fundamento<textarea className="block w-full border p-2" value={reason[row.id]??''} onChange={e=>setReason({...reason,[row.id]:e.target.value})}/></label><button className="rounded bg-emerald-900 px-4 py-2 text-white" disabled={busy!==null} onClick={()=>assign(row)}>{busy===row.id?'A guardar…':'Guardar atribuição'}</button></section>)}</main>;
|
||||
type Row = {
|
||||
id: string;
|
||||
protocol: string;
|
||||
status: string;
|
||||
version: number;
|
||||
analyst_id: number | null;
|
||||
due_at: string | null;
|
||||
etag?: string;
|
||||
};
|
||||
export default function DeskAssignments() {
|
||||
const { requests, analysts, kind, flash } = usePage<{
|
||||
requests: Row[];
|
||||
analysts: { id: number; name: string }[];
|
||||
kind?: 'interest';
|
||||
flash?: { success?: string };
|
||||
}>().props;
|
||||
const alertRef = useRef<HTMLDivElement>(null);
|
||||
const stateNames: Record<string, string> = {
|
||||
received: 'Recebido',
|
||||
submitted: 'Submetido',
|
||||
in_review: 'Em revisão',
|
||||
reviewed: 'Revisto',
|
||||
qualification: 'Em qualificação',
|
||||
qualified: 'Qualificado',
|
||||
contacted: 'Contactado',
|
||||
contact_accepted: 'Contacto aceite',
|
||||
referred: 'Encaminhado',
|
||||
due_diligence: 'Em diligência',
|
||||
negotiation: 'Em negociação',
|
||||
pending: 'Pendente',
|
||||
accepted: 'Aceite',
|
||||
rejected: 'Recusado',
|
||||
returned: 'Devolvido',
|
||||
processing: 'Em tratamento',
|
||||
draft: 'Rascunho',
|
||||
};
|
||||
const title =
|
||||
kind === 'interest'
|
||||
? 'Atribuições de interesses'
|
||||
: 'Atribuições do Balcão';
|
||||
const [selected, setSelected] = useState<Record<string, string>>({});
|
||||
const [reason, setReason] = useState<Record<string, string>>({});
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
function assign(row: Row) {
|
||||
setBusy(row.id);
|
||||
setErrors({});
|
||||
router.post(
|
||||
kind === 'interest'
|
||||
? `/management/interests/${row.id}/responsavel`
|
||||
: `/balcao-virtual/pedidos/${row.id}/responsavel`,
|
||||
{
|
||||
...(kind === 'interest'
|
||||
? { etag: row.etag }
|
||||
: { version: row.version }),
|
||||
analyst_id: selected[row.id] ?? String(row.analyst_id ?? ''),
|
||||
reason: reason[row.id] ?? '',
|
||||
},
|
||||
{
|
||||
preserveScroll: true,
|
||||
onError: (e) => {
|
||||
setErrors(e);
|
||||
queueMicrotask(() => alertRef.current?.focus());
|
||||
},
|
||||
onFinish: () => setBusy(null),
|
||||
},
|
||||
);
|
||||
}
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl space-y-6 p-6">
|
||||
<Head title={title} />
|
||||
<h1 className="text-2xl font-semibold">{title}</h1>
|
||||
<p>
|
||||
Atribua o acompanhamento de um pedido. Esta lista não dá acesso
|
||||
ao conteúdo privado do dossier. O proponente não pode ser
|
||||
designado como analista do seu pedido.
|
||||
</p>
|
||||
<a
|
||||
href={
|
||||
kind === 'interest'
|
||||
? '/management/interests'
|
||||
: '/balcao-virtual/painel'
|
||||
}
|
||||
className="underline"
|
||||
>
|
||||
{kind === 'interest'
|
||||
? 'Interesses atribuídos'
|
||||
: 'Voltar ao Balcão'}
|
||||
</a>
|
||||
<div ref={alertRef} role="alert" tabIndex={-1}>
|
||||
{Object.values(errors).join(' ')}
|
||||
</div>
|
||||
{flash?.success && <p role="status">{flash.success}</p>}
|
||||
{requests.length === 0 ? (
|
||||
<p>Não há pedidos para atribuir.</p>
|
||||
) : (
|
||||
requests.map((row) => (
|
||||
<section
|
||||
key={row.id}
|
||||
className="space-y-3 rounded border p-4"
|
||||
>
|
||||
<h2 className="font-semibold">
|
||||
{row.protocol || row.id}
|
||||
</h2>
|
||||
<p>
|
||||
Estado: {stateNames[row.status] ?? 'Por esclarecer'}
|
||||
</p>
|
||||
<label className="block">
|
||||
Responsável
|
||||
<select
|
||||
className="ml-2 border p-2"
|
||||
value={
|
||||
selected[row.id] ??
|
||||
String(row.analyst_id ?? '')
|
||||
}
|
||||
onChange={(e) =>
|
||||
setSelected({
|
||||
...selected,
|
||||
[row.id]: e.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">Seleccione</option>
|
||||
{analysts.map((a) => (
|
||||
<option key={a.id} value={a.id}>
|
||||
{a.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="block">
|
||||
Fundamento
|
||||
<textarea
|
||||
className="block w-full border p-2"
|
||||
value={reason[row.id] ?? ''}
|
||||
onChange={(e) =>
|
||||
setReason({
|
||||
...reason,
|
||||
[row.id]: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
className="rounded bg-emerald-900 px-4 py-2 text-white"
|
||||
disabled={busy !== null}
|
||||
onClick={() => assign(row)}
|
||||
>
|
||||
{busy === row.id
|
||||
? 'A guardar…'
|
||||
: 'Guardar atribuição'}
|
||||
</button>
|
||||
</section>
|
||||
))
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,10 +10,32 @@ type Plan = {
|
||||
installed: boolean;
|
||||
imported: boolean;
|
||||
publication: string;
|
||||
rows: { table: string; id: string; code: string; status: string; current_visibility: string | null }[];
|
||||
rows: {
|
||||
table: string;
|
||||
id: string;
|
||||
code: string;
|
||||
status: string;
|
||||
current_visibility: string | null;
|
||||
}[];
|
||||
sources: { name: string; sha256: string; ready: boolean }[];
|
||||
scan: { at: string; files: { name: string; sha256: string; scan: { result: string; engine: string } }[] } | null;
|
||||
operations: Record<Operation, { ready: boolean; hash: string; reasons: string[]; backupDate: string | null; evidence_mode: string }>;
|
||||
scan: {
|
||||
at: string;
|
||||
files: {
|
||||
name: string;
|
||||
sha256: string;
|
||||
scan: { result: string; engine: string };
|
||||
}[];
|
||||
} | null;
|
||||
operations: Record<
|
||||
Operation,
|
||||
{
|
||||
ready: boolean;
|
||||
hash: string;
|
||||
reasons: string[];
|
||||
backupDate: string | null;
|
||||
evidence_mode: string;
|
||||
}
|
||||
>;
|
||||
};
|
||||
const labels: Record<Operation, string> = {
|
||||
schema: 'Instalar apenas o esquema',
|
||||
@@ -27,63 +49,217 @@ export default function EconomicReferences({ plan }: { plan: Plan }) {
|
||||
const [confirm, setConfirm] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [receipt, setReceipt] = useState<Record<string, unknown> | null>(null);
|
||||
const last = useRef<{ operation: Operation; payload: Record<string, unknown> } | null>(null);
|
||||
const [receipt, setReceipt] = useState<Record<string, unknown> | null>(
|
||||
null,
|
||||
);
|
||||
const last = useRef<{
|
||||
operation: Operation;
|
||||
payload: Record<string, unknown>;
|
||||
} | null>(null);
|
||||
|
||||
async function perform(operation: Operation, replay = false) {
|
||||
const payload = replay && last.current?.operation === operation ? last.current.payload : {
|
||||
hash: plan.operations[operation].hash,
|
||||
idempotency_key: crypto.randomUUID(),
|
||||
reason,
|
||||
confirm,
|
||||
};
|
||||
const payload =
|
||||
replay && last.current?.operation === operation
|
||||
? last.current.payload
|
||||
: {
|
||||
hash: plan.operations[operation].hash,
|
||||
idempotency_key: crypto.randomUUID(),
|
||||
reason,
|
||||
confirm,
|
||||
};
|
||||
if (!replay) last.current = { operation, payload };
|
||||
setBusy(true); setError('');
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const token = document.cookie.split('; ').find((s) => s.startsWith('XSRF-TOKEN='))?.split('=').slice(1).join('=') ?? '';
|
||||
const response = await fetch(`/management/economic-references/lot-01/${operation}`, {
|
||||
method: 'POST', credentials: 'same-origin',
|
||||
headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-XSRF-TOKEN': decodeURIComponent(token) },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const token =
|
||||
document.cookie
|
||||
.split('; ')
|
||||
.find((s) => s.startsWith('XSRF-TOKEN='))
|
||||
?.split('=')
|
||||
.slice(1)
|
||||
.join('=') ?? '';
|
||||
const response = await fetch(
|
||||
`/management/economic-references/lot-01/${operation}`,
|
||||
{
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-XSRF-TOKEN': decodeURIComponent(token),
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
},
|
||||
);
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(Object.values(data.errors ?? {}).flat().join(' ') || data.message || 'Não foi possível concluir esta operação.');
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
Object.values(data.errors ?? {})
|
||||
.flat()
|
||||
.join(' ') ||
|
||||
data.message ||
|
||||
'Não foi possível concluir esta operação.',
|
||||
);
|
||||
setReceipt(data.receipt);
|
||||
router.reload({ only: ['plan'] });
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Operação indisponível. Atualize a prévia e consulte o motivo.');
|
||||
} finally { setBusy(false); }
|
||||
setError(
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Operação indisponível. Atualize a prévia e consulte o motivo.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return <Management title="Referências económicas — lote delimitado">
|
||||
<p>Destino: {plan.target.database}:{plan.target.port}</p>
|
||||
<p>Esquema: {plan.installed ? 'instalado' : 'pendente'} · Importação: {plan.imported ? 'recuperada' : 'pendente'} · Publicação: {plan.publication}</p>
|
||||
<p>Divisão 01 como subsector e subclasse 01120 como atividade apenas neste recorte. Os cinco níveis originais permanecem. A divergência documental 600/579 continua aberta; não há conformidade normativa integral declarada.</p>
|
||||
<p>Os cinco elos do CLU-01 são um modelo editorial, sem operadores, capacidades ou relações comerciais confirmados. Importar não publica referências, documentos ou anúncios.</p>
|
||||
<details><summary>Revisão e manifesto</summary><p className="break-all">Código: {plan.code_hash}</p><p className="break-all">Manifesto: {plan.manifest_sha256}</p></details>
|
||||
<section className="my-4" aria-label="Originais privados e scan">
|
||||
<h2 className="text-lg font-semibold">Originais privados</h2>
|
||||
{plan.sources.map((s) => <p className="break-words" key={s.sha256}>{s.name}: {s.ready ? 'bytes conferidos' : 'ausente ou divergente'} · <span className="break-all">{s.sha256}</span></p>)}
|
||||
<p>{plan.scan ? `Scan registado em ${plan.scan.at}.` : 'O scan real será executado na importação e novamente antes da publicação.'}</p>
|
||||
{plan.scan?.files.map((s) => <p key={s.sha256}>{s.name}: {s.scan.result} · {s.scan.engine}</p>)}
|
||||
</section>
|
||||
<label className="block" htmlFor="economic-reason">Justificação desta operação</label>
|
||||
<textarea id="economic-reason" className={control} value={reason} minLength={20} maxLength={1000} onChange={(e) => setReason(e.target.value)} />
|
||||
<label className="my-3 block"><input type="checkbox" checked={confirm} onChange={(e) => setConfirm(e.target.checked)} /> Confirmo somente a ação selecionada para este lote.</label>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{(Object.keys(labels) as Operation[]).map((operation) => <section className="rounded border p-3" key={operation}>
|
||||
<h2 className="font-semibold">{labels[operation]}</h2>
|
||||
<p>{operation === 'schema' ? 'Migration nominal, sem importar dados.' : operation === 'import' ? 'Apenas ausências, privadamente; repetição sem duplicações.' : operation === 'publish' ? 'Expor apenas as referências do manifesto. Não divulga relações de investimentos.' : 'Retirada expressa e auditada; preserva UUID, decisões e recuperação histórica.'}</p>
|
||||
<p>Backup/restauro: {plan.operations[operation].backupDate ?? (plan.operations[operation].evidence_mode === 'isolated_QA' ? 'Ensaio QA isolado' : 'prova própria ainda necessária')}</p>
|
||||
{plan.operations[operation].reasons.map((r) => <p className="text-sm" key={r}>{r}</p>)}
|
||||
<button className={button} disabled={busy || !confirm || reason.trim().length < 20 || !plan.operations[operation].ready} onClick={() => perform(operation)}>{labels[operation]}</button>
|
||||
</section>)}
|
||||
</div>
|
||||
{error && <p className="my-3" role="alert">{error}</p>}
|
||||
{receipt && <section className="my-4" aria-live="polite"><h2 className="text-lg font-semibold">Recibo da operação</h2><pre className="overflow-auto whitespace-pre-wrap break-all text-sm">{JSON.stringify(receipt, null, 2)}</pre><button className={button} disabled={busy || !last.current} onClick={() => last.current && perform(last.current.operation, true)}>Repetir pedido anterior, sem duplicar</button></section>}
|
||||
<section className="mt-4"><h2 className="text-lg font-semibold">Referências previstas e recuperadas</h2>
|
||||
{plan.rows.map((r) => <p key={r.id}>{r.code}: {r.status} · {r.current_visibility ?? 'a inserir privadamente'}</p>)}
|
||||
</section>
|
||||
<p className="mt-4">Reversão após uso é parcial e compatível: conservar schema/dados, fontes funcionais e build de compatibilidade. Trocar código não retira publicação automaticamente.</p>
|
||||
</Management>;
|
||||
return (
|
||||
<Management title="Referências económicas — lote delimitado">
|
||||
<p>
|
||||
Destino: {plan.target.database}:{plan.target.port}
|
||||
</p>
|
||||
<p>
|
||||
Esquema: {plan.installed ? 'instalado' : 'pendente'} ·
|
||||
Importação: {plan.imported ? 'recuperada' : 'pendente'} ·
|
||||
Publicação: {plan.publication}
|
||||
</p>
|
||||
<p>
|
||||
Divisão 01 como subsector e subclasse 01120 como atividade
|
||||
apenas neste recorte. Os cinco níveis originais permanecem. A
|
||||
divergência documental 600/579 continua aberta; não há
|
||||
conformidade normativa integral declarada.
|
||||
</p>
|
||||
<p>
|
||||
Os cinco elos do CLU-01 são um modelo editorial, sem operadores,
|
||||
capacidades ou relações comerciais confirmados. Importar não
|
||||
publica referências, documentos ou anúncios.
|
||||
</p>
|
||||
<details>
|
||||
<summary>Revisão e manifesto</summary>
|
||||
<p className="break-all">Código: {plan.code_hash}</p>
|
||||
<p className="break-all">Manifesto: {plan.manifest_sha256}</p>
|
||||
</details>
|
||||
<section className="my-4" aria-label="Originais privados e scan">
|
||||
<h2 className="text-lg font-semibold">Originais privados</h2>
|
||||
{plan.sources.map((s) => (
|
||||
<p className="break-words" key={s.sha256}>
|
||||
{s.name}:{' '}
|
||||
{s.ready ? 'bytes conferidos' : 'ausente ou divergente'}{' '}
|
||||
· <span className="break-all">{s.sha256}</span>
|
||||
</p>
|
||||
))}
|
||||
<p>
|
||||
{plan.scan
|
||||
? `Scan registado em ${plan.scan.at}.`
|
||||
: 'O scan real será executado na importação e novamente antes da publicação.'}
|
||||
</p>
|
||||
{plan.scan?.files.map((s) => (
|
||||
<p key={s.sha256}>
|
||||
{s.name}: {s.scan.result} · {s.scan.engine}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
<label className="block" htmlFor="economic-reason">
|
||||
Justificação desta operação
|
||||
</label>
|
||||
<textarea
|
||||
id="economic-reason"
|
||||
className={control}
|
||||
value={reason}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
<label className="my-3 block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={confirm}
|
||||
onChange={(e) => setConfirm(e.target.checked)}
|
||||
/>{' '}
|
||||
Confirmo somente a ação selecionada para este lote.
|
||||
</label>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{(Object.keys(labels) as Operation[]).map((operation) => (
|
||||
<section className="rounded border p-3" key={operation}>
|
||||
<h2 className="font-semibold">{labels[operation]}</h2>
|
||||
<p>
|
||||
{operation === 'schema'
|
||||
? 'Migration nominal, sem importar dados.'
|
||||
: operation === 'import'
|
||||
? 'Apenas ausências, privadamente; repetição sem duplicações.'
|
||||
: operation === 'publish'
|
||||
? 'Expor apenas as referências do manifesto. Não divulga relações de investimentos.'
|
||||
: 'Retirada expressa e auditada; preserva UUID, decisões e recuperação histórica.'}
|
||||
</p>
|
||||
<p>
|
||||
Backup/restauro:{' '}
|
||||
{plan.operations[operation].backupDate ??
|
||||
(plan.operations[operation].evidence_mode ===
|
||||
'isolated_QA'
|
||||
? 'Ensaio QA isolado'
|
||||
: 'prova própria ainda necessária')}
|
||||
</p>
|
||||
{plan.operations[operation].reasons.map((r) => (
|
||||
<p className="text-sm" key={r}>
|
||||
{r}
|
||||
</p>
|
||||
))}
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
busy ||
|
||||
!confirm ||
|
||||
reason.trim().length < 20 ||
|
||||
!plan.operations[operation].ready
|
||||
}
|
||||
onClick={() => perform(operation)}
|
||||
>
|
||||
{labels[operation]}
|
||||
</button>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
{error && (
|
||||
<p className="my-3" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{receipt && (
|
||||
<section className="my-4" aria-live="polite">
|
||||
<h2 className="text-lg font-semibold">
|
||||
Recibo da operação
|
||||
</h2>
|
||||
<pre className="overflow-auto text-sm break-all whitespace-pre-wrap">
|
||||
{JSON.stringify(receipt, null, 2)}
|
||||
</pre>
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || !last.current}
|
||||
onClick={() =>
|
||||
last.current &&
|
||||
perform(last.current.operation, true)
|
||||
}
|
||||
>
|
||||
Repetir pedido anterior, sem duplicar
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
<section className="mt-4">
|
||||
<h2 className="text-lg font-semibold">
|
||||
Referências previstas e recuperadas
|
||||
</h2>
|
||||
{plan.rows.map((r) => (
|
||||
<p key={r.id}>
|
||||
{r.code}: {r.status} ·{' '}
|
||||
{r.current_visibility ?? 'a inserir privadamente'}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
<p className="mt-4">
|
||||
Reversão após uso é parcial e compatível: conservar
|
||||
schema/dados, fontes funcionais e build de compatibilidade.
|
||||
Trocar código não retira publicação automaticamente.
|
||||
</p>
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Head } from "@inertiajs/react";
|
||||
import { useRef, useState, type FormEvent } from "react";
|
||||
import FiscalQaPreview from "@/components/fiscal-qa-preview";
|
||||
import { readVersionedArithmeticReportReference } from "@/lib/simulation-form";
|
||||
import { Head } from '@inertiajs/react';
|
||||
import { useRef, useState, type FormEvent } from 'react';
|
||||
import FiscalQaPreview from '@/components/fiscal-qa-preview';
|
||||
import { readVersionedArithmeticReportReference } from '@/lib/simulation-form';
|
||||
import {
|
||||
isApiSimulationCreateResponseV1,
|
||||
isApiSimulationReadResponseV1,
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
isApiSimulationResultSnapshotV1,
|
||||
type ApiSimulationExecutionV1,
|
||||
type ApiSimulationHistoryEntryV1,
|
||||
} from "@/lib/simulation-contract";
|
||||
} from '@/lib/simulation-contract';
|
||||
|
||||
class ReviewOperationError extends Error {}
|
||||
|
||||
@@ -19,9 +19,9 @@ export default function FiscalQaReview({
|
||||
}: {
|
||||
rule: { id: string; code: string; version: number };
|
||||
}) {
|
||||
const [base, setBase] = useState("");
|
||||
const [date, setDate] = useState("");
|
||||
const [currency, setCurrency] = useState("");
|
||||
const [base, setBase] = useState('');
|
||||
const [date, setDate] = useState('');
|
||||
const [currency, setCurrency] = useState('');
|
||||
const [declared, setDeclared] = useState(false);
|
||||
const [selected, setSelected] = useState<ApiSimulationExecutionV1 | null>(
|
||||
null,
|
||||
@@ -33,7 +33,7 @@ export default function FiscalQaReview({
|
||||
snapshot: unknown;
|
||||
} | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState("");
|
||||
const [message, setMessage] = useState('');
|
||||
const key = useRef<string | null>(null);
|
||||
const gate = useRef(false);
|
||||
const changed = () => {
|
||||
@@ -41,12 +41,12 @@ export default function FiscalQaReview({
|
||||
};
|
||||
const statusLabel = (status: string) =>
|
||||
({
|
||||
queued: "na fila",
|
||||
running: "em processamento",
|
||||
completed: "concluída",
|
||||
failed: "não concluída",
|
||||
cancelled: "cancelada",
|
||||
})[status] ?? "recebida";
|
||||
queued: 'na fila',
|
||||
running: 'em processamento',
|
||||
completed: 'concluída',
|
||||
failed: 'não concluída',
|
||||
cancelled: 'cancelada',
|
||||
})[status] ?? 'recebida';
|
||||
|
||||
async function request(
|
||||
url: string,
|
||||
@@ -54,20 +54,20 @@ export default function FiscalQaReview({
|
||||
): Promise<unknown> {
|
||||
const xsrf = decodeURIComponent(
|
||||
document.cookie
|
||||
.split("; ")
|
||||
.find((part) => part.startsWith("XSRF-TOKEN="))
|
||||
?.slice(11) ?? "",
|
||||
.split('; ')
|
||||
.find((part) => part.startsWith('XSRF-TOKEN='))
|
||||
?.slice(11) ?? '',
|
||||
);
|
||||
const response = await fetch(url, {
|
||||
method: body ? "POST" : "GET",
|
||||
credentials: "same-origin",
|
||||
method: body ? 'POST' : 'GET',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
Accept: 'application/json',
|
||||
...(body
|
||||
? {
|
||||
"Content-Type": "application/json",
|
||||
"X-XSRF-TOKEN": xsrf,
|
||||
"Idempotency-Key": key.current!,
|
||||
'Content-Type': 'application/json',
|
||||
'X-XSRF-TOKEN': xsrf,
|
||||
'Idempotency-Key': key.current!,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
@@ -76,8 +76,8 @@ export default function FiscalQaReview({
|
||||
if (!response.ok)
|
||||
throw new ReviewOperationError(
|
||||
response.status === 401 || response.status === 419
|
||||
? "A sessão expirou. Inicie sessão e consulte o histórico antes de voltar a calcular."
|
||||
: "Não foi possível concluir a operação. Reveja as entradas e consulte o histórico antes de tentar novamente.",
|
||||
? 'A sessão expirou. Inicie sessão e consulte o histórico antes de voltar a calcular.'
|
||||
: 'Não foi possível concluir a operação. Reveja as entradas e consulte o histórico antes de tentar novamente.',
|
||||
);
|
||||
return response.json();
|
||||
}
|
||||
@@ -86,15 +86,15 @@ export default function FiscalQaReview({
|
||||
if (gate.current) return;
|
||||
gate.current = true;
|
||||
setBusy(true);
|
||||
setMessage("");
|
||||
setMessage('');
|
||||
try {
|
||||
await work();
|
||||
} catch (cause) {
|
||||
console.error("[fiscal-qa-review]", cause);
|
||||
console.error('[fiscal-qa-review]', cause);
|
||||
setMessage(
|
||||
cause instanceof ReviewOperationError
|
||||
? cause.message
|
||||
: "Não foi possível concluir a ligação ao servidor. Consulte o histórico antes de tentar novamente.",
|
||||
: 'Não foi possível concluir a ligação ao servidor. Consulte o histórico antes de tentar novamente.',
|
||||
);
|
||||
} finally {
|
||||
gate.current = false;
|
||||
@@ -106,7 +106,7 @@ export default function FiscalQaReview({
|
||||
const payload = await request(`/api/v1/simulations/${id}`);
|
||||
if (!isApiSimulationReadResponseV1(payload))
|
||||
throw new ReviewOperationError(
|
||||
"O resultado guardado tem formato incompatível.",
|
||||
'O resultado guardado tem formato incompatível.',
|
||||
);
|
||||
setSelected(payload.data);
|
||||
setReport(null);
|
||||
@@ -123,38 +123,38 @@ export default function FiscalQaReview({
|
||||
base,
|
||||
currency,
|
||||
reference_date: date,
|
||||
operation: "internal_general_net",
|
||||
operation: 'internal_general_net',
|
||||
},
|
||||
);
|
||||
if (!isApiSimulationCreateResponseV1(payload))
|
||||
throw new ReviewOperationError(
|
||||
"A execução devolveu um formato incompatível.",
|
||||
'A execução devolveu um formato incompatível.',
|
||||
);
|
||||
let simulation = await recover(payload.data.id);
|
||||
for (
|
||||
let attempt = 0;
|
||||
attempt < 10 &&
|
||||
["queued", "running"].includes(simulation.status);
|
||||
['queued', 'running'].includes(simulation.status);
|
||||
attempt++
|
||||
) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
simulation = await recover(payload.data.id);
|
||||
}
|
||||
setMessage(
|
||||
simulation.status === "completed"
|
||||
? "Execução concluída e gravada no histórico. Pode recuperar esta execução e consultar o relatório guardado."
|
||||
: "A execução foi gravada e continua pendente. Consulte o histórico para a recuperar.",
|
||||
simulation.status === 'completed'
|
||||
? 'Execução concluída e gravada no histórico. Pode recuperar esta execução e consultar o relatório guardado.'
|
||||
: 'A execução foi gravada e continua pendente. Consulte o histórico para a recuperar.',
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async function loadHistory() {
|
||||
const payload = await request(
|
||||
"/api/v1/simulations/history?per_page=10",
|
||||
'/api/v1/simulations/history?per_page=10',
|
||||
);
|
||||
if (!isApiSimulationHistoryResponseV1(payload))
|
||||
throw new ReviewOperationError(
|
||||
"O histórico devolveu um formato incompatível.",
|
||||
'O histórico devolveu um formato incompatível.',
|
||||
);
|
||||
setHistory(payload.data);
|
||||
}
|
||||
@@ -163,7 +163,7 @@ export default function FiscalQaReview({
|
||||
const reference = readVersionedArithmeticReportReference(selected);
|
||||
if (!selected || !reference)
|
||||
throw new ReviewOperationError(
|
||||
"O relatório ainda não está disponível para esta execução.",
|
||||
'O relatório ainda não está disponível para esta execução.',
|
||||
);
|
||||
const payload = (await request(
|
||||
`/api/v1/simulations/${selected.id}/reports/${reference.id}`,
|
||||
@@ -180,7 +180,7 @@ export default function FiscalQaReview({
|
||||
!isApiSimulationResultSnapshotV1(payload.data.report_snapshot)
|
||||
) {
|
||||
throw new ReviewOperationError(
|
||||
"O relatório guardado não corresponde à referência desta execução.",
|
||||
'O relatório guardado não corresponde à referência desta execução.',
|
||||
);
|
||||
}
|
||||
setReport({
|
||||
@@ -190,9 +190,9 @@ export default function FiscalQaReview({
|
||||
});
|
||||
}
|
||||
|
||||
const field = "mt-1 block w-full rounded border border-slate-400 p-2";
|
||||
const field = 'mt-1 block w-full rounded border border-slate-400 p-2';
|
||||
const button =
|
||||
"rounded border border-emerald-800 px-4 py-2 font-semibold disabled:opacity-50";
|
||||
'rounded border border-emerald-800 px-4 py-2 font-semibold disabled:opacity-50';
|
||||
return (
|
||||
<main className="mx-auto max-w-4xl space-y-5 p-6">
|
||||
<Head title="Revisão do lote IVA em QA" />
|
||||
@@ -287,13 +287,13 @@ export default function FiscalQaReview({
|
||||
>
|
||||
<h2 className="font-semibold">Execução seleccionada</h2>
|
||||
<p className="break-all">
|
||||
ID: {selected.id} · estado:{" "}
|
||||
ID: {selected.id} · estado:{' '}
|
||||
{statusLabel(selected.status)}
|
||||
</p>
|
||||
<FiscalQaPreview snapshot={selected.result_snapshot} />
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || selected.status !== "completed"}
|
||||
disabled={busy || selected.status !== 'completed'}
|
||||
onClick={() => void action(loadReport)}
|
||||
>
|
||||
Consultar relatório guardado
|
||||
@@ -313,9 +313,9 @@ export default function FiscalQaReview({
|
||||
{history.map((entry) => (
|
||||
<li
|
||||
key={entry.id}
|
||||
className="break-all rounded border p-3"
|
||||
className="rounded border p-3 break-all"
|
||||
>
|
||||
{entry.id} · {statusLabel(entry.status)}{" "}
|
||||
{entry.id} · {statusLabel(entry.status)}{' '}
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy}
|
||||
@@ -323,7 +323,7 @@ export default function FiscalQaReview({
|
||||
void action(async () => {
|
||||
await recover(entry.id);
|
||||
setMessage(
|
||||
"Execução recuperada do histórico, sem recalcular.",
|
||||
'Execução recuperada do histórico, sem recalcular.',
|
||||
);
|
||||
})
|
||||
}
|
||||
|
||||
@@ -233,7 +233,13 @@ export default function Opportunities({
|
||||
<p>Atualizado: {r.updated_at}</p>
|
||||
<div className="flex flex-wrap gap-4">
|
||||
<Link href={`${basePath}/${r.id}/view`}>Ver</Link>
|
||||
{r.can_promote && <Link href={`/minhas-oportunidades/${r.id}/divulgacao`}>Divulgação promocional</Link>}
|
||||
{r.can_promote && (
|
||||
<Link
|
||||
href={`/minhas-oportunidades/${r.id}/divulgacao`}
|
||||
>
|
||||
Divulgação promocional
|
||||
</Link>
|
||||
)}
|
||||
{r.can_edit !== false && (
|
||||
<Link href={`${basePath}/${r.id}/edit`}>
|
||||
{r.deleted_at || r.status === 'archived'
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import {ProactiveInvestmentEditor,newProactive,type ProactiveAnalysis,type ProactiveOptions} from '@/components/proactive-investment';
|
||||
import { inputText } from '../../lib/input-text.ts';
|
||||
import {
|
||||
ProactiveInvestmentEditor,
|
||||
newProactive,
|
||||
type ProactiveAnalysis,
|
||||
type ProactiveOptions,
|
||||
} from '@/components/proactive-investment';
|
||||
import { ClassificationReview } from '@/components/opportunity-classification';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { valueText } from '@/lib/value-text';
|
||||
@@ -42,7 +48,13 @@ export default function OpportunityDraft({
|
||||
}: {
|
||||
record: Entry | null;
|
||||
proactiveOptions?: ProactiveOptions;
|
||||
proactiveHistory?: {version:number;at:string;state:string;problem:string;confirmation:string}[];
|
||||
proactiveHistory?: {
|
||||
version: number;
|
||||
at: string;
|
||||
state: string;
|
||||
problem: string;
|
||||
confirmation: string;
|
||||
}[];
|
||||
values: Values;
|
||||
etag: string | null;
|
||||
readOnly: boolean;
|
||||
@@ -140,11 +152,20 @@ export default function OpportunityDraft({
|
||||
auth: { user: { id: number } };
|
||||
canEditDraft?: boolean;
|
||||
}>().props;
|
||||
const proactiveEntryUrl=usePage().url;
|
||||
const uniquePromoterContext=profileAccess?.contexts.length===1?profileAccess.contexts[0]:undefined;
|
||||
const proactiveEntryUrl = usePage().url;
|
||||
const uniquePromoterContext =
|
||||
profileAccess?.contexts.length === 1
|
||||
? profileAccess.contexts[0]
|
||||
: undefined;
|
||||
const [data, setData] = useState<Values>({
|
||||
...values,
|
||||
...(!record && !values.proactive && new URLSearchParams(proactiveEntryUrl.split('?')[1]??'').get('analysis')==='proactive' ? {proactive:newProactive()} : {}),
|
||||
...(!record &&
|
||||
!values.proactive &&
|
||||
new URLSearchParams(proactiveEntryUrl.split('?')[1] ?? '').get(
|
||||
'analysis',
|
||||
) === 'proactive'
|
||||
? { proactive: newProactive() }
|
||||
: {}),
|
||||
...(profileMode
|
||||
? {
|
||||
organization_id: record
|
||||
@@ -174,11 +195,18 @@ export default function OpportunityDraft({
|
||||
const unavailable = Boolean(
|
||||
record?.deleted_at || record?.status === 'archived',
|
||||
);
|
||||
const hasCanonicalPreparation = profileMode && canonicalOptions && Boolean(data.opportunity_category) && !data.proactive;
|
||||
const hasCanonicalPreparation =
|
||||
profileMode &&
|
||||
canonicalOptions &&
|
||||
Boolean(data.opportunity_category) &&
|
||||
!data.proactive;
|
||||
const archiveAvailable = Boolean(usePage().props.opportunityManagement);
|
||||
const set = (key: string, value: string) =>
|
||||
setData((d) => ({ ...d, [key]: value }));
|
||||
async function send(action: 'save' | 'delete' | 'archive' | 'restore', resourcesGroup?: string) {
|
||||
async function send(
|
||||
action: 'save' | 'delete' | 'archive' | 'restore',
|
||||
resourcesGroup?: string,
|
||||
) {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
setErrors({});
|
||||
@@ -226,10 +254,25 @@ export default function OpportunityDraft({
|
||||
}
|
||||
setMessage(result.message);
|
||||
if (result.etag) setToken(result.etag);
|
||||
if (resourcesGroup) router.visit(`${basePath}/${record?.id ?? result.id}/resources?return_group=${encodeURIComponent(resourcesGroup)}`);
|
||||
else if (!record) router.visit(`${basePath}/${result.id}/edit${window.location.hash.startsWith('#fill-') ? window.location.hash : ''}`);
|
||||
if (resourcesGroup)
|
||||
router.visit(
|
||||
`${basePath}/${record?.id ?? result.id}/resources?return_group=${encodeURIComponent(resourcesGroup)}`,
|
||||
);
|
||||
else if (!record)
|
||||
router.visit(
|
||||
`${basePath}/${result.id}/edit${window.location.hash.startsWith('#fill-') ? window.location.hash : ''}`,
|
||||
);
|
||||
else if (action !== 'save') router.reload();
|
||||
else if (profileMode) router.reload({only:['canonicalResponse','etag','history','workflowState','profileContext']});
|
||||
else if (profileMode)
|
||||
router.reload({
|
||||
only: [
|
||||
'canonicalResponse',
|
||||
'etag',
|
||||
'history',
|
||||
'workflowState',
|
||||
'profileContext',
|
||||
],
|
||||
});
|
||||
} catch {
|
||||
setMessage(
|
||||
'Resposta indisponível. Os dados foram preservados; confira o registo no servidor antes de repetir.',
|
||||
@@ -242,7 +285,10 @@ export default function OpportunityDraft({
|
||||
'[data-association-index][aria-invalid="true"]',
|
||||
);
|
||||
if (invalidAssociation) invalidAssociation.focus();
|
||||
else document.getElementById('opportunity-result')?.focus({preventScroll:true});
|
||||
else
|
||||
document
|
||||
.getElementById('opportunity-result')
|
||||
?.focus({ preventScroll: true });
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -255,13 +301,42 @@ export default function OpportunityDraft({
|
||||
}
|
||||
>
|
||||
{!profileMode && <Link href={basePath}>Voltar à gestão</Link>}
|
||||
{promotionHref && <Link className="ml-3 underline" href={promotionHref}>Divulgação promocional — Em preparação</Link>}
|
||||
{promotionHref && (
|
||||
<Link className="ml-3 underline" href={promotionHref}>
|
||||
Divulgação promocional — Em preparação
|
||||
</Link>
|
||||
)}
|
||||
{!!profileContext?.corridor_agribusiness && (
|
||||
<section className="my-4 space-y-2 rounded border p-4">
|
||||
<h2 className="font-semibold">Origem e enquadramento da oportunidade</h2>
|
||||
<p>{valueText((profileContext.corridor_agribusiness as Record<string, unknown>).corridor)}</p>
|
||||
<p>Fonte: {valueText((profileContext.corridor_agribusiness as Record<string, unknown>).source)}</p>
|
||||
<p>Em preparação. O corredor indicado na fonte não confirma implantação, promotor, viabilidade ou financiamento. Complete a ficha e reveja a prévia antes de divulgar.</p>
|
||||
<h2 className="font-semibold">
|
||||
Origem e enquadramento da oportunidade
|
||||
</h2>
|
||||
<p>
|
||||
{valueText(
|
||||
(
|
||||
profileContext.corridor_agribusiness as Record<
|
||||
string,
|
||||
unknown
|
||||
>
|
||||
).corridor,
|
||||
)}
|
||||
</p>
|
||||
<p>
|
||||
Fonte:{' '}
|
||||
{valueText(
|
||||
(
|
||||
profileContext.corridor_agribusiness as Record<
|
||||
string,
|
||||
unknown
|
||||
>
|
||||
).source,
|
||||
)}
|
||||
</p>
|
||||
<p>
|
||||
Em preparação. O corredor indicado na fonte não confirma
|
||||
implantação, promotor, viabilidade ou financiamento.
|
||||
Complete a ficha e reveja a prévia antes de divulgar.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
{record && (
|
||||
@@ -277,7 +352,9 @@ export default function OpportunityDraft({
|
||||
aria-label="Disponibilidade por modalidade"
|
||||
className="rounded border p-3"
|
||||
>
|
||||
<summary className="cursor-pointer font-medium">Modalidades disponíveis e condições de submissão</summary>
|
||||
<summary className="cursor-pointer font-medium">
|
||||
Modalidades disponíveis e condições de submissão
|
||||
</summary>
|
||||
<p>
|
||||
Seis categorias base: projeto de investimento,
|
||||
imobiliário, fundiário, venda de negócio, parceria e
|
||||
@@ -336,7 +413,8 @@ export default function OpportunityDraft({
|
||||
}));
|
||||
}}
|
||||
>
|
||||
{(profileAccess?.internalPromoter || !uniquePromoterContext) && (
|
||||
{(profileAccess?.internalPromoter ||
|
||||
!uniquePromoterContext) && (
|
||||
<option value="|">
|
||||
Selecionar o promotor real da oportunidade
|
||||
</option>
|
||||
@@ -481,13 +559,132 @@ export default function OpportunityDraft({
|
||||
void send('save');
|
||||
}}
|
||||
>
|
||||
{profileMode&&Boolean(data.proactive)&&<fieldset disabled={busy||readOnly||unavailable} className="space-y-3 rounded border p-4"><legend>Contexto existente da análise</legend>
|
||||
<Field label="Título da análise"><input aria-label="Título da análise" className={control} value={String((data.canonical as Record<string,unknown>|undefined)?.official_title??data.title??'')} onChange={e=>{const title=e.target.value;setData(d=>({...d,title,...(d.canonical&&Object.prototype.hasOwnProperty.call(d.canonical,'official_title')?{canonical:{...(d.canonical as Record<string,unknown>),official_title:title}}:{})}));}}/></Field>
|
||||
<Field label="Sector da análise"><select aria-label="Sector da análise" className={control} value={String(data.sector_id??'')} onChange={e=>setData(d=>({...d,sector_id:e.target.value,...(d.canonical?{canonical:{...(d.canonical as Record<string,unknown>),sector_id:Number(e.target.value)||null}}:{})}))}><option value="">Por determinar</option>{sectors.map(s=><option key={s.id} value={s.id}>{s.name}</option>)}</select></Field>
|
||||
<p>Seleccione apenas o nível territorial conhecido; não exige coordenadas, montante ou promotor.</p>
|
||||
{(['province_id','district_id','admin_post_id','locality_id']as const).map((key,index)=><TerritoryLevel key={`proactive-${key}-${path[index-1]?.id??''}`} index={index} parent={path[index-1]?.id??''} selected={path[index]} endpoint="/minhas-oportunidades/territory-options" fieldError={errors[key]} onChange={value=>{const next=[...path.slice(0,index),...(value?[value]:[])];setPath(next);setData(d=>({...d,province_id:next[0]?.id??'',district_id:next[1]?.id??'',admin_post_id:next[2]?.id??'',locality_id:next[3]?.id??''}));}}/>)}
|
||||
</fieldset>}
|
||||
<fieldset disabled={busy || readOnly || unavailable}><ProactiveInvestmentEditor value={data.proactive as ProactiveAnalysis|undefined} onChange={v=>setData(d=>({...d,proactive:v}))} options={proactiveOptions} history={proactiveHistory} territoryId={path.at(-1)?.id} recordId={record?.id}/></fieldset>
|
||||
{profileMode && Boolean(data.proactive) && (
|
||||
<fieldset
|
||||
disabled={busy || readOnly || unavailable}
|
||||
className="space-y-3 rounded border p-4"
|
||||
>
|
||||
<legend>Contexto existente da análise</legend>
|
||||
<Field label="Título da análise">
|
||||
<input
|
||||
aria-label="Título da análise"
|
||||
className={control}
|
||||
value={inputText(
|
||||
(
|
||||
data.canonical as
|
||||
| Record<string, unknown>
|
||||
| undefined
|
||||
)?.official_title ??
|
||||
data.title ??
|
||||
'',
|
||||
)}
|
||||
onChange={(e) => {
|
||||
const title = e.target.value;
|
||||
setData((d) => ({
|
||||
...d,
|
||||
title,
|
||||
...(d.canonical &&
|
||||
Object.prototype.hasOwnProperty.call(
|
||||
d.canonical,
|
||||
'official_title',
|
||||
)
|
||||
? {
|
||||
canonical: {
|
||||
...(d.canonical as Record<
|
||||
string,
|
||||
unknown
|
||||
>),
|
||||
official_title: title,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Sector da análise">
|
||||
<select
|
||||
aria-label="Sector da análise"
|
||||
className={control}
|
||||
value={inputText(data.sector_id ?? '')}
|
||||
onChange={(e) =>
|
||||
setData((d) => ({
|
||||
...d,
|
||||
sector_id: e.target.value,
|
||||
...(d.canonical
|
||||
? {
|
||||
canonical: {
|
||||
...(d.canonical as Record<
|
||||
string,
|
||||
unknown
|
||||
>),
|
||||
sector_id:
|
||||
Number(
|
||||
e.target.value,
|
||||
) || null,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
}))
|
||||
}
|
||||
>
|
||||
<option value="">Por determinar</option>
|
||||
{sectors.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<p>
|
||||
Seleccione apenas o nível territorial conhecido; não
|
||||
exige coordenadas, montante ou promotor.
|
||||
</p>
|
||||
{(
|
||||
[
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
] as const
|
||||
).map((key, index) => (
|
||||
<TerritoryLevel
|
||||
key={`proactive-${key}-${path[index - 1]?.id ?? ''}`}
|
||||
index={index}
|
||||
parent={path[index - 1]?.id ?? ''}
|
||||
selected={path[index]}
|
||||
endpoint="/minhas-oportunidades/territory-options"
|
||||
fieldError={errors[key]}
|
||||
onChange={(value) => {
|
||||
const next = [
|
||||
...path.slice(0, index),
|
||||
...(value ? [value] : []),
|
||||
];
|
||||
setPath(next);
|
||||
setData((d) => ({
|
||||
...d,
|
||||
province_id: next[0]?.id ?? '',
|
||||
district_id: next[1]?.id ?? '',
|
||||
admin_post_id: next[2]?.id ?? '',
|
||||
locality_id: next[3]?.id ?? '',
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</fieldset>
|
||||
)}
|
||||
<fieldset disabled={busy || readOnly || unavailable}>
|
||||
<ProactiveInvestmentEditor
|
||||
value={data.proactive as ProactiveAnalysis | undefined}
|
||||
onChange={(v) =>
|
||||
setData((d) => ({ ...d, proactive: v }))
|
||||
}
|
||||
options={proactiveOptions}
|
||||
history={proactiveHistory}
|
||||
territoryId={path.at(-1)?.id}
|
||||
recordId={record?.id}
|
||||
/>
|
||||
</fieldset>
|
||||
{!profileMode && (
|
||||
<fieldset
|
||||
disabled={busy || readOnly || unavailable}
|
||||
@@ -823,18 +1020,20 @@ export default function OpportunityDraft({
|
||||
)}
|
||||
{!readOnly && (
|
||||
<>
|
||||
{!hasCanonicalPreparation && <Field
|
||||
label="Motivo da alteração"
|
||||
error={errors.reason}
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
/>
|
||||
</Field>}
|
||||
{!hasCanonicalPreparation && (
|
||||
<Field
|
||||
label="Motivo da alteração"
|
||||
error={errors.reason}
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
{!unavailable && !hasCanonicalPreparation && (
|
||||
<button className={button} disabled={busy}>
|
||||
Guardar rascunho
|
||||
@@ -893,110 +1092,153 @@ export default function OpportunityDraft({
|
||||
</>
|
||||
)}
|
||||
</form>
|
||||
{record && (!profileMode || readOnly || unavailable || !canonicalOptions || !data.opportunity_category) && (
|
||||
<Link
|
||||
href={
|
||||
resourcesInstalled
|
||||
? `${basePath}/${record.id}/resources`
|
||||
: '/management/opportunity-resources-install'
|
||||
}
|
||||
>
|
||||
{resourcesInstalled
|
||||
? 'Imagens, documentos e localizações'
|
||||
: 'Plano de ativação de imagens, documentos e localizações'}
|
||||
</Link>
|
||||
)}
|
||||
{record &&
|
||||
(!profileMode ||
|
||||
readOnly ||
|
||||
unavailable ||
|
||||
!canonicalOptions ||
|
||||
!data.opportunity_category) && (
|
||||
<Link
|
||||
href={
|
||||
resourcesInstalled
|
||||
? `${basePath}/${record.id}/resources`
|
||||
: '/management/opportunity-resources-install'
|
||||
}
|
||||
>
|
||||
{resourcesInstalled
|
||||
? 'Imagens, documentos e localizações'
|
||||
: 'Plano de ativação de imagens, documentos e localizações'}
|
||||
</Link>
|
||||
)}
|
||||
{record && !profileMode && (
|
||||
<Link href={`${basePath}/${record.id}/context`}>
|
||||
Associações territoriais e produtivas existentes
|
||||
</Link>
|
||||
)}
|
||||
{profileMode && canonicalOptions && Boolean(data.opportunity_category) && (
|
||||
<section>
|
||||
{record && !readOnly && !unavailable && (
|
||||
<details><summary className="cursor-pointer font-medium">Acrescentar um contacto à oportunidade</summary><OpportunityContactForm
|
||||
id={record.id}
|
||||
etag={token ?? ''}
|
||||
{profileMode &&
|
||||
canonicalOptions &&
|
||||
Boolean(data.opportunity_category) && (
|
||||
<section>
|
||||
{record && !readOnly && !unavailable && (
|
||||
<details>
|
||||
<summary className="cursor-pointer font-medium">
|
||||
Acrescentar um contacto à oportunidade
|
||||
</summary>
|
||||
<OpportunityContactForm
|
||||
id={record.id}
|
||||
etag={token ?? ''}
|
||||
organization={
|
||||
(data.organization_id ?? null) as
|
||||
| string
|
||||
| null
|
||||
}
|
||||
investors={
|
||||
canonicalOptions.contactInvestors ?? []
|
||||
}
|
||||
disabled={busy || !token}
|
||||
onSaved={(contact) => {
|
||||
setSavedContacts((prior) => [
|
||||
...prior.filter(
|
||||
(row) => row.id !== contact.id,
|
||||
),
|
||||
contact,
|
||||
]);
|
||||
setData((prior) => ({
|
||||
...prior,
|
||||
canonical: {
|
||||
...(prior.canonical as Record<
|
||||
string,
|
||||
unknown
|
||||
>),
|
||||
internal_contact_id: contact.id,
|
||||
},
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
</details>
|
||||
)}
|
||||
<OpportunityCanonicalFields
|
||||
value={
|
||||
(data.canonical ?? {}) as Record<
|
||||
string,
|
||||
unknown
|
||||
>
|
||||
}
|
||||
onChange={(v) =>
|
||||
setData((d) => ({ ...d, canonical: v }))
|
||||
}
|
||||
options={{
|
||||
...canonicalOptions,
|
||||
contacts: [
|
||||
...canonicalOptions.contacts.filter(
|
||||
(row) =>
|
||||
!savedContacts.some(
|
||||
(saved) => saved.id === row.id,
|
||||
),
|
||||
),
|
||||
...savedContacts,
|
||||
],
|
||||
}}
|
||||
errors={errors}
|
||||
missingPaths={
|
||||
canonicalResponse?.completion.missing_paths
|
||||
}
|
||||
category={valueText(
|
||||
data.opportunity_category ?? '',
|
||||
)}
|
||||
organization={
|
||||
(data.organization_id ?? null) as string | null
|
||||
}
|
||||
investors={canonicalOptions.contactInvestors ?? []}
|
||||
disabled={busy || !token}
|
||||
onSaved={(contact) => {
|
||||
setSavedContacts((prior) => [
|
||||
...prior.filter(
|
||||
(row) => row.id !== contact.id,
|
||||
),
|
||||
contact,
|
||||
]);
|
||||
setData((prior) => ({
|
||||
...prior,
|
||||
canonical: {
|
||||
...(prior.canonical as Record<
|
||||
string,
|
||||
unknown
|
||||
>),
|
||||
internal_contact_id: contact.id,
|
||||
},
|
||||
}));
|
||||
}}
|
||||
/></details>
|
||||
)}
|
||||
<OpportunityCanonicalFields
|
||||
value={
|
||||
(data.canonical ?? {}) as Record<string, unknown>
|
||||
}
|
||||
onChange={(v) =>
|
||||
setData((d) => ({ ...d, canonical: v }))
|
||||
}
|
||||
options={{
|
||||
...canonicalOptions,
|
||||
contacts: [
|
||||
...canonicalOptions.contacts.filter(
|
||||
(row) =>
|
||||
!savedContacts.some(
|
||||
(saved) => saved.id === row.id,
|
||||
),
|
||||
),
|
||||
...savedContacts,
|
||||
],
|
||||
}}
|
||||
errors={errors}
|
||||
missingPaths={canonicalResponse?.completion.missing_paths}
|
||||
category={valueText(data.opportunity_category ?? '')}
|
||||
organization={
|
||||
(data.organization_id ?? null) as string | null
|
||||
}
|
||||
actorId={auth.user.id}
|
||||
sectors={sectors}
|
||||
disabled={busy || readOnly || unavailable}
|
||||
onOpenResources={!readOnly && !unavailable && resourcesInstalled ? (group) => void send('save',group) : undefined}
|
||||
/>
|
||||
{!readOnly && !unavailable && hasCanonicalPreparation && (
|
||||
<div className="sticky bottom-0 space-y-3 rounded border bg-background p-4 shadow-sm">
|
||||
<Field label="O que alterou nesta preparação" error={errors.reason}>
|
||||
<textarea className={control} value={reason} onChange={(event) => setReason(event.target.value)} minLength={20} maxLength={1000} />
|
||||
</Field>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() => void send('save')}
|
||||
>
|
||||
Guardar preparação
|
||||
</button>
|
||||
<p className="text-sm">Pode guardar incompleto e continuar mais tarde em Minhas oportunidades.</p>
|
||||
</div>
|
||||
)}
|
||||
{Object.entries(errors)
|
||||
.filter(([key]) => key.startsWith('canonical'))
|
||||
.map(([key, msg]) => (
|
||||
<p key={key} role="alert">
|
||||
{key}: {msg}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
actorId={auth.user.id}
|
||||
sectors={sectors}
|
||||
disabled={busy || readOnly || unavailable}
|
||||
onOpenResources={
|
||||
!readOnly && !unavailable && resourcesInstalled
|
||||
? (group) => void send('save', group)
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
{!readOnly &&
|
||||
!unavailable &&
|
||||
hasCanonicalPreparation && (
|
||||
<div className="bg-background sticky bottom-0 space-y-3 rounded border p-4 shadow-sm">
|
||||
<Field
|
||||
label="O que alterou nesta preparação"
|
||||
error={errors.reason}
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
value={reason}
|
||||
onChange={(event) =>
|
||||
setReason(event.target.value)
|
||||
}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
/>
|
||||
</Field>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() => void send('save')}
|
||||
>
|
||||
Guardar preparação
|
||||
</button>
|
||||
<p className="text-sm">
|
||||
Pode guardar incompleto e continuar mais
|
||||
tarde em Minhas oportunidades.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{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>
|
||||
|
||||
@@ -124,7 +124,9 @@ export default function Install({
|
||||
: 'Aplicar plano de gestão'}
|
||||
</button>
|
||||
{extension && !operationKey && (
|
||||
<p role="alert">Atualize a prévia para obter a chave desta operação.</p>
|
||||
<p role="alert">
|
||||
Atualize a prévia para obter a chave desta operação.
|
||||
</p>
|
||||
)}
|
||||
{!ready && (
|
||||
<p>
|
||||
|
||||
@@ -1,81 +1,476 @@
|
||||
import {ProactivePublicationFields,ProactiveSummary,newPublicProactive,type ProactivePublic,type ProactiveEvidence,type ProactiveOptions} from '@/components/proactive-investment';
|
||||
import {
|
||||
ProactivePublicationFields,
|
||||
ProactiveSummary,
|
||||
newPublicProactive,
|
||||
type ProactivePublic,
|
||||
type ProactiveEvidence,
|
||||
type ProactiveOptions,
|
||||
} from '@/components/proactive-investment';
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { profileJson, ProfileValidationError } from '@/lib/profile-json';
|
||||
import { Management, Field, control, button } from './shared';
|
||||
|
||||
type Draft = {proactive_public?:ProactivePublic;proactive_reviewed?:boolean;title: string; summary: string; description: string; limitations: string; source_reference: string; edition: string; source_date: string; sector_id: number | null; territory_ids: string[]};
|
||||
type Projection = {title: string; summary: string; description: string; sector_id: number | null; maturity_label: string; territories: {id: string; label: string}[];proactive?:ProactivePublic};
|
||||
type Preview = {token: string; action: 'disclose' | 'withdraw'; projection: Projection; current: {title: string; summary: string; description: string; status: string}};
|
||||
type Draft = {
|
||||
proactive_public?: ProactivePublic;
|
||||
proactive_reviewed?: boolean;
|
||||
title: string;
|
||||
summary: string;
|
||||
description: string;
|
||||
limitations: string;
|
||||
source_reference: string;
|
||||
edition: string;
|
||||
source_date: string;
|
||||
sector_id: number | null;
|
||||
territory_ids: string[];
|
||||
};
|
||||
type Projection = {
|
||||
title: string;
|
||||
summary: string;
|
||||
description: string;
|
||||
sector_id: number | null;
|
||||
maturity_label: string;
|
||||
territories: { id: string; label: string }[];
|
||||
proactive?: ProactivePublic;
|
||||
};
|
||||
type Preview = {
|
||||
token: string;
|
||||
action: 'disclose' | 'withdraw';
|
||||
projection: Projection;
|
||||
current: {
|
||||
title: string;
|
||||
summary: string;
|
||||
description: string;
|
||||
status: string;
|
||||
};
|
||||
};
|
||||
|
||||
export default function OpportunityPromotion({proactiveEnabled=false,proactiveKind,proactiveRelations=[],proactiveEvidence=[],proactiveOptions,record, initial, etag, publicNow, reauthenticationRequired, sectors, territories, history}: {
|
||||
proactiveRelations?:{id:string;label:string;relationship:string}[];proactiveEnabled?:boolean;proactiveKind?:string;proactiveEvidence?:ProactiveEvidence[];proactiveOptions?:ProactiveOptions;
|
||||
record: {id: number; reference: string}; initial: Draft; etag: string; publicNow: boolean; reauthenticationRequired: boolean;
|
||||
sectors: {id: number; name: string}[]; territories: {id: string; name: string; location_type: string}[];
|
||||
history: {id: string; action: string; actor_user_id: number; occurred_at: string}[];
|
||||
export default function OpportunityPromotion({
|
||||
proactiveEnabled = false,
|
||||
proactiveKind,
|
||||
proactiveRelations = [],
|
||||
proactiveEvidence = [],
|
||||
proactiveOptions,
|
||||
record,
|
||||
initial,
|
||||
etag,
|
||||
publicNow,
|
||||
reauthenticationRequired,
|
||||
sectors,
|
||||
territories,
|
||||
history,
|
||||
}: {
|
||||
proactiveRelations?: { id: string; label: string; relationship: string }[];
|
||||
proactiveEnabled?: boolean;
|
||||
proactiveKind?: string;
|
||||
proactiveEvidence?: ProactiveEvidence[];
|
||||
proactiveOptions?: ProactiveOptions;
|
||||
record: { id: number; reference: string };
|
||||
initial: Draft;
|
||||
etag: string;
|
||||
publicNow: boolean;
|
||||
reauthenticationRequired: boolean;
|
||||
sectors: { id: number; name: string }[];
|
||||
territories: { id: string; name: string; location_type: string }[];
|
||||
history: {
|
||||
id: string;
|
||||
action: string;
|
||||
actor_user_id: number;
|
||||
occurred_at: string;
|
||||
}[];
|
||||
}) {
|
||||
const [draft, setDraft] = useState<Draft>({...initial, source_date: initial.source_date ?? '',...(proactiveEnabled?{proactive_public:initial.proactive_public??{...newPublicProactive(),group:proactiveKind??'ideas'},proactive_reviewed:false}:{})});
|
||||
const [draft, setDraft] = useState<Draft>({
|
||||
...initial,
|
||||
source_date: initial.source_date ?? '',
|
||||
...(proactiveEnabled
|
||||
? {
|
||||
proactive_public: initial.proactive_public ?? {
|
||||
...newPublicProactive(),
|
||||
group: proactiveKind ?? 'ideas',
|
||||
},
|
||||
proactive_reviewed: false,
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
const [preview, setPreview] = useState<Preview | null>(null);
|
||||
const [operationKey, setOperationKey] = useState(createOperationKey);
|
||||
const [reason, setReason] = useState('');
|
||||
const [confirmed, setConfirmed] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [errors, setErrors] = useState<Record<string,string>>({});
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [needsMfa, setNeedsMfa] = useState(reauthenticationRequired);
|
||||
function change<K extends keyof Draft>(key: K, value: Draft[K]) { setDraft(current => ({...current, [key]:value})); setPreview(null); setConfirmed(false); }
|
||||
function report(error: unknown) {setMessage(error instanceof Error ? error.message : 'Não foi possível concluir. A ficha anterior foi preservada.'); setErrors(error instanceof ProfileValidationError ? error.fields : {}); if(error instanceof ProfileValidationError && error.reauthenticate)setNeedsMfa(true);}
|
||||
function renewAuthentication() { router.post('/logout', {}, {onSuccess:()=>router.visit(`/minhas-oportunidades/${record.id}/divulgacao`)}); }
|
||||
function change<K extends keyof Draft>(key: K, value: Draft[K]) {
|
||||
setDraft((current) => ({ ...current, [key]: value }));
|
||||
setPreview(null);
|
||||
setConfirmed(false);
|
||||
}
|
||||
function report(error: unknown) {
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Não foi possível concluir. A ficha anterior foi preservada.',
|
||||
);
|
||||
setErrors(error instanceof ProfileValidationError ? error.fields : {});
|
||||
if (error instanceof ProfileValidationError && error.reauthenticate)
|
||||
setNeedsMfa(true);
|
||||
}
|
||||
function renewAuthentication() {
|
||||
router.post(
|
||||
'/logout',
|
||||
{},
|
||||
{
|
||||
onSuccess: () =>
|
||||
router.visit(
|
||||
`/minhas-oportunidades/${record.id}/divulgacao`,
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
async function prepare(action: 'disclose' | 'withdraw') {
|
||||
setBusy(true); setMessage(''); setErrors({}); setPreview(null); setConfirmed(false);
|
||||
try { const result = await profileJson(`/minhas-oportunidades/${record.id}/divulgacao/previa`, {...draft, etag, action}); setPreview(result); setOperationKey(createOperationKey()); }
|
||||
catch (error) { report(error); } finally { setBusy(false); }
|
||||
setBusy(true);
|
||||
setMessage('');
|
||||
setErrors({});
|
||||
setPreview(null);
|
||||
setConfirmed(false);
|
||||
try {
|
||||
const result = await profileJson(
|
||||
`/minhas-oportunidades/${record.id}/divulgacao/previa`,
|
||||
{ ...draft, etag, action },
|
||||
);
|
||||
setPreview(result);
|
||||
setOperationKey(createOperationKey());
|
||||
} catch (error) {
|
||||
report(error);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
async function publish() {
|
||||
if (!preview || !confirmed) return;
|
||||
setBusy(true); setErrors({});
|
||||
try {const result = await profileJson(`/minhas-oportunidades/${record.id}/divulgacao/confirmar`, {token:preview.token, operation_key:operationKey, reason, confirm:confirmed});
|
||||
setMessage(result.message); setPreview(null); setConfirmed(false); router.reload();
|
||||
} catch (error) { report(error); } finally {setBusy(false);}
|
||||
setBusy(true);
|
||||
setErrors({});
|
||||
try {
|
||||
const result = await profileJson(
|
||||
`/minhas-oportunidades/${record.id}/divulgacao/confirmar`,
|
||||
{
|
||||
token: preview.token,
|
||||
operation_key: operationKey,
|
||||
reason,
|
||||
confirm: confirmed,
|
||||
},
|
||||
);
|
||||
setMessage(result.message);
|
||||
setPreview(null);
|
||||
setConfirmed(false);
|
||||
router.reload();
|
||||
} catch (error) {
|
||||
report(error);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
const labels: Record<string,string> = {promotional_summary_published:'Resumo divulgado', promotional_summary_updated:'Resumo actualizado', promotional_summary_withdrawn:'Resumo retirado'};
|
||||
return <Management title={`Divulgação promocional — ${record.reference}`}>
|
||||
<Link className="underline" href={`/minhas-oportunidades/${record.id}/view`}>Voltar à oportunidade</Link>
|
||||
<p>Prepare o resumo público e reveja a prévia antes de confirmar. A divulgação fica identificada como <strong>Em preparação</strong> e não autoriza a execução do investimento. Documentos e contactos do cadastro continuam privados.</p>
|
||||
<p role="status">{publicNow ? 'Resumo actualmente divulgado.' : 'Resumo não divulgado.'} {message}</p>
|
||||
{needsMfa && <p role="alert">Entre novamente com a sua conta e MFA para confirmar esta operação. O cadastro guardado permanece disponível; a prévia ainda não confirmada terá de ser preparada novamente. <button className="underline" onClick={renewAuthentication}>Renovar entrada com MFA</button></p>}
|
||||
{Object.entries(errors).map(([key,value]) => <p role="alert" key={key}>{key}: {value}</p>)}
|
||||
<form className="space-y-4 rounded border p-5" onSubmit={e=>{e.preventDefault(); void prepare('disclose');}}>
|
||||
{proactiveEnabled&&draft.proactive_public&&<ProactivePublicationFields value={draft.proactive_public} onChange={v=>{change('proactive_public',v);change('proactive_reviewed',false);}} evidence={proactiveEvidence} relations={proactiveRelations} options={proactiveOptions} reviewed={Boolean(draft.proactive_reviewed)} onReview={v=>change('proactive_reviewed',v)}/>}
|
||||
<Field label="Título público"><input required className={control} maxLength={255} value={draft.title} onChange={e=>change('title',e.target.value)}/></Field>
|
||||
<Field label="Resumo público"><textarea required className={control} maxLength={499} value={draft.summary} onChange={e=>change('summary',e.target.value)}/></Field>
|
||||
<Field label="Descrição pública"><textarea className={control} maxLength={6000} value={draft.description} onChange={e=>change('description',e.target.value)}/></Field>
|
||||
<Field label="Limitações e lacunas conhecidas"><textarea className={control} value={draft.limitations} onChange={e=>change('limitations',e.target.value)}/></Field>
|
||||
<Field label="Fonte do resumo"><textarea className={control} value={draft.source_reference} onChange={e=>change('source_reference',e.target.value)}/></Field>
|
||||
<Field label="Edição"><input className={control} value={draft.edition} onChange={e=>change('edition',e.target.value)}/></Field>
|
||||
<Field label="Data-base"><input className={control} type="date" value={draft.source_date} onChange={e=>change('source_date',e.target.value)}/></Field>
|
||||
<Field label="Sector divulgado"><select className={control} value={draft.sector_id ?? ''} onChange={e=>change('sector_id',e.target.value ? Number(e.target.value):null)}><option value="">Por indicar</option>{sectors.map(s=><option key={s.id} value={s.id}>{s.name}</option>)}</select></Field>
|
||||
<Field label="Acrescentar abrangência territorial documentada"><select className={control} value="" onChange={e=>{if(e.target.value && !draft.territory_ids.includes(e.target.value))change('territory_ids',[...draft.territory_ids,e.target.value]);}}><option value="">Seleccionar território existente</option>{territories.map(t=><option key={t.id} value={t.id}>{t.name} · {t.location_type}</option>)}</select></Field>
|
||||
<p>Seleccione apenas a abrangência que pretende divulgar e cuja origem está identificada. Abrangência não comprova implantação ou disponibilidade de terreno. Sem selecção, a localização fica por indicar.</p>
|
||||
<ul>{draft.territory_ids.map(id=><li key={id}>{territories.find(t=>t.id===id)?.name ?? 'Referência anterior indisponível'} <button type="button" className="underline" onClick={()=>change('territory_ids',draft.territory_ids.filter(t=>t!==id))}>Remover abrangência</button></li>)}</ul>
|
||||
<button className={button} disabled={busy || needsMfa}>{publicNow ? 'Rever actualização do resumo' : 'Preparar prévia de divulgação'}</button>
|
||||
{publicNow && <button type="button" className={`${button} ml-3`} disabled={busy || needsMfa} onClick={()=>void prepare('withdraw')}>Preparar retirada do resumo</button>}
|
||||
</form>
|
||||
{preview && <section className="space-y-4 rounded border p-5" aria-label="Prévia da divulgação">
|
||||
<h2 className="text-xl font-semibold">{preview.action === 'withdraw' ? 'Rever retirada do catálogo' : 'Prévia do conteúdo público'}</h2>
|
||||
<p><strong>{preview.projection.maturity_label}</strong></p>
|
||||
<ProactiveSummary value={preview.projection.proactive}/>
|
||||
<h3>{preview.projection.title}</h3><p>{preview.projection.summary}</p><p className="whitespace-pre-wrap">{preview.projection.description}</p>
|
||||
<p>Sector: {sectors.find(s=>s.id===preview.projection.sector_id)?.name ?? 'Por indicar'}</p>
|
||||
<ul>{preview.projection.territories.map(t=><li key={t.id}>{t.label}</li>)}</ul>
|
||||
{!preview.projection.territories.length && <p>Abrangência territorial por indicar.</p>}
|
||||
<p>Esta prévia ainda não alterou o portal público. {preview.action === 'withdraw' ? 'A confirmação retira o resumo da consulta pública e preserva o cadastro.' : 'Só este texto e o enquadramento apresentado serão divulgados; os anexos e contactos não são incluídos.'}</p>
|
||||
<Field label="Motivo da divulgação, alteração ou retirada"><textarea required className={control} minLength={10} maxLength={1000} value={reason} onChange={e=>setReason(e.target.value)}/></Field>
|
||||
<label className="block"><input type="checkbox" checked={confirmed} onChange={e=>setConfirmed(e.target.checked)}/> Confirmo o conteúdo público desta prévia e a operação indicada.</label>
|
||||
<button className={button} disabled={busy || !confirmed || reason.trim().length<10} onClick={()=>void publish()}>{preview.action === 'withdraw' ? 'Confirmar retirada do resumo' : 'Confirmar divulgação do resumo'}</button>
|
||||
<button className="ml-3 underline" disabled={busy} onClick={()=>{setPreview(null);setConfirmed(false);}}>Cancelar prévia</button>
|
||||
</section>}
|
||||
<section aria-label="Histórico da divulgação"><h2 className="text-xl font-semibold">Histórico da divulgação</h2><ul>{history.map(h=><li key={h.id}>{labels[h.action] ?? h.action} · {h.occurred_at} · responsável {h.actor_user_id}</li>)}</ul></section>
|
||||
</Management>;
|
||||
const labels: Record<string, string> = {
|
||||
promotional_summary_published: 'Resumo divulgado',
|
||||
promotional_summary_updated: 'Resumo actualizado',
|
||||
promotional_summary_withdrawn: 'Resumo retirado',
|
||||
};
|
||||
return (
|
||||
<Management title={`Divulgação promocional — ${record.reference}`}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/minhas-oportunidades/${record.id}/view`}
|
||||
>
|
||||
Voltar à oportunidade
|
||||
</Link>
|
||||
<p>
|
||||
Prepare o resumo público e reveja a prévia antes de confirmar. A
|
||||
divulgação fica identificada como <strong>Em preparação</strong>{' '}
|
||||
e não autoriza a execução do investimento. Documentos e
|
||||
contactos do cadastro continuam privados.
|
||||
</p>
|
||||
<p role="status">
|
||||
{publicNow
|
||||
? 'Resumo actualmente divulgado.'
|
||||
: 'Resumo não divulgado.'}{' '}
|
||||
{message}
|
||||
</p>
|
||||
{needsMfa && (
|
||||
<p role="alert">
|
||||
Entre novamente com a sua conta e MFA para confirmar esta
|
||||
operação. O cadastro guardado permanece disponível; a prévia
|
||||
ainda não confirmada terá de ser preparada novamente.{' '}
|
||||
<button className="underline" onClick={renewAuthentication}>
|
||||
Renovar entrada com MFA
|
||||
</button>
|
||||
</p>
|
||||
)}
|
||||
{Object.entries(errors).map(([key, value]) => (
|
||||
<p role="alert" key={key}>
|
||||
{key}: {value}
|
||||
</p>
|
||||
))}
|
||||
<form
|
||||
className="space-y-4 rounded border p-5"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void prepare('disclose');
|
||||
}}
|
||||
>
|
||||
{proactiveEnabled && draft.proactive_public && (
|
||||
<ProactivePublicationFields
|
||||
value={draft.proactive_public}
|
||||
onChange={(v) => {
|
||||
change('proactive_public', v);
|
||||
change('proactive_reviewed', false);
|
||||
}}
|
||||
evidence={proactiveEvidence}
|
||||
relations={proactiveRelations}
|
||||
options={proactiveOptions}
|
||||
reviewed={Boolean(draft.proactive_reviewed)}
|
||||
onReview={(v) => change('proactive_reviewed', v)}
|
||||
/>
|
||||
)}
|
||||
<Field label="Título público">
|
||||
<input
|
||||
required
|
||||
className={control}
|
||||
maxLength={255}
|
||||
value={draft.title}
|
||||
onChange={(e) => change('title', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Resumo público">
|
||||
<textarea
|
||||
required
|
||||
className={control}
|
||||
maxLength={499}
|
||||
value={draft.summary}
|
||||
onChange={(e) => change('summary', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Descrição pública">
|
||||
<textarea
|
||||
className={control}
|
||||
maxLength={6000}
|
||||
value={draft.description}
|
||||
onChange={(e) => change('description', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Limitações e lacunas conhecidas">
|
||||
<textarea
|
||||
className={control}
|
||||
value={draft.limitations}
|
||||
onChange={(e) => change('limitations', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Fonte do resumo">
|
||||
<textarea
|
||||
className={control}
|
||||
value={draft.source_reference}
|
||||
onChange={(e) =>
|
||||
change('source_reference', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Edição">
|
||||
<input
|
||||
className={control}
|
||||
value={draft.edition}
|
||||
onChange={(e) => change('edition', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Data-base">
|
||||
<input
|
||||
className={control}
|
||||
type="date"
|
||||
value={draft.source_date}
|
||||
onChange={(e) => change('source_date', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Sector divulgado">
|
||||
<select
|
||||
className={control}
|
||||
value={draft.sector_id ?? ''}
|
||||
onChange={(e) =>
|
||||
change(
|
||||
'sector_id',
|
||||
e.target.value ? Number(e.target.value) : null,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Por indicar</option>
|
||||
{sectors.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Acrescentar abrangência territorial documentada">
|
||||
<select
|
||||
className={control}
|
||||
value=""
|
||||
onChange={(e) => {
|
||||
if (
|
||||
e.target.value &&
|
||||
!draft.territory_ids.includes(e.target.value)
|
||||
)
|
||||
change('territory_ids', [
|
||||
...draft.territory_ids,
|
||||
e.target.value,
|
||||
]);
|
||||
}}
|
||||
>
|
||||
<option value="">
|
||||
Seleccionar território existente
|
||||
</option>
|
||||
{territories.map((t) => (
|
||||
<option key={t.id} value={t.id}>
|
||||
{t.name} · {t.location_type}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<p>
|
||||
Seleccione apenas a abrangência que pretende divulgar e cuja
|
||||
origem está identificada. Abrangência não comprova
|
||||
implantação ou disponibilidade de terreno. Sem selecção, a
|
||||
localização fica por indicar.
|
||||
</p>
|
||||
<ul>
|
||||
{draft.territory_ids.map((id) => (
|
||||
<li key={id}>
|
||||
{territories.find((t) => t.id === id)?.name ??
|
||||
'Referência anterior indisponível'}{' '}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() =>
|
||||
change(
|
||||
'territory_ids',
|
||||
draft.territory_ids.filter(
|
||||
(t) => t !== id,
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
Remover abrangência
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<button className={button} disabled={busy || needsMfa}>
|
||||
{publicNow
|
||||
? 'Rever actualização do resumo'
|
||||
: 'Preparar prévia de divulgação'}
|
||||
</button>
|
||||
{publicNow && (
|
||||
<button
|
||||
type="button"
|
||||
className={`${button} ml-3`}
|
||||
disabled={busy || needsMfa}
|
||||
onClick={() => void prepare('withdraw')}
|
||||
>
|
||||
Preparar retirada do resumo
|
||||
</button>
|
||||
)}
|
||||
</form>
|
||||
{preview && (
|
||||
<section
|
||||
className="space-y-4 rounded border p-5"
|
||||
aria-label="Prévia da divulgação"
|
||||
>
|
||||
<h2 className="text-xl font-semibold">
|
||||
{preview.action === 'withdraw'
|
||||
? 'Rever retirada do catálogo'
|
||||
: 'Prévia do conteúdo público'}
|
||||
</h2>
|
||||
<p>
|
||||
<strong>{preview.projection.maturity_label}</strong>
|
||||
</p>
|
||||
<ProactiveSummary value={preview.projection.proactive} />
|
||||
<h3>{preview.projection.title}</h3>
|
||||
<p>{preview.projection.summary}</p>
|
||||
<p className="whitespace-pre-wrap">
|
||||
{preview.projection.description}
|
||||
</p>
|
||||
<p>
|
||||
Sector:{' '}
|
||||
{sectors.find(
|
||||
(s) => s.id === preview.projection.sector_id,
|
||||
)?.name ?? 'Por indicar'}
|
||||
</p>
|
||||
<ul>
|
||||
{preview.projection.territories.map((t) => (
|
||||
<li key={t.id}>{t.label}</li>
|
||||
))}
|
||||
</ul>
|
||||
{!preview.projection.territories.length && (
|
||||
<p>Abrangência territorial por indicar.</p>
|
||||
)}
|
||||
<p>
|
||||
Esta prévia ainda não alterou o portal público.{' '}
|
||||
{preview.action === 'withdraw'
|
||||
? 'A confirmação retira o resumo da consulta pública e preserva o cadastro.'
|
||||
: 'Só este texto e o enquadramento apresentado serão divulgados; os anexos e contactos não são incluídos.'}
|
||||
</p>
|
||||
<Field label="Motivo da divulgação, alteração ou retirada">
|
||||
<textarea
|
||||
required
|
||||
className={control}
|
||||
minLength={10}
|
||||
maxLength={1000}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={confirmed}
|
||||
onChange={(e) => setConfirmed(e.target.checked)}
|
||||
/>{' '}
|
||||
Confirmo o conteúdo público desta prévia e a operação
|
||||
indicada.
|
||||
</label>
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
busy || !confirmed || reason.trim().length < 10
|
||||
}
|
||||
onClick={() => void publish()}
|
||||
>
|
||||
{preview.action === 'withdraw'
|
||||
? 'Confirmar retirada do resumo'
|
||||
: 'Confirmar divulgação do resumo'}
|
||||
</button>
|
||||
<button
|
||||
className="ml-3 underline"
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
setPreview(null);
|
||||
setConfirmed(false);
|
||||
}}
|
||||
>
|
||||
Cancelar prévia
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
<section aria-label="Histórico da divulgação">
|
||||
<h2 className="text-xl font-semibold">
|
||||
Histórico da divulgação
|
||||
</h2>
|
||||
<ul>
|
||||
{history.map((h) => (
|
||||
<li key={h.id}>
|
||||
{labels[h.action] ?? h.action} · {h.occurred_at} ·
|
||||
responsável {h.actor_user_id}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -179,8 +179,12 @@ export default function OpportunityResources({
|
||||
readOnly?: boolean;
|
||||
countries?: { code: string; name: string }[];
|
||||
}>().props;
|
||||
const returnGroup = new URLSearchParams(usePage().url.split('?')[1] ?? '').get('return_group');
|
||||
const returnHash = ['territory', 'evidence'].includes(returnGroup ?? '') ? `#fill-${returnGroup}` : '#fill-evidence';
|
||||
const returnGroup = new URLSearchParams(
|
||||
usePage().url.split('?')[1] ?? '',
|
||||
).get('return_group');
|
||||
const returnHash = ['territory', 'evidence'].includes(returnGroup ?? '')
|
||||
? `#fill-${returnGroup}`
|
||||
: '#fill-evidence';
|
||||
const [kind, setKind] = useState<Kind>('locations');
|
||||
const [editing, setEditing] = useState<Resource | null>(null);
|
||||
const [payload, setPayload] = useState<Payload>({ country_code: 'MZ' });
|
||||
|
||||
@@ -15,7 +15,9 @@ export default function TerritoryAssociations() {
|
||||
const [retry, setRetry] = useState(0);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setLoading(true); setError(''); setRows([]);
|
||||
setLoading(true);
|
||||
setError('');
|
||||
setRows([]);
|
||||
const timer = setTimeout(async () => {
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
@@ -41,10 +43,10 @@ export default function TerritoryAssociations() {
|
||||
setError('');
|
||||
} catch {
|
||||
if (!controller.signal.aborted)
|
||||
setError(
|
||||
'Não foi possível concluir a pesquisa.',
|
||||
);
|
||||
} finally { if (!controller.signal.aborted) setLoading(false); }
|
||||
setError('Não foi possível concluir a pesquisa.');
|
||||
} finally {
|
||||
if (!controller.signal.aborted) setLoading(false);
|
||||
}
|
||||
}, 250);
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
@@ -76,7 +78,12 @@ export default function TerritoryAssociations() {
|
||||
<option value="opportunities">Oportunidades</option>
|
||||
</select>
|
||||
</Field>
|
||||
<SearchState loading={loading} error={error} total={rows.length} retry={() => setRetry(value => value + 1)} />
|
||||
<SearchState
|
||||
loading={loading}
|
||||
error={error}
|
||||
total={rows.length}
|
||||
retry={() => setRetry((value) => value + 1)}
|
||||
/>
|
||||
<Field label="Pesquisar investimento">
|
||||
<input
|
||||
className={control}
|
||||
|
||||
Reference in New Issue
Block a user