Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

39.3 KB
Raw Blame
import { readEnv, getAppUrl } from '../../app-config';
import { Notifications } from '../../db/entities/Notifications.entity';
import type { NotificationJoinRow, NotificationsRepository } from '../../db/repositories/Notifications.repository';
import { logDebug, logError } from '../audit/audit-log.logger';
import { avatarUrl } from '../common/avatarUrl';
import { UnitOfWork } from '../database/unit-of-work';
import { RealtimeService } from '../realtime/realtime.service';
import { shouldSendToUser } from './channel-gate';
import { getChannel, listChannels } from './channel-registry';
import { registerBuiltinChannels } from './channels/builtins';
import { getAction, registerAction } from './in-app-actions';
import { InFlightSends } from './in-flight-sends';
import { getEventText } from './mailer/email-html';
import { MailerService } from './mailer/mailer.service';
import {
  isAdminGlobalChannel,
  type ChannelMessage,
  type ExternalChannel,
  type NotifEventType,
} from './notification-events';
import { NotificationPreferencesService, type PreferencesMatrix } from './notification-preferences.service';
import { NtfyService, type NtfyConfig } from './transports/ntfy.service';
import { WebPushService } from './transports/web-push.service';
import { WebhookService } from './transports/webhook.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import type { ChannelTestResult } from '@trek/shared';

// SQLite's CURRENT_TIMESTAMP is UTC but the string ('YYYY-MM-DD HH:MM:SS') has
// no 'T'/'Z', so `new Date(...)` parses it as LOCAL time. Normalize to ISO-UTC
// so the client renders notification times in the viewer's own timezone (#1149).
function toUtcIso(ts: string): string {
  return ts.endsWith('Z') ? ts : ts.replace(' ', 'T') + 'Z';
}

type NotificationType = 'simple' | 'boolean' | 'navigate';
type NotificationScope = 'trip' | 'user' | 'admin';
type NotificationResponse = 'positive' | 'negative';

interface BaseNotificationInput {
  type: NotificationType;
  scope: NotificationScope;
  target: number;
  sender_id: number | null;
  event_type?: NotifEventType;
  title_key: string;
  title_params?: Record<string, string>;
  text_key: string;
  text_params?: Record<string, string>;
}

interface SimpleNotificationInput extends BaseNotificationInput {
  type: 'simple';
}

interface BooleanNotificationInput extends BaseNotificationInput {
  type: 'boolean';
  positive_text_key: string;
  negative_text_key: string;
  positive_callback: { action: string; payload: Record<string, unknown> };
  negative_callback: { action: string; payload: Record<string, unknown> };
}

interface NavigateNotificationInput extends BaseNotificationInput {
  type: 'navigate';
  navigate_text_key: string;
  navigate_target: string;
}

type NotificationInput = SimpleNotificationInput | BooleanNotificationInput | NavigateNotificationInput;

interface NotificationRow {
  id: number;
  type: NotificationType;
  scope: NotificationScope;
  target: number;
  sender_id: number | null;
  sender_username?: string | null;
  sender_avatar?: string | null;
  recipient_id: number;
  title_key: string;
  title_params: string | null;
  text_key: string;
  text_params: string | null;
  positive_text_key: string | null;
  negative_text_key: string | null;
  positive_callback: string | null;
  negative_callback: string | null;
  response: NotificationResponse | null;
  navigate_text_key: string | null;
  navigate_target: string | null;
  is_read: number | null;
  created_at: string;
}

type RespondResult = { success: boolean; error?: string; notification?: NotificationRow };

/**
 * A stored notification as the bell reads it: the time as ISO UTC, the sender's
 * avatar as a URL. The repository row's `type`/`scope`/`response` are plain
 * TEXT; narrowing them to the unions above is the same unchecked boundary the
 * legacy `db.all<NotificationRow>(...)` generic drew.
 */
function withSender(row: NotificationJoinRow): NotificationRow {
  return {
    ...row,
    created_at: toUtcIso(row.created_at!),
    sender_avatar: avatarUrl({ avatar: row.sender_avatar }),
  } as NotificationRow;
}

// ── Event config map ───────────────────────────────────────────────────────

interface EventNotifConfig {
  inAppType: 'simple' | 'navigate';
  titleKey: string;
  textKey: string | ((params: Record<string, string>) => string);
  navigateTextKey?: string;
  navigateTarget: (params: Record<string, string>) => string | null;
}

// WAN-02: the three texts of a wanderer hint, one per state. Each sits in a
// textKey of its own so the client's key check (scripts/i18n-keys.mjs, which
// reads *Key properties in the server) sees every one of them as in use.
const WANDERER_HINT_TEXT: Record<string, { textKey: string }> = {
  changed: { textKey: 'notif.wanderer_source_hint.changed' },
  unverifiable: { textKey: 'notif.wanderer_source_hint.unverifiable' },
  possible_change: { textKey: 'notif.wanderer_source_hint.possible_change' },
};

