Add inline price basis switching to saved estimate answers
This commit is contained in:
@@ -579,11 +579,12 @@ def init_db():
|
||||
def save_message(username: str, tab_id: str, role: str, content: str):
|
||||
"""Save a user or assistant message."""
|
||||
with _conn() as conn:
|
||||
conn.execute(
|
||||
cursor = conn.execute(
|
||||
"INSERT INTO messages (session_id, username, tab_id, role, content, timestamp) "
|
||||
"VALUES (?, ?, ?, ?, ?, ?)",
|
||||
(f"{username}/{tab_id}", username, tab_id, role, content, time.time()),
|
||||
)
|
||||
return cursor.lastrowid
|
||||
|
||||
|
||||
HISTORY_LIMIT = 2000 # потолок выдачи истории: длинные переписки нужны целиком
|
||||
@@ -601,7 +602,7 @@ def get_history(username: str, tab_id: str, limit: int = HISTORY_LIMIT,
|
||||
(проверено на всех 1299 диалогах боевой базы 09.09.2026), но записи, добавленные задним
|
||||
числом — цена под старым ответом, — обязаны вставать на своё место, а не в конец
|
||||
диалога."""
|
||||
sql = "SELECT role, content, timestamp FROM messages WHERE username = ? AND tab_id = ?"
|
||||
sql = "SELECT id, role, content, timestamp FROM messages WHERE username = ? AND tab_id = ?"
|
||||
args: list = [username, tab_id]
|
||||
if roles:
|
||||
sql += " AND role IN (" + ",".join("?" * len(roles)) + ")"
|
||||
@@ -613,6 +614,68 @@ def get_history(username: str, tab_id: str, limit: int = HISTORY_LIMIT,
|
||||
return [dict(r) for r in reversed(rows)]
|
||||
|
||||
|
||||
def get_linked_estimate(username: str, tab_id: str, estimate_id: int) -> dict | None:
|
||||
"""Return an estimate only when its answer belongs to the same user's dialog."""
|
||||
import json
|
||||
|
||||
with _conn() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT content FROM messages WHERE id=? AND username=? AND tab_id=? AND role='estimate'",
|
||||
(estimate_id, username, tab_id),
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
try:
|
||||
data = json.loads(row["content"])
|
||||
assistant_id = data.get("_assistant_id")
|
||||
except (ValueError, AttributeError, TypeError):
|
||||
return None
|
||||
if not isinstance(assistant_id, int) or isinstance(assistant_id, bool):
|
||||
return None
|
||||
answer = conn.execute(
|
||||
"SELECT id FROM messages WHERE id=? AND username=? AND tab_id=? AND role='assistant'",
|
||||
(assistant_id, username, tab_id),
|
||||
).fetchone()
|
||||
return data if answer else None
|
||||
|
||||
|
||||
def replace_linked_estimate(username: str, tab_id: str, estimate_id: int,
|
||||
expected_revision: int, data: dict, answer: str) -> str:
|
||||
"""Compare-and-swap answer and estimate in one SQLite transaction."""
|
||||
import json
|
||||
|
||||
with _conn() as conn:
|
||||
conn.execute("BEGIN IMMEDIATE")
|
||||
row = conn.execute(
|
||||
"SELECT content FROM messages WHERE id=? AND username=? AND tab_id=? AND role='estimate'",
|
||||
(estimate_id, username, tab_id),
|
||||
).fetchone()
|
||||
if not row:
|
||||
return "missing"
|
||||
try:
|
||||
current = json.loads(row["content"])
|
||||
assistant_id = current.get("_assistant_id")
|
||||
revision = current.get("_revision", 0)
|
||||
except (ValueError, AttributeError, TypeError):
|
||||
return "missing"
|
||||
if not isinstance(assistant_id, int) or isinstance(assistant_id, bool):
|
||||
return "missing"
|
||||
if revision != expected_revision:
|
||||
return "stale"
|
||||
answer_row = conn.execute(
|
||||
"SELECT id FROM messages WHERE id=? AND username=? AND tab_id=? AND role='assistant'",
|
||||
(assistant_id, username, tab_id),
|
||||
).fetchone()
|
||||
if not answer_row:
|
||||
return "missing"
|
||||
data["_assistant_id"] = assistant_id
|
||||
data["_revision"] = expected_revision + 1
|
||||
conn.execute("UPDATE messages SET content=? WHERE id=?", (answer, assistant_id))
|
||||
conn.execute("UPDATE messages SET content=? WHERE id=?",
|
||||
(json.dumps(data, ensure_ascii=False), estimate_id))
|
||||
return "ok"
|
||||
|
||||
|
||||
def clear_history(username: str, tab_id: str):
|
||||
"""Delete chat messages for one tab — backs the explicit reset action.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user