mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 18:04:18 +00:00
refactor(notifications): reminder crons, mailer, ntfy and webhook transports through repositories
This commit is contained in:
@@ -2,6 +2,7 @@ import type { TodoItems } from '../entities/TodoItems.entity';
|
||||
import { type AssertRowKeys } from './_shared/rows';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
import { presenceSet } from './_shared/presence-set';
|
||||
import { columnRef, currentTimestamp, nowMinusHours } from '../dialect/sql-functions';
|
||||
|
||||
/** A bare `todo_items` row — every scalar column, incl. the two `persist(false)` relation mirrors (`trip_id`, `assigned_user_id`). */
|
||||
export interface TodoItemRow {
|
||||
@@ -159,4 +160,99 @@ export class TodoItemsRepository extends TrekRepository<TodoItems> {
|
||||
.executeTakeFirstOrThrow();
|
||||
return Number(result.insertId);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plan 3f Task 4 (`ReminderJobsService#todoTick`) — additive. `this.qb()`,
|
||||
// not Kysely: RJ5's dedup window needs `nowMinusHours` (a raw MikroORM
|
||||
// `RawQueryFragment` from `sql-functions.ts`, which composes with a
|
||||
// QueryBuilder/native filter but not with Kysely — the Kysely `sql` tag is
|
||||
// banned under `src/db/repositories/**`), and the join needs `columnRef`
|
||||
// to read `trip_id`/`assigned_user_id` (both `persist(false)` mirrors of
|
||||
// the real `trip`/`assignedUser` relations — a bare select silently drops
|
||||
// them, per `RoadtripDayBoundariesRepository`'s documented trap). `ti.trip`
|
||||
// is ALSO the join target here, so it is never itself selected (that
|
||||
// aliases off the JOINED row's own PK instead of the FK scalar —
|
||||
// `PlaceRatingsRepository.listForPlaces`'s documented trap); `t.user` is
|
||||
// safe to select bare (its target, `users`, is not separately joined in
|
||||
// this query), aliasing to the physical `user_id` column per
|
||||
// `TripsRepository.findAccessible`'s precedent.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* RJ4 (`reminder-jobs.service.ts#todoTick`) — restructured per Task 0's R9
|
||||
* ruling. Legacy: `SELECT ti.id, ti.trip_id, ti.name, ti.due_date,
|
||||
* ti.assigned_user_id, t.title AS trip_title, t.user_id AS trip_owner_id
|
||||
* FROM todo_items ti JOIN trips t ON t.id = ti.trip_id WHERE ti.checked = 0
|
||||
* AND ti.due_date IS NOT NULL AND ti.due_date <> '' AND date(ti.due_date)
|
||||
* <= date('now', '+' || ? || ' days') AND date(ti.due_date) >= date('now')
|
||||
* AND (ti.reminded_at IS NULL OR ti.reminded_at <= datetime('now', '-20
|
||||
* hours'))`.
|
||||
*
|
||||
* The `date('now', '+' || ? || ' days')`/`date('now')` bounds are
|
||||
* JS-computed by the caller (`todayDate`/`cutoffDate`, both `Date.UTC`-
|
||||
* based `YYYY-MM-DD` text — matching SQLite's own UTC `date('now')`, per
|
||||
* the same reasoning RJ3's restructuring documents) and bound directly
|
||||
* against `ti.due_date` (documented elsewhere as always canonical
|
||||
* `YYYY-MM-DD` text, so `date(ti.due_date)`'s normalization is a no-op for
|
||||
* well-formed rows and the wrapping is dropped). The `datetime('now',
|
||||
* '-20 hours')` dedup bound stays genuinely in SQL, via `nowMinusHours`
|
||||
* (Task 0's R9 helper) — RJ5's brief explicitly calls for it, not a JS
|
||||
* equivalent.
|
||||
*/
|
||||
async listDueForReminder(todayDate: string, cutoffDate: string): Promise<TodoReminderRow[]> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
const rows = await this.qb('ti')
|
||||
.join('ti.trip', 't')
|
||||
.select(['ti.id', columnRef(platform, 'ti.trip_id'), 'ti.name', 'ti.due_date', columnRef(platform, 'ti.assigned_user_id'), 't.title', 't.user'])
|
||||
.andWhere({ checked: 0 })
|
||||
.andWhere({ due_date: { $ne: null } })
|
||||
.andWhere({ due_date: { $ne: '' } })
|
||||
.andWhere({ due_date: { $gte: todayDate } })
|
||||
.andWhere({ due_date: { $lte: cutoffDate } })
|
||||
.andWhere({ $or: [{ reminded_at: null }, { reminded_at: { $lte: nowMinusHours(platform, 20) } }] })
|
||||
.execute<TodoReminderQueryRow[]>('all', false);
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
trip_id: row.trip_id,
|
||||
name: row.name,
|
||||
due_date: row.due_date,
|
||||
assigned_user_id: row.assigned_user_id,
|
||||
trip_title: row.title,
|
||||
trip_owner_id: row.user_id,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* RJ5 (`reminder-jobs.service.ts#todoTick`, looped) — `UPDATE todo_items
|
||||
* SET reminded_at = CURRENT_TIMESTAMP WHERE id = ?`. Stays AFTER the
|
||||
* notification send in call order (plan3f-inputs.md correction #8 — a
|
||||
* documented, not-fixed-by-this-plan at-least-once ordering, unlike
|
||||
* `notifications.service.ts#respond`'s deliberately claim-then-act shape).
|
||||
*/
|
||||
async markReminded(id: number): Promise<void> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
await this.nativeUpdate({ id }, { reminded_at: currentTimestamp(platform) });
|
||||
}
|
||||
}
|
||||
|
||||
/** {@link TodoItemsRepository.listDueForReminder}'s raw QB row — before the `trip_title`/`trip_owner_id` rename. */
|
||||
interface TodoReminderQueryRow {
|
||||
id: number;
|
||||
trip_id: number;
|
||||
name: string;
|
||||
due_date: string;
|
||||
assigned_user_id: number | null;
|
||||
title: string;
|
||||
user_id: number;
|
||||
}
|
||||
|
||||
/** {@link TodoItemsRepository.listDueForReminder}'s output row. */
|
||||
export interface TodoReminderRow {
|
||||
id: number;
|
||||
trip_id: number;
|
||||
name: string;
|
||||
due_date: string;
|
||||
assigned_user_id: number | null;
|
||||
trip_title: string;
|
||||
trip_owner_id: number;
|
||||
}
|
||||
|
||||
@@ -735,6 +735,47 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
.executeTakeFirst();
|
||||
return row?.currency;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plan 3f Task 4 (`ReminderJobsService`) — additive.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* RJ2 (`reminder-jobs.service.ts`'s boot banner, inside `runOnBoot`) —
|
||||
* `SELECT COUNT(*) as c FROM trips WHERE reminder_days > 0 AND start_date
|
||||
* IS NOT NULL`.
|
||||
*/
|
||||
async countActiveWithReminders(): Promise<number> {
|
||||
return this.count({ reminder_days: { $gt: 0 }, start_date: { $ne: null } });
|
||||
}
|
||||
|
||||
/**
|
||||
* RJ3 (`reminder-jobs.service.ts#tripTick`) — restructured per 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, which no bound-parameter or JS-constant-spelled helper
|
||||
* can express. This narrows the SQL read to the same WHERE minus the date
|
||||
* comparison (`SELECT t.id, t.title, t.user_id, t.reminder_days,
|
||||
* t.start_date FROM trips t WHERE t.reminder_days > 0 AND t.start_date IS
|
||||
* NOT NULL`); the caller (`ReminderJobsService.tripTick`) does the
|
||||
* per-row date-equality check in JS against `start_date`, per R9's exact
|
||||
* verified shape.
|
||||
*/
|
||||
async listReminderCandidates(): Promise<TripReminderCandidateRow[]> {
|
||||
return await this.qb('t')
|
||||
.select(['t.id', 't.title', 't.user', 't.reminder_days', 't.start_date'])
|
||||
.andWhere({ reminder_days: { $gt: 0 }, start_date: { $ne: null } })
|
||||
.execute<TripReminderCandidateRow[]>('all', false);
|
||||
}
|
||||
}
|
||||
|
||||
/** {@link TripsRepository.listReminderCandidates}'s row — `t.user` selected bare (not joined here), so it aliases to the physical `user_id` column per `findAccessible`'s documented precedent. */
|
||||
export interface TripReminderCandidateRow {
|
||||
id: number;
|
||||
title: string;
|
||||
user_id: number;
|
||||
reminder_days: number;
|
||||
start_date: string;
|
||||
}
|
||||
|
||||
/** `PublicApiService.listTrips`/`getTrip`'s 8-column trip projection. */
|
||||
|
||||
@@ -1228,6 +1228,22 @@ export class UsersRepository extends TrekRepository<Users> {
|
||||
const row = await this.findOne({ id }, { fields: ['username', 'email'] });
|
||||
return row ? { username: row.username, email: row.email } : undefined;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Plan 3f Task 4 (MS2 — mailer.service.ts#getUserEmail) — additive.
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* MS2 — `SELECT email FROM users WHERE id = ? AND COALESCE(is_guest, 0) = 0`
|
||||
* — defense-in-depth (#1362 class): a guest's synthetic email must never be
|
||||
* emailed. `is_guest: 0` is exact parity for the `COALESCE(is_guest, 0) = 0`
|
||||
* guard (`countNonGuest`'s docstring above: the column is `NOT NULL DEFAULT
|
||||
* 0`, so no row can store `NULL` there).
|
||||
*/
|
||||
async getEmailNonGuest(id: number): Promise<string | null> {
|
||||
const row = await this.findOne({ id, is_guest: 0 }, { fields: ['email'] });
|
||||
return row?.email ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { MailerService } from './mailer.service';
|
||||
import { Users } from '../../../db/entities/Users.entity';
|
||||
import { Settings } from '../../../db/entities/Settings.entity';
|
||||
import { AppSettings } from '../../../db/entities/AppSettings.entity';
|
||||
|
||||
/**
|
||||
* Outgoing SMTP. A leaf module on purpose: AuthModule imports it for the
|
||||
@@ -7,8 +11,17 @@ import { MailerService } from './mailer.service';
|
||||
* channel. Since NotificationsModule already imports AuthModule (the demo gate
|
||||
* in NotificationsMcp), the mailer living in the notifications domain would
|
||||
* close a hard cycle — this module is what keeps it a DAG without a forwardRef.
|
||||
*
|
||||
* `MikroOrmModule.forFeature([Users, Settings, AppSettings])` (Plan 3f Task
|
||||
* 4) registers `UsersRepository`/`SettingsRepository`/`AppSettingsRepository`
|
||||
* for `MailerService`'s `@InjectRepository`-free constructor-injected
|
||||
* repositories — this module is the ONLY place `MailerService` is a
|
||||
* provider (`AuthModule`/`NotificationsModule` both just import this module
|
||||
* and reuse the exported singleton), so no other module needs the
|
||||
* registration.
|
||||
*/
|
||||
@Module({
|
||||
imports: [MikroOrmModule.forFeature([Users, Settings, AppSettings])],
|
||||
providers: [MailerService],
|
||||
exports: [MailerService],
|
||||
})
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import nodemailer from 'nodemailer';
|
||||
import { PASSWORD_RESET_I18N } from '@trek/shared/i18n/externalNotifications';
|
||||
import { readEnv } from '../../../app-config';
|
||||
import { logError, logInfo, logDebug, logWarn } from '../../audit/audit-log.logger';
|
||||
import { decrypt_api_key } from '../../common/crypto/apiKeyCrypto';
|
||||
import { DatabaseService } from '../../database/database.service';
|
||||
import { AppSettingsRepository } from '../../../db/repositories/AppSettings.repository';
|
||||
import { SettingsRepository } from '../../../db/repositories/Settings.repository';
|
||||
import { UsersRepository } from '../../../db/repositories/Users.repository';
|
||||
import { AppSettings } from '../../../db/entities/AppSettings.entity';
|
||||
import { Settings } from '../../../db/entities/Settings.entity';
|
||||
import { Users } from '../../../db/entities/Users.entity';
|
||||
import { buildEmailHtml, buildPasswordResetHtml } from './email-html';
|
||||
import { describeSmtpFailure, describeSmtpGap, parseSmtpPort, type SmtpTarget } from './smtp-diagnostics';
|
||||
|
||||
@@ -54,21 +60,21 @@ const TEST_SOCKET_TIMEOUT_MS = 30_000;
|
||||
export class MailerService {
|
||||
private skippedTlsWarned = false;
|
||||
|
||||
constructor(private readonly db: DatabaseService) {}
|
||||
|
||||
private async getAppSetting(key: string): Promise<string | null> {
|
||||
return this.db.get<{ value: string }>('SELECT value FROM app_settings WHERE key = ?', key)?.value || null;
|
||||
}
|
||||
constructor(
|
||||
@InjectRepository(Users) private readonly users: UsersRepository,
|
||||
@InjectRepository(Settings) private readonly settings: SettingsRepository,
|
||||
@InjectRepository(AppSettings) private readonly appSettings: AppSettingsRepository,
|
||||
) {}
|
||||
|
||||
/** Env wins over the admin panel, per field. Read fresh on every send. */
|
||||
private async readSmtpSettings() {
|
||||
const smtpEnv = readEnv().smtp;
|
||||
return {
|
||||
host: smtpEnv.host || (await this.getAppSetting('smtp_host')),
|
||||
port: smtpEnv.port || (await this.getAppSetting('smtp_port')),
|
||||
user: smtpEnv.user || (await this.getAppSetting('smtp_user')),
|
||||
pass: smtpEnv.pass || decrypt_api_key(await this.getAppSetting('smtp_pass')) || '',
|
||||
from: smtpEnv.from || (await this.getAppSetting('smtp_from')),
|
||||
host: smtpEnv.host || (await this.appSettings.getValue('smtp_host')),
|
||||
port: smtpEnv.port || (await this.appSettings.getValue('smtp_port')),
|
||||
user: smtpEnv.user || (await this.appSettings.getValue('smtp_user')),
|
||||
pass: smtpEnv.pass || decrypt_api_key(await this.appSettings.getValue('smtp_pass')) || '',
|
||||
from: smtpEnv.from || (await this.appSettings.getValue('smtp_from')),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -96,7 +102,7 @@ export class MailerService {
|
||||
* one method is the only change, and it keeps the freshness property visible.
|
||||
*/
|
||||
private async createTransport(config: SmtpConfig, socketTimeoutMs: number = SOCKET_TIMEOUT_MS) {
|
||||
const skipTls = readEnv().smtp.skipTlsVerify || (await this.getAppSetting('smtp_skip_tls_verify')) === 'true';
|
||||
const skipTls = readEnv().smtp.skipTlsVerify || (await this.appSettings.getValue('smtp_skip_tls_verify')) === 'true';
|
||||
if (skipTls) this.warnOnceAboutSkippedTls(config);
|
||||
return nodemailer.createTransport({
|
||||
host: config.host,
|
||||
@@ -131,20 +137,17 @@ export class MailerService {
|
||||
|
||||
/** Is SMTP configured at the instance level? (Independent of any one user's address.) */
|
||||
async isSmtpConfigured(): Promise<boolean> {
|
||||
return !!(readEnv().smtp.host || (await this.getAppSetting('smtp_host')));
|
||||
return !!(readEnv().smtp.host || (await this.appSettings.getValue('smtp_host')));
|
||||
}
|
||||
|
||||
async getUserEmail(userId: number): Promise<string | null> {
|
||||
// Defense-in-depth (#1362): a guest's synthetic email must never be emailed.
|
||||
return this.db.get<{ email: string }>(
|
||||
'SELECT email FROM users WHERE id = ? AND COALESCE(is_guest, 0) = 0', userId,
|
||||
)?.email || null;
|
||||
return await this.users.getEmailNonGuest(userId);
|
||||
}
|
||||
|
||||
async getUserLanguage(userId: number): Promise<string> {
|
||||
return this.db.get<{ value: string }>(
|
||||
"SELECT value FROM settings WHERE user_id = ? AND key = 'language'", userId,
|
||||
)?.value || 'en';
|
||||
const row = await this.settings.getOne(userId, 'language');
|
||||
return row?.value || 'en';
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -15,6 +15,9 @@ import { StorageModule } from '../storage/storage.module';
|
||||
import { Notifications } from '../../db/entities/Notifications.entity';
|
||||
import { NotificationChannelPreferences } from '../../db/entities/NotificationChannelPreferences.entity';
|
||||
import { AppSettings } from '../../db/entities/AppSettings.entity';
|
||||
import { Settings } from '../../db/entities/Settings.entity';
|
||||
import { Trips } from '../../db/entities/Trips.entity';
|
||||
import { TodoItems } from '../../db/entities/TodoItems.entity';
|
||||
|
||||
/** Notifications domain (L6 leaf module). Registered in AppModule.
|
||||
* AuthModule feeds NotificationsMcp's demo gate; MailerModule carries SMTP,
|
||||
@@ -27,15 +30,26 @@ import { AppSettings } from '../../db/entities/AppSettings.entity';
|
||||
* in-container consumers (AdminController's dev test send and preferences tab,
|
||||
* the plugin RPC surface, HostSurfaceRpc).
|
||||
* MikroOrmModule.forFeature([Notifications, NotificationChannelPreferences,
|
||||
* AppSettings]) (Plan 3f Task 3) registers NotificationsRepository/
|
||||
* AppSettings, Settings, Trips, TodoItems]) (Plan 3f Task 3, extended by
|
||||
* Task 4) registers NotificationsRepository/
|
||||
* NotificationChannelPreferencesRepository/AppSettingsRepository for
|
||||
* NotificationsService/NotificationPreferencesService's @InjectRepository
|
||||
* constructor params — the TodoModule/PermissionsModule precedent. Only
|
||||
* this module needs the registration: NotificationsService/
|
||||
* NotificationPreferencesService are providers here alone, every other
|
||||
* module injects the exported singleton rather than declaring its own. */
|
||||
* constructor params, plus SettingsRepository (NtfyService/WebhookService)
|
||||
* and TripsRepository/TodoItemsRepository (ReminderJobsService) — the
|
||||
* TodoModule/PermissionsModule precedent. Only this module needs the
|
||||
* registration: WebhookService/NtfyService/ReminderJobsService/
|
||||
* NotificationsService/NotificationPreferencesService are providers here
|
||||
* alone, every other module injects the exported singleton (or, for
|
||||
* MailerService, goes through MailerModule's own forFeature) rather than
|
||||
* declaring its own. */
|
||||
@Module({
|
||||
imports: [MikroOrmModule.forFeature([Notifications, NotificationChannelPreferences, AppSettings]), AuthModule, MailerModule, SchedulingModule, StorageModule],
|
||||
imports: [
|
||||
MikroOrmModule.forFeature([Notifications, NotificationChannelPreferences, AppSettings, Settings, Trips, TodoItems]),
|
||||
AuthModule,
|
||||
MailerModule,
|
||||
SchedulingModule,
|
||||
StorageModule,
|
||||
],
|
||||
controllers: [NotificationsController, AdminNotificationPreferencesController],
|
||||
providers: [
|
||||
NotificationsService,
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { logInfo, logError } from '../audit/audit-log.logger';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { AppSettingsRepository } from '../../db/repositories/AppSettings.repository';
|
||||
import { TripsRepository } from '../../db/repositories/Trips.repository';
|
||||
import { TodoItemsRepository } from '../../db/repositories/TodoItems.repository';
|
||||
import { AppSettings } from '../../db/entities/AppSettings.entity';
|
||||
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';
|
||||
|
||||
@@ -11,6 +17,14 @@ import { CronRegistrarService } from '../scheduling/cron-registrar.service';
|
||||
* app-tz and read their enable gate from app_settings per tick, so toggling
|
||||
* notify_trip_reminder / notify_todo_due takes effect at the next run without
|
||||
* a restart.
|
||||
*
|
||||
* Plan 3f Task 4: converted off raw SQL onto `AppSettingsRepository` (the
|
||||
* shared `getValue(key)` — RJ1, one of six identical `app_settings` reads
|
||||
* across this plan, per R4/the inventory's own duplication note — never a
|
||||
* bespoke local wrapper), `TripsRepository` (RJ2/RJ3) and `TodoItemsRepository`
|
||||
* (RJ4/RJ5). RJ3/RJ4's column-concatenated `date()` modifiers restructure to
|
||||
* plain JS date arithmetic per Task 0's verified R9 shape (`Date.UTC`-based,
|
||||
* matching SQLite's own UTC `date('now')`).
|
||||
*/
|
||||
|
||||
// Each todo is reminded at most once per ~24 h (tracked via
|
||||
@@ -21,15 +35,13 @@ const TODO_REMINDER_LEAD_DAYS = 3;
|
||||
@Injectable()
|
||||
export class ReminderJobsService implements OnApplicationBootstrap {
|
||||
constructor(
|
||||
private readonly db: DatabaseService,
|
||||
@InjectRepository(AppSettings) private readonly appSettings: AppSettingsRepository,
|
||||
@InjectRepository(Trips) private readonly trips: TripsRepository,
|
||||
@InjectRepository(TodoItems) private readonly todoItems: TodoItemsRepository,
|
||||
private readonly notifications: NotificationsService,
|
||||
private readonly registrar: CronRegistrarService,
|
||||
) {}
|
||||
|
||||
private async getSetting(key: string): Promise<string | undefined> {
|
||||
return this.db.get<{ value: string }>('SELECT value FROM app_settings WHERE key = ?', key)?.value;
|
||||
}
|
||||
|
||||
async onApplicationBootstrap(): Promise<void> {
|
||||
if (!this.registrar.isEnabled()) return;
|
||||
|
||||
@@ -39,17 +51,17 @@ export class ReminderJobsService implements OnApplicationBootstrap {
|
||||
// safe if this dependency graph goes repository-backed later).
|
||||
await this.registrar.runOnBoot('reminder-jobs-boot', async () => {
|
||||
try {
|
||||
const reminderEnabled = (await this.getSetting('notify_trip_reminder')) !== 'false';
|
||||
const channelsRaw = (await this.getSetting('notification_channels')) || (await this.getSetting('notification_channel')) || 'none';
|
||||
const reminderEnabled = (await this.appSettings.getValue('notify_trip_reminder')) !== 'false';
|
||||
const channelsRaw = (await this.appSettings.getValue('notification_channels')) || (await this.appSettings.getValue('notification_channel')) || 'none';
|
||||
const activeChannels = channelsRaw === 'none' ? [] : channelsRaw.split(',').map(c => c.trim());
|
||||
if (!reminderEnabled) {
|
||||
logInfo('Trip reminders: disabled in settings');
|
||||
} else {
|
||||
const tripCount = this.db.get<{ c: number }>('SELECT COUNT(*) as c FROM trips WHERE reminder_days > 0 AND start_date IS NOT NULL')?.c ?? 0;
|
||||
const tripCount = await this.trips.countActiveWithReminders();
|
||||
logInfo(`Trip reminders: enabled via [${activeChannels.join(',')}]${tripCount > 0 ? `, ${tripCount} trip(s) with active reminders` : ''}`);
|
||||
}
|
||||
|
||||
if ((await this.getSetting('notify_todo_due')) !== 'false') {
|
||||
if ((await this.appSettings.getValue('notify_todo_due')) !== 'false') {
|
||||
logInfo(`Todo due reminders: enabled (lead ${TODO_REMINDER_LEAD_DAYS}d)`);
|
||||
} else {
|
||||
logInfo('Todo due reminders: disabled in settings');
|
||||
@@ -66,14 +78,22 @@ export class ReminderJobsService implements OnApplicationBootstrap {
|
||||
/** Daily check for trips starting exactly reminder_days from now. */
|
||||
async tripTick(): Promise<void> {
|
||||
try {
|
||||
if ((await this.getSetting('notify_trip_reminder')) === 'false') return;
|
||||
if ((await this.appSettings.getValue('notify_trip_reminder')) === 'false') return;
|
||||
|
||||
const trips = this.db.all<{ id: number; title: string; user_id: number; reminder_days: number }>(`
|
||||
SELECT t.id, t.title, t.user_id, t.reminder_days FROM trips t
|
||||
WHERE t.reminder_days > 0
|
||||
AND t.start_date IS NOT NULL
|
||||
AND t.start_date = date('now', '+' || t.reminder_days || ' days')
|
||||
`);
|
||||
// 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 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);
|
||||
});
|
||||
|
||||
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(() => {});
|
||||
@@ -90,26 +110,22 @@ export class ReminderJobsService implements OnApplicationBootstrap {
|
||||
/** Daily check for unchecked todos due inside the lead window. */
|
||||
async todoTick(): Promise<void> {
|
||||
try {
|
||||
if ((await this.getSetting('notify_todo_due')) === 'false') return;
|
||||
if ((await this.appSettings.getValue('notify_todo_due')) === 'false') return;
|
||||
|
||||
// Select unchecked todos with a due date inside the lead window
|
||||
// that haven't been reminded in the last 24 hours. `due_date` is
|
||||
// stored as a YYYY-MM-DD text; SQLite date() handles it directly.
|
||||
const todos = this.db.all<{
|
||||
id: number; trip_id: number; name: string; due_date: string;
|
||||
assigned_user_id: number | null; trip_title: string; trip_owner_id: number;
|
||||
}>(`
|
||||
SELECT ti.id, ti.trip_id, ti.name, ti.due_date, ti.assigned_user_id,
|
||||
t.title AS trip_title, t.user_id AS trip_owner_id
|
||||
FROM todo_items ti
|
||||
JOIN trips t ON t.id = ti.trip_id
|
||||
WHERE ti.checked = 0
|
||||
AND ti.due_date IS NOT NULL
|
||||
AND ti.due_date <> ''
|
||||
AND date(ti.due_date) <= date('now', '+' || ? || ' days')
|
||||
AND date(ti.due_date) >= date('now')
|
||||
AND (ti.reminded_at IS NULL OR ti.reminded_at <= datetime('now', '-20 hours'))
|
||||
`, TODO_REMINDER_LEAD_DAYS);
|
||||
// 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);
|
||||
|
||||
const todos = await this.todoItems.listDueForReminder(todayDate, cutoffDate);
|
||||
|
||||
for (const todo of todos) {
|
||||
const targetScope: 'user' | 'trip' = todo.assigned_user_id ? 'user' : 'trip';
|
||||
@@ -126,7 +142,8 @@ export class ReminderJobsService implements OnApplicationBootstrap {
|
||||
due: todo.due_date,
|
||||
},
|
||||
}).catch(() => {});
|
||||
this.db.run('UPDATE todo_items SET reminded_at = CURRENT_TIMESTAMP WHERE id = ?', todo.id);
|
||||
// RJ5 stays AFTER the send, unchanged (plan3f-inputs.md correction #8).
|
||||
await this.todoItems.markReminded(todo.id);
|
||||
}
|
||||
|
||||
if (todos.length > 0) {
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';
|
||||
import { Injectable, Logger, OnApplicationBootstrap, Optional } from '@nestjs/common';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { withRequestContext } from '../database/request-context';
|
||||
import { StorageEventsService } from '../storage/storage-events.service';
|
||||
import { NotificationsService } from './notifications.service';
|
||||
import { ReplicaFailureDebouncer } from './replica-failure-debouncer';
|
||||
@@ -10,6 +12,22 @@ const DEBOUNCE_WINDOW_MS = 60 * 60 * 1000;
|
||||
* Lives HERE (not in StorageModule) because NotificationsModule → AuthModule
|
||||
* → StorageModule — the reverse import would cycle. Subscribes at bootstrap;
|
||||
* the debouncer keeps an outage from becoming a notification storm.
|
||||
*
|
||||
* Plan 3f Task 4 (R3): Task 0's emitter trace found one ambiguous path — the
|
||||
* "Sync now" backfill sweep (`StorageJobsService.startBackfill`) detaches
|
||||
* from its originating admin request (`void driver.backfill(...)`,
|
||||
* fire-and-forget), so a failure it reports could reach this listener long
|
||||
* after that request's own EntityManager fork was meant to be done with. No
|
||||
* emitter was found with NO context at all, but wrapping here is cheap
|
||||
* insurance regardless (Task 0's own recommendation): the listener now forks
|
||||
* its OWN fresh request context on every invocation — the same
|
||||
* `withRequestContext` shape `CronRegistrarService.register`'s wrapped tick
|
||||
* uses — independent of whatever context (if any) was active at the call
|
||||
* site that triggered the failure. `orm` is `@Optional()` (matching
|
||||
* `CronRegistrarService`'s own reasoning): a hand-built test double that
|
||||
* constructs this service directly, with no MikroORM, still gets the exact
|
||||
* pre-Task-4 behavior (send called without a context wrapper) rather than
|
||||
* failing to compile or throwing.
|
||||
*/
|
||||
@Injectable()
|
||||
export class StorageHealthNotifierService implements OnApplicationBootstrap {
|
||||
@@ -19,31 +37,38 @@ export class StorageHealthNotifierService implements OnApplicationBootstrap {
|
||||
constructor(
|
||||
private readonly events: StorageEventsService,
|
||||
private readonly notifications: NotificationsService,
|
||||
@Optional() private readonly orm?: MikroORM,
|
||||
) {}
|
||||
|
||||
onApplicationBootstrap(): void {
|
||||
this.events.onReplicaFailure((failure) => {
|
||||
const suppressed = this.debouncer.admit(failure.backend);
|
||||
if (suppressed === null) return;
|
||||
void this.notifications
|
||||
.send({
|
||||
event: 'replica_failure',
|
||||
actorId: null,
|
||||
scope: 'admin',
|
||||
targetId: 0,
|
||||
params: {
|
||||
backend: failure.backend,
|
||||
key: failure.key,
|
||||
op: failure.op,
|
||||
error: failure.error,
|
||||
suppressed: String(suppressed),
|
||||
},
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
this.logger.error(
|
||||
`replica_failure notification failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
});
|
||||
const sendNotification = () =>
|
||||
this.notifications
|
||||
.send({
|
||||
event: 'replica_failure',
|
||||
actorId: null,
|
||||
scope: 'admin',
|
||||
targetId: 0,
|
||||
params: {
|
||||
backend: failure.backend,
|
||||
key: failure.key,
|
||||
op: failure.op,
|
||||
error: failure.error,
|
||||
suppressed: String(suppressed),
|
||||
},
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
this.logger.error(
|
||||
`replica_failure notification failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||
);
|
||||
});
|
||||
if (this.orm) {
|
||||
void withRequestContext(this.orm, sendNotification);
|
||||
} else {
|
||||
void sendNotification();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { logDebug, logError, logInfo } from '../../audit/audit-log.logger';
|
||||
import { decrypt_api_key } from '../../common/crypto/apiKeyCrypto';
|
||||
import { DatabaseService } from '../../database/database.service';
|
||||
import { AppSettingsRepository } from '../../../db/repositories/AppSettings.repository';
|
||||
import { SettingsRepository } from '../../../db/repositories/Settings.repository';
|
||||
import { AppSettings } from '../../../db/entities/AppSettings.entity';
|
||||
import { Settings } from '../../../db/entities/Settings.entity';
|
||||
import { safeFetchFollow, SsrfBlockedError } from '../../../utils/ssrfGuard';
|
||||
import type { NotifEventType } from '../notification-events';
|
||||
|
||||
/** NS2's three per-user ntfy keys, read together off `SettingsRepository.getForUser`. */
|
||||
const NTFY_USER_KEYS = new Set(['ntfy_topic', 'ntfy_server', 'ntfy_token']);
|
||||
|
||||
export interface NtfyConfig {
|
||||
server: string | null;
|
||||
topic: string | null;
|
||||
@@ -107,19 +114,24 @@ function encodeHeaderValue(value: string): string {
|
||||
/** ntfy push: the per-user and admin topic config, and the header-based POST. */
|
||||
@Injectable()
|
||||
export class NtfyService {
|
||||
constructor(private readonly db: DatabaseService) {}
|
||||
|
||||
private async getAppSetting(key: string): Promise<string | null> {
|
||||
return this.db.get<{ value: string }>('SELECT value FROM app_settings WHERE key = ?', key)?.value || null;
|
||||
}
|
||||
constructor(
|
||||
@InjectRepository(Settings) private readonly settings: SettingsRepository,
|
||||
@InjectRepository(AppSettings) private readonly appSettings: AppSettingsRepository,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* NS2. R4's fold ruling: `getForUser` (the existing, shared
|
||||
* `SettingsRepository`'s method) followed by a JS filter to the three
|
||||
* `ntfy_*` keys — no new batch method on the repository. `rows.length ===
|
||||
* 0` gates on the FILTERED (ntfy_*) row count, matching the legacy `IN
|
||||
* (...)`-scoped statement's own `rows.length === 0` check exactly (a row
|
||||
* present with a NULL value still counts as present — only its absence
|
||||
* from the settings table returns null here).
|
||||
*/
|
||||
async getUserNtfyConfig(userId: number): Promise<NtfyConfig | null> {
|
||||
const rows = this.db.all<{ key: string; value: string }>(
|
||||
"SELECT key, value FROM settings WHERE user_id = ? AND key IN ('ntfy_topic', 'ntfy_server', 'ntfy_token')",
|
||||
userId,
|
||||
);
|
||||
const rows = (await this.settings.getForUser(userId)).filter((r) => NTFY_USER_KEYS.has(r.key));
|
||||
if (rows.length === 0) return null;
|
||||
const map: Record<string, string> = {};
|
||||
const map: Record<string, string | null> = {};
|
||||
for (const r of rows) map[r.key] = r.value;
|
||||
return {
|
||||
topic: map['ntfy_topic'] || null,
|
||||
@@ -128,10 +140,11 @@ export class NtfyService {
|
||||
};
|
||||
}
|
||||
|
||||
/** NS1 — three of the plan's six identical `app_settings` reads, R4's shared `AppSettingsRepository.getValue(key)`. */
|
||||
async getAdminNtfyConfig(): Promise<NtfyConfig> {
|
||||
const topic = (await this.getAppSetting('admin_ntfy_topic')) || null;
|
||||
const server = (await this.getAppSetting('admin_ntfy_server')) || null;
|
||||
const rawToken = (await this.getAppSetting('admin_ntfy_token')) || null;
|
||||
const topic = (await this.appSettings.getValue('admin_ntfy_topic')) || null;
|
||||
const server = (await this.appSettings.getValue('admin_ntfy_server')) || null;
|
||||
const rawToken = (await this.appSettings.getValue('admin_ntfy_token')) || null;
|
||||
return {
|
||||
topic,
|
||||
server,
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { logDebug, logError, logInfo } from '../../audit/audit-log.logger';
|
||||
import { decrypt_api_key } from '../../common/crypto/apiKeyCrypto';
|
||||
import { DatabaseService } from '../../database/database.service';
|
||||
import { AppSettingsRepository } from '../../../db/repositories/AppSettings.repository';
|
||||
import { SettingsRepository } from '../../../db/repositories/Settings.repository';
|
||||
import { AppSettings } from '../../../db/entities/AppSettings.entity';
|
||||
import { Settings } from '../../../db/entities/Settings.entity';
|
||||
import { safeFetchFollow, SsrfBlockedError } from '../../../utils/ssrfGuard';
|
||||
|
||||
/**
|
||||
@@ -44,19 +48,21 @@ export function buildWebhookBody(
|
||||
/** Outgoing webhooks: the per-user and the admin-global URL, and the POST itself. */
|
||||
@Injectable()
|
||||
export class WebhookService {
|
||||
constructor(private readonly db: DatabaseService) {}
|
||||
constructor(
|
||||
@InjectRepository(Settings) private readonly settings: SettingsRepository,
|
||||
@InjectRepository(AppSettings) private readonly appSettings: AppSettingsRepository,
|
||||
) {}
|
||||
|
||||
/** WH1 — R4's fold ruling: the shared, already-populated `SettingsRepository.getOne(userId, key)`. */
|
||||
async getUserWebhookUrl(userId: number): Promise<string | null> {
|
||||
const value = this.db.get<{ value: string }>(
|
||||
"SELECT value FROM settings WHERE user_id = ? AND key = 'webhook_url'", userId,
|
||||
)?.value || null;
|
||||
const row = await this.settings.getOne(userId, 'webhook_url');
|
||||
const value = row?.value || null;
|
||||
return value ? decrypt_api_key(value) : null;
|
||||
}
|
||||
|
||||
/** WH2 — one of the plan's six identical `app_settings` reads, R4's shared `AppSettingsRepository.getValue(key)`. */
|
||||
async getAdminWebhookUrl(): Promise<string | null> {
|
||||
const value = this.db.get<{ value: string }>(
|
||||
'SELECT value FROM app_settings WHERE key = ?', 'admin_webhook_url',
|
||||
)?.value || null;
|
||||
const value = (await this.appSettings.getValue('admin_webhook_url')) || null;
|
||||
return value ? decrypt_api_key(value) : null;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user