feat(notifications): send branded transactional emails for shop events
Deploy Canina / deploy (push) Failing after 1m57s

Add Canina-branded welcome, contact confirmation/admin notify, and order created/paid/shipped emails via support@canina.ir without blocking the SMS flows.
This commit is contained in:
devops committed 2026-11-10 13:27:37 +00:00
1 parent 6fbbd7140d
commit 625c3f5ce2
19 files changed
+331 -20

No files matched your search

+2
View File
@@ -9,6 +9,7 @@ import { AdminModule } from "../admin/admin.module";
import { getJwtSecret } from "./auth.constants";
import { RedisModule } from "../redis/redis.module";
import { NotificationsModule } from "../notifications/notifications.module";
@Module({
imports: [
@@ -16,6 +17,7 @@ import { RedisModule } from "../redis/redis.module";
forwardRef(() => AdminModule),
PassportModule,
RedisModule,
NotificationsModule,
JwtModule.registerAsync({
useFactory: () => ({
secret: getJwtSecret(),
+2
View File
@@ -4,6 +4,7 @@ import { PrismaService } from "../prisma/prisma.service";
import { JwtService } from "@nestjs/jwt";
import { RedisService } from "../redis/redis.service";
import { SmsService } from "../common/services/sms.service";
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
import { BadRequestException } from "@nestjs/common";
describe("AuthService", () => {
@@ -43,6 +44,7 @@ describe("AuthService", () => {
{ provide: JwtService, useValue: mockJwt },
{ provide: RedisService, useValue: mockRedis },
{ provide: SmsService, useValue: mockSms },
{ provide: TransactionalEmailsService, useValue: { sendWelcome: jest.fn().mockResolvedValue(undefined), sendOrderCreated: jest.fn().mockResolvedValue(undefined), sendOrderPaid: jest.fn().mockResolvedValue(undefined), sendOrderShipped: jest.fn().mockResolvedValue(undefined), sendContactConfirmation: jest.fn().mockResolvedValue(undefined), notifyAdminsAboutContact: jest.fn().mockResolvedValue(undefined) } },
],
}).compile();
+9
View File
@@ -11,6 +11,7 @@ import { RedisService } from "../redis/redis.service";
import { SendOtpDto } from "./dto/send-otp.dto";
import { VerifyOtpDto } from "./dto/verify-otp.dto";
import { SmsService } from "../common/services/sms.service";
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
import * as bcrypt from "bcryptjs";
import * as crypto from "crypto";
import { normalizeMobile } from "../common/utils/phone.utils";
@@ -42,6 +43,7 @@ export class AuthService {
private jwtService: JwtService,
private redisService: RedisService,
private smsService: SmsService,
private transactionalEmails: TransactionalEmailsService,
) {}
private async generateTokens(payload: Record<string, any>) {
@@ -257,6 +259,13 @@ export class AuthService {
},
});
// Fire-and-forget welcome email when register provided an address
if (user.email) {
this.transactionalEmails
.sendWelcome(user.email, user.firstName)
.catch(() => {});
}
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role };
const tokens = await this.generateTokens(payload);
+2 -1
View File
@@ -2,9 +2,10 @@ import { Module } from "@nestjs/common";
import { ContactController } from "./contact.controller";
import { ContactService } from "./contact.service";
import { SmsModule } from "../common/sms.module";
import { NotificationsModule } from "../notifications/notifications.module";
@Module({
imports: [SmsModule],
imports: [SmsModule, NotificationsModule],
controllers: [ContactController],
providers: [ContactService],
exports: [ContactService],
@@ -2,6 +2,7 @@ import { Test, TestingModule } from "@nestjs/testing";
import { ContactService, CreateContactSubmissionDto } from "./contact.service";
import { PrismaService } from "../prisma/prisma.service";
import { SmsService } from "../common/services/sms.service";
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
describe("ContactService", () => {
let service: ContactService;
@@ -34,6 +35,17 @@ describe("ContactService", () => {
provide: SmsService,
useValue: mockSmsService,
},
{
provide: TransactionalEmailsService,
useValue: {
sendWelcome: jest.fn().mockResolvedValue(undefined),
sendOrderCreated: jest.fn().mockResolvedValue(undefined),
sendOrderPaid: jest.fn().mockResolvedValue(undefined),
sendOrderShipped: jest.fn().mockResolvedValue(undefined),
sendContactConfirmation: jest.fn().mockResolvedValue(undefined),
notifyAdminsAboutContact: jest.fn().mockResolvedValue(undefined),
},
},
],
}).compile();
+24
View File
@@ -1,6 +1,7 @@
import { Injectable, Logger } from "@nestjs/common";
import { PrismaService } from "../prisma/prisma.service";
import { SmsService } from "../common/services/sms.service";
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
export interface CreateContactSubmissionDto {
name: string;
@@ -25,6 +26,7 @@ export class ContactService {
constructor(
private readonly prisma: PrismaService,
private readonly smsService: SmsService,
private readonly transactionalEmails: TransactionalEmailsService,
) {}
async submitContactForm(dto: CreateContactSubmissionDto) {
@@ -56,6 +58,28 @@ export class ContactService {
);
}
// Email confirmation to submitter + admin notify (non-blocking)
void Promise.resolve(
this.transactionalEmails.notifyAdminsAboutContact({
name: dto.name,
phone: dto.phone,
email: dto.email,
subject: dto.subject,
message: dto.message,
submissionId: submission.id,
}),
).catch(() => {});
if (dto.email) {
void Promise.resolve(
this.transactionalEmails.sendContactConfirmation(
dto.email,
dto.name,
dto.message,
submission.id,
),
).catch(() => {});
}
return {
success: true,
message:
+98
View File
@@ -0,0 +1,98 @@
/**
* Branded HTML wrappers for Canina transactional emails.
* Colors match the storefront tokens in frontend/application/app/globals.css.
*/
const BRAND = {
blue: '#1E4053',
gold: '#F1B646',
teal: '#9BC8CC',
dark: '#060709',
soft: '#F4F7F6',
border: '#E5ECE9',
muted: '#445D60',
} as const;
export function escapeHtml(value: string): string {
return String(value)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
export function textToHtmlParagraphs(text: string): string {
return escapeHtml(text)
.split(/\r?\n/)
.map((line) => (line.trim().length === 0 ? '&nbsp;' : line))
.join('<br/>');
}
export interface CaninaEmailLayoutOptions {
title: string;
bodyHtml: string;
eyebrow?: string;
footerNote?: string;
}
export function renderCaninaEmailLayout(options: CaninaEmailLayoutOptions): string {
const title = escapeHtml(options.title);
const eyebrow = escapeHtml(options.eyebrow || 'CANINA');
const footerNote = escapeHtml(
options.footerNote || 'این پیام از طرف فروشگاه کنینا ارسال شده است.',
);
return `<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${title}</title>
</head>
<body style="margin:0;padding:0;background:${BRAND.soft};color:${BRAND.dark};font-family:Tahoma,Arial,sans-serif;line-height:1.9;font-size:15px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;background:${BRAND.soft};">
<tr>
<td align="center" style="padding:28px 14px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;max-width:600px;background:#ffffff;text-align:right;border:1px solid ${BRAND.border};">
<tr>
<td style="padding:0;height:4px;background:${BRAND.gold};font-size:0;line-height:0;">&nbsp;</td>
</tr>
<tr>
<td style="padding:24px 28px 8px;background:${BRAND.blue};">
<p style="margin:0;font-size:11px;letter-spacing:0.18em;color:${BRAND.teal};">${eyebrow}</p>
<p style="margin:8px 0 0;font-size:22px;font-weight:700;color:#ffffff;">کنینا</p>
<p style="margin:4px 0 0;font-size:13px;color:${BRAND.gold};">مکمل تخصصی حیوانات خانگی</p>
</td>
</tr>
<tr>
<td style="padding:28px;">
<h1 style="margin:0 0 16px;font-size:20px;font-weight:700;color:${BRAND.blue};">${title}</h1>
<div style="color:${BRAND.muted};">${options.bodyHtml}</div>
</td>
</tr>
<tr>
<td style="padding:18px 28px;background:${BRAND.dark};color:#d5dde0;font-size:12px;">
<p style="margin:0;color:#ffffff;font-weight:700;">کنینا ایران</p>
<p style="margin:8px 0 0;">
<a href="mailto:support@canina.ir" style="color:${BRAND.gold};text-decoration:none;" dir="ltr">support@canina.ir</a>
&nbsp;·&nbsp;
<a href="https://canina.ir" style="color:${BRAND.teal};text-decoration:none;" dir="ltr">canina.ir</a>
</p>
<p style="margin:10px 0 0;color:#9aa8ad;">${footerNote}</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>`;
}
export function renderCaninaNotificationEmail(subject: string, content: string): string {
return renderCaninaEmailLayout({
title: subject || 'اطلاعیه کنینا',
bodyHtml: `<p style="margin:0;">${textToHtmlParagraphs(content || '')}</p>`,
});
}
+2 -2
View File
@@ -45,7 +45,7 @@ export class EmailService {
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',
fromEmail: dbConfig.fromEmail || process.env.SMTP_FROM_EMAIL || 'support@canina.ir',
};
} catch (err: any) {
this.logger.error(`Error loading email config: ${err?.message}`);
@@ -57,7 +57,7 @@ export class EmailService {
user: process.env.SMTP_USER || '',
password: process.env.SMTP_PASSWORD || '',
fromName: 'کنینا ایران',
fromEmail: 'info@canina.ir',
fromEmail: 'support@canina.ir',
};
}
}
@@ -115,6 +115,10 @@ describe('NotificationsQueueService', () => {
text: 'Test Body',
html: expect.stringContaining('Test Body'),
});
const sentHtml = String((emailService.sendMail as jest.Mock).mock.calls[0][0].html);
expect(sentHtml).toContain('#1E4053');
expect(sentHtml).toContain('#F1B646');
expect(sentHtml).toContain('support@canina.ir');
expect(prisma.notificationQueue.update).toHaveBeenCalledWith({
where: { id: 'item-1' },
data: expect.objectContaining({ status: 'SENT' }),
@@ -1,6 +1,7 @@
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 {
@@ -104,11 +105,12 @@ export class NotificationsQueueService implements OnModuleInit, OnModuleDestroy
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: item.subject || 'اطلاعیه کنینا ایران',
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>`,
html: payloadObj.html || renderCaninaNotificationEmail(subject, item.content || ''),
});
if (res.success) {
@@ -12,6 +12,7 @@ import {
} from '@nestjs/common';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { EmailService } from './email.service';
import { escapeHtml, renderCaninaEmailLayout, textToHtmlParagraphs } from './email-layout';
import { NotificationsQueueService } from './notifications-queue.service';
import { SmsService } from '../common/services/sms.service';
import { PrismaService } from '../prisma/prisma.service';
@@ -109,20 +110,18 @@ export class NotificationsController {
async sendTestEmail(@Body() body: SendTestEmailDto) {
if (!body.to) throw new BadRequestException('آدرس ایمیل مقصد الزامی است.');
const subject = body.subject || 'تست اتصال ایمیل - کنینا ایران';
const message =
body.message ||
'این یک ایمیل آزمایشی جهت بررسی صحت تنظیمات سرور SMTP در فروشگاه کنینا است.';
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>
`,
subject,
text: message,
html: renderCaninaEmailLayout({
title: subject,
bodyHtml: `<p style="margin:0 0 16px;">${textToHtmlParagraphs(message)}</p><p style="margin:0;font-size:13px;color:#7A9B9F;">زمان ارسال: ${escapeHtml(new Date().toLocaleString('fa-IR'))}</p>`,
}),
});
if (!res.success) {
@@ -4,11 +4,12 @@ import { SmsModule } from '../common/sms.module';
import { EmailService } from './email.service';
import { NotificationsQueueService } from './notifications-queue.service';
import { NotificationsController } from './notifications.controller';
import { TransactionalEmailsService } from './transactional-emails.service';
@Module({
imports: [PrismaModule, SmsModule],
controllers: [NotificationsController],
providers: [EmailService, NotificationsQueueService],
exports: [EmailService, NotificationsQueueService],
providers: [EmailService, NotificationsQueueService, TransactionalEmailsService],
exports: [EmailService, NotificationsQueueService, TransactionalEmailsService],
})
export class NotificationsModule {}
@@ -0,0 +1,122 @@
import { Injectable, Logger } from '@nestjs/common';
import { EmailService } from './email.service';
import {
escapeHtml,
renderCaninaEmailLayout,
textToHtmlParagraphs,
} from './email-layout';
const ADMIN_NOTIFY_TO = [
'support@canina.ir',
'parsa.aghaee@gmail.com',
] as const;
@Injectable()
export class TransactionalEmailsService {
private readonly logger = new Logger(TransactionalEmailsService.name);
constructor(private readonly emailService: EmailService) {}
private async sendSafe(to: string, subject: string, text: string, html: string) {
try {
const res = await this.emailService.sendMail({ to, subject, text, html });
if (!res.success) {
this.logger.warn(`Email to ${to} failed: ${res.error || 'unknown'}`);
}
return res;
} catch (err) {
this.logger.warn(`Email to ${to} threw: ${(err as Error).message}`);
return { success: false, error: (err as Error).message };
}
}
async sendWelcome(to: string | null | undefined, firstName?: string | null) {
if (!to) return;
const name = (firstName || '').trim() || 'کاربر گرامی';
const subject = 'به کنینا خوش آمدید';
const text = `سلام ${name}،\n\nثبت‌نام شما در فروشگاه کنینا با موفقیت انجام شد.\n\ncanina.ir`;
const html = renderCaninaEmailLayout({
title: subject,
bodyHtml: `<p style="margin:0 0 12px;">سلام ${escapeHtml(name)}،</p><p style="margin:0;">ثبت‌نام شما در فروشگاه کنینا با موفقیت انجام شد. از این به بعد می‌توانید سفارش‌ها و وضعیت حساب خود را از سایت پیگیری کنید.</p>`,
});
await this.sendSafe(to, subject, text, html);
}
async sendOrderCreated(to: string | null | undefined, order: { id?: string; trackingNumber?: string | null; totalAmount?: number | string | null }) {
if (!to) return;
const orderRef = escapeHtml(String(order.trackingNumber || order.id || ''));
const amount = Number(order.totalAmount || 0);
const subject = 'سفارش شما در کنینا ثبت شد';
const text = `سفارش شما ثبت شد.\nشماره/کد: ${order.trackingNumber || order.id || ''}\nمبلغ: ${amount.toLocaleString('fa-IR')} تومان`;
const html = renderCaninaEmailLayout({
title: subject,
bodyHtml: `<p style="margin:0 0 12px;">سفارش شما ثبت شد.</p><p style="margin:0 0 8px;">شناسه/کد پیگیری: <b dir="ltr">${orderRef}</b></p><p style="margin:0;">مبلغ سفارش: <b>${escapeHtml(amount.toLocaleString('fa-IR'))}</b> تومان</p><p style="margin:16px 0 0;font-size:13px;color:#7A9B9F;">این پیام به‌تنهایی به‌معنای تأیید پرداخت نیست؛ وضعیت پرداخت را در حساب کاربری بررسی کنید.</p>`,
});
await this.sendSafe(to, subject, text, html);
}
async sendOrderPaid(to: string | null | undefined, order: { id?: string; trackingNumber?: string | null; totalAmount?: number | string | null }) {
if (!to) return;
const orderRef = escapeHtml(String(order.trackingNumber || order.id || ''));
const amount = Number(order.totalAmount || 0);
const subject = 'پرداخت سفارش کنینا تأیید شد';
const text = `پرداخت سفارش تأیید شد.\nشماره/کد: ${order.trackingNumber || order.id || ''}\nمبلغ: ${amount.toLocaleString('fa-IR')} تومان`;
const html = renderCaninaEmailLayout({
title: subject,
bodyHtml: `<p style="margin:0 0 12px;">پرداخت سفارش شما با موفقیت تأیید شد.</p><p style="margin:0 0 8px;">شناسه/کد پیگیری: <b dir="ltr">${orderRef}</b></p><p style="margin:0;">مبلغ پرداخت‌شده: <b>${escapeHtml(amount.toLocaleString('fa-IR'))}</b> تومان</p>`,
});
await this.sendSafe(to, subject, text, html);
}
async sendOrderShipped(
to: string | null | undefined,
order: { id?: string; trackingNumber?: string | null },
trackingCode?: string,
) {
if (!to) return;
const track = escapeHtml(String(trackingCode || order.trackingNumber || 'ارسال با پیک شهری'));
const orderRef = escapeHtml(String(order.trackingNumber || order.id || ''));
const subject = 'سفارش کنینا ارسال شد';
const text = `سفارش شما ارسال شد.\nسفارش: ${order.trackingNumber || order.id || ''}\nرهگیری: ${trackingCode || order.trackingNumber || 'ارسال با پیک شهری'}`;
const html = renderCaninaEmailLayout({
title: subject,
bodyHtml: `<p style="margin:0 0 12px;">وضعیت سفارش به ارسال‌شده تغییر کرد.</p><p style="margin:0 0 8px;">سفارش: <b dir="ltr">${orderRef}</b></p><p style="margin:0;">کد/روش ارسال: <b dir="ltr">${track}</b></p>`,
});
await this.sendSafe(to, subject, text, html);
}
async sendContactConfirmation(to: string | null | undefined, name: string, message: string, submissionId?: string) {
if (!to) return;
const subject = 'پیام شما در کنینا ثبت شد';
const text = `سلام ${name}،\n\nپیام شما ثبت شد و به‌زودی بررسی می‌شود.\nشناسه: ${submissionId || ''}\n\n${message}`;
const html = renderCaninaEmailLayout({
title: subject,
bodyHtml: `<p style="margin:0 0 12px;">سلام ${escapeHtml(name)}،</p><p style="margin:0 0 16px;">پیام شما از طریق فرم تماس کنینا ثبت شد و به‌زودی بررسی می‌شود.</p><div style="padding:14px;background:#F4F7F6;border:1px solid #E5ECE9;border-right:3px solid #F1B646;"><p style="margin:0;white-space:pre-wrap;">${textToHtmlParagraphs(message || '')}</p></div>${submissionId ? `<p style="margin:16px 0 0;font-size:13px;color:#7A9B9F;">شناسه پیگیری: <span dir="ltr">#${escapeHtml(submissionId)}</span></p>` : ''}`,
});
await this.sendSafe(to, subject, text, html);
}
async notifyAdminsAboutContact(dto: {
name: string;
phone: string;
email?: string;
subject?: string;
message: string;
submissionId?: string;
}) {
const subject = `پیام جدید فرم تماس کنینا${dto.subject ? ` — ${dto.subject}` : ''}`;
const text = `نام: ${dto.name}\nتلفن: ${dto.phone}\nایمیل: ${dto.email || '-'}\nموضوع: ${dto.subject || '-'}\nشناسه: ${dto.submissionId || '-'}\n\n${dto.message}`;
const html = renderCaninaEmailLayout({
title: 'پیام جدید از فرم تماس',
bodyHtml: `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;">
<tr><td style="padding:10px 12px;background:#F4F7F6;border:1px solid #E5ECE9;width:110px;">نام</td><td style="padding:10px 12px;border:1px solid #E5ECE9;">${escapeHtml(dto.name)}</td></tr>
<tr><td style="padding:10px 12px;background:#F4F7F6;border:1px solid #E5ECE9;">تلفن</td><td style="padding:10px 12px;border:1px solid #E5ECE9;" dir="ltr">${escapeHtml(dto.phone)}</td></tr>
<tr><td style="padding:10px 12px;background:#F4F7F6;border:1px solid #E5ECE9;">ایمیل</td><td style="padding:10px 12px;border:1px solid #E5ECE9;" dir="ltr">${escapeHtml(dto.email || '-')}</td></tr>
<tr><td style="padding:10px 12px;background:#F4F7F6;border:1px solid #E5ECE9;vertical-align:top;">پیام</td><td style="padding:10px 12px;border:1px solid #E5ECE9;white-space:pre-wrap;">${textToHtmlParagraphs(dto.message || '')}</td></tr>
</table>`,
});
await Promise.all(
ADMIN_NOTIFY_TO.map((to) => this.sendSafe(to, subject, text, html)),
);
}
}
+2
View File
@@ -1,8 +1,10 @@
import { Module } from "@nestjs/common";
import { OrdersService } from "./orders.service";
import { OrdersController } from "./orders.controller";
import { NotificationsModule } from "../notifications/notifications.module";
@Module({
imports: [NotificationsModule],
controllers: [OrdersController],
providers: [OrdersService],
})
@@ -2,6 +2,7 @@ import { Test, TestingModule } from "@nestjs/testing";
import { OrdersService } from "./orders.service";
import { PrismaService } from "../prisma/prisma.service";
import { SmsService } from "../common/services/sms.service";
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
import { NotFoundException, BadRequestException } from "@nestjs/common";
import { Prisma } from "@prisma/client";
@@ -58,6 +59,7 @@ describe("OrdersService", () => {
OrdersService,
{ provide: PrismaService, useValue: mockPrisma },
{ provide: SmsService, useValue: mockSmsService },
{ provide: TransactionalEmailsService, useValue: { sendWelcome: jest.fn().mockResolvedValue(undefined), sendOrderCreated: jest.fn().mockResolvedValue(undefined), sendOrderPaid: jest.fn().mockResolvedValue(undefined), sendOrderShipped: jest.fn().mockResolvedValue(undefined), sendContactConfirmation: jest.fn().mockResolvedValue(undefined), notifyAdminsAboutContact: jest.fn().mockResolvedValue(undefined) } },
],
}).compile();
+16
View File
@@ -8,6 +8,7 @@ import { PrismaService } from "../prisma/prisma.service";
import { PaginationDto } from "../common/dto/pagination.dto";
import { CreateOrderDto } from "./dto/create-order.dto";
import { SmsService } from "../common/services/sms.service";
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
import { Prisma } from "@prisma/client";
@Injectable()
@@ -17,6 +18,7 @@ export class OrdersService {
constructor(
private prisma: PrismaService,
private smsService: SmsService,
private transactionalEmails: TransactionalEmailsService,
) {}
private generateTrackingNumber(): string {
@@ -303,6 +305,9 @@ export class OrdersService {
this.logger.warn(`Failed to trigger wallet order SMS: ${err}`);
});
}
this.transactionalEmails
.sendOrderPaid(user.email, createdWalletOrder)
.catch(() => {});
return createdWalletOrder;
}
@@ -375,6 +380,11 @@ export class OrdersService {
.triggerEvent("ORDER_CREATED", orderData)
.catch(() => {});
}
if (user?.email) {
this.transactionalEmails
.sendOrderCreated(user.email, createdOrder)
.catch(() => {});
}
}
return createdOrder;
@@ -529,6 +539,9 @@ export class OrdersService {
: "پیک شهری";
this.smsService.triggerEvent("ORDER_SHIPPED", orderData).catch(() => {});
this.transactionalEmails
.sendOrderShipped(updatedOrder.user?.email, updatedOrder, finalTracking)
.catch(() => {});
}
return updatedOrder;
@@ -707,6 +720,9 @@ export class OrdersService {
.triggerEvent("ORDER_PAID", orderData)
.catch(() => {});
}
this.transactionalEmails
.sendOrderPaid(user.email, order)
.catch(() => {});
return {
success: true,
+2 -1
View File
@@ -1,4 +1,5 @@
import { Module } from "@nestjs/common";
import { NotificationsModule } from "../notifications/notifications.module";
import { PaymentController } from "./payment.controller";
import { PaymentService } from "./payment.service";
import { ZibalService } from "./zibal.service";
@@ -7,7 +8,7 @@ import { PrismaModule } from "../prisma/prisma.module";
import { SmsModule } from "../common/sms.module";
@Module({
imports: [PrismaModule, SmsModule],
imports: [NotificationsModule, PrismaModule, SmsModule],
controllers: [PaymentController],
providers: [PaymentService, ZibalService, ZibalEBankService],
exports: [PaymentService, ZibalService, ZibalEBankService],
@@ -3,6 +3,7 @@ import { PaymentService } from "./payment.service";
import { PrismaService } from "../prisma/prisma.service";
import { ZibalService } from "./zibal.service";
import { SmsService } from "../common/services/sms.service";
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
import { BadRequestException, NotFoundException } from "@nestjs/common";
import { Prisma } from "@prisma/client";
@@ -72,6 +73,7 @@ describe("PaymentService", () => {
{ provide: PrismaService, useValue: mockPrisma },
{ provide: ZibalService, useValue: mockZibalService },
{ provide: SmsService, useValue: mockSmsService },
{ provide: TransactionalEmailsService, useValue: { sendWelcome: jest.fn().mockResolvedValue(undefined), sendOrderCreated: jest.fn().mockResolvedValue(undefined), sendOrderPaid: jest.fn().mockResolvedValue(undefined), sendOrderShipped: jest.fn().mockResolvedValue(undefined), sendContactConfirmation: jest.fn().mockResolvedValue(undefined), notifyAdminsAboutContact: jest.fn().mockResolvedValue(undefined) } },
],
}).compile();
+12
View File
@@ -8,6 +8,7 @@ import {
import { PrismaService } from "../prisma/prisma.service";
import { ZibalService } from "./zibal.service";
import { SmsService } from "../common/services/sms.service";
import { TransactionalEmailsService } from "../notifications/transactional-emails.service";
import { Prisma } from "@prisma/client";
import { AdminTransactionFilterDto } from "./dto/admin-transaction-filter.dto";
@@ -24,6 +25,7 @@ export class PaymentService {
private readonly prisma: PrismaService,
private readonly zibalService: ZibalService,
private readonly smsService: SmsService,
private readonly transactionalEmails: TransactionalEmailsService,
) {}
/**
@@ -641,6 +643,16 @@ export class PaymentService {
this.smsService.triggerEvent("ORDER_PAID", orderData).catch((err) => {
this.logger.warn(`Could not trigger SMS event ORDER_PAID: ${err}`);
});
const emailTo =
transaction.user?.email ||
order?.user?.email ||
null;
const orderForEmail = order || transaction.order;
if (emailTo && orderForEmail) {
this.transactionalEmails
.sendOrderPaid(emailTo, orderForEmail)
.catch(() => {});
}
}
// Send SMS notification if wallet top-up