remove unused modules
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
|
||||
import { CategoryService } from '../providers/category.service';
|
||||
import { CreateCategoryDto } from '../dto/create-category.dto';
|
||||
import { UpdateCategoryDto } from '../dto/update-category.dto';
|
||||
import {
|
||||
ApiTags,
|
||||
ApiOperation,
|
||||
ApiCreatedResponse,
|
||||
ApiOkResponse,
|
||||
ApiNotFoundResponse,
|
||||
ApiParam,
|
||||
ApiBody,
|
||||
ApiBearerAuth,
|
||||
ApiHeader,
|
||||
} from '@nestjs/swagger';
|
||||
import { AdminAuthGuard } from 'src/modules/auth/guards/adminAuth.guard';
|
||||
import { UseGuards } from '@nestjs/common';
|
||||
import { RestId } from 'src/common/decorators';
|
||||
import { Permission } from 'src/common/enums/permission.enum';
|
||||
import { Permissions } from 'src/common/decorators/permissions.decorator';
|
||||
import { API_HEADER_SLUG } from 'src/common/constants';
|
||||
|
||||
@ApiTags('category')
|
||||
@Controller()
|
||||
export class CategoryController {
|
||||
constructor(private readonly categoryService: CategoryService) { }
|
||||
|
||||
@Get('public/categories/restaurant/:slug')
|
||||
@ApiOperation({ summary: 'Get all categories by restaurant slug' })
|
||||
@ApiHeader(API_HEADER_SLUG)
|
||||
@ApiParam({ name: 'slug', required: true, description: 'Restaurant Slug' })
|
||||
@ApiOkResponse({ description: 'List of all categories for the restaurant' })
|
||||
findAllByRestaurant(@Param('slug') slug: string) {
|
||||
return this.categoryService.findAllByRestaurant(slug);
|
||||
}
|
||||
|
||||
/*** Admin ***/
|
||||
|
||||
@ApiOperation({ summary: 'Create category' })
|
||||
@ApiBody({ type: CreateCategoryDto })
|
||||
@Permissions(Permission.MANAGE_CATEGORIES)
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/categories')
|
||||
create(@Body() dto: CreateCategoryDto, @RestId() restId: string) {
|
||||
return this.categoryService.create(restId, dto);
|
||||
}
|
||||
@Permissions(Permission.MANAGE_CATEGORIES)
|
||||
@ApiOperation({ summary: 'my restaurant categories' })
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/categories')
|
||||
findAll(@RestId() restId: string) {
|
||||
return this.categoryService.findAllByRestaurantId(restId);
|
||||
}
|
||||
|
||||
@Permissions(Permission.MANAGE_CATEGORIES)
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/categories/:id')
|
||||
@ApiOperation({ summary: 'Get category' })
|
||||
@ApiParam({ name: 'id', required: true, type: String })
|
||||
findOne(@Param('id') id: string, @RestId() restId: string) {
|
||||
return this.categoryService.findOne(restId, id);
|
||||
}
|
||||
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Permissions(Permission.MANAGE_CATEGORIES)
|
||||
@Patch('admin/categories/:id')
|
||||
@ApiOperation({ summary: 'Update category' })
|
||||
@ApiParam({ name: 'id' })
|
||||
@ApiBody({ type: UpdateCategoryDto })
|
||||
update(@Param('id') id: string, @Body() dto: UpdateCategoryDto, @RestId() restId: string) {
|
||||
return this.categoryService.update(restId, id, dto);
|
||||
}
|
||||
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Permissions(Permission.MANAGE_CATEGORIES)
|
||||
@Delete('admin/categories/:id')
|
||||
@ApiOperation({ summary: 'Delete category' })
|
||||
@ApiParam({ name: 'id' })
|
||||
@ApiOkResponse({ description: 'Deleted' })
|
||||
remove(@Param('id') id: string, @RestId() restId: string) {
|
||||
return this.categoryService.remove(restId, id);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import { Controller, Get, Post, Body, Patch, Param, Delete, Query, UseGuards } from '@nestjs/common';
|
||||
import { productService } from '../providers/product.service';
|
||||
import { CreateproductDto } from '../dto/create-product.dto';
|
||||
import { UpdateproductDto } from '../dto/update-product.dto';
|
||||
import { FindproductsDto } from '../dto/find-products.dto';
|
||||
import {
|
||||
ApiTags,
|
||||
ApiOperation,
|
||||
ApiCreatedResponse,
|
||||
ApiOkResponse,
|
||||
ApiNotFoundResponse,
|
||||
ApiQuery,
|
||||
ApiBody,
|
||||
ApiParam,
|
||||
ApiBearerAuth,
|
||||
ApiHeader,
|
||||
} from '@nestjs/swagger';
|
||||
import { AdminAuthGuard } from 'src/modules/auth/guards/adminAuth.guard';
|
||||
import { RestId, UserId } from 'src/common/decorators';
|
||||
import { AuthGuard } from 'src/modules/auth/guards/auth.guard';
|
||||
import { OptionalAuthGuard } from 'src/modules/auth/guards/optinalAuth.guard';
|
||||
import { API_HEADER_SLUG } from 'src/common/constants';
|
||||
import { Permission } from 'src/common/enums/permission.enum';
|
||||
import { Permissions } from 'src/common/decorators/permissions.decorator';
|
||||
|
||||
@ApiTags('products')
|
||||
@Controller()
|
||||
export class productController {
|
||||
constructor(private readonly productsService: productService) { }
|
||||
|
||||
@Get('public/products/restaurant/:slug')
|
||||
@ApiOperation({ summary: 'Get all products by restaurant slug' })
|
||||
@ApiHeader(API_HEADER_SLUG)
|
||||
@ApiParam({ name: 'slug', required: true, description: 'Restaurant Slug' })
|
||||
findAllByRestaurant(@Param('slug') slug: string) {
|
||||
return this.productsService.findByWeekDateAndMealType(slug);
|
||||
}
|
||||
|
||||
@Get('public/products/:productId')
|
||||
@UseGuards(OptionalAuthGuard)
|
||||
@ApiHeader(API_HEADER_SLUG)
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'Get a product by id' })
|
||||
@ApiParam({ name: 'productId', required: true })
|
||||
findPublicproductById(@Param('productId') productId: string, @UserId() userId?: string): Promise<any> {
|
||||
const a = this.productsService.findPublicById(productId, userId);
|
||||
return a;
|
||||
}
|
||||
|
||||
@Post('public/products/favorite/:productId')
|
||||
@UseGuards(AuthGuard)
|
||||
@ApiHeader(API_HEADER_SLUG)
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'toggle a product as favorite' })
|
||||
@ApiParam({ name: 'productId', required: true })
|
||||
setAsFavorute(@Param('productId') productId: string, @UserId() userId: string) {
|
||||
return this.productsService.toggleFavorite(userId, productId);
|
||||
}
|
||||
|
||||
@Get('public/products/favorite')
|
||||
@UseGuards(AuthGuard)
|
||||
@ApiHeader(API_HEADER_SLUG)
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'get my favorites' })
|
||||
getMyFavorites(@UserId() userId: string, @RestId() restId: string) {
|
||||
return this.productsService.getMyFavorites(userId, restId);
|
||||
}
|
||||
|
||||
/* ---------------------------------- Admin ---------------------------------- */
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Permissions(Permission.MANAGE_productS)
|
||||
@Post('admin/products')
|
||||
@ApiOperation({ summary: 'Create a new product' })
|
||||
@ApiBody({ type: CreateproductDto })
|
||||
create(@Body() createproductDto: CreateproductDto, @RestId() restId: string) {
|
||||
return this.productsService.create(restId, createproductDto);
|
||||
}
|
||||
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Permissions(Permission.MANAGE_productS)
|
||||
@Get('admin/products')
|
||||
@ApiOperation({ summary: 'Get a paginated list of products' })
|
||||
@ApiQuery({ name: 'page', required: false, type: Number })
|
||||
@ApiQuery({ name: 'limit', required: false, type: Number })
|
||||
@ApiQuery({ name: 'search', required: false, type: String })
|
||||
@ApiQuery({ name: 'orderBy', required: false, type: String })
|
||||
@ApiQuery({ name: 'order', required: false, enum: ['asc', 'desc'] })
|
||||
@ApiQuery({ name: 'categoryId', required: false, type: String })
|
||||
@ApiQuery({ name: 'isActive', required: false, type: Boolean })
|
||||
async findAll(@Query() dto: FindproductsDto, @RestId() restId: string) {
|
||||
const result = await this.productsService.findAll(restId, dto);
|
||||
return result;
|
||||
}
|
||||
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Permissions(Permission.MANAGE_productS)
|
||||
@Get('admin/products/:id')
|
||||
@ApiOperation({ summary: 'Get a product by id' })
|
||||
@ApiParam({ name: 'id', required: true })
|
||||
findById(@Param('id') id: string, @RestId() restId: string) {
|
||||
return this.productsService.findAdminById(restId, id);
|
||||
}
|
||||
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Permissions(Permission.MANAGE_productS)
|
||||
@Patch('admin/products/:id')
|
||||
@ApiOperation({ summary: 'Update a product' })
|
||||
@ApiParam({ name: 'id', required: true })
|
||||
@ApiBody({ type: UpdateproductDto })
|
||||
update(@Param('id') id: string, @Body() updateproductDto: UpdateproductDto, @RestId() restId: string) {
|
||||
return this.productsService.update(restId, id, updateproductDto);
|
||||
}
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Permissions(Permission.MANAGE_productS)
|
||||
@Delete('admin/products/:id')
|
||||
@ApiOperation({ summary: 'Delete (soft) a product' })
|
||||
@ApiParam({ name: 'id', required: true })
|
||||
remove(@Param('id') id: string, @RestId() restId: string) {
|
||||
return this.productsService.remove(restId, id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Cron } from '@nestjs/schedule';
|
||||
import { EntityManager } from '@mikro-orm/postgresql';
|
||||
import { Inventory } from '../../inventory/entities/inventory.entity';
|
||||
|
||||
@Injectable()
|
||||
export class productStockCrone {
|
||||
private readonly logger = new Logger(productStockCrone.name);
|
||||
|
||||
constructor(private readonly em: EntityManager) { }
|
||||
|
||||
// run every day at 00:03
|
||||
@Cron('3 0 * * *', {
|
||||
name: 'resetAvailableStock',
|
||||
timeZone: 'UTC',
|
||||
})
|
||||
async handleCron() {
|
||||
try {
|
||||
this.logger.debug('Starting daily inventory reset (availableStock = totalStock)');
|
||||
|
||||
const inventories = await this.em.find(Inventory, {});
|
||||
if (!inventories || inventories.length === 0) {
|
||||
this.logger.debug('No inventory records found to reset');
|
||||
return;
|
||||
}
|
||||
|
||||
this.logger.log(`Resetting available stock for ${inventories.length} inventory records`);
|
||||
|
||||
await this.em.transactional(async em => {
|
||||
for (const inv of inventories) {
|
||||
// reload inside transaction to avoid concurrency issues
|
||||
const record = await em.findOne(Inventory, { id: inv.id });
|
||||
if (!record) continue;
|
||||
record.availableStock = record.totalStock;
|
||||
em.persist(record);
|
||||
}
|
||||
await em.flush();
|
||||
});
|
||||
|
||||
this.logger.log('Daily inventory reset completed');
|
||||
} catch (err) {
|
||||
this.logger.error(`productStockCrone failed: ${err?.message}`, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { IsString, IsOptional, IsBoolean, IsInt, Min } from 'class-validator';
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
|
||||
export class CreateCategoryDto {
|
||||
@IsString()
|
||||
@ApiPropertyOptional({ example: 'ایرانی' })
|
||||
title!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@Type(() => Boolean)
|
||||
@ApiPropertyOptional({ example: true })
|
||||
isActive?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiPropertyOptional({ example: 'https://cdn.example.com/avatar.png' })
|
||||
avatarUrl?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
@Type(() => Number)
|
||||
@ApiPropertyOptional({ example: 1 })
|
||||
order?: number;
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { Type } from 'class-transformer';
|
||||
import {
|
||||
ArrayUnique,
|
||||
IsArray,
|
||||
IsBoolean,
|
||||
IsEnum,
|
||||
IsInt,
|
||||
IsNotEmpty,
|
||||
IsNumber,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Max,
|
||||
Min,
|
||||
} from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { MealType } from '../interface/product.interface';
|
||||
|
||||
export class CreateproductDto {
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
@ApiProperty()
|
||||
categoryId: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiPropertyOptional({ example: 'قرمه سبزی' })
|
||||
title?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiPropertyOptional({ example: 'توضیحات غذا' })
|
||||
desc?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
@ApiPropertyOptional({ type: [String] })
|
||||
content?: string[];
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ArrayUnique()
|
||||
@IsInt({ each: true })
|
||||
@Min(0, { each: true })
|
||||
@Max(6, { each: true })
|
||||
@Type(() => Number)
|
||||
@ApiPropertyOptional({ type: [Number], example: [0, 1, 2, 3, 4, 5, 6] })
|
||||
weekDays?: number[];
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ArrayUnique()
|
||||
@IsEnum(MealType, { each: true })
|
||||
@ApiPropertyOptional({ enum: MealType, isArray: true })
|
||||
mealTypes?: MealType[];
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@Type(() => Number)
|
||||
@ApiPropertyOptional({ example: 120000 })
|
||||
price?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
@Type(() => Number)
|
||||
@ApiPropertyOptional({ example: 15 })
|
||||
prepareTime?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@ApiPropertyOptional({ example: true })
|
||||
@Type(() => Boolean)
|
||||
isActive?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
@ApiPropertyOptional({ type: [String] })
|
||||
images?: string[];
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@ApiPropertyOptional({ example: false })
|
||||
@Type(() => Boolean)
|
||||
inPlaceServe?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@ApiPropertyOptional({ example: false })
|
||||
@Type(() => Boolean)
|
||||
pickupServe?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@Type(() => Number)
|
||||
@ApiPropertyOptional({ example: 0 })
|
||||
discount?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@Type(() => Number)
|
||||
@ApiProperty({ example: 50 })
|
||||
dailyStock: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@ApiPropertyOptional({ example: false })
|
||||
@Type(() => Boolean)
|
||||
isSpecialOffer?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
@Type(() => Number)
|
||||
@ApiPropertyOptional({ example: 1 })
|
||||
order?: number;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { IsOptional, IsNumber, IsString, IsIn, IsBoolean } from 'class-validator';
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
|
||||
export class FindproductsDto {
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Type(() => Number)
|
||||
@ApiPropertyOptional({ example: 1 })
|
||||
page?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Type(() => Number)
|
||||
@ApiPropertyOptional({ example: 10 })
|
||||
limit?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiPropertyOptional()
|
||||
search?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiPropertyOptional({ example: 'createdAt' })
|
||||
orderBy?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(['asc', 'desc'])
|
||||
@ApiPropertyOptional({ example: 'desc' })
|
||||
order?: 'asc' | 'desc';
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiPropertyOptional()
|
||||
categoryId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@Type(() => Boolean)
|
||||
@ApiPropertyOptional({ example: true })
|
||||
isActive?: boolean;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from '@nestjs/swagger';
|
||||
import { CreateCategoryDto } from './create-category.dto';
|
||||
|
||||
export class UpdateCategoryDto extends PartialType(CreateCategoryDto) {}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from '@nestjs/swagger';
|
||||
import { CreateproductDto } from './create-product.dto';
|
||||
|
||||
export class UpdateproductDto extends PartialType(CreateproductDto) { }
|
||||
@@ -0,0 +1,27 @@
|
||||
import { Entity, Index, Property, Collection, OneToMany, ManyToOne } from '@mikro-orm/core';
|
||||
import { product } from './product.entity';
|
||||
import { BaseEntity } from '../../../common/entities/base.entity';
|
||||
import { Restaurant } from 'src/modules/restaurants/entities/restaurant.entity';
|
||||
|
||||
@Entity({ tableName: 'categories' })
|
||||
@Index({ properties: ['restaurant', 'isActive'] })
|
||||
@Index({ properties: ['isActive'] })
|
||||
export class Category extends BaseEntity {
|
||||
@Property()
|
||||
title!: string;
|
||||
|
||||
@OneToMany(() => product, product => product.category)
|
||||
products = new Collection<product>(this);
|
||||
|
||||
@Property({ default: true })
|
||||
isActive: boolean = true;
|
||||
|
||||
@ManyToOne(() => Restaurant)
|
||||
restaurant!: Restaurant;
|
||||
|
||||
@Property({ nullable: true })
|
||||
avatarUrl?: string;
|
||||
|
||||
@Property({ type: 'int', nullable: true })
|
||||
order?: number;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Entity, ManyToOne, Unique } from '@mikro-orm/core';
|
||||
import { BaseEntity } from '../../../common/entities/base.entity';
|
||||
import { User } from '../../user/entities/user.entity';
|
||||
import { product } from '../../products/entities/product.entity';
|
||||
|
||||
@Entity({ tableName: 'favorites' })
|
||||
@Unique({ properties: ['user', 'product'] })
|
||||
export class Favorite extends BaseEntity {
|
||||
@ManyToOne(() => User)
|
||||
user: User;
|
||||
|
||||
@ManyToOne(() => product)
|
||||
product: product;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { Cascade, Collection, Entity, Index, ManyToOne, OneToMany, Property, OneToOne } from '@mikro-orm/core';
|
||||
import { Category } from './category.entity';
|
||||
import { BaseEntity } from '../../../common/entities/base.entity';
|
||||
import { Restaurant } from '../../../modules/restaurants/entities/restaurant.entity';
|
||||
import { Review } from 'src/modules/review/entities/review.entity';
|
||||
import { Inventory } from 'src/modules/inventory/entities/inventory.entity';
|
||||
import { MealType } from '../interface/product.interface';
|
||||
import { Favorite } from './favorite.entity';
|
||||
|
||||
@Entity({ tableName: 'products' })
|
||||
@Index({ properties: ['restaurant', 'isActive'] })
|
||||
@Index({ properties: ['category', 'isActive'] })
|
||||
@Index({ properties: ['isActive'] })
|
||||
export class product extends BaseEntity {
|
||||
@ManyToOne(() => Restaurant)
|
||||
restaurant: Restaurant;
|
||||
|
||||
@ManyToOne(() => Category)
|
||||
category: Category;
|
||||
|
||||
@OneToMany(() => Review, review => review.product, { cascade: [Cascade.ALL], orphanRemoval: true })
|
||||
reviews = new Collection<Review>(this);
|
||||
|
||||
@OneToOne(() => Inventory, {
|
||||
mappedBy: 'product',
|
||||
nullable: true,
|
||||
})
|
||||
inventory?: Inventory;
|
||||
|
||||
@OneToMany(() => Favorite, favorite => favorite.product)
|
||||
favorites = new Collection<Favorite>(this);
|
||||
|
||||
@Property({ nullable: true })
|
||||
title?: string;
|
||||
|
||||
@Property({ type: 'text', nullable: true })
|
||||
desc?: string;
|
||||
|
||||
@Property({ type: 'json', nullable: true })
|
||||
content?: string[];
|
||||
|
||||
@Property({ type: 'decimal', precision: 10, scale: 2, nullable: true })
|
||||
price?: number;
|
||||
|
||||
@Property({ type: 'int', nullable: true })
|
||||
order?: number;
|
||||
|
||||
@Property({ type: 'int', nullable: true })
|
||||
prepareTime?: number; // in minutes
|
||||
|
||||
@Property({ type: 'jsonb', default: [] })
|
||||
weekDays: number[] = [0, 1, 2, 3, 4, 5, 6];
|
||||
|
||||
@Property({ type: 'jsonb', default: [] })
|
||||
mealTypes: MealType[] = [];
|
||||
|
||||
@Property({ type: 'boolean', default: true })
|
||||
isActive: boolean = true;
|
||||
|
||||
@Property({ type: 'json', nullable: true })
|
||||
images?: string[];
|
||||
|
||||
@Property({ type: 'boolean', default: false })
|
||||
inPlaceServe: boolean = false;
|
||||
|
||||
@Property({ type: 'boolean', default: false })
|
||||
pickupServe: boolean = false;
|
||||
|
||||
@Property({ type: 'float', default: null })
|
||||
score?: number | null = null;
|
||||
|
||||
@Property({ type: 'float', default: 0 })
|
||||
discount: number = 0;
|
||||
|
||||
@Property({ type: 'boolean', default: false })
|
||||
isSpecialOffer: boolean = false;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { productService } from './providers/product.service';
|
||||
import { productStockCrone } from './crone/product.crone';
|
||||
import { productController } from './controllers/product.controller';
|
||||
import { CategoryController } from './controllers/category.controller';
|
||||
import { CategoryService } from './providers/category.service';
|
||||
import { productRepository } from './repositories/product.repository';
|
||||
import { CategoryRepository } from './repositories/category.repository';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { Category } from './entities/category.entity';
|
||||
import { product } from './entities/product.entity';
|
||||
import { RestaurantsModule } from '../restaurants/restaurants.module';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { UtilsModule } from '../util/utils.module';
|
||||
import { Favorite } from './entities/favorite.entity';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
MikroOrmModule.forFeature([product, Category, Favorite]),
|
||||
RestaurantsModule,
|
||||
AuthModule,
|
||||
JwtModule,
|
||||
UtilsModule,
|
||||
],
|
||||
controllers: [productController, CategoryController],
|
||||
providers: [productService, CategoryService, productRepository, CategoryRepository, productStockCrone],
|
||||
exports: [productRepository, CategoryRepository],
|
||||
})
|
||||
export class productModule { }
|
||||
@@ -0,0 +1,6 @@
|
||||
export enum MealType {
|
||||
BREAKFAST = 'breakfast',
|
||||
LUNCH = 'lunch',
|
||||
DINNER = 'dinner',
|
||||
SNACK = 'snack',
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { CreateCategoryDto } from '../dto/create-category.dto';
|
||||
import { UpdateCategoryDto } from '../dto/update-category.dto';
|
||||
import { CategoryRepository } from '../repositories/category.repository';
|
||||
import { EntityManager } from '@mikro-orm/postgresql';
|
||||
import { RequiredEntityData } from '@mikro-orm/core';
|
||||
import { Category } from '../entities/category.entity';
|
||||
import { CategoryMessage, RestMessage } from 'src/common/enums/message.enum';
|
||||
import { Restaurant } from 'src/modules/restaurants/entities/restaurant.entity';
|
||||
|
||||
@Injectable()
|
||||
export class CategoryService {
|
||||
constructor(
|
||||
private readonly categoryRepository: CategoryRepository,
|
||||
private readonly em: EntityManager,
|
||||
) { }
|
||||
|
||||
async create(restId: string, dto: CreateCategoryDto): Promise<Category> {
|
||||
const restaurant = await this.em.findOne(Restaurant, { id: restId });
|
||||
if (!restaurant) {
|
||||
throw new NotFoundException(RestMessage.NOT_FOUND);
|
||||
}
|
||||
const data: RequiredEntityData<Category> = {
|
||||
title: dto.title,
|
||||
isActive: dto.isActive ?? true,
|
||||
restaurant: restaurant,
|
||||
avatarUrl: dto.avatarUrl,
|
||||
};
|
||||
|
||||
const category = this.categoryRepository.create(data);
|
||||
await this.em.persistAndFlush(category);
|
||||
return category;
|
||||
}
|
||||
|
||||
async findAllByRestaurant(slug: string): Promise<Category[]> {
|
||||
const restaurant = await this.em.findOne(Restaurant, { slug });
|
||||
if (!restaurant || !restaurant.id) {
|
||||
throw new NotFoundException(RestMessage.NOT_FOUND);
|
||||
}
|
||||
return this.categoryRepository.find({ restaurant: restaurant, isActive: true });
|
||||
}
|
||||
|
||||
async findAllByRestaurantId(restId: string): Promise<Category[]> {
|
||||
return this.categoryRepository.find({ restaurant: { id: restId } });
|
||||
}
|
||||
|
||||
// async findAll(opts?: { restId?: string; isActive?: boolean }): Promise<Category[]> {
|
||||
// const where: FilterQuery<Category> = {};
|
||||
// if (opts?.restId) where.restId = opts.restId;
|
||||
// if (opts && typeof opts.isActive === 'boolean') where.isActive = opts.isActive;
|
||||
// const cats = await this.categoryRepository.find(where, { populate: ['products'] });
|
||||
|
||||
// // Return plain objects to avoid circular references during JSON serialization
|
||||
// return cats.map(cat => ({
|
||||
// id: cat.id,
|
||||
// title: cat.title,
|
||||
// isActive: cat.isActive,
|
||||
// restId: cat.restId,
|
||||
// avatarUrl: cat.avatarUrl,
|
||||
// createdAt: cat.createdAt,
|
||||
// updatedAt: cat.updatedAt,
|
||||
// products: cat.products.getItems().map(f => ({ id: f.id, title: f.title })),
|
||||
// })) as unknown as Category[];
|
||||
// }
|
||||
|
||||
async findOne(restId: string, id: string): Promise<Category> {
|
||||
const cat = await this.categoryRepository.findOne({ id, restaurant: { id: restId } }, { populate: ['products'] });
|
||||
if (!cat) throw new NotFoundException(CategoryMessage.NOT_FOUND);
|
||||
|
||||
return {
|
||||
id: cat.id,
|
||||
title: cat.title,
|
||||
isActive: cat.isActive,
|
||||
restaurant: cat.restaurant,
|
||||
avatarUrl: cat.avatarUrl,
|
||||
createdAt: cat.createdAt,
|
||||
updatedAt: cat.updatedAt,
|
||||
products: cat.products.getItems().map(f => ({ id: f.id, title: f.title })),
|
||||
} as unknown as Category;
|
||||
}
|
||||
|
||||
async findRestaurantCategories(restId: string): Promise<Category> {
|
||||
const cat = await this.categoryRepository.findOne({ restaurant: { id: restId } }, { populate: ['products'] });
|
||||
if (!cat) throw new NotFoundException(CategoryMessage.NOT_FOUND);
|
||||
|
||||
return {
|
||||
id: cat.id,
|
||||
title: cat.title,
|
||||
isActive: cat.isActive,
|
||||
restaurant: cat.restaurant,
|
||||
avatarUrl: cat.avatarUrl,
|
||||
createdAt: cat.createdAt,
|
||||
updatedAt: cat.updatedAt,
|
||||
} as unknown as Category;
|
||||
}
|
||||
|
||||
async update(restId: string, id: string, dto: UpdateCategoryDto): Promise<Category> {
|
||||
const cat = await this.categoryRepository.findOne({ id, restaurant: { id: restId } });
|
||||
if (!cat) throw new NotFoundException(CategoryMessage.NOT_FOUND);
|
||||
this.em.assign(cat, dto);
|
||||
await this.em.persistAndFlush(cat);
|
||||
return cat;
|
||||
}
|
||||
|
||||
async remove(restId: string, id: string): Promise<void> {
|
||||
const cat = await this.categoryRepository.findOne({ id, restaurant: { id: restId } });
|
||||
if (!cat) throw new NotFoundException(CategoryMessage.NOT_FOUND);
|
||||
cat.deletedAt = new Date();
|
||||
await this.em.persistAndFlush(cat);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { CreateproductDto } from '../dto/create-product.dto';
|
||||
import { FindproductsDto } from '../dto/find-products.dto';
|
||||
import { productRepository } from '../repositories/product.repository';
|
||||
import { CategoryRepository } from '../repositories/category.repository';
|
||||
import { EntityManager } from '@mikro-orm/postgresql';
|
||||
import { RequiredEntityData, FilterQuery } from '@mikro-orm/core';
|
||||
import { product } from '../entities/product.entity';
|
||||
import { CategoryMessage, productMessage, RestMessage } from 'src/common/enums/message.enum';
|
||||
import { RestRepository } from 'src/modules/restaurants/repositories/rest.repository';
|
||||
import { CacheService } from '../../util/cache.service';
|
||||
import { Favorite } from '../entities/favorite.entity';
|
||||
import { MealType } from '../interface/product.interface';
|
||||
import { Inventory } from 'src/modules/inventory/entities/inventory.entity';
|
||||
|
||||
@Injectable()
|
||||
export class productService {
|
||||
private readonly productS_BY_RESTAURANT_CACHE_KEY_PREFIX = 'products:restaurant:';
|
||||
private readonly productS_CACHE_TTL = 600; // 10 minutes in seconds
|
||||
|
||||
constructor(
|
||||
private readonly productRepository: productRepository,
|
||||
private readonly categoryRepository: CategoryRepository,
|
||||
private readonly restRepository: RestRepository,
|
||||
private readonly em: EntityManager,
|
||||
private readonly cacheService: CacheService,
|
||||
) { }
|
||||
|
||||
async create(restId: string, createproductDto: CreateproductDto) {
|
||||
const { categoryId, dailyStock = 0, ...rest } = createproductDto;
|
||||
const restaurant = await this.restRepository.findOne({ id: restId });
|
||||
if (!restaurant) {
|
||||
throw new NotFoundException(RestMessage.NOT_FOUND);
|
||||
}
|
||||
const category = await this.categoryRepository.findOne({ id: categoryId, restaurant: { id: restId } });
|
||||
if (!category) {
|
||||
throw new NotFoundException(CategoryMessage.NOT_FOUND);
|
||||
}
|
||||
|
||||
const { product, inventory } = await this.em.transactional(async em => {
|
||||
// prepare data with defaults for required fields so repository.create typing is satisfied
|
||||
const data: RequiredEntityData<product> = {
|
||||
desc: rest.desc,
|
||||
isActive: rest.isActive ?? true,
|
||||
inPlaceServe: rest.inPlaceServe ?? false,
|
||||
pickupServe: rest.pickupServe ?? false,
|
||||
discount: rest.discount ?? 0,
|
||||
isSpecialOffer: rest.isSpecialOffer ?? false,
|
||||
order: rest.order ?? null,
|
||||
// map single-title/content DTO to localized fields
|
||||
title: rest.title,
|
||||
content: rest.content,
|
||||
// numeric/array fields
|
||||
price: rest.price ?? 0,
|
||||
prepareTime: rest.prepareTime ?? 0,
|
||||
images: rest.images ?? undefined,
|
||||
// new fields
|
||||
weekDays: rest.weekDays ?? [0, 1, 2, 3, 4, 5, 6],
|
||||
mealTypes: rest.mealTypes ?? [],
|
||||
restaurant: restaurant,
|
||||
category: category,
|
||||
};
|
||||
|
||||
const product = em.create(product, data);
|
||||
const newInventoryRecord = em.create(Inventory, {
|
||||
product: product,
|
||||
availableStock: dailyStock,
|
||||
totalStock: dailyStock,
|
||||
});
|
||||
|
||||
await em.flush();
|
||||
return { product, inventory: newInventoryRecord };
|
||||
});
|
||||
|
||||
// Re-load created entities with the primary EM to ensure they're attached
|
||||
const savedproduct = product?.id
|
||||
? await this.productRepository.findOne({ id: product.id }, { populate: ['category', 'restaurant'] })
|
||||
: null;
|
||||
const savedInventory = inventory?.id ? await this.em.findOne(Inventory, { id: inventory.id }) : inventory;
|
||||
|
||||
return { product: savedproduct ?? product, inventory: savedInventory ?? inventory };
|
||||
}
|
||||
|
||||
findAll(restId: string, dto: FindproductsDto) {
|
||||
return this.productRepository.findAllPaginated(restId, dto);
|
||||
}
|
||||
|
||||
/**
|
||||
* Public product detail (only active products are visible).
|
||||
*/
|
||||
async findPublicById(productId: string, userId?: string): Promise<any> {
|
||||
const product = await this.productRepository.findOne({ id: productId, isActive: true }, { populate: ['category', 'inventory'] });
|
||||
if (!product) throw new NotFoundException(productMessage.NOT_FOUND);
|
||||
let isFavorite = false;
|
||||
if (userId) {
|
||||
isFavorite = (await this.em.count(Favorite, { user: { id: userId }, product: { id: productId } })) > 0;
|
||||
}
|
||||
return {
|
||||
...product,
|
||||
isFavorite,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Admin product detail (scoped to the authenticated restaurant).
|
||||
*/
|
||||
async findAdminById(restId: string, id: string): Promise<product> {
|
||||
const product = await this.productRepository.findOne({ id, restaurant: { id: restId } }, { populate: ['category', 'inventory'] });
|
||||
|
||||
if (!product) throw new NotFoundException(productMessage.NOT_FOUND);
|
||||
return product;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find active products for a restaurant based on current week day and meal type in Iran timezone.
|
||||
* @param slug - Restaurant slug identifier
|
||||
* @returns Array of active products matching current day and meal time
|
||||
*/
|
||||
async findByWeekDateAndMealType(slug: string): Promise<product[]> {
|
||||
const restaurant = await this.restRepository.findOne({ slug });
|
||||
if (!restaurant) {
|
||||
throw new NotFoundException(RestMessage.NOT_FOUND);
|
||||
}
|
||||
|
||||
const { iranWeekDay, mealType } = this.getCurrentIranTimeContext();
|
||||
|
||||
const queryFilter: FilterQuery<product> = {
|
||||
restaurant: { slug },
|
||||
isActive: true,
|
||||
// weekDays: { $contains: iranWeekDay },
|
||||
// ...(mealType ? { mealTypes: { $contains: mealType } } : {}),
|
||||
} as unknown as FilterQuery<product>;
|
||||
|
||||
return this.productRepository.find(queryFilter, { populate: ['category'] });
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current Iran timezone context (weekday and meal type).
|
||||
* @returns Object containing Iran weekday (0-6, where 0=Saturday) and current meal type
|
||||
*/
|
||||
private getCurrentIranTimeContext(): { iranWeekDay: number; mealType: MealType | null } {
|
||||
const nowInIran = new Date(new Date().toLocaleString('en-US', { timeZone: 'Asia/Tehran' }));
|
||||
const weekDay = nowInIran.getDay(); // 0 = Sunday, 6 = Saturday
|
||||
const currentHour = nowInIran.getHours();
|
||||
|
||||
// Convert to Iran weekday: Saturday=0, Sunday=1, ..., Friday=6
|
||||
// JavaScript: Sunday=0, Monday=1, ..., Saturday=6
|
||||
// Iran week: Saturday=0, Sunday=1, ..., Friday=6
|
||||
const iranWeekDay = (weekDay + 1) % 7;
|
||||
|
||||
const mealType = this.getMealTypeByHour(currentHour);
|
||||
|
||||
return { iranWeekDay, mealType };
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine meal type based on current hour in Iran timezone.
|
||||
* @param hour - Current hour (0-23)
|
||||
* @returns Meal type or null if outside meal hours
|
||||
*/
|
||||
private getMealTypeByHour(hour: number): MealType | null {
|
||||
const MEAL_TIME_RANGES = {
|
||||
BREAKFAST: { start: 6, end: 11 },
|
||||
LUNCH: { start: 11, end: 15 },
|
||||
SNACK: { start: 15, end: 19 },
|
||||
DINNER: { start: 19, end: 24 },
|
||||
} as const;
|
||||
|
||||
if (hour >= MEAL_TIME_RANGES.BREAKFAST.start && hour < MEAL_TIME_RANGES.BREAKFAST.end) {
|
||||
return MealType.BREAKFAST;
|
||||
}
|
||||
if (hour >= MEAL_TIME_RANGES.LUNCH.start && hour < MEAL_TIME_RANGES.LUNCH.end) {
|
||||
return MealType.LUNCH;
|
||||
}
|
||||
if (hour >= MEAL_TIME_RANGES.SNACK.start && hour < MEAL_TIME_RANGES.SNACK.end) {
|
||||
return MealType.SNACK;
|
||||
}
|
||||
if (hour >= MEAL_TIME_RANGES.DINNER.start && hour < MEAL_TIME_RANGES.DINNER.end) {
|
||||
return MealType.DINNER;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async update(restId: string, id: string, dto: Partial<CreateproductDto>): Promise<product> {
|
||||
const { categoryId, dailyStock, ...rest } = dto;
|
||||
const product = await this.productRepository.findOne({ id, restaurant: { id: restId } }, { populate: ['restaurant'] });
|
||||
if (!product) {
|
||||
throw new NotFoundException(productMessage.NOT_FOUND);
|
||||
}
|
||||
|
||||
// attach new categories if provided (adds, does not attempt to preserve/remove existing ones)
|
||||
if (categoryId) {
|
||||
const category = await this.categoryRepository.findOne({ id: categoryId, restaurant: { id: restId } });
|
||||
|
||||
if (!category) {
|
||||
throw new NotFoundException(CategoryMessage.NOT_FOUND);
|
||||
}
|
||||
|
||||
this.em.assign(product, { category: category });
|
||||
}
|
||||
|
||||
// assign other fields from DTO (excluding dailyStock handled below)
|
||||
this.em.assign(product, rest);
|
||||
|
||||
// Persist product and update/create related inventory atomically
|
||||
await this.em.transactional(async em => {
|
||||
await em.persistAndFlush(product);
|
||||
|
||||
if (typeof dailyStock !== 'undefined') {
|
||||
const inventoryRecord = await em.findOne(Inventory, { product: product });
|
||||
if (inventoryRecord) {
|
||||
inventoryRecord.totalStock = dailyStock;
|
||||
} else {
|
||||
em.create(Inventory, {
|
||||
product: product,
|
||||
availableStock: dailyStock,
|
||||
totalStock: dailyStock,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await em.flush();
|
||||
});
|
||||
|
||||
// Re-load the product to ensure populated relations and stable instance
|
||||
const savedproduct = await this.productRepository.findOne({ id: product.id }, { populate: ['category', 'restaurant'] });
|
||||
|
||||
// Invalidate cache for the restaurant if present (optional)
|
||||
// await this.invalidateRestaurantproductsCache(savedproduct?.restaurant?.slug);
|
||||
|
||||
return savedproduct ?? product;
|
||||
}
|
||||
|
||||
async remove(restId: string, id: string): Promise<void> {
|
||||
const product = await this.productRepository.findOne({ id, restaurant: { id: restId } }, { populate: ['restaurant'] });
|
||||
if (!product) {
|
||||
throw new NotFoundException(productMessage.NOT_FOUND);
|
||||
}
|
||||
|
||||
// const restaurantSlug = product.restaurant.slug;
|
||||
product.deletedAt = new Date();
|
||||
await this.em.persistAndFlush(product);
|
||||
|
||||
// Invalidate cache for the restaurant
|
||||
// await this.invalidateRestaurantproductsCache(restaurantSlug);
|
||||
}
|
||||
|
||||
|
||||
async toggleFavorite(userId: string, productId: string) {
|
||||
|
||||
const favorite = await this.em.findOne(Favorite, { user: userId, product: productId });
|
||||
if (favorite) {
|
||||
return this.em.removeAndFlush(favorite);
|
||||
}
|
||||
const newFavorite = this.em.create(Favorite, {
|
||||
user: userId,
|
||||
product: productId,
|
||||
});
|
||||
return this.em.persistAndFlush(newFavorite);
|
||||
}
|
||||
|
||||
|
||||
async getMyFavorites(userId: string, restId: string) {
|
||||
return this.em.find(Favorite, { user: userId, product: { restaurant: { id: restId } } }, { populate: ['product'] });
|
||||
}
|
||||
/**
|
||||
* Invalidate cache for restaurant products
|
||||
*/
|
||||
// private async invalidateRestaurantproductsCache(slug: string): Promise<void> {
|
||||
// const cacheKey = `${this.productS_BY_RESTAURANT_CACHE_KEY_PREFIX}${slug}`;
|
||||
// await this.cacheService.del(cacheKey);
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { EntityManager, EntityRepository } from '@mikro-orm/postgresql';
|
||||
import { Category } from '../entities/category.entity';
|
||||
|
||||
@Injectable()
|
||||
export class CategoryRepository extends EntityRepository<Category> {
|
||||
constructor(readonly em: EntityManager) {
|
||||
super(em, Category);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { EntityManager, EntityRepository } from '@mikro-orm/postgresql';
|
||||
import { FilterQuery } from '@mikro-orm/core';
|
||||
import { product } from '../entities/product.entity';
|
||||
import { PaginatedResult } from 'src/common/interfaces/pagination.interface';
|
||||
|
||||
type FindproductsOpts = {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
search?: string;
|
||||
orderBy?: string;
|
||||
order?: 'asc' | 'desc';
|
||||
categoryId?: string;
|
||||
isActive?: boolean;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class productRepository extends EntityRepository<product> {
|
||||
constructor(readonly em: EntityManager) {
|
||||
super(em, product);
|
||||
}
|
||||
/**
|
||||
* Find products with pagination and optional filters.
|
||||
* Supports: search (title/content), categoryId, isActive, ordering.
|
||||
*/
|
||||
async findAllPaginated(restId: string, opts: FindproductsOpts = {}): Promise<PaginatedResult<product>> {
|
||||
const { page = 1, limit = 10, search, orderBy = 'createdAt', order = 'desc', categoryId, isActive } = opts;
|
||||
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
const where: FilterQuery<product> = { restaurant: { id: restId } };
|
||||
|
||||
if (typeof isActive === 'boolean') {
|
||||
where.isActive = isActive;
|
||||
}
|
||||
|
||||
if (search) {
|
||||
const pattern = `%${search}%`;
|
||||
where.$or = [{ title: { $ilike: pattern } }, { desc: { $ilike: pattern } }];
|
||||
}
|
||||
|
||||
if (categoryId) {
|
||||
// filter by related category (product has a single `category` relation)
|
||||
Object.assign(where, { category: { id: categoryId } } as unknown as FilterQuery<product>);
|
||||
}
|
||||
|
||||
const [data, total] = await this.findAndCount(where, {
|
||||
limit,
|
||||
offset,
|
||||
orderBy: { [orderBy]: order.toLowerCase() as 'asc' | 'desc' },
|
||||
populate: ['category', 'inventory'],
|
||||
});
|
||||
|
||||
const totalPages = Math.ceil(total / limit);
|
||||
|
||||
return {
|
||||
data,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages,
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user