Files
canina/backend/src/pets/pets.controller.ts
T

297 lines
8.2 KiB
TypeScript

import {
Controller,
Get,
Post,
Body,
Patch,
Param,
Delete,
UseGuards,
Req,
HttpStatus,
Query,
UseInterceptors,
UploadedFile,
BadRequestException,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { extname, join } from 'path';
import * as fs from 'fs';
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';
@ApiTags('Pets - مدیریت حیوانات خانگی')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Controller('pets')
@ApiResponse({
status: HttpStatus.UNAUTHORIZED,
description: 'عدم احراز هویت - توکن معتبر نیست یا ارسال نشده است',
schema: {
example: {
success: false,
message: 'Unauthorized',
code: 'UNAUTHORIZED',
details: {},
},
},
})
export class PetsController {
constructor(private readonly petsService: PetsService) {}
@Post('upload-image')
@UseInterceptors(
FileInterceptor('file', {
storage: diskStorage({
destination: (req, file, cb) => {
const dir = join(process.cwd(), 'uploads', 'pets');
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
cb(null, dir);
},
filename: (req, file, cb) => {
const randomName = Array(32)
.fill(null)
.map(() => Math.round(Math.random() * 16).toString(16))
.join('');
cb(null, `${randomName}${extname(file.originalname)}`);
},
}),
limits: { fileSize: 10 * 1024 * 1024 }, // 10MB
}),
)
@ApiOperation({ summary: 'آپلود تصویر حیوان خانگی' })
uploadPetImage(@UploadedFile() file: Express.Multer.File) {
if (!file) {
throw new BadRequestException('فایلی ارسال نشده است');
}
const url = `/uploads/pets/${file.filename}`;
return { url, filename: file.filename };
}
@Post()
@ApiOperation({ summary: 'ثبت حیوان خانگی جدید' })
@ApiCreatedResponse({
description: 'حیوان خانگی جدید با موفقیت ثبت شد',
schema: {
example: {
id: 'c7b8d9e0-1234-5678-abcd-ef1234567890',
userId: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
name: 'بادی',
type: 'سگ',
breed: 'ژرمن شپرد',
age: 3,
weight: '25.50',
activityLevel: 'متوسط',
imageUrl: null,
createdAt: '2026-05-26T18:10:00.000Z',
},
},
})
@ApiBadRequestResponse({
description: 'خطا در صحت‌سنجی فیلدهای ورودی',
schema: {
example: {
success: false,
message: 'نوع حیوان خانگی اجباری است',
code: 'BAD_REQUEST',
details: {},
},
},
})
create(
@Req() req: { user: { id: string } },
@Body() createPetDto: CreatePetDto,
) {
return this.petsService.create(req.user.id, createPetDto);
}
@Get()
@ApiOperation({ summary: 'لیست حیوانات خانگی کاربر فعلی' })
@ApiOkResponse({
description: 'آرایه‌ای از حیوانات خانگی ثبت شده کاربر (صفحه‌بندی شده)',
schema: {
example: {
data: [
{
id: 'c7b8d9e0-1234-5678-abcd-ef1234567890',
userId: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
name: 'بادی',
type: 'سگ',
breed: 'ژرمن شپرد',
age: 3,
weight: '25.50',
activityLevel: 'متوسط',
imageUrl: null,
createdAt: '2026-05-26T18:10:00.000Z',
},
],
meta: {
total: 1,
page: 1,
lastPage: 1,
limit: 10,
},
},
},
})
findAll(@Req() req: { user: { id: string } }, @Query() query: PaginationDto) {
return this.petsService.findAllByUser(req.user.id, query);
}
@Get(':id')
@ApiOperation({ summary: 'دریافت جزئیات کامل یک حیوان خانگی' })
@ApiOkResponse({
description: 'اطلاعات کامل حیوان خانگی مشخص شده با ID',
schema: {
example: {
id: 'c7b8d9e0-1234-5678-abcd-ef1234567890',
userId: 'd8c4e428-cd2f-4c55-bfa3-dfa312bb6480',
name: 'بادی',
type: 'سگ',
breed: 'ژرمن شپرد',
age: 3,
weight: '25.50',
activityLevel: 'متوسط',
imageUrl: null,
medicalConditions: [],
reminders: [],
healthLogs: [],
createdAt: '2026-05-26T18:10:00.000Z',
},
},
})
@ApiNotFoundResponse({
description: 'حیوان خانگی پیدا نشد یا متعلق به کاربر جاری نیست',
schema: {
example: {
success: false,
message: 'Pet not found or unauthorized',
code: 'NOT_FOUND',
details: {},
},
},
})
findOne(@Req() req: { user: { id: string } }, @Param('id') id: string) {
return this.petsService.findOne(id, req.user.id);
}
@Patch(':id')
@ApiOperation({ summary: 'بروزرسانی اطلاعات حیوان خانگی' })
@ApiOkResponse({
description: 'اطلاعات حیوان خانگی با موفقیت به‌روزرسانی شد',
schema: {
example: {
id: 'c7b8d9e0-1234-5678-abcd-ef1234567890',
name: 'بادی قهرمان',
type: 'سگ',
breed: 'ژرمن شپرد',
age: 4,
weight: '26.00',
activityLevel: 'زیاد',
},
},
})
@ApiNotFoundResponse({
description: 'حیوان خانگی یافت نشد',
schema: {
example: {
success: false,
message: 'Pet not found',
code: 'NOT_FOUND',
details: {},
},
},
})
update(
@Req() req: { user: { id: string } },
@Param('id') id: string,
@Body() updatePetDto: UpdatePetDto,
) {
return this.petsService.update(id, req.user.id, updatePetDto);
}
@Delete(':id')
@ApiOperation({ summary: 'حذف حیوان خانگی' })
@ApiOkResponse({
description: 'حیوان خانگی با موفقیت حذف شد',
schema: {
example: {
success: true,
message: 'حیوان خانگی با موفقیت حذف شد',
},
},
})
@ApiNotFoundResponse({
description: 'حیوان خانگی یافت نشد',
schema: {
example: {
success: false,
message: 'Pet not found',
code: 'NOT_FOUND',
details: {},
},
},
})
remove(@Req() req: { user: { id: string } }, @Param('id') id: string) {
return this.petsService.remove(id, req.user.id);
}
@Post(':petId/reminders')
@ApiOperation({ summary: 'ثبت یادآور جدید برای پت' })
addReminder(
@Req() req: { user: { id: string } },
@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: { user: { id: string } },
@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: { user: { id: string } },
@Param('petId') petId: string,
@Body() createHealthLogDto: CreateHealthLogDto,
) {
return this.petsService.addHealthLog(
req.user.id,
petId,
createHealthLogDto,
);
}
}