XQ0001 排班异常识别 / XQ0002 雇主险增减操作 / XQ0012 ERP 付款申请 / XQ0013 社保费用申报 / XQ0042 抖音平台核对 / XQ0084 银行卡更新:逻辑与界面 bundle 更新(含各自版本号变更)
178 lines
7.1 KiB
Python
178 lines
7.1 KiB
Python
# -*- 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)
|
||
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}
|