Files
canina/backend/src/notifications/notifications-queue.service.ts
T
devops 625c3f5ce2
Deploy Canina / deploy (push) Failing after 1m57s
feat(notifications): send branded transactional emails for shop events
Add Canina-branded welcome, contact confirmation/admin notify, and order created/paid/shipped emails via support@canina.ir without blocking the SMS flows.
2026-11-10 13:27:37 +00:00

282 lines
8.0 KiB
TypeScript

import { Injectable, Logger, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { EmailService } from './email.service';
import { renderCaninaNotificationEmail } from './email-layout';
import { SmsService } from '../common/services/sms.service';
export interface EnqueueOptions {
channel: 'SMS' | 'EMAIL';
recipient: string;
event: string;
subject?: string;
content: string;
payload?: any;
idempotencyKey?: string;
maxAttempts?: number;
}
@Injectable()
export class NotificationsQueueService implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(NotificationsQueueService.name);
private workerInterval: NodeJS.Timeout | null = null;
private isProcessing = false;
constructor(
private readonly prisma: PrismaService,
private readonly emailService: EmailService,
private readonly smsService: SmsService,
) {}
onModuleInit() {
// Run background queue processor every 15 seconds
this.workerInterval = setInterval(() => {
this.processQueue().catch((err) => {
this.logger.error(`Error in queue worker: ${err?.message}`);
});
}, 15000);
}
onModuleDestroy() {
if (this.workerInterval) {
clearInterval(this.workerInterval);
this.workerInterval = null;
}
}
/**
* Enqueue a durable notification with idempotency check
*/
async enqueue(options: EnqueueOptions) {
if (options.idempotencyKey) {
const existing = await this.prisma.notificationQueue.findUnique({
where: { idempotencyKey: options.idempotencyKey },
});
if (existing) {
this.logger.log(`Notification idempotency matched for key: ${options.idempotencyKey}`);
return existing;
}
}
const item = await this.prisma.notificationQueue.create({
data: {
channel: options.channel,
recipient: options.recipient,
event: options.event,
subject: options.subject || null,
content: options.content,
payload: options.payload ?? null,
idempotencyKey: options.idempotencyKey || null,
maxAttempts: options.maxAttempts ?? 3,
status: 'QUEUED',
},
});
// Attempt immediate asynchronous process in the background
setImmediate(() => {
this.processItem(item.id).catch(() => {});
});
return item;
}
/**
* Process a single queued item by ID
*/
async processItem(id: string) {
const item = await this.prisma.notificationQueue.findUnique({ where: { id } });
if (!item || item.status === 'SENT') return;
if (item.attempts >= item.maxAttempts) {
await this.prisma.notificationQueue.update({
where: { id },
data: { status: 'FAILED' },
});
return;
}
await this.prisma.notificationQueue.update({
where: { id },
data: {
status: 'PROCESSING',
attempts: { increment: 1 },
},
});
try {
if (item.channel === 'EMAIL') {
const payloadObj = (item.payload as Record<string, any>) || {};
const subject = item.subject || 'اطلاعیه کنینا ایران';
const res = await this.emailService.sendMail({
to: item.recipient,
subject,
text: item.content,
html: payloadObj.html || renderCaninaNotificationEmail(subject, item.content || ''),
});
if (res.success) {
await this.prisma.notificationQueue.update({
where: { id },
data: {
status: 'SENT',
sentAt: new Date(),
lastError: null,
},
});
return;
} else {
throw new Error(res.error || 'خطای نامشخص در ارسال ایمیل');
}
} else if (item.channel === 'SMS') {
const payloadObj = (item.payload as Record<string, any>) || {};
if (payloadObj.patternId && Array.isArray(payloadObj.args)) {
const sent = await this.smsService.sendPatternSms({
to: item.recipient,
bodyId: Number(payloadObj.patternId),
args: payloadObj.args,
type: item.event,
});
if (!sent) {
throw new Error(`ارسال پیامک پترن ${payloadObj.patternId} ناموفق بود.`);
}
} else {
const sent = await this.smsService.sendSms(item.recipient, item.content);
if (!sent) {
throw new Error(`ارسال پیامک متنی به ${item.recipient} ناموفق بود.`);
}
}
await this.prisma.notificationQueue.update({
where: { id },
data: {
status: 'SENT',
sentAt: new Date(),
lastError: null,
},
});
return;
}
} catch (err: any) {
const isFinalAttempt = item.attempts + 1 >= item.maxAttempts;
await this.prisma.notificationQueue.update({
where: { id },
data: {
status: isFinalAttempt ? 'FAILED' : 'QUEUED',
lastError: err?.message || 'خطا در ارسال پیام',
},
});
this.logger.warn(`Failed to deliver notification ${id} (${item.channel} to ${item.recipient}): ${err?.message}`);
}
}
/**
* Process pending batch of queue
*/
async processQueue(batchSize = 10) {
if (this.isProcessing) return;
this.isProcessing = true;
try {
const pendingItems = await this.prisma.notificationQueue.findMany({
where: {
status: 'QUEUED',
attempts: { lt: 3 },
},
orderBy: { createdAt: 'asc' },
take: batchSize,
});
for (const item of pendingItems) {
await this.processItem(item.id);
}
} finally {
this.isProcessing = false;
}
}
/**
* Retry a failed notification manually
*/
async retry(id: string) {
const item = await this.prisma.notificationQueue.findUnique({ where: { id } });
if (!item) throw new Error('آیتم صف یافت نشد.');
const updated = await this.prisma.notificationQueue.update({
where: { id },
data: {
status: 'QUEUED',
attempts: 0,
lastError: null,
},
});
setImmediate(() => {
this.processItem(id).catch(() => {});
});
return updated;
}
/**
* Get queue items with filtering and pagination
*/
async getQueue(query: { page?: number; limit?: number; status?: string; channel?: string; search?: string }) {
const page = Math.max(1, Number(query.page || 1));
const limit = Math.max(1, Math.min(100, Number(query.limit || 20)));
const skip = (page - 1) * limit;
const where: any = {};
if (query.status) where.status = query.status;
if (query.channel) where.channel = query.channel;
if (query.search) {
where.OR = [
{ recipient: { contains: query.search, mode: 'insensitive' } },
{ subject: { contains: query.search, mode: 'insensitive' } },
{ event: { contains: query.search, mode: 'insensitive' } },
];
}
const [items, total] = await Promise.all([
this.prisma.notificationQueue.findMany({
where,
orderBy: { createdAt: 'desc' },
skip,
take: limit,
}),
this.prisma.notificationQueue.count({ where }),
]);
const stats = await this.getStats();
return {
items,
total,
page,
limit,
totalPages: Math.ceil(total / limit) || 1,
stats,
};
}
/**
* Get overall stats
*/
async getStats() {
const [total, queued, processing, sent, failed] = await Promise.all([
this.prisma.notificationQueue.count(),
this.prisma.notificationQueue.count({ where: { status: 'QUEUED' } }),
this.prisma.notificationQueue.count({ where: { status: 'PROCESSING' } }),
this.prisma.notificationQueue.count({ where: { status: 'SENT' } }),
this.prisma.notificationQueue.count({ where: { status: 'FAILED' } }),
]);
return {
total,
queued,
processing,
sent,
failed,
successRate: total > 0 ? Math.round((sent / total) * 100) : 100,
};
}
}