|
|
import os |
|
|
import logging |
|
|
import aiohttp |
|
|
from fastapi import APIRouter, HTTPException, Header |
|
|
from pydantic import BaseModel |
|
|
from datetime import datetime |
|
|
|
|
|
router = APIRouter() |
|
|
|
|
|
|
|
|
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" |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
|
|
|
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() |
|
|
|
|
|
|
|
|
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"] |
|
|
|
|
|
|
|
|
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)} |