Files
canina/backend/src/tickets/tickets.service.ts
T
devops ddbf1ca026
Deploy Canina / deploy (push) Successful in 4m1s
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 7s
test: comprehensive test suites and quality gates pass across backend, storefront and admin
- Backend (NestJS): 82 suites, 641 tests passing; 0 ESLint errors; 0 tsc errors. Hardened SSL cert/key matching, SSRF IP pinning, and eBank validation.
- Admin Panel (Vite/React): 48 suites, 300 tests passing; 0 ESLint errors; 0 tsc errors. Full coverage across all pages and settings.
- Storefront (Next.js): 62 suites, 368 tests passing; 0 ESLint errors; 0 tsc errors.
- Fixed unmount lifecycle guards, promise error handling, and component edge cases.
2026-10-13 16:01:00 +00:00

295 lines
7.1 KiB
TypeScript

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,
};
}
}