qrcode_channel_service.py 11.6 KB
from __future__ import annotations

from datetime import datetime, timedelta, timezone
from typing import Optional

from sqlalchemy import or_
from sqlalchemy.orm import Session as OrmSession

from app.infrastructure.file_parser import OSSClient
from app.model.agent import Agent, AgentPosition, AgentStatus
from app.model.agent_group import QrcodeChannel
from app.model.position_tag import PositionTag
from app.model.wecom_sync import WeComBot
from app.schema.qrcode_channel import (
    QrcodeBatchStatusResponse,
    QrcodeCreateResponse,
    QrcodeDeleteResponse,
    QrcodeDetailResponse,
    QrcodeDisableResponse,
    QrcodeEnableResponse,
    QrcodeExportResponse,
    QrcodeListItem,
    QrcodeListResponse,
    QrcodeUpdateResponse,
)
from app.service.agent_group_helper_service import WeComClient


class QrcodeChannelService:
    def __init__(self, db: OrmSession, wecom: WeComClient, oss: Optional[OSSClient] = None):
        self.db = db
        self.wecom = wecom
        self.oss = oss

    def create(self, req) -> QrcodeCreateResponse:
        position = self.db.query(PositionTag).filter(PositionTag.code == req.position_code).first()
        if not position:
            raise ValueError("岗位不存在")

        if self.db.query(QrcodeChannel).filter(QrcodeChannel.position_id == position.id).first():
            raise ValueError("该岗位已存在活码")

        bot = self.db.query(WeComBot).filter(WeComBot.bot_id == req.employee_id).first()
        if bot is None:
            bot = self.db.query(WeComBot).filter(WeComBot.bot_id == req.wechat_user_id).first()
        if bot is None or not bot.bot_id:
            raise ValueError("员工不存在")

        if req.wechat_user_id and str(req.wechat_user_id) != str(bot.bot_id):
            raise ValueError("employee_id 和 wechat_user_id 不匹配")

        if self.db.query(QrcodeChannel).filter(QrcodeChannel.wecom_bot_id == bot.id).first():
            raise ValueError("该员工已绑定活码")

        employee_id = str(bot.bot_id)
        employee_name = bot.bot_name or employee_id

        steward = self.db.query(Agent).filter(Agent.code == "steward", Agent.is_deleted == False).first()
        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()
        )
        agent_list = list(position_agents)
        if steward and steward not in agent_list:
            agent_list.insert(0, steward)

        agent_ids = [a.id for a in agent_list]
        agent_names = [a.name for a in agent_list]

        channel_code = position.code
        qrcode_url = self.wecom.create_qrcode(channel_code, req.welcome_message or "")

        qr = QrcodeChannel(
            qrcode_name=req.qrcode_name,
            position_id=position.id,
            position_name=position.name,
            wecom_bot_id=bot.id,
            employee_id=employee_id,
            employee_name=employee_name,
            channel_code=channel_code,
            qrcode_url=qrcode_url,
            agent_ids=agent_ids,
            agent_names=agent_names,
            remark=req.remark,
            welcome_message=req.welcome_message,
            created_by="admin",
        )
        self.db.add(qr)
        self.db.commit()
        self.db.refresh(qr)

        return QrcodeCreateResponse(
            qrcode_id=qr.id,
            qrcode_name=qr.qrcode_name or "",
            qrcode_url=qr.qrcode_url or "",
            channel_code=qr.channel_code,
            status=qr.status,
            agent_ids=agent_ids,
            agent_names=agent_names,
            created_at=qr.created_at,
        )

    def update(self, qrcode_id: int, req) -> QrcodeUpdateResponse:
        qr = self._get_or_404(qrcode_id)
        qr.qrcode_name = req.qrcode_name
        qr.remark = req.remark
        qr.welcome_message = req.welcome_message
        self.db.commit()
        self.db.refresh(qr)
        return QrcodeUpdateResponse(success=True, updated_at=qr.updated_at)

    def get_detail(self, qrcode_id: int) -> QrcodeDetailResponse:
        qr = self._get_or_404(qrcode_id)
        position_agents = (
            self.db.query(Agent)
            .join(AgentPosition, AgentPosition.agent_id == Agent.id)
            .filter(
                AgentPosition.position_id == qr.position_id,
                Agent.is_deleted == False,
                Agent.status == AgentStatus.enable,
            )
            .all()
            if qr.position_id is not None
            else []
        )
        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_ids = [a.id for a in agent_list]
        agent_names = [a.name for a in agent_list]

        return QrcodeDetailResponse(
            qrcode_id=qr.id,
            qrcode_name=qr.qrcode_name,
            employee_id=qr.employee_id,
            employee_name=qr.employee_name,
            position_name=qr.position_name,
            channel_code=qr.channel_code,
            qrcode_url=qr.qrcode_url,
            agent_ids=agent_ids,
            agent_names=agent_names,
            remark=qr.remark,
            welcome_message=qr.welcome_message,
            status=qr.status,
            created_at=qr.created_at,
            created_by=qr.created_by,
            updated_at=qr.updated_at,
        )

    def list_qrcodes(
        self,
        page: int = 1,
        page_size: int = 20,
        status: Optional[str] = None,
        keyword: Optional[str] = None,
    ) -> QrcodeListResponse:
        query = self.db.query(QrcodeChannel)
        if status:
            query = query.filter(QrcodeChannel.status == status)
        if keyword:
            query = query.filter(
                or_(
                    QrcodeChannel.employee_name.like(f"%{keyword}%"),
                    QrcodeChannel.position_name.like(f"%{keyword}%"),
                    QrcodeChannel.channel_code.like(f"%{keyword}%"),
                )
            )

        total = query.count()
        rows = query.order_by(QrcodeChannel.id.desc()).offset((page - 1) * page_size).limit(page_size).all()
        items = []
        for r in rows:
            position_agents = (
                self.db.query(Agent)
                .join(AgentPosition, AgentPosition.agent_id == Agent.id)
                .filter(
                    AgentPosition.position_id == r.position_id,
                    Agent.is_deleted == False,
                    Agent.status == AgentStatus.enable,
                )
                .all()
                if r.position_id is not None
                else []
            )
            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_names = [a.name for a in agent_list]
            operations = ["查看", "编辑"]
            if r.status == "enable":
                operations.append("停用")
            else:
                operations.append("启用")
            items.append(
                QrcodeListItem(
                    qrcode_id=r.id,
                    qrcode_name=r.qrcode_name,
                    employee_name=r.employee_name,
                    position_name=r.position_name,
                    channel_code=r.channel_code,
                    qrcode_url=r.qrcode_url,
                    agent_count=len(agent_list),
                    agent_names_preview=agent_names,
                    status=r.status,
                    created_at=r.created_at,
                    operations=operations,
                )
            )
        return QrcodeListResponse(total=total, page=page, page_size=page_size, list=items)

    def export(self, req) -> QrcodeExportResponse:
        query = self.db.query(QrcodeChannel)
        if req.filter_conditions:
            if req.filter_conditions.get("position_name"):
                query = query.filter(QrcodeChannel.position_name == req.filter_conditions["position_name"])
            if req.filter_conditions.get("status"):
                query = query.filter(QrcodeChannel.status == req.filter_conditions["status"])

        rows = query.order_by(QrcodeChannel.id.asc()).all()
        fields = req.export_fields or ["employee_name", "position_name", "channel_code", "status"]
        lines = [",".join(fields)]
        for r in rows:
            vals = []
            for f in fields:
                if f == "employee_name":
                    vals.append(r.employee_name)
                elif f == "position_name":
                    vals.append(r.position_name)
                elif f == "channel_code":
                    vals.append(r.channel_code)
                elif f == "status":
                    vals.append(r.status)
                elif f == "agent_names":
                    vals.append(";".join(r.agent_names or []))
                else:
                    vals.append("")
            lines.append(",".join(vals))

        csv_data = "\n".join(lines).encode("utf-8-sig")
        now = datetime.now(timezone.utc)
        file_name = f"qrcode_export_{now.strftime('%Y%m%d_%H%M%S')}.csv"
        file_url = self.oss.upload(csv_data, file_name, "text/csv") if self.oss else f"https://oss.example.com/export/{file_name}"
        return QrcodeExportResponse(file_url=file_url, file_name=file_name, total_count=len(rows), expires_at=now + timedelta(hours=24))

    def disable(self, qrcode_id: int, reason: str) -> QrcodeDisableResponse:
        qr = self._get_or_404(qrcode_id)
        prev = qr.status
        qr.status = "disable"
        qr.disable_reason = reason
        self.db.commit()
        return QrcodeDisableResponse(success=True, disabled_at=datetime.now(timezone.utc), previous_status=prev)

    def enable(self, qrcode_id: int) -> QrcodeEnableResponse:
        qr = self._get_or_404(qrcode_id)
        prev = qr.status
        qr.status = "enable"
        qr.disable_reason = None
        self.db.commit()
        return QrcodeEnableResponse(success=True, enabled_at=datetime.now(timezone.utc), previous_status=prev)

    def batch_status(self, qrcode_ids: list[int], target_status: str, reason: Optional[str] = None) -> QrcodeBatchStatusResponse:
        success = 0
        failed = []
        for qid in qrcode_ids:
            try:
                if target_status == "disable":
                    self.disable(qid, reason or "")
                else:
                    self.enable(qid)
                success += 1
            except Exception as e:
                failed.append({"qrcode_id": qid, "error": str(e)})
        return QrcodeBatchStatusResponse(success_count=success, failed_count=len(failed), failed_list=failed)

    def delete(self, qrcode_id: int) -> QrcodeDeleteResponse:
        qr = self._get_or_404(qrcode_id)
        self.db.delete(qr)
        self.db.commit()
        return QrcodeDeleteResponse(success=True, deleted_at=datetime.now(timezone.utc))

    def _get_or_404(self, qrcode_id: int) -> QrcodeChannel:
        qr = self.db.query(QrcodeChannel).filter(QrcodeChannel.id == qrcode_id).first()
        if not qr:
            raise ValueError("渠道活码不存在")
        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)]