All files / src/platform/communications/push push.service.ts

0% Statements 0/40
0% Branches 0/23
0% Functions 0/9
0% Lines 0/37

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143                                                                                                                                                                                                                                                                                             
import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import {
  PushInstallation,
  PushTopicSubscription,
  PushDelivery,
} from './schemas/push.schema';
 
@Injectable()
export class PushNotificationService {
  private readonly logger = new Logger(PushNotificationService.name);
 
  constructor(
    @InjectModel(PushInstallation.name)
    private readonly installationModel: Model<PushInstallation>,
    @InjectModel(PushTopicSubscription.name)
    private readonly subscriptionModel: Model<PushTopicSubscription>,
    @InjectModel(PushDelivery.name)
    private readonly deliveryModel: Model<PushDelivery>,
  ) {}
 
  async registerToken(
    userId: string,
    tenantId: string,
    token: string,
    platform: 'ios' | 'android' | 'flutter',
    deviceId?: string,
    deviceName?: string,
  ): Promise<PushInstallation> {
    const existing = await this.installationModel.findOne({ token }).exec();
    const doc = existing ?? new this.installationModel({ token });
 
    doc.userId = userId;
    doc.tenantId = tenantId;
    doc.platform = platform;
    doc.deviceId = deviceId ?? '';
    doc.deviceName = deviceName ?? '';
    doc.isActive = true;
    doc.lastRegisteredAt = new Date();
 
    await doc.save();
    this.logger.log(`Push token registered for user: ${userId}`);
    return doc;
  }
 
  async deregisterToken(token: string): Promise<void> {
    await this.installationModel
      .findOneAndUpdate({ token }, { isActive: false })
      .exec();
    this.logger.log(`Push token deactivated`);
  }
 
  async subscribeToTopic(
    tenantId: string,
    userId: string,
    topic: string,
  ): Promise<void> {
    await this.subscriptionModel
      .findOneAndUpdate(
        { tenantId, userId, topic },
        { isActive: true },
        { upsert: true },
      )
      .exec();
  }
 
  async unsubscribeFromTopic(
    tenantId: string,
    userId: string,
    topic: string,
  ): Promise<void> {
    await this.subscriptionModel
      .findOneAndUpdate({ tenantId, userId, topic }, { isActive: false })
      .exec();
  }
 
  async sendToUser(
    tenantId: string,
    userId: string,
    title: string,
    body: string,
    data: Record<string, string> = {},
  ): Promise<void> {
    const activeInstallations = await this.installationModel
      .find({ userId, tenantId, isActive: true })
      .exec();
    if (activeInstallations.length === 0) {
      this.logger.warn(
        `No active push installations found for user: ${userId}`,
      );
      return;
    }
 
    const tokens = activeInstallations.map((i) => i.token);
    await this.sendToTokens(tenantId, userId, tokens, title, body, data);
  }
 
  async sendToTokens(
    tenantId: string,
    userId: string,
    tokens: string[],
    title: string,
    body: string,
    data: Record<string, string> = {},
  ): Promise<void> {
    // In production, invoke Firebase Admin SDK FCM Client.
    // For local fallback/mock:
    this.logger.log(
      `[FCM Mock Push] Sending to user ${userId} (${tokens.length} devices): "${title}" - "${body}"`,
    );
 
    // Log the delivery
    await this.deliveryModel.create({
      tenantId,
      userId,
      title,
      body,
      data,
      status: 'sent',
    });
  }
 
  async sendToTopic(
    tenantId: string,
    topic: string,
    title: string,
    body: string,
    data: Record<string, string> = {},
  ): Promise<void> {
    const subscriptions = await this.subscriptionModel
      .find({ tenantId, topic, isActive: true })
      .exec();
    this.logger.log(
      `[FCM Mock Push] Topic '${topic}': Sending to ${subscriptions.length} users`,
    );
 
    for (const sub of subscriptions) {
      await this.sendToUser(tenantId, sub.userId, title, body, data);
    }
  }
}