This commit is contained in:
vahidrezvani 2025-07-07 11:12:48 +03:30
commit 25f8bfe69b
88 changed files with 17743 additions and 0 deletions

56
.gitignore vendored Normal file
View File

@ -0,0 +1,56 @@
# compiled output
/dist
/node_modules
/build
# 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

4
.prettierrc Normal file
View File

@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}

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).

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
}
}

14956
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

93
package.json Normal file
View File

@ -0,0 +1,93 @@
{
"name": "fartak",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"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": {
"@aws-sdk/client-s3": "^3.839.0",
"@nestjs-modules/ioredis": "^2.0.2",
"@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.2",
"@nestjs/core": "^11.0.1",
"@nestjs/jwt": "^11.0.0",
"@nestjs/mongoose": "^11.0.3",
"@nestjs/passport": "^11.0.5",
"@nestjs/platform-express": "^11.0.1",
"aws-sdk": "^2.1692.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.2",
"dotenv": "^17.0.0",
"file-type": "^21.0.0",
"ioredis": "^5.6.1",
"mongoose": "^8.16.1",
"multer": "^2.0.1",
"multer-s3": "^3.0.1",
"passport": "^0.7.0",
"passport-google-oauth20": "^2.0.0",
"passport-jwt": "^4.0.1",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"uuid": "^11.1.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",
"@swc/cli": "^0.6.0",
"@swc/core": "^1.10.7",
"@types/express": "^5.0.0",
"@types/jest": "^29.5.14",
"@types/multer": "^1.4.13",
"@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": "^29.7.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",
"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"
}
}

View File

@ -0,0 +1,22 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});

12
src/app.controller.ts Normal file
View File

@ -0,0 +1,12 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}

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

@ -0,0 +1,27 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { SellerModule } from './seller/seller.module';
import { LoginModule } from './login/login.module';
import { AuthModule } from './auth/auth.module';
import { ShopModule } from './shop/shop.module';
import { UploadModule } from './upload/upload.module';
import { MongooseModule } from '@nestjs/mongoose';
import { CategorySchema } from './schemas/category.schema';
import { CategoryModule } from './category/category.module';
import { ConfigModule } from '@nestjs/config';
import { ProductModule } from './product/product.module';
import { DiscountModule } from './discount/discount.module';
import { DiscountTypeModule } from './discount-type/discount-type.module';
@Module({
imports: [
CategoryModule,UploadModule,LoginModule,ShopModule,ProductModule,DiscountModule,
MongooseModule.forRoot('mongodb://localhost/fartak'),
ConfigModule.forRoot({ isGlobal: true }), DiscountTypeModule
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}

8
src/app.service.ts Normal file
View File

@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AuthController } from './auth.controller';
describe('AuthController', () => {
let controller: AuthController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [AuthController],
}).compile();
controller = module.get<AuthController>(AuthController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,6 @@
import { Controller } from '@nestjs/common';
@Controller('auth')
export class AuthController {
}

26
src/auth/auth.module.ts Normal file
View File

@ -0,0 +1,26 @@
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { AuthService } from './auth.service';
import { JwtStrategy } from './jwt.strategy';
import { AuthController } from './auth.controller';
@Module({
imports: [
ConfigModule,
PassportModule,
JwtModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => ({
secret: configService.get<string>('JWT_REFRESH_SECRET'),
signOptions: { expiresIn: '1h'},
}),
}),
],
providers: [AuthService, JwtStrategy],
exports: [AuthService],
controllers: [AuthController],
})
export class AuthModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AuthService } from './auth.service';
describe('AuthService', () => {
let service: AuthService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AuthService],
}).compile();
service = module.get<AuthService>(AuthService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

41
src/auth/auth.service.ts Normal file
View File

@ -0,0 +1,41 @@
// auth.service.ts
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class AuthService {
constructor(private jwtService: JwtService) {}
async generateTokens(payload:any) {
console.log(process.env.JWT_SECRET)
const accessToken = await this.jwtService.signAsync(payload, {
secret: process.env.JWT_SECRET,
expiresIn: '15m',
});
const refreshToken = await this.jwtService.signAsync(payload, {
secret: process.env.JWT_REFRESH_SECRET,
expiresIn: '7d',
});
return {
accessToken,
refreshToken,
};
}
async verifyRefreshToken(token: string) {
return this.jwtService.verifyAsync(token, {
secret: process.env.JWT_REFRESH_SECRET,
});
}
async loginWithGoogle(user: any) {
const payload = { email: user.email, sub: user.email };
return {
access_token: this.jwtService.sign(payload),
user,
};
}
}

View File

@ -0,0 +1,32 @@
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, VerifyCallback } from 'passport-google-oauth20';
import { Injectable } from '@nestjs/common';
import * as dotenv from 'dotenv';
dotenv.config();
@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
constructor() {
super({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: 'http://localhost:3000/auth/google/redirect',
scope: ['email', 'profile'],
});
}
async validate(accessToken: string, refreshToken: string, profile: any, done: VerifyCallback): Promise<any> {
const { name, emails, photos } = profile;
const user = {
email: emails[0].value,
firstName: name.givenName,
lastName: name.familyName,
picture: photos[0].value,
accessToken,
};
done(null, user);
}
}

View File

@ -0,0 +1,5 @@
import { Injectable, ExecutionContext } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}

21
src/auth/jwt.strategy.ts Normal file
View File

