File size: 1,533 Bytes
b057ee3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()
    )