Create support.py
Browse files- routes/support.py +112 -0
routes/support.py
ADDED
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import logging
|
3 |
+
import aiohttp
|
4 |
+
from fastapi import APIRouter, HTTPException, Header
|
5 |
+
from pydantic import BaseModel
|
6 |
+
from datetime import datetime
|
7 |
+
|
8 |
+
router = APIRouter()
|
9 |
+
|
10 |
+
# 🔧 Supabase Config
|
11 |
+
SUPABASE_URL = "https://ussxqnifefkgkaumjann.supabase.co"
|
12 |
+
SUPABASE_KEY = os.getenv("SUPA_KEY")
|
13 |
+
SUPABASE_ROLE_KEY = os.getenv("SUPA_SERVICE_KEY")
|
14 |
+
|
15 |
+
if not SUPABASE_KEY or not SUPABASE_ROLE_KEY:
|
16 |
+
raise ValueError("❌ SUPA_KEY or SUPA_SERVICE_KEY not set in environment!")
|
17 |
+
|
18 |
+
SUPABASE_HEADERS = {
|
19 |
+
"apikey": SUPABASE_KEY,
|
20 |
+
"Authorization": f"Bearer {SUPABASE_KEY}",
|
21 |
+
"Content-Type": "application/json"
|
22 |
+
}
|
23 |
+
|
24 |
+
SUPABASE_ROLE_HEADERS = {
|
25 |
+
"apikey": SUPABASE_ROLE_KEY,
|
26 |
+
"Authorization": f"Bearer {SUPABASE_ROLE_KEY}",
|
27 |
+
"Content-Type": "application/json"
|
28 |
+
}
|
29 |
+
|
30 |
+
|
31 |
+
# 🛡️ Função para verificar token de qualquer usuário (sem admin check)
|
32 |
+
async def verify_user_token(user_token: str) -> str:
|
33 |
+
headers = {
|
34 |
+
"Authorization": f"Bearer {user_token}",
|
35 |
+
"apikey": SUPABASE_KEY,
|
36 |
+
"Content-Type": "application/json"
|
37 |
+
}
|
38 |
+
|
39 |
+
async with aiohttp.ClientSession() as session:
|
40 |
+
async with session.get(f"{SUPABASE_URL}/auth/v1/user", headers=headers) as response:
|
41 |
+
if response.status != 200:
|
42 |
+
raise HTTPException(status_code=401, detail="Token inválido ou expirado")
|
43 |
+
|
44 |
+
user_data = await response.json()
|
45 |
+
user_id = user_data.get("id")
|
46 |
+
if not user_id:
|
47 |
+
raise HTTPException(status_code=400, detail="ID do usuário não encontrado")
|
48 |
+
|
49 |
+
return user_id
|
50 |
+
|
51 |
+
|
52 |
+
# 📨 Modelo da requisição
|
53 |
+
class CreateTicketRequest(BaseModel):
|
54 |
+
message: str
|
55 |
+
|
56 |
+
|
57 |
+
@router.post("/ticket/create")
|
58 |
+
async def create_ticket(
|
59 |
+
body: CreateTicketRequest,
|
60 |
+
user_token: str = Header(None, alias="User-key")
|
61 |
+
):
|
62 |
+
try:
|
63 |
+
user_id = await verify_user_token(user_token)
|
64 |
+
created_at = datetime.utcnow().isoformat()
|
65 |
+
|
66 |
+
# 1. Cria o ticket
|
67 |
+
ticket_payload = {
|
68 |
+
"user_id": user_id,
|
69 |
+
"support_id": None,
|
70 |
+
"created_at": created_at
|
71 |
+
}
|
72 |
+
|
73 |
+
async with aiohttp.ClientSession() as session:
|
74 |
+
async with session.post(
|
75 |
+
f"{SUPABASE_URL}/rest/v1/Tickets",
|
76 |
+
headers=SUPABASE_HEADERS,
|
77 |
+
json=ticket_payload
|
78 |
+
) as ticket_resp:
|
79 |
+
|
80 |
+
if ticket_resp.status != 201:
|
81 |
+
error_detail = await ticket_resp.text()
|
82 |
+
raise HTTPException(status_code=500, detail=f"Erro ao criar ticket: {error_detail}")
|
83 |
+
|
84 |
+
ticket_data = await ticket_resp.json()
|
85 |
+
ticket_id = ticket_data[0]["id"]
|
86 |
+
|
87 |
+
# 2. Cria a mensagem inicial
|
88 |
+
message_payload = {
|
89 |
+
"user": user_id,
|
90 |
+
"content": body.message,
|
91 |
+
"created_at": created_at,
|
92 |
+
"ticket_id": ticket_id
|
93 |
+
}
|
94 |
+
|
95 |
+
async with aiohttp.ClientSession() as session:
|
96 |
+
async with session.post(
|
97 |
+
f"{SUPABASE_URL}/rest/v1/messages_tickets",
|
98 |
+
headers=SUPABASE_HEADERS,
|
99 |
+
json=message_payload
|
100 |
+
) as message_resp:
|
101 |
+
|
102 |
+
if message_resp.status != 201:
|
103 |
+
error_detail = await message_resp.text()
|
104 |
+
raise HTTPException(status_code=500, detail=f"Erro ao criar mensagem: {error_detail}")
|
105 |
+
|
106 |
+
return {"success": True, "ticket_id": ticket_id}
|
107 |
+
|
108 |
+
except HTTPException as http_ex:
|
109 |
+
return {"success": False, "detail": http_ex.detail}
|
110 |
+
except Exception as e:
|
111 |
+
logging.error(f"❌ Erro inesperado ao criar ticket: {str(e)}")
|
112 |
+
return {"success": False, "detail": str(e)}
|