feat: 新增定性评价推送插件 v1.1.1
This commit is contained in:
@@ -0,0 +1,607 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0038 定性评价推送:OA 绩效评价单批量推送(蓝凌 EKP kmReviewMain)
|
||||
|
||||
功能:
|
||||
读取《定性评价导入明细.xlsx》的「加工辅助表」,按 定性发起标记(序号-部门-序列)
|
||||
+ 部门负责人工号 分组,每组推送一张绩效评价单:
|
||||
- 明细表多行 = 组内成员(按 Excel 行序),A-N 列数据原样填入
|
||||
- 人员类别 = 标记末段序列映射(管理→管理序列、专业→专业序列)
|
||||
- 被评价人(单选)= 第一顺序部门负责人
|
||||
- 绩效复核人(多选)= 全部部门负责人(按工号列顺序)
|
||||
默认仅暂存(草稿箱可见、不发起流程、零通知);确认无误后改 SEND_MODE=True 走真实发送。
|
||||
每组提交成功后自动回验 edit 页(明细工号、复核人是否落库)。
|
||||
|
||||
导出模式(RUN_MODE='export'):按门户查询方案(管理/专业序列定性评价,searchId 固化),
|
||||
以 创建时间=EXPORT_DATE(空=当天)为条件,走 search.do 结构化导出接口:
|
||||
1) dataxml.jsp?s_bean=sysSearchResultExportDictService 取字段字典(两方案模板独立、fd 不同,各自解析)
|
||||
2) GET search.do?method=result 建查询上下文并提取 exportNum 总数
|
||||
3) POST search.do?method=exportResult 直接返回 xls 字节流,落盘到数据源同目录并打印摘要
|
||||
无需解析 HTML;两方案当天实测 90/290 条全部拉全。
|
||||
导出后自动核对:取门户页内嵌登录信息(var userName/loginName)得到登录账号,
|
||||
「当前处理人」含登录账号姓名的行判为异常,生成 *_核对.xlsx(末列「异常标记」)。
|
||||
|
||||
数据源(DATA_FILE / DATA_SHEET,表头行=DATA_HEADER_ROW,首行为提示语):
|
||||
- A-N 列为 OA 明细数据,原样推送(定性得分/定性系数/定性占比/绩效系数/绩效等级留空,
|
||||
由负责人在 OA 端填写定性得分后页面联动计算)
|
||||
- P 列 定性发起标记:格式 序号-部门-序列,末段 管理/专业 决定人员类别
|
||||
- 「部门负责人工号」列:支持多个(、,,;;分隔),按顺序全部解析为绩效复核人
|
||||
|
||||
运行:项目根目录执行 .venv\\Scripts\\python.exe "workflows\\XQ0001-0100\\XQ0038 定性评价推送\\oa_review_push.py"
|
||||
依赖:requests、openpyxl(推送)/ xlrd(导出,仅导出模式用);登录态来自 oa_cookies.json,失效请先更新。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
from collections import OrderedDict
|
||||
|
||||
import requests
|
||||
|
||||
# ============ 配置区(按需修改) ============
|
||||
RUN_MODE = 'push' # 'push'=推送定性评价单;'export'=导出已提交单据数据(见下方导出配置)
|
||||
TEMPLATE_FD_ID = '1994af414ec11b46ca19109447fb6fb6' # 绩效评价单模板
|
||||
BASE_URL = 'https://oa.37du.co'
|
||||
COOKIE_FILE = os.path.join(os.getenv('LOCALAPPDATA'), '37duAutomation',
|
||||
'.sessions', 'oa_cookies.json')
|
||||
DATA_FILE = r'D:\资料\人资\定性评价推送\定性评价导入明细.xlsx'
|
||||
DATA_SHEET = '加工辅助表'
|
||||
DATA_HEADER_ROW = 2 # 表头所在行(首行为提示语)
|
||||
SEND_MODE = True # False=仅暂存草稿;True=真实发送(发起流程、通知复核人,不可逆)
|
||||
TEST_MODE = True # True=测试模式:明细「评价说明」末尾附加【测试】标志,便于负责人识别
|
||||
MAX_RETRY = 3 # 单组失败重试次数
|
||||
DEBUG = False # True 时输出调试信息
|
||||
|
||||
# ---- 导出模式配置(RUN_MODE='export' 时生效) ----
|
||||
MODEL_NAME = 'com.landray.kmss.km.review.model.KmReviewMain'
|
||||
SEARCH_PLANS = OrderedDict([ # 门户查询方案(管理/专业序列定性评价)
|
||||
('管理序列(新)', '199bd93c6d6998ef08fc293409cbc6a7'),
|
||||
('专业序列(新)', '199bd9679aebbf36aab8e224cd698d2b'),
|
||||
])
|
||||
EXPORT_DATE = '' # 创建时间条件(等于);空=运行当天
|
||||
EXPORT_KEYWORDS = ( # 导出列:按字段字典中文名「包含」匹配,两方案各自命中(如专业序列无「定性得分」)
|
||||
'KPI考核得分', 'KPI系数', '被评价人', '部门', '创建时间', '定性得分',
|
||||
'定性考评系数', '定性考评占比', '考核月份', '文档状态',
|
||||
'员工工号', '员工姓名显示值', '最终绩效等级', '最终绩效系数',
|
||||
)
|
||||
# ==========================================
|
||||
|
||||
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
ADD_URL = (BASE_URL + '/km/review/km_review_main/kmReviewMain.do?method=add&fdTemplateId='
|
||||
+ TEMPLATE_FD_ID)
|
||||
EDIT_URL = BASE_URL + '/km/review/km_review_main/kmReviewMain.do?method=edit&fdId='
|
||||
VIEW_URL = BASE_URL + '/km/review/km_review_main/kmReviewMain.do?method=view&fdId='
|
||||
POST_URL = BASE_URL + '/km/review/km_review_main/kmReviewMain.do'
|
||||
SEARCH_URL = BASE_URL + '/sys/search/search.do'
|
||||
DATAXML_URL = BASE_URL + '/sys/common/dataxml.jsp'
|
||||
PORTAL_URL = (BASE_URL + '/sys/portal/page.jsp'
|
||||
'?portalId=174c4a7ebfac0e2a320e0474539b1251')
|
||||
|
||||
# 单头字段
|
||||
FD_REPORTER = 'fd_3b07f5cf6764ec' # 提报人(new_address,页面 JS 自动填当前用户)
|
||||
FD_CATEGORY = 'fd_3b07f60887a0e0' # 人员类别(单选)
|
||||
FD_EVAL_USER = 'fd_3b3ed9a88d549a' # 被评价人(relation_choose 单选)
|
||||
FD_MONTH = 'fd_3e7d96f3848888' # 考核月份
|
||||
FD_REVIEWER = 'fd_3e798512bd3dd8' # 绩效复核人(address 多选)
|
||||
|
||||
# 明细表(模板 fd_3b07f63c1975a2.<行号>.<fd>)字段 → 加工辅助表 A-N 列名
|
||||
DET_PREFIX = 'fd_3b07f63c1975a2'
|
||||
DET_USER_FD = 'fd_3e92ac2eabd704' # 明细行被评价人(address)
|
||||
DET_FIELDS = OrderedDict([
|
||||
('月份', 'fd_3b07f66df3dddc'),
|
||||
('工号', 'fd_3b07f66b2fd146'),
|
||||
('部门1', 'fd_3b07f6961e2d74'),
|
||||
('是否参与强制分布', 'fd_3e859de2c946a4'),
|
||||
('定性得分', 'fd_3e74f39c387020'),
|
||||
('定性系数', 'fd_3e74f39f1d12bc'),
|
||||
('定性占比', 'fd_3e74f3a1ee9b0e'),
|
||||
('KPI系数', 'fd_3b1bced70cac6e'),
|
||||
('KPI得分', 'fd_3b07f65f9c0cba'),
|
||||
('KPI占比', 'fd_3b07f65cbc2212'),
|
||||
('绩效系数', 'fd_3e74f39dcd3e78'),
|
||||
('绩效等级', 'fd_3e74f3a729b0b2'),
|
||||
('评价说明', 'fd_3e7b401a25c082'),
|
||||
])
|
||||
|
||||
SERIES_MAP = {'管理': '管理序列', '专业': '专业序列'}
|
||||
|
||||
TAG_RE = re.compile(r'<input\b[^>]*>|<textarea\b[^>]*>.*?</textarea>', re.S | re.I)
|
||||
ATTR_RE = re.compile(r'''(name|value|type|checked|selected)\s*=\s*("([^"]*)"|'([^']*)')''', re.I)
|
||||
|
||||
|
||||
def log(msg):
|
||||
print(time.strftime('[%H:%M:%S] ') + str(msg), flush=True)
|
||||
|
||||
|
||||
def build_session():
|
||||
s = requests.Session()
|
||||
s.headers.update({"User-Agent": UA,
|
||||
"Referer": BASE_URL + "/km/review/km_review_main/kmReviewMain.do",
|
||||
"Origin": BASE_URL})
|
||||
with open(COOKIE_FILE, encoding='utf-8') as f:
|
||||
for c in json.load(f):
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
s.cookies.set(c["name"], c["value"], domain=c["domain"],
|
||||
path=c.get("path", "/"))
|
||||
return s
|
||||
|
||||
|
||||
def get_attrs(tag):
|
||||
out = {}
|
||||
for m in 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 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 org_search(s, key):
|
||||
"""通讯录查询(orgType=8 人员):key 支持工号精确/姓名模糊,返回 (id, name)。"""
|
||||
resp = s.post(BASE_URL + '/sys/common/dataxml.jsp',
|
||||
data={"s_bean": "organizationDialogSearch", "key": key,
|
||||
"startWith": "", "orgType": "8", "times": "2"}, timeout=20)
|
||||
m = re.search(r'<data\b[^>]*>', resp.text)
|
||||
if not m:
|
||||
return None, None
|
||||
tag = m.group(0)
|
||||
i = re.search(r'''\bid="([^"]+)"''', tag)
|
||||
n = re.search(r'''\bname="([^"]+)"''', tag)
|
||||
return (i.group(1) if i else None, n.group(1) if n else None)
|
||||
|
||||
|
||||
# ---------- 导出模式(search.do 结构化导出) ----------
|
||||
|
||||
def get_export_columns(s, search_id):
|
||||
"""查询方案字段字典,返回 [(fd, 中文名), ...]。"""
|
||||
resp = s.get(DATAXML_URL, params={"s_bean": "sysSearchResultExportDictService",
|
||||
"fdModelName": MODEL_NAME, "searchId": search_id,
|
||||
"type": "opt"}, timeout=20)
|
||||
return re.findall(r'<data\s+key0="([^"]+)"\s+key1="([^"]*)"', resp.text)
|
||||
|
||||
|
||||
def export_plan_once(s, search_id, day, out_path):
|
||||
"""单次导出一个查询方案,返回 (行数, 错误信息);错误信息为空即成功。"""
|
||||
ts = str(int(time.time() * 1000))
|
||||
# 条件槽位与门户抓包一致:v0_2=eq & v1_2=创建时间(当天)
|
||||
base = {"method": "result", "fdModelName": MODEL_NAME, "searchId": search_id,
|
||||
"canClose": "false", "isNew": "true", "j_aside": "false",
|
||||
"j_rIframe": "true", "j_iframe": "true",
|
||||
"v0_2": "eq", "v1_2": day, "j_timestamp": ts}
|
||||
resp = s.get(SEARCH_URL, params=base, timeout=30, headers={"Referer": SEARCH_URL})
|
||||
m = re.search(r'exportNum:\s*"(\d+)"', resp.text)
|
||||
if not m:
|
||||
return None, '结果页未取得 exportNum(登录态可能失效,请更新 oa_cookies.json)'
|
||||
total = int(m.group(1))
|
||||
if total == 0:
|
||||
return 0, ''
|
||||
cols = [fd for fd, name in get_export_columns(s, search_id)
|
||||
if any(kw in name for kw in EXPORT_KEYWORDS)]
|
||||
if not cols:
|
||||
return None, '字段字典未匹配到导出列'
|
||||
data = dict(base)
|
||||
data["method"] = "exportResult"
|
||||
data.update({"fdColumns": ';'.join(cols), "fdNum": str(total),
|
||||
"fdNumStart": "1", "fdNumEnd": str(total),
|
||||
"fdKeepRtfStyle": "true", "checkIdValues": ""})
|
||||
resp = s.post(SEARCH_URL, data=data, timeout=120, headers={"Referer": SEARCH_URL})
|
||||
ctype = resp.headers.get('Content-Type', '')
|
||||
if 'application/vnd.ms-excel' not in ctype:
|
||||
text = re.sub(r'\s+', ' ', re.sub(r'<[^>]+>', ' ', resp.text))
|
||||
return None, '导出返回非 xls(%s):%s' % (ctype, text[:150])
|
||||
with open(out_path, 'wb') as f:
|
||||
f.write(resp.content)
|
||||
return total, ''
|
||||
|
||||
|
||||
def get_login_user(s):
|
||||
"""门户页内嵌登录信息,返回 (姓名 userName, 登录名/工号 loginName)。"""
|
||||
resp = s.get(PORTAL_URL, timeout=30)
|
||||
name = re.search(r"var\s+userName\s*=\s*'([^']*)'", resp.text)
|
||||
no = re.search(r"var\s+loginName\s*=\s*'([^']*)'", resp.text)
|
||||
return (name.group(1) if name else '', no.group(1) if no else '')
|
||||
|
||||
|
||||
def audit_xls(path, user_name):
|
||||
"""核对导出 xls:「当前处理人」含登录账号姓名 -> 异常,生成 *_核对.xlsx。
|
||||
|
||||
返回异常行数(user_name 为空时跳过核对返回 -1)。
|
||||
导出表只有姓名文本、无处理人工号列(字段字典无此字段),故按姓名匹配。
|
||||
"""
|
||||
import openpyxl
|
||||
import xlrd
|
||||
wb = xlrd.open_workbook(path)
|
||||
sh = wb.sheet_by_index(0)
|
||||
head = [str(sh.cell_value(0, c)) for c in range(sh.ncols)]
|
||||
if '当前处理人' not in head:
|
||||
log(' 核对跳过:导出表无「当前处理人」列')
|
||||
return -1
|
||||
proc_idx = head.index('当前处理人')
|
||||
key_idx = {n: (head.index(n) if n in head else -1)
|
||||
for n in ('员工工号', '被评价人', '当前环节')}
|
||||
rows_out, bad = [], []
|
||||
for r in range(sh.nrows):
|
||||
vals = []
|
||||
for c in range(sh.ncols):
|
||||
v = sh.cell_value(r, c)
|
||||
if isinstance(v, float) and '时间' in head[c]:
|
||||
try:
|
||||
v = xlrd.xldate.xldate_as_datetime(v, wb.datemode).strftime(
|
||||
'%Y-%m-%d %H:%M')
|
||||
except Exception:
|
||||
pass
|
||||
vals.append('' if v is None else str(v))
|
||||
if r == 0:
|
||||
vals.append('异常标记')
|
||||
else:
|
||||
handlers = [x.strip() for x in re.split(r'[;;,,]', vals[proc_idx])
|
||||
if x.strip()]
|
||||
mark = '异常:当前处理人含登录账号' if user_name and user_name in handlers else ''
|
||||
if mark:
|
||||
bad.append(vals)
|
||||
vals.append(mark)
|
||||
rows_out.append(vals)
|
||||
out_path = re.sub(r'\.xls$', '_核对.xlsx', path)
|
||||
owb = openpyxl.Workbook()
|
||||
osh = owb.active
|
||||
osh.title = '核对结果'
|
||||
for vals in rows_out:
|
||||
osh.append(vals)
|
||||
owb.save(out_path)
|
||||
log(' sheet=%s 行=%d(含表头) 列=%d -> %s'
|
||||
% (sh.name, sh.nrows, sh.ncols, os.path.basename(out_path)))
|
||||
log(' 异常 %d 行(当前处理人=%s)' % (len(bad), user_name or '未知,未核对'))
|
||||
for vals in bad[:20]:
|
||||
log(' %s | %s | %s | 处理人=%s' % (
|
||||
vals[key_idx['员工工号']], vals[key_idx['被评价人']],
|
||||
vals[key_idx['当前环节']], vals[proc_idx]))
|
||||
return len(bad)
|
||||
|
||||
|
||||
def run_export():
|
||||
day = EXPORT_DATE or time.strftime('%Y-%m-%d')
|
||||
out_dir = os.path.dirname(DATA_FILE)
|
||||
s = build_session()
|
||||
log('导出模式:创建时间=%s,方案 %d 个' % (day, len(SEARCH_PLANS)))
|
||||
user_name, login_no = get_login_user(s)
|
||||
if user_name:
|
||||
log('登录账号:%s(%s),将核对当前处理人' % (user_name, login_no))
|
||||
else:
|
||||
log('警告:未取得门户登录账号,跳过当前处理人核对')
|
||||
fail = []
|
||||
for name, sid in SEARCH_PLANS.items():
|
||||
label = name.split('(')[0]
|
||||
out_path = os.path.join(out_dir, '定性评价结果_%s_%s.xls'
|
||||
% (label, day.replace('-', '')))
|
||||
last_err = ''
|
||||
for attempt in range(1, MAX_RETRY + 1):
|
||||
try:
|
||||
total, err = export_plan_once(s, sid, day, out_path)
|
||||
except Exception:
|
||||
total, err = None, '异常: ' + traceback.format_exc(limit=1).replace('\n', ' ')
|
||||
if not err:
|
||||
log('%s -> %d 条 -> %s' % (name, total, out_path))
|
||||
if total:
|
||||
audit_xls(out_path, user_name)
|
||||
break
|
||||
last_err = err
|
||||
log('%s -> 第%d次失败:%s' % (name, attempt, err))
|
||||
time.sleep(1)
|
||||
else:
|
||||
fail.append((name, last_err))
|
||||
log('==== 导出完成:成功 %d / 失败 %d ====' % (len(SEARCH_PLANS) - len(fail), len(fail)))
|
||||
for name, err in fail:
|
||||
log('失败 %s:%s' % (name, err))
|
||||
return 0 if not fail else 1
|
||||
|
||||
|
||||
# ---------- 数据读取与分组 ----------
|
||||
|
||||
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(DATA_FILE, read_only=True, data_only=True)
|
||||
if DATA_SHEET not in wb.sheetnames:
|
||||
raise ValueError('数据文件缺少 sheet:%s(现有:%s)'
|
||||
% (DATA_SHEET, '/'.join(wb.sheetnames)))
|
||||
ws = wb[DATA_SHEET]
|
||||
it = ws.iter_rows(values_only=True)
|
||||
for _ in range(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(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 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']
|
||||
|
||||
# 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(ADD_URL, timeout=30)
|
||||
page = resp.text
|
||||
if 'kmReviewMainForm' not in page:
|
||||
return '', False, 'add 页加载异常(登录态可能失效,请更新 oa_cookies.json)'
|
||||
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)' % FD_CATEGORY] = SERIES_MAP[series]
|
||||
# 被评价人(人员类别2,relationChoose 关联工号串):实测手动发起的成功单据该字段为空,
|
||||
# 子流程(N7 启动子流程)数据映射依赖它;若填入"工号字符串"会使子流程被评价人解析失效,
|
||||
# 报"启动子流程失败,存在处理人为空或失效"。故留空(与手动发起一致)。
|
||||
for suffix in ('', '_text', '_dataFdId', '_dataSourceId', '_dataModelName',
|
||||
'_selectedDatas'):
|
||||
data['extendDataFormInfo.value(%s%s)' % (FD_EVAL_USER, suffix)] = ''
|
||||
# 考核月份(取组内首行月份,与明细一致)
|
||||
data['extendDataFormInfo.value(%s)' % FD_MONTH] = rows[0]['月份']
|
||||
# 绩效复核人(多选地址本,分号分隔、按工号列顺序)
|
||||
data['extendDataFormInfo.value(%s.id)' % FD_REVIEWER] = ';'.join(o[0] for o in owners)
|
||||
data['extendDataFormInfo.value(%s.name)' % FD_REVIEWER] = ';'.join(o[1] for o in owners)
|
||||
|
||||
# 5) 明细多行(A-N 列原样,行序=Excel 行序)
|
||||
det_prefix = 'extendDataFormInfo.value(%s.' % 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 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, DET_USER_FD), m_id))
|
||||
row_pairs.append(('%s%d.%s.name)' % (det_prefix, i, 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 中整体转义(< " 等),需先反转义再解析。
|
||||
m_xml = re.search(
|
||||
r'name="sysWfBusinessForm\.fdCurNodeXML"[^>]*value="([^"]*)"', page)
|
||||
raw = m_xml.group(1) if m_xml else ''
|
||||
raw = raw.replace('"', '"').replace('<', '<').replace('>', '>')
|
||||
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)' % FD_REPORTER] = identity_id
|
||||
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 DEBUG:
|
||||
log('[DEBUG] payload 字段数=%d fdId=%s 明细行数=%d 复核人=%s'
|
||||
% (len(payload), fd_id, len(rows), [o[1] for o in owners]))
|
||||
|
||||
# 7) 提交
|
||||
post = s.post(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((VIEW_URL if SEND_MODE else 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):
|
||||
"""单组处理,含全局重试。"""
|
||||
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, 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:
|
||||
log('%s -> %s fdId=%s' % (label, msg, fd_id))
|
||||
return True, fd_id
|
||||
last_err = msg
|
||||
log('%s -> 第%d次失败:%s' % (label, attempt, msg))
|
||||
time.sleep(1)
|
||||
log('%s -> 已重试%d次仍失败' % (label, MAX_RETRY))
|
||||
return False, last_err
|
||||
|
||||
|
||||
def main():
|
||||
if RUN_MODE == 'export':
|
||||
return run_export()
|
||||
row_cnt, groups = read_groups()
|
||||
log('读取 %d 行,分 %d 组(%s | 模式=%s)' % (
|
||||
row_cnt, len(groups), os.path.basename(DATA_FILE),
|
||||
'真实发送' if SEND_MODE else '仅暂存'))
|
||||
s = build_session()
|
||||
ok_cnt, fail_list = 0, []
|
||||
for seq, (key, grp_rows) in enumerate(groups.items(), 1):
|
||||
ok, info = process_one(s, {'key': key, 'rows': grp_rows}, seq)
|
||||
if ok:
|
||||
ok_cnt += 1
|
||||
else:
|
||||
fail_list.append((seq, key, len(grp_rows), info))
|
||||
log('==== 完成:成功 %d 组 / 失败 %d 组 ====' % (ok_cnt, len(fail_list)))
|
||||
for seq, key, cnt, err in fail_list:
|
||||
log('失败 组%d %s-%s 负责人[%s] %d人:%s'
|
||||
% (seq, key[0], key[1], '/'.join(key[2]), cnt, err))
|
||||
return 0 if not fail_list else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user