chore(workspace): eradicate all tsc errors and eslint warnings across frontend, admin, and backend
Deploy Canina / deploy (push) Failing after 29s

This commit is contained in:
parsa committed 2026-08-07 07:39:26 +03:30
1 parent 4659a7b1de
commit 9f11d8fb2d
98 files changed
+1272 -1009

No files matched your search

+75 -152
View File
@@ -1,15 +1,20 @@
import {
Controller,
Get,
UseGuards,
Param,
Put,
Post,
Body,
Put,
Delete,
Body,
Param,
Query,
UseGuards,
} from '@nestjs/common';
import { AdminService } from './admin.service';
import {
AdminService,
PaginationQuery,
ProductInput,
CouponInput,
} from './admin.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import {
ApiTags,
@@ -18,65 +23,44 @@ import {
ApiQuery,
} from '@nestjs/swagger';
@ApiTags('Admin - پنل مدیریت')
@ApiTags('Admin - مدیریت سیستم')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Controller('admin')
export class AdminController {
constructor(private readonly adminService: AdminService) {}
@UseGuards(JwtAuthGuard)
@Get('dashboard/stats')
@ApiOperation({ summary: 'دریافت آمار کلی داشبورد' })
@ApiOperation({ summary: 'داشبورد مدیریت و آمار کلیدی سیستم' })
async getDashboardStats() {
const stats = await this.adminService.getDashboardStats();
return {
success: true,
data: stats,
};
const data = await this.adminService.getDashboardStats();
return { success: true, data };
}
@UseGuards(JwtAuthGuard)
@Get('users')
@ApiOperation({ summary: 'لیست کاربران' })
@ApiOperation({ summary: 'لیست کاربران سیستم (با صفحه‌بندی)' })
@ApiQuery({ name: 'page', required: false, description: 'شماره صفحه' })
@ApiQuery({ name: 'limit', required: false, description: 'تعداد آیتم‌ها' })
@ApiQuery({
name: 'search',
required: false,
description: 'جستجو در نام یا ایمیل',
})
@ApiQuery({
name: 'role',
required: false,
description: 'فیلتر بر اساس نقش کاربر',
})
async getUsers(
@Query('page') page?: string,
@Query('limit') limit?: string,
@Query('search') search?: string,
@Query('role') role?: string,
) {
const data = await this.adminService.getUsers({
page,
limit,
search,
role,
});
return { success: true, ...data };
@ApiQuery({ name: 'search', required: false, description: 'جستجو' })
async getUsers(@Query() query: PaginationQuery) {
const result = await this.adminService.getUsers(query);
return { success: true, ...result };
}
@Get('users/:id')
@ApiOperation({ summary: 'جزئیات کاربر' })
async getUserDetails(@Param('id') id: string) {
const data = await this.adminService.getUserDetails(id);
return { success: true, data };
}
@UseGuards(JwtAuthGuard)
@Put('users/:id/role')
@ApiOperation({ summary: 'تغییر نقش کاربر' })
async updateUserRole(@Param('id') id: string, @Body('role') role: string) {
const user = await this.adminService.updateUserRole(id, role);
return {
success: true,
data: user,
};
return { success: true, data: user };
}
@UseGuards(JwtAuthGuard)
@Post('users/:id/wallet-adjust')
@ApiOperation({ summary: 'شارژ یا کسر مستقیم کیف پول کاربر توسط ادمین' })
async adjustWallet(
@@ -98,44 +82,26 @@ export class AdminController {
};
}
@UseGuards(JwtAuthGuard)
@Get('products')
@ApiOperation({ summary: 'لیست محصولات (مدیریت)' })
@ApiQuery({ name: 'page', required: false, description: 'شماره صفحه' })
@ApiQuery({ name: 'limit', required: false, description: 'تعداد آیتم‌ها' })
@ApiQuery({ name: 'search', required: false, description: 'جستجو' })
@ApiQuery({
name: 'categoryId',
required: false,
description: 'شناسه دسته‌بندی',
})
async getProducts(
@Query('page') page?: string,
@Query('limit') limit?: string,
@Query('search') search?: string,
@Query('categoryId') categoryId?: string,
) {
const data = await this.adminService.getProducts({
page,
limit,
search,
categoryId,
});
return { success: true, ...data };
async getProducts(@Query() query: PaginationQuery) {
const result = await this.adminService.getProducts(query);
return { success: true, ...result };
}
@UseGuards(JwtAuthGuard)
@Post('products')
@ApiOperation({ summary: 'ایجاد محصول جدید' })
async createProduct(@Body() data: any) {
async createProduct(@Body() data: ProductInput) {
const product = await this.adminService.createProduct(data);
return { success: true, data: product };
}
@UseGuards(JwtAuthGuard)
@Put('products/:id')
@ApiOperation({ summary: 'ویرایش محصول' })
async updateProduct(@Param('id') id: string, @Body() data: any) {
async updateProduct(@Param('id') id: string, @Body() data: ProductInput) {
const product = await this.adminService.updateProduct(id, data);
return {
success: true,
@@ -143,87 +109,62 @@ export class AdminController {
};
}
@UseGuards(JwtAuthGuard)
@Delete('products/:id')
@ApiOperation({ summary: 'حذف محصول' })
async deleteProduct(@Param('id') id: string) {
await this.adminService.deleteProduct(id);
return {
success: true,
message: 'Product deleted',
};
return { success: true };
}
@UseGuards(JwtAuthGuard)
@Get('orders')
@ApiOperation({ summary: 'لیست سفارش‌ها' })
@ApiOperation({ summary: 'لیست سفارش‌ها (مدیریت)' })
@ApiQuery({ name: 'page', required: false, description: 'شماره صفحه' })
@ApiQuery({ name: 'limit', required: false, description: 'تعداد آیتم‌ها' })
@ApiQuery({ name: 'search', required: false, description: 'جستجو' })
@ApiQuery({ name: 'status', required: false, description: 'وضعیت سفارش' })
async getOrders(
@Query('page') page?: string,
@Query('limit') limit?: string,
@Query('search') search?: string,
@Query('status') status?: string,
) {
const data = await this.adminService.getOrders({
page,
limit,
search,
status,
});
return { success: true, ...data };
@ApiQuery({ name: 'status', required: false, description: 'فیلتر وضعیت' })
async getOrders(@Query() query: PaginationQuery) {
const result = await this.adminService.getOrders(query);
return { success: true, ...result };
}
@UseGuards(JwtAuthGuard)
@Put('orders/:id/status')
@ApiOperation({ summary: 'تغییر وضعیت و کد رهگیری سفارش' })
@ApiOperation({ summary: 'بروزرسانی وضعیت سفارش' })
async updateOrderStatus(
@Param('id') id: string,
@Body('status') status: string,
@Body('trackingNumber') trackingNumber?: string,
@Body('trackingCode') trackingCode?: string,
) {
const order = await this.adminService.updateOrderStatus(
id,
status,
trackingNumber,
trackingCode,
);
return {
success: true,
data: order,
};
return { success: true, data: order };
}
// --- Coupons ---
@UseGuards(JwtAuthGuard)
@Get('coupons')
@ApiOperation({ summary: 'لیست کد تخفیف‌ها' })
@ApiQuery({ name: 'page', required: false, description: 'شماره صفحه' })
@ApiQuery({ name: 'limit', required: false, description: 'تعداد آیتم‌ها' })
@ApiQuery({ name: 'search', required: false, description: 'جستجو' })
async getCoupons(@Query() query: any) {
async getCoupons(@Query() query: PaginationQuery) {
const coupons = await this.adminService.getCoupons(query);
return { success: true, ...coupons };
}
@UseGuards(JwtAuthGuard)
@Post('coupons')
@ApiOperation({ summary: 'ایجاد کد تخفیف جدید' })
async createCoupon(@Body() data: any) {
async createCoupon(@Body() data: CouponInput) {
const coupon = await this.adminService.createCoupon(data);
return { success: true, data: coupon };
}
@UseGuards(JwtAuthGuard)
@Put('coupons/:id')
@ApiOperation({ summary: 'ویرایش کد تخفیف' })
async updateCoupon(@Param('id') id: string, @Body() data: any) {
async updateCoupon(@Param('id') id: string, @Body() data: CouponInput) {
const coupon = await this.adminService.updateCoupon(id, data);
return { success: true, data: coupon };
}
@UseGuards(JwtAuthGuard)
@Put('coupons/:id/toggle')
@ApiOperation({ summary: 'فعال/غیرفعال کردن کد تخفیف' })
async toggleCoupon(
@@ -234,7 +175,6 @@ export class AdminController {
return { success: true, data: coupon };
}
@UseGuards(JwtAuthGuard)
@Delete('coupons/:id')
@ApiOperation({ summary: 'حذف کد تخفیف' })
async deleteCoupon(@Param('id') id: string) {
@@ -242,63 +182,46 @@ export class AdminController {
return { success: true };
}
// --- Settings ---
@UseGuards(JwtAuthGuard)
@Get('settings')
@ApiOperation({ summary: 'دریافت تنظیمات' })
async getSettings() {
const settings = await this.adminService.getSettings();
return { success: true, data: settings };
}
@UseGuards(JwtAuthGuard)
@Put('settings')
@ApiOperation({ summary: 'ذخیره تنظیمات' })
async updateSettings(@Body() data: Record<string, string>) {
const settings = await this.adminService.updateSettings(data);
return { success: true, data: settings };
}
@UseGuards(JwtAuthGuard)
@Get('pets')
@ApiOperation({ summary: 'لیست پت‌ها (مدیریت)' })
@ApiQuery({ name: 'page', required: false })
@ApiQuery({ name: 'limit', required: false })
@ApiQuery({ name: 'search', required: false })
async getPets(
@Query('page') page?: string,
@Query('limit') limit?: string,
@Query('search') search?: string,
) {
const data = await this.adminService.getPets({ page, limit, search });
return { success: true, ...data };
}
// --- Doctors / Vets ---
@Get('doctors')
@ApiOperation({ summary: 'لیست پزشکان و متخصصان' })
@ApiOperation({ summary: 'لیست پزشکان و متخصصین' })
async getDoctors() {
const doctors = await this.adminService.getDoctors();
return { success: true, data: doctors };
const data = await this.adminService.getDoctors();
return { success: true, data };
}
@UseGuards(JwtAuthGuard)
@Post('doctors')
@ApiOperation({ summary: 'افزودن پزشک جدید' })
async createDoctor(@Body() body: any) {
const doctor = await this.adminService.createDoctor(body);
return { success: true, data: doctor };
async createDoctor(
@Body()
body: {
name: string;
title: string;
avatarUrl?: string;
bio?: string;
clinic?: string;
},
) {
const data = await this.adminService.createDoctor(body);
return { success: true, data };
}
@UseGuards(JwtAuthGuard)
@Put('doctors/:id')
@ApiOperation({ summary: 'ویرایش اطلاعات پزشک' })
async updateDoctor(@Param('id') id: string, @Body() body: any) {
const doctor = await this.adminService.updateDoctor(id, body);
return { success: true, data: doctor };
@ApiOperation({ summary: 'ویرایش پزشک' })
async updateDoctor(
@Param('id') id: string,
@Body()
body: {
name?: string;
title?: string;
avatarUrl?: string;
bio?: string;
clinic?: string;
},
) {
const data = await this.adminService.updateDoctor(id, body);
return { success: true, data };
}
@UseGuards(JwtAuthGuard)
@Delete('doctors/:id')
@ApiOperation({ summary: 'حذف پزشک' })
async deleteDoctor(@Param('id') id: string) {
+161 -105
View File
@@ -1,7 +1,64 @@
import { Injectable, HttpException, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { RedisService } from '../redis/redis.service';
export class PaginationQuery {
page?: number | string;
limit?: number | string;
search?: string;
role?: string;
categoryId?: string;
status?: string;
}
export class ProductInput {
artNo?: string;
nameFa?: string;
nameEn?: string;
scientificTagline?: string;
description?: string;
shortDescription?: string;
categoryId?: string;
categorySlug?: string;
priceValue?: number;
priceDisplay?: string;
unit?: string;
packageSize?: number;
dosageLogic?: string;
suitableFor?: string;
imageUrl?: string;
images?: string | string[];
podcastUrl?: string | null;
videoUrl?: string | null;
pdfUrl?: string | null;
metaTitle?: string;
metaDescription?: string;
keywords?: string;
canonicalUrl?: string;
slug?: string;
symptoms?: string[];
}
export class CouponTargetInput {
targetType!: string;
targetId!: string;
modifierType?: string;
modifierValue?: number;
}
export class CouponInput {
code!: string;
type?: string;
value!: number;
minCartValue?: number;
maxCartValue?: number;
maxUses?: number;
expiresAt?: string | Date;
isActive?: boolean;
targets?: CouponTargetInput[];
}
@Injectable()
export class AdminService {
constructor(
@@ -10,7 +67,6 @@ export class AdminService {
) {}
async getDashboardStats() {
// total revenue
const orders = await this.prisma.order.findMany({
where: { status: { not: 'failed' } },
select: { totalAmount: true },
@@ -18,15 +74,12 @@ export class AdminService {
const revenue = orders.reduce((sum, o) => sum + Number(o.totalAmount), 0);
// new orders count (processing status)
const newOrders = await this.prisma.order.count({
where: { status: 'processing' },
});
// active users count
const users = await this.prisma.user.count();
// Today's request count from Redis counter (set by MetricsController)
const todayKey = `visits:${new Date().toISOString().split('T')[0]}`;
let todayVisits = 0;
try {
@@ -57,12 +110,12 @@ export class AdminService {
};
}
async getUsers(query: any) {
async getUsers(query: PaginationQuery = {}) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 10;
const skip = (page - 1) * limit;
const where: any = {};
const where: Prisma.UserWhereInput = {};
if (query.search) {
where.OR = [
{ firstName: { contains: query.search, mode: 'insensitive' } },
@@ -102,51 +155,18 @@ export class AdminService {
};
}
async adjustUserWallet(
userId: string,
amount: number,
type: 'deposit' | 'withdrawal' | 'refund',
description?: string,
) {
const user = await this.prisma.user.findUnique({ where: { id: userId } });
if (!user) {
throw new NotFoundException('کاربر مورد نظر یافت نشد');
}
const adjustAmount =
type === 'withdrawal' ? -Math.abs(amount) : Math.abs(amount);
const currentBalance = Number(user.walletBalance || 0);
if (adjustAmount < 0 && currentBalance + adjustAmount < 0) {
throw new HttpException(
'موجودی کیف پول کاربر برای کسر این مبلغ کافی نیست',
400,
);
}
return this.prisma.$transaction([
this.prisma.walletTransaction.create({
data: {
userId,
amount: Math.abs(amount),
type: type === 'withdrawal' ? 'withdrawal' : 'deposit',
status: 'completed',
description:
description ||
(type === 'refund'
? 'بازگشت وجه توسط ادمین'
: type === 'deposit'
? 'شارژ توسط ادمین'
: 'کسر توسط ادمین'),
},
}),
this.prisma.user.update({
where: { id: userId },
data: {
walletBalance: { increment: adjustAmount },
},
}),
]);
async getUserDetails(id: string) {
const user = await this.prisma.user.findUnique({
where: { id },
include: {
addresses: true,
pets: true,
orders: { orderBy: { createdAt: 'desc' }, take: 10 },
walletTransactions: { orderBy: { createdAt: 'desc' }, take: 20 },
},
});
if (!user) throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد.`);
return user;
}
async updateUserRole(id: string, role: string) {
@@ -156,16 +176,16 @@ export class AdminService {
});
}
async getProducts(query: any) {
async getProducts(query: PaginationQuery = {}) {
try {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 10;
const skip = (page - 1) * limit;
const where: any = {};
const where: Prisma.ProductWhereInput = {};
if (query.search) {
where.OR = [
{ name: { contains: query.search, mode: 'insensitive' } },
{ nameFa: { contains: query.search, mode: 'insensitive' } },
{ artNo: { contains: query.search } },
];
}
@@ -189,29 +209,30 @@ export class AdminService {
meta: { total, page, limit, lastPage: Math.ceil(total / limit) },
};
} catch (error) {
console.error('[AdminService] getProducts error:', error);
throw new HttpException(error.message || 'Error fetching products', 500);
const err = error as { message?: string };
console.error('[AdminService] getProducts error:', err);
throw new HttpException(err.message || 'Error fetching products', 500);
}
}
async createProduct(data: any) {
async createProduct(data: ProductInput) {
const product = await this.prisma.product.create({
data: {
artNo: data.artNo,
nameFa: data.nameFa,
nameEn: data.nameEn,
scientificTagline: data.scientificTagline,
description: data.description,
shortDescription: data.shortDescription,
categoryId: data.categoryId,
artNo: data.artNo || `ART-${Date.now()}`,
nameFa: data.nameFa || '',
nameEn: data.nameEn || '',
scientificTagline: data.scientificTagline || '',
description: data.description || '',
shortDescription: data.shortDescription || '',
categoryId: data.categoryId || '',
categorySlug: data.categorySlug || 'general',
priceValue: data.priceValue,
priceDisplay: data.priceDisplay,
unit: data.unit,
packageSize: data.packageSize,
dosageLogic: data.dosageLogic,
suitableFor: data.suitableFor,
imageUrl: data.imageUrl,
priceValue: data.priceValue || 0,
priceDisplay: data.priceDisplay || '',
unit: data.unit || 'عدد',
packageSize: data.packageSize || 100,
dosageLogic: data.dosageLogic || '',
suitableFor: data.suitableFor || 'سگ',
imageUrl: data.imageUrl || '',
images: Array.isArray(data.images)
? data.images
: data.images
@@ -220,11 +241,11 @@ export class AdminService {
podcastUrl: data.podcastUrl || null,
videoUrl: data.videoUrl || null,
pdfUrl: data.pdfUrl || null,
metaTitle: data.metaTitle,
metaDescription: data.metaDescription,
keywords: data.keywords,
canonicalUrl: data.canonicalUrl,
slug: data.slug || data.artNo,
metaTitle: data.metaTitle || '',
metaDescription: data.metaDescription || '',
keywords: data.keywords || '',
canonicalUrl: data.canonicalUrl || '',
slug: data.slug || data.artNo || `slug-${Date.now()}`,
},
});
@@ -235,14 +256,14 @@ export class AdminService {
productId: product.id,
symptom: s.trim(),
}))
.filter((s: any) => s.symptom.length > 0),
.filter((s: { symptom: string }) => s.symptom.length > 0),
});
}
return product;
}
async updateProduct(id: string, data: any) {
async updateProduct(id: string, data: ProductInput) {
const existing = await this.prisma.product.findUnique({ where: { id } });
if (!existing) {
throw new NotFoundException(`محصولی با شناسه ${id} یافت نشد.`);
@@ -266,7 +287,11 @@ export class AdminService {
dosageLogic: data.dosageLogic,
suitableFor: data.suitableFor,
imageUrl: data.imageUrl,
images: Array.isArray(data.images) ? data.images : undefined,
images: Array.isArray(data.images)
? data.images
: data.images
? [data.images]
: undefined,
podcastUrl: data.podcastUrl !== undefined ? data.podcastUrl : undefined,
videoUrl: data.videoUrl !== undefined ? data.videoUrl : undefined,
pdfUrl: data.pdfUrl !== undefined ? data.pdfUrl : undefined,
@@ -287,7 +312,7 @@ export class AdminService {
productId: id,
symptom: s.trim(),
}))
.filter((s: any) => s.symptom.length > 0),
.filter((s: { symptom: string }) => s.symptom.length > 0),
});
}
}
@@ -301,21 +326,20 @@ export class AdminService {
});
}
async getOrders(query: any) {
async getOrders(query: PaginationQuery = {}) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 10;
const skip = (page - 1) * limit;
const where: any = {};
const where: Prisma.OrderWhereInput = {};
if (query.search) {
where.OR = [
{ id: { contains: query.search } },
{ trackingNumber: { contains: query.search, mode: 'insensitive' } },
{
user: { firstName: { contains: query.search, mode: 'insensitive' } },
},
{ user: { lastName: { contains: query.search, mode: 'insensitive' } } },
{ user: { phone: { contains: query.search } } },
{ user: { mobile: { contains: query.search } } },
];
}
if (query.status) {
@@ -348,7 +372,7 @@ export class AdminService {
}
async updateOrderStatus(id: string, status: string, trackingNumber?: string) {
const dataToUpdate: any = { status };
const dataToUpdate: Prisma.OrderUpdateInput = { status };
if (trackingNumber !== undefined) {
dataToUpdate.trackingNumber = trackingNumber;
}
@@ -366,22 +390,22 @@ export class AdminService {
});
}
// --- Coupons Engine ---
async getCoupons(query: any) {
const { page = 1, limit = 10, search = '' } = query;
const skip = (Number(page) - 1) * Number(limit);
async getCoupons(query: PaginationQuery = {}) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 10;
const skip = (page - 1) * limit;
const where = search
? { code: { contains: search, mode: 'insensitive' as any } }
const where: Prisma.CouponWhereInput = query.search
? { code: { contains: query.search, mode: 'insensitive' } }
: {};
const [data, total] = await Promise.all([
this.prisma.coupon.findMany({
where,
skip,
take: Number(limit),
take: limit,
orderBy: { createdAt: 'desc' },
include: { targets: true }, // Include polymorphic targets
include: { targets: true },
}),
this.prisma.coupon.count({ where }),
]);
@@ -390,14 +414,14 @@ export class AdminService {
data,
meta: {
total,
page: Number(page),
limit: Number(limit),
lastPage: Math.ceil(total / Number(limit)),
page,
limit,
lastPage: Math.ceil(total / limit),
},
};
}
async createCoupon(data: any) {
async createCoupon(data: CouponInput) {
return this.prisma.coupon.create({
data: {
code: data.code,
@@ -411,7 +435,7 @@ export class AdminService {
targets:
data.targets && data.targets.length > 0
? {
create: data.targets.map((t: any) => ({
create: data.targets.map((t) => ({
targetType: t.targetType,
targetId: t.targetId,
modifierType: t.modifierType || 'override',
@@ -424,8 +448,7 @@ export class AdminService {
});
}
async updateCoupon(id: string, data: any) {
// Delete old targets and recreate them
async updateCoupon(id: string, data: CouponInput) {
await this.prisma.couponTarget.deleteMany({ where: { couponId: id } });
return this.prisma.coupon.update({
@@ -442,7 +465,7 @@ export class AdminService {
targets:
data.targets && data.targets.length > 0
? {
create: data.targets.map((t: any) => ({
create: data.targets.map((t) => ({
targetType: t.targetType,
targetId: t.targetId,
modifierType: t.modifierType || 'override',
@@ -472,12 +495,11 @@ export class AdminService {
const settings = await this.prisma.uiText.findMany();
return settings.reduce(
(acc, curr) => ({ ...acc, [curr.key]: curr.value }),
{},
{} as Record<string, string>,
);
}
async updateSettings(data: Record<string, string>) {
// Upsert all keys
const operations = Object.entries(data).map(([key, value]) => {
return this.prisma.uiText.upsert({
where: { key },
@@ -490,12 +512,12 @@ export class AdminService {
return this.getSettings();
}
async getPets(query: any) {
async getPets(query: PaginationQuery = {}) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 10;
const skip = (page - 1) * limit;
const where: any = {};
const where: Prisma.PetWhereInput = {};
if (query.search) {
where.OR = [
{ name: { contains: query.search, mode: 'insensitive' } },
@@ -572,4 +594,38 @@ export class AdminService {
async deleteDoctor(id: string) {
return this.prisma.doctor.delete({ where: { id } });
}
async adjustUserWallet(
userId: string,
amount: number,
type: 'deposit' | 'withdrawal' | 'refund',
description?: string,
) {
const user = await this.prisma.user.findUnique({ where: { id: userId } });
if (!user) {
throw new NotFoundException(`کاربری با شناسه ${userId} یافت نشد.`);
}
const transaction = await this.prisma.walletTransaction.create({
data: {
userId,
amount,
type,
status: 'completed',
description: description || 'تغییر دستی توسط مدیر سیستم',
},
});
const isIncrement = type === 'deposit' || type === 'refund';
await this.prisma.user.update({
where: { id: userId },
data: {
walletBalance: isIncrement
? { increment: amount }
: { decrement: amount },
},
});
return transaction;
}
}
+11 -4
View File
@@ -10,7 +10,8 @@ import {
UseGuards,
Request,
} from '@nestjs/common';
import { BlogsService } from './blogs.service';
import { Prisma } from '@prisma/client';
import { BlogsService, BlogQuery } from './blogs.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import {
ApiTags,
@@ -31,20 +32,26 @@ export class BlogsController {
@ApiQuery({ name: 'page', required: false, description: 'شماره صفحه' })
@ApiQuery({ name: 'limit', required: false, description: 'تعداد آیتم‌ها' })
@ApiQuery({ name: 'search', required: false, description: 'جستجو' })
async getBlogs(@Query() query: any) {
async getBlogs(@Query() query: BlogQuery) {
return this.blogsService.getBlogs(query);
}
@Post()
@ApiOperation({ summary: 'ایجاد مقاله جدید' })
async createBlog(@Body() body: any, @Request() req: any) {
async createBlog(
@Body() body: Prisma.BlogCreateWithoutAuthorInput,
@Request() req: { user: { id: string } },
) {
const data = await this.blogsService.createBlog(body, req.user.id);
return { success: true, data };
}
@Put(':id')
@ApiOperation({ summary: 'ویرایش مقاله' })
async updateBlog(@Param('id') id: string, @Body() body: any) {
async updateBlog(
@Param('id') id: string,
@Body() body: Prisma.BlogUpdateInput,
) {
const data = await this.blogsService.updateBlog(id, body);
return { success: true, data };
}
+23 -12
View File
@@ -1,23 +1,31 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
export class BlogQuery {
page?: number | string;
limit?: number | string;
search?: string;
}
@Injectable()
export class BlogsService {
constructor(private prisma: PrismaService) {}
async getBlogs(query: any) {
const { page = 1, limit = 10, search = '' } = query;
const skip = (Number(page) - 1) * Number(limit);
async getBlogs(query: BlogQuery = {}) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 10;
const skip = (page - 1) * limit;
const where = search
? { title: { contains: search, mode: 'insensitive' as any } }
const where: Prisma.BlogWhereInput = query.search
? { title: { contains: query.search, mode: 'insensitive' } }
: {};
const [data, total] = await Promise.all([
this.prisma.blog.findMany({
where,
skip,
take: Number(limit),
take: limit,
orderBy: { createdAt: 'desc' },
include: { author: { select: { firstName: true, lastName: true } } },
}),
@@ -28,20 +36,23 @@ export class BlogsService {
data,
meta: {
total,
page: Number(page),
limit: Number(limit),
lastPage: Math.ceil(total / Number(limit)),
page,
limit,
lastPage: Math.ceil(total / limit),
},
};
}
async createBlog(data: any, authorId: string) {
async createBlog(
data: Prisma.BlogCreateWithoutAuthorInput,
authorId: string,
) {
return this.prisma.blog.create({
data: { ...data, authorId },
data: { ...data, author: { connect: { id: authorId } } },
});
}
async updateBlog(id: string, data: any) {
async updateBlog(id: string, data: Prisma.BlogUpdateInput) {
const blog = await this.prisma.blog.findUnique({ where: { id } });
if (!blog) throw new NotFoundException('Blog not found');
return this.prisma.blog.update({ where: { id }, data });
+8 -4
View File
@@ -9,7 +9,8 @@ import {
Query,
UseGuards,
} from '@nestjs/common';
import { CategoriesService } from './categories.service';
import { Prisma } from '@prisma/client';
import { CategoriesService, CategoryQuery } from './categories.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import {
ApiTags,
@@ -30,7 +31,7 @@ export class CategoriesController {
@ApiQuery({ name: 'page', required: false, description: 'شماره صفحه' })
@ApiQuery({ name: 'limit', required: false, description: 'تعداد آیتم‌ها' })
@ApiQuery({ name: 'search', required: false, description: 'جستجو در نام' })
async getCategories(@Query() query: any) {
async getCategories(@Query() query: CategoryQuery) {
return this.categoriesService.getCategories(query);
}
@@ -43,14 +44,17 @@ export class CategoriesController {
@Post()
@ApiOperation({ summary: 'ایجاد دسته‌بندی جدید' })
async createCategory(@Body() body: any) {
async createCategory(@Body() body: Prisma.CategoryCreateInput) {
const data = await this.categoriesService.createCategory(body);
return { success: true, data };
}
@Put(':id')
@ApiOperation({ summary: 'ویرایش دسته‌بندی' })
async updateCategory(@Param('id') id: string, @Body() body: any) {
async updateCategory(
@Param('id') id: string,
@Body() body: Prisma.CategoryUpdateInput,
) {
const data = await this.categoriesService.updateCategory(id, body);
return { success: true, data };
}
+28 -25
View File
@@ -1,23 +1,31 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
export class CategoryQuery {
page?: number | string;
limit?: number | string;
search?: string;
}
@Injectable()
export class CategoriesService {
constructor(private prisma: PrismaService) {}
async getCategories(query: any) {
const { page = 1, limit = 10, search = '' } = query;
const skip = (Number(page) - 1) * Number(limit);
async getCategories(query: CategoryQuery = {}) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 10;
const skip = (page - 1) * limit;
const where = search
? { name: { contains: search, mode: 'insensitive' as any } }
const where: Prisma.CategoryWhereInput = query.search
? { name: { contains: query.search, mode: 'insensitive' } }
: {};
const [data, total] = await Promise.all([
this.prisma.category.findMany({
where,
skip,
take: Number(limit),
take: limit,
orderBy: { createdAt: 'desc' },
}),
this.prisma.category.count({ where }),
@@ -27,9 +35,9 @@ export class CategoriesService {
data,
meta: {
total,
page: Number(page),
limit: Number(limit),
lastPage: Math.ceil(total / Number(limit)),
page,
limit,
lastPage: Math.ceil(total / limit),
},
};
}
@@ -38,28 +46,23 @@ export class CategoriesService {
return this.prisma.category.findMany({ orderBy: { name: 'asc' } });
}
async createCategory(data: any) {
const cleanData = { ...data };
Object.keys(cleanData).forEach((k) => {
if (cleanData[k] === '') cleanData[k] = null;
});
// Ensure required fields
if (!cleanData.slug)
cleanData.slug = cleanData.name.replace(/\s+/g, '-').toLowerCase();
async createCategory(data: Prisma.CategoryCreateInput) {
const nameStr = data.name || '';
const slugStr = data.slug || nameStr.replace(/\s+/g, '-').toLowerCase();
return this.prisma.category.create({ data: cleanData });
return this.prisma.category.create({
data: {
...data,
slug: slugStr,
},
});
}
async updateCategory(id: string, data: any) {
async updateCategory(id: string, data: Prisma.CategoryUpdateInput) {
const category = await this.prisma.category.findUnique({ where: { id } });
if (!category) throw new NotFoundException('Category not found');
const cleanData = { ...data };
Object.keys(cleanData).forEach((k) => {
if (cleanData[k] === '') cleanData[k] = null;
});
return this.prisma.category.update({ where: { id }, data: cleanData });
return this.prisma.category.update({ where: { id }, data });
}
async deleteCategory(id: string) {
+2 -2
View File
@@ -6,7 +6,7 @@ import {
Query,
UseGuards,
} from '@nestjs/common';
import { PetsService } from './pets.service';
import { PetsService, PetQuery } from './pets.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import {
ApiTags,
@@ -27,7 +27,7 @@ export class PetsController {
@ApiQuery({ name: 'page', required: false, description: 'شماره صفحه' })
@ApiQuery({ name: 'limit', required: false, description: 'تعداد آیتم‌ها' })
@ApiQuery({ name: 'search', required: false, description: 'جستجو' })
async getPets(@Query() query: any) {
async getPets(@Query() query: PetQuery) {
return this.petsService.getPets(query);
}
+17 -9
View File
@@ -1,23 +1,31 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
export class PetQuery {
page?: number | string;
limit?: number | string;
search?: string;
}
@Injectable()
export class PetsService {
constructor(private prisma: PrismaService) {}
async getPets(query: any) {
const { page = 1, limit = 10, search = '' } = query;
const skip = (Number(page) - 1) * Number(limit);
async getPets(query: PetQuery = {}) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 10;
const skip = (page - 1) * limit;
const where = search
? { name: { contains: search, mode: 'insensitive' as any } }
const where: Prisma.PetWhereInput = query.search
? { name: { contains: query.search, mode: 'insensitive' } }
: {};
const [data, total] = await Promise.all([
this.prisma.pet.findMany({
where,
skip,
take: Number(limit),
take: limit,
orderBy: { createdAt: 'desc' },
include: {
user: {
@@ -37,9 +45,9 @@ export class PetsService {
data,
meta: {
total,
page: Number(page),
limit: Number(limit),
lastPage: Math.ceil(total / Number(limit)),
page,
limit,
lastPage: Math.ceil(total / limit),
},
};
}
-6
View File
@@ -76,12 +76,6 @@ export class ReportsService {
});
// 3. Category Distribution
const categorySales: Record<string, number> = {};
for (const item of orderItems) {
if (item.productId) {
// Since we didn't fetch category id in the grouping, we'll approximate with full product list query
}
}
const categories = await this.prisma.category.findMany({
include: { products: { select: { id: true } } },
});
+8 -4
View File
@@ -9,7 +9,8 @@ import {
Query,
UseGuards,
} from '@nestjs/common';
import { WikiService } from './wiki.service';
import { Prisma } from '@prisma/client';
import { WikiService, WikiQuery } from './wiki.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import {
ApiTags,
@@ -30,20 +31,23 @@ export class WikiController {
@ApiQuery({ name: 'page', required: false, description: 'شماره صفحه' })
@ApiQuery({ name: 'limit', required: false, description: 'تعداد آیتم‌ها' })
@ApiQuery({ name: 'search', required: false, description: 'جستجو' })
async getTerms(@Query() query: any) {
async getTerms(@Query() query: WikiQuery) {
return this.wikiService.getTerms(query);
}
@Post()
@ApiOperation({ summary: 'ایجاد اصطلاح جدید' })
async createTerm(@Body() body: any) {
async createTerm(@Body() body: Prisma.ScientificTermCreateInput) {
const data = await this.wikiService.createTerm(body);
return { success: true, data };
}
@Put(':key')
@ApiOperation({ summary: 'ویرایش اصطلاح' })
async updateTerm(@Param('key') key: string, @Body() body: any) {
async updateTerm(
@Param('key') key: string,
@Body() body: Prisma.ScientificTermUpdateInput,
) {
const data = await this.wikiService.updateTerm(key, body);
return { success: true, data };
}
+19 -11
View File
@@ -1,23 +1,31 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
export class WikiQuery {
page?: number | string;
limit?: number | string;
search?: string;
}
@Injectable()
export class WikiService {
constructor(private prisma: PrismaService) {}
async getTerms(query: any) {
const { page = 1, limit = 10, search = '' } = query;
const skip = (Number(page) - 1) * Number(limit);
async getTerms(query: WikiQuery = {}) {
const page = Number(query.page) || 1;
const limit = Number(query.limit) || 10;
const skip = (page - 1) * limit;
const where = search
? { term: { contains: search, mode: 'insensitive' as any } }
const where: Prisma.ScientificTermWhereInput = query.search
? { term: { contains: query.search, mode: 'insensitive' } }
: {};
const [data, total] = await Promise.all([
this.prisma.scientificTerm.findMany({
where,
skip,
take: Number(limit),
take: limit,
orderBy: { term: 'asc' },
}),
this.prisma.scientificTerm.count({ where }),
@@ -27,18 +35,18 @@ export class WikiService {
data,
meta: {
total,
page: Number(page),
limit: Number(limit),
lastPage: Math.ceil(total / Number(limit)),
page,
limit,
lastPage: Math.ceil(total / limit),
},
};
}
async createTerm(data: any) {
async createTerm(data: Prisma.ScientificTermCreateInput) {
return this.prisma.scientificTerm.create({ data });
}
async updateTerm(key: string, data: any) {
async updateTerm(key: string, data: Prisma.ScientificTermUpdateInput) {
const term = await this.prisma.scientificTerm.findUnique({
where: { key },
});