Commit 96e2b5d4 by imwangxiaozhou

feat(backend): 新增多类功能并优化后台配置与业务逻辑

- 新增下游聊天服务配置,调整服务端口为8082,新增统一启动脚本优化部署流程
- 新增员工活码管理功能,包括数据库表、API接口与业务逻辑重构
- 新增建群后自动发送欢迎语的能力,完善企微消息调用链路
- 优化官网站点的agent展示与活码选择逻辑,调整媒体上传校验规则
- 重构定时任务调度器,支持秒级定时配置并优化日志输出
- 调整二维码渠道更新的schema,新增状态校验字段
1 parent 1e9ff34b
Showing 26 changed files with 560 additions and 98 deletions
...@@ -19,9 +19,12 @@ RUN pip install --no-cache-dir -r requirements.txt ...@@ -19,9 +19,12 @@ RUN pip install --no-cache-dir -r requirements.txt
COPY app/ ./app/ COPY app/ ./app/
COPY config/ ./config/ COPY config/ ./config/
COPY skills/ ./skills/ COPY skills/ ./skills/
COPY scripts/ ./scripts/
COPY sitecustomize.py ./ COPY sitecustomize.py ./
EXPOSE 8000 RUN chmod +x /app/scripts/start-dev.sh /app/scripts/start-prod.sh
# 开发模式:热重载 EXPOSE 8082
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]
# 开发模式:同容器内同时启动 Web 和 Scheduler
CMD ["sh", "/app/scripts/start-dev.sh"]
...@@ -28,14 +28,16 @@ COPY --from=builder /install /usr/local ...@@ -28,14 +28,16 @@ COPY --from=builder /install /usr/local
COPY app/ ./app/ COPY app/ ./app/
COPY config/ ./config/ COPY config/ ./config/
COPY skills/ ./skills/ COPY skills/ ./skills/
COPY scripts/ ./scripts/
COPY sitecustomize.py ./ COPY sitecustomize.py ./
# 创建非 root 用户并切换 # 创建非 root 用户并切换
RUN groupadd -r appuser && useradd -r -g appuser -d /app -s /sbin/nologin appuser \ RUN groupadd -r appuser && useradd -r -g appuser -d /app -s /sbin/nologin appuser \
&& chown -R appuser:appuser /app && chown -R appuser:appuser /app \
&& chmod +x /app/scripts/start-dev.sh /app/scripts/start-prod.sh
USER appuser USER appuser
EXPOSE 8000 EXPOSE 8082
# 生产模式:多进程,无热重载 # 生产模式:同容器内同时启动 Web 和 Scheduler
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4"] CMD ["sh", "/app/scripts/start-prod.sh"]
...@@ -3,7 +3,13 @@ from sqlalchemy.orm import Session ...@@ -3,7 +3,13 @@ from sqlalchemy.orm import Session
from app.infrastructure.database import get_db from app.infrastructure.database import get_db
from app.schema.common import ApiResponse, success_response_payload from app.schema.common import ApiResponse, success_response_payload
from app.schema.agent_group import EmployeeMountsResponse, EmployeeQrcodesResponse, PositionEmployeesResponse from app.schema.agent_group import (
EmployeeMountsResponse,
EmployeeQrcodesResponse,
PositionEmployeesResponse,
SaveEmployeeQrcodeRequest,
SaveEmployeeQrcodeResponse,
)
from app.service.agent_group_helper_service import ( from app.service.agent_group_helper_service import (
AgentGroupHelperService, AgentGroupHelperService,
PositionNotFoundError, PositionNotFoundError,
...@@ -54,6 +60,25 @@ def get_employee_qrcodes( ...@@ -54,6 +60,25 @@ def get_employee_qrcodes(
) )
@router.put(
"/employee/{employee_id}/qrcode",
response_model=ApiResponse[SaveEmployeeQrcodeResponse],
)
def save_employee_qrcode(
employee_id: str,
req: SaveEmployeeQrcodeRequest,
db: Session = Depends(get_db),
):
svc = AgentGroupHelperService(db, get_wecom_client())
try:
return success_response_payload(
200,
svc.save_employee_qrcode(employee_id, req.qrcode_url).model_dump(mode="json"),
)
except ValueError as exc:
raise HTTPException(status_code=404, detail=str(exc))
@router.get( @router.get(
"/employees/mounts", "/employees/mounts",
response_model=ApiResponse[EmployeeMountsResponse], response_model=ApiResponse[EmployeeMountsResponse],
......
...@@ -4,6 +4,7 @@ from sqlalchemy.orm import Session ...@@ -4,6 +4,7 @@ from sqlalchemy.orm import Session
from app.infrastructure.database import get_db from app.infrastructure.database import get_db
from app.infrastructure.shared_cache import shared_h5_cache from app.infrastructure.shared_cache import shared_h5_cache
from app.schema.official_site_agent_display import ( from app.schema.official_site_agent_display import (
AgentDisplayDetailResponse,
AvailableAgentsResponse, AvailableAgentsResponse,
ConfiguredAgentsResponse, ConfiguredAgentsResponse,
DeleteAgentConfigResponse, DeleteAgentConfigResponse,
...@@ -24,6 +25,15 @@ def list_available_agents(tab_id: int, db: Session = Depends(get_db)): ...@@ -24,6 +25,15 @@ def list_available_agents(tab_id: int, db: Session = Depends(get_db)):
raise HTTPException(status_code=404, detail=str(e)) raise HTTPException(status_code=404, detail=str(e))
@router.get("/api/v1/official-site/agent-displays/{display_id}", response_model=AgentDisplayDetailResponse)
def get_agent_display_detail(display_id: int, db: Session = Depends(get_db)):
svc = OfficialSiteAgentDisplayService(db, shared_h5_cache)
try:
return svc.get_display_detail(display_id)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
@router.post("/api/v1/official-site/agent-displays/{display_id}/config", response_model=SaveAgentConfigResponse) @router.post("/api/v1/official-site/agent-displays/{display_id}/config", response_model=SaveAgentConfigResponse)
def save_agent_config(display_id: int, req: SaveAgentConfigRequest, db: Session = Depends(get_db)): def save_agent_config(display_id: int, req: SaveAgentConfigRequest, db: Session = Depends(get_db)):
svc = OfficialSiteAgentDisplayService(db, shared_h5_cache) svc = OfficialSiteAgentDisplayService(db, shared_h5_cache)
......
...@@ -93,10 +93,11 @@ def update_tab_status(tab_id: int, req: UpdateTabStatusRequest, db: Session = De ...@@ -93,10 +93,11 @@ def update_tab_status(tab_id: int, req: UpdateTabStatusRequest, db: Session = De
@router.get("/qrcodes/available", response_model=ApiResponse[AvailableQrcodeListResponse]) @router.get("/qrcodes/available", response_model=ApiResponse[AvailableQrcodeListResponse])
def list_available_qrcodes( def list_available_qrcodes(
position_code: Optional[str] = Query(None), position_code: Optional[str] = Query(None),
tab_id: Optional[int] = Query(None),
db: Session = Depends(get_db), db: Session = Depends(get_db),
): ):
svc = OfficialSiteTabService(db, shared_h5_cache) svc = OfficialSiteTabService(db, shared_h5_cache)
return success_response_payload( return success_response_payload(
200, 200,
svc.list_available_qrcodes(position_code=position_code).model_dump(mode="json"), svc.list_available_qrcodes(position_code=position_code, tab_id=tab_id).model_dump(mode="json"),
) )
...@@ -55,6 +55,8 @@ def create_qrcode(req: QrcodeCreateRequest, db: Session = Depends(get_db), wecom ...@@ -55,6 +55,8 @@ def create_qrcode(req: QrcodeCreateRequest, db: Session = Depends(get_db), wecom
raise HTTPException(status_code=409, detail=msg) raise HTTPException(status_code=409, detail=msg)
if msg == "员工不存在": if msg == "员工不存在":
raise HTTPException(status_code=400, detail=msg) raise HTTPException(status_code=400, detail=msg)
if msg == "承接员工活码不存在":
raise HTTPException(status_code=400, detail=msg)
raise HTTPException(status_code=400, detail=msg) raise HTTPException(status_code=400, detail=msg)
......
...@@ -34,6 +34,11 @@ class WeComSyncSettings(BaseModel): ...@@ -34,6 +34,11 @@ class WeComSyncSettings(BaseModel):
api_key: str = "" api_key: str = ""
class DownstreamChatSettings(BaseModel):
host: str = "127.0.0.1"
port: int = 8000
class OSSSettings(BaseModel): class OSSSettings(BaseModel):
access_key_id: str = "" access_key_id: str = ""
access_key_secret: str = "" access_key_secret: str = ""
...@@ -43,14 +48,15 @@ class OSSSettings(BaseModel): ...@@ -43,14 +48,15 @@ class OSSSettings(BaseModel):
class SchedulerJobSettings(BaseModel): class SchedulerJobSettings(BaseModel):
minutes: int seconds: int | None = None
minutes: int | None = None
class SchedulerSettings(BaseModel): class SchedulerSettings(BaseModel):
jobs: dict[str, SchedulerJobSettings] = { jobs: dict[str, SchedulerJobSettings] = {
"sync_wecom_bots_groups_messages": SchedulerJobSettings(minutes=10), "sync_wecom_bots_groups_messages": SchedulerJobSettings(seconds=10),
"sync_customer_groups": SchedulerJobSettings(minutes=2), "sync_customer_groups": SchedulerJobSettings(seconds=10),
"dispatch_customer_group_messages": SchedulerJobSettings(minutes=1), "dispatch_customer_group_messages": SchedulerJobSettings(seconds=10),
} }
...@@ -60,5 +66,6 @@ class Settings(BaseModel): ...@@ -60,5 +66,6 @@ class Settings(BaseModel):
server: ServerSettings = ServerSettings() server: ServerSettings = ServerSettings()
im: IMSettings = IMSettings() im: IMSettings = IMSettings()
wecom_sync: WeComSyncSettings = WeComSyncSettings() wecom_sync: WeComSyncSettings = WeComSyncSettings()
downstream_chat: DownstreamChatSettings = DownstreamChatSettings()
oss: OSSSettings = OSSSettings() oss: OSSSettings = OSSSettings()
scheduler: SchedulerSettings = SchedulerSettings() scheduler: SchedulerSettings = SchedulerSettings()
...@@ -246,6 +246,27 @@ def ensure_runtime_schema(engine) -> None: ...@@ -246,6 +246,27 @@ def ensure_runtime_schema(engine) -> None:
if "position_name" in qrcode_columns or "channel_code" in qrcode_columns or "agent_names" in qrcode_columns: 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) _rebuild_qrcode_channels_without_redundant_position_fields(conn)
if "wecom_employee_qrcodes" not in table_names:
conn.execute(
text(
"""
CREATE TABLE wecom_employee_qrcodes (
id INTEGER PRIMARY KEY,
employee_id VARCHAR(100) NOT NULL UNIQUE,
qrcode_url VARCHAR(500) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL
)
"""
)
)
conn.execute(
text(
"CREATE UNIQUE INDEX IF NOT EXISTS uk_wecom_employee_qrcodes_employee_id "
"ON wecom_employee_qrcodes(employee_id)"
)
)
if "wecom_job_configs" not in table_names: if "wecom_job_configs" not in table_names:
conn.execute( conn.execute(
text( text(
......
...@@ -115,6 +115,24 @@ class HttpWeComSyncClient(WeComSyncClient): ...@@ -115,6 +115,24 @@ class HttpWeComSyncClient(WeComSyncClient):
def get_task(self, *, task_id: str) -> dict[str, Any]: def get_task(self, *, task_id: str) -> dict[str, Any]:
return self._get(f"/api/v1/business/tasks/{task_id}", {}) return self._get(f"/api/v1/business/tasks/{task_id}", {})
def send_message(
self,
*,
contact_id: str,
content: str,
msg_type: str,
bot_id: str,
biz_rela_no: str,
) -> dict[str, Any]:
payload: dict[str, Any] = {
"contact_id": contact_id,
"content": content,
"msg_type": msg_type,
"bot_id": bot_id,
"biz_rela_no": biz_rela_no,
}
return self._post("/api/v1/business/messages/send", payload)
def _get(self, path: str, params: dict[str, Any]) -> dict[str, Any]: def _get(self, path: str, params: dict[str, Any]) -> dict[str, Any]:
headers = {"Content-Type": "application/json"} headers = {"Content-Type": "application/json"}
if self.api_key: if self.api_key:
......
...@@ -44,11 +44,17 @@ def load_job_specs() -> list[dict[str, int | str]]: ...@@ -44,11 +44,17 @@ def load_job_specs() -> list[dict[str, int | str]]:
specs: list[dict[str, int | str]] = [] specs: list[dict[str, int | str]] = []
for default_spec in DEFAULT_JOB_SPECS: for default_spec in DEFAULT_JOB_SPECS:
job_key = str(default_spec["job_key"]) job_key = str(default_spec["job_key"])
minutes = default_spec["minutes"] trigger_value = int(default_spec["minutes"])
trigger_unit = "minutes"
job_settings = settings.scheduler.jobs.get(job_key) job_settings = settings.scheduler.jobs.get(job_key)
if job_settings is not None: if job_settings is not None:
minutes = job_settings.minutes if job_settings.seconds is not None:
specs.append({"job_key": job_key, "minutes": minutes}) trigger_value = job_settings.seconds
trigger_unit = "seconds"
elif job_settings.minutes is not None:
trigger_value = job_settings.minutes
trigger_unit = "minutes"
specs.append({"job_key": job_key, "trigger_unit": trigger_unit, "trigger_value": trigger_value})
return specs return specs
...@@ -56,15 +62,16 @@ def build_scheduler() -> BlockingScheduler: ...@@ -56,15 +62,16 @@ def build_scheduler() -> BlockingScheduler:
scheduler = BlockingScheduler(timezone="Asia/Shanghai") scheduler = BlockingScheduler(timezone="Asia/Shanghai")
job_specs = load_job_specs() job_specs = load_job_specs()
for spec in job_specs: for spec in job_specs:
interval_kwargs = {str(spec["trigger_unit"]): int(spec["trigger_value"])}
scheduler.add_job( scheduler.add_job(
run_job, run_job,
"interval", "interval",
minutes=spec["minutes"],
args=[spec["job_key"]], args=[spec["job_key"]],
id=spec["job_key"], id=spec["job_key"],
replace_existing=True, replace_existing=True,
max_instances=1, max_instances=1,
coalesce=True, coalesce=True,
**interval_kwargs,
) )
scheduler.add_listener(_job_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR) scheduler.add_listener(_job_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)
return scheduler return scheduler
...@@ -76,10 +83,11 @@ def main() -> None: ...@@ -76,10 +83,11 @@ def main() -> None:
logger.info("APScheduler starting,当前将注册 3 类任务:同步机器人与客户群消息 / 同步一客一群建群编排 / 分发客户群消息到下游") logger.info("APScheduler starting,当前将注册 3 类任务:同步机器人与客户群消息 / 同步一客一群建群编排 / 分发客户群消息到下游")
for spec in job_specs: for spec in job_specs:
logger.info( logger.info(
"Registered job: job_key=%s task=%s interval_minutes=%s", "Registered job: job_key=%s task=%s interval_%s=%s",
spec["job_key"], spec["job_key"],
JOB_NAME_MAP.get(str(spec["job_key"]), str(spec["job_key"])), JOB_NAME_MAP.get(str(spec["job_key"]), str(spec["job_key"])),
spec["minutes"], spec["trigger_unit"],
spec["trigger_value"],
) )
scheduler.start() scheduler.start()
......
...@@ -25,3 +25,13 @@ class QrcodeChannel(Base): ...@@ -25,3 +25,13 @@ class QrcodeChannel(Base):
UniqueConstraint("position_id", name="uk_qrcode_position_id"), UniqueConstraint("position_id", name="uk_qrcode_position_id"),
UniqueConstraint("wecom_bot_id", name="uk_qrcode_wecom_bot_id"), UniqueConstraint("wecom_bot_id", name="uk_qrcode_wecom_bot_id"),
) )
class WeComEmployeeQrcode(Base):
__tablename__ = "wecom_employee_qrcodes"
id = Column(Integer, primary_key=True, index=True)
employee_id = Column(String(100), nullable=False, unique=True, index=True)
qrcode_url = Column(String(500), nullable=False)
created_at = Column(DateTime, server_default=func.now(), nullable=False)
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
from datetime import datetime from datetime import datetime
from typing import List from typing import List, Optional
from pydantic import BaseModel from pydantic import BaseModel
...@@ -18,17 +18,25 @@ class PositionEmployeesResponse(BaseModel): ...@@ -18,17 +18,25 @@ class PositionEmployeesResponse(BaseModel):
class EmployeeQrcode(BaseModel): class EmployeeQrcode(BaseModel):
qrcode_id: int employee_id: str
position_name: str qrcode_url: str
channel_code: str
status: str
created_at: datetime created_at: datetime
updated_at: datetime
class EmployeeQrcodesResponse(BaseModel): class EmployeeQrcodesResponse(BaseModel):
employee_name: str employee_name: str
qrcode_count: int qrcode: Optional[EmployeeQrcode] = None
qrcodes: List[EmployeeQrcode]
class SaveEmployeeQrcodeRequest(BaseModel):
qrcode_url: str
class SaveEmployeeQrcodeResponse(BaseModel):
employee_id: str
qrcode_url: str
updated_at: datetime
class EmployeeMountedAgent(BaseModel): class EmployeeMountedAgent(BaseModel):
......
...@@ -15,6 +15,8 @@ class AvailableAgentItem(BaseModel): ...@@ -15,6 +15,8 @@ class AvailableAgentItem(BaseModel):
icon_url: Optional[str] = None icon_url: Optional[str] = None
media_url: Optional[str] = None media_url: Optional[str] = None
summary: Optional[str] = None summary: Optional[str] = None
speech_title: Optional[str] = None
speech_content: Optional[str] = None
display_status: str = Field("enable", description="官网展示状态,来源于 official_site_agent_display.display_status。") display_status: str = Field("enable", description="官网展示状态,来源于 official_site_agent_display.display_status。")
agent_status: str = Field("enable", description="Agent 状态快照,来源于 official_site_agent_display.status。") agent_status: str = Field("enable", description="Agent 状态快照,来源于 official_site_agent_display.status。")
...@@ -38,7 +40,6 @@ class SaveAgentConfigRequest(BaseModel): ...@@ -38,7 +40,6 @@ class SaveAgentConfigRequest(BaseModel):
media_type: str = Field(..., description="素材类型,支持 jpg/jpeg/png/webp/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_content: str = Field(..., description="展示话术内容。") speech_content: str = Field(..., description="展示话术内容。")
sort_order: int = Field(0, description="当前 Tab 下的展示排序,越小越靠前。") sort_order: int = Field(0, description="当前 Tab 下的展示排序,越小越靠前。")
display_status: str = Field("enable", pattern=r"^(enable|disable)$", description="官网展示状态,写入 official_site_agent_display.display_status。") display_status: str = Field("enable", pattern=r"^(enable|disable)$", description="官网展示状态,写入 official_site_agent_display.display_status。")
...@@ -53,6 +54,25 @@ class SaveAgentConfigResponse(BaseModel): ...@@ -53,6 +54,25 @@ class SaveAgentConfigResponse(BaseModel):
updated_at: datetime updated_at: datetime
class AgentDisplayDetailResponse(BaseModel):
display_id: int
tab_id: int
agent_id: int
agent_name: str
agent_code: str
media_url: Optional[str]
media_type: Optional[str]
icon_url: Optional[str] = None
speech_title: Optional[str] = None
speech_content: Optional[str] = None
sort_order: int
agent_status: str
display_status: str
summary: Optional[str] = None
updated_at: datetime
created_at: datetime
class ConfiguredAgentItem(BaseModel): class ConfiguredAgentItem(BaseModel):
config_id: int config_id: int
agent_id: int agent_id: int
......
...@@ -26,7 +26,7 @@ class QrcodeCreateResponse(BaseModel): ...@@ -26,7 +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 status: str = Field(..., pattern=r"^(enable|disable)$")
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)
......
...@@ -3,7 +3,7 @@ from typing import Protocol ...@@ -3,7 +3,7 @@ from typing import Protocol
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from app.model.agent import Agent from app.model.agent import Agent
from app.model.agent_group import QrcodeChannel from app.model.agent_group import QrcodeChannel, WeComEmployeeQrcode
from app.model.position_tag import PositionTag, PositionTagUser from app.model.position_tag import PositionTag, PositionTagUser
from app.model.wecom_sync import WeComBot from app.model.wecom_sync import WeComBot
from app.schema.agent_group import ( from app.schema.agent_group import (
...@@ -15,6 +15,7 @@ from app.schema.agent_group import ( ...@@ -15,6 +15,7 @@ from app.schema.agent_group import (
EmployeeQrcode, EmployeeQrcode,
EmployeeQrcodesResponse, EmployeeQrcodesResponse,
PositionEmployeesResponse, PositionEmployeesResponse,
SaveEmployeeQrcodeResponse,
) )
...@@ -148,31 +149,47 @@ class AgentGroupHelperService: ...@@ -148,31 +149,47 @@ class AgentGroupHelperService:
) )
def list_employee_qrcodes(self, employee_id: str) -> EmployeeQrcodesResponse: def list_employee_qrcodes(self, employee_id: str) -> EmployeeQrcodesResponse:
rows = ( bot = self.db.query(WeComBot).filter(WeComBot.bot_id == employee_id).first()
self.db.query(QrcodeChannel) employee_name = bot.bot_name or "" if bot else ""
.filter(QrcodeChannel.employee_id == employee_id) row = (
.order_by(QrcodeChannel.id.asc()) self.db.query(WeComEmployeeQrcode)
.all() .filter(WeComEmployeeQrcode.employee_id == employee_id)
.first()
) )
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 ""
qrcodes = [
EmployeeQrcode(
qrcode_id=row.id,
position_name=position_map.get(row.position_id).name if position_map.get(row.position_id) else "",
channel_code=position_map.get(row.position_id).code if position_map.get(row.position_id) else "",
status=row.status,
created_at=row.created_at,
)
for row in rows
]
return EmployeeQrcodesResponse( return EmployeeQrcodesResponse(
employee_name=employee_name, employee_name=employee_name,
qrcode_count=len(qrcodes), qrcode=EmployeeQrcode(
qrcodes=qrcodes, employee_id=row.employee_id,
qrcode_url=row.qrcode_url,
created_at=row.created_at,
updated_at=row.updated_at,
)
if row
else None,
)
def save_employee_qrcode(self, employee_id: str, qrcode_url: str) -> SaveEmployeeQrcodeResponse:
bot = self.db.query(WeComBot).filter(WeComBot.bot_id == employee_id).first()
if not bot or not bot.bot_id:
raise ValueError("员工不存在")
record = (
self.db.query(WeComEmployeeQrcode)
.filter(WeComEmployeeQrcode.employee_id == employee_id)
.first()
)
if record is None:
record = WeComEmployeeQrcode(employee_id=employee_id, qrcode_url=qrcode_url)
self.db.add(record)
else:
record.qrcode_url = qrcode_url
self.db.commit()
self.db.refresh(record)
return SaveEmployeeQrcodeResponse(
employee_id=record.employee_id,
qrcode_url=record.qrcode_url,
updated_at=record.updated_at,
) )
def list_employee_mounts(self) -> EmployeeMountsResponse: def list_employee_mounts(self) -> EmployeeMountsResponse:
......
...@@ -6,10 +6,11 @@ from sqlalchemy.orm import Session as OrmSession ...@@ -6,10 +6,11 @@ from sqlalchemy.orm import Session as OrmSession
from app.infrastructure.h5_cache import H5CacheManager 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, AgentPosition
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, PositionTag from app.model.position_tag import OfficialTab, PositionTag
from app.schema.official_site_agent_display import ( from app.schema.official_site_agent_display import (
AgentDisplayDetailResponse,
AvailableAgentItem, AvailableAgentItem,
AvailableAgentsResponse, AvailableAgentsResponse,
ConfiguredAgentItem, ConfiguredAgentItem,
...@@ -21,9 +22,7 @@ from app.schema.official_site_agent_display import ( ...@@ -21,9 +22,7 @@ from app.schema.official_site_agent_display import (
) )
_STEWARD_CODE = "steward" _STEWARD_CODE = "steward"
_ALLOWED_MEDIA_TYPES = {"gif", "mp4"}
_MAX_MEDIA_SIZE = 20971520 _MAX_MEDIA_SIZE = 20971520
_MAX_SPEECH_TITLE_LEN = 100
_MAX_SPEECH_CONTENT_LEN = 200 _MAX_SPEECH_CONTENT_LEN = 200
...@@ -40,6 +39,8 @@ class OfficialSiteAgentDisplayService: ...@@ -40,6 +39,8 @@ class OfficialSiteAgentDisplayService:
if not tab: if not tab:
raise ValueError("Tab不存在") raise ValueError("Tab不存在")
self._sync_tab_display_agent_relations(tab)
rows = ( rows = (
self.db.query(OfficialSiteAgentDisplay) self.db.query(OfficialSiteAgentDisplay)
.filter(OfficialSiteAgentDisplay.tab_id == tab_id) .filter(OfficialSiteAgentDisplay.tab_id == tab_id)
...@@ -56,7 +57,7 @@ class OfficialSiteAgentDisplayService: ...@@ -56,7 +57,7 @@ class OfficialSiteAgentDisplayService:
AvailableAgentItem( AvailableAgentItem(
display_id=row.id, display_id=row.id,
agent_id=row.agent_id, agent_id=row.agent_id,
agent_name=row.agent_name, agent_name=agent.name if agent and agent.name else row.agent_name,
agent_code=agent.code if agent else "", agent_code=agent.code if agent else "",
is_configured=bool( is_configured=bool(
row.summary row.summary
...@@ -65,13 +66,15 @@ class OfficialSiteAgentDisplayService: ...@@ -65,13 +66,15 @@ class OfficialSiteAgentDisplayService:
or row.speech_title or row.speech_title
or row.speech_content or row.speech_content
), ),
configured_description=row.speech_title, configured_description=agent.name if agent and agent.name else row.speech_title,
is_steward=bool(agent.is_steward) if agent else False, is_steward=bool(agent.is_steward) if agent else False,
icon_url=row.icon_url, icon_url=row.icon_url,
media_url=row.media_url, media_url=row.media_url,
summary=row.summary, summary=row.summary,
speech_title=agent.name if agent and agent.name else row.speech_title,
speech_content=row.speech_content,
display_status=row.display_status, display_status=row.display_status,
agent_status=row.status, agent_status=agent.status.value if agent and agent.status else row.status,
) )
) )
...@@ -93,19 +96,39 @@ class OfficialSiteAgentDisplayService: ...@@ -93,19 +96,39 @@ class OfficialSiteAgentDisplayService:
steward_agent=steward_info, steward_agent=steward_info,
) )
def get_display_detail(self, display_id: int) -> AgentDisplayDetailResponse:
config = self.db.query(OfficialSiteAgentDisplay).filter(OfficialSiteAgentDisplay.id == display_id).first()
if not config:
raise ValueError("展示记录不存在")
agent = self.db.query(Agent).filter(Agent.id == config.agent_id, Agent.is_deleted == False).first()
return AgentDisplayDetailResponse(
display_id=config.id,
tab_id=config.tab_id,
agent_id=config.agent_id,
agent_name=agent.name if agent and agent.name else config.agent_name,
agent_code=agent.code if agent else "",
media_url=config.media_url,
media_type=config.media_type,
icon_url=config.icon_url,
speech_title=agent.name if agent and agent.name else config.speech_title,
speech_content=config.speech_content,
sort_order=config.sort_order,
agent_status=agent.status.value if agent and agent.status else config.status,
display_status=config.display_status,
summary=config.summary,
updated_at=config.updated_at,
created_at=config.created_at,
)
def save_config(self, display_id: int, req: SaveAgentConfigRequest) -> SaveAgentConfigResponse: def save_config(self, display_id: int, req: SaveAgentConfigRequest) -> SaveAgentConfigResponse:
if req.media_type not in _ALLOWED_MEDIA_TYPES:
raise ValueError(f"素材格式不支持,仅允许 {_ALLOWED_MEDIA_TYPES}")
if req.media_size > _MAX_MEDIA_SIZE: if req.media_size > _MAX_MEDIA_SIZE:
raise ValueError("素材大小超过 20MB 限制") raise ValueError("素材大小超过 20MB 限制")
if len(req.speech_title) > _MAX_SPEECH_TITLE_LEN:
raise ValueError("话术标题超过限制")
if len(req.speech_content) > _MAX_SPEECH_CONTENT_LEN: if len(req.speech_content) > _MAX_SPEECH_CONTENT_LEN:
raise ValueError("话术正文超过限制") raise ValueError("话术正文超过限制")
config = self.db.query(OfficialSiteAgentDisplay).filter( config = self.db.query(OfficialSiteAgentDisplay).filter(OfficialSiteAgentDisplay.id == display_id).first()
OfficialSiteAgentDisplay.id == display_id,
).first()
if not config: if not config:
raise ValueError("展示记录不存在") raise ValueError("展示记录不存在")
...@@ -118,7 +141,6 @@ class OfficialSiteAgentDisplayService: ...@@ -118,7 +141,6 @@ class OfficialSiteAgentDisplayService:
config.summary = req.summary config.summary = req.summary
config.display_status = req.display_status config.display_status = req.display_status
config.media_type = req.media_type config.media_type = req.media_type
config.speech_title = req.speech_title
config.speech_content = req.speech_content config.speech_content = req.speech_content
config.sort_order = req.sort_order config.sort_order = req.sort_order
...@@ -146,29 +168,29 @@ class OfficialSiteAgentDisplayService: ...@@ -146,29 +168,29 @@ class OfficialSiteAgentDisplayService:
.all() .all()
) )
items = [ items = []
ConfiguredAgentItem( for config in configs:
config_id=c.id, agent = self.db.query(Agent).filter(Agent.id == config.agent_id, Agent.is_deleted == False).first()
agent_id=c.agent_id, items.append(
agent_name=c.agent_name, ConfiguredAgentItem(
media_url=c.media_url, config_id=config.id,
media_type=c.media_type, agent_id=config.agent_id,
icon_url=c.icon_url, agent_name=agent.name if agent and agent.name else config.agent_name,
speech_title=c.speech_title, media_url=config.media_url,
speech_content=c.speech_content, media_type=config.media_type,
sort_order=c.sort_order, icon_url=config.icon_url,
agent_status=c.status, speech_title=agent.name if agent and agent.name else config.speech_title,
display_status=c.display_status, speech_content=config.speech_content,
summary=c.summary, sort_order=config.sort_order,
agent_status=agent.status.value if agent and agent.status else config.status,
display_status=config.display_status,
summary=config.summary,
)
) )
for c in configs
]
return ConfiguredAgentsResponse(tab_id=tab_id, configured_agents=items) return ConfiguredAgentsResponse(tab_id=tab_id, configured_agents=items)
def delete_config(self, display_id: int) -> DeleteAgentConfigResponse: def delete_config(self, display_id: int) -> DeleteAgentConfigResponse:
config = self.db.query(OfficialSiteAgentDisplay).filter( config = self.db.query(OfficialSiteAgentDisplay).filter(OfficialSiteAgentDisplay.id == display_id).first()
OfficialSiteAgentDisplay.id == display_id,
).first()
if not config: if not config:
raise ValueError("配置不存在") raise ValueError("配置不存在")
...@@ -185,3 +207,63 @@ class OfficialSiteAgentDisplayService: ...@@ -185,3 +207,63 @@ class OfficialSiteAgentDisplayService:
self.cache.invalidate_home_page() self.cache.invalidate_home_page()
return DeleteAgentConfigResponse(success=True, deleted_at=datetime.now(timezone.utc)) return DeleteAgentConfigResponse(success=True, deleted_at=datetime.now(timezone.utc))
def _sync_tab_display_agent_relations(self, tab: OfficialTab) -> None:
position_id = tab.position_id
if position_id is None:
self.db.query(OfficialSiteAgentDisplay).filter(OfficialSiteAgentDisplay.tab_id == tab.id).delete()
self.db.commit()
return
agents = (
self.db.query(Agent)
.join(AgentPosition, AgentPosition.agent_id == Agent.id)
.filter(
AgentPosition.position_id == position_id,
Agent.is_deleted == False,
Agent.code != _STEWARD_CODE,
)
.order_by(Agent.id.asc())
.all()
)
existing = (
self.db.query(OfficialSiteAgentDisplay)
.filter(OfficialSiteAgentDisplay.tab_id == tab.id)
.all()
)
existing_by_agent = {item.agent_id: item for item in existing}
valid_agent_ids = {agent.id for agent in agents}
changed = False
for item in existing:
if item.agent_id not in valid_agent_ids:
self.db.delete(item)
changed = True
for agent in agents:
row = existing_by_agent.get(agent.id)
if row is None:
self.db.add(
OfficialSiteAgentDisplay(
tab_id=tab.id,
agent_id=agent.id,
agent_name=agent.name or "",
status=agent.status.value if agent.status else "enable",
display_status="enable",
sort_order=0,
)
)
changed = True
else:
new_name = agent.name or row.agent_name
new_status = agent.status.value if agent.status else row.status
if row.agent_name != new_name:
row.agent_name = new_name
changed = True
if row.status != new_status:
row.status = new_status
changed = True
if changed:
self.db.commit()
...@@ -230,6 +230,7 @@ class OfficialSiteTabService: ...@@ -230,6 +230,7 @@ class OfficialSiteTabService:
def list_available_qrcodes( def list_available_qrcodes(
self, self,
position_code: Optional[str] = None, position_code: Optional[str] = None,
tab_id: Optional[int] = None,
) -> AvailableQrcodeListResponse: ) -> AvailableQrcodeListResponse:
query = self.db.query(QrcodeChannel).filter(QrcodeChannel.status == "enable") query = self.db.query(QrcodeChannel).filter(QrcodeChannel.status == "enable")
if position_code: if position_code:
...@@ -237,6 +238,24 @@ class OfficialSiteTabService: ...@@ -237,6 +238,24 @@ class OfficialSiteTabService:
PositionTag.code == position_code PositionTag.code == position_code
) )
bound_qrcode_ids = {
row.qrcode_id
for row in self.db.query(OfficialTab.qrcode_id)
.filter(OfficialTab.deleted_at.is_(None), OfficialTab.qrcode_id.isnot(None))
.all()
if row.qrcode_id is not None
}
current_tab_qrcode_id = None
if tab_id is not None:
current_tab = self._get_or_404(tab_id)
current_tab_qrcode_id = current_tab.qrcode_id
if current_tab_qrcode_id is not None and current_tab_qrcode_id in bound_qrcode_ids:
bound_qrcode_ids.remove(current_tab_qrcode_id)
if bound_qrcode_ids:
query = query.filter(~QrcodeChannel.id.in_(bound_qrcode_ids))
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}) 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 [] positions = self.db.query(PositionTag).filter(PositionTag.id.in_(position_ids)).all() if position_ids else []
......
...@@ -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", "png", "jpg", "jpeg", "webp"}, "max_size": 20 * 1024 * 1024, "dir": "agent"}, "agent_media": {"exts": None, "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"},
...@@ -25,7 +25,7 @@ class OfficialSiteUploadService: ...@@ -25,7 +25,7 @@ class OfficialSiteUploadService:
raise ValueError(f"不支持的上传类型: {usage_type}") raise ValueError(f"不支持的上传类型: {usage_type}")
ext = _get_extension(file_name) ext = _get_extension(file_name)
if ext not in rules["exts"]: if rules["exts"] is not None and ext not in rules["exts"]:
raise ValueError(f"文件格式不支持,仅允许 {rules['exts']}") raise ValueError(f"文件格式不支持,仅允许 {rules['exts']}")
if len(file_data) > rules["max_size"]: if len(file_data) > rules["max_size"]:
......
...@@ -8,7 +8,7 @@ from sqlalchemy.orm import Session as OrmSession ...@@ -8,7 +8,7 @@ from sqlalchemy.orm import Session as OrmSession
from app.infrastructure.file_parser import OSSClient from app.infrastructure.file_parser import OSSClient
from app.model.agent import Agent, AgentPosition, AgentStatus from app.model.agent import Agent, AgentPosition, AgentStatus
from app.model.agent_group import QrcodeChannel from app.model.agent_group import QrcodeChannel, WeComEmployeeQrcode
from app.model.position_tag import PositionTag from app.model.position_tag import PositionTag
from app.model.wecom_sync import WeComBot from app.model.wecom_sync import WeComBot
from app.schema.qrcode_channel import ( from app.schema.qrcode_channel import (
...@@ -37,6 +37,18 @@ class QrcodeChannelService: ...@@ -37,6 +37,18 @@ class QrcodeChannelService:
return None return None
return self.db.query(PositionTag).filter(PositionTag.id == position_id).first() return self.db.query(PositionTag).filter(PositionTag.id == position_id).first()
def _get_employee_qrcode_url(self, employee_id: Optional[str]) -> Optional[str]:
if not employee_id:
return None
row = (
self.db.query(WeComEmployeeQrcode)
.filter(WeComEmployeeQrcode.employee_id == employee_id)
.first()
)
if row and row.qrcode_url:
return row.qrcode_url
return None
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:
...@@ -78,8 +90,15 @@ class QrcodeChannelService: ...@@ -78,8 +90,15 @@ class QrcodeChannelService:
agent_ids = [a.id for a in agent_list] agent_ids = [a.id for a in agent_list]
agent_names = [a.name for a in agent_list] agent_names = [a.name for a in agent_list]
channel_code = position.code employee_qrcode = (
qrcode_url = self.wecom.create_qrcode(channel_code, req.welcome_message or "") self.db.query(WeComEmployeeQrcode)
.filter(WeComEmployeeQrcode.employee_id == employee_id)
.first()
)
if employee_qrcode is None or not employee_qrcode.qrcode_url:
raise ValueError("承接员工活码不存在")
qrcode_url = employee_qrcode.qrcode_url
qr = QrcodeChannel( qr = QrcodeChannel(
qrcode_name=req.qrcode_name, qrcode_name=req.qrcode_name,
...@@ -111,6 +130,9 @@ class QrcodeChannelService: ...@@ -111,6 +130,9 @@ class QrcodeChannelService:
def update(self, qrcode_id: int, req) -> QrcodeUpdateResponse: def update(self, qrcode_id: int, req) -> QrcodeUpdateResponse:
qr = self._get_or_404(qrcode_id) qr = self._get_or_404(qrcode_id)
qr.qrcode_name = req.qrcode_name qr.qrcode_name = req.qrcode_name
qr.status = req.status
if req.status == "enable":
qr.disable_reason = None
qr.remark = req.remark qr.remark = req.remark
qr.welcome_message = req.welcome_message qr.welcome_message = req.welcome_message
self.db.commit() self.db.commit()
...@@ -146,7 +168,7 @@ class QrcodeChannelService: ...@@ -146,7 +168,7 @@ class QrcodeChannelService:
employee_name=qr.employee_name, employee_name=qr.employee_name,
position_name=position.name if position and position.name else "", position_name=position.name if position and position.name else "",
channel_code=position.code if position and position.code else "", channel_code=position.code if position and position.code else "",
qrcode_url=qr.qrcode_url, qrcode_url=self._get_employee_qrcode_url(qr.employee_id),
agent_ids=agent_ids, agent_ids=agent_ids,
agent_names=agent_names, agent_names=agent_names,
remark=qr.remark, remark=qr.remark,
...@@ -214,7 +236,7 @@ class QrcodeChannelService: ...@@ -214,7 +236,7 @@ class QrcodeChannelService:
employee_name=r.employee_name, employee_name=r.employee_name,
position_name=position.name if position and position.name else "", position_name=position.name if position and position.name else "",
channel_code=position.code if position and position.code else "", channel_code=position.code if position and position.code else "",
qrcode_url=r.qrcode_url, qrcode_url=self._get_employee_qrcode_url(r.employee_id),
agent_count=len(agent_list), agent_count=len(agent_list),
agent_names_preview=agent_names, agent_names_preview=agent_names,
status=r.status, status=r.status,
......
...@@ -67,10 +67,10 @@ class NoopGroupMessageBatchDispatcher: ...@@ -67,10 +67,10 @@ class NoopGroupMessageBatchDispatcher:
class HttpChatCompletionsBatchDispatcher: class HttpChatCompletionsBatchDispatcher:
def __init__(self, base_url: str | None = None, timeout_seconds: float = 30.0) -> None: def __init__(self, base_url: str | None = None, timeout_seconds: float = 30.0) -> None:
settings = ConfigLoader().load_settings() settings = ConfigLoader().load_settings()
host = os.getenv("DOWNSTREAM_CHAT_HOST") or settings.server.host or "127.0.0.1" host = os.getenv("DOWNSTREAM_CHAT_HOST") or settings.downstream_chat.host or "127.0.0.1"
if host in {"0.0.0.0", "::", ""}: if host in {"0.0.0.0", "::", ""}:
host = "127.0.0.1" host = "127.0.0.1"
port = int(os.getenv("DOWNSTREAM_CHAT_PORT") or settings.server.port) port = int(os.getenv("DOWNSTREAM_CHAT_PORT") or settings.downstream_chat.port)
resolved_base_url = base_url or f"http://{host}:{port}" resolved_base_url = base_url or f"http://{host}:{port}"
self.base_url = resolved_base_url.rstrip("/") self.base_url = resolved_base_url.rstrip("/")
self.timeout_seconds = timeout_seconds self.timeout_seconds = timeout_seconds
...@@ -110,17 +110,30 @@ class HttpChatCompletionsBatchDispatcher: ...@@ -110,17 +110,30 @@ class HttpChatCompletionsBatchDispatcher:
"messages": [ "messages": [
{ {
"msg_id": item.get("msg_id"), "msg_id": item.get("msg_id"),
"msg_time": item.get("msg_time"), "msg_time": self._serialize_msg_time(item.get("msg_time")),
"sender_id": item.get("sender_id"), "sender_id": item.get("sender_id"),
"sender_name": item.get("sender_name"), "sender_name": item.get("sender_name"),
"msg_type": item.get("msg_type"), "msg_type": item.get("msg_type"),
"msg_content": item.get("msg_content") or "", "msg_content": item.get("msg_content") or "",
"payload": item.get("payload") or {}, "payload": {},
} }
for item in (payload.get("messages") or []) for item in (payload.get("messages") or [])
], ],
} }
def _serialize_msg_time(self, value: Any) -> str:
if isinstance(value, datetime):
normalized = value.astimezone(timezone.utc) if value.tzinfo else value.replace(tzinfo=timezone.utc)
return normalized.isoformat().replace("+00:00", "Z")
if isinstance(value, str):
try:
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
normalized = parsed.astimezone(timezone.utc) if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
return normalized.isoformat().replace("+00:00", "Z")
except ValueError:
return value
return str(value or "")
@dataclass @dataclass
class ResolvedCustomerGroupBinding: class ResolvedCustomerGroupBinding:
...@@ -228,6 +241,7 @@ class WeComCustomerGroupOrchestrationService: ...@@ -228,6 +241,7 @@ class WeComCustomerGroupOrchestrationService:
continue continue
self._upsert_customer_group_from_request(request) self._upsert_customer_group_from_request(request)
self._send_group_welcome_message_once(request)
processed += 1 processed += 1
if processed: if processed:
...@@ -443,7 +457,7 @@ class WeComCustomerGroupOrchestrationService: ...@@ -443,7 +457,7 @@ class WeComCustomerGroupOrchestrationService:
customer_name=None, customer_name=None,
qrcode_id=qrcode.id if qrcode else 0, qrcode_id=qrcode.id if qrcode else 0,
qrcode_name=qrcode.qrcode_name if qrcode else None, qrcode_name=qrcode.qrcode_name if qrcode else None,
channel_code=qrcode.channel_code if qrcode else "", channel_code=position.code if position and position.code else "",
position_id=position.id if position else 0, position_id=position.id if position else 0,
position_code=position.code if position else "", position_code=position.code if position else "",
position_name=position.name if position else "", position_name=position.name if position else "",
...@@ -484,6 +498,18 @@ class WeComCustomerGroupOrchestrationService: ...@@ -484,6 +498,18 @@ class WeComCustomerGroupOrchestrationService:
biz_rela_no = f"biz-group-{int(_utcnow().timestamp() * 1000)}-{uuid4().hex[:6]}" biz_rela_no = f"biz-group-{int(_utcnow().timestamp() * 1000)}-{uuid4().hex[:6]}"
group_name = self._build_group_name(item.customer_name, item.contact_id) group_name = self._build_group_name(item.customer_name, item.contact_id)
logger.info(
format_job_log(
"机器人[%s]:我准备发起建群啦!!客户=%s(%s),群名=%s,群成员=%s"
% (
bot.bot_name or bot.bot_id,
item.customer_name or "-",
item.contact_id,
group_name,
", ".join(resolved_member_list) or "-",
)
)
)
task_payload = self.client.create_group( task_payload = self.client.create_group(
bot_code=bot.bot_code, bot_code=bot.bot_code,
group_name=group_name, group_name=group_name,
...@@ -502,7 +528,7 @@ class WeComCustomerGroupOrchestrationService: ...@@ -502,7 +528,7 @@ class WeComCustomerGroupOrchestrationService:
customer_name=item.customer_name, customer_name=item.customer_name,
qrcode_id=qrcode.id, qrcode_id=qrcode.id,
qrcode_name=qrcode.qrcode_name, qrcode_name=qrcode.qrcode_name,
channel_code=qrcode.channel_code, channel_code=position.code,
position_id=position.id, position_id=position.id,
position_code=position.code, position_code=position.code,
position_name=position.name, position_name=position.name,
...@@ -550,8 +576,62 @@ class WeComCustomerGroupOrchestrationService: ...@@ -550,8 +576,62 @@ class WeComCustomerGroupOrchestrationService:
request.resolved_contact_type = str(resolved.get("contact_type") or "") or None request.resolved_contact_type = str(resolved.get("contact_type") or "") or None
request.external_result = payload request.external_result = payload
request.resolved_at = _utcnow() request.resolved_at = _utcnow()
bot = self.db.query(WeComBot).filter(WeComBot.bot_id == request.bot_id).first()
member_names = [request.customer_name] + list(request.member_bot_ids or [])
logger.info(
format_job_log(
"机器人[%s]:我建群成功了!群名叫[%s],群里有:%s"
% (
(bot.bot_name if bot and bot.bot_name else request.bot_id),
request.resolved_group_name or request.group_name,
"、".join([str(name) for name in member_names if name]) or "-",
)
)
)
return True return True
def _send_group_welcome_message_once(self, request: WeComGroupCreateRequest) -> None:
if not request.resolved_group_contact_id or not request.bot_id:
return
qrcode = self.db.query(QrcodeChannel).filter(QrcodeChannel.id == request.qrcode_id).first()
if qrcode is None:
return
content = str(qrcode.welcome_message or "").strip()
if not content:
return
biz_rela_no = f"biz-msg-{int(_utcnow().timestamp() * 1000)}-{uuid4().hex[:6]}"
bot = self.db.query(WeComBot).filter(WeComBot.bot_id == request.bot_id).first()
logger.info(
format_job_log(
"机器人[%s]:我准备发送欢迎语:%s"
% ((bot.bot_name if bot and bot.bot_name else request.bot_id), content)
)
)
try:
self.client.send_message(
contact_id=request.resolved_group_contact_id,
content=content,
msg_type="text",
bot_id=request.bot_id,
biz_rela_no=biz_rela_no,
)
logger.info(
format_job_log(
"建群成功后已发送欢迎语: group_contact_id=%s bot_id=%s biz_rela_no=%s"
% (request.resolved_group_contact_id, request.bot_id, biz_rela_no)
)
)
except Exception:
logger.exception(
format_job_log(
"建群成功后发送欢迎语失败: group_contact_id=%s bot_id=%s"
% (request.resolved_group_contact_id, request.bot_id)
)
)
def _scan_new_customers_for_bot(self, *, bot_id: str) -> list[WeComNewCustomerItem]: def _scan_new_customers_for_bot(self, *, bot_id: str) -> list[WeComNewCustomerItem]:
bot = self.db.query(WeComBot).filter(WeComBot.bot_id == bot_id).first() bot = self.db.query(WeComBot).filter(WeComBot.bot_id == bot_id).first()
if bot is None: if bot is None:
...@@ -594,6 +674,17 @@ class WeComCustomerGroupOrchestrationService: ...@@ -594,6 +674,17 @@ class WeComCustomerGroupOrchestrationService:
skip_reason = None skip_reason = None
if not member_bots: if not member_bots:
skip_reason = "no_members" skip_reason = "no_members"
logger.info(
format_job_log(
"发现了一个新客户:机器人[%s] 发现客户[%s](contact_id=%s),可建群=%s"
% (
bot.bot_name or bot.bot_id,
customer_name or "-",
contact_id,
"是" if can_create_group else "否",
)
)
)
candidates.append( candidates.append(
WeComNewCustomerItem( WeComNewCustomerItem(
bot_id=bot.bot_id, bot_id=bot.bot_id,
......
...@@ -94,6 +94,17 @@ class WeComSyncClient(Protocol): ...@@ -94,6 +94,17 @@ class WeComSyncClient(Protocol):
def get_task(self, *, task_id: str) -> dict[str, Any]: def get_task(self, *, task_id: str) -> dict[str, Any]:
... ...
def send_message(
self,
*,
contact_id: str,
content: str,
msg_type: str,
bot_id: str,
biz_rela_no: str,
) -> dict[str, Any]:
...
class WeComMessageDispatcher(Protocol): class WeComMessageDispatcher(Protocol):
def dispatch(self, message: WeComMessage) -> None: def dispatch(self, message: WeComMessage) -> None:
...@@ -370,6 +381,18 @@ class WeComSyncService: ...@@ -370,6 +381,18 @@ class WeComSyncService:
bot_send=False, bot_send=False,
) )
self.db.add(record) self.db.add(record)
logger.info(
format_job_log(
"发现了条新消息:bot_id=%s,发送人=%s,群/会话=%s,消息类型=%s,消息内容=%s"
% (
str(data.get("bot_id") or ""),
str(data.get("sender_name") or data.get("sender_id") or "-"),
str(data.get("contact_id") or data.get("session_title") or "-"),
str(data.get("msg_type") or "-"),
str(data.get("msg_content") or "")[:100],
)
)
)
record.bot_code = bot_code record.bot_code = bot_code
record.channel = str(data.get("channel") or record.channel) record.channel = str(data.get("channel") or record.channel)
record.bot_id = str(data.get("bot_id") or record.bot_id) record.bot_id = str(data.get("bot_id") or record.bot_id)
......
...@@ -15,6 +15,10 @@ ...@@ -15,6 +15,10 @@
"base_url": "http://yjy.dev.glsx.com.cn/webim", "base_url": "http://yjy.dev.glsx.com.cn/webim",
"api_key": "" "api_key": ""
}, },
"downstream_chat": {
"host": "192.168.1.191",
"port": 8000
},
"oss": { "oss": {
"access_key_id": "LTAI5tB2Q3EJFmaosMYN3uPc", "access_key_id": "LTAI5tB2Q3EJFmaosMYN3uPc",
"access_key_secret": "wMS8hRb4k7sWGcnq1gO6BRWcVjPfu4", "access_key_secret": "wMS8hRb4k7sWGcnq1gO6BRWcVjPfu4",
......
...@@ -3,6 +3,8 @@ services: ...@@ -3,6 +3,8 @@ services:
build: build:
context: . context: .
dockerfile: Dockerfile.prod dockerfile: Dockerfile.prod
ports:
- "8082:8082"
volumes: [] volumes: []
env_file: env_file:
- path: .env - path: .env
...@@ -11,6 +13,9 @@ services: ...@@ -11,6 +13,9 @@ services:
- DATABASE_URL=${DATABASE_URL} - DATABASE_URL=${DATABASE_URL}
- IM_BASE_URL=${IM_BASE_URL:-http://yjy.dev.glsx.com.cn/webim} - IM_BASE_URL=${IM_BASE_URL:-http://yjy.dev.glsx.com.cn/webim}
- USE_CONSOLE_IM=${USE_CONSOLE_IM:-false} - USE_CONSOLE_IM=${USE_CONSOLE_IM:-false}
- DOWNSTREAM_CHAT_HOST=127.0.0.1
- DOWNSTREAM_CHAT_PORT=8082
restart: always
deploy: deploy:
resources: resources:
limits: limits:
......
...@@ -4,11 +4,12 @@ services: ...@@ -4,11 +4,12 @@ services:
context: . context: .
dockerfile: Dockerfile.dev dockerfile: Dockerfile.dev
ports: ports:
- "8082:8000" - "8082:8082"
volumes: volumes:
- ./app:/app/app - ./app:/app/app
- ./config:/app/config - ./config:/app/config
- ./skills:/app/skills - ./skills:/app/skills
- ./scripts:/app/scripts
- ./tests:/app/tests - ./tests:/app/tests
env_file: env_file:
- path: .env - path: .env
...@@ -17,6 +18,9 @@ services: ...@@ -17,6 +18,9 @@ services:
- DATABASE_URL=${DATABASE_URL:-sqlite:///./dev.db} - DATABASE_URL=${DATABASE_URL:-sqlite:///./dev.db}
- IM_BASE_URL=${IM_BASE_URL:-http://yjy.dev.glsx.com.cn/webim} - IM_BASE_URL=${IM_BASE_URL:-http://yjy.dev.glsx.com.cn/webim}
- USE_CONSOLE_IM=${USE_CONSOLE_IM:-false} - USE_CONSOLE_IM=${USE_CONSOLE_IM:-false}
- DOWNSTREAM_CHAT_HOST=127.0.0.1
- DOWNSTREAM_CHAT_PORT=8082
restart: always
depends_on: depends_on:
- im-service - im-service
......
#!/bin/sh
set -eu
uvicorn app.main:app --host 0.0.0.0 --port 8082 --reload &
WEB_PID=$!
python -m app.jobs.scheduler &
SCHED_PID=$!
cleanup() {
kill "$WEB_PID" "$SCHED_PID" 2>/dev/null || true
}
trap cleanup INT TERM
while true; do
if ! kill -0 "$WEB_PID" 2>/dev/null; then
kill "$SCHED_PID" 2>/dev/null || true
wait "$WEB_PID" || true
wait "$SCHED_PID" || true
exit 1
fi
if ! kill -0 "$SCHED_PID" 2>/dev/null; then
kill "$WEB_PID" 2>/dev/null || true
wait "$WEB_PID" || true
wait "$SCHED_PID" || true
exit 1
fi
sleep 2
done
#!/bin/sh
set -eu
uvicorn app.main:app --host 0.0.0.0 --port 8082 --workers 4 &
WEB_PID=$!
python -m app.jobs.scheduler &
SCHED_PID=$!
cleanup() {
kill "$WEB_PID" "$SCHED_PID" 2>/dev/null || true
}
trap cleanup INT TERM
while true; do
if ! kill -0 "$WEB_PID" 2>/dev/null; then
kill "$SCHED_PID" 2>/dev/null || true
wait "$WEB_PID" || true
wait "$SCHED_PID" || true
exit 1
fi
if ! kill -0 "$SCHED_PID" 2>/dev/null; then
kill "$WEB_PID" 2>/dev/null || true
wait "$WEB_PID" || true
wait "$SCHED_PID" || true
exit 1
fi
sleep 2
done
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!