Spaces:
Sleeping

axeronis commited on
Commit
3bafddd
·
1 Parent(s): 6661747

feat: File upload to Supabase Storage

Browse files
backend/app/api/upload.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File Upload API - Upload files to Supabase Storage
3
+ """
4
+ from fastapi import APIRouter, Depends, UploadFile, File, HTTPException
5
+ from uuid import UUID
6
+ import time
7
+ import logging
8
+
9
+ from app.core.supabase import supabase_client
10
+ from app.api.deps import get_current_user
11
+ from app.models.user import User
12
+
13
+ logger = logging.getLogger(__name__)
14
+ router = APIRouter()
15
+
16
+
17
+ @router.post("/file")
18
+ async def upload_file(
19
+ file: UploadFile = File(...),
20
+ current_user: User = Depends(get_current_user)
21
+ ):
22
+ """
23
+ Upload a file to Supabase Storage.
24
+ Returns public URL of uploaded file.
25
+ """
26
+ if not supabase_client:
27
+ raise HTTPException(status_code=500, detail="Storage not configured")
28
+
29
+ # Validate file
30
+ if not file.filename:
31
+ raise HTTPException(status_code=400, detail="No filename")
32
+
33
+ # Read file content
34
+ content = await file.read()
35
+ if len(content) > 10 * 1024 * 1024: # 10MB limit
36
+ raise HTTPException(status_code=400, detail="File too large (max 10MB)")
37
+
38
+ # Determine bucket based on content type
39
+ content_type = file.content_type or "application/octet-stream"
40
+
41
+ if content_type.startswith("image/"):
42
+ bucket = "media"
43
+ folder = "images"
44
+ elif content_type == "application/pdf":
45
+ bucket = "media"
46
+ folder = "documents"
47
+ elif content_type.startswith("video/"):
48
+ bucket = "media"
49
+ folder = "videos"
50
+ else:
51
+ bucket = "media"
52
+ folder = "files"
53
+
54
+ # Generate unique filename
55
+ timestamp = int(time.time())
56
+ safe_filename = file.filename.replace(" ", "_")
57
+ path = f"{current_user.tenant_id}/{folder}/{timestamp}_{safe_filename}"
58
+
59
+ try:
60
+ # Upload to Supabase Storage
61
+ result = supabase_client.storage.from_(bucket).upload(
62
+ path=path,
63
+ file=content,
64
+ file_options={"content-type": content_type}
65
+ )
66
+
67
+ # Get public URL
68
+ public_url = supabase_client.storage.from_(bucket).get_public_url(path)
69
+
70
+ logger.info(f"✅ File uploaded: {path} -> {public_url[:60]}...")
71
+
72
+ return {
73
+ "ok": True,
74
+ "url": public_url,
75
+ "filename": file.filename,
76
+ "content_type": content_type,
77
+ "size": len(content)
78
+ }
79
+
80
+ except Exception as e:
81
+ logger.error(f"❌ Upload failed: {e}")
82
+ raise HTTPException(status_code=500, detail=f"Upload failed: {str(e)}")
83
+
84
+
85
+ @router.post("/image")
86
+ async def upload_image(
87
+ file: UploadFile = File(...),
88
+ current_user: User = Depends(get_current_user)
89
+ ):
90
+ """
91
+ Upload an image file. Validates that it's actually an image.
92
+ """
93
+ if not file.content_type or not file.content_type.startswith("image/"):
94
+ raise HTTPException(status_code=400, detail="File must be an image")
95
+
96
+ return await upload_file(file, current_user)
97
+
98
+
99
+ @router.post("/document")
100
+ async def upload_document(
101
+ file: UploadFile = File(...),
102
+ current_user: User = Depends(get_current_user)
103
+ ):
104
+ """
105
+ Upload a document (PDF, DOC, etc).
106
+ """
107
+ allowed_types = [
108
+ "application/pdf",
109
+ "application/msword",
110
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
111
+ ]
112
+
113
+ if file.content_type not in allowed_types:
114
+ raise HTTPException(status_code=400, detail="File must be PDF or DOC")
115
+
116
+ return await upload_file(file, current_user)
backend/app/main.py CHANGED
@@ -7,7 +7,7 @@ from app.core.config import settings
7
  from app.core.database import init_pgvector
8
  from app.core.logging import configure_logging, get_logger
9
  from app.middleware.request_id import RequestIDMiddleware
10
- from app.api import webhook, leads, knowledge, channels, auth, tenants, analytics, chats, playbook, billing, ai_training, crm, admin, team, telegram_webhook, partners, notifications, products, bookings, jobs, system, meta_webhooks, voice, google_calendar, websocket_voice, websocket_chat, oauth, landing, site_settings
11
 
12
  # ... (omitted lines)
13
 
@@ -196,6 +196,7 @@ app.include_router(websocket_chat.router, prefix="/ws/chat", tags=["Chat Stream"
196
  app.include_router(google_calendar.router, prefix="/api/v1/google-calendar", tags=["Google Calendar"])
197
  app.include_router(landing.router, prefix="/api/v1/landing", tags=["Landing Page"])
198
  app.include_router(site_settings.router, prefix="/api/v1", tags=["Site Settings"])
 
199
 
200
 
201
  @app.on_event("startup")
 
7
  from app.core.database import init_pgvector
8
  from app.core.logging import configure_logging, get_logger
9
  from app.middleware.request_id import RequestIDMiddleware
10
+ from app.api import webhook, leads, knowledge, channels, auth, tenants, analytics, chats, playbook, billing, ai_training, crm, admin, team, telegram_webhook, partners, notifications, products, bookings, jobs, system, meta_webhooks, voice, google_calendar, websocket_voice, websocket_chat, oauth, landing, site_settings, upload
11
 
12
  # ... (omitted lines)
13
 
 
196
  app.include_router(google_calendar.router, prefix="/api/v1/google-calendar", tags=["Google Calendar"])
197
  app.include_router(landing.router, prefix="/api/v1/landing", tags=["Landing Page"])
198
  app.include_router(site_settings.router, prefix="/api/v1", tags=["Site Settings"])
199
+ app.include_router(upload.router, prefix="/api/v1/upload", tags=["File Upload"])
200
 
201
 
202
  @app.on_event("startup")
frontend/components/knowledge/KnowledgeFilesManager.tsx CHANGED
@@ -2,7 +2,7 @@
2
 
3
  import { useState } from 'react'
4
  import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
5
- import { knowledgeApi } from '@/lib/api'
6
  import { useToast } from '@/contexts/ToastContext'
7
  import { Plus, Trash2, Edit2, FileText, Image as ImageIcon, Video, Link as LinkIcon, Loader2, Save, X, Tag, Calendar, GitBranch, Sparkles, Upload } from 'lucide-react'
8
  import { motion, AnimatePresence } from 'framer-motion'
@@ -47,6 +47,7 @@ export function KnowledgeFilesManager() {
47
  const queryClient = useQueryClient()
48
  const [editingFile, setEditingFile] = useState<KnowledgeFile | null>(null)
49
  const [showForm, setShowForm] = useState(false)
 
50
  const [formData, setFormData] = useState({
51
  name: '',
52
  file_type: 'document',
@@ -294,17 +295,31 @@ export function KnowledgeFilesManager() {
294
  <label className="text-sm font-medium text-slate-400 mb-2 block">Документ (PDF)</label>
295
 
296
  {/* Upload button */}
297
- <label className="flex items-center justify-center gap-2 p-4 border-2 border-dashed border-white/20 rounded-xl cursor-pointer hover:border-emerald-500/50 hover:bg-emerald-500/5 transition-all mb-3">
298
- <Upload className="w-5 h-5 text-slate-400" />
299
- <span className="text-slate-400">Загрузить PDF</span>
 
 
 
 
300
  <input
301
  type="file"
302
  accept=".pdf,.doc,.docx"
303
  className="hidden"
 
304
  onChange={async (e) => {
305
  const file = e.target.files?.[0]
306
  if (file) {
307
- toast.info('Загрузка файлов скоро будет доступна. Пока используйте URL.')
 
 
 
 
 
 
 
 
 
308
  }
309
  }}
310
  />
@@ -330,17 +345,31 @@ export function KnowledgeFilesManager() {
330
  <label className="text-sm font-medium text-slate-400 mb-2 block">Изображение</label>
331
 
332
  {/* Upload button */}
333
- <label className="flex items-center justify-center gap-2 p-4 border-2 border-dashed border-white/20 rounded-xl cursor-pointer hover:border-emerald-500/50 hover:bg-emerald-500/5 transition-all mb-3">
334
- <Upload className="w-5 h-5 text-slate-400" />
335
- <span className="text-slate-400">Загрузить изображение</span>
 
 
 
 
336
  <input
337
  type="file"
338
  accept="image/*"
339
  className="hidden"
 
340
  onChange={async (e) => {
341
  const file = e.target.files?.[0]
342
  if (file) {
343
- toast.info('Загрузка файлов скоро будет доступна. Пока используйте URL.')
 
 
 
 
 
 
 
 
 
344
  }
345
  }}
346
  />
 
2
 
3
  import { useState } from 'react'
4
  import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
5
+ import { knowledgeApi, uploadApi } from '@/lib/api'
6
  import { useToast } from '@/contexts/ToastContext'
7
  import { Plus, Trash2, Edit2, FileText, Image as ImageIcon, Video, Link as LinkIcon, Loader2, Save, X, Tag, Calendar, GitBranch, Sparkles, Upload } from 'lucide-react'
8
  import { motion, AnimatePresence } from 'framer-motion'
 
47
  const queryClient = useQueryClient()
48
  const [editingFile, setEditingFile] = useState<KnowledgeFile | null>(null)
49
  const [showForm, setShowForm] = useState(false)
50
+ const [uploading, setUploading] = useState(false)
51
  const [formData, setFormData] = useState({
52
  name: '',
53
  file_type: 'document',
 
295
  <label className="text-sm font-medium text-slate-400 mb-2 block">Документ (PDF)</label>
296
 
297
  {/* Upload button */}
298
+ <label className={`flex items-center justify-center gap-2 p-4 border-2 border-dashed rounded-xl cursor-pointer transition-all mb-3 ${uploading ? 'border-emerald-500 bg-emerald-500/10' : 'border-white/20 hover:border-emerald-500/50 hover:bg-emerald-500/5'}`}>
299
+ {uploading ? (
300
+ <Loader2 className="w-5 h-5 text-emerald-400 animate-spin" />
301
+ ) : (
302
+ <Upload className="w-5 h-5 text-slate-400" />
303
+ )}
304
+ <span className="text-slate-400">{uploading ? 'Загрузка...' : 'Загрузить PDF'}</span>
305
  <input
306
  type="file"
307
  accept=".pdf,.doc,.docx"
308
  className="hidden"
309
+ disabled={uploading}
310
  onChange={async (e) => {
311
  const file = e.target.files?.[0]
312
  if (file) {
313
+ try {
314
+ setUploading(true)
315
+ const result = await uploadApi.uploadDocument(file)
316
+ setFormData({ ...formData, file_url: result.url })
317
+ toast.success('Документ загружен!')
318
+ } catch (err) {
319
+ toast.error('Ошибка загрузки')
320
+ } finally {
321
+ setUploading(false)
322
+ }
323
  }
324
  }}
325
  />
 
345
  <label className="text-sm font-medium text-slate-400 mb-2 block">Изображение</label>
346
 
347
  {/* Upload button */}
348
+ <label className={`flex items-center justify-center gap-2 p-4 border-2 border-dashed rounded-xl cursor-pointer transition-all mb-3 ${uploading ? 'border-emerald-500 bg-emerald-500/10' : 'border-white/20 hover:border-emerald-500/50 hover:bg-emerald-500/5'}`}>
349
+ {uploading ? (
350
+ <Loader2 className="w-5 h-5 text-emerald-400 animate-spin" />
351
+ ) : (
352
+ <Upload className="w-5 h-5 text-slate-400" />
353
+ )}
354
+ <span className="text-slate-400">{uploading ? 'Загрузка...' : 'Загрузить изображение'}</span>
355
  <input
356
  type="file"
357
  accept="image/*"
358
  className="hidden"
359
+ disabled={uploading}
360
  onChange={async (e) => {
361
  const file = e.target.files?.[0]
362
  if (file) {
363
+ try {
364
+ setUploading(true)
365
+ const result = await uploadApi.uploadImage(file)
366
+ setFormData({ ...formData, file_url: result.url })
367
+ toast.success('Изображение загружено!')
368
+ } catch (err) {
369
+ toast.error('Ошибка загрузки')
370
+ } finally {
371
+ setUploading(false)
372
+ }
373
  }
374
  }}
375
  />
frontend/components/knowledge/PaymentMethodsManager.tsx CHANGED
@@ -2,7 +2,7 @@
2
 
3
  import { useState } from 'react'
4
  import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
5
- import { knowledgeApi } from '@/lib/api'
6
  import { useToast } from '@/contexts/ToastContext'
7
  import { Plus, Trash2, Edit2, CreditCard, Link as LinkIcon, Image as ImageIcon, Loader2, Save, X, Upload } from 'lucide-react'
8
  import { motion, AnimatePresence } from 'framer-motion'
@@ -36,6 +36,7 @@ export function PaymentMethodsManager() {
36
  const queryClient = useQueryClient()
37
  const [editingMethod, setEditingMethod] = useState<PaymentMethod | null>(null)
38
  const [showForm, setShowForm] = useState(false)
 
39
  const [formData, setFormData] = useState({
40
  name: '',
41
  payment_type: 'requisites',
@@ -274,18 +275,31 @@ export function PaymentMethodsManager() {
274
  <label className="text-sm font-medium text-slate-400 mb-2 block">Изображение (QR-код или фото)</label>
275
 
276
  {/* Upload button */}
277
- <label className="flex items-center justify-center gap-2 p-4 border-2 border-dashed border-white/20 rounded-xl cursor-pointer hover:border-indigo-500/50 hover:bg-indigo-500/5 transition-all mb-3">
278
- <Upload className="w-5 h-5 text-slate-400" />
279
- <span className="text-slate-400">Загрузить изображение</span>
 
 
 
 
280
  <input
281
  type="file"
282
  accept="image/*"
283
  className="hidden"
 
284
  onChange={async (e) => {
285
  const file = e.target.files?.[0]
286
  if (file) {
287
- // For now, show a placeholder - in production would upload to storage
288
- toast.info('Загрузка файлов скоро будет доступна. Пока используйте URL.')
 
 
 
 
 
 
 
 
289
  }
290
  }}
291
  />
 
2
 
3
  import { useState } from 'react'
4
  import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
5
+ import { knowledgeApi, uploadApi } from '@/lib/api'
6
  import { useToast } from '@/contexts/ToastContext'
7
  import { Plus, Trash2, Edit2, CreditCard, Link as LinkIcon, Image as ImageIcon, Loader2, Save, X, Upload } from 'lucide-react'
8
  import { motion, AnimatePresence } from 'framer-motion'
 
36
  const queryClient = useQueryClient()
37
  const [editingMethod, setEditingMethod] = useState<PaymentMethod | null>(null)
38
  const [showForm, setShowForm] = useState(false)
39
+ const [uploading, setUploading] = useState(false)
40
  const [formData, setFormData] = useState({
41
  name: '',
42
  payment_type: 'requisites',
 
275
  <label className="text-sm font-medium text-slate-400 mb-2 block">Изображение (QR-код или фото)</label>
276
 
277
  {/* Upload button */}
278
+ <label className={`flex items-center justify-center gap-2 p-4 border-2 border-dashed rounded-xl cursor-pointer transition-all mb-3 ${uploading ? 'border-indigo-500 bg-indigo-500/10' : 'border-white/20 hover:border-indigo-500/50 hover:bg-indigo-500/5'}`}>
279
+ {uploading ? (
280
+ <Loader2 className="w-5 h-5 text-indigo-400 animate-spin" />
281
+ ) : (
282
+ <Upload className="w-5 h-5 text-slate-400" />
283
+ )}
284
+ <span className="text-slate-400">{uploading ? 'Загрузка...' : 'Загрузить изображение'}</span>
285
  <input
286
  type="file"
287
  accept="image/*"
288
  className="hidden"
289
+ disabled={uploading}
290
  onChange={async (e) => {
291
  const file = e.target.files?.[0]
292
  if (file) {
293
+ try {
294
+ setUploading(true)
295
+ const result = await uploadApi.uploadImage(file)
296
+ setFormData({ ...formData, image_url: result.url })
297
+ toast.success('Изображение загружено!')
298
+ } catch (err) {
299
+ toast.error('Ошибка загрузки')
300
+ } finally {
301
+ setUploading(false)
302
+ }
303
  }
304
  }}
305
  />
frontend/lib/api.ts CHANGED
@@ -587,3 +587,39 @@ export const googleSheetsApi = {
587
  return response.data
588
  }
589
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
587
  return response.data
588
  }
589
  }
590
+
591
+ // Upload API - File uploads to Supabase Storage
592
+ export const uploadApi = {
593
+ // Upload any file
594
+ uploadFile: async (file: File): Promise<{ ok: boolean; url: string; filename: string }> => {
595
+ const formData = new FormData()
596
+ formData.append('file', file)
597
+
598
+ const response = await api.post('/api/v1/upload/file', formData, {
599
+ headers: { 'Content-Type': 'multipart/form-data' }
600
+ })
601
+ return response.data
602
+ },
603
+
604
+ // Upload image specifically
605
+ uploadImage: async (file: File): Promise<{ ok: boolean; url: string; filename: string }> => {
606
+ const formData = new FormData()
607
+ formData.append('file', file)
608
+
609
+ const response = await api.post('/api/v1/upload/image', formData, {
610
+ headers: { 'Content-Type': 'multipart/form-data' }
611
+ })
612
+ return response.data
613
+ },
614
+
615
+ // Upload document (PDF, DOC)
616
+ uploadDocument: async (file: File): Promise<{ ok: boolean; url: string; filename: string }> => {
617
+ const formData = new FormData()
618
+ formData.append('file', file)
619
+
620
+ const response = await api.post('/api/v1/upload/document', formData, {
621
+ headers: { 'Content-Type': 'multipart/form-data' }
622
+ })
623
+ return response.data
624
+ }
625
+ }