commit for pushing in holding repo

This commit is contained in:
pooya
2026-02-19 16:19:43 +03:30
commit 2286156f6e
108 changed files with 18159 additions and 0 deletions

58
.gitignore vendored Normal file
View File

@@ -0,0 +1,58 @@
# compiled output
/dist
/node_modules
/build
/uploads
# Logs
logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# temp directory
.temp
.tmp
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

98
README.md Normal file
View File

@@ -0,0 +1,98 @@
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
</p>
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
## Description
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
## Project setup
```bash
$ npm install
```
## Compile and run the project
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
```
## Run tests
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
## Deployment
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
```bash
$ npm install -g @nestjs/mau
$ mau deploy
```
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
## Resources
Check out a few resources that may come in handy when working with NestJS:
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
## Stay in touch
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).

26
ecosystem.config.js Normal file
View File

@@ -0,0 +1,26 @@
module.exports = {
apps: [
{
name: "server",
script: "npm",
args: "start",
cwd: __dirname,
instances: 1,
exec_mode: "fork",
watch: false,
env: {
SITE_URL: "http://robinnetwork.ir",
PORT: 4000,
DATABASE_HOST: "localhost",
DATABASE_PORT: 5432,
DATABASE_USER: "postgres",
DATABASE_PASSWORD: 1234,
DATABASE_NAME: "robin-network",
OTP_EXPIRE_TIME_MINUTES: 5,
JWT_SECRET: "IOnf9828bcoeiwfnoUTFDIUWND983bBCIUWYUVXU@$YTCE%OINiuesvfc7632biUBEC&OInuy2vciabkjmcpqocuyBIUBFUEYVXUWVD",
JWT_EXPIRATION: "10d",
JWT_EXPIRATION_IN_HOUR: 240,
},
},
],
};

34
eslint.config.mjs Normal file
View File

@@ -0,0 +1,34 @@
// @ts-check
import eslint from '@eslint/js';
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
import globals from 'globals';
import tseslint from 'typescript-eslint';
export default tseslint.config(
{
ignores: ['eslint.config.mjs'],
},
eslint.configs.recommended,
...tseslint.configs.recommendedTypeChecked,
eslintPluginPrettierRecommended,
{
languageOptions: {
globals: {
...globals.node,
...globals.jest,
},
sourceType: 'commonjs',
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
},
{
rules: {
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-floating-promises': 'warn',
'@typescript-eslint/no-unsafe-argument': 'warn'
},
},
);

8
nest-cli.json Normal file
View File

@@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}

14355
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

98
package.json Normal file
View File

@@ -0,0 +1,98 @@
{
"name": "server",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"dev": "nest start --watch",
"migration:run": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js migration:run -d ./src/utilities/data-source.ts",
"migration:generate": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js migration:generate ./src/migrations/$npm_config_name -d ./src/utilities/data-source.ts",
"migration:revert": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js migration:revert -d ./src/utilities/data-source.ts",
"schema:drop": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js schema:drop -d ./src/utilities/data-source.ts",
"db:reset": "npm run schema:drop && npm run migration:run",
"seed": "ts-node -r tsconfig-paths/register ./src/seeders/index.ts",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs-modules/mailer": "^2.0.2",
"@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.2",
"@nestjs/core": "^11.0.1",
"@nestjs/jwt": "^11.0.0",
"@nestjs/passport": "^11.0.5",
"@nestjs/platform-express": "^11.1.9",
"@nestjs/swagger": "^11.2.0",
"@nestjs/typeorm": "^11.0.0",
"@types/multer": "^2.0.0",
"bcryptjs": "^3.0.2",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.2",
"cookie-parser": "^1.4.7",
"dotenv": "^17.2.2",
"multer": "^2.0.2",
"nodemailer": "^7.0.6",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"pg": "^8.16.3",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"uuid": "^13.0.0"
},
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",
"@eslint/js": "^9.18.0",
"@nestjs/cli": "^11.0.0",
"@nestjs/schematics": "^11.0.0",
"@nestjs/testing": "^11.0.1",
"@types/express": "^5.0.0",
"@types/jest": "^30.0.0",
"@types/node": "^22.10.7",
"@types/supertest": "^6.0.2",
"eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-prettier": "^5.2.2",
"globals": "^16.0.0",
"jest": "^30.0.0",
"prettier": "^3.4.2",
"source-map-support": "^0.5.21",
"supertest": "^7.0.0",
"ts-jest": "^29.2.5",
"ts-loader": "^9.5.2",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"typeorm": "^0.3.27",
"typeorm-ts-node-commonjs": "^0.3.20",
"typescript": "^5.7.3",
"typescript-eslint": "^8.20.0"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

39
src/app.module.ts Normal file
View File

@@ -0,0 +1,39 @@
import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { TypeOrmModule } from "@nestjs/typeorm";
import { TypeOrmDataSource } from "./utilities/data-source";
import { AuthModule } from "./modules/auth/auth.module";
import { MailModule } from "./modules/mails/mails.module";
import { UsersModule } from "./modules/users/users.module";
import { APP_GUARD } from "@nestjs/core";
import { JwtAuthCuard } from "./guards/jwt-auth.guard";
import { RolesGuard } from "./guards/roles.guard";
import { BlogsModule } from "./modules/blogs/blogs.module";
import { UploadModule } from "./modules/uploads/uploads.module";
import { PortfoliosModule } from "./modules/portfolios/portfolios.module";
import { ContactsModule } from "./modules/contacts/contacts.module";
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
TypeOrmModule.forRoot(TypeOrmDataSource.options),
AuthModule,
MailModule,
UsersModule,
BlogsModule,
PortfoliosModule,
ContactsModule,
UploadModule,
],
providers: [
{
provide: APP_GUARD,
useClass: JwtAuthCuard,
},
{
provide: APP_GUARD,
useClass: RolesGuard,
},
],
})
export class AppModule {}

View File

@@ -0,0 +1,5 @@
import { SetMetadata } from "@nestjs/common";
export const PUBLIC_ROUTE_KEY = "is-public-route";
export const PublicRoute = () => SetMetadata(PUBLIC_ROUTE_KEY, true);

View File

@@ -0,0 +1,6 @@
import { SetMetadata } from "@nestjs/common";
import { RoleEnum } from "src/enums/role.enum";
export const AVAILABLE_ROLES_KEY = "available_roles";
export const Roles = (...roles: RoleEnum[]) => SetMetadata(AVAILABLE_ROLES_KEY, [...roles]);

View File

@@ -0,0 +1,17 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsNotEmpty, IsString, MaxLength, MinLength } from "class-validator";
export class LoginDto {
@ApiProperty({ name: "identifier", example: "example@gmail.com" })
@IsString({ message: "identifier should be a string" })
@IsNotEmpty({ message: "please enter your Username or Email" })
@MinLength(3, { message: "Username or Email is not valid" })
identifier: string;
@ApiProperty({ name: "code", example: "74013" })
@IsString({ message: "code should be a string" })
@IsNotEmpty({ message: "please enter your validation code" })
@MinLength(5, { message: "code is not valid" })
@MaxLength(5, { message: "code is not valid" })
code: string;
}

View File

@@ -0,0 +1,10 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsNotEmpty, IsString, Matches, MinLength } from "class-validator";
export class SendCodeDto {
@ApiProperty({ name: "identifier", example: "example@gmail.com" })
@IsString({ message: "identifier should be a string" })
@IsNotEmpty({ message: "please enter your Username or Email" })
@MinLength(3, { message: "Username or Email is not valid" })
identifier: string;
}

View File

@@ -0,0 +1,28 @@
import { ApiProperty } from "@nestjs/swagger";
import { Transform } from "class-transformer";
import { IsNotEmpty, IsString, Matches, MaxLength, MinLength } from "class-validator";
export class InsertAboutFieldsDto {
@ApiProperty({ name: "title", example: "عنوان بلاگ" })
@IsString({ message: "title should be a string" })
@IsNotEmpty({ message: "please fill the title" })
@MinLength(3, { message: "title should be 3 characters at least" })
@MaxLength(150, { message: "title can be 150 characters maximum" })
title: string;
@ApiProperty({ name: "href", example: "blog-short-link" })
@IsString({ message: "short link should be a string" })
@IsNotEmpty({ message: "please fill the short link" })
@MinLength(3, { message: "short link should be 3 characters at least" })
@MaxLength(50, { message: "short link can be 50 characters maximum" })
@Transform(({ value }) => value.toLowerCase().trim())
@Matches(/^[a-z-]+$/, { message: 'short link is not valid only characters "-" is alowed' })
href: string;
@ApiProperty({ name: "description", example: "توضیحات" })
@IsString({ message: "description should be a string" })
@IsNotEmpty({ message: "please fill the description" })
@MinLength(10, { message: "description should be 10 characters at least" })
@MaxLength(350, { message: "description can be 350 characters maximum" })
description: string;
}

View File

@@ -0,0 +1,18 @@
import { Type } from "class-transformer";
import { IsArray, IsNotEmpty, IsString, ValidateNested } from "class-validator";
import { EditorBlockDto } from "./update-dynamic-data.dto";
export class TranslationLanguageDto {
@IsString({ message: "title must be a string" })
@IsNotEmpty({ message: "title should not be empty" })
title: string;
@IsString({ message: "description must be a string" })
@IsNotEmpty({ message: "description should not be empty" })
description: string;
@IsArray({ message: "editor must be an array" })
@ValidateNested({ each: true })
@Type(() => EditorBlockDto)
editor: EditorBlockDto[];
}

View File

@@ -0,0 +1,3 @@
import { InsertAboutFieldsDto } from "./insert-about-fields.dto";
export class UpdateAboutFieldsDto extends InsertAboutFieldsDto {}

View File

@@ -0,0 +1,85 @@
import {
IsArray,
IsEnum,
IsInt,
IsString,
Min,
ValidateNested,
ValidationArguments,
ValidatorConstraint,
ValidatorConstraintInterface,
Validate,
Matches,
} from "class-validator";
import { Type } from "class-transformer";
@ValidatorConstraint({ name: "validContentByType", async: false })
export class ValidContentByTypeConstraint implements ValidatorConstraintInterface {
validate(content: any, args: ValidationArguments) {
const block = args.object as any;
switch (block.type) {
case "heading":
case "paragraph":
return typeof content === "string" && content.trim() !== "";
case "image":
return typeof content === "number" && Number.isInteger(content);
case "link":
return (
content &&
typeof content === "object" &&
typeof content.content === "string" &&
content.content.trim() !== "" &&
typeof content.link === "string" &&
/^https?:\/\//i.test(content.link.trim())
);
default:
return false;
}
}
defaultMessage(args: ValidationArguments) {
const block = args.object as any;
switch (block.type) {
case "heading":
case "paragraph":
return "content should`nt be empty";
case "image":
return "please select the image";
case "link":
return "link should be valid";
default:
return "invalid block type";
}
}
}
// Link sub-object
class LinkContentDto {
@IsString({ message: "link text must be a string" })
content: string;
@IsString({ message: "link URL must be a string" })
@Matches(/^https?:\/\//i, { message: "link must start with http:// or https://" })
link: string;
}
export class EditorBlockDto {
@IsEnum(["image", "link", "paragraph", "heading"], {
message: "type must be one of: image, link, paragraph, heading",
})
type: "image" | "link" | "paragraph" | "heading";
@IsInt({ message: "sort must be an integer" })
sort: number;
@Validate(ValidContentByTypeConstraint)
content: string | number | LinkContentDto;
}
export class UpdateDynamicDataDto {
@IsArray({ message: "editor must be an array" })
@ValidateNested({ each: true })
@Type(() => EditorBlockDto)
editor: EditorBlockDto[];
}

View File

@@ -0,0 +1,9 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsNotEmpty, IsString } from "class-validator";
export class UpdateFeaturedImageDto {
@ApiProperty({ name: "image", example: "image-42389-4932" })
@IsString({ message: "image url must be a string" })
@IsNotEmpty({ message: "please send image url" })
image: string;
}

View File

@@ -0,0 +1,9 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsArray, IsNotEmpty } from "class-validator";
export class UpdateGalleryDto {
@ApiProperty({ name: "gallery", example: ["image-1", "image-2", "image-3"] })
@IsArray({ message: "gallery must be an array of strings" })
@IsNotEmpty({ message: "please send gallery urls" })
gallery: string[];
}

View File

@@ -0,0 +1,13 @@
import { Type } from "class-transformer";
import { ValidateNested } from "class-validator";
import { TranslationLanguageDto } from "./translation-language.dto";
export class UpdateTranslationsDto {
@ValidateNested()
@Type(() => TranslationLanguageDto)
en: TranslationLanguageDto;
@ValidateNested()
@Type(() => TranslationLanguageDto)
ar: TranslationLanguageDto;
}

View File

@@ -0,0 +1,25 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsNotEmpty, IsString, MaxLength, MinLength } from "class-validator";
export class InsertContactDto {
@ApiProperty({ name: "fullName", example: "مجید حسینی" })
@IsString({ message: "نام خانوادگی باید وارد شود" })
@IsNotEmpty({ message: "نام خانوادگی باید وارد شود" })
@MinLength(3, { message: "نام خانوادگی باید حداقل 3 کارکتر باشد" })
@MaxLength(30, { message: "نام خانوادگی باید حداکثر 30 کارکتر باشد" })
fullName: string;
@ApiProperty({ name: "email", example: "example@gmail.com" })
@IsString({ message: "ایمیل باید وارد شود" })
@IsNotEmpty({ message: "ایمیل باید وارد شود" })
@MinLength(10, { message: "ایمیل باید حداقل 10 کارکتر باشد" })
@MaxLength(40, { message: "ایمیل باید حداکثر 40 کارکتر باشد" })
email: string;
@ApiProperty({ name: "text", example: "متن پیاممتن" })
@IsString({ message: "متن باید وارد شود" })
@IsNotEmpty({ message: "متن باید وارد شود" })
@MinLength(5, { message: "متن باید حداقل 5 کارکتر باشد" })
@MaxLength(400, { message: "متن باید حداکثر 400 کارکتر باشد" })
text: string;
}

View File

