Files
ita-ito-horaires/app/admin/exceptions/actions.ts
T
vliaudatandClaude Opus 5 5f7aa951d3 feat: explain a schedule change on the panel, and preview it in advance
Two things the shop asked for, and one it will notice.

**A message on an exception.** A closure or a late opening can now carry
a reason, and it reaches the panel. It shows while the door is shut and
disappears the moment the shop opens — a notice explaining a late
opening is worse than useless once the door is open.

It outranks a free message on purpose: "closed this afternoon, back
tomorrow" is what someone standing outside needs, and "new collection in
store" can wait. Say so if you would rather it were the other way.

The first version keyed this off the day's `isOpen`, which means "this
day has opening hours" — so a day opening at 14:00 counted as open all
morning, exactly when the reason is needed. A test caught it; the rule
now reads the state at this minute.

**Reusable phrases.** The same handful of notices get written over and
over. /admin/modeles keeps them, translated once, and offers them
wherever a message is composed — exceptions, closure periods, the
banner. Picking one costs no translation at all: the saved English is
reused directly, where the service takes the better part of ten seconds.

Exception notes and holiday labels are translated too, which they were
not before. After the save rather than during it, so a slow service
never costs the shop its dates.

**Previewing the future.** The dashboard can render the panel at any
moment within about a year: "what will the window say while I'm away?"
is worth answering before someone is standing in front of a locked door.
The whole pipeline was already a function of "now", so this costs
passing a different instant. An unparseable or absurd value falls back
to the present rather than confidently rendering nonsense.

Checked against a three-week holiday, which surfaced something worth
knowing: the automatic "opens on…" line stays empty, because the
resolver's search is bounded to fourteen days. During a long closure the
message is the only thing that tells customers when the shop is back —
which is a good reason for this feature to exist.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012cSY9pVhZmJUKNN7wf1Myd
2026-09-23 09:34:14 +02:00

