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