feat: connect UI texts, address CRUD, OTP autofocus and profile to backend

This commit is contained in:
parsa committed 2026-05-26 21:39:14 +03:30
1 parent 4e2c8d5cfe
commit 467532713c
82 files changed
+14436 -274

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});
+12
View File
@@ -0,0 +1,12 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}
+16
View File
@@ -0,0 +1,16 @@
import { Module } from '@nestjs/common';
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 { AuthModule } from './auth/auth.module';
import { PetsModule } from './pets/pets.module';
import { OrdersModule } from './orders/orders.module';
import { SettingsModule } from './settings/settings.module';
@Module({
imports: [PrismaModule, RedisModule, ProductsModule, UsersModule, AuthModule, PetsModule, OrdersModule, SettingsModule],
controllers: [],
providers: [],
})
export class AppModule {}
+8
View File
@@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}
+27
View File
@@ -0,0 +1,27 @@
import { Controller, Post, Body, HttpCode, HttpStatus } from '@nestjs/common';
import { AuthService } from './auth.service';
import { SendOtpDto } from './dto/send-otp.dto';
import { VerifyOtpDto } from './dto/verify-otp.dto';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
@ApiTags('Auth')
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Post('send-otp')
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: 'ارسال کد تایید پیامکی' })
@ApiResponse({ status: 200, description: 'کد با موفقیت ارسال شد' })
sendOtp(@Body() sendOtpDto: SendOtpDto) {
return this.authService.sendOtp(sendOtpDto);
}
@Post('verify-otp')
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: 'تایید کد پیامکی و ورود/ثبت‌نام' })
@ApiResponse({ status: 200, description: 'ورود موفق به همراه توکن' })
verifyOtp(@Body() verifyOtpDto: VerifyOtpDto) {
return this.authService.verifyOtp(verifyOtpDto);
}
}
+22
View File
@@ -0,0 +1,22 @@
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { JwtStrategy } from './jwt.strategy';
import { UsersModule } from '../users/users.module';
@Module({
imports: [
UsersModule,
PassportModule,
JwtModule.register({
secret: process.env.JWT_SECRET || 'super-secret-key',
signOptions: { expiresIn: '7d' },
}),
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy],
exports: [AuthService],
})
export class AuthModule {}
+66
View File
@@ -0,0 +1,66 @@
import { Injectable, BadRequestException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { PrismaService } from '../prisma/prisma.service';
import { RedisService } from '../redis/redis.service';
import { SendOtpDto } from './dto/send-otp.dto';
import { VerifyOtpDto } from './dto/verify-otp.dto';
@Injectable()
export class AuthService {
constructor(
private prisma: PrismaService,
private jwtService: JwtService,
private redisService: RedisService,
) {}
async sendOtp(sendOtpDto: SendOtpDto) {
const { phoneNumber } = sendOtpDto;
const code = Math.floor(10000 + Math.random() * 90000).toString();
console.log(`[Mock SMS] Sending OTP ${code} to ${phoneNumber}`);
await this.redisService.set(`otp:${phoneNumber}`, code, 120);
return { success: true, message: 'کد تایید ارسال شد', code };
}
async verifyOtp(verifyOtpDto: VerifyOtpDto) {
const { phoneNumber, code } = verifyOtpDto;
const savedCode = await this.redisService.get(`otp:${phoneNumber}`);
if (!savedCode) {
throw new BadRequestException({ message: 'کد تایید منقضی شده است', error: 'OTP_EXPIRED' });
}
if (savedCode !== code) {
throw new BadRequestException({ message: 'کد تایید اشتباه است', error: 'OTP_INVALID' });
}
await this.redisService.del(`otp:${phoneNumber}`);
let user = await this.prisma.user.findUnique({ where: { mobile: phoneNumber } });
if (!user) {
user = await this.prisma.user.create({
data: {
mobile: phoneNumber,
firstName: 'کاربر',
lastName: 'جدید',
email: `${phoneNumber}@temp.local`,
},
});
}
const payload = { sub: user.id, phoneNumber: user.mobile };
const accessToken = this.jwtService.sign(payload);
return {
success: true,
data: {
user,
accessToken,
},
};
}
}
+10
View File
@@ -0,0 +1,10 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString, Matches } from 'class-validator';
export class SendOtpDto {
@ApiProperty({ description: 'شماره موبایل کاربر', example: '09123456789' })
@IsNotEmpty()
@IsString()
@Matches(/^09\d{9}$/, { message: 'شماره موبایل نامعتبر است' })
phoneNumber: string;
}
+16
View File
@@ -0,0 +1,16 @@
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsString, Length, Matches } from 'class-validator';
export class VerifyOtpDto {
@ApiProperty({ description: 'شماره موبایل کاربر', example: '09123456789' })
@IsNotEmpty()
@IsString()
@Matches(/^09\d{9}$/, { message: 'شماره موبایل نامعتبر است' })
phoneNumber: string;
@ApiProperty({ description: 'کد تایید پیامک شده', example: '12345' })
@IsNotEmpty()
@IsString()
@Length(5, 5, { message: 'کد تایید باید ۵ رقم باشد' })
code: string;
}
+12
View File
@@ -0,0 +1,12 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
handleRequest(err: any, user: any, info: any) {
if (err || !user) {
throw err || new UnauthorizedException('لطفا ابتدا وارد حساب کاربری خود شوید');
}
return user;
}
}
+23
View File
@@ -0,0 +1,23 @@
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { UsersService } from '../users/users.service';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly usersService: UsersService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.JWT_SECRET || 'super-secret-key',
});
}
async validate(payload: any) {
const user = await this.usersService.findById(payload.sub);
if (!user) {
throw new UnauthorizedException('کاربر یافت نشد');
}
return user;
}
}
@@ -0,0 +1,19 @@
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Response } from 'express';
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const status = exception.getStatus();
const exceptionResponse: any = exception.getResponse();
response.status(status).json({
success: false,
message: typeof exceptionResponse === 'string' ? exceptionResponse : (exceptionResponse.message || 'خطای سرور'),
code: exceptionResponse.error || (status === 400 ? 'BAD_REQUEST' : 'ERROR'),
details: typeof exceptionResponse === 'object' ? exceptionResponse : {}
});
}
}
+28
View File
@@ -0,0 +1,28 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix('api');
app.enableCors();
app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true }));
app.useGlobalFilters(new HttpExceptionFilter());
const config = new DocumentBuilder()
.setTitle('Canina Iran API')
.setDescription('API Documentation for Canina Iran Pet Health & Supplement Platform')
.setVersion('1.0.0')
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api/docs', app, document);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
@@ -0,0 +1,28 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsNotEmpty, IsArray, ValidateNested, IsNumber, IsOptional, IsString } from 'class-validator';
import { Type } from 'class-transformer';
class OrderItemDto {
@ApiProperty({ description: 'ID محصول' })
@IsNotEmpty()
@IsString()
productId: string;
@ApiProperty({ description: 'تعداد محصول' })
@IsNotEmpty()
@IsNumber()
quantity: number;
}
export class CreateOrderDto {
@ApiPropertyOptional({ description: 'ID حیوان خانگی مرتبط' })
@IsOptional()
@IsString()
petId?: string;
@ApiProperty({ description: 'لیست اقلام سفارش', type: [OrderItemDto] })
@IsArray()
@ValidateNested({ each: true })
@Type(() => OrderItemDto)
items: OrderItemDto[];
}
+31
View File
@@ -0,0 +1,31 @@
import { Controller, Get, Post, Body, Param, UseGuards, Req } 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 } from '@nestjs/swagger';
@ApiTags('Orders')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Controller('orders')
export class OrdersController {
constructor(private readonly ordersService: OrdersService) {}
@Post()
@ApiOperation({ summary: 'ثبت سفارش جدید' })
create(@Req() req: any, @Body() createOrderDto: CreateOrderDto) {
return this.ordersService.create(req.user.id, createOrderDto);
}
@Get()
@ApiOperation({ summary: 'لیست سفارش‌های کاربر' })
findAll(@Req() req: any) {
return this.ordersService.findAllByUser(req.user.id);
}
@Get(':id')
@ApiOperation({ summary: 'جزئیات یک سفارش' })
findOne(@Req() req: any, @Param('id') id: string) {
return this.ordersService.findOne(id, req.user.id);
}
}
+9
View File
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { OrdersService } from './orders.service';
import { OrdersController } from './orders.controller';
@Module({
controllers: [OrdersController],
providers: [OrdersService],
})
export class OrdersModule {}
+69
View File
@@ -0,0 +1,69 @@
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreateOrderDto } from './dto/create-order.dto';
@Injectable()
export class OrdersService {
constructor(private prisma: PrismaService) {}
async create(userId: string, createOrderDto: CreateOrderDto) {
let totalAmount = 0;
const orderItems = [];
for (const item of createOrderDto.items) {
const product = await this.prisma.product.findUnique({ where: { id: item.productId } });
if (!product) {
throw new NotFoundException(`محصول با شناسه ${item.productId} یافت نشد`);
}
totalAmount += Number(product.priceValue) * item.quantity;
orderItems.push({
productId: product.id,
quantity: item.quantity,
});
}
if (orderItems.length === 0) {
throw new BadRequestException('سبد خرید خالی است');
}
return this.prisma.order.create({
data: {
userId,
totalAmount,
status: 'processing',
orderItems: {
create: orderItems,
},
},
include: {
orderItems: {
include: { product: true }
}
}
});
}
async findAllByUser(userId: string) {
return this.prisma.order.findMany({
where: { userId },
include: {
orderItems: { include: { product: true } },
},
orderBy: { createdAt: 'desc' },
});
}
async findOne(id: string, userId: string) {
const order = await this.prisma.order.findFirst({
where: { id, userId },
include: {
orderItems: { include: { product: true } },
},
});
if (!order) {
throw new NotFoundException('سفارش یافت نشد');
}
return order;
}
}
+44
View File
@@ -0,0 +1,44 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsNotEmpty, IsString, IsOptional, IsNumber, IsBoolean, IsDateString } from 'class-validator';
export class CreatePetDto {
@ApiProperty({ description: 'نام حیوان خانگی', example: 'بادی' })
@IsNotEmpty()
@IsString()
name: string;
@ApiProperty({ description: 'نوع (سگ/گربه)', example: 'سگ' })
@IsNotEmpty()
@IsString()
type: string;
@ApiPropertyOptional({ description: 'نژاد', example: 'ژرمن شپرد' })
@IsOptional()
@IsString()
breed?: string;
@ApiPropertyOptional({ description: 'جنسیت', example: 'نر' })
@IsOptional()
@IsString()
gender?: string;
@ApiPropertyOptional({ description: 'وزن (کیلوگرم)', example: 25.5 })
@IsOptional()
@IsNumber()
weight?: number;
@ApiPropertyOptional({ description: 'تاریخ تولد' })
@IsOptional()
@IsDateString()
birthDate?: string;
@ApiPropertyOptional({ description: 'عقیم شده است؟', example: false })
@IsOptional()
@IsBoolean()
isNeutered?: boolean;
@ApiPropertyOptional({ description: 'سوابق پزشکی مختصر' })
@IsOptional()
@IsString()
medicalHistory?: string;
}
+4
View File
@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/swagger';
import { CreatePetDto } from './create-pet.dto';
export class UpdatePetDto extends PartialType(CreatePetDto) {}
+44
View File
@@ -0,0 +1,44 @@
import { Controller, Get, Post, Body, Patch, Param, Delete, UseGuards, Req } from '@nestjs/common';
import { PetsService } from './pets.service';
import { CreatePetDto } from './dto/create-pet.dto';
import { UpdatePetDto } from './dto/update-pet.dto';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
@ApiTags('Pets')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Controller('pets')
export class PetsController {
constructor(private readonly petsService: PetsService) {}
@Post()
@ApiOperation({ summary: 'ثبت حیوان خانگی جدید' })
create(@Req() req: any, @Body() createPetDto: CreatePetDto) {
return this.petsService.create(req.user.id, createPetDto);
}
@Get()
@ApiOperation({ summary: 'لیست حیوانات خانگی کاربر' })
findAll(@Req() req: any) {
return this.petsService.findAllByUser(req.user.id);
}
@Get(':id')
@ApiOperation({ summary: 'دریافت جزئیات یک حیوان خانگی' })
findOne(@Req() req: any, @Param('id') id: string) {
return this.petsService.findOne(id, req.user.id);
}
@Patch(':id')
@ApiOperation({ summary: 'بروزرسانی اطلاعات حیوان خانگی' })
update(@Req() req: any, @Param('id') id: string, @Body() updatePetDto: UpdatePetDto) {
return this.petsService.update(id, req.user.id, updatePetDto);
}
@Delete(':id')
@ApiOperation({ summary: 'حذف حیوان خانگی' })
remove(@Req() req: any, @Param('id') id: string) {
return this.petsService.remove(id, req.user.id);
}
}
+9
View File
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { PetsService } from './pets.service';
import { PetsController } from './pets.controller';
@Module({
controllers: [PetsController],
providers: [PetsService],
})
export class PetsModule {}
+61
View File
@@ -0,0 +1,61 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreatePetDto } from './dto/create-pet.dto';
import { UpdatePetDto } from './dto/update-pet.dto';
@Injectable()
export class PetsService {
constructor(private prisma: PrismaService) {}
async create(userId: string, createPetDto: CreatePetDto) {
return this.prisma.pet.create({
data: {
name: createPetDto.name,
type: createPetDto.type,
breed: createPetDto.breed || '',
activityLevel: 'متوسط', // Default
age: 1, // Default
weight: createPetDto.weight || 0,
userId,
},
});
}
async findAllByUser(userId: string) {
return this.prisma.pet.findMany({
where: { userId },
orderBy: { createdAt: 'desc' },
});
}
async findOne(id: string, userId: string) {
const pet = await this.prisma.pet.findFirst({
where: { id, userId },
include: { reminders: true, healthLogs: true },
});
if (!pet) {
throw new NotFoundException('حیوان خانگی یافت نشد');
}
return pet;
}
async update(id: string, userId: string, updatePetDto: UpdatePetDto) {
await this.findOne(id, userId); // Ensure it exists and belongs to user
return this.prisma.pet.update({
where: { id },
data: {
name: updatePetDto.name,
type: updatePetDto.type,
breed: updatePetDto.breed,
weight: updatePetDto.weight,
},
});
}
async remove(id: string, userId: string) {
await this.findOne(id, userId);
return this.prisma.pet.delete({
where: { id },
});
}
}
+9
View File
@@ -0,0 +1,9 @@
import { Global, Module } from '@nestjs/common';
import { PrismaService } from './prisma.service';
@Global()
@Module({
providers: [PrismaService],
exports: [PrismaService],
})
export class PrismaModule {}
+13
View File
@@ -0,0 +1,13 @@
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
async onModuleInit() {
await this.$connect();
}
async onModuleDestroy() {
await this.$disconnect();
}
}
@@ -0,0 +1,19 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsOptional, IsString, IsEnum } from 'class-validator';
export class GetProductsDto {
@ApiPropertyOptional({ description: 'Filter by category slug' })
@IsOptional()
@IsString()
category?: string;
@ApiPropertyOptional({ description: 'Filter by pet type', enum: ['سگ', 'گربه', 'all'] })
@IsOptional()
@IsEnum(['سگ', 'گربه', 'all'])
petType?: string;
@ApiPropertyOptional({ description: 'Search query string' })
@IsOptional()
@IsString()
query?: string;
}
@@ -0,0 +1,28 @@
import { Controller, Get, Query, Param, NotFoundException } from '@nestjs/common';
import { ProductsService } from './products.service';
import { GetProductsDto } from './dto/get-products.dto';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
@ApiTags('Products')
@Controller('products')
export class ProductsController {
constructor(private readonly productsService: ProductsService) {}
@Get()
@ApiOperation({ summary: 'List Products' })
@ApiResponse({ status: 200, description: 'List of products' })
findAll(@Query() query: GetProductsDto) {
return this.productsService.findAll(query);
}
@Get(':id')
@ApiOperation({ summary: 'Get Product by ID' })
@ApiResponse({ status: 200, description: 'Product details' })
async findOne(@Param('id') id: string) {
const product = await this.productsService.findOne(id);
if (!product) {
throw new NotFoundException(`Product with ID ${id} not found`);
}
return product;
}
}
+9
View File
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { ProductsService } from './products.service';
import { ProductsController } from './products.controller';
@Module({
controllers: [ProductsController],
providers: [ProductsService],
})
export class ProductsModule {}
+49
View File
@@ -0,0 +1,49 @@
import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { GetProductsDto } from './dto/get-products.dto';
@Injectable()
export class ProductsService {
constructor(private prisma: PrismaService) {}
async findAll(filters: GetProductsDto) {
const { category, petType, query } = filters;
const whereClause: any = {};
if (category) {
whereClause.categorySlug = category;
}
if (petType && petType !== 'all') {
whereClause.suitableFor = { in: [petType, 'هر دو'] };
}
if (query) {
whereClause.OR = [
{ name: { contains: query, mode: 'insensitive' } },
{ description: { contains: query, mode: 'insensitive' } },
];
}
const products = await this.prisma.product.findMany({
where: whereClause,
include: {
ingredients: true,
symptoms: true,
},
});
return products;
}
async findOne(id: string) {
return this.prisma.product.findUnique({
where: { id },
include: {
ingredients: true,
symptoms: true,
},
});
}
}
+9
View File
@@ -0,0 +1,9 @@
import { Module, Global } from '@nestjs/common';
import { RedisService } from './redis.service';
@Global()
@Module({
providers: [RedisService],
exports: [RedisService],
})
export class RedisModule {}
+34
View File
@@ -0,0 +1,34 @@
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import Redis from 'ioredis';
@Injectable()
export class RedisService implements OnModuleInit, OnModuleDestroy {
private client: Redis;
onModuleInit() {
this.client = new Redis({
host: process.env.REDIS_HOST || 'localhost',
port: Number(process.env.REDIS_PORT) || 16379,
});
}
onModuleDestroy() {
this.client.disconnect();
}
async set(key: string, value: string, ttlSeconds?: number): Promise<void> {
if (ttlSeconds) {
await this.client.set(key, value, 'EX', ttlSeconds);
} else {
await this.client.set(key, value);
}
}
async get(key: string): Promise<string | null> {
return this.client.get(key);
}
async del(key: string): Promise<void> {
await this.client.del(key);
}
}
@@ -0,0 +1,51 @@
import { Controller, Get, Patch, Put, Delete, Body, Param, UseGuards } from '@nestjs/common';
import { SettingsService } from './settings.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { ApiTags, ApiOperation, ApiBearerAuth, ApiResponse } from '@nestjs/swagger';
@ApiTags('Settings')
@Controller('settings')
export class SettingsController {
constructor(private readonly settingsService: SettingsService) {}
@Get('ui-texts')
@ApiOperation({ summary: 'دریافت تمامی متون رابط کاربری' })
@ApiResponse({ status: 200, description: 'تمامی متون بازگردانده شدند' })
getUiTexts() {
return this.settingsService.getUiTexts();
}
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@Patch('ui-texts/:key')
@ApiOperation({ summary: 'ویرایش متن یک کلید در رابط کاربری' })
@ApiResponse({ status: 200, description: 'متن با موفقیت به‌روزرسانی شد' })
updateUiText(@Param('key') key: string, @Body('value') value: string) {
return this.settingsService.updateUiText(key, value);
}
@Get('scientific-terms')
@ApiOperation({ summary: 'دریافت تمامی اصطلاحات علمی' })
@ApiResponse({ status: 200, description: 'تمامی اصطلاحات علمی بازگردانده شدند' })
getScientificTerms() {
return this.settingsService.getScientificTerms();
}
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@Put('scientific-terms/:key')
@ApiOperation({ summary: 'ثبت یا ویرایش یک اصطلاح علمی' })
@ApiResponse({ status: 200, description: 'اصطلاح علمی ثبت یا ویرایش شد' })
upsertScientificTerm(@Param('key') key: string, @Body() data: any) {
return this.settingsService.upsertScientificTerm(key, data);
}
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@Delete('scientific-terms/:key')
@ApiOperation({ summary: 'حذف یک اصطلاح علمی' })
@ApiResponse({ status: 200, description: 'اصطلاح علمی حذف شد' })
deleteScientificTerm(@Param('key') key: string) {
return this.settingsService.deleteScientificTerm(key);
}
}
+12
View File
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { SettingsService } from './settings.service';
import { SettingsController } from './settings.controller';
import { PrismaModule } from '../prisma/prisma.module';
@Module({
imports: [PrismaModule],
controllers: [SettingsController],
providers: [SettingsService],
exports: [SettingsService],
})
export class SettingsModule {}
+46
View File
@@ -0,0 +1,46 @@
import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
@Injectable()
export class SettingsService {
constructor(private prisma: PrismaService) {}
async getUiTexts() {
return this.prisma.uiText.findMany();
}
async updateUiText(key: string, value: string) {
return this.prisma.uiText.upsert({
where: { key },
update: { value },
create: { key, value },
});
}
async getScientificTerms() {
return this.prisma.scientificTerm.findMany();
}
async upsertScientificTerm(key: string, data: any) {
return this.prisma.scientificTerm.upsert({
where: { key },
update: {
term: data.term,
definition: data.definition,
wikiId: data.wikiId || 'general',
},
create: {
key,
term: data.term,
definition: data.definition,
wikiId: data.wikiId || 'general',
},
});
}
async deleteScientificTerm(key: string) {
return this.prisma.scientificTerm.delete({
where: { key },
});
}
}
+44
View File
@@ -0,0 +1,44 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsString, IsNotEmpty, IsOptional, IsBoolean } from 'class-validator';
export class AddressDto {
@ApiProperty({ description: 'عنوان آدرس (مثلا خانه، کار)' })
@IsString()
@IsNotEmpty()
title: string;
@ApiProperty({ description: 'نام تحویل‌گیرنده' })
@IsString()
@IsNotEmpty()
receptorName: string;
@ApiProperty({ description: 'شماره تلفن گیرنده' })
@IsString()
@IsNotEmpty()
phone: string;
@ApiProperty({ description: 'استان' })
@IsString()
@IsNotEmpty()
province: string;
@ApiProperty({ description: 'شهر' })
@IsString()
@IsNotEmpty()
city: string;
@ApiProperty({ description: 'جزئیات آدرس پستی' })
@IsString()
@IsNotEmpty()
detail: string;
@ApiProperty({ description: 'کد پستی' })
@IsString()
@IsNotEmpty()
zipCode: string;
@ApiPropertyOptional({ description: 'انتخاب به عنوان آدرس پیش‌فرض' })
@IsOptional()
@IsBoolean()
isDefault?: boolean;
}
@@ -0,0 +1,24 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsOptional, IsString, IsEmail } from 'class-validator';
export class UpdateProfileDto {
@ApiPropertyOptional({ description: 'نام کاربر' })
@IsOptional()
@IsString()
firstName?: string;
@ApiPropertyOptional({ description: 'نام خانوادگی کاربر' })
@IsOptional()
@IsString()
lastName?: string;
@ApiPropertyOptional({ description: 'ایمیل کاربر' })
@IsOptional()
@IsEmail({}, { message: 'ایمیل نامعتبر است' })
email?: string;
@ApiPropertyOptional({ description: 'شماره موبایل کاربر' })
@IsOptional()
@IsString()
mobile?: string;
}
+64
View File
@@ -0,0 +1,64 @@
import { Controller, Get, Patch, Post, Delete, Body, Param, UseGuards, Req } from '@nestjs/common';
import { UsersService } from './users.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { UpdateProfileDto } from './dto/update-profile.dto';
import { AddressDto } from './dto/address.dto';
@ApiTags('Users')
@ApiBearerAuth()
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@UseGuards(JwtAuthGuard)
@Get('profile')
@ApiOperation({ summary: 'دریافت پروفایل کاربر فعلی' })
getProfile(@Req() req: any) {
return this.usersService.findById(req.user.id);
}
@UseGuards(JwtAuthGuard)
@Patch('profile')
@ApiOperation({ summary: 'ویرایش پروفایل کاربر فعلی' })
@ApiResponse({ status: 200, description: 'پروفایل با موفقیت ویرایش شد' })
updateProfile(@Req() req: any, @Body() updateProfileDto: UpdateProfileDto) {
return this.usersService.update(req.user.id, updateProfileDto);
}
@UseGuards(JwtAuthGuard)
@Post('addresses')
@ApiOperation({ summary: 'ایجاد آدرس جدید برای کاربر' })
@ApiResponse({ status: 201, description: 'آدرس جدید با موفقیت ایجاد شد' })
addAddress(@Req() req: any, @Body() addressDto: AddressDto) {
return this.usersService.addAddress(req.user.id, addressDto);
}
@UseGuards(JwtAuthGuard)
@Patch('addresses/:addressId')
@ApiOperation({ summary: 'ویرایش آدرس کاربر' })
@ApiResponse({ status: 200, description: 'آدرس با موفقیت ویرایش شد' })
updateAddress(
@Req() req: any,
@Param('addressId') addressId: string,
@Body() addressDto: AddressDto,
) {
return this.usersService.updateAddress(req.user.id, addressId, addressDto);
}
@UseGuards(JwtAuthGuard)
@Delete('addresses/:addressId')
@ApiOperation({ summary: 'حذف آدرس کاربر' })
@ApiResponse({ status: 200, description: 'آدرس با موفقیت حذف شد' })
deleteAddress(@Req() req: any, @Param('addressId') addressId: string) {
return this.usersService.deleteAddress(req.user.id, addressId);
}
@UseGuards(JwtAuthGuard)
@Patch('addresses/:addressId/default')
@ApiOperation({ summary: 'انتخاب آدرس به عنوان پیش‌فرض' })
@ApiResponse({ status: 200, description: 'آدرس به عنوان پیش‌فرض ثبت شد' })
setDefaultAddress(@Req() req: any, @Param('addressId') addressId: string) {
return this.usersService.setDefaultAddress(req.user.id, addressId);
}
}
+10
View File
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { UsersService } from './users.service';
import { UsersController } from './users.controller';
@Module({
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService],
})
export class UsersModule {}
+111
View File
@@ -0,0 +1,111 @@
import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
@Injectable()
export class UsersService {
constructor(private prisma: PrismaService) {}
async findById(id: string) {
return this.prisma.user.findUnique({
where: { id },
include: {
pets: true,
orders: {
include: {
orderItems: {
include: { product: true }
}
}
},
addresses: true,
walletTransactions: true
}
});
}
async update(id: string, data: any) {
return this.prisma.user.update({
where: { id },
data,
include: {
pets: true,
orders: {
include: {
orderItems: {
include: { product: true }
}
}
},
addresses: true,
walletTransactions: true
}
});
}
async addAddress(userId: string, data: any) {
if (data.isDefault) {
await this.prisma.userAddress.updateMany({
where: { userId },
data: { isDefault: false },
});
}
return this.prisma.userAddress.create({
data: {
title: data.title,
receptorName: data.receptorName,
phone: data.phone,
province: data.province,
city: data.city,
detail: data.detail,
zipCode: data.zipCode,
isDefault: data.isDefault || false,
userId: userId,
},
});
}
async updateAddress(userId: string, addressId: string, data: any) {
if (data.isDefault) {
await this.prisma.userAddress.updateMany({
where: { userId, NOT: { id: addressId } },
data: { isDefault: false },
});
}
return this.prisma.userAddress.update({
where: { id: addressId, userId },
data: {
title: data.title,
receptorName: data.receptorName,
phone: data.phone,
province: data.province,
city: data.city,
detail: data.detail,
zipCode: data.zipCode,
isDefault: data.isDefault || false,
},
});
}
async deleteAddress(userId: string, addressId: string) {
return this.prisma.userAddress.delete({
where: { id: addressId, userId },
});
}
async setDefaultAddress(userId: string, addressId: string) {
await this.prisma.userAddress.updateMany({
where: { userId },
data: { isDefault: false },
});
return this.prisma.userAddress.update({
where: { id: addressId, userId },
data: { isDefault: true },
});
}
async findByPhone(phoneNumber: string) {
return this.prisma.user.findUnique({
where: { mobile: phoneNumber },
});
}
}