change entity names

This commit is contained in:
2026-02-08 09:18:20 +03:30
parent 6be6a66079
commit 9a7010dcea
180 changed files with 2751 additions and 2513 deletions
+51 -51
View File
@@ -2,32 +2,32 @@ import { Injectable, NotFoundException, BadRequestException, Logger } from '@nes
import { EntityManager } from '@mikro-orm/postgresql';
import { Order } from '../entities/order.entity';
import { OrderItem } from '../entities/order-item.entity';
import { User } from '../../users/entities/user.entity';
import { Restaurant } from '../../restaurants/entities/restaurant.entity';
import { Food } from '../../foods/entities/food.entity';
import { CartService } from '../../cart/providers/cart.service';
import { User } from '../../../users/entities/user.entity';
import { Shop } from ../../..shops/entities/shop.entity';
import { Product } from ../../..products/entities/product.entity';
import { CartService } from '../../../cart/providers/cart.service';
import { OrderStatus, OrderUserAddress, OrderCarAddress } from '../interface/order.interface';
import { PaymentMethodEnum, PaymentStatusEnum } from '../../payments/interface/payment';
import { Cart } from '../../cart/interfaces/cart.interface';
import { PaymentMethod } from '../../payments/entities/payment-method.entity';
import { PaymentsService } from '../../payments/services/payments.service';
import { DeliveryMethodEnum } from '../../delivery/interface/delivery';
import { Delivery } from '../../delivery/entities/delivery.entity';
import { PaymentMethodEnum, PaymentStatusEnum } from '../../../payments/interface/payment';
import { Cart } from '../../../cart/interfaces/cart.interface';
import { PaymentMethod } from '../../../payments/entities/payment-method.entity';
import { PaymentsService } from '../../../payments/services/payments.service';
import { DeliveryMethodEnum } from '../../../delivery/interface/delivery';
import { Delivery } from '../../../delivery/entities/delivery.entity';
import { OrderRepository } from '../repositories/order.repository';
import { FindOrdersDto } from '../dto/find-orders.dto';
import { PaginatedResult } from 'src/common/interfaces/pagination.interface';
import { Payment } from 'src/modules/payments/entities/payment.entity';
import { InventoryService } from 'src/modules/inventory/inventory.service';
import { BulkReserveFoodDto } from 'src/modules/inventory/dto/bulk-reserve-food.dto';
import { BulkReserveFoodDto } from 'src/modules/inventory/dto/bulk-reserve-product.dto';
import { StatusTransitionRef } from '../interface/order.interface';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { OrderCreatedEvent, OrderStatusChangedEvent } from '../events/order.events';
import { OrderMessage } from 'src/common/enums/message.enum';
type OrderItemData = { food: Food; quantity: number; unitPrice: number; discount: number };
type OrderItemData = { product: Product; quantity: number; unitPrice: number; discount: number };
type ValidatedCartForOrder = {
user: User;
restaurant: Restaurant;
shop: Shop;
delivery: Delivery;
userAddress: OrderUserAddress | null;
carAddress: OrderCarAddress | null;
@@ -66,7 +66,7 @@ export class OrdersService {
const order = await this.em.transactional(async em => {
const order = em.create(Order, {
user: validated.user,
restaurant: validated.restaurant,
shop: validated.shop,
deliveryMethod: validated.delivery,
userAddress: validated.userAddress,
carAddress: validated.carAddress,
@@ -89,15 +89,15 @@ export class OrdersService {
em.persist(order);
for (const itemData of validated.orderItemsData) {
const { food, quantity, unitPrice, discount } = itemData;
const { product, quantity, unitPrice, discount } = itemData;
this.assertFoodHasSufficientStock(food, quantity);
this.assertFoodHasSufficientStock(product, quantity);
const totalPrice = (unitPrice - discount) * quantity;
const orderItem = em.create(OrderItem, {
order,
food,
product,
quantity,
unitPrice,
discount,
@@ -119,13 +119,13 @@ export class OrdersService {
// reserve stock based on payment method.
const bulkReserveFoodDto: BulkReserveFoodDto = {
items: validated.orderItemsData.map(item => ({
foodId: item.food.id,
foodId: item.product.id,
quantity: item.quantity,
})),
};
await this.inventoryService.deductFromInventory(em, bulkReserveFoodDto);
await em.flush();
this.logger.debug(`Order ${order.id} created for user ${userId} (restaurant ${restaurantId})`);
this.logger.debug(`Order ${order.id} created for user ${userId} (shop ${restaurantId})`);
return order;
});
@@ -148,7 +148,7 @@ export class OrdersService {
this.assertCartHasDeliveryMethod(cart);
this.assertCartHasPaymentMethod(cart);
const [user, restaurant, delivery] = await Promise.all([
const [user, shop, delivery] = await Promise.all([
this.getUserOrFail(userId),
this.getRestaurantOrFail(restaurantId),
this.getDeliveryOrFail(cart.deliveryMethodId!),
@@ -164,7 +164,7 @@ export class OrdersService {
return {
user,
restaurant,
shop,
delivery,
paymentMethod,
userAddress: delivery.method === DeliveryMethodEnum.DeliveryCourier ? (cart?.userAddress ?? null) : null,
@@ -209,18 +209,18 @@ export class OrdersService {
async findOne(id: string, restId: string): Promise<Order> {
const order = await this.orderRepository.findOne(
{ id, restaurant: { id: restId } },
{ id, shop: { id: restId } },
{
populate: [
'user',
'restaurant',
'shop',
'deliveryMethod',
'userAddress',
'carAddress',
'paymentMethod',
'payments',
'items',
'items.food',
'items.product',
],
},
);
@@ -333,7 +333,7 @@ export class OrdersService {
private async getOrderOrFail(orderId: string, restId: string): Promise<Order> {
const order = await this.em.findOne(
Order,
{ id: orderId, restaurant: { id: restId } },
{ id: orderId, shop: { id: restId } },
{ populate: ['paymentMethod', 'deliveryMethod', 'user'] },
);
if (!order) throw new NotFoundException(OrderMessage.NOT_FOUND);
@@ -364,10 +364,10 @@ export class OrdersService {
return user;
}
private async getRestaurantOrFail(restaurantId: string): Promise<Restaurant> {
const restaurant = await this.em.findOne(Restaurant, { id: restaurantId });
if (!restaurant) throw new NotFoundException(OrderMessage.RESTAURANT_NOT_FOUND);
return restaurant;
private async getRestaurantOrFail(restaurantId: string): Promise<Shop> {
const shop = await this.em.findOne(Shop, { id: restaurantId });
if (!shop) throw new NotFoundException(OrderMessage.RESTAURANT_NOT_FOUND);
return shop;
}
private async getDeliveryOrFail(deliveryId: string): Promise<Delivery> {
@@ -404,13 +404,13 @@ export class OrdersService {
PaymentMethod,
{
id: paymentMethodId,
restaurant: { id: restaurantId },
shop: { id: restaurantId },
},
{ populate: ['restaurant'] },
{ populate: ['shop'] },
);
if (!paymentMethod) {
throw new NotFoundException(`Payment method with ID ${paymentMethodId} not found for restaurant ${restaurantId}`);
throw new NotFoundException(`Payment method with ID ${paymentMethodId} not found for shop ${restaurantId}`);
}
return paymentMethod;
@@ -426,28 +426,28 @@ export class OrdersService {
const orderItemsData: OrderItemData[] = [];
for (const cartItem of cart.items) {
const food = await this.em.findOne(Food, { id: cartItem.foodId }, { populate: ['restaurant', 'inventory'] });
if (!food) throw new NotFoundException(OrderMessage.FOOD_NOT_FOUND);
const product = await this.em.findOne(Product, { id: cartItem.foodId }, { populate: ['shop', 'inventory'] });
if (!product) throw new NotFoundException(OrderMessage.FOOD_NOT_FOUND);
if (food.restaurant.id !== restaurantId) {
if (product.shop.id !== restaurantId) {
throw new BadRequestException(OrderMessage.FOOD_NOT_BELONGS_TO_RESTAURANT);
}
this.assertFoodHasSufficientStock(food, cartItem.quantity);
this.assertFoodHasSufficientStock(product, cartItem.quantity);
orderItemsData.push({
food,
product,
quantity: cartItem.quantity,
unitPrice: food.price || 0,
discount: food.discount || 0,
unitPrice: product.price || 0,
discount: product.discount || 0,
});
}
return orderItemsData;
}
private assertFoodHasSufficientStock(food: Food, quantity: number) {
const availableStock = food.inventory?.availableStock ?? 0;
private assertFoodHasSufficientStock(product: Product, quantity: number) {
const availableStock = product.inventory?.availableStock ?? 0;
if (availableStock < quantity) {
throw new BadRequestException(OrderMessage.FOOD_NOT_FOUND);
}
@@ -458,7 +458,7 @@ export class OrdersService {
return this.em.transactional(async em => {
// 1. Total orders count (excluding pending and canceled)
const totalOrders = await em.count(Order, {
restaurant: { id: restId },
shop: { id: restId },
status: {
$in: [
OrderStatus.PAID,
@@ -471,13 +471,13 @@ export class OrdersService {
},
});
// 2. Active foods count
const activeFoods = await em.count(Food, {
restaurant: { id: restId },
// 2. Active products count
const activeFoods = await em.count(Product, {
shop: { id: restId },
isActive: true,
});
// 3. Total clients count (distinct users with orders for this restaurant)
// 3. Total clients count (distinct users with orders for this shop)
const clientsResult = await em.execute(
`
SELECT COUNT(DISTINCT o.user_id) as count
@@ -488,7 +488,7 @@ export class OrdersService {
);
const totalClients = Number(clientsResult[0]?.count || 0);
// 4. Total revenue (sum of paid payments for orders of this restaurant)
// 4. Total revenue (sum of paid payments for orders of this shop)
const revenueResult = await em.execute(
`
SELECT COALESCE(SUM(p.amount), 0)::numeric as total
@@ -525,7 +525,7 @@ export class OrdersService {
const lastDayOfLastMonth = new Date(now.getFullYear(), now.getMonth(), 0, 23, 59, 59, 999);
this.logger.debug(
`Food sales pie chart query params: restId=${restId}, startDate=${startDate.toISOString()}, endDate=${endDate.toISOString()}`,
`Product sales pie chart query params: restId=${restId}, startDate=${startDate.toISOString()}, endDate=${endDate.toISOString()}`,
);
// Diagnostic query to check what orders exist
@@ -545,7 +545,7 @@ export class OrdersService {
`,
[restId],
);
this.logger.debug(`Diagnostic: Found ${diagnosticResult.length} recent orders for restaurant ${restId}`);
this.logger.debug(`Diagnostic: Found ${diagnosticResult.length} recent orders for shop ${restId}`);
if (diagnosticResult.length > 0) {
this.logger.debug(`Sample order: status=${diagnosticResult[0].status}, created_at=${diagnosticResult[0].created_at}`);
}
@@ -561,7 +561,7 @@ export class OrdersService {
COALESCE(SUM(oi.total_price), 0)::numeric as total_revenue
FROM order_items oi
INNER JOIN orders o ON oi.order_id = o.id
INNER JOIN foods f ON oi.food_id = f.id
INNER JOIN products f ON oi.food_id = f.id
WHERE o.restaurant_id = ?
AND o.created_at >= ?
AND o.created_at <= ?
@@ -572,7 +572,7 @@ export class OrdersService {
[restId, startDate, endDate],
);
this.logger.debug(`Food sales pie chart query returned ${result.length} rows`);
this.logger.debug(`Product sales pie chart query returned ${result.length} rows`);
// Calculate total revenue for percentage calculation
const totalRevenue = result.reduce((sum: number, item: any) => {