crud product

This commit is contained in:
2026-01-13 18:19:51 +03:30
parent 984b889587
commit 6522acff5f
27 changed files with 333 additions and 1080 deletions
@@ -6,9 +6,6 @@ import { FindproductsDto } from '../dto/find-products.dto';
import {
ApiTags,
ApiOperation,
ApiCreatedResponse,
ApiOkResponse,
ApiNotFoundResponse,
ApiQuery,
ApiBody,
ApiParam,
@@ -16,10 +13,8 @@ import {
ApiHeader,
} from '@nestjs/swagger';
import { AdminAuthGuard } from 'src/modules/auth/guards/adminAuth.guard';
import { RestId, UserId } from 'src/common/decorators';
import { 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';
@@ -28,53 +23,27 @@ import { Permissions } from 'src/common/decorators/permissions.decorator';
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;
}
// @Get('public/products/:productId')
// @UseGuards()
// @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')
@Post('admin/product')
@ApiOperation({ summary: 'Create a new product' })
@ApiBody({ type: CreateproductDto })
create(@Body() createproductDto: CreateproductDto, @RestId() restId: string) {
return this.productsService.create(restId, createproductDto);
create(@Body() createproductDto: CreateproductDto) {
return this.productsService.create(createproductDto);
}
@UseGuards(AdminAuthGuard)
@@ -89,19 +58,19 @@ export class productController {
@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);
async findAll(@Query() dto: FindproductsDto) {
const result = await this.productsService.findAll(dto);
return result;
}
@Get('admin/products/:id')
@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);
findById(@Param('id') id: string,) {
return this.productsService.findById(id);
}
@UseGuards(AdminAuthGuard)
@@ -111,8 +80,8 @@ export class productController {
@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);
update(@Param('id') id: string, @Body() updateproductDto: UpdateproductDto) {
return this.productsService.update(id, updateproductDto);
}
@UseGuards(AdminAuthGuard)
@ApiBearerAuth()
@@ -120,7 +89,7 @@ export class productController {
@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);
remove(@Param('id') id: string,) {
return this.productsService.remove(id);
}
}
+3 -68
View File
@@ -1,19 +1,14 @@
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()
@@ -23,43 +18,14 @@ export class CreateproductDto {
@IsOptional()
@IsString()
@ApiPropertyOptional({ example: 'قرمه سبزی' })
title?: string;
@ApiPropertyOptional({ example: 'کارت ویزیت' })
title: string;
@IsOptional()
@IsString()
@ApiPropertyOptional({ example: 'توضیحات غذا' })
desc?: string;
@IsOptional()
@IsArray()
@IsString({ each: true })
@ApiPropertyOptional({ type: [String] })
content?: string[];
desc: 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()
@@ -80,37 +46,6 @@ export class CreateproductDto {
@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()
@@ -1,6 +1,6 @@
import { Entity, Property, ManyToOne } from '@mikro-orm/core';
import { BaseEntity } from '../../../common/entities/base.entity';
import { Attribute } from './attribute.entity';
// import { Attribute } from './attribute.entity';
@Entity({ tableName: 'attribute_values' })
export class AttributeValue extends BaseEntity {
@@ -10,13 +10,13 @@ export class AttributeValue extends BaseEntity {
@Property()
value: string;
@ManyToOne(() => Attribute)
attribute: Attribute;
// @ManyToOne(() => Attribute)
// attribute: Attribute;
@Property({ type: 'bigint' })
attributeId: bigint;
@Property({ type: 'int', nullable: true })
sortOrder?: number;
order?: number;
}
@@ -4,6 +4,9 @@ import { AttributeType } from '../interface/product.interface';
@Entity({ tableName: 'attributes' })
export class Attribute extends BaseEntity {
@Property({ type: 'bigint' })
productId: string
@Property({ primary: true })
id: bigint;
@@ -0,0 +1,30 @@
import { Entity, Index, Property, Collection, OneToMany, ManyToOne } from '@mikro-orm/core';
import { Product } from './product.entity';
import { BaseEntity } from '../../../common/entities/base.entity';
@Entity({ tableName: 'categories' })
@Index({ properties: ['isActive'] })
export class Category extends BaseEntity {
@ManyToOne(() => Category)
parent?: Category | null
@Property({ primary: true })
id: bigint
@Property()
title!: string;
@OneToMany(() => Product, product => product.category)
Products = new Collection<Product>(this);
@Property({ default: true })
isActive: boolean = true;
@Property({ nullable: true })
avatarUrl?: string;
@Property({ type: 'int', nullable: true })
order?: number;
}
+19 -2
View File
@@ -1,15 +1,29 @@
import { Entity, Property } from '@mikro-orm/core';
import { Collection, Entity, ManyToOne, OneToMany, Property } from '@mikro-orm/core';
import { BaseEntity } from '../../../common/entities/base.entity';
import { Category } from './category.entity';
import { Attribute } from './attribute.entity';
@Entity({ tableName: 'products' })
export class product extends BaseEntity {
export class Product extends BaseEntity {
@Property({ primary: true })
id: bigint
@ManyToOne(() => Category)
category: Category
@OneToMany(() => Attribute, (attr) => attr.productId)
attributes = new Collection<Attribute>(this)
@Property()
title: string;
@Property({ type: 'json' })
desc: string[]
@Property()
prepareTime: number;
@Property({ type: 'text', nullable: true })
linkUrl?: string;
@@ -19,4 +33,7 @@ export class product extends BaseEntity {
@Property({ type: 'json', nullable: true })
images?: string[];
@Property({ type: 'int' })
order?: number | null
}
+5 -7
View File
@@ -1,27 +1,25 @@
import { Module } from '@nestjs/common';
import { productService } from './providers/product.service';
import { productStockCrone } from './crone/product.crone';
import { productController } from './controllers/product.controller';
import { productRepository } from './repositories/product.repository';
import { ProductRepository } from './repositories/product.repository';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { Category } from './entities/category.entity';
import { product } from './entities/product.entity';
import { Product } from './entities/product.entity';
import { Attribute } from './entities/attribute.entity';
import { AttributeValue } from './entities/attribute-value.entity';
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, Attribute, AttributeValue]),
MikroOrmModule.forFeature([Product, Category, Attribute, AttributeValue]),
AuthModule,
JwtModule,
UtilsModule,
],
controllers: [productController,],
providers: [productService, productRepository, productStockCrone],
exports: [productRepository,],
providers: [productService, ProductRepository,],
exports: [ProductRepository,],
})
export class productModule { }
+100 -229
View File
@@ -1,264 +1,135 @@
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 { ProductRepository } from '../repositories/product.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 { CacheService } from '../../util/cache.service';
import { RequiredEntityData } from '@mikro-orm/core';
import { Product } from '../entities/product.entity';
import { CategoryMessage, productMessage } from 'src/common/enums/message.enum';
import { CategoryRepository } from '../repositories/category.repository';
@Injectable()
export class productService {
constructor(
private readonly productRepository: productRepository,
private readonly productRepository: ProductRepository,
private readonly categoryRepository: CategoryRepository,
private readonly em: EntityManager,
) { }
) { }
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 } });
async create(createproductDto: CreateproductDto) {
const { categoryId, ...rest } = createproductDto;
const category = await this.categoryRepository.findOne({ id: categoryId });
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,
const data: RequiredEntityData<Product> = {
isActive: rest.isActive ?? true,
order: rest.order ?? null,
title: rest.title,
desc: rest.desc,
prepareTime: rest.prepareTime ?? 0,
images: rest.images ?? undefined,
category,
};
return this.productRepository.create(data)
}
/**
* 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'] });
async update(productId: string, createproductDto: Partial<CreateproductDto>) {
const { categoryId, ...rest } = createproductDto;
const product = await this.productRepository.findOne({ id: productId })
if (!product) {
throw new NotFoundException(productMessage.NOT_FOUND);
}
if (categoryId) {
const category = await this.categoryRepository.findOne({ id: categoryId });
if (!category) {
throw new NotFoundException(CategoryMessage.NOT_FOUND);
}
this.productRepository.assign(product, { category })
}
this.productRepository.assign(product, rest)
//TODO : which one od these are correct
// this.productRepository.nativeUpdate(productId,product)
this.em.persistAndFlush(product)
}
findAll(dto: FindproductsDto) {
return this.productRepository.findAllPaginated(dto);
}
async findById(productId: string): Promise<Product> {
const product = await this.productRepository.findOne({ id: productId }, { populate: ['category', 'attributes'] });
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);
}
// async update( 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);
// }
const { iranWeekDay, mealType } = this.getCurrentIranTimeContext();
// // 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 } });
const queryFilter: FilterQuery<product> = {
restaurant: { slug },
isActive: true,
// weekDays: { $contains: iranWeekDay },
// ...(mealType ? { mealTypes: { $contains: mealType } } : {}),
} as unknown as FilterQuery<product>;
// if (!category) {
// throw new NotFoundException(CategoryMessage.NOT_FOUND);
// }
return this.productRepository.find(queryFilter, { populate: ['category'] });
}
// this.em.assign(product, { category: 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();
// // assign other fields from DTO (excluding dailyStock handled below)
// this.em.assign(product, rest);
// 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;
// // Persist product and update/create related inventory atomically
// await this.em.transactional(async em => {
// await em.persistAndFlush(product);
const mealType = this.getMealTypeByHour(currentHour);
// 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,
// });
// }
// }
return { iranWeekDay, mealType };
}
// await em.flush();
// });
/**
* 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;
// // Re-load the product to ensure populated relations and stable instance
// const savedproduct = await this.productRepository.findOne({ id: product.id }, { populate: ['category', 'restaurant'] });
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;
}
// // Invalidate cache for the restaurant if present (optional)
// // await this.invalidateRestaurantproductsCache(savedproduct?.restaurant?.slug);
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);
// return savedproduct ?? product;
// }
async remove(id: string): Promise<void> {
const product = await this.productRepository.findOne({ id });
if (!product) {
throw new NotFoundException(productMessage.NOT_FOUND);
}
product.deletedAt = new Date();
return await this.em.persistAndFlush(product);
}
}
@@ -0,0 +1,55 @@
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';
import { Category } from '../entities/category.entity';
type FindCategoriesOpts = {
page?: number;
limit?: number;
search?: string;
orderBy?: string;
order?: 'asc' | 'desc';
isActive?: boolean;
};
@Injectable()
export class CategoryRepository extends EntityRepository<Category> {
constructor(readonly em: EntityManager) {
super(em, Category);
}
async findAllPaginated(opts: FindCategoriesOpts = {}): Promise<PaginatedResult<Category>> {
const { page = 1, limit = 10, search, orderBy = 'createdAt', order = 'desc', isActive } = opts;
const offset = (page - 1) * limit;
const where: FilterQuery<Category> = {};
if (typeof isActive === 'boolean') {
where.isActive = isActive;
}
const [data, total] = await this.findAndCount(where, {
limit,
offset,
orderBy: { [orderBy]: order.toLowerCase() as 'asc' | 'desc' },
});
const totalPages = Math.ceil(total / limit);
return {
data,
meta: {
total,
page,
limit,
totalPages,
},
};
}
}
@@ -1,7 +1,7 @@
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 { Product } from '../entities/product.entity';
import { PaginatedResult } from 'src/common/interfaces/pagination.interface';
type FindproductsOpts = {
@@ -15,20 +15,17 @@ type FindproductsOpts = {
};
@Injectable()
export class productRepository extends EntityRepository<product> {
export class ProductRepository extends EntityRepository<Product> {
constructor(readonly em: EntityManager) {
super(em, product);
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>> {
async findAllPaginated(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 } };
const where: FilterQuery<Product> = {};
if (typeof isActive === 'boolean') {
where.isActive = isActive;
@@ -36,19 +33,19 @@ export class productRepository extends EntityRepository<product> {
if (search) {
const pattern = `%${search}%`;
where.$or = [{ title: { $ilike: pattern } }, { desc: { $ilike: pattern } }];
where.$or = [{ title: { $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>);
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'],
populate: ['category'],
});
const totalPages = Math.ceil(total / limit);