feat: consolidar desenvolvimentos do portal InvestMoz
This commit is contained in:
@@ -1,9 +1,12 @@
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { useCrmRecordEdit } from '@/lib/crm-record-edit';
|
||||
import CrmEditComparison from '@/components/crm-edit-comparison';
|
||||
import { Management, Field, control, button } from '../management/shared';
|
||||
import { leadStates } from './types';
|
||||
|
||||
type Contact = {
|
||||
id: string;
|
||||
version_no: number;
|
||||
full_name: string;
|
||||
email: string | null;
|
||||
phone: string | null;
|
||||
@@ -15,44 +18,61 @@ function ContactForm({
|
||||
contact: Contact;
|
||||
investorId: string;
|
||||
}) {
|
||||
const form = useForm({
|
||||
full_name: contact.full_name,
|
||||
email: contact.email ?? '',
|
||||
phone: contact.phone ?? '',
|
||||
const edit = useCrmRecordEdit({
|
||||
id: contact.id,
|
||||
kind: 'contact',
|
||||
version: contact.version_no,
|
||||
values: {
|
||||
full_name: contact.full_name,
|
||||
email: contact.email ?? '',
|
||||
phone: contact.phone ?? '',
|
||||
},
|
||||
});
|
||||
const form = edit.form;
|
||||
return (
|
||||
<form
|
||||
className="space-y-3 rounded border p-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.patch(
|
||||
edit.submit(
|
||||
`/management/crm/investors/${investorId}/contacts/${contact.id}`,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<Field label="Nome do contacto" error={form.errors.full_name}>
|
||||
<Field label="Nome do contacto" error={edit.error('full_name')}>
|
||||
<input
|
||||
className={control}
|
||||
value={form.data.full_name}
|
||||
onChange={(e) => form.setData('full_name', e.target.value)}
|
||||
value={edit.values.full_name}
|
||||
onChange={(e) => edit.change('full_name', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Email" error={form.errors.email}>
|
||||
<Field label="Email" error={edit.error('email')}>
|
||||
<input
|
||||
className={control}
|
||||
type="email"
|
||||
value={form.data.email}
|
||||
onChange={(e) => form.setData('email', e.target.value)}
|
||||
value={edit.values.email}
|
||||
onChange={(e) => edit.change('email', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Telefone" error={form.errors.phone}>
|
||||
<Field label="Telefone" error={edit.error('phone')}>
|
||||
<input
|
||||
className={control}
|
||||
value={form.data.phone}
|
||||
onChange={(e) => form.setData('phone', e.target.value)}
|
||||
value={edit.values.phone}
|
||||
onChange={(e) => edit.change('phone', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<button className={button} disabled={form.processing}>
|
||||
<CrmEditComparison
|
||||
editor={edit}
|
||||
labels={{
|
||||
full_name: 'Nome do contacto',
|
||||
email: 'Email',
|
||||
phone: 'Telefone',
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
className={button}
|
||||
disabled={form.processing || edit.blocked}
|
||||
>
|
||||
Guardar contacto
|
||||
</button>
|
||||
</form>
|
||||
@@ -65,6 +85,7 @@ export default function InvestorDetail({
|
||||
}: {
|
||||
investor: {
|
||||
id: string;
|
||||
version_no: number;
|
||||
legal_name: string;
|
||||
investor_type: string;
|
||||
status: string;
|
||||
@@ -72,38 +93,44 @@ export default function InvestorDetail({
|
||||
contacts: Contact[];
|
||||
leads: { id: string; title: string; status: string }[];
|
||||
}) {
|
||||
const form = useForm({
|
||||
legal_name: investor.legal_name,
|
||||
investor_type: investor.investor_type,
|
||||
status: investor.status,
|
||||
const edit = useCrmRecordEdit({
|
||||
id: investor.id,
|
||||
kind: 'investor',
|
||||
version: investor.version_no,
|
||||
values: {
|
||||
legal_name: investor.legal_name,
|
||||
investor_type: investor.investor_type,
|
||||
status: investor.status,
|
||||
},
|
||||
});
|
||||
const form = edit.form;
|
||||
return (
|
||||
<Management title={investor.legal_name}>
|
||||
<form
|
||||
className="max-w-xl space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.patch(`/management/crm/investors/${investor.id}`);
|
||||
edit.submit(`/management/crm/investors/${investor.id}`);
|
||||
}}
|
||||
>
|
||||
<Field label="Nome legal" error={form.errors.legal_name}>
|
||||
<Field label="Nome legal" error={edit.error('legal_name')}>
|
||||
<input
|
||||
className={control}
|
||||
value={form.data.legal_name}
|
||||
value={edit.values.legal_name}
|
||||
onChange={(e) =>
|
||||
form.setData('legal_name', e.target.value)
|
||||
edit.change('legal_name', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label="Tipo de investidor"
|
||||
error={form.errors.investor_type}
|
||||
error={edit.error('investor_type')}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.investor_type}
|
||||
value={edit.values.investor_type}
|
||||
onChange={(e) =>
|
||||
form.setData('investor_type', e.target.value)
|
||||
edit.change('investor_type', e.target.value)
|
||||
}
|
||||
>
|
||||
{Object.entries({
|
||||
@@ -118,11 +145,11 @@ export default function InvestorDetail({
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Estado" error={form.errors.status}>
|
||||
<Field label="Estado" error={edit.error('status')}>
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.status}
|
||||
onChange={(e) => form.setData('status', e.target.value)}
|
||||
value={edit.values.status}
|
||||
onChange={(e) => edit.change('status', e.target.value)}
|
||||
>
|
||||
{Object.entries({
|
||||
prospect: 'Potencial investidor',
|
||||
@@ -135,7 +162,34 @@ export default function InvestorDetail({
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<button className={button} disabled={form.processing}>
|
||||
<CrmEditComparison
|
||||
editor={edit}
|
||||
labels={{
|
||||
legal_name: 'Nome legal',
|
||||
investor_type: 'Tipo de investidor',
|
||||
status: 'Estado',
|
||||
}}
|
||||
display={(key, value) =>
|
||||
key === 'investor_type'
|
||||
? ({
|
||||
domestic: 'Nacional',
|
||||
foreign: 'Estrangeiro',
|
||||
institutional: 'Institucional',
|
||||
individual: 'Individual',
|
||||
}[value] ?? value)
|
||||
: key === 'status'
|
||||
? ({
|
||||
prospect: 'Potencial investidor',
|
||||
active: 'Activo',
|
||||
inactive: 'Inactivo',
|
||||
}[value] ?? value)
|
||||
: value
|
||||
}
|
||||
/>
|
||||
<button
|
||||
className={button}
|
||||
disabled={form.processing || edit.blocked}
|
||||
>
|
||||
Guardar investidor
|
||||
</button>
|
||||
</form>
|
||||
|
||||
+117
-90
@@ -1,16 +1,28 @@
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import CrmTaskCreation from '@/components/crm-task-creation';
|
||||
import type { TaskCreationContext } from '@/lib/crm-task-creation';
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { useCrmRecordEdit } from '@/lib/crm-record-edit';
|
||||
import CrmEditComparison from '@/components/crm-edit-comparison';
|
||||
import { Management, Field, button, control } from '../management/shared';
|
||||
import { leadStates, taskStates } from './types';
|
||||
import type { Lead, Owner, Task } from './types';
|
||||
|
||||
function TaskRow({ task, leadId }: { task: Task; leadId: string }) {
|
||||
const form = useForm({ status: task.status });
|
||||
const edit = useCrmRecordEdit({
|
||||
id: task.id,
|
||||
kind: 'task',
|
||||
version: task.version_no,
|
||||
values: { status: task.status },
|
||||
});
|
||||
const form = edit.form;
|
||||
return (
|
||||
<form
|
||||
id={`crm-task-${task.id}`}
|
||||
className="space-y-3 rounded border p-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.patch(`/management/crm/leads/${leadId}/tasks/${task.id}`);
|
||||
if (task.can_update === false) return;
|
||||
edit.submit(`/management/crm/leads/${leadId}/tasks/${task.id}`);
|
||||
}}
|
||||
>
|
||||
<h3 className="font-semibold">{task.title}</h3>
|
||||
@@ -26,12 +38,13 @@ function TaskRow({ task, leadId }: { task: Task; leadId: string }) {
|
||||
</p>
|
||||
<Field
|
||||
label={`Estado da tarefa: ${task.title}`}
|
||||
error={form.errors.status}
|
||||
error={edit.error('status')}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.status}
|
||||
onChange={(e) => form.setData('status', e.target.value)}
|
||||
disabled={task.can_update === false}
|
||||
value={edit.values.status}
|
||||
onChange={(e) => edit.change('status', e.target.value)}
|
||||
>
|
||||
{Object.entries(taskStates).map(([key, label]) => (
|
||||
<option key={key} value={key}>
|
||||
@@ -40,9 +53,26 @@ function TaskRow({ task, leadId }: { task: Task; leadId: string }) {
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<button className={button} disabled={form.processing}>
|
||||
Actualizar tarefa
|
||||
</button>
|
||||
{task.can_update !== false ? (
|
||||
<>
|
||||
<CrmEditComparison
|
||||
editor={edit}
|
||||
labels={{ status: 'Estado da tarefa' }}
|
||||
display={(_key, value) => taskStates[value] ?? value}
|
||||
/>
|
||||
<button
|
||||
className={button}
|
||||
disabled={form.processing || edit.blocked}
|
||||
>
|
||||
Actualizar tarefa
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<p>
|
||||
Dossier associado encerrado; tarefa disponível para
|
||||
consulta.
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -50,6 +80,8 @@ export default function LeadDetail({
|
||||
lead,
|
||||
contacts,
|
||||
owners,
|
||||
nextAction,
|
||||
taskCreation,
|
||||
}: {
|
||||
lead: Lead;
|
||||
contacts: {
|
||||
@@ -59,17 +91,21 @@ export default function LeadDetail({
|
||||
phone: string | null;
|
||||
}[];
|
||||
owners: Owner[];
|
||||
nextAction?: { future_tasks: number };
|
||||
taskCreation: TaskCreationContext;
|
||||
}) {
|
||||
const review = useForm({
|
||||
status: lead.status,
|
||||
owner_user_id: String(lead.owner_user_id ?? ''),
|
||||
qualification_reason: '',
|
||||
});
|
||||
const task = useForm({
|
||||
title: '',
|
||||
due_at: '',
|
||||
assignee_user_id: String(lead.owner_user_id ?? ''),
|
||||
const edit = useCrmRecordEdit({
|
||||
id: lead.id,
|
||||
kind: 'lead',
|
||||
version: lead.version_no,
|
||||
blankAfterSave: ['qualification_reason'],
|
||||
values: {
|
||||
status: lead.status,
|
||||
owner_user_id: String(lead.owner_user_id ?? ''),
|
||||
qualification_reason: '',
|
||||
},
|
||||
});
|
||||
const review = edit.form;
|
||||
return (
|
||||
<Management title={lead.title}>
|
||||
<Link className="underline" href="/management/crm/leads">
|
||||
@@ -108,23 +144,46 @@ export default function LeadDetail({
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
{nextAction && (
|
||||
<section
|
||||
aria-label="Próxima acção"
|
||||
className="space-y-2 rounded border p-4"
|
||||
>
|
||||
<p>
|
||||
{nextAction.future_tasks === 1
|
||||
? '1 tarefa disponível com prazo futuro.'
|
||||
: `${nextAction.future_tasks} tarefas disponíveis com prazo futuro.`}
|
||||
</p>
|
||||
{nextAction.future_tasks === 0 &&
|
||||
['new', 'qualified'].includes(lead.status) && (
|
||||
<p role="status">
|
||||
Registe uma próxima acção com prazo futuro antes
|
||||
de qualificar o acompanhamento ou concluir a sua
|
||||
última tarefa. Tarefas num dossier encerrado
|
||||
ficam no histórico e não contam como próxima
|
||||
acção.
|
||||
</p>
|
||||
)}
|
||||
<a className="underline" href="#new-crm-task">
|
||||
Registar próxima acção
|
||||
</a>
|
||||
</section>
|
||||
)}
|
||||
<form
|
||||
className="max-w-xl space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
review.patch(`/management/crm/leads/${lead.id}`);
|
||||
edit.submit(`/management/crm/leads/${lead.id}`);
|
||||
}}
|
||||
>
|
||||
<h2 className="text-lg font-semibold">
|
||||
Qualificação e atribuição
|
||||
</h2>
|
||||
<Field label="Estado do lead" error={review.errors.status}>
|
||||
<Field label="Estado do lead" error={edit.error('status')}>
|
||||
<select
|
||||
className={control}
|
||||
value={review.data.status}
|
||||
onChange={(e) =>
|
||||
review.setData('status', e.target.value)
|
||||
}
|
||||
value={edit.values.status}
|
||||
onChange={(e) => edit.change('status', e.target.value)}
|
||||
>
|
||||
{Object.entries(leadStates)
|
||||
.filter(([key]) => key !== 'converted')
|
||||
@@ -135,12 +194,12 @@ export default function LeadDetail({
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Responsável" error={review.errors.owner_user_id}>
|
||||
<Field label="Responsável" error={edit.error('owner_user_id')}>
|
||||
<select
|
||||
className={control}
|
||||
value={review.data.owner_user_id}
|
||||
value={edit.values.owner_user_id}
|
||||
onChange={(e) =>
|
||||
review.setData('owner_user_id', e.target.value)
|
||||
edit.change('owner_user_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Seleccione</option>
|
||||
@@ -153,16 +212,13 @@ export default function LeadDetail({
|
||||
</Field>
|
||||
<Field
|
||||
label="Fundamento da alteração"
|
||||
error={review.errors.qualification_reason}
|
||||
error={edit.error('qualification_reason')}
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
value={review.data.qualification_reason}
|
||||
value={edit.values.qualification_reason}
|
||||
onChange={(e) =>
|
||||
review.setData(
|
||||
'qualification_reason',
|
||||
e.target.value,
|
||||
)
|
||||
edit.change('qualification_reason', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
@@ -171,9 +227,30 @@ export default function LeadDetail({
|
||||
Último fundamento: {lead.qualification_reason}
|
||||
</p>
|
||||
)}
|
||||
<CrmEditComparison
|
||||
editor={edit}
|
||||
labels={{
|
||||
status: 'Estado do lead',
|
||||
owner_user_id: 'Responsável',
|
||||
qualification_reason: 'Fundamento da alteração',
|
||||
}}
|
||||
display={(key, value) =>
|
||||
key === 'status'
|
||||
? (leadStates[value] ?? value)
|
||||
: key === 'owner_user_id'
|
||||
? (owners.find(
|
||||
(owner) => String(owner.id) === value,
|
||||
)?.name ?? 'Responsável por confirmar')
|
||||
: value
|
||||
}
|
||||
/>
|
||||
<button
|
||||
className={button}
|
||||
disabled={review.processing || lead.status === 'converted'}
|
||||
disabled={
|
||||
review.processing ||
|
||||
edit.blocked ||
|
||||
lead.status === 'converted'
|
||||
}
|
||||
>
|
||||
Guardar lead
|
||||
</button>
|
||||
@@ -185,62 +262,12 @@ export default function LeadDetail({
|
||||
))}
|
||||
{!lead.tasks.length && <p>Não existem tarefas.</p>}
|
||||
</section>
|
||||
<form
|
||||
className="max-w-xl space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
task.transform((data) => ({
|
||||
...data,
|
||||
due_at: data.due_at
|
||||
? new Date(data.due_at).toISOString()
|
||||
: '',
|
||||
}));
|
||||
task.post(`/management/crm/leads/${lead.id}/tasks`, {
|
||||
onSuccess: () => task.reset('title', 'due_at'),
|
||||
});
|
||||
}}
|
||||
>
|
||||
<h2 className="text-lg font-semibold">
|
||||
Registar próxima acção
|
||||
</h2>
|
||||
<Field label="Tarefa" error={task.errors.title}>
|
||||
<input
|
||||
className={control}
|
||||
value={task.data.title}
|
||||
onChange={(e) => task.setData('title', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Prazo (hora local)" error={task.errors.due_at}>
|
||||
<input
|
||||
type="datetime-local"
|
||||
className={control}
|
||||
value={task.data.due_at}
|
||||
onChange={(e) => task.setData('due_at', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label="Responsável pela tarefa"
|
||||
error={task.errors.assignee_user_id}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={task.data.assignee_user_id}
|
||||
onChange={(e) =>
|
||||
task.setData('assignee_user_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Seleccione</option>
|
||||
{owners.map((owner) => (
|
||||
<option key={owner.id} value={owner.id}>
|
||||
{owner.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<button className={button} disabled={task.processing}>
|
||||
Criar tarefa
|
||||
</button>
|
||||
</form>
|
||||
<CrmTaskCreation
|
||||
key={`${lead.id}:${taskCreation.actor_id}`}
|
||||
lead={lead}
|
||||
owners={owners}
|
||||
context={taskCreation}
|
||||
/>
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
export type Owner = { id: number; name: string };
|
||||
export type Task = {
|
||||
version_no: number;
|
||||
can_update?: boolean;
|
||||
id: string;
|
||||
title: string;
|
||||
status: string;
|
||||
@@ -7,6 +9,7 @@ export type Task = {
|
||||
assignee_user_id: number | null;
|
||||
};
|
||||
export type Lead = {
|
||||
version_no: number;
|
||||
id: string;
|
||||
title: string;
|
||||
status: string;
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import ProfileNavigation from '@/components/profile-navigation';
|
||||
import ContentManagementEntry from '@/components/content-management-entry';
|
||||
import DashboardWorkQueue, {
|
||||
type DashboardQueue,
|
||||
} from '@/components/dashboard-work-queue';
|
||||
import { Head, Link } from '@inertiajs/react';
|
||||
import { dashboard } from '@/routes';
|
||||
import type { InvestmentContext } from '@/pages/investor-path/index';
|
||||
@@ -32,9 +35,11 @@ export default function Dashboard({
|
||||
summary,
|
||||
investorPath,
|
||||
opportunityManagement,
|
||||
workQueue,
|
||||
}: {
|
||||
summary: Summary | null;
|
||||
opportunityManagement?: OpportunityManagementAccess | null;
|
||||
workQueue?: DashboardQueue | null;
|
||||
investorPath?: {
|
||||
contexts: InvestmentContext[];
|
||||
current: {
|
||||
@@ -53,8 +58,15 @@ export default function Dashboard({
|
||||
<h1 className="text-2xl font-semibold">Painel do portal</h1>
|
||||
<ProfileNavigation />
|
||||
<ContentManagementEntry />
|
||||
<DashboardWorkQueue queue={workQueue} />
|
||||
{summary ? (
|
||||
<>
|
||||
<Link
|
||||
className="inline-block rounded-lg border px-4 py-2 underline"
|
||||
href="/management/product-usage"
|
||||
>
|
||||
Indicadores de utilização e cobertura
|
||||
</Link>
|
||||
{opportunityManagement && (
|
||||
<section
|
||||
aria-label="Gestão de Oportunidades"
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { Link, useForm, usePage } from '@inertiajs/react';
|
||||
import DeskCaseStateForm from '@/components/desk-case-state-form';
|
||||
import { useRef, useState } from 'react';
|
||||
import DeskDocumentPicker, {
|
||||
type ReusableDeskDocument,
|
||||
} from '@/components/desk-document-picker';
|
||||
import { Link, router, useForm, usePage } from '@inertiajs/react';
|
||||
import { Frame, card, input, button } from '@/pages/investment/shared';
|
||||
import {
|
||||
InvestorGuidance,
|
||||
@@ -91,6 +96,8 @@ type Event = {
|
||||
export default function Case({
|
||||
case: dossier,
|
||||
canWrite,
|
||||
canChangeState = false,
|
||||
activity = null,
|
||||
manager,
|
||||
requests,
|
||||
services,
|
||||
@@ -107,15 +114,27 @@ export default function Case({
|
||||
id: string;
|
||||
title: string;
|
||||
version: number;
|
||||
closed_at?: string | null;
|
||||
workflow: Record<string, Stage>;
|
||||
investor_id?: string;
|
||||
project_id?: string;
|
||||
journey_id?: string;
|
||||
};
|
||||
canWrite: boolean;
|
||||
canChangeState?: boolean;
|
||||
activity?: {
|
||||
open_requests: number | null;
|
||||
open_tasks: number | null;
|
||||
pending_payments: number | null;
|
||||
} | null;
|
||||
manager: boolean;
|
||||
requests: { id: string; status: string; protocol: string | null }[];
|
||||
services: { id: string; title: string; version: number }[];
|
||||
services: {
|
||||
id: string;
|
||||
title: string;
|
||||
version: number;
|
||||
effective_from?: string | null;
|
||||
}[];
|
||||
documents: DeskDocument[];
|
||||
links: {
|
||||
id: string;
|
||||
@@ -143,6 +162,9 @@ export default function Case({
|
||||
events: Event[];
|
||||
}) {
|
||||
const actor = usePage<{ auth: { user: { id: number } } }>().props.auth.user;
|
||||
const [documentOrigin, setDocumentOrigin] =
|
||||
useState<ReusableDeskDocument | null>(null);
|
||||
const uploadInput = useRef<HTMLInputElement | null>(null);
|
||||
const requestForm = useForm({
|
||||
service_version_id: services[0]?.id ?? '',
|
||||
client_key: createOperationKey(),
|
||||
@@ -156,7 +178,7 @@ export default function Case({
|
||||
status: 'preparing',
|
||||
reason: '',
|
||||
evidence: '',
|
||||
document_id: '',
|
||||
document_link_id: '',
|
||||
valid_until: '',
|
||||
exception: false,
|
||||
});
|
||||
@@ -177,6 +199,12 @@ export default function Case({
|
||||
});
|
||||
return (
|
||||
<Frame title={dossier.title}>
|
||||
{dossier.closed_at && (
|
||||
<p role="status">
|
||||
Dossier encerrado. Os pedidos, documentos e o histórico
|
||||
continuam disponíveis para consulta.
|
||||
</p>
|
||||
)}
|
||||
{legacyRequest && (
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-bold">
|
||||
@@ -206,6 +234,22 @@ export default function Case({
|
||||
<Link href="/balcao-virtual/painel" className="underline">
|
||||
Voltar ao Balcão Virtual
|
||||
</Link>
|
||||
{canChangeState && (
|
||||
<DeskCaseStateForm
|
||||
dossier={dossier}
|
||||
activity={activity}
|
||||
disabled={
|
||||
upload.processing ||
|
||||
stageForm.processing ||
|
||||
requestForm.processing
|
||||
}
|
||||
onChanged={() => {
|
||||
upload.reset('file', 'consent');
|
||||
if (uploadInput.current) uploadInput.current.value = '';
|
||||
setDocumentOrigin(null);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<p>
|
||||
Um dossier, os mesmos pedidos, documentos, conversas e tarefas.
|
||||
Projecto existente:{' '}
|
||||
@@ -250,6 +294,14 @@ export default function Case({
|
||||
className={card + ' space-y-3'}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (
|
||||
!services.some(
|
||||
(service) =>
|
||||
service.id ===
|
||||
requestForm.data.service_version_id,
|
||||
)
|
||||
)
|
||||
return;
|
||||
requestForm.post(
|
||||
`/balcao-virtual/dossiers/${dossier.id}/pedidos`,
|
||||
);
|
||||
@@ -269,9 +321,29 @@ export default function Case({
|
||||
}
|
||||
>
|
||||
<option value="">Seleccione</option>
|
||||
{requestForm.data.service_version_id &&
|
||||
!services.some(
|
||||
(service) =>
|
||||
service.id ===
|
||||
requestForm.data.service_version_id,
|
||||
) && (
|
||||
<option
|
||||
value={
|
||||
requestForm.data
|
||||
.service_version_id
|
||||
}
|
||||
disabled
|
||||
>
|
||||
A versão seleccionada já não está na
|
||||
lista. Escolha o formulário actual.
|
||||
</option>
|
||||
)}
|
||||
{services.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.title} — v{s.version}
|
||||
{s.effective_from
|
||||
? ` · desde ${s.effective_from}`
|
||||
: ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -279,11 +351,28 @@ export default function Case({
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
requestForm.processing || !services.length
|
||||
requestForm.processing ||
|
||||
!services.some(
|
||||
(service) =>
|
||||
service.id ===
|
||||
requestForm.data.service_version_id,
|
||||
)
|
||||
}
|
||||
>
|
||||
Preparar rascunho de pedido
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
disabled={requestForm.processing}
|
||||
onClick={() =>
|
||||
router.reload({
|
||||
only: ['services'],
|
||||
})
|
||||
}
|
||||
>
|
||||
Actualizar versões disponíveis
|
||||
</button>
|
||||
{!services.length && (
|
||||
<p>
|
||||
Sem serviços publicados. A orientação e os
|
||||
@@ -328,7 +417,7 @@ export default function Case({
|
||||
</article>
|
||||
),
|
||||
)}
|
||||
{(canWrite || manager) && (
|
||||
{!dossier.closed_at && (canWrite || manager) && (
|
||||
<form
|
||||
className={card + ' space-y-3'}
|
||||
onSubmit={(e) => {
|
||||
@@ -412,17 +501,34 @@ export default function Case({
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Identificador do documento de suporte
|
||||
<input
|
||||
Documento de suporte já associado ao dossier
|
||||
<select
|
||||
className={input}
|
||||
value={stageForm.data.document_id}
|
||||
value={stageForm.data.document_link_id}
|
||||
onChange={(e) =>
|
||||
stageForm.setData(
|
||||
'document_id',
|
||||
'document_link_id',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
>
|
||||
<option value="">
|
||||
Sem suporte seleccionado
|
||||
</option>
|
||||
{documents.map((document) => (
|
||||
<option
|
||||
key={document.id}
|
||||
value={document.id}
|
||||
>
|
||||
{document.file_name} · versão{' '}
|
||||
{document.version_no ?? 'por confirmar'}{' '}
|
||||
· {document.source_reference}
|
||||
{document.valid_until
|
||||
? ` · validade declarada ${document.valid_until}`
|
||||
: ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<p>
|
||||
Conclusão e não aplicabilidade exigem revisão por
|
||||
@@ -473,53 +579,85 @@ export default function Case({
|
||||
upload.transform((d) => ({
|
||||
...d,
|
||||
version: dossier.version,
|
||||
file: documentOrigin ? null : d.file,
|
||||
document_id: documentOrigin?.document_id || '',
|
||||
reuse_link_id: documentOrigin?.id || '',
|
||||
source_reference:
|
||||
documentOrigin?.source_reference?.trim()
|
||||
? undefined
|
||||
: d.source_reference,
|
||||
}));
|
||||
upload.post(
|
||||
`/balcao-virtual/dossiers/${dossier.id}/documentos`,
|
||||
{
|
||||
onSuccess: () => {
|
||||
upload.reset(
|
||||
'file',
|
||||
'consent',
|
||||
'source_reference',
|
||||
);
|
||||
if (uploadInput.current)
|
||||
uploadInput.current.value = '';
|
||||
setDocumentOrigin(null);
|
||||
},
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
<label>
|
||||
Ficheiro privado
|
||||
<input
|
||||
className={input}
|
||||
type="file"
|
||||
accept=".pdf,.png,.jpg,.jpeg,.txt"
|
||||
onChange={(e) =>
|
||||
upload.setData(
|
||||
'file',
|
||||
e.target.files?.[0] ?? null,
|
||||
)
|
||||
<DeskDocumentPicker
|
||||
caseId={dossier.id}
|
||||
disabled={upload.processing}
|
||||
selected={documentOrigin}
|
||||
onSelect={(document) => {
|
||||
setDocumentOrigin(document);
|
||||
upload.setData('consent', false);
|
||||
if (document) {
|
||||
upload.setData('file', null);
|
||||
if (uploadInput.current)
|
||||
uploadInput.current.value = '';
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Ou identificador de documento já autorizado
|
||||
<input
|
||||
className={input}
|
||||
value={upload.data.document_id}
|
||||
onChange={(e) =>
|
||||
upload.setData(
|
||||
'document_id',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Proveniência e referência
|
||||
<input
|
||||
className={input}
|
||||
required
|
||||
value={upload.data.source_reference}
|
||||
onChange={(e) =>
|
||||
upload.setData(
|
||||
'source_reference',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
}}
|
||||
/>
|
||||
{!documentOrigin && (
|
||||
<label>
|
||||
Ficheiro privado
|
||||
<input
|
||||
className={input}
|
||||
type="file"
|
||||
ref={uploadInput}
|
||||
accept=".pdf,.png,.jpg,.jpeg,.txt"
|
||||
onChange={(e) =>
|
||||
upload.setData(
|
||||
'file',
|
||||
e.target.files?.[0] ?? null,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
{documentOrigin?.source_reference?.trim() ? (
|
||||
<p>
|
||||
Referência já registada:{' '}
|
||||
{documentOrigin.source_reference}. Será
|
||||
conservada com a validade declarada e a versão
|
||||
do original.
|
||||
</p>
|
||||
) : (
|
||||
<label>
|
||||
Proveniência e referência
|
||||
<input
|
||||
className={input}
|
||||
required
|
||||
value={upload.data.source_reference}
|
||||
onChange={(e) =>
|
||||
upload.setData(
|
||||
'source_reference',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
<label>
|
||||
Assunto da evidência — não equivale a validação
|
||||
<select
|
||||
@@ -565,7 +703,7 @@ export default function Case({
|
||||
</form>
|
||||
)}
|
||||
</section>
|
||||
{manager && !canWrite && (
|
||||
{!dossier.closed_at && manager && !canWrite && (
|
||||
<DocumentReview
|
||||
caseId={dossier.id}
|
||||
version={dossier.version}
|
||||
|
||||
@@ -9,6 +9,7 @@ export default function Catalogue({
|
||||
services: {
|
||||
id: string;
|
||||
version: number;
|
||||
effective_from?: string | null;
|
||||
definition: { title: string; result: string };
|
||||
}[];
|
||||
prepared: Record<string, { title: string; result: string }>;
|
||||
@@ -34,8 +35,16 @@ export default function Catalogue({
|
||||
</p>
|
||||
)}
|
||||
{(installed
|
||||
? services.map((s) => ({ ...s.definition, version: s.version }))
|
||||
: Object.values(prepared).map((s) => ({ ...s, version: null }))
|
||||
? services.map((s) => ({
|
||||
...s.definition,
|
||||
version: s.version,
|
||||
effective_from: s.effective_from,
|
||||
}))
|
||||
: Object.values(prepared).map((s) => ({
|
||||
...s,
|
||||
version: null,
|
||||
effective_from: null,
|
||||
}))
|
||||
).map((s) => (
|
||||
<article className={card} key={s.title}>
|
||||
<h2 className="text-xl font-bold">{s.title}</h2>
|
||||
@@ -45,6 +54,13 @@ export default function Catalogue({
|
||||
? `Versão ${s.version}`
|
||||
: 'Preparado, ainda indisponível para novos pedidos'}
|
||||
</p>
|
||||
{s.effective_from && (
|
||||
<p>
|
||||
Esta versão aplica-se a novos pedidos desde{' '}
|
||||
{s.effective_from}. Pedidos anteriores mantêm o
|
||||
formulário com que foram criados.
|
||||
</p>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
</Frame>
|
||||
|
||||
+572
-151
@@ -1,6 +1,20 @@
|
||||
import { DossierPrefill } from '@/components/dossier-prefill';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { deskFieldApplies } from '@/lib/desk-field-visibility';
|
||||
import {
|
||||
deskEmpty,
|
||||
deskChoices,
|
||||
deskScalar,
|
||||
mergeDeskPrefill,
|
||||
type DeskAnswer,
|
||||
} from '@/lib/desk-field-values';
|
||||
import DeskTypedChoice from '@/components/desk-typed-choice';
|
||||
import DeskDraftRecovery from '@/components/desk-draft-recovery';
|
||||
import DeskAttachmentField, {
|
||||
type AttachmentInventory,
|
||||
} from '@/components/desk-attachment-field';
|
||||
import { useState } from 'react';
|
||||
import type { Field } from '@/pages/desk/service-editor';
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { Frame, card, input, button } from '@/pages/investment/shared';
|
||||
import CountrySelect, { type Country } from '@/components/country-select';
|
||||
@@ -15,21 +29,19 @@ import {
|
||||
type DeskPayment,
|
||||
} from '@/components/desk-internal-operations';
|
||||
|
||||
type Field = {
|
||||
label: string;
|
||||
type: string;
|
||||
required: boolean;
|
||||
options?: Record<string, string>;
|
||||
when?: { field: string; equals: string };
|
||||
};
|
||||
const emptyDocuments: DeskDocument[] = [];
|
||||
|
||||
export default function RequestPage({
|
||||
request,
|
||||
request: initialRequest,
|
||||
case: dossier,
|
||||
definition,
|
||||
owner,
|
||||
manager,
|
||||
analyst,
|
||||
fieldsEditable,
|
||||
operationsEditable = !['closed', 'cancelled'].includes(
|
||||
initialRequest.status,
|
||||
),
|
||||
states,
|
||||
transitions,
|
||||
findings,
|
||||
@@ -38,18 +50,23 @@ export default function RequestPage({
|
||||
territoryPaths,
|
||||
events,
|
||||
documents,
|
||||
reusableDocuments = emptyDocuments,
|
||||
payments,
|
||||
caseVersion,
|
||||
countries,
|
||||
toolPrefill,
|
||||
boundContextRevision = 0,
|
||||
serviceEffectiveFrom,
|
||||
returnReasons = {},
|
||||
}: {
|
||||
returnReasons?: Record<string, string>;
|
||||
serviceEffectiveFrom?: string | null;
|
||||
boundContextRevision?: number;
|
||||
request: {
|
||||
id: string;
|
||||
version: number;
|
||||
status: string;
|
||||
payload: Record<string, string>;
|
||||
payload: Record<string, DeskAnswer>;
|
||||
protocol: string | null;
|
||||
editable_fields: string[];
|
||||
analyst_id: number | null;
|
||||
@@ -65,6 +82,7 @@ export default function RequestPage({
|
||||
manager: boolean;
|
||||
analyst: boolean;
|
||||
fieldsEditable: boolean;
|
||||
operationsEditable?: boolean;
|
||||
states: Record<string, string>;
|
||||
transitions: string[];
|
||||
findings: {
|
||||
@@ -83,6 +101,7 @@ export default function RequestPage({
|
||||
analysts: { id: number; name: string }[];
|
||||
territoryPaths: Record<string, TerritoryOption[]>;
|
||||
documents: DeskDocument[];
|
||||
reusableDocuments?: DeskDocument[];
|
||||
payments: DeskPayment[];
|
||||
caseVersion: number;
|
||||
countries: Country[];
|
||||
@@ -100,6 +119,51 @@ export default function RequestPage({
|
||||
payload: Record<string, unknown>;
|
||||
}[];
|
||||
}) {
|
||||
const [recoveredRequest, setRecoveredRequest] = useState<
|
||||
typeof initialRequest | null
|
||||
>(null);
|
||||
const request =
|
||||
recoveredRequest?.id === initialRequest.id &&
|
||||
recoveredRequest.version > initialRequest.version
|
||||
? recoveredRequest
|
||||
: initialRequest;
|
||||
const [checkpointBusy, setCheckpointBusy] = useState(false);
|
||||
const [checkpointBlocked, setCheckpointBlocked] = useState(false);
|
||||
const [attachmentInventory, setAttachmentInventory] = useState<
|
||||
| (AttachmentInventory & {
|
||||
sourceDocuments: DeskDocument[];
|
||||
sourceReusable: DeskDocument[];
|
||||
})
|
||||
| null
|
||||
>(null);
|
||||
const [attachmentBusy, setAttachmentBusy] = useState<
|
||||
Record<string, boolean>
|
||||
>({});
|
||||
const filesBusy = Object.values(attachmentBusy).some(Boolean);
|
||||
const inventoryNewer =
|
||||
attachmentInventory && attachmentInventory.case_version > caseVersion;
|
||||
const inventorySame =
|
||||
attachmentInventory && attachmentInventory.case_version === caseVersion;
|
||||
const currentInventory = {
|
||||
case_version: Math.max(
|
||||
attachmentInventory?.case_version ?? 0,
|
||||
caseVersion,
|
||||
),
|
||||
documents:
|
||||
attachmentInventory &&
|
||||
(inventoryNewer ||
|
||||
(inventorySame &&
|
||||
attachmentInventory.sourceDocuments === documents))
|
||||
? attachmentInventory.documents
|
||||
: documents,
|
||||
reusable_documents:
|
||||
attachmentInventory &&
|
||||
(inventoryNewer ||
|
||||
(inventorySame &&
|
||||
attachmentInventory.sourceReusable === reusableDocuments))
|
||||
? (attachmentInventory.reusable_documents ?? emptyDocuments)
|
||||
: reusableDocuments,
|
||||
};
|
||||
const form = useForm({
|
||||
context_revision: 0,
|
||||
context_reviewed: false,
|
||||
@@ -114,6 +178,7 @@ export default function RequestPage({
|
||||
status: transitions[0] ?? '',
|
||||
reason: '',
|
||||
editable_fields: [] as string[],
|
||||
return_reason_code: 'unspecified',
|
||||
});
|
||||
const assignment = useForm({
|
||||
version: request.version,
|
||||
@@ -122,9 +187,19 @@ export default function RequestPage({
|
||||
due_at: '',
|
||||
});
|
||||
const message = useForm({ body: '', client_key: createOperationKey() });
|
||||
const canEdit = owner && fieldsEditable;
|
||||
const canEdit =
|
||||
owner &&
|
||||
fieldsEditable &&
|
||||
['draft', 'returned'].includes(request.status);
|
||||
return (
|
||||
<Frame title={definition.title}>
|
||||
{serviceEffectiveFrom && (
|
||||
<p>
|
||||
Entrada em vigor do formulário deste pedido:{' '}
|
||||
{serviceEffectiveFrom}. O pedido conserva a versão com que
|
||||
foi criado.
|
||||
</p>
|
||||
)}
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/balcao-virtual/dossiers/${dossier.id}`}
|
||||
@@ -132,6 +207,56 @@ export default function RequestPage({
|
||||
Voltar ao dossier {dossier.title}
|
||||
</Link>
|
||||
<p>{definition.result}</p>
|
||||
{canEdit && (
|
||||
<DeskDraftRecovery
|
||||
key={`${request.id}:${request.version}`}
|
||||
id={request.id}
|
||||
version={request.version}
|
||||
payload={form.data.payload}
|
||||
initial={request.payload}
|
||||
reason={form.data.reason}
|
||||
fields={Object.fromEntries(
|
||||
Object.entries(definition.fields).map(
|
||||
([key, field]) => [
|
||||
key,
|
||||
field.type === 'attachment'
|
||||
? {
|
||||
...field,
|
||||
options: Object.fromEntries(
|
||||
currentInventory.documents.map(
|
||||
(document) => [
|
||||
document.id,
|
||||
document.file_name,
|
||||
],
|
||||
),
|
||||
),
|
||||
}
|
||||
: field,
|
||||
],
|
||||
),
|
||||
)}
|
||||
paused={form.processing}
|
||||
pendingWork={filesBusy}
|
||||
onBusy={setCheckpointBusy}
|
||||
onBlocked={setCheckpointBlocked}
|
||||
onRecover={(payload, reason, current) => {
|
||||
setRecoveredRequest({
|
||||
...request,
|
||||
...current,
|
||||
payload: current.payload,
|
||||
});
|
||||
form.setData((d) => ({
|
||||
...d,
|
||||
payload,
|
||||
reason,
|
||||
version: current.version,
|
||||
consent: false,
|
||||
context_reviewed: false,
|
||||
context_revision: 0,
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{owner && (
|
||||
<DossierPrefill
|
||||
contextId={dossier.id}
|
||||
@@ -145,8 +270,11 @@ export default function RequestPage({
|
||||
'context_opportunity',
|
||||
].filter(
|
||||
(k) =>
|
||||
request.status !== 'returned' ||
|
||||
request.editable_fields.includes(k),
|
||||
!['consent', 'attachment'].includes(
|
||||
definition.fields[k]?.type,
|
||||
) &&
|
||||
(request.status !== 'returned' ||
|
||||
request.editable_fields.includes(k)),
|
||||
)}
|
||||
onReview={(revision, reviewed) =>
|
||||
form.setData((d) => ({
|
||||
@@ -158,21 +286,12 @@ export default function RequestPage({
|
||||
onApply={(patch, replace) =>
|
||||
form.setData((d) => ({
|
||||
...d,
|
||||
payload: {
|
||||
...d.payload,
|
||||
...Object.fromEntries(
|
||||
Object.entries(patch)
|
||||
.filter(
|
||||
([k]) =>
|
||||
replace ||
|
||||
!d.payload[k]?.trim(),
|
||||
)
|
||||
.map(([k, v]) => [
|
||||
k,
|
||||
typeof v === 'string' ? v : '',
|
||||
]),
|
||||
),
|
||||
},
|
||||
payload: mergeDeskPrefill(
|
||||
d.payload,
|
||||
patch,
|
||||
definition.fields,
|
||||
replace,
|
||||
),
|
||||
}))
|
||||
}
|
||||
/>
|
||||
@@ -226,7 +345,10 @@ export default function RequestPage({
|
||||
className={button}
|
||||
disabled={
|
||||
form.processing ||
|
||||
!!form.data.payload.description?.trim()
|
||||
checkpointBusy ||
|
||||
checkpointBlocked ||
|
||||
filesBusy ||
|
||||
!deskEmpty(form.data.payload.description)
|
||||
}
|
||||
onClick={() => {
|
||||
form.transform((data) => ({
|
||||
@@ -279,6 +401,13 @@ export default function RequestPage({
|
||||
className={card + ' space-y-3'}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (
|
||||
checkpointBusy ||
|
||||
checkpointBlocked ||
|
||||
filesBusy ||
|
||||
!canEdit
|
||||
)
|
||||
return;
|
||||
form.transform((d) => ({
|
||||
...d,
|
||||
version: request.version,
|
||||
@@ -295,7 +424,7 @@ export default function RequestPage({
|
||||
label="País do requerente (opcional)"
|
||||
error={form.errors['payload.country']}
|
||||
countries={countries}
|
||||
value={form.data.payload.country ?? ''}
|
||||
value={deskScalar(form.data.payload.country)}
|
||||
allowLegacyValue
|
||||
onChange={(value) =>
|
||||
form.setData('payload', {
|
||||
@@ -317,7 +446,9 @@ export default function RequestPage({
|
||||
label="País de origem do pedido (opcional)"
|
||||
error={form.errors['payload.declared_origin_country_code']}
|
||||
countries={countries}
|
||||
value={form.data.payload.declared_origin_country_code ?? ''}
|
||||
value={deskScalar(
|
||||
form.data.payload.declared_origin_country_code,
|
||||
)}
|
||||
disabled={
|
||||
!canEdit ||
|
||||
form.processing ||
|
||||
@@ -378,6 +509,140 @@ export default function RequestPage({
|
||||
</p>
|
||||
)}
|
||||
</fieldset>
|
||||
) : f.type === 'attachment' ? (
|
||||
<div key={key}>
|
||||
<DeskAttachmentField
|
||||
caseId={dossier.id}
|
||||
requestId={request.id}
|
||||
caseVersion={currentInventory.case_version}
|
||||
fieldKey={key}
|
||||
field={f}
|
||||
value={form.data.payload[key]}
|
||||
documents={currentInventory.documents}
|
||||
reusableDocuments={
|
||||
currentInventory.reusable_documents
|
||||
}
|
||||
disabled={
|
||||
!canEdit ||
|
||||
form.processing ||
|
||||
(request.status === 'returned' &&
|
||||
!request.editable_fields.includes(
|
||||
key,
|
||||
))
|
||||
}
|
||||
uploading={filesBusy}
|
||||
onBusy={(value) =>
|
||||
setAttachmentBusy((state) => ({
|
||||
...state,
|
||||
[key]: value,
|
||||
}))
|
||||
}
|
||||
onChange={(value) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
[key]: value,
|
||||
})
|
||||
}
|
||||
onInventory={(result, select) => {
|
||||
setAttachmentInventory({
|
||||
...result,
|
||||
reusable_documents:
|
||||
result.reusable_documents ??
|
||||
currentInventory.reusable_documents,
|
||||
sourceDocuments: documents,
|
||||
sourceReusable: reusableDocuments,
|
||||
});
|
||||
const linkId = result.link_id;
|
||||
if (select && linkId)
|
||||
form.setData((d) => {
|
||||
const ids = deskChoices(
|
||||
d.payload[key],
|
||||
);
|
||||
const uploaded =
|
||||
result.documents.find(
|
||||
(document) =>
|
||||
document.id ===
|
||||
linkId,
|
||||
);
|
||||
const alreadySelected =
|
||||
ids.includes(linkId) ||
|
||||
(!!uploaded &&
|
||||
ids.some(
|
||||
(id) =>
|
||||
result.documents.find(
|
||||
(
|
||||
document,
|
||||
) =>
|
||||
document.id ===
|
||||
id,
|
||||
)
|
||||
?.document_id ===
|
||||
uploaded.document_id,
|
||||
));
|
||||
return {
|
||||
...d,
|
||||
payload: {
|
||||
...d.payload,
|
||||
[key]:
|
||||
alreadySelected ||
|
||||
ids.length >=
|
||||
(f.max_files ??
|
||||
1)
|
||||
? ids
|
||||
: [
|
||||
...ids,
|
||||
linkId,
|
||||
],
|
||||
},
|
||||
};
|
||||
});
|
||||
}}
|
||||
/>
|
||||
{Object.entries(form.errors)
|
||||
.filter(
|
||||
([path]) =>
|
||||
path === `payload.${key}` ||
|
||||
path.startsWith(`payload.${key}.`),
|
||||
)
|
||||
.map(([path, error]) => (
|
||||
<p role="alert" key={path}>
|
||||
{error}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
) : ['multiselect', 'consent'].includes(f.type) ? (
|
||||
<div key={key}>
|
||||
<DeskTypedChoice
|
||||
fieldKey={key}
|
||||
field={f}
|
||||
value={form.data.payload[key]}
|
||||
disabled={
|
||||
!canEdit ||
|
||||
form.processing ||
|
||||
(request.status === 'returned' &&
|
||||
!request.editable_fields.includes(
|
||||
key,
|
||||
))
|
||||
}
|
||||
onChange={(value) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
[key]: value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
{Object.entries(form.errors)
|
||||
.filter(
|
||||
([path]) =>
|
||||
path === `payload.${key}` ||
|
||||
path.startsWith(`payload.${key}.`),
|
||||
)
|
||||
.map(([path, error]) => (
|
||||
<p key={path} role="alert">
|
||||
{error}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<label className="block" key={key}>
|
||||
{f.label}
|
||||
@@ -392,7 +657,9 @@ export default function RequestPage({
|
||||
key,
|
||||
))
|
||||
}
|
||||
value={form.data.payload[key] ?? ''}
|
||||
value={deskScalar(
|
||||
form.data.payload[key],
|
||||
)}
|
||||
onChange={(e) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
@@ -419,7 +686,9 @@ export default function RequestPage({
|
||||
key,
|
||||
))
|
||||
}
|
||||
value={form.data.payload[key] ?? ''}
|
||||
value={deskScalar(
|
||||
form.data.payload[key],
|
||||
)}
|
||||
onChange={(e) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
@@ -449,7 +718,9 @@ export default function RequestPage({
|
||||
key,
|
||||
))
|
||||
}
|
||||
value={form.data.payload[key] ?? ''}
|
||||
value={deskScalar(
|
||||
form.data.payload[key],
|
||||
)}
|
||||
onChange={(e) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
@@ -463,17 +734,27 @@ export default function RequestPage({
|
||||
)}
|
||||
{canEdit && (
|
||||
<>
|
||||
<label>
|
||||
Justificação de correcção
|
||||
<textarea
|
||||
className={input}
|
||||
value={form.data.reason}
|
||||
onChange={(e) =>
|
||||
form.setData('reason', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<button className={button} disabled={form.processing}>
|
||||
{request.status === 'returned' && (
|
||||
<label>
|
||||
Justificação de correcção
|
||||
<textarea
|
||||
className={input}
|
||||
value={form.data.reason}
|
||||
onChange={(e) =>
|
||||
form.setData('reason', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
form.processing ||
|
||||
checkpointBusy ||
|
||||
checkpointBlocked ||
|
||||
filesBusy
|
||||
}
|
||||
>
|
||||
Guardar rascunho
|
||||
</button>
|
||||
<label className="flex gap-2">
|
||||
@@ -490,8 +771,21 @@ export default function RequestPage({
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={form.processing || !form.data.consent}
|
||||
disabled={
|
||||
form.processing ||
|
||||
checkpointBusy ||
|
||||
checkpointBlocked ||
|
||||
filesBusy ||
|
||||
!form.data.consent
|
||||
}
|
||||
onClick={() => {
|
||||
if (
|
||||
checkpointBusy ||
|
||||
checkpointBlocked ||
|
||||
filesBusy ||
|
||||
!canEdit
|
||||
)
|
||||
return;
|
||||
form.transform((d) => ({
|
||||
...d,
|
||||
version: request.version,
|
||||
@@ -512,108 +806,228 @@ export default function RequestPage({
|
||||
</p>
|
||||
))}
|
||||
</form>
|
||||
{!owner && (manager || analyst) && transitions.length > 0 && (
|
||||
<form
|
||||
className={card + ' space-y-3'}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
decision.transform((d) => ({
|
||||
...d,
|
||||
version: request.version,
|
||||
}));
|
||||
decision.post(
|
||||
`/balcao-virtual/pedidos/${request.id}/estado`,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<h2 className="text-xl font-bold">
|
||||
Resposta / análise do responsável
|
||||
</h2>
|
||||
<label>
|
||||
Estado
|
||||
<select
|
||||
className={input}
|
||||
value={decision.data.status}
|
||||
onChange={(e) =>
|
||||
decision.setData('status', e.target.value)
|
||||
{operationsEditable &&
|
||||
owner &&
|
||||
['draft', 'returned'].includes(request.status) && (
|
||||
<form
|
||||
className={card + ' space-y-3'}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
if (
|
||||
decision.processing ||
|
||||
form.processing ||
|
||||
checkpointBusy ||
|
||||
filesBusy
|
||||
)
|
||||
return;
|
||||
decision.transform((data) => ({
|
||||
...data,
|
||||
version: request.version,
|
||||
status: 'cancelled',
|
||||
}));
|
||||
decision.post(
|
||||
`/balcao-virtual/pedidos/${request.id}/estado`,
|
||||
{
|
||||
onSuccess: (page) => {
|
||||
const saved = page.props.request as
|
||||
| typeof initialRequest
|
||||
| undefined;
|
||||
if (
|
||||
saved?.id === request.id &&
|
||||
saved.status === 'cancelled'
|
||||
) {
|
||||
form.setData(
|
||||
'payload',
|
||||
saved.payload,
|
||||
);
|
||||
form.setData(
|
||||
'version',
|
||||
saved.version,
|
||||
);
|
||||
form.setData('reason', '');
|
||||
form.setData('consent', false);
|
||||
setRecoveredRequest(null);
|
||||
}
|
||||
},
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
<h2 className="text-xl font-bold">
|
||||
Cancelar este pedido
|
||||
</h2>
|
||||
<p>
|
||||
O cancelamento conserva a última versão guardada, os
|
||||
documentos e o histórico. O dossier continua
|
||||
disponível; alterações por guardar não são
|
||||
submetidas.
|
||||
</p>
|
||||
<label className="block">
|
||||
Motivo do cancelamento
|
||||
<textarea
|
||||
className={input}
|
||||
required
|
||||
minLength={3}
|
||||
maxLength={5000}
|
||||
value={decision.data.reason}
|
||||
onChange={(event) =>
|
||||
decision.setData(
|
||||
'reason',
|
||||
event.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
decision.processing ||
|
||||
form.processing ||
|
||||
checkpointBusy ||
|
||||
filesBusy
|
||||
}
|
||||
>
|
||||
{transitions
|
||||
.filter(
|
||||
(s) =>
|
||||
manager ||
|
||||
![
|
||||
'accepted',
|
||||
'rejected',
|
||||
'closed',
|
||||
].includes(s),
|
||||
)
|
||||
.map((s) => (
|
||||
<option value={s} key={s}>
|
||||
{states[s]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Fundamento da resposta
|
||||
<textarea
|
||||
className={input}
|
||||
required
|
||||
minLength={3}
|
||||
value={decision.data.reason}
|
||||
onChange={(e) =>
|
||||
decision.setData('reason', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
{decision.data.status === 'returned' && (
|
||||
<fieldset>
|
||||
<legend>Campos autorizados para correcção</legend>
|
||||
{Object.entries({
|
||||
...definition.fields,
|
||||
country: { label: 'País do requerente' },
|
||||
declared_origin_country_code: {
|
||||
label: 'Origem declarada da solicitação',
|
||||
},
|
||||
}).map(([k, f]) => (
|
||||
<label className="block" key={k}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={decision.data.editable_fields.includes(
|
||||
k,
|
||||
)}
|
||||
Confirmar cancelamento deste pedido
|
||||
</button>
|
||||
{Object.entries(decision.errors).map(([key, error]) => (
|
||||
<p role="alert" key={key}>
|
||||
{error}
|
||||
</p>
|
||||
))}
|
||||
</form>
|
||||
)}
|
||||
{operationsEditable &&
|
||||
!owner &&
|
||||
(manager || analyst) &&
|
||||
transitions.length > 0 && (
|
||||
<form
|
||||
className={card + ' space-y-3'}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
decision.transform((d) => ({
|
||||
...d,
|
||||
version: request.version,
|
||||
}));
|
||||
decision.post(
|
||||
`/balcao-virtual/pedidos/${request.id}/estado`,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<h2 className="text-xl font-bold">
|
||||
Resposta / análise do responsável
|
||||
</h2>
|
||||
<label>
|
||||
Estado
|
||||
<select
|
||||
className={input}
|
||||
value={decision.data.status}
|
||||
onChange={(e) =>
|
||||
decision.setData('status', e.target.value)
|
||||
}
|
||||
>
|
||||
{transitions
|
||||
.filter(
|
||||
(s) =>
|
||||
manager ||
|
||||
![
|
||||
'accepted',
|
||||
'rejected',
|
||||
'closed',
|
||||
].includes(s),
|
||||
)
|
||||
.map((s) => (
|
||||
<option value={s} key={s}>
|
||||
{states[s]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Fundamento da resposta
|
||||
<textarea
|
||||
className={input}
|
||||
required
|
||||
minLength={3}
|
||||
value={decision.data.reason}
|
||||
onChange={(e) =>
|
||||
decision.setData('reason', e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
{decision.data.status === 'returned' && (
|
||||
<fieldset>
|
||||
<legend>Devolução para correcção</legend>
|
||||
<label className="block">
|
||||
Categoria do motivo (opcional, para
|
||||
indicadores)
|
||||
<select
|
||||
className={input}
|
||||
value={decision.data.return_reason_code}
|
||||
onChange={(e) =>
|
||||
decision.setData(
|
||||
'editable_fields',
|
||||
e.target.checked
|
||||
? [
|
||||
...decision.data
|
||||
.editable_fields,
|
||||
k,
|
||||
]
|
||||
: decision.data.editable_fields.filter(
|
||||
(v) => v !== k,
|
||||
),
|
||||
'return_reason_code',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>{' '}
|
||||
{f.label}
|
||||
>
|
||||
{Object.entries(returnReasons).map(
|
||||
([code, label]) => (
|
||||
<option key={code} value={code}>
|
||||
{label}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
)}
|
||||
<button className={button} disabled={decision.processing}>
|
||||
Registar resposta fundamentada
|
||||
</button>
|
||||
{Object.entries(decision.errors).map(([k, v]) => (
|
||||
<p role="alert" key={k}>
|
||||
{v}
|
||||
</p>
|
||||
))}
|
||||
</form>
|
||||
)}
|
||||
{manager &&
|
||||
<p>Campos autorizados para correcção</p>
|
||||
{Object.entries({
|
||||
...definition.fields,
|
||||
country: { label: 'País do requerente' },
|
||||
declared_origin_country_code: {
|
||||
label: 'Origem declarada da solicitação',
|
||||
},
|
||||
}).map(([k, f]) => (
|
||||
<label className="block" key={k}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={decision.data.editable_fields.includes(
|
||||
k,
|
||||
)}
|
||||
onChange={(e) =>
|
||||
decision.setData(
|
||||
'editable_fields',
|
||||
e.target.checked
|
||||
? [
|
||||
...decision.data
|
||||
.editable_fields,
|
||||
k,
|
||||
]
|
||||
: decision.data.editable_fields.filter(
|
||||
(v) => v !== k,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>{' '}
|
||||
{f.label}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
)}
|
||||
<button
|
||||
className={button}
|
||||
disabled={decision.processing}
|
||||
>
|
||||
Registar resposta fundamentada
|
||||
</button>
|
||||
{Object.entries(decision.errors).map(([k, v]) => (
|
||||
<p role="alert" key={k}>
|
||||
{v}
|
||||
</p>
|
||||
))}
|
||||
</form>
|
||||
)}
|
||||
{operationsEditable &&
|
||||
manager &&
|
||||
!['draft', 'closed', 'cancelled'].includes(request.status) && (
|
||||
<form
|
||||
className={card + ' space-y-3'}
|
||||
@@ -706,7 +1120,7 @@ export default function RequestPage({
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
{!['closed', 'cancelled'].includes(request.status) && (
|
||||
{operationsEditable && (
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -750,7 +1164,7 @@ export default function RequestPage({
|
||||
</form>
|
||||
)}
|
||||
</section>
|
||||
{!owner && (manager || analyst) && (
|
||||
{operationsEditable && !owner && (manager || analyst) && (
|
||||
<DocumentReview
|
||||
caseId={dossier.id}
|
||||
version={caseVersion}
|
||||
@@ -758,15 +1172,13 @@ export default function RequestPage({
|
||||
requestId={request.id}
|
||||
/>
|
||||
)}
|
||||
{!['closed', 'cancelled'].includes(request.status) && (
|
||||
<RequestOperations
|
||||
requestId={request.id}
|
||||
owner={owner}
|
||||
reviewer={!owner && (manager || analyst)}
|
||||
documents={documents}
|
||||
payments={payments}
|
||||
/>
|
||||
)}
|
||||
<RequestOperations
|
||||
requestId={request.id}
|
||||
owner={owner && operationsEditable}
|
||||
reviewer={operationsEditable && !owner && (manager || analyst)}
|
||||
documents={documents}
|
||||
payments={payments}
|
||||
/>
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-bold">Respostas e histórico</h2>
|
||||
{events.map((e) => (
|
||||
@@ -777,6 +1189,15 @@ export default function RequestPage({
|
||||
{typeof e.payload.reason === 'string' && (
|
||||
<p>{e.payload.reason}</p>
|
||||
)}
|
||||
{e.action === 'request_returned' && (
|
||||
<p>
|
||||
Categoria:{' '}
|
||||
{typeof e.payload.return_reason_label ===
|
||||
'string'
|
||||
? e.payload.return_reason_label
|
||||
: 'Sem classificação registada'}
|
||||
</p>
|
||||
)}
|
||||
{[
|
||||
'document_reviewed',
|
||||
'payment_reviewed',
|
||||
|
||||
@@ -9,7 +9,11 @@ export type Field = {
|
||||
required: boolean;
|
||||
min?: number;
|
||||
options?: Record<string, string>;
|
||||
when?: { field: string; equals: string };
|
||||
statement?: string;
|
||||
mime_types?: string[];
|
||||
max_size_kb?: number;
|
||||
max_files?: number;
|
||||
when?: { field: string; equals: string; operator?: 'equals' | 'contains' };
|
||||
};
|
||||
export type Definition = {
|
||||
title: string;
|
||||
@@ -26,6 +30,9 @@ type Service = {
|
||||
definition: Definition;
|
||||
fixedTypes?: Record<string, string>;
|
||||
editable?: boolean;
|
||||
effective_from?: string | null;
|
||||
activeVersion?: number;
|
||||
upcoming?: { version: number; effective_from: string }[];
|
||||
};
|
||||
const types: Record<string, string> = {
|
||||
text: 'Texto curto',
|
||||
@@ -33,6 +40,9 @@ const types: Record<string, string> = {
|
||||
number: 'Número',
|
||||
date: 'Data',
|
||||
select: 'Lista de opções',
|
||||
multiselect: 'Selecção múltipla',
|
||||
consent: 'Declaração de consentimento',
|
||||
attachment: 'Anexos de documentos autorizados',
|
||||
territory: 'Localização do cadastro',
|
||||
email: 'Email',
|
||||
tel: 'Telefone',
|
||||
@@ -51,6 +61,14 @@ function describeField(field: Field | undefined): string {
|
||||
field.label,
|
||||
types[field.type] ?? field.type,
|
||||
field.required ? 'Obrigatório' : 'Opcional',
|
||||
...(field.statement ? [`Declaração: ${field.statement}`] : []),
|
||||
...(field.type === 'attachment'
|
||||
? [
|
||||
`Formatos: ${field.mime_types?.join(', ')}`,
|
||||
`Tamanho por ficheiro: ${field.max_size_kb} KiB`,
|
||||
`Máximo de ficheiros: ${field.max_files}`,
|
||||
]
|
||||
: []),
|
||||
...(field.min !== undefined ? [`Mínimo: ${field.min}`] : []),
|
||||
...(field.options
|
||||
? [
|
||||
@@ -60,12 +78,22 @@ function describeField(field: Field | undefined): string {
|
||||
]
|
||||
: []),
|
||||
field.when
|
||||
? `Aplica-se quando ${field.when.field} = ${field.when.equals}`
|
||||
? `Aplica-se quando ${field.when.field} ${field.when.operator === 'contains' ? 'inclui' : '='} ${field.when.equals}`
|
||||
: 'Sempre aplicável',
|
||||
].join(' · ');
|
||||
}
|
||||
|
||||
export default function ServiceEditor({ services }: { services: Service[] }) {
|
||||
export default function ServiceEditor({
|
||||
services,
|
||||
schedulingAvailable = false,
|
||||
today = '',
|
||||
calendarTimezone = '',
|
||||
}: {
|
||||
services: Service[];
|
||||
schedulingAvailable?: boolean;
|
||||
today?: string;
|
||||
calendarTimezone?: string;
|
||||
}) {
|
||||
const [code, setCode] = useState(services[0]?.code ?? '');
|
||||
const service = services.find((row) => row.code === code);
|
||||
return (
|
||||
@@ -103,6 +131,9 @@ export default function ServiceEditor({ services }: { services: Service[] }) {
|
||||
<Editor
|
||||
key={`${service.code}:${service.version}`}
|
||||
service={service}
|
||||
schedulingAvailable={schedulingAvailable}
|
||||
today={today}
|
||||
calendarTimezone={calendarTimezone}
|
||||
/>
|
||||
) : !service ? (
|
||||
<p>Não existem serviços disponíveis para edição.</p>
|
||||
@@ -118,7 +149,17 @@ export default function ServiceEditor({ services }: { services: Service[] }) {
|
||||
);
|
||||
}
|
||||
|
||||
function Editor({ service }: { service: Service }) {
|
||||
function Editor({
|
||||
service,
|
||||
schedulingAvailable = false,
|
||||
today = '',
|
||||
calendarTimezone = '',
|
||||
}: {
|
||||
service: Service;
|
||||
schedulingAvailable?: boolean;
|
||||
today?: string;
|
||||
calendarTimezone?: string;
|
||||
}) {
|
||||
const form = useForm(
|
||||
`desk-service-editor:${service.code}:${service.version}`,
|
||||
{
|
||||
@@ -126,11 +167,24 @@ function Editor({ service }: { service: Service }) {
|
||||
definition: structuredClone(service.definition),
|
||||
reason: '',
|
||||
confirm: false,
|
||||
effective_from:
|
||||
schedulingAvailable &&
|
||||
service.effective_from &&
|
||||
service.effective_from > today
|
||||
? service.effective_from
|
||||
: '',
|
||||
},
|
||||
);
|
||||
const [newKey, setNewKey] = useState('');
|
||||
const [localError, setLocalError] = useState('');
|
||||
const fields = form.data.definition.fields;
|
||||
const dateChanged =
|
||||
schedulingAvailable &&
|
||||
(form.data.effective_from
|
||||
? form.data.effective_from !== (service.effective_from ?? '')
|
||||
: Boolean(
|
||||
service.effective_from && service.effective_from > today,
|
||||
));
|
||||
const setFields = (value: Record<string, Field>) =>
|
||||
form.setData((data) => ({
|
||||
...data,
|
||||
@@ -202,6 +256,67 @@ function Editor({ service }: { service: Service }) {
|
||||
Etapa do percurso existente: {service.definition.stage}.
|
||||
Este editor não altera a sequência de tramitação.
|
||||
</p>
|
||||
<p>
|
||||
Base de edição: última versão publicada, {service.version}.
|
||||
Versão actualmente disponível para novos pedidos:{' '}
|
||||
{(service.activeVersion ?? service.version) || 'nenhuma'}.
|
||||
Entrada em vigor da base:{' '}
|
||||
{service.effective_from ||
|
||||
'sem data explícita (versão histórica)'}
|
||||
.
|
||||
</p>
|
||||
{Boolean(service.upcoming?.length) && (
|
||||
<div>
|
||||
<p>
|
||||
Edições já agendadas que se aplicarão nas
|
||||
respectivas datas:
|
||||
</p>
|
||||
<ul>
|
||||
{service.upcoming!.map((edition) => (
|
||||
<li key={edition.version}>
|
||||
Versão {edition.version}:{' '}
|
||||
{edition.effective_from}.
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p>
|
||||
Uma correcção imediata não cancela estas datas. Para
|
||||
substituir uma edição futura, publique a correcção
|
||||
com a mesma data de início.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{schedulingAvailable ? (
|
||||
<label className="block">
|
||||
Data de entrada em vigor da nova versão
|
||||
<input
|
||||
className={input}
|
||||
type="date"
|
||||
min={today || undefined}
|
||||
value={form.data.effective_from}
|
||||
onChange={(event) =>
|
||||
form.setData((data) => ({
|
||||
...data,
|
||||
confirm: false,
|
||||
effective_from: event.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
<span className="block text-sm">
|
||||
Vazio significa a data da publicação. Calendário do
|
||||
portal
|
||||
{calendarTimezone ? `: ${calendarTimezone}` : ''}.
|
||||
Versões futuras não substituem a versão actual antes
|
||||
dessa data.
|
||||
</span>
|
||||
</label>
|
||||
) : (
|
||||
<p className="text-sm">
|
||||
O agendamento requer a actualização das datas de entrada
|
||||
em vigor neste destino. A publicação imediata existente
|
||||
continua disponível.
|
||||
</p>
|
||||
)}
|
||||
</fieldset>
|
||||
<fieldset disabled={form.processing} className="space-y-4">
|
||||
<legend className="text-xl font-bold">
|
||||
@@ -240,14 +355,54 @@ function Editor({ service }: { service: Service }) {
|
||||
...field,
|
||||
type: event.target.value,
|
||||
};
|
||||
if (next.type !== 'select')
|
||||
if (
|
||||
!['select', 'multiselect'].includes(
|
||||
next.type,
|
||||
)
|
||||
)
|
||||
delete next.options;
|
||||
else
|
||||
next.options ??= {
|
||||
opcao_1: 'Primeira opção',
|
||||
};
|
||||
if (next.type !== 'number') delete next.min;
|
||||
setFields({ ...fields, [key]: next });
|
||||
if (next.type !== 'consent')
|
||||
delete next.statement;
|
||||
else next.statement ??= '';
|
||||
if (next.type === 'attachment') {
|
||||
next.mime_types ??= [
|
||||
'application/pdf',
|
||||
'image/png',
|
||||
'image/jpeg',
|
||||
'text/plain',
|
||||
];
|
||||
next.max_size_kb ??= 10240;
|
||||
next.max_files ??= 1;
|
||||
} else {
|
||||
delete next.mime_types;
|
||||
delete next.max_size_kb;
|
||||
delete next.max_files;
|
||||
}
|
||||
const changedFields = {
|
||||
...fields,
|
||||
[key]: next,
|
||||
};
|
||||
for (const [
|
||||
dependentKey,
|
||||
dependent,
|
||||
] of Object.entries(changedFields)) {
|
||||
if (dependent.when?.field !== key)
|
||||
continue;
|
||||
const when = { ...dependent.when };
|
||||
if (next.type === 'multiselect')
|
||||
when.operator = 'contains';
|
||||
else delete when.operator;
|
||||
changedFields[dependentKey] = {
|
||||
...dependent,
|
||||
when,
|
||||
};
|
||||
}
|
||||
setFields(changedFields);
|
||||
}}
|
||||
>
|
||||
{Object.entries(types).map(([value, label]) => (
|
||||
@@ -293,7 +448,118 @@ function Editor({ service }: { service: Service }) {
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
{field.type === 'select' && (
|
||||
{field.type === 'attachment' && (
|
||||
<fieldset className="space-y-2 rounded border p-3">
|
||||
<legend>
|
||||
Limites dos documentos desta pergunta
|
||||
</legend>
|
||||
<p>
|
||||
Aplicam-se à versão publicada e aos novos
|
||||
pedidos que a utilizarem. Pedidos anteriores
|
||||
conservam os seus limites.
|
||||
</p>
|
||||
{Object.entries({
|
||||
'application/pdf': 'PDF',
|
||||
'image/png': 'Imagem PNG',
|
||||
'image/jpeg': 'Imagem JPEG',
|
||||
'text/plain': 'Texto simples',
|
||||
}).map(([mime, label]) => (
|
||||
<label className="block" key={mime}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={
|
||||
field.mime_types?.includes(
|
||||
mime,
|
||||
) ?? false
|
||||
}
|
||||
onChange={(event) =>
|
||||
update(key, {
|
||||
mime_types: event.target
|
||||
.checked
|
||||
? [
|
||||
...(field.mime_types ??
|
||||
[]),
|
||||
mime,
|
||||
]
|
||||
: (
|
||||
field.mime_types ??
|
||||
[]
|
||||
).filter(
|
||||
(value) =>
|
||||
value !==
|
||||
mime,
|
||||
),
|
||||
})
|
||||
}
|
||||
/>{' '}
|
||||
{label}
|
||||
</label>
|
||||
))}
|
||||
<label className="block">
|
||||
Máximo por ficheiro (KB)
|
||||
<input
|
||||
className={input}
|
||||
type="number"
|
||||
required
|
||||
min={1}
|
||||
max={10240}
|
||||
step={1}
|
||||
value={field.max_size_kb ?? ''}
|
||||
onChange={(event) =>
|
||||
update(key, {
|
||||
max_size_kb: Number(
|
||||
event.target.value,
|
||||
),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
Máximo de ficheiros seleccionados
|
||||
<input
|
||||
className={input}
|
||||
type="number"
|
||||
required
|
||||
min={1}
|
||||
max={100}
|
||||
step={1}
|
||||
value={field.max_files ?? ''}
|
||||
onChange={(event) =>
|
||||
update(key, {
|
||||
max_files: Number(
|
||||
event.target.value,
|
||||
),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
</fieldset>
|
||||
)}
|
||||
{field.type === 'consent' && (
|
||||
<label className="block">
|
||||
Texto exacto da declaração
|
||||
<textarea
|
||||
required
|
||||
minLength={3}
|
||||
maxLength={5000}
|
||||
className={input}
|
||||
value={field.statement ?? ''}
|
||||
onChange={(event) =>
|
||||
update(key, {
|
||||
statement: event.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<span className="block text-sm">
|
||||
A pessoa escolhe aceitar ou recusar;
|
||||
obrigatório exige uma resposta explícita.
|
||||
Esta escolha não substitui o consentimento
|
||||
da submissão nem concede permissões ou
|
||||
validação oficial.
|
||||
</span>
|
||||
</label>
|
||||
)}
|
||||
{['select', 'multiselect'].includes(field.type) && (
|
||||
<fieldset className="space-y-2">
|
||||
<legend>Opções de resposta</legend>
|
||||
{Object.entries(field.options ?? {}).map(
|
||||
@@ -370,17 +636,40 @@ function Editor({ service }: { service: Service }) {
|
||||
next.when = {
|
||||
field: event.target.value,
|
||||
equals: '',
|
||||
...(fields[event.target.value]
|
||||
?.type === 'multiselect'
|
||||
? {
|
||||
operator:
|
||||
'contains' as const,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
else delete next.when;
|
||||
setFields({ ...fields, [key]: next });
|
||||
}}
|
||||
>
|
||||
<option value="">Sempre</option>
|
||||
{field.when &&
|
||||
(!fields[field.when.field] ||
|
||||
['number', 'attachment'].includes(
|
||||
fields[field.when.field].type,
|
||||
)) && (
|
||||
<option
|
||||
disabled
|
||||
value={field.when.field}
|
||||
>
|
||||
Origem indisponível para esta
|
||||
condição; escolha outra resposta ou
|
||||
«Sempre»
|
||||
</option>
|
||||
)}
|
||||
{Object.entries(fields)
|
||||
.filter(
|
||||
([other, source]) =>
|
||||
other !== key &&
|
||||
source.type !== 'number',
|
||||
!['number', 'attachment'].includes(
|
||||
source.type,
|
||||
),
|
||||
)
|
||||
.map(([other, value]) => (
|
||||
<option key={other} value={other}>
|
||||
@@ -393,7 +682,9 @@ function Editor({ service }: { service: Service }) {
|
||||
{field.when && (
|
||||
<label className="block">
|
||||
Resposta que torna o campo aplicável
|
||||
{fields[field.when.field]?.type === 'select' ? (
|
||||
{['select', 'multiselect', 'consent'].includes(
|
||||
fields[field.when.field]?.type,
|
||||
) ? (
|
||||
<select
|
||||
required
|
||||
className={input}
|
||||
@@ -401,6 +692,7 @@ function Editor({ service }: { service: Service }) {
|
||||
onChange={(event) =>
|
||||
update(key, {
|
||||
when: {
|
||||
...field.when!,
|
||||
field: field.when!.field,
|
||||
equals: event.target.value,
|
||||
},
|
||||
@@ -411,8 +703,14 @@ function Editor({ service }: { service: Service }) {
|
||||
Seleccionar resposta
|
||||
</option>
|
||||
{Object.entries(
|
||||
fields[field.when.field].options ??
|
||||
{},
|
||||
fields[field.when.field].type ===
|
||||
'consent'
|
||||
? {
|
||||
accepted: 'Aceite',
|
||||
declined: 'Recusado',
|
||||
}
|
||||
: (fields[field.when.field]
|
||||
.options ?? {}),
|
||||
).map(([value, label]) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
@@ -552,6 +850,20 @@ function Editor({ service }: { service: Service }) {
|
||||
e submissões anteriores continuam vinculados à sua definição
|
||||
original; as respectivas respostas não são reescritas.
|
||||
</p>
|
||||
{schedulingAvailable && (
|
||||
<p>
|
||||
Entrada em vigor proposta:{' '}
|
||||
{form.data.effective_from ||
|
||||
today ||
|
||||
'na data da publicação'}
|
||||
{dateChanged ? ' (alterada)' : ''}. Para cada serviço,
|
||||
aplica-se a data de início já atingida mais recente; na
|
||||
mesma data, prevalece a versão mais elevada. As versões
|
||||
históricas sem data são usadas enquanto não existir uma
|
||||
edição com início aplicável. Uma correcção para hoje não
|
||||
cancela uma edição já agendada para uma data posterior.
|
||||
</p>
|
||||
)}
|
||||
<label className="block">
|
||||
Motivo da alteração
|
||||
<textarea
|
||||
@@ -587,7 +899,8 @@ function Editor({ service }: { service: Service }) {
|
||||
!form.data.confirm ||
|
||||
(service.version > 0 &&
|
||||
changed.length === 0 &&
|
||||
metaChanges.length === 0)
|
||||
metaChanges.length === 0 &&
|
||||
!dateChanged)
|
||||
}
|
||||
>
|
||||
{form.processing ? 'A publicar…' : 'Publicar nova versão'}
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import EducationReview from '@/components/education-review';
|
||||
import type { EducationReviewProps } from '@/lib/education-review';
|
||||
import { Management, Pagination } from '../management/shared';
|
||||
import type { Paginated } from '../management/shared';
|
||||
|
||||
type ReviewEntry = {
|
||||
id: string;
|
||||
version: number | null;
|
||||
actor: string | null;
|
||||
occurred_at: string;
|
||||
available: boolean;
|
||||
status: 'reviewed' | 'rejected' | null;
|
||||
reason: string | null;
|
||||
previous_reason: string | null;
|
||||
};
|
||||
export default function Declaration(
|
||||
props: EducationReviewProps & {
|
||||
backUrl: string;
|
||||
references: Record<string, string | null>;
|
||||
history?: Paginated<ReviewEntry>;
|
||||
},
|
||||
) {
|
||||
const row = props.declaration;
|
||||
const labels: Record<string, string> = {
|
||||
occupation: 'Ocupação',
|
||||
skill: 'Competência',
|
||||
location: 'Localização',
|
||||
project: 'Projecto',
|
||||
course: 'Curso',
|
||||
};
|
||||
return (
|
||||
<Management
|
||||
title={
|
||||
props.kind === 'demands'
|
||||
? 'Declaração de procura de trabalhadores'
|
||||
: 'Declaração de vagas formativas'
|
||||
}
|
||||
>
|
||||
<Link className="underline" href={props.backUrl}>
|
||||
Voltar às declarações
|
||||
</Link>
|
||||
<section className="space-y-3 rounded border p-4">
|
||||
<h2 className="text-xl font-semibold break-words">
|
||||
{row.qualification}
|
||||
</h2>
|
||||
<p>
|
||||
{row.quantity}{' '}
|
||||
{props.kind === 'demands'
|
||||
? 'trabalhadores'
|
||||
: 'vagas formativas'}{' '}
|
||||
· {row.period_start} a {row.period_end}
|
||||
</p>
|
||||
<p>
|
||||
Fonte válida até {row.valid_until}
|
||||
{row.valid_until < props.today ? ' · Expirada' : ''}
|
||||
</p>
|
||||
{row.reference_date && (
|
||||
<p>Data de referência: {row.reference_date}</p>
|
||||
)}
|
||||
{props.kind === 'demands' && row.employer && (
|
||||
<p>Empregador declarado: {row.employer}</p>
|
||||
)}
|
||||
<p className="break-words whitespace-pre-wrap">
|
||||
Fonte: {row.source}
|
||||
</p>
|
||||
{!!Object.keys(props.references).length && (
|
||||
<h3 className="font-semibold">
|
||||
Referências no cadastro actual
|
||||
</h3>
|
||||
)}
|
||||
{Object.entries(props.references).map(([field, value]) => (
|
||||
<p key={field}>
|
||||
{labels[field] ?? field}:{' '}
|
||||
{value || 'Não identificado no cadastro actual'}
|
||||
</p>
|
||||
))}
|
||||
{row.submitted_by_name && (
|
||||
<p>Submetida por {row.submitted_by_name}</p>
|
||||
)}
|
||||
{row.reviewed_by_name && (
|
||||
<p>Revisão actual por {row.reviewed_by_name}</p>
|
||||
)}
|
||||
{row.review_reason && (
|
||||
<p className="break-words whitespace-pre-wrap">
|
||||
Último fundamento registado: {row.review_reason}
|
||||
</p>
|
||||
)}
|
||||
{props.kind === 'demands' && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/management/education/demands/${row.id}/analysis`}
|
||||
>
|
||||
Analisar procura e oferta
|
||||
</Link>
|
||||
)}
|
||||
</section>
|
||||
<EducationReview
|
||||
key={`${props.kind}:${row.id}:${props.actorId}`}
|
||||
{...props}
|
||||
/>
|
||||
{props.history && (
|
||||
<section className="space-y-3 rounded border p-4">
|
||||
<h2 className="text-xl font-semibold">
|
||||
Registos de revisão disponíveis
|
||||
</h2>
|
||||
<p>
|
||||
Os registos anteriores à preservação dos fundamentos
|
||||
podem não estar disponíveis.
|
||||
</p>
|
||||
{!props.history.data.length && (
|
||||
<p>Sem registos de revisão preservados.</p>
|
||||
)}
|
||||
{props.history.data.map((entry) => (
|
||||
<article
|
||||
key={entry.id}
|
||||
className="space-y-2 border-t pt-3"
|
||||
>
|
||||
<h3 className="font-semibold">
|
||||
Versão {entry.version ?? 'não identificada'} ·{' '}
|
||||
{entry.actor ?? 'Autor não identificado'}
|
||||
</h3>
|
||||
<p>{entry.occurred_at}</p>
|
||||
{entry.available ? (
|
||||
<>
|
||||
<p>
|
||||
{entry.status === 'reviewed'
|
||||
? 'Revista'
|
||||
: 'Rejeitada'}
|
||||
</p>
|
||||
<p className="break-words whitespace-pre-wrap">
|
||||
Fundamento: {entry.reason}
|
||||
</p>
|
||||
{entry.previous_reason && (
|
||||
<p className="break-words whitespace-pre-wrap">
|
||||
Fundamento anterior capturado:{' '}
|
||||
{entry.previous_reason}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<p>
|
||||
Fundamento indisponível para leitura. O
|
||||
registo original foi preservado.
|
||||
</p>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
<Pagination page={props.history} />
|
||||
</section>
|
||||
)}
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,14 @@
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { Link, router, useForm } from '@inertiajs/react';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import {
|
||||
portalRequest,
|
||||
PortalApiError,
|
||||
newSubmissionKey,
|
||||
} from '@/lib/portal-api';
|
||||
import EducationSubmittedSnapshot, {
|
||||
type EducationDraft,
|
||||
type EducationDraftSummary,
|
||||
} from '@/components/education-submitted-snapshot';
|
||||
import {
|
||||
Management,
|
||||
Field,
|
||||
@@ -23,8 +32,28 @@ type RecordRow = {
|
||||
period_start: string;
|
||||
period_end: string;
|
||||
source: string;
|
||||
can_review?: boolean;
|
||||
review_unavailable?: 'self' | 'expired' | null;
|
||||
details_url?: string;
|
||||
};
|
||||
type WorkCounts = {
|
||||
total: number;
|
||||
submitted: number;
|
||||
reviewed: number;
|
||||
rejected: number;
|
||||
expired: number;
|
||||
to_review: number;
|
||||
};
|
||||
type Props = {
|
||||
workQueue?: {
|
||||
actor_id: number;
|
||||
drafts: number | null;
|
||||
demands: WorkCounts;
|
||||
capacities: WorkCounts;
|
||||
};
|
||||
draftsAvailable?: boolean;
|
||||
selectedDraft?: EducationDraft | null;
|
||||
ownDrafts?: Paginated<EducationDraftSummary> | null;
|
||||
demands: Paginated<RecordRow>;
|
||||
capacities: Paginated<RecordRow>;
|
||||
skills: Option[];
|
||||
@@ -34,7 +63,12 @@ type Props = {
|
||||
projects: Option[];
|
||||
territories: TerritoryOption[];
|
||||
today: string;
|
||||
filters: { q?: string; status?: string; geo_location_id?: string };
|
||||
filters: {
|
||||
q?: string;
|
||||
status?: string;
|
||||
geo_location_id?: string;
|
||||
scope?: 'all' | 'mine' | 'review';
|
||||
};
|
||||
indicators: {
|
||||
demand_records: number;
|
||||
capacity_records: number;
|
||||
@@ -92,6 +126,11 @@ function Select({
|
||||
required
|
||||
>
|
||||
<option value="">Seleccione</option>
|
||||
{value && !options.some((option) => option.id === value) && (
|
||||
<option value={value}>
|
||||
Selecção guardada não incluída nesta lista
|
||||
</option>
|
||||
)}
|
||||
{options.map((o) => (
|
||||
<option key={o.id} value={o.id}>
|
||||
{o.code ? `${o.code} — ` : ''}
|
||||
@@ -169,32 +208,111 @@ function Catalog({
|
||||
</details>
|
||||
);
|
||||
}
|
||||
function Intake({
|
||||
export function Intake({
|
||||
kind,
|
||||
props,
|
||||
onSaved,
|
||||
onDirty,
|
||||
}: {
|
||||
kind: 'demands' | 'capacities';
|
||||
props: Props;
|
||||
onSaved?: (draft: EducationDraft) => void;
|
||||
onDirty?: (kind: 'demands' | 'capacities', dirty: boolean) => void;
|
||||
}) {
|
||||
const demand = kind === 'demands';
|
||||
const initial =
|
||||
props.selectedDraft?.kind === kind ? props.selectedDraft : null;
|
||||
const [active, setActive] = useState<EducationDraft | null>(initial);
|
||||
const [clientKey] = useState(newSubmissionKey);
|
||||
const [draftBusy, setDraftBusy] = useState(false);
|
||||
const [draftMessage, setDraftMessage] = useState('');
|
||||
const [draftError, setDraftError] = useState('');
|
||||
const [initialPath] = useState(() =>
|
||||
territoryPath(
|
||||
String(initial?.payload.geo_location_id ?? ''),
|
||||
props.territories,
|
||||
),
|
||||
);
|
||||
const [territoryResetKey, setTerritoryResetKey] = useState(0);
|
||||
const form = useForm({
|
||||
project_id: '',
|
||||
course_id: '',
|
||||
occupation_id: '',
|
||||
skill_id: '',
|
||||
geo_location_id: '',
|
||||
employer: '',
|
||||
qualification: '',
|
||||
quantity: '',
|
||||
period_start: '',
|
||||
period_end: '',
|
||||
source: '',
|
||||
reference_date: props.today,
|
||||
valid_until: '',
|
||||
project_id: String(initial?.payload.project_id ?? ''),
|
||||
course_id: String(initial?.payload.course_id ?? ''),
|
||||
occupation_id: String(initial?.payload.occupation_id ?? ''),
|
||||
skill_id: String(initial?.payload.skill_id ?? ''),
|
||||
geo_location_id: String(initial?.payload.geo_location_id ?? ''),
|
||||
employer: String(initial?.payload.employer ?? ''),
|
||||
qualification: String(initial?.payload.qualification ?? ''),
|
||||
quantity: String(initial?.payload.quantity ?? ''),
|
||||
period_start: String(initial?.payload.period_start ?? ''),
|
||||
period_end: String(initial?.payload.period_end ?? ''),
|
||||
source: String(initial?.payload.source ?? ''),
|
||||
reference_date: initial
|
||||
? String(initial.payload.reference_date ?? '')
|
||||
: props.today,
|
||||
valid_until: String(initial?.payload.valid_until ?? ''),
|
||||
});
|
||||
useEffect(
|
||||
() => onDirty?.(kind, form.isDirty),
|
||||
[onDirty, kind, form.isDirty],
|
||||
);
|
||||
async function persist(submit = false) {
|
||||
if (draftBusy) return;
|
||||
setDraftBusy(true);
|
||||
setDraftMessage('');
|
||||
setDraftError('');
|
||||
form.clearErrors();
|
||||
const payload = { ...form.data };
|
||||
try {
|
||||
const url =
|
||||
`/management/education/drafts/${kind}` +
|
||||
(active ? `/${active.id}` : '') +
|
||||
(submit ? '/submit' : '');
|
||||
const saved = await portalRequest<EducationDraft>(url, {
|
||||
method: submit || !active ? 'POST' : 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
version_no: active?.version_no ?? 0,
|
||||
client_key: clientKey,
|
||||
payload,
|
||||
}),
|
||||
});
|
||||
setActive(saved);
|
||||
form.setDefaults(payload);
|
||||
onSaved?.(saved);
|
||||
setDraftMessage(
|
||||
submit
|
||||
? 'Declaração submetida para revisão independente.'
|
||||
: 'Rascunho privado guardado. Pode recuperá-lo na sua lista.',
|
||||
);
|
||||
} catch (failure) {
|
||||
if (failure instanceof PortalApiError) {
|
||||
form.setError(
|
||||
Object.fromEntries(
|
||||
Object.entries(failure.errors).map(
|
||||
([key, messages]) => [
|
||||
key,
|
||||
messages[0] ?? failure.message,
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
setDraftError(
|
||||
failure.status === 409
|
||||
? 'O rascunho foi alterado noutra sessão. As suas edições continuam neste formulário; abra a versão guardada antes de tentar novamente.'
|
||||
: failure.message,
|
||||
);
|
||||
} else
|
||||
setDraftError(
|
||||
'Não foi possível guardar. As suas edições continuam neste formulário.',
|
||||
);
|
||||
} finally {
|
||||
setDraftBusy(false);
|
||||
}
|
||||
}
|
||||
if (active?.state === 'submitted')
|
||||
return <EducationSubmittedSnapshot draft={active} />;
|
||||
return (
|
||||
<details className="rounded border p-4">
|
||||
<details className="rounded border p-4" open={initial !== null}>
|
||||
<summary className="cursor-pointer font-semibold">
|
||||
{demand
|
||||
? 'Declarar procura de trabalhadores'
|
||||
@@ -204,6 +322,10 @@ function Intake({
|
||||
className="mt-4 grid gap-4 md:grid-cols-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (active) {
|
||||
void persist(true);
|
||||
return;
|
||||
}
|
||||
form.post(`/management/education/${kind}`, {
|
||||
onSuccess: () => {
|
||||
form.reset();
|
||||
@@ -212,125 +334,176 @@ function Intake({
|
||||
});
|
||||
}}
|
||||
>
|
||||
<Select
|
||||
label={demand ? 'Projecto' : 'Curso'}
|
||||
options={demand ? props.projects : props.courses}
|
||||
value={demand ? form.data.project_id : form.data.course_id}
|
||||
onChange={(v) =>
|
||||
form.setData(demand ? 'project_id' : 'course_id', v)
|
||||
}
|
||||
/>
|
||||
<Select
|
||||
label="Ocupação"
|
||||
options={props.occupations}
|
||||
value={form.data.occupation_id}
|
||||
onChange={(v) => form.setData('occupation_id', v)}
|
||||
/>
|
||||
<Select
|
||||
label="Competência principal"
|
||||
options={props.skills}
|
||||
value={form.data.skill_id}
|
||||
onChange={(v) => form.setData('skill_id', v)}
|
||||
/>
|
||||
<div className="md:col-span-2">
|
||||
<TerritoryFields
|
||||
key={territoryResetKey}
|
||||
endpoint="/management/territory-options"
|
||||
onChange={(path) =>
|
||||
form.setData(
|
||||
'geo_location_id',
|
||||
path[path.length - 1]?.id ?? '',
|
||||
)
|
||||
<fieldset
|
||||
className="contents"
|
||||
disabled={draftBusy || form.processing}
|
||||
>
|
||||
<Select
|
||||
label={demand ? 'Projecto' : 'Curso'}
|
||||
options={demand ? props.projects : props.courses}
|
||||
value={
|
||||
demand ? form.data.project_id : form.data.course_id
|
||||
}
|
||||
onChange={(v) =>
|
||||
form.setData(demand ? 'project_id' : 'course_id', v)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
{demand && (
|
||||
<Field label="Empregador declarante">
|
||||
<Select
|
||||
label="Ocupação"
|
||||
options={props.occupations}
|
||||
value={form.data.occupation_id}
|
||||
onChange={(v) => form.setData('occupation_id', v)}
|
||||
/>
|
||||
<Select
|
||||
label="Competência principal"
|
||||
options={props.skills}
|
||||
value={form.data.skill_id}
|
||||
onChange={(v) => form.setData('skill_id', v)}
|
||||
/>
|
||||
<div className="md:col-span-2">
|
||||
{initial?.payload.geo_location_id &&
|
||||
form.data.geo_location_id ===
|
||||
initial.payload.geo_location_id &&
|
||||
initialPath.length === 0 && (
|
||||
<p>
|
||||
O local guardado já não consta do cadastro
|
||||
disponível. A referência foi conservada;
|
||||
escolha uma localização actual antes de
|
||||
submeter.
|
||||
</p>
|
||||
)}
|
||||
<TerritoryFields
|
||||
key={territoryResetKey}
|
||||
initial={initialPath}
|
||||
disabled={draftBusy || form.processing}
|
||||
endpoint="/management/territory-options"
|
||||
onChange={(path) =>
|
||||
form.setData(
|
||||
'geo_location_id',
|
||||
path[path.length - 1]?.id ?? '',
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
{demand && (
|
||||
<Field label="Empregador declarante">
|
||||
<input
|
||||
className={control}
|
||||
required
|
||||
value={form.data.employer}
|
||||
onChange={(e) =>
|
||||
form.setData('employer', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
<Field label="Qualificação exigida / desenvolvida">
|
||||
<input
|
||||
className={control}
|
||||
required
|
||||
value={form.data.employer}
|
||||
value={form.data.qualification}
|
||||
onChange={(e) =>
|
||||
form.setData('employer', e.target.value)
|
||||
form.setData('qualification', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
<Field label="Qualificação exigida / desenvolvida">
|
||||
<input
|
||||
className={control}
|
||||
required
|
||||
value={form.data.qualification}
|
||||
onChange={(e) =>
|
||||
form.setData('qualification', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label={
|
||||
demand
|
||||
? 'Trabalhadores necessários'
|
||||
: 'Vagas disponíveis (não trabalhadores)'
|
||||
}
|
||||
>
|
||||
<input
|
||||
className={control}
|
||||
type="number"
|
||||
min="1"
|
||||
required
|
||||
value={form.data.quantity}
|
||||
onChange={(e) =>
|
||||
form.setData('quantity', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{(
|
||||
[
|
||||
'period_start',
|
||||
'period_end',
|
||||
'reference_date',
|
||||
'valid_until',
|
||||
] as const
|
||||
).map((key) => (
|
||||
<Field
|
||||
key={key}
|
||||
label={
|
||||
{
|
||||
period_start: demand
|
||||
? 'Início da necessidade'
|
||||
: 'Início da formação',
|
||||
period_end: demand
|
||||
? 'Fim da necessidade'
|
||||
: 'Conclusão prevista',
|
||||
reference_date: 'Data de referência da fonte',
|
||||
valid_until: 'Fonte válida até',
|
||||
}[key]
|
||||
demand
|
||||
? 'Trabalhadores necessários'
|
||||
: 'Vagas disponíveis (não trabalhadores)'
|
||||
}
|
||||
>
|
||||
<input
|
||||
className={control}
|
||||
type="date"
|
||||
type="number"
|
||||
min="1"
|
||||
required
|
||||
value={form.data[key]}
|
||||
onChange={(e) => form.setData(key, e.target.value)}
|
||||
value={form.data.quantity}
|
||||
onChange={(e) =>
|
||||
form.setData('quantity', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
))}
|
||||
<Field label="Fonte, referência da evidência e responsável pelos dados">
|
||||
<textarea
|
||||
className={control}
|
||||
required
|
||||
minLength={10}
|
||||
value={form.data.source}
|
||||
onChange={(e) => form.setData('source', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<div>
|
||||
<Errors errors={form.errors} />
|
||||
<button className={button} disabled={form.processing}>
|
||||
Submeter para revisão
|
||||
</button>
|
||||
</div>
|
||||
{(
|
||||
[
|
||||
'period_start',
|
||||
'period_end',
|
||||
'reference_date',
|
||||
'valid_until',
|
||||
] as const
|
||||
).map((key) => (
|
||||
<Field
|
||||
key={key}
|
||||
label={
|
||||
{
|
||||
period_start: demand
|
||||
? 'Início da necessidade'
|
||||
: 'Início da formação',
|
||||
period_end: demand
|
||||
? 'Fim da necessidade'
|
||||
: 'Conclusão prevista',
|
||||
reference_date:
|
||||
'Data de referência da fonte',
|
||||
valid_until: 'Fonte válida até',
|
||||
}[key]
|
||||
}
|
||||
>
|
||||
<input
|
||||
className={control}
|
||||
type="date"
|
||||
required
|
||||
value={form.data[key]}
|
||||
onChange={(e) =>
|
||||
form.setData(key, e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
))}
|
||||
<Field label="Fonte, referência da evidência e responsável pelos dados">
|
||||
<textarea
|
||||
className={control}
|
||||
required
|
||||
minLength={10}
|
||||
value={form.data.source}
|
||||
onChange={(e) =>
|
||||
form.setData('source', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<div>
|
||||
<Errors errors={form.errors} />
|
||||
{draftError && <p role="alert">{draftError}</p>}
|
||||
{draftMessage && <p role="status">{draftMessage}</p>}
|
||||
{props.draftsAvailable && (
|
||||
<>
|
||||
<p className="text-sm">
|
||||
Guardar rascunho conserva informação
|
||||
incompleta apenas na sua conta; ainda não
|
||||
declara trabalhadores ou vagas para análise.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={draftBusy || form.processing}
|
||||
onClick={() => void persist()}
|
||||
>
|
||||
Guardar rascunho
|
||||
</button>
|
||||
{active && (
|
||||
<p className="text-sm">
|
||||
Rascunho guardado na versão{' '}
|
||||
{active.version_no}. A submissão usa os
|
||||
campos actuais deste formulário.
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<button className={button} disabled={form.processing}>
|
||||
Submeter para revisão
|
||||
</button>
|
||||
</div>
|
||||
</fieldset>
|
||||
</form>
|
||||
</details>
|
||||
);
|
||||
@@ -344,11 +517,6 @@ function Review({
|
||||
kind: string;
|
||||
today: string;
|
||||
}) {
|
||||
const form = useForm({
|
||||
version_no: row.version_no,
|
||||
status: 'reviewed',
|
||||
review_reason: '',
|
||||
});
|
||||
return (
|
||||
<article className="space-y-3 rounded border p-4">
|
||||
<p className="font-semibold">
|
||||
@@ -361,72 +529,98 @@ function Review({
|
||||
? 'Fonte expirada'
|
||||
: (
|
||||
{
|
||||
submitted: 'Submetido',
|
||||
reviewed: 'Revisto internamente',
|
||||
rejected: 'Rejeitado',
|
||||
submitted: 'Submetida',
|
||||
reviewed: 'Revista internamente',
|
||||
rejected: 'Rejeitada',
|
||||
} as Record<string, string>
|
||||
)[row.status]}
|
||||
</p>
|
||||
<p className="break-words">Fonte: {row.source}</p>
|
||||
{kind === 'demands' && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/management/education/demands/${row.id}/analysis`}
|
||||
>
|
||||
Analisar procura e oferta
|
||||
{row.review_unavailable === 'self' && (
|
||||
<p>Submetida por si; a revisão cabe a outro gestor.</p>
|
||||
)}
|
||||
{row.details_url && (
|
||||
<Link className="underline" href={row.details_url}>
|
||||
{row.can_review
|
||||
? 'Consultar e rever'
|
||||
: 'Consultar declaração'}
|
||||
</Link>
|
||||
)}
|
||||
<details>
|
||||
<summary>Revisão independente</summary>
|
||||
<form
|
||||
className="mt-3 space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.transform((data) => ({
|
||||
...data,
|
||||
version_no: row.version_no,
|
||||
}));
|
||||
form.post(
|
||||
`/management/education/${kind}/${row.id}/review`,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<Field label="Decisão interna">
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.status}
|
||||
onChange={(e) =>
|
||||
form.setData('status', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="reviewed">Registar revisão</option>
|
||||
<option value="rejected">
|
||||
Rejeitar declaração
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Justificação e evidência da revisão">
|
||||
<textarea
|
||||
className={control}
|
||||
minLength={15}
|
||||
required
|
||||
value={form.data.review_reason}
|
||||
onChange={(e) =>
|
||||
form.setData('review_reason', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Errors errors={form.errors} />
|
||||
<button className={button} disabled={form.processing}>
|
||||
Guardar decisão
|
||||
</button>
|
||||
</form>
|
||||
</details>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
export default function Index(props: Props) {
|
||||
const [savedHere, setSavedHere] = useState<EducationDraftSummary[]>([]);
|
||||
const [dirtyForms, setDirtyForms] = useState({
|
||||
demands: false,
|
||||
capacities: false,
|
||||
});
|
||||
const markDirty = useCallback(
|
||||
(kind: 'demands' | 'capacities', dirty: boolean) => {
|
||||
setDirtyForms((current) =>
|
||||
current[kind] === dirty
|
||||
? current
|
||||
: { ...current, [kind]: dirty },
|
||||
);
|
||||
},
|
||||
[],
|
||||
);
|
||||
const saved = useCallback((draft: EducationDraft) => {
|
||||
setSavedHere((current) => [
|
||||
{
|
||||
id: draft.id,
|
||||
kind: draft.kind,
|
||||
version_no: draft.version_no,
|
||||
state: draft.state,
|
||||
updated_at: draft.updated_at,
|
||||
label: String(draft.payload.qualification ?? ''),
|
||||
},
|
||||
...current.filter((item) => item.id !== draft.id),
|
||||
]);
|
||||
if (draft.state === 'submitted')
|
||||
router.reload({
|
||||
only: [
|
||||
'demands',
|
||||
'capacities',
|
||||
'indicators',
|
||||
'ownDrafts',
|
||||
'workQueue',
|
||||
],
|
||||
});
|
||||
}, []);
|
||||
const unsaved = dirtyForms.demands || dirtyForms.capacities;
|
||||
useEffect(() => {
|
||||
const warn = (event: BeforeUnloadEvent) => {
|
||||
if (unsaved) {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
}
|
||||
};
|
||||
window.addEventListener('beforeunload', warn);
|
||||
const unsubscribe = router.on('before', (event) => {
|
||||
if (
|
||||
unsaved &&
|
||||
event.detail.visit.method === 'get' &&
|
||||
event.detail.visit.preserveState !== true &&
|
||||
!window.confirm(
|
||||
'Há alterações por guardar nos formulários de Educação. Pretende sair sem as guardar?',
|
||||
)
|
||||
)
|
||||
event.preventDefault();
|
||||
});
|
||||
return () => {
|
||||
window.removeEventListener('beforeunload', warn);
|
||||
unsubscribe();
|
||||
};
|
||||
}, [unsaved]);
|
||||
const ownDrafts = [
|
||||
...savedHere,
|
||||
...(props.ownDrafts?.data ?? []).filter(
|
||||
(item) => !savedHere.some((saved) => saved.id === item.id),
|
||||
),
|
||||
];
|
||||
const search = useForm({
|
||||
scope: props.filters.scope ?? 'all',
|
||||
q: props.filters.q ?? '',
|
||||
status: props.filters.status ?? '',
|
||||
geo_location_id: props.filters.geo_location_id ?? '',
|
||||
@@ -464,6 +658,54 @@ export default function Index(props: Props) {
|
||||
filtros. Não representam totais de trabalhadores, lacunas
|
||||
validadas ou resultados educativos.
|
||||
</p>
|
||||
{props.workQueue && (
|
||||
<section
|
||||
aria-label="O meu acompanhamento em Educação"
|
||||
className="space-y-3 rounded border p-4"
|
||||
>
|
||||
<h2 className="text-lg font-semibold">
|
||||
O meu acompanhamento
|
||||
</h2>
|
||||
<p>
|
||||
Contagens das minhas declarações, em todos os filtros.
|
||||
</p>
|
||||
{props.workQueue.drafts !== null && (
|
||||
<p>
|
||||
Rascunhos privados por concluir:{' '}
|
||||
{props.workQueue.drafts}
|
||||
</p>
|
||||
)}
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{(['demands', 'capacities'] as const).map((kind) => {
|
||||
const counts = props.workQueue?.[kind];
|
||||
if (!counts) return null;
|
||||
return (
|
||||
<section key={kind} className="space-y-2">
|
||||
<h3 className="font-semibold">
|
||||
{kind === 'demands'
|
||||
? 'Declarações de procura'
|
||||
: 'Declarações de capacidade formativa'}
|
||||
</h3>
|
||||
<p>Submetidas por mim: {counts.total}</p>
|
||||
<p>
|
||||
Por rever, com fonte vigente:{' '}
|
||||
{counts.submitted}
|
||||
</p>
|
||||
<p>
|
||||
Revistas: {counts.reviewed} ·
|
||||
Rejeitadas: {counts.rejected} · Fonte
|
||||
expirada: {counts.expired}
|
||||
</p>
|
||||
<p>
|
||||
Disponíveis para a minha revisão
|
||||
independente: {counts.to_review}
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
<form
|
||||
className="grid gap-4 md:grid-cols-4"
|
||||
onSubmit={(e) => {
|
||||
@@ -473,6 +715,31 @@ export default function Index(props: Props) {
|
||||
});
|
||||
}}
|
||||
>
|
||||
<Field label="Âmbito das declarações">
|
||||
<select
|
||||
className={control}
|
||||
value={search.data.scope}
|
||||
onChange={(event) =>
|
||||
search.setData({
|
||||
...search.data,
|
||||
scope: event.target.value as
|
||||
| 'all'
|
||||
| 'mine'
|
||||
| 'review',
|
||||
status:
|
||||
event.target.value === 'review'
|
||||
? ''
|
||||
: search.data.status,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="all">Todas as declarações</option>
|
||||
<option value="mine">Submetidas por mim</option>
|
||||
<option value="review">
|
||||
Disponíveis para revisão independente
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Pesquisar qualificação">
|
||||
<input
|
||||
className={control}
|
||||
@@ -481,25 +748,29 @@ export default function Index(props: Props) {
|
||||
onChange={(e) => search.setData('q', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Estado">
|
||||
<select
|
||||
className={control}
|
||||
value={search.data.status}
|
||||
onChange={(e) =>
|
||||
search.setData('status', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
<option value="submitted">
|
||||
Por rever, fonte vigente
|
||||
</option>
|
||||
<option value="reviewed">Revisto, fonte vigente</option>
|
||||
<option value="rejected">
|
||||
Rejeitado, fonte vigente
|
||||
</option>
|
||||
<option value="expired">Fonte expirada</option>
|
||||
</select>
|
||||
</Field>
|
||||
{search.data.scope !== 'review' && (
|
||||
<Field label="Estado">
|
||||
<select
|
||||
className={control}
|
||||
value={search.data.status}
|
||||
onChange={(e) =>
|
||||
search.setData('status', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
<option value="submitted">
|
||||
Por rever, fonte vigente
|
||||
</option>
|
||||
<option value="reviewed">
|
||||
Revisto, fonte vigente
|
||||
</option>
|
||||
<option value="rejected">
|
||||
Rejeitado, fonte vigente
|
||||
</option>
|
||||
<option value="expired">Fonte expirada</option>
|
||||
</select>
|
||||
</Field>
|
||||
)}
|
||||
<div className="md:col-span-2">
|
||||
<TerritoryFields
|
||||
initial={territoryPath(
|
||||
@@ -543,8 +814,65 @@ export default function Index(props: Props) {
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
<Intake kind="demands" props={props} />
|
||||
<Intake kind="capacities" props={props} />
|
||||
{props.draftsAvailable && (
|
||||
<section className="space-y-3 rounded border p-4">
|
||||
<h2 className="text-xl font-semibold">
|
||||
Os meus rascunhos e submissões
|
||||
</h2>
|
||||
<p>
|
||||
Estes registos pertencem apenas à sua conta. Rascunhos
|
||||
incompletos não entram nos indicadores de trabalhadores
|
||||
ou vagas.
|
||||
</p>
|
||||
<Link className="underline" href="/management/education">
|
||||
Iniciar outra declaração
|
||||
</Link>
|
||||
{ownDrafts.length === 0 && (
|
||||
<p>Ainda não guardou rascunhos.</p>
|
||||
)}
|
||||
<ul>
|
||||
{ownDrafts.map((item) => (
|
||||
<li key={item.id}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/management/education?draft=${encodeURIComponent(item.id)}`}
|
||||
preserveState={false}
|
||||
>
|
||||
{item.kind === 'demands'
|
||||
? 'Procura de trabalhadores'
|
||||
: 'Capacidade formativa'}{' '}
|
||||
—{' '}
|
||||
{item.state === 'submitted'
|
||||
? 'submetida'
|
||||
: 'rascunho'}
|
||||
, versão {item.version_no}
|
||||
{item.label
|
||||
? ` — ${item.label}`
|
||||
: ''} —{' '}
|
||||
{new Date(item.updated_at).toLocaleString(
|
||||
'pt-MZ',
|
||||
)}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{props.ownDrafts && <Pagination page={props.ownDrafts} />}
|
||||
</section>
|
||||
)}
|
||||
<Intake
|
||||
key={`demands:${props.selectedDraft?.kind === 'demands' ? props.selectedDraft.id : 'new'}`}
|
||||
kind="demands"
|
||||
props={props}
|
||||
onSaved={saved}
|
||||
onDirty={markDirty}
|
||||
/>
|
||||
<Intake
|
||||
key={`capacities:${props.selectedDraft?.kind === 'capacities' ? props.selectedDraft.id : 'new'}`}
|
||||
kind="capacities"
|
||||
props={props}
|
||||
onSaved={saved}
|
||||
onDirty={markDirty}
|
||||
/>
|
||||
{(['demands', 'capacities'] as const).map((kind) => (
|
||||
<section key={kind} className="space-y-3">
|
||||
<h2 className="text-xl font-semibold">
|
||||
|
||||
@@ -1,19 +1,8 @@
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { portalRequest } from '@/lib/portal-api';
|
||||
import FundingCriteriaAssessment from '@/components/funding-criteria-assessment';
|
||||
import { Frame, card, button } from '@/pages/investment/shared';
|
||||
import { type Programme, windowLabels } from './shared';
|
||||
|
||||
type Assessment = {
|
||||
notice: string;
|
||||
criteria: { code: string; status: string }[];
|
||||
};
|
||||
const statusLabels: Record<string, string> = {
|
||||
matches: 'Corresponde à resposta esperada',
|
||||
does_not_match: 'Não corresponde à resposta esperada',
|
||||
unknown: 'Informação por confirmar',
|
||||
not_applicable: 'Não aplicável ao tipo de candidato indicado',
|
||||
};
|
||||
export default function Show({
|
||||
record,
|
||||
saved,
|
||||
@@ -23,50 +12,7 @@ export default function Show({
|
||||
saved: { version: number; saved_at: string } | null;
|
||||
authenticated: boolean;
|
||||
}) {
|
||||
const [kind, setKind] = useState('unknown');
|
||||
const [windowCode, setWindowCode] = useState('');
|
||||
const [answers, setAnswers] = useState<Record<string, string>>({});
|
||||
const [assessment, setAssessment] = useState<Assessment | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const payload = record.payload;
|
||||
const window = payload.windows.find((item) => item.code === windowCode);
|
||||
const criteria = [...payload.criteria, ...(window?.criteria ?? [])];
|
||||
async function assess() {
|
||||
setBusy(true);
|
||||
setError('');
|
||||
setAssessment(null);
|
||||
try {
|
||||
setAssessment(
|
||||
await portalRequest<Assessment>(
|
||||
`/fundos/${record.id}/criterios`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
version_id: record.version_id,
|
||||
applicant_kind: kind,
|
||||
window_code: windowCode || null,
|
||||
answers: Object.fromEntries(
|
||||
criteria.map((c) => [
|
||||
c.code,
|
||||
answers[c.code] ?? 'unknown',
|
||||
]),
|
||||
),
|
||||
}),
|
||||
},
|
||||
),
|
||||
);
|
||||
} catch (failure) {
|
||||
setError(
|
||||
failure instanceof Error
|
||||
? failure.message
|
||||
: 'Não foi possível conferir os critérios.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Frame title={payload.title}>
|
||||
<Link className="underline" href="/fundos/guardados">
|
||||
@@ -167,103 +113,10 @@ export default function Show({
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
<section className={card}>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Conferir critérios documentados
|
||||
</h2>
|
||||
<p>
|
||||
Esta consulta não envia candidatura nem concede
|
||||
financiamento. As respostas não ficam guardadas.
|
||||
</p>
|
||||
<label className="block">
|
||||
Tipo de candidato
|
||||
<select
|
||||
disabled={busy}
|
||||
className="m-2 rounded border p-2"
|
||||
value={kind}
|
||||
onChange={(e) => {
|
||||
setKind(e.target.value);
|
||||
setAssessment(null);
|
||||
}}
|
||||
>
|
||||
<option value="unknown">Por definir</option>
|
||||
<option value="individual">Pessoa singular</option>
|
||||
<option value="entity">Entidade</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="block">
|
||||
Janela
|
||||
<select
|
||||
disabled={busy}
|
||||
className="m-2 rounded border p-2"
|
||||
value={windowCode}
|
||||
onChange={(e) => {
|
||||
setWindowCode(e.target.value);
|
||||
setAssessment(null);
|
||||
}}
|
||||
>
|
||||
<option value="">Apenas critérios gerais</option>
|
||||
{payload.windows.map((item) => (
|
||||
<option key={item.code} value={item.code}>
|
||||
{item.title}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{criteria.length === 0 && (
|
||||
<p>
|
||||
Esta ficha não contém critérios suficientes para
|
||||
conferir a correspondência.
|
||||
</p>
|
||||
)}
|
||||
{criteria.map((criterion) => (
|
||||
<div key={criterion.code} className="my-4">
|
||||
<label>
|
||||
{criterion.question}
|
||||
<select
|
||||
disabled={busy}
|
||||
className="m-2 rounded border p-2"
|
||||
value={answers[criterion.code] ?? 'unknown'}
|
||||
onChange={(e) => {
|
||||
setAnswers({
|
||||
...answers,
|
||||
[criterion.code]: e.target.value,
|
||||
});
|
||||
setAssessment(null);
|
||||
}}
|
||||
>
|
||||
<option value="unknown">
|
||||
Não sei / por confirmar
|
||||
</option>
|
||||
<option value="yes">Sim</option>
|
||||
<option value="no">Não</option>
|
||||
</select>
|
||||
</label>
|
||||
<p>{criterion.explanation}</p>
|
||||
<p>Fonte: {criterion.source_reference}</p>
|
||||
{assessment && (
|
||||
<p>
|
||||
{
|
||||
statusLabels[
|
||||
assessment.criteria.find(
|
||||
(c) => c.code === criterion.code,
|
||||
)?.status ?? 'unknown'
|
||||
]
|
||||
}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || criteria.length === 0}
|
||||
onClick={() => void assess()}
|
||||
>
|
||||
{busy ? 'A conferir…' : 'Conferir respostas'}
|
||||
</button>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{assessment && <p role="status">{assessment.notice}</p>}
|
||||
</section>
|
||||
<FundingCriteriaAssessment
|
||||
key={record.id + ':' + record.version_id}
|
||||
record={record}
|
||||
/>
|
||||
{payload.documents.length > 0 && (
|
||||
<section className={card}>
|
||||
<h2>Documentos associados</h2>
|
||||
|
||||
@@ -6,6 +6,11 @@ import {
|
||||
type TerritoryOption,
|
||||
} from '@/components/investment-territory';
|
||||
import { businessModalities } from './business-types';
|
||||
import {
|
||||
BusinessDistance,
|
||||
GeographicCoverage,
|
||||
type BusinessGeographicCoverage,
|
||||
} from '@/components/similar-businesses';
|
||||
import {
|
||||
ClassificationSummary,
|
||||
type PublicClassification,
|
||||
@@ -25,6 +30,10 @@ type PublicBusiness = {
|
||||
currency?: string | null;
|
||||
sector?: { name: string; slug: string } | null;
|
||||
province?: string | null;
|
||||
distance_km?: number | null;
|
||||
location_recorded_at?: string | null;
|
||||
location_source_reference?: string | null;
|
||||
location_source_date?: string | null;
|
||||
};
|
||||
type PaginationLink = { url: string | null; label: string; active: boolean };
|
||||
type Props = {
|
||||
@@ -52,6 +61,7 @@ type Props = {
|
||||
locality_id?: string;
|
||||
};
|
||||
territorySelection?: TerritoryOption[];
|
||||
geographicCoverage?: BusinessGeographicCoverage | null;
|
||||
};
|
||||
|
||||
export default function BusinessMarketplace({
|
||||
@@ -60,7 +70,20 @@ export default function BusinessMarketplace({
|
||||
territorySelection = [],
|
||||
classificationOptions,
|
||||
authorities = [],
|
||||
geographicCoverage,
|
||||
}: Props) {
|
||||
const [radiusSelection, setRadiusSelection] = useState({
|
||||
origin: filters.near_business,
|
||||
value: filters.radius_km ?? '',
|
||||
});
|
||||
const radius =
|
||||
radiusSelection.origin === filters.near_business
|
||||
? radiusSelection.value
|
||||
: (filters.radius_km ?? '');
|
||||
const proximity =
|
||||
filters.near_business && radius
|
||||
? { near_business: filters.near_business, radius_km: radius }
|
||||
: {};
|
||||
const [classification, setClassification] = useState<
|
||||
Record<string, string>
|
||||
>(() =>
|
||||
@@ -85,12 +108,15 @@ export default function BusinessMarketplace({
|
||||
admin_post_id: filters.admin_post_id ?? '',
|
||||
locality_id: filters.locality_id ?? '',
|
||||
});
|
||||
const returnQuery = new URLSearchParams({
|
||||
...(query ? { q: query } : {}),
|
||||
...(modality ? { modality } : {}),
|
||||
...territory,
|
||||
...classification,
|
||||
}).toString();
|
||||
// Detail links describe the results actually retrieved, even while the next search is being edited.
|
||||
const returnQuery = new URLSearchParams(
|
||||
Object.fromEntries(
|
||||
Object.entries(filters).filter(
|
||||
(entry): entry is [string, string] =>
|
||||
entry[1] !== undefined && entry[1] !== '',
|
||||
),
|
||||
),
|
||||
).toString();
|
||||
const paginationLinks =
|
||||
results.meta?.links ??
|
||||
(Array.isArray(results.links) ? results.links : []);
|
||||
@@ -111,11 +137,44 @@ export default function BusinessMarketplace({
|
||||
modality: modality || undefined,
|
||||
...territory,
|
||||
...classification,
|
||||
...proximity,
|
||||
},
|
||||
{ preserveState: true, preserveScroll: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
{filters.near_business && (
|
||||
<fieldset className="w-full rounded border p-3">
|
||||
<legend>
|
||||
Distância a partir da ficha de referência
|
||||
</legend>
|
||||
<label>
|
||||
Raio em km (0,1 a 2000)
|
||||
<input
|
||||
className={input}
|
||||
type="number"
|
||||
min="0.1"
|
||||
max="2000"
|
||||
step="any"
|
||||
value={radius}
|
||||
onChange={(event) =>
|
||||
setRadiusSelection({
|
||||
origin: filters.near_business,
|
||||
value: event.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<p className="text-sm">
|
||||
Referência:{' '}
|
||||
{geographicCoverage?.origin_title ??
|
||||
'ficha pública seleccionada'}
|
||||
. Limpar o raio retira o filtro de distância na
|
||||
próxima pesquisa. Um filtro territorial adicional
|
||||
restringe também os resultados.
|
||||
</p>
|
||||
</fieldset>
|
||||
)}
|
||||
<label className="sr-only" htmlFor="business-search">
|
||||
Pesquisar negócios
|
||||
</label>
|
||||
@@ -290,6 +349,16 @@ export default function BusinessMarketplace({
|
||||
)}
|
||||
<button className={button}>Pesquisar</button>
|
||||
</form>
|
||||
{geographicCoverage && (
|
||||
<GeographicCoverage coverage={geographicCoverage} />
|
||||
)}
|
||||
{results.data.length === 0 && (
|
||||
<p>
|
||||
Não foram encontradas fichas públicas com estes critérios. A
|
||||
cobertura do catálogo não demonstra ausência de negócios no
|
||||
mercado.
|
||||
</p>
|
||||
)}
|
||||
<ul className="grid gap-4 md:grid-cols-2">
|
||||
{results.data.map((record) => (
|
||||
<li className={card} key={record.id}>
|
||||
@@ -297,6 +366,7 @@ export default function BusinessMarketplace({
|
||||
{businessModalities[record.modality] ??
|
||||
'Modalidade por indicar'}
|
||||
</p>
|
||||
<BusinessDistance record={record} />
|
||||
<h2 className="text-xl font-bold">
|
||||
<Link
|
||||
className="underline"
|
||||
|
||||
@@ -2,7 +2,9 @@ import { Link } from '@inertiajs/react';
|
||||
import { Frame, button, card } from './shared';
|
||||
import { businessModalities } from './business-types';
|
||||
import PartnershipSourceLinks from '@/components/partnership-source-links';
|
||||
import SimilarBusinesses from '@/components/similar-businesses';
|
||||
import SimilarBusinesses, {
|
||||
BusinessLocationSource,
|
||||
} from '@/components/similar-businesses';
|
||||
import { downloadPublicBusinessOffline } from '@/lib/public-business-offline';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
@@ -28,6 +30,9 @@ type Business = {
|
||||
locality?: string | null;
|
||||
sector?: { name: string; slug: string } | null;
|
||||
published_at?: string | null;
|
||||
location_recorded_at?: string | null;
|
||||
location_source_reference?: string | null;
|
||||
location_source_date?: string | null;
|
||||
};
|
||||
|
||||
export default function BusinessOpportunity({
|
||||
@@ -35,11 +40,13 @@ export default function BusinessOpportunity({
|
||||
returnUrl = '/negocios',
|
||||
interestUrl = `/negocios/${record.slug}/manifestar-interesse`,
|
||||
similarCatalogueUrl,
|
||||
similarRadiusAvailable = false,
|
||||
}: {
|
||||
record: Business;
|
||||
returnUrl?: string;
|
||||
interestUrl?: string;
|
||||
similarCatalogueUrl?: string;
|
||||
similarRadiusAvailable?: boolean;
|
||||
}) {
|
||||
const [offlineMessage, setOfflineMessage] = useState('');
|
||||
return (
|
||||
@@ -71,6 +78,7 @@ export default function BusinessOpportunity({
|
||||
.join(', ')}
|
||||
</p>
|
||||
)}
|
||||
<BusinessLocationSource record={record} showRecorded />
|
||||
{(record.amount_min || record.amount_max) && (
|
||||
<p>
|
||||
Montante indicativo: {record.amount_min ?? '—'} –{' '}
|
||||
@@ -128,16 +136,19 @@ export default function BusinessOpportunity({
|
||||
currentId={record.id}
|
||||
classifications={record.multidimensional}
|
||||
catalogueUrl={similarCatalogueUrl}
|
||||
criteria={[
|
||||
businessModalities[record.modality] ?? record.modality,
|
||||
...(record.sector ? [record.sector.name] : []),
|
||||
...(record.province &&
|
||||
radiusAvailable={similarRadiusAvailable}
|
||||
areaLabel={
|
||||
record.province &&
|
||||
new URL(
|
||||
similarCatalogueUrl,
|
||||
'https://portal.invalid',
|
||||
).searchParams.has('province_id')
|
||||
? [record.province]
|
||||
: []),
|
||||
? record.province
|
||||
: undefined
|
||||
}
|
||||
criteria={[
|
||||
businessModalities[record.modality] ?? record.modality,
|
||||
...(record.sector ? [record.sector.name] : []),
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -6,6 +6,9 @@ import type { Business } from './business-types';
|
||||
import { businessModalities } from './business-types';
|
||||
import BusinessObjects from './business-objects';
|
||||
import type { BusinessObject } from './business-objects';
|
||||
import BusinessPointSummary, {
|
||||
type RegisteredBusinessLocation,
|
||||
} from '@/components/business-point-summary';
|
||||
import {
|
||||
decodeBusinessLocations,
|
||||
emptyBusinessLocation,
|
||||
@@ -13,6 +16,8 @@ import {
|
||||
hasDuplicateBusinessLocationPath,
|
||||
locationPathFromPayload,
|
||||
updateBusinessLocation,
|
||||
businessPointTerritoryKey,
|
||||
businessPointRequiredFields,
|
||||
} from '../../lib/business-locations';
|
||||
|
||||
export type FormSchema = Record<
|
||||
@@ -36,6 +41,8 @@ type Props = {
|
||||
objects: BusinessObject[];
|
||||
objectKinds: string[];
|
||||
sectors: { id: number; name: string }[];
|
||||
registeredLocation?: RegisteredBusinessLocation | null;
|
||||
pointPublicationAvailable?: boolean;
|
||||
};
|
||||
const steps = [
|
||||
['Proponente', 'Applicant'],
|
||||
@@ -185,6 +192,8 @@ export default function BusinessWizard({
|
||||
objects,
|
||||
objectKinds,
|
||||
sectors,
|
||||
registeredLocation,
|
||||
pointPublicationAvailable,
|
||||
}: Props) {
|
||||
const [english, setEnglish] = useState(false);
|
||||
const t = (pt: string, en: string) => (english ? en : pt);
|
||||
@@ -206,6 +215,7 @@ export default function BusinessWizard({
|
||||
return initial;
|
||||
});
|
||||
const modality = record.modality;
|
||||
const pointRequired = businessPointRequiredFields(payload);
|
||||
const [sectorId, setSectorId] = useState(record.sector_id ?? null);
|
||||
const [sectorSearch, setSectorSearch] = useState('');
|
||||
const [publicTitle, setPublicTitle] = useState(record.public_title ?? '');
|
||||
@@ -530,6 +540,13 @@ export default function BusinessWizard({
|
||||
<p>
|
||||
{record.code} · {t('Versão', 'Version')} {version}
|
||||
</p>
|
||||
{[5, 7, 8].includes(step) && (
|
||||
<BusinessPointSummary
|
||||
payload={payload}
|
||||
registered={registeredLocation}
|
||||
available={pointPublicationAvailable}
|
||||
/>
|
||||
)}
|
||||
<p>
|
||||
{t(
|
||||
'Área privada. Guardar ou submeter não publica a oportunidade nem confirma a titularidade ou a transmissibilidade.',
|
||||
@@ -720,7 +737,7 @@ export default function BusinessWizard({
|
||||
label={
|
||||
field.type === 'checkbox'
|
||||
? ''
|
||||
: `${english ? field.en : field.pt}${requiredFields.has(key) || ((key === 'mandate_reference' || key === 'mandate_document_reference' || key === 'disclosure_scope') && payload.acting_capacity === 'representative') || (key === 'project_stage_other' && payload.project_stage === 'other') || (key === 'available_from' && payload.availability === 'from_date') || (key === 'province_id' && payload.geography_scope === 'specific') || (key === 'locations_json' && payload.geography_scope === 'multiple') || (['value_meaning', 'currency', 'asking_value'].includes(key) && ['defined', 'indicative'].includes(payload.value_status ?? '')) || (key === 'investment_total' && payload.opportunity_type === 'investment_project') || (key === 'asset_deal_kind' && ['company_sale', 'asset_sale'].includes(payload.opportunity_type ?? '')) || (key === 'partnership_contribution' && payload.opportunity_type === 'business_partnership') || (key === 'amount_sought' && payload.opportunity_type === 'financing_request') || (key === 'asset_modality' && payload.opportunity_type === 'asset_sale') || (['concession_entity', 'concession_reference'].includes(key) && payload.opportunity_type === 'concession_opportunity') || (key === 'supply_description' && payload.opportunity_type === 'supply_opportunity') ? ' *' : ''}`
|
||||
: `${english ? field.en : field.pt}${pointRequired.has(key) || requiredFields.has(key) || ((key === 'mandate_reference' || key === 'mandate_document_reference' || key === 'disclosure_scope') && payload.acting_capacity === 'representative') || (key === 'project_stage_other' && payload.project_stage === 'other') || (key === 'available_from' && payload.availability === 'from_date') || (key === 'province_id' && payload.geography_scope === 'specific') || (key === 'locations_json' && payload.geography_scope === 'multiple') || (['value_meaning', 'currency', 'asking_value'].includes(key) && ['defined', 'indicative'].includes(payload.value_status ?? '')) || (key === 'investment_total' && payload.opportunity_type === 'investment_project') || (key === 'asset_deal_kind' && ['company_sale', 'asset_sale'].includes(payload.opportunity_type ?? '')) || (key === 'partnership_contribution' && payload.opportunity_type === 'business_partnership') || (key === 'amount_sought' && payload.opportunity_type === 'financing_request') || (key === 'asset_modality' && payload.opportunity_type === 'asset_sale') || (['concession_entity', 'concession_reference'].includes(key) && payload.opportunity_type === 'concession_opportunity') || (key === 'supply_description' && payload.opportunity_type === 'supply_opportunity') ? ' *' : ''}`
|
||||
}
|
||||
>
|
||||
{field.type === 'checkbox' ? (
|
||||
@@ -775,6 +792,71 @@ export default function BusinessWizard({
|
||||
update(key, value)
|
||||
}
|
||||
/>
|
||||
) : field.type === 'point_territory' ? (
|
||||
<select
|
||||
className={input}
|
||||
value={payload[key] ?? ''}
|
||||
onChange={(event) =>
|
||||
update(key, event.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
{t(
|
||||
'Seleccionar uma localização declarada',
|
||||
'Select a declared location',
|
||||
)}
|
||||
</option>
|
||||
{payload[key] &&
|
||||
!locationRows.some(
|
||||
(row) =>
|
||||
businessPointTerritoryKey(
|
||||
row,
|
||||
) === payload[key],
|
||||
) && (
|
||||
<option
|
||||
value={payload[key]}
|
||||
>
|
||||
{t(
|
||||
'Selecção guardada fora das localizações actuais; reconcilie antes de submeter',
|
||||
'Saved selection is outside the current locations; reconcile before submitting',
|
||||
)}
|
||||
</option>
|
||||
)}
|
||||
{locationRows
|
||||
.map((row, index) => ({
|
||||
row,
|
||||
index,
|
||||
}))
|
||||
.filter(
|
||||
({ row }) =>
|
||||
row.province_id,
|
||||
)
|
||||
.map(({ row, index }) => (
|
||||
<option
|
||||
key={businessPointTerritoryKey(
|
||||
row,
|
||||
)}
|
||||
value={businessPointTerritoryKey(
|
||||
row,
|
||||
)}
|
||||
>
|
||||
{t(
|
||||
'Localização',
|
||||
'Location',
|
||||
)}{' '}
|
||||
{index + 1}
|
||||
{payload.locations_json ===
|
||||
resolvedLocationJson &&
|
||||
territoryPaths[index]
|
||||
?.length
|
||||
? ` — ${territoryPaths[index].join(' / ')}`
|
||||
: t(
|
||||
' (declarada nesta etapa)',
|
||||
' (declared in this step)',
|
||||
)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
) : field.type === 'select' ? (
|
||||
<select
|
||||
className={input}
|
||||
@@ -846,8 +928,8 @@ export default function BusinessWizard({
|
||||
</h3>
|
||||
<p className="text-sm">
|
||||
{t(
|
||||
'Indique pelo menos duas localizações distintas. Não são recolhidas coordenadas neste formulário.',
|
||||
'Enter at least two distinct locations. This form does not collect coordinates.',
|
||||
'Indique pelo menos duas localizações distintas. Se preparar um ponto exacto, escolha acima a localização a que pertence. Não é escolhido automaticamente o primeiro território.',
|
||||
'Enter at least two distinct locations. If preparing an exact point, select its location above. The first territory is not selected automatically.',
|
||||
)}
|
||||
</p>
|
||||
{locationRows.map((row, index) => (
|
||||
|
||||
@@ -10,6 +10,10 @@ import type { BusinessVerification } from './business-verifications';
|
||||
import BusinessWizard from './business-wizard';
|
||||
import type { FormSchema } from './business-wizard';
|
||||
import type { Country } from '@/components/country-select';
|
||||
import BusinessPointSummary, {
|
||||
type RegisteredBusinessLocation,
|
||||
} from '@/components/business-point-summary';
|
||||
import { businessPointTerritoryLabel } from '@/lib/business-locations';
|
||||
|
||||
type Props = {
|
||||
countries: Country[];
|
||||
@@ -18,6 +22,8 @@ type Props = {
|
||||
sectors: { id: number; name: string }[];
|
||||
record: Business;
|
||||
canEdit: boolean;
|
||||
registeredLocation?: RegisteredBusinessLocation | null;
|
||||
pointPublicationAvailable?: boolean;
|
||||
owner: boolean;
|
||||
canReview: boolean;
|
||||
canTriage: boolean;
|
||||
@@ -68,6 +74,8 @@ function Editor({
|
||||
verifications,
|
||||
formSchema,
|
||||
sectors,
|
||||
registeredLocation,
|
||||
pointPublicationAvailable,
|
||||
}: Props) {
|
||||
const [payload, setPayload] = useState(record.payload);
|
||||
const [modality, setModality] = useState(record.modality);
|
||||
@@ -131,6 +139,16 @@ function Editor({
|
||||
{businessStates[record.status]} · versão {record.version_no} ·
|
||||
informação reservada
|
||||
</p>
|
||||
<BusinessPointSummary
|
||||
payload={record.payload}
|
||||
registered={registeredLocation}
|
||||
available={pointPublicationAvailable}
|
||||
published={record.status === 'published'}
|
||||
territoryLabel={businessPointTerritoryLabel(
|
||||
record.payload,
|
||||
record.territory_paths,
|
||||
)}
|
||||
/>
|
||||
<p>
|
||||
Informação declarada, pendente de validação. Não constitui
|
||||
anúncio público, certificação, avaliação ou autorização de
|
||||
@@ -148,7 +166,18 @@ function Editor({
|
||||
</div>
|
||||
{Object.entries(formSchema)
|
||||
.filter(
|
||||
([key]) =>
|
||||
([key, field]) =>
|
||||
!key.startsWith('location_point_') &&
|
||||
![
|
||||
'location_latitude',
|
||||
'location_longitude',
|
||||
].includes(key) &&
|
||||
Object.entries(field.when ?? {}).every(
|
||||
([dependency, values]) =>
|
||||
values.includes(
|
||||
record.payload[dependency] ?? '',
|
||||
),
|
||||
) &&
|
||||
![
|
||||
'title',
|
||||
'description',
|
||||
|
||||
@@ -0,0 +1,386 @@
|
||||
import { useRef, useState } from 'react';
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { Frame, card, input, button } from './shared';
|
||||
import { profileJson } from '@/lib/profile-json';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import {
|
||||
companyComparisonUrl,
|
||||
type CompanyAnswers,
|
||||
} from '@/lib/company-comparison';
|
||||
|
||||
type Question = { label: string; options: Record<string, string> };
|
||||
type Result = {
|
||||
engine_version: string;
|
||||
source: {
|
||||
title: string;
|
||||
edition: string;
|
||||
issued_on: string;
|
||||
consulted_on: string;
|
||||
url: string;
|
||||
};
|
||||
questions: Record<string, Question>;
|
||||
active: string[];
|
||||
pending: string[];
|
||||
route: string;
|
||||
scope: string;
|
||||
preparation: string[];
|
||||
forms: {
|
||||
code: string;
|
||||
title: string;
|
||||
description: string;
|
||||
articles: string;
|
||||
source_href: string;
|
||||
constraints: string[];
|
||||
notes: string[];
|
||||
selected: boolean;
|
||||
}[];
|
||||
};
|
||||
type Props = {
|
||||
definition: { version: string; questions: Record<string, Question> };
|
||||
case: { id: string; title: string; version: number } | null;
|
||||
canWrite: boolean;
|
||||
answers: CompanyAnswers;
|
||||
result: Result;
|
||||
saved: { revision: number; at: string; result: Result } | null;
|
||||
history: {
|
||||
id: string;
|
||||
revision: number;
|
||||
at: string;
|
||||
engine_version: string;
|
||||
}[];
|
||||
historyNext: number | null;
|
||||
historical: boolean;
|
||||
workingCopy: boolean;
|
||||
};
|
||||
export default function CompanyComparison(props: Props) {
|
||||
return (
|
||||
<Comparator
|
||||
key={JSON.stringify([
|
||||
props.case?.id,
|
||||
props.answers,
|
||||
props.result.engine_version,
|
||||
props.historical,
|
||||
])}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
function Comparator(props: Props) {
|
||||
const { definition, result, saved, history, historical, workingCopy } =
|
||||
props;
|
||||
const dossier = props.case;
|
||||
const [answers, setAnswers] = useState(props.answers);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
const operation = useRef(createOperationKey());
|
||||
const base = dossier
|
||||
? `/investimentos/${dossier.id}/forma-juridica`
|
||||
: '/formas-juridicas';
|
||||
const oldDefinition =
|
||||
!workingCopy && saved && result.engine_version !== definition.version;
|
||||
const readOnly = historical || !!oldDefinition;
|
||||
const active = ['representation', 'cooperation'].includes(answers.purpose)
|
||||
? ['purpose', 'regulated']
|
||||
: Object.keys(definition.questions);
|
||||
const currentValues = (): CompanyAnswers => {
|
||||
const data = new FormData(formRef.current!);
|
||||
return Object.fromEntries(
|
||||
Object.keys(definition.questions).map((key) => {
|
||||
const value = data.get(`answers[${key}]`);
|
||||
return [
|
||||
key,
|
||||
typeof value === 'string'
|
||||
? value
|
||||
: (answers[key] ?? 'unknown'),
|
||||
];
|
||||
}),
|
||||
);
|
||||
};
|
||||
async function save() {
|
||||
if (!dossier || busy) return;
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
await profileJson(base, {
|
||||
version: dossier.version,
|
||||
operation_key: operation.current,
|
||||
answers: currentValues(),
|
||||
});
|
||||
router.visit(base, { preserveState: false });
|
||||
} catch (e) {
|
||||
setError(
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Não foi possível guardar. As respostas continuam no formulário.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Frame title="Comparar formas jurídicas">
|
||||
{dossier && (
|
||||
<p>
|
||||
Dossier:{' '}
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/investimentos/${dossier.id}`}
|
||||
>
|
||||
{dossier.title}
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
Compare a estrutura pretendida e os pontos a esclarecer antes de
|
||||
preparar o acto constitutivo.
|
||||
</p>
|
||||
{saved && (
|
||||
<p>
|
||||
{historical
|
||||
? 'Revisão histórica'
|
||||
: 'Última comparação guardada'}
|
||||
: {saved.revision} · {saved.at}.{' '}
|
||||
{workingCopy &&
|
||||
'As respostas desta consulta ainda não substituem a edição guardada.'}
|
||||
</p>
|
||||
)}
|
||||
{readOnly ? (
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold">
|
||||
Respostas conservadas
|
||||
</h2>
|
||||
<dl>
|
||||
{result.active.map((key) => (
|
||||
<div key={key}>
|
||||
<dt>{result.questions[key]?.label ?? key}</dt>
|
||||
<dd>
|
||||
{result.questions[key]?.options[
|
||||
answers[key]
|
||||
] ?? answers[key]}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
<Link
|
||||
className="underline"
|
||||
href={companyComparisonUrl(base, answers)}
|
||||
>
|
||||
Preparar nova comparação com estas respostas
|
||||
</Link>
|
||||
</section>
|
||||
) : (
|
||||
<form ref={formRef} action={base} method="get" className={card}>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{Object.entries(definition.questions).map(
|
||||
([key, question]) =>
|
||||
active.includes(key) ? (
|
||||
<label key={key} className="grid gap-1">
|
||||
{question.label}
|
||||
<select
|
||||
className={input}
|
||||
name={`answers[${key}]`}
|
||||
value={answers[key] ?? 'unknown'}
|
||||
disabled={busy}
|
||||
onChange={(e) => {
|
||||
setAnswers({
|
||||
...answers,
|
||||
[key]: e.target.value,
|
||||
});
|
||||
setDirty(true);
|
||||
operation.current =
|
||||
createOperationKey();
|
||||
}}
|
||||
>
|
||||
{Object.entries(
|
||||
question.options,
|
||||
).map(([code, label]) => (
|
||||
<option key={code} value={code}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
) : (
|
||||
<input
|
||||
key={key}
|
||||
type="hidden"
|
||||
name={`answers[${key}]`}
|
||||
value={answers[key] ?? 'unknown'}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-4 flex flex-wrap gap-3">
|
||||
<button className={button} disabled={busy}>
|
||||
Actualizar comparação
|
||||
</button>
|
||||
{dossier ? (
|
||||
props.canWrite && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={save}
|
||||
>
|
||||
{busy ? 'A guardar…' : 'Guardar no dossier'}
|
||||
</button>
|
||||
)
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() =>
|
||||
router.visit(
|
||||
companyComparisonUrl(
|
||||
'/investimentos',
|
||||
currentValues(),
|
||||
'company_comparison',
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
Escolher dossier para guardar
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{dirty && (
|
||||
<p role="status">
|
||||
Actualize a comparação para reflectir as alterações.
|
||||
Guardar utiliza as respostas actuais.
|
||||
</p>
|
||||
)}
|
||||
{dossier && !props.canWrite && (
|
||||
<p>
|
||||
Consulta do dossier. A edição depende do acesso
|
||||
actual e de o dossier estar aberto.
|
||||
</p>
|
||||
)}
|
||||
{error && (
|
||||
<div role="alert">
|
||||
<p>{error}</p>
|
||||
<p>
|
||||
As respostas continuam no formulário. Reabra a
|
||||
comparação com estes valores para recuperar a
|
||||
sessão ou a versão actual do dossier.
|
||||
</p>
|
||||
<button
|
||||
className={button}
|
||||
type="submit"
|
||||
disabled={busy}
|
||||
>
|
||||
Reabrir com estas respostas
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
)}
|
||||
<section className={card} aria-label="Resultado da comparação">
|
||||
<h2 className="text-lg font-semibold">
|
||||
Alternativas e pontos a conferir
|
||||
</h2>
|
||||
<p>{result.route}</p>
|
||||
{result.pending.length > 0 && (
|
||||
<p>
|
||||
Por esclarecer:{' '}
|
||||
{result.pending
|
||||
.map((key) => result.questions[key]?.label ?? key)
|
||||
.join(' · ')}
|
||||
</p>
|
||||
)}
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{result.forms.map((item) => (
|
||||
<article
|
||||
key={item.code}
|
||||
className="space-y-2 rounded border p-4"
|
||||
>
|
||||
<h3 className="font-semibold">
|
||||
{item.title}
|
||||
{item.selected
|
||||
? ' · Preferência para aprofundar'
|
||||
: ''}
|
||||
</h3>
|
||||
<p>{item.description}</p>
|
||||
{item.constraints.map((text) => (
|
||||
<p key={text}>
|
||||
Incompatibilidade a resolver: {text}
|
||||
</p>
|
||||
))}
|
||||
{item.notes.map((text) => (
|
||||
<p key={text}>{text}</p>
|
||||
))}
|
||||
<a
|
||||
className="underline"
|
||||
href={item.source_href}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
{item.articles} · consultar fonte
|
||||
</a>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
<h3 className="mt-4 font-semibold">
|
||||
Preparar a próxima conversa
|
||||
</h3>
|
||||
<ul className="list-disc pl-5">
|
||||
{result.preparation.map((item) => (
|
||||
<li key={item}>{item}</li>
|
||||
))}
|
||||
</ul>
|
||||
<p>{result.scope}</p>
|
||||
</section>
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold">
|
||||
Fonte e edição consultadas
|
||||
</h2>
|
||||
<a
|
||||
className="underline"
|
||||
href={result.source.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
{result.source.title}
|
||||
</a>
|
||||
<p>
|
||||
{result.source.edition}. Publicação:{' '}
|
||||
{result.source.issued_on}. Consulta desta edição:{' '}
|
||||
{result.source.consulted_on}.
|
||||
</p>
|
||||
</section>
|
||||
{dossier && (
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold">
|
||||
Comparações guardadas
|
||||
</h2>
|
||||
<ul>
|
||||
{history.map((item) => (
|
||||
<li key={item.id}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`${base}?revision=${item.id}`}
|
||||
>
|
||||
Revisão {item.revision} · {item.at}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{props.historyNext && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={`${base}?history_before=${props.historyNext}`}
|
||||
>
|
||||
Comparações anteriores
|
||||
</Link>
|
||||
)}
|
||||
{historical && (
|
||||
<Link className="underline" href={base}>
|
||||
Voltar à comparação actual
|
||||
</Link>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,790 @@
|
||||
import { useRef, useState } from 'react';
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { Frame, card, input, button } from './shared';
|
||||
import { profileJson, ProfileValidationError } from '@/lib/profile-json';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import {
|
||||
preparationValues,
|
||||
type CompanyFacts,
|
||||
type Party,
|
||||
} from '@/lib/company-preparation';
|
||||
|
||||
type Review = {
|
||||
issues: string[];
|
||||
totals: Record<string, string | null> | null;
|
||||
note: string;
|
||||
};
|
||||
type Props = {
|
||||
case: { id: string; title: string; version: number };
|
||||
canWrite: boolean;
|
||||
historical: boolean;
|
||||
definition: {
|
||||
version: string;
|
||||
forms: Record<string, { title: string }>;
|
||||
roles: Record<string, string>;
|
||||
template_notice: string;
|
||||
source: { title: string; edition: string; url: string };
|
||||
};
|
||||
facts: CompanyFacts;
|
||||
review: Review;
|
||||
saved: { revision: number; at: string } | null;
|
||||
sources: Record<
|
||||
string,
|
||||
{ name: string; kind: 'person' | 'entity'; origin: string }
|
||||
>;
|
||||
history: { id: string; revision: number; at: string }[];
|
||||
historyNext: number | null;
|
||||
};
|
||||
|
||||
export default function CompanyPreparation(props: Props) {
|
||||
return (
|
||||
<Preparation
|
||||
key={`${props.case.id}:${props.saved?.revision}:${props.historical}`}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function Preparation(props: Props) {
|
||||
const [facts, setFacts] = useState(props.facts);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [fields, setFields] = useState<Record<string, string>>({});
|
||||
const [recovery, setRecovery] = useState<Props | null>(null);
|
||||
const [version, setVersion] = useState(props.case.version);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
const form = useRef<HTMLFormElement>(null);
|
||||
const operation = useRef(createOperationKey());
|
||||
const base = `/investimentos/${props.case.id}/preparar-empresa`;
|
||||
const readOnly = !props.canWrite || props.historical;
|
||||
const corporate = !!facts.form && facts.form !== 'individual';
|
||||
const shares = ['anonymous', 'simplified'].includes(facts.form ?? '');
|
||||
function update(key: keyof CompanyFacts, value: string) {
|
||||
setFacts((old) => ({ ...old, [key]: value || null }));
|
||||
}
|
||||
function party(id: string, changes: Partial<Party>) {
|
||||
setFacts((old) => ({
|
||||
...old,
|
||||
parties: old.parties.map((p) =>
|
||||
p.id === id ? { ...p, ...changes } : p,
|
||||
),
|
||||
}));
|
||||
}
|
||||
function text(
|
||||
key: Exclude<keyof CompanyFacts, 'parties'>,
|
||||
label: string,
|
||||
multiline = false,
|
||||
) {
|
||||
return (
|
||||
<label className="block" key={key}>
|
||||
{label}
|
||||
{multiline ? (
|
||||
<textarea
|
||||
className={input}
|
||||
name={key}
|
||||
value={facts[key] ?? ''}
|
||||
onChange={(e) => update(key, e.target.value)}
|
||||
maxLength={2000}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
className={input}
|
||||
name={key}
|
||||
value={facts[key] ?? ''}
|
||||
onChange={(e) => update(key, e.target.value)}
|
||||
maxLength={
|
||||
key === 'proposed_name'
|
||||
? 250
|
||||
: key === 'currency'
|
||||
? 3
|
||||
: 25
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
function partyText(
|
||||
p: Party,
|
||||
key:
|
||||
| 'name'
|
||||
| 'cash'
|
||||
| 'in_kind'
|
||||
| 'paid'
|
||||
| 'share_count'
|
||||
| 'work'
|
||||
| 'commitment',
|
||||
label: string,
|
||||
) {
|
||||
return (
|
||||
<label className="block" key={key}>
|
||||
{label}
|
||||
<input
|
||||
className={input}
|
||||
name={`${p.id}.${key}`}
|
||||
value={p[key] ?? ''}
|
||||
readOnly={key === 'name' && !!p.source}
|
||||
onChange={(e) =>
|
||||
party(p.id, { [key]: e.target.value || null })
|
||||
}
|
||||
maxLength={
|
||||
['work', 'commitment'].includes(key)
|
||||
? 2000
|
||||
: key === 'name'
|
||||
? 250
|
||||
: 25
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
async function save() {
|
||||
if (busy || readOnly) return;
|
||||
setBusy(true);
|
||||
setError('');
|
||||
setFields({});
|
||||
const values = preparationValues(form.current!, facts);
|
||||
setFacts(values);
|
||||
try {
|
||||
await profileJson(base, {
|
||||
version,
|
||||
operation_key: operation.current,
|
||||
facts: values,
|
||||
});
|
||||
router.visit(base, { preserveState: false });
|
||||
} catch (e) {
|
||||
setError(
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Não foi possível guardar. Os dados continuam no formulário.',
|
||||
);
|
||||
if (e instanceof ProfileValidationError) setFields(e.fields);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
async function recover() {
|
||||
setBusy(true);
|
||||
try {
|
||||
setRecovery(await profileJson(base, {}, 'GET'));
|
||||
} catch (e) {
|
||||
setError(
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Não foi possível consultar o dossier.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Frame title="Preparar a constituição da empresa">
|
||||
<p>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/investimentos/${props.case.id}`}
|
||||
>
|
||||
{props.case.title}
|
||||
</Link>{' '}
|
||||
·{' '}
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/investimentos/${props.case.id}/forma-juridica`}
|
||||
>
|
||||
Comparar formas jurídicas
|
||||
</Link>
|
||||
</p>
|
||||
<p>{props.definition.template_notice}</p>
|
||||
<p>
|
||||
Guarde mesmo que faltem dados. Só se pedem informações desta
|
||||
preparação; valores indicados como realizados são declarações,
|
||||
não comprovativos de pagamento.
|
||||
</p>
|
||||
{props.saved && (
|
||||
<p>
|
||||
{props.historical
|
||||
? 'Revisão histórica'
|
||||
: 'Última ficha guardada'}
|
||||
: {props.saved.revision} · {props.saved.at}.{' '}
|
||||
<Link className="underline" href={base}>
|
||||
Abrir a preparação actual
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
{dirty && (
|
||||
<p role="status">
|
||||
Alterações por guardar. Os totais e as questões serão
|
||||
conferidos quando guardar esta ficha.
|
||||
</p>
|
||||
)}
|
||||
{error && (
|
||||
<div role="alert" className={card}>
|
||||
<p>{error}</p>
|
||||
<ul>
|
||||
{Object.entries(fields).map(([key, message]) => (
|
||||
<li key={key}>{message}</li>
|
||||
))}
|
||||
</ul>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={recover}
|
||||
>
|
||||
Conferir edição actual sem perder estes dados
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{recovery && (
|
||||
<section className={card}>
|
||||
<h2 className="font-semibold">
|
||||
Edição actualmente guardada no dossier
|
||||
</h2>
|
||||
<p>
|
||||
Versão {recovery.case.version}. Compare os dados antes
|
||||
de voltar a guardar; a nova gravação conserva esta
|
||||
edição no histórico.
|
||||
</p>
|
||||
<SavedFacts
|
||||
facts={recovery.facts}
|
||||
definition={recovery.definition}
|
||||
/>
|
||||
{recovery.canWrite && (
|
||||
<button
|
||||
className={button}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setVersion(recovery.case.version);
|
||||
operation.current = createOperationKey();
|
||||
setRecovery(null);
|
||||
setError('');
|
||||
}}
|
||||
>
|
||||
Conferi: manter os meus dados para uma nova revisão
|
||||
</button>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
<form
|
||||
ref={form}
|
||||
onChange={() => setDirty(true)}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void save();
|
||||
}}
|
||||
className="space-y-5"
|
||||
>
|
||||
<fieldset disabled={readOnly || busy} className="space-y-5">
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold">
|
||||
1. Forma jurídica
|
||||
</h2>
|
||||
<label className="block">
|
||||
Alternativa a preparar
|
||||
<select
|
||||
className={input}
|
||||
name="form"
|
||||
value={facts.form ?? ''}
|
||||
onChange={(e) => update('form', e.target.value)}
|
||||
>
|
||||
<option value="">Ainda por definir</option>
|
||||
{Object.entries(props.definition.forms).map(
|
||||
([code, f]) => (
|
||||
<option key={code} value={code}>
|
||||
{f.title}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
</section>
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold">
|
||||
2. Intervenientes e papéis
|
||||
</h2>
|
||||
<p>
|
||||
A mesma pessoa pode acumular papéis. Ter uma
|
||||
participação não atribui automaticamente
|
||||
administração, representação ou qualidade de
|
||||
beneficiário efectivo.
|
||||
</p>
|
||||
{facts.parties.map((p, index) => (
|
||||
<fieldset
|
||||
key={p.id}
|
||||
className="my-4 space-y-2 rounded border p-3"
|
||||
>
|
||||
<legend>Interveniente {index + 1}</legend>
|
||||
<label className="block">
|
||||
Origem do nome
|
||||
<select
|
||||
className={input}
|
||||
value={p.source ?? ''}
|
||||
onChange={(e) => {
|
||||
const s =
|
||||
props.sources[e.target.value];
|
||||
party(p.id, {
|
||||
source: e.target.value || null,
|
||||
source_snapshot: undefined,
|
||||
...(s
|
||||
? {
|
||||
name: s.name,
|
||||
kind: s.kind,
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
}}
|
||||
>
|
||||
<option value="">
|
||||
Informação nova desta preparação
|
||||
</option>
|
||||
{Object.entries(props.sources).map(
|
||||
([key, source]) => (
|
||||
<option key={key} value={key}>
|
||||
{source.origin} ·{' '}
|
||||
{source.name}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
{p.source_snapshot && (
|
||||
<p>
|
||||
Versão utilizada:{' '}
|
||||
{p.source_snapshot.version ??
|
||||
'não indicada'}{' '}
|
||||
· {p.source_snapshot.origin}. Conservada
|
||||
nesta ficha; mudanças no cadastro não a
|
||||
substituem.
|
||||
</p>
|
||||
)}
|
||||
{partyText(
|
||||
p,
|
||||
'name',
|
||||
'Nome da pessoa ou entidade',
|
||||
)}
|
||||
<label className="block">
|
||||
Natureza
|
||||
<select
|
||||
className={input}
|
||||
value={p.kind}
|
||||
disabled={!!p.source}
|
||||
onChange={(e) =>
|
||||
party(p.id, {
|
||||
kind: e.target
|
||||
.value as Party['kind'],
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="person">
|
||||
Pessoa singular
|
||||
</option>
|
||||
<option value="entity">Entidade</option>
|
||||
</select>
|
||||
</label>
|
||||
{Object.entries(props.definition.roles).map(
|
||||
([code, label]) => (
|
||||
<label key={code} className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={p.roles.includes(code)}
|
||||
onChange={(e) =>
|
||||
party(p.id, {
|
||||
roles: e.target.checked
|
||||
? [...p.roles, code]
|
||||
: p.roles.filter(
|
||||
(r) =>
|
||||
r !==
|
||||
code,
|
||||
),
|
||||
})
|
||||
}
|
||||
/>{' '}
|
||||
{label}
|
||||
</label>
|
||||
),
|
||||
)}
|
||||
{p.roles.includes('representative') && (
|
||||
<label className="block">
|
||||
Quem representa?
|
||||
<select
|
||||
className={input}
|
||||
value={p.represented_id ?? ''}
|
||||
onChange={(e) =>
|
||||
party(p.id, {
|
||||
represented_id:
|
||||
e.target.value || null,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Ainda por identificar
|
||||
</option>
|
||||
{facts.parties
|
||||
.filter(
|
||||
(other) =>
|
||||
other.id !== p.id,
|
||||
)
|
||||
.map((other, i) => (
|
||||
<option
|
||||
key={other.id}
|
||||
value={other.id}
|
||||
>
|
||||
{other.name ||
|
||||
`Interveniente ${i + 1}`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() => {
|
||||
setDirty(true);
|
||||
setFacts((old) => ({
|
||||
...old,
|
||||
parties: old.parties.filter(
|
||||
(other) => other.id !== p.id,
|
||||
),
|
||||
}));
|
||||
}}
|
||||
>
|
||||
Retirar da preparação actual
|
||||
</button>
|
||||
</fieldset>
|
||||
))}
|
||||
<button
|
||||
className={button}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setDirty(true);
|
||||
setFacts((old) => ({
|
||||
...old,
|
||||
parties: [
|
||||
...old.parties,
|
||||
{
|
||||
id: createOperationKey(),
|
||||
name: null,
|
||||
kind: 'person',
|
||||
source: null,
|
||||
roles: [],
|
||||
represented_id: null,
|
||||
cash: null,
|
||||
in_kind: null,
|
||||
paid: null,
|
||||
share_count: null,
|
||||
work: null,
|
||||
commitment: null,
|
||||
},
|
||||
],
|
||||
}));
|
||||
}}
|
||||
>
|
||||
Adicionar interveniente
|
||||
</button>
|
||||
</section>
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold">
|
||||
3. Nome e sede propostos
|
||||
</h2>
|
||||
{text('proposed_name', 'Denominação proposta')}
|
||||
{text(
|
||||
'seat',
|
||||
'Sede proposta (distinta da morada pessoal)',
|
||||
true,
|
||||
)}
|
||||
</section>
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold">
|
||||
4. Actividades
|
||||
</h2>
|
||||
{text(
|
||||
'activities',
|
||||
'Actividades a incluir no objecto',
|
||||
true,
|
||||
)}
|
||||
<label className="block">
|
||||
Existem regras sectoriais ou profissionais próprias?
|
||||
<select
|
||||
className={input}
|
||||
name="regulated"
|
||||
value={facts.regulated}
|
||||
onChange={(e) =>
|
||||
update('regulated', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="unknown">
|
||||
Ainda não confirmei
|
||||
</option>
|
||||
<option value="yes">Sim</option>
|
||||
<option value="no">Não identifiquei</option>
|
||||
</select>
|
||||
</label>
|
||||
<p>
|
||||
Descrever o objecto não concede licença para exercer
|
||||
a actividade.
|
||||
</p>
|
||||
</section>
|
||||
{corporate && (
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold">
|
||||
5. Capital e participações
|
||||
</h2>
|
||||
<p>
|
||||
Indique zero apenas quando confirmado; deixe em
|
||||
branco o que desconhece. Todos os valores
|
||||
monetários desta ficha usam a mesma moeda, sem
|
||||
conversão.
|
||||
</p>
|
||||
{text(
|
||||
'currency',
|
||||
'Código da moeda (três letras, por exemplo MZN)',
|
||||
)}
|
||||
{text('capital', 'Capital declarado')}
|
||||
{shares &&
|
||||
text(
|
||||
'nominal_value',
|
||||
'Valor nominal de cada acção',
|
||||
)}
|
||||
{facts.parties
|
||||
.filter((p) => p.roles.includes('subscriber'))
|
||||
.map((p) => (
|
||||
<fieldset
|
||||
key={p.id}
|
||||
className="my-4 border p-3"
|
||||
>
|
||||
<legend>
|
||||
{p.name ||
|
||||
'Participante ainda sem nome'}
|
||||
</legend>
|
||||
{partyText(
|
||||
p,
|
||||
'cash',
|
||||
'Entrada subscrita em dinheiro',
|
||||
)}
|
||||
{partyText(
|
||||
p,
|
||||
'in_kind',
|
||||
'Entrada subscrita em espécie (valor declarado)',
|
||||
)}
|
||||
{partyText(
|
||||
p,
|
||||
'paid',
|
||||
'Total já realizado (declaração)',
|
||||
)}
|
||||
{shares &&
|
||||
partyText(
|
||||
p,
|
||||
'share_count',
|
||||
'Número de acções',
|
||||
)}
|
||||
{partyText(
|
||||
p,
|
||||
'work',
|
||||
'Contribuição em trabalho, se pretendida; não somada ao capital',
|
||||
)}
|
||||
{partyText(
|
||||
p,
|
||||
'commitment',
|
||||
'Condições e prazos ainda por cumprir, se definidos',
|
||||
)}
|
||||
</fieldset>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold">
|
||||
6. Administração e forma de obrigar
|
||||
</h2>
|
||||
{text(
|
||||
'management',
|
||||
'Estrutura, nomeações e poderes pretendidos',
|
||||
true,
|
||||
)}
|
||||
{text(
|
||||
'binding',
|
||||
'Quem poderá vincular a entidade e em que condições?',
|
||||
true,
|
||||
)}
|
||||
</section>
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold">
|
||||
7. Conferência e preparação para revisão
|
||||
</h2>
|
||||
{text(
|
||||
'notes',
|
||||
'Questões a esclarecer nesta preparação',
|
||||
true,
|
||||
)}
|
||||
<button type="submit" className={button}>
|
||||
Guardar ficha no dossier
|
||||
</button>
|
||||
</section>
|
||||
</fieldset>
|
||||
</form>
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold">
|
||||
{props.saved
|
||||
? 'Conferência da ficha guardada'
|
||||
: 'Pontos a preparar'}
|
||||
</h2>
|
||||
<p>{props.review.note}</p>
|
||||
{props.review.totals && (
|
||||
<dl>
|
||||
{Object.entries(props.review.totals).map(
|
||||
([key, value]) => (
|
||||
<div key={key}>
|
||||
<dt>
|
||||
{{
|
||||
currency: 'Moeda',
|
||||
subscribed: 'Total subscrito',
|
||||
paid: 'Realizado declarado',
|
||||
unpaid: 'Por realizar declarado',
|
||||
shares_nominal:
|
||||
'Valor nominal total das acções',
|
||||
}[key] ?? key}
|
||||
</dt>
|
||||
<dd>{value ?? 'Por determinar'}</dd>
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
</dl>
|
||||
)}
|
||||
<ul>
|
||||
{props.review.issues.map((issue) => (
|
||||
<li key={issue}>{issue}</li>
|
||||
))}
|
||||
</ul>
|
||||
<p>
|
||||
<a
|
||||
className="underline"
|
||||
href={props.definition.source.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
{props.definition.source.title}
|
||||
</a>{' '}
|
||||
· {props.definition.source.edition}
|
||||
</p>
|
||||
</section>
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold">Histórico</h2>
|
||||
<ul>
|
||||
{props.history.map((h) => (
|
||||
<li key={h.id}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`${base}?revision=${h.id}`}
|
||||
>
|
||||
Revisão {h.revision} · {h.at}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{props.historyNext && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={`${base}?history_before=${props.historyNext}`}
|
||||
>
|
||||
Edições anteriores
|
||||
</Link>
|
||||
)}
|
||||
</section>
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
|
||||
function SavedFacts({
|
||||
facts,
|
||||
definition,
|
||||
}: Pick<Props, 'facts' | 'definition'>) {
|
||||
const labels: {
|
||||
key: Exclude<keyof CompanyFacts, 'parties'>;
|
||||
label: string;
|
||||
}[] = [
|
||||
{ key: 'form', label: 'Forma jurídica' },
|
||||
{ key: 'proposed_name', label: 'Denominação proposta' },
|
||||
{ key: 'seat', label: 'Sede proposta' },
|
||||
{ key: 'activities', label: 'Actividades' },
|
||||
{
|
||||
key: 'regulated',
|
||||
label: 'Regras sectoriais ou profissionais identificadas',
|
||||
},
|
||||
{ key: 'currency', label: 'Moeda' },
|
||||
{ key: 'capital', label: 'Capital declarado' },
|
||||
{ key: 'nominal_value', label: 'Valor nominal por acção' },
|
||||
{ key: 'management', label: 'Administração pretendida' },
|
||||
{ key: 'binding', label: 'Forma de obrigar pretendida' },
|
||||
{ key: 'notes', label: 'Questões a esclarecer' },
|
||||
];
|
||||
return (
|
||||
<div className="max-h-96 space-y-3 overflow-auto">
|
||||
<dl>
|
||||
{labels.map(({ key, label }) => (
|
||||
<div key={key}>
|
||||
<dt className="font-medium">{label}</dt>
|
||||
<dd className="whitespace-pre-wrap">
|
||||
{key === 'form'
|
||||
? (definition.forms[facts.form ?? '']?.title ??
|
||||
'Por definir')
|
||||
: key === 'regulated'
|
||||
? ({
|
||||
yes: 'Sim',
|
||||
no: 'Não identificadas',
|
||||
unknown: 'Por confirmar',
|
||||
}[facts.regulated] ?? 'Por confirmar')
|
||||
: (facts[key] ?? 'Por definir')}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
{facts.parties.map((p, index) => (
|
||||
<section key={p.id} className="rounded border p-3">
|
||||
<h3 className="font-semibold">
|
||||
Interveniente {index + 1}:{' '}
|
||||
{p.name ?? 'Nome por definir'}
|
||||
</h3>
|
||||
<p>
|
||||
{p.kind === 'entity' ? 'Entidade' : 'Pessoa singular'} ·{' '}
|
||||
{p.roles
|
||||
.map((role) => definition.roles[role] ?? role)
|
||||
.join(', ') || 'Papéis por definir'}
|
||||
</p>
|
||||
{p.source_snapshot && (
|
||||
<p>
|
||||
{p.source_snapshot.origin} · versão{' '}
|
||||
{p.source_snapshot.version ?? 'não indicada'}
|
||||
</p>
|
||||
)}
|
||||
{p.roles.includes('representative') && (
|
||||
<p>
|
||||
Representa:{' '}
|
||||
{facts.parties.find(
|
||||
(other) => other.id === p.represented_id,
|
||||
)?.name ?? 'Por identificar'}
|
||||
</p>
|
||||
)}
|
||||
<dl>
|
||||
{(
|
||||
[
|
||||
['cash', 'Entrada em dinheiro'],
|
||||
['in_kind', 'Entrada em espécie'],
|
||||
['paid', 'Realização declarada'],
|
||||
['share_count', 'Número de acções'],
|
||||
['work', 'Contribuição em trabalho'],
|
||||
['commitment', 'Condições e prazos'],
|
||||
] as const
|
||||
).map(([key, label]) => (
|
||||
<div key={key}>
|
||||
<dt>{label}</dt>
|
||||
<dd className="whitespace-pre-wrap">
|
||||
{p[key] ?? 'Por definir'}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,676 @@
|
||||
import { useRef, useState } from 'react';
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { Frame, card, input, button } from './shared';
|
||||
import { profileJson, ProfileValidationError } from '@/lib/profile-json';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { guideChoices, guideUrl } from '@/lib/investment-guides';
|
||||
|
||||
type Guide = {
|
||||
slug: string;
|
||||
version: string;
|
||||
sha256: string;
|
||||
title: string;
|
||||
reviewed_on: string;
|
||||
scope: string;
|
||||
selection_label?: string;
|
||||
selection_hint?: string;
|
||||
cards_title?: string;
|
||||
eligibility_title?: string;
|
||||
preparation_title?: string;
|
||||
requirements?: GuideRequirement[];
|
||||
documents?: {
|
||||
id: string;
|
||||
title: string;
|
||||
text: string;
|
||||
paths: string[];
|
||||
citations: GuideCitation[];
|
||||
}[];
|
||||
handoffs?: { title: string; url: string; note: string }[];
|
||||
instruments: Record<
|
||||
string,
|
||||
{
|
||||
title: string;
|
||||
description: string;
|
||||
risks: string[];
|
||||
prepare: string[];
|
||||
sources: string[];
|
||||
requirements?: GuideRequirement[];
|
||||
}
|
||||
>;
|
||||
sources: Record<
|
||||
string,
|
||||
{
|
||||
title: string;
|
||||
url: string;
|
||||
edition: string;
|
||||
locator: string;
|
||||
consulted_on: string;
|
||||
sha256: string | null;
|
||||
valid_until?: string;
|
||||
}
|
||||
>;
|
||||
eligibility: {
|
||||
text: string;
|
||||
sources: string[];
|
||||
citations?: GuideCitation[];
|
||||
}[];
|
||||
preparation: {
|
||||
title: string;
|
||||
text: string;
|
||||
sources: string[];
|
||||
responsible?: string;
|
||||
citations?: GuideCitation[];
|
||||
}[];
|
||||
next: string[];
|
||||
limits: string[];
|
||||
};
|
||||
type GuideCitation = { source: string; reference: string; page: number };
|
||||
type GuideRequirement = {
|
||||
id: string;
|
||||
text: string;
|
||||
kind: 'requirement' | 'exception' | 'gap';
|
||||
citations: GuideCitation[];
|
||||
};
|
||||
type Props = {
|
||||
guide: Guide;
|
||||
instruments: string[];
|
||||
note: string;
|
||||
case: { id: string; title: string; version: number } | null;
|
||||
saved: {
|
||||
revision: number;
|
||||
at: string;
|
||||
note: string;
|
||||
instruments: string[];
|
||||
guide: Guide;
|
||||
context: { revision: number };
|
||||
} | null;
|
||||
canWrite: boolean;
|
||||
historical: boolean;
|
||||
olderEdition: boolean;
|
||||
currentAvailable: boolean;
|
||||
workingCopy: boolean;
|
||||
contextChanged: boolean;
|
||||
unavailableInstruments: string[];
|
||||
history: { id: string; revision: number; at: string; edition: string }[];
|
||||
historyNext: number | null;
|
||||
};
|
||||
|
||||
export default function InvestmentGuide(props: Props) {
|
||||
return (
|
||||
<GuideView
|
||||
key={`${props.case?.id}:${props.guide.sha256}:${props.saved?.revision}:${props.historical}:${props.workingCopy}:${props.instruments.join(',')}`}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function GuideView(props: Props) {
|
||||
const { guide, saved, historical, olderEdition } = props;
|
||||
const dossier = props.case;
|
||||
const [selected, setSelected] = useState(props.instruments);
|
||||
const [note, setNote] = useState(props.note);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [recovery, setRecovery] = useState<Props | null>(null);
|
||||
const [version, setVersion] = useState(dossier?.version ?? 0);
|
||||
const form = useRef<HTMLFormElement>(null);
|
||||
const operation = useRef(createOperationKey());
|
||||
const base = dossier
|
||||
? `/investimentos/${dossier.id}/guias/${guide.slug}`
|
||||
: `/guias-investimento/${guide.slug}`;
|
||||
const readOnly =
|
||||
historical || olderEdition || (!!dossier && !props.canWrite);
|
||||
const visible = selected.length ? selected : Object.keys(guide.instruments);
|
||||
function sourceLinks(keys: string[]) {
|
||||
return (
|
||||
<p className="text-sm">
|
||||
Fontes:{' '}
|
||||
{keys.map((key) => (
|
||||
<span key={key}>
|
||||
<a className="mr-3 underline" href={`#source-${key}`}>
|
||||
{guide.sources[key]?.title ?? key}
|
||||
</a>
|
||||
</span>
|
||||
))}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
function citations(items: GuideCitation[] = []) {
|
||||
return (
|
||||
<ul className="text-sm">
|
||||
{items.map((item) => (
|
||||
<li key={`${item.source}:${item.reference}:${item.page}`}>
|
||||
<a
|
||||
className="underline"
|
||||
href={`${guide.sources[item.source].url}#page=${item.page}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
{guide.sources[item.source].title} ·{' '}
|
||||
{item.reference} · p. {item.page} do PDF
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
function requirements(items: GuideRequirement[] = []) {
|
||||
return (
|
||||
<ul className="space-y-3">
|
||||
{items.map((item) => (
|
||||
<li key={item.id} className="rounded border p-3">
|
||||
<p>
|
||||
<strong>
|
||||
{
|
||||
{
|
||||
gap: 'Por esclarecer',
|
||||
exception:
|
||||
'Regra com dispensa ou condição específica',
|
||||
requirement: 'Conferir requisito',
|
||||
}[item.kind]
|
||||
}
|
||||
:
|
||||
</strong>{' '}
|
||||
{item.text}
|
||||
</p>
|
||||
{citations(item.citations)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
function choose() {
|
||||
router.visit(
|
||||
guideUrl(
|
||||
'/investimentos',
|
||||
{
|
||||
slug: guide.slug,
|
||||
sha256: guide.sha256,
|
||||
instruments: guideChoices(form.current!),
|
||||
},
|
||||
true,
|
||||
),
|
||||
);
|
||||
}
|
||||
async function save() {
|
||||
if (!dossier || busy || readOnly) return;
|
||||
setBusy(true);
|
||||
setError('');
|
||||
const values = new FormData(form.current!);
|
||||
const currentNote = values.get('note');
|
||||
const chosen = guideChoices(form.current!);
|
||||
const text = typeof currentNote === 'string' ? currentNote : note;
|
||||
setNote(text);
|
||||
setSelected(chosen);
|
||||
try {
|
||||
await profileJson(base, {
|
||||
version,
|
||||
operation_key: operation.current,
|
||||
sha256: guide.sha256,
|
||||
instruments: chosen,
|
||||
note: text,
|
||||
});
|
||||
router.visit(base, { preserveState: false });
|
||||
} catch (e) {
|
||||
setError(
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Não foi possível guardar. A nota continua nesta página.',
|
||||
);
|
||||
if (
|
||||
e instanceof ProfileValidationError &&
|
||||
Object.values(e.fields).length
|
||||
)
|
||||
setError(Object.values(e.fields).join(' '));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
async function recover() {
|
||||
setBusy(true);
|
||||
try {
|
||||
setRecovery(await profileJson(base, {}, 'GET'));
|
||||
} catch (e) {
|
||||
setError(
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Não foi possível consultar o dossier.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Frame title={guide.title}>
|
||||
{dossier && (
|
||||
<p>
|
||||
Dossier:{' '}
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/investimentos/${dossier.id}`}
|
||||
>
|
||||
{dossier.title}
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
<p>{guide.scope}</p>
|
||||
<p>
|
||||
Edição {guide.version} · Conteúdo conferido em{' '}
|
||||
{guide.reviewed_on}.
|
||||
</p>
|
||||
{saved && (
|
||||
<p>
|
||||
{historical
|
||||
? 'Referência histórica'
|
||||
: 'Última referência guardada'}
|
||||
: revisão {saved.revision} · {saved.at} · contexto{' '}
|
||||
{saved.context.revision}.
|
||||
{props.workingCopy &&
|
||||
' Esta preparação ainda não substitui a referência guardada.'}
|
||||
</p>
|
||||
)}
|
||||
{props.contextChanged && (
|
||||
<p>
|
||||
Os dados de contexto disponíveis nesta consulta diferem dos
|
||||
utilizados na referência. Confira a sua pertinência; a
|
||||
edição guardada conserva o contexto anterior.
|
||||
</p>
|
||||
)}
|
||||
{props.unavailableInstruments.length > 0 && (
|
||||
<p>
|
||||
Esta edição deixou de incluir:{' '}
|
||||
{props.unavailableInstruments.join(', ')}. A selecção e o
|
||||
conteúdo anteriores continuam na referência guardada e no
|
||||
histórico.
|
||||
</p>
|
||||
)}
|
||||
{(historical || olderEdition) && (
|
||||
<p>
|
||||
Consulta preservada da edição utilizada.{' '}
|
||||
{props.currentAvailable ? (
|
||||
<Link className="underline" href={`${base}?current=1`}>
|
||||
Preparar uma nova referência com o guia actual
|
||||
</Link>
|
||||
) : (
|
||||
'O guia foi retirado da consulta actual; esta referência continua disponível.'
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
<form
|
||||
ref={form}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (dossier) void save();
|
||||
else choose();
|
||||
}}
|
||||
className={card}
|
||||
>
|
||||
<fieldset disabled={busy || readOnly} className="space-y-3">
|
||||
<legend className="font-semibold">
|
||||
{guide.selection_label ??
|
||||
'Que instrumentos pretende aprofundar?'}
|
||||
</legend>
|
||||
<p>
|
||||
{guide.selection_hint ??
|
||||
'Sem selecção, consulte o conjunto. Pode combinar instrumentos; a selecção organiza a consulta e não é uma recomendação.'}
|
||||
</p>
|
||||
{Object.entries(guide.instruments).map(([code, item]) => (
|
||||
<label key={code} className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
name="instruments[]"
|
||||
value={code}
|
||||
checked={selected.includes(code)}
|
||||
onChange={(e) =>
|
||||
setSelected((old) =>
|
||||
e.target.checked
|
||||
? [...old, code]
|
||||
: old.filter((v) => v !== code),
|
||||
)
|
||||
}
|
||||
/>{' '}
|
||||
{item.title}
|
||||
</label>
|
||||
))}
|
||||
{dossier && (
|
||||
<label className="block">
|
||||
Questões a discutir nesta preparação (opcional)
|
||||
<textarea
|
||||
className={input}
|
||||
name="note"
|
||||
value={note}
|
||||
maxLength={3000}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
/>
|
||||
<span className="text-sm">
|
||||
A nota fica privada no dossier; reutilize os
|
||||
dados e documentos já registados.
|
||||
</span>
|
||||
</label>
|
||||
)}
|
||||
<button type="submit" className={button}>
|
||||
{dossier
|
||||
? 'Guardar referência no dossier'
|
||||
: 'Escolher dossier para preparar'}
|
||||
</button>
|
||||
</fieldset>
|
||||
</form>
|
||||
{error && (
|
||||
<div role="alert" className={card}>
|
||||
<p>{error}</p>
|
||||
<button
|
||||
className={button}
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={recover}
|
||||
>
|
||||
Conferir a referência actual sem perder a nota
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{recovery && (
|
||||
<section className={card}>
|
||||
<h2 className="font-semibold">
|
||||
Referência actualmente guardada
|
||||
</h2>
|
||||
<p>
|
||||
Dossier: {recovery.case?.title} · Edição{' '}
|
||||
{recovery.guide.version} · revisão{' '}
|
||||
{recovery.saved?.revision ?? 'ainda não guardada'}
|
||||
</p>
|
||||
<p>
|
||||
{recovery.instruments
|
||||
.map(
|
||||
(code) =>
|
||||
recovery.guide.instruments[code]?.title ??
|
||||
code,
|
||||
)
|
||||
.join(', ') || 'Consulta do conjunto'}
|
||||
</p>
|
||||
<p className="whitespace-pre-wrap">
|
||||
{recovery.note || 'Sem nota'}
|
||||
</p>
|
||||
{recovery.canWrite &&
|
||||
recovery.case &&
|
||||
recovery.currentAvailable &&
|
||||
!recovery.olderEdition &&
|
||||
recovery.guide.sha256 === guide.sha256 && (
|
||||
<button
|
||||
className={button}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setVersion(recovery.case!.version);
|
||||
operation.current = createOperationKey();
|
||||
setRecovery(null);
|
||||
setError('');
|
||||
}}
|
||||
>
|
||||
Conferi: manter a minha preparação numa nova
|
||||
revisão
|
||||
</button>
|
||||
)}
|
||||
{(recovery.guide.sha256 !== guide.sha256 ||
|
||||
recovery.olderEdition ||
|
||||
!recovery.currentAvailable) && (
|
||||
<p>
|
||||
O guia utilizado foi alterado. Conserve a nota e
|
||||
abra o guia actual numa nova página para comparar as
|
||||
edições.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold">
|
||||
{guide.cards_title ?? 'Instrumentos, riscos e preparação'}
|
||||
</h2>
|
||||
{guide.requirements && (
|
||||
<div className="my-4">
|
||||
<h3 className="font-semibold">
|
||||
Conferência comum aos percursos deste guião
|
||||
</h3>
|
||||
{requirements(guide.requirements)}
|
||||
</div>
|
||||
)}
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{visible.map((code) => {
|
||||
const item = guide.instruments[code];
|
||||
return (
|
||||
item && (
|
||||
<article
|
||||
className="space-y-2 rounded border p-3"
|
||||
key={code}
|
||||
>
|
||||
<h3 className="font-semibold">
|
||||
{item.title}
|
||||
</h3>
|
||||
<p>{item.description}</p>
|
||||
<h4 className="font-medium">
|
||||
Riscos e pontos a conferir
|
||||
</h4>
|
||||
<ul className="list-disc pl-5">
|
||||
{item.risks.map((text) => (
|
||||
<li key={text}>{text}</li>
|
||||
))}
|
||||
</ul>
|
||||
{item.prepare.length > 0 && (
|
||||
<>
|
||||
<h4 className="font-medium">
|
||||
Preparar para discussão
|
||||
</h4>
|
||||
<ul className="list-disc pl-5">
|
||||
{item.prepare.map((text) => (
|
||||
<li key={text}>{text}</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
{sourceLinks(item.sources)}
|
||||
{requirements(item.requirements)}
|
||||
</article>
|
||||
)
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
{guide.documents && (
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold">
|
||||
Documentos dos percursos seleccionados
|
||||
</h2>
|
||||
<p>
|
||||
Os documentos comuns aparecem uma vez; as condições
|
||||
específicas de cada segmento devem ser conservadas.
|
||||
Reutilize os documentos do dossier e confira a sua
|
||||
actualidade com o operador.
|
||||
</p>
|
||||
{guide.documents
|
||||
.filter((doc) =>
|
||||
doc.paths.some((code) => visible.includes(code)),
|
||||
)
|
||||
.map((doc) => (
|
||||
<article key={doc.id} className="my-4">
|
||||
<h3 className="font-semibold">{doc.title}</h3>
|
||||
<p>{doc.text}</p>
|
||||
<p className="text-sm">
|
||||
Percursos:{' '}
|
||||
{doc.paths
|
||||
.filter((code) =>
|
||||
visible.includes(code),
|
||||
)
|
||||
.map(
|
||||
(code) =>
|
||||
guide.instruments[code].title,
|
||||
)
|
||||
.join(' · ')}
|
||||
</p>
|
||||
{citations(doc.citations)}
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold">
|
||||
{guide.eligibility_title ??
|
||||
'Elegibilidade: confirmar com a entidade'}
|
||||
</h2>
|
||||
{guide.eligibility.map((item) => (
|
||||
<div key={item.text}>
|
||||
<p>{item.text}</p>
|
||||
{sourceLinks(item.sources)}
|
||||
{citations(item.citations)}
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold">
|
||||
{guide.preparation_title ?? 'Dados e documentos a preparar'}
|
||||
</h2>
|
||||
<p>
|
||||
Referência de preparação; a lista exigida em cada operação é
|
||||
definida pela entidade destinatária.
|
||||
</p>
|
||||
{guide.preparation.map((item) => (
|
||||
<article className="my-3" key={item.title}>
|
||||
<h3 className="font-semibold">{item.title}</h3>
|
||||
<p>{item.text}</p>
|
||||
{item.responsible && (
|
||||
<p>Intervenientes: {item.responsible}</p>
|
||||
)}
|
||||
{sourceLinks(item.sources)}
|
||||
{citations(item.citations)}
|
||||
</article>
|
||||
))}
|
||||
{dossier && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/balcao-virtual/dossiers/${dossier.id}`}
|
||||
>
|
||||
Reutilizar ou anexar documentos neste dossier
|
||||
</Link>
|
||||
)}
|
||||
</section>
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold">Próximos passos</h2>
|
||||
<ol className="list-decimal pl-5">
|
||||
{guide.next.map((text) => (
|
||||
<li key={text}>{text}</li>
|
||||
))}
|
||||
</ol>
|
||||
<ul className="mt-4 list-disc pl-5">
|
||||
{guide.limits.map((text) => (
|
||||
<li key={text}>{text}</li>
|
||||
))}
|
||||
</ul>
|
||||
{guide.handoffs?.map((handoff) => (
|
||||
<p key={handoff.url} className="my-3">
|
||||
<a
|
||||
className="underline"
|
||||
href={handoff.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
{handoff.title}
|
||||
</a>{' '}
|
||||
· {handoff.note}
|
||||
</p>
|
||||
))}
|
||||
<p>
|
||||
<Link
|
||||
className="underline"
|
||||
href={
|
||||
dossier
|
||||
? `/investimentos/${dossier.id}/guias/${guide.slug === 'bolsa' ? 'capitalizacao' : 'bolsa'}`
|
||||
: `/guias-investimento/${guide.slug === 'bolsa' ? 'capitalizacao' : 'bolsa'}`
|
||||
}
|
||||
>
|
||||
{guide.slug === 'bolsa'
|
||||
? 'Consultar a preparação de capitalização'
|
||||
: 'Consultar o guião de admissão à Bolsa'}
|
||||
</Link>
|
||||
</p>
|
||||
<Link
|
||||
className="underline"
|
||||
href={
|
||||
dossier
|
||||
? `/investimentos/${dossier.id}`
|
||||
: '/investimentos'
|
||||
}
|
||||
>
|
||||
Continuar a preparação no percurso existente
|
||||
</Link>
|
||||
</section>
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold">
|
||||
Fontes e edição consultada
|
||||
</h2>
|
||||
{Object.entries(guide.sources).map(([key, source]) => (
|
||||
<article className="my-3" key={key} id={`source-${key}`}>
|
||||
<h3>
|
||||
<a
|
||||
className="underline"
|
||||
href={source.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
{source.title}
|
||||
</a>
|
||||
</h3>
|
||||
<p>
|
||||
{source.edition} · {source.locator} · consulta{' '}
|
||||
{source.consulted_on}
|
||||
</p>
|
||||
{source.valid_until && (
|
||||
<p>
|
||||
Período indicado até {source.valid_until}; fonte
|
||||
histórica, sem aplicação como mínimo actual.
|
||||
</p>
|
||||
)}
|
||||
{source.sha256 && (
|
||||
<details>
|
||||
<summary>
|
||||
Identificação do exemplar consultado
|
||||
</summary>
|
||||
<p className="break-all">
|
||||
SHA256: {source.sha256}
|
||||
</p>
|
||||
<p>
|
||||
A fonte externa pode ser actualizada; a
|
||||
referência guardada conserva os dados da
|
||||
edição utilizada.
|
||||
</p>
|
||||
</details>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
{dossier && (
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold">
|
||||
Histórico de referências
|
||||
</h2>
|
||||
<ul>
|
||||
{props.history.map((h) => (
|
||||
<li key={h.id}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`${base}?revision=${h.id}`}
|
||||
>
|
||||
Revisão {h.revision} · {h.edition} · {h.at}
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{props.historyNext && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={`${base}?history_before=${props.historyNext}`}
|
||||
>
|
||||
Referências anteriores
|
||||
</Link>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
import { Link, router, useForm } from '@inertiajs/react';
|
||||
import { Frame, Field, input, button, card } from './shared';
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { Frame, button, card } from './shared';
|
||||
import PartnershipSourceLinks from '@/components/partnership-source-links';
|
||||
import CountrySelect, { type Country } from '@/components/country-select';
|
||||
import { useEffect, useId } from 'react';
|
||||
import { type Country } from '@/components/country-select';
|
||||
import { useCallback, useState } from 'react';
|
||||
import Editor from '@/components/investment-profile-editor';
|
||||
import OrganizationEditor from '@/components/organization-country-editor';
|
||||
import { usePagePreparationGuard } from '@/lib/page-preparation-guard';
|
||||
|
||||
type RecordData = { version: number; payload: Record<string, string> };
|
||||
type Company = RecordData & {
|
||||
@@ -37,19 +40,38 @@ const labels: Record<string, string> = {
|
||||
|
||||
export default function Profile({
|
||||
account,
|
||||
actorId,
|
||||
companies,
|
||||
countries,
|
||||
organizations = [],
|
||||
organizationCountryAvailable = false,
|
||||
}: {
|
||||
account: RecordData;
|
||||
actorId: number;
|
||||
companies: Company[];
|
||||
countries: Country[];
|
||||
organizations?: Organization[];
|
||||
organizationCountryAvailable?: boolean;
|
||||
}) {
|
||||
const [preparations, setPreparations] = useState<Record<string, boolean>>(
|
||||
{},
|
||||
);
|
||||
const reportDirty = useCallback(
|
||||
(id: string, dirty: boolean) =>
|
||||
setPreparations((prior) =>
|
||||
prior[id] === dirty ? prior : { ...prior, [id]: dirty },
|
||||
),
|
||||
[],
|
||||
);
|
||||
usePagePreparationGuard(
|
||||
Object.values(preparations).some(Boolean),
|
||||
'Existem dados por guardar nesta página. Sair e perder a preparação?',
|
||||
);
|
||||
return (
|
||||
<Frame title="Perfil de investimento e empresas">
|
||||
<Link className="underline" href="/formas-juridicas">
|
||||
Comparar formas jurídicas antes de constituir uma entidade
|
||||
</Link>
|
||||
<Link href="/investidor/manifestacoes" className="underline">
|
||||
Voltar à área do investidor
|
||||
</Link>
|
||||
@@ -62,7 +84,11 @@ export default function Profile({
|
||||
.
|
||||
</p>
|
||||
<Editor
|
||||
key={'account-' + account.version}
|
||||
key={'account-' + actorId}
|
||||
actorId={actorId}
|
||||
editorId="account"
|
||||
labels={labels}
|
||||
reportDirty={reportDirty}
|
||||
record={account}
|
||||
countries={countries}
|
||||
fields={[
|
||||
@@ -102,8 +128,13 @@ export default function Profile({
|
||||
</p>
|
||||
)}
|
||||
<Editor
|
||||
key={company.version}
|
||||
key={company.id + '-' + actorId}
|
||||
actorId={actorId}
|
||||
editorId={company.id}
|
||||
labels={labels}
|
||||
reportDirty={reportDirty}
|
||||
record={company}
|
||||
organizations={organizations}
|
||||
countries={countries}
|
||||
fields={[
|
||||
'name',
|
||||
@@ -114,42 +145,20 @@ export default function Profile({
|
||||
'description',
|
||||
]}
|
||||
/>
|
||||
{organizations
|
||||
.filter((o) => o.country)
|
||||
.map((org) => (
|
||||
<div key={org.id} className="mt-3 space-y-2">
|
||||
<p>
|
||||
País mestre de {org.name}: {org.country}. A
|
||||
reutilização altera somente esta declaração;
|
||||
manifestações anteriores conservam o seu
|
||||
valor.
|
||||
</p>
|
||||
<button
|
||||
className={button}
|
||||
onClick={() =>
|
||||
router.post(
|
||||
`/investidor/companies/${company.id}/organization-country`,
|
||||
{
|
||||
version: company.version,
|
||||
organization_id: org.id,
|
||||
organization_version:
|
||||
org.version,
|
||||
},
|
||||
{ preserveScroll: true },
|
||||
)
|
||||
}
|
||||
>
|
||||
Reutilizar país de {org.name}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
className={button + ' mt-4'}
|
||||
onClick={() =>
|
||||
onClick={() => {
|
||||
if (
|
||||
Object.values(preparations).some(Boolean) &&
|
||||
!window.confirm(
|
||||
'Existem dados por guardar nesta página. Sair e perder a preparação?',
|
||||
)
|
||||
)
|
||||
return;
|
||||
router.post('/investidor/manifestacoes', {
|
||||
company_id: company.id,
|
||||
})
|
||||
}
|
||||
});
|
||||
}}
|
||||
>
|
||||
Preparar manifestação desta empresa
|
||||
</button>
|
||||
@@ -159,7 +168,11 @@ export default function Profile({
|
||||
<section className={card}>
|
||||
<h3 className="text-xl font-bold">Acrescentar empresa</h3>
|
||||
<Editor
|
||||
key={'new-' + companies.length}
|
||||
key={'new-' + actorId}
|
||||
actorId={actorId}
|
||||
editorId="new-company"
|
||||
labels={labels}
|
||||
reportDirty={reportDirty}
|
||||
record={{ version: 0, payload: {} }}
|
||||
company
|
||||
countries={countries}
|
||||
@@ -195,7 +208,9 @@ export default function Profile({
|
||||
)}
|
||||
{organizations.map((org) => (
|
||||
<OrganizationEditor
|
||||
key={org.id + org.version}
|
||||
key={org.id + '-' + actorId}
|
||||
actorId={actorId}
|
||||
reportDirty={reportDirty}
|
||||
organization={org}
|
||||
countries={countries}
|
||||
/>
|
||||
@@ -203,201 +218,3 @@ export default function Profile({
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
function OrganizationEditor({
|
||||
organization,
|
||||
countries,
|
||||
}: {
|
||||
organization: Organization;
|
||||
countries: Country[];
|
||||
}) {
|
||||
const form = useForm({
|
||||
version: organization.version,
|
||||
country: organization.country ?? '',
|
||||
source_reference: organization.provenance?.reference ?? '',
|
||||
});
|
||||
const id = useId();
|
||||
useEffect(() => {
|
||||
if (Object.keys(form.errors).length)
|
||||
document
|
||||
.getElementById(id)
|
||||
?.querySelector<HTMLElement>('[aria-invalid="true"]')
|
||||
?.focus();
|
||||
}, [form.errors, id]);
|
||||
return (
|
||||
<section
|
||||
className={card}
|
||||
aria-label={`Cadastro mestre: ${organization.name}`}
|
||||
>
|
||||
<h3 className="text-xl font-bold">{organization.name}</h3>
|
||||
<p>
|
||||
Versão {organization.version}; origem do país:{' '}
|
||||
{organization.provenance?.kind === 'representative_declaration'
|
||||
? 'declaração do representante'
|
||||
: 'não informada'}
|
||||
.
|
||||
</p>
|
||||
<form
|
||||
className="mt-4 space-y-4"
|
||||
id={id}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
form.put(
|
||||
`/investidor/organizations/${organization.id}/country`,
|
||||
{ preserveScroll: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
<Field label="País de constituição da organização">
|
||||
<CountrySelect
|
||||
id={id + '-country'}
|
||||
label="País de constituição da organização"
|
||||
countries={countries}
|
||||
value={form.data.country}
|
||||
disabled={!organization.canEdit}
|
||||
error={form.errors.country}
|
||||
onChange={(country) => form.setData('country', country)}
|
||||
/>
|
||||
</Field>
|
||||
<label className="block" htmlFor={id + '-source'}>
|
||||
Fonte ou referência deste país
|
||||
</label>
|
||||
<textarea
|
||||
id={id + '-source'}
|
||||
className={input}
|
||||
value={form.data.source_reference}
|
||||
disabled={!organization.canEdit}
|
||||
maxLength={2000}
|
||||
aria-invalid={!!form.errors.source_reference}
|
||||
aria-describedby={
|
||||
form.errors.source_reference
|
||||
? id + '-source-error'
|
||||
: undefined
|
||||
}
|
||||
onChange={(event) =>
|
||||
form.setData('source_reference', event.target.value)
|
||||
}
|
||||
/>
|
||||
{form.errors.source_reference && (
|
||||
<p id={id + '-source-error'} role="alert">
|
||||
{form.errors.source_reference}
|
||||
</p>
|
||||
)}
|
||||
{form.errors.version && (
|
||||
<p role="alert">{form.errors.version}</p>
|
||||
)}
|
||||
<button
|
||||
className={button}
|
||||
disabled={!organization.canEdit || form.processing}
|
||||
>
|
||||
Guardar país da organização
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
function Editor({
|
||||
record,
|
||||
fields,
|
||||
company = false,
|
||||
countries,
|
||||
}: {
|
||||
record: RecordData & { id?: string };
|
||||
fields: string[];
|
||||
company?: boolean;
|
||||
countries: Country[];
|
||||
}) {
|
||||
const isCompany = company || !!record.id;
|
||||
const form = useForm({
|
||||
version: record.version,
|
||||
payload: Object.fromEntries(
|
||||
[...fields, 'country'].map((key) => [
|
||||
key,
|
||||
record.payload[key] ?? '',
|
||||
]),
|
||||
),
|
||||
});
|
||||
return (
|
||||
<form
|
||||
className="mt-4 space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const options = { preserveScroll: true };
|
||||
if (isCompany)
|
||||
form.post(
|
||||
'/investidor/companies' +
|
||||
(record.id ? '/' + record.id : ''),
|
||||
options,
|
||||
);
|
||||
else form.put('/investidor/profile', options);
|
||||
}}
|
||||
>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
{record.payload.country && (
|
||||
<p>
|
||||
País anteriormente registado: {record.payload.country}.
|
||||
Conservado sem atribuir automaticamente residência,
|
||||
constituição ou origem da solicitação.
|
||||
</p>
|
||||
)}
|
||||
{fields.map((key) => (
|
||||
<Field key={key} label={labels[key]}>
|
||||
{key.endsWith('_country_code') ? (
|
||||
<CountrySelect
|
||||
id={key + (record.id ?? 'account')}
|
||||
countries={countries}
|
||||
label={labels[key]}
|
||||
error={form.errors[`payload.${key}`]}
|
||||
value={form.data.payload[key]}
|
||||
onChange={(value) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
[key]: value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
className={input}
|
||||
value={form.data.payload[key]}
|
||||
required={
|
||||
isCompany &&
|
||||
['name', 'country', 'role'].includes(key)
|
||||
}
|
||||
maxLength={
|
||||
key === 'description' ||
|
||||
key === 'experience'
|
||||
? 2000
|
||||
: key === 'investment_capacity'
|
||||
? 1000
|
||||
: 200
|
||||
}
|
||||
onChange={(e) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
[key]: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{!key.endsWith('_country_code') &&
|
||||
form.errors[`payload.${key}`] && (
|
||||
<p role="alert" className="text-red-700">
|
||||
{form.errors[`payload.${key}`]}
|
||||
</p>
|
||||
)}
|
||||
</Field>
|
||||
))}
|
||||
</div>
|
||||
{Object.entries(form.errors).map(([key, value]) => (
|
||||
<p role="alert" key={key} className="text-red-700">
|
||||
{value}
|
||||
</p>
|
||||
))}
|
||||
<button className={button} disabled={form.processing}>
|
||||
{isCompany
|
||||
? 'Guardar declaração da empresa'
|
||||
: 'Guardar perfil de investimento'}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -287,12 +287,22 @@ export default function ZoneAttachments({
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
void send(
|
||||
onClick={() => {
|
||||
setBusy(true);
|
||||
setError('');
|
||||
router.post(
|
||||
`/management/documents/${item.document_id}/malware/retry`,
|
||||
{},
|
||||
)
|
||||
}
|
||||
{
|
||||
preserveScroll: true,
|
||||
onError: () =>
|
||||
setError(
|
||||
'Não foi possível pedir a análise. Actualize o estado antes de repetir.',
|
||||
),
|
||||
onFinish: () => setBusy(false),
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
Tentar análise novamente
|
||||
</button>
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { Head, Link, router, useForm } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
companyComparisonUrl,
|
||||
type CompanyAnswers,
|
||||
} from '@/lib/company-comparison';
|
||||
import type { LegacyArticle } from '@/pages/portal/legacy';
|
||||
import { guideUrl, type GuideSelection } from '@/lib/investment-guides';
|
||||
|
||||
export type InvestmentContext = {
|
||||
id: string;
|
||||
@@ -15,8 +20,12 @@ export default function InvestmentContexts({
|
||||
contentSource,
|
||||
sectorSource,
|
||||
zoneSource,
|
||||
companyComparisonAnswers,
|
||||
guideSelection,
|
||||
}: {
|
||||
contexts: InvestmentContext[];
|
||||
companyComparisonAnswers?: CompanyAnswers | null;
|
||||
guideSelection?: GuideSelection | null;
|
||||
contentSource?: LegacyArticle;
|
||||
zoneSource?: {
|
||||
zone_id: string;
|
||||
@@ -37,11 +46,29 @@ export default function InvestmentContexts({
|
||||
reuse_consent: false,
|
||||
content_resource_id: contentSource?.id,
|
||||
sector_slug: sectorSource?.slug,
|
||||
...(companyComparisonAnswers
|
||||
? { company_comparison: companyComparisonAnswers }
|
||||
: {}),
|
||||
...(guideSelection ? { investment_guide: guideSelection } : {}),
|
||||
});
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl space-y-6 p-4 md:p-8">
|
||||
<Head title="Os meus investimentos" />
|
||||
<h1 className="text-2xl font-semibold">Os meus investimentos</h1>
|
||||
{guideSelection && (
|
||||
<p>
|
||||
Escolha ou crie o dossier onde pretende preparar esta
|
||||
referência. O guia e a nota só serão guardados quando
|
||||
confirmar nesse dossier.
|
||||
</p>
|
||||
)}
|
||||
{companyComparisonAnswers && (
|
||||
<p>
|
||||
Escolha o dossier para continuar a comparação de formas
|
||||
jurídicas. As respostas só serão guardadas quando confirmar
|
||||
nesse dossier.
|
||||
</p>
|
||||
)}
|
||||
{zoneSource && (
|
||||
<section className="rounded border p-4">
|
||||
<h2>Parque escolhido: {zoneSource.title}</h2>
|
||||
@@ -78,7 +105,19 @@ export default function InvestmentContexts({
|
||||
<li key={item.id} className="rounded-xl border p-4">
|
||||
<Link
|
||||
className="font-semibold underline"
|
||||
href={`/investimentos/${item.id}`}
|
||||
href={
|
||||
guideSelection
|
||||
? guideUrl(
|
||||
`/investimentos/${item.id}/guias/${guideSelection.slug}`,
|
||||
guideSelection,
|
||||
)
|
||||
: companyComparisonAnswers
|
||||
? companyComparisonUrl(
|
||||
`/investimentos/${item.id}/forma-juridica`,
|
||||
companyComparisonAnswers,
|
||||
)
|
||||
: `/investimentos/${item.id}`
|
||||
}
|
||||
>
|
||||
{item.title}
|
||||
</Link>
|
||||
|
||||
@@ -930,6 +930,29 @@ export default function InvestmentPath(path: Path) {
|
||||
</section>
|
||||
<section className="space-y-3 rounded-xl border p-4">
|
||||
<h2 className="text-lg font-semibold">Documentos</h2>
|
||||
<Link
|
||||
className="block underline"
|
||||
href={`/investimentos/${path.case.id}/guias/capitalizacao`}
|
||||
>
|
||||
Preparar capitalização e financiamento
|
||||
</Link>
|
||||
<Link
|
||||
className="block underline"
|
||||
href={`/investimentos/${path.case.id}/guias/bolsa`}
|
||||
>
|
||||
Preparar a admissão à Bolsa de Valores de Moçambique
|
||||
</Link>
|
||||
<Link
|
||||
className="block underline"
|
||||
href={`/investimentos/${path.case.id}/preparar-empresa`}
|
||||
>
|
||||
Preparar os dados para a constituição da empresa
|
||||
</Link>
|
||||
{path.tools.company && (
|
||||
<Link className="underline" href={path.tools.company}>
|
||||
Comparar formas jurídicas para este investimento
|
||||
</Link>
|
||||
)}
|
||||
<ul>
|
||||
{path.documents.map((doc) => (
|
||||
<li key={doc.id}>
|
||||
|
||||
@@ -0,0 +1,722 @@
|
||||
import { Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { Frame, card, input, button } from '@/pages/investment/shared';
|
||||
import { profileJson, ProfileValidationError } from '@/lib/profile-json';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import {
|
||||
experimentDifferences,
|
||||
mergeExperimentValues,
|
||||
type ExperimentView,
|
||||
} from '@/lib/product-experiments';
|
||||
import { usageValue } from '@/lib/product-usage';
|
||||
|
||||
export default function ExperimentPage(props: ExperimentView) {
|
||||
return (
|
||||
<Editor
|
||||
key={`${props.id ?? 'new'}:${props.document?.version ?? 0}:${props.historical}`}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
function Editor(props: ExperimentView) {
|
||||
const [values, setValues] = useState(props.values);
|
||||
const [base, setBase] = useState(props.values);
|
||||
const [editedKeys, setEditedKeys] = useState<string[]>([]);
|
||||
const [referenceDocument, setReferenceDocument] = useState(props.document);
|
||||
const [catalogue, setCatalogue] = useState(props.catalogue);
|
||||
const [version, setVersion] = useState(
|
||||
props.document?.version ?? props.currentVersion,
|
||||
);
|
||||
const [operation, setOperation] = useState(createOperationKey);
|
||||
const [reason, setReason] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [current, setCurrent] = useState<ExperimentView | null>(null);
|
||||
const [resolved, setResolved] = useState<string[]>([]);
|
||||
const [confirmPlan, setConfirmPlan] = useState(false);
|
||||
const [confirmObservation, setConfirmObservation] = useState(false);
|
||||
const [refreshIndicator, setRefreshIndicator] = useState(false);
|
||||
const [attachReport, setAttachReport] = useState(false);
|
||||
const [removeReport, setRemoveReport] = useState(false);
|
||||
const readonly = props.historical || !props.installed;
|
||||
const document = referenceDocument;
|
||||
const differences = current
|
||||
? experimentDifferences(
|
||||
base,
|
||||
values,
|
||||
current.values,
|
||||
editedKeys,
|
||||
).filter((k) => !resolved.includes(k))
|
||||
: [];
|
||||
const planComplete = !['draft', 'cancelled'].includes(values.state);
|
||||
const showObservation =
|
||||
['observing', 'reviewed'].includes(values.state) ||
|
||||
[
|
||||
'observed_from',
|
||||
'observed_to',
|
||||
'control_result',
|
||||
'variant_result',
|
||||
'result',
|
||||
'decision',
|
||||
].some((k) => values[k]);
|
||||
const frozenIndicator =
|
||||
document?.indicator?.id === values.indicator_id && !refreshIndicator
|
||||
? document.indicator
|
||||
: null;
|
||||
const selectedIndicator =
|
||||
frozenIndicator ??
|
||||
catalogue.items.find((m) => m.id === values.indicator_id);
|
||||
function change(key: string, value: string) {
|
||||
setEditedKeys((keys) => (keys.includes(key) ? keys : [...keys, key]));
|
||||
setValues((v) => ({ ...v, [key]: value }));
|
||||
}
|
||||
function field(key: string, required = false, type = 'textarea') {
|
||||
const error = errors['values.' + key];
|
||||
return (
|
||||
<label className="block space-y-1" key={key}>
|
||||
<span>{props.labels[key]}</span>
|
||||
{type === 'textarea' ? (
|
||||
<textarea
|
||||
className={input}
|
||||
rows={3}
|
||||
maxLength={5000}
|
||||
readOnly={readonly}
|
||||
required={required}
|
||||
value={values[key] ?? ''}
|
||||
onChange={(e) => change(key, e.target.value)}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
className={input}
|
||||
type={type}
|
||||
readOnly={readonly}
|
||||
required={required}
|
||||
value={values[key] ?? ''}
|
||||
maxLength={key === 'title' ? 200 : 1500}
|
||||
onChange={(e) => change(key, e.target.value)}
|
||||
/>
|
||||
)}
|
||||
{error && (
|
||||
<span role="alert" className="block">
|
||||
{error}
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
async function save() {
|
||||
if (readonly || current !== null) return;
|
||||
setBusy(true);
|
||||
setMessage('');
|
||||
setErrors({});
|
||||
try {
|
||||
const result = await profileJson(
|
||||
props.id
|
||||
? `/management/product-experiments/${props.id}/revisions`
|
||||
: '/management/product-experiments',
|
||||
{
|
||||
version,
|
||||
operation_key: operation,
|
||||
reason,
|
||||
values,
|
||||
confirm_plan_change: confirmPlan,
|
||||
confirm_observation_plan: confirmObservation,
|
||||
refresh_indicator: refreshIndicator,
|
||||
attach_report: attachReport,
|
||||
remove_report: removeReport,
|
||||
indicator_definition_version: catalogue.definition_version,
|
||||
},
|
||||
);
|
||||
router.visit('/management/product-experiments/' + result.id, {
|
||||
preserveState: false,
|
||||
});
|
||||
} catch (error) {
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Não foi possível guardar. As suas alterações continuam neste formulário.',
|
||||
);
|
||||
if (error instanceof ProfileValidationError)
|
||||
setErrors(error.fields);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
async function compare() {
|
||||
if (!props.id) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
setCurrent(
|
||||
await profileJson(
|
||||
'/management/product-experiments/' + props.id,
|
||||
{},
|
||||
'GET',
|
||||
),
|
||||
);
|
||||
setResolved([]);
|
||||
} catch (error) {
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Não foi possível consultar a versão actual.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
function adoptBase() {
|
||||
if (!current || differences.length > 0) return;
|
||||
const merged = mergeExperimentValues(
|
||||
base,
|
||||
values,
|
||||
current.values,
|
||||
editedKeys,
|
||||
);
|
||||
setValues(merged);
|
||||
setEditedKeys(
|
||||
Object.keys(merged).filter((k) => merged[k] !== current.values[k]),
|
||||
);
|
||||
setBase(current.values);
|
||||
setReferenceDocument(current.document);
|
||||
setCatalogue(current.catalogue);
|
||||
setVersion(current.currentVersion);
|
||||
setOperation(createOperationKey());
|
||||
setCurrent(null);
|
||||
setMessage(
|
||||
'Versão actual usada como base. Confira o formulário e guarde quando estiver pronto.',
|
||||
);
|
||||
}
|
||||
function download() {
|
||||
if (!document) return;
|
||||
const url = URL.createObjectURL(
|
||||
new Blob([JSON.stringify(document, null, 2)], {
|
||||
type: 'application/json',
|
||||
}),
|
||||
);
|
||||
const anchor = window.document.createElement('a');
|
||||
anchor.href = url;
|
||||
anchor.download = `experiencia-${props.id}-v${document.version}.json`;
|
||||
anchor.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
return (
|
||||
<Frame
|
||||
title={
|
||||
props.historical
|
||||
? `Experiência · versão histórica ${document?.version}`
|
||||
: 'Preparar e acompanhar experiência'
|
||||
}
|
||||
>
|
||||
<Link className="underline" href="/management/product-experiments">
|
||||
Registo de experiências
|
||||
</Link>
|
||||
<p>
|
||||
Os dados deste registo são declarações e referências do autor. A
|
||||
distribuição de grupos e a execução da alteração ocorrem nos
|
||||
percursos autorizados correspondentes. Este formulário não
|
||||
altera consentimentos, permissões ou decisões de investimento.
|
||||
</p>
|
||||
{!props.installed && (
|
||||
<p role="status">
|
||||
O registo ainda não está disponível neste destino.
|
||||
</p>
|
||||
)}
|
||||
{props.historical && (
|
||||
<p role="status">
|
||||
Consulta da versão {document?.version}.{' '}
|
||||
<Link
|
||||
className="underline"
|
||||
href={'/management/product-experiments/' + props.id}
|
||||
>
|
||||
Abrir versão actual
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
{document && (
|
||||
<section
|
||||
className={card + ' space-y-2'}
|
||||
aria-label="Versão consultada"
|
||||
>
|
||||
<p>
|
||||
Versão {document.version}, registada em {document.at}{' '}
|
||||
por {document.actor.name}.
|
||||
</p>
|
||||
<p>Motivo: {document.reason || 'Primeiro registo.'}</p>
|
||||
{document.registration.first_at && (
|
||||
<p>
|
||||
Primeiro plano registado em{' '}
|
||||
{document.registration.first_at}. Alterações
|
||||
posteriores do plano:{' '}
|
||||
{document.registration.amendments}. A data de
|
||||
registo é conservada; não demonstra, por si, registo
|
||||
anterior à execução.
|
||||
</p>
|
||||
)}
|
||||
{document.registration.amended_after_observation && (
|
||||
<p>
|
||||
O plano foi alterado após uma observação declarada.
|
||||
Consulte as versões e as limitações antes de
|
||||
comparar resultados.
|
||||
</p>
|
||||
)}
|
||||
<button type="button" className={button} onClick={download}>
|
||||
Exportar versão consultada (JSON)
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
{message && <p role="alert">{message}</p>}
|
||||
{!readonly && props.id && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={compare}
|
||||
>
|
||||
Consultar versão actual para comparar
|
||||
</button>
|
||||
)}
|
||||
{current && (
|
||||
<section
|
||||
className={card + ' space-y-3'}
|
||||
aria-label="Comparação com a versão actual"
|
||||
>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Comparar com versão {current.currentVersion}
|
||||
</h2>
|
||||
<p>
|
||||
As suas edições foram conservadas. Escolha como tratar
|
||||
cada diferença; os campos que não editou serão
|
||||
actualizados a partir da versão consultada.
|
||||
</p>
|
||||
{differences.map((k) => (
|
||||
<div className="rounded border p-3" key={k}>
|
||||
<h3 className="font-semibold">
|
||||
{props.labels[k] ?? k}
|
||||
</h3>
|
||||
<p className="whitespace-pre-wrap">
|
||||
Sua edição: {values[k] || '(vazio)'}
|
||||
</p>
|
||||
<p className="whitespace-pre-wrap">
|
||||
Versão actual: {current.values[k] || '(vazio)'}
|
||||
</p>
|
||||
<div className="flex gap-3">
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() =>
|
||||
setResolved((r) => [...r, k])
|
||||
}
|
||||
>
|
||||
Manter a minha edição
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() => {
|
||||
change(k, current.values[k] ?? '');
|
||||
setResolved((r) => [...r, k]);
|
||||
}}
|
||||
>
|
||||
Usar valor actual
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={differences.length > 0}
|
||||
onClick={adoptBase}
|
||||
>
|
||||
Usar esta versão como base e rever
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
<form
|
||||
className="space-y-5"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void save();
|
||||
}}
|
||||
>
|
||||
<fieldset className={card + ' space-y-3'} disabled={readonly}>
|
||||
<legend className="text-xl font-semibold">
|
||||
Plano e alteração
|
||||
</legend>
|
||||
{field('title', planComplete, 'text')}
|
||||
<label>
|
||||
Estado do registo
|
||||
<select
|
||||
className={input}
|
||||
value={values.state}
|
||||
onChange={(e) => change('state', e.target.value)}
|
||||
>
|
||||
{Object.entries(props.states).map(([k, label]) => (
|
||||
<option key={k} value={k}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Tipo de alteração
|
||||
<select
|
||||
className={input}
|
||||
value={values.change_kind}
|
||||
onChange={(e) =>
|
||||
change('change_kind', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Ainda por definir</option>
|
||||
{Object.entries(props.changeKinds).map(
|
||||
([k, label]) => (
|
||||
<option key={k} value={k}>
|
||||
{label}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
{field('reference', planComplete)}
|
||||
{field('hypothesis', planComplete)}
|
||||
<label>
|
||||
Indicador
|
||||
<select
|
||||
className={input}
|
||||
value={values.indicator_id}
|
||||
onChange={(e) =>
|
||||
change('indicator_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Ainda por definir</option>
|
||||
{catalogue.items.map((m) => (
|
||||
<option key={m.id} value={m.id}>
|
||||
{m.title}
|
||||
</option>
|
||||
))}
|
||||
{document?.indicator &&
|
||||
document.indicator.id !== 'manual' &&
|
||||
!catalogue.items.some(
|
||||
(m) => m.id === document.indicator?.id,
|
||||
) && (
|
||||
<option value={document.indicator.id}>
|
||||
{document.indicator.title} · definição
|
||||
conservada
|
||||
</option>
|
||||
)}
|
||||
<option value="manual">
|
||||
Documentar indicador próprio
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
{values.indicator_id === 'manual' ? (
|
||||
<>
|
||||
{field('indicator_title', planComplete, 'text')}
|
||||
{field('indicator_definition', planComplete)}
|
||||
{field('indicator_unit', planComplete, 'text')}
|
||||
</>
|
||||
) : (
|
||||
selectedIndicator && (
|
||||
<details>
|
||||
<summary className="cursor-pointer underline">
|
||||
Definição do indicador seleccionado
|
||||
</summary>
|
||||
<p>{selectedIndicator.source}</p>
|
||||
<p>{selectedIndicator.limits}</p>
|
||||
<p>
|
||||
Unidade: {selectedIndicator.unit}. Edição:{' '}
|
||||
{frozenIndicator?.definition_version ??
|
||||
catalogue.definition_version}
|
||||
.
|
||||
</p>
|
||||
</details>
|
||||
)
|
||||
)}
|
||||
{document?.indicator &&
|
||||
document.indicator.id !== 'manual' &&
|
||||
document.indicator.id === values.indicator_id &&
|
||||
document.indicator.definition_version !==
|
||||
catalogue.definition_version && (
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={refreshIndicator}
|
||||
onChange={(e) =>
|
||||
setRefreshIndicator(e.target.checked)
|
||||
}
|
||||
/>{' '}
|
||||
Adoptar explicitamente a definição actual do
|
||||
indicador
|
||||
</label>
|
||||
)}
|
||||
{field('period_from', planComplete, 'date')}
|
||||
{field('period_to', planComplete, 'date')}
|
||||
{field('segment', planComplete)}
|
||||
{field('control', planComplete)}
|
||||
{field('variant', planComplete)}
|
||||
{field('assignment', planComplete)}
|
||||
{field('criterion', planComplete)}
|
||||
</fieldset>
|
||||
<fieldset className={card + ' space-y-3'} disabled={readonly}>
|
||||
<legend className="text-xl font-semibold">
|
||||
Preservação dos requisitos
|
||||
</legend>
|
||||
{['transparency', 'consent', 'security', 'equality'].map(
|
||||
(k) => field(k, planComplete),
|
||||
)}
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={values.preserves_requirements === 'yes'}
|
||||
onChange={(e) =>
|
||||
change(
|
||||
'preserves_requirements',
|
||||
e.target.checked ? 'yes' : '',
|
||||
)
|
||||
}
|
||||
/>{' '}
|
||||
O plano mantém a transparência, o consentimento, a
|
||||
segurança e a igualdade de tratamento.
|
||||
</label>
|
||||
</fieldset>
|
||||
{showObservation && (
|
||||
<fieldset
|
||||
className={card + ' space-y-3'}
|
||||
disabled={readonly}
|
||||
>
|
||||
<legend className="text-xl font-semibold">
|
||||
Observação e decisão
|
||||
</legend>
|
||||
<p>
|
||||
Identifique as evidências e descreva as bases de
|
||||
comparação. Não inclua listas de pessoas ou dados de
|
||||
visitantes.
|
||||
</p>
|
||||
{field(
|
||||
'observed_from',
|
||||
values.state === 'reviewed' ||
|
||||
values.state === 'observing',
|
||||
'date',
|
||||
)}
|
||||
{field(
|
||||
'observed_to',
|
||||
values.state === 'reviewed',
|
||||
'date',
|
||||
)}
|
||||
{[
|
||||
'control_result',
|
||||
'variant_result',
|
||||
'result',
|
||||
'limitations',
|
||||
'evidence',
|
||||
].map((k) => field(k, values.state === 'reviewed'))}
|
||||
<label>
|
||||
Decisão declarada
|
||||
<select
|
||||
className={input}
|
||||
value={values.decision}
|
||||
onChange={(e) =>
|
||||
change('decision', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Ainda sem decisão</option>
|
||||
{Object.entries(props.decisions).map(
|
||||
([k, label]) => (
|
||||
<option key={k} value={k}>
|
||||
{label}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
{field('decision_reason', values.state === 'reviewed')}
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={confirmObservation}
|
||||
onChange={(e) =>
|
||||
setConfirmObservation(e.target.checked)
|
||||
}
|
||||
/>{' '}
|
||||
Confirmei que estas observações se referem ao plano
|
||||
desta versão
|
||||
</label>
|
||||
<label>
|
||||
Serviço do relatório de contexto
|
||||
<select
|
||||
className={input}
|
||||
value={values.report_service}
|
||||
onChange={(e) =>
|
||||
change('report_service', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Todos os serviços</option>
|
||||
{catalogue.services.map((s) => (
|
||||
<option key={s.code} value={s.code}>
|
||||
{s.title} ({s.code})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={attachReport}
|
||||
onChange={(e) => {
|
||||
setAttachReport(e.target.checked);
|
||||
if (e.target.checked)
|
||||
setRemoveReport(false);
|
||||
}}
|
||||
/>{' '}
|
||||
Anexar relatório operacional do período observado ao
|
||||
guardar
|
||||
</label>
|
||||
<p>
|
||||
Este relatório dá contexto à coorte operacional. Não
|
||||
identifica controlo/variante, não mede o segmento
|
||||
livre acima e não comprova o efeito da alteração.
|
||||
</p>
|
||||
{document?.operational_report && (
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={removeReport}
|
||||
onChange={(e) => {
|
||||
setRemoveReport(e.target.checked);
|
||||
if (e.target.checked)
|
||||
setAttachReport(false);
|
||||
}}
|
||||
/>{' '}
|
||||
Retirar o relatório da próxima versão; conservar
|
||||
no histórico
|
||||
</label>
|
||||
)}
|
||||
</fieldset>
|
||||
)}
|
||||
{!readonly && (
|
||||
<section className={card + ' space-y-3'}>
|
||||
{document?.registration.first_at && (
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={confirmPlan}
|
||||
onChange={(e) =>
|
||||
setConfirmPlan(e.target.checked)
|
||||
}
|
||||
/>{' '}
|
||||
Confirmo a alteração do plano já registado; as
|
||||
versões e observações anteriores permanecem no
|
||||
histórico
|
||||
</label>
|
||||
)}
|
||||
<label className="block">
|
||||
Motivo desta versão
|
||||
<textarea
|
||||
className={input}
|
||||
required={
|
||||
props.id !== null ||
|
||||
values.state === 'cancelled'
|
||||
}
|
||||
minLength={3}
|
||||
maxLength={3000}
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
{Object.entries(errors).map(([key, value]) => (
|
||||
<p role="alert" key={key}>
|
||||
{props.labels[key.replace('values.', '')] ??
|
||||
key}
|
||||
: {value}
|
||||
</p>
|
||||
))}
|
||||
<button
|
||||
className={button}
|
||||
disabled={busy || current !== null}
|
||||
>
|
||||
{busy ? 'A guardar…' : 'Guardar versão do registo'}
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
</form>
|
||||
{document?.operational_report && (
|
||||
<section
|
||||
className={card + ' space-y-3'}
|
||||
aria-label="Relatório de contexto conservado"
|
||||
>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Relatório operacional conservado nesta versão
|
||||
</h2>
|
||||
<p>
|
||||
Período {document.operational_report.filters.from} a{' '}
|
||||
{document.operational_report.filters.to}; serviço{' '}
|
||||
{document.operational_report.filters.service_code ??
|
||||
'todos'}
|
||||
. Gerado em {document.operational_report.generated_at}.
|
||||
</p>
|
||||
{!document.report_matches_observation && (
|
||||
<p>
|
||||
Os filtros deste relatório diferem da observação
|
||||
actual. O relatório anterior foi conservado; pode
|
||||
anexar outro numa nova versão.
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
Não separa grupos da experiência nem comprova
|
||||
causalidade.
|
||||
</p>
|
||||
<ul>
|
||||
{document.operational_report.metrics.map((m) => (
|
||||
<li key={m.id}>
|
||||
{m.title}: {usageValue(m.value, m.unit)} ·{' '}
|
||||
{m.state === 'partial'
|
||||
? 'cobertura parcial'
|
||||
: m.state === 'unmeasured'
|
||||
? 'sem base para calcular'
|
||||
: 'observado'}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
{document &&
|
||||
document.observation_plan_sha256 !== document.plan_sha256 &&
|
||||
showObservation && (
|
||||
<p role="status">
|
||||
As observações conservadas referem-se a um plano
|
||||
anterior. Reveja as diferenças e as evidências antes de
|
||||
as reafirmar para o plano actual.
|
||||
</p>
|
||||
)}
|
||||
{props.history.length > 0 && (
|
||||
<section
|
||||
className={card + ' space-y-3'}
|
||||
aria-label="Histórico de versões"
|
||||
>
|
||||
<h2 className="text-xl font-semibold">Histórico</h2>
|
||||
{props.history.map((h) => (
|
||||
<p key={h.version}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/management/product-experiments/${props.id}?revision=${h.version}`}
|
||||
>
|
||||
Versão {h.version}
|
||||
</Link>{' '}
|
||||
· {h.at} · {h.actor} ·{' '}
|
||||
{props.states[h.state] ?? h.state}. {h.reason}
|
||||
</p>
|
||||
))}
|
||||
{props.historyNext !== null && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/management/product-experiments/${props.id}?history_before=${props.historyNext}`}
|
||||
>
|
||||
Versões anteriores
|
||||
</Link>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { Frame, card, input, button } from '@/pages/investment/shared';
|
||||
|
||||
export default function Experiments({
|
||||
installed,
|
||||
states,
|
||||
filters,
|
||||
items,
|
||||
page,
|
||||
pages,
|
||||
total,
|
||||
}: {
|
||||
installed: boolean;
|
||||
states: Record<string, string>;
|
||||
filters: { state: string };
|
||||
items: {
|
||||
id: string;
|
||||
version: number;
|
||||
state: string;
|
||||
title: string;
|
||||
hypothesis: string;
|
||||
at: string;
|
||||
}[];
|
||||
page: number;
|
||||
pages: number;
|
||||
total: number;
|
||||
}) {
|
||||
const url = (p: number) =>
|
||||
'/management/product-experiments?' +
|
||||
new URLSearchParams({ state: filters.state, page: String(p) });
|
||||
return (
|
||||
<Frame title="Registo de experiências">
|
||||
<Link className="underline" href="/management/product-usage">
|
||||
Indicadores de utilização
|
||||
</Link>
|
||||
<p>
|
||||
Documente planos, comparações observadas, evidências e decisões.
|
||||
O estado é uma declaração do autor; registar um plano ou uma
|
||||
decisão não publica alterações nem distribui visitantes por
|
||||
variantes.
|
||||
</p>
|
||||
{!installed ? (
|
||||
<p role="status">
|
||||
O registo ainda não está disponível neste destino. Os
|
||||
indicadores existentes continuam disponíveis.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<Link
|
||||
className={button}
|
||||
href="/management/product-experiments/new"
|
||||
>
|
||||
Preparar experiência
|
||||
</Link>
|
||||
<form
|
||||
className={card + ' flex flex-wrap gap-3'}
|
||||
method="get"
|
||||
action="/management/product-experiments"
|
||||
>
|
||||
<label>
|
||||
Estado
|
||||
<select
|
||||
className={input}
|
||||
name="state"
|
||||
defaultValue={filters.state}
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
{Object.entries(states).map(([code, label]) => (
|
||||
<option key={code} value={code}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<button className={button}>Filtrar</button>
|
||||
</form>
|
||||
<p>
|
||||
{total} registos. Página {page} de {pages}.
|
||||
</p>
|
||||
{items.length === 0 && (
|
||||
<p>Ainda não existem registos para este filtro.</p>
|
||||
)}
|
||||
{items.map((item) => (
|
||||
<article className={card + ' space-y-2'} key={item.id}>
|
||||
<h2 className="text-lg font-semibold">
|
||||
<Link
|
||||
className="underline"
|
||||
href={
|
||||
'/management/product-experiments/' +
|
||||
item.id
|
||||
}
|
||||
>
|
||||
{item.title || 'Experiência sem título'}
|
||||
</Link>
|
||||
</h2>
|
||||
<p>
|
||||
{states[item.state] ?? item.state} · versão{' '}
|
||||
{item.version} · {item.at}
|
||||
</p>
|
||||
<p className="whitespace-pre-wrap">
|
||||
{item.hypothesis ||
|
||||
'Hipótese ainda por preencher.'}
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
<nav aria-label="Páginas do registo" className="flex gap-4">
|
||||
{page > 1 && (
|
||||
<Link className="underline" href={url(page - 1)}>
|
||||
Anterior
|
||||
</Link>
|
||||
)}
|
||||
{page < pages && (
|
||||
<Link className="underline" href={url(page + 1)}>
|
||||
Seguinte
|
||||
</Link>
|
||||
)}
|
||||
</nav>
|
||||
</>
|
||||
)}
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,9 @@ import { createOperationKey } from '@/lib/operation-key';
|
||||
import { valueText } from '@/lib/value-text';
|
||||
import { modalityLabels } from '@/components/opportunity-search-filters';
|
||||
import OpportunityProfileActions from '@/components/opportunity-profile-actions';
|
||||
import OpportunityTechnicalIncidents, {
|
||||
type OpportunityTechnicalIncident,
|
||||
} from '@/components/opportunity-technical-incidents';
|
||||
import OpportunityContactForm from '@/components/opportunity-contact-form';
|
||||
import OpportunityCanonicalFields, {
|
||||
type CanonicalOptions,
|
||||
@@ -89,6 +92,7 @@ export default function OpportunityDraft({
|
||||
workflowState,
|
||||
canonicalResponse,
|
||||
workflowTasks = [],
|
||||
workflowIncidents = [],
|
||||
workflowParticipants,
|
||||
publicationPreview,
|
||||
publicationState,
|
||||
@@ -101,6 +105,7 @@ export default function OpportunityDraft({
|
||||
profileMode?: boolean;
|
||||
profileOrganization?: string | null;
|
||||
profileActions?: string[];
|
||||
workflowIncidents?: OpportunityTechnicalIncident[];
|
||||
profileReauthenticationRequired?: boolean;
|
||||
profileContext?: Record<string, unknown> | null;
|
||||
profileAccess?: {
|
||||
@@ -1259,6 +1264,9 @@ export default function OpportunityDraft({
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
{profileMode && record && (
|
||||
<OpportunityTechnicalIncidents incidents={workflowIncidents} />
|
||||
)}
|
||||
{profileMode && record && etag && (
|
||||
<OpportunityProfileActions
|
||||
reauthenticationRequired={profileReauthenticationRequired}
|
||||
|
||||
@@ -2,6 +2,9 @@ import OpportunityLibraryReuse, {
|
||||
type LibrarySource,
|
||||
} from '@/components/opportunity-library-reuse';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import OpportunityTechnicalIncidents, {
|
||||
type OpportunityTechnicalIncident,
|
||||
} from '@/components/opportunity-technical-incidents';
|
||||
import { valueText } from '@/lib/value-text';
|
||||
import { Link, router, usePage } from '@inertiajs/react';
|
||||
import TerritoryGeometryPreview from '@/components/territory-geometry-preview';
|
||||
@@ -150,6 +153,7 @@ export default function OpportunityResources({
|
||||
existingLocations,
|
||||
assessment,
|
||||
imageProcessingAvailable,
|
||||
technicalIncidents = [],
|
||||
librarySources = [],
|
||||
locationReference = { path: [], differences: [] },
|
||||
}: {
|
||||
@@ -164,6 +168,7 @@ export default function OpportunityResources({
|
||||
existingLocations: { id: string; name: string; location_type: string }[];
|
||||
assessment: string[];
|
||||
imageProcessingAvailable: boolean;
|
||||
technicalIncidents?: OpportunityTechnicalIncident[];
|
||||
librarySources?: LibrarySource[];
|
||||
locationReference?: {
|
||||
path: TerritoryOption[];
|
||||
@@ -313,6 +318,7 @@ export default function OpportunityResources({
|
||||
!!opportunity.deleted_at || opportunity.status === 'archived';
|
||||
return (
|
||||
<Management title="Imagens, documentos e localizações">
|
||||
<OpportunityTechnicalIncidents incidents={technicalIncidents} />
|
||||
<Link href={`${basePath}/${opportunity.id}/edit${returnHash}`}>
|
||||
Regressar ao rascunho #{opportunity.id}
|
||||
</Link>
|
||||
|
||||
@@ -0,0 +1,419 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { Management, button, control } from './shared';
|
||||
|
||||
type Filters = {
|
||||
source_hash?: string | null;
|
||||
observation_id?: string | null;
|
||||
q?: string | null;
|
||||
status: string;
|
||||
page: number;
|
||||
};
|
||||
type Observation = {
|
||||
id: string;
|
||||
name: string;
|
||||
province: string;
|
||||
district: string;
|
||||
territory_id: string | null;
|
||||
territory_resolution: string;
|
||||
canonical_territory: string | null;
|
||||
canonical_type: string | null;
|
||||
cae: string;
|
||||
activity: string;
|
||||
sector: string;
|
||||
source_date: string;
|
||||
sheet: string;
|
||||
row_number: number;
|
||||
source_hash: string;
|
||||
identity_conflict: boolean;
|
||||
duplicate_of: string | null;
|
||||
source_name: string;
|
||||
source_period: string;
|
||||
imported_at: string;
|
||||
};
|
||||
type Source = {
|
||||
sha256: string;
|
||||
name: string;
|
||||
period: string;
|
||||
limitations: string;
|
||||
imported_at: string;
|
||||
};
|
||||
type Coverage = {
|
||||
observations: number;
|
||||
distinct_observations: number;
|
||||
repeated: number;
|
||||
unmapped: number;
|
||||
ambiguous: number;
|
||||
territory_unavailable: number;
|
||||
identity_conflict: number;
|
||||
unclassified: number;
|
||||
unnamed: number;
|
||||
};
|
||||
type Props = {
|
||||
installed: boolean;
|
||||
filters: Filters;
|
||||
sources: Source[];
|
||||
coverage: Coverage | null;
|
||||
rows: Observation[];
|
||||
total: number | null;
|
||||
per_page: number;
|
||||
limitations: string;
|
||||
status: string;
|
||||
recordId?: number | null;
|
||||
errors?: Record<string, string>;
|
||||
};
|
||||
const resolutions: Record<string, string> = {
|
||||
exact_normalized_province_district:
|
||||
'Distrito identificado dentro da província',
|
||||
exact_normalized_province_subterritory:
|
||||
'Território subordinado identificado dentro da província',
|
||||
province_only_district_unknown: 'Apenas província; distrito por determinar',
|
||||
ambiguous: 'Várias correspondências possíveis, sem escolha automática',
|
||||
unresolved: 'Sem correspondência inequívoca',
|
||||
};
|
||||
const states: Record<string, string> = {
|
||||
all: 'Todas as observações',
|
||||
unmapped: 'Sem correspondência territorial',
|
||||
ambiguous: 'Correspondência territorial ambígua',
|
||||
territory_unavailable: 'Referência territorial indisponível',
|
||||
identity_conflict: 'Identificador com denominações divergentes',
|
||||
repeated: 'Projecções administrativas repetidas',
|
||||
unclassified: 'Sem designação da actividade',
|
||||
unnamed: 'Sem denominação social',
|
||||
};
|
||||
export function supplyReviewUrl(
|
||||
filters: Partial<Filters>,
|
||||
recordId?: number | null,
|
||||
): string {
|
||||
const values = Object.entries({
|
||||
...filters,
|
||||
...(recordId ? { record_id: recordId } : {}),
|
||||
}).filter(
|
||||
([, value]) => value !== undefined && value !== null && value !== '',
|
||||
);
|
||||
const query = new URLSearchParams(
|
||||
values.map(([key, value]) => [key, String(value)]),
|
||||
);
|
||||
return (
|
||||
'/minhas-oportunidades/oferta-interna/revisao' +
|
||||
(query.size ? `?${query}` : '')
|
||||
);
|
||||
}
|
||||
export default function SupplyReview({
|
||||
installed,
|
||||
filters,
|
||||
sources,
|
||||
coverage,
|
||||
rows,
|
||||
total,
|
||||
per_page,
|
||||
limitations,
|
||||
status,
|
||||
recordId,
|
||||
errors = {},
|
||||
}: Props) {
|
||||
const pages = total === null ? 1 : Math.max(1, Math.ceil(total / per_page));
|
||||
return (
|
||||
<Management title="Conferência da base interna de empresas e empreendimentos">
|
||||
<Link
|
||||
className="underline"
|
||||
href={
|
||||
recordId
|
||||
? `/minhas-oportunidades/${recordId}`
|
||||
: '/minhas-oportunidades'
|
||||
}
|
||||
>
|
||||
Voltar à preparação de oportunidades
|
||||
</Link>
|
||||
<p>{limitations}</p>
|
||||
<p>
|
||||
Consulta das observações já importadas, incluindo pendências que
|
||||
não entram na pesquisa por território. Esta página não altera
|
||||
linhas, correspondências ou cadastros, não consolida entidades e
|
||||
não publica empresas.
|
||||
</p>
|
||||
<form
|
||||
key={supplyReviewUrl(filters, recordId)}
|
||||
action="/minhas-oportunidades/oferta-interna/revisao"
|
||||
method="get"
|
||||
className="grid gap-3 rounded border p-4 md:grid-cols-3"
|
||||
>
|
||||
{recordId && (
|
||||
<input type="hidden" name="record_id" value={recordId} />
|
||||
)}
|
||||
<label>
|
||||
Origem
|
||||
<select
|
||||
name="source_hash"
|
||||
className={control}
|
||||
defaultValue={filters.source_hash ?? ''}
|
||||
>
|
||||
<option value="">Todas as origens</option>
|
||||
{sources.map((source) => (
|
||||
<option key={source.sha256} value={source.sha256}>
|
||||
{source.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Conferir
|
||||
<select
|
||||
name="status"
|
||||
className={control}
|
||||
defaultValue={filters.status}
|
||||
>
|
||||
{Object.entries(states).map(([value, label]) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Nome, local original ou actividade
|
||||
<input
|
||||
name="q"
|
||||
type="search"
|
||||
maxLength={120}
|
||||
defaultValue={filters.q ?? ''}
|
||||
className={control}
|
||||
/>
|
||||
</label>
|
||||
<button className={button}>Pesquisar observações</button>
|
||||
</form>
|
||||
{Object.entries(errors).map(([key, message]) => (
|
||||
<p key={key} role="alert">
|
||||
{message}
|
||||
</p>
|
||||
))}
|
||||
{filters.observation_id && (
|
||||
<p>
|
||||
Está a consultar uma referência específica.{' '}
|
||||
<Link
|
||||
className="underline"
|
||||
href={supplyReviewUrl(
|
||||
{ ...filters, observation_id: null, page: 1 },
|
||||
recordId,
|
||||
)}
|
||||
>
|
||||
Retirar filtro da referência
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
{!installed && (
|
||||
<p role="status">
|
||||
A base interna ainda não está carregada neste ambiente.
|
||||
</p>
|
||||
)}
|
||||
{coverage && (
|
||||
<section
|
||||
className="space-y-2 rounded border p-4"
|
||||
aria-label="Cobertura documental"
|
||||
>
|
||||
<h2 className="text-lg font-semibold">
|
||||
Cobertura documental da origem seleccionada
|
||||
</h2>
|
||||
<p>
|
||||
Contagens anteriores aos filtros de estado, texto e
|
||||
referência; todas as origens quando nenhuma é
|
||||
seleccionada. Os indicadores de pendência podem
|
||||
sobrepor-se.
|
||||
</p>
|
||||
<dl className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{(
|
||||
[
|
||||
[
|
||||
'observations',
|
||||
'Observações retidas (inclui repetições)',
|
||||
],
|
||||
[
|
||||
'distinct_observations',
|
||||
'Projecções administrativas distintas',
|
||||
],
|
||||
[
|
||||
'repeated',
|
||||
'Projecções repetidas conservadas',
|
||||
],
|
||||
['unmapped', 'Sem território canónico'],
|
||||
['ambiguous', 'Territórios ambíguos'],
|
||||
[
|
||||
'territory_unavailable',
|
||||
'Referências territoriais indisponíveis',
|
||||
],
|
||||
[
|
||||
'identity_conflict',
|
||||
'Observações com divergências de identidade',
|
||||
],
|
||||
[
|
||||
'unclassified',
|
||||
'Sem designação de actividade',
|
||||
],
|
||||
['unnamed', 'Sem denominação social'],
|
||||
] as [keyof Coverage, string][]
|
||||
).map(([key, label]) => (
|
||||
<div key={key}>
|
||||
<dt>{label}</dt>
|
||||
<dd className="font-semibold">
|
||||
{coverage[key].toLocaleString('pt-MZ')}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
<p>
|
||||
Estas contagens não são números de empresas únicas,
|
||||
estabelecimentos em funcionamento ou necessidades de
|
||||
investimento confirmadas.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
<p role="status">
|
||||
{status}
|
||||
{total !== null && (
|
||||
<>
|
||||
{' '}
|
||||
{total.toLocaleString('pt-MZ')} observações nestes
|
||||
filtros.
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
<div className="space-y-4">
|
||||
{rows.map((row) => (
|
||||
<article
|
||||
key={row.id}
|
||||
className="space-y-2 rounded border p-4"
|
||||
>
|
||||
<h2 className="text-lg font-semibold">
|
||||
{row.name || 'Denominação não indicada'}
|
||||
</h2>
|
||||
<p>
|
||||
Local escrito no original:{' '}
|
||||
{row.province || 'província não indicada'} /{' '}
|
||||
{row.district || 'distrito não indicado'}.
|
||||
</p>
|
||||
<p>
|
||||
Correspondência guardada:{' '}
|
||||
{resolutions[row.territory_resolution] ||
|
||||
'por conferir'}
|
||||
. Referência territorial consultável:{' '}
|
||||
{row.canonical_territory || 'não disponível'}. Não é
|
||||
uma georreferenciação por coordenadas.
|
||||
</p>
|
||||
<p>
|
||||
CAE: {row.cae || 'não indicado'} · Actividade:{' '}
|
||||
{row.activity || 'sem designação correspondente'} ·
|
||||
Sector CAE: {row.sector || 'não correspondido'}.
|
||||
</p>
|
||||
{row.identity_conflict && (
|
||||
<p className="font-semibold">
|
||||
Identificador partilhado por denominações
|
||||
divergentes. A identidade continua por conferir;
|
||||
não foi feita fusão automática.
|
||||
</p>
|
||||
)}
|
||||
{row.duplicate_of && (
|
||||
<p>
|
||||
Projecção repetida, conservada para
|
||||
rastreabilidade.{' '}
|
||||
<Link
|
||||
className="underline"
|
||||
href={supplyReviewUrl(
|
||||
{
|
||||
observation_id: row.duplicate_of,
|
||||
status: 'all',
|
||||
page: 1,
|
||||
},
|
||||
recordId,
|
||||
)}
|
||||
>
|
||||
Conferir a observação de referência
|
||||
</Link>
|
||||
. Não conte esta linha como outra empresa.
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
Fonte: {row.source_name} · {row.sheet}, linha{' '}
|
||||
{row.row_number}. Data original:{' '}
|
||||
{row.source_date || 'não indicada'}. Período do
|
||||
exemplar: {row.source_period || 'não determinado'}.
|
||||
</p>
|
||||
<p>
|
||||
Importação registada em {row.imported_at}; não
|
||||
representa actualização ou confirmação da actividade
|
||||
da empresa.
|
||||
</p>
|
||||
<details>
|
||||
<summary>
|
||||
Referência e integridade da origem
|
||||
</summary>
|
||||
<p className="break-all">
|
||||
SHA256 do original: {row.source_hash}.
|
||||
</p>
|
||||
<p>
|
||||
Código da correspondência:{' '}
|
||||
{row.territory_resolution || 'não indicado'}.
|
||||
</p>
|
||||
</details>
|
||||
<Link
|
||||
className="underline"
|
||||
href={supplyReviewUrl(
|
||||
{
|
||||
observation_id: row.id,
|
||||
source_hash: row.source_hash,
|
||||
status: 'all',
|
||||
page: 1,
|
||||
},
|
||||
recordId,
|
||||
)}
|
||||
>
|
||||
Ligação para recuperar esta linha
|
||||
</Link>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
{total !== null && total > 0 && (
|
||||
<nav
|
||||
className="flex gap-4"
|
||||
aria-label="Paginação das observações"
|
||||
>
|
||||
{filters.page > 1 && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={supplyReviewUrl(
|
||||
{ ...filters, page: filters.page - 1 },
|
||||
recordId,
|
||||
)}
|
||||
>
|
||||
Anterior
|
||||
</Link>
|
||||
)}
|
||||
<span>
|
||||
Página {filters.page} de {pages}
|
||||
</span>
|
||||
{filters.page < pages && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={supplyReviewUrl(
|
||||
{ ...filters, page: filters.page + 1 },
|
||||
recordId,
|
||||
)}
|
||||
>
|
||||
Seguinte
|
||||
</Link>
|
||||
)}
|
||||
</nav>
|
||||
)}
|
||||
<details>
|
||||
<summary>Origens disponíveis e limites dos exemplares</summary>
|
||||
{sources.map((source) => (
|
||||
<div key={source.sha256} className="mt-3">
|
||||
<p className="font-semibold">{source.name}</p>
|
||||
<p>
|
||||
{source.period}. {source.limitations}
|
||||
</p>
|
||||
<p>Registo da importação: {source.imported_at}.</p>
|
||||
</div>
|
||||
))}
|
||||
</details>
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
import { Link, usePage } from '@inertiajs/react';
|
||||
import { Frame, card, input, button } from '@/pages/investment/shared';
|
||||
import { usageExport, usageValue, type UsageReport } from '@/lib/product-usage';
|
||||
import SearchUsage from '@/components/search-usage-report';
|
||||
|
||||
const coverageLabels: Record<string, string> = {
|
||||
cohort_requests: 'Pedidos na coorte',
|
||||
complete_histories: 'Com historial completo',
|
||||
unknown_histories: 'Sem historial suficiente',
|
||||
classified_returned_requests: 'Devolvidos com causa determinada',
|
||||
unclassified_returned_requests: 'Devolvidos com causa por classificar',
|
||||
valid_duration_requests: 'Com duração válida',
|
||||
invalid_duration_requests: 'Com intervalo negativo excluído',
|
||||
};
|
||||
|
||||
export default function ProductUsage({ report }: { report: UsageReport }) {
|
||||
const { errors } = usePage().props;
|
||||
function download() {
|
||||
const url = URL.createObjectURL(
|
||||
new Blob([usageExport(report)], { type: 'application/json' }),
|
||||
);
|
||||
const anchor = document.createElement('a');
|
||||
anchor.href = url;
|
||||
anchor.download = `indicadores-${report.filters.from}-${report.filters.to}.json`;
|
||||
anchor.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
return (
|
||||
<Frame title="Indicadores de utilização">
|
||||
<nav
|
||||
className="flex flex-wrap gap-4"
|
||||
aria-label="Navegação de indicadores"
|
||||
>
|
||||
<Link className="underline" href="/dashboard">
|
||||
Voltar ao painel
|
||||
</Link>
|
||||
<Link
|
||||
className="underline"
|
||||
href="/management/product-experiments"
|
||||
>
|
||||
Registo de experiências e decisões
|
||||
</Link>
|
||||
</nav>
|
||||
<p>
|
||||
Leitura dos registos operacionais disponíveis. Cada indicador
|
||||
apresenta a sua base e as limitações de cobertura.
|
||||
</p>
|
||||
<form
|
||||
key={JSON.stringify(report.filters)}
|
||||
action="/management/product-usage"
|
||||
method="get"
|
||||
className={card + ' grid gap-4 md:grid-cols-4'}
|
||||
>
|
||||
<label>
|
||||
Desde (UTC)
|
||||
<input
|
||||
className={input}
|
||||
type="date"
|
||||
name="from"
|
||||
required
|
||||
defaultValue={report.filters.from}
|
||||
max={report.generated_at.slice(0, 10)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Até (UTC)
|
||||
<input
|
||||
className={input}
|
||||
type="date"
|
||||
name="to"
|
||||
required
|
||||
defaultValue={report.filters.to}
|
||||
max={report.generated_at.slice(0, 10)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Serviço
|
||||
<select
|
||||
className={input}
|
||||
name="service_code"
|
||||
defaultValue={report.filters.service_code ?? ''}
|
||||
>
|
||||
<option value="">Todos os serviços</option>
|
||||
{report.services.map((s) => (
|
||||
<option key={s.code} value={s.code}>
|
||||
{s.title} ({s.code})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{report.search && (
|
||||
<label>
|
||||
Edição da recolha de pesquisa
|
||||
<select
|
||||
className={input}
|
||||
name="search_definition"
|
||||
defaultValue={
|
||||
report.filters.search_definition ??
|
||||
report.search.definition_version
|
||||
}
|
||||
>
|
||||
{report.search.available_definitions.map(
|
||||
(version) => (
|
||||
<option key={version} value={version}>
|
||||
{version}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<button className={button}>Aplicar filtros</button>
|
||||
{Object.entries(errors).map(([k, v]) => (
|
||||
<p role="alert" key={k}>
|
||||
{String(v)}
|
||||
</p>
|
||||
))}
|
||||
</form>
|
||||
<section
|
||||
className={card + ' space-y-3'}
|
||||
aria-label="Período aplicado"
|
||||
>
|
||||
<p>
|
||||
Período aplicado: {report.filters.from} a{' '}
|
||||
{report.filters.to}, em {report.timezone}. Serviço:{' '}
|
||||
{report.filters.service_code ?? 'todos'}.
|
||||
</p>
|
||||
<p>
|
||||
{report.search ? (
|
||||
<>
|
||||
Eventos do Balcão anteriores a{' '}
|
||||
{report.observed_before}. Pesquisas usam as
|
||||
contagens diárias na leitura indicada abaixo.
|
||||
</>
|
||||
) : (
|
||||
<>Observações anteriores a {report.observed_before}.</>
|
||||
)}{' '}
|
||||
Relatório gerado em {report.generated_at}.
|
||||
</p>
|
||||
<button className={button} onClick={download}>
|
||||
Exportar este relatório (JSON)
|
||||
</button>
|
||||
</section>
|
||||
{report.search && <SearchUsage search={report.search} />}
|
||||
<section className={card} aria-labelledby="coverage-title">
|
||||
<h2 id="coverage-title" className="text-xl font-semibold">
|
||||
Cobertura da coorte de pedidos
|
||||
</h2>
|
||||
<dl className="grid gap-3 md:grid-cols-3">
|
||||
{Object.entries(report.coverage).map(([key, value]) => (
|
||||
<div key={key}>
|
||||
<dt>{coverageLabels[key] ?? key}</dt>
|
||||
<dd className="font-semibold">
|
||||
{usageValue(value)}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
<p>
|
||||
Pedidos sem historial suficiente ficam fora das taxas. Uma
|
||||
base vazia ou desconhecida não produz uma taxa de 0%.
|
||||
</p>
|
||||
</section>
|
||||
<div className={card + ' overflow-x-auto'}>
|
||||
<table className="w-full text-left">
|
||||
<caption className="mb-3 text-left text-xl font-semibold">
|
||||
Indicadores observáveis
|
||||
</caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="p-2">Indicador</th>
|
||||
<th className="p-2">Valor</th>
|
||||
<th className="p-2">Base</th>
|
||||
<th className="p-2">Definição e limites</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{report.metrics.map((m) => (
|
||||
<tr key={m.id} className="border-t align-top">
|
||||
<th scope="row" className="p-2">
|
||||
{m.title}
|
||||
</th>
|
||||
<td className="p-2">
|
||||
{usageValue(m.value, m.unit)}
|
||||
<p>
|
||||
{m.state === 'partial'
|
||||
? 'Cobertura parcial'
|
||||
: m.state === 'unmeasured'
|
||||
? 'Sem base para calcular'
|
||||
: 'Observado'}
|
||||
</p>
|
||||
</td>
|
||||
<td className="p-2">
|
||||
{m.numerator !== null && (
|
||||
<p>
|
||||
Numerador: {usageValue(m.numerator)}
|
||||
</p>
|
||||
)}
|
||||
{m.denominator !== null && (
|
||||
<p>
|
||||
Denominador:{' '}
|
||||
{usageValue(m.denominator)}
|
||||
</p>
|
||||
)}
|
||||
{m.numerator === null &&
|
||||
m.denominator === null &&
|
||||
'Contagem directa'}
|
||||
</td>
|
||||
<td className="p-2">
|
||||
<details>
|
||||
<summary className="cursor-pointer underline">
|
||||
Consultar definição
|
||||
</summary>
|
||||
<p>{m.source}</p>
|
||||
<p>{m.limits}</p>
|
||||
</details>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<section
|
||||
className={card + ' space-y-3'}
|
||||
aria-labelledby="unmeasured-title"
|
||||
>
|
||||
<h2 id="unmeasured-title" className="text-xl font-semibold">
|
||||
Indicadores ainda sem medição
|
||||
</h2>
|
||||
{report.unmeasured.map((m) => (
|
||||
<details key={m.id}>
|
||||
<summary className="cursor-pointer underline">
|
||||
{m.title}
|
||||
</summary>
|
||||
<p>{m.reason}</p>
|
||||
{m.href && (
|
||||
<Link className="underline" href={m.href}>
|
||||
Consultar registo
|
||||
</Link>
|
||||
)}
|
||||
</details>
|
||||
))}
|
||||
</section>
|
||||
<section
|
||||
className={card + ' space-y-3'}
|
||||
aria-labelledby="limits-title"
|
||||
>
|
||||
<h2 id="limits-title" className="text-xl font-semibold">
|
||||
Como interpretar
|
||||
</h2>
|
||||
<ul className="list-disc pl-5">
|
||||
{report.limits.map((l) => (
|
||||
<li key={l}>{l}</li>
|
||||
))}
|
||||
</ul>
|
||||
<details>
|
||||
<summary className="cursor-pointer underline">
|
||||
Identificação do relatório
|
||||
</summary>
|
||||
<p>Definição: {report.definition_version}</p>
|
||||
<p className="break-all">SHA-256: {report.fingerprint}</p>
|
||||
<p>Consistência da leitura: {report.read_consistency}</p>
|
||||
</details>
|
||||
</section>
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
@@ -54,7 +54,7 @@ export function Management({
|
||||
const { flash, educationEnabled, aiEnabled, auth, basePath } = usePage<{
|
||||
auth?: { canManagePortal?: boolean };
|
||||
basePath?: string;
|
||||
flash?: { success?: string };
|
||||
flash?: { success?: string; warning?: string };
|
||||
educationEnabled?: boolean;
|
||||
aiEnabled?: boolean;
|
||||
}>().props;
|
||||
@@ -126,6 +126,14 @@ export function Management({
|
||||
{flash.success}
|
||||
</p>
|
||||
)}
|
||||
{flash?.warning && (
|
||||
<p
|
||||
role="alert"
|
||||
className="rounded-md border border-amber-500 p-3"
|
||||
>
|
||||
{flash.warning}
|
||||
</p>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import AgreementInstrument from '@/components/partnership-agreement-instrument';
|
||||
import { Frame, labels } from './shared';
|
||||
|
||||
type Availability =
|
||||
| 'available'
|
||||
| 'not_recorded'
|
||||
| 'scope_unknown'
|
||||
| 'restricted'
|
||||
| 'malformed';
|
||||
type Snapshot = {
|
||||
availability: Availability;
|
||||
version?: number;
|
||||
status?: string;
|
||||
instrument_availability?: Availability;
|
||||
instrument?: unknown;
|
||||
instrument_partnership_version?: number;
|
||||
instrument_interest_version?: number;
|
||||
};
|
||||
type Entry = {
|
||||
version: number | null;
|
||||
restricted: boolean;
|
||||
action: string | null;
|
||||
actor_name: string | null;
|
||||
occurred_at: string | null;
|
||||
reason: string | null;
|
||||
confirmation_party: string | null;
|
||||
partnership_version: number | null;
|
||||
interest_version: number | null;
|
||||
previous: Snapshot;
|
||||
after: Snapshot;
|
||||
};
|
||||
type Props = {
|
||||
room_id: number;
|
||||
entries: Entry[];
|
||||
first_url: string;
|
||||
next_url: string | null;
|
||||
older_page: boolean;
|
||||
room_href: string;
|
||||
dashboard_href: string;
|
||||
};
|
||||
const actions: Record<string, string> = {
|
||||
record: 'Registo de instrumento',
|
||||
confirm: 'Confirmação de parte',
|
||||
start: 'Início do acompanhamento',
|
||||
complete: 'Conclusão',
|
||||
cancel: 'Cancelamento',
|
||||
renew: 'Renovação',
|
||||
};
|
||||
const unavailable: Record<string, string> = {
|
||||
not_recorded:
|
||||
'Esta informação não ficou guardada no evento. Não foi preenchida com a versão actual.',
|
||||
scope_unknown:
|
||||
'O âmbito deste registo antigo não ficou identificado; o conteúdo não está disponível para esta conta.',
|
||||
restricted:
|
||||
'O registo pertence a uma representação à qual esta conta não tem acesso actual.',
|
||||
malformed:
|
||||
'O instrumento guardado não tem uma estrutura reconhecida. O registo foi conservado.',
|
||||
};
|
||||
function Version({ value, title }: { value: Snapshot; title: string }) {
|
||||
return (
|
||||
<section className="space-y-3 rounded border p-4">
|
||||
<h3 className="font-bold">{title}</h3>
|
||||
{value.availability !== 'available' ? (
|
||||
<p>{unavailable[value.availability]}</p>
|
||||
) : (
|
||||
<>
|
||||
<p>
|
||||
Versão da sala {value.version} ·{' '}
|
||||
{labels[value.status ?? ''] ??
|
||||
value.status ??
|
||||
'Estado não registado'}
|
||||
</p>
|
||||
{value.instrument_availability !== 'available' ? (
|
||||
<p>
|
||||
{
|
||||
unavailable[
|
||||
value.instrument_availability ??
|
||||
'not_recorded'
|
||||
]
|
||||
}
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<p>
|
||||
Contexto do instrumento: proposta{' '}
|
||||
{value.instrument_partnership_version ??
|
||||
'não registada'}{' '}
|
||||
· candidatura{' '}
|
||||
{value.instrument_interest_version ??
|
||||
'não registada'}
|
||||
.
|
||||
</p>
|
||||
<AgreementInstrument value={value.instrument} />
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
export default function AgreementHistory(p: Props) {
|
||||
return (
|
||||
<Frame title={`Histórico do acordo · Sala ${p.room_id}`}>
|
||||
<div className="space-y-6 break-words">
|
||||
<nav
|
||||
aria-label="Navegação do histórico"
|
||||
className="flex flex-wrap gap-4"
|
||||
>
|
||||
<Link className="underline" href={p.room_href}>
|
||||
Voltar à sala
|
||||
</Link>
|
||||
<Link className="underline" href={p.dashboard_href}>
|
||||
Painel de parcerias
|
||||
</Link>
|
||||
{p.older_page && (
|
||||
<Link className="underline" href={p.first_url}>
|
||||
Versões mais recentes
|
||||
</Link>
|
||||
)}
|
||||
</nav>
|
||||
<p>
|
||||
Consulta das decisões e instrumentos guardados, do mais
|
||||
recente para o mais antigo. Os nomes de pessoas provêm do
|
||||
cadastro actual; as condições, motivos e confirmações são os
|
||||
que ficaram registados. Esta consulta não altera decisões
|
||||
nem certifica assinatura jurídica.
|
||||
</p>
|
||||
{!p.entries.length && (
|
||||
<p>
|
||||
Ainda não existem alterações do acordo guardadas para
|
||||
apresentar.
|
||||
</p>
|
||||
)}
|
||||
{p.entries.map((entry, index) => (
|
||||
<details
|
||||
key={index}
|
||||
open={index === 0}
|
||||
className="space-y-4 rounded border p-4"
|
||||
>
|
||||
<summary className="cursor-pointer font-bold">
|
||||
Versão {entry.version ?? 'não registada'} ·{' '}
|
||||
{entry.restricted
|
||||
? 'Conteúdo reservado'
|
||||
: (actions[entry.action ?? ''] ??
|
||||
'Alteração registada')}
|
||||
</summary>
|
||||
{!entry.restricted && (
|
||||
<>
|
||||
<p>
|
||||
{entry.actor_name ?? 'Autor não registado'}{' '}
|
||||
·{' '}
|
||||
{entry.occurred_at ?? 'Data não registada'}
|
||||
</p>
|
||||
<p>
|
||||
Contexto da decisão: proposta{' '}
|
||||
{entry.partnership_version ??
|
||||
'não registada'}{' '}
|
||||
· candidatura{' '}
|
||||
{entry.interest_version ?? 'não registada'}.
|
||||
</p>
|
||||
{entry.confirmation_party && (
|
||||
<p>
|
||||
Parte que confirmou:{' '}
|
||||
{entry.confirmation_party ===
|
||||
'proponent'
|
||||
? 'Proponente'
|
||||
: 'Candidata'}
|
||||
.
|
||||
</p>
|
||||
)}
|
||||
{entry.reason !== null && (
|
||||
<p className="whitespace-pre-wrap">
|
||||
Motivo: {entry.reason || 'Não indicado'}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
<Version
|
||||
title="Antes da alteração"
|
||||
value={entry.previous}
|
||||
/>
|
||||
<Version
|
||||
title="Após a alteração"
|
||||
value={entry.after}
|
||||
/>
|
||||
</div>
|
||||
</details>
|
||||
))}
|
||||
{p.next_url && (
|
||||
<Link className="inline-block underline" href={p.next_url}>
|
||||
Consultar versões anteriores
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
@@ -5,7 +5,8 @@ type Props = {
|
||||
interests: {
|
||||
id: number;
|
||||
partnership_id: number;
|
||||
title: string;
|
||||
title: string | null;
|
||||
partnership_href: string | null;
|
||||
status: string;
|
||||
decision_reason: string | null;
|
||||
room_id: number | null;
|
||||
@@ -38,6 +39,14 @@ export default function Dashboard(p: Props) {
|
||||
{x.title || 'Ideia sem título'}
|
||||
</Link>
|
||||
<p>{labels[x.status] ?? x.status}</p>
|
||||
<p>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/parcerias/${x.id}/historico`}
|
||||
>
|
||||
Consultar versões e decisões da publicação
|
||||
</Link>
|
||||
</p>
|
||||
<p>
|
||||
Próxima ação:{' '}
|
||||
{['draft', 'returned', 'rejected'].includes(
|
||||
@@ -57,15 +66,30 @@ export default function Dashboard(p: Props) {
|
||||
</h2>
|
||||
{p.interests.map((x) => (
|
||||
<article className="my-4 rounded border p-4" key={x.id}>
|
||||
<Link
|
||||
className="underline"
|
||||
href={'/parcerias/' + x.partnership_id}
|
||||
>
|
||||
{x.title}
|
||||
</Link>
|
||||
{x.partnership_href ? (
|
||||
<Link
|
||||
className="underline"
|
||||
href={x.partnership_href}
|
||||
>
|
||||
{x.title || 'Parceria sem título'}
|
||||
</Link>
|
||||
) : (
|
||||
<p>
|
||||
Parceria {x.partnership_id} · consulta da
|
||||
proposta indisponível com o acesso actual
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
{labels[x.status]} · {x.decision_reason}
|
||||
</p>
|
||||
<p>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/parcerias/candidaturas/${x.id}/historico`}
|
||||
>
|
||||
Consultar versões e decisões
|
||||
</Link>
|
||||
</p>
|
||||
{x.room_id && (
|
||||
<Link
|
||||
className={button}
|
||||
@@ -88,6 +112,13 @@ export default function Dashboard(p: Props) {
|
||||
>
|
||||
{x.title} · {labels[x.status]}
|
||||
</Link>
|
||||
{' · '}
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/parcerias/${x.id}/historico`}
|
||||
>
|
||||
Histórico da publicação
|
||||
</Link>
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
@@ -96,6 +127,12 @@ export default function Dashboard(p: Props) {
|
||||
<h2 className="text-xl font-bold">
|
||||
Notificações no portal
|
||||
</h2>
|
||||
<p>
|
||||
São apresentados os avisos cuja consulta está autorizada
|
||||
no âmbito actual e no que ficou guardado no evento.
|
||||
Avisos antigos sem esse âmbito identificável permanecem
|
||||
no registo.
|
||||
</p>
|
||||
{p.notifications.map((n) => (
|
||||
<article className="my-3 rounded border p-3" key={n.id}>
|
||||
<Link href={n.href} className="underline">
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { Link, useForm, usePage } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import PartnershipPublication from '@/components/partnership-publication';
|
||||
import PublicationSummary from '@/components/partnership-publication-summary';
|
||||
import type { PublicationHistorySummary } from '@/lib/partnership-history';
|
||||
import { Link, usePage } from '@inertiajs/react';
|
||||
import PartnershipCandidacies from '@/components/partnership-candidacies';
|
||||
import { ComplementEntryActions } from '@/components/investment-complements';
|
||||
import StructureGeographyPanel, {
|
||||
type StructureGeography,
|
||||
} from '@/components/structure-geography';
|
||||
import {
|
||||
Frame,
|
||||
Errors,
|
||||
Field,
|
||||
control,
|
||||
button,
|
||||
labels,
|
||||
type Catalogues,
|
||||
@@ -16,10 +18,14 @@ import {
|
||||
type Source,
|
||||
} from './shared';
|
||||
type Props = Catalogues & {
|
||||
publicationActions: string[];
|
||||
publicationCommands: { key: string; action: string; version: number }[];
|
||||
record: Partnership;
|
||||
owner: boolean;
|
||||
canEdit: boolean;
|
||||
moderator: boolean;
|
||||
acceptingInterests: boolean;
|
||||
canStartInterest: boolean;
|
||||
origins: (Source & { geography: StructureGeography | null })[];
|
||||
locations: {
|
||||
id: string;
|
||||
@@ -29,454 +35,11 @@ type Props = Catalogues & {
|
||||
path: { name: string }[];
|
||||
}[];
|
||||
interests: Interest[];
|
||||
history: {
|
||||
event_type: string;
|
||||
actor_id: number;
|
||||
occurred_at: string;
|
||||
payload: string;
|
||||
}[];
|
||||
historySummary: PublicationHistorySummary | null;
|
||||
};
|
||||
function Publication({ p }: { p: Props }) {
|
||||
const form = useForm({ version: p.record.version, action: '', reason: '' });
|
||||
const action = (value: string) => {
|
||||
form.transform((data) => ({ ...data, action: value }));
|
||||
form.post('/parcerias/' + p.record.id + '/estado', {
|
||||
preserveScroll: true,
|
||||
});
|
||||
};
|
||||
return (
|
||||
<section className="space-y-4 rounded border p-5">
|
||||
<h2 className="text-xl font-bold">Pré-visualização e publicação</h2>
|
||||
<p>
|
||||
Estado: {labels[p.record.status] ?? p.record.status}.
|
||||
Verificação da organização, setor e localização permanecem por
|
||||
confirmar quando não há evidência.
|
||||
</p>
|
||||
<Field label="Motivo da ação">
|
||||
<textarea
|
||||
className={control}
|
||||
value={form.data.reason}
|
||||
onChange={(e) => form.setData('reason', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Errors errors={form.errors} />
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{p.canEdit &&
|
||||
['draft', 'returned', 'rejected'].includes(
|
||||
p.record.status,
|
||||
) && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={form.processing || !form.data.reason}
|
||||
onClick={() => action('submit')}
|
||||
>
|
||||
Submeter para publicação
|
||||
</button>
|
||||
)}
|
||||
{p.moderator &&
|
||||
!p.owner &&
|
||||
['submitted', 'pending'].includes(p.record.status) &&
|
||||
['publish', 'return', 'reject'].map((value) => (
|
||||
<button
|
||||
className={button}
|
||||
key={value}
|
||||
disabled={form.processing || !form.data.reason}
|
||||
onClick={() => action(value)}
|
||||
>
|
||||
{
|
||||
{
|
||||
publish: 'Publicar',
|
||||
return: 'Devolver para correção',
|
||||
reject: 'Rejeitar com fundamento',
|
||||
}[value]
|
||||
}
|
||||
</button>
|
||||
))}
|
||||
{p.canEdit &&
|
||||
['published', 'suspended', 'archived'].includes(
|
||||
p.record.status,
|
||||
) && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={form.processing || !form.data.reason}
|
||||
onClick={() => action('renew')}
|
||||
>
|
||||
Renovar em rascunho
|
||||
</button>
|
||||
)}
|
||||
{p.canEdit &&
|
||||
['draft', 'published', 'suspended', 'rejected'].includes(
|
||||
p.record.status,
|
||||
) && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={form.processing || !form.data.reason}
|
||||
onClick={() => action('archive')}
|
||||
>
|
||||
Arquivar publicação
|
||||
</button>
|
||||
)}
|
||||
{p.canEdit && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={'/parcerias/' + p.record.id + '/editar'}
|
||||
>
|
||||
Editar rascunho
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
function InterestForm({
|
||||
record,
|
||||
interest,
|
||||
organizations,
|
||||
}: {
|
||||
record: Partnership;
|
||||
interest?: Interest;
|
||||
organizations: Catalogues['organizations'];
|
||||
}) {
|
||||
const form = useForm({
|
||||
version: interest?.version ?? null,
|
||||
organization_id: interest?.organization_id ?? '',
|
||||
proposal: interest?.proposal ?? '',
|
||||
payload: {
|
||||
capacity: interest?.payload.capacity ?? '',
|
||||
availability: interest?.payload.availability ?? '',
|
||||
contribution: interest?.payload.contribution ?? '',
|
||||
conflicts: interest?.payload.conflicts ?? '',
|
||||
consent: interest?.payload.consent ?? false,
|
||||
},
|
||||
});
|
||||
return (
|
||||
<form
|
||||
className="space-y-4 rounded border p-5"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.post('/parcerias/' + record.id + '/interesses', {
|
||||
preserveScroll: true,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<h2 className="text-xl font-bold">
|
||||
{interest
|
||||
? 'Atualizar manifestação de interesse'
|
||||
: 'Manifestar interesse'}
|
||||
</h2>
|
||||
<p>
|
||||
Declarações são informações comunicadas por si; não atribuem
|
||||
verificação. Dados desconhecidos podem ser esclarecidos no
|
||||
processo.
|
||||
</p>
|
||||
<Errors errors={form.errors} />
|
||||
<Field label="Participação">
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.organization_id}
|
||||
onChange={(e) =>
|
||||
form.setData('organization_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Participação pessoal</option>
|
||||
{organizations.map((o) => (
|
||||
<option key={o.id} value={o.id}>
|
||||
{o.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Proposta curta">
|
||||
<textarea
|
||||
className={control}
|
||||
value={form.data.proposal}
|
||||
onChange={(e) => form.setData('proposal', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
{(
|
||||
[
|
||||
'capacity',
|
||||
'availability',
|
||||
'contribution',
|
||||
'conflicts',
|
||||
] as const
|
||||
).map((key) => (
|
||||
<Field
|
||||
key={key}
|
||||
label={
|
||||
{
|
||||
capacity: 'Capacidade disponível',
|
||||
availability: 'Disponibilidade',
|
||||
contribution: 'Contribuição proposta',
|
||||
conflicts: 'Conflitos de interesse declarados',
|
||||
}[key]
|
||||
}
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
value={form.data.payload[key]}
|
||||
onChange={(e) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
[key]: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
))}
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.payload.consent}
|
||||
onChange={(e) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
consent: e.target.checked,
|
||||
})
|
||||
}
|
||||
/>{' '}
|
||||
Autorizo a partilha desta candidatura com o responsável pela
|
||||
parceria.
|
||||
</label>
|
||||
<button className={button} disabled={form.processing}>
|
||||
Guardar interesse
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
function Candidacy({
|
||||
interest,
|
||||
owner,
|
||||
canEdit,
|
||||
record,
|
||||
organizations,
|
||||
}: {
|
||||
interest: Interest;
|
||||
owner: boolean;
|
||||
canEdit: boolean;
|
||||
record: Partnership;
|
||||
organizations: Catalogues['organizations'];
|
||||
}) {
|
||||
const assessment = Object.fromEntries(
|
||||
interest.match.criteria.map((c) => [
|
||||
c.code,
|
||||
{
|
||||
state: interest.assessment[c.code]?.state ?? 'unknown',
|
||||
evidence: interest.assessment[c.code]?.evidence ?? '',
|
||||
},
|
||||
]),
|
||||
);
|
||||
const form = useForm({
|
||||
version: interest.version,
|
||||
action: '',
|
||||
reason: '',
|
||||
assessment,
|
||||
});
|
||||
const act = (action: string) => {
|
||||
form.transform((data) => ({
|
||||
...data,
|
||||
action,
|
||||
assessment: action === 'assess' ? data.assessment : {},
|
||||
}));
|
||||
form.post('/parcerias/candidaturas/' + interest.id, {
|
||||
preserveScroll: true,
|
||||
});
|
||||
};
|
||||
return (
|
||||
<article className="space-y-4 rounded border p-5">
|
||||
<h3 className="text-lg font-bold">
|
||||
Candidatura {interest.id} · {labels[interest.status]}
|
||||
</h3>
|
||||
<p>{interest.proposal}</p>
|
||||
<p>{interest.payload.capacity}</p>
|
||||
<p>
|
||||
Disponibilidade:{' '}
|
||||
{interest.payload.availability || 'Por esclarecer'}
|
||||
</p>
|
||||
<p>
|
||||
Contribuição:{' '}
|
||||
{interest.payload.contribution || 'Por esclarecer'}
|
||||
</p>
|
||||
<p>
|
||||
Conflitos declarados:{' '}
|
||||
{interest.payload.conflicts || 'Sem informação'}
|
||||
</p>
|
||||
{interest.decision_reason && (
|
||||
<p>Última decisão: {interest.decision_reason}</p>
|
||||
)}
|
||||
<p>
|
||||
Correspondência: {interest.match.score_min}–
|
||||
{interest.match.score_max}% · Elegibilidade:{' '}
|
||||
{labels[interest.match.eligibility]}. O intervalo distingue
|
||||
dados desconhecidos de incumprimentos; não é uma aprovação.
|
||||
</p>
|
||||
<ul className="space-y-2">
|
||||
{interest.match.criteria.map((c) => (
|
||||
<li key={c.code}>
|
||||
{c.label} · peso {c.weight} · {labels[c.state]}
|
||||
{c.mandatory ? ' · Obrigatório' : ''}
|
||||
{c.evidence && <> · Evidência: {c.evidence}</>}
|
||||
<p className="text-sm">{c.explanation}</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{interest.room_id && (
|
||||
<Link
|
||||
className={button}
|
||||
href={'/parcerias/salas/' + interest.room_id}
|
||||
>
|
||||
Abrir conexão privada
|
||||
</Link>
|
||||
)}
|
||||
{owner &&
|
||||
canEdit &&
|
||||
['submitted', 'clarification', 'shortlisted'].includes(
|
||||
interest.status,
|
||||
) && (
|
||||
<>
|
||||
<details className="space-y-4">
|
||||
<summary>Registar avaliação fundamentada</summary>
|
||||
{interest.match.criteria.map((c) => (
|
||||
<div
|
||||
className="my-3 grid gap-3 md:grid-cols-2"
|
||||
key={c.code}
|
||||
>
|
||||
<Field label={c.label}>
|
||||
<select
|
||||
className={control}
|
||||
value={
|
||||
form.data.assessment[c.code]
|
||||
.state
|
||||
}
|
||||
onChange={(e) =>
|
||||
form.setData('assessment', {
|
||||
...form.data.assessment,
|
||||
[c.code]: {
|
||||
...form.data.assessment[
|
||||
c.code
|
||||
],
|
||||
state: e.target.value,
|
||||
},
|
||||
})
|
||||
}
|
||||
>
|
||||
{['unknown', 'met', 'unmet'].map(
|
||||
(state) => (
|
||||
<option
|
||||
key={state}
|
||||
value={state}
|
||||
>
|
||||
{labels[state]}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Referência da evidência">
|
||||
<input
|
||||
className={control}
|
||||
value={
|
||||
form.data.assessment[c.code]
|
||||
.evidence
|
||||
}
|
||||
onChange={(e) =>
|
||||
form.setData('assessment', {
|
||||
...form.data.assessment,
|
||||
[c.code]: {
|
||||
...form.data.assessment[
|
||||
c.code
|
||||
],
|
||||
evidence:
|
||||
e.target.value,
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
))}
|
||||
</details>
|
||||
<Field label="Motivo da decisão ou pedido de esclarecimento">
|
||||
<textarea
|
||||
className={control}
|
||||
value={form.data.reason}
|
||||
onChange={(e) =>
|
||||
form.setData('reason', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{[
|
||||
'assess',
|
||||
'clarify',
|
||||
'shortlist',
|
||||
'reject',
|
||||
...(interest.status === 'shortlisted'
|
||||
? ['connect']
|
||||
: []),
|
||||
].map((action) => (
|
||||
<button
|
||||
key={action}
|
||||
className={button}
|
||||
disabled={
|
||||
form.processing || !form.data.reason
|
||||
}
|
||||
onClick={() => act(action)}
|
||||
>
|
||||
{
|
||||
{
|
||||
assess: 'Guardar avaliação',
|
||||
clarify: 'Pedir esclarecimento',
|
||||
shortlist:
|
||||
'Adicionar à lista curta',
|
||||
reject: 'Não selecionar',
|
||||
connect: 'Abrir negociação',
|
||||
}[action]
|
||||
}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{!owner &&
|
||||
['submitted', 'clarification', 'shortlisted'].includes(
|
||||
interest.status,
|
||||
) && (
|
||||
<>
|
||||
<Field label="Motivo da retirada">
|
||||
<textarea
|
||||
className={control}
|
||||
value={form.data.reason}
|
||||
onChange={(e) =>
|
||||
form.setData('reason', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<button
|
||||
className={button}
|
||||
disabled={form.processing || !form.data.reason}
|
||||
onClick={() => act('withdraw')}
|
||||
>
|
||||
Retirar candidatura
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{!owner &&
|
||||
['submitted', 'clarification', 'withdrawn'].includes(
|
||||
interest.status,
|
||||
) && (
|
||||
<InterestForm
|
||||
record={record}
|
||||
interest={interest}
|
||||
organizations={organizations}
|
||||
/>
|
||||
)}
|
||||
<Errors errors={form.errors} />
|
||||
</article>
|
||||
);
|
||||
}
|
||||
export default function Detail(p: Props) {
|
||||
const { auth } = usePage<{ auth: { user: unknown } }>().props;
|
||||
const { auth } = usePage<{ auth: { user: { id: number } | null } }>().props;
|
||||
const [publicationDirty, setPublicationDirty] = useState(false);
|
||||
return (
|
||||
<Frame title={p.record.title || 'Pré-visualização da ideia'}>
|
||||
<ComplementEntryActions target={'partnership:' + p.record.id} />
|
||||
@@ -548,8 +111,13 @@ export default function Detail(p: Props) {
|
||||
)}
|
||||
</section>
|
||||
))}
|
||||
{(p.owner || p.moderator) && (
|
||||
<Publication key={p.record.version} p={p} />
|
||||
{auth.user && (
|
||||
<PartnershipPublication
|
||||
key={`${p.record.id}:${auth.user.id}`}
|
||||
p={p}
|
||||
actorId={auth.user.id}
|
||||
onDirty={setPublicationDirty}
|
||||
/>
|
||||
)}
|
||||
{p.owner && p.interests.length > 0 && (
|
||||
<section className="overflow-x-auto rounded border p-4">
|
||||
@@ -589,40 +157,18 @@ export default function Detail(p: Props) {
|
||||
</table>
|
||||
</section>
|
||||
)}
|
||||
{p.interests.map((i) => (
|
||||
<Candidacy
|
||||
key={i.id + ':' + i.version}
|
||||
interest={i}
|
||||
owner={p.owner}
|
||||
canEdit={p.canEdit}
|
||||
record={p.record}
|
||||
organizations={p.organizations}
|
||||
/>
|
||||
))}
|
||||
{!p.owner &&
|
||||
p.record.status === 'published' &&
|
||||
auth.user &&
|
||||
!p.interests.length && (
|
||||
<InterestForm
|
||||
record={p.record}
|
||||
organizations={p.organizations}
|
||||
/>
|
||||
)}
|
||||
<PartnershipCandidacies
|
||||
key={auth.user?.id ?? 'public'}
|
||||
p={p}
|
||||
otherDirty={publicationDirty}
|
||||
/>
|
||||
{!auth.user && p.record.status === 'published' && (
|
||||
<Link className={button} href="/login">
|
||||
Entrar para manifestar interesse
|
||||
</Link>
|
||||
)}
|
||||
{p.history.length > 0 && (
|
||||
<details>
|
||||
<summary>Histórico e decisões</summary>
|
||||
{p.history.map((h, i) => (
|
||||
<p key={i}>
|
||||
{h.occurred_at} · Autor {h.actor_id} ·{' '}
|
||||
{h.event_type}
|
||||
</p>
|
||||
))}
|
||||
</details>
|
||||
{(p.owner || p.moderator) && p.historySummary && (
|
||||
<PublicationSummary value={p.historySummary} />
|
||||
)}
|
||||
</div>
|
||||
</Frame>
|
||||
|
||||
@@ -1,55 +1,22 @@
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { Link, useForm } from '@inertiajs/react';
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
usePartnershipEdit,
|
||||
type PartnershipEditProps,
|
||||
} from '@/lib/partnership-edit';
|
||||
import PartnershipEditComparison from '@/components/partnership-edit-comparison';
|
||||
import {
|
||||
Frame,
|
||||
Field,
|
||||
Errors,
|
||||
control,
|
||||
button,
|
||||
type Partnership,
|
||||
type Catalogues,
|
||||
} from './shared';
|
||||
type Location = {
|
||||
geo_location_id: string;
|
||||
role: string;
|
||||
source_reference: string;
|
||||
};
|
||||
type Origin = { type: string; target_id: string };
|
||||
type Props = Catalogues & {
|
||||
record: Partnership | null;
|
||||
locations: Location[];
|
||||
origins: Origin[];
|
||||
};
|
||||
type Props = Catalogues & PartnershipEditProps;
|
||||
function Editor(p: Props) {
|
||||
const form = useForm({
|
||||
client_key: createOperationKey(),
|
||||
version: p.record?.version ?? null,
|
||||
title: p.record?.title ?? '',
|
||||
offer: p.record?.offer ?? '',
|
||||
seeking: p.record?.seeking ?? '',
|
||||
organization_id: p.record?.organization_id ?? '',
|
||||
sector_id: p.record?.sector_id?.toString() ?? '',
|
||||
kind: p.record?.kind ?? 'seeking',
|
||||
partnership_type: p.record?.partnership_type ?? '',
|
||||
deadline: p.record?.deadline ?? '',
|
||||
payload: {
|
||||
summary: p.record?.payload.summary ?? '',
|
||||
requirements: p.record?.payload.requirements ?? '',
|
||||
mandatory: p.record?.payload.mandatory ?? ([] as string[]),
|
||||
confidentiality: p.record?.payload.confidentiality ?? 'public',
|
||||
consent: p.record?.payload.consent ?? false,
|
||||
},
|
||||
locations: p.locations.map((x) => ({
|
||||
geo_location_id: x.geo_location_id,
|
||||
role: x.role,
|
||||
source_reference: x.source_reference,
|
||||
})),
|
||||
origins: p.origins.map((x) => ({
|
||||
type: x.type,
|
||||
target_id: x.target_id,
|
||||
})),
|
||||
});
|
||||
const edit = usePartnershipEdit(p);
|
||||
const form = edit.form;
|
||||
const [place, setPlace] = useState('');
|
||||
const [role, setRole] = useState('primary');
|
||||
const [source, setSource] = useState('Declaração do proponente');
|
||||
@@ -65,384 +32,493 @@ function Editor(p: Props) {
|
||||
className="space-y-5"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (p.record) form.put('/parcerias/' + p.record.id);
|
||||
else form.post('/parcerias/rascunhos');
|
||||
edit.save();
|
||||
}}
|
||||
>
|
||||
<Errors errors={form.errors} />
|
||||
<Field label="Título">
|
||||
<input
|
||||
className={control}
|
||||
value={form.data.title}
|
||||
onChange={(e) => form.setData('title', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<div className="grid gap-5 md:grid-cols-2">
|
||||
<Field label="Organização que representa (opcional)">
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.organization_id}
|
||||
onChange={(e) =>
|
||||
form.setData('organization_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Ideia pessoal — sem organização indicada
|
||||
</option>
|
||||
{p.organizations.map((x) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{x.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Oferta ou procura">
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.kind}
|
||||
onChange={(e) =>
|
||||
form.setData('kind', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="seeking">Procura</option>
|
||||
<option value="offering">Oferta</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Tipo de parceria">
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.partnership_type}
|
||||
onChange={(e) =>
|
||||
form.setData('partnership_type', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Por definir</option>
|
||||
{Object.entries(p.types).map(([k, v]) => (
|
||||
<option key={k} value={k}>
|
||||
{v}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Setor">
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.sector_id}
|
||||
onChange={(e) =>
|
||||
form.setData('sector_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Por definir</option>
|
||||
{p.sectors.map((x) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{x.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
</div>
|
||||
<Field label="Resumo público">
|
||||
<textarea
|
||||
className={control}
|
||||
value={form.data.payload.summary}
|
||||
onChange={(e) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
summary: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="O que oferece">
|
||||
<textarea
|
||||
className={control}
|
||||
value={form.data.offer}
|
||||
onChange={(e) => form.setData('offer', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="O que procura">
|
||||
<textarea
|
||||
className={control}
|
||||
value={form.data.seeking}
|
||||
onChange={(e) =>
|
||||
form.setData('seeking', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Requisitos e critérios desejáveis">
|
||||
<textarea
|
||||
className={control}
|
||||
value={form.data.payload.requirements}
|
||||
onChange={(e) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
requirements: e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<fieldset className="space-y-2 rounded border p-4">
|
||||
<legend>
|
||||
Critérios obrigatórios expressos da proposta
|
||||
</legend>
|
||||
<p>
|
||||
Marque apenas condições necessárias. Critérios
|
||||
desejáveis servem a pontuação. Informação desconhecida
|
||||
exige esclarecimento e não constitui incumprimento
|
||||
comprovado.
|
||||
</p>
|
||||
{Object.entries(p.criteria).map(([k, v]) => (
|
||||
<label className="block" key={k}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.payload.mandatory.includes(
|
||||
k,
|
||||
)}
|
||||
onChange={(e) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
mandatory: e.target.checked
|
||||
? [
|
||||
...form.data.payload
|
||||
.mandatory,
|
||||
k,
|
||||
]
|
||||
: form.data.payload.mandatory.filter(
|
||||
(x) => x !== k,
|
||||
),
|
||||
})
|
||||
}
|
||||
/>{' '}
|
||||
{v}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<Field label="Prazo para interesses">
|
||||
<PartnershipEditComparison editor={edit} catalogues={p} />
|
||||
<fieldset
|
||||
className="space-y-5"
|
||||
disabled={!edit.editable || edit.invalid}
|
||||
>
|
||||
<legend className="sr-only">Conteúdo da parceria</legend>
|
||||
<Field label="Título">
|
||||
<input
|
||||
type="date"
|
||||
className={control}
|
||||
value={form.data.deadline}
|
||||
value={form.data.title}
|
||||
onChange={(e) =>
|
||||
form.setData('deadline', e.target.value)
|
||||
edit.setData('title', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Visibilidade do conteúdo detalhado">
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.payload.confidentiality}
|
||||
onChange={(e) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
confidentiality: e.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="public">
|
||||
Público após moderação
|
||||
</option>
|
||||
<option value="private">
|
||||
Resumo público; detalhes privados
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
</div>
|
||||
<section className="space-y-4 rounded border p-5">
|
||||
<h2 className="font-bold">Localizações e abrangência</h2>
|
||||
<p>
|
||||
A localização de uma origem fica como contexto. Só
|
||||
acrescente uma localização própria com fonte; não se
|
||||
deduz por proximidade ou pertença a cluster.
|
||||
</p>
|
||||
<div className="grid gap-3 md:grid-cols-3">
|
||||
<Field label="Localização do cadastro">
|
||||
<div className="grid gap-5 md:grid-cols-2">
|
||||
<Field label="Organização que representa (opcional)">
|
||||
<select
|
||||
className={control}
|
||||
value={place}
|
||||
onChange={(e) => setPlace(e.target.value)}
|
||||
value={form.data.organization_id}
|
||||
onChange={(e) =>
|
||||
edit.setData(
|
||||
'organization_id',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Escolher território</option>
|
||||
{p.territories.map((x) => (
|
||||
<option value="">
|
||||
Sem organização indicada
|
||||
</option>
|
||||
{form.data.organization_id &&
|
||||
!p.organizations.some(
|
||||
(organization) =>
|
||||
String(organization.id) ===
|
||||
form.data.organization_id,
|
||||
) && (
|
||||
<option
|
||||
value={form.data.organization_id}
|
||||
>
|
||||
Organização anteriormente indicada —
|
||||
fora da lista actual
|
||||
</option>
|
||||
)}
|
||||
{p.organizations.map((x) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{x.name} · {x.location_type}
|
||||
{x.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<p className="text-sm">
|
||||
A autoria mantém-se. Sem organização ligada, só
|
||||
o proponente originalmente registado pode editar
|
||||
esta proposta.
|
||||
</p>
|
||||
</Field>
|
||||
<Field label="Oferta ou procura">
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.kind}
|
||||
onChange={(e) =>
|
||||
edit.setData('kind', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="seeking">Procura</option>
|
||||
<option value="offering">Oferta</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Tipo de parceria">
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.partnership_type}
|
||||
onChange={(e) =>
|
||||
edit.setData(
|
||||
'partnership_type',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Por definir</option>
|
||||
{form.data.partnership_type &&
|
||||
!Object.hasOwn(
|
||||
p.types,
|
||||
form.data.partnership_type,
|
||||
) && (
|
||||
<option
|
||||
value={form.data.partnership_type}
|
||||
>
|
||||
Tipo anteriormente indicado — fora
|
||||
da configuração actual
|
||||
</option>
|
||||
)}
|
||||
{Object.entries(p.types).map(([k, v]) => (
|
||||
<option key={k} value={k}>
|
||||
{v}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Papel">
|
||||
<Field label="Setor">
|
||||
<select
|
||||
className={control}
|
||||
value={role}
|
||||
onChange={(e) => setRole(e.target.value)}
|
||||
value={form.data.sector_id}
|
||||
onChange={(e) =>
|
||||
edit.setData('sector_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="primary">Principal</option>
|
||||
<option value="operating">
|
||||
Área de atuação
|
||||
</option>
|
||||
<option value="coverage">Abrangência</option>
|
||||
<option value="">Por definir</option>
|
||||
{form.data.sector_id &&
|
||||
!p.sectors.some(
|
||||
(sector) =>
|
||||
String(sector.id) ===
|
||||
form.data.sector_id,
|
||||
) && (
|
||||
<option value={form.data.sector_id}>
|
||||
Sector anteriormente indicado — fora
|
||||
da lista actual
|
||||
</option>
|
||||
)}
|
||||
{p.sectors.map((x) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{x.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Fonte da localização">
|
||||
</div>
|
||||
<Field label="Resumo público">
|
||||
<textarea
|
||||
className={control}
|
||||
value={form.data.payload.summary}
|
||||
onChange={(e) =>
|
||||
edit.setData('payload', (previous) => ({
|
||||
...previous,
|
||||
summary: e.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="O que oferece">
|
||||
<textarea
|
||||
className={control}
|
||||
value={form.data.offer}
|
||||
onChange={(e) =>
|
||||
edit.setData('offer', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="O que procura">
|
||||
<textarea
|
||||
className={control}
|
||||
value={form.data.seeking}
|
||||
onChange={(e) =>
|
||||
edit.setData('seeking', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Requisitos e critérios desejáveis">
|
||||
<textarea
|
||||
className={control}
|
||||
value={form.data.payload.requirements}
|
||||
onChange={(e) =>
|
||||
edit.setData('payload', (previous) => ({
|
||||
...previous,
|
||||
requirements: e.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Disponibilidade dos recursos ou da colaboração (opcional)">
|
||||
<textarea
|
||||
className={control}
|
||||
maxLength={1000}
|
||||
value={form.data.payload.availability}
|
||||
onChange={(event) =>
|
||||
edit.setData('payload', (previous) => ({
|
||||
...previous,
|
||||
availability: event.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
<p className="text-sm">
|
||||
Indique quando e em que condições os recursos ou a
|
||||
colaboração estarão disponíveis. O prazo de recepção
|
||||
de interesses é indicado separadamente.
|
||||
</p>
|
||||
</Field>
|
||||
<fieldset className="space-y-2 rounded border p-4">
|
||||
<legend>
|
||||
Critérios obrigatórios expressos da proposta
|
||||
</legend>
|
||||
<p>
|
||||
Marque apenas condições necessárias. Critérios
|
||||
desejáveis servem a pontuação. Informação
|
||||
desconhecida exige esclarecimento e não constitui
|
||||
incumprimento comprovado.
|
||||
</p>
|
||||
{Object.entries(p.criteria).map(([k, v]) => (
|
||||
<label className="block" key={k}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.payload.mandatory.includes(
|
||||
k,
|
||||
)}
|
||||
onChange={(e) =>
|
||||
edit.setData('payload', (previous) => ({
|
||||
...previous,
|
||||
mandatory: e.target.checked
|
||||
? [...previous.mandatory, k]
|
||||
: previous.mandatory.filter(
|
||||
(x) => x !== k,
|
||||
),
|
||||
}))
|
||||
}
|
||||
/>{' '}
|
||||
{v}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
{form.data.payload.mandatory
|
||||
.filter((code) => !Object.hasOwn(p.criteria, code))
|
||||
.map((code) => (
|
||||
<p className="rounded border p-3" key={code}>
|
||||
Critério anteriormente indicado — fora da
|
||||
configuração actual: {code}. Retirá-lo da
|
||||
preparação altera apenas a próxima gravação; o
|
||||
histórico mantém-se.{' '}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
disabled={!edit.editable || edit.invalid}
|
||||
onClick={() =>
|
||||
edit.setData('payload', (previous) => ({
|
||||
...previous,
|
||||
mandatory:
|
||||
previous.mandatory.filter(
|
||||
(value) => value !== code,
|
||||
),
|
||||
}))
|
||||
}
|
||||
>
|
||||
Retirar da preparação
|
||||
</button>
|
||||
</p>
|
||||
))}
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<Field label="Prazo para receber manifestações de interesse (opcional)">
|
||||
<input
|
||||
type="date"
|
||||
className={control}
|
||||
value={source}
|
||||
onChange={(e) => setSource(e.target.value)}
|
||||
value={form.data.deadline}
|
||||
onChange={(e) =>
|
||||
edit.setData('deadline', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={!place || !source}
|
||||
onClick={() => {
|
||||
if (
|
||||
!form.data.locations.some(
|
||||
(x) =>
|
||||
x.geo_location_id === place &&
|
||||
x.role === role,
|
||||
)
|
||||
)
|
||||
form.setData('locations', [
|
||||
...form.data.locations,
|
||||
{
|
||||
geo_location_id: place,
|
||||
role,
|
||||
source_reference: source,
|
||||
},
|
||||
]);
|
||||
}}
|
||||
>
|
||||
Acrescentar localização
|
||||
</button>
|
||||
{form.data.locations.map((l, i) => (
|
||||
<p key={i}>
|
||||
{
|
||||
p.territories.find(
|
||||
(t) => t.id === l.geo_location_id,
|
||||
)?.name
|
||||
}{' '}
|
||||
· {l.role} · {l.source_reference}{' '}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() =>
|
||||
form.setData(
|
||||
'locations',
|
||||
form.data.locations.filter(
|
||||
(_, j) => j !== i,
|
||||
),
|
||||
)
|
||||
<Field label="Visibilidade do conteúdo detalhado">
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.payload.confidentiality}
|
||||
onChange={(e) =>
|
||||
edit.setData('payload', (previous) => ({
|
||||
...previous,
|
||||
confidentiality: e.target.value,
|
||||
}))
|
||||
}
|
||||
>
|
||||
Remover
|
||||
</button>
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
<section className="space-y-3 rounded border p-5">
|
||||
<h2 className="font-bold">Registos de origem</h2>
|
||||
<Field label="Adicionar origem existente">
|
||||
<select
|
||||
className={control}
|
||||
value={origin}
|
||||
onChange={(e) => setOrigin(e.target.value)}
|
||||
>
|
||||
<option value="">
|
||||
Escolher empresa, investimento, projeto,
|
||||
cluster, zona ou ficha
|
||||
</option>
|
||||
{p.sources?.map((x) => (
|
||||
<option
|
||||
key={x.type + ':' + x.target_id}
|
||||
value={x.type + ':' + x.target_id}
|
||||
>
|
||||
{x.title}
|
||||
<option value="public">
|
||||
Público após moderação
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={!origin}
|
||||
onClick={() => {
|
||||
const [type, target_id] = origin.split(':');
|
||||
if (
|
||||
!form.data.origins.some(
|
||||
(x) =>
|
||||
x.type === type &&
|
||||
x.target_id === target_id,
|
||||
)
|
||||
)
|
||||
form.setData('origins', [
|
||||
...form.data.origins,
|
||||
{ type, target_id },
|
||||
]);
|
||||
}}
|
||||
>
|
||||
Ligar origem
|
||||
</button>
|
||||
{form.data.origins.map((o, i) => (
|
||||
<p key={i}>
|
||||
{p.sources?.find(
|
||||
(x) =>
|
||||
x.type === o.type &&
|
||||
x.target_id === o.target_id,
|
||||
)?.title ?? 'Origem documental ligada'}{' '}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() =>
|
||||
form.setData(
|
||||
'origins',
|
||||
form.data.origins.filter(
|
||||
(_, j) => j !== i,
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
Remover
|
||||
</button>
|
||||
<option value="private">
|
||||
Resumo público; detalhes privados
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
</div>
|
||||
<section className="space-y-4 rounded border p-5">
|
||||
<h2 className="font-bold">
|
||||
Localizações e abrangência
|
||||
</h2>
|
||||
<p>
|
||||
A localização de uma origem fica como contexto. Só
|
||||
acrescente uma localização própria com fonte; não se
|
||||
deduz por proximidade ou pertença a cluster.
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.payload.consent}
|
||||
onChange={(e) =>
|
||||
form.setData('payload', {
|
||||
...form.data.payload,
|
||||
consent: e.target.checked,
|
||||
})
|
||||
}
|
||||
/>{' '}
|
||||
Autorizo submeter o conteúdo indicado para divulgação no
|
||||
âmbito escolhido. Não confirma verificação ou certificação.
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-4">
|
||||
<button className={button} disabled={form.processing}>
|
||||
Guardar rascunho
|
||||
</button>
|
||||
{p.record && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={'/parcerias/' + p.record.id}
|
||||
<div className="grid gap-3 md:grid-cols-3">
|
||||
<Field label="Localização do cadastro">
|
||||
<select
|
||||
className={control}
|
||||
value={place}
|
||||
onChange={(e) => setPlace(e.target.value)}
|
||||
>
|
||||
<option value="">
|
||||
Escolher território
|
||||
</option>
|
||||
{p.territories.map((x) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{x.name} · {x.location_type}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Papel">
|
||||
<select
|
||||
className={control}
|
||||
value={role}
|
||||
onChange={(e) => setRole(e.target.value)}
|
||||
>
|
||||
<option value="primary">Principal</option>
|
||||
<option value="operating">
|
||||
Área de atuação
|
||||
</option>
|
||||
<option value="coverage">
|
||||
Abrangência
|
||||
</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Fonte da localização">
|
||||
<input
|
||||
className={control}
|
||||
value={source}
|
||||
onChange={(e) => setSource(e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={!place || !source}
|
||||
onClick={() => {
|
||||
edit.setData('locations', (previous) =>
|
||||
previous.some(
|
||||
(x) =>
|
||||
x.geo_location_id === place &&
|
||||
x.role === role,
|
||||
)
|
||||
? previous
|
||||
: [
|
||||
...previous,
|
||||
{
|
||||
geo_location_id: place,
|
||||
role,
|
||||
source_reference: source,
|
||||
},
|
||||
],
|
||||
);
|
||||
}}
|
||||
>
|
||||
Pré-visualizar e submeter
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
Acrescentar localização
|
||||
</button>
|
||||
{form.data.locations.map((l, i) => (
|
||||
<p key={i}>
|
||||
{
|
||||
p.territories.find(
|
||||
(t) => t.id === l.geo_location_id,
|
||||
)?.name
|
||||
}{' '}
|
||||
· {l.role} · {l.source_reference}{' '}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() =>
|
||||
edit.setData('locations', (previous) =>
|
||||
previous.filter(
|
||||
(item) =>
|
||||
item.geo_location_id !==
|
||||
l.geo_location_id ||
|
||||
item.role !== l.role,
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
Remover
|
||||
</button>
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
<section className="space-y-3 rounded border p-5">
|
||||
<h2 className="font-bold">Registos de origem</h2>
|
||||
<Field label="Adicionar origem existente">
|
||||
<select
|
||||
className={control}
|
||||
value={origin}
|
||||
onChange={(e) => setOrigin(e.target.value)}
|
||||
>
|
||||
<option value="">
|
||||
Escolher empresa, investimento, projeto,
|
||||
cluster, zona ou ficha
|
||||
</option>
|
||||
{p.sources?.map((x) => (
|
||||
<option
|
||||
key={x.type + ':' + x.target_id}
|
||||
value={x.type + ':' + x.target_id}
|
||||
>
|
||||
{x.title}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={!origin}
|
||||
onClick={() => {
|
||||
const [type, target_id] = origin.split(':');
|
||||
edit.setData('origins', (previous) =>
|
||||
previous.some(
|
||||
(item) =>
|
||||
item.type === type &&
|
||||
item.target_id === target_id,
|
||||
)
|
||||
? previous
|
||||
: [...previous, { type, target_id }],
|
||||
);
|
||||
}}
|
||||
>
|
||||
Ligar origem
|
||||
</button>
|
||||
{form.data.origins.map((o, i) => (
|
||||
<p key={i}>
|
||||
{p.sources?.find(
|
||||
(x) =>
|
||||
x.type === o.type &&
|
||||
x.target_id === o.target_id,
|
||||
)?.title ?? 'Origem documental ligada'}{' '}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() =>
|
||||
edit.setData('origins', (previous) =>
|
||||
previous.filter(
|
||||
(item) =>
|
||||
item.type !== o.type ||
|
||||
item.target_id !==
|
||||
o.target_id,
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
Remover
|
||||
</button>
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.data.payload.consent}
|
||||
onChange={(e) =>
|
||||
edit.setData('payload', (previous) => ({
|
||||
...previous,
|
||||
consent: e.target.checked,
|
||||
}))
|
||||
}
|
||||
/>{' '}
|
||||
Autorizo submeter o conteúdo indicado para divulgação no
|
||||
âmbito escolhido. Não confirma verificação ou
|
||||
certificação.
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-4">
|
||||
<button
|
||||
className={button}
|
||||
disabled={form.processing || edit.blocked}
|
||||
>
|
||||
{edit.retryingCreation
|
||||
? 'Recuperar gravação anterior'
|
||||
: edit.current?.status === 'published'
|
||||
? 'Guardar revisão em rascunho'
|
||||
: 'Guardar rascunho'}
|
||||
</button>
|
||||
{p.record && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={'/parcerias/' + p.record.id}
|
||||
>
|
||||
Pré-visualizar e submeter
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</fieldset>
|
||||
</form>
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
export default function Page(p: Props) {
|
||||
return (
|
||||
<Editor
|
||||
key={`${p.record?.id ?? 'new'}:${p.record?.version ?? 0}`}
|
||||
{...p}
|
||||
/>
|
||||
);
|
||||
return <Editor key={p.editorActorId ?? 'legacy-editor'} {...p} />;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,350 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { Frame, labels } from './shared';
|
||||
|
||||
type Assessment = {
|
||||
code: string;
|
||||
label: string;
|
||||
state: string | null;
|
||||
evidence: string | null;
|
||||
actor_name: string | null;
|
||||
assessed_at: string | null;
|
||||
};
|
||||
type Snapshot = {
|
||||
availability: 'available' | 'not_recorded' | 'scope_unknown' | 'restricted';
|
||||
version?: number | null;
|
||||
status?: string | null;
|
||||
scope_known?: boolean;
|
||||
organization_id?: string | null;
|
||||
organization_name?: string | null;
|
||||
fields?: Record<string, string | null>;
|
||||
consent_known?: boolean;
|
||||
consent?: boolean | null;
|
||||
assessment_recorded?: boolean;
|
||||
assessment?: Assessment[];
|
||||
references?: Record<string, string>;
|
||||
complete?: boolean;
|
||||
};
|
||||
type Matching = {
|
||||
algorithm_version: string | null;
|
||||
weights_hash: string | null;
|
||||
eligibility: string | null;
|
||||
score_min: number | null;
|
||||
score_max: number | null;
|
||||
unknown_weight: number | null;
|
||||
criteria: {
|
||||
code: string;
|
||||
label: string | null;
|
||||
state: string | null;
|
||||
weight: number | null;
|
||||
mandatory: boolean | null;
|
||||
evidence: string | null;
|
||||
explanation: string | null;
|
||||
}[];
|
||||
};
|
||||
type Entry = {
|
||||
version: number | null;
|
||||
restricted: boolean;
|
||||
action: string | null;
|
||||
actor_name: string | null;
|
||||
occurred_at: string | null;
|
||||
reason: string | null;
|
||||
previous: Snapshot;
|
||||
after: Snapshot;
|
||||
matching: Matching | null;
|
||||
partnership_version: number | null;
|
||||
};
|
||||
type Props = {
|
||||
candidacy_id: number;
|
||||
entries: Entry[];
|
||||
next_url: string | null;
|
||||
first_url: string;
|
||||
older_page: boolean;
|
||||
partnership_href: string | null;
|
||||
dashboard_href: string;
|
||||
};
|
||||
const actions: Record<string, string> = {
|
||||
submit: 'Submissão',
|
||||
assess: 'Avaliação',
|
||||
clarify: 'Pedido de esclarecimento',
|
||||
shortlist: 'Selecção para lista curta',
|
||||
reject: 'Rejeição',
|
||||
connect: 'Abertura de negociação',
|
||||
withdraw: 'Retirada',
|
||||
};
|
||||
const fields: Record<string, string> = {
|
||||
proposal: 'Proposta curta',
|
||||
capacity: 'Capacidade disponível',
|
||||
availability: 'Disponibilidade',
|
||||
contribution: 'Contribuição proposta',
|
||||
conflicts: 'Conflitos de interesse declarados',
|
||||
decision_reason: 'Motivo da decisão',
|
||||
};
|
||||
const display = (value: string | null | undefined) =>
|
||||
value ? (labels[value] ?? value) : 'Não consta do registo';
|
||||
function Version({ value, title }: { value: Snapshot; title: string }) {
|
||||
const unavailable = {
|
||||
not_recorded: 'Esta versão não foi guardada no evento.',
|
||||
scope_unknown:
|
||||
'O âmbito desta versão antiga não ficou identificado; o seu conteúdo não está disponível para esta conta.',
|
||||
restricted:
|
||||
'Esta versão pertence a uma representação à qual esta conta não tem acesso actual.',
|
||||
};
|
||||
return (
|
||||
<section className="min-w-0 space-y-3 rounded border p-4">
|
||||
<h3 className="font-bold">{title}</h3>
|
||||
{value.availability !== 'available' ? (
|
||||
<p>{unavailable[value.availability]}</p>
|
||||
) : (
|
||||
<>
|
||||
{!value.complete && (
|
||||
<p>
|
||||
Registo parcial. Os campos em falta não foram
|
||||
completados com dados actuais.
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
Versão: {value.version ?? 'Não consta do registo'} ·
|
||||
Estado: {display(value.status)}
|
||||
</p>
|
||||
<p>
|
||||
Participação:{' '}
|
||||
{!value.scope_known
|
||||
? 'Âmbito não registado'
|
||||
: value.organization_id
|
||||
? (value.organization_name ??
|
||||
`Organização ${value.organization_id}`)
|
||||
: 'Em nome pessoal'}
|
||||
</p>
|
||||
<dl className="space-y-2">
|
||||
{Object.entries(fields).map(([key, label]) => (
|
||||
<div key={key}>
|
||||
<dt className="font-semibold">{label}</dt>
|
||||
<dd className="break-words whitespace-pre-wrap">
|
||||
{Object.hasOwn(value.fields ?? {}, key)
|
||||
? value.fields?.[key] || 'Não indicado'
|
||||
: 'Não consta do registo'}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Autorização de partilha
|
||||
</dt>
|
||||
<dd>
|
||||
{value.consent_known
|
||||
? value.consent
|
||||
? 'Autorizada'
|
||||
: 'Não autorizada'
|
||||
: 'Não consta do registo'}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<h4 className="font-semibold">Avaliação guardada</h4>
|
||||
{!value.assessment_recorded ? (
|
||||
<p>Não consta do registo.</p>
|
||||
) : !value.assessment?.length ? (
|
||||
<p>Sem critérios avaliados nesta versão.</p>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-sm">
|
||||
Os nomes dos critérios abaixo provêm do catálogo
|
||||
actual; os estados e evidências são os que
|
||||
ficaram guardados.
|
||||
</p>
|
||||
<ul className="space-y-3">
|
||||
{value.assessment.map((item, index) => (
|
||||
<li key={`${item.code}:${index}`}>
|
||||
<p>
|
||||
{item.label} · {display(item.state)}
|
||||
</p>
|
||||
<p className="whitespace-pre-wrap">
|
||||
Evidência:{' '}
|
||||
{item.evidence ||
|
||||
'Não consta do registo'}
|
||||
</p>
|
||||
<p>
|
||||
{item.actor_name ||
|
||||
'Autor não registado'}{' '}
|
||||
·{' '}
|
||||
{item.assessed_at ||
|
||||
'Data não registada'}
|
||||
</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
{Object.keys(value.references ?? {}).length > 0 && (
|
||||
<details>
|
||||
<summary>Referências guardadas</summary>
|
||||
<dl>
|
||||
{Object.entries(value.references ?? {}).map(
|
||||
([key, id]) => (
|
||||
<div key={key}>
|
||||
<dt>
|
||||
{key === 'sector_id'
|
||||
? 'Sector'
|
||||
: 'Localização'}{' '}
|
||||
· referência
|
||||
</dt>
|
||||
<dd className="break-all">{id}</dd>
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
</dl>
|
||||
</details>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
function FrozenMatching({ value }: { value: Matching | null }) {
|
||||
if (!value)
|
||||
return (
|
||||
<p>
|
||||
O contexto de correspondência não ficou guardado ou não está
|
||||
disponível neste âmbito. Não foi recalculado.
|
||||
</p>
|
||||
);
|
||||
return (
|
||||
<section className="space-y-3 rounded border p-4">
|
||||
<h3 className="font-bold">Correspondência guardada na decisão</h3>
|
||||
<p>
|
||||
Intervalo:{' '}
|
||||
{value.score_min === null || value.score_max === null
|
||||
? 'Por determinar'
|
||||
: `${value.score_min}–${value.score_max}%`}{' '}
|
||||
· Elegibilidade: {display(value.eligibility)}. Este registo não
|
||||
constitui aprovação.
|
||||
</p>
|
||||
<p>
|
||||
São apresentados os parâmetros guardados, sem aplicar os
|
||||
critérios actuais.
|
||||
</p>
|
||||
<ul className="space-y-3">
|
||||
{value.criteria.map((item, index) => (
|
||||
<li key={`${item.code}:${index}`}>
|
||||
<p>
|
||||
{item.label ?? item.code} · Peso:{' '}
|
||||
{item.weight ?? 'Por determinar'} ·{' '}
|
||||
{display(item.state)} ·{' '}
|
||||
{item.mandatory === null
|
||||
? 'Obrigatoriedade não registada'
|
||||
: item.mandatory
|
||||
? 'Obrigatório'
|
||||
: 'Não obrigatório'}
|
||||
</p>
|
||||
<p className="whitespace-pre-wrap">
|
||||
Evidência:{' '}
|
||||
{item.evidence || 'Não consta do registo'}
|
||||
</p>
|
||||
<p>{item.explanation || 'Explicação não registada'}</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<details>
|
||||
<summary>Parâmetros do cálculo guardado</summary>
|
||||
<p>
|
||||
Algoritmo:{' '}
|
||||
{value.algorithm_version ?? 'Não consta do registo'}
|
||||
</p>
|
||||
<p className="break-all">
|
||||
Referência dos pesos:{' '}
|
||||
{value.weights_hash ?? 'Não consta do registo'}
|
||||
</p>
|
||||
<p>
|
||||
Peso desconhecido:{' '}
|
||||
{value.unknown_weight ?? 'Por determinar'}
|
||||
</p>
|
||||
</details>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
export default function InterestHistory(p: Props) {
|
||||
return (
|
||||
<Frame title={`Versões e decisões · Candidatura ${p.candidacy_id}`}>
|
||||
<div className="space-y-6 break-words">
|
||||
<nav
|
||||
aria-label="Navegação do histórico"
|
||||
className="flex flex-wrap gap-4"
|
||||
>
|
||||
<Link className="underline" href={p.dashboard_href}>
|
||||
Painel de parcerias
|
||||
</Link>
|
||||
{p.partnership_href && (
|
||||
<Link className="underline" href={p.partnership_href}>
|
||||
Consultar parceria
|
||||
</Link>
|
||||
)}
|
||||
{p.older_page && (
|
||||
<Link className="underline" href={p.first_url}>
|
||||
Versões mais recentes
|
||||
</Link>
|
||||
)}
|
||||
</nav>
|
||||
<p>
|
||||
Consulta dos valores guardados em cada alteração, do mais
|
||||
recente para o mais antigo. Os nomes de pessoas e
|
||||
organizações são os disponíveis no cadastro actual para as
|
||||
referências guardadas.
|
||||
</p>
|
||||
{!p.entries.length && (
|
||||
<p>Ainda não existem versões guardadas para apresentar.</p>
|
||||
)}
|
||||
{p.entries.map((entry, index) => (
|
||||
<details
|
||||
className="space-y-4 rounded border p-4"
|
||||
key={index}
|
||||
open={index === 0}
|
||||
>
|
||||
<summary className="cursor-pointer font-bold">
|
||||
Versão {entry.version ?? 'não registada'} ·{' '}
|
||||
{entry.restricted
|
||||
? 'Conteúdo reservado'
|
||||
: (actions[entry.action ?? ''] ??
|
||||
'Alteração registada')}
|
||||
</summary>
|
||||
{!entry.restricted && (
|
||||
<>
|
||||
<p>
|
||||
{entry.actor_name ?? 'Autor não registado'}{' '}
|
||||
·{' '}
|
||||
{entry.occurred_at ?? 'Data não registada'}
|
||||
</p>
|
||||
<p>
|
||||
Versão da parceria:{' '}
|
||||
{entry.partnership_version ??
|
||||
'Não consta do registo'}
|
||||
</p>
|
||||
{entry.reason && (
|
||||
<p className="whitespace-pre-wrap">
|
||||
Motivo: {entry.reason}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
<Version
|
||||
title="Antes da alteração"
|
||||
value={entry.previous}
|
||||
/>
|
||||
<Version
|
||||
title="Após a alteração"
|
||||
value={entry.after}
|
||||
/>
|
||||
</div>
|
||||
{!entry.restricted && (
|
||||
<FrozenMatching value={entry.matching} />
|
||||
)}
|
||||
</details>
|
||||
))}
|
||||
{p.next_url && (
|
||||
<Link className="inline-block underline" href={p.next_url}>
|
||||
Consultar versões anteriores
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { publicationHistoryActions as actions } from '@/lib/partnership-history';
|
||||
import { Frame, labels } from './shared';
|
||||
|
||||
type Snapshot = {
|
||||
availability: 'available' | 'not_recorded' | 'scope_unknown' | 'restricted';
|
||||
version?: number | null;
|
||||
status?: string | null;
|
||||
scope_known?: boolean;
|
||||
organization_id?: string | null;
|
||||
organization_name?: string | null;
|
||||
fields?: Record<string, string | null>;
|
||||
sector_recorded?: boolean;
|
||||
sector_id?: string | null;
|
||||
consent_known?: boolean;
|
||||
consent?: boolean | null;
|
||||
mandatory_known?: boolean;
|
||||
mandatory?: string[];
|
||||
origins_recorded?: boolean;
|
||||
origins_incomplete?: boolean;
|
||||
origins?: { type: string; target_id: string }[];
|
||||
locations_recorded?: boolean;
|
||||
locations_incomplete?: boolean;
|
||||
locations?: {
|
||||
geo_location_id: string;
|
||||
role: string | null;
|
||||
source_reference: string | null;
|
||||
}[];
|
||||
complete?: boolean;
|
||||
};
|
||||
type Entry = {
|
||||
version: number | null;
|
||||
restricted: boolean;
|
||||
action: string | null;
|
||||
actor_name: string | null;
|
||||
occurred_at: string | null;
|
||||
reason: string | null;
|
||||
previous: Snapshot;
|
||||
after: Snapshot;
|
||||
};
|
||||
type Props = {
|
||||
partnership_id: number;
|
||||
entries: Entry[];
|
||||
first_url: string;
|
||||
next_url: string | null;
|
||||
older_page: boolean;
|
||||
partnership_href: string;
|
||||
dashboard_href: string;
|
||||
};
|
||||
const fields: Record<string, string> = {
|
||||
title: 'Título',
|
||||
kind: 'Oferta ou procura',
|
||||
partnership_type: 'Tipo de parceria',
|
||||
summary: 'Resumo público',
|
||||
offer: 'O que oferece',
|
||||
seeking: 'O que procura',
|
||||
requirements: 'Requisitos',
|
||||
availability: 'Disponibilidade',
|
||||
confidentiality: 'Partilha dos detalhes',
|
||||
deadline: 'Prazo',
|
||||
published_at: 'Data de publicação guardada',
|
||||
};
|
||||
function display(key: string, value: string | null | undefined) {
|
||||
if (!value) return 'Não indicado';
|
||||
if (key === 'kind')
|
||||
return value === 'offering'
|
||||
? 'Oferta'
|
||||
: value === 'seeking'
|
||||
? 'Procura'
|
||||
: value;
|
||||
if (key === 'confidentiality')
|
||||
return value === 'private'
|
||||
? 'Detalhes reservados à conexão privada'
|
||||
: value === 'public'
|
||||
? 'Pública'
|
||||
: value;
|
||||
return value;
|
||||
}
|
||||
function Version({ value, title }: { value: Snapshot; title: string }) {
|
||||
const unavailable = {
|
||||
not_recorded: 'Esta versão não foi guardada no evento.',
|
||||
scope_unknown:
|
||||
'O âmbito ou a identidade desta versão antiga não está suficientemente identificado para a apresentar nesta consulta.',
|
||||
restricted:
|
||||
'Esta versão pertence a uma representação à qual a conta não tem acesso actual.',
|
||||
};
|
||||
return (
|
||||
<section className="min-w-0 space-y-3 rounded border p-4">
|
||||
<h3 className="font-bold">{title}</h3>
|
||||
{value.availability !== 'available' ? (
|
||||
<p>{unavailable[value.availability]}</p>
|
||||
) : (
|
||||
<>
|
||||
{!value.complete && (
|
||||
<p>
|
||||
Registo parcial. Os campos em falta não foram
|
||||
preenchidos com dados actuais.
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
Versão: {value.version ?? 'Não consta do registo'} ·
|
||||
Estado:{' '}
|
||||
{value.status
|
||||
? (labels[value.status] ?? value.status)
|
||||
: 'Não consta do registo'}
|
||||
</p>
|
||||
<p>
|
||||
Participação:{' '}
|
||||
{!value.scope_known
|
||||
? 'Âmbito não registado'
|
||||
: value.organization_id
|
||||
? (value.organization_name ??
|
||||
`Organização ${value.organization_id}`)
|
||||
: 'Em nome pessoal'}
|
||||
</p>
|
||||
<dl className="space-y-3">
|
||||
{Object.entries(fields).map(([key, label]) => (
|
||||
<div key={key}>
|
||||
<dt className="font-semibold">{label}</dt>
|
||||
<dd className="break-words whitespace-pre-wrap">
|
||||
{Object.hasOwn(value.fields ?? {}, key)
|
||||
? display(key, value.fields?.[key])
|
||||
: 'Não consta do registo'}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Autorização de partilha
|
||||
</dt>
|
||||
<dd>
|
||||
{value.consent_known
|
||||
? value.consent
|
||||
? 'Autorizada'
|
||||
: 'Não autorizada'
|
||||
: 'Não consta do registo'}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Critérios obrigatórios · códigos guardados
|
||||
</dt>
|
||||
<dd>
|
||||
{!value.mandatory_known
|
||||
? 'Não consta do registo'
|
||||
: value.mandatory?.length
|
||||
? value.mandatory.join(', ')
|
||||
: 'Sem critérios obrigatórios nesta versão'}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Referência do sector
|
||||
</dt>
|
||||
<dd>
|
||||
{value.sector_recorded
|
||||
? (value.sector_id ??
|
||||
'Sem classificação indicada')
|
||||
: 'Não consta do registo'}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<details>
|
||||
<summary>
|
||||
Referências da origem e localização guardadas
|
||||
</summary>
|
||||
<div className="mt-3 space-y-3">
|
||||
<p>
|
||||
As referências identificam as ligações guardadas
|
||||
nesta versão. Consultar os dados das fontes
|
||||
continua sujeito às suas permissões actuais.
|
||||
</p>
|
||||
<h4 className="font-semibold">Origens</h4>
|
||||
{!value.origins_recorded ? (
|
||||
<p>Não constam do registo.</p>
|
||||
) : (
|
||||
<>
|
||||
{value.origins_incomplete && (
|
||||
<p>
|
||||
Há referências incompletas que não
|
||||
podem ser apresentadas
|
||||
integralmente.
|
||||
</p>
|
||||
)}
|
||||
{!value.origins?.length &&
|
||||
!value.origins_incomplete ? (
|
||||
<p>Sem origens ligadas nesta versão.</p>
|
||||
) : (
|
||||
<ul>
|
||||
{value.origins?.map(
|
||||
(origin, index) => (
|
||||
<li
|
||||
className="break-all"
|
||||
key={index}
|
||||
>
|
||||
{origin.type} ·{' '}
|
||||
{origin.target_id}
|
||||
</li>
|
||||
),
|
||||
)}
|
||||
</ul>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<h4 className="font-semibold">Localizações</h4>
|
||||
{!value.locations_recorded ? (
|
||||
<p>Não constam do registo.</p>
|
||||
) : (
|
||||
<>
|
||||
{value.locations_incomplete && (
|
||||
<p>
|
||||
Há localizações incompletas que não
|
||||
podem ser apresentadas
|
||||
integralmente.
|
||||
</p>
|
||||
)}
|
||||
{!value.locations?.length &&
|
||||
!value.locations_incomplete ? (
|
||||
<p>
|
||||
Sem localizações ligadas nesta
|
||||
versão.
|
||||
</p>
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{value.locations?.map(
|
||||
(location, index) => (
|
||||
<li
|
||||
className="break-words"
|
||||
key={index}
|
||||
>
|
||||
<p>
|
||||
Referência:{' '}
|
||||
{
|
||||
location.geo_location_id
|
||||
}{' '}
|
||||
·{' '}
|
||||
{location.role
|
||||
? ({
|
||||
primary:
|
||||
'Principal',
|
||||
operating:
|
||||
'Área de actuação',
|
||||
coverage:
|
||||
'Abrangência',
|
||||
}[
|
||||
location
|
||||
.role
|
||||
] ??
|
||||
location.role)
|
||||
: 'Papel não registado'}
|
||||
</p>
|
||||
<p className="whitespace-pre-wrap">
|
||||
Fonte declarada:{' '}
|
||||
{location.source_reference ||
|
||||
'Não consta do registo'}
|
||||
</p>
|
||||
</li>
|
||||
),
|
||||
)}
|
||||
</ul>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</details>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
export default function PublicationHistory(p: Props) {
|
||||
return (
|
||||
<Frame
|
||||
title={`Versões e decisões da publicação · Parceria ${p.partnership_id}`}
|
||||
>
|
||||
<div className="space-y-6 break-words">
|
||||
<nav
|
||||
className="flex flex-wrap gap-4"
|
||||
aria-label="Navegação do histórico"
|
||||
>
|
||||
<Link className="underline" href={p.dashboard_href}>
|
||||
Painel de parcerias
|
||||
</Link>
|
||||
<Link className="underline" href={p.partnership_href}>
|
||||
Consultar parceria
|
||||
</Link>
|
||||
{p.older_page && (
|
||||
<Link className="underline" href={p.first_url}>
|
||||
Versões mais recentes
|
||||
</Link>
|
||||
)}
|
||||
</nav>
|
||||
<p>
|
||||
São apresentados os valores guardados, do mais recente para
|
||||
o mais antigo. Os nomes de pessoas e organizações provêm do
|
||||
cadastro actual das referências identificadas. Este
|
||||
histórico não restaura nem volta a publicar versões.
|
||||
</p>
|
||||
{!p.entries.length && (
|
||||
<p>Não existem versões guardadas para apresentar.</p>
|
||||
)}
|
||||
{p.entries.map((entry, index) => (
|
||||
<details
|
||||
className="space-y-4 rounded border p-4"
|
||||
key={index}
|
||||
open={index === 0}
|
||||
>
|
||||
<summary className="cursor-pointer font-bold">
|
||||
Versão {entry.version ?? 'não registada'} ·{' '}
|
||||
{entry.restricted
|
||||
? 'Conteúdo reservado'
|
||||
: (actions[entry.action ?? ''] ??
|
||||
'Alteração registada')}
|
||||
</summary>
|
||||
{!entry.restricted && (
|
||||
<>
|
||||
<p>
|
||||
{entry.actor_name ?? 'Autor não registado'}{' '}
|
||||
·{' '}
|
||||
{entry.occurred_at ?? 'Data não registada'}
|
||||
</p>
|
||||
{entry.reason !== null && (
|
||||
<p className="whitespace-pre-wrap">
|
||||
Motivo: {entry.reason}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
<Version
|
||||
title="Antes da alteração"
|
||||
value={entry.previous}
|
||||
/>
|
||||
<Version
|
||||
title="Após a alteração"
|
||||
value={entry.after}
|
||||
/>
|
||||
</div>
|
||||
</details>
|
||||
))}
|
||||
{p.next_url && (
|
||||
<Link className="inline-block underline" href={p.next_url}>
|
||||
Consultar versões anteriores
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,10 @@
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { useForm, usePage, Link, router } from '@inertiajs/react';
|
||||
import { usePage, Link, router } from '@inertiajs/react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useRoomEdit, useRoomLeaveGuard } from '@/lib/partnership-room-edit';
|
||||
import RoomComparison from '@/components/partnership-room-comparison';
|
||||
import { useRoomDelivery } from '@/lib/partnership-room-delivery';
|
||||
import { readAgreement } from '@/lib/partnership-agreement';
|
||||
import AgreementInstrument from '@/components/partnership-agreement-instrument';
|
||||
import {
|
||||
Frame,
|
||||
Field,
|
||||
@@ -13,31 +18,44 @@ type Room = {
|
||||
id: number;
|
||||
status: string;
|
||||
version: number;
|
||||
agreement: {
|
||||
title: string;
|
||||
terms: string;
|
||||
confirmations: Record<string, { actor_id: number; date: string }>;
|
||||
legal_signature_status: string;
|
||||
} | null;
|
||||
agreement: unknown;
|
||||
};
|
||||
type Milestone = {
|
||||
id: number;
|
||||
title: string;
|
||||
responsible_id: number;
|
||||
responsible_name: string | null;
|
||||
responsible_is_participant: boolean;
|
||||
due_date: string | null;
|
||||
status: string;
|
||||
evidence: string | null;
|
||||
version: number;
|
||||
client_key?: string | null;
|
||||
};
|
||||
type Props = {
|
||||
agreementActorId: number;
|
||||
agreementParty: 'proponent' | 'candidate' | null;
|
||||
agreementCommands: {
|
||||
key: string;
|
||||
action: string;
|
||||
version: number;
|
||||
status: string;
|
||||
party: string | null;
|
||||
}[];
|
||||
room: Room;
|
||||
partnership: Partnership & { user_id: number };
|
||||
interest: { id: number; user_id: number };
|
||||
interest: { id: number; user_id: number; version: number };
|
||||
canWrite: boolean;
|
||||
participants: {
|
||||
id: number;
|
||||
name: string;
|
||||
parties: ('proponent' | 'candidate')[];
|
||||
}[];
|
||||
messages: {
|
||||
id: number;
|
||||
name: string;
|
||||
author_id: number;
|
||||
client_key?: string | null;
|
||||
body: string;
|
||||
created_at: string;
|
||||
}[];
|
||||
@@ -48,119 +66,267 @@ type Props = {
|
||||
shared: boolean;
|
||||
status: string;
|
||||
malware_scan_status: string;
|
||||
document_id: string;
|
||||
}[];
|
||||
milestones: Milestone[];
|
||||
};
|
||||
function MilestoneForm({ p, item }: { p: Props; item?: Milestone }) {
|
||||
const form = useForm({
|
||||
title: item?.title ?? '',
|
||||
responsible_id: item?.responsible_id ?? p.partnership.user_id,
|
||||
due_date: item?.due_date ?? '',
|
||||
status: item?.status ?? 'pending',
|
||||
evidence: item?.evidence ?? '',
|
||||
version: item?.version ?? null,
|
||||
function MilestoneForm({
|
||||
p,
|
||||
item,
|
||||
onDirty,
|
||||
}: {
|
||||
p: Props;
|
||||
item?: Milestone;
|
||||
onDirty?: (id: string, dirty: boolean) => void;
|
||||
}) {
|
||||
const editor = useRoomEdit({
|
||||
props: p,
|
||||
roomId: p.room.id,
|
||||
kind: 'milestone',
|
||||
itemId: item?.id ?? null,
|
||||
});
|
||||
const form = editor.form;
|
||||
const draftId = 'milestone:' + (item?.id ?? 'new');
|
||||
useEffect(() => {
|
||||
onDirty?.(draftId, editor.dirty);
|
||||
}, [onDirty, draftId, editor.dirty]);
|
||||
useEffect(() => () => onDirty?.(draftId, false), [onDirty, draftId]);
|
||||
if (!editor.editable && !editor.dirty && !editor.problem) return null;
|
||||
const currentResponsible = p.participants.some(
|
||||
(participant) =>
|
||||
String(participant.id) === editor.values.responsible_id,
|
||||
);
|
||||
return (
|
||||
<form
|
||||
data-room-form={draftId}
|
||||
className="space-y-3 rounded border p-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (item)
|
||||
form.put(
|
||||
`/parcerias/salas/${p.room.id}/marcos/${item.id}`,
|
||||
{ preserveScroll: true },
|
||||
);
|
||||
else
|
||||
form.post(`/parcerias/salas/${p.room.id}/marcos`, {
|
||||
preserveScroll: true,
|
||||
});
|
||||
if (
|
||||
form.processing ||
|
||||
(!currentResponsible && !editor.recovering)
|
||||
)
|
||||
return;
|
||||
editor.submit();
|
||||
}}
|
||||
>
|
||||
<h3 className="font-bold">
|
||||
{item ? 'Atualizar marco' : 'Acrescentar marco'}
|
||||
</h3>
|
||||
<Field label="Entregável">
|
||||
<input
|
||||
className={control}
|
||||
value={form.data.title}
|
||||
onChange={(e) => form.setData('title', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Responsável">
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.responsible_id}
|
||||
onChange={(e) =>
|
||||
form.setData('responsible_id', Number(e.target.value))
|
||||
}
|
||||
>
|
||||
<option value={p.partnership.user_id}>Proponente</option>
|
||||
<option value={p.interest.user_id}>Candidato</option>
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Data prevista">
|
||||
<input
|
||||
className={control}
|
||||
type="date"
|
||||
value={form.data.due_date}
|
||||
onChange={(e) => form.setData('due_date', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Estado">
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.status}
|
||||
onChange={(e) => form.setData('status', e.target.value)}
|
||||
>
|
||||
{['pending', 'progress', 'completed'].map((x) => (
|
||||
<option key={x} value={x}>
|
||||
{x === 'pending' ? 'Pendente' : labels[x]}
|
||||
<RoomComparison
|
||||
editor={editor}
|
||||
labels={{
|
||||
title: 'Entregável',
|
||||
responsible_id: 'Responsável pelo marco',
|
||||
due_date: 'Data prevista',
|
||||
status: 'Estado',
|
||||
evidence: 'Evidência ou referência do resultado',
|
||||
}}
|
||||
display={(key, value) =>
|
||||
key === 'responsible_id'
|
||||
? (p.participants.find(
|
||||
(person) => String(person.id) === value,
|
||||
)?.name ??
|
||||
(String(item?.responsible_id) === value
|
||||
? item?.responsible_name
|
||||
: null) ??
|
||||
'Participante já indisponível')
|
||||
: key === 'status'
|
||||
? value === 'pending'
|
||||
? 'Pendente'
|
||||
: (labels[value] ?? value)
|
||||
: value || 'Não indicado'
|
||||
}
|
||||
/>
|
||||
<fieldset
|
||||
disabled={!editor.editable || form.processing}
|
||||
className="space-y-3"
|
||||
>
|
||||
<Field label="Entregável">
|
||||
<input
|
||||
className={control}
|
||||
value={editor.values.title}
|
||||
onChange={(e) => editor.change('title', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Responsável pelo marco">
|
||||
<select
|
||||
className={control}
|
||||
required
|
||||
value={editor.values.responsible_id}
|
||||
onChange={(e) =>
|
||||
editor.change('responsible_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Seleccione um participante autorizado
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Evidência ou referência do resultado">
|
||||
<textarea
|
||||
className={control}
|
||||
value={form.data.evidence}
|
||||
onChange={(e) => form.setData('evidence', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
{item &&
|
||||
!p.participants.some(
|
||||
(participant) =>
|
||||
participant.id === item.responsible_id,
|
||||
) && (
|
||||
<option
|
||||
value={String(item.responsible_id)}
|
||||
disabled
|
||||
>
|
||||
{item.responsible_name ??
|
||||
'Responsável registado indisponível'}{' '}
|
||||
{item.responsible_is_participant
|
||||
? '— atribuição registada; selecção indisponível neste estado'
|
||||
: '— sem representação actual'}
|
||||
</option>
|
||||
)}
|
||||
{p.participants.map((participant) => (
|
||||
<option
|
||||
key={participant.id}
|
||||
value={String(participant.id)}
|
||||
>
|
||||
{participant.name} —{' '}
|
||||
{participant.parties
|
||||
.map((party) =>
|
||||
party === 'proponent'
|
||||
? 'Proponente'
|
||||
: 'Candidato',
|
||||
)
|
||||
.join(' / ')}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
{editor.editable &&
|
||||
editor.values.responsible_id &&
|
||||
!currentResponsible && (
|
||||
<p role="status">
|
||||
{item &&
|
||||
editor.values.responsible_id ===
|
||||
String(item.responsible_id)
|
||||
? 'A atribuição anterior foi conservada. Para guardar uma alteração, seleccione um participante actualmente autorizado; consultar não altera o responsável.'
|
||||
: 'O participante seleccionado deixou de estar disponível para esta atribuição. Escolha outro participante autorizado antes de guardar.'}
|
||||
</p>
|
||||
)}
|
||||
<Field label="Data prevista">
|
||||
<input
|
||||
className={control}
|
||||
type="date"
|
||||
value={editor.values.due_date}
|
||||
onChange={(e) =>
|
||||
editor.change('due_date', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Estado">
|
||||
<select
|
||||
className={control}
|
||||
value={editor.values.status}
|
||||
onChange={(e) =>
|
||||
editor.change('status', e.target.value)
|
||||
}
|
||||
>
|
||||
{['pending', 'progress', 'completed'].map((x) => (
|
||||
<option key={x} value={x}>
|
||||
{x === 'pending' ? 'Pendente' : labels[x]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
<Field label="Evidência ou referência do resultado">
|
||||
<textarea
|
||||
className={control}
|
||||
value={editor.values.evidence}
|
||||
onChange={(e) =>
|
||||
editor.change('evidence', e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
</fieldset>
|
||||
<Errors errors={form.errors} />
|
||||
<button className={button} disabled={form.processing}>
|
||||
Guardar marco
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
form.processing ||
|
||||
editor.blocked ||
|
||||
(!currentResponsible && !editor.recovering)
|
||||
}
|
||||
>
|
||||
{editor.recovering
|
||||
? 'Recuperar criação do marco'
|
||||
: 'Guardar marco'}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
export default function Page(p: Props) {
|
||||
return <RoomPage key={p.room.id + ':' + p.room.version} {...p} />;
|
||||
}
|
||||
function RoomPage(p: Props) {
|
||||
const { auth } = usePage<{ auth: { user: { id: number } } }>().props;
|
||||
const message = useForm({ body: '', client_key: createOperationKey() });
|
||||
const agreement = useForm({
|
||||
version: p.room.version,
|
||||
action: 'record',
|
||||
title: p.room.agreement?.title ?? '',
|
||||
terms: p.room.agreement?.terms ?? '',
|
||||
reason: '',
|
||||
});
|
||||
const upload = useForm<{ file: File | null; shared: boolean }>({
|
||||
file: null,
|
||||
shared: false,
|
||||
});
|
||||
const act = (action: string) => {
|
||||
agreement.transform((data) => ({ ...data, action }));
|
||||
agreement.post(`/parcerias/salas/${p.room.id}/acordo`, {
|
||||
preserveScroll: true,
|
||||
});
|
||||
};
|
||||
const openedRoom = useRef(p.room.id);
|
||||
return (
|
||||
<RoomPage
|
||||
key={openedRoom.current + ':' + auth.user.id}
|
||||
{...p}
|
||||
expectedRoomId={openedRoom.current}
|
||||
/>
|
||||
);
|
||||
}
|
||||
function RoomPage(p: Props & { expectedRoomId: number }) {
|
||||
const instrument = readAgreement(p.room.agreement);
|
||||
const { auth } = usePage<{ auth: { user: { id: number } } }>().props;
|
||||
const mutable =
|
||||
p.canWrite && !['closed', 'cancelled'].includes(p.room.status);
|
||||
p.canWrite &&
|
||||
p.room.id === p.expectedRoomId &&
|
||||
!['closed', 'cancelled'].includes(p.room.status);
|
||||
const messageEdit = useRoomDelivery({
|
||||
roomId: p.expectedRoomId,
|
||||
actorId: auth.user.id,
|
||||
kind: 'message',
|
||||
mutable,
|
||||
canWrite: p.canWrite && p.room.id === p.expectedRoomId,
|
||||
});
|
||||
const message = messageEdit.form;
|
||||
const agreementEdit = useRoomEdit({
|
||||
props: p,
|
||||
roomId: p.expectedRoomId,
|
||||
kind: 'agreement',
|
||||
});
|
||||
const agreement = agreementEdit.form;
|
||||
const uploadEdit = useRoomDelivery({
|
||||
roomId: p.expectedRoomId,
|
||||
actorId: auth.user.id,
|
||||
kind: 'upload',
|
||||
mutable,
|
||||
canWrite: p.canWrite && p.room.id === p.expectedRoomId,
|
||||
});
|
||||
const upload = uploadEdit.form;
|
||||
const uploadInput = useRef<HTMLInputElement>(null);
|
||||
useEffect(() => {
|
||||
if (!upload.data.file && uploadInput.current)
|
||||
uploadInput.current.value = '';
|
||||
}, [upload.data.file]);
|
||||
const act = (action: string) => agreementEdit.submit(action);
|
||||
const childDrafts = useRef(new Map<string, boolean>());
|
||||
const [childDraftCount, setChildDraftCount] = useState(0);
|
||||
const onDirty = useCallback((id: string, dirty: boolean) => {
|
||||
if ((childDrafts.current.get(id) ?? false) === dirty) return;
|
||||
childDrafts.current.set(id, dirty);
|
||||
setChildDraftCount(
|
||||
[...childDrafts.current.values()].filter(Boolean).length,
|
||||
);
|
||||
}, []);
|
||||
useRoomLeaveGuard(
|
||||
agreementEdit.dirty ||
|
||||
messageEdit.dirty ||
|
||||
uploadEdit.dirty ||
|
||||
childDraftCount > 0,
|
||||
);
|
||||
return (
|
||||
<Frame title={'Conexão privada — ' + p.partnership.title}>
|
||||
<div className="space-y-6">
|
||||
{p.room.id !== p.expectedRoomId && (
|
||||
<p role="alert">
|
||||
A resposta não corresponde à sala aberta. Recupere os
|
||||
dados antes de continuar; a sua preparação foi
|
||||
conservada.
|
||||
</p>
|
||||
)}
|
||||
<Link
|
||||
className="underline"
|
||||
href={'/parcerias/' + p.partnership.id}
|
||||
@@ -184,42 +350,53 @@ function RoomPage(p: Props) {
|
||||
<p className="whitespace-pre-wrap">{m.body}</p>
|
||||
</article>
|
||||
))}
|
||||
{mutable && (
|
||||
{(mutable || messageEdit.dirty) && (
|
||||
<form
|
||||
data-room-form="message"
|
||||
className="space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
message.post(
|
||||
`/parcerias/salas/${p.room.id}/mensagens`,
|
||||
{
|
||||
preserveScroll: true,
|
||||
onSuccess: () => {
|
||||
message.setData({
|
||||
body: '',
|
||||
client_key:
|
||||
createOperationKey(),
|
||||
});
|
||||
},
|
||||
},
|
||||
);
|
||||
messageEdit.submit();
|
||||
}}
|
||||
>
|
||||
<Field label="Mensagem privada">
|
||||
<textarea
|
||||
className={control}
|
||||
disabled={message.processing}
|
||||
disabled={message.processing || !mutable}
|
||||
value={message.data.body}
|
||||
onChange={(e) =>
|
||||
message.setData('body', e.target.value)
|
||||
messageEdit.change(
|
||||
'body',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Errors errors={message.errors} />
|
||||
{messageEdit.problem && (
|
||||
<p role="alert">{messageEdit.problem}</p>
|
||||
)}
|
||||
{!mutable && messageEdit.dirty && (
|
||||
<p role="status">
|
||||
A mensagem em preparação foi conservada. O
|
||||
estado ou acesso actual não permite novas
|
||||
mensagens.
|
||||
</p>
|
||||
)}
|
||||
{messageEdit.recovering && (
|
||||
<p role="status">
|
||||
Recuperar repete a mensagem original com a
|
||||
mesma chave; o texto escrito depois fica
|
||||
para outra mensagem.
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
className={button}
|
||||
disabled={message.processing}
|
||||
disabled={messageEdit.blocked}
|
||||
>
|
||||
Enviar mensagem
|
||||
{messageEdit.recovering
|
||||
? 'Recuperar mensagem enviada'
|
||||
: 'Enviar mensagem'}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
@@ -290,39 +467,42 @@ function RoomPage(p: Props) {
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
{mutable && (
|
||||
{(mutable || uploadEdit.dirty) && (
|
||||
<form
|
||||
data-room-form="upload"
|
||||
className="space-y-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
upload.post(
|
||||
`/parcerias/salas/${p.room.id}/documentos`,
|
||||
{
|
||||
forceFormData: true,
|
||||
preserveScroll: true,
|
||||
},
|
||||
);
|
||||
uploadEdit.submit();
|
||||
}}
|
||||
>
|
||||
<Field label="Anexar PDF ou imagem">
|
||||
<input
|
||||
type="file"
|
||||
ref={uploadInput}
|
||||
disabled={!mutable || upload.processing}
|
||||
className="w-full max-w-full min-w-0"
|
||||
accept=".pdf,.jpg,.jpeg,.png"
|
||||
onChange={(e) =>
|
||||
upload.setData(
|
||||
uploadEdit.change(
|
||||
'file',
|
||||
e.target.files?.[0] ?? null,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{upload.data.file && (
|
||||
<p role="status">
|
||||
Ficheiro preparado: {upload.data.file.name}
|
||||
</p>
|
||||
)}
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
disabled={!mutable || upload.processing}
|
||||
checked={upload.data.shared}
|
||||
onChange={(e) =>
|
||||
upload.setData(
|
||||
uploadEdit.change(
|
||||
'shared',
|
||||
e.target.checked,
|
||||
)
|
||||
@@ -331,13 +511,35 @@ function RoomPage(p: Props) {
|
||||
Autorizo a consulta pela contraparte desta sala.
|
||||
</label>
|
||||
<Errors errors={upload.errors} />
|
||||
{uploadEdit.problem && (
|
||||
<p role="alert">{uploadEdit.problem}</p>
|
||||
)}
|
||||
{!mutable && uploadEdit.dirty && (
|
||||
<p role="status">
|
||||
O ficheiro em preparação foi conservado em
|
||||
memória. O estado ou acesso actual não
|
||||
permite novos documentos.
|
||||
</p>
|
||||
)}
|
||||
{uploadEdit.recovering && (
|
||||
<p role="status">
|
||||
Recuperar repete o ficheiro e a autorização
|
||||
originais, sem criar outro documento. Uma
|
||||
selecção posterior fica preparada para outro
|
||||
envio.
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
upload.processing || !upload.data.file
|
||||
uploadEdit.blocked ||
|
||||
(!upload.data.file &&
|
||||
!uploadEdit.recovering)
|
||||
}
|
||||
>
|
||||
Guardar documento privado
|
||||
{uploadEdit.recovering
|
||||
? 'Recuperar envio do documento'
|
||||
: 'Guardar documento privado'}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
@@ -353,143 +555,200 @@ function RoomPage(p: Props) {
|
||||
concordância comunicada pelas partes; não certifica
|
||||
assinatura jurídica ou due diligence.
|
||||
</p>
|
||||
{p.room.agreement && (
|
||||
<>
|
||||
<h3 className="font-bold">
|
||||
{p.room.agreement.title}
|
||||
</h3>
|
||||
<p className="whitespace-pre-wrap">
|
||||
{p.room.agreement.terms}
|
||||
</p>
|
||||
<p>
|
||||
Confirmações:{' '}
|
||||
{Object.entries(p.room.agreement.confirmations)
|
||||
.map(
|
||||
([party, c]) =>
|
||||
`${party}: autor ${c.actor_id}, ${c.date}`,
|
||||
)
|
||||
.join('; ') || 'Pendentes'}
|
||||
</p>
|
||||
</>
|
||||
<Link
|
||||
className="inline-block underline"
|
||||
href={`/parcerias/salas/${p.room.id}/historico`}
|
||||
>
|
||||
Consultar histórico do acordo
|
||||
</Link>
|
||||
<AgreementInstrument value={p.room.agreement} />
|
||||
{p.agreementParty && (
|
||||
<p>
|
||||
A sua acção é registada pela parte{' '}
|
||||
{p.agreementParty === 'proponent'
|
||||
? 'proponente'
|
||||
: 'candidata'}
|
||||
, segundo a representação actual. Registar outra
|
||||
versão retira as confirmações dessa versão e
|
||||
conserva o histórico.
|
||||
</p>
|
||||
)}
|
||||
{mutable && (
|
||||
<RoomComparison
|
||||
editor={agreementEdit}
|
||||
labels={{
|
||||
title: 'Título do instrumento',
|
||||
terms: 'Condições e plano de valor',
|
||||
reason: 'Motivo da acção',
|
||||
}}
|
||||
/>
|
||||
{(mutable || agreementEdit.dirty) && (
|
||||
<>
|
||||
<Field label="Motivo da ação">
|
||||
<textarea
|
||||
className={control}
|
||||
value={agreement.data.reason}
|
||||
onChange={(e) =>
|
||||
agreement.setData(
|
||||
'reason',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{['negotiation', 'agreement_recorded'].includes(
|
||||
p.room.status,
|
||||
) && (
|
||||
<>
|
||||
<Field label="Título do instrumento">
|
||||
<input
|
||||
className={control}
|
||||
value={agreement.data.title}
|
||||
onChange={(e) =>
|
||||
agreement.setData(
|
||||
'title',
|
||||
e.target.value,
|
||||
)
|
||||
<fieldset
|
||||
data-room-form="agreement"
|
||||
disabled={!agreementEdit.editable}
|
||||
className="space-y-4"
|
||||
>
|
||||
<Field label="Motivo da ação">
|
||||
<textarea
|
||||
className={control}
|
||||
value={agreementEdit.values.reason}
|
||||
onChange={(e) =>
|
||||
agreementEdit.change(
|
||||
'reason',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{([
|
||||
'negotiation',
|
||||
'agreement_recorded',
|
||||
].includes(p.room.status) ||
|
||||
agreementEdit.dirty) && (
|
||||
<>
|
||||
<Field label="Título do instrumento">
|
||||
<input
|
||||
className={control}
|
||||
disabled={
|
||||
![
|
||||
'negotiation',
|
||||
'agreement_recorded',
|
||||
].includes(p.room.status)
|
||||
}
|
||||
value={
|
||||
agreementEdit.values.title
|
||||
}
|
||||
onChange={(e) =>
|
||||
agreementEdit.change(
|
||||
'title',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Condições e plano de valor">
|
||||
<textarea
|
||||
className={control}
|
||||
rows={6}
|
||||
disabled={
|
||||
![
|
||||
'negotiation',
|
||||
'agreement_recorded',
|
||||
].includes(p.room.status)
|
||||
}
|
||||
value={
|
||||
agreementEdit.values.terms
|
||||
}
|
||||
onChange={(e) =>
|
||||
agreementEdit.change(
|
||||
'terms',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
agreement.processing ||
|
||||
agreementEdit.blocked ||
|
||||
![
|
||||
'negotiation',
|
||||
'agreement_recorded',
|
||||
].includes(p.room.status) ||
|
||||
!agreementEdit.values.reason
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Condições e plano de valor">
|
||||
<textarea
|
||||
className={control}
|
||||
rows={6}
|
||||
value={agreement.data.terms}
|
||||
onChange={(e) =>
|
||||
agreement.setData(
|
||||
'terms',
|
||||
e.target.value,
|
||||
)
|
||||
onClick={() => act('record')}
|
||||
>
|
||||
Registar versão do acordo
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{(agreementEdit.values.title !==
|
||||
agreementEdit.current.title ||
|
||||
agreementEdit.values.terms !==
|
||||
agreementEdit.current.terms) && (
|
||||
<p role="status">
|
||||
Há alterações locais no instrumento
|
||||
ainda por registar. As outras acções
|
||||
referem-se à versão actualmente
|
||||
guardada, apresentada acima.
|
||||
</p>
|
||||
)}
|
||||
{p.room.status === 'agreement_recorded' && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
agreement.processing ||
|
||||
agreementEdit.blocked ||
|
||||
!agreementEdit.values.reason
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
onClick={() => act('confirm')}
|
||||
>
|
||||
{p.agreementParty &&
|
||||
instrument.confirmations[
|
||||
p.agreementParty
|
||||
]?.actorId
|
||||
? 'Actualizar confirmação da minha parte'
|
||||
: 'Confirmar pela minha parte'}
|
||||
</button>
|
||||
)}
|
||||
{p.room.status === 'agreed' && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
agreement.processing ||
|
||||
agreementEdit.blocked ||
|
||||
!agreementEdit.values.reason
|
||||
}
|
||||
onClick={() => act('start')}
|
||||
>
|
||||
Iniciar acompanhamento
|
||||
</button>
|
||||
)}
|
||||
{p.room.status === 'execution' && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
agreement.processing ||
|
||||
agreementEdit.blocked ||
|
||||
!agreementEdit.values.reason
|
||||
}
|
||||
onClick={() => act('complete')}
|
||||
>
|
||||
Concluir após os marcos
|
||||
</button>
|
||||
)}
|
||||
{['agreed', 'execution'].includes(
|
||||
p.room.status,
|
||||
) && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
agreement.processing ||
|
||||
agreementEdit.blocked ||
|
||||
!agreementEdit.values.reason
|
||||
}
|
||||
onClick={() => act('renew')}
|
||||
>
|
||||
Registar renovação
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
agreement.processing ||
|
||||
!agreement.data.reason
|
||||
agreementEdit.blocked ||
|
||||
!agreementEdit.values.reason
|
||||
}
|
||||
onClick={() => act('record')}
|
||||
onClick={() => act('cancel')}
|
||||
>
|
||||
Registar versão do acordo
|
||||
Cancelar conexão com motivo
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{p.room.status === 'agreement_recorded' && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
agreement.processing ||
|
||||
!agreement.data.reason
|
||||
}
|
||||
onClick={() => act('confirm')}
|
||||
>
|
||||
Confirmar pela minha parte
|
||||
</button>
|
||||
)}
|
||||
{p.room.status === 'agreed' && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
agreement.processing ||
|
||||
!agreement.data.reason
|
||||
}
|
||||
onClick={() => act('start')}
|
||||
>
|
||||
Iniciar acompanhamento
|
||||
</button>
|
||||
)}
|
||||
{p.room.status === 'execution' && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
agreement.processing ||
|
||||
!agreement.data.reason
|
||||
}
|
||||
onClick={() => act('complete')}
|
||||
>
|
||||
Concluir após os marcos
|
||||
</button>
|
||||
)}
|
||||
{['agreed', 'execution'].includes(
|
||||
p.room.status,
|
||||
) && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
agreement.processing ||
|
||||
!agreement.data.reason
|
||||
}
|
||||
onClick={() => act('renew')}
|
||||
>
|
||||
Registar renovação
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
agreement.processing ||
|
||||
!agreement.data.reason
|
||||
}
|
||||
onClick={() => act('cancel')}
|
||||
>
|
||||
Cancelar conexão com motivo
|
||||
</button>
|
||||
</div>
|
||||
<Errors errors={agreement.errors} />
|
||||
</div>
|
||||
<Errors errors={agreement.errors} />
|
||||
</fieldset>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
@@ -505,25 +764,23 @@ function RoomPage(p: Props) {
|
||||
.
|
||||
</p>
|
||||
{p.milestones.map((m) => (
|
||||
<article
|
||||
key={m.id + ':' + m.version}
|
||||
className="space-y-3"
|
||||
>
|
||||
<article key={m.id} className="space-y-3">
|
||||
<p>
|
||||
{m.title} ·{' '}
|
||||
{m.status === 'pending'
|
||||
? 'Pendente'
|
||||
: labels[m.status]}{' '}
|
||||
· Prazo: {m.due_date ?? 'Pendente'} ·
|
||||
Responsável ID {m.responsible_id}
|
||||
Responsável:{' '}
|
||||
{m.responsible_name ??
|
||||
'Responsável registado indisponível'}
|
||||
{!m.responsible_is_participant &&
|
||||
' · Sem representação actual; atribuição anterior conservada'}
|
||||
</p>
|
||||
{mutable && <MilestoneForm p={p} item={m} />}
|
||||
<MilestoneForm p={p} item={m} onDirty={onDirty} />
|
||||
</article>
|
||||
))}
|
||||
{mutable &&
|
||||
['agreement_recorded', 'agreed', 'execution'].includes(
|
||||
p.room.status,
|
||||
) && <MilestoneForm p={p} />}
|
||||
<MilestoneForm p={p} onDirty={onDirty} />
|
||||
</section>
|
||||
</div>
|
||||
</Frame>
|
||||
|
||||
@@ -28,6 +28,7 @@ export type Partnership = {
|
||||
title: string;
|
||||
status: string;
|
||||
version: number;
|
||||
client_key?: string | null;
|
||||
kind: string;
|
||||
partnership_type: string | null;
|
||||
sector_id: number | null;
|
||||
@@ -45,6 +46,7 @@ export type Partnership = {
|
||||
};
|
||||
};
|
||||
export type Match = {
|
||||
weights_hash?: string;
|
||||
score_min: number | null;
|
||||
score_max: number | null;
|
||||
eligibility: string;
|
||||
@@ -67,12 +69,16 @@ export type Interest = {
|
||||
status: string;
|
||||
decision_reason: string | null;
|
||||
organization_id: string | null;
|
||||
can_edit?: boolean;
|
||||
commands?: { key: string; version: number; action: string }[];
|
||||
payload: {
|
||||
capacity?: string;
|
||||
availability?: string;
|
||||
contribution?: string;
|
||||
conflicts?: string;
|
||||
consent?: boolean;
|
||||
sector_id?: number | null;
|
||||
territory_id?: string | null;
|
||||
};
|
||||
assessment: Record<string, { state: string; evidence?: string }>;
|
||||
match: Match;
|
||||
|
||||
@@ -58,6 +58,17 @@ const PrivacyPolicy = () => {
|
||||
dispositivo, navegador utilizado e informações
|
||||
relacionadas com cookies ou tecnologias semelhantes.
|
||||
</p>
|
||||
<p className="text-muted-foreground leading-relaxed">
|
||||
Nos pedidos do Balcão com gravação automática
|
||||
disponível, as respostas ainda incompletas e a
|
||||
justificação do rascunho são conservadas cifradas no
|
||||
servidor para recuperação pela própria conta,
|
||||
sujeita ao acesso actual ao pedido. Esta recuperação
|
||||
não submete o pedido nem confirma a revisão do
|
||||
contexto ou a autorização de submissão. O estado e
|
||||
as falhas da gravação são apresentados no
|
||||
formulário.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section className="space-y-3 pt-2">
|
||||
@@ -75,6 +86,17 @@ const PrivacyPolicy = () => {
|
||||
legais e produzir estatísticas agregadas sobre a
|
||||
utilização do portal.
|
||||
</p>
|
||||
<p className="text-muted-foreground leading-relaxed">
|
||||
Os contadores de pesquisa dos catálogos
|
||||
instrumentados conservam apenas totais por dia UTC,
|
||||
canal e edição da medição, incluindo respostas sem
|
||||
resultados e os instantes da primeira e última
|
||||
observação agregada. Estes contadores não guardam os
|
||||
termos pesquisados, valores de filtros, endereço IP,
|
||||
cookies ou identificadores de utilizadores ou
|
||||
visitantes. A recolha é omitida nos pedidos que
|
||||
enviem DNT: 1 ou Sec-GPC: 1.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section className="space-y-3 pt-2">
|
||||
|
||||
@@ -573,7 +573,29 @@ export default function Services(p: Props) {
|
||||
{['procedures', 'documents', 'legislation'].includes(
|
||||
p.section,
|
||||
) && <JourneyDocumentResources stages={p.stages} />}
|
||||
{p.section === 'procedures' && <InvestmentRoadmap />}
|
||||
{p.section === 'procedures' && (
|
||||
<>
|
||||
<Link className="underline" href="/formas-juridicas">
|
||||
Comparar formas jurídicas antes de preparar a
|
||||
constituição
|
||||
</Link>
|
||||
<InvestmentRoadmap />
|
||||
<Link
|
||||
className="block underline"
|
||||
href="/guias-investimento/capitalizacao"
|
||||
>
|
||||
Conhecer formas de capitalização e preparar o
|
||||
financiamento
|
||||
</Link>
|
||||
<Link
|
||||
className="block underline"
|
||||
href="/guias-investimento/bolsa"
|
||||
>
|
||||
Consultar o guião de admissão à Bolsa de Valores de
|
||||
Moçambique
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
{(p.section === 'documents' || p.section === 'legislation') && (
|
||||
<>
|
||||
<form
|
||||
|
||||
@@ -344,9 +344,11 @@ function InternalStaffGrant({
|
||||
function Grant({
|
||||
types,
|
||||
organizations,
|
||||
technicalSupportAvailable = false,
|
||||
}: {
|
||||
types: string[];
|
||||
organizations: { id: string; name: string }[];
|
||||
technicalSupportAvailable?: boolean;
|
||||
}) {
|
||||
const [user, setUser] = useState('');
|
||||
const [role, setRole] = useState('validator');
|
||||
@@ -436,8 +438,27 @@ function Grant({
|
||||
setResponsibilities([]);
|
||||
}}
|
||||
>
|
||||
{['validator', 'publisher', 'auditor'].map((v) => (
|
||||
<option key={v}>{v}</option>
|
||||
{[
|
||||
'validator',
|
||||
'publisher',
|
||||
'auditor',
|
||||
...(technicalSupportAvailable
|
||||
? ['technical_support']
|
||||
: []),
|
||||
].map((v) => (
|
||||
<option key={v} value={v}>
|
||||
{
|
||||
(
|
||||
{
|
||||
validator: 'Validador',
|
||||
publisher: 'Publicador',
|
||||
auditor: 'Auditor',
|
||||
technical_support:
|
||||
'Suporte técnico',
|
||||
} as Record<string, string>
|
||||
)[v]
|
||||
}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
@@ -839,7 +860,9 @@ export default function Administration({
|
||||
operatorOrganizations,
|
||||
internalTypes,
|
||||
staffAccounts,
|
||||
technicalSupportAvailable = false,
|
||||
}: {
|
||||
technicalSupportAvailable?: boolean;
|
||||
operatorOrganizations: OperatorOrganization[];
|
||||
internalTypes: string[];
|
||||
staffAccounts: {
|
||||
@@ -920,7 +943,11 @@ export default function Administration({
|
||||
organizations={organizations}
|
||||
operators={operatorOrganizations}
|
||||
/>
|
||||
<Grant types={types} organizations={organizations} />
|
||||
<Grant
|
||||
types={types}
|
||||
organizations={organizations}
|
||||
technicalSupportAvailable={technicalSupportAvailable}
|
||||
/>
|
||||
<Security
|
||||
pair={pair}
|
||||
entries={securityRequests}
|
||||
|
||||
@@ -2,8 +2,11 @@ import { createOperationKey } from '@/lib/operation-key';
|
||||
import { useState } from 'react';
|
||||
import { Management, button, control } from '@/pages/management/shared';
|
||||
import { profileJson } from '@/lib/profile-json';
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { usePagePreparationGuard } from '@/lib/page-preparation-guard';
|
||||
|
||||
type Plan = {
|
||||
technicalSupportUpdateUrl?: string;
|
||||
installed: boolean;
|
||||
consistent: boolean;
|
||||
ready: boolean;
|
||||
@@ -36,6 +39,18 @@ export default function Installation(initial: Plan) {
|
||||
const [confirmationUrl, setConfirmationUrl] = useState<string | null>(null);
|
||||
const [installationKey] = useState(createOperationKey);
|
||||
const [bootstrapKey] = useState(createOperationKey);
|
||||
const [confirmedPreparation, setConfirmedPreparation] = useState({
|
||||
reason: '',
|
||||
first: '',
|
||||
second: '',
|
||||
});
|
||||
usePagePreparationGuard(
|
||||
busy ||
|
||||
reason !== confirmedPreparation.reason ||
|
||||
first !== confirmedPreparation.first ||
|
||||
second !== confirmedPreparation.second,
|
||||
'Existe uma preparação ou uma operação de perfis em curso. Sair desta página?',
|
||||
);
|
||||
async function run(bootstrap = false) {
|
||||
setBusy(true);
|
||||
setMessage('');
|
||||
@@ -55,6 +70,11 @@ export default function Installation(initial: Plan) {
|
||||
: {}),
|
||||
},
|
||||
);
|
||||
setConfirmedPreparation((previous) => ({
|
||||
...previous,
|
||||
reason,
|
||||
...(bootstrap ? { first, second } : {}),
|
||||
}));
|
||||
setMessage(
|
||||
bootstrap
|
||||
? 'Pedido registado, sem atribuir privilégios. O segundo titular deve autenticar-se com MFA e confirmar pelo endereço abaixo.'
|
||||
@@ -85,6 +105,14 @@ export default function Installation(initial: Plan) {
|
||||
}
|
||||
return (
|
||||
<Management title="Instalação dos perfis — 040000">
|
||||
{plan.technicalSupportUpdateUrl && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={plan.technicalSupportUpdateUrl}
|
||||
>
|
||||
Actualização do Suporte técnico
|
||||
</Link>
|
||||
)}
|
||||
<p>
|
||||
Base {plan.target.database}:{plan.target.port} ·{' '}
|
||||
{plan.installed ? 'Schema instalado' : 'Schema por instalar'}
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { Management, button, control } from '../management/shared';
|
||||
import {
|
||||
useProfileSupportInstallation,
|
||||
type SupportPlan,
|
||||
} from '@/lib/profile-support-installation';
|
||||
function SupportInstallationForm({ initial }: { initial: SupportPlan }) {
|
||||
const edit = useProfileSupportInstallation(initial),
|
||||
plan = edit.plan;
|
||||
return (
|
||||
<section className="space-y-4">
|
||||
<p>
|
||||
Destino: {plan.target.database}:{plan.target.port}
|
||||
</p>
|
||||
<p>
|
||||
{plan.installed
|
||||
? 'Suporte técnico actualizado'
|
||||
: plan.repairable
|
||||
? 'Migração registada com a restrição anterior; reposição delimitada disponível.'
|
||||
: 'Actualização do Suporte técnico por aplicar'}
|
||||
</p>
|
||||
<p>
|
||||
{plan.ready
|
||||
? 'Provas actuais verificadas.'
|
||||
: 'Dependências ou provas por completar.'}{' '}
|
||||
Backup/restauro: {plan.backupDate ?? 'Prova actual pendente'}
|
||||
</p>
|
||||
{!plan.mfa_confirmed && (
|
||||
<p role="alert">
|
||||
Renove a autenticação MFA nesta conta antes de aplicar a
|
||||
actualização.
|
||||
</p>
|
||||
)}
|
||||
{!plan.consistent && !plan.repairable && (
|
||||
<p role="alert">
|
||||
A estrutura não corresponde à versão reconhecida. Preserve
|
||||
os dados e reconcilie a divergência antes de instalar.
|
||||
</p>
|
||||
)}
|
||||
<ul>
|
||||
{Object.entries(plan.dependencies).map(([name, ok]) => (
|
||||
<li key={name}>
|
||||
{(
|
||||
{
|
||||
profiles_installed: 'Base dos perfis instalada',
|
||||
profiles_consistent:
|
||||
'Base dos perfis consistente',
|
||||
management_020000: 'Gestão de oportunidades',
|
||||
resources_030000: 'Recursos das oportunidades',
|
||||
existing_identity_organization_audit:
|
||||
'Identidades, organizações e auditoria',
|
||||
} as Record<string, string>
|
||||
)[name] ?? 'Dependência da instalação'}
|
||||
: {ok ? 'presente' : 'pendente'}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<ul>
|
||||
{plan.changes.map((change) => (
|
||||
<li key={change}>{change}</li>
|
||||
))}
|
||||
</ul>
|
||||
<p>{plan.rollback}</p>
|
||||
{edit.stale && (
|
||||
<section
|
||||
className="space-y-2 rounded border p-3"
|
||||
aria-label="Comparar prévia da actualização"
|
||||
>
|
||||
<h2 className="font-semibold">A prévia mudou</h2>
|
||||
<p>
|
||||
Anterior:{' '}
|
||||
{edit.base.installed ? 'Actualizado' : 'Por actualizar'}{' '}
|
||||
·{' '}
|
||||
{edit.base.ready
|
||||
? 'Provas verificadas'
|
||||
: 'Provas pendentes'}{' '}
|
||||
· {edit.base.backupDate ?? 'Sem prova actual'}
|
||||
</p>
|
||||
<p>
|
||||
Actual:{' '}
|
||||
{plan.installed ? 'Actualizado' : 'Por actualizar'} ·{' '}
|
||||
{plan.ready ? 'Provas verificadas' : 'Provas pendentes'}{' '}
|
||||
· {plan.backupDate ?? 'Sem prova actual'}
|
||||
</p>
|
||||
<p>
|
||||
Confira novamente o destino, a estrutura e as alterações
|
||||
indicadas antes de confirmar.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={!edit.canAdopt}
|
||||
onClick={edit.adopt}
|
||||
>
|
||||
Confirmar leitura da prévia actual
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
<label className="block">
|
||||
Fundamento da actualização
|
||||
<textarea
|
||||
className={control}
|
||||
minLength={20}
|
||||
maxLength={1000}
|
||||
value={edit.reason}
|
||||
onChange={(event) => edit.change(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={edit.confirmed}
|
||||
disabled={edit.busy || edit.uncertain}
|
||||
onChange={(event) =>
|
||||
edit.setConfirmed(event.target.checked)
|
||||
}
|
||||
/>{' '}
|
||||
Confirmo esta actualização no destino indicado
|
||||
</label>
|
||||
{edit.uncertain && (
|
||||
<p>
|
||||
O envio original aguarda confirmação. A repetição conserva o
|
||||
plano, o fundamento e a confirmação originais.
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={!edit.canSend}
|
||||
onClick={() => void edit.send()}
|
||||
>
|
||||
Aplicar actualização do Suporte técnico
|
||||
</button>
|
||||
{edit.canRetry && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() => void edit.send(true)}
|
||||
>
|
||||
Repetir envio original
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={edit.refreshing}
|
||||
onClick={() => void edit.refresh()}
|
||||
>
|
||||
Actualizar prévia
|
||||
</button>
|
||||
</div>
|
||||
{edit.message && <p role="status">{edit.message}</p>}
|
||||
{edit.error && <p role="alert">{edit.error}</p>}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
export default function SupportInstallation(plan: SupportPlan) {
|
||||
return (
|
||||
<Management title="Actualizar Suporte técnico">
|
||||
<Link className="underline" href="/management/profile-install">
|
||||
Voltar à instalação dos perfis
|
||||
</Link>
|
||||
<SupportInstallationForm
|
||||
key={`${plan.actorId}:${plan.target.database}:${plan.target.port}`}
|
||||
initial={plan}
|
||||
/>
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import TechnicalIncidentHandling from '@/components/technical-incident-handling';
|
||||
import TechnicalIncidentNotice from '@/components/technical-incident-notice';
|
||||
import {
|
||||
handlingLabels,
|
||||
commandLabels,
|
||||
incidentOperationLabel,
|
||||
incidentErrorLabel,
|
||||
} from '@/lib/technical-incident-labels';
|
||||
import type { HandlingProps, Command } from '@/lib/technical-incident-handling';
|
||||
import { Management, Pagination, type Paginated } from '../management/shared';
|
||||
export default function TechnicalIncident(
|
||||
props: HandlingProps & {
|
||||
backUrl: string;
|
||||
notice?: { unread: boolean };
|
||||
history: Paginated<{
|
||||
id: string;
|
||||
version: number | null;
|
||||
action: Command | null;
|
||||
status: string | null;
|
||||
actor: string | null;
|
||||
occurred_at: string;
|
||||
note: string | null;
|
||||
note_available: boolean;
|
||||
}>;
|
||||
},
|
||||
) {
|
||||
const row = props.incident;
|
||||
return (
|
||||
<Management title="Tratamento de incidente técnico">
|
||||
<Link className="underline" href={props.backUrl}>
|
||||
Voltar à fila de suporte
|
||||
</Link>
|
||||
<section className="space-y-2 rounded border p-4">
|
||||
<h2 className="font-semibold">
|
||||
{incidentOperationLabel(row.operation)} · versão observada{' '}
|
||||
{row.observed_version}
|
||||
</h2>
|
||||
<p className="break-all">Referência: {row.reference}</p>
|
||||
<p>{row.occurred_at}</p>
|
||||
<p>{incidentErrorLabel(row.error_code)}</p>
|
||||
<p>Estado técnico: {handlingLabels[row.handling.status]}</p>
|
||||
<p>
|
||||
Responsável actual:{' '}
|
||||
{row.handling.assignee_name || 'Por assumir'}
|
||||
</p>
|
||||
</section>
|
||||
{props.notice && (
|
||||
<TechnicalIncidentNotice
|
||||
key={`notice:${props.actorId}:${row.reference}`}
|
||||
actorId={props.actorId}
|
||||
reference={row.reference}
|
||||
unread={props.notice.unread}
|
||||
/>
|
||||
)}
|
||||
<TechnicalIncidentHandling
|
||||
key={`${props.actorId}:${row.reference}`}
|
||||
{...props}
|
||||
/>
|
||||
<section className="space-y-3" aria-label="Histórico do tratamento">
|
||||
<h2 className="text-xl font-semibold">
|
||||
Histórico do tratamento
|
||||
</h2>
|
||||
{!props.history.data.length && <p>Sem tratamento registado.</p>}
|
||||
{props.history.data.map((entry) => (
|
||||
<article
|
||||
className="space-y-2 rounded border p-4"
|
||||
key={entry.id}
|
||||
>
|
||||
<h3 className="font-semibold">
|
||||
Versão {entry.version ?? 'não identificada'} ·{' '}
|
||||
{entry.action
|
||||
? commandLabels[entry.action]
|
||||
: 'Registo anterior'}
|
||||
</h3>
|
||||
<p>
|
||||
{entry.actor || 'Autor não identificado'} ·{' '}
|
||||
{entry.occurred_at}
|
||||
</p>
|
||||
<p>
|
||||
Estado:{' '}
|
||||
{entry.status
|
||||
? handlingLabels[entry.status] ||
|
||||
'Não identificado'
|
||||
: 'Não identificado'}
|
||||
</p>
|
||||
<p className="break-words whitespace-pre-wrap">
|
||||
{entry.note_available
|
||||
? entry.note
|
||||
: 'Nota indisponível para leitura; original preservado.'}
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
<Pagination page={props.history} />
|
||||
</section>
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import { Management, Pagination, type Paginated } from '../management/shared';
|
||||
import type { OpportunityTechnicalIncident } from '@/components/opportunity-technical-incidents';
|
||||
import { Link } from '@inertiajs/react';
|
||||
import {
|
||||
handlingLabels,
|
||||
incidentOperationLabel,
|
||||
incidentErrorLabel,
|
||||
} from '@/lib/technical-incident-labels';
|
||||
import type { HandlingState } from '@/lib/technical-incident-handling';
|
||||
import TechnicalIncidentNotice from '@/components/technical-incident-notice';
|
||||
export default function TechnicalSupport({
|
||||
incidents,
|
||||
actorId,
|
||||
filters = { status: 'all' },
|
||||
}: {
|
||||
actorId?: number;
|
||||
incidents: Paginated<
|
||||
OpportunityTechnicalIncident & {
|
||||
handling?: HandlingState | null;
|
||||
details_url?: string;
|
||||
unread?: boolean;
|
||||
}
|
||||
>;
|
||||
filters?: { status: string; unread?: boolean };
|
||||
}) {
|
||||
function href(status: string, unread = !!filters.unread) {
|
||||
const query = new URLSearchParams({
|
||||
...(status !== 'all' ? { status } : {}),
|
||||
...(unread ? { unread: '1' } : {}),
|
||||
}).toString();
|
||||
return '/suporte-tecnico/incidentes' + (query ? '?' + query : '');
|
||||
}
|
||||
return (
|
||||
<Management title="Suporte técnico — incidentes">
|
||||
<p>
|
||||
Incidentes de submissão, publicação, uploads e preparação de
|
||||
imagens nas organizações e tipos abrangidos pela sua atribuição
|
||||
actual. A fila apresenta metadados técnicos; o perfil de suporte
|
||||
não concede acesso aos processos ou documentos.
|
||||
</p>
|
||||
<nav
|
||||
aria-label="Filtrar por estado técnico"
|
||||
className="flex flex-wrap gap-4"
|
||||
>
|
||||
{Object.entries({ all: 'Todos', ...handlingLabels }).map(
|
||||
([value, label]) => (
|
||||
<Link
|
||||
key={value}
|
||||
className="underline"
|
||||
href={href(value)}
|
||||
aria-current={
|
||||
filters.status === value ? 'page' : undefined
|
||||
}
|
||||
>
|
||||
{label}
|
||||
</Link>
|
||||
),
|
||||
)}
|
||||
</nav>
|
||||
<nav
|
||||
aria-label="Filtrar avisos de suporte"
|
||||
className="flex flex-wrap gap-4"
|
||||
>
|
||||
<Link
|
||||
className="underline"
|
||||
href={href(filters.status, false)}
|
||||
aria-current={!filters.unread ? 'page' : undefined}
|
||||
>
|
||||
Todos os avisos
|
||||
</Link>
|
||||
<Link
|
||||
className="underline"
|
||||
href={href(filters.status, true)}
|
||||
aria-current={filters.unread ? 'page' : undefined}
|
||||
>
|
||||
Por consultar
|
||||
</Link>
|
||||
</nav>
|
||||
{!incidents.data.length && (
|
||||
<p>Não existem incidentes disponíveis neste âmbito.</p>
|
||||
)}
|
||||
{incidents.data.map((incident) => (
|
||||
<article
|
||||
key={incident.reference}
|
||||
className="space-y-2 rounded border p-4"
|
||||
>
|
||||
<h2 className="font-semibold">
|
||||
{incidentOperationLabel(incident.operation)} · versão
|
||||
observada {incident.version}
|
||||
</h2>
|
||||
<p>{incident.occurred_at}</p>
|
||||
<p>{incidentErrorLabel(incident.error_code)}</p>
|
||||
<p className="break-all">
|
||||
Referência: {incident.reference}
|
||||
</p>
|
||||
{actorId && typeof incident.unread === 'boolean' && (
|
||||
<TechnicalIncidentNotice
|
||||
key={`notice:${actorId}:${incident.reference}`}
|
||||
actorId={actorId}
|
||||
reference={incident.reference}
|
||||
unread={incident.unread}
|
||||
/>
|
||||
)}
|
||||
{incident.handling ? (
|
||||
<p>
|
||||
Estado técnico:{' '}
|
||||
{handlingLabels[incident.handling.status]} ·{' '}
|
||||
{incident.handling.assignee_name || 'Por assumir'}
|
||||
</p>
|
||||
) : (
|
||||
<p>
|
||||
Estado técnico indisponível; registos preservados.
|
||||
</p>
|
||||
)}
|
||||
{incident.details_url && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={
|
||||
incident.details_url +
|
||||
(incidents.current_page > 1 ||
|
||||
filters.status !== 'all' ||
|
||||
filters.unread
|
||||
? '?' +
|
||||
new URLSearchParams({
|
||||
...(incidents.current_page > 1
|
||||
? {
|
||||
page: String(
|
||||
incidents.current_page,
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
...(filters.status !== 'all'
|
||||
? { status: filters.status }
|
||||
: {}),
|
||||
...(filters.unread
|
||||
? { unread: '1' }
|
||||
: {}),
|
||||
}).toString()
|
||||
: '')
|
||||
}
|
||||
>
|
||||
Consultar e tratar incidente
|
||||
</Link>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
<Pagination page={incidents} />
|
||||
</Management>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user