import { Inject, Injectable } from "@nestjs/common"; import { PrismaService } from "../prisma/prisma.service.js"; import { PushTokenService } from "./push-token.service.js"; import { PUSH_PROVIDER, type PushProvider } from "./push-provider.js"; export interface SendToUserResult { attempted: number; succeeded: number; } // Q-3 推播通知:提醒觸發(J 群組)、角色主動訊息、鎖屏通知都走這個服務——同一個使用者可能有 // 多台裝置,逐一送出並各自留一筆記錄(成功或失敗皆記),方便之後追查「提醒有沒有真的送達」。 @Injectable() export class PushNotificationService { constructor( private readonly prisma: PrismaService, private readonly pushToken: PushTokenService, @Inject(PUSH_PROVIDER) private readonly provider: PushProvider, ) {} async sendToUser(userId: string, title: string, body: string, data?: Record): Promise { const tokens = await this.pushToken.listForUser(userId); let succeeded = 0; for (const { token } of tokens) { const result = await this.provider.send({ token, title, body, data }); await this.prisma.client.pushNotificationLog.create({ data: { userId, title, body, success: result.success, errorText: result.errorText }, }); if (result.success) { succeeded += 1; } } return { attempted: tokens.length, succeeded }; } }