Files
ita-ito-horaires/lib/screen/viewmodel.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

194 lines
5.8 KiB
TypeScript

/**
* Builds the frozen screen payload from resolved schedule data.
*
* Every string the panel will show is computed here, server-side and in both
* languages. The renderer downstream draws and nothing else: it has no access
* to the schedule, so it cannot disagree with this file about what the shop's
* hours are. That separation is what lets the whole display be tested without
* a device attached.
*/
import {
addCivilDays,
civilDayOfWeek,
startOfCivilWeek,
toCivilDate,
toIsoWithOffset,
} from '@/lib/schedule/civil';
import {
formatDateEn,
formatDateFr,
formatHoursText,
formatNextChangeEn,
formatNextChangeFr,
shortDayLabelEn,
shortDayLabelFr,
type NextChange,
} from '@/lib/schedule/format';
import { detectDivergence, getCurrentStatus, resolveCivilDay } from '@/lib/schedule/resolver';
import type { ScheduleContext, ShopStatus } from '@/lib/schedule/types';
import {
AUTO_BANNERS,
MESSAGE_MAX_CHARS,
SCREEN_SCHEMA_VERSION,
type ScreenBanner,
type ScreenPayload,
type ScreenWeekDay,
} from './contract';
export type MessageCandidate = {
textFr: string;
/** `null` while the translation is pending, or if it failed. */
textEn: string | null;
startsAt: Date | null;
endsAt: Date | null;
priority: number;
isActive: boolean;
};
export type ScreenInput = {
now: Date;
ctx: ScheduleContext;
shopName: string;
logoUrl: string;
messages: MessageCandidate[];
};
/** The highest-priority message that is active and inside its validity window. */
export function selectActiveMessage(
messages: MessageCandidate[],
now: Date,
): MessageCandidate | null {
const instant = now.getTime();
const live = messages.filter(
(message) =>
message.isActive &&
(message.startsAt === null || message.startsAt.getTime() <= instant) &&
(message.endsAt === null || message.endsAt.getTime() >= instant),
);
if (live.length === 0) {
return null;
}
return live.reduce((best, candidate) => (candidate.priority > best.priority ? candidate : best));
}
export function buildScreenPayload({
now,
ctx,
shopName,
logoUrl,
messages,
}: ScreenInput): ScreenPayload {
const today = toCivilDate(now, ctx.timezone);
const status = getCurrentStatus(now, ctx);
// Closing soon is still open, and opening soon is still closed: the large
// word states the fact, the line under it carries the nuance.
const isOpenNow = status.status === 'OPEN' || status.status === 'CLOSING_SOON';
const nextChange: NextChange | null = status.nextChangeAt
? {
kind: isOpenNow ? 'CLOSES' : 'OPENS',
date: status.nextChangeAt.date,
time: status.nextChangeAt.time,
}
: null;
return {
schema: SCREEN_SCHEMA_VERSION,
generated_at: toIsoWithOffset(now, ctx.timezone),
shop_name: shopName,
logo_url: logoUrl,
today: {
date_fr: formatDateFr(today),
date_en: formatDateEn(today),
status: status.status,
status_fr: isOpenNow ? 'OUVERT' : 'FERMÉ',
status_en: isOpenNow ? 'OPEN' : 'CLOSED',
hours_text: formatHoursText(status.today.slots),
next_change_fr: formatNextChangeFr(nextChange, today),
next_change_en: formatNextChangeEn(nextChange, today),
is_exception: status.today.isException,
},
week: buildWeek(today, ctx),
banner: buildBanner(now, ctx, messages, status, isOpenNow),
};
}
/** Monday through Sunday of the week containing `today`. */
function buildWeek(today: string, ctx: ScheduleContext): ScreenWeekDay[] {
const monday = startOfCivilWeek(today);
return Array.from({ length: 7 }, (_, offset) => {
const date = addCivilDays(monday, offset);
const day = resolveCivilDay(date, ctx);
const dayOfWeek = civilDayOfWeek(date);
return {
label_fr: shortDayLabelFr(dayOfWeek),
label_en: shortDayLabelEn(dayOfWeek),
hours_text: formatHoursText(day.slots),
is_today: date === today,
is_closed: !day.isOpen,
is_exception: day.isException,
};
});
}
function buildBanner(
now: Date,
ctx: ScheduleContext,
messages: MessageCandidate[],
status: ShopStatus,
isOpenNow: boolean,
): ScreenBanner | null {
// The reason today's hours changed, while the door is shut.
//
// 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. And it disappears the moment the shop opens — a notice
// explaining a late opening is worse than useless once the door is open.
//
// `isOpenNow` is the state at this minute, not the day's: a day that opens
// at 14:00 has opening hours all morning while its door is shut, and that
// morning is exactly when the reason needs to be on screen.
const exceptionNote = status.today.isException && !isOpenNow ? status.today : null;
if (exceptionNote?.noteFr) {
return {
kind: 'EXCEPTION',
text_fr: clamp(exceptionNote.noteFr),
text_en: clamp(exceptionNote.noteEn ?? ''),
};
}
// Otherwise a message someone took the trouble to write wins the space.
const message = selectActiveMessage(messages, now);
if (message) {
return {
kind: 'MESSAGE',
text_fr: clamp(message.textFr),
text_en: clamp(message.textEn ?? ''),
};
}
const divergence = detectDivergence(now, ctx);
if (divergence === 'NONE') {
return null;
}
const kind = divergence === 'TODAY' ? 'SCHEDULE_TODAY' : 'SCHEDULE_WEEK';
const wording = AUTO_BANNERS[kind];
return { kind, text_fr: wording.fr, text_en: wording.en };
}
/**
* The editor warns before anyone can save something this long, so reaching
* here means the limit changed after the fact. Cut rather than let the text
* spill off a panel nobody can scroll.
*/
function clamp(text: string): string {
if (text.length <= MESSAGE_MAX_CHARS) {
return text;
}
return `${text.slice(0, MESSAGE_MAX_CHARS - 1).trimEnd()}…`;
}