wecom.py 4.71 KB
"""企业微信:机器人登记、接收对象(发到哪个群 / 哪个人、做什么用)、收发记录、测试发送。"""
from __future__ import annotations

import datetime as dt

from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel

from ..services import audit, im, settings
from .deps import Scope, current_store

router = APIRouter(prefix="/api/wecom", tags=["wecom"])


class BotIn(BaseModel):
    name: str
    bot_id: str
    channel: str = "yjy_ww"
    enabled: bool = True
    note: str = ""


class TargetIn(BaseModel):
    name: str
    bot_ref: int
    kind: str = "group"
    contact_id: str
    at_ids: str = ""
    bot_names: str = ""
    require_at: bool = False
    purposes: list[str] = ["chat"]
    alert_min: str = "warn"
    enabled: bool = True


@router.get("/overview")
def overview(s: Scope = Depends(current_store)):
    return {"bots": im.bots(), "targets": im.targets(s.store_id), "purposes": im.PURPOSES,
            "contact_types": im.CONTACT_TYPES, "gateway": settings.get().im_api_base}


@router.get("/contacts")
def contacts(bot_ref: int, type: str = "", keyword: str = "", page: int = 1, size: int = 20,
             s: Scope = Depends(current_store)):
    """从网关通讯录选群 / 选人(只开放企微外部群、内部群、同事、客户四种)。"""
    try:
        return im.contacts(s.store_id, bot_ref, type, keyword.strip(), page, size)
    except ValueError as e:
        raise HTTPException(400, str(e))
    except RuntimeError as e:
        raise HTTPException(502, str(e))


@router.post("/bots")
def create_bot(body: BotIn, s: Scope = Depends(current_store)):
    try:
        bid = im.save_bot(body.model_dump())
    except ValueError as e:
        raise HTTPException(400, str(e))
    audit.record(s.store_id, s.actor, "im.bot.save", target_type="im_bot", target_id=str(bid), after=body.model_dump())
    return {"id": bid}


@router.put("/bots/{bid}")
def update_bot(bid: int, body: BotIn, s: Scope = Depends(current_store)):
    before = im.bot(bid)
    if not before:
        raise HTTPException(404, "机器人不存在")
    try:
        im.save_bot(body.model_dump(), bid)
    except ValueError as e:
        raise HTTPException(400, str(e))
    audit.record(s.store_id, s.actor, "im.bot.save", target_type="im_bot", target_id=str(bid),
                 before={k: before[k] for k in ("name", "bot_id", "channel", "enabled")}, after=body.model_dump())
    return {"ok": True}


@router.delete("/bots/{bid}")
def delete_bot(bid: int, s: Scope = Depends(current_store)):
    try:
        im.delete_bot(bid)
    except ValueError as e:
        raise HTTPException(409, str(e))
    audit.record(s.store_id, s.actor, "im.bot.delete", target_type="im_bot", target_id=str(bid))
    return {"ok": True}


@router.post("/targets")
def create_target(body: TargetIn, s: Scope = Depends(current_store)):
    try:
        tid = im.save_target(s.store_id, body.model_dump())
    except ValueError as e:
        raise HTTPException(400, str(e))
    audit.record(s.store_id, s.actor, "im.target.save", target_type="im_target", target_id=str(tid),
                 after=body.model_dump())
    return {"id": tid}


@router.put("/targets/{tid}")
def update_target(tid: int, body: TargetIn, s: Scope = Depends(current_store)):
    before = im.target(tid)
    if not before or before["store_id"] != s.store_id:
        raise HTTPException(404, "接收对象不存在")
    try:
        im.save_target(s.store_id, body.model_dump(), tid)
    except ValueError as e:
        raise HTTPException(400, str(e))
    audit.record(s.store_id, s.actor, "im.target.save", target_type="im_target", target_id=str(tid),
                 before={k: before[k] for k in ("name", "bot_ref", "kind", "contact_id", "at_ids", "bot_names", "require_at", "purposes",
                                                "alert_min", "enabled")}, after=body.model_dump())
    return {"ok": True}


@router.delete("/targets/{tid}")
def delete_target(tid: int, s: Scope = Depends(current_store)):
    im.delete_target(s.store_id, tid)
    audit.record(s.store_id, s.actor, "im.target.delete", target_type="im_target", target_id=str(tid))
    return {"ok": True}


@router.post("/targets/{tid}/test")
def test_target(tid: int, s: Scope = Depends(current_store)):
    t = im.target(tid)
    if not t or t["store_id"] != s.store_id:
        raise HTTPException(404, "接收对象不存在")
    ok, err = im.test_send(t, s.actor.name)
    return {"ok": ok, "error": err}


@router.get("/logs")
def logs(page: int = 1, size: int = 30, direction: str = "", since: dt.date | None = None,
         until: dt.date | None = None, keyword: str = "", s: Scope = Depends(current_store)):
    return im.logs(s.store_id, page, size, direction, since, until, keyword.strip())