// The two texts of a booking added from a mail: the forwarder's and a co-traveller's,
// each in a textKey of its own for the client's key check, as above.
const MAIL_BOOKING_TEXT: Record<'forwarder' | 'traveller', { textKey: string }> = {
  forwarder: { textKey: 'notif.mail_booking_added.text' },
  traveller: { textKey: 'notif.mail_booking_added.shared' },
};

const EVENT_NOTIFICATION_CONFIG: Record<string, EventNotifConfig> = {
  // ── Dev-only test events ──────────────────────────────────────────────────
  test_simple: {
    inAppType: 'simple',
    titleKey: 'notif.test.title',
    textKey: 'notif.test.simple.text',
    navigateTarget: () => null,
  },
  test_boolean: {
    inAppType: 'simple', // overridden by inApp.type at call site
    titleKey: 'notif.test.title',
    textKey: 'notif.test.boolean.text',
    navigateTarget: () => null,
  },
  test_navigate: {
    inAppType: 'navigate',
    titleKey: 'notif.test.title',
    textKey: 'notif.test.navigate.text',
    navigateTextKey: 'notif.action.view',
    navigateTarget: () => '/dashboard',
  },
  // ── Plugin-mediated notification (#plugins) — raw title/body carried as params,
  // rendered by the passthrough keys. The plugin never picks a recipient directly;
  // the host forces scope/target to the acting user or a trip they belong to. ──────
  plugin_notification: {
    inAppType: 'navigate',
    titleKey: 'notif.plugin.title',
    textKey: 'notif.plugin.text',
    navigateTextKey: 'notif.action.view',
    navigateTarget: (p) => p.link || null,
  },
  // ── Production events ─────────────────────────────────────────────────────
  trip_invite: {
    inAppType: 'navigate',
    titleKey: 'notif.trip_invite.title',
    textKey: 'notif.trip_invite.text',
    navigateTextKey: 'notif.action.view_trip',
    navigateTarget: (p) => (p.tripId ? `/trips/${p.tripId}` : null),
  },
  booking_change: {
    inAppType: 'navigate',
    titleKey: 'notif.booking_change.title',
    textKey: 'notif.booking_change.text',
    navigateTextKey: 'notif.action.view_trip',
    navigateTarget: (p) => (p.tripId ? `/trips/${p.tripId}` : null),
  },
  // Live flight status (flight-live): the poll saw the flight leave, land or run late.
  flight_departed: {
    inAppType: 'navigate',
    titleKey: 'notif.flight_departed.title',
    textKey: 'notif.flight_departed.text',
    navigateTextKey: 'notif.action.view_trip',
    navigateTarget: (p) => (p.tripId ? `/trips/${p.tripId}` : null),
  },
  flight_delayed: {
    inAppType: 'navigate',
    titleKey: 'notif.flight_delayed.title',
    textKey: 'notif.flight_delayed.text',
    navigateTextKey: 'notif.action.view_trip',
    navigateTarget: (p) => (p.tripId ? `/trips/${p.tripId}` : null),
  },
  flight_landed: {
    inAppType: 'navigate',
    titleKey: 'notif.flight_landed.title',
    textKey: 'notif.flight_landed.text',
    navigateTextKey: 'notif.action.view_trip',
    navigateTarget: (p) => (p.tripId ? `/trips/${p.tripId}` : null),
  },
  trip_reminder: {
    inAppType: 'navigate',
    titleKey: 'notif.trip_reminder.title',
    textKey: 'notif.trip_reminder.text',
    navigateTextKey: 'notif.action.view_trip',
    navigateTarget: (p) => (p.tripId ? `/trips/${p.tripId}` : null),
  },
  todo_due: {
    inAppType: 'navigate',
    titleKey: 'notif.todo_due.title',
    textKey: 'notif.todo_due.text',
    navigateTextKey: 'notif.action.view_trip',
    navigateTarget: (p) => (p.tripId ? `/trips/${p.tripId}` : null),
  },
  vacay_invite: {
    inAppType: 'navigate',
    titleKey: 'notif.vacay_invite.title',
    textKey: 'notif.vacay_invite.text',
    navigateTextKey: 'notif.action.view_vacay',
    navigateTarget: () => '/vacay',
  },
  vacay_share: {
    inAppType: 'navigate',
    titleKey: 'notif.vacay_share.title',
    textKey: 'notif.vacay_share.text',
    navigateTextKey: 'notif.action.view_vacay',
    navigateTarget: () => '/vacay',
  },
  collection_invite: {
    inAppType: 'navigate',
    titleKey: 'notif.collection_invite.title',
    textKey: 'notif.collection_invite.text',
    navigateTextKey: 'notif.action.view_collection',
    navigateTarget: (p) => (p.collectionId ? `/collections/${p.collectionId}` : '/collections'),
  },
  photos_shared: {
    inAppType: 'navigate',
    titleKey: 'notif.photos_shared.title',
    textKey: 'notif.photos_shared.text',
    navigateTextKey: 'notif.action.view_trip',
    navigateTarget: (p) => (p.tripId ? `/trips/${p.tripId}` : null),
  },
  collab_message: {
    inAppType: 'navigate',
    titleKey: 'notif.collab_message.title',
    textKey: 'notif.collab_message.text',
    navigateTextKey: 'notif.action.view_collab',
    navigateTarget: (p) => (p.tripId ? `/trips/${p.tripId}?tab=collab` : '/dashboard'),
  },
  packing_tagged: {
    inAppType: 'navigate',
    titleKey: 'notif.packing_tagged.title',
    textKey: 'notif.packing_tagged.text',
    navigateTextKey: 'notif.action.view_packing',
    navigateTarget: (p) => (p.tripId ? `/trips/${p.tripId}` : null),
  },
  version_available: {
    inAppType: 'navigate',
    titleKey: 'notif.version_available.title',
    textKey: 'notif.version_available.text',
    navigateTextKey: 'notif.action.view_admin',
    navigateTarget: () => '/admin',
  },
  replica_failure: {
    inAppType: 'navigate',
    titleKey: 'notif.replica_failure.title',
    textKey: (p) =>
      p.suppressed && p.suppressed !== '0' ? 'notif.replica_failure.textSuppressed' : 'notif.replica_failure.text',
    navigateTextKey: 'notif.action.view',
    navigateTarget: () => '/admin?tab=storage',
  },
  paddle_region_requested: {
    inAppType: 'navigate',
    titleKey: 'notif.paddle_region_requested.title',
    textKey: 'notif.paddle_region_requested.text',
    navigateTextKey: 'notif.action.view_admin',
    navigateTarget: () => '/admin?tab=addons',
  },
  // WAN-02: the wanderer watch found something about a snapshot's source; the
  // text says which of the three it is, the button opens the tour in its trip.
  wanderer_source_hint: {
    inAppType: 'navigate',
    titleKey: 'notif.wanderer_source_hint.title',
    textKey: (p) => (WANDERER_HINT_TEXT[p.state] ?? WANDERER_HINT_TEXT.possible_change).textKey,
    navigateTextKey: 'notif.action.view_tour',
    navigateTarget: (p) => (p.tripId && p.placeId ? `/trips/${p.tripId}?tab=plan&place=${p.placeId}` : null),
  },
  // A booking from a forwarded mail went into a trip. The forwarder's copy is a
  // keep/undo question (the call site makes it boolean); a co-traveller's opens the trip.
  mail_booking_added: {
    inAppType: 'navigate',
    titleKey: 'notif.mail_booking_added.title',
    textKey: (p) => (p.role === 'traveller' ? MAIL_BOOKING_TEXT.traveller : MAIL_BOOKING_TEXT.forwarder).textKey,
    navigateTextKey: 'notif.action.view_trip',
    navigateTarget: (p) => (p.tripId ? `/trips/${p.tripId}?tab=buchungen` : null),
  },
  // Bookings from forwarded mails wait in the person's inbox for a decision.
  mail_booking_pending: {
    inAppType: 'navigate',
    titleKey: 'notif.mail_booking_pending.title',
    textKey: 'notif.mail_booking_pending.text',
    navigateTextKey: 'notif.action.review',
    navigateTarget: () => '/dashboard?inbox=mail',
  },
  // The import stopped (a plan without it, or an admin switched it off): every
  // person with an address hears it once, with nothing to open.
  mail_ingest_paused: {
    inAppType: 'simple',
    titleKey: 'notif.mail_ingest_paused.title',
    textKey: 'notif.mail_ingest_paused.text',
    navigateTarget: () => null,
  },
  synology_session_cleared: {
    inAppType: 'simple',
    titleKey: 'notifications.synologySessionCleared.title',
    textKey: 'notifications.synologySessionCleared.text',
    navigateTarget: () => null,
  },
};

