feat: complete tickets & vet consultation, fix wallet balance overflow, b2b toggle, and transaction manual verification
Deploy Canina / deploy (push) Successful in 1m51s
Deploy Canina / deploy (push) Successful in 1m51s
This commit is contained in:
1 parent
1aa9d6e34d
commit
42707c04cf
24 files changed
+1856
-139
No files matched your search
@@ -477,6 +477,9 @@ export class AdminService {
|
||||
},
|
||||
},
|
||||
coupon: true,
|
||||
paymentTransactions: {
|
||||
orderBy: { createdAt: 'desc' },
|
||||
},
|
||||
},
|
||||
}),
|
||||
this.prisma.order.count({ where }),
|
||||
|
||||
@@ -28,6 +28,7 @@ import { IngredientsModule } from './ingredients/ingredients.module';
|
||||
import { PrescriptionsModule } from './prescriptions/prescriptions.module';
|
||||
import { B2BModule } from './b2b/b2b.module';
|
||||
import { PaymentModule } from './payment/payment.module';
|
||||
import { TicketsModule } from './tickets/tickets.module';
|
||||
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
|
||||
@@ -44,6 +45,7 @@ import { Request, Response, NextFunction } from 'express';
|
||||
OrdersModule,
|
||||
SettingsModule,
|
||||
PaymentModule,
|
||||
TicketsModule,
|
||||
ThrottlerModule.forRoot([
|
||||
{
|
||||
ttl: 60000,
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
BadRequestException,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { PaginationDto } from '../common/dto/pagination.dto';
|
||||
@@ -11,6 +12,8 @@ import { Prisma } from '@prisma/client';
|
||||
|
||||
@Injectable()
|
||||
export class OrdersService {
|
||||
private readonly logger = new Logger(OrdersService.name);
|
||||
|
||||
constructor(
|
||||
private prisma: PrismaService,
|
||||
private smsService: SmsService,
|
||||
@@ -186,7 +189,7 @@ export class OrdersService {
|
||||
);
|
||||
}
|
||||
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
const createdWalletOrder = await this.prisma.$transaction(async (tx) => {
|
||||
await tx.user.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
@@ -236,6 +239,21 @@ export class OrdersService {
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
// Send Order Confirmation SMS for wallet orders
|
||||
if (user.mobile) {
|
||||
this.smsService
|
||||
.sendOrderConfirmation(
|
||||
user.mobile,
|
||||
trackingNumber,
|
||||
Number(finalAmount).toLocaleString('fa-IR'),
|
||||
)
|
||||
.catch((err) => {
|
||||
this.logger.warn(`Failed to send wallet order SMS: ${err}`);
|
||||
});
|
||||
}
|
||||
|
||||
return createdWalletOrder;
|
||||
}
|
||||
|
||||
const isOnline = createOrderDto.paymentMethod === 'online';
|
||||
|
||||
@@ -212,6 +212,30 @@ export class PaymentController {
|
||||
return this.paymentService.adminLiveInquiry(id);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/manual-verify/:id')
|
||||
@ApiOperation({ summary: 'تایید دستی تراکنش یا فیش واریزی کارتبهکارت توسط ادمین' })
|
||||
async manualVerify(
|
||||
@Param('id') id: string,
|
||||
@Body() body: { adminNote?: string },
|
||||
) {
|
||||
return this.paymentService.adminManualVerify(id, body.adminNote);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/manual-reject/:id')
|
||||
@ApiOperation({ summary: 'رد دستی تراکنش پرداخت توسط ادمین' })
|
||||
async manualReject(
|
||||
@Param('id') id: string,
|
||||
@Body() body: { reason?: string },
|
||||
) {
|
||||
return this.paymentService.adminManualReject(id, body.reason);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
|
||||
@@ -478,16 +478,22 @@ export class PaymentService {
|
||||
});
|
||||
|
||||
// Send SMS notification if order payment
|
||||
if (transaction.type === 'ORDER' && transaction.order?.user?.mobile) {
|
||||
const mobile = transaction.order.user.mobile;
|
||||
const customerMobile =
|
||||
transaction.order?.user?.mobile ||
|
||||
transaction.user?.mobile ||
|
||||
(transaction.rawRequest as { mobile?: string })?.mobile;
|
||||
|
||||
if (transaction.type === 'ORDER' && customerMobile) {
|
||||
const trackingNum =
|
||||
transaction.order.trackingNumber || transaction.order.id;
|
||||
transaction.order?.trackingNumber ||
|
||||
transaction.orderId ||
|
||||
transaction.id;
|
||||
const formattedAmount = Number(transaction.amount).toLocaleString(
|
||||
'fa-IR',
|
||||
);
|
||||
|
||||
this.smsService
|
||||
.sendOrderConfirmation(mobile, trackingNum, formattedAmount)
|
||||
.sendOrderConfirmation(customerMobile, trackingNum, formattedAmount)
|
||||
.catch((err) => {
|
||||
this.logger.warn(`Could not send SMS confirmation: ${err}`);
|
||||
});
|
||||
@@ -842,16 +848,101 @@ export class PaymentService {
|
||||
return {
|
||||
transactionId: transaction.id,
|
||||
trackId: transaction.trackId,
|
||||
currentDbStatus: transaction.status,
|
||||
gatewayResponse: inquiryRes,
|
||||
status: inquiryRes.status,
|
||||
statusMessage: statusMsg,
|
||||
result: inquiryRes.result,
|
||||
resultMessage: resultMsg,
|
||||
inquiredAt: new Date(),
|
||||
amount: inquiryRes.amount,
|
||||
refNumber: inquiryRes.refNumber,
|
||||
cardNumber: inquiryRes.cardNumber,
|
||||
paidAt: inquiryRes.paidAt,
|
||||
rawInquiryResponse: inquiryRes,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 9. Gateway Health Check for Admin
|
||||
* 9. Admin: Manually Approve / Verify a Transaction (e.g. Card-to-Card receipt or bank transfer)
|
||||
*/
|
||||
async adminManualVerify(transactionId: string, adminNote?: string) {
|
||||
const transaction = await this.prisma.paymentTransaction.findUnique({
|
||||
where: { id: transactionId },
|
||||
include: { order: true, user: true },
|
||||
});
|
||||
|
||||
if (!transaction) {
|
||||
throw new NotFoundException('تراکنش یافت نشد');
|
||||
}
|
||||
|
||||
if (transaction.status === 'VERIFIED') {
|
||||
throw new BadRequestException('این تراکنش قبلاً تایید شده است');
|
||||
}
|
||||
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
await tx.paymentTransaction.update({
|
||||
where: { id: transactionId },
|
||||
data: {
|
||||
status: 'VERIFIED',
|
||||
message: adminNote || 'تایید دستی توسط مدیر سیستم (کارت به کارت / فیش بانکی)',
|
||||
paidAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
if (transaction.type === 'WALLET_TOPUP') {
|
||||
await tx.user.update({
|
||||
where: { id: transaction.userId },
|
||||
data: {
|
||||
walletBalance: { increment: Number(transaction.amount) },
|
||||
},
|
||||
});
|
||||
|
||||
await tx.walletTransaction.create({
|
||||
data: {
|
||||
userId: transaction.userId,
|
||||
amount: transaction.amount,
|
||||
type: 'deposit',
|
||||
status: 'completed',
|
||||
description: `افزایش موجودی دستی تایید شده توسط ادمین (${adminNote || 'کارت به کارت'})`,
|
||||
},
|
||||
});
|
||||
} else if (transaction.type === 'ORDER' && transaction.orderId) {
|
||||
await tx.order.update({
|
||||
where: { id: transaction.orderId },
|
||||
data: {
|
||||
status: 'processing',
|
||||
paymentMethod: 'card_to_card',
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return { success: true, message: 'تراکنش با موفقیت به صورت دستی تایید و اعمال شد' };
|
||||
}
|
||||
|
||||
/**
|
||||
* 10. Admin: Manually Reject a Transaction
|
||||
*/
|
||||
async adminManualReject(transactionId: string, reason?: string) {
|
||||
const transaction = await this.prisma.paymentTransaction.findUnique({
|
||||
where: { id: transactionId },
|
||||
});
|
||||
|
||||
if (!transaction) {
|
||||
throw new NotFoundException('تراکنش یافت نشد');
|
||||
}
|
||||
|
||||
await this.prisma.paymentTransaction.update({
|
||||
where: { id: transactionId },
|
||||
data: {
|
||||
status: 'FAILED',
|
||||
message: reason || 'رد شده توسط ادمین سیستم',
|
||||
},
|
||||
});
|
||||
|
||||
return { success: true, message: 'تراکنش به عنوان ناموفق/رد شده علامتگذاری شد' };
|
||||
}
|
||||
|
||||
/**
|
||||
* 11. Gateway Health Check for Admin
|
||||
*/
|
||||
async checkGatewayHealth() {
|
||||
return this.zibalService.checkHealth();
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { IsString, IsNotEmpty, IsOptional, IsEnum, IsArray } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class CreateTicketDto {
|
||||
@ApiProperty({ description: 'موضوع تیکت یا عنوان مشاوره', example: 'مشاوره مصرف مکمل کانینوکال' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
subject: string;
|
||||
|
||||
@ApiProperty({ description: 'متن پیام یا شرح وضعیت', example: 'سگ من ۵ ماهشه و میخواستم بدونم...' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
message: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'دستهبندی تیکت', example: 'VET_CONSULTATION', enum: ['VET_CONSULTATION', 'ORDER_SUPPORT', 'PRODUCT_INQUIRY', 'GENERAL'] })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
category?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'اولویت تیکت', example: 'MEDIUM', enum: ['LOW', 'MEDIUM', 'HIGH', 'URGENT'] })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
priority?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'شناسه حیوان خانگی مرتبط (اختیاری)', example: '9a8f4171-86bb-4236-9d6d-e4bc60255156' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
petId?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'لینک تصویر آزمایش یا نسخه ضمیمه شده' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
attachment?: string;
|
||||
}
|
||||
|
||||
export class ReplyTicketDto {
|
||||
@ApiProperty({ description: 'متن پاسخ تیکت', example: 'با سلام، دوز مصرفی پیشنهادی...' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
message: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'لینک فایل ضمیمه' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
attachment?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'تغییر وضعیت تیکت (توسط ادمین)', enum: ['OPEN', 'IN_PROGRESS', 'ANSWERED', 'CLOSED'] })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
status?: string;
|
||||
}
|
||||
|
||||
export class AdminUpdateTicketDto {
|
||||
@ApiPropertyOptional({ description: 'وضعیت جدید تیکت', enum: ['OPEN', 'IN_PROGRESS', 'ANSWERED', 'CLOSED'] })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
status?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'اولویت تیکت', enum: ['LOW', 'MEDIUM', 'HIGH', 'URGENT'] })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
priority?: string;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { IsOptional, IsString, IsNumber } from 'class-validator';
|
||||
import { Type } from 'class-transformer';
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class TicketQueryDto {
|
||||
@ApiPropertyOptional({ description: 'شماره صفحه', default: 1 })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsNumber()
|
||||
page?: number = 1;
|
||||
|
||||
@ApiPropertyOptional({ description: 'تعداد در هر صفحه', default: 15 })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsNumber()
|
||||
limit?: number = 15;
|
||||
|
||||
@ApiPropertyOptional({ description: 'فیلتر بر اساس وضعیت', enum: ['OPEN', 'IN_PROGRESS', 'ANSWERED', 'CLOSED'] })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
status?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'فیلتر بر اساس دستهبندی', enum: ['VET_CONSULTATION', 'ORDER_SUPPORT', 'PRODUCT_INQUIRY', 'GENERAL'] })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
category?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'جستجو در موضوع، شماره تیکت یا مشخصات کاربر' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
search?: string;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
UseGuards,
|
||||
Req,
|
||||
} from '@nestjs/common';
|
||||
import { TicketsService } from './tickets.service';
|
||||
import { CreateTicketDto, ReplyTicketDto, AdminUpdateTicketDto } from './dto/create-ticket.dto';
|
||||
import { TicketQueryDto } from './dto/ticket-query.dto';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { RolesGuard } from '../common/guards/roles.guard';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
import {
|
||||
ApiTags,
|
||||
ApiOperation,
|
||||
ApiBearerAuth,
|
||||
ApiOkResponse,
|
||||
} from '@nestjs/swagger';
|
||||
|
||||
@ApiTags('Tickets & Vet Consultation - تیکتینگ، پشتیبانی و مشاوره آنلاین دامپزشک')
|
||||
@Controller('tickets')
|
||||
export class TicketsController {
|
||||
constructor(private readonly ticketsService: TicketsService) {}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Post()
|
||||
@ApiOperation({ summary: 'ثبت تیکت جدید یا درخواست مشاوره دامپزشک توسط کاربر' })
|
||||
async createTicket(
|
||||
@Req() req: { user: { id: string } },
|
||||
@Body() dto: CreateTicketDto,
|
||||
) {
|
||||
return this.ticketsService.createTicket(req.user.id, dto);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Get('my-tickets')
|
||||
@ApiOperation({ summary: 'دریافت لیست تیکتهای کاربر لاگین شده' })
|
||||
async getMyTickets(@Req() req: { user: { id: string } }) {
|
||||
return this.ticketsService.getUserTickets(req.user.id);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Get(':id')
|
||||
@ApiOperation({ summary: 'دریافت رشته پیامها و جزئیات تیکت' })
|
||||
async getTicketDetails(
|
||||
@Req() req: { user: { id: string; role?: string } },
|
||||
@Param('id') id: string,
|
||||
) {
|
||||
const isAdmin = req.user.role?.includes('Admin') || false;
|
||||
return this.ticketsService.getTicketDetails(id, req.user.id, isAdmin);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Post(':id/messages')
|
||||
@ApiOperation({ summary: 'ارسال پاسخ جدید به تیکت توسط کاربر یا ادمین' })
|
||||
async replyTicket(
|
||||
@Req() req: { user: { id: string; role?: string } },
|
||||
@Param('id') id: string,
|
||||
@Body() dto: ReplyTicketDto,
|
||||
) {
|
||||
const isAdmin = req.user.role?.includes('Admin') || false;
|
||||
return this.ticketsService.replyToTicket(id, req.user.id, dto, isAdmin);
|
||||
}
|
||||
|
||||
// --- ADMIN ENDPOINTS ---
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/all')
|
||||
@ApiOperation({ summary: 'مشاهده و فیلتر تمامی تیکتها در پنل ادمین' })
|
||||
async getAdminTickets(@Query() query: TicketQueryDto) {
|
||||
return this.ticketsService.getAdminTickets(query);
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('Admin')
|
||||
@ApiBearerAuth()
|
||||
@Put('admin/:id/status')
|
||||
@ApiOperation({ summary: 'تغییر وضعیت و اولویت تیکت توسط ادمین' })
|
||||
async updateTicketStatus(
|
||||
@Param('id') id: string,
|
||||
@Body() dto: AdminUpdateTicketDto,
|
||||
) {
|
||||
return this.ticketsService.updateTicketStatus(id, dto);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TicketsService } from './tickets.service';
|
||||
import { TicketsController } from './tickets.controller';
|
||||
import { PrismaModule } from '../prisma/prisma.module';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule],
|
||||
controllers: [TicketsController],
|
||||
providers: [TicketsService],
|
||||
exports: [TicketsService],
|
||||
})
|
||||
export class TicketsModule {}
|
||||
@@ -0,0 +1,276 @@
|
||||
import {
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { CreateTicketDto, ReplyTicketDto, AdminUpdateTicketDto } from './dto/create-ticket.dto';
|
||||
import { TicketQueryDto } from './dto/ticket-query.dto';
|
||||
import { Prisma } from '@prisma/client';
|
||||
|
||||
@Injectable()
|
||||
export class TicketsService {
|
||||
private readonly logger = new Logger(TicketsService.name);
|
||||
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
private generateTicketNumber(): string {
|
||||
const random = Math.floor(10000 + Math.random() * 90000);
|
||||
return `TK-${random}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. Create a new support ticket / veterinary consultation
|
||||
*/
|
||||
async createTicket(userId: string, dto: CreateTicketDto) {
|
||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||
if (!user) {
|
||||
throw new NotFoundException('کاربر یافت نشد');
|
||||
}
|
||||
|
||||
const ticketNumber = this.generateTicketNumber();
|
||||
const senderName = `${user.firstName || ''} ${user.lastName || ''}`.trim() || user.mobile;
|
||||
|
||||
const ticket = await this.prisma.ticket.create({
|
||||
data: {
|
||||
ticketNumber,
|
||||
userId,
|
||||
petId: dto.petId || null,
|
||||
subject: dto.subject,
|
||||
category: dto.category || 'VET_CONSULTATION',
|
||||
priority: dto.priority || 'MEDIUM',
|
||||
status: 'OPEN',
|
||||
messages: {
|
||||
create: {
|
||||
senderId: userId,
|
||||
senderRole: user.role.includes('Admin') ? 'ADMIN' : 'USER',
|
||||
senderName,
|
||||
message: dto.message,
|
||||
attachment: dto.attachment || null,
|
||||
},
|
||||
},
|
||||
},
|
||||
include: {
|
||||
pet: true,
|
||||
messages: {
|
||||
orderBy: { createdAt: 'asc' },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'تیکت شما با موفقیت ثبت شد و به زودی توسط کارشناسان پاسخ داده میشود.',
|
||||
data: ticket,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 2. Get tickets of a specific user
|
||||
*/
|
||||
async getUserTickets(userId: string) {
|
||||
const tickets = await this.prisma.ticket.findMany({
|
||||
where: { userId },
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
include: {
|
||||
pet: true,
|
||||
messages: {
|
||||
orderBy: { createdAt: 'asc' },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: tickets,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 3. Get single ticket details
|
||||
*/
|
||||
async getTicketDetails(ticketId: string, userId?: string, isAdmin: boolean = false) {
|
||||
const ticket = await this.prisma.ticket.findUnique({
|
||||
where: { id: ticketId },
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
mobile: true,
|
||||
email: true,
|
||||
role: true,
|
||||
},
|
||||
},
|
||||
pet: true,
|
||||
messages: {
|
||||
orderBy: { createdAt: 'asc' },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!ticket) {
|
||||
throw new NotFoundException('تیکت یافت نشد');
|
||||
}
|
||||
|
||||
if (!isAdmin && userId && ticket.userId !== userId) {
|
||||
throw new ForbiddenException('شما دسترسی به این تیکت را ندارید');
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: ticket,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 4. Reply to a ticket (User or Admin)
|
||||
*/
|
||||
async replyToTicket(
|
||||
ticketId: string,
|
||||
senderId: string,
|
||||
dto: ReplyTicketDto,
|
||||
isAdmin: boolean = false,
|
||||
) {
|
||||
const ticket = await this.prisma.ticket.findUnique({
|
||||
where: { id: ticketId },
|
||||
include: { user: true },
|
||||
});
|
||||
|
||||
if (!ticket) {
|
||||
throw new NotFoundException('تیکت یافت نشد');
|
||||
}
|
||||
|
||||
if (!isAdmin && ticket.userId !== senderId) {
|
||||
throw new ForbiddenException('شما دسترسی به این تیکت را ندارید');
|
||||
}
|
||||
|
||||
const sender = await this.prisma.user.findUnique({ where: { id: senderId } });
|
||||
const senderRole = isAdmin ? (sender?.role.includes('Doctor') ? 'VET_DOCTOR' : 'ADMIN') : 'USER';
|
||||
const senderName = isAdmin
|
||||
? `${sender?.firstName || 'پشتیبان'} ${sender?.lastName || 'کنینا'}`.trim()
|
||||
: `${sender?.firstName || ''} ${sender?.lastName || ''}`.trim() || sender?.mobile || 'کاربر';
|
||||
|
||||
const newStatus = isAdmin ? (dto.status || 'ANSWERED') : 'IN_PROGRESS';
|
||||
|
||||
const [newMessage] = await this.prisma.$transaction([
|
||||
this.prisma.ticketMessage.create({
|
||||
data: {
|
||||
ticketId,
|
||||
senderId,
|
||||
senderRole,
|
||||
senderName,
|
||||
message: dto.message,
|
||||
attachment: dto.attachment || null,
|
||||
},
|
||||
}),
|
||||
this.prisma.ticket.update({
|
||||
where: { id: ticketId },
|
||||
data: {
|
||||
status: newStatus,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'پاسخ با موفقیت ارسال شد',
|
||||
data: newMessage,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 5. Admin: List all tickets with filtering & pagination
|
||||
*/
|
||||
async getAdminTickets(query: TicketQueryDto) {
|
||||
const page = Math.max(1, Number(query.page) || 1);
|
||||
const limit = Math.max(1, Math.min(100, Number(query.limit) || 15));
|
||||
const skip = (page - 1) * limit;
|
||||
|
||||
const where: Prisma.TicketWhereInput = {};
|
||||
|
||||
if (query.status && query.status !== 'ALL') {
|
||||
where.status = query.status;
|
||||
}
|
||||
|
||||
if (query.category && query.category !== 'ALL') {
|
||||
where.category = query.category;
|
||||
}
|
||||
|
||||
if (query.search) {
|
||||
const s = query.search.trim();
|
||||
where.OR = [
|
||||
{ ticketNumber: { contains: s, mode: 'insensitive' } },
|
||||
{ subject: { contains: s, mode: 'insensitive' } },
|
||||
{
|
||||
user: {
|
||||
OR: [
|
||||
{ firstName: { contains: s, mode: 'insensitive' } },
|
||||
{ lastName: { contains: s, mode: 'insensitive' } },
|
||||
{ mobile: { contains: s } },
|
||||
],
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const [tickets, total] = await Promise.all([
|
||||
this.prisma.ticket.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: limit,
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
include: {
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
mobile: true,
|
||||
},
|
||||
},
|
||||
pet: true,
|
||||
messages: {
|
||||
take: 1,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
},
|
||||
},
|
||||
}),
|
||||
this.prisma.ticket.count({ where }),
|
||||
]);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: tickets,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
lastPage: Math.ceil(total / limit),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 6. Admin: Update Ticket Status / Priority
|
||||
*/
|
||||
async updateTicketStatus(ticketId: string, dto: AdminUpdateTicketDto) {
|
||||
const ticket = await this.prisma.ticket.update({
|
||||
where: { id: ticketId },
|
||||
data: {
|
||||
...(dto.status ? { status: dto.status } : {}),
|
||||
...(dto.priority ? { priority: dto.priority } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'وضعیت تیکت بروزرسانی شد',
|
||||
data: ticket,
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user