新增步骤7脚本,实现OA待办对账销办逻辑: 1. 解析OA待办链路由fdId获取HR任务ID 2. 核对任务/流程状态,仅销办COMPLETED状态的待办 3. 校验账号权限,仅处理当前人资账号待办 4. 支持试算模式,避免误操作 同时更新XQ0035转正流程规则,将分支1回填条件从"到期能否考核通过=能"调整为"人员处理意见=直接离职/无需处理",并更新XQ0037合同模板逻辑,为超龄人员配置专用合同模板组合
264 lines
12 KiB
Python
264 lines
12 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""通联平台交易数据导出(xq0045_xq0046 插件内自包含)。
|
||
|
||
服务端行为已探明(探针 workflows/share/debug_tranx25 实测验证):
|
||
- 请求必须带 Referer,否则被重定向回 /main.dsr;
|
||
- 商户列表内嵌在搜索页 JS:var childcuslist = '[{"key":"商户号","value":"商户名"},...]';
|
||
- 查询:POST /tranx25/search,data={issubmit,cusid,startDate,endDate,export:false,pageIndex,
|
||
canemptycusid},响应为整页 HTML(结果表格 #dataTable);
|
||
- 导出(异步三步),插件走页面「一键导出」export=onebtnexpt(账号全量):
|
||
1) POST /tranx25/search 带 export=onebtnexpt → JSON {"code":"0","message":"<fid>"}(code=1 失败);
|
||
2) POST /export/statusdownload {id:fid} 每 6 秒轮询至 code=0(就绪);
|
||
3) POST /export/downloadexport/ {id:fid} → {"code":"0","message":"<下载URL>"} → GET 落文件。
|
||
- 页面另有一个「导出」按钮(export=true,按 cusid 查询条件过滤,人工按门店导用这个):
|
||
与 onebtnexpt 逐笔数据实测一致,仅文件结构不同(export=true 33 列、无「汇总」sheet)。
|
||
"""
|
||
import json
|
||
import os
|
||
import re
|
||
import time
|
||
import zipfile
|
||
from datetime import datetime, timedelta
|
||
from pathlib import Path
|
||
|
||
from .. import config
|
||
|
||
|
||
# ==================== HTTP 封装(统一带 Referer) ====================
|
||
def _get(session, url, **kw):
|
||
return session.get(url, headers=config.SEARCH_HEADERS, timeout=20, **kw)
|
||
|
||
|
||
def _post(session, url, data=None, **kw):
|
||
return session.post(url, data=data, headers=config.SEARCH_HEADERS, timeout=30, **kw)
|
||
|
||
|
||
def _parse_code_message(text):
|
||
"""解析服务端返回的 JS 风格对象(单引号,如 {code:'0',message:'fid'})。
|
||
|
||
前端用 eval('('+data+')') 解析,说明响应不是标准 JSON;
|
||
先试标准 JSON,失败再正则提取 code/message。返回 (code, message)。
|
||
"""
|
||
text = (text or '').strip()
|
||
try:
|
||
j = json.loads(text)
|
||
return str(j.get('code')), str(j.get('message') or '')
|
||
except Exception:
|
||
pass
|
||
m_code = re.search(r"code\s*:\s*'?([^',}]+)'?", text)
|
||
m_msg = re.search(r"message\s*:\s*'([^']*)'", text)
|
||
code = m_code.group(1).strip() if m_code else ''
|
||
msg = m_msg.group(1) if m_msg else ''
|
||
if not (m_code or m_msg):
|
||
raise RuntimeError(f"响应无法解析(可能会话失效被踢回页面):{text[:200]}")
|
||
return code, msg
|
||
|
||
|
||
# ==================== 商户列表 ====================
|
||
def get_cus_list(session):
|
||
"""GET 搜索页解析 childcuslist → [{'key': 商户号, 'value': 商户名}, ...]。"""
|
||
resp = _get(session, config.SEARCH_URL)
|
||
m = re.search(r"var childcuslist\s*=\s*'([^']*)'", resp.text)
|
||
if not m:
|
||
raise RuntimeError("搜索页未找到 childcuslist(会话可能失效,请重新登录)")
|
||
data = json.loads(m.group(1))
|
||
if not isinstance(data, list):
|
||
raise RuntimeError("childcuslist 解析异常")
|
||
return data
|
||
|
||
|
||
# ==================== 异步导出三步 ====================
|
||
def start_export(session, cusid, start, end):
|
||
"""发起导出 → 返回 fid。
|
||
|
||
导出语义(探针实测):
|
||
- export=onebtnexpt = 页面「一键导出」,账号全量(含所有商户),不受 cusid 过滤;
|
||
- export=true = 页面「导出」,按 cusid 查询条件过滤(人工按门店导用这个),
|
||
导出 0 笔门店时返回 HTML 错误页而非空文件;
|
||
- export=all = 忽略日期区间、导出当天全量(错误行为),勿用。
|
||
两种可用方式的数据逐笔实测一致,仅文件结构不同(export=true 33 列、无「汇总」sheet),
|
||
故这里只导一份全量,由调用方按商户名拆分。
|
||
流程:先 export=false 查询建立结果集,再用 onebtnexpt 导出;cusid 传账号下任一真实
|
||
商户号即可(实测空串也能跑,但不依赖该行为)。
|
||
"""
|
||
base = {
|
||
'issubmit': 'issubmit',
|
||
'cusid': cusid,
|
||
'startDate': start,
|
||
'endDate': end,
|
||
'pageIndex': '1',
|
||
'canemptycusid': 'true',
|
||
}
|
||
# 1) 查询建立结果集(export=false)
|
||
_post(session, config.SEARCH_URL, {**base, 'export': 'false'})
|
||
# 2) 导出当前结果集(onebtnexpt)
|
||
code, msg = _parse_code_message(
|
||
_post(session, config.SEARCH_URL, {**base, 'export': config.EXPORT_CURRENT}).text)
|
||
if code == '1':
|
||
raise RuntimeError(f"导出失败:{msg}")
|
||
fid = msg
|
||
if not fid:
|
||
raise RuntimeError("导出响应缺少 fid")
|
||
return fid
|
||
|
||
|
||
def wait_export_done(session, fid):
|
||
"""轮询导出状态,直到就绪(code=0)或超时。
|
||
|
||
状态契约(探针实测):code='0'=文件就绪;code='1'=生成中。
|
||
其它码(如 '2' 失败)只告警不判就绪,避免误把失败态当成功去取下载地址;
|
||
超时错误里带最后状态,便于定位。
|
||
"""
|
||
last = ""
|
||
for i in range(1, config.STATUS_POLL_MAX + 1):
|
||
code, msg = _parse_code_message(_post(session, config.STATUS_URL, {'id': fid}).text)
|
||
last = f"code={code} {msg}".strip()
|
||
if code == '0':
|
||
config.log(f"[导出] fid={fid} 文件就绪(轮询 {i} 次)")
|
||
return True
|
||
if code != '1':
|
||
config.log(f"[导出] fid={fid} 状态异常({last}),继续等待", "WARN")
|
||
else:
|
||
# 每次轮询都打进度,避免长时间静默被误认为卡死
|
||
config.log(f"[导出] fid={fid} 文件生成中(第 {i} 次轮询,已等待 {i * config.STATUS_POLL_INTERVAL} 秒)…")
|
||
time.sleep(config.STATUS_POLL_INTERVAL)
|
||
raise RuntimeError(f"导出超时(服务端未在时限内生成文件,最后状态:{last})")
|
||
|
||
|
||
def get_download_url(session, fid):
|
||
"""获取下载地址。"""
|
||
code, msg = _parse_code_message(_post(session, config.DOWNLOAD_INFO_URL, {'id': fid}).text)
|
||
if code != '0':
|
||
raise RuntimeError(f"获取下载地址失败:{msg}")
|
||
return msg
|
||
|
||
|
||
# ==================== 下载校验 ====================
|
||
def _check_download_content_type(resp):
|
||
"""下载响应 Content-Type 校验:HTML/文本说明可能被踢回登录页,直接报错。"""
|
||
ct = (resp.headers.get('Content-Type') or '').lower()
|
||
if 'html' in ct or ct.startswith('text/'):
|
||
raise RuntimeError(
|
||
f"下载返回非文件内容(Content-Type={ct or 'unknown'}),会话可能已失效,请重新登录")
|
||
|
||
|
||
def _is_zip_file(path):
|
||
"""文件头魔数校验:zip/xlsx 均以 PK 开头。"""
|
||
try:
|
||
with open(path, 'rb') as f:
|
||
return f.read(2) == b'PK'
|
||
except OSError:
|
||
return False
|
||
|
||
|
||
def _safe_extract(zip_path, extract_dir):
|
||
"""解压 zip,并拦截路径穿越条目(.. / 绝对路径)。"""
|
||
with zipfile.ZipFile(zip_path) as zf:
|
||
for info in zf.infolist():
|
||
parts = Path(info.filename).parts
|
||
if info.filename.startswith('/') or '..' in parts or ':' in parts:
|
||
raise RuntimeError(f"压缩包含非法路径条目,已中止解压:{info.filename}")
|
||
zf.extractall(extract_dir)
|
||
|
||
|
||
def download_file(session, url, folder, stem):
|
||
"""下载导出文件到 folder/,文件名 stem + 扩展名(优先 Content-Disposition,默认 .xlsx)。
|
||
返回最终文件路径。带 Content-Type 与文件魔数校验,防会话失效时把 HTML 落成伪文件。"""
|
||
resp = session.get(url, headers=config.SEARCH_HEADERS, timeout=180, stream=True)
|
||
resp.raise_for_status()
|
||
_check_download_content_type(resp)
|
||
ext = '.xlsx'
|
||
cd = resp.headers.get('Content-Disposition', '')
|
||
m = re.search(r'filename\*?=(?:UTF-8\'\')?"?([^\";]+)"?', cd, re.I)
|
||
if m:
|
||
nm = m.group(1).strip().strip('"')
|
||
if '.' in nm:
|
||
ext = '.' + nm.rsplit('.', 1)[1].lower()
|
||
os.makedirs(folder, exist_ok=True)
|
||
path = os.path.join(folder, f"{stem}{ext}")
|
||
total = int(resp.headers.get('Content-Length') or 0)
|
||
received, last_log = 0, time.time()
|
||
with open(path, 'wb') as f:
|
||
for chunk in resp.iter_content(chunk_size=8192):
|
||
f.write(chunk)
|
||
received += len(chunk)
|
||
now = time.time()
|
||
if now - last_log >= 8: # 每 8 秒报一次下载进度,避免长下载静默
|
||
last_log = now
|
||
mb = received / 1048576
|
||
if total:
|
||
pct = received * 100 // max(1, total)
|
||
config.log(f"[导出] 下载中 {mb:.1f}MB / {total / 1048576:.1f}MB({pct}%)…")
|
||
else:
|
||
config.log(f"[导出] 下载中 {mb:.1f}MB…")
|
||
if not _is_zip_file(path): # xlsx 本质是 zip,文件头须为 PK
|
||
os.remove(path)
|
||
raise RuntimeError(f"下载文件不是有效 xlsx(文件头异常),已删除:{path}")
|
||
config.log(f"[导出] 已保存:{path}({received / 1048576:.1f} MB)")
|
||
return path
|
||
|
||
|
||
# ==================== 日期范围 ====================
|
||
def build_date_range(mode, date_str):
|
||
"""按模式把日期字符串转成查询区间 (start, end)。
|
||
mode='月':date_str=YYYY-MM → 当月 1 日 10:00:00 ~ 下月 1 日 10:00:00(对账 10 点切日口径);
|
||
mode='日':date_str=YYYY-MM-DD(数据起始日,默认昨天)→ 当天 00:00:00 ~ 次日 23:59:59
|
||
(即默认 = 昨天0点 ~ 今天24点,今天数据少基本无影响)。"""
|
||
if mode == '月':
|
||
ym = datetime.strptime(date_str, '%Y-%m')
|
||
next_month = (ym.replace(day=1) + timedelta(days=32)).replace(day=1)
|
||
return (ym.strftime('%Y-%m-01 10:00:00'),
|
||
next_month.strftime('%Y-%m-01 10:00:00'))
|
||
d = datetime.strptime(date_str, '%Y-%m-%d')
|
||
nxt = d + timedelta(days=1)
|
||
return d.strftime('%Y-%m-%d 00:00:00'), nxt.strftime('%Y-%m-%d 23:59:59')
|
||
|
||
|
||
def default_dates(mode):
|
||
"""未填日期时的默认值:日=昨天;月=上月。"""
|
||
today = datetime.now()
|
||
if mode == '月':
|
||
first_this = today.replace(day=1)
|
||
last_month = first_this - timedelta(days=1)
|
||
return last_month.strftime('%Y-%m')
|
||
yesterday = today - timedelta(days=1)
|
||
return yesterday.strftime('%Y-%m-%d')
|
||
|
||
|
||
# ==================== 账单导出(主账号,zip 下载 + 解压) ====================
|
||
def bill_download(session, date_str, bill_type, folder):
|
||
"""通联账单下载(只导主账号/当前商户)。
|
||
|
||
POST /checkacct25/download:日账单 ?reportdate=YYYYMMDD;月账单 ?type=month&reportdate=YYYYMM。
|
||
服务端返回 {"code":"0","message":"<zip 下载 URL>"},GET 下载 zip 并解压。
|
||
date_str = YYYY-MM-DD(日)或 YYYY-MM(月);bill_type = 'day' | 'month'。
|
||
返回 (zip_path, extract_dir)。
|
||
"""
|
||
reportdate = date_str.replace('-', '')
|
||
params = {'reportdate': reportdate}
|
||
if bill_type == 'month':
|
||
params['type'] = 'month'
|
||
resp = _post(session, config.BILL_URL, params=params)
|
||
code, msg = _parse_code_message(resp.text)
|
||
if code != '0':
|
||
raise RuntimeError(f"账单下载失败:{msg}")
|
||
url = msg
|
||
|
||
os.makedirs(folder, exist_ok=True)
|
||
zr = session.get(url, headers=config.SEARCH_HEADERS, timeout=180, stream=True)
|
||
zr.raise_for_status()
|
||
_check_download_content_type(zr)
|
||
prefix = '日账单' if bill_type == 'day' else '月账单'
|
||
zip_path = os.path.join(folder, f"{prefix}_{date_str}.zip")
|
||
with open(zip_path, 'wb') as f:
|
||
for chunk in zr.iter_content(chunk_size=8192):
|
||
f.write(chunk)
|
||
if not _is_zip_file(zip_path):
|
||
os.remove(zip_path)
|
||
raise RuntimeError(f"账单下载不是有效 zip(文件头异常),已删除:{zip_path}")
|
||
|
||
extract_dir = os.path.join(folder, f"{prefix}_{date_str}")
|
||
_safe_extract(zip_path, extract_dir)
|
||
config.log(f"[账单] 已下载并解压:{extract_dir}")
|
||
return zip_path, extract_dir
|