Merge pull request 'Добавлено отладочное логирование в компоненты создания и отображения товаров, обновлены типы продуктов в GraphQL запросах и резолверах. Опт…' (#2) from testing into main

Reviewed-on: #2
This commit is contained in:
2025-07-30 17:46:06 +03:00
6 changed files with 550 additions and 293 deletions

View File

@ -203,10 +203,6 @@ export const resolvers = {
JSON: JSONScalar,
DateTime: DateTimeScalar,
Product: {
type: (parent: any) => parent.type || "PRODUCT",
},
Query: {
me: async (_: unknown, __: unknown, context: Context) => {
if (!context.user) {
@ -782,11 +778,14 @@ export const resolvers = {
throw new GraphQLError("У пользователя нет организации");
}
// TypeScript assertion - мы знаем что organization не null после проверки выше
const organization = currentUser.organization;
// Получаем заказы поставок, созданные этим фулфилмент-центром для себя
const fulfillmentSupplyOrders = await prisma.supplyOrder.findMany({
where: {
organizationId: currentUser.organization.id, // Создали мы
fulfillmentCenterId: currentUser.organization.id, // Получатель - мы
organizationId: organization.id, // Создали мы
fulfillmentCenterId: organization.id, // Получатель - мы
status: {
in: ["PENDING", "CONFIRMED", "IN_TRANSIT", "DELIVERED"], // Все статусы
},
@ -833,8 +832,8 @@ export const resolvers = {
imageUrl: null,
createdAt: order.createdAt,
updatedAt: order.updatedAt,
organizationId: currentUser.organization.id,
organization: currentUser.organization,
organizationId: organization.id,
organization: organization,
shippedQuantity: 0,
}))
);
@ -842,8 +841,8 @@ export const resolvers = {
// Логирование для отладки
console.log("🔥🔥🔥 FULFILLMENT SUPPLIES RESOLVER CALLED 🔥🔥🔥");
console.log("📊 Расходники фулфилмента:", {
organizationId: currentUser.organization.id,
organizationType: currentUser.organization.type,
organizationId: organization.id,
organizationType: organization.type,
fulfillmentOrdersCount: fulfillmentSupplyOrders.length,
fulfillmentSuppliesCount: fulfillmentSupplies.length,
fulfillmentOrders: fulfillmentSupplyOrders.map((o) => ({
@ -1036,8 +1035,14 @@ export const resolvers = {
});
},
// Мои товары (для поставщиков)
// Мои товары и расходники (для поставщиков)
myProducts: async (_: unknown, __: unknown, context: Context) => {
console.log("🔍 MY_PRODUCTS RESOLVER - ВЫЗВАН:", {
hasUser: !!context.user,
userId: context.user?.id,
timestamp: new Date().toISOString(),
});
if (!context.user) {
throw new GraphQLError("Требуется авторизация", {
extensions: { code: "UNAUTHENTICATED" },
@ -1049,19 +1054,30 @@ export const resolvers = {
include: { organization: true },
});
console.log("👤 ПОЛЬЗОВАТЕЛЬ НАЙДЕН:", {
userId: currentUser?.id,
hasOrganization: !!currentUser?.organization,
organizationType: currentUser?.organization?.type,
organizationName: currentUser?.organization?.name,
});
if (!currentUser?.organization) {
throw new GraphQLError("У пользователя нет организации");
}
// Проверяем, что это поставщик
if (currentUser.organization.type !== "WHOLESALE") {
console.log("❌ ДОСТУП ЗАПРЕЩЕН - НЕ ПОСТАВЩИК:", {
actualType: currentUser.organization.type,
requiredType: "WHOLESALE",
});
throw new GraphQLError("Товары доступны только для поставщиков");
}
const products = await prisma.product.findMany({
where: {
organizationId: currentUser.organization.id,
type: "PRODUCT", // Показываем только товары, исключаем расходники
// Показываем и товары, и расходники поставщика
},
include: {
category: true,
@ -1071,13 +1087,18 @@ export const resolvers = {
});
console.log("🔥 MY_PRODUCTS RESOLVER DEBUG:", {
userId: currentUser.id,
organizationId: currentUser.organization.id,
organizationType: currentUser.organization.type,
organizationName: currentUser.organization.name,
totalProducts: products.length,
productTypes: products.map((p) => ({
id: p.id,
name: p.name,
article: p.article,
type: p.type,
isActive: p.isActive,
createdAt: p.createdAt,
})),
});
@ -1133,7 +1154,7 @@ export const resolvers = {
});
// Собираем все товары из доставленных заказов
const allProducts: any[] = [];
const allProducts: unknown[] = [];
console.log("🔍 Резолвер warehouseProducts (доставленные заказы):", {
currentUserId: currentUser.id,
@ -1197,12 +1218,19 @@ export const resolvers = {
return allProducts;
},
// Все товары всех поставщиков для маркета
// Все товары и расходники поставщиков для маркета
allProducts: async (
_: unknown,
args: { search?: string; category?: string },
context: Context
) => {
console.log("🛍️ ALL_PRODUCTS RESOLVER - ВЫЗВАН:", {
userId: context.user?.id,
search: args.search,
category: args.category,
timestamp: new Date().toISOString(),
});
if (!context.user) {
throw new GraphQLError("Требуется авторизация", {
extensions: { code: "UNAUTHENTICATED" },
@ -1211,7 +1239,7 @@ export const resolvers = {
const where: Record<string, unknown> = {
isActive: true, // Показываем только активные товары
type: "PRODUCT", // Показываем только товары, исключаем расходники
// Показываем и товары, и расходники поставщиков
organization: {
type: "WHOLESALE", // Только товары поставщиков
},
@ -1599,21 +1627,6 @@ export const resolvers = {
return scheduleRecords;
},
// Получение всех категорий товаров
categories: async () => {
try {
const categories = await prisma.category.findMany({
orderBy: {
name: "asc",
},
});
return categories;
} catch (error) {
console.error("Ошибка получения категорий:", error);
throw new GraphQLError("Не удалось получить категории");
}
},
},
Mutation: {
@ -3538,8 +3551,6 @@ export const resolvers = {
where: { id: args.input.supplyId },
data: {
currentStock: existingSupply.currentStock - args.input.quantityUsed,
usedStock:
(existingSupply.usedStock || 0) + args.input.quantityUsed,
updatedAt: new Date(),
},
include: { organization: true },
@ -3549,7 +3560,6 @@ export const resolvers = {
supplyName: updatedSupply.name,
quantityUsed: args.input.quantityUsed,
remainingStock: updatedSupply.currentStock,
totalUsed: updatedSupply.usedStock,
description: args.input.description,
});
@ -3724,7 +3734,7 @@ export const resolvers = {
try {
// Определяем начальный статус в зависимости от роли организации
let initialStatus = "PENDING";
let initialStatus: "PENDING" | "CONFIRMED" = "PENDING";
if (organizationRole === "SELLER") {
initialStatus = "PENDING"; // Селлер создает заказ, ждет подтверждения поставщика
} else if (organizationRole === "FULFILLMENT") {
@ -3780,7 +3790,10 @@ export const resolvers = {
const suppliesData = args.input.items.map((item) => {
const product = products.find((p) => p.id === item.productId)!;
const productWithCategory = supplyOrder.items.find(
(orderItem) => orderItem.productId === item.productId
(orderItem: {
productId: string;
product: { category?: { name: string } | null };
}) => orderItem.productId === item.productId
)?.product;
return {
@ -3900,6 +3913,13 @@ export const resolvers = {
},
context: Context
) => {
console.log("🆕 CREATE_PRODUCT RESOLVER - ВЫЗВАН:", {
hasUser: !!context.user,
userId: context.user?.id,
inputData: args.input,
timestamp: new Date().toISOString(),
});
if (!context.user) {
throw new GraphQLError("Требуется авторизация", {
extensions: { code: "UNAUTHENTICATED" },
@ -3936,6 +3956,18 @@ export const resolvers = {
}
try {
console.log("🛍️ СОЗДАНИЕ ТОВАРА - НАЧАЛО:", {
userId: currentUser.id,
organizationId: currentUser.organization.id,
organizationType: currentUser.organization.type,
productData: {
name: args.input.name,
article: args.input.article,
type: args.input.type || "PRODUCT",
isActive: args.input.isActive ?? true,
},
});
const product = await prisma.product.create({
data: {
name: args.input.name,
@ -3962,6 +3994,16 @@ export const resolvers = {
},
});
console.log("✅ ТОВАР УСПЕШНО СОЗДАН:", {
productId: product.id,
name: product.name,
article: product.article,
type: product.type,
isActive: product.isActive,
organizationId: product.organizationId,
createdAt: product.createdAt,
});
return {
success: true,
message: "Товар успешно создан",
@ -5497,6 +5539,7 @@ export const resolvers = {
},
Product: {
type: (parent: { type?: string | null }) => parent.type || "PRODUCT",
images: (parent: { images: unknown }) => {
// Если images это строка JSON, парсим её в массив
if (typeof parent.images === "string") {