Spaces:
Sleeping
Sleeping
Upload main.py
Browse files46 unmodified lines4748495051525333 unmodified lines878889909192266 unmodified lines3593603613623633643653663671 unmodified line36937037137237337437537637737837938038138238338438538638738838939018 unmodified lines40941041141241341441510 unmodified lines42642742842943043143243343443543643743843919 unmodified lines45946046146246346446525 unmodified lines4914924934944954964978 unmodified lines50650750850951051151234 unmodified lines54754854955055155255314 unmodified lines5685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026032 unmodified lines60660760860961061161262 unmodified lines67567667767867968068144 unmodified lines72672772872973073173299 unmodified lines83283383483583683783840 unmodified lines8798808818828838848858868878888898908916 unmodified lines89889990090190290346 unmodified linesapp.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"])# ------------------------------------------------------------------# Global exception handler to return tracebacks to client (debug)# ------------------------------------------------------------------@app.exception_handler(Exception)async def global_exception_handler(request: Request, exc: Exception):33 unmodified linesWHATSAPP_ACCESS_TOKEN = os.environ.get("WHATSAPP_ACCESS_TOKEN")WHATSAPP_PHONE_ID = os.environ.get("WHATSAPP_PHONE_ID")PRODUCTION_HOST = os.environ.get("PRODUCTION_HOST", "https://kevsono-penafort-concierge.hf.space")# ------------------------------------------------------------------# Supabase client266 unmodified lineslogger.error(f"Save conversation error: {e}", exc_info=True)# ------------------------------------------------------------------# Auth endpoints# ------------------------------------------------------------------class AuthRequest(BaseModel):email: strpassword: str1 unmodified lineemail: str@app.post("/auth/register")async def register(auth: AuthRequest):try:resp = get_supabase().auth.sign_up({"email": auth.email,"password": auth.password,})if resp.user:logger.info(f"User registered: {resp.user.id}")return {"user_id": resp.user.id, "message": "Registration successful. Please verify your email if required."}raise HTTPException(status_code=400, detail="Registration failed")except Exception as e:logger.error(f"Registration error: {str(e)}", exc_info=True)raise HTTPException(status_code=400, detail=str(e))@app.post("/auth/login")async def login(auth: AuthRequest):try:resp = get_supabase().auth.sign_in_with_password({"email": auth.email,18 unmodified linestoken = authorization.split(" ")[1]try:get_supabase().auth.sign_out(token)logger.info("User logged out")return {"message": "Logged out"}except Exception as e:logger.error(f"Logout error: {e}", exc_info=True)10 unmodified linesasync def reset_password(req: ResetPasswordRequest):try:get_supabase().auth.reset_password_for_email(req.email)logger.info(f"Password reset email sent to {req.email}")return {"message": "Password reset email sent. Please check your inbox."}except Exception as e:logger.error(f"Reset password error for {req.email}: {e}", exc_info=True)raise HTTPException(status_code=400, detail=str(e))# ------------------------------------------------------------------# Chat endpoint# ------------------------------------------------------------------class ChatRequest(BaseModel):message: str19 unmodified linesraise HTTPException(status_code=500, detail="AI service error")# ------------------------------------------------------------------# Support tickets# ------------------------------------------------------------------class TicketRequest(BaseModel):subject: str25 unmodified lines"message": ticket_req.message,"created_at": datetime.now().isoformat()}).execute()logger.info(f"Ticket created: {ticket_id} for org {org_id}")return {"ticket_id": str(ticket_id), "confirmation": f"✅ Ticket #{str(ticket_id)[:8]} created."}except Exception as e:logger.error(f"Create ticket error: {e}", exc_info=True)8 unmodified linesif status:query = query.eq("status", status)result = query.order("created_at", desc=True).execute()logger.info(f"Fetched {len(result.data)} tickets for org {org_id}")return {"tickets": result.data}except Exception as e:logger.error(f"Get tickets error: {e}", exc_info=True)34 unmodified lines"created_at": datetime.now().isoformat()}).execute()messages = client.table("ticket_messages").select("*").eq("ticket_id", ticket_id).order("created_at", desc=False).execute()logger.info(f"Agent message added to ticket {ticket_id}")return {"messages": messages.data}except HTTPException:raise14 unmodified lines"resolution_notes": req.resolution_notes,"resolved_at": datetime.now().isoformat()}).eq("id", ticket_id).eq("org_id", org_id).eq("user_id", user_id).execute()logger.info(f"Ticket {ticket_id} resolved by user {user_id} in org {org_id}")return {"message": "Ticket resolved"}except Exception as e:logger.error(f"Resolve error: {e}", exc_info=True)raise HTTPException(status_code=500, detail="Failed to resolve ticket")# ------------------------------------------------------------------# Customer context (fixed: target_user_id optional)# ------------------------------------------------------------------@app.get("/support/customer-context")async def customer_context(target_user_id: Optional[str] = None,user_org: Tuple[str, str] = Depends(get_current_org)):# If no target_user_id provided, use the authenticated user's own IDcurrent_user_id, org_id = user_orguser_id = target_user_id if target_user_id else current_user_idclient = get_supabase()try:# Verify target user belongs to same orgmembership = client.table("org_members").select("org_id").eq("user_id", user_id).maybe_single().execute()if not membership or not membership.data or membership.data["org_id"] != org_id:raise HTTPException(status_code=403, detail="Not authorised to view this user")profile = client.table("profiles").select("*").eq("id", user_id).maybe_single().execute()loyalty = Noneif profile and profile.data and profile.data.get("membership_id"):loyalty = client.table("customer_points_summary").select("*").eq("membership_id", profile.data["membership_id"]).maybe_single().execute()return {"profile": profile.data if profile else None, "loyalty": loyalty.data if loyalty else None}except HTTPException:raise2 unmodified linesraise HTTPException(status_code=500, detail="Failed to fetch context")# ------------------------------------------------------------------# Loyalty & Inventory (filtered by org_id)# ------------------------------------------------------------------@app.get("/loyalty/lookup")async def loyalty_lookup(phone: str, user_org: Tuple[str, str] = Depends(get_current_org)):62 unmodified lines"message": req.reason,"created_at": datetime.now().isoformat()}).execute()logger.info(f"Escalation ticket {ticket_id} created for org {org_id}")return {"ticket_id": str(ticket_id)}except Exception as e:logger.error(f"Escalate error: {e}", exc_info=True)44 unmodified linesreturn {"status": "healthy", "timestamp": datetime.now().isoformat()}# ------------------------------------------------------------------# Chat widget JS (served for convenience)# ------------------------------------------------------------------@app.get("/chat-widget.js", response_class=PlainTextResponse)async def widget():99 unmodified lines"""# ------------------------------------------------------------------# WhatsApp webhook# ------------------------------------------------------------------@app.get("/webhook")async def verify_webhook(request: Request):40 unmodified linestry:async with httpx.AsyncClient() as client:await client.post(url, json=payload, headers=headers)logger.info(f"WhatsApp message sent to {to}")except Exception as e:logger.error(f"Failed to send WhatsApp message: {e}", exc_info=True)# ------------------------------------------------------------------# Root# ------------------------------------------------------------------@app.get("/")async def root():return {6 unmodified lines"loyalty": "/loyalty/lookup","inventory": "/inventory/public-list","escalate": "/support/escalate","diagnose": "/api/diagnose"}}46 unmodified lines4748495051525333 unmodified lines87888990919293266 unmodified lines3603613623633643653663673683693703713723731 unmodified line37537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242318 unmodified lines44244344444544644710 unmodified lines45845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551619 unmodified lines53653753853954054154225 unmodified lines5685695705715725738 unmodified lines58258358458558658734 unmodified lines62262362462562662714 unmodified lines6426436446456466476486496506516526536546556566576586596606616626636646656666676682 unmodified lines67167267367467567667762 unmodified lines74074174274374474544 unmodified lines79079179279379479579699 unmodified lines89689789889990090190240 unmodified lines9439449459469479489499509516 unmodified lines95895996096196296396446 unmodified linesapp.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"])# ------------------------------------------------------------------# Global exception handler# ------------------------------------------------------------------@app.exception_handler(Exception)async def global_exception_handler(request: Request, exc: Exception):33 unmodified linesWHATSAPP_ACCESS_TOKEN = os.environ.get("WHATSAPP_ACCESS_TOKEN")WHATSAPP_PHONE_ID = os.environ.get("WHATSAPP_PHONE_ID")PRODUCTION_HOST = os.environ.get("PRODUCTION_HOST", "https://kevsono-penafort-concierge.hf.space")ADMIN_SECRET_KEY = os.environ.get("ADMIN_SECRET_KEY", "change_this_in_production") # you set this!# ------------------------------------------------------------------# Supabase client266 unmodified lineslogger.error(f"Save conversation error: {e}", exc_info=True)# ------------------------------------------------------------------# Auth endpoints (with invite code registration)# ------------------------------------------------------------------class RegisterRequest(BaseModel):email: strpassword: strinvite_code: str # e.g. "KD001"class LoginRequest(BaseModel):email: strpassword: str1 unmodified lineemail: str@app.post("/auth/register")async def register(auth: RegisterRequest):client = get_supabase()# Lookup organisation by invite codeorg_result = client.table("organisations").select("id").eq("invite_code", auth.invite_code).maybe_single().execute()if not org_result or not org_result.data:raise HTTPException(status_code=400, detail="Invalid invite code. Please check and try again.")org_id = org_result.data["id"]try:# Create auth userresp = client.auth.sign_up({"email": auth.email,"password": auth.password,})if not resp.user:raise HTTPException(status_code=400, detail="Registration failed")user_id = resp.user.id# Create empty profileclient.table("profiles").insert({"id": user_id,"email": auth.email,"first_name": "","last_name": "","membership_id": f"MEM-{user_id[:8]}","status": "Active"}).execute()# Link user to organisationclient.table("org_members").insert({"user_id": user_id,"org_id": org_id,"role": "customer","joined_at": datetime.now().isoformat()}).execute()return {"user_id": user_id, "message": "Registration successful! Please verify your email if required."}except Exception as e:logger.error(f"Registration error: {str(e)}", exc_info=True)raise HTTPException(status_code=400, detail=str(e))@app.post("/auth/login")async def login(auth: LoginRequest):try:resp = get_supabase().auth.sign_in_with_password({"email": auth.email,18 unmodified linestoken = authorization.split(" ")[1]try:get_supabase().auth.sign_out(token)return {"message": "Logged out"}except Exception as e:logger.error(f"Logout error: {e}", exc_info=True)10 unmodified linesasync def reset_password(req: ResetPasswordRequest):try:get_supabase().auth.reset_password_for_email(req.email)return {"message": "Password reset email sent. Please check your inbox."}except Exception as e:logger.error(f"Reset password error: {req.email}: {e}", exc_info=True)raise HTTPException(status_code=400, detail=str(e))# ------------------------------------------------------------------# Admin endpoint to create organisation (auto‑generates invite code)# ------------------------------------------------------------------class CreateOrgRequest(BaseModel):org_name: strlocation: strniche: strbudget: int@app.post("/admin/create-org")async def create_organisation(req: CreateOrgRequest,x_admin_key: str = Header(..., alias="X-Admin-Key")):if x_admin_key != ADMIN_SECRET_KEY:raise HTTPException(status_code=403, detail="Invalid admin key")client = get_supabase()# Insert organisation (invite_code will be auto-generated by trigger)result = client.table("organisations").insert({"org_name": req.org_name,"location": req.location,"niche": req.niche,"budget": req.budget,"created_at": datetime.now().isoformat()}).execute()if not result.data:raise HTTPException(status_code=500, detail="Failed to create organisation")new_org = result.data[0]# Fetch the generated invite codereturn {"org_id": new_org["id"],"invite_code": new_org["invite_code"],"message": f"Organisation created. Invite code: {new_org['invite_code']}"}# ------------------------------------------------------------------# Endpoint to get organisation info by invite code (for frontend verification)# ------------------------------------------------------------------@app.get("/public/org-info")async def org_info(invite_code: str):client = get_supabase()result = client.table("organisations").select("org_name").eq("invite_code", invite_code).maybe_single().execute()if not result or not result.data:raise HTTPException(status_code=404, detail="Organisation not found")return {"org_name": result.data["org_name"]}# ------------------------------------------------------------------# Chat endpoint (requires org)# ------------------------------------------------------------------class ChatRequest(BaseModel):message: str19 unmodified linesraise HTTPException(status_code=500, detail="AI service error")# ------------------------------------------------------------------# Support tickets (full CRUD) – unchanged but keep for brevity# ------------------------------------------------------------------class TicketRequest(BaseModel):subject: str25 unmodified lines"message": ticket_req.message,"created_at": datetime.now().isoformat()}).execute()return {"ticket_id": str(ticket_id), "confirmation": f"✅ Ticket #{str(ticket_id)[:8]} created."}except Exception as e:logger.error(f"Create ticket error: {e}", exc_info=True)8 unmodified linesif status:query = query.eq("status", status)result = query.order("created_at", desc=True).execute()return {"tickets": result.data}except Exception as e:logger.error(f"Get tickets error: {e}", exc_info=True)34 unmodified lines"created_at": datetime.now().isoformat()}).execute()messages = client.table("ticket_messages").select("*").eq("ticket_id", ticket_id).order("created_at", desc=False).execute()return {"messages": messages.data}except HTTPException:raise14 unmodified lines"resolution_notes": req.resolution_notes,"resolved_at": datetime.now().isoformat()}).eq("id", ticket_id).eq("org_id", org_id).eq("user_id", user_id).execute()return {"message": "Ticket resolved"}except Exception as e:logger.error(f"Resolve error: {e}", exc_info=True)raise HTTPException(status_code=500, detail="Failed to resolve ticket")@app.get("/support/customer-context")async def customer_context(target_user_id: Optional[str] = None,user_org: Tuple[str, str] = Depends(get_current_org)):current_user_id, org_id = user_orguser_id = target_user_id if target_user_id else current_user_idclient = get_supabase()try:membership = client.table("org_members").select("org_id").eq("user_id", user_id).maybe_single().execute()if not membership or not membership.data or membership.data["org_id"] != org_id:raise HTTPException(status_code=403, detail="Not authorised to view this user")profile = client.table("profiles").select("*").eq("id", user_id).maybe_single().execute()loyalty = Noneif profile and profile.data and profile.data.get("membership_id"):loyalty = client.table("customer_points_summary").select("*").eq("membership_id", profile.data["membership_id"]).maybe_single().execute()return {"profile": profile.data if profile else None, "loyalty": loyalty.data if loyalty else None}except HTTPException:raise2 unmodified linesraise HTTPException(status_code=500, detail="Failed to fetch context")# ------------------------------------------------------------------# Loyalty & Inventory# ------------------------------------------------------------------@app.get("/loyalty/lookup")async def loyalty_lookup(phone: str, user_org: Tuple[str, str] = Depends(get_current_org)):62 unmodified lines"message": req.reason,"created_at": datetime.now().isoformat()}).execute()return {"ticket_id": str(ticket_id)}except Exception as e:logger.error(f"Escalate error: {e}", exc_info=True)44 unmodified linesreturn {"status": "healthy", "timestamp": datetime.now().isoformat()}# ------------------------------------------------------------------# Chat widget JS (unchanged)# ------------------------------------------------------------------@app.get("/chat-widget.js", response_class=PlainTextResponse)async def widget():99 unmodified lines"""# ------------------------------------------------------------------# WhatsApp webhook (kept as is)# ------------------------------------------------------------------@app.get("/webhook")async def verify_webhook(request: Request):40 unmodified linestry:async with httpx.AsyncClient() as client:await client.post(url, json=payload, headers=headers)except Exception as e:logger.error(f"Failed to send WhatsApp message: {e}", exc_info=True)@app.get("/")async def root():return {6 unmodified lines"loyalty": "/loyalty/lookup","inventory": "/inventory/public-list","escalate": "/support/escalate","admin": "/admin/create-org (requires X-Admin-Key header)","diagnose": "/api/diagnose"}}
main.py+96-35