Spaces:
Running

axeronis commited on
Commit
db2dc5e
·
1 Parent(s): a5f1f5e

feat: voice cancel button, delete messages API, leads list mobile fixes

Browse files
backend/app/api/chats.py CHANGED
@@ -702,3 +702,64 @@ async def generate_ai_reply(
702
  status_code=500,
703
  detail=f"AI generation failed: {str(e)}"
704
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
702
  status_code=500,
703
  detail=f"AI generation failed: {str(e)}"
704
  )
705
+
706
+
707
+ @router.delete("/messages/{message_id}", status_code=status.HTTP_200_OK)
708
+ async def delete_message(
709
+ message_id: UUID,
710
+ session: AsyncSession = Depends(get_session),
711
+ current_user: User = Depends(get_current_user)
712
+ ):
713
+ """
714
+ Delete a message from chat.
715
+
716
+ Only allows deletion of messages with sender_type='human' (manager's own messages).
717
+ AI and user messages cannot be deleted.
718
+ """
719
+
720
+ # 1. Get tenant from user
721
+ tenant = await session.get(Tenant, current_user.tenant_id)
722
+ if not tenant:
723
+ raise HTTPException(
724
+ status_code=status.HTTP_404_NOT_FOUND,
725
+ detail="Tenant not found"
726
+ )
727
+
728
+ # 2. Find message
729
+ message = await session.get(Message, message_id)
730
+ if not message:
731
+ raise HTTPException(
732
+ status_code=status.HTTP_404_NOT_FOUND,
733
+ detail="Message not found"
734
+ )
735
+
736
+ # 3. Check message belongs to tenant
737
+ if message.tenant_id != tenant.id:
738
+ raise HTTPException(
739
+ status_code=status.HTTP_403_FORBIDDEN,
740
+ detail="Not authorized to delete this message"
741
+ )
742
+
743
+ # 4. Only allow deletion of human messages (manager's own messages)
744
+ if message.sender_type != "human":
745
+ raise HTTPException(
746
+ status_code=status.HTTP_400_BAD_REQUEST,
747
+ detail="Only your own messages can be deleted"
748
+ )
749
+
750
+ # 5. Delete message
751
+ await session.delete(message)
752
+ await session.commit()
753
+
754
+ logger.info(
755
+ "🗑️ Message deleted",
756
+ message_id=str(message_id),
757
+ user_email=current_user.email,
758
+ tenant_id=str(tenant.id)
759
+ )
760
+
761
+ return {
762
+ "success": True,
763
+ "message_id": str(message_id),
764
+ "deleted": True
765
+ }
frontend/components/ChatWindow.tsx CHANGED
@@ -191,6 +191,38 @@ export function ChatWindow({
191
  }
192
  }
193
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
  const handleSendMessage = async (e: React.FormEvent, file?: File | null, audioBlob?: Blob | null) => {
195
  e.preventDefault()
196
 
@@ -288,6 +320,7 @@ export function ChatWindow({
288
  isSequence={!!isSequence}
289
  showDate={showDate}
290
  dateLabel={getDateLabel(msg.created_at)}
 
291
  />
292
  )
293
  })}
 
191
  }
192
  }
193
 
194
+ const handleDeleteMessage = async (messageId: string) => {
195
+ if (!confirm('Удалить сообщение?')) return
196
+
197
+ try {
198
+ const token = localStorage.getItem('token')
199
+ if (!token) throw new Error('Не авторизован')
200
+
201
+ const response = await fetch(
202
+ `${process.env.NEXT_PUBLIC_API_URL}/api/v1/chats/messages/${messageId}`,
203
+ {
204
+ method: 'DELETE',
205
+ headers: { 'Authorization': `Bearer ${token}` }
206
+ }
207
+ )
208
+
209
+ if (!response.ok) {
210
+ const err = await response.json().catch(() => ({}))
211
+ throw new Error(err.detail || 'Failed to delete')
212
+ }
213
+
214
+ // Remove from local state
215
+ setOptimisticMessages(prev => prev.filter(m => m.id !== messageId))
216
+ setRealtimeMessages(prev => prev.filter(m => m.id !== messageId))
217
+
218
+ // Refresh to get updated list
219
+ if (onRefresh) onRefresh()
220
+ } catch (error: any) {
221
+ console.error('Error deleting message:', error)
222
+ alert(error.message || 'Ошибка удаления сообщения')
223
+ }
224
+ }
225
+
226
  const handleSendMessage = async (e: React.FormEvent, file?: File | null, audioBlob?: Blob | null) => {
227
  e.preventDefault()
228
 
 
320
  isSequence={!!isSequence}
321
  showDate={showDate}
322
  dateLabel={getDateLabel(msg.created_at)}
323
+ onDelete={handleDeleteMessage}
324
  />
325
  )
326
  })}
frontend/components/ChatWindow/MessageBubble.tsx CHANGED
@@ -1,7 +1,7 @@
1
  'use client'
2
 
3
  import { cn, formatDate } from '@/lib/utils'
4
- import { Bot, User, FileText, Download, Play, Pause } from 'lucide-react'
5
  import { motion } from 'framer-motion'