@@ -0,0 +1,52 @@
import { ApiProperty } from "@nestjs/swagger";
import { Transform } from "class-transformer";
import { IsEnum, IsNotEmpty, IsString, Matches, MaxLength, MinLength } from "class-validator";
import { PortfolioCategoryEnum } from "src/enums/portfolio-category.enum";
export class InsertPortfolioAboutFieldsDto {
@ApiProperty({ name: "title", example: "عنوان بلاگ" })
@IsString({ message: "title should be a string" })
@IsNotEmpty({ message: "please fill the title" })
@MinLength(3, { message: "title should be 3 characters at least" })
@MaxLength(150, { message: "title can be 150 characters maximum" })
title: string;
@ApiProperty({ name: "href", example: "blog-short-link" })
@IsString({ message: "short link should be a string" })
@IsNotEmpty({ message: "please fill the short link" })
@MinLength(3, { message: "short link should be 3 characters at least" })
@MaxLength(50, { message: "short link can be 50 characters maximum" })
@Transform(({ value }) => value.toLowerCase().trim())
@Matches(/^[a-z-]+$/, { message: 'short link is not valid only characters "-" is alowed' })
href: string;
@ApiProperty({ name: "description", example: "توضیحات" })
@IsString({ message: "description should be a string" })
@IsNotEmpty({ message: "please fill the description" })
@MinLength(10, { message: "description should be 10 characters at least" })
@MaxLength(800, { message: "description can be 800 characters maximum" })
description: string;
@ApiProperty({ name: "employer", example: "اقای رمضانی" })
@IsString({ message: "employer should be a string" })
@IsNotEmpty({ message: "please fill the employer" })
@MinLength(3, { message: "employer should be 3 characters at least" })
@MaxLength(50, { message: "employer can be 50 characters maximum" })
employer: string;
@ApiProperty({ name: "external link", example: "https://website.com" })
@IsString({ message: "external link should be a string" })
@IsNotEmpty({ message: "please fill the external link" })
@MinLength(11, { message: "external link should be 10 characters at least" })
@MaxLength(350, { message: "external link can be 350 characters maximum" })
@Matches(/^https?:\/\//i, { message: "link must start with http:// or https://" })
externalLink: string;
@ApiProperty({
name: "category",
enum: PortfolioCategoryEnum,
example: PortfolioCategoryEnum.Network,
})
@IsEnum(PortfolioCategoryEnum, { message: "category is not valid" })
category: PortfolioCategoryEnum;
}

View File

@@ -0,0 +1,26 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsNotEmpty, IsString, MaxLength, MinLength } from "class-validator";
export class TranslationLanguagePortfolioDto {
@ApiProperty({ name: "title", example: "عنوان بلاگ" })
@IsString({ message: "title should be a string" })
@IsNotEmpty({ message: "please fill the title" })
@MinLength(3, { message: "title should be 3 characters at least" })
@MaxLength(150, { message: "title can be 150 characters maximum" })
title: string;
@ApiProperty({ name: "description", example: "توضیحات" })
@IsString({ message: "description should be a string" })
@IsNotEmpty({ message: "please fill the description" })
@MinLength(10, { message: "description should be 10 characters at least" })
@MaxLength(800, { message: "description can be 800 characters maximum" })
description: string;
@ApiProperty({ name: "employer", example: "اقای رمضانی" })
@IsString({ message: "employer should be a string" })
@IsNotEmpty({ message: "please fill the employer" })
@MinLength(3, { message: "employer should be 3 characters at least" })
@MaxLength(50, { message: "employer can be 50 characters maximum" })
employer: string;
}

View File

@@ -0,0 +1,3 @@
import { InsertPortfolioAboutFieldsDto } from "./insert-about-fields.dto";
export class UpdatePortfolioAboutFieldsDto extends InsertPortfolioAboutFieldsDto {}

View File

@@ -0,0 +1,9 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsNotEmpty, IsString } from "class-validator";
export class UpdatePortfolioFeaturedImageDto {
@ApiProperty({ name: "image", example: "image-42389-4932" })
@IsString({ message: "image url must be a string" })
@IsNotEmpty({ message: "please send image url" })
image: string;
}

View File

@@ -0,0 +1,9 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsArray, IsNotEmpty } from "class-validator";
export class UpdatePortfolioGalleryDto {
@ApiProperty({ name: "gallery", example: ["image-1", "image-2", "image-3"] })
@IsArray({ message: "gallery must be an array of strings" })
@IsNotEmpty({ message: "please send gallery urls" })
gallery: string[];
}

View File

@@ -0,0 +1,13 @@
import { Type } from "class-transformer";
import { ValidateNested } from "class-validator";
import { TranslationLanguagePortfolioDto } from "./translation-language.dto";
export class UpdatePortfolioTranslationsDto {
@ValidateNested()
@Type(() => TranslationLanguagePortfolioDto)
en: TranslationLanguagePortfolioDto;
@ValidateNested()
@Type(() => TranslationLanguagePortfolioDto)
ar: TranslationLanguagePortfolioDto;
}

View File

@@ -0,0 +1,18 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsNotEmpty, IsString, Matches, MaxLength, MinLength } from "class-validator";
import { emailRegexp } from "src/helpers/regex";
export class CreateUserDto {
@ApiProperty({ name: "username", example: "izmajid" })
@IsString({ message: "username should be a string" })
@IsNotEmpty({ message: "please enter the username" })
@MinLength(3, { message: "username should be 3 Characters at least" })
@MaxLength(15, { message: "username can be Maximum 15 Characters" })
username: string;
@ApiProperty({ name: "email", example: "majid.izadi@gmail.com" })
@IsString({ message: "email should be a string" })
@IsNotEmpty({ message: "please enter the email" })
@Matches(emailRegexp, { message: "email is not valid" })
email: string;
}

View File

@@ -0,0 +1,3 @@
import { CreateUserDto } from "./create-user.dto";
export class UpdateUserDto extends CreateUserDto {}

View File

@@ -0,0 +1,54 @@
import {
Column,
CreateDateColumn,
DeleteDateColumn,
Entity,
JoinColumn,
ManyToOne,
OneToMany,
PrimaryColumn,
UpdateDateColumn,
} from "typeorm";
import { User } from "./users.entity";
import { BlogTranslation } from "./blogs_translation.entity";
import { PhaseEnum } from "src/enums/phase.enum";
@Entity({ name: "blogs" })
export class Blog {
@PrimaryColumn()
id: string;
@Column({ nullable: false })
writerId: string;
@Column({ nullable: true })
featuredImage: string;
@Column({ type: "jsonb", nullable: true, default: () => "'[]'" })
gallery: string[];
@Column({ nullable: false })
href: string;
@Column({ type: "enum", nullable: false, enum: PhaseEnum, default: () => PhaseEnum.BlogAboutData })
phase: string;
@Column({ nullable: true })
publishedAt: Date;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
@DeleteDateColumn()
deletedAt: Date;
@ManyToOne(() => User, (user) => user.blogs)
@JoinColumn({ name: "writerId", referencedColumnName: "id" })
writer: User;
@OneToMany(() => BlogTranslation, (bt) => bt.blog)
translations: BlogTranslation[];
}

View File

@@ -0,0 +1,29 @@
import { LanguageEnum } from "src/enums/language.enum";
import { Column, Entity, JoinColumn, ManyToOne, PrimaryColumn, Unique } from "typeorm";
import { Blog } from "./blogs.entity";
@Entity({ name: "blogs_translation" })
@Unique(["blogId", "language"])
export class BlogTranslation {
@PrimaryColumn()
id: string;
@Column({ nullable: true })
title: string;
@Column({ nullable: true })
description: string;
@Column({ type: "jsonb", nullable: true })
editor: any;
@Column({ type: "enum", enum: LanguageEnum, default: LanguageEnum.Farsi })
language: LanguageEnum;
@Column({ nullable: false })
blogId: string;
@ManyToOne(() => Blog, (blog) => blog.translations, { onDelete: "CASCADE" })
@JoinColumn({ name: "blogId", referencedColumnName: "id" })
blog: Blog;
}

View File

@@ -0,0 +1,19 @@
import { Column, Entity, PrimaryColumn } from "typeorm";
@Entity({ name: "contacts" })
export class Contact {
@PrimaryColumn()
id: string;
@Column({ nullable: false })
fullName: string;
@Column({ nullable: false })
email: string;
@Column({ nullable: false })
text: string;
@Column({ nullable: true })
ip: string;
}

View File

@@ -0,0 +1,16 @@
import { Column, Entity, PrimaryColumn } from "typeorm";
@Entity({ name: "otps" })
export class Otp {
@PrimaryColumn()
id: string;
@Column({ nullable: false })
email: string;
@Column({ nullable: false })
code: string;
@Column({ nullable: false })
expireAt: Date;
}

View File

@@ -0,0 +1,43 @@
import { PortfolioPhaseEnum } from "src/enums/portfolio-phase.enum";
import { Column, CreateDateColumn, DeleteDateColumn, Entity, OneToMany, PrimaryColumn, UpdateDateColumn } from "typeorm";
import { PortfolioTranslation } from "./portfolios_translation.entity";
import { PortfolioCategoryEnum } from "src/enums/portfolio-category.enum";
@Entity({ name: "portfolios" })
export class Portfolio {
@PrimaryColumn()
id: string;
@Column({ type: "enum", enum: PortfolioCategoryEnum, default: () => PortfolioCategoryEnum.Network })
category: PortfolioCategoryEnum;
@Column({ nullable: true })
externalLink: string;
@Column({ nullable: true })
featuredImage: string;
@Column({ type: "jsonb", nullable: true, default: () => "'[]'" })
gallery: string[];
@Column({ nullable: false })
href: string;
@Column({ type: "enum", nullable: false, enum: PortfolioPhaseEnum, default: () => PortfolioPhaseEnum.PortfolioAboutData })
phase: string;
@Column({ nullable: true })
publishedAt: Date;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
@DeleteDateColumn()
deletedAt: Date;
@OneToMany(() => PortfolioTranslation, (pt) => pt.portfolio)
translations: PortfolioTranslation[];
}

View File

@@ -0,0 +1,28 @@
import { LanguageEnum } from "src/enums/language.enum";
import { Column, Entity, JoinColumn, ManyToOne, PrimaryColumn } from "typeorm";
import { Portfolio } from "./portfolios.entity";
@Entity({ name: "portfolios_translation" })
export class PortfolioTranslation {
@PrimaryColumn()
id: string;
@Column({ nullable: true })
title: string;
@Column({ nullable: true })
description: string;
@Column({ nullable: true })
employer: string;
@Column({ type: "enum", enum: LanguageEnum, default: () => LanguageEnum.Farsi })
language: LanguageEnum;
@Column({ nullable: false })
portfolioId: string;
@ManyToOne(() => Portfolio, (p) => p.translations, { onDelete: "CASCADE" })
@JoinColumn({ name: "portfolioId", referencedColumnName: "id" })
portfolio: Portfolio;
}

View File

@@ -0,0 +1,56 @@
import {
Column,
CreateDateColumn,
DeleteDateColumn,
Entity,
JoinColumn,
ManyToOne,
OneToMany,
PrimaryColumn,
UpdateDateColumn,
} from "typeorm";
import { User } from "./users.entity";
import { Task } from "./tasks.entity";
@Entity({ name: "projects" })
export class Project {
@PrimaryColumn()
id: string;
@Column({ nullable: false, unique: true })
title: string;
@Column({ nullable: false })
adminId: string;
@Column({ nullable: false })
ownerFirstname: string;
@Column({ nullable: false })
ownerLastname: string;
@Column({ nullable: false })
ownerPhone: string;
@Column({ nullable: false })
status: string;
@Column({ nullable: false })
percentage: number;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
@DeleteDateColumn()
deletedAt: Date;
@ManyToOne(() => User, (user) => user.adminProjects)
@JoinColumn({ name: "adminId", referencedColumnName: "id" })
admin: User;
@OneToMany(() => Task, (task) => task.project)
tasks: Task[];
}

View File

@@ -0,0 +1,54 @@
import { Column, CreateDateColumn, DeleteDateColumn, Entity, JoinColumn, ManyToOne, PrimaryColumn, UpdateDateColumn } from "typeorm";
import { User } from "./users.entity";
import { Project } from "./projects.entity";
@Entity({ name: "tasks" })
export class Task {
@PrimaryColumn()
id: string;
@Column({ nullable: false })
creatorId: string;
@Column({ nullable: false })
userId: string;
@Column({ nullable: false })
projectId: string;
@Column({ nullable: false })
title: string;
@Column({ nullable: false })
description: string;
@Column({ nullable: false })
deadlineTime: Date;
@Column({ nullable: true })
rejectReason: string;
@Column({ nullable: true })
rejectDeadline: Date;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
@DeleteDateColumn()
deletedAt: Date;
@ManyToOne(() => User, (user) => user.createdTasks)
@JoinColumn({ name: "creatorId", referencedColumnName: "id" })
creator: User;
@ManyToOne(() => User, (user) => user.tasks)
@JoinColumn({ name: "userId", referencedColumnName: "id" })
user: User;
@ManyToOne(() => Project, (project) => project.tasks)
@JoinColumn({ name: "projectId", referencedColumnName: "id" })
project: Project;
}

View File

@@ -0,0 +1,41 @@
import { RoleEnum } from "src/enums/role.enum";
import { Column, CreateDateColumn, DeleteDateColumn, Entity, OneToMany, PrimaryColumn, UpdateDateColumn } from "typeorm";
import { Project } from "./projects.entity";
import { Task } from "./tasks.entity";
import { Blog } from "./blogs.entity";
@Entity({ name: "users" })
export class User {
@PrimaryColumn()
id: string;
@Column({ nullable: false })
username: string;
@Column({ nullable: false })
email: string;
@Column({ enum: RoleEnum, type: "enum", default: RoleEnum.Tech })
role: RoleEnum;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
@DeleteDateColumn()
deletedAt: Date;
@OneToMany(() => Project, (project) => project.admin)
adminProjects: Project[];
@OneToMany(() => Task, (task) => task.creator)
createdTasks: Task[];
@OneToMany(() => Task, (task) => task.user)
tasks: Task[];
@OneToMany(() => Blog, (blog) => blog.writer)
blogs: Blog[];
}

View File

@@ -0,0 +1,5 @@
export enum LanguageEnum {
Farsi = "fa",
English = "en",
Arabic = "ar",
}

7
src/enums/phase.enum.ts Normal file
View File

@@ -0,0 +1,7 @@
export enum PhaseEnum {
BlogAboutData = "blogAboutData",
BlogFeaturedImageData = "blogFeaturedImageData",
BlogGalleryData = "blogGalleryData",
BlogDynamicData = "blogDynamicData",
BlogTranslationData = "blogTranslationData",
}

View File

@@ -0,0 +1,6 @@
export enum PortfolioCategoryEnum {
Network = "network",
Software = "software",
Marketing = "marketing",
Electronics = "electronics",
}

View File

@@ -0,0 +1,6 @@
export enum PortfolioPhaseEnum {
PortfolioAboutData = "portfolioAboutData",
PortfolioFeaturedImageData = "portfolioFeaturedImageData",
PortfolioGalleryData = "portfolioGalleryData",
PortfolioTranslationData = "portfolioTranslationData",
}

4
src/enums/role.enum.ts Normal file
View File

@@ -0,0 +1,4 @@
export enum RoleEnum {
Admin = "admin",
Tech = "technician",
}

View File

@@ -0,0 +1,27 @@
import { ExecutionContext, HttpStatus, Injectable } from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { AuthGuard } from "@nestjs/passport";
import { Observable } from "rxjs";
import { PUBLIC_ROUTE_KEY } from "src/decorators/public-route.decorator";
import { ApiError } from "src/utilities/api-error";
@Injectable()
export class JwtAuthCuard extends AuthGuard("jwt") {
constructor(private reflector: Reflector) {
super();
}
canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
const isPublic = this.reflector.getAllAndOverride<boolean>(PUBLIC_ROUTE_KEY, [context.getClass(), context.getHandler()]);
if (isPublic) return true;
return super.canActivate(context);
}
handleRequest<TUser = any>(err: any, user: any, info: any, context: ExecutionContext, status?: any): TUser {
if (err || !user) {
throw new ApiError("please login", HttpStatus.UNAUTHORIZED);
}
return user;
}
}

24
src/guards/roles.guard.ts Normal file
View File