// ── Fallback config for unknown event types ────────────────────────────────

const FALLBACK_EVENT_CONFIG: EventNotifConfig = {
  inAppType: 'simple',
  titleKey: 'notif.generic.title',
  textKey: 'notif.generic.text',
  navigateTarget: () => null,
};

// ── Unified send() API ─────────────────────────────────────────────────────

export interface NotificationPayload {
  event: NotifEventType;
  actorId: number | null;
  params: Record<string, string>;
  scope: 'trip' | 'user' | 'admin';
  targetId: number; // tripId for trip scope, userId for user scope, 0 for admin
  /** Optional in-app overrides (e.g. boolean type with callbacks) */
  inApp?: {
    type?: 'simple' | 'boolean' | 'navigate';
    positiveTextKey?: string;
    negativeTextKey?: string;
    positiveCallback?: { action: string; payload: Record<string, unknown> };
    negativeCallback?: { action: string; payload: Record<string, unknown> };
    navigateTarget?: string; // override the auto-generated navigate target
  };
}

/**
 * What one {@link NotificationsService.send} reached: every in-app notification
 * and channel message it tried, and how many of those went out. A channel that
 * rejects or answers `false` (SMTP down, a webhook 5xx) did not deliver.
 * `attempted` is 0 when nobody wanted the event at all.
 */