@ -0,0 +1,21 @@
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private configService: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: configService.get<string>('JWT_REFRESH_SECRET'),
});
}
async validate(payload: any) {
console.log("payload")
console.log(payload)
return { userId: payload.sellerid};
}
}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { CategoryController } from './category.controller';
describe('CategoryController', () => {
let controller: CategoryController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [CategoryController],
}).compile();
controller = module.get<CategoryController>(CategoryController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,15 @@
import { Body, Controller, Res, Post } from '@nestjs/common';
import { Response } from 'express';
import { CategoryService } from './category.service';
import { CreatCategoryDto } from './dto/creatCategory.dto';
@Controller('category')
export class CategoryController {
constructor(private readonly categoryService: CategoryService) {}
@Post('/add')
async create(@Body() dto: CreatCategoryDto, @Res() res: Response) {
const result = await this.categoryService.creatCategory(dto);
return res.status(result.status).json(result);
}
}

View File

@ -0,0 +1,15 @@
import { Module } from '@nestjs/common';
import { CategoryController } from './category.controller';
import { CategoryService } from './category.service';
import { MongooseModule } from '@nestjs/mongoose';
import {CategorySchema} from '../schemas/category.schema'
@Module({
imports:[
MongooseModule.forFeature([
{ name: 'Category', schema: CategorySchema },
])],
controllers: [CategoryController],
providers: [CategoryService],
exports:[CategoryService]
})
export class CategoryModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { CategoryService } from './category.service';
describe('CategoryService', () => {
let service: CategoryService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [CategoryService],
}).compile();
service = module.get<CategoryService>(CategoryService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,68 @@
import { Injectable } from '@nestjs/common';
import { Category,CategoryDocument} from 'src/schemas/category.schema';
import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose';
import { CreatCategoryDto } from './dto/creatCategory.dto';
import { v4 as uuidv4 } from 'uuid';
import mongoose from 'mongoose';
interface CreateSellerResponse {
message: string;
status: number;
data: any;
}
@Injectable()
export class CategoryService {
constructor(@InjectModel(Category.name) private categoryModel: Model<CategoryDocument>){}
async creatCategory (creatCategory:CreatCategoryDto) : Promise<CreateSellerResponse> {
const newUuid: string = uuidv4();
try{
const newCategory = new this.categoryModel({
Name:creatCategory.Name,
Description:creatCategory.Description,
ID:newUuid
})
const result = newCategory.save()
return{
"message":"دسته بندی جدید با موفقیت ایجاد شد . ",
"status":200,
"data":newCategory
}
}catch(e){
console.log(e)
return{
"message":"دسته بندی جدید ذخیره نشد",
"status":401,
"data":null
}
}
}
async findCategory(id:string) :Promise <CreateSellerResponse> {
const category = await this.categoryModel.findOne({ID:id})
if(category){
return {
"message":"این دسته بندی موجود است",
"status":200,
"data":category
}
}else{
return {
"message":"این دسته بندی وجود ندارد",
"status":404,
"data":null
}
}
}
}

View File

@ -0,0 +1,15 @@
import { IsNotEmpty, IsString } from "class-validator";
export class CreatCategoryDto {
@IsNotEmpty({message:"نام دسته بندی نباید خالی باشد . "})
@IsString({message:"نام دسته بندی باید متن باشد . "})
Name:string;
@IsNotEmpty({message:"نام دسته بندی نباید خالی باشد . "})
@IsString({message:"نام دسته بندی باید متن باشد . "})
Description:string
}

View File

@ -0,0 +1,3 @@
export function generateCode(): string {
return Math.floor(10000 + Math.random() * 90000).toString();
}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { DiscountTypeController } from './discount-type.controller';
describe('DiscountTypeController', () => {
let controller: DiscountTypeController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [DiscountTypeController],
}).compile();
controller = module.get<DiscountTypeController>(DiscountTypeController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,15 @@
import { Body, Controller, Res, Post } from '@nestjs/common';
import { Response } from 'express';
import { DiscountTypeService } from './discount-type.service';
import { CreatDiscountTypeDto } from './dto/discountType.dto';
@Controller('DiscountType')
export class DiscountTypeController {
constructor(private readonly discountTypeService: DiscountTypeService) {}
@Post('/add')
async create(@Body() dto: CreatDiscountTypeDto, @Res() res: Response) {
const result = await this.discountTypeService.creatDiscountType(dto);
return res.status(result.status).json(result);
}
}

View File

@ -0,0 +1,17 @@
import { Module } from '@nestjs/common';
import { DiscountTypeController } from './discount-type.controller';
import { DiscountTypeService } from './discount-type.service';
import { MongooseModule } from '@nestjs/mongoose';
import { DiscountTypeSchema } from 'src/schemas/discountType.schema';
@Module({
imports:[
MongooseModule.forFeature([
{ name: 'DiscountType', schema: DiscountTypeSchema },
])
],
controllers: [DiscountTypeController],
providers: [DiscountTypeService],
exports :[DiscountTypeService]
})
export class DiscountTypeModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { DiscountTypeService } from './discount-type.service';
describe('DiscountTypeService', () => {
let service: DiscountTypeService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [DiscountTypeService],
}).compile();
service = module.get<DiscountTypeService>(DiscountTypeService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,64 @@
import { Injectable } from '@nestjs/common';
import { DiscountType,DiscountTypeDocument} from '../schemas/discountType.schema';
import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose';
import { CreatDiscountTypeDto } from './dto/discountType.dto';
import { CreateSellerResponse } from 'src/interfaces/request';
import { v4 as uuidv4 } from 'uuid';
import mongoose from 'mongoose';
@Injectable()
export class DiscountTypeService {
constructor(@InjectModel(DiscountType.name) private discountTypeModel: Model<DiscountTypeDocument>){}
async creatDiscountType (creatDiscountType:CreatDiscountTypeDto) : Promise<CreateSellerResponse> {
const newUuid: string = uuidv4();
try{
const newDiscountType = new this.discountTypeModel({
Name:creatDiscountType.Name,
Description:creatDiscountType.Description,
ID:newUuid
})
const result = newDiscountType.save()
return{
"message":"دسته بندی تخفیف جدید با موفقیت ایجاد شد . ",
"status":200,
"data":newDiscountType
}
}catch(e){
console.log(e)
return{
"message":"دسته بندی تخفیف جدید ذخیره نشد",
"status":401,
"data":null
}
}
}
async findDiscountType(id:string) :Promise <CreateSellerResponse> {
const category = await this.discountTypeModel.findOne({ID:id})
if(category){
return {
"message":"این دسته بندی تخفبف موجود است",
"status":200,
"data":category
}
}else{
return {
"message":"این دسته بندی تخفیف وجود ندارد",
"status":404,
"data":null
}
}
}
}

View File

@ -0,0 +1,15 @@
import { IsNotEmpty, IsString } from "class-validator";
export class CreatDiscountTypeDto {
@IsNotEmpty({message:"نام دسته بندی نباید خالی باشد . "})
@IsString({message:"نام دسته بندی باید متن باشد . "})
Name:string;
@IsNotEmpty({message:"نام دسته بندی نباید خالی باشد . "})
@IsString({message:"نام دسته بندی باید متن باشد . "})
Description:string
}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { DiscountController } from './discount.controller';
describe('DiscountController', () => {
let controller: DiscountController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [DiscountController],
}).compile();
controller = module.get<DiscountController>(DiscountController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,32 @@
import {
Controller,
Post,
Body,
UseGuards,
Res,
Req,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { DiscountService } from './discount.service';
import { JwtAuthGuard } from 'src/auth/jwt-auth.guard';
import { AuthenticatedRequest } from 'src/interfaces/request';
import { CreateDiscountDto } from './dto/discount.dto';
import { Response } from 'express';
@Controller('discount')
export class DiscountController {
constructor(
private readonly discountService: DiscountService,
) {}
@UseGuards(JwtAuthGuard)
@Post('/add')
async create(
@Body() dto:CreateDiscountDto,
@Req() req: AuthenticatedRequest,
@Res() res: Response,
) {
const creatDiscount = await this.discountService.creatDiscount(dto,req.user.userId);
return res.status(creatDiscount.status).json(creatDiscount);
}
}

View File

@ -0,0 +1,20 @@
import { Module } from '@nestjs/common';
import { DiscountController } from './discount.controller';
import { DiscountService } from './discount.service';
import { MongooseModule } from '@nestjs/mongoose';
import { DiscountSchema } from 'src/schemas/discount.schema';
import { ProductModule } from 'src/product/product.module';
import { ShopModule } from 'src/shop/shop.module';
import { DiscountTypeModule } from 'src/discount-type/discount-type.module';
@Module({
imports:[
MongooseModule.forFeature([
{ name: 'Discount', schema: DiscountSchema },
]),ProductModule,DiscountTypeModule,ShopModule
],
controllers: [DiscountController],
providers: [DiscountService]
})
export class DiscountModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { DiscountService } from './discount.service';
describe('DiscountService', () => {
let service: DiscountService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [DiscountService],
}).compile();
service = module.get<DiscountService>(DiscountService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,119 @@
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Discount, DiscountDocument } from 'src/schemas/discount.schema';
import { Model, Types } from 'mongoose';
import { CategoryService } from 'src/category/category.service';
import { ProductService } from 'src/product/product.service';
import { DiscountTypeService } from 'src/discount-type/discount-type.service';
import { CreateDiscountDto } from './dto/discount.dto';
import { CreateSellerResponse } from 'src/interfaces/request';
import { v4 as uuidv4 } from 'uuid';
import { ShopService } from 'src/shop/shop.service';
@Injectable()
export class DiscountService {
constructor(
@InjectModel(Discount.name)
private readonly discountModel: Model<DiscountDocument>,
private readonly shopService: ShopService,
private readonly productService: ProductService,
private readonly discountTypeService: DiscountTypeService,
) {}
async creatDiscount(
creatDiscountDto: CreateDiscountDto,
user: any,
): Promise<CreateSellerResponse> {
const newUuid: string = uuidv4();
console.log("creatDiscountDto")
console.log(creatDiscountDto)
const existCategory = await this.discountTypeService.findDiscountType(creatDiscountDto.Type);
if (existCategory.status !== 200 || !existCategory.data) {
return {
message: 'نوع تخفیف ثبت نشده است',
status: 404,
data: null,
};
}
const existShop = await this.shopService.findShopSingle(creatDiscountDto.Shop);
if (existShop.status !== 200 || !existShop.data) {
return {
message: 'فروشگاه ثبت نشده است',
status: 404,
data: null,
};
}
if (!existShop.data.Seller) {
return {
message: 'اطلاعات فروشنده فروشگاه ناقص است',
status: 500,
data: null,
};
}
const sellerId = new Types.ObjectId(user);
const shopSellerId = existShop.data.Seller;
if (!sellerId.equals(shopSellerId)) {
return {
message: 'این فروشنده مجاز به ثبت تخفیف برای این فروشگاه نیست',
status: 403,
data: null,
};
}
const existProduct = await this.productService.findProductSingle(creatDiscountDto.Product);
if (existProduct.status !== 200 || !existProduct.data) {
return {
message: 'محصول ثبت نشده است',
status: 404,
data: null,
};
}
if (!existProduct.data.Shop.equals(existShop.data._id)) {
return {
message: 'این محصول در این فروشگاه ثبت نشده است',
status: 400,
data: null,
};
}
try {
const newDiscount = new this.discountModel({
Shop: existShop.data._id,
Product: existProduct.data._id,
Type: existCategory.data._id,
Description: creatDiscountDto.Description,
StartDate: creatDiscountDto.Start,
EndDate: creatDiscountDto.End,
StartTime: creatDiscountDto.StartTime,
EndTime: creatDiscountDto.EndTime,
Radius: Number(creatDiscountDto.Radius),
QRcode: "",
Status: true,
ID: newUuid,
});
await newDiscount.save();
return {
data: newDiscount,
message: 'تخفیف با موفقیت ایجاد شد',
status: 200,
};
} catch (e) {
console.error('Error saving discount:', e);
return {
data: null,
message: 'ثبت تخفیف با شکست مواجه شد',
status: 500,
};
}
}
}

View File

@ -0,0 +1,53 @@
import { IsNotEmpty,IsDateString, IsNumberString, IsString,ArrayMinSize, Matches,Length,ArrayNotEmpty, IsOptional,IsArray,ValidateNested,Validate, IsDate} from 'class-validator';
import { Type } from 'class-transformer';
export class CreateDiscountDto {
@IsNotEmpty({ message: 'شناسه فروشگاه نباید خالی باشد' })
@IsString({ message: 'شناسه فروشگاه باید شامل متن باشد' })
Shop: string;
@IsNotEmpty({ message: 'نوع تخفیف نباید خالی باشد' })
@IsString({ message: 'نوع تخفیف باید شامل متن باشد' })
Type: string;
@IsNotEmpty({ message: 'شناسه محصول نباید خالی باشد' })
@IsString({ message: 'شناسه محصول باید شامل متن باشد' })
Product: string;
@IsNotEmpty({ message: 'توضیحات تخفیف نباید خالی باشد' })
@IsString({ message: 'توضیحات تخفیف باید شامل متن باشد' })
@Length(0, 250, { message: 'طول توضیحات تخفیف حداکثر 250 حرف می تواند باشد' })
Description: string;
@IsNotEmpty({ message: 'تاریخ شروع نباید خالی باشد' })
@IsDateString({},{ message: 'تاریخ شروع باید به فرمت تاریخ باشد' })
Start: string;
@IsNotEmpty({ message: 'تاریخ پایان نباید خالی باشد' })
@IsDateString({},{ message: 'تاریخ پایان باید به فرمت تاریخ باشد' })
End: string;
@IsNotEmpty({ message: 'ساعت شروع نباید خالی باشد' })
@Matches(/^([01]\d|2[0-3]):([0-5]\d)$/, {
message: 'فرمت تایم شروع صحیح نیست',
})
StartTime: string;
@IsNotEmpty({ message: 'ساعت پایان نباید خالی باشد' })
@Matches(/^([01]\d|2[0-3]):([0-5]\d)$/, {
message: 'فرمت تایم پایان صحیح نیست',
})
EndTime: string;
@IsNotEmpty({ message: 'شعاع ارسال اعلان نباید خالی باشد' })
@IsNumberString({},{ message: 'شعاع ارسال اعلان باید شامل عدد باشد' })
Radius: number;
}

13
src/interfaces/request.ts Normal file
View File

@ -0,0 +1,13 @@
import { Request } from "express";
export interface AuthenticatedRequest extends Request {
user: {
userId: string;
};
}
export interface CreateSellerResponse {
message: string;
status: number;
data: any;
}

View File

@ -0,0 +1,21 @@
import { IsNotEmpty, IsNumber, IsNumberString, Length, Matches } from 'class-validator';
export class SendOTPCodeDto {
@IsNotEmpty({ message: 'کد کشور نمی‌تواند خالی باشد.' })
@IsNumberString({},{ message: 'کد کشور باید فقط شامل اعداد باشد.' })
@Length(1, 4, { message: 'کد کشور باید بین 1 تا 4 رقم باشد.' })
Code: number;
@IsNotEmpty({ message: 'شماره تلفن نمی‌تواند خالی باشد.' })
@IsNumberString({},{ message: 'شماره تلفن باید فقط شامل اعداد باشد.' })
@Length(10, 10, { message: 'شماره تلفن باید دقیقاً 10 رقم باشد.' })
Phone: number;
@IsNotEmpty({ message: 'کد ارسالی نمی‌تواند خالی باشد.' })
@IsNumberString({},{ message: 'کد ارسالی باید فقط شامل اعداد باشد.' })
@Length(5, 5, { message: 'عدد باید دقیقاً ۵ رقم باشد' })
OTP: number;
}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { LoginController } from './login.controller';
describe('LoginController', () => {
let controller: LoginController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [LoginController],
}).compile();
controller = module.get<LoginController>(LoginController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,23 @@
import { Body, Controller, Res, Post } from '@nestjs/common';
import { Response } from 'express';
import { LoginService } from './login.service';
import { CreateSellerDto } from '../seller/dto/creat-seller.dto';
import { SendOTPCodeDto } from './dto/sendcode.dto';
@Controller('login')
export class LoginController {
constructor(private readonly loginService:LoginService){}
@Post('/sendcode')
async sendCode(@Body() dto: CreateSellerDto,@Res() res: Response) {
const result = await this.loginService.sendCode(dto);
return res.status(result.status).json(result);
}
@Post('/getcode')
async getcode(@Body() dto: SendOTPCodeDto,@Res() res: Response) {
const result = await this.loginService.getcode(dto);
return res.status(result.status).json(result);
}
}

12
src/login/login.module.ts Normal file
View File

@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { LoginController } from './login.controller';
import { LoginService } from './login.service';
import { SellerService } from 'src/seller/seller.service';
import { AuthModule } from 'src/auth/auth.module';
import { SellerModule } from 'src/seller/seller.module';
@Module({
imports:[SellerModule,AuthModule],
controllers: [LoginController],
providers: [LoginService]
})
export class LoginModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { LoginService } from './login.service';
describe('LoginService', () => {
let service: LoginService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [LoginService],
}).compile();
service = module.get<LoginService>(LoginService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,96 @@
import { Injectable ,NotFoundException} from '@nestjs/common';
import {generateCode} from '../common/helpers/creatcodeotp';
import { CreateSellerDto } from '../seller/dto/creat-seller.dto';
import redis from '../redis/redis.provider';
import { SellerService } from 'src/seller/seller.service';
import {SendOTPCodeDto} from './dto/sendcode.dto'
import { AuthService } from '../auth/auth.service'
interface CreateSellerResponse {
message: string;
status: number;
data: any;
}
@Injectable()
export class LoginService {
constructor(private readonly sellerService: SellerService,private readonly authService: AuthService) {}
async sendCode(createSellerDto: CreateSellerDto): Promise<CreateSellerResponse> {
const code = await generateCode();
console.log(`verified code is : ${code}`);
const getSeller = await this.sellerService.findSellerwidtPhone(createSellerDto.Code,createSellerDto.Phone);
if (!getSeller) {
throw new NotFoundException('User not found');
}
await redis.set(`login-code:${createSellerDto.Phone}`, Number(code), 'EX', 60);
return {
message: 'کد یکبار مصرف ارسال شد',
status: 200,
data: { phone: createSellerDto.Phone }
};
}
async getcode(sendOTPCodeDto: SendOTPCodeDto): Promise<CreateSellerResponse> {
const otpcode = await redis.get(`login-code:${sendOTPCodeDto.Phone}`);
console.log("otpcode")
console.log(otpcode)
if(!otpcode){
return {
"message":"کد یکبار مصرف منقضی شده است",
"status":401,
"data":null
}
}
if(otpcode && Number(otpcode) !== Number(sendOTPCodeDto.OTP)){
return {
"message":"کد یکبار مصرف اشتباه است",
"status":401,
"data":null
}
}
const getSeller = await this.sellerService.findSellerwidtPhone(sendOTPCodeDto.Code,sendOTPCodeDto.Phone);
console.log("getSeller")
console.log(getSeller)
if (!getSeller) {
throw new NotFoundException('User not found');
}
if(getSeller.status == 404){
const creatSeller = await this.sellerService.createWithPhone({Phone:sendOTPCodeDto.Phone,Code:sendOTPCodeDto.Code})
if(creatSeller.status == 200){
console.log("creatSeller")
console.log(creatSeller)
const token = await this.authService.generateTokens({sellerid:creatSeller.data._id,sellerID:creatSeller.data.ID})
return {
"message":"ورود با موفقیت انجام شد",
"status":200,
"data": {
"accessToken":token.accessToken,
"refreshToken":token.refreshToken
}
}
}
}
if(getSeller.status == 200){
// last ip and last login
const token = await this.authService.generateTokens({sellerid:getSeller.data._id,sellerID:getSeller.data.ID})
return {
"message":"ورود با موفقیت انجام شد",
"status":200,
"data": {
"accessToken":token.accessToken,
"refreshToken":token.refreshToken
}
}
}
return {
"message":"خطای ناشناخته",
"status":502,
"data":null
}
}
}

15
src/main.ts Normal file
View File

@ -0,0 +1,15 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
}));
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();

View File

@ -0,0 +1,30 @@
import { IsNotEmpty, IsNumberString, IsString,ArrayMinSize, Length,ArrayNotEmpty, IsOptional,IsArray,ValidateNested,Validate, IsNumber} from 'class-validator';
import { Type } from 'class-transformer';
export class CreatProductDto {
@IsNotEmpty({ message: 'نام محصول نباید خالی باشد' })
@IsString({ message: 'نام محصول باید شامل متن باشد' })
@Length(0, 50, { message: 'طول نام محصول حداکثر 50 حرف می تواند باشد' })
Name: string;
@IsNotEmpty({ message: 'توضیحات محصول نباید خالی باشد' })
@IsString({ message: 'توضیحات محصول باید شامل متن باشد' })
@Length(0, 250, { message: 'طول توضیحات محصول حداکثر 250 حرف می تواند باشد' })
Description: string;
@IsNotEmpty({ message: 'شناسه فروشگاه نباید خالی باشد' })
@IsString({ message: 'شناسه فروشگاه باید شامل متن باشد' })
Shop: string;
@IsNotEmpty({ message: 'قیمت محصول نباید خالی باشد' })
@IsNumberString({},{ message: 'قیمت محصول باید شامل عدد باشد' })
Price: number;
@IsNotEmpty({ message: 'نوع فعالیت نباید خالی باشد' })
@IsString({ message: 'نوع فعالیت باید شامل متن باشد' })
Category: string;
}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ProductController } from './product.controller';
describe('ProductController', () => {
let controller: ProductController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [ProductController],
}).compile();
controller = module.get<ProductController>(ProductController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,69 @@
import {
Controller,
Body,
Post,
UploadedFiles,
UseInterceptors,
Req,
Res,
BadRequestException,
UseGuards,
} from '@nestjs/common';
import { FilesInterceptor } from '@nestjs/platform-express';
import { UploadService } from 'src/upload/upload.service';
import { ProductService } from './product.service';
import { JwtAuthGuard } from 'src/auth/jwt-auth.guard';
import { AuthenticatedRequest } from 'src/interfaces/request';
import { Response } from 'express';
import { CreatProductDto } from './dto/creat-product.dto';
@Controller('product')
export class ProductController {
constructor(
private readonly upload: UploadService,
private readonly productService: ProductService,
) {}
@UseGuards(JwtAuthGuard)
@Post('/add')
@UseInterceptors(
FilesInterceptor('Images', 3, {
limits: {
fileSize: 2 * 1024 * 1024, // 2MB
},
fileFilter: (req, file, cb) => {
const allowedMimeTypes = ['image/png', 'image/jpeg', 'image/jpg'];
if (!allowedMimeTypes.includes(file.mimetype)) {
cb(new BadRequestException('فقط فرمت PNG یا JPG مجاز است'), false);
} else {
cb(null, true);
}
},
}),
)
async create(
@Body() dto:CreatProductDto,
@UploadedFiles() files: Express.Multer.File[],
@Req() req: AuthenticatedRequest,
@Res() res: Response,
) {
let fileIds: string[] = [];
if (files && files.length > 0) {
for (const file of files) {
const result = await this.upload.uploadFileSingle(file);
if (result.status !== 200) {
return res.status(400).json({
message: 'آپلود فایل با خطا مواجه شد',
status: 400,
});
}
fileIds.push(result.data._id);
}
}
const createdProduct = await this.productService.creatProduct(dto,fileIds,req.user.userId)
return res.status(createdProduct.status).json(createdProduct);
}
}

View File

@ -0,0 +1,20 @@
import { Module } from '@nestjs/common';
import { ProductController } from './product.controller';
import {ProductService} from './product.service'
import { ShopModule } from 'src/shop/shop.module';
import { CategoryModule } from 'src/category/category.module';
import { ProductSchema } from 'src/schemas/product.schema';
import mongoose from 'mongoose';
import { MongooseModule } from '@nestjs/mongoose';
import { UploadModule } from 'src/upload/upload.module';
@Module({
imports:[ShopModule,CategoryModule,UploadModule,
MongooseModule.forFeature([
{ name:'Product', schema: ProductSchema },
])
],
controllers: [ProductController],
providers: [ProductService],
exports:[ProductService]
})
export class ProductModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ProductService } from './product.service';
describe('ProductService', () => {
let service: ProductService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [ProductService],
}).compile();
service = module.get<ProductService>(ProductService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,95 @@
import { Injectable } from '@nestjs/common';
import { Product,ProductDocument } from 'src/schemas/product.schema';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { CreatProductDto } from './dto/creat-product.dto';
import { ShopService } from 'src/shop/shop.service';
import { CategoryService } from 'src/category/category.service';
import { v4 as uuidv4 } from 'uuid';
import { CreateSellerResponse } from 'src/interfaces/request';
@Injectable()
export class ProductService {
constructor(
@InjectModel(Product.name) private productModel: Model<ProductDocument>,
private readonly shopService: ShopService,
private readonly categoryService: CategoryService,
) {}
async creatProduct(creatProductDto:CreatProductDto,images:(string[] | null) ,user:any) :Promise<CreateSellerResponse>{
const newUuid: string = uuidv4();
const existcategory = await this.categoryService.findCategory(creatProductDto.Category);
if(existcategory.status !== 200){
return {
"message":"نوع فعالیت ،ثبت نشده است",
"status":404,
"data":null
}
}
const existshop = await this.shopService.findShopSingle(creatProductDto.Shop);
if(existcategory.status !== 200){
return {
"message":"شناسه فروشگاه ،ثبت نشده است",
"status":404,
"data":null
}
}
console.log("images")
console.log(images)
try {
const newProduct = new this.productModel({
Name:creatProductDto.Name,
Description:creatProductDto.Description,
Shop:existshop.data._id,
Images:images,
Price:creatProductDto.Price,
Category:existcategory.data._id,
Comments:[],
Scores:[],
ID:newUuid
})
await newProduct.save()
return {
"message" :"محصول با موفقیت ثبت شد",
"status" : 200,
"data":newProduct.ID
}
}catch(e){
return {
"message" :"ثبت با شکست مواجه شد",
"status" : 500,
"data":e
}
}
}
async findProductSingle(id:string) : Promise<CreateSellerResponse>{
const product = await this.productModel.findOne({ID:id})
if(product){
return {
"message":"محصول ثبت شده است",
"status":200,
"data":product
}
}else {
return {
"message":"محصولی با این شناسه موجود نیست",
"status":404,
"data":null
}
}
}
}

View File

@ -0,0 +1,9 @@
// src/redis.client.ts
import Redis from 'ioredis';
const redis = new Redis({
host: 'localhost', // یا IP سرور Redis
port: 6379, // پورت پیش‌فرض Redis
});
export default redis;

18
src/redis/redis.spec.ts Normal file
View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { Redis } from './redis.provider';
describe('Redis', () => {
let provider: Redis;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [Redis],
}).compile();
provider = module.get<Redis>(Redis);
});
it('should be defined', () => {
expect(provider).toBeDefined();
});
});

View File

@ -0,0 +1,21 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { HydratedDocument } from 'mongoose';
export type CategoryDocument = HydratedDocument<Category>;
@Schema({ timestamps: true })
export class Category {
@Prop({ required: true, unique: true })
Name: string;
@Prop()
Description: string;
@Prop({required:true,unique: true})
ID: string;
}
export const CategorySchema = SchemaFactory.createForClass(Category);
CategorySchema.index({ ID: 1 });

View File

@ -0,0 +1,55 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import mongoose, { HydratedDocument } from 'mongoose';
export type DiscountDocument = HydratedDocument<Discount>;
@Schema({ timestamps: true })
export class Discount {
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Shop', default: null,required:true})
Shop: mongoose.Schema.Types.ObjectId;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Product', default: null,required:true })
Product: mongoose.Schema.Types.ObjectId;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'DiscountType', default: null,required:true })
Type: mongoose.Schema.Types.ObjectId;
@Prop({})
Description: string;
@Prop({required:true})
StartDate:Date
@Prop({required:true})
EndDate:Date
@Prop({required:true})
StartTime:string
@Prop({required:true})
EndTime:string
@Prop({required:true})
Radius:number
@Prop({})
QRcode:string
@Prop({required:true})
Status:boolean
@Prop({required:true,unique:true})
ID:string
}
export const DiscountSchema = SchemaFactory.createForClass(Discount);
DiscountSchema.index({ID:1});

