Commit ab2df777 by imwangxiaozhou

refactor: 清理冗余位置字段并优化关联查询,扩展官网媒体上传格式

移除OfficialTab和QrcodeChannel模型中的冗余位置字段,避免数据重复存储
新增SQLite数据库迁移脚本以重建相关表
优化服务层查询逻辑,通过关联PositionTag表获取实际位置信息
扩展agent_media类型上传支持的格式,新增png/jpg/jpeg/webp
简化活码禁用接口,移除不必要的参数校验和处理逻辑
清理冗余的Schema定义和未使用的代码
1 parent b36a2063
...@@ -21,7 +21,7 @@ def get_oss() -> OSSClient: ...@@ -21,7 +21,7 @@ def get_oss() -> OSSClient:
description=( description=(
"使用 `multipart/form-data` 上传官网相关媒体文件。" "使用 `multipart/form-data` 上传官网相关媒体文件。"
"目前支持四类用途:`agent_media`、`agent_icon`、`methodology_icon`、`methodology_image`。" "目前支持四类用途:`agent_media`、`agent_icon`、`methodology_icon`、`methodology_image`。"
"`agent_media` 仅允许 `gif/mp4`,最大 20MB;" "`agent_media` 允许 `gif/mp4/png/jpg/jpeg/webp`,最大 20MB;"
"`agent_icon` 仅允许 `png/jpg/jpeg`,最大 2MB;" "`agent_icon` 仅允许 `png/jpg/jpeg`,最大 2MB;"
"`methodology_icon` 仅允许 `png/jpg/jpeg`,最大 2MB;" "`methodology_icon` 仅允许 `png/jpg/jpeg`,最大 2MB;"
"`methodology_image` 仅允许 `png/jpg/jpeg`,最大 10MB。" "`methodology_image` 仅允许 `png/jpg/jpeg`,最大 10MB。"
......
...@@ -13,7 +13,6 @@ from app.schema.qrcode_channel import ( ...@@ -13,7 +13,6 @@ from app.schema.qrcode_channel import (
QrcodeCreateResponse, QrcodeCreateResponse,
QrcodeDeleteResponse, QrcodeDeleteResponse,
QrcodeDetailResponse, QrcodeDetailResponse,
QrcodeDisableRequest,
QrcodeDisableResponse, QrcodeDisableResponse,
QrcodeEnableResponse, QrcodeEnableResponse,
QrcodeExportRequest, QrcodeExportRequest,
...@@ -96,10 +95,10 @@ def export_qrcodes(req: QrcodeExportRequest, db: Session = Depends(get_db), oss: ...@@ -96,10 +95,10 @@ def export_qrcodes(req: QrcodeExportRequest, db: Session = Depends(get_db), oss:
@router.put("/{qrcode_id}/disable", response_model=QrcodeDisableResponse) @router.put("/{qrcode_id}/disable", response_model=QrcodeDisableResponse)
def disable_qrcode(qrcode_id: int, req: QrcodeDisableRequest, db: Session = Depends(get_db)): def disable_qrcode(qrcode_id: int, db: Session = Depends(get_db)):
svc = QrcodeChannelService(db, _wecom) svc = QrcodeChannelService(db, _wecom)
try: try:
return svc.disable(qrcode_id, req.reason) return svc.disable(qrcode_id, "")
except ValueError as e: except ValueError as e:
raise HTTPException(status_code=404, detail=str(e)) raise HTTPException(status_code=404, detail=str(e))
......
...@@ -78,6 +78,148 @@ def _rebuild_official_site_agent_display_without_unique(conn) -> None: ...@@ -78,6 +78,148 @@ def _rebuild_official_site_agent_display_without_unique(conn) -> None:
conn.execute(text("PRAGMA foreign_keys=ON")) conn.execute(text("PRAGMA foreign_keys=ON"))
def _rebuild_qrcode_channels_without_redundant_position_fields(conn) -> None:
conn.execute(text("PRAGMA foreign_keys=OFF"))
conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS qrcode_channels_new (
id INTEGER PRIMARY KEY,
qrcode_name VARCHAR(50),
position_id INTEGER,
wecom_bot_id INTEGER,
employee_id VARCHAR(100) NOT NULL,
employee_name VARCHAR(100) NOT NULL DEFAULT '',
qrcode_url VARCHAR(500),
agent_ids JSON,
remark VARCHAR(200),
welcome_message VARCHAR(500),
status VARCHAR(20) NOT NULL DEFAULT 'enable',
disable_reason VARCHAR(200),
created_by VARCHAR(64),
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
)
"""
)
)
conn.execute(
text(
"""
INSERT INTO qrcode_channels_new (
id,
qrcode_name,
position_id,
wecom_bot_id,
employee_id,
employee_name,
qrcode_url,
agent_ids,
remark,
welcome_message,
status,
disable_reason,
created_by,
created_at,
updated_at
)
SELECT
id,
qrcode_name,
position_id,
wecom_bot_id,
employee_id,
COALESCE(employee_name, ''),
qrcode_url,
agent_ids,
remark,
welcome_message,
COALESCE(status, 'enable'),
disable_reason,
created_by,
created_at,
updated_at
FROM qrcode_channels
"""
)
)
conn.execute(text("DROP TABLE qrcode_channels"))
conn.execute(text("ALTER TABLE qrcode_channels_new RENAME TO qrcode_channels"))
conn.execute(text("CREATE UNIQUE INDEX IF NOT EXISTS uk_qrcode_position_id ON qrcode_channels(position_id)"))
conn.execute(text("CREATE UNIQUE INDEX IF NOT EXISTS uk_qrcode_wecom_bot_id ON qrcode_channels(wecom_bot_id)"))
conn.execute(text("CREATE INDEX IF NOT EXISTS ix_qrcode_channels_employee_id ON qrcode_channels(employee_id)"))
conn.execute(text("CREATE INDEX IF NOT EXISTS ix_qrcode_channels_status ON qrcode_channels(status)"))
conn.execute(text("CREATE INDEX IF NOT EXISTS ix_qrcode_channels_position_id ON qrcode_channels(position_id)"))
conn.execute(text("CREATE INDEX IF NOT EXISTS ix_qrcode_channels_wecom_bot_id ON qrcode_channels(wecom_bot_id)"))
conn.execute(text("PRAGMA foreign_keys=ON"))
def _rebuild_official_tabs_without_redundant_position_fields(conn) -> None:
conn.execute(text("PRAGMA foreign_keys=OFF"))
conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS official_tabs_new (
id INTEGER PRIMARY KEY,
tab_name VARCHAR(100) NOT NULL,
position_id INTEGER,
qrcode_id INTEGER,
display_status VARCHAR(20) NOT NULL DEFAULT 'enable',
sort_order INTEGER NOT NULL DEFAULT 0,
main_title VARCHAR(200),
sub_title VARCHAR(500),
created_by VARCHAR(64),
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
deleted_at DATETIME
)
"""
)
)
conn.execute(
text(
"""
INSERT INTO official_tabs_new (
id,
tab_name,
position_id,
qrcode_id,
display_status,
sort_order,
main_title,
sub_title,
created_by,
created_at,
updated_at,
deleted_at
)
SELECT
id,
COALESCE(tab_name, ''),
position_id,
qrcode_id,
COALESCE(display_status, 'enable'),
COALESCE(sort_order, 0),
main_title,
sub_title,
created_by,
created_at,
updated_at,
deleted_at
FROM official_tabs
"""
)
)
conn.execute(text("DROP TABLE official_tabs"))
conn.execute(text("ALTER TABLE official_tabs_new RENAME TO official_tabs"))
conn.execute(text("CREATE INDEX IF NOT EXISTS ix_official_tabs_position_id ON official_tabs(position_id)"))
conn.execute(text("CREATE INDEX IF NOT EXISTS ix_official_tabs_qrcode_id ON official_tabs(qrcode_id)"))
conn.execute(text("CREATE INDEX IF NOT EXISTS ix_official_tabs_display_status ON official_tabs(display_status)"))
conn.execute(text("CREATE INDEX IF NOT EXISTS ix_official_tabs_sort_order ON official_tabs(sort_order)"))
conn.execute(text("CREATE INDEX IF NOT EXISTS ix_official_tabs_deleted_at ON official_tabs(deleted_at)"))
conn.execute(text("PRAGMA foreign_keys=ON"))
def ensure_runtime_schema(engine) -> None: def ensure_runtime_schema(engine) -> None:
if not str(engine.url).startswith("sqlite"): if not str(engine.url).startswith("sqlite"):
return return
...@@ -96,6 +238,14 @@ def ensure_runtime_schema(engine) -> None: ...@@ -96,6 +238,14 @@ def ensure_runtime_schema(engine) -> None:
conn.execute(text("DROP TABLE wecom_groups")) conn.execute(text("DROP TABLE wecom_groups"))
table_names.remove("wecom_groups") table_names.remove("wecom_groups")
if "qrcode_channels" in table_names:
qrcode_columns = {
row[1]
for row in conn.execute(text("PRAGMA table_info(qrcode_channels)"))
}
if "position_name" in qrcode_columns or "channel_code" in qrcode_columns or "agent_names" in qrcode_columns:
_rebuild_qrcode_channels_without_redundant_position_fields(conn)
if "wecom_job_configs" not in table_names: if "wecom_job_configs" not in table_names:
conn.execute( conn.execute(
text( text(
...@@ -217,6 +367,13 @@ def ensure_runtime_schema(engine) -> None: ...@@ -217,6 +367,13 @@ def ensure_runtime_schema(engine) -> None:
for row in conn.execute(text("PRAGMA table_info(official_tabs)")) for row in conn.execute(text("PRAGMA table_info(official_tabs)"))
} }
if "position_code" in official_tab_columns or "position_name" in official_tab_columns:
_rebuild_official_tabs_without_redundant_position_fields(conn)
official_tab_columns = {
row[1]
for row in conn.execute(text("PRAGMA table_info(official_tabs)"))
}
if "main_title" not in official_tab_columns: if "main_title" not in official_tab_columns:
conn.execute( conn.execute(
text("ALTER TABLE official_tabs ADD COLUMN main_title VARCHAR(200)") text("ALTER TABLE official_tabs ADD COLUMN main_title VARCHAR(200)")
......
...@@ -8,14 +8,11 @@ class QrcodeChannel(Base): ...@@ -8,14 +8,11 @@ class QrcodeChannel(Base):
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
qrcode_name = Column(String(50), default=None) qrcode_name = Column(String(50), default=None)
position_id = Column(Integer, nullable=False, index=True) position_id = Column(Integer, nullable=False, index=True)
position_name = Column(String(100), nullable=False, default="")
wecom_bot_id = Column(Integer, nullable=False, index=True) wecom_bot_id = Column(Integer, nullable=False, index=True)
employee_id = Column(String(100), nullable=False, index=True) employee_id = Column(String(100), nullable=False, index=True)
employee_name = Column(String(100), nullable=False, default="") employee_name = Column(String(100), nullable=False, default="")
channel_code = Column(String(100), nullable=False, unique=True, index=True)
qrcode_url = Column(String(500), default=None) qrcode_url = Column(String(500), default=None)
agent_ids = Column(JSON, default=None) agent_ids = Column(JSON, default=None)
agent_names = Column(JSON, default=None)
remark = Column(String(200), default=None) remark = Column(String(200), default=None)
welcome_message = Column(String(500), default=None) welcome_message = Column(String(500), default=None)
status = Column(String(20), nullable=False, default="enable") status = Column(String(20), nullable=False, default="enable")
......
...@@ -22,8 +22,6 @@ class OfficialTab(Base): ...@@ -22,8 +22,6 @@ class OfficialTab(Base):
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
tab_name = Column(String(100), nullable=False) tab_name = Column(String(100), nullable=False)
position_id = Column(Integer, default=None, index=True) position_id = Column(Integer, default=None, index=True)
position_code = Column(String(100), default=None, index=True)
position_name = Column(String(100), default=None)
qrcode_id = Column(Integer, default=None, index=True) qrcode_id = Column(Integer, default=None, index=True)
display_status = Column(String(20), nullable=False, default="enable", index=True) display_status = Column(String(20), nullable=False, default="enable", index=True)
sort_order = Column(Integer, nullable=False, default=0, index=True) sort_order = Column(Integer, nullable=False, default=0, index=True)
......
from datetime import datetime from datetime import datetime
from typing import List, Optional from typing import List, Optional
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
...@@ -34,7 +35,7 @@ class AvailableAgentsResponse(BaseModel): ...@@ -34,7 +35,7 @@ class AvailableAgentsResponse(BaseModel):
class SaveAgentConfigRequest(BaseModel): class SaveAgentConfigRequest(BaseModel):
media_url: str = Field(..., max_length=500, description="展示素材地址。") media_url: str = Field(..., max_length=500, description="展示素材地址。")
media_type: str = Field(..., description="素材类型,仅支持 gif / mp4。") media_type: str = Field(..., description="素材类型,支持 jpg/jpeg/png/webp/gif/mp4。")
media_size: int = Field(0, description="素材大小,单位字节。") media_size: int = Field(0, description="素材大小,单位字节。")
icon_url: Optional[str] = Field(None, max_length=500, description="Agent 头像或图标地址。") icon_url: Optional[str] = Field(None, max_length=500, description="Agent 头像或图标地址。")
speech_title: str = Field(..., description="展示话术标题。") speech_title: str = Field(..., description="展示话术标题。")
......
...@@ -26,6 +26,7 @@ class QrcodeCreateResponse(BaseModel): ...@@ -26,6 +26,7 @@ class QrcodeCreateResponse(BaseModel):
class QrcodeUpdateRequest(BaseModel): class QrcodeUpdateRequest(BaseModel):
qrcode_name: str = Field(..., max_length=50) qrcode_name: str = Field(..., max_length=50)
agent_ids: Optional[List[int]] = None
remark: Optional[str] = Field(None, max_length=200) remark: Optional[str] = Field(None, max_length=200)
welcome_message: Optional[str] = Field(None, max_length=500) welcome_message: Optional[str] = Field(None, max_length=500)
...@@ -86,10 +87,6 @@ class QrcodeExportResponse(BaseModel): ...@@ -86,10 +87,6 @@ class QrcodeExportResponse(BaseModel):
expires_at: Optional[datetime] = None expires_at: Optional[datetime] = None
class QrcodeDisableRequest(BaseModel):
reason: str = Field(..., max_length=200)
class QrcodeDisableResponse(BaseModel): class QrcodeDisableResponse(BaseModel):
success: bool success: bool
disabled_at: datetime disabled_at: datetime
......
...@@ -154,13 +154,16 @@ class AgentGroupHelperService: ...@@ -154,13 +154,16 @@ class AgentGroupHelperService:
.order_by(QrcodeChannel.id.asc()) .order_by(QrcodeChannel.id.asc())
.all() .all()
) )
position_ids = sorted({row.position_id for row in rows if row.position_id is not None})
positions = self.db.query(PositionTag).filter(PositionTag.id.in_(position_ids)).all() if position_ids else []
position_map = {row.id: row for row in positions}
employee_name = rows[0].employee_name if rows else "" employee_name = rows[0].employee_name if rows else ""
qrcodes = [ qrcodes = [
EmployeeQrcode( EmployeeQrcode(
qrcode_id=row.id, qrcode_id=row.id,
position_name=row.position_name, position_name=position_map.get(row.position_id).name if position_map.get(row.position_id) else "",
channel_code=row.channel_code, channel_code=position_map.get(row.position_id).code if position_map.get(row.position_id) else "",
status=row.status, status=row.status,
created_at=row.created_at, created_at=row.created_at,
) )
...@@ -182,6 +185,9 @@ class AgentGroupHelperService: ...@@ -182,6 +185,9 @@ class AgentGroupHelperService:
agent_map.setdefault(agent.managed_user_id, []).append(agent) agent_map.setdefault(agent.managed_user_id, []).append(agent)
qrcode_rows = self.db.query(QrcodeChannel).all() qrcode_rows = self.db.query(QrcodeChannel).all()
position_ids = sorted({row.position_id for row in qrcode_rows if row.position_id is not None})
positions = self.db.query(PositionTag).filter(PositionTag.id.in_(position_ids)).all() if position_ids else []
position_map = {row.id: row for row in positions}
qrcode_map: dict[int, list[QrcodeChannel]] = {} qrcode_map: dict[int, list[QrcodeChannel]] = {}
for row in qrcode_rows: for row in qrcode_rows:
if row.wecom_bot_id is None: if row.wecom_bot_id is None:
...@@ -211,10 +217,10 @@ class AgentGroupHelperService: ...@@ -211,10 +217,10 @@ class AgentGroupHelperService:
EmployeeMountedQrcode( EmployeeMountedQrcode(
qrcode_id=q.id, qrcode_id=q.id,
qrcode_name=q.qrcode_name or "", qrcode_name=q.qrcode_name or "",
channel_code=q.channel_code, channel_code=position_map.get(q.position_id).code if position_map.get(q.position_id) else "",
status=q.status, status=q.status,
position_id=q.position_id, position_id=q.position_id,
position_name=q.position_name, position_name=position_map.get(q.position_id).name if position_map.get(q.position_id) else "",
) )
for q in mounted_qrcodes for q in mounted_qrcodes
], ],
......
...@@ -8,7 +8,7 @@ from app.infrastructure.h5_cache import H5CacheManager ...@@ -8,7 +8,7 @@ from app.infrastructure.h5_cache import H5CacheManager
from app.infrastructure.schema_patch import ensure_runtime_schema from app.infrastructure.schema_patch import ensure_runtime_schema
from app.model.agent import Agent from app.model.agent import Agent
from app.model.official_site_agent_display import OfficialSiteAgentDisplay from app.model.official_site_agent_display import OfficialSiteAgentDisplay
from app.model.position_tag import OfficialTab from app.model.position_tag import OfficialTab, PositionTag
from app.schema.official_site_agent_display import ( from app.schema.official_site_agent_display import (
AvailableAgentItem, AvailableAgentItem,
AvailableAgentsResponse, AvailableAgentsResponse,
...@@ -84,9 +84,10 @@ class OfficialSiteAgentDisplayService: ...@@ -84,9 +84,10 @@ class OfficialSiteAgentDisplayService:
note="管家 Agent 不参与官网展示配置", note="管家 Agent 不参与官网展示配置",
) )
position = self.db.query(PositionTag).filter(PositionTag.id == tab.position_id).first() if tab.position_id is not None else None
return AvailableAgentsResponse( return AvailableAgentsResponse(
tab_id=tab_id, tab_id=tab_id,
position_name=tab.position_name or "", position_name=position.name if position and position.name else "",
qrcode_id=tab.qrcode_id, qrcode_id=tab.qrcode_id,
available_agents=available_items, available_agents=available_items,
steward_agent=steward_info, steward_agent=steward_info,
......
...@@ -6,7 +6,7 @@ from app.infrastructure.h5_cache import H5CacheManager ...@@ -6,7 +6,7 @@ from app.infrastructure.h5_cache import H5CacheManager
from app.model.agent_group import QrcodeChannel from app.model.agent_group import QrcodeChannel
from app.model.methodology import OfficialSiteMethodology, OfficialSiteMethodologyStep from app.model.methodology import OfficialSiteMethodology, OfficialSiteMethodologyStep
from app.model.official_site_agent_display import OfficialSiteAgentDisplay from app.model.official_site_agent_display import OfficialSiteAgentDisplay
from app.model.position_tag import OfficialTab from app.model.position_tag import OfficialTab, PositionTag
from app.schema.official_site_home import ( from app.schema.official_site_home import (
H5HomeAgentItem, H5HomeAgentItem,
H5HomeMethodologyItem, H5HomeMethodologyItem,
...@@ -53,7 +53,11 @@ class H5HomeService: ...@@ -53,7 +53,11 @@ class H5HomeService:
) )
result = [] result = []
position_ids = sorted({tab.position_id for tab in active_tabs if tab.position_id is not None})
positions = self.db.query(PositionTag).filter(PositionTag.id.in_(position_ids)).all() if position_ids else []
position_map = {row.id: row for row in positions}
for tab in active_tabs: for tab in active_tabs:
position = position_map.get(tab.position_id)
qrcode_url = None qrcode_url = None
qrcode_status = None qrcode_status = None
if tab.qrcode_id: if tab.qrcode_id:
...@@ -90,8 +94,8 @@ class H5HomeService: ...@@ -90,8 +94,8 @@ class H5HomeService:
result.append(H5HomeTabItem( result.append(H5HomeTabItem(
tab_id=tab.id, tab_id=tab.id,
position_code=tab.position_code or "", position_code=position.code if position and position.code else "",
position_name=tab.position_name or "", position_name=position.name if position and position.name else "",
main_title=tab.main_title, main_title=tab.main_title,
sub_title=tab.sub_title, sub_title=tab.sub_title,
qrcode_url=qrcode_url, qrcode_url=qrcode_url,
......
...@@ -32,6 +32,11 @@ class OfficialSiteTabService: ...@@ -32,6 +32,11 @@ class OfficialSiteTabService:
self.db = db self.db = db
self.cache = cache self.cache = cache
def _get_position(self, position_id: Optional[int]) -> Optional[PositionTag]:
if position_id is None:
return None
return self.db.query(PositionTag).filter(PositionTag.id == position_id).first()
def create(self, req: CreateTabRequest) -> CreateTabResponse: def create(self, req: CreateTabRequest) -> CreateTabResponse:
now = datetime.now(timezone.utc) now = datetime.now(timezone.utc)
position = self.db.query(PositionTag).filter(PositionTag.code == req.position_code).first() position = self.db.query(PositionTag).filter(PositionTag.code == req.position_code).first()
...@@ -44,8 +49,6 @@ class OfficialSiteTabService: ...@@ -44,8 +49,6 @@ class OfficialSiteTabService:
tab = OfficialTab( tab = OfficialTab(
tab_name=req.position_name, tab_name=req.position_name,
position_code=req.position_code,
position_name=req.position_name,
position_id=position.id, position_id=position.id,
qrcode_id=req.qrcode_id, qrcode_id=req.qrcode_id,
display_status=req.display_status, display_status=req.display_status,
...@@ -67,8 +70,8 @@ class OfficialSiteTabService: ...@@ -67,8 +70,8 @@ class OfficialSiteTabService:
return CreateTabResponse( return CreateTabResponse(
tab_id=tab.id, tab_id=tab.id,
position_code=tab.position_code or "", position_code=position.code or "",
position_name=tab.position_name or "", position_name=position.name or "",
qrcode_id=tab.qrcode_id or 0, qrcode_id=tab.qrcode_id or 0,
main_title=tab.main_title, main_title=tab.main_title,
sub_title=tab.sub_title, sub_title=tab.sub_title,
...@@ -89,8 +92,6 @@ class OfficialSiteTabService: ...@@ -89,8 +92,6 @@ class OfficialSiteTabService:
raise ValueError("活码不存在或已停用") raise ValueError("活码不存在或已停用")
old_position_id = tab.position_id old_position_id = tab.position_id
tab.position_code = req.position_code
tab.position_name = req.position_name
tab.tab_name = req.position_name tab.tab_name = req.position_name
tab.position_id = position.id tab.position_id = position.id
tab.qrcode_id = req.qrcode_id tab.qrcode_id = req.qrcode_id
...@@ -143,13 +144,14 @@ class OfficialSiteTabService: ...@@ -143,13 +144,14 @@ class OfficialSiteTabService:
def get_detail(self, tab_id: int) -> TabDetailResponse: def get_detail(self, tab_id: int) -> TabDetailResponse:
tab = self._get_or_404(tab_id) tab = self._get_or_404(tab_id)
position = self._get_position(tab.position_id)
agent_count, qr_name, qr_employee_id, qr_employee_name, qr_url, qr_status, _ = self._build_tab_related_data(tab) agent_count, qr_name, qr_employee_id, qr_employee_name, qr_url, qr_status, _ = self._build_tab_related_data(tab)
return TabDetailResponse( return TabDetailResponse(
tab_id=tab.id, tab_id=tab.id,
position_id=tab.position_id, position_id=tab.position_id,
position_code=tab.position_code or "", position_code=position.code if position and position.code else "",
position_name=tab.position_name or "", position_name=position.name if position and position.name else "",
qrcode_id=tab.qrcode_id, qrcode_id=tab.qrcode_id,
qrcode_name=qr_name, qrcode_name=qr_name,
qrcode_employee_id=qr_employee_id, qrcode_employee_id=qr_employee_id,
...@@ -173,13 +175,14 @@ class OfficialSiteTabService: ...@@ -173,13 +175,14 @@ class OfficialSiteTabService:
keyword: Optional[str] = None, keyword: Optional[str] = None,
display_status: Optional[str] = None, display_status: Optional[str] = None,
) -> TabListResponse: ) -> TabListResponse:
query = self.db.query(OfficialTab).filter(OfficialTab.deleted_at.is_(None)) query = self.db.query(OfficialTab).outerjoin(PositionTag, OfficialTab.position_id == PositionTag.id).filter(OfficialTab.deleted_at.is_(None))
if keyword: if keyword:
query = query.filter( query = query.filter(
or_( or_(
OfficialTab.position_name.like(f"%{keyword}%"), PositionTag.name.like(f"%{keyword}%"),
OfficialTab.position_code.like(f"%{keyword}%"), PositionTag.code.like(f"%{keyword}%"),
OfficialTab.tab_name.like(f"%{keyword}%"),
) )
) )
if display_status: if display_status:
...@@ -187,9 +190,13 @@ class OfficialSiteTabService: ...@@ -187,9 +190,13 @@ class OfficialSiteTabService:
total = query.count() total = query.count()
rows = query.order_by(OfficialTab.sort_order.asc(), OfficialTab.id.asc()).offset((page - 1) * page_size).limit(page_size).all() rows = query.order_by(OfficialTab.sort_order.asc(), OfficialTab.id.asc()).offset((page - 1) * page_size).limit(page_size).all()
position_ids = sorted({row.position_id for row in rows if row.position_id is not None})
positions = self.db.query(PositionTag).filter(PositionTag.id.in_(position_ids)).all() if position_ids else []
position_map = {row.id: row for row in positions}
items = [] items = []
for r in rows: for r in rows:
position = position_map.get(r.position_id)
agent_count, qr_name, _, qr_employee_name, qr_url, qr_status, channel_code = self._build_tab_related_data(r) agent_count, qr_name, _, qr_employee_name, qr_url, qr_status, channel_code = self._build_tab_related_data(r)
operations = ["查看", "编辑"] operations = ["查看", "编辑"]
...@@ -200,8 +207,8 @@ class OfficialSiteTabService: ...@@ -200,8 +207,8 @@ class OfficialSiteTabService:
items.append(TabListItem( items.append(TabListItem(
tab_id=r.id, tab_id=r.id,
position_code=r.position_code or "", position_code=position.code if position and position.code else "",
position_name=r.position_name or "", position_name=position.name if position and position.name else "",
qrcode_id=r.qrcode_id, qrcode_id=r.qrcode_id,
qrcode_name=qr_name, qrcode_name=qr_name,
channel_code=channel_code, channel_code=channel_code,
...@@ -231,12 +238,15 @@ class OfficialSiteTabService: ...@@ -231,12 +238,15 @@ class OfficialSiteTabService:
) )
rows = query.order_by(QrcodeChannel.id.asc()).all() rows = query.order_by(QrcodeChannel.id.asc()).all()
position_ids = sorted({row.position_id for row in rows if row.position_id is not None})
positions = self.db.query(PositionTag).filter(PositionTag.id.in_(position_ids)).all() if position_ids else []
position_map = {row.id: row for row in positions}
items = [ items = [
AvailableQrcodeItem( AvailableQrcodeItem(
qrcode_id=qr.id, qrcode_id=qr.id,
channel_code=qr.channel_code, channel_code=position_map.get(qr.position_id).code if position_map.get(qr.position_id) else "",
employee_name=qr.employee_name, employee_name=qr.employee_name,
position_name=qr.position_name, position_name=position_map.get(qr.position_id).name if position_map.get(qr.position_id) else "",
status=qr.status, status=qr.status,
) )
for qr in rows for qr in rows
...@@ -261,12 +271,13 @@ class OfficialSiteTabService: ...@@ -261,12 +271,13 @@ class OfficialSiteTabService:
if tab.qrcode_id: if tab.qrcode_id:
qr = self.db.query(QrcodeChannel).filter(QrcodeChannel.id == tab.qrcode_id).first() qr = self.db.query(QrcodeChannel).filter(QrcodeChannel.id == tab.qrcode_id).first()
if qr: if qr:
position = self.db.query(PositionTag).filter(PositionTag.id == qr.position_id).first() if qr.position_id is not None else None
qr_name = qr.qrcode_name qr_name = qr.qrcode_name
qr_employee_id = qr.employee_id qr_employee_id = qr.employee_id
qr_employee_name = qr.employee_name qr_employee_name = qr.employee_name
qr_url = qr.qrcode_url qr_url = qr.qrcode_url
qr_status = qr.status qr_status = qr.status
channel_code = qr.channel_code channel_code = position.code if position and position.code else ""
return agent_count, qr_name, qr_employee_id, qr_employee_name, qr_url, qr_status, channel_code return agent_count, qr_name, qr_employee_id, qr_employee_name, qr_url, qr_status, channel_code
......
...@@ -8,7 +8,7 @@ from app.infrastructure.file_parser import OSSClient ...@@ -8,7 +8,7 @@ from app.infrastructure.file_parser import OSSClient
from app.schema.official_site_upload import UploadMediaResponse from app.schema.official_site_upload import UploadMediaResponse
_USAGE_RULES = { _USAGE_RULES = {
"agent_media": {"exts": {"gif", "mp4"}, "max_size": 20 * 1024 * 1024, "dir": "agent"}, "agent_media": {"exts": {"gif", "mp4", "png", "jpg", "jpeg", "webp"}, "max_size": 20 * 1024 * 1024, "dir": "agent"},
"agent_icon": {"exts": {"png", "jpg", "jpeg"}, "max_size": 2 * 1024 * 1024, "dir": "agent/icon"}, "agent_icon": {"exts": {"png", "jpg", "jpeg"}, "max_size": 2 * 1024 * 1024, "dir": "agent/icon"},
"methodology_icon": {"exts": {"png", "jpg", "jpeg"}, "max_size": 2 * 1024 * 1024, "dir": "methodology/icon"}, "methodology_icon": {"exts": {"png", "jpg", "jpeg"}, "max_size": 2 * 1024 * 1024, "dir": "methodology/icon"},
"methodology_image": {"exts": {"png", "jpg", "jpeg"}, "max_size": 10 * 1024 * 1024, "dir": "methodology/image"}, "methodology_image": {"exts": {"png", "jpg", "jpeg"}, "max_size": 10 * 1024 * 1024, "dir": "methodology/image"},
...@@ -57,7 +57,14 @@ def _get_extension(file_name: str) -> str: ...@@ -57,7 +57,14 @@ def _get_extension(file_name: str) -> str:
def _content_type_for_ext(ext: str) -> str: def _content_type_for_ext(ext: str) -> str:
mapping = {"gif": "image/gif", "mp4": "video/mp4", "png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg"} mapping = {
"gif": "image/gif",
"mp4": "video/mp4",
"png": "image/png",
"jpg": "image/jpeg",
"jpeg": "image/jpeg",
"webp": "image/webp",
}
return mapping.get(ext, "application/octet-stream") return mapping.get(ext, "application/octet-stream")
......
...@@ -36,6 +36,29 @@ class PositionTagService: ...@@ -36,6 +36,29 @@ class PositionTagService:
user_ids=[], user_ids=[],
) )
self.db.add(tag) self.db.add(tag)
self.db.flush()
steward = (
self.db.query(Agent)
.filter(
Agent.is_deleted == False,
((Agent.is_steward == True) | (Agent.code == "steward")),
)
.order_by(Agent.id.asc())
.first()
)
if steward:
exists = (
self.db.query(AgentPosition)
.filter(
AgentPosition.agent_id == steward.id,
AgentPosition.position_id == tag.id,
)
.first()
)
if not exists:
self.db.add(AgentPosition(agent_id=steward.id, position_id=tag.id))
self.db.commit() self.db.commit()
self.db.refresh(tag) self.db.refresh(tag)
return tag return tag
...@@ -66,9 +89,9 @@ class PositionTagService: ...@@ -66,9 +89,9 @@ class PositionTagService:
detachable = [] detachable = []
hints = [] hints = []
qrcode_refs = self.db.query(QrcodeChannel).filter(QrcodeChannel.position_name == tag.name).all() qrcode_refs = self.db.query(QrcodeChannel).filter(QrcodeChannel.position_id == tag.id).all()
for qr in qrcode_refs: for qr in qrcode_refs:
blocking.append(BlockingReference(type="qrcode_channel", id=qr.id, name=qr.channel_code)) blocking.append(BlockingReference(type="qrcode_channel", id=qr.id, name=tag.code or ""))
tab_refs = self.db.query(OfficialTab).filter(OfficialTab.position_id == tag_id).all() tab_refs = self.db.query(OfficialTab).filter(OfficialTab.position_id == tag_id).all()
for tab in tab_refs: for tab in tab_refs:
...@@ -151,6 +174,7 @@ class PositionTagService: ...@@ -151,6 +174,7 @@ class PositionTagService:
] ]
def get_qrcode_channels_by_position(self, tag_id: int) -> list[PositionTagListQrcodeChannelItem]: def get_qrcode_channels_by_position(self, tag_id: int) -> list[PositionTagListQrcodeChannelItem]:
tag = self._get_tag_or_404(tag_id)
rows = ( rows = (
self.db.query(QrcodeChannel) self.db.query(QrcodeChannel)
.filter(QrcodeChannel.position_id == tag_id) .filter(QrcodeChannel.position_id == tag_id)
...@@ -161,7 +185,7 @@ class PositionTagService: ...@@ -161,7 +185,7 @@ class PositionTagService:
PositionTagListQrcodeChannelItem( PositionTagListQrcodeChannelItem(
id=row.id, id=row.id,
qrcode_name=row.qrcode_name, qrcode_name=row.qrcode_name,
channel_code=row.channel_code, channel_code=tag.code or "",
employee_id=row.employee_id, employee_id=row.employee_id,
employee_name=row.employee_name, employee_name=row.employee_name,
status=row.status, status=row.status,
......
...@@ -32,6 +32,11 @@ class QrcodeChannelService: ...@@ -32,6 +32,11 @@ class QrcodeChannelService:
self.wecom = wecom self.wecom = wecom
self.oss = oss self.oss = oss
def _get_position(self, position_id: Optional[int]) -> Optional[PositionTag]:
if position_id is None:
return None
return self.db.query(PositionTag).filter(PositionTag.id == position_id).first()
def create(self, req) -> QrcodeCreateResponse: def create(self, req) -> QrcodeCreateResponse:
position = self.db.query(PositionTag).filter(PositionTag.code == req.position_code).first() position = self.db.query(PositionTag).filter(PositionTag.code == req.position_code).first()
if not position: if not position:
...@@ -79,14 +84,11 @@ class QrcodeChannelService: ...@@ -79,14 +84,11 @@ class QrcodeChannelService:
qr = QrcodeChannel( qr = QrcodeChannel(
qrcode_name=req.qrcode_name, qrcode_name=req.qrcode_name,
position_id=position.id, position_id=position.id,
position_name=position.name,
wecom_bot_id=bot.id, wecom_bot_id=bot.id,
employee_id=employee_id, employee_id=employee_id,
employee_name=employee_name, employee_name=employee_name,
channel_code=channel_code,
qrcode_url=qrcode_url, qrcode_url=qrcode_url,
agent_ids=agent_ids, agent_ids=agent_ids,
agent_names=agent_names,
remark=req.remark, remark=req.remark,
welcome_message=req.welcome_message, welcome_message=req.welcome_message,
created_by="admin", created_by="admin",
...@@ -99,7 +101,7 @@ class QrcodeChannelService: ...@@ -99,7 +101,7 @@ class QrcodeChannelService:
qrcode_id=qr.id, qrcode_id=qr.id,
qrcode_name=qr.qrcode_name or "", qrcode_name=qr.qrcode_name or "",
qrcode_url=qr.qrcode_url or "", qrcode_url=qr.qrcode_url or "",
channel_code=qr.channel_code, channel_code=position.code or "",
status=qr.status, status=qr.status,
agent_ids=agent_ids, agent_ids=agent_ids,
agent_names=agent_names, agent_names=agent_names,
...@@ -117,6 +119,7 @@ class QrcodeChannelService: ...@@ -117,6 +119,7 @@ class QrcodeChannelService:
def get_detail(self, qrcode_id: int) -> QrcodeDetailResponse: def get_detail(self, qrcode_id: int) -> QrcodeDetailResponse:
qr = self._get_or_404(qrcode_id) qr = self._get_or_404(qrcode_id)
position = self._get_position(qr.position_id)
position_agents = ( position_agents = (
self.db.query(Agent) self.db.query(Agent)
.join(AgentPosition, AgentPosition.agent_id == Agent.id) .join(AgentPosition, AgentPosition.agent_id == Agent.id)
...@@ -141,8 +144,8 @@ class QrcodeChannelService: ...@@ -141,8 +144,8 @@ class QrcodeChannelService:
qrcode_name=qr.qrcode_name, qrcode_name=qr.qrcode_name,
employee_id=qr.employee_id, employee_id=qr.employee_id,
employee_name=qr.employee_name, employee_name=qr.employee_name,
position_name=qr.position_name, position_name=position.name if position and position.name else "",
channel_code=qr.channel_code, channel_code=position.code if position and position.code else "",
qrcode_url=qr.qrcode_url, qrcode_url=qr.qrcode_url,
agent_ids=agent_ids, agent_ids=agent_ids,
agent_names=agent_names, agent_names=agent_names,
...@@ -161,22 +164,27 @@ class QrcodeChannelService: ...@@ -161,22 +164,27 @@ class QrcodeChannelService:
status: Optional[str] = None, status: Optional[str] = None,
keyword: Optional[str] = None, keyword: Optional[str] = None,
) -> QrcodeListResponse: ) -> QrcodeListResponse:
query = self.db.query(QrcodeChannel) query = self.db.query(QrcodeChannel).outerjoin(PositionTag, QrcodeChannel.position_id == PositionTag.id)
if status: if status:
query = query.filter(QrcodeChannel.status == status) query = query.filter(QrcodeChannel.status == status)
if keyword: if keyword:
query = query.filter( query = query.filter(
or_( or_(
QrcodeChannel.employee_name.like(f"%{keyword}%"), QrcodeChannel.employee_name.like(f"%{keyword}%"),
QrcodeChannel.position_name.like(f"%{keyword}%"), PositionTag.name.like(f"%{keyword}%"),
QrcodeChannel.channel_code.like(f"%{keyword}%"), PositionTag.code.like(f"%{keyword}%"),
QrcodeChannel.qrcode_name.like(f"%{keyword}%"),
) )
) )
total = query.count() total = query.count()
rows = query.order_by(QrcodeChannel.id.desc()).offset((page - 1) * page_size).limit(page_size).all() rows = query.order_by(QrcodeChannel.id.desc()).offset((page - 1) * page_size).limit(page_size).all()
position_ids = sorted({row.position_id for row in rows if row.position_id is not None})
positions = self.db.query(PositionTag).filter(PositionTag.id.in_(position_ids)).all() if position_ids else []
position_map = {row.id: row for row in positions}
items = [] items = []
for r in rows: for r in rows:
position = position_map.get(r.position_id)
position_agents = ( position_agents = (
self.db.query(Agent) self.db.query(Agent)
.join(AgentPosition, AgentPosition.agent_id == Agent.id) .join(AgentPosition, AgentPosition.agent_id == Agent.id)
...@@ -204,8 +212,8 @@ class QrcodeChannelService: ...@@ -204,8 +212,8 @@ class QrcodeChannelService:
qrcode_id=r.id, qrcode_id=r.id,
qrcode_name=r.qrcode_name, qrcode_name=r.qrcode_name,
employee_name=r.employee_name, employee_name=r.employee_name,
position_name=r.position_name, position_name=position.name if position and position.name else "",
channel_code=r.channel_code, channel_code=position.code if position and position.code else "",
qrcode_url=r.qrcode_url, qrcode_url=r.qrcode_url,
agent_count=len(agent_list), agent_count=len(agent_list),
agent_names_preview=agent_names, agent_names_preview=agent_names,
...@@ -217,29 +225,53 @@ class QrcodeChannelService: ...@@ -217,29 +225,53 @@ class QrcodeChannelService:
return QrcodeListResponse(total=total, page=page, page_size=page_size, list=items) return QrcodeListResponse(total=total, page=page, page_size=page_size, list=items)
def export(self, req) -> QrcodeExportResponse: def export(self, req) -> QrcodeExportResponse:
query = self.db.query(QrcodeChannel) query = self.db.query(QrcodeChannel).outerjoin(PositionTag, QrcodeChannel.position_id == PositionTag.id)
if req.filter_conditions: if req.filter_conditions:
if req.filter_conditions.get("position_name"): if req.filter_conditions.get("position_name"):
query = query.filter(QrcodeChannel.position_name == req.filter_conditions["position_name"]) query = query.filter(PositionTag.name == req.filter_conditions["position_name"])
if req.filter_conditions.get("status"): if req.filter_conditions.get("status"):
query = query.filter(QrcodeChannel.status == req.filter_conditions["status"]) query = query.filter(QrcodeChannel.status == req.filter_conditions["status"])
rows = query.order_by(QrcodeChannel.id.asc()).all() rows = query.order_by(QrcodeChannel.id.asc()).all()
position_ids = sorted({row.position_id for row in rows if row.position_id is not None})
positions = self.db.query(PositionTag).filter(PositionTag.id.in_(position_ids)).all() if position_ids else []
position_map = {row.id: row for row in positions}
agent_map_by_position_id: dict[int, list[str]] = {}
for position in positions:
position_agents = (
self.db.query(Agent)
.join(AgentPosition, AgentPosition.agent_id == Agent.id)
.filter(
AgentPosition.position_id == position.id,
Agent.is_deleted == False,
Agent.status == AgentStatus.enable,
)
.all()
)
steward = self.db.query(Agent).filter(Agent.code == "steward", Agent.is_deleted == False).first()
agent_list = list(position_agents)
if steward and steward not in agent_list:
agent_list.insert(0, steward)
agent_map_by_position_id[position.id] = [agent.name for agent in agent_list]
fields = req.export_fields or ["employee_name", "position_name", "channel_code", "status"] fields = req.export_fields or ["employee_name", "position_name", "channel_code", "status"]
lines = [",".join(fields)] lines = [",".join(fields)]
for r in rows: for r in rows:
position = position_map.get(r.position_id)
resolved_position_name = position.name if position and position.name else ""
resolved_channel_code = position.code if position and position.code else ""
resolved_agent_names = agent_map_by_position_id.get(r.position_id or -1, [])
vals = [] vals = []
for f in fields: for f in fields:
if f == "employee_name": if f == "employee_name":
vals.append(r.employee_name) vals.append(r.employee_name)
elif f == "position_name": elif f == "position_name":
vals.append(r.position_name) vals.append(resolved_position_name or "")
elif f == "channel_code": elif f == "channel_code":
vals.append(r.channel_code) vals.append(resolved_channel_code or "")
elif f == "status": elif f == "status":
vals.append(r.status) vals.append(r.status)
elif f == "agent_names": elif f == "agent_names":
vals.append(";".join(r.agent_names or [])) vals.append(";".join(resolved_agent_names))
else: else:
vals.append("") vals.append("")
lines.append(",".join(vals)) lines.append(",".join(vals))
...@@ -292,8 +324,3 @@ class QrcodeChannelService: ...@@ -292,8 +324,3 @@ class QrcodeChannelService:
raise ValueError("渠道活码不存在") raise ValueError("渠道活码不存在")
return qr return qr
@staticmethod
def _merge_agents(agent_ids: Optional[list[int]], agent_names: Optional[list[str]]) -> list[dict]:
ids = agent_ids or []
names = agent_names or []
return [{"id": aid, "name": (names[idx] if idx < len(names) else "")} for idx, aid in enumerate(ids)]
...@@ -94,20 +94,14 @@ class HttpChatCompletionsBatchDispatcher: ...@@ -94,20 +94,14 @@ class HttpChatCompletionsBatchDispatcher:
def _build_request_body(self, payload: dict[str, Any]) -> dict[str, Any]: def _build_request_body(self, payload: dict[str, Any]) -> dict[str, Any]:
group = payload.get("group") or {} group = payload.get("group") or {}
messages = payload.get("messages") or []
session_id = f"wecom_group_{group.get('group_contact_id') or 'unknown'}"
return { return {
"session_id": session_id,
"group": { "group": {
"group_contact_id": group.get("group_contact_id"), "group_contact_id": group.get("group_contact_id"),
"group_name": group.get("group_name"), "group_name": group.get("group_name"),
"bot_code": group.get("bot_code"),
}, },
"position": payload.get("position"),
"agents": [ "agents": [
{ {
"agent_id": item.get("agent_id"), "agent_id": item.get("agent_id"),
"agent_name": item.get("agent_name"),
"bot_id": item.get("bot_id"), "bot_id": item.get("bot_id"),
"is_steward": item.get("is_steward", False), "is_steward": item.get("is_steward", False),
} }
...@@ -123,7 +117,7 @@ class HttpChatCompletionsBatchDispatcher: ...@@ -123,7 +117,7 @@ class HttpChatCompletionsBatchDispatcher:
"msg_content": item.get("msg_content") or "", "msg_content": item.get("msg_content") or "",
"payload": item.get("payload") or {}, "payload": item.get("payload") or {},
} }
for item in messages for item in (payload.get("messages") or [])
], ],
} }
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!