export interface NotificationDelivery {
  attempted: number;
  delivered: number;
}

/**
 * DI-native notifications domain service. The in-app notification SQL moved
 * 1:1 from the legacy `services/inAppNotifications.ts` (identical statements,
 * post-insert re-selects) and the unified `send()` dispatcher moved 1:1 from
 * `services/notificationService.ts` (identical event-config map, gating and
 * log lines). The trailing fix(server) commit then normalized the carried
 * defects: `toUtcIso` now applies on every broadcast/re-select path (#1149
 * was originally patched on only one of three), and `respond` claims the
 * response atomically BEFORE running the action handler (double-submits can
 * no longer execute the action twice; a handler failure releases the claim).
 * The channel transports and the preference matrix are injected providers
 * since the notifications fold; the channel registry stays a module singleton
 * so every separately-constructed instance (the no-Nest test harnesses — the
 * last production out-of-container consumer, notifications.instance.ts, died
 * with the bridge fold) sees the channels the plugin runtime pushes in.
 *
 * Every production consumer injects this service now: the plugin RPC host via
 * `HostSurfaceRpc`, the reminder crons via ReminderJobsService.
 */
@Injectable()
export class NotificationsService {
  private readonly inFlight = new InFlightSends();

  constructor(
    private readonly realtime: RealtimeService,
    private readonly mailer: MailerService,
    private readonly webhook: WebhookService,
    private readonly ntfy: NtfyService,
    private readonly prefs: NotificationPreferencesService,
    private readonly uow: UnitOfWork,
    @InjectRepository(Notifications) private readonly notificationsRepo: NotificationsRepository,
    push: WebPushService,
  ) {
    // The registry is a module singleton shared with the plugin runtime and any
    // separately-constructed instance (which never runs onModuleInit), so
    // registering from here means every path that can dispatch has the
    // built-ins. registerChannel is an idempotent Map.set.
    registerBuiltinChannels({ mailer, webhook, ntfy, push });
  }

  async getPreferences(userId: number, role: string): Promise<PreferencesMatrix> {
    return await this.prefs.getPreferencesMatrix(userId, role, 'user');
  }

  /** Send a test notification over any registered channel (built-in or plugin). */
  async testChannel(userId: number, channelId: string): Promise<ChannelTestResult> {
    const channel = await getChannel(channelId);
    if (!channel) return { success: false, error: 'Unknown channel' };
    if (!channel.test) return { success: false, error: 'This channel does not support test sends' };
    if (!(await channel.isConfiguredFor(userId)))
      return { success: false, error: 'Channel is not configured for this user' };
    try {
      return await channel.test(userId);
    } catch (e) {
      return { success: false, error: e instanceof Error ? e.message : 'Unknown error' };
    }
  }

  async setPreferences(
    userId: number,
    body: Parameters<NotificationPreferencesService['setPreferences']>[1],
  ): Promise<void> {
    await this.prefs.setPreferences(userId, body);
  }

  testSmtp(to: string): Promise<ChannelTestResult> {
    return this.mailer.testSmtp(to);
  }

  testWebhook(url: string): Promise<ChannelTestResult> {
    return this.webhook.testWebhook(url);
  }

  testNtfy(cfg: { topic: string; server?: string | null; token?: string | null }): Promise<ChannelTestResult> {
    return this.ntfy.testNtfy(cfg);
  }

  async userWebhookUrl(userId: number): Promise<string | null> {
    return await this.webhook.getUserWebhookUrl(userId);
  }

  async adminWebhookUrl(): Promise<string | null> {
    return await this.webhook.getAdminWebhookUrl();
  }

  async userNtfyConfig(userId: number): Promise<NtfyConfig | null> {
    return await this.ntfy.getUserNtfyConfig(userId);
  }

  async adminNtfyConfig(): Promise<NtfyConfig> {
    return await this.ntfy.getAdminNtfyConfig();
  }

  // ── In-app notification store (from services/inAppNotifications.ts) ───────

