Files
canina/backend/src/notifications/notifications.controller.ts
T
2026-11-07 07:52:39 +00:00

332 lines
9.9 KiB
TypeScript

import {
Controller,
Get,
Post,
Put,
Delete,
Body,
Param,
Query,
UseGuards,
BadRequestException,
} from '@nestjs/common';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { EmailService } from './email.service';
import { NotificationsQueueService } from './notifications-queue.service';
import { SmsService } from '../common/services/sms.service';
import { PrismaService } from '../prisma/prisma.service';
import {
UpdateEmailConfigDto,
TestSmtpDto,
SendTestEmailDto,
SendTestSmsDto,
ManualSendDto,
CreateTemplateDto,
} from './notifications.dto';
@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: UpdateEmailConfigDto) {
// 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?: TestSmtpDto) {
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: SendTestEmailDto) {
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: SendTestSmsDto) {
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: ManualSendDto) {
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: CreateTemplateDto) {
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: 'قالب رویداد حذف شد.',
};
}
}