209 lines
9.5 KiB
JavaScript
209 lines
9.5 KiB
JavaScript
"use strict";
|
|
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
};
|
|
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
};
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.CashPaymentsService = void 0;
|
|
const common_1 = require("@nestjs/common");
|
|
const client_1 = require("@prisma/client");
|
|
const prisma_service_1 = require("../prisma/prisma.service");
|
|
const name_1 = require("../common/utils/name");
|
|
const notifications_service_1 = require("../notifications/notifications.service");
|
|
const RECEIPT_SUBMITTABLE_STATUSES = [
|
|
client_1.OrderStatus.cash_in_progress,
|
|
client_1.OrderStatus.cash_invoice_issued,
|
|
client_1.OrderStatus.awaiting_cash_payment,
|
|
client_1.OrderStatus.cash_payment_submitted,
|
|
client_1.OrderStatus.awaiting_cash_confirmation,
|
|
];
|
|
let CashPaymentsService = class CashPaymentsService {
|
|
prisma;
|
|
notifications;
|
|
constructor(prisma, notifications) {
|
|
this.prisma = prisma;
|
|
this.notifications = notifications;
|
|
}
|
|
async submitReceipt(userId, orderId, dto) {
|
|
const order = await this.prisma.order.findUnique({
|
|
where: { id: orderId },
|
|
include: { cashReceipt: true, items: true },
|
|
});
|
|
if (!order)
|
|
throw new common_1.NotFoundException('سفارش یافت نشد');
|
|
if (order.userId !== userId) {
|
|
throw new common_1.ForbiddenException('دسترسی به این سفارش مجاز نیست');
|
|
}
|
|
if (order.settlementType !== client_1.SettlementType.cash) {
|
|
throw new common_1.BadRequestException('این سفارش تسویه نقدی نیست');
|
|
}
|
|
if (!RECEIPT_SUBMITTABLE_STATUSES.includes(order.status)) {
|
|
throw new common_1.BadRequestException('در وضعیت فعلی سفارش امکان ثبت رسید وجود ندارد');
|
|
}
|
|
if (order.cashInvoiceExpiresAt &&
|
|
order.cashInvoiceExpiresAt.getTime() < Date.now()) {
|
|
throw new common_1.BadRequestException('مهلت پرداخت فاکتور نقدی به پایان رسیده است');
|
|
}
|
|
const companyIds = [
|
|
...new Set([
|
|
order.companyId,
|
|
...order.items.map((item) => item.companyId).filter(Boolean),
|
|
].filter(Boolean)),
|
|
];
|
|
const account = await this.prisma.bankAccount.findFirst({
|
|
where: {
|
|
id: dto.destinationAccountId,
|
|
companyId: { in: companyIds },
|
|
isActive: true,
|
|
},
|
|
});
|
|
if (!account) {
|
|
throw new common_1.BadRequestException('حساب مقصد نامعتبر است');
|
|
}
|
|
const receipt = await this.prisma.$transaction(async (tx) => {
|
|
const data = {
|
|
amount: dto.amount,
|
|
paidAmount: dto.paidAmount ?? dto.amount,
|
|
transferDate: new Date(dto.transferDate),
|
|
transferTime: dto.transferTime.trim(),
|
|
trackingNumber: dto.trackingNumber.trim(),
|
|
destinationAccountId: dto.destinationAccountId,
|
|
receiptImage: dto.receiptImage || null,
|
|
notes: dto.notes?.trim() || null,
|
|
expiresAt: order.cashInvoiceExpiresAt,
|
|
status: client_1.CashPaymentStatus.pending_review,
|
|
submittedAt: new Date(),
|
|
};
|
|
const saved = order.cashReceipt
|
|
? await tx.cashPaymentReceipt.update({
|
|
where: { orderId },
|
|
data,
|
|
})
|
|
: await tx.cashPaymentReceipt.create({
|
|
data: { orderId, ...data },
|
|
});
|
|
await tx.order.update({
|
|
where: { id: orderId },
|
|
data: { status: client_1.OrderStatus.awaiting_cash_confirmation },
|
|
});
|
|
await tx.orderStatusHistory.create({
|
|
data: {
|
|
orderId,
|
|
fromStatus: order.status,
|
|
toStatus: client_1.OrderStatus.awaiting_cash_confirmation,
|
|
changedBy: 'customer',
|
|
note: 'رسید پرداخت نقدی ارسال شد',
|
|
},
|
|
});
|
|
return saved;
|
|
});
|
|
this.notifications.dispatchAdmin({
|
|
title: 'رسید پرداخت نقدی ثبت شد',
|
|
body: `مشتری برای سفارش ${order.orderNumber} رسید به مبلغ ${Math.round(dto.amount).toLocaleString('fa-IR')} تومان ثبت کرد.`,
|
|
link: `/orders/${orderId}`,
|
|
});
|
|
return this.mapReceipt(receipt, order.orderNumber, '');
|
|
}
|
|
async findAll(status) {
|
|
const receipts = await this.prisma.cashPaymentReceipt.findMany({
|
|
where: status ? { status } : undefined,
|
|
orderBy: { createdAt: 'desc' },
|
|
include: {
|
|
order: {
|
|
include: { user: true },
|
|
},
|
|
},
|
|
});
|
|
return receipts.map((r) => this.mapReceipt(r, r.order.orderNumber, (0, name_1.joinFullName)(r.order.user.firstName, r.order.user.lastName)));
|
|
}
|
|
async updateStatus(id, adminId, dto) {
|
|
const receipt = await this.prisma.cashPaymentReceipt.findUnique({
|
|
where: { id },
|
|
include: { order: { include: { user: true } } },
|
|
});
|
|
if (!receipt)
|
|
throw new common_1.NotFoundException('رسید نقدی یافت نشد');
|
|
const updated = await this.prisma.$transaction(async (tx) => {
|
|
const result = await tx.cashPaymentReceipt.update({
|
|
where: { id },
|
|
data: {
|
|
status: dto.status,
|
|
notes: dto.note
|
|
? [receipt.notes, dto.note].filter(Boolean).join('\n')
|
|
: receipt.notes,
|
|
},
|
|
include: { order: { include: { user: true } } },
|
|
});
|
|
let nextStatus = null;
|
|
if (dto.status === client_1.CashPaymentStatus.approved) {
|
|
nextStatus = client_1.OrderStatus.cash_confirmed;
|
|
}
|
|
else if (dto.status === client_1.CashPaymentStatus.rejected) {
|
|
nextStatus = client_1.OrderStatus.awaiting_cash_payment;
|
|
}
|
|
else if (dto.status === client_1.CashPaymentStatus.expired) {
|
|
nextStatus = client_1.OrderStatus.expired;
|
|
}
|
|
if (nextStatus && nextStatus !== receipt.order.status) {
|
|
await tx.order.update({
|
|
where: { id: receipt.orderId },
|
|
data: { status: nextStatus },
|
|
});
|
|
await tx.orderStatusHistory.create({
|
|
data: {
|
|
orderId: receipt.orderId,
|
|
fromStatus: receipt.order.status,
|
|
toStatus: nextStatus,
|
|
changedBy: `admin:${adminId}`,
|
|
note: dto.note || `وضعیت پرداخت نقدی: ${dto.status}`,
|
|
},
|
|
});
|
|
}
|
|
return result;
|
|
});
|
|
if (dto.status === client_1.CashPaymentStatus.approved) {
|
|
this.notifications.dispatchOrderEvent(receipt.orderId, 'receipt_approved');
|
|
}
|
|
else if (dto.status === client_1.CashPaymentStatus.rejected) {
|
|
this.notifications.dispatchOrderEvent(receipt.orderId, 'receipt_rejected', { note: dto.note ?? null });
|
|
}
|
|
else if (dto.status === client_1.CashPaymentStatus.expired) {
|
|
this.notifications.dispatchOrderEvent(receipt.orderId, 'cash_invoice_expired');
|
|
}
|
|
return this.mapReceipt(updated, updated.order.orderNumber, (0, name_1.joinFullName)(updated.order.user.firstName, updated.order.user.lastName));
|
|
}
|
|
mapReceipt(r, orderNumber, customerName) {
|
|
return {
|
|
id: r.id,
|
|
orderId: r.orderId,
|
|
orderNumber,
|
|
customerName,
|
|
amount: r.amount,
|
|
paidAmount: r.paidAmount,
|
|
transferDate: r.transferDate?.toISOString() ?? null,
|
|
transferTime: r.transferTime ?? undefined,
|
|
trackingNumber: r.trackingNumber ?? '',
|
|
trackingCode: r.trackingNumber ?? '',
|
|
destinationAccountId: r.destinationAccountId ?? undefined,
|
|
receiptImage: r.receiptImage ?? undefined,
|
|
notes: r.notes ?? undefined,
|
|
expiresAt: r.expiresAt?.toISOString() ?? '',
|
|
status: r.status,
|
|
submittedAt: r.submittedAt?.toISOString(),
|
|
createdAt: r.createdAt.toISOString(),
|
|
updatedAt: r.updatedAt.toISOString(),
|
|
};
|
|
}
|
|
};
|
|
exports.CashPaymentsService = CashPaymentsService;
|
|
exports.CashPaymentsService = CashPaymentsService = __decorate([
|
|
(0, common_1.Injectable)(),
|
|
__metadata("design:paramtypes", [prisma_service_1.PrismaService,
|
|
notifications_service_1.NotificationsService])
|
|
], CashPaymentsService);
|
|
//# sourceMappingURL=cash-payments.service.js.map
|