Repository Public
1// SP Mail Next — mise en veille et rappels de suivi : échéances proposées (calculées dans le fuseau de l'utilisateur, heure2// d'été comprise), formes du serveur, collections synchronisées et écritures (/api/next/snoozes, /api/next/reminders).3import { nx } from "./api"4import { createCollection } from "./collection"5import type { Party } from "./types"67// ---------------------------------------------------------------- temps civil dans un fuseau (fonctions pures)8export interface Wall {9 year: number10 /** 1 à 12 */11 month: number12 day: number13 hour: number14 minute: number15 /** 0 = dimanche … 6 = samedi */16 weekday: number17}18const formatters = new Map<string, Intl.DateTimeFormat>()19const formatter = (timeZone: string): Intl.DateTimeFormat => {20 let f = formatters.get(timeZone)21 if (!f) formatters.set(timeZone, (f = new Intl.DateTimeFormat("en-US", { timeZone, hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" })))22 return f23}24/** Fuseau de l'appareil (celui dans lequel l'utilisateur lit ses dates). */25export const deviceZone = (): string => {26 try {27 return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"28 } catch {29 return "UTC"30 }31}32/** Date et heure civiles d'un instant dans un fuseau. */33export function wallOf(at: Date, timeZone: string): Wall {34 const p: Record<string, number> = {}35 for (const part of formatter(timeZone).formatToParts(at)) if (part.type !== "literal") p[part.type] = Number(part.value)36 return { year: p.year, month: p.month, day: p.day, hour: p.hour % 24, minute: p.minute, weekday: new Date(Date.UTC(p.year, p.month - 1, p.day)).getUTCDay() }37}38/**39 * Instant d'une heure civile dans un fuseau (le jour peut déborder : `day + 3` passe au mois suivant). Au passage à l'heure40 * d'été, une heure qui n'existe pas (2 h 30) est décalée d'une heure ; au retour à l'heure normale, une heure qui existe deux41 * fois désigne la première.42 */43export function zonedTime(year: number, month: number, day: number, hour: number, minute: number, timeZone: string): Date {44 const wanted = Date.UTC(year, month - 1, day, hour, minute)45 const offsetAt = (ms: number) => {46 const w = wallOf(new Date(ms), timeZone)47 return Date.UTC(w.year, w.month - 1, w.day, w.hour, w.minute) - Math.floor(ms / 60_000) * 60_00048 }49 // deux passes : le décalage lu à la première estimation peut être celui de l'autre côté d'un changement d'heure50 const first = wanted - offsetAt(wanted)51 const second = wanted - offsetAt(first)52 if (second === first) return new Date(first)53 // les deux estimations diffèrent : heure ambiguë ou inexistante — la plus ancienne dont l'heure civile correspond, sinon la plus tardive54 const lo = Math.min(first, second)55 const w = wallOf(new Date(lo), timeZone)56 return new Date(w.hour === hour && w.minute === minute ? lo : Math.max(first, second))57}58/** Valeurs d'un champ `date` (AAAA-MM-JJ) et d'un champ `time` (HH:MM) → instant dans le fuseau ; null si illisible. */59export function parseLocal(date: string, time: string, timeZone: string): Date | null {60 const d = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date)61 const h = /^(\d{2}):(\d{2})/.exec(time)62 if (!d || !h) return null63 const [y, mo, da, ho, mi] = [Number(d[1]), Number(d[2]), Number(d[3]), Number(h[1]), Number(h[2])]64 if (mo < 1 || mo > 12 || da < 1 || da > 31 || ho > 23 || mi > 59) return null65 return zonedTime(y, mo, da, ho, mi, timeZone)66}67const pad = (n: number) => String(n).padStart(2, "0")68/** Instant → valeurs des champs `date` et `time` dans le fuseau. */69export function toLocalFields(at: Date, timeZone: string): { date: string; time: string } {70 const w = wallOf(at, timeZone)71 return { date: `${w.year}-${pad(w.month)}-${pad(w.day)}`, time: `${pad(w.hour)}:${pad(w.minute)}` }72}7374// ---------------------------------------------------------------- échéances proposées75export const HOURS = { morning: 8, evening: 18, weekend: 9 } as const76export type SnoozePresetId = "laterToday" | "tonight" | "tomorrow" | "weekend" | "nextWeekend" | "nextWeek"77export type ReminderPresetId = "tomorrow" | "in3days" | "in1week" | "in2weeks"78export interface Preset<Id extends string = string> {79 id: Id80 at: Date81}82const HALF_HOUR = 30 * 60_0008384/**85 * Échéances de mise en veille proposées à l'instant `now`, dans l'ordre chronologique :86 * - « plus tard aujourd'hui » : dans trois heures, arrondi à la demi-heure suivante, tant que cela reste le même jour ;87 * - « ce soir » : 18 h, s'il reste au moins une demi-heure ;88 * - « demain matin » : 8 h ;89 * - « ce week-end » : samedi 9 h (du lundi au vendredi) ; le samedi et le dimanche, « le week-end prochain » (samedi suivant) ;90 * - « la semaine prochaine » : lundi 8 h (omise le dimanche, où elle se confond avec « demain matin »).91 */92export function snoozePresets(now: Date, timeZone: string): Preset<SnoozePresetId>[] {93 const w = wallOf(now, timeZone)94 const day = (offset: number, hour: number) => zonedTime(w.year, w.month, w.day + offset, hour, 0, timeZone)95 const out: Preset<SnoozePresetId>[] = []96 const later = new Date(Math.ceil((now.getTime() + 3 * 3_600_000) / HALF_HOUR) * HALF_HOUR)97 const lw = wallOf(later, timeZone)98 if (lw.day === w.day && lw.month === w.month) out.push({ id: "laterToday", at: later })99 const tonight = day(0, HOURS.evening)100 if (tonight.getTime() - now.getTime() >= HALF_HOUR) out.push({ id: "tonight", at: tonight })101 out.push({ id: "tomorrow", at: day(1, HOURS.morning) })102 const weekendDay = w.weekday === 6 ? 7 : w.weekday === 0 ? 6 : 6 - w.weekday103 out.push({ id: w.weekday === 6 || w.weekday === 0 ? "nextWeekend" : "weekend", at: day(weekendDay, HOURS.weekend) })104 const monday = w.weekday === 0 ? 1 : 8 - w.weekday105 if (monday > 1) out.push({ id: "nextWeek", at: day(monday, HOURS.morning) })106 // « ce soir » avant « plus tard » quand il tombe plus tôt107 return out.sort((a, b) => a.at.getTime() - b.at.getTime())108}109/** Échéances d'un rappel de suivi : demain, dans trois jours, une semaine, deux semaines — toujours à 8 h. */110export function reminderPresets(now: Date, timeZone: string): Preset<ReminderPresetId>[] {111 const w = wallOf(now, timeZone)112 const day = (offset: number) => zonedTime(w.year, w.month, w.day + offset, HOURS.morning, 0, timeZone)113 return [{ id: "tomorrow", at: day(1) }, { id: "in3days", at: day(3) }, { id: "in1week", at: day(7) }, { id: "in2weeks", at: day(14) }]114}115/** Une échéance n'est acceptée (par le serveur aussi) que dans le futur. */116export const isFuture = (at: Date | null, now: Date = new Date()): at is Date => !!at && !Number.isNaN(at.getTime()) && at.getTime() > now.getTime()117118// ---------------------------------------------------------------- formes du serveur (server/src/next/snooze.ts)119export interface Snooze {120 id: string121 mailbox_id: string122 email_id: string123 thread_id: string | null124 subject: string125 from: Party | null126 until: string127 status: "active" | "done" | "cancelled" | "missing"128 created_at: string129}130export interface Reminder {131 id: string132 mailbox_id: string133 email_id: string134 thread_id: string | null135 subject: string136 counterpart: Party | null137 due_at: string138 only_if_no_reply: boolean139 note: string | null140 status: "pending" | "due" | "done" | "resolved" | "cancelled"141 fired_at: string | null142 created_at: string143}144/** Dossier (sans rôle, à la racine) où le serveur range les messages en veille. */145export const SNOOZED_FOLDER = "Snoozed"146export const KW_SNOOZED = "$snoozed"147export const KW_FOLLOWUP = "$followup"148export const NOTE_MAX = 500149150const byDate = <T>(key: (x: T) => string) => (a: T, b: T) => Date.parse(key(a)) - Date.parse(key(b))151export const sortSnoozes = (list: readonly Snooze[]): Snooze[] => list.filter((s) => s.status === "active").sort(byDate((s) => s.until))152/** Rappels ouverts, en deux sections : échus (les plus anciens d'abord) et à venir (les plus proches d'abord). */153export function splitReminders(list: readonly Reminder[]): { due: Reminder[]; pending: Reminder[] } {154 return { due: list.filter((r) => r.status === "due").sort(byDate((r) => r.fired_at ?? r.due_at)), pending: list.filter((r) => r.status === "pending").sort(byDate((r) => r.due_at)) }155}156157// ---------------------------------------------------------------- collections et écritures158export const snoozesCollection = createCollection<Snooze>("snoozes", async () => sortSnoozes(await nx.list<Snooze>("snoozes", { status: "active" })))159export const remindersCollection = createCollection<Reminder>("reminders", async () => {160 const [pending, due] = await Promise.all([nx.list<Reminder>("reminders", { status: "pending" }), nx.list<Reminder>("reminders", { status: "due" })])161 return [...due, ...pending]162})163164/** Met en veille des messages d'une boîte ; rend les mises en veille actives créées (ou replanifiées). */165export async function postSnooze(mailboxId: string, emailIds: string[], until: Date): Promise<Snooze[]> {166 const out: Snooze[] = []167 for (let i = 0; i < emailIds.length; i += 200) out.push(...(await nx.post<{ data: Snooze[] }>("snoozes", { mailbox_id: mailboxId, email_ids: emailIds.slice(i, i + 200), until: until.toISOString() })).data)168 snoozesCollection.mutate((items) => sortSnoozes([...items.filter((s) => !out.some((o) => o.id === s.id)), ...out]))169 return out170}171export async function patchSnooze(id: string, until: Date): Promise<Snooze> {172 const s = await nx.patch<Snooze>(`snoozes/${id}`, { until: until.toISOString() })173 snoozesCollection.mutate((items) => sortSnoozes(items.map((x) => (x.id === id ? s : x))))174 return s175}176/** Réveil immédiat : le message retourne à sa place (sans redevenir non lu). */177export async function deleteSnooze(id: string): Promise<void> {178 await nx.del(`snoozes/${id}`)179 snoozesCollection.mutate((items) => items.filter((x) => x.id !== id))180}181export async function postReminder(input: { mailboxId: string; emailId: string; dueAt: Date; onlyIfNoReply: boolean; note: string }): Promise<Reminder> {182 const note = input.note.trim().slice(0, NOTE_MAX)183 const r = await nx.post<Reminder>("reminders", { mailbox_id: input.mailboxId, email_id: input.emailId, due_at: input.dueAt.toISOString(), only_if_no_reply: input.onlyIfNoReply, ...(note ? { note } : {}) })184 remindersCollection.mutate((items) => [...items.filter((x) => x.id !== r.id), r])185 return r186}187/** `done` clôt le rappel ; une nouvelle échéance réarme un rappel échu (il redevient « à venir »). */188export async function patchReminder(id: string, patch: { dueAt?: Date; done?: boolean }): Promise<Reminder> {189 const r = await nx.patch<Reminder>(`reminders/${id}`, patch.done ? { status: "done" } : { due_at: patch.dueAt!.toISOString() })190 remindersCollection.mutate((items) => (r.status === "pending" || r.status === "due" ? items.map((x) => (x.id === id ? r : x)) : items.filter((x) => x.id !== id)))191 return r192}193export async function deleteReminder(id: string): Promise<void> {194 await nx.del(`reminders/${id}`)195 remindersCollection.mutate((items) => items.filter((x) => x.id !== id))196}197