"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; var PushNotificationService_1; Object.defineProperty(exports, "__esModule", { value: true }); exports.PushNotificationService = void 0; const common_1 = require("@nestjs/common"); const config_1 = require("@nestjs/config"); const typeorm_1 = require("@nestjs/typeorm"); const typeorm_2 = require("typeorm"); const webpush = __importStar(require("web-push")); const entities_1 = require("../entities"); let PushNotificationService = PushNotificationService_1 = class PushNotificationService { constructor(configService, deviceRepository, logRepository) { this.configService = configService; this.deviceRepository = deviceRepository; this.logRepository = logRepository; this.logger = new common_1.Logger(PushNotificationService_1.name); this.isConfigured = false; } onModuleInit() { const vapidPublicKey = this.configService.get('VAPID_PUBLIC_KEY'); const vapidPrivateKey = this.configService.get('VAPID_PRIVATE_KEY'); const vapidSubject = this.configService.get('VAPID_SUBJECT', 'mailto:admin@example.com'); if (vapidPublicKey && vapidPrivateKey) { try { webpush.setVapidDetails(vapidSubject, vapidPublicKey, vapidPrivateKey); this.isConfigured = true; this.logger.log('Web Push configured with VAPID keys'); } catch (error) { this.logger.error(`Failed to configure Web Push: ${error.message}`); } } else { this.logger.warn('VAPID keys not configured. Push notifications will be disabled.'); } } isEnabled() { return this.isConfigured; } getVapidPublicKey() { if (!this.isConfigured) { return null; } return this.configService.get('VAPID_PUBLIC_KEY') || null; } async sendToUser(userId, tenantId, payload, notificationId) { if (!this.isConfigured) { this.logger.warn('Push notifications not configured, skipping send'); return []; } const devices = await this.deviceRepository.find({ where: { user_id: userId, tenant_id: tenantId, is_active: true }, }); if (devices.length === 0) { this.logger.debug(`No active devices found for user ${userId}`); return []; } const results = []; const pushPayload = JSON.stringify({ title: payload.title, body: payload.body, icon: payload.icon || '/icon-192.png', badge: payload.badge || '/badge-72.png', url: payload.url || '/', data: payload.data, actions: payload.actions || [ { action: 'view', title: 'Ver' }, { action: 'dismiss', title: 'Descartar' }, ], }); for (const device of devices) { const result = await this.sendToDevice(device, pushPayload, notificationId); results.push(result); } const successCount = results.filter((r) => r.success).length; this.logger.log(`Push sent to user ${userId}: ${successCount}/${results.length} successful`); return results; } async sendToDevice(device, payload, notificationId) { try { const subscription = JSON.parse(device.device_token); await webpush.sendNotification(subscription, payload); device.last_used_at = new Date(); await this.deviceRepository.save(device); if (notificationId) { await this.logRepository.save({ notification_id: notificationId, channel: 'push', status: 'sent', provider: 'web-push', device_id: device.id, delivered_at: new Date(), }); } return { deviceId: device.id, success: true, }; } catch (error) { const statusCode = error.statusCode; if (statusCode === 410 || statusCode === 404) { this.logger.warn(`Device ${device.id} subscription expired (${statusCode}), marking inactive`); device.is_active = false; await this.deviceRepository.save(device); } if (notificationId) { await this.logRepository.save({ notification_id: notificationId, channel: 'push', status: 'failed', provider: 'web-push', device_id: device.id, error_code: statusCode?.toString(), error_message: error.message, }); } return { deviceId: device.id, success: false, error: error.message, statusCode, }; } } async sendBroadcast(tenantId, payload) { if (!this.isConfigured) { this.logger.warn('Push notifications not configured, skipping broadcast'); return { total: 0, successful: 0, failed: 0 }; } const devices = await this.deviceRepository.find({ where: { tenant_id: tenantId, is_active: true }, }); const pushPayload = JSON.stringify({ title: payload.title, body: payload.body, icon: payload.icon || '/icon-192.png', badge: payload.badge || '/badge-72.png', url: payload.url || '/', data: payload.data, }); let successful = 0; let failed = 0; for (const device of devices) { const result = await this.sendToDevice(device, pushPayload); if (result.success) { successful++; } else { failed++; } } this.logger.log(`Broadcast to tenant ${tenantId}: ${successful}/${devices.length} successful`); return { total: devices.length, successful, failed, }; } validateSubscription(subscriptionJson) { try { const subscription = JSON.parse(subscriptionJson); if (!subscription.endpoint) { return false; } if (!subscription.keys?.p256dh || !subscription.keys?.auth) { return false; } return true; } catch { return false; } } }; exports.PushNotificationService = PushNotificationService; exports.PushNotificationService = PushNotificationService = PushNotificationService_1 = __decorate([ (0, common_1.Injectable)(), __param(1, (0, typeorm_1.InjectRepository)(entities_1.UserDevice)), __param(2, (0, typeorm_1.InjectRepository)(entities_1.NotificationLog)), __metadata("design:paramtypes", [config_1.ConfigService, typeorm_2.Repository, typeorm_2.Repository]) ], PushNotificationService); //# sourceMappingURL=push-notification.service.js.map