# -*- coding: utf-8 -*- """ERP报表导出 - webhost 场景插件(XQ0031 + XQ0032 合并版) 金蝶 K3Cloud 报表自动导出,两种报表可单选或同次会话连导(登录一次): 物料收发汇总表(XQ0031):组织/仓库编码(或关系多行)/日期多档(N天或自定义区间)逐档导出 采购订单列表(XQ0032):快捷方案 → 等查询 → 按列表引出数据 个性化设计(自带 Vue 界面,plugin.json 声明 "ui": true): - ERP 新/旧系统、登录账号密码由用户在插件窗口内自行填写, 经 /api/plugin-config 保存在执行机本机,下次打开自动回填; - 仓库编码、日期选项均为多选(可自建条目,日期可混入自定义区间); - 浏览器每次现场真登录(auto_port 独立实例),确保用的就是本次配置的账号。 """ import time from datetime import datetime from pathlib import Path from webhost.backend.plugins.base import PLUGINS, ScenePlugin from . import config from . import erp_login # 执行模式 MODE_31 = '物料收发汇总表' MODE_32 = '采购订单列表' MODE_BOTH = '两个都导' def _as_str_list(value): """fields 里的多选值归一为去空去重的字符串列表(兼容逗号/空格分隔的字符串)。""" if value is None: return [] if isinstance(value, str): parts = value.replace(',', ',').replace(' ', ',').split(',') elif isinstance(value, (list, tuple)): parts = list(value) else: parts = [value] out, seen = [], set() for p in parts: s = str(p).strip() if s and s not in seen: seen.add(s) out.append(s) return out class ErpReportExportPlugin(ScenePlugin): id = "xq0031_xq0032" name = "ERP物料收发汇总-采购订单报表导出" version = "1.0.2" description = "金蝶K3Cloud报表导出:物料收发汇总表(需求31)+ 采购订单列表(需求32),支持新旧系统与个性化配置" platform = "" # ERP 自带登录页(无验证码),插件内现场真登录,不使用底座共享登录态 uses_month = False # 富字段声明(与 plugin.json 保持一致):ui=true 时壳子隐藏通用表单、展示打开插件窗口入口; # 此处仅作为无 manifest 时的兜底与参数契约文档 fields = [ {"key": "mode", "label": "执行模式", "type": "select", "options": [MODE_BOTH, MODE_31, MODE_32], "default": MODE_BOTH}, {"key": "erp_system", "label": "ERP系统", "type": "select", "options": ["新版", "旧版"], "default": "新版"}, {"key": "erp_username", "label": "ERP登录账号", "type": "text", "default": ""}, {"key": "erp_password", "label": "ERP登录密码", "type": "password", "default": ""}, {"key": "org_name", "label": "查询组织", "type": "text", "default": config.ORG_NAME}, {"key": "stock_codes", "label": "仓库编码(多选,或关系)", "type": "multiselect", "options": config.STOCK_CODES_DEFAULT, "default": list(config.STOCK_CODES_DEFAULT)}, {"key": "date_options", "label": "日期选项(多选,逐个导出)", "type": "multiselect", "options": config.DATE_OPTIONS_DEFAULT, "default": list(config.DATE_OPTIONS_DEFAULT)}, {"key": "scheme_name", "label": "采购订单快捷方案", "type": "text", "default": config.SCHEME_NAME}, {"key": "save_dir", "label": "保存目录(空=桌面/采购计划报表_日期)", "type": "text", "default": ""}, ] def run(self, fields: dict, ctx) -> dict: fields = fields or {} # 注入日志钩子(插件内全部模块经 config.log 输出) config.set_log(ctx.log) # ---------- 解析与校验 ---------- mode = str(fields.get("mode") or MODE_BOTH).strip() erp = 'old' if str(fields.get("erp_system") or "新版").strip() == "旧版" else 'new' username = str(fields.get("erp_username") or "").strip() password = str(fields.get("erp_password") or "") org = str(fields.get("org_name") or "").strip() or config.ORG_NAME scheme = str(fields.get("scheme_name") or "").strip() or config.SCHEME_NAME codes = _as_str_list(fields.get("stock_codes")) or list(config.STOCK_CODES_DEFAULT) dates = _as_str_list(fields.get("date_options")) or list(config.DATE_OPTIONS_DEFAULT) if not username or not password: raise RuntimeError("ERP 登录账号/密码缺失:请在插件界面填写并保存配置后重试") if mode not in (MODE_BOTH, MODE_31, MODE_32): raise RuntimeError(f"未知执行模式:{mode}") if mode in (MODE_BOTH, MODE_31) and not (codes and dates): raise RuntimeError("物料收发汇总表需要仓库编码与日期选项(请在插件界面配置)") save_dir_raw = str(fields.get("save_dir") or "").strip().strip('"') save_dir = Path(save_dir_raw) if save_dir_raw else Path( _desktop()) / f"{config.FOLDER_NAME}_{datetime.now():%Y-%m-%d}" save_dir.mkdir(parents=True, exist_ok=True) ctx.log(f"保存目录: {save_dir}") # ---------- 登录(一次,两种报表共用会话) ---------- ctx.progress(3) ctx.log(f"ERP 系统:{'新版' if erp == 'new' else '旧版'}({erp_login.ERP_URLS[erp]})") ok, page = erp_login.erp_login(erp, username, password) if not ok: raise RuntimeError("ERP 登录失败(账号密码错误或网络异常),详见日志") ctx.progress(8) # ---------- 执行计划与整体进度(进度 = 8 + 88*已完成单元/总单元) ---------- do_31 = mode in (MODE_BOTH, MODE_31) do_32 = mode in (MODE_BOTH, MODE_32) units_31 = len(dates) if do_31 else 0 total = units_31 + (1 if do_32 else 0) def _report(done_abs): ctx.progress(8 + int(88 * done_abs / max(1, total))) saved, failed = [], [] try: try: page.set.window.max() except Exception: pass time.sleep(1) from . import material_summary, purchase_order if do_31: try: ctx.log(f"开始导出物料收发汇总表:仓库 {len(codes)} 个 / 日期 {len(dates)} 档") files31, failed31 = material_summary.run( page, save_dir, org, codes, dates, progress=lambda done_i, _total: _report(done_i)) saved += files31 failed += [f"物料收发汇总表[{x}]" for x in failed31] except RuntimeError as e: failed.append(f"物料收发汇总表[{e}]") if do_32: _back_home(page, erp) # 报表间回到主界面,保证全局搜索可用 if do_32: try: ctx.log(f"开始导出采购订单列表(方案:{scheme})") f32 = purchase_order.run(page, save_dir, scheme, progress=lambda _i, _t: _report(units_31 + 1)) if f32: saved.append(f32) else: failed.append("采购订单列表") except RuntimeError as e: failed.append(f"采购订单列表[{e}]") finally: try: page.quit() except Exception: pass ctx.progress(100) # ---------- 汇总 ---------- notes = [f"已保存 {len(saved)} 个文件:"] + [f" {p}" for p in saved] if failed: notes.append(f"失败 {len(failed)} 项:{'、'.join(failed)}") summary = f"导出完成(部分失败):成功 {len(saved)} 个,失败 {len(failed)} 项" else: summary = f"导出完成:共 {len(saved)} 个文件 → {save_dir}" return {"summary": summary, "rows": [], "notes": notes} # ================== 小工具 ================== def _desktop(): from .k3_common import get_desktop return get_desktop() def _back_home(page, erp): """两种报表连导时回到 K3 主界面(全局搜索入口所在页),保证下个报表可打开。""" try: home = erp_login.ERP_URLS.get(erp, erp_login.ERP_URLS['new']) if erp_login.SUCCESS_KEYWORD not in (page.url or ''): page.get(home) time.sleep(2) except Exception as e: config.log(f"回主界面异常(继续尝试): {e}") PLUGINS.append(ErpReportExportPlugin())