-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
181 lines (159 loc) · 6.21 KB
/
Copy pathdatabase.py
File metadata and controls
181 lines (159 loc) · 6.21 KB
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import aiomysql
import os
from datetime import datetime
from typing import Optional
# MySQL connection pool
_pool: Optional[aiomysql.Pool] = None
async def get_pool() -> aiomysql.Pool:
"""Get or create MySQL connection pool"""
global _pool
if _pool is None:
_pool = await aiomysql.create_pool(
host=os.getenv("MYSQL_HOST", "localhost"),
port=int(os.getenv("MYSQL_PORT", 3306)),
user=os.getenv("MYSQL_USER", "root"),
password=os.getenv("MYSQL_PASSWORD", ""),
db=os.getenv("MYSQL_DATABASE", "vtorynka_bot"),
autocommit=True,
charset="utf8mb4",
minsize=1,
maxsize=10
)
return _pool
async def close_pool():
"""Close the connection pool"""
global _pool
if _pool:
_pool.close()
await _pool.wait_closed()
_pool = None
async def init_db():
"""Initialize database"""
pool = await get_pool()
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute("""
CREATE TABLE IF NOT EXISTS conversations (
user_id BIGINT PRIMARY KEY,
username VARCHAR(255),
language VARCHAR(10) DEFAULT NULL,
history LONGTEXT,
reminder_count INT DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
""")
# Migration: add language column if it doesn't exist
try:
await cur.execute("""
ALTER TABLE conversations
ADD COLUMN language VARCHAR(10) DEFAULT NULL
""")
except Exception:
pass # Column already exists
# Migration: add reminder_count column if it doesn't exist
try:
await cur.execute("""
ALTER TABLE conversations
ADD COLUMN reminder_count INT DEFAULT 0
""")
except Exception:
pass # Column already exists
await cur.execute("""
CREATE TABLE IF NOT EXISTS seller_leads (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id BIGINT,
username VARCHAR(255),
client_name VARCHAR(255),
phone VARCHAR(50),
property_type VARCHAR(100),
address VARCHAR(500),
rooms VARCHAR(50),
area VARCHAR(50),
price VARCHAR(100),
callback_time VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
status VARCHAR(50) DEFAULT 'new',
notes TEXT,
INDEX idx_user_id (user_id),
INDEX idx_status (status),
INDEX idx_created (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
""")
async def get_user_language(user_id: int) -> Optional[str]:
"""Get user's selected language"""
pool = await get_pool()
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(
"SELECT language FROM conversations WHERE user_id = %s", (user_id,)
)
row = await cur.fetchone()
if row:
return row[0]
return None
async def set_user_language(user_id: int, username: Optional[str], language: str):
"""Set user's language preference"""
pool = await get_pool()
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute("""
INSERT INTO conversations (user_id, username, language, updated_at)
VALUES (%s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
language = VALUES(language),
updated_at = VALUES(updated_at)
""", (user_id, username, language, datetime.now()))
async def get_conversation_history(user_id: int) -> list:
"""Get user's conversation history"""
import json
pool = await get_pool()
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute(
"SELECT history FROM conversations WHERE user_id = %s", (user_id,)
)
row = await cur.fetchone()
if row and row[0]:
return json.loads(row[0])
return []
async def save_conversation_history(user_id: int, username: Optional[str], history: list):
"""Save conversation history"""
import json
history_json = json.dumps(history, ensure_ascii=False)
pool = await get_pool()
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute("""
INSERT INTO conversations (user_id, username, history, updated_at)
VALUES (%s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
history = VALUES(history),
updated_at = VALUES(updated_at)
""", (user_id, username, history_json, datetime.now()))
async def save_seller_lead(
user_id: int,
username: Optional[str],
client_name: str,
phone: str,
property_type: str = "",
address: str = "",
rooms: str = "",
area: str = "",
price: str = "",
callback_time: str = ""
):
"""Save seller lead for exclusive agreement"""
pool = await get_pool()
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute("""
INSERT INTO seller_leads (
user_id, username, client_name, phone,
property_type, address, rooms, area, price, callback_time
)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
""", (
user_id, username, client_name, phone,
property_type, address, rooms, area, price, callback_time
))