Spaces:
Running

axeronis commited on
Commit
d02194a
·
1 Parent(s): 40bb82e

fix: avatar persistence, password toggle, delete account, forgot password link

Browse files
backend/app/api/auth.py CHANGED
@@ -794,3 +794,66 @@ async def change_password(
794
  await session.commit()
795
 
796
  return {"message": "Password updated successfully"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
794
  await session.commit()
795
 
796
  return {"message": "Password updated successfully"}
797
+
798
+
799
+ @router.delete("/me")
800
+ async def delete_account(
801
+ current_user: User = Depends(get_current_user),
802
+ session: AsyncSession = Depends(get_async_session)
803
+ ):
804
+ """
805
+ Delete current user's account and all associated data.
806
+ This is a destructive action.
807
+ """
808
+ # Get user from current session
809
+ result = await session.execute(
810
+ select(User).where(User.id == current_user.id)
811
+ )
812
+ user = result.scalar_one_or_none()
813
+
814
+ if not user:
815
+ raise HTTPException(
816
+ status_code=status.HTTP_404_NOT_FOUND,
817
+ detail="User not found"
818
+ )
819
+
820
+ tenant_id = user.tenant_id
821
+
822
+ # Check if user is the only owner - if so, we can delete the tenant too
823
+ result = await session.execute(
824
+ select(User).where(
825
+ User.tenant_id == tenant_id,
826
+ User.role == UserRole.OWNER,
827
+ User.id != user.id
828
+ )
829
+ )
830
+ other_owners = result.scalars().all()
831
+
832
+ try:
833
+ # Delete the user
834
+ await session.delete(user)
835
+
836
+ # If no other owners, delete the entire tenant
837
+ if len(other_owners) == 0:
838
+ result = await session.execute(
839
+ select(Tenant).where(Tenant.id == tenant_id)
840
+ )
841
+ tenant = result.scalar_one_or_none()
842
+ if tenant:
843
+ # Soft delete - mark as inactive
844
+ tenant.is_active = False
845
+ session.add(tenant)
846
+
847
+ await session.commit()
848
+
849
+ logger.info(f"Account deleted: user_id={current_user.id}, tenant_id={tenant_id}")
850
+
851
+ return {"message": "Account deleted successfully"}
852
+
853
+ except Exception as e:
854
+ await session.rollback()
855
+ logger.error(f"Failed to delete account: {e}")
856
+ raise HTTPException(
857
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
858
+ detail="Failed to delete account"
859
+ )
frontend/app/login/page.tsx CHANGED
@@ -98,7 +98,7 @@ export default function LoginPage() {
98
  <div>
99
  <div className="flex items-center justify-between mb-1.5 ml-1">
100
  <label className="block text-xs font-medium text-slate-400">{t('auth.password')}</label>
101
- <Link href="#" className="text-xs text-indigo-400 hover:text-indigo-300 transition-colors">
102
  {t('auth.forgotPassword')}
103
  </Link>
104
  </div>
 
98
  <div>
99
  <div className="flex items-center justify-between mb-1.5 ml-1">
100
  <label className="block text-xs font-medium text-slate-400">{t('auth.password')}</label>
101
+ <Link href="/forgot-password" className="text-xs text-indigo-400 hover:text-indigo-300 transition-colors">
102
  {t('auth.forgotPassword')}
103
  </Link>
104
  </div>
frontend/app/settings/account/page.tsx CHANGED
@@ -2,14 +2,15 @@
2
 
3
  import { useState, useEffect, useRef } from 'react'
4
  import { useQuery, useQueryClient } from '@tanstack/react-query'
5
- import { motion } from 'framer-motion'
6
- import { User, Building2, Camera, Save, Loader2, Mail, Lock, Globe, Clock, Trash2, Phone, Shield, MapPin, ChevronDown } from 'lucide-react'
7
  import { useAuth } from '@/contexts/AuthContext'
8
  import { useToast } from '@/contexts/ToastContext'
9
  import { api, tenantsApi, uploadApi } from '@/lib/api'
10
  import { cn } from '@/lib/utils'
 
11
 
12
- // Popular timezones for CIS region
13
  const TIMEZONES = [
14
  { value: 'Asia/Bishkek', label: 'Бишкек', offset: 'UTC+6' },
15
  { value: 'Asia/Almaty', label: 'Алматы', offset: 'UTC+6' },
@@ -35,7 +36,7 @@ const REGIONS = [
35
  { value: 'by', label: 'Беларусь', flag: '🇧🇾' },
36
  ]
37
 
38
- // Card component for consistent styling
39
  function SettingsCard({ children, className }: { children: React.ReactNode; className?: string }) {
40
  return (
41
  <motion.div
@@ -56,29 +57,48 @@ function FormInput({
56
  label,
57
  icon: Icon,
58
  disabled,
 
 
59
  ...props
60
  }: {
61
  label: string
62
  icon?: React.ElementType
63
  disabled?: boolean
 
64
  } & React.InputHTMLAttributes<HTMLInputElement>) {
 
 
 
65
  return (
66
  <div className="space-y-2">
67
  <label className="text-xs font-semibold uppercase tracking-wider text-slate-500 flex items-center gap-2">
68
  {Icon && <Icon className="w-3.5 h-3.5" />}
69
  {label}
70
  </label>
71
- <input
72
- {...props}
73
- disabled={disabled}
74
- className={cn(
75
- "w-full px-4 py-3.5 bg-white/[0.03] border border-white/[0.08] rounded-xl",
76
- "text-white placeholder:text-slate-600 font-medium",
77
- "focus:outline-none focus:border-indigo-500/50 focus:bg-white/[0.05]",
78
- "transition-all duration-200",
79
- disabled && "opacity-50 cursor-not-allowed"
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  )}
81
- />
82
  </div>
83
  )
84
  }
@@ -126,17 +146,104 @@ function FormSelect({
126
  )
127
  }
128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  export default function AccountSettingsPage() {
130
- const { user, setUser } = useAuth()
131
  const toast = useToast()
132
  const queryClient = useQueryClient()
133
  const fileInputRef = useRef<HTMLInputElement>(null)
 
134
 
135
  // Loading states
136
  const [savingProfile, setSavingProfile] = useState(false)
137
  const [savingTimezone, setSavingTimezone] = useState(false)
138
  const [changingPassword, setChangingPassword] = useState(false)
139
  const [uploadingAvatar, setUploadingAvatar] = useState(false)
 
 
140
 
141
  // Form data
142
  const [formData, setFormData] = useState({
@@ -159,8 +266,18 @@ export default function AccountSettingsPage() {
159
  confirm_password: ''
160
  })
161
 
162
- // React Query for tenant data
163
- const { data: tenantData, isLoading } = useQuery({
 
 
 
 
 
 
 
 
 
 
164
  queryKey: ['tenant-profile', user?.tenant_id],
165
  queryFn: async () => {
166
  const res = await api.get('/api/v1/tenants/me')
@@ -169,33 +286,38 @@ export default function AccountSettingsPage() {
169
  enabled: !!user,
170
  })
171
 
172
- // Sync form data with query data
173
  useEffect(() => {
174
- if (tenantData && user) {
175
  setTenantId(tenantData.id)
176
  setFormData({
177
- full_name: user.full_name || '',
178
- email: user.email || '',
179
- phone: user.phone || '',
180
  company_name: tenantData.company_name || tenantData.business_name || '',
181
- avatar_url: user.avatar_url || ''
182
  })
183
  if (tenantData.timezone) setTimezone(tenantData.timezone)
184
  if (tenantData.region) setRegion(tenantData.region)
185
  }
186
- }, [tenantData, user])
187
 
188
  // Save profile
189
  const handleSaveProfile = async () => {
190
  setSavingProfile(true)
191
  try {
192
  await api.patch('/api/v1/tenants/me', { company_name: formData.company_name })
193
- await api.patch('/api/v1/auth/me', { full_name: formData.full_name, avatar_url: formData.avatar_url, phone: formData.phone })
 
 
 
 
194
 
 
195
  if (setUser && user) {
196
  setUser({ ...user, full_name: formData.full_name, avatar_url: formData.avatar_url, phone: formData.phone })
197
  }
198
-
199
  queryClient.invalidateQueries({ queryKey: ['tenant-profile'] })
200
  toast.success('Сохранено', 'Профиль успешно обновлён')
201
  } catch {
@@ -219,6 +341,7 @@ export default function AccountSettingsPage() {
219
  setFormData(prev => ({ ...prev, avatar_url: res.url }))
220
  await api.patch('/api/v1/auth/me', { avatar_url: res.url })
221
  if (setUser && user) setUser({ ...user, avatar_url: res.url })
 
222
  toast.success('Готово', 'Аватар обновлён')
223
  }
224
  } catch {
@@ -268,9 +391,27 @@ export default function AccountSettingsPage() {
268
  }
269
  }
270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271
  if (isLoading) {
272
  return (
273
- <div className="flex items-center justify-center min-h-screen bg-[#0D0E18]">
274
  <Loader2 className="w-10 h-10 animate-spin text-indigo-500" />
275
  </div>
276
  )
@@ -278,7 +419,7 @@ export default function AccountSettingsPage() {
278
 
279
  return (
280
  <div className="min-h-screen bg-[#0a0a12] text-slate-300">
281
- {/* Background gradient */}
282
  <div className="fixed inset-0 pointer-events-none">
283
  <div className="absolute top-0 left-1/2 -translate-x-1/2 w-[800px] h-[400px] bg-indigo-500/5 rounded-full blur-[120px]" />
284
  </div>
@@ -286,23 +427,14 @@ export default function AccountSettingsPage() {
286
  {/* Content */}
287
  <div className="relative z-10 max-w-2xl mx-auto px-4 sm:px-6 py-6 sm:py-10 lg:py-16 pb-24">
288
  {/* Header */}
289
- <motion.div
290
- initial={{ opacity: 0, y: -20 }}
291
- animate={{ opacity: 1, y: 0 }}
292
- className="mb-8 sm:mb-12"
293
- >
294
- <h1 className="text-2xl sm:text-3xl lg:text-4xl font-bold text-white tracking-tight">
295
- Настройки аккаунта
296
- </h1>
297
- <p className="text-slate-500 text-sm sm:text-base mt-2">
298
- Управляйте профилем и безопасностью
299
- </p>
300
  </motion.div>
301
 
302
  <div className="space-y-4 sm:space-y-6">
303
  {/* Profile Card */}
304
  <SettingsCard>
305
- {/* Avatar Section */}
306
  <div className="flex flex-col sm:flex-row items-center gap-4 sm:gap-6 mb-6 sm:mb-8">
307
  <div className="relative group">
308
  <div
@@ -316,98 +448,40 @@ export default function AccountSettingsPage() {
316
  )}
317
  >
318
  {formData.avatar_url ? (
319
- <img
320
- src={formData.avatar_url}
321
- alt="Avatar"
322
- className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110"
323
- />
324
  ) : (
325
  <span className="text-2xl sm:text-3xl font-bold text-white">
326
  {formData.full_name?.charAt(0)?.toUpperCase() || 'U'}
327
  </span>
328
  )}
329
-
330
- {/* Hover overlay */}
331
  <div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center rounded-2xl">
332
- {uploadingAvatar ? (
333
- <Loader2 className="w-6 h-6 animate-spin text-white" />
334
- ) : (
335
- <Camera className="w-6 h-6 text-white" />
336
- )}
337
  </div>
338
  </div>
339
- <input
340
- type="file"
341
- className="hidden"
342
- ref={fileInputRef}
343
- onChange={handleFileChange}
344
- accept="image/*"
345
- />
346
  </div>
347
-
348
  <div className="text-center sm:text-left">
349
- <h2 className="text-lg sm:text-xl font-bold text-white">
350
- {formData.full_name || 'Ваш профиль'}
351
- </h2>
352
  <p className="text-indigo-400 text-sm mt-0.5">{formData.email}</p>
353
  <p className="text-slate-500 text-xs mt-1">Нажмите на аватар для изменения</p>
354
  </div>
355
  </div>
356
 
357
- {/* Form Fields */}
358
  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-5">
359
- <FormInput
360
- label="Полное имя"
361
- icon={User}
362
- type="text"
363
- value={formData.full_name}
364
- onChange={(e) => setFormData({ ...formData, full_name: e.target.value })}
365
- placeholder="Алексей Иванов"
366
- />
367
- <FormInput
368
- label="Компания"
369
- icon={Building2}
370
- type="text"
371
- value={formData.company_name}
372
- onChange={(e) => setFormData({ ...formData, company_name: e.target.value })}
373
- placeholder="ООО Ромашка"
374
- />
375
- <FormInput
376
- label="Email"
377
- icon={Mail}
378
- type="email"
379
- value={formData.email}
380
- disabled
381
- />
382
- <FormInput
383
- label="Телефон"
384
- icon={Phone}
385
- type="tel"
386
- value={formData.phone}
387
- onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
388
- placeholder="+7 999 123 45 67"
389
- />
390
  </div>
391
 
392
- {/* Save Button */}
393
  <div className="mt-6 sm:mt-8">
394
- <button
395
- onClick={handleSaveProfile}
396
- disabled={savingProfile}
397
- className={cn(
398
- "w-full sm:w-auto px-8 py-3.5 rounded-xl font-semibold",
399
- "bg-white text-black",
400
- "hover:bg-slate-100 active:scale-[0.98]",
401
- "transition-all duration-200",
402
- "flex items-center justify-center gap-2.5",
403
- "disabled:opacity-50 disabled:cursor-not-allowed"
404
- )}
405
- >
406
- {savingProfile ? (
407
- <Loader2 className="w-4 h-4 animate-spin" />
408
- ) : (
409
- <Save className="w-4 h-4" />
410
- )}
411
  Сохранить изменения
412
  </button>
413
  </div>
@@ -416,45 +490,23 @@ export default function AccountSettingsPage() {
416
  {/* Regional Settings */}
417
  <SettingsCard>
418
  <div className="flex items-start gap-4 mb-6">
419
- <div className="p-2.5 bg-indigo-500/10 rounded-xl">
420
- <Globe className="w-5 h-5 text-indigo-400" />
421
- </div>
422
  <div>
423
  <h3 className="text-lg font-semibold text-white">Региональные настройки</h3>
424
  <p className="text-slate-500 text-sm mt-0.5">Часовой пояс и формат даты</p>
425
  </div>
426
  </div>
427
-
428
  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-5">
429
- <FormSelect
430
- label="Часовой пояс"
431
- icon={Clock}
432
- options={TIMEZONES}
433
- value={timezone}
434
- onChange={setTimezone}
435
- />
436
- <FormSelect
437
- label="Страна"
438
- icon={MapPin}
439
- options={REGIONS}
440
- value={region}
441
- onChange={setRegion}
442
- />
443
  </div>
444
-
445
  <div className="mt-6">
446
- <button
447
- onClick={handleSaveTimezone}
448
- disabled={savingTimezone}
449
- className={cn(
450
- "px-6 py-2.5 rounded-xl font-medium text-sm",
451
- "bg-white/[0.05] border border-white/[0.08] text-white",
452
- "hover:bg-white/[0.08] active:scale-[0.98]",
453
- "transition-all duration-200",
454
- "flex items-center gap-2",
455
- "disabled:opacity-50"
456
- )}
457
- >
458
  {savingTimezone ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
459
  Сохранить
460
  </button>
@@ -464,55 +516,26 @@ export default function AccountSettingsPage() {
464
  {/* Security */}
465
  <SettingsCard>
466
  <div className="flex items-start gap-4 mb-6">
467
- <div className="p-2.5 bg-amber-500/10 rounded-xl">
468
- <Shield className="w-5 h-5 text-amber-400" />
469
- </div>
470
  <div>
471
  <h3 className="text-lg font-semibold text-white">Безопасность</h3>
472
  <p className="text-slate-500 text-sm mt-0.5">Смена пароля для защиты аккаунта</p>
473
  </div>
474
  </div>
475
-
476
  <div className="space-y-4">
477
- <FormInput
478
- label="Текущий пароль"
479
- icon={Lock}
480
- type="password"
481
- value={passwordData.current_password}
482
- onChange={(e) => setPasswordData({ ...passwordData, current_password: e.target.value })}
483
- placeholder="••••••••"
484
- />
485
  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
486
- <FormInput
487
- label="Новый пароль"
488
- type="password"
489
- value={passwordData.new_password}
490
- onChange={(e) => setPasswordData({ ...passwordData, new_password: e.target.value })}
491
- placeholder="Минимум 8 символов"
492
- />
493
- <FormInput
494
- label="Подтверждение"
495
- type="password"
496
- value={passwordData.confirm_password}
497
- onChange={(e) => setPasswordData({ ...passwordData, confirm_password: e.target.value })}
498
- placeholder="Повторите пароль"
499
- />
500
  </div>
501
  </div>
502
-
503
  <div className="mt-6">
504
- <button
505
- onClick={handleChangePassword}
506
- disabled={changingPassword || !passwordData.current_password || !passwordData.new_password}
507
- className={cn(
508
- "px-6 py-2.5 rounded-xl font-medium text-sm",
509
- "bg-white/[0.05] border border-white/[0.08] text-white",
510
- "hover:bg-white/[0.08] active:scale-[0.98]",
511
- "transition-all duration-200",
512
- "flex items-center gap-2",
513
- "disabled:opacity-30 disabled:cursor-not-allowed"
514
- )}
515
- >
516
  {changingPassword ? <Loader2 className="w-4 h-4 animate-spin" /> : <Lock className="w-4 h-4" />}
517
  Сменить пароль
518
  </button>
@@ -523,26 +546,34 @@ export default function AccountSettingsPage() {
523
  <SettingsCard className="border-red-500/20 bg-red-500/[0.02]">
524
  <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
525
  <div className="flex items-start gap-4">
526
- <div className="p-2.5 bg-red-500/10 rounded-xl">
527
- <Trash2 className="w-5 h-5 text-red-500" />
528
- </div>
529
  <div>
530
  <h3 className="text-base font-semibold text-red-400">Удаление аккаунта</h3>
531
  <p className="text-red-500/50 text-sm mt-0.5">Все данные будут удалены безвозвратно</p>
532
  </div>
533
  </div>
534
- <button className={cn(
535
- "w-full sm:w-auto px-5 py-2.5 rounded-xl font-medium text-sm",
536
- "border border-red-500/30 text-red-400",
537
- "hover:bg-red-500 hover:text-white hover:border-transparent",
538
- "transition-all duration-200"
539
- )}>
 
 
540
  Удалить аккаунт
541
  </button>
542
  </div>
543
  </SettingsCard>
544
  </div>
545
  </div>
 
 
 
 
 
 
 
 
546
  </div>
547
  )
548
  }
 
2
 
3
  import { useState, useEffect, useRef } from 'react'
4
  import { useQuery, useQueryClient } from '@tanstack/react-query'
5
+ import { motion, AnimatePresence } from 'framer-motion'
6
+ import { User, Building2, Camera, Save, Loader2, Mail, Lock, Globe, Clock, Trash2, Phone, Shield, MapPin, ChevronDown, Eye, EyeOff, AlertTriangle, X } from 'lucide-react'
7
  import { useAuth } from '@/contexts/AuthContext'
8
  import { useToast } from '@/contexts/ToastContext'
9
  import { api, tenantsApi, uploadApi } from '@/lib/api'
10
  import { cn } from '@/lib/utils'
11
+ import { useRouter } from 'next/navigation'
12
 
13
+ // Timezones
14
  const TIMEZONES = [
15
  { value: 'Asia/Bishkek', label: 'Бишкек', offset: 'UTC+6' },
16
  { value: 'Asia/Almaty', label: 'Алматы', offset: 'UTC+6' },
 
36
  { value: 'by', label: 'Беларусь', flag: '🇧🇾' },
37
  ]
38
 
39
+ // Card component
40
  function SettingsCard({ children, className }: { children: React.ReactNode; className?: string }) {
41
  return (
42
  <motion.div
 
57
  label,
58
  icon: Icon,
59
  disabled,
60
+ type = 'text',
61
+ showToggle,
62
  ...props
63
  }: {
64
  label: string
65
  icon?: React.ElementType
66
  disabled?: boolean
67
+ showToggle?: boolean
68
  } & React.InputHTMLAttributes<HTMLInputElement>) {
69
+ const [showPassword, setShowPassword] = useState(false)
70
+ const isPassword = type === 'password'
71
+
72
  return (
73
  <div className="space-y-2">
74
  <label className="text-xs font-semibold uppercase tracking-wider text-slate-500 flex items-center gap-2">
75
  {Icon && <Icon className="w-3.5 h-3.5" />}
76
  {label}
77
  </label>
78
+ <div className="relative">
79
+ <input
80
+ {...props}
81
+ type={isPassword && showPassword ? 'text' : type}
82
+ disabled={disabled}
83
+ className={cn(
84
+ "w-full px-4 py-3.5 bg-white/[0.03] border border-white/[0.08] rounded-xl",
85
+ "text-white placeholder:text-slate-600 font-medium",
86
+ "focus:outline-none focus:border-indigo-500/50 focus:bg-white/[0.05]",
87
+ "transition-all duration-200",
88
+ isPassword && "pr-12",
89
+ disabled && "opacity-50 cursor-not-allowed"
90
+ )}
91
+ />
92
+ {isPassword && (
93
+ <button
94
+ type="button"
95
+ onClick={() => setShowPassword(!showPassword)}
96
+ className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-500 hover:text-slate-300 transition-colors"
97
+ >
98
+ {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
99
+ </button>
100
  )}
101
+ </div>
102
  </div>
103
  )
104
  }
 
146
  )
147
  }
148
 
149
+ // Delete Account Modal
150
+ function DeleteAccountModal({ isOpen, onClose, onConfirm, loading }: {
151
+ isOpen: boolean
152
+ onClose: () => void
153
+ onConfirm: () => void
154
+ loading: boolean
155
+ }) {
156
+ const [confirmText, setConfirmText] = useState('')
157
+
158
+ if (!isOpen) return null
159
+
160
+ return (
161
+ <AnimatePresence>
162
+ <motion.div
163
+ initial={{ opacity: 0 }}
164
+ animate={{ opacity: 1 }}
165
+ exit={{ opacity: 0 }}
166
+ className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm"
167
+ onClick={onClose}
168
+ >
169
+ <motion.div
170
+ initial={{ scale: 0.95, opacity: 0 }}
171
+ animate={{ scale: 1, opacity: 1 }}
172
+ exit={{ scale: 0.95, opacity: 0 }}
173
+ className="w-full max-w-md bg-[#12131a] border border-red-500/20 rounded-2xl p-6 shadow-2xl"
174
+ onClick={(e) => e.stopPropagation()}
175
+ >
176
+ <div className="flex items-center gap-4 mb-4">
177
+ <div className="p-3 bg-red-500/10 rounded-xl">
178
+ <AlertTriangle className="w-6 h-6 text-red-500" />
179
+ </div>
180
+ <div>
181
+ <h3 className="text-lg font-bold text-white">Удаление аккаунта</h3>
182
+ <p className="text-red-400/70 text-sm">Это действие необратимо</p>
183
+ </div>
184
+ <button onClick={onClose} className="ml-auto p-2 hover:bg-white/5 rounded-lg transition-colors">
185
+ <X className="w-5 h-5 text-slate-500" />
186
+ </button>
187
+ </div>
188
+
189
+ <p className="text-slate-400 text-sm mb-4">
190
+ Все данные вашего аккаунта, включая настройки AI, каталог, диалоги и подписку будут удалены безвозвратно.
191
+ </p>
192
+
193
+ <div className="mb-4">
194
+ <label className="text-xs font-semibold text-slate-500 mb-2 block">
195
+ Введите "УДАЛИТЬ" для подтверждения
196
+ </label>
197
+ <input
198
+ type="text"
199
+ value={confirmText}
200
+ onChange={(e) => setConfirmText(e.target.value)}
201
+ placeholder="УДАЛИТЬ"
202
+ className="w-full px-4 py-3 bg-white/[0.03] border border-red-500/30 rounded-xl text-white placeholder:text-slate-600 focus:outline-none focus:border-red-500"
203
+ />
204
+ </div>
205
+
206
+ <div className="flex gap-3">
207
+ <button
208
+ onClick={onClose}
209
+ className="flex-1 px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white font-medium hover:bg-white/10 transition-colors"
210
+ >
211
+ Отмена
212
+ </button>
213
+ <button
214
+ onClick={onConfirm}
215
+ disabled={confirmText !== 'УДАЛИТЬ' || loading}
216
+ className={cn(
217
+ "flex-1 px-4 py-3 rounded-xl font-medium flex items-center justify-center gap-2",
218
+ "bg-red-500 text-white",
219
+ "disabled:opacity-40 disabled:cursor-not-allowed",
220
+ "hover:bg-red-600 transition-colors"
221
+ )}
222
+ >
223
+ {loading && <Loader2 className="w-4 h-4 animate-spin" />}
224
+ Удалить
225
+ </button>
226
+ </div>
227
+ </motion.div>
228
+ </motion.div>
229
+ </AnimatePresence>
230
+ )
231
+ }
232
+
233
  export default function AccountSettingsPage() {
234
+ const { user, setUser, logout } = useAuth()
235
  const toast = useToast()
236
  const queryClient = useQueryClient()
237
  const fileInputRef = useRef<HTMLInputElement>(null)
238
+ const router = useRouter()
239
 
240
  // Loading states
241
  const [savingProfile, setSavingProfile] = useState(false)
242
  const [savingTimezone, setSavingTimezone] = useState(false)
243
  const [changingPassword, setChangingPassword] = useState(false)
244
  const [uploadingAvatar, setUploadingAvatar] = useState(false)
245
+ const [deletingAccount, setDeletingAccount] = useState(false)
246
+ const [showDeleteModal, setShowDeleteModal] = useState(false)
247
 
248
  // Form data
249
  const [formData, setFormData] = useState({
 
266
  confirm_password: ''
267
  })
268
 
269
+ // Fetch FRESH user data from API (not just context)
270
+ const { data: userData, isLoading: userLoading } = useQuery({
271
+ queryKey: ['user-profile'],
272
+ queryFn: async () => {
273
+ const res = await api.get('/api/v1/auth/me')
274
+ return res.data
275
+ },
276
+ enabled: !!user,
277
+ })
278
+
279
+ // Fetch tenant data
280
+ const { data: tenantData, isLoading: tenantLoading } = useQuery({
281
  queryKey: ['tenant-profile', user?.tenant_id],
282
  queryFn: async () => {
283
  const res = await api.get('/api/v1/tenants/me')
 
286
  enabled: !!user,
287
  })
288
 
289
+ // Sync form data with API data (not context)
290
  useEffect(() => {
291
+ if (userData && tenantData) {
292
  setTenantId(tenantData.id)
293
  setFormData({
294
+ full_name: userData.full_name || '',
295
+ email: userData.email || '',
296
+ phone: userData.phone || '',
297
  company_name: tenantData.company_name || tenantData.business_name || '',
298
+ avatar_url: userData.avatar_url || ''
299
  })
300
  if (tenantData.timezone) setTimezone(tenantData.timezone)
301
  if (tenantData.region) setRegion(tenantData.region)
302
  }
303
+ }, [userData, tenantData])
304
 
305
  // Save profile
306
  const handleSaveProfile = async () => {
307
  setSavingProfile(true)
308
  try {
309
  await api.patch('/api/v1/tenants/me', { company_name: formData.company_name })
310
+ await api.patch('/api/v1/auth/me', {
311
+ full_name: formData.full_name,
312
+ avatar_url: formData.avatar_url,
313
+ phone: formData.phone
314
+ })
315
 
316
+ // Update context and refetch
317
  if (setUser && user) {
318
  setUser({ ...user, full_name: formData.full_name, avatar_url: formData.avatar_url, phone: formData.phone })
319
  }
320
+ queryClient.invalidateQueries({ queryKey: ['user-profile'] })
321
  queryClient.invalidateQueries({ queryKey: ['tenant-profile'] })
322
  toast.success('Сохранено', 'Профиль успешно обновлён')
323
  } catch {
 
341
  setFormData(prev => ({ ...prev, avatar_url: res.url }))
342
  await api.patch('/api/v1/auth/me', { avatar_url: res.url })
343
  if (setUser && user) setUser({ ...user, avatar_url: res.url })
344
+ queryClient.invalidateQueries({ queryKey: ['user-profile'] })
345
  toast.success('Готово', 'Аватар обновлён')
346
  }
347
  } catch {
 
391
  }
392
  }
393
 
394
+ // Delete account
395
+ const handleDeleteAccount = async () => {
396
+ setDeletingAccount(true)
397
+ try {
398
+ await api.delete('/api/v1/auth/me')
399
+ toast.success('Аккаунт удалён', 'Ваши данные были удалены')
400
+ logout()
401
+ router.push('/login')
402
+ } catch (e: any) {
403
+ toast.error('Ошибка', e.response?.data?.detail || 'Не удалось удалить аккаунт')
404
+ } finally {
405
+ setDeletingAccount(false)
406
+ setShowDeleteModal(false)
407
+ }
408
+ }
409
+
410
+ const isLoading = userLoading || tenantLoading
411
+
412
  if (isLoading) {
413
  return (
414
+ <div className="flex items-center justify-center min-h-screen bg-[#0a0a12]">
415
  <Loader2 className="w-10 h-10 animate-spin text-indigo-500" />
416
  </div>
417
  )
 
419
 
420
  return (
421
  <div className="min-h-screen bg-[#0a0a12] text-slate-300">
422
+ {/* Background */}
423
  <div className="fixed inset-0 pointer-events-none">
424
  <div className="absolute top-0 left-1/2 -translate-x-1/2 w-[800px] h-[400px] bg-indigo-500/5 rounded-full blur-[120px]" />
425
  </div>
 
427
  {/* Content */}
428
  <div className="relative z-10 max-w-2xl mx-auto px-4 sm:px-6 py-6 sm:py-10 lg:py-16 pb-24">
429
  {/* Header */}
430
+ <motion.div initial={{ opacity: 0, y: -20 }} animate={{ opacity: 1, y: 0 }} className="mb-8 sm:mb-12">
431
+ <h1 className="text-2xl sm:text-3xl lg:text-4xl font-bold text-white tracking-tight">Настройки аккаунта</h1>
432
+ <p className="text-slate-500 text-sm sm:text-base mt-2">Управляйте профилем и безопасностью</p>
 
 
 
 
 
 
 
 
433
  </motion.div>
434
 
435
  <div className="space-y-4 sm:space-y-6">
436
  {/* Profile Card */}
437
  <SettingsCard>
 
438
  <div className="flex flex-col sm:flex-row items-center gap-4 sm:gap-6 mb-6 sm:mb-8">
439
  <div className="relative group">
440
  <div
 
448
  )}
449
  >
450
  {formData.avatar_url ? (
451
+ <img src={formData.avatar_url} alt="Avatar" className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110" />
 
 
 
 
452
  ) : (
453
  <span className="text-2xl sm:text-3xl font-bold text-white">
454
  {formData.full_name?.charAt(0)?.toUpperCase() || 'U'}
455
  </span>
456
  )}
 
 
457
  <div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center rounded-2xl">
458
+ {uploadingAvatar ? <Loader2 className="w-6 h-6 animate-spin text-white" /> : <Camera className="w-6 h-6 text-white" />}
 
 
 
 
459
  </div>
460
  </div>
461
+ <input type="file" className="hidden" ref={fileInputRef} onChange={handleFileChange} accept="image/*" />
 
 
 
 
 
 
462
  </div>
 
463
  <div className="text-center sm:text-left">
464
+ <h2 className="text-lg sm:text-xl font-bold text-white">{formData.full_name || 'Ваш профиль'}</h2>
 
 
465
  <p className="text-indigo-400 text-sm mt-0.5">{formData.email}</p>
466
  <p className="text-slate-500 text-xs mt-1">Нажмите на аватар для изменения</p>
467
  </div>
468
  </div>
469
 
 
470
  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-5">
471
+ <FormInput label="Полное имя" icon={User} value={formData.full_name} onChange={(e) => setFormData({ ...formData, full_name: e.target.value })} placeholder="Алексей Иванов" />
472
+ <FormInput label="Компания" icon={Building2} value={formData.company_name} onChange={(e) => setFormData({ ...formData, company_name: e.target.value })} placeholder="ООО Ромашка" />
473
+ <FormInput label="Email" icon={Mail} type="email" value={formData.email} disabled />
474
+ <FormInput label="Телефон" icon={Phone} type="tel" value={formData.phone} onChange={(e) => setFormData({ ...formData, phone: e.target.value })} placeholder="+7 999 123 45 67" />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
475
  </div>
476
 
 
477
  <div className="mt-6 sm:mt-8">
478
+ <button onClick={handleSaveProfile} disabled={savingProfile} className={cn(
479
+ "w-full sm:w-auto px-8 py-3.5 rounded-xl font-semibold",
480
+ "bg-white text-black hover:bg-slate-100 active:scale-[0.98]",
481
+ "transition-all duration-200 flex items-center justify-center gap-2.5",
482
+ "disabled:opacity-50 disabled:cursor-not-allowed"
483
+ )}>
484
+ {savingProfile ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
 
 
 
 
 
 
 
 
 
 
485
  Сохранить изменения
486
  </button>
487
  </div>
 
490
  {/* Regional Settings */}
491
  <SettingsCard>
492
  <div className="flex items-start gap-4 mb-6">
493
+ <div className="p-2.5 bg-indigo-500/10 rounded-xl"><Globe className="w-5 h-5 text-indigo-400" /></div>
 
 
494
  <div>
495
  <h3 className="text-lg font-semibold text-white">Региональные настройки</h3>
496
  <p className="text-slate-500 text-sm mt-0.5">Часовой пояс и формат даты</p>
497
  </div>
498
  </div>
 
499
  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-5">
500
+ <FormSelect label="Часовой пояс" icon={Clock} options={TIMEZONES} value={timezone} onChange={setTimezone} />
501
+ <FormSelect label="Страна" icon={MapPin} options={REGIONS} value={region} onChange={setRegion} />
 
 
 
 
 
 
 
 
 
 
 
 
502
  </div>
 
503
  <div className="mt-6">
504
+ <button onClick={handleSaveTimezone} disabled={savingTimezone} className={cn(
505
+ "px-6 py-2.5 rounded-xl font-medium text-sm",
506
+ "bg-white/[0.05] border border-white/[0.08] text-white",
507
+ "hover:bg-white/[0.08] active:scale-[0.98] transition-all duration-200",
508
+ "flex items-center gap-2 disabled:opacity-50"
509
+ )}>
 
 
 
 
 
 
510
  {savingTimezone ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
511
  Сохранить
512
  </button>
 
516
  {/* Security */}
517
  <SettingsCard>
518
  <div className="flex items-start gap-4 mb-6">
519
+ <div className="p-2.5 bg-amber-500/10 rounded-xl"><Shield className="w-5 h-5 text-amber-400" /></div>
 
 
520
  <div>
521
  <h3 className="text-lg font-semibold text-white">Безопасность</h3>
522
  <p className="text-slate-500 text-sm mt-0.5">Смена пароля для защиты аккаунта</p>
523
  </div>
524
  </div>
 
525
  <div className="space-y-4">
526
+ <FormInput label="Текущий пароль" icon={Lock} type="password" value={passwordData.current_password} onChange={(e) => setPasswordData({ ...passwordData, current_password: e.target.value })} placeholder="••••••••" />
 
 
 
 
 
 
 
527
  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
528
+ <FormInput label="Новый пароль" type="password" value={passwordData.new_password} onChange={(e) => setPasswordData({ ...passwordData, new_password: e.target.value })} placeholder="Минимум 8 символов" />
529
+ <FormInput label="Подтверждение" type="password" value={passwordData.confirm_password} onChange={(e) => setPasswordData({ ...passwordData, confirm_password: e.target.value })} placeholder="Повторите пароль" />
 
 
 
 
 
 
 
 
 
 
 
 
530
  </div>
531
  </div>
 
532
  <div className="mt-6">
533
+ <button onClick={handleChangePassword} disabled={changingPassword || !passwordData.current_password || !passwordData.new_password} className={cn(
534
+ "px-6 py-2.5 rounded-xl font-medium text-sm",
535
+ "bg-white/[0.05] border border-white/[0.08] text-white",
536
+ "hover:bg-white/[0.08] active:scale-[0.98] transition-all duration-200",
537
+ "flex items-center gap-2 disabled:opacity-30 disabled:cursor-not-allowed"
538
+ )}>
 
 
 
 
 
 
539
  {changingPassword ? <Loader2 className="w-4 h-4 animate-spin" /> : <Lock className="w-4 h-4" />}
540
  Сменить пароль
541
  </button>
 
546
  <SettingsCard className="border-red-500/20 bg-red-500/[0.02]">
547
  <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
548
  <div className="flex items-start gap-4">
549
+ <div className="p-2.5 bg-red-500/10 rounded-xl"><Trash2 className="w-5 h-5 text-red-500" /></div>
 
 
550
  <div>
551
  <h3 className="text-base font-semibold text-red-400">Удаление аккаунта</h3>
552
  <p className="text-red-500/50 text-sm mt-0.5">Все данные будут удалены безвозвратно</p>
553
  </div>
554
  </div>
555
+ <button
556
+ onClick={() => setShowDeleteModal(true)}
557
+ className={cn(
558
+ "w-full sm:w-auto px-5 py-2.5 rounded-xl font-medium text-sm",
559
+ "border border-red-500/30 text-red-400",
560
+ "hover:bg-red-500 hover:text-white hover:border-transparent transition-all duration-200"
561
+ )}
562
+ >
563
  Удалить аккаунт
564
  </button>
565
  </div>
566
  </SettingsCard>
567
  </div>
568
  </div>
569
+
570
+ {/* Delete Modal */}
571
+ <DeleteAccountModal
572
+ isOpen={showDeleteModal}
573
+ onClose={() => setShowDeleteModal(false)}
574
+ onConfirm={handleDeleteAccount}
575
+ loading={deletingAccount}
576
+ />
577
  </div>
578
  )
579
  }