View File

@ -0,0 +1,22 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import mongoose, { HydratedDocument } from 'mongoose';
export type DiscountTypeDocument = HydratedDocument<DiscountType>;
@Schema({ timestamps: true })
export class DiscountType {
@Prop({required:true})
Name: string;
@Prop()
Description: string;
@Prop({required:true,unique: true})
ID: string;
}
export const DiscountTypeSchema = SchemaFactory.createForClass(DiscountType);
DiscountTypeSchema.index({ ID: 1 });

View File

@ -0,0 +1,32 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import mongoose, { HydratedDocument } from 'mongoose';
export type FileDocument = HydratedDocument<File>;
@Schema({ timestamps: true })
export class File {
@Prop({ required: true,enum:['image','video','document']})
FileType: string;
@Prop({required:false})
Title:string
@Prop({required:false})
Description:string
@Prop({required:false})
Format:string
@Prop({required:false})
Url:string
@Prop({required:true,unique:true})
ID:string
}
export const FileSchema = SchemaFactory.createForClass(File);
FileSchema.index({ ID: 1 });

View File

@ -0,0 +1,51 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import mongoose, { HydratedDocument } from 'mongoose';
export type ProductDocument = HydratedDocument<Product>;
@Schema()
class ProductScore {
@Prop()
Score: number;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User', default: null })
User: mongoose.Schema.Types.ObjectId;
}
@Schema({ timestamps: true })
export class Product {
@Prop()
Name: string;
@Prop()
Description: string;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Shop', default: null })
Shop: mongoose.Schema.Types.ObjectId;
@Prop({ type: [mongoose.Schema.Types.ObjectId], ref: 'File', default: [] })
Images: mongoose.Schema.Types.ObjectId[];
@Prop()
Price: number;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Category', default: null })
Category: mongoose.Schema.Types.ObjectId;
@Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comments', default: [] }] })
Comments: mongoose.Schema.Types.ObjectId[];
@Prop({ type: [ProductScore], default: [] })
Scores: ProductScore[];
@Prop({required:true,unique:true})
ID:string
}
export const ProductSchema = SchemaFactory.createForClass(Product);
ProductSchema.index({ID:1});