227 lines
6.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use server';
import { revalidatePath } from 'next/cache';
import { diffOf, recordAudit } from '@/lib/audit';
import { requireAdmin } from '@/lib/auth/actions';
import { prisma } from '@/lib/db';
import type { CivilDate } from '@/lib/schedule/civil';
import { checkRange, expandRange, MAX_RANGE_DAYS } from '@/lib/schedule/exceptions';
import type { Slot } from '@/lib/schedule/types';
import { validateSlots } from '@/lib/schedule/validate';
import { translateToEnglish } from '@/lib/translation/service';
export type ExceptionReason = 'TEMPORARY' | 'SPECIAL_EVENT';
export type ActionResult = { ok: true } | { ok: false; error: string };
export type ExceptionInput = {
date: CivilDate;
isClosed: boolean;
slots: Slot[];
reason: ExceptionReason;
noteFr: string | null;
};
export async function saveException(input: ExceptionInput): Promise<ActionResult> {
const gate = await requireAdmin();
if (!gate.ok) {
return { ok: false, error: gate.error };
}
const slots = input.isClosed ? [] : input.slots;
if (!input.isClosed) {
const problems = validateSlots(slots);
if (slots.length === 0) {
problems.push('Une ouverture exceptionnelle doit avoir au moins une plage horaire.');
}
if (problems.length > 0) {
return { ok: false, error: problems.join(' ') };
}
}
const date = asDate(input.date);
const existing = await prisma.scheduleException.findUnique({ where: { date } });
// A phrase saved as a template has already been translated. Reusing it costs
// nothing and is instant, where the service takes the better part of ten
// seconds — which is most of the point of having templates at all.
const fromTemplate = input.noteFr
? await prisma.messageTemplate.findUnique({ where: { textFr: input.noteFr } })
: null;
const noteEn = fromTemplate?.textEn ?? null;
await prisma.scheduleException.upsert({
where: { date },
update: {
isClosed: input.isClosed,
slots: input.isClosed ? undefined : slots,
reason: input.reason,
noteFr: input.noteFr,
// The French text changed, so any English translation is stale.
noteEn: existing?.noteFr === input.noteFr ? undefined : noteEn,
source: 'MANUAL',
},
create: {
date,
isClosed: input.isClosed,
slots: input.isClosed ? undefined : slots,
reason: input.reason,
noteFr: input.noteFr,
noteEn,
source: 'MANUAL',
createdBy: gate.value.email,
},
});
await recordAudit({
userEmail: gate.value.email,
action: existing ? 'exception.update' : 'exception.create',
entity: 'ScheduleException',
entityId: input.date,
diff: diffOf(
existing ? { fermé: existing.isClosed, horaires: summarise(existing.slots as Slot[] | null), note: existing.noteFr } : null,
{ fermé: input.isClosed, horaires: summarise(slots), note: input.noteFr },
),
});
revalidateAll();
return { ok: true };
}
export async function saveExceptionRange(input: {
start: CivilDate;
end: CivilDate;
noteFr: string | null;
}): Promise<ActionResult> {
const gate = await requireAdmin();
if (!gate.ok) {
return { ok: false, error: gate.error };
}
const problem = checkRange(input.start, input.end);
if (problem === 'EMPTY') {
return { ok: false, error: 'Indiquez une date de début et une date de fin.' };
}
if (problem === 'REVERSED') {
return { ok: false, error: 'La date de fin précède la date de début.' };
}
if (problem === 'TOO_LONG') {
return {
ok: false,
error: `Période trop longue (${MAX_RANGE_DAYS} jours au maximum). Utilisez les vacances pour une fermeture plus longue.`,
};
}
const dates = expandRange(input.start, input.end);
await prisma.$transaction(
dates.map((date) =>
prisma.scheduleException.upsert({
where: { date: asDate(date) },
update: { isClosed: true, slots: undefined, reason: 'TEMPORARY', noteFr: input.noteFr, noteEn: null, source: 'MANUAL' },
create: {
date: asDate(date),
isClosed: true,
reason: 'TEMPORARY',
noteFr: input.noteFr,
source: 'MANUAL',
createdBy: gate.value.email,
},
}),
),
);
await recordAudit({
userEmail: gate.value.email,
action: 'exception.create_range',
entity: 'ScheduleException',
entityId: `${input.start}…${input.end}`,
diff: { période: { before: null, after: `${dates.length} jours fermés` } },
});
revalidateAll();
return { ok: true };
}
export async function deleteException(date: CivilDate): Promise<ActionResult> {
const gate = await requireAdmin();
if (!gate.ok) {
return { ok: false, error: gate.error };
}
const existing = await prisma.scheduleException.findUnique({ where: { date: asDate(date) } });
if (!existing) {
return { ok: false, error: 'Cette exception a déjà été supprimée.' };
}
await prisma.scheduleException.delete({ where: { date: asDate(date) } });
await recordAudit({
userEmail: gate.value.email,
action: 'exception.delete',
entity: 'ScheduleException',
entityId: date,
diff: diffOf(
{ fermé: existing.isClosed, horaires: summarise(existing.slots as Slot[] | null), note: existing.noteFr },
null,
),
});
revalidateAll();
return { ok: true };
}
function summarise(slots: Slot[] | null): string {
if (!slots || slots.length === 0) {
return 'Fermé';
}
return slots.map((slot) => `${slot.open}–${slot.close}`).join(' · ');
}
function asDate(value: CivilDate): Date {
return new Date(`${value}T00:00:00.000Z`);
}
function revalidateAll(): void {
revalidatePath('/admin');
revalidatePath('/admin/exceptions');
}
/**
* Translates an exception's message, if it still needs it.
*
* Called after the save rather than during it: the panel's message is worth
* having, but not at the price of making the two-click path wait ten seconds
* for a process to start on another machine. A failure leaves the French
* alone on screen, which is what the renderer already does gracefully.
*/
export async function translateExceptionNote(date: CivilDate): Promise<ActionResult> {
const gate = await requireAdmin();
if (!gate.ok) {
return { ok: false, error: gate.error };
}
const existing = await prisma.scheduleException.findUnique({ where: { date: asDate(date) } });
if (!existing?.noteFr) {
return { ok: true };
}
if (existing.noteEn) {
// Already translated, most often by having come from a template.
return { ok: true };
}
const outcome = await translateToEnglish(existing.noteFr);
if (!outcome.ok) {
return { ok: false, error: outcome.error };
}
await prisma.scheduleException.update({
where: { date: asDate(date) },
data: { noteEn: outcome.text },
});
revalidateAll();
return { ok: true };
}