Skip to content

Commit

Permalink
feature/EF-200 send email when cancel order
Browse files Browse the repository at this point in the history
  • Loading branch information
MinhhTien committed Mar 16, 2024
1 parent 0225558 commit 14830ef
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 54 deletions.
97 changes: 43 additions & 54 deletions src/order/services/order.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Injectable } from '@nestjs/common'
import { Injectable, Logger } from '@nestjs/common'
import { OrderRepository } from '@order/repositories/order.repository'
import { PaginationParams } from '@common/decorators/pagination.decorator'
import { OrderStatus, TransactionStatus, UserRole } from '@common/contracts/constant'
Expand All @@ -21,17 +21,20 @@ import {
RefundMomoPaymentDto
} from '@payment/dto/momo-payment.dto'
import { ConfigService } from '@nestjs/config'
import { MailerService } from '@nestjs-modules/mailer'

@Injectable()
export class OrderService {
private readonly logger = new Logger(OrderService.name)
constructor(
@InjectConnection() readonly connection: Connection,
private readonly orderRepository: OrderRepository,
private readonly paymentService: PaymentService,
private readonly paymentRepository: PaymentRepository,
private readonly cartService: CartService,
private readonly productRepository: ProductRepository,
private readonly configService: ConfigService
private readonly configService: ConfigService,
private readonly mailerService: MailerService
) {}

public async getOrderList(filter: FilterQuery<Order>, paginationParams: PaginationParams) {
Expand Down Expand Up @@ -259,7 +262,7 @@ export class OrderService {
try {
const { orderId, orderHistoryItem, reason } = cancelOrderDto
// 1. Update order status, reason and order history
console.log(`1. Update order status, reason and order history`)
this.logger.log(`1. Update order status, reason and order history`)
const order = await this.orderRepository.findOneAndUpdate(
{
_id: orderId,
Expand All @@ -277,7 +280,7 @@ export class OrderService {
)
if (!order) throw new AppException(Errors.ORDER_STATUS_INVALID)

console.log(`2. Push update quantity in product.variants to operation to execute later`)
this.logger.log(`2. Push update quantity in product.variants to operation to execute later`)
// 2. Push update quantity in product.variants to operation to execute later
// array to process bulk update
const operations = []
Expand All @@ -294,8 +297,7 @@ export class OrderService {
await this.productRepository.model.bulkWrite(operations)

// 3. Refund payment via MOMO
console.log(`3. Refund payment via MOMO::`)
console.log(JSON.stringify(order.payment))
this.logger.log(`3. Refund payment via MOMO::`)
const refundOrderId = `FUR${new Date().getTime()}${Math.floor(Math.random() * 100)}`
this.paymentService.setStrategy(this.paymentService.momoPaymentStrategy)
const refundMomoPaymentDto: RefundMomoPaymentDto = {
Expand All @@ -307,34 +309,20 @@ export class OrderService {
description: `Furnique - Hoàn tiền đơn hàng #${orderId}`
}
const refundedTransaction = await this.paymentService.refundTransaction(refundMomoPaymentDto)
console.log(JSON.stringify(refundedTransaction))

// 4. Save refunded payment
console.log(`4. Save refunded payment`)
await this.paymentRepository.create(
{
transactionStatus: TransactionStatus.REFUNDED,
transaction: refundedTransaction,
paymentMethod: order.payment?.paymentMethod,
amount: refundedTransaction.amount
},
{
session
}
)
this.logger.log(JSON.stringify(refundedTransaction))

// 5. Fetch newest transaction of order
console.log(`5. Fetch newest transaction of order`)
// 4. Fetch newest transaction of order
this.logger.log(`4. Fetch newest transaction of order`)
const queryMomoPaymentDto: QueryMomoPaymentDto = {
orderId: order.orderId,
requestId: order.orderId,
lang: 'vi'
}
const transaction = await this.paymentService.getTransaction(queryMomoPaymentDto)
console.log(JSON.stringify(transaction))
this.logger.log(JSON.stringify(transaction))

// 6. Update payment transactionStatus, transaction
console.log(`6. Update payment transactionStatus, transaction`)
// 5. Update payment transactionStatus, transaction
this.logger.log(`5. Update payment transactionStatus, transaction`)
const payment = await this.paymentRepository.findOneAndUpdate(
{
_id: order.payment._id
Expand All @@ -351,8 +339,8 @@ export class OrderService {
new: true
}
)
// 7. Update order transactionStatus, payment
console.log(`7. Update order transactionStatus, payment`)
// 6. Update order transactionStatus, payment
this.logger.log(`6. Update order transactionStatus, payment`)
await this.orderRepository.findOneAndUpdate(
{
_id: order._id
Expand All @@ -368,32 +356,33 @@ export class OrderService {
}
)

// 8. Send email/notification to customer
// console.log(`8. Send email/notification to customer`)
// this.mailerService.sendMail({
// to: order.customer.email,
// subject: `[Furnique] Hoàn tiền đơn hàng #${order.orderId}`,
// template: 'order-refunded',
// context: {
// ...order,
// _id: order._id,
// orderId: order.orderId,
// customer: order.customer,
// items: order.items.map((item) => {
// const variant = item.product.variants.find((variant) => variant.sku === item.sku)
// return {
// ...item,
// product: {
// ...item.product,
// variant: {
// ...variant,
// price: Intl.NumberFormat('en-DE').format(variant.price)
// }
// }
// }
// }),
// totalAmount: Intl.NumberFormat('en-DE').format(order.totalAmount)
// }
// 7. Send email/notification to customer
this.logger.log(`7. Send email/notification to customer`)
this.mailerService.sendMail({
to: order.customer.email,
subject: `[Furnique] Thông báo hủy đơn hàng #${order.orderId}`,
template: 'order-canceled',
context: {
...order,
_id: order._id,
orderId: order.orderId,
customer: order.customer,
items: order.items.map((item) => {
const variant = item.product.variants.find((variant) => variant.sku === item.sku)
return {
...item,
product: {
...item.product,
variant: {
...variant,
price: Intl.NumberFormat('en-DE').format(variant.price)
}
}
}
}),
totalAmount: Intl.NumberFormat('en-DE').format(order.totalAmount)
}
})
await session.commitTransaction()
return new SuccessResponse(true)
} catch (error) {
Expand Down
38 changes: 38 additions & 0 deletions src/templates/order-canceled.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<pre style="font-family: Helvetica, sans-serif; font-size: 1.5em;">
<h2>Thông báo hủy đơn hàng!</h2>
Xin chào <%= customer.firstName %> <%= customer.lastName %>,

Furnique xác nhận rằng đơn hàng của bạn đã được hủy thành công.
Số tiền đã thanh toán sẽ được hoàn lại vào tài khoản của bạn trong thời gian sớm nhất.

Mã Đơn Hàng: <b><%= orderId %></b>

Chi tiết đơn hàng:
<table style="width: 100%; border-collapse: collapse;">
<thead>
<tr style="background-color: #a9a3a3; color: #fff;">
<th style="border: 1px solid #ddd; padding: 8px; width: 200px;">#</th>
<th style="border: 1px solid #ddd; padding: 8px;">Sản Phẩm</th>
<th style="border: 1px solid #ddd; padding: 8px;">Số Lượng</th>
<th style="border: 1px solid #ddd; padding: 8px;">Giá</th>
</tr>
</thead>
<tbody>
<% items.forEach(function(item) { %>
<tr>
<td style="border: 1px solid #ddd; padding: 8px;"><img style="width: 200px; height: 200px;" src="<%= item.product.images[0] %>" alt="<%= item.product.name %>" /></td>
<td style="border: 1px solid #ddd; padding: 8px;"><%= item.product.name %></td>
<td style="border: 1px solid #ddd; padding: 8px;"><%= item.quantity %></td>
<td style="border: 1px solid #ddd; padding: 8px;">&#8363;<%= item.product.variant.price %></td>
</tr>
<% }); %>
</tbody>
</table>
<p style="text-align: right; margin-top: 0;">Tổng tiền: <b>&#8363;<%= totalAmount %></b></p>
<div align="center" style="padding-top:10px">
<a href="https://www.furnique.tech/customer/orders/<%= _id %>" target="_blank" style="text-decoration: none;">
<img src="https://ci3.googleusercontent.com/meips/ADKq_NYVaPakFqAiVY0nV0ofSouvN9L1z5IPXEMnXGI7cDC2QzODNqWZbtxPiVtknKQTDcngkmkS0VgcnEczKmq2VcvjA7rxWbMeLU19p7LjY9ScARIX6-0xLQ=s0-d-e1-ft#https://img.alicdn.com/tfs/TB178CsJeH2gK0jSZFEXXcqMpXa-300-50.jpg" style="max-width:300px" border="0" class="CToWUd" data-bit="iit">
</a>
</div>
</pre>
<%- include('web-footer') -%>
1 change: 1 addition & 0 deletions src/templates/web-footer.ejs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<pre style="font-family: Arial, Helvetica, sans-serif; font-size: 1.5em;">
□□□───────────────────────────────
Cảm ơn bạn đã sử dụng dịch vụ của chúng tôi!

Trân trọng,
Furnique
Expand Down

0 comments on commit 14830ef

Please sign in to comment.