  async resolveRecipients(scope: NotificationScope, target: number, excludeUserId?: number | null): Promise<number[]> {
    let userIds: number[] = [];

    // Guests (#1362) are trip members for assignment purposes but have no inbox/email,
    // so they must never be resolved as notification recipients on any scope. This is the
    // single chokepoint for in-app/email/webhook/ntfy, so filtering here covers all channels.
    if (scope === 'trip') {
      const ownerId = await this.notificationsRepo.getTripOwnerId(target);
      const memberIds = await this.notificationsRepo.listNonGuestTripMemberIds(target);
      const ids = new Set<number>();
      if (ownerId != null) ids.add(ownerId);
      for (const id of memberIds) ids.add(id);
      userIds = Array.from(ids);
    } else if (scope === 'user') {
      // A guest can be a todo assignee (scope='user'); never notify them.
      const u = await this.notificationsRepo.findGuestFlag(target);
      userIds = u && u.is_guest ? [] : [target];
    } else if (scope === 'admin') {
      userIds = await this.notificationsRepo.listNonGuestUserIdsByRole('admin');
    }

    // Only exclude sender for group scopes (trip/admin) — for user scope, the target is explicit
    if (excludeUserId != null && scope !== 'user') {
      userIds = userIds.filter((id) => id !== excludeUserId);
    }

    return userIds;
  }

  /**
   * Legacy multi-recipient insert path (resolve + per-recipient pref check in
   * one transaction). `send()` resolves recipients itself and uses
   * `createNotificationForRecipient`; this remains for direct callers/tests.
   */
  async createNotification(input: NotificationInput): Promise<number[]> {
    const recipients = await this.resolveRecipients(input.scope, input.target, input.sender_id);
    if (recipients.length === 0) return [];

    const titleParams = JSON.stringify(input.title_params ?? {});
    const textParams = JSON.stringify(input.text_params ?? {});

    // Track inserted id → recipientId pairs (some recipients may be skipped by pref check)
    const insertedPairs: Array<{ id: number; recipientId: number }> = [];

    await this.uow.transactional(async () => {
      for (const recipientId of recipients) {
        // Check per-user in-app preference if an event_type is provided
        if (input.event_type && !(await this.prefs.isEnabledForEvent(recipientId, input.event_type, 'inapp'))) {
          continue;
        }

        let positiveTextKey: string | null = null;
        let negativeTextKey: string | null = null;
        let positiveCallback: string | null = null;
        let negativeCallback: string | null = null;
        let navigateTextKey: string | null = null;
        let navigateTarget: string | null = null;

        if (input.type === 'boolean') {
          positiveTextKey = input.positive_text_key;
          negativeTextKey = input.negative_text_key;
          positiveCallback = JSON.stringify(input.positive_callback);
          negativeCallback = JSON.stringify(input.negative_callback);
        } else if (input.type === 'navigate') {
          navigateTextKey = input.navigate_text_key;
          navigateTarget = input.navigate_target;
        }

        const id = await this.notificationsRepo.insertNotification({
          type: input.type,
          scope: input.scope,
          target: input.target,
          sender_id: input.sender_id,
          recipient_id: recipientId,
          title_key: input.title_key,
          title_params: titleParams,
          text_key: input.text_key,
          text_params: textParams,
          positive_text_key: positiveTextKey,
          negative_text_key: negativeTextKey,
          positive_callback: positiveCallback,
          negative_callback: negativeCallback,
          navigate_text_key: navigateTextKey,
          navigate_target: navigateTarget,
        });

        insertedPairs.push({ id, recipientId });
      }
    });

    // Fetch sender info once for WS payloads
    const sender = input.sender_id ? await this.notificationsRepo.findUserBasic(input.sender_id) : undefined;

    // Broadcast to each recipient
    for (const { id: notificationId, recipientId } of insertedPairs) {
      const row = await this.notificationsRepo.findById(notificationId);
      if (!row) continue;

      this.realtime.broadcastToUser(recipientId, {
        type: 'notification:new',
        notification: {
          ...row,
          created_at: toUtcIso(row.created_at!),
          sender_username: sender?.username ?? null,
          sender_avatar: avatarUrl({ avatar: sender?.avatar ?? null }),
        },
      });
    }

    return insertedPairs.map((p) => p.id);
  }

