feat(notifications & advisors): implement unified notification queue, SMTP config, and catalog advisor contact flow
Deploy Canina / deploy (push) Successful in 8m17s
Deploy Canina / deploy (push) Successful in 8m17s
This commit is contained in:
1 parent
d881dc491e
commit
fae4b570f9
20 files changed
+3445
-8
No files matched your search
@@ -0,0 +1,125 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Patch,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { AdvisorsService, CreateAdvisorDto } from './advisors.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
@Controller('admin')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
export class AdvisorsController {
|
||||
constructor(
|
||||
private readonly advisorsService: AdvisorsService,
|
||||
private readonly prisma: PrismaService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Advisors Management
|
||||
*/
|
||||
@Get('advisors')
|
||||
async listAdvisors() {
|
||||
const data = await this.advisorsService.listAdvisors();
|
||||
return { success: true, data };
|
||||
}
|
||||
|
||||
@Post('advisors')
|
||||
async createAdvisor(@Body() dto: CreateAdvisorDto) {
|
||||
const data = await this.advisorsService.createAdvisor(dto);
|
||||
return { success: true, message: 'مشاور جدید با موفقیت اضافه شد.', data };
|
||||
}
|
||||
|
||||
@Put('advisors/:id')
|
||||
async updateAdvisor(@Param('id') id: string, @Body() dto: Partial<CreateAdvisorDto>) {
|
||||
const data = await this.advisorsService.updateAdvisor(id, dto);
|
||||
return { success: true, message: 'اطلاعات مشاور بهروزرسانی شد.', data };
|
||||
}
|
||||
|
||||
@Patch('advisors/:id/set-default')
|
||||
async setDefaultAdvisor(@Param('id') id: string) {
|
||||
const data = await this.advisorsService.setDefaultAdvisor(id);
|
||||
return { success: true, message: 'مشاور با موفقیت به عنوان پیشفرض سیستم انتخاب شد.', data };
|
||||
}
|
||||
|
||||
@Delete('advisors/:id')
|
||||
async deleteAdvisor(@Param('id') id: string) {
|
||||
return this.advisorsService.deleteAdvisor(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Leads (Contact Requests) Management
|
||||
*/
|
||||
@Get('leads')
|
||||
async listLeads(
|
||||
@Query('page') page?: number,
|
||||
@Query('limit') limit?: number,
|
||||
@Query('status') status?: string,
|
||||
@Query('search') search?: string,
|
||||
) {
|
||||
const data = await this.advisorsService.listLeads({ page, limit, status, search });
|
||||
return { success: true, data };
|
||||
}
|
||||
|
||||
@Patch('leads/:id/status')
|
||||
async updateLeadStatus(
|
||||
@Param('id') id: string,
|
||||
@Body() body: { status: string; notes?: string },
|
||||
) {
|
||||
const data = await this.advisorsService.updateLeadStatus(id, body.status, body.notes);
|
||||
return { success: true, message: 'وضعیت درخواست تماس بهروزرسانی شد.', data };
|
||||
}
|
||||
|
||||
@Delete('leads/:id')
|
||||
async deleteLead(@Param('id') id: string) {
|
||||
return this.advisorsService.deleteLead(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Product Advisor Linking
|
||||
*/
|
||||
@Get('products/:productId/advisor')
|
||||
async getProductAdvisor(@Param('productId') productId: string) {
|
||||
const pa = await this.prisma.productAdvisor.findFirst({
|
||||
where: { productId },
|
||||
include: { advisor: true },
|
||||
});
|
||||
return { success: true, data: pa?.advisor || null };
|
||||
}
|
||||
|
||||
@Post('products/:productId/advisor')
|
||||
async assignProductAdvisor(
|
||||
@Param('productId') productId: string,
|
||||
@Body() body: { advisorId: string | null },
|
||||
) {
|
||||
if (!body.advisorId) {
|
||||
// Remove product advisor assignment
|
||||
await this.prisma.productAdvisor.deleteMany({ where: { productId } });
|
||||
return { success: true, message: 'مشاور اختصاصی محصول حذف و به حالت پیشفرض بازگشت.' };
|
||||
}
|
||||
|
||||
// Upsert assignment
|
||||
await this.prisma.productAdvisor.upsert({
|
||||
where: {
|
||||
productId_advisorId: {
|
||||
productId,
|
||||
advisorId: body.advisorId,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
productId,
|
||||
advisorId: body.advisorId,
|
||||
},
|
||||
update: {},
|
||||
});
|
||||
|
||||
return { success: true, message: 'مشاور اختصاصی محصول با موفقیت تعیین شد.' };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PrismaModule } from '../prisma/prisma.module';
|
||||
import { NotificationsModule } from '../notifications/notifications.module';
|
||||
import { AdvisorsService } from './advisors.service';
|
||||
import { AdvisorsController } from './advisors.controller';
|
||||
import { PublicLeadController } from './public-lead.controller';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, NotificationsModule],
|
||||
controllers: [AdvisorsController, PublicLeadController],
|
||||
providers: [AdvisorsService],
|
||||
exports: [AdvisorsService],
|
||||
})
|
||||
export class AdvisorsModule {}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AdvisorsService } from './advisors.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { NotificationsQueueService } from '../notifications/notifications-queue.service';
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
|
||||
describe('AdvisorsService', () => {
|
||||
let service: AdvisorsService;
|
||||
let prisma: any;
|
||||
let queueService: any;
|
||||
|
||||
beforeEach(async () => {
|
||||
prisma = {
|
||||
advisorContact: {
|
||||
findMany: jest.fn(),
|
||||
findUnique: jest.fn(),
|
||||
findFirst: jest.fn(),
|
||||
create: jest.fn(),
|
||||
update: jest.fn(),
|
||||
updateMany: jest.fn(),
|
||||
delete: jest.fn(),
|
||||
},
|
||||
lead: {
|
||||
findMany: jest.fn(),
|
||||
count: jest.fn(),
|
||||
findUnique: jest.fn(),
|
||||
create: jest.fn(),
|
||||
update: jest.fn(),
|
||||
delete: jest.fn(),
|
||||
},
|
||||
product: {
|
||||
findUnique: jest.fn(),
|
||||
},
|
||||
productAdvisor: {
|
||||
findFirst: jest.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
queueService = {
|
||||
enqueue: jest.fn().mockResolvedValue({ id: 'q-1' }),
|
||||
};
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
AdvisorsService,
|
||||
{ provide: PrismaService, useValue: prisma },
|
||||
{ provide: NotificationsQueueService, useValue: queueService },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<AdvisorsService>(AdvisorsService);
|
||||
});
|
||||
|
||||
it('should list advisors with counts', async () => {
|
||||
prisma.advisorContact.findMany.mockResolvedValueOnce([
|
||||
{
|
||||
id: 'adv-1',
|
||||
name: 'دکتر علوی',
|
||||
phone: '09123456789',
|
||||
isDefault: true,
|
||||
isActive: true,
|
||||
_count: { productAdvisors: 2, leads: 5 },
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await service.listAdvisors();
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].name).toBe('دکتر علوی');
|
||||
expect(result[0].productsCount).toBe(2);
|
||||
expect(result[0].leadsCount).toBe(5);
|
||||
});
|
||||
|
||||
it('should create lead and enqueue notifications for default advisor and client', async () => {
|
||||
prisma.lead.count.mockResolvedValueOnce(0); // rate limit
|
||||
prisma.advisorContact.findFirst.mockResolvedValueOnce({
|
||||
id: 'adv-def',
|
||||
name: 'مشاور پیشفرض',
|
||||
phone: '09120000000',
|
||||
isDefault: true,
|
||||
isActive: true,
|
||||
});
|
||||
prisma.lead.create.mockResolvedValueOnce({
|
||||
id: 'lead-1',
|
||||
firstName: 'علی',
|
||||
lastName: 'رضایی',
|
||||
phone: '09129876543',
|
||||
advisorId: 'adv-def',
|
||||
status: 'PENDING',
|
||||
});
|
||||
|
||||
const res = await service.handlePublicLead({
|
||||
firstName: 'علی',
|
||||
lastName: 'رضایی',
|
||||
phone: '09129876543',
|
||||
});
|
||||
|
||||
expect(res.success).toBe(true);
|
||||
expect(res.leadId).toBe('lead-1');
|
||||
expect(queueService.enqueue).toHaveBeenCalledTimes(2); // 1 for advisor, 1 for client
|
||||
});
|
||||
|
||||
it('should reject invalid phone format', async () => {
|
||||
await expect(
|
||||
service.handlePublicLead({
|
||||
firstName: 'تست',
|
||||
lastName: 'تستی',
|
||||
phone: '1234',
|
||||
}),
|
||||
).rejects.toThrow(BadRequestException);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,341 @@
|
||||
import { Injectable, BadRequestException, NotFoundException, Logger } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { NotificationsQueueService } from '../notifications/notifications-queue.service';
|
||||
|
||||
export class CreateAdvisorDto {
|
||||
name!: string;
|
||||
phone!: string;
|
||||
title?: string;
|
||||
isDefault?: boolean;
|
||||
isActive?: boolean;
|
||||
}
|
||||
|
||||
export class CreateLeadDto {
|
||||
firstName!: string;
|
||||
lastName!: string;
|
||||
phone!: string;
|
||||
productId?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AdvisorsService {
|
||||
private readonly logger = new Logger(AdvisorsService.name);
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly queueService: NotificationsQueueService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* List all advisors with attached product count and leads count
|
||||
*/
|
||||
async listAdvisors() {
|
||||
const advisors = await this.prisma.advisorContact.findMany({
|
||||
orderBy: [{ isDefault: 'desc' }, { createdAt: 'desc' }],
|
||||
include: {
|
||||
_count: {
|
||||
select: {
|
||||
productAdvisors: true,
|
||||
leads: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return advisors.map((a) => ({
|
||||
id: a.id,
|
||||
name: a.name,
|
||||
phone: a.phone,
|
||||
title: a.title,
|
||||
isDefault: a.isDefault,
|
||||
isActive: a.isActive,
|
||||
productsCount: a._count.productAdvisors,
|
||||
leadsCount: a._count.leads,
|
||||
createdAt: a.createdAt,
|
||||
updatedAt: a.updatedAt,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new advisor
|
||||
*/
|
||||
async createAdvisor(dto: CreateAdvisorDto) {
|
||||
if (!dto.name || !dto.phone) {
|
||||
throw new BadRequestException('نام و شماره موبایل مشاور الزامی است.');
|
||||
}
|
||||
|
||||
const cleanPhone = dto.phone.trim();
|
||||
const existing = await this.prisma.advisorContact.findUnique({
|
||||
where: { phone: cleanPhone },
|
||||
});
|
||||
if (existing) {
|
||||
throw new BadRequestException('مشاوری با این شماره تلفن قبلاً ثبت شده است.');
|
||||
}
|
||||
|
||||
// If marked default, unset others first
|
||||
if (dto.isDefault) {
|
||||
await this.prisma.advisorContact.updateMany({
|
||||
where: { isDefault: true },
|
||||
data: { isDefault: false },
|
||||
});
|
||||
}
|
||||
|
||||
const advisor = await this.prisma.advisorContact.create({
|
||||
data: {
|
||||
name: dto.name.trim(),
|
||||
phone: cleanPhone,
|
||||
title: dto.title?.trim() || null,
|
||||
isDefault: Boolean(dto.isDefault),
|
||||
isActive: dto.isActive !== undefined ? Boolean(dto.isActive) : true,
|
||||
},
|
||||
});
|
||||
|
||||
return advisor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update advisor
|
||||
*/
|
||||
async updateAdvisor(id: string, dto: Partial<CreateAdvisorDto>) {
|
||||
const existing = await this.prisma.advisorContact.findUnique({ where: { id } });
|
||||
if (!existing) throw new NotFoundException('مشاور مورد نظر یافت نشد.');
|
||||
|
||||
if (dto.phone && dto.phone !== existing.phone) {
|
||||
const phoneExists = await this.prisma.advisorContact.findUnique({
|
||||
where: { phone: dto.phone.trim() },
|
||||
});
|
||||
if (phoneExists && phoneExists.id !== id) {
|
||||
throw new BadRequestException('شماره تلفن وارد شده برای مشاور دیگری ثبت شده است.');
|
||||
}
|
||||
}
|
||||
|
||||
if (dto.isDefault) {
|
||||
await this.prisma.advisorContact.updateMany({
|
||||
where: { isDefault: true, id: { not: id } },
|
||||
data: { isDefault: false },
|
||||
});
|
||||
}
|
||||
|
||||
return this.prisma.advisorContact.update({
|
||||
where: { id },
|
||||
data: {
|
||||
name: dto.name ? dto.name.trim() : undefined,
|
||||
phone: dto.phone ? dto.phone.trim() : undefined,
|
||||
title: dto.title !== undefined ? dto.title?.trim() || null : undefined,
|
||||
isDefault: dto.isDefault !== undefined ? Boolean(dto.isDefault) : undefined,
|
||||
isActive: dto.isActive !== undefined ? Boolean(dto.isActive) : undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Set advisor as default
|
||||
*/
|
||||
async setDefaultAdvisor(id: string) {
|
||||
const existing = await this.prisma.advisorContact.findUnique({ where: { id } });
|
||||
if (!existing) throw new NotFoundException('مشاور یافت نشد.');
|
||||
|
||||
await this.prisma.advisorContact.updateMany({
|
||||
where: { isDefault: true },
|
||||
data: { isDefault: false },
|
||||
});
|
||||
|
||||
return this.prisma.advisorContact.update({
|
||||
where: { id },
|
||||
data: { isDefault: true, isActive: true },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete advisor
|
||||
*/
|
||||
async deleteAdvisor(id: string) {
|
||||
const existing = await this.prisma.advisorContact.findUnique({ where: { id } });
|
||||
if (!existing) throw new NotFoundException('مشاور یافت نشد.');
|
||||
|
||||
await this.prisma.advisorContact.delete({ where: { id } });
|
||||
return { success: true, message: 'مشاور با موفقیت حذف شد.' };
|
||||
}
|
||||
|
||||
/**
|
||||
* List customer leads (contact requests)
|
||||
*/
|
||||
async listLeads(query: { page?: number; limit?: number; status?: 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 && query.status !== 'ALL') {
|
||||
where.status = query.status;
|
||||
}
|
||||
if (query.search) {
|
||||
where.OR = [
|
||||
{ firstName: { contains: query.search, mode: 'insensitive' } },
|
||||
{ lastName: { contains: query.search, mode: 'insensitive' } },
|
||||
{ phone: { contains: query.search, mode: 'insensitive' } },
|
||||
];
|
||||
}
|
||||
|
||||
const [items, total] = await Promise.all([
|
||||
this.prisma.lead.findMany({
|
||||
where,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
skip,
|
||||
take: limit,
|
||||
include: {
|
||||
advisor: {
|
||||
select: { id: true, name: true, phone: true, title: true },
|
||||
},
|
||||
product: {
|
||||
select: { id: true, nameFa: true, nameEn: true, slug: true, imageUrl: true },
|
||||
},
|
||||
},
|
||||
}),
|
||||
this.prisma.lead.count({ where }),
|
||||
]);
|
||||
|
||||
const [pendingCount, contactedCount, cancelledCount] = await Promise.all([
|
||||
this.prisma.lead.count({ where: { status: 'PENDING' } }),
|
||||
this.prisma.lead.count({ where: { status: 'CONTACTED' } }),
|
||||
this.prisma.lead.count({ where: { status: 'CANCELLED' } }),
|
||||
]);
|
||||
|
||||
return {
|
||||
items,
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages: Math.ceil(total / limit) || 1,
|
||||
stats: {
|
||||
total,
|
||||
pending: pendingCount,
|
||||
contacted: contactedCount,
|
||||
cancelled: cancelledCount,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Update lead status or notes
|
||||
*/
|
||||
async updateLeadStatus(id: string, status: string, notes?: string) {
|
||||
const lead = await this.prisma.lead.findUnique({ where: { id } });
|
||||
if (!lead) throw new NotFoundException('درخواست تماس یافت نشد.');
|
||||
|
||||
return this.prisma.lead.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status,
|
||||
notes: notes !== undefined ? notes : undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete lead
|
||||
*/
|
||||
async deleteLead(id: string) {
|
||||
await this.prisma.lead.delete({ where: { id } });
|
||||
return { success: true, message: 'درخواست تماس با موفقیت حذف شد.' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Public Lead Creation from Website
|
||||
*/
|
||||
async handlePublicLead(dto: CreateLeadDto) {
|
||||
if (!dto.firstName || !dto.lastName || !dto.phone) {
|
||||
throw new BadRequestException('نام، نام خانوادگی و شماره موبایل الزامی است.');
|
||||
}
|
||||
|
||||
const cleanPhone = dto.phone.replace(/\s+/g, '').replace(/^(\+98|0098)/, '0');
|
||||
if (!/^09\d{9}$/.test(cleanPhone)) {
|
||||
throw new BadRequestException('شماره موبایل وارد شده نامعتبر است (مثال: ۰۹۱۲۳۴۵۶۷۸۹).');
|
||||
}
|
||||
|
||||
// Rate limit: max 3 requests per 24 hours per phone
|
||||
const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
|
||||
const countToday = await this.prisma.lead.count({
|
||||
where: {
|
||||
phone: cleanPhone,
|
||||
createdAt: { gte: oneDayAgo },
|
||||
},
|
||||
});
|
||||
|
||||
if (countToday >= 3) {
|
||||
throw new BadRequestException('حداکثر تعداد درخواست روزانه برای این شماره تکمیل شده است. همکاران ما به زودی با شما تماس خواهند گرفت.');
|
||||
}
|
||||
|
||||
// Resolve advisor: Product-specific -> Default advisor -> First active advisor
|
||||
let advisor = null;
|
||||
let product = null;
|
||||
|
||||
if (dto.productId) {
|
||||
product = await this.prisma.product.findUnique({
|
||||
where: { id: dto.productId },
|
||||
select: { id: true, nameFa: true },
|
||||
});
|
||||
|
||||
const pa = await this.prisma.productAdvisor.findFirst({
|
||||
where: { productId: dto.productId },
|
||||
include: { advisor: true },
|
||||
});
|
||||
if (pa?.advisor?.isActive) {
|
||||
advisor = pa.advisor;
|
||||
}
|
||||
}
|
||||
|
||||
if (!advisor) {
|
||||
advisor = await this.prisma.advisorContact.findFirst({
|
||||
where: { isDefault: true, isActive: true },
|
||||
});
|
||||
}
|
||||
|
||||
if (!advisor) {
|
||||
advisor = await this.prisma.advisorContact.findFirst({
|
||||
where: { isActive: true },
|
||||
});
|
||||
}
|
||||
|
||||
// Create lead record in DB
|
||||
const lead = await this.prisma.lead.create({
|
||||
data: {
|
||||
firstName: dto.firstName.trim(),
|
||||
lastName: dto.lastName.trim(),
|
||||
phone: cleanPhone,
|
||||
productId: dto.productId || null,
|
||||
advisorId: advisor?.id || null,
|
||||
status: 'PENDING',
|
||||
},
|
||||
});
|
||||
|
||||
// Enqueue SMS notification to Advisor
|
||||
if (advisor) {
|
||||
const productName = product ? product.nameFa : 'مشاوره عمومی';
|
||||
const advisorMsg = `مشاور گرامی، درخواست تماس جدیدی از ${dto.firstName} ${dto.lastName} (${cleanPhone}) برای «${productName}» ثبت شد. لطفاً در اسرع وقت تماس حاصل فرمایید.`;
|
||||
await this.queueService.enqueue({
|
||||
channel: 'SMS',
|
||||
recipient: advisor.phone,
|
||||
event: 'NEW_LEAD',
|
||||
content: advisorMsg,
|
||||
idempotencyKey: `lead_advisor_${lead.id}`,
|
||||
});
|
||||
}
|
||||
|
||||
// Enqueue confirmation SMS to Client
|
||||
const clientMsg = `${dto.firstName} عزیز، درخواست مشاوره شما در کنینا ثبت شد. مشاوران تخصصی ما به زودی با شما تماس خواهند گرفت.`;
|
||||
await this.queueService.enqueue({
|
||||
channel: 'SMS',
|
||||
recipient: cleanPhone,
|
||||
event: 'LEAD_CONFIRMATION',
|
||||
content: clientMsg,
|
||||
idempotencyKey: `lead_client_${lead.id}`,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'درخواست مشاوره شما با موفقیت ثبت شد. مشاور ما به زودی با شما تماس خواهد گرفت.',
|
||||
leadId: lead.id,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import {
|
||||
Controller,
|
||||
Post,
|
||||
Body,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { AdvisorsService, CreateLeadDto } from './advisors.service';
|
||||
|
||||
@Controller('public')
|
||||
export class PublicLeadController {
|
||||
constructor(private readonly advisorsService: AdvisorsService) {}
|
||||
|
||||
@Post('lead')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async createLead(@Body() dto: CreateLeadDto) {
|
||||
const result = await this.advisorsService.handlePublicLead(dto);
|
||||
return {
|
||||
ok: true,
|
||||
success: true,
|
||||
message: result.message,
|
||||
leadId: result.leadId,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,8 @@ import { DoctorsModule } from "./doctors/doctors.module";
|
||||
import { FaqModule } from "./faq/faq.module";
|
||||
import { MenuModule } from "./menu/menu.module";
|
||||
import { RevalidationModule } from "./common/revalidation/revalidation.module";
|
||||
import { NotificationsModule } from "./notifications/notifications.module";
|
||||
import { AdvisorsModule } from "./advisors/advisors.module";
|
||||
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
|
||||
@@ -79,6 +81,8 @@ import { Request, Response, NextFunction } from "express";
|
||||
B2BModule,
|
||||
FaqModule,
|
||||
MenuModule,
|
||||
NotificationsModule,
|
||||
AdvisorsModule,
|
||||
],
|
||||
controllers: [MetricsController],
|
||||
providers: [
|
||||
|
||||
@@ -0,0 +1,387 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import * as net from 'net';
|
||||
import * as tls from 'tls';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
export interface SmtpConfig {
|
||||
enabled: boolean;
|
||||
host: string;
|
||||
port: number;
|
||||
secure?: boolean; // true for 465 (TLS), false for 587/25 (STARTTLS)
|
||||
user: string;
|
||||
password: string;
|
||||
fromName: string;
|
||||
fromEmail: string;
|
||||
}
|
||||
|
||||
export interface SendMailOptions {
|
||||
to: string;
|
||||
subject: string;
|
||||
text?: string;
|
||||
html?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class EmailService {
|
||||
private readonly logger = new Logger(EmailService.name);
|
||||
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
/**
|
||||
* Read SMTP configuration from DB Setting table with fallback to env variables
|
||||
*/
|
||||
async getConfig(): Promise<SmtpConfig> {
|
||||
try {
|
||||
const setting = await this.prisma.setting.findFirst({
|
||||
where: { category: 'email' },
|
||||
});
|
||||
const dbConfig = (setting?.value as Record<string, any>) || {};
|
||||
|
||||
return {
|
||||
enabled: dbConfig.enabled !== undefined ? Boolean(dbConfig.enabled) : true,
|
||||
host: dbConfig.host || process.env.SMTP_HOST || 'mail.canina.ir',
|
||||
port: Number(dbConfig.port || process.env.SMTP_PORT || 587),
|
||||
secure: dbConfig.secure !== undefined ? Boolean(dbConfig.secure) : Number(dbConfig.port || 587) === 465,
|
||||
user: dbConfig.user || process.env.SMTP_USER || '',
|
||||
password: dbConfig.password || process.env.SMTP_PASSWORD || '',
|
||||
fromName: dbConfig.fromName || process.env.SMTP_FROM_NAME || 'کنینا ایران',
|
||||
fromEmail: dbConfig.fromEmail || process.env.SMTP_FROM_EMAIL || 'info@canina.ir',
|
||||
};
|
||||
} catch (err: any) {
|
||||
this.logger.error(`Error loading email config: ${err?.message}`);
|
||||
return {
|
||||
enabled: true,
|
||||
host: process.env.SMTP_HOST || 'mail.canina.ir',
|
||||
port: Number(process.env.SMTP_PORT || 587),
|
||||
secure: Number(process.env.SMTP_PORT || 587) === 465,
|
||||
user: process.env.SMTP_USER || '',
|
||||
password: process.env.SMTP_PASSWORD || '',
|
||||
fromName: 'کنینا ایران',
|
||||
fromEmail: 'info@canina.ir',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save SMTP configuration to database
|
||||
*/
|
||||
async saveConfig(dto: Partial<SmtpConfig>): Promise<SmtpConfig> {
|
||||
const current = await this.getConfig();
|
||||
const updated: SmtpConfig = {
|
||||
...current,
|
||||
...dto,
|
||||
port: Number(dto.port ?? current.port),
|
||||
secure: dto.secure ?? (Number(dto.port ?? current.port) === 465),
|
||||
};
|
||||
|
||||
const existing = await this.prisma.setting.findFirst({ where: { category: 'email' } });
|
||||
if (existing) {
|
||||
await this.prisma.setting.update({
|
||||
where: { id: existing.id },
|
||||
data: { value: updated as any },
|
||||
});
|
||||
} else {
|
||||
await this.prisma.setting.create({
|
||||
data: {
|
||||
category: 'email',
|
||||
key: 'smtp_config',
|
||||
value: updated as any,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return updated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test SMTP connection with the given or stored configuration
|
||||
*/
|
||||
async testConnection(customConfig?: Partial<SmtpConfig>): Promise<{ success: boolean; message: string; banner?: string }> {
|
||||
const config = customConfig ? { ...(await this.getConfig()), ...customConfig } : await this.getConfig();
|
||||
|
||||
if (!config.host || !config.port) {
|
||||
return { success: false, message: 'آدرس هاست و پورت SMTP الزامی است.' };
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const isExplicitTls = config.secure || config.port === 465;
|
||||
let buffer = '';
|
||||
let stage = 0; // 0=greet, 1=ehlo, 2=auth_login, 3=user, 4=pass, 5=quit
|
||||
let banner = '';
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
socket.destroy();
|
||||
} catch {}
|
||||
resolve({ success: false, message: 'تایماوت در اتصال به سرور SMTP (بیش از ۱۰ ثانیه)' });
|
||||
}, 10000);
|
||||
|
||||
const cleanup = (res: { success: boolean; message: string; banner?: string }) => {
|
||||
clearTimeout(timer);
|
||||
try {
|
||||
socket.end();
|
||||
socket.destroy();
|
||||
} catch {}
|
||||
resolve(res);
|
||||
};
|
||||
|
||||
const handleData = (chunk: Buffer) => {
|
||||
buffer += chunk.toString('utf8');
|
||||
const lines = buffer.split('\r\n');
|
||||
buffer = lines.pop() || '';
|
||||
|
||||
for (const line of lines) {
|
||||
if (!line) continue;
|
||||
const code = parseInt(line.substring(0, 3), 10);
|
||||
const isFinal = line.charAt(3) === ' ';
|
||||
|
||||
if (!isFinal) continue; // Multi-line response continuation
|
||||
|
||||
if (stage === 0) {
|
||||
banner = line;
|
||||
if (code >= 200 && code < 300) {
|
||||
stage = 1;
|
||||
socket.write(`EHLO canina.ir\r\n`);
|
||||
} else {
|
||||
return cleanup({ success: false, message: `پاسخ ناموفق از سرور: ${line}`, banner });
|
||||
}
|
||||
} else if (stage === 1) {
|
||||
if (code >= 200 && code < 300) {
|
||||
if (config.user && config.password) {
|
||||
stage = 2;
|
||||
socket.write('AUTH LOGIN\r\n');
|
||||
} else {
|
||||
stage = 5;
|
||||
socket.write('QUIT\r\n');
|
||||
return cleanup({ success: true, message: 'اتصال به سرور SMTP بدون احراز هویت با موفقیت برقرار شد.', banner });
|
||||
}
|
||||
} else {
|
||||
return cleanup({ success: false, message: `خطای EHLO: ${line}`, banner });
|
||||
}
|
||||
} else if (stage === 2) {
|
||||
if (code === 334) {
|
||||
stage = 3;
|
||||
socket.write(Buffer.from(config.user).toString('base64') + '\r\n');
|
||||
} else {
|
||||
return cleanup({ success: false, message: `سرور از AUTH LOGIN پشتیبانی نمیکند یا خطا داد: ${line}`, banner });
|
||||
}
|
||||
} else if (stage === 3) {
|
||||
if (code === 334) {
|
||||
stage = 4;
|
||||
socket.write(Buffer.from(config.password).toString('base64') + '\r\n');
|
||||
} else {
|
||||
return cleanup({ success: false, message: `نام کاربری پذیرفته نشد: ${line}`, banner });
|
||||
}
|
||||
} else if (stage === 4) {
|
||||
if (code === 235 || (code >= 200 && code < 300)) {
|
||||
stage = 5;
|
||||
socket.write('QUIT\r\n');
|
||||
return cleanup({ success: true, message: 'اتصال و احراز هویت با سرور SMTP با موفقیت تأیید شد.', banner });
|
||||
} else {
|
||||
return cleanup({ success: false, message: `احراز هویت ناموفق بود (نام کاربری یا رمز عبور اشتباه است): ${line}`, banner });
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let socket: net.Socket;
|
||||
|
||||
try {
|
||||
if (isExplicitTls) {
|
||||
socket = tls.connect({
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
rejectUnauthorized: false,
|
||||
}, () => {});
|
||||
} else {
|
||||
socket = net.connect({
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
}, () => {});
|
||||
}
|
||||
|
||||
socket.on('data', handleData);
|
||||
socket.on('error', (err) => {
|
||||
cleanup({ success: false, message: `خطای شبکه در ارتباط با ${config.host}:${config.port} - ${err.message}` });
|
||||
});
|
||||
} catch (err: any) {
|
||||
cleanup({ success: false, message: `خطا در باز کردن سوکت: ${err?.message}` });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a MIME Email message through SMTP
|
||||
*/
|
||||
async sendMail(options: SendMailOptions, customConfig?: Partial<SmtpConfig>): Promise<{ success: boolean; messageId?: string; error?: string }> {
|
||||
const config = customConfig ? { ...(await this.getConfig()), ...customConfig } : await this.getConfig();
|
||||
|
||||
if (!config.enabled) {
|
||||
return { success: false, error: 'سرویس ارسال ایمیل در تنظیمات غیرفعال است.' };
|
||||
}
|
||||
|
||||
if (!config.host || !options.to) {
|
||||
return { success: false, error: 'هاست SMTP یا آدرس گیرنده مشخص نشده است.' };
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const isExplicitTls = config.secure || config.port === 465;
|
||||
let buffer = '';
|
||||
let stage = 0; // 0=greet, 1=ehlo, 2=auth_login, 3=user, 4=pass, 5=mail_from, 6=rcpt_to, 7=data_cmd, 8=data_body, 9=quit
|
||||
const messageId = `<${Date.now()}.${Math.random().toString(36).substring(2)}@${config.host}>`;
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
socket.destroy();
|
||||
} catch {}
|
||||
resolve({ success: false, error: 'تایماوت ارسال ایمیل (۱۵ ثانیه)' });
|
||||
}, 15000);
|
||||
|
||||
const cleanup = (res: { success: boolean; messageId?: string; error?: string }) => {
|
||||
clearTimeout(timer);
|
||||
try {
|
||||
socket.end();
|
||||
socket.destroy();
|
||||
} catch {}
|
||||
resolve(res);
|
||||
};
|
||||
|
||||
const handleData = (chunk: Buffer) => {
|
||||
buffer += chunk.toString('utf8');
|
||||
const lines = buffer.split('\r\n');
|
||||
buffer = lines.pop() || '';
|
||||
|
||||
for (const line of lines) {
|
||||
if (!line) continue;
|
||||
const code = parseInt(line.substring(0, 3), 10);
|
||||
const isFinal = line.charAt(3) === ' ';
|
||||
|
||||
if (!isFinal) continue;
|
||||
|
||||
if (stage === 0) {
|
||||
if (code >= 200 && code < 300) {
|
||||
stage = 1;
|
||||
socket.write(`EHLO canina.ir\r\n`);
|
||||
} else {
|
||||
return cleanup({ success: false, error: `پاسخ سرور: ${line}` });
|
||||
}
|
||||
} else if (stage === 1) {
|
||||
if (code >= 200 && code < 300) {
|
||||
if (config.user && config.password) {
|
||||
stage = 2;
|
||||
socket.write('AUTH LOGIN\r\n');
|
||||
} else {
|
||||
stage = 5;
|
||||
socket.write(`MAIL FROM:<${config.fromEmail}>\r\n`);
|
||||
}
|
||||
} else {
|
||||
return cleanup({ success: false, error: `خطای EHLO: ${line}` });
|
||||
}
|
||||
} else if (stage === 2) {
|
||||
if (code === 334) {
|
||||
stage = 3;
|
||||
socket.write(Buffer.from(config.user).toString('base64') + '\r\n');
|
||||
} else {
|
||||
return cleanup({ success: false, error: `خطای احراز هویت: ${line}` });
|
||||
}
|
||||
} else if (stage === 3) {
|
||||
if (code === 334) {
|
||||
stage = 4;
|
||||
socket.write(Buffer.from(config.password).toString('base64') + '\r\n');
|
||||
} else {
|
||||
return cleanup({ success: false, error: `نام کاربری رد شد: ${line}` });
|
||||
}
|
||||
} else if (stage === 4) {
|
||||
if (code === 235 || (code >= 200 && code < 300)) {
|
||||
stage = 5;
|
||||
socket.write(`MAIL FROM:<${config.fromEmail}>\r\n`);
|
||||
} else {
|
||||
return cleanup({ success: false, error: `رمز عبور رد شد: ${line}` });
|
||||
}
|
||||
} else if (stage === 5) {
|
||||
if (code >= 200 && code < 300) {
|
||||
stage = 6;
|
||||
socket.write(`RCPT TO:<${options.to}>\r\n`);
|
||||
} else {
|
||||
return cleanup({ success: false, error: `آدرس فرستنده رد شد: ${line}` });
|
||||
}
|
||||
} else if (stage === 6) {
|
||||
if (code >= 200 && code < 300) {
|
||||
stage = 7;
|
||||
socket.write('DATA\r\n');
|
||||
} else {
|
||||
return cleanup({ success: false, error: `آدرس گیرنده رد شد: ${line}` });
|
||||
}
|
||||
} else if (stage === 7) {
|
||||
if (code === 354) {
|
||||
stage = 8;
|
||||
const encodedSubject = `=?UTF-8?B?${Buffer.from(options.subject).toString('base64')}?=`;
|
||||
const encodedFromName = `=?UTF-8?B?${Buffer.from(config.fromName).toString('base64')}?=`;
|
||||
const boundary = `boundary_${Date.now()}`;
|
||||
|
||||
let emailBody = '';
|
||||
emailBody += `From: ${encodedFromName} <${config.fromEmail}>\r\n`;
|
||||
emailBody += `To: <${options.to}>\r\n`;
|
||||
emailBody += `Subject: ${encodedSubject}\r\n`;
|
||||
emailBody += `Message-ID: ${messageId}\r\n`;
|
||||
emailBody += `Date: ${new Date().toUTCString()}\r\n`;
|
||||
emailBody += `MIME-Version: 1.0\r\n`;
|
||||
emailBody += `Content-Type: multipart/alternative; boundary="${boundary}"\r\n\r\n`;
|
||||
|
||||
if (options.text) {
|
||||
emailBody += `--${boundary}\r\n`;
|
||||
emailBody += `Content-Type: text/plain; charset=UTF-8\r\n`;
|
||||
emailBody += `Content-Transfer-Encoding: base64\r\n\r\n`;
|
||||
emailBody += Buffer.from(options.text).toString('base64') + '\r\n\r\n';
|
||||
}
|
||||
|
||||
const htmlContent = options.html || options.text || '';
|
||||
emailBody += `--${boundary}\r\n`;
|
||||
emailBody += `Content-Type: text/html; charset=UTF-8\r\n`;
|
||||
emailBody += `Content-Transfer-Encoding: base64\r\n\r\n`;
|
||||
emailBody += Buffer.from(htmlContent).toString('base64') + '\r\n\r\n';
|
||||
|
||||
emailBody += `--${boundary}--\r\n.\r\n`;
|
||||
|
||||
socket.write(emailBody);
|
||||
} else {
|
||||
return cleanup({ success: false, error: `دستور DATA رد شد: ${line}` });
|
||||
}
|
||||
} else if (stage === 8) {
|
||||
if (code >= 200 && code < 300) {
|
||||
stage = 9;
|
||||
socket.write('QUIT\r\n');
|
||||
return cleanup({ success: true, messageId });
|
||||
} else {
|
||||
return cleanup({ success: false, error: `رد شدن ارسال محتوا: ${line}` });
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let socket: net.Socket;
|
||||
|
||||
try {
|
||||
if (isExplicitTls) {
|
||||
socket = tls.connect({
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
rejectUnauthorized: false,
|
||||
}, () => {});
|
||||
} else {
|
||||
socket = net.connect({
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
}, () => {});
|
||||
}
|
||||
|
||||
socket.on('data', handleData);
|
||||
socket.on('error', (err) => {
|
||||
cleanup({ success: false, error: `خطای ارسال: ${err.message}` });
|
||||
});
|
||||
} catch (err: any) {
|
||||
cleanup({ success: false, error: `خطا در باز کردن اتصال: ${err?.message}` });
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { NotificationsQueueService } from './notifications-queue.service';
|
||||
import { EmailService } from './email.service';
|
||||
import { SmsService } from '../common/services/sms.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
describe('NotificationsQueueService', () => {
|
||||
let service: NotificationsQueueService;
|
||||
let prisma: any;
|
||||
let emailService: any;
|
||||
let smsService: any;
|
||||
|
||||
beforeEach(async () => {
|
||||
prisma = {
|
||||
notificationQueue: {
|
||||
findUnique: jest.fn(),
|
||||
create: jest.fn(),
|
||||
update: jest.fn(),
|
||||
findMany: jest.fn(),
|
||||
count: jest.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
emailService = {
|
||||
sendMail: jest.fn().mockResolvedValue({ success: true, messageId: 'msg-123' }),
|
||||
};
|
||||
|
||||
smsService = {
|
||||
sendPatternSms: jest.fn().mockResolvedValue(true),
|
||||
sendSms: jest.fn().mockResolvedValue(true),
|
||||
};
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
NotificationsQueueService,
|
||||
{ provide: PrismaService, useValue: prisma },
|
||||
{ provide: EmailService, useValue: emailService },
|
||||
{ provide: SmsService, useValue: smsService },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<NotificationsQueueService>(NotificationsQueueService);
|
||||
});
|
||||
|
||||
it('should enqueue notification and preserve idempotency', async () => {
|
||||
prisma.notificationQueue.findUnique.mockResolvedValueOnce(null);
|
||||
prisma.notificationQueue.create.mockResolvedValueOnce({
|
||||
id: 'queue-1',
|
||||
channel: 'EMAIL',
|
||||
recipient: 'user@example.com',
|
||||
event: 'ORDER_CREATED',
|
||||
content: 'Hello World',
|
||||
idempotencyKey: 'idemp-1',
|
||||
status: 'QUEUED',
|
||||
attempts: 0,
|
||||
});
|
||||
|
||||
const res = await service.enqueue({
|
||||
channel: 'EMAIL',
|
||||
recipient: 'user@example.com',
|
||||
event: 'ORDER_CREATED',
|
||||
content: 'Hello World',
|
||||
idempotencyKey: 'idemp-1',
|
||||
});
|
||||
|
||||
expect(prisma.notificationQueue.findUnique).toHaveBeenCalledWith({ where: { idempotencyKey: 'idemp-1' } });
|
||||
expect(prisma.notificationQueue.create).toHaveBeenCalled();
|
||||
expect(res.id).toBe('queue-1');
|
||||
});
|
||||
|
||||
it('should return existing notification if idempotency key exists', async () => {
|
||||
const existing = {
|
||||
id: 'existing-1',
|
||||
channel: 'SMS',
|
||||
recipient: '09121111111',
|
||||
event: 'OTP',
|
||||
content: '12345',
|
||||
idempotencyKey: 'idemp-2',
|
||||
status: 'SENT',
|
||||
};
|
||||
prisma.notificationQueue.findUnique.mockResolvedValueOnce(existing);
|
||||
|
||||
const res = await service.enqueue({
|
||||
channel: 'SMS',
|
||||
recipient: '09121111111',
|
||||
event: 'OTP',
|
||||
content: '12345',
|
||||
idempotencyKey: 'idemp-2',
|
||||
});
|
||||
|
||||
expect(prisma.notificationQueue.create).not.toHaveBeenCalled();
|
||||
expect(res.id).toBe('existing-1');
|
||||
});
|
||||
|
||||
it('should process email queue item and mark as SENT', async () => {
|
||||
const item = {
|
||||
id: 'item-1',
|
||||
channel: 'EMAIL',
|
||||
recipient: 'user@example.com',
|
||||
subject: 'Test Subject',
|
||||
content: 'Test Body',
|
||||
payload: {},
|
||||
status: 'QUEUED',
|
||||
attempts: 0,
|
||||
maxAttempts: 3,
|
||||
};
|
||||
prisma.notificationQueue.findUnique.mockResolvedValueOnce(item);
|
||||
prisma.notificationQueue.update.mockResolvedValue({});
|
||||
|
||||
await service.processItem('item-1');
|
||||
|
||||
expect(emailService.sendMail).toHaveBeenCalledWith({
|
||||
to: 'user@example.com',
|
||||
subject: 'Test Subject',
|
||||
text: 'Test Body',
|
||||
html: expect.stringContaining('Test Body'),
|
||||
});
|
||||
expect(prisma.notificationQueue.update).toHaveBeenCalledWith({
|
||||
where: { id: 'item-1' },
|
||||
data: expect.objectContaining({ status: 'SENT' }),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,273 @@
|
||||
import { Injectable, Logger, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { EmailService } from './email.service';
|
||||
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 res = await this.emailService.sendMail({
|
||||
to: item.recipient,
|
||||
subject: item.subject || 'اطلاعیه کنینا ایران',
|
||||
text: item.content,
|
||||
html: payloadObj.html || `<div style="font-family:Tahoma,sans-serif;direction:rtl;padding:20px;">${item.content.replace(/\n/g, '<br/>')}</div>`,
|
||||
});
|
||||
|
||||
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)) {
|
||||
await this.smsService.sendPatternSms({
|
||||
to: item.recipient,
|
||||
bodyId: Number(payloadObj.patternId),
|
||||
args: payloadObj.args,
|
||||
type: item.event,
|
||||
});
|
||||
} else {
|
||||
await this.smsService.sendSms(item.recipient, item.content);
|
||||
}
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
UseGuards,
|
||||
BadRequestException,
|
||||
} from '@nestjs/common';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { EmailService, SmtpConfig } from './email.service';
|
||||
import { NotificationsQueueService } from './notifications-queue.service';
|
||||
import { SmsService } from '../common/services/sms.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
|
||||
@Controller('admin/notifications')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
export class NotificationsController {
|
||||
constructor(
|
||||
private readonly emailService: EmailService,
|
||||
private readonly queueService: NotificationsQueueService,
|
||||
private readonly smsService: SmsService,
|
||||
private readonly prisma: PrismaService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Get notification settings (Email & SMS)
|
||||
*/
|
||||
@Get('config')
|
||||
async getConfig() {
|
||||
const [email, sms] = await Promise.all([
|
||||
this.emailService.getConfig(),
|
||||
this.smsService.getSmsConfig(),
|
||||
]);
|
||||
|
||||
// Mask password for security
|
||||
const maskedEmail = {
|
||||
...email,
|
||||
password: email.password ? '••••••••' : '',
|
||||
};
|
||||
|
||||
const maskedSms = {
|
||||
...sms,
|
||||
password: sms.password ? '••••••••' : '',
|
||||
};
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
email: maskedEmail,
|
||||
sms: maskedSms,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Update SMTP Email config
|
||||
*/
|
||||
@Put('email-config')
|
||||
async updateEmailConfig(@Body() dto: Partial<SmtpConfig>) {
|
||||
// If password is masked, don't overwrite with dots
|
||||
if (dto.password && dto.password.includes('•')) {
|
||||
delete dto.password;
|
||||
}
|
||||
|
||||
const saved = await this.emailService.saveConfig(dto);
|
||||
return {
|
||||
success: true,
|
||||
message: 'تنظیمات ایمیل با موفقیت ذخیره شد.',
|
||||
data: {
|
||||
...saved,
|
||||
password: saved.password ? '••••••••' : '',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Test SMTP connection live
|
||||
*/
|
||||
@Post('test-smtp')
|
||||
async testSmtp(@Body() customConfig?: Partial<SmtpConfig>) {
|
||||
if (customConfig?.password && customConfig.password.includes('•')) {
|
||||
delete customConfig.password;
|
||||
}
|
||||
|
||||
const res = await this.emailService.testConnection(customConfig);
|
||||
return {
|
||||
success: res.success,
|
||||
message: res.message,
|
||||
banner: res.banner,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Send test email
|
||||
*/
|
||||
@Post('send-test-email')
|
||||
async sendTestEmail(@Body() body: { to: string; subject?: string; message?: string }) {
|
||||
if (!body.to) throw new BadRequestException('آدرس ایمیل مقصد الزامی است.');
|
||||
|
||||
const res = await this.emailService.sendMail({
|
||||
to: body.to,
|
||||
subject: body.subject || 'تست اتصال ایمیل - کنینا ایران',
|
||||
text: body.message || 'این یک ایمیل آزمایشی جهت بررسی صحت تنظیمات سرور SMTP در فروشگاه کنینا است.',
|
||||
html: `
|
||||
<div style="font-family:Tahoma,sans-serif;direction:rtl;background:#f3f4f6;padding:30px;color:#1f2937;">
|
||||
<div style="max-width:550px;margin:0 auto;background:#fff;border-radius:12px;padding:24px;border:1px solid #e5e7eb;">
|
||||
<h2 style="color:#7c3aed;margin-top:0;">کنینا ایران | تست سرور ایمیل</h2>
|
||||
<p>${body.message || 'این یک ایمیل آزمایشی جهت بررسی صحت تنظیمات سرور SMTP در فروشگاه کنینا است.'}</p>
|
||||
<hr style="border:0;border-top:1px solid #f3f4f6;margin:20px 0;" />
|
||||
<small style="color:#9ca3af;">زمان ارسال: ${new Date().toLocaleString('fa-IR')}</small>
|
||||
</div>
|
||||
</div>
|
||||
`,
|
||||
});
|
||||
|
||||
if (!res.success) {
|
||||
throw new BadRequestException(res.error || 'ارسال ایمیل تستی ناموفق بود.');
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `ایمیل تستی با موفقیت به ${body.to} ارسال شد.`,
|
||||
messageId: res.messageId,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Send test SMS
|
||||
*/
|
||||
@Post('send-test-sms')
|
||||
async sendTestSms(@Body() body: { to: string; message: string }) {
|
||||
if (!body.to || !body.message) {
|
||||
throw new BadRequestException('شماره موبایل و متن پیام الزامی است.');
|
||||
}
|
||||
|
||||
const res = await this.smsService.sendSms(body.to, body.message);
|
||||
if (!res) throw new BadRequestException('ارسال پیامک تستی ناموفق بود.');
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `پیامک تستی با موفقیت به ${body.to} ارسال شد.`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Manual targeted notification send
|
||||
*/
|
||||
@Post('manual-send')
|
||||
async manualSend(
|
||||
@Body()
|
||||
body: {
|
||||
channel: 'SMS' | 'EMAIL';
|
||||
targetType: 'single' | 'all_users' | 'custom_list';
|
||||
recipient?: string;
|
||||
recipients?: string[];
|
||||
subject?: string;
|
||||
content: string;
|
||||
},
|
||||
) {
|
||||
if (!body.channel || !body.content) {
|
||||
throw new BadRequestException('کانال ارسال و متن پیام الزامی است.');
|
||||
}
|
||||
|
||||
let targetList: string[] = [];
|
||||
|
||||
if (body.targetType === 'single') {
|
||||
if (!body.recipient) throw new BadRequestException('گیرنده پیام مشخص نشده است.');
|
||||
targetList = [body.recipient.trim()];
|
||||
} else if (body.targetType === 'custom_list') {
|
||||
if (!Array.isArray(body.recipients) || !body.recipients.length) {
|
||||
throw new BadRequestException('لیست گیرندگان خالی است.');
|
||||
}
|
||||
targetList = body.recipients.map((r) => r.trim()).filter(Boolean);
|
||||
} else if (body.targetType === 'all_users') {
|
||||
const users = await this.prisma.user.findMany({
|
||||
select: { mobile: true, email: true },
|
||||
take: 1000,
|
||||
});
|
||||
|
||||
if (body.channel === 'SMS') {
|
||||
targetList = users.map((u) => u.mobile).filter(Boolean) as string[];
|
||||
} else {
|
||||
targetList = users.map((u) => u.email).filter(Boolean) as string[];
|
||||
}
|
||||
}
|
||||
|
||||
if (!targetList.length) {
|
||||
throw new BadRequestException('هیچ گیرنده معتبری برای ارسال یافت نشد.');
|
||||
}
|
||||
|
||||
// Enqueue all items into durable queue
|
||||
const queuedItems = await Promise.all(
|
||||
targetList.map((rec) =>
|
||||
this.queueService.enqueue({
|
||||
channel: body.channel,
|
||||
recipient: rec,
|
||||
event: 'MANUAL_TARGETED_SEND',
|
||||
subject: body.subject,
|
||||
content: body.content,
|
||||
idempotencyKey: `manual_${body.channel}_${rec}_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: `${queuedItems.length} پیام با موفقیت در صف ارسال قرار گرفت.`,
|
||||
count: queuedItems.length,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get queue items and statistics
|
||||
*/
|
||||
@Get('queue')
|
||||
async getQueue(
|
||||
@Query('page') page?: number,
|
||||
@Query('limit') limit?: number,
|
||||
@Query('status') status?: string,
|
||||
@Query('channel') channel?: string,
|
||||
@Query('search') search?: string,
|
||||
) {
|
||||
const data = await this.queueService.getQueue({ page, limit, status, channel, search });
|
||||
return {
|
||||
success: true,
|
||||
data,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Retry failed queue item
|
||||
*/
|
||||
@Post('queue/:id/retry')
|
||||
async retryQueueItem(@Param('id') id: string) {
|
||||
const retried = await this.queueService.retry(id);
|
||||
return {
|
||||
success: true,
|
||||
message: 'پیام مجدداً در صف ارسال قرار گرفت.',
|
||||
data: retried,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get notification templates & event definitions
|
||||
*/
|
||||
@Get('templates')
|
||||
async getTemplates() {
|
||||
const templates = await this.prisma.notificationTemplate.findMany({
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
|
||||
const defaultEvents = [
|
||||
{ event: 'ORDER_CREATED', name: 'ثبت سفارش جدید', variables: ['order_id', 'customer_name', 'total_amount'] },
|
||||
{ event: 'PAYMENT_SUCCESS', name: 'پرداخت موفق سفارش', variables: ['order_id', 'track_id', 'amount'] },
|
||||
{ event: 'ORDER_SHIPPED', name: 'ارسال سفارش پستی', variables: ['order_id', 'tracking_code', 'carrier'] },
|
||||
{ event: 'NEW_LEAD', name: 'درخواست تماس یا مشاوره جدید', variables: ['lead_name', 'phone', 'product_name'] },
|
||||
{ event: 'USER_REGISTERED', name: 'ثبتنام کاربر جدید', variables: ['user_name', 'mobile'] },
|
||||
{ event: 'TICKET_REPLIED', name: 'پاسخ به تیکت پشتیبانی', variables: ['ticket_id', 'user_name'] },
|
||||
];
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
templates,
|
||||
events: defaultEvents,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create or update notification template
|
||||
*/
|
||||
@Post('templates')
|
||||
async upsertTemplate(
|
||||
@Body()
|
||||
dto: {
|
||||
id?: string;
|
||||
channel: 'SMS' | 'EMAIL';
|
||||
event: string;
|
||||
name: string;
|
||||
subject?: string;
|
||||
body: string;
|
||||
patternCode?: string;
|
||||
variables?: string[];
|
||||
recipientType?: string;
|
||||
customRecipient?: string;
|
||||
isActive?: boolean;
|
||||
},
|
||||
) {
|
||||
if (!dto.channel || !dto.event || !dto.name || !dto.body) {
|
||||
throw new BadRequestException('اطلاعات ضروری قالب ناقص است.');
|
||||
}
|
||||
|
||||
const data = {
|
||||
channel: dto.channel,
|
||||
event: dto.event,
|
||||
name: dto.name,
|
||||
subject: dto.subject || null,
|
||||
body: dto.body,
|
||||
patternCode: dto.patternCode || null,
|
||||
variables: dto.variables || [],
|
||||
recipientType: dto.recipientType || 'customer',
|
||||
customRecipient: dto.customRecipient || null,
|
||||
isActive: dto.isActive !== undefined ? dto.isActive : true,
|
||||
};
|
||||
|
||||
let template;
|
||||
if (dto.id) {
|
||||
template = await this.prisma.notificationTemplate.update({
|
||||
where: { id: dto.id },
|
||||
data,
|
||||
});
|
||||
} else {
|
||||
template = await this.prisma.notificationTemplate.upsert({
|
||||
where: {
|
||||
channel_event: {
|
||||
channel: dto.channel,
|
||||
event: dto.event,
|
||||
},
|
||||
},
|
||||
create: data,
|
||||
update: data,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'قالب رویداد با موفقیت ذخیره شد.',
|
||||
data: template,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete template
|
||||
*/
|
||||
@Delete('templates/:id')
|
||||
async deleteTemplate(@Param('id') id: string) {
|
||||
await this.prisma.notificationTemplate.delete({ where: { id } });
|
||||
return {
|
||||
success: true,
|
||||
message: 'قالب رویداد حذف شد.',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PrismaModule } from '../prisma/prisma.module';
|
||||
import { SmsModule } from '../common/sms.module';
|
||||
import { EmailService } from './email.service';
|
||||
import { NotificationsQueueService } from './notifications-queue.service';
|
||||
import { NotificationsController } from './notifications.controller';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule, SmsModule],
|
||||
controllers: [NotificationsController],
|
||||
providers: [EmailService, NotificationsQueueService],
|
||||
exports: [EmailService, NotificationsQueueService],
|
||||
})
|
||||
export class NotificationsModule {}
|
||||
Reference in new issue
Block a user