diff --git a/backend/src/auth/auth.module.ts b/backend/src/auth/auth.module.ts index d639a801..ec3a923d 100644 --- a/backend/src/auth/auth.module.ts +++ b/backend/src/auth/auth.module.ts @@ -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(), diff --git a/backend/src/auth/auth.service.spec.ts b/backend/src/auth/auth.service.spec.ts index b95b0889..dd574eef 100644 --- a/backend/src/auth/auth.service.spec.ts +++ b/backend/src/auth/auth.service.spec.ts @@ -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(); diff --git a/backend/src/auth/auth.service.ts b/backend/src/auth/auth.service.ts index 36364b39..d2ac9f59 100644 --- a/backend/src/auth/auth.service.ts +++ b/backend/src/auth/auth.service.ts @@ -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) { @@ -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); diff --git a/backend/src/contact/contact.module.ts b/backend/src/contact/contact.module.ts index 0dcefda5..aa471ac8 100644 --- a/backend/src/contact/contact.module.ts +++ b/backend/src/contact/contact.module.ts @@ -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], diff --git a/backend/src/contact/contact.service.spec.ts b/backend/src/contact/contact.service.spec.ts index 0ad0a8c6..644eaf3d 100644 --- a/backend/src/contact/contact.service.spec.ts +++ b/backend/src/contact/contact.service.spec.ts @@ -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(); diff --git a/backend/src/contact/contact.service.ts b/backend/src/contact/contact.service.ts index 785c952e..df7a8473 100644 --- a/backend/src/contact/contact.service.ts +++ b/backend/src/contact/contact.service.ts @@ -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: diff --git a/backend/src/notifications/email-layout.ts b/backend/src/notifications/email-layout.ts new file mode 100644 index 00000000..d8a8dada --- /dev/null +++ b/backend/src/notifications/email-layout.ts @@ -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, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +export function textToHtmlParagraphs(text: string): string { + return escapeHtml(text) + .split(/\r?\n/) + .map((line) => (line.trim().length === 0 ? ' ' : line)) + .join('
'); +} + +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 ` + + + + + ${title} + + + + + + +
+ + + + + + + + + + + + + +
 
+

${eyebrow}

+

کنینا

+

مکمل تخصصی حیوانات خانگی

+
+

${title}

+
${options.bodyHtml}
+
+

کنینا ایران

+

+ support@canina.ir +  ·  + canina.ir +

+

${footerNote}

+
+
+ +`; +} + +export function renderCaninaNotificationEmail(subject: string, content: string): string { + return renderCaninaEmailLayout({ + title: subject || 'اطلاعیه کنینا', + bodyHtml: `

${textToHtmlParagraphs(content || '')}

`, + }); +} diff --git a/backend/src/notifications/email.service.ts b/backend/src/notifications/email.service.ts index daf51afd..58665ba8 100644 --- a/backend/src/notifications/email.service.ts +++ b/backend/src/notifications/email.service.ts @@ -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', }; } } diff --git a/backend/src/notifications/notifications-queue.service.spec.ts b/backend/src/notifications/notifications-queue.service.spec.ts index bf911c05..eb748d9f 100644 --- a/backend/src/notifications/notifications-queue.service.spec.ts +++ b/backend/src/notifications/notifications-queue.service.spec.ts @@ -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' }), diff --git a/backend/src/notifications/notifications-queue.service.ts b/backend/src/notifications/notifications-queue.service.ts index 7afe5404..b6390737 100644 --- a/backend/src/notifications/notifications-queue.service.ts +++ b/backend/src/notifications/notifications-queue.service.ts @@ -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) || {}; + const subject = item.subject || 'اطلاعیه کنینا ایران'; const res = await this.emailService.sendMail({ to: item.recipient, - subject: item.subject || 'اطلاعیه کنینا ایران', + subject, text: item.content, - html: payloadObj.html || `
${item.content.replace(/\n/g, '
')}
`, + html: payloadObj.html || renderCaninaNotificationEmail(subject, item.content || ''), }); if (res.success) { diff --git a/backend/src/notifications/notifications.controller.ts b/backend/src/notifications/notifications.controller.ts index 1200ab0a..10e5260f 100644 --- a/backend/src/notifications/notifications.controller.ts +++ b/backend/src/notifications/notifications.controller.ts @@ -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: ` -
-
-

کنینا ایران | تست سرور ایمیل

-

${body.message || 'این یک ایمیل آزمایشی جهت بررسی صحت تنظیمات سرور SMTP در فروشگاه کنینا است.'}

-
- زمان ارسال: ${new Date().toLocaleString('fa-IR')} -
-
- `, + subject, + text: message, + html: renderCaninaEmailLayout({ + title: subject, + bodyHtml: `

${textToHtmlParagraphs(message)}

زمان ارسال: ${escapeHtml(new Date().toLocaleString('fa-IR'))}

`, + }), }); if (!res.success) { diff --git a/backend/src/notifications/notifications.module.ts b/backend/src/notifications/notifications.module.ts index 5ca2d99c..1b723c4f 100644 --- a/backend/src/notifications/notifications.module.ts +++ b/backend/src/notifications/notifications.module.ts @@ -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 {} diff --git a/backend/src/notifications/transactional-emails.service.ts b/backend/src/notifications/transactional-emails.service.ts new file mode 100644 index 00000000..ac8abda1 --- /dev/null +++ b/backend/src/notifications/transactional-emails.service.ts @@ -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: `

سلام ${escapeHtml(name)}،

ثبت‌نام شما در فروشگاه کنینا با موفقیت انجام شد. از این به بعد می‌توانید سفارش‌ها و وضعیت حساب خود را از سایت پیگیری کنید.

`, + }); + 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: `

سفارش شما ثبت شد.

شناسه/کد پیگیری: ${orderRef}

مبلغ سفارش: ${escapeHtml(amount.toLocaleString('fa-IR'))} تومان

این پیام به‌تنهایی به‌معنای تأیید پرداخت نیست؛ وضعیت پرداخت را در حساب کاربری بررسی کنید.

`, + }); + 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: `

پرداخت سفارش شما با موفقیت تأیید شد.

شناسه/کد پیگیری: ${orderRef}

مبلغ پرداخت‌شده: ${escapeHtml(amount.toLocaleString('fa-IR'))} تومان

`, + }); + 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: `

وضعیت سفارش به ارسال‌شده تغییر کرد.

سفارش: ${orderRef}

کد/روش ارسال: ${track}

`, + }); + 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: `

سلام ${escapeHtml(name)}،

پیام شما از طریق فرم تماس کنینا ثبت شد و به‌زودی بررسی می‌شود.

${textToHtmlParagraphs(message || '')}

${submissionId ? `

شناسه پیگیری: #${escapeHtml(submissionId)}

` : ''}`, + }); + 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: ` + + + + +
نام${escapeHtml(dto.name)}
تلفن${escapeHtml(dto.phone)}
ایمیل${escapeHtml(dto.email || '-')}
پیام${textToHtmlParagraphs(dto.message || '')}
`, + }); + await Promise.all( + ADMIN_NOTIFY_TO.map((to) => this.sendSafe(to, subject, text, html)), + ); + } +} diff --git a/backend/src/orders/orders.module.ts b/backend/src/orders/orders.module.ts index 565a1b2d..c258a5de 100644 --- a/backend/src/orders/orders.module.ts +++ b/backend/src/orders/orders.module.ts @@ -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], }) diff --git a/backend/src/orders/orders.service.spec.ts b/backend/src/orders/orders.service.spec.ts index da68cc71..beb8d1a0 100644 --- a/backend/src/orders/orders.service.spec.ts +++ b/backend/src/orders/orders.service.spec.ts @@ -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(); diff --git a/backend/src/orders/orders.service.ts b/backend/src/orders/orders.service.ts index 9f8b587d..4bbfd4bc 100644 --- a/backend/src/orders/orders.service.ts +++ b/backend/src/orders/orders.service.ts @@ -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, diff --git a/backend/src/payment/payment.module.ts b/backend/src/payment/payment.module.ts index b92e762f..4b90eecc 100644 --- a/backend/src/payment/payment.module.ts +++ b/backend/src/payment/payment.module.ts @@ -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], diff --git a/backend/src/payment/payment.service.spec.ts b/backend/src/payment/payment.service.spec.ts index b4161620..42429261 100644 --- a/backend/src/payment/payment.service.spec.ts +++ b/backend/src/payment/payment.service.spec.ts @@ -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(); diff --git a/backend/src/payment/payment.service.ts b/backend/src/payment/payment.service.ts index 27b54976..daa63eea 100644 --- a/backend/src/payment/payment.service.ts +++ b/backend/src/payment/payment.service.ts @@ -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