Обновление компонентов интерфейса и оптимизация логики

- Добавлен компонент AppShell в RootLayout для улучшения структуры
- Обновлен компонент Sidebar для предотвращения дублирования при рендеринге
- Оптимизированы импорты в компонентах AdvertisingTab и SalesTab
- Реализована логика кэширования статистики селлера в GraphQL резолверах
This commit is contained in:
Bivekich
2025-08-08 09:24:15 +03:00
parent b43269073f
commit 547e6e7d95
13 changed files with 610 additions and 275 deletions

View File

@ -1,3 +1,4 @@
import { AppShell } from '@/components/layout/app-shell'
import { Toaster } from '@/components/ui/sonner'
import './globals.css'
@ -7,7 +8,11 @@ export default function RootLayout({ children }: { children: React.ReactNode })
return (
<html lang="ru" className="dark">
<body className="min-h-screen bg-gradient-smooth text-white overflow-x-hidden">
<Providers>{children}</Providers>
<Providers>
<div className="h-screen flex overflow-hidden">
<AppShell>{children}</AppShell>
</div>
</Providers>
<Toaster />
</body>
</html>

View File

@ -2,24 +2,24 @@
import { useQuery } from '@apollo/client'
import {
Settings,
LogOut,
Store,
MessageCircle,
Wrench,
Warehouse,
Users,
Truck,
Handshake,
ChevronLeft,
ChevronRight,
BarChart3,
Home,
DollarSign,
BarChart3,
ChevronLeft,
ChevronRight,
DollarSign,
Handshake,
Home,
LogOut,
MessageCircle,
Settings,
Store,
Truck,
Users,
Warehouse,
Wrench,
} from 'lucide-react'
import { useRouter, usePathname } from 'next/navigation'
import { usePathname, useRouter } from 'next/navigation'
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { Button } from '@/components/ui/button'
import { GET_CONVERSATIONS, GET_INCOMING_REQUESTS, GET_PENDING_SUPPLIES_COUNT } from '@/graphql/queries'
import { useAuth } from '@/hooks/useAuth'
@ -83,7 +83,17 @@ function WholesaleOrdersNotification() {
)
}
export function Sidebar() {
declare global {
interface Window {
__SIDEBAR_ROOT_MOUNTED__?: boolean
}
}
export function Sidebar({ isRootInstance = false }: { isRootInstance?: boolean } = {}) {
// Если уже есть корневой сайдбар и это не корневой экземпляр — не рендерим дубликат
if (typeof window !== 'undefined' && !isRootInstance && (window as any).__SIDEBAR_ROOT_MOUNTED__) {
return null
}
const { user, logout } = useAuth()
const router = useRouter()
const pathname = usePathname()
@ -236,6 +246,11 @@ export function Sidebar() {
pathname.startsWith('/supplier-orders')
const isPartnersActive = pathname.startsWith('/partners')
// Помечаем, что корневой экземпляр смонтирован
if (typeof window !== 'undefined' && isRootInstance) {
;(window as any).__SIDEBAR_ROOT_MOUNTED__ = true
}
return (
<div className="relative">
{/* Основной сайдбар */}
@ -255,7 +270,6 @@ export function Sidebar() {
size="icon"
onClick={toggleSidebar}
className="relative h-12 w-12 rounded-full bg-gradient-to-br from-white/20 to-white/5 border border-white/30 hover:from-white/30 hover:to-white/10 transition-all duration-300 ease-out hover:scale-110 active:scale-95 backdrop-blur-xl shadow-lg hover:shadow-xl hover:shadow-purple-500/20 group-hover:border-purple-300/50"
title={isCollapsed ? 'Развернуть сайдбар' : 'Свернуть сайдбар'}
>
{/* Простая анимированная иконка */}
<div className="transition-transform duration-300 ease-out group-hover:scale-110">
@ -270,17 +284,7 @@ export function Sidebar() {
<div className="absolute inset-0 rounded-full bg-gradient-to-r from-purple-500/0 to-blue-500/0 group-hover:from-purple-500/10 group-hover:to-blue-500/10 transition-all duration-500"></div>
</Button>
{/* Подсказка только в свернутом состоянии */}
{isCollapsed && (
<div className="absolute left-full ml-3 top-1/2 -translate-y-1/2 whitespace-nowrap opacity-0 group-hover:opacity-100 transition-all duration-300">
<div className="bg-gradient-to-r from-purple-500/20 to-blue-500/20 backdrop-blur-xl border border-white/20 rounded-lg px-3 py-2">
<div className="text-sm text-white font-medium flex items-center space-x-2">
<div className="w-2 h-2 bg-green-400 rounded-full animate-pulse"></div>
<span> Развернуть</span>
</div>
</div>
</div>
)}
{/* Убраны текстовые подсказки при наведении */}
</div>
</div>

View File

@ -0,0 +1,19 @@
'use client'
import { usePathname } from 'next/navigation'
import { Sidebar } from '@/components/dashboard/sidebar'
export function AppShell({ children }: { children: React.ReactNode }) {
const pathname = usePathname()
const hideSidebar = pathname === '/login' || pathname === '/register'
return (
<>
{!hideSidebar && <Sidebar isRootInstance />}
<div className="flex-1 min-w-0 overflow-hidden">{children}</div>
</>
)
}

View File

@ -0,0 +1,6 @@
'use client'
import { createContext } from 'react'
export const SidebarRootContext = createContext<boolean>(false)

View File

@ -1,61 +1,39 @@
'use client'
import { useQuery, useLazyQuery, useMutation } from '@apollo/client'
import { useLazyQuery, useMutation, useQuery } from '@apollo/client'
import {
TrendingUp,
TrendingDown,
Eye,
MousePointer,
ShoppingCart,
DollarSign,
ChevronRight,
ChevronDown,
Plus,
Trash2,
ExternalLink,
Copy,
AlertCircle,
BarChart3,
Minimize2,
Calendar,
Package,
Link,
Smartphone,
Monitor,
Globe,
Target,
ArrowUpDown,
Percent,
AlertCircle,
BarChart3,
Eye,
Minimize2,
TrendingUp
} from 'lucide-react'
import React, { useState, useEffect, useRef, useMemo, useCallback } from 'react'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
BarChart,
Bar,
ResponsiveContainer,
ComposedChart,
Bar,
BarChart,
CartesianGrid,
ResponsiveContainer,
XAxis,
YAxis
} from 'recharts'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { ChartConfig, ChartContainer, ChartTooltip, ChartTooltipContent } from '@/components/ui/chart'
import { ChartTooltip } from '@/components/ui/chart'
import { Checkbox } from '@/components/ui/checkbox'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Skeleton } from '@/components/ui/skeleton'
import {
CREATE_EXTERNAL_AD,
DELETE_EXTERNAL_AD,
UPDATE_EXTERNAL_AD,
UPDATE_EXTERNAL_AD_CLICKS,
CREATE_EXTERNAL_AD,
DELETE_EXTERNAL_AD,
UPDATE_EXTERNAL_AD,
UPDATE_EXTERNAL_AD_CLICKS,
} from '@/graphql/mutations'
import { GET_WILDBERRIES_CAMPAIGN_STATS, GET_WILDBERRIES_CAMPAIGNS_LIST, GET_EXTERNAL_ADS } from '@/graphql/queries'
import { GET_EXTERNAL_ADS, GET_WILDBERRIES_CAMPAIGN_STATS, GET_WILDBERRIES_CAMPAIGNS_LIST } from '@/graphql/queries'
import { useAuth } from '@/hooks/useAuth'
import { WildberriesService } from '@/services/wildberries-service'
@ -770,19 +748,76 @@ const AdvertisingTab = React.memo(({
}
}
// Автоматически загружаем все доступные кампании
useEffect(() => {
if (campaignsData?.getWildberriesCampaignsList?.data?.adverts) {
const campaigns = campaignsData.getWildberriesCampaignsList.data.adverts
const allCampaignIds = campaigns.flatMap((group: CampaignGroup) =>
group.advert_list.map((item: CampaignListItem) => item.advertId),
)
// Функция запуска загрузки статистики кампаний (стабилизирована)
const handleCampaignsSelected = useCallback((ids: number[]) => {
if (ids.length === 0) return
if (allCampaignIds.length > 0) {
handleCampaignsSelected(allCampaignIds)
let campaigns
if (useCustomDates && startDate && endDate) {
campaigns = ids.map((id) => ({
id,
interval: {
begin: startDate,
end: endDate,
},
}))
} else {
const endDateCalc = new Date()
const startDateCalc = new Date()
switch (selectedPeriod) {
case 'week':
startDateCalc.setDate(endDateCalc.getDate() - 7)
break
case 'month':
startDateCalc.setMonth(endDateCalc.getMonth() - 1)
break
case 'quarter':
startDateCalc.setMonth(endDateCalc.getMonth() - 3)
break
}
campaigns = ids.map((id) => ({
id,
interval: {
begin: startDateCalc.toISOString().split('T')[0],
end: endDateCalc.toISOString().split('T')[0],
},
}))
}
}, [campaignsData, selectedPeriod, useCustomDates, startDate, endDate])
getCampaignStats({
variables: {
input: { campaigns },
},
})
}, [useCustomDates, startDate, endDate, selectedPeriod, getCampaignStats])
// Ключ загрузки для защиты от повторов
const loadKey = useMemo(
() => (useCustomDates && startDate && endDate ? `custom_${startDate}_${endDate}` : selectedPeriod),
[useCustomDates, startDate, endDate, selectedPeriod],
)
const fetchingRef = useRef(false)
const lastLoadedKeyRef = useRef<string | null>(null)
// Автозагрузка всех кампаний для выбранного периода (однократно на ключ)
useEffect(() => {
const adverts = campaignsData?.getWildberriesCampaignsList?.data?.adverts
if (!adverts) return
if (fetchingRef.current) return
if (lastLoadedKeyRef.current === loadKey) return
const allCampaignIds = adverts.flatMap((group: CampaignGroup) =>
group.advert_list.map((item: CampaignListItem) => item.advertId),
)
if (allCampaignIds.length === 0) return
fetchingRef.current = true
handleCampaignsSelected(allCampaignIds)
lastLoadedKeyRef.current = loadKey
fetchingRef.current = false
}, [campaignsData, loadKey, handleCampaignsSelected])
// Преобразование данных кампаний в новый формат таблицы
const convertCampaignDataToDailyData = (campaigns: CampaignStats[]): DailyAdvertisingData[] => {
@ -1018,8 +1053,8 @@ const AdvertisingTab = React.memo(({
setDailyData(newDailyData)
prevCampaignStats.current = campaignStats
// Сохраняем данные в кэш
if (setCachedData) {
// Сохраняем данные в кэш (через ref, чтобы не зациклиться на изменении ссылки функции)
if (setCachedDataRef.current) {
const cacheData = {
dailyData: newDailyData,
campaignStats: campaignStats,
@ -1033,56 +1068,20 @@ const AdvertisingTab = React.memo(({
0,
),
}
setCachedData(cacheData)
setCachedDataRef.current(cacheData)
console.warn('Advertising: Data cached successfully')
}
}
}
}, [campaignStats, externalAdsData, setCachedData]) // Добавляем externalAdsData и setCachedData в зависимости
}, [campaignStats, externalAdsData])
const handleCampaignsSelected = (ids: number[]) => {
if (ids.length === 0) return
// Храним setCachedData в ref, чтобы не триггерить эффект из-за смены ссылки на функцию в родителе
const setCachedDataRef = useRef<typeof setCachedData | undefined>(setCachedData)
useEffect(() => {
setCachedDataRef.current = setCachedData
}, [setCachedData])
let campaigns
if (useCustomDates && startDate && endDate) {
campaigns = ids.map((id) => ({
id,
interval: {
begin: startDate,
end: endDate,
},
}))
} else {
const endDateCalc = new Date()
const startDateCalc = new Date()
switch (selectedPeriod) {
case 'week':
startDateCalc.setDate(endDateCalc.getDate() - 7)
break
case 'month':
startDateCalc.setMonth(endDateCalc.getMonth() - 1)
break
case 'quarter':
startDateCalc.setMonth(endDateCalc.getMonth() - 3)
break
}
campaigns = ids.map((id) => ({
id,
interval: {
begin: startDateCalc.toISOString().split('T')[0],
end: endDateCalc.toISOString().split('T')[0],
},
}))
}
getCampaignStats({
variables: {
input: { campaigns },
},
})
}
const toggleCampaignExpanded = (campaignId: number) => {
const newExpanded = new Set(expandedCampaigns)

View File

@ -1,10 +1,9 @@
'use client'
import { useQuery } from '@apollo/client'
import { gql } from '@apollo/client'
import { TrendingUp, Info, BarChart3, ChevronDown, ChevronUp } from 'lucide-react'
import React, { useState, useEffect, useMemo, useCallback } from 'react'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, ResponsiveContainer } from 'recharts'
import { gql, useQuery } from '@apollo/client'
import { BarChart3, ChevronDown, ChevronUp, Info, TrendingUp } from 'lucide-react'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from 'recharts'
import { Badge } from '@/components/ui/badge'
import { Card } from '@/components/ui/card'
@ -192,9 +191,20 @@ const SalesTab = React.memo(({
skip: true, // Изначально пропускаем запрос, будем запускать вручную
})
// Ключ загрузки для защиты от повторов
const loadKey = useMemo(
() => (useCustomDates && startDate && endDate ? `custom_${startDate}_${endDate}` : selectedPeriod),
[useCustomDates, startDate, endDate, selectedPeriod],
)
const loadingRef = useRef(false)
const lastLoadedKeyRef = useRef<string | null>(null)
// Эффект для проверки кэша и загрузки данных
useEffect(() => {
const loadData = async () => {
if (loadingRef.current) return
if (lastLoadedKeyRef.current === loadKey) return
loadingRef.current = true
// Сначала проверяем локальный кэш
if (getCachedData) {
const cachedData = getCachedData()
@ -202,6 +212,8 @@ const SalesTab = React.memo(({
setChartData(cachedData.chartData || mockChartData)
setTableData(cachedData.tableData || mockTableData)
console.warn('Sales: Using cached data')
lastLoadedKeyRef.current = loadKey
loadingRef.current = false
return
}
}
@ -210,15 +222,24 @@ const SalesTab = React.memo(({
if (setIsLoadingData) setIsLoadingData(true)
try {
const result = await refetch()
const refetchVars = useCustomDates ? { startDate, endDate } : { period: selectedPeriod }
let result = await refetch(refetchVars)
// Retry 1 раз при 429
const errMsg = (result as unknown as { error?: { message?: string } })?.error?.message || ''
if (!result.data?.getWildberriesStatistics?.success && errMsg.includes('429')) {
await new Promise((r) => setTimeout(r, 1200))
result = await refetch(refetchVars)
}
if (result.data?.getWildberriesStatistics?.success) {
console.warn('Sales: Loading fresh data from API')
// Обрабатываем данные в существующем useEffect
lastLoadedKeyRef.current = loadKey
}
} catch (error) {
console.error('Sales: Error loading data:', error)
} finally {
if (setIsLoadingData) setIsLoadingData(false)
loadingRef.current = false
}
}
@ -227,14 +248,12 @@ const SalesTab = React.memo(({
if (!shouldSkip) {
loadData()
}
}, [selectedPeriod, useCustomDates, startDate, endDate, getCachedData, refetch, setIsLoadingData])
}, [selectedPeriod, useCustomDates, startDate, endDate, getCachedData, refetch, setIsLoadingData, loadKey])
useEffect(() => {
if (wbData?.getWildberriesStatistics?.success && wbData.getWildberriesStatistics.data) {
const realData = wbData.getWildberriesStatistics.data
// Улучшенная агрегация с более надежной обработкой дат
const aggregateByDate = (
// Применение данных: агрегация, сортировка, установка состояний и кэша
const applyData = useCallback((realData: Array<{ date: string; sales: number; orders: number; advertising: number; refusals: number; returns: number; revenue: number; buyoutPercentage: number }>) => {
// Улучшенная агрегация с более надежной обработкой дат
const aggregateByDate = (
data: Array<{
date: string
sales: number
@ -325,51 +344,55 @@ const SalesTab = React.memo(({
: 0,
}))
}
const aggregatedData = aggregateByDate(realData)
const aggregatedData = aggregateByDate(realData)
// Сортируем по дате (новые сверху)
const sortedData = aggregatedData.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
// Сортируем по дате (новые сверху)
const sortedData = aggregatedData.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
// Обновляем данные для графика
const newChartData = sortedData.map((item) => ({
date: new Date(item.date).toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit' }),
sales: item.sales,
orders: item.orders,
advertising: Math.round(item.advertising),
refusals: item.refusals,
returns: item.returns,
}))
// Обновляем данные для графика
const newChartData = sortedData.map((item) => ({
date: new Date(item.date).toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit' }),
sales: item.sales,
orders: item.orders,
advertising: Math.round(item.advertising),
refusals: item.refusals,
returns: item.returns,
}))
// Обновляем данные для таблицы
const newTableData = sortedData.map((item) => ({
date: new Date(item.date).toLocaleDateString('ru-RU'),
salesUnits: item.sales,
buyoutPercentage: item.buyoutPercentage,
advertising: Math.round(item.advertising),
orders: item.orders,
refusals: item.refusals,
returns: item.returns,
revenue: Math.round(item.revenue),
}))
// Обновляем данные для таблицы
const newTableData = sortedData.map((item) => ({
date: new Date(item.date).toLocaleDateString('ru-RU'),
salesUnits: item.sales,
buyoutPercentage: item.buyoutPercentage,
advertising: Math.round(item.advertising),
orders: item.orders,
refusals: item.refusals,
returns: item.returns,
revenue: Math.round(item.revenue),
}))
setChartData(newChartData.reverse()) // Для графика - старые даты слева
setTableData(newTableData) // Для таблицы - новые даты сверху
setChartData(newChartData.reverse()) // Для графика - старые даты слева
setTableData(newTableData) // Для таблицы - новые даты сверху
// Сохраняем данные в кэш
if (setCachedData) {
const cacheData = {
chartData: newChartData,
tableData: newTableData,
totalSales: newTableData.reduce((sum, item) => sum + item.sales, 0),
totalOrders: newTableData.reduce((sum, item) => sum + item.orders, 0),
productsCount: newTableData.length,
}
setCachedData(cacheData)
console.warn('Sales: Data cached successfully')
// Сохраняем данные в кэш
if (setCachedData) {
const cacheData = {
chartData: newChartData,
tableData: newTableData,
totalSales: newTableData.reduce((sum, item) => sum + item.salesUnits, 0),
totalOrders: newTableData.reduce((sum, item) => sum + item.orders, 0),
productsCount: newTableData.length,
}
setCachedData(cacheData)
console.warn('Sales: Data cached successfully')
}
}, [wbData, setCachedData])
}, [setCachedData])
useEffect(() => {
if (wbData?.getWildberriesStatistics?.success && wbData.getWildberriesStatistics.data) {
applyData(wbData.getWildberriesStatistics.data)
}
}, [wbData, applyData])
// Функция для переключения видимости метрики
const toggleMetric = (metric: keyof typeof visibleMetrics) => {

View File

@ -2,20 +2,13 @@
import { useQuery } from '@apollo/client'
import {
ChevronDown,
ChevronRight,
Plus,
Trash2,
Link,
Copy,
Eye,
MousePointer,
ShoppingCart,
DollarSign,
Search,
Package,
Copy,
Package,
Plus,
Search,
Trash2
} from 'lucide-react'
import React, { useState } from 'react'
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
@ -374,11 +367,16 @@ export function SimpleAdvertisingTable({
{/* Реклама внешняя - многострочная ячейка с кнопками */}
<div className="text-center">
<div className="space-y-1">
{product.advertising.externalAds.map((ad) => (
{product.advertising.externalAds.map((ad) => {
const overlayClicks = generatedLinksData[day.date]?.find(
(link) => link.adId === ad.id,
)?.clicks
const displayClicks = overlayClicks ?? ad.clicks ?? 0
return (
<div key={ad.id} className="text-xs bg-purple-500/10 rounded p-1">
<div className="text-purple-400 font-medium truncate">{ad.name}</div>
<div className="text-white/80">{formatCurrency(ad.cost)}</div>
<div className="text-white/60">{ad.clicks || 0} кликов</div>
<div className="text-white/60">{displayClicks} кликов</div>
<div className="flex gap-1 justify-center mt-1">
{onGenerateLink && (
<Button
@ -410,7 +408,8 @@ export function SimpleAdvertisingTable({
)}
</div>
</div>
))}
)
})}
{/* Инлайн форма добавления внешней рекламы */}
{onAddExternalAd && (

View File

@ -1,8 +1,8 @@
'use client'
/* eslint-disable @typescript-eslint/no-explicit-any */
import { useQuery, useMutation } from '@apollo/client'
import React, { useState, useEffect } from 'react'
import { useMutation, useQuery } from '@apollo/client'
import { useEffect, useState } from 'react'
import { toast } from 'sonner'
import { Sidebar } from '@/components/dashboard/sidebar'
@ -112,17 +112,17 @@ export function WBWarehouseDashboard() {
// Получаем аналитические данные для данного nmId
const analytics = analyticsMap.get(card.nmID)
if (analytics && Array.isArray(analytics)) {
analytics.forEach((item: any) => {
if (item.stocks && Array.isArray(item.stocks)) {
item.stocks.forEach((stockItem: any) => {
if (analytics && analytics.data && analytics.data.regions && Array.isArray(analytics.data.regions)) {
analytics.data.regions.forEach((region: any) => {
if (region.offices && Array.isArray(region.offices)) {
region.offices.forEach((office: any) => {
stock.stocks.push({
warehouseId: stockItem.warehouseId || 0,
warehouseName: String(stockItem.warehouseName || 'Неизвестный склад'),
quantity: Number(stockItem.quantity) || 0,
quantityFull: Number(stockItem.quantityFull) || 0,
inWayToClient: Number(stockItem.inWayToClient) || 0,
inWayFromClient: Number(stockItem.inWayFromClient) || 0,
warehouseId: office.officeID || 0,
warehouseName: String(office.officeName || 'Неизвестный склад'),
quantity: Number(office.metrics?.stockCount) || 0,
quantityFull: Number(office.metrics?.stockCount) || 0,
inWayToClient: Number(office.metrics?.toClientCount) || 0,
inWayFromClient: Number(office.metrics?.fromClientCount) || 0,
})
})
}
@ -363,12 +363,12 @@ export function WBWarehouseDashboard() {
}, [cacheLoading, user?.organization, initialized])
return (
<div className="h-screen flex overflow-hidden">
<div className="h-screen flex overflow-hidden min-h-0">
<Sidebar />
<main className={`flex-1 ${getSidebarMargin()} px-6 py-4 overflow-hidden transition-all duration-300`}>
<div className="h-full w-full flex flex-col">
<main className={`flex-1 ${getSidebarMargin()} px-6 py-4 overflow-hidden transition-all duration-300 min-h-0 flex flex-col`}>
<div className="h-full w-full flex flex-col min-h-0">
{/* Табы */}
<Tabs value={activeTab} onValueChange={setActiveTab} className="flex-1 flex flex-col">
<Tabs value={activeTab} onValueChange={setActiveTab} className="flex-1 flex flex-col min-h-0">
<TabsList className="grid grid-cols-3 w-full max-w-md mb-6 bg-white/5 border border-white/10">
<TabsTrigger
value="fulfillment"
@ -390,12 +390,12 @@ export function WBWarehouseDashboard() {
</TabsTrigger>
</TabsList>
<div className="flex-1 overflow-hidden">
<TabsContent value="fulfillment" className="h-full mt-0">
<div className="flex-1 overflow-hidden min-h-0">
<TabsContent value="fulfillment" className="h-full mt-0 min-h-0">
<FulfillmentWarehouseTab />
</TabsContent>
<TabsContent value="wildberries" className="h-full mt-0">
<TabsContent value="wildberries" className="h-full mt-0 min-h-0">
<WildberriesWarehouseTab
stocks={stocks}
warehouses={warehouses}
@ -412,7 +412,7 @@ export function WBWarehouseDashboard() {
/>
</TabsContent>
<TabsContent value="my-warehouse" className="h-full mt-0">
<TabsContent value="my-warehouse" className="h-full mt-0 min-h-0">
<MyWarehouseTab />
</TabsContent>
</div>

View File

@ -1,8 +1,8 @@
'use client'
/* eslint-disable @typescript-eslint/no-explicit-any */
import { TrendingUp, Package } from 'lucide-react'
import React, { useState } from 'react'
import { Package, TrendingUp } from 'lucide-react'
import { useState } from 'react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
@ -97,41 +97,45 @@ export function WildberriesWarehouseTab({
}
return (
<div className="h-full flex flex-col">
<div className="h-full flex flex-col overflow-hidden min-h-0">
{/* Статистика */}
<StatsCards
totalProducts={totalProducts}
totalStocks={totalStocks}
totalReserved={totalReserved}
totalFromClient={totalFromClient}
activeWarehouses={activeWarehouses}
loading={!initialized || loading || cacheLoading}
/>
<div className="flex-shrink-0">
<StatsCards
totalProducts={totalProducts}
totalStocks={totalStocks}
totalReserved={totalReserved}
totalFromClient={totalFromClient}
activeWarehouses={activeWarehouses}
loading={!initialized || loading || cacheLoading}
/>
</div>
{/* Аналитика по складам WB */}
{initialized && analyticsData.length > 0 && (
<Card className="glass-card border-white/10 p-4 mb-6">
<h3 className="text-lg font-semibold text-white mb-4 flex items-center">
<TrendingUp className="h-5 w-5 mr-2 text-blue-400" />
Аналитика по складам WB
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{analyticsData.slice(0, 6).map((item, index) => (
<div key={index} className="bg-white/5 rounded-lg p-3">
<div className="text-sm text-white/60">Склад {index + 1}</div>
<div className="text-lg font-medium text-white">
{JSON.stringify(item).length > 50
? `${JSON.stringify(item).substring(0, 50)}...`
: JSON.stringify(item)}
<div className="flex-shrink-0 mb-4">
<Card className="glass-card border-white/10 p-4">
<h3 className="text-lg font-semibold text-white mb-4 flex items-center">
<TrendingUp className="h-5 w-5 mr-2 text-blue-400" />
Аналитика по складам WB
</h3>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{analyticsData.slice(0, 6).map((item, index) => (
<div key={index} className="bg-white/5 rounded-lg p-3">
<div className="text-sm text-white/60">Склад {index + 1}</div>
<div className="text-lg font-medium text-white">
{JSON.stringify(item).length > 50
? `${JSON.stringify(item).substring(0, 50)}...`
: JSON.stringify(item)}
</div>
</div>
</div>
))}
</div>
</Card>
))}
</div>
</Card>
</div>
)}
{/* Основной контент */}
<Card className="glass-card border-white/10 flex-1 flex flex-col overflow-hidden">
<Card className="glass-card border-white/10 flex-1 flex flex-col overflow-hidden min-h-0">
<div className="p-6 border-b border-white/10 flex-shrink-0">
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
<div>
@ -155,7 +159,7 @@ export function WildberriesWarehouseTab({
</div>
{/* Контент с таблицей */}
<div className="flex-1 overflow-hidden">
<div className="flex-1 overflow-hidden min-h-0">
{!initialized || loading || cacheLoading ? (
<div className="p-6">
<LoadingSkeleton />
@ -173,7 +177,7 @@ export function WildberriesWarehouseTab({
</div>
</div>
) : (
<div className="h-full overflow-auto">
<div className="h-full overflow-y-auto">
<div className="p-6 space-y-3">
{/* Заголовок таблицы */}
<TableHeader />

View File

@ -9,7 +9,7 @@ import { MarketplaceService } from '@/services/marketplace-service'
import { SmsService } from '@/services/sms-service'
import { WildberriesService } from '@/services/wildberries-service'
import '@/lib/seed-init' // Автоматическая инициализация БД
import '@/lib/seed-init'; // Автоматическая инициализация БД
// Сервисы
const smsService = new SmsService()
@ -7489,6 +7489,68 @@ const wildberriesQueries = {
}
} catch (error) {
console.error('Error fetching WB statistics:', error)
// Фолбэк: пробуем вернуть последние данные из кеша статистики селлера
try {
const user = await prisma.user.findUnique({
where: { id: context.user!.id },
include: { organization: true },
})
if (user?.organization) {
const whereCache: any = {
organizationId: user.organization.id,
period: startDate && endDate ? 'custom' : period ?? 'week',
}
if (startDate && endDate) {
whereCache.dateFrom = new Date(startDate)
whereCache.dateTo = new Date(endDate)
}
const cache = await prisma.sellerStatsCache.findFirst({
where: whereCache,
orderBy: { createdAt: 'desc' },
})
if (cache?.productsData) {
// Ожидаем, что productsData — строка JSON с полями, сохраненными клиентом
const parsed = JSON.parse(cache.productsData as unknown as string) as {
tableData?: Array<{
date: string
salesUnits: number
orders: number
advertising: number
refusals: number
returns: number
revenue: number
buyoutPercentage: number
}>
}
const table = parsed.tableData ?? []
const dataFromCache = table.map((row) => ({
date: row.date,
sales: row.salesUnits,
orders: row.orders,
advertising: row.advertising,
refusals: row.refusals,
returns: row.returns,
revenue: row.revenue,
buyoutPercentage: row.buyoutPercentage,
}))
if (dataFromCache.length > 0) {
return {
success: true,
data: dataFromCache,
message: 'Данные возвращены из кеша из-за ошибки WB API',
}
}
}
}
} catch (fallbackErr) {
console.error('Seller stats cache fallback failed:', fallbackErr)
}
return {
success: false,
message: error instanceof Error ? error.message : 'Ошибка получения статистики',
@ -8186,6 +8248,84 @@ resolvers.Query = {
...wildberriesQueries,
...externalAdQueries,
...wbWarehouseCacheQueries,
// Кеш статистики селлера
getSellerStatsCache: async (
_: unknown,
args: { period: string; dateFrom?: string | null; dateTo?: string | null },
context: Context,
) => {
if (!context.user) {
throw new GraphQLError('Требуется авторизация', {
extensions: { code: 'UNAUTHENTICATED' },
})
}
try {
const user = await prisma.user.findUnique({
where: { id: context.user.id },
include: { organization: true },
})
if (!user?.organization) {
throw new GraphQLError('Организация не найдена')
}
const today = new Date()
today.setHours(0, 0, 0, 0)
// Для custom учитываем диапазон, иначе только period
const where: any = {
organizationId: user.organization.id,
cacheDate: today,
period: args.period,
}
if (args.period === 'custom') {
if (!args.dateFrom || !args.dateTo) {
throw new GraphQLError('Для custom необходимо указать dateFrom и dateTo')
}
where.dateFrom = new Date(args.dateFrom)
where.dateTo = new Date(args.dateTo)
}
const cache = await prisma.sellerStatsCache.findFirst({
where,
orderBy: { createdAt: 'desc' },
})
if (!cache) {
return {
success: true,
message: 'Кеш не найден',
cache: null,
fromCache: false,
}
}
return {
success: true,
message: 'Данные получены из кеша',
cache: {
...cache,
cacheDate: cache.cacheDate.toISOString().split('T')[0],
dateFrom: cache.dateFrom ? cache.dateFrom.toISOString().split('T')[0] : null,
dateTo: cache.dateTo ? cache.dateTo.toISOString().split('T')[0] : null,
productsTotalSales: cache.productsTotalSales ? Number(cache.productsTotalSales) : null,
advertisingTotalCost: cache.advertisingTotalCost ? Number(cache.advertisingTotalCost) : null,
createdAt: cache.createdAt.toISOString(),
updatedAt: cache.updatedAt.toISOString(),
},
fromCache: true,
}
} catch (error) {
console.error('Error getting Seller Stats cache:', error)
return {
success: false,
message: error instanceof Error ? error.message : 'Ошибка получения кеша статистики',
cache: null,
fromCache: false,
}
}
},
}
resolvers.Mutation = {
@ -8193,4 +8333,87 @@ resolvers.Mutation = {
...adminMutations,
...externalAdMutations,
...wbWarehouseCacheMutations,
// Сохранение кеша статистики селлера
saveSellerStatsCache: async (
_: unknown,
{ input }: { input: { period: string; dateFrom?: string | null; dateTo?: string | null; productsData?: string | null; productsTotalSales?: number | null; productsTotalOrders?: number | null; productsCount?: number | null; advertisingData?: string | null; advertisingTotalCost?: number | null; advertisingTotalViews?: number | null; advertisingTotalClicks?: number | null; expiresAt: string } },
context: Context,
) => {
if (!context.user) {
throw new GraphQLError('Требуется авторизация', {
extensions: { code: 'UNAUTHENTICATED' },
})
}
try {
const user = await prisma.user.findUnique({
where: { id: context.user.id },
include: { organization: true },
})
if (!user?.organization) {
throw new GraphQLError('Организация не найдена')
}
const today = new Date()
today.setHours(0, 0, 0, 0)
const data: any = {
organizationId: user.organization.id,
cacheDate: today,
period: input.period,
dateFrom: input.period === 'custom' && input.dateFrom ? new Date(input.dateFrom) : null,
dateTo: input.period === 'custom' && input.dateTo ? new Date(input.dateTo) : null,
productsData: input.productsData ?? null,
productsTotalSales: input.productsTotalSales ?? null,
productsTotalOrders: input.productsTotalOrders ?? null,
productsCount: input.productsCount ?? null,
advertisingData: input.advertisingData ?? null,
advertisingTotalCost: input.advertisingTotalCost ?? null,
advertisingTotalViews: input.advertisingTotalViews ?? null,
advertisingTotalClicks: input.advertisingTotalClicks ?? null,
expiresAt: new Date(input.expiresAt),
}
// upsert с составным уникальным ключом, содержащим NULL, в Prisma вызывает валидацию.
// Делаем вручную: findFirst по уникальному набору, затем update или create.
const existing = await prisma.sellerStatsCache.findFirst({
where: {
organizationId: user.organization.id,
cacheDate: today,
period: input.period,
dateFrom: data.dateFrom,
dateTo: data.dateTo,
},
})
const cache = existing
? await prisma.sellerStatsCache.update({ where: { id: existing.id }, data })
: await prisma.sellerStatsCache.create({ data })
return {
success: true,
message: 'Кеш статистики сохранен',
cache: {
...cache,
cacheDate: cache.cacheDate.toISOString().split('T')[0],
dateFrom: cache.dateFrom ? cache.dateFrom.toISOString().split('T')[0] : null,
dateTo: cache.dateTo ? cache.dateTo.toISOString().split('T')[0] : null,
productsTotalSales: cache.productsTotalSales ? Number(cache.productsTotalSales) : null,
advertisingTotalCost: cache.advertisingTotalCost ? Number(cache.advertisingTotalCost) : null,
createdAt: cache.createdAt.toISOString(),
updatedAt: cache.updatedAt.toISOString(),
},
fromCache: false,
}
} catch (error) {
console.error('Error saving Seller Stats cache:', error)
return {
success: false,
message: error instanceof Error ? error.message : 'Ошибка сохранения кеша статистики',
cache: null,
fromCache: false,
}
}
},
}

View File

@ -1325,6 +1325,59 @@ export const typeDefs = gql`
saveWBWarehouseCache(input: WBWarehouseCacheInput!): WBWarehouseCacheResponse!
}
# Типы для кеша статистики продаж селлера
type SellerStatsCache {
id: ID!
organizationId: String!
cacheDate: String!
period: String!
dateFrom: String
dateTo: String
productsData: String
productsTotalSales: Float
productsTotalOrders: Int
productsCount: Int
advertisingData: String
advertisingTotalCost: Float
advertisingTotalViews: Int
advertisingTotalClicks: Int
expiresAt: String!
createdAt: String!
updatedAt: String!
}
type SellerStatsCacheResponse {
success: Boolean!
message: String
cache: SellerStatsCache
fromCache: Boolean!
}
input SellerStatsCacheInput {
period: String!
dateFrom: String
dateTo: String
productsData: String
productsTotalSales: Float
productsTotalOrders: Int
productsCount: Int
advertisingData: String
advertisingTotalCost: Float
advertisingTotalViews: Int
advertisingTotalClicks: Int
expiresAt: String!
}
extend type Query {
getSellerStatsCache(period: String!, dateFrom: String, dateTo: String): SellerStatsCacheResponse!
}
extend type Mutation {
saveSellerStatsCache(input: SellerStatsCacheInput!): SellerStatsCacheResponse!
}
# Типы для заявок на возврат WB
type WbReturnClaim {
id: String!

View File

@ -1,30 +1,30 @@
// Общее хранилище кликов для всех API роутов
class ClickStorage {
private static instance: ClickStorage
private storage = new Map<string, number>()
// Глобальное хранилище кликов на уровне процесса, общее для всех роутов
// Важно: в serverless/edge окружении память не шарится между инстансами.
// Для dev/Node runtime это обеспечит единый Map для разных route-бандлов.
static getInstance(): ClickStorage {
if (!ClickStorage.instance) {
ClickStorage.instance = new ClickStorage()
}
return ClickStorage.instance
}
recordClick(linkId: string): number {
const currentClicks = this.storage.get(linkId) || 0
const newClicks = currentClicks + 1
this.storage.set(linkId, newClicks)
console.warn(`Click recorded for ${linkId}: ${newClicks} total`)
return newClicks
}
getClicks(linkId: string): number {
return this.storage.get(linkId) || 0
}
getAllClicks(): Record<string, number> {
return Object.fromEntries(this.storage)
}
type GlobalWithClickStorage = typeof globalThis & {
__CLICK_STORAGE__?: Map<string, number>
}
export const clickStorage = ClickStorage.getInstance()
const g = globalThis as GlobalWithClickStorage
if (!g.__CLICK_STORAGE__) {
g.__CLICK_STORAGE__ = new Map<string, number>()
}
const storage = g.__CLICK_STORAGE__
export const clickStorage = {
recordClick(linkId: string): number {
const currentClicks = storage!.get(linkId) || 0
const newClicks = currentClicks + 1
storage!.set(linkId, newClicks)
console.warn(`Click recorded for ${linkId}: ${newClicks} total`)
return newClicks
},
getClicks(linkId: string): number {
return storage!.get(linkId) || 0
},
getAllClicks(): Record<string, number> {
return Object.fromEntries(storage!)
},
}