feat: 新增微盟数据导出和门店出勤积分更新插件
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""微盟数据导出 - webhost 场景插件(XQ0047)
|
||||
|
||||
流程:
|
||||
1) 复用有效登录态(API 校验 weimob_cookies.json),失效则打开可见浏览器登录;
|
||||
微盟登录可能弹腾讯验证码,脚本无法绕过,会提示「请在浏览器窗口完成验证」并等待;
|
||||
2) 探测「上月1日 00:00 ~ 此刻」订单总数,按单段 45000 单等分并逐段校验细分;
|
||||
3) 批量创建 exportOrder 导出任务 → 统一轮询 download/list → 并发下载 zip 解压;
|
||||
4) 各段 Excel 合并为单个 xlsx(桌面/微盟订单导出/微盟订单_YYYYMMDD_HHMMSS.xlsx)。
|
||||
"""
|
||||
import os
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from .data import weimob_export, weimob_login
|
||||
|
||||
|
||||
class WeimobExportPlugin(ScenePlugin):
|
||||
id = "xq0047"
|
||||
name = "微盟数据导出"
|
||||
version = "1.0.1"
|
||||
description = ("微盟商家后台订单数据自动导出:登录微盟(腾讯验证码需人工完成,登录态缓存复用),"
|
||||
"按订单量自动等分时间区间批量创建导出任务,统一轮询下载并合并为一个 Excel")
|
||||
platform = "" # 微盟自带登录页(腾讯验证码),插件内现场真登录,不使用底座共享登录态
|
||||
uses_month = False
|
||||
capabilities = ["xq0047"]
|
||||
permissions = {"platforms": []}
|
||||
# 与 plugin.json.fields 一致(ui=true 前端自渲染,此处分层作为参数契约文档)
|
||||
fields = {
|
||||
"wm_username": {"type": "string", "title": "微盟登录手机号", "default": ""},
|
||||
"wm_password": {"type": "string", "title": "微盟登录密码", "default": "",
|
||||
"format": "password"},
|
||||
"save_dir": {"type": "string", "title": "保存目录", "default": ""},
|
||||
}
|
||||
|
||||
def run(self, fields, ctx) -> dict:
|
||||
fields = fields or {}
|
||||
config.set_log(ctx.log)
|
||||
|
||||
# ---------- 解析与校验 ----------
|
||||
username = str(fields.get("wm_username") or "").strip()
|
||||
password = str(fields.get("wm_password") or "").strip()
|
||||
save_dir = str(fields.get("save_dir") or "").strip().strip('"') or config.default_output_dir()
|
||||
|
||||
if not username or not password:
|
||||
raise RuntimeError("微盟登录账号/密码缺失:请在插件界面填写并保存配置后重试")
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ctx.log(f"保存目录:{save_dir}")
|
||||
|
||||
# ---------- 登录(缓存复用,失效时浏览器现场登录) ----------
|
||||
ctx.progress(2)
|
||||
login = weimob_login.ensure_login(username, password)
|
||||
if not login.get("success"):
|
||||
raise RuntimeError(f"微盟登录失败:{login.get('message')}")
|
||||
ctx.log(login.get("message") or "登录态就绪")
|
||||
ctx.progress(10)
|
||||
|
||||
# ---------- 导出 ----------
|
||||
result = weimob_export.run_export(save_dir, ctx.progress)
|
||||
if not result.get("success"):
|
||||
raise RuntimeError(result.get("message") or "微盟订单导出失败")
|
||||
|
||||
ctx.progress(100)
|
||||
return {
|
||||
"summary": result["message"],
|
||||
"detail": {
|
||||
"excel_path": result.get("excel_path"),
|
||||
"segments": result.get("segments", 0),
|
||||
"rows": result.get("rows", 0),
|
||||
"save_dir": save_dir,
|
||||
},
|
||||
"path": result.get("excel_path"),
|
||||
}
|
||||
|
||||
|
||||
PLUGINS.append(WeimobExportPlugin())
|
||||
@@ -0,0 +1,44 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""发布打包辅助(开发工具,`_` 前缀运行时不会被插件扫描加载)。
|
||||
|
||||
把本插件压成 dist-plugin/xq0047_v<版本>.zip,
|
||||
包根布局:plugin.json / 各 .py / ui / requirements.txt 直接位于 zip 根。
|
||||
排除项:ui-src、__pycache__、debug、.sessions、本脚本、*.pyc。
|
||||
|
||||
用法(仓库根下执行):
|
||||
.venv\\Scripts\\python.exe "plugins\\XQ0001-0100\\XQ0047 微盟数据导出\\_pack.py"
|
||||
随后发布(desktop/ 下执行,见 docs/插件/发版规范.md):
|
||||
.venv\\Scripts\\python.exe -m controlplane.tools.agent_cli publish \\
|
||||
dist-plugin/xq0047_v1.0.1.zip --id xq0047 --version 1.0.1
|
||||
"""
|
||||
import json
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
# 仓库根 = plugins/XQ0001-0100/<插件目录>/ 的 parents[2],统一出包位置
|
||||
_OUT_DIR = _HERE.parents[2] / "dist-plugin"
|
||||
_EXCLUDE_DIRS = {"ui-src", "__pycache__", "debug", ".sessions"}
|
||||
_EXCLUDE_FILES = {"_pack.py"}
|
||||
|
||||
|
||||
def main():
|
||||
manifest = json.loads((_HERE / "plugin.json").read_text(encoding="utf-8"))
|
||||
pid, ver = manifest["id"], manifest["version"]
|
||||
ui_index = _HERE / "ui" / "index.html"
|
||||
if not ui_index.exists():
|
||||
raise SystemExit(f"缺少构建产物 {ui_index}:请先在 ui-src 下 npm run build")
|
||||
_OUT_DIR.mkdir(exist_ok=True)
|
||||
out = _OUT_DIR / f"{pid}_v{ver}.zip"
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for p in sorted(_HERE.rglob("*")):
|
||||
rel = p.relative_to(_HERE)
|
||||
if set(rel.parts) & _EXCLUDE_DIRS or p.name in _EXCLUDE_FILES or p.suffix == ".pyc":
|
||||
continue
|
||||
if p.is_file():
|
||||
zf.write(p, str(rel))
|
||||
print(f"已打包: {out}({out.stat().st_size / 1024:.0f} KB)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,134 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0047 微盟数据导出 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
业务模块统一经 config.log() 输出日志(转发到 ctx.log,无 ctx 时回落到 print)。
|
||||
商家标识默认内置金色印象账号值(与原影刀流程一致),其他账号需改本文件常量。
|
||||
"""
|
||||
import os
|
||||
import ctypes
|
||||
from pathlib import Path
|
||||
|
||||
# ==================== 微盟平台 ====================
|
||||
LOGIN_URL = 'https://account.weimob.com/login.html'
|
||||
SUCCESS_KEYWORD = 'master.weimob.com/bos/products/home'
|
||||
|
||||
ORDER_LIST_URL = ("https://master.weimob.com/bos/products/ecOrder/4022571268153/"
|
||||
"4sidacmmkX1q2pyt1eX4sinvqste/order/order/orderlist")
|
||||
QUERY_LIST_URL = "https://master.weimob.com/api3/mall/mgr/order/queryOrderList"
|
||||
EXPORT_URL = "https://master.weimob.com/api3/mall/mgr/order/exportOrder"
|
||||
DOWNLOAD_LIST_URL = "https://master.weimob.com/api3/merchant/backstage/service/download/list"
|
||||
|
||||
# 导出模块要求的页面路由头(缺失会被鉴权拒绝)
|
||||
X_PAGE_ROUTE = ("/bos/products/ecOrder/4022571268153/"
|
||||
"4sidacmmkX1q2pyt1eX4sinvqste/order/order/orderlist")
|
||||
X_AGGS_ROUTE = "products/ecOrder/4sidacmmkX1q2pyt1eX4sinvqste/order/order/orderlist"
|
||||
REFER_EXTEND = "/bos/products/ecOrder/{bosId}/{key}/order/order/orderlist"
|
||||
|
||||
# ==================== 商家配置(金色印象,其他账号改这里) ====================
|
||||
BOS_ID = '4022571268153'
|
||||
MERCHANT_ID = 2000527625153
|
||||
VID = 6017432629153
|
||||
PRODUCT_ID = 145
|
||||
PRODUCT_VERSION_ID = '12010'
|
||||
PRODUCT_INSTANCE_ID = 22515052153
|
||||
TCODE = 'weimob'
|
||||
|
||||
# ==================== 输出与切分配置 ====================
|
||||
FILE_PREFIX = '微盟订单' # 最终文件名前缀
|
||||
SEG_TARGET = 45000 # 单段目标订单数(接口 Excel 上限 5w,留约 10% 明细行余量)
|
||||
MIN_SPLIT_MS = 3600 * 1000 # 最小细分粒度(1 小时):到该粒度仍超限则直接导出尝试
|
||||
INTERVAL_MIN = 3 # 请求间限流下限(秒)
|
||||
INTERVAL_MAX = 5 # 请求间限流上限(秒,随机化模拟人工节奏,降低风控触发)
|
||||
|
||||
# ==================== 运行参数(项目规范:全局重试3次) ====================
|
||||
RETRY_MAX = 3 # 单段 exportOrder 最大重试次数
|
||||
POLL_MAX = 180 # 统一轮询 download/list 最大次数(180×10s ≈ 30 分钟)
|
||||
POLL_INTERVAL = 10 # 轮询间隔(秒)
|
||||
DOWNLOAD_WORKERS = 4 # 并发下载线程数
|
||||
TIMEOUT = 25 # 接口请求超时(秒)
|
||||
DOWNLOAD_TIMEOUT = 180 # 文件下载超时(秒)
|
||||
HEADER_ROWS = 1 # 导出 xlsx 表头行数(合并时跳过,后续追加数据)
|
||||
|
||||
# ==================== 登录参数 ====================
|
||||
LOGIN_WAIT = 180 # 登录等待总时长(秒):含人工处理腾讯验证码的时间
|
||||
HEADLESS = False # 微盟登录需人工兜底验证码,必须可见浏览器
|
||||
|
||||
|
||||
# ==================== 共享路径 ====================
|
||||
def _app_data_dir():
|
||||
return os.path.join(
|
||||
os.environ.get('LOCALAPPDATA') or os.environ.get('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
|
||||
|
||||
SESSIONS_DIR = os.path.join(_app_data_dir(), '.sessions')
|
||||
COOKIE_FILE = os.path.join(SESSIONS_DIR, 'weimob_cookies.json') # 与影刀版共用,可互相复用
|
||||
TOKEN_FILE = os.path.join(SESSIONS_DIR, 'weimob_tokens.json')
|
||||
|
||||
|
||||
def get_desktop():
|
||||
"""获取真实桌面路径,适配 OneDrive 等重定向的不同电脑。"""
|
||||
try:
|
||||
from ctypes import wintypes
|
||||
guid = wintypes.GUID(
|
||||
data1=0xB4BFCC3A, data2=0xDB2C, data3=0x424C,
|
||||
data4=(0xB0, 0x29, 0x7F, 0xE9, 0x9A, 0x87, 0xC6, 0x41))
|
||||
func = ctypes.windll.shell32.SHGetKnownFolderPath
|
||||
func.argtypes = [wintypes.GUID, wintypes.DWORD, wintypes.HANDLE,
|
||||
ctypes.POINTER(ctypes.c_wchar_p)]
|
||||
ptr = ctypes.c_wchar_p()
|
||||
func(ctypes.byref(guid), 0, None, ctypes.byref(ptr))
|
||||
return ptr.value
|
||||
except Exception:
|
||||
return str(Path.home() / 'Desktop')
|
||||
|
||||
|
||||
def default_output_dir():
|
||||
"""默认输出目录:桌面/微盟订单导出。"""
|
||||
return os.path.join(get_desktop(), '微盟订单导出')
|
||||
|
||||
|
||||
def get_browser_profile_dir():
|
||||
"""独立固定浏览器用户目录:登录态跨次保留(免重复验证码),不占用日常 Chrome 配置。"""
|
||||
return os.path.join(_app_data_dir(), 'browser_sessions', 'xq0047')
|
||||
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
"""注入 ctx.log(RunContext.log),各模块经 log()/logger 输出。"""
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:统一转发到 config.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
log(msg % args if args else msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
log(msg % args if args else msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
log(msg % args if args else msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
log(msg % args if args else msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
@@ -0,0 +1 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
@@ -0,0 +1,508 @@
|
||||
# -*- 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 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 .. 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}
|
||||
|
||||
|
||||
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
|
||||
for p in paths:
|
||||
src = load_workbook(p, read_only=True)
|
||||
for ws in src.worksheets:
|
||||
# 微盟导出的 xlsx 缺 <dimension>,read_only 模式会误判为 A1:A1,必须重置尺寸
|
||||
ws.reset_dimensions()
|
||||
rows = ws.iter_rows(values_only=True)
|
||||
if not header_written:
|
||||
for _ in range(config.HEADER_ROWS):
|
||||
row = next(rows, None)
|
||||
if row is not None:
|
||||
out_ws.append(list(row))
|
||||
header_written = True
|
||||
else:
|
||||
for _ in range(config.HEADER_ROWS): # 跳过其余 sheet 表头
|
||||
next(rows, None)
|
||||
for row in rows:
|
||||
if all(v is None for v in row): # 跳过空行
|
||||
continue
|
||||
out_ws.append(list(row))
|
||||
total_rows += 1
|
||||
src.close()
|
||||
out_wb.save(final_path)
|
||||
config.log(f"合并完成:单 sheet 共 {total_rows} 行数据(含表头 {total_rows + config.HEADER_ROWS} 行)")
|
||||
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}"}
|
||||
@@ -0,0 +1,282 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""微盟(Weimob)登录模块(xq0047 插件内自包含)。
|
||||
|
||||
自 workflows/XQ0001-0100/XQ0047 微盟数据导出/wm_login.py 迁移,插件化改造点:
|
||||
- 账号密码由插件界面配置经 fields 注入(不再读共享 .env);
|
||||
- print → config.log(转发 ctx.log);
|
||||
- 浏览器使用独立固定用户目录(%LOCALAPPDATA%\\37duAutomation\\browser_sessions\\xq0047)。
|
||||
|
||||
登录说明:
|
||||
- 微盟登录页默认打开是「验证码登录」,脚本自动切换到「密码登录」tab;
|
||||
- 点击登录后若弹出腾讯验证码(滑块/点选),自动化无法绕过:脚本暂停并提示人工在浏览器窗口
|
||||
手动完成,完成后自动继续并保存登录态;已有有效登录态则直接复用,不重新登录;
|
||||
- 登录态与影刀版共用:%LOCALAPPDATA%\\37duAutomation\\.sessions\\weimob_cookies.json
|
||||
(Cookies)与 weimob_tokens.json(localStorage 票据)。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
import requests
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
# ================== Cookies / 票据持久化 ==================
|
||||
def _ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
def save_session(page):
|
||||
"""登录成功后保存 Cookies 与 localStorage 票据。"""
|
||||
cookies = page.cookies(all_domains=True)
|
||||
_ensure_dir(config.SESSIONS_DIR)
|
||||
if cookies:
|
||||
with open(config.COOKIE_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump(cookies, f, ensure_ascii=False, indent=2)
|
||||
config.log(f"已保存 {len(cookies)} 个 Cookies 到 {config.COOKIE_FILE}")
|
||||
try:
|
||||
raw = page.run_js('''
|
||||
const data = {};
|
||||
for (let i = 0; i < localStorage.length; i++) {
|
||||
const k = localStorage.key(i);
|
||||
const v = localStorage.getItem(k);
|
||||
if (v && v.length < 100000) data[k] = v;
|
||||
}
|
||||
return JSON.stringify(data);
|
||||
''')
|
||||
ls = json.loads(raw) if raw else {}
|
||||
if ls:
|
||||
with open(config.TOKEN_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump({"localStorage": ls, "saved_at": time.strftime("%Y-%m-%d %H:%M:%S")},
|
||||
f, ensure_ascii=False, indent=2)
|
||||
config.log(f"已保存 localStorage 票据 {len(ls)} 项到 {config.TOKEN_FILE}")
|
||||
except Exception as e:
|
||||
config.log(f"保存 localStorage 票据失败(不影响 Cookies):{e}", "WARN")
|
||||
|
||||
|
||||
def load_cookies():
|
||||
if not os.path.exists(config.COOKIE_FILE):
|
||||
return None
|
||||
try:
|
||||
with open(config.COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
except Exception as e:
|
||||
config.log(f"读取 Cookies 文件失败:{e}", "WARN")
|
||||
return None
|
||||
return cookies or None
|
||||
|
||||
|
||||
# ================== 会话构建与校验(无需打开浏览器) ==================
|
||||
def _build_validate_body():
|
||||
"""构造 download/list 校验请求体(仅商家标识可变)。"""
|
||||
bos_id = config.BOS_ID
|
||||
return {
|
||||
"bosId": bos_id,
|
||||
"pageSize": 1,
|
||||
"basicInfo": {
|
||||
"merchantId": config.MERCHANT_ID,
|
||||
"bosId": int(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 build_session():
|
||||
"""用保存的 cookies 构建 requests.Session(仅注入微盟相关域)。
|
||||
|
||||
微盟 api3 接口除 cookie 外,还必须携带如下请求头才能通过鉴权(否则 errcode=1041 fail auth):
|
||||
Authorization: Bearer <saasAuthData cookie 值>
|
||||
Apiclient: saas-pc
|
||||
weimob-bosId: <bosId>
|
||||
"""
|
||||
cookies = load_cookies()
|
||||
if not cookies:
|
||||
return None
|
||||
token = next((c["value"] for c in cookies
|
||||
if c.get("name") == "saasAuthData" and c.get("value")), "")
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Origin": "https://master.weimob.com",
|
||||
"Referer": "https://master.weimob.com/",
|
||||
"Authorization": f"Bearer {token}",
|
||||
"Apiclient": "saas-pc",
|
||||
"weimob-bosId": config.BOS_ID,
|
||||
})
|
||||
for c in cookies:
|
||||
domain = c.get("domain") or ""
|
||||
if any(k in domain for k in ("weimob.com", "weimobwmc.com")):
|
||||
session.cookies.set(c["name"], c["value"], domain=domain, path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
def is_session_valid():
|
||||
"""API 轻量校验微盟登录态:download/list 返回 {"errcode":"0"} 视为有效。"""
|
||||
session = build_session()
|
||||
if session is None:
|
||||
return False
|
||||
try:
|
||||
resp = session.post(config.DOWNLOAD_LIST_URL, json=_build_validate_body(), timeout=15)
|
||||
except Exception as e:
|
||||
config.log(f"API 校验微盟登录态异常:{e}")
|
||||
return False
|
||||
if resp.status_code != 200:
|
||||
config.log(f"API 校验微盟登录态状态码异常:{resp.status_code}")
|
||||
return False
|
||||
try:
|
||||
data = resp.json()
|
||||
if data.get("errcode") == "0":
|
||||
return True
|
||||
config.log(f"API 校验返回非成功码:{str(data)[:200]}(若为账号配置问题请检查 bosId)", "WARN")
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def _wait_login(page):
|
||||
"""登录等待:处理协议弹窗 + 提示人工完成腾讯验证码,直到登录成功或超时。"""
|
||||
deadline = time.time() + config.LOGIN_WAIT
|
||||
captcha_hinted = False
|
||||
while time.time() < deadline:
|
||||
if config.SUCCESS_KEYWORD in page.url:
|
||||
return True
|
||||
# 协议确认弹窗(首次登录出现「同意」按钮),自动点同意
|
||||
try:
|
||||
agree = page.ele('xpath://button[contains(.,"意")]', timeout=1)
|
||||
if agree:
|
||||
config.log("检测到协议确认弹窗,点击「同意」")
|
||||
agree.click()
|
||||
time.sleep(1)
|
||||
continue
|
||||
except Exception:
|
||||
pass
|
||||
# 腾讯验证码提示(跨域 iframe,脚本无法自动操作,交给人工)
|
||||
if not captcha_hinted:
|
||||
try:
|
||||
cap = page.ele('css:iframe[src*="captcha"],iframe[src*="gtimg"]', timeout=1)
|
||||
if cap:
|
||||
config.log("检测到腾讯验证码,请在浏览器窗口手动完成验证……完成前脚本会持续等待")
|
||||
captcha_hinted = True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(2)
|
||||
return False
|
||||
|
||||
|
||||
def _do_login(username, password):
|
||||
"""打开浏览器完成微盟登录(人工兜底验证码),成功保存登录态。"""
|
||||
co = ChromiumOptions()
|
||||
if config.HEADLESS:
|
||||
co.headless()
|
||||
co.set_argument('--start-maximized')
|
||||
co.set_pref('credentials_enable_service', False)
|
||||
co.set_pref('profile.password_manager_enabled', False)
|
||||
# 独立固定用户目录(%LOCALAPPDATA% 下):登录态跨次保留,不占用用户日常 Chrome 配置
|
||||
co.set_user_data_path(config.get_browser_profile_dir())
|
||||
page = ChromiumPage(co)
|
||||
try:
|
||||
page.get(config.LOGIN_URL)
|
||||
time.sleep(2)
|
||||
|
||||
if config.SUCCESS_KEYWORD in page.url:
|
||||
config.log("已是登录状态,直接保存登录态")
|
||||
save_session(page)
|
||||
return True
|
||||
|
||||
# 默认打开是「验证码登录」,切换到「密码登录」tab
|
||||
if not page.ele('css:input[placeholder="请输入密码"]', timeout=5):
|
||||
tab = page.ele('xpath://span[contains(@class,"tabItem") and text()="密码登录"]', timeout=5)
|
||||
if tab:
|
||||
tab.click()
|
||||
time.sleep(1)
|
||||
else:
|
||||
config.log("找不到「密码登录」切换入口", "ERROR")
|
||||
return False
|
||||
|
||||
account = page.ele('css:input[placeholder="请输入手机号码"]', timeout=config.TIMEOUT)
|
||||
if not account:
|
||||
config.log("找不到手机号输入框", "ERROR")
|
||||
return False
|
||||
account.clear()
|
||||
account.input(username)
|
||||
time.sleep(0.5)
|
||||
|
||||
pwd = page.ele('css:input[placeholder="请输入密码"]', timeout=config.TIMEOUT)
|
||||
if not pwd:
|
||||
config.log("找不到密码输入框", "ERROR")
|
||||
return False
|
||||
pwd.clear()
|
||||
pwd.input(password)
|
||||
time.sleep(0.5)
|
||||
|
||||
# 勾选「登录即表示同意」协议复选框(未勾选时点击一次)
|
||||
try:
|
||||
checkbox = page.ele('css:input[type="checkbox"].ant-checkbox-input', timeout=3)
|
||||
if checkbox:
|
||||
if getattr(checkbox, 'checked', False):
|
||||
config.log("协议复选框已勾选")
|
||||
else:
|
||||
checkbox.click()
|
||||
time.sleep(0.5)
|
||||
config.log("已勾选「登录即表示同意」协议复选框")
|
||||
except Exception as e:
|
||||
config.log(f"勾选协议复选框异常(继续尝试登录):{e}", "WARN")
|
||||
|
||||
# 登录按钮文本在子 span 内,需用 contains(.,...) 才能匹配
|
||||
login_btn = page.ele('xpath://button[contains(.,"登")]', timeout=5)
|
||||
if not login_btn:
|
||||
config.log("找不到登录按钮", "ERROR")
|
||||
return False
|
||||
login_btn.click()
|
||||
|
||||
if _wait_login(page):
|
||||
config.log("登录成功")
|
||||
save_session(page)
|
||||
return True
|
||||
config.log(f"登录失败(等待超时 {config.LOGIN_WAIT}s 未进入后台)", "ERROR")
|
||||
return False
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def ensure_login(username, password, force=False):
|
||||
"""确保存在有效的微盟登录态并缓存 Cookies/票据。
|
||||
|
||||
返回 dict:{success, cookie_path, message, relogin}
|
||||
"""
|
||||
username = (username or '').strip()
|
||||
password = (password or '').strip()
|
||||
if not (username and password):
|
||||
return {"success": False, "cookie_path": config.COOKIE_FILE,
|
||||
"message": "微盟登录账号/密码缺失:请在插件界面填写并保存配置后重试", "relogin": False}
|
||||
|
||||
# 优先复用已保存的登录态(通过 API 校验有效性,无需打开浏览器)
|
||||
if not force and is_session_valid():
|
||||
config.log("已通过缓存的 Cookies 复用微盟登录态")
|
||||
return {"success": True, "cookie_path": config.COOKIE_FILE,
|
||||
"message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
config.log("登录态失效或不存在,打开浏览器登录(腾讯验证码需人工完成)…")
|
||||
ok = _do_login(username, password)
|
||||
if ok:
|
||||
return {"success": True, "cookie_path": config.COOKIE_FILE, "message": "登录成功", "relogin": True}
|
||||
return {"success": False, "cookie_path": config.COOKIE_FILE,
|
||||
"message": "登录失败(可能验证码未完成或账号密码有误)", "relogin": True}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0047",
|
||||
"name": "微盟数据导出",
|
||||
"version": "1.0.1",
|
||||
"description": "微盟商家后台(master.weimob.com)订单数据自动导出:登录微盟(腾讯验证码需人工完成,登录态缓存复用),按订单量自动等分时间区间批量创建导出任务,统一轮询下载 zip 并合并为一个 Excel",
|
||||
"category": "报表",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0047"],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"wm_username": {
|
||||
"type": "string",
|
||||
"title": "微盟登录手机号",
|
||||
"default": "",
|
||||
"description": "微盟商家后台登录手机号(保存在本机,下次免填)"
|
||||
},
|
||||
"wm_password": {
|
||||
"type": "string",
|
||||
"title": "微盟登录密码",
|
||||
"default": "",
|
||||
"format": "password",
|
||||
"description": "仅保存在本机(%LOCALAPPDATA%\\37duAutomation\\plugin_configs),下次免填"
|
||||
},
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "保存目录",
|
||||
"default": "",
|
||||
"description": "留空=桌面/微盟订单导出;输出单个 xlsx(微盟订单_YYYYMMDD_HHMMSS.xlsx),各段源文件同目录保留"
|
||||
}
|
||||
},
|
||||
"required": ["wm_username", "wm_password"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
DrissionPage>=4.1
|
||||
requests>=2.28
|
||||
openpyxl>=3.1
|
||||
@@ -0,0 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>微盟数据导出</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+1585
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "xq0047-ui",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"element-plus": "^2.14.5",
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"vite": "^6.0.3"
|
||||
},
|
||||
"allowScripts": {
|
||||
"esbuild@0.25.12": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<!-- 未登录 / 结果横幅 -->
|
||||
<transition name="fade-slide">
|
||||
<el-alert v-if="needLogin" type="warning" :closable="false" show-icon
|
||||
title="未登录:请先在壳子(工作台)登录统一账户,再刷新本界面" />
|
||||
<el-alert v-else-if="banner" :type="banner.type" :closable="true" show-icon @close="banner = null">
|
||||
<template #title>{{ banner.text }}</template>
|
||||
</el-alert>
|
||||
</transition>
|
||||
|
||||
<!-- 执行配置(头部含多配置方案:方案供「定时任务」引用,到点自动取方案最新参数) -->
|
||||
<el-card shadow="never" class="panel">
|
||||
<template #header>
|
||||
<div class="panel-head">
|
||||
<div class="panel-title">
|
||||
<span class="title-ico">
|
||||
<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor"
|
||||
stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
|
||||
<polyline points="7 10 12 15 17 10" />
|
||||
<line x1="12" y1="15" x2="12" y2="3" />
|
||||
</svg>
|
||||
</span>
|
||||
<div class="title-txts">
|
||||
<div class="title-txt">执行配置</div>
|
||||
<div class="title-sub">参数自动保存到本机,方案供定时任务到点引用</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="head-tools">
|
||||
<span v-if="lastSavedAt" class="saved">
|
||||
<i class="dot" />已保存 {{ lastSavedAt }}
|
||||
</span>
|
||||
<el-select v-model="schemeSel" class="scheme-sel" size="small" :disabled="running"
|
||||
@change="onSchemeChange">
|
||||
<el-option v-for="o in schemeOptions" :key="o.value" :label="o.label" :value="o.value" />
|
||||
</el-select>
|
||||
<el-button size="small" :disabled="running" @click="saveSchemeAs">存为方案</el-button>
|
||||
<el-button size="small" text type="danger" :disabled="running || !schemeSel"
|
||||
@click="removeScheme">删除</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<el-form label-position="top">
|
||||
<!-- 登录账号 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">01</span>
|
||||
<span class="sec-name">登录账号</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="grid">
|
||||
<el-form-item label="微盟登录手机号">
|
||||
<el-input v-model="form.wm_username" placeholder="微盟登录手机号" :disabled="running" clearable />
|
||||
</el-form-item>
|
||||
<el-form-item label="登录密码">
|
||||
<el-input v-model="form.wm_password" type="password" show-password placeholder="仅保存在本机,下次免填"
|
||||
:disabled="running" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">
|
||||
首次登录或登录态失效时会打开浏览器,需人工完成腾讯验证码;登录成功后的登录态会被记住,后续直接复用。
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 导出参数 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">02</span>
|
||||
<span class="sec-name">导出参数</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<el-form-item label="保存目录">
|
||||
<el-input v-model="form.save_dir" :disabled="running" clearable
|
||||
placeholder="留空 = 桌面/微盟订单导出" />
|
||||
<div class="tip">导出区间固定为上月 1 日 00:00 至执行时刻;按 4.5 万单自动分段导出并合并为一份 xlsx(含各分段中间文件)</div>
|
||||
</el-form-item>
|
||||
</section>
|
||||
|
||||
<!-- 操作 -->
|
||||
<div class="actions">
|
||||
<el-button type="primary" size="large" class="btn-run" :loading="running" @click="run">
|
||||
{{ running ? '执行中 ' + progress + '%' : '一键执行' }}
|
||||
</el-button>
|
||||
<el-button v-if="running" type="danger" size="large" plain :loading="stopping"
|
||||
@click="forceStop">强制停止</el-button>
|
||||
<span class="spacer" />
|
||||
<el-button size="large" :disabled="running" @click="saveNow(true)">保存配置</el-button>
|
||||
<el-button size="large" text :disabled="running" @click="resetDefaults">恢复默认</el-button>
|
||||
</div>
|
||||
</el-form>
|
||||
</el-card>
|
||||
|
||||
<!-- 运行状态 -->
|
||||
<transition name="fade-slide">
|
||||
<div v-if="running" class="status">
|
||||
<el-progress :percentage="progress" :stroke-width="10" :show-text="false" class="status-bar" />
|
||||
<div class="status-row">
|
||||
<span class="pulse" />
|
||||
<span class="status-txt">正在执行,日志与进度实时显示在工作台下方【运行日志】区</span>
|
||||
<span class="status-pct">{{ progress }}%</span>
|
||||
</div>
|
||||
</div>
|
||||
</transition>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { usePluginUI } from './usePluginUI'
|
||||
|
||||
const DEFAULTS = () => ({
|
||||
wm_username: '',
|
||||
wm_password: '',
|
||||
save_dir: '',
|
||||
})
|
||||
|
||||
const {
|
||||
form, needLogin, banner, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults,
|
||||
schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
run, forceStop,
|
||||
} = usePluginUI({
|
||||
defaults: DEFAULTS,
|
||||
validate() {
|
||||
if (!form.wm_username.trim() || !form.wm_password.trim()) {
|
||||
ElMessage.warning('请先填写微盟登录手机号和密码')
|
||||
return false
|
||||
}
|
||||
return true
|
||||
},
|
||||
buildPayload(f) {
|
||||
return {
|
||||
wm_username: f.wm_username.trim(),
|
||||
wm_password: f.wm_password.trim(),
|
||||
save_dir: f.save_dir,
|
||||
}
|
||||
},
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* ---------- 页面骨架 ---------- */
|
||||
.page {
|
||||
width: 100%;
|
||||
padding: 6px 4px 28px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.fade-slide-enter-active,
|
||||
.fade-slide-leave-active {
|
||||
transition: opacity 0.25s ease, transform 0.25s ease;
|
||||
}
|
||||
.fade-slide-enter-from,
|
||||
.fade-slide-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(-6px);
|
||||
}
|
||||
|
||||
/* ---------- 主容器(无边框平铺:外层由壳子 iframe 的边框统一包裹) ---------- */
|
||||
.panel {
|
||||
background: transparent;
|
||||
border-radius: 0;
|
||||
border: none;
|
||||
box-shadow: none;
|
||||
overflow: hidden;
|
||||
}
|
||||
.panel :deep(.el-card__header) {
|
||||
padding: 6px 2px 16px;
|
||||
border-bottom: 1px solid var(--el-border-color-lighter);
|
||||
background: transparent;
|
||||
}
|
||||
.panel :deep(.el-card__body) {
|
||||
padding: 16px 2px 2px;
|
||||
}
|
||||
|
||||
/* ---------- 卡片头部 ---------- */
|
||||
.panel-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.panel-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
.title-ico {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--el-color-primary);
|
||||
background: linear-gradient(135deg, var(--el-color-primary-light-8), var(--el-color-primary-light-6));
|
||||
box-shadow: inset 0 0 0 1px var(--el-color-primary-light-5);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.title-txts {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
.title-txt {
|
||||
font-weight: 700;
|
||||
font-size: 15px;
|
||||
line-height: 1.2;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
.title-sub {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.3;
|
||||
}
|
||||
.head-tools {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.scheme-sel {
|
||||
width: 200px;
|
||||
}
|
||||
.saved {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
color: #2ea44f;
|
||||
background: rgba(46, 164, 79, 0.1);
|
||||
border: 1px solid rgba(46, 164, 79, 0.25);
|
||||
padding: 2px 10px;
|
||||
border-radius: 999px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.saved .dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: #2ea44f;
|
||||
}
|
||||
|
||||
/* ---------- 表单分区 ---------- */
|
||||
.sec {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.sec:last-of-type {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.sec-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.sec-badge {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 7px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: var(--el-color-primary);
|
||||
background: var(--el-color-primary-light-9);
|
||||
border: 1px solid var(--el-color-primary-light-7);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.sec-name {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--el-text-color-primary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.sec-line {
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: linear-gradient(90deg, var(--el-border-color-lighter), transparent);
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
|
||||
gap: 0 18px;
|
||||
}
|
||||
.grid :deep(.el-form-item) {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.grid :deep(.el-form-item__label) {
|
||||
padding-bottom: 6px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.tip {
|
||||
width: 100%;
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.6;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
/* ---------- 操作区 ---------- */
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
border-top: 1px dashed var(--el-border-color);
|
||||
padding-top: 18px;
|
||||
margin-top: 18px;
|
||||
}
|
||||
.spacer {
|
||||
flex: 1;
|
||||
}
|
||||
.btn-run {
|
||||
min-width: 150px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
letter-spacing: 2px;
|
||||
background: linear-gradient(135deg, var(--el-color-primary), var(--el-color-primary-dark-2));
|
||||
box-shadow: 0 6px 16px var(--el-color-primary-light-6);
|
||||
transition: filter 0.2s, box-shadow 0.2s, transform 0.15s;
|
||||
}
|
||||
.btn-run:hover {
|
||||
filter: brightness(1.06);
|
||||
box-shadow: 0 8px 20px var(--el-color-primary-light-5);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
.btn-run:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
.btn-run.is-loading {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* ---------- 运行状态 ---------- */
|
||||
.status {
|
||||
padding: 14px 16px;
|
||||
border-radius: 12px;
|
||||
background: linear-gradient(135deg, var(--el-color-primary-light-9), var(--el-color-primary-light-8));
|
||||
border: 1px solid var(--el-color-primary-light-6);
|
||||
box-shadow: 0 2px 10px var(--el-color-primary-light-7);
|
||||
}
|
||||
.status-bar :deep(.el-progress-bar__outer) {
|
||||
background: rgba(64, 158, 255, 0.15);
|
||||
}
|
||||
.status-bar :deep(.el-progress-bar__inner) {
|
||||
background: linear-gradient(90deg, var(--el-color-primary), var(--el-color-primary-dark-2));
|
||||
}
|
||||
.status-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.pulse {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--el-color-primary);
|
||||
animation: pulse 1.4s ease-out infinite;
|
||||
}
|
||||
@keyframes pulse {
|
||||
0% {
|
||||
box-shadow: 0 0 0 0 var(--el-color-primary-light-6);
|
||||
}
|
||||
70% {
|
||||
box-shadow: 0 0 0 8px transparent;
|
||||
}
|
||||
100% {
|
||||
box-shadow: 0 0 0 0 transparent;
|
||||
}
|
||||
}
|
||||
.status-txt {
|
||||
flex: 1;
|
||||
font-size: 12.5px;
|
||||
color: var(--el-text-color-regular);
|
||||
line-height: 1.5;
|
||||
}
|
||||
.status-pct {
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
color: var(--el-color-primary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,2 @@
|
||||
// 插件身份声明(API 实现收敛在 usePluginUI.js 公共 kit,各插件 ui-src 只需声明自己的 id)
|
||||
export const PLUGIN_ID = 'xq0047'
|
||||
@@ -0,0 +1,7 @@
|
||||
import { createApp } from 'vue'
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.css'
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
import App from './App.vue'
|
||||
|
||||
createApp(App).use(ElementPlus, { locale: zhCn }).mount('#app')
|
||||
@@ -0,0 +1,340 @@
|
||||
// 插件 UI 公共 kit(vendored 进各插件 ui-src,构建期内联进产物,运行零外部依赖)。
|
||||
// 收敛三块通用逻辑,App.vue 只保留各插件差异部分(表单字段/校验/布局):
|
||||
// 1. 本机当前配置:加载、防抖自动保存、恢复默认(/api/plugin-config/<id>)
|
||||
// 2. 多配置方案:列表/应用/存为方案/删除(/api/plugin-configs,同名覆盖、密码明文保存;
|
||||
// 供壳子「定时任务」按 config_id 引用,到点自动取方案最新参数)
|
||||
// 3. 执行状态机:一键执行、强制停止、WS 实时进度 + 轮询兜底、未登录重试
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { PLUGIN_ID } from './api'
|
||||
|
||||
async function j(url, opts) {
|
||||
const res = await fetch(url, opts)
|
||||
if (res.status === 401) {
|
||||
throw Object.assign(new Error('未登录:请先在壳子登录统一账户再打开本界面'), { code: 401 })
|
||||
}
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`
|
||||
try { msg = (await res.json()).detail || msg } catch (_) { /* 保留默认 */ }
|
||||
throw new Error(msg)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
// ---- 后端 API(同源,统一账户会话 cookie 自动携带)----
|
||||
function loadConfig() {
|
||||
return j(`/api/plugin-config/${PLUGIN_ID}`)
|
||||
}
|
||||
|
||||
function saveConfig(data) {
|
||||
return j(`/api/plugin-config/${PLUGIN_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
function listSchemes() {
|
||||
return j(`/api/plugin-configs?plugin_id=${encodeURIComponent(PLUGIN_ID)}`)
|
||||
}
|
||||
|
||||
function saveScheme(name, fields) {
|
||||
return j('/api/plugin-configs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, name, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
function deleteScheme(cfgId) {
|
||||
return j(`/api/plugin-configs/${encodeURIComponent(PLUGIN_ID)}/${encodeURIComponent(cfgId)}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
}
|
||||
|
||||
function startRun(fields) {
|
||||
return j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
function getRun(runId) {
|
||||
return j(`/api/runs/${runId}`)
|
||||
}
|
||||
|
||||
function stopRun(runId) {
|
||||
return j(`/api/runs/${runId}/stop`, { method: 'POST' })
|
||||
}
|
||||
|
||||
function connectWS(onEvent) {
|
||||
const ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://')
|
||||
+ location.host + '/ws')
|
||||
ws.onmessage = (e) => { try { onEvent(JSON.parse(e.data)) } catch (_) { /* 忽略脏帧 */ } }
|
||||
return ws
|
||||
}
|
||||
|
||||
// ---- 工具 ----
|
||||
const clone = (o) => JSON.parse(JSON.stringify(o))
|
||||
|
||||
// 保存字段合并规则:标量空值(''/null/undefined)不覆盖;数组照原样应用——
|
||||
// 空数组可能是有意配置(如 xq0031 仓库留空 = 全部不筛选),必须还原
|
||||
function mergeSaved(form, saved) {
|
||||
Object.keys(form).forEach((k) => {
|
||||
const v = saved ? saved[k] : undefined
|
||||
if (v === undefined || v === null || v === '') return
|
||||
form[k] = Array.isArray(v) ? [...v] : v
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 插件 UI 公共状态机
|
||||
* @param {Object} opts
|
||||
* @param {Function} opts.defaults 默认表单工厂;恢复默认时传入当前表单作参考
|
||||
* (如 xq0031 按当前 erp_system 带出对应默认组织/仓库)
|
||||
* @param {Function} [opts.validate] 执行前校验,失败自行 ElMessage 提示并返回 false
|
||||
* @param {Function} [opts.buildPayload] 定制提交参数(缺省 = 表单全量深拷贝)
|
||||
*/
|
||||
export function usePluginUI(opts = {}) {
|
||||
const { defaults, validate, buildPayload } = opts
|
||||
|
||||
const form = reactive(defaults ? defaults() : {})
|
||||
const loaded = ref(false)
|
||||
const needLogin = ref(false)
|
||||
const banner = ref(null)
|
||||
const lastSavedAt = ref('')
|
||||
const running = ref(false)
|
||||
const progress = ref(0)
|
||||
const stopping = ref(false)
|
||||
|
||||
let ws = null
|
||||
let runId = ''
|
||||
let pollTimer = null
|
||||
let saveTimer = null
|
||||
|
||||
// ---------- 当前配置:加载 / 防抖自动保存 ----------
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const saved = await loadConfig()
|
||||
mergeSaved(form, saved)
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.warning('读取本机配置失败,已用默认值:' + e.message)
|
||||
}
|
||||
loaded.value = true
|
||||
refreshSchemes() // 方案列表一并加载:重开界面/切插件回来(iframe 重挂载)后,下拉仍列出全部已存方案
|
||||
})
|
||||
|
||||
// 配置变更自动保存(防抖 800ms),执行中不保存
|
||||
watch(form, () => {
|
||||
if (!loaded.value || running.value) return
|
||||
clearTimeout(saveTimer)
|
||||
saveTimer = setTimeout(() => saveNow(false), 800)
|
||||
}, { deep: true })
|
||||
|
||||
async function saveNow(explicit) {
|
||||
try {
|
||||
await saveConfig(clone(form))
|
||||
lastSavedAt.value = new Date().toLocaleTimeString('zh-CN', { hour12: false })
|
||||
if (explicit) ElMessage.success('配置已保存到本机')
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('配置保存失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
function resetDefaults() {
|
||||
Object.assign(form, defaults ? defaults(form) : {})
|
||||
ElMessage.info('已恢复默认配置')
|
||||
}
|
||||
|
||||
// ---------- 多配置方案(定时任务引用的参数快照,在插件界面维护) ----------
|
||||
const schemes = ref([]) // [{id, name, fields, at}]
|
||||
const schemeSel = ref('') // '' = 当前配置(即表单本身)
|
||||
const schemeOptions = computed(() => [
|
||||
{ value: '', label: '当前配置(自动保存)' },
|
||||
...schemes.value.map((s) => ({ value: s.id, label: s.name })),
|
||||
])
|
||||
|
||||
async function refreshSchemes() {
|
||||
try {
|
||||
const r = await listSchemes()
|
||||
schemes.value = r.configs || []
|
||||
} catch (_) {
|
||||
/* 方案是辅助能力,加载失败静默(下拉仅剩当前配置) */
|
||||
}
|
||||
}
|
||||
|
||||
// 应用方案:载入方案字段(密码随方案明文保存)→ 防抖自动保存固化为当前配置;
|
||||
// 执行永远提交表单当前值,方案本身只作为定时任务的参数快照源
|
||||
function onSchemeChange(id) {
|
||||
if (!id) return // 切回「当前配置」:表单即当前配置,无需动作
|
||||
const s = schemes.value.find((x) => x.id === id)
|
||||
if (!s) return
|
||||
mergeSaved(form, s.fields)
|
||||
ElMessage.success(`已应用方案「${s.name}」`)
|
||||
}
|
||||
|
||||
async function saveSchemeAs() {
|
||||
const cur = schemes.value.find((x) => x.id === schemeSel.value)
|
||||
let name = ''
|
||||
try {
|
||||
({ value: name } = await ElMessageBox.prompt(
|
||||
'方案保存到本机(同名覆盖,密码明文保存,每套方案可绑定不同账号),供「定时任务」引用:到点自动取该方案的最新参数执行。',
|
||||
'存为配置方案',
|
||||
{
|
||||
inputValue: cur ? cur.name : '',
|
||||
confirmButtonText: '保存方案',
|
||||
cancelButtonText: '取消',
|
||||
inputPattern: /\S/,
|
||||
inputErrorMessage: '请输入方案名称',
|
||||
}
|
||||
))
|
||||
} catch (_) {
|
||||
return // 用户取消
|
||||
}
|
||||
name = String(name).trim()
|
||||
if (!name) return
|
||||
const dup = schemes.value.find((x) => x.name === name)
|
||||
if (dup) {
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`已存在同名方案「${dup.name}」,保存将覆盖它的参数(多套不同配置请用不同名称)。`,
|
||||
'覆盖已有方案',
|
||||
{ type: 'warning', confirmButtonText: '覆盖保存', cancelButtonText: '取消' }
|
||||
)
|
||||
} catch (_) {
|
||||
return // 用户取消覆盖
|
||||
}
|
||||
}
|
||||
try {
|
||||
const r = await saveScheme(name, clone(form))
|
||||
await refreshSchemes()
|
||||
schemeSel.value = r.config ? r.config.id : ''
|
||||
ElMessage.success(`方案「${name}」已保存`)
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('方案保存失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
async function removeScheme() {
|
||||
const s = schemes.value.find((x) => x.id === schemeSel.value)
|
||||
if (!s) return
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`删除配置方案「${s.name}」?引用它的定时任务到点会跳过触发并提示重选。`,
|
||||
'删除方案',
|
||||
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
|
||||
)
|
||||
} catch (_) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await deleteScheme(s.id)
|
||||
schemeSel.value = ''
|
||||
await refreshSchemes()
|
||||
ElMessage.success('方案已删除')
|
||||
} catch (e) {
|
||||
ElMessage.error('方案删除失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 执行 ----------
|
||||
async function run() {
|
||||
if (running.value) return
|
||||
// 未登录不再静默返回:先重试一次配置读取(会话可能在打开后已恢复),仍失败则明确提示
|
||||
if (needLogin.value) {
|
||||
try {
|
||||
await loadConfig()
|
||||
needLogin.value = false
|
||||
ElMessage.success('登录态已恢复,请再次点击执行')
|
||||
return
|
||||
} catch (_) { /* 仍未登录 */ }
|
||||
ElMessage.warning('未登录:请先在壳子登录统一账户,再打开本界面')
|
||||
return
|
||||
}
|
||||
if (validate && !validate()) return
|
||||
await saveNow(false)
|
||||
running.value = true
|
||||
progress.value = 0
|
||||
banner.value = null
|
||||
try {
|
||||
const r = await startRun(buildPayload ? buildPayload(form) : clone(form))
|
||||
runId = r.run_id
|
||||
connect() // runId 就绪后再连 WS,避免早到的运行事件被过滤掉
|
||||
startPolling()
|
||||
} catch (e) {
|
||||
running.value = false
|
||||
stopPolling()
|
||||
if (e.code === 401) needLogin.value = true
|
||||
banner.value = { type: 'error', text: '启动执行失败:' + e.message }
|
||||
}
|
||||
}
|
||||
|
||||
// 强制停止(整树强杀执行子进程,含浏览器)
|
||||
async function forceStop() {
|
||||
if (!runId || stopping.value) return
|
||||
stopping.value = true
|
||||
try {
|
||||
await stopRun(runId)
|
||||
ElMessage.warning('已发出强制停止指令,正在终止执行进程…')
|
||||
} catch (e) {
|
||||
ElMessage.error('停止失败:' + e.message)
|
||||
} finally {
|
||||
stopping.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 实时进度 + 完成(WS 只取进度/结束事件,日志由壳子下方日志区展示;断开后轮询兜底)
|
||||
function connect() {
|
||||
if (ws && ws.readyState <= 1) return
|
||||
ws = connectWS((ev) => {
|
||||
if (ev.run_id && ev.run_id !== runId) return // 只看本次运行
|
||||
if (ev.t === 'progress') progress.value = Math.max(progress.value, ev.pct || 0)
|
||||
else if (ev.t === 'run_done') ev.ok ? finished() : failed(ev.error || '执行失败')
|
||||
})
|
||||
ws.onclose = () => { ws = null }
|
||||
}
|
||||
|
||||
function startPolling() {
|
||||
stopPolling()
|
||||
pollTimer = setInterval(async () => {
|
||||
if (!runId) return
|
||||
try {
|
||||
const r = await getRun(runId)
|
||||
if (r.status === 'done') finished(r.result?.summary || '执行完成')
|
||||
else if (r.status === 'error') failed(r.error || '执行失败')
|
||||
} catch (_) { /* 下轮再试 */ }
|
||||
}, 5000)
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
if (pollTimer) { clearInterval(pollTimer); pollTimer = null }
|
||||
}
|
||||
|
||||
function finished(summary) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
progress.value = 100
|
||||
banner.value = { type: 'success', text: summary || '执行完成' }
|
||||
}
|
||||
|
||||
function failed(err) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
banner.value = { type: 'error', text: '执行失败:' + err }
|
||||
}
|
||||
|
||||
return {
|
||||
// 状态
|
||||
form, loaded, needLogin, banner, lastSavedAt, running, progress, stopping,
|
||||
// 当前配置
|
||||
saveNow, resetDefaults,
|
||||
// 多配置方案
|
||||
schemes, schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
// 执行
|
||||
run, forceStop,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// 插件 UI 由壳子后端托管在 /pui/xq0047/ 下,
|
||||
// 构建产物直接输出到插件包 ui/ 目录(随插件 zip 发布,壳子零改动)。
|
||||
// dev 模式经代理访问本机壳子后端,便于联调。
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
base: '/pui/xq0047/',
|
||||
build: {
|
||||
outDir: '../ui',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
server: {
|
||||
port: 5181,
|
||||
proxy: {
|
||||
'/api': 'http://127.0.0.1:8799',
|
||||
'/ws': { target: 'ws://127.0.0.1:8799', ws: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>微盟数据导出</title>
|
||||
<script type="module" crossorigin src="/pui/xq0047/assets/index-CXWi8_0M.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0047/assets/index-BS4ABaKl.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user