View File

@ -0,0 +1,20 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import mongoose, { HydratedDocument } from 'mongoose';
export type ReservationDocument = HydratedDocument<Reservation>;
@Schema({ timestamps: true })
export class Reservation {
@Prop({type:mongoose.Schema.Types.ObjectId,ref:'Discount',required:true})
Discount: mongoose.Schema.Types.ObjectId;
@Prop({type:mongoose.Schema.Types.ObjectId,ref:'User',required:true})
User: mongoose.Schema.Types.ObjectId;
@Prop({required:true})
Status:Boolean
}
export const ReservationSchema = SchemaFactory.createForClass(Reservation);

View File

@ -0,0 +1,40 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import mongoose, { HydratedDocument } from 'mongoose';
export type SellerDocument = HydratedDocument<Seller>;
@Schema({ timestamps: true })
export class Seller {
@Prop({ unique: true })
Email: string;
@Prop({ unique: true })
ID: string;
@Prop({ required: true, unique: true })
Phone: number;
@Prop({ required: false })
verify: boolean;
@Prop({ required: false })
VerifyCode: number;
@Prop({ required: false })
VerifyTime: Date;
@Prop({ default: null })
LastLogin: Date;
@Prop({ default: null })
IpAddress: string;
@Prop({ type: { type: mongoose.Schema.Types.ObjectId, ref: 'Shop' } })
Shops: mongoose.Schema.Types.ObjectId;
@Prop()
CountryCode: number;
}
export const SellerSchema = SchemaFactory.createForClass(Seller);

