Files
puddy cf86b568f0 feat(plugin): 新增 XQ0012 EHR 预支及支付报酬自动发起 ERP 付款申请(0.1.0)
- 读 EHR 预支台账 → 按 ERP 付款申请单口径逐行建单,默认试算不写库
- 可选建单后自动提交、按套打样例生成 PDF 直连网络打印,打印完成钉钉提醒领取
- 含幂等查重与异常清单,业务口径与字段顺序按生产单核对
- 依赖 erpsdk / printkit / dingtalk_sdk(plugin.json requires.sdks 声明)
- 需求单文档同步:开发/流程/评分/需求文档更新,新增交接文档
2026-11-16 11:27:38 +08:00

178 lines
7.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""钉钉提醒:套打打印完成后,用**企业内部应用工作通知**提醒指定人去领取纸质单。
口径参考 XQ0052(湖畔储值卡导出):不走群机器人、不走 dws 客户端,直接
`topapi/message/corpconversation/asyncsend_v2` 发工作通知给「姓名/工号」指定的接收人。
接收人解析:
- 界面填「姓名/工号」,多个用「、」「,」「;」或换行分隔;
- 先按姓名搜索 userId(钉钉通讯录搜索会命中重名),再用工号(jobnumber)精确挑人;
- 只填姓名且搜到多个 → 报错并列出候选,要求补工号。
推送是附带动作:失败只记日志与返回值,不影响单据与打印结果。
"""
from __future__ import annotations
import re
import time
import requests
from .. import config
TAG = '[钉钉]'
MAX_ATTEMPTS = 3
RETRY_WAIT = 3
_ENTRY_SEP = re.compile(r"[,,、;;\n\r]+")
_CODE_OPEN = re.compile(r"[((//]")
_CODE_CLOSE = re.compile(r"[))]")
# ==================== 文案 ====================
def build_message(printed: list, printer: str, failed: int = 0) -> str:
"""组装提醒正文(纯函数,便于自检)。"""
printer = printer or config.PRINTER_DEFAULT
n = len(printed)
total = sum(float(p.get('amount') or 0) for p in printed)
lines = [f"【付款申请单已打印】请到「{printer}」打印机处领取", '']
for p in printed[:30]:
lines.append(f"{p.get('bill_no', '')} {p.get('name', '')} {float(p.get('amount') or 0):.2f}")
if n > 30:
lines.append(f"… 另有 {n - 30} 张")
lines += ['', f"合计 {total:.2f} 元"]
if failed:
lines.append(f"另 {failed} 张打印失败,PDF 已落盘,请人工补打")
return '\n'.join(lines)
# ==================== 接收人 ====================
def parse_recipients(text) -> list:
"""「张三/37036361」「张三」→ [(姓名, 工号), …]。"""
out = []
for raw in _ENTRY_SEP.split(str(text or "")):
item = raw.strip().strip("\"'“”")
if not item:
continue
name, code = item, ''
hit = _CODE_OPEN.search(item)
if hit:
name = item[:hit.start()].strip()
code = _CODE_CLOSE.sub('', item[hit.end():]).strip()
if name:
out.append((name, code))
return out
def _token(kind: str) -> str:
from dingtalk_sdk import auth
return auth.AccessToken(kind=kind, app_key=config.DINGTALK_APP_KEY,
app_secret=config.DINGTALK_APP_SECRET).get()
def _search_by_name(name: str) -> list:
data = requests.post(
config.DINGTALK_USER_SEARCH_URL,
json={"queryWord": name, "offset": 0, "size": 20, "maxResults": 20},
headers={"x-acs-dingtalk-access-token": _token('v1'), "Content-Type": "application/json"},
timeout=20).json()
ids = []
for item in data.get("list") or []:
uid = item if isinstance(item, str) else (item.get("userid") or item.get("userId") or '')
if uid:
ids.append(str(uid))
return ids
def _user_detail(user_id: str) -> dict:
data = requests.get(config.DINGTALK_USER_GET_URL,
params={"access_token": _token('oapi'), "userid": user_id},
timeout=20).json()
if int(data.get("errcode") or 0) != 0:
raise RuntimeError('钉钉 user/get 失败:%s' % data.get('errmsg'))
return data
def resolve_user_id(name: str, code: str) -> str:
ids = _search_by_name(name)
if not ids:
raise RuntimeError('钉钉通讯录里没搜到「%s」' % name)
cands = [{'uid': u, 'name': str(_user_detail(u).get('name') or ''),
'jobnumber': str(_user_detail(u).get('jobnumber') or '').strip()} for u in ids]
hint = ';'.join('%s(工号 %s / userId %s)' % (c['name'] or name, c['jobnumber'] or '无', c['uid'])
for c in cands)
if code:
for c in cands:
if c['jobnumber'] == code or c['uid'] == code:
return c['uid']
raise RuntimeError('「%s」的候选中没有工号 %s,请核对:%s' % (name, code, hint))
if len(cands) == 1:
return cands[0]['uid']
raise RuntimeError('「%s」在钉钉里有多个人,请带工号重试:%s' % (name, hint))
def _send_work_notice(user_ids: list, content: str) -> None:
data = requests.post(
config.DINGTALK_WORK_SEND_URL,
params={"access_token": _token('oapi')},
json={"agent_id": config.DINGTALK_AGENT_ID,
"userid_list": ','.join(user_ids),
"msg": {"msgtype": "text", "text": {"content": content}}},
timeout=30).json()
if int(data.get("errcode") or 0) != 0:
raise RuntimeError('工作通知失败 errcode=%s errmsg=%s' % (data.get('errcode'), data.get('errmsg')))
def _retry(fn, what):
last = None
for attempt in range(1, MAX_ATTEMPTS + 1):
try:
return fn()
except Exception as e: # noqa: BLE001
last = e
config.log(f'{TAG} {what} 第 {attempt}/{MAX_ATTEMPTS} 次失败:{e}', 'ERROR')
if attempt < MAX_ATTEMPTS:
time.sleep(RETRY_WAIT)
raise last
# ==================== 对外入口 ====================
def notify_printed(printed: list, printer: str, failed: int = 0, *,
users_text: str = '', dry_run: bool = False) -> dict:
"""打印完成提醒。返回 {'ok', 'sent', 'failed'[], 'skipped'/'error'},永不抛异常。"""
if not printed:
return {'ok': False, 'sent': 0, 'failed': [], 'skipped': '没有打印成功的单据'}
recipients = parse_recipients(users_text or config.DINGTALK_USERS_DEFAULT)
if not recipients:
config.log(f'{TAG} 未配置接收人,跳过提醒')
return {'ok': False, 'sent': 0, 'failed': [], 'skipped': '未配置接收人'}
content = build_message(printed, printer, failed)
if dry_run:
config.log(f'{TAG} 试运行不推送 → {recipients}')
return {'ok': True, 'sent': 0, 'failed': [], 'skipped': 'dry_run', 'content': content}
user_ids, failed_list = [], []
for name, code in recipients:
label = f'{name}/{code}' if code else name
try:
uid = _retry(lambda: resolve_user_id(name, code), f'解析接收人「{label}」')
user_ids.append(uid)
config.log(f'{TAG} 接收人「{label}」→ userId={uid}')
except Exception as e: # noqa: BLE001
failed_list.append(f'{label}:{e}')
if not user_ids:
return {'ok': False, 'sent': 0, 'failed': failed_list,
'error': '0/%d 人匹配到钉钉账号' % len(recipients)}
try:
_retry(lambda: _send_work_notice(user_ids, content), '发送工作通知')
except Exception as e: # noqa: BLE001
config.log(f'{TAG} 推送失败(不影响单据):{e}', 'ERROR')
return {'ok': False, 'sent': 0, 'failed': failed_list + [str(e)[:200]], 'error': str(e)[:200]}
config.log(f'{TAG} 已提醒 {len(user_ids)} 人:{printer}')
return {'ok': not failed_list, 'sent': len(user_ids), 'failed': failed_list}