Files
gsfdc/server/app/models/valuation.py
T
wuzilongandCursor 2074a45681 feat: 增加会员服务与估价模版智能体
会员服务改为固定栏目,首页在线服务不再进入报告审核。估价模版智能体可多会话制作模版并下载,下载过程显示加载状态。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-23 13:36:19 +08:00

259 lines
11 KiB
Python

from datetime import datetime, timezone
import json
from sqlalchemy import Boolean, DateTime, Integer, String, Text, inspect, select, text
from sqlalchemy.dialects.mysql import MEDIUMTEXT
from sqlalchemy.orm import Mapped, mapped_column
from app.db import Base
def _now() -> datetime:
return datetime.now(timezone.utc).replace(tzinfo=None)
def _mysql_args() -> dict:
return {"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"}
def _long_text():
return Text().with_variant(MEDIUMTEXT(), "mysql")
WELCOME = (
"您好,我是智能估价。可依据库内估值报告,询问评估对象、基准日、价值类型、结论值或方法要点。"
)
DEFAULT_SUGGESTIONS = (
"日播时尚这份估值报告的评估对象和价值结论是什么?",
"华润三九相关估值报告采用了哪些主要方法?",
"浙江建投申报稿前部的评估报告清单包含哪些子报告?",
)
class ValuationSession(Base):
__tablename__ = "valuation_session"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
member_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
owner_key: Mapped[str] = mapped_column(String(32), nullable=False, default="", index=True)
title: Mapped[str] = mapped_column(String(80), nullable=False, default="新会话")
dify_conversation_id: Mapped[str] = mapped_column(String(64), nullable=False, default="")
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
class ValuationMessage(Base):
__tablename__ = "valuation_message"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
session_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
role: Mapped[str] = mapped_column(String(16), nullable=False)
content: Mapped[str] = mapped_column(_long_text(), nullable=False, default="")
thought: Mapped[str] = mapped_column(_long_text(), nullable=False, default="")
attachments: Mapped[str] = mapped_column(Text, nullable=False, default="")
web_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
kind: Mapped[str] = mapped_column(String(16), nullable=False, default="chat")
draft_format: Mapped[str] = mapped_column(String(8), nullable=False, default="")
draft_name: Mapped[str] = mapped_column(String(80), nullable=False, default="")
sources: Mapped[str] = mapped_column(Text, nullable=False, default="[]")
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
class ValuationFile(Base):
__tablename__ = "valuation_file"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
member_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
owner_key: Mapped[str] = mapped_column(String(32), nullable=False, default="", index=True)
session_id: Mapped[int | None] = mapped_column(Integer, nullable=True, index=True)
filename: Mapped[str] = mapped_column(String(255), nullable=False)
extension: Mapped[str] = mapped_column(String(16), nullable=False)
content_type: Mapped[str] = mapped_column(String(128), nullable=False, default="")
size: Mapped[int] = mapped_column(Integer, nullable=False)
object_key: Mapped[str] = mapped_column(String(255), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
DEFAULT_TEMPLATE_NAME = "估价说明草稿"
DEFAULT_TEMPLATE_OUTLINE = """一、评估对象概述
二、价值类型与评估基准日
三、评估方法与关键假设
四、主要参数与依据
五、结论摘要(辅助,非正式)"""
class ValuationTemplate(Base):
__tablename__ = "valuation_template"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(80), nullable=False)
filename: Mapped[str] = mapped_column(String(255), nullable=False, default="")
object_key: Mapped[str] = mapped_column(String(255), nullable=False, default="")
outline: Mapped[str] = mapped_column(_long_text(), nullable=False, default="")
enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
class ValuationSuggestion(Base):
__tablename__ = "valuation_suggestion"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
text: Mapped[str] = mapped_column(String(200), nullable=False)
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
COACH_WELCOME = (
"我是估价模版智能体,专门帮你制作估价智能体要用的报告模版。"
"可以上传历史 Word 或 PPT,也可以上传 pdf、表格和图片作参考。"
"直接说要保留哪些章节、做成 Word 还是 PPT。"
"整理好后下载到本地,你可以再改,然后回到模版列表里自己上传。"
"这里不会把文件直接放进模版列表,也不回答具体估价问题。"
)
class ValuationCoachSession(Base):
__tablename__ = "valuation_coach_session"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
owner_key: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
title: Mapped[str] = mapped_column(String(80), nullable=False, default="新会话")
outline_name: Mapped[str] = mapped_column(String(80), nullable=False, default="")
outline_format: Mapped[str] = mapped_column(String(8), nullable=False, default="")
outline_text: Mapped[str] = mapped_column(_long_text(), nullable=False, default="")
source_text: Mapped[str] = mapped_column(_long_text(), nullable=False, default="")
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
class ValuationCoachMessage(Base):
__tablename__ = "valuation_coach_message"
__table_args__ = _mysql_args()
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
session_id: Mapped[int] = mapped_column(Integer, nullable=False, index=True)
role: Mapped[str] = mapped_column(String(16), nullable=False)
content: Mapped[str] = mapped_column(_long_text(), nullable=False, default="")
thought: Mapped[str] = mapped_column(_long_text(), nullable=False, default="")
attachments: Mapped[str] = mapped_column(Text, nullable=False, default="")
kind: Mapped[str] = mapped_column(String(16), nullable=False, default="chat")
draft_format: Mapped[str] = mapped_column(String(8), nullable=False, default="")
draft_name: Mapped[str] = mapped_column(String(80), nullable=False, default="")
outline: Mapped[str] = mapped_column(_long_text(), nullable=False, default="")
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=_now)
def ensure_valuation_columns(db) -> None:
bind = db.get_bind()
if bind.dialect.name != "mysql":
return
names = {column["name"] for column in inspect(bind).get_columns("valuation_message")}
if "attachments" not in names:
db.execute(text("ALTER TABLE valuation_message ADD COLUMN attachments TEXT NULL"))
if "web_enabled" not in names:
db.execute(text("ALTER TABLE valuation_message ADD COLUMN web_enabled TINYINT(1) NOT NULL DEFAULT 0"))
if "kind" not in names:
db.execute(text("ALTER TABLE valuation_message ADD COLUMN kind VARCHAR(16) NOT NULL DEFAULT 'chat'"))
if "sources" not in names:
db.execute(text("ALTER TABLE valuation_message ADD COLUMN sources TEXT NULL"))
if "draft_format" not in names:
db.execute(text("ALTER TABLE valuation_message ADD COLUMN draft_format VARCHAR(8) NOT NULL DEFAULT ''"))
if "draft_name" not in names:
db.execute(text("ALTER TABLE valuation_message ADD COLUMN draft_name VARCHAR(80) NOT NULL DEFAULT ''"))
for table in ("valuation_session", "valuation_file"):
columns = {column["name"] for column in inspect(bind).get_columns(table)}
if "owner_key" not in columns:
db.execute(
text(f"ALTER TABLE {table} ADD COLUMN owner_key VARCHAR(32) NOT NULL DEFAULT ''")
)
tables = set(inspect(bind).get_table_names())
if "valuation_coach_session" in tables:
coach_columns = {column["name"] for column in inspect(bind).get_columns("valuation_coach_session")}
if "title" not in coach_columns:
db.execute(
text(
"ALTER TABLE valuation_coach_session "
"ADD COLUMN title VARCHAR(80) NOT NULL DEFAULT '新会话'"
)
)
for table, column in (
("valuation_message", "content"),
("valuation_message", "thought"),
("valuation_template", "outline"),
):
row = db.execute(
text(
"SELECT DATA_TYPE FROM information_schema.COLUMNS "
"WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :table AND COLUMN_NAME = :column"
),
{"table": table, "column": column},
).first()
if row is not None and str(row[0]).lower() == "text":
db.execute(text(f"ALTER TABLE {table} MODIFY {column} MEDIUMTEXT"))
db.commit()
def attachment_names(raw: str) -> list[str]:
names: list[str] = []
for item in _json_list(raw):
if isinstance(item, str) and item.strip():
names.append(item.strip())
return names
def stored_knowledge_names(raw: str) -> list[str]:
names: list[str] = []
for item in _json_list(raw):
if isinstance(item, str) and item.strip():
names.append(item.strip())
elif isinstance(item, dict) and item.get("kind") != "attachment":
name = str(item.get("name") or "").strip()
if name:
names.append(name)
return names
def _json_list(raw: str) -> list:
if not raw:
return []
try:
value = json.loads(raw)
except json.JSONDecodeError:
return []
return value if isinstance(value, list) else []
def ensure_default_template(db) -> None:
exists = db.scalar(select(ValuationTemplate.id).limit(1))
if exists is not None:
return
db.add(
ValuationTemplate(
name=DEFAULT_TEMPLATE_NAME,
filename="估价说明草稿.docx",
object_key="",
outline=DEFAULT_TEMPLATE_OUTLINE,
enabled=True,
created_at=_now(),
)
)
db.commit()
def ensure_default_suggestions(db) -> None:
exists = db.scalar(select(ValuationSuggestion.id).limit(1))
if exists is not None:
return
for index, text in enumerate(DEFAULT_SUGGESTIONS):
db.add(ValuationSuggestion(text=text, sort_order=index, enabled=True, created_at=_now()))
db.commit()