  /**
   * Insert a single in-app notification for one pre-resolved recipient and broadcast via WebSocket.
   * Used by send() which handles recipient resolution externally.
   */
  async createNotificationForRecipient(
    input: NotificationInput,
    recipientId: number,
    sender: { username: string; avatar: string | null } | null,
  ): Promise<number | null> {
    const titleParams = JSON.stringify(input.title_params ?? {});
    const textParams = JSON.stringify(input.text_params ?? {});

    let positiveTextKey: string | null = null;
    let negativeTextKey: string | null = null;
    let positiveCallback: string | null = null;
    let negativeCallback: string | null = null;
    let navigateTextKey: string | null = null;
    let navigateTarget: string | null = null;

    if (input.type === 'boolean') {
      positiveTextKey = input.positive_text_key;
      negativeTextKey = input.negative_text_key;
      positiveCallback = JSON.stringify(input.positive_callback);
      negativeCallback = JSON.stringify(input.negative_callback);
    } else if (input.type === 'navigate') {
      navigateTextKey = input.navigate_text_key;
      navigateTarget = input.navigate_target;
    }

    const notificationId = await this.notificationsRepo.insertNotification({
      type: input.type,
      scope: input.scope,
      target: input.target,
      sender_id: input.sender_id,
      recipient_id: recipientId,
      title_key: input.title_key,
      title_params: titleParams,
      text_key: input.text_key,
      text_params: textParams,
      positive_text_key: positiveTextKey,
      negative_text_key: negativeTextKey,
      positive_callback: positiveCallback,
      negative_callback: negativeCallback,
      navigate_text_key: navigateTextKey,
      navigate_target: navigateTarget,
    });

    const row = await this.notificationsRepo.findById(notificationId);
    if (!row) return null;

    this.realtime.broadcastToUser(recipientId, {
      type: 'notification:new',
      notification: {
        ...row,
        created_at: toUtcIso(row.created_at!),
        sender_username: sender?.username ?? null,
        sender_avatar: avatarUrl({ avatar: sender?.avatar ?? null }),
      },
    });

    return notificationId;
  }

  // Returns the native service shape (NotificationRow[] is a superset of the
  // client-facing InAppListResult contract); the controller surfaces it as-is.
  async listInApp(
    userId: number,
    options: { limit?: number; offset?: number; unreadOnly?: boolean } = {},
  ): Promise<{ notifications: NotificationRow[]; total: number; unread_count: number }> {
    const limit = Math.min(options.limit ?? 20, 50);
    const offset = options.offset ?? 0;
    const unreadOnly = options.unreadOnly ?? false;

    const rows = await this.notificationsRepo.listForRecipient(userId, limit, offset, unreadOnly);
    const total = await this.notificationsRepo.countForRecipient(userId, unreadOnly);
    const unread_count = await this.notificationsRepo.countUnreadForRecipient(userId);

    return { notifications: rows.map(withSender), total, unread_count };
  }

  async unreadCount(userId: number): Promise<number> {
    return await this.notificationsRepo.countUnreadForRecipient(userId);
  }

  /**
   * The read state of one of the user's notifications. The user's other tabs and
   * devices get the row as it now reads (`socketId`, REST's requesting tab, is
   * left out: it changed its bell itself), so their bell and count follow.
   */
  async markRead(notificationId: number, userId: number, socketId: string | undefined): Promise<boolean> {
    return this.setReadState(notificationId, userId, 1, socketId);
  }

  async markUnread(notificationId: number, userId: number, socketId: string | undefined): Promise<boolean> {
    return this.setReadState(notificationId, userId, 0, socketId);
  }

  /** Every notification of the user read at once; the other tabs read their list again when anything changed. */
  async markAllRead(userId: number, socketId: string | undefined): Promise<number> {
    const count = await this.notificationsRepo.markAllRead(userId);
    if (count > 0) this.realtime.broadcastToUser(userId, { type: 'notification:read-all' }, socketId);
    return count;
  }

  private async setReadState(id: number, userId: number, read: 0 | 1, socketId: string | undefined) {
    if ((await this.notificationsRepo.setRead(id, userId, read)) === 0) return false;
    const row = await this.notificationsRepo.findWithSenderById(id);
    if (row) {
      this.realtime.broadcastToUser(userId, { type: 'notification:updated', notification: withSender(row) }, socketId);
    }
    return true;
  }

  /** The name a notification gives its actor, as the routes read it off their session user. */
  async actorName(userId: number): Promise<string> {
    return (await this.notificationsRepo.findUserBasic(userId))?.username ?? '';
  }

  async deleteOne(notificationId: number, userId: number): Promise<boolean> {
    return (await this.notificationsRepo.deleteForRecipient(notificationId, userId)) > 0;
  }

  async deleteAll(userId: number): Promise<number> {
    return await this.notificationsRepo.deleteAllForRecipient(userId);
  }

  /**
   * Names what a tap on a yes/no notification does: a domain that sends one
   * registers its action here from its module's init, so this module never
   * imports the domain. The handler gets the payload the notification
   * carried and the person who answered; a handler that throws leaves the
   * notification unanswered, with its message as the error.
   */
  registerResponseAction(
    action: string,
    handler: (payload: Record<string, unknown>, respondingUserId: number) => Promise<void>,
  ): void {
    registerAction(action, handler);
  }

