This commit is contained in:
2026-03-06 12:44:57 +08:00
parent fa61b11b02
commit 006b035de4
132 changed files with 1361 additions and 17400 deletions

View File

@@ -113,6 +113,11 @@ def init_db():
conn.execute("CREATE INDEX idx_ts ON chat_logs(timestamp)")
if "idx_acc" not in exists:
conn.execute("CREATE INDEX idx_acc ON chat_logs(acc_id)")
# 添加 image_urls 列(如果不存在)
try:
conn.execute("ALTER TABLE chat_logs ADD COLUMN image_urls TEXT DEFAULT ''")
except Exception:
pass # 列已存在
else:
conn.execute("""
CREATE TABLE IF NOT EXISTS chat_logs (
@@ -133,6 +138,10 @@ def init_db():
conn.execute("ALTER TABLE chat_logs ADD COLUMN acc_id TEXT DEFAULT ''")
except Exception:
pass
try:
conn.execute("ALTER TABLE chat_logs ADD COLUMN image_urls TEXT DEFAULT ''")
except Exception:
pass
conn.execute("CREATE INDEX IF NOT EXISTS idx_acc ON chat_logs(acc_id)")
conn.commit()
@@ -150,15 +159,16 @@ def log_message(
acc_id: str = "", # 店铺账号ID
platform: str = "",
msg_type: int = 0,
image_urls: str = "", # 图片URL列表用\n分隔
):
"""记录一条聊天消息"""
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with _get_conn() as conn:
conn.execute(
_sql("INSERT INTO chat_logs "
"(customer_id, customer_name, acc_id, platform, direction, message, msg_type, timestamp) "
"VALUES (?,?,?,?,?,?,?,?)"),
(customer_id, customer_name, acc_id, platform, direction, message, msg_type, ts),
"(customer_id, customer_name, acc_id, platform, direction, message, msg_type, timestamp, image_urls) "
"VALUES (?,?,?,?,?,?,?,?,?)"),
(customer_id, customer_name, acc_id, platform, direction, message, msg_type, ts, image_urls),
)
conn.commit()
@@ -198,10 +208,10 @@ def get_customers(limit: int = 100) -> List[Dict]:
return [dict(r) for r in rows]
def get_conversation(customer_id: str, limit: int = 200) -> List[Dict]:
def get_conversation(customer_id: str, limit: int = 200, acc_id: str = "") -> List[Dict]:
"""返回某客户的最近对话记录(按时间升序)"""
# 忽略 acc_id 过滤,实现全店铺记忆
with _get_conn() as conn:
# 核心修复:先取最新的 limit 条,再按时间正序排列
rows = conn.execute(_sql("""
SELECT * FROM (
SELECT id, direction, message, msg_type, timestamp, acc_id
@@ -216,24 +226,15 @@ def get_conversation(customer_id: str, limit: int = 200) -> List[Dict]:
def get_recent_conversation(customer_id: str, acc_id: str = "", limit: int = 10) -> List[Dict]:
"""返回某客户近期对话(同店铺),用于企微推送保持连贯"""
"""返回某客户近期对话,忽略 acc_id 过滤"""
with _get_conn() as conn:
if acc_id:
rows = conn.execute(_sql("""
SELECT id, direction, message, timestamp, acc_id
FROM chat_logs
WHERE customer_id = ? AND acc_id = ?
ORDER BY id DESC
LIMIT ?
"""), (customer_id, acc_id, limit)).fetchall()
else:
rows = conn.execute(_sql("""
SELECT id, direction, message, timestamp, acc_id
FROM chat_logs
WHERE customer_id = ?
ORDER BY id DESC
LIMIT ?
"""), (customer_id, limit)).fetchall()
rows = conn.execute(_sql("""
SELECT id, direction, message, timestamp, acc_id
FROM chat_logs
WHERE customer_id = ?
ORDER BY id DESC
LIMIT ?
"""), (customer_id, limit)).fetchall()
out = [dict(r) for r in reversed(rows)]
return out

Binary file not shown.

View File

@@ -76,6 +76,8 @@ class CustomerProfile:
last_gemini_prompt: str = "" # 最近一次图片的 Gemini 处理提示词
last_aspect_ratio: str = "1:1" # 最近一次图片的建议输出比例
last_perspective: str = "no" # 最近一次图片的透视状态
last_image_analysis: str = "" # 最近一次图片分析结果JSON字符串用于数据标定
image_analysis_history: List[str] = None # 图片分析历史记录JSON列表用于数据标定
pending_quote_images: List[str] = None # 待统一报价图片队列(持久化)
pending_quote_requirements: List[str] = None # 待统一报价需求队列(持久化)
@@ -165,6 +167,8 @@ class CustomerProfile:
self.pending_quote_images = []
if self.pending_quote_requirements is None:
self.pending_quote_requirements = []
if self.image_analysis_history is None:
self.image_analysis_history = []
class CustomerDatabase:

Binary file not shown.

View File

@@ -47,6 +47,13 @@ class ImageTaskManager:
''')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_status ON image_tasks(status)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_cust_plat ON image_tasks(customer_id, platform)')
# 兼容旧库:补齐缺失字段
cursor.execute("PRAGMA table_info(image_tasks)")
existing_cols = {row[1] for row in cursor.fetchall()}
if "outcome" not in existing_cols:
cursor.execute("ALTER TABLE image_tasks ADD COLUMN outcome TEXT DEFAULT 'pending'")
if "price" not in existing_cols:
cursor.execute("ALTER TABLE image_tasks ADD COLUMN price REAL DEFAULT 0.0")
conn.commit()
conn.close()
@@ -88,6 +95,27 @@ class ImageTaskManager:
except Exception as e:
logger.error(f"Failed to update task status: {e}")
def update_price(self, customer_id: str, platform: str, price: float):
"""记录任务的成交价格"""
now = datetime.now().isoformat()
try:
conn = self._get_conn()
cursor = conn.cursor()
cursor.execute('''
UPDATE image_tasks
SET price = ?, updated_at = ?
WHERE task_id = (
SELECT task_id FROM image_tasks
WHERE customer_id = ? AND platform = ?
ORDER BY created_at DESC LIMIT 1
)
''', (price, now, customer_id, platform))
conn.commit()
conn.close()
logger.info(f"[DB] 客户 {customer_id} 任务价格更新为: ¥{price}")
except Exception as e:
logger.error(f"Failed to update price: {e}")
def update_outcome(self, customer_id: str, platform: str, outcome: str):
"""记录任务的最终结局(用于训练样本分类)"""
now = datetime.now().isoformat()