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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user