from datetime import datetime, timezone from db import supabase def utc_now(): return datetime.now(timezone.utc).isoformat() def get_session(customer_phone: str, bot_number: str): res = ( supabase.table("chat_sessions") .select("*") .eq("customer_phone", customer_phone) .eq("bot_number", bot_number) .limit(1) .execute() ) rows = res.data or [] if not rows: return None return rows[0] def upsert_session(customer_phone: str, bot_number: str, current_state: str, flow_type=None, flow_data=None, last_message=None): payload = { "customer_phone": customer_phone, "bot_number": bot_number, "current_state": current_state, "flow_type": flow_type, "flow_data": flow_data or {}, "last_message": last_message, "updated_at": utc_now(), } return ( supabase.table("chat_sessions") .upsert(payload, on_conflict="customer_phone,bot_number") .execute() ) def clear_session(customer_phone: str, bot_number: str): payload = { "customer_phone": customer_phone, "bot_number": bot_number, "current_state": "START", "flow_type": None, "flow_data": {}, "last_message": None, "updated_at": utc_now(), } return ( supabase.table("chat_sessions") .upsert(payload, on_conflict="customer_phone,bot_number") .execute() )