@@ -0,0 +1,24 @@
import { CanActivate, ExecutionContext, HttpStatus, Injectable } from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { Observable } from "rxjs";
import { PUBLIC_ROUTE_KEY } from "src/decorators/public-route.decorator";
import { AVAILABLE_ROLES_KEY } from "src/decorators/roles.decorator";
import { ApiError } from "src/utilities/api-error";
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
async canActivate(context: ExecutionContext) {
const isPublic = this.reflector.getAllAndOverride<boolean>(PUBLIC_ROUTE_KEY, [context.getClass(), context.getHandler()]);
if (isPublic) return true;
const req = await context.switchToHttp().getRequest();
const availableRoles: string[] | undefined = this.reflector.getAllAndOverride<string[]>(AVAILABLE_ROLES_KEY, [
context.getClass(),
context.getHandler(),
]);
if (req.user && availableRoles && availableRoles.includes(req.user.role)) return true;
throw new ApiError("You Are not have Permission to do this", HttpStatus.FORBIDDEN);
}
}

21
src/helpers/generate.ts Normal file
View File

@@ -0,0 +1,21 @@
export class CustomGenerate {
static replacePreZeroInStringWith(string: string, replaceNumber: number): string {
if (string[0] === "0") {
return `${replaceNumber}${string.slice(1)}`;
}
return string;
}
static generateRandomDigitsCodeByLength(codeLength: number): string {
let code = "";
for (let i = 0; i < codeLength; i++) {
code += Math.floor(Math.random() * 10);
}
return this.replacePreZeroInStringWith(code, 1);
}
static generateExpireTimeByMinutes(minutes: number): Date {
const now = Date.now();
return new Date(now + minutes * 60 * 1000);
}
}

1
src/helpers/regex.ts Normal file
View File

@@ -0,0 +1 @@
export const emailRegexp: RegExp = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

15
src/helpers/types.ts Normal file
View File

@@ -0,0 +1,15 @@
import { LanguageEnum } from "src/enums/language.enum";
export interface BlogTranslationType {
title: string;
description: string;
editor: any[];
language: LanguageEnum;
}
export interface PortfolioTranslationType {
title: string;
description: string;
employer: string;
language: LanguageEnum;
}

41
src/main.ts Normal file
View File

@@ -0,0 +1,41 @@
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import { ValidationPipe } from "@nestjs/common";
import { GlobalExceptionFilter } from "./utilities/global-exception.filter";
import { CustomSwagger } from "./utilities/swagger";
import { NestExpressApplication } from "@nestjs/platform-express";
import { join } from "path";
const cookieParser = require("cookie-parser");
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
app.useStaticAssets(join(__dirname, "..", "uploads"), { prefix: "/uploads/" });
app.enableCors({
origin: [
"http://localhost:3000",
"http://localhost:5000",
"http://robinnetwork.ir",
"http://panel.robinnetwork.ir",
"http://api.robinnetwork.ir",
],
credentials: true,
});
app.use(cookieParser());
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
})
);
app.useGlobalFilters(new GlobalExceptionFilter());
CustomSwagger.initialize(app);
await app.listen(process.env.PORT ?? 4000);
}
bootstrap();

View File

@@ -0,0 +1,57 @@
import { RoleEnum } from "src/enums/role.enum";
import { MigrationInterface, QueryRunner, Table } from "typeorm";
export class UsersTable1760456584800 implements MigrationInterface {
name = "UsersTable1760456584800";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(
new Table({
name: "users",
columns: [
{
name: "id",
type: "varchar",
isPrimary: true,
},
{
name: "username",
type: "varchar",
isNullable: false,
},
{
name: "email",
type: "varchar",
isNullable: false,
},
{
name: "role",
type: "enum",
enum: Object.values(RoleEnum),
default: `'${RoleEnum.Tech}'`,
},
{
name: "createdAt",
type: "timestamp",
default: "now()",
},
{
name: "updatedAt",
type: "timestamp",
default: "now()",
onUpdate: "now()",
},
{
name: "deletedAt",
type: "timestamp",
isNullable: true,
},
],
})
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable("users");
}
}

View File

@@ -0,0 +1,70 @@
import { MigrationInterface, QueryRunner, Table } from "typeorm";
export class ProjectsTable1760456664246 implements MigrationInterface {
name = "ProjectsTable1760456664246";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(
new Table({
name: "projects",
columns: [
{
name: "id",
type: "varchar",
isPrimary: true,
},
{
name: "adminId",
type: "varchar",
isNullable: false,
},
{
name: "ownerFirstname",
type: "varchar",
isNullable: false,
},
{
name: "ownerLastname",
type: "varchar",
isNullable: false,
},
{
name: "ownerPhone",
type: "varchar",
isNullable: false,
},
{
name: "status",
type: "varchar",
isNullable: false,
},
{
name: "percentage",
type: "smallint",
isNullable: false,
},
{
name: "createdAt",
type: "timestamp",
default: "now()",
},
{
name: "updatedAt",
type: "timestamp",
default: "now()",
onUpdate: "now()",
},
{
name: "deletedAt",
type: "timestamp",
isNullable: true,
},
],
})
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable("projects");
}
}

View File

@@ -0,0 +1,21 @@
import { MigrationInterface, QueryRunner, TableForeignKey } from "typeorm";
export class UsersProjectsRelation1760457409653 implements MigrationInterface {
name = "UsersProjectsRelation1760457409653";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createForeignKey(
"projects",
new TableForeignKey({
columnNames: ["adminId"],
referencedTableName: "users",
referencedColumnNames: ["id"],
name: "FK_USERS_PROJECTS_ADMIN",
})
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropForeignKey("projects", "FK_USERS_PROJECTS_ADMIN");
}
}

View File

@@ -0,0 +1,80 @@
import { MigrationInterface, QueryRunner, Table } from "typeorm";
export class TasksTable1760458298453 implements MigrationInterface {
name = "TasksTable1760458298453";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(
new Table({
name: "tasks",
columns: [
{
name: "id",
type: "varchar",
isPrimary: true,
},
{
name: "creatorId",
type: "varchar",
isNullable: false,
},
{
name: "userId",
type: "varchar",
isNullable: false,
},
{
name: "projectId",
type: "varchar",
isNullable: false,
},
{
name: "title",
type: "varchar",
isNullable: false,
},
{
name: "desc",
type: "varchar",
isNullable: false,
},
{
name: "deadlineTime",
type: "timestamp",
isNullable: false,
},
{
name: "rejectReason",
type: "varchar",
isNullable: true,
},
{
name: "rejectDeadline",
type: "timestamp",
isNullable: true,
},
{
name: "createdAt",
type: "timestamp",
default: "now()",
},
{
name: "updatedAt",
type: "timestamp",
default: "now()",
onUpdate: "now()",
},
{
name: "deletedAt",
type: "timestamp",
isNullable: true,
},
],
})
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable("tasks");
}
}

View File

@@ -0,0 +1,34 @@
import { MigrationInterface, QueryRunner, TableForeignKey } from "typeorm";
export class TasksUsersProjectsRelation1760458629108 implements MigrationInterface {
name = "TasksUsersProjectsRelation1760458629108";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createForeignKeys("tasks", [
new TableForeignKey({
columnNames: ["creatorId"],
referencedTableName: "users",
referencedColumnNames: ["id"],
name: "FK_TASKS_USERS_CREATOR",
}),
new TableForeignKey({
columnNames: ["userId"],
referencedTableName: "users",
referencedColumnNames: ["id"],
name: "FK_TASKS_USERS_USER",
}),
new TableForeignKey({
columnNames: ["projectId"],
referencedTableName: "projects",
referencedColumnNames: ["id"],
name: "FK_TASKS_PROJECTS_PROJECT",
}),
]);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropForeignKey("tasks", "FK_TASKS_USERS_CREATOR");
await queryRunner.dropForeignKey("tasks", "FK_TASKS_USERS_USER");
await queryRunner.dropForeignKey("tasks", "FK_TASKS_PROJECTS_PROJECT");
}
}

View File

@@ -0,0 +1,13 @@
import { MigrationInterface, QueryRunner } from "typeorm";
export class TasksDescRename1760459670377 implements MigrationInterface {
name = "TasksDescRename1760459670377";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.renameColumn("tasks", "desc", "description");
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.renameColumn("tasks", "description", "desc");
}
}

View File

@@ -0,0 +1,39 @@
import { MigrationInterface, QueryRunner, Table } from "typeorm";
export class OtpsTable1760509369673 implements MigrationInterface {
name = "OtpsTable1760509369673";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(
new Table({
name: "otps",
columns: [
{
name: "id",
type: "varchar",
isPrimary: true,
},
{
name: "email",
type: "varchar",
isNullable: false,
},
{
name: "code",
type: "varchar",
isNullable: false,
},
{
name: "expireAt",
type: "timestamp",
isNullable: false,
},
],
})
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable("otps");
}
}

View File

@@ -0,0 +1,21 @@
import { MigrationInterface, QueryRunner, TableColumn } from "typeorm";
export class AddTitleToProjects1761541127347 implements MigrationInterface {
name = "AddTitleToProjects1761541127347";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.addColumn(
"projects",
new TableColumn({
name: "title",
type: "varchar",
isNullable: false,
isUnique: true,
})
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropColumn("proejcts", "title");
}
}

View File

@@ -0,0 +1,22 @@
import { MigrationInterface, QueryRunner, Table } from "typeorm";
export class BlogsTable1763398866781 implements MigrationInterface {
name = "BlogsTable1763398866781";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(
new Table({
name: "blogs",
columns: [
{ name: "id", type: "varchar", isPrimary: true },
{ name: "title", type: "varchar", isNullable: false },
{ name: "editor", type: "jsonb", isNullable: false },
],
})
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable("blogs");
}
}

View File

@@ -0,0 +1,18 @@
import { MigrationInterface, QueryRunner, TableColumn } from "typeorm";
export class AddFieldsBlogsTable1763399431842 implements MigrationInterface {
name = "AddFieldsBlogsTable1763399431842";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.addColumns("blogs", [
new TableColumn({ name: "writerId", type: "varchar", isNullable: false }),
new TableColumn({ name: "createdAt", type: "timestamp", default: "now()" }),
new TableColumn({ name: "updatedAt", type: "timestamp", default: "now()", onUpdate: "now()" }),
new TableColumn({ name: "deletedAt", type: "timestamp", isNullable: true }),
]);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropColumns("blogs", ["writerId", "createdAt", "updatedAt", "deletedAt"]);
}
}

View File

@@ -0,0 +1,20 @@
import { MigrationInterface, QueryRunner, TableForeignKey } from "typeorm";
export class AddRelationToBlogsTable1763399635628 implements MigrationInterface {
name = "AddRelationToBlogsTable1763399635628";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createForeignKey(
"blogs",
new TableForeignKey({
columnNames: ["writerId"],
referencedTableName: "users",
referencedColumnNames: ["id"],
})
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropForeignKey("blogs", "");
}
}

View File

@@ -0,0 +1,20 @@
import { MigrationInterface, QueryRunner, TableColumn } from "typeorm";
export class AddDescToBlogs1763400008204 implements MigrationInterface {
name = "AddDescToBlogs1763400008204";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.addColumn(
"blogs",
new TableColumn({
name: "description",
type: "varchar",
isNullable: false,
})
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropColumn("blogs", "description");
}
}

View File

@@ -0,0 +1,17 @@
import { MigrationInterface, QueryRunner, TableColumn } from "typeorm";
export class RemoveFieldsFromBlogs1763401913367 implements MigrationInterface {
name = "RemoveFieldsFromBlogs1763401913367";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropColumns("blogs", ["title", "description", "editor"]);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.addColumns("blogs", [
new TableColumn({ name: "title", type: "varchar", isNullable: false }),
new TableColumn({ name: "description", type: "varchar", isNullable: false }),
new TableColumn({ name: "editor", type: "jsonb", isNullable: false }),
]);
}
}

View File

@@ -0,0 +1,52 @@
import { LanguageEnum } from "src/enums/language.enum";
import { MigrationInterface, QueryRunner, Table } from "typeorm";
export class CreateBlogsTranslationTable1763402732483 implements MigrationInterface {
name = "CreateBlogsTranslationTable1763402732483";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(
new Table({
name: "blogs_translation",
columns: [
{
name: "id",
type: "varchar",
isPrimary: true,
},
{
name: "title",
type: "varchar",
isNullable: false,
},
{
name: "description",
type: "varchar",
isNullable: false,
},
{
name: "editor",
type: "jsonb",
isNullable: false,
},
{
name: "language",
type: "enum",
isNullable: false,
enum: Object.values(LanguageEnum),
default: `'${LanguageEnum.Farsi}'`,
},
{
name: "blogId",
type: "varchar",
isNullable: false,
},
],
})
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable("blogs_translation");
}
}

View File

@@ -0,0 +1,21 @@
import { MigrationInterface, QueryRunner, TableForeignKey } from "typeorm";
export class AddRelationToBlogsTranslation1763447596953 implements MigrationInterface {
name = "AddRelationToBlogsTranslation1763447596953";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createForeignKey(
"blogs_translation",
new TableForeignKey({
columnNames: ["blogId"],
referencedTableName: "blogs",
referencedColumnNames: ["id"],
name: "FK_BLOG_TRANSLATION_TO_BLOG",
})
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropForeignKey("blogs_translation", "FK_BLOG_TRANSLATION_TO_BLOG");
}
}

View File

@@ -0,0 +1,19 @@
import { MigrationInterface, QueryRunner, TableUnique } from "typeorm";
export class AddUniqueConstraintToBlogsTranslation1763447741924 implements MigrationInterface {
name = "AddUniqueConstraintToBlogsTranslation1763447741924";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createUniqueConstraint(
"blogs_translation",
new TableUnique({
name: "UQ_BLOGID_LANGUAGE",
columnNames: ["blogId", "language"],
})
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropUniqueConstraint("blogs_translation", "UQ_BLOGID_LANGUAGE");
}
}

View File

@@ -0,0 +1,39 @@
import { MigrationInterface, QueryRunner, TableColumn } from "typeorm";
export class RemoveNotNullFromBlogsTranslation1763476024503 implements MigrationInterface {
name = "RemoveNotNullFromBlogsTranslation1763476024503";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.changeColumns("blogs_translation", [
{
oldColumn: new TableColumn({ name: "title", type: "varchar", isNullable: false }),
newColumn: new TableColumn({ name: "title", type: "varchar", isNullable: true }),
},
{
oldColumn: new TableColumn({ name: "description", type: "varchar", isNullable: false }),
newColumn: new TableColumn({ name: "description", type: "varchar", isNullable: true }),
},
{
oldColumn: new TableColumn({ name: "editor", type: "jsonb", isNullable: false }),
newColumn: new TableColumn({ name: "editor", type: "jsonb", isNullable: true }),
},
]);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.changeColumns("blogs_translation", [
{
oldColumn: new TableColumn({ name: "title", type: "varchar", isNullable: true }),
newColumn: new TableColumn({ name: "title", type: "varchar", isNullable: false }),
},
{
oldColumn: new TableColumn({ name: "description", type: "varchar", isNullable: true }),
newColumn: new TableColumn({ name: "description", type: "varchar", isNullable: false }),
},
{
oldColumn: new TableColumn({ name: "editor", type: "jsonb", isNullable: true }),
newColumn: new TableColumn({ name: "editor", type: "jsonb", isNullable: false }),
},
]);
}
}

