feat: consolidar desenvolvimentos do portal InvestMoz
This commit is contained in:
@@ -5,6 +5,58 @@ export type BusinessLocationPath = {
|
||||
locality_id: string;
|
||||
};
|
||||
|
||||
export function businessPointTerritoryKey(path: BusinessLocationPath): string {
|
||||
return [
|
||||
path.province_id,
|
||||
path.district_id,
|
||||
path.admin_post_id,
|
||||
path.locality_id,
|
||||
].join('|');
|
||||
}
|
||||
|
||||
export function businessPointTerritoryLabel(
|
||||
payload: Record<string, string | undefined>,
|
||||
paths: string[][] = [],
|
||||
): string {
|
||||
const index =
|
||||
payload.geography_scope === 'specific'
|
||||
? 0
|
||||
: decodeBusinessLocations(payload.locations_json).findIndex(
|
||||
(path) =>
|
||||
businessPointTerritoryKey(path) ===
|
||||
payload.location_point_territory,
|
||||
);
|
||||
return paths[index]?.join(' / ') || 'Localização por reconciliar';
|
||||
}
|
||||
|
||||
export function businessPointApplicable(
|
||||
payload: Record<string, string | undefined>,
|
||||
): boolean {
|
||||
return (
|
||||
payload.location_point_enabled === 'yes' &&
|
||||
['specific', 'multiple'].includes(payload.geography_scope ?? '') &&
|
||||
payload.disclosure_precision === 'exact' &&
|
||||
payload.location_unknown === 'no'
|
||||
);
|
||||
}
|
||||
|
||||
export function businessPointRequiredFields(
|
||||
payload: Record<string, string | undefined>,
|
||||
): Set<string> {
|
||||
if (!businessPointApplicable(payload)) return new Set();
|
||||
return new Set([
|
||||
'location_latitude',
|
||||
'location_longitude',
|
||||
'location_point_source_mode',
|
||||
...(payload.geography_scope === 'multiple'
|
||||
? ['location_point_territory']
|
||||
: []),
|
||||
...(payload.location_point_source_mode === 'custom'
|
||||
? ['location_point_source_reference']
|
||||
: []),
|
||||
]);
|
||||
}
|
||||
|
||||
export const emptyBusinessLocation = (): BusinessLocationPath => ({
|
||||
province_id: '',
|
||||
district_id: '',
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
export type CompanyAnswers = Record<string, string>;
|
||||
export function companyComparisonUrl(
|
||||
base: string,
|
||||
answers: CompanyAnswers,
|
||||
field = 'answers',
|
||||
): string {
|
||||
return (
|
||||
base +
|
||||
'?' +
|
||||
new URLSearchParams(
|
||||
Object.entries(answers).map(([key, value]) => [
|
||||
`${field}[${key}]`,
|
||||
value,
|
||||
]),
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
export type Party = {
|
||||
id: string;
|
||||
name: string | null;
|
||||
kind: 'person' | 'entity';
|
||||
source: string | null;
|
||||
roles: string[];
|
||||
represented_id: string | null;
|
||||
cash: string | null;
|
||||
in_kind: string | null;
|
||||
paid: string | null;
|
||||
share_count: string | null;
|
||||
work: string | null;
|
||||
commitment: string | null;
|
||||
source_snapshot?: {
|
||||
origin: string;
|
||||
reference: string;
|
||||
version: string | number | null;
|
||||
};
|
||||
};
|
||||
export type CompanyFacts = {
|
||||
form: string | null;
|
||||
proposed_name: string | null;
|
||||
seat: string | null;
|
||||
activities: string | null;
|
||||
regulated: string;
|
||||
currency: string | null;
|
||||
capital: string | null;
|
||||
nominal_value: string | null;
|
||||
management: string | null;
|
||||
binding: string | null;
|
||||
notes: string | null;
|
||||
parties: Party[];
|
||||
};
|
||||
|
||||
/** Read actual form values, including autofill, without serializing private provenance. */
|
||||
export function preparationValues(
|
||||
form: HTMLFormElement,
|
||||
facts: CompanyFacts,
|
||||
): CompanyFacts {
|
||||
const data = new FormData(form);
|
||||
const value = (key: string, fallback: string | null) => {
|
||||
const v = data.get(key);
|
||||
return typeof v === 'string' ? v.trim() || null : fallback;
|
||||
};
|
||||
return {
|
||||
form: value('form', facts.form),
|
||||
proposed_name: value('proposed_name', facts.proposed_name),
|
||||
seat: value('seat', facts.seat),
|
||||
activities: value('activities', facts.activities),
|
||||
regulated: value('regulated', facts.regulated) ?? 'unknown',
|
||||
currency: value('currency', facts.currency),
|
||||
capital: value('capital', facts.capital),
|
||||
nominal_value: value('nominal_value', facts.nominal_value),
|
||||
management: value('management', facts.management),
|
||||
binding: value('binding', facts.binding),
|
||||
notes: value('notes', facts.notes),
|
||||
parties: facts.parties.map((p) => ({
|
||||
id: p.id,
|
||||
name: value(`${p.id}.name`, p.name),
|
||||
kind: p.kind,
|
||||
source: p.source,
|
||||
roles: p.roles,
|
||||
represented_id: p.represented_id,
|
||||
cash: value(`${p.id}.cash`, p.cash),
|
||||
in_kind: value(`${p.id}.in_kind`, p.in_kind),
|
||||
paid: value(`${p.id}.paid`, p.paid),
|
||||
share_count: value(`${p.id}.share_count`, p.share_count),
|
||||
work: value(`${p.id}.work`, p.work),
|
||||
commitment: value(`${p.id}.commitment`, p.commitment),
|
||||
})),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { useRef, useState } from 'react';
|
||||
|
||||
type Values = Record<string, string>;
|
||||
type Kind = 'investor' | 'contact' | 'lead' | 'task';
|
||||
function object(value: unknown): value is Record<string, unknown> {
|
||||
return !!value && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
function savedRecord(
|
||||
props: Record<string, unknown>,
|
||||
kind: Kind,
|
||||
id: string,
|
||||
): Record<string, unknown> | null {
|
||||
let candidate: unknown = kind === 'investor' ? props.investor : props.lead;
|
||||
if (kind === 'contact')
|
||||
candidate = Array.isArray(props.contacts)
|
||||
? props.contacts.find((value) => object(value) && value.id === id)
|
||||
: null;
|
||||
if (kind === 'task')
|
||||
candidate =
|
||||
object(props.lead) && Array.isArray(props.lead.tasks)
|
||||
? props.lead.tasks.find(
|
||||
(value) => object(value) && value.id === id,
|
||||
)
|
||||
: null;
|
||||
return object(candidate) && candidate.id === id ? candidate : null;
|
||||
}
|
||||
|
||||
/** Keeps deliberate edits, including a deliberate return to the original value. */
|
||||
export function useCrmRecordEdit({
|
||||
id,
|
||||
kind,
|
||||
version,
|
||||
values,
|
||||
blankAfterSave = [],
|
||||
}: {
|
||||
id: string;
|
||||
kind: Kind;
|
||||
version: number;
|
||||
values: Values;
|
||||
blankAfterSave?: string[];
|
||||
}) {
|
||||
const form = useForm({ version, values });
|
||||
const live = useRef(form.data);
|
||||
live.current = form.data;
|
||||
const identity = useRef(id);
|
||||
identity.current = id;
|
||||
const base = useRef({ id, version, values: { ...values } });
|
||||
const edited = useRef(new Set<string>());
|
||||
const generation = useRef<Record<string, number>>({});
|
||||
const [choices, setChoices] = useState<Record<string, 'mine' | 'current'>>(
|
||||
{},
|
||||
);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const keys = Object.keys(values);
|
||||
const stale = version !== form.data.version;
|
||||
const changed = keys.filter(
|
||||
(key) => values[key] !== base.current.values[key],
|
||||
);
|
||||
const conflicts = changed.filter(
|
||||
(key) =>
|
||||
edited.current.has(key) && form.data.values[key] !== values[key],
|
||||
);
|
||||
const unresolved = conflicts.filter(
|
||||
(key) => choices[`${version}:${key}`] !== 'mine',
|
||||
);
|
||||
const invalid =
|
||||
base.current.id !== id || !Number.isInteger(version) || version < 1;
|
||||
|
||||
function change(key: string, value: string) {
|
||||
if (!keys.includes(key)) return;
|
||||
edited.current.add(key);
|
||||
generation.current[key] = (generation.current[key] ?? 0) + 1;
|
||||
setChoices((previous) => {
|
||||
const next = { ...previous };
|
||||
delete next[`${version}:${key}`];
|
||||
return next;
|
||||
});
|
||||
live.current = {
|
||||
...live.current,
|
||||
values: { ...live.current.values, [key]: value },
|
||||
};
|
||||
form.setData((previous) => ({
|
||||
...previous,
|
||||
values: { ...previous.values, [key]: value },
|
||||
}));
|
||||
}
|
||||
function choose(key: string, choice: 'mine' | 'current') {
|
||||
if (choice === 'current') change(key, values[key]);
|
||||
setChoices((previous) => ({
|
||||
...previous,
|
||||
[`${version}:${key}`]: choice,
|
||||
}));
|
||||
}
|
||||
function adopt() {
|
||||
if (!stale || invalid || refreshing || unresolved.length) return;
|
||||
const next = Object.fromEntries(
|
||||
keys.map((key) => [
|
||||
key,
|
||||
edited.current.has(key)
|
||||
? live.current.values[key]
|
||||
: values[key],
|
||||
]),
|
||||
);
|
||||
base.current = { id, version, values: { ...values } };
|
||||
live.current = { version, values: next };
|
||||
form.setData(live.current);
|
||||
form.clearErrors('version');
|
||||
setChoices({});
|
||||
}
|
||||
function refresh() {
|
||||
if (refreshing || form.processing) return;
|
||||
setRefreshing(true);
|
||||
router.reload({
|
||||
only:
|
||||
kind === 'lead' || kind === 'task'
|
||||
? ['lead', 'owners', 'taskCreation', 'nextAction']
|
||||
: ['investor', 'contacts'],
|
||||
onFinish: () => setRefreshing(false),
|
||||
});
|
||||
}
|
||||
const blocked = invalid || stale || refreshing || !!form.errors.version;
|
||||
function submit(url: string) {
|
||||
if (blocked || form.processing) return;
|
||||
const submitted = {
|
||||
...live.current.values,
|
||||
version: live.current.version,
|
||||
};
|
||||
const sentGeneration = { ...generation.current };
|
||||
form.transform(() => submitted);
|
||||
form.patch(url, {
|
||||
preserveScroll: true,
|
||||
onSuccess: (page) => {
|
||||
if (identity.current !== id) return;
|
||||
const record = savedRecord(page.props, kind, id);
|
||||
const actualVersion = record?.version_no;
|
||||
if (
|
||||
!record ||
|
||||
typeof actualVersion !== 'number' ||
|
||||
!Number.isInteger(actualVersion) ||
|
||||
actualVersion < 1
|
||||
)
|
||||
return;
|
||||
const next: Values = {};
|
||||
for (const key of keys) {
|
||||
const value = record[key];
|
||||
if (
|
||||
blankAfterSave.includes(key) ||
|
||||
value === null ||
|
||||
value === undefined
|
||||
)
|
||||
next[key] = '';
|
||||
else if (
|
||||
typeof value === 'string' ||
|
||||
typeof value === 'number'
|
||||
)
|
||||
next[key] = String(value);
|
||||
else return;
|
||||
}
|
||||
base.current = {
|
||||
id,
|
||||
version: actualVersion,
|
||||
values: { ...next },
|
||||
};
|
||||
edited.current.clear();
|
||||
const merged = { ...next };
|
||||
for (const key of keys) {
|
||||
if (
|
||||
(generation.current[key] ?? 0) !==
|
||||
(sentGeneration[key] ?? 0)
|
||||
) {
|
||||
merged[key] = live.current.values[key];
|
||||
edited.current.add(key);
|
||||
}
|
||||
}
|
||||
setChoices({});
|
||||
const saved = { version: actualVersion, values: next };
|
||||
form.setDefaults(saved);
|
||||
live.current = { version: actualVersion, values: merged };
|
||||
form.setData(live.current);
|
||||
form.clearErrors();
|
||||
},
|
||||
});
|
||||
}
|
||||
function error(key: string): string | undefined {
|
||||
const value = Object.entries(form.errors).find(
|
||||
([name]) => name === key,
|
||||
)?.[1];
|
||||
return typeof value === 'string' ? value : undefined;
|
||||
}
|
||||
return {
|
||||
form,
|
||||
values: form.data.values,
|
||||
current: values,
|
||||
version,
|
||||
baseVersion: form.data.version,
|
||||
changed,
|
||||
conflicts,
|
||||
unresolved,
|
||||
stale,
|
||||
refreshing,
|
||||
invalid,
|
||||
blocked,
|
||||
change,
|
||||
choose,
|
||||
adopt,
|
||||
refresh,
|
||||
submit,
|
||||
error,
|
||||
};
|
||||
}
|
||||
|
||||
export type CrmRecordEditor = ReturnType<typeof useCrmRecordEdit>;
|
||||
@@ -0,0 +1,371 @@
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { createOperationKey } from './operation-key';
|
||||
import type { Lead } from '@/pages/crm/types';
|
||||
import {
|
||||
useCrmTaskPreparation,
|
||||
taskDeadlineLocal,
|
||||
taskDeadlineUtc,
|
||||
} from './crm-task-preparation';
|
||||
import type {
|
||||
TaskPreparationView,
|
||||
TaskPreparationSnapshot,
|
||||
} from './crm-task-preparation';
|
||||
|
||||
export type TaskCreationContext = {
|
||||
lead_id: string;
|
||||
actor_id: number;
|
||||
commands: { key: string; task_id: string; version: number }[];
|
||||
preparation?: TaskPreparationView;
|
||||
};
|
||||
type Values = { title: string; due_at: string; assignee_user_id: string };
|
||||
type Attempt = {
|
||||
values: Values & { client_key: string };
|
||||
generation: Record<string, number>;
|
||||
};
|
||||
const object = (value: unknown): value is Record<string, unknown> =>
|
||||
!!value && typeof value === 'object' && !Array.isArray(value);
|
||||
const positive = (value: unknown): value is number =>
|
||||
typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
|
||||
|
||||
export function useCrmTaskCreation(lead: Lead, context: TaskCreationContext) {
|
||||
const form = useForm<Values>({
|
||||
title: '',
|
||||
due_at: '',
|
||||
assignee_user_id: String(lead.owner_user_id ?? ''),
|
||||
});
|
||||
const live = useRef(form.data);
|
||||
live.current = form.data;
|
||||
const blank = context.preparation?.snapshot;
|
||||
const sameBlank =
|
||||
blank?.pending === null &&
|
||||
blank.values?.title === '' &&
|
||||
blank.values?.due_at === '' &&
|
||||
blank.values?.assignee_user_id === String(lead.owner_user_id ?? '') &&
|
||||
Object.values(blank.generation ?? {}).length === 3 &&
|
||||
Object.values(blank.generation ?? {}).every(
|
||||
(value) => Number.isSafeInteger(value) && value >= 0,
|
||||
);
|
||||
const generation = useRef<Record<string, number>>(
|
||||
sameBlank ? { ...blank.generation } : {},
|
||||
);
|
||||
const pending = useRef<Attempt | null>(null);
|
||||
const submitted = useRef<string | null>(null);
|
||||
const recoveredDeadline = useRef<{ local: string; utc: string } | null>(
|
||||
null,
|
||||
);
|
||||
const alive = useRef(true);
|
||||
const [waiting, setWaiting] = useState(false);
|
||||
const [blocked, setBlocked] = useState(false);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [notice, setNotice] = useState('');
|
||||
const valid =
|
||||
context.lead_id === lead.id &&
|
||||
positive(context.actor_id) &&
|
||||
Array.isArray(context.commands);
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (generation.current.assignee_user_id) return;
|
||||
const assignee_user_id = String(lead.owner_user_id ?? '');
|
||||
live.current = { ...live.current, assignee_user_id };
|
||||
form.setData(live.current);
|
||||
}, [lead.owner_user_id]);
|
||||
|
||||
function change(key: keyof Values, value: string) {
|
||||
if (key === 'due_at') recoveredDeadline.current = null;
|
||||
generation.current[key] = (generation.current[key] ?? 0) + 1;
|
||||
live.current = { ...live.current, [key]: value };
|
||||
form.setData(live.current);
|
||||
}
|
||||
function scoped(props: unknown): props is Record<string, unknown> & {
|
||||
taskCreation: TaskCreationContext;
|
||||
} {
|
||||
return (
|
||||
object(props) &&
|
||||
object(props.lead) &&
|
||||
props.lead.id === lead.id &&
|
||||
object(props.taskCreation) &&
|
||||
props.taskCreation.lead_id === lead.id &&
|
||||
props.taskCreation.actor_id === context.actor_id &&
|
||||
Array.isArray(props.taskCreation.commands)
|
||||
);
|
||||
}
|
||||
function acknowledge(props: unknown) {
|
||||
const attempt = pending.current;
|
||||
if (!alive.current || !attempt || !scoped(props)) return false;
|
||||
const receipt = props.taskCreation.commands.find(
|
||||
(item: unknown) =>
|
||||
object(item) && item.key === attempt.values.client_key,
|
||||
);
|
||||
if (
|
||||
!receipt ||
|
||||
typeof receipt.task_id !== 'string' ||
|
||||
!positive(receipt.version)
|
||||
)
|
||||
return false;
|
||||
const task =
|
||||
object(props.lead) && Array.isArray(props.lead.tasks)
|
||||
? props.lead.tasks.find(
|
||||
(item: unknown) =>
|
||||
object(item) && item.id === receipt.task_id,
|
||||
)
|
||||
: null;
|
||||
if (
|
||||
task &&
|
||||
(!positive(task.version_no) ||
|
||||
task.version_no < receipt.version ||
|
||||
(task.version_no === receipt.version &&
|
||||
(task.title !== attempt.values.title.trim() ||
|
||||
task.assignee_user_id !==
|
||||
Number(attempt.values.assignee_user_id) ||
|
||||
new Date(task.due_at).getTime() !==
|
||||
new Date(attempt.values.due_at).getTime())))
|
||||
)
|
||||
return false;
|
||||
const next = { ...live.current };
|
||||
for (const key of ['title', 'due_at'] as const) {
|
||||
if (
|
||||
(generation.current[key] ?? 0) ===
|
||||
(attempt.generation[key] ?? 0)
|
||||
)
|
||||
next[key] = '';
|
||||
}
|
||||
live.current = next;
|
||||
form.setData(next);
|
||||
form.clearErrors();
|
||||
pending.current = null;
|
||||
setWaiting(false);
|
||||
setBlocked(false);
|
||||
setNotice(
|
||||
task
|
||||
? 'Tarefa registada. As alterações posteriores ao envio foram conservadas.'
|
||||
: 'A criação já foi registada. A tarefa já não está disponível neste lead; consulte o histórico antes de criar outra.',
|
||||
);
|
||||
return true;
|
||||
}
|
||||
function capture(): TaskPreparationSnapshot {
|
||||
return {
|
||||
values: {
|
||||
...live.current,
|
||||
due_at:
|
||||
recoveredDeadline.current?.local === live.current.due_at
|
||||
? recoveredDeadline.current.utc
|
||||
: taskDeadlineUtc(live.current.due_at),
|
||||
},
|
||||
generation: {
|
||||
title: generation.current.title ?? 0,
|
||||
due_at: generation.current.due_at ?? 0,
|
||||
assignee_user_id: generation.current.assignee_user_id ?? 0,
|
||||
},
|
||||
pending: pending.current
|
||||
? {
|
||||
values: { ...pending.current.values },
|
||||
generation: {
|
||||
title: pending.current.generation.title ?? 0,
|
||||
due_at: pending.current.generation.due_at ?? 0,
|
||||
assignee_user_id:
|
||||
pending.current.generation.assignee_user_id ?? 0,
|
||||
},
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
const preparation = useCrmTaskPreparation({
|
||||
leadId: lead.id,
|
||||
actorId: context.actor_id,
|
||||
view: context.preparation,
|
||||
getSnapshot: capture,
|
||||
onRecover: (snapshot) => {
|
||||
if (
|
||||
pending.current &&
|
||||
submitted.current === pending.current.values.client_key &&
|
||||
pending.current.values.client_key !==
|
||||
snapshot.pending?.values.client_key
|
||||
)
|
||||
return false;
|
||||
generation.current = { ...snapshot.generation };
|
||||
generation.current.assignee_user_id = Math.max(
|
||||
1,
|
||||
snapshot.generation.assignee_user_id,
|
||||
);
|
||||
live.current = {
|
||||
...snapshot.values,
|
||||
due_at: taskDeadlineLocal(snapshot.values.due_at),
|
||||
};
|
||||
recoveredDeadline.current = {
|
||||
local: live.current.due_at,
|
||||
utc: snapshot.values.due_at,
|
||||
};
|
||||
form.setData(live.current);
|
||||
pending.current = snapshot.pending;
|
||||
submitted.current = snapshot.pending?.values.client_key ?? null;
|
||||
setWaiting(!!snapshot.pending);
|
||||
setBlocked(false);
|
||||
if (snapshot.pending) {
|
||||
if (!acknowledge({ lead, taskCreation: context }))
|
||||
setNotice(
|
||||
'Foi recuperado um envio sem confirmação. Recupere a mesma criação antes de iniciar outra.',
|
||||
);
|
||||
}
|
||||
return true;
|
||||
},
|
||||
});
|
||||
const canReplay =
|
||||
!!pending.current &&
|
||||
submitted.current === pending.current.values.client_key;
|
||||
function submit() {
|
||||
if (
|
||||
!valid ||
|
||||
blocked ||
|
||||
refreshing ||
|
||||
form.processing ||
|
||||
(preparation.blocked && !canReplay)
|
||||
)
|
||||
return;
|
||||
if (!pending.current) {
|
||||
let client_key: string;
|
||||
try {
|
||||
client_key = createOperationKey();
|
||||
} catch {
|
||||
setNotice(
|
||||
'Não foi possível preparar o envio. Reabra o portal no endereço HTTPS configurado.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
pending.current = {
|
||||
values: {
|
||||
...live.current,
|
||||
due_at: capture().values.due_at,
|
||||
client_key,
|
||||
},
|
||||
generation: { ...generation.current },
|
||||
};
|
||||
}
|
||||
const attempt = pending.current;
|
||||
setWaiting(true);
|
||||
if (canReplay || !preparation.enabled) send(attempt);
|
||||
else {
|
||||
setNotice('A guardar a preparação antes de criar a tarefa…');
|
||||
void preparation.ensure().then((saved) => {
|
||||
if (!alive.current || pending.current !== attempt) return;
|
||||
if (saved) send(attempt);
|
||||
else
|
||||
setNotice(
|
||||
'O envio ficou por confirmar. Volte a guardar a preparação antes de continuar.',
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
function send(attempt: Attempt) {
|
||||
submitted.current = attempt.values.client_key;
|
||||
setNotice('A aguardar confirmação da criação.');
|
||||
form.transform(() => attempt.values);
|
||||
form.post(`/management/crm/leads/${lead.id}/tasks`, {
|
||||
preserveScroll: true,
|
||||
onSuccess: (page) => {
|
||||
if (!alive.current || pending.current !== attempt) return;
|
||||
if (!acknowledge(page.props))
|
||||
setNotice(
|
||||
'A resposta não permitiu confirmar a criação. Actualize as tarefas ou recupere o mesmo envio.',
|
||||
);
|
||||
},
|
||||
onError: () => {
|
||||
if (!alive.current || pending.current !== attempt) return;
|
||||
pending.current = null;
|
||||
setWaiting(false);
|
||||
setNotice(
|
||||
'Reveja os campos assinalados. As suas alterações foram conservadas.',
|
||||
);
|
||||
},
|
||||
onNetworkError: () => {
|
||||
if (alive.current && pending.current === attempt)
|
||||
setNotice(
|
||||
'Sem confirmação do envio. Recupere a mesma criação para evitar duplicar a tarefa.',
|
||||
);
|
||||
},
|
||||
onHttpException: (response) => {
|
||||
if (!alive.current || pending.current !== attempt) return;
|
||||
if ([401, 403, 404, 409, 419].includes(response.status))
|
||||
setBlocked(true);
|
||||
setNotice(
|
||||
'Não foi possível confirmar a criação. Actualize as tarefas e o acesso antes de continuar. As alterações foram conservadas.',
|
||||
);
|
||||
},
|
||||
onCancel: () => {
|
||||
if (alive.current && pending.current === attempt)
|
||||
setNotice(
|
||||
'Envio interrompido sem confirmação. Recupere a mesma criação.',
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
function refresh() {
|
||||
if (refreshing || form.processing) return;
|
||||
setRefreshing(true);
|
||||
router.reload({
|
||||
only: ['lead', 'owners', 'taskCreation', 'nextAction'],
|
||||
onSuccess: (page) => {
|
||||
if (!alive.current || !scoped(page.props)) return;
|
||||
setBlocked(false);
|
||||
if (pending.current && !acknowledge(page.props))
|
||||
setNotice(
|
||||
'A criação ainda não foi confirmada. Recupere o mesmo envio; as edições posteriores ficam para a próxima tarefa.',
|
||||
);
|
||||
},
|
||||
onFinish: () => {
|
||||
if (alive.current) setRefreshing(false);
|
||||
},
|
||||
});
|
||||
}
|
||||
const guard = useRef(false);
|
||||
guard.current =
|
||||
!preparation.durable &&
|
||||
(waiting ||
|
||||
!!form.data.title ||
|
||||
!!form.data.due_at ||
|
||||
(!!generation.current.assignee_user_id &&
|
||||
form.data.assignee_user_id !==
|
||||
String(lead.owner_user_id ?? '')));
|
||||
useEffect(() => {
|
||||
const remove = router.on('before', (event) => {
|
||||
const visit = event.detail.visit;
|
||||
if (
|
||||
guard.current &&
|
||||
visit.method === 'get' &&
|
||||
!visit.preserveState &&
|
||||
!window.confirm(
|
||||
'Existem alterações ou um envio por confirmar. Sair desta página?',
|
||||
)
|
||||
)
|
||||
event.preventDefault();
|
||||
});
|
||||
const unload = (event: BeforeUnloadEvent) => {
|
||||
if (guard.current) {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
}
|
||||
};
|
||||
window.addEventListener('beforeunload', unload);
|
||||
return () => {
|
||||
remove();
|
||||
window.removeEventListener('beforeunload', unload);
|
||||
};
|
||||
}, []);
|
||||
return {
|
||||
form,
|
||||
change,
|
||||
submit,
|
||||
refresh,
|
||||
waiting,
|
||||
blocked: blocked || !valid || (preparation.blocked && !canReplay),
|
||||
refreshing,
|
||||
notice,
|
||||
sent: pending.current?.values,
|
||||
preparation,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { profileJson, ProfileValidationError } from './profile-json';
|
||||
import { createOperationKey } from './operation-key';
|
||||
|
||||
export type TaskValues = {
|
||||
title: string;
|
||||
due_at: string;
|
||||
assignee_user_id: string;
|
||||
};
|
||||
export type TaskGeneration = Record<keyof TaskValues, number>;
|
||||
export type TaskAttempt = {
|
||||
values: TaskValues & { client_key: string };
|
||||
generation: TaskGeneration;
|
||||
};
|
||||
export type TaskPreparationSnapshot = {
|
||||
values: TaskValues;
|
||||
generation: TaskGeneration;
|
||||
pending: TaskAttempt | null;
|
||||
};
|
||||
export type TaskPreparationView = {
|
||||
installed: boolean;
|
||||
version: number;
|
||||
snapshot: TaskPreparationSnapshot | null;
|
||||
operation_key: string | null;
|
||||
unavailable: boolean;
|
||||
updated_at: string | null;
|
||||
};
|
||||
type Save = {
|
||||
version: number;
|
||||
operation_key: string;
|
||||
snapshot: TaskPreparationSnapshot;
|
||||
};
|
||||
const fields = ['title', 'due_at', 'assignee_user_id'] as const;
|
||||
const object = (value: unknown): value is Record<string, unknown> =>
|
||||
!!value && typeof value === 'object' && !Array.isArray(value);
|
||||
const integer = (value: unknown): value is number =>
|
||||
typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
|
||||
const values = (value: unknown): value is TaskValues =>
|
||||
object(value) && fields.every((field) => typeof value[field] === 'string');
|
||||
const generation = (value: unknown): value is TaskGeneration =>
|
||||
object(value) && fields.every((field) => integer(value[field]));
|
||||
function snapshot(value: unknown): value is TaskPreparationSnapshot {
|
||||
return (
|
||||
object(value) &&
|
||||
values(value.values) &&
|
||||
generation(value.generation) &&
|
||||
(value.pending === null ||
|
||||
(object(value.pending) &&
|
||||
object(value.pending.values) &&
|
||||
typeof value.pending.values.client_key === 'string' &&
|
||||
values(value.pending.values) &&
|
||||
generation(value.pending.generation)))
|
||||
);
|
||||
}
|
||||
function read(value: unknown): TaskPreparationView | null {
|
||||
return object(value) &&
|
||||
typeof value.installed === 'boolean' &&
|
||||
integer(value.version) &&
|
||||
typeof value.unavailable === 'boolean' &&
|
||||
(value.snapshot === null || snapshot(value.snapshot)) &&
|
||||
(value.operation_key === null ||
|
||||
typeof value.operation_key === 'string') &&
|
||||
(value.updated_at === null || typeof value.updated_at === 'string')
|
||||
? (value as TaskPreparationView)
|
||||
: null;
|
||||
}
|
||||
const signature = (value: TaskPreparationSnapshot) =>
|
||||
JSON.stringify({
|
||||
values: fields.map((field) => value.values[field]),
|
||||
generation: fields.map((field) => value.generation[field]),
|
||||
pending: value.pending
|
||||
? {
|
||||
values: [
|
||||
...fields.map((field) => value.pending?.values[field]),
|
||||
value.pending.values.client_key,
|
||||
],
|
||||
generation: fields.map(
|
||||
(field) => value.pending?.generation[field],
|
||||
),
|
||||
}
|
||||
: null,
|
||||
});
|
||||
export function taskDeadlineUtc(value: string): string {
|
||||
const date = new Date(value);
|
||||
return value && !Number.isNaN(date.getTime()) ? date.toISOString() : value;
|
||||
}
|
||||
export function taskDeadlineLocal(value: string): string {
|
||||
const date = new Date(value);
|
||||
return value && !Number.isNaN(date.getTime())
|
||||
? new Date(date.getTime() - date.getTimezoneOffset() * 60000)
|
||||
.toISOString()
|
||||
.slice(0, 16)
|
||||
: value;
|
||||
}
|
||||
|
||||
export function useCrmTaskPreparation({
|
||||
leadId,
|
||||
actorId,
|
||||
view,
|
||||
getSnapshot,
|
||||
onRecover,
|
||||
}: {
|
||||
leadId: string;
|
||||
actorId: number;
|
||||
view: unknown;
|
||||
getSnapshot: () => TaskPreparationSnapshot;
|
||||
onRecover: (value: TaskPreparationSnapshot) => boolean;
|
||||
}) {
|
||||
const incoming = read(view);
|
||||
const latest = useRef({ getSnapshot, onRecover });
|
||||
latest.current = { getSnapshot, onRecover };
|
||||
const alive = useRef(true),
|
||||
busy = useRef(false);
|
||||
const base = useRef(incoming);
|
||||
const initial = getSnapshot();
|
||||
const different =
|
||||
incoming?.snapshot &&
|
||||
(incoming.snapshot.pending !== null ||
|
||||
fields.some(
|
||||
(field) =>
|
||||
incoming.snapshot?.values[field] !== initial.values[field],
|
||||
));
|
||||
const saved = useRef(
|
||||
different && incoming.snapshot
|
||||
? signature(incoming.snapshot)
|
||||
: signature(initial),
|
||||
);
|
||||
const saveAttempt = useRef<Save | null>(null);
|
||||
const [comparison, setComparison] = useState<TaskPreparationView | null>(
|
||||
different ? incoming : null,
|
||||
);
|
||||
const [choices, setChoices] = useState<
|
||||
Partial<
|
||||
Record<
|
||||
keyof TaskValues,
|
||||
{ source: 'page' | 'saved'; generation: number }
|
||||
>
|
||||
>
|
||||
>({});
|
||||
const [state, setState] = useState<
|
||||
'ready' | 'saving' | 'error' | 'unavailable'
|
||||
>(incoming?.unavailable || (!!view && !incoming) ? 'unavailable' : 'ready');
|
||||
const [memoryOnly, setMemoryOnly] = useState(false);
|
||||
const [message, setMessage] = useState(
|
||||
incoming?.unavailable || (!!view && !incoming)
|
||||
? 'A preparação guardada não pôde ser lida. Actualize para recuperar o acesso ou continue só nesta página; os dados guardados ficam preservados.'
|
||||
: '',
|
||||
);
|
||||
const [, setTick] = useState(0);
|
||||
const current = getSnapshot(),
|
||||
currentSignature = signature(current);
|
||||
const enabled = !!incoming?.installed && !memoryOnly;
|
||||
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
};
|
||||
}, []);
|
||||
function response(value: unknown): TaskPreparationView | null {
|
||||
return object(value) &&
|
||||
value.lead_id === leadId &&
|
||||
value.actor_id === actorId
|
||||
? read(value.preparation)
|
||||
: null;
|
||||
}
|
||||
function confirmed(next: TaskPreparationView, attempt: Save) {
|
||||
if (
|
||||
next.version !== attempt.version + 1 ||
|
||||
next.operation_key !== attempt.operation_key ||
|
||||
!next.snapshot ||
|
||||
signature(next.snapshot) !== signature(attempt.snapshot)
|
||||
)
|
||||
return false;
|
||||
base.current = next;
|
||||
saved.current = signature(attempt.snapshot);
|
||||
saveAttempt.current = null;
|
||||
setState('ready');
|
||||
setMessage(
|
||||
'Preparação guardada no servidor. Pode retomá-la nesta conta.',
|
||||
);
|
||||
return true;
|
||||
}
|
||||
useEffect(() => {
|
||||
if (!incoming || !incoming.installed || memoryOnly || busy.current)
|
||||
return;
|
||||
if (saveAttempt.current && confirmed(incoming, saveAttempt.current))
|
||||
return;
|
||||
if (incoming.version > (base.current?.version ?? 0)) {
|
||||
setComparison(incoming);
|
||||
setChoices({});
|
||||
setMessage(
|
||||
'A preparação mudou. Compare antes de substituir os dados guardados.',
|
||||
);
|
||||
}
|
||||
}, [view, state, memoryOnly]);
|
||||
|
||||
async function ensure(forSubmission = true): Promise<boolean> {
|
||||
if (!enabled) return true;
|
||||
const now = latest.current.getSnapshot();
|
||||
if (
|
||||
forSubmission &&
|
||||
now.pending &&
|
||||
base.current?.snapshot?.pending?.values.client_key ===
|
||||
now.pending.values.client_key
|
||||
)
|
||||
return true;
|
||||
if (busy.current || comparison || state === 'unavailable') return false;
|
||||
if (!saveAttempt.current && signature(now) === saved.current)
|
||||
return true;
|
||||
let attempt = saveAttempt.current;
|
||||
if (!attempt) {
|
||||
try {
|
||||
attempt = {
|
||||
version: base.current?.version ?? 0,
|
||||
operation_key: createOperationKey(),
|
||||
snapshot: now,
|
||||
};
|
||||
} catch {
|
||||
setState('error');
|
||||
setMessage(
|
||||
'Não foi possível preparar a gravação. Reabra o portal no endereço HTTPS configurado.',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
saveAttempt.current = attempt;
|
||||
busy.current = true;
|
||||
setState('saving');
|
||||
setMessage('A guardar a preparação…');
|
||||
try {
|
||||
const result: unknown = await profileJson(
|
||||
`/management/crm/leads/${leadId}/task-preparation`,
|
||||
attempt,
|
||||
);
|
||||
if (!alive.current) return false;
|
||||
const next = response(result);
|
||||
if (!next || !confirmed(next, attempt))
|
||||
throw new Error('Unconfirmed preparation');
|
||||
// A previous automatic save may have preceded the creation attempt.
|
||||
const pending = latest.current.getSnapshot().pending;
|
||||
if (
|
||||
forSubmission &&
|
||||
pending &&
|
||||
next.snapshot?.pending?.values.client_key !==
|
||||
pending.values.client_key
|
||||
) {
|
||||
busy.current = false;
|
||||
return await ensure(true);
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (alive.current) {
|
||||
if (
|
||||
error instanceof ProfileValidationError &&
|
||||
Object.keys(error.fields).length
|
||||
)
|
||||
saveAttempt.current = null;
|
||||
setState('error');
|
||||
setMessage(
|
||||
error instanceof ProfileValidationError
|
||||
? Object.keys(error.fields).length
|
||||
? 'Reveja os campos da preparação antes de guardar. As alterações desta página foram conservadas.'
|
||||
: error.message
|
||||
: 'Não foi possível confirmar a preparação. Conserve esta página e volte a guardar ou actualize para comparar.',
|
||||
);
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
busy.current = false;
|
||||
if (alive.current) setTick((value) => value + 1);
|
||||
}
|
||||
}
|
||||
useEffect(() => {
|
||||
const hasWork =
|
||||
!!current.values.title ||
|
||||
!!current.values.due_at ||
|
||||
!!current.pending ||
|
||||
fields.some((field) => current.generation[field] > 0);
|
||||
if (
|
||||
!enabled ||
|
||||
state !== 'ready' ||
|
||||
comparison ||
|
||||
busy.current ||
|
||||
!hasWork ||
|
||||
currentSignature === saved.current
|
||||
)
|
||||
return;
|
||||
const timer = setTimeout(() => {
|
||||
void ensure(false);
|
||||
}, 800);
|
||||
return () => clearTimeout(timer);
|
||||
}, [currentSignature, enabled, state, comparison]);
|
||||
|
||||
const source = (field: keyof TaskValues) =>
|
||||
choices[field]?.source ??
|
||||
(current.generation[field] > 0 ? 'page' : 'saved');
|
||||
const unresolved = fields.filter(
|
||||
(field) =>
|
||||
choices[field]?.source === 'saved' &&
|
||||
choices[field]?.generation !== current.generation[field],
|
||||
);
|
||||
function choose(field: keyof TaskValues, value: 'page' | 'saved') {
|
||||
setChoices((previous) => ({
|
||||
...previous,
|
||||
[field]: {
|
||||
source: value,
|
||||
generation: latest.current.getSnapshot().generation[field],
|
||||
},
|
||||
}));
|
||||
}
|
||||
function recover() {
|
||||
if (
|
||||
!comparison?.snapshot ||
|
||||
comparison.unavailable ||
|
||||
busy.current ||
|
||||
unresolved.length
|
||||
)
|
||||
return;
|
||||
const now = latest.current.getSnapshot(),
|
||||
stored = comparison.snapshot;
|
||||
const next: TaskPreparationSnapshot = {
|
||||
values: { ...stored.values },
|
||||
generation: { ...stored.generation },
|
||||
pending: stored.pending,
|
||||
};
|
||||
for (const field of fields) {
|
||||
if (source(field) === 'page') {
|
||||
next.values[field] = now.values[field];
|
||||
next.generation[field] =
|
||||
Math.max(
|
||||
now.generation[field],
|
||||
stored.generation[field],
|
||||
stored.pending?.generation[field] ?? 0,
|
||||
) + 1;
|
||||
}
|
||||
}
|
||||
if (!latest.current.onRecover(next)) {
|
||||
setMessage(
|
||||
'Existe outro envio sem confirmação nesta página. Recupere esse envio antes de adoptar a preparação guardada.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
base.current = comparison;
|
||||
saved.current = signature(stored);
|
||||
saveAttempt.current = null;
|
||||
setComparison(null);
|
||||
setChoices({});
|
||||
setState('ready');
|
||||
setMessage(
|
||||
'Preparação recuperada. Compare os campos e confirme a acção pretendida.',
|
||||
);
|
||||
}
|
||||
return {
|
||||
enabled,
|
||||
state,
|
||||
comparison,
|
||||
current,
|
||||
source,
|
||||
unresolved,
|
||||
choose,
|
||||
recover,
|
||||
ensure,
|
||||
message,
|
||||
blocked:
|
||||
enabled &&
|
||||
(!!comparison ||
|
||||
state === 'unavailable' ||
|
||||
state === 'saving' ||
|
||||
state === 'error'),
|
||||
durable:
|
||||
enabled &&
|
||||
state === 'ready' &&
|
||||
!saveAttempt.current &&
|
||||
currentSignature === saved.current,
|
||||
manual: () => {
|
||||
setMemoryOnly(true);
|
||||
setComparison(null);
|
||||
setMessage(
|
||||
'Continua apenas nesta página. A preparação guardada no servidor foi preservada.',
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import type { DeskAnswer } from './desk-field-values';
|
||||
|
||||
export type DeskAnswers = Record<string, DeskAnswer>;
|
||||
export type CheckpointRequest = {
|
||||
id: string;
|
||||
version: number;
|
||||
status: string;
|
||||
payload: DeskAnswers;
|
||||
editable_fields: string[];
|
||||
can_edit: boolean;
|
||||
protocol: string | null;
|
||||
analyst_id: number | null;
|
||||
due_at: string | null;
|
||||
};
|
||||
export type CheckpointInput = {
|
||||
version: number;
|
||||
request_version: number;
|
||||
operation_key: string;
|
||||
payload: DeskAnswers;
|
||||
edited_keys: string[];
|
||||
reason: string;
|
||||
};
|
||||
export type DeskCheckpoint = {
|
||||
version: number;
|
||||
request_version: number;
|
||||
updated_at: string;
|
||||
payload: DeskAnswers;
|
||||
base_payload: DeskAnswers;
|
||||
edited_keys: string[];
|
||||
reason: string;
|
||||
};
|
||||
export type CheckpointView = {
|
||||
installed: boolean;
|
||||
request: CheckpointRequest;
|
||||
checkpoint: DeskCheckpoint | null;
|
||||
};
|
||||
export type RecoveryChoice = 'page' | 'saved' | 'current';
|
||||
|
||||
export function checkpointSignature(values: DeskAnswers): string {
|
||||
return JSON.stringify(
|
||||
Object.fromEntries(
|
||||
Object.entries(values)
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.map(([key, value]) => [
|
||||
key,
|
||||
Array.isArray(value) ? [...value].sort() : (value ?? null),
|
||||
]),
|
||||
),
|
||||
);
|
||||
}
|
||||
export const checkpointSame = (
|
||||
a: DeskAnswer | undefined,
|
||||
b: DeskAnswer | undefined,
|
||||
) =>
|
||||
checkpointSignature({ value: a ?? null }) ===
|
||||
checkpointSignature({ value: b ?? null });
|
||||
|
||||
const contextKeys = [
|
||||
'context_opportunity',
|
||||
'context_opportunity_snapshot',
|
||||
'context_reuse',
|
||||
];
|
||||
function contextLabel(values: DeskAnswers | undefined): string {
|
||||
if (!values?.context_opportunity) return 'Sem oportunidade seleccionada';
|
||||
try {
|
||||
const snapshot = JSON.parse(
|
||||
String(values.context_opportunity_snapshot ?? '{}'),
|
||||
);
|
||||
if (typeof snapshot.choice?.opportunity?.title === 'string')
|
||||
return (
|
||||
snapshot.choice.opportunity.title +
|
||||
(Number.isInteger(snapshot.revision)
|
||||
? ` · revisão ${snapshot.revision}`
|
||||
: '')
|
||||
);
|
||||
} catch {
|
||||
/* A legacy context still remains recoverable. */
|
||||
}
|
||||
return 'Oportunidade seleccionada; designação por recuperar';
|
||||
}
|
||||
|
||||
/** Three sources remain explicit; a deliberate revert is still an edit. */
|
||||
export function checkpointRecovery(
|
||||
base: DeskAnswers,
|
||||
page: DeskAnswers,
|
||||
edited: readonly string[],
|
||||
current: DeskAnswers,
|
||||
saved: DeskCheckpoint | null,
|
||||
allowed: readonly string[],
|
||||
choices: Record<string, RecoveryChoice> = {},
|
||||
) {
|
||||
const payload = { ...current };
|
||||
const conflicts: string[] = [];
|
||||
const intent: string[] = [];
|
||||
const rows: {
|
||||
key: string;
|
||||
page: DeskAnswer | null;
|
||||
saved: DeskAnswer | null;
|
||||
current: DeskAnswer | null;
|
||||
conflict: boolean;
|
||||
choice: RecoveryChoice;
|
||||
}[] = [];
|
||||
for (const key of allowed) {
|
||||
if (contextKeys.includes(key) && key !== 'context_opportunity')
|
||||
continue;
|
||||
const group =
|
||||
key === 'context_opportunity'
|
||||
? contextKeys.filter((k) => allowed.includes(k))
|
||||
: [key];
|
||||
const same = (a: DeskAnswers | undefined, b: DeskAnswers | undefined) =>
|
||||
group.every((k) => checkpointSame(a?.[k], b?.[k]));
|
||||
const local =
|
||||
group.some((k) => edited.includes(k)) || !same(page, base);
|
||||
const remote =
|
||||
!!saved &&
|
||||
(group.some((k) => saved.edited_keys.includes(k)) ||
|
||||
!same(saved.payload, saved.base_payload));
|
||||
if (!local && !remote) continue;
|
||||
const conflict =
|
||||
(local && remote && !same(page, saved?.payload)) ||
|
||||
(local && !same(base, current) && !same(page, current)) ||
|
||||
(remote &&
|
||||
!same(saved?.base_payload, current) &&
|
||||
!same(saved?.payload, current));
|
||||
const choice = choices[key] ?? (local ? 'page' : 'saved');
|
||||
if (conflict && !choices[key]) conflicts.push(key);
|
||||
for (const member of group)
|
||||
payload[member] =
|
||||
(choice === 'page'
|
||||
? page[member]
|
||||
: choice === 'saved'
|
||||
? saved?.payload[member]
|
||||
: current[member]) ?? null;
|
||||
if (choice !== 'current') intent.push(...group);
|
||||
rows.push({
|
||||
key,
|
||||
page:
|
||||
key === 'context_opportunity'
|
||||
? contextLabel(page)
|
||||
: (page[key] ?? null),
|
||||
saved:
|
||||
key === 'context_opportunity'
|
||||
? contextLabel(saved?.payload)
|
||||
: (saved?.payload[key] ?? null),
|
||||
current:
|
||||
key === 'context_opportunity'
|
||||
? contextLabel(current)
|
||||
: (current[key] ?? null),
|
||||
conflict,
|
||||
choice,
|
||||
});
|
||||
}
|
||||
return { payload, conflicts, intent, rows };
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
export type DeskValueField = { type: string; options?: Record<string, string> };
|
||||
export type DeskAnswer = string | number | boolean | string[] | null;
|
||||
|
||||
export function deskScalar(value: unknown): string {
|
||||
if (typeof value === 'string' || typeof value === 'number')
|
||||
return String(value);
|
||||
if (typeof value === 'boolean') return value ? '1' : '';
|
||||
return '';
|
||||
}
|
||||
|
||||
export function deskChoices(value: unknown): string[] {
|
||||
return Array.isArray(value) && value.every((v) => typeof v === 'string')
|
||||
? value
|
||||
: [];
|
||||
}
|
||||
|
||||
export function deskEmpty(value: unknown): boolean {
|
||||
return (
|
||||
value === null ||
|
||||
value === undefined ||
|
||||
(typeof value === 'string' && value.trim() === '') ||
|
||||
(Array.isArray(value) && value.length === 0)
|
||||
);
|
||||
}
|
||||
|
||||
/** Preserve typed answers and refusals; a master/profile can never supply a consent declaration. */
|
||||
export function mergeDeskPrefill(
|
||||
current: Record<string, DeskAnswer>,
|
||||
patch: Record<string, unknown>,
|
||||
fields: Record<string, DeskValueField>,
|
||||
replace = false,
|
||||
): Record<string, DeskAnswer> {
|
||||
const next = { ...current };
|
||||
for (const [key, value] of Object.entries(patch)) {
|
||||
const field = fields[key];
|
||||
if (
|
||||
field?.type === 'consent' ||
|
||||
field?.type === 'attachment' ||
|
||||
(!replace && !deskEmpty(current[key]))
|
||||
)
|
||||
continue;
|
||||
if (field?.type === 'multiselect') {
|
||||
if (
|
||||
Array.isArray(value) &&
|
||||
value.every(
|
||||
(v) =>
|
||||
typeof v === 'string' &&
|
||||
Object.hasOwn(field.options ?? {}, v),
|
||||
)
|
||||
)
|
||||
next[key] = [...value];
|
||||
} else if (
|
||||
value === null ||
|
||||
typeof value === 'string' ||
|
||||
typeof value === 'number' ||
|
||||
typeof value === 'boolean'
|
||||
)
|
||||
next[key] = value;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
type ConditionalField = { when?: { field: string; equals: string } };
|
||||
type ConditionalField = {
|
||||
when?: { field: string; equals: string; operator?: 'equals' | 'contains' };
|
||||
};
|
||||
|
||||
export function deskFieldApplies(
|
||||
key: string,
|
||||
@@ -10,6 +12,21 @@ export function deskFieldApplies(
|
||||
if (!field || ancestors.has(key)) return false;
|
||||
if (!field.when) return true;
|
||||
const value = payload[field.when.field];
|
||||
if (field.when.operator === 'contains') {
|
||||
if (
|
||||
!Array.isArray(value) ||
|
||||
!value.some(
|
||||
(v) => typeof v === 'string' && v === field.when!.equals,
|
||||
)
|
||||
)
|
||||
return false;
|
||||
return deskFieldApplies(
|
||||
field.when.field,
|
||||
fields,
|
||||
payload,
|
||||
new Set([...ancestors, key]),
|
||||
);
|
||||
}
|
||||
if (!['string', 'number', 'boolean'].includes(typeof value)) return false;
|
||||
const answer =
|
||||
typeof value === 'boolean' ? (value ? '1' : '') : String(value);
|
||||
|
||||
@@ -0,0 +1,388 @@
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { createOperationKey } from './operation-key';
|
||||
|
||||
export type EducationDeclaration = {
|
||||
id: string;
|
||||
qualification: string;
|
||||
quantity: number;
|
||||
status: string;
|
||||
version_no: number;
|
||||
period_start: string;
|
||||
period_end: string;
|
||||
reference_date?: string;
|
||||
valid_until: string;
|
||||
source: string;
|
||||
submitted_by_name?: string | null;
|
||||
reviewed_by_name?: string | null;
|
||||
review_reason?: string | null;
|
||||
employer?: string;
|
||||
can_review?: boolean;
|
||||
review_unavailable?: 'self' | 'expired' | null;
|
||||
review_context?: {
|
||||
actor_id: number;
|
||||
commands: { key: string; version: number }[];
|
||||
};
|
||||
};
|
||||
export type EducationReviewProps = {
|
||||
declaration: EducationDeclaration;
|
||||
kind: 'demands' | 'capacities';
|
||||
actorId: number;
|
||||
today: string;
|
||||
references?: Record<string, string | null>;
|
||||
};
|
||||
type Values = { version_no: number; status: string; review_reason: string };
|
||||
type Snapshot = Pick<
|
||||
EducationDeclaration,
|
||||
| 'version_no'
|
||||
| 'qualification'
|
||||
| 'quantity'
|
||||
| 'status'
|
||||
| 'period_start'
|
||||
| 'period_end'
|
||||
| 'valid_until'
|
||||
| 'source'
|
||||
> & {
|
||||
reference_date: string;
|
||||
employer: string;
|
||||
references: Record<string, string | null>;
|
||||
};
|
||||
type Attempt = {
|
||||
values: Values & { client_key: string };
|
||||
reasonGeneration: number;
|
||||
statusGeneration: number;
|
||||
base: Snapshot;
|
||||
};
|
||||
const object = (value: unknown): value is Record<string, unknown> =>
|
||||
!!value && typeof value === 'object' && !Array.isArray(value);
|
||||
const positive = (value: unknown): value is number =>
|
||||
typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
|
||||
const snapshot = (
|
||||
row: EducationDeclaration,
|
||||
references: Record<string, string | null> = {},
|
||||
): Snapshot => ({
|
||||
version_no: row.version_no,
|
||||
qualification: row.qualification,
|
||||
quantity: row.quantity,
|
||||
status: row.status,
|
||||
period_start: row.period_start,
|
||||
period_end: row.period_end,
|
||||
valid_until: row.valid_until,
|
||||
source: row.source,
|
||||
reference_date: row.reference_date ?? '',
|
||||
employer: row.employer ?? '',
|
||||
references: { ...references },
|
||||
});
|
||||
|
||||
export function useEducationReview({
|
||||
declaration: row,
|
||||
kind,
|
||||
actorId,
|
||||
references = {},
|
||||
}: EducationReviewProps) {
|
||||
const form = useForm<Values>({
|
||||
version_no: row.version_no,
|
||||
status: 'reviewed',
|
||||
review_reason: '',
|
||||
});
|
||||
const live = useRef(form.data);
|
||||
live.current = form.data;
|
||||
const base = useRef(snapshot(row, references)),
|
||||
pending = useRef<Attempt | null>(null),
|
||||
alive = useRef(true);
|
||||
const generation = useRef({ status: 0, review_reason: 0 });
|
||||
const [uncertain, setUncertain] = useState(false),
|
||||
[conflict, setConflict] = useState(false),
|
||||
[refreshing, setRefreshing] = useState(false),
|
||||
[accessBlocked, setAccessBlocked] = useState(false),
|
||||
[notice, setNotice] = useState('');
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
};
|
||||
}, []);
|
||||
const invalid =
|
||||
!positive(actorId) ||
|
||||
row.review_context?.actor_id !== actorId ||
|
||||
!positive(row.version_no) ||
|
||||
!Array.isArray(row.review_context?.commands);
|
||||
const stale = form.data.version_no !== row.version_no;
|
||||
function change(field: 'status' | 'review_reason', value: string) {
|
||||
generation.current[field]++;
|
||||
live.current = { ...live.current, [field]: value };
|
||||
form.setData(live.current);
|
||||
}
|
||||
function read(props: unknown): EducationDeclaration | null {
|
||||
if (
|
||||
!object(props) ||
|
||||
props.actorId !== actorId ||
|
||||
props.kind !== kind ||
|
||||
!object(props.declaration) ||
|
||||
props.declaration.id !== row.id
|
||||
)
|
||||
return null;
|
||||
const value = props.declaration;
|
||||
if (
|
||||
!positive(value.version_no) ||
|
||||
!object(value.review_context) ||
|
||||
value.review_context.actor_id !== actorId ||
|
||||
!Array.isArray(value.review_context.commands)
|
||||
)
|
||||
return null;
|
||||
return value as EducationDeclaration;
|
||||
}
|
||||
function returnedReferences(
|
||||
props: Record<string, unknown>,
|
||||
): Record<string, string | null> | null {
|
||||
if (
|
||||
!object(props.references) ||
|
||||
Object.values(props.references).some(
|
||||
(value) => value !== null && typeof value !== 'string',
|
||||
)
|
||||
)
|
||||
return null;
|
||||
return props.references as Record<string, string | null>;
|
||||
}
|
||||
function acknowledge(
|
||||
record: EducationDeclaration,
|
||||
currentReferences: Record<string, string | null> = references,
|
||||
) {
|
||||
const attempt = pending.current;
|
||||
if (
|
||||
!alive.current ||
|
||||
!attempt ||
|
||||
record.review_context?.actor_id !== actorId
|
||||
)
|
||||
return false;
|
||||
const receipt = record.review_context.commands.find(
|
||||
(item) => item.key === attempt.values.client_key,
|
||||
);
|
||||
if (
|
||||
!receipt ||
|
||||
receipt.version !== attempt.values.version_no + 1 ||
|
||||
record.version_no < receipt.version
|
||||
)
|
||||
return false;
|
||||
base.current =
|
||||
record.version_no === receipt.version
|
||||
? snapshot(record, currentReferences)
|
||||
: {
|
||||
...attempt.base,
|
||||
version_no: receipt.version,
|
||||
status: attempt.values.status,
|
||||
};
|
||||
live.current = {
|
||||
version_no: receipt.version,
|
||||
status:
|
||||
generation.current.status === attempt.statusGeneration
|
||||
? 'reviewed'
|
||||
: live.current.status,
|
||||
review_reason:
|
||||
generation.current.review_reason === attempt.reasonGeneration
|
||||
? ''
|
||||
: live.current.review_reason,
|
||||
};
|
||||
form.setData(live.current);
|
||||
form.clearErrors();
|
||||
pending.current = null;
|
||||
setUncertain(false);
|
||||
setConflict(false);
|
||||
setAccessBlocked(false);
|
||||
setNotice(
|
||||
'Revisão registada. As alterações posteriores ao envio foram conservadas.',
|
||||
);
|
||||
return true;
|
||||
}
|
||||
useEffect(() => {
|
||||
if (!invalid && pending.current) acknowledge(row);
|
||||
}, [row, actorId, invalid]);
|
||||
function submit() {
|
||||
if (
|
||||
invalid ||
|
||||
accessBlocked ||
|
||||
refreshing ||
|
||||
form.processing ||
|
||||
(!pending.current && (row.can_review !== true || stale || conflict))
|
||||
)
|
||||
return;
|
||||
if (!pending.current) {
|
||||
let key: string;
|
||||
try {
|
||||
key = createOperationKey();
|
||||
} catch {
|
||||
setNotice(
|
||||
'Não foi possível preparar a decisão. Reabra o portal no endereço HTTPS configurado.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
pending.current = {
|
||||
values: { ...live.current, client_key: key },
|
||||
reasonGeneration: generation.current.review_reason,
|
||||
statusGeneration: generation.current.status,
|
||||
base: { ...base.current },
|
||||
};
|
||||
}
|
||||
const attempt = pending.current;
|
||||
setUncertain(true);
|
||||
setNotice('A aguardar confirmação da revisão.');
|
||||
form.transform(() => attempt.values);
|
||||
form.post(`/management/education/${kind}/${row.id}/review`, {
|
||||
preserveScroll: true,
|
||||
onSuccess: (page) => {
|
||||
if (!alive.current || pending.current !== attempt) return;
|
||||
const record = read(page.props),
|
||||
labels = returnedReferences(page.props);
|
||||
if (!record || !labels || !acknowledge(record, labels))
|
||||
setNotice(
|
||||
'A resposta não permitiu confirmar a revisão. Actualize a declaração ou recupere o mesmo envio.',
|
||||
);
|
||||
},
|
||||
onError: () => {
|
||||
if (!alive.current || pending.current !== attempt) return;
|
||||
pending.current = null;
|
||||
setUncertain(false);
|
||||
setNotice(
|
||||
'Reveja os campos assinalados. A decisão preparada foi conservada.',
|
||||
);
|
||||
},
|
||||
onNetworkError: () => {
|
||||
if (alive.current && pending.current === attempt)
|
||||
setNotice(
|
||||
'Sem confirmação da revisão. Recupere o mesmo envio antes de preparar outra decisão.',
|
||||
);
|
||||
},
|
||||
onCancel: () => {
|
||||
if (alive.current && pending.current === attempt)
|
||||
setNotice(
|
||||
'Envio interrompido sem confirmação. Recupere o mesmo envio.',
|
||||
);
|
||||
},
|
||||
onHttpException: (response) => {
|
||||
if (!alive.current || pending.current !== attempt) return;
|
||||
if ([401, 403, 419].includes(response.status))
|
||||
setAccessBlocked(true);
|
||||
if (response.status === 422) {
|
||||
pending.current = null;
|
||||
setUncertain(false);
|
||||
}
|
||||
if ([409, 422].includes(response.status)) setConflict(true);
|
||||
setNotice(
|
||||
'Não foi possível confirmar a revisão. Actualize a declaração e o acesso antes de continuar. A decisão preparada foi conservada.',
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
function refresh() {
|
||||
if (refreshing || form.processing) return;
|
||||
setRefreshing(true);
|
||||
router.reload({
|
||||
only: [
|
||||
'declaration',
|
||||
'references',
|
||||
'today',
|
||||
'actorId',
|
||||
'kind',
|
||||
'history',
|
||||
],
|
||||
onSuccess: (page) => {
|
||||
if (!alive.current) return;
|
||||
const record = read(page.props),
|
||||
labels = returnedReferences(page.props);
|
||||
if (!record || !labels) return;
|
||||
setAccessBlocked(false);
|
||||
if (pending.current) acknowledge(record, labels);
|
||||
},
|
||||
onFinish: () => {
|
||||
if (alive.current) setRefreshing(false);
|
||||
},
|
||||
});
|
||||
}
|
||||
function adopt() {
|
||||
if (
|
||||
invalid ||
|
||||
!stale ||
|
||||
row.can_review !== true ||
|
||||
refreshing ||
|
||||
form.processing
|
||||
)
|
||||
return;
|
||||
const attempt = pending.current;
|
||||
if (attempt) {
|
||||
if (acknowledge(row)) return;
|
||||
if (
|
||||
row.version_no <= attempt.values.version_no ||
|
||||
row.review_context?.commands.some(
|
||||
(item) => item.key === attempt.values.client_key,
|
||||
)
|
||||
)
|
||||
return;
|
||||
pending.current = null;
|
||||
setUncertain(false);
|
||||
}
|
||||
base.current = snapshot(row, references);
|
||||
live.current = { ...live.current, version_no: row.version_no };
|
||||
form.setData(live.current);
|
||||
setConflict(false);
|
||||
form.clearErrors('version_no');
|
||||
setNotice(
|
||||
'Versão actual confirmada. A sua decisão preparada foi conservada para rever antes de enviar.',
|
||||
);
|
||||
}
|
||||
const guard = useRef(false);
|
||||
guard.current =
|
||||
uncertain ||
|
||||
!!form.data.review_reason ||
|
||||
form.data.status !== 'reviewed';
|
||||
useEffect(() => {
|
||||
const remove = router.on('before', (event) => {
|
||||
if (
|
||||
guard.current &&
|
||||
event.detail.visit.method === 'get' &&
|
||||
!event.detail.visit.preserveState &&
|
||||
!window.confirm(
|
||||
'Existe uma revisão preparada ou um envio sem confirmação. Sair desta página?',
|
||||
)
|
||||
)
|
||||
event.preventDefault();
|
||||
});
|
||||
const unload = (event: BeforeUnloadEvent) => {
|
||||
if (guard.current) {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
}
|
||||
};
|
||||
window.addEventListener('beforeunload', unload);
|
||||
return () => {
|
||||
remove();
|
||||
window.removeEventListener('beforeunload', unload);
|
||||
};
|
||||
}, []);
|
||||
return {
|
||||
form,
|
||||
change,
|
||||
submit,
|
||||
refresh,
|
||||
adopt,
|
||||
base: base.current,
|
||||
current: snapshot(row, references),
|
||||
stale,
|
||||
conflict,
|
||||
refreshing,
|
||||
uncertain,
|
||||
notice,
|
||||
canAdopt:
|
||||
!invalid &&
|
||||
stale &&
|
||||
row.can_review === true &&
|
||||
!refreshing &&
|
||||
!form.processing,
|
||||
blocked:
|
||||
invalid ||
|
||||
accessBlocked ||
|
||||
refreshing ||
|
||||
(!pending.current &&
|
||||
(row.can_review !== true || stale || conflict)),
|
||||
sent: pending.current?.values,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
export type GuideSelection = {
|
||||
slug: string;
|
||||
sha256: string;
|
||||
instruments: string[];
|
||||
};
|
||||
|
||||
export function guideUrl(
|
||||
base: string,
|
||||
selection: GuideSelection,
|
||||
choosingDossier = false,
|
||||
): string {
|
||||
const query = new URLSearchParams();
|
||||
if (choosingDossier) {
|
||||
query.set('investment_guide[slug]', selection.slug);
|
||||
query.set('investment_guide[sha256]', selection.sha256);
|
||||
selection.instruments.forEach((code) =>
|
||||
query.append('investment_guide[instruments][]', code),
|
||||
);
|
||||
} else {
|
||||
query.set('current', '1');
|
||||
query.set('selection', '1');
|
||||
query.set('sha256', selection.sha256);
|
||||
selection.instruments.forEach((code) =>
|
||||
query.append('instruments[]', code),
|
||||
);
|
||||
}
|
||||
return `${base}?${query}`;
|
||||
}
|
||||
|
||||
export function guideChoices(form: HTMLFormElement): string[] {
|
||||
return new FormData(form)
|
||||
.getAll('instruments[]')
|
||||
.filter((v): v is string => typeof v === 'string');
|
||||
}
|
||||
@@ -0,0 +1,433 @@
|
||||
import { router } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { createOperationKey } from './operation-key';
|
||||
import { portalRequest, PortalApiError } from './portal-api';
|
||||
|
||||
export type ProfileRecord = {
|
||||
id?: string;
|
||||
version: number;
|
||||
payload: Record<string, string>;
|
||||
};
|
||||
export type OrganizationRecord = {
|
||||
id: string;
|
||||
name: string;
|
||||
version: number;
|
||||
country: string | null;
|
||||
canEdit: boolean;
|
||||
provenance: { reference: string; kind: string } | null;
|
||||
};
|
||||
type Attempt = {
|
||||
version: number;
|
||||
payload: Record<string, string>;
|
||||
operation_key: string;
|
||||
};
|
||||
const values = (record: ProfileRecord, fields: string[]) =>
|
||||
Object.fromEntries(
|
||||
[...fields, 'country'].map((key) => [key, record.payload[key] ?? '']),
|
||||
);
|
||||
const same = (left: Record<string, string>, right: Record<string, string>) =>
|
||||
JSON.stringify(left) === JSON.stringify(right);
|
||||
|
||||
export function useInvestmentProfileEditor(
|
||||
record: ProfileRecord,
|
||||
fields: string[],
|
||||
company: boolean,
|
||||
actorId: number,
|
||||
editorId: string,
|
||||
reportDirty: (id: string, dirty: boolean) => void,
|
||||
organization?: { id: string; canEdit: boolean },
|
||||
) {
|
||||
const [base, setBase] = useState(() => ({
|
||||
...record,
|
||||
payload: values(record, fields),
|
||||
})),
|
||||
[draft, setDraft] = useState(() => values(record, fields)),
|
||||
[remote, setRemote] = useState<ProfileRecord | null>(null),
|
||||
[busy, setBusy] = useState(false),
|
||||
[reading, setReading] = useState(false),
|
||||
[uncertain, setUncertain] = useState(false),
|
||||
[blocked, setBlocked] = useState(false),
|
||||
[errors, setErrors] = useState<Record<string, string>>({}),
|
||||
[error, setError] = useState(''),
|
||||
[notice, setNotice] = useState(''),
|
||||
[externalBusy, setExternalBusy] = useState(false),
|
||||
[permission, setPermission] = useState<{
|
||||
editable: boolean;
|
||||
propVersion: number;
|
||||
propCanEdit: boolean;
|
||||
} | null>(null);
|
||||
const pending = useRef<Attempt | null>(null),
|
||||
externalLock = useRef(false),
|
||||
readInFlight = useRef(false),
|
||||
active = useRef(false),
|
||||
alive = useRef(true),
|
||||
origin = useRef({ actorId, id: record.id }),
|
||||
current = useRef({ actorId, id: record.id });
|
||||
current.current = { actorId, id: record.id };
|
||||
const valid = () =>
|
||||
alive.current &&
|
||||
Number.isSafeInteger(actorId) &&
|
||||
actorId > 0 &&
|
||||
origin.current.actorId === current.current.actorId &&
|
||||
origin.current.id === current.current.id;
|
||||
const dirty =
|
||||
!same(draft, base.payload) || busy || uncertain || externalBusy;
|
||||
const stale = (!company || !!record.id) && record.version > base.version;
|
||||
const mayEdit =
|
||||
!organization ||
|
||||
(permission &&
|
||||
permission.propVersion === record.version &&
|
||||
permission.propCanEdit === organization.canEdit
|
||||
? permission.editable
|
||||
: organization.canEdit);
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
reportDirty(editorId, dirty);
|
||||
}, [dirty, editorId, reportDirty]);
|
||||
useEffect(
|
||||
() => () => reportDirty(editorId, false),
|
||||
[editorId, reportDirty],
|
||||
);
|
||||
function change(key: string, value: string) {
|
||||
if (
|
||||
active.current ||
|
||||
externalLock.current ||
|
||||
uncertain ||
|
||||
blocked ||
|
||||
!mayEdit ||
|
||||
!valid()
|
||||
)
|
||||
return;
|
||||
setDraft((prior) => ({ ...prior, [key]: value }));
|
||||
setErrors((prior) => {
|
||||
const next = { ...prior };
|
||||
delete next['payload.' + key];
|
||||
delete next[key];
|
||||
return next;
|
||||
});
|
||||
setNotice('');
|
||||
}
|
||||
async function save() {
|
||||
if (
|
||||
active.current ||
|
||||
externalLock.current ||
|
||||
readInFlight.current ||
|
||||
reading ||
|
||||
blocked ||
|
||||
!mayEdit ||
|
||||
!valid() ||
|
||||
(stale && !pending.current)
|
||||
)
|
||||
return;
|
||||
try {
|
||||
pending.current ??= {
|
||||
version: base.version,
|
||||
payload: { ...draft },
|
||||
operation_key: createOperationKey(),
|
||||
};
|
||||
} catch (failure) {
|
||||
setError(
|
||||
failure instanceof Error
|
||||
? failure.message
|
||||
: 'Não foi possível preparar o pedido.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
const attempt = pending.current;
|
||||
active.current = true;
|
||||
setBusy(true);
|
||||
setError('');
|
||||
setErrors({});
|
||||
setNotice('');
|
||||
try {
|
||||
const result = await portalRequest<{
|
||||
version: number;
|
||||
id?: string;
|
||||
country?: string;
|
||||
}>(
|
||||
organization
|
||||
? '/api/v1/investment/organizations/' +
|
||||
organization.id +
|
||||
'/country'
|
||||
: company
|
||||
? '/api/v1/investment/companies' +
|
||||
(record.id ? '/' + record.id : '')
|
||||
: '/api/v1/investment/profile',
|
||||
{
|
||||
method: company ? 'POST' : 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(
|
||||
organization
|
||||
? {
|
||||
version: attempt.version,
|
||||
operation_key: attempt.operation_key,
|
||||
...attempt.payload,
|
||||
}
|
||||
: attempt,
|
||||
),
|
||||
},
|
||||
);
|
||||
if (!valid() || pending.current !== attempt) return;
|
||||
if (
|
||||
!Number.isSafeInteger(result.version) ||
|
||||
result.version !== attempt.version + 1 ||
|
||||
(organization && result.country !== attempt.payload.country) ||
|
||||
(company &&
|
||||
(typeof result.id !== 'string' ||
|
||||
!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(
|
||||
result.id,
|
||||
) ||
|
||||
(record.id && result.id !== record.id)))
|
||||
)
|
||||
throw new Error('Unconfirmed response');
|
||||
pending.current = null;
|
||||
setUncertain(false);
|
||||
setRemote(null);
|
||||
if (company && !record.id) {
|
||||
const empty = values({ version: 0, payload: {} }, fields);
|
||||
setDraft(empty);
|
||||
setBase({ version: 0, payload: empty });
|
||||
} else
|
||||
setBase({
|
||||
...record,
|
||||
version: result.version,
|
||||
payload: { ...attempt.payload },
|
||||
});
|
||||
setNotice('Gravação confirmada.');
|
||||
router.reload({
|
||||
only: organization
|
||||
? ['organizations']
|
||||
: ['account', 'companies'],
|
||||
});
|
||||
} catch (failure) {
|
||||
if (!valid() || pending.current !== attempt) return;
|
||||
if (failure instanceof PortalApiError && failure.status === 422) {
|
||||
pending.current = null;
|
||||
setUncertain(false);
|
||||
setErrors(
|
||||
Object.fromEntries(
|
||||
Object.entries(failure.errors).map(
|
||||
([key, messages]) => [
|
||||
key,
|
||||
messages[0] ?? 'Verifique este campo.',
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
setError('Verifique os campos assinalados.');
|
||||
} else if (
|
||||
failure instanceof PortalApiError &&
|
||||
failure.status === 409
|
||||
) {
|
||||
pending.current = null;
|
||||
setUncertain(false);
|
||||
setBlocked(true);
|
||||
setError(
|
||||
'O registo mudou ou este pedido já tem outro conteúdo. Consulte e compare o registo guardado antes de voltar a gravar.',
|
||||
);
|
||||
} else if (
|
||||
failure instanceof PortalApiError &&
|
||||
[401, 403, 404, 419].includes(failure.status)
|
||||
) {
|
||||
setBlocked(true);
|
||||
setUncertain(true);
|
||||
setError(
|
||||
'A sessão ou o acesso já não permite confirmar o pedido. A preparação permanece nesta página. Restabeleça o acesso e consulte o registo.',
|
||||
);
|
||||
} else {
|
||||
setUncertain(true);
|
||||
setError(
|
||||
'Não foi possível confirmar a gravação. A preparação foi conservada. Repita o mesmo pedido para confirmar o resultado antes de editar.',
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (valid()) {
|
||||
active.current = false;
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
async function refresh() {
|
||||
if (
|
||||
active.current ||
|
||||
externalLock.current ||
|
||||
readInFlight.current ||
|
||||
!valid()
|
||||
)
|
||||
return;
|
||||
readInFlight.current = true;
|
||||
setReading(true);
|
||||
setError('');
|
||||
try {
|
||||
const response = await portalRequest<{
|
||||
actorId: number;
|
||||
account: ProfileRecord;
|
||||
companies: ProfileRecord[];
|
||||
organizations?: OrganizationRecord[];
|
||||
}>('/api/v1/investment/profile');
|
||||
if (!valid()) return;
|
||||
if (
|
||||
response.actorId !== actorId ||
|
||||
!Array.isArray(response.companies)
|
||||
)
|
||||
throw new Error('Context changed');
|
||||
const org = organization
|
||||
? response.organizations?.find(
|
||||
(item) => item.id === organization.id,
|
||||
)
|
||||
: undefined;
|
||||
if (
|
||||
organization &&
|
||||
(!org ||
|
||||
typeof org.canEdit !== 'boolean' ||
|
||||
(org.country !== null && typeof org.country !== 'string') ||
|
||||
(org.provenance !== null &&
|
||||
typeof org.provenance?.reference !== 'string'))
|
||||
) {
|
||||
setBlocked(true);
|
||||
throw new Error('Organisation unavailable');
|
||||
}
|
||||
if (org && organization)
|
||||
setPermission({
|
||||
editable: org.canEdit,
|
||||
propVersion: record.version,
|
||||
propCanEdit: organization.canEdit,
|
||||
});
|
||||
const next = org
|
||||
? {
|
||||
id: org.id,
|
||||
version: org.version,
|
||||
payload: {
|
||||
country: org.country ?? '',
|
||||
source_reference: org.provenance?.reference ?? '',
|
||||
},
|
||||
}
|
||||
: company
|
||||
? record.id
|
||||
? response.companies.find((item) => item.id === record.id)
|
||||
: { version: 0, payload: {} }
|
||||
: response.account;
|
||||
if (
|
||||
!next ||
|
||||
!Number.isSafeInteger(next.version) ||
|
||||
next.version < 0 ||
|
||||
!next.payload ||
|
||||
typeof next.payload !== 'object' ||
|
||||
Array.isArray(next.payload) ||
|
||||
fields.some(
|
||||
(key) =>
|
||||
next.payload[key] != null &&
|
||||
typeof next.payload[key] !== 'string',
|
||||
)
|
||||
)
|
||||
throw new Error('Record unavailable');
|
||||
setRemote({ ...next, payload: values(next, fields) });
|
||||
setBlocked(pending.current === null);
|
||||
setNotice(
|
||||
uncertain
|
||||
? 'Registo consultado. Confirme primeiro o pedido sem resposta; a preparação não foi alterada.'
|
||||
: 'Registo consultado. Compare os valores antes de escolher como continuar.',
|
||||
);
|
||||
} catch {
|
||||
if (valid())
|
||||
setError(
|
||||
'Não foi possível consultar o registo nesta sessão. A preparação foi conservada.',
|
||||
);
|
||||
} finally {
|
||||
if (valid()) {
|
||||
readInFlight.current = false;
|
||||
setReading(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
function adopt(keepDraft: boolean) {
|
||||
if (
|
||||
!remote ||
|
||||
active.current ||
|
||||
externalLock.current ||
|
||||
readInFlight.current ||
|
||||
busy ||
|
||||
reading ||
|
||||
uncertain ||
|
||||
pending.current ||
|
||||
!mayEdit ||
|
||||
!valid()
|
||||
)
|
||||
return;
|
||||
setBase(remote);
|
||||
if (!keepDraft) setDraft({ ...remote.payload });
|
||||
setRemote(null);
|
||||
setBlocked(false);
|
||||
setError('');
|
||||
setErrors({});
|
||||
setNotice(
|
||||
keepDraft
|
||||
? 'Versão actual adoptada; a sua preparação foi conservada. Reveja antes de guardar.'
|
||||
: 'Valores guardados carregados.',
|
||||
);
|
||||
}
|
||||
function beginCountryReuse(): boolean {
|
||||
if (
|
||||
!company ||
|
||||
!record.id ||
|
||||
dirty ||
|
||||
blocked ||
|
||||
stale ||
|
||||
active.current ||
|
||||
readInFlight.current ||
|
||||
externalLock.current ||
|
||||
pending.current ||
|
||||
!valid()
|
||||
)
|
||||
return false;
|
||||
externalLock.current = true;
|
||||
setExternalBusy(true);
|
||||
return true;
|
||||
}
|
||||
function endCountryReuse(result?: {
|
||||
version: number;
|
||||
country: string;
|
||||
}): void {
|
||||
if (!externalLock.current || !valid()) return;
|
||||
if (result) {
|
||||
const payload = {
|
||||
...base.payload,
|
||||
incorporation_country_code: result.country,
|
||||
};
|
||||
setBase({ ...base, version: result.version, payload });
|
||||
setDraft(payload);
|
||||
setRemote(null);
|
||||
setErrors({});
|
||||
setError('');
|
||||
}
|
||||
externalLock.current = false;
|
||||
setExternalBusy(false);
|
||||
}
|
||||
return {
|
||||
base,
|
||||
draft,
|
||||
busy,
|
||||
reading,
|
||||
uncertain,
|
||||
blocked,
|
||||
errors,
|
||||
error,
|
||||
notice,
|
||||
stale,
|
||||
remote,
|
||||
dirty,
|
||||
externalBusy,
|
||||
beginCountryReuse,
|
||||
endCountryReuse,
|
||||
mayEdit,
|
||||
change,
|
||||
save,
|
||||
refresh,
|
||||
adopt,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
import { router } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { createOperationKey } from './operation-key';
|
||||
import { portalRequest, PortalApiError } from './portal-api';
|
||||
import type {
|
||||
useInvestmentProfileEditor,
|
||||
OrganizationRecord,
|
||||
} from './investment-profile-editor';
|
||||
|
||||
export type CountryReusePreview = {
|
||||
organizationId: string;
|
||||
organizationName: string;
|
||||
organizationVersion: number;
|
||||
country: string;
|
||||
reference: string;
|
||||
companyVersion: number;
|
||||
companyCountry: string;
|
||||
};
|
||||
type Attempt = {
|
||||
version: number;
|
||||
organization_id: string;
|
||||
organization_version: number;
|
||||
operation_key: string;
|
||||
country: string;
|
||||
};
|
||||
type Editor = ReturnType<typeof useInvestmentProfileEditor>;
|
||||
const object = (value: unknown): value is Record<string, unknown> =>
|
||||
!!value && typeof value === 'object' && !Array.isArray(value);
|
||||
const version = (value: unknown): value is number =>
|
||||
typeof value === 'number' && Number.isSafeInteger(value) && value >= 1;
|
||||
|
||||
export function useOrganizationCountryReuse(
|
||||
companyId: string,
|
||||
actorId: number,
|
||||
editor: Editor,
|
||||
reportDirty: (id: string, dirty: boolean) => void,
|
||||
organizations: OrganizationRecord[],
|
||||
) {
|
||||
const [preview, setPreview] = useState<CountryReusePreview | null>(null),
|
||||
[busy, setBusy] = useState(false),
|
||||
[reading, setReading] = useState(false),
|
||||
[uncertain, setUncertain] = useState(false),
|
||||
[blocked, setBlocked] = useState(false),
|
||||
[error, setError] = useState(''),
|
||||
[notice, setNotice] = useState('');
|
||||
const pending = useRef<Attempt | null>(null),
|
||||
active = useRef(false),
|
||||
alive = useRef(true),
|
||||
liveEditor = useRef(editor),
|
||||
sources = useRef(organizations),
|
||||
origin = useRef({ companyId, actorId }),
|
||||
current = useRef({ companyId, actorId });
|
||||
current.current = { companyId, actorId };
|
||||
liveEditor.current = editor;
|
||||
sources.current = organizations;
|
||||
const valid = () =>
|
||||
alive.current &&
|
||||
Number.isSafeInteger(actorId) &&
|
||||
actorId > 0 &&
|
||||
origin.current.actorId === current.current.actorId &&
|
||||
origin.current.companyId === current.current.companyId;
|
||||
const changedSource = () => {
|
||||
if (!preview || pending.current) return false;
|
||||
const source = sources.current.find(
|
||||
(item) => item.id === preview.organizationId,
|
||||
);
|
||||
return (
|
||||
!source ||
|
||||
source.version > preview.organizationVersion ||
|
||||
(source.version === preview.organizationVersion &&
|
||||
source.country !== preview.country)
|
||||
);
|
||||
};
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
reportDirty(
|
||||
'country-reuse-' + companyId,
|
||||
!!preview || busy || uncertain,
|
||||
);
|
||||
}, [preview, busy, uncertain, companyId, reportDirty]);
|
||||
useEffect(
|
||||
() => () => reportDirty('country-reuse-' + companyId, false),
|
||||
[companyId, reportDirty],
|
||||
);
|
||||
|
||||
async function inspect(organizationId: string) {
|
||||
if (active.current || !valid()) return;
|
||||
if (
|
||||
!pending.current &&
|
||||
(liveEditor.current.dirty ||
|
||||
liveEditor.current.blocked ||
|
||||
liveEditor.current.stale)
|
||||
) {
|
||||
setError(
|
||||
'Guarde ou confirme a preparação desta declaração antes de reutilizar o país.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
active.current = true;
|
||||
setReading(true);
|
||||
setError('');
|
||||
setNotice('');
|
||||
try {
|
||||
const data = await portalRequest<unknown>(
|
||||
'/api/v1/investment/profile',
|
||||
);
|
||||
if (!valid()) return;
|
||||
if (
|
||||
!object(data) ||
|
||||
data.actorId !== actorId ||
|
||||
!Array.isArray(data.companies) ||
|
||||
!Array.isArray(data.organizations)
|
||||
)
|
||||
throw new Error('Invalid context');
|
||||
const company = data.companies.find(
|
||||
(item) => object(item) && item.id === companyId,
|
||||
),
|
||||
source = data.organizations.find(
|
||||
(item) => object(item) && item.id === organizationId,
|
||||
);
|
||||
if (
|
||||
!object(company) ||
|
||||
!version(company.version) ||
|
||||
!object(company.payload) ||
|
||||
!object(source) ||
|
||||
!version(source.version) ||
|
||||
typeof source.name !== 'string'
|
||||
) {
|
||||
setBlocked(true);
|
||||
throw new Error('Source unavailable');
|
||||
}
|
||||
if (pending.current) {
|
||||
setBlocked(false);
|
||||
setNotice(
|
||||
'Estado consultado: declaração na versão ' +
|
||||
company.version +
|
||||
'. Confirme o pedido sem resposta antes de preparar outra reutilização.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
company.version !== liveEditor.current.base.version ||
|
||||
liveEditor.current.dirty
|
||||
) {
|
||||
setPreview(null);
|
||||
setError(
|
||||
'A declaração ou a preparação mudou. Consulte e compare o registo no formulário antes de reutilizar.',
|
||||
);
|
||||
router.reload({ only: ['companies', 'organizations'] });
|
||||
return;
|
||||
}
|
||||
if (
|
||||
typeof source.country !== 'string' ||
|
||||
!/^[A-Z]{2}$/.test(source.country)
|
||||
) {
|
||||
setPreview(null);
|
||||
setError(
|
||||
'O país de constituição ainda não está disponível nesta organização.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
const reference =
|
||||
object(source.provenance) &&
|
||||
typeof source.provenance.reference === 'string'
|
||||
? source.provenance.reference
|
||||
: '';
|
||||
setPreview({
|
||||
organizationId,
|
||||
organizationName: source.name,
|
||||
organizationVersion: source.version,
|
||||
country: source.country,
|
||||
reference,
|
||||
companyVersion: company.version,
|
||||
companyCountry:
|
||||
typeof company.payload.incorporation_country_code ===
|
||||
'string'
|
||||
? company.payload.incorporation_country_code
|
||||
: '',
|
||||
});
|
||||
setBlocked(false);
|
||||
} catch {
|
||||
if (valid())
|
||||
setError(
|
||||
'Não foi possível consultar a declaração e a organização nesta sessão. A preparação foi conservada.',
|
||||
);
|
||||
} finally {
|
||||
if (valid()) {
|
||||
active.current = false;
|
||||
setReading(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
async function confirm() {
|
||||
if (active.current || blocked || !valid()) return;
|
||||
if (!pending.current) {
|
||||
if (changedSource()) {
|
||||
setError(
|
||||
'A organização mudou. Consulte novamente o país antes de confirmar.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!preview ||
|
||||
preview.companyVersion !== liveEditor.current.base.version
|
||||
) {
|
||||
setError('Volte a consultar os valores antes de confirmar.');
|
||||
return;
|
||||
}
|
||||
let key: string;
|
||||
try {
|
||||
key = createOperationKey();
|
||||
} catch (failure) {
|
||||
setError(
|
||||
failure instanceof Error
|
||||
? failure.message
|
||||
: 'Não foi possível preparar o pedido.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!liveEditor.current.beginCountryReuse()) {
|
||||
setError(
|
||||
'Guarde ou confirme a preparação desta declaração antes de reutilizar o país.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
pending.current = {
|
||||
version: preview.companyVersion,
|
||||
organization_id: preview.organizationId,
|
||||
organization_version: preview.organizationVersion,
|
||||
operation_key: key,
|
||||
country: preview.country,
|
||||
};
|
||||
}
|
||||
const attempt = pending.current;
|
||||
active.current = true;
|
||||
setBusy(true);
|
||||
setError('');
|
||||
setNotice('');
|
||||
try {
|
||||
const { country: expectedCountry, ...command } = attempt;
|
||||
const result = await portalRequest<unknown>(
|
||||
'/api/v1/investment/companies/' +
|
||||
companyId +
|
||||
'/organization-country',
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(command),
|
||||
},
|
||||
);
|
||||
if (!valid() || pending.current !== attempt) return;
|
||||
if (
|
||||
!object(result) ||
|
||||
!version(result.version) ||
|
||||
result.version !== attempt.version + 1 ||
|
||||
result.country !== expectedCountry
|
||||
)
|
||||
throw new Error('Unconfirmed result');
|
||||
liveEditor.current.endCountryReuse({
|
||||
version: result.version,
|
||||
country: expectedCountry,
|
||||
});
|
||||
pending.current = null;
|
||||
setPreview(null);
|
||||
setUncertain(false);
|
||||
setBlocked(false);
|
||||
setNotice('País reutilizado e gravação confirmada.');
|
||||
router.reload({ only: ['companies', 'organizations'] });
|
||||
} catch (failure) {
|
||||
if (!valid() || pending.current !== attempt) return;
|
||||
if (
|
||||
failure instanceof PortalApiError &&
|
||||
[409, 422].includes(failure.status)
|
||||
) {
|
||||
pending.current = null;
|
||||
liveEditor.current.endCountryReuse();
|
||||
setUncertain(false);
|
||||
setPreview(null);
|
||||
setError(
|
||||
'A declaração ou a fonte já não corresponde ao pedido. Consulte os valores guardados antes de preparar outra reutilização.',
|
||||
);
|
||||
router.reload({ only: ['companies', 'organizations'] });
|
||||
} else {
|
||||
setUncertain(true);
|
||||
setBlocked(
|
||||
failure instanceof PortalApiError &&
|
||||
[401, 403, 404, 419].includes(failure.status),
|
||||
);
|
||||
setError(
|
||||
'Não foi possível confirmar a reutilização. O pedido original foi conservado. Consulte o estado ou repita o mesmo pedido antes de editar.',
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (valid()) {
|
||||
active.current = false;
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
function cancel() {
|
||||
if (pending.current || active.current || !valid()) return;
|
||||
setPreview(null);
|
||||
setError('');
|
||||
setNotice('');
|
||||
}
|
||||
return {
|
||||
preview,
|
||||
busy,
|
||||
reading,
|
||||
uncertain,
|
||||
blocked,
|
||||
error,
|
||||
notice,
|
||||
inspect,
|
||||
confirm,
|
||||
cancel,
|
||||
sourceChanged: changedSource(),
|
||||
pendingOrganizationId: pending.current?.organization_id,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { router } from '@inertiajs/react';
|
||||
import { useEffect, useRef } from 'react';
|
||||
export function usePagePreparationGuard(dirty: boolean, message: string) {
|
||||
const guard = useRef({ dirty, message });
|
||||
guard.current = { dirty, message };
|
||||
useEffect(() => {
|
||||
const remove = router.on('before', (event) => {
|
||||
if (
|
||||
guard.current.dirty &&
|
||||
event.detail.visit.method === 'get' &&
|
||||
!event.detail.visit.preserveState &&
|
||||
!window.confirm(guard.current.message)
|
||||
)
|
||||
event.preventDefault();
|
||||
});
|
||||
const unload = (event: BeforeUnloadEvent) => {
|
||||
if (guard.current.dirty) {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
}
|
||||
};
|
||||
window.addEventListener('beforeunload', unload);
|
||||
return () => {
|
||||
remove();
|
||||
window.removeEventListener('beforeunload', unload);
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
export type Confirmation = {
|
||||
actorId: number | null;
|
||||
actorName: string | null;
|
||||
date: string | null;
|
||||
reason: string | null;
|
||||
};
|
||||
export const agreementParties = ['proponent', 'candidate'] as const;
|
||||
export function agreementObject(
|
||||
value: unknown,
|
||||
): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
const text = (value: unknown) => (typeof value === 'string' ? value : null);
|
||||
export function readAgreement(value: unknown) {
|
||||
const record = agreementObject(value) ? value : null;
|
||||
const map =
|
||||
record && agreementObject(record.confirmations)
|
||||
? record.confirmations
|
||||
: record &&
|
||||
Array.isArray(record.confirmations) &&
|
||||
record.confirmations.length === 0
|
||||
? {}
|
||||
: null;
|
||||
const confirmations: Partial<
|
||||
Record<(typeof agreementParties)[number], Confirmation>
|
||||
> = {};
|
||||
for (const party of agreementParties) {
|
||||
if (!map || !Object.hasOwn(map, party)) continue;
|
||||
const stamp = agreementObject(map[party]) ? map[party] : {};
|
||||
const id = stamp.actor_id;
|
||||
confirmations[party] = {
|
||||
actorId:
|
||||
typeof id === 'number' && Number.isSafeInteger(id) && id > 0
|
||||
? id
|
||||
: null,
|
||||
actorName: text(stamp.actor_name),
|
||||
date: text(stamp.date),
|
||||
reason: text(stamp.reason),
|
||||
};
|
||||
}
|
||||
return {
|
||||
kind:
|
||||
value == null
|
||||
? ('absent' as const)
|
||||
: record
|
||||
? ('recorded' as const)
|
||||
: ('malformed' as const),
|
||||
title: text(record?.title),
|
||||
terms: text(record?.terms),
|
||||
confirmationsState: map
|
||||
? ('recorded' as const)
|
||||
: record?.confirmations == null
|
||||
? ('absent' as const)
|
||||
: ('malformed' as const),
|
||||
confirmations,
|
||||
extraConfirmations:
|
||||
!!map &&
|
||||
Object.keys(map).some(
|
||||
(key) => !agreementParties.some((party) => party === key),
|
||||
),
|
||||
legalStatus: text(record?.legal_signature_status),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,805 @@
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { createOperationKey } from './operation-key';
|
||||
type Values = Record<string, string>;
|
||||
type Criterion = {
|
||||
code: string;
|
||||
label: string;
|
||||
weight: number;
|
||||
mandatory: boolean;
|
||||
};
|
||||
type Snapshot = {
|
||||
id: number | null;
|
||||
version: number | null;
|
||||
parentVersion: number;
|
||||
status: string;
|
||||
context: string;
|
||||
weightsHash: string;
|
||||
criteria: Criterion[];
|
||||
owner: boolean;
|
||||
canSubmit: boolean;
|
||||
canDecide: boolean;
|
||||
canWithdraw: boolean;
|
||||
values: Values;
|
||||
commands: { key: string; version: number; action: string }[];
|
||||
};
|
||||
function object(value: unknown): value is Record<string, unknown> {
|
||||
return !!value && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
function dictionary(value: unknown): Record<string, unknown> | null {
|
||||
return object(value)
|
||||
? value
|
||||
: Array.isArray(value) && value.length === 0
|
||||
? {}
|
||||
: null;
|
||||
}
|
||||
function positive(value: unknown): value is number {
|
||||
return (
|
||||
typeof value === 'number' && Number.isSafeInteger(value) && value > 0
|
||||
);
|
||||
}
|
||||
function text(value: unknown): string | null {
|
||||
return value == null ? '' : typeof value === 'string' ? value : null;
|
||||
}
|
||||
export function criterionValue(value: string | undefined): {
|
||||
state: string;
|
||||
evidence: string;
|
||||
} {
|
||||
try {
|
||||
const item: unknown = JSON.parse(value ?? '');
|
||||
if (
|
||||
object(item) &&
|
||||
['unknown', 'met', 'unmet'].includes(String(item.state)) &&
|
||||
typeof item.evidence === 'string'
|
||||
)
|
||||
return { state: String(item.state), evidence: item.evidence };
|
||||
} catch {
|
||||
/* An invalid preparation is not an assessment. */
|
||||
}
|
||||
return { state: 'unknown', evidence: '' };
|
||||
}
|
||||
const pack = (state: string, evidence: string) =>
|
||||
JSON.stringify({ state, evidence });
|
||||
function read(
|
||||
props: unknown,
|
||||
recordId: number,
|
||||
target: number | null,
|
||||
mode: 'submission' | 'decision',
|
||||
actorId: number | null,
|
||||
key?: string,
|
||||
action?: string,
|
||||
): Snapshot | null {
|
||||
if (
|
||||
!object(props) ||
|
||||
!object(props.record) ||
|
||||
props.record.id !== recordId ||
|
||||
!positive(props.record.version) ||
|
||||
typeof props.record.status !== 'string' ||
|
||||
typeof props.owner !== 'boolean' ||
|
||||
typeof props.canEdit !== 'boolean' ||
|
||||
typeof props.acceptingInterests !== 'boolean' ||
|
||||
!Array.isArray(props.interests)
|
||||
)
|
||||
return null;
|
||||
const record = props.record;
|
||||
const item = key
|
||||
? props.interests.find(
|
||||
(item) =>
|
||||
object(item) &&
|
||||
Array.isArray(item.commands) &&
|
||||
item.commands.some(
|
||||
(command) =>
|
||||
object(command) &&
|
||||
command.key === key &&
|
||||
command.action === action,
|
||||
),
|
||||
)
|
||||
: target === null
|
||||
? null
|
||||
: props.interests.find((item) => object(item) && item.id === target);
|
||||
if ((target !== null && !object(item)) || (key && !object(item)))
|
||||
return null;
|
||||
const entry = object(item) ? item : null;
|
||||
if (
|
||||
entry &&
|
||||
(!positive(entry.id) ||
|
||||
!positive(entry.version) ||
|
||||
typeof entry.status !== 'string' ||
|
||||
typeof entry.can_edit !== 'boolean' ||
|
||||
!dictionary(entry.payload) ||
|
||||
!dictionary(entry.assessment) ||
|
||||
!object(entry.match) ||
|
||||
!Array.isArray(entry.match.criteria) ||
|
||||
typeof entry.match.weights_hash !== 'string' ||
|
||||
!/^[a-f0-9]{64}$/.test(entry.match.weights_hash))
|
||||
)
|
||||
return null;
|
||||
const match = entry && object(entry.match) ? entry.match : null;
|
||||
const criteria: Criterion[] = [];
|
||||
for (const candidate of match && Array.isArray(match.criteria)
|
||||
? match.criteria
|
||||
: []) {
|
||||
if (
|
||||
!object(candidate) ||
|
||||
typeof candidate.code !== 'string' ||
|
||||
typeof candidate.label !== 'string' ||
|
||||
typeof candidate.weight !== 'number' ||
|
||||
typeof candidate.mandatory !== 'boolean'
|
||||
)
|
||||
return null;
|
||||
criteria.push({
|
||||
code: candidate.code,
|
||||
label: candidate.label,
|
||||
weight: candidate.weight,
|
||||
mandatory: candidate.mandatory,
|
||||
});
|
||||
}
|
||||
const values: Values = {};
|
||||
if (mode === 'submission') {
|
||||
const payload = entry ? (dictionary(entry.payload) ?? {}) : {};
|
||||
for (const field of ['organization_id', 'proposal']) {
|
||||
const value = text(entry?.[field]);
|
||||
if (value === null) return null;
|
||||
values[field] = value;
|
||||
}
|
||||
for (const field of [
|
||||
'capacity',
|
||||
'availability',
|
||||
'contribution',
|
||||
'conflicts',
|
||||
]) {
|
||||
const value = text(payload[field]);
|
||||
if (value === null) return null;
|
||||
values[field] = value;
|
||||
}
|
||||
values.consent = [true, 1, '1', 'yes', 'on'].includes(
|
||||
payload.consent as string | number | boolean,
|
||||
)
|
||||
? 'yes'
|
||||
: 'no';
|
||||
} else {
|
||||
values.reason = '';
|
||||
const assessment = entry ? (dictionary(entry.assessment) ?? {}) : {};
|
||||
for (const criterion of props.owner ? criteria : []) {
|
||||
const data = assessment[criterion.code];
|
||||
const assessed = object(data) ? data : {};
|
||||
const state = assessed.state ?? 'unknown',
|
||||
evidence = text(assessed.evidence);
|
||||
if (
|
||||
typeof state !== 'string' ||
|
||||
!['met', 'unmet', 'unknown'].includes(state) ||
|
||||
evidence === null
|
||||
)
|
||||
return null;
|
||||
values['criterion:' + criterion.code] = pack(state, evidence);
|
||||
}
|
||||
}
|
||||
const commands: Snapshot['commands'] = [];
|
||||
for (const candidate of entry && Array.isArray(entry.commands)
|
||||
? entry.commands
|
||||
: [])
|
||||
if (
|
||||
object(candidate) &&
|
||||
typeof candidate.key === 'string' &&
|
||||
positive(candidate.version) &&
|
||||
typeof candidate.action === 'string'
|
||||
)
|
||||
commands.push({
|
||||
key: candidate.key,
|
||||
version: candidate.version,
|
||||
action: candidate.action,
|
||||
});
|
||||
const id = entry && positive(entry.id) ? entry.id : null,
|
||||
version = entry && positive(entry.version) ? entry.version : null,
|
||||
status =
|
||||
entry && typeof entry.status === 'string' ? entry.status : 'new';
|
||||
const effectiveRepresentation = entry
|
||||
? entry.can_edit === true
|
||||
: !!actorId && !props.owner;
|
||||
const context =
|
||||
mode === 'submission'
|
||||
? [
|
||||
record.version,
|
||||
record.status,
|
||||
record.deadline,
|
||||
props.owner,
|
||||
effectiveRepresentation,
|
||||
props.acceptingInterests,
|
||||
]
|
||||
: props.owner
|
||||
? [
|
||||
record.version,
|
||||
record.status,
|
||||
record.deadline,
|
||||
props.owner,
|
||||
props.canEdit,
|
||||
match?.weights_hash,
|
||||
criteria,
|
||||
]
|
||||
: [recordId, props.owner, effectiveRepresentation];
|
||||
return {
|
||||
id,
|
||||
version,
|
||||
parentVersion: record.version as number,
|
||||
status,
|
||||
context: JSON.stringify(context),
|
||||
weightsHash:
|
||||
typeof match?.weights_hash === 'string' ? match.weights_hash : '',
|
||||
criteria,
|
||||
owner: props.owner,
|
||||
canSubmit:
|
||||
!!actorId &&
|
||||
!props.owner &&
|
||||
props.acceptingInterests &&
|
||||
(entry
|
||||
? entry.can_edit === true &&
|
||||
['submitted', 'clarification', 'withdrawn'].includes(status)
|
||||
: props.canStartInterest === true),
|
||||
canDecide: props.owner && props.canEdit && !!entry,
|
||||
canWithdraw: !!entry && entry.can_edit === true,
|
||||
values,
|
||||
commands,
|
||||
};
|
||||
}
|
||||
const same = (a: Values, b: Values) =>
|
||||
[...new Set([...Object.keys(a), ...Object.keys(b)])].every(
|
||||
(key) => a[key] === b[key],
|
||||
);
|
||||
function normal(values: Values): Values {
|
||||
return Object.fromEntries(
|
||||
Object.entries(values).map(([key, value]) => [
|
||||
key,
|
||||
key.startsWith('criterion:')
|
||||
? pack(
|
||||
criterionValue(value).state,
|
||||
criterionValue(value).evidence.trim(),
|
||||
)
|
||||
: value.trim(),
|
||||
]),
|
||||
);
|
||||
}
|
||||
type Pending = {
|
||||
command: Record<string, unknown>;
|
||||
values: Values;
|
||||
generations: Record<string, number>;
|
||||
action: string;
|
||||
base: Snapshot;
|
||||
ambiguous: boolean;
|
||||
};
|
||||
export function useCandidacyEdit({
|
||||
props,
|
||||
recordId,
|
||||
interestId = null,
|
||||
mode,
|
||||
actorId,
|
||||
}: {
|
||||
props: unknown;
|
||||
recordId: number;
|
||||
interestId?: number | null;
|
||||
mode: 'submission' | 'decision';
|
||||
actorId: number | null;
|
||||
}) {
|
||||
const [resolved, setResolved] = useState<number | null>(interestId);
|
||||
const target = interestId ?? resolved;
|
||||
const current = read(props, recordId, target, mode, actorId);
|
||||
const initial = useRef(current);
|
||||
const criterionLabels = useRef(
|
||||
new Map(
|
||||
(current?.criteria ?? []).map((criterion) => [
|
||||
criterion.code,
|
||||
criterion.label,
|
||||
]),
|
||||
),
|
||||
);
|
||||
for (const criterion of current?.criteria ?? [])
|
||||
criterionLabels.current.set(criterion.code, criterion.label);
|
||||
const identity = JSON.stringify([recordId, interestId, mode, actorId]);
|
||||
const opened = useRef(identity);
|
||||
const observed = useRef(identity);
|
||||
observed.current = identity;
|
||||
const empty: Values =
|
||||
mode === 'submission'
|
||||
? {
|
||||
organization_id: '',
|
||||
proposal: '',
|
||||
capacity: '',
|
||||
availability: '',
|
||||
contribution: '',
|
||||
conflicts: '',
|
||||
consent: 'no',
|
||||
}
|
||||
: { reason: '' };
|
||||
const form = useForm<{ values: Values }>({
|
||||
values: current?.values ?? empty,
|
||||
});
|
||||
const live = useRef(form.data.values);
|
||||
live.current = form.data.values;
|
||||
const edited = useRef(new Set<string>()),
|
||||
generations = useRef<Record<string, number>>({});
|
||||
const pending = useRef<Pending | null>(null);
|
||||
const [choices, setChoices] = useState<Record<string, 'mine' | 'current'>>(
|
||||
{},
|
||||
);
|
||||
const [refreshing, setRefreshing] = useState(false),
|
||||
[needsCompare, setNeedsCompare] = useState(false),
|
||||
[problem, setProblem] = useState<string | null>(null);
|
||||
const base = initial.current;
|
||||
const keys = [
|
||||
...new Set([
|
||||
...Object.keys(base?.values ?? empty),
|
||||
...Object.keys(current?.values ?? {}),
|
||||
]),
|
||||
];
|
||||
const invalid =
|
||||
!current ||
|
||||
!base ||
|
||||
opened.current !== observed.current ||
|
||||
current.id !== base.id;
|
||||
const stale =
|
||||
!!current &&
|
||||
!!base &&
|
||||
(current.version !== base.version ||
|
||||
current.context !== base.context ||
|
||||
current.status !== base.status ||
|
||||
!same(current.values, base.values));
|
||||
const changed =
|
||||
current && base
|
||||
? keys.filter((key) => current.values[key] !== base.values[key])
|
||||
: [];
|
||||
const conflicts = current
|
||||
? changed.filter(
|
||||
(key) =>
|
||||
Object.hasOwn(current.values, key) &&
|
||||
edited.current.has(key) &&
|
||||
live.current[key] !== current.values[key],
|
||||
)
|
||||
: [];
|
||||
const choiceKey = (key: string) =>
|
||||
JSON.stringify([
|
||||
current?.id,
|
||||
current?.version,
|
||||
current?.context,
|
||||
key,
|
||||
current?.values[key],
|
||||
]);
|
||||
const unresolved = conflicts.filter(
|
||||
(key) => choices[choiceKey(key)] !== 'mine',
|
||||
);
|
||||
const active =
|
||||
!!current &&
|
||||
['submitted', 'clarification', 'shortlisted'].includes(current.status);
|
||||
const editable =
|
||||
!!current &&
|
||||
(mode === 'submission'
|
||||
? current.canSubmit
|
||||
: active &&
|
||||
(current.owner ? current.canDecide : current.canWithdraw));
|
||||
const canRecover = (action: string) =>
|
||||
!!current &&
|
||||
(action === 'submit'
|
||||
? current.id === null
|
||||
? !!actorId && !current.owner
|
||||
: current.canWithdraw
|
||||
: action === 'withdraw'
|
||||
? current.canWithdraw
|
||||
: current.canDecide);
|
||||
const recovering = !!pending.current?.ambiguous;
|
||||
const blocked =
|
||||
invalid ||
|
||||
refreshing ||
|
||||
form.processing ||
|
||||
(recovering && pending.current
|
||||
? !canRecover(pending.current.action)
|
||||
: stale || needsCompare || !editable);
|
||||
const dirty =
|
||||
!!pending.current ||
|
||||
(!!base &&
|
||||
(!same(live.current, base.values) ||
|
||||
keys.some(
|
||||
(key) =>
|
||||
edited.current.has(key) &&
|
||||
current &&
|
||||
live.current[key] !== current.values[key],
|
||||
)));
|
||||
const retired = Object.keys(live.current).filter(
|
||||
(key) =>
|
||||
key.startsWith('criterion:') &&
|
||||
!current?.criteria.some(
|
||||
(criterion) => 'criterion:' + criterion.code === key,
|
||||
),
|
||||
);
|
||||
useEffect(() => {
|
||||
if (
|
||||
!current ||
|
||||
invalid ||
|
||||
!stale ||
|
||||
dirty ||
|
||||
edited.current.size > 0 ||
|
||||
pending.current ||
|
||||
form.processing ||
|
||||
needsCompare
|
||||
)
|
||||
return;
|
||||
initial.current = current;
|
||||
live.current = { ...current.values };
|
||||
form.setDefaults({ values: live.current });
|
||||
form.setData({ values: live.current });
|
||||
}, [current, invalid, stale, dirty, form.processing, needsCompare]);
|
||||
function change(key: string, value: string) {
|
||||
if (!keys.includes(key)) return;
|
||||
edited.current.add(key);
|
||||
generations.current[key] = (generations.current[key] ?? 0) + 1;
|
||||
live.current = { ...live.current, [key]: value };
|
||||
form.setData({ values: live.current });
|
||||
setChoices((previous) => {
|
||||
const next = { ...previous };
|
||||
delete next[choiceKey(key)];
|
||||
return next;
|
||||
});
|
||||
}
|
||||
function changeCriterion(
|
||||
code: string,
|
||||
field: 'state' | 'evidence',
|
||||
value: string,
|
||||
) {
|
||||
const key = 'criterion:' + code,
|
||||
data = criterionValue(live.current[key]);
|
||||
change(key, JSON.stringify({ ...data, [field]: value }));
|
||||
}
|
||||
function discardRetired() {
|
||||
if (form.processing || pending.current) return;
|
||||
const values = { ...live.current };
|
||||
for (const key of retired) {
|
||||
delete values[key];
|
||||
edited.current.delete(key);
|
||||
}
|
||||
live.current = values;
|
||||
form.setData({ values });
|
||||
}
|
||||
function choose(key: string, value: 'mine' | 'current') {
|
||||
if (!current) return;
|
||||
if (value === 'current') change(key, current.values[key] ?? '');
|
||||
setChoices((previous) => ({ ...previous, [choiceKey(key)]: value }));
|
||||
}
|
||||
function adopt() {
|
||||
if (
|
||||
!current ||
|
||||
invalid ||
|
||||
!stale ||
|
||||
unresolved.length ||
|
||||
refreshing ||
|
||||
form.processing
|
||||
)
|
||||
return;
|
||||
const values = { ...current.values };
|
||||
for (const key of Object.keys(live.current))
|
||||
if (edited.current.has(key)) values[key] = live.current[key];
|
||||
initial.current = current;
|
||||
live.current = values;
|
||||
pending.current = null;
|
||||
form.setDefaults({ values: current.values });
|
||||
form.setData({ values });
|
||||
form.clearErrors();
|
||||
setChoices({});
|
||||
setNeedsCompare(false);
|
||||
setProblem(null);
|
||||
}
|
||||
function refresh() {
|
||||
if (refreshing || form.processing) return;
|
||||
setRefreshing(true);
|
||||
router.reload({
|
||||
only: [
|
||||
'record',
|
||||
'interests',
|
||||
'owner',
|
||||
'canEdit',
|
||||
'moderator',
|
||||
'publicationActions',
|
||||
'publicationCommands',
|
||||
'historySummary',
|
||||
'acceptingInterests',
|
||||
'organizations',
|
||||
],
|
||||
onSuccess: (page) => {
|
||||
const fresh = read(page.props, recordId, target, mode, actorId);
|
||||
if (
|
||||
fresh &&
|
||||
initial.current &&
|
||||
fresh.id === initial.current.id &&
|
||||
fresh.version === initial.current.version &&
|
||||
fresh.context === initial.current.context &&
|
||||
fresh.status === initial.current.status &&
|
||||
same(fresh.values, initial.current.values)
|
||||
) {
|
||||
setNeedsCompare(false);
|
||||
setProblem(null);
|
||||
}
|
||||
},
|
||||
onHttpException: () => {
|
||||
setProblem(
|
||||
'Não foi possível recuperar esta candidatura com o acesso actual. A preparação foi conservada.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
onNetworkError: () => {
|
||||
setProblem(
|
||||
'A recuperação não foi confirmada. A preparação foi conservada.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
onFinish: () => setRefreshing(false),
|
||||
});
|
||||
}
|
||||
function submit(
|
||||
requestedAction = mode === 'submission' ? 'submit' : 'assess',
|
||||
) {
|
||||
if (blocked || !current || !base) return;
|
||||
const action = pending.current?.action ?? requestedAction;
|
||||
if (!recovering) {
|
||||
if (
|
||||
mode === 'decision' &&
|
||||
(action === 'withdraw'
|
||||
? !current.canWithdraw
|
||||
: !current.canDecide)
|
||||
)
|
||||
return;
|
||||
if (action === 'connect' && current.status !== 'shortlisted')
|
||||
return;
|
||||
}
|
||||
let operation = pending.current;
|
||||
if (!operation) {
|
||||
const values = { ...live.current };
|
||||
const command: Record<string, unknown> =
|
||||
mode === 'submission'
|
||||
? {
|
||||
interest_id: target,
|
||||
version: current.version,
|
||||
partnership_version: current.parentVersion,
|
||||
organization_id: values.organization_id,
|
||||
proposal: values.proposal,
|
||||
payload: {
|
||||
capacity: values.capacity,
|
||||
availability: values.availability,
|
||||
contribution: values.contribution,
|
||||
conflicts: values.conflicts,
|
||||
consent: values.consent === 'yes',
|
||||
},
|
||||
}
|
||||
: {
|
||||
version: current.version,
|
||||
action,
|
||||
reason: values.reason,
|
||||
assessment:
|
||||
action === 'assess'
|
||||
? Object.fromEntries(
|
||||
current.criteria.map((criterion) => [
|
||||
criterion.code,
|
||||
criterionValue(
|
||||
values[
|
||||
'criterion:' +
|
||||
criterion.code
|
||||
],
|
||||
),
|
||||
]),
|
||||
)
|
||||
: {},
|
||||
...(action === 'withdraw'
|
||||
? {}
|
||||
: {
|
||||
partnership_version: current.parentVersion,
|
||||
weights_hash: current.weightsHash,
|
||||
}),
|
||||
};
|
||||
command.client_key = createOperationKey();
|
||||
operation = {
|
||||
command,
|
||||
values,
|
||||
generations: { ...generations.current },
|
||||
base: current,
|
||||
action,
|
||||
ambiguous: false,
|
||||
};
|
||||
pending.current = operation;
|
||||
}
|
||||
const sent = operation;
|
||||
setProblem(null);
|
||||
form.transform(() => sent.command);
|
||||
const unknown = () => {
|
||||
if (pending.current) pending.current.ambiguous = true;
|
||||
setProblem(
|
||||
'A operação não foi confirmada. Recuperar repete o pedido original; as alterações posteriores foram conservadas.',
|
||||
);
|
||||
return false;
|
||||
};
|
||||
form.post(
|
||||
mode === 'submission'
|
||||
? `/parcerias/${recordId}/interesses`
|
||||
: `/parcerias/candidaturas/${target}`,
|
||||
{
|
||||
preserveScroll: true,
|
||||
onSuccess: (page) => {
|
||||
if (observed.current !== opened.current) return;
|
||||
const saved = read(
|
||||
page.props,
|
||||
recordId,
|
||||
target,
|
||||
mode,
|
||||
actorId,
|
||||
String(sent.command.client_key),
|
||||
sent.action,
|
||||
);
|
||||
const acknowledgement = saved?.commands.find(
|
||||
(command) =>
|
||||
command.key === sent.command.client_key &&
|
||||
command.action === sent.action,
|
||||
);
|
||||
if (!saved || saved.id === null || !acknowledgement) {
|
||||
unknown();
|
||||
return;
|
||||
}
|
||||
const acknowledgedKeys =
|
||||
mode === 'decision' && sent.action === 'assess'
|
||||
? [
|
||||
'reason',
|
||||
...sent.base.criteria.map(
|
||||
(criterion) =>
|
||||
'criterion:' + criterion.code,
|
||||
),
|
||||
]
|
||||
: null;
|
||||
const submittedValues = acknowledgedKeys
|
||||
? Object.fromEntries(
|
||||
acknowledgedKeys.map((key) => [
|
||||
key,
|
||||
sent.values[key],
|
||||
]),
|
||||
)
|
||||
: mode === 'submission'
|
||||
? sent.values
|
||||
: sent.base.values;
|
||||
const expected = normal(submittedValues);
|
||||
if (mode === 'decision') expected.reason = '';
|
||||
const actualExpectedVersion =
|
||||
sent.base.version === null ? 1 : sent.base.version + 1;
|
||||
if (
|
||||
acknowledgement.version !== actualExpectedVersion ||
|
||||
(target !== null && saved.id !== target)
|
||||
) {
|
||||
unknown();
|
||||
return;
|
||||
}
|
||||
const exact =
|
||||
saved.version === acknowledgement.version &&
|
||||
saved.context === sent.base.context &&
|
||||
same(saved.values, expected);
|
||||
const merged = { ...expected };
|
||||
const oldEdited = new Set(edited.current);
|
||||
edited.current.clear();
|
||||
for (const key of Object.keys(live.current)) {
|
||||
const sentCriterion =
|
||||
!key.startsWith('criterion:') ||
|
||||
sent.base.criteria.some(
|
||||
(criterion) =>
|
||||
'criterion:' + criterion.code === key,
|
||||
);
|
||||
if (
|
||||
(generations.current[key] ?? 0) !==
|
||||
(sent.generations[key] ?? 0) ||
|
||||
(mode === 'decision' &&
|
||||
(sent.action !== 'assess' || !sentCriterion) &&
|
||||
key !== 'reason' &&
|
||||
oldEdited.has(key))
|
||||
) {
|
||||
merged[key] = live.current[key];
|
||||
edited.current.add(key);
|
||||
}
|
||||
}
|
||||
initial.current = exact
|
||||
? saved
|
||||
: {
|
||||
...saved,
|
||||
version: acknowledgement.version,
|
||||
context: sent.base.context,
|
||||
parentVersion: sent.base.parentVersion,
|
||||
values: expected,
|
||||
};
|
||||
if (target === null) setResolved(saved.id);
|
||||
pending.current = null;
|
||||
live.current = merged;
|
||||
form.setDefaults({ values: expected });
|
||||
form.setData({ values: merged });
|
||||
form.clearErrors();
|
||||
setChoices({});
|
||||
setNeedsCompare(!exact);
|
||||
setProblem(
|
||||
exact
|
||||
? null
|
||||
: 'A operação original foi identificada, mas a candidatura ou o contexto tem dados posteriores. Compare antes de continuar; a preparação foi conservada.',
|
||||
);
|
||||
},
|
||||
onError: () => {
|
||||
if (!pending.current?.ambiguous) pending.current = null;
|
||||
},
|
||||
onHttpException: (response) => {
|
||||
if (
|
||||
response.status >= 500 ||
|
||||
response.status === 409 ||
|
||||
pending.current?.ambiguous
|
||||
) {
|
||||
if (response.status === 409) setNeedsCompare(true);
|
||||
return unknown();
|
||||
}
|
||||
pending.current = null;
|
||||
setProblem(
|
||||
'Não foi possível confirmar esta operação com o acesso actual. A preparação foi conservada.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
onNetworkError: unknown,
|
||||
onCancel: unknown,
|
||||
},
|
||||
);
|
||||
}
|
||||
return {
|
||||
form,
|
||||
values: form.data.values,
|
||||
current: current?.values ?? empty,
|
||||
currentSnapshot: current,
|
||||
criteria: current?.criteria ?? base?.criteria ?? [],
|
||||
criterionLabels: Object.fromEntries(criterionLabels.current),
|
||||
retired,
|
||||
activeId: target,
|
||||
editable,
|
||||
ownerMode: current?.owner ?? base?.owner ?? false,
|
||||
status: current?.status,
|
||||
version: current?.version,
|
||||
baseVersion: base?.version,
|
||||
stale,
|
||||
invalid,
|
||||
changed,
|
||||
conflicts,
|
||||
unresolved,
|
||||
refreshing,
|
||||
blocked,
|
||||
dirty,
|
||||
problem,
|
||||
recovering,
|
||||
pendingAction: pending.current?.action,
|
||||
change,
|
||||
changeCriterion,
|
||||
discardRetired,
|
||||
choose,
|
||||
adopt,
|
||||
refresh,
|
||||
submit,
|
||||
};
|
||||
}
|
||||
export type CandidacyEditor = ReturnType<typeof useCandidacyEdit>;
|
||||
export function useCandidacyLeaveGuard(dirty: boolean) {
|
||||
const current = useRef(dirty);
|
||||
current.current = dirty;
|
||||
useEffect(() => {
|
||||
const leave = (event: BeforeUnloadEvent) => {
|
||||
if (current.current) {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
}
|
||||
};
|
||||
const stop = router.on('before', (event) => {
|
||||
if (
|
||||
current.current &&
|
||||
event.detail.visit.method === 'get' &&
|
||||
event.detail.visit.preserveState !== true &&
|
||||
!window.confirm(
|
||||
'Há preparação ou acções por confirmar nesta parceria. Pretende sair sem as conservar?',
|
||||
)
|
||||
)
|
||||
event.preventDefault();
|
||||
});
|
||||
window.addEventListener('beforeunload', leave);
|
||||
return () => {
|
||||
stop();
|
||||
window.removeEventListener('beforeunload', leave);
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
@@ -0,0 +1,862 @@
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { createOperationKey } from '@/lib/operation-key';
|
||||
import type { Partnership } from '@/pages/partnerships/shared';
|
||||
|
||||
export type PartnershipLocation = {
|
||||
geo_location_id: string;
|
||||
role: string;
|
||||
source_reference: string;
|
||||
};
|
||||
export type PartnershipOrigin = { type: string; target_id: string };
|
||||
export type PartnershipEditProps = {
|
||||
editorActorId?: number;
|
||||
saveCommands?: { key: string; version: number }[];
|
||||
record: Partnership | null;
|
||||
locations: PartnershipLocation[];
|
||||
origins: PartnershipOrigin[];
|
||||
};
|
||||
type Payload = {
|
||||
summary: string;
|
||||
requirements: string;
|
||||
mandatory: string[];
|
||||
confidentiality: string;
|
||||
consent: boolean;
|
||||
availability: string;
|
||||
};
|
||||
type Sections = Payload & {
|
||||
title: string;
|
||||
offer: string;
|
||||
seeking: string;
|
||||
organization_id: string;
|
||||
sector_id: string;
|
||||
kind: string;
|
||||
partnership_type: string;
|
||||
deadline: string;
|
||||
locations: PartnershipLocation[];
|
||||
origins: PartnershipOrigin[];
|
||||
};
|
||||
type Draft = Omit<Sections, keyof Payload> & {
|
||||
payload: Payload;
|
||||
client_key: string;
|
||||
version: number | null;
|
||||
};
|
||||
type Snapshot = {
|
||||
actorId: number | null;
|
||||
commands: { key: string; version: number }[];
|
||||
id: number | null;
|
||||
version: number | null;
|
||||
status: string;
|
||||
clientKey: string | null;
|
||||
values: Sections;
|
||||
};
|
||||
const textKeys = [
|
||||
'title',
|
||||
'offer',
|
||||
'seeking',
|
||||
'organization_id',
|
||||
'sector_id',
|
||||
'kind',
|
||||
'partnership_type',
|
||||
'deadline',
|
||||
'summary',
|
||||
'requirements',
|
||||
'confidentiality',
|
||||
'availability',
|
||||
] as const;
|
||||
const keys = [
|
||||
...textKeys,
|
||||
'mandatory',
|
||||
'consent',
|
||||
'locations',
|
||||
'origins',
|
||||
] as const;
|
||||
export type PartnershipSection = (typeof keys)[number];
|
||||
const editableStates = ['draft', 'returned', 'rejected', 'published'];
|
||||
function object(value: unknown): value is Record<string, unknown> {
|
||||
return !!value && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
function text(value: unknown, fallback = '') {
|
||||
return value == null
|
||||
? fallback
|
||||
: typeof value === 'string'
|
||||
? value
|
||||
: undefined;
|
||||
}
|
||||
function bool(value: unknown) {
|
||||
return value == null
|
||||
? false
|
||||
: value === true || value === 1 || value === '1'
|
||||
? true
|
||||
: value === false || value === 0 || value === '0'
|
||||
? false
|
||||
: undefined;
|
||||
}
|
||||
function location(value: unknown): value is PartnershipLocation {
|
||||
return (
|
||||
object(value) &&
|
||||
typeof value.geo_location_id === 'string' &&
|
||||
typeof value.role === 'string' &&
|
||||
typeof value.source_reference === 'string'
|
||||
);
|
||||
}
|
||||
function origin(value: unknown): value is PartnershipOrigin {
|
||||
return (
|
||||
object(value) &&
|
||||
typeof value.type === 'string' &&
|
||||
typeof value.target_id === 'string'
|
||||
);
|
||||
}
|
||||
function validSections(value: unknown): value is Sections {
|
||||
return (
|
||||
object(value) &&
|
||||
textKeys.every((key) => typeof value[key] === 'string') &&
|
||||
typeof value.consent === 'boolean' &&
|
||||
Array.isArray(value.mandatory) &&
|
||||
value.mandatory.every((item) => typeof item === 'string') &&
|
||||
Array.isArray(value.locations) &&
|
||||
value.locations.every(location) &&
|
||||
Array.isArray(value.origins) &&
|
||||
value.origins.every(origin)
|
||||
);
|
||||
}
|
||||
function readSnapshot(props: unknown): Snapshot | null {
|
||||
if (
|
||||
!object(props) ||
|
||||
!Array.isArray(props.locations) ||
|
||||
!Array.isArray(props.origins)
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
props.editorActorId !== undefined &&
|
||||
(typeof props.editorActorId !== 'number' ||
|
||||
!Number.isSafeInteger(props.editorActorId) ||
|
||||
props.editorActorId < 1)
|
||||
)
|
||||
return null;
|
||||
if (
|
||||
props.saveCommands !== undefined &&
|
||||
(!Array.isArray(props.saveCommands) ||
|
||||
!props.saveCommands.every(
|
||||
(value) =>
|
||||
object(value) &&
|
||||
typeof value.key === 'string' &&
|
||||
typeof value.version === 'number' &&
|
||||
Number.isSafeInteger(value.version) &&
|
||||
value.version > 0,
|
||||
))
|
||||
)
|
||||
return null;
|
||||
const record = props.record;
|
||||
if (
|
||||
record !== null &&
|
||||
(!object(record) ||
|
||||
!Number.isSafeInteger(record.id) ||
|
||||
typeof record.id !== 'number' ||
|
||||
record.id < 1 ||
|
||||
!Number.isSafeInteger(record.version) ||
|
||||
typeof record.version !== 'number' ||
|
||||
record.version < 1 ||
|
||||
typeof record.status !== 'string' ||
|
||||
(!object(record.payload) &&
|
||||
!(
|
||||
Array.isArray(record.payload) && record.payload.length === 0
|
||||
)))
|
||||
)
|
||||
return null;
|
||||
const row = object(record) ? record : {};
|
||||
const payload = object(row.payload) ? row.payload : {};
|
||||
const values = {
|
||||
title: text(row.title),
|
||||
offer: text(row.offer),
|
||||
seeking: text(row.seeking),
|
||||
organization_id: text(row.organization_id),
|
||||
sector_id:
|
||||
row.sector_id == null
|
||||
? ''
|
||||
: typeof row.sector_id === 'number'
|
||||
? String(row.sector_id)
|
||||
: undefined,
|
||||
kind: text(row.kind, 'seeking'),
|
||||
partnership_type: text(row.partnership_type),
|
||||
deadline: text(row.deadline),
|
||||
summary: text(payload.summary),
|
||||
requirements: text(payload.requirements),
|
||||
mandatory: payload.mandatory ?? [],
|
||||
confidentiality: text(payload.confidentiality, 'public'),
|
||||
consent: bool(payload.consent),
|
||||
availability: text(payload.availability),
|
||||
locations: props.locations.map((item) =>
|
||||
object(item)
|
||||
? {
|
||||
geo_location_id: item.geo_location_id,
|
||||
role: item.role,
|
||||
source_reference: text(item.source_reference),
|
||||
}
|
||||
: null,
|
||||
),
|
||||
origins: props.origins.map((item) =>
|
||||
object(item)
|
||||
? { type: item.type, target_id: item.target_id }
|
||||
: null,
|
||||
),
|
||||
};
|
||||
if (!validSections(values)) return null;
|
||||
return {
|
||||
actorId:
|
||||
typeof props.editorActorId === 'number'
|
||||
? props.editorActorId
|
||||
: null,
|
||||
commands: Array.isArray(props.saveCommands)
|
||||
? props.saveCommands.map((value) => ({
|
||||
key: value.key,
|
||||
version: value.version,
|
||||
}))
|
||||
: [],
|
||||
id: typeof row.id === 'number' ? row.id : null,
|
||||
version: typeof row.version === 'number' ? row.version : null,
|
||||
status: typeof row.status === 'string' ? row.status : 'draft',
|
||||
clientKey: typeof row.client_key === 'string' ? row.client_key : null,
|
||||
values,
|
||||
};
|
||||
}
|
||||
function toDraft(
|
||||
values: Sections,
|
||||
client_key: string,
|
||||
version: number | null,
|
||||
): Draft {
|
||||
const {
|
||||
summary,
|
||||
requirements,
|
||||
mandatory,
|
||||
confidentiality,
|
||||
consent,
|
||||
availability,
|
||||
...fields
|
||||
} = values;
|
||||
return {
|
||||
...fields,
|
||||
client_key,
|
||||
version,
|
||||
payload: {
|
||||
summary,
|
||||
requirements,
|
||||
mandatory,
|
||||
confidentiality,
|
||||
consent,
|
||||
availability,
|
||||
},
|
||||
};
|
||||
}
|
||||
function sections({
|
||||
payload,
|
||||
client_key: _key,
|
||||
version: _version,
|
||||
...fields
|
||||
}: Draft): Sections {
|
||||
return { ...fields, ...payload };
|
||||
}
|
||||
function canonical(value: Sections[PartnershipSection]) {
|
||||
return JSON.stringify(
|
||||
Array.isArray(value)
|
||||
? value.map((item) => JSON.stringify(item)).sort()
|
||||
: value,
|
||||
);
|
||||
}
|
||||
function equal(
|
||||
a: Sections[PartnershipSection],
|
||||
b: Sections[PartnershipSection],
|
||||
) {
|
||||
return canonical(a) === canonical(b);
|
||||
}
|
||||
function same(a: Sections, b: Sections) {
|
||||
return keys.every((key) => equal(a[key], b[key]));
|
||||
}
|
||||
function normalised(values: Sections): Sections {
|
||||
const result = { ...values };
|
||||
for (const key of textKeys) result[key] = result[key].trim();
|
||||
return {
|
||||
...result,
|
||||
locations: result.locations.map((item) => ({
|
||||
geo_location_id: item.geo_location_id.trim(),
|
||||
role: item.role.trim(),
|
||||
source_reference: item.source_reference.trim(),
|
||||
})),
|
||||
origins: result.origins.map((item) => ({
|
||||
type: item.type.trim(),
|
||||
target_id: item.target_id.trim(),
|
||||
})),
|
||||
};
|
||||
}
|
||||
const empty = readSnapshot({ record: null, locations: [], origins: [] });
|
||||
if (!empty) throw new Error('Empty partnership editor definition is invalid.');
|
||||
const emptyValues = empty.values;
|
||||
export function usePartnershipEdit(props: PartnershipEditProps) {
|
||||
const alive = useRef(true);
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
};
|
||||
}, []);
|
||||
const current = readSnapshot(props);
|
||||
const operationKey = useRef(createOperationKey());
|
||||
const form = useForm(
|
||||
toDraft(
|
||||
current?.values ?? emptyValues,
|
||||
operationKey.current,
|
||||
current?.version ?? null,
|
||||
),
|
||||
);
|
||||
const base = useRef(current);
|
||||
const live = useRef(form.data);
|
||||
live.current = form.data;
|
||||
const identity = useRef(current?.id ?? null);
|
||||
identity.current = current?.id ?? null;
|
||||
const edited = useRef(new Set<PartnershipSection>());
|
||||
const generation = useRef<Partial<Record<PartnershipSection, number>>>({});
|
||||
const pendingCreation = useRef<{
|
||||
command: Draft;
|
||||
generation: Partial<Record<PartnershipSection, number>>;
|
||||
ambiguous: boolean;
|
||||
} | null>(null);
|
||||
const createdId = useRef<number | null>(null);
|
||||
const pendingUpdate = useRef<{
|
||||
id: number;
|
||||
command: Draft & { operation_key: string };
|
||||
generation: Partial<Record<PartnershipSection, number>>;
|
||||
base: Snapshot;
|
||||
ambiguous: boolean;
|
||||
} | null>(null);
|
||||
const [choices, setChoices] = useState<Record<string, 'mine' | 'current'>>(
|
||||
{},
|
||||
);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [problem, setProblem] = useState<string | null>(null);
|
||||
const [needsCompare, setNeedsCompare] = useState(false);
|
||||
const [mustRefresh, setMustRefresh] = useState(false),
|
||||
[accessDenied, setAccessDenied] = useState(false);
|
||||
const own = sections(form.data);
|
||||
const invalid =
|
||||
!current ||
|
||||
!base.current ||
|
||||
current.actorId !== base.current.actorId ||
|
||||
(current.id !== base.current.id &&
|
||||
!(
|
||||
base.current.id === null &&
|
||||
(current.id === createdId.current ||
|
||||
current.clientKey ===
|
||||
pendingCreation.current?.command.client_key)
|
||||
));
|
||||
const stale =
|
||||
!!current &&
|
||||
!!base.current &&
|
||||
(current.id !== base.current.id ||
|
||||
current.version !== base.current.version ||
|
||||
current.status !== base.current.status ||
|
||||
!same(current.values, base.current.values));
|
||||
const baseline = base.current;
|
||||
const changed =
|
||||
current && baseline
|
||||
? keys.filter(
|
||||
(key) => !equal(current.values[key], baseline.values[key]),
|
||||
)
|
||||
: [];
|
||||
const conflicts = current
|
||||
? changed.filter(
|
||||
(key) =>
|
||||
edited.current.has(key) &&
|
||||
!equal(own[key], current.values[key]),
|
||||
)
|
||||
: [];
|
||||
const choiceKey = (key: PartnershipSection) =>
|
||||
JSON.stringify([
|
||||
current?.id,
|
||||
current?.version,
|
||||
current?.status,
|
||||
key,
|
||||
current ? canonical(current.values[key]) : '',
|
||||
]);
|
||||
const unresolved = conflicts.filter(
|
||||
(key) => choices[choiceKey(key)] !== 'mine',
|
||||
);
|
||||
const editable = !!current && editableStates.includes(current.status);
|
||||
const blocked =
|
||||
invalid ||
|
||||
stale ||
|
||||
refreshing ||
|
||||
needsCompare ||
|
||||
accessDenied ||
|
||||
!!pendingUpdate.current ||
|
||||
!editable;
|
||||
const dirty =
|
||||
!!baseline &&
|
||||
(!!pendingUpdate.current ||
|
||||
!!pendingCreation.current ||
|
||||
!same(own, baseline.values) ||
|
||||
(!!current &&
|
||||
keys.some(
|
||||
(key) =>
|
||||
edited.current.has(key) &&
|
||||
!equal(own[key], current.values[key]),
|
||||
)));
|
||||
useEffect(() => {
|
||||
const leave = (event: BeforeUnloadEvent) => {
|
||||
if (dirty) {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
}
|
||||
};
|
||||
const stop = router.on('before', (event) => {
|
||||
if (
|
||||
dirty &&
|
||||
event.detail.visit.method === 'get' &&
|
||||
event.detail.visit.preserveState !== true &&
|
||||
!window.confirm(
|
||||
'Há alterações por guardar na parceria. Pretende sair sem as guardar?',
|
||||
)
|
||||
)
|
||||
event.preventDefault();
|
||||
});
|
||||
window.addEventListener('beforeunload', leave);
|
||||
return () => {
|
||||
stop();
|
||||
window.removeEventListener('beforeunload', leave);
|
||||
};
|
||||
}, [dirty]);
|
||||
function replace(next: Draft) {
|
||||
const previous = sections(live.current),
|
||||
after = sections(next);
|
||||
const changed = keys.filter((key) => !equal(previous[key], after[key]));
|
||||
for (const key of changed) {
|
||||
edited.current.add(key);
|
||||
generation.current[key] = (generation.current[key] ?? 0) + 1;
|
||||
}
|
||||
live.current = next;
|
||||
form.setData(() => next);
|
||||
setChoices((previous) => {
|
||||
const next = { ...previous };
|
||||
for (const key of changed) delete next[choiceKey(key)];
|
||||
return next;
|
||||
});
|
||||
}
|
||||
function setData<K extends keyof Draft>(
|
||||
key: K,
|
||||
value: Draft[K] | ((previous: Draft[K]) => Draft[K]),
|
||||
) {
|
||||
const next =
|
||||
typeof value === 'function' ? value(live.current[key]) : value;
|
||||
replace({ ...live.current, [key]: next });
|
||||
}
|
||||
function choose(key: PartnershipSection, choice: 'mine' | 'current') {
|
||||
if (!current) return;
|
||||
if (choice === 'current')
|
||||
replace(
|
||||
toDraft(
|
||||
{ ...sections(live.current), [key]: current.values[key] },
|
||||
live.current.client_key,
|
||||
live.current.version,
|
||||
),
|
||||
);
|
||||
setChoices((previous) => ({ ...previous, [choiceKey(key)]: choice }));
|
||||
}
|
||||
function adopt() {
|
||||
if (
|
||||
!current ||
|
||||
(!stale && !pendingUpdate.current?.ambiguous && !needsCompare) ||
|
||||
invalid ||
|
||||
refreshing ||
|
||||
form.processing ||
|
||||
unresolved.length
|
||||
)
|
||||
return;
|
||||
if (mustRefresh) return;
|
||||
const selected = { ...current.values };
|
||||
for (const key of keys)
|
||||
if (edited.current.has(key))
|
||||
Object.assign(selected, { [key]: sections(live.current)[key] });
|
||||
const saved = toDraft(
|
||||
current.values,
|
||||
current.clientKey ?? live.current.client_key,
|
||||
current.version,
|
||||
);
|
||||
base.current = current;
|
||||
createdId.current = null;
|
||||
pendingCreation.current = null;
|
||||
pendingUpdate.current = null;
|
||||
form.setDefaults(saved);
|
||||
live.current = toDraft(selected, saved.client_key, saved.version);
|
||||
form.setData(live.current);
|
||||
form.clearErrors();
|
||||
setProblem(null);
|
||||
setNeedsCompare(false);
|
||||
setChoices({});
|
||||
}
|
||||
function refresh() {
|
||||
if (refreshing || form.processing) return;
|
||||
setRefreshing(true);
|
||||
router.reload({
|
||||
only: [
|
||||
'record',
|
||||
'locations',
|
||||
'origins',
|
||||
'editorActorId',
|
||||
'saveCommands',
|
||||
],
|
||||
onSuccess: (page) => {
|
||||
if (!alive.current) return;
|
||||
if (
|
||||
pendingUpdate.current &&
|
||||
acknowledgeUpdate(page.props, pendingUpdate.current)
|
||||
)
|
||||
return;
|
||||
const fresh = readSnapshot(page.props);
|
||||
if (
|
||||
!fresh ||
|
||||
fresh.actorId !== base.current?.actorId ||
|
||||
fresh.id !== base.current?.id
|
||||
) {
|
||||
setProblem(
|
||||
'A resposta não corresponde a esta conta e parceria. A preparação foi conservada.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
setMustRefresh(false);
|
||||
setAccessDenied(false);
|
||||
if (
|
||||
fresh &&
|
||||
base.current &&
|
||||
fresh.id === base.current.id &&
|
||||
fresh.version === base.current.version &&
|
||||
fresh.status === base.current.status &&
|
||||
same(fresh.values, base.current.values)
|
||||
) {
|
||||
setNeedsCompare(false);
|
||||
setProblem(null);
|
||||
}
|
||||
},
|
||||
onHttpException: () => {
|
||||
if (!alive.current) return false;
|
||||
setAccessDenied(true);
|
||||
setMustRefresh(true);
|
||||
setProblem(
|
||||
'Não foi possível recuperar esta parceria com o acesso actual. As suas edições foram conservadas.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
onNetworkError: () => {
|
||||
if (!alive.current) return false;
|
||||
setProblem(
|
||||
'A recuperação não foi confirmada. As suas edições foram conservadas.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
onFinish: () => {
|
||||
if (alive.current) setRefreshing(false);
|
||||
},
|
||||
});
|
||||
}
|
||||
function applySaved(
|
||||
saved: Snapshot,
|
||||
command: Draft,
|
||||
sentGeneration: Partial<Record<PartnershipSection, number>>,
|
||||
later = false,
|
||||
) {
|
||||
const merged = { ...saved.values };
|
||||
edited.current.clear();
|
||||
for (const key of keys)
|
||||
if ((generation.current[key] ?? 0) !== (sentGeneration[key] ?? 0)) {
|
||||
Object.assign(merged, { [key]: sections(live.current)[key] });
|
||||
edited.current.add(key);
|
||||
}
|
||||
base.current = saved;
|
||||
createdId.current = null;
|
||||
pendingCreation.current = null;
|
||||
pendingUpdate.current = null;
|
||||
const defaults = toDraft(
|
||||
saved.values,
|
||||
saved.clientKey ?? command.client_key,
|
||||
saved.version,
|
||||
);
|
||||
form.setDefaults(defaults);
|
||||
live.current = toDraft(merged, defaults.client_key, defaults.version);
|
||||
form.setData(live.current);
|
||||
form.clearErrors();
|
||||
setChoices({});
|
||||
setMustRefresh(false);
|
||||
setAccessDenied(false);
|
||||
setNeedsCompare(later);
|
||||
setProblem(
|
||||
later
|
||||
? 'A gravação foi reconhecida. Existem alterações posteriores; compare antes de voltar a guardar.'
|
||||
: null,
|
||||
);
|
||||
}
|
||||
function acknowledgeUpdate(
|
||||
pageProps: unknown,
|
||||
sent: NonNullable<typeof pendingUpdate.current>,
|
||||
): boolean {
|
||||
if (
|
||||
!alive.current ||
|
||||
pendingUpdate.current !== sent ||
|
||||
identity.current !== sent.id
|
||||
)
|
||||
return false;
|
||||
const saved = readSnapshot(pageProps),
|
||||
expectedVersion = (sent.base.version ?? 0) + 1;
|
||||
if (
|
||||
!saved ||
|
||||
saved.id !== sent.id ||
|
||||
saved.actorId !== sent.base.actorId ||
|
||||
!saved.commands.some(
|
||||
(command) =>
|
||||
command.key === sent.command.operation_key &&
|
||||
command.version === expectedVersion,
|
||||
) ||
|
||||
saved.version === null ||
|
||||
saved.version < expectedVersion
|
||||
)
|
||||
return false;
|
||||
const expected = normalised(sections(sent.command));
|
||||
if (saved.version === expectedVersion) {
|
||||
if (saved.status !== 'draft' || !same(saved.values, expected))
|
||||
return false;
|
||||
applySaved(saved, sent.command, sent.generation);
|
||||
return true;
|
||||
}
|
||||
applySaved(
|
||||
{
|
||||
...sent.base,
|
||||
version: expectedVersion,
|
||||
status: 'draft',
|
||||
values: expected,
|
||||
commands: saved.commands,
|
||||
},
|
||||
sent.command,
|
||||
sent.generation,
|
||||
true,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
function save(recover = false) {
|
||||
if (
|
||||
!alive.current ||
|
||||
form.processing ||
|
||||
refreshing ||
|
||||
invalid ||
|
||||
accessDenied ||
|
||||
(!recover && blocked)
|
||||
)
|
||||
return;
|
||||
const update = recover ? pendingUpdate.current : null;
|
||||
if (recover && (!update?.ambiguous || current?.id !== update.id))
|
||||
return;
|
||||
const submittedId = update?.id ?? base.current?.id ?? null;
|
||||
const pending = submittedId === null ? pendingCreation.current : null;
|
||||
const command =
|
||||
update?.command ??
|
||||
pending?.command ??
|
||||
structuredClone(live.current);
|
||||
const sentGeneration = update?.generation ??
|
||||
pending?.generation ?? { ...generation.current };
|
||||
if (submittedId !== null && !update && base.current)
|
||||
pendingUpdate.current = {
|
||||
id: submittedId,
|
||||
command: { ...command, operation_key: createOperationKey() },
|
||||
generation: sentGeneration,
|
||||
base: base.current,
|
||||
ambiguous: false,
|
||||
};
|
||||
const submittedUpdate = pendingUpdate.current;
|
||||
if (submittedId === null && !pending)
|
||||
pendingCreation.current = {
|
||||
command,
|
||||
generation: sentGeneration,
|
||||
ambiguous: false,
|
||||
};
|
||||
setProblem(null);
|
||||
form.transform(() => submittedUpdate?.command ?? command);
|
||||
const options = {
|
||||
preserveScroll: true,
|
||||
onSuccess: (page: { props: Record<string, unknown> }) => {
|
||||
if (!alive.current) return;
|
||||
if (submittedUpdate) {
|
||||
if (
|
||||
!acknowledgeUpdate(page.props, submittedUpdate) &&
|
||||
pendingUpdate.current === submittedUpdate
|
||||
) {
|
||||
submittedUpdate.ambiguous = true;
|
||||
setMustRefresh(true);
|
||||
setNeedsCompare(true);
|
||||
setProblem(
|
||||
'A resposta não confirmou esta gravação. A preparação foi conservada; recupere a mesma tentativa ou compare os dados actuais.',
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const saved = readSnapshot(page.props);
|
||||
if (
|
||||
!saved ||
|
||||
saved.id === null ||
|
||||
(submittedId !== null
|
||||
? saved.id !== submittedId ||
|
||||
identity.current !== submittedId
|
||||
: saved.clientKey !== command.client_key ||
|
||||
(identity.current !== null &&
|
||||
identity.current !== saved.id))
|
||||
) {
|
||||
setProblem(
|
||||
'A gravação não foi reconciliada com este formulário. Compare os dados antes de continuar.',
|
||||
);
|
||||
setNeedsCompare(true);
|
||||
return;
|
||||
}
|
||||
if (submittedId === null) createdId.current = saved.id;
|
||||
pendingCreation.current = null;
|
||||
if (
|
||||
saved.status !== 'draft' ||
|
||||
!same(saved.values, normalised(sections(command)))
|
||||
) {
|
||||
setProblem(
|
||||
'A resposta contém uma versão com dados diferentes do que enviou. Compare antes de voltar a guardar; as suas edições foram conservadas.',
|
||||
);
|
||||
setNeedsCompare(true);
|
||||
return;
|
||||
}
|
||||
applySaved(saved, command, sentGeneration);
|
||||
},
|
||||
onError: () => {
|
||||
if (!alive.current) return;
|
||||
if (
|
||||
submittedUpdate &&
|
||||
pendingUpdate.current === submittedUpdate
|
||||
)
|
||||
pendingUpdate.current = null;
|
||||
if (!pendingCreation.current?.ambiguous)
|
||||
pendingCreation.current = null;
|
||||
},
|
||||
onHttpException: (response: { status: number }) => {
|
||||
if (!alive.current) return false;
|
||||
if (submittedUpdate) {
|
||||
if (pendingUpdate.current !== submittedUpdate) return false;
|
||||
if (
|
||||
response.status >= 500 ||
|
||||
[401, 403, 404, 419].includes(response.status)
|
||||
)
|
||||
submittedUpdate.ambiguous = true;
|
||||
else pendingUpdate.current = null;
|
||||
setMustRefresh(true);
|
||||
setNeedsCompare(true);
|
||||
setAccessDenied(
|
||||
[401, 403, 404, 419].includes(response.status),
|
||||
);
|
||||
setProblem(
|
||||
'A gravação não foi confirmada com os dados e acesso actuais. Compare antes de continuar; as edições foram conservadas.',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
if (submittedId !== null && response.status === 409) {
|
||||
setNeedsCompare(true);
|
||||
setProblem(
|
||||
'A parceria foi alterada ou mudou de estado. Compare com os dados actuais antes de guardar; as suas edições foram conservadas.',
|
||||
);
|
||||
} else {
|
||||
setProblem(
|
||||
response.status === 403
|
||||
? 'Não foi possível confirmar a operação com o acesso actual. As suas edições foram conservadas.'
|
||||
: 'A gravação não foi confirmada. As suas edições foram conservadas.',
|
||||
);
|
||||
if (submittedId !== null)
|
||||
setNeedsCompare(response.status >= 500);
|
||||
}
|
||||
if (pendingCreation.current) {
|
||||
if (
|
||||
response.status >= 500 ||
|
||||
response.status === 409 ||
|
||||
pendingCreation.current.ambiguous
|
||||
)
|
||||
pendingCreation.current.ambiguous = true;
|
||||
else pendingCreation.current = null;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
onNetworkError: () => {
|
||||
if (!alive.current) return false;
|
||||
if (
|
||||
submittedUpdate &&
|
||||
pendingUpdate.current !== submittedUpdate
|
||||
)
|
||||
return false;
|
||||
if (
|
||||
submittedUpdate &&
|
||||
pendingUpdate.current === submittedUpdate
|
||||
) {
|
||||
submittedUpdate.ambiguous = true;
|
||||
setMustRefresh(true);
|
||||
}
|
||||
setProblem(
|
||||
'A gravação não foi confirmada. As suas edições foram conservadas.',
|
||||
);
|
||||
if (pendingCreation.current)
|
||||
pendingCreation.current.ambiguous = true;
|
||||
else setNeedsCompare(true);
|
||||
return false;
|
||||
},
|
||||
onCancel: () => {
|
||||
if (!alive.current) return;
|
||||
if (
|
||||
submittedUpdate &&
|
||||
pendingUpdate.current !== submittedUpdate
|
||||
)
|
||||
return;
|
||||
if (
|
||||
submittedUpdate &&
|
||||
pendingUpdate.current === submittedUpdate
|
||||
) {
|
||||
submittedUpdate.ambiguous = true;
|
||||
setMustRefresh(true);
|
||||
}
|
||||
if (pendingCreation.current)
|
||||
pendingCreation.current.ambiguous = true;
|
||||
else setNeedsCompare(true);
|
||||
setProblem(
|
||||
'A gravação foi interrompida; conserve a edição e recupere os dados antes de continuar.',
|
||||
);
|
||||
},
|
||||
};
|
||||
if (submittedId === null) form.post('/parcerias/rascunhos', options);
|
||||
else form.put(`/parcerias/${submittedId}`, options);
|
||||
}
|
||||
return {
|
||||
form,
|
||||
setData,
|
||||
save,
|
||||
refresh,
|
||||
adopt,
|
||||
choose,
|
||||
problem,
|
||||
current,
|
||||
values: own,
|
||||
changed,
|
||||
conflicts,
|
||||
unresolved,
|
||||
stale,
|
||||
invalid,
|
||||
refreshing,
|
||||
editable,
|
||||
blocked,
|
||||
dirty,
|
||||
retryingCreation: !!pendingCreation.current?.ambiguous,
|
||||
retryingSave: !!pendingUpdate.current?.ambiguous,
|
||||
canRecoverSave:
|
||||
!!pendingUpdate.current?.ambiguous &&
|
||||
!invalid &&
|
||||
!accessDenied &&
|
||||
!refreshing &&
|
||||
!form.processing,
|
||||
recoverSave: () => save(true),
|
||||
mustRefresh,
|
||||
baseVersion: base.current?.version ?? null,
|
||||
};
|
||||
}
|
||||
export type PartnershipEditor = ReturnType<typeof usePartnershipEdit>;
|
||||
@@ -0,0 +1,26 @@
|
||||
export const publicationHistoryActions: Record<string, string> = {
|
||||
create: 'Criação do rascunho',
|
||||
edit: 'Edição do rascunho',
|
||||
submit: 'Submissão para moderação',
|
||||
publish: 'Publicação',
|
||||
return: 'Devolução para correcção',
|
||||
reject: 'Rejeição',
|
||||
suspend: 'Suspensão',
|
||||
archive: 'Arquivo',
|
||||
renew: 'Renovação em rascunho',
|
||||
};
|
||||
export type PublicationHistorySummary = {
|
||||
limit: number;
|
||||
has_more: boolean;
|
||||
href: string;
|
||||
entries: {
|
||||
version: number | null;
|
||||
restricted: boolean;
|
||||
action: string | null;
|
||||
actor_name: string | null;
|
||||
occurred_at: string | null;
|
||||
reason: string | null;
|
||||
status_before: string | null;
|
||||
status_after: string | null;
|
||||
}[];
|
||||
};
|
||||
@@ -0,0 +1,465 @@
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { createOperationKey } from './operation-key';
|
||||
import type { Partnership } from '@/pages/partnerships/shared';
|
||||
|
||||
export type PublicationProps = {
|
||||
record: Partnership;
|
||||
owner: boolean;
|
||||
canEdit: boolean;
|
||||
moderator: boolean;
|
||||
publicationActions: string[];
|
||||
publicationCommands: { key: string; action: string; version: number }[];
|
||||
origins: unknown[];
|
||||
locations: unknown[];
|
||||
};
|
||||
type Snapshot = {
|
||||
id: number;
|
||||
version: number;
|
||||
status: string;
|
||||
context: string;
|
||||
values: Record<string, string>;
|
||||
actions: string[];
|
||||
canEdit: boolean;
|
||||
moderator: boolean;
|
||||
commands: PublicationProps['publicationCommands'];
|
||||
};
|
||||
const states: Record<string, string> = {
|
||||
submit: 'submitted',
|
||||
publish: 'published',
|
||||
return: 'returned',
|
||||
reject: 'rejected',
|
||||
suspend: 'suspended',
|
||||
archive: 'archived',
|
||||
renew: 'draft',
|
||||
};
|
||||
const object = (value: unknown): value is Record<string, unknown> =>
|
||||
!!value && typeof value === 'object' && !Array.isArray(value);
|
||||
const positive = (value: unknown): value is number =>
|
||||
typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
|
||||
function scalar(value: unknown): string | null {
|
||||
return value == null
|
||||
? ''
|
||||
: typeof value === 'string' ||
|
||||
typeof value === 'number' ||
|
||||
typeof value === 'boolean'
|
||||
? String(value)
|
||||
: null;
|
||||
}
|
||||
function canonical(value: unknown): unknown {
|
||||
return Array.isArray(value)
|
||||
? value.map(canonical)
|
||||
: object(value)
|
||||
? Object.fromEntries(
|
||||
Object.keys(value)
|
||||
.sort()
|
||||
.map((key) => [key, canonical(value[key])]),
|
||||
)
|
||||
: value;
|
||||
}
|
||||
function read(props: unknown, id: number): Snapshot | null {
|
||||
if (
|
||||
!object(props) ||
|
||||
!object(props.record) ||
|
||||
props.record.id !== id ||
|
||||
!positive(props.record.version) ||
|
||||
typeof props.record.status !== 'string' ||
|
||||
typeof props.canEdit !== 'boolean' ||
|
||||
typeof props.moderator !== 'boolean' ||
|
||||
!Array.isArray(props.publicationActions) ||
|
||||
!props.publicationActions.every(
|
||||
(value) =>
|
||||
typeof value === 'string' && Object.hasOwn(states, value),
|
||||
) ||
|
||||
!Array.isArray(props.publicationCommands) ||
|
||||
!props.publicationCommands.every(
|
||||
(value) =>
|
||||
object(value) &&
|
||||
typeof value.key === 'string' &&
|
||||
typeof value.action === 'string' &&
|
||||
Object.hasOwn(states, value.action) &&
|
||||
positive(value.version),
|
||||
) ||
|
||||
!Array.isArray(props.origins) ||
|
||||
!Array.isArray(props.locations)
|
||||
)
|
||||
return null;
|
||||
const payload = object(props.record.payload)
|
||||
? props.record.payload
|
||||
: Array.isArray(props.record.payload) &&
|
||||
props.record.payload.length === 0
|
||||
? {}
|
||||
: null;
|
||||
if (!payload) return null;
|
||||
const { version, status, ...content } = props.record;
|
||||
const values: Record<string, string> = {};
|
||||
for (const key of [
|
||||
'title',
|
||||
'offer',
|
||||
'seeking',
|
||||
'kind',
|
||||
'partnership_type',
|
||||
'sector_id',
|
||||
'organization_id',
|
||||
'deadline',
|
||||
]) {
|
||||
const value = scalar(props.record[key]);
|
||||
if (value === null) return null;
|
||||
values[key] = value;
|
||||
}
|
||||
for (const key of [
|
||||
'summary',
|
||||
'requirements',
|
||||
'confidentiality',
|
||||
'availability',
|
||||
'consent',
|
||||
'mandatory',
|
||||
]) {
|
||||
const item = payload[key];
|
||||
const value =
|
||||
key === 'mandatory' &&
|
||||
Array.isArray(item) &&
|
||||
item.every((entry) => typeof entry === 'string')
|
||||
? item.join(', ')
|
||||
: scalar(item);
|
||||
if (value === null) return null;
|
||||
values[key] = value;
|
||||
}
|
||||
values.origins = props.origins
|
||||
.map((value) =>
|
||||
object(value)
|
||||
? (scalar(value.title ?? value.type) ??
|
||||
'Origem indisponível para comparação')
|
||||
: '',
|
||||
)
|
||||
.join('\n');
|
||||
values.locations = props.locations
|
||||
.map((value) =>
|
||||
object(value)
|
||||
? `${scalar(value.name ?? value.id) ?? 'Localização indisponível'} · ${scalar(value.role) ?? 'Papel indisponível'} · ${scalar(value.source_reference) ?? 'Fonte indisponível'}`
|
||||
: '',
|
||||
)
|
||||
.join('\n');
|
||||
return {
|
||||
id,
|
||||
version,
|
||||
status,
|
||||
context: JSON.stringify(
|
||||
canonical([content, props.origins, props.locations]),
|
||||
),
|
||||
values,
|
||||
actions: props.publicationActions,
|
||||
commands:
|
||||
props.publicationCommands as PublicationProps['publicationCommands'],
|
||||
canEdit: props.canEdit,
|
||||
moderator: props.moderator,
|
||||
};
|
||||
}
|
||||
type Pending = {
|
||||
command: {
|
||||
client_key: string;
|
||||
version: number;
|
||||
action: string;
|
||||
reason: string;
|
||||
};
|
||||
generation: number;
|
||||
base: Snapshot;
|
||||
ambiguous: boolean;
|
||||
};
|
||||
export function usePublication(p: PublicationProps, actorId: number) {
|
||||
const alive = useRef(true);
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
};
|
||||
}, []);
|
||||
const id = p.record.id,
|
||||
current = read(p, id),
|
||||
identity = `${id}:${actorId}`;
|
||||
const opened = useRef(identity),
|
||||
observed = useRef(identity);
|
||||
observed.current = identity;
|
||||
const base = useRef(current),
|
||||
pending = useRef<Pending | null>(null),
|
||||
generation = useRef(0);
|
||||
const form = useForm({ reason: '' });
|
||||
const live = useRef(form.data.reason);
|
||||
live.current = form.data.reason;
|
||||
const [problem, setProblem] = useState<string | null>(null),
|
||||
[needsCompare, setNeedsCompare] = useState(false),
|
||||
[refreshing, setRefreshing] = useState(false),
|
||||
[mustRefresh, setMustRefresh] = useState(false),
|
||||
[, render] = useState(0);
|
||||
const invalid =
|
||||
!current || !base.current || opened.current !== observed.current;
|
||||
const stale =
|
||||
!!current &&
|
||||
!!base.current &&
|
||||
(current.version !== base.current.version ||
|
||||
current.status !== base.current.status ||
|
||||
current.context !== base.current.context);
|
||||
const dirty = !!live.current || !!pending.current;
|
||||
const can = (action: string) =>
|
||||
!!current &&
|
||||
(['publish', 'return', 'reject', 'suspend'].includes(action)
|
||||
? current.moderator && !current.canEdit
|
||||
: current.canEdit);
|
||||
useEffect(() => {
|
||||
if (current && stale && !dirty && !needsCompare && !form.processing) {
|
||||
base.current = current;
|
||||
render((value) => value + 1);
|
||||
}
|
||||
}, [current, stale, dirty, needsCompare, form.processing]);
|
||||
function change(value: string) {
|
||||
generation.current++;
|
||||
live.current = value;
|
||||
form.setData('reason', value);
|
||||
}
|
||||
function acknowledge(props: unknown, sent: Pending): boolean {
|
||||
if (
|
||||
!alive.current ||
|
||||
pending.current !== sent ||
|
||||
observed.current !== opened.current
|
||||
)
|
||||
return false;
|
||||
const fresh = read(props, id),
|
||||
command = fresh?.commands.find(
|
||||
(value) =>
|
||||
value.key === sent.command.client_key &&
|
||||
value.action === sent.command.action &&
|
||||
value.version === sent.command.version + 1,
|
||||
);
|
||||
if (
|
||||
!fresh ||
|
||||
!command ||
|
||||
fresh.version < command.version ||
|
||||
(fresh.version === command.version &&
|
||||
(fresh.status !== states[sent.command.action] ||
|
||||
fresh.context !== sent.base.context))
|
||||
)
|
||||
return false;
|
||||
const exact = fresh.version === command.version;
|
||||
base.current = exact
|
||||
? fresh
|
||||
: {
|
||||
...sent.base,
|
||||
version: command.version,
|
||||
status: states[sent.command.action],
|
||||
};
|
||||
pending.current = null;
|
||||
if (generation.current === sent.generation) {
|
||||
live.current = '';
|
||||
form.setData('reason', '');
|
||||
}
|
||||
form.setDefaults({ reason: '' });
|
||||
form.clearErrors();
|
||||
setNeedsCompare(!exact);
|
||||
setProblem(
|
||||
exact
|
||||
? null
|
||||
: 'A acção foi reconhecida. Há alterações posteriores; compare antes de preparar outra decisão.',
|
||||
);
|
||||
setMustRefresh(false);
|
||||
render((value) => value + 1);
|
||||
return true;
|
||||
}
|
||||
function refresh() {
|
||||
if (refreshing || form.processing) return;
|
||||
setRefreshing(true);
|
||||
router.reload({
|
||||
only: [
|
||||
'record',
|
||||
'owner',
|
||||
'canEdit',
|
||||
'moderator',
|
||||
'publicationActions',
|
||||
'publicationCommands',
|
||||
'historySummary',
|
||||
'origins',
|
||||
'locations',
|
||||
],
|
||||
onSuccess: (page) => {
|
||||
if (!alive.current || observed.current !== opened.current)
|
||||
return;
|
||||
if (pending.current && acknowledge(page.props, pending.current))
|
||||
return;
|
||||
const fresh = read(page.props, id);
|
||||
if (!fresh) {
|
||||
setProblem(
|
||||
'Resposta incompatível com esta proposta. O motivo preparado foi conservado.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
setMustRefresh(false);
|
||||
if (
|
||||
base.current &&
|
||||
fresh.version === base.current.version &&
|
||||
fresh.status === base.current.status &&
|
||||
fresh.context === base.current.context
|
||||
) {
|
||||
setNeedsCompare(false);
|
||||
setProblem(null);
|
||||
}
|
||||
},
|
||||
onNetworkError: () => {
|
||||
setProblem(
|
||||
'Não foi possível confirmar a actualização. O motivo foi conservado.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
onHttpException: () => {
|
||||
setNeedsCompare(true);
|
||||
setProblem(
|
||||
'Não foi possível consultar a proposta com o acesso actual. O motivo foi conservado.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
onFinish: () => {
|
||||
if (alive.current) setRefreshing(false);
|
||||
},
|
||||
});
|
||||
}
|
||||
function adopt() {
|
||||
if (invalid || !current || mustRefresh || refreshing || form.processing)
|
||||
return;
|
||||
base.current = current;
|
||||
pending.current = null;
|
||||
setNeedsCompare(false);
|
||||
setProblem(null);
|
||||
form.clearErrors();
|
||||
render((value) => value + 1);
|
||||
}
|
||||
function send(action: string, recover = false) {
|
||||
if (
|
||||
invalid ||
|
||||
!current ||
|
||||
!base.current ||
|
||||
refreshing ||
|
||||
form.processing ||
|
||||
!can(action)
|
||||
)
|
||||
return;
|
||||
let sent = pending.current;
|
||||
if (recover) {
|
||||
if (!sent?.ambiguous || sent.command.action !== action) return;
|
||||
} else {
|
||||
if (
|
||||
sent ||
|
||||
stale ||
|
||||
needsCompare ||
|
||||
!current.actions.includes(action) ||
|
||||
!live.current.trim()
|
||||
)
|
||||
return;
|
||||
sent = {
|
||||
command: {
|
||||
client_key: createOperationKey(),
|
||||
version: base.current.version,
|
||||
action,
|
||||
reason: live.current,
|
||||
},
|
||||
generation: generation.current,
|
||||
base: base.current,
|
||||
ambiguous: false,
|
||||
};
|
||||
pending.current = sent;
|
||||
}
|
||||
if (!sent) return;
|
||||
const request = sent;
|
||||
form.transform(() => ({ ...request.command }));
|
||||
form.post(`/parcerias/${id}/estado`, {
|
||||
preserveScroll: true,
|
||||
onSuccess: (page) => {
|
||||
if (!alive.current) return;
|
||||
if (
|
||||
!acknowledge(page.props, request) &&
|
||||
pending.current === request
|
||||
) {
|
||||
request.ambiguous = true;
|
||||
setMustRefresh(true);
|
||||
setNeedsCompare(true);
|
||||
setProblem(
|
||||
'A resposta não confirmou esta tentativa. Conserve o motivo e recupere a mesma acção ou compare os dados actuais.',
|
||||
);
|
||||
}
|
||||
},
|
||||
onError: () => {
|
||||
if (
|
||||
!alive.current ||
|
||||
pending.current !== request ||
|
||||
observed.current !== opened.current
|
||||
)
|
||||
return;
|
||||
pending.current = null;
|
||||
setProblem(
|
||||
'A acção não foi gravada. Corrija os campos indicados; o motivo foi conservado.',
|
||||
);
|
||||
},
|
||||
onNetworkError: () => {
|
||||
if (
|
||||
alive.current &&
|
||||
pending.current === request &&
|
||||
observed.current === opened.current
|
||||
) {
|
||||
request.ambiguous = true;
|
||||
setMustRefresh(true);
|
||||
setProblem(
|
||||
'A resposta perdeu-se. Pode recuperar exactamente a mesma tentativa, sem repetir uma decisão já gravada.',
|
||||
);
|
||||
}
|
||||
return false;
|
||||
},
|
||||
onHttpException: (response) => {
|
||||
if (
|
||||
!alive.current ||
|
||||
pending.current !== request ||
|
||||
observed.current !== opened.current
|
||||
)
|
||||
return false;
|
||||
if (response.status >= 500) request.ambiguous = true;
|
||||
else pending.current = null;
|
||||
setMustRefresh(true);
|
||||
setNeedsCompare(true);
|
||||
setProblem(
|
||||
'A acção não foi confirmada com os dados e acesso actuais. Compare antes de continuar; o motivo foi conservado.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
});
|
||||
}
|
||||
return {
|
||||
form,
|
||||
current,
|
||||
base: base.current,
|
||||
stale,
|
||||
invalid,
|
||||
dirty,
|
||||
problem,
|
||||
refreshing,
|
||||
needsCompare,
|
||||
mustRefresh,
|
||||
changes:
|
||||
current && base.current
|
||||
? Object.keys(current.values).filter(
|
||||
(key) =>
|
||||
current.values[key] !== base.current?.values[key],
|
||||
)
|
||||
: [],
|
||||
blocked:
|
||||
invalid ||
|
||||
stale ||
|
||||
needsCompare ||
|
||||
!!pending.current ||
|
||||
refreshing ||
|
||||
form.processing,
|
||||
recovery: pending.current?.ambiguous
|
||||
? pending.current.command.action
|
||||
: null,
|
||||
can,
|
||||
change,
|
||||
refresh,
|
||||
adopt,
|
||||
send,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { useRef, useState } from 'react';
|
||||
import { createOperationKey } from './operation-key';
|
||||
type Data = {
|
||||
body: string;
|
||||
file: File | null;
|
||||
shared: boolean;
|
||||
client_key: string;
|
||||
};
|
||||
function object(value: unknown): value is Record<string, unknown> {
|
||||
return !!value && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
/** Keeps the original command, including the immutable File object, until delivery is confirmed. */
|
||||
export function useRoomDelivery({
|
||||
roomId,
|
||||
actorId,
|
||||
kind,
|
||||
mutable,
|
||||
canWrite,
|
||||
}: {
|
||||
roomId: number;
|
||||
actorId: number;
|
||||
kind: 'message' | 'upload';
|
||||
mutable: boolean;
|
||||
canWrite: boolean;
|
||||
}) {
|
||||
const form = useForm<Data>({
|
||||
body: '',
|
||||
file: null,
|
||||
shared: false,
|
||||
client_key: createOperationKey(),
|
||||
});
|
||||
const live = useRef(form.data);
|
||||
live.current = form.data;
|
||||
const generation = useRef({ body: 0, file: 0, shared: 0 });
|
||||
const identity = useRef(JSON.stringify([roomId, actorId, kind]));
|
||||
const observed = useRef(identity.current);
|
||||
observed.current = JSON.stringify([roomId, actorId, kind]);
|
||||
const pending = useRef<{
|
||||
data: Data;
|
||||
generation: typeof generation.current;
|
||||
ambiguous: boolean;
|
||||
} | null>(null);
|
||||
const [problem, setProblem] = useState<string | null>(null);
|
||||
const recovering = !!pending.current?.ambiguous;
|
||||
const invalid = observed.current !== identity.current;
|
||||
const dirty =
|
||||
!!pending.current ||
|
||||
(kind === 'message' ? !!form.data.body : !!form.data.file);
|
||||
const blocked =
|
||||
form.processing || invalid || !canWrite || (!mutable && !recovering);
|
||||
function change<K extends 'body' | 'file' | 'shared'>(
|
||||
key: K,
|
||||
value: Data[K],
|
||||
) {
|
||||
generation.current[key]++;
|
||||
live.current = { ...live.current, [key]: value };
|
||||
form.setData(live.current);
|
||||
}
|
||||
function submit() {
|
||||
if (
|
||||
blocked ||
|
||||
(kind === 'upload' &&
|
||||
!pending.current?.data.file &&
|
||||
!live.current.file)
|
||||
)
|
||||
return;
|
||||
const command = pending.current ?? {
|
||||
data: { ...live.current },
|
||||
generation: { ...generation.current },
|
||||
ambiguous: false,
|
||||
};
|
||||
pending.current = command;
|
||||
setProblem(null);
|
||||
form.transform(() =>
|
||||
kind === 'message'
|
||||
? {
|
||||
body: command.data.body,
|
||||
client_key: command.data.client_key,
|
||||
}
|
||||
: {
|
||||
file: command.data.file,
|
||||
shared: command.data.shared,
|
||||
client_key: command.data.client_key,
|
||||
},
|
||||
);
|
||||
const unknown = () => {
|
||||
if (pending.current) pending.current.ambiguous = true;
|
||||
setProblem(
|
||||
'O envio não foi confirmado. A tentativa original e a sua preparação foram conservadas.',
|
||||
);
|
||||
return false;
|
||||
};
|
||||
form.post(
|
||||
`/parcerias/salas/${roomId}/${kind === 'message' ? 'mensagens' : 'documentos'}`,
|
||||
{
|
||||
preserveScroll: true,
|
||||
forceFormData: kind === 'upload',
|
||||
onSuccess: (page) => {
|
||||
if (observed.current !== identity.current) return;
|
||||
const props = page.props;
|
||||
const room = props.room;
|
||||
const flash = props.flash;
|
||||
const confirmed =
|
||||
object(room) &&
|
||||
room.id === roomId &&
|
||||
(kind === 'message'
|
||||
? Array.isArray(props.messages) &&
|
||||
props.messages.some(
|
||||
(message) =>
|
||||
object(message) &&
|
||||
message.author_id === actorId &&
|
||||
message.client_key ===
|
||||
command.data.client_key &&
|
||||
message.body === command.data.body.trim(),
|
||||
)
|
||||
: object(flash) &&
|
||||
typeof flash.uploaded_document_id === 'string' &&
|
||||
Array.isArray(props.documents) &&
|
||||
props.documents.some(
|
||||
(document) =>
|
||||
object(document) &&
|
||||
document.document_id ===
|
||||
flash.uploaded_document_id &&
|
||||
document.owner_id === actorId &&
|
||||
document.file_name ===
|
||||
command.data.file?.name,
|
||||
));
|
||||
if (!confirmed) {
|
||||
unknown();
|
||||
return;
|
||||
}
|
||||
const next: Data = {
|
||||
body: '',
|
||||
file: null,
|
||||
shared: false,
|
||||
client_key: createOperationKey(),
|
||||
};
|
||||
if (
|
||||
kind === 'message' &&
|
||||
generation.current.body !== command.generation.body
|
||||
)
|
||||
next.body = live.current.body;
|
||||
if (kind === 'upload') {
|
||||
if (
|
||||
generation.current.file !== command.generation.file
|
||||
) {
|
||||
next.file = live.current.file;
|
||||
next.shared = live.current.shared;
|
||||
} else if (
|
||||
generation.current.shared !==
|
||||
command.generation.shared
|
||||
)
|
||||
next.shared = live.current.shared;
|
||||
}
|
||||
pending.current = null;
|
||||
live.current = next;
|
||||
form.setDefaults({
|
||||
body: '',
|
||||
file: null,
|
||||
shared: false,
|
||||
client_key: next.client_key,
|
||||
});
|
||||
form.setData(next);
|
||||
form.clearErrors();
|
||||
setProblem(null);
|
||||
},
|
||||
onError: () => {
|
||||
if (!pending.current?.ambiguous) pending.current = null;
|
||||
},
|
||||
onHttpException: (response) => {
|
||||
if (
|
||||
response.status >= 500 ||
|
||||
response.status === 409 ||
|
||||
pending.current?.ambiguous
|
||||
)
|
||||
return unknown();
|
||||
pending.current = null;
|
||||
setProblem(
|
||||
'Não foi possível confirmar o envio com o acesso actual. A preparação foi conservada.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
onNetworkError: unknown,
|
||||
onCancel: unknown,
|
||||
},
|
||||
);
|
||||
}
|
||||
return {
|
||||
form,
|
||||
data: form.data,
|
||||
change,
|
||||
submit,
|
||||
problem,
|
||||
recovering,
|
||||
dirty,
|
||||
blocked,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,845 @@
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { createOperationKey } from './operation-key';
|
||||
|
||||
type Values = Record<string, string>;
|
||||
type Kind = 'agreement' | 'milestone';
|
||||
type Snapshot = {
|
||||
actorId: number | null;
|
||||
partnershipVersion: number | null;
|
||||
interestVersion: number | null;
|
||||
commands: {
|
||||
key: string;
|
||||
action: string;
|
||||
version: number;
|
||||
status: string;
|
||||
party: string | null;
|
||||
}[];
|
||||
confirmations: Record<string, { actorId: number; reason: string }>;
|
||||
id: number | null;
|
||||
version: number | null;
|
||||
context: string;
|
||||
roomVersion: number;
|
||||
status: string;
|
||||
canWrite: boolean;
|
||||
values: Values;
|
||||
};
|
||||
function object(value: unknown): value is Record<string, unknown> {
|
||||
return !!value && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
function positive(value: unknown): value is number {
|
||||
return (
|
||||
typeof value === 'number' && Number.isSafeInteger(value) && value > 0
|
||||
);
|
||||
}
|
||||
function text(value: unknown): string | null {
|
||||
return value == null ? '' : typeof value === 'string' ? value : null;
|
||||
}
|
||||
const milestoneKeys = [
|
||||
'title',
|
||||
'responsible_id',
|
||||
'due_date',
|
||||
'status',
|
||||
'evidence',
|
||||
];
|
||||
function snapshot(
|
||||
props: unknown,
|
||||
roomId: number,
|
||||
kind: Kind,
|
||||
itemId: number | null,
|
||||
creationKey?: string,
|
||||
): Snapshot | null {
|
||||
if (
|
||||
!object(props) ||
|
||||
!object(props.room) ||
|
||||
props.room.id !== roomId ||
|
||||
!positive(props.room.version) ||
|
||||
typeof props.room.status !== 'string' ||
|
||||
typeof props.canWrite !== 'boolean'
|
||||
)
|
||||
return null;
|
||||
const room = props.room;
|
||||
const actorId = positive(props.agreementActorId)
|
||||
? props.agreementActorId
|
||||
: null;
|
||||
const partnershipVersion =
|
||||
object(props.partnership) && positive(props.partnership.version)
|
||||
? props.partnership.version
|
||||
: null;
|
||||
const interestVersion =
|
||||
object(props.interest) && positive(props.interest.version)
|
||||
? props.interest.version
|
||||
: null;
|
||||
if (
|
||||
kind === 'agreement' &&
|
||||
(!actorId ||
|
||||
!partnershipVersion ||
|
||||
!interestVersion ||
|
||||
!Array.isArray(props.agreementCommands) ||
|
||||
!props.agreementCommands.every(
|
||||
(command) =>
|
||||
object(command) &&
|
||||
typeof command.key === 'string' &&
|
||||
typeof command.action === 'string' &&
|
||||
positive(command.version) &&
|
||||
typeof command.status === 'string' &&
|
||||
(command.party === null ||
|
||||
command.party === 'proponent' ||
|
||||
command.party === 'candidate'),
|
||||
))
|
||||
)
|
||||
return null;
|
||||
let values: Record<string, string | null>,
|
||||
id: number | null = roomId,
|
||||
version: number | null = room.version as number;
|
||||
const confirmations: Snapshot['confirmations'] = {};
|
||||
if (kind === 'agreement') {
|
||||
if (room.agreement !== null && !object(room.agreement)) return null;
|
||||
const agreement = object(room.agreement) ? room.agreement : {};
|
||||
if (object(agreement.confirmations))
|
||||
for (const party of ['proponent', 'candidate']) {
|
||||
const confirmation = agreement.confirmations[party];
|
||||
if (object(confirmation) && positive(confirmation.actor_id))
|
||||
confirmations[party] = {
|
||||
actorId: confirmation.actor_id,
|
||||
reason:
|
||||
typeof confirmation.reason === 'string'
|
||||
? confirmation.reason
|
||||
: '',
|
||||
};
|
||||
}
|
||||
values = {
|
||||
title: text(agreement.title),
|
||||
terms: text(agreement.terms),
|
||||
reason: '',
|
||||
};
|
||||
} else if (itemId === null && !creationKey) {
|
||||
id = null;
|
||||
version = null;
|
||||
values = {
|
||||
title: '',
|
||||
responsible_id: '',
|
||||
due_date: '',
|
||||
status: 'pending',
|
||||
evidence: '',
|
||||
};
|
||||
} else {
|
||||
if (!Array.isArray(props.milestones)) return null;
|
||||
const item = props.milestones.find(
|
||||
(candidate) =>
|
||||
object(candidate) &&
|
||||
(creationKey
|
||||
? candidate.client_key === creationKey
|
||||
: candidate.id === itemId),
|
||||
);
|
||||
if (
|
||||
!object(item) ||
|
||||
!positive(item.id) ||
|
||||
!positive(item.version) ||
|
||||
!positive(item.responsible_id)
|
||||
)
|
||||
return null;
|
||||
id = item.id;
|
||||
version = item.version;
|
||||
values = {
|
||||
title: text(item.title),
|
||||
responsible_id: String(item.responsible_id),
|
||||
due_date: text(item.due_date),
|
||||
status: text(item.status),
|
||||
evidence: text(item.evidence),
|
||||
};
|
||||
}
|
||||
if (!Object.values(values).every((value) => typeof value === 'string'))
|
||||
return null;
|
||||
return {
|
||||
actorId,
|
||||
partnershipVersion,
|
||||
interestVersion,
|
||||
confirmations,
|
||||
commands:
|
||||
kind === 'agreement' && Array.isArray(props.agreementCommands)
|
||||
? props.agreementCommands.map((command) => ({
|
||||
key: command.key,
|
||||
action: command.action,
|
||||
version: command.version,
|
||||
status: command.status,
|
||||
party: command.party,
|
||||
}))
|
||||
: [],
|
||||
id,
|
||||
version,
|
||||
context: JSON.stringify(
|
||||
kind === 'agreement'
|
||||
? [
|
||||
room.version,
|
||||
room.status,
|
||||
props.canWrite,
|
||||
partnershipVersion,
|
||||
interestVersion,
|
||||
]
|
||||
: [room.version, room.status, props.canWrite],
|
||||
),
|
||||
roomVersion: room.version as number,
|
||||
status: room.status as string,
|
||||
canWrite: props.canWrite,
|
||||
values: values as Values,
|
||||
};
|
||||
}
|
||||
const same = (a: Values, b: Values) =>
|
||||
Object.keys(a).every((key) => a[key] === b[key]);
|
||||
const normal = (value: string) => value.trim();
|
||||
export function useRoomEdit({
|
||||
props,
|
||||
roomId,
|
||||
kind,
|
||||
itemId = null,
|
||||
}: {
|
||||
props: unknown;
|
||||
roomId: number;
|
||||
kind: Kind;
|
||||
itemId?: number | null;
|
||||
}) {
|
||||
const alive = useRef(true);
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
};
|
||||
}, []);
|
||||
const current = snapshot(props, roomId, kind, itemId);
|
||||
const initial = useRef(current);
|
||||
const initialIdentity = useRef(JSON.stringify([roomId, kind, itemId]));
|
||||
const observedIdentity = useRef(initialIdentity.current);
|
||||
observedIdentity.current = JSON.stringify([roomId, kind, itemId]);
|
||||
const empty: Values =
|
||||
kind === 'agreement'
|
||||
? { title: '', terms: '', reason: '' }
|
||||
: {
|
||||
title: '',
|
||||
responsible_id: '',
|
||||
due_date: '',
|
||||
status: 'pending',
|
||||
evidence: '',
|
||||
};
|
||||
const form = useForm<{
|
||||
version: number | null;
|
||||
client_key: string;
|
||||
values: Values;
|
||||
}>({
|
||||
version: current?.version ?? null,
|
||||
client_key: createOperationKey(),
|
||||
values: current?.values ?? empty,
|
||||
});
|
||||
const live = useRef(form.data);
|
||||
live.current = form.data;
|
||||
const edited = useRef(new Set<string>());
|
||||
const generation = useRef<Record<string, number>>({});
|
||||
const pending = useRef<{
|
||||
command: Record<string, string | number | null>;
|
||||
generations: Record<string, number>;
|
||||
ambiguous: boolean;
|
||||
base: Snapshot;
|
||||
values: Values;
|
||||
} | null>(null);
|
||||
const [choices, setChoices] = useState<Record<string, 'mine' | 'current'>>(
|
||||
{},
|
||||
);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
const [needsCompare, setNeedsCompare] = useState(false);
|
||||
const [problem, setProblem] = useState<string | null>(null);
|
||||
const [mustRefresh, setMustRefresh] = useState(false),
|
||||
[accessDenied, setAccessDenied] = useState(false);
|
||||
const [created, setCreated] = useState<number | null>(null);
|
||||
const isNew = kind === 'milestone' && itemId === null;
|
||||
const keys = Object.keys(current?.values ?? empty);
|
||||
const invalid =
|
||||
!current ||
|
||||
!initial.current ||
|
||||
(kind === 'agreement' && current.actorId !== initial.current.actorId) ||
|
||||
initialIdentity.current !== JSON.stringify([roomId, kind, itemId]);
|
||||
const stale =
|
||||
!!current &&
|
||||
!!initial.current &&
|
||||
(current.version !== initial.current.version ||
|
||||
current.context !== initial.current.context ||
|
||||
!same(current.values, initial.current.values));
|
||||
const changed =
|
||||
current && initial.current
|
||||
? keys.filter(
|
||||
(key) => current.values[key] !== initial.current?.values[key],
|
||||
)
|
||||
: [];
|
||||
const conflicts = current
|
||||
? changed.filter(
|
||||
(key) =>
|
||||
edited.current.has(key) &&
|
||||
live.current.values[key] !== current.values[key],
|
||||
)
|
||||
: [];
|
||||
const choiceKey = (key: string) =>
|
||||
JSON.stringify([
|
||||
current?.version,
|
||||
current?.context,
|
||||
key,
|
||||
current?.values[key],
|
||||
]);
|
||||
const unresolved = conflicts.filter(
|
||||
(key) => choices[choiceKey(key)] !== 'mine',
|
||||
);
|
||||
const editable =
|
||||
!!current?.canWrite &&
|
||||
(kind === 'agreement'
|
||||
? ['negotiation', 'agreement_recorded', 'agreed', 'execution']
|
||||
: ['agreement_recorded', 'agreed', 'execution']
|
||||
).includes(current.status);
|
||||
const recovering =
|
||||
(isNew || kind === 'agreement') &&
|
||||
!!pending.current?.ambiguous &&
|
||||
!!current?.canWrite &&
|
||||
!accessDenied;
|
||||
const blocked =
|
||||
invalid ||
|
||||
stale ||
|
||||
refreshing ||
|
||||
needsCompare ||
|
||||
(kind === 'agreement' && (accessDenied || !!pending.current)) ||
|
||||
(!editable && !recovering);
|
||||
const dirty =
|
||||
!!pending.current ||
|
||||
(!!initial.current &&
|
||||
(!same(live.current.values, initial.current.values) ||
|
||||
keys.some(
|
||||
(key) =>
|
||||
edited.current.has(key) &&
|
||||
current &&
|
||||
live.current.values[key] !== current.values[key],
|
||||
)));
|
||||
// Untouched controls follow current data. Deliberate edits and uncertain commands require comparison.
|
||||
useEffect(() => {
|
||||
if (
|
||||
!current ||
|
||||
invalid ||
|
||||
(!stale && !(kind === 'agreement' && pending.current?.ambiguous)) ||
|
||||
dirty ||
|
||||
edited.current.size > 0 ||
|
||||
pending.current ||
|
||||
form.processing ||
|
||||
needsCompare
|
||||
)
|
||||
return;
|
||||
if (kind === 'agreement' && mustRefresh) return;
|
||||
initial.current = current;
|
||||
live.current = {
|
||||
...live.current,
|
||||
version: current.version,
|
||||
values: { ...current.values },
|
||||
};
|
||||
form.setDefaults(live.current);
|
||||
form.setData(live.current);
|
||||
}, [current, invalid, stale, dirty, form.processing, needsCompare]);
|
||||
function change(key: string, value: string) {
|
||||
if (!keys.includes(key)) return;
|
||||
edited.current.add(key);
|
||||
generation.current[key] = (generation.current[key] ?? 0) + 1;
|
||||
live.current = {
|
||||
...live.current,
|
||||
values: { ...live.current.values, [key]: value },
|
||||
};
|
||||
form.setData(live.current);
|
||||
setChoices((previous) => {
|
||||
const next = { ...previous };
|
||||
delete next[choiceKey(key)];
|
||||
return next;
|
||||
});
|
||||
}
|
||||
function choose(key: string, value: 'mine' | 'current') {
|
||||
if (!current || !keys.includes(key)) return;
|
||||
if (value === 'current') change(key, current.values[key]);
|
||||
setChoices((previous) => ({ ...previous, [choiceKey(key)]: value }));
|
||||
}
|
||||
function adopt() {
|
||||
if (
|
||||
!current ||
|
||||
invalid ||
|
||||
(!stale && !(kind === 'agreement' && pending.current?.ambiguous)) ||
|
||||
(kind === 'agreement' && (mustRefresh || accessDenied)) ||
|
||||
unresolved.length ||
|
||||
refreshing ||
|
||||
form.processing
|
||||
)
|
||||
return;
|
||||
const values = { ...current.values };
|
||||
for (const key of keys)
|
||||
if (edited.current.has(key)) values[key] = live.current.values[key];
|
||||
initial.current = current;
|
||||
live.current = { ...live.current, version: current.version, values };
|
||||
form.setData(live.current);
|
||||
form.setDefaults({ ...live.current, values: current.values });
|
||||
form.clearErrors();
|
||||
setChoices({});
|
||||
setNeedsCompare(false);
|
||||
setProblem(null);
|
||||
if (kind === 'agreement') pending.current = null;
|
||||
}
|
||||
function httpFailure(response: { status: number }) {
|
||||
if (!alive.current) return false;
|
||||
if (kind === 'agreement') {
|
||||
setMustRefresh(true);
|
||||
setAccessDenied([401, 403, 404, 419].includes(response.status));
|
||||
}
|
||||
setProblem(
|
||||
response.status === 409
|
||||
? 'O registo ou o estado da sala mudou. Compare com os dados actuais; as suas edições foram conservadas.'
|
||||
: 'Não foi possível confirmar a operação com o acesso actual. As suas edições foram conservadas.',
|
||||
);
|
||||
if (response.status === 409 || response.status >= 500)
|
||||
setNeedsCompare(true);
|
||||
if (pending.current) {
|
||||
if (kind === 'agreement' && response.status === 409) {
|
||||
pending.current = null;
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
response.status >= 500 ||
|
||||
response.status === 409 ||
|
||||
pending.current.ambiguous
|
||||
)
|
||||
pending.current.ambiguous = true;
|
||||
else pending.current = null;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function refresh() {
|
||||
if (refreshing || form.processing) return;
|
||||
setRefreshing(true);
|
||||
router.reload({
|
||||
only: [
|
||||
'room',
|
||||
'milestones',
|
||||
'participants',
|
||||
'canWrite',
|
||||
'messages',
|
||||
'documents',
|
||||
'partnership',
|
||||
'interest',
|
||||
'agreementActorId',
|
||||
'agreementCommands',
|
||||
'agreementParty',
|
||||
],
|
||||
onSuccess: (page) => {
|
||||
if (!alive.current) return;
|
||||
if (
|
||||
kind === 'agreement' &&
|
||||
pending.current &&
|
||||
acknowledgeAgreement(page.props, pending.current)
|
||||
)
|
||||
return;
|
||||
const fresh = snapshot(page.props, roomId, kind, itemId);
|
||||
if (
|
||||
kind === 'agreement' &&
|
||||
fresh &&
|
||||
fresh.actorId === initial.current?.actorId
|
||||
) {
|
||||
setMustRefresh(false);
|
||||
setAccessDenied(false);
|
||||
}
|
||||
if (
|
||||
fresh &&
|
||||
initial.current &&
|
||||
fresh.version === initial.current.version &&
|
||||
fresh.context === initial.current.context &&
|
||||
same(fresh.values, initial.current.values)
|
||||
) {
|
||||
setNeedsCompare(false);
|
||||
setProblem(null);
|
||||
}
|
||||
},
|
||||
onHttpException: () => {
|
||||
if (!alive.current) return false;
|
||||
if (kind === 'agreement') {
|
||||
setMustRefresh(true);
|
||||
setAccessDenied(true);
|
||||
}
|
||||
setProblem(
|
||||
'Não foi possível recuperar esta sala com o acesso actual. As suas edições foram conservadas.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
onNetworkError: () => {
|
||||
if (!alive.current) return false;
|
||||
setProblem(
|
||||
'A recuperação não foi confirmada. As suas edições foram conservadas.',
|
||||
);
|
||||
return false;
|
||||
},
|
||||
onFinish: () => {
|
||||
if (alive.current) setRefreshing(false);
|
||||
},
|
||||
});
|
||||
}
|
||||
function acknowledgeAgreement(
|
||||
props: unknown,
|
||||
sent: NonNullable<typeof pending.current>,
|
||||
): boolean {
|
||||
if (!alive.current || pending.current !== sent) return false;
|
||||
const fresh = snapshot(props, roomId, 'agreement', null),
|
||||
action = String(sent.command.action),
|
||||
version = Number(sent.command.version) + 1;
|
||||
const receipt = fresh?.commands.find(
|
||||
(command) =>
|
||||
command.key === sent.command.client_key &&
|
||||
command.action === action &&
|
||||
command.version === version,
|
||||
);
|
||||
if (
|
||||
!fresh ||
|
||||
!receipt ||
|
||||
fresh.actorId !== sent.base.actorId ||
|
||||
fresh.version === null ||
|
||||
fresh.version < version
|
||||
)
|
||||
return false;
|
||||
const expected: Values =
|
||||
action === 'record'
|
||||
? {
|
||||
title: normal(sent.values.title),
|
||||
terms: normal(sent.values.terms),
|
||||
reason: '',
|
||||
}
|
||||
: { ...sent.base.values, reason: '' };
|
||||
if (
|
||||
fresh.version === version &&
|
||||
(fresh.status !== receipt.status ||
|
||||
fresh.values.title !== expected.title ||
|
||||
fresh.values.terms !== expected.terms)
|
||||
)
|
||||
return false;
|
||||
if (
|
||||
fresh.version === version &&
|
||||
action === 'confirm' &&
|
||||
(!receipt.party ||
|
||||
fresh.confirmations[receipt.party]?.actorId !==
|
||||
sent.base.actorId ||
|
||||
fresh.confirmations[receipt.party]?.reason !==
|
||||
normal(String(sent.command.reason)) ||
|
||||
(receipt.status === 'agreed' &&
|
||||
(!fresh.confirmations.proponent ||
|
||||
!fresh.confirmations.candidate)))
|
||||
)
|
||||
return false;
|
||||
const later =
|
||||
fresh.version > version ||
|
||||
fresh.partnershipVersion !== sent.base.partnershipVersion ||
|
||||
fresh.interestVersion !== sent.base.interestVersion;
|
||||
const saved: Snapshot = later
|
||||
? {
|
||||
...sent.base,
|
||||
version,
|
||||
roomVersion: version,
|
||||
status: receipt.status,
|
||||
values: expected,
|
||||
context: JSON.stringify([
|
||||
version,
|
||||
receipt.status,
|
||||
sent.base.canWrite,
|
||||
sent.base.partnershipVersion,
|
||||
sent.base.interestVersion,
|
||||
]),
|
||||
}
|
||||
: fresh;
|
||||
const merged = { ...saved.values };
|
||||
edited.current.clear();
|
||||
for (const key of keys)
|
||||
if (
|
||||
(generation.current[key] ?? 0) !==
|
||||
(sent.generations[key] ?? 0) ||
|
||||
(action !== 'record' &&
|
||||
key !== 'reason' &&
|
||||
live.current.values[key] !== sent.base.values[key])
|
||||
) {
|
||||
merged[key] = live.current.values[key];
|
||||
edited.current.add(key);
|
||||
}
|
||||
initial.current = saved;
|
||||
pending.current = null;
|
||||
live.current = {
|
||||
...live.current,
|
||||
version: saved.version,
|
||||
values: merged,
|
||||
};
|
||||
form.setDefaults({ ...live.current, values: saved.values });
|
||||
form.setData(live.current);
|
||||
form.clearErrors();
|
||||
setChoices({});
|
||||
setNeedsCompare(later);
|
||||
setMustRefresh(false);
|
||||
setAccessDenied(false);
|
||||
setProblem(
|
||||
later
|
||||
? 'A acção foi reconhecida, mas existem decisões posteriores. Compare antes de preparar outra acção.'
|
||||
: null,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
function submit(action = 'record', recover = false) {
|
||||
if (
|
||||
!alive.current ||
|
||||
form.processing ||
|
||||
!initial.current ||
|
||||
(kind === 'agreement' &&
|
||||
(invalid || accessDenied || !current?.canWrite || refreshing))
|
||||
)
|
||||
return;
|
||||
if (recover && kind === 'agreement') {
|
||||
if (!pending.current?.ambiguous) return;
|
||||
action = String(pending.current.command.action);
|
||||
} else if (blocked) return;
|
||||
const base = initial.current;
|
||||
if (kind === 'agreement' && !recover) {
|
||||
const allowed: Record<string, string[]> = {
|
||||
record: ['negotiation', 'agreement_recorded'],
|
||||
confirm: ['agreement_recorded'],
|
||||
start: ['agreed'],
|
||||
complete: ['execution'],
|
||||
renew: ['agreed', 'execution'],
|
||||
cancel: [
|
||||
'negotiation',
|
||||
'agreement_recorded',
|
||||
'agreed',
|
||||
'execution',
|
||||
],
|
||||
};
|
||||
if (!allowed[action]?.includes(base.status)) return;
|
||||
}
|
||||
const command: Record<string, string | number | null> =
|
||||
pending.current?.command ??
|
||||
(kind === 'agreement'
|
||||
? action === 'record'
|
||||
? {
|
||||
...live.current.values,
|
||||
version: live.current.version,
|
||||
action,
|
||||
client_key: createOperationKey(),
|
||||
partnership_version: base.partnershipVersion,
|
||||
interest_version: base.interestVersion,
|
||||
}
|
||||
: {
|
||||
version: live.current.version,
|
||||
action,
|
||||
reason: live.current.values.reason,
|
||||
client_key: createOperationKey(),
|
||||
partnership_version: base.partnershipVersion,
|
||||
interest_version: base.interestVersion,
|
||||
}
|
||||
: {
|
||||
...live.current.values,
|
||||
version: live.current.version,
|
||||
...(isNew ? { client_key: live.current.client_key } : {}),
|
||||
});
|
||||
const sentGenerations = pending.current?.generations ?? {
|
||||
...generation.current,
|
||||
};
|
||||
if ((isNew || kind === 'agreement') && !pending.current)
|
||||
pending.current = {
|
||||
command,
|
||||
generations: sentGenerations,
|
||||
ambiguous: false,
|
||||
base,
|
||||
values: { ...live.current.values },
|
||||
};
|
||||
const sentValues = { ...live.current.values };
|
||||
const attempt = pending.current;
|
||||
setProblem(null);
|
||||
form.transform(() => command);
|
||||
const unknown = () => {
|
||||
if (!alive.current) return false;
|
||||
if (kind === 'agreement' && pending.current !== attempt)
|
||||
return false;
|
||||
if (kind === 'agreement') setMustRefresh(true);
|
||||
if (pending.current) pending.current.ambiguous = true;
|
||||
else setNeedsCompare(true);
|
||||
setProblem(
|
||||
'A gravação não foi confirmada. As suas edições foram conservadas.',
|
||||
);
|
||||
return false;
|
||||
};
|
||||
const options = {
|
||||
preserveScroll: true,
|
||||
onSuccess: (page: { props: Record<string, unknown> }) => {
|
||||
if (!alive.current) return;
|
||||
if (kind === 'agreement') {
|
||||
if (
|
||||
attempt &&
|
||||
pending.current === attempt &&
|
||||
!acknowledgeAgreement(page.props, attempt)
|
||||
) {
|
||||
attempt.ambiguous = true;
|
||||
setMustRefresh(true);
|
||||
setNeedsCompare(true);
|
||||
setProblem(
|
||||
'A resposta não reconheceu esta tentativa. A preparação foi conservada.',
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (
|
||||
observedIdentity.current !==
|
||||
JSON.stringify([roomId, kind, itemId])
|
||||
)
|
||||
return;
|
||||
const saved = snapshot(
|
||||
page.props,
|
||||
roomId,
|
||||
kind,
|
||||
itemId,
|
||||
isNew ? String(command.client_key) : undefined,
|
||||
);
|
||||
if (
|
||||
!saved ||
|
||||
(!isNew && saved.version !== Number(command.version) + 1)
|
||||
) {
|
||||
setProblem(
|
||||
'A resposta não confirmou este registo. Recupere os dados antes de continuar; a edição foi conservada.',
|
||||
);
|
||||
setNeedsCompare(true);
|
||||
if (pending.current) pending.current.ambiguous = true;
|
||||
return;
|
||||
}
|
||||
if (!isNew) {
|
||||
if (
|
||||
milestoneKeys.some(
|
||||
(key) =>
|
||||
saved.values[key] !== normal(sentValues[key]),
|
||||
) ||
|
||||
saved.context !== base.context
|
||||
) {
|
||||
setProblem(
|
||||
'Os dados devolvidos diferem da operação enviada. Compare antes de continuar; a sua edição foi conservada.',
|
||||
);
|
||||
setNeedsCompare(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
const defaults = isNew
|
||||
? snapshot(page.props, roomId, kind, null)
|
||||
: saved;
|
||||
if (!defaults) return;
|
||||
const merged = { ...defaults.values };
|
||||
edited.current.clear();
|
||||
for (const key of keys)
|
||||
if (
|
||||
(generation.current[key] ?? 0) !==
|
||||
(sentGenerations[key] ?? 0)
|
||||
) {
|
||||
merged[key] = live.current.values[key];
|
||||
edited.current.add(key);
|
||||
}
|
||||
initial.current = defaults;
|
||||
if (isNew) {
|
||||
setCreated(saved.id);
|
||||
pending.current = null;
|
||||
}
|
||||
live.current = {
|
||||
version: defaults.version,
|
||||
client_key: isNew
|
||||
? createOperationKey()
|
||||
: live.current.client_key,
|
||||
values: merged,
|
||||
};
|
||||
form.setDefaults({ ...live.current, values: defaults.values });
|
||||
form.setData(live.current);
|
||||
form.clearErrors();
|
||||
setChoices({});
|
||||
setNeedsCompare(false);
|
||||
setProblem(null);
|
||||
},
|
||||
onError: () => {
|
||||
if (
|
||||
!alive.current ||
|
||||
(kind === 'agreement' && pending.current !== attempt)
|
||||
)
|
||||
return;
|
||||
if (pending.current && !pending.current.ambiguous)
|
||||
pending.current = null;
|
||||
},
|
||||
onHttpException: (response: { status: number }) =>
|
||||
kind === 'agreement' && pending.current !== attempt
|
||||
? false
|
||||
: httpFailure(response),
|
||||
onNetworkError: unknown,
|
||||
onCancel: unknown,
|
||||
};
|
||||
if (kind === 'agreement')
|
||||
form.post(`/parcerias/salas/${roomId}/acordo`, options);
|
||||
else if (isNew) form.post(`/parcerias/salas/${roomId}/marcos`, options);
|
||||
else form.put(`/parcerias/salas/${roomId}/marcos/${itemId}`, options);
|
||||
}
|
||||
return {
|
||||
form,
|
||||
values: form.data.values,
|
||||
current: current?.values ?? empty,
|
||||
baseVersion: initial.current?.version,
|
||||
version: current?.version,
|
||||
status: current?.status,
|
||||
stale,
|
||||
invalid,
|
||||
editable,
|
||||
dirty,
|
||||
blocked,
|
||||
refreshing,
|
||||
changed,
|
||||
conflicts,
|
||||
unresolved,
|
||||
problem,
|
||||
recovering,
|
||||
pendingAction:
|
||||
kind === 'agreement' && pending.current?.ambiguous
|
||||
? String(pending.current.command.action)
|
||||
: null,
|
||||
canRecover:
|
||||
kind === 'agreement' &&
|
||||
recovering &&
|
||||
!invalid &&
|
||||
!refreshing &&
|
||||
!form.processing,
|
||||
recover: () => submit('record', true),
|
||||
mustRefresh: kind === 'agreement' && mustRefresh,
|
||||
created,
|
||||
change,
|
||||
choose,
|
||||
adopt,
|
||||
refresh,
|
||||
submit,
|
||||
};
|
||||
}
|
||||
export type RoomEditor = ReturnType<typeof useRoomEdit>;
|
||||
|
||||
/** One room-level leave guard. No draft content is persisted in browser storage. */
|
||||
export function useRoomLeaveGuard(dirty: boolean) {
|
||||
const live = useRef(dirty);
|
||||
live.current = dirty;
|
||||
useEffect(() => {
|
||||
const leave = (event: BeforeUnloadEvent) => {
|
||||
if (live.current) {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
}
|
||||
};
|
||||
const stop = router.on('before', (event) => {
|
||||
if (
|
||||
live.current &&
|
||||
event.detail.visit.method === 'get' &&
|
||||
event.detail.visit.preserveState !== true &&
|
||||
!window.confirm(
|
||||
'Há alterações por guardar nesta sala. Pretende sair sem as guardar?',
|
||||
)
|
||||
)
|
||||
event.preventDefault();
|
||||
});
|
||||
window.addEventListener('beforeunload', leave);
|
||||
return () => {
|
||||
stop();
|
||||
window.removeEventListener('beforeunload', leave);
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import type { UsageReport } from './product-usage';
|
||||
|
||||
export type ExperimentValues = Record<string, string>;
|
||||
export type ExperimentDocument = {
|
||||
definition_version: string;
|
||||
version: number;
|
||||
at: string;
|
||||
actor: { id: number; name: string };
|
||||
reason: string;
|
||||
values: ExperimentValues;
|
||||
indicator: {
|
||||
id: string;
|
||||
title: string;
|
||||
unit: string;
|
||||
source: string;
|
||||
limits: string;
|
||||
definition_version: string;
|
||||
} | null;
|
||||
plan_sha256: string;
|
||||
observation_plan_sha256: string | null;
|
||||
registration: {
|
||||
first_at: string | null;
|
||||
original_plan_sha256: string | null;
|
||||
amendments: number;
|
||||
amended_after_observation: boolean;
|
||||
};
|
||||
operational_report: UsageReport | null;
|
||||
report_matches_observation: boolean | null;
|
||||
report_scope: string;
|
||||
};
|
||||
export type ExperimentView = {
|
||||
installed: boolean;
|
||||
id: string | null;
|
||||
currentVersion: number;
|
||||
historical: boolean;
|
||||
document: ExperimentDocument | null;
|
||||
values: ExperimentValues;
|
||||
states: Record<string, string>;
|
||||
changeKinds: Record<string, string>;
|
||||
decisions: Record<string, string>;
|
||||
labels: Record<string, string>;
|
||||
catalogue: {
|
||||
definition_version: string;
|
||||
items: Omit<
|
||||
NonNullable<ExperimentDocument['indicator']>,
|
||||
'definition_version'
|
||||
>[];
|
||||
services: { code: string; title: string; version: number }[];
|
||||
};
|
||||
history: {
|
||||
version: number;
|
||||
at: string;
|
||||
actor: string;
|
||||
state: string;
|
||||
reason: string;
|
||||
}[];
|
||||
historyNext: number | null;
|
||||
};
|
||||
|
||||
export function experimentDifferences(
|
||||
base: ExperimentValues,
|
||||
mine: ExperimentValues,
|
||||
current: ExperimentValues,
|
||||
editedKeys?: readonly string[],
|
||||
): string[] {
|
||||
return [
|
||||
...new Set([
|
||||
...Object.keys(base),
|
||||
...Object.keys(mine),
|
||||
...Object.keys(current),
|
||||
]),
|
||||
].filter(
|
||||
(key) =>
|
||||
(base[key] ?? '') !== (current[key] ?? '') &&
|
||||
(editedKeys
|
||||
? editedKeys.includes(key)
|
||||
: (mine[key] ?? '') !== (base[key] ?? '')) &&
|
||||
(mine[key] ?? '') !== (current[key] ?? ''),
|
||||
);
|
||||
}
|
||||
|
||||
/** Merge only changes the user did not edit; conflicts remain explicit. */
|
||||
export function mergeExperimentValues(
|
||||
base: ExperimentValues,
|
||||
mine: ExperimentValues,
|
||||
current: ExperimentValues,
|
||||
editedKeys?: readonly string[],
|
||||
): ExperimentValues {
|
||||
return Object.fromEntries(
|
||||
[
|
||||
...new Set([
|
||||
...Object.keys(base),
|
||||
...Object.keys(mine),
|
||||
...Object.keys(current),
|
||||
]),
|
||||
].map((key) => [
|
||||
key,
|
||||
(
|
||||
editedKeys
|
||||
? !editedKeys.includes(key)
|
||||
: (mine[key] ?? '') === (base[key] ?? '')
|
||||
)
|
||||
? (current[key] ?? '')
|
||||
: (mine[key] ?? ''),
|
||||
]),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
export type SearchUsageReport = {
|
||||
installed: boolean;
|
||||
enabled_now: boolean;
|
||||
applicable: boolean;
|
||||
from: string;
|
||||
to: string;
|
||||
timezone: string;
|
||||
read_at: string;
|
||||
definition_version: string;
|
||||
available_definitions: string[];
|
||||
definition_conflict_now: boolean;
|
||||
responses: number | null;
|
||||
zero_responses: number | null;
|
||||
zero_rate: number | null;
|
||||
channels: {
|
||||
id: string;
|
||||
label: string;
|
||||
responses: number | null;
|
||||
zero_responses: number | null;
|
||||
zero_rate: number | null;
|
||||
first_recorded_at: string | null;
|
||||
last_recorded_at: string | null;
|
||||
definition_versions: string[];
|
||||
}[];
|
||||
exclusions: string[];
|
||||
limits: string[];
|
||||
completeness: string;
|
||||
temporal_basis: string;
|
||||
};
|
||||
export type UsageReport = {
|
||||
definition_version: string;
|
||||
generated_at: string;
|
||||
timezone: string;
|
||||
observed_before: string;
|
||||
filters: {
|
||||
from: string;
|
||||
to: string;
|
||||
service_code: string | null;
|
||||
search_definition?: string;
|
||||
};
|
||||
search?: SearchUsageReport;
|
||||
services: { code: string; title: string; version: number }[];
|
||||
coverage: Record<string, number | null>;
|
||||
metrics: {
|
||||
id: string;
|
||||
title: string;
|
||||
value: number | null;
|
||||
unit: string;
|
||||
numerator: number | null;
|
||||
denominator: number | null;
|
||||
state: string;
|
||||
source: string;
|
||||
limits: string;
|
||||
}[];
|
||||
unmeasured: { id: string; title: string; reason: string; href?: string }[];
|
||||
limits: string[];
|
||||
fingerprint: string;
|
||||
read_consistency: string;
|
||||
};
|
||||
|
||||
export function usageValue(value: number | null, unit = ''): string {
|
||||
if (value === null) return 'Sem medição';
|
||||
return `${value.toLocaleString('pt-PT', { maximumFractionDigits: 2 })}${unit ? ` ${unit}` : ''}`;
|
||||
}
|
||||
|
||||
/** Export the applied server snapshot, never the pending filter form. */
|
||||
export function usageExport(report: UsageReport): string {
|
||||
return JSON.stringify(report, null, 2);
|
||||
}
|
||||
@@ -35,10 +35,20 @@ export async function profileJson(
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
...(typeof FormData !== 'undefined' && data instanceof FormData
|
||||
? {}
|
||||
: { 'Content-Type': 'application/json' }),
|
||||
...(method === 'GET' ? {} : { 'X-XSRF-TOKEN': token }),
|
||||
},
|
||||
...(method === 'GET' ? {} : { body: JSON.stringify(data) }),
|
||||
...(method === 'GET'
|
||||
? {}
|
||||
: {
|
||||
body:
|
||||
typeof FormData !== 'undefined' &&
|
||||
data instanceof FormData
|
||||
? data
|
||||
: JSON.stringify(data),
|
||||
}),
|
||||
});
|
||||
const result = await response.json().catch(() => null);
|
||||
const reauthenticate =
|
||||
|
||||
@@ -0,0 +1,406 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { portalRequest, PortalApiError } from './portal-api';
|
||||
import { createOperationKey } from './operation-key';
|
||||
import { usePagePreparationGuard } from './page-preparation-guard';
|
||||
export type SupportPlan = {
|
||||
actorId: number;
|
||||
target: { database: string; port: number };
|
||||
hash: string;
|
||||
code_hash: string;
|
||||
installed: boolean;
|
||||
consistent: boolean;
|
||||
repairable: boolean;
|
||||
ready: boolean;
|
||||
action: 'none' | 'install' | 'repair_known_base' | 'blocked';
|
||||
schema: { state: string; ledger: boolean };
|
||||
dependencies: Record<string, boolean>;
|
||||
changes: string[];
|
||||
backupDate: string | null;
|
||||
rollback: string;
|
||||
commands: { key: string; code_hash: string }[];
|
||||
mfa_confirmed: boolean;
|
||||
};
|
||||
type Attempt = {
|
||||
body: {
|
||||
hash: string;
|
||||
reason: string;
|
||||
confirm: true;
|
||||
idempotency_key: string;
|
||||
};
|
||||
code: string;
|
||||
generation: number;
|
||||
};
|
||||
const endpoint = '/management/profile-install/technical-support';
|
||||
const object = (v: unknown): v is Record<string, unknown> =>
|
||||
!!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const hex = (v: unknown): v is string =>
|
||||
typeof v === 'string' && /^[a-f0-9]{64}$/.test(v);
|
||||
const target = (v: unknown): v is SupportPlan['target'] =>
|
||||
object(v) &&
|
||||
typeof v.database === 'string' &&
|
||||
Number.isSafeInteger(v.port) &&
|
||||
Number(v.port) > 0;
|
||||
const validPlan = (v: unknown): v is SupportPlan =>
|
||||
object(v) &&
|
||||
typeof v.actorId === 'number' &&
|
||||
Number.isSafeInteger(v.actorId) &&
|
||||
v.actorId > 0 &&
|
||||
target(v.target) &&
|
||||
hex(v.hash) &&
|
||||
hex(v.code_hash) &&
|
||||
typeof v.installed === 'boolean' &&
|
||||
typeof v.consistent === 'boolean' &&
|
||||
typeof v.repairable === 'boolean' &&
|
||||
typeof v.ready === 'boolean' &&
|
||||
['none', 'install', 'repair_known_base', 'blocked'].includes(
|
||||
String(v.action),
|
||||
) &&
|
||||
object(v.schema) &&
|
||||
typeof v.schema.state === 'string' &&
|
||||
typeof v.schema.ledger === 'boolean' &&
|
||||
object(v.dependencies) &&
|
||||
Object.values(v.dependencies).every((x) => typeof x === 'boolean') &&
|
||||
Array.isArray(v.changes) &&
|
||||
v.changes.every((x) => typeof x === 'string') &&
|
||||
(v.backupDate === null || typeof v.backupDate === 'string') &&
|
||||
typeof v.rollback === 'string' &&
|
||||
typeof v.mfa_confirmed === 'boolean' &&
|
||||
Array.isArray(v.commands) &&
|
||||
v.commands.every(
|
||||
(x) => object(x) && typeof x.key === 'string' && hex(x.code_hash),
|
||||
);
|
||||
const sameTarget = (a: SupportPlan['target'], b: SupportPlan['target']) =>
|
||||
a.database === b.database && a.port === b.port;
|
||||
export function useProfileSupportInstallation(initial: SupportPlan) {
|
||||
const [plan, setPlan] = useState(initial),
|
||||
[base, setBase] = useState(initial),
|
||||
[reason, setReason] = useState(''),
|
||||
[confirmed, setConfirmed] = useState(false),
|
||||
[busy, setBusy] = useState(false),
|
||||
[refreshing, setRefreshing] = useState(false),
|
||||
[uncertain, setUncertain] = useState(false),
|
||||
[blocked, setBlocked] = useState(false),
|
||||
[needsRefresh, setNeedsRefresh] = useState(false),
|
||||
[message, setMessage] = useState(''),
|
||||
[error, setError] = useState('');
|
||||
const origin = useRef({ actor: initial.actorId, target: initial.target }),
|
||||
epoch = useRef({ actor: initial.actorId, target: initial.target }),
|
||||
alive = useRef(true),
|
||||
pending = useRef<Attempt | null>(null),
|
||||
active = useRef<Attempt | null>(null),
|
||||
reading = useRef<object | null>(null),
|
||||
generation = useRef(0),
|
||||
text = useRef(reason),
|
||||
committed = useRef<Attempt | null>(null);
|
||||
if (
|
||||
epoch.current.actor !== initial.actorId ||
|
||||
!sameTarget(epoch.current.target, initial.target)
|
||||
)
|
||||
epoch.current = { actor: initial.actorId, target: initial.target };
|
||||
text.current = reason;
|
||||
const valid =
|
||||
validPlan(plan) &&
|
||||
plan.actorId === origin.current.actor &&
|
||||
sameTarget(plan.target, origin.current.target) &&
|
||||
initial.actorId === origin.current.actor &&
|
||||
sameTarget(initial.target, origin.current.target);
|
||||
const stale = base.hash !== plan.hash;
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
};
|
||||
}, []);
|
||||
function change(value: string) {
|
||||
generation.current++;
|
||||
text.current = value;
|
||||
setReason(value);
|
||||
setConfirmed(false);
|
||||
setError('');
|
||||
}
|
||||
function acknowledge(attempt: Attempt) {
|
||||
if (pending.current !== attempt) return;
|
||||
pending.current = null;
|
||||
active.current = null;
|
||||
committed.current = attempt;
|
||||
setBusy(false);
|
||||
setUncertain(false);
|
||||
setNeedsRefresh(true);
|
||||
setConfirmed(false);
|
||||
setError('');
|
||||
setMessage(
|
||||
'Resultado da actualização confirmado. Confira a prévia actual.',
|
||||
);
|
||||
if (generation.current === attempt.generation) {
|
||||
text.current = '';
|
||||
setReason('');
|
||||
}
|
||||
}
|
||||
function read(value: unknown) {
|
||||
if (
|
||||
!validPlan(value) ||
|
||||
value.actorId !== origin.current.actor ||
|
||||
!sameTarget(value.target, origin.current.target)
|
||||
)
|
||||
return false;
|
||||
setPlan(value);
|
||||
setBlocked(false);
|
||||
setError('');
|
||||
const attempt = pending.current;
|
||||
if (
|
||||
attempt &&
|
||||
value.commands.some(
|
||||
(c) =>
|
||||
c.key === attempt.body.idempotency_key &&
|
||||
c.code_hash === attempt.code,
|
||||
)
|
||||
)
|
||||
acknowledge(attempt);
|
||||
const known = committed.current;
|
||||
if (known) {
|
||||
if (
|
||||
!value.commands.some(
|
||||
(c) =>
|
||||
c.key === known.body.idempotency_key &&
|
||||
c.code_hash === known.code,
|
||||
)
|
||||
) {
|
||||
setError(
|
||||
'Esta consulta ainda não confirma o resultado já recebido. Actualize novamente antes de outra acção.',
|
||||
);
|
||||
return true;
|
||||
}
|
||||
if (
|
||||
value.code_hash === known.code &&
|
||||
value.installed &&
|
||||
value.consistent
|
||||
)
|
||||
setBase(value);
|
||||
committed.current = null;
|
||||
setNeedsRefresh(false);
|
||||
} else setNeedsRefresh(false);
|
||||
return true;
|
||||
}
|
||||
useEffect(() => {
|
||||
if (validPlan(initial)) read(initial);
|
||||
}, [initial]);
|
||||
async function refresh() {
|
||||
if (reading.current) return;
|
||||
const request = {},
|
||||
scope = epoch.current;
|
||||
reading.current = request;
|
||||
setRefreshing(true);
|
||||
try {
|
||||
const value = await portalRequest<unknown>(endpoint);
|
||||
if (alive.current && epoch.current === scope && !read(value))
|
||||
setError(
|
||||
'A consulta recebida não corresponde a esta conta e destino. A preparação foi conservada.',
|
||||
);
|
||||
} catch (e) {
|
||||
if (alive.current && epoch.current === scope) {
|
||||
if (
|
||||
e instanceof PortalApiError &&
|
||||
[401, 403, 419].includes(e.status)
|
||||
)
|
||||
setBlocked(true);
|
||||
setError(
|
||||
'Não foi possível actualizar a prévia. O fundamento e a tentativa original foram conservados.',
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (
|
||||
alive.current &&
|
||||
epoch.current === scope &&
|
||||
reading.current === request
|
||||
) {
|
||||
reading.current = null;
|
||||
setRefreshing(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
async function send(retry = false) {
|
||||
if (
|
||||
!valid ||
|
||||
blocked ||
|
||||
!plan.mfa_confirmed ||
|
||||
active.current ||
|
||||
reading.current
|
||||
)
|
||||
return;
|
||||
if (
|
||||
!retry &&
|
||||
(pending.current ||
|
||||
stale ||
|
||||
needsRefresh ||
|
||||
!confirmed ||
|
||||
!plan.ready ||
|
||||
plan.installed ||
|
||||
!plan.mfa_confirmed ||
|
||||
(!plan.consistent && !plan.repairable))
|
||||
)
|
||||
return;
|
||||
let attempt = pending.current;
|
||||
if (!attempt) {
|
||||
if (text.current.trim().length < 20 || text.current.length > 1000) {
|
||||
setError('Preencha o fundamento com 20 a 1000 caracteres.');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
attempt = {
|
||||
body: {
|
||||
hash: base.hash,
|
||||
reason: text.current,
|
||||
confirm: true,
|
||||
idempotency_key: createOperationKey().toLowerCase(),
|
||||
},
|
||||
code: base.code_hash,
|
||||
generation: generation.current,
|
||||
};
|
||||
} catch (e) {
|
||||
setError(
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Não foi possível preparar a operação.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
pending.current = attempt;
|
||||
}
|
||||
const scope = epoch.current;
|
||||
active.current = attempt;
|
||||
setBusy(true);
|
||||
setUncertain(true);
|
||||
setError('');
|
||||
try {
|
||||
const result = await portalRequest<unknown>(endpoint, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(attempt.body),
|
||||
});
|
||||
if (
|
||||
!alive.current ||
|
||||
epoch.current !== scope ||
|
||||
pending.current !== attempt
|
||||
)
|
||||
return;
|
||||
if (
|
||||
!object(result) ||
|
||||
result.actor_id !== origin.current.actor ||
|
||||
result.command_key !== attempt.body.idempotency_key ||
|
||||
result.migration !==
|
||||
'2026_11_03_080000_add_technical_support_profile' ||
|
||||
result.code_hash !== attempt.code ||
|
||||
result.installed !== true ||
|
||||
!target(result.target) ||
|
||||
!sameTarget(result.target, origin.current.target)
|
||||
)
|
||||
throw new Error(
|
||||
'A confirmação não corresponde à tentativa preparada. Consulte a prévia antes de continuar.',
|
||||
);
|
||||
acknowledge(attempt);
|
||||
void refresh();
|
||||
} catch (e) {
|
||||
if (
|
||||
!alive.current ||
|
||||
epoch.current !== scope ||
|
||||
pending.current !== attempt
|
||||
)
|
||||
return;
|
||||
if (e instanceof PortalApiError && [409, 422].includes(e.status)) {
|
||||
pending.current = null;
|
||||
setUncertain(false);
|
||||
setConfirmed(false);
|
||||
setError(
|
||||
e.status === 409
|
||||
? 'A tentativa foi recusada porque o plano mudou. Actualize e compare a prévia; o fundamento foi conservado.'
|
||||
: e.errors.reason?.join(' ') ||
|
||||
'A operação foi recusada. Confira as dependências, as provas e o fundamento.',
|
||||
);
|
||||
if (e.status === 409) {
|
||||
setNeedsRefresh(true);
|
||||
void refresh();
|
||||
}
|
||||
} else if (
|
||||
e instanceof PortalApiError &&
|
||||
[401, 403, 419].includes(e.status)
|
||||
) {
|
||||
setBlocked(true);
|
||||
setError(
|
||||
'Confirme a conta e renove a autenticação MFA antes de repetir. A preparação foi conservada.',
|
||||
);
|
||||
} else
|
||||
setError(
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Resultado sem confirmação. Conserve a tentativa original.',
|
||||
);
|
||||
} finally {
|
||||
if (
|
||||
alive.current &&
|
||||
epoch.current === scope &&
|
||||
active.current === attempt
|
||||
) {
|
||||
active.current = null;
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
function adopt() {
|
||||
if (!valid || busy || refreshing || pending.current || blocked) return;
|
||||
setBase(plan);
|
||||
setConfirmed(false);
|
||||
setNeedsRefresh(false);
|
||||
setMessage(
|
||||
'Prévia actual confirmada. Reveja o fundamento e confirme esta operação.',
|
||||
);
|
||||
setError('');
|
||||
}
|
||||
usePagePreparationGuard(
|
||||
!!reason || uncertain,
|
||||
'Existe um fundamento preparado ou uma instalação sem confirmação. Sair desta página?',
|
||||
);
|
||||
return {
|
||||
plan,
|
||||
base,
|
||||
reason,
|
||||
change,
|
||||
confirmed,
|
||||
setConfirmed,
|
||||
busy,
|
||||
refreshing,
|
||||
uncertain,
|
||||
message,
|
||||
error,
|
||||
stale,
|
||||
refresh,
|
||||
send,
|
||||
adopt,
|
||||
canAdopt:
|
||||
valid &&
|
||||
!busy &&
|
||||
!refreshing &&
|
||||
!pending.current &&
|
||||
!blocked &&
|
||||
stale,
|
||||
canRetry:
|
||||
valid &&
|
||||
plan.mfa_confirmed &&
|
||||
!busy &&
|
||||
!refreshing &&
|
||||
!blocked &&
|
||||
!!pending.current,
|
||||
canSend:
|
||||
valid &&
|
||||
!blocked &&
|
||||
!busy &&
|
||||
!refreshing &&
|
||||
!needsRefresh &&
|
||||
!stale &&
|
||||
!uncertain &&
|
||||
confirmed &&
|
||||
plan.ready &&
|
||||
!plan.installed &&
|
||||
plan.mfa_confirmed &&
|
||||
(plan.consistent || plan.repairable),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
import { router } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { portalRequest, PortalApiError } from './portal-api';
|
||||
import { createOperationKey } from './operation-key';
|
||||
export type HandlingState = {
|
||||
version: number;
|
||||
status: 'open' | 'in_progress' | 'resolved';
|
||||
assignee_user_id: number | null;
|
||||
assignee_name: string | null;
|
||||
updated_at: string | null;
|
||||
resolved_at: string | null;
|
||||
};
|
||||
export type Incident = {
|
||||
reference: string;
|
||||
operation: string;
|
||||
observed_version: number;
|
||||
occurred_at: string;
|
||||
error_code: string;
|
||||
handling: HandlingState;
|
||||
};
|
||||
export type Command = 'claim' | 'release' | 'note' | 'resolve' | 'reopen';
|
||||
export type HandlingProps = {
|
||||
incident: Incident;
|
||||
actorId: number;
|
||||
commands: { key: string; version: number }[];
|
||||
};
|
||||
type Attempt = {
|
||||
values: {
|
||||
version: number;
|
||||
action: Command;
|
||||
note: string;
|
||||
operation_key: string;
|
||||
};
|
||||
generation: number;
|
||||
};
|
||||
const object = (v: unknown): v is Record<string, unknown> =>
|
||||
!!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const integer = (v: unknown, min = 0): v is number =>
|
||||
typeof v === 'number' && Number.isSafeInteger(v) && v >= min;
|
||||
const validState = (v: unknown): v is HandlingState =>
|
||||
object(v) &&
|
||||
integer(v.version) &&
|
||||
['open', 'in_progress', 'resolved'].includes(String(v.status)) &&
|
||||
(v.assignee_user_id === null || integer(v.assignee_user_id, 1)) &&
|
||||
(v.assignee_name === null || typeof v.assignee_name === 'string') &&
|
||||
(v.updated_at === null || typeof v.updated_at === 'string') &&
|
||||
(v.resolved_at === null || typeof v.resolved_at === 'string');
|
||||
export function useTechnicalIncidentHandling(props: HandlingProps) {
|
||||
const { incident, actorId, commands } = props;
|
||||
const [note, setNote] = useState(''),
|
||||
[base, setBase] = useState(() => ({ ...incident.handling })),
|
||||
[busy, setBusy] = useState(false),
|
||||
[uncertain, setUncertain] = useState(false),
|
||||
[refreshing, setRefreshing] = useState(false),
|
||||
[blocked, setBlocked] = useState(false),
|
||||
[needsRefresh, setNeedsRefresh] = useState(false),
|
||||
[notice, setNotice] = useState(''),
|
||||
[error, setError] = useState('');
|
||||
const pending = useRef<Attempt | null>(null),
|
||||
activeRequest = useRef<Attempt | null>(null),
|
||||
liveNote = useRef(note),
|
||||
generation = useRef(0),
|
||||
confirmed = useRef<number | null>(null),
|
||||
alive = useRef(true),
|
||||
origin = useRef({ actorId, reference: incident.reference }),
|
||||
scope = useRef({ actorId, reference: incident.reference });
|
||||
if (
|
||||
scope.current.actorId !== actorId ||
|
||||
scope.current.reference !== incident.reference
|
||||
)
|
||||
scope.current = { actorId, reference: incident.reference };
|
||||
liveNote.current = note;
|
||||
const valid =
|
||||
integer(actorId, 1) &&
|
||||
actorId === origin.current.actorId &&
|
||||
incident.reference === origin.current.reference &&
|
||||
validState(incident.handling) &&
|
||||
Array.isArray(commands) &&
|
||||
commands.every(
|
||||
(item) => typeof item.key === 'string' && integer(item.version, 1),
|
||||
);
|
||||
const stale = base.version !== incident.handling.version;
|
||||
function change(value: string) {
|
||||
generation.current++;
|
||||
liveNote.current = value;
|
||||
setNote(value);
|
||||
setError('');
|
||||
}
|
||||
function acknowledge(attempt: Attempt, version: number) {
|
||||
if (pending.current !== attempt) return;
|
||||
pending.current = null;
|
||||
activeRequest.current = null;
|
||||
setBusy(false);
|
||||
setUncertain(false);
|
||||
setNeedsRefresh(true);
|
||||
confirmed.current = version;
|
||||
if (generation.current === attempt.generation) {
|
||||
liveNote.current = '';
|
||||
setNote('');
|
||||
}
|
||||
setNotice(
|
||||
'Tratamento registado. As alterações posteriores da nota foram conservadas.',
|
||||
);
|
||||
setError('');
|
||||
}
|
||||
function read(value: unknown) {
|
||||
if (
|
||||
!object(value) ||
|
||||
value.actorId !== actorId ||
|
||||
!object(value.incident) ||
|
||||
value.incident.reference !== incident.reference ||
|
||||
!validState(value.incident.handling) ||
|
||||
!Array.isArray(value.commands)
|
||||
)
|
||||
return false;
|
||||
const attempt = pending.current;
|
||||
if (
|
||||
attempt &&
|
||||
value.commands.some(
|
||||
(c) =>
|
||||
object(c) &&
|
||||
c.key === attempt.values.operation_key &&
|
||||
c.version === attempt.values.version + 1,
|
||||
) &&
|
||||
value.incident.handling.version >= attempt.values.version + 1
|
||||
)
|
||||
acknowledge(attempt, attempt.values.version + 1);
|
||||
if (confirmed.current !== null) {
|
||||
if (value.incident.handling.version === confirmed.current)
|
||||
setBase({ ...value.incident.handling });
|
||||
if (value.incident.handling.version >= confirmed.current) {
|
||||
confirmed.current = null;
|
||||
setNeedsRefresh(false);
|
||||
}
|
||||
}
|
||||
setBlocked(false);
|
||||
return true;
|
||||
}
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
return () => {
|
||||
alive.current = false;
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (valid) read(props);
|
||||
}, [incident, commands, actorId]);
|
||||
function refresh() {
|
||||
if (refreshing) return;
|
||||
const epoch = scope.current;
|
||||
setRefreshing(true);
|
||||
router.reload({
|
||||
only: ['incident', 'history', 'commands', 'actorId'],
|
||||
onSuccess: (page) => {
|
||||
if (
|
||||
alive.current &&
|
||||
scope.current === epoch &&
|
||||
!read(page.props)
|
||||
)
|
||||
setError(
|
||||
'Não foi possível confirmar esta consulta. A nota preparada foi conservada.',
|
||||
);
|
||||
},
|
||||
onError: () => {
|
||||
if (alive.current && scope.current === epoch)
|
||||
setError(
|
||||
'Não foi possível actualizar o incidente. A nota foi conservada.',
|
||||
);
|
||||
},
|
||||
onFinish: () => {
|
||||
if (alive.current && scope.current === epoch)
|
||||
setRefreshing(false);
|
||||
},
|
||||
});
|
||||
}
|
||||
async function send(action: Command, retry = false) {
|
||||
if (
|
||||
!valid ||
|
||||
blocked ||
|
||||
refreshing ||
|
||||
activeRequest.current ||
|
||||
(!retry && (stale || needsRefresh || pending.current))
|
||||
)
|
||||
return;
|
||||
let attempt = pending.current;
|
||||
if (!attempt) {
|
||||
if (
|
||||
liveNote.current.trim().length < 10 ||
|
||||
liveNote.current.length > 3000
|
||||
) {
|
||||
setError('Preencha uma nota com 10 a 3000 caracteres.');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
attempt = {
|
||||
values: {
|
||||
version: base.version,
|
||||
action,
|
||||
note: liveNote.current,
|
||||
operation_key: createOperationKey().toLowerCase(),
|
||||
},
|
||||
generation: generation.current,
|
||||
};
|
||||
} catch (e) {
|
||||
setError(
|
||||
e instanceof Error
|
||||
? e.message
|
||||
: 'Não foi possível preparar o registo.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
pending.current = attempt;
|
||||
}
|
||||
const epoch = scope.current;
|
||||
activeRequest.current = attempt;
|
||||
setBusy(true);
|
||||
setUncertain(true);
|
||||
setError('');
|
||||
try {
|
||||
const result = await portalRequest<unknown>(
|
||||
`/suporte-tecnico/incidentes/${incident.reference}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(attempt.values),
|
||||
},
|
||||
);
|
||||
if (
|
||||
!alive.current ||
|
||||
scope.current !== epoch ||
|
||||
pending.current !== attempt
|
||||
)
|
||||
return;
|
||||
if (
|
||||
!object(result) ||
|
||||
result.reference !== incident.reference ||
|
||||
result.actor_id !== actorId ||
|
||||
result.operation_key !== attempt.values.operation_key ||
|
||||
result.result_version !== attempt.values.version + 1 ||
|
||||
!validState(result.handling) ||
|
||||
result.handling.version < result.result_version
|
||||
)
|
||||
throw new Error(
|
||||
'A confirmação recebida não corresponde a esta tentativa. Actualize o incidente.',
|
||||
);
|
||||
acknowledge(attempt, result.result_version);
|
||||
refresh();
|
||||
} catch (e) {
|
||||
if (
|
||||
!alive.current ||
|
||||
scope.current !== epoch ||
|
||||
pending.current !== attempt
|
||||
)
|
||||
return;
|
||||
if (e instanceof PortalApiError && e.status === 422) {
|
||||
pending.current = null;
|
||||
setUncertain(false);
|
||||
setError(
|
||||
e.errors.note?.join(' ') ||
|
||||
'Este tratamento não pode ser aplicado ao estado actual. Actualize os dados e reveja a nota.',
|
||||
);
|
||||
} else if (
|
||||
e instanceof PortalApiError &&
|
||||
(e.status === 403 || e.status === 401 || e.status === 419)
|
||||
) {
|
||||
setBlocked(true);
|
||||
setError(
|
||||
'O acesso ou a sessão precisam de confirmação. A nota e a tentativa original foram conservadas.',
|
||||
);
|
||||
} else
|
||||
setError(
|
||||
e instanceof PortalApiError && e.status === 409
|
||||
? 'O incidente mudou. Actualize e compare o estado antes de preparar outra tentativa.'
|
||||
: e instanceof Error
|
||||
? e.message
|
||||
: 'Resultado sem confirmação. Conserve a tentativa original.',
|
||||
);
|
||||
} finally {
|
||||
if (
|
||||
alive.current &&
|
||||
scope.current === epoch &&
|
||||
activeRequest.current === attempt
|
||||
) {
|
||||
activeRequest.current = null;
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
function adopt() {
|
||||
if (!valid || !stale || busy || refreshing || needsRefresh || blocked)
|
||||
return;
|
||||
const attempt = pending.current;
|
||||
if (attempt) {
|
||||
if (
|
||||
incident.handling.version <= attempt.values.version ||
|
||||
commands.some((c) => c.key === attempt.values.operation_key)
|
||||
)
|
||||
return;
|
||||
pending.current = null;
|
||||
setUncertain(false);
|
||||
}
|
||||
setBase({ ...incident.handling });
|
||||
setError('');
|
||||
setNotice(
|
||||
'Estado actual confirmado. Reveja a nota conservada antes de a enviar.',
|
||||
);
|
||||
}
|
||||
const guard = useRef(false);
|
||||
guard.current = !!note || uncertain;
|
||||
useEffect(() => {
|
||||
const remove = router.on('before', (event) => {
|
||||
if (
|
||||
guard.current &&
|
||||
event.detail.visit.method === 'get' &&
|
||||
!event.detail.visit.preserveState &&
|
||||
!window.confirm(
|
||||
'Existe uma nota preparada ou um envio sem confirmação. Sair desta página?',
|
||||
)
|
||||
)
|
||||
event.preventDefault();
|
||||
});
|
||||
const unload = (event: BeforeUnloadEvent) => {
|
||||
if (guard.current) {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
}
|
||||
};
|
||||
window.addEventListener('beforeunload', unload);
|
||||
return () => {
|
||||
remove();
|
||||
window.removeEventListener('beforeunload', unload);
|
||||
};
|
||||
}, []);
|
||||
return {
|
||||
note,
|
||||
change,
|
||||
base,
|
||||
stale,
|
||||
busy,
|
||||
uncertain,
|
||||
refreshing,
|
||||
notice,
|
||||
error,
|
||||
refresh,
|
||||
send,
|
||||
adopt,
|
||||
blocked:
|
||||
!valid ||
|
||||
blocked ||
|
||||
busy ||
|
||||
refreshing ||
|
||||
needsRefresh ||
|
||||
stale ||
|
||||
uncertain,
|
||||
canRetry:
|
||||
valid && !blocked && !busy && !refreshing && !!pending.current,
|
||||
canAdopt:
|
||||
valid &&
|
||||
!blocked &&
|
||||
!busy &&
|
||||
!refreshing &&
|
||||
!needsRefresh &&
|
||||
stale &&
|
||||
(!pending.current ||
|
||||
incident.handling.version > pending.current.values.version),
|
||||
pendingAction: pending.current?.values.action,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { Command } from './technical-incident-handling';
|
||||
export const incidentOperationLabels: Record<string, string> = {
|
||||
submit: 'Submissão para validação',
|
||||
publish: 'Publicação',
|
||||
upload_document: 'Carregamento de documento',
|
||||
upload_image: 'Carregamento de imagem',
|
||||
prepare_image: 'Preparação de imagens WebP',
|
||||
scan_document: 'Análise de segurança de documento',
|
||||
};
|
||||
export function incidentOperationLabel(operation: string) {
|
||||
return (
|
||||
incidentOperationLabels[operation] ||
|
||||
'Operação técnica não identificada'
|
||||
);
|
||||
}
|
||||
export function incidentErrorLabel(code: string) {
|
||||
return (
|
||||
(
|
||||
{
|
||||
database_failure:
|
||||
'Falha no serviço de dados durante a operação.',
|
||||
workflow_unavailable: 'Falha técnica durante a operação.',
|
||||
scan_dispatch_unconfirmed:
|
||||
'Encaminhamento da análise sem confirmação.',
|
||||
scan_inconclusive: 'Análise de segurança inconclusiva.',
|
||||
scan_worker_failed:
|
||||
'Falha na execução da análise de segurança.',
|
||||
scan_cleanup_unconfirmed:
|
||||
'Limpeza do ficheiro temporário por confirmar.',
|
||||
} as Record<string, string>
|
||||
)[code] || 'Falha técnica durante a operação.'
|
||||
);
|
||||
}
|
||||
export const handlingLabels: Record<string, string> = {
|
||||
open: 'Na fila',
|
||||
in_progress: 'Em tratamento',
|
||||
resolved: 'Resolvido',
|
||||
};
|
||||
export const commandLabels: Record<Command, string> = {
|
||||
claim: 'Assumir tratamento',
|
||||
release: 'Devolver à fila',
|
||||
note: 'Acrescentar nota',
|
||||
resolve: 'Resolver incidente',
|
||||
reopen: 'Reabrir incidente',
|
||||
};
|
||||
Reference in New Issue
Block a user