fix(notifications): take today from the instance's TZ and catch up missed trip reminders

The reminder crons run at 09:00 in the instance's TZ but computed today
in UTC, so east of Greenwich a trip reminder arrived a day late. A day
the job did not run also lost that day's trip reminders for good: the
match was 'starts exactly N days from today'. Trips now record the start
date a reminder went out for, and the job sends every reminder that is
due and not yet sent. The active-trip redirect and the upcoming
reservations use the instance's date and clock as well.
This commit is contained in:
Maurice
2026-10-07 16:16:26 +02:00
parent e0aedbb2c6
commit a8fc93dfde
10 changed files with 119 additions and 31 deletions
+12
View File
@@ -1,4 +1,5 @@
import tzlookup from 'tz-lookup';
import { readEnv } from '../../app-config';
/** Local calendar date and clock time for an instant in an IANA timezone. */
export function localParts(iso: string | null, timezone: string | null): { date: string | null; time: string | null } {
@@ -34,3 +35,14 @@ export function resolveTimeZone(lat: unknown, lng: unknown): string | null {
return null;
}
}
/**
* Today's date and the clock time where the instance runs, in the TZ the crons
* are scheduled in (CronRegistrarService). A UTC "today" disagreed with the
* schedule: east of Greenwich a 09:00 job saw the previous date.
*/
export function appClock(now: Date = new Date()): { date: string; time: string } {
const { date, time } = localParts(now.toISOString(), readEnv().app.tz || null);
return { date: date ?? now.toISOString().slice(0, 10), time: time ?? now.toISOString().slice(11, 16) };
}
@@ -9,6 +9,8 @@ import { Trips } from '../../db/entities/Trips.entity';
import { TodoItems } from '../../db/entities/TodoItems.entity';
import { NotificationsService } from './notifications.service';
import { CronRegistrarService } from '../scheduling/cron-registrar.service';
import { addIsoDays } from '@trek/shared';
import { appClock } from '../common/timezoneService';
/**
* The trip-reminder and todo-due reminder crons, in the domain that owns them
@@ -75,28 +77,27 @@ export class ReminderJobsService implements OnApplicationBootstrap {
this.registrar.register('todo-reminders', '0 9 * * *', () => this.todoTick());
}
/** Daily check for trips starting exactly reminder_days from now. */
/**
* Daily check for trips whose reminder is due: the reminder day has come,
* the trip has not started yet, and no reminder went out for this start
* date. A day the job did not run is caught up on the next one, and a trip
* moved to a new start date is reminded again. "Today" is the date in the
* TZ the job is scheduled in, not UTC.
*/
async tripTick(): Promise<void> {
try {
if ((await this.appSettings.getValue('notify_trip_reminder')) === 'false') return;
// RJ3 (Task 0's R9 ruling): the legacy statement concatenated a
// per-row column (`t.reminder_days`) into a `date('now', '+' ||
// t.reminder_days || ' days')` modifier — no bound-parameter or
// JS-constant-spelled helper can express that. Read the narrower
// candidate set (reminder_days set, start_date set) and do the
// per-row date-equality check in JS instead. `Date.UTC(...)` matches
// SQLite's own `date('now')`, which is UTC, not server-local time.
const today = appClock().date;
const candidates = await this.trips.listReminderCandidates();
const todayUtc = new Date();
const trips = candidates.filter((t) => {
const target = new Date(Date.UTC(todayUtc.getUTCFullYear(), todayUtc.getUTCMonth(), todayUtc.getUTCDate()));
target.setUTCDate(target.getUTCDate() + t.reminder_days);
return t.start_date === target.toISOString().slice(0, 10);
});
const trips = candidates.filter((t) =>
t.reminder_sent_for !== t.start_date
&& t.start_date >= today
&& addIsoDays(t.start_date, -t.reminder_days) <= today);
for (const trip of trips) {
await this.notifications.send({ event: 'trip_reminder', actorId: null, scope: 'trip', targetId: trip.id, params: { trip: trip.title, tripId: String(trip.id) } }).catch(() => {});
await this.trips.markReminderSent(trip.id, trip.start_date);
}
if (trips.length > 0) {
@@ -112,18 +113,10 @@ export class ReminderJobsService implements OnApplicationBootstrap {
try {
if ((await this.appSettings.getValue('notify_todo_due')) === 'false') return;
// RJ4 (Task 0's R9 ruling): `date('now', '+' || ? || ' days')`
// concatenates a bound parameter into the modifier — resolved in JS
// the same way RJ3 is (`Date.UTC`-based, matching SQLite's UTC
// `date('now')`). `due_date` is documented as always canonical
// `YYYY-MM-DD` text, so a direct text-range bind reproduces
// `date(ti.due_date) <= / >= ...` for well-formed rows.
const todayUtc = new Date();
const today = new Date(Date.UTC(todayUtc.getUTCFullYear(), todayUtc.getUTCMonth(), todayUtc.getUTCDate()));
const todayDate = today.toISOString().slice(0, 10);
const cutoff = new Date(today);
cutoff.setUTCDate(cutoff.getUTCDate() + TODO_REMINDER_LEAD_DAYS);
const cutoffDate = cutoff.toISOString().slice(0, 10);
// `due_date` is canonical `YYYY-MM-DD` text, so a text-range bind
// covers the lead window. "Today" is the date in the job's TZ.
const todayDate = appClock().date;
const cutoffDate = addIsoDays(todayDate, TODO_REMINDER_LEAD_DAYS);
const todos = await this.todoItems.listDueForReminder(todayDate, cutoffDate);
@@ -37,6 +37,7 @@ import { Trips } from '../../db/entities/Trips.entity';
import { BudgetItems } from '../../db/entities/BudgetItems.entity';
import type { BudgetItemsRepository } from '../../db/repositories/BudgetItems.repository';
import type { TripsRepository } from '../../db/repositories/Trips.repository';
import { appClock } from '../common/timezoneService';
type Trip = TripAccess;
type BudgetEntry = { total_price?: number; category?: string; currency?: string | null; exchange_rate?: number } | undefined;
@@ -484,9 +485,10 @@ export class ReservationsService {
* docstring for the CTE/`UNION ALL`/GLOB/CAST shape.
*/
async listUpcoming(userId: number, limit = 6) {
const today = new Date().toISOString().slice(0, 10);
const now = new Date().toISOString();
return await this.reservationsRepo.listUpcomingForUser(userId, today, now.slice(11, 16), limit);
// Reservation dates and times are wall-clock values, so "now" is the
// instance's local clock rather than UTC.
const { date, time } = appClock();
return await this.reservationsRepo.listUpcomingForUser(userId, date, time, limit);
}
async getReservationWithJoins(id: string | number) {
+2 -1
View File
@@ -52,6 +52,7 @@ import { escapeLikePattern } from '../places/places.helpers';
import { NotFoundError, ValidationError } from '../common/domain-errors';
import { UnitOfWork } from '../database/unit-of-work';
import { legacyBoundIntegerText } from '../common/row-id';
import { appClock } from '../common/timezoneService';
/**
* The date range is refused, not cut short: generateDays used to clip the day
@@ -455,7 +456,7 @@ export class TripsService {
* trip with its per-trip day/place counts.
*/
/** TP21 — `TripsRepository.activeTrip`: the triple `CASE WHEN … relevance` projection and the double-`CASE WHEN` `ORDER BY`. */
async activeTrip(userId: number, today = new Date().toISOString().slice(0, 10)) {
async activeTrip(userId: number, today = appClock().date) {
return await this.tripsRepo.activeTrip(userId, today) as ActiveTrip & { relevance: number } | undefined;
}