feat: consolidar desenvolvimentos do portal InvestMoz
This commit is contained in:
@@ -0,0 +1,131 @@
|
||||
import { businessPointApplicable } from '@/lib/business-locations';
|
||||
|
||||
export type RegisteredBusinessLocation = {
|
||||
id: string;
|
||||
precision_level: string;
|
||||
is_public: boolean;
|
||||
has_geometry: boolean;
|
||||
latitude: number | string | null;
|
||||
longitude: number | string | null;
|
||||
};
|
||||
|
||||
export default function BusinessPointSummary({
|
||||
payload,
|
||||
registered,
|
||||
available = true,
|
||||
published = false,
|
||||
territoryLabel,
|
||||
}: {
|
||||
payload: Record<string, string | undefined>;
|
||||
registered?: RegisteredBusinessLocation | null;
|
||||
available?: boolean;
|
||||
published?: boolean;
|
||||
territoryLabel?: string;
|
||||
}) {
|
||||
const active = businessPointApplicable(payload);
|
||||
if (!active && !registered) return null;
|
||||
const source =
|
||||
payload.location_point_source_mode === 'listing'
|
||||
? payload.source_reference
|
||||
: payload.location_point_source_reference;
|
||||
const date =
|
||||
payload.location_point_source_mode === 'listing'
|
||||
? payload.source_date
|
||||
: payload.location_point_source_date;
|
||||
return (
|
||||
<aside
|
||||
className="space-y-2 rounded border p-3 text-sm"
|
||||
aria-label="Localização primária e preparação do ponto"
|
||||
>
|
||||
{registered && (
|
||||
<p>
|
||||
Localização primária actualmente cadastrada:{' '}
|
||||
{registered.is_public
|
||||
? 'divulgação marcada como pública'
|
||||
: 'reservada'}
|
||||
, precisão{' '}
|
||||
{(
|
||||
{
|
||||
province: 'província',
|
||||
district: 'distrito',
|
||||
admin_post: 'posto administrativo',
|
||||
locality: 'localidade',
|
||||
exact: 'exacta',
|
||||
} as Record<string, string>
|
||||
)[registered.precision_level] ?? registered.precision_level}
|
||||
.
|
||||
{registered.latitude !== null &&
|
||||
registered.longitude !== null && (
|
||||
<>
|
||||
{' '}
|
||||
Latitude {registered.latitude}; longitude{' '}
|
||||
{registered.longitude}.
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
{active ? (
|
||||
<>
|
||||
<p>
|
||||
{published
|
||||
? 'Ponto declarado na publicação: latitude'
|
||||
: 'Ponto em preparação: latitude'}{' '}
|
||||
{payload.location_latitude || 'por indicar'}; longitude{' '}
|
||||
{payload.location_longitude || 'por indicar'}. Usa o
|
||||
território declarado; com várias localizações, é
|
||||
necessário escolher a correspondente.
|
||||
</p>
|
||||
{territoryLabel && (
|
||||
<p>
|
||||
Localização declarada para o ponto: {territoryLabel}
|
||||
.
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
Fonte do ponto: {source || 'por indicar'}. Data da
|
||||
fonte: {date || 'desconhecida'}. Referência{' '}
|
||||
{payload.location_point_share_source === 'yes'
|
||||
? 'também proposta para divulgação pública'
|
||||
: 'mantida no processo reservado'}
|
||||
; a data acompanha o ponto publicado.
|
||||
</p>
|
||||
{published ? (
|
||||
<p>
|
||||
Dados utilizados na publicação e preservados no
|
||||
histórico reservado. A localização actualmente
|
||||
cadastrada é apresentada acima; uma edição posterior
|
||||
não reescreve o histórico.
|
||||
</p>
|
||||
) : (
|
||||
<p>
|
||||
A gravação não publica o ponto. Na publicação
|
||||
autorizada do anúncio, este ponto passa a primário
|
||||
público e substitui o primário cadastrado. A versão
|
||||
anterior fica no histórico reservado; as
|
||||
localizações secundárias são conservadas. Confirme
|
||||
território e coordenadas após alterações: a
|
||||
declaração não comprova a correspondência espacial
|
||||
ou a localização real.
|
||||
</p>
|
||||
)}
|
||||
{!available && (
|
||||
<p role="alert">
|
||||
O suplemento de localização ainda não está instalado
|
||||
neste destino. Instale a actualização antes de
|
||||
submeter este ponto ou conserve o cadastro
|
||||
existente.
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
registered && (
|
||||
<p>
|
||||
Este formulário não propõe um novo ponto. O cadastro
|
||||
existente é conservado, incluindo as divulgações já
|
||||
registadas.
|
||||
</p>
|
||||
)
|
||||
)}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import type { CrmRecordEditor } from '@/lib/crm-record-edit';
|
||||
|
||||
export default function CrmEditComparison({
|
||||
editor,
|
||||
labels,
|
||||
display = (_key, value) => value || 'Não indicado',
|
||||
}: {
|
||||
editor: CrmRecordEditor;
|
||||
labels: Record<string, string>;
|
||||
display?: (key: string, value: string) => string;
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-2 rounded border p-3">
|
||||
<button
|
||||
type="button"
|
||||
disabled={editor.refreshing || editor.form.processing}
|
||||
onClick={editor.refresh}
|
||||
>
|
||||
Comparar com os dados actuais
|
||||
</button>
|
||||
{editor.form.errors.version && (
|
||||
<p role="alert">{editor.form.errors.version}</p>
|
||||
)}
|
||||
{editor.invalid && (
|
||||
<p role="alert">
|
||||
Recupere este registo antes de gravar. A versão disponível
|
||||
não foi confirmada.
|
||||
</p>
|
||||
)}
|
||||
{editor.refreshing && (
|
||||
<p role="status">
|
||||
A recuperar os dados actuais. As suas edições são
|
||||
conservadas.
|
||||
</p>
|
||||
)}
|
||||
{editor.stale && (
|
||||
<>
|
||||
<p role="alert">
|
||||
O registo mudou desde a versão {editor.baseVersion}.
|
||||
Compare com a versão {editor.version} antes de
|
||||
continuar.
|
||||
</p>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full border-collapse text-left text-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Campo</th>
|
||||
<th>Actualmente guardado</th>
|
||||
<th>Sua edição</th>
|
||||
<th>Escolha</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{editor.changed.map((key) => (
|
||||
<tr key={key}>
|
||||
<td>{labels[key] ?? key}</td>
|
||||
<td className="whitespace-pre-wrap">
|
||||
{display(key, editor.current[key])}
|
||||
</td>
|
||||
<td className="whitespace-pre-wrap">
|
||||
{display(key, editor.values[key])}
|
||||
</td>
|
||||
<td>
|
||||
{editor.conflicts.includes(key) ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
editor.choose(
|
||||
key,
|
||||
'current',
|
||||
)
|
||||
}
|
||||
>
|
||||
Usar valor actual
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
editor.choose(
|
||||
key,
|
||||
'mine',
|
||||
)
|
||||
}
|
||||
>
|
||||
Manter minha alteração
|
||||
</button>
|
||||
{editor.unresolved.includes(
|
||||
key,
|
||||
) && (
|
||||
<p>
|
||||
Escolha o valor a
|
||||
conservar neste
|
||||
campo.
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
'Actualização compatível com a sua edição'
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
disabled={
|
||||
editor.refreshing || editor.unresolved.length > 0
|
||||
}
|
||||
onClick={editor.adopt}
|
||||
>
|
||||
Usar esta versão e conservar as alterações escolhidas
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
import { useCrmTaskCreation } from '@/lib/crm-task-creation';
|
||||
import type { TaskCreationContext } from '@/lib/crm-task-creation';
|
||||
import type { Lead, Owner } from '@/pages/crm/types';
|
||||
import { Field, button, control } from '@/pages/management/shared';
|
||||
import { useState } from 'react';
|
||||
|
||||
export default function CrmTaskCreation({
|
||||
lead,
|
||||
owners,
|
||||
context,
|
||||
}: {
|
||||
lead: Lead;
|
||||
owners: Owner[];
|
||||
context: TaskCreationContext;
|
||||
}) {
|
||||
const edit = useCrmTaskCreation(lead, context);
|
||||
const { form } = edit;
|
||||
const [showPreparation, setShowPreparation] = useState(false);
|
||||
const preparation = edit.preparation;
|
||||
const labels = {
|
||||
title: 'Tarefa',
|
||||
due_at: 'Prazo',
|
||||
assignee_user_id: 'Responsável pela tarefa',
|
||||
};
|
||||
function display(field: keyof typeof labels, value: string) {
|
||||
if (!value) return 'Por preencher';
|
||||
if (field === 'assignee_user_id')
|
||||
return (
|
||||
owners.find((owner) => String(owner.id) === value)?.name ??
|
||||
'Responsável anterior indisponível'
|
||||
);
|
||||
if (field === 'due_at') {
|
||||
const date = new Date(value);
|
||||
return Number.isNaN(date.getTime())
|
||||
? 'Prazo por confirmar'
|
||||
: new Intl.DateTimeFormat('pt-MZ', {
|
||||
dateStyle: 'medium',
|
||||
timeStyle: 'short',
|
||||
timeZone: 'Africa/Maputo',
|
||||
}).format(date) + ' (Maputo)';
|
||||
}
|
||||
return value;
|
||||
}
|
||||
const missing =
|
||||
form.data.assignee_user_id &&
|
||||
!owners.some(
|
||||
(owner) => String(owner.id) === form.data.assignee_user_id,
|
||||
);
|
||||
const sentDate = edit.sent ? new Date(edit.sent.due_at) : null;
|
||||
const sentDeadline =
|
||||
sentDate && !Number.isNaN(sentDate.getTime())
|
||||
? new Intl.DateTimeFormat('pt-MZ', {
|
||||
dateStyle: 'medium',
|
||||
timeStyle: 'short',
|
||||
timeZone: 'Africa/Maputo',
|
||||
}).format(sentDate) + ' (Maputo)'
|
||||
: 'Prazo por confirmar';
|
||||
return (
|
||||
<form
|
||||
id="new-crm-task"
|
||||
className="max-w-xl space-y-4"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
edit.submit();
|
||||
}}
|
||||
>
|
||||
<h2 className="text-lg font-semibold">Registar próxima acção</h2>
|
||||
{context.preparation && (
|
||||
<section
|
||||
aria-label="Recuperação da preparação"
|
||||
className="space-y-3 rounded border p-3"
|
||||
>
|
||||
<p role="status">
|
||||
{preparation.message ||
|
||||
(context.preparation.installed
|
||||
? 'A preparação acompanha as alterações e pode ser retomada nesta conta.'
|
||||
: 'A recuperação persistente ainda não está instalada. A criação manual continua disponível nesta página.')}
|
||||
</p>
|
||||
{preparation.comparison && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() => setShowPreparation(true)}
|
||||
>
|
||||
Comparar preparação guardada
|
||||
</button>
|
||||
{showPreparation &&
|
||||
preparation.comparison.snapshot && (
|
||||
<>
|
||||
<p>
|
||||
Compare antes de adoptar. As
|
||||
alterações desta página permanecem
|
||||
até confirmar as suas escolhas.
|
||||
</p>
|
||||
{(
|
||||
Object.keys(
|
||||
labels,
|
||||
) as (keyof typeof labels)[]
|
||||
).map((field) => (
|
||||
<div
|
||||
key={field}
|
||||
className="space-y-1"
|
||||
>
|
||||
<p className="font-semibold">
|
||||
{labels[field]}
|
||||
</p>
|
||||
<p>
|
||||
Nesta página:{' '}
|
||||
{display(
|
||||
field,
|
||||
preparation.current
|
||||
.values[field],
|
||||
)}
|
||||
</p>
|
||||
<p>
|
||||
Guardado:{' '}
|
||||
{display(
|
||||
field,
|
||||
preparation.comparison
|
||||
?.snapshot?.values[
|
||||
field
|
||||
] ?? '',
|
||||
)}
|
||||
</p>
|
||||
<label>
|
||||
Valor a retomar:{' '}
|
||||
{labels[field]}
|
||||
<select
|
||||
className={control}
|
||||
value={preparation.source(
|
||||
field,
|
||||
)}
|
||||
onChange={(event) =>
|
||||
preparation.choose(
|
||||
field,
|
||||
event.target
|
||||
.value ===
|
||||
'saved'
|
||||
? 'saved'
|
||||
: 'page',
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="page">
|
||||
Manter desta página
|
||||
</option>
|
||||
<option value="saved">
|
||||
Usar guardado
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
))}
|
||||
{preparation.comparison.snapshot
|
||||
.pending && (
|
||||
<p>
|
||||
Existe uma tentativa por
|
||||
confirmar. A recuperação
|
||||
conserva os seus dados e não
|
||||
cria a tarefa automaticamente.
|
||||
</p>
|
||||
)}
|
||||
{!!preparation.unresolved.length && (
|
||||
<p role="alert">
|
||||
Existem alterações posteriores à
|
||||
escolha. Reveja esses campos
|
||||
antes de retomar.
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={
|
||||
!!preparation.unresolved.length
|
||||
}
|
||||
onClick={preparation.recover}
|
||||
>
|
||||
Aplicar escolhas e retomar
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{preparation.enabled && preparation.state === 'error' && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() => {
|
||||
void preparation.ensure(false);
|
||||
}}
|
||||
>
|
||||
Voltar a guardar preparação
|
||||
</button>
|
||||
)}
|
||||
{preparation.enabled &&
|
||||
!preparation.comparison &&
|
||||
['error', 'unavailable'].includes(
|
||||
preparation.state,
|
||||
) && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={preparation.manual}
|
||||
>
|
||||
Continuar só nesta página
|
||||
</button>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
{edit.notice && <p role="status">{edit.notice}</p>}
|
||||
{edit.waiting && (
|
||||
<p>
|
||||
A recuperação repete os dados da tentativa:{' '}
|
||||
{edit.sent?.title}; {sentDeadline};{' '}
|
||||
{owners.find(
|
||||
(owner) =>
|
||||
String(owner.id) === edit.sent?.assignee_user_id,
|
||||
)?.name ?? 'Responsável do envio anterior'}
|
||||
. As edições posteriores ficam conservadas para a próxima
|
||||
tarefa.
|
||||
</p>
|
||||
)}
|
||||
<Field label="Tarefa" error={form.errors.title}>
|
||||
<input
|
||||
className={control}
|
||||
maxLength={200}
|
||||
value={form.data.title}
|
||||
onChange={(e) => edit.change('title', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Prazo (hora local)" error={form.errors.due_at}>
|
||||
<input
|
||||
type="datetime-local"
|
||||
className={control}
|
||||
value={form.data.due_at}
|
||||
onChange={(e) => edit.change('due_at', e.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
<Field
|
||||
label="Responsável pela tarefa"
|
||||
error={form.errors.assignee_user_id}
|
||||
>
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.assignee_user_id}
|
||||
onChange={(e) =>
|
||||
edit.change('assignee_user_id', e.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Seleccione</option>
|
||||
{missing && (
|
||||
<option value={form.data.assignee_user_id}>
|
||||
Responsável anterior indisponível — seleccione para
|
||||
novo envio
|
||||
</option>
|
||||
)}
|
||||
{owners.map((owner) => (
|
||||
<option key={owner.id} value={owner.id}>
|
||||
{owner.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
{Object.keys(form.errors).includes('client_key') && (
|
||||
<p role="alert">
|
||||
Não foi possível reconhecer o envio. Actualize as tarefas
|
||||
antes de continuar.
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
form.processing || edit.blocked || edit.refreshing
|
||||
}
|
||||
>
|
||||
{edit.waiting
|
||||
? 'Recuperar a mesma criação'
|
||||
: 'Criar tarefa'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={form.processing || edit.refreshing}
|
||||
onClick={edit.refresh}
|
||||
>
|
||||
Actualizar tarefas
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { states as interestStates } from '@/pages/management/shared';
|
||||
import { taskStates } from '@/pages/crm/types';
|
||||
|
||||
type WorkItem = {
|
||||
id: string;
|
||||
title: string;
|
||||
reference: string | null;
|
||||
status: string;
|
||||
due_at: string | null;
|
||||
overdue: boolean;
|
||||
href: string;
|
||||
};
|
||||
type WorkGroup = {
|
||||
total: number;
|
||||
overdue: number;
|
||||
items: WorkItem[];
|
||||
page: number;
|
||||
last_page: number;
|
||||
previous: string | null;
|
||||
next: string | null;
|
||||
};
|
||||
export type DashboardQueue = {
|
||||
as_of: string;
|
||||
desk_states: Record<string, string>;
|
||||
groups: Partial<Record<'interests' | 'desk' | 'crm_tasks', WorkGroup>>;
|
||||
};
|
||||
const groups = {
|
||||
interests: 'Manifestações atribuídas a mim',
|
||||
desk: 'Pedidos do Balcão atribuídos a mim',
|
||||
crm_tasks: 'Tarefas do CRM atribuídas a mim',
|
||||
} as const;
|
||||
const date = (value: string) =>
|
||||
new Intl.DateTimeFormat('pt-MZ', {
|
||||
dateStyle: 'medium',
|
||||
timeStyle: 'short',
|
||||
timeZone: 'Africa/Maputo',
|
||||
}).format(new Date(value));
|
||||
|
||||
export default function DashboardWorkQueue({
|
||||
queue,
|
||||
}: {
|
||||
queue: DashboardQueue | null | undefined;
|
||||
}) {
|
||||
if (!queue) return null;
|
||||
return (
|
||||
<section aria-labelledby="my-work-title" className="space-y-4">
|
||||
<h2 id="my-work-title" className="text-xl font-semibold">
|
||||
O meu acompanhamento
|
||||
</h2>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Pedidos e tarefas atribuídos a si, por prazo. Actualizado em{' '}
|
||||
<time dateTime={queue.as_of}>{date(queue.as_of)} (Maputo)</time>
|
||||
.
|
||||
</p>
|
||||
<div className="grid gap-4 lg:grid-cols-3">
|
||||
{Object.entries(groups).map(([kind, title]) => {
|
||||
const group = queue.groups[kind as keyof typeof groups];
|
||||
if (!group) return null;
|
||||
const states =
|
||||
kind === 'interests'
|
||||
? interestStates
|
||||
: kind === 'desk'
|
||||
? queue.desk_states
|
||||
: taskStates;
|
||||
return (
|
||||
<section
|
||||
key={kind}
|
||||
aria-labelledby={`work-${kind}`}
|
||||
className="space-y-3 rounded-xl border p-4"
|
||||
>
|
||||
<h3 id={`work-${kind}`} className="font-semibold">
|
||||
{title}
|
||||
</h3>
|
||||
<p>
|
||||
{group.total} por acompanhar · {group.overdue}{' '}
|
||||
com prazo ultrapassado
|
||||
</p>
|
||||
{group.items.length ? (
|
||||
<ul className="space-y-3">
|
||||
{group.items.map((item) => (
|
||||
<li
|
||||
key={item.id}
|
||||
className="space-y-1 border-t pt-3"
|
||||
>
|
||||
<Link
|
||||
className="focus-visible:outline-primary font-medium underline focus-visible:outline-2"
|
||||
href={item.href}
|
||||
>
|
||||
{item.title}
|
||||
</Link>
|
||||
{item.reference && (
|
||||
<p className="text-sm">
|
||||
{item.reference}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm">
|
||||
{states[item.status] ??
|
||||
item.status}
|
||||
</p>
|
||||
<p className="text-sm">
|
||||
{item.due_at ? (
|
||||
<>
|
||||
<time
|
||||
dateTime={
|
||||
item.due_at
|
||||
}
|
||||
>
|
||||
{date(item.due_at)}{' '}
|
||||
(Maputo)
|
||||
</time>
|
||||
{item.overdue && (
|
||||
<strong>
|
||||
{' '}
|
||||
· Prazo
|
||||
ultrapassado
|
||||
</strong>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
'Sem prazo definido'
|
||||
)}
|
||||
</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p>
|
||||
Não tem registos activos atribuídos neste
|
||||
acompanhamento.
|
||||
</p>
|
||||
)}
|
||||
{group.last_page > 1 && (
|
||||
<nav
|
||||
aria-label={`Páginas: ${title}`}
|
||||
className="flex flex-wrap items-center gap-3"
|
||||
>
|
||||
{group.previous && (
|
||||
<Link
|
||||
href={group.previous}
|
||||
preserveScroll
|
||||
className="underline"
|
||||
>
|
||||
Anterior
|
||||
</Link>
|
||||
)}
|
||||
<span>
|
||||
Página {group.page} de {group.last_page}
|
||||
</span>
|
||||
{group.next && (
|
||||
<Link
|
||||
href={group.next}
|
||||
preserveScroll
|
||||
className="underline"
|
||||
>
|
||||
Seguinte
|
||||
</Link>
|
||||
)}
|
||||
</nav>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,453 @@
|
||||
import { useRef, useState } from 'react';
|
||||
import { profileJson, ProfileValidationError } from '@/lib/profile-json';
|
||||
import { deskChoices } from '@/lib/desk-field-values';
|
||||
import type { DeskDocument } from './desk-internal-operations';
|
||||
import DeskDocumentPicker, {
|
||||
type ReusableDeskDocument,
|
||||
} from './desk-document-picker';
|
||||
|
||||
export type AttachmentField = {
|
||||
label: string;
|
||||
required: boolean;
|
||||
mime_types?: string[];
|
||||
max_size_kb?: number;
|
||||
max_files?: number;
|
||||
};
|
||||
export type AttachmentInventory = {
|
||||
documents: DeskDocument[];
|
||||
case_version: number;
|
||||
link_id?: string | null;
|
||||
reused_link?: boolean;
|
||||
reusable_documents?: DeskDocument[];
|
||||
};
|
||||
type Props = {
|
||||
caseId: string;
|
||||
requestId: string;
|
||||
caseVersion: number;
|
||||
fieldKey: string;
|
||||
field: AttachmentField;
|
||||
value: unknown;
|
||||
documents: DeskDocument[];
|
||||
reusableDocuments?: DeskDocument[];
|
||||
disabled: boolean;
|
||||
uploading: boolean;
|
||||
onChange: (ids: string[]) => void;
|
||||
onBusy: (busy: boolean) => void;
|
||||
onInventory: (result: AttachmentInventory, select: boolean) => void;
|
||||
};
|
||||
const formatLabels: Record<string, string> = {
|
||||
'application/pdf': 'PDF',
|
||||
'image/png': 'PNG',
|
||||
'image/jpeg': 'JPEG',
|
||||
'text/plain': 'Texto simples',
|
||||
};
|
||||
|
||||
export default function DeskAttachmentField(props: Props) {
|
||||
const latest = useRef(props);
|
||||
const fileInput = useRef<HTMLInputElement | null>(null);
|
||||
latest.current = props;
|
||||
const [file, setFile] = useState<File | null>(null),
|
||||
[source, setSource] = useState(''),
|
||||
[consent, setConsent] = useState(false);
|
||||
const [busy, setBusy] = useState(false),
|
||||
[message, setMessage] = useState(''),
|
||||
[errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [reuseId, setReuseId] = useState('');
|
||||
const [remoteOrigin, setRemoteOrigin] =
|
||||
useState<ReusableDeskDocument | null>(null);
|
||||
const reusable = [
|
||||
...new Map(
|
||||
(props.reusableDocuments ?? [])
|
||||
.filter(
|
||||
(doc) =>
|
||||
!props.documents.some(
|
||||
(current) =>
|
||||
current.document_id === doc.document_id,
|
||||
),
|
||||
)
|
||||
.map((doc) => [
|
||||
JSON.stringify([
|
||||
doc.document_id,
|
||||
doc.source_reference,
|
||||
doc.stage ?? null,
|
||||
doc.valid_until ?? null,
|
||||
]),
|
||||
doc,
|
||||
]),
|
||||
).values(),
|
||||
];
|
||||
const origin = remoteOrigin ?? reusable.find((doc) => doc.id === reuseId);
|
||||
const selected = deskChoices(props.value);
|
||||
const unique = [
|
||||
...new Map(
|
||||
props.documents.map((doc) => [
|
||||
doc.document_id,
|
||||
props.documents.find(
|
||||
(d) =>
|
||||
d.document_id === doc.document_id &&
|
||||
selected.includes(d.id),
|
||||
) ?? doc,
|
||||
]),
|
||||
).values(),
|
||||
];
|
||||
async function refresh() {
|
||||
if (busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const data = await profileJson(
|
||||
`/balcao-virtual/pedidos/${props.requestId}`,
|
||||
{},
|
||||
'GET',
|
||||
);
|
||||
if (
|
||||
!Array.isArray(data.documents) ||
|
||||
!Number.isInteger(data.caseVersion)
|
||||
)
|
||||
throw new Error(
|
||||
'Não foi possível confirmar a lista dos documentos. As respostas desta página foram conservadas.',
|
||||
);
|
||||
latest.current.onInventory(
|
||||
{
|
||||
documents: data.documents,
|
||||
case_version: data.caseVersion,
|
||||
reusable_documents: data.reusableDocuments,
|
||||
},
|
||||
false,
|
||||
);
|
||||
setMessage(
|
||||
'Estado e lista dos documentos actualizados. As respostas desta página foram conservadas.',
|
||||
);
|
||||
} catch (error) {
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Não foi possível actualizar os documentos.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
async function upload() {
|
||||
if (
|
||||
props.disabled ||
|
||||
props.uploading ||
|
||||
busy ||
|
||||
(!file && !origin) ||
|
||||
!consent ||
|
||||
(!origin?.source_reference?.trim() && !source.trim())
|
||||
)
|
||||
return;
|
||||
if (
|
||||
!origin &&
|
||||
file &&
|
||||
file.size > (props.field.max_size_kb ?? 10240) * 1024
|
||||
) {
|
||||
setErrors({
|
||||
file: 'O ficheiro excede o tamanho máximo desta pergunta.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
props.onBusy(true);
|
||||
setErrors({});
|
||||
setMessage('A enviar o documento privado…');
|
||||
const data = new FormData();
|
||||
data.set('version', String(props.caseVersion));
|
||||
data.set('request_id', props.requestId);
|
||||
data.set('field_key', props.fieldKey);
|
||||
if (origin) {
|
||||
data.set('document_id', origin.document_id);
|
||||
if (origin.id) data.set('reuse_link_id', origin.id);
|
||||
if (!origin.source_reference?.trim())
|
||||
data.set('source_reference', source);
|
||||
} else if (file) {
|
||||
data.set('file', file);
|
||||
data.set('source_reference', source);
|
||||
}
|
||||
data.set('consent', '1');
|
||||
try {
|
||||
const result: AttachmentInventory = await profileJson(
|
||||
`/balcao-virtual/dossiers/${props.caseId}/documentos`,
|
||||
data,
|
||||
);
|
||||
if (
|
||||
!Array.isArray(result.documents) ||
|
||||
!Number.isInteger(result.case_version) ||
|
||||
typeof result.link_id !== 'string' ||
|
||||
!result.documents.some(
|
||||
(document) => document.id === result.link_id,
|
||||
)
|
||||
)
|
||||
throw new Error(
|
||||
'O envio não confirmou o documento associado. Actualize a lista antes de repetir; o ficheiro seleccionado continua nesta página.',
|
||||
);
|
||||
latest.current.onInventory(result, true);
|
||||
setFile(null);
|
||||
if (fileInput.current) fileInput.current.value = '';
|
||||
setConsent(false);
|
||||
setReuseId('');
|
||||
setRemoteOrigin(null);
|
||||
setMessage(
|
||||
result.reused_link
|
||||
? 'Este documento já estava associado. Conservou-se a referência registada; pode seleccioná-lo nesta pergunta.'
|
||||
: 'Documento associado ao pedido. A análise de segurança e a selecção nesta pergunta são apresentadas abaixo.',
|
||||
);
|
||||
} catch (error) {
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'O envio não foi confirmado. Actualize a lista antes de repetir.',
|
||||
);
|
||||
if (error instanceof ProfileValidationError)
|
||||
setErrors(error.fields);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
latest.current.onBusy(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<fieldset
|
||||
className="space-y-2 rounded border p-3"
|
||||
disabled={props.disabled}
|
||||
>
|
||||
<legend>
|
||||
{props.field.label}
|
||||
{props.field.required ? ' *' : ''}
|
||||
</legend>
|
||||
<p>
|
||||
Seleccione documentos já associados a este dossier ou envie um
|
||||
ficheiro. O mesmo original pode apoiar várias perguntas, sem
|
||||
novo envio.
|
||||
</p>
|
||||
<p>
|
||||
Formatos:{' '}
|
||||
{(props.field.mime_types ?? [])
|
||||
.map((mime) => formatLabels[mime] ?? mime)
|
||||
.join(', ')}
|
||||
. Até {props.field.max_size_kb} KB por ficheiro e{' '}
|
||||
{props.field.max_files} ficheiro(s) seleccionados.
|
||||
</p>
|
||||
{unique.map((doc) => {
|
||||
const checked = selected.includes(doc.id);
|
||||
const mime = doc.media_type?.split(';')[0].trim().toLowerCase();
|
||||
const known =
|
||||
!!mime &&
|
||||
doc.size_bytes !== null &&
|
||||
doc.size_bytes !== undefined;
|
||||
const fits =
|
||||
(!mime || props.field.mime_types?.includes(mime)) &&
|
||||
(doc.size_bytes === null ||
|
||||
doc.size_bytes === undefined ||
|
||||
doc.size_bytes <=
|
||||
(props.field.max_size_kb ?? 0) * 1024);
|
||||
return (
|
||||
<label className="block" key={doc.id}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
disabled={
|
||||
!checked &&
|
||||
(!fits ||
|
||||
selected.length >=
|
||||
(props.field.max_files ?? 1))
|
||||
}
|
||||
onChange={(event) =>
|
||||
props.onChange(
|
||||
event.target.checked
|
||||
? [...selected, doc.id]
|
||||
: selected.filter(
|
||||
(id) =>
|
||||
!props.documents.some(
|
||||
(document) =>
|
||||
document.id === id &&
|
||||
document.document_id ===
|
||||
doc.document_id,
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
/>{' '}
|
||||
{doc.file_name} · versão{' '}
|
||||
{doc.version_no ?? 'por confirmar'} ·{' '}
|
||||
{doc.malware_scan_status === 'clean' &&
|
||||
doc.status === 'active'
|
||||
? 'Análise de segurança concluída'
|
||||
: 'Análise ou disponibilidade pendente'}
|
||||
{!fits && ' · Não satisfaz os limites desta pergunta'}
|
||||
{!known &&
|
||||
' · Formato ou tamanho por conferir ao submeter'}
|
||||
<span className="block text-sm">
|
||||
{doc.source_reference}
|
||||
</span>
|
||||
{doc.status === 'active' &&
|
||||
doc.malware_scan_status === 'clean' && (
|
||||
<a
|
||||
className="block underline"
|
||||
href={`/balcao-virtual/dossiers/${props.caseId}/documentos/${doc.id}`}
|
||||
>
|
||||
Consultar documento autorizado
|
||||
</a>
|
||||
)}
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
{selected
|
||||
.filter((id) => !props.documents.some((doc) => doc.id === id))
|
||||
.map((id) => (
|
||||
<p key={id}>
|
||||
Existe uma selecção cuja disponibilidade precisa de ser
|
||||
actualizada.{' '}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
props.onChange(
|
||||
selected.filter((value) => value !== id),
|
||||
)
|
||||
}
|
||||
>
|
||||
Retirar esta selecção
|
||||
</button>
|
||||
</p>
|
||||
))}
|
||||
{!unique.length && (
|
||||
<p>
|
||||
Ainda não existem documentos associados a este pedido ou ao
|
||||
dossier para seleccionar.
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => void refresh()}
|
||||
>
|
||||
Actualizar documentos disponíveis
|
||||
</button>
|
||||
<p>
|
||||
Pode guardar o rascunho enquanto a análise está pendente. Para
|
||||
submeter uma pergunta aplicável, os suportes seleccionados têm
|
||||
de estar disponíveis, autorizados e com análise de segurança
|
||||
válida; isso não os torna documentos oficialmente aprovados.
|
||||
</p>
|
||||
<div className="space-y-2 border-t pt-3">
|
||||
<h3>Enviar novo suporte para esta pergunta</h3>
|
||||
<p>
|
||||
Escolher um ficheiro ou um documento de origem não o associa
|
||||
ao pedido. Confirme a associação nesta pergunta antes de
|
||||
submeter.
|
||||
</p>
|
||||
{reusable.length > 0 && (
|
||||
<label className="block">
|
||||
Ou reutilizar um documento autorizado de outro pedido
|
||||
deste dossier
|
||||
<select
|
||||
value={reuseId}
|
||||
disabled={busy || props.uploading}
|
||||
onChange={(event) => {
|
||||
setReuseId(event.target.value);
|
||||
setRemoteOrigin(null);
|
||||
setConsent(false);
|
||||
if (event.target.value) {
|
||||
setFile(null);
|
||||
if (fileInput.current)
|
||||
fileInput.current.value = '';
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="">Enviar um novo ficheiro</option>
|
||||
{reusable.map((doc) => (
|
||||
<option key={doc.id} value={doc.id}>
|
||||
{doc.file_name} · versão{' '}
|
||||
{doc.version_no ?? 'por confirmar'} ·{' '}
|
||||
{doc.source_reference ||
|
||||
'Referência por completar'}
|
||||
{doc.stage ? ` · origem ${doc.stage}` : ''}
|
||||
{doc.valid_until
|
||||
? ` · validade declarada ${doc.valid_until}`
|
||||
: ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<DeskDocumentPicker
|
||||
caseId={props.caseId}
|
||||
disabled={busy || props.uploading || props.disabled}
|
||||
selected={remoteOrigin}
|
||||
onSelect={(document) => {
|
||||
setRemoteOrigin(document);
|
||||
setReuseId('');
|
||||
setConsent(false);
|
||||
if (document) {
|
||||
setFile(null);
|
||||
if (fileInput.current) fileInput.current.value = '';
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{!origin && (
|
||||
<label className="block">
|
||||
Ficheiro
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInput}
|
||||
accept={props.field.mime_types?.join(',')}
|
||||
disabled={busy || props.uploading}
|
||||
onChange={(event) =>
|
||||
setFile(event.target.files?.[0] ?? null)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
{!origin || !origin.source_reference?.trim() ? (
|
||||
<label className="block">
|
||||
Proveniência e referência do documento
|
||||
<input
|
||||
value={source}
|
||||
maxLength={3000}
|
||||
disabled={busy || props.uploading}
|
||||
onChange={(event) => setSource(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
) : (
|
||||
<p>
|
||||
Referência já registada: {origin.source_reference}. Será
|
||||
conservada com a versão deste original.
|
||||
</p>
|
||||
)}
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={consent}
|
||||
disabled={busy || props.uploading}
|
||||
onChange={(event) => setConsent(event.target.checked)}
|
||||
/>{' '}
|
||||
Autorizo associar este documento ao pedido privado.
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
disabled={
|
||||
busy ||
|
||||
props.uploading ||
|
||||
(!file && !origin) ||
|
||||
!consent ||
|
||||
(!origin?.source_reference?.trim() && !source.trim())
|
||||
}
|
||||
onClick={() => void upload()}
|
||||
>
|
||||
{origin
|
||||
? 'Reutilizar documento nesta pergunta'
|
||||
: 'Associar ficheiro a esta pergunta'}
|
||||
</button>
|
||||
</div>
|
||||
{message && (
|
||||
<p role="status" aria-live="polite">
|
||||
{message}
|
||||
</p>
|
||||
)}
|
||||
{Object.entries(errors).map(([key, error]) => (
|
||||
<p role="alert" key={key}>
|
||||
{error}
|
||||
</p>
|
||||
))}
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { button, card, input } from '@/pages/investment/shared';
|
||||
|
||||
type CaseState = { id: string; version: number; closed_at?: string | null };
|
||||
export default function DeskCaseStateForm({
|
||||
dossier,
|
||||
activity,
|
||||
disabled = false,
|
||||
onChanged,
|
||||
}: {
|
||||
dossier: CaseState;
|
||||
activity: {
|
||||
open_requests: number | null;
|
||||
open_tasks: number | null;
|
||||
pending_payments: number | null;
|
||||
} | null;
|
||||
disabled?: boolean;
|
||||
onChanged?: () => void;
|
||||
}) {
|
||||
const target = dossier.closed_at ? 'open' : 'closed';
|
||||
const form = useForm({
|
||||
version: dossier.version,
|
||||
state: target,
|
||||
reason: '',
|
||||
client_key: createOperationKey(),
|
||||
});
|
||||
const stale =
|
||||
form.data.version !== dossier.version || form.data.state !== target;
|
||||
return (
|
||||
<form
|
||||
className={card + ' space-y-3'}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
if (form.processing || stale || disabled) return;
|
||||
form.put(`/balcao-virtual/dossiers/${dossier.id}/estado`, {
|
||||
onSuccess: (page) => {
|
||||
const current = page.props.case as
|
||||
| CaseState
|
||||
| undefined;
|
||||
if (
|
||||
current?.id === dossier.id &&
|
||||
Number.isInteger(current.version)
|
||||
) {
|
||||
form.setData('version', current.version);
|
||||
form.setData(
|
||||
'state',
|
||||
current.closed_at ? 'open' : 'closed',
|
||||
);
|
||||
form.reset('reason');
|
||||
form.setData('client_key', createOperationKey());
|
||||
onChanged?.();
|
||||
}
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<h2 className="text-xl font-bold">
|
||||
{target === 'closed' ? 'Encerrar dossier' : 'Reabrir dossier'}
|
||||
</h2>
|
||||
<p>
|
||||
Esta decisão pertence ao dono do dossier e fica registada com o
|
||||
motivo e a versão.
|
||||
</p>
|
||||
<p>
|
||||
{target === 'closed'
|
||||
? 'O encerramento deixa o dossier disponível para consulta. Mantém os estados e as pendências dos pedidos, pagamentos e tarefas.'
|
||||
: 'A reabertura permite continuar as operações autorizadas. Cada pedido, pagamento e tarefa mantém o seu estado e histórico.'}
|
||||
</p>
|
||||
<p>
|
||||
Pedidos em curso: {activity?.open_requests ?? 'por confirmar'} ·
|
||||
tarefas em curso: {activity?.open_tasks ?? 'por confirmar'} ·
|
||||
comprovativos por conferir:{' '}
|
||||
{activity?.pending_payments ?? 'por confirmar'}.
|
||||
</p>
|
||||
{stale && (
|
||||
<p role="alert">
|
||||
O dossier foi actualizado. Confira o estado actual antes de
|
||||
confirmar.{' '}
|
||||
<button
|
||||
type="button"
|
||||
disabled={form.processing}
|
||||
onClick={() => {
|
||||
form.setData('version', dossier.version);
|
||||
form.setData('state', target);
|
||||
form.setData('client_key', createOperationKey());
|
||||
}}
|
||||
>
|
||||
Usar estado actual, conservando o motivo
|
||||
</button>
|
||||
</p>
|
||||
)}
|
||||
<label className="block">
|
||||
Motivo{' '}
|
||||
{target === 'closed' ? 'do encerramento' : 'da reabertura'}
|
||||
<textarea
|
||||
className={input}
|
||||
required
|
||||
minLength={3}
|
||||
maxLength={5000}
|
||||
disabled={form.processing}
|
||||
value={form.data.reason}
|
||||
onChange={(event) => {
|
||||
form.setData('reason', event.target.value);
|
||||
form.setData('client_key', createOperationKey());
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
className={button}
|
||||
disabled={form.processing || stale || disabled}
|
||||
>
|
||||
{target === 'closed'
|
||||
? 'Confirmar encerramento do dossier'
|
||||
: 'Confirmar reabertura do dossier'}
|
||||
</button>
|
||||
{Object.entries(form.errors).map(([key, error]) => (
|
||||
<p role="alert" key={key}>
|
||||
{error}
|
||||
</p>
|
||||
))}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import { useId, useRef, useState } from 'react';
|
||||
import { profileJson } from '@/lib/profile-json';
|
||||
|
||||
export type ReusableDeskDocument = {
|
||||
id: string | null;
|
||||
document_id: string;
|
||||
file_name: string;
|
||||
version_no: number | null;
|
||||
source_reference: string | null;
|
||||
category: string | null;
|
||||
stage: string | null;
|
||||
valid_until: string | null;
|
||||
origin_label: string | null;
|
||||
status: string;
|
||||
malware_scan_status: string;
|
||||
media_type: string | null;
|
||||
size_bytes: number | null;
|
||||
};
|
||||
type Props = {
|
||||
caseId: string;
|
||||
disabled: boolean;
|
||||
selected: ReusableDeskDocument | null;
|
||||
onSelect: (document: ReusableDeskDocument | null) => void;
|
||||
};
|
||||
const key = (doc: ReusableDeskDocument) =>
|
||||
doc.id ?? `upload:${doc.document_id}`;
|
||||
|
||||
export default function DeskDocumentPicker(props: Props) {
|
||||
const group = useId();
|
||||
const [query, setQuery] = useState('');
|
||||
const [documents, setDocuments] = useState<ReusableDeskDocument[]>([]);
|
||||
const [next, setNext] = useState<number | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState('');
|
||||
const latest = useRef(props);
|
||||
latest.current = props;
|
||||
const sequence = useRef(0);
|
||||
|
||||
async function search(offset = 0) {
|
||||
if (busy || props.disabled) return;
|
||||
const ticket = ++sequence.current;
|
||||
const caseId = props.caseId;
|
||||
setBusy(true);
|
||||
setMessage('A pesquisar documentos autorizados…');
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
q: query,
|
||||
offset: String(offset),
|
||||
});
|
||||
const result = await profileJson(
|
||||
`/balcao-virtual/dossiers/${caseId}/documentos-disponiveis?${params}`,
|
||||
{},
|
||||
'GET',
|
||||
);
|
||||
if (ticket !== sequence.current || latest.current.caseId !== caseId)
|
||||
return;
|
||||
if (
|
||||
!Array.isArray(result.documents) ||
|
||||
(result.next_offset !== null &&
|
||||
!Number.isInteger(result.next_offset))
|
||||
)
|
||||
throw new Error(
|
||||
'Não foi possível confirmar os resultados. A selecção anterior foi conservada.',
|
||||
);
|
||||
setDocuments(result.documents);
|
||||
setNext(result.next_offset);
|
||||
setMessage(
|
||||
result.documents.length
|
||||
? 'Seleccione a origem que pretende reutilizar.'
|
||||
: 'Sem documentos nesta página. Pode ajustar a pesquisa ou continuar, se houver mais resultados.',
|
||||
);
|
||||
} catch (error) {
|
||||
if (ticket === sequence.current && latest.current.caseId === caseId)
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Não foi possível pesquisar documentos.',
|
||||
);
|
||||
} finally {
|
||||
if (ticket === sequence.current) setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2 rounded border p-3">
|
||||
<p>Reutilizar um documento autorizado</p>
|
||||
<p className="text-sm">
|
||||
Pesquise pelo nome do ficheiro, dossier ou referência. A
|
||||
selecção conserva a origem e a validade declarada; a associação
|
||||
exige confirmação.
|
||||
</p>
|
||||
<label className="block">
|
||||
Nome ou referência do documento
|
||||
<input
|
||||
value={query}
|
||||
maxLength={120}
|
||||
disabled={props.disabled || busy}
|
||||
onChange={(event) => {
|
||||
setQuery(event.target.value);
|
||||
setDocuments([]);
|
||||
setNext(null);
|
||||
setMessage(
|
||||
'Pesquisa alterada. Pesquise para actualizar os resultados.',
|
||||
);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
void search();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
disabled={props.disabled || busy}
|
||||
onClick={() => void search()}
|
||||
>
|
||||
Pesquisar documentos
|
||||
</button>
|
||||
<p role="status">{message}</p>
|
||||
{documents.map((doc) => (
|
||||
<label className="block" key={key(doc)}>
|
||||
<input
|
||||
type="radio"
|
||||
name={`document-origin-${group}`}
|
||||
checked={
|
||||
props.selected
|
||||
? key(props.selected) === key(doc)
|
||||
: false
|
||||
}
|
||||
disabled={props.disabled || busy}
|
||||
onChange={() => props.onSelect(doc)}
|
||||
/>{' '}
|
||||
{doc.file_name} · versão {doc.version_no ?? 'por confirmar'}{' '}
|
||||
· {doc.origin_label ?? 'Ficheiro enviado por si'} ·{' '}
|
||||
{doc.source_reference || 'Referência por completar'}
|
||||
{doc.stage ? ` · origem ${doc.stage}` : ''}
|
||||
{doc.valid_until
|
||||
? ` · validade declarada ${doc.valid_until}`
|
||||
: ''}{' '}
|
||||
· {doc.malware_scan_status}
|
||||
</label>
|
||||
))}
|
||||
{next !== null && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={props.disabled || busy}
|
||||
onClick={() => void search(next)}
|
||||
>
|
||||
Próxima página de documentos
|
||||
</button>
|
||||
)}
|
||||
{props.selected && (
|
||||
<div>
|
||||
<p>
|
||||
Origem seleccionada: {props.selected.file_name} ·{' '}
|
||||
{props.selected.source_reference ||
|
||||
'Referência por completar'}
|
||||
{props.selected.valid_until
|
||||
? ` · validade declarada ${props.selected.valid_until}`
|
||||
: ''}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
disabled={props.disabled || busy}
|
||||
onClick={() => props.onSelect(null)}
|
||||
>
|
||||
Retirar origem seleccionada
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,691 @@
|
||||
import { router } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { profileJson, ProfileValidationError } from '@/lib/profile-json';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import {
|
||||
checkpointRecovery,
|
||||
checkpointSignature,
|
||||
checkpointSame,
|
||||
type CheckpointView,
|
||||
type DeskAnswers,
|
||||
type RecoveryChoice,
|
||||
type CheckpointRequest,
|
||||
type CheckpointInput,
|
||||
} from '@/lib/desk-checkpoints';
|
||||
import type { DeskAnswer } from '@/lib/desk-field-values';
|
||||
|
||||
type Props = {
|
||||
id: string;
|
||||
version: number;
|
||||
payload: DeskAnswers;
|
||||
initial: DeskAnswers;
|
||||
reason: string;
|
||||
fields: Record<
|
||||
string,
|
||||
{ label: string; type?: string; options?: Record<string, string> }
|
||||
>;
|
||||
paused: boolean;
|
||||
pendingWork?: boolean;
|
||||
onBusy: (busy: boolean) => void;
|
||||
onBlocked: (blocked: boolean) => void;
|
||||
onRecover: (
|
||||
payload: DeskAnswers,
|
||||
reason: string,
|
||||
request: CheckpointRequest,
|
||||
) => void;
|
||||
};
|
||||
|
||||
const commonLabels: Record<string, string> = {
|
||||
country: 'País do requerente',
|
||||
declared_origin_country_code: 'País de origem',
|
||||
context_opportunity: 'Contexto da oportunidade',
|
||||
};
|
||||
|
||||
export default function DeskDraftRecovery(props: Props) {
|
||||
const latest = useRef(props);
|
||||
latest.current = props;
|
||||
const alive = useRef(true),
|
||||
busy = useRef(false),
|
||||
edited = useRef<string[]>([]);
|
||||
const previous = useRef(props.payload),
|
||||
base = useRef(props.initial);
|
||||
const previousReason = useRef(props.reason),
|
||||
reasonEdited = useRef(false),
|
||||
failedSignature = useRef('');
|
||||
const recoveryPending = useRef<{
|
||||
body: CheckpointInput;
|
||||
request: CheckpointRequest;
|
||||
payload: DeskAnswers;
|
||||
reason: string;
|
||||
} | null>(null);
|
||||
const view = useRef<CheckpointView | null>(null),
|
||||
pending = useRef<CheckpointInput | null>(null);
|
||||
const saved = useRef(
|
||||
checkpointSignature({ ...props.payload, __reason: props.reason }),
|
||||
);
|
||||
const force = useRef(false);
|
||||
const [state, setState] = useState<
|
||||
'loading' | 'ready' | 'saving' | 'error' | 'compare' | 'unavailable'
|
||||
>('loading');
|
||||
const [message, setMessage] = useState('A recuperar o estado do rascunho…');
|
||||
const [comparison, setComparison] = useState<CheckpointView | null>(null);
|
||||
const [choices, setChoices] = useState<Record<string, RecoveryChoice>>({});
|
||||
const [reasonChoice, setReasonChoice] = useState<'page' | 'saved'>('page');
|
||||
const [tick, setTick] = useState(0);
|
||||
const signature = checkpointSignature({
|
||||
...props.payload,
|
||||
__reason: props.reason,
|
||||
});
|
||||
const unsaved =
|
||||
props.pendingWork ||
|
||||
force.current ||
|
||||
signature !== saved.current ||
|
||||
pending.current !== null ||
|
||||
recoveryPending.current !== null;
|
||||
const markBusy = (value: boolean) => {
|
||||
busy.current = value;
|
||||
latest.current.onBusy(value);
|
||||
};
|
||||
const compare = (data: CheckpointView) => {
|
||||
view.current = data;
|
||||
setComparison(data);
|
||||
setChoices({});
|
||||
setReasonChoice(
|
||||
latest.current.reason || reasonEdited.current ? 'page' : 'saved',
|
||||
);
|
||||
setState('compare');
|
||||
latest.current.onBlocked(true);
|
||||
setMessage(
|
||||
'Compare o que está nesta página, o rascunho recuperado e o pedido actual.',
|
||||
);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
void profileJson(
|
||||
`/balcao-virtual/pedidos/${props.id}/rascunho`,
|
||||
{},
|
||||
'GET',
|
||||
)
|
||||
.then((data: CheckpointView) => {
|
||||
if (!alive.current) return;
|
||||
view.current = data;
|
||||
if (!data.installed) {
|
||||
setState('unavailable');
|
||||
setMessage(
|
||||
'Gravação automática ainda não instalada. Pode continuar a guardar manualmente.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
const different =
|
||||
data.checkpoint &&
|
||||
(checkpointSignature(data.checkpoint.payload) !==
|
||||
checkpointSignature(latest.current.payload) ||
|
||||
data.checkpoint.reason !== latest.current.reason);
|
||||
if (
|
||||
data.request.version !== props.version ||
|
||||
!data.request.can_edit ||
|
||||
different
|
||||
)
|
||||
compare(data);
|
||||
else {
|
||||
setState('ready');
|
||||
setMessage(
|
||||
data.checkpoint
|
||||
? 'Rascunho recuperável no servidor.'
|
||||
: 'A gravação automática acompanha as alterações.',
|
||||
);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (alive.current) {
|
||||
setState('unavailable');
|
||||
setMessage(
|
||||
'Não foi possível consultar a recuperação. As edições desta página e a gravação manual continuam disponíveis.',
|
||||
);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
alive.current = false;
|
||||
};
|
||||
}, [props.id, props.version]);
|
||||
|
||||
useEffect(() => {
|
||||
const keys = new Set([
|
||||
...Object.keys(previous.current),
|
||||
...Object.keys(props.payload),
|
||||
]);
|
||||
for (const key of keys)
|
||||
if (
|
||||
!checkpointSame(previous.current[key], props.payload[key]) &&
|
||||
!edited.current.includes(key)
|
||||
)
|
||||
edited.current.push(key);
|
||||
previous.current = props.payload;
|
||||
if (previousReason.current !== props.reason)
|
||||
reasonEdited.current = true;
|
||||
previousReason.current = props.reason;
|
||||
}, [props.payload, props.reason]);
|
||||
|
||||
async function persist() {
|
||||
const p = latest.current,
|
||||
current = view.current;
|
||||
if (
|
||||
busy.current ||
|
||||
p.paused ||
|
||||
!current?.installed ||
|
||||
!current.request.can_edit ||
|
||||
state === 'compare'
|
||||
)
|
||||
return;
|
||||
if (
|
||||
!pending.current &&
|
||||
!force.current &&
|
||||
checkpointSignature({ ...p.payload, __reason: p.reason }) ===
|
||||
saved.current
|
||||
)
|
||||
return;
|
||||
const body = pending.current ?? {
|
||||
version: current.checkpoint?.version ?? 0,
|
||||
request_version: current.request.version,
|
||||
operation_key: createOperationKey(),
|
||||
payload: structuredClone(p.payload),
|
||||
edited_keys: [...edited.current],
|
||||
reason: p.reason,
|
||||
};
|
||||
pending.current = body;
|
||||
markBusy(true);
|
||||
setState('saving');
|
||||
setMessage('A guardar automaticamente…');
|
||||
try {
|
||||
const data: CheckpointView = await profileJson(
|
||||
`/balcao-virtual/pedidos/${p.id}/rascunho`,
|
||||
body,
|
||||
);
|
||||
if (!alive.current) return;
|
||||
if (
|
||||
!data.checkpoint ||
|
||||
data.request.id !== p.id ||
|
||||
data.checkpoint.version !== body.version + 1 ||
|
||||
data.checkpoint.request_version !== body.request_version
|
||||
)
|
||||
throw new Error(
|
||||
'A resposta da gravação não confirmou a versão esperada. Compare com o servidor antes de continuar.',
|
||||
);
|
||||
view.current = data;
|
||||
pending.current = null;
|
||||
force.current = false;
|
||||
saved.current = checkpointSignature({
|
||||
...body.payload,
|
||||
__reason: body.reason,
|
||||
});
|
||||
setState('ready');
|
||||
setMessage(
|
||||
'Guardado automaticamente no servidor. Ainda não foi submetido.',
|
||||
);
|
||||
setTick((v) => v + 1);
|
||||
} catch (error) {
|
||||
if (!alive.current) return;
|
||||
failedSignature.current = checkpointSignature({
|
||||
...body.payload,
|
||||
__reason: body.reason,
|
||||
});
|
||||
if (
|
||||
error instanceof ProfileValidationError &&
|
||||
Object.keys(error.fields).length
|
||||
)
|
||||
pending.current = null;
|
||||
setState('error');
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'A gravação falhou. As alterações continuam nesta página.',
|
||||
);
|
||||
} finally {
|
||||
if (alive.current) markBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
state === 'error' &&
|
||||
pending.current === null &&
|
||||
signature !== failedSignature.current
|
||||
) {
|
||||
setState('ready');
|
||||
return;
|
||||
}
|
||||
if (state !== 'ready' || props.paused || !unsaved) return;
|
||||
const timer = setTimeout(() => void persist(), 2000);
|
||||
return () => clearTimeout(timer);
|
||||
}, [signature, state, props.paused, tick]);
|
||||
|
||||
useEffect(() => {
|
||||
const leave = (event: BeforeUnloadEvent) => {
|
||||
if (unsaved) {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
}
|
||||
};
|
||||
const stop = router.on('before', (event) => {
|
||||
if (
|
||||
event.detail.visit.method === 'get' &&
|
||||
unsaved &&
|
||||
!window.confirm(
|
||||
'Existem alterações ainda não guardadas automaticamente. Pretende sair desta página?',
|
||||
)
|
||||
)
|
||||
event.preventDefault();
|
||||
});
|
||||
window.addEventListener('beforeunload', leave);
|
||||
return () => {
|
||||
stop();
|
||||
window.removeEventListener('beforeunload', leave);
|
||||
};
|
||||
}, [unsaved]);
|
||||
|
||||
async function refresh() {
|
||||
if (busy.current) return;
|
||||
markBusy(true);
|
||||
try {
|
||||
const data: CheckpointView = await profileJson(
|
||||
`/balcao-virtual/pedidos/${props.id}/rascunho`,
|
||||
{},
|
||||
'GET',
|
||||
);
|
||||
if (alive.current) {
|
||||
pending.current = null;
|
||||
recoveryPending.current = null;
|
||||
if (data.installed) compare(data);
|
||||
else {
|
||||
setState('unavailable');
|
||||
setMessage(
|
||||
'Gravação automática ainda não instalada. Pode continuar a guardar manualmente.',
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (alive.current)
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Não foi possível comparar.',
|
||||
);
|
||||
} finally {
|
||||
if (alive.current) markBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const allowed = comparison
|
||||
? comparison.request.status === 'returned'
|
||||
? comparison.request.editable_fields
|
||||
: [
|
||||
...new Set([
|
||||
...Object.keys(props.fields),
|
||||
'country',
|
||||
'declared_origin_country_code',
|
||||
'context_reuse',
|
||||
'context_opportunity',
|
||||
'context_opportunity_snapshot',
|
||||
]),
|
||||
]
|
||||
: [];
|
||||
const recovery = comparison
|
||||
? checkpointRecovery(
|
||||
base.current,
|
||||
props.payload,
|
||||
edited.current,
|
||||
comparison.request.payload,
|
||||
comparison.checkpoint,
|
||||
allowed,
|
||||
choices,
|
||||
)
|
||||
: null;
|
||||
async function adopt(useSaved: boolean) {
|
||||
if (
|
||||
busy.current ||
|
||||
!comparison ||
|
||||
!comparison.request.can_edit ||
|
||||
(useSaved && recovery!.conflicts.length)
|
||||
)
|
||||
return;
|
||||
const payload = useSaved
|
||||
? recovery!.payload
|
||||
: { ...comparison.request.payload };
|
||||
if (!useSaved)
|
||||
for (const key of allowed)
|
||||
if (Object.hasOwn(props.payload, key))
|
||||
payload[key] = props.payload[key];
|
||||
const intent = useSaved
|
||||
? recovery!.intent
|
||||
: allowed.filter(
|
||||
(key) =>
|
||||
!checkpointSame(
|
||||
payload[key],
|
||||
comparison.request.payload[key],
|
||||
),
|
||||
);
|
||||
const reason =
|
||||
useSaved && reasonChoice === 'saved'
|
||||
? (comparison.checkpoint?.reason ?? '')
|
||||
: props.reason;
|
||||
const attempt = recoveryPending.current ?? {
|
||||
body: {
|
||||
version: comparison.checkpoint?.version ?? 0,
|
||||
request_version: comparison.request.version,
|
||||
operation_key: createOperationKey(),
|
||||
payload,
|
||||
edited_keys: intent,
|
||||
reason,
|
||||
},
|
||||
request: comparison.request,
|
||||
payload,
|
||||
reason,
|
||||
};
|
||||
recoveryPending.current = attempt;
|
||||
markBusy(true);
|
||||
try {
|
||||
const data: CheckpointView = await profileJson(
|
||||
`/balcao-virtual/pedidos/${props.id}/rascunho`,
|
||||
attempt.body,
|
||||
);
|
||||
if (!alive.current) return;
|
||||
if (
|
||||
!data.checkpoint ||
|
||||
data.request.id !== props.id ||
|
||||
data.checkpoint.version !== attempt.body.version + 1 ||
|
||||
data.checkpoint.request_version !== attempt.body.request_version
|
||||
)
|
||||
throw new Error(
|
||||
'A recuperação não confirmou a versão esperada. Compare com o servidor antes de continuar.',
|
||||
);
|
||||
previous.current = attempt.payload;
|
||||
base.current = attempt.request.payload;
|
||||
view.current = data;
|
||||
edited.current = attempt.body.edited_keys;
|
||||
pending.current = null;
|
||||
recoveryPending.current = null;
|
||||
force.current = false;
|
||||
saved.current = checkpointSignature({
|
||||
...attempt.payload,
|
||||
__reason: attempt.reason,
|
||||
});
|
||||
setComparison(null);
|
||||
setState('ready');
|
||||
latest.current.onBlocked(false);
|
||||
latest.current.onRecover(
|
||||
attempt.payload,
|
||||
attempt.reason,
|
||||
attempt.request,
|
||||
);
|
||||
setMessage(
|
||||
'Rascunho recuperado e guardado no servidor, sem submeter.',
|
||||
);
|
||||
setTick((v) => v + 1);
|
||||
} catch (error) {
|
||||
if (alive.current)
|
||||
setMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'A recuperação não foi guardada. Repita a mesma tentativa ou compare novamente.',
|
||||
);
|
||||
} finally {
|
||||
if (alive.current) markBusy(false);
|
||||
}
|
||||
}
|
||||
const display = (value: DeskAnswer | undefined, key: string) =>
|
||||
value === null || value === undefined || value === ''
|
||||
? 'Por preencher'
|
||||
: Array.isArray(value)
|
||||
? value
|
||||
.map(
|
||||
(code) =>
|
||||
props.fields[key]?.options?.[code] ??
|
||||
(props.fields[key]?.type === 'attachment'
|
||||
? 'Documento por recuperar na lista actual'
|
||||
: code),
|
||||
)
|
||||
.join(' · ')
|
||||
: props.fields[key]?.type === 'consent'
|
||||
? value === 'accepted'
|
||||
? 'Aceite'
|
||||
: value === 'declined'
|
||||
? 'Recusado'
|
||||
: String(value)
|
||||
: (props.fields[key]?.options?.[String(value)] ??
|
||||
String(value));
|
||||
return (
|
||||
<section
|
||||
className="space-y-3 rounded border p-3"
|
||||
aria-label="Recuperação do rascunho"
|
||||
>
|
||||
<h2 className="font-bold">Gravação automática do rascunho</h2>
|
||||
<p role="status" aria-live="polite">
|
||||
{message}
|
||||
</p>
|
||||
<p>
|
||||
As respostas ficam cifradas no servidor para a sua conta,
|
||||
incluindo valores ainda incompletos. Esta gravação não submete,
|
||||
não revê o contexto e não autoriza a submissão.
|
||||
</p>
|
||||
{unsaved && state !== 'compare' && (
|
||||
<p>
|
||||
Existem alterações nesta página ainda por guardar
|
||||
automaticamente.
|
||||
</p>
|
||||
)}
|
||||
{state === 'error' && (
|
||||
<>
|
||||
<button type="button" onClick={() => void persist()}>
|
||||
Tentar novamente a mesma gravação
|
||||
</button>
|
||||
<button type="button" onClick={() => void refresh()}>
|
||||
Comparar com o servidor
|
||||
</button>
|
||||
<p>
|
||||
Se a sessão expirou, mantenha esta página e
|
||||
autentique-se noutro separador antes de tentar
|
||||
novamente.
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
{state === 'unavailable' && (
|
||||
<button type="button" onClick={() => void refresh()}>
|
||||
Voltar a consultar a recuperação
|
||||
</button>
|
||||
)}
|
||||
{comparison && recovery && (
|
||||
<>
|
||||
<p>
|
||||
Pedido actual: versão {comparison.request.version}.{' '}
|
||||
{comparison.checkpoint && (
|
||||
<>
|
||||
Rascunho automático: versão{' '}
|
||||
{comparison.checkpoint.version}, guardado em{' '}
|
||||
{comparison.checkpoint.updated_at}.
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
{!comparison.request.can_edit ? (
|
||||
<p>
|
||||
O pedido já não permite edição. As respostas desta
|
||||
página são conservadas aqui; pode consultar o pedido
|
||||
actual antes de sair.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="overflow-x-auto">
|
||||
<table>
|
||||
<caption>
|
||||
Comparação das respostas a recuperar
|
||||
</caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Campo</th>
|
||||
<th>Nesta página</th>
|
||||
<th>Guardado automaticamente</th>
|
||||
<th>Pedido actual</th>
|
||||
<th>Escolha</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{recovery.rows.map((row) => (
|
||||
<tr key={row.key}>
|
||||
<th>
|
||||
{props.fields[row.key]
|
||||
?.label ??
|
||||
commonLabels[row.key] ??
|
||||
row.key}
|
||||
</th>
|
||||
<td className="whitespace-pre-wrap">
|
||||
{display(row.page, row.key)}
|
||||
</td>
|
||||
<td className="whitespace-pre-wrap">
|
||||
{display(
|
||||
row.saved,
|
||||
row.key,
|
||||
)}
|
||||
</td>
|
||||
<td className="whitespace-pre-wrap">
|
||||
{display(
|
||||
row.current,
|
||||
row.key,
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<label>
|
||||
Resposta a conservar{' '}
|
||||
{row.conflict &&
|
||||
!choices[row.key] &&
|
||||
'(escolha necessária)'}
|
||||
<select
|
||||
disabled={
|
||||
busy.current ||
|
||||
recoveryPending.current !==
|
||||
null
|
||||
}
|
||||
value={
|
||||
choices[
|
||||
row.key
|
||||
] ??
|
||||
(row.conflict
|
||||
? ''
|
||||
: row.choice)
|
||||
}
|
||||
onChange={(e) =>
|
||||
setChoices(
|
||||
(c) => ({
|
||||
...c,
|
||||
[row.key]:
|
||||
e
|
||||
.target
|
||||
.value as RecoveryChoice,
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<option
|
||||
value=""
|
||||
disabled
|
||||
>
|
||||
Escolha uma
|
||||
resposta
|
||||
</option>
|
||||
<option value="page">
|
||||
Nesta página
|
||||
</option>
|
||||
{comparison.checkpoint && (
|
||||
<option value="saved">
|
||||
Guardado
|
||||
automaticamente
|
||||
</option>
|
||||
)}
|
||||
<option value="current">
|
||||
Pedido actual
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{comparison.checkpoint && (
|
||||
<label>
|
||||
Justificação de correcção a recuperar
|
||||
<select
|
||||
disabled={
|
||||
busy.current ||
|
||||
recoveryPending.current !== null
|
||||
}
|
||||
value={reasonChoice}
|
||||
onChange={(e) =>
|
||||
setReasonChoice(
|
||||
e.target.value === 'saved'
|
||||
? 'saved'
|
||||
: 'page',
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="page">
|
||||
Nesta página:{' '}
|
||||
{props.reason || 'Por preencher'}
|
||||
</option>
|
||||
<option value="saved">
|
||||
Guardada:{' '}
|
||||
{comparison.checkpoint.reason ||
|
||||
'Por preencher'}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<p>
|
||||
Em pedidos devolvidos, apenas os campos
|
||||
autorizados são recuperados. A autorização de
|
||||
submissão e a revisão do contexto têm de ser
|
||||
confirmadas de novo.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
disabled={
|
||||
recovery.conflicts.length > 0 ||
|
||||
busy.current
|
||||
}
|
||||
onClick={() => void adopt(true)}
|
||||
>
|
||||
Recuperar as respostas escolhidas
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={
|
||||
busy.current ||
|
||||
recoveryPending.current !== null
|
||||
}
|
||||
onClick={() => void adopt(false)}
|
||||
>
|
||||
Manter esta página e substituir o rascunho
|
||||
automático
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy.current}
|
||||
onClick={() => void refresh()}
|
||||
>
|
||||
Actualizar a comparação
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{state === 'error' && message && (
|
||||
<p role="alert">
|
||||
A gravação automática está interrompida. {message}
|
||||
{message &&
|
||||
pending.current &&
|
||||
' A tentativa anterior é conservada para repetição sem duplicação.'}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { card, input, button } from '@/pages/investment/shared';
|
||||
import DeskPaymentDocumentForm from './desk-payment-document-form';
|
||||
|
||||
export type DeskDocument = {
|
||||
id: string;
|
||||
@@ -10,6 +11,12 @@ export type DeskDocument = {
|
||||
malware_scan_status: string;
|
||||
category: string;
|
||||
source_reference: string;
|
||||
request_id?: string | null;
|
||||
media_type?: string | null;
|
||||
size_bytes?: number | null;
|
||||
version_no?: number | null;
|
||||
stage?: string | null;
|
||||
valid_until?: string | null;
|
||||
};
|
||||
export function DocumentReview({
|
||||
caseId,
|
||||
@@ -163,6 +170,14 @@ export type DeskPayment = {
|
||||
verified_by: number | null;
|
||||
reason: string | null;
|
||||
version: number;
|
||||
document_evidence?: {
|
||||
link_id: string;
|
||||
file_name: string;
|
||||
document_version: number;
|
||||
source_reference: string;
|
||||
sha256: string;
|
||||
valid_until: string | null;
|
||||
} | null;
|
||||
};
|
||||
export function RequestOperations({
|
||||
requestId,
|
||||
@@ -182,7 +197,7 @@ export function RequestOperations({
|
||||
amount: '',
|
||||
currency: 'MZN',
|
||||
source_reference: '',
|
||||
document_id: '',
|
||||
document_link_id: '',
|
||||
consent: false,
|
||||
});
|
||||
const review = useForm({
|
||||
@@ -221,10 +236,35 @@ export function RequestOperations({
|
||||
: 'Declarado — por conferir'}
|
||||
</p>
|
||||
<p>Fonte do valor: {p.source_reference}</p>
|
||||
{p.document_evidence ? (
|
||||
<p>
|
||||
Comprovativo: {p.document_evidence.file_name} ·
|
||||
versão {p.document_evidence.document_version} ·
|
||||
referência documental:{' '}
|
||||
{p.document_evidence.source_reference}
|
||||
{p.document_evidence.valid_until
|
||||
? ` · validade declarada ${p.document_evidence.valid_until}`
|
||||
: ''}
|
||||
</p>
|
||||
) : (
|
||||
<p>
|
||||
{p.document_id
|
||||
? 'Comprovativo associado em registo anterior; metadados da associação não capturados à época.'
|
||||
: 'Comprovativo ainda não associado.'}
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
Responsável pela conferência:{' '}
|
||||
{p.verified_by ?? 'Ainda sem conferência'} · {p.reason}
|
||||
</p>
|
||||
{owner &&
|
||||
['pending', 'internal_issue'].includes(p.status) && (
|
||||
<DeskPaymentDocumentForm
|
||||
requestId={requestId}
|
||||
payment={p}
|
||||
documents={documents}
|
||||
/>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
{owner && (
|
||||
@@ -240,6 +280,10 @@ export function RequestOperations({
|
||||
<h3 className="font-bold">
|
||||
Registar referência e comprovativo
|
||||
</h3>
|
||||
<p>
|
||||
Se esta referência já está registada acima, junte ou
|
||||
corrija o comprovativo nesse registo.
|
||||
</p>
|
||||
<label>
|
||||
Referência fornecida
|
||||
<input
|
||||
@@ -297,17 +341,22 @@ export function RequestOperations({
|
||||
Comprovativo associado ao mesmo dossier
|
||||
<select
|
||||
className={input}
|
||||
value={payment.data.document_id}
|
||||
value={payment.data.document_link_id}
|
||||
onChange={(e) =>
|
||||
payment.setData('document_id', e.target.value)
|
||||
payment.setData(
|
||||
'document_link_id',
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
Pendente — registar referência agora
|
||||
</option>
|
||||
{documents.map((d) => (
|
||||
<option key={d.id} value={d.document_id}>
|
||||
{d.file_name}
|
||||
<option key={d.id} value={d.id}>
|
||||
{d.file_name} · versão{' '}
|
||||
{d.version_no ?? 'por confirmar'} ·{' '}
|
||||
{d.source_reference}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import { button, card, input } from '@/pages/investment/shared';
|
||||
import type { DeskDocument, DeskPayment } from './desk-internal-operations';
|
||||
|
||||
export default function DeskPaymentDocumentForm({
|
||||
requestId,
|
||||
payment,
|
||||
documents,
|
||||
}: {
|
||||
requestId: string;
|
||||
payment: DeskPayment;
|
||||
documents: DeskDocument[];
|
||||
}) {
|
||||
const form = useForm({
|
||||
version: payment.version,
|
||||
document_link_id: '',
|
||||
reason: '',
|
||||
consent: false,
|
||||
client_key: createOperationKey(),
|
||||
});
|
||||
return (
|
||||
<form
|
||||
className={card + ' space-y-3'}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
if (form.processing || form.data.version !== payment.version)
|
||||
return;
|
||||
form.put(
|
||||
`/balcao-virtual/pedidos/${requestId}/pagamentos/${payment.id}/comprovativo`,
|
||||
{
|
||||
onSuccess: () => {
|
||||
form.reset('document_link_id', 'reason', 'consent');
|
||||
form.setData('version', form.data.version + 1);
|
||||
form.setData('client_key', createOperationKey());
|
||||
},
|
||||
},
|
||||
);
|
||||
}}
|
||||
>
|
||||
<h4 className="font-bold">
|
||||
{payment.document_id
|
||||
? 'Corrigir comprovativo deste registo'
|
||||
: 'Juntar comprovativo a este registo'}
|
||||
</h4>
|
||||
<p>
|
||||
A referência, o valor e a moeda já registados são conservados. O
|
||||
comprovativo ficará por conferir; o histórico da conferência
|
||||
anterior é preservado.
|
||||
</p>
|
||||
{form.data.version !== payment.version && (
|
||||
<p role="alert">
|
||||
Este registo foi actualizado. Confira a versão actual antes
|
||||
de continuar.{' '}
|
||||
<button
|
||||
type="button"
|
||||
disabled={form.processing}
|
||||
onClick={() => {
|
||||
form.setData('version', payment.version);
|
||||
form.setData('client_key', createOperationKey());
|
||||
form.setData('consent', false);
|
||||
}}
|
||||
>
|
||||
Usar versão actual, conservando a selecção
|
||||
</button>
|
||||
</p>
|
||||
)}
|
||||
<label className="block">
|
||||
Comprovativo já associado ao pedido ou dossier
|
||||
<select
|
||||
className={input}
|
||||
required
|
||||
disabled={form.processing}
|
||||
value={form.data.document_link_id}
|
||||
onChange={(event) => {
|
||||
form.setData('document_link_id', event.target.value);
|
||||
form.setData('client_key', createOperationKey());
|
||||
form.setData('consent', false);
|
||||
}}
|
||||
>
|
||||
<option value="">Seleccione o documento de suporte</option>
|
||||
{documents.map((doc) => (
|
||||
<option key={doc.id} value={doc.id}>
|
||||
{doc.file_name} · versão{' '}
|
||||
{doc.version_no ?? 'por confirmar'} ·{' '}
|
||||
{doc.source_reference}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<p>
|
||||
Se o original ainda não está associado, utilize os anexos do
|
||||
pedido ou os documentos do dossier e regresse a este registo.
|
||||
</p>
|
||||
<label className="block">
|
||||
Motivo da associação ou correcção
|
||||
<textarea
|
||||
className={input}
|
||||
required
|
||||
minLength={3}
|
||||
maxLength={3000}
|
||||
disabled={form.processing}
|
||||
value={form.data.reason}
|
||||
onChange={(event) => {
|
||||
form.setData('reason', event.target.value);
|
||||
form.setData('client_key', createOperationKey());
|
||||
form.setData('consent', false);
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<label className="flex gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
required
|
||||
disabled={form.processing}
|
||||
checked={form.data.consent}
|
||||
onChange={(event) =>
|
||||
form.setData('consent', event.target.checked)
|
||||
}
|
||||
/>
|
||||
Autorizo associar este comprovativo ao registo existente.
|
||||
</label>
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
form.processing || form.data.version !== payment.version
|
||||
}
|
||||
>
|
||||
Guardar comprovativo no mesmo registo
|
||||
</button>
|
||||
{Object.entries(form.errors).map(([key, error]) => (
|
||||
<p role="alert" key={key}>
|
||||
{error}
|
||||
</p>
|
||||
))}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -9,6 +9,7 @@ type Version = {
|
||||
author_id: number | null;
|
||||
published_by: number | null;
|
||||
published_at: string | null;
|
||||
effective_from?: string | null;
|
||||
definition: Definition;
|
||||
source: { identifier?: string; edition?: string; sha256?: string };
|
||||
reason: string | null;
|
||||
@@ -147,6 +148,17 @@ export default function DeskServiceHistory({
|
||||
{publishedDate(version.published_at)}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Entrada em vigor
|
||||
</dt>
|
||||
<dd>
|
||||
{version.effective_from ||
|
||||
'Sem data explícita (versão histórica)'}
|
||||
. Pedidos existentes mantêm esta versão,
|
||||
mesmo após uma edição posterior.
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Motivo registado
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { deskChoices, deskScalar } from '@/lib/desk-field-values';
|
||||
|
||||
export default function DeskTypedChoice({
|
||||
fieldKey,
|
||||
field,
|
||||
value,
|
||||
disabled,
|
||||
onChange,
|
||||
}: {
|
||||
fieldKey: string;
|
||||
field: {
|
||||
type: string;
|
||||
label: string;
|
||||
required: boolean;
|
||||
options?: Record<string, string>;
|
||||
statement?: string;
|
||||
};
|
||||
value: unknown;
|
||||
disabled: boolean;
|
||||
onChange: (value: string | string[]) => void;
|
||||
}) {
|
||||
return (
|
||||
<fieldset disabled={disabled} className="space-y-2 rounded border p-3">
|
||||
<legend>
|
||||
{field.label}
|
||||
{field.required ? ' *' : ''}
|
||||
</legend>
|
||||
{field.type === 'multiselect' ? (
|
||||
<>
|
||||
<p>
|
||||
Seleccione as opções aplicáveis.{' '}
|
||||
{field.required &&
|
||||
'Ao submeter, escolha pelo menos uma.'}
|
||||
</p>
|
||||
{Object.entries(field.options ?? {}).map(
|
||||
([code, label]) => (
|
||||
<label className="block" key={code}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={deskChoices(value).includes(code)}
|
||||
onChange={(event) =>
|
||||
onChange(
|
||||
event.target.checked
|
||||
? [...deskChoices(value), code]
|
||||
: deskChoices(value).filter(
|
||||
(v) => v !== code,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>{' '}
|
||||
{label}
|
||||
</label>
|
||||
),
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="whitespace-pre-wrap">{field.statement}</p>
|
||||
<p>
|
||||
Registe a sua escolha. Uma resposta obrigatória exige
|
||||
escolher aceitar ou recusar; não exige aceitar.
|
||||
</p>
|
||||
{Object.entries({
|
||||
accepted: 'Aceito esta declaração',
|
||||
declined: 'Não aceito esta declaração',
|
||||
}).map(([code, label]) => (
|
||||
<label className="block" key={code}>
|
||||
<input
|
||||
type="radio"
|
||||
name={'desk-declaration-' + fieldKey}
|
||||
checked={deskScalar(value) === code}
|
||||
onChange={() => onChange(code)}
|
||||
/>{' '}
|
||||
{label}
|
||||
</label>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
onClick={() => onChange('')}
|
||||
>
|
||||
Deixar por responder
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
import { useEducationReview } from '@/lib/education-review';
|
||||
import type { EducationReviewProps } from '@/lib/education-review';
|
||||
import { Field, button, control } from '@/pages/management/shared';
|
||||
const states: Record<string, string> = {
|
||||
submitted: 'Submetida',
|
||||
reviewed: 'Revista internamente',
|
||||
rejected: 'Rejeitada',
|
||||
};
|
||||
export default function EducationReview(props: EducationReviewProps) {
|
||||
const edit = useEducationReview(props),
|
||||
{ form } = edit,
|
||||
row = props.declaration;
|
||||
return (
|
||||
<section
|
||||
className="space-y-4"
|
||||
aria-label="Revisão interna da declaração"
|
||||
>
|
||||
{edit.notice && <p role="status">{edit.notice}</p>}
|
||||
{(edit.stale || edit.conflict) && (
|
||||
<section
|
||||
className="space-y-3 rounded border p-4"
|
||||
aria-label="Comparação da declaração"
|
||||
>
|
||||
<h2 className="font-semibold">A declaração mudou</h2>
|
||||
<p>
|
||||
Compare a versão analisada com os dados actuais antes de
|
||||
confirmar a decisão.
|
||||
</p>
|
||||
<dl className="space-y-2">
|
||||
<dt>Qualificação</dt>
|
||||
<dd>
|
||||
Analisada: {edit.base.qualification} · Actual:{' '}
|
||||
{edit.current.qualification}
|
||||
</dd>
|
||||
<dt>
|
||||
Quantidade de{' '}
|
||||
{props.kind === 'demands'
|
||||
? 'trabalhadores'
|
||||
: 'vagas formativas'}
|
||||
</dt>
|
||||
<dd>
|
||||
Analisada: {edit.base.quantity} · Actual:{' '}
|
||||
{edit.current.quantity}
|
||||
</dd>
|
||||
<dt>Período</dt>
|
||||
<dd>
|
||||
Analisado: {edit.base.period_start} a{' '}
|
||||
{edit.base.period_end} · Actual:{' '}
|
||||
{edit.current.period_start} a{' '}
|
||||
{edit.current.period_end}
|
||||
</dd>
|
||||
<dt>Validade da fonte</dt>
|
||||
<dd>
|
||||
Analisada: {edit.base.valid_until} · Actual:{' '}
|
||||
{edit.current.valid_until}
|
||||
</dd>
|
||||
<dt>Fonte</dt>
|
||||
<dd className="break-words whitespace-pre-wrap">
|
||||
Analisada: {edit.base.source} · Actual:{' '}
|
||||
{edit.current.source}
|
||||
</dd>
|
||||
<dt>Data de referência</dt>
|
||||
<dd>
|
||||
Analisada:{' '}
|
||||
{edit.base.reference_date || 'Não identificada'} ·
|
||||
Actual:{' '}
|
||||
{edit.current.reference_date || 'Não identificada'}
|
||||
</dd>
|
||||
{props.kind === 'demands' && (
|
||||
<>
|
||||
<dt>Empregador declarado</dt>
|
||||
<dd>
|
||||
Analisado:{' '}
|
||||
{edit.base.employer || 'Não identificado'} ·
|
||||
Actual:{' '}
|
||||
{edit.current.employer ||
|
||||
'Não identificado'}
|
||||
</dd>
|
||||
</>
|
||||
)}
|
||||
{Array.from(
|
||||
new Set([
|
||||
...Object.keys(edit.base.references),
|
||||
...Object.keys(edit.current.references),
|
||||
]),
|
||||
).map((field) => (
|
||||
<div key={field}>
|
||||
<dt>
|
||||
{(
|
||||
{
|
||||
occupation: 'Ocupação',
|
||||
skill: 'Competência',
|
||||
project: 'Projecto',
|
||||
course: 'Curso',
|
||||
location: 'Localização',
|
||||
} as Record<string, string>
|
||||
)[field] ?? 'Referência'}
|
||||
</dt>
|
||||
<dd>
|
||||
Analisada:{' '}
|
||||
{edit.base.references[field] ||
|
||||
'Não identificada'}{' '}
|
||||
· Actual:{' '}
|
||||
{edit.current.references[field] ||
|
||||
'Não identificada'}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
<dt>Estado</dt>
|
||||
<dd>
|
||||
Analisado:{' '}
|
||||
{states[edit.base.status] ?? edit.base.status} ·
|
||||
Actual:{' '}
|
||||
{states[edit.current.status] ?? edit.current.status}
|
||||
</dd>
|
||||
</dl>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={edit.refresh}
|
||||
disabled={edit.refreshing || form.processing}
|
||||
>
|
||||
Actualizar declaração
|
||||
</button>
|
||||
{edit.canAdopt && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={edit.adopt}
|
||||
>
|
||||
Confirmar a leitura desta versão
|
||||
</button>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
{row.can_review !== true && !edit.uncertain ? (
|
||||
<p>
|
||||
{row.review_unavailable === 'self'
|
||||
? 'Esta declaração foi submetida por si. A revisão cabe a outro gestor.'
|
||||
: row.review_unavailable === 'expired'
|
||||
? 'A fonte expirou. A declaração permanece disponível para consulta.'
|
||||
: 'Actualize a declaração para confirmar as opções de revisão.'}
|
||||
</p>
|
||||
) : (
|
||||
<form
|
||||
id="education-review"
|
||||
className="max-w-xl space-y-3"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
edit.submit();
|
||||
}}
|
||||
>
|
||||
<h2 className="text-lg font-semibold">
|
||||
Decisão de revisão interna
|
||||
</h2>
|
||||
{edit.uncertain && (
|
||||
<p>
|
||||
A recuperação repete a decisão enviada:{' '}
|
||||
{states[edit.sent?.status ?? ''] ?? 'Por confirmar'}
|
||||
. Fundamento: {edit.sent?.review_reason}. As edições
|
||||
posteriores ficam conservadas.
|
||||
</p>
|
||||
)}
|
||||
<Field label="Decisão interna" error={form.errors.status}>
|
||||
<select
|
||||
className={control}
|
||||
value={form.data.status}
|
||||
onChange={(event) =>
|
||||
edit.change('status', event.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"
|
||||
error={form.errors.review_reason}
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
required
|
||||
minLength={15}
|
||||
maxLength={3000}
|
||||
value={form.data.review_reason}
|
||||
onChange={(event) =>
|
||||
edit.change('review_reason', event.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{form.errors.version_no && (
|
||||
<p role="alert">
|
||||
Actualize e compare a declaração antes de continuar.
|
||||
A decisão preparada foi conservada.
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<button
|
||||
className={button}
|
||||
disabled={edit.blocked || form.processing}
|
||||
>
|
||||
{edit.uncertain
|
||||
? 'Recuperar a mesma revisão'
|
||||
: 'Guardar decisão'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={edit.refresh}
|
||||
disabled={edit.refreshing || form.processing}
|
||||
>
|
||||
Actualizar dados da declaração
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
{row.can_review !== true &&
|
||||
!edit.uncertain &&
|
||||
form.data.review_reason && (
|
||||
<p className="break-words whitespace-pre-wrap">
|
||||
Fundamento preparado nesta página:{' '}
|
||||
{form.data.review_reason}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
|
||||
export type EducationDraft = {
|
||||
id: string;
|
||||
kind: 'demands' | 'capacities';
|
||||
version_no: number;
|
||||
state: 'draft' | 'submitted';
|
||||
updated_at: string;
|
||||
payload: Record<string, string | number | null>;
|
||||
record_id: string | null;
|
||||
references: {
|
||||
project_id?: { name?: string };
|
||||
course_id?: { title?: string };
|
||||
occupation_id?: { name?: string };
|
||||
skill_id?: { name?: string };
|
||||
territory_path?: { name: string }[];
|
||||
} | null;
|
||||
};
|
||||
export type EducationDraftSummary = Pick<
|
||||
EducationDraft,
|
||||
'id' | 'kind' | 'version_no' | 'state' | 'updated_at'
|
||||
> & { label?: string | null };
|
||||
|
||||
export default function EducationSubmittedSnapshot({
|
||||
draft,
|
||||
}: {
|
||||
draft: EducationDraft;
|
||||
}) {
|
||||
const labels: Record<string, string> = {
|
||||
employer: 'Empregador declarante',
|
||||
qualification: 'Qualificação',
|
||||
quantity:
|
||||
draft.kind === 'demands'
|
||||
? 'Trabalhadores necessários'
|
||||
: 'Vagas formativas',
|
||||
period_start: 'Início do período',
|
||||
period_end: 'Fim do período',
|
||||
reference_date: 'Data de referência da fonte',
|
||||
valid_until: 'Fonte válida até',
|
||||
source: 'Fonte e evidência',
|
||||
};
|
||||
return (
|
||||
<section className="rounded border p-4">
|
||||
<h2 className="text-xl font-semibold">Declaração submetida</h2>
|
||||
<p>
|
||||
Os dados abaixo conservam a submissão efectuada. A revisão
|
||||
independente mantém o seu percurso; esta consulta não certifica
|
||||
a instituição ou formação.
|
||||
</p>
|
||||
<dl className="my-4 space-y-2">
|
||||
{Object.entries(labels)
|
||||
.filter(
|
||||
([key]) =>
|
||||
draft.payload[key] !== undefined &&
|
||||
draft.payload[key] !== null &&
|
||||
draft.payload[key] !== '',
|
||||
)
|
||||
.map(([key, label]) => (
|
||||
<div key={key}>
|
||||
<dt className="font-semibold">{label}</dt>
|
||||
<dd className="whitespace-pre-wrap">
|
||||
{draft.payload[key]}
|
||||
</dd>
|
||||
</div>
|
||||
))}
|
||||
{draft.references && (
|
||||
<>
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
{draft.kind === 'demands'
|
||||
? 'Projecto utilizado'
|
||||
: 'Curso utilizado'}
|
||||
</dt>
|
||||
<dd>
|
||||
{draft.references.project_id?.name ??
|
||||
draft.references.course_id?.title ??
|
||||
'Referência conservada'}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">
|
||||
Ocupação / competência utilizadas
|
||||
</dt>
|
||||
<dd>
|
||||
{draft.references.occupation_id?.name} /{' '}
|
||||
{draft.references.skill_id?.name}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="font-semibold">Local utilizado</dt>
|
||||
<dd>
|
||||
{draft.references.territory_path
|
||||
?.map((node) => node.name)
|
||||
.join(' / ') || 'Referência conservada'}
|
||||
</dd>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</dl>
|
||||
{draft.kind === 'demands' && draft.record_id && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/management/education/demands/${draft.record_id}/analysis`}
|
||||
>
|
||||
Consultar análise e estado actual
|
||||
</Link>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import { useState } from 'react';
|
||||
import { portalRequest } from '@/lib/portal-api';
|
||||
import { card, button } from '@/pages/investment/shared';
|
||||
import type { Programme } from '@/pages/funding/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 FundingCriteriaAssessment({
|
||||
record,
|
||||
}: {
|
||||
record: Programme;
|
||||
}) {
|
||||
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 selectedWindow = record.payload.windows.find(
|
||||
(item) => item.code === windowCode,
|
||||
);
|
||||
const criteria = [
|
||||
...record.payload.criteria,
|
||||
...(selectedWindow?.criteria ?? []),
|
||||
];
|
||||
const applicable = criteria.filter(
|
||||
(item) => item.applies_to === 'all' || item.applies_to === kind,
|
||||
);
|
||||
const awaitingType = criteria.filter(
|
||||
(item) => item.applies_to !== 'all' && kind === 'unknown',
|
||||
).length;
|
||||
const notApplicable = criteria.length - applicable.length - awaitingType;
|
||||
function resetResult() {
|
||||
setAssessment(null);
|
||||
setError('');
|
||||
}
|
||||
async function assess() {
|
||||
setBusy(true);
|
||||
resetResult();
|
||||
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(
|
||||
applicable.map((item) => [
|
||||
item.code,
|
||||
answers[item.code] ?? 'unknown',
|
||||
]),
|
||||
),
|
||||
}),
|
||||
},
|
||||
),
|
||||
);
|
||||
} catch (failure) {
|
||||
setError(
|
||||
failure instanceof Error
|
||||
? failure.message
|
||||
: 'Não foi possível conferir os critérios.',
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<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
|
||||
name="applicant-kind"
|
||||
disabled={busy}
|
||||
className="m-2 rounded border p-2"
|
||||
value={kind}
|
||||
onChange={(event) => {
|
||||
setKind(event.target.value);
|
||||
resetResult();
|
||||
}}
|
||||
>
|
||||
<option value="unknown">Por definir</option>
|
||||
<option value="individual">Pessoa singular</option>
|
||||
<option value="entity">Entidade</option>
|
||||
</select>
|
||||
</label>
|
||||
{record.payload.windows.length > 0 && (
|
||||
<label className="block">
|
||||
Janela
|
||||
<select
|
||||
name="funding-window"
|
||||
disabled={busy}
|
||||
className="m-2 rounded border p-2"
|
||||
value={windowCode}
|
||||
onChange={(event) => {
|
||||
setWindowCode(event.target.value);
|
||||
resetResult();
|
||||
}}
|
||||
>
|
||||
<option value="">Apenas critérios gerais</option>
|
||||
{record.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>
|
||||
)}
|
||||
{awaitingType > 0 && (
|
||||
<p>
|
||||
Escolha o tipo de candidato para apresentar os{' '}
|
||||
{awaitingType} critérios específicos. Sem essa escolha,
|
||||
ficam por confirmar.
|
||||
</p>
|
||||
)}
|
||||
{notApplicable > 0 && (
|
||||
<p>
|
||||
{notApplicable} critérios de outro tipo de candidato não se
|
||||
aplicam à escolha indicada.
|
||||
</p>
|
||||
)}
|
||||
{applicable.map((item) => (
|
||||
<div key={item.code} className="my-4">
|
||||
<label>
|
||||
{item.question}
|
||||
<select
|
||||
name={`criterion-${item.code}`}
|
||||
disabled={busy}
|
||||
className="m-2 rounded border p-2"
|
||||
value={answers[item.code] ?? 'unknown'}
|
||||
onChange={(event) => {
|
||||
setAnswers({
|
||||
...answers,
|
||||
[item.code]: event.target.value,
|
||||
});
|
||||
resetResult();
|
||||
}}
|
||||
>
|
||||
<option value="unknown">
|
||||
Não sei / por confirmar
|
||||
</option>
|
||||
<option value="yes">Sim</option>
|
||||
<option value="no">Não</option>
|
||||
</select>
|
||||
</label>
|
||||
<p>{item.explanation}</p>
|
||||
<p>Fonte: {item.source_reference}</p>
|
||||
{assessment && (
|
||||
<p>
|
||||
{
|
||||
statusLabels[
|
||||
assessment.criteria.find(
|
||||
(result) => result.code === item.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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
import { useEffect, useId } from 'react';
|
||||
import CountrySelect, { type Country } from './country-select';
|
||||
import OrganizationCountryReuse from './organization-country-reuse';
|
||||
import { Field, input, button } from '@/pages/investment/shared';
|
||||
import {
|
||||
useInvestmentProfileEditor,
|
||||
type ProfileRecord,
|
||||
type OrganizationRecord,
|
||||
} from '@/lib/investment-profile-editor';
|
||||
|
||||
export default function InvestmentProfileEditor({
|
||||
record,
|
||||
fields,
|
||||
countries,
|
||||
company = false,
|
||||
actorId,
|
||||
editorId,
|
||||
reportDirty,
|
||||
labels,
|
||||
organizations = [],
|
||||
}: {
|
||||
record: ProfileRecord;
|
||||
fields: string[];
|
||||
countries: Country[];
|
||||
company?: boolean;
|
||||
actorId: number;
|
||||
editorId: string;
|
||||
reportDirty: (id: string, dirty: boolean) => void;
|
||||
labels: Record<string, string>;
|
||||
organizations?: OrganizationRecord[];
|
||||
}) {
|
||||
const isCompany = company || !!record.id;
|
||||
const editor = useInvestmentProfileEditor(
|
||||
record,
|
||||
fields,
|
||||
isCompany,
|
||||
actorId,
|
||||
editorId,
|
||||
reportDirty,
|
||||
);
|
||||
const id = useId(),
|
||||
disabled =
|
||||
editor.busy ||
|
||||
editor.uncertain ||
|
||||
editor.blocked ||
|
||||
editor.externalBusy;
|
||||
useEffect(() => {
|
||||
if (Object.keys(editor.errors).length)
|
||||
document
|
||||
.getElementById(id)
|
||||
?.querySelector<HTMLElement>('[aria-invalid="true"]')
|
||||
?.focus();
|
||||
}, [editor.errors, id]);
|
||||
const fieldErrorKeys = [
|
||||
...fields.map((key) => 'payload.' + key),
|
||||
...(isCompany ? ['payload.country'] : []),
|
||||
];
|
||||
return (
|
||||
<>
|
||||
<form
|
||||
id={id}
|
||||
aria-label={
|
||||
isCompany
|
||||
? record.id
|
||||
? 'Declaração de empresa'
|
||||
: 'Nova declaração de empresa'
|
||||
: 'Perfil de investimento'
|
||||
}
|
||||
className="mt-4 space-y-4"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
void editor.save();
|
||||
}}
|
||||
>
|
||||
<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) => {
|
||||
const fieldId = id + '-' + key,
|
||||
error =
|
||||
editor.errors['payload.' + key] ??
|
||||
(key === 'incorporation_country_code'
|
||||
? editor.errors['payload.country']
|
||||
: undefined),
|
||||
long = [
|
||||
'description',
|
||||
'experience',
|
||||
'investment_capacity',
|
||||
].includes(key);
|
||||
return (
|
||||
<Field key={key} label={labels[key]}>
|
||||
{key.endsWith('_country_code') ? (
|
||||
<CountrySelect
|
||||
id={fieldId}
|
||||
countries={countries}
|
||||
label={labels[key]}
|
||||
error={error}
|
||||
value={editor.draft[key]}
|
||||
disabled={disabled}
|
||||
required={
|
||||
isCompany &&
|
||||
key ===
|
||||
'incorporation_country_code' &&
|
||||
!editor.draft.country
|
||||
}
|
||||
onChange={(value) =>
|
||||
editor.change(key, value)
|
||||
}
|
||||
/>
|
||||
) : long ? (
|
||||
<textarea
|
||||
id={fieldId}
|
||||
aria-label={labels[key]}
|
||||
className={input}
|
||||
value={editor.draft[key]}
|
||||
disabled={disabled}
|
||||
rows={3}
|
||||
maxLength={
|
||||
key === 'investment_capacity'
|
||||
? 1000
|
||||
: 2000
|
||||
}
|
||||
aria-invalid={!!error}
|
||||
aria-describedby={
|
||||
error
|
||||
? fieldId + '-error'
|
||||
: undefined
|
||||
}
|
||||
onChange={(event) =>
|
||||
editor.change(
|
||||
key,
|
||||
event.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
id={fieldId}
|
||||
aria-label={labels[key]}
|
||||
className={input}
|
||||
value={editor.draft[key]}
|
||||
disabled={disabled}
|
||||
required={
|
||||
isCompany &&
|
||||
['name', 'role'].includes(key)
|
||||
}
|
||||
maxLength={
|
||||
key === 'phone'
|
||||
? 30
|
||||
: key === 'registration'
|
||||
? 100
|
||||
: ['role', 'sector'].includes(
|
||||
key,
|
||||
)
|
||||
? 150
|
||||
: 200
|
||||
}
|
||||
aria-invalid={!!error}
|
||||
aria-describedby={
|
||||
error
|
||||
? fieldId + '-error'
|
||||
: undefined
|
||||
}
|
||||
onChange={(event) =>
|
||||
editor.change(
|
||||
key,
|
||||
event.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{!key.endsWith('_country_code') && error && (
|
||||
<p
|
||||
id={fieldId + '-error'}
|
||||
role="alert"
|
||||
className="text-red-700"
|
||||
>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</Field>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{editor.error && <p role="alert">{editor.error}</p>}
|
||||
{Object.entries(editor.errors)
|
||||
.filter(([key]) => !fieldErrorKeys.includes(key))
|
||||
.map(([key, value]) => (
|
||||
<p role="alert" key={key}>
|
||||
{value}
|
||||
</p>
|
||||
))}
|
||||
{editor.notice && <p role="status">{editor.notice}</p>}
|
||||
{editor.stale && (
|
||||
<p role="alert">
|
||||
Existe uma versão mais recente deste registo. A sua
|
||||
preparação foi conservada; consulte e compare antes de
|
||||
guardar.
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
editor.busy ||
|
||||
editor.externalBusy ||
|
||||
editor.reading ||
|
||||
editor.blocked ||
|
||||
(editor.stale && !editor.uncertain)
|
||||
}
|
||||
>
|
||||
{editor.uncertain
|
||||
? 'Repetir o mesmo pedido'
|
||||
: isCompany
|
||||
? 'Guardar declaração da empresa'
|
||||
: 'Guardar perfil de investimento'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={
|
||||
editor.busy || editor.externalBusy || editor.reading
|
||||
}
|
||||
onClick={() => void editor.refresh()}
|
||||
>
|
||||
Consultar registo guardado
|
||||
</button>
|
||||
</div>
|
||||
{editor.remote && (
|
||||
<section
|
||||
aria-label="Comparação do registo guardado"
|
||||
className="space-y-3 rounded border p-3"
|
||||
>
|
||||
<p>
|
||||
Versão guardada: {editor.remote.version}; versão da
|
||||
preparação: {editor.base.version}.
|
||||
</p>
|
||||
<table className="w-full text-left text-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Campo</th>
|
||||
<th>Preparação nesta página</th>
|
||||
<th>Registo guardado</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{fields
|
||||
.filter(
|
||||
(key) =>
|
||||
editor.draft[key] !==
|
||||
editor.remote?.payload[key],
|
||||
)
|
||||
.map((key) => (
|
||||
<tr key={key}>
|
||||
<th>{labels[key]}</th>
|
||||
<td className="break-words">
|
||||
{editor.draft[key] ||
|
||||
'Não informado'}
|
||||
</td>
|
||||
<td className="break-words">
|
||||
{editor.remote?.payload[key] ||
|
||||
'Não informado'}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{!editor.uncertain && (
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() => editor.adopt(true)}
|
||||
>
|
||||
Usar versão actual e manter a preparação
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() => {
|
||||
if (
|
||||
window.confirm(
|
||||
'Substituir a preparação desta página pelos valores guardados?',
|
||||
)
|
||||
)
|
||||
editor.adopt(false);
|
||||
}}
|
||||
>
|
||||
Carregar os valores guardados
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
</form>
|
||||
{isCompany && record.id && (
|
||||
<OrganizationCountryReuse
|
||||
companyId={record.id}
|
||||
actorId={actorId}
|
||||
organizations={organizations}
|
||||
editor={editor}
|
||||
reportDirty={reportDirty}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -33,6 +33,7 @@ export type Guidance = {
|
||||
rules_version: string;
|
||||
computed_at: string;
|
||||
can_write: boolean;
|
||||
can_update_tasks?: boolean;
|
||||
facts: Record<string, string>;
|
||||
financial_draft: Record<string, unknown> | null;
|
||||
consulted: {
|
||||
@@ -725,21 +726,25 @@ export function InvestorGuidance({
|
||||
Consultar o pedido e a resposta do responsável
|
||||
</Link>
|
||||
)}
|
||||
{(manager || actorId === task.assignee_user_id) && (
|
||||
<>
|
||||
<label className="block">
|
||||
Resultado ou motivo
|
||||
<textarea
|
||||
className={input}
|
||||
value={reason}
|
||||
onChange={(e) =>
|
||||
setReason(e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{['in_progress', 'done', 'cancelled'].map(
|
||||
(status) => (
|
||||
{guidance.can_update_tasks !== false &&
|
||||
(manager || actorId === task.assignee_user_id) && (
|
||||
<>
|
||||
<label className="block">
|
||||
Resultado ou motivo
|
||||
<textarea
|
||||
className={input}
|
||||
value={reason}
|
||||
onChange={(e) =>
|
||||
setReason(e.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{[
|
||||
'in_progress',
|
||||
'done',
|
||||
'cancelled',
|
||||
].map((status) => (
|
||||
<button
|
||||
key={status}
|
||||
type="button"
|
||||
@@ -763,11 +768,10 @@ export function InvestorGuidance({
|
||||
? 'Registar conclusão'
|
||||
: 'Cancelar tarefa'}
|
||||
</button>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
{!guidance.tasks.length && (
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import {
|
||||
incidentOperationLabel,
|
||||
incidentErrorLabel,
|
||||
} from '@/lib/technical-incident-labels';
|
||||
|
||||
export type OpportunityTechnicalIncident = {
|
||||
reference: string;
|
||||
operation: string;
|
||||
version: number;
|
||||
occurred_at: string;
|
||||
error_code: string;
|
||||
handling?: {
|
||||
version: number;
|
||||
status: string;
|
||||
updated_at: string | null;
|
||||
} | null;
|
||||
};
|
||||
|
||||
export default function OpportunityTechnicalIncidents({
|
||||
incidents,
|
||||
}: {
|
||||
incidents: OpportunityTechnicalIncident[];
|
||||
}) {
|
||||
if (!incidents.length) return null;
|
||||
return (
|
||||
<section
|
||||
className="space-y-3 rounded border p-4"
|
||||
aria-label="As minhas tentativas com falha técnica"
|
||||
>
|
||||
<h2 className="text-lg font-semibold">
|
||||
As minhas tentativas com falha técnica
|
||||
</h2>
|
||||
<p>
|
||||
Últimos dez registos desta conta. Consulte o estado actual antes
|
||||
de repetir uma operação. Um incidente não confirma nem desfaz
|
||||
uma gravação, submissão ou publicação.
|
||||
</p>
|
||||
<p>
|
||||
Guarde a referência para acompanhamento. O Suporte técnico
|
||||
consulta os incidentes no âmbito da sua atribuição e não altera
|
||||
a decisão de investimento.
|
||||
</p>
|
||||
{incidents.map((incident) => (
|
||||
<article
|
||||
key={incident.reference}
|
||||
className="space-y-1 border-t pt-2"
|
||||
>
|
||||
<h3 className="font-semibold">
|
||||
{incidentOperationLabel(incident.operation)} · versão
|
||||
observada {incident.version}
|
||||
</h3>
|
||||
<p>{incident.occurred_at}</p>
|
||||
{incident.handling ? (
|
||||
<p>
|
||||
Estado técnico:{' '}
|
||||
{(
|
||||
{
|
||||
open: 'Na fila',
|
||||
in_progress: 'Em tratamento',
|
||||
resolved: 'Resolvido',
|
||||
} as Record<string, string>
|
||||
)[incident.handling.status] || 'Não identificado'}
|
||||
</p>
|
||||
) : (
|
||||
<p>Estado técnico indisponível para consulta.</p>
|
||||
)}
|
||||
<p>{incidentErrorLabel(incident.error_code)}</p>
|
||||
{incident.operation === 'scan_document' && (
|
||||
<p>
|
||||
O recurso já foi registado. Acompanhe o estado da
|
||||
análise de segurança antes de pedir nova análise.
|
||||
</p>
|
||||
)}
|
||||
<p className="break-all">
|
||||
Referência para acompanhamento: {incident.reference}
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
import { useEffect, useId } from 'react';
|
||||
import CountrySelect, { type Country } from './country-select';
|
||||
import { Field, input, button, card } from '@/pages/investment/shared';
|
||||
import {
|
||||
useInvestmentProfileEditor,
|
||||
type OrganizationRecord,
|
||||
} from '@/lib/investment-profile-editor';
|
||||
|
||||
export default function OrganizationCountryEditor({
|
||||
organization,
|
||||
countries,
|
||||
actorId,
|
||||
reportDirty,
|
||||
}: {
|
||||
organization: OrganizationRecord;
|
||||
countries: Country[];
|
||||
actorId: number;
|
||||
reportDirty: (id: string, dirty: boolean) => void;
|
||||
}) {
|
||||
const fields = ['country', 'source_reference'];
|
||||
const editor = useInvestmentProfileEditor(
|
||||
{
|
||||
id: organization.id,
|
||||
version: organization.version,
|
||||
payload: {
|
||||
country: organization.country ?? '',
|
||||
source_reference: organization.provenance?.reference ?? '',
|
||||
},
|
||||
},
|
||||
fields,
|
||||
false,
|
||||
actorId,
|
||||
'organization-' + organization.id,
|
||||
reportDirty,
|
||||
organization,
|
||||
);
|
||||
const id = useId(),
|
||||
disabled =
|
||||
!editor.mayEdit ||
|
||||
editor.busy ||
|
||||
editor.uncertain ||
|
||||
editor.blocked;
|
||||
useEffect(() => {
|
||||
if (Object.keys(editor.errors).length)
|
||||
document
|
||||
.getElementById(id)
|
||||
?.querySelector<HTMLElement>('[aria-invalid="true"]')
|
||||
?.focus();
|
||||
}, [editor.errors, id]);
|
||||
return (
|
||||
<section
|
||||
className={card}
|
||||
aria-label={'País de constituição: ' + organization.name}
|
||||
>
|
||||
<h3 className="text-xl font-bold">{organization.name}</h3>
|
||||
<p>
|
||||
Versão guardada: {organization.version}.{' '}
|
||||
{organization.provenance?.kind === 'representative_declaration'
|
||||
? 'País declarado pelo representante.'
|
||||
: 'Fonte do país ainda não informada.'}
|
||||
</p>
|
||||
{!editor.mayEdit && (
|
||||
<p role="status">
|
||||
Consulta do país de constituição. A sua representação actual
|
||||
não permite alterar esta informação.
|
||||
</p>
|
||||
)}
|
||||
<form
|
||||
id={id}
|
||||
className="mt-4 space-y-4"
|
||||
aria-label={'País da organização: ' + organization.name}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
void editor.save();
|
||||
}}
|
||||
>
|
||||
<Field label="País de constituição da organização">
|
||||
<CountrySelect
|
||||
id={id + '-country'}
|
||||
label="País de constituição da organização"
|
||||
required
|
||||
countries={countries}
|
||||
value={editor.draft.country}
|
||||
disabled={disabled}
|
||||
error={editor.errors.country}
|
||||
onChange={(country) =>
|
||||
editor.change('country', country)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
<label htmlFor={id + '-source'}>
|
||||
Fonte ou referência deste país
|
||||
</label>
|
||||
<textarea
|
||||
id={id + '-source'}
|
||||
aria-label="Fonte ou referência deste país"
|
||||
className={input}
|
||||
value={editor.draft.source_reference}
|
||||
disabled={disabled}
|
||||
required
|
||||
minLength={5}
|
||||
maxLength={2000}
|
||||
rows={3}
|
||||
aria-invalid={!!editor.errors.source_reference}
|
||||
aria-describedby={
|
||||
editor.errors.source_reference
|
||||
? id + '-source-error'
|
||||
: undefined
|
||||
}
|
||||
onChange={(event) =>
|
||||
editor.change('source_reference', event.target.value)
|
||||
}
|
||||
/>
|
||||
{editor.errors.source_reference && (
|
||||
<p id={id + '-source-error'} role="alert">
|
||||
{editor.errors.source_reference}
|
||||
</p>
|
||||
)}
|
||||
{Object.entries(editor.errors)
|
||||
.filter(([key]) => !fields.includes(key))
|
||||
.map(([key, value]) => (
|
||||
<p role="alert" key={key}>
|
||||
{value}
|
||||
</p>
|
||||
))}
|
||||
{editor.error && <p role="alert">{editor.error}</p>}
|
||||
{editor.notice && <p role="status">{editor.notice}</p>}
|
||||
{editor.stale && (
|
||||
<p role="alert">
|
||||
O país ou outra informação da organização foi alterado.
|
||||
A sua preparação foi conservada; consulte e compare
|
||||
antes de guardar.
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{editor.mayEdit && (
|
||||
<button
|
||||
className={button}
|
||||
disabled={
|
||||
editor.busy ||
|
||||
editor.reading ||
|
||||
editor.blocked ||
|
||||
(editor.stale && !editor.uncertain)
|
||||
}
|
||||
>
|
||||
{editor.uncertain
|
||||
? 'Repetir o mesmo pedido'
|
||||
: 'Guardar país da organização'}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
className={button}
|
||||
type="button"
|
||||
disabled={editor.busy || editor.reading}
|
||||
onClick={() => void editor.refresh()}
|
||||
>
|
||||
Consultar país guardado
|
||||
</button>
|
||||
</div>
|
||||
{editor.remote && (
|
||||
<section
|
||||
aria-label="Comparação do país da organização"
|
||||
className="space-y-3 rounded border p-3"
|
||||
>
|
||||
<p>
|
||||
Versão guardada: {editor.remote.version}; versão da
|
||||
preparação: {editor.base.version}.
|
||||
</p>
|
||||
<table className="w-full text-left text-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Campo</th>
|
||||
<th>Preparação nesta página</th>
|
||||
<th>Registo guardado</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{fields
|
||||
.filter(
|
||||
(key) =>
|
||||
editor.draft[key] !==
|
||||
editor.remote?.payload[key],
|
||||
)
|
||||
.map((key) => (
|
||||
<tr key={key}>
|
||||
<th>
|
||||
{key === 'country'
|
||||
? 'País de constituição'
|
||||
: 'Fonte ou referência'}
|
||||
</th>
|
||||
<td className="break-words">
|
||||
{editor.draft[key] ||
|
||||
'Não informado'}
|
||||
</td>
|
||||
<td className="break-words">
|
||||
{editor.remote?.payload[key] ||
|
||||
'Não informado'}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{editor.mayEdit && !editor.uncertain && (
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() => editor.adopt(true)}
|
||||
>
|
||||
Usar versão actual e manter a preparação
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() => {
|
||||
if (
|
||||
window.confirm(
|
||||
'Substituir a preparação desta organização pelos valores guardados?',
|
||||
)
|
||||
)
|
||||
editor.adopt(false);
|
||||
}}
|
||||
>
|
||||
Carregar os valores guardados
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
</form>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { button } from '@/pages/investment/shared';
|
||||
import { useOrganizationCountryReuse } from '@/lib/organization-country-reuse';
|
||||
import type {
|
||||
useInvestmentProfileEditor,
|
||||
OrganizationRecord,
|
||||
} from '@/lib/investment-profile-editor';
|
||||
|
||||
export default function OrganizationCountryReuse({
|
||||
companyId,
|
||||
actorId,
|
||||
organizations,
|
||||
editor,
|
||||
reportDirty,
|
||||
}: {
|
||||
companyId: string;
|
||||
actorId: number;
|
||||
organizations: OrganizationRecord[];
|
||||
editor: ReturnType<typeof useInvestmentProfileEditor>;
|
||||
reportDirty: (id: string, dirty: boolean) => void;
|
||||
}) {
|
||||
const reuse = useOrganizationCountryReuse(
|
||||
companyId,
|
||||
actorId,
|
||||
editor,
|
||||
reportDirty,
|
||||
organizations,
|
||||
);
|
||||
const preview = reuse.preview;
|
||||
const sources = organizations.filter((source) => source.country);
|
||||
if (
|
||||
!organizations.length &&
|
||||
!preview &&
|
||||
!reuse.uncertain &&
|
||||
!reuse.error &&
|
||||
!reuse.notice
|
||||
)
|
||||
return null;
|
||||
return (
|
||||
<section
|
||||
aria-label="Reutilizar país de uma organização"
|
||||
className="mt-4 space-y-3 rounded border p-3"
|
||||
>
|
||||
<h4 className="font-bold">Reutilizar o país de constituição</h4>
|
||||
<p>
|
||||
Escolha uma organização representada para consultar o país
|
||||
guardado. A confirmação altera esta declaração; manifestações
|
||||
anteriores conservam os seus valores.
|
||||
</p>
|
||||
{editor.dirty && !editor.externalBusy && (
|
||||
<p>
|
||||
Guarde ou confirme a preparação da declaração antes de
|
||||
reutilizar o país.
|
||||
</p>
|
||||
)}
|
||||
{!reuse.uncertain && (
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{sources.map((source) => (
|
||||
<button
|
||||
key={source.id}
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={
|
||||
reuse.busy ||
|
||||
reuse.reading ||
|
||||
editor.dirty ||
|
||||
editor.blocked ||
|
||||
editor.stale
|
||||
}
|
||||
onClick={() => void reuse.inspect(source.id)}
|
||||
>
|
||||
Consultar país de {source.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{!sources.length && !reuse.uncertain && (
|
||||
<p>
|
||||
Sem país guardado nas organizações representadas nesta
|
||||
página.
|
||||
</p>
|
||||
)}
|
||||
{reuse.error && <p role="alert">{reuse.error}</p>}
|
||||
{reuse.notice && <p role="status">{reuse.notice}</p>}
|
||||
{reuse.sourceChanged && (
|
||||
<p role="alert">
|
||||
A organização foi alterada. Consulte novamente o país antes
|
||||
de confirmar.
|
||||
</p>
|
||||
)}
|
||||
{preview && (
|
||||
<section
|
||||
aria-label="Confirmar reutilização do país"
|
||||
className="space-y-3"
|
||||
>
|
||||
<p>
|
||||
Declaração: versão {preview.companyVersion}; país
|
||||
actual: {preview.companyCountry || 'Não informado'}.
|
||||
</p>
|
||||
<p>
|
||||
País a reutilizar: {preview.country}, de{' '}
|
||||
{preview.organizationName}, versão{' '}
|
||||
{preview.organizationVersion}.
|
||||
</p>
|
||||
<p>
|
||||
Fonte ou referência:{' '}
|
||||
{preview.reference ||
|
||||
'Não informada no registo guardado'}
|
||||
.
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={
|
||||
reuse.busy ||
|
||||
reuse.reading ||
|
||||
reuse.blocked ||
|
||||
reuse.sourceChanged
|
||||
}
|
||||
onClick={() => void reuse.confirm()}
|
||||
>
|
||||
{reuse.uncertain
|
||||
? 'Repetir a mesma reutilização'
|
||||
: 'Confirmar reutilização do país'}
|
||||
</button>
|
||||
{reuse.uncertain ? (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={reuse.busy || reuse.reading}
|
||||
onClick={() =>
|
||||
void reuse.inspect(
|
||||
reuse.pendingOrganizationId ??
|
||||
preview.organizationId,
|
||||
)
|
||||
}
|
||||
>
|
||||
Consultar estado da reutilização
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={reuse.busy || reuse.reading}
|
||||
onClick={reuse.cancel}
|
||||
>
|
||||
Cancelar preparação da reutilização
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { agreementParties, readAgreement } from '@/lib/partnership-agreement';
|
||||
|
||||
export default function AgreementInstrument({ value }: { value: unknown }) {
|
||||
const instrument = readAgreement(value);
|
||||
if (instrument.kind === 'absent')
|
||||
return <p>Não ficou registado um instrumento nesta versão.</p>;
|
||||
if (instrument.kind === 'malformed')
|
||||
return (
|
||||
<p role="alert">
|
||||
O instrumento guardado não tem uma estrutura reconhecida. O
|
||||
registo foi conservado.
|
||||
</p>
|
||||
);
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<h3 className="font-bold">
|
||||
{instrument.title === null
|
||||
? 'Título não registado'
|
||||
: instrument.title || 'Título não indicado'}
|
||||
</h3>
|
||||
<p className="whitespace-pre-wrap">
|
||||
{instrument.terms === null
|
||||
? 'Condições não registadas'
|
||||
: instrument.terms || 'Condições não indicadas'}
|
||||
</p>
|
||||
{instrument.confirmationsState === 'absent' ? (
|
||||
<p>As confirmações não ficaram registadas neste instrumento.</p>
|
||||
) : instrument.confirmationsState === 'malformed' ? (
|
||||
<p role="alert">
|
||||
As confirmações guardadas não têm uma estrutura reconhecida.
|
||||
O registo foi conservado.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
{!Object.keys(instrument.confirmations).length && (
|
||||
<p>Confirmações: Pendentes</p>
|
||||
)}
|
||||
{agreementParties.map((party) => {
|
||||
const stamp = instrument.confirmations[party];
|
||||
if (!stamp)
|
||||
return (
|
||||
<p key={party}>
|
||||
{party === 'proponent'
|
||||
? 'Proponente'
|
||||
: 'Candidata'}
|
||||
: sem confirmação registada.
|
||||
</p>
|
||||
);
|
||||
return (
|
||||
<div key={party}>
|
||||
<p>
|
||||
{party === 'proponent'
|
||||
? 'Proponente'
|
||||
: 'Candidata'}
|
||||
:{' '}
|
||||
{stamp.actorId === null
|
||||
? 'Registo de confirmação incompleto'
|
||||
: `autor ${stamp.actorName ?? stamp.actorId}`}{' '}
|
||||
· {stamp.date ?? 'Data não registada'}
|
||||
</p>
|
||||
{stamp.reason !== null && (
|
||||
<p className="whitespace-pre-wrap">
|
||||
Motivo: {stamp.reason || 'Não indicado'}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{instrument.extraConfirmations && (
|
||||
<p>
|
||||
Existem referências adicionais no registo; não
|
||||
substituem a confirmação de cada parte.
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<p>
|
||||
Estado de assinatura guardado:{' '}
|
||||
{instrument.legalStatus === 'not_verified'
|
||||
? 'não verificada'
|
||||
: (instrument.legalStatus ?? 'não registado')}
|
||||
. Esta consulta não certifica assinatura jurídica.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,730 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Link, usePage } from '@inertiajs/react';
|
||||
import {
|
||||
criterionValue,
|
||||
useCandidacyEdit,
|
||||
useCandidacyLeaveGuard,
|
||||
type CandidacyEditor,
|
||||
} from '@/lib/partnership-candidacy-edit';
|
||||
import {
|
||||
Field,
|
||||
Errors,
|
||||
control,
|
||||
button,
|
||||
labels,
|
||||
type Interest,
|
||||
type Catalogues,
|
||||
type Partnership,
|
||||
} from '@/pages/partnerships/shared';
|
||||
export type CandidacyProps = {
|
||||
record: Partnership;
|
||||
owner: boolean;
|
||||
canEdit: boolean;
|
||||
acceptingInterests: boolean;
|
||||
canStartInterest: boolean;
|
||||
interests: Interest[];
|
||||
organizations: Catalogues['organizations'];
|
||||
};
|
||||
type DraftReporter = (id: string, dirty: boolean) => void;
|
||||
function useReport(editor: CandidacyEditor, id: string, report: DraftReporter) {
|
||||
useEffect(() => {
|
||||
report(id, editor.dirty);
|
||||
}, [report, id, editor.dirty]);
|
||||
useEffect(() => () => report(id, false), [report, id]);
|
||||
}
|
||||
const submissionLabels: Record<string, string> = {
|
||||
organization_id: 'Participação',
|
||||
proposal: 'Proposta curta',
|
||||
capacity: 'Capacidade disponível',
|
||||
availability: 'Disponibilidade',
|
||||
contribution: 'Contribuição proposta',
|
||||
conflicts: 'Conflitos de interesse declarados',
|
||||
consent: 'Autorização de partilha',
|
||||
};
|
||||
function Comparison({
|
||||
editor,
|
||||
organizations,
|
||||
}: {
|
||||
editor: CandidacyEditor;
|
||||
organizations: Catalogues['organizations'];
|
||||
}) {
|
||||
const label = (key: string) =>
|
||||
key.startsWith('criterion:')
|
||||
? (editor.criterionLabels[key.slice('criterion:'.length)] ??
|
||||
'Critério já indisponível')
|
||||
: (submissionLabels[key] ?? 'Motivo da acção');
|
||||
const display = (key: string, value: string | undefined) =>
|
||||
key.startsWith('criterion:')
|
||||
? `${labels[criterionValue(value).state]} — ${criterionValue(value).evidence || 'Sem referência de evidência'}`
|
||||
: key === 'organization_id'
|
||||
? value
|
||||
? (organizations.find(
|
||||
(organization) => organization.id === value,
|
||||
)?.name ?? 'Organização já indisponível')
|
||||
: 'Sem organização indicada'
|
||||
: key === 'consent'
|
||||
? value === 'yes'
|
||||
? 'Autorizada'
|
||||
: 'Não autorizada'
|
||||
: value || 'Não indicado';
|
||||
return (
|
||||
<div className="space-y-3 rounded border p-3">
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
disabled={editor.refreshing || editor.form.processing}
|
||||
onClick={editor.refresh}
|
||||
>
|
||||
Comparar com os dados actuais da candidatura
|
||||
</button>
|
||||
{editor.problem && <p role="alert">{editor.problem}</p>}
|
||||
{editor.invalid && (
|
||||
<p role="alert">
|
||||
A candidatura não está disponível para este formulário com o
|
||||
acesso actual. A preparação foi conservada e a gravação está
|
||||
suspensa.
|
||||
</p>
|
||||
)}
|
||||
{!editor.editable && editor.dirty && (
|
||||
<p role="status">
|
||||
O estado ou acesso actual não permite novas alterações. A
|
||||
preparação abaixo foi conservada em memória, sem nova
|
||||
autorização.
|
||||
</p>
|
||||
)}
|
||||
{editor.refreshing && (
|
||||
<p role="status">A recuperar sem apagar a preparação.</p>
|
||||
)}
|
||||
{editor.stale && (
|
||||
<>
|
||||
<p role="alert">
|
||||
A candidatura, a parceria ou os critérios foram
|
||||
alterados. Reveja as declarações e os requisitos actuais
|
||||
antes de continuar.
|
||||
</p>
|
||||
{editor.changed.length > 0 && (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left text-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Campo</th>
|
||||
<th>Actualmente guardado</th>
|
||||
<th>Sua preparação</th>
|
||||
<th>Escolha</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{editor.changed.map((key) => (
|
||||
<tr key={key}>
|
||||
<td>{label(key)}</td>
|
||||
<td className="whitespace-pre-wrap">
|
||||
{display(
|
||||
key,
|
||||
editor.current[key],
|
||||
)}
|
||||
</td>
|
||||
<td className="whitespace-pre-wrap">
|
||||
{display(
|
||||
key,
|
||||
editor.values[key],
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
{editor.conflicts.includes(
|
||||
key,
|
||||
) ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
editor.choose(
|
||||
key,
|
||||
'current',
|
||||
)
|
||||
}
|
||||
>
|
||||
Usar valor actual
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
editor.choose(
|
||||
key,
|
||||
'mine',
|
||||
)
|
||||
}
|
||||
>
|
||||
Manter minha
|
||||
alteração
|
||||
</button>
|
||||
{editor.unresolved.includes(
|
||||
key,
|
||||
) && (
|
||||
<p>
|
||||
Escolha o valor
|
||||
a conservar.
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
'Actualização compatível'
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
disabled={
|
||||
editor.invalid ||
|
||||
editor.refreshing ||
|
||||
editor.form.processing ||
|
||||
editor.unresolved.length > 0
|
||||
}
|
||||
onClick={editor.adopt}
|
||||
>
|
||||
Usar este contexto e conservar as alterações escolhidas
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{editor.retired.length > 0 && (
|
||||
<details>
|
||||
<summary>
|
||||
Critérios anteriores conservados apenas nesta preparação
|
||||
</summary>
|
||||
{editor.retired.map((key) => (
|
||||
<p key={key}>
|
||||
{label(key)}: {display(key, editor.values[key])}
|
||||
</p>
|
||||
))}
|
||||
<p>
|
||||
Estes critérios já não pertencem à avaliação actual e
|
||||
não serão enviados.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
disabled={editor.form.processing || editor.recovering}
|
||||
onClick={editor.discardRetired}
|
||||
>
|
||||
Descartar preparação dos critérios anteriores
|
||||
</button>
|
||||
<p>
|
||||
Esta acção só descarta a preparação local; não altera o
|
||||
histórico guardado.
|
||||
</p>
|
||||
</details>
|
||||
)}
|
||||
{editor.recovering && (
|
||||
<p role="status">
|
||||
Recuperar repete o pedido original. As alterações escritas
|
||||
depois do envio ficam para uma próxima operação.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function Submission({
|
||||
p,
|
||||
recordId,
|
||||
interestId = null,
|
||||
actorId,
|
||||
report,
|
||||
onCreated,
|
||||
suppressed = false,
|
||||
}: {
|
||||
p: CandidacyProps;
|
||||
recordId: number;
|
||||
interestId?: number | null;
|
||||
actorId: number | null;
|
||||
report: DraftReporter;
|
||||
onCreated?: (id: number | null) => void;
|
||||
suppressed?: boolean;
|
||||
}) {
|
||||
const editor = useCandidacyEdit({
|
||||
props: p,
|
||||
recordId,
|
||||
interestId,
|
||||
mode: 'submission',
|
||||
actorId,
|
||||
});
|
||||
const draftId = 'submission:' + (interestId ?? 'new');
|
||||
useReport(editor, draftId, report);
|
||||
useEffect(() => {
|
||||
onCreated?.(editor.activeId);
|
||||
}, [onCreated, editor.activeId]);
|
||||
const fresh = interestId === null;
|
||||
const available = fresh
|
||||
? p.interests.length === 0 || editor.activeId !== null
|
||||
: true;
|
||||
if (
|
||||
(!available || suppressed || !editor.editable) &&
|
||||
!editor.dirty &&
|
||||
!editor.problem
|
||||
)
|
||||
return null;
|
||||
const interest = p.interests.find(
|
||||
(candidate) => candidate.id === (interestId ?? editor.activeId),
|
||||
);
|
||||
return (
|
||||
<form
|
||||
data-candidacy-form={draftId}
|
||||
className="space-y-4 rounded border p-5"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
editor.submit();
|
||||
}}
|
||||
>
|
||||
<h3 className="text-lg font-bold">
|
||||
{editor.activeId === null
|
||||
? 'Manifestar interesse'
|
||||
: 'Actualizar manifestação de interesse'}
|
||||
</h3>
|
||||
<p>
|
||||
Declarações são informações comunicadas por si; não atribuem
|
||||
verificação. Dados desconhecidos podem ser esclarecidos no
|
||||
processo.
|
||||
</p>
|
||||
{editor.activeId !== null && (
|
||||
<p>
|
||||
Voltar a submeter cria uma nova versão e reinicia a
|
||||
avaliação actual. Esta operação conserva a versão anterior
|
||||
no histórico de auditoria.
|
||||
</p>
|
||||
)}
|
||||
<Comparison editor={editor} organizations={p.organizations} />
|
||||
<fieldset
|
||||
disabled={!editor.editable || editor.form.processing}
|
||||
className="space-y-4"
|
||||
>
|
||||
<Field label="Participação">
|
||||
<select
|
||||
className={control}
|
||||
value={editor.values.organization_id}
|
||||
onChange={(event) =>
|
||||
editor.change('organization_id', event.target.value)
|
||||
}
|
||||
>
|
||||
<option value="">Sem organização indicada</option>
|
||||
{editor.values.organization_id &&
|
||||
!p.organizations.some(
|
||||
(organization) =>
|
||||
organization.id ===
|
||||
editor.values.organization_id,
|
||||
) && (
|
||||
<option
|
||||
value={editor.values.organization_id}
|
||||
disabled
|
||||
>
|
||||
Organização já indisponível
|
||||
</option>
|
||||
)}
|
||||
{p.organizations.map((organization) => (
|
||||
<option
|
||||
key={organization.id}
|
||||
value={organization.id}
|
||||
>
|
||||
{organization.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
{interest?.organization_id &&
|
||||
!editor.values.organization_id && (
|
||||
<p role="status">
|
||||
Retirar a organização conserva o autor registado da
|
||||
candidatura; a edição passa a depender desse autor,
|
||||
conforme a regra de participação pessoal.
|
||||
</p>
|
||||
)}
|
||||
<Field label="Proposta curta">
|
||||
<textarea
|
||||
className={control}
|
||||
maxLength={15000}
|
||||
value={editor.values.proposal}
|
||||
onChange={(event) =>
|
||||
editor.change('proposal', event.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{(
|
||||
[
|
||||
'capacity',
|
||||
'availability',
|
||||
'contribution',
|
||||
'conflicts',
|
||||
] as const
|
||||
).map((key) => (
|
||||
<Field key={key} label={submissionLabels[key]}>
|
||||
<textarea
|
||||
className={control}
|
||||
maxLength={key === 'availability' ? 1000 : 5000}
|
||||
value={editor.values[key]}
|
||||
onChange={(event) =>
|
||||
editor.change(key, event.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
))}
|
||||
<label className="block">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={editor.values.consent === 'yes'}
|
||||
onChange={(event) =>
|
||||
editor.change(
|
||||
'consent',
|
||||
event.target.checked ? 'yes' : 'no',
|
||||
)
|
||||
}
|
||||
/>{' '}
|
||||
Autorizo a partilha desta candidatura com o responsável pela
|
||||
parceria.
|
||||
</label>
|
||||
</fieldset>
|
||||
<Errors errors={editor.form.errors} />
|
||||
<button className={button} disabled={editor.blocked}>
|
||||
{editor.recovering
|
||||
? 'Recuperar submissão enviada'
|
||||
: 'Guardar interesse'}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
function Decision({
|
||||
p,
|
||||
recordId,
|
||||
interestId,
|
||||
actorId,
|
||||
report,
|
||||
}: {
|
||||
p: CandidacyProps;
|
||||
recordId: number;
|
||||
interestId: number;
|
||||
actorId: number | null;
|
||||
report: DraftReporter;
|
||||
}) {
|
||||
const editor = useCandidacyEdit({
|
||||
props: p,
|
||||
recordId,
|
||||
interestId,
|
||||
mode: 'decision',
|
||||
actorId,
|
||||
});
|
||||
useReport(editor, 'decision:' + interestId, report);
|
||||
if (!editor.editable && !editor.dirty && !editor.problem) return null;
|
||||
const unrecorded = editor.criteria.some(
|
||||
(criterion) =>
|
||||
editor.values['criterion:' + criterion.code] !==
|
||||
editor.current['criterion:' + criterion.code],
|
||||
);
|
||||
return (
|
||||
<section
|
||||
data-candidacy-form={'decision:' + interestId}
|
||||
className="space-y-4"
|
||||
>
|
||||
<Comparison editor={editor} organizations={p.organizations} />
|
||||
<fieldset
|
||||
disabled={!editor.editable || editor.form.processing}
|
||||
className="space-y-4"
|
||||
>
|
||||
{editor.ownerMode && (
|
||||
<details className="space-y-4">
|
||||
<summary>Registar avaliação fundamentada</summary>
|
||||
{editor.criteria.map((criterion) => {
|
||||
const value = criterionValue(
|
||||
editor.values['criterion:' + criterion.code],
|
||||
);
|
||||
return (
|
||||
<div
|
||||
key={criterion.code}
|
||||
className="grid gap-3 md:grid-cols-2"
|
||||
>
|
||||
<Field label={criterion.label}>
|
||||
<select
|
||||
className={control}
|
||||
value={value.state}
|
||||
onChange={(event) =>
|
||||
editor.changeCriterion(
|
||||
criterion.code,
|
||||
'state',
|
||||
event.target.value,
|
||||
)
|
||||
}
|
||||
>
|
||||
{['unknown', 'met', 'unmet'].map(
|
||||
(state) => (
|
||||
<option
|
||||
key={state}
|
||||
value={state}
|
||||
>
|
||||
{labels[state]}
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</Field>
|
||||
<Field
|
||||
label={
|
||||
'Referência da evidência — ' +
|
||||
criterion.label
|
||||
}
|
||||
>
|
||||
<input
|
||||
className={control}
|
||||
maxLength={2000}
|
||||
value={value.evidence}
|
||||
onChange={(event) =>
|
||||
editor.changeCriterion(
|
||||
criterion.code,
|
||||
'evidence',
|
||||
event.target.value,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</details>
|
||||
)}
|
||||
<Field
|
||||
label={
|
||||
editor.ownerMode
|
||||
? 'Motivo da decisão ou pedido de esclarecimento'
|
||||
: 'Motivo da retirada'
|
||||
}
|
||||
>
|
||||
<textarea
|
||||
className={control}
|
||||
maxLength={2000}
|
||||
value={editor.values.reason}
|
||||
onChange={(event) =>
|
||||
editor.change('reason', event.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
{editor.ownerMode && unrecorded && (
|
||||
<p role="status">
|
||||
Existem alterações de avaliação ainda por guardar. As
|
||||
outras decisões usam a avaliação actualmente guardada,
|
||||
apresentada acima.
|
||||
</p>
|
||||
)}
|
||||
</fieldset>
|
||||
<Errors errors={editor.form.errors} />
|
||||
{editor.recovering ? (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={editor.blocked}
|
||||
onClick={() => editor.submit()}
|
||||
>
|
||||
Recuperar acção enviada
|
||||
</button>
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{(editor.ownerMode
|
||||
? [
|
||||
'assess',
|
||||
'clarify',
|
||||
'shortlist',
|
||||
'reject',
|
||||
...(editor.status === 'shortlisted'
|
||||
? ['connect']
|
||||
: []),
|
||||
]
|
||||
: ['withdraw']
|
||||
).map((action) => (
|
||||
<button
|
||||
type="button"
|
||||
key={action}
|
||||
className={button}
|
||||
disabled={editor.blocked || !editor.values.reason}
|
||||
onClick={() => editor.submit(action)}
|
||||
>
|
||||
{
|
||||
{
|
||||
assess: 'Guardar avaliação',
|
||||
clarify: 'Pedir esclarecimento',
|
||||
shortlist: 'Adicionar à lista curta',
|
||||
reject: 'Não seleccionar',
|
||||
connect: 'Abrir negociação',
|
||||
withdraw: 'Retirar candidatura',
|
||||
}[action]
|
||||
}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
function Card({
|
||||
p,
|
||||
id,
|
||||
recordId,
|
||||
actorId,
|
||||
report,
|
||||
suppressed,
|
||||
}: {
|
||||
p: CandidacyProps;
|
||||
id: number;
|
||||
recordId: number;
|
||||
actorId: number | null;
|
||||
report: DraftReporter;
|
||||
suppressed: boolean;
|
||||
}) {
|
||||
const interest = p.interests.find((interest) => interest.id === id);
|
||||
const score =
|
||||
interest &&
|
||||
interest.match.score_min !== null &&
|
||||
interest.match.score_max !== null
|
||||
? `${interest.match.score_min}–${interest.match.score_max}%`
|
||||
: 'Por determinar';
|
||||
return (
|
||||
<article className="space-y-4 rounded border p-5" data-candidacy={id}>
|
||||
{interest ? (
|
||||
<>
|
||||
<h3 className="text-lg font-bold">
|
||||
Candidatura {interest.id} · {labels[interest.status]}
|
||||
</h3>
|
||||
<p>{interest.proposal}</p>
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/parcerias/candidaturas/${interest.id}/historico`}
|
||||
>
|
||||
Consultar versões e decisões
|
||||
</Link>
|
||||
<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: {score} · 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((criterion) => (
|
||||
<li key={criterion.code}>
|
||||
{criterion.label} · peso {criterion.weight} ·{' '}
|
||||
{labels[criterion.state]}
|
||||
{criterion.mandatory ? ' · Obrigatório' : ''}
|
||||
{criterion.evidence && (
|
||||
<> · Evidência: {criterion.evidence}</>
|
||||
)}
|
||||
<p className="text-sm">
|
||||
{criterion.explanation}
|
||||
</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{interest.room_id && (
|
||||
<Link
|
||||
className={button}
|
||||
href={'/parcerias/salas/' + interest.room_id}
|
||||
>
|
||||
Abrir conexão privada
|
||||
</Link>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<p role="alert">
|
||||
Esta candidatura deixou de estar disponível para consulta
|
||||
nesta conta. A preparação local foi conservada; não é uma
|
||||
autorização de acesso.
|
||||
</p>
|
||||
)}
|
||||
<Decision
|
||||
p={p}
|
||||
recordId={recordId}
|
||||
interestId={id}
|
||||
actorId={actorId}
|
||||
report={report}
|
||||
/>
|
||||
<Submission
|
||||
p={p}
|
||||
recordId={recordId}
|
||||
interestId={id}
|
||||
actorId={actorId}
|
||||
report={report}
|
||||
suppressed={suppressed}
|
||||
/>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
export default function PartnershipCandidacies({
|
||||
p,
|
||||
otherDirty = false,
|
||||
}: {
|
||||
p: CandidacyProps;
|
||||
otherDirty?: boolean;
|
||||
}) {
|
||||
const { auth } = usePage<{ auth: { user: { id: number } | null } }>().props;
|
||||
const openedRecord = useRef(p.record.id);
|
||||
const [drafts, setDrafts] = useState<Record<string, boolean>>({});
|
||||
const [created, setCreated] = useState<number | null>(null);
|
||||
const report = useCallback((id: string, dirty: boolean) => {
|
||||
setDrafts((previous) =>
|
||||
(previous[id] ?? false) === dirty
|
||||
? previous
|
||||
: { ...previous, [id]: dirty },
|
||||
);
|
||||
}, []);
|
||||
const onCreated = useCallback((id: number | null) => setCreated(id), []);
|
||||
const retained = Object.entries(drafts)
|
||||
.filter(([key, dirty]) => dirty && !key.endsWith(':new'))
|
||||
.map(([key]) => Number(key.split(':')[1]))
|
||||
.filter(Number.isSafeInteger);
|
||||
const ids = [
|
||||
...new Set([
|
||||
...p.interests.map((interest) => interest.id),
|
||||
...retained,
|
||||
]),
|
||||
];
|
||||
useCandidacyLeaveGuard(otherDirty || Object.values(drafts).some(Boolean));
|
||||
return (
|
||||
<section className="space-y-6" aria-label="Candidaturas e preparação">
|
||||
{p.record.id !== openedRecord.current && (
|
||||
<p role="alert">
|
||||
A resposta não corresponde à parceria aberta. A preparação
|
||||
foi conservada e os comandos estão suspensos.
|
||||
</p>
|
||||
)}
|
||||
{ids.map((id) => (
|
||||
<Card
|
||||
key={id}
|
||||
p={p}
|
||||
id={id}
|
||||
recordId={openedRecord.current}
|
||||
actorId={auth.user?.id ?? null}
|
||||
report={report}
|
||||
suppressed={created === id}
|
||||
/>
|
||||
))}
|
||||
<Submission
|
||||
p={p}
|
||||
recordId={openedRecord.current}
|
||||
actorId={auth.user?.id ?? null}
|
||||
report={report}
|
||||
onCreated={onCreated}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
import type {
|
||||
PartnershipEditor,
|
||||
PartnershipSection,
|
||||
} from '@/lib/partnership-edit';
|
||||
import { labels, type Catalogues } from '@/pages/partnerships/shared';
|
||||
|
||||
const fields: Record<PartnershipSection, string> = {
|
||||
title: 'Título',
|
||||
offer: 'Recursos que oferece',
|
||||
seeking: 'Colaboração que procura',
|
||||
organization_id: 'Organização representada',
|
||||
sector_id: 'Sector',
|
||||
kind: 'Oferta ou procura',
|
||||
partnership_type: 'Tipo de parceria',
|
||||
deadline: 'Prazo para manifestações de interesse',
|
||||
summary: 'Resumo',
|
||||
requirements: 'Requisitos desejáveis',
|
||||
mandatory: 'Critérios obrigatórios',
|
||||
confidentiality: 'Visibilidade',
|
||||
consent: 'Autorização de divulgação',
|
||||
availability: 'Disponibilidade dos recursos ou colaboração',
|
||||
locations: 'Localizações e respectivas fontes',
|
||||
origins: 'Origens documentais',
|
||||
};
|
||||
export default function PartnershipEditComparison({
|
||||
editor,
|
||||
catalogues,
|
||||
}: {
|
||||
editor: PartnershipEditor;
|
||||
catalogues: Catalogues;
|
||||
}) {
|
||||
function display(
|
||||
key: PartnershipSection,
|
||||
value: PartnershipEditor['values'][PartnershipSection],
|
||||
): string {
|
||||
if (typeof value === 'boolean')
|
||||
return value ? 'Autorização indicada' : 'Sem autorização indicada';
|
||||
if (Array.isArray(value))
|
||||
return value.length
|
||||
? value
|
||||
.map((item) => {
|
||||
if (typeof item === 'string')
|
||||
return (
|
||||
catalogues.criteria[item] ??
|
||||
'Critério anterior fora da configuração actual'
|
||||
);
|
||||
if ('geo_location_id' in item)
|
||||
return `${catalogues.territories.find((place) => place.id === item.geo_location_id)?.name ?? 'Localização anteriormente indicada'} · ${{ primary: 'Principal', operating: 'Operação', coverage: 'Cobertura' }[item.role] ?? item.role} · ${item.source_reference}`;
|
||||
return (
|
||||
catalogues.sources?.find(
|
||||
(source) =>
|
||||
source.type === item.type &&
|
||||
source.target_id === item.target_id,
|
||||
)?.title ??
|
||||
'Origem documental anteriormente associada'
|
||||
);
|
||||
})
|
||||
.join('\n')
|
||||
: 'Nenhuma selecção';
|
||||
if (!value) return 'Não indicado';
|
||||
if (key === 'organization_id')
|
||||
return (
|
||||
catalogues.organizations.find(
|
||||
(item) => String(item.id) === value,
|
||||
)?.name ?? 'Organização anteriormente indicada'
|
||||
);
|
||||
if (key === 'sector_id')
|
||||
return (
|
||||
catalogues.sectors.find((item) => String(item.id) === value)
|
||||
?.name ?? 'Sector anteriormente indicado'
|
||||
);
|
||||
if (key === 'partnership_type')
|
||||
return (
|
||||
catalogues.types[value] ??
|
||||
'Tipo anterior fora da configuração actual'
|
||||
);
|
||||
if (key === 'kind')
|
||||
return value === 'offering'
|
||||
? 'Oferta'
|
||||
: value === 'seeking'
|
||||
? 'Procura'
|
||||
: value;
|
||||
if (key === 'confidentiality')
|
||||
return value === 'private'
|
||||
? 'Privada'
|
||||
: value === 'public'
|
||||
? 'Pública'
|
||||
: value;
|
||||
return value;
|
||||
}
|
||||
return (
|
||||
<section
|
||||
aria-label="Comparação da parceria"
|
||||
className="space-y-3 rounded border p-4"
|
||||
>
|
||||
{editor.problem && <p role="alert">{editor.problem}</p>}
|
||||
{editor.invalid && (
|
||||
<p role="alert">
|
||||
Os dados desta edição não foram reconhecidos. Reabra a
|
||||
parceria correcta antes de guardar; a edição actual foi
|
||||
conservada.
|
||||
</p>
|
||||
)}
|
||||
{editor.retryingCreation && (
|
||||
<p>
|
||||
Repita a criação anterior para recuperar o registo. O pedido
|
||||
anterior será reutilizado, sem substituir as suas edições
|
||||
posteriores nem criar outra parceria.
|
||||
</p>
|
||||
)}
|
||||
{editor.retryingSave && (
|
||||
<div className="space-y-2">
|
||||
<p>
|
||||
A edição anterior não foi confirmada. Recuperar repete
|
||||
exactamente a mesma tentativa e conserva o que preparou
|
||||
depois de enviar.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
disabled={!editor.canRecoverSave}
|
||||
onClick={editor.recoverSave}
|
||||
>
|
||||
Recuperar a mesma gravação
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{editor.mustRefresh && (
|
||||
<p>
|
||||
Consulte os dados actuais antes de adoptar uma versão para
|
||||
uma nova tentativa.
|
||||
</p>
|
||||
)}
|
||||
{editor.refreshing && (
|
||||
<p role="status">
|
||||
A recuperar os dados actuais. As suas edições são
|
||||
conservadas.
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
disabled={editor.refreshing || editor.form.processing}
|
||||
onClick={editor.refresh}
|
||||
>
|
||||
Comparar com os dados actuais
|
||||
</button>
|
||||
{editor.current && !editor.editable && (
|
||||
<p role="status">
|
||||
Estado actual:{' '}
|
||||
{labels[editor.current.status] ?? 'Estado por confirmar'}. A
|
||||
parceria está disponível para consulta; a edição por guardar
|
||||
foi conservada e não pode ser gravada neste estado.
|
||||
</p>
|
||||
)}
|
||||
{editor.current?.status === 'published' && (
|
||||
<p>
|
||||
Ao guardar esta revisão, a proposta volta a rascunho e
|
||||
requer nova submissão e revisão pelo percurso existente.
|
||||
</p>
|
||||
)}
|
||||
{(editor.stale || editor.retryingSave) && (
|
||||
<>
|
||||
<p role="alert">
|
||||
A proposta mudou desde{' '}
|
||||
{editor.baseVersion === null
|
||||
? 'a preparação inicial'
|
||||
: `a versão ${editor.baseVersion}`}
|
||||
. Compare com a versão {editor.current?.version} e
|
||||
escolha como conservar os seus dados.
|
||||
</p>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left text-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Campo</th>
|
||||
<th>Actualmente guardado</th>
|
||||
<th>Sua edição</th>
|
||||
<th>Escolha</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{editor.changed.map((key) => (
|
||||
<tr key={key} className="border-t">
|
||||
<th
|
||||
scope="row"
|
||||
className="p-2 align-top"
|
||||
>
|
||||
{fields[key]}
|
||||
</th>
|
||||
<td className="max-w-md p-2 align-top break-words whitespace-pre-wrap">
|
||||
{editor.current &&
|
||||
display(
|
||||
key,
|
||||
editor.current.values[key],
|
||||
)}
|
||||
</td>
|
||||
<td className="max-w-md p-2 align-top break-words whitespace-pre-wrap">
|
||||
{display(key, editor.values[key])}
|
||||
</td>
|
||||
<td className="space-y-2 p-2 align-top">
|
||||
{editor.conflicts.includes(key) ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className="block underline"
|
||||
disabled={
|
||||
editor.refreshing ||
|
||||
editor.form
|
||||
.processing
|
||||
}
|
||||
onClick={() =>
|
||||
editor.choose(
|
||||
key,
|
||||
'current',
|
||||
)
|
||||
}
|
||||
>
|
||||
Usar valor actual
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="block underline"
|
||||
disabled={
|
||||
editor.refreshing ||
|
||||
editor.form
|
||||
.processing
|
||||
}
|
||||
onClick={() =>
|
||||
editor.choose(
|
||||
key,
|
||||
'mine',
|
||||
)
|
||||
}
|
||||
>
|
||||
Manter minha alteração
|
||||
</button>
|
||||
{editor.unresolved.includes(
|
||||
key,
|
||||
) && (
|
||||
<p>
|
||||
Escolha o valor a
|
||||
conservar neste
|
||||
campo.
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
'Actualização compatível com a sua edição'
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
disabled={
|
||||
editor.invalid ||
|
||||
editor.refreshing ||
|
||||
editor.form.processing ||
|
||||
editor.mustRefresh ||
|
||||
editor.unresolved.length > 0
|
||||
}
|
||||
onClick={editor.adopt}
|
||||
>
|
||||
Usar esta versão e conservar as alterações escolhidas
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import {
|
||||
publicationHistoryActions,
|
||||
type PublicationHistorySummary,
|
||||
} from '@/lib/partnership-history';
|
||||
import { labels } from '@/pages/partnerships/shared';
|
||||
|
||||
const status = (value: string | null) =>
|
||||
value === null
|
||||
? 'Estado não registado ou reservado'
|
||||
: (labels[value] ?? 'Estado não identificado no registo');
|
||||
export default function PublicationSummary({
|
||||
value,
|
||||
}: {
|
||||
value: PublicationHistorySummary;
|
||||
}) {
|
||||
return (
|
||||
<section
|
||||
className="space-y-3 rounded border p-4 break-words"
|
||||
aria-label="Histórico e decisões"
|
||||
>
|
||||
<h2 className="text-xl font-bold">Histórico e decisões</h2>
|
||||
<p>
|
||||
Até {value.limit}{' '}
|
||||
{value.limit === 1
|
||||
? 'alteração mais recente'
|
||||
: 'alterações mais recentes'}
|
||||
. Os nomes são os disponíveis no cadastro actual; as decisões e
|
||||
motivos são os que ficaram guardados.
|
||||
</p>
|
||||
{!value.entries.length ? (
|
||||
<p>Ainda não existem alterações guardadas para apresentar.</p>
|
||||
) : (
|
||||
<ol className="space-y-4">
|
||||
{value.entries.map((entry, index) => (
|
||||
<li key={index} className="space-y-1 border-l-2 pl-3">
|
||||
<p className="font-semibold">
|
||||
Versão {entry.version ?? 'não registada'} ·{' '}
|
||||
{entry.restricted
|
||||
? 'Conteúdo reservado'
|
||||
: (publicationHistoryActions[
|
||||
entry.action ?? ''
|
||||
] ?? 'Alteração registada')}
|
||||
</p>
|
||||
{entry.restricted ? (
|
||||
<p>
|
||||
Os dados desta alteração não estão
|
||||
disponíveis para esta conta. Consulte o
|
||||
histórico para conhecer os limites do
|
||||
registo.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<p>
|
||||
{entry.actor_name ??
|
||||
'Autor não registado'}{' '}
|
||||
·{' '}
|
||||
{entry.occurred_at ??
|
||||
'Data não registada'}
|
||||
</p>
|
||||
<p>
|
||||
{status(entry.status_before)} →{' '}
|
||||
{status(entry.status_after)}
|
||||
</p>
|
||||
{entry.reason !== null && (
|
||||
<p className="whitespace-pre-wrap">
|
||||
Motivo:{' '}
|
||||
{entry.reason || 'Não indicado'}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
)}
|
||||
{value.has_more && (
|
||||
<p>Existem alterações anteriores no histórico completo.</p>
|
||||
)}
|
||||
<Link className="inline-block underline" href={value.href}>
|
||||
Consultar versões e decisões da publicação
|
||||
</Link>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { useEffect } from 'react';
|
||||
import {
|
||||
usePublication,
|
||||
type PublicationProps,
|
||||
} from '@/lib/partnership-publication';
|
||||
import {
|
||||
Field,
|
||||
Errors,
|
||||
control,
|
||||
button,
|
||||
labels,
|
||||
} from '@/pages/partnerships/shared';
|
||||
const actions: Record<string, string> = {
|
||||
submit: 'Submeter para publicação',
|
||||
publish: 'Publicar',
|
||||
return: 'Devolver para correcção',
|
||||
reject: 'Rejeitar com fundamento',
|
||||
suspend: 'Suspender publicação',
|
||||
archive: 'Arquivar publicação',
|
||||
renew: 'Renovar em rascunho',
|
||||
};
|
||||
const fields: Record<string, string> = {
|
||||
title: 'Título',
|
||||
offer: 'Oferta',
|
||||
seeking: 'Procura',
|
||||
kind: 'Oferta ou procura',
|
||||
partnership_type: 'Tipo de parceria',
|
||||
sector_id: 'Referência do sector',
|
||||
organization_id: 'Referência da organização',
|
||||
deadline: 'Prazo',
|
||||
summary: 'Resumo público',
|
||||
requirements: 'Requisitos',
|
||||
confidentiality: 'Partilha dos detalhes',
|
||||
availability: 'Disponibilidade',
|
||||
consent: 'Autorização de partilha',
|
||||
mandatory: 'Critérios obrigatórios',
|
||||
origins: 'Origens',
|
||||
locations: 'Localizações',
|
||||
};
|
||||
export default function PartnershipPublication({
|
||||
p,
|
||||
actorId,
|
||||
onDirty,
|
||||
}: {
|
||||
p: PublicationProps;
|
||||
actorId: number;
|
||||
onDirty: (value: boolean) => void;
|
||||
}) {
|
||||
const edit = usePublication(p, actorId);
|
||||
useEffect(() => {
|
||||
onDirty(edit.dirty);
|
||||
}, [edit.dirty, onDirty]);
|
||||
useEffect(() => () => onDirty(false), [onDirty]);
|
||||
if (!edit.dirty && !p.owner && !p.moderator) return null;
|
||||
const active = edit.current?.actions ?? [];
|
||||
return (
|
||||
<section
|
||||
className="space-y-4 rounded border p-5"
|
||||
data-publication-form="publication"
|
||||
>
|
||||
<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, sector e localização permanecem por
|
||||
confirmar quando não há evidência.
|
||||
</p>
|
||||
<p>
|
||||
A acção aplica-se à versão revista da proposta. Submeter
|
||||
encaminha para moderação; renovar prepara um rascunho. Estas
|
||||
acções não decidem candidaturas nem alteram salas ou marcos.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
disabled={edit.refreshing || edit.form.processing}
|
||||
onClick={edit.refresh}
|
||||
>
|
||||
Comparar com a proposta actual
|
||||
</button>
|
||||
{edit.problem && <p role="alert">{edit.problem}</p>}
|
||||
{edit.invalid && (
|
||||
<p role="alert">
|
||||
A resposta ou conta actual não corresponde a esta
|
||||
preparação. A gravação está suspensa.
|
||||
</p>
|
||||
)}
|
||||
{(edit.stale || edit.needsCompare || edit.recovery) && (
|
||||
<div className="space-y-3 rounded border p-3">
|
||||
<p>
|
||||
Reveja o contexto antes de outra acção. O motivo
|
||||
preparado foi conservado.
|
||||
</p>
|
||||
<p>
|
||||
Versão revista: {edit.base?.version} ·{' '}
|
||||
{labels[edit.base?.status ?? '']} → Actual:{' '}
|
||||
{edit.current?.version} ·{' '}
|
||||
{labels[edit.current?.status ?? '']}
|
||||
</p>
|
||||
{edit.changes.length > 0 && (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Campo</th>
|
||||
<th>Antes</th>
|
||||
<th>Actualmente</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{edit.changes.map((key) => (
|
||||
<tr key={key}>
|
||||
<th>{fields[key] ?? key}</th>
|
||||
<td className="break-words whitespace-pre-wrap">
|
||||
{edit.base?.values[key] ||
|
||||
'Não indicado'}
|
||||
</td>
|
||||
<td className="break-words whitespace-pre-wrap">
|
||||
{edit.current?.values[key] ||
|
||||
'Não indicado'}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
<p>
|
||||
Adoptar esta versão conserva o motivo e permite preparar
|
||||
uma nova tentativa. Uma tentativa anterior sem
|
||||
confirmação deixa de ser recuperada por este formulário;
|
||||
o seu registo no processo mantém-se.
|
||||
</p>
|
||||
{edit.mustRefresh && (
|
||||
<p>
|
||||
Compare com a proposta actual antes de adoptar uma
|
||||
nova versão.
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={
|
||||
edit.invalid ||
|
||||
edit.mustRefresh ||
|
||||
edit.refreshing ||
|
||||
edit.form.processing
|
||||
}
|
||||
onClick={edit.adopt}
|
||||
>
|
||||
Revi esta versão; conservar o motivo e preparar nova
|
||||
acção
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{(active.length > 0 || edit.dirty) && (
|
||||
<Field label="Motivo da ação">
|
||||
<textarea
|
||||
className={control}
|
||||
value={edit.form.data.reason}
|
||||
onChange={(event) => edit.change(event.target.value)}
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
{!active.length && edit.dirty && (
|
||||
<p>
|
||||
O estado ou acesso actual não permite nova acção. O motivo
|
||||
preparado foi conservado em memória.
|
||||
</p>
|
||||
)}
|
||||
<Errors errors={edit.form.errors} />
|
||||
{edit.recovery && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={
|
||||
edit.invalid ||
|
||||
!edit.can(edit.recovery) ||
|
||||
edit.refreshing ||
|
||||
edit.form.processing
|
||||
}
|
||||
onClick={() => edit.send(edit.recovery!, true)}
|
||||
>
|
||||
Recuperar a mesma tentativa: {actions[edit.recovery]}
|
||||
</button>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{active.map((action) => (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
key={action}
|
||||
disabled={edit.blocked || !edit.form.data.reason.trim()}
|
||||
onClick={() => edit.send(action)}
|
||||
>
|
||||
{actions[action]}
|
||||
</button>
|
||||
))}
|
||||
{p.canEdit && (
|
||||
<Link
|
||||
className="underline"
|
||||
href={`/parcerias/${p.record.id}/editar`}
|
||||
>
|
||||
Editar rascunho
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import type { RoomEditor } from '@/lib/partnership-room-edit';
|
||||
import { labels as states } from '@/pages/partnerships/shared';
|
||||
export default function RoomComparison({
|
||||
editor,
|
||||
labels,
|
||||
display = (_key, value) => value || 'Não indicado',
|
||||
}: {
|
||||
editor: RoomEditor;
|
||||
labels: Record<string, string>;
|
||||
display?: (key: string, value: string) => string;
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-3 rounded border p-3">
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
disabled={editor.refreshing || editor.form.processing}
|
||||
onClick={editor.refresh}
|
||||
>
|
||||
Comparar com os dados actuais da sala
|
||||
</button>
|
||||
{editor.problem && <p role="alert">{editor.problem}</p>}
|
||||
{editor.pendingAction && (
|
||||
<div className="space-y-2">
|
||||
<p>
|
||||
A acção anterior não foi confirmada. Recuperar repete a
|
||||
tentativa original sem substituir a preparação
|
||||
posterior.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
disabled={!editor.canRecover}
|
||||
onClick={editor.recover}
|
||||
>
|
||||
Recuperar a mesma acção
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{editor.mustRefresh && (
|
||||
<p>
|
||||
Consulte o contexto actual antes de adoptar uma nova
|
||||
tentativa.
|
||||
</p>
|
||||
)}
|
||||
{editor.invalid && (
|
||||
<p role="alert">
|
||||
Este registo não foi recuperado correctamente. As edições
|
||||
foram conservadas e a gravação está suspensa.
|
||||
</p>
|
||||
)}
|
||||
{!editor.editable && editor.dirty && (
|
||||
<p role="status">
|
||||
O estado ou o acesso actual não permite editar este registo.
|
||||
A preparação abaixo foi conservada em memória; não foi
|
||||
gravada.
|
||||
</p>
|
||||
)}
|
||||
{editor.refreshing && (
|
||||
<p role="status">A recuperar sem apagar a sua preparação.</p>
|
||||
)}
|
||||
{(editor.stale || editor.pendingAction) && (
|
||||
<>
|
||||
<p role="alert">
|
||||
O registo ou o contexto da sala mudou. Compare os dados
|
||||
antes de continuar. Estado actual:{' '}
|
||||
{states[editor.status ?? ''] ?? 'Por recuperar'}.
|
||||
</p>
|
||||
{editor.changed.length > 0 && (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left text-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Campo</th>
|
||||
<th>Actualmente guardado</th>
|
||||
<th>Sua edição</th>
|
||||
<th>Escolha</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{editor.changed.map((key) => (
|
||||
<tr key={key}>
|
||||
<td>{labels[key] ?? key}</td>
|
||||
<td className="whitespace-pre-wrap">
|
||||
{display(
|
||||
key,
|
||||
editor.current[key],
|
||||
)}
|
||||
</td>
|
||||
<td className="whitespace-pre-wrap">
|
||||
{display(
|
||||
key,
|
||||
editor.values[key],
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
{editor.conflicts.includes(
|
||||
key,
|
||||
) ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
editor.choose(
|
||||
key,
|
||||
'current',
|
||||
)
|
||||
}
|
||||
>
|
||||
Usar valor actual
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
editor.choose(
|
||||
key,
|
||||
'mine',
|
||||
)
|
||||
}
|
||||
>
|
||||
Manter minha
|
||||
alteração
|
||||
</button>
|
||||
{editor.unresolved.includes(
|
||||
key,
|
||||
) && (
|
||||
<p>
|
||||
Escolha o valor
|
||||
a conservar.
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
'Actualização compatível'
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="underline"
|
||||
disabled={
|
||||
editor.refreshing ||
|
||||
editor.form.processing ||
|
||||
editor.unresolved.length > 0 ||
|
||||
editor.mustRefresh ||
|
||||
editor.invalid
|
||||
}
|
||||
onClick={editor.adopt}
|
||||
>
|
||||
Usar este contexto e conservar as alterações escolhidas
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{editor.recovering && (
|
||||
<p role="status">
|
||||
A criação não foi confirmada. Recuperar repete a chave e o
|
||||
conteúdo originais; alterações posteriores ficam como
|
||||
preparação de outro marco.
|
||||
</p>
|
||||
)}
|
||||
{editor.created !== null && (
|
||||
<p role="status">
|
||||
O marco foi confirmado na lista desta sala. Alterações
|
||||
feitas depois do envio foram conservadas como nova
|
||||
preparação; o marco criado pode ser editado na lista.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { button, control, Field } from '@/pages/management/shared';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import type { ProactiveAnalysis } from './proactive-investment';
|
||||
@@ -45,7 +46,9 @@ export function ProactiveSupplyBrowser({
|
||||
}) {
|
||||
const [activity, setActivity] = useState('');
|
||||
const [sector, setSector] = useState('');
|
||||
const [result, setResult] = useState<Result | null>(null);
|
||||
const [loaded, setLoaded] = useState<{ key: string; data: Result } | null>(
|
||||
null,
|
||||
);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [query, setQuery] = useState<{
|
||||
@@ -54,8 +57,14 @@ export function ProactiveSupplyBrowser({
|
||||
sector: string;
|
||||
page: number;
|
||||
} | null>(null);
|
||||
const requestKey =
|
||||
query?.territory === territoryId
|
||||
? JSON.stringify([recordId, query])
|
||||
: '';
|
||||
const result =
|
||||
requestKey && loaded?.key === requestKey ? loaded.data : null;
|
||||
useEffect(() => {
|
||||
setResult(null);
|
||||
setLoaded(null);
|
||||
setQuery(null);
|
||||
setSector('');
|
||||
setError('');
|
||||
@@ -87,10 +96,13 @@ export function ProactiveSupplyBrowser({
|
||||
);
|
||||
return r.json() as Promise<Result>;
|
||||
})
|
||||
.then(setResult)
|
||||
.then((data) => {
|
||||
if (!controller.signal.aborted)
|
||||
setLoaded({ key: JSON.stringify([recordId, query]), data });
|
||||
})
|
||||
.catch((e) => {
|
||||
if (e.name !== 'AbortError') {
|
||||
setResult(null);
|
||||
if (!controller.signal.aborted && e.name !== 'AbortError') {
|
||||
setLoaded(null);
|
||||
setError(e.message);
|
||||
}
|
||||
})
|
||||
@@ -143,6 +155,15 @@ export function ProactiveSupplyBrowser({
|
||||
return (
|
||||
<fieldset className="space-y-3 rounded border p-3">
|
||||
<legend>Consultar oferta existente — base interna</legend>
|
||||
<Link
|
||||
className="underline"
|
||||
href={
|
||||
'/minhas-oportunidades/oferta-interna/revisao' +
|
||||
(recordId ? `?record_id=${recordId}` : '')
|
||||
}
|
||||
>
|
||||
Conferir origens, repetições e correspondências por resolver
|
||||
</Link>
|
||||
<p>
|
||||
Consulta a localização escolhida nesta ficha e os seus
|
||||
territórios subordinados. Os filtros por sector e actividade CAE
|
||||
|
||||
@@ -22,6 +22,19 @@ export function profileLinks(access: ProfileAccess | null | undefined) {
|
||||
...(access.audit
|
||||
? [{ title: 'Auditoria de acessos', href: access.audit }]
|
||||
: []),
|
||||
...(access.technicalSupport
|
||||
? [
|
||||
{
|
||||
title:
|
||||
typeof access.technicalSupportUnread === 'number' &&
|
||||
Number.isSafeInteger(access.technicalSupportUnread) &&
|
||||
access.technicalSupportUnread > 0
|
||||
? `Suporte técnico · ${access.technicalSupportUnread} por consultar`
|
||||
: 'Suporte técnico',
|
||||
href: access.technicalSupport,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(access.administration
|
||||
? [{ title: 'Gestão de perfis', href: access.administration }]
|
||||
: []),
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import { usageValue, type SearchUsageReport } from '@/lib/product-usage';
|
||||
import { card } from '@/pages/investment/shared';
|
||||
|
||||
export default function SearchUsage({ search }: { search: SearchUsageReport }) {
|
||||
return (
|
||||
<section
|
||||
className={card + ' space-y-3'}
|
||||
aria-labelledby="search-usage-title"
|
||||
>
|
||||
<h2 id="search-usage-title" className="text-xl font-semibold">
|
||||
Pesquisas — respostas registadas
|
||||
</h2>
|
||||
<p>
|
||||
Uma resposta HTTP de primeira página com critérios explícitos é
|
||||
a unidade desta medição. Repetições e actualizações contam
|
||||
novamente; pessoas, bots e pesquisas únicas não são
|
||||
identificados.
|
||||
</p>
|
||||
<p>
|
||||
Edição: {search.definition_version}. Dias {search.from} a{' '}
|
||||
{search.to}, em {search.timezone}. Leitura em {search.read_at}.
|
||||
As contagens diárias usam o snapshot do relatório; o dia actual
|
||||
é parcial e não há corte por fracção de segundo.
|
||||
</p>
|
||||
{!search.installed && (
|
||||
<p role="status">
|
||||
Ainda não há dados de recolha disponíveis neste destino.
|
||||
</p>
|
||||
)}
|
||||
{!search.enabled_now && (
|
||||
<p role="status">
|
||||
A recolha está desligada neste momento. O histórico
|
||||
registado mantém-se disponível.
|
||||
</p>
|
||||
)}
|
||||
{!search.applicable && (
|
||||
<p role="status">
|
||||
Estas pesquisas públicas não têm associação comprovada ao
|
||||
serviço do Balcão seleccionado. Os valores não são
|
||||
calculados para esse filtro.
|
||||
</p>
|
||||
)}
|
||||
{search.definition_conflict_now && (
|
||||
<p role="status">
|
||||
A definição desta edição foi preservada. Uma configuração
|
||||
diferente com o mesmo identificador não acrescenta contagens
|
||||
a esta série.
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
Respostas: {usageValue(search.responses)}. Sem resultados
|
||||
principais: {usageValue(search.zero_responses)}. Taxa entre
|
||||
respostas registadas: {usageValue(search.zero_rate, '%')}.
|
||||
</p>
|
||||
<p>
|
||||
Cobertura parcial: falhas de recolha podem deixar respostas por
|
||||
contar. Sem registos de medição não significa zero pesquisas.
|
||||
</p>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left">
|
||||
<caption className="text-left font-semibold">
|
||||
Canais públicos instrumentados nesta edição
|
||||
</caption>
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="p-2">Canal</th>
|
||||
<th className="p-2">Respostas</th>
|
||||
<th className="p-2">Sem resultados principais</th>
|
||||
<th className="p-2">Taxa na base registada</th>
|
||||
<th className="p-2">
|
||||
Primeira / última observação no período
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{search.channels.map((channel) => (
|
||||
<tr className="border-t align-top" key={channel.id}>
|
||||
<th scope="row" className="p-2">
|
||||
{channel.label}
|
||||
</th>
|
||||
<td className="p-2">
|
||||
{usageValue(channel.responses)}
|
||||
</td>
|
||||
<td className="p-2">
|
||||
{usageValue(channel.zero_responses)}
|
||||
</td>
|
||||
<td className="p-2">
|
||||
{usageValue(channel.zero_rate, '%')}
|
||||
</td>
|
||||
<td className="p-2">
|
||||
{channel.first_recorded_at ? (
|
||||
<>
|
||||
{channel.first_recorded_at}
|
||||
<br />
|
||||
{channel.last_recorded_at}
|
||||
</>
|
||||
) : (
|
||||
'Sem registos'
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<details>
|
||||
<summary className="cursor-pointer underline">
|
||||
Âmbito, exclusões e interpretação
|
||||
</summary>
|
||||
<ul className="list-disc pl-5">
|
||||
{[...search.limits, ...search.exclusions].map((text) => (
|
||||
<li key={text}>{text}</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -7,13 +7,22 @@ type Match = {
|
||||
slug: string;
|
||||
title: string;
|
||||
published_at?: string | null;
|
||||
distance_km?: number | null;
|
||||
location_recorded_at?: string | null;
|
||||
location_source_reference?: string | null;
|
||||
location_source_date?: string | null;
|
||||
};
|
||||
function publicationDate(value?: string | null): string | null {
|
||||
if (typeof value !== 'string' || !value.trim()) return null;
|
||||
const date = new Date(value);
|
||||
return Number.isNaN(date.getTime())
|
||||
? null
|
||||
: date.toLocaleDateString('pt-MZ');
|
||||
: date.toLocaleDateString(
|
||||
'pt-MZ',
|
||||
/^\d{4}-\d{2}-\d{2}$/.test(value)
|
||||
? { timeZone: 'UTC' }
|
||||
: undefined,
|
||||
);
|
||||
}
|
||||
type Classification = {
|
||||
target_type: string;
|
||||
@@ -30,13 +39,140 @@ type Props = {
|
||||
catalogueUrl: string;
|
||||
criteria: string[];
|
||||
classifications?: Classification[];
|
||||
radiusAvailable?: boolean;
|
||||
areaLabel?: string;
|
||||
};
|
||||
|
||||
export type BusinessGeographicCoverage = {
|
||||
origin_id: string;
|
||||
origin_title: string;
|
||||
radius_km: number;
|
||||
origin_recorded_at: string | null;
|
||||
origin_source_reference?: string | null;
|
||||
origin_source_date?: string | null;
|
||||
with_public_point: number;
|
||||
without_public_point: number;
|
||||
source: string;
|
||||
method: string;
|
||||
};
|
||||
|
||||
export function GeographicCoverage({
|
||||
coverage,
|
||||
}: {
|
||||
coverage: BusinessGeographicCoverage;
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-1 rounded border p-3 text-sm">
|
||||
<p>
|
||||
Raio de {coverage.radius_km} km a partir de{' '}
|
||||
{coverage.origin_title}.
|
||||
</p>
|
||||
<p>
|
||||
Fonte: {coverage.source}. {coverage.method}
|
||||
</p>
|
||||
<p>
|
||||
Cobertura entre as fichas públicas que cumprem os restantes
|
||||
filtros, antes de aplicar o raio: {coverage.with_public_point}{' '}
|
||||
com ponto utilizável; {coverage.without_public_point} sem ponto
|
||||
público exacto utilizável, excluídas da pesquisa por distância.
|
||||
Esta contagem pode incluir a ficha de referência.
|
||||
</p>
|
||||
<p>
|
||||
Localização da referência registada em:{' '}
|
||||
{publicationDate(coverage.origin_recorded_at) ??
|
||||
'data não indicada'}
|
||||
. A data de registo não confirma a actualidade dos dados de
|
||||
origem. Cobertura incompleta não demonstra ausência de negócios.
|
||||
</p>
|
||||
<p>
|
||||
Fonte de origem da localização:{' '}
|
||||
{coverage.origin_source_reference ||
|
||||
'referência não divulgada ou não indicada'}
|
||||
. Data da fonte:{' '}
|
||||
{publicationDate(coverage.origin_source_date) ?? 'desconhecida'}
|
||||
.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function BusinessDistance({
|
||||
record,
|
||||
}: {
|
||||
record: Pick<
|
||||
Match,
|
||||
| 'distance_km'
|
||||
| 'location_recorded_at'
|
||||
| 'location_source_reference'
|
||||
| 'location_source_date'
|
||||
>;
|
||||
}) {
|
||||
if (
|
||||
typeof record.distance_km !== 'number' ||
|
||||
!Number.isFinite(record.distance_km) ||
|
||||
record.distance_km < 0
|
||||
)
|
||||
return null;
|
||||
return (
|
||||
<div className="text-sm">
|
||||
<p>
|
||||
Distância aproximada em linha recta:{' '}
|
||||
{record.distance_km.toLocaleString('pt-MZ')} km. Localização
|
||||
registada em:{' '}
|
||||
{publicationDate(record.location_recorded_at) ??
|
||||
'data não indicada'}
|
||||
.
|
||||
</p>
|
||||
<BusinessLocationSource record={record} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function BusinessLocationSource({
|
||||
record,
|
||||
showRecorded = false,
|
||||
}: {
|
||||
record: Pick<
|
||||
Match,
|
||||
| 'location_recorded_at'
|
||||
| 'location_source_reference'
|
||||
| 'location_source_date'
|
||||
>;
|
||||
showRecorded?: boolean;
|
||||
}) {
|
||||
if (
|
||||
!record.location_recorded_at &&
|
||||
!record.location_source_reference &&
|
||||
!record.location_source_date
|
||||
)
|
||||
return null;
|
||||
return (
|
||||
<p className="text-sm">
|
||||
Fonte de origem da localização:{' '}
|
||||
{record.location_source_reference ||
|
||||
'referência não divulgada ou não indicada'}
|
||||
. Data da fonte:{' '}
|
||||
{publicationDate(record.location_source_date) ?? 'desconhecida'}.
|
||||
{showRecorded && (
|
||||
<>
|
||||
{' '}
|
||||
Registada em:{' '}
|
||||
{publicationDate(record.location_recorded_at) ??
|
||||
'data não indicada'}
|
||||
. A data de registo não confirma a actualidade da origem.
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
export default function SimilarBusinesses({
|
||||
currentId,
|
||||
catalogueUrl,
|
||||
criteria,
|
||||
classifications = [],
|
||||
radiusAvailable = false,
|
||||
areaLabel,
|
||||
}: Props) {
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
const [selection, setSelection] = useState({
|
||||
@@ -49,7 +185,26 @@ export default function SimilarBusinesses({
|
||||
(row) => classificationKey(row) === selection.value,
|
||||
)
|
||||
: undefined;
|
||||
const [radiusSelection, setRadiusSelection] = useState({
|
||||
recordId: currentId,
|
||||
value: '',
|
||||
});
|
||||
const radius =
|
||||
radiusAvailable && radiusSelection.recordId === currentId
|
||||
? radiusSelection.value
|
||||
: '';
|
||||
const query = new URL(catalogueUrl, 'https://portal.invalid');
|
||||
if (radius) {
|
||||
for (const field of [
|
||||
'province_id',
|
||||
'district_id',
|
||||
'admin_post_id',
|
||||
'locality_id',
|
||||
])
|
||||
query.searchParams.delete(field);
|
||||
query.searchParams.set('near_business', currentId);
|
||||
query.searchParams.set('radius_km', radius);
|
||||
}
|
||||
if (selected) {
|
||||
query.searchParams.set('association_type', selected.target_type);
|
||||
query.searchParams.set('association_target', selected.target_id);
|
||||
@@ -62,6 +217,7 @@ export default function SimilarBusinesses({
|
||||
key: string;
|
||||
rows: Match[];
|
||||
error: boolean;
|
||||
coverage: BusinessGeographicCoverage | null;
|
||||
} | null>(null);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
@@ -69,14 +225,31 @@ export default function SimilarBusinesses({
|
||||
.searchParams;
|
||||
params.set('per_page', '7');
|
||||
params.set('page', '1');
|
||||
void portalRequest<{ data: Match[] }>(
|
||||
`/api/v1/business-opportunities?${params}`,
|
||||
{ signal: controller.signal },
|
||||
)
|
||||
void portalRequest<{
|
||||
data: Match[];
|
||||
geographicCoverage?: BusinessGeographicCoverage | null;
|
||||
}>(`/api/v1/business-opportunities?${params}`, {
|
||||
signal: controller.signal,
|
||||
})
|
||||
.then((response) => {
|
||||
if (controller.signal.aborted) return;
|
||||
if (!Array.isArray(response.data))
|
||||
throw new Error('Invalid catalogue response');
|
||||
const coverage = response.geographicCoverage ?? null;
|
||||
if (
|
||||
radius &&
|
||||
(!coverage ||
|
||||
coverage.origin_id !== currentId ||
|
||||
coverage.radius_km !== Number(radius) ||
|
||||
!Number.isInteger(coverage.with_public_point) ||
|
||||
coverage.with_public_point < 0 ||
|
||||
!Number.isInteger(coverage.without_public_point) ||
|
||||
coverage.without_public_point < 0 ||
|
||||
typeof coverage.origin_title !== 'string' ||
|
||||
typeof coverage.source !== 'string' ||
|
||||
typeof coverage.method !== 'string')
|
||||
)
|
||||
throw new Error('Invalid radius coverage');
|
||||
const seen = new Set([currentId]);
|
||||
if (
|
||||
response.data.some(
|
||||
@@ -87,7 +260,11 @@ export default function SimilarBusinesses({
|
||||
typeof row.slug !== 'string' ||
|
||||
!row.slug.trim() ||
|
||||
typeof row.title !== 'string' ||
|
||||
!row.title.trim(),
|
||||
!row.title.trim() ||
|
||||
(radius &&
|
||||
(typeof row.distance_km !== 'number' ||
|
||||
!Number.isFinite(row.distance_km) ||
|
||||
row.distance_km < 0)),
|
||||
)
|
||||
) {
|
||||
throw new Error('Invalid catalogue record');
|
||||
@@ -106,14 +283,14 @@ export default function SimilarBusinesses({
|
||||
return true;
|
||||
})
|
||||
.slice(0, 6);
|
||||
setResult({ key, rows, error: false });
|
||||
setResult({ key, rows, error: false, coverage });
|
||||
})
|
||||
.catch(() => {
|
||||
if (!controller.signal.aborted)
|
||||
setResult({ key, rows: [], error: true });
|
||||
setResult({ key, rows: [], error: true, coverage: null });
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [currentId, effectiveCatalogueUrl, key]);
|
||||
}, [currentId, effectiveCatalogueUrl, key, radius]);
|
||||
const current = result?.key === key ? result : null;
|
||||
return (
|
||||
<section
|
||||
@@ -124,11 +301,17 @@ export default function SimilarBusinesses({
|
||||
<h2 className="text-xl font-bold">Explorar negócios semelhantes</h2>
|
||||
<p>
|
||||
Critérios:{' '}
|
||||
{[...criteria, ...(selected ? [selected.label] : [])].join(
|
||||
' · ',
|
||||
)}
|
||||
{[
|
||||
...criteria,
|
||||
...(!radius && areaLabel ? [areaLabel] : []),
|
||||
...(radius ? [`Raio de ${radius} km`] : []),
|
||||
...(selected ? [selected.label] : []),
|
||||
].join(' · ')}
|
||||
. A consulta compara os dados publicados; não avalia
|
||||
rentabilidade nem proximidade geográfica.
|
||||
rentabilidade.{' '}
|
||||
{radius
|
||||
? 'O raio substitui o filtro por área e pode atravessar limites administrativos.'
|
||||
: 'Sem raio seleccionado, não é calculada proximidade geográfica.'}
|
||||
</p>
|
||||
{!current ? (
|
||||
<p role="status">A consultar o catálogo…</p>
|
||||
@@ -171,6 +354,7 @@ export default function SimilarBusinesses({
|
||||
'Data de publicação não indicada.'
|
||||
)}
|
||||
</p>
|
||||
<BusinessDistance record={row} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
@@ -181,6 +365,46 @@ export default function SimilarBusinesses({
|
||||
mercado.
|
||||
</p>
|
||||
)}
|
||||
{current && !current.error && current.coverage && (
|
||||
<GeographicCoverage coverage={current.coverage} />
|
||||
)}
|
||||
{radiusAvailable ? (
|
||||
<fieldset className="rounded border p-3">
|
||||
<legend>Âmbito geográfico</legend>
|
||||
<label>
|
||||
Pesquisar por área ou distância
|
||||
<select
|
||||
className="block w-full rounded border p-2"
|
||||
value={radius}
|
||||
onChange={(event) =>
|
||||
setRadiusSelection({
|
||||
recordId: currentId,
|
||||
value: event.target.value,
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="">
|
||||
{areaLabel
|
||||
? `Área: ${areaLabel}`
|
||||
: 'Sem limite por distância'}
|
||||
</option>
|
||||
{[1, 5, 10, 25, 50, 100, 250, 500, 1000, 2000].map(
|
||||
(value) => (
|
||||
<option key={value} value={String(value)}>
|
||||
Até {value} km desta ficha
|
||||
</option>
|
||||
),
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
</fieldset>
|
||||
) : (
|
||||
<p className="text-sm">
|
||||
A pesquisa por raio requer um ponto primário público exacto
|
||||
na ficha de referência. Pode continuar por área, sector e
|
||||
classificação.
|
||||
</p>
|
||||
)}
|
||||
{classifications.length > 0 && (
|
||||
<label className="block space-y-1">
|
||||
Comparar também por uma classificação divulgada
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import {
|
||||
useTechnicalIncidentHandling,
|
||||
type HandlingProps,
|
||||
type Command,
|
||||
} from '@/lib/technical-incident-handling';
|
||||
import { button, control } from '@/pages/management/shared';
|
||||
import { handlingLabels, commandLabels } from '@/lib/technical-incident-labels';
|
||||
export default function TechnicalIncidentHandling(props: HandlingProps) {
|
||||
const edit = useTechnicalIncidentHandling(props),
|
||||
state = props.incident.handling;
|
||||
const actions: Command[] =
|
||||
state.status === 'resolved'
|
||||
? ['note', 'reopen']
|
||||
: [
|
||||
'claim',
|
||||
'note',
|
||||
'resolve',
|
||||
...(state.status === 'in_progress'
|
||||
? ['release' as const]
|
||||
: []),
|
||||
];
|
||||
return (
|
||||
<section
|
||||
className="space-y-3 rounded border p-4"
|
||||
aria-label="Tratar incidente técnico"
|
||||
>
|
||||
<h2 className="text-xl font-semibold">Tratar incidente técnico</h2>
|
||||
<p>
|
||||
O tratamento é partilhado pela equipa autorizada neste âmbito.
|
||||
Assumir um tratamento em curso substitui o responsável e
|
||||
conserva o histórico.
|
||||
</p>
|
||||
<p>
|
||||
Resolver este incidente não submete, publica ou aprova a
|
||||
oportunidade.
|
||||
</p>
|
||||
{edit.notice && <p role="status">{edit.notice}</p>}
|
||||
{edit.error && <p role="alert">{edit.error}</p>}
|
||||
{edit.stale && (
|
||||
<section
|
||||
className="rounded border p-3"
|
||||
aria-label="Comparar tratamento"
|
||||
>
|
||||
<p>
|
||||
O incidente mudou. Compare antes de confirmar o estado
|
||||
actual.
|
||||
</p>
|
||||
<p>
|
||||
Analisado: {handlingLabels[edit.base.status]} ·
|
||||
responsável {edit.base.assignee_name || 'por assumir'} ·
|
||||
versão {edit.base.version}
|
||||
</p>
|
||||
<p>
|
||||
Actual: {handlingLabels[state.status]} · responsável{' '}
|
||||
{state.assignee_name || 'por assumir'} · versão{' '}
|
||||
{state.version}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={!edit.canAdopt}
|
||||
onClick={edit.adopt}
|
||||
>
|
||||
Confirmar leitura do estado actual
|
||||
</button>
|
||||
</section>
|
||||
)}
|
||||
<label className="block">
|
||||
Nota interna do tratamento
|
||||
<textarea
|
||||
className={control}
|
||||
value={edit.note}
|
||||
maxLength={3000}
|
||||
onChange={(event) => edit.change(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<p>
|
||||
A nota é visível à equipa de suporte autorizada e fica no
|
||||
histórico. O autor da tentativa acompanha apenas o estado
|
||||
técnico.
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{actions
|
||||
.filter(
|
||||
(action) =>
|
||||
action !== 'claim' ||
|
||||
state.assignee_user_id !== props.actorId,
|
||||
)
|
||||
.map((action) => (
|
||||
<button
|
||||
type="button"
|
||||
key={action}
|
||||
className={button}
|
||||
disabled={edit.blocked}
|
||||
onClick={() => void edit.send(action)}
|
||||
>
|
||||
{commandLabels[action]}
|
||||
</button>
|
||||
))}
|
||||
{edit.canRetry && (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
onClick={() =>
|
||||
void edit.send(edit.pendingAction ?? 'note', true)
|
||||
}
|
||||
>
|
||||
Repetir o registo original
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={edit.refreshing}
|
||||
onClick={edit.refresh}
|
||||
>
|
||||
Actualizar incidente
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { router } from '@inertiajs/react';
|
||||
import { portalRequest } from '@/lib/portal-api';
|
||||
import { button } from '@/pages/management/shared';
|
||||
|
||||
export default function TechnicalIncidentNotice({
|
||||
actorId,
|
||||
reference,
|
||||
unread,
|
||||
}: {
|
||||
actorId: number;
|
||||
reference: string;
|
||||
unread: boolean;
|
||||
}) {
|
||||
const [read, setRead] = useState(!unread),
|
||||
[busy, setBusy] = useState(false),
|
||||
[error, setError] = useState('');
|
||||
const scope = useRef({ actorId, reference }),
|
||||
alive = useRef(true),
|
||||
active = useRef(false),
|
||||
confirmed = useRef(!unread);
|
||||
const current = useRef({ actorId, reference });
|
||||
current.current = { actorId, reference };
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (!unread) {
|
||||
confirmed.current = true;
|
||||
setRead(true);
|
||||
setError('');
|
||||
}
|
||||
}, [unread]);
|
||||
function applicable() {
|
||||
return (
|
||||
alive.current &&
|
||||
current.current.actorId === scope.current.actorId &&
|
||||
current.current.reference === scope.current.reference
|
||||
);
|
||||
}
|
||||
async function mark() {
|
||||
if (!applicable() || active.current || confirmed.current) return;
|
||||
active.current = true;
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const value = await portalRequest<unknown>(
|
||||
'/suporte-tecnico/incidentes/' +
|
||||
scope.current.reference +
|
||||
'/consultado',
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: '{}',
|
||||
},
|
||||
);
|
||||
if (!applicable() || confirmed.current) return;
|
||||
if (
|
||||
!value ||
|
||||
typeof value !== 'object' ||
|
||||
!('actor_id' in value) ||
|
||||
value.actor_id !== scope.current.actorId ||
|
||||
!('reference' in value) ||
|
||||
value.reference !== scope.current.reference ||
|
||||
!('read' in value) ||
|
||||
value.read !== true
|
||||
)
|
||||
throw new Error('Unconfirmed receipt');
|
||||
confirmed.current = true;
|
||||
setRead(true);
|
||||
router.reload({
|
||||
only: ['incidents', 'profileAccess', 'notice'],
|
||||
});
|
||||
} catch {
|
||||
if (applicable() && !confirmed.current)
|
||||
setError(
|
||||
'Não foi possível confirmar a consulta. Pode repetir esta acção; o tratamento e as notas mantêm-se.',
|
||||
);
|
||||
} finally {
|
||||
if (applicable()) {
|
||||
active.current = false;
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{read ? (
|
||||
<p>Aviso consultado por si.</p>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={busy}
|
||||
onClick={() => void mark()}
|
||||
>
|
||||
{error
|
||||
? 'Repetir confirmação de consulta'
|
||||
: 'Marcar aviso como consultado'}
|
||||
</button>
|
||||
)}
|
||||
{error && <p role="alert">{error}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,58 @@ export type BusinessLocationPath = {
|
||||
locality_id: string;
|
||||
};
|
||||
|
||||
export function businessPointTerritoryKey(path: BusinessLocationPath): string {
|
||||
return [
|
||||
path.province_id,
|
||||
path.district_id,
|
||||
path.admin_post_id,
|
||||
path.locality_id,
|
||||
].join('|');
|
||||
}
|
||||
|
||||
export function businessPointTerritoryLabel(
|
||||
payload: Record<string, string | undefined>,
|
||||
paths: string[][] = [],
|
||||
): string {
|
||||
const index =
|
||||
payload.geography_scope === 'specific'
|
||||
? 0
|
||||
: decodeBusinessLocations(payload.locations_json).findIndex(
|
||||
(path) =>
|
||||
businessPointTerritoryKey(path) ===
|
||||
payload.location_point_territory,
|
||||
);
|
||||
return paths[index]?.join(' / ') || 'Localização por reconciliar';
|
||||
}
|
||||
|
||||
export function businessPointApplicable(
|
||||
payload: Record<string, string | undefined>,
|
||||
): boolean {
|
||||
return (
|
||||
payload.location_point_enabled === 'yes' &&
|
||||
['specific', 'multiple'].includes(payload.geography_scope ?? '') &&
|
||||
payload.disclosure_precision === 'exact' &&
|
||||
payload.location_unknown === 'no'
|
||||
);
|
||||
}
|
||||
|
||||
export function businessPointRequiredFields(
|
||||
payload: Record<string, string | undefined>,
|
||||
): Set<string> {
|
||||
if (!businessPointApplicable(payload)) return new Set();
|
||||
return new Set([
|
||||
'location_latitude',
|
||||
'location_longitude',
|
||||
'location_point_source_mode',
|
||||
...(payload.geography_scope === 'multiple'
|
||||
? ['location_point_territory']
|
||||
: []),
|
||||
...(payload.location_point_source_mode === 'custom'
|
||||
? ['location_point_source_reference']
|
||||
: []),
|
||||
]);
|
||||
}
|
||||
|
||||
export const emptyBusinessLocation = (): BusinessLocationPath => ({
|
||||
province_id: '',
|
||||
district_id: '',
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
export type CompanyAnswers = Record<string, string>;
|
||||
export function companyComparisonUrl(
|
||||
base: string,
|
||||
answers: CompanyAnswers,
|
||||
field = 'answers',
|
||||
): string {
|
||||
return (
|
||||
base +
|
||||
'?' +
|
||||
new URLSearchParams(
|
||||
Object.entries(answers).map(([key, value]) => [
|
||||
`${field}[${key}]`,
|
||||
value,
|
||||
]),
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
export type Party = {
|
||||
id: string;
|
||||
name: string | null;
|
||||
kind: 'person' | 'entity';
|
||||
source: string | null;
|
||||
roles: string[];
|
||||
represented_id: string | null;
|
||||
cash: string | null;
|
||||
in_kind: string | null;
|
||||
paid: string | null;
|
||||
share_count: string | null;
|
||||
work: string | null;
|
||||
commitment: string | null;
|
||||
source_snapshot?: {
|
||||
origin: string;
|
||||
reference: string;
|
||||
version: string | number | null;
|
||||
};
|
||||
};
|
||||
export type CompanyFacts = {
|
||||
form: string | null;
|
||||
proposed_name: string | null;
|
||||
seat: string | null;
|
||||
activities: string | null;
|
||||
regulated: string;
|
||||
currency: string | null;
|
||||
capital: string | null;
|
||||
nominal_value: string | null;
|
||||
management: string | null;
|
||||
binding: string | null;
|
||||
notes: string | null;
|
||||
parties: Party[];
|
||||
};
|
||||
|
||||
/** Read actual form values, including autofill, without serializing private provenance. */
|
||||
export function preparationValues(
|
||||
form: HTMLFormElement,
|
||||
facts: CompanyFacts,
|
||||
): CompanyFacts {
|
||||
const data = new FormData(form);
|
||||
const value = (key: string, fallback: string | null) => {
|
||||
const v = data.get(key);
|
||||
return typeof v === 'string' ? v.trim() || null : fallback;
|
||||
};
|
||||
return {
|
||||
form: value('form', facts.form),
|
||||
proposed_name: value('proposed_name', facts.proposed_name),
|
||||
seat: value('seat', facts.seat),
|
||||
activities: value('activities', facts.activities),
|
||||
regulated: value('regulated', facts.regulated) ?? 'unknown',
|
||||
currency: value('currency', facts.currency),
|
||||
capital: value('capital', facts.capital),
|
||||
nominal_value: value('nominal_value', facts.nominal_value),
|
||||
management: value('management', facts.management),
|
||||
binding: value('binding', facts.binding),
|
||||
notes: value('notes', facts.notes),
|
||||
parties: facts.parties.map((p) => ({
|
||||
id: p.id,
|
||||
name: value(`${p.id}.name`, p.name),
|
||||
kind: p.kind,
|
||||
source: p.source,
|
||||
roles: p.roles,
|
||||
represented_id: p.represented_id,
|
||||
cash: value(`${p.id}.cash`, p.cash),
|
||||
in_kind: value(`${p.id}.in_kind`, p.in_kind),
|
||||
paid: value(`${p.id}.paid`, p.paid),
|
||||
share_count: value(`${p.id}.share_count`, p.share_count),
|
||||
work: value(`${p.id}.work`, p.work),
|
||||
commitment: value(`${p.id}.commitment`, p.commitment),
|
||||
})),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { useRef, useState } from 'react';
|
||||
|
||||
type Values = Record<string, string>;
|
||||
type Kind = 'investor' | 'contact' | 'lead' | 'task';
|
||||
function object(value: unknown): value is Record<string, unknown> {
|
||||
return !!value && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
function savedRecord(
|
||||
props: Record<string, unknown>,
|
||||
kind: Kind,
|
||||
id: string,
|
||||
): Record<string, unknown> | null {
|
||||
let candidate: unknown = kind === 'investor' ? props.investor : props.lead;
|
||||
if (kind === 'contact')
|
||||
candidate = Array.isArray(props.contacts)
|
||||
? props.contacts.find((value) => object(value) && value.id === id)
|
||||
: null;
|
||||
if (kind === 'task')
|
||||
candidate =
|
||||
object(props.lead) && Array.isArray(props.lead.tasks)
|
||||
? props.lead.tasks.find(
|
||||
(value) => object(value) && value.id === id,
|
||||
)
|
||||
: null;
|
||||
return object(candidate) && candidate.id === id ? candidate : null;
|
||||
}
|
||||
|
||||
/** Keeps deliberate edits, including a deliberate return to the original value. */
|
||||
export function useCrmRecordEdit({
|
||||
id,
|
||||
kind,
|
||||
version,
|
||||
values,
|
||||
blankAfterSave = [],
|
||||
}: {
|
||||
id: string;
|
||||
kind: Kind;
|
||||
version: number;
|
||||
values: Values;
|
||||
blankAfterSave?: string[];
|
||||
}) {
|
||||
const form = useForm({ version, values });
|
||||
const live = useRef(form.data);
|
||||
live.current = form.data;
|
||||
const identity = useRef(id);
|
||||
identity.current = id;
|
||||
const base = useRef({ id, version, values: { ...values } });
|
||||
const edited = useRef(new Set<string>());
|
||||
const generation = useRef<Record<string, number>>({});
|
||||
const [choices, setChoices] = useState<Record<string, 'mine' | 'current'>>(
|
||||
{},
|
||||
);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const keys = Object.keys(values);
|
||||
const stale = version !== form.data.version;
|
||||
const changed = keys.filter(
|
||||
(key) => values[key] !== base.current.values[key],
|
||||
);
|
||||
const conflicts = changed.filter(
|
||||
(key) =>
|
||||
edited.current.has(key) && form.data.values[key] !== values[key],
|
||||
);
|
||||
const unresolved = conflicts.filter(
|
||||
(key) => choices[`${version}:${key}`] !== 'mine',
|
||||
);
|
||||
const invalid =
|
||||
base.current.id !== id || !Number.isInteger(version) || version < 1;
|
||||
|
||||
function change(key: string, value: string) {
|
||||
if (!keys.includes(key)) return;
|
||||
edited.current.add(key);
|
||||
generation.current[key] = (generation.current[key] ?? 0) + 1;
|
||||
setChoices((previous) => {
|
||||
const next = { ...previous };
|
||||
delete next[`${version}:${key}`];
|
||||
return next;
|
||||
});
|
||||
live.current = {
|
||||
...live.current,
|
||||
values: { ...live.current.values, [key]: value },
|
||||
};
|
||||
form.setData((previous) => ({
|
||||
...previous,
|
||||
values: { ...previous.values, [key]: value },
|
||||
}));
|
||||
}
|
||||
function choose(key: string, choice: 'mine' | 'current') {
|
||||
if (choice === 'current') change(key, values[key]);
|
||||
setChoices((previous) => ({
|
||||
...previous,
|
||||
[`${version}:${key}`]: choice,
|
||||
}));
|
||||
}
|
||||
function adopt() {
|
||||
if (!stale || invalid || refreshing || unresolved.length) return;
|
||||
const next = Object.fromEntries(
|
||||
keys.map((key) => [
|
||||
key,
|
||||
edited.current.has(key)
|
||||
? live.current.values[key]
|
||||
: values[key],
|
||||
]),
|
||||
);
|
||||
base.current = { id, version, values: { ...values } };
|
||||
live.current = { version, values: next };
|
||||
form.setData(live.current);
|
||||
form.clearErrors('version');
|
||||
setChoices({});
|
||||
}
|
||||
function refresh() {
|
||||
if (refreshing || form.processing) return;
|
||||
setRefreshing(true);
|
||||
router.reload({
|
||||
only:
|
||||
kind === 'lead' || kind === 'task'
|
||||
? ['lead', 'owners', 'taskCreation', 'nextAction']
|
||||
: ['investor', 'contacts'],
|
||||
onFinish: () => setRefreshing(false),
|
||||
});
|
||||
}
|
||||
const blocked = invalid || stale || refreshing || !!form.errors.version;
|
||||
function submit(url: string) {
|
||||
if (blocked || form.processing) return;
|
||||
const submitted = {
|
||||
...live.current.values,
|
||||
version: live.current.version,
|
||||
};
|
||||
const sentGeneration = { ...generation.current };
|
||||
form.transform(() => submitted);
|
||||
form.patch(url, {
|
||||
preserveScroll: true,
|
||||
onSuccess: (page) => {
|
||||
if (identity.current !== id) return;
|
||||
const record = savedRecord(page.props, kind, id);
|
||||
const actualVersion = record?.version_no;
|
||||
if (
|
||||
!record ||
|
||||
typeof actualVersion !== 'number' ||
|
||||
!Number.isInteger(actualVersion) ||
|
||||
actualVersion < 1
|
||||
)
|
||||
return;
|
||||
const next: Values = {};
|
||||
for (const key of keys) {
|
||||
const value = record[key];
|
||||
if (
|
||||
blankAfterSave.includes(key) ||
|
||||
value === null ||
|
||||
value === undefined
|
||||
)
|
||||
next[key] = '';
|
||||
else if (
|
||||
typeof value === 'string' ||
|
||||
typeof value === 'number'
|
||||
)
|
||||
next[key] = String(value);
|
||||
else return;
|
||||
}
|
||||
base.current = {
|
||||
id,
|
||||
version: actualVersion,
|
||||
values: { ...next },
|
||||
};
|
||||
edited.current.clear();
|
||||
const merged = { ...next };
|
||||
for (const key of keys) {
|
||||
if (
|
||||
(generation.current[key] ?? 0) !==
|
||||
(sentGeneration[key] ?? 0)
|
||||
) {
|
||||
merged[key] = live.current.values[key];
|
||||
edited.current.add(key);
|
||||
}
|
||||
}
|
||||
setChoices({});
|
||||
const saved = { version: actualVersion, values: next };
|
||||
form.setDefaults(saved);
|
||||
live.current = { version: actualVersion, values: merged };
|
||||
form.setData(live.current);
|
||||
form.clearErrors();
|
||||
},
|
||||
});
|
||||
}
|
||||
function error(key: string): string | undefined {
|
||||
const value = Object.entries(form.errors).find(
|
||||
([name]) => name === key,
|
||||
)?.[1];
|
||||
return typeof value === 'string' ? value : undefined;
|
||||
}
|
||||
return {
|
||||
form,
|
||||
values: form.data.values,
|
||||
current: values,
|
||||
version,
|
||||
baseVersion: form.data.version,
|
||||
changed,
|
||||
conflicts,
|
||||
unresolved,
|
||||
stale,
|
||||
refreshing,
|
||||
invalid,
|
||||
blocked,
|
||||
change,
|
||||
choose,
|
||||
adopt,
|
||||
refresh,
|
||||
submit,
|
||||
error,
|
||||
};
|
||||
}
|
||||
|
||||
export type CrmRecordEditor = ReturnType<typeof useCrmRecordEdit>;
|
||||
@@ -0,0 +1,371 @@
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { createOperationKey } from './operation-key';
|
||||
import type { Lead } from '@/pages/crm/types';
|
||||
import {
|
||||
useCrmTaskPreparation,
|
||||
taskDeadlineLocal,
|
||||
taskDeadlineUtc,
|
||||
} from './crm-task-preparation';
|
||||
import type {
|
||||
TaskPreparationView,
|
||||
TaskPreparationSnapshot,
|
||||
} from './crm-task-preparation';
|
||||
|
||||
export type TaskCreationContext = {
|
||||
lead_id: string;
|
||||
actor_id: number;
|
||||
commands: { key: string; task_id: string; version: number }[];
|
||||
preparation?: TaskPreparationView;
|
||||
};
|
||||
type Values = { title: string; due_at: string; assignee_user_id: string };
|
||||
type Attempt = {
|
||||
values: Values & { client_key: string };
|
||||
generation: Record<string, number>;
|
||||
};
|
||||
const object = (value: unknown): value is Record<string, unknown> =>
|
||||
!!value && typeof value === 'object' && !Array.isArray(value);
|
||||
const positive = (value: unknown): value is number =>
|
||||
typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
|
||||
|
||||
export function useCrmTaskCreation(lead: Lead, context: TaskCreationContext) {
|
||||
const form = useForm<Values>({
|
||||
title: '',
|
||||
due_at: '',
|
||||
assignee_user_id: String(lead.owner_user_id ?? ''),
|
||||
});
|
||||
const live = useRef(form.data);
|
||||
live.current = form.data;
|
||||
const blank = context.preparation?.snapshot;
|
||||
const sameBlank =
|
||||
blank?.pending === null &&
|
||||
blank.values?.title === '' &&
|
||||
blank.values?.due_at === '' &&
|
||||
blank.values?.assignee_user_id === String(lead.owner_user_id ?? '') &&
|
||||
Object.values(blank.generation ?? {}).length === 3 &&
|
||||
Object.values(blank.generation ?? {}).every(
|
||||
(value) => Number.isSafeInteger(value) && value >= 0,
|
||||
);
|
||||
const generation = useRef<Record<string, number>>(
|
||||
sameBlank ? { ...blank.generation } : {},
|
||||
);
|
||||
const pending = useRef<Attempt | null>(null);
|
||||
const submitted = useRef<string | null>(null);
|
||||
const recoveredDeadline = useRef<{ local: string; utc: string } | null>(
|
||||
null,
|
||||
);
|
||||
const alive = useRef(true);
|
||||
const [waiting, setWaiting] = useState(false);
|
||||
const [blocked, setBlocked] = useState(false);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [notice, setNotice] = useState('');
|
||||
const valid =
|
||||
context.lead_id === lead.id &&
|
||||
positive(context.actor_id) &&
|
||||
Array.isArray(context.commands);
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (generation.current.assignee_user_id) return;
|
||||
const assignee_user_id = String(lead.owner_user_id ?? '');
|
||||
live.current = { ...live.current, assignee_user_id };
|
||||
form.setData(live.current);
|
||||
}, [lead.owner_user_id]);
|
||||
|
||||
function change(key: keyof Values, value: string) {
|
||||
if (key === 'due_at') recoveredDeadline.current = null;
|
||||
generation.current[key] = (generation.current[key] ?? 0) + 1;
|
||||
live.current = { ...live.current, [key]: value };
|
||||
form.setData(live.current);
|
||||
}
|
||||
function scoped(props: unknown): props is Record<string, unknown> & {
|
||||
taskCreation: TaskCreationContext;
|
||||
} {
|
||||
return (
|
||||
object(props) &&
|
||||
object(props.lead) &&
|
||||
props.lead.id === lead.id &&
|
||||
object(props.taskCreation) &&
|
||||
props.taskCreation.lead_id === lead.id &&
|
||||
props.taskCreation.actor_id === context.actor_id &&
|
||||
Array.isArray(props.taskCreation.commands)
|
||||
);
|
||||
}
|
||||
function acknowledge(props: unknown) {
|
||||
const attempt = pending.current;
|
||||
if (!alive.current || !attempt || !scoped(props)) return false;
|
||||
const receipt = props.taskCreation.commands.find(
|
||||
(item: unknown) =>
|
||||
object(item) && item.key === attempt.values.client_key,
|
||||
);
|
||||
if (
|
||||
!receipt ||
|
||||
typeof receipt.task_id !== 'string' ||
|
||||
!positive(receipt.version)
|
||||
)
|
||||
return false;
|
||||
const task =
|
||||
object(props.lead) && Array.isArray(props.lead.tasks)
|
||||
? props.lead.tasks.find(
|
||||
(item: unknown) =>
|
||||
object(item) && item.id === receipt.task_id,
|
||||
)
|
||||
: null;
|
||||
if (
|
||||
task &&
|
||||
(!positive(task.version_no) ||
|
||||
task.version_no < receipt.version ||
|
||||
(task.version_no === receipt.version &&
|
||||
(task.title !== attempt.values.title.trim() ||
|
||||
task.assignee_user_id !==
|
||||
Number(attempt.values.assignee_user_id) ||
|
||||
new Date(task.due_at).getTime() !==
|
||||
new Date(attempt.values.due_at).getTime())))
|
||||
)
|
||||
return false;
|
||||
const next = { ...live.current };
|
||||
for (const key of ['title', 'due_at'] as const) {
|
||||
if (
|
||||
(generation.current[key] ?? 0) ===
|
||||
(attempt.generation[key] ?? 0)
|
||||
)
|
||||
next[key] = '';
|
||||
}
|
||||
live.current = next;
|
||||
form.setData(next);
|
||||
form.clearErrors();
|
||||
pending.current = null;
|
||||
setWaiting(false);
|
||||
setBlocked(false);
|
||||
setNotice(
|
||||
task
|
||||
? 'Tarefa registada. As alterações posteriores ao envio foram conservadas.'
|
||||
: 'A criação já foi registada. A tarefa já não está disponível neste lead; consulte o histórico antes de criar outra.',
|
||||
);
|
||||
return true;
|
||||
}
|
||||
function capture(): TaskPreparationSnapshot {
|
||||
return {
|
||||
values: {
|
||||
...live.current,
|
||||
due_at:
|
||||
recoveredDeadline.current?.local === live.current.due_at
|
||||
? recoveredDeadline.current.utc
|
||||
: taskDeadlineUtc(live.current.due_at),
|
||||
},
|
||||
generation: {
|
||||
title: generation.current.title ?? 0,
|
||||
due_at: generation.current.due_at ?? 0,
|
||||
assignee_user_id: generation.current.assignee_user_id ?? 0,
|
||||
},
|
||||
pending: pending.current
|
||||
? {
|
||||
values: { ...pending.current.values },
|
||||
generation: {
|
||||
title: pending.current.generation.title ?? 0,
|
||||
due_at: pending.current.generation.due_at ?? 0,
|
||||
assignee_user_id:
|
||||
pending.current.generation.assignee_user_id ?? 0,
|
||||
},
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
const preparation = useCrmTaskPreparation({
|
||||
leadId: lead.id,
|
||||
actorId: context.actor_id,
|
||||
view: context.preparation,
|
||||
getSnapshot: capture,
|
||||
onRecover: (snapshot) => {
|
||||
if (
|
||||
pending.current &&
|
||||
submitted.current === pending.current.values.client_key &&
|
||||
pending.current.values.client_key !==
|
||||
snapshot.pending?.values.client_key
|
||||
)
|
||||
return false;
|
||||
generation.current = { ...snapshot.generation };
|
||||
generation.current.assignee_user_id = Math.max(
|
||||
1,
|
||||
snapshot.generation.assignee_user_id,
|
||||
);
|
||||
live.current = {
|
||||
...snapshot.values,
|
||||
due_at: taskDeadlineLocal(snapshot.values.due_at),
|
||||
};
|
||||
recoveredDeadline.current = {
|
||||
local: live.current.due_at,
|
||||
utc: snapshot.values.due_at,
|
||||
};
|
||||
form.setData(live.current);
|
||||
pending.current = snapshot.pending;
|
||||
submitted.current = snapshot.pending?.values.client_key ?? null;
|
||||
setWaiting(!!snapshot.pending);
|
||||
setBlocked(false);
|
||||
if (snapshot.pending) {
|
||||
if (!acknowledge({ lead, taskCreation: context }))
|
||||
setNotice(
|
||||
'Foi recuperado um envio sem confirmação. Recupere a mesma criação antes de iniciar outra.',
|
||||
);
|
||||
}
|
||||
return true;
|
||||
},
|
||||
});
|
||||
const canReplay =
|
||||
!!pending.current &&
|
||||
submitted.current === pending.current.values.client_key;
|
||||
function submit() {
|
||||
if (
|
||||
!valid ||
|
||||
blocked ||
|
||||
refreshing ||
|
||||
form.processing ||
|
||||
(preparation.blocked && !canReplay)
|
||||
)
|
||||
return;
|
||||
if (!pending.current) {
|
||||
let client_key: string;
|
||||
try {
|
||||
client_key = createOperationKey();
|
||||
} catch {
|
||||
setNotice(
|
||||
'Não foi possível preparar o envio. Reabra o portal no endereço HTTPS configurado.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
pending.current = {
|
||||
values: {
|
||||
...live.current,
|
||||
due_at: capture().values.due_at,
|
||||
client_key,
|
||||
},
|
||||
generation: { ...generation.current },
|
||||
};
|
||||
}
|
||||
const attempt = pending.current;
|
||||
setWaiting(true);
|
||||
if (canReplay || !preparation.enabled) send(attempt);
|
||||
else {
|
||||
setNotice('A guardar a preparação antes de criar a tarefa…');
|
||||
void preparation.ensure().then((saved) => {
|
||||
if (!alive.current || pending.current !== attempt) return;
|
||||
if (saved) send(attempt);
|
||||
else
|
||||
setNotice(
|
||||
'O envio ficou por confirmar. Volte a guardar a preparação antes de continuar.',
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
function send(attempt: Attempt) {
|
||||
submitted.current = attempt.values.client_key;
|
||||
setNotice('A aguardar confirmação da criação.');
|
||||
form.transform(() => attempt.values);
|
||||
form.post(`/management/crm/leads/${lead.id}/tasks`, {
|
||||
preserveScroll: true,
|
||||
onSuccess: (page) => {
|
||||
if (!alive.current || pending.current !== attempt) return;
|
||||
if (!acknowledge(page.props))
|
||||
setNotice(
|
||||
'A resposta não permitiu confirmar a criação. Actualize as tarefas ou recupere o mesmo envio.',
|
||||
);
|
||||
},
|
||||
onError: () => {
|
||||
if (!alive.current || pending.current !== attempt) return;
|
||||
pending.current = null;
|
||||
setWaiting(false);
|
||||
setNotice(
|
||||
'Reveja os campos assinalados. As suas alterações foram conservadas.',
|
||||
);
|
||||
},
|
||||
onNetworkError: () => {
|
||||
if (alive.current && pending.current === attempt)
|
||||
setNotice(
|
||||
'Sem confirmação do envio. Recupere a mesma criação para evitar duplicar a tarefa.',
|
||||
);
|
||||
},
|
||||
onHttpException: (response) => {
|
||||
if (!alive.current || pending.current !== attempt) return;
|
||||
if ([401, 403, 404, 409, 419].includes(response.status))
|
||||
setBlocked(true);
|
||||
setNotice(
|
||||
'Não foi possível confirmar a criação. Actualize as tarefas e o acesso antes de continuar. As alterações foram conservadas.',
|
||||
);
|
||||
},
|
||||
onCancel: () => {
|
||||
if (alive.current && pending.current === attempt)
|
||||
setNotice(
|
||||
'Envio interrompido sem confirmação. Recupere a mesma criação.',
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
function refresh() {
|
||||
if (refreshing || form.processing) return;
|
||||
setRefreshing(true);
|
||||
router.reload({
|
||||
only: ['lead', 'owners', 'taskCreation', 'nextAction'],
|
||||
onSuccess: (page) => {
|
||||
if (!alive.current || !scoped(page.props)) return;
|
||||
setBlocked(false);
|
||||
if (pending.current && !acknowledge(page.props))
|
||||
setNotice(
|
||||
'A criação ainda não foi confirmada. Recupere o mesmo envio; as edições posteriores ficam para a próxima tarefa.',
|
||||
);
|
||||
},
|
||||
onFinish: () => {
|
||||
if (alive.current) setRefreshing(false);
|
||||
},
|
||||
});
|
||||
}
|
||||
const guard = useRef(false);
|
||||
guard.current =
|
||||
!preparation.durable &&
|
||||
(waiting ||
|
||||
!!form.data.title ||
|
||||
!!form.data.due_at ||
|
||||
(!!generation.current.assignee_user_id &&
|
||||
form.data.assignee_user_id !==
|
||||
String(lead.owner_user_id ?? '')));
|
||||
useEffect(() => {
|
||||
const remove = router.on('before', (event) => {
|
||||
const visit = event.detail.visit;
|
||||
if (
|
||||
guard.current &&
|
||||
visit.method === 'get' &&
|
||||
!visit.preserveState &&
|
||||
!window.confirm(
|
||||
'Existem alterações ou um envio por confirmar. Sair desta página?',
|
||||
)
|
||||
)
|
||||
event.preventDefault();
|
||||
});
|
||||
const unload = (event: BeforeUnloadEvent) => {
|
||||
if (guard.current) {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
}
|
||||
};
|
||||
window.addEventListener('beforeunload', unload);
|
||||
return () => {
|
||||
remove();
|
||||
window.removeEventListener('beforeunload', unload);
|
||||
};
|
||||
}, []);
|
||||
return {
|
||||
form,
|
||||
change,
|
||||
submit,
|
||||
refresh,
|
||||
waiting,
|
||||
blocked: blocked || !valid || (preparation.blocked && !canReplay),
|
||||
refreshing,
|
||||
notice,
|
||||
sent: pending.current?.values,
|
||||
preparation,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { profileJson, ProfileValidationError } from './profile-json';
|
||||
import { createOperationKey } from './operation-key';
|
||||
|
||||
export type TaskValues = {
|
||||
title: string;
|
||||
due_at: string;
|
||||
assignee_user_id: string;
|
||||
};
|
||||
export type TaskGeneration = Record<keyof TaskValues, number>;
|
||||
export type TaskAttempt = {
|
||||
values: TaskValues & { client_key: string };
|
||||
generation: TaskGeneration;
|
||||
};
|
||||
export type TaskPreparationSnapshot = {
|
||||
values: TaskValues;
|
||||
generation: TaskGeneration;
|
||||
pending: TaskAttempt | null;
|
||||
};
|
||||
export type TaskPreparationView = {
|
||||
installed: boolean;
|
||||
version: number;
|
||||
snapshot: TaskPreparationSnapshot | null;
|
||||
operation_key: string | null;
|
||||
unavailable: boolean;
|
||||
updated_at: string | null;
|
||||
};
|
||||
type Save = {
|
||||
version: number;
|
||||
operation_key: string;
|
||||
snapshot: TaskPreparationSnapshot;
|
||||
};
|
||||
const fields = ['title', 'due_at', 'assignee_user_id'] as const;
|
||||
const object = (value: unknown): value is Record<string, unknown> =>
|
||||
!!value && typeof value === 'object' && !Array.isArray(value);
|
||||
const integer = (value: unknown): value is number =>
|
||||
typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
|
||||
const values = (value: unknown): value is TaskValues =>
|
||||
object(value) && fields.every((field) => typeof value[field] === 'string');
|
||||
const generation = (value: unknown): value is TaskGeneration =>
|
||||
object(value) && fields.every((field) => integer(value[field]));
|
||||
function snapshot(value: unknown): value is TaskPreparationSnapshot {
|
||||
return (
|
||||
object(value) &&
|
||||
values(value.values) &&
|
||||
generation(value.generation) &&
|
||||
(value.pending === null ||
|
||||
(object(value.pending) &&
|
||||
object(value.pending.values) &&
|
||||
typeof value.pending.values.client_key === 'string' &&
|
||||
values(value.pending.values) &&
|
||||
generation(value.pending.generation)))
|
||||
);
|
||||
}
|
||||
function read(value: unknown): TaskPreparationView | null {
|
||||
return object(value) &&
|
||||
typeof value.installed === 'boolean' &&
|
||||
integer(value.version) &&
|
||||
typeof value.unavailable === 'boolean' &&
|
||||
(value.snapshot === null || snapshot(value.snapshot)) &&
|
||||
(value.operation_key === null ||
|
||||
typeof value.operation_key === 'string') &&
|
||||
(value.updated_at === null || typeof value.updated_at === 'string')
|
||||
? (value as TaskPreparationView)
|
||||
: null;
|
||||
}
|
||||
const signature = (value: TaskPreparationSnapshot) =>
|
||||
JSON.stringify({
|
||||
values: fields.map((field) => value.values[field]),
|
||||
generation: fields.map((field) => value.generation[field]),
|
||||
pending: value.pending
|
||||
? {
|
||||
values: [
|
||||
...fields.map((field) => value.pending?.values[field]),
|
||||
value.pending.values.client_key,
|
||||
],
|
||||
generation: fields.map(
|
||||
(field) => value.pending?.generation[field],
|
||||
),
|
||||
}
|
||||
: null,
|
||||
});
|
||||
export function taskDeadlineUtc(value: string): string {
|
||||
const date = new Date(value);
|
||||
return value && !Number.isNaN(date.getTime()) ? date.toISOString() : value;
|
||||
}
|
||||
export function taskDeadlineLocal(value: string): string {
|
||||
const date = new Date(value);
|
||||
return value && !Number.isNaN(date.getTime())
|
||||
? new Date(date.getTime() - date.getTimezoneOffset() * 60000)
|
||||
.toISOString()
|
||||
.slice(0, 16)
|
||||
: value;
|
||||
}
|
||||
|
||||
export function useCrmTaskPreparation({
|
||||
leadId,
|
||||
actorId,
|
||||
view,
|
||||
getSnapshot,
|
||||
onRecover,
|
||||
}: {
|
||||
leadId: string;
|
||||
actorId: number;
|
||||
view: unknown;
|
||||
getSnapshot: () => TaskPreparationSnapshot;
|
||||
onRecover: (value: TaskPreparationSnapshot) => boolean;
|
||||
}) {
|
||||
const incoming = read(view);
|
||||
const latest = useRef({ getSnapshot, onRecover });
|
||||
latest.current = { getSnapshot, onRecover };
|
||||
const alive = useRef(true),
|
||||
busy = useRef(false);
|
||||
const base = useRef(incoming);
|
||||
const initial = getSnapshot();
|
||||
const different =
|
||||
incoming?.snapshot &&
|
||||
(incoming.snapshot.pending !== null ||
|
||||
fields.some(
|
||||
(field) =>
|
||||
incoming.snapshot?.values[field] !== initial.values[field],
|
||||
));
|
||||
const saved = useRef(
|
||||
different && incoming.snapshot
|
||||
? signature(incoming.snapshot)
|
||||
: signature(initial),
|
||||
);
|
||||
const saveAttempt = useRef<Save | null>(null);
|
||||
const [comparison, setComparison] = useState<TaskPreparationView | null>(
|
||||
different ? incoming : null,
|
||||
);
|
||||
const [choices, setChoices] = useState<
|
||||
Partial<
|
||||
Record<
|
||||
keyof TaskValues,
|
||||
{ source: 'page' | 'saved'; generation: number }
|
||||
>
|
||||
>
|
||||
>({});
|
||||
const [state, setState] = useState<
|
||||
'ready' | 'saving' | 'error' | 'unavailable'
|
||||
>(incoming?.unavailable || (!!view && !incoming) ? 'unavailable' : 'ready');
|
||||
const [memoryOnly, setMemoryOnly] = useState(false);
|
||||
const [message, setMessage] = useState(
|
||||
incoming?.unavailable || (!!view && !incoming)
|
||||
? 'A preparação guardada não pôde ser lida. Actualize para recuperar o acesso ou continue só nesta página; os dados guardados ficam preservados.'
|
||||
: '',
|
||||
);
|
||||
const [, setTick] = useState(0);
|
||||
const current = getSnapshot(),
|
||||
currentSignature = signature(current);
|
||||
const enabled = !!incoming?.installed && !memoryOnly;
|
||||
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
};
|
||||
}, []);
|
||||
function response(value: unknown): TaskPreparationView | null {
|
||||
return object(value) &&
|
||||
value.lead_id === leadId &&
|
||||
value.actor_id === actorId
|
||||
? read(value.preparation)
|
||||
: null;
|
||||
}
|
||||
function confirmed(next: TaskPreparationView, attempt: Save) {
|
||||
if (
|
||||
next.version !== attempt.version + 1 ||
|
||||
next.operation_key !== attempt.operation_key ||
|
||||
!next.snapshot ||
|
||||
signature(next.snapshot) !== signature(attempt.snapshot)
|
||||
)
|
||||
return false;
|
||||
base.current = next;
|
||||
saved.current = signature(attempt.snapshot);
|
||||
saveAttempt.current = null;
|
||||
setState('ready');
|
||||
setMessage(
|
||||
'Preparação guardada no servidor. Pode retomá-la nesta conta.',
|
||||
);
|
||||
return true;
|
||||
}
|
||||
useEffect(() => {
|
||||
if (!incoming || !incoming.installed || memoryOnly || busy.current)
|
||||
return;
|
||||
if (saveAttempt.current && confirmed(incoming, saveAttempt.current))
|
||||
return;
|
||||
if (incoming.version > (base.current?.version ?? 0)) {
|
||||
setComparison(incoming);
|
||||
setChoices({});
|
||||
setMessage(
|
||||
'A preparação mudou. Compare antes de substituir os dados guardados.',
|
||||
);
|
||||
}
|
||||
}, [view, state, memoryOnly]);
|
||||
|
||||
async function ensure(forSubmission = true): Promise<boolean> {
|
||||
if (!enabled) return true;
|
||||
const now = latest.current.getSnapshot();
|
||||
if (
|
||||
forSubmission &&
|
||||
now.pending &&
|
||||
base.current?.snapshot?.pending?.values.client_key ===
|
||||
now.pending.values.client_key
|
||||
)
|
||||
return true;
|
||||
if (busy.current || comparison || state === 'unavailable') return false;
|
||||
if (!saveAttempt.current && signature(now) === saved.current)
|
||||
return true;
|
||||
let attempt = saveAttempt.current;
|
||||
if (!attempt) {
|
||||
try {
|
||||
attempt = {
|
||||
version: base.current?.version ?? 0,
|
||||
operation_key: createOperationKey(),
|
||||
snapshot: now,
|
||||
};
|
||||
} catch {
|
||||
setState('error');
|
||||
setMessage(
|
||||
'Não foi possível preparar a gravação. Reabra o portal no endereço HTTPS configurado.',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
saveAttempt.current = attempt;
|
||||
busy.current = true;
|
||||
setState('saving');
|
||||
setMessage('A guardar a preparação…');
|
||||
try {
|
||||
const result: unknown = await profileJson(
|
||||
`/management/crm/leads/${leadId}/task-preparation`,
|
||||
attempt,
|
||||
);
|
||||
if (!alive.current) return false;
|
||||
const next = response(result);
|
||||
if (!next || !confirmed(next, attempt))
|
||||
throw new Error('Unconfirmed preparation');
|
||||
// A previous automatic save may have preceded the creation attempt.
|
||||
const pending = latest.current.getSnapshot().pending;
|
||||
if (
|
||||
forSubmission &&
|
||||
pending &&
|
||||
next.snapshot?.pending?.values.client_key !==
|
||||
pending.values.client_key
|
||||
) {
|
||||
busy.current = false;
|
||||
return await ensure(true);
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (alive.current) {
|
||||
if (
|
||||
error instanceof ProfileValidationError &&
|
||||
Object.keys(error.fields).length
|
||||
)
|
||||
saveAttempt.current = null;
|
||||
setState('error');
|
||||
setMessage(
|
||||
error instanceof ProfileValidationError
|
||||
? Object.keys(error.fields).length
|
||||
? 'Reveja os campos da preparação antes de guardar. As alterações desta página foram conservadas.'
|
||||
: error.message
|
||||
: 'Não foi possível confirmar a preparação. Conserve esta página e volte a guardar ou actualize para comparar.',
|
||||
);
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
busy.current = false;
|
||||
if (alive.current) setTick((value) => value + 1);
|
||||
}
|
||||
}
|
||||
useEffect(() => {
|
||||
const hasWork =
|
||||
!!current.values.title ||
|
||||
!!current.values.due_at ||
|
||||
!!current.pending ||
|
||||
fields.some((field) => current.generation[field] > 0);
|
||||
if (
|
||||
!enabled ||
|
||||
state !== 'ready' ||
|
||||
comparison ||
|
||||
busy.current ||
|
||||
!hasWork ||
|
||||
currentSignature === saved.current
|
||||
)
|
||||
return;
|
||||
const timer = setTimeout(() => {
|
||||
void ensure(false);
|
||||
}, 800);
|
||||
return () => clearTimeout(timer);
|
||||
}, [currentSignature, enabled, state, comparison]);
|
||||
|
||||
const source = (field: keyof TaskValues) =>
|
||||
choices[field]?.source ??
|
||||
(current.generation[field] > 0 ? 'page' : 'saved');
|
||||
const unresolved = fields.filter(
|
||||
(field) =>
|
||||
choices[field]?.source === 'saved' &&
|
||||
choices[field]?.generation !== current.generation[field],
|
||||
);
|
||||
function choose(field: keyof TaskValues, value: 'page' | 'saved') {
|
||||
setChoices((previous) => ({
|
||||
...previous,
|
||||
[field]: {
|
||||
source: value,
|
||||
generation: latest.current.getSnapshot().generation[field],
|
||||
},
|
||||
}));
|
||||
}
|
||||
function recover() {
|
||||
if (
|
||||
!comparison?.snapshot ||
|
||||
comparison.unavailable ||
|
||||
busy.current ||
|
||||
unresolved.length
|
||||
)
|
||||
return;
|
||||
const now = latest.current.getSnapshot(),
|
||||
stored = comparison.snapshot;
|
||||
const next: TaskPreparationSnapshot = {
|
||||
values: { ...stored.values },
|
||||
generation: { ...stored.generation },
|
||||
pending: stored.pending,
|
||||
};
|
||||
for (const field of fields) {
|
||||
if (source(field) === 'page') {
|
||||
next.values[field] = now.values[field];
|
||||
next.generation[field] =
|
||||
Math.max(
|
||||
now.generation[field],
|
||||
stored.generation[field],
|
||||
stored.pending?.generation[field] ?? 0,
|
||||
) + 1;
|
||||
}
|
||||
}
|
||||
if (!latest.current.onRecover(next)) {
|
||||
setMessage(
|
||||
'Existe outro envio sem confirmação nesta página. Recupere esse envio antes de adoptar a preparação guardada.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
base.current = comparison;
|
||||
saved.current = signature(stored);
|
||||
saveAttempt.current = null;
|
||||
setComparison(null);
|
||||
setChoices({});
|
||||
setState('ready');
|
||||
setMessage(
|
||||
'Preparação recuperada. Compare os campos e confirme a acção pretendida.',
|
||||
);
|
||||
}
|
||||
return {
|
||||
enabled,
|
||||
state,
|
||||
comparison,
|
||||
current,
|
||||
source,
|
||||
unresolved,
|
||||
choose,
|
||||
recover,
|
||||
ensure,
|
||||
message,
|
||||
blocked:
|
||||
enabled &&
|
||||
(!!comparison ||
|
||||
state === 'unavailable' ||
|
||||
state === 'saving' ||
|
||||
state === 'error'),
|
||||
durable:
|
||||
enabled &&
|
||||
state === 'ready' &&
|
||||
!saveAttempt.current &&
|
||||
currentSignature === saved.current,
|
||||
manual: () => {
|
||||
setMemoryOnly(true);
|
||||
setComparison(null);
|
||||
setMessage(
|
||||
'Continua apenas nesta página. A preparação guardada no servidor foi preservada.',
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import type { DeskAnswer } from './desk-field-values';
|
||||
|
||||
export type DeskAnswers = Record<string, DeskAnswer>;
|
||||
export type CheckpointRequest = {
|
||||
id: string;
|
||||
version: number;
|
||||
status: string;
|
||||
payload: DeskAnswers;
|
||||
editable_fields: string[];
|
||||
can_edit: boolean;
|
||||
protocol: string | null;
|
||||
analyst_id: number | null;
|
||||
due_at: string | null;
|
||||
};
|
||||
export type CheckpointInput = {
|
||||
version: number;
|
||||
request_version: number;
|
||||
operation_key: string;
|
||||
payload: DeskAnswers;
|
||||
edited_keys: string[];
|
||||
reason: string;
|
||||
};
|
||||
export type DeskCheckpoint = {
|
||||
version: number;
|
||||
request_version: number;
|
||||
updated_at: string;
|
||||
payload: DeskAnswers;
|
||||
base_payload: DeskAnswers;
|
||||
edited_keys: string[];
|
||||
reason: string;
|
||||
};
|
||||
export type CheckpointView = {
|
||||
installed: boolean;
|
||||
request: CheckpointRequest;
|
||||
checkpoint: DeskCheckpoint | null;
|
||||
};
|
||||
export type RecoveryChoice = 'page' | 'saved' | 'current';
|
||||
|
||||
export function checkpointSignature(values: DeskAnswers): string {
|
||||
return JSON.stringify(
|
||||
Object.fromEntries(
|
||||
Object.entries(values)
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.map(([key, value]) => [
|
||||
key,
|
||||
Array.isArray(value) ? [...value].sort() : (value ?? null),
|
||||
]),
|
||||
),
|
||||
);
|
||||
}
|
||||
export const checkpointSame = (
|
||||
a: DeskAnswer | undefined,
|
||||
b: DeskAnswer | undefined,
|
||||
) =>
|
||||
checkpointSignature({ value: a ?? null }) ===
|
||||
checkpointSignature({ value: b ?? null });
|
||||
|
||||
const contextKeys = [
|
||||
'context_opportunity',
|
||||
'context_opportunity_snapshot',
|
||||
'context_reuse',
|
||||
];
|
||||
function contextLabel(values: DeskAnswers | undefined): string {
|
||||
if (!values?.context_opportunity) return 'Sem oportunidade seleccionada';
|
||||
try {
|
||||
const snapshot = JSON.parse(
|
||||
String(values.context_opportunity_snapshot ?? '{}'),
|
||||
);
|
||||
if (typeof snapshot.choice?.opportunity?.title === 'string')
|
||||
return (
|
||||
snapshot.choice.opportunity.title +
|
||||
(Number.isInteger(snapshot.revision)
|
||||
? ` · revisão ${snapshot.revision}`
|
||||
: '')
|
||||
);
|
||||
} catch {
|
||||
/* A legacy context still remains recoverable. */
|
||||
}
|
||||
return 'Oportunidade seleccionada; designação por recuperar';
|
||||
}
|
||||
|
||||
/** Three sources remain explicit; a deliberate revert is still an edit. */
|
||||
export function checkpointRecovery(
|
||||
base: DeskAnswers,
|
||||
page: DeskAnswers,
|
||||
edited: readonly string[],
|
||||
current: DeskAnswers,
|
||||
saved: DeskCheckpoint | null,
|
||||
allowed: readonly string[],
|
||||
choices: Record<string, RecoveryChoice> = {},
|
||||
) {
|
||||
const payload = { ...current };
|
||||
const conflicts: string[] = [];
|
||||
const intent: string[] = [];
|
||||
const rows: {
|
||||
key: string;
|
||||
page: DeskAnswer | null;
|
||||
saved: DeskAnswer | null;
|
||||
current: DeskAnswer | null;
|
||||
conflict: boolean;
|
||||
choice: RecoveryChoice;
|
||||
}[] = [];
|
||||
for (const key of allowed) {
|
||||
if (contextKeys.includes(key) && key !== 'context_opportunity')
|
||||
continue;
|
||||
const group =
|
||||
key === 'context_opportunity'
|
||||
? contextKeys.filter((k) => allowed.includes(k))
|
||||
: [key];
|
||||
const same = (a: DeskAnswers | undefined, b: DeskAnswers | undefined) =>
|
||||
group.every((k) => checkpointSame(a?.[k], b?.[k]));
|
||||
const local =
|
||||
group.some((k) => edited.includes(k)) || !same(page, base);
|
||||
const remote =
|
||||
!!saved &&
|
||||
(group.some((k) => saved.edited_keys.includes(k)) ||
|
||||
!same(saved.payload, saved.base_payload));
|
||||
if (!local && !remote) continue;
|
||||
const conflict =
|
||||
(local && remote && !same(page, saved?.payload)) ||
|
||||
(local && !same(base, current) && !same(page, current)) ||
|
||||
(remote &&
|
||||
!same(saved?.base_payload, current) &&
|
||||
!same(saved?.payload, current));
|
||||
const choice = choices[key] ?? (local ? 'page' : 'saved');
|
||||
if (conflict && !choices[key]) conflicts.push(key);
|
||||
for (const member of group)
|
||||
payload[member] =
|
||||
(choice === 'page'
|
||||
? page[member]
|
||||
: choice === 'saved'
|
||||
? saved?.payload[member]
|
||||
: current[member]) ?? null;
|
||||
if (choice !== 'current') intent.push(...group);
|
||||
rows.push({
|
||||
key,
|
||||
page:
|
||||
key === 'context_opportunity'
|
||||
? contextLabel(page)
|
||||
: (page[key] ?? null),
|
||||
saved:
|
||||
key === 'context_opportunity'
|
||||
? contextLabel(saved?.payload)
|
||||
: (saved?.payload[key] ?? null),
|
||||
current:
|
||||
key === 'context_opportunity'
|
||||
? contextLabel(current)
|
||||
: (current[key] ?? null),
|
||||
conflict,
|
||||
choice,
|
||||
});
|
||||
}
|
||||
return { payload, conflicts, intent, rows };
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
export type DeskValueField = { type: string; options?: Record<string, string> };
|
||||
export type DeskAnswer = string | number | boolean | string[] | null;
|
||||
|
||||
export function deskScalar(value: unknown): string {
|
||||
if (typeof value === 'string' || typeof value === 'number')
|
||||
return String(value);
|
||||
if (typeof value === 'boolean') return value ? '1' : '';
|
||||
return '';
|
||||
}
|
||||
|
||||
export function deskChoices(value: unknown): string[] {
|
||||
return Array.isArray(value) && value.every((v) => typeof v === 'string')
|
||||
? value
|
||||
: [];
|
||||
}
|
||||
|
||||
export function deskEmpty(value: unknown): boolean {
|
||||
return (
|
||||
value === null ||
|
||||
value === undefined ||
|
||||
(typeof value === 'string' && value.trim() === '') ||
|
||||
(Array.isArray(value) && value.length === 0)
|
||||
);
|
||||
}
|
||||
|
||||
/** Preserve typed answers and refusals; a master/profile can never supply a consent declaration. */
|
||||
export function mergeDeskPrefill(
|
||||
current: Record<string, DeskAnswer>,
|
||||
patch: Record<string, unknown>,
|
||||
fields: Record<string, DeskValueField>,
|
||||
replace = false,
|
||||
): Record<string, DeskAnswer> {
|
||||
const next = { ...current };
|
||||
for (const [key, value] of Object.entries(patch)) {
|
||||
const field = fields[key];
|
||||
if (
|
||||
field?.type === 'consent' ||
|
||||
field?.type === 'attachment' ||
|
||||
(!replace && !deskEmpty(current[key]))
|
||||
)
|
||||
continue;
|
||||
if (field?.type === 'multiselect') {
|
||||
if (
|
||||
Array.isArray(value) &&
|
||||
value.every(
|
||||
(v) =>
|
||||
typeof v === 'string' &&
|
||||
Object.hasOwn(field.options ?? {}, v),
|
||||
)
|
||||
)
|
||||
next[key] = [...value];
|
||||
} else if (
|
||||
value === null ||
|
||||
typeof value === 'string' ||
|
||||
typeof value === 'number' ||
|
||||
typeof value === 'boolean'
|
||||
)
|
||||
next[key] = value;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
type ConditionalField = { when?: { field: string; equals: string } };
|
||||
type ConditionalField = {
|
||||
when?: { field: string; equals: string; operator?: 'equals' | 'contains' };
|
||||
};
|
||||
|
||||
export function deskFieldApplies(
|
||||
key: string,
|
||||
@@ -10,6 +12,21 @@ export function deskFieldApplies(
|
||||
if (!field || ancestors.has(key)) return false;
|
||||
if (!field.when) return true;
|
||||
const value = payload[field.when.field];
|
||||
if (field.when.operator === 'contains') {
|
||||
if (
|
||||
!Array.isArray(value) ||
|
||||
!value.some(
|
||||
(v) => typeof v === 'string' && v === field.when!.equals,
|
||||
)
|
||||
)
|
||||
return false;
|
||||
return deskFieldApplies(
|
||||
field.when.field,
|
||||
fields,
|
||||
payload,
|
||||
new Set([...ancestors, key]),
|
||||
);
|
||||
}
|
||||
if (!['string', 'number', 'boolean'].includes(typeof value)) return false;
|
||||
const answer =
|
||||
typeof value === 'boolean' ? (value ? '1' : '') : String(value);
|
||||
|
||||
@@ -0,0 +1,388 @@
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { createOperationKey } from './operation-key';
|
||||
|
||||
export type EducationDeclaration = {
|
||||
id: string;
|
||||
qualification: string;
|
||||
quantity: number;
|
||||
status: string;
|
||||
version_no: number;
|
||||
period_start: string;
|
||||
period_end: string;
|
||||
reference_date?: string;
|
||||
valid_until: string;
|
||||
source: string;
|
||||
submitted_by_name?: string | null;
|
||||
reviewed_by_name?: string | null;
|
||||
review_reason?: string | null;
|
||||
employer?: string;
|
||||
can_review?: boolean;
|
||||
review_unavailable?: 'self' | 'expired' | null;
|
||||
review_context?: {
|
||||
actor_id: number;
|
||||
commands: { key: string; version: number }[];
|
||||
};
|
||||
};
|
||||
export type EducationReviewProps = {
|
||||
declaration: EducationDeclaration;
|
||||
kind: 'demands' | 'capacities';
|
||||
actorId: number;
|
||||
today: string;
|
||||
references?: Record<string, string | null>;
|
||||
};
|
||||
type Values = { version_no: number; status: string; review_reason: string };
|
||||
type Snapshot = Pick<
|
||||
EducationDeclaration,
|
||||
| 'version_no'
|
||||
| 'qualification'
|
||||
| 'quantity'
|
||||
| 'status'
|
||||
| 'period_start'
|
||||
| 'period_end'
|
||||
| 'valid_until'
|
||||
| 'source'
|
||||
> & {
|
||||
reference_date: string;
|
||||
employer: string;
|
||||
references: Record<string, string | null>;
|
||||
};
|
||||
type Attempt = {
|
||||
values: Values & { client_key: string };
|
||||
reasonGeneration: number;
|
||||
statusGeneration: number;
|
||||
base: Snapshot;
|
||||
};
|
||||
const object = (value: unknown): value is Record<string, unknown> =>
|
||||
!!value && typeof value === 'object' && !Array.isArray(value);
|
||||
const positive = (value: unknown): value is number =>
|
||||
typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
|
||||
const snapshot = (
|
||||
row: EducationDeclaration,
|
||||
references: Record<string, string | null> = {},
|
||||
): Snapshot => ({
|
||||
version_no: row.version_no,
|
||||
qualification: row.qualification,
|
||||
quantity: row.quantity,
|
||||
status: row.status,
|
||||
period_start: row.period_start,
|
||||
period_end: row.period_end,
|
||||
valid_until: row.valid_until,
|
||||
source: row.source,
|
||||
reference_date: row.reference_date ?? '',
|
||||
employer: row.employer ?? '',
|
||||
references: { ...references },
|
||||
});
|
||||
|
||||
export function useEducationReview({
|
||||
declaration: row,
|
||||
kind,
|
||||
actorId,
|
||||
references = {},
|
||||
}: EducationReviewProps) {
|
||||
const form = useForm<Values>({
|
||||
version_no: row.version_no,
|
||||
status: 'reviewed',
|
||||
review_reason: '',
|
||||
});
|
||||
const live = useRef(form.data);
|
||||
live.current = form.data;
|
||||
const base = useRef(snapshot(row, references)),
|
||||
pending = useRef<Attempt | null>(null),
|
||||
alive = useRef(true);
|
||||
const generation = useRef({ status: 0, review_reason: 0 });
|
||||
const [uncertain, setUncertain] = useState(false),
|
||||
[conflict, setConflict] = useState(false),
|
||||
[refreshing, setRefreshing] = useState(false),
|
||||
[accessBlocked, setAccessBlocked] = useState(false),
|
||||
[notice, setNotice] = useState('');
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
};
|
||||
}, []);
|
||||
const invalid =
|
||||
!positive(actorId) ||
|
||||
row.review_context?.actor_id !== actorId ||
|
||||
!positive(row.version_no) ||
|
||||
!Array.isArray(row.review_context?.commands);
|
||||
const stale = form.data.version_no !== row.version_no;
|
||||
function change(field: 'status' | 'review_reason', value: string) {
|
||||
generation.current[field]++;
|
||||
live.current = { ...live.current, [field]: value };
|
||||
form.setData(live.current);
|
||||
}
|
||||
function read(props: unknown): EducationDeclaration | null {
|
||||
if (
|
||||
!object(props) ||
|
||||
props.actorId !== actorId ||
|
||||
props.kind !== kind ||
|
||||
!object(props.declaration) ||
|
||||
props.declaration.id !== row.id
|
||||
)
|
||||
return null;
|
||||
const value = props.declaration;
|
||||
if (
|
||||
!positive(value.version_no) ||
|
||||
!object(value.review_context) ||
|
||||
value.review_context.actor_id !== actorId ||
|
||||
!Array.isArray(value.review_context.commands)
|
||||
)
|
||||
return null;
|
||||
return value as EducationDeclaration;
|
||||
}
|
||||
function returnedReferences(
|
||||
props: Record<string, unknown>,
|
||||
): Record<string, string | null> | null {
|
||||
if (
|
||||
!object(props.references) ||
|
||||
Object.values(props.references).some(
|
||||
(value) => value !== null && typeof value !== 'string',
|
||||
)
|
||||
)
|
||||
return null;
|
||||
return props.references as Record<string, string | null>;
|
||||
}
|
||||
function acknowledge(
|
||||
record: EducationDeclaration,
|
||||
currentReferences: Record<string, string | null> = references,
|
||||
) {
|
||||
const attempt = pending.current;
|
||||
if (
|
||||
!alive.current ||
|
||||
!attempt ||
|
||||
record.review_context?.actor_id !== actorId
|
||||
)
|
||||
return false;
|
||||
const receipt = record.review_context.commands.find(
|
||||
(item) => item.key === attempt.values.client_key,
|
||||
);
|
||||
if (
|
||||
!receipt ||
|
||||
receipt.version !== attempt.values.version_no + 1 ||
|
||||
record.version_no < receipt.version
|
||||
)
|
||||
return false;
|
||||
base.current =
|
||||
record.version_no === receipt.version
|
||||
? snapshot(record, currentReferences)
|
||||
: {
|
||||
...attempt.base,
|
||||
version_no: receipt.version,
|
||||
status: attempt.values.status,
|
||||
};
|
||||
live.current = {
|
||||
version_no: receipt.version,
|
||||
status:
|
||||
generation.current.status === attempt.statusGeneration
|
||||
? 'reviewed'
|
||||
: live.current.status,
|
||||
review_reason:
|
||||
generation.current.review_reason === attempt.reasonGeneration
|
||||
? ''
|
||||
: live.current.review_reason,
|
||||
};
|
||||
form.setData(live.current);
|
||||
form.clearErrors();
|
||||
pending.current = null;
|
||||
setUncertain(false);
|
||||
setConflict(false);
|
||||
setAccessBlocked(false);
|
||||
setNotice(
|
||||
'Revisão registada. As alterações posteriores ao envio foram conservadas.',
|
||||
);
|
||||
return true;
|
||||
}
|
||||
useEffect(() => {
|
||||
if (!invalid && pending.current) acknowledge(row);
|
||||
}, [row, actorId, invalid]);
|
||||
function submit() {
|
||||
if (
|
||||
invalid ||
|
||||
accessBlocked ||
|
||||
refreshing ||
|
||||
form.processing ||
|
||||
(!pending.current && (row.can_review !== true || stale || conflict))
|
||||
)
|
||||
return;
|
||||
if (!pending.current) {
|
||||
let key: string;
|
||||
try {
|
||||
key = createOperationKey();
|
||||
} catch {
|
||||
setNotice(
|
||||
'Não foi possível preparar a decisão. Reabra o portal no endereço HTTPS configurado.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
pending.current = {
|
||||
values: { ...live.current, client_key: key },
|
||||
reasonGeneration: generation.current.review_reason,
|
||||
statusGeneration: generation.current.status,
|
||||
base: { ...base.current },
|
||||
};
|
||||
}
|
||||
const attempt = pending.current;
|
||||
setUncertain(true);
|
||||
setNotice('A aguardar confirmação da revisão.');
|
||||
form.transform(() => attempt.values);
|
||||
form.post(`/management/education/${kind}/${row.id}/review`, {
|
||||
preserveScroll: true,
|
||||
onSuccess: (page) => {
|
||||
if (!alive.current || pending.current !== attempt) return;
|
||||
const record = read(page.props),
|
||||
labels = returnedReferences(page.props);
|
||||
if (!record || !labels || !acknowledge(record, labels))
|
||||
setNotice(
|
||||
'A resposta não permitiu confirmar a revisão. Actualize a declaração ou recupere o mesmo envio.',
|
||||
);
|
||||
},
|
||||
onError: () => {
|
||||
if (!alive.current || pending.current !== attempt) return;
|
||||
pending.current = null;
|
||||
setUncertain(false);
|
||||
setNotice(
|
||||
'Reveja os campos assinalados. A decisão preparada foi conservada.',
|
||||
);
|
||||
},
|
||||
onNetworkError: () => {
|
||||
if (alive.current && pending.current === attempt)
|
||||
setNotice(
|
||||
'Sem confirmação da revisão. Recupere o mesmo envio antes de preparar outra decisão.',
|
||||
);
|
||||
},
|
||||
onCancel: () => {
|
||||
if (alive.current && pending.current === attempt)
|
||||
setNotice(
|
||||
'Envio interrompido sem confirmação. Recupere o mesmo envio.',
|
||||
);
|
||||
},
|
||||
onHttpException: (response) => {
|
||||
if (!alive.current || pending.current !== attempt) return;
|
||||
if ([401, 403, 419].includes(response.status))
|
||||
setAccessBlocked(true);
|
||||
if (response.status === 422) {
|
||||
pending.current = null;
|
||||
setUncertain(false);
|
||||
}
|
||||
if ([409, 422].includes(response.status)) setConflict(true);
|
||||
setNotice(
|
||||
'Não foi possível confirmar a revisão. Actualize a declaração e o acesso antes de continuar. A decisão preparada foi conservada.',
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
function refresh() {
|
||||
if (refreshing || form.processing) return;
|
||||
setRefreshing(true);
|
||||
router.reload({
|
||||
only: [
|
||||
'declaration',
|
||||
'references',
|
||||
'today',
|
||||
'actorId',
|
||||
'kind',
|
||||
'history',
|
||||
],
|
||||
onSuccess: (page) => {
|
||||
if (!alive.current) return;
|
||||
const record = read(page.props),
|
||||
labels = returnedReferences(page.props);
|
||||
if (!record || !labels) return;
|
||||
setAccessBlocked(false);
|
||||
if (pending.current) acknowledge(record, labels);
|
||||
},
|
||||
onFinish: () => {
|
||||
if (alive.current) setRefreshing(false);
|
||||
},
|
||||
});
|
||||
}
|
||||
function adopt() {
|
||||
if (
|
||||
invalid ||
|
||||
!stale ||
|
||||
row.can_review !== true ||
|
||||
refreshing ||
|
||||
form.processing
|
||||
)
|
||||
return;
|
||||
const attempt = pending.current;
|
||||
if (attempt) {
|
||||
if (acknowledge(row)) return;
|
||||
if (
|
||||
row.version_no <= attempt.values.version_no ||
|
||||
row.review_context?.commands.some(
|
||||
(item) => item.key === attempt.values.client_key,
|
||||
)
|
||||
)
|
||||
return;
|
||||
pending.current = null;
|
||||
setUncertain(false);
|
||||
}
|
||||
base.current = snapshot(row, references);
|
||||
live.current = { ...live.current, version_no: row.version_no };
|
||||
form.setData(live.current);
|
||||
setConflict(false);
|
||||
form.clearErrors('version_no');
|
||||
setNotice(
|
||||
'Versão actual confirmada. A sua decisão preparada foi conservada para rever antes de enviar.',
|
||||
);
|
||||
}
|
||||
const guard = useRef(false);
|
||||
guard.current =
|
||||
uncertain ||
|
||||
!!form.data.review_reason ||
|
||||
form.data.status !== 'reviewed';
|
||||
useEffect(() => {
|
||||
const remove = router.on('before', (event) => {
|
||||
if (
|
||||
guard.current &&
|
||||
event.detail.visit.method === 'get' &&
|
||||
!event.detail.visit.preserveState &&
|
||||
!window.confirm(
|
||||
'Existe uma revisão preparada ou um envio sem confirmação. Sair desta página?',
|
||||
)
|
||||
)
|
||||
event.preventDefault();
|
||||
});
|
||||
const unload = (event: BeforeUnloadEvent) => {
|
||||
if (guard.current) {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
}
|
||||
};
|
||||
window.addEventListener('beforeunload', unload);
|
||||
return () => {
|
||||
remove();
|
||||
window.removeEventListener('beforeunload', unload);
|
||||
};
|
||||
}, []);
|
||||
return {
|
||||
form,
|
||||
change,
|
||||
submit,
|
||||
refresh,
|
||||
adopt,
|
||||
base: base.current,
|
||||
current: snapshot(row, references),
|
||||
stale,
|
||||
conflict,
|
||||
refreshing,
|
||||
uncertain,
|
||||
notice,
|
||||
canAdopt:
|
||||
!invalid &&
|
||||
stale &&
|
||||
row.can_review === true &&
|
||||
!refreshing &&
|
||||
!form.processing,
|
||||
blocked:
|
||||
invalid ||
|
||||
accessBlocked ||
|
||||
refreshing ||
|
||||
(!pending.current &&
|
||||
(row.can_review !== true || stale || conflict)),
|
||||
sent: pending.current?.values,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
export type GuideSelection = {
|
||||
slug: string;
|
||||
sha256: string;
|
||||
instruments: string[];
|
||||
};
|
||||
|
||||
export function guideUrl(
|
||||
base: string,
|
||||
selection: GuideSelection,
|
||||
choosingDossier = false,
|
||||
): string {
|
||||
const query = new URLSearchParams();
|
||||
if (choosingDossier) {
|
||||
query.set('investment_guide[slug]', selection.slug);
|
||||
query.set('investment_guide[sha256]', selection.sha256);
|
||||
selection.instruments.forEach((code) =>
|
||||
query.append('investment_guide[instruments][]', code),
|
||||
);
|
||||
} else {
|
||||
query.set('current', '1');
|
||||
query.set('selection', '1');
|
||||
query.set('sha256', selection.sha256);
|
||||
selection.instruments.forEach((code) =>
|
||||
query.append('instruments[]', code),
|
||||
);
|
||||
}
|
||||
return `${base}?${query}`;
|
||||
}
|
||||
|
||||
export function guideChoices(form: HTMLFormElement): string[] {
|
||||
return new FormData(form)
|
||||
.getAll('instruments[]')
|
||||
.filter((v): v is string => typeof v === 'string');
|
||||
}
|
||||
@@ -0,0 +1,433 @@
|
||||
import { router } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { createOperationKey } from './operation-key';
|
||||
import { portalRequest, PortalApiError } from './portal-api';
|
||||
|
||||
export type ProfileRecord = {
|
||||
id?: string;
|
||||
version: number;
|
||||
payload: Record<string, string>;
|
||||
};
|
||||
export type OrganizationRecord = {
|
||||
id: string;
|
||||
name: string;
|
||||
version: number;
|
||||
country: string | null;
|
||||
canEdit: boolean;
|
||||
provenance: { reference: string; kind: string } | null;
|
||||
};
|
||||
type Attempt = {
|
||||
version: number;
|
||||
payload: Record<string, string>;
|
||||
operation_key: string;
|
||||
};
|
||||
const values = (record: ProfileRecord, fields: string[]) =>
|
||||
Object.fromEntries(
|
||||
[...fields, 'country'].map((key) => [key, record.payload[key] ?? '']),
|
||||
);
|
||||
const same = (left: Record<string, string>, right: Record<string, string>) =>
|
||||
JSON.stringify(left) === JSON.stringify(right);
|
||||
|
||||
export function useInvestmentProfileEditor(
|
||||
record: ProfileRecord,
|
||||
fields: string[],
|
||||
company: boolean,
|
||||
actorId: number,
|
||||
editorId: string,
|
||||
reportDirty: (id: string, dirty: boolean) => void,
|
||||
organization?: { id: string; canEdit: boolean },
|
||||
) {
|
||||
const [base, setBase] = useState(() => ({
|
||||
...record,
|
||||
payload: values(record, fields),
|
||||
})),
|
||||
[draft, setDraft] = useState(() => values(record, fields)),
|
||||
[remote, setRemote] = useState<ProfileRecord | null>(null),
|
||||
[busy, setBusy] = useState(false),
|
||||
[reading, setReading] = useState(false),
|
||||
[uncertain, setUncertain] = useState(false),
|
||||
[blocked, setBlocked] = useState(false),
|
||||
[errors, setErrors] = useState<Record<string, string>>({}),
|
||||
[error, setError] = useState(''),
|
||||
[notice, setNotice] = useState(''),
|
||||
[externalBusy, setExternalBusy] = useState(false),
|
||||
[permission, setPermission] = useState<{
|
||||
editable: boolean;
|
||||
propVersion: number;
|
||||
propCanEdit: boolean;
|
||||
} | null>(null);
|
||||
const pending = useRef<Attempt | null>(null),
|
||||
externalLock = useRef(false),
|
||||
readInFlight = useRef(false),
|
||||
active = useRef(false),
|
||||
alive = useRef(true),
|
||||
origin = useRef({ actorId, id: record.id }),
|
||||
current = useRef({ actorId, id: record.id });
|
||||
current.current = { actorId, id: record.id };
|
||||
const valid = () =>
|
||||
alive.current &&
|
||||
Number.isSafeInteger(actorId) &&
|
||||
actorId > 0 &&
|
||||
origin.current.actorId === current.current.actorId &&
|
||||
origin.current.id === current.current.id;
|
||||
const dirty =
|
||||
!same(draft, base.payload) || busy || uncertain || externalBusy;
|
||||
const stale = (!company || !!record.id) && record.version > base.version;
|
||||
const mayEdit =
|
||||
!organization ||
|
||||
(permission &&
|
||||
permission.propVersion === record.version &&
|
||||
permission.propCanEdit === organization.canEdit
|
||||
? permission.editable
|
||||
: organization.canEdit);
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
reportDirty(editorId, dirty);
|
||||
}, [dirty, editorId, reportDirty]);
|
||||
useEffect(
|
||||
() => () => reportDirty(editorId, false),
|
||||
[editorId, reportDirty],
|
||||
);
|
||||
function change(key: string, value: string) {
|
||||
if (
|
||||
active.current ||
|
||||
externalLock.current ||
|
||||
uncertain ||
|
||||
blocked ||
|
||||
!mayEdit ||
|
||||
!valid()
|
||||
)
|
||||
return;
|
||||
setDraft((prior) => ({ ...prior, [key]: value }));
|
||||
setErrors((prior) => {
|
||||
const next = { ...prior };
|
||||
delete next['payload.' + key];
|
||||
delete next[key];
|
||||
return next;
|
||||
});
|
||||
setNotice('');
|
||||
}
|
||||
async function save() {
|
||||
if (
|
||||
active.current ||
|
||||
externalLock.current ||
|
||||
readInFlight.current ||
|
||||
reading ||
|
||||
blocked ||
|
||||
!mayEdit ||
|
||||
!valid() ||
|
||||
(stale && !pending.current)
|
||||
)
|
||||
return;
|
||||
try {
|
||||
pending.current ??= {
|
||||
version: base.version,
|
||||
payload: { ...draft },
|
||||
operation_key: createOperationKey(),
|
||||
};
|
||||
} catch (failure) {
|
||||
setError(
|
||||
failure instanceof Error
|
||||
? failure.message
|
||||
: 'Não foi possível preparar o pedido.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
const attempt = pending.current;
|
||||
active.current = true;
|
||||
setBusy(true);
|
||||
setError('');
|
||||
setErrors({});
|
||||
setNotice('');
|
||||
try {
|
||||
const result = await portalRequest<{
|
||||
version: number;
|
||||
id?: string;
|
||||
country?: string;
|
||||
}>(
|
||||
organization
|
||||
? '/api/v1/investment/organizations/' +
|
||||
organization.id +
|
||||
'/country'
|
||||
: company
|
||||
? '/api/v1/investment/companies' +
|
||||
(record.id ? '/' + record.id : '')
|
||||
: '/api/v1/investment/profile',
|
||||
{
|
||||
method: company ? 'POST' : 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(
|
||||
organization
|
||||
? {
|
||||
version: attempt.version,
|
||||
operation_key: attempt.operation_key,
|
||||
...attempt.payload,
|
||||
}
|
||||
: attempt,
|
||||
),
|
||||
},
|
||||
);
|
||||
if (!valid() || pending.current !== attempt) return;
|
||||
if (
|
||||
!Number.isSafeInteger(result.version) ||
|
||||
result.version !== attempt.version + 1 ||
|
||||
(organization && result.country !== attempt.payload.country) ||
|
||||
(company &&
|
||||
(typeof result.id !== 'string' ||
|
||||
!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(
|
||||
result.id,
|
||||
) ||
|
||||
(record.id && result.id !== record.id)))
|
||||
)
|
||||
throw new Error('Unconfirmed response');
|
||||
pending.current = null;
|
||||
setUncertain(false);
|
||||
setRemote(null);
|
||||
if (company && !record.id) {
|
||||
const empty = values({ version: 0, payload: {} }, fields);
|
||||
setDraft(empty);
|
||||
setBase({ version: 0, payload: empty });
|
||||
} else
|
||||
setBase({
|
||||
...record,
|
||||
version: result.version,
|
||||
payload: { ...attempt.payload },
|
||||
});
|
||||
setNotice('Gravação confirmada.');
|
||||
router.reload({
|
||||
only: organization
|
||||
? ['organizations']
|
||||
: ['account', 'companies'],
|
||||
});
|
||||
} catch (failure) {
|
||||
if (!valid() || pending.current !== attempt) return;
|
||||
if (failure instanceof PortalApiError && failure.status === 422) {
|
||||
pending.current = null;
|
||||
setUncertain(false);
|
||||
setErrors(
|
||||
Object.fromEntries(
|
||||
Object.entries(failure.errors).map(
|
||||
([key, messages]) => [
|
||||
key,
|
||||
messages[0] ?? 'Verifique este campo.',
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
setError('Verifique os campos assinalados.');
|
||||
} else if (
|
||||
failure instanceof PortalApiError &&
|
||||
failure.status === 409
|
||||
) {
|
||||
pending.current = null;
|
||||
setUncertain(false);
|
||||
setBlocked(true);
|
||||
setError(
|
||||
'O registo mudou ou este pedido já tem outro conteúdo. Consulte e compare o registo guardado antes de voltar a gravar.',
|
||||
);
|
||||
} else if (
|
||||
failure instanceof PortalApiError &&
|
||||
[401, 403, 404, 419].includes(failure.status)
|
||||
) {
|
||||
setBlocked(true);
|
||||
setUncertain(true);
|
||||
setError(
|
||||
'A sessão ou o acesso já não permite confirmar o pedido. A preparação permanece nesta página. Restabeleça o acesso e consulte o registo.',
|
||||
);
|
||||
} else {
|
||||
setUncertain(true);
|
||||
setError(
|
||||
'Não foi possível confirmar a gravação. A preparação foi conservada. Repita o mesmo pedido para confirmar o resultado antes de editar.',
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (valid()) {
|
||||
active.current = false;
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
async function refresh() {
|
||||
if (
|
||||
active.current ||
|
||||
externalLock.current ||
|
||||
readInFlight.current ||
|
||||
!valid()
|
||||
)
|
||||
return;
|
||||
readInFlight.current = true;
|
||||
setReading(true);
|
||||
setError('');
|
||||
try {
|
||||
const response = await portalRequest<{
|
||||
actorId: number;
|
||||
account: ProfileRecord;
|
||||
companies: ProfileRecord[];
|
||||
organizations?: OrganizationRecord[];
|
||||
}>('/api/v1/investment/profile');
|
||||
if (!valid()) return;
|
||||
if (
|
||||
response.actorId !== actorId ||
|
||||
!Array.isArray(response.companies)
|
||||
)
|
||||
throw new Error('Context changed');
|
||||
const org = organization
|
||||
? response.organizations?.find(
|
||||
(item) => item.id === organization.id,
|
||||
)
|
||||
: undefined;
|
||||
if (
|
||||
organization &&
|
||||
(!org ||
|
||||
typeof org.canEdit !== 'boolean' ||
|
||||
(org.country !== null && typeof org.country !== 'string') ||
|
||||
(org.provenance !== null &&
|
||||
typeof org.provenance?.reference !== 'string'))
|
||||
) {
|
||||
setBlocked(true);
|
||||
throw new Error('Organisation unavailable');
|
||||
}
|
||||
if (org && organization)
|
||||
setPermission({
|
||||
editable: org.canEdit,
|
||||
propVersion: record.version,
|
||||
propCanEdit: organization.canEdit,
|
||||
});
|
||||
const next = org
|
||||
? {
|
||||
id: org.id,
|
||||
version: org.version,
|
||||
payload: {
|
||||
country: org.country ?? '',
|
||||
source_reference: org.provenance?.reference ?? '',
|
||||
},
|
||||
}
|
||||
: company
|
||||
? record.id
|
||||
? response.companies.find((item) => item.id === record.id)
|
||||
: { version: 0, payload: {} }
|
||||
: response.account;
|
||||
if (
|
||||
!next ||
|
||||
!Number.isSafeInteger(next.version) ||
|
||||
next.version < 0 ||
|
||||
!next.payload ||
|
||||
typeof next.payload !== 'object' ||
|
||||
Array.isArray(next.payload) ||
|
||||
fields.some(
|
||||
(key) =>
|
||||
next.payload[key] != null &&
|
||||
typeof next.payload[key] !== 'string',
|
||||
)
|
||||
)
|
||||
throw new Error('Record unavailable');
|
||||
setRemote({ ...next, payload: values(next, fields) });
|
||||
setBlocked(pending.current === null);
|
||||
setNotice(
|
||||
uncertain
|
||||
? 'Registo consultado. Confirme primeiro o pedido sem resposta; a preparação não foi alterada.'
|
||||
: 'Registo consultado. Compare os valores antes de escolher como continuar.',
|
||||
);
|
||||
} catch {
|
||||
if (valid())
|
||||
setError(
|
||||
'Não foi possível consultar o registo nesta sessão. A preparação foi conservada.',
|
||||
);
|
||||
} finally {
|
||||
if (valid()) {
|
||||
readInFlight.current = false;
|
||||
setReading(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
function adopt(keepDraft: boolean) {
|
||||
if (
|
||||
!remote ||
|
||||
active.current ||
|
||||
externalLock.current ||
|
||||
readInFlight.current ||
|
||||
busy ||
|
||||
reading ||
|
||||
uncertain ||
|
||||
pending.current ||
|
||||
!mayEdit ||
|
||||
!valid()
|
||||
)
|
||||
return;
|
||||
setBase(remote);
|
||||
if (!keepDraft) setDraft({ ...remote.payload });
|
||||
setRemote(null);
|
||||
setBlocked(false);
|
||||
setError('');
|
||||
setErrors({});
|
||||
setNotice(
|
||||
keepDraft
|
||||
? 'Versão actual adoptada; a sua preparação foi conservada. Reveja antes de guardar.'
|
||||
: 'Valores guardados carregados.',
|
||||
);
|
||||
}
|
||||
function beginCountryReuse(): boolean {
|
||||
if (
|
||||
!company ||
|
||||
!record.id ||
|
||||
dirty ||
|
||||
blocked ||
|
||||
stale ||
|
||||
active.current ||
|
||||
readInFlight.current ||
|
||||
externalLock.current ||
|
||||
pending.current ||
|
||||
!valid()
|
||||
)
|
||||
return false;
|
||||
externalLock.current = true;
|
||||
setExternalBusy(true);
|
||||
return true;
|
||||
}
|
||||
function endCountryReuse(result?: {
|
||||
version: number;
|
||||
country: string;
|
||||
}): void {
|
||||
if (!externalLock.current || !valid()) return;
|
||||
if (result) {
|
||||
const payload = {
|
||||
...base.payload,
|
||||
incorporation_country_code: result.country,
|
||||
};
|
||||
setBase({ ...base, version: result.version, payload });
|
||||
setDraft(payload);
|
||||
setRemote(null);
|
||||
setErrors({});
|
||||
setError('');
|
||||
}
|
||||
externalLock.current = false;
|
||||
setExternalBusy(false);
|
||||
}
|
||||
return {
|
||||
base,
|
||||
draft,
|
||||
busy,
|
||||
reading,
|
||||
uncertain,
|
||||
blocked,
|
||||
errors,
|
||||
error,
|
||||
notice,
|
||||
stale,
|
||||
remote,
|
||||
dirty,
|
||||
externalBusy,
|
||||
beginCountryReuse,
|
||||
endCountryReuse,
|
||||
mayEdit,
|
||||
change,
|
||||
save,
|
||||
refresh,
|
||||
adopt,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
import { router } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { createOperationKey } from './operation-key';
|
||||
import { portalRequest, PortalApiError } from './portal-api';
|
||||
import type {
|
||||
useInvestmentProfileEditor,
|
||||
OrganizationRecord,
|
||||
} from './investment-profile-editor';
|
||||
|
||||
export type CountryReusePreview = {
|
||||
organizationId: string;
|
||||
organizationName: string;
|
||||
organizationVersion: number;
|
||||
country: string;
|
||||
reference: string;
|
||||
companyVersion: number;
|
||||
companyCountry: string;
|
||||
};
|
||||
type Attempt = {
|
||||
version: number;
|
||||
organization_id: string;
|
||||
organization_version: number;
|
||||
operation_key: string;
|
||||
country: string;
|
||||
};
|
||||
type Editor = ReturnType<typeof useInvestmentProfileEditor>;
|
||||
const object = (value: unknown): value is Record<string, unknown> =>
|
||||
!!value && typeof value === 'object' && !Array.isArray(value);
|
||||
const version = (value: unknown): value is number =>
|
||||
typeof value === 'number' && Number.isSafeInteger(value) && value >= 1;
|
||||
|
||||
export function useOrganizationCountryReuse(
|
||||
companyId: string,
|
||||
actorId: number,
|
||||
editor: Editor,
|
||||
reportDirty: (id: string, dirty: boolean) => void,
|
||||
organizations: OrganizationRecord[],
|
||||
) {
|
||||
const [preview, setPreview] = useState<CountryReusePreview | null>(null),
|
||||
[busy, setBusy] = useState(false),
|
||||
[reading, setReading] = useState(false),
|
||||
[uncertain, setUncertain] = useState(false),
|
||||
[blocked, setBlocked] = useState(false),
|
||||
[error, setError] = useState(''),
|
||||
[notice, setNotice] = useState('');
|
||||
const pending = useRef<Attempt | null>(null),
|
||||
active = useRef(false),
|
||||
alive = useRef(true),
|
||||
liveEditor = useRef(editor),
|
||||
sources = useRef(organizations),
|
||||
origin = useRef({ companyId, actorId }),
|
||||
current = useRef({ companyId, actorId });
|
||||
current.current = { companyId, actorId };
|
||||
liveEditor.current = editor;
|
||||
sources.current = organizations;
|
||||
const valid = () =>
|
||||
alive.current &&
|
||||
Number.isSafeInteger(actorId) &&
|
||||
actorId > 0 &&
|
||||
origin.current.actorId === current.current.actorId &&
|
||||
origin.current.companyId === current.current.companyId;
|
||||
const changedSource = () => {
|
||||
if (!preview || pending.current) return false;
|
||||
const source = sources.current.find(
|
||||
(item) => item.id === preview.organizationId,
|
||||
);
|
||||
return (
|
||||
!source ||
|
||||
source.version > preview.organizationVersion ||
|
||||
(source.version === preview.organizationVersion &&
|
||||
source.country !== preview.country)
|
||||
);
|
||||
};
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
reportDirty(
|
||||
'country-reuse-' + companyId,
|
||||
!!preview || busy || uncertain,
|
||||
);
|
||||
}, [preview, busy, uncertain, companyId, reportDirty]);
|
||||
useEffect(
|
||||
() => () => reportDirty('country-reuse-' + companyId, false),
|
||||
[companyId, reportDirty],
|
||||
);
|
||||
|
||||
async function inspect(organizationId: string) {
|
||||
if (active.current || !valid()) return;
|
||||
if (
|
||||
!pending.current &&
|
||||
(liveEditor.current.dirty ||
|
||||
liveEditor.current.blocked ||
|
||||
liveEditor.current.stale)
|
||||
) {
|
||||
setError(
|
||||
'Guarde ou confirme a preparação desta declaração antes de reutilizar o país.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
active.current = true;
|
||||
setReading(true);
|
||||
setError('');
|
||||
setNotice('');
|
||||
try {
|
||||
const data = await portalRequest<unknown>(
|
||||
'/api/v1/investment/profile',
|
||||
);
|
||||
if (!valid()) return;
|
||||
if (
|
||||
!object(data) ||
|
||||
data.actorId !== actorId ||
|
||||
!Array.isArray(data.companies) ||
|
||||
!Array.isArray(data.organizations)
|
||||
)
|
||||
throw new Error('Invalid context');
|
||||
const company = data.companies.find(
|
||||
(item) => object(item) && item.id === companyId,
|
||||
),
|
||||
source = data.organizations.find(
|
||||
(item) => object(item) && item.id === organizationId,
|
||||
);
|
||||
if (
|
||||
!object(company) ||
|
||||
!version(company.version) ||
|
||||
!object(company.payload) ||
|
||||
!object(source) ||
|
||||
!version(source.version) ||
|
||||
typeof source.name !== 'string'
|
||||
) {
|
||||
setBlocked(true);
|
||||
throw new Error('Source unavailable');
|
||||
}
|
||||
if (pending.current) {
|
||||
setBlocked(false);
|
||||
setNotice(
|
||||
'Estado consultado: declaração na versão ' +
|
||||
company.version +
|
||||
'. Confirme o pedido sem resposta antes de preparar outra reutilização.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
company.version !== liveEditor.current.base.version ||
|
||||
liveEditor.current.dirty
|
||||
) {
|
||||
setPreview(null);
|
||||
setError(
|
||||
'A declaração ou a preparação mudou. Consulte e compare o registo no formulário antes de reutilizar.',
|
||||
);
|
||||
router.reload({ only: ['companies', 'organizations'] });
|
||||
return;
|
||||
}
|
||||
if (
|
||||
typeof source.country !== 'string' ||
|
||||
!/^[A-Z]{2}$/.test(source.country)
|
||||
) {
|
||||
setPreview(null);
|
||||
setError(
|
||||
'O país de constituição ainda não está disponível nesta organização.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
const reference =
|
||||
object(source.provenance) &&
|
||||
typeof source.provenance.reference === 'string'
|
||||
? source.provenance.reference
|
||||
: '';
|
||||
setPreview({
|
||||
organizationId,
|
||||
organizationName: source.name,
|
||||
organizationVersion: source.version,
|
||||
country: source.country,
|
||||
reference,
|
||||
companyVersion: company.version,
|
||||
companyCountry:
|
||||
typeof company.payload.incorporation_country_code ===
|
||||
'string'
|
||||
? company.payload.incorporation_country_code
|
||||
: '',
|
||||
});
|
||||
setBlocked(false);
|
||||
} catch {
|
||||
if (valid())
|
||||
setError(
|
||||
'Não foi possível consultar a declaração e a organização nesta sessão. A preparação foi conservada.',
|
||||
);
|
||||
} finally {
|
||||
if (valid()) {
|
||||
active.current = false;
|
||||
setReading(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
async function confirm() {
|
||||
if (active.current || blocked || !valid()) return;
|
||||
if (!pending.current) {
|
||||
if (changedSource()) {
|
||||
setError(
|
||||
'A organização mudou. Consulte novamente o país antes de confirmar.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!preview ||
|
||||
preview.companyVersion !== liveEditor.current.base.version
|
||||
) {
|
||||
setError('Volte a consultar os valores antes de confirmar.');
|
||||
return;
|
||||
}
|
||||
let key: string;
|
||||
try {
|
||||
key = createOperationKey();
|
||||
} catch (failure) {
|
||||
setError(
|
||||
failure instanceof Error
|
||||
? failure.message
|
||||
: 'Não foi possível preparar o pedido.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!liveEditor.current.beginCountryReuse()) {
|
||||
setError(
|
||||
'Guarde ou confirme a preparação desta declaração antes de reutilizar o país.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
pending.current = {
|
||||
version: preview.companyVersion,
|
||||
organization_id: preview.organizationId,
|
||||
organization_version: preview.organizationVersion,
|
||||
operation_key: key,
|
||||
country: preview.country,
|
||||
};
|
||||
}
|
||||
const attempt = pending.current;
|
||||
active.current = true;
|
||||
setBusy(true);
|
||||
setError('');
|
||||
setNotice('');
|
||||
try {
|
||||
const { country: expectedCountry, ...command } = attempt;
|
||||
const result = await portalRequest<unknown>(
|
||||
'/api/v1/investment/companies/' +
|
||||
companyId +
|
||||
'/organization-country',
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(command),
|
||||
},
|
||||
);
|
||||
if (!valid() || pending.current !== attempt) return;
|
||||
if (
|
||||
!object(result) ||
|
||||
!version(result.version) ||
|
||||
result.version !== attempt.version + 1 ||
|
||||
result.country !== expectedCountry
|
||||
)
|
||||
throw new Error('Unconfirmed result');
|
||||
liveEditor.current.endCountryReuse({
|
||||
version: result.version,
|
||||
country: expectedCountry,
|
||||
});
|
||||
pending.current = null;
|
||||
setPreview(null);
|
||||
setUncertain(false);
|
||||
setBlocked(false);
|
||||
setNotice('País reutilizado e gravação confirmada.');
|
||||
router.reload({ only: ['companies', 'organizations'] });
|
||||
} catch (failure) {
|
||||
if (!valid() || pending.current !== attempt) return;
|
||||
if (
|
||||
failure instanceof PortalApiError &&
|
||||
[409, 422].includes(failure.status)
|
||||
) {
|
||||
pending.current = null;
|
||||
liveEditor.current.endCountryReuse();
|
||||
setUncertain(false);
|
||||
setPreview(null);
|
||||
setError(
|
||||
'A declaração ou a fonte já não corresponde ao pedido. Consulte os valores guardados antes de preparar outra reutilização.',
|
||||
);
|
||||
router.reload({ only: ['companies', 'organizations'] });
|
||||
} else {
|
||||
setUncertain(true);
|
||||
setBlocked(
|
||||
failure instanceof PortalApiError &&
|
||||
[401, 403, 404, 419].includes(failure.status),
|
||||
);
|
||||
setError(
|
||||
'Não foi possível confirmar a reutilização. O pedido original foi conservado. Consulte o estado ou repita o mesmo pedido antes de editar.',
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (valid()) {
|
||||
active.current = false;
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
function cancel() {
|
||||
if (pending.current || active.current || !valid()) return;
|
||||
setPreview(null);
|
||||
setError('');
|
||||
setNotice('');
|
||||
}
|
||||
return {
|
||||
preview,
|
||||
busy,
|
||||
reading,
|
||||
uncertain,
|
||||
blocked,
|
||||
error,
|
||||
notice,
|
||||
inspect,
|
||||
confirm,
|
||||
cancel,
|
||||
sourceChanged: changedSource(),
|
||||
pendingOrganizationId: pending.current?.organization_id,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { router } from '@inertiajs/react';
|
||||
import { useEffect, useRef } from 'react';
|
||||
export function usePagePreparationGuard(dirty: boolean, message: string) {
|
||||
const guard = useRef({ dirty, message });
|
||||
guard.current = { dirty, message };
|
||||
useEffect(() => {
|
||||
const remove = router.on('before', (event) => {
|
||||
if (
|
||||
guard.current.dirty &&
|
||||
event.detail.visit.method === 'get' &&
|
||||
!event.detail.visit.preserveState &&
|
||||
!window.confirm(guard.current.message)
|
||||
)
|
||||
event.preventDefault();
|
||||
});
|
||||
const unload = (event: BeforeUnloadEvent) => {
|
||||
if (guard.current.dirty) {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
}
|
||||
};
|
||||
window.addEventListener('beforeunload', unload);
|
||||
return () => {
|
||||
remove();
|
||||
window.removeEventListener('beforeunload', unload);
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
export type Confirmation = {
|
||||
actorId: number | null;
|
||||
actorName: string | null;
|
||||
date: string | null;
|
||||
reason: string | null;
|
||||
};
|
||||
export const agreementParties = ['proponent', 'candidate'] as const;
|
||||
export function agreementObject(
|
||||
value: unknown,
|
||||
): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
const text = (value: unknown) => (typeof value === 'string' ? value : null);
|
||||
export function readAgreement(value: unknown) {
|
||||
const record = agreementObject(value) ? value : null;
|
||||
const map =
|
||||
record && agreementObject(record.confirmations)
|
||||
? record.confirmations
|
||||
: record &&
|
||||
Array.isArray(record.confirmations) &&
|
||||
record.confirmations.length === 0
|
||||
? {}
|
||||
: null;
|
||||
const confirmations: Partial<
|
||||
Record<(typeof agreementParties)[number], Confirmation>
|
||||
> = {};
|
||||
for (const party of agreementParties) {
|
||||
if (!map || !Object.hasOwn(map, party)) continue;
|
||||
const stamp = agreementObject(map[party]) ? map[party] : {};
|
||||
const id = stamp.actor_id;
|
||||
confirmations[party] = {
|
||||
actorId:
|
||||
typeof id === 'number' && Number.isSafeInteger(id) && id > 0
|
||||
? id
|
||||
: null,
|
||||
actorName: text(stamp.actor_name),
|
||||
date: text(stamp.date),
|
||||
reason: text(stamp.reason),
|
||||
};
|
||||
}
|
||||
return {
|
||||
kind:
|
||||
value == null
|
||||
? ('absent' as const)
|
||||
: record
|
||||
? ('recorded' as const)
|
||||
: ('malformed' as const),
|
||||
title: text(record?.title),
|
||||
terms: text(record?.terms),
|
||||
confirmationsState: map
|
||||
? ('recorded' as const)
|
||||
: record?.confirmations == null
|
||||
? ('absent' as const)
|
||||
: ('malformed' as const),
|
||||
confirmations,
|
||||
extraConfirmations:
|
||||
!!map &&
|
||||
Object.keys(map).some(
|
||||
(key) => !agreementParties.some((party) => party === key),
|
||||
),
|
||||
legalStatus: text(record?.legal_signature_status),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,805 @@
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { createOperationKey } from './operation-key';
|
||||
type Values = Record<string, string>;
|
||||
type Criterion = {
|
||||
code: string;
|
||||
label: string;
|
||||
weight: number;
|
||||
mandatory: boolean;
|
||||
};
|
||||
type Snapshot = {
|
||||
id: number | null;
|
||||
version: number | null;
|
||||
parentVersion: number;
|
||||
status: string;
|
||||
context: string;
|
||||
weightsHash: string;
|
||||
criteria: Criterion[];
|
||||
owner: boolean;
|
||||
canSubmit: boolean;
|
||||
canDecide: boolean;
|
||||
canWithdraw: boolean;
|
||||
values: Values;
|
||||
commands: { key: string; version: number; action: string }[];
|
||||
};
|
||||
function object(value: unknown): value is Record<string, unknown> {
|
||||
return !!value && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
function dictionary(value: unknown): Record<string, unknown> | null {
|
||||
return object(value)
|
||||
? value
|
||||
: Array.isArray(value) && value.length === 0
|
||||
? {}
|
||||
: null;
|
||||
}
|
||||
function positive(value: unknown): value is number {
|
||||
return (
|
||||
typeof value === 'number' && Number.isSafeInteger(value) && value > 0
|
||||
);
|
||||
}
|
||||
function text(value: unknown): string | null {
|
||||
return value == null ? '' : typeof value === 'string' ? value : null;
|
||||
}
|
||||
export function criterionValue(value: string | undefined): {
|
||||
state: string;
|
||||
evidence: string;
|
||||
} {
|
||||
try {
|
||||
const item: unknown = JSON.parse(value ?? '');
|
||||
if (
|
||||
object(item) &&
|
||||
['unknown', 'met', 'unmet'].includes(String(item.state)) &&
|
||||
typeof item.evidence === 'string'
|
||||
)
|
||||
return { state: String(item.state), evidence: item.evidence };
|
||||
} catch {
|
||||
/* An invalid preparation is not an assessment. */
|
||||
}
|
||||
return { state: 'unknown', evidence: '' };
|
||||
}
|
||||
const pack = (state: string, evidence: string) =>
|
||||
JSON.stringify({ state, evidence });
|
||||
function read(
|
||||
props: unknown,
|
||||
recordId: number,
|
||||
target: number | null,
|
||||
mode: 'submission' | 'decision',
|
||||
actorId: number | null,
|
||||
key?: string,
|
||||
action?: string,
|
||||
): Snapshot | null {
|
||||
if (
|
||||
!object(props) ||
|
||||
!object(props.record) ||
|
||||
props.record.id !== recordId ||
|
||||
!positive(props.record.version) ||
|
||||
typeof props.record.status !== 'string' ||
|
||||
typeof props.owner !== 'boolean' ||
|
||||
typeof props.canEdit !== 'boolean' ||
|
||||
typeof props.acceptingInterests !== 'boolean' ||
|
||||
!Array.isArray(props.interests)
|
||||
)
|
||||
return null;
|
||||
const record = props.record;
|
||||
const item = key
|
||||
? props.interests.find(
|
||||
(item) =>
|
||||
object(item) &&
|
||||
Array.isArray(item.commands) &&
|
||||
item.commands.some(
|
||||
(command) =>
|
||||
object(command) &&
|
||||
command.key === key &&
|
||||
command.action === action,
|
||||
),
|
||||
)
|
||||
: target === null
|
||||
? null
|
||||
: props.interests.find((item) => object(item) && item.id === target);
|
||||
if ((target !== null && !object(item)) || (key && !object(item)))
|
||||
return null;
|
||||
const entry = object(item) ? item : null;
|
||||
if (
|
||||
entry &&
|
||||
(!positive(entry.id) ||
|
||||
!positive(entry.version) ||
|
||||
typeof entry.status !== 'string' ||
|
||||
typeof entry.can_edit !== 'boolean' ||
|
||||
!dictionary(entry.payload) ||
|
||||
!dictionary(entry.assessment) ||
|
||||
!object(entry.match) ||
|
||||
!Array.isArray(entry.match.criteria) ||
|
||||
typeof entry.match.weights_hash !== 'string' ||
|
||||
!/^[a-f0-9]{64}$/.test(entry.match.weights_hash))
|
||||
)
|
||||
return null;
|
||||
const match = entry && object(entry.match) ? entry.match : null;
|
||||
const criteria: Criterion[] = [];
|
||||
for (const candidate of match && Array.isArray(match.criteria)
|
||||
? match.criteria
|
||||
: []) {
|
||||
if (
|
||||
!object(candidate) ||
|
||||
typeof candidate.code !== 'string' ||
|
||||
typeof candidate.label !== 'string' ||
|
||||
typeof candidate.weight !== 'number' ||
|
||||
typeof candidate.mandatory !== 'boolean'
|
||||
)
|
||||
return null;
|
||||
criteria.push({
|
||||
code: candidate.code,
|
||||
label: candidate.label,
|
||||
weight: candidate.weight,
|
||||
mandatory: candidate.mandatory,
|
||||
});
|
||||
}
|
||||
const values: Values = {};
|
||||
if (mode === 'submission') {
|
||||
const payload = entry ? (dictionary(entry.payload) ?? {}) : {};
|
||||
for (const field of ['organization_id', 'proposal']) {
|
||||
const value = text(entry?.[field]);
|
||||
if (value === null) return null;
|
||||
values[field] = value;
|
||||
}
|
||||
for (const field of [
|
||||
'capacity',
|
||||
'availability',
|
||||
'contribution',
|
||||
'conflicts',
|
||||
]) {
|
||||
const value = text(payload[field]);
|
||||
if (value === null) return null;
|
||||
values[field] = value;
|
||||
}
|
||||
values.consent = [true, 1, '1', 'yes', 'on'].includes(
|
||||
payload.consent as string | number | boolean,
|
||||
)
|
||||
? 'yes'
|
||||
: 'no';
|
||||
} else {
|
||||
values.reason = '';
|
||||
const assessment = entry ? (dictionary(entry.assessment) ?? {}) : {};
|
||||
for (const criterion of props.owner ? criteria : []) {
|
||||
const data = assessment[criterion.code];
|
||||
const assessed = object(data) ? data : {};
|
||||
const state = assessed.state ?? 'unknown',
|
||||
evidence = text(assessed.evidence);
|
||||
if (
|
||||
typeof state !== 'string' ||
|
||||
!['met', 'unmet', 'unknown'].includes(state) ||
|
||||
evidence === null
|
||||
)
|
||||
return null;
|
||||
values['criterion:' + criterion.code] = pack(state, evidence);
|
||||
}
|
||||
}
|
||||
const commands: Snapshot['commands'] = [];
|
||||
for (const candidate of entry && Array.isArray(entry.commands)
|
||||
? entry.commands
|
||||
: [])
|
||||
if (
|
||||
object(candidate) &&
|
||||
typeof candidate.key === 'string' &&
|
||||
positive(candidate.version) &&
|
||||
typeof candidate.action === 'string'
|
||||
)
|
||||
commands.push({
|
||||
key: candidate.key,
|
||||
version: candidate.version,
|
||||
action: candidate.action,
|
||||
});
|
||||
const id = entry && positive(entry.id) ? entry.id : null,
|
||||
version = entry && positive(entry.version) ? entry.version : null,
|
||||
status =
|
||||
entry && typeof entry.status === 'string' ? entry.status : 'new';
|
||||
const effectiveRepresentation = entry
|
||||
? entry.can_edit === true
|
||||
: !!actorId && !props.owner;
|
||||
const context =
|
||||
mode === 'submission'
|
||||
? [
|
||||
record.version,
|
||||
record.status,
|
||||
record.deadline,
|
||||
props.owner,
|
||||
effectiveRepresentation,
|
||||
props.acceptingInterests,
|
||||
]
|
||||
: props.owner
|
||||
? [
|
||||
record.version,
|
||||
record.status,
|
||||
record.deadline,
|
||||
props.owner,
|
||||
props.canEdit,
|
||||
match?.weights_hash,
|
||||
criteria,
|
||||
]
|
||||
: [recordId, props.owner, effectiveRepresentation];
|
||||
return {
|
||||
id,
|
||||
version,
|
||||
parentVersion: record.version as number,
|
||||
status,
|
||||
context: JSON.stringify(context),
|
||||
weightsHash:
|
||||
typeof match?.weights_hash === 'string' ? match.weights_hash : '',
|
||||
criteria,
|
||||
owner: props.owner,
|
||||
canSubmit:
|
||||
!!actorId &&
|
||||
!props.owner &&
|
||||
props.acceptingInterests &&
|
||||
(entry
|
||||
? entry.can_edit === true &&
|
||||
['submitted', 'clarification', 'withdrawn'].includes(status)
|
||||
: props.canStartInterest === true),
|
||||
canDecide: props.owner && props.canEdit && !!entry,
|
||||
canWithdraw: !!entry && entry.can_edit === true,
|
||||
values,
|
||||
commands,
|
||||
};
|
||||
}
|
||||
const same = (a: Values, b: Values) =>
|
||||
[...new Set([...Object.keys(a), ...Object.keys(b)])].every(
|
||||
(key) => a[key] === b[key],
|
||||
);
|
||||
function normal(values: Values): Values {
|
||||
return Object.fromEntries(
|
||||
Object.entries(values).map(([key, value]) => [
|
||||
key,
|
||||
key.startsWith('criterion:')
|
||||
? pack(
|
||||
criterionValue(value).state,
|
||||
criterionValue(value).evidence.trim(),
|
||||
)
|
||||
: value.trim(),
|
||||
]),
|
||||
);
|
||||
}
|
||||
type Pending = {
|
||||
command: Record<string, unknown>;
|
||||
values: Values;
|
||||
generations: Record<string, number>;
|
||||
action: string;
|
||||
base: Snapshot;
|
||||
ambiguous: boolean;
|
||||
};
|
||||
export function useCandidacyEdit({
|
||||
props,
|
||||
recordId,
|
||||
interestId = null,
|
||||
mode,
|
||||
actorId,
|
||||
}: {
|
||||
props: unknown;
|
||||
recordId: number;
|
||||
interestId?: number | null;
|
||||
mode: 'submission' | 'decision';
|
||||
actorId: number | null;
|
||||
}) {
|
||||
const [resolved, setResolved] = useState<number | null>(interestId);
|
||||
const target = interestId ?? resolved;
|
||||
const current = read(props, recordId, target, mode, actorId);
|
||||
const initial = useRef(current);
|
||||
const criterionLabels = useRef(
|
||||
new Map(
|
||||
(current?.criteria ?? []).map((criterion) => [
|
||||
criterion.code,
|
||||
criterion.label,
|
||||
]),
|
||||
),
|
||||
);
|
||||
for (const criterion of current?.criteria ?? [])
|
||||
criterionLabels.current.set(criterion.code, criterion.label);
|
||||
const identity = JSON.stringify([recordId, interestId, mode, actorId]);
|
||||
const opened = useRef(identity);
|
||||
const observed = useRef(identity);
|
||||
observed.current = identity;
|
||||
const empty: Values =
|
||||
mode === 'submission'
|
||||
? {
|
||||
organization_id: '',
|
||||
proposal: '',
|
||||
capacity: '',
|
||||
availability: '',
|
||||
contribution: '',
|
||||
conflicts: '',
|
||||
consent: 'no',
|
||||
}
|
||||
: { reason: '' };
|
||||
const form = useForm<{ values: Values }>({
|
||||
values: current?.values ?? empty,
|
||||
});
|
||||
const live = useRef(form.data.values);
|
||||
live.current = form.data.values;
|
||||
const edited = useRef(new Set<string>()),
|
||||
generations = useRef<Record<string, number>>({});
|
||||
const pending = useRef<Pending | null>(null);
|
||||
const [choices, setChoices] = useState<Record<string, 'mine' | 'current'>>(
|
||||
{},
|
||||
);
|
||||
const [refreshing, setRefreshing] = useState(false),
|
||||
[needsCompare, setNeedsCompare] = useState(false),
|
||||
[problem, setProblem] = useState<string | null>(null);
|
||||
const base = initial.current;
|
||||
const keys = [
|
||||
...new Set([
|
||||
...Object.keys(base?.values ?? empty),
|
||||
...Object.keys(current?.values ?? {}),
|
||||
]),
|
||||
];
|
||||
const invalid =
|
||||
!current ||
|
||||
!base ||
|
||||
opened.current !== observed.current ||
|
||||
current.id !== base.id;
|
||||
const stale =
|
||||
!!current &&
|
||||
!!base &&
|
||||
(current.version !== base.version ||
|
||||
current.context !== base.context ||
|
||||
current.status !== base.status ||
|
||||
!same(current.values, base.values));
|
||||
const changed =
|
||||
current && base
|
||||
? keys.filter((key) => current.values[key] !== base.values[key])
|
||||
: [];
|
||||
const conflicts = current
|
||||
? changed.filter(
|
||||
(key) =>
|
||||
Object.hasOwn(current.values, key) &&
|
||||
edited.current.has(key) &&
|
||||
live.current[key] !== current.values[key],
|
||||
)
|
||||
: [];
|
||||
const choiceKey = (key: string) =>
|
||||
JSON.stringify([
|
||||
current?.id,
|
||||
current?.version,
|
||||
current?.context,
|
||||
key,
|
||||
current?.values[key],
|
||||
]);
|
||||
const unresolved = conflicts.filter(
|
||||
(key) => choices[choiceKey(key)] !== 'mine',
|
||||
);
|
||||
const active =
|
||||
!!current &&
|
||||
['submitted', 'clarification', 'shortlisted'].includes(current.status);
|
||||
const editable =
|
||||
!!current &&
|
||||
(mode === 'submission'
|
||||
? current.canSubmit
|
||||
: active &&
|
||||
(current.owner ? current.canDecide : current.canWithdraw));
|
||||
const canRecover = (action: string) =>
|
||||
!!current &&
|
||||
(action === 'submit'
|
||||
? current.id === null
|
||||
? !!actorId && !current.owner
|
||||
: current.canWithdraw
|
||||
: action === 'withdraw'
|
||||
? current.canWithdraw
|
||||
: current.canDecide);
|
||||
const recovering = !!pending.current?.ambiguous;
|
||||
const blocked =
|
||||
invalid ||
|
||||
refreshing ||
|
||||
form.processing ||
|
||||
(recovering && pending.current
|
||||
? !canRecover(pending.current.action)
|
||||
: stale || needsCompare || !editable);
|
||||
const dirty =
|
||||
!!pending.current ||
|
||||
(!!base &&
|
||||
(!same(live.current, base.values) ||
|
||||
keys.some(
|
||||
(key) =>
|
||||
edited.current.has(key) &&
|
||||
current &&
|
||||
live.current[key] !== current.values[key],
|
||||
)));
|
||||
const retired = Object.keys(live.current).filter(
|
||||
(key) =>
|
||||
key.startsWith('criterion:') &&
|
||||
!current?.criteria.some(
|
||||
(criterion) => 'criterion:' + criterion.code === key,
|
||||
),
|
||||
);
|
||||
useEffect(() => {
|
||||
if (
|
||||
!current ||
|
||||
invalid ||
|
||||
!stale ||
|
||||
dirty ||
|
||||
edited.current.size > 0 ||
|
||||
pending.current ||
|
||||
form.processing ||
|
||||
needsCompare
|
||||
)
|
||||
return;
|
||||
initial.current = current;
|
||||
live.current = { ...current.values };
|
||||
form.setDefaults({ values: live.current });
|
||||
form.setData({ values: live.current });
|
||||
}, [current, invalid, stale, dirty, form.processing, needsCompare]);
|
||||
function change(key: string, value: string) {
|
||||
if (!keys.includes(key)) return;
|
||||
edited.current.add(key);
|
||||
generations.current[key] = (generations.current[key] ?? 0) + 1;
|
||||
live.current = { ...live.current, [key]: value };
|
||||
form.setData({ values: live.current });
|
||||
setChoices((previous) => {
|
||||
const next = { ...previous };
|
||||
delete next[choiceKey(key)];
|
||||
return next;
|
||||
});
|
||||
}
|
||||
function changeCriterion(
|
||||
code: string,
|
||||
field: 'state' | 'evidence',
|
||||
value: string,
|
||||
) {
|
||||
const key = 'criterion:' + code,
|
||||
data = criterionValue(live.current[key]);
|
||||
change(key, JSON.stringify({ ...data, [field]: value }));
|
||||
}
|
||||
function discardRetired() {
|
||||
if (form.processing || pending.current) return;
|
||||
const values = { ...live.current };
|
||||
for (const key of retired) {
|
||||
delete values[key];
|
||||
edited.current.delete(key);
|
||||
}
|
||||
live.current = values;
|
||||
form.setData({ values });
|
||||
}
|
||||
function choose(key: string, value: 'mine' | 'current') {
|
||||
if (!current) return;
|
||||
if (value === 'current') change(key, current.values[key] ?? '');
|
||||
setChoices((previous) => ({ ...previous, [choiceKey(key)]: value }));
|
||||
}
|
||||
function adopt() {
|
||||
if (
|
||||
!current ||
|
||||
invalid ||
|
||||
!stale ||
|
||||
unresolved.length ||
|
||||
refreshing ||
|
||||
form.processing
|
||||
)
|
||||
return;
|
||||
const values = { ...current.values };
|
||||
for (const key of Object.keys(live.current))
|
||||
if (edited.current.has(key)) values[key] = live.current[key];
|
||||
initial.current = current;
|
||||
live.current = values;
|
||||
pending.current = null;
|
||||
form.setDefaults({ values: current.values });
|
||||
form.setData({ values });
|
||||
form.clearErrors();
|
||||
setChoices({});
|
||||
setNeedsCompare(false);
|
||||
setProblem(null);
|
||||
}
|
||||
function refresh() {
|
||||
if (refreshing || form.processing) return;
|
||||
setRefreshing(true);
|
||||
router.reload({
|
||||
only: [
|
||||
'record',
|
||||
'interests',
|
||||
'owner',
|
||||
'canEdit',
|
||||
'moderator',
|
||||
'publicationActions',
|
||||
'publicationCommands',
|
||||
'historySummary',
|
||||
'acceptingInterests',
|
||||
'organizations',
|
||||
],
|
||||
onSuccess: (page) => {
|
||||
const fresh = read(page.props, recordId, target, mode, actorId);
|
||||
if (
|
||||
fresh &&
|
||||
initial.current &&
|
||||
fresh.id === initial.current.id &&
|
||||
fresh.version === initial.current.version &&
|
||||
fresh.context === initial.current.context &&
|
||||
fresh.status === initial.current.status &&
|
||||
same(fresh.values, initial.current.values)
|
||||
) {
|
||||
setNeedsCompare(false);
|
||||
setProblem(null);
|
||||
}
|
||||
},
|
||||
onHttpException: () => {
|
||||
setProblem(
|
||||
'Não foi possível recuperar esta candidatura com o acesso actual. A preparação foi conservada.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
onNetworkError: () => {
|
||||
setProblem(
|
||||
'A recuperação não foi confirmada. A preparação foi conservada.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
onFinish: () => setRefreshing(false),
|
||||
});
|
||||
}
|
||||
function submit(
|
||||
requestedAction = mode === 'submission' ? 'submit' : 'assess',
|
||||
) {
|
||||
if (blocked || !current || !base) return;
|
||||
const action = pending.current?.action ?? requestedAction;
|
||||
if (!recovering) {
|
||||
if (
|
||||
mode === 'decision' &&
|
||||
(action === 'withdraw'
|
||||
? !current.canWithdraw
|
||||
: !current.canDecide)
|
||||
)
|
||||
return;
|
||||
if (action === 'connect' && current.status !== 'shortlisted')
|
||||
return;
|
||||
}
|
||||
let operation = pending.current;
|
||||
if (!operation) {
|
||||
const values = { ...live.current };
|
||||
const command: Record<string, unknown> =
|
||||
mode === 'submission'
|
||||
? {
|
||||
interest_id: target,
|
||||
version: current.version,
|
||||
partnership_version: current.parentVersion,
|
||||
organization_id: values.organization_id,
|
||||
proposal: values.proposal,
|
||||
payload: {
|
||||
capacity: values.capacity,
|
||||
availability: values.availability,
|
||||
contribution: values.contribution,
|
||||
conflicts: values.conflicts,
|
||||
consent: values.consent === 'yes',
|
||||
},
|
||||
}
|
||||
: {
|
||||
version: current.version,
|
||||
action,
|
||||
reason: values.reason,
|
||||
assessment:
|
||||
action === 'assess'
|
||||
? Object.fromEntries(
|
||||
current.criteria.map((criterion) => [
|
||||
criterion.code,
|
||||
criterionValue(
|
||||
values[
|
||||
'criterion:' +
|
||||
criterion.code
|
||||
],
|
||||
),
|
||||
]),
|
||||
)
|
||||
: {},
|
||||
...(action === 'withdraw'
|
||||
? {}
|
||||
: {
|
||||
partnership_version: current.parentVersion,
|
||||
weights_hash: current.weightsHash,
|
||||
}),
|
||||
};
|
||||
command.client_key = createOperationKey();
|
||||
operation = {
|
||||
command,
|
||||
values,
|
||||
generations: { ...generations.current },
|
||||
base: current,
|
||||
action,
|
||||
ambiguous: false,
|
||||
};
|
||||
pending.current = operation;
|
||||
}
|
||||
const sent = operation;
|
||||
setProblem(null);
|
||||
form.transform(() => sent.command);
|
||||
const unknown = () => {
|
||||
if (pending.current) pending.current.ambiguous = true;
|
||||
setProblem(
|
||||
'A operação não foi confirmada. Recuperar repete o pedido original; as alterações posteriores foram conservadas.',
|
||||
);
|
||||
return false;
|
||||
};
|
||||
form.post(
|
||||
mode === 'submission'
|
||||
? `/parcerias/${recordId}/interesses`
|
||||
: `/parcerias/candidaturas/${target}`,
|
||||
{
|
||||
preserveScroll: true,
|
||||
onSuccess: (page) => {
|
||||
if (observed.current !== opened.current) return;
|
||||
const saved = read(
|
||||
page.props,
|
||||
recordId,
|
||||
target,
|
||||
mode,
|
||||
actorId,
|
||||
String(sent.command.client_key),
|
||||
sent.action,
|
||||
);
|
||||
const acknowledgement = saved?.commands.find(
|
||||
(command) =>
|
||||
command.key === sent.command.client_key &&
|
||||
command.action === sent.action,
|
||||
);
|
||||
if (!saved || saved.id === null || !acknowledgement) {
|
||||
unknown();
|
||||
return;
|
||||
}
|
||||
const acknowledgedKeys =
|
||||
mode === 'decision' && sent.action === 'assess'
|
||||
? [
|
||||
'reason',
|
||||
...sent.base.criteria.map(
|
||||
(criterion) =>
|
||||
'criterion:' + criterion.code,
|
||||
),
|
||||
]
|
||||
: null;
|
||||
const submittedValues = acknowledgedKeys
|
||||
? Object.fromEntries(
|
||||
acknowledgedKeys.map((key) => [
|
||||
key,
|
||||
sent.values[key],
|
||||
]),
|
||||
)
|
||||
: mode === 'submission'
|
||||
? sent.values
|
||||
: sent.base.values;
|
||||
const expected = normal(submittedValues);
|
||||
if (mode === 'decision') expected.reason = '';
|
||||
const actualExpectedVersion =
|
||||
sent.base.version === null ? 1 : sent.base.version + 1;
|
||||
if (
|
||||
acknowledgement.version !== actualExpectedVersion ||
|
||||
(target !== null && saved.id !== target)
|
||||
) {
|
||||
unknown();
|
||||
return;
|
||||
}
|
||||
const exact =
|
||||
saved.version === acknowledgement.version &&
|
||||
saved.context === sent.base.context &&
|
||||
same(saved.values, expected);
|
||||
const merged = { ...expected };
|
||||
const oldEdited = new Set(edited.current);
|
||||
edited.current.clear();
|
||||
for (const key of Object.keys(live.current)) {
|
||||
const sentCriterion =
|
||||
!key.startsWith('criterion:') ||
|
||||
sent.base.criteria.some(
|
||||
(criterion) =>
|
||||
'criterion:' + criterion.code === key,
|
||||
);
|
||||
if (
|
||||
(generations.current[key] ?? 0) !==
|
||||
(sent.generations[key] ?? 0) ||
|
||||
(mode === 'decision' &&
|
||||
(sent.action !== 'assess' || !sentCriterion) &&
|
||||
key !== 'reason' &&
|
||||
oldEdited.has(key))
|
||||
) {
|
||||
merged[key] = live.current[key];
|
||||
edited.current.add(key);
|
||||
}
|
||||
}
|
||||
initial.current = exact
|
||||
? saved
|
||||
: {
|
||||
...saved,
|
||||
version: acknowledgement.version,
|
||||
context: sent.base.context,
|
||||
parentVersion: sent.base.parentVersion,
|
||||
values: expected,
|
||||
};
|
||||
if (target === null) setResolved(saved.id);
|
||||
pending.current = null;
|
||||
live.current = merged;
|
||||
form.setDefaults({ values: expected });
|
||||
form.setData({ values: merged });
|
||||
form.clearErrors();
|
||||
setChoices({});
|
||||
setNeedsCompare(!exact);
|
||||
setProblem(
|
||||
exact
|
||||
? null
|
||||
: 'A operação original foi identificada, mas a candidatura ou o contexto tem dados posteriores. Compare antes de continuar; a preparação foi conservada.',
|
||||
);
|
||||
},
|
||||
onError: () => {
|
||||
if (!pending.current?.ambiguous) pending.current = null;
|
||||
},
|
||||
onHttpException: (response) => {
|
||||
if (
|
||||
response.status >= 500 ||
|
||||
response.status === 409 ||
|
||||
pending.current?.ambiguous
|
||||
) {
|
||||
if (response.status === 409) setNeedsCompare(true);
|
||||
return unknown();
|
||||
}
|
||||
pending.current = null;
|
||||
setProblem(
|
||||
'Não foi possível confirmar esta operação com o acesso actual. A preparação foi conservada.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
onNetworkError: unknown,
|
||||
onCancel: unknown,
|
||||
},
|
||||
);
|
||||
}
|
||||
return {
|
||||
form,
|
||||
values: form.data.values,
|
||||
current: current?.values ?? empty,
|
||||
currentSnapshot: current,
|
||||
criteria: current?.criteria ?? base?.criteria ?? [],
|
||||
criterionLabels: Object.fromEntries(criterionLabels.current),
|
||||
retired,
|
||||
activeId: target,
|
||||
editable,
|
||||
ownerMode: current?.owner ?? base?.owner ?? false,
|
||||
status: current?.status,
|
||||
version: current?.version,
|
||||
baseVersion: base?.version,
|
||||
stale,
|
||||
invalid,
|
||||
changed,
|
||||
conflicts,
|
||||
unresolved,
|
||||
refreshing,
|
||||
blocked,
|
||||
dirty,
|
||||
problem,
|
||||
recovering,
|
||||
pendingAction: pending.current?.action,
|
||||
change,
|
||||
changeCriterion,
|
||||
discardRetired,
|
||||
choose,
|
||||
adopt,
|
||||
refresh,
|
||||
submit,
|
||||
};
|
||||
}
|
||||
export type CandidacyEditor = ReturnType<typeof useCandidacyEdit>;
|
||||
export function useCandidacyLeaveGuard(dirty: boolean) {
|
||||
const current = useRef(dirty);
|
||||
current.current = dirty;
|
||||
useEffect(() => {
|
||||
const leave = (event: BeforeUnloadEvent) => {
|
||||
if (current.current) {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
}
|
||||
};
|
||||
const stop = router.on('before', (event) => {
|
||||
if (
|
||||
current.current &&
|
||||
event.detail.visit.method === 'get' &&
|
||||
event.detail.visit.preserveState !== true &&
|
||||
!window.confirm(
|
||||
'Há preparação ou acções por confirmar nesta parceria. Pretende sair sem as conservar?',
|
||||
)
|
||||
)
|
||||
event.preventDefault();
|
||||
});
|
||||
window.addEventListener('beforeunload', leave);
|
||||
return () => {
|
||||
stop();
|
||||
window.removeEventListener('beforeunload', leave);
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
@@ -0,0 +1,862 @@
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import type { Partnership } from '@/pages/partnerships/shared';
|
||||
|
||||
export type PartnershipLocation = {
|
||||
geo_location_id: string;
|
||||
role: string;
|
||||
source_reference: string;
|
||||
};
|
||||
export type PartnershipOrigin = { type: string; target_id: string };
|
||||
export type PartnershipEditProps = {
|
||||
editorActorId?: number;
|
||||
saveCommands?: { key: string; version: number }[];
|
||||
record: Partnership | null;
|
||||
locations: PartnershipLocation[];
|
||||
origins: PartnershipOrigin[];
|
||||
};
|
||||
type Payload = {
|
||||
summary: string;
|
||||
requirements: string;
|
||||
mandatory: string[];
|
||||
confidentiality: string;
|
||||
consent: boolean;
|
||||
availability: string;
|
||||
};
|
||||
type Sections = Payload & {
|
||||
title: string;
|
||||
offer: string;
|
||||
seeking: string;
|
||||
organization_id: string;
|
||||
sector_id: string;
|
||||
kind: string;
|
||||
partnership_type: string;
|
||||
deadline: string;
|
||||
locations: PartnershipLocation[];
|
||||
origins: PartnershipOrigin[];
|
||||
};
|
||||
type Draft = Omit<Sections, keyof Payload> & {
|
||||
payload: Payload;
|
||||
client_key: string;
|
||||
version: number | null;
|
||||
};
|
||||
type Snapshot = {
|
||||
actorId: number | null;
|
||||
commands: { key: string; version: number }[];
|
||||
id: number | null;
|
||||
version: number | null;
|
||||
status: string;
|
||||
clientKey: string | null;
|
||||
values: Sections;
|
||||
};
|
||||
const textKeys = [
|
||||
'title',
|
||||
'offer',
|
||||
'seeking',
|
||||
'organization_id',
|
||||
'sector_id',
|
||||
'kind',
|
||||
'partnership_type',
|
||||
'deadline',
|
||||
'summary',
|
||||
'requirements',
|
||||
'confidentiality',
|
||||
'availability',
|
||||
] as const;
|
||||
const keys = [
|
||||
...textKeys,
|
||||
'mandatory',
|
||||
'consent',
|
||||
'locations',
|
||||
'origins',
|
||||
] as const;
|
||||
export type PartnershipSection = (typeof keys)[number];
|
||||
const editableStates = ['draft', 'returned', 'rejected', 'published'];
|
||||
function object(value: unknown): value is Record<string, unknown> {
|
||||
return !!value && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
function text(value: unknown, fallback = '') {
|
||||
return value == null
|
||||
? fallback
|
||||
: typeof value === 'string'
|
||||
? value
|
||||
: undefined;
|
||||
}
|
||||
function bool(value: unknown) {
|
||||
return value == null
|
||||
? false
|
||||
: value === true || value === 1 || value === '1'
|
||||
? true
|
||||
: value === false || value === 0 || value === '0'
|
||||
? false
|
||||
: undefined;
|
||||
}
|
||||
function location(value: unknown): value is PartnershipLocation {
|
||||
return (
|
||||
object(value) &&
|
||||
typeof value.geo_location_id === 'string' &&
|
||||
typeof value.role === 'string' &&
|
||||
typeof value.source_reference === 'string'
|
||||
);
|
||||
}
|
||||
function origin(value: unknown): value is PartnershipOrigin {
|
||||
return (
|
||||
object(value) &&
|
||||
typeof value.type === 'string' &&
|
||||
typeof value.target_id === 'string'
|
||||
);
|
||||
}
|
||||
function validSections(value: unknown): value is Sections {
|
||||
return (
|
||||
object(value) &&
|
||||
textKeys.every((key) => typeof value[key] === 'string') &&
|
||||
typeof value.consent === 'boolean' &&
|
||||
Array.isArray(value.mandatory) &&
|
||||
value.mandatory.every((item) => typeof item === 'string') &&
|
||||
Array.isArray(value.locations) &&
|
||||
value.locations.every(location) &&
|
||||
Array.isArray(value.origins) &&
|
||||
value.origins.every(origin)
|
||||
);
|
||||
}
|
||||
function readSnapshot(props: unknown): Snapshot | null {
|
||||
if (
|
||||
!object(props) ||
|
||||
!Array.isArray(props.locations) ||
|
||||
!Array.isArray(props.origins)
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
props.editorActorId !== undefined &&
|
||||
(typeof props.editorActorId !== 'number' ||
|
||||
!Number.isSafeInteger(props.editorActorId) ||
|
||||
props.editorActorId < 1)
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
props.saveCommands !== undefined &&
|
||||
(!Array.isArray(props.saveCommands) ||
|
||||
!props.saveCommands.every(
|
||||
(value) =>
|
||||
object(value) &&
|
||||
typeof value.key === 'string' &&
|
||||
typeof value.version === 'number' &&
|
||||
Number.isSafeInteger(value.version) &&
|
||||
value.version > 0,
|
||||
))
|
||||
)
|
||||
return null;
|
||||
const record = props.record;
|
||||
if (
|
||||
record !== null &&
|
||||
(!object(record) ||
|
||||
!Number.isSafeInteger(record.id) ||
|
||||
typeof record.id !== 'number' ||
|
||||
record.id < 1 ||
|
||||
!Number.isSafeInteger(record.version) ||
|
||||
typeof record.version !== 'number' ||
|
||||
record.version < 1 ||
|
||||
typeof record.status !== 'string' ||
|
||||
(!object(record.payload) &&
|
||||
!(
|
||||
Array.isArray(record.payload) && record.payload.length === 0
|
||||
)))
|
||||
)
|
||||
return null;
|
||||
const row = object(record) ? record : {};
|
||||
const payload = object(row.payload) ? row.payload : {};
|
||||
const values = {
|
||||
title: text(row.title),
|
||||
offer: text(row.offer),
|
||||
seeking: text(row.seeking),
|
||||
organization_id: text(row.organization_id),
|
||||
sector_id:
|
||||
row.sector_id == null
|
||||
? ''
|
||||
: typeof row.sector_id === 'number'
|
||||
? String(row.sector_id)
|
||||
: undefined,
|
||||
kind: text(row.kind, 'seeking'),
|
||||
partnership_type: text(row.partnership_type),
|
||||
deadline: text(row.deadline),
|
||||
summary: text(payload.summary),
|
||||
requirements: text(payload.requirements),
|
||||
mandatory: payload.mandatory ?? [],
|
||||
confidentiality: text(payload.confidentiality, 'public'),
|
||||
consent: bool(payload.consent),
|
||||
availability: text(payload.availability),
|
||||
locations: props.locations.map((item) =>
|
||||
object(item)
|
||||
? {
|
||||
geo_location_id: item.geo_location_id,
|
||||
role: item.role,
|
||||
source_reference: text(item.source_reference),
|
||||
}
|
||||
: null,
|
||||
),
|
||||
origins: props.origins.map((item) =>
|
||||
object(item)
|
||||
? { type: item.type, target_id: item.target_id }
|
||||
: null,
|
||||
),
|
||||
};
|
||||
if (!validSections(values)) return null;
|
||||
return {
|
||||
actorId:
|
||||
typeof props.editorActorId === 'number'
|
||||
? props.editorActorId
|
||||
: null,
|
||||
commands: Array.isArray(props.saveCommands)
|
||||
? props.saveCommands.map((value) => ({
|
||||
key: value.key,
|
||||
version: value.version,
|
||||
}))
|
||||
: [],
|
||||
id: typeof row.id === 'number' ? row.id : null,
|
||||
version: typeof row.version === 'number' ? row.version : null,
|
||||
status: typeof row.status === 'string' ? row.status : 'draft',
|
||||
clientKey: typeof row.client_key === 'string' ? row.client_key : null,
|
||||
values,
|
||||
};
|
||||
}
|
||||
function toDraft(
|
||||
values: Sections,
|
||||
client_key: string,
|
||||
version: number | null,
|
||||
): Draft {
|
||||
const {
|
||||
summary,
|
||||
requirements,
|
||||
mandatory,
|
||||
confidentiality,
|
||||
consent,
|
||||
availability,
|
||||
...fields
|
||||
} = values;
|
||||
return {
|
||||
...fields,
|
||||
client_key,
|
||||
version,
|
||||
payload: {
|
||||
summary,
|
||||
requirements,
|
||||
mandatory,
|
||||
confidentiality,
|
||||
consent,
|
||||
availability,
|
||||
},
|
||||
};
|
||||
}
|
||||
function sections({
|
||||
payload,
|
||||
client_key: _key,
|
||||
version: _version,
|
||||
...fields
|
||||
}: Draft): Sections {
|
||||
return { ...fields, ...payload };
|
||||
}
|
||||
function canonical(value: Sections[PartnershipSection]) {
|
||||
return JSON.stringify(
|
||||
Array.isArray(value)
|
||||
? value.map((item) => JSON.stringify(item)).sort()
|
||||
: value,
|
||||
);
|
||||
}
|
||||
function equal(
|
||||
a: Sections[PartnershipSection],
|
||||
b: Sections[PartnershipSection],
|
||||
) {
|
||||
return canonical(a) === canonical(b);
|
||||
}
|
||||
function same(a: Sections, b: Sections) {
|
||||
return keys.every((key) => equal(a[key], b[key]));
|
||||
}
|
||||
function normalised(values: Sections): Sections {
|
||||
const result = { ...values };
|
||||
for (const key of textKeys) result[key] = result[key].trim();
|
||||
return {
|
||||
...result,
|
||||
locations: result.locations.map((item) => ({
|
||||
geo_location_id: item.geo_location_id.trim(),
|
||||
role: item.role.trim(),
|
||||
source_reference: item.source_reference.trim(),
|
||||
})),
|
||||
origins: result.origins.map((item) => ({
|
||||
type: item.type.trim(),
|
||||
target_id: item.target_id.trim(),
|
||||
})),
|
||||
};
|
||||
}
|
||||
const empty = readSnapshot({ record: null, locations: [], origins: [] });
|
||||
if (!empty) throw new Error('Empty partnership editor definition is invalid.');
|
||||
const emptyValues = empty.values;
|
||||
export function usePartnershipEdit(props: PartnershipEditProps) {
|
||||
const alive = useRef(true);
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
};
|
||||
}, []);
|
||||
const current = readSnapshot(props);
|
||||
const operationKey = useRef(createOperationKey());
|
||||
const form = useForm(
|
||||
toDraft(
|
||||
current?.values ?? emptyValues,
|
||||
operationKey.current,
|
||||
current?.version ?? null,
|
||||
),
|
||||
);
|
||||
const base = useRef(current);
|
||||
const live = useRef(form.data);
|
||||
live.current = form.data;
|
||||
const identity = useRef(current?.id ?? null);
|
||||
identity.current = current?.id ?? null;
|
||||
const edited = useRef(new Set<PartnershipSection>());
|
||||
const generation = useRef<Partial<Record<PartnershipSection, number>>>({});
|
||||
const pendingCreation = useRef<{
|
||||
command: Draft;
|
||||
generation: Partial<Record<PartnershipSection, number>>;
|
||||
ambiguous: boolean;
|
||||
} | null>(null);
|
||||
const createdId = useRef<number | null>(null);
|
||||
const pendingUpdate = useRef<{
|
||||
id: number;
|
||||
command: Draft & { operation_key: string };
|
||||
generation: Partial<Record<PartnershipSection, number>>;
|
||||
base: Snapshot;
|
||||
ambiguous: boolean;
|
||||
} | null>(null);
|
||||
const [choices, setChoices] = useState<Record<string, 'mine' | 'current'>>(
|
||||
{},
|
||||
);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [problem, setProblem] = useState<string | null>(null);
|
||||
const [needsCompare, setNeedsCompare] = useState(false);
|
||||
const [mustRefresh, setMustRefresh] = useState(false),
|
||||
[accessDenied, setAccessDenied] = useState(false);
|
||||
const own = sections(form.data);
|
||||
const invalid =
|
||||
!current ||
|
||||
!base.current ||
|
||||
current.actorId !== base.current.actorId ||
|
||||
(current.id !== base.current.id &&
|
||||
!(
|
||||
base.current.id === null &&
|
||||
(current.id === createdId.current ||
|
||||
current.clientKey ===
|
||||
pendingCreation.current?.command.client_key)
|
||||
));
|
||||
const stale =
|
||||
!!current &&
|
||||
!!base.current &&
|
||||
(current.id !== base.current.id ||
|
||||
current.version !== base.current.version ||
|
||||
current.status !== base.current.status ||
|
||||
!same(current.values, base.current.values));
|
||||
const baseline = base.current;
|
||||
const changed =
|
||||
current && baseline
|
||||
? keys.filter(
|
||||
(key) => !equal(current.values[key], baseline.values[key]),
|
||||
)
|
||||
: [];
|
||||
const conflicts = current
|
||||
? changed.filter(
|
||||
(key) =>
|
||||
edited.current.has(key) &&
|
||||
!equal(own[key], current.values[key]),
|
||||
)
|
||||
: [];
|
||||
const choiceKey = (key: PartnershipSection) =>
|
||||
JSON.stringify([
|
||||
current?.id,
|
||||
current?.version,
|
||||
current?.status,
|
||||
key,
|
||||
current ? canonical(current.values[key]) : '',
|
||||
]);
|
||||
const unresolved = conflicts.filter(
|
||||
(key) => choices[choiceKey(key)] !== 'mine',
|
||||
);
|
||||
const editable = !!current && editableStates.includes(current.status);
|
||||
const blocked =
|
||||
invalid ||
|
||||
stale ||
|
||||
refreshing ||
|
||||
needsCompare ||
|
||||
accessDenied ||
|
||||
!!pendingUpdate.current ||
|
||||
!editable;
|
||||
const dirty =
|
||||
!!baseline &&
|
||||
(!!pendingUpdate.current ||
|
||||
!!pendingCreation.current ||
|
||||
!same(own, baseline.values) ||
|
||||
(!!current &&
|
||||
keys.some(
|
||||
(key) =>
|
||||
edited.current.has(key) &&
|
||||
!equal(own[key], current.values[key]),
|
||||
)));
|
||||
useEffect(() => {
|
||||
const leave = (event: BeforeUnloadEvent) => {
|
||||
if (dirty) {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
}
|
||||
};
|
||||
const stop = router.on('before', (event) => {
|
||||
if (
|
||||
dirty &&
|
||||
event.detail.visit.method === 'get' &&
|
||||
event.detail.visit.preserveState !== true &&
|
||||
!window.confirm(
|
||||
'Há alterações por guardar na parceria. Pretende sair sem as guardar?',
|
||||
)
|
||||
)
|
||||
event.preventDefault();
|
||||
});
|
||||
window.addEventListener('beforeunload', leave);
|
||||
return () => {
|
||||
stop();
|
||||
window.removeEventListener('beforeunload', leave);
|
||||
};
|
||||
}, [dirty]);
|
||||
function replace(next: Draft) {
|
||||
const previous = sections(live.current),
|
||||
after = sections(next);
|
||||
const changed = keys.filter((key) => !equal(previous[key], after[key]));
|
||||
for (const key of changed) {
|
||||
edited.current.add(key);
|
||||
generation.current[key] = (generation.current[key] ?? 0) + 1;
|
||||
}
|
||||
live.current = next;
|
||||
form.setData(() => next);
|
||||
setChoices((previous) => {
|
||||
const next = { ...previous };
|
||||
for (const key of changed) delete next[choiceKey(key)];
|
||||
return next;
|
||||
});
|
||||
}
|
||||
function setData<K extends keyof Draft>(
|
||||
key: K,
|
||||
value: Draft[K] | ((previous: Draft[K]) => Draft[K]),
|
||||
) {
|
||||
const next =
|
||||
typeof value === 'function' ? value(live.current[key]) : value;
|
||||
replace({ ...live.current, [key]: next });
|
||||
}
|
||||
function choose(key: PartnershipSection, choice: 'mine' | 'current') {
|
||||
if (!current) return;
|
||||
if (choice === 'current')
|
||||
replace(
|
||||
toDraft(
|
||||
{ ...sections(live.current), [key]: current.values[key] },
|
||||
live.current.client_key,
|
||||
live.current.version,
|
||||
),
|
||||
);
|
||||
setChoices((previous) => ({ ...previous, [choiceKey(key)]: choice }));
|
||||
}
|
||||
function adopt() {
|
||||
if (
|
||||
!current ||
|
||||
(!stale && !pendingUpdate.current?.ambiguous && !needsCompare) ||
|
||||
invalid ||
|
||||
refreshing ||
|
||||
form.processing ||
|
||||
unresolved.length
|
||||
)
|
||||
return;
|
||||
if (mustRefresh) return;
|
||||
const selected = { ...current.values };
|
||||
for (const key of keys)
|
||||
if (edited.current.has(key))
|
||||
Object.assign(selected, { [key]: sections(live.current)[key] });
|
||||
const saved = toDraft(
|
||||
current.values,
|
||||
current.clientKey ?? live.current.client_key,
|
||||
current.version,
|
||||
);
|
||||
base.current = current;
|
||||
createdId.current = null;
|
||||
pendingCreation.current = null;
|
||||
pendingUpdate.current = null;
|
||||
form.setDefaults(saved);
|
||||
live.current = toDraft(selected, saved.client_key, saved.version);
|
||||
form.setData(live.current);
|
||||
form.clearErrors();
|
||||
setProblem(null);
|
||||
setNeedsCompare(false);
|
||||
setChoices({});
|
||||
}
|
||||
function refresh() {
|
||||
if (refreshing || form.processing) return;
|
||||
setRefreshing(true);
|
||||
router.reload({
|
||||
only: [
|
||||
'record',
|
||||
'locations',
|
||||
'origins',
|
||||
'editorActorId',
|
||||
'saveCommands',
|
||||
],
|
||||
onSuccess: (page) => {
|
||||
if (!alive.current) return;
|
||||
if (
|
||||
pendingUpdate.current &&
|
||||
acknowledgeUpdate(page.props, pendingUpdate.current)
|
||||
)
|
||||
return;
|
||||
const fresh = readSnapshot(page.props);
|
||||
if (
|
||||
!fresh ||
|
||||
fresh.actorId !== base.current?.actorId ||
|
||||
fresh.id !== base.current?.id
|
||||
) {
|
||||
setProblem(
|
||||
'A resposta não corresponde a esta conta e parceria. A preparação foi conservada.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
setMustRefresh(false);
|
||||
setAccessDenied(false);
|
||||
if (
|
||||
fresh &&
|
||||
base.current &&
|
||||
fresh.id === base.current.id &&
|
||||
fresh.version === base.current.version &&
|
||||
fresh.status === base.current.status &&
|
||||
same(fresh.values, base.current.values)
|
||||
) {
|
||||
setNeedsCompare(false);
|
||||
setProblem(null);
|
||||
}
|
||||
},
|
||||
onHttpException: () => {
|
||||
if (!alive.current) return false;
|
||||
setAccessDenied(true);
|
||||
setMustRefresh(true);
|
||||
setProblem(
|
||||
'Não foi possível recuperar esta parceria com o acesso actual. As suas edições foram conservadas.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
onNetworkError: () => {
|
||||
if (!alive.current) return false;
|
||||
setProblem(
|
||||
'A recuperação não foi confirmada. As suas edições foram conservadas.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
onFinish: () => {
|
||||
if (alive.current) setRefreshing(false);
|
||||
},
|
||||
});
|
||||
}
|
||||
function applySaved(
|
||||
saved: Snapshot,
|
||||
command: Draft,
|
||||
sentGeneration: Partial<Record<PartnershipSection, number>>,
|
||||
later = false,
|
||||
) {
|
||||
const merged = { ...saved.values };
|
||||
edited.current.clear();
|
||||
for (const key of keys)
|
||||
if ((generation.current[key] ?? 0) !== (sentGeneration[key] ?? 0)) {
|
||||
Object.assign(merged, { [key]: sections(live.current)[key] });
|
||||
edited.current.add(key);
|
||||
}
|
||||
base.current = saved;
|
||||
createdId.current = null;
|
||||
pendingCreation.current = null;
|
||||
pendingUpdate.current = null;
|
||||
const defaults = toDraft(
|
||||
saved.values,
|
||||
saved.clientKey ?? command.client_key,
|
||||
saved.version,
|
||||
);
|
||||
form.setDefaults(defaults);
|
||||
live.current = toDraft(merged, defaults.client_key, defaults.version);
|
||||
form.setData(live.current);
|
||||
form.clearErrors();
|
||||
setChoices({});
|
||||
setMustRefresh(false);
|
||||
setAccessDenied(false);
|
||||
setNeedsCompare(later);
|
||||
setProblem(
|
||||
later
|
||||
? 'A gravação foi reconhecida. Existem alterações posteriores; compare antes de voltar a guardar.'
|
||||
: null,
|
||||
);
|
||||
}
|
||||
function acknowledgeUpdate(
|
||||
pageProps: unknown,
|
||||
sent: NonNullable<typeof pendingUpdate.current>,
|
||||
): boolean {
|
||||
if (
|
||||
!alive.current ||
|
||||
pendingUpdate.current !== sent ||
|
||||
identity.current !== sent.id
|
||||
)
|
||||
return false;
|
||||
const saved = readSnapshot(pageProps),
|
||||
expectedVersion = (sent.base.version ?? 0) + 1;
|
||||
if (
|
||||
!saved ||
|
||||
saved.id !== sent.id ||
|
||||
saved.actorId !== sent.base.actorId ||
|
||||
!saved.commands.some(
|
||||
(command) =>
|
||||
command.key === sent.command.operation_key &&
|
||||
command.version === expectedVersion,
|
||||
) ||
|
||||
saved.version === null ||
|
||||
saved.version < expectedVersion
|
||||
)
|
||||
return false;
|
||||
const expected = normalised(sections(sent.command));
|
||||
if (saved.version === expectedVersion) {
|
||||
if (saved.status !== 'draft' || !same(saved.values, expected))
|
||||
return false;
|
||||
applySaved(saved, sent.command, sent.generation);
|
||||
return true;
|
||||
}
|
||||
applySaved(
|
||||
{
|
||||
...sent.base,
|
||||
version: expectedVersion,
|
||||
status: 'draft',
|
||||
values: expected,
|
||||
commands: saved.commands,
|
||||
},
|
||||
sent.command,
|
||||
sent.generation,
|
||||
true,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
function save(recover = false) {
|
||||
if (
|
||||
!alive.current ||
|
||||
form.processing ||
|
||||
refreshing ||
|
||||
invalid ||
|
||||
accessDenied ||
|
||||
(!recover && blocked)
|
||||
)
|
||||
return;
|
||||
const update = recover ? pendingUpdate.current : null;
|
||||
if (recover && (!update?.ambiguous || current?.id !== update.id))
|
||||
return;
|
||||
const submittedId = update?.id ?? base.current?.id ?? null;
|
||||
const pending = submittedId === null ? pendingCreation.current : null;
|
||||
const command =
|
||||
update?.command ??
|
||||
pending?.command ??
|
||||
structuredClone(live.current);
|
||||
const sentGeneration = update?.generation ??
|
||||
pending?.generation ?? { ...generation.current };
|
||||
if (submittedId !== null && !update && base.current)
|
||||
pendingUpdate.current = {
|
||||
id: submittedId,
|
||||
command: { ...command, operation_key: createOperationKey() },
|
||||
generation: sentGeneration,
|
||||
base: base.current,
|
||||
ambiguous: false,
|
||||
};
|
||||
const submittedUpdate = pendingUpdate.current;
|
||||
if (submittedId === null && !pending)
|
||||
pendingCreation.current = {
|
||||
command,
|
||||
generation: sentGeneration,
|
||||
ambiguous: false,
|
||||
};
|
||||
setProblem(null);
|
||||
form.transform(() => submittedUpdate?.command ?? command);
|
||||
const options = {
|
||||
preserveScroll: true,
|
||||
onSuccess: (page: { props: Record<string, unknown> }) => {
|
||||
if (!alive.current) return;
|
||||
if (submittedUpdate) {
|
||||
if (
|
||||
!acknowledgeUpdate(page.props, submittedUpdate) &&
|
||||
pendingUpdate.current === submittedUpdate
|
||||
) {
|
||||
submittedUpdate.ambiguous = true;
|
||||
setMustRefresh(true);
|
||||
setNeedsCompare(true);
|
||||
setProblem(
|
||||
'A resposta não confirmou esta gravação. A preparação foi conservada; recupere a mesma tentativa ou compare os dados actuais.',
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const saved = readSnapshot(page.props);
|
||||
if (
|
||||
!saved ||
|
||||
saved.id === null ||
|
||||
(submittedId !== null
|
||||
? saved.id !== submittedId ||
|
||||
identity.current !== submittedId
|
||||
: saved.clientKey !== command.client_key ||
|
||||
(identity.current !== null &&
|
||||
identity.current !== saved.id))
|
||||
) {
|
||||
setProblem(
|
||||
'A gravação não foi reconciliada com este formulário. Compare os dados antes de continuar.',
|
||||
);
|
||||
setNeedsCompare(true);
|
||||
return;
|
||||
}
|
||||
if (submittedId === null) createdId.current = saved.id;
|
||||
pendingCreation.current = null;
|
||||
if (
|
||||
saved.status !== 'draft' ||
|
||||
!same(saved.values, normalised(sections(command)))
|
||||
) {
|
||||
setProblem(
|
||||
'A resposta contém uma versão com dados diferentes do que enviou. Compare antes de voltar a guardar; as suas edições foram conservadas.',
|
||||
);
|
||||
setNeedsCompare(true);
|
||||
return;
|
||||
}
|
||||
applySaved(saved, command, sentGeneration);
|
||||
},
|
||||
onError: () => {
|
||||
if (!alive.current) return;
|
||||
if (
|
||||
submittedUpdate &&
|
||||
pendingUpdate.current === submittedUpdate
|
||||
)
|
||||
pendingUpdate.current = null;
|
||||
if (!pendingCreation.current?.ambiguous)
|
||||
pendingCreation.current = null;
|
||||
},
|
||||
onHttpException: (response: { status: number }) => {
|
||||
if (!alive.current) return false;
|
||||
if (submittedUpdate) {
|
||||
if (pendingUpdate.current !== submittedUpdate) return false;
|
||||
if (
|
||||
response.status >= 500 ||
|
||||
[401, 403, 404, 419].includes(response.status)
|
||||
)
|
||||
submittedUpdate.ambiguous = true;
|
||||
else pendingUpdate.current = null;
|
||||
setMustRefresh(true);
|
||||
setNeedsCompare(true);
|
||||
setAccessDenied(
|
||||
[401, 403, 404, 419].includes(response.status),
|
||||
);
|
||||
setProblem(
|
||||
'A gravação não foi confirmada com os dados e acesso actuais. Compare antes de continuar; as edições foram conservadas.',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
if (submittedId !== null && response.status === 409) {
|
||||
setNeedsCompare(true);
|
||||
setProblem(
|
||||
'A parceria foi alterada ou mudou de estado. Compare com os dados actuais antes de guardar; as suas edições foram conservadas.',
|
||||
);
|
||||
} else {
|
||||
setProblem(
|
||||
response.status === 403
|
||||
? 'Não foi possível confirmar a operação com o acesso actual. As suas edições foram conservadas.'
|
||||
: 'A gravação não foi confirmada. As suas edições foram conservadas.',
|
||||
);
|
||||
if (submittedId !== null)
|
||||
setNeedsCompare(response.status >= 500);
|
||||
}
|
||||
if (pendingCreation.current) {
|
||||
if (
|
||||
response.status >= 500 ||
|
||||
response.status === 409 ||
|
||||
pendingCreation.current.ambiguous
|
||||
)
|
||||
pendingCreation.current.ambiguous = true;
|
||||
else pendingCreation.current = null;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
onNetworkError: () => {
|
||||
if (!alive.current) return false;
|
||||
if (
|
||||
submittedUpdate &&
|
||||
pendingUpdate.current !== submittedUpdate
|
||||
)
|
||||
return false;
|
||||
if (
|
||||
submittedUpdate &&
|
||||
pendingUpdate.current === submittedUpdate
|
||||
) {
|
||||
submittedUpdate.ambiguous = true;
|
||||
setMustRefresh(true);
|
||||
}
|
||||
setProblem(
|
||||
'A gravação não foi confirmada. As suas edições foram conservadas.',
|
||||
);
|
||||
if (pendingCreation.current)
|
||||
pendingCreation.current.ambiguous = true;
|
||||
else setNeedsCompare(true);
|
||||
return false;
|
||||
},
|
||||
onCancel: () => {
|
||||
if (!alive.current) return;
|
||||
if (
|
||||
submittedUpdate &&
|
||||
pendingUpdate.current !== submittedUpdate
|
||||
)
|
||||
return;
|
||||
if (
|
||||
submittedUpdate &&
|
||||
pendingUpdate.current === submittedUpdate
|
||||
) {
|
||||
submittedUpdate.ambiguous = true;
|
||||
setMustRefresh(true);
|
||||
}
|
||||
if (pendingCreation.current)
|
||||
pendingCreation.current.ambiguous = true;
|
||||
else setNeedsCompare(true);
|
||||
setProblem(
|
||||
'A gravação foi interrompida; conserve a edição e recupere os dados antes de continuar.',
|
||||
);
|
||||
},
|
||||
};
|
||||
if (submittedId === null) form.post('/parcerias/rascunhos', options);
|
||||
else form.put(`/parcerias/${submittedId}`, options);
|
||||
}
|
||||
return {
|
||||
form,
|
||||
setData,
|
||||
save,
|
||||
refresh,
|
||||
adopt,
|
||||
choose,
|
||||
problem,
|
||||
current,
|
||||
values: own,
|
||||
changed,
|
||||
conflicts,
|
||||
unresolved,
|
||||
stale,
|
||||
invalid,
|
||||
refreshing,
|
||||
editable,
|
||||
blocked,
|
||||
dirty,
|
||||
retryingCreation: !!pendingCreation.current?.ambiguous,
|
||||
retryingSave: !!pendingUpdate.current?.ambiguous,
|
||||
canRecoverSave:
|
||||
!!pendingUpdate.current?.ambiguous &&
|
||||
!invalid &&
|
||||
!accessDenied &&
|
||||
!refreshing &&
|
||||
!form.processing,
|
||||
recoverSave: () => save(true),
|
||||
mustRefresh,
|
||||
baseVersion: base.current?.version ?? null,
|
||||
};
|
||||
}
|
||||
export type PartnershipEditor = ReturnType<typeof usePartnershipEdit>;
|
||||
@@ -0,0 +1,26 @@
|
||||
export const publicationHistoryActions: Record<string, string> = {
|
||||
create: 'Criação do rascunho',
|
||||
edit: 'Edição do rascunho',
|
||||
submit: 'Submissão para moderação',
|
||||
publish: 'Publicação',
|
||||
return: 'Devolução para correcção',
|
||||
reject: 'Rejeição',
|
||||
suspend: 'Suspensão',
|
||||
archive: 'Arquivo',
|
||||
renew: 'Renovação em rascunho',
|
||||
};
|
||||
export type PublicationHistorySummary = {
|
||||
limit: number;
|
||||
has_more: boolean;
|
||||
href: string;
|
||||
entries: {
|
||||
version: number | null;
|
||||
restricted: boolean;
|
||||
action: string | null;
|
||||
actor_name: string | null;
|
||||
occurred_at: string | null;
|
||||
reason: string | null;
|
||||
status_before: string | null;
|
||||
status_after: string | null;
|
||||
}[];
|
||||
};
|
||||
@@ -0,0 +1,465 @@
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { createOperationKey } from './operation-key';
|
||||
import type { Partnership } from '@/pages/partnerships/shared';
|
||||
|
||||
export type PublicationProps = {
|
||||
record: Partnership;
|
||||
owner: boolean;
|
||||
canEdit: boolean;
|
||||
moderator: boolean;
|
||||
publicationActions: string[];
|
||||
publicationCommands: { key: string; action: string; version: number }[];
|
||||
origins: unknown[];
|
||||
locations: unknown[];
|
||||
};
|
||||
type Snapshot = {
|
||||
id: number;
|
||||
version: number;
|
||||
status: string;
|
||||
context: string;
|
||||
values: Record<string, string>;
|
||||
actions: string[];
|
||||
canEdit: boolean;
|
||||
moderator: boolean;
|
||||
commands: PublicationProps['publicationCommands'];
|
||||
};
|
||||
const states: Record<string, string> = {
|
||||
submit: 'submitted',
|
||||
publish: 'published',
|
||||
return: 'returned',
|
||||
reject: 'rejected',
|
||||
suspend: 'suspended',
|
||||
archive: 'archived',
|
||||
renew: 'draft',
|
||||
};
|
||||
const object = (value: unknown): value is Record<string, unknown> =>
|
||||
!!value && typeof value === 'object' && !Array.isArray(value);
|
||||
const positive = (value: unknown): value is number =>
|
||||
typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
|
||||
function scalar(value: unknown): string | null {
|
||||
return value == null
|
||||
? ''
|
||||
: typeof value === 'string' ||
|
||||
typeof value === 'number' ||
|
||||
typeof value === 'boolean'
|
||||
? String(value)
|
||||
: null;
|
||||
}
|
||||
function canonical(value: unknown): unknown {
|
||||
return Array.isArray(value)
|
||||
? value.map(canonical)
|
||||
: object(value)
|
||||
? Object.fromEntries(
|
||||
Object.keys(value)
|
||||
.sort()
|
||||
.map((key) => [key, canonical(value[key])]),
|
||||
)
|
||||
: value;
|
||||
}
|
||||
function read(props: unknown, id: number): Snapshot | null {
|
||||
if (
|
||||
!object(props) ||
|
||||
!object(props.record) ||
|
||||
props.record.id !== id ||
|
||||
!positive(props.record.version) ||
|
||||
typeof props.record.status !== 'string' ||
|
||||
typeof props.canEdit !== 'boolean' ||
|
||||
typeof props.moderator !== 'boolean' ||
|
||||
!Array.isArray(props.publicationActions) ||
|
||||
!props.publicationActions.every(
|
||||
(value) =>
|
||||
typeof value === 'string' && Object.hasOwn(states, value),
|
||||
) ||
|
||||
!Array.isArray(props.publicationCommands) ||
|
||||
!props.publicationCommands.every(
|
||||
(value) =>
|
||||
object(value) &&
|
||||
typeof value.key === 'string' &&
|
||||
typeof value.action === 'string' &&
|
||||
Object.hasOwn(states, value.action) &&
|
||||
positive(value.version),
|
||||
) ||
|
||||
!Array.isArray(props.origins) ||
|
||||
!Array.isArray(props.locations)
|
||||
)
|
||||
return null;
|
||||
const payload = object(props.record.payload)
|
||||
? props.record.payload
|
||||
: Array.isArray(props.record.payload) &&
|
||||
props.record.payload.length === 0
|
||||
? {}
|
||||
: null;
|
||||
if (!payload) return null;
|
||||
const { version, status, ...content } = props.record;
|
||||
const values: Record<string, string> = {};
|
||||
for (const key of [
|
||||
'title',
|
||||
'offer',
|
||||
'seeking',
|
||||
'kind',
|
||||
'partnership_type',
|
||||
'sector_id',
|
||||
'organization_id',
|
||||
'deadline',
|
||||
]) {
|
||||
const value = scalar(props.record[key]);
|
||||
if (value === null) return null;
|
||||
values[key] = value;
|
||||
}
|
||||
for (const key of [
|
||||
'summary',
|
||||
'requirements',
|
||||
'confidentiality',
|
||||
'availability',
|
||||
'consent',
|
||||
'mandatory',
|
||||
]) {
|
||||
const item = payload[key];
|
||||
const value =
|
||||
key === 'mandatory' &&
|
||||
Array.isArray(item) &&
|
||||
item.every((entry) => typeof entry === 'string')
|
||||
? item.join(', ')
|
||||
: scalar(item);
|
||||
if (value === null) return null;
|
||||
values[key] = value;
|
||||
}
|
||||
values.origins = props.origins
|
||||
.map((value) =>
|
||||
object(value)
|
||||
? (scalar(value.title ?? value.type) ??
|
||||
'Origem indisponível para comparação')
|
||||
: '',
|
||||
)
|
||||
.join('\n');
|
||||
values.locations = props.locations
|
||||
.map((value) =>
|
||||
object(value)
|
||||
? `${scalar(value.name ?? value.id) ?? 'Localização indisponível'} · ${scalar(value.role) ?? 'Papel indisponível'} · ${scalar(value.source_reference) ?? 'Fonte indisponível'}`
|
||||
: '',
|
||||
)
|
||||
.join('\n');
|
||||
return {
|
||||
id,
|
||||
version,
|
||||
status,
|
||||
context: JSON.stringify(
|
||||
canonical([content, props.origins, props.locations]),
|
||||
),
|
||||
values,
|
||||
actions: props.publicationActions,
|
||||
commands:
|
||||
props.publicationCommands as PublicationProps['publicationCommands'],
|
||||
canEdit: props.canEdit,
|
||||
moderator: props.moderator,
|
||||
};
|
||||
}
|
||||
type Pending = {
|
||||
command: {
|
||||
client_key: string;
|
||||
version: number;
|
||||
action: string;
|
||||
reason: string;
|
||||
};
|
||||
generation: number;
|
||||
base: Snapshot;
|
||||
ambiguous: boolean;
|
||||
};
|
||||
export function usePublication(p: PublicationProps, actorId: number) {
|
||||
const alive = useRef(true);
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
};
|
||||
}, []);
|
||||
const id = p.record.id,
|
||||
current = read(p, id),
|
||||
identity = `${id}:${actorId}`;
|
||||
const opened = useRef(identity),
|
||||
observed = useRef(identity);
|
||||
observed.current = identity;
|
||||
const base = useRef(current),
|
||||
pending = useRef<Pending | null>(null),
|
||||
generation = useRef(0);
|
||||
const form = useForm({ reason: '' });
|
||||
const live = useRef(form.data.reason);
|
||||
live.current = form.data.reason;
|
||||
const [problem, setProblem] = useState<string | null>(null),
|
||||
[needsCompare, setNeedsCompare] = useState(false),
|
||||
[refreshing, setRefreshing] = useState(false),
|
||||
[mustRefresh, setMustRefresh] = useState(false),
|
||||
[, render] = useState(0);
|
||||
const invalid =
|
||||
!current || !base.current || opened.current !== observed.current;
|
||||
const stale =
|
||||
!!current &&
|
||||
!!base.current &&
|
||||
(current.version !== base.current.version ||
|
||||
current.status !== base.current.status ||
|
||||
current.context !== base.current.context);
|
||||
const dirty = !!live.current || !!pending.current;
|
||||
const can = (action: string) =>
|
||||
!!current &&
|
||||
(['publish', 'return', 'reject', 'suspend'].includes(action)
|
||||
? current.moderator && !current.canEdit
|
||||
: current.canEdit);
|
||||
useEffect(() => {
|
||||
if (current && stale && !dirty && !needsCompare && !form.processing) {
|
||||
base.current = current;
|
||||
render((value) => value + 1);
|
||||
}
|
||||
}, [current, stale, dirty, needsCompare, form.processing]);
|
||||
function change(value: string) {
|
||||
generation.current++;
|
||||
live.current = value;
|
||||
form.setData('reason', value);
|
||||
}
|
||||
function acknowledge(props: unknown, sent: Pending): boolean {
|
||||
if (
|
||||
!alive.current ||
|
||||
pending.current !== sent ||
|
||||
observed.current !== opened.current
|
||||
)
|
||||
return false;
|
||||
const fresh = read(props, id),
|
||||
command = fresh?.commands.find(
|
||||
(value) =>
|
||||
value.key === sent.command.client_key &&
|
||||
value.action === sent.command.action &&
|
||||
value.version === sent.command.version + 1,
|
||||
);
|
||||
if (
|
||||
!fresh ||
|
||||
!command ||
|
||||
fresh.version < command.version ||
|
||||
(fresh.version === command.version &&
|
||||
(fresh.status !== states[sent.command.action] ||
|
||||
fresh.context !== sent.base.context))
|
||||
)
|
||||
return false;
|
||||
const exact = fresh.version === command.version;
|
||||
base.current = exact
|
||||
? fresh
|
||||
: {
|
||||
...sent.base,
|
||||
version: command.version,
|
||||
status: states[sent.command.action],
|
||||
};
|
||||
pending.current = null;
|
||||
if (generation.current === sent.generation) {
|
||||
live.current = '';
|
||||
form.setData('reason', '');
|
||||
}
|
||||
form.setDefaults({ reason: '' });
|
||||
form.clearErrors();
|
||||
setNeedsCompare(!exact);
|
||||
setProblem(
|
||||
exact
|
||||
? null
|
||||
: 'A acção foi reconhecida. Há alterações posteriores; compare antes de preparar outra decisão.',
|
||||
);
|
||||
setMustRefresh(false);
|
||||
render((value) => value + 1);
|
||||
return true;
|
||||
}
|
||||
function refresh() {
|
||||
if (refreshing || form.processing) return;
|
||||
setRefreshing(true);
|
||||
router.reload({
|
||||
only: [
|
||||
'record',
|
||||
'owner',
|
||||
'canEdit',
|
||||
'moderator',
|
||||
'publicationActions',
|
||||
'publicationCommands',
|
||||
'historySummary',
|
||||
'origins',
|
||||
'locations',
|
||||
],
|
||||
onSuccess: (page) => {
|
||||
if (!alive.current || observed.current !== opened.current)
|
||||
return;
|
||||
if (pending.current && acknowledge(page.props, pending.current))
|
||||
return;
|
||||
const fresh = read(page.props, id);
|
||||
if (!fresh) {
|
||||
setProblem(
|
||||
'Resposta incompatível com esta proposta. O motivo preparado foi conservado.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
setMustRefresh(false);
|
||||
if (
|
||||
base.current &&
|
||||
fresh.version === base.current.version &&
|
||||
fresh.status === base.current.status &&
|
||||
fresh.context === base.current.context
|
||||
) {
|
||||
setNeedsCompare(false);
|
||||
setProblem(null);
|
||||
}
|
||||
},
|
||||
onNetworkError: () => {
|
||||
setProblem(
|
||||
'Não foi possível confirmar a actualização. O motivo foi conservado.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
onHttpException: () => {
|
||||
setNeedsCompare(true);
|
||||
setProblem(
|
||||
'Não foi possível consultar a proposta com o acesso actual. O motivo foi conservado.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
onFinish: () => {
|
||||
if (alive.current) setRefreshing(false);
|
||||
},
|
||||
});
|
||||
}
|
||||
function adopt() {
|
||||
if (invalid || !current || mustRefresh || refreshing || form.processing)
|
||||
return;
|
||||
base.current = current;
|
||||
pending.current = null;
|
||||
setNeedsCompare(false);
|
||||
setProblem(null);
|
||||
form.clearErrors();
|
||||
render((value) => value + 1);
|
||||
}
|
||||
function send(action: string, recover = false) {
|
||||
if (
|
||||
invalid ||
|
||||
!current ||
|
||||
!base.current ||
|
||||
refreshing ||
|
||||
form.processing ||
|
||||
!can(action)
|
||||
)
|
||||
return;
|
||||
let sent = pending.current;
|
||||
if (recover) {
|
||||
if (!sent?.ambiguous || sent.command.action !== action) return;
|
||||
} else {
|
||||
if (
|
||||
sent ||
|
||||
stale ||
|
||||
needsCompare ||
|
||||
!current.actions.includes(action) ||
|
||||
!live.current.trim()
|
||||
)
|
||||
return;
|
||||
sent = {
|
||||
command: {
|
||||
client_key: createOperationKey(),
|
||||
version: base.current.version,
|
||||
action,
|
||||
reason: live.current,
|
||||
},
|
||||
generation: generation.current,
|
||||
base: base.current,
|
||||
ambiguous: false,
|
||||
};
|
||||
pending.current = sent;
|
||||
}
|
||||
if (!sent) return;
|
||||
const request = sent;
|
||||
form.transform(() => ({ ...request.command }));
|
||||
form.post(`/parcerias/${id}/estado`, {
|
||||
preserveScroll: true,
|
||||
onSuccess: (page) => {
|
||||
if (!alive.current) return;
|
||||
if (
|
||||
!acknowledge(page.props, request) &&
|
||||
pending.current === request
|
||||
) {
|
||||
request.ambiguous = true;
|
||||
setMustRefresh(true);
|
||||
setNeedsCompare(true);
|
||||
setProblem(
|
||||
'A resposta não confirmou esta tentativa. Conserve o motivo e recupere a mesma acção ou compare os dados actuais.',
|
||||
);
|
||||
}
|
||||
},
|
||||
onError: () => {
|
||||
if (
|
||||
!alive.current ||
|
||||
pending.current !== request ||
|
||||
observed.current !== opened.current
|
||||
)
|
||||
return;
|
||||
pending.current = null;
|
||||
setProblem(
|
||||
'A acção não foi gravada. Corrija os campos indicados; o motivo foi conservado.',
|
||||
);
|
||||
},
|
||||
onNetworkError: () => {
|
||||
if (
|
||||
alive.current &&
|
||||
pending.current === request &&
|
||||
observed.current === opened.current
|
||||
) {
|
||||
request.ambiguous = true;
|
||||
setMustRefresh(true);
|
||||
setProblem(
|
||||
'A resposta perdeu-se. Pode recuperar exactamente a mesma tentativa, sem repetir uma decisão já gravada.',
|
||||
);
|
||||
}
|
||||
return false;
|
||||
},
|
||||
onHttpException: (response) => {
|
||||
if (
|
||||
!alive.current ||
|
||||
pending.current !== request ||
|
||||
observed.current !== opened.current
|
||||
)
|
||||
return false;
|
||||
if (response.status >= 500) request.ambiguous = true;
|
||||
else pending.current = null;
|
||||
setMustRefresh(true);
|
||||
setNeedsCompare(true);
|
||||
setProblem(
|
||||
'A acção não foi confirmada com os dados e acesso actuais. Compare antes de continuar; o motivo foi conservado.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
});
|
||||
}
|
||||
return {
|
||||
form,
|
||||
current,
|
||||
base: base.current,
|
||||
stale,
|
||||
invalid,
|
||||
dirty,
|
||||
problem,
|
||||
refreshing,
|
||||
needsCompare,
|
||||
mustRefresh,
|
||||
changes:
|
||||
current && base.current
|
||||
? Object.keys(current.values).filter(
|
||||
(key) =>
|
||||
current.values[key] !== base.current?.values[key],
|
||||
)
|
||||
: [],
|
||||
blocked:
|
||||
invalid ||
|
||||
stale ||
|
||||
needsCompare ||
|
||||
!!pending.current ||
|
||||
refreshing ||
|
||||
form.processing,
|
||||
recovery: pending.current?.ambiguous
|
||||
? pending.current.command.action
|
||||
: null,
|
||||
can,
|
||||
change,
|
||||
refresh,
|
||||
adopt,
|
||||
send,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { useRef, useState } from 'react';
|
||||
import { createOperationKey } from './operation-key';
|
||||
type Data = {
|
||||
body: string;
|
||||
file: File | null;
|
||||
shared: boolean;
|
||||
client_key: string;
|
||||
};
|
||||
function object(value: unknown): value is Record<string, unknown> {
|
||||
return !!value && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
/** Keeps the original command, including the immutable File object, until delivery is confirmed. */
|
||||
export function useRoomDelivery({
|
||||
roomId,
|
||||
actorId,
|
||||
kind,
|
||||
mutable,
|
||||
canWrite,
|
||||
}: {
|
||||
roomId: number;
|
||||
actorId: number;
|
||||
kind: 'message' | 'upload';
|
||||
mutable: boolean;
|
||||
canWrite: boolean;
|
||||
}) {
|
||||
const form = useForm<Data>({
|
||||
body: '',
|
||||
file: null,
|
||||
shared: false,
|
||||
client_key: createOperationKey(),
|
||||
});
|
||||
const live = useRef(form.data);
|
||||
live.current = form.data;
|
||||
const generation = useRef({ body: 0, file: 0, shared: 0 });
|
||||
const identity = useRef(JSON.stringify([roomId, actorId, kind]));
|
||||
const observed = useRef(identity.current);
|
||||
observed.current = JSON.stringify([roomId, actorId, kind]);
|
||||
const pending = useRef<{
|
||||
data: Data;
|
||||
generation: typeof generation.current;
|
||||
ambiguous: boolean;
|
||||
} | null>(null);
|
||||
const [problem, setProblem] = useState<string | null>(null);
|
||||
const recovering = !!pending.current?.ambiguous;
|
||||
const invalid = observed.current !== identity.current;
|
||||
const dirty =
|
||||
!!pending.current ||
|
||||
(kind === 'message' ? !!form.data.body : !!form.data.file);
|
||||
const blocked =
|
||||
form.processing || invalid || !canWrite || (!mutable && !recovering);
|
||||
function change<K extends 'body' | 'file' | 'shared'>(
|
||||
key: K,
|
||||
value: Data[K],
|
||||
) {
|
||||
generation.current[key]++;
|
||||
live.current = { ...live.current, [key]: value };
|
||||
form.setData(live.current);
|
||||
}
|
||||
function submit() {
|
||||
if (
|
||||
blocked ||
|
||||
(kind === 'upload' &&
|
||||
!pending.current?.data.file &&
|
||||
!live.current.file)
|
||||
)
|
||||
return;
|
||||
const command = pending.current ?? {
|
||||
data: { ...live.current },
|
||||
generation: { ...generation.current },
|
||||
ambiguous: false,
|
||||
};
|
||||
pending.current = command;
|
||||
setProblem(null);
|
||||
form.transform(() =>
|
||||
kind === 'message'
|
||||
? {
|
||||
body: command.data.body,
|
||||
client_key: command.data.client_key,
|
||||
}
|
||||
: {
|
||||
file: command.data.file,
|
||||
shared: command.data.shared,
|
||||
client_key: command.data.client_key,
|
||||
},
|
||||
);
|
||||
const unknown = () => {
|
||||
if (pending.current) pending.current.ambiguous = true;
|
||||
setProblem(
|
||||
'O envio não foi confirmado. A tentativa original e a sua preparação foram conservadas.',
|
||||
);
|
||||
return false;
|
||||
};
|
||||
form.post(
|
||||
`/parcerias/salas/${roomId}/${kind === 'message' ? 'mensagens' : 'documentos'}`,
|
||||
{
|
||||
preserveScroll: true,
|
||||
forceFormData: kind === 'upload',
|
||||
onSuccess: (page) => {
|
||||
if (observed.current !== identity.current) return;
|
||||
const props = page.props;
|
||||
const room = props.room;
|
||||
const flash = props.flash;
|
||||
const confirmed =
|
||||
object(room) &&
|
||||
room.id === roomId &&
|
||||
(kind === 'message'
|
||||
? Array.isArray(props.messages) &&
|
||||
props.messages.some(
|
||||
(message) =>
|
||||
object(message) &&
|
||||
message.author_id === actorId &&
|
||||
message.client_key ===
|
||||
command.data.client_key &&
|
||||
message.body === command.data.body.trim(),
|
||||
)
|
||||
: object(flash) &&
|
||||
typeof flash.uploaded_document_id === 'string' &&
|
||||
Array.isArray(props.documents) &&
|
||||
props.documents.some(
|
||||
(document) =>
|
||||
object(document) &&
|
||||
document.document_id ===
|
||||
flash.uploaded_document_id &&
|
||||
document.owner_id === actorId &&
|
||||
document.file_name ===
|
||||
command.data.file?.name,
|
||||
));
|
||||
if (!confirmed) {
|
||||
unknown();
|
||||
return;
|
||||
}
|
||||
const next: Data = {
|
||||
body: '',
|
||||
file: null,
|
||||
shared: false,
|
||||
client_key: createOperationKey(),
|
||||
};
|
||||
if (
|
||||
kind === 'message' &&
|
||||
generation.current.body !== command.generation.body
|
||||
)
|
||||
next.body = live.current.body;
|
||||
if (kind === 'upload') {
|
||||
if (
|
||||
generation.current.file !== command.generation.file
|
||||
) {
|
||||
next.file = live.current.file;
|
||||
next.shared = live.current.shared;
|
||||
} else if (
|
||||
generation.current.shared !==
|
||||
command.generation.shared
|
||||
)
|
||||
next.shared = live.current.shared;
|
||||
}
|
||||
pending.current = null;
|
||||
live.current = next;
|
||||
form.setDefaults({
|
||||
body: '',
|
||||
file: null,
|
||||
shared: false,
|
||||
client_key: next.client_key,
|
||||
});
|
||||
form.setData(next);
|
||||
form.clearErrors();
|
||||
setProblem(null);
|
||||
},
|
||||
onError: () => {
|
||||
if (!pending.current?.ambiguous) pending.current = null;
|
||||
},
|
||||
onHttpException: (response) => {
|
||||
if (
|
||||
response.status >= 500 ||
|
||||
response.status === 409 ||
|
||||
pending.current?.ambiguous
|
||||
)
|
||||
return unknown();
|
||||
pending.current = null;
|
||||
setProblem(
|
||||
'Não foi possível confirmar o envio com o acesso actual. A preparação foi conservada.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
onNetworkError: unknown,
|
||||
onCancel: unknown,
|
||||
},
|
||||
);
|
||||
}
|
||||
return {
|
||||
form,
|
||||
data: form.data,
|
||||
change,
|
||||
submit,
|
||||
problem,
|
||||
recovering,
|
||||
dirty,
|
||||
blocked,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,845 @@
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { createOperationKey } from './operation-key';
|
||||
|
||||
type Values = Record<string, string>;
|
||||
type Kind = 'agreement' | 'milestone';
|
||||
type Snapshot = {
|
||||
actorId: number | null;
|
||||
partnershipVersion: number | null;
|
||||
interestVersion: number | null;
|
||||
commands: {
|
||||
key: string;
|
||||
action: string;
|
||||
version: number;
|
||||
status: string;
|
||||
party: string | null;
|
||||
}[];
|
||||
confirmations: Record<string, { actorId: number; reason: string }>;
|
||||
id: number | null;
|
||||
version: number | null;
|
||||
context: string;
|
||||
roomVersion: number;
|
||||
status: string;
|
||||
canWrite: boolean;
|
||||
values: Values;
|
||||
};
|
||||
function object(value: unknown): value is Record<string, unknown> {
|
||||
return !!value && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
function positive(value: unknown): value is number {
|
||||
return (
|
||||
typeof value === 'number' && Number.isSafeInteger(value) && value > 0
|
||||
);
|
||||
}
|
||||
function text(value: unknown): string | null {
|
||||
return value == null ? '' : typeof value === 'string' ? value : null;
|
||||
}
|
||||
const milestoneKeys = [
|
||||
'title',
|
||||
'responsible_id',
|
||||
'due_date',
|
||||
'status',
|
||||
'evidence',
|
||||
];
|
||||
function snapshot(
|
||||
props: unknown,
|
||||
roomId: number,
|
||||
kind: Kind,
|
||||
itemId: number | null,
|
||||
creationKey?: string,
|
||||
): Snapshot | null {
|
||||
if (
|
||||
!object(props) ||
|
||||
!object(props.room) ||
|
||||
props.room.id !== roomId ||
|
||||
!positive(props.room.version) ||
|
||||
typeof props.room.status !== 'string' ||
|
||||
typeof props.canWrite !== 'boolean'
|
||||
)
|
||||
return null;
|
||||
const room = props.room;
|
||||
const actorId = positive(props.agreementActorId)
|
||||
? props.agreementActorId
|
||||
: null;
|
||||
const partnershipVersion =
|
||||
object(props.partnership) && positive(props.partnership.version)
|
||||
? props.partnership.version
|
||||
: null;
|
||||
const interestVersion =
|
||||
object(props.interest) && positive(props.interest.version)
|
||||
? props.interest.version
|
||||
: null;
|
||||
if (
|
||||
kind === 'agreement' &&
|
||||
(!actorId ||
|
||||
!partnershipVersion ||
|
||||
!interestVersion ||
|
||||
!Array.isArray(props.agreementCommands) ||
|
||||
!props.agreementCommands.every(
|
||||
(command) =>
|
||||
object(command) &&
|
||||
typeof command.key === 'string' &&
|
||||
typeof command.action === 'string' &&
|
||||
positive(command.version) &&
|
||||
typeof command.status === 'string' &&
|
||||
(command.party === null ||
|
||||
command.party === 'proponent' ||
|
||||
command.party === 'candidate'),
|
||||
))
|
||||
)
|
||||
return null;
|
||||
let values: Record<string, string | null>,
|
||||
id: number | null = roomId,
|
||||
version: number | null = room.version as number;
|
||||
const confirmations: Snapshot['confirmations'] = {};
|
||||
if (kind === 'agreement') {
|
||||
if (room.agreement !== null && !object(room.agreement)) return null;
|
||||
const agreement = object(room.agreement) ? room.agreement : {};
|
||||
if (object(agreement.confirmations))
|
||||
for (const party of ['proponent', 'candidate']) {
|
||||
const confirmation = agreement.confirmations[party];
|
||||
if (object(confirmation) && positive(confirmation.actor_id))
|
||||
confirmations[party] = {
|
||||
actorId: confirmation.actor_id,
|
||||
reason:
|
||||
typeof confirmation.reason === 'string'
|
||||
? confirmation.reason
|
||||
: '',
|
||||
};
|
||||
}
|
||||
values = {
|
||||
title: text(agreement.title),
|
||||
terms: text(agreement.terms),
|
||||
reason: '',
|
||||
};
|
||||
} else if (itemId === null && !creationKey) {
|
||||
id = null;
|
||||
version = null;
|
||||
values = {
|
||||
title: '',
|
||||
responsible_id: '',
|
||||
due_date: '',
|
||||
status: 'pending',
|
||||
evidence: '',
|
||||
};
|
||||
} else {
|
||||
if (!Array.isArray(props.milestones)) return null;
|
||||
const item = props.milestones.find(
|
||||
(candidate) =>
|
||||
object(candidate) &&
|
||||
(creationKey
|
||||
? candidate.client_key === creationKey
|
||||
: candidate.id === itemId),
|
||||
);
|
||||
if (
|
||||
!object(item) ||
|
||||
!positive(item.id) ||
|
||||
!positive(item.version) ||
|
||||
!positive(item.responsible_id)
|
||||
)
|
||||
return null;
|
||||
id = item.id;
|
||||
version = item.version;
|
||||
values = {
|
||||
title: text(item.title),
|
||||
responsible_id: String(item.responsible_id),
|
||||
due_date: text(item.due_date),
|
||||
status: text(item.status),
|
||||
evidence: text(item.evidence),
|
||||
};
|
||||
}
|
||||
if (!Object.values(values).every((value) => typeof value === 'string'))
|
||||
return null;
|
||||
return {
|
||||
actorId,
|
||||
partnershipVersion,
|
||||
interestVersion,
|
||||
confirmations,
|
||||
commands:
|
||||
kind === 'agreement' && Array.isArray(props.agreementCommands)
|
||||
? props.agreementCommands.map((command) => ({
|
||||
key: command.key,
|
||||
action: command.action,
|
||||
version: command.version,
|
||||
status: command.status,
|
||||
party: command.party,
|
||||
}))
|
||||
: [],
|
||||
id,
|
||||
version,
|
||||
context: JSON.stringify(
|
||||
kind === 'agreement'
|
||||
? [
|
||||
room.version,
|
||||
room.status,
|
||||
props.canWrite,
|
||||
partnershipVersion,
|
||||
interestVersion,
|
||||
]
|
||||
: [room.version, room.status, props.canWrite],
|
||||
),
|
||||
roomVersion: room.version as number,
|
||||
status: room.status as string,
|
||||
canWrite: props.canWrite,
|
||||
values: values as Values,
|
||||
};
|
||||
}
|
||||
const same = (a: Values, b: Values) =>
|
||||
Object.keys(a).every((key) => a[key] === b[key]);
|
||||
const normal = (value: string) => value.trim();
|
||||
export function useRoomEdit({
|
||||
props,
|
||||
roomId,
|
||||
kind,
|
||||
itemId = null,
|
||||
}: {
|
||||
props: unknown;
|
||||
roomId: number;
|
||||
kind: Kind;
|
||||
itemId?: number | null;
|
||||
}) {
|
||||
const alive = useRef(true);
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
};
|
||||
}, []);
|
||||
const current = snapshot(props, roomId, kind, itemId);
|
||||
const initial = useRef(current);
|
||||
const initialIdentity = useRef(JSON.stringify([roomId, kind, itemId]));
|
||||
const observedIdentity = useRef(initialIdentity.current);
|
||||
observedIdentity.current = JSON.stringify([roomId, kind, itemId]);
|
||||
const empty: Values =
|
||||
kind === 'agreement'
|
||||
? { title: '', terms: '', reason: '' }
|
||||
: {
|
||||
title: '',
|
||||
responsible_id: '',
|
||||
due_date: '',
|
||||
status: 'pending',
|
||||
evidence: '',
|
||||
};
|
||||
const form = useForm<{
|
||||
version: number | null;
|
||||
client_key: string;
|
||||
values: Values;
|
||||
}>({
|
||||
version: current?.version ?? null,
|
||||
client_key: createOperationKey(),
|
||||
values: current?.values ?? empty,
|
||||
});
|
||||
const live = useRef(form.data);
|
||||
live.current = form.data;
|
||||
const edited = useRef(new Set<string>());
|
||||
const generation = useRef<Record<string, number>>({});
|
||||
const pending = useRef<{
|
||||
command: Record<string, string | number | null>;
|
||||
generations: Record<string, number>;
|
||||
ambiguous: boolean;
|
||||
base: Snapshot;
|
||||
values: Values;
|
||||
} | null>(null);
|
||||
const [choices, setChoices] = useState<Record<string, 'mine' | 'current'>>(
|
||||
{},
|
||||
);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [needsCompare, setNeedsCompare] = useState(false);
|
||||
const [problem, setProblem] = useState<string | null>(null);
|
||||
const [mustRefresh, setMustRefresh] = useState(false),
|
||||
[accessDenied, setAccessDenied] = useState(false);
|
||||
const [created, setCreated] = useState<number | null>(null);
|
||||
const isNew = kind === 'milestone' && itemId === null;
|
||||
const keys = Object.keys(current?.values ?? empty);
|
||||
const invalid =
|
||||
!current ||
|
||||
!initial.current ||
|
||||
(kind === 'agreement' && current.actorId !== initial.current.actorId) ||
|
||||
initialIdentity.current !== JSON.stringify([roomId, kind, itemId]);
|
||||
const stale =
|
||||
!!current &&
|
||||
!!initial.current &&
|
||||
(current.version !== initial.current.version ||
|
||||
current.context !== initial.current.context ||
|
||||
!same(current.values, initial.current.values));
|
||||
const changed =
|
||||
current && initial.current
|
||||
? keys.filter(
|
||||
(key) => current.values[key] !== initial.current?.values[key],
|
||||
)
|
||||
: [];
|
||||
const conflicts = current
|
||||
? changed.filter(
|
||||
(key) =>
|
||||
edited.current.has(key) &&
|
||||
live.current.values[key] !== current.values[key],
|
||||
)
|
||||
: [];
|
||||
const choiceKey = (key: string) =>
|
||||
JSON.stringify([
|
||||
current?.version,
|
||||
current?.context,
|
||||
key,
|
||||
current?.values[key],
|
||||
]);
|
||||
const unresolved = conflicts.filter(
|
||||
(key) => choices[choiceKey(key)] !== 'mine',
|
||||
);
|
||||
const editable =
|
||||
!!current?.canWrite &&
|
||||
(kind === 'agreement'
|
||||
? ['negotiation', 'agreement_recorded', 'agreed', 'execution']
|
||||
: ['agreement_recorded', 'agreed', 'execution']
|
||||
).includes(current.status);
|
||||
const recovering =
|
||||
(isNew || kind === 'agreement') &&
|
||||
!!pending.current?.ambiguous &&
|
||||
!!current?.canWrite &&
|
||||
!accessDenied;
|
||||
const blocked =
|
||||
invalid ||
|
||||
stale ||
|
||||
refreshing ||
|
||||
needsCompare ||
|
||||
(kind === 'agreement' && (accessDenied || !!pending.current)) ||
|
||||
(!editable && !recovering);
|
||||
const dirty =
|
||||
!!pending.current ||
|
||||
(!!initial.current &&
|
||||
(!same(live.current.values, initial.current.values) ||
|
||||
keys.some(
|
||||
(key) =>
|
||||
edited.current.has(key) &&
|
||||
current &&
|
||||
live.current.values[key] !== current.values[key],
|
||||
)));
|
||||
// Untouched controls follow current data. Deliberate edits and uncertain commands require comparison.
|
||||
useEffect(() => {
|
||||
if (
|
||||
!current ||
|
||||
invalid ||
|
||||
(!stale && !(kind === 'agreement' && pending.current?.ambiguous)) ||
|
||||
dirty ||
|
||||
edited.current.size > 0 ||
|
||||
pending.current ||
|
||||
form.processing ||
|
||||
needsCompare
|
||||
)
|
||||
return;
|
||||
if (kind === 'agreement' && mustRefresh) return;
|
||||
initial.current = current;
|
||||
live.current = {
|
||||
...live.current,
|
||||
version: current.version,
|
||||
values: { ...current.values },
|
||||
};
|
||||
form.setDefaults(live.current);
|
||||
form.setData(live.current);
|
||||
}, [current, invalid, stale, dirty, form.processing, needsCompare]);
|
||||
function change(key: string, value: string) {
|
||||
if (!keys.includes(key)) return;
|
||||
edited.current.add(key);
|
||||
generation.current[key] = (generation.current[key] ?? 0) + 1;
|
||||
live.current = {
|
||||
...live.current,
|
||||
values: { ...live.current.values, [key]: value },
|
||||
};
|
||||
form.setData(live.current);
|
||||
setChoices((previous) => {
|
||||
const next = { ...previous };
|
||||
delete next[choiceKey(key)];
|
||||
return next;
|
||||
});
|
||||
}
|
||||
function choose(key: string, value: 'mine' | 'current') {
|
||||
if (!current || !keys.includes(key)) return;
|
||||
if (value === 'current') change(key, current.values[key]);
|
||||
setChoices((previous) => ({ ...previous, [choiceKey(key)]: value }));
|
||||
}
|
||||
function adopt() {
|
||||
if (
|
||||
!current ||
|
||||
invalid ||
|
||||
(!stale && !(kind === 'agreement' && pending.current?.ambiguous)) ||
|
||||
(kind === 'agreement' && (mustRefresh || accessDenied)) ||
|
||||
unresolved.length ||
|
||||
refreshing ||
|
||||
form.processing
|
||||
)
|
||||
return;
|
||||
const values = { ...current.values };
|
||||
for (const key of keys)
|
||||
if (edited.current.has(key)) values[key] = live.current.values[key];
|
||||
initial.current = current;
|
||||
live.current = { ...live.current, version: current.version, values };
|
||||
form.setData(live.current);
|
||||
form.setDefaults({ ...live.current, values: current.values });
|
||||
form.clearErrors();
|
||||
setChoices({});
|
||||
setNeedsCompare(false);
|
||||
setProblem(null);
|
||||
if (kind === 'agreement') pending.current = null;
|
||||
}
|
||||
function httpFailure(response: { status: number }) {
|
||||
if (!alive.current) return false;
|
||||
if (kind === 'agreement') {
|
||||
setMustRefresh(true);
|
||||
setAccessDenied([401, 403, 404, 419].includes(response.status));
|
||||
}
|
||||
setProblem(
|
||||
response.status === 409
|
||||
? 'O registo ou o estado da sala mudou. Compare com os dados actuais; as suas edições foram conservadas.'
|
||||
: 'Não foi possível confirmar a operação com o acesso actual. As suas edições foram conservadas.',
|
||||
);
|
||||
if (response.status === 409 || response.status >= 500)
|
||||
setNeedsCompare(true);
|
||||
if (pending.current) {
|
||||
if (kind === 'agreement' && response.status === 409) {
|
||||
pending.current = null;
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
response.status >= 500 ||
|
||||
response.status === 409 ||
|
||||
pending.current.ambiguous
|
||||
)
|
||||
pending.current.ambiguous = true;
|
||||
else pending.current = null;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function refresh() {
|
||||
if (refreshing || form.processing) return;
|
||||
setRefreshing(true);
|
||||
router.reload({
|
||||
only: [
|
||||
'room',
|
||||
'milestones',
|
||||
'participants',
|
||||
'canWrite',
|
||||
'messages',
|
||||
'documents',
|
||||
'partnership',
|
||||
'interest',
|
||||
'agreementActorId',
|
||||
'agreementCommands',
|
||||
'agreementParty',
|
||||
],
|
||||
onSuccess: (page) => {
|
||||
if (!alive.current) return;
|
||||
if (
|
||||
kind === 'agreement' &&
|
||||
pending.current &&
|
||||
acknowledgeAgreement(page.props, pending.current)
|
||||
)
|
||||
return;
|
||||
const fresh = snapshot(page.props, roomId, kind, itemId);
|
||||
if (
|
||||
kind === 'agreement' &&
|
||||
fresh &&
|
||||
fresh.actorId === initial.current?.actorId
|
||||
) {
|
||||
setMustRefresh(false);
|
||||
setAccessDenied(false);
|
||||
}
|
||||
if (
|
||||
fresh &&
|
||||
initial.current &&
|
||||
fresh.version === initial.current.version &&
|
||||
fresh.context === initial.current.context &&
|
||||
same(fresh.values, initial.current.values)
|
||||
) {
|
||||
setNeedsCompare(false);
|
||||
setProblem(null);
|
||||
}
|
||||
},
|
||||
onHttpException: () => {
|
||||
if (!alive.current) return false;
|
||||
if (kind === 'agreement') {
|
||||
setMustRefresh(true);
|
||||
setAccessDenied(true);
|
||||
}
|
||||
setProblem(
|
||||
'Não foi possível recuperar esta sala com o acesso actual. As suas edições foram conservadas.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
onNetworkError: () => {
|
||||
if (!alive.current) return false;
|
||||
setProblem(
|
||||
'A recuperação não foi confirmada. As suas edições foram conservadas.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
onFinish: () => {
|
||||
if (alive.current) setRefreshing(false);
|
||||
},
|
||||
});
|
||||
}
|
||||
function acknowledgeAgreement(
|
||||
props: unknown,
|
||||
sent: NonNullable<typeof pending.current>,
|
||||
): boolean {
|
||||
if (!alive.current || pending.current !== sent) return false;
|
||||
const fresh = snapshot(props, roomId, 'agreement', null),
|
||||
action = String(sent.command.action),
|
||||
version = Number(sent.command.version) + 1;
|
||||
const receipt = fresh?.commands.find(
|
||||
(command) =>
|
||||
command.key === sent.command.client_key &&
|
||||
command.action === action &&
|
||||
command.version === version,
|
||||
);
|
||||
if (
|
||||
!fresh ||
|
||||
!receipt ||
|
||||
fresh.actorId !== sent.base.actorId ||
|
||||
fresh.version === null ||
|
||||
fresh.version < version
|
||||
)
|
||||
return false;
|
||||
const expected: Values =
|
||||
action === 'record'
|
||||
? {
|
||||
title: normal(sent.values.title),
|
||||
terms: normal(sent.values.terms),
|
||||
reason: '',
|
||||
}
|
||||
: { ...sent.base.values, reason: '' };
|
||||
if (
|
||||
fresh.version === version &&
|
||||
(fresh.status !== receipt.status ||
|
||||
fresh.values.title !== expected.title ||
|
||||
fresh.values.terms !== expected.terms)
|
||||
)
|
||||
return false;
|
||||
if (
|
||||
fresh.version === version &&
|
||||
action === 'confirm' &&
|
||||
(!receipt.party ||
|
||||
fresh.confirmations[receipt.party]?.actorId !==
|
||||
sent.base.actorId ||
|
||||
fresh.confirmations[receipt.party]?.reason !==
|
||||
normal(String(sent.command.reason)) ||
|
||||
(receipt.status === 'agreed' &&
|
||||
(!fresh.confirmations.proponent ||
|
||||
!fresh.confirmations.candidate)))
|
||||
)
|
||||
return false;
|
||||
const later =
|
||||
fresh.version > version ||
|
||||
fresh.partnershipVersion !== sent.base.partnershipVersion ||
|
||||
fresh.interestVersion !== sent.base.interestVersion;
|
||||
const saved: Snapshot = later
|
||||
? {
|
||||
...sent.base,
|
||||
version,
|
||||
roomVersion: version,
|
||||
status: receipt.status,
|
||||
values: expected,
|
||||
context: JSON.stringify([
|
||||
version,
|
||||
receipt.status,
|
||||
sent.base.canWrite,
|
||||
sent.base.partnershipVersion,
|
||||
sent.base.interestVersion,
|
||||
]),
|
||||
}
|
||||
: fresh;
|
||||
const merged = { ...saved.values };
|
||||
edited.current.clear();
|
||||
for (const key of keys)
|
||||
if (
|
||||
(generation.current[key] ?? 0) !==
|
||||
(sent.generations[key] ?? 0) ||
|
||||
(action !== 'record' &&
|
||||
key !== 'reason' &&
|
||||
live.current.values[key] !== sent.base.values[key])
|
||||
) {
|
||||
merged[key] = live.current.values[key];
|
||||
edited.current.add(key);
|
||||
}
|
||||
initial.current = saved;
|
||||
pending.current = null;
|
||||
live.current = {
|
||||
...live.current,
|
||||
version: saved.version,
|
||||
values: merged,
|
||||
};
|
||||
form.setDefaults({ ...live.current, values: saved.values });
|
||||
form.setData(live.current);
|
||||
form.clearErrors();
|
||||
setChoices({});
|
||||
setNeedsCompare(later);
|
||||
setMustRefresh(false);
|
||||
setAccessDenied(false);
|
||||
setProblem(
|
||||
later
|
||||
? 'A acção foi reconhecida, mas existem decisões posteriores. Compare antes de preparar outra acção.'
|
||||
: null,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
function submit(action = 'record', recover = false) {
|
||||
if (
|
||||
!alive.current ||
|
||||
form.processing ||
|
||||
!initial.current ||
|
||||
(kind === 'agreement' &&
|
||||
(invalid || accessDenied || !current?.canWrite || refreshing))
|
||||
)
|
||||
return;
|
||||
if (recover && kind === 'agreement') {
|
||||
if (!pending.current?.ambiguous) return;
|
||||
action = String(pending.current.command.action);
|
||||
} else if (blocked) return;
|
||||
const base = initial.current;
|
||||
if (kind === 'agreement' && !recover) {
|
||||
const allowed: Record<string, string[]> = {
|
||||
record: ['negotiation', 'agreement_recorded'],
|
||||
confirm: ['agreement_recorded'],
|
||||
start: ['agreed'],
|
||||
complete: ['execution'],
|
||||
renew: ['agreed', 'execution'],
|
||||
cancel: [
|
||||
'negotiation',
|
||||
'agreement_recorded',
|
||||
'agreed',
|
||||
'execution',
|
||||
],
|
||||
};
|
||||
if (!allowed[action]?.includes(base.status)) return;
|
||||
}
|
||||
const command: Record<string, string | number | null> =
|
||||
pending.current?.command ??
|
||||
(kind === 'agreement'
|
||||
? action === 'record'
|
||||
? {
|
||||
...live.current.values,
|
||||
version: live.current.version,
|
||||
action,
|
||||
client_key: createOperationKey(),
|
||||
partnership_version: base.partnershipVersion,
|
||||
interest_version: base.interestVersion,
|
||||
}
|
||||
: {
|
||||
version: live.current.version,
|
||||
action,
|
||||
reason: live.current.values.reason,
|
||||
client_key: createOperationKey(),
|
||||
partnership_version: base.partnershipVersion,
|
||||
interest_version: base.interestVersion,
|
||||
}
|
||||
: {
|
||||
...live.current.values,
|
||||
version: live.current.version,
|
||||
...(isNew ? { client_key: live.current.client_key } : {}),
|
||||
});
|
||||
const sentGenerations = pending.current?.generations ?? {
|
||||
...generation.current,
|
||||
};
|
||||
if ((isNew || kind === 'agreement') && !pending.current)
|
||||
pending.current = {
|
||||
command,
|
||||
generations: sentGenerations,
|
||||
ambiguous: false,
|
||||
base,
|
||||
values: { ...live.current.values },
|
||||
};
|
||||
const sentValues = { ...live.current.values };
|
||||
const attempt = pending.current;
|
||||
setProblem(null);
|
||||
form.transform(() => command);
|
||||
const unknown = () => {
|
||||
if (!alive.current) return false;
|
||||
if (kind === 'agreement' && pending.current !== attempt)
|
||||
return false;
|
||||
if (kind === 'agreement') setMustRefresh(true);
|
||||
if (pending.current) pending.current.ambiguous = true;
|
||||
else setNeedsCompare(true);
|
||||
setProblem(
|
||||
'A gravação não foi confirmada. As suas edições foram conservadas.',
|
||||
);
|
||||
return false;
|
||||
};
|
||||
const options = {
|
||||
preserveScroll: true,
|
||||
onSuccess: (page: { props: Record<string, unknown> }) => {
|
||||
if (!alive.current) return;
|
||||
if (kind === 'agreement') {
|
||||
if (
|
||||
attempt &&
|
||||
pending.current === attempt &&
|
||||
!acknowledgeAgreement(page.props, attempt)
|
||||
) {
|
||||
attempt.ambiguous = true;
|
||||
setMustRefresh(true);
|
||||
setNeedsCompare(true);
|
||||
setProblem(
|
||||
'A resposta não reconheceu esta tentativa. A preparação foi conservada.',
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (
|
||||
observedIdentity.current !==
|
||||
JSON.stringify([roomId, kind, itemId])
|
||||
)
|
||||
return;
|
||||
const saved = snapshot(
|
||||
page.props,
|
||||
roomId,
|
||||
kind,
|
||||
itemId,
|
||||
isNew ? String(command.client_key) : undefined,
|
||||
);
|
||||
if (
|
||||
!saved ||
|
||||
(!isNew && saved.version !== Number(command.version) + 1)
|
||||
) {
|
||||
setProblem(
|
||||
'A resposta não confirmou este registo. Recupere os dados antes de continuar; a edição foi conservada.',
|
||||
);
|
||||
setNeedsCompare(true);
|
||||
if (pending.current) pending.current.ambiguous = true;
|
||||
return;
|
||||
}
|
||||
if (!isNew) {
|
||||
if (
|
||||
milestoneKeys.some(
|
||||
(key) =>
|
||||
saved.values[key] !== normal(sentValues[key]),
|
||||
) ||
|
||||
saved.context !== base.context
|
||||
) {
|
||||
setProblem(
|
||||
'Os dados devolvidos diferem da operação enviada. Compare antes de continuar; a sua edição foi conservada.',
|
||||
);
|
||||
setNeedsCompare(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
const defaults = isNew
|
||||
? snapshot(page.props, roomId, kind, null)
|
||||
: saved;
|
||||
if (!defaults) return;
|
||||
const merged = { ...defaults.values };
|
||||
edited.current.clear();
|
||||
for (const key of keys)
|
||||
if (
|
||||
(generation.current[key] ?? 0) !==
|
||||
(sentGenerations[key] ?? 0)
|
||||
) {
|
||||
merged[key] = live.current.values[key];
|
||||
edited.current.add(key);
|
||||
}
|
||||
initial.current = defaults;
|
||||
if (isNew) {
|
||||
setCreated(saved.id);
|
||||
pending.current = null;
|
||||
}
|
||||
live.current = {
|
||||
version: defaults.version,
|
||||
client_key: isNew
|
||||
? createOperationKey()
|
||||
: live.current.client_key,
|
||||
values: merged,
|
||||
};
|
||||
form.setDefaults({ ...live.current, values: defaults.values });
|
||||
form.setData(live.current);
|
||||
form.clearErrors();
|
||||
setChoices({});
|
||||
setNeedsCompare(false);
|
||||
setProblem(null);
|
||||
},
|
||||
onError: () => {
|
||||
if (
|
||||
!alive.current ||
|
||||
(kind === 'agreement' && pending.current !== attempt)
|
||||
)
|
||||
return;
|
||||
if (pending.current && !pending.current.ambiguous)
|
||||
pending.current = null;
|
||||
},
|
||||
onHttpException: (response: { status: number }) =>
|
||||
kind === 'agreement' && pending.current !== attempt
|
||||
? false
|
||||
: httpFailure(response),
|
||||
onNetworkError: unknown,
|
||||
onCancel: unknown,
|
||||
};
|
||||
if (kind === 'agreement')
|
||||
form.post(`/parcerias/salas/${roomId}/acordo`, options);
|
||||
else if (isNew) form.post(`/parcerias/salas/${roomId}/marcos`, options);
|
||||
else form.put(`/parcerias/salas/${roomId}/marcos/${itemId}`, options);
|
||||
}
|
||||
return {
|
||||
form,
|
||||
values: form.data.values,
|
||||
current: current?.values ?? empty,
|
||||
baseVersion: initial.current?.version,
|
||||
version: current?.version,
|
||||
status: current?.status,
|
||||
stale,
|
||||
invalid,
|
||||
editable,
|
||||
dirty,
|
||||
blocked,
|
||||
refreshing,
|
||||
changed,
|
||||
conflicts,
|
||||
unresolved,
|
||||
problem,
|
||||
recovering,
|
||||
pendingAction:
|
||||
kind === 'agreement' && pending.current?.ambiguous
|
||||
? String(pending.current.command.action)
|
||||
: null,
|
||||
canRecover:
|
||||
kind === 'agreement' &&
|
||||
recovering &&
|
||||
!invalid &&
|
||||
!refreshing &&
|
||||
!form.processing,
|
||||
recover: () => submit('record', true),
|
||||
mustRefresh: kind === 'agreement' && mustRefresh,
|
||||
created,
|
||||
change,
|
||||
choose,
|
||||
adopt,
|
||||
refresh,
|
||||
submit,
|
||||
};
|
||||
}
|
||||
export type RoomEditor = ReturnType<typeof useRoomEdit>;
|
||||
|
||||
/** One room-level leave guard. No draft content is persisted in browser storage. */
|
||||
export function useRoomLeaveGuard(dirty: boolean) {
|
||||
const live = useRef(dirty);
|
||||
live.current = dirty;
|
||||
useEffect(() => {
|
||||
const leave = (event: BeforeUnloadEvent) => {
|
||||
if (live.current) {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
}
|
||||
};
|
||||
const stop = router.on('before', (event) => {
|
||||
if (
|
||||
live.current &&
|
||||
event.detail.visit.method === 'get' &&
|
||||
event.detail.visit.preserveState !== true &&
|
||||
!window.confirm(
|
||||
'Há alterações por guardar nesta sala. Pretende sair sem as guardar?',
|
||||
)
|
||||
)
|
||||
event.preventDefault();
|
||||
});
|
||||
window.addEventListener('beforeunload', leave);
|
||||
return () => {
|
||||
stop();
|
||||
window.removeEventListener('beforeunload', leave);
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import type { UsageReport } from './product-usage';
|
||||
|
||||
export type ExperimentValues = Record<string, string>;
|
||||
export type ExperimentDocument = {
|
||||
definition_version: string;
|
||||
version: number;
|
||||
at: string;
|
||||
actor: { id: number; name: string };
|
||||
reason: string;
|
||||
values: ExperimentValues;
|
||||
indicator: {
|
||||
id: string;
|
||||
title: string;
|
||||
unit: string;
|
||||
source: string;
|
||||
limits: string;
|
||||
definition_version: string;
|
||||
} | null;
|
||||
plan_sha256: string;
|
||||
observation_plan_sha256: string | null;
|
||||
registration: {
|
||||
first_at: string | null;
|
||||
original_plan_sha256: string | null;
|
||||
amendments: number;
|
||||
amended_after_observation: boolean;
|
||||
};
|
||||
operational_report: UsageReport | null;
|
||||
report_matches_observation: boolean | null;
|
||||
report_scope: string;
|
||||
};
|
||||
export type ExperimentView = {
|
||||
installed: boolean;
|
||||
id: string | null;
|
||||
currentVersion: number;
|
||||
historical: boolean;
|
||||
document: ExperimentDocument | null;
|
||||
values: ExperimentValues;
|
||||
states: Record<string, string>;
|
||||
changeKinds: Record<string, string>;
|
||||
decisions: Record<string, string>;
|
||||
labels: Record<string, string>;
|
||||
catalogue: {
|
||||
definition_version: string;
|
||||
items: Omit<
|
||||
NonNullable<ExperimentDocument['indicator']>,
|
||||
'definition_version'
|
||||
>[];
|
||||
services: { code: string; title: string; version: number }[];
|
||||
};
|
||||
history: {
|
||||
version: number;
|
||||
at: string;
|
||||
actor: string;
|
||||
state: string;
|
||||
reason: string;
|
||||
}[];
|
||||
historyNext: number | null;
|
||||
};
|
||||
|
||||
export function experimentDifferences(
|
||||
base: ExperimentValues,
|
||||
mine: ExperimentValues,
|
||||
current: ExperimentValues,
|
||||
editedKeys?: readonly string[],
|
||||
): string[] {
|
||||
return [
|
||||
...new Set([
|
||||
...Object.keys(base),
|
||||
...Object.keys(mine),
|
||||
...Object.keys(current),
|
||||
]),
|
||||
].filter(
|
||||
(key) =>
|
||||
(base[key] ?? '') !== (current[key] ?? '') &&
|
||||
(editedKeys
|
||||
? editedKeys.includes(key)
|
||||
: (mine[key] ?? '') !== (base[key] ?? '')) &&
|
||||
(mine[key] ?? '') !== (current[key] ?? ''),
|
||||
);
|
||||
}
|
||||
|
||||
/** Merge only changes the user did not edit; conflicts remain explicit. */
|
||||
export function mergeExperimentValues(
|
||||
base: ExperimentValues,
|
||||
mine: ExperimentValues,
|
||||
current: ExperimentValues,
|
||||
editedKeys?: readonly string[],
|
||||
): ExperimentValues {
|
||||
return Object.fromEntries(
|
||||
[
|
||||
...new Set([
|
||||
...Object.keys(base),
|
||||
...Object.keys(mine),
|
||||
...Object.keys(current),
|
||||
]),
|
||||
].map((key) => [
|
||||
key,
|
||||
(
|
||||
editedKeys
|
||||
? !editedKeys.includes(key)
|
||||
: (mine[key] ?? '') === (base[key] ?? '')
|
||||
)
|
||||
? (current[key] ?? '')
|
||||
: (mine[key] ?? ''),
|
||||
]),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
export type SearchUsageReport = {
|
||||
installed: boolean;
|
||||
enabled_now: boolean;
|
||||
applicable: boolean;
|
||||
from: string;
|
||||
to: string;
|
||||
timezone: string;
|
||||
read_at: string;
|
||||
definition_version: string;
|
||||
available_definitions: string[];
|
||||
definition_conflict_now: boolean;
|
||||
responses: number | null;
|
||||
zero_responses: number | null;
|
||||
zero_rate: number | null;
|
||||
channels: {
|
||||
id: string;
|
||||
label: string;
|
||||
responses: number | null;
|
||||
zero_responses: number | null;
|
||||
zero_rate: number | null;
|
||||
first_recorded_at: string | null;
|
||||
last_recorded_at: string | null;
|
||||
definition_versions: string[];
|
||||
}[];
|
||||
exclusions: string[];
|
||||
limits: string[];
|
||||
completeness: string;
|
||||
temporal_basis: string;
|
||||
};
|
||||
export type UsageReport = {
|
||||
definition_version: string;
|
||||
generated_at: string;
|
||||
timezone: string;
|
||||
observed_before: string;
|
||||
filters: {
|
||||
from: string;
|
||||
to: string;
|
||||
service_code: string | null;
|
||||
search_definition?: string;
|
||||
};
|
||||
search?: SearchUsageReport;
|
||||
services: { code: string; title: string; version: number }[];
|
||||
coverage: Record<string, number | null>;
|
||||
metrics: {
|
||||
id: string;
|
||||
title: string;
|
||||
value: number | null;
|
||||
unit: string;
|
||||
numerator: number | null;
|
||||
denominator: number | null;
|
||||
state: string;
|
||||
source: string;
|
||||
limits: string;
|
||||
}[];
|
||||
unmeasured: { id: string; title: string; reason: string; href?: string }[];
|
||||
limits: string[];
|
||||
fingerprint: string;
|
||||
read_consistency: string;
|
||||
};
|
||||
|
||||
export function usageValue(value: number | null, unit = ''): string {
|
||||
if (value === null) return 'Sem medição';
|
||||
return `${value.toLocaleString('pt-PT', { maximumFractionDigits: 2 })}${unit ? ` ${unit}` : ''}`;
|
||||
}
|
||||
|
||||
/** Export the applied server snapshot, never the pending filter form. */
|
||||
export function usageExport(report: UsageReport): string {
|
||||
return JSON.stringify(report, null, 2);
|
||||
}
|
||||
@@ -35,10 +35,20 @@ export async function profileJson(
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
...(typeof FormData !== 'undefined' && data instanceof FormData
|
||||
? {}
|
||||
: { 'Content-Type': 'application/json' }),
|
||||
...(method === 'GET' ? {} : { 'X-XSRF-TOKEN': token }),
|
||||
},
|
||||
...(method === 'GET' ? {} : { body: JSON.stringify(data) }),
|
||||
...(method === 'GET'
|
||||
? {}
|
||||
: {
|
||||
body:
|
||||
typeof FormData !== 'undefined' &&
|
||||
data instanceof FormData
|
||||
? data
|
||||
: JSON.stringify(data),
|
||||
}),
|
||||
});
|
||||
const result = await response.json().catch(() => null);
|
||||
const reauthenticate =
|
||||
|
||||
@@ -0,0 +1,406 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { portalRequest, PortalApiError } from './portal-api';
|
||||
import { createOperationKey } from './operation-key';
|
||||
import { usePagePreparationGuard } from './page-preparation-guard';
|
||||
export type SupportPlan = {
|
||||
actorId: number;
|
||||
target: { database: string; port: number };
|
||||
hash: string;
|
||||
code_hash: string;
|
||||
installed: boolean;
|
||||
consistent: boolean;
|
||||
repairable: boolean;
|
||||
ready: boolean;
|
||||
action: 'none' | 'install' | 'repair_known_base' | 'blocked';
|
||||
schema: { state: string; ledger: boolean };
|
||||
dependencies: Record<string, boolean>;
|
||||
changes: string[];
|
||||
backupDate: string | null;
|
||||
rollback: string;
|
||||
commands: { key: string; code_hash: string }[];
|
||||
mfa_confirmed: boolean;
|
||||
};
|
||||
type Attempt = {
|
||||
body: {
|
||||
hash: string;
|
||||
reason: string;
|
||||
confirm: true;
|
||||
idempotency_key: string;
|
||||
};
|
||||
code: string;
|
||||
generation: number;
|
||||
};
|
||||
const endpoint = '/management/profile-install/technical-support';
|
||||
const object = (v: unknown): v is Record<string, unknown> =>
|
||||
!!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const hex = (v: unknown): v is string =>
|
||||
typeof v === 'string' && /^[a-f0-9]{64}$/.test(v);
|
||||
const target = (v: unknown): v is SupportPlan['target'] =>
|
||||
object(v) &&
|
||||
typeof v.database === 'string' &&
|
||||
Number.isSafeInteger(v.port) &&
|
||||
Number(v.port) > 0;
|
||||
const validPlan = (v: unknown): v is SupportPlan =>
|
||||
object(v) &&
|
||||
typeof v.actorId === 'number' &&
|
||||
Number.isSafeInteger(v.actorId) &&
|
||||
v.actorId > 0 &&
|
||||
target(v.target) &&
|
||||
hex(v.hash) &&
|
||||
hex(v.code_hash) &&
|
||||
typeof v.installed === 'boolean' &&
|
||||
typeof v.consistent === 'boolean' &&
|
||||
typeof v.repairable === 'boolean' &&
|
||||
typeof v.ready === 'boolean' &&
|
||||
['none', 'install', 'repair_known_base', 'blocked'].includes(
|
||||
String(v.action),
|
||||
) &&
|
||||
object(v.schema) &&
|
||||
typeof v.schema.state === 'string' &&
|
||||
typeof v.schema.ledger === 'boolean' &&
|
||||
object(v.dependencies) &&
|
||||
Object.values(v.dependencies).every((x) => typeof x === 'boolean') &&
|
||||
Array.isArray(v.changes) &&
|
||||
v.changes.every((x) => typeof x === 'string') &&
|
||||
(v.backupDate === null || typeof v.backupDate === 'string') &&
|
||||
typeof v.rollback === 'string' &&
|
||||
typeof v.mfa_confirmed === 'boolean' &&
|
||||
Array.isArray(v.commands) &&
|
||||
v.commands.every(
|
||||
(x) => object(x) && typeof x.key === 'string' && hex(x.code_hash),
|
||||
);
|
||||
const sameTarget = (a: SupportPlan['target'], b: SupportPlan['target']) =>
|
||||
a.database === b.database && a.port === b.port;
|
||||
export function useProfileSupportInstallation(initial: SupportPlan) {
|
||||
const [plan, setPlan] = useState(initial),
|
||||
[base, setBase] = useState(initial),
|
||||
[reason, setReason] = useState(''),
|
||||
[confirmed, setConfirmed] = useState(false),
|
||||
[busy, setBusy] = useState(false),
|
||||
[refreshing, setRefreshing] = useState(false),
|
||||
[uncertain, setUncertain] = useState(false),
|
||||
[blocked, setBlocked] = useState(false),
|
||||
[needsRefresh, setNeedsRefresh] = useState(false),
|
||||
[message, setMessage] = useState(''),
|
||||
[error, setError] = useState('');
|
||||
const origin = useRef({ actor: initial.actorId, target: initial.target }),
|
||||
epoch = useRef({ actor: initial.actorId, target: initial.target }),
|
||||
alive = useRef(true),
|
||||
pending = useRef<Attempt | null>(null),
|
||||
active = useRef<Attempt | null>(null),
|
||||
reading = useRef<object | null>(null),
|
||||
generation = useRef(0),
|
||||
text = useRef(reason),
|
||||
committed = useRef<Attempt | null>(null);
|
||||
if (
|
||||
epoch.current.actor !== initial.actorId ||
|
||||
!sameTarget(epoch.current.target, initial.target)
|
||||
)
|
||||
epoch.current = { actor: initial.actorId, target: initial.target };
|
||||
text.current = reason;
|
||||
const valid =
|
||||
validPlan(plan) &&
|
||||
plan.actorId === origin.current.actor &&
|
||||
sameTarget(plan.target, origin.current.target) &&
|
||||
initial.actorId === origin.current.actor &&
|
||||
sameTarget(initial.target, origin.current.target);
|
||||
const stale = base.hash !== plan.hash;
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
};
|
||||
}, []);
|
||||
function change(value: string) {
|
||||
generation.current++;
|
||||
text.current = value;
|
||||
setReason(value);
|
||||
setConfirmed(false);
|
||||
setError('');
|
||||
}
|
||||
function acknowledge(attempt: Attempt) {
|
||||
if (pending.current !== attempt) return;
|
||||
pending.current = null;
|
||||
active.current = null;
|
||||
committed.current = attempt;
|
||||
setBusy(false);
|
||||
setUncertain(false);
|
||||
setNeedsRefresh(true);
|
||||
setConfirmed(false);
|
||||
setError('');
|
||||
setMessage(
|
||||
'Resultado da actualização confirmado. Confira a prévia actual.',
|
||||
);
|
||||
if (generation.current === attempt.generation) {
|
||||
text.current = '';
|
||||
setReason('');
|
||||
}
|
||||
}
|
||||
function read(value: unknown) {
|
||||
if (
|
||||
!validPlan(value) ||
|
||||
value.actorId !== origin.current.actor ||
|
||||
!sameTarget(value.target, origin.current.target)
|
||||
)
|
||||
return false;
|
||||
setPlan(value);
|
||||
setBlocked(false);
|
||||
setError('');
|
||||
const attempt = pending.current;
|
||||
if (
|
||||
attempt &&
|
||||
value.commands.some(
|
||||
(c) =>
|
||||
c.key === attempt.body.idempotency_key &&
|
||||
c.code_hash === attempt.code,
|
||||
)
|
||||
)
|
||||
acknowledge(attempt);
|
||||
const known = committed.current;
|
||||
if (known) {
|
||||
if (
|
||||
!value.commands.some(
|
||||
(c) =>
|
||||
c.key === known.body.idempotency_key &&
|
||||
c.code_hash === known.code,
|
||||
)
|
||||
) {
|
||||
setError(
|
||||
'Esta consulta ainda não confirma o resultado já recebido. Actualize novamente antes de outra acção.',
|
||||
);
|
||||
return true;
|
||||
}
|
||||
if (
|
||||
value.code_hash === known.code &&
|
||||
value.installed &&
|
||||
value.consistent
|
||||
)
|
||||
setBase(value);
|
||||
committed.current = null;
|
||||
setNeedsRefresh(false);
|
||||
} else setNeedsRefresh(false);
|
||||
return true;
|
||||
}
|
||||
useEffect(() => {
|
||||
if (validPlan(initial)) read(initial);
|
||||
}, [initial]);
|
||||
async function refresh() {
|
||||
if (reading.current) return;
|
||||
const request = {},
|
||||
scope = epoch.current;
|
||||
reading.current = request;
|
||||
setRefreshing(true);
|
||||
try {
|
||||
const value = await portalRequest<unknown>(endpoint);
|
||||
if (alive.current && epoch.current === scope && !read(value))
|
||||
setError(
|
||||
'A consulta recebida não corresponde a esta conta e destino. A preparação foi conservada.',
|
||||
);
|
||||
} catch (e) {
|
||||
if (alive.current && epoch.current === scope) {
|
||||
if (
|
||||
e instanceof PortalApiError &&
|
||||
[401, 403, 419].includes(e.status)
|
||||
)
|
||||
setBlocked(true);
|
||||
setError(
|
||||
'Não foi possível actualizar a prévia. O fundamento e a tentativa original foram conservados.',
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (
|
||||
alive.current &&
|
||||
epoch.current === scope &&
|
||||
reading.current === request
|
||||
) {
|
||||
reading.current = null;
|
||||
setRefreshing(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
async function send(retry = false) {
|
||||
if (
|
||||
!valid ||
|
||||
blocked ||
|
||||
!plan.mfa_confirmed ||
|
||||
active.current ||
|
||||
reading.current
|
||||
)
|
||||
return;
|
||||
if (
|
||||
!retry &&
|
||||
(pending.current ||
|
||||
stale ||
|
||||
needsRefresh ||
|
||||
!confirmed ||
|
||||
!plan.ready ||
|
||||
plan.installed ||
|
||||
!plan.mfa_confirmed ||
|
||||
(!plan.consistent && !plan.repairable))
|
||||
)
|
||||
return;
|
||||
let attempt = pending.current;
|
||||
if (!attempt) {
|
||||
if (text.current.trim().length < 20 || text.current.length > 1000) {
|
||||
setError('Preencha o fundamento com 20 a 1000 caracteres.');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
attempt = {
|
||||
body: {
|
||||
hash: base.hash,
|
||||
reason: text.current,
|
||||
confirm: true,
|
||||
idempotency_key: createOperationKey().toLowerCase(),
|
||||
},
|
||||
code: base.code_hash,
|
||||
generation: generation.current,
|
||||
};
|
||||
} catch (e) {
|
||||
setError(
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Não foi possível preparar a operação.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
pending.current = attempt;
|
||||
}
|
||||
const scope = epoch.current;
|
||||
active.current = attempt;
|
||||
setBusy(true);
|
||||
setUncertain(true);
|
||||
setError('');
|
||||
try {
|
||||
const result = await portalRequest<unknown>(endpoint, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(attempt.body),
|
||||
});
|
||||
if (
|
||||
!alive.current ||
|
||||
epoch.current !== scope ||
|
||||
pending.current !== attempt
|
||||
)
|
||||
return;
|
||||
if (
|
||||
!object(result) ||
|
||||
result.actor_id !== origin.current.actor ||
|
||||
result.command_key !== attempt.body.idempotency_key ||
|
||||
result.migration !==
|
||||
'2026_11_03_080000_add_technical_support_profile' ||
|
||||
result.code_hash !== attempt.code ||
|
||||
result.installed !== true ||
|
||||
!target(result.target) ||
|
||||
!sameTarget(result.target, origin.current.target)
|
||||
)
|
||||
throw new Error(
|
||||
'A confirmação não corresponde à tentativa preparada. Consulte a prévia antes de continuar.',
|
||||
);
|
||||
acknowledge(attempt);
|
||||
void refresh();
|
||||
} catch (e) {
|
||||
if (
|
||||
!alive.current ||
|
||||
epoch.current !== scope ||
|
||||
pending.current !== attempt
|
||||
)
|
||||
return;
|
||||
if (e instanceof PortalApiError && [409, 422].includes(e.status)) {
|
||||
pending.current = null;
|
||||
setUncertain(false);
|
||||
setConfirmed(false);
|
||||
setError(
|
||||
e.status === 409
|
||||
? 'A tentativa foi recusada porque o plano mudou. Actualize e compare a prévia; o fundamento foi conservado.'
|
||||
: e.errors.reason?.join(' ') ||
|
||||
'A operação foi recusada. Confira as dependências, as provas e o fundamento.',
|
||||
);
|
||||
if (e.status === 409) {
|
||||
setNeedsRefresh(true);
|
||||
void refresh();
|
||||
}
|
||||
} else if (
|
||||
e instanceof PortalApiError &&
|
||||
[401, 403, 419].includes(e.status)
|
||||
) {
|
||||
setBlocked(true);
|
||||
setError(
|
||||
'Confirme a conta e renove a autenticação MFA antes de repetir. A preparação foi conservada.',
|
||||
);
|
||||
} else
|
||||
setError(
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Resultado sem confirmação. Conserve a tentativa original.',
|
||||
);
|
||||
} finally {
|
||||
if (
|
||||
alive.current &&
|
||||
epoch.current === scope &&
|
||||
active.current === attempt
|
||||
) {
|
||||
active.current = null;
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
function adopt() {
|
||||
if (!valid || busy || refreshing || pending.current || blocked) return;
|
||||
setBase(plan);
|
||||
setConfirmed(false);
|
||||
setNeedsRefresh(false);
|
||||
setMessage(
|
||||
'Prévia actual confirmada. Reveja o fundamento e confirme esta operação.',
|
||||
);
|
||||
setError('');
|
||||
}
|
||||
usePagePreparationGuard(
|
||||
!!reason || uncertain,
|
||||
'Existe um fundamento preparado ou uma instalação sem confirmação. Sair desta página?',
|
||||
);
|
||||
return {
|
||||
plan,
|
||||
base,
|
||||
reason,
|
||||
change,
|
||||
confirmed,
|
||||
setConfirmed,
|
||||
busy,
|
||||
refreshing,
|
||||
uncertain,
|
||||
message,
|
||||
error,
|
||||
stale,
|
||||
refresh,
|
||||
send,
|
||||
adopt,
|
||||
canAdopt:
|
||||
valid &&
|
||||
!busy &&
|
||||
!refreshing &&
|
||||
!pending.current &&
|
||||
!blocked &&
|
||||
stale,
|
||||
canRetry:
|
||||
valid &&
|
||||
plan.mfa_confirmed &&
|
||||
!busy &&
|
||||
!refreshing &&
|
||||
!blocked &&
|
||||
!!pending.current,
|
||||
canSend:
|
||||
valid &&
|
||||
!blocked &&
|
||||
!busy &&
|
||||
!refreshing &&
|
||||
!needsRefresh &&
|
||||
!stale &&
|
||||
!uncertain &&
|
||||
confirmed &&
|
||||
plan.ready &&
|
||||
!plan.installed &&
|
||||
plan.mfa_confirmed &&
|
||||
(plan.consistent || plan.repairable),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
import { router } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { portalRequest, PortalApiError } from './portal-api';
|
||||
import { createOperationKey } from './operation-key';
|
||||
export type HandlingState = {
|
||||
version: number;
|
||||
status: 'open' | 'in_progress' | 'resolved';
|
||||
assignee_user_id: number | null;
|
||||
assignee_name: string | null;
|
||||
updated_at: string | null;
|
||||
resolved_at: string | null;
|
||||
};
|
||||
export type Incident = {
|
||||
reference: string;
|
||||
operation: string;
|
||||
observed_version: number;
|
||||
occurred_at: string;
|
||||
error_code: string;
|
||||
handling: HandlingState;
|
||||
};
|
||||
export type Command = 'claim' | 'release' | 'note' | 'resolve' | 'reopen';
|
||||
export type HandlingProps = {
|
||||
incident: Incident;
|
||||
actorId: number;
|
||||
commands: { key: string; version: number }[];
|
||||
};
|
||||
type Attempt = {
|
||||
values: {
|
||||
version: number;
|
||||
action: Command;
|
||||
note: string;
|
||||
operation_key: string;
|
||||
};
|
||||
generation: number;
|
||||
};
|
||||
const object = (v: unknown): v is Record<string, unknown> =>
|
||||
!!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const integer = (v: unknown, min = 0): v is number =>
|
||||
typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
|
||||
const validState = (v: unknown): v is HandlingState =>
|
||||
object(v) &&
|
||||
integer(v.version) &&
|
||||
['open', 'in_progress', 'resolved'].includes(String(v.status)) &&
|
||||
(v.assignee_user_id === null || integer(v.assignee_user_id, 1)) &&
|
||||
(v.assignee_name === null || typeof v.assignee_name === 'string') &&
|
||||
(v.updated_at === null || typeof v.updated_at === 'string') &&
|
||||
(v.resolved_at === null || typeof v.resolved_at === 'string');
|
||||
export function useTechnicalIncidentHandling(props: HandlingProps) {
|
||||
const { incident, actorId, commands } = props;
|
||||
const [note, setNote] = useState(''),
|
||||
[base, setBase] = useState(() => ({ ...incident.handling })),
|
||||
[busy, setBusy] = useState(false),
|
||||
[uncertain, setUncertain] = useState(false),
|
||||
[refreshing, setRefreshing] = useState(false),
|
||||
[blocked, setBlocked] = useState(false),
|
||||
[needsRefresh, setNeedsRefresh] = useState(false),
|
||||
[notice, setNotice] = useState(''),
|
||||
[error, setError] = useState('');
|
||||
const pending = useRef<Attempt | null>(null),
|
||||
activeRequest = useRef<Attempt | null>(null),
|
||||
liveNote = useRef(note),
|
||||
generation = useRef(0),
|
||||
confirmed = useRef<number | null>(null),
|
||||
alive = useRef(true),
|
||||
origin = useRef({ actorId, reference: incident.reference }),
|
||||
scope = useRef({ actorId, reference: incident.reference });
|
||||
if (
|
||||
scope.current.actorId !== actorId ||
|
||||
scope.current.reference !== incident.reference
|
||||
)
|
||||
scope.current = { actorId, reference: incident.reference };
|
||||
liveNote.current = note;
|
||||
const valid =
|
||||
integer(actorId, 1) &&
|
||||
actorId === origin.current.actorId &&
|
||||
incident.reference === origin.current.reference &&
|
||||
validState(incident.handling) &&
|
||||
Array.isArray(commands) &&
|
||||
commands.every(
|
||||
(item) => typeof item.key === 'string' && integer(item.version, 1),
|
||||
);
|
||||
const stale = base.version !== incident.handling.version;
|
||||
function change(value: string) {
|
||||
generation.current++;
|
||||
liveNote.current = value;
|
||||
setNote(value);
|
||||
setError('');
|
||||
}
|
||||
function acknowledge(attempt: Attempt, version: number) {
|
||||
if (pending.current !== attempt) return;
|
||||
pending.current = null;
|
||||
activeRequest.current = null;
|
||||
setBusy(false);
|
||||
setUncertain(false);
|
||||
setNeedsRefresh(true);
|
||||
confirmed.current = version;
|
||||
if (generation.current === attempt.generation) {
|
||||
liveNote.current = '';
|
||||
setNote('');
|
||||
}
|
||||
setNotice(
|
||||
'Tratamento registado. As alterações posteriores da nota foram conservadas.',
|
||||
);
|
||||
setError('');
|
||||
}
|
||||
function read(value: unknown) {
|
||||
if (
|
||||
!object(value) ||
|
||||
value.actorId !== actorId ||
|
||||
!object(value.incident) ||
|
||||
value.incident.reference !== incident.reference ||
|
||||
!validState(value.incident.handling) ||
|
||||
!Array.isArray(value.commands)
|
||||
)
|
||||
return false;
|
||||
const attempt = pending.current;
|
||||
if (
|
||||
attempt &&
|
||||
value.commands.some(
|
||||
(c) =>
|
||||
object(c) &&
|
||||
c.key === attempt.values.operation_key &&
|
||||
c.version === attempt.values.version + 1,
|
||||
) &&
|
||||
value.incident.handling.version >= attempt.values.version + 1
|
||||
)
|
||||
acknowledge(attempt, attempt.values.version + 1);
|
||||
if (confirmed.current !== null) {
|
||||
if (value.incident.handling.version === confirmed.current)
|
||||
setBase({ ...value.incident.handling });
|
||||
if (value.incident.handling.version >= confirmed.current) {
|
||||
confirmed.current = null;
|
||||
setNeedsRefresh(false);
|
||||
}
|
||||
}
|
||||
setBlocked(false);
|
||||
return true;
|
||||
}
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (valid) read(props);
|
||||
}, [incident, commands, actorId]);
|
||||
function refresh() {
|
||||
if (refreshing) return;
|
||||
const epoch = scope.current;
|
||||
setRefreshing(true);
|
||||
router.reload({
|
||||
only: ['incident', 'history', 'commands', 'actorId'],
|
||||
onSuccess: (page) => {
|
||||
if (
|
||||
alive.current &&
|
||||
scope.current === epoch &&
|
||||
!read(page.props)
|
||||
)
|
||||
setError(
|
||||
'Não foi possível confirmar esta consulta. A nota preparada foi conservada.',
|
||||
);
|
||||
},
|
||||
onError: () => {
|
||||
if (alive.current && scope.current === epoch)
|
||||
setError(
|
||||
'Não foi possível actualizar o incidente. A nota foi conservada.',
|
||||
);
|
||||
},
|
||||
onFinish: () => {
|
||||
if (alive.current && scope.current === epoch)
|
||||
setRefreshing(false);
|
||||
},
|
||||
});
|
||||
}
|
||||
async function send(action: Command, retry = false) {
|
||||
if (
|
||||
!valid ||
|
||||
blocked ||
|
||||
refreshing ||
|
||||
activeRequest.current ||
|
||||
(!retry && (stale || needsRefresh || pending.current))
|
||||
)
|
||||
return;
|
||||
let attempt = pending.current;
|
||||
if (!attempt) {
|
||||
if (
|
||||
liveNote.current.trim().length < 10 ||
|
||||
liveNote.current.length > 3000
|
||||
) {
|
||||
setError('Preencha uma nota com 10 a 3000 caracteres.');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
attempt = {
|
||||
values: {
|
||||
version: base.version,
|
||||
action,
|
||||
note: liveNote.current,
|
||||
operation_key: createOperationKey().toLowerCase(),
|
||||
},
|
||||
generation: generation.current,
|
||||
};
|
||||
} catch (e) {
|
||||
setError(
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Não foi possível preparar o registo.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
pending.current = attempt;
|
||||
}
|
||||
const epoch = scope.current;
|
||||
activeRequest.current = attempt;
|
||||
setBusy(true);
|
||||
setUncertain(true);
|
||||
setError('');
|
||||
try {
|
||||
const result = await portalRequest<unknown>(
|
||||
`/suporte-tecnico/incidentes/${incident.reference}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(attempt.values),
|
||||
},
|
||||
);
|
||||
if (
|
||||
!alive.current ||
|
||||
scope.current !== epoch ||
|
||||
pending.current !== attempt
|
||||
)
|
||||
return;
|
||||
if (
|
||||
!object(result) ||
|
||||
result.reference !== incident.reference ||
|
||||
result.actor_id !== actorId ||
|
||||
result.operation_key !== attempt.values.operation_key ||
|
||||
result.result_version !== attempt.values.version + 1 ||
|
||||
!validState(result.handling) ||
|
||||
result.handling.version < result.result_version
|
||||
)
|
||||
throw new Error(
|
||||
'A confirmação recebida não corresponde a esta tentativa. Actualize o incidente.',
|
||||
);
|
||||
acknowledge(attempt, result.result_version);
|
||||
refresh();
|
||||
} catch (e) {
|
||||
if (
|
||||
!alive.current ||
|
||||
scope.current !== epoch ||
|
||||
pending.current !== attempt
|
||||
)
|
||||
return;
|
||||
if (e instanceof PortalApiError && e.status === 422) {
|
||||
pending.current = null;
|
||||
setUncertain(false);
|
||||
setError(
|
||||
e.errors.note?.join(' ') ||
|
||||
'Este tratamento não pode ser aplicado ao estado actual. Actualize os dados e reveja a nota.',
|
||||
);
|
||||
} else if (
|
||||
e instanceof PortalApiError &&
|
||||
(e.status === 403 || e.status === 401 || e.status === 419)
|
||||
) {
|
||||
setBlocked(true);
|
||||
setError(
|
||||
'O acesso ou a sessão precisam de confirmação. A nota e a tentativa original foram conservadas.',
|
||||
);
|
||||
} else
|
||||
setError(
|
||||
e instanceof PortalApiError && e.status === 409
|
||||
? 'O incidente mudou. Actualize e compare o estado antes de preparar outra tentativa.'
|
||||
: e instanceof Error
|
||||
? e.message
|
||||
: 'Resultado sem confirmação. Conserve a tentativa original.',
|
||||
);
|
||||
} finally {
|
||||
if (
|
||||
alive.current &&
|
||||
scope.current === epoch &&
|
||||
activeRequest.current === attempt
|
||||
) {
|
||||
activeRequest.current = null;
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
function adopt() {
|
||||
if (!valid || !stale || busy || refreshing || needsRefresh || blocked)
|
||||
return;
|
||||
const attempt = pending.current;
|
||||
if (attempt) {
|
||||
if (
|
||||
incident.handling.version <= attempt.values.version ||
|
||||
commands.some((c) => c.key === attempt.values.operation_key)
|
||||
)
|
||||
return;
|
||||
pending.current = null;
|
||||
setUncertain(false);
|
||||
}
|
||||
setBase({ ...incident.handling });
|
||||
setError('');
|
||||
setNotice(
|
||||
'Estado actual confirmado. Reveja a nota conservada antes de a enviar.',
|
||||
);
|
||||
}
|
||||
const guard = useRef(false);
|
||||
guard.current = !!note || uncertain;
|
||||
useEffect(() => {
|
||||
const remove = router.on('before', (event) => {
|
||||
if (
|
||||
guard.current &&
|
||||
event.detail.visit.method === 'get' &&
|
||||
!event.detail.visit.preserveState &&
|
||||
!window.confirm(
|
||||
'Existe uma nota preparada ou um envio sem confirmação. Sair desta página?',
|
||||
)
|
||||
)
|
||||
event.preventDefault();
|
||||
});
|
||||
const unload = (event: BeforeUnloadEvent) => {
|
||||
if (guard.current) {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
}
|
||||
};
|
||||
window.addEventListener('beforeunload', unload);
|
||||
return () => {
|
||||
remove();
|
||||
window.removeEventListener('beforeunload', unload);
|
||||
};
|
||||
}, []);
|
||||
return {
|
||||
note,
|
||||
change,
|
||||
base,
|
||||
stale,
|
||||
busy,
|
||||
uncertain,
|
||||
refreshing,
|
||||
notice,
|
||||
error,
|
||||
refresh,
|
||||
send,
|
||||
adopt,
|
||||
blocked:
|
||||
!valid ||
|
||||
blocked ||
|
||||
busy ||
|
||||
refreshing ||
|
||||
needsRefresh ||
|
||||
stale ||
|
||||
uncertain,
|
||||
canRetry:
|
||||
valid && !blocked && !busy && !refreshing && !!pending.current,
|
||||
canAdopt:
|
||||
valid &&
|
||||
!blocked &&
|
||||
!busy &&
|
||||
!refreshing &&
|
||||
!needsRefresh &&
|
||||
stale &&
|
||||
(!pending.current ||
|
||||
incident.handling.version > pending.current.values.version),
|
||||
pendingAction: pending.current?.values.action,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { Command } from './technical-incident-handling';
|
||||
export const incidentOperationLabels: Record<string, string> = {
|
||||
submit: 'Submissão para validação',
|
||||
publish: 'Publicação',
|
||||
upload_document: 'Carregamento de documento',
|
||||
upload_image: 'Carregamento de imagem',
|
||||
prepare_image: 'Preparação de imagens WebP',
|
||||
scan_document: 'Análise de segurança de documento',
|
||||
};
|
||||
export function incidentOperationLabel(operation: string) {
|
||||
return (
|
||||
incidentOperationLabels[operation] ||
|
||||
'Operação técnica não identificada'
|
||||
);
|
||||
}
|
||||
export function incidentErrorLabel(code: string) {
|
||||
return (
|
||||
(
|
||||
{
|
||||
database_failure:
|
||||
'Falha no serviço de dados durante a operação.',
|
||||
workflow_unavailable: 'Falha técnica durante a operação.',
|
||||
scan_dispatch_unconfirmed:
|
||||
'Encaminhamento da análise sem confirmação.',
|
||||
scan_inconclusive: 'Análise de segurança inconclusiva.',
|
||||
scan_worker_failed:
|
||||
'Falha na execução da análise de segurança.',
|
||||
scan_cleanup_unconfirmed:
|
||||
'Limpeza do ficheiro temporário por confirmar.',
|
||||
} as Record<string, string>
|
||||
)[code] || 'Falha técnica durante a operação.'
|
||||
);
|
||||
}
|
||||
export const handlingLabels: Record<string, string> = {
|
||||
open: 'Na fila',
|
||||
in_progress: 'Em tratamento',
|
||||
resolved: 'Resolvido',
|
||||
};
|
||||
export const commandLabels: Record<Command, string> = {
|
||||
claim: 'Assumir tratamento',
|
||||
release: 'Devolver à fila',
|
||||
note: 'Acrescentar nota',
|
||||
resolve: 'Resolver incidente',
|
||||
reopen: 'Reabrir incidente',
|
||||
};
|
||||
@@ -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'}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user