Files
canina/backend/src/prescriptions/prescriptions.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

166 lines
4.6 KiB
TypeScript

import {
Injectable,
NotFoundException,
ForbiddenException,
Logger,
} from "@nestjs/common";
import { PrismaService } from "../prisma/prisma.service";
import { SmsService } from "../common/services/sms.service";
@Injectable()
export class PrescriptionsService {
private readonly logger = new Logger(PrescriptionsService.name);
constructor(
private prisma: PrismaService,
private smsService: SmsService,
) {}
async create(
userId: string | null,
data: {
petId?: string;
petName?: string;
petType?: string;
petBreed?: string;
petAge?: number;
petWeight?: number;
phone?: string;
fileUrl: string;
notes?: string;
},
) {
let finalUserId = userId;
let finalPetId = data.petId || null;
// 1. If phone is provided, find or create user automatically
if (data.phone) {
const cleanPhone = data.phone.trim();
let user = await this.prisma.user.findFirst({
where: { mobile: cleanPhone },
});
if (!user) {
user = await this.prisma.user.create({
data: {
mobile: cleanPhone,
role: "Customer",
firstName: data.petName ? `سرپرست ${data.petName}` : "کاربر",
lastName: "کنینا",
},
});
}
finalUserId = user.id;
// 2. If petName is provided and user exists, find or create pet
if (data.petName && !finalPetId) {
const cleanPetName = data.petName.trim();
let pet = await this.prisma.pet.findFirst({
where: {
userId: user.id,
name: cleanPetName,
},
});
if (!pet) {
pet = await this.prisma.pet.create({
data: {
userId: user.id,
name: cleanPetName,
type: data.petType || "سگ",
breed: data.petBreed || "نامشخص",
age: data.petAge !== undefined ? data.petAge : 0,
weight: data.petWeight !== undefined ? data.petWeight : 0,
activityLevel: "متوسط",
},
});
}
finalPetId = pet.id;
}
}
return this.prisma.prescription.create({
data: {
userId: finalUserId || undefined,
petId: finalPetId || undefined,
fileUrl: data.fileUrl,
notes: data.notes,
status: "PENDING",
},
include: { user: true, pet: true },
});
}
async findAll(userId: string, isAdmin: boolean) {
if (isAdmin) {
return this.prisma.prescription.findMany({
orderBy: { createdAt: "desc" },
include: { user: true, pet: true },
});
}
return this.prisma.prescription.findMany({
where: { userId },
orderBy: { createdAt: "desc" },
include: { pet: true },
});
}
async findOne(id: string, userId: string, isAdmin: boolean) {
const item = await this.prisma.prescription.findUnique({
where: { id },
include: { user: true, pet: true },
});
if (!item) {
throw new NotFoundException(`Prescription with ID ${id} not found`);
}
if (!isAdmin && item.userId !== userId) {
throw new ForbiddenException("Access denied to this prescription");
}
return item;
}
async review(
id: string,
reviewData: {
status: "APPROVED" | "REJECTED" | "PENDING";
adminNotes?: string;
},
) {
const item = await this.prisma.prescription.findUnique({
where: { id },
include: { user: true, pet: true },
});
if (!item) {
throw new NotFoundException(`Prescription with ID ${id} not found`);
}
const updated = await this.prisma.prescription.update({
where: { id },
data: {
status: reviewData.status,
adminNotes: reviewData.adminNotes,
},
include: { user: true, pet: true },
});
// Send SMS notification if prescription was reviewed/approved and user has mobile
if (item.user?.mobile && reviewData.status === "APPROVED") {
const petTitle = item.pet?.name ? ` برای «${item.pet.name}»` : "";
const smsText = `کنینا: نسخه پزشکی شما${petTitle} توسط تیم تخصصی بررسی و تایید شد. جهت مشاهده تجویز پزشک و سفارش مکمل‌ها به پنل کاربری خود در canina.ir مراجعه کنید.`;
try {
await this.smsService.sendSms(item.user.mobile, smsText);
} catch (smsErr) {
this.logger.warn(
`Failed to send prescription SMS to ${item.user.mobile}:`,
smsErr,
);
}
}
return updated;
}
}