Spaces:
Running

axeronis commited on
Commit
53b30a5
·
1 Parent(s): baea058

Perf: Migrate remaining pages to React Query caching - profile, voice, partners

Browse files
frontend/app/partners/page.tsx CHANGED
@@ -1,7 +1,8 @@
1
  'use client'
2
 
3
- import { useState, useEffect } from 'react'
4
  import Link from 'next/link'
 
5
  import { useAuth } from '@/contexts/AuthContext'
6
  import { useToast } from '@/contexts/ToastContext'
7
  import { api } from '@/lib/api'
@@ -38,46 +39,41 @@ interface Referral {
38
  }
39
 
40
  export default function PartnersPage() {
41
- const { user, isLoading: authLoading } = useAuth()
42
  const toast = useToast()
43
- const [loading, setLoading] = useState(true)
44
- const [partner, setPartner] = useState<PartnerData | null>(null)
45
- const [referrals, setReferrals] = useState<Referral[]>([])
46
  const [isJoining, setIsJoining] = useState(false)
47
  const [showPayoutModal, setShowPayoutModal] = useState(false)
48
  const [payoutAmount, setPayoutAmount] = useState('')
49
  const [payoutMethod, setPayoutMethod] = useState<'paypal' | 'crypto'>('paypal')
50
  const [payoutDetails, setPayoutDetails] = useState('')
51
 
52
- useEffect(() => {
53
- // Load data when user is available (from cache or fresh)
54
- if (user) {
55
- loadPartnerData()
56
- }
57
- }, [user])
58
-
59
- const loadPartnerData = async () => {
60
- try {
61
- const res = await api.get('/api/v1/partners/me')
62
- setPartner(res.data)
63
-
64
- // Load referrals if active
65
- if (res.data.status === 'ACTIVE') {
66
- try {
67
- const refRes = await api.get('/api/v1/partners/me/referrals')
68
- setReferrals(refRes.data)
69
- } catch (e) {
70
- console.error('Failed to load referrals')
71
- }
72
  }
73
- } catch (error: any) {
74
- if (error.response?.status !== 404) {
75
- console.error('Failed to load partner data')
76
- }
77
- } finally {
78
- setLoading(false)
79
- }
80
- }
 
 
 
 
 
 
 
81
 
82
  const handleJoin = async () => {
83
  const companyName = prompt('Введите название вашей компании:')
 
1
  'use client'
2
 
3
+ import { useState } from 'react'
4
  import Link from 'next/link'
5
+ import { useQuery, useQueryClient } from '@tanstack/react-query'
6
  import { useAuth } from '@/contexts/AuthContext'
7
  import { useToast } from '@/contexts/ToastContext'
8
  import { api } from '@/lib/api'
 
39
  }
40
 
41
  export default function PartnersPage() {
42
+ const { user } = useAuth()
43
  const toast = useToast()
44
+ const queryClient = useQueryClient()
 
 
45
  const [isJoining, setIsJoining] = useState(false)
46
  const [showPayoutModal, setShowPayoutModal] = useState(false)
47
  const [payoutAmount, setPayoutAmount] = useState('')
48
  const [payoutMethod, setPayoutMethod] = useState<'paypal' | 'crypto'>('paypal')
49
  const [payoutDetails, setPayoutDetails] = useState('')
50
 
51
+ // React Query for partner data - cached!
52
+ const { data: partner, isLoading: partnerLoading } = useQuery<PartnerData | null>({
53
+ queryKey: ['partner-data', user?.id],
54
+ queryFn: async () => {
55
+ try {
56
+ const res = await api.get('/api/v1/partners/me')
57
+ return res.data
58
+ } catch (error: any) {
59
+ if (error.response?.status === 404) return null
60
+ throw error
 
 
 
 
 
 
 
 
 
 
61
  }
62
+ },
63
+ enabled: !!user,
64
+ })
65
+
66
+ // React Query for referrals - cached!
67
+ const { data: referrals = [] } = useQuery<Referral[]>({
68
+ queryKey: ['partner-referrals', user?.id],
69
+ queryFn: async () => {
70
+ const res = await api.get('/api/v1/partners/me/referrals')
71
+ return res.data
72
+ },
73
+ enabled: !!user && partner?.status === 'ACTIVE',
74
+ })
75
+
76
+ const loading = partnerLoading
77
 
78
  const handleJoin = async () => {
79
  const companyName = prompt('Введите название вашей компании:')
frontend/app/settings/profile/page.tsx CHANGED
@@ -1,6 +1,7 @@
1
  'use client'
2
 
3
  import { useState, useEffect } from 'react'
 
4
  import { useAuth } from '@/contexts/AuthContext'
5
  import { useToast } from '@/contexts/ToastContext'
6
  import { api } from '@/lib/api'
@@ -10,7 +11,7 @@ import { motion } from 'framer-motion'
10
  export default function ProfilePage() {
11
  const { user } = useAuth()
12
  const toast = useToast()
13
- const [loading, setLoading] = useState(true)
14
  const [saving, setSaving] = useState(false)
15
  const [changingPassword, setChangingPassword] = useState(false)
16
 
@@ -26,24 +27,26 @@ export default function ProfilePage() {
26
  confirm_password: ''
27
  })
28
 
29
- useEffect(() => {
30
- loadProfile()
31
- }, [])
32
-
33
- const loadProfile = async () => {
34
- try {
35
  const res = await api.get('/api/v1/tenants/me')
 
 
 
 
 
 
 
 
36
  setFormData({
37
- full_name: user?.full_name || '',
38
- email: user?.email || '',
39
- company_name: res.data.company_name || ''
40
  })
41
- } catch (e) {
42
- console.error('Failed to load profile')
43
- } finally {
44
- setLoading(false)
45
  }
46
- }
47
 
48
  const handleSaveProfile = async (e: React.FormEvent) => {
49
  e.preventDefault()
@@ -52,6 +55,7 @@ export default function ProfilePage() {
52
  await api.patch('/api/v1/tenants/me', {
53
  company_name: formData.company_name
54
  })
 
55
  toast.success('Успех!', 'Профиль сохранён')
56
  } catch (e) {
57
  toast.error('Ошибка', 'Не удалось сохранить')
 
1
  'use client'
2
 
3
  import { useState, useEffect } from 'react'
4
+ import { useQuery, useQueryClient } from '@tanstack/react-query'
5
  import { useAuth } from '@/contexts/AuthContext'
6
  import { useToast } from '@/contexts/ToastContext'
7
  import { api } from '@/lib/api'
 
11
  export default function ProfilePage() {
12
  const { user } = useAuth()
13
  const toast = useToast()
14
+ const queryClient = useQueryClient()
15
  const [saving, setSaving] = useState(false)
16
  const [changingPassword, setChangingPassword] = useState(false)
17
 
 
27
  confirm_password: ''
28
  })
29
 
30
+ // React Query for tenant data - cached!
31
+ const { data: tenantData, isLoading: loading } = useQuery({
32
+ queryKey: ['tenant-profile', user?.tenant_id],
33
+ queryFn: async () => {
 
 
34
  const res = await api.get('/api/v1/tenants/me')
35
+ return res.data
36
+ },
37
+ enabled: !!user,
38
+ })
39
+
40
+ // Sync form data with query data
41
+ useEffect(() => {
42
+ if (tenantData && user) {
43
  setFormData({
44
+ full_name: user.full_name || '',
45
+ email: user.email || '',
46
+ company_name: tenantData.company_name || ''
47
  })
 
 
 
 
48
  }
49
+ }, [tenantData, user])
50
 
51
  const handleSaveProfile = async (e: React.FormEvent) => {
52
  e.preventDefault()
 
55
  await api.patch('/api/v1/tenants/me', {
56
  company_name: formData.company_name
57
  })
58
+ queryClient.invalidateQueries({ queryKey: ['tenant-profile'] })
59
  toast.success('Успех!', 'Профиль сохранён')
60
  } catch (e) {
61
  toast.error('Ошибка', 'Не удалось сохранить')
frontend/app/settings/voice/page.tsx CHANGED
@@ -1,6 +1,7 @@
1
  'use client'
2
 
3
  import React, { useState, useEffect } from 'react'
 
4
  import { useAuth } from '@/contexts/AuthContext'
5
  import {
6
  Mic, MicOff, Upload, Trash2, Save, Loader2, CheckCircle2,
@@ -54,38 +55,41 @@ const VOICE_OPTIONS = [
54
  ]
55
 
56
  export default function VoiceSettingsPage() {
57
- const { token } = useAuth()
58
  const toast = useToast()
 
59
  const [settings, setSettings] = useState<VoiceSettings>({
60
  voice_id: 'professional_male',
61
  voice_enabled: true,
62
  voice_reference_url: null
63
  })
64
- const [loading, setLoading] = useState(true)
65
  const [saving, setSaving] = useState(false)
66
  const [playingVoice, setPlayingVoice] = useState<string | null>(null)
67
- const [isServiceAvailable] = useState<boolean>(true) // Chatterbox deployed on Railway
68
  const audioRef = React.useRef<HTMLAudioElement | null>(null)
69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  useEffect(() => {
71
- const fetchSettings = async () => {
72
- try {
73
- const response = await api.get('/api/v1/tenants/me', {
74
- headers: { Authorization: `Bearer ${token}` }
75
- })
76
- setSettings({
77
- voice_id: response.data.voice_id || 'professional_male',
78
- voice_enabled: response.data.voice_enabled ?? true,
79
- voice_reference_url: response.data.voice_reference_url || null
80
- })
81
- } catch (error) {
82
- console.error('Failed to fetch voice settings:', error)
83
- } finally {
84
- setLoading(false)
85
- }
86
  }
87
- if (token) fetchSettings()
88
- }, [token])
89
 
90
  const playDemoVoice = async (voiceId: string, text: string) => {
91
  // Stop current playback
@@ -142,6 +146,7 @@ export default function VoiceSettingsPage() {
142
  await api.patch('/api/v1/tenants/me', settings, {
143
  headers: { Authorization: `Bearer ${token}` }
144
  })
 
145
  toast.success('Настройки голоса сохранены!')
146
  } catch (error) {
147
  toast.error('Ошибка сохранения настроек')
 
1
  'use client'
2
 
3
  import React, { useState, useEffect } from 'react'
4
+ import { useQuery, useQueryClient } from '@tanstack/react-query'
5
  import { useAuth } from '@/contexts/AuthContext'
6
  import {
7
  Mic, MicOff, Upload, Trash2, Save, Loader2, CheckCircle2,
 
55
  ]
56
 
57
  export default function VoiceSettingsPage() {
58
+ const { token, user } = useAuth()
59
  const toast = useToast()
60
+ const queryClient = useQueryClient()
61
  const [settings, setSettings] = useState<VoiceSettings>({
62
  voice_id: 'professional_male',
63
  voice_enabled: true,
64
  voice_reference_url: null
65
  })
 
66
  const [saving, setSaving] = useState(false)
67
  const [playingVoice, setPlayingVoice] = useState<string | null>(null)
68
+ const [isServiceAvailable] = useState<boolean>(true)
69
  const audioRef = React.useRef<HTMLAudioElement | null>(null)
70
 
71
+ // React Query for voice settings - cached!
72
+ const { data: tenantData, isLoading: loading } = useQuery({
73
+ queryKey: ['voice-settings', user?.tenant_id],
74
+ queryFn: async () => {
75
+ const response = await api.get('/api/v1/tenants/me', {
76
+ headers: { Authorization: `Bearer ${token}` }
77
+ })
78
+ return response.data
79
+ },
80
+ enabled: !!token && !!user,
81
+ })
82
+
83
+ // Sync settings with query data
84
  useEffect(() => {
85
+ if (tenantData) {
86
+ setSettings({
87
+ voice_id: tenantData.voice_id || 'professional_male',
88
+ voice_enabled: tenantData.voice_enabled ?? true,
89
+ voice_reference_url: tenantData.voice_reference_url || null
90
+ })
 
 
 
 
 
 
 
 
 
91
  }
92
+ }, [tenantData])
 
93
 
94
  const playDemoVoice = async (voiceId: string, text: string) => {
95
  // Stop current playback
 
146
  await api.patch('/api/v1/tenants/me', settings, {
147
  headers: { Authorization: `Bearer ${token}` }
148
  })
149
+ queryClient.invalidateQueries({ queryKey: ['voice-settings'] })
150
  toast.success('Настройки голоса сохранены!')
151
  } catch (error) {
152
  toast.error('Ошибка сохранения настроек')