View File

@ -0,0 +1,97 @@
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import mongoose, { HydratedDocument } from 'mongoose';
import { Document } from 'mongoose';
export type ShopDocument = HydratedDocument<Shop>;
@Schema()
class ShopSchedule {
@Prop({enum:['Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']})
Day: string;
@Prop()
StartTime: string;
@Prop()
EndTime: string;
@Prop()
Status: boolean;
}
@Schema({ timestamps: true })
export class Shop {
@Prop({required:true})
Name: string;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Seller', default: null })
Seller: mongoose.Schema.Types.ObjectId;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Category', default: null })
Category: mongoose.Schema.Types.ObjectId;
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'File', default: null })
Logo: mongoose.Schema.Types.ObjectId | null;
@Prop()
Address: string;
@Prop({
type: {
type: String,
enum: ['Point'],
required: true,
default: 'Point',
},
coordinates: {
type: [Number],
required: true,
},
})
Map: {
type: 'Point';
coordinates: [number, number];
};
@Prop([String])
Property: string[];
@Prop()
BusinessLicense: number;
@Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Product' }], default: [] })
Products: mongoose.Schema.Types.ObjectId[] ;
@Prop()
City: string;
@Prop()
Province: string;
@Prop()
PostalCode: number;
@Prop()
ShopNumber: number;
@Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'File' }], default: [] })
Images: mongoose.Schema.Types.ObjectId[];
@Prop({ type: [ShopSchedule], default: [] })
Schedule: ShopSchedule[];
@Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'ProductDiscount' }], default: [] })
Discounts: mongoose.Schema.Types.ObjectId[];
@Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Order' }], default: [] })
Orders: mongoose.Schema.Types.ObjectId[];
@Prop({required:true,unique:true})
ID:string
}
export const ShopSchema = SchemaFactory.createForClass(Shop);
ShopSchema.index({ Map: '2dsphere' ,ID:1});