View File

@@ -0,0 +1,17 @@
import { MigrationInterface, QueryRunner, TableColumn } from "typeorm";
export class AddFieldsToBlogs1763476513917 implements MigrationInterface {
name = "AddFieldsToBlogs1763476513917";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.addColumns("blogs", [
new TableColumn({ name: "featuredImage", type: "varchar", isNullable: true }),
new TableColumn({ name: "gallery", type: "jsonb", isNullable: true, default: "'[]'::jsonb" }),
new TableColumn({ name: "publishedAt", type: "timestamp", isNullable: true, default: null }),
]);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropColumns("blogs", ["featuredImage", "gallery", "publishedAt"]);
}
}

View File

@@ -0,0 +1,13 @@
import { MigrationInterface, QueryRunner, TableColumn } from "typeorm";
export class AddHrefToBlogs1763524567094 implements MigrationInterface {
name = "AddHrefToBlogs1763524567094";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.addColumn("blogs", new TableColumn({ name: "href", type: "varchar", isNullable: false }));
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropColumn("blogs", "href");
}
}

View File

@@ -0,0 +1,22 @@
import { PhaseEnum } from "src/enums/phase.enum";
import { MigrationInterface, QueryRunner, TableColumn } from "typeorm";
export class AddPhaseToBlogs1764475888409 implements MigrationInterface {
name = "AddPhaseToBlogs1764475888409";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.addColumn(
"blogs",
new TableColumn({
name: "phase",
type: "enum",
enum: Object.values(PhaseEnum),
default: `'${PhaseEnum.BlogAboutData}'`,
})
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropColumn("blogs", "phase");
}
}

View File

@@ -0,0 +1,31 @@
import { PortfolioCategoryEnum } from "src/enums/portfolio-category.enum";
import { PortfolioPhaseEnum } from "src/enums/portfolio-phase.enum";
import { MigrationInterface, QueryRunner, Table } from "typeorm";
export class CreatePortfoliosTable1764920289930 implements MigrationInterface {
name = "CreatePortfoliosTable1764920289930";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(
new Table({
name: "portfolios",
columns: [
{ name: "id", type: "varchar", isPrimary: true },
{ name: "externalLink", type: "varchar", isNullable: true },
{ name: "featuredImage", type: "varchar", isNullable: true },
{ name: "gallery", type: "jsonb", default: "'[]'::jsonb" },
{ name: "href", type: "varchar", isNullable: false },
{ name: "category", type: "enum", enum: Object.values(PortfolioCategoryEnum), default: `'${PortfolioCategoryEnum.Network}'` },
{ name: "phase", type: "enum", enum: Object.values(PortfolioPhaseEnum), default: `'${PortfolioPhaseEnum.PortfolioAboutData}'` },
{ name: "createdAt", type: "timestamp", default: "now()" },
{ name: "updatedAt", type: "timestamp", default: "now()", onUpdate: "now()" },
{ name: "deletedAt", type: "timestamp", isNullable: true },
],
})
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable("portfolios");
}
}

View File

@@ -0,0 +1,30 @@
import { LanguageEnum } from "src/enums/language.enum";
import { MigrationInterface, QueryRunner, Table, TableForeignKey } from "typeorm";
export class CreatePortfoliosTranslationTable1764920694090 implements MigrationInterface {
name = "CreatePortfoliosTranslationTable1764920694090";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(
new Table({
name: "portfolios_translation",
columns: [
{ name: "id", type: "varchar", isPrimary: true },
{ name: "title", type: "varchar", isNullable: true },
{ name: "description", type: "varchar", isNullable: true },
{ name: "employer", type: "varchar", isNullable: true },
{ name: "language", type: "enum", enum: Object.values(LanguageEnum), default: `'${LanguageEnum.Farsi}'` },
{ name: "portfolioId", type: "varchar", isNullable: false },
],
})
);
await queryRunner.createForeignKey(
"portfolios_translation",
new TableForeignKey({ columnNames: ["portfolioId"], referencedColumnNames: ["id"], referencedTableName: "portfolios" })
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable("portfolios_translation");
}
}

View File

@@ -0,0 +1,20 @@
import { MigrationInterface, QueryRunner, TableColumn } from "typeorm";
export class AddPublishedAtToPortfolios1764921703181 implements MigrationInterface {
name = "AddPublishedAtToPortfolios1764921703181";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.addColumn(
"portfolios",
new TableColumn({
name: "publishedAt",
type: "timestamp",
isNullable: true,
})
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropColumn("portfolios", "publishedAt");
}
}

View File

@@ -0,0 +1,24 @@
import { MigrationInterface, QueryRunner, Table } from "typeorm";
export class CreateContactsTable1764940518537 implements MigrationInterface {
name = "CreateContactsTable1764940518537";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.createTable(
new Table({
name: "contacts",
columns: [
{ name: "id", type: "varchar", isPrimary: true },
{ name: "fullName", type: "varchar", isNullable: false },
{ name: "email", type: "varchar", isNullable: false },
{ name: "text", type: "varchar", isNullable: false },
{ name: "ip", type: "varchar", isNullable: true },
],
})
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable("contacts");
}
}

View File

@@ -0,0 +1,65 @@
import { Body, Controller, Get, HttpStatus, Post, Req, Res } from "@nestjs/common";
import { ApiOperation, ApiTags } from "@nestjs/swagger";
import { AuthService } from "./auth.service";
import { MailService } from "../mails/mails.service";
import type { Response } from "express";
import { SendCodeDto } from "src/dtos/auth/send-code.dto";
import { CustomResponses } from "src/utilities/responses";
import { CustomGenerate } from "src/helpers/generate";
import { PublicRoute } from "src/decorators/public-route.decorator";
import { LoginDto } from "src/dtos/auth/login.dto";
import { Roles } from "src/decorators/roles.decorator";
import { RoleEnum } from "src/enums/role.enum";
@ApiTags("Authentication Management")
@Controller("auth")
export class AuthController {
constructor(
private readonly authService: AuthService,
private readonly mailService: MailService
) {}
@ApiOperation({ summary: "Send Two-Factor Verification Code for Email" })
@PublicRoute()
@Post("send-code")
async SendVerificationCode(@Body() sendCodeDto: SendCodeDto, @Res() res: Response): Promise<void> {
const user = await this.authService.throwIfUserDontExistsByIdentifier(sendCodeDto);
const otp = await this.authService.createOtp(user.email, CustomGenerate.generateRandomDigitsCodeByLength(5));
CustomResponses.successResponse(res, "Code has been Sent to your Email", HttpStatus.CREATED);
this.mailService.sendVerifyCode(user.email, otp.code, user.username).catch(null);
}
@ApiOperation({ summary: "check otp and Log in" })
@PublicRoute()
@Post("login")
async loginUser(@Body() loginDto: LoginDto, @Res() res: Response): Promise<Response> {
const { id, username, email } = await this.authService.isCodeCorrectAndHasTime(loginDto);
await this.authService.setJwtToken(res, { id, username });
await this.authService.deleteOtpsByEmail(email);
return CustomResponses.successResponse(res, "you have been logged in successfully", HttpStatus.OK);
}
@ApiOperation({ summary: "logout" })
@Roles(RoleEnum.Admin, RoleEnum.Tech)
@Post("logout")
async logoutUser(@Res() res: Response): Promise<Response> {
res.clearCookie("token");
return CustomResponses.successResponse(res, "you have been logged out successfully", HttpStatus.OK);
}
@ApiOperation({ summary: "get your information" })
@Roles(RoleEnum.Admin, RoleEnum.Tech)
@Get("me")
async getMe(@Req() req: any, @Res() res: Response): Promise<Response> {
const me = await this.authService.getMe(req.user.id);
return CustomResponses.successResponse(res, "", HttpStatus.OK, me);
}
@ApiOperation({ summary: "is user admin" })
@Roles(RoleEnum.Admin)
@Get("admin")
isUserAdmin(@Res() res: Response): Response {
return CustomResponses.successResponse(res, "", HttpStatus.OK);
}
}

View File

@@ -0,0 +1,31 @@
import { Module } from "@nestjs/common";
import { MailModule } from "../mails/mails.module";
import { AuthService } from "./auth.service";
import { UsersModule } from "../users/users.module";
import { TypeOrmModule } from "@nestjs/typeorm";
import { Otp } from "src/entities/otps.entity";
import { AuthController } from "./auth.controller";
import { PassportModule } from "@nestjs/passport";
import { JwtModule } from "@nestjs/jwt";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { JwtStrategy } from "src/utilities/jwt";
@Module({
imports: [
MailModule,
UsersModule,
TypeOrmModule.forFeature([Otp]),
PassportModule.register({ defaultStrategy: "jwt" }),
JwtModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
secret: configService.get<string>("JWT_SECRET"),
signOptions: { expiresIn: configService.get<string>("JWT_EXPIRATION") as any },
}),
}),
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy],
})
export class AuthModule {}

View File

@@ -0,0 +1,69 @@
import { HttpStatus, Injectable } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { InjectRepository } from "@nestjs/typeorm";
import type { Response } from "express";
import { Otp } from "src/entities/otps.entity";
import { CustomGenerate } from "src/helpers/generate";
import { JwtPayload } from "src/utilities/jwt";
import { CustomUuid } from "src/utilities/uuid";
import { Repository } from "typeorm";
import { UsersService } from "../users/users.service";
import { SendCodeDto } from "src/dtos/auth/send-code.dto";
import { ApiError } from "src/utilities/api-error";
import { User } from "src/entities/users.entity";
import { LoginDto } from "src/dtos/auth/login.dto";
@Injectable()
export class AuthService {
constructor(
@InjectRepository(Otp)
private otpsRepository: Repository<Otp>,
private readonly jwtService: JwtService,
private readonly usersService: UsersService
) {}
async getMe(id: string): Promise<User | null> {
return await this.usersService.getMeById(id);
}
async createOtp(email: string, code: string): Promise<Otp> {
const otp = this.otpsRepository.create({
id: CustomUuid.generateUuid(),
email,
code,
expireAt: CustomGenerate.generateExpireTimeByMinutes(+(process.env.OTP_EXPIRE_TIME_MINUTES || "5")),
});
return await this.otpsRepository.save(otp);
}
async deleteOtpsByEmail(email: string) {
await this.otpsRepository.delete({ email });
}
async setJwtToken(res: Response, payload: JwtPayload) {
const token = await this.jwtService.signAsync(payload);
res.cookie("token", token, {
httpOnly: true,
maxAge: +(process.env.JWT_EXPIRATION_IN_HOUR || "240") * 60 * 60 * 1000,
secure: process.env.NODE_ENV === "production",
sameSite: "strict",
});
}
async throwIfUserDontExistsByIdentifier(sendCodeDto: SendCodeDto): Promise<User> {
const isUserExists = await this.usersService.findUserByIdentifier(sendCodeDto.identifier);
if (!isUserExists) throw new ApiError("Username or Email is not Valid", HttpStatus.NOT_FOUND);
return isUserExists;
}
async isCodeCorrectAndHasTime(loginDto: LoginDto) {
const { code, identifier } = loginDto;
const user = await this.throwIfUserDontExistsByIdentifier({ identifier });
const isCodeCorrect = await this.otpsRepository.findOne({ where: { email: user.email, code } });
if (!isCodeCorrect) throw new ApiError("code is not correct", HttpStatus.UNPROCESSABLE_ENTITY);
if (isCodeCorrect.expireAt.getTime() < Date.now()) {
throw new ApiError("the code has been expired", HttpStatus.UNPROCESSABLE_ENTITY);
}
return { id: user.id, username: user.username, email: user.email };
}
}

View File

