Spaces:
Sleeping
Sleeping
axeronis commited on
Commit ·
0ca368e
1
Parent(s): e428ab3
лучшение UX/UI чатов и исправление критического бага авторизации
Browse files- едизайн списка лидов: улучшенная типографика и статус-индикаторы
- одернизация ChatWindow: обновленные баблы сообщений, область ввода, мобильный drawer
- едизайн AI Summary (ClientCard): структурированная сетка с Lucide иконками
- справлен критический баг: замена 'access_token' на 'auth_token' в 9 файлах
- странены все ошибки 401 авторизации
Files changed (10)
- frontend/app/admin/page.tsx+7-7
- frontend/app/chats/page.tsx+90-93
- frontend/app/dashboard/page.tsx+1-1
- frontend/app/partner/page.tsx+6-6
- frontend/app/settings/brain/page_advanced.tsx+15-17
- frontend/app/settings/brain/page_old.tsx+4-4
- frontend/app/settings/partner/page.tsx+2-2
- frontend/app/settings/team/page.tsx+4-4
- frontend/components/ChatWindow.tsx+234-408
- frontend/components/ClientCard.tsx+167-645
85 unmodified lines8687888990919211 unmodified lines10410510610710810911018 unmodified lines12913013113213313413513613713823 unmodified lines16216316416516616716822 unmodified lines19119219319419519619711 unmodified lines20921021121221321421585 unmodified linesconst loadConfig = async () => {try {const res = await fetch('/api/v1/admin/landing-config', {headers: { 'Authorization': `Bearer ${localStorage.getItem('access_token')}` }})if (res.ok) {const data = await res.json()11 unmodified linesmethod: 'POST',headers: {'Content-Type': 'application/json','Authorization': `Bearer ${localStorage.getItem('access_token')}`},body: JSON.stringify(landingConfig)})18 unmodified linesconst [tenantsRes, statsRes] = await Promise.all([fetch(`/api/v1/admin/tenants?${params.toString()}`, {headers: { 'Authorization': `Bearer ${localStorage.getItem('access_token')}` }}),fetch('/api/v1/admin/stats', {headers: { 'Authorization': `Bearer ${localStorage.getItem('access_token')}` }})])23 unmodified linesmethod: 'POST',headers: {'Content-Type': 'application/json','Authorization': `Bearer ${localStorage.getItem('access_token')}`},body: JSON.stringify({plan: editPlan,22 unmodified linestry {const response = await fetch(`/api/v1/admin/tenants/${tenantId}/suspend`, {method: 'POST',headers: { 'Authorization': `Bearer ${localStorage.getItem('access_token')}` }})if (response.ok) {11 unmodified linestry {const response = await fetch(`/api/v1/admin/tenants/${tenantId}/activate`, {method: 'POST',headers: { 'Authorization': `Bearer ${localStorage.getItem('access_token')}` }})if (response.ok) {85 unmodified lines8687888990919211 unmodified lines10410510610710810911018 unmodified lines12913013113213313413513613713823 unmodified lines16216316416516616716822 unmodified lines19119219319419519619711 unmodified lines20921021121221321421585 unmodified linesconst loadConfig = async () => {try {const res = await fetch('/api/v1/admin/landing-config', {headers: { 'Authorization': `Bearer ${localStorage.getItem('auth_token')}` }})if (res.ok) {const data = await res.json()11 unmodified linesmethod: 'POST',headers: {'Content-Type': 'application/json','Authorization': `Bearer ${localStorage.getItem('auth_token')}`},body: JSON.stringify(landingConfig)})18 unmodified linesconst [tenantsRes, statsRes] = await Promise.all([fetch(`/api/v1/admin/tenants?${params.toString()}`, {headers: { 'Authorization': `Bearer ${localStorage.getItem('auth_token')}` }}),fetch('/api/v1/admin/stats', {headers: { 'Authorization': `Bearer ${localStorage.getItem('auth_token')}` }})])23 unmodified linesmethod: 'POST',headers: {'Content-Type': 'application/json','Authorization': `Bearer ${localStorage.getItem('auth_token')}`},body: JSON.stringify({plan: editPlan,22 unmodified linestry {const response = await fetch(`/api/v1/admin/tenants/${tenantId}/suspend`, {method: 'POST',headers: { 'Authorization': `Bearer ${localStorage.getItem('auth_token')}` }})if (response.ok) {11 unmodified linestry {const response = await fetch(`/api/v1/admin/tenants/${tenantId}/activate`, {method: 'POST',headers: { 'Authorization': `Bearer ${localStorage.getItem('auth_token')}` }})if (response.ok) {
34 unmodified lines353637383940414243449 unmodified lines5455565758596037 unmodified lines989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220 unmodified lines22322422522622722822923024 unmodified lines25525625725825926026126234 unmodified linesconst unsubscribe = subscribeToLeads(user.tenant_id, (updatedLead) => {console.log('🔄 Lead updated via Realtime:', updatedLead)// Refetch leads to update the list (includes new heat_score, status, etc.)refetchLeads()// CRITICAL FIX: Update selectedLead if it's the one that changedif (selectedLead && selectedLead.id === updatedLead.id) {console.log('✅ Updating selected lead state with fresh data')9 unmodified linesconst handleTakeover = async () => {if (!selectedLead || !user) returntry {await leadsApi.takeover(selectedLead.id, user.id)alert('Диалог взят в работу! ИИ больше не будет отвечать.')37 unmodified lines<h2 className="text-lg font-bold text-slate-900">Диалоги</h2><p className="text-xs text-slate-500 mt-1">{leads?.length || 0} активных лидов</p></div><div className="divide-y divide-slate-100">{leads && leads.length > 0 ? (leads.map((lead) => {const isSelected = selectedLead?.id === lead.id// Map heat_level to status dot colorconst getStatusDotColor = (heatLevel: string) => {switch (heatLevel.toUpperCase()) {case 'HOT':return 'bg-red-500'case 'WARM':return 'bg-orange-500'case 'COLD':return 'bg-blue-500'default:return 'bg-gray-400'}}const getBadgeLabel = (heatLevel: string) => {switch (heatLevel.toUpperCase()) {case 'HOT':return 'Горячий'case 'WARM':return 'Тёплый'case 'COLD':return 'Холодный'default:return heatLevel}}const getPsychotypeLabel = (psychotype: string) => {const lower = psychotype.toLowerCase()const map: Record<string, string> = {'dominant': 'Доминантный','influential': 'Влияющий','steady': 'Стабильный','conscientious': 'Аналитический','unknown': 'Не определён'}return map[lower] || psychotype}return (<divkey={lead.id}onClick={() => setSelectedLead(lead)}className={cn("p-4 cursor-pointer transition-all duration-200 hover:bg-gray-50",isSelected && "bg-blue-50 border-l-2 border-blue-600")}><div className="flex items-start gap-3 mb-2">{/* Status Indicator Dot */}<div className="mt-1.5 flex-shrink-0"><div className={cn("w-2 h-2 rounded-full", getStatusDotColor(lead.heat_level))} /></div><div className="flex-1 min-w-0"><h3 className="font-semibold text-slate-900 text-sm truncate">{lead.name || 'Без имени'}</h3></div><span className="text-xs text-slate-500 font-medium flex-shrink-0">{lead.heat_score}</span></div><div className="flex items-center gap-2 mb-2 ml-5"><span className="inline-flex items-center px-2 py-0.5 text-xs font-medium bg-purple-50 text-purple-700 rounded">{getPsychotypeLabel(lead.psychotype)}</span><span className="text-xs text-slate-400">{getBadgeLabel(lead.heat_level)}</span></div><p className="text-xs text-slate-600 line-clamp-2 ml-5">{lead.ai_summary_json?.intent || lead.ai_summary_json?.recommendation || 'Нет анализа'}</p><p className="text-xs text-slate-400 mt-2 ml-5">{new Date(lead.last_message_at).toLocaleString('ru-RU', {day: '2-digit',month: '2-digit',hour: '2-digit',minute: '2-digit'})}</p></div>)})) : (<div className="flex flex-col items-center justify-center py-12 px-6 text-center"><div className="w-16 h-16 rounded-full bg-gradient-to-br from-slate-100 to-slate-200 flex items-center justify-center mb-4"><svg className="w-8 h-8 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" /></svg></div>20 unmodified lines</div></div>) : conversation ? (<ChatWindowmessages={conversation.messages}leadId={selectedLead.id}tenantId={user.tenant_id}conversationId={conversation.id}24 unmodified lines{/* Col 3 - Intelligence Panel - Hidden on mobile, shown in drawer */}<div className="hidden md:block w-96 border-l border-slate-200 bg-white overflow-y-auto flex-shrink-0 h-screen">{selectedLead ? (<ClientCardlead={selectedLead}onTakeover={handleTakeover}isAnalyzing={selectedLead.processing_status === 'analyzing' || selectedLead.processing_status === 'generating'}onRefresh={handleRefreshLead}34 unmodified lines353637383940414243449 unmodified lines5455565758596037 unmodified lines989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920 unmodified lines22022122222322422522622724 unmodified lines25225325425525625725825934 unmodified linesconst unsubscribe = subscribeToLeads(user.tenant_id, (updatedLead) => {console.log('🔄 Lead updated via Realtime:', updatedLead)// Refetch leads to update the list (includes new heat_score, status, etc.)refetchLeads()// CRITICAL FIX: Update selectedLead if it's the one that changedif (selectedLead && selectedLead.id === updatedLead.id) {console.log('✅ Updating selected lead state with fresh data')9 unmodified linesconst handleTakeover = async () => {if (!selectedLead || !user) returntry {await leadsApi.takeover(selectedLead.id, user.id)alert('Диалог взят в работу! ИИ больше не будет отвечать.')37 unmodified lines<h2 className="text-lg font-bold text-slate-900">Диалоги</h2><p className="text-xs text-slate-500 mt-1">{leads?.length || 0} активных лидов</p></div><div className="divide-y divide-slate-100">{leads && leads.length > 0 ? (leads.map((lead) => {const isSelected = selectedLead?.id === lead.id// Map heat_level to status dot colorconst getStatusDotColor = (heatLevel: string) => {switch (heatLevel.toUpperCase()) {case 'HOT': return 'bg-red-500 shadow-[0_0_8px_rgba(239,68,68,0.4)]'case 'WARM': return 'bg-amber-500 shadow-[0_0_8px_rgba(245,158,11,0.4)]'case 'COLD': return 'bg-blue-500 shadow-[0_0_8px_rgba(59,130,246,0.4)]'default: return 'bg-slate-300'}}const getBadgeLabel = (heatLevel: string) => {switch (heatLevel.toUpperCase()) {case 'HOT': return 'Горячий'case 'WARM': return 'Тёплый'case 'COLD': return 'Холодный'default: return heatLevel}}const getPsychotypeLabel = (psychotype: string) => {const lower = psychotype.toLowerCase()const map: Record<string, string> = {'dominant': 'Доминантный','influential': 'Влияющий','steady': 'Стабильный','conscientious': 'Аналитический','unknown': 'Не определён'}return map[lower] || psychotype}return (<divkey={lead.id}onClick={() => setSelectedLead(lead)}className={cn("p-4 cursor-pointer transition-all duration-200 hover:bg-slate-50 border-l-4 border-transparent",isSelected? "bg-indigo-50/50 border-indigo-600": "hover:border-slate-200")}><div className="flex items-start justify-between mb-1"><div className="flex items-center gap-2 min-w-0"><h3 className={cn("font-semibold text-sm truncate transition-colors",isSelected ? "text-indigo-900" : "text-slate-900")}>{lead.name || 'Без имени'}</h3>{lead.heat_score > 0 && (<span className={cn("text-[10px] font-bold px-1.5 py-0.5 rounded-full",lead.heat_score >= 80 ? "bg-red-100 text-red-700" :lead.heat_score >= 50 ? "bg-amber-100 text-amber-700" :"bg-blue-100 text-blue-700")}>{lead.heat_score}</span>)}</div><span className="text-[10px] text-slate-400 font-medium whitespace-nowrap ml-2">{new Date(lead.last_message_at).toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' })}</span></div><div className="flex items-center gap-2 mb-2"><div className={cn("w-2 h-2 rounded-full", getStatusDotColor(lead.heat_level))} /><span className="text-xs text-slate-500 font-medium">{getBadgeLabel(lead.heat_level)}</span><span className="text-slate-300">•</span><span className="text-xs text-slate-400 truncate max-w-[100px]">{getPsychotypeLabel(lead.psychotype)}</span></div><p className={cn("text-xs line-clamp-2 leading-relaxed",isSelected ? "text-indigo-900/70" : "text-slate-500")}>{lead.ai_summary_json?.intent || lead.ai_summary_json?.recommendation || 'Нет анализа'}</p></div>)})) : (<div className="flex flex-col items-center justify-center py-12 px-6 text-center"><div className="w-16 h-16 rounded-full bg-slate-50 flex items-center justify-center mb-4"><svg className="w-8 h-8 text-slate-300" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" /></svg></div>20 unmodified lines</div></div>) : conversation ? (<ChatWindowmessages={conversation.messages}leadId={selectedLead.id}tenantId={user.tenant_id}conversationId={conversation.id}24 unmodified lines{/* Col 3 - Intelligence Panel - Hidden on mobile, shown in drawer */}<div className="hidden md:block w-96 border-l border-slate-200 bg-white overflow-y-auto flex-shrink-0 h-screen">{selectedLead ? (<ClientCardlead={selectedLead}onTakeover={handleTakeover}isAnalyzing={selectedLead.processing_status === 'analyzing' || selectedLead.processing_status === 'generating'}onRefresh={handleRefreshLead}
93 unmodified lines94959697989910093 unmodified linestry {setLoading(true)setError(null)const token = localStorage.getItem('access_token')const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/analytics/dashboard`, {headers: {'Authorization': `Bearer ${token}`93 unmodified lines94959697989910093 unmodified linestry {setLoading(true)setError(null)const token = localStorage.getItem('auth_token')const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/analytics/dashboard`, {headers: {'Authorization': `Bearer ${token}`
2 unmodified lines3456789101148 unmodified lines60616263646566676869141 unmodified lines2112122132142152162172 unmodified linesimport { useState, useEffect } from 'react'import { useAuth } from '@/contexts/AuthContext'import { useToast } from '@/contexts/ToastContext'import {Users,DollarSign,TrendingUp,Copy,CheckCircle,48 unmodified linestry {const [infoRes, clientsRes] = await Promise.all([fetch('/api/v1/billing/referral-link', {headers: { 'Authorization': `Bearer ${localStorage.getItem('access_token')}` }}),fetch('/api/v1/partner/clients', {headers: { 'Authorization': `Bearer ${localStorage.getItem('access_token')}` }})])141 unmodified lines<p className="text-indigo-100 mb-4">Делитесь этой ссылкой с потенциальными клиентами. Вы получите {(partnerInfo.commission_rate * 100).toFixed(0)}% комиссии от их платежей!</p><div className="flex items-center gap-3"><div className="flex-1 bg-white/10 backdrop-blur rounded-xl px-4 py-3 border-2 border-white/20"><p className="text-white font-mono text-sm break-all">{partnerInfo.referral_link}</p>2 unmodified lines3456789101148 unmodified lines60616263646566676869141 unmodified lines2112122132142152162172 unmodified linesimport { useState, useEffect } from 'react'import { useAuth } from '@/contexts/AuthContext'import { useToast } from '@/contexts/ToastContext'import {Users,DollarSign,TrendingUp,Copy,CheckCircle,48 unmodified linestry {const [infoRes, clientsRes] = await Promise.all([fetch('/api/v1/billing/referral-link', {headers: { 'Authorization': `Bearer ${localStorage.getItem('auth_token')}` }}),fetch('/api/v1/partner/clients', {headers: { 'Authorization': `Bearer ${localStorage.getItem('auth_token')}` }})])141 unmodified lines<p className="text-indigo-100 mb-4">Делитесь этой ссылкой с потенциальными клиентами. Вы получите {(partnerInfo.commission_rate * 100).toFixed(0)}% комиссии от их платежей!</p><div className="flex items-center gap-3"><div className="flex-1 bg-white/10 backdrop-blur rounded-xl px-4 py-3 border-2 border-white/20"><p className="text-white font-mono text-sm break-all">{partnerInfo.referral_link}</p>
63 unmodified lines6465666768697014 unmodified lines858687888990919293949596979816 unmodified lines1151161171181191201211221231241251261271 unmodified line12913013113213313413513 unmodified lines14915015115215315415514 unmodified lines17017117217317417517648 unmodified lines22522622722822923023123223323423524 unmodified lines26026126226326426526626726826927055 unmodified lines32632732832933033133257 unmodified lines39039139239339439539663 unmodified linesconst [saving, setSaving] = useState(false)const [newField, setNewField] = useState('')const [newBannedWord, setNewBannedWord] = useState('')const [settings, setSettings] = useState<AISettings>({business_description: '',selling_style: 'Consultative',14 unmodified linesconst fetchSettings = async () => {if (!user?.tenant_id) returntry {const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/tenants/${user.tenant_id}`, {headers: {'Authorization': `Bearer ${localStorage.getItem('access_token')}`}})if (response.ok) {const data = await response.json()if (data.ai_settings) {16 unmodified linesconst handleSave = async () => {if (!user?.tenant_id) returnsetSaving(true)try {const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/tenants/${user.tenant_id}`, {method: 'PATCH',headers: {'Authorization': `Bearer ${localStorage.getItem('access_token')}`,'Content-Type': 'application/json'},body: JSON.stringify({1 unmodified line...persona})})if (response.ok) {alert('✅ Настройки AI Brain сохранены!')} else {13 unmodified linesalert('Это поле уже добавлено')return}setSettings({...settings,custom_fields: [...settings.custom_fields, newField.trim()]14 unmodified linesalert('Это слово уже в списке')return}setPersona({...persona,banned_words: [...persona.banned_words, newBannedWord.trim()]48 unmodified lines<buttonkey={tone.value}onClick={() => setPersona({ ...persona, tone_of_voice: tone.value as any })}className={`p-4 rounded-lg border-2 transition-all duration-200 text-left ${persona.tone_of_voice === tone.value? 'border-indigo-600 bg-indigo-50': 'border-gray-200 hover:border-indigo-300 bg-white'}`}><div className="flex items-center gap-2 mb-1"><Icon className={`w-4 h-4 ${persona.tone_of_voice === tone.value ? 'text-indigo-600' : 'text-slate-600'}`} />24 unmodified lines<buttonkey={method.value}onClick={() => setPersona({ ...persona, sales_methodology: method.value as any })}className={`w-full p-4 rounded-lg border-2 transition-all duration-200 text-left ${persona.sales_methodology === method.value? 'border-purple-600 bg-purple-50': 'border-gray-200 hover:border-purple-300 bg-white'}`}><div className="flex items-start gap-3"><Icon className={`w-5 h-5 flex-shrink-0 mt-0.5 ${persona.sales_methodology === method.value ? 'text-purple-600' : 'text-slate-600'}`} />55 unmodified lines<p className="text-sm text-slate-600 mb-4">Какую информацию AI должен собирать о клиентах</p><div className="flex flex-wrap gap-2 mb-4">{settings.custom_fields.map((field) => (<div57 unmodified lines<p className="text-sm text-slate-600 mb-4">Слова и фразы, которые AI никогда не должен использовать</p><div className="flex flex-wrap gap-2 mb-4">{persona.banned_words.map((word) => (<div63 unmodified lines6465666768697014 unmodified lines858687888990919293949596979816 unmodified lines1151161171181191201211221231241251261271 unmodified line12913013113213313413513 unmodified lines14915015115215315415514 unmodified lines17017117217317417517648 unmodified lines22522622722822923023123223323424 unmodified lines25926026126226326426526626726855 unmodified lines32432532632732832933057 unmodified lines38838939039139239339463 unmodified linesconst [saving, setSaving] = useState(false)const [newField, setNewField] = useState('')const [newBannedWord, setNewBannedWord] = useState('')const [settings, setSettings] = useState<AISettings>({business_description: '',selling_style: 'Consultative',14 unmodified linesconst fetchSettings = async () => {if (!user?.tenant_id) returntry {const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/tenants/${user.tenant_id}`, {headers: {'Authorization': `Bearer ${localStorage.getItem('auth_token')}`}})if (response.ok) {const data = await response.json()if (data.ai_settings) {16 unmodified linesconst handleSave = async () => {if (!user?.tenant_id) returnsetSaving(true)try {const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/tenants/${user.tenant_id}`, {method: 'PATCH',headers: {'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,'Content-Type': 'application/json'},body: JSON.stringify({1 unmodified line...persona})})if (response.ok) {alert('✅ Настройки AI Brain сохранены!')} else {13 unmodified linesalert('Это поле уже добавлено')return}setSettings({...settings,custom_fields: [...settings.custom_fields, newField.trim()]14 unmodified linesalert('Это слово уже в списке')return}setPersona({...persona,banned_words: [...persona.banned_words, newBannedWord.trim()]48 unmodified lines<buttonkey={tone.value}onClick={() => setPersona({ ...persona, tone_of_voice: tone.value as any })}className={`p-4 rounded-lg border-2 transition-all duration-200 text-left ${persona.tone_of_voice === tone.value? 'border-indigo-600 bg-indigo-50': 'border-gray-200 hover:border-indigo-300 bg-white'}`}><div className="flex items-center gap-2 mb-1"><Icon className={`w-4 h-4 ${persona.tone_of_voice === tone.value ? 'text-indigo-600' : 'text-slate-600'}`} />24 unmodified lines<buttonkey={method.value}onClick={() => setPersona({ ...persona, sales_methodology: method.value as any })}className={`w-full p-4 rounded-lg border-2 transition-all duration-200 text-left ${persona.sales_methodology === method.value? 'border-purple-600 bg-purple-50': 'border-gray-200 hover:border-purple-300 bg-white'}`}><div className="flex items-start gap-3"><Icon className={`w-5 h-5 flex-shrink-0 mt-0.5 ${persona.sales_methodology === method.value ? 'text-purple-600' : 'text-slate-600'}`} />55 unmodified lines<p className="text-sm text-slate-600 mb-4">Какую информацию AI должен собирать о клиентах</p><div className="flex flex-wrap gap-2 mb-4">{settings.custom_fields.map((field) => (<div57 unmodified lines<p className="text-sm text-slate-600 mb-4">Слова и фразы, которые AI никогда не должен использовать</p><div className="flex flex-wrap gap-2 mb-4">{persona.banned_words.map((word) => (<div
47 unmodified lines4849505152535418 unmodified lines73747576777879108 unmodified lines18818919019119219319419547 unmodified linestry {const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/tenants/${user.tenant_id}`, {headers: {'Authorization': `Bearer ${localStorage.getItem('access_token')}`}})18 unmodified linesconst response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/tenants/${user.tenant_id}`, {method: 'PATCH',headers: {'Authorization': `Bearer ${localStorage.getItem('access_token')}`,'Content-Type': 'application/json'},body: JSON.stringify({ ai_settings: settings })108 unmodified lineskey={style.value}onClick={() => setSettings({ ...settings, selling_style: style.value as any })}className={`p-4 rounded-lg border-2 transition-all duration-200 text-left ${settings.selling_style === style.value? 'border-indigo-600 bg-indigo-50': 'border-gray-200 hover:border-indigo-300 bg-white'}`}><h3 className={`font-bold mb-1 ${settings.selling_style === style.value ? 'text-indigo-900' : 'text-slate-900'47 unmodified lines4849505152535418 unmodified lines73747576777879108 unmodified lines18818919019119219319419547 unmodified linestry {const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/tenants/${user.tenant_id}`, {headers: {'Authorization': `Bearer ${localStorage.getItem('auth_token')}`}})18 unmodified linesconst response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/tenants/${user.tenant_id}`, {method: 'PATCH',headers: {'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,'Content-Type': 'application/json'},body: JSON.stringify({ ai_settings: settings })108 unmodified lineskey={style.value}onClick={() => setSettings({ ...settings, selling_style: style.value as any })}className={`p-4 rounded-lg border-2 transition-all duration-200 text-left ${settings.selling_style === style.value? 'border-indigo-600 bg-indigo-50': 'border-gray-200 hover:border-indigo-300 bg-white'}`}><h3 className={`font-bold mb-1 ${settings.selling_style === style.value ? 'text-indigo-900' : 'text-slate-900'
42 unmodified lines4344454647484922 unmodified lines7273747576777842 unmodified linesconst checkPartnerStatus = async () => {try {const response = await fetch('/api/v1/billing/partner/status', {headers: { 'Authorization': `Bearer ${localStorage.getItem('access_token')}` }})if (response.ok) {22 unmodified linesmethod: 'POST',headers: {'Content-Type': 'application/json','Authorization': `Bearer ${localStorage.getItem('access_token')}`},body: JSON.stringify({company_name: companyName42 unmodified lines4344454647484922 unmodified lines7273747576777842 unmodified linesconst checkPartnerStatus = async () => {try {const response = await fetch('/api/v1/billing/partner/status', {headers: { 'Authorization': `Bearer ${localStorage.getItem('auth_token')}` }})if (response.ok) {22 unmodified linesmethod: 'POST',headers: {'Content-Type': 'application/json','Authorization': `Bearer ${localStorage.getItem('auth_token')}`},body: JSON.stringify({company_name: companyName
38 unmodified lines3940414243444527 unmodified lines7374757677787922 unmodified lines10210310410510610710814 unmodified lines12312412512612712812938 unmodified linestry {const response = await fetch('/api/v1/team/members', {headers: {'Authorization': `Bearer ${localStorage.getItem('access_token')}`}})27 unmodified linesmethod: 'POST',headers: {'Content-Type': 'application/json','Authorization': `Bearer ${localStorage.getItem('access_token')}`},body: JSON.stringify(formData)})22 unmodified linesconst response = await fetch(`/api/v1/team/members/${memberId}`, {method: 'DELETE',headers: {'Authorization': `Bearer ${localStorage.getItem('access_token')}`}})14 unmodified linesconst response = await fetch(`/api/v1/team/members/${memberId}/toggle`, {method: 'PATCH',headers: {'Authorization': `Bearer ${localStorage.getItem('access_token')}`}})38 unmodified lines3940414243444527 unmodified lines7374757677787922 unmodified lines10210310410510610710814 unmodified lines12312412512612712812938 unmodified linestry {const response = await fetch('/api/v1/team/members', {headers: {'Authorization': `Bearer ${localStorage.getItem('auth_token')}`}})27 unmodified linesmethod: 'POST',headers: {'Content-Type': 'application/json','Authorization': `Bearer ${localStorage.getItem('auth_token')}`},body: JSON.stringify(formData)})22 unmodified linesconst response = await fetch(`/api/v1/team/members/${memberId}`, {method: 'DELETE',headers: {'Authorization': `Bearer ${localStorage.getItem('auth_token')}`}})14 unmodified linesconst response = await fetch(`/api/v1/team/members/${memberId}/toggle`, {method: 'PATCH',headers: {'Authorization': `Bearer ${localStorage.getItem('auth_token')}`}})
2 unmodified lines34567892 unmodified lines12131415161718192021222324254 unmodified lines3031323334353637381 unmodified line4041424344454647482 unmodified lines515253545556577 unmodified lines6566676869707172737475767778798081828384858687888990919293949596972 unmodified lines1001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515522 unmodified linesimport { useState, useRef, useEffect } from 'react'import { Message, Lead, leadsApi, playbookApi } from '@/lib/api'import { cn, formatDate } from '@/lib/utils'import { Bot, User, Send, Sparkles, Loader2, Info, X, ArrowLeft } from 'lucide-react'import { StageStepper, SalesStage } from './StageStepper'import { ClientCard } from './ClientCard'import { subscribeToMessages, isRealtimeEnabled } from '@/lib/supabaseClient'2 unmodified linesmessages: Message[]leadId?: stringtenantId?: stringconversationId?: string // CRITICAL: Need this to send messageslead?: Lead // Add lead prop for stage trackingconversation?: any // For human_takeover stateisLoading?: booleanisAnalyzing?: booleanonRefresh?: () => voidonTakeover?: () => void // For ClientCard in mobile draweronBack?: () => void // Mobile: go back to leads list}export function ChatWindow({ messages, leadId, tenantId, conversationId, lead, conversation, isLoading, isAnalyzing, onRefresh, onTakeover, onBack }: ChatWindowProps) {4 unmodified linesconst [stages, setStages] = useState<SalesStage[]>([])const [loadingStages, setLoadingStages] = useState(false)const [updatingStage, setUpdatingStage] = useState(false)const [isMobileDrawerOpen, setIsMobileDrawerOpen] = useState(false) // Mobile drawer stateconst [isTogglingAI, setIsTogglingAI] = useState(false) // AI toggle stateconst [realtimeMessages, setRealtimeMessages] = useState<Message[]>([]) // Messages from Realtimeconst scrollToBottom = () => {messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })1 unmodified lineuseEffect(() => {scrollToBottom()}, [messages])// Load stages when component mounts or tenantId changesuseEffect(() => {if (tenantId) {loadStages()2 unmodified linesconst loadStages = async () => {if (!tenantId) returnsetLoadingStages(true)try {const data = await playbookApi.getStages()7 unmodified linesconst handleStageClick = async (stageId: string) => {if (!leadId || !tenantId || updatingStage) returnsetUpdatingStage(true)try {await leadsApi.updateStage(leadId, stageId)// Refresh lead data to update UIif (onRefresh) {onRefresh()}} catch (error) {console.error('Ошибка обновления этапа:', error)alert('Ошибка обновления этапа')} finally {setUpdatingStage(false)}}// Toggle AI Auto/Manual modeconst handleToggleAI = async () => {if (!leadId || isTogglingAI) returnsetIsTogglingAI(true)try {const newIsAIActive = !!conversation?.human_takeover // If human took over, turn AI back onconst token = localStorage.getItem('auth_token')if (!token) throw new Error('Не авторизован')const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/leads/${leadId}/toggle-ai`,{2 unmodified lines'Authorization': `Bearer ${token}`,'Content-Type': 'application/json'},body: JSON.stringify({is_ai_active: newIsAIActive})})if (!response.ok) {const error = await response.json()throw new Error(error.detail || 'Не удалось переключить режим')}const data = await response.json()console.log('✅ AI mode toggled:', data)// Refresh conversation dataif (onRefresh) {setTimeout(onRefresh, 300)}} catch (error) {console.error('❌ Failed to toggle AI:', error)alert('Ошибка переключения режима')} finally {setIsTogglingAI(false)}}// TASK 2: Replace Polling with Supabase RealtimeuseEffect(() => {if (!conversationId) return// Check if Realtime is enabledif (!isRealtimeEnabled()) {console.warn('⚠️ Supabase Realtime not configured. Set NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY')return}console.log('🔌 Setting up Realtime subscription for conversation:', conversationId)// Subscribe to new messagesconst unsubscribe = subscribeToMessages(conversationId, (newMessage) => {console.log('✨ New message from Realtime:', newMessage)// Add to realtime messages (deduplicate by ID)setRealtimeMessages(prev => {// Check if message already existsif (prev.some(msg => msg.id === newMessage.id)) {return prev}return [...prev, newMessage]})// Auto-scroll to new messagesetTimeout(() => scrollToBottom(), 100)})// Cleanup on unmount or conversation changereturn () => {console.log('🔌 Cleaning up Realtime subscription')unsubscribe()setRealtimeMessages([]) // Clear realtime messages}}, [conversationId])const handleSend = async () => {if (!inputMessage.trim() || !leadId || !tenantId || !conversationId) returnif (isSending) return // Prevent double-sendconst messageContent = inputMessage.trim()setInputMessage('') // Clear input immediatelysetIsSending(true)// Optimistic UI: Add message locally before API respondsconst optimisticMessage: Message = {id: `optimistic-${Date.now()}`,conversation_id: conversationId,tenant_id: tenantId,sender_type: 'human',content: messageContent,created_at: new Date().toISOString(),prompt_tokens: null,completion_tokens: null,model_used: null}setOptimisticMessages(prev => [...prev, optimisticMessage])try {const token = localStorage.getItem('auth_token')if (!token) {throw new Error('Нет токена авторизации')}const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/chats/send`, {method: 'POST',headers: {'Content-Type': 'application/json','Authorization': `Bearer ${token}`},body: JSON.stringify({lead_id: leadId,conversation_id: conversationId,message: messageContent})})if (!response.ok) {const error = await response.json()// Show specific error from backendthrow new Error(error.detail || error.message || 'Не удалось отправить сообщение')}const data = await response.json()console.log('✅ Message sent:', data)// Warn if Telegram failed but message savedif (!data.telegram_sent && data.telegram_error) {console.warn('⚠️ Ошибка Telegram:', data.telegram_error)alert(`❗ Сообщение сохранено, но не отправлено в Telegram:\n${data.telegram_error}`)}// Remove optimistic message and refresh to get real datasetOptimisticMessages(prev => prev.filter(msg => msg.id !== optimisticMessage.id))// Trigger refresh to get the real message from DBif (onRefresh) {setTimeout(onRefresh, 300) // Small delay to let backend save}} catch (error) {console.error('❌ Failed to send message:', error)// Remove optimistic message on errorsetOptimisticMessages(prev => prev.filter(msg => msg.id !== optimisticMessage.id))// Show specific error message from backendconst errorMessage = error instanceof Error ? error.message : 'Неизвестная ошибка'alert(`❌ Ошибка отправки:\n${errorMessage}`)} finally {setIsSending(false)}}return (<><div className="flex flex-col h-full">{/* Sales Funnel Stepper - Horizontal Progress Bar */}{stages.length > 0 && lead && (<StageStepperstages={stages}currentStageId={lead.current_stage_id || null}onStageClick={handleStageClick}isLoading={updatingStage}/>)}{/* AI Mode Header Banner - Clean with Status Badge */}<div className="bg-white border-b border-slate-200 px-4 py-3 flex items-center justify-between"><div className="flex items-center gap-3">{/* Mobile Back Button */}{onBack && (<buttononClick={onBack}className="md:hidden p-1.5 hover:bg-slate-100 rounded-full transition-colors"title="Назад"><ArrowLeft className="w-5 h-5 text-slate-600" /></button>)}{/* Lead Name */}<h3 className="font-semibold text-slate-900 text-base">{lead?.name || 'Без имени'}</h3>{/* Status Badge */}{lead && (<span className={cn("inline-flex items-center px-2 py-0.5 text-xs font-semibold rounded-full",lead.heat_level.toUpperCase() === 'HOT' && "bg-red-100 text-red-700",lead.heat_level.toUpperCase() === 'WARM' && "bg-orange-100 text-orange-700",lead.heat_level.toUpperCase() === 'COLD' && "bg-blue-100 text-blue-700")}>{lead.heat_level.toUpperCase() === 'HOT' && 'Горячий'}{lead.heat_level.toUpperCase() === 'WARM' && 'Тёплый'}{lead.heat_level.toUpperCase() === 'COLD' && 'Холодный'}</span>)}</div><div className="flex items-center gap-3">{/* Mobile Info Button */}<buttononClick={() => setIsMobileDrawerOpen(true)}className="md:hidden p-2 hover:bg-slate-100 rounded-full transition-colors"title="Показать аналитику"><Info className="w-5 h-5 text-slate-600" /></button>{/* Auto/Manual Toggle - Clean */}<buttononClick={handleToggleAI}disabled={isTogglingAI}className="flex items-center gap-2 px-3 py-1.5 rounded-full transition-all disabled:opacity-50"><span className="text-xs font-semibold text-slate-600">Автопилот</span><div className={cn("w-10 h-5 rounded-full transition-colors relative",conversation?.human_takeover ? "bg-slate-300" : "bg-green-500")}><div className={cn("absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform shadow-sm",conversation?.human_takeover ? "translate-x-0" : "translate-x-5")} /></div></button></div></div>{/* Баннер анализа ИИ */}{isAnalyzing && (<div className="bg-gradient-to-r from-indigo-50 to-purple-50 border-b border-indigo-200 px-4 py-2"><div className="flex items-center gap-2 text-indigo-700"><Loader2 className="w-4 h-4 animate-spin" /><span className="text-sm font-medium">ИИ анализирует лида...</span><div className="flex gap-1 ml-2"><div className="w-1.5 h-1.5 bg-indigo-600 rounded-full animate-pulse" /><div className="w-1.5 h-1.5 bg-indigo-600 rounded-full animate-pulse" style={{ animationDelay: '200ms' }} /><div className="w-1.5 h-1.5 bg-indigo-600 rounded-full animate-pulse" style={{ animationDelay: '400ms' }} /></div></div></div>)}{/* Область сообщений */}<div className="flex-1 overflow-y-auto p-6 space-y-4">{/* Пустое состояние */}{messages.length === 0 && optimisticMessages.length === 0 && (<div className="flex flex-col items-center justify-center h-full text-center"><div className="w-16 h-16 rounded-full bg-gradient-to-br from-indigo-100 to-purple-100 flex items-center justify-center mb-4"><Sparkles className="w-8 h-8 text-indigo-600" /></div><h3 className="text-lg font-semibold text-slate-900 mb-2">Начните диалог</h3><p className="text-sm text-slate-500 max-w-xs">Отправьте первое сообщение, чтобы начать общение с клиентом</p></div>)}{/* Список сообщений */}{[...messages, ...realtimeMessages, ...optimisticMessages].map((message, index) => {// Клиент (user) — слева, наши сообщения (ai, human) — справаconst isClient = message.sender_type === 'user'const isOurMessage = message.sender_type === 'ai' || message.sender_type === 'human'const isAI = message.sender_type === 'ai'return (<divkey={message.id}className={cn("flex gap-3 items-start",isOurMessage ? "justify-end" : "justify-start")}>{/* Аватар клиента слева */}{isClient && (<div className="w-8 h-8 rounded-full bg-gradient-to-br from-slate-400 to-slate-600 flex items-center justify-center flex-shrink-0 shadow-md"><User className="w-4 h-4 text-white" /></div>)}<div className="flex flex-col max-w-[75%]"><divclassName={cn("px-4 py-3 shadow-sm",isOurMessage? "bg-indigo-600 text-white rounded-2xl rounded-tr-sm": "bg-white text-slate-800 rounded-2xl rounded-tl-sm border border-slate-100")}><p className="text-sm leading-relaxed whitespace-pre-wrap">{message.content}</p></div>{/* Метаданные под пузырьком */}<div className={cn("flex items-center gap-2 mt-1 px-2 text-xs",isOurMessage ? "justify-end" : "justify-start")}><span className="text-slate-400">{formatDate(message.created_at)}</span>{isAI && message.model_used && (<><span className="text-slate-300">•</span><span className="text-slate-400 italic">ИИ</span></>)}{message.sender_type === 'human' && (<><span className="text-slate-300">•</span><span className="text-slate-400 italic">Менеджер</span></>)}{message.id.startsWith('optimistic-') && (<><span className="text-slate-300">•</span><span className="text-slate-400 italic">Отправляется...</span></>)}</div></div>{/* Аватар наших сообщений справа */}{isOurMessage && (<div className={cn("w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 shadow-md",isAI? "bg-gradient-to-br from-indigo-500 to-purple-600": "bg-indigo-600")}>{isAI ? (<Sparkles className="w-4 h-4 text-white" />) : (<User className="w-4 h-4 text-white" />)}</div>)}</div>)})}{/* Индикатор загрузки ИИ */}{isLoading && (<div className="flex justify-end gap-3 items-end"><div className="bg-indigo-100 text-indigo-700 rounded-2xl px-4 py-3 shadow-sm border border-indigo-200"><div className="flex gap-1"><div className="w-2 h-2 bg-indigo-600 rounded-full animate-bounce" style={{ animationDelay: '0ms' }} /><div className="w-2 h-2 bg-indigo-600 rounded-full animate-bounce" style={{ animationDelay: '150ms' }} /><div className="w-2 h-2 bg-indigo-600 rounded-full animate-bounce" style={{ animationDelay: '300ms' }} /></div></div><div className="w-8 h-8 rounded-full bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center flex-shrink-0 shadow-md"><Sparkles className="w-4 h-4 text-white" /></div></div>)}<div ref={messagesEndRef} /></div>{/* Поле ввода - Плавающий стиль с тенью */}{leadId && tenantId && conversationId ? (<div className="p-4 bg-white border-t border-slate-200">{/* Подсказка о режиме */}{conversation?.human_takeover && (<div className="mb-3 px-3 py-2 bg-amber-50 border border-amber-200 rounded-lg flex items-center gap-2"><User className="w-4 h-4 text-amber-600" /><p className="text-xs text-amber-700"><span className="font-semibold">Ручной режим:</span> ИИ не будет отвечать автоматически</p></div>)}<div className="relative bg-white rounded-xl shadow-lg border border-slate-200"><textareavalue={inputMessage}onChange={(e) => setInputMessage(e.target.value)}onKeyDown={(e) => {if (e.key === 'Enter' && !e.shiftKey) {e.preventDefault()handleSend()}}}placeholder={conversation?.human_takeover? "Вы отвечаете вручную...": "Напишите сообщение..."}className="w-full px-4 py-3 pr-14 bg-transparent focus:outline-none resize-none text-sm placeholder:text-slate-400"rows={1}disabled={isSending}/><buttononClick={handleSend}disabled={!inputMessage.trim() || isSending}className="absolute right-2 bottom-2 p-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg transition-all duration-200 shadow-md hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-indigo-600"title="Отправить">{isSending ? (<Loader2 className="w-4 h-4 animate-spin" />) : (<Send className="w-4 h-4" />)}</button></div>{/* Подсказка по управлению */}<p className="text-xs text-slate-500 mt-2 text-center"><kbd className="px-1.5 py-0.5 bg-slate-100 border border-slate-300 rounded text-xs">Enter</kbd> — отправить • <kbd className="px-1.5 py-0.5 bg-slate-100 border border-slate-300 rounded text-xs">Shift + Enter</kbd> — новая строка</p></div>) : (<div className="p-4 bg-slate-50 border-t border-slate-200"><p className="text-sm text-slate-500 text-center">Выберите диалог для отправки сообщений</p></div>)}</div>{/* Mobile Drawer for ClientCard */}{isMobileDrawerOpen && lead && (<div className="fixed inset-0 z-50 md:hidden">{/* Backdrop */}<divclassName="absolute inset-0 bg-black/50"onClick={() => setIsMobileDrawerOpen(false)}/>{/* Drawer */}<div className="absolute right-0 top-0 h-full w-full max-w-sm bg-white shadow-xl overflow-y-auto animate-slide-in-right">{/* Header */}<div className="sticky top-0 bg-white border-b border-slate-200 px-4 py-3 flex items-center justify-between z-10"><h3 className="font-bold text-slate-900">Аналитика ИИ</h3><buttononClick={() => setIsMobileDrawerOpen(false)}className="p-2 hover:bg-slate-100 rounded-full transition-colors"><X className="w-5 h-5 text-slate-600" /></button></div>{/* ClientCard Content */}<ClientCardlead={lead}onTakeover={onTakeover || (() => {})}isAnalyzing={isAnalyzing}onRefresh={onRefresh}conversationId={conversationId}tenantId={tenantId}/></div></div>)}</>)}2 unmodified lines34567892 unmodified lines12131415161718192021222324254 unmodified lines3031323334353637381 unmodified line40414243444546472 unmodified lines5051525354557 unmodified lines636465666768697071727374757677787980818283848586872 unmodified lines909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773782 unmodified linesimport { useState, useRef, useEffect } from 'react'import { Message, Lead, leadsApi, playbookApi } from '@/lib/api'import { cn, formatDate } from '@/lib/utils'import { Bot, User, Send, Sparkles, Loader2, Info, X, ArrowLeft, Paperclip, Smile } from 'lucide-react'import { StageStepper, SalesStage } from './StageStepper'import { ClientCard } from './ClientCard'import { subscribeToMessages, isRealtimeEnabled } from '@/lib/supabaseClient'2 unmodified linesmessages: Message[]leadId?: stringtenantId?: stringconversationId?: stringlead?: Leadconversation?: anyisLoading?: booleanisAnalyzing?: booleanonRefresh?: () => voidonTakeover?: () => voidonBack?: () => void}export function ChatWindow({ messages, leadId, tenantId, conversationId, lead, conversation, isLoading, isAnalyzing, onRefresh, onTakeover, onBack }: ChatWindowProps) {4 unmodified linesconst [stages, setStages] = useState<SalesStage[]>([])const [loadingStages, setLoadingStages] = useState(false)const [updatingStage, setUpdatingStage] = useState(false)const [isMobileDrawerOpen, setIsMobileDrawerOpen] = useState(false)const [isTogglingAI, setIsTogglingAI] = useState(false)const [realtimeMessages, setRealtimeMessages] = useState<Message[]>([])const scrollToBottom = () => {messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })1 unmodified lineuseEffect(() => {scrollToBottom()}, [messages, optimisticMessages, realtimeMessages])useEffect(() => {if (tenantId) {loadStages()2 unmodified linesconst loadStages = async () => {if (!tenantId) returnsetLoadingStages(true)try {const data = await playbookApi.getStages()7 unmodified linesconst handleStageClick = async (stageId: string) => {if (!leadId || !tenantId || updatingStage) returnsetUpdatingStage(true)try {await leadsApi.updateStage(leadId, stageId)if (onRefresh) onRefresh()} catch (error) {console.error('Ошибка обновления этапа:', error)} finally {setUpdatingStage(false)}}const handleToggleAI = async () => {if (!leadId || isTogglingAI) returnsetIsTogglingAI(true)try {const newIsAIActive = !!conversation?.human_takeoverconst token = localStorage.getItem('auth_token')if (!token) throw new Error('Не авторизован')const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/leads/${leadId}/toggle-ai`,{2 unmodified lines'Authorization': `Bearer ${token}`,'Content-Type': 'application/json'},body: JSON.stringify({ enable: newIsAIActive })})if (!response.ok) throw new Error('Failed to toggle AI')if (onRefresh) onRefresh()} catch (error) {console.error('Error toggling AI:', error)alert('Ошибка переключения режима AI')} finally {setIsTogglingAI(false)}}useEffect(() => {if (!leadId || !tenantId || !isRealtimeEnabled()) returnsetRealtimeMessages([])const unsubscribe = subscribeToMessages(conversationId || '', (newMessage) => {setRealtimeMessages(prev => {if (prev.some(m => m.id === newMessage.id)) return prevreturn [...prev, newMessage]})})return () => { unsubscribe() }}, [leadId, tenantId])const handleSendMessage = async (e: React.FormEvent) => {e.preventDefault()if (!inputMessage.trim() || !leadId || !conversationId) returnconst tempId = Date.now().toString()const optimisticMessage: Message = {id: tempId,conversation_id: conversationId,sender_type: 'human',content: inputMessage,created_at: new Date().toISOString(),}setOptimisticMessages(prev => [...prev, optimisticMessage])setInputMessage('')setIsSending(true)try {// @ts-ignore - sendMessage exists in API but might be missing in type definitionawait leadsApi.sendMessage(leadId, inputMessage)setOptimisticMessages(prev => prev.filter(m => m.id !== tempId))} catch (error) {console.error('Error sending message:', error)setOptimisticMessages(prev => prev.filter(m => m.id !== tempId))alert('Не удалось отправить сообщение')} finally {setIsSending(false)}}const allMessages = [...messages, ...optimisticMessages, ...realtimeMessages].filter((msg, index, self) =>index === self.findIndex((t) => t.id === msg.id)).sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime())const isAIActive = !conversation?.human_takeoverreturn (<div className="flex flex-col h-full bg-slate-50 font-['Inter'] relative">{/* Header */}<div className="bg-white border-b border-slate-200 p-4 flex items-center justify-between shadow-sm z-10"><div className="flex items-center gap-3"><button onClick={onBack} className="md:hidden p-2 -ml-2 text-slate-500 hover:text-slate-900"><ArrowLeft className="w-5 h-5" /></button><div className="flex items-center gap-3"><div className="w-10 h-10 rounded-full bg-gradient-to-br from-indigo-100 to-purple-100 flex items-center justify-center text-indigo-600 font-bold text-sm border border-indigo-50">{lead?.name?.charAt(0) || 'L'}</div><div><h2 className="font-bold text-slate-900 text-sm">{lead?.name || 'Лид'}</h2><div className="flex items-center gap-2"><span className="text-xs text-slate-500">{(lead as any)?.channel_source || 'Unknown'}</span>{isAnalyzing && (<span className="flex items-center gap-1 text-[10px] text-indigo-600 bg-indigo-50 px-1.5 py-0.5 rounded-full animate-pulse"><Sparkles className="w-3 h-3" />AI думает...</span>)}</div></div></div></div><div className="flex items-center gap-2"><buttononClick={handleToggleAI}disabled={isTogglingAI}className={cn("flex items-center gap-2 px-3 py-1.5 rounded-lg text-xs font-medium transition-all duration-200 border",isAIActive? "bg-indigo-50 text-indigo-700 border-indigo-200 hover:bg-indigo-100": "bg-slate-50 text-slate-600 border-slate-200 hover:bg-slate-100")}>{isTogglingAI ? (<Loader2 className="w-3.5 h-3.5 animate-spin" />) : (<Bot className={cn("w-3.5 h-3.5", isAIActive ? "text-indigo-600" : "text-slate-400")} />)}{isAIActive ? 'AI Активен' : 'AI Отключен'}</button><buttononClick={() => setIsMobileDrawerOpen(true)}className="md:hidden p-2 text-slate-400 hover:text-slate-600"><Info className="w-5 h-5" /></button></div></div>{/* Stage Stepper */}<div className="bg-white border-b border-slate-100 px-4 py-2 overflow-x-auto scrollbar-hide">{loadingStages ? (<div className="h-8 w-full bg-slate-100 animate-pulse rounded" />) : (<StageStepperstages={stages}currentStageId={lead?.current_stage_id || null}onStageClick={handleStageClick}isLoading={updatingStage}/>)}</div>{/* Messages Area */}<div className="flex-1 overflow-y-auto p-4 space-y-6 bg-slate-50/50">{isLoading ? (<div className="flex items-center justify-center h-full"><Loader2 className="w-8 h-8 animate-spin text-indigo-600" /></div>) : allMessages.length === 0 ? (<div className="flex flex-col items-center justify-center h-full text-slate-400"><div className="w-16 h-16 bg-white rounded-full flex items-center justify-center shadow-sm mb-4"><Bot className="w-8 h-8 text-slate-300" /></div><p className="text-sm font-medium">История сообщений пуста</p><p className="text-xs mt-1">Начните диалог первым</p></div>) : (allMessages.map((msg) => {const isAI = msg.sender_type === 'ai'const isHuman = msg.sender_type === 'human'return (<divkey={msg.id}className={cn("flex w-full max-w-3xl mx-auto group",isAI ? "justify-start" : "justify-end")}><div className={cn("flex gap-3 max-w-[85%]",isAI ? "flex-row" : "flex-row-reverse")}>{/* Avatar */}<div className={cn("w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 shadow-sm mt-auto mb-1",isAI ? "bg-indigo-600 text-white" : "bg-white text-slate-600 border border-slate-200")}>{isAI ? <Bot className="w-4 h-4" /> : <User className="w-4 h-4" />}</div>{/* Message Bubble */}<div className="flex flex-col gap-1"><div className={cn("px-4 py-3 rounded-2xl text-sm leading-relaxed shadow-sm relative",isAI? "bg-white text-slate-800 border border-slate-100 rounded-bl-none": "bg-indigo-600 text-white rounded-br-none")}>{msg.content}</div><span className={cn("text-[10px] text-slate-400 px-1",isAI ? "text-left" : "text-right")}>{formatDate(msg.created_at)}</span></div></div></div>)}))}<div ref={messagesEndRef} /></div>{/* Input Area */}<div className="p-4 bg-white border-t border-slate-200"><div className="max-w-3xl mx-auto relative"><formonSubmit={handleSendMessage}className="flex items-end gap-2 bg-slate-50 p-2 rounded-2xl border border-slate-200 focus-within:border-indigo-300 focus-within:ring-4 focus-within:ring-indigo-50 transition-all"><buttontype="button"className="p-2 text-slate-400 hover:text-indigo-600 hover:bg-white rounded-xl transition-colors"><Paperclip className="w-5 h-5" /></button><textareavalue={inputMessage}onChange={(e) => setInputMessage(e.target.value)}placeholder="Напишите сообщение..."className="flex-1 bg-transparent border-none focus:ring-0 text-slate-900 placeholder:text-slate-400 resize-none py-2.5 max-h-32 min-h-[44px] text-sm"rows={1}onKeyDown={(e) => {if (e.key === 'Enter' && !e.shiftKey) {e.preventDefault()handleSendMessage(e)}}}/><div className="flex items-center gap-1"><buttontype="button"className="p-2 text-slate-400 hover:text-amber-500 hover:bg-white rounded-xl transition-colors"><Smile className="w-5 h-5" /></button><buttontype="submit"disabled={!inputMessage.trim() || isSending}className={cn("p-2 rounded-xl transition-all duration-200 flex items-center justify-center shadow-sm",inputMessage.trim() && !isSending? "bg-indigo-600 text-white hover:bg-indigo-700 hover:shadow-md hover:scale-105": "bg-slate-200 text-slate-400 cursor-not-allowed")}>{isSending ? (<Loader2 className="w-5 h-5 animate-spin" />) : (<Send className="w-5 h-5" />)}</button></div></form><p className="text-[10px] text-center text-slate-400 mt-2">Enter для отправки, Shift + Enter для переноса строки</p></div></div>{/* Mobile Drawer */}{isMobileDrawerOpen && (<div className="fixed inset-0 z-50 md:hidden"><div className="absolute inset-0 bg-black/50 backdrop-blur-sm" onClick={() => setIsMobileDrawerOpen(false)} /><div className="absolute right-0 top-0 bottom-0 w-[85%] bg-white shadow-2xl flex flex-col animate-in slide-in-from-right duration-300"><div className="p-4 border-b border-slate-100 flex items-center justify-between"><h3 className="font-bold text-slate-900">Инфо о лиде</h3><button onClick={() => setIsMobileDrawerOpen(false)} className="p-2 hover:bg-slate-100 rounded-full"><X className="w-5 h-5 text-slate-500" /></button></div><div className="flex-1 overflow-y-auto">{lead && (<ClientCardlead={lead}onTakeover={onTakeover || (() => { })}isAnalyzing={isAnalyzing}onRefresh={onRefresh}conversationId={conversationId}tenantId={tenantId}/>)}</div></div></div>)}</div>)}
2 unmodified lines34567897 unmodified lines17181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237242 unmodified linesimport { useState, useEffect } from 'react'import { Lead } from '@/lib/api'import { cn } from '@/lib/utils'import { Brain, TrendingUp, DollarSign, Target, Clock, AlertCircle, Lightbulb, User as UserIcon, CheckCircle2, Phone, Check, Loader2, RefreshCw, Bot, Zap, Database, Shield } from 'lucide-react'import { useToast } from '@/contexts/ToastContext'interface ClientCardProps {7 unmodified linesexport function ClientCard({ lead, onTakeover, isAnalyzing, onRefresh, conversationId, tenantId }: ClientCardProps) {const toast = useToast()// Parse AI Summary JSON - The Golden 11 Fieldsconst summary = lead.ai_summary_json || {}// FIXED: Use lead.id as key for state (per-lead state tracking)const [analyzingLeads, setAnalyzingLeads] = useState<Set<string>>(new Set())const [syncingLeads, setSyncingLeads] = useState<Set<string>>(new Set())const isManualAnalyzing = analyzingLeads.has(lead.id)const isSyncingCRM = syncingLeads.has(lead.id)// Проверка на ошибки в данныхconst isErrorValue = (value: any): boolean => {if (!value || typeof value !== 'string') return falseconst errorPatterns = ['unknown','error','failed','retry','analysis failed','summary generation','typeerror','undefined']return errorPatterns.some(pattern => value.toLowerCase().includes(pattern))}// Очистка значения от ошибокconst cleanValue = (value: any, fallback: string): string => {if (!value || isErrorValue(value)) return fallbackreturn value}// Extract all 11 fields with fallbacks и очисткой от ошибокconst golden11 = {// Hard Data (4 fields)intent: cleanValue(summary.intent || lead.need, 'Не определено'),budget: cleanValue(summary.budget || lead.budget, 'Не определён'),authority: cleanValue(summary.authority || lead.authority, 'Неизвестно'),timeline: cleanValue(summary.timeline || lead.timeline, 'Не указаны'),// Soft Data (3 fields)pain_points: Array.isArray(summary.pain_points)? summary.pain_points.filter((p: string) => !isErrorValue(p)): [],objections: Array.isArray(summary.objections)? summary.objections.filter((o: string) => !isErrorValue(o)): [],psychotype: cleanValue(summary.psychotype || lead.psychotype, 'unknown'),// Strategy (4 fields)hidden_signals: isErrorValue(summary.hidden_signals) ? null : (summary.hidden_signals || null),recommendation: isErrorValue(summary.recommendation) ? null : (summary.recommendation || null),draft_reply: isErrorValue(summary.draft_reply) ? null : (summary.draft_reply || null),heat_score: typeof summary.heat_score === 'number' ? summary.heat_score : (lead.heat_score || 0)}// Psychotype localization with colorsconst localizePsychotype = (psychotype: string): { label: string; color: string } => {const lower = psychotype.toLowerCase()const map: Record<string, { label: string; color: string }> = {'dominant': { label: 'Доминантный', color: 'bg-red-100 text-red-700 border-red-200' },'influential': { label: 'Влияющий', color: 'bg-yellow-100 text-yellow-700 border-yellow-200' },'steady': { label: 'Стабильный', color: 'bg-green-100 text-green-700 border-green-200' },'conscientious': { label: 'Аналитический', color: 'bg-blue-100 text-blue-700 border-blue-200' },'unknown': { label: 'Не определён', color: 'bg-gray-100 text-gray-700 border-gray-200' }}return map[lower] || { label: psychotype, color: 'bg-gray-100 text-gray-700 border-gray-200' }}// Get psychotype badge color (removed, now in localizePsychotype)const psychotypeData = localizePsychotype(golden11.psychotype)// Calculate donut chart - PERFECTLY ALIGNED WITH CONTAINERconst scorePercentage = golden11.heat_score// For w-48 h-48 (192px), optimal radius calculation:// Container: 192px, StrokeWidth: 16px (thicker for visibility)// Radius = (192 - strokeWidth - padding*2) / 2 = (192 - 16 - 20) / 2 = 78const strokeWidth = 16const radius = 78 // Maximized to fit perfectly in viewBox 192x192const circumference = 2 * Math.PI * radiusconst strokeDashoffset = circumference - (scorePercentage / 100) * circumference// Get color based on score - ALIGNED WITH BACKEND (backend\app\models\lead.py)// Backend uses: hot >= 70, warm >= 40, cold >= 20const getScoreColor = (score: number) => {if (score >= 70) return { // FIXED: was 80, now matches backendtext: 'text-emerald-600',stroke: 'stroke-emerald-500',bg: 'bg-emerald-50',glow: 'shadow-emerald-200',label: 'Горячий'}if (score >= 40) return { // FIXED: was 50, now matches backendtext: 'text-amber-600',stroke: 'stroke-amber-500',bg: 'bg-amber-50',glow: 'shadow-amber-200',label: 'Тёплый'}if (score >= 20) return {text: 'text-blue-600',stroke: 'stroke-blue-500',bg: 'bg-blue-50',glow: 'shadow-blue-200',label: 'Холодный'}return {text: 'text-slate-500',stroke: 'stroke-slate-400',bg: 'bg-slate-50',glow: 'shadow-slate-200',label: 'Нет данных'}}const scoreColors = getScoreColor(scorePercentage)// 11th field: Heat Score (displayed in donut chart)// Manual analysis trigger - PER-LEAD STATE TRACKINGconst handleManualAnalysis = async () => {// Add this lead to analyzing setsetAnalyzingLeads(prev => new Set(prev).add(lead.id))toast.info('Анализ запущен',`Обновление AI саммари для ${lead.name || 'клиента'}...`)try {const token = localStorage.getItem('auth_token')if (!token) {throw new Error('Not authenticated')}console.log('🔍 Triggering manual analysis for lead:', lead.id)const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/leads/${lead.id}/analyze`,{method: 'POST',headers: {'Authorization': `Bearer ${token}`,'Content-Type': 'application/json'}})if (!response.ok) {const error = await response.json()throw new Error(error.detail?.error_message || error.detail || 'Analysis failed')}const data = await response.json()console.log('✅ Analysis result:', data)if (data.validation?.all_fields_present) {toast.success('Анализ завершён','Все 11 полей AI саммари успешно обновлены')} else {toast.warning('Анализ завершён',`Отсутствуют поля: ${data.validation?.missing_fields?.join(', ')}`)}if (onRefresh) {onRefresh()}} catch (error) {console.error('❌ Manual analysis failed:', error)const errorMessage = error instanceof Error ? error.message : 'Неизвестная ошибка'toast.error('Ошибка анализа',errorMessage)} finally {// Remove this lead from analyzing setsetAnalyzingLeads(prev => {const next = new Set(prev)next.delete(lead.id)return next})}}// Removed: Delegate to AI button (now handled by toggle in ChatWindow)// Sync to CRM - PER-LEAD STATE TRACKINGconst handleSyncToCRM = async () => {if (!tenantId) {toast.error('Ошибка', 'tenant_id не найден')return}// Add this lead to syncing setsetSyncingLeads(prev => new Set(prev).add(lead.id))toast.info('Синхронизация...', 'Отправка данных в CRM системы')try {const token = localStorage.getItem('auth_token')if (!token) {throw new Error('Not authenticated')}console.log('🔄 Syncing lead to CRM:', lead.id)// Get active integrations firstconst integrationsResponse = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/crm/${tenantId}/integrations`,{headers: {'Authorization': `Bearer ${token}`}})if (!integrationsResponse.ok) {throw new Error('Не удалось получить список интеграций')}const integrations = await integrationsResponse.json()const activeIntegrations = integrations.filter((i: any) => i.is_active && i.status === 'active')if (activeIntegrations.length === 0) {toast.warning('Нет активных интеграций','Настройте интеграцию в разделе "CRM Интеграция"')return}// Sync to all active integrationslet successCount = 0let errors: string[] = []for (const integration of activeIntegrations) {try {const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/crm/${tenantId}/leads/${lead.id}/sync-to-crm?integration_id=${integration.id}&force=true`,{method: 'POST',headers: {'Authorization': `Bearer ${token}`,'Content-Type': 'application/json'}})if (response.ok) {successCount++} else {const error = await response.json()errors.push(`${integration.integration_name}: ${error.detail}`)}} catch (error) {errors.push(`${integration.integration_name}: Ошибка подключения`)}}if (successCount > 0) {toast.success('Синхронизация успешна',`Данные отправлены в ${successCount} CRM систем${successCount > 1 ? 'ы' : 'у'}`)if (errors.length > 0) {toast.warning('Частичные ошибки', errors.join('; '))}if (onRefresh) {onRefresh()}} else {toast.error('Ошибка синхронизации',errors.join('; '))}} catch (error) {console.error('❌ CRM sync failed:', error)const errorMessage = error instanceof Error ? error.message : 'Неизвестная ошибка'toast.error('Ошибка синхронизации с CRM', errorMessage)} finally {// Remove this lead from syncing setsetSyncingLeads(prev => {const next = new Set(prev)next.delete(lead.id)return next})}}return (<div className="h-full overflow-y-auto bg-gradient-to-b from-slate-50 to-white"><div className="p-6 space-y-6">{/* Header: Анализ Клиента + Кнопка обновления - FIXED Z-INDEX */}<div className="sticky top-0 bg-white/95 backdrop-blur-sm -mx-6 -mt-6 px-6 py-4 border-b border-slate-200 shadow-sm z-50"><div className="flex items-center justify-between mb-3"><div className="flex items-center gap-3"><h2 className="text-lg font-bold text-slate-900 flex items-center gap-2"><Brain className="w-5 h-5 text-indigo-600" />Анализ ИИ</h2>{/* Индикатор состояния данных */}{scorePercentage === 0 ? (<span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-amber-50 border border-amber-200 rounded-full text-xs font-semibold text-amber-700"><span className="w-2 h-2 bg-amber-500 rounded-full animate-pulse" />Нет анализа</span>) : (<span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-emerald-50 border border-emerald-200 rounded-full text-xs font-semibold text-emerald-700"><span className="w-2 h-2 bg-emerald-500 rounded-full" />Актуально</span>)}</div><buttononClick={handleManualAnalysis}disabled={isManualAnalyzing} // FIXED: Only disable for THIS lead, not globalclassName="flex items-center gap-2 px-3 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-xs font-semibold transition-all shadow-sm hover:shadow-md disabled:opacity-50 disabled:cursor-not-allowed"title="Обновить анализ ИИ">{isManualAnalyzing ? ( // FIXED: Only check local state<><Loader2 className="w-3.5 h-3.5 animate-spin" /><span>Анализ...</span></>) : (<><RefreshCw className="w-3.5 h-3.5" /><span>Обновить</span></>)}</button></div>{/* Подсказка */}{!isManualAnalyzing && (<p className="text-xs text-slate-500">Нажмите "Обновить" для получения свежего анализа</p>)}{/* Индикатор анализа */}{isManualAnalyzing && (<div className="mt-3 flex items-center gap-2 px-3 py-2 bg-indigo-50 border border-indigo-200 rounded-lg"><Loader2 className="w-4 h-4 text-indigo-600 animate-spin" /><span className="text-xs text-indigo-700 font-medium">ИИ анализирует диалог...</span></div>)}</div><div className="flex flex-col items-center">{/* Score Header with Donut Chart - FIXED SVG VIEWBOX */}<div className="relative w-48 h-48 mb-6">{/* Фоновый градиент с анимацией */}<div className={cn("absolute inset-0 rounded-full opacity-30 blur-2xl animate-pulse",scoreColors.bg)} />{/* Внешнее кольцо с тенью */}<div className={cn("absolute inset-3 rounded-full shadow-2xl",scoreColors.glow)} />{/* PERFECTLY ALIGNED: viewBox matches w-48 (192px) */}<svg className="w-48 h-48 transform -rotate-90 relative z-10" viewBox="0 0 192 192">{/* Фоновый круг */}<circlecx="96"cy="96"r={radius}stroke="#e5e7eb"strokeWidth={strokeWidth}fill="none"/>{/* Прогресс */}<circlecx="96"cy="96"r={radius}className={scoreColors.stroke}strokeWidth={strokeWidth}fill="none"strokeDasharray={circumference}strokeDashoffset={strokeDashoffset}strokeLinecap="round"style={{filter: 'drop-shadow(0 4px 6px rgba(0,0,0,0.2))',transition: 'stroke-dashoffset 0.8s cubic-bezier(0.4, 0, 0.2, 1)'}}/></svg>{/* Центральный контент - БЕЗ перекрытия */}<div className="absolute inset-0 flex flex-col items-center justify-center pointer-events-none"><div className="flex flex-col items-center gap-2"><span className={cn("text-7xl font-black tracking-tighter leading-none",scoreColors.text)}>{scorePercentage}</span><div className="flex flex-col items-center gap-1"><span className="text-[10px] text-slate-500 font-bold uppercase tracking-widest">Вероятность</span>{/* Статус лида */}<div className={cn("px-3 py-1 rounded-full text-xs font-bold shadow-sm",scoreColors.bg,scoreColors.text)}>{scoreColors.label}</div></div></div></div></div><h3 className="text-xl font-bold text-slate-900 mb-1">{lead.name || 'Без имени'}</h3>{/* Psychotype Badge - Улучшенный */}<div className="flex items-center gap-2 mt-2"><span className={cn("inline-flex items-center px-3 py-1.5 text-sm font-bold rounded-full border-2 shadow-sm",psychotypeData.color)}>{psychotypeData.label}</span></div></div>{/* BANT Grid - Улучшенный дизайн с градиентами */}<div><h3 className="font-bold text-slate-700 mb-4 text-sm uppercase tracking-wider flex items-center gap-2"><Target className="w-4 h-4 text-indigo-600" />Квалификация BANT</h3><div className="grid grid-cols-2 gap-3">{/* БЮДЖЕТ */}<div className="bg-gradient-to-br from-white to-emerald-50 rounded-xl p-4 border-2 border-emerald-100 shadow-sm hover:shadow-md transition-all"><div className="flex items-center gap-2 mb-2"><div className="w-8 h-8 rounded-lg bg-emerald-100 flex items-center justify-center"><DollarSign className="w-4 h-4 text-emerald-700" /></div><p className="text-xs font-bold text-emerald-700 uppercase tracking-wide">Бюджет</p></div><p className={cn("text-sm font-bold mt-2",golden11.budget === 'Не определен' ? 'text-slate-400' : 'text-slate-900')}>{golden11.budget === 'Не определен' ? '—' : golden11.budget}</p></div>{/* ЛПР */}<div className="bg-gradient-to-br from-white to-blue-50 rounded-xl p-4 border-2 border-blue-100 shadow-sm hover:shadow-md transition-all"><div className="flex items-center gap-2 mb-2"><div className="w-8 h-8 rounded-lg bg-blue-100 flex items-center justify-center"><UserIcon className="w-4 h-4 text-blue-700" /></div><p className="text-xs font-bold text-blue-700 uppercase tracking-wide">ЛПР</p></div><p className={cn("text-sm font-bold mt-2",golden11.authority === 'Неизвестно' ? 'text-slate-400' : 'text-slate-900')}>{golden11.authority === 'Неизвестно' ? '—' : golden11.authority}</p></div>{/* СРОКИ */}<div className="bg-gradient-to-br from-white to-indigo-50 rounded-xl p-4 border-2 border-indigo-100 shadow-sm hover:shadow-md transition-all"><div className="flex items-center gap-2 mb-2"><div className="w-8 h-8 rounded-lg bg-indigo-100 flex items-center justify-center"><Clock className="w-4 h-4 text-indigo-700" /></div><p className="text-xs font-bold text-indigo-700 uppercase tracking-wide">Сроки</p></div><p className={cn("text-sm font-bold mt-2",golden11.timeline === 'Не указаны' ? 'text-slate-400' : 'text-slate-900')}>{golden11.timeline === 'Не указаны' ? '—' : golden11.timeline}</p></div>{/* ЦЕЛЬ */}<div className="bg-gradient-to-br from-white to-orange-50 rounded-xl p-4 border-2 border-orange-100 shadow-sm hover:shadow-md transition-all"><div className="flex items-center gap-2 mb-2"><div className="w-8 h-8 rounded-lg bg-orange-100 flex items-center justify-center"><Zap className="w-4 h-4 text-orange-700" /></div><p className="text-xs font-bold text-orange-700 uppercase tracking-wide">Цель</p></div><p className={cn("text-sm font-bold mt-2",golden11.intent === 'Не определено' ? 'text-slate-400' : 'text-slate-900')}>{golden11.intent === 'Не определено' ? '—' : golden11.intent}</p></div></div></div>{/* Психология - Премиальный дизайн */}<div><h3 className="font-bold text-slate-700 mb-4 text-sm uppercase tracking-wider flex items-center gap-2"><Brain className="w-4 h-4 text-purple-600" />Психология клиента</h3>{/* Боли - Красный акцент */}{golden11.pain_points.length > 0 ? (<div className="bg-gradient-to-br from-red-50 to-orange-50 rounded-xl p-4 mb-3 border-2 border-red-100 shadow-sm"><div className="flex items-center gap-2 mb-3"><div className="w-8 h-8 rounded-lg bg-red-100 flex items-center justify-center"><AlertCircle className="w-4 h-4 text-red-700" /></div><p className="text-xs font-bold text-red-700 uppercase tracking-wide">Болевые точки</p></div><ul className="space-y-2">{golden11.pain_points.map((pain, i) => (<li key={i} className="flex items-start gap-3 text-sm text-slate-800"><span className="flex-shrink-0 w-5 h-5 rounded-full bg-red-200 text-red-700 flex items-center justify-center text-xs font-bold mt-0.5">{i + 1}</span><span className="leading-relaxed">{pain}</span></li>))}</ul></div>) : (<div className="bg-gradient-to-br from-slate-50 to-slate-100 rounded-xl p-4 mb-3 border-2 border-slate-200"><div className="flex items-center gap-2 mb-2"><div className="w-8 h-8 rounded-lg bg-slate-200 flex items-center justify-center"><AlertCircle className="w-4 h-4 text-slate-400" /></div><p className="text-xs font-bold text-slate-500 uppercase tracking-wide">Болевые точки</p></div><p className="text-sm text-slate-400 italic">Не выявлено</p></div>)}{/* Возражения - Жёлтый акцент */}{golden11.objections.length > 0 ? (<div className="bg-gradient-to-br from-amber-50 to-yellow-50 rounded-xl p-4 border-2 border-amber-100 shadow-sm"><div className="flex items-center gap-2 mb-3"><div className="w-8 h-8 rounded-lg bg-amber-100 flex items-center justify-center"><Shield className="w-4 h-4 text-amber-700" /></div><p className="text-xs font-bold text-amber-700 uppercase tracking-wide">Возражения</p></div><ul className="space-y-2">{golden11.objections.map((objection, i) => (<li key={i} className="flex items-start gap-3 text-sm text-slate-800"><span className="flex-shrink-0 w-5 h-5 rounded-full bg-amber-200 text-amber-700 flex items-center justify-center text-xs font-bold mt-0.5">{i + 1}</span><span className="leading-relaxed">{objection}</span></li>))}</ul></div>) : (<div className="bg-gradient-to-br from-slate-50 to-slate-100 rounded-xl p-4 border-2 border-slate-200"><div className="flex items-center gap-2 mb-2"><div className="w-8 h-8 rounded-lg bg-slate-200 flex items-center justify-center"><Shield className="w-4 h-4 text-slate-400" /></div><p className="text-xs font-bold text-slate-500 uppercase tracking-wide">Возражения</p></div><p className="text-sm text-slate-400 italic">Не выявлено</p></div>)}</div>{/* Psychology Section - Removed per requirements */}{/* Pain points and hidden signals moved to draft reply context */}{/* Стратегия - Премиальный дизайн */}<div><h3 className="font-bold text-slate-700 mb-4 text-sm uppercase tracking-wider flex items-center gap-2"><Lightbulb className="w-4 h-4 text-amber-600" />Стратегия продаж</h3>{/* Скрытые сигналы */}{golden11.hidden_signals ? (<div className="bg-gradient-to-br from-blue-50 to-indigo-50 rounded-xl p-5 mb-3 border-2 border-blue-200 shadow-md"><div className="flex items-start gap-3 mb-3"><div className="w-9 h-9 rounded-lg bg-blue-100 flex items-center justify-center flex-shrink-0"><Lightbulb className="w-5 h-5 text-blue-700" /></div><div className="flex-1"><span className="text-sm font-bold text-blue-900 uppercase tracking-wide block mb-2">Скрытые сигналы</span><p className="text-sm text-blue-900 leading-relaxed">{golden11.hidden_signals}</p></div></div></div>) : (<div className="bg-gradient-to-br from-slate-50 to-slate-100 rounded-xl p-5 mb-3 border-2 border-slate-200"><div className="flex items-start gap-3"><div className="w-9 h-9 rounded-lg bg-slate-200 flex items-center justify-center flex-shrink-0"><Lightbulb className="w-5 h-5 text-slate-400" /></div><div className="flex-1"><span className="text-sm font-bold text-slate-500 uppercase tracking-wide block mb-2">Скрытые сигналы</span><p className="text-sm text-slate-400 italic">Нет данных для анализа</p></div></div></div>)}{/* Рекомендация */}{golden11.recommendation ? (<div className="bg-gradient-to-br from-emerald-50 to-green-50 rounded-xl p-5 mb-3 border-2 border-emerald-200 shadow-md"><div className="flex items-start gap-3 mb-3"><div className="w-9 h-9 rounded-lg bg-emerald-100 flex items-center justify-center flex-shrink-0"><CheckCircle2 className="w-5 h-5 text-emerald-700" /></div><div className="flex-1"><span className="text-sm font-bold text-emerald-900 uppercase tracking-wide block mb-2">Рекомендация</span><p className="text-sm text-emerald-900 leading-relaxed font-medium">{golden11.recommendation}</p></div></div></div>) : (<div className="bg-gradient-to-br from-slate-50 to-slate-100 rounded-xl p-5 mb-3 border-2 border-slate-200"><div className="flex items-start gap-3"><div className="w-9 h-9 rounded-lg bg-slate-200 flex items-center justify-center flex-shrink-0"><CheckCircle2 className="w-5 h-5 text-slate-400" /></div><div className="flex-1"><span className="text-sm font-bold text-slate-500 uppercase tracking-wide block mb-2">Рекомендация</span><p className="text-sm text-slate-400 italic">Нужен анализ диалога</p></div></div></div>)}{/* Черновик ответа - Премиальный дизайн */}{golden11.draft_reply ? (<div className="bg-gradient-to-br from-indigo-50 to-purple-50 rounded-xl p-5 border-2 border-indigo-200 shadow-md"><div className="flex items-start gap-3 mb-4"><div className="w-9 h-9 rounded-lg bg-indigo-100 flex items-center justify-center flex-shrink-0"><Phone className="w-5 h-5 text-indigo-700" /></div><div className="flex-1"><span className="text-sm font-bold text-indigo-900 uppercase tracking-wide block mb-3">Черновик ответа</span><div className="bg-white/80 backdrop-blur-sm rounded-lg p-4 border border-indigo-100"><p className="text-sm text-slate-800 leading-relaxed">{golden11.draft_reply}</p></div></div></div><buttonclassName="w-full px-4 py-3 bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 text-white rounded-lg transition-all duration-200 font-semibold text-sm flex items-center justify-center gap-2 shadow-md hover:shadow-lg"onClick={() => {if (golden11.draft_reply) {navigator.clipboard.writeText(golden11.draft_reply)// Визуальная обратная связьconst button = document.activeElement as HTMLButtonElementconst originalText = button.innerHTMLbutton.innerHTML = '<span class="flex items-center gap-2">Скопировано!</span>'button.classList.add('bg-emerald-600')setTimeout(() => {button.innerHTML = originalTextbutton.classList.remove('bg-emerald-600')}, 2000)}}}><svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" /></svg>Скопировать текст</button></div>) : (<div className="bg-gradient-to-br from-slate-50 to-slate-100 rounded-xl p-5 border-2 border-slate-200"><div className="flex items-start gap-3"><div className="w-9 h-9 rounded-lg bg-slate-200 flex items-center justify-center flex-shrink-0"><Phone className="w-5 h-5 text-slate-400" /></div><div className="flex-1"><span className="text-sm font-bold text-slate-500 uppercase tracking-wide block mb-2">Черновик ответа</span><p className="text-sm text-slate-400 italic">Будет сгенерирован после анализа</p></div></div></div>)}</div>{/* Bottom Action - Removed per requirements */}{/* Takeover button integrated into header toggle */}</div></div>)}2 unmodified lines345678910111213147 unmodified lines2223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462 unmodified linesimport { useState, useEffect } from 'react'import { Lead } from '@/lib/api'import { cn } from '@/lib/utils'import {Brain, TrendingUp, DollarSign, Target, Clock, AlertCircle,Lightbulb, User as UserIcon, CheckCircle2, Phone, Check,Loader2, RefreshCw, Bot, Zap, Database, Shield, MessageSquare,AlertTriangle, ThumbsUp, PenTool} from 'lucide-react'import { useToast } from '@/contexts/ToastContext'interface ClientCardProps {7 unmodified linesexport function ClientCard({ lead, onTakeover, isAnalyzing, onRefresh, conversationId, tenantId }: ClientCardProps) {const toast = useToast()const summary = lead.ai_summary_json || {}// Helper to clean valuesconst cleanValue = (value: any, fallback: string): string => {if (!value || typeof value !== 'string') return fallbackconst errorPatterns = ['unknown', 'error', 'failed', 'undefined']return errorPatterns.some(p => value.toLowerCase().includes(p)) ? fallback : value}// Structured Dataconst data = {intent: cleanValue(summary.intent || lead.need, 'Не определено'),budget: cleanValue(summary.budget || lead.budget, 'Не определён'),authority: cleanValue(summary.authority || lead.authority, 'Неизвестно'),timeline: cleanValue(summary.timeline || lead.timeline, 'Не указаны'),pain_points: Array.isArray(summary.pain_points) ? summary.pain_points : [],objections: Array.isArray(summary.objections) ? summary.objections : [],psychotype: cleanValue(summary.psychotype || lead.psychotype, 'unknown'),hidden_signals: summary.hidden_signals,recommendation: summary.recommendation,draft_reply: summary.draft_reply,heat_score: typeof summary.heat_score === 'number' ? summary.heat_score : (lead.heat_score || 0)}// Psychotype Colors & Labelsconst getPsychotypeInfo = (type: string) => {const map: Record<string, { label: string; color: string; bg: string; icon: any }> = {'dominant': { label: 'Доминантный', color: 'text-red-600', bg: 'bg-red-50', icon: Zap },'influential': { label: 'Влияющий', color: 'text-amber-600', bg: 'bg-amber-50', icon: StarIcon },'steady': { label: 'Стабильный', color: 'text-emerald-600', bg: 'bg-emerald-50', icon: Shield },'conscientious': { label: 'Аналитический', color: 'text-blue-600', bg: 'bg-blue-50', icon: Database },'unknown': { label: 'Не определён', color: 'text-slate-500', bg: 'bg-slate-50', icon: UserIcon }}return map[type.toLowerCase()] || map['unknown']}const psychotype = getPsychotypeInfo(data.psychotype)// Score Colorconst getScoreColor = (score: number) => {if (score >= 80) return 'text-red-500'if (score >= 50) return 'text-amber-500'return 'text-blue-500'}return (<div className="h-full flex flex-col bg-white font-['Inter']">{/* Header */}<div className="p-5 border-b border-slate-100 flex items-center justify-between bg-white sticky top-0 z-10"><div className="flex items-center gap-3"><div className="w-10 h-10 rounded-xl bg-indigo-50 flex items-center justify-center text-indigo-600"><Brain className="w-5 h-5" /></div><div><h2 className="font-bold text-slate-900 text-sm">AI Анализ</h2><p className="text-xs text-slate-500">Инсайт по клиенту</p></div></div>{/* Score Ring */}<div className="relative w-12 h-12 flex items-center justify-center"><svg className="w-full h-full transform -rotate-90"><circle cx="24" cy="24" r="20" stroke="#f1f5f9" strokeWidth="4" fill="none" /><circlecx="24" cy="24" r="20"stroke="currentColor"strokeWidth="4"fill="none"strokeDasharray={126}strokeDashoffset={126 - (data.heat_score / 100) * 126}className={cn("transition-all duration-1000", getScoreColor(data.heat_score))}strokeLinecap="round"/></svg><span className={cn("absolute text-xs font-bold", getScoreColor(data.heat_score))}>{data.heat_score}</span></div></div>{/* Content */}<div className="flex-1 overflow-y-auto p-5 space-y-6 scrollbar-thin scrollbar-thumb-slate-200">{/* Key Metrics Grid */}<div className="grid grid-cols-2 gap-3"><div className="p-3 bg-slate-50 rounded-xl border border-slate-100"><div className="flex items-center gap-2 mb-1"><Target className="w-3.5 h-3.5 text-slate-400" /><span className="text-[10px] font-semibold text-slate-500 uppercase tracking-wide">Намерение</span></div><p className="text-xs font-medium text-slate-900 line-clamp-2">{data.intent}</p></div><div className="p-3 bg-slate-50 rounded-xl border border-slate-100"><div className="flex items-center gap-2 mb-1"><DollarSign className="w-3.5 h-3.5 text-slate-400" /><span className="text-[10px] font-semibold text-slate-500 uppercase tracking-wide">Бюджет</span></div><p className="text-xs font-medium text-slate-900">{data.budget}</p></div><div className="p-3 bg-slate-50 rounded-xl border border-slate-100"><div className="flex items-center gap-2 mb-1"><UserIcon className="w-3.5 h-3.5 text-slate-400" /><span className="text-[10px] font-semibold text-slate-500 uppercase tracking-wide">ЛПР</span></div><p className="text-xs font-medium text-slate-900">{data.authority}</p></div><div className="p-3 bg-slate-50 rounded-xl border border-slate-100"><div className="flex items-center gap-2 mb-1"><Clock className="w-3.5 h-3.5 text-slate-400" /><span className="text-[10px] font-semibold text-slate-500 uppercase tracking-wide">Сроки</span></div><p className="text-xs font-medium text-slate-900">{data.timeline}</p></div></div>{/* Psychotype */}<div className={cn("p-4 rounded-xl border flex items-center gap-4", psychotype.bg, psychotype.color.replace('text-', 'border-').replace('600', '200'))}><div className={cn("w-10 h-10 rounded-full flex items-center justify-center bg-white shadow-sm", psychotype.color)}><psychotype.icon className="w-5 h-5" /></div><div><span className="text-[10px] font-bold uppercase opacity-70">Психотип</span><p className="font-bold text-sm">{psychotype.label}</p></div></div>{/* Pain Points & Objections */}<div className="space-y-4">{data.pain_points.length > 0 && (<div><h3 className="text-xs font-bold text-slate-900 mb-2 flex items-center gap-2"><AlertCircle className="w-3.5 h-3.5 text-red-500" />Боли клиента</h3><div className="flex flex-wrap gap-2">{data.pain_points.map((point: string, i: number) => (<span key={i} className="px-2 py-1 bg-red-50 text-red-700 text-[10px] font-medium rounded-md border border-red-100">{point}</span>))}</div></div>)}{data.objections.length > 0 && (<div><h3 className="text-xs font-bold text-slate-900 mb-2 flex items-center gap-2"><AlertTriangle className="w-3.5 h-3.5 text-amber-500" />Возражения</h3><div className="flex flex-wrap gap-2">{data.objections.map((obj: string, i: number) => (<span key={i} className="px-2 py-1 bg-amber-50 text-amber-700 text-[10px] font-medium rounded-md border border-amber-100">{obj}</span>))}</div></div>)}</div>{/* Strategy Section */}<div className="space-y-3 pt-2 border-t border-slate-100">{data.hidden_signals && (<div className="p-3 bg-indigo-50/50 rounded-xl border border-indigo-100"><h4 className="text-[10px] font-bold text-indigo-600 uppercase mb-1 flex items-center gap-1"><MessageSquare className="w-3 h-3" />Скрытые сигналы</h4><p className="text-xs text-slate-700 leading-relaxed">{data.hidden_signals}</p></div>)}{data.recommendation && (<div className="p-3 bg-emerald-50/50 rounded-xl border border-emerald-100"><h4 className="text-[10px] font-bold text-emerald-600 uppercase mb-1 flex items-center gap-1"><ThumbsUp className="w-3 h-3" />Рекомендация</h4><p className="text-xs text-slate-700 leading-relaxed">{data.recommendation}</p></div>)}</div>{/* Actions */}<div className="pt-4 mt-auto"><buttononClick={onTakeover}className="w-full py-2.5 bg-white border border-slate-200 text-slate-700 text-xs font-bold rounded-xl hover:bg-slate-50 hover:text-slate-900 transition-colors shadow-sm flex items-center justify-center gap-2"><UserIcon className="w-3.5 h-3.5" />Взять диалог на себя</button></div></div></div>)}// Helper icon for Influential typefunction StarIcon(props: any) {return (<svg{...props}xmlns="http://www.w3.org/2000/svg"width="24"height="24"viewBox="0 0 24 24"fill="none"stroke="currentColor"strokeWidth="2"strokeLinecap="round"strokeLinejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" /></svg>)}
frontend/app/admin/page.tsx+7-7
frontend/app/chats/page.tsx+90-93
frontend/app/dashboard/page.tsx+1-1
frontend/app/partner/page.tsx+6-6
frontend/app/settings/brain/page_advanced.tsx+15-17
frontend/app/settings/brain/page_old.tsx+4-4
frontend/app/settings/partner/page.tsx+2-2
frontend/app/settings/team/page.tsx+4-4
frontend/components/ChatWindow.tsx+234-408
frontend/components/ClientCard.tsx+167-645