6
  import type { Message } from '@/types'
7
  import { useState, useRef } from 'react'
@@ -13,6 +13,7 @@ interface MessageBubbleProps {
13
  isSequence: boolean
14
  showDate: boolean
15
  dateLabel: string
 
16
  }
17
 
18
  /**
@@ -156,6 +157,7 @@ export function MessageBubble({
156
  isSequence,
157
  showDate,
158
  dateLabel,
 
159
  }: MessageBubbleProps) {
160
  const hasMedia = !!message.media_url
161
  const hasText = !!message.content?.trim()
@@ -212,12 +214,24 @@ export function MessageBubble({
212
  <MediaContent message={message} isMe={isMe} />
213
  </div>
214
  {!isSequence && (
215
- <span className={cn(
216
- "text-[10px] text-slate-400 px-1 flex items-center gap-1",
217
- isMe ? "justify-end text-right" : "justify-start text-left"
218
  )}>
219
- {formatDate(message.created_at)}
220
- </span>
 
 
 
 
 
 
 
 
 
 
 
 
221
  )}
222
  </div>
223
  </div>
 
1
  'use client'
2
 
3
  import { cn, formatDate } from '@/lib/utils'
4
+ import { Bot, User, FileText, Download, Play, Pause, Trash2 } from 'lucide-react'
5
  import { motion } from 'framer-motion'
6
  import type { Message } from '@/types'
7
  import { useState, useRef } from 'react'
 
13
  isSequence: boolean
14
  showDate: boolean
15
  dateLabel: string
16
+ onDelete?: (messageId: string) => void
17
  }
18
 
19
  /**
 
157
  isSequence,
158
  showDate,
159
  dateLabel,
160
+ onDelete,
161
  }: MessageBubbleProps) {
162
  const hasMedia = !!message.media_url
163
  const hasText = !!message.content?.trim()
 
214
  <MediaContent message={message} isMe={isMe} />
215
  </div>
216
  {!isSequence && (
217
+ <div className={cn(
218
+ "flex items-center gap-1 px-1",
219
+ isMe ? "justify-end" : "justify-start"
220
  )}>
221
+ <span className="text-[10px] text-slate-400">
222
+ {formatDate(message.created_at)}
223
+ </span>
224
+ {/* Delete button - only for own non-AI messages */}
225
+ {isMe && !isAI && onDelete && (
226
+ <button
227
+ onClick={() => onDelete(message.id)}
228
+ className="opacity-0 group-hover:opacity-100 p-1 text-slate-500 hover:text-red-400 rounded transition-all"
229
+ title="Удалить сообщение"
230
+ >
231
+ <Trash2 className="w-3 h-3" />
232
+ </button>
233
+ )}
234
+ </div>
235
  )}
236
  </div>
237
  </div>
