Обновление компонентов интерфейса и оптимизация логики
- Добавлен компонент AppShell в RootLayout для улучшения структуры - Обновлен компонент Sidebar для предотвращения дублирования при рендеринге - Оптимизированы импорты в компонентах AdvertisingTab и SalesTab - Реализована логика кэширования статистики селлера в GraphQL резолверах
This commit is contained in:
4
.vscode/settings.json
vendored
4
.vscode/settings.json
vendored
@ -2,8 +2,8 @@
|
|||||||
"editor.formatOnSave": true,
|
"editor.formatOnSave": true,
|
||||||
"editor.defaultFormatter": "esbenp.prettier-vscode",
|
"editor.defaultFormatter": "esbenp.prettier-vscode",
|
||||||
"editor.codeActionsOnSave": {
|
"editor.codeActionsOnSave": {
|
||||||
"source.fixAll.eslint": true,
|
"source.fixAll.eslint": "explicit",
|
||||||
"source.organizeImports": true
|
"source.organizeImports": "explicit"
|
||||||
},
|
},
|
||||||
"typescript.tsdk": "node_modules/typescript/lib",
|
"typescript.tsdk": "node_modules/typescript/lib",
|
||||||
"typescript.enablePromptUseWorkspaceTsdk": true,
|
"typescript.enablePromptUseWorkspaceTsdk": true,
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
import { AppShell } from '@/components/layout/app-shell'
|
||||||
import { Toaster } from '@/components/ui/sonner'
|
import { Toaster } from '@/components/ui/sonner'
|
||||||
|
|
||||||
import './globals.css'
|
import './globals.css'
|
||||||
@ -7,7 +8,11 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|||||||
return (
|
return (
|
||||||
<html lang="ru" className="dark">
|
<html lang="ru" className="dark">
|
||||||
<body className="min-h-screen bg-gradient-smooth text-white overflow-x-hidden">
|
<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 />
|
<Toaster />
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
@ -2,24 +2,24 @@
|
|||||||
|
|
||||||
import { useQuery } from '@apollo/client'
|
import { useQuery } from '@apollo/client'
|
||||||
import {
|
import {
|
||||||
Settings,
|
BarChart3,
|
||||||
LogOut,
|
ChevronLeft,
|
||||||
Store,
|
ChevronRight,
|
||||||
MessageCircle,
|
DollarSign,
|
||||||
Wrench,
|
Handshake,
|
||||||
Warehouse,
|
Home,
|
||||||
Users,
|
LogOut,
|
||||||
Truck,
|
MessageCircle,
|
||||||
Handshake,
|
Settings,
|
||||||
ChevronLeft,
|
Store,
|
||||||
ChevronRight,
|
Truck,
|
||||||
BarChart3,
|
Users,
|
||||||
Home,
|
Warehouse,
|
||||||
DollarSign,
|
Wrench,
|
||||||
} from 'lucide-react'
|
} 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 { Button } from '@/components/ui/button'
|
||||||
import { GET_CONVERSATIONS, GET_INCOMING_REQUESTS, GET_PENDING_SUPPLIES_COUNT } from '@/graphql/queries'
|
import { GET_CONVERSATIONS, GET_INCOMING_REQUESTS, GET_PENDING_SUPPLIES_COUNT } from '@/graphql/queries'
|
||||||
import { useAuth } from '@/hooks/useAuth'
|
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 { user, logout } = useAuth()
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const pathname = usePathname()
|
const pathname = usePathname()
|
||||||
@ -236,6 +246,11 @@ export function Sidebar() {
|
|||||||
pathname.startsWith('/supplier-orders')
|
pathname.startsWith('/supplier-orders')
|
||||||
const isPartnersActive = pathname.startsWith('/partners')
|
const isPartnersActive = pathname.startsWith('/partners')
|
||||||
|
|
||||||
|
// Помечаем, что корневой экземпляр смонтирован
|
||||||
|
if (typeof window !== 'undefined' && isRootInstance) {
|
||||||
|
;(window as any).__SIDEBAR_ROOT_MOUNTED__ = true
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
{/* Основной сайдбар */}
|
{/* Основной сайдбар */}
|
||||||
@ -255,7 +270,6 @@ export function Sidebar() {
|
|||||||
size="icon"
|
size="icon"
|
||||||
onClick={toggleSidebar}
|
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"
|
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">
|
<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>
|
<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>
|
</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>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
19
src/components/layout/app-shell.tsx
Normal file
19
src/components/layout/app-shell.tsx
Normal 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>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
6
src/components/layout/sidebar-root-context.ts
Normal file
6
src/components/layout/sidebar-root-context.ts
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { createContext } from 'react'
|
||||||
|
|
||||||
|
export const SidebarRootContext = createContext<boolean>(false)
|
||||||
|
|
@ -1,61 +1,39 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useQuery, useLazyQuery, useMutation } from '@apollo/client'
|
import { useLazyQuery, useMutation, useQuery } from '@apollo/client'
|
||||||
import {
|
import {
|
||||||
TrendingUp,
|
AlertCircle,
|
||||||
TrendingDown,
|
BarChart3,
|
||||||
Eye,
|
Eye,
|
||||||
MousePointer,
|
Minimize2,
|
||||||
ShoppingCart,
|
TrendingUp
|
||||||
DollarSign,
|
|
||||||
ChevronRight,
|
|
||||||
ChevronDown,
|
|
||||||
Plus,
|
|
||||||
Trash2,
|
|
||||||
ExternalLink,
|
|
||||||
Copy,
|
|
||||||
AlertCircle,
|
|
||||||
BarChart3,
|
|
||||||
Minimize2,
|
|
||||||
Calendar,
|
|
||||||
Package,
|
|
||||||
Link,
|
|
||||||
Smartphone,
|
|
||||||
Monitor,
|
|
||||||
Globe,
|
|
||||||
Target,
|
|
||||||
ArrowUpDown,
|
|
||||||
Percent,
|
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
import React, { useState, useEffect, useRef, useMemo, useCallback } from 'react'
|
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||||
import {
|
import {
|
||||||
LineChart,
|
Bar,
|
||||||
Line,
|
BarChart,
|
||||||
XAxis,
|
CartesianGrid,
|
||||||
YAxis,
|
ResponsiveContainer,
|
||||||
CartesianGrid,
|
XAxis,
|
||||||
BarChart,
|
YAxis
|
||||||
Bar,
|
|
||||||
ResponsiveContainer,
|
|
||||||
ComposedChart,
|
|
||||||
} from 'recharts'
|
} from 'recharts'
|
||||||
|
|
||||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||||
import { Badge } from '@/components/ui/badge'
|
import { Badge } from '@/components/ui/badge'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Card } from '@/components/ui/card'
|
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 { Checkbox } from '@/components/ui/checkbox'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
import { Label } from '@/components/ui/label'
|
import { Label } from '@/components/ui/label'
|
||||||
import { Skeleton } from '@/components/ui/skeleton'
|
import { Skeleton } from '@/components/ui/skeleton'
|
||||||
import {
|
import {
|
||||||
CREATE_EXTERNAL_AD,
|
CREATE_EXTERNAL_AD,
|
||||||
DELETE_EXTERNAL_AD,
|
DELETE_EXTERNAL_AD,
|
||||||
UPDATE_EXTERNAL_AD,
|
UPDATE_EXTERNAL_AD,
|
||||||
UPDATE_EXTERNAL_AD_CLICKS,
|
UPDATE_EXTERNAL_AD_CLICKS,
|
||||||
} from '@/graphql/mutations'
|
} 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 { useAuth } from '@/hooks/useAuth'
|
||||||
import { WildberriesService } from '@/services/wildberries-service'
|
import { WildberriesService } from '@/services/wildberries-service'
|
||||||
|
|
||||||
@ -770,19 +748,76 @@ const AdvertisingTab = React.memo(({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Автоматически загружаем все доступные кампании
|
// Функция запуска загрузки статистики кампаний (стабилизирована)
|
||||||
useEffect(() => {
|
const handleCampaignsSelected = useCallback((ids: number[]) => {
|
||||||
if (campaignsData?.getWildberriesCampaignsList?.data?.adverts) {
|
if (ids.length === 0) return
|
||||||
const campaigns = campaignsData.getWildberriesCampaignsList.data.adverts
|
|
||||||
const allCampaignIds = campaigns.flatMap((group: CampaignGroup) =>
|
|
||||||
group.advert_list.map((item: CampaignListItem) => item.advertId),
|
|
||||||
)
|
|
||||||
|
|
||||||
if (allCampaignIds.length > 0) {
|
let campaigns
|
||||||
handleCampaignsSelected(allCampaignIds)
|
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[] => {
|
const convertCampaignDataToDailyData = (campaigns: CampaignStats[]): DailyAdvertisingData[] => {
|
||||||
@ -1018,8 +1053,8 @@ const AdvertisingTab = React.memo(({
|
|||||||
setDailyData(newDailyData)
|
setDailyData(newDailyData)
|
||||||
prevCampaignStats.current = campaignStats
|
prevCampaignStats.current = campaignStats
|
||||||
|
|
||||||
// Сохраняем данные в кэш
|
// Сохраняем данные в кэш (через ref, чтобы не зациклиться на изменении ссылки функции)
|
||||||
if (setCachedData) {
|
if (setCachedDataRef.current) {
|
||||||
const cacheData = {
|
const cacheData = {
|
||||||
dailyData: newDailyData,
|
dailyData: newDailyData,
|
||||||
campaignStats: campaignStats,
|
campaignStats: campaignStats,
|
||||||
@ -1033,56 +1068,20 @@ const AdvertisingTab = React.memo(({
|
|||||||
0,
|
0,
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
setCachedData(cacheData)
|
setCachedDataRef.current(cacheData)
|
||||||
console.warn('Advertising: Data cached successfully')
|
console.warn('Advertising: Data cached successfully')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [campaignStats, externalAdsData, setCachedData]) // Добавляем externalAdsData и setCachedData в зависимости
|
}, [campaignStats, externalAdsData])
|
||||||
|
|
||||||
const handleCampaignsSelected = (ids: number[]) => {
|
// Храним setCachedData в ref, чтобы не триггерить эффект из-за смены ссылки на функцию в родителе
|
||||||
if (ids.length === 0) return
|
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 toggleCampaignExpanded = (campaignId: number) => {
|
||||||
const newExpanded = new Set(expandedCampaigns)
|
const newExpanded = new Set(expandedCampaigns)
|
||||||
|
@ -1,10 +1,9 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { useQuery } from '@apollo/client'
|
import { gql, useQuery } from '@apollo/client'
|
||||||
import { gql } from '@apollo/client'
|
import { BarChart3, ChevronDown, ChevronUp, Info, TrendingUp } from 'lucide-react'
|
||||||
import { TrendingUp, Info, BarChart3, ChevronDown, ChevronUp } from 'lucide-react'
|
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||||
import React, { useState, useEffect, useMemo, useCallback } from 'react'
|
import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from 'recharts'
|
||||||
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, ResponsiveContainer } from 'recharts'
|
|
||||||
|
|
||||||
import { Badge } from '@/components/ui/badge'
|
import { Badge } from '@/components/ui/badge'
|
||||||
import { Card } from '@/components/ui/card'
|
import { Card } from '@/components/ui/card'
|
||||||
@ -192,9 +191,20 @@ const SalesTab = React.memo(({
|
|||||||
skip: true, // Изначально пропускаем запрос, будем запускать вручную
|
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(() => {
|
useEffect(() => {
|
||||||
const loadData = async () => {
|
const loadData = async () => {
|
||||||
|
if (loadingRef.current) return
|
||||||
|
if (lastLoadedKeyRef.current === loadKey) return
|
||||||
|
loadingRef.current = true
|
||||||
// Сначала проверяем локальный кэш
|
// Сначала проверяем локальный кэш
|
||||||
if (getCachedData) {
|
if (getCachedData) {
|
||||||
const cachedData = getCachedData()
|
const cachedData = getCachedData()
|
||||||
@ -202,6 +212,8 @@ const SalesTab = React.memo(({
|
|||||||
setChartData(cachedData.chartData || mockChartData)
|
setChartData(cachedData.chartData || mockChartData)
|
||||||
setTableData(cachedData.tableData || mockTableData)
|
setTableData(cachedData.tableData || mockTableData)
|
||||||
console.warn('Sales: Using cached data')
|
console.warn('Sales: Using cached data')
|
||||||
|
lastLoadedKeyRef.current = loadKey
|
||||||
|
loadingRef.current = false
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -210,15 +222,24 @@ const SalesTab = React.memo(({
|
|||||||
if (setIsLoadingData) setIsLoadingData(true)
|
if (setIsLoadingData) setIsLoadingData(true)
|
||||||
|
|
||||||
try {
|
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) {
|
if (result.data?.getWildberriesStatistics?.success) {
|
||||||
console.warn('Sales: Loading fresh data from API')
|
console.warn('Sales: Loading fresh data from API')
|
||||||
// Обрабатываем данные в существующем useEffect
|
// Обрабатываем данные в существующем useEffect
|
||||||
|
lastLoadedKeyRef.current = loadKey
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Sales: Error loading data:', error)
|
console.error('Sales: Error loading data:', error)
|
||||||
} finally {
|
} finally {
|
||||||
if (setIsLoadingData) setIsLoadingData(false)
|
if (setIsLoadingData) setIsLoadingData(false)
|
||||||
|
loadingRef.current = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -227,14 +248,12 @@ const SalesTab = React.memo(({
|
|||||||
if (!shouldSkip) {
|
if (!shouldSkip) {
|
||||||
loadData()
|
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 applyData = useCallback((realData: Array<{ date: string; sales: number; orders: number; advertising: number; refusals: number; returns: number; revenue: number; buyoutPercentage: number }>) => {
|
||||||
const realData = wbData.getWildberriesStatistics.data
|
// Улучшенная агрегация с более надежной обработкой дат
|
||||||
|
const aggregateByDate = (
|
||||||
// Улучшенная агрегация с более надежной обработкой дат
|
|
||||||
const aggregateByDate = (
|
|
||||||
data: Array<{
|
data: Array<{
|
||||||
date: string
|
date: string
|
||||||
sales: number
|
sales: number
|
||||||
@ -325,51 +344,55 @@ const SalesTab = React.memo(({
|
|||||||
: 0,
|
: 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) => ({
|
const newTableData = sortedData.map((item) => ({
|
||||||
date: new Date(item.date).toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit' }),
|
date: new Date(item.date).toLocaleDateString('ru-RU'),
|
||||||
sales: item.sales,
|
salesUnits: item.sales,
|
||||||
orders: item.orders,
|
buyoutPercentage: item.buyoutPercentage,
|
||||||
advertising: Math.round(item.advertising),
|
advertising: Math.round(item.advertising),
|
||||||
refusals: item.refusals,
|
orders: item.orders,
|
||||||
returns: item.returns,
|
refusals: item.refusals,
|
||||||
}))
|
returns: item.returns,
|
||||||
|
revenue: Math.round(item.revenue),
|
||||||
|
}))
|
||||||
|
|
||||||
// Обновляем данные для таблицы
|
setChartData(newChartData.reverse()) // Для графика - старые даты слева
|
||||||
const newTableData = sortedData.map((item) => ({
|
setTableData(newTableData) // Для таблицы - новые даты сверху
|
||||||
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) // Для таблицы - новые даты сверху
|
if (setCachedData) {
|
||||||
|
const cacheData = {
|
||||||
// Сохраняем данные в кэш
|
chartData: newChartData,
|
||||||
if (setCachedData) {
|
tableData: newTableData,
|
||||||
const cacheData = {
|
totalSales: newTableData.reduce((sum, item) => sum + item.salesUnits, 0),
|
||||||
chartData: newChartData,
|
totalOrders: newTableData.reduce((sum, item) => sum + item.orders, 0),
|
||||||
tableData: newTableData,
|
productsCount: newTableData.length,
|
||||||
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')
|
|
||||||
}
|
}
|
||||||
|
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) => {
|
const toggleMetric = (metric: keyof typeof visibleMetrics) => {
|
||||||
|
@ -2,20 +2,13 @@
|
|||||||
|
|
||||||
import { useQuery } from '@apollo/client'
|
import { useQuery } from '@apollo/client'
|
||||||
import {
|
import {
|
||||||
ChevronDown,
|
Copy,
|
||||||
ChevronRight,
|
Package,
|
||||||
Plus,
|
Plus,
|
||||||
Trash2,
|
Search,
|
||||||
Link,
|
Trash2
|
||||||
Copy,
|
|
||||||
Eye,
|
|
||||||
MousePointer,
|
|
||||||
ShoppingCart,
|
|
||||||
DollarSign,
|
|
||||||
Search,
|
|
||||||
Package,
|
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
import React, { useState } from 'react'
|
import { useState } from 'react'
|
||||||
|
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
@ -374,11 +367,16 @@ export function SimpleAdvertisingTable({
|
|||||||
{/* Реклама внешняя - многострочная ячейка с кнопками */}
|
{/* Реклама внешняя - многострочная ячейка с кнопками */}
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
<div className="space-y-1">
|
<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 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-purple-400 font-medium truncate">{ad.name}</div>
|
||||||
<div className="text-white/80">{formatCurrency(ad.cost)}</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">
|
<div className="flex gap-1 justify-center mt-1">
|
||||||
{onGenerateLink && (
|
{onGenerateLink && (
|
||||||
<Button
|
<Button
|
||||||
@ -410,7 +408,8 @@ export function SimpleAdvertisingTable({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
)
|
||||||
|
})}
|
||||||
|
|
||||||
{/* Инлайн форма добавления внешней рекламы */}
|
{/* Инлайн форма добавления внешней рекламы */}
|
||||||
{onAddExternalAd && (
|
{onAddExternalAd && (
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
'use client'
|
'use client'
|
||||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
|
|
||||||
import { useQuery, useMutation } from '@apollo/client'
|
import { useMutation, useQuery } from '@apollo/client'
|
||||||
import React, { useState, useEffect } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { toast } from 'sonner'
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
import { Sidebar } from '@/components/dashboard/sidebar'
|
import { Sidebar } from '@/components/dashboard/sidebar'
|
||||||
@ -112,17 +112,17 @@ export function WBWarehouseDashboard() {
|
|||||||
|
|
||||||
// Получаем аналитические данные для данного nmId
|
// Получаем аналитические данные для данного nmId
|
||||||
const analytics = analyticsMap.get(card.nmID)
|
const analytics = analyticsMap.get(card.nmID)
|
||||||
if (analytics && Array.isArray(analytics)) {
|
if (analytics && analytics.data && analytics.data.regions && Array.isArray(analytics.data.regions)) {
|
||||||
analytics.forEach((item: any) => {
|
analytics.data.regions.forEach((region: any) => {
|
||||||
if (item.stocks && Array.isArray(item.stocks)) {
|
if (region.offices && Array.isArray(region.offices)) {
|
||||||
item.stocks.forEach((stockItem: any) => {
|
region.offices.forEach((office: any) => {
|
||||||
stock.stocks.push({
|
stock.stocks.push({
|
||||||
warehouseId: stockItem.warehouseId || 0,
|
warehouseId: office.officeID || 0,
|
||||||
warehouseName: String(stockItem.warehouseName || 'Неизвестный склад'),
|
warehouseName: String(office.officeName || 'Неизвестный склад'),
|
||||||
quantity: Number(stockItem.quantity) || 0,
|
quantity: Number(office.metrics?.stockCount) || 0,
|
||||||
quantityFull: Number(stockItem.quantityFull) || 0,
|
quantityFull: Number(office.metrics?.stockCount) || 0,
|
||||||
inWayToClient: Number(stockItem.inWayToClient) || 0,
|
inWayToClient: Number(office.metrics?.toClientCount) || 0,
|
||||||
inWayFromClient: Number(stockItem.inWayFromClient) || 0,
|
inWayFromClient: Number(office.metrics?.fromClientCount) || 0,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@ -363,12 +363,12 @@ export function WBWarehouseDashboard() {
|
|||||||
}, [cacheLoading, user?.organization, initialized])
|
}, [cacheLoading, user?.organization, initialized])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="h-screen flex overflow-hidden">
|
<div className="h-screen flex overflow-hidden min-h-0">
|
||||||
<Sidebar />
|
<Sidebar />
|
||||||
<main className={`flex-1 ${getSidebarMargin()} px-6 py-4 overflow-hidden transition-all duration-300`}>
|
<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">
|
<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">
|
<TabsList className="grid grid-cols-3 w-full max-w-md mb-6 bg-white/5 border border-white/10">
|
||||||
<TabsTrigger
|
<TabsTrigger
|
||||||
value="fulfillment"
|
value="fulfillment"
|
||||||
@ -390,12 +390,12 @@ export function WBWarehouseDashboard() {
|
|||||||
</TabsTrigger>
|
</TabsTrigger>
|
||||||
</TabsList>
|
</TabsList>
|
||||||
|
|
||||||
<div className="flex-1 overflow-hidden">
|
<div className="flex-1 overflow-hidden min-h-0">
|
||||||
<TabsContent value="fulfillment" className="h-full mt-0">
|
<TabsContent value="fulfillment" className="h-full mt-0 min-h-0">
|
||||||
<FulfillmentWarehouseTab />
|
<FulfillmentWarehouseTab />
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
|
|
||||||
<TabsContent value="wildberries" className="h-full mt-0">
|
<TabsContent value="wildberries" className="h-full mt-0 min-h-0">
|
||||||
<WildberriesWarehouseTab
|
<WildberriesWarehouseTab
|
||||||
stocks={stocks}
|
stocks={stocks}
|
||||||
warehouses={warehouses}
|
warehouses={warehouses}
|
||||||
@ -412,7 +412,7 @@ export function WBWarehouseDashboard() {
|
|||||||
/>
|
/>
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
|
|
||||||
<TabsContent value="my-warehouse" className="h-full mt-0">
|
<TabsContent value="my-warehouse" className="h-full mt-0 min-h-0">
|
||||||
<MyWarehouseTab />
|
<MyWarehouseTab />
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
</div>
|
</div>
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
'use client'
|
'use client'
|
||||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||||
|
|
||||||
import { TrendingUp, Package } from 'lucide-react'
|
import { Package, TrendingUp } from 'lucide-react'
|
||||||
import React, { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { toast } from 'sonner'
|
import { toast } from 'sonner'
|
||||||
|
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
@ -97,41 +97,45 @@ export function WildberriesWarehouseTab({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="h-full flex flex-col">
|
<div className="h-full flex flex-col overflow-hidden min-h-0">
|
||||||
{/* Статистика */}
|
{/* Статистика */}
|
||||||
<StatsCards
|
<div className="flex-shrink-0">
|
||||||
totalProducts={totalProducts}
|
<StatsCards
|
||||||
totalStocks={totalStocks}
|
totalProducts={totalProducts}
|
||||||
totalReserved={totalReserved}
|
totalStocks={totalStocks}
|
||||||
totalFromClient={totalFromClient}
|
totalReserved={totalReserved}
|
||||||
activeWarehouses={activeWarehouses}
|
totalFromClient={totalFromClient}
|
||||||
loading={!initialized || loading || cacheLoading}
|
activeWarehouses={activeWarehouses}
|
||||||
/>
|
loading={!initialized || loading || cacheLoading}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Аналитика по складам WB */}
|
{/* Аналитика по складам WB */}
|
||||||
{initialized && analyticsData.length > 0 && (
|
{initialized && analyticsData.length > 0 && (
|
||||||
<Card className="glass-card border-white/10 p-4 mb-6">
|
<div className="flex-shrink-0 mb-4">
|
||||||
<h3 className="text-lg font-semibold text-white mb-4 flex items-center">
|
<Card className="glass-card border-white/10 p-4">
|
||||||
<TrendingUp className="h-5 w-5 mr-2 text-blue-400" />
|
<h3 className="text-lg font-semibold text-white mb-4 flex items-center">
|
||||||
Аналитика по складам WB
|
<TrendingUp className="h-5 w-5 mr-2 text-blue-400" />
|
||||||
</h3>
|
Аналитика по складам WB
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
</h3>
|
||||||
{analyticsData.slice(0, 6).map((item, index) => (
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||||
<div key={index} className="bg-white/5 rounded-lg p-3">
|
{analyticsData.slice(0, 6).map((item, index) => (
|
||||||
<div className="text-sm text-white/60">Склад {index + 1}</div>
|
<div key={index} className="bg-white/5 rounded-lg p-3">
|
||||||
<div className="text-lg font-medium text-white">
|
<div className="text-sm text-white/60">Склад {index + 1}</div>
|
||||||
{JSON.stringify(item).length > 50
|
<div className="text-lg font-medium text-white">
|
||||||
? `${JSON.stringify(item).substring(0, 50)}...`
|
{JSON.stringify(item).length > 50
|
||||||
: JSON.stringify(item)}
|
? `${JSON.stringify(item).substring(0, 50)}...`
|
||||||
|
: JSON.stringify(item)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
))}
|
||||||
))}
|
</div>
|
||||||
</div>
|
</Card>
|
||||||
</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="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 className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
|
||||||
<div>
|
<div>
|
||||||
@ -155,7 +159,7 @@ export function WildberriesWarehouseTab({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Контент с таблицей */}
|
{/* Контент с таблицей */}
|
||||||
<div className="flex-1 overflow-hidden">
|
<div className="flex-1 overflow-hidden min-h-0">
|
||||||
{!initialized || loading || cacheLoading ? (
|
{!initialized || loading || cacheLoading ? (
|
||||||
<div className="p-6">
|
<div className="p-6">
|
||||||
<LoadingSkeleton />
|
<LoadingSkeleton />
|
||||||
@ -173,7 +177,7 @@ export function WildberriesWarehouseTab({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="h-full overflow-auto">
|
<div className="h-full overflow-y-auto">
|
||||||
<div className="p-6 space-y-3">
|
<div className="p-6 space-y-3">
|
||||||
{/* Заголовок таблицы */}
|
{/* Заголовок таблицы */}
|
||||||
<TableHeader />
|
<TableHeader />
|
||||||
|
@ -9,7 +9,7 @@ import { MarketplaceService } from '@/services/marketplace-service'
|
|||||||
import { SmsService } from '@/services/sms-service'
|
import { SmsService } from '@/services/sms-service'
|
||||||
import { WildberriesService } from '@/services/wildberries-service'
|
import { WildberriesService } from '@/services/wildberries-service'
|
||||||
|
|
||||||
import '@/lib/seed-init' // Автоматическая инициализация БД
|
import '@/lib/seed-init'; // Автоматическая инициализация БД
|
||||||
|
|
||||||
// Сервисы
|
// Сервисы
|
||||||
const smsService = new SmsService()
|
const smsService = new SmsService()
|
||||||
@ -7489,6 +7489,68 @@ const wildberriesQueries = {
|
|||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error fetching WB statistics:', 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 {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
message: error instanceof Error ? error.message : 'Ошибка получения статистики',
|
message: error instanceof Error ? error.message : 'Ошибка получения статистики',
|
||||||
@ -8186,6 +8248,84 @@ resolvers.Query = {
|
|||||||
...wildberriesQueries,
|
...wildberriesQueries,
|
||||||
...externalAdQueries,
|
...externalAdQueries,
|
||||||
...wbWarehouseCacheQueries,
|
...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 = {
|
resolvers.Mutation = {
|
||||||
@ -8193,4 +8333,87 @@ resolvers.Mutation = {
|
|||||||
...adminMutations,
|
...adminMutations,
|
||||||
...externalAdMutations,
|
...externalAdMutations,
|
||||||
...wbWarehouseCacheMutations,
|
...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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
@ -1325,6 +1325,59 @@ export const typeDefs = gql`
|
|||||||
saveWBWarehouseCache(input: WBWarehouseCacheInput!): WBWarehouseCacheResponse!
|
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
|
# Типы для заявок на возврат WB
|
||||||
type WbReturnClaim {
|
type WbReturnClaim {
|
||||||
id: String!
|
id: String!
|
||||||
|
@ -1,30 +1,30 @@
|
|||||||
// Общее хранилище кликов для всех API роутов
|
// Глобальное хранилище кликов на уровне процесса, общее для всех роутов
|
||||||
class ClickStorage {
|
// Важно: в serverless/edge окружении память не шарится между инстансами.
|
||||||
private static instance: ClickStorage
|
// Для dev/Node runtime это обеспечит единый Map для разных route-бандлов.
|
||||||
private storage = new Map<string, number>()
|
|
||||||
|
|
||||||
static getInstance(): ClickStorage {
|
type GlobalWithClickStorage = typeof globalThis & {
|
||||||
if (!ClickStorage.instance) {
|
__CLICK_STORAGE__?: Map<string, number>
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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!)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
Reference in New Issue
Block a user