feat: 新增内网文件服务器离线监控,升级ERP报表导出插件适配新旧系统差异

1.  新增内网文件服务器心跳上报与离线监控功能:
    - 为文件服务器添加周期心跳上报到中心机的能力
    - 中心机新增文件服务器状态监控线程,超时自动判离线并钉钉告警管理员
    - 新增数据库表存储文件服务器状态,提供管理端API查看在线状态
2.  修复ERP物料收发汇总报表插件:
    - 调整插件版本到1.0.9,更新前端配置与UI适配新旧ERP系统
    - 重构组织与仓库默认值逻辑,区分新版/旧版ERP的默认配置
    - 统一所有场景下显式设置查询组织,移除旧版默认组织的兼容逻辑
    - 新增代管仓仓库编码适配旧版系统
3.  优化文件服务器打包脚本路径,更新文档示例命令
This commit is contained in:
2026-09-19 14:55:22 +08:00
parent 600379933d
commit b034b51685
31 changed files with 39259 additions and 145 deletions
+1 -1
View File
@@ -38,7 +38,7 @@ AI 智能体开发约束 & 项目执行规范
- 变量配置规范:禁止使用命令行传入变量的方式实现参数配置,所有参数、变量、配置项均在代码/配置文件内部定义、固化或读取本地配置,保证运行无外部参数依赖。
5. 发版与自动更新操作规范
- 自动更新:插件由执行机按账号权限自下载(plugin_sync.py);壳子由执行机自动下载安装包 + 用户点击升级重启(shell_updater.py)。版本源都在中心机控制面。
- 发版统一走 agent CLI(在 desktop/ 目录下执行:.venv\Scripts\python.exe -m controlplane.tools.agent_cli,即控制面 /api/admin/pkg 与 shell 源)。鉴权两种方式:① 密码登录(推荐,任意机器可用):`--admin <管理员> --password <密码>`(或环境变量 AGENT_ADMIN_PASSWORD / AGENT_ADMIN_ACCOUNT),远程机器再加 `--base http://<中心机地址>:8800`;② 本机密钥自签(中心机本机):复用 controlplane/.env 与 .admin_secret。
- 发版统一走 agent CLI(在 desktop/ 目录下执行:.venv\Scripts\python.exe -m controlplane.tools.agent_cli,即控制面 /api/admin/pkg 与 shell 源)。鉴权两种方式:① 密码登录(推荐,任意机器可用):`--admin <管理员> --password <密码>`(或环境变量 AGENT_ADMIN_PASSWORD / AGENT_ADMIN_ACCOUNT),远程机器再加 `--base http://<中心机地址>:8800`;② 本机密钥自签(中心机本机):复用 controlplane/.env 与 .admin_secret。实际账号:管理员 `puddy`,密码 `123456`,中心机控制面 `http://117.72.191.188:8800`;本开发机直接示例:`d:\work\code\37duAutomation\.venv\Scripts\python.exe -m controlplane.tools.agent_cli --admin puddy --password 123456 --base http://117.72.191.188:8800 publish <插件.zip> --id <id> --version <v>`。
- 壳子发版(按实际流程):改 desktop/webhost/tools/shell.version 与 install.iss 的 MyAppVersion → desktop/webhost/frontend 执行 npm run build → PyInstaller 打 desktop/webhost/tools/37du-host.spec、37du-host-runner.spec(37du-host-console.spec 是调试版不入安装包,可跳过)→ ISCC.exe desktop/webhost/tools/install.iss 出安装包;然后 agent_cli file push <安装包> --category shell --version <新版本> [--notes "说明"](安装包上传到内网文件服务器 FILESERVER_BASE_URL=172.30.35.135:8802,并登记到中心机 file_sources(shell),执行机 shell_updater 从该直链下载;不要用旧的 shell-release 子命令)。
- 插件发版:根级 plugins/<id>/ 目录打成 zip(根目录含 plugin.json)后 agent_cli publish <插件.zip> --id <id> --version <v>;权限用 agent_cli grant / revoke 管理。
- 中心机发版:控制面为源码部署(宝塔 gunicorn 8800,不打包 exe)。改后端代码后按 .trae/documents/控制面前后端部署SOP.md「后端部署流程」上传文件 + 重启项目;改前端后按同一文档「前端部署流程」构建并发布到静态站 8090。
@@ -0,0 +1,86 @@
# -*- coding: utf-8 -*-
"""内网文件服务器状态 API:心跳上报接收 + 管理端状态查看。
- 文件服务器(fileserver,8802)周期主动上报心跳,本模块落库 fileserver_status;
- 中心机监控线程(core/monitor.py)依据 last_seen 超时判离线,并钉钉告警管理员;
- 心跳上报仅需 X-API-Token(底座凭证),查看需管理员票据。
"""
from __future__ import annotations
from fastapi import APIRouter, Header, HTTPException, Query
from pydantic import BaseModel, Field
from controlplane.core.auth import _check_token, _require_admin
from controlplane.core.db import _db, _now
router = APIRouter()
class FileserverHeartbeatIn(BaseModel):
"""文件服务器心跳载荷(主动上报状态)。host 为唯一标识,默认=对外下载根。"""
host: str = Field(default="", max_length=255)
base_url: str = Field(default="", max_length=255)
hostname: str = Field(default="", max_length=128)
ip: str = Field(default="", max_length=64)
port: int = 0
file_count: int = 0
total_size: int = 0
version: str = Field(default="", max_length=64)
uptime_sec: int = 0
@router.post("/api/fileserver/heartbeat")
def fileserver_heartbeat(b: FileserverHeartbeatIn,
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
"""接收文件服务器心跳:upsert 状态快照,last_seen 刷新;离线中收到心跳则恢复在线。"""
_check_token(x_api_token)
host = b.host.strip()
if not host:
raise HTTPException(400, "host 不能为空")
now = _now()
with _db() as conn:
row = conn.execute(
"SELECT status, offline_notified FROM fileserver_status WHERE host = %s",
(host,)).fetchone()
if row:
# 离线期间恢复上线:标记在线、清除离线告警标记(恢复时不再推送)
was_offline = (not row["status"]) or bool(row["offline_notified"])
conn.execute(
"UPDATE fileserver_status SET base_url=%s, hostname=%s, ip=%s, port=%s, "
"file_count=%s, total_size=%s, version=%s, uptime_sec=%s, last_seen=%s, "
"status=1, offline_notified=0"
+ (", last_status_change=%s" if was_offline else "") +
" WHERE host=%s",
(b.base_url.strip(), b.hostname.strip(), b.ip.strip(), int(b.port or 0),
int(b.file_count or 0), int(b.total_size or 0), b.version.strip(),
int(b.uptime_sec or 0), now) +
((now, host) if was_offline else (host,)))
else:
conn.execute(
"INSERT INTO fileserver_status(host, base_url, hostname, ip, port, file_count, "
"total_size, version, uptime_sec, last_seen, status, offline_notified, "
"created_at, last_status_change) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 1, 0, %s, %s)",
(host, b.base_url.strip(), b.hostname.strip(), b.ip.strip(), int(b.port or 0),
int(b.file_count or 0), int(b.total_size or 0), b.version.strip(),
int(b.uptime_sec or 0), now, now, now))
conn.commit()
return {"ok": True, "host": host, "last_seen": now}
@router.get("/api/admin/fileserver/status")
def fileserver_status_list(limit: int = Query(default=100, ge=1, le=1000),
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
"""管理端查看文件服务器在线状态列表(按最近心跳倒序)。"""
_require_admin(x_admin_token, x_api_token)
with _db() as conn:
rows = [dict(r) for r in conn.execute(
"SELECT id, host, base_url, hostname, ip, port, file_count, total_size, version, "
" uptime_sec, last_seen, status, last_status_change, offline_notified, "
" created_at "
"FROM fileserver_status ORDER BY last_seen DESC LIMIT %s", (limit,))]
for r in rows:
r["status"] = bool(r["status"])
r["offline_notified"] = bool(r["offline_notified"])
return {"fileservers": rows}
+5
View File
@@ -27,11 +27,13 @@ from fastapi.middleware.cors import CORSMiddleware
from controlplane import config
from controlplane.core.db import _init_db, _seed
from controlplane.core.monitor import start_fileserver_monitor
from controlplane.apis import admin as api_admin
from controlplane.apis import auth as api_auth
from controlplane.apis import config_push as api_config_push
from controlplane.apis import dingtalk as api_dingtalk
from controlplane.apis import file_sources as api_file_sources
from controlplane.apis import fileserver_status as api_fileserver_status
from controlplane.apis import meta as api_meta
from controlplane.apis import plugins as api_plugins
from controlplane.apis import schedules as api_schedules
@@ -41,6 +43,8 @@ from controlplane.apis import schedules as api_schedules
async def lifespan(app: FastAPI):
_init_db()
_seed()
# 内网文件服务器离线监控:心跳超时判离线并钉钉告警管理员(daemon 线程)
start_fileserver_monitor()
yield
@@ -53,6 +57,7 @@ app.include_router(api_plugins.router)
app.include_router(api_auth.router)
app.include_router(api_config_push.router)
app.include_router(api_file_sources.router)
app.include_router(api_fileserver_status.router)
app.include_router(api_schedules.router)
app.include_router(api_dingtalk.router)
app.include_router(api_admin.router)
+5
View File
@@ -81,6 +81,11 @@ DINGTALK_AGENT_ID = (os.getenv("DINGTALK_AGENT_ID", "")
# 权限开通提醒的管理员姓名(钉钉扫码自动建号时通知其开通权限),经「搜索用户」接口直查 userid。
DINGTALK_ADMIN_NAME = os.getenv("DINGTALK_ADMIN_NAME", "夏一平")
# 内网文件服务器离线监控:心跳超时判离线(秒)+ 监控扫描间隔(秒)。
# 文件服务器周期上报心跳(默认 60s),超过该阈值未上报则判离线并钉钉告警管理员。
FILESERVER_HEARTBEAT_TIMEOUT = int(os.getenv("FILESERVER_HEARTBEAT_TIMEOUT", "180") or "180")
FILESERVER_MONITOR_INTERVAL = int(os.getenv("FILESERVER_MONITOR_INTERVAL", "30") or "30")
# 客户端敏感凭证默认值参考(webhost 不再明文落盘,中心机 .env 为唯一可信明文源)。
# 明文源只由管理员经 /api/admin/creds/seed 录入;客户端 register 不再自动填充本默认值
# (防任何登录账号借 register 自证拿到全局密钥),本配置保留供管理台 seed 时参考/未来使用。
+27 -3
View File
@@ -19,9 +19,9 @@ from controlplane.core import config
from controlplane.core.crypto import _hash_password
# 初始迁移版本:全量 DDL 建齐后登记;后续增量 DDL 在此追加新版本并配套迁移逻辑
_SCHEMA_VERSION = "20260919_001"
_SCHEMA_VERSION = "20260919_002"
# 全量 DDL(14 张表,MySQL 5.7 兼容;与 tools/schema_mysql.sql 逐条一致)
# 全量 DDL(15 张表,MySQL 5.7 兼容;与 tools/schema_mysql.sql 逐条一致)
_DDL_TABLES = (
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
@@ -234,6 +234,30 @@ _DDL_TABLES = (
PRIMARY KEY (account)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='壳子定时任务配置备份(防丢失)'
""",
"""
CREATE TABLE IF NOT EXISTS fileserver_status (
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增ID',
host VARCHAR(255) NOT NULL COMMENT '文件服务器标识(唯一,默认=对外下载根)',
base_url VARCHAR(255) NOT NULL DEFAULT '' COMMENT '对外下载根',
hostname VARCHAR(128) NOT NULL DEFAULT '' COMMENT '主机名',
ip VARCHAR(64) NOT NULL DEFAULT '' COMMENT 'IP 地址',
port INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '服务端口',
file_count INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '文件数量',
total_size BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '文件总字节',
version VARCHAR(64) NOT NULL DEFAULT '' COMMENT '服务版本',
uptime_sec INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '进程运行秒数',
last_seen DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最后心跳时间(心跳上报更新)',
status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '在线状态:1=在线 0=离线(监控线程维护)',
last_status_change DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最近一次在线/离线切换时间',
offline_notified TINYINT(1) NOT NULL DEFAULT 0 COMMENT '离线已告警:1=已通知 0=未通知(防重复推送)',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '首次上报时间',
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (id),
UNIQUE KEY uk_host (host),
KEY idx_status (status),
KEY idx_last_seen (last_seen)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='内网文件服务器状态(心跳上报+离线监控)'
""",
)
@@ -314,7 +338,7 @@ def _init_db() -> None:
with _db() as conn:
for ddl in _DDL_TABLES:
conn.execute(ddl)
for _ver in ("20260916_001", _SCHEMA_VERSION):
for _ver in ("20260916_001", "20260919_001", _SCHEMA_VERSION):
conn.execute(
"INSERT IGNORE INTO schema_migrations(version) VALUES (%s)",
(_ver,))
+68
View File
@@ -0,0 +1,68 @@
# -*- coding: utf-8 -*-
"""中心机后台监控:内网文件服务器心跳超时判离线 → 钉钉告警管理员。
- 文件服务器周期主动上报心跳(/api/fileserver/heartbeat,默认 60s 一次,落库 last_seen);
- 本模块后台线程按 FILESERVER_MONITOR_INTERVAL 扫描「在线且未告警」的记录,
对 last_seen 超过 FILESERVER_HEARTBEAT_TIMEOUT 的判定离线并推送钉钉;
- 离线转换用「带条件的原子 UPDATE」认领(status=1 且 offline_notified=0 且 last_seen 超时),
gunicorn 多 worker 并发下仅一个 worker 认领成功,避免重复告警;
- 恢复上线由心跳接口处理:收到心跳即翻转在线并清除告警标记,无需本线程干预。
"""
from __future__ import annotations
import logging
import threading
import time
from datetime import datetime, timedelta
from controlplane.core import config
from controlplane.core.db import _db, _now
from controlplane.core.notify import notify_fileserver_down
log = logging.getLogger(__name__)
def _scan_once() -> None:
"""扫描一次:将心跳超时的在线文件服务器翻转为离线并告警(幂等 / 并发安全)。"""
if not config.MYSQL_HOST:
return
cutoff = (datetime.now() - timedelta(seconds=config.FILESERVER_HEARTBEAT_TIMEOUT)) \
.strftime("%Y-%m-%d %H:%M:%S")
with _db() as conn:
rows = conn.execute(
"SELECT host, hostname, ip, last_seen FROM fileserver_status "
"WHERE status = 1 AND offline_notified = 0").fetchall()
for r in rows:
host = r["host"]
try:
with _db() as conn:
cur = conn.execute(
"UPDATE fileserver_status SET status = 0, offline_notified = 1, "
"last_status_change = %s "
"WHERE host = %s AND status = 1 AND offline_notified = 0 AND last_seen < %s",
(_now(), host, cutoff))
conn.commit()
claimed = cur.rowcount > 0
except Exception: # noqa: BLE001 单条认领失败不影响其余扫描
log.exception("文件服务器离线认领失败(host=%s)", host)
continue
if not claimed:
continue # 已被其它 worker 认领,或刚恢复心跳
log.warning("检测到文件服务器离线:%s(最后心跳 %s)", host, r["last_seen"])
notify_fileserver_down(host, r["hostname"] or "", r["ip"] or "",
str(r["last_seen"] or ""))
def _monitor_loop() -> None:
while True:
try:
_scan_once()
except Exception: # noqa: BLE001 监控异常不退出线程,下轮重试
log.exception("文件服务器监控扫描异常")
time.sleep(max(5, config.FILESERVER_MONITOR_INTERVAL))
def start_fileserver_monitor() -> None:
"""启动文件服务器离线监控线程(daemon,随进程退出)。"""
threading.Thread(target=_monitor_loop, daemon=True,
name="fileserver-monitor").start()
+47
View File
@@ -171,3 +171,50 @@ def _send_robot(title: str, text: str) -> None:
log.warning("钉钉群通知被拒: %s", body)
except Exception as e: # noqa: BLE001 通知失败不阻断业务
log.warning("钉钉群通知异常: %s", e)
# ==================== 内网文件服务器离线告警(中心机监控线程触发) ====================
def _admin_names() -> list[str]:
"""管理员名单(nickname 优先,其次 account),用于离线告警收件人。"""
try:
from controlplane.core.db import _db
with _db() as conn:
rows = conn.execute(
"SELECT account, nickname FROM accounts WHERE is_admin = 1 ORDER BY id").fetchall()
return [(r["nickname"] or r["account"] or "").strip() for r in rows if r]
except Exception: # noqa: BLE001 取管理员失败按空处理,回退群机器人
log.warning("取管理员名单失败,离线告警回退群机器人")
return []
def _work_fileserver_down(host: str, hostname: str, ip: str, last_seen: str) -> None:
"""文件服务器离线告警:优先工作通知推给全部管理员,无人送达回退群机器人 webhook。"""
title = "内网文件服务器下线告警"
content = (
f"> 服务:{hostname or '—'}\n\n"
f"> 地址:{host}\n\n"
f"> IP:{ip or '—'}\n\n"
f"> 最后心跳:{last_seen or '—'}\n\n"
"> 提示:执行机将无法下载大文件(壳子/Chrome 安装包),请尽快排查进程或网络;"
"服务恢复后将自动解除告警")
agent_id = (config.DINGTALK_AGENT_ID or "").strip()
at = _dingtalk_topapi_token() if agent_id else ""
sent_any = False
if at:
for name in _admin_names():
if not name:
continue
uid = _userid_by_name(at, name)
if uid and _send_work_to(at, agent_id, uid, title, content, status="error"):
sent_any = True
if not sent_any:
log.warning("文件服务器离线告警:管理员工作通知均未送达,回退群机器人")
if not sent_any:
_send_robot(title, content)
def notify_fileserver_down(host: str, hostname: str = "", ip: str = "",
last_seen: str = "") -> None:
"""内网文件服务器离线告警:推送钉钉给管理员(后台线程,失败不阻断监控)。"""
threading.Thread(target=_work_fileserver_down,
args=(host, hostname, ip, last_seen), daemon=True).start()
@@ -251,3 +251,29 @@ CREATE TABLE IF NOT EXISTS schedule_backups (
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (account)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='壳子定时任务配置备份(防丢失)';
-- ------------------------------------------------------------
-- 内网文件服务器状态:心跳上报 + 离线监控(超时判离线并钉钉告警)
-- ------------------------------------------------------------
CREATE TABLE IF NOT EXISTS fileserver_status (
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增ID',
host VARCHAR(255) NOT NULL COMMENT '文件服务器标识(唯一,默认=对外下载根)',
base_url VARCHAR(255) NOT NULL DEFAULT '' COMMENT '对外下载根',
hostname VARCHAR(128) NOT NULL DEFAULT '' COMMENT '主机名',
ip VARCHAR(64) NOT NULL DEFAULT '' COMMENT 'IP 地址',
port INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '服务端口',
file_count INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '文件数量',
total_size BIGINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '文件总字节',
version VARCHAR(64) NOT NULL DEFAULT '' COMMENT '服务版本',
uptime_sec INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '进程运行秒数',
last_seen DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最后心跳时间(心跳上报更新)',
status TINYINT(1) NOT NULL DEFAULT 1 COMMENT '在线状态:1=在线 0=离线(监控线程维护)',
last_status_change DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最近一次在线/离线切换时间',
offline_notified TINYINT(1) NOT NULL DEFAULT 0 COMMENT '离线已告警:1=已通知 0=未通知(防重复推送)',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '首次上报时间',
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (id),
UNIQUE KEY uk_host (host),
KEY idx_status (status),
KEY idx_last_seen (last_seen)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='内网文件服务器状态(心跳上报+离线监控)';
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,128 @@
This file lists modules PyInstaller was not able to find. This does not
necessarily mean these modules are required for running your program. Both
Python's standard library and 3rd-party Python packages often conditionally
import optional modules, some of which may be available only on certain
platforms.
Types of import:
* top-level: imported at the top-level - look at these first
* conditional: imported within an if-statement
* delayed: imported within a function
* optional: imported within a try-except-statement
IMPORTANT: Do NOT post this list to the issue-tracker. Use it as a basis for
tracking down the missing module yourself. Thanks!
missing module named _frozen_importlib_external - imported by importlib._bootstrap (delayed), importlib (optional), importlib.abc (optional), zipimport (top-level)
excluded module named _frozen_importlib - imported by importlib (optional), importlib.abc (optional), zipimport (top-level)
missing module named 'org.python' - imported by copy (optional), xml.sax (delayed, conditional)
missing module named posix - imported by os (conditional, optional), posixpath (optional), shutil (conditional), importlib._bootstrap_external (conditional)
missing module named resource - imported by posix (top-level)
missing module named grp - imported by shutil (delayed, optional), tarfile (optional), pathlib (delayed, optional), subprocess (delayed, conditional, optional)
missing module named pwd - imported by posixpath (delayed, conditional, optional), shutil (delayed, optional), tarfile (optional), pathlib (delayed, optional), subprocess (delayed, conditional, optional), webbrowser (delayed), getpass (delayed), netrc (delayed, conditional)
missing module named _posixsubprocess - imported by subprocess (conditional), multiprocessing.util (delayed)
missing module named fcntl - imported by subprocess (optional)
missing module named _posixshmem - imported by multiprocessing.resource_tracker (conditional), multiprocessing.shared_memory (conditional)
missing module named _scproxy - imported by urllib.request (conditional)
missing module named termios - imported by click._termui_impl (conditional), tty (top-level), getpass (optional)
missing module named 'java.lang' - imported by platform (delayed, optional), xml.sax._exceptions (conditional)
missing module named multiprocessing.BufferTooShort - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
missing module named multiprocessing.AuthenticationError - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
missing module named multiprocessing.get_context - imported by multiprocessing (top-level), multiprocessing.pool (top-level), multiprocessing.managers (top-level), multiprocessing.sharedctypes (top-level)
missing module named multiprocessing.TimeoutError - imported by multiprocessing (top-level), multiprocessing.pool (top-level)
missing module named org - imported by pickle (optional)
missing module named multiprocessing.set_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
missing module named multiprocessing.get_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
missing module named multiprocessing.Pipe - imported by multiprocessing (top-level), uvicorn.supervisors.multiprocess (top-level)
missing module named pyimod02_importers - imported by D:\work\code\37duAutomation\.venv\Lib\site-packages\PyInstaller\hooks\rthooks\pyi_rth_pkgutil.py (delayed)
missing module named email_validator - imported by pydantic.networks (delayed, conditional, optional), pydantic.v1.networks (delayed, conditional, optional), fastapi.openapi.models (optional), D:\work\code\37duAutomation\desktop\fileserver\launch.py (top-level), pydantic.v1._hypothesis_plugin (optional)
missing module named asyncio.DefaultEventLoopPolicy - imported by asyncio (delayed, conditional), asyncio.events (delayed, conditional)
missing module named annotationlib - imported by typing_extensions (conditional), pydantic._internal._typing_extra (delayed, conditional), pydantic._internal._model_construction (delayed, conditional), pydantic.v1.main (delayed, conditional), fastapi.dependencies.utils (delayed, conditional, optional)
missing module named vms_lib - imported by platform (delayed, optional)
missing module named java - imported by platform (delayed)
missing module named _winreg - imported by platform (delayed, optional)
missing module named trio - imported by httpx._transports.asgi (delayed, conditional), httpcore._synchronization (optional), httpcore._backends.trio (top-level), websockets.trio.client (top-level), websockets.trio.connection (top-level), websockets.trio.messages (top-level), websockets.trio.utils (top-level), websockets.trio.router (top-level), websockets.trio.server (top-level)
missing module named sniffio - imported by anyio._core._eventloop (optional), httpx._transports.asgi (delayed, optional), httpcore._synchronization (delayed, optional)
missing module named socksio - imported by httpcore._sync.socks_proxy (top-level), httpcore._async.socks_proxy (top-level), httpx._transports.default (delayed, conditional, optional)
missing module named 'h2.settings' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
missing module named 'h2.exceptions' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
missing module named 'h2.events' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
missing module named 'h2.connection' - imported by httpcore._sync.http2 (top-level), httpcore._async.http2 (top-level)
missing module named h2 - imported by httpcore._sync.http2 (top-level), httpx._client (delayed, conditional, optional)
missing module named 'h2.config' - imported by httpcore._async.http2 (top-level)
missing module named 'rich.table' - imported by httpx._main (top-level)
missing module named 'rich.syntax' - imported by httpx._main (top-level)
missing module named 'rich.progress' - imported by httpx._main (top-level)
missing module named 'rich.markup' - imported by httpx._main (top-level)
missing module named 'rich.console' - imported by httpx._main (top-level)
missing module named 'pygments.util' - imported by httpx._main (top-level)
missing module named pygments - imported by httpx._main (top-level)
missing module named '_typeshed.wsgi' - imported by httpx._transports.wsgi (conditional)
missing module named _typeshed - imported by anyio.abc._eventloop (conditional), anyio._core._sockets (conditional), anyio._core._fileio (conditional), anyio._core._tempfile (conditional), pydantic_core._pydantic_core (top-level), pydantic._internal._dataclasses (conditional), httpx._transports.wsgi (conditional), anyio._backends._asyncio (conditional), anyio._core._asyncio_selector_thread (conditional), anyio._backends._trio (conditional)
missing module named zstandard - imported by httpx._decoders (optional)
missing module named brotlicffi - imported by httpx._decoders (optional)
missing module named brotli - imported by httpx._decoders (optional)
missing module named wsproto - imported by uvicorn.protocols.websockets.wsproto_impl (top-level), uvicorn.protocols.websockets.auto (optional), D:\work\code\37duAutomation\desktop\fileserver\launch.py (top-level)
missing module named 'trio.abc' - imported by websockets.trio.connection (top-level), websockets.trio.server (top-level)
missing module named 'werkzeug.routing' - imported by websockets.asyncio.router (optional), websockets.sync.router (optional), websockets.trio.router (optional)
missing module named 'werkzeug.exceptions' - imported by websockets.sync.router (optional), websockets.trio.router (optional)
missing module named 'python_socks.async_' - imported by websockets.asyncio.client (optional), websockets.trio.client (optional)
missing module named python_socks - imported by websockets.asyncio.client (optional), websockets.sync.client (optional), websockets.trio.client (optional)
missing module named 'python_socks.sync' - imported by websockets.sync.client (optional)
missing module named readline - imported by websockets.cli (delayed, optional)
missing module named werkzeug - imported by websockets.asyncio.router (optional)
missing module named httptools - imported by uvicorn.protocols.http.httptools_impl (top-level), uvicorn.protocols.http.auto (optional), D:\work\code\37duAutomation\desktop\fileserver\launch.py (top-level)
missing module named a2wsgi - imported by uvicorn.middleware.wsgi (optional)
missing module named zttp - imported by uvicorn.protocols.http.zttp_impl (top-level)
missing module named 'IPython.core' - imported by dotenv.ipython (top-level)
missing module named IPython - imported by dotenv.ipython (top-level)
excluded module named win32con - imported by win32evtlogutil (top-level)
excluded module named win32api - imported by win32evtlogutil (top-level)
missing module named 'wsproto.utilities' - imported by uvicorn.protocols.websockets.wsproto_impl (top-level)
missing module named 'wsproto.extensions' - imported by uvicorn.protocols.websockets.wsproto_impl (top-level)
missing module named 'wsproto.connection' - imported by uvicorn.protocols.websockets.wsproto_impl (top-level)
missing module named uvloop - imported by uvicorn.loops.auto (delayed, optional), uvicorn.loops.uvloop (top-level), anyio._backends._asyncio (delayed, conditional)
missing module named 'trio.testing' - imported by anyio._backends._trio (delayed)
missing module named exceptiongroup - imported by anyio._core._exceptions (conditional), anyio._core._sockets (conditional), starlette._utils (conditional, optional), anyio._backends._asyncio (conditional), anyio._backends._trio (conditional)
missing module named 'trio.to_thread' - imported by anyio._backends._trio (top-level)
missing module named 'trio.socket' - imported by anyio._backends._trio (top-level)
missing module named outcome - imported by anyio._backends._trio (top-level)
missing module named 'trio.lowlevel' - imported by anyio._backends._trio (top-level)
missing module named 'trio.from_thread' - imported by anyio._backends._trio (top-level)
missing module named '_pytest.outcomes' - imported by anyio._backends._asyncio (delayed)
missing module named _pytest - imported by anyio._backends._asyncio (delayed)
missing module named winloop - imported by anyio._backends._asyncio (delayed, conditional)
missing module named 'pathlib.types' - imported by anyio._core._fileio (conditional)
missing module named cython - imported by pydantic.v1.version (optional)
missing module named toml - imported by pydantic.v1.mypy (delayed, conditional, optional)
missing module named tomli - imported by pydantic.mypy (delayed, conditional, optional), pydantic.v1.mypy (delayed, conditional, optional)
missing module named 'mypy.version' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
missing module named 'mypy.util' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
missing module named 'mypy.typevars' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
missing module named 'mypy.types' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
missing module named 'mypy.server' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
missing module named 'mypy.semanal' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
missing module named 'mypy.plugins' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
missing module named 'mypy.plugin' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
missing module named 'mypy.options' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
missing module named 'mypy.nodes' - imported by pydantic.mypy (top-level), pydantic.v1.mypy (top-level)
missing module named 'mypy.errorcodes' - imported by pydantic.v1.mypy (top-level)
missing module named hypothesis - imported by pydantic.v1._hypothesis_plugin (top-level)
missing module named 'mypy.typeops' - imported by pydantic.mypy (top-level)
missing module named 'mypy.type_visitor' - imported by pydantic.mypy (top-level)
missing module named 'mypy.state' - imported by pydantic.mypy (top-level)
missing module named 'mypy.expandtype' - imported by pydantic.mypy (top-level)
missing module named mypy - imported by pydantic.mypy (top-level)
missing module named eval_type_backport - imported by pydantic._internal._typing_extra (delayed, optional)
missing module named 'rich.pretty' - imported by pydantic._internal._core_utils (delayed)
missing module named rich - imported by pydantic._internal._core_utils (conditional)
missing module named pydantic.PydanticSchemaGenerationError - imported by pydantic (delayed), pydantic.functional_validators (delayed), fastapi._compat.v2 (top-level)
missing module named pydantic.PydanticUserError - imported by pydantic (top-level), pydantic.root_model (top-level)
missing module named pydantic.BaseModel - imported by pydantic (conditional), pydantic._internal._typing_extra (conditional), pydantic._internal._core_utils (delayed), pydantic._internal._import_utils (delayed, conditional), pydantic.deprecated.copy_internals (delayed, conditional), fastapi.exceptions (top-level), fastapi.types (top-level), fastapi._compat.shared (top-level), fastapi._compat.v2 (top-level), fastapi.openapi.models (top-level), fastapi.security.http (top-level), fastapi.dependencies.utils (top-level), fastapi.encoders (top-level), fastapi.sse (top-level), fastapi.openapi.utils (top-level)
missing module named 'itsdangerous.exc' - imported by starlette.middleware.sessions (top-level)
missing module named itsdangerous - imported by starlette.middleware.sessions (top-level)
missing module named pydantic_extra_types - imported by fastapi.encoders (optional)
missing module named 'gunicorn.workers' - imported by uvicorn.workers (top-level)
missing module named gunicorn - imported by uvicorn.workers (top-level)
missing module named watchfiles - imported by uvicorn.supervisors.watchfilesreload (top-level)
File diff suppressed because it is too large Load Diff
+10
View File
@@ -27,6 +27,13 @@ TOKEN = os.getenv("FILESERVER_TOKEN", "") # 上传/删除/列表鉴权
DATA_DIR = Path(os.getenv("FILESERVER_DATA_DIR", "") or (APP_DIR / "data")).resolve()
# 对外下载根(生成 url 用,须内网机器可访问);未配时回退 本机 IP 端口 形式
BASE_URL = os.getenv("FILESERVER_BASE_URL", "").rstrip("/") or f"http://127.0.0.1:{PORT}"
# 中心机(控制面)上报:非空时后台线程周期上报心跳状态,中心机据此监控在线/离线。
# CONTROLPLANE_URL 中心机地址,如 http://117.72.191.188:8800
# CONTROLPLANE_TOKEN 与中心机 controlplane/.env 的 CONTROLPLANE_TOKEN 一致
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
# 心跳上报间隔(秒)
HEARTBEAT_INTERVAL = int(os.getenv("FILESERVER_HEARTBEAT_INTERVAL", "60") or "60")
def load_dotenv() -> None:
@@ -51,6 +58,9 @@ PORT = int(os.getenv("FILESERVER_PORT", "8802") or "8802")
TOKEN = os.getenv("FILESERVER_TOKEN", "")
DATA_DIR = Path(os.getenv("FILESERVER_DATA_DIR", "") or (APP_DIR / "data")).resolve()
BASE_URL = os.getenv("FILESERVER_BASE_URL", "").rstrip("/") or f"http://127.0.0.1:{PORT}"
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
HEARTBEAT_INTERVAL = int(os.getenv("FILESERVER_HEARTBEAT_INTERVAL", "60") or "60")
def default_token() -> str:
+88 -1
View File
@@ -14,9 +14,14 @@ from __future__ import annotations
import hashlib
import json
import logging
import re
import secrets
import socket
import threading
import time
import urllib.request
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi import FastAPI, Header, HTTPException, UploadFile
@@ -24,7 +29,7 @@ from fastapi.responses import FileResponse
from fileserver.core import config
app = FastAPI(title="37du 内网文件服务器")
log = logging.getLogger("fileserver.heartbeat")
_DATA_DIR = config.DATA_DIR
_DATA_DIR.mkdir(parents=True, exist_ok=True)
@@ -32,6 +37,9 @@ _DATA_DIR.mkdir(parents=True, exist_ok=True)
_STATUS_DIR = _DATA_DIR / ".meta"
_STATUS_DIR.mkdir(parents=True, exist_ok=True)
# 进程启动时间(心跳上报 uptime 用)
_START_TS = time.time()
def _require_token(x_api_token: str = "") -> None:
"""校验管理 token;未配置 token 时放行(纯开发模式)。"""
@@ -62,6 +70,85 @@ def _file_meta(fid: str) -> dict:
return {}
# ==================== 中心机心跳上报(主动上报状态,供中心机监控在线/离线) ====================
def _server_status() -> dict:
"""收集本服务器状态快照:文件数/占用/主机/IP/运行时长等。"""
meta_files = list(_STATUS_DIR.glob("*.json"))
total = 0
for mf in meta_files:
try:
m = json.loads(mf.read_text(encoding="utf-8"))
total += int(m.get("size") or 0)
except Exception: # noqa: BLE001
pass
hostname = socket.gethostname()
ip = ""
try:
ip = socket.gethostbyname(hostname)
except OSError: # noqa: BLE001
pass
return {
"host": config.BASE_URL, # 中心机以其唯一标识本服务器(默认=对外下载根)
"base_url": config.BASE_URL,
"hostname": hostname,
"ip": ip,
"port": config.PORT,
"file_count": len(meta_files),
"total_size": total,
"version": "37du-fileserver",
"uptime_sec": int(time.time() - _START_TS),
}
def _post_heartbeat() -> bool:
"""单次上报心跳到中心机;成功返回 True。"""
payload = json.dumps(_server_status(), ensure_ascii=False).encode("utf-8")
req = urllib.request.Request(
f"{config.CONTROLPLANE_URL}/api/fileserver/heartbeat",
data=payload, method="POST")
req.add_header("Content-Type", "application/json")
if config.CONTROLPLANE_TOKEN:
req.add_header("X-API-Token", config.CONTROLPLANE_TOKEN)
try:
with urllib.request.urlopen(req, timeout=10) as resp:
return resp.status < 400
except OSError as exc: # noqa: BLE001 网络/中心机异常按失败处理
log.warning("心跳上报失败:%s", exc)
return False
def _heartbeat_loop() -> None:
"""后台线程:周期向中心机上报心跳。未配置 CONTROLPLANE_URL 则直接退出。
每次上报最多重试 3 次(项目级重试约定),三次失败记错误日志;不阻塞文件服务。
"""
if not config.CONTROLPLANE_URL:
log.info("未配置 CONTROLPLANE_URL,跳过心跳上报")
return
while True:
try:
ok = False
for _i in range(3):
if _post_heartbeat():
ok = True
break
if not ok:
log.error("心跳上报连续失败(3 次):%s", config.CONTROLPLANE_URL)
except Exception: # noqa: BLE001 上报异常不拖垮文件服务
log.exception("心跳上报线程异常")
time.sleep(max(5, config.HEARTBEAT_INTERVAL))
@asynccontextmanager
async def _lifespan(_app: FastAPI):
threading.Thread(target=_heartbeat_loop, daemon=True,
name="fileserver-heartbeat").start()
yield
app = FastAPI(title="37du 内网文件服务器", lifespan=_lifespan)
@app.post("/api/upload")
async def api_upload(upload: UploadFile,
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
+18 -18
View File
@@ -1,31 +1,31 @@
@echo off
REM ===== 37du 内网文件服务器 打包脚本(在 Windows 本机执行)=====
REM 前置:desktop/.venv 已安装 fastapi uvicorn python-multipart pyinstaller
REM 用法:在 desktop\ 目录下用项目 .venv 执行本脚本
REM ===== 37du intranet file server build script (run on Windows) =====
REM prereq: desktop/.venv with fastapi uvicorn python-multipart pyinstaller
REM usage: run inside desktop\ directory with project .venv
setlocal
cd /d %~dp0\..\..
set PY=..\.venv\Scripts\python.exe
if not exist %PY% (
echo [err] 未找到 %PY% ,请确认在 desktop\ 目录且 .venv 存在
echo [err] PYTHON NOT FOUND: %PY% - run from desktop\ and ensure .venv exists
pause & exit /b 1
)
echo [1/3] 打包 exe ...
%PY% -m PyInstaller desktop\fileserver\tools\37du-fileserver.spec ^
--distpath desktop\fileserver\dist-exe ^
--workpath desktop\fileserver\build-exe ^
echo [1/3] building exe ...
%PY% -m PyInstaller fileserver\tools\37du-fileserver.spec ^
--distpath fileserver\dist-exe ^
--workpath fileserver\build-exe ^
--noconfirm
if errorlevel 1 (echo [err] 打包失败 & pause & exit /b 1)
if errorlevel 1 (echo [err] BUILD FAILED & pause & exit /b 1)
echo [2/3] 装配部署目录 ...
set DEP=desktop\fileserver\dist-exe\fileserver
echo [2/3] assembling deploy dir ...
set DEP=fileserver\dist-exe\fileserver
if not exist %DEP% mkdir %DEP%
REM 拷贝 .env 到 exe 同目录(含 FILESERVER_BASE_URL 指向内网)
copy /y desktop\fileserver\.env %DEP%\.env >nul
move /y desktop\fileserver\dist-exe\37du-fileserver.exe %DEP%\37du-fileserver.exe >nul
REM copy .env next to exe (contains FILESERVER_BASE_URL pointing to intranet)
copy /y fileserver\.env %DEP%\.env >nul
move /y fileserver\dist-exe\37du-fileserver.exe %DEP%\37du-fileserver.exe >nul
echo [3/3] 完成。
echo 部署目录: %DEP%
echo 部署到内网机器 172.30.35.135,先改该 .env 的 FILESERVER_BASE_URL/TOKEN 再运行 install_autostart.bat
pause
echo [3/3] done.
echo deploy dir: %DEP%
echo deploy to 172.30.35.135: adjust FILESERVER_BASE_URL/TOKEN in .env, then run install_autostart.bat
pause
+7 -5
View File
@@ -48,7 +48,7 @@ def _as_str_list(value):
class ErpReportExportPlugin(ScenePlugin):
id = "xq0031_xq0032"
name = "ERP物料收发汇总-采购订单报表导出"
version = "1.0.8"
version = "1.0.9"
description = "金蝶K3Cloud报表导出:物料收发汇总表+ 采购订单列表,支持新旧系统与个性化配置"
platform = "" # ERP 自带登录页(无验证码),插件内现场真登录,不使用底座共享登录态
uses_month = False
@@ -64,7 +64,8 @@ class ErpReportExportPlugin(ScenePlugin):
{"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)},
"options": config.STOCK_CODES_DEFAULT + config.STOCK_CODES_DEFAULT_OLD,
"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",
@@ -82,7 +83,8 @@ class ErpReportExportPlugin(ScenePlugin):
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
org = str(fields.get("org_name") or "").strip() or (
config.ORG_NAME_OLD if erp == 'old' else config.ORG_NAME)
scheme = str(fields.get("scheme_name") or "").strip() or config.SCHEME_NAME
codes = _as_str_list(fields.get("stock_codes")) # 空 = 全部仓库不筛选
dates = _as_str_list(fields.get("date_options")) or list(config.DATE_OPTIONS_DEFAULT)
@@ -101,7 +103,7 @@ class ErpReportExportPlugin(ScenePlugin):
# ---------- 登录(一次,两种报表共用会话) ----------
ctx.progress(3)
ctx.log(f"ERP 系统:{'新版' if erp == 'new' else '旧版'}({erp_login.ERP_URLS[erp]})")
ctx.log(f"ERP 系统:{'新版' if erp == 'new' else '旧版'}({erp_login.ERP_URLS[erp]}),查询组织:{org}")
ok, page = erp_login.erp_login(erp, username, password)
if not ok:
raise RuntimeError("ERP 登录失败(账号密码错误或网络异常),详见日志")
@@ -131,7 +133,7 @@ class ErpReportExportPlugin(ScenePlugin):
files31, failed31 = material_summary.run(
page, save_dir, org, codes, dates,
progress=lambda done_i, _total: _report(done_i),
set_org=(erp != 'old')) # 旧系统不换组织,使用登录默认组织
set_org=True) # 新旧系统均显式设置查询组织(旧系统登录默认组织已不再默认)
saved += files31
failed += [f"物料收发汇总表[{x}]" for x in failed31]
except RuntimeError as e:
+5 -2
View File
@@ -10,10 +10,11 @@ webhost /api/plugin-config 落执行机本机,run() 时经 fields 注入;
"""
# ==================== 1. 业务默认值(fields 未传/留空时的兜底) ====================
ORG_NAME = '99.01 重庆金七象供应链管理有限公司' # 查询组织
ORG_NAME = '99.01 重庆金七象供应链管理有限公司' # 查询组织(新版默认)
ORG_NAME_OLD = '99.01.07.01.01 石桥铺会馆' # 查询组织(旧版默认;登录已不再默认,须显式选择)
# 仓库编码→仓库中文名(现场映射,供「下载全部仓库后按中文名筛选」使用):
# 0101010101 重庆运营总仓 / 0101010201 重庆美得三方仓 / 0101020201 成都美得三方仓
# 0101030201 长沙乐行三方仓 / 0101040201 西安美得三方仓
# 0101030201 长沙乐行三方仓 / 0101040201 西安美得三方仓 / 03010127 代管仓(旧版登录默认)
# 前端仍要求选择仓库编码(决定最终保留哪些仓库),查询统一下载全部仓库,
# 下载后用 openpyxl 按本映射把仓库中文名列筛到所选编码对应仓库,覆盖保存。
STOCK_NAME_MAP = {
@@ -22,10 +23,12 @@ STOCK_NAME_MAP = {
'0101020201': '成都美得三方仓',
'0101030201': '长沙乐行三方仓',
'0101040201': '西安美得三方仓',
'03010127': '代管仓',
}
# 前端可选仓库编码列表(与 STOCK_NAME_MAP 键一致;留空 = 全部仓库不筛选)
STOCK_CODES_DEFAULT = ['0101010101', '0101010201', '0101020201', '0101030201', '0101040201']
STOCK_CODES_DEFAULT_OLD = ['03010127'] # 旧版默认仓库(代管仓,随 ERP 系统选项切换)
DATE_OPTIONS_DEFAULT = ['60D', '30D', '15D', '7D', '3D']
SCHEME_NAME = '默认方案(个人)' # 需求32 快捷方案(精确匹配)
FOLDER_NAME = '采购计划报表' # 保存目录命名前缀(31/32 同目录)
+2 -2
View File
@@ -953,7 +953,7 @@ def _run_once(page, begin, end, save_dir, new_name, first, org, set_org=True):
if not _open_filter(page):
return False
if first:
# 首档:新版/旧版唯一区别是组织——新版需选组织(set_org=True),旧版用登录默认组织;
# 首档:新旧系统均需显式设置查询组织(set_org=True,旧系统登录默认组织已不再默认);
# 其余完全一致:无需点「保存」固化方案,仓库范围由 _submit_query 提交前以键盘方式
# 清空,日期正常输入,编码不做 K3 过滤,下载后按所选编码的中文名筛选 Excel(见 run())。
if set_org and not _set_org(page, org):
@@ -976,7 +976,7 @@ def _run_once(page, begin, end, save_dir, new_name, first, org, set_org=True):
# ================== 入口 ==================
def run(page, save_dir, org, codes, date_options, progress=None, set_org=True):
"""先全局搜索打开报表,再逐日期选项导出(组织/仓库仅首档完整设置,后续档只改日期)。
set_org=False 时跳过组织设置(旧系统使用登录默认组织)。
set_org=True 时首档显式设置查询组织;新旧系统一致(旧系统登录默认组织已不再默认)。
progress(done, total) 为整体进度回调;返回 (saved_files, failed_labels)。"""
if not _open_report(page):
raise RuntimeError("打开「物料收发汇总表」失败:全局搜索未打开报表过滤界面(详见日志)")
+5 -4
View File
@@ -2,7 +2,7 @@
"schema_version": 1,
"id": "xq0031_xq0032",
"name": "ERP物料收发汇总-采购订单报表导出",
"version": "1.0.8",
"version": "1.0.9",
"description": "金蝶K3Cloud报表自动导出:物料收发汇总表+ 采购订单列表,支持新旧系统、下载全部仓库后按所选仓库中文名自动筛选、日期多选(含自定义区间),个性化配置保存在本机",
"category": "报表",
"icon": "",
@@ -46,17 +46,18 @@
"org_name": {
"type": "string",
"title": "查询组织",
"default": "99.01 重庆金七象供应链管理有限公司"
"default": "99.01 重庆金七象供应链管理有限公司",
"description": "新版默认=金七象;旧版默认=99.01.07.01.01 石桥铺会馆,插件界面切换ERP系统自动带出"
},
"stock_codes": {
"type": "array",
"title": "仓库编码(可多选)",
"items": {
"type": "string",
"enum": ["0101010101", "0101010201", "0101020201", "0101030201", "0101040201"]
"enum": ["0101010101", "0101010201", "0101020201", "0101030201", "0101040201", "03010127"]
},
"default": ["0101010101", "0101010201", "0101020201", "0101030201", "0101040201"],
"description": "查询统一下载全部仓库,下载后按所选编码对应的中文仓库名自动筛选保存;留空=全部仓库不筛选"
"description": "查询统一下载全部仓库,下载后按所选编码对应的中文仓库名自动筛选保存;留空=全部仓库不筛选。新版默认=五个三方仓;旧版默认=03010127(代管仓,切换ERP系统自动带出)"
},
"date_options": {
"type": "array",
+2 -2
View File
@@ -1,11 +1,11 @@
{
"name": "erp-report-export-ui",
"name": "xq0031-xq0032-ui",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "erp-report-export-ui",
"name": "xq0031-xq0032-ui",
"version": "1.0.0",
"dependencies": {
"@element-plus/icons-vue": "^2.3.2",
+45 -13
View File
@@ -1,8 +1,7 @@
<template>
<div class="page">
<!-- 未登录 / 结果横幅 -->
<el-alert v-if="needLogin" type="warning" :closable="false" show-icon
title="未登录:请先在壳子(工作台)登录统一账户,再刷新本界面" />
<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>
@@ -35,14 +34,15 @@
<el-input v-model="form.erp_username" placeholder="你的ERP登录账号" :disabled="running" clearable />
</el-form-item>
<el-form-item label="登录密码">
<el-input v-model="form.erp_password" type="password" show-password
placeholder="仅保存在本机,下次免填" :disabled="running" />
<el-input v-model="form.erp_password" type="password" show-password placeholder="仅保存在本机,下次免填"
:disabled="running" />
</el-form-item>
</div>
<el-form-item label="查询组织">
<el-input v-model="form.org_name" :disabled="running" clearable
placeholder="确保过滤界面组织为该值,否则自动重新选择" />
placeholder="新版默认=金七象;旧版默认=99.01.07.01.01 石桥铺会馆,切换ERP系统自动带出" />
<div class="tip">切换 ERP 系统时会自动带出该系统默认组织;如已自定义组织名则保持不变</div>
</el-form-item>
<template v-if="form.mode !== '采购订单列表'">
@@ -51,7 +51,8 @@
:reserve-keyword="false" placeholder="勾选预设或输入新编码后回车" :disabled="running" class="wide">
<el-option v-for="c in STOCK_PRESETS" :key="c" :value="c" :label="c" />
</el-select>
<div class="tip">查询统一下载全部仓库,下载后按所选编码对应的中文仓库名自动筛选;留空=全部不筛选</div>
<div class="tip">查询统一下载全部仓库,下载后按所选编码对应的中文仓库名自动筛选;留空=全部不筛选。切换 ERP 系统自动带出该系统默认仓库(新版=五个三方仓;旧版=03010127 代管仓)
</div>
</el-form-item>
<el-form-item label="日期选项">
<el-select v-model="form.date_options" multiple filterable allow-create default-first-option
@@ -64,12 +65,10 @@
<div class="grid">
<el-form-item v-if="form.mode !== '物料收发汇总表'" label="快捷方案">
<el-input v-model="form.scheme_name" :disabled="running" clearable
placeholder="采购订单列表使用的过滤方案名(精确匹配)" />
<el-input v-model="form.scheme_name" :disabled="running" clearable placeholder="采购订单列表使用的过滤方案名(精确匹配)" />
</el-form-item>
<el-form-item label="保存目录">
<el-input v-model="form.save_dir" :disabled="running" clearable
placeholder="留空 = 桌面/采购计划报表_今天日期" />
<el-input v-model="form.save_dir" :disabled="running" clearable placeholder="留空 = 桌面/采购计划报表_今天日期" />
</el-form-item>
</div>
@@ -98,16 +97,28 @@ import { onMounted, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { connectWS, getRun, loadConfig, saveConfig, startRun, stopRun } from './api'
const STOCK_PRESETS = ['0101010101', '0101010201', '0101020201', '0101030201', '0101040201']
const STOCK_PRESETS = ['0101010101', '0101010201', '0101020201', '0101030201', '0101040201', '03010127']
const DATE_PRESETS = ['60D', '30D', '15D', '7D', '3D']
// 新旧系统各自的默认查询组织(旧系统登录已不再默认该组织,须在过滤界面显式选择)
const ORG_DEFAULTS = {
'新版': '99.01 重庆金七象供应链管理有限公司',
'旧版': '99.01.07.01.01 石桥铺会馆',
}
// 新旧系统各自的默认仓库编码(旧版登录默认仓库 = 03010127 代管仓)
const STOCK_DEFAULTS = {
'新版': ['0101010101', '0101010201', '0101020201', '0101030201', '0101040201'],
'旧版': ['03010127'],
}
const DEFAULTS = () => ({
mode: '两个都导',
erp_system: '新版',
erp_username: '',
erp_password: '',
org_name: '99.01 重庆金七象供应链管理有限公司',
stock_codes: [...STOCK_PRESETS],
org_name: ORG_DEFAULTS['新版'],
stock_codes: [...STOCK_DEFAULTS['新版']],
date_options: [...DATE_PRESETS],
scheme_name: '默认方案(个人)',
save_dir: '',
@@ -150,6 +161,23 @@ watch(form, () => {
saveTimer = setTimeout(() => saveNow(false), 800)
}, { deep: true })
// 切换 ERP 系统:组织名/仓库编码未自定义(空 或 仍是另一系统默认)时自动带出本系统默认
watch(() => form.erp_system, (sys) => {
if (!loaded.value || running.value) return
const orgOther = sys === '新版' ? ORG_DEFAULTS['旧版'] : ORG_DEFAULTS['新版']
if (!form.org_name || form.org_name === orgOther) form.org_name = ORG_DEFAULTS[sys]
const stkOther = sys === '新版' ? STOCK_DEFAULTS['旧版'] : STOCK_DEFAULTS['新版']
if (!form.stock_codes.length || sameArray(form.stock_codes, stkOther)) {
form.stock_codes = [...STOCK_DEFAULTS[sys]]
}
})
function sameArray(a, b) {
if (a.length !== b.length) return false
const s = new Set(a)
return b.every((x) => s.has(x))
}
async function saveNow(explicit) {
try {
await saveConfig(JSON.parse(JSON.stringify(form)))
@@ -162,7 +190,11 @@ async function saveNow(explicit) {
}
function resetDefaults() {
const sys = form.erp_system // 保留当前选择的 ERP 系统
Object.assign(form, DEFAULTS())
form.erp_system = sys
form.org_name = ORG_DEFAULTS[sys] // 恢复默认时按当前系统默认组织
form.stock_codes = [...STOCK_DEFAULTS[sys]] // 恢复默认时按当前系统默认仓库
ElMessage.info('已恢复默认配置')
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+13 -13
View File
@@ -1,13 +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>ERP报表导出</title>
<script type="module" crossorigin src="/pui/xq0031_xq0032/assets/index-BH35ivwT.js"></script>
<link rel="stylesheet" crossorigin href="/pui/xq0031_xq0032/assets/index-Wnhz7vCv.css">
</head>
<body>
<div id="app"></div>
</body>
</html>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ERP报表导出</title>
<script type="module" crossorigin src="/pui/xq0031_xq0032/assets/index-B7DSB6ed.js"></script>
<link rel="stylesheet" crossorigin href="/pui/xq0031_xq0032/assets/index-C1QhPHbp.css">
</head>
<body>
<div id="app"></div>
</body>
</html>