fix(xq0009): 修复收银月份格式致技师整体漏判;新增钉钉群文件推送(1.0.15)
- xq0009 收银技师考勤月份归一(202610 被取成 0 月、202611 会错拉 1 月),统计月拉取失败改为中止,不再静默导出缺技师名单 - xq0009 新增「钉钉群名」字段:导出后把名单推到群(dingtalk_sdk.dws),执行前按群全称精确校验,识别不到直接报错并列出候选群 - xq0009 技师月末仍在休(HR 无请假单)时备注补「截至 X 仍在病假」;推送超时不再重试(避免重复发文件) - dingtalk_sdk 0.1.2:兼容 dws 异步任务返回(outcome=pending 视为已受理并轮询 query-send-status),修复误判失败导致同一条消息重复发送 - 文档:SDK 发版直发正式(--prod),插件仍走测试通道→人工转正;xq0001 自测兼容门禁 runpy 直跑
This commit is contained in:
@@ -170,10 +170,10 @@ cd libs\dingtalk; ..\..\.venv\Scripts\python.exe -m dingtalk_sdk._selftest; cd .
|
||||
# 打包 + 本地安装到 %LOCALAPPDATA%\37duAutomation\sdk(含兼容预检)
|
||||
.venv\Scripts\python.exe tools\sdk_pack.py --sdk libs\dingtalk --install
|
||||
|
||||
# 发测试通道(人工验证后由人转正)
|
||||
# 直发正式(SDK 无独立入口、无法单测,不走测试通道;要小范围看就发消费插件的测试版)
|
||||
.venv\Scripts\python.exe tools\agent_cli.py --admin puddy --password 123456 `
|
||||
--base http://172.30.30.243:8800 `
|
||||
sdk-publish dist-sdk\dingtalk_sdk_v0.1.0.zip --baseline-sdk <上一版 zip>
|
||||
sdk-publish dist-sdk\dingtalk_sdk_v0.1.2.zip --baseline-sdk <上一版 zip> --prod
|
||||
```
|
||||
|
||||
完整发版 SOP 见技能 `.skills/37du-SDK-Deploy/SKILL.md`;`^0.x` 是标准 caret 语义,
|
||||
|
||||
@@ -33,7 +33,7 @@ AI 表格(notable)读写 :class:`aitable.AiTable` 与值归一工具
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
__version__ = "0.1.0"
|
||||
__version__ = "0.1.2"
|
||||
|
||||
from . import aitable, auth, config, dws, errors, http, media, robot
|
||||
from .aitable import (AiTable, coerce_for_fields, flatten, ms_to_str, norm, resolve_base,
|
||||
|
||||
@@ -162,6 +162,26 @@ def test_dws() -> None:
|
||||
res = limiter.send_group_message("测试群", content="", file_path="", record_dir="")
|
||||
_eq(res["success"], False, "文本与文件都为空时失败")
|
||||
|
||||
# dws 异步任务返回体(2026-11 实测):outcome=pending + meta.operation 必须算成功,
|
||||
# 否则上层重试会把同一条消息重复发多次。
|
||||
pending = {
|
||||
"ok": True, "outcome": "pending",
|
||||
"data": {"arguments": [], "errorCode": None, "errorMsg": None,
|
||||
"result": {"friendlyHint": "", "openTaskId": "Dp8G2MgCqJQ=",
|
||||
"retryable": False},
|
||||
"success": True},
|
||||
"meta": {"operation": {"id": "Dp8G2MgCqJQ=", "state": "processing",
|
||||
"next_command": "dws chat message query-send-status "
|
||||
"--open-task-id Dp8G2MgCqJQ="}},
|
||||
}
|
||||
_ok(dws.is_success(pending), "异步受理(pending)判为已受理")
|
||||
_eq(dws.operation_of(pending).get("state"), "processing", "取到 operation.state")
|
||||
_ok(dws.is_success({"success": True}), "同步 success=true 仍判成功")
|
||||
_ok(dws.is_success({"ok": True, "outcome": "success"}), "outcome=success 判成功")
|
||||
_ok(not dws.is_success({"ok": False, "outcome": "failed"}), "outcome=failed 判失败")
|
||||
_ok(not dws.is_success({"error": {"message": "boom"}}), "无 success 字段判失败")
|
||||
_eq(dws.operation_of({"success": True}), {}, "无 meta 时 operation 为空")
|
||||
|
||||
|
||||
# ==================== AI 表格 ====================
|
||||
|
||||
|
||||
@@ -32,6 +32,13 @@ RECORD_PATH_GLV = "push_record_path" # 影刀全局变量名(非影刀环
|
||||
|
||||
DEFAULT_TIMEOUT = 300.0 # 单条 dws 命令超时秒(大文件上传留足时间)
|
||||
CODE_NO_CONVERSATION = "11056"
|
||||
TASK_WAIT = 20.0 # 异步任务(outcome=pending)查询终态的最长等待秒
|
||||
TASK_POLL = 1.0 # 异步任务状态查询间隔秒
|
||||
|
||||
# dws 任务状态:受理中 / 已成功 / 已失败(取值大小写不一,统一小写比较)
|
||||
_ACCEPTED_STATES = ("pending", "processing", "accepted", "queued", "running", "in_progress")
|
||||
_DONE_STATES = ("done", "success", "succeeded", "completed", "finished", "sent")
|
||||
_FAILED_STATES = ("failed", "error", "cancelled", "canceled", "timeout", "expired")
|
||||
|
||||
|
||||
# ==================== 工具 ====================
|
||||
@@ -78,6 +85,43 @@ def record_csv_path(record_dir: str) -> str:
|
||||
return os.path.join(record_dir, datetime.now().strftime("%Y-%m-%d"), "推送记录.csv")
|
||||
|
||||
|
||||
def _truthy(value) -> bool:
|
||||
"""宽松布尔:True/1/"true"/"ok"/"success"/"done" 都算真。"""
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
if isinstance(value, (int, float)):
|
||||
return value != 0
|
||||
return str(value or "").strip().lower() in ("true", "1", "ok", "success", "done")
|
||||
|
||||
|
||||
def is_success(data) -> bool:
|
||||
"""dws 返回体是否代表「已成功 / 已受理」(同步与异步两种形态都认)。
|
||||
|
||||
- 同步:``{"success": true, ...}``(旧版 dws)或 ``{"ok": true, ...}``;
|
||||
- 异步受理:``{"ok": true, "outcome": "pending", "data": {"success": true,
|
||||
"result": {"openTaskId": ...}}, "meta": {"operation": {"state": "processing",
|
||||
"next_command": "dws chat message query-send-status --open-task-id ..."}}}``
|
||||
—— 这是**发送任务已进队列**,不是失败;旧实现只认顶层 ``success``,
|
||||
于是把成功当失败、上层重试导致同一条消息重复发送多次。
|
||||
"""
|
||||
if not isinstance(data, dict):
|
||||
return False
|
||||
if _truthy(data.get("success")):
|
||||
return True
|
||||
inner = data.get("data")
|
||||
if isinstance(inner, dict) and _truthy(inner.get("success")):
|
||||
return True
|
||||
outcome = str(data.get("outcome") or "").strip().lower()
|
||||
return outcome in _ACCEPTED_STATES or outcome in _DONE_STATES
|
||||
|
||||
|
||||
def operation_of(data) -> dict:
|
||||
"""取异步任务信息 ``meta.operation``(没有则返回空 dict)。"""
|
||||
meta = data.get("meta") if isinstance(data, dict) else None
|
||||
op = meta.get("operation") if isinstance(meta, dict) else None
|
||||
return op if isinstance(op, dict) else {}
|
||||
|
||||
|
||||
# ==================== 客户端 ====================
|
||||
|
||||
class Dws:
|
||||
@@ -89,12 +133,16 @@ class Dws:
|
||||
rate_window: 限流窗口秒(默认 60)
|
||||
record_dir: 默认推送记录目录(可在每次调用时覆盖)
|
||||
timeout: 单条命令超时秒
|
||||
task_wait: 异步任务(outcome=pending)查询终态的最长等待秒,默认 20
|
||||
task_poll: 异步任务状态查询间隔秒,默认 1
|
||||
log: 日志回调
|
||||
"""
|
||||
|
||||
def __init__(self, bin: str = "", rate_limit: Optional[int] = None,
|
||||
rate_window: Optional[float] = None, record_dir: str = "",
|
||||
timeout: Optional[float] = None,
|
||||
task_wait: Optional[float] = None,
|
||||
task_poll: Optional[float] = None,
|
||||
log: Optional[Callable[[str], None]] = None) -> None:
|
||||
cfg = get_settings()
|
||||
self._bin = (bin or "").strip()
|
||||
@@ -103,6 +151,8 @@ class Dws:
|
||||
else cfg.rate_window)
|
||||
self.record_dir = record_dir or ""
|
||||
self.timeout = float(timeout if timeout is not None else DEFAULT_TIMEOUT)
|
||||
self.task_wait = float(task_wait if task_wait is not None else TASK_WAIT)
|
||||
self.task_poll = float(task_poll if task_poll is not None else TASK_POLL)
|
||||
self.log = log or (lambda msg: None)
|
||||
self._open_id_cache: Dict[Tuple[str, str], str] = {}
|
||||
self._rate_history: List[float] = []
|
||||
@@ -124,7 +174,21 @@ class Dws:
|
||||
return path
|
||||
|
||||
def run(self, args: Sequence[str]) -> dict:
|
||||
"""执行 dws 子命令并返回完整 JSON(已校验 ``success`` 字段)。"""
|
||||
"""执行 dws 子命令并返回完整 JSON。
|
||||
|
||||
返回值兼容两种形态:同步 ``{"success": true}`` 与**异步受理**
|
||||
``{"ok": true, "outcome": "pending", "meta": {"operation": {...}}}``。
|
||||
异步受理会按 ``meta.operation.next_command`` 轮询发送结果(最多 ``task_wait`` 秒),
|
||||
查不到终态时按「已受理」返回,避免上层重试导致重复发送。
|
||||
"""
|
||||
data = self._exec(args)
|
||||
if not is_success(data):
|
||||
raise DwsError(f"命令未成功: {mask(data)}",
|
||||
code=_extract_error_code(json.dumps(data, ensure_ascii=False)))
|
||||
return self._await_task(data)
|
||||
|
||||
def _exec(self, args: Sequence[str]) -> dict:
|
||||
"""真正执行 dws 并解析 JSON(不做成功判定,供轮询复用)。"""
|
||||
cmd = [self.require_bin(), *[str(a) for a in args]]
|
||||
try:
|
||||
proc = subprocess.run(cmd, capture_output=True, text=True,
|
||||
@@ -141,9 +205,40 @@ class Dws:
|
||||
idx = raw.find("{")
|
||||
if idx < 0:
|
||||
raise DwsError(f"dws 输出无法解析:{mask(raw[:200])}")
|
||||
data = json.loads(raw[idx:])
|
||||
if not data.get("success"):
|
||||
raise DwsError(f"命令未成功: {mask(data)}", code=_extract_error_code(raw))
|
||||
return json.loads(raw[idx:])
|
||||
|
||||
def _await_task(self, data: dict) -> dict:
|
||||
"""异步受理的发送任务:轮询 ``query-send-status`` 至终态,超时按已受理返回。"""
|
||||
op = operation_of(data)
|
||||
state = str(op.get("state") or "").strip().lower()
|
||||
next_cmd = str(op.get("next_command") or "").strip()
|
||||
if state not in _ACCEPTED_STATES or not next_cmd.startswith("dws "):
|
||||
return data
|
||||
args = next_cmd.split()[1:] # 去掉命令名 dws 本身
|
||||
if not args:
|
||||
return data
|
||||
self.log(f"[INFO] dws 任务已受理(state={state}),查询发送结果…")
|
||||
deadline = time.time() + self.task_wait
|
||||
while time.time() < deadline:
|
||||
time.sleep(self.task_poll)
|
||||
try:
|
||||
st = self._exec(args)
|
||||
except (DwsError, ConfigError) as exc:
|
||||
# 查询失败不等于发送失败:消息已进队列,按成功处理,绝不重发
|
||||
self.log(f"[WARN] 查询发送状态失败(消息已受理,按成功处理):{mask(exc)}")
|
||||
return data
|
||||
st_state = str(operation_of(st).get("state")
|
||||
or st.get("outcome") or "").strip().lower()
|
||||
if st_state in _DONE_STATES:
|
||||
self.log("[INFO] dws 发送任务完成")
|
||||
return st
|
||||
if st_state in _FAILED_STATES:
|
||||
raise DwsError(f"发送任务失败(state={st_state}):{mask(st)}")
|
||||
if st_state not in _ACCEPTED_STATES:
|
||||
# 状态字段换了/无法识别:按已受理处理,别为一条消息卡满 task_wait
|
||||
self.log(f"[WARN] 发送状态无法识别({st_state or '空'}),按已受理处理")
|
||||
return data
|
||||
self.log(f"[WARN] dws 发送任务 {self.task_wait:.0f}s 内未返回终态,按已受理处理(勿重复发送)")
|
||||
return data
|
||||
|
||||
# ---- 限流 ----
|
||||
|
||||
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "dingtalk_sdk"
|
||||
version = "0.1.0"
|
||||
version = "0.1.2"
|
||||
description = "钉钉能力 SDK:群机器人推送 / 应用鉴权 / 媒体上传 / 单聊群聊推送(dws)/ AI 表格读写与月报周报采集"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.9"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "dingtalk_sdk",
|
||||
"name": "钉钉 SDK",
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.2",
|
||||
"description": "钉钉能力集合:群机器人推送(加签/Markdown/状态色/分批/块格式/多环境)、企业内部应用鉴权(v1 + oapi)、媒体库上传、dws 单聊/群聊推送(文本/文件/@/限流/推送记录)、AI 表格读写与月报周报采集",
|
||||
"provides": [
|
||||
"dingtalk_sdk"
|
||||
|
||||
Reference in New Issue
Block a user