Complete durable private Education review preparation and recovery
tests / ci (push) Canceled after 0s
tests / ci (push) Canceled after 0s
This commit is contained in:
@@ -16,6 +16,46 @@ export default function EducationReview(props: EducationReviewProps) {
|
||||
aria-label="Revisão interna da declaração"
|
||||
>
|
||||
{edit.notice && <p role="status">{edit.notice}</p>}
|
||||
{edit.preparationAvailable && (
|
||||
<section
|
||||
className="space-y-2 rounded border p-3"
|
||||
aria-label="Preparação privada da revisão"
|
||||
>
|
||||
<p>
|
||||
Guarde a preparação para retomar noutra entrada. É
|
||||
privada desta conta e declaração; guardar não decide nem
|
||||
aprova a declaração.
|
||||
</p>
|
||||
{edit.savedPreparation?.version ? (
|
||||
<p>
|
||||
Preparação guardada: versão{' '}
|
||||
{edit.savedPreparation.version}.
|
||||
</p>
|
||||
) : (
|
||||
<p>Ainda sem preparação privada guardada.</p>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={edit.persisting}
|
||||
onClick={() => void edit.persistPreparation()}
|
||||
>
|
||||
Guardar preparação da revisão
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={button}
|
||||
disabled={edit.persisting || form.processing}
|
||||
onClick={() => void edit.restorePreparation()}
|
||||
>
|
||||
Recuperar preparação guardada
|
||||
</button>
|
||||
{edit.persisting && (
|
||||
<p role="status">A conferir a preparação privada…</p>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{(edit.stale || edit.conflict) && (
|
||||
<section
|
||||
className="space-y-3 rounded border p-4"
|
||||
@@ -155,7 +195,7 @@ export default function EducationReview(props: EducationReviewProps) {
|
||||
</h2>
|
||||
{edit.uncertain && (
|
||||
<p>
|
||||
A recuperação repete a decisão enviada:{' '}
|
||||
A recuperação mantém a mesma intenção de revisão:{' '}
|
||||
{states[edit.sent?.status ?? ''] ?? 'Por confirmar'}
|
||||
. Fundamento: {edit.sent?.review_reason}. As edições
|
||||
posteriores ficam conservadas.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { router, useForm } from '@inertiajs/react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { createOperationKey } from './operation-key';
|
||||
import { profileJson } from './profile-json';
|
||||
|
||||
export type EducationDeclaration = {
|
||||
id: string;
|
||||
@@ -29,6 +30,7 @@ export type EducationReviewProps = {
|
||||
kind: 'demands' | 'capacities';
|
||||
actorId: number;
|
||||
today: string;
|
||||
preparation?: ReviewPreparation;
|
||||
references?: Record<string, string | null>;
|
||||
};
|
||||
type Values = { version_no: number; status: string; review_reason: string };
|
||||
@@ -53,6 +55,27 @@ type Attempt = {
|
||||
statusGeneration: number;
|
||||
base: Snapshot;
|
||||
};
|
||||
export type ReviewPreparationSnapshot = {
|
||||
values: Values;
|
||||
generation: { status: number; review_reason: number };
|
||||
base: Snapshot;
|
||||
pending: Attempt | null;
|
||||
};
|
||||
export type ReviewPreparation = {
|
||||
actor_id: number;
|
||||
kind: 'demands' | 'capacities';
|
||||
record_id: string;
|
||||
version: number;
|
||||
operation_key: string | null;
|
||||
snapshot: ReviewPreparationSnapshot | null;
|
||||
unavailable: boolean;
|
||||
};
|
||||
type PreparationSave = {
|
||||
actor_id: number;
|
||||
version: number;
|
||||
operation_key: string;
|
||||
snapshot: ReviewPreparationSnapshot;
|
||||
};
|
||||
const object = (value: unknown): value is Record<string, unknown> =>
|
||||
!!value && typeof value === 'object' && !Array.isArray(value);
|
||||
const positive = (value: unknown): value is number =>
|
||||
@@ -79,6 +102,7 @@ export function useEducationReview({
|
||||
kind,
|
||||
actorId,
|
||||
references = {},
|
||||
preparation,
|
||||
}: EducationReviewProps) {
|
||||
const form = useForm<Values>({
|
||||
version_no: row.version_no,
|
||||
@@ -91,6 +115,8 @@ export function useEducationReview({
|
||||
pending = useRef<Attempt | null>(null),
|
||||
alive = useRef(true);
|
||||
const generation = useRef({ status: 0, review_reason: 0 });
|
||||
const observed = useRef({ row, references });
|
||||
observed.current = { row, references };
|
||||
const [uncertain, setUncertain] = useState(false),
|
||||
[conflict, setConflict] = useState(false),
|
||||
[refreshing, setRefreshing] = useState(false),
|
||||
@@ -102,6 +128,229 @@ export function useEducationReview({
|
||||
alive.current = false;
|
||||
};
|
||||
}, []);
|
||||
const [savedPreparation, setSavedPreparation] = useState(
|
||||
preparation ?? null,
|
||||
);
|
||||
const [persisting, setPersisting] = useState(false);
|
||||
const preparationVersion = useRef(preparation?.version ?? 0);
|
||||
const preparationSave = useRef<PreparationSave | null>(null);
|
||||
const saving = useRef(false);
|
||||
const preparationUrl = `/management/education/${kind}/${row.id}/review-preparation`;
|
||||
function privateSnapshot(): ReviewPreparationSnapshot {
|
||||
return structuredClone({
|
||||
values: live.current,
|
||||
generation: generation.current,
|
||||
base: base.current,
|
||||
pending: pending.current,
|
||||
});
|
||||
}
|
||||
function validPreparation(value: unknown): value is ReviewPreparation {
|
||||
const nonnegative = (n: unknown): n is number =>
|
||||
typeof n === 'number' && Number.isSafeInteger(n) && n >= 0;
|
||||
const values = (v: unknown): v is Values =>
|
||||
object(v) &&
|
||||
positive(v.version_no) &&
|
||||
typeof v.review_reason === 'string' &&
|
||||
['reviewed', 'rejected'].includes(String(v.status));
|
||||
const evidence = (v: unknown): v is Snapshot =>
|
||||
object(v) &&
|
||||
positive(v.version_no) &&
|
||||
nonnegative(v.quantity) &&
|
||||
[
|
||||
'qualification',
|
||||
'status',
|
||||
'period_start',
|
||||
'period_end',
|
||||
'valid_until',
|
||||
'source',
|
||||
'reference_date',
|
||||
'employer',
|
||||
].every((k) => typeof v[k] === 'string') &&
|
||||
object(v.references) &&
|
||||
Object.values(v.references).every(
|
||||
(v) => v === null || typeof v === 'string',
|
||||
);
|
||||
if (
|
||||
!object(value) ||
|
||||
value.actor_id !== actorId ||
|
||||
value.kind !== kind ||
|
||||
value.record_id !== row.id ||
|
||||
!nonnegative(value.version) ||
|
||||
!(
|
||||
value.operation_key === null ||
|
||||
typeof value.operation_key === 'string'
|
||||
) ||
|
||||
typeof value.unavailable !== 'boolean'
|
||||
)
|
||||
return false;
|
||||
if (value.snapshot === null) return true;
|
||||
const state = value.snapshot;
|
||||
if (
|
||||
!object(state) ||
|
||||
!values(state.values) ||
|
||||
!evidence(state.base) ||
|
||||
state.values.version_no !== state.base.version_no ||
|
||||
!object(state.generation) ||
|
||||
!nonnegative(state.generation.status) ||
|
||||
!nonnegative(state.generation.review_reason)
|
||||
)
|
||||
return false;
|
||||
return (
|
||||
state.pending === null ||
|
||||
(object(state.pending) &&
|
||||
values(state.pending.values) &&
|
||||
object(state.pending.values) &&
|
||||
'client_key' in state.pending.values &&
|
||||
typeof state.pending.values.client_key === 'string' &&
|
||||
evidence(state.pending.base) &&
|
||||
state.pending.values.version_no ===
|
||||
state.pending.base.version_no &&
|
||||
nonnegative(state.pending.reasonGeneration) &&
|
||||
nonnegative(state.pending.statusGeneration))
|
||||
);
|
||||
}
|
||||
async function persistPreparation(attempt?: Attempt): Promise<boolean> {
|
||||
if (
|
||||
invalid ||
|
||||
preparation === undefined ||
|
||||
saving.current ||
|
||||
(attempt !== undefined && form.processing)
|
||||
)
|
||||
return false;
|
||||
saving.current = true;
|
||||
setPersisting(true);
|
||||
try {
|
||||
preparationSave.current ??= {
|
||||
actor_id: actorId,
|
||||
version: preparationVersion.current,
|
||||
operation_key: createOperationKey(),
|
||||
snapshot: privateSnapshot(),
|
||||
};
|
||||
const sent = preparationSave.current;
|
||||
const value = await profileJson(preparationUrl, sent);
|
||||
if (!alive.current || preparationSave.current !== sent)
|
||||
return false;
|
||||
if (!validPreparation(value))
|
||||
throw new Error(
|
||||
'A resposta da preparação não pôde ser conferida.',
|
||||
);
|
||||
if (value.unavailable || !value.snapshot)
|
||||
throw new Error(
|
||||
'A intenção guardada não pôde ser recuperada com segurança.',
|
||||
);
|
||||
setSavedPreparation(value);
|
||||
if (value.operation_key !== sent.operation_key) {
|
||||
setNotice(
|
||||
'Há uma preparação mais recente noutra janela. Foi preservada; recupere e compare antes de continuar.',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
preparationVersion.current = value.version;
|
||||
preparationSave.current = null;
|
||||
if (
|
||||
attempt &&
|
||||
sent.snapshot.pending?.values.client_key !==
|
||||
attempt.values.client_key
|
||||
) {
|
||||
setNotice(
|
||||
'A preparação anterior foi recuperada. Guarde a intenção mais recente antes de enviar a revisão.',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
setNotice(
|
||||
JSON.stringify(sent.snapshot) ===
|
||||
JSON.stringify(privateSnapshot())
|
||||
? 'Preparação privada guardada. Ainda não constitui uma decisão de revisão.'
|
||||
: 'Preparação guardada; as edições feitas entretanto continuam por guardar.',
|
||||
);
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (alive.current)
|
||||
setNotice(
|
||||
(error instanceof Error
|
||||
? error.message
|
||||
: 'Não foi possível guardar a preparação.') +
|
||||
' A decisão não foi enviada. Repita a mesma gravação para recuperar a resposta incerta.',
|
||||
);
|
||||
return false;
|
||||
} finally {
|
||||
saving.current = false;
|
||||
if (alive.current) setPersisting(false);
|
||||
}
|
||||
}
|
||||
async function restorePreparation() {
|
||||
if (
|
||||
invalid ||
|
||||
saving.current ||
|
||||
form.processing ||
|
||||
preparation === undefined
|
||||
)
|
||||
return;
|
||||
saving.current = true;
|
||||
setPersisting(true);
|
||||
const before = JSON.stringify(privateSnapshot());
|
||||
try {
|
||||
const value = await profileJson(
|
||||
`${preparationUrl}?actor_id=${actorId}`,
|
||||
{},
|
||||
'GET',
|
||||
);
|
||||
if (!alive.current) return;
|
||||
if (!validPreparation(value))
|
||||
throw new Error(
|
||||
'A preparação guardada não pôde ser conferida.',
|
||||
);
|
||||
setSavedPreparation(value);
|
||||
if (value.unavailable || !value.snapshot) {
|
||||
setNotice(
|
||||
value.unavailable
|
||||
? 'A preparação guardada está indisponível e foi preservada.'
|
||||
: 'Ainda não existe preparação guardada para esta conta e declaração.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (before !== JSON.stringify(privateSnapshot())) {
|
||||
setNotice(
|
||||
'Conserve as novas edições: a preparação recuperada não as substituiu. Compare antes de recuperar novamente.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
(live.current.review_reason.trim() || pending.current) &&
|
||||
!window.confirm(
|
||||
'Substituir a preparação local pela versão privada guardada?',
|
||||
)
|
||||
)
|
||||
return;
|
||||
const state = structuredClone(value.snapshot);
|
||||
preparationVersion.current = value.version;
|
||||
preparationSave.current = null;
|
||||
base.current = state.base;
|
||||
generation.current = state.generation;
|
||||
pending.current = state.pending;
|
||||
live.current = state.values;
|
||||
form.setData(state.values);
|
||||
form.clearErrors();
|
||||
setUncertain(state.pending !== null);
|
||||
setConflict(false);
|
||||
setAccessBlocked(false);
|
||||
setNotice(
|
||||
'Preparação recuperada. Confira a versão e a fonte actuais antes de enviar.',
|
||||
);
|
||||
if (state.pending)
|
||||
acknowledge(observed.current.row, observed.current.references);
|
||||
} catch (error) {
|
||||
if (alive.current)
|
||||
setNotice(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: 'Não foi possível recuperar a preparação.',
|
||||
);
|
||||
} finally {
|
||||
saving.current = false;
|
||||
if (alive.current) setPersisting(false);
|
||||
}
|
||||
}
|
||||
const invalid =
|
||||
!positive(actorId) ||
|
||||
row.review_context?.actor_id !== actorId ||
|
||||
@@ -200,6 +449,7 @@ export function useEducationReview({
|
||||
function submit() {
|
||||
if (
|
||||
invalid ||
|
||||
saving.current ||
|
||||
accessBlocked ||
|
||||
refreshing ||
|
||||
form.processing ||
|
||||
@@ -226,53 +476,63 @@ export function useEducationReview({
|
||||
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) {
|
||||
const send = () => {
|
||||
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);
|
||||
}
|
||||
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.',
|
||||
);
|
||||
},
|
||||
});
|
||||
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.',
|
||||
);
|
||||
},
|
||||
});
|
||||
};
|
||||
if (preparation !== undefined) {
|
||||
setNotice('A conservar a intenção de revisão antes do envio.');
|
||||
void persistPreparation(attempt).then((stored) => {
|
||||
if (stored && alive.current && pending.current === attempt)
|
||||
send();
|
||||
});
|
||||
} else send();
|
||||
}
|
||||
|
||||
function refresh() {
|
||||
if (refreshing || form.processing) return;
|
||||
setRefreshing(true);
|
||||
@@ -360,6 +620,11 @@ export function useEducationReview({
|
||||
}, []);
|
||||
return {
|
||||
form,
|
||||
persistPreparation: () => persistPreparation(),
|
||||
restorePreparation,
|
||||
preparationAvailable: preparation !== undefined,
|
||||
savedPreparation,
|
||||
persisting,
|
||||
change,
|
||||
submit,
|
||||
refresh,
|
||||
@@ -378,6 +643,7 @@ export function useEducationReview({
|
||||
!refreshing &&
|
||||
!form.processing,
|
||||
blocked:
|
||||
persisting ||
|
||||
invalid ||
|
||||
accessBlocked ||
|
||||
refreshing ||
|
||||
|
||||
Reference in New Issue
Block a user