تغییرات کلی در backend و frontend

This commit is contained in:
parsa aghaei committed 2026-07-11 12:30:17 +03:30
1 parent a74f4bda48
commit 3dedc89ee1
41 files changed
+2373 -1957

No files matched your search

+2 -1
View File
@@ -14,9 +14,10 @@ import { WikiService } from './wiki.service';
import { PetsController } from './pets.controller';
import { PetsService } from './pets.service';
import { PrismaModule } from '../prisma/prisma.module';
import { RedisModule } from '../redis/redis.module';
@Module({
imports: [PrismaModule],
imports: [PrismaModule, RedisModule],
controllers: [AdminController, ReportsController, MediaController, CategoriesController, BlogsController, WikiController, PetsController],
providers: [AdminService, ReportsService, MediaService, CategoriesService, BlogsService, WikiService, PetsService],
})
+17 -3
View File
@@ -1,9 +1,13 @@
import { Injectable, HttpException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { RedisService } from '../redis/redis.service';
@Injectable()
export class AdminService {
constructor(private prisma: PrismaService) {}
constructor(
private prisma: PrismaService,
private redisService: RedisService,
) {}
async getDashboardStats() {
// total revenue
@@ -14,7 +18,7 @@ export class AdminService {
const revenue = orders.reduce((sum, o) => sum + Number(o.totalAmount), 0);
// new orders count (last 24 hours or total depending on logic, let's do total processing)
// new orders count (processing status)
const newOrders = await this.prisma.order.count({
where: { status: 'processing' }
});
@@ -22,11 +26,21 @@ export class AdminService {
// 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 {
const count = await this.redisService.get(todayKey);
todayVisits = count ? parseInt(count, 10) : 0;
} catch {
todayVisits = 0;
}
return {
revenue,
newOrders,
users,
todayVisits: Math.floor(Math.random() * 500) + 100 // mock visits since we don't track analytics
todayVisits
};
}
+7
View File
@@ -3,6 +3,7 @@ import { PrismaModule } from './prisma/prisma.module';
import { ProductsModule } from './products/products.module';
import { UsersModule } from './users/users.module';
import { RedisModule } from './redis/redis.module';
import { RedisService } from './redis/redis.service';
import { AuthModule } from './auth/auth.module';
import { PetsModule } from './pets/pets.module';
import { OrdersModule } from './orders/orders.module';
@@ -40,13 +41,19 @@ import { WikiModule } from './wiki/wiki.module';
provide: APP_GUARD,
useClass: ThrottlerGuard,
},
RedisService,
],
})
export class AppModule implements NestModule {
constructor(private readonly redisService: RedisService) {}
configure(consumer: MiddlewareConsumer) {
consumer
.apply((req: any, res: any, next: () => void) => {
MetricsController.incrementRequestCount();
// Increment daily visits counter in Redis (fire-and-forget)
const todayKey = `visits:${new Date().toISOString().split('T')[0]}`;
this.redisService.incr(todayKey, 86400).catch(() => {}); // TTL = 24h
next();
})
.exclude('metrics')
+6 -3
View File
@@ -53,13 +53,16 @@ describe('AuthService', () => {
});
describe('sendOtp', () => {
it('should generate a 5 digit OTP and save it in Redis', async () => {
it('should generate a 5 digit OTP, save it in Redis, and not expose it in response', async () => {
const result = await service.sendOtp({ phoneNumber: '09123456789' });
expect(result.success).toBe(true);
expect(result.code).toHaveLength(5);
expect(result.message).toBe('کد تایید ارسال شد');
// Code should NOT be in the response (security)
expect((result as any).code).toBeUndefined();
// But it should have been stored in Redis
expect(redis.set).toHaveBeenCalledWith(
'otp:09123456789',
result.code,
expect.stringMatching(/^\d{5}$/),
120,
);
});
+4 -2
View File
@@ -18,11 +18,13 @@ export class AuthService {
const { phoneNumber } = sendOtpDto;
const code = Math.floor(10000 + Math.random() * 90000).toString();
console.log(`[Mock SMS] Sending OTP ${code} to ${phoneNumber}`);
// In production: replace this log with a real SMS provider (e.g. KaveNegar, Melipayamak)
console.log(`[Dev SMS] OTP for ${phoneNumber}: ${code}`);
await this.redisService.set(`otp:${phoneNumber}`, code, 120);
return { success: true, message: 'کد تایید ارسال شد', code };
// SECURITY: Never return the OTP code in the response
return { success: true, message: 'کد تایید ارسال شد' };
}
async verifyOtp(verifyOtpDto: VerifyOtpDto) {
@@ -20,6 +20,11 @@ export class CreateOrderDto {
@IsString()
petId?: string;
@ApiPropertyOptional({ description: 'کد تخفیف (اختیاری)' })
@IsOptional()
@IsString()
couponCode?: string;
@ApiProperty({ description: 'لیست اقلام سفارش', type: [OrderItemDto] })
@IsArray()
@ValidateNested({ each: true })
+32 -2
View File
@@ -1,9 +1,19 @@
import { Controller, Get, Post, Body, Param, UseGuards, Req, HttpStatus, Query } from '@nestjs/common';
import { Controller, Get, Post, Patch, Body, Param, UseGuards, Req, HttpStatus, Query } from '@nestjs/common';
import { OrdersService } from './orders.service';
import { CreateOrderDto } from './dto/create-order.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiResponse, ApiOkResponse, ApiCreatedResponse, ApiBadRequestResponse, ApiNotFoundResponse } from '@nestjs/swagger';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiResponse, ApiOkResponse, ApiCreatedResponse, ApiBadRequestResponse, ApiNotFoundResponse, ApiBody } from '@nestjs/swagger';
import { PaginationDto } from '../common/dto/pagination.dto';
import { IsString, IsNumber, IsNotEmpty } from 'class-validator';
class ValidateCouponDto {
@IsString()
@IsNotEmpty()
code: string;
@IsNumber()
cartTotal: number;
}
@ApiTags('Orders - مدیریت سفارش‌ها')
@ApiBearerAuth()
@@ -56,6 +66,26 @@ export class OrdersController {
return this.ordersService.create(req.user.id, createOrderDto);
}
@Post('validate-coupon')
@ApiOperation({ summary: 'اعتبارسنجی کد تخفیف و محاسبه میزان تخفیف' })
@ApiOkResponse({
description: 'نتیجه اعتبارسنجی کد تخفیف',
schema: {
example: {
valid: true,
couponId: 'abc-123',
code: 'CANINO10',
type: 'percent',
discountValue: 175000,
message: 'کد تخفیف اعمال شد — ۱۷۵,۰۰۰ تومان تخفیف'
}
}
})
@ApiBadRequestResponse({ description: 'کد تخفیف نامعتبر، منقضی، یا شرایط آن برقرار نیست' })
validateCoupon(@Req() req: any, @Body() body: ValidateCouponDto) {
return this.ordersService.validateCoupon(body.code, body.cartTotal, req.user.id);
}
@Get()
@ApiOperation({ summary: 'لیست سفارش‌های کاربر فعلی' })
@ApiOkResponse({
+85 -1
View File
@@ -2,13 +2,75 @@ import { Injectable, NotFoundException, BadRequestException } from '@nestjs/comm
import { PrismaService } from '../prisma/prisma.service';
import { PaginationDto } from '../common/dto/pagination.dto';
import { CreateOrderDto } from './dto/create-order.dto';
import { Decimal } from '@prisma/client/runtime/library';
@Injectable()
export class OrdersService {
constructor(private prisma: PrismaService) {}
private generateTrackingNumber(): string {
const date = new Date();
const dateStr = `${date.getFullYear()}${String(date.getMonth() + 1).padStart(2, '0')}${String(date.getDate()).padStart(2, '0')}`;
const random = Math.floor(10000 + Math.random() * 90000);
return `CN-${dateStr}-${random}`;
}
async validateCoupon(code: string, cartTotal: number, userId: string) {
const coupon = await this.prisma.coupon.findUnique({
where: { code: code.toUpperCase().trim() },
include: { targets: true },
});
if (!coupon || !coupon.isActive) {
throw new BadRequestException({ message: 'کد تخفیف معتبر نیست یا منقضی شده است', error: 'COUPON_INVALID' });
}
if (coupon.expiresAt && new Date() > coupon.expiresAt) {
throw new BadRequestException({ message: 'کد تخفیف منقضی شده است', error: 'COUPON_EXPIRED' });
}
if (coupon.maxUses && coupon.usedCount >= coupon.maxUses) {
throw new BadRequestException({ message: 'ظرفیت استفاده از این کد تخفیف تکمیل شده است', error: 'COUPON_LIMIT_REACHED' });
}
if (coupon.minCartValue && cartTotal < Number(coupon.minCartValue)) {
throw new BadRequestException({
message: `حداقل مبلغ سبد خرید برای استفاده از این کد ${Number(coupon.minCartValue).toLocaleString('fa-IR')} تومان است`,
error: 'COUPON_MIN_CART'
});
}
// Check user-specific targets
const userTargets = coupon.targets.filter(t => t.targetType === 'USER');
if (userTargets.length > 0 && !userTargets.some(t => t.targetId === userId)) {
throw new BadRequestException({ message: 'این کد تخفیف برای حساب شما معتبر نیست', error: 'COUPON_NOT_FOR_USER' });
}
let discountValue: number;
if (coupon.type === 'percent') {
discountValue = cartTotal * (Number(coupon.value) / 100);
if (coupon.maxCartValue) {
discountValue = Math.min(discountValue, Number(coupon.maxCartValue));
}
} else {
discountValue = Number(coupon.value);
}
discountValue = Math.min(discountValue, cartTotal);
return {
valid: true,
couponId: coupon.id,
code: coupon.code,
type: coupon.type,
discountValue,
message: `کد تخفیف اعمال شد — ${discountValue.toLocaleString('fa-IR')} تومان تخفیف`,
};
}
async create(userId: string, createOrderDto: CreateOrderDto) {
let totalAmount = 0;
let couponId: string | null = null;
const orderItems = [];
for (const item of createOrderDto.items) {
@@ -27,10 +89,32 @@ export class OrdersService {
throw new BadRequestException('سبد خرید خالی است');
}
// Apply coupon if provided
let discountAmount = 0;
if (createOrderDto.couponCode) {
try {
const couponResult = await this.validateCoupon(createOrderDto.couponCode, totalAmount, userId);
discountAmount = couponResult.discountValue;
couponId = couponResult.couponId;
// Increment usedCount
await this.prisma.coupon.update({
where: { id: couponId },
data: { usedCount: { increment: 1 } },
});
} catch {
// Invalid coupon — ignore and proceed without discount
}
}
const finalAmount = Math.max(totalAmount - discountAmount, 0);
const trackingNumber = this.generateTrackingNumber();
return this.prisma.order.create({
data: {
userId,
totalAmount,
couponId,
totalAmount: finalAmount,
trackingNumber,
status: 'processing',
orderItems: {
create: orderItems,
@@ -0,0 +1,24 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsNotEmpty, IsString, IsOptional } from 'class-validator';
export class CreateHealthLogDto {
@ApiProperty({ description: 'وضعیت اشتها', example: 'عالی' })
@IsNotEmpty()
@IsString()
appetite: string;
@ApiProperty({ description: 'وضعیت انرژی', example: 'نرمال' })
@IsNotEmpty()
@IsString()
energy: string;
@ApiProperty({ description: 'وضعیت گوارش', example: 'نرمال' })
@IsNotEmpty()
@IsString()
digestion: string;
@ApiPropertyOptional({ description: 'یادداشت یا توضیح اضافی', example: 'امروز فعالیت خوبی داشت.' })
@IsOptional()
@IsString()
note?: string;
}
@@ -0,0 +1,24 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsNotEmpty, IsString, IsOptional } from 'class-validator';
export class CreateReminderDto {
@ApiProperty({ description: 'عنوان یادآور', example: 'قرص کلسیم' })
@IsNotEmpty()
@IsString()
title: string;
@ApiProperty({ description: 'زمان یادآور (مثال: 08:30)', example: '08:30' })
@IsNotEmpty()
@IsString()
time: string;
@ApiProperty({ description: 'دوره زمانی (روزانه / هفتگی)', example: 'روزانه' })
@IsNotEmpty()
@IsString()
frequency: string;
@ApiPropertyOptional({ description: 'شناسه محصول مربوطه', example: 'a1b2c3d4-1234-5678-abcd-ef1234567890' })
@IsOptional()
@IsString()
productId?: string;
}
+33
View File
@@ -2,6 +2,8 @@ import { Controller, Get, Post, Body, Patch, Param, Delete, UseGuards, Req, Http
import { PetsService } from './pets.service';
import { CreatePetDto } from './dto/create-pet.dto';
import { UpdatePetDto } from './dto/update-pet.dto';
import { CreateReminderDto } from './dto/create-reminder.dto';
import { CreateHealthLogDto } from './dto/create-health-log.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiResponse, ApiOkResponse, ApiCreatedResponse, ApiBadRequestResponse, ApiNotFoundResponse } from '@nestjs/swagger';
import { PaginationDto } from '../common/dto/pagination.dto';
@@ -185,4 +187,35 @@ export class PetsController {
remove(@Req() req: any, @Param('id') id: string) {
return this.petsService.remove(id, req.user.id);
}
@Post(':petId/reminders')
@ApiOperation({ summary: 'ثبت یادآور جدید برای پت' })
addReminder(
@Req() req: any,
@Param('petId') petId: string,
@Body() createReminderDto: CreateReminderDto,
) {
return this.petsService.addReminder(req.user.id, petId, createReminderDto);
}
@Post(':petId/reminders/:reminderId/toggle')
@ApiOperation({ summary: 'تغییر وضعیت انجام یادآور در یک تاریخ خاص' })
toggleReminder(
@Req() req: any,
@Param('petId') petId: string,
@Param('reminderId') reminderId: string,
@Body('date') date: string,
) {
return this.petsService.toggleReminder(req.user.id, petId, reminderId, date);
}
@Post(':petId/health-logs')
@ApiOperation({ summary: 'ثبت لاگ سلامت جدید برای پت' })
addHealthLog(
@Req() req: any,
@Param('petId') petId: string,
@Body() createHealthLogDto: CreateHealthLogDto,
) {
return this.petsService.addHealthLog(req.user.id, petId, createHealthLogDto);
}
}
+65
View File
@@ -103,4 +103,69 @@ export class PetsService {
where: { id },
});
}
async addReminder(userId: string, petId: string, data: any) {
await this.findOne(petId, userId);
return this.prisma.reminder.create({
data: {
petId,
productId: data.productId || null,
title: data.title,
time: data.time,
frequency: data.frequency,
},
});
}
async toggleReminder(userId: string, petId: string, reminderId: string, dateStr: string) {
await this.findOne(petId, userId);
const reminder = await this.prisma.reminder.findUnique({
where: { id: reminderId },
});
if (!reminder || reminder.petId !== petId) {
throw new NotFoundException('یادآور یافت نشد');
}
const dateParts = dateStr.split('-');
const completedDate = new Date(Date.UTC(Number(dateParts[0]), Number(dateParts[1]) - 1, Number(dateParts[2])));
const existingCompletion = await this.prisma.reminderCompletion.findUnique({
where: {
reminderId_completedDate: {
reminderId,
completedDate,
},
},
});
if (existingCompletion) {
await this.prisma.reminderCompletion.delete({
where: { id: existingCompletion.id },
});
return { completed: false };
} else {
await this.prisma.reminderCompletion.create({
data: {
reminderId,
completedDate,
},
});
return { completed: true };
}
}
async addHealthLog(userId: string, petId: string, data: any) {
await this.findOne(petId, userId);
return this.prisma.healthLog.create({
data: {
petId,
appetite: data.appetite,
energy: data.energy,
digestion: data.digestion,
note: data.note || null,
loggedDate: new Date(),
},
});
}
}
+9
View File
@@ -31,4 +31,13 @@ export class RedisService implements OnModuleInit, OnModuleDestroy {
async del(key: string): Promise<void> {
await this.client.del(key);
}
async incr(key: string, ttlSeconds?: number): Promise<number> {
const count = await this.client.incr(key);
// Set expiry only on the first increment (count === 1)
if (count === 1 && ttlSeconds) {
await this.client.expire(key, ttlSeconds);
}
return count;
}
}
+27 -1
View File
@@ -1,4 +1,4 @@
import { Controller, Get, Patch, Post, Delete, Body, Param, UseGuards, Req, HttpStatus } from '@nestjs/common';
import { Controller, Get, Patch, Post, Delete, Body, Param, UseGuards, Req, HttpStatus, BadRequestException } from '@nestjs/common';
import { UsersService } from './users.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiResponse, ApiOkResponse, ApiCreatedResponse, ApiBadRequestResponse } from '@nestjs/swagger';
@@ -169,4 +169,30 @@ export class UsersController {
setDefaultAddress(@Req() req: any, @Param('addressId') addressId: string) {
return this.usersService.setDefaultAddress(req.user.id, addressId);
}
@UseGuards(JwtAuthGuard)
@Post('wallet/top-up')
@ApiOperation({ summary: 'شارژ کیف پول کاربر' })
@ApiCreatedResponse({
description: 'کیف پول با موفقیت شارژ شد',
schema: {
example: {
id: 'txn-uuid',
userId: 'user-uuid',
amount: '500000.00',
type: 'deposit',
status: 'completed',
description: 'شارژ کیف پول',
createdAt: '2026-07-11T08:00:00.000Z'
}
}
})
@ApiBadRequestResponse({ description: 'مبلغ نامعتبر است' })
async topUpWallet(@Req() req: any, @Body() body: { amount: number }) {
const amount = Number(body.amount);
if (!amount || amount <= 0) {
throw new BadRequestException('مبلغ شارژ باید بزرگتر از صفر باشد');
}
return this.usersService.topUpWallet(req.user.id, amount);
}
}
+40 -2
View File
@@ -9,8 +9,19 @@ export class UsersService {
return this.prisma.user.findUnique({
where: { id },
include: {
pets: true,
pets: {
include: {
medicalConditions: true,
reminders: {
include: {
completions: true
}
},
healthLogs: true,
}
},
orders: {
orderBy: { createdAt: 'desc' },
include: {
orderItems: {
include: { product: true }
@@ -18,7 +29,10 @@ export class UsersService {
}
},
addresses: true,
walletTransactions: true
walletTransactions: {
orderBy: { createdAt: 'desc' },
take: 50
}
}
});
}
@@ -103,6 +117,30 @@ export class UsersService {
});
}
async topUpWallet(userId: string, amount: number) {
if (amount <= 0) {
throw new Error('مبلغ شارژ باید بزرگتر از صفر باشد');
}
const [transaction] = await this.prisma.$transaction([
this.prisma.walletTransaction.create({
data: {
userId,
amount,
type: 'deposit',
status: 'completed',
description: 'شارژ کیف پول',
},
}),
this.prisma.user.update({
where: { id: userId },
data: { walletBalance: { increment: amount } },
}),
]);
return transaction;
}
async findByPhone(phoneNumber: string) {
return this.prisma.user.findUnique({
where: { mobile: phoneNumber },