chore: add ticket module and tickets entity

This commit is contained in:
mahyargdz
2025-01-22 17:03:46 +03:30
parent c48ec70638
commit e3762c1eba
16 changed files with 166 additions and 27 deletions
+1
View File
@@ -54,6 +54,7 @@
"pg": "^8.13.1", "pg": "^8.13.1",
"reflect-metadata": "^0.2.2", "reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1", "rxjs": "^7.8.1",
"slugify": "^1.6.6",
"typeorm": "^0.3.20" "typeorm": "^0.3.20"
}, },
"devDependencies": { "devDependencies": {
+9
View File
@@ -89,6 +89,9 @@ importers:
rxjs: rxjs:
specifier: ^7.8.1 specifier: ^7.8.1
version: 7.8.1 version: 7.8.1
slugify:
specifier: ^1.6.6
version: 1.6.6
typeorm: typeorm:
specifier: ^0.3.20 specifier: ^0.3.20
version: 0.3.20(ioredis@5.4.2)(pg@8.13.1)(redis@4.7.0)(ts-node@10.9.2(@types/node@20.17.14)(typescript@5.7.3)) version: 0.3.20(ioredis@5.4.2)(pg@8.13.1)(redis@4.7.0)(ts-node@10.9.2(@types/node@20.17.14)(typescript@5.7.3))
@@ -4212,6 +4215,10 @@ packages:
slick@1.12.2: slick@1.12.2:
resolution: {integrity: sha512-4qdtOGcBjral6YIBCWJ0ljFSKNLz9KkhbWtuGvUyRowl1kxfuE1x/Z/aJcaiilpb3do9bl5K7/1h9XC5wWpY/A==} resolution: {integrity: sha512-4qdtOGcBjral6YIBCWJ0ljFSKNLz9KkhbWtuGvUyRowl1kxfuE1x/Z/aJcaiilpb3do9bl5K7/1h9XC5wWpY/A==}
slugify@1.6.6:
resolution: {integrity: sha512-h+z7HKHYXj6wJU+AnS/+IH8Uh9fdcX1Lrhg1/VMdf9PwoBQXFcXiAdsy2tSK0P6gKwJLXp02r90ahUCqHk9rrw==}
engines: {node: '>=8.0.0'}
sonic-boom@4.2.0: sonic-boom@4.2.0:
resolution: {integrity: sha512-INb7TM37/mAcsGmc9hyyI6+QR3rR1zVRu36B0NeGXKnOOLiZOfER5SA+N7X7k3yUYRzLWafduTDvJAfDswwEww==} resolution: {integrity: sha512-INb7TM37/mAcsGmc9hyyI6+QR3rR1zVRu36B0NeGXKnOOLiZOfER5SA+N7X7k3yUYRzLWafduTDvJAfDswwEww==}
@@ -9963,6 +9970,8 @@ snapshots:
slick@1.12.2: slick@1.12.2:
optional: true optional: true
slugify@1.6.6: {}
sonic-boom@4.2.0: sonic-boom@4.2.0:
dependencies: dependencies:
atomic-sleep: 1.0.0 atomic-sleep: 1.0.0
+4 -1
View File
@@ -56,11 +56,14 @@ export const enum UserMessage {
EMAIL_EXIST = "ایمیل قبلا ثبت شده است", EMAIL_EXIST = "ایمیل قبلا ثبت شده است",
ROLE_NOT_FOUND = "نقش یافت نشد", ROLE_NOT_FOUND = "نقش یافت نشد",
USER_EXISTS = "کاربر با این مشخصات وجود دارد", USER_EXISTS = "کاربر با این مشخصات وجود دارد",
USERNAME_EXIST = "نام کاربری قبلا ثبت شده است",
USERNAME_NOT_EMPTY = "نام کاربری نمی‌تواند خالی باشد",
USERNAME_SHOULD_BE_BETWEEN_3_AND_50 = "نام کاربری باید بین ۳ تا ۵۰ کاراکتر باشد",
} }
export const enum CommonMessage { export const enum CommonMessage {
VALIDITY_TYPE_REQUIRED = "نوع اعتبار سنجی مورد نیاز است", VALIDITY_TYPE_REQUIRED = "نوع اعتبار سنجی مورد نیاز است",
THIS_FILED_IS_REQUIRED = "این فیلد الزامی است", THIS_FILED_IS_REQUIRED = "این فیلد الزامی است",
VALID_FOR_CHOOSE = "معتبر برای انتخاب", VALID_FOR_CHOOSE = "معتبر برای انتخاب",
USER_EXIST = "کاربر وجود دارد", UPDATE_SUCCESS = "با موفقیت به روز رسانی شد",
} }
+4 -4
View File
@@ -1,7 +1,7 @@
import { BadRequestException, Injectable, Logger } from "@nestjs/common"; import { BadRequestException, Injectable, Logger } from "@nestjs/common";
import { TokensService } from "./tokens.service"; import { TokensService } from "./tokens.service";
import { AuthMessage, CommonMessage, UserMessage } from "../../../common/enums/message.enum"; import { AuthMessage, UserMessage } from "../../../common/enums/message.enum";
import { UsersService } from "../../users/providers/users.service"; import { UsersService } from "../../users/providers/users.service";
import { OTPService } from "../../utils/providers/otp.service"; import { OTPService } from "../../utils/providers/otp.service";
import { PasswordService } from "../../utils/providers/password.service"; import { PasswordService } from "../../utils/providers/password.service";
@@ -34,7 +34,7 @@ export class AuthService {
} }
const otpCode = await this.otpService.generateAndSetInCache(phone, "REGISTER"); const otpCode = await this.otpService.generateAndSetInCache(phone, "REGISTER");
// await SmsService.sendOtp(phone, otpCode); // await SmsService.sendOtp(phone, otpCode);
this.logger.log(`OTP sent to ${phone}: ${otpCode}`); this.logger.debug(`OTP sent to ${phone}: ${otpCode}`);
return { return {
message: AuthMessage.OTP_SENT, message: AuthMessage.OTP_SENT,
@@ -82,7 +82,7 @@ export class AuthService {
async checkUserExist(checkUserExistDto: CheckUserExistDto) { async checkUserExist(checkUserExistDto: CheckUserExistDto) {
const user = await this.usersService.findOneWithEmail(checkUserExistDto.email); const user = await this.usersService.findOneWithEmail(checkUserExistDto.email);
if (!user) throw new BadRequestException(UserMessage.USER_NOT_FOUND); if (!user) throw new BadRequestException(UserMessage.USER_NOT_FOUND);
return { message: CommonMessage.USER_EXIST }; return { message: UserMessage.USER_EXISTS };
} }
//****************** */ //****************** */
@@ -102,7 +102,7 @@ export class AuthService {
const otpCode = await this.otpService.generateAndSetInCache(phone, "LOGIN"); const otpCode = await this.otpService.generateAndSetInCache(phone, "LOGIN");
// await SmsService.sendOtp(phone, otpCode); // await SmsService.sendOtp(phone, otpCode);
this.logger.log(`OTP sent to ${phone}: ${otpCode}`); this.logger.debug(`OTP sent to ${phone}: ${otpCode}`);
return { return {
message: AuthMessage.OTP_SENT, message: AuthMessage.OTP_SENT,
@@ -0,0 +1,16 @@
import { Column, Entity, OneToMany } from "typeorm";
import { Ticket } from "./ticket.entity";
import { BaseEntity } from "../../../common/entities/base.entity";
@Entity()
export class TicketCategory extends BaseEntity {
@Column({ type: "varchar", length: 150, nullable: false, unique: true })
name: string;
@Column({ type: "text", nullable: true })
description: string;
@OneToMany(() => Ticket, (ticket) => ticket.category)
tickets: Ticket[];
}
@@ -0,0 +1,36 @@
import { Column, Entity, JoinColumn, ManyToOne } from "typeorm";
import { TicketCategory } from "./ticket-category.entity";
import { BaseEntity } from "../../../common/entities/base.entity";
import { User } from "../../users/entities/user.entity";
import { TicketPriority } from "../enums/ticket-priority.enum";
import { TicketStatus } from "../enums/ticket-status.enum";
@Entity()
export class Ticket extends BaseEntity {
@Column({ type: "varchar", length: 150, nullable: false })
title: string;
@Column({ type: "varchar", length: 150, nullable: false })
subject: string;
@Column({ type: "enum", enum: TicketStatus, default: TicketStatus.PENDING })
status: TicketStatus;
@Column({ type: "enum", enum: TicketPriority, nullable: false })
priority: TicketPriority;
//TODO:ADD service reference here
@JoinColumn()
@ManyToOne(() => User, (user) => user.tickets, { nullable: true })
assignedTo: User;
@JoinColumn()
@ManyToOne(() => User, (user) => user.tickets, { onDelete: "CASCADE", nullable: false })
user: User;
@JoinColumn()
@ManyToOne(() => TicketCategory, (category) => category.tickets, { onDelete: "RESTRICT", nullable: false })
category: TicketCategory;
}
@@ -0,0 +1,5 @@
export enum TicketPriority {
LOW = "LOW",
MEDIUM = "MEDIUM",
HIGH = "HIGH",
}
@@ -0,0 +1,5 @@
export enum TicketStatus {
PENDING = "PENDING",
ANSWERED = "ANSWERED",
CLOSED = "CLOSED",
}
+9 -4
View File
@@ -1,9 +1,14 @@
import { Module } from '@nestjs/common'; import { Module } from "@nestjs/common";
import { TicketsService } from './tickets.service'; import { TypeOrmModule } from "@nestjs/typeorm";
import { TicketsController } from './tickets.controller';
import { TicketCategory } from "./entities/ticket-category.entity";
import { Ticket } from "./entities/ticket.entity";
import { TicketsController } from "./tickets.controller";
import { TicketsService } from "./tickets.service";
@Module({ @Module({
imports: [TypeOrmModule.forFeature([Ticket, TicketCategory])],
providers: [TicketsService], providers: [TicketsService],
controllers: [TicketsController] controllers: [TicketsController],
}) })
export class TicketsModule {} export class TicketsModule {}
+3 -2
View File
@@ -1,7 +1,7 @@
import { ApiProperty } from "@nestjs/swagger"; import { ApiProperty } from "@nestjs/swagger";
import { IsEnum, IsNotEmpty, IsString } from "class-validator"; import { IsEnum, IsNotEmpty, IsString, Length } from "class-validator";
import { CommonMessage } from "../../../common/enums/message.enum"; import { CommonMessage, UserMessage } from "../../../common/enums/message.enum";
import { ValidityType } from "../enums/validity-type.enum"; import { ValidityType } from "../enums/validity-type.enum";
export class CheckValidityDTO { export class CheckValidityDTO {
@@ -11,6 +11,7 @@ export class CheckValidityDTO {
type: ValidityType; type: ValidityType;
@IsNotEmpty({ message: CommonMessage.THIS_FILED_IS_REQUIRED }) @IsNotEmpty({ message: CommonMessage.THIS_FILED_IS_REQUIRED })
@Length(3, 50, { message: UserMessage.USERNAME_SHOULD_BE_BETWEEN_3_AND_50 })
@IsString({ message: CommonMessage.THIS_FILED_IS_REQUIRED }) @IsString({ message: CommonMessage.THIS_FILED_IS_REQUIRED })
@ApiProperty({ example: "mahyargdz" }) @ApiProperty({ example: "mahyargdz" })
value: string; value: string;
+13 -2
View File
@@ -1,3 +1,14 @@
export class UpdateProfileDto { import { ApiProperty, PartialType, PickType } from "@nestjs/swagger";
userName: string; import { IsNotEmpty, IsOptional, IsString, Length } from "class-validator";
import { UserMessage } from "../../../common/enums/message.enum";
import { CompleteRegistrationDto } from "../../auth/DTO/complete-register.dto";
export class UpdateProfileDto extends PartialType(PickType(CompleteRegistrationDto, ["firstName", "lastName", "birthDate"] as const)) {
@IsOptional()
@IsNotEmpty({ message: UserMessage.USERNAME_NOT_EMPTY })
@Length(3, 50, { message: UserMessage.USERNAME_SHOULD_BE_BETWEEN_3_AND_50 })
@IsString({ message: UserMessage.USERNAME_NOT_EMPTY })
@ApiProperty({ description: "User name", example: "mamad24" })
userName?: string;
} }
+9 -5
View File
@@ -1,7 +1,8 @@
import { Column, Entity, JoinColumn, OneToOne } from "typeorm"; import { Column, Entity, JoinColumn, ManyToOne, OneToMany } from "typeorm";
import { Role } from "./role.entity"; import { Role } from "./role.entity";
import { BaseEntity } from "../../../common/entities/base.entity"; import { BaseEntity } from "../../../common/entities/base.entity";
import { Ticket } from "../../tickets/entities/ticket.entity";
@Entity() @Entity()
export class User extends BaseEntity { export class User extends BaseEntity {
@@ -11,7 +12,7 @@ export class User extends BaseEntity {
@Column({ type: "varchar", length: 11, unique: true, nullable: false }) @Column({ type: "varchar", length: 11, unique: true, nullable: false })
phone: string; phone: string;
@Column({ type: "varchar", length: 150, unique: true, nullable: true }) @Column({ type: "varchar", length: 50, unique: true, nullable: true })
userName: string; userName: string;
@Column({ type: "varchar", length: 150 }) @Column({ type: "varchar", length: 150 })
@@ -23,13 +24,16 @@ export class User extends BaseEntity {
@Column({ type: "varchar", length: 200 }) @Column({ type: "varchar", length: 200 })
lastName: string; lastName: string;
@Column() @Column({ type: "varchar", length: 12, nullable: true })
birthDate: string; birthDate: string;
@Column({ type: "varchar", length: 100 }) @Column({ type: "varchar", length: 100, unique: true, nullable: false })
nationalCode: string; nationalCode: string;
@JoinColumn() @JoinColumn()
@OneToOne(() => Role, { eager: true, cascade: true, onDelete: "RESTRICT", nullable: false }) @ManyToOne(() => Role, { eager: true, onDelete: "RESTRICT", nullable: false })
role: Role; role: Role;
@OneToMany(() => Ticket, (ticket) => ticket.user)
tickets: Ticket[];
} }
@@ -21,4 +21,10 @@ export class UserRepository extends Repository<User> {
phone, phone,
}); });
} }
async findOneWithUserName(userName: string): Promise<User | null> {
return this.findOneBy({
userName,
});
}
} }
+35 -3
View File
@@ -1,4 +1,6 @@
import { BadRequestException, Injectable, Logger } from "@nestjs/common"; import { BadRequestException, Injectable, Logger } from "@nestjs/common";
import slugify from "slugify";
import { Not } from "typeorm";
import { RoleRepository } from "./roles.repository"; import { RoleRepository } from "./roles.repository";
import { UserRepository } from "./users.repository"; import { UserRepository } from "./users.repository";
@@ -6,8 +8,10 @@ import { roles } from "../../../../db/seeders/role.seeder";
import { CommonMessage, UserMessage } from "../../../common/enums/message.enum"; import { CommonMessage, UserMessage } from "../../../common/enums/message.enum";
import { CompleteRegistrationDto } from "../../auth/DTO/complete-register.dto"; import { CompleteRegistrationDto } from "../../auth/DTO/complete-register.dto";
import { CheckValidityDTO } from "../DTO/check-validity.dto"; import { CheckValidityDTO } from "../DTO/check-validity.dto";
import { UpdateProfileDto } from "../DTO/update-profile.dto";
import { User } from "../entities/user.entity"; import { User } from "../entities/user.entity";
import { RoleEnum } from "../enums/role.enum"; import { RoleEnum } from "../enums/role.enum";
import { ValidityType } from "../enums/validity-type.enum";
@Injectable() @Injectable()
export class UsersService { export class UsersService {
@@ -38,6 +42,31 @@ export class UsersService {
if (!user) throw new BadRequestException(UserMessage.USER_NOT_FOUND); if (!user) throw new BadRequestException(UserMessage.USER_NOT_FOUND);
return { user }; return { user };
} }
/************************************************************ */
async updateProfile(userId: string, updateProfileDto: UpdateProfileDto) {
const { firstName, lastName, birthDate } = updateProfileDto;
if (updateProfileDto.userName) {
updateProfileDto.userName = slugify(updateProfileDto.userName, { lower: true, trim: true });
const existUserName = await this.userRepository.findOneBy({ userName: updateProfileDto.userName, id: Not(userId) });
if (existUserName) throw new BadRequestException(UserMessage.USERNAME_EXIST);
}
const user = await this.userRepository.findOneBy({ id: userId });
if (!user) throw new BadRequestException(UserMessage.USER_NOT_FOUND);
const { userName } = updateProfileDto;
if (userName) user.userName = userName;
if (firstName) user.firstName = firstName;
if (lastName) user.lastName = lastName;
if (birthDate) user.birthDate = birthDate;
await this.userRepository.save(user);
return {
message: CommonMessage.UPDATE_SUCCESS,
};
}
/************************************************************ */ /************************************************************ */
async findOneWithEmail(email: string): Promise<User | null> { async findOneWithEmail(email: string): Promise<User | null> {
@@ -65,10 +94,13 @@ export class UsersService {
} }
/************************************************************ */ /************************************************************ */
async checkValidity(checkDto: CheckValidityDTO) { async checkValidity(checkDto: CheckValidityDTO, userId: string) {
const { type, value } = checkDto; const { type } = checkDto;
const user = await this.userRepository.findOneBy({ [type]: value }); if (type === ValidityType.USERNAME) checkDto.value = slugify(checkDto.value, { lower: true, trim: true });
const user = await this.userRepository.findOneBy({ [type]: checkDto.value, id: Not(userId) });
if (user) throw new BadRequestException(UserMessage.USER_EXISTS); if (user) throw new BadRequestException(UserMessage.USER_EXISTS);
return { message: CommonMessage.VALID_FOR_CHOOSE }; return { message: CommonMessage.VALID_FOR_CHOOSE };
} }
+10 -4
View File
@@ -1,7 +1,8 @@
import { Body, Controller, Get, Patch, Post } from "@nestjs/common"; import { Body, Controller, Get, HttpCode, HttpStatus, Patch, Post } from "@nestjs/common";
import { ApiOperation, ApiTags } from "@nestjs/swagger"; import { ApiOperation, ApiTags } from "@nestjs/swagger";
import { CheckValidityDTO } from "./DTO/check-validity.dto"; import { CheckValidityDTO } from "./DTO/check-validity.dto";
import { UpdateProfileDto } from "./DTO/update-profile.dto";
import { User } from "./entities/user.entity"; import { User } from "./entities/user.entity";
import { UsersService } from "./providers/users.service"; import { UsersService } from "./providers/users.service";
import { AuthGuards } from "../../common/decorators/auth-guard.decorator"; import { AuthGuards } from "../../common/decorators/auth-guard.decorator";
@@ -19,13 +20,18 @@ export class UsersController {
return this.usersService.getMe(user.id); return this.usersService.getMe(user.id);
} }
@AuthGuards()
@ApiOperation({ summary: "Update user profile" })
@Patch("update-profile") @Patch("update-profile")
updateProfile() {} updateProfile(@Body() updateProfileDto: UpdateProfileDto, @UserDec() user: User) {
return this.usersService.updateProfile(user.id, updateProfileDto);
}
@AuthGuards() @AuthGuards()
@ApiOperation({ summary: "Check validity of user field" }) @ApiOperation({ summary: "Check validity of user field" })
@HttpCode(HttpStatus.OK)
@Post("check-validity") @Post("check-validity")
checkValidity(@Body() checkValidityDto: CheckValidityDTO) { checkValidity(@Body() checkValidityDto: CheckValidityDTO, @UserDec() user: User) {
return this.usersService.checkValidity(checkValidityDto); return this.usersService.checkValidity(checkValidityDto, user.id);
} }
} }
+1 -2
View File
@@ -1,8 +1,7 @@
{ {
"extends": "./tsconfig.json", "extends": "./tsconfig.json",
"compilerOptions": { "compilerOptions": {
"outDir": "./dist", "outDir": "./dist"
"incremental": true
}, },
"include": ["src"], "include": ["src"],
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"] "exclude": ["node_modules", "test", "dist", "**/*spec.ts"]