Files
37duAutomation/plugins/XQ0001-0100/XQ0047 微盟数据导出/data/weimob_export.py
T
puddy 01b21551c4 feat(XQ0047): 微盟数据导出插件 v1.0.2 版本更新,拆分合并单元格并优化导出
新增合并单元格拆分逻辑,将微盟导出Excel中同一订单的纵向合并单元格值填充到区域内每一行,使每行数据自包含便于筛选统计
更新插件版本号、打包脚本及需求文档中的版本信息
2026-10-21 16:16:34 +08:00

579 lines
25 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 -*-
"""XQ0047 微盟订单数据导出主流程(xq0047 插件内自包含)。
自 workflows/XQ0001-0100/XQ0047 微盟数据导出/wm_export.py 迁移,插件化改造点:
- print → config.log(转发 ctx.log);商家标识/URL/运行参数统一收敛到 config;
- 输出目录由 run() 传入;阶段进度经 progress 回调上报 ctx.progress。
导出策略(与原流程一致):
1) queryOrderList 探测「上月1日0:00~此刻」订单总数 totalCount;
2) 按 ceil(total / SEG_TARGET) 等分时间区间,再用新时段逐段探测校验:
满足阈值则定稿,超限则按 ceil(cnt / SEG_TARGET) 继续等分,直到每段都不超限;
3) 批量创建 exportOrder 导出任务(异步,不逐段等待);
4) 统一轮询 download/list 一次取回全部任务状态,全部完成后再并发下载 zip 解压;
5) 各段 Excel 的全部 sheet 数据合并到同一个工作表,输出单个最终 xlsx。
"""
import math
import os
import random
import re
import shutil
import time
import zipfile
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timezone, timedelta
from openpyxl import Workbook, load_workbook
from openpyxl.utils.cell import range_boundaries
from .. import config
from .weimob_login import build_session
# ================== 工具函数 ==================
def _sleep_interval():
"""请求间/段间限流:随机 3~5 秒,模拟人工节奏,降低风控触发概率。"""
time.sleep(random.uniform(config.INTERVAL_MIN, config.INTERVAL_MAX))
def _time_range():
"""时间范围:上月1日 00:00:00(北京时间)~ 此刻。返回毫秒时间戳 (start, end)。"""
cn_tz = timezone(timedelta(hours=8))
now = datetime.now(cn_tz)
if now.month == 1:
start_dt = datetime(now.year - 1, 12, 1, 0, 0, 0, tzinfo=cn_tz)
else:
start_dt = datetime(now.year, now.month - 1, 1, 0, 0, 0, tzinfo=cn_tz)
return int(start_dt.timestamp() * 1000), int(now.timestamp() * 1000)
def _fmt_range(a, b):
"""区间可读标签(北京时间)。"""
return (f"[{datetime.fromtimestamp(a / 1000):%m-%d %H:%M} ~ "
f"{datetime.fromtimestamp(b / 1000):%m-%d %H:%M}]")
def _emit(progress, pct):
"""上报进度(回调可能为 None;异常不影响主流程)。"""
if progress:
try:
progress(int(pct))
except Exception:
pass
# ================== 请求体模板 ==================
def _build_basic_info():
return {
"tcode": config.TCODE, "merchantId": config.MERCHANT_ID, "bosId": int(config.BOS_ID),
"vid": config.VID, "vidType": 2, "vidTypeName": "品牌", "vidTypes": [2],
"parentVid": 0, "vidPath": f"-{config.VID}-", "vidDeleted": False,
"vidStatus": 1, "wxOnlineStatus": 0, "onlineStoreStatus": 0,
"onlineStoreAbilityType": 1, "onlineStoreAbilityRelationVid": None,
"activeStatus": True, "vidRelation": True, "isRootVid": True,
"productId": config.PRODUCT_ID, "productVersionId": config.PRODUCT_VERSION_ID,
"productInstanceId": config.PRODUCT_INSTANCE_ID,
"statusCode": "in_use", "vidName": "金色印象商城", "productName": "商城",
"productVersionName": "商城连锁-PE", "overPrivilegeTime": None,
"rootVid": config.VID, "rootVidType": 2, "packCode": None,
}
def _query_param(start_ms, end_ms):
"""与 exportOrder 完全一致的查询条件(orderTypes 等保持一致,保证条数探测准确)。"""
return {
"orderStatuses": [], "urgePayTimeType": -1, "needBuyerHeadUrl": True,
"bizSourceTypes": [-1], "searchType": 4, "keyword": "",
"queryTime": {"type": 0, "startTime": start_ms, "endTime": end_ms},
"processVids": [], "vids": [], "orderAssign": 0, "flagRanks": [],
"channelTypes": [], "orderSources": [-1], "deliveryMode": [-1],
"orderTypes": [1, 98, 96, 11, 12], "goodsSellModes": [], "subGoodsTypes": [],
"paymentTypes": [], "deliveryTypes": [], "activities": [], "labelTypes": [],
"warehouseIds": [], "queryAmount": {"type": 1, "minAmount": "", "maxAmount": ""},
"searchScene": 0,
}
def _build_export_body(start_ms, end_ms):
"""exportOrder 请求体(exportFieldCodeList 全 null=默认导出列;仅 queryTime 动态)。"""
return {
"basicInfo": _build_basic_info(),
"operationSource": 1,
"exportFieldCodeList": [None] * 142,
"exportFormat": 1,
"exportType": 1,
"orderMenuCode": 5,
"queryParameter": _query_param(start_ms, end_ms),
"i18n": {"language": "zh-CN", "timezone": 8},
"extendInfo": {"refer": config.REFER_EXTEND, "source": 80},
}
def _build_query_body(start_ms, end_ms):
"""queryOrderList 请求体(分页,用于探测区间条数)。"""
return {
"basicInfo": _build_basic_info(),
"operationSource": 1,
"pageNum": 1,
"pageSize": 1,
"queryParameter": _query_param(start_ms, end_ms),
"i18n": {"language": "zh-CN", "timezone": 8},
"extendInfo": {"refer": config.REFER_EXTEND, "source": 80},
}
def _build_dl_body(page_size=20):
"""download/list 请求体(分页取最近导出记录,page_size 按本轮段数放大)。"""
return {
"bosId": config.BOS_ID,
"pageSize": page_size,
"basicInfo": {
"merchantId": config.MERCHANT_ID, "bosId": int(config.BOS_ID), "vid": config.VID,
"vidType": 2, "vidTypes": [2], "productId": config.PRODUCT_ID,
"productVersionId": config.PRODUCT_VERSION_ID,
"productInstanceId": config.PRODUCT_INSTANCE_ID, "tcode": config.TCODE,
},
"i18n": {"language": "zh-CN", "timezone": 8},
"extendInfo": {"refer": config.REFER_EXTEND, "source": 80},
}
# ================== 区间探测与切分 ==================
def query_count(session, start_ms, end_ms):
"""调用 queryOrderList 返回区间订单总数(失败返回 -1)。"""
try:
resp = session.post(config.QUERY_LIST_URL, json=_build_query_body(start_ms, end_ms),
timeout=config.TIMEOUT)
data = resp.json() if resp.status_code == 200 else {}
if data.get("errcode") == "0":
return int((data.get("data") or {}).get("totalCount") or 0)
config.log(f"queryOrderList 异常:{str(data)[:200]}", "WARN")
except Exception as e:
config.log(f"queryOrderList 请求异常:{e}", "WARN")
return -1
def _split_equal(start_ms, end_ms, n):
"""把 [start_ms, end_ms] 等分为 n 段(毫秒),返回不重叠、连续覆盖的区间列表。"""
n = max(1, n)
span = end_ms - start_ms + 1
step = -(-span // n) # 向上取整,保证 n 段覆盖整区间
segments = []
cur = start_ms
for _ in range(n):
if cur + step - 1 >= end_ms:
segments.append((cur, end_ms))
break
segments.append((cur, cur + step - 1))
cur += step
return segments
def plan_segments(session, start_ms, end_ms):
"""按条数等分 + 逐段校验细分,最小化导出次数。
返回 (segments, total):total < 0 表示探测失败;total == 0 表示区间无订单。
"""
total = query_count(session, start_ms, end_ms)
if total < 0:
return [], -1
config.log(f"总区间订单数:{total}")
if total == 0:
return [], 0
if total <= config.SEG_TARGET:
return [(start_ms, end_ms)], total
n = math.ceil(total / config.SEG_TARGET)
queue = _split_equal(start_ms, end_ms, n)
config.log(f"按 {config.SEG_TARGET} 单/段向上取整,先等分为 {n} 段,逐段探测校验:")
segments = []
probe_limit = 200 # 防御:探测次数上限,避免异常数据导致无限细分
probes = 0
while queue:
probes += 1
if probes > probe_limit:
config.log("警告:细分探测次数超限,中止", "ERROR")
return [], total
a, b = queue.pop(0)
_sleep_interval()
cnt = query_count(session, a, b)
if cnt < 0:
return [], total
label = _fmt_range(a, b)
if cnt <= config.SEG_TARGET:
segments.append((a, b))
config.log(f" ✓ {label} 订单数={cnt} → 定稿")
continue
if b - a < config.MIN_SPLIT_MS:
config.log(f" ! {label} 订单数={cnt} 超限但已到最小粒度,直接导出尝试", "WARN")
segments.append((a, b))
continue
k = math.ceil(cnt / config.SEG_TARGET)
config.log(f" ↻ {label} 订单数={cnt} 超限 → 再等分 {k} 段")
queue[0:0] = _split_equal(a, b, k) # 保持时间顺序继续校验
segments.sort()
return segments, total
# ================== 导出流程 ==================
def create_export_task(session, start_ms, end_ms):
"""调用 exportOrder 创建导出任务,成功返回触发时间戳(用于匹配任务)。"""
body = _build_export_body(start_ms, end_ms)
trigger_ms = int(time.time() * 1000) # 调用前记录:任务创建时间必然在此之后,匹配更稳
for attempt in range(1, config.RETRY_MAX + 1):
try:
resp = session.post(config.EXPORT_URL, json=body, timeout=config.TIMEOUT)
data = resp.json() if resp.status_code == 200 else {}
if data.get("errcode") == "0" and (data.get("data") or {}).get("success"):
return trigger_ms
config.log(f"exportOrder 第{attempt}次失败:{str(data)[:200]}", "WARN")
except Exception as e:
config.log(f"exportOrder 第{attempt}次异常:{e}", "WARN")
if attempt < config.RETRY_MAX:
_sleep_interval()
return None
def _parse_create_ms(item):
"""解析导出记录的 createTime 为毫秒时间戳;失败返回 None。"""
try:
dt = datetime.fromisoformat((item.get("createTime") or "").replace("Z", "+00:00"))
return dt.timestamp() * 1000
except Exception:
return None
def _task_in_window(item, lo_ms, hi_ms):
"""判断导出记录是否属于某段任务:状态成功 + 订单导出 + createTime 落在时间窗内。"""
if item.get("status") != 1 or "订单导出" not in (item.get("fileName") or ""):
return False
ct = _parse_create_ms(item)
if ct is None:
return False
return ct >= lo_ms and (hi_ms is None or ct < hi_ms)
def _fetch_download_items(session, page_size):
"""取最近导出记录列表;失败返回 None。"""
try:
resp = session.post(config.DOWNLOAD_LIST_URL, json=_build_dl_body(page_size),
timeout=config.TIMEOUT)
data = resp.json() if resp.status_code == 200 else {}
if data.get("errcode") != "0":
config.log(f"download/list 返回异常:{str(data)[:200]}", "WARN")
return None
return (data.get("data") or {}).get("items") or []
except Exception as e:
config.log(f"download/list 异常:{e}", "WARN")
return None
def create_export_tasks(session, segments, progress=None):
"""批量创建导出任务:串行调 exportOrder(随机限流),不逐段等待生成。
返回 [{'start','end','trigger_ms'}];任一段创建失败返回 None。
"""
tasks = []
total = len(segments)
for i, (a, b) in enumerate(segments, 1):
config.log(f" 创建任务 {i}/{total}:{_fmt_range(a, b)}")
trigger_ms = create_export_task(session, a, b)
if trigger_ms is None:
return None
tasks.append({"start": a, "end": b, "trigger_ms": trigger_ms})
_emit(progress, 20 + 15 * i / max(1, total))
if i < total:
_sleep_interval()
return tasks
def wait_all_done(session, tasks, progress=None):
"""统一轮询 download/list,一次请求取回全部任务状态(异步并行等待)。
任务归属:第 i 段任务 = createTime ∈ [trigger_i, trigger_{i+1}),末段上界为 None;
下界留 1 秒容差,兼容 createTime 秒级截断。
返回与 tasks 顺序一致的完成记录列表;超时返回 None(打印最近记录便于诊断)。
"""
windows = []
for i, t in enumerate(tasks):
lo = t["trigger_ms"] - 1000
hi = tasks[i + 1]["trigger_ms"] - 1000 if i + 1 < len(tasks) else None
windows.append((lo, hi))
page_size = max(20, len(tasks) + 10)
done = {}
used = set()
pending = list(range(len(tasks)))
for round_no in range(1, config.POLL_MAX + 1):
time.sleep(config.POLL_INTERVAL if round_no > 1 else 3)
items = _fetch_download_items(session, page_size)
if items is None:
continue
for idx in list(pending):
lo, hi = windows[idx]
cand = [it for it in items
if it.get("id") not in used and _task_in_window(it, lo, hi)]
if not cand:
continue
cand.sort(key=lambda it: it.get("createTime") or "")
done[idx] = cand[0]
used.add(cand[0].get("id"))
pending.remove(idx)
config.log(f" 任务 {idx + 1}/{len(tasks)} 已生成:{cand[0].get('fileName')}")
_emit(progress, 35 + 25 * len(done) / max(1, len(tasks)))
if not pending:
return [done[i] for i in range(len(tasks))]
config.log(f" 轮询 {round_no}/{config.POLL_MAX}:已完成 {len(done)}/{len(tasks)}")
config.log(" 等待超时,最近导出记录:", "ERROR")
for it in (_fetch_download_items(session, page_size) or [])[:10]:
config.log(f" id={it.get('id')} status={it.get('status')} "
f"fileName={it.get('fileName')} createTime={it.get('createTime')}")
return None
def _fix_zip_name(name):
"""修复 zip 内 GBK 编码的中文文件名乱码。"""
try:
return name.encode('cp437').decode('gbk')
except Exception:
return name
def download_and_extract(item, out_dir):
"""(并发线程内执行)用独立会话流式下载 mediaUrl(zip) → 解压出 Excel。
返回 {'path', 'bytes', 'cost'};日志由调用方在主线程输出(避免多线程写日志)。
"""
media_url = item.get("mediaUrl") or ""
if not media_url:
raise RuntimeError("导出记录缺少 mediaUrl")
session = build_session() # 独立会话:requests.Session 非线程安全,并发下载需独立连接
if session is None:
raise RuntimeError("未找到微盟登录态")
zip_path = os.path.join(out_dir, f"导出任务_{item.get('id')}.zip")
t0 = time.time()
with session.get(media_url, timeout=config.DOWNLOAD_TIMEOUT, stream=True) as resp:
if resp.status_code != 200:
raise RuntimeError(f"下载失败(status={resp.status_code})")
total = 0
with open(zip_path, "wb") as f:
for chunk in resp.iter_content(1024 * 1024):
if chunk:
f.write(chunk)
total += len(chunk)
cost = max(time.time() - t0, 0.001)
excel_in_zip = None
with zipfile.ZipFile(zip_path) as zf:
for info in zf.infolist():
if info.is_dir():
continue
name = _fix_zip_name(info.filename)
if name.lower().endswith((".xlsx", ".xls")):
excel_in_zip = (info.filename, name)
break
if excel_in_zip is None:
raise RuntimeError("压缩包内未找到 Excel 文件")
src_in_zip, src_name = excel_in_zip
tmp = os.path.join(out_dir, src_name)
with zf.open(src_in_zip) as f_in, open(tmp, "wb") as f_out:
shutil.copyfileobj(f_in, f_out)
os.remove(zip_path)
return {"path": tmp, "bytes": total, "cost": cost}
_MERGE_REF_RE = re.compile(rb'<mergeCell[^>]*ref="([^"]+)"')
def _read_merge_refs(zip_path, sheet_path):
"""直接从 xlsx 内 sheet XML 提取合并区域(read_only 模式 openpyxl 不解析合并信息)。
微盟导出文件把同一订单的多行明细做纵向合并;合并时把合并区左上角的值
拆分填充到区域内每一行/列,失败则订单级字段会残缺。
"""
refs, seen = [], set()
with zipfile.ZipFile(zip_path) as zf:
with zf.open(sheet_path) as f:
tail = b''
while True:
chunk = f.read(4 * 1024 * 1024)
if not chunk:
break
buf = tail + chunk
for m in _MERGE_REF_RE.finditer(buf):
ref = m.group(1).decode('ascii')
if ref not in seen:
seen.add(ref)
refs.append(ref)
tail = buf[-16:]
return refs
def _merge_ranges(refs):
"""把合并区域 ref 按顶行分组(排除表头合并与单单元格),供逐行拆分填充。"""
tops = {}
for ref in refs:
min_col, min_row, max_col, max_row = range_boundaries(ref)
if max_row <= config.HEADER_ROWS: # 表头合并(标题跨列)不拆分
continue
if min_row == max_row and min_col == max_col:
continue
tops.setdefault(min_row, []).append((min_col, min_row, max_col, max_row))
return tops
def merge_excels(paths, out_dir):
"""把各段 xlsx 的全部 sheet 数据合并到同一个工作表。
取第一个 sheet 的 HEADER_ROWS 行表头,其余所有 sheet 仅追加数据行;
输出单 sheet 的最终文件(write_only 流式写入,8w+ 行也不占大内存)。
微盟按订单纵向合并的明细单元格在此拆分:把合并区左上角的值填充到区域内
每一行/列,使每行数据自包含(输出不保留合并单元格,便于筛选与统计)。
返回 (final_path, total_rows)。
"""
if not paths:
return None, 0
final_name = f"{config.FILE_PREFIX}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
final_path = os.path.join(out_dir, final_name)
out_wb = Workbook(write_only=True)
out_ws = out_wb.create_sheet("订单数据")
header_written = False
total_rows = 0
split_count = 0
for p in paths:
src = load_workbook(p, read_only=True)
sheet_merges = {ws._worksheet_path: _read_merge_refs(p, ws._worksheet_path)
for ws in src.worksheets}
for ws in src.worksheets:
# 微盟导出的 xlsx 缺 <dimension>,read_only 模式会误判为 A1:A1,必须重置尺寸
ws.reset_dimensions()
rows = ws.iter_rows(values_only=True)
tops = _merge_ranges(sheet_merges.get(ws._worksheet_path, []))
pending = {} # 源行号 → {列号: 值}:上方合并单元格拆分下来的填充值
src_row = 0
if not header_written:
for _ in range(config.HEADER_ROWS):
row = next(rows, None)
src_row += 1
if row is not None:
out_ws.append(list(row))
header_written = True
else:
for _ in range(config.HEADER_ROWS): # 跳过其余 sheet 表头
next(rows, None)
src_row += 1
for row in rows:
src_row += 1
row = list(row)
# 先填充上方合并单元格拆分下来的值,再处理本行作为合并区顶行的情况
for col, val in pending.pop(src_row, {}).items():
if col > len(row):
row.extend([None] * (col - len(row)))
row[col - 1] = val
for min_col, min_row, max_col, max_row in tops.get(src_row, []):
val = row[min_col - 1] if min_col <= len(row) else None
if val is None:
continue
split_count += 1
for rr in range(min_row, max_row + 1):
for cc in range(min_col, max_col + 1):
if rr == min_row and cc == min_col:
continue
pending.setdefault(rr, {})[cc] = val
if all(v is None for v in row): # 跳过空行
continue
out_ws.append(row)
total_rows += 1
src.close()
out_wb.save(final_path)
config.log(f"合并完成:单 sheet 共 {total_rows} 行数据(含表头 {total_rows + config.HEADER_ROWS} 行),"
f"拆分填充合并单元格 {split_count} 处")
config.log("各段源文件已保留:")
for p in paths:
config.log(f" {p}")
return final_path, total_rows
# ================== 主流程 ==================
def run_export(out_dir, progress=None):
"""微盟订单导出主流程(登录态须已就绪)。
探测条数 → 按条数等分并逐段校验 → 批量建导出任务 → 统一轮询 → 下载解压 → 合并一个 Excel。
返回 dict {success, excel_path, message, segments, rows}。
"""
start_ms, end_ms = _time_range()
config.log(f"导出时间范围:上月1日 0:00 ~ 此刻({datetime.now():%Y-%m-%d %H:%M:%S})")
session = build_session()
if session is None:
return {"success": False, "excel_path": "", "segments": 0, "rows": 0,
"message": "未找到微盟登录态(weimob_cookies.json),请先完成登录"}
os.makedirs(out_dir, exist_ok=True)
# 阶段 1:探测与分片
_emit(progress, 12)
segments, total = plan_segments(session, start_ms, end_ms)
if total < 0:
return {"success": False, "excel_path": "", "segments": 0, "rows": 0,
"message": "区间订单数探测失败(登录态可能失效,请重试)"}
if total == 0:
return {"success": False, "excel_path": "", "segments": 0, "rows": 0,
"message": "区间内无订单(未生成文件)"}
config.log(f"最终导出段数:{len(segments)}")
_emit(progress, 20)
# 阶段 2:批量创建导出任务(异步,不逐段等待)
config.log("批量创建导出任务:")
tasks = create_export_tasks(session, segments, progress)
if tasks is None:
return {"success": False, "excel_path": "", "segments": len(segments), "rows": 0,
"message": "创建导出任务失败(请检查登录态或风控状态后重试)"}
# 阶段 3:统一轮询全部任务(一次请求拿全部状态,等最慢的一段)
config.log("等待全部导出任务生成:")
items = wait_all_done(session, tasks, progress)
if items is None:
return {"success": False, "excel_path": "", "segments": len(segments), "rows": 0,
"message": "等待导出任务完成超时(已创建任务可能仍在生成,稍后可重试)"}
_emit(progress, 60)
# 阶段 4:并发下载各段 zip(独立连接,避免单连接 CDN 限速串行等待)→ 解压 Excel
excel_paths = [None] * len(segments)
workers = min(config.DOWNLOAD_WORKERS, len(items))
config.log(f"并发下载 {len(items)} 段({workers} 线程):")
done = 0
with ThreadPoolExecutor(max_workers=workers) as pool:
futures = {pool.submit(download_and_extract, it, out_dir): i
for i, it in enumerate(items)}
for fut in as_completed(futures):
i = futures[fut]
try:
info = fut.result()
excel_paths[i] = info["path"]
done += 1
config.log(f" [段 {i + 1}/{len(segments)}] 完成:{info['path']}"
f"({info['bytes'] / 1024 / 1024:.1f} MB,耗时 {info['cost']:.1f}s,"
f"{info['bytes'] / info['cost'] / 1024:.0f} KB/s)")
_emit(progress, 60 + 28 * done / max(1, len(segments)))
except Exception as e:
return {"success": False, "excel_path": "", "segments": len(segments), "rows": 0,
"message": f"第 {i + 1} 段下载/解压失败:{e}"}
if any(p is None for p in excel_paths):
return {"success": False, "excel_path": "", "segments": len(segments), "rows": 0,
"message": "部分段下载结果缺失"}
# 阶段 5:合并为一个工作表
_emit(progress, 90)
final_path, rows = merge_excels(excel_paths, out_dir)
if not final_path:
return {"success": False, "excel_path": "", "segments": len(segments), "rows": 0,
"message": "合并结果为空"}
_emit(progress, 98)
return {"success": True, "excel_path": final_path, "segments": len(segments), "rows": rows,
"message": f"微盟订单导出成功({len(segments)} 段合并,{rows} 行)→ {final_path}"}