  /**
   * Run a notification's action for the recipient's answer.
   * @txIndependent the claim commits on its own before the action runs, so a second
   * submit sees it; a failing action releases it again.
   */
  async respond(notificationId: number, userId: number, response: NotificationResponse): Promise<RespondResult> {
    const notification = await this.notificationsRepo.findByIdForRecipient(notificationId, userId);

    if (!notification) return { success: false, error: 'Notification not found' };
    if (notification.type !== 'boolean') return { success: false, error: 'Not a boolean notification' };
    if (notification.response !== null) return { success: false, error: 'Already responded' };

    const callbackJson = response === 'positive' ? notification.positive_callback : notification.negative_callback;
    if (!callbackJson) return { success: false, error: 'No callback defined' };

    let callback: { action: string; payload: Record<string, unknown> };
    try {
      callback = JSON.parse(callbackJson);
    } catch {
      return { success: false, error: 'Invalid callback format' };
    }

    const handler = getAction(callback.action);
    if (!handler) return { success: false, error: `Unknown action: ${callback.action}` };

    // Atomic claim BEFORE the handler runs — only updates if response is still
    // NULL, so a concurrent double-submit can never execute the action twice
    // (the legacy order ran the handler first, letting both submits through).
    const changes = await this.notificationsRepo.claimResponse(notificationId, userId, response);

    if (changes === 0) return { success: false, error: 'Already responded' };

    try {
      await handler(callback.payload, userId);
    } catch (err) {
      // Release the claim so the user can retry — legacy contract: a handler
      // failure returns its message and leaves the notification unresponded.
      await this.notificationsRepo.releaseResponse(notificationId, userId, notification.is_read);
      return { success: false, error: err instanceof Error ? err.message : 'Action failed' };
    }

    const mappedUpdated = withSender((await this.notificationsRepo.findWithSenderById(notificationId))!);

    this.realtime.broadcastToUser(userId, { type: 'notification:updated', notification: mappedUpdated });

    return { success: true, notification: mappedUpdated };
  }

  // ── Unified dispatcher (from services/notificationService.ts) ─────────────

  /**
   * Resolves the recipients of one event and delivers it on every active
   * channel. A caller may leave the send running; `settled()` waits for it.
   *
   * @txStandalone a notification reports a change after it is written; email
   * and webhook delivery are network I/O, which never runs inside a transaction.
   */
  send(payload: NotificationPayload): Promise<NotificationDelivery> {
    return this.inFlight.track(this.deliver(payload));
  }

  /** Resolves once every send started before the call has finished, delivered or not. */
  settled(): Promise<void> {
    return this.inFlight.settled();
  }