View File

@ -0,0 +1,13 @@
import { IsNotEmpty, IsNumberString, Length, Matches } from 'class-validator';
export class CreateSellerDto {
@IsNotEmpty({ message: 'کد کشور نمی‌تواند خالی باشد.' })
@IsNumberString({},{ message: 'کد کشور باید فقط شامل اعداد باشد.' })
@Length(1, 4, { message: 'کد کشور باید بین 1 تا 4 رقم باشد.' })
Code: number;
@IsNotEmpty({ message: 'شماره تلفن نمی‌تواند خالی باشد.' })
@IsNumberString({},{ message: 'شماره تلفن باید فقط شامل اعداد باشد.' })
@Length(10, 10, { message: 'شماره تلفن باید دقیقاً 10 رقم باشد.' })
Phone: number;
}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { SellerController } from './seller.controller';
describe('SellerController', () => {
let controller: SellerController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [SellerController],
}).compile();
controller = module.get<SellerController>(SellerController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,4 @@
import { Controller } from '@nestjs/common';
@Controller('seller')
export class SellerController {}

View File

@ -0,0 +1,16 @@
import { Module } from '@nestjs/common';
import { SellerController } from './seller.controller';
import { SellerService } from './seller.service';
import { MongooseModule } from '@nestjs/mongoose';
import { SellerSchema } from 'src/schemas/seller.schema';
@Module({
imports:[
MongooseModule.forFeature([
{ name:'Seller', schema: SellerSchema },
])],
controllers: [SellerController],
providers: [SellerService],
exports:[SellerService]
})
export class SellerModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { SellerService } from './seller.service';
describe('SellerService', () => {
let service: SellerService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [SellerService],
}).compile();
service = module.get<SellerService>(SellerService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,113 @@
import { Injectable, NotFoundException, InternalServerErrorException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Seller, SellerDocument } from '../schemas/seller.schema';
import { CreateSellerDto } from './dto/creat-seller.dto';
import { v4 as uuidv4 } from 'uuid';
interface CreateSellerResponse {
message: string;
status: number;
data: any;
}
@Injectable()
export class SellerService {
constructor(
@InjectModel(Seller.name) private sellerModel: Model<SellerDocument>,
) {}
async createWithPhone(createSellerDto: CreateSellerDto): Promise<CreateSellerResponse> {
const newUuid: string = uuidv4();
try {
const createdSeller = new this.sellerModel({
"Email": null,
"ID": newUuid,
"Phone": createSellerDto.Phone,
"verify": false,
"VerifyCode": null,
"VerifyTime": null,
"LastLogin": null,
"IpAddress": null,
"Shops": [],
"CountryCode": 98
});
const savedSeller = await createdSeller.save();
return {
"message": "فروشنده با موفقیت ساخته شد",
"status": 200,
"data": {
"_id":createdSeller._id,
"ID":createdSeller.ID
}
};
} catch (e) {
console.error("Error saving seller:", e);
throw new InternalServerErrorException("ذخیره دیتا با شکست مواجه شد");
}
}
async findSellerwidtID(id: string): Promise<CreateSellerResponse> {
try {
const seller = await this.sellerModel.findOne({ ID: id }).exec();
if (!seller) {
return {
"message" : "فروشنده ای با این شناسه ایدی موجود نیست",
"status":404,
"data":null
}
}
return {
"message":"اطلاعات فروشنده",
"status":200,
"data":{
"ID":seller.ID,
"Phone":seller.Phone
}
}
} catch (e) {
console.error("Error finding seller:", e);
return {
"message":"خطا در دریافت اطلاعات فروشنده",
"status":502,
"data":null
}
}
}
async findSellerwidtPhone(code:number,phone:number): Promise<CreateSellerResponse> {
try {
const seller = await this.sellerModel.findOne({CountryCode: code,Phone:phone }).exec();
if (!seller) {
return {
"message" : "فروشنده ای با این شناسه ایدی موجود نیست",
"status":404,
"data":null
}
}
return {
"message":"اطلاعات فروشنده",
"status":200,
"data":{
"ID":seller.ID,
"Phone":seller.Phone,
"_id":seller._id
}
}
} catch (e) {
console.error("Error finding seller:", e);
return {
"message":"خطا در دریافت اطلاعات فروشنده",
"status":502,
"data":null
}
}
}
}

View File

@ -0,0 +1,26 @@
import { IsNotEmpty, IsNumberString, IsString, Length, Matches,IsIn, IsNumber ,IsBoolean} from 'class-validator';
export class ScheduleShop {
@IsNotEmpty({ message: 'روز هفته نباید خالی باشد' })
@IsIn(['Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], {
message: 'روز هفته معتبر نیست',
})
Day: string;
@IsNotEmpty({ message: 'ساعت شروع نباید خالی باشد' })
@Matches(/^([01]\d|2[0-3]):([0-5]\d)$/, {
message: 'فرمت تایم شروع صحیح نیست',
})
StartTime: string;
@IsNotEmpty({ message: 'تایم پایان نباید خالی باشد' })
@Matches(/^([01]\d|2[0-3]):([0-5]\d)$/, {
message: 'فرمت تایم پایان صحیح نیست',
})
EndTime: string;
@IsNotEmpty({ message: 'وضعیت فروشگاه نباید خالی باشد' })
@IsBoolean({ message: 'وضعیت فروشگاه باید باز یا بسته باشد' })
Status: Boolean;
}

View File

@ -0,0 +1,16 @@
import { IsString, IsNumber, IsArray, IsOptional, ValidateNested, Min, Max, ArrayMinSize } from 'class-validator';
import { Type } from 'class-transformer';
export class CoordinateDto {
@Type(() => Number)
@IsNumber()
@Min(-180)
@Max(180)
longitude: number;
@Type(() => Number)
@IsNumber()
@Min(-90)
@Max(90)
latitude: number;
}

View File

@ -0,0 +1,75 @@
import { IsNotEmpty, IsNumberString, IsString,ArrayMinSize, Length,ArrayNotEmpty, IsOptional,IsArray,ValidateNested,Validate} from 'class-validator';
import { Type } from 'class-transformer';
import {ScheduleShop} from './Schedule.dto'
import { CoordinateDto } from './coordinate.dto';
import { IsScheduleValid } from './validate-schedule-array';
import { IsCategoryExists } from './validate-category';
export class CreateShopDto {
@IsNotEmpty({ message: 'نام فروشگاه نباید خالی باشد' })
@IsString({ message: 'نام فروشگاه باید شامل متن باشد' })
@Length(0, 30, { message: 'طول نام فروشگاه حداکثر 30 حرف می تواند باشد' })
Name: string;
@IsNotEmpty({ message: 'نوع فعالیت نباید خالی باشد' })
@IsString({ message: 'نوع فعالیت باید شامل متن باشد' })
//@Validate(IsCategoryExists)
Category: string;
@IsNotEmpty({ message: 'نام استان نباید خالی باشد' })
@IsString({ message: 'نام استان باید شامل متن باشد' })
@Length(0, 20, { message: 'طول نام استان حداکثر 20 حرف می تواند باشد' })
Province: string;
@IsNotEmpty({ message: 'نام شهر نباید خالی باشد' })
@IsString({ message: 'نام شهر باید شامل متن باشد' })
@Length(0, 20, { message: 'طول نام شهر حداکثر 20 حرف می تواند باشد' })
City: string;
@IsNotEmpty({ message: 'آدرس فروشگاه نباید خالی باشد' })
@IsString({ message: 'آدرس فروشگاه باید شامل متن باشد' })
@Length(0, 100, { message: 'طول آدرس حداکثر 100 حرف می تواند باشد' })
Address: string;
@IsArray({ message: 'ویژگی‌ها باید به صورت آرایه باشند' })
@ArrayNotEmpty({ message: 'ویژگی‌ها نمی‌توانند خالی باشند' })
@ArrayMinSize(1, { message: 'حداقل باید یک ویژگی وارد شود' })
@IsString({ each: true, message: 'تمام ویژگی‌ها باید رشته باشند' })
Property: string[];
@IsOptional()
@IsNumberString({},{ message: 'شماره تلفن باید فقط شامل اعداد باشد.' })
@Length(1, 12, { message: 'شماره تلفن باید حداکثر 12 رقم باشد.' })
ShopNumber: string;
@IsNotEmpty({message: 'کد پستی نباید خالی باشد.'})
@IsNumberString({},{ message: 'کد پستی باید فقط شامل اعداد باشد.' })
PostalCode: string;
@IsArray()
@ValidateNested({ each: true })
@Type(() => ScheduleShop)
@Validate(IsScheduleValid, {
message: 'تایم کاری تکراری است یا زمان پایان باید بزرگتر از زمان شروع باشد.',
})
Schedule: ScheduleShop[];
@IsOptional()
@IsNumberString({},{ message: 'شماره جواز کسب باید فقط شامل اعداد باشد.' })
@Length(1, 12, { message: 'شماره جواز کسب باید حداکثر 12 رقم باشد.' })
BusinessLicense: string;
@ValidateNested()
@Type(() => CoordinateDto)
Coordinates: CoordinateDto;
}

View File

@ -0,0 +1,22 @@
import {
ValidatorConstraint,
ValidatorConstraintInterface,
ValidationArguments,
} from 'class-validator';
import { Injectable } from '@nestjs/common';
import { CategoryService } from 'src/category/category.service';
@ValidatorConstraint({ async: true })
@Injectable()
export class IsCategoryExists implements ValidatorConstraintInterface {
constructor(private readonly categoryService: CategoryService) {}
async validate(categoryId: string): Promise<boolean> {
const result = await this.categoryService.findCategory(categoryId);
return result.status === 200;
}
defaultMessage(args: ValidationArguments): string {
return 'نوع فعالیت ثبت نشده است';
}
}

View File

View File

@ -0,0 +1,45 @@
import {
ValidatorConstraint,
ValidatorConstraintInterface,
ValidationArguments,
} from 'class-validator';
@ValidatorConstraint({ name: 'isScheduleValid', async: false })
export class IsScheduleValid implements ValidatorConstraintInterface {
validate(schedules: any[], args: ValidationArguments) {
console.log("schedules")
console.log(schedules)
if (typeof schedules === 'string') {
schedules = JSON.parse(schedules);
}
if (!Array.isArray(schedules)) return false;
const days = ['Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
for (const day of days) {
const count = schedules.filter(s => s.Day === day).length;
if (count > 1) return false;
}
console.log(schedules[0])
for (var schedule of schedules) {
if (typeof schedule === 'string') {
schedule = JSON.parse(schedule);
}
const start = this.convertToMinutes(schedule.StartTime);
const end = this.convertToMinutes(schedule.EndTime);
if (end <= start) return false;
}
return true;
}
defaultMessage(args: ValidationArguments) {
return 'تایم کاری تکراری است یا زمان پایان باید بزرگتر از زمان شروع باشد.';
}
private convertToMinutes(time: string): number {
const [hours, minutes] = time.split(':').map(Number);
return hours * 60 + minutes;
}
}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ShopController } from './shop.controller';
describe('ShopController', () => {
let controller: ShopController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [ShopController],
}).compile();
controller = module.get<ShopController>(ShopController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,73 @@
import {
Controller,
Post,
UploadedFile,
UseInterceptors,
Body,
UseGuards,
Res,
Req,
BadRequestException,
} from '@nestjs/common';
import { Response } from 'express';
import { UploadService } from '../upload/upload.service';
import { ShopService } from './shop.service';
import { JwtAuthGuard } from 'src/auth/jwt-auth.guard';
import { CreateShopDto } from './dto/creat-shop.dto';
import { FileInterceptor } from '@nestjs/platform-express';
import { AuthenticatedRequest } from 'src/interfaces/request';
@Controller('shop')
export class ShopController {
constructor(
private readonly upload: UploadService,
private readonly shopService: ShopService,
) {}
@UseGuards(JwtAuthGuard)
@Post('/add')
@UseInterceptors(
FileInterceptor('Logo', {
limits: {
fileSize: 2 * 1024 * 1024, // 2MB
},
fileFilter: (req, file, cb) => {
const allowedMimeTypes = ['image/png', 'image/jpeg', 'image/jpg'];
if (!allowedMimeTypes.includes(file.mimetype)) {
cb(new BadRequestException('فقط فرمت PNG یا JPG مجاز است'), false);
} else {
cb(null, true);
}
},
}),
)
async create(
@Body() body:any,
@UploadedFile() file: Express.Multer.File,
@Req() req: AuthenticatedRequest,
@Res() res: Response,
) {
const shopData : CreateShopDto = {
...body,
Coordinates :JSON.parse(body.Coordinates),
Schedule :JSON.parse(body.Schedule),
Property:JSON.parse(body.Property)
}
let fileId: string | null = null;
if (file) {
const result = await this.upload.uploadFileSingle(file);
if (result.status !== 200) {
return res.status(400).json({
message: 'آپلود لوگو با خطا مواجه شد',
status: 400,
});
}
fileId = result.data._id;
}
const createdShop = await this.shopService.creatshop(shopData, fileId, req.user.userId);
return res.status(createdShop.status).json(createdShop);
}
}

22
src/shop/shop.module.ts Normal file
View File

@ -0,0 +1,22 @@
import { Module } from '@nestjs/common';
import { ShopService } from './shop.service';
import { ShopController } from './shop.controller';
import { MongooseModule } from '@nestjs/mongoose';
import { ShopSchema } from 'src/schemas/shop.schema';
import { UploadModule } from 'src/upload/upload.module';
import { AuthModule } from 'src/auth/auth.module';
import { CategoryModule } from 'src/category/category.module';
@Module({
imports:[
CategoryModule,
AuthModule,
UploadModule,
MongooseModule.forFeature([
{ name:'Shop', schema: ShopSchema },
])
],
providers: [ShopService],
controllers: [ShopController],
exports:[ShopService]
})
export class ShopModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ShopService } from './shop.service';
describe('ShopService', () => {
let service: ShopService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [ShopService],
}).compile();
service = module.get<ShopService>(ShopService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

123
src/shop/shop.service.ts Normal file
View File

@ -0,0 +1,123 @@
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, ObjectId } from 'mongoose';
import { Shop,ShopDocument } from 'src/schemas/shop.schema';
import { CreateShopDto } from './dto/creat-shop.dto';
import { CreateSellerResponse } from 'src/interfaces/request';
import { CategoryService } from 'src/category/category.service';
import { v4 as uuidv4 } from 'uuid';
@Injectable()
export class ShopService {
constructor(@InjectModel(Shop.name) private shopModel: Model<ShopDocument>,
private readonly categoryService:CategoryService, ){}
async creatshop(creatshopDto:CreateShopDto,image:(string | null) ,user:any) : Promise<CreateSellerResponse> {
const newUuid: string = uuidv4();
const existcategory = await this.categoryService.findCategory(creatshopDto.Category);
if(existcategory.status !== 200){
return {
"message":"نوع فعالیت ،ثبت نشده است",
"status":404,
"data":null
}
}
try {
const newShop = new this.shopModel({
"Name":creatshopDto.Name,
"Seller":user,
"Category":existcategory.data._id,
"Logo":image,
"Address":creatshopDto.Address,
"Map":{
"type":'Point',
"coordinates":[creatshopDto.Coordinates.latitude,creatshopDto.Coordinates.latitude]
},
"Property":creatshopDto.Property,
"BusinessLicense":creatshopDto.BusinessLicense,
"Products":[],
"City":creatshopDto.City,
"Province":creatshopDto.Province,
"PostalCode":creatshopDto.PostalCode,
"ShopNumber":creatshopDto.ShopNumber,
"Images":null,
"Schedule":creatshopDto.Schedule,
"Discounts":[],
"Orders":[],
"ID":newUuid
})
console.log("newShop")
console.log(newShop)
await newShop.save()
return{
"data":{
"ID":newUuid
},
"message":"فروشگاه با موفقیت ایجاد شد",
"status":200
}
}catch(e){
console.log(e)
return{
"data":null,
"message":"ثبت فروشگاه با شکست مواجه شد",
"status":500
}
}
/*
//check schedule
['Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'].forEach(element=>{
let result = creatshopDto.Schedule.filter((el)=>{el.Day === element})
if(result.length>1){
return {
"message":"تایم کاری تکراری ثبت شده است. ",
"status":404,
"data":null
}
}
})
creatshopDto.Schedule.forEach(element => {
const start = this.convertToMinutes(element.StartTime);
const end = this.convertToMinutes(element.EndTime);
if (end <= start) {
return {
"message":"تایم کاری شروع نباید بزرگتر از تایم کاری پایان باشد . ",
"status":404,
"data":null
}
}
});
*/
}
async findShopSingle(id:string) : Promise<CreateSellerResponse>{
const shop = await this.shopModel.findOne({ID:id})
if(shop){
return {
"message":"فروشگاه ثبت شده است",
"status":200,
"data":shop
}
}else {
return {
"message":"فروشگاهی با این شناسه موجود نیست",
"status":404,
"data":null
}
}
}
}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UploadController } from './upload.controller';
describe('UploadController', () => {
let controller: UploadController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [UploadController],
}).compile();
controller = module.get<UploadController>(UploadController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,18 @@
import { Body,Post,Controller ,Res,UseInterceptors ,UploadedFile} from '@nestjs/common';
import { UploadService } from './upload.service';
import { FileInterceptor } from '@nestjs/platform-express';
import { Response } from 'express';
@Controller('upload')
export class UploadController {
constructor(private readonly uploadService:UploadService){}
@Post()
@UseInterceptors(FileInterceptor('file'))
async uploadfiles (@UploadedFile() file: Express.Multer.File,@Res() res: Response) {
const result = await this.uploadService.uploadFileSingle(file);
return res.status(result.status).json(result);
}
}

View File

@ -0,0 +1,19 @@
import { Module } from '@nestjs/common';
import { UploadService } from './upload.service';
import { UploadController } from './upload.controller';
import { FileSchema } from 'src/schemas/file.schema';
import { MongooseModule } from '@nestjs/mongoose';
import { ConfigModule } from '@nestjs/config';
import { ConfigService } from '@nestjs/config';
@Module({
imports:[
ConfigModule,
MongooseModule.forFeature([
{ name: 'File', schema: FileSchema },
])],
providers: [UploadService,ConfigService],
controllers: [UploadController],
exports: [UploadService],
})
export class UploadModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UploadService } from './upload.service';
describe('UploadService', () => {
let service: UploadService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [UploadService],
}).compile();
service = module.get<UploadService>(UploadService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,116 @@
// src/s3/s3.service.ts
import { Injectable } from '@nestjs/common';
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import { ConfigService } from '@nestjs/config';
import { v4 as uuidv4 } from 'uuid';
import { extname } from 'path';
import {File,FileDocument} from '../schemas/file.schema'
import { InjectModel } from '@nestjs/mongoose';
import {Model} from 'mongoose'
interface CreateSellerResponse {
message: string;
status: number;
data: any;
}
@Injectable()
export class UploadService {
private s3: S3Client;
private bucket: string;
private region: string;
private endpoint: string;
constructor(private configService: ConfigService,
@InjectModel(File.name) private fileModel: Model<FileDocument>,
) {
const accessKeyId = configService.get<string>('LIARA_ACCESS_KEY');
const secretAccessKey = configService.get<string>('LIARA_SECRET_KEY');
const region = configService.get<string>('LIARA_REGION') || 'default';
const endpoint = configService.get<string>('LIARA_ENDPOINT');
const bucket = configService.get<string>('LIARA_BUCKET_NAME');
if (!accessKeyId || !secretAccessKey || !bucket || !endpoint) {
throw new Error('Missing Liara S3 configuration');
}
this.bucket = bucket;
this.region = region;
this.endpoint = endpoint;
this.s3 = new S3Client({
region: this.region,
endpoint: this.endpoint,
forcePathStyle: true,
credentials: {
accessKeyId,
secretAccessKey,
},
});
}
async uploadFileSingle(file: Express.Multer.File): Promise<CreateSellerResponse> {
const key :string = uuidv4();
const extension = extname(file.originalname);
const urlFile = `${this.endpoint}/${this.bucket}/${key}${extension}`;
const keyWithExt = `${key}${extension}`;
const command = new PutObjectCommand({
Bucket: this.bucket,
Key: keyWithExt,
Body: file.buffer,
ContentType: file.mimetype,
});
await this.s3.send(command);
const mimeType = file.mimetype;
let fileType: 'image' | 'video' | 'document' | 'other' = 'other';
if (mimeType.startsWith('image/')) {
fileType = 'image';
} else if (mimeType.startsWith('video/')) {
fileType = 'video';
} else if (
mimeType === 'application/pdf' ||
mimeType === 'application/msword' ||
mimeType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
) {
fileType = 'document';
}
try {
const newFile = new this.fileModel({
"FileType":fileType,
"Title":"avatar",
"Description" : "avatar",
"Format":mimeType,
"Url":urlFile,
"ID":key
})
const savedSeller = await newFile.save();
return {
"message":"فایل با موفقیت آپلود شد .",
"status":200,
"data":{
"ID":key,
"Url":urlFile,
"_id":newFile._id
}
}
}
catch(e){
return {
"message":"آپلود فایل با شکست مواجه شد",
"status":502,
"data":null
}
}
}
}

25
test/app.e2e-spec.ts Normal file
View File

@ -0,0 +1,25 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { App } from 'supertest/types';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication<App>;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
});

9
test/jest-e2e.json Normal file
View File

@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}

4
tsconfig.build.json Normal file
View File

@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

21
tsconfig.json Normal file
View File

@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2023",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": true,
"forceConsistentCasingInFileNames": true,
"noImplicitAny": false,
"strictBindCallApply": false,
"noFallthroughCasesInSwitch": false
}
}