frontend/components/ChatWindow/MessageInput.tsx CHANGED
@@ -22,7 +22,9 @@ export function MessageInput({
22
  const fileInputRef = useRef<HTMLInputElement>(null)
23
  const [selectedFile, setSelectedFile] = useState<File | null>(null)
24
  const [isRecording, setIsRecording] = useState(false)
 
25
  const mediaRecorderRef = useRef<MediaRecorder | null>(null)
 
26
  const chunksRef = useRef<Blob[]>([])
27
 
28
  const handleKeyDown = (e: React.KeyboardEvent) => {
@@ -51,9 +53,11 @@ export function MessageInput({
51
  const startRecording = async () => {
52
  try {
53
  const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
 
54
  const mediaRecorder = new MediaRecorder(stream)
55
  mediaRecorderRef.current = mediaRecorder
56
  chunksRef.current = []
 
57
 
58
  mediaRecorder.ondataavailable = (e) => {
59
  if (e.data.size > 0) {
@@ -62,9 +66,14 @@ export function MessageInput({
62
  }
63
 
64
  mediaRecorder.onstop = () => {
65
- const blob = new Blob(chunksRef.current, { type: 'audio/webm' })
66
- onSubmit({ preventDefault: () => { } } as React.FormEvent, null, blob)
67
- stream.getTracks().forEach(track => track.stop())
 
 
 
 
 
68
  }
69
 
70
  mediaRecorder.start()
@@ -77,6 +86,16 @@ export function MessageInput({
77
 
78
  const stopRecording = () => {
79
  if (mediaRecorderRef.current && isRecording) {
 
 
 
 
 
 
 
 
 
 
80
  mediaRecorderRef.current.stop()
81
  setIsRecording(false)
82
  }
@@ -98,17 +117,31 @@ export function MessageInput({
98
 
99
  {/* Audio Recording UI */}
100
  {isRecording && (
101
- <div className="absolute inset-0 bg-surface-elevated rounded-2xl border border-red-500/50 flex items-center justify-between px-4 z-10 animate-pulse">
102
  <div className="flex items-center gap-2 text-red-400">
103
  <div className="w-2 h-2 rounded-full bg-red-500 animate-pulse" />
104
- <span className="text-sm font-medium">Запись голосового сообщения...</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  </div>
106
- <button
107
- onClick={stopRecording}
108
- className="p-2 bg-red-500/10 text-red-500 rounded-full hover:bg-red-500/20"
109
- >
110
- <Send className="w-5 h-5" />
111
- </button>
112
  </div>
113
  )}
114
 
 
22
  const fileInputRef = useRef<HTMLInputElement>(null)
23
  const [selectedFile, setSelectedFile] = useState<File | null>(null)
24
  const [isRecording, setIsRecording] = useState(false)
25
+ const [isCancelled, setIsCancelled] = useState(false)
26
  const mediaRecorderRef = useRef<MediaRecorder | null>(null)
27
+ const streamRef = useRef<MediaStream | null>(null)
28
  const chunksRef = useRef<Blob[]>([])
29
 
30
  const handleKeyDown = (e: React.KeyboardEvent) => {
 
53
  const startRecording = async () => {
54
  try {
55
  const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
56
+ streamRef.current = stream
57
  const mediaRecorder = new MediaRecorder(stream)
58
  mediaRecorderRef.current = mediaRecorder
59
  chunksRef.current = []
60
+ setIsCancelled(false)
61
 
62
  mediaRecorder.ondataavailable = (e) => {
63
  if (e.data.size > 0) {
 
66
  }
67
 
68
  mediaRecorder.onstop = () => {
69
+ // Only send if not cancelled
70
+ if (!isCancelled && chunksRef.current.length > 0) {
71
+ const blob = new Blob(chunksRef.current, { type: 'audio/webm' })
72
+ onSubmit({ preventDefault: () => { } } as React.FormEvent, null, blob)
73
+ }
74
+ // Cleanup stream
75
+ streamRef.current?.getTracks().forEach(track => track.stop())
76
+ streamRef.current = null
77
  }
78
 
79
  mediaRecorder.start()
 
86
 
87
  const stopRecording = () => {
88
  if (mediaRecorderRef.current && isRecording) {
89
+ setIsCancelled(false)
90
+ mediaRecorderRef.current.stop()
91
+ setIsRecording(false)
92
+ }
93
+ }
94
+
95
+ const cancelRecording = () => {
96
+ if (mediaRecorderRef.current && isRecording) {
97
+ setIsCancelled(true)
98
+ chunksRef.current = [] // Clear chunks
99
  mediaRecorderRef.current.stop()
100
  setIsRecording(false)
101
  }
 
117
 
118
  {/* Audio Recording UI */}
119
  {isRecording && (
120
+ <div className="absolute inset-0 bg-surface-elevated rounded-2xl border border-red-500/50 flex items-center justify-between px-4 z-10">
121
  <div className="flex items-center gap-2 text-red-400">
122
  <div className="w-2 h-2 rounded-full bg-red-500 animate-pulse" />
123
+ <span className="text-sm font-medium">Запись...</span>
124
+ </div>
125
+ <div className="flex items-center gap-2">
126
+ {/* Cancel Button */}
127
+ <button
128
+ type="button"
129
+ onClick={cancelRecording}
130
+ className="p-2 bg-slate-500/20 text-slate-400 rounded-full hover:bg-slate-500/30 transition-colors"
131
+ title="Отменить запись"
132
+ >
133
+ <X className="w-5 h-5" />
134
+ </button>
135
+ {/* Send Button */}
136
+ <button
137
+ type="button"
138
+ onClick={stopRecording}
139
+ className="p-2 bg-red-500/20 text-red-500 rounded-full hover:bg-red-500/30 transition-colors"
140
+ title="Отправить голосовое"
141
+ >
142
+ <Send className="w-5 h-5" />
143
+ </button>
144
  </div>
 
 
 
 
 
 
145
  </div>
146
  )}
147
 
frontend/components/LeadsList.tsx CHANGED
@@ -208,8 +208,8 @@ export function LeadsList({
208
  </div>
209
  </div>
210
 
211
- {/* List Content */}
212
- <div className="flex-1 overflow-y-auto scrollbar-thin scrollbar-thumb-white/10 p-2 space-y-1">
213
  {isLoading ? (
214
  // Skeleton Loading
215
  <div className="space-y-2 p-2">
@@ -281,7 +281,7 @@ export function LeadsList({
281
  "p-1.5 rounded-lg transition-all",
282
  isSelected
283
  ? "opacity-100 bg-red-500/20 text-red-400"
284
- : "opacity-0 group-hover:opacity-100 hover:bg-red-500/20 text-red-400"
285
  )}
286
  title="Удалить чат"
287
  >
 
208
  </div>
209
  </div>
210
 
211
+ {/* List Content - with bottom padding for mobile nav */}
212
+ <div className="flex-1 overflow-y-auto scrollbar-thin scrollbar-thumb-white/10 p-2 pb-16 md:pb-2 space-y-1">
213
  {isLoading ? (
214
  // Skeleton Loading
215
  <div className="space-y-2 p-2">
 
281
  "p-1.5 rounded-lg transition-all",
282
  isSelected
283
  ? "opacity-100 bg-red-500/20 text-red-400"
284
+ : "opacity-100 md:opacity-0 md:group-hover:opacity-100 hover:bg-red-500/20 text-red-400"
285
  )}
286
  title="Удалить чат"
287
  >