/** * Backend Notifications Domain Service * * Manages IN_APP notifications only. This service handles the creation, retrieval, * and deletion of in-app notifications (bell icon notifications, system alerts, etc.). * * NOTE: Email, SMS, and Push notifications are handled by @plyaz/notifications package, * NOT by this domain service. This service is strictly for IN_APP notifications that * appear in the user's notification center. * * Extends BaseBackendDomainService which provides: * - Automatic validation → mapper → repository → mapper flow * - Event emission throughout CRUD lifecycle * - Repository-based data access * - Configurable error throwing behavior * - Cache support for read operations * * Runtime: Backend (NestJS, Express, Node.js) * * @example * ```typescript * const service = await BackendNotificationsDomainService.create({ * throwOnValidationError: true, * throwOnRepositoryError: true, * }); * * // CRUD operations (inherited from base) * const entity = await service.create({ * userId: 'user-123', * type: 'SYSTEM', * title: 'Welcome!', * message: 'Thanks for signing up.', * category: 'transactional', * }); * const fetched = await service.getById(entity.id); * await service.delete(entity.id, { soft: true }); * const list = await service.getAll({ user_id: 'user-123' }); * ``` */ import { BaseBackendDomainService } from '../base'; import type { CoreServiceCreateOptions, CoreInjectedServices } from '@plyaz/types/core'; import { NotificationsRepository, NotificationPreferencesRepository, type NotificationPreferencesDatabaseRow } from '../../models/notifications'; import { ShortUrlRepository } from '../../models/shortUrls'; import type { PreferenceChecker, NotificationCategory, NotificationChannel, UrlAnalytics, TokenPayload, TokenStrategy } from '@plyaz/types/notifications'; import { NotificationsMapperClass } from './mappers/NotificationsMapper'; import { NotificationsValidatorClass } from './validators/NotificationsValidator'; import type { NotificationsEntity, NotificationsResponseDTO, CreateNotificationsDTO, UpdateNotificationsDTO, PatchNotificationsDTO, QueryNotificationsDTO, DeleteNotificationsDTO, NotificationStoreItem, NotificationsDomainServiceConfig, NotificationsDatabaseRow } from '@plyaz/types/core'; /** * Mapper type for this service */ type NotificationsMapper = InstanceType; /** * Validator type for this service */ type NotificationsValidator = InstanceType; /** * Backend Notifications Domain Service * * All CRUD methods are inherited from BaseBackendDomainService: * - create(data): Promise * - getById(id): Promise * - getAll(query?): Promise * - patch(id, data): Promise * - delete(id, options?): Promise * - exists(id): Promise * - bulkCreate(dataArray): Promise * - bulkDelete(ids, options?): Promise */ export declare class BackendNotificationsDomainService extends BaseBackendDomainService { /** Lazy-loaded repository instance for data access */ private _repository?; /** Lazy-loaded short URL repository for URL shortening */ private _shortUrlRepository?; /** Lazy-loaded preferences repository for opt-out checking */ private _preferencesRepository?; /** Preference cache for performance */ private _preferenceCache; /** Event prefix for all events emitted by this service */ protected eventPrefix: string; /** Cache prefix for namespacing cache keys */ protected cachePrefix: string; /** * Lazy repository getter - creates repository on first access. * Defers DbService requirement until repository is actually used. */ protected get repository(): NotificationsRepository; /** * Lazy short URL repository getter. * Used for URL shortening in notifications (email tracking links, etc.) */ protected get shortUrlRepository(): ShortUrlRepository; /** * Lazy preferences repository getter. * Used for checking user notification preferences (opt-out). */ protected get preferencesRepository(): NotificationPreferencesRepository; /** Unique key for this service (used by ServiceRegistry) */ static readonly serviceKey: "notifications"; /** * Factory method for ServiceRegistry auto-initialization. * Auto-registers event handlers for DB persistence. */ static create(config?: NotificationsDomainServiceConfig, options?: CoreServiceCreateOptions): Promise; /** * Register event handlers for DB persistence. * Auto-called by create() method when service is initialized. * * Customize this method to persist data to DB when domain events fire. * Uses BackendEventPersistenceHandler for a scalable, reusable pattern. * * @param verbose - Enable verbose logging */ static registerEventHandlers(verbose?: boolean): void; constructor(config?: NotificationsDomainServiceConfig, injected?: CoreInjectedServices); /** * Check if service is available */ isAvailable(): boolean; /** * Dispose/cleanup the service */ dispose(): void; /** * Get all notifications for a user */ getByUserId(userId: string): Promise; /** * Soft delete with reason */ softDeleteWithReason(id: string, reason: string): Promise; /** * Resolve a short URL and increment click count. * Used by redirect endpoint to look up original URL. * * @param shortCode - The short code to resolve * @returns Original URL or null if not found/expired */ resolveShortUrl(shortCode: string): Promise; /** * Get analytics for a short URL. * * @param shortCode - The short code to get analytics for * @returns Analytics data or null if not found */ getShortUrlAnalytics(shortCode: string): Promise; /** * Clean up expired short URLs. * Should be called periodically (e.g., via cron job). */ cleanupExpiredShortUrls(): Promise; /** * Check if a notification should be sent to a recipient. * Implements PreferenceChecker.shouldSend() interface. */ shouldSendNotification(recipientId: string, category: NotificationCategory, channel: NotificationChannel): Promise; /** * Bulk preference check for batch operations. * Implements PreferenceChecker.shouldSendBulk() interface. */ shouldSendNotificationBulk(recipients: Array<{ recipientId: string; category: NotificationCategory; channel: NotificationChannel; }>): Promise; /** * Get user notification preferences. */ getUserPreferences(userId: string): Promise; /** * Update user notification preferences. */ updateUserPreferences(userId: string, data: Partial): Promise; /** * Handle unsubscribe request from email link. * Verifies the token and updates user preferences to disable the category. * * @param token - Encrypted token from unsubscribe URL * @param secret - Encryption key for token verification * @param strategy - Token strategy (default: 'aes-256-gcm') * @returns Result with payload on success * @throws NotificationPackageError on token verification or update failure */ unsubscribe(token: string, secret: string, strategy?: TokenStrategy): Promise<{ success: boolean; message: string; payload: TokenPayload; }>; /** * Create a PreferenceChecker object for use with @plyaz/notifications. * Pass this to NotificationService config.preferenceChecker. */ createPreferenceChecker(): PreferenceChecker; /** * After creating a notification, emit streaming event for real-time delivery. * Broadcasts to user:notifications:{userId} channel. */ protected afterCreate(entity: NotificationsEntity): Promise; } /** * Get or create singleton instance */ export declare function getBackendNotificationsDomainService(config?: NotificationsDomainServiceConfig, options?: CoreServiceCreateOptions): Promise; /** * Reset singleton instance (for testing) */ export declare function resetNotificationsDomainService(): void; export {}; //# sourceMappingURL=BackendNotificationsDomainService.d.ts.map