Files
37duAutomation/plugins/xq0038/logic/__init__.py
T
puddy 843ff244a6 feat: 新增多插件 UI 支持及运行日志集中回传功能
本次提交包含多项功能更新:
1. 为多个插件(xq0002/0003/0004/0008/0010/0011/0020/0031_xq0032/0033/0035/0037/0045_xq0046/0047/0048)新增 UI 界面及配置支持
2. 新增运行日志集中回传功能,客户端自动上传运行日志到中心机集中存储
3. 新增插件分类字段支持,用于场景库分组管理
4. 优化 xq0034/0037/0048 等插件的功能及描述
5. 修复控制面响应兼容问题,支持新旧版本数据格式
6. 新增 xq0033 插件的状态存储模块,用于历史记录管理
7. 优化 CRM 登录窗口模式,支持全屏置顶
2026-10-26 15:42:50 +08:00

374 lines
18 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 -*-
"""XQ0038 定性评价推送 插件 - 业务逻辑层:读分组、OA 填表提交、回验、推送编排。
只依赖 Python 标准库 / config(常量与钩子)/ data(通讯录查询)。
会话统一经 config.get_oa_session() 获取(底座注入)。
"""
import json
import os
import re
import time
import traceback
from collections import OrderedDict
from .. import config
from ..data import org_search
# ==================== 页面表单解析(模拟浏览器整表提交) ====================
def get_attrs(tag):
out = {}
for m in config.ATTR_RE.finditer(tag):
val = m.group(3) if m.group(3) is not None else m.group(4)
out[m.group(1).lower()] = val
for flag in ('checked', 'selected'):
if re.search(r'\b%s\b' % flag, tag, re.I) and flag not in out:
out[flag] = flag
return out
def parse_fields(page):
"""解析 add 页全部 input/textarea 为 (name, value) 保序列表(模拟浏览器整表提交)。"""
fields = []
for tag in config.TAG_RE.findall(page):
low = tag.lower()
if low.startswith('<textarea'):
m = re.search(r'name\s*=\s*("([^"]*)"|\'([^\']*)\')', tag, re.I)
if not m:
continue
name = m.group(2) if m.group(2) is not None else m.group(3)
body = re.match(r'<textarea\b[^>]*>(.*?)</textarea>', tag, re.S | re.I)
fields.append((name, body.group(1) if body else ''))
continue
a = get_attrs(tag)
name = a.get('name')
if name is None:
continue
itype = (a.get('type') or 'text').lower()
if itype in ('submit', 'button', 'image', 'file', 'reset'):
continue
if itype in ('checkbox', 'radio') and 'checked' not in a:
continue
fields.append((name, a.get('value', '')))
return fields
# ==================== 数据读取与分组 ====================
def clean_header(h):
"""列名清洗:去掉 (*) 与尾部中文括号注记。"""
h = re.sub(r'\(\*\)\s*$', '', h.strip())
h = re.sub(r'([^)]*)\s*$', '', h)
return h.strip()
def read_groups():
"""读取加工辅助表并按(标记序号, 序列, 部门负责人工号串)分组。
返回 (总行数, OrderedDict{key: [行记录,...]}),组内行序=Excel 行序。
行记录 = {明细列名: 值}(A-N 原样)。
"""
import openpyxl
wb = openpyxl.load_workbook(config.get_data_file(), read_only=True, data_only=True)
if config.DATA_SHEET not in wb.sheetnames:
raise ValueError('数据文件缺少 sheet:%s(现有:%s)'
% (config.DATA_SHEET, '/'.join(wb.sheetnames)))
ws = wb[config.DATA_SHEET]
it = ws.iter_rows(values_only=True)
for _ in range(config.DATA_HEADER_ROW - 1):
next(it, None)
header = [clean_header('' if h is None else str(h)) for h in next(it)]
col = {}
for i, h in enumerate(header):
if h and h not in col:
col[h] = i
need = list(config.DET_FIELDS.keys()) + ['定性发起标记', '部门负责人工号']
miss = [c for c in need if c not in col]
if miss:
raise ValueError('加工辅助表缺少列:%s' % '、'.join(miss))
rows = []
for vals in it:
if vals is None or all(v is None or str(v).strip() == '' for v in vals):
continue
r = {}
for c in need:
i = col[c]
v = vals[i] if i < len(vals) else None
r[c] = '' if v is None else str(v).strip()
if not r['工号'] or not r['定性发起标记']:
continue
rows.append(r)
wb.close()
groups = OrderedDict()
for r in rows:
parts = [p.strip() for p in r['定性发起标记'].split('-')]
if len(parts) < 3:
raise ValueError('定性发起标记格式异常:%s(工号 %s)'
% (r['定性发起标记'], r['工号']))
series = parts[-1]
if series not in config.SERIES_MAP:
raise ValueError('未知序列:%s(标记 %s,工号 %s)'
% (series, r['定性发起标记'], r['工号']))
owner_nos = tuple(n for n in re.split(r'[、,,;;\s]+', r['部门负责人工号']) if n)
if not owner_nos:
raise ValueError('部门负责人工号为空(工号 %s)' % r['工号'])
key = (parts[0], series, owner_nos)
groups.setdefault(key, []).append(r)
return len(rows), groups
# ==================== 单据创建 ====================
def fill_and_post(s, group):
"""推送一组(一张单,明细多行),返回 (fdId, 是否成功, 说明)。失败由调用方重试。"""
seq_no, series, owner_nos = group['key']
rows = group['rows']
send_mode = config.get_send_mode()
test_mode = config.get_test_mode()
# 1) 解析部门负责人(多选,按工号列顺序)
owners = []
for no in owner_nos:
o_id, o_name = org_search(s, no)
if not o_id:
return '', False, '通讯录未查到部门负责人工号 %s' % no
owners.append((o_id, o_name))
# 2) 解析组内成员(按 Excel 行序,同工号复用)
members = OrderedDict()
for r in rows:
no = r['工号']
if no in members:
continue
m_id, m_name = org_search(s, no)
if not m_id:
return '', False, '通讯录未查到工号 %s' % no
members[no] = (m_id, m_name)
# 3) 取 add 页(每次独立,fdId 服务端预生成)
resp = s.get(config.ADD_URL, timeout=30)
page = resp.text
if 'kmReviewMainForm' not in page:
return '', False, 'add 页加载异常(OA 登录态可能失效,请重新登录)'
data = dict(parse_fields(page))
fd_id = data.get('fdId', '')
# 4) 单头
data['method'] = 'saveDraft' if not send_mode else 'save'
data['docStatus'] = '10'
if not send_mode:
# 暂存开关(浏览器"暂存"按钮行为):服务端走仅保存分支、不启动流程
data['sysWfBusinessForm.canStartProcess'] = 'false'
data['extendDataFormInfo.value(%s)' % config.FD_CATEGORY] = config.SERIES_MAP[series]
# 被评价人(人员类别2,relationChoose 关联工号串):实测手动发起的成功单据该字段为空,
# 子流程(N7 启动子流程)数据映射依赖它;若填入"工号字符串"会使子流程被评价人解析失效,
# 报"启动子流程失败,存在处理人为空或失效"。故留空(与手动发起一致)。
for suffix in ('', '_text', '_dataFdId', '_dataSourceId', '_dataModelName',
'_selectedDatas'):
data['extendDataFormInfo.value(%s%s)' % (config.FD_EVAL_USER, suffix)] = ''
# 考核月份(取组内首行月份,与明细一致)
data['extendDataFormInfo.value(%s)' % config.FD_MONTH] = rows[0]['月份']
# 绩效复核人(多选地址本,分号分隔、按工号列顺序)
data['extendDataFormInfo.value(%s.id)' % config.FD_REVIEWER] = ';'.join(o[0] for o in owners)
data['extendDataFormInfo.value(%s.name)' % config.FD_REVIEWER] = ';'.join(o[1] for o in owners)
# 5) 明细多行(A-N 列原样,行序=Excel 行序)
det_prefix = 'extendDataFormInfo.value(%s.' % config.DET_PREFIX
data = {k: v for k, v in data.items() if not k.startswith(det_prefix)}
row_pairs = []
for i, r in enumerate(rows):
m_id, m_name = members[r['工号']]
row_pairs.append(('%s%d.fdId)' % (det_prefix, i), ''))
for col_name, fd in config.DET_FIELDS.items():
val = r.get(col_name, '')
if col_name == '评价说明' and test_mode:
val = val + '【测试】' if val else '【测试】'
row_pairs.append(('%s%d.%s)' % (det_prefix, i, fd), val))
row_pairs.append(('%s%d.%s.id)' % (det_prefix, i, config.DET_USER_FD), m_id))
row_pairs.append(('%s%d.%s.name)' % (det_prefix, i, config.DET_USER_FD), m_name))
# 6) 流程参数(严格还原 add 页 /sys/lbpmservice/include/syslbpmprocess_submit.js
# 中 lbpm.globals.setParameterOnSubmit() + 起草提交操作 operation_drafter_submit.js
# 的 setOperationParam() 的组装结果):
# taskId = lbpm.nowProcessorInfoObj.id → fdCurNodeXML 中 draftWorkitem 任务 id
# processId = $("input[name='sysWfBusinessForm.fdProcessId']").val()
# activityType = lbpm.nowProcessorInfoObj.type → "draftWorkitem"
# operationType= lbpm.currentOperationType → 选中 oprGroup=drafter_submit:提交文档
# param.operationName = 当前操作名(提交文档)
# param.identityId = rolesSelectObj 选中值 → 提交人身份(fdIdentityId/fdDefaultIdentity)
# 注意 activityType 必须是 draftWorkitem:若误传 draftNode,引擎会在 draftNode
# 活动里按 taskId 找不到工作项,抛 TaskRefExecutionIsNullException(页面提示
# "当前处理的流程已被其他人抢先一步提交")。
# 提交人身份/操作(浏览器真实提交参数,经 agent-browser 抓包验证):
# 表单字段 oprGroup=drafter_submit:提交文档、rolesSelectObj=<身份id>、
# sysWfBusinessForm.fdSystemNotifyType={}、提报人 extendDataFormInfo.value(fd_xxx.id)
# param 内 identityId、operationName。这些缺一不可:引擎读 oprGroup/身份来确定
# "提交人/启动人",漏传会导致子流程启动节点解析启动人身份为空/失效,
# 报"启动子流程失败,存在处理人为空或失效"(对应启动人策略③提示错误)。
param_json = {
"taskId": "", "processId": fd_id, "activityType": "draftWorkitem",
"param": {"notifyType": "{}",
"notifyLevel": data.get('sysWfBusinessForm.fdNotifyLevel', '3'),
"notifyOnFinish": True, "notifyForFollow": False,
"auditNote": "",
"auditNoteFdId": data.get('sysWfBusinessForm.fdAuditNoteFdId', ''),
"dayOfNotifyDrafter": "0", "hourOfNotifyDrafter": "0",
"minuteOfNotifyDrafter": "0"},
}
if send_mode:
# 真实发起:taskId 必须指向 fdCurNodeXML 中注册了 drafter_submit 操作的
# draftWorkitem 任务(taskId 为空会默认落到 draftNode 任务,而该任务只注册
# drafter_abandon 操作,报"drafter_submit操作未授权")。该隐藏域 value 在
# HTML 中整体转义(&lt; &quot; 等),需先反转义再解析。
m_xml = re.search(
r'name="sysWfBusinessForm\.fdCurNodeXML"[^>]*value="([^"]*)"', page)
raw = m_xml.group(1) if m_xml else ''
raw = raw.replace('&quot;', '"').replace('&lt;', '<').replace('&gt;', '>')
m_task = re.search(r'<task type="draftWorkitem"[^>]*id="([^"]+)"', raw)
param_json["taskId"] = m_task.group(1) if m_task else ''
param_json["operationType"] = "drafter_submit"
param_json["processId"] = data.get('sysWfBusinessForm.fdProcessId', '') or fd_id
# 提交人身份(弹窗选中值=rolesSelectObj;页面默认 fdIdentityId/fdDefaultIdentity)
identity_id = (data.get('sysWfBusinessForm.fdIdentityId', '')
or data.get('sysWfBusinessForm.fdDefaultIdentity', '') or '')
param_json["param"]["identityId"] = identity_id
param_json["param"]["operationName"] = "提交文档"
# 浏览器真实提交的流程相关表单字段(引擎据 oprGroup/rolesSelectObj 确定操作人与身份)
data['oprGroup'] = 'drafter_submit:提交文档'
data['rolesSelectObj'] = identity_id
data['handlerIds[0]'] = ''
data['handlerNames[0]'] = ''
data['commonUsages'] = ''
data['fdCanCircularize'] = 'true'
data['sysWfBusinessForm.fdSystemNotifyType'] = '{}'
if identity_id:
data['extendDataFormInfo.value(%s.id)' % config.FD_REPORTER] = identity_id
config.log('[DEBUG] 发起参数 fdId=%s taskId=%s processId=%s identityId=%s'
% (fd_id, param_json['taskId'], param_json['processId'], identity_id))
data['sysWfBusinessForm.fdParameterJson'] = json.dumps(
param_json, separators=(',', ':'), ensure_ascii=False)
payload = list(data.items()) + row_pairs
if config.DEBUG:
config.log('[DEBUG] payload 字段数=%d fdId=%s 明细行数=%d 复核人=%s'
% (len(payload), fd_id, len(rows), [o[1] for o in owners]))
# 7) 提交
post = s.post(config.POST_URL, data=payload, timeout=30, allow_redirects=True)
body = post.text
if send_mode:
# 成功会返回 edit 页(含 ResourceStringCache 等内联 JS,其中可能有
# "Exception"字样,不能用它判断失败);服务端错误页固定含"很抱歉,
# 操作失败"。提交是否真正落库交由下方 edit 页回验兜底。
ok = (post.status_code == 200 and '很抱歉,操作失败' not in body)
else:
ok = ('您的操作已成功' in body) or ('method=edit&fdId=' in body)
if ok:
# 8) edit 页回验:明细每人工号、复核人姓名是否落库
miss = verify_draft(s, fd_id, rows, owners)
if miss:
return fd_id, False, '已提交但回验缺失:%s' % '、'.join(miss)
return fd_id, True, ('发送成功' if send_mode else '草稿成功')
text = re.sub(r'<[^>]+>', ' ', body)
text = re.sub(r'\s+', ' ', text)
m = re.search(r'(很抱歉,操作失败.*?)(?:</|$)', text)
return fd_id, False, (m.group(1)[:200] if m else text[:200])
def verify_draft(s, fd_id, rows, owners):
"""回验落库,返回缺失项列表(空=通过)。
暂存走 edit 页(起草人可编辑);真实发送后单据已进入复核人待办、起草人失去
编辑权(edit 返回 403),须改走 view 页(提交后仍可只读查看)。
"""
resp = s.get((config.VIEW_URL if config.get_send_mode() else config.EDIT_URL)
+ fd_id, timeout=30)
body = resp.text
miss = [r['工号'] for r in rows if r['工号'] not in body]
miss += ['复核人' + o[1] for o in owners if o[1] and o[1] not in body]
return miss
def process_one(s, group, seq):
"""单组处理,含全局重试,返回 (是否成功, fdId/错误)。"""
seq_no, series, owner_nos = group['key']
label = '组%d %s-%s 负责人[%s] %d人' % (
seq, seq_no, series, '/'.join(owner_nos), len(group['rows']))
last_err = ''
for attempt in range(1, config.MAX_RETRY + 1):
try:
fd_id, ok, msg = fill_and_post(s, group)
except Exception:
last_err = '异常: ' + traceback.format_exc(limit=1).replace('\n', ' ')
fd_id, ok, msg = '', False, last_err
if ok:
config.log('%s -> %s fdId=%s' % (label, msg, fd_id))
return True, {'fdId': fd_id, 'message': msg}
last_err = msg
config.log('%s -> 第%d次失败:%s' % (label, attempt, msg))
time.sleep(1)
config.log('%s -> 已重试%d次仍失败' % (label, config.MAX_RETRY))
return False, last_err
# ==================== 推送编排 ====================
def run_push():
"""批量推送编排:读分组 → 逐组提交(含重试)→ 汇总。返回 {summary, detail, path}。"""
row_cnt, groups = read_groups()
config.log('读取 %d 行,分 %d 组(%s | 模式=%s)' % (
row_cnt, len(groups), os.path.basename(config.get_data_file()),
'真实发送' if config.get_send_mode() else '仅暂存'))
s = config.get_oa_session()
items = list(groups.items())
n = len(items)
ok_cnt, fail_list, detail = 0, [], {}
for i, (seq, (key, grp_rows)) in enumerate(items, 1):
config.progress(int(100 * (i - 1) / n) if n else 0)
group = {'key': key, 'rows': grp_rows}
ok, info = process_one(s, group, seq)
label = '组%d %s-%s 负责人[%s]' % (seq, key[0], key[1], '/'.join(key[2]))
detail[label] = {
'seq': seq, 'series': key[1], 'owners': list(key[2]),
'rows': len(grp_rows), 'success': ok, 'result': info,
}
if ok:
ok_cnt += 1
else:
fail_list.append((seq, key, len(grp_rows), info))
config.progress(int(100 * i / n) if n else 100)
config.progress(100)
config.log('==== 完成:成功 %d 组 / 失败 %d 组 ====' % (ok_cnt, len(fail_list)))
for seq, key, cnt, err in fail_list:
config.log('失败 组%d %s-%s 负责人[%s] %d人:%s'
% (seq, key[0], key[1], '/'.join(key[2]), cnt, err))
summary = '定性评价推送完成:成功 %d 组 / 失败 %d 组%s' % (
ok_cnt, len(fail_list),
'(%s)' % '、'.join(str(f[0]) for f in fail_list) if fail_list else '')
return {'summary': summary, 'detail': detail, 'path': config.get_data_file()}
# ==================== 总编排(入口 __init__.py 委托至此) ====================
def run():
"""总编排:批量推送(0-80%)→ 真实发送且勾选核对时追加导出核对(80-100%)。
暂存草稿不发起流程、无可核对单据,故仅 send_mode 且 export_check 时执行第二阶段。
返回 {summary, detail, path}。
"""
config.set_progress_range(0, 80)
result = run_push()
if config.get_send_mode() and config.get_export_check():
from .. import report # 插件内互引,延迟导入避免环
config.set_progress_range(80, 20)
config.log('---- 推送完成,开始导出核对 ----', 'INFO')
export_result = report.run_export()
result['summary'] += ';' + export_result['summary']
result['detail'] = {'推送': result['detail'], '导出核对': export_result['detail']}
result['path'] = [result['path'], export_result['path']]
config.set_progress_range(0, 100)
return result