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
This commit is contained in:
2026-09-23 09:34:14 +02:00
co-authored by Claude Opus 5
parent 743a3778cc
commit 5f7aa951d3
29 changed files with 1141 additions and 59 deletions
+108 -7
View File
@@ -6,27 +6,90 @@ import { useState } from 'react';
* The panel, at a readable size.
*
* Rendered by the same code path that serves the device, so this is not an
* impression of the screen: it is the screen. `key` is bumped to defeat the
* browser cache when the data behind it has just changed.
* impression of the screen: it is the screen.
*
* With `timeTravel`, it also answers the question the shop actually asks
* before a holiday — "what will the window say while I'm away?" — without
* waiting until someone is standing in front of a locked door to find out.
*/
export default function ScreenPreview({ className = '' }: { className?: string }) {
export default function ScreenPreview({
className = '',
timeTravel = false,
}: {
className?: string;
timeTravel?: boolean;
}) {
const [at, setAt] = useState('');
const [nonce, setNonce] = useState(() => Date.now());
const source = at
? `/api/admin/preview?at=${encodeURIComponent(at)}&t=${nonce}`
: `/api/admin/preview?t=${nonce}`;
function jumpTo(date: Date) {
setAt(toLocalInput(date));
setNonce(Date.now());
}
return (
<figure className={className}>
<div className="overflow-hidden rounded-[var(--radius-md)] border border-[var(--line-strong)] bg-white">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
key={nonce}
src={`/api/admin/preview?t=${nonce}`}
alt="Aperçu de l’écran de la vitrine"
key={source}
src={source}
alt={
at
? `Aperçu de l’écran tel qu’il sera le ${at.replace('T', ' à ')}`
: 'Aperçu de l’écran de la vitrine'
}
width={800}
height={480}
className="block h-auto w-full"
/>
</div>
{timeTravel ? (
<div className="mt-3 flex flex-wrap items-end gap-x-3 gap-y-2">
<label className="text-sm">
<span className="block text-[var(--ink-muted)]">Afficher l’écran au</span>
<input
type="datetime-local"
value={at}
onChange={(event) => {
setAt(event.target.value);
setNonce(Date.now());
}}
className="mt-1 rounded-[var(--radius-sm)] border border-[var(--line-strong)] bg-[var(--surface)] px-2 py-1.5 text-base"
/>
</label>
<div className="flex flex-wrap gap-2 text-sm">
<Jump label="Demain 10:00" onClick={() => jumpTo(tomorrowAt(10))} />
<Jump label="Samedi 10:00" onClick={() => jumpTo(nextWeekdayAt(6, 10))} />
<Jump label="Dans 1 mois" onClick={() => jumpTo(inDays(30, 10))} />
{at ? (
<button
type="button"
onClick={() => {
setAt('');
setNonce(Date.now());
}}
className="rounded-[var(--radius-sm)] border border-[var(--accent)] px-3 py-1.5 text-[var(--accent-ink)] hover:bg-[var(--accent-tint)]"
>
Revenir à maintenant
</button>
) : null}
</div>
</div>
) : null}
<figcaption className="mt-2 flex flex-wrap items-center gap-3 text-xs text-[var(--ink-muted)]">
<span>800 × 480, noir et blanc — rendu réellement envoyé à l’écran.</span>
<span>
{at
? 'Projection : l’écran tel qu’il sera à cette date, avec les horaires et fermetures enregistrés.'
: '800 × 480, noir et blanc — rendu réellement envoyé à l’écran.'}
</span>
<button
type="button"
onClick={() => setNonce(Date.now())}
@@ -38,3 +101,41 @@ export default function ScreenPreview({ className = '' }: { className?: string }
</figure>
);
}
function Jump({ label, onClick }: { label: string; onClick: () => void }) {
return (
<button
type="button"
onClick={onClick}
className="rounded-[var(--radius-sm)] border border-[var(--line-strong)] px-3 py-1.5 hover:bg-[var(--surface-muted)]"
>
{label}
</button>
);
}
/** `datetime-local` speaks local wall-clock time with no zone, so build one. */
function toLocalInput(date: Date): string {
const pad = (value: number) => value.toString().padStart(2, '0');
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(
date.getHours(),
)}:${pad(date.getMinutes())}`;
}
function tomorrowAt(hour: number): Date {
return inDays(1, hour);
}
function inDays(days: number, hour: number): Date {
const date = new Date();
date.setDate(date.getDate() + days);
date.setHours(hour, 0, 0, 0);
return date;
}
/** The next occurrence of a weekday, 0 = Sunday. */
function nextWeekdayAt(weekday: number, hour: number): Date {
const date = new Date();
const ahead = (weekday - date.getDay() + 7) % 7 || 7;
return inDays(ahead, hour);
}
+57
View File
@@ -0,0 +1,57 @@
'use client';
/**
* Offers the shop's saved phrases wherever a message is composed.
*
* A picker rather than a free-text-only field, because the same handful of
* notices get written over and over: choosing one keeps the wording
* consistent and — more importantly — reuses a phrase that has already been
* translated, instead of paying for a fresh translation of the same sentence.
*
* The chosen text lands in the field and stays editable. A template is a
* starting point, not a constraint.
*/
export type Template = { id: string; textFr: string };
export default function TemplatePicker({
templates,
onPick,
disabled = false,
label = 'Modèle',
}: {
templates: Template[];
onPick: (textFr: string) => void;
disabled?: boolean;
label?: string;
}) {
if (templates.length === 0) {
return null;
}
return (
<label className="flex items-center gap-2 text-sm">
<span className="text-[var(--ink-muted)]">{label}</span>
<select
aria-label={`${label} de message`}
value=""
disabled={disabled}
onChange={(event) => {
const picked = templates.find((template) => template.id === event.target.value);
if (picked) {
onPick(picked.textFr);
}
// Back to the placeholder: the control is an action, not a state.
event.target.value = '';
}}
className="max-w-56 rounded-[var(--radius-sm)] border border-[var(--line-strong)] bg-[var(--surface)] px-2 py-1.5 text-sm disabled:opacity-40"
>
<option value="">Choisir…</option>
{templates.map((template) => (
<option key={template.id} value={template.id}>
{template.textFr}
</option>
))}
</select>
</label>
);
}
+68 -24
View File
@@ -2,10 +2,18 @@
import { useState, useTransition } from 'react';
import TemplatePicker, { type Template } from '@/app/admin/components/TemplatePicker';
import { earlyClosing, lateOpening, usualBounds } from '@/lib/schedule/exceptions';
import type { ExceptionKind, Slot } from '@/lib/schedule/types';
import { deleteException, saveException, saveExceptionRange } from './actions';
import { MESSAGE_MAX_CHARS } from '@/lib/screen/contract';
import {
deleteException,
saveException,
saveExceptionRange,
translateExceptionNote,
} from './actions';
export type UpcomingDay = {
date: string;
@@ -34,6 +42,7 @@ type Props = {
today: string;
days: SelectableDay[];
upcoming: UpcomingDay[];
templates: Template[];
};
const KIND_LABELS: Record<string, { text: string; className: string }> = {
@@ -42,7 +51,7 @@ const KIND_LABELS: Record<string, { text: string; className: string }> = {
VACATION: { text: 'vacances', className: 'bg-[var(--surface-muted)] text-[var(--ink-muted)]' },
};
export default function ExceptionsManager({ canEdit, today, days, upcoming }: Props) {
export default function ExceptionsManager({ canEdit, today, days, upcoming, templates }: Props) {
const [pending, startTransition] = useTransition();
const [message, setMessage] = useState<{ kind: 'ok' | 'error'; text: string } | null>(null);
@@ -69,9 +78,11 @@ export default function ExceptionsManager({ canEdit, today, days, upcoming }: Pr
</p>
) : null}
{canEdit ? <QuickPanel today={today} days={days} pending={pending} run={run} /> : null}
{canEdit ? (
<QuickPanel today={today} days={days} templates={templates} pending={pending} run={run} />
) : null}
{canEdit ? <RangePanel pending={pending} run={run} /> : null}
{canEdit ? <RangePanel templates={templates} pending={pending} run={run} /> : null}
<section>
<h2 className="text-lg">À venir</h2>
@@ -135,35 +146,49 @@ export default function ExceptionsManager({ canEdit, today, days, upcoming }: Pr
function QuickPanel({
today,
days,
templates,
pending,
run,
}: {
today: string;
days: SelectableDay[];
templates: Template[];
pending: boolean;
run: (work: () => Promise<{ ok: true } | { ok: false; error: string }>, success: string) => void;
}) {
const [date, setDate] = useState(today);
const [note, setNote] = useState('');
const day = days.find((candidate) => candidate.date === date) ?? days[0];
const isToday = day?.date === today;
const isOpenThatDay = (day?.usualSlots.length ?? 0) > 0;
function apply(slots: Slot[], note: string, success: string) {
function apply(slots: Slot[], success: string) {
if (!day) {
return;
}
run(
() =>
saveException({
date: day.date,
isClosed: slots.length === 0,
slots,
reason: 'TEMPORARY',
noteFr: note,
}),
success,
);
const text = note.trim();
run(async () => {
const saved = await saveException({
date: day.date,
isClosed: slots.length === 0,
slots,
reason: 'TEMPORARY',
// Empty means no notice: the message now drives what the panel shows,
// so it has to be something the shop chose to say rather than a
// sentence the form filled in on its behalf.
noteFr: text || null,
});
if (saved.ok && text) {
// Separate from the save: a message is worth having, but not at the
// price of making the two-click path wait for the translation
// service. A failure simply leaves the French alone on screen.
await translateExceptionNote(day.date);
}
return saved;
}, success);
}
const when = isToday ? 'aujourd’hui' : `le ${day?.label.toLowerCase() ?? ''}`;
@@ -196,13 +221,29 @@ function QuickPanel({
{day?.isException ? ` Actuellement : ${day.effectiveText}.` : ''}
</p>
<div className="mt-4 flex flex-wrap items-end gap-3">
<label className="min-w-56 flex-1 text-sm">
<span className="block text-[var(--ink-muted)]">Message affiché (facultatif)</span>
<input
type="text"
value={note}
maxLength={MESSAGE_MAX_CHARS}
placeholder="Fermeture exceptionnelle, retour demain"
onChange={(event) => setNote(event.target.value)}
className="mt-1 w-full rounded-[var(--radius-sm)] border border-[var(--line-strong)] bg-[var(--surface)] px-2 py-2 text-base"
/>
</label>
<TemplatePicker templates={templates} onPick={setNote} disabled={pending} />
</div>
<p className="mt-1 text-sm text-[var(--ink-muted)]">
Affiché sur l’écran tant que la boutique est fermée ce jour-là, et retiré dès qu’elle ouvre.
</p>
<div className="mt-4 space-y-3">
<button
type="button"
disabled={pending}
onClick={() =>
apply([], 'Fermeture exceptionnelle', `La boutique sera fermée ${when}.`)
}
onClick={() => apply([], `La boutique sera fermée ${when}.`)}
className="w-full rounded-[var(--radius-md)] bg-[var(--accent)] px-4 py-3 font-medium text-[var(--on-accent)] transition-colors hover:bg-[var(--accent-hover)] disabled:opacity-40 sm:w-auto"
>
{isToday ? 'Fermé aujourd’hui' : `Fermé ${when}`}
@@ -226,9 +267,11 @@ function QuickPanel({
/** A specific date, or a short run of days. Longer closures are holidays. */
function RangePanel({
templates,
pending,
run,
}: {
templates: Template[];
pending: boolean;
run: (work: () => Promise<{ ok: true } | { ok: false; error: string }>, success: string) => void;
}) {
@@ -265,16 +308,17 @@ function RangePanel({
/>
</label>
<label className="min-w-48 flex-1 text-sm">
<span className="block text-[var(--ink-muted)]">Note affichée (facultatif)</span>
<span className="block text-[var(--ink-muted)]">Message affiché (facultatif)</span>
<input
type="text"
value={note}
maxLength={120}
maxLength={MESSAGE_MAX_CHARS}
placeholder="Fermeture exceptionnelle"
onChange={(event) => setNote(event.target.value)}
className="mt-1 w-full rounded-[var(--radius-sm)] border border-[var(--line-strong)] bg-[var(--surface)] px-2 py-2 text-base"
/>
</label>
<TemplatePicker templates={templates} onPick={setNote} disabled={pending} />
</div>
<button
@@ -316,7 +360,7 @@ function AdjustHours({
}: {
day: SelectableDay;
pending: boolean;
apply: (slots: Slot[], note: string, success: string) => void;
apply: (slots: Slot[], success: string) => void;
}) {
const bounds = usualBounds(day.usualSlots);
const [openFrom, setOpenFrom] = useState(bounds.open);
@@ -332,7 +376,7 @@ function AdjustHours({
type="button"
disabled={pending || lateResult.length === 0}
onClick={() =>
apply(lateResult, `Ouverture à ${openFrom}`, `Ouverture repoussée à ${openFrom}.`)
apply(lateResult, `Ouverture repoussée à ${openFrom}.`)
}
className="rounded-[var(--radius-md)] border border-[var(--line-strong)] px-4 py-2.5 transition-colors hover:bg-[var(--surface-muted)] disabled:opacity-40"
>
@@ -355,7 +399,7 @@ function AdjustHours({
type="button"
disabled={pending || earlyResult.length === 0}
onClick={() =>
apply(earlyResult, `Fermeture à ${closeAt}`, `Fermeture avancée à ${closeAt}.`)
apply(earlyResult, `Fermeture avancée à ${closeAt}.`)
}
className="rounded-[var(--radius-md)] border border-[var(--line-strong)] px-4 py-2.5 transition-colors hover:bg-[var(--surface-muted)] disabled:opacity-40"
>
+48 -1
View File
@@ -9,6 +9,7 @@ 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';
@@ -42,6 +43,14 @@ export async function saveException(input: ExceptionInput): Promise<ActionResult
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: {
@@ -50,7 +59,7 @@ export async function saveException(input: ExceptionInput): Promise<ActionResult
reason: input.reason,
noteFr: input.noteFr,
// The French text changed, so any English translation is stale.
noteEn: existing?.noteFr === input.noteFr ? undefined : null,
noteEn: existing?.noteFr === input.noteFr ? undefined : noteEn,
source: 'MANUAL',
},
create: {
@@ -59,6 +68,7 @@ export async function saveException(input: ExceptionInput): Promise<ActionResult
slots: input.isClosed ? undefined : slots,
reason: input.reason,
noteFr: input.noteFr,
noteEn,
source: 'MANUAL',
createdBy: gate.value.email,
},
@@ -177,3 +187,40 @@ 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 };
}
+7 -1
View File
@@ -4,6 +4,7 @@ import { addCivilDays, toCivilDate } from '@/lib/schedule/civil';
import { loadScheduleContext, loadSettings } from '@/lib/schedule/context';
import { formatDateFr, formatHoursText } from '@/lib/schedule/format';
import { resolveCivilDay } from '@/lib/schedule/resolver';
import { loadTemplates } from '@/lib/templates';
import type { ScheduleContext } from '@/lib/schedule/types';
import ExceptionsManager, { type SelectableDay, type UpcomingDay } from './ExceptionsManager';
@@ -14,7 +15,11 @@ export const metadata = { title: 'Changements ponctuels — ITA ITO' };
const HORIZON_DAYS = 60;
export default async function ExceptionsPage() {
const [session, settings] = await Promise.all([auth(), loadSettings()]);
const [session, settings, templates] = await Promise.all([
auth(),
loadSettings(),
loadTemplates(),
]);
const now = new Date();
const context = await loadScheduleContext(now, settings);
const today = toCivilDate(now, settings.timezone);
@@ -41,6 +46,7 @@ export default async function ExceptionsPage() {
today={today}
days={days}
upcoming={upcoming}
templates={templates}
/>
</main>
);
+1
View File
@@ -10,6 +10,7 @@ const NAV = [
{ href: '/admin/exceptions', label: 'Exceptions' },
{ href: '/admin/vacances', label: 'Vacances' },
{ href: '/admin/messages', label: 'Messages' },
{ href: '/admin/modeles', label: 'Modèles' },
{ href: '/admin/feries', label: 'Fériés' },
{ href: '/admin/parametres', label: 'Paramètres' },
];
+7
View File
@@ -3,6 +3,7 @@
import { useState, useTransition } from 'react';
import ScreenPreview from '@/app/admin/ScreenPreview';
import TemplatePicker, { type Template } from '@/app/admin/components/TemplatePicker';
import { MESSAGE_MAX_CHARS } from '@/lib/screen/contract';
import {
@@ -34,9 +35,11 @@ const STATUS: Record<MessageRow['translationStatus'], { label: string; className
export default function MessageManager({
canEdit,
messages,
templates,
}: {
canEdit: boolean;
messages: MessageRow[];
templates: Template[];
}) {
const [pending, startTransition] = useTransition();
const [message, setMessage] = useState<{ kind: 'ok' | 'error'; text: string } | null>(null);
@@ -119,6 +122,10 @@ export default function MessageManager({
/>
</label>
<div className="mt-2">
<TemplatePicker templates={templates} onPick={setTextFr} disabled={pending} />
</div>
<p
className={`mt-1 text-sm ${
remaining < 0 ? 'text-[var(--danger)]' : 'text-[var(--ink-muted)]'
+8 -2
View File
@@ -1,15 +1,17 @@
import { auth } from '@/lib/auth';
import { prisma } from '@/lib/db';
import { selectActiveMessage } from '@/lib/screen/viewmodel';
import { loadTemplates } from '@/lib/templates';
import MessageManager, { type MessageRow } from './MessageManager';
export const metadata = { title: 'Messages — ITA ITO' };
export default async function MessagesPage() {
const [session, rows] = await Promise.all([
const [session, rows, templates] = await Promise.all([
auth(),
prisma.message.findMany({ orderBy: [{ isActive: 'desc' }, { priority: 'desc' }, { createdAt: 'desc' }] }),
loadTemplates(),
]);
const now = new Date();
@@ -48,7 +50,11 @@ export default async function MessagesPage() {
libre prend la place du bandeau automatique « horaires exceptionnels ».
</p>
<MessageManager canEdit={session?.user?.role === 'admin'} messages={messages} />
<MessageManager
canEdit={session?.user?.role === 'admin'}
messages={messages}
templates={templates}
/>
</main>
);
}
+223
View File
@@ -0,0 +1,223 @@
'use client';
import { useState, useTransition } from 'react';
import { MESSAGE_MAX_CHARS } from '@/lib/screen/contract';
import {
deleteTemplate,
saveTemplate,
setTemplateTranslation,
translateTemplate,
} from './actions';
export type TemplateRow = {
id: string;
textFr: string;
textEn: string | null;
translationStatus: 'PENDING' | 'DONE' | 'MANUAL' | 'ERROR';
sortOrder: number;
};
const STATUS: Record<TemplateRow['translationStatus'], { label: string; className: string }> = {
PENDING: { label: 'traduction en attente', className: 'bg-[var(--surface-muted)] text-[var(--ink-muted)]' },
DONE: { label: 'traduit', className: 'bg-[var(--success-tint)] text-[var(--success)]' },
MANUAL: { label: 'traduction manuelle', className: 'bg-[var(--accent-tint)] text-[var(--accent-ink)]' },
ERROR: { label: 'traduction en échec', className: 'bg-[var(--danger-tint)] text-[var(--danger)]' },
};
export default function TemplateManager({
canEdit,
templates,
}: {
canEdit: boolean;
templates: TemplateRow[];
}) {
const [textFr, setTextFr] = useState('');
const [pending, startTransition] = useTransition();
const [message, setMessage] = useState<{ kind: 'ok' | 'error'; text: string } | null>(null);
const remaining = MESSAGE_MAX_CHARS - textFr.length;
function run(work: () => Promise<{ ok: true } | { ok: false; error: string }>, success: string) {
setMessage(null);
startTransition(async () => {
const result = await work();
setMessage(result.ok ? { kind: 'ok', text: success } : { kind: 'error', text: result.error });
});
}
function create() {
setMessage(null);
startTransition(async () => {
const saved = await saveTemplate({ textFr, sortOrder: templates.length });
if (!saved.ok) {
setMessage({ kind: 'error', text: saved.error });
return;
}
setTextFr('');
setMessage({ kind: 'ok', text: 'Modèle enregistré. Traduction en cours…' });
const translated = await translateTemplate(saved.value.id);
setMessage(
translated.ok
? { kind: 'ok', text: 'Modèle enregistré et traduit.' }
: { kind: 'error', text: `Modèle enregistré, mais la traduction a échoué : ${translated.error}` },
);
});
}
return (
<div className="mt-8 space-y-8">
{message ? (
<p
role="status"
className={`rounded-[var(--radius-md)] px-4 py-3 text-sm ${
message.kind === 'ok'
? 'bg-[var(--success-tint)] text-[var(--success)]'
: 'bg-[var(--danger-tint)] text-[var(--danger)]'
}`}
>
{message.text}
</p>
) : null}
{canEdit ? (
<section className="rounded-[var(--radius-md)] border border-[var(--line)] bg-[var(--surface)] p-5">
<h2 className="text-lg">Nouveau modèle</h2>
<label className="mt-4 block text-sm">
<span className="block text-[var(--ink-muted)]">Texte en français</span>
<input
type="text"
value={textFr}
onChange={(event) => setTextFr(event.target.value)}
placeholder="Fermeture exceptionnelle, retour demain"
className="mt-1 w-full rounded-[var(--radius-sm)] border border-[var(--line-strong)] bg-[var(--surface)] px-3 py-2 text-base"
/>
</label>
<p
className={`mt-1 text-sm ${remaining < 0 ? 'text-[var(--danger)]' : 'text-[var(--ink-muted)]'}`}
>
{remaining >= 0
? `${remaining} caractères restants.`
: `${-remaining} caractères de trop : le message serait coupé sur l’écran.`}
</p>
<button
type="button"
disabled={pending || textFr.trim().length === 0 || remaining < 0}
onClick={create}
className="mt-4 rounded-[var(--radius-md)] bg-[var(--accent)] px-4 py-2.5 font-medium text-[var(--on-accent)] transition-colors hover:bg-[var(--accent-hover)] disabled:opacity-40"
>
{pending ? 'Enregistrement…' : 'Ajouter'}
</button>
</section>
) : null}
<section>
<h2 className="text-lg">Modèles enregistrés</h2>
{templates.length === 0 ? (
<p className="mt-3 text-sm text-[var(--ink-muted)]">
Aucun modèle. Ceux que vous ajoutez ici seront proposés partout où l’on compose un
message.
</p>
) : (
<ul className="mt-3 space-y-3">
{templates.map((row) => (
<TemplateCard
key={row.id}
row={row}
canEdit={canEdit}
pending={pending}
run={run}
startTransition={startTransition}
setMessage={setMessage}
/>
))}
</ul>
)}
</section>
</div>
);
}
function TemplateCard({
row,
canEdit,
pending,
run,
startTransition,
setMessage,
}: {
row: TemplateRow;
canEdit: boolean;
pending: boolean;
run: (work: () => Promise<{ ok: true } | { ok: false; error: string }>, success: string) => void;
startTransition: (work: () => void) => void;
setMessage: (value: { kind: 'ok' | 'error'; text: string } | null) => void;
}) {
const [draftEn, setDraftEn] = useState(row.textEn ?? '');
const badge = STATUS[row.translationStatus];
return (
<li className="rounded-[var(--radius-md)] border border-[var(--line)] bg-[var(--surface)] p-4">
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
<p className="font-medium">{row.textFr}</p>
<span className={`rounded-[var(--radius-sm)] px-2 py-0.5 text-xs ${badge.className}`}>
{badge.label}
</span>
</div>
{canEdit ? (
<div className="mt-3 flex flex-wrap items-end gap-2">
<label className="min-w-56 flex-1 text-sm">
<span className="block text-[var(--ink-muted)]">Traduction anglaise</span>
<input
type="text"
value={draftEn}
onChange={(event) => setDraftEn(event.target.value)}
className="mt-1 w-full rounded-[var(--radius-sm)] border border-[var(--line-strong)] bg-[var(--surface)] px-2 py-1.5 text-base"
/>
</label>
<button
type="button"
disabled={pending || draftEn === (row.textEn ?? '')}
onClick={() =>
run(() => setTemplateTranslation(row.id, draftEn), 'Traduction enregistrée.')
}
className="rounded-[var(--radius-sm)] border border-[var(--line-strong)] px-3 py-1.5 text-sm hover:bg-[var(--surface-muted)] disabled:opacity-40"
>
Enregistrer
</button>
<button
type="button"
disabled={pending}
onClick={() => {
setMessage(null);
startTransition(async () => {
const result = await translateTemplate(row.id);
setMessage(
result.ok
? { kind: 'ok', text: 'Traduction mise à jour.' }
: { kind: 'error', text: result.error },
);
});
}}
className="rounded-[var(--radius-sm)] border border-[var(--line-strong)] px-3 py-1.5 text-sm hover:bg-[var(--surface-muted)] disabled:opacity-40"
>
{row.translationStatus === 'ERROR' ? 'Réessayer' : 'Retraduire'}
</button>
<button
type="button"
disabled={pending}
onClick={() => run(() => deleteTemplate(row.id), 'Modèle supprimé.')}
className="ml-auto text-sm text-[var(--ink-muted)] underline-offset-2 hover:text-[var(--danger)] hover:underline disabled:opacity-40"
>
Supprimer
</button>
</div>
) : row.textEn ? (
<p className="mt-2 text-sm text-[var(--ink-muted)]">{row.textEn}</p>
) : null}
</li>
);
}
+164
View File
@@ -0,0 +1,164 @@
'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 { MESSAGE_MAX_CHARS } from '@/lib/screen/contract';
import { translateToEnglish } from '@/lib/translation/service';
export type ActionResult<T = undefined> = { ok: true; value: T } | { ok: false; error: string };
/**
* Saves a reusable phrase.
*
* Templates are translated like any other message, but once rather than at
* every use: that is most of the point of having them.
*/
export async function saveTemplate(input: {
id?: string;
textFr: string;
sortOrder: number;
}): Promise<ActionResult<{ id: string }>> {
const gate = await requireAdmin();
if (!gate.ok) {
return { ok: false, error: gate.error };
}
const textFr = input.textFr.trim();
if (textFr.length === 0) {
return { ok: false, error: 'Le modèle ne peut pas être vide.' };
}
if (textFr.length > MESSAGE_MAX_CHARS) {
return {
ok: false,
error: `Le modèle dépasse ${MESSAGE_MAX_CHARS} caractères et ne tiendrait pas sur l’écran.`,
};
}
const existing = input.id
? await prisma.messageTemplate.findUnique({ where: { id: input.id } })
: null;
// The French text is the identity of a template: two identical phrases are
// one phrase, and a duplicate would only ever be half-corrected later.
const clash = await prisma.messageTemplate.findUnique({ where: { textFr } });
if (clash && clash.id !== existing?.id) {
return { ok: false, error: 'Ce modèle existe déjà.' };
}
const textChanged = existing ? existing.textFr !== textFr : true;
const data = {
textFr,
sortOrder: input.sortOrder,
...(textChanged ? { textEn: null, translationStatus: 'PENDING' as const } : {}),
};
const saved = existing
? await prisma.messageTemplate.update({ where: { id: existing.id }, data })
: await prisma.messageTemplate.create({ data: { ...data, createdBy: gate.value.email } });
await recordAudit({
userEmail: gate.value.email,
action: existing ? 'template.update' : 'template.create',
entity: 'MessageTemplate',
entityId: saved.id,
diff: diffOf(existing ? { texte: existing.textFr } : null, { texte: textFr }),
});
revalidateAll();
return { ok: true, value: { id: saved.id } };
}
export async function translateTemplate(id: string): Promise<ActionResult<{ textEn: string }>> {
const gate = await requireAdmin();
if (!gate.ok) {
return { ok: false, error: gate.error };
}
const template = await prisma.messageTemplate.findUnique({ where: { id } });
if (!template) {
return { ok: false, error: 'Ce modèle a été supprimé.' };
}
if (template.translationStatus === 'MANUAL') {
return { ok: false, error: 'La traduction a été saisie à la main; elle n’est pas écrasée.' };
}
const outcome = await translateToEnglish(template.textFr);
if (!outcome.ok) {
await prisma.messageTemplate.update({ where: { id }, data: { translationStatus: 'ERROR' } });
revalidateAll();
return { ok: false, error: outcome.error };
}
await prisma.messageTemplate.update({
where: { id },
data: { textEn: outcome.text, translationStatus: 'DONE' },
});
revalidateAll();
return { ok: true, value: { textEn: outcome.text } };
}
export async function setTemplateTranslation(id: string, textEn: string): Promise<ActionResult> {
const gate = await requireAdmin();
if (!gate.ok) {
return { ok: false, error: gate.error };
}
const trimmed = textEn.trim();
const existing = await prisma.messageTemplate.findUnique({ where: { id } });
if (!existing) {
return { ok: false, error: 'Ce modèle a été supprimé.' };
}
await prisma.messageTemplate.update({
where: { id },
data: { textEn: trimmed || null, translationStatus: trimmed ? 'MANUAL' : 'PENDING' },
});
await recordAudit({
userEmail: gate.value.email,
action: 'template.translate_manual',
entity: 'MessageTemplate',
entityId: id,
diff: diffOf({ anglais: existing.textEn }, { anglais: trimmed || null }),
});
revalidateAll();
return { ok: true, value: undefined };
}
export async function deleteTemplate(id: string): Promise<ActionResult> {
const gate = await requireAdmin();
if (!gate.ok) {
return { ok: false, error: gate.error };
}
const existing = await prisma.messageTemplate.findUnique({ where: { id } });
if (!existing) {
return { ok: false, error: 'Ce modèle a déjà été supprimé.' };
}
await prisma.messageTemplate.delete({ where: { id } });
await recordAudit({
userEmail: gate.value.email,
action: 'template.delete',
entity: 'MessageTemplate',
entityId: id,
diff: diffOf({ texte: existing.textFr }, null),
});
revalidateAll();
return { ok: true, value: undefined };
}
function revalidateAll(): void {
// Templates appear in the pickers on every page that composes a message.
revalidatePath('/admin/modeles');
revalidatePath('/admin/exceptions');
revalidatePath('/admin/vacances');
revalidatePath('/admin/messages');
}
+33
View File
@@ -0,0 +1,33 @@
import { auth } from '@/lib/auth';
import { prisma } from '@/lib/db';
import TemplateManager, { type TemplateRow } from './TemplateManager';
export const metadata = { title: 'Modèles de message — ITA ITO' };
export default async function TemplatesPage() {
const [session, rows] = await Promise.all([
auth(),
prisma.messageTemplate.findMany({ orderBy: [{ sortOrder: 'asc' }, { createdAt: 'asc' }] }),
]);
const templates: TemplateRow[] = rows.map((row) => ({
id: row.id,
textFr: row.textFr,
textEn: row.textEn,
translationStatus: row.translationStatus,
sortOrder: row.sortOrder,
}));
return (
<main className="mx-auto max-w-3xl px-4 py-10">
<h1 className="text-2xl">Modèles de message</h1>
<p className="mt-2 max-w-prose text-[var(--ink-muted)]">
Les phrases que la boutique écrit souvent. Enregistrées ici, elles sont traduites une fois
et proposées partout où l’on compose un message — exceptions, vacances, bandeau.
</p>
<TemplateManager canEdit={session?.user?.role === 'admin'} templates={templates} />
</main>
);
}
+2 -2
View File
@@ -112,8 +112,8 @@ export default async function AdminHome() {
<div className="mt-8 grid gap-8 lg:grid-cols-[1.2fr_1fr]">
<section>
<h2 className="text-lg">L’écran en ce moment</h2>
<ScreenPreview className="mt-3" />
<h2 className="text-lg">L’écran</h2>
<ScreenPreview className="mt-3" timeTravel />
</section>
<section>
+14 -5
View File
@@ -2,9 +2,10 @@
import { useState, useTransition } from 'react';
import TemplatePicker, { type Template } from '@/app/admin/components/TemplatePicker';
import { countDays } from '@/lib/schedule/vacations';
import { createVacation, deleteVacation } from './actions';
import { createVacation, deleteVacation, translateVacationLabel } from './actions';
export type VacationRow = {
id: string;
@@ -18,9 +19,11 @@ export type VacationRow = {
export default function VacationManager({
canEdit,
periods,
templates,
}: {
canEdit: boolean;
periods: VacationRow[];
templates: Template[];
}) {
const [startDate, setStartDate] = useState('');
const [endDate, setEndDate] = useState('');
@@ -97,6 +100,7 @@ export default function VacationManager({
className="mt-1 w-full rounded-[var(--radius-sm)] border border-[var(--line-strong)] bg-[var(--surface)] px-2 py-2 text-base"
/>
</label>
<TemplatePicker templates={templates} onPick={setLabelFr} disabled={pending} />
</div>
<div className="mt-4 flex flex-wrap items-center gap-3">
@@ -104,10 +108,15 @@ export default function VacationManager({
type="button"
disabled={pending || !startDate || !endDate || labelFr.trim().length === 0}
onClick={() =>
run(
() => createVacation({ startDate, endDate, labelFr }),
'Période de fermeture enregistrée.',
)
run(async () => {
const created = await createVacation({ startDate, endDate, labelFr });
if (created.ok) {
// After the fact: the dates matter more than the English,
// and the translation service is measured in seconds.
await translateVacationLabel(created.id);
}
return created;
}, 'Période de fermeture enregistrée.')
}
className="rounded-[var(--radius-md)] bg-[var(--accent)] px-4 py-2.5 font-medium text-[var(--on-accent)] transition-colors hover:bg-[var(--accent-hover)] disabled:opacity-40"
>
+38 -2
View File
@@ -7,6 +7,7 @@ import { requireAdmin } from '@/lib/auth/actions';
import { prisma } from '@/lib/db';
import type { CivilDate } from '@/lib/schedule/civil';
import { countDays, findOverlap, validatePeriod } from '@/lib/schedule/vacations';
import { translateToEnglish } from '@/lib/translation/service';
export type ActionResult = { ok: true } | { ok: false; error: string };
@@ -14,7 +15,9 @@ export async function createVacation(input: {
startDate: CivilDate;
endDate: CivilDate;
labelFr: string;
}): Promise<ActionResult> {
// Returns the new id so the caller can translate it without having to ask
// which row was "the last one", which would be a race.
}): Promise<{ ok: true; id: string } | { ok: false; error: string }> {
const gate = await requireAdmin();
if (!gate.ok) {
return { ok: false, error: gate.error };
@@ -45,11 +48,17 @@ export async function createVacation(input: {
};
}
// A phrase saved as a template is already translated; reusing it is instant
// where the service takes seconds. The label reaches the panel during the
// closure, so it needs its English.
const fromTemplate = await prisma.messageTemplate.findUnique({ where: { textFr: labelFr } });
const created = await prisma.vacationPeriod.create({
data: {
startDate: asDate(input.startDate),
endDate: asDate(input.endDate),
labelFr,
labelEn: fromTemplate?.textEn ?? null,
createdBy: gate.value.email,
},
});
@@ -68,7 +77,7 @@ export async function createVacation(input: {
});
revalidateAll();
return { ok: true };
return { ok: true, id: created.id };
}
export async function deleteVacation(id: string): Promise<ActionResult> {
@@ -116,3 +125,30 @@ function revalidateAll(): void {
revalidatePath('/admin/vacances');
revalidatePath('/admin/exceptions');
}
/**
* Translates a period's label, if it still needs one.
*
* Separate from the creation, so a slow translation service never costs the
* shop its holiday dates. A failure leaves the French alone on screen.
*/
export async function translateVacationLabel(id: string): Promise<ActionResult> {
const gate = await requireAdmin();
if (!gate.ok) {
return { ok: false, error: gate.error };
}
const existing = await prisma.vacationPeriod.findUnique({ where: { id } });
if (!existing || existing.labelEn) {
return { ok: true };
}
const outcome = await translateToEnglish(existing.labelFr);
if (!outcome.ok) {
return { ok: false, error: outcome.error };
}
await prisma.vacationPeriod.update({ where: { id }, data: { labelEn: outcome.text } });
revalidateAll();
return { ok: true };
}
+7 -1
View File
@@ -3,6 +3,7 @@ import { prisma } from '@/lib/db';
import { toCivilDate } from '@/lib/schedule/civil';
import { loadSettings } from '@/lib/schedule/context';
import { periodsOverlap, upcomingPeriods } from '@/lib/schedule/vacations';
import { loadTemplates } from '@/lib/templates';
import VacationManager, { type VacationRow } from './VacationManager';
import YearCalendar from './YearCalendar';
@@ -10,7 +11,11 @@ import YearCalendar from './YearCalendar';
export const metadata = { title: 'Vacances — ITA ITO' };
export default async function VacationsPage() {
const [session, settings] = await Promise.all([auth(), loadSettings()]);
const [session, settings, templates] = await Promise.all([
auth(),
loadSettings(),
loadTemplates(),
]);
const today = toCivilDate(new Date(), settings.timezone);
const rows = await prisma.vacationPeriod.findMany({ orderBy: { startDate: 'asc' } });
@@ -39,6 +44,7 @@ export default async function VacationsPage() {
<VacationManager
canEdit={session?.user?.role === 'admin'}
periods={upcomingPeriods(periods, today)}
templates={templates}
/>
<section className="mt-10">
+10 -2
View File
@@ -1,22 +1,30 @@
import { publicBaseUrl } from '@/lib/config';
import { encodeScreen } from '@/lib/screen/encode';
import { parsePreviewTime } from '@/lib/screen/preview-time';
import { renderScreenSvg } from '@/lib/screen/render';
import { buildCurrentScreen } from '@/lib/screen/service';
export const dynamic = 'force-dynamic';
/**
* The panel as it stands right now, as a PNG for the browser.
* The panel as it stands, or as it will stand at a given moment.
*
* Deliberately the same pipeline the device is served from — payload, SVG,
* threshold — so what the admin sees is what the shop window shows, down to
* the last thresholded pixel. A preview drawn any other way would eventually
* disagree with reality, and quietly.
*
* `?at=` moves the clock. The whole pipeline is already a function of "now",
* so showing next Tuesday costs nothing but passing a different instant —
* which is how a holiday closure can be checked before anyone is standing in
* front of a locked door.
*
* Behind /api/admin, so the middleware requires a session.
*/
export async function GET(request: Request) {
const { payload } = await buildCurrentScreen(new Date(), publicBaseUrl(request));
const { at } = parsePreviewTime(new URL(request.url).searchParams.get('at'), new Date());
const { payload } = await buildCurrentScreen(at, publicBaseUrl(request));
const png = encodeScreen(await renderScreenSvg(payload), 'png');
return new Response(new Uint8Array(png), {