This commit is contained in:
2025-11-23 09:46:24 +03:30
parent cc28b78596
commit f196366421
11 changed files with 456 additions and 11 deletions
@@ -0,0 +1,33 @@
import { Controller, Get, UseGuards } from '@nestjs/common';
import {
ApiTags,
ApiOperation,
ApiCreatedResponse,
ApiOkResponse,
ApiNotFoundResponse,
ApiParam,
ApiBody,
ApiBearerAuth,
} from '@nestjs/swagger';
import { RestaurantShipmentMethodService } from '../providers/restaurant-shipment-method.service';
import { RestaurantShipmentMethod } from '../entities/restaurant-shipment-method.entity';
import { RestId } from 'src/common/decorators/rest-id.decorator';
import { AuthGuard } from 'src/modules/auth/guards/auth.guard';
@UseGuards(AuthGuard)
@ApiBearerAuth()
@ApiTags('restaurant-shipment-methods')
@Controller('restaurant-shipment-methods')
export class PublicRestaurantShipmentMethodController {
constructor(private readonly restaurantShipmentMethodService: RestaurantShipmentMethodService) {}
@Get()
@ApiOperation({ summary: 'Get restaurant shipment methods ' })
@ApiOkResponse({
description: 'List of restaurant shipment methods',
type: [RestaurantShipmentMethod],
})
findAll(@RestId() restId: string) {
return this.restaurantShipmentMethodService.findAll(restId);
}
}
@@ -0,0 +1,84 @@
import { Controller, Get, Post, Body, Patch, Param, Delete, UseGuards } from '@nestjs/common';
import {
ApiTags,
ApiOperation,
ApiCreatedResponse,
ApiOkResponse,
ApiNotFoundResponse,
ApiParam,
ApiBody,
ApiBearerAuth,
} from '@nestjs/swagger';
import { RestaurantShipmentMethodService } from '../providers/restaurant-shipment-method.service';
import { CreateRestaurantShipmentMethodDto } from '../dto/create-restaurant-shipment-method.dto';
import { UpdateRestaurantShipmentMethodDto } from '../dto/update-restaurant-shipment-method.dto';
import { RestaurantShipmentMethod } from '../entities/restaurant-shipment-method.entity';
import { AdminAuthGuard } from 'src/modules/auth/guards/adminAuth.guard';
import { RestId } from 'src/common/decorators/rest-id.decorator';
@UseGuards(AdminAuthGuard)
@ApiBearerAuth()
@ApiTags('admin/restaurant-shipment-methods')
@Controller('admin/restaurant-shipment-methods')
export class RestaurantShipmentMethodController {
constructor(private readonly restaurantShipmentMethodService: RestaurantShipmentMethodService) {}
@Post()
@ApiOperation({ summary: 'Create a new restaurant shipment method' })
@ApiBody({ type: CreateRestaurantShipmentMethodDto })
@ApiCreatedResponse({
description: 'Restaurant shipment method created successfully',
type: RestaurantShipmentMethod,
})
create(@Body() createDto: CreateRestaurantShipmentMethodDto, @RestId() restId: string) {
return this.restaurantShipmentMethodService.create(restId, createDto);
}
@Get()
@ApiOperation({ summary: 'Get all restaurant shipment methods' })
@ApiOkResponse({
description: 'List of restaurant shipment methods',
type: [RestaurantShipmentMethod],
})
findAll(@RestId() restId: string) {
return this.restaurantShipmentMethodService.findAll(restId);
}
@Get(':shipmentMethodId')
@ApiOperation({ summary: 'Get a restaurant shipment method by shipment method ID' })
@ApiParam({ name: 'shipmentMethodId', description: 'Shipment method ID' })
@ApiOkResponse({
description: 'Restaurant shipment method details',
type: RestaurantShipmentMethod,
})
@ApiNotFoundResponse({ description: 'Restaurant shipment method not found' })
findOne(@Param('shipmentMethodId') shipmentMethodId: string, @RestId() restId: string) {
return this.restaurantShipmentMethodService.findOne(restId, shipmentMethodId);
}
@Patch(':shipmentMethodId')
@ApiOperation({ summary: 'Update a restaurant shipment method' })
@ApiParam({ name: 'shipmentMethodId', description: 'Shipment method ID' })
@ApiBody({ type: UpdateRestaurantShipmentMethodDto })
@ApiOkResponse({
description: 'Restaurant shipment method updated successfully',
type: RestaurantShipmentMethod,
})
@ApiNotFoundResponse({ description: 'Restaurant shipment method not found' })
update(
@Param('shipmentMethodId') shipmentMethodId: string,
@Body() updateDto: UpdateRestaurantShipmentMethodDto,
@RestId() restId: string,
) {
return this.restaurantShipmentMethodService.update(restId, shipmentMethodId, updateDto);
}
@Delete(':shipmentMethodId')
@ApiOperation({ summary: 'Delete a restaurant shipment method' })
@ApiParam({ name: 'shipmentMethodId', description: 'Shipment method ID' })
@ApiOkResponse({ description: 'Restaurant shipment method deleted successfully' })
@ApiNotFoundResponse({ description: 'Restaurant shipment method not found' })
remove(@Param('shipmentMethodId') shipmentMethodId: string, @RestId() restId: string) {
return this.restaurantShipmentMethodService.remove(restId, shipmentMethodId);
}
}
@@ -0,0 +1,28 @@
import { IsNumber, IsBoolean, IsOptional, IsString, Min } from 'class-validator';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Type } from 'class-transformer';
export class CreateRestaurantShipmentMethodDto {
@ApiProperty({ example: 'shipment-method-id', description: 'Shipment method ID' })
@IsString()
shipmentMethodId!: string;
@ApiProperty({ example: 5000, description: 'Shipping price' })
@IsNumber()
@Min(0)
@Type(() => Number)
price!: number;
@ApiProperty({ example: 100000, description: 'Minimum order price for free shipping' })
@IsNumber()
@Min(0)
@Type(() => Number)
minOrderPrice!: number;
@ApiPropertyOptional({ example: true, description: 'Is this shipment method active?' })
@IsOptional()
@IsBoolean()
@Type(() => Boolean)
isActive?: boolean;
}
@@ -0,0 +1,5 @@
import { PartialType } from '@nestjs/swagger';
import { CreateRestaurantShipmentMethodDto } from './create-restaurant-shipment-method.dto';
export class UpdateRestaurantShipmentMethodDto extends PartialType(CreateRestaurantShipmentMethodDto) {}
@@ -0,0 +1,22 @@
import { Entity, ManyToOne, Property, Unique } from '@mikro-orm/core';
import { Restaurant } from './restaurant.entity';
import { ShipmentMethod } from './shipment-method.entity';
@Entity({ tableName: 'restaurant_shipment_methods' })
@Unique({ properties: ['restaurant', 'shipmentMethod'] })
export class RestaurantShipmentMethod {
@ManyToOne(() => Restaurant, { primary: true })
restaurant!: Restaurant;
@ManyToOne(() => ShipmentMethod, { primary: true })
shipmentMethod!: ShipmentMethod;
@Property({ type: 'decimal', precision: 10, scale: 0, default: 0 })
price: number = 0;
@Property({ type: 'decimal', precision: 10, scale: 0, default: 0 })
minOrderPrice: number = 0;
@Property({ default: true })
isActive: boolean = true;
}
@@ -1,5 +1,7 @@
import { Entity, Property } from '@mikro-orm/core';
import { Collection, Entity, ManyToMany, Property } from '@mikro-orm/core';
import { BaseEntity } from '../../../common/entities/base.entity';
import { ShipmentMethod } from './shipment-method.entity';
import { RestaurantShipmentMethod } from './restaurant-shipment-method.entity';
@Entity({ tableName: 'restaurants' })
export class Restaurant extends BaseEntity {
@@ -75,4 +77,12 @@ export class Restaurant extends BaseEntity {
// --- مالیات یا VAT ---
@Property({ type: 'decimal', default: 0 })
vat?: number = 0;
// --- روش‌های ارسال ---
@ManyToMany({
entity: () => ShipmentMethod,
pivotEntity: () => RestaurantShipmentMethod,
inversedBy: sm => sm.restaurants,
})
shipmentMethods = new Collection<ShipmentMethod>(this);
}
@@ -0,0 +1,22 @@
import { Entity, Property, Unique, ManyToMany, Collection } from '@mikro-orm/core';
import { BaseEntity } from '../../../common/entities/base.entity';
import { Restaurant } from './restaurant.entity';
@Entity({ tableName: 'shipment_methods' })
export class ShipmentMethod extends BaseEntity {
@Property()
@Unique()
name!: string;
@Property()
title!: string;
@Property({ nullable: true })
description?: string;
@Property({ default: true })
isActive: boolean = true;
@ManyToMany({ entity: () => Restaurant, mappedBy: 'shipmentMethods' })
restaurants = new Collection<Restaurant>(this);
}
@@ -0,0 +1,142 @@
import { Injectable, NotFoundException, ConflictException } from '@nestjs/common';
import { EntityManager, RequiredEntityData } from '@mikro-orm/postgresql';
import { RestaurantShipmentMethod } from '../entities/restaurant-shipment-method.entity';
import { RestaurantShipmentMethodRepository } from '../repositories/restaurant-shipment-method.repository';
import { CreateRestaurantShipmentMethodDto } from '../dto/create-restaurant-shipment-method.dto';
import { UpdateRestaurantShipmentMethodDto } from '../dto/update-restaurant-shipment-method.dto';
import { RestRepository } from '../repositories/rest.repository';
import { ShipmentMethod } from '../entities/shipment-method.entity';
@Injectable()
export class RestaurantShipmentMethodService {
constructor(
private readonly restaurantShipmentMethodRepository: RestaurantShipmentMethodRepository,
private readonly restRepository: RestRepository,
private readonly em: EntityManager,
) {}
async create(restId: string, createDto: CreateRestaurantShipmentMethodDto): Promise<RestaurantShipmentMethod> {
const restaurant = await this.restRepository.findOne({ id: restId });
if (!restaurant) {
throw new NotFoundException(`رستوران با شناسه ${restId} یافت نشد.`);
}
const shipmentMethod = await this.em.findOne(ShipmentMethod, { id: createDto.shipmentMethodId });
if (!shipmentMethod) {
throw new NotFoundException(`روش ارسال با شناسه ${createDto.shipmentMethodId} یافت نشد.`);
}
// Check if the relationship already exists
const existing = await this.restaurantShipmentMethodRepository.findOne({
restaurant: { id: restId },
shipmentMethod: { id: createDto.shipmentMethodId },
});
if (existing) {
throw new ConflictException('این روش ارسال قبلاً برای این رستوران ثبت شده است.');
}
const data: RequiredEntityData<RestaurantShipmentMethod> = {
restaurant,
shipmentMethod,
price: createDto.price,
minOrderPrice: createDto.minOrderPrice,
isActive: createDto.isActive ?? true,
};
const restaurantShipmentMethod = this.restaurantShipmentMethodRepository.create(data);
await this.em.persistAndFlush(restaurantShipmentMethod);
return restaurantShipmentMethod;
}
async findAll(restId: string): Promise<RestaurantShipmentMethod[]> {
return this.restaurantShipmentMethodRepository.find(
{ restaurant: { id: restId } },
{ populate: ['shipmentMethod'] },
);
}
async findOne(restId: string, shipmentMethodId: string): Promise<RestaurantShipmentMethod> {
const restaurantShipmentMethod = await this.restaurantShipmentMethodRepository.findOne(
{
restaurant: { id: restId },
shipmentMethod: { id: shipmentMethodId },
},
{ populate: ['shipmentMethod'] },
);
if (!restaurantShipmentMethod) {
throw new NotFoundException(`روش ارسال با شناسه ${shipmentMethodId} برای رستوران با شناسه ${restId} یافت نشد.`);
}
return restaurantShipmentMethod;
}
async update(
restId: string,
shipmentMethodId: string,
updateDto: UpdateRestaurantShipmentMethodDto,
): Promise<RestaurantShipmentMethod> {
const restaurantShipmentMethod = await this.restaurantShipmentMethodRepository.findOne({
restaurant: { id: restId },
shipmentMethod: { id: shipmentMethodId },
});
if (!restaurantShipmentMethod) {
throw new NotFoundException(`روش ارسال با شناسه ${shipmentMethodId} برای رستوران با شناسه ${restId} یافت نشد.`);
}
const updateData: Partial<RestaurantShipmentMethod> = {};
if (updateDto.price !== undefined) {
updateData.price = updateDto.price;
}
if (updateDto.minOrderPrice !== undefined) {
updateData.minOrderPrice = updateDto.minOrderPrice;
}
if (updateDto.isActive !== undefined) {
updateData.isActive = updateDto.isActive;
}
// If shipmentMethodId is being updated, we need to check for conflicts
if (updateDto.shipmentMethodId !== undefined && updateDto.shipmentMethodId !== shipmentMethodId) {
const newShipmentMethod = await this.em.findOne(ShipmentMethod, { id: updateDto.shipmentMethodId });
if (!newShipmentMethod) {
throw new NotFoundException(`روش ارسال با شناسه ${updateDto.shipmentMethodId} یافت نشد.`);
}
// Check if the new relationship already exists
const existing = await this.restaurantShipmentMethodRepository.findOne({
restaurant: { id: restId },
shipmentMethod: { id: updateDto.shipmentMethodId },
});
if (existing) {
throw new ConflictException('این روش ارسال قبلاً برای این رستوران ثبت شده است.');
}
updateData.shipmentMethod = newShipmentMethod;
}
this.em.assign(restaurantShipmentMethod, updateData);
await this.em.persistAndFlush(restaurantShipmentMethod);
// Reload with populated relations
await this.em.populate(restaurantShipmentMethod, ['shipmentMethod']);
return restaurantShipmentMethod;
}
async remove(restId: string, shipmentMethodId: string): Promise<void> {
const restaurantShipmentMethod = await this.restaurantShipmentMethodRepository.findOne({
restaurant: { id: restId },
shipmentMethod: { id: shipmentMethodId },
});
if (!restaurantShipmentMethod) {
throw new NotFoundException(`روش ارسال با شناسه ${shipmentMethodId} برای رستوران با شناسه ${restId} یافت نشد.`);
}
await this.em.removeAndFlush(restaurantShipmentMethod);
}
}
@@ -0,0 +1,11 @@
import { EntityManager, EntityRepository } from '@mikro-orm/postgresql';
import { Injectable } from '@nestjs/common';
import { RestaurantShipmentMethod } from '../entities/restaurant-shipment-method.entity';
@Injectable()
export class RestaurantShipmentMethodRepository extends EntityRepository<RestaurantShipmentMethod> {
constructor(readonly em: EntityManager) {
super(em, RestaurantShipmentMethod);
}
}
+27 -3
View File
@@ -7,16 +7,40 @@ import { Restaurant } from './entities/restaurant.entity';
import { RestRepository } from './repositories/rest.repository';
import { ScheduleRepository } from './repositories/schedule.repository';
import { Schedule } from './entities/schedule.entity';
import { ShipmentMethod } from './entities/shipment-method.entity';
import { RestaurantShipmentMethod } from './entities/restaurant-shipment-method.entity';
import { ScheduleService } from './providers/schedule.service';
import { ScheduleController } from './controllers/schedule.controller';
import { PublicScheduleController } from './controllers/public-schedule.controller';
import { RestaurantShipmentMethodController } from './controllers/restaurant-shipment-method.controller';
import { RestaurantShipmentMethodService } from './providers/restaurant-shipment-method.service';
import { RestaurantShipmentMethodRepository } from './repositories/restaurant-shipment-method.repository';
import { JwtModule } from '@nestjs/jwt';
import { AuthModule } from '../auth/auth.module';
import { PublicRestaurantShipmentMethodController } from './controllers/public-restaurant-shipment-method.controller';
@Module({
controllers: [RestaurantsController, PublicRestaurantController, ScheduleController, PublicScheduleController],
providers: [RestaurantsService, RestRepository, ScheduleRepository, ScheduleService],
imports: [MikroOrmModule.forFeature([Restaurant, Schedule]), JwtModule, forwardRef(() => AuthModule)],
controllers: [
RestaurantsController,
PublicRestaurantController,
ScheduleController,
PublicScheduleController,
RestaurantShipmentMethodController,
PublicRestaurantShipmentMethodController,
],
providers: [
RestaurantsService,
RestRepository,
ScheduleRepository,
ScheduleService,
RestaurantShipmentMethodService,
RestaurantShipmentMethodRepository,
],
imports: [
MikroOrmModule.forFeature([Restaurant, Schedule, ShipmentMethod, RestaurantShipmentMethod]),
JwtModule,
forwardRef(() => AuthModule),
],
exports: [RestRepository, ScheduleRepository, ScheduleService],
})
export class RestaurantsModule {}
+71 -7
View File
@@ -10,6 +10,7 @@ import { Restaurant } from '../modules/restaurants/entities/restaurant.entity';
import { User } from '../modules/users/entities/user.entity';
import { Permission, PermissionTitles } from '../common/enums/permission.enum';
import { PaymentMethod } from '../modules/payments/entities/payment-method.entity';
import { ShipmentMethod } from '../modules/restaurants/entities/shipment-method.entity';
export class DatabaseSeeder extends Seeder {
async run(em: EntityManager) {
@@ -105,7 +106,54 @@ export class DatabaseSeeder extends Seeder {
await em.flush();
// 4. Create Restaurants (Farsi)
// 4. Create Shipment Methods (Farsi)
const shipmentMethods = [
{
name: 'dine-in',
title: 'سرو در رستوران',
description: 'سرو غذا در رستوران',
isActive: true,
},
{
name: 'delivery-location',
title: 'تحویل در محل',
description: 'تحویل غذا در محل',
isActive: true,
},
{
name: 'delivery-car',
title: 'تحویل با ماشین',
description: 'تحویل غذا با ماشین',
isActive: true,
},
{
name: 'delivery-courier',
title: 'تحویل با پیک',
description: 'تحویل غذا با پیک',
isActive: true,
},
];
const createdShipmentMethods: ShipmentMethod[] = [];
for (const methodData of shipmentMethods) {
let shipmentMethod = await em.findOne(ShipmentMethod, { name: methodData.name });
if (!shipmentMethod) {
shipmentMethod = em.create(ShipmentMethod, methodData);
em.persist(shipmentMethod);
} else {
// Update existing method if needed
if (shipmentMethod.title !== methodData.title || shipmentMethod.description !== methodData.description) {
shipmentMethod.title = methodData.title;
shipmentMethod.description = methodData.description;
em.persist(shipmentMethod);
}
}
createdShipmentMethods.push(shipmentMethod);
}
await em.flush();
// 5. Create Restaurants (Farsi)
const zhivanRestaurant = await em.findOne(Restaurant, { slug: 'zhivan' });
if (!zhivanRestaurant) {
const restaurant = em.create(Restaurant, {
@@ -115,7 +163,15 @@ export class DatabaseSeeder extends Seeder {
phone: '09123456789',
serviceArea: {
type: 'Polygon',
coordinates: [[[51.389, 35.6892], [51.390, 35.6892], [51.390, 35.6902], [51.389, 35.6902], [51.389, 35.6892]]],
coordinates: [
[
[51.389, 35.6892],
[51.39, 35.6892],
[51.39, 35.6902],
[51.389, 35.6902],
[51.389, 35.6892],
],
],
},
});
em.persist(restaurant);
@@ -130,7 +186,15 @@ export class DatabaseSeeder extends Seeder {
phone: '09123456790',
serviceArea: {
type: 'Polygon',
coordinates: [[[51.389, 35.6892], [51.390, 35.6892], [51.390, 35.6902], [51.389, 35.6902], [51.389, 35.6892]]],
coordinates: [
[
[51.389, 35.6892],
[51.39, 35.6892],
[51.39, 35.6902],
[51.389, 35.6902],
[51.389, 35.6892],
],
],
},
});
em.persist(restaurant);
@@ -142,7 +206,7 @@ export class DatabaseSeeder extends Seeder {
const zhivan = await em.findOne(Restaurant, { slug: 'zhivan' });
const boote = await em.findOne(Restaurant, { slug: 'boote' });
// 5. Create Categories (Farsi)
// 6. Create Categories (Farsi)
const categories = [
{ title: 'غذای اصلی', restId: zhivan?.id },
{ title: 'پیش غذا', restId: zhivan?.id },
@@ -172,7 +236,7 @@ export class DatabaseSeeder extends Seeder {
await em.flush();
// 6. Create Foods (Farsi)
// 7. Create Foods (Farsi)
const foods = [
// Zhivan Restaurant Foods
{
@@ -455,7 +519,7 @@ export class DatabaseSeeder extends Seeder {
await em.flush();
// 7. Create Admins (Farsi)
// 8. Create Admins (Farsi)
const adminMorteza = await em.findOne(Admin, { phone: '09362532122' });
if (!adminMorteza && restaurantRole && zhivan) {
const admin = em.create(Admin, {
@@ -515,7 +579,7 @@ export class DatabaseSeeder extends Seeder {
await em.flush();
// 8. Create Users (Farsi)
// 9. Create Users (Farsi)
const userMorteza = await em.findOne(User, { phone: '09362532122' });
if (!userMorteza && zhivan) {
const user = em.create(User, {