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