Commit 1c4887a3 by imwangxiaozhou Committed by 胡悦

refactor: 统一项目时区处理,调整官网agent默认展示状态并优化日志配置

- 新增 `app/infrastructure/time.py` 封装中国时区当前时间工具函数,替换全项目手动处理UTC时区的代码
- 新增数据库迁移脚本将 `official_site_agent_display` 表的 `display_status` 默认值设为 `disable`
- 更新对应模型、Schema、业务服务的默认展示状态配置
- 调整第三方库日志级别至WARNING,减少apscheduler、httpx等库的冗余日志输出
- 优化企业微信同步模块的日志格式和消息过滤逻辑,统一时区处理
1 parent 691a5d7e
# 会议纪要
**【会议主题】**:优加二手车平台业务模式、财务合规与运营策略对齐会
**【会议日期】**:[未提及]
**【参会人】**:说话人 0、说话人 1、说话人 2、说话人 3、说话人 4、说话人 5
**【缺席人】**:[未提及]
**【本次会议要点】**
1. 确定优加与广联体外合作模式:优加负责签单与确认收入,广联提供资金与服务。
2. 明确二手车税务逻辑:按销售额0.5%简易计税,收入确认以实际售出收款为准。
3. 采用清分或双合同模式规避优加与广联直接关联交易,确保财务路径合规。
4. 拍卖平台增设"包店车源"与"试拍车源"双频道,区分保收与竞价交易规则。
5. 推出轻量化拓店政策:通过企微引流、线索奖励及资金赋能激励一线销售。
6. 要求1月起全面切换新业务模式,加快平台全链路跑通与专项人员招聘。
**【详细任务列表】**
| 编号 | 类别 | 事项 | 责任人 | 计划完成时间 |
| --- | --- | --- | --- | --- |
| 1 | 财务合规 | 拟定优加与广联框架合同,明确资产管理费与资金占用费结算标准,确保体外合规运作。 | 说话人 4 | 近期 |
| 2 | 平台运营 | 开发并上线"包店车源"与"试拍车源"双频道,配置差异化保留价规则,支撑分类处置。 | 说话人 2 | 近期 |
| 3 | 商务政策 | 制定一线销售轻量化拓店激励方案,明确企微添加与线索转化奖励标准,于1月下发执行。 | 说话人 1 | 本周内 |
| 4 | 营销推广 | 精修内外部招商海报并补充引流二维码,经人工审核后统一分发,用于门店与朋友圈投放。 | 说话人 4 | 会后立即 |
| 5 | 流程跑通 | 验证收车、上拍、改价至过户结算全链路,修复系统改价卡点与财务对账逻辑,保障流程顺畅。 | 说话人 3 | 1月前 |
| 6 | 团队建设 | 落实车商拓展运营人员(肖峰等)到岗,明确驻店评估与赋能拓店职责,建立周复盘机制。 | 说话人 1 | 下周内 |
| 7 | 制度流程 | 完成OA系统二手车审批流配置,将资金拨付与业务单据全量接入优加体系,实现线上闭环。 | 说话人 2 | 近期 |
\ No newline at end of file
"""Memory 包装层 — 封装 ConversationHistory 的消息存取和压缩。"""
from __future__ import annotations
import logging
from typing import Any, List, Optional
from agentscope.message import Msg
from app.infrastructure.session_store import SessionStore
logger = logging.getLogger(__name__)
class SessionMemory:
"""管理单个 session 的消息历史,提供 Memory API(add / get_messages / compress)。"""
......@@ -30,41 +25,22 @@ class SessionMemory:
return []
return list(existing.get("conversation_history") or [])
def add(self, role: str, content: str | list[dict], name: Optional[str] = None) -> None:
def add(self, role: str, content: str, agent_code: Optional[str] = None) -> None:
existing = self._store.get(self.session_id)
if not existing:
return
history: list[dict[str, Any]] = list(existing.get("conversation_history") or [])
msg = Msg(
name=name or role,
content=content,
role=role,
)
history.append(msg.to_dict())
from app.infrastructure.time import china_now
history.append({
"role": role,
"content": content,
"agent_code": agent_code,
"agent_id": None,
"intent": None,
"timestamp": china_now().isoformat(),
})
existing["conversation_history"] = history
self._store.set(self.session_id, existing)
logger.info(
"[SessionMemory] session=%s add role=%s name=%s → conversation_history 长度=%d",
self.session_id, role, name or role, len(history),
)
def remove_last(self, role: Optional[str] = None) -> Optional[dict]:
"""移除 conversation_history 最后一条(可限定 role),返回被移除的消息。"""
history = self._load()
if not history:
return None
if role is not None and history[-1].get("role") != role:
return None
popped = history.pop()
data = self._store.get(self.session_id)
if data:
data["conversation_history"] = history
self._store.set(self.session_id, data)
logger.info(
"[SessionMemory] session=%s remove_last role_filter=%s → conversation_history 长度=%d",
self.session_id, role, len(history),
)
return popped
def get_messages(
self,
......@@ -88,8 +64,7 @@ class SessionMemory:
result = []
if include_summary and overflow:
summary = self._summarize(overflow)
summary_msg = Msg("system", f"[早期对话摘要] {summary}", "system")
result.append(summary_msg.to_dict())
result.append({"role": "system", "content": f"[早期对话摘要] {summary}"})
result.extend(recent)
return result
......
......@@ -56,10 +56,3 @@ def configure_logging(service_name: str, level: int = logging.INFO) -> None:
logger.handlers.clear()
logger.propagate = True
logger.setLevel(logging.WARNING)
# AgentScope 框架自己的 logger("as"),默认 propagate=False,只输出到控制台。
# 清掉它的 handler 并 propagate,让模型/工具日志进入项目的文件日志。
as_logger = logging.getLogger("as")
as_logger.handlers.clear()
as_logger.propagate = True
as_logger.setLevel(level)
from __future__ import annotations
import json
import logging
from dataclasses import dataclass
from datetime import datetime
from app.infrastructure.time import china_now
from typing import Optional
from app.infrastructure.session_store import SessionStore
from app.model.session import Session
logger = logging.getLogger(__name__)
def _utcnow_iso() -> str:
return china_now().isoformat()
@dataclass(frozen=True)
class ActiveSessionInfo:
id: str
session_id: str
channel: str
room_id: str
status: str = "active"
class ActiveSessionService:
def __init__(self, store: Optional[SessionStore] = None, db=None) -> None:
self.store = store or SessionStore()
self._db = db
def get_or_create_session(
self,
session_id: str,
room_id: str = "",
channel: str = "wechat_group",
) -> ActiveSessionInfo:
# 1. 先查内存(热路径)
existing = self.store.get(session_id)
if existing:
return ActiveSessionInfo(
id=session_id,
session_id=session_id,
channel=existing.get("channel", channel),
room_id=existing.get("room_id", room_id),
)
# 2. 查 DB(冷恢复)
if self._db:
db_sess = self._db.query(Session).filter(
Session.session_id == session_id
).first()
if db_sess:
payload = {
"session_id": db_sess.session_id,
"channel": db_sess.channel,
"room_id": db_sess.room_id,
"conversation_history": json.loads(
db_sess.conversation_history or "[]"
),
"context_entities": {},
"created_at": (
db_sess.created_at.isoformat()
if db_sess.created_at else _utcnow_iso()
),
"updated_at": _utcnow_iso(),
}
self.store.set(session_id, payload)
return ActiveSessionInfo(
id=session_id,
session_id=session_id,
channel=db_sess.channel,
room_id=db_sess.room_id,
)
# 3. 都没有,创建新 session
payload = {
"session_id": session_id,
"channel": channel,
"room_id": room_id,
"conversation_history": [],
"context_entities": {},
"created_at": _utcnow_iso(),
"updated_at": _utcnow_iso(),
}
self.store.set(session_id, payload)
return ActiveSessionInfo(
id=session_id,
session_id=session_id,
channel=channel,
room_id=room_id,
)
def save_to_db(self, session_id: str) -> None:
"""将内存中的 session 持久化到 DB。"""
if not self._db:
return
data = self.store.get(session_id)
if not data:
return
try:
existing = self._db.query(Session).filter(
Session.session_id == session_id
).first()
if existing:
existing.room_id = data.get("room_id", "")
existing.channel = data.get("channel", "wechat_group")
existing.conversation_history = json.dumps(
data.get("conversation_history", []), ensure_ascii=False
)
else:
db_sess = Session(
session_id=session_id,
room_id=data.get("room_id", ""),
channel=data.get("channel", "wechat_group"),
conversation_history=json.dumps(
data.get("conversation_history", []), ensure_ascii=False
),
)
self._db.add(db_sess)
self._db.commit()
except Exception:
self._db.rollback()
logger.exception("Failed to persist session %s to DB", session_id)
......@@ -57,9 +57,6 @@ class WeComSyncClient(Protocol):
def list_bots(self, *, page: int, page_size: int) -> dict[str, Any]:
...
def list_contacts(self, *, bot_id: str, page: int, page_size: int, contact_type: str | None = None) -> dict[str, Any]:
...
def list_customers(
self,
*,
......@@ -134,7 +131,7 @@ class WeComSyncService:
db: Session,
client: WeComSyncClient,
dispatcher: WeComMessageDispatcher | None = None,
page_size: int = 50,
page_size: int = 100,
) -> None:
self.db = db
self.client = client
......@@ -274,7 +271,7 @@ class WeComSyncService:
.filter(
WeComMessage.bot_send == False,
WeComMessage.dispatch_status == "pending",
WeComMessage.msg_type != "other",
WeComMessage.msg_type.in_(("text", "file")),
)
.order_by(WeComMessage.msg_time.asc(), WeComMessage.id.asc())
)
......@@ -406,7 +403,7 @@ class WeComSyncService:
record.session_title = data.get("session_title")
record.bot_send = self._infer_message_bot_send(data)
record.payload = dict(data)
if not record.bot_send and record.dispatch_status is None and record.msg_type != "other":
if not record.bot_send and record.dispatch_status is None and record.msg_type in ("text", "file"):
record.dispatch_status = "pending"
record.dispatch_error = None
self.db.flush()
......@@ -425,10 +422,22 @@ class WeComSyncService:
contact_id = str(data.get("contact_id") or "").strip()
sender_id = str(data.get("sender_id") or "").strip()
if not bot_id or not contact_id or not sender_id:
logger.warning(
format_job_log(
"bot_send 判定缺少关键字段,默认视为 bot_send=True: bot_id=%s contact_id=%s sender_id=%s msg_id=%s"
% (bot_id or "-", contact_id or "-", sender_id or "-", str(data.get("msg_id") or "-"))
)
)
return True
customer_contact_id = self._resolve_customer_contact_id(bot_id=bot_id, group_contact_id=contact_id)
if not customer_contact_id:
logger.warning(
format_job_log(
"未找到群绑定客户信息,默认视为 bot_send=True: bot_id=%s contact_id=%s sender_id=%s msg_id=%s"
% (bot_id, contact_id, sender_id, str(data.get("msg_id") or "-"))
)
)
return True
# 只有客户本人发言才需要分发(bot_send=False)
......
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
ALTER TABLE official_site_agent_display ALTER COLUMN display_status SET DEFAULT 'disable';
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!