  /** @txIndependent each recipient's row is written on its own, between deliveries. */
  private async deliver(payload: NotificationPayload): Promise<NotificationDelivery> {
    const { event, actorId, params, scope, targetId, inApp } = payload;
    const delivery: NotificationDelivery = { attempted: 0, delivered: 0 };

    // Resolve recipients based on scope
    const recipients = await this.resolveRecipients(scope, targetId, actorId);
    if (recipients.length === 0) return delivery;

    const configEntry = EVENT_NOTIFICATION_CONFIG[event];
    if (!configEntry) {
      logDebug(`notificationService.send: unknown event type "${event}", using fallback`);
      if (readEnv().app.isDevelopment && actorId != null) {
        const devSender = (await this.notificationsRepo.findUserBasic(actorId)) ?? null;
        await this.createNotificationForRecipient(
          {
            type: 'simple',
            scope: 'user',
            target: actorId,
            sender_id: null,
            title_key: 'notif.dev.unknown_event.title',
            text_key: 'notif.dev.unknown_event.text',
            text_params: { event },
          },
          actorId,
          devSender,
        );
      }
    }
    const config = configEntry ?? FALLBACK_EVENT_CONFIG;
    const activeChannels = await this.prefs.getActiveChannels();
    const channels = await listChannels();
    const appUrl = getAppUrl();

    // Build navigate target (used by email/webhook CTA and in-app navigate)
    const navigateTarget = inApp?.navigateTarget ?? config.navigateTarget(params);
    const fullLink = navigateTarget ? `${appUrl}${navigateTarget}` : undefined;

    // Resolve the in-app text key once, so all three in-app branches below agree
    // (e.g. replica_failure picks the "N more failures suppressed" phrasing off params.suppressed).
    const textKey = typeof config.textKey === 'function' ? config.textKey(params) : config.textKey;

    // Fetch sender info once for in-app WS payloads
    const sender = actorId ? ((await this.notificationsRepo.findUserBasic(actorId)) ?? null) : null;

    logDebug(
      `notificationService.send event=${event} scope=${scope} targetId=${targetId} recipients=${recipients.length} channels=inapp,${activeChannels.join(',')}`,
    );

    // Dispatch to each recipient in parallel
    await Promise.all(
      recipients.map(async (recipientId) => {
        const promises: Promise<unknown>[] = [];

        // ── In-app ──────────────────────────────────────────────────────────
        if (await this.prefs.isEnabledForEvent(recipientId, event, 'inapp')) {
          const inAppType = inApp?.type ?? config.inAppType;
          let notifInput: NotificationInput;

          if (inAppType === 'boolean' && inApp?.positiveCallback && inApp?.negativeCallback) {
            notifInput = {
              type: 'boolean',
              scope,
              target: targetId,
              sender_id: actorId,
              event_type: event,
              title_key: config.titleKey,
              title_params: params,
              text_key: textKey,
              text_params: params,
              positive_text_key: inApp.positiveTextKey ?? 'notif.action.accept',
              negative_text_key: inApp.negativeTextKey ?? 'notif.action.decline',
              positive_callback: inApp.positiveCallback,
              negative_callback: inApp.negativeCallback,
            };
          } else if (inAppType === 'navigate' && navigateTarget) {
            notifInput = {
              type: 'navigate',
              scope,
              target: targetId,
              sender_id: actorId,
              event_type: event,
              title_key: config.titleKey,
              title_params: params,
              text_key: textKey,
              text_params: params,
              navigate_text_key: config.navigateTextKey ?? 'notif.action.view',
              navigate_target: navigateTarget,
            };
          } else {
            notifInput = {
              type: 'simple',
              scope,
              target: targetId,
              sender_id: actorId,
              event_type: event,
              title_key: config.titleKey,
              title_params: params,
              text_key: textKey,
              text_params: params,
            };
          }

          promises.push(
            Promise.resolve().then(() => this.createNotificationForRecipient(notifInput, recipientId, sender ?? null)),
          );
        }

        // ── External channels (email, webhook, ntfy, push, plugin:*) ─────────
        // One loop over the registry. The message is rendered once per recipient, in
        // their language, and handed to every channel that wants it — so a plugin
        // channel never touches i18n.
        // R1.4: `filter` cannot await, and the credential check behind shouldSendToUser
        // is now async (a plugin channel reads the recipient's stored settings).
        const deliverable: ExternalChannel[] = [];
        for (const ch of channels) {
          if (await shouldSendToUser(ch, event, recipientId, activeChannels, this.prefs)) deliverable.push(ch);
        }
        if (deliverable.length > 0) {
          const lang = await this.mailer.getUserLanguage(recipientId);
          const { title, body } = getEventText(lang, event, params);
          const msg: ChannelMessage = {
            event,
            title,
            body,
            navigateTarget: navigateTarget ?? undefined,
            url: fullLink,
            tripName: params.trip,
          };
          for (const ch of deliverable) promises.push(ch.sendToUser(recipientId, msg));
        }

        const results = await Promise.allSettled(promises);
        delivery.attempted += results.length;
        for (const result of results) {
          if (result.status === 'rejected') {
            logError(
              `notificationService.send channel dispatch failed event=${event} recipient=${recipientId}: ${result.reason instanceof Error ? result.reason.message : result.reason}`,
            );
          } else if (result.value !== false) {
            delivery.delivered += 1;
          }
        }
      }),
    );

    // ── Admin-global copies (scope: admin) ───────────────────────────────
    // One send per channel, over the admin's own credentials, not per-recipient.
    // Always rendered in English — there is no single recipient to take a language from.
    if (scope === 'admin') {
      // R1.4: `filter` cannot await, and the admin global preference is now an
      // async read. Same channels, same order, one explicit loop.
      const globalChannels: ExternalChannel[] = [];
      for (const ch of channels) {
        if (!ch.sendGlobal || !ch.supportsEvent(event) || !isAdminGlobalChannel(ch.id)) continue;
        if (!(await this.prefs.getAdminGlobalPref(event, ch.id))) continue;
        globalChannels.push(ch);
      }
      if (globalChannels.length > 0) {
        const { title, body } = getEventText('en', event, params);
        const msg: ChannelMessage = { event, title, body, navigateTarget: navigateTarget ?? undefined, url: fullLink };
        const sent = await Promise.all(
          globalChannels.map((ch) =>
            ch.sendGlobal!(msg).catch((err: unknown) => {
              logError(
                `notificationService.send admin ${ch.id} failed event=${event}: ${err instanceof Error ? err.message : err}`,
              );
              return false;
            }),
          ),
        );
        delivery.attempted += sent.length;
        delivery.delivered += sent.filter((result) => result !== false).length;
      }
    }
    return delivery;
  }
}

export type { NotificationInput, NotificationRow, NotificationType, NotificationScope, NotificationResponse };