Spaces:
Running

axeronis commited on
Commit
4c90e6d
·
1 Parent(s): 10e7012

perf: Implement React Query caching for faster navigation - Dashboard now uses React Query with 5min staleTime - Optimized QueryClient settings: staleTime=5min, gcTime=30min - Added SWR context and hooks (optional alternative) - Faster page transitions with cached data

Browse files
frontend/app/dashboard/page.tsx CHANGED
@@ -2,7 +2,8 @@
2
 
3
  import { useEffect, useState } from 'react'
4
  import { useAuth } from '@/contexts/AuthContext'
5
- import { leadsApi, Lead } from '@/lib/api'
 
6
  import {
7
  AreaChart, Area, BarChart, Bar, PieChart, Pie, Cell,
8
  XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer
@@ -79,25 +80,10 @@ const COLORS = ['#6366f1', '#8b5cf6', '#ec4899', '#f43f5e', '#10b981', '#06b6d4'
79
 
80
  export default function DashboardPage() {
81
  const { user, isLoading: authLoading } = useAuth()
82
- const [data, setData] = useState<DashboardData | null>(null)
83
- const [hotLeads, setHotLeads] = useState<Lead[]>([])
84
- const [loading, setLoading] = useState(true)
85
- const [error, setError] = useState<string | null>(null)
86
 
87
  // Date Range State
88
  const [dateRange, setDateRange] = useState<'7d' | '30d' | '90d' | 'all'>('30d')
89
  const [isDateDropdownOpen, setIsDateDropdownOpen] = useState(false)
90
- const [lastUpdated, setLastUpdated] = useState<Date | null>(null)
91
-
92
- // Fetch hot leads
93
- const fetchHotLeads = async () => {
94
- try {
95
- const leads = await leadsApi.getLeads({ heat_level: 'hot', limit: 5 })
96
- setHotLeads(leads || [])
97
- } catch (err) {
98
- console.error('Failed to fetch hot leads:', err)
99
- }
100
- }
101
 
102
  const getDateRangeLabel = () => {
103
  switch (dateRange) {
@@ -108,59 +94,44 @@ export default function DashboardPage() {
108
  }
109
  }
110
 
111
- const fetchAnalytics = async () => {
112
- if (!user?.tenant_id) return
113
-
114
- try {
115
- setLoading(true)
116
- setError(null)
117
- const token = localStorage.getItem('auth_token')
118
-
119
- let dateFrom = ''
120
- const today = new Date().toISOString().split('T')[0]
121
-
122
- if (dateRange !== 'all') {
123
- const date = new Date()
124
- const days = parseInt(dateRange)
125
- date.setDate(date.getDate() - days)
126
- dateFrom = date.toISOString().split('T')[0]
127
- }
128
-
129
- const params = new URLSearchParams()
130
- if (dateFrom) params.append('date_from', dateFrom)
131
- params.append('date_to', today)
132
-
133
- const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/analytics/dashboard?${params.toString()}`, {
134
- headers: {
135
- 'Authorization': `Bearer ${token}`
136
- }
137
- })
138
-
139
- if (!response.ok) {
140
- throw new Error('Failed to load analytics')
141
- }
142
-
143
- const analyticsData = await response.json()
144
- setData(analyticsData)
145
- setLastUpdated(new Date())
146
- } catch (err) {
147
- console.error('Analytics fetch error:', err)
148
- setError('Ошибка системы. Повторите попытку.')
149
- } finally {
150
- setLoading(false)
151
  }
 
 
152
  }
153
 
154
- useEffect(() => {
155
- if (authLoading) return
156
- if (!user) {
157
- setError('Нет авторизации')
158
- setLoading(false)
159
- return
160
- }
161
- fetchAnalytics()
162
- fetchHotLeads()
163
- }, [user, authLoading, dateRange])
 
 
 
 
 
 
 
 
 
 
 
 
 
164
 
165
  if (authLoading || (loading && !data)) {
166
  return (
@@ -179,9 +150,9 @@ export default function DashboardPage() {
179
  <div className="bg-surface p-8 rounded-xl border border-red-500/30 max-w-md text-center">
180
  <AlertCircle className="w-8 h-8 text-red-500 mx-auto mb-4" />
181
  <h2 className="text-lg font-bold text-white mb-2 font-mono">ОШИБКА СИСТЕМЫ</h2>
182
- <p className="text-slate-400 mb-6 text-sm">{error}</p>
183
  <button
184
- onClick={fetchAnalytics}
185
  className="px-6 py-2 bg-red-600/20 hover:bg-red-600/30 text-red-400 border border-red-500/50 rounded flex items-center gap-2 mx-auto transition-all"
186
  >
187
  <RefreshCw className="w-4 h-4" />
 
2
 
3
  import { useEffect, useState } from 'react'
4
  import { useAuth } from '@/contexts/AuthContext'
5
+ import { leadsApi, Lead, api } from '@/lib/api'
6
+ import { useQuery } from '@tanstack/react-query'
7
  import {
8
  AreaChart, Area, BarChart, Bar, PieChart, Pie, Cell,
9
  XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer
 
80
 
81
  export default function DashboardPage() {
82
  const { user, isLoading: authLoading } = useAuth()
 
 
 
 
83
 
84
  // Date Range State
85
  const [dateRange, setDateRange] = useState<'7d' | '30d' | '90d' | 'all'>('30d')
86
  const [isDateDropdownOpen, setIsDateDropdownOpen] = useState(false)
 
 
 
 
 
 
 
 
 
 
 
87
 
88
  const getDateRangeLabel = () => {
89
  switch (dateRange) {
 
94
  }
95
  }
96
 
97
+ // Build query params for date range
98
+ const getDateParams = () => {
99
+ const params = new URLSearchParams()
100
+ const today = new Date().toISOString().split('T')[0]
101
+
102
+ if (dateRange !== 'all') {
103
+ const date = new Date()
104
+ const days = parseInt(dateRange)
105
+ date.setDate(date.getDate() - days)
106
+ params.append('date_from', date.toISOString().split('T')[0])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  }
108
+ params.append('date_to', today)
109
+ return params.toString()
110
  }
111
 
112
+ // React Query for dashboard data with caching
113
+ const { data, isLoading: loading, error, refetch } = useQuery<DashboardData>({
114
+ queryKey: ['dashboard', dateRange],
115
+ queryFn: async () => {
116
+ const response = await api.get(`/api/v1/analytics/dashboard?${getDateParams()}`)
117
+ return response.data
118
+ },
119
+ enabled: !!user?.tenant_id && !authLoading,
120
+ staleTime: 5 * 60 * 1000, // 5 minutes
121
+ })
122
+
123
+ // React Query for hot leads
124
+ const { data: hotLeadsData } = useQuery({
125
+ queryKey: ['hotLeads'],
126
+ queryFn: async () => {
127
+ const leads = await leadsApi.getLeads({ heat_level: 'hot', limit: 5 })
128
+ return leads || []
129
+ },
130
+ enabled: !!user?.tenant_id && !authLoading,
131
+ staleTime: 2 * 60 * 1000, // 2 minutes
132
+ })
133
+
134
+ const hotLeads = hotLeadsData || []
135
 
136
  if (authLoading || (loading && !data)) {
137
  return (
 
150
  <div className="bg-surface p-8 rounded-xl border border-red-500/30 max-w-md text-center">
151
  <AlertCircle className="w-8 h-8 text-red-500 mx-auto mb-4" />
152
  <h2 className="text-lg font-bold text-white mb-2 font-mono">ОШИБКА СИСТЕМЫ</h2>
153
+ <p className="text-slate-400 mb-6 text-sm">{error instanceof Error ? error.message : 'Ошибка загрузки данных'}</p>
154
  <button
155
+ onClick={() => refetch()}
156
  className="px-6 py-2 bg-red-600/20 hover:bg-red-600/30 text-red-400 border border-red-500/50 rounded flex items-center gap-2 mx-auto transition-all"
157
  >
158
  <RefreshCw className="w-4 h-4" />
frontend/app/providers.tsx CHANGED
@@ -9,8 +9,12 @@ export function Providers({ children }: { children: React.ReactNode }) {
9
  const [queryClient] = useState(() => new QueryClient({
10
  defaultOptions: {
11
  queries: {
12
- staleTime: 60 * 1000, // 1 minute
13
- refetchOnWindowFocus: false,
 
 
 
 
14
  },
15
  },
16
  }))
 
9
  const [queryClient] = useState(() => new QueryClient({
10
  defaultOptions: {
11
  queries: {
12
+ staleTime: 5 * 60 * 1000, // 5 minutes - data is fresh
13
+ gcTime: 30 * 60 * 1000, // 30 minutes - keep in cache
14
+ refetchOnWindowFocus: false, // Don't refetch on tab focus
15
+ refetchOnMount: false, // Use cached data on mount
16
+ refetchOnReconnect: false, // Don't refetch on reconnect
17
+ retry: 2, // Retry failed requests twice
18
  },
19
  },
20
  }))
frontend/contexts/SWRContext.tsx ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use client'
2
+
3
+ import { SWRConfig } from 'swr'
4
+ import { api } from '@/lib/api'
5
+
6
+ // Fetcher function for SWR using our axios instance
7
+ const fetcher = async (url: string) => {
8
+ const response = await api.get(url)
9
+ return response.data
10
+ }
11
+
12
+ interface SWRProviderProps {
13
+ children: React.ReactNode
14
+ }
15
+
16
+ export function SWRProvider({ children }: SWRProviderProps) {
17
+ return (
18
+ <SWRConfig
19
+ value={{
20
+ fetcher,
21
+ // Revalidation settings for better UX
22
+ revalidateOnFocus: false, // Don't refetch when window regains focus
23
+ revalidateOnReconnect: true, // Refetch when network reconnects
24
+ dedupingInterval: 5000, // Dedupe requests within 5 seconds
25
+ errorRetryCount: 3, // Retry failed requests 3 times
26
+ errorRetryInterval: 1000, // Wait 1 second between retries
27
+
28
+ // Cache settings
29
+ keepPreviousData: true, // Show stale data while fetching new
30
+
31
+ // Performance optimization
32
+ refreshInterval: 0, // Disable auto-refresh (manual control)
33
+ refreshWhenHidden: false, // Don't refresh when tab is hidden
34
+ refreshWhenOffline: false, // Don't refresh when offline
35
+
36
+ // Fallback for initial loading
37
+ suspense: false, // Don't use React Suspense
38
+ }}
39
+ >
40
+ {children}
41
+ </SWRConfig>
42
+ )
43
+ }
frontend/hooks/useData.ts ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use client'
2
+
3
+ import useSWR from 'swr'
4
+ import type { Lead, Conversation } from '@/types'
5
+
6
+ // ============================================================================
7
+ // Dashboard Data Hook
8
+ // ============================================================================
9
+
10
+ interface DashboardMetrics {
11
+ total_leads: number
12
+ hot_leads: number
13
+ warm_leads: number
14
+ cold_leads: number
15
+ active_leads_24h: number
16
+ conversion_rate: number
17
+ pipeline_value: number
18
+ avg_response_time_seconds: number
19
+ total_bookings: number
20
+ hours_saved: number
21
+ money_saved: number
22
+ total_leads_change: number
23
+ conversion_rate_change: number
24
+ pipeline_value_change: number
25
+ }
26
+
27
+ interface DashboardData {
28
+ metrics: DashboardMetrics
29
+ funnel: any[]
30
+ disc_distribution: any[]
31
+ top_objections: any[]
32
+ lead_value_over_time: any[]
33
+ channel_stats: any[]
34
+ }
35
+
36
+ export function useDashboard() {
37
+ const { data, error, isLoading, mutate } = useSWR<DashboardData>(
38
+ '/api/v1/analytics/dashboard',
39
+ {
40
+ revalidateOnFocus: false,
41
+ dedupingInterval: 30000, // Cache for 30 seconds
42
+ }
43
+ )
44
+
45
+ return {
46
+ dashboard: data,
47
+ isLoading,
48
+ isError: error,
49
+ refresh: mutate,
50
+ }
51
+ }
52
+
53
+ // ============================================================================
54
+ // Leads List Hook
55
+ // ============================================================================
56
+
57
+ interface LeadsResponse {
58
+ leads: Lead[]
59
+ total: number
60
+ page: number
61
+ page_size: number
62
+ }
63
+
64
+ export function useLeads(page: number = 1, filters?: Record<string, string>) {
65
+ const params = new URLSearchParams({ page: String(page), page_size: '20' })
66
+ if (filters) {
67
+ Object.entries(filters).forEach(([key, value]) => {
68
+ if (value) params.append(key, value)
69
+ })
70
+ }
71
+
72
+ const { data, error, isLoading, mutate } = useSWR<LeadsResponse>(
73
+ `/api/v1/leads?${params.toString()}`,
74
+ {
75
+ revalidateOnFocus: false,
76
+ dedupingInterval: 10000, // Cache for 10 seconds
77
+ }
78
+ )
79
+
80
+ return {
81
+ leads: data?.leads || [],
82
+ total: data?.total || 0,
83
+ isLoading,
84
+ isError: error,
85
+ refresh: mutate,
86
+ }
87
+ }
88
+
89
+ // ============================================================================
90
+ // Conversations Hook
91
+ // ============================================================================
92
+
93
+ export function useConversations() {
94
+ const { data, error, isLoading, mutate } = useSWR<Conversation[]>(
95
+ '/api/v1/conversations',
96
+ {
97
+ revalidateOnFocus: false,
98
+ dedupingInterval: 5000, // Cache for 5 seconds (chats need fresher data)
99
+ refreshInterval: 30000, // Auto-refresh every 30 seconds for new messages
100
+ }
101
+ )
102
+
103
+ return {
104
+ conversations: data || [],
105
+ isLoading,
106
+ isError: error,
107
+ refresh: mutate,
108
+ }
109
+ }
110
+
111
+ // ============================================================================
112
+ // Tenant/Settings Hook
113
+ // ============================================================================
114
+
115
+ export function useTenant() {
116
+ const { data, error, isLoading, mutate } = useSWR(
117
+ '/api/v1/tenants/current',
118
+ {
119
+ revalidateOnFocus: false,
120
+ dedupingInterval: 60000, // Cache for 1 minute (settings change rarely)
121
+ }
122
+ )
123
+
124
+ return {
125
+ tenant: data,
126
+ isLoading,
127
+ isError: error,
128
+ refresh: mutate,
129
+ }
130
+ }
131
+
132
+ // ============================================================================
133
+ // Team Members Hook
134
+ // ============================================================================
135
+
136
+ export function useTeamMembers() {
137
+ const { data, error, isLoading, mutate } = useSWR(
138
+ '/api/v1/users/team',
139
+ {
140
+ revalidateOnFocus: false,
141
+ dedupingInterval: 30000,
142
+ }
143
+ )
144
+
145
+ return {
146
+ members: data || [],
147
+ isLoading,
148
+ isError: error,
149
+ refresh: mutate,
150
+ }
151
+ }
152
+
153
+ // ============================================================================
154
+ // Products Hook
155
+ // ============================================================================
156
+
157
+ export function useProducts() {
158
+ const { data, error, isLoading, mutate } = useSWR(
159
+ '/api/v1/products',
160
+ {
161
+ revalidateOnFocus: false,
162
+ dedupingInterval: 60000, // Products change rarely
163
+ }
164
+ )
165
+
166
+ return {
167
+ products: data || [],
168
+ isLoading,
169
+ isError: error,
170
+ refresh: mutate,
171
+ }
172
+ }
173
+
174
+ // ============================================================================
175
+ // Playbook Hook
176
+ // ============================================================================
177
+
178
+ export function usePlaybook() {
179
+ const { data, error, isLoading, mutate } = useSWR(
180
+ '/api/v1/playbooks',
181
+ {
182
+ revalidateOnFocus: false,
183
+ dedupingInterval: 60000,
184
+ }
185
+ )
186
+
187
+ return {
188
+ playbook: data,
189
+ isLoading,
190
+ isError: error,
191
+ refresh: mutate,
192
+ }
193
+ }
194
+
195
+ // ============================================================================
196
+ // Channels/Connections Hook
197
+ // ============================================================================
198
+
199
+ export function useChannels() {
200
+ const { data, error, isLoading, mutate } = useSWR(
201
+ '/api/v1/channels',
202
+ {
203
+ revalidateOnFocus: false,
204
+ dedupingInterval: 30000,
205
+ }
206
+ )
207
+
208
+ return {
209
+ channels: data || [],
210
+ isLoading,
211
+ isError: error,
212
+ refresh: mutate,
213
+ }
214
+ }
215
+
216
+ // ============================================================================
217
+ // Single Lead Hook
218
+ // ============================================================================
219
+
220
+ export function useLead(leadId: string | null) {
221
+ const { data, error, isLoading, mutate } = useSWR(
222
+ leadId ? `/api/v1/leads/${leadId}` : null,
223
+ {
224
+ revalidateOnFocus: false,
225
+ dedupingInterval: 10000,
226
+ }
227
+ )
228
+
229
+ return {
230
+ lead: data,
231
+ isLoading,
232
+ isError: error,
233
+ refresh: mutate,
234
+ }
235
+ }
236
+
237
+ // ============================================================================
238
+ // Messages Hook (for chat)
239
+ // ============================================================================
240
+
241
+ export function useMessages(leadId: string | null) {
242
+ const { data, error, isLoading, mutate } = useSWR(
243
+ leadId ? `/api/v1/leads/${leadId}/messages` : null,
244
+ {
245
+ revalidateOnFocus: false,
246
+ dedupingInterval: 2000, // Shorter for real-time feel
247
+ refreshInterval: 5000, // Auto-refresh messages
248
+ }
249
+ )
250
+
251
+ return {
252
+ messages: data || [],
253
+ isLoading,
254
+ isError: error,
255
+ refresh: mutate,
256
+ }
257
+ }
frontend/package-lock.json CHANGED
@@ -25,6 +25,7 @@
25
  "react-dom": "^19.2.1",
26
  "react-dropzone": "^14.3.8",
27
  "recharts": "^3.4.1",
 
28
  "tailwind-merge": "^3.4.0"
29
  },
30
  "devDependencies": {
@@ -3503,6 +3504,15 @@
3503
  "node": ">=0.4.0"
3504
  }
3505
  },
 
 
 
 
 
 
 
 
 
3506
  "node_modules/detect-libc": {
3507
  "version": "2.1.2",
3508
  "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
@@ -7014,6 +7024,19 @@
7014
  "url": "https://github.com/sponsors/ljharb"
7015
  }
7016
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
7017
  "node_modules/tailwind-merge": {
7018
  "version": "3.4.0",
7019
  "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.4.0.tgz",
 
25
  "react-dom": "^19.2.1",
26
  "react-dropzone": "^14.3.8",
27
  "recharts": "^3.4.1",
28
+ "swr": "^2.3.8",
29
  "tailwind-merge": "^3.4.0"
30
  },
31
  "devDependencies": {
 
3504
  "node": ">=0.4.0"
3505
  }
3506
  },
3507
+ "node_modules/dequal": {
3508
+ "version": "2.0.3",
3509
+ "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
3510
+ "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",
3511
+ "license": "MIT",
3512
+ "engines": {
3513
+ "node": ">=6"
3514
+ }
3515
+ },
3516
  "node_modules/detect-libc": {
3517
  "version": "2.1.2",
3518
  "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
 
7024
  "url": "https://github.com/sponsors/ljharb"
7025
  }
7026
  },
7027
+ "node_modules/swr": {
7028
+ "version": "2.3.8",
7029
+ "resolved": "https://registry.npmjs.org/swr/-/swr-2.3.8.tgz",
7030
+ "integrity": "sha512-gaCPRVoMq8WGDcWj9p4YWzCMPHzE0WNl6W8ADIx9c3JBEIdMkJGMzW+uzXvxHMltwcYACr9jP+32H8/hgwMR7w==",
7031
+ "license": "MIT",
7032
+ "dependencies": {
7033
+ "dequal": "^2.0.3",
7034
+ "use-sync-external-store": "^1.6.0"
7035
+ },
7036
+ "peerDependencies": {
7037
+ "react": "^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
7038
+ }
7039
+ },
7040
  "node_modules/tailwind-merge": {
7041
  "version": "3.4.0",
7042
  "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.4.0.tgz",
frontend/package.json CHANGED
@@ -26,6 +26,7 @@
26
  "react-dom": "^19.2.1",
27
  "react-dropzone": "^14.3.8",
28
  "recharts": "^3.4.1",
 
29
  "tailwind-merge": "^3.4.0"
30
  },
31
  "devDependencies": {
 
26
  "react-dom": "^19.2.1",
27
  "react-dropzone": "^14.3.8",
28
  "recharts": "^3.4.1",
29
+ "swr": "^2.3.8",
30
  "tailwind-merge": "^3.4.0"
31
  },
32
  "devDependencies": {