@@ -0,0 +1,228 @@
import { Body, Controller, Delete, Get, HttpStatus, Param, Patch, Post, Req, Res } from "@nestjs/common";
import { BlogsService } from "./blogs.service";
import { RoleEnum } from "src/enums/role.enum";
import { Roles } from "src/decorators/roles.decorator";
import { ApiOperation, ApiTags } from "@nestjs/swagger";
import type { Response } from "express";
import { InsertAboutFieldsDto } from "src/dtos/blogs/insert-about-fields.dto";
import { CustomResponses } from "src/utilities/responses";
import { IsUuidPipe } from "src/pipes/public/is-uuid.pipe";
import { UpdateAboutFieldsDto } from "src/dtos/blogs/update-about-fields.dto";
import { UpdateFeaturedImageDto } from "src/dtos/blogs/update-featured-image.dto";
import { ApiError } from "src/utilities/api-error";
import { UpdateGalleryDto } from "src/dtos/blogs/update-gallery.dto";
import { UpdateDynamicDataDto } from "src/dtos/blogs/update-dynamic-data.dto";
import { PublicRoute } from "src/decorators/public-route.decorator";
import { UpdateTranslationsDto } from "src/dtos/blogs/update-translations.dto";
import { LanguageEnum } from "src/enums/language.enum";
import { IsLanguageEnumPipe } from "src/pipes/public/is-language.pipe";
import { IsHrefPipe } from "src/pipes/public/is-href.pipe";
@ApiTags("Manage Blogs")
@Controller("blogs")
export class BlogsController {
constructor(private readonly blogsService: BlogsService) {}
@ApiOperation({ summary: "get all blogs" })
@Roles(RoleEnum.Admin)
@Get()
async getAllBlogs(@Res() res: Response) {
const blogs = await this.blogsService.getAllBlogsTitleAndPublished();
return CustomResponses.successResponse(res, "", HttpStatus.OK, blogs);
}
@ApiOperation({ summary: "insert the about data" })
@Roles(RoleEnum.Admin)
@Post("about")
async insertAboutFields(@Req() req: any, @Res() res: Response, @Body() insertAboutFieldsDto: InsertAboutFieldsDto): Promise<Response> {
const id = await this.blogsService.insertAboutFields(insertAboutFieldsDto, req.user.id);
return CustomResponses.successResponse(res, "", HttpStatus.CREATED, id);
}
@ApiOperation({ summary: "get the current phase" })
@Roles(RoleEnum.Admin)
@Get("phase/:id")
async getCurrentPhase(@Res() res: Response, @Param("id", new IsUuidPipe("blog not found")) id: string): Promise<Response> {
const phase = await this.blogsService.getPhase(id);
return CustomResponses.successResponse(res, "", HttpStatus.OK, phase);
}
@ApiOperation({ summary: "get the about fields" })
@Roles(RoleEnum.Admin)
@Get("about/:id")
async getAboutFields(@Res() res: Response, @Param("id", new IsUuidPipe("blog not found")) id: string): Promise<Response> {
if (!(await this.blogsService.isBlogExistsById(id))) throw new ApiError("blog not found", HttpStatus.NOT_FOUND);
const fields = await this.blogsService.fetchAboutFieldsById(id);
return CustomResponses.successResponse(res, "", HttpStatus.OK, fields);
}
@ApiOperation({ summary: "update the about data" })
@Roles(RoleEnum.Admin)
@Patch("about/:id")
async updateAboutFields(
@Res() res: Response,
@Body() updateAboutFieldsDto: UpdateAboutFieldsDto,
@Param("id", new IsUuidPipe("blog not found")) id: string
): Promise<Response> {
await this.blogsService.updateAboutFields(id, updateAboutFieldsDto);
return CustomResponses.successResponse(res, "", HttpStatus.OK);
}
@ApiOperation({ summary: "get the featured image" })
@Roles(RoleEnum.Admin)
@Get("feature/:id")
async getFeaturedImage(@Res() res: Response, @Param("id", new IsUuidPipe("blog not found")) id: string): Promise<Response> {
if (!(await this.blogsService.isBlogExistsById(id))) throw new ApiError("blog not found", HttpStatus.NOT_FOUND);
const image = await this.blogsService.fetchFeaturedImageById(id);
return CustomResponses.successResponse(res, "", HttpStatus.OK, image);
}
@ApiOperation({ summary: "update the featured image" })
@Roles(RoleEnum.Admin)
@Patch("feature/:id")
async updateFeaturedImage(
@Res() res: Response,
@Body() updateFeaturedImageDto: UpdateFeaturedImageDto,
@Param("id", new IsUuidPipe("blog not found")) id: string
): Promise<Response> {
if (!(await this.blogsService.isBlogExistsById(id))) throw new ApiError("blog not found", HttpStatus.NOT_FOUND);
await this.blogsService.updateFeaturedImageById(id, updateFeaturedImageDto.image);
return CustomResponses.successResponse(res, "", HttpStatus.OK);
}
@ApiOperation({ summary: "get the gallery images" })
@Roles(RoleEnum.Admin)
@Get("gallery/:id")
async getGallery(@Res() res: Response, @Param("id", new IsUuidPipe("blog not found")) id: string): Promise<Response> {
if (!(await this.blogsService.isBlogExistsById(id))) throw new ApiError("blog not found", HttpStatus.NOT_FOUND);
const gallery = await this.blogsService.fetchGalleryById(id);
return CustomResponses.successResponse(res, "", HttpStatus.OK, gallery);
}
@ApiOperation({ summary: "update the gallery" })
@Roles(RoleEnum.Admin)
@Patch("gallery/:id")
async updateGallery(
@Res() res: Response,
@Body() updateGalleryDto: UpdateGalleryDto,
@Param("id", new IsUuidPipe("blog not found")) id: string
): Promise<Response> {
if (!(await this.blogsService.isBlogExistsById(id))) throw new ApiError("blog not found", HttpStatus.NOT_FOUND);
await this.blogsService.updateGalleryById(id, updateGalleryDto.gallery);
return CustomResponses.successResponse(res, "", HttpStatus.OK);
}
@ApiOperation({ summary: "get the dynamic data" })
@Roles(RoleEnum.Admin)
@Get("dynamic/:id")
async getDynamicData(@Res() res: Response, @Param("id", new IsUuidPipe("blog not found")) id: string): Promise<Response> {
if (!(await this.blogsService.isBlogExistsById(id))) throw new ApiError("blog not found", HttpStatus.NOT_FOUND);
const editor = await this.blogsService.fetchDynamicDataById(id);
return CustomResponses.successResponse(res, "", HttpStatus.OK, editor);
}
@ApiOperation({ summary: "update the dynamic data" })
@Roles(RoleEnum.Admin)
@Patch("dynamic/:id")
async updateDynamicData(
@Res() res: Response,
@Body() updateDynamicDataDto: UpdateDynamicDataDto,
@Param("id", new IsUuidPipe("blog not found")) id: string
): Promise<Response> {
if (!(await this.blogsService.isBlogExistsById(id))) throw new ApiError("blog not found", HttpStatus.NOT_FOUND);
await this.blogsService.updateDynamicDataById(id, updateDynamicDataDto);
return CustomResponses.successResponse(res, "", HttpStatus.OK);
}
@ApiOperation({ summary: "get the translation data" })
@Roles(RoleEnum.Admin)
@Get("translation/:id")
async getTranslationData(@Res() res: Response, @Param("id", new IsUuidPipe("blog not found")) id: string): Promise<Response> {
if (!(await this.blogsService.isBlogExistsById(id))) throw new ApiError("blog not found", HttpStatus.NOT_FOUND);
const translations = await this.blogsService.fetchTranslationDataById(id);
return CustomResponses.successResponse(res, "", HttpStatus.OK, translations);
}
@ApiOperation({ summary: "update the translation data" })
@Roles(RoleEnum.Admin)
@Patch("translation/:id")
async updateTranslations(
@Res() res: Response,
@Body() updateTranslationsDto: UpdateTranslationsDto,
@Param("id", new IsUuidPipe("blog not found")) id: string
): Promise<Response> {
if (!(await this.blogsService.isBlogExistsById(id))) throw new ApiError("blog not found", HttpStatus.NOT_FOUND);
await this.blogsService.updateTranslationsDataById(id, updateTranslationsDto);
return CustomResponses.successResponse(res, "Translation has been saved successfully", HttpStatus.OK);
}
@ApiOperation({ summary: "publish the blog" })
@Roles(RoleEnum.Admin)
@Patch("publish/:id")
async publishBlog(@Res() res: Response, @Param("id", new IsUuidPipe("blog not found")) id: string): Promise<Response> {
if (!(await this.blogsService.isBlogExistsById(id))) throw new ApiError("blog not found", HttpStatus.NOT_FOUND);
await this.blogsService.publishBlogById(id);
return CustomResponses.successResponse(res, "", HttpStatus.OK);
}
@ApiOperation({ summary: "archive the blog" })
@Roles(RoleEnum.Admin)
@Patch("archive/:id")
async archiveBlog(@Res() res: Response, @Param("id", new IsUuidPipe("blog not found")) id: string): Promise<Response> {
if (!(await this.blogsService.isBlogExistsById(id))) throw new ApiError("blog not found", HttpStatus.NOT_FOUND);
await this.blogsService.archiveBlogById(id);
return CustomResponses.successResponse(res, "blog has been archived successfully", HttpStatus.OK, id);
}
@ApiOperation({ summary: "unarchive the blog" })
@Roles(RoleEnum.Admin)
@Patch("unarchive/:id")
async unarchiveBlog(@Res() res: Response, @Param("id", new IsUuidPipe("blog not found")) id: string): Promise<Response> {
if (!(await this.blogsService.isBlogExistsIncludeSoftDeletedById(id))) throw new ApiError("blog not found", HttpStatus.NOT_FOUND);
await this.blogsService.unarchiveBlogById(id);
return CustomResponses.successResponse(res, "blog has been restored successfully", HttpStatus.OK, id);
}
@ApiOperation({ summary: "delete drafted blog" })
@Roles(RoleEnum.Admin)
@Delete(":id")
async deleteDraftedBlog(@Res() res: Response, @Param("id", new IsUuidPipe("blog not found")) id: string): Promise<Response> {
if (!(await this.blogsService.isBlogExistsById(id))) throw new ApiError("blog not found", HttpStatus.NOT_FOUND);
await this.blogsService.deleteDraftedBlogById(id);
return CustomResponses.successResponse(res, "blog has been deleted successfully", HttpStatus.OK, id);
}
@ApiOperation({ summary: "fetch latest blog by language" })
@PublicRoute()
@Get("latest/:language")
async getLatestBlogs(
@Res() res: Response,
@Param("language", new IsLanguageEnumPipe("language not found")) language: LanguageEnum
): Promise<Response> {
const blogs = await this.blogsService.fetchLastBlogsByLanguage(language);
return CustomResponses.successResponse(res, "", HttpStatus.OK, blogs);
}
@ApiOperation({ summary: "fetch latest blog by language" })
@PublicRoute()
@Get("all/:language")
async getNewestBlogs(
@Res() res: Response,
@Param("language", new IsLanguageEnumPipe("language not found")) language: LanguageEnum
): Promise<Response> {
const blogs = await this.blogsService.fetchNewestBlogsByLanguage(language);
return CustomResponses.successResponse(res, "", HttpStatus.OK, blogs);
}
@ApiOperation({ summary: "fetch single blog by language and href" })
@PublicRoute()
@Get("single/:href/:language")
async getSingleBlog(
@Res() res: Response,
@Param("language", new IsLanguageEnumPipe("language not found")) language: LanguageEnum,
@Param("href", new IsHrefPipe("blog not found")) href: string
): Promise<Response> {
const blog = await this.blogsService.fetchSingleBlogByLanguageAndHref(language, href);
return CustomResponses.successResponse(res, "", HttpStatus.OK, blog);
}
}

View File

@@ -0,0 +1,13 @@
import { Module } from "@nestjs/common";
import { BlogsController } from "./blogs.controller";
import { BlogsService } from "./blogs.service";
import { TypeOrmModule } from "@nestjs/typeorm";
import { Blog } from "src/entities/blogs.entity";
import { BlogTranslation } from "src/entities/blogs_translation.entity";
@Module({
imports: [TypeOrmModule.forFeature([Blog, BlogTranslation])],
controllers: [BlogsController],
providers: [BlogsService],
})
export class BlogsModule {}

View File

@@ -0,0 +1,323 @@
import { HttpStatus, Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { InsertAboutFieldsDto } from "src/dtos/blogs/insert-about-fields.dto";
import { UpdateAboutFieldsDto } from "src/dtos/blogs/update-about-fields.dto";
import { UpdateDynamicDataDto } from "src/dtos/blogs/update-dynamic-data.dto";
import { UpdateTranslationsDto } from "src/dtos/blogs/update-translations.dto";
import { Blog } from "src/entities/blogs.entity";
import { BlogTranslation } from "src/entities/blogs_translation.entity";
import { LanguageEnum } from "src/enums/language.enum";
import { PhaseEnum } from "src/enums/phase.enum";
import { BlogTranslationType } from "src/helpers/types";
import { ApiError } from "src/utilities/api-error";
import { CustomUuid } from "src/utilities/uuid";
import { IsNull, Not, Repository } from "typeorm";
@Injectable()
export class BlogsService {
constructor(
@InjectRepository(Blog)
private readonly blogsRepository: Repository<Blog>,
@InjectRepository(BlogTranslation)
private readonly blogsTranslationRepository: Repository<BlogTranslation>
) {}
async isBlogExistsById(id: string): Promise<boolean> {
return await this.blogsRepository.exists({ where: { id } });
}
async isBlogExistsIncludeSoftDeletedById(id: string): Promise<boolean> {
const blog = await this.blogsRepository.createQueryBuilder("blog").withDeleted().where("blog.id = :id", { id }).getRawOne();
console.log(blog, !!blog);
return !!blog;
}
async getPhase(id: string): Promise<string | undefined> {
const blog = await this.blogsRepository.findOne({ where: { id }, select: ["phase"] });
return blog?.phase;
}
async getAllBlogsTitleAndPublished(): Promise<Blog[]> {
const blogs = await this.blogsRepository
.createQueryBuilder("blog")
.withDeleted()
.leftJoin("blog.translations", "t", "t.language = :lang", {
lang: LanguageEnum.Farsi,
})
.select("blog.id", "id")
.addSelect("blog.href", "href")
.addSelect("t.title", "title")
.addSelect(
`CASE
WHEN blog.publishedAt IS NULL THEN false
ELSE true
END`,
"isPublished"
)
.addSelect(
`CASE
WHEN blog.deletedAt IS NULL THEN false
ELSE true
END`,
"isArchived"
)
.getRawMany();
return blogs;
}
async isHrefUnique(href: string): Promise<boolean> {
const isAlreadyTaken = await this.blogsRepository.exists({ where: { href } });
return !isAlreadyTaken;
}
async isHrefUniqueForPatchById(id: string, href: string) {
const isAlreadyTaken = await this.blogsRepository.exists({ where: { href, id: Not(id) } });
return !isAlreadyTaken;
}
async insertAboutFields(insertAboutFieldsDto: InsertAboutFieldsDto, writerId: string): Promise<string> {
if (!(await this.isHrefUnique(insertAboutFieldsDto.href))) throw new ApiError("this short-link is already taken", 422);
const { title, description, href } = insertAboutFieldsDto;
const newBlog = this.blogsRepository.create({
id: CustomUuid.generateUuid(),
href,
writerId,
phase: PhaseEnum.BlogAboutData,
});
await this.blogsRepository.save(newBlog);
const newBlogTranslation = this.blogsTranslationRepository.create({
id: CustomUuid.generateUuid(),
title,
description,
language: LanguageEnum.Farsi,
blogId: newBlog.id,
});
await this.blogsTranslationRepository.save(newBlogTranslation);
return newBlog.id;
}
async updateAboutFields(id: string, updateAboutFieldsDto: UpdateAboutFieldsDto) {
if (!(await this.isHrefUniqueForPatchById(id, updateAboutFieldsDto.href))) return new ApiError("this short-link is already taken", 422);
const { title, description, href } = updateAboutFieldsDto;
await this.blogsRepository.update({ id }, { href });
await this.blogsTranslationRepository.update({ blogId: id, language: LanguageEnum.Farsi }, { title, description });
}
async fetchAboutFieldsById(id: string): Promise<Object | null> {
const fields = await this.blogsRepository
.createQueryBuilder("blog")
.leftJoin("blog.translations", "t", "t.language = :lang", {
lang: LanguageEnum.Farsi,
})
.select("blog.href", "href")
.addSelect("t.title", "title")
.addSelect("t.description", "description")
.where("blog.id = :id", { id })
.getRawOne();
return fields;
}
async updateFeaturedImageById(id: string, imageUrl: string): Promise<void> {
const currentPhase = await this.getPhase(id);
await this.blogsRepository.update(
{ id },
{
featuredImage: imageUrl,
phase: currentPhase === PhaseEnum.BlogAboutData ? PhaseEnum.BlogFeaturedImageData : currentPhase,
}
);
}
async fetchFeaturedImageById(id: string): Promise<string | null> {
const blog = await this.blogsRepository.findOne({ where: { id }, select: ["featuredImage"] });
return blog?.featuredImage ?? null;
}
async updateGalleryById(id: string, gallery: string[]): Promise<void> {
const currentPhase = await this.getPhase(id);
await this.blogsRepository.update(
{ id },
{
gallery,
phase: currentPhase === PhaseEnum.BlogFeaturedImageData ? PhaseEnum.BlogGalleryData : currentPhase,
}
);
}
async fetchGalleryById(id: string): Promise<string[] | null> {
const blog = await this.blogsRepository.findOne({ where: { id }, select: ["gallery"] });
return blog?.gallery ?? null;
}
async createTranslationByIdAndLanguage(id: string, language: LanguageEnum, data: { title: string; description: string; editor: any[] }) {
const newBlogTranslation = this.blogsTranslationRepository.create({
id: CustomUuid.generateUuid(),
title: data?.title,
description: data?.description,
editor: data.editor,
language,
blogId: id,
});
await this.blogsTranslationRepository.save(newBlogTranslation);
}
async createOrUpdateOtherTranslationsById(id: string, updateDynamicDataDto: UpdateDynamicDataDto) {
const faTranslation = await this.blogsTranslationRepository.findOne({
where: { blogId: id, language: LanguageEnum.Farsi },
select: ["title", "description"],
});
if (!faTranslation) return;
const [isArTranslationExists, isEnTranslationExists] = await Promise.all([
this.blogsTranslationRepository.findOne({ where: { blogId: id, language: LanguageEnum.Arabic } }),
this.blogsTranslationRepository.findOne({ where: { blogId: id, language: LanguageEnum.Arabic } }),
]);
if (isArTranslationExists) {
await this.updateTranslationByIdAndLanguage(id, LanguageEnum.Arabic, {
title: isArTranslationExists.title,
description: isArTranslationExists.description,
editor: updateDynamicDataDto.editor,
});
} else {
await this.createTranslationByIdAndLanguage(id, LanguageEnum.Arabic, {
title: faTranslation.title,
description: faTranslation.description,
editor: updateDynamicDataDto.editor,
});
}
if (isEnTranslationExists) {
await this.updateTranslationByIdAndLanguage(id, LanguageEnum.English, {
title: isEnTranslationExists.title,
description: isEnTranslationExists.description,
editor: updateDynamicDataDto.editor,
});
} else {
await this.createTranslationByIdAndLanguage(id, LanguageEnum.English, {
title: faTranslation.title,
description: faTranslation.description,
editor: updateDynamicDataDto.editor,
});
}
}
async updateDynamicDataById(id: string, updateDynamicDataDto: UpdateDynamicDataDto): Promise<void> {
const currentPhase = await this.getPhase(id);
const blog = await this.blogsTranslationRepository.findOne({ where: { blogId: id, language: LanguageEnum.Farsi }, select: ["editor"] });
await this.blogsTranslationRepository.update({ blogId: id, language: LanguageEnum.Farsi }, { editor: updateDynamicDataDto.editor });
await this.blogsRepository.update(
{ id },
{ phase: currentPhase === PhaseEnum.BlogGalleryData ? PhaseEnum.BlogDynamicData : currentPhase }
);
if (blog?.editor) {
const plainBlogEditor = blog.editor.map((b: any) => ({ type: b.type, sort: b.sort, content: b.content }));
const plainUpdateEditor = updateDynamicDataDto.editor.map((b) => ({ type: b.type, sort: b.sort, content: b.content }));
if (JSON.stringify(plainBlogEditor) !== JSON.stringify(plainUpdateEditor)) {
await this.createOrUpdateOtherTranslationsById(id, updateDynamicDataDto);
} else return;
} else {
await this.createOrUpdateOtherTranslationsById(id, updateDynamicDataDto);
}
}
async fetchDynamicDataById(id: string): Promise<any[] | null> {
const blog = await this.blogsTranslationRepository.findOne({ where: { blogId: id, language: LanguageEnum.Farsi }, select: ["editor"] });
return blog?.editor ?? null;
}
async fetchTranslationDataById(id: string): Promise<BlogTranslationType[]> {
const translations = await this.blogsTranslationRepository
.createQueryBuilder("translation")
.select("translation.title", "title")
.addSelect("translation.description", "description")
.addSelect("translation.editor", "editor")
.addSelect("translation.language", "language")
.where("translation.blogId = :blogId", { blogId: id })
.getRawMany();
return translations;
}
async updateTranslationByIdAndLanguage(id: string, language: LanguageEnum, data: { title: string; description: string; editor: any[] }) {
const { description, editor, title } = data;
await this.blogsTranslationRepository.update({ blogId: id, language }, { title, description, editor });
}
async updateTranslationsDataById(id: string, updateTranslationsDto: UpdateTranslationsDto) {
const { en, ar } = updateTranslationsDto;
await this.updateTranslationByIdAndLanguage(id, LanguageEnum.English, en);
await this.updateTranslationByIdAndLanguage(id, LanguageEnum.Arabic, ar);
}
async publishBlogById(id: string) {
if (await this.isBlogPublishedById(id)) return;
await this.blogsRepository.update({ id }, { publishedAt: () => "NOW()" });
}
async archiveBlogById(id: string): Promise<void> {
await this.blogsRepository.softDelete({ id });
}
async unarchiveBlogById(id: string): Promise<void> {
await this.blogsRepository.restore({ id });
}
async isBlogPublishedById(id: string): Promise<boolean> {
return await this.blogsRepository.exists({ where: { id, publishedAt: Not(IsNull()) } });
}
async deleteDraftedBlogById(id: string): Promise<void> {
if (await this.isBlogPublishedById(id)) {
throw new ApiError("this blog cannot be deleted because it published", HttpStatus.FORBIDDEN);
}
await this.blogsTranslationRepository.delete({ blogId: id });
await this.blogsRepository.delete({ id });
}
async fetchLastBlogsByLanguage(language: LanguageEnum): Promise<Blog[]> {
const blogs = await this.blogsRepository
.createQueryBuilder("blog")
.select(["blog.id", "blog.featuredImage", "blog.gallery", "blog.href", "blog.publishedAt"])
.leftJoinAndSelect("blog.translations", "translation", "translation.language = :language", { language })
.where("blog.publishedAt IS NOT NULL")
.orderBy("blog.publishedAt", "DESC")
.limit(3)
.getMany();
return blogs;
}
async fetchNewestBlogsByLanguage(language: LanguageEnum): Promise<Blog[]> {
const blogs = await this.blogsRepository
.createQueryBuilder("blog")
.select(["blog.id", "blog.featuredImage", "blog.gallery", "blog.href", "blog.publishedAt"])
.leftJoinAndSelect("blog.translations", "translation", "translation.language = :language", { language })
.where("blog.publishedAt IS NOT NULL")
.orderBy("blog.publishedAt", "DESC")
.getMany();
return blogs;
}
async fetchSingleBlogByLanguageAndHref(language: LanguageEnum, href: string): Promise<Blog | null> {
const blog = await this.blogsRepository
.createQueryBuilder("blog")
.select(["blog.id", "blog.featuredImage", "blog.gallery", "blog.href", "blog.publishedAt"])
.leftJoinAndSelect("blog.translations", "translation", "translation.language = :language", { language })
.where("blog.publishedAt IS NOT NULL AND blog.href = :href", { href })
.getOne();
return blog;
}
}

View File

@@ -0,0 +1,21 @@
import { Body, Controller, HttpStatus, Ip, Post, Res } from "@nestjs/common";
import { ApiOperation, ApiTags } from "@nestjs/swagger";
import type { Response } from "express";
import { PublicRoute } from "src/decorators/public-route.decorator";
import { InsertContactDto } from "src/dtos/contacts/insert-contact.dto";
import { ContactsService } from "./contacts.service";
import { CustomResponses } from "src/utilities/responses";
@ApiTags("Contacts Managements")
@Controller("contacts")
export class ContactsController {
constructor(private readonly contactsService: ContactsService) {}
@ApiOperation({ summary: "create new contact" })
@PublicRoute()
@Post()
async insertContact(@Body() insertContactDto: InsertContactDto, @Ip() ip: string, @Res() res: Response): Promise<Response> {
await this.contactsService.insertContact(insertContactDto, ip);
return CustomResponses.successResponse(res, "پیام شما با موفقیت ارسال شد", HttpStatus.CREATED);
}
}

View File

@@ -0,0 +1,12 @@
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { Contact } from "src/entities/contacts.entity";
import { ContactsController } from "./contacts.controller";
import { ContactsService } from "./contacts.service";
@Module({
imports: [TypeOrmModule.forFeature([Contact])],
controllers: [ContactsController],
providers: [ContactsService],
})
export class ContactsModule {}

View File

@@ -0,0 +1,24 @@
import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { InsertContactDto } from "src/dtos/contacts/insert-contact.dto";
import { Contact } from "src/entities/contacts.entity";
import { CustomUuid } from "src/utilities/uuid";
import { Repository } from "typeorm";
@Injectable()
export class ContactsService {
constructor(
@InjectRepository(Contact)
private contactsRepository: Repository<Contact>
) {}
async insertContact(insertContactDto: InsertContactDto, ip: string): Promise<void> {
const newContact = this.contactsRepository.create({
id: CustomUuid.generateUuid(),
...insertContactDto,
ip,
});
await this.contactsRepository.save(newContact);
}
}

View File

@@ -0,0 +1,33 @@
import { Module } from "@nestjs/common";
import { MailService } from "./mails.service";
import { EjsAdapter } from "@nestjs-modules/mailer/dist/adapters/ejs.adapter";
import { MailerModule } from "@nestjs-modules/mailer";
@Module({
imports: [
MailerModule.forRoot({
transport: {
host: "smtp.gmail.com",
port: 587,
secure: false,
auth: {
user: "robinnetwork.ltd@gmail.com",
pass: "nfwy tibw lmqb kzqk",
},
},
defaults: {
from: '"Robin Network Panel" <robinnetwork.ltd@gmail.com>',
},
template: {
dir: process.cwd() + "/src" + "/templates",
adapter: new EjsAdapter(),
options: {
strict: false,
},
},
}),
],
providers: [MailService],
exports: [MailService],
})
export class MailModule {}

View File

@@ -0,0 +1,19 @@
import { MailerService } from "@nestjs-modules/mailer";
import { Injectable } from "@nestjs/common";
@Injectable()
export class MailService {
constructor(private readonly mailerService: MailerService) {}
async sendVerifyCode(email: string, code: string, username: string) {
await this.mailerService.sendMail({
to: email,
subject: `Welcome to RobinNetwork Panel`,
template: "./send-code",
context: {
username,
code,
},
});
}
}

View File

@@ -0,0 +1,230 @@
import { Body, Controller, Delete, Get, HttpStatus, Param, Patch, Post, Req, Res } from "@nestjs/common";
import { RoleEnum } from "src/enums/role.enum";
import { Roles } from "src/decorators/roles.decorator";
import { ApiOperation, ApiTags } from "@nestjs/swagger";
import type { Response } from "express";
import { CustomResponses } from "src/utilities/responses";
import { IsUuidPipe } from "src/pipes/public/is-uuid.pipe";
import { ApiError } from "src/utilities/api-error";
import { PortfoliosService } from "./portfolios.service";
import { PublicRoute } from "src/decorators/public-route.decorator";
import { IsLanguageEnumPipe } from "src/pipes/public/is-language.pipe";
import { LanguageEnum } from "src/enums/language.enum";
import { PortfolioCategoryEnum } from "src/enums/portfolio-category.enum";
import { IsPortfolioCategoryPipe } from "src/pipes/portfolios/is-portfolio-category.pipe";
import { InsertPortfolioAboutFieldsDto } from "src/dtos/portfolios/insert-about-fields.dto";
import { UpdatePortfolioAboutFieldsDto } from "src/dtos/portfolios/update-about-fields.dto";
import { UpdatePortfolioFeaturedImageDto } from "src/dtos/portfolios/update-featured-image.dto";
import { UpdatePortfolioGalleryDto } from "src/dtos/portfolios/update-gallery.dto";
import { UpdatePortfolioTranslationsDto } from "src/dtos/portfolios/update-translations.dto";
import { IsHrefPipe } from "src/pipes/public/is-href.pipe";
@ApiTags("Manage Portfolios")
@Controller("portfolios")
export class PortfoliosController {
constructor(private readonly portfoliosService: PortfoliosService) {}
@ApiOperation({ summary: "get all portfolios" })
@Roles(RoleEnum.Admin)
@Get()
async getAllPortfolios(@Res() res: Response) {
const portfolios = await this.portfoliosService.getAllPortfoliosTitleAndPublished();
return CustomResponses.successResponse(res, "", HttpStatus.OK, portfolios);
}
@ApiOperation({ summary: "insert the about data" })
@Roles(RoleEnum.Admin)
@Post("about")
async insertAboutFields(
@Req() req: any,
@Res() res: Response,
@Body() insertAboutFieldsDto: InsertPortfolioAboutFieldsDto
): Promise<Response> {
const id = await this.portfoliosService.insertAboutFields(insertAboutFieldsDto);
return CustomResponses.successResponse(res, "", HttpStatus.CREATED, id);
}
@ApiOperation({ summary: "get the current phase" })
@Roles(RoleEnum.Admin)
@Get("phase/:id")
async getCurrentPhase(@Res() res: Response, @Param("id", new IsUuidPipe("portfolio not found")) id: string): Promise<Response> {
const phase = await this.portfoliosService.getPhase(id);
return CustomResponses.successResponse(res, "", HttpStatus.OK, phase);
}
@ApiOperation({ summary: "get the about fields" })
@Roles(RoleEnum.Admin)
@Get("about/:id")
async getAboutFields(@Res() res: Response, @Param("id", new IsUuidPipe("portfolio not found")) id: string): Promise<Response> {
if (!(await this.portfoliosService.isPortfolioExistsById(id))) throw new ApiError("portfolio not found", HttpStatus.NOT_FOUND);
const fields = await this.portfoliosService.fetchAboutFieldsById(id);
return CustomResponses.successResponse(res, "", HttpStatus.OK, fields);
}
@ApiOperation({ summary: "update the about data" })
@Roles(RoleEnum.Admin)
@Patch("about/:id")
async updateAboutFields(
@Res() res: Response,
@Body() updateAboutFieldsDto: UpdatePortfolioAboutFieldsDto,
@Param("id", new IsUuidPipe("portfolio not found")) id: string
): Promise<Response> {
await this.portfoliosService.updateAboutFields(id, updateAboutFieldsDto);
return CustomResponses.successResponse(res, "", HttpStatus.OK);
}
@ApiOperation({ summary: "get the featured image" })
@Roles(RoleEnum.Admin)
@Get("feature/:id")
async getFeaturedImage(@Res() res: Response, @Param("id", new IsUuidPipe("portfolio not found")) id: string): Promise<Response> {
if (!(await this.portfoliosService.isPortfolioExistsById(id))) throw new ApiError("portfolio not found", HttpStatus.NOT_FOUND);
const image = await this.portfoliosService.fetchFeaturedImageById(id);
return CustomResponses.successResponse(res, "", HttpStatus.OK, image);
}
@ApiOperation({ summary: "update the featured image" })
@Roles(RoleEnum.Admin)
@Patch("feature/:id")
async updateFeaturedImage(
@Res() res: Response,
@Body() updateFeaturedImageDto: UpdatePortfolioFeaturedImageDto,
@Param("id", new IsUuidPipe("portfolio not found")) id: string
): Promise<Response> {
if (!(await this.portfoliosService.isPortfolioExistsById(id))) throw new ApiError("portfolio not found", HttpStatus.NOT_FOUND);
await this.portfoliosService.updateFeaturedImageById(id, updateFeaturedImageDto.image);
return CustomResponses.successResponse(res, "", HttpStatus.OK);
}
@ApiOperation({ summary: "get the gallery images" })
@Roles(RoleEnum.Admin)
@Get("gallery/:id")
async getGallery(@Res() res: Response, @Param("id", new IsUuidPipe("portfolio not found")) id: string): Promise<Response> {
if (!(await this.portfoliosService.isPortfolioExistsById(id))) throw new ApiError("portfolio not found", HttpStatus.NOT_FOUND);
const gallery = await this.portfoliosService.fetchGalleryById(id);
return CustomResponses.successResponse(res, "", HttpStatus.OK, gallery);
}
@ApiOperation({ summary: "update the gallery" })
@Roles(RoleEnum.Admin)
@Patch("gallery/:id")
async updateGallery(
@Res() res: Response,
@Body() updateGalleryDto: UpdatePortfolioGalleryDto,
@Param("id", new IsUuidPipe("portfolio not found")) id: string
): Promise<Response> {
if (!(await this.portfoliosService.isPortfolioExistsById(id))) throw new ApiError("portfolio not found", HttpStatus.NOT_FOUND);
await this.portfoliosService.updateGalleryById(id, updateGalleryDto.gallery);
return CustomResponses.successResponse(res, "", HttpStatus.OK);
}
@ApiOperation({ summary: "get the translation data" })
@Roles(RoleEnum.Admin)
@Get("translation/:id")
async getTranslationData(@Res() res: Response, @Param("id", new IsUuidPipe("portfolio not found")) id: string): Promise<Response> {
if (!(await this.portfoliosService.isPortfolioExistsById(id))) throw new ApiError("portfolio not found", HttpStatus.NOT_FOUND);
const translations = await this.portfoliosService.fetchTranslationDataById(id);
return CustomResponses.successResponse(res, "", HttpStatus.OK, translations);
}
@ApiOperation({ summary: "update the translation data" })
@Roles(RoleEnum.Admin)
@Patch("translation/:id")
async updateTranslations(
@Res() res: Response,
@Body() updateTranslationsDto: UpdatePortfolioTranslationsDto,
@Param("id", new IsUuidPipe("portfolio not found")) id: string
): Promise<Response> {
if (!(await this.portfoliosService.isPortfolioExistsById(id))) throw new ApiError("portfolio not found", HttpStatus.NOT_FOUND);
await this.portfoliosService.updateTranslationsDataById(id, updateTranslationsDto);
return CustomResponses.successResponse(res, "Translation has been saved successfully", HttpStatus.OK);
}
@ApiOperation({ summary: "publish the blog" })
@Roles(RoleEnum.Admin)
@Patch("publish/:id")
async publishPortfolio(@Res() res: Response, @Param("id", new IsUuidPipe("portfolio not found")) id: string): Promise<Response> {
if (!(await this.portfoliosService.isPortfolioExistsById(id))) throw new ApiError("portfolio not found", HttpStatus.NOT_FOUND);
await this.portfoliosService.publishPortfolioById(id);
return CustomResponses.successResponse(res, "", HttpStatus.OK);
}
@ApiOperation({ summary: "archive the portfolio" })
@Roles(RoleEnum.Admin)
@Patch("archive/:id")
async archivePortfolio(@Res() res: Response, @Param("id", new IsUuidPipe("portfolio not found")) id: string): Promise<Response> {
if (!(await this.portfoliosService.isPortfolioExistsById(id))) throw new ApiError("portfolio not found", HttpStatus.NOT_FOUND);
await this.portfoliosService.archivePortfolioById(id);
return CustomResponses.successResponse(res, "portfolio has been archived successfully", HttpStatus.OK, id);
}
@ApiOperation({ summary: "unarchive the portfolio" })
@Roles(RoleEnum.Admin)
@Patch("unarchive/:id")
async unarchivePortfolio(@Res() res: Response, @Param("id", new IsUuidPipe("portfolio not found")) id: string): Promise<Response> {
if (!(await this.portfoliosService.isPortfolioExistsIncludeSoftDeletedById(id)))
throw new ApiError("portfolio not found", HttpStatus.NOT_FOUND);
await this.portfoliosService.unarchivePortfolioById(id);
return CustomResponses.successResponse(res, "portfolio has been restored successfully", HttpStatus.OK, id);
}
@ApiOperation({ summary: "delete drafted portfolio" })
@Roles(RoleEnum.Admin)
@Delete(":id")
async deleteDraftedPortfolio(@Res() res: Response, @Param("id", new IsUuidPipe("portfolio not found")) id: string): Promise<Response> {
if (!(await this.portfoliosService.isPortfolioExistsById(id))) throw new ApiError("portfolio not found", HttpStatus.NOT_FOUND);
await this.portfoliosService.deleteDraftedPortfolioById(id);
return CustomResponses.successResponse(res, "portfolio has been deleted successfully", HttpStatus.OK, id);
}
@ApiOperation({ summary: "get the latest portfolios by category and language" })
@PublicRoute()
@Get("latest/:category/:language")
async getLatestPortfoliosByCategory(
@Res() res: Response,
@Param("language", new IsLanguageEnumPipe("language not found")) language: LanguageEnum,
@Param("category", new IsPortfolioCategoryPipe("category not found")) category: PortfolioCategoryEnum
): Promise<Response> {
const portfolios = await this.portfoliosService.fetchPortfoliosByLanguageAndCategory(language, category, true, null);
return CustomResponses.successResponse(res, "", HttpStatus.OK, portfolios);
}
@ApiOperation({ summary: "get the all portfolios by category and language" })
@PublicRoute()
@Get("all/:category/:language")
async getAllPortfoliosByCategory(
@Res() res: Response,
@Param("language", new IsLanguageEnumPipe("language not found")) language: LanguageEnum,
@Param("category", new IsPortfolioCategoryPipe("category not found")) category: PortfolioCategoryEnum
): Promise<Response> {
const portfolios = await this.portfoliosService.fetchPortfoliosByLanguageAndCategory(language, category, false, null);
return CustomResponses.successResponse(res, "", HttpStatus.OK, portfolios);
}
@ApiOperation({ summary: "get the related portfolios by language" })
@PublicRoute()
@Get("related/:category/:language/:exceptionhref")
async getRelatedPortfoliosByCategory(
@Res() res: Response,
@Param("language", new IsLanguageEnumPipe("language not found")) language: LanguageEnum,
@Param("category", new IsPortfolioCategoryPipe("category not found")) category: PortfolioCategoryEnum,
@Param("exceptionhref") exceptionHref: string
): Promise<Response> {
const portfolios = await this.portfoliosService.fetchPortfoliosByLanguageAndCategory(language, category, false, exceptionHref);
return CustomResponses.successResponse(res, "", HttpStatus.OK, portfolios);
}
@ApiOperation({ summary: "get single portfolio by language" })
@PublicRoute()
@Get("single/:href/:language")
async getSinglePortfolio(
@Res() res: Response,
@Param("language", new IsLanguageEnumPipe("language not found")) language: LanguageEnum,
@Param("href", new IsHrefPipe("portfolio not found")) href: string
): Promise<Response> {
if (!(await this.portfoliosService.isPortfolioPublishedByHref(href))) {
throw new ApiError("portfolio not found", HttpStatus.NOT_FOUND);
}
const portfolio = await this.portfoliosService.fetchSinglePortfolioByHrefAndLanguage(href, language);
return CustomResponses.successResponse(res, "", HttpStatus.OK, portfolio);
}
}

View File

@@ -0,0 +1,13 @@
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { PortfoliosController } from "./portfolios.controller";
import { PortfoliosService } from "./portfolios.service";
import { Portfolio } from "src/entities/portfolios.entity";
import { PortfolioTranslation } from "src/entities/portfolios_translation.entity";
@Module({
imports: [TypeOrmModule.forFeature([Portfolio, PortfolioTranslation])],
controllers: [PortfoliosController],
providers: [PortfoliosService],
})
export class PortfoliosModule {}

View File

@@ -0,0 +1,287 @@
import { HttpStatus, Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { InsertPortfolioAboutFieldsDto } from "src/dtos/portfolios/insert-about-fields.dto";
import { UpdatePortfolioAboutFieldsDto } from "src/dtos/portfolios/update-about-fields.dto";
import { UpdatePortfolioTranslationsDto } from "src/dtos/portfolios/update-translations.dto";
import { Blog } from "src/entities/blogs.entity";
import { BlogTranslation } from "src/entities/blogs_translation.entity";
import { Portfolio } from "src/entities/portfolios.entity";
import { PortfolioTranslation } from "src/entities/portfolios_translation.entity";
import { LanguageEnum } from "src/enums/language.enum";
import { PortfolioCategoryEnum } from "src/enums/portfolio-category.enum";
import { PortfolioPhaseEnum } from "src/enums/portfolio-phase.enum";
import { BlogTranslationType, PortfolioTranslationType } from "src/helpers/types";
import { ApiError } from "src/utilities/api-error";
import { CustomUuid } from "src/utilities/uuid";
import { IsNull, Not, Repository } from "typeorm";
@Injectable()
export class PortfoliosService {
constructor(
@InjectRepository(Portfolio)
private readonly portfoliosRepository: Repository<Portfolio>,
@InjectRepository(PortfolioTranslation)
private readonly portfoliosTranslationRepository: Repository<PortfolioTranslation>
) {}
async isPortfolioExistsById(id: string): Promise<boolean> {
return await this.portfoliosRepository.exists({ where: { id } });
}
async isPortfolioExistsIncludeSoftDeletedById(id: string): Promise<boolean> {
const portfolio = await this.portfoliosRepository
.createQueryBuilder("portfolio")
.withDeleted()
.where("portfolio.id = :id", { id })
.getRawOne();
return !!portfolio;
}
async getPhase(id: string): Promise<string | undefined> {
const portfolio = await this.portfoliosRepository.findOne({ where: { id }, select: ["phase"] });
return portfolio?.phase;
}
async getAllPortfoliosTitleAndPublished(): Promise<Blog[]> {
const portfolios = await this.portfoliosRepository
.createQueryBuilder("portfolio")
.withDeleted()
.leftJoin("portfolio.translations", "t", "t.language = :lang", {
lang: LanguageEnum.Farsi,
})
.select("portfolio.id", "id")
.addSelect("portfolio.category", "category")
.addSelect("t.title", "title")
.addSelect(
`CASE
WHEN portfolio.publishedAt IS NULL THEN false
ELSE true
END`,
"isPublished"
)
.addSelect(
`CASE
WHEN portfolio.deletedAt IS NULL THEN false
ELSE true
END`,
"isArchived"
)
.getRawMany();
return portfolios;
}
async isHrefUnique(href: string): Promise<boolean> {
const isAlreadyTaken = await this.portfoliosRepository.exists({ where: { href } });
return !isAlreadyTaken;
}
async isHrefUniqueForPatchById(id: string, href: string) {
const isAlreadyTaken = await this.portfoliosRepository.exists({ where: { href, id: Not(id) } });
return !isAlreadyTaken;
}
async insertAboutFields(insertAboutFieldsDto: InsertPortfolioAboutFieldsDto): Promise<string> {
if (!(await this.isHrefUnique(insertAboutFieldsDto.href))) throw new ApiError("this short-link is already taken", 422);
const { title, description, href, category, employer, externalLink } = insertAboutFieldsDto;
const newPortfolio = this.portfoliosRepository.create({
id: CustomUuid.generateUuid(),
href,
category,
externalLink,
phase: PortfolioPhaseEnum.PortfolioAboutData,
});
await this.portfoliosRepository.save(newPortfolio);
await this.createTranslationByIdAndLanguage(newPortfolio.id, LanguageEnum.Farsi, { description, employer, title });
await this.createTranslationByIdAndLanguage(newPortfolio.id, LanguageEnum.English, { description, employer, title });
await this.createTranslationByIdAndLanguage(newPortfolio.id, LanguageEnum.Arabic, { description, employer, title });
return newPortfolio.id;
}
async updateAboutFields(id: string, updateAboutFieldsDto: UpdatePortfolioAboutFieldsDto) {
if (!(await this.isHrefUniqueForPatchById(id, updateAboutFieldsDto.href))) return new ApiError("this short-link is already taken", 422);
const { title, description, href, category, employer, externalLink } = updateAboutFieldsDto;
await this.portfoliosRepository.update({ id }, { href, externalLink, category });
await this.portfoliosTranslationRepository.update({ portfolioId: id, language: LanguageEnum.Farsi }, { title, description, employer });
}
async fetchAboutFieldsById(id: string): Promise<Object | null> {
const fields = await this.portfoliosRepository
.createQueryBuilder("portfolio")
.leftJoin("portfolio.translations", "t", "t.language = :lang", {
lang: LanguageEnum.Farsi,
})
.select("portfolio.href", "href")
.addSelect("portfolio.category", "category")
.addSelect("portfolio.externalLink", "externalLink")
.addSelect("t.title", "title")
.addSelect("t.description", "description")
.addSelect("t.employer", "employer")
.where("portfolio.id = :id", { id })
.getRawOne();
return fields;
}
async updateFeaturedImageById(id: string, imageUrl: string): Promise<void> {
const currentPhase = await this.getPhase(id);
await this.portfoliosRepository.update(
{ id },
{
featuredImage: imageUrl,
phase: currentPhase === PortfolioPhaseEnum.PortfolioAboutData ? PortfolioPhaseEnum.PortfolioFeaturedImageData : currentPhase,
}
);
}
async fetchFeaturedImageById(id: string): Promise<string | null> {
const blog = await this.portfoliosRepository.findOne({ where: { id }, select: ["featuredImage"] });
return blog?.featuredImage ?? null;
}
async updateGalleryById(id: string, gallery: string[]): Promise<void> {
const currentPhase = await this.getPhase(id);
await this.portfoliosRepository.update(
{ id },
{
gallery,
phase: currentPhase === PortfolioPhaseEnum.PortfolioFeaturedImageData ? PortfolioPhaseEnum.PortfolioGalleryData : currentPhase,
}
);
}
async fetchGalleryById(id: string): Promise<string[] | null> {
const blog = await this.portfoliosRepository.findOne({ where: { id }, select: ["gallery"] });
return blog?.gallery ?? null;
}
async createTranslationByIdAndLanguage(
id: string,
language: LanguageEnum,
data: { title: string; description: string; employer: string }
) {
const newPortfolioTranslation = this.portfoliosTranslationRepository.create({
id: CustomUuid.generateUuid(),
title: data?.title,
description: data?.description,
employer: data.employer,
language,
portfolioId: id,
});
await this.portfoliosTranslationRepository.save(newPortfolioTranslation);
}
async fetchTranslationDataById(id: string): Promise<PortfolioTranslationType[]> {
const translations = await this.portfoliosTranslationRepository
.createQueryBuilder("translation")
.select("translation.title", "title")
.addSelect("translation.description", "description")
.addSelect("translation.employer", "employer")
.addSelect("translation.language", "language")
.where("translation.portfolioId = :portfolioId", { portfolioId: id })
.getRawMany();
return translations;
}
async updateTranslationByIdAndLanguage(
id: string,
language: LanguageEnum,
data: { title: string; description: string; employer: string }
) {
const { description, employer, title } = data;
await this.portfoliosTranslationRepository.update({ portfolioId: id, language }, { title, description, employer });
}
async updateTranslationsDataById(id: string, updateTranslationsDto: UpdatePortfolioTranslationsDto) {
const { en, ar } = updateTranslationsDto;
await this.updateTranslationByIdAndLanguage(id, LanguageEnum.English, en);
await this.updateTranslationByIdAndLanguage(id, LanguageEnum.Arabic, ar);
}
async publishPortfolioById(id: string) {
if (await this.isPortfolioPublishedById(id)) return;
await this.portfoliosRepository.update({ id }, { publishedAt: () => "NOW()" });
}
async archivePortfolioById(id: string): Promise<void> {
await this.portfoliosRepository.softDelete({ id });
}
async unarchivePortfolioById(id: string): Promise<void> {
await this.portfoliosRepository.restore({ id });
}
async isPortfolioPublishedById(id: string): Promise<boolean> {
return await this.portfoliosRepository.exists({ where: { id, publishedAt: Not(IsNull()) } });
}
async isPortfolioPublishedByHref(href: string): Promise<boolean> {
return await this.portfoliosRepository.exists({ where: { href, publishedAt: Not(IsNull()) } });
}
async deleteDraftedPortfolioById(id: string): Promise<void> {
if (await this.isPortfolioPublishedById(id)) {
throw new ApiError("this portfolio cannot be deleted because it published", HttpStatus.FORBIDDEN);
}
await this.portfoliosTranslationRepository.delete({ portfolioId: id });
await this.portfoliosRepository.delete({ id });
}
async fetchPortfoliosByLanguageAndCategory(
language: LanguageEnum,
category: PortfolioCategoryEnum,
latest: boolean,
exceptionHref: string | null
): Promise<Portfolio[]> {
const query = await this.portfoliosRepository
.createQueryBuilder("p")
.leftJoin("p.translations", "t", "t.language = :language", { language })
.select("p.id AS id")
.addSelect("p.featuredImage", "featuredImage")
.addSelect("p.externalLink", "externalLink")
.addSelect("p.href", "href")
.addSelect("p.category", "category")
.addSelect("t.title", "title")
.addSelect("t.description", "description")
.addSelect("t.employer", "employer")
.where("p.publishedAt IS NOT NULL")
.andWhere("p.category = :category", { category })
.orderBy("p.publishedAt", "DESC");
if (exceptionHref) {
query.andWhere("p.href != :href", { href: exceptionHref });
}
if (latest || exceptionHref) {
query.limit(3);
}
return await query.getRawMany();
}
async fetchSinglePortfolioByHrefAndLanguage(href: string, language: LanguageEnum): Promise<Portfolio | null> {
const portfolio = await this.portfoliosRepository
.createQueryBuilder("p")
.leftJoin("p.translations", "t", "t.language = :language", { language })
.select("p.id", "id")
.addSelect("p.featuredImage", "featuredImage")
.addSelect("p.gallery", "gallery")
.addSelect("p.externalLink", "externalLink")
.addSelect("p.href", "href")
.addSelect("p.category", "category")
.addSelect("t.title", "title")
.addSelect("t.description", "description")
.addSelect("t.employer", "employer")
.where("p.publishedAt IS NOT NULL")
.andWhere("p.href = :href", { href })
.getRawOne();
return portfolio;
}
}

View File

@@ -0,0 +1,7 @@
import { Controller } from "@nestjs/common";
import { ProjectsService } from "./projects.service";
@Controller("projects")
export class ProjectsController {
constructor(private readonly projectsService: ProjectsService) {}
}

View File

@@ -0,0 +1,12 @@
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { User } from "src/entities/users.entity";
import { ProjectsController } from "./projects.controller";
import { ProjectsService } from "./projects.service";
@Module({
imports: [TypeOrmModule.forFeature([User])],
controllers: [ProjectsController],
providers: [ProjectsService],
})
export class ProjectsModule {}

View File

@@ -0,0 +1,12 @@
import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { User } from "src/entities/users.entity";
import { Repository } from "typeorm";
@Injectable()
export class ProjectsService {
constructor(
@InjectRepository(User)
private usersRepository: Repository<User>
) {}
}

View File

@@ -0,0 +1,75 @@
import { Controller, Post, UploadedFiles, UseInterceptors, HttpStatus, Res, UploadedFile } from "@nestjs/common";
import { FileInterceptor, FilesInterceptor } from "@nestjs/platform-express";
import { diskStorage } from "multer";
import { extname } from "path";
import { ApiError } from "src/utilities/api-error";
import type { Response } from "express";
import { CustomResponses } from "src/utilities/responses";
import { ApiOperation, ApiTags } from "@nestjs/swagger";
import { Roles } from "src/decorators/roles.decorator";
import { RoleEnum } from "src/enums/role.enum";
@ApiTags("manage file uploads")
@Roles(RoleEnum.Admin)
@Controller("uploads")
export class UploadController {
@ApiOperation({ summary: "upload single image" })
@Post("single")
@UseInterceptors(
FileInterceptor("image", {
storage: diskStorage({
destination: "./uploads",
filename: (req, file, cb) => {
const randomName = file.originalname + "-" + Date.now() + "-" + Math.round(Math.random() * 1e9);
cb(null, `${randomName}${extname(file.originalname)}`);
},
}),
fileFilter: (req, file, cb) => {
if (!file.mimetype.match(/\/(jpg|jpeg|png|webp)$/)) {
cb(new ApiError("Only image files are allowed", HttpStatus.UNPROCESSABLE_ENTITY), false);
} else {
cb(null, true);
}
},
limits: { fileSize: 1 * 1024 * 1024 },
})
)
uploadFile(@UploadedFile() file: Express.Multer.File, @Res() res: Response): Response {
if (!file) {
throw new ApiError("File not uploaded or invalid.", HttpStatus.UNPROCESSABLE_ENTITY);
}
return CustomResponses.successResponse(res, "", HttpStatus.CREATED, file.filename);
}
@ApiOperation({ summary: "upload multiple images" })
@Post("multiple")
@UseInterceptors(
FilesInterceptor("images", 10, {
storage: diskStorage({
destination: "./uploads",
filename: (req, file, cb) => {
const randomName = file.originalname + "-" + Date.now() + "-" + Math.round(Math.random() * 1e9);
cb(null, `${randomName}${extname(file.originalname)}`);
},
}),
fileFilter: (req, file, cb) => {
if (!file.mimetype.match(/\/(jpg|jpeg|png|webp)$/)) {
cb(new ApiError("Only image files are allowed", HttpStatus.UNPROCESSABLE_ENTITY), false);
} else {
cb(null, true);
}
},
limits: { fileSize: 1 * 1024 * 1024 },
})
)
uploadMultipleFiles(@UploadedFiles() files: Express.Multer.File[], @Res() res: Response): Response {
if (!files || files.length === 0) {
throw new ApiError("No files uploaded or all invalid.", HttpStatus.UNPROCESSABLE_ENTITY);
}
const fileNames = files.map((file) => file.filename);
return CustomResponses.successResponse(res, "", HttpStatus.CREATED, fileNames);
}
}

View File

@@ -0,0 +1,7 @@
import { Module } from "@nestjs/common";
import { UploadController } from "./uploads.controller";
@Module({
controllers: [UploadController],
})
export class UploadModule {}

View File

@@ -0,0 +1,66 @@
import { Body, Controller, Delete, Get, HttpStatus, Param, Patch, Post, Res } from "@nestjs/common";
import { ApiOperation, ApiTags } from "@nestjs/swagger";
import { Roles } from "src/decorators/roles.decorator";
import { CreateUserDto } from "src/dtos/users/create-user.dto";
import { RoleEnum } from "src/enums/role.enum";
import { UsersService } from "./users.service";
import { ApiError } from "src/utilities/api-error";
import { CustomResponses } from "src/utilities/responses";
import type { Response } from "express";
import { UpdateUserDto } from "src/dtos/users/update-user.dto";
import { IsUuidPipe } from "src/pipes/public/is-uuid.pipe";
@ApiTags("Manage Users")
@Controller("users")
export class UsersController {
constructor(private usersService: UsersService) {}
@ApiOperation({ summary: "fetch all normal users" })
@Roles(RoleEnum.Admin)
@Get()
async getAllNormalUsers(@Res() res: Response): Promise<Response> {
const normalUsers = await this.usersService.fetchNormalUsers();
return CustomResponses.successResponse(res, "normal users fetched", HttpStatus.OK, normalUsers);
}
@ApiOperation({ summary: "create new user" })
@Roles(RoleEnum.Admin)
@Post()
async createNewUser(@Body() createUserDto: CreateUserDto, @Res() res: Response): Promise<Response> {
if (await this.usersService.areUsernameAndEmailUnique(createUserDto)) {
throw new ApiError("email or username is already taken", HttpStatus.UNPROCESSABLE_ENTITY);
}
const newUser = await this.usersService.createUser(createUserDto);
return CustomResponses.successResponse(res, "user has been created successfully", HttpStatus.CREATED, newUser);
}
@ApiOperation({ summary: "update user info" })
@Roles(RoleEnum.Admin)
@Patch(":id")
async updateUserInfo(
@Body() updateUserDto: UpdateUserDto,
@Res() res: Response,
@Param("id", new IsUuidPipe("user not found")) id: string
): Promise<Response> {
if (!(await this.usersService.fetchUserById(id))) {
throw new ApiError("user not found", HttpStatus.UNPROCESSABLE_ENTITY);
}
if (await this.usersService.areUsernameAndEmailOnlyHaveOneInstance(id, updateUserDto)) {
throw new ApiError("email or username is already taken", HttpStatus.UNPROCESSABLE_ENTITY);
}
await this.usersService.updateUser(id, updateUserDto);
const updatedUser = await this.usersService.fetchUserById(id);
return CustomResponses.successResponse(res, "user has been updated successfully", HttpStatus.CREATED, updatedUser);
}
@ApiOperation({ summary: "soft delete user" })
@Roles(RoleEnum.Admin)
@Delete(":id")
async softDeleteUser(@Res() res: Response, @Param("id", new IsUuidPipe("user not found")) id: string): Promise<Response> {
if (!(await this.usersService.fetchUserById(id))) {
throw new ApiError("user not found", HttpStatus.UNPROCESSABLE_ENTITY);
}
await this.usersService.softDeleteUser(id);
return CustomResponses.successResponse(res, "user has been deleted successfully", HttpStatus.OK, id);
}
}

View File

@@ -0,0 +1,13 @@
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { User } from "src/entities/users.entity";
import { UsersService } from "./users.service";
import { UsersController } from "./users.controller";
@Module({
imports: [TypeOrmModule.forFeature([User])],
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService],
})
export class UsersModule {}

View File

@@ -0,0 +1,61 @@
import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { CreateUserDto } from "src/dtos/users/create-user.dto";
import { UpdateUserDto } from "src/dtos/users/update-user.dto";
import { User } from "src/entities/users.entity";
import { RoleEnum } from "src/enums/role.enum";
import { CustomUuid } from "src/utilities/uuid";
import { Not, Repository } from "typeorm";
@Injectable()
export class UsersService {
constructor(
@InjectRepository(User)
private usersRepository: Repository<User>
) {}
async findUserByIdentifier(identifier: string): Promise<User | null> {
return await this.usersRepository.findOne({ where: [{ username: identifier }, { email: identifier }] });
}
async fetchUserById(id: string): Promise<User | null> {
return await this.usersRepository.findOne({ where: { id } });
}
async getMeById(id: string): Promise<User | null> {
return await this.usersRepository.findOne({ where: { id }, select: ["email", "username", "role"] });
}
async areUsernameAndEmailUnique(createUserDto: CreateUserDto): Promise<boolean> {
const isUnique = await this.usersRepository.findOne({ where: { ...createUserDto } });
return isUnique ? true : false;
}
async areUsernameAndEmailOnlyHaveOneInstance(id: string, updateUserDto: UpdateUserDto) {
const { email, username } = updateUserDto;
const isHaveOneInstance = await this.usersRepository.findOne({
where: [
{ username, id: Not(id) },
{ email, id: Not(id) },
],
});
return isHaveOneInstance ? true : false;
}
async createUser(createUserDto: CreateUserDto): Promise<User> {
const newUser = this.usersRepository.create({ id: CustomUuid.generateUuid(), ...createUserDto, role: RoleEnum.Tech });
return await this.usersRepository.save(newUser);
}
async updateUser(id: string, updateUserDto: UpdateUserDto): Promise<void> {
await this.usersRepository.update({ id }, { ...updateUserDto });
}
async softDeleteUser(id: string): Promise<void> {
await this.usersRepository.softDelete({ id });
}
async fetchNormalUsers(): Promise<User[]> {
return await this.usersRepository.find({ where: { role: Not(RoleEnum.Admin) } });
}
}

View File

@@ -0,0 +1,16 @@
import { ArgumentMetadata, HttpStatus, Injectable, PipeTransform } from "@nestjs/common";
import { PortfolioCategoryEnum } from "src/enums/portfolio-category.enum";
import { ApiError } from "src/utilities/api-error";
@Injectable()
export class IsPortfolioCategoryPipe implements PipeTransform<string> {
constructor(private readonly message = "Incorrect category") {}
transform(value: string, metadata: ArgumentMetadata) {
if (!Object.values(PortfolioCategoryEnum).includes(value as PortfolioCategoryEnum)) {
throw new ApiError(this.message, HttpStatus.UNPROCESSABLE_ENTITY);
}
return value;
}
}

View File

@@ -0,0 +1,14 @@
import { ArgumentMetadata, HttpStatus, Injectable, PipeTransform } from "@nestjs/common";
import { ApiError } from "src/utilities/api-error";
@Injectable()
export class IsHrefPipe implements PipeTransform<string> {
constructor(private readonly message = "href is invalid") {}
transform(value: string, metadata: ArgumentMetadata) {
if (!/^[A-Za-z-]+$/.test(value)) {
throw new ApiError(this.message, HttpStatus.UNPROCESSABLE_ENTITY);
}
return value.toLowerCase();
}
}

View File

@@ -0,0 +1,18 @@
import { ArgumentMetadata, HttpStatus, Injectable, PipeTransform } from "@nestjs/common";
import { ApiError } from "src/utilities/api-error";
import { LanguageEnum } from "src/enums/language.enum";
@Injectable()
export class IsLanguageEnumPipe implements PipeTransform<string> {
constructor(private readonly message = "Invalid language") {}
transform(value: string, metadata: ArgumentMetadata): string {
const isValid = Object.values(LanguageEnum).includes(value as LanguageEnum);
if (!isValid) {
throw new ApiError(this.message, HttpStatus.UNPROCESSABLE_ENTITY);
}
return value;
}
}

View File

@@ -0,0 +1,15 @@
import { ArgumentMetadata, HttpStatus, Injectable, PipeTransform } from "@nestjs/common";
import { ApiError } from "src/utilities/api-error";
import { CustomUuid } from "src/utilities/uuid";
@Injectable()
export class IsUuidPipe implements PipeTransform<string> {
constructor(private readonly message = "id is not valid") {}
transform(value: string, metadata: ArgumentMetadata) {
if (!CustomUuid.validate(value)) {
throw new ApiError(this.message, HttpStatus.UNPROCESSABLE_ENTITY);
}
return value;
}
}

View File

@@ -0,0 +1,34 @@
<!DOCTYPE html>
<html>
<head>
<style>
main {
display: flex;
flex-direction: column;
align-items: center;
gap: 4rem;
width: 100%;
height: 100%;
text-align: center;
color: gray;
}
p {
font-size: large;
}
b {
color: black;
font-size: x-large;
}
</style>
</head>
<body>
<main>
<h1>Welcome Back <%= username %> 👋</h1>
<p>Great to see you again!</p>
<p>Your Verification Code: <b><%= code %></b></p>
<p>Lets get things done and stay on top of your tasks!</p>
</main>
</body>
</html>

View File

@@ -0,0 +1,7 @@
import { HttpException } from "@nestjs/common";
export class ApiError extends HttpException {
constructor(message: string, statusCode: number, data?: any) {
super({ message, data }, statusCode);
}
}

Some files were not shown because too many files have changed in this diff Show More