feat(plugin): 新增 XQ0012 EHR 预支及支付报酬自动发起 ERP 付款申请(0.1.0)

- 读 EHR 预支台账 → 按 ERP 付款申请单口径逐行建单,默认试算不写库
- 可选建单后自动提交、按套打样例生成 PDF 直连网络打印,打印完成钉钉提醒领取
- 含幂等查重与异常清单,业务口径与字段顺序按生产单核对
- 依赖 erpsdk / printkit / dingtalk_sdk(plugin.json requires.sdks 声明)
- 需求单文档同步:开发/流程/评分/需求文档更新,新增交接文档
This commit is contained in:
2026-11-16 11:27:38 +08:00
parent 3f1951fba1
commit cf86b568f0
34 changed files with 5064 additions and 24 deletions
@@ -0,0 +1,55 @@
# XQ0012 付款申请单自动发起(xq0012)
读 EHR 预支台账 → 在 ERP 生成付款申请单(默认试算不写库)→ 可选提交 → 自动套打打印。
## 功能
1. **台账取数**:目录内取最新「预支」xlsx,读 `预支报酬台账`;工号非空、金额 > 0、无 `#N/A` 的行才算有效。
2. **单据组装**:按 ERP 付款申请单口径生成 Save Model(申请人按工号、部门在申请人之后、分录最后)。
3. **幂等建单**:按「日期 + 会馆 + 姓名」查重,已存在则跳过;建单失败重试 3 次。
4. **可选提交**:提交后 `A → B` 进审批流;关闭时只建草稿,由 HR 在 ERP 核对后手动提交。
5. **套打打印**:按 ERP 套打样例自绘 PDF(A4 / SimSun / 表格线坐标实测),`printkit` 直连网络打印机出纸。
6. **异常清单**:哪一行、什么原因没建成/没打成,逐条返回。
7. **钉钉提醒**:打印成功后用企业内部应用「工作通知」推给指定接收人(单号/收款人/金额/打印机),提醒去领取签字(默认开)。
## 界面字段(plugin.json)
| 字段 | 说明 |
|---|---|
| `ledger_dir` / `ledger_file` | 台账目录(取最新)/ 指定文件 |
| `apply_date` | 申请日期,空=今天 |
| `pay_purpose` | 个人借款 / 工资预提 / 工资发放(⚠️ 业务口径待确认) |
| `apply_dept` | 申请部门编码,默认 `BM000477 人力资源部` |
| `expect_days` | 期望付款日 = 申请日 + N 天 |
| `erp_system` / `erp_username` / `erp_password` | ERP 新版/旧版与账密(仅存本机) |
| `dry_run` | **默认开**:只组装 + 查重 + 输出,不写 ERP |
| `submit` | 建单后自动提交(默认关) |
| `print_enabled` / `printer` / `copies` | 套打打印、打印机(人力资源部双面 / 网络信息部单面)、份数 |
| `dingtalk_enabled` / `dingtalk_users` | 打印后钉钉提醒(默认开)、接收人「姓名/工号」(多个用「、」分隔,留空=不提醒) |
## 依赖
- SDK:`erpsdk ^0.1`(ERP WebAPI)、`printkit ^0.1`(IPP 打印)、`dingtalk_sdk ^0.1`(企业应用 token),由执行机按 `plugin.json.requires.sdks` 下发;
- 第三方库:`openpyxl`、`pymupdf`、`requests`(见 requirements.txt)。
## 自检 / 打包 / 发布
```bash
# 自检(离线:不登录、不出纸)
set PYTHONPATH=libs\erpsdk;libs\printkit;libs\dingtalk
.venv\Scripts\python.exe "plugins\XQ0001-0100\XQ0012 EHR预支及支付报酬自动发起ERP付款申请\_selftest.py"
# 打包
.venv\Scripts\python.exe "plugins\XQ0001-0100\XQ0012 EHR预支及支付报酬自动发起ERP付款申请\_pack.py"
# 发布(默认进测试通道,人工验证后转正)
.venv\Scripts\python.exe tools\agent_cli.py publish dist-plugin\xq0012_v0.1.0.zip --id xq0012 --base http://172.30.30.243:8800 --admin puddy --password 123456
```
## 已知限制
- 收款账号/开户行/账户名暂无数据源(台账不含银行卡,HR 侧有工资卡接口),当前留空;
- 台账组织名称→编码依赖工作簿内 `辅助2-ERP组织机构` 表;
- 不做审批动作,提交后交给 ERP 审批流。
口径细节见 `docs/需求单/XQ0001-0100/XQ0012 .../` 下 需求/流程/开发/评分 四份文档。
@@ -0,0 +1,163 @@
# -*- coding: utf-8 -*-
"""XQ0012 EHR 预支及支付报酬 → ERP 付款申请单(webhost 场景插件)。
流程:读 EHR 预支台账(xlsx)→ 逐行组装 Save Model →(幂等查重)→ 建单 →
(可选提交)→ 自绘套打 PDF →(可选)printkit 出纸。
默认 **试算模式**(dry_run=True):不写 ERP,只输出将要提交的报文与校验结果;
业务口径确认后关掉试算、按需打开「提交」「打印」。
"""
import os
from datetime import date
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
from . import config
from .data import erp as erp_mod
from .data import ledger
from .logic import flow
def _parse_date(s: str):
s = (s or '').strip()
if not s:
return None
for fmt in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d'):
try:
return date(*[int(x) for x in _split(s, fmt)])
except Exception: # noqa: BLE001
continue
return None
def _split(s: str, fmt: str):
import re
nums = [int(x) for x in re.findall(r'\d+', s)]
return nums[:3]
class PrepayPayApplyPlugin(ScenePlugin):
"""EHR 预支 → ERP 付款申请单(需求 XQ0012)。"""
id = 'xq0012'
name = 'EHR预支及支付报酬自动发起ERP付款申请'
version = '0.1.0'
description = ('读 EHR 预支台账 → 自动在 ERP 建付款申请单(默认试算不写库),'
'可选提交、自动套打打印;含幂等查重与异常清单')
platform = '' # 走 ERP WebAPI 账密登录,不用底座共享登录态
uses_month = False
capabilities = ['xq0012']
permissions = {'platforms': []}
fields = {
'ledger_dir': {
'type': 'string', 'title': '台账目录', 'default': config.LEDGER_DIR_DEFAULT,
'description': '预支台账 xlsx 所在目录;留空=默认目录,自动取最新一个',
},
'ledger_file': {
'type': 'string', 'title': '台账文件(可选)', 'default': '',
'description': '指定具体 xlsx 路径;留空=按目录取最新',
},
'apply_date': {
'type': 'string', 'title': '申请日期', 'default': '',
'description': 'YYYY-MM-DD;留空=今天',
},
'pay_purpose': {
'type': 'string', 'title': '付款用途', 'default': '个人借款',
'enum': ['个人借款', '工资预提', '工资发放'],
'description': '⚠️ 业务待确认:人工模板=个人借款,生产真实单=工资预提',
},
'apply_dept': {
'type': 'string', 'title': '申请部门编码', 'default': config.APPLY_DEPT_ID,
'description': '默认 BM000477 人力资源部(生产真实单口径)',
},
'expect_days': {
'type': 'number', 'title': '期望付款日=申请日+N 天', 'default': config.DEFAULT_EXPECT_DAYS,
},
'erp_system': {
'type': 'string', 'title': 'ERP系统', 'default': '新版', 'enum': ['新版', '旧版'],
},
'erp_username': {'type': 'string', 'title': 'ERP登录账号', 'default': ''},
'erp_password': {'type': 'string', 'title': 'ERP登录密码', 'default': '', 'format': 'password'},
'dry_run': {
'type': 'boolean', 'title': '试算模式(不写 ERP)', 'default': True,
'description': '开启后只组装+查重+输出结果,不建单;验证通过后再关',
},
'submit': {
'type': 'boolean', 'title': '建单后自动提交', 'default': False,
'description': '关闭时只建草稿(A),由 HR 在 ERP 确认后手动提交',
},
'print_enabled': {
'type': 'boolean', 'title': '建单后套打打印', 'default': False,
},
'printer': {
'type': 'string', 'title': '打印机', 'default': config.PRINTER_DEFAULT,
'enum': config.PRINTER_OPTIONS,
},
'copies': {'type': 'number', 'title': '打印份数', 'default': config.PRINT_COPIES_DEFAULT},
'dingtalk_enabled': {
'type': 'boolean', 'title': '打印后钉钉提醒领取',
'default': config.DINGTALK_ENABLED_DEFAULT,
'description': '打印成功后推送一条群提醒(单号/收款人/金额/打印机),提醒去领取签字',
},
'dingtalk_users': {
'type': 'string', 'title': '钉钉接收人(姓名/工号)',
'default': config.DINGTALK_USERS_DEFAULT,
'description': '多个用「、」「,」「;」或换行分隔;重名必须带工号;留空=不提醒',
},
'debug_mode': {'type': 'boolean', 'title': '调试日志', 'default': False},
}
def run(self, fields: dict, ctx) -> dict:
fields = fields or {}
debug = bool(fields.get('debug_mode', False))
def log(msg: str, level: str = 'INFO') -> None:
if level == 'DEBUG' and not debug:
return
try:
ctx.log(msg, level)
except TypeError:
ctx.log(msg)
config.set_log(log)
work_dir = str(fields.get('ledger_dir') or '').strip() or config.LEDGER_DIR_DEFAULT
ledger_file = str(fields.get('ledger_file') or '').strip()
path = ledger_file or ledger.find_latest_ledger(work_dir)
log(f'[台账] {path}')
rows = ledger.read_rows(path)
log(f'[台账] 有效数据 {len(rows)} 行')
if not rows:
return {'summary': '台账无有效数据(检查工号/金额是否为空或含 #N/A)', 'detail': [], 'path': ''}
org_map = ledger.load_org_map(path)
purpose = config.PAY_PURPOSE_OPTIONS.get(
str(fields.get('pay_purpose') or '个人借款').strip(), config.PAY_PURPOSE_ID)
dept_code = str(fields.get('apply_dept') or '').strip() or config.APPLY_DEPT_ID
apply_date = _parse_date(str(fields.get('apply_date') or ''))
dry_run = bool(fields.get('dry_run', True))
client = None
if not dry_run:
user = str(fields.get('erp_username') or '').strip()
pwd = str(fields.get('erp_password') or '')
if not (user and pwd):
return {'summary': '未填 ERP 账号密码(试算模式不需要)', 'detail': [], 'path': ''}
erp = 'old' if str(fields.get('erp_system') or '新版').strip() == '旧版' else 'new'
client = erp_mod.login(user, pwd, erp=erp)
out = flow.run_flow(
rows_data=rows, org_map=org_map, client=client,
apply_date=apply_date, purpose_id=purpose, dept_code=dept_code,
expect_days=int(fields.get('expect_days') or config.DEFAULT_EXPECT_DAYS),
submit=bool(fields.get('submit', False)),
print_enabled=bool(fields.get('print_enabled', False)),
printer=str(fields.get('printer') or config.PRINTER_DEFAULT),
copies=int(fields.get('copies') or 1),
dry_run=dry_run,
)
log(f'[完成] {out["summary"]}')
return out
PLUGINS.append(PrepayPayApplyPlugin())
@@ -0,0 +1,39 @@
# -*- coding: utf-8 -*-
"""发布打包辅助(`_` 前缀,运行时不会被插件扫描加载)。
把插件压成 dist-plugin/xq0012_v<版本>.zip(zip 根含 plugin.json)。
排除:ui-src(前端源码)、__pycache__、_selftest*、本脚本、*.pyc。
"""
import json
import sys
import zipfile
from pathlib import Path
_HERE = Path(__file__).resolve().parent
_OUT_DIR = _HERE.parents[2] / "dist-plugin"
_EXCLUDE_DIRS = {"ui-src", "__pycache__", "debug", ".sessions"}
_EXCLUDE_FILES = {"_pack.py"}
_EXCLUDE_PREFIXES = ("_selftest",)
def main():
manifest = json.loads((_HERE / "plugin.json").read_text(encoding="utf-8"))
pid, ver = manifest["id"], manifest["version"]
if manifest.get("ui") and not (_HERE / "ui" / "index.html").is_file():
sys.exit("缺少 ui/index.html:请先在 ui-src 下执行 npm install && 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:
continue
if p.name.startswith(_EXCLUDE_PREFIXES) 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,130 @@
# -*- coding: utf-8 -*-
"""插件自检(不联网:不登录 ERP、不出纸)。
会被壳子/SDK 分发流程当作自检入口(见 sdk.json 约定),也可手动跑:
.venv\\Scripts\\python.exe "plugins\\XQ0001-0100\\XQ0012 EHR预支及支付报酬自动发起ERP付款申请\\_selftest.py"
覆盖:配置常量 → payload 字段顺序 → 台账读取 → 套打 PDF 生成 → 流程试算。
"""
import sys
import types
from datetime import date
from pathlib import Path
HERE = Path(__file__).resolve().parent
# 以「包」的方式加载(跳过 __init__.py 的 webhost 依赖)
_pkg = types.ModuleType("xq0012")
_pkg.__path__ = [str(HERE)]
sys.modules["xq0012"] = _pkg
from xq0012 import config # noqa: E402
from xq0012.logic import payload, flow # noqa: E402
from xq0012.report import payapply_pdf, notify # noqa: E402
FAILED = []
def check(name, fn):
try:
fn()
print(f"[ok] {name}")
except Exception as e: # noqa: BLE001
FAILED.append((name, e))
print(f"[FAIL] {name}: {e}")
def t_config():
assert config.FORM_ID == 'CN_PAYAPPLY'
assert config.BILL_TYPE_ID == 'FKSQ006.0YS'
assert config.SAVE_OPTIONS['is_auto_adjust_field'] is False, 'IsAutoAdjustField 必须关'
def t_payload_order():
row = {'seq': '1', 'month': '202610', 'staff': '37000365', 'name': '何广飞',
'date': '2026-10-30', 'amount': 2000.0, 'reason': '缴纳弟弟生活费',
'org_path': '集团-金色印象事业部-第一大区-水晶郦城CEO会馆', 'dept': '接待组'}
m = payload.build_model(row, org_code='99.01.06.01.02.01.05', dept_code='BM000477',
purpose_id='SFKYT11_SYS', apply_date=date(2026, 10, 30), expect_days=1,
venue='水晶郦城CEO会馆')
keys = list(m)
assert keys[-1] == 'FPAYAPPLYENTRY', '分录必须最后'
assert keys.index('FBJ_SQR') < keys.index('F_VTUY_Base_re5'), '部门必须在申请人之后'
assert m['FBJ_SQR'] == {'FSTAFFNUMBER': '37000365'}
assert m['FCONTACTUNIT'] == {'FNumber': '37000365'}, '往来单位用工号键 FNumber'
assert m['FPAYAPPLYENTRY'][0]['FAPPLYAMOUNTFOR'] == 2000.0
assert m['FPAYAPPLYENTRY'][0]['FEXPECTPAYDATE'] == '2026-10-31'
assert '何广飞' in m['F_VTUY_Remarks_qtr']
def t_ledger_read():
p = config.LEDGER_DIR_DEFAULT
import os
if not os.path.isdir(p):
print(' (台账目录不存在,跳过)')
return
sys.path.insert(0, str(HERE))
from xq0012.data import ledger
f = ledger.find_latest_ledger(p)
rows = ledger.read_rows(f)
assert rows and rows[0]['staff'], '台账应至少有一条有效行'
org = ledger.load_org_map(f)
print(f' {Path(f).name}: {len(rows)} 行,组织映射 {len(org)} 条')
def t_render_pdf():
data = payapply_pdf.from_view({}, 'SELFTEST-0001')
data.update({'applicant': '何广飞', 'applicant_no': '37000365', 'dept': '人力资源部',
'pay_org': '重庆三十七度健康管理有限公司', 'apply_amount': '2000.00',
'approve_amount': '2000.00', 'create_date': '2026/11/14', 'currency': '人民币'})
data['entries'] = [{'cost': '预支工资', 'account_name': '何广飞', 'bank': '招商银行',
'account_no': '6222***0000', 'amount': '2000.00', 'dept': '', 'remark': ''}]
out = str(HERE.parents[2] / 'out' / '_selftest_payapply.pdf')
payapply_pdf.render_payapply(data, out)
import pymupdf
doc = pymupdf.open(out)
assert doc.page_count == 1
text = doc[0].get_text('text')
assert 'SELFTEST-0001' in text and '2000.00' in text
assert len([d for d in doc[0].get_drawings()]) >= 30, '表格线数量异常'
doc.close()
def t_notify_message():
body = notify.build_message(
[{'bill_no': 'FKSQ20261100001', 'name': '何广飞', 'amount': 2000.0},
{'bill_no': 'FKSQ20261100002', 'name': '唐雪非', 'amount': 1500.5}],
'网络信息部', failed=1)
assert '网络信息部' in body and '打印机处领取' in body
assert 'FKSQ20261100001' in body and '1500.50' in body
assert '合计 3500.50 元' in body
assert '打印失败' in body
def t_notify_recipients():
got = notify.parse_recipients('陈莲/37001090、张三(37000236); 李四')
assert got[0] == ('陈莲', '37001090') and got[1] == ('张三', '37000236')
assert got[2] == ('李四', '')
def t_flow_dry_run():
rows = [{'seq': '1', 'staff': '37000365', 'name': '何广飞', 'date': '2026-10-30',
'amount': 2000.0, 'reason': '测试', 'org_path': '集团-水晶郦城CEO会馆', 'dept': '接待组'}]
out = flow.run_flow(rows_data=rows, org_map={'水晶郦城CEO会馆': '99.01.06.01.02.01.05'},
dry_run=True, apply_date=date(2026, 10, 30))
assert '试算' in out['summary'] and len(out['detail']) == 1
if __name__ == '__main__':
check('配置常量', t_config)
check('payload 字段顺序', t_payload_order)
check('台账读取', t_ledger_read)
check('套打 PDF', t_render_pdf)
check('钉钉提醒文案', t_notify_message)
check('钉钉接收人解析', t_notify_recipients)
check('流程试算', t_flow_dry_run)
print('=' * 50)
if FAILED:
print(f'失败 {len(FAILED)} 项')
sys.exit(1)
print('全部通过')
@@ -0,0 +1,90 @@
# -*- coding: utf-8 -*-
"""XQ0012 插件配置:常量 + 业务口径 + 全局日志钩子。
插件自包含:只依赖标准库 / 第三方库 / erpsdk、printkit(SDK 下发)/ 底座注入的 RunContext。
业务口径分两类:
- 「已验证」:表单号、单据类型、字段引用键、Save 参数、表头字段顺序、套打版面 —— 2026-11-14 测试服实测;
- 「待业务确认」:付款用途、备注列、申请部门、期望付款日口径 —— 用常量集中管理,确认后只改这里。
"""
# ==================== 已验证:ERP 接口口径 ====================
FORM_ID = 'CN_PAYAPPLY' # 付款申请单(不是 AP_PAYAPPLY)
BILL_TYPE_ID = 'FKSQ006.0YS' # 个人工资付款申请
COST_ID = '0111001' # 费用项目:预支工资
COST_ID_WAGE = '0111002' # 费用项目:工资(支付报酬场景备用)
SETTLETYPE_ID = 'JSFS04_SYS' # 结算方式:转账
CURRENCY_ID = 'PRE001' # 币别:人民币
APPLY_ORG_ID = '99.01' # 申请组织:重庆三十七度健康管理有限公司
# 付款用途(⚠️ 业务待确认:人工模板用 SFKYT11_SYS 个人借款,生产真实单用 SFKYT45_SYS 工资预提)
PAY_PURPOSE_ID = 'SFKYT11_SYS'
PAY_PURPOSE_OPTIONS = {'个人借款': 'SFKYT11_SYS', '工资预提': 'SFKYT45_SYS', '工资发放': 'SFKYT19_SYS'}
# 申请部门(模板/生产真实单均为 人力资源部;测试服备份账套用 BM000027 集团)
APPLY_DEPT_ID = 'BM000477'
# Save 参数:IsAutoAdjustField 必须关掉,否则报「申请人、申请部门必录」(§6.8)
SAVE_OPTIONS = {'need_return_fields': ['FBillNo'], 'is_auto_adjust_field': False}
# ==================== 已验证:套打版面(见 report/payapply_pdf.py) ====================
PDF_NAME_TPL = '套打_付款申请单_{bill_no}.pdf'
# ==================== 钉钉提醒(打印完成 → 提醒领取) ====================
DINGTALK_ENABLED_DEFAULT = True # 默认开:打印成功才发,未打印不会打扰
DINGTALK_USERS_DEFAULT = '陈莲/37004121' # 默认接收人(姓名/工号,重名必须带工号)
# 企业内部应用凭证(与 XQ0052 同一应用;插件自包含,不读根 .env)
DINGTALK_APP_KEY = 'dingc1fnokzybr3u5bbl'
DINGTALK_APP_SECRET = ('AOKyKOc0byGpQkzd20_GqK9-G1LI-Py2qlNeOiCQpR2TnBtzuJCpBuldIqRWX58A')
DINGTALK_AGENT_ID = '4974749954'
DINGTALK_USER_SEARCH_URL = 'https://api.dingtalk.com/v1.0/contact/users/search'
DINGTALK_USER_GET_URL = 'https://oapi.dingtalk.com/user/get'
DINGTALK_WORK_SEND_URL = 'https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2'
# ==================== 打印 ====================
PRINTER_DEFAULT = '人力资源部' # l6570,支持双面;测试机用「网络信息部」l565
PRINTER_OPTIONS = ['人力资源部', '网络信息部']
PRINT_COPIES_DEFAULT = 1
# ==================== 数据源 ====================
LEDGER_DIR_DEFAULT = r'D:\资料\人资\预支' # 预支台账 xlsx 所在目录(取最新)
LEDGER_KEYWORDS = ('预支', '工资预付') # 文件名关键词
LEDGER_SHEET = '预支报酬台账'
ORG_SHEET = '辅助2-ERP组织机构' # 同工作簿内的组织编码→名称表
# 台账列名(第 2 行表头,数据从第 3 行起)
COL_SEQ = '序号'
COL_MONTH = '预支报酬年月'
COL_STAFF = '工号'
COL_NAME = '姓名'
COL_DATE = '提报日期'
COL_AMOUNT = '预支金额'
COL_REASON = '预支原因'
COL_ORG_PATH = '预支组织全路径'
COL_DEPT_PATH = '预支五级部门'
COL_PAY_STATUS = '付款状态'
# ==================== 运行参数 ====================
RETRY_MAX = 3 # 项目规范:全局重试 3 次
TIMEOUT = 60
DEFAULT_EXPECT_DAYS = 1 # 期望付款日 = 申请日 + N 天(待业务确认)
# ==================== 日志钩子 ====================
_log_fn = print
def set_log(fn) -> None:
global _log_fn
_log_fn = fn if fn else print
def log(msg: str, level: str = 'INFO') -> None:
try:
_log_fn(msg, level)
except TypeError:
try:
_log_fn(msg)
except Exception:
pass
except Exception:
pass
@@ -0,0 +1 @@
# -*- coding: utf-8 -*-
@@ -0,0 +1,62 @@
# -*- coding: utf-8 -*-
"""ERP 动作层:登录 / 查重 / 建单 / 提交 / 撤回 / 删除(薄封装 erpsdk)。
已验证细节(2026-11-14 测试服):
- 提交后状态 B;撤回用 `CancelAssign`(`revoke()` 自动探测),B→D;只有 A/Z/D 可删;
- Save 必须传 `is_auto_adjust_field=False`(见 config.SAVE_OPTIONS);
- `view()` 不回 FBillNo,单号要自己带。
"""
from __future__ import annotations
from erpsdk import ErpClient, ErpError, save_options
from .. import config
TAG = '[ERP]'
def login(username: str, password: str, erp: str = 'new', acct: str = '') -> ErpClient:
client = ErpClient(erp, acct=(acct or None), timeout=config.TIMEOUT,
logger=config.log, retry=config.RETRY_MAX)
client.login(username, password)
return client
def find_duplicate(client: ErpClient, remark_fragment: str) -> list:
"""幂等查重:按申请说明片段查同月同日同人同额的已建单。
WAF 会拦含 `and` 的组合过滤,这里只用一个 like 条件。
"""
if not remark_fragment:
return []
try:
return client.bill_query(
config.FORM_ID, 'FBillNo,FDocumentStatus,FDATE',
filter_string=f"F_VTUY_Remarks_qtr like '%{remark_fragment}%'", limit=20) or []
except ErpError as e:
config.log(f'{TAG} 查重失败(忽略继续):{e}')
return []
def create(client: ErpClient, model: dict) -> tuple:
"""保存草稿 → (Id, 单号)。"""
res = client.save(config.FORM_ID, model, extra=save_options(**config.SAVE_OPTIONS))
return res.get('Id'), res.get('Number') or res.get('FBillNo')
def submit(client: ErpClient, number: str) -> None:
client.submit(config.FORM_ID, numbers=[number])
def revoke(client: ErpClient, number: str) -> None:
client.revoke(config.FORM_ID, numbers=[number])
def delete(client: ErpClient, bill_id) -> None:
client.delete(config.FORM_ID, ids=[bill_id])
def status(client: ErpClient, number: str) -> str | None:
rows = client.bill_query(config.FORM_ID, 'FBillNo,FDocumentStatus',
filter_string=f"FBillNo='{number}'", limit=5)
return rows[0][1] if rows else None
@@ -0,0 +1,117 @@
# -*- coding: utf-8 -*-
"""台账数据层:读 EHR 导出的「预支台账」工作簿。
口径(2026-11-14 实测于 1030工资预支付款申请--已付.xlsx):
- sheet「预支报酬台账」:第 2 行是表头,第 3 行起是数据,后面大量空行/公式残留;
- 有效行:工号非空、预支金额 > 0、整行无 #N/A 类错误值;
- 同工作簿的「辅助2-ERP组织机构」sheet(FNumber/FName)用来做 组织名称 → 编码 映射。
"""
from __future__ import annotations
import os
import re
from datetime import datetime
import openpyxl
from .. import config
ERR_RE = re.compile(r'^#(N/A|REF!|VALUE!|DIV/0!|NAME\?|NULL!|NUM!|GETTING_DATA)$', re.I)
def _s(v) -> str:
if v is None:
return ''
if isinstance(v, datetime):
return v.strftime('%Y-%m-%d')
s = str(v).strip()
return '' if ERR_RE.match(s) else s
def _num(v):
try:
return float(str(v).replace(',', ''))
except (TypeError, ValueError):
return 0.0
def find_latest_ledger(work_dir: str = '') -> str:
"""取目录下最新的预支台账 xlsx(文件名含关键词,忽略临时文件)。"""
work_dir = work_dir or config.LEDGER_DIR_DEFAULT
cands = []
for name in os.listdir(work_dir):
if not name.lower().endswith(('.xlsx', '.xlsm')) or name.startswith('~$'):
continue
if any(k in name for k in config.LEDGER_KEYWORDS):
cands.append(os.path.join(work_dir, name))
if not cands:
raise FileNotFoundError(f'{work_dir} 下没有找到预支台账 xlsx(关键词:{config.LEDGER_KEYWORDS})')
cands.sort(key=lambda p: os.path.getmtime(p), reverse=True)
return cands[0]
def load_org_map(path: str) -> dict:
"""组织名称 → 编码(辅助2-ERP组织机构:FNumber / FName#2052)。"""
wb = openpyxl.load_workbook(path, data_only=True, read_only=True)
try:
if config.ORG_SHEET not in wb.sheetnames:
return {}
ws = wb[config.ORG_SHEET]
out = {}
for row in ws.iter_rows(min_row=3, values_only=True):
code, name = _s(row[0] if row else ''), _s(row[1] if len(row) > 1 else '')
if code and name:
out[name] = code
return out
finally:
wb.close()
def read_rows(path: str) -> list:
"""读台账有效数据行,返回行字典列表(键见 config.COL_*)。"""
wb = openpyxl.load_workbook(path, data_only=True)
if config.LEDGER_SHEET not in wb.sheetnames:
raise ValueError(f'{path} 缺少 sheet「{config.LEDGER_SHEET}」')
ws = wb[config.LEDGER_SHEET]
header = {}
for idx, cell in enumerate(next(ws.iter_rows(min_row=2, max_row=2, values_only=True)), 1):
name = _s(cell)
if name:
header[name] = idx - 1
rows = []
for raw in ws.iter_rows(min_row=3, values_only=True):
if not raw:
continue
def get(col):
i = header.get(col)
return raw[i] if i is not None and i < len(raw) else None
staff, amount = _s(get(config.COL_STAFF)), _num(get(config.COL_AMOUNT))
if not staff or amount <= 0:
continue
if any(ERR_RE.match(_s(v)) for v in raw):
continue
rows.append({
'seq': _s(get(config.COL_SEQ)),
'month': _s(get(config.COL_MONTH)),
'staff': staff,
'name': _s(get(config.COL_NAME)),
'date': _s(get(config.COL_DATE)),
'amount': amount,
'reason': _s(get(config.COL_REASON)),
'org_path': _s(get(config.COL_ORG_PATH)),
'dept': _s(get(config.COL_DEPT_PATH)),
'pay_status': _s(get(config.COL_PAY_STATUS)),
})
wb.close()
return rows
def guess_org_code(row: dict, org_map: dict) -> str:
"""从「预支组织全路径」推断付款组织编码(会馆级优先,其次公司级)。"""
path = str(row.get('org_path') or '')
parts = [p for p in re.split(r'[-/→>]', path) if p]
for p in reversed(parts): # 从末级向上找:会馆名优先
p = p.strip()
if p and p in org_map:
return org_map[p]
return config.APPLY_ORG_ID
@@ -0,0 +1 @@
# -*- coding: utf-8 -*-
@@ -0,0 +1,119 @@
# -*- coding: utf-8 -*-
"""流程编排:台账行 → 组装 → 查重 → 建单 →(提交)→ 套打 PDF →(打印)。
安全默认:`dry_run=True` 时**不写 ERP**,只把将要提交的 Model 与校验结果打出来;
`submit=False` 时只建草稿(A 状态),由 HR 在 ERP 里确认后再提交。
"""
from __future__ import annotations
import os
from datetime import date, datetime
from .. import config
from ..data import erp as erp_mod
from ..data import ledger
from . import payload
from ..report import payapply_pdf
def _venue(row: dict) -> str:
path = str(row.get('org_path') or '')
parts = [p for p in path.replace('/', '-').split('-') if p.strip()]
return parts[-1].strip() if parts else ''
def run_flow(*, rows_data: list, org_map: dict, client=None,
apply_date: date | None = None, purpose_id: str = '',
dept_code: str = '', expect_days: int = 1,
submit: bool = False, print_enabled: bool = False,
printer: str = '', copies: int = 1,
dry_run: bool = True, out_dir: str = '') -> dict:
"""执行整批,返回 {summary, detail, path}。"""
apply_date = apply_date or date.today()
purpose_id = purpose_id or config.PAY_PURPOSE_ID
dept_code = dept_code or config.APPLY_DEPT_ID
out_dir = out_dir or os.path.join(os.getcwd(), 'out')
os.makedirs(out_dir, exist_ok=True)
detail, errors, printed, printed_items = [], [], [], []
for row in rows_data:
venue = _venue(row)
org_code = ledger.guess_org_code(row, org_map)
item = {'seq': row.get('seq'), 'staff': row['staff'], 'name': row['name'],
'amount': row['amount'], 'org': org_code, 'venue': venue, 'status': ''}
try:
model = payload.build_model(row, org_code=org_code, dept_code=dept_code,
purpose_id=purpose_id, apply_date=apply_date,
expect_days=expect_days, venue=venue)
except Exception as e: # noqa: BLE001
item['status'] = f'组装失败:{e}'
errors.append(item)
detail.append(item)
continue
if dry_run or client is None:
item['status'] = '试算(未写 ERP)'
detail.append(item)
continue
# 幂等查重(同日期 + 同会馆 + 同姓名)
dup = erp_mod.find_duplicate(client, f"{row.get('date') or payload.fmt_date(apply_date)} {venue}-{row['name']}")
if dup:
item['status'] = f"已存在,跳过({dup[0][0]})"
detail.append(item)
continue
# 重试建单(项目规范:最多 3 次)
last = None
for attempt in range(1, config.RETRY_MAX + 1):
try:
bill_id, number = erp_mod.create(client, model)
item.update({'bill_id': bill_id, 'bill_no': number})
break
except Exception as e: # noqa: BLE001
last = e
config.log(f"[建单] {row['staff']} 第 {attempt} 次失败:{e}", 'ERROR')
if not item.get('bill_no'):
item['status'] = f'建单失败:{last}'
errors.append(item)
detail.append(item)
continue
# 提交
if submit:
try:
erp_mod.submit(client, item['bill_no'])
item['status'] = '已提交(B)'
except Exception as e: # noqa: BLE001
item['status'] = f'已建单,提交失败:{e}'
errors.append(item)
else:
item['status'] = '已建草稿(A)'
# 套打 + 打印
if print_enabled:
try:
doc = client.view(config.FORM_ID, number=item['bill_no'])
pdf = os.path.join(out_dir, config.PDF_NAME_TPL.format(bill_no=item['bill_no']))
payapply_pdf.render_payapply(payapply_pdf.from_view(doc, item['bill_no']), pdf)
item['pdf'] = pdf
from ..report import print as print_mod
pr = print_mod.print_pdf(pdf, printer, copies, dry_run=False)
item['print'] = pr
printed.append(pdf)
if any(x.get('ok') for x in pr):
printed_items.append({'bill_no': item['bill_no'], 'name': row['name'],
'amount': row['amount']})
except Exception as e: # noqa: BLE001
item['pdf_error'] = str(e)[:200]
config.log(f"[套打] {item['bill_no']} 失败:{e}", 'ERROR')
detail.append(item)
total = sum(float(r['amount']) for r in rows_data)
summary = (f"台账 {len(rows_data)} 行,合计 {total:.2f} 元;"
f"{'试算' if dry_run else '建单'} {len([d for d in detail if d.get('bill_no')])} 张,"
f"异常 {len(errors)} 条,打印 {len(printed)} 张")
print_failed = len([d for d in detail if d.get('print') and not any(x.get('ok') for x in d['print'])])
return {'summary': summary, 'detail': detail, 'errors': errors,
'path': printed[0] if printed else '',
'printed': printed_items, 'print_failed': print_failed, 'printer': printer}
@@ -0,0 +1,63 @@
# -*- coding: utf-8 -*-
"""台账行 → ERP 付款申请单 Save Model。
⚠️ 字段顺序是**硬约束**(2026-11-14 实测):JSON 里「申请部门 F_VTUY_Base_re5」
必须排在申请人 FBJ_SQR 之后,否则报「申请人、申请部门必录」;
且表头字段一律不得出现在 FPAYAPPLYENTRY 之后。见 §6.8。
"""
from __future__ import annotations
from datetime import date, timedelta
from .. import config
def fmt_date(d: date) -> str:
return d.strftime('%Y-%m-%d')
def build_remark(row: dict, venue: str = '') -> str:
"""申请说明:`{日期} {会馆}-{姓名}(-)的预支,原因:{原因}`(与生产真实单同格式)。"""
return (f"{row.get('date', '')} {venue}-{row.get('name', '')}(-)的预支,"
f"原因:{row.get('reason', '')}")
def build_model(row: dict, *, org_code: str, dept_code: str, purpose_id: str,
apply_date: date, expect_days: int = 1, bank: dict | None = None,
venue: str = '') -> dict:
"""组装 Save Model(字段顺序即下方书写顺序,勿重排)。"""
bank = bank or {}
expect = apply_date + timedelta(days=int(expect_days or 0))
staff = str(row['staff'])
model = {
# --- 单据头(顺序:类型 → 日期 → 往来/收款 → 币别/组织 → 申请人 → 部门 → 说明) ---
'FBILLTYPEID': {'FNumber': config.BILL_TYPE_ID},
'FDATE': fmt_date(apply_date),
'FCONTACTUNITTYPE': 'BD_Empinfo',
'FCONTACTUNIT': {'FNumber': staff},
'FRECTUNITTYPE': 'BD_Empinfo',
'FRECTUNIT': {'FNumber': staff},
'FCURRENCYID': {'FNumber': config.CURRENCY_ID},
'FSETTLECUR': {'FNumber': config.CURRENCY_ID},
'FPAYORGID': {'FNumber': org_code},
'FSETTLEORGID': {'FNumber': org_code},
'FAPPLYORGID': {'FNumber': config.APPLY_ORG_ID},
'FBJ_SQR': {'FSTAFFNUMBER': staff}, # 申请人:工号键,必须
'F_VTUY_Base_re5': {'FNumber': dept_code}, # 部门:必须在申请人之后
'F_VTUY_Remarks_qtr': build_remark(row, venue),
# --- 分录 ---
'FPAYAPPLYENTRY': [{
'FCOSTID': {'FNumber': config.COST_ID},
'F_VTUY_Ba': {'FSTAFFNUMBER': staff},
'FSETTLETYPEID': {'FNumber': config.SETTLETYPE_ID},
'FPAYPURPOSEID': {'FNumber': purpose_id},
'FENDDATE': fmt_date(expect),
'FEXPECTPAYDATE': fmt_date(expect),
'FAPPLYAMOUNTFOR': round(float(row['amount']), 2),
'FEACHCCOUNTNAME': bank.get('account_name') or row.get('name', ''),
'FEACHBANKNAME': bank.get('bank', ''),
'F_VTUY_Text_apv1': bank.get('account_no', ''),
}],
}
assert list(model)[-1] == 'FPAYAPPLYENTRY', '分录必须是最后一个字段'
return model
@@ -0,0 +1,145 @@
{
"schema_version": 1,
"id": "xq0012",
"name": "付款申请单自动发起",
"version": "0.1.0",
"description": "读 EHR 预支台账 → 按 ERP 付款申请单口径逐行建单(默认试算不写库),可选提交、自动套打打印;含幂等查重与异常清单;打印完成后钉钉提醒去领取",
"category": "人资",
"icon": "",
"platform": "",
"uses_month": false,
"ui": true,
"requires": {
"sdks": {
"erpsdk": {
"compat": "^0.1"
},
"printkit": {
"compat": "^0.1"
},
"dingtalk_sdk": {
"compat": "^0.1"
}
}
},
"capabilities": [
"xq0012"
],
"permissions": {
"platforms": []
},
"fields": {
"type": "object",
"properties": {
"ledger_dir": {
"type": "string",
"title": "台账目录",
"default": "D:\\资料\\人资\\预支",
"description": "预支台账 xlsx 所在目录;留空=默认目录,自动取最新一个"
},
"ledger_file": {
"type": "string",
"title": "台账文件(可选)",
"default": "",
"description": "指定具体 xlsx 路径;留空=按目录取最新"
},
"apply_date": {
"type": "string",
"title": "申请日期",
"default": "",
"description": "YYYY-MM-DD;留空=今天"
},
"pay_purpose": {
"type": "string",
"title": "付款用途",
"default": "个人借款",
"enum": [
"个人借款",
"工资预提",
"工资发放"
],
"description": "⚠️ 业务待确认:人工模板=个人借款,生产真实单=工资预提"
},
"apply_dept": {
"type": "string",
"title": "申请部门编码",
"default": "BM000477",
"description": "默认 BM000477 人力资源部(生产真实单口径)"
},
"expect_days": {
"type": "number",
"title": "期望付款日=申请日+N 天",
"default": 1
},
"erp_system": {
"type": "string",
"title": "ERP系统",
"default": "新版",
"enum": [
"新版",
"旧版"
]
},
"erp_username": {
"type": "string",
"title": "ERP登录账号",
"default": ""
},
"erp_password": {
"type": "string",
"title": "ERP登录密码",
"default": "",
"format": "password"
},
"dry_run": {
"type": "boolean",
"title": "试算模式(不写 ERP)",
"default": true,
"description": "开启后只组装+查重+输出结果,不建单;验证通过后再关"
},
"submit": {
"type": "boolean",
"title": "建单后自动提交",
"default": false,
"description": "关闭时只建草稿(A),由 HR 在 ERP 确认后手动提交"
},
"print_enabled": {
"type": "boolean",
"title": "建单后套打打印",
"default": false
},
"printer": {
"type": "string",
"title": "打印机",
"default": "人力资源部",
"enum": [
"人力资源部",
"网络信息部"
]
},
"copies": {
"type": "number",
"title": "打印份数",
"default": 1
},
"debug_mode": {
"type": "boolean",
"title": "调试日志",
"default": false
},
"dingtalk_enabled": {
"type": "boolean",
"title": "打印后钉钉提醒领取",
"default": true,
"description": "打印成功后用企业内部应用「工作通知」提醒接收人去领取签字"
},
"dingtalk_users": {
"type": "string",
"title": "钉钉接收人(姓名/工号)",
"default": "陈莲/37004121",
"description": "多个用「、」「,」「;」或换行分隔;重名必须带工号,如 陈莲/37001090;留空=不提醒"
}
},
"required": []
}
}
@@ -0,0 +1 @@
# -*- coding: utf-8 -*-
@@ -0,0 +1,177 @@
# -*- coding: utf-8 -*-
"""钉钉提醒:套打打印完成后,用**企业内部应用工作通知**提醒指定人去领取纸质单。
口径参考 XQ0052(湖畔储值卡导出):不走群机器人、不走 dws 客户端,直接
`topapi/message/corpconversation/asyncsend_v2` 发工作通知给「姓名/工号」指定的接收人。
接收人解析:
- 界面填「姓名/工号」,多个用「、」「,」「;」或换行分隔;
- 先按姓名搜索 userId(钉钉通讯录搜索会命中重名),再用工号(jobnumber)精确挑人;
- 只填姓名且搜到多个 → 报错并列出候选,要求补工号。
推送是附带动作:失败只记日志与返回值,不影响单据与打印结果。
"""
from __future__ import annotations
import re
import time
import requests
from .. import config
TAG = '[钉钉]'
MAX_ATTEMPTS = 3
RETRY_WAIT = 3
_ENTRY_SEP = re.compile(r"[,,、;;\n\r]+")
_CODE_OPEN = re.compile(r"[((//]")
_CODE_CLOSE = re.compile(r"[))]")
# ==================== 文案 ====================
def build_message(printed: list, printer: str, failed: int = 0) -> str:
"""组装提醒正文(纯函数,便于自检)。"""
printer = printer or config.PRINTER_DEFAULT
n = len(printed)
total = sum(float(p.get('amount') or 0) for p in printed)
lines = [f"【付款申请单已打印】请到「{printer}」打印机处领取", '']
for p in printed[:30]:
lines.append(f"{p.get('bill_no', '')} {p.get('name', '')} {float(p.get('amount') or 0):.2f}")
if n > 30:
lines.append(f"… 另有 {n - 30} 张")
lines += ['', f"合计 {total:.2f} 元"]
if failed:
lines.append(f"另 {failed} 张打印失败,PDF 已落盘,请人工补打")
return '\n'.join(lines)
# ==================== 接收人 ====================
def parse_recipients(text) -> list:
"""「张三/37036361」「张三」→ [(姓名, 工号), …]。"""
out = []
for raw in _ENTRY_SEP.split(str(text or "")):
item = raw.strip().strip("\"'“”")
if not item:
continue
name, code = item, ''
hit = _CODE_OPEN.search(item)
if hit:
name = item[:hit.start()].strip()
code = _CODE_CLOSE.sub('', item[hit.end():]).strip()
if name:
out.append((name, code))
return out
def _token(kind: str) -> str:
from dingtalk_sdk import auth
return auth.AccessToken(kind=kind, app_key=config.DINGTALK_APP_KEY,
app_secret=config.DINGTALK_APP_SECRET).get()
def _search_by_name(name: str) -> list:
data = requests.post(
config.DINGTALK_USER_SEARCH_URL,
json={"queryWord": name, "offset": 0, "size": 20, "maxResults": 20},
headers={"x-acs-dingtalk-access-token": _token('v1'), "Content-Type": "application/json"},
timeout=20).json()
ids = []
for item in data.get("list") or []:
uid = item if isinstance(item, str) else (item.get("userid") or item.get("userId") or '')
if uid:
ids.append(str(uid))
return ids
def _user_detail(user_id: str) -> dict:
data = requests.get(config.DINGTALK_USER_GET_URL,
params={"access_token": _token('oapi'), "userid": user_id},
timeout=20).json()
if int(data.get("errcode") or 0) != 0:
raise RuntimeError('钉钉 user/get 失败:%s' % data.get('errmsg'))
return data
def resolve_user_id(name: str, code: str) -> str:
ids = _search_by_name(name)
if not ids:
raise RuntimeError('钉钉通讯录里没搜到「%s」' % name)
cands = [{'uid': u, 'name': str(_user_detail(u).get('name') or ''),
'jobnumber': str(_user_detail(u).get('jobnumber') or '').strip()} for u in ids]
hint = ';'.join('%s(工号 %s / userId %s)' % (c['name'] or name, c['jobnumber'] or '无', c['uid'])
for c in cands)
if code:
for c in cands:
if c['jobnumber'] == code or c['uid'] == code:
return c['uid']
raise RuntimeError('「%s」的候选中没有工号 %s,请核对:%s' % (name, code, hint))
if len(cands) == 1:
return cands[0]['uid']
raise RuntimeError('「%s」在钉钉里有多个人,请带工号重试:%s' % (name, hint))
def _send_work_notice(user_ids: list, content: str) -> None:
data = requests.post(
config.DINGTALK_WORK_SEND_URL,
params={"access_token": _token('oapi')},
json={"agent_id": config.DINGTALK_AGENT_ID,
"userid_list": ','.join(user_ids),
"msg": {"msgtype": "text", "text": {"content": content}}},
timeout=30).json()
if int(data.get("errcode") or 0) != 0:
raise RuntimeError('工作通知失败 errcode=%s errmsg=%s' % (data.get('errcode'), data.get('errmsg')))
def _retry(fn, what):
last = None
for attempt in range(1, MAX_ATTEMPTS + 1):
try:
return fn()
except Exception as e: # noqa: BLE001
last = e
config.log(f'{TAG} {what} 第 {attempt}/{MAX_ATTEMPTS} 次失败:{e}', 'ERROR')
if attempt < MAX_ATTEMPTS:
time.sleep(RETRY_WAIT)
raise last
# ==================== 对外入口 ====================
def notify_printed(printed: list, printer: str, failed: int = 0, *,
users_text: str = '', dry_run: bool = False) -> dict:
"""打印完成提醒。返回 {'ok', 'sent', 'failed'[], 'skipped'/'error'},永不抛异常。"""
if not printed:
return {'ok': False, 'sent': 0, 'failed': [], 'skipped': '没有打印成功的单据'}
recipients = parse_recipients(users_text or config.DINGTALK_USERS_DEFAULT)
if not recipients:
config.log(f'{TAG} 未配置接收人,跳过提醒')
return {'ok': False, 'sent': 0, 'failed': [], 'skipped': '未配置接收人'}
content = build_message(printed, printer, failed)
if dry_run:
config.log(f'{TAG} 试运行不推送 → {recipients}')
return {'ok': True, 'sent': 0, 'failed': [], 'skipped': 'dry_run', 'content': content}
user_ids, failed_list = [], []
for name, code in recipients:
label = f'{name}/{code}' if code else name
try:
uid = _retry(lambda: resolve_user_id(name, code), f'解析接收人「{label}」')
user_ids.append(uid)
config.log(f'{TAG} 接收人「{label}」→ userId={uid}')
except Exception as e: # noqa: BLE001
failed_list.append(f'{label}:{e}')
if not user_ids:
return {'ok': False, 'sent': 0, 'failed': failed_list,
'error': '0/%d 人匹配到钉钉账号' % len(recipients)}
try:
_retry(lambda: _send_work_notice(user_ids, content), '发送工作通知')
except Exception as e: # noqa: BLE001
config.log(f'{TAG} 推送失败(不影响单据):{e}', 'ERROR')
return {'ok': False, 'sent': 0, 'failed': failed_list + [str(e)[:200]], 'error': str(e)[:200]}
config.log(f'{TAG} 已提醒 {len(user_ids)} 人:{printer}')
return {'ok': not failed_list, 'sent': len(user_ids), 'failed': failed_list}
@@ -0,0 +1,295 @@
# -*- coding: utf-8 -*-
"""XQ0012 付款申请单套打(自绘 PDF)。
背景
----
金蝶 WebAPI 没有打印接口(2026-11-14 探测确认),ERP 客户端套打出来的版面
(`C:\\Users\\admin\\Downloads\\套打_付款申请单_2026111414513723.PDF`)已按坐标量过:
A4 竖版、SimSun、11pt 正文 / 15pt 标题、0.75pt 表格线,全部是矢量,可直接复刻。
本模块按同一套坐标重绘这张单,数据从 ERP `view()` 返回单据里取,
输出 PDF 后交 `printkit` 出纸(IPP 直连,不走驱动/队列)。
用法(由 logic/flow 调用,不接命令行参数):
pdf = render_payapply(erp_view_dict, out_path)
"""
from __future__ import annotations
import datetime as _dt
import os
import pymupdf as _mu
# ---------------- 版面常量(单位 pt,均实测自 ERP 套打样例) ----------------
PAGE_W, PAGE_H = 595.28, 841.89 # A4
LINE_W = 0.75
COLOR = (0, 0, 0)
FONT_SIZE, TITLE_SIZE = 11, 15
ASCENT = 0.859375 # SimSun 实测;baseline = y0 + ASCENT*size
LEFT, RIGHT = 6.8, 586.6 # 表格左右外框
# 顶部固定行(y 依次)
Y_TOP = 59.8
Y_R1, Y_R2, Y_R3, Y_R4, Y_R5 = 59.8, 92.1, 124.3, 156.6, 188.9
Y_ACC_TOP = 221.2 # 收款人账户明细表起始
ACC_HEAD_H, ACC_ROW_H = 32.3, 32.5
SIG_H, GAP_H = 32.9, 3.9 # 报销人签名行 / 间隔
FEE_TITLE_H, FEE_HEAD_H, FEE_ROW_H = 32.6, 32.5, 32.6
FONT_FILES = [r"C:\Windows\Fonts\simsun.ttc", r"C:\Windows\Fonts\simhei.ttf"]
def _pick_font() -> str | None:
for p in FONT_FILES:
if os.path.exists(p):
return p
return None
def _ml(v) -> str:
"""多语言文本 → 当前语言值(View 返回 [{'Key':2052,'Value':...}])。"""
if isinstance(v, list):
for it in v:
if isinstance(it, dict) and it.get("Key") == 2052:
return str(it.get("Value") or "")
return ""
if isinstance(v, dict):
return _ml(v.get("Name")) or str(v.get("Value") or "")
return "" if v is None else str(v)
def _name(ref: dict | None) -> str:
return _ml((ref or {}).get("Name"))
def _date_cn(iso: str) -> str:
"""2026-11-14T00:00:00 → 2026/11/14"""
s = str(iso or "")[:10]
return s.replace("-", "/") if s else ""
def _money(v) -> str:
try:
return f"{float(v):.2f}"
except (TypeError, ValueError):
return ""
def from_view(view: dict, bill_no: str | None = None) -> dict:
"""ERP `view()` 单据 → 套打数据(字段缺失时留空,不抛异常)。"""
head = (view or {}).get("Result") or view or {}
entries = head.get("FPAYAPPLYENTRY") or []
total = sum(float((e or {}).get("FAPPLYAMOUNTFOR") or 0) for e in entries)
return {
"bill_no": bill_no or head.get("FBillNo") or "",
"applicant": _name(head.get("FBJ_SQR")),
"applicant_no": (head.get("FBJ_SQR") or {}).get("FStaffNumber") or "",
"dept": _name(head.get("F_VTUY_Base_re5")),
"pay_org": _name(head.get("FPAYORGID")),
"cost_center": "", # 样例为空;需要时按部门全路径补
"apply_amount": _money(total),
"approve_amount": _money(total),
"create_date": _date_cn(head.get("FCREATEDATE") or head.get("FDATE")),
"print_time": _dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"currency": _name(head.get("FCURRENCYID")) or "人民币",
"entries": [{
"cost": _name((e or {}).get("FCOSTID")),
"account_name": _ml((e or {}).get("FEACHCCOUNTNAME")),
"bank": _ml((e or {}).get("FEACHBANKNAME")),
"account_no": str((e or {}).get("F_VTUY_Text_apv1") or ""),
"amount": _money((e or {}).get("FAPPLYAMOUNTFOR")),
"dept": _name((e or {}).get("F_VTUY_Base_re5_entry")) or "",
"remark": "",
} for e in entries],
}
class _Canvas:
"""一页 A4 + SimSun:画线、左对齐/居中文字。"""
def __init__(self, doc, page):
self.doc, self.page = doc, page
self.fontname = "sun"
ff = _pick_font()
if ff:
self.page.insert_font(fontname=self.fontname, fontfile=ff)
self.font = _mu.Font(fontfile=ff)
else: # 兜底:pymupdf 内置 CJK
self.fontname = "china-s"
self.font = _mu.Font("china-s")
def line(self, x0, y0, x1, y1):
self.page.draw_line(_mu.Point(x0, y0), _mu.Point(x1, y1),
color=COLOR, width=LINE_W)
def hline(self, y, x0=LEFT, x1=RIGHT):
self.line(x0, y, x1, y)
def vline(self, x, y0, y1):
self.line(x, y0, x, y1)
def width(self, txt, size):
return self.font.text_length(txt, fontsize=size)
def text(self, x, y0, txt, size=FONT_SIZE):
if not txt:
return
self.page.insert_text((x, y0 + ASCENT * size), str(txt),
fontname=self.fontname, fontsize=size)
def center(self, x0, x1, y0, txt, size=FONT_SIZE):
if not txt:
return
w = self.width(str(txt), size)
self.text((x0 + x1) / 2 - w / 2, y0, txt, size)
def cell(self, x0, x1, y0, txt, size=FONT_SIZE):
"""表格单元格:居中。"""
self.center(x0, x1, y0, txt, size)
def _header(c: _Canvas):
# 标题(页面居中)
c.center(0, PAGE_W, 25.4, "个人工资付款申请", TITLE_SIZE)
# 5 行固定表头网格 + 左右外框
for y in (Y_R1, Y_R2, Y_R3, Y_R4, Y_R5):
c.hline(y)
c.vline(LEFT, Y_R1, Y_ACC_TOP)
c.vline(RIGHT, Y_R1, Y_ACC_TOP)
for x, y0, y1 in (
(83.8, Y_R1, Y_R5), (284.3, Y_R1, Y_R2), (387.6, Y_R1, Y_R5),
(184.3, Y_R2, Y_R3), (284.8, Y_R2, Y_R4), (478.5, Y_R2, Y_R3),
(586.6, Y_R1, Y_R2), (586.6, Y_R3, Y_R4),
(184.3, Y_R4, Y_R5), (478.5, Y_R4, Y_R5),
):
c.vline(x, y0, y1)
def _header_text(c: _Canvas, d: dict):
y = Y_R1
c.text(7.9, y + 9.8, "标题")
c.text(84.9, y + 9.8, f"{d['applicant']}提报的付款申请")
c.text(286.0, y + 9.8, "单据编号")
c.text(388.7, y + 9.8, d["bill_no"])
y = Y_R2
c.text(7.9, y + 9.8, "报销人")
c.text(84.9, y + 9.8, d["applicant"])
c.text(185.4, y + 9.8, "报销人工号")
c.text(286.0, y + 9.8, d["applicant_no"])
c.text(388.7, y + 9.8, "报销人部门")
c.text(479.6, y + 9.8, d["dept"])
y = Y_R3
c.text(7.9, y + 9.9, "费用归属主体")
c.text(84.9, y + 9.9, d["pay_org"])
c.text(286.0, y + 9.9, "费用归属成本中心")
if d.get("cost_center"):
c.text(388.7, y + 9.9, d["cost_center"])
y = Y_R4
c.text(7.9, y + 3.6, "合计申请金")
c.text(84.9, y + 9.8, d["apply_amount"])
c.text(7.9, y + 16.1, "(RMB)")
c.text(185.4, y + 3.6, "合计核准金额")
c.text(286.0, y + 9.8, d["approve_amount"])
c.text(185.4, y + 16.1, "(RMB)")
c.text(388.7, y + 9.8, "创建时间")
c.text(479.6, y + 9.8, d["create_date"])
# 收款人账户明细 段标题
c.text(7.9, 198.7, "收款人账户明细")
def _account_table(c: _Canvas, d: dict, n: int) -> float:
"""收款人账户明细表(N 行),返回表底 y。"""
top = Y_ACC_TOP
db = d["entries"]
c.hline(top)
c.vline(LEFT, top, top + ACC_HEAD_H + n * ACC_ROW_H)
c.vline(RIGHT, top, top + ACC_HEAD_H + n * ACC_ROW_H)
bottom = top + ACC_HEAD_H + n * ACC_ROW_H
# 表头
hy = top
cols = [(LEFT, 83.8), (83.8, 184.3), (184.3, 284.8), (284.8, 478.8), (478.8, RIGHT)]
for x, _ in cols[1:]:
c.vline(x, top, bottom)
for (x0, x1), label in zip(cols, ("支付货币", "收款人账户名", "收款人开户行",
"收款人账号", "收款金额")):
c.cell(x0, x1, hy + 9.8, label)
c.hline(top + ACC_HEAD_H)
for i, e in enumerate(db[:n]):
y0 = top + ACC_HEAD_H + i * ACC_ROW_H
vals = (d["currency"], e["account_name"], e["bank"], e["account_no"], e["amount"])
for (x0, x1), v in zip(cols, vals):
c.cell(x0, x1, y0 + 9.9, v)
if i < n - 1:
c.hline(y0 + ACC_ROW_H)
c.hline(bottom)
return bottom
def _signature(c: _Canvas, d: dict, top: float) -> float:
c.vline(LEFT, top, top + SIG_H)
c.vline(RIGHT, top, top + SIG_H)
c.vline(387.6, top, top + SIG_H)
c.vline(83.8, top, top + SIG_H)
c.text(17.3, top + 10.1, "报销人签名")
c.text(314.2, top + 10.1, "打印日期")
c.text(434.9, top + 10.1, d["print_time"])
bottom = top + SIG_H
c.hline(bottom)
return bottom
def _fee_table(c: _Canvas, d: dict, top: float, n: int) -> float:
"""费用分摊明细表(N 行 + 合计行)。"""
c.vline(LEFT, top, top + FEE_TITLE_H + FEE_HEAD_H + n * FEE_ROW_H + FEE_ROW_H)
c.vline(RIGHT, top, top + FEE_TITLE_H + FEE_HEAD_H + n * FEE_ROW_H + FEE_ROW_H)
c.text(7.9, top + 10.0, "费用分摊明细")
head_top = top + FEE_TITLE_H
c.hline(head_top)
cols = [(LEFT, 184.3), (184.3, 284.8), (284.8, 387.6), (387.6, RIGHT)]
for x, _ in cols[1:]:
c.vline(x, head_top, head_top + FEE_HEAD_H + n * FEE_ROW_H + FEE_ROW_H)
for (x0, x1), label in zip(cols, ("费用项目", "分摊部门", "分摊金额", "备注")):
c.cell(x0, x1, head_top + 9.9, label)
c.hline(head_top + FEE_HEAD_H)
total = 0.0
for i, e in enumerate(d["entries"][:n]):
y0 = head_top + FEE_HEAD_H + i * FEE_ROW_H
vals = (e["cost"], e["dept"], e["amount"], e["remark"])
for (x0, x1), v in zip(cols, vals):
c.cell(x0, x1, y0 + 10.0, v)
try:
total += float(e["amount"])
except ValueError:
pass
c.hline(y0 + FEE_ROW_H)
# 合计行
y0 = head_top + FEE_HEAD_H + n * FEE_ROW_H
c.text(57.1, y0 + 10.0, "分摊表合计金额")
c.cell(284.8, 387.6, y0 + 10.0, _money(total))
bottom = y0 + FEE_ROW_H
c.hline(bottom)
return bottom
def render_payapply(data: dict, out_path: str) -> str:
"""按套打模板画一张付款申请单 → PDF 路径。"""
n = max(1, len(data.get("entries") or []))
doc = _mu.open()
page = doc.new_page(width=PAGE_W, height=PAGE_H)
c = _Canvas(doc, page)
_header(c)
_header_text(c, data)
bottom = _account_table(c, data, n)
bottom = _signature(c, data, bottom)
bottom += GAP_H # 3.9pt 间隔
c.hline(bottom) # 费用分摊段顶线
bottom = _fee_table(c, data, bottom, n)
doc.set_metadata({"title": f"付款申请单 {data.get('bill_no', '')}",
"creator": "37duAutomation/XQ0012"})
os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
doc.save(out_path, deflate=True)
doc.close()
return out_path
@@ -0,0 +1,28 @@
# -*- coding: utf-8 -*-
"""打印层:套打 PDF → printkit 网络打印机出纸。
printkit 走 IPP over TLS,不装驱动、不弹框、不走 Windows 队列;
l6570(人力资源部)支持双面,l565(网络信息部)仅单面(printkit 会自动降级)。
"""
from __future__ import annotations
from printkit import Printer
from .. import config
TAG = '[打印]'
def print_pdf(pdf_path: str, printer: str = '', copies: int = 1, dry_run: bool = False) -> list:
"""打印 PDF,返回每次结果(copies>1 时逐份提交)。"""
name = printer or config.PRINTER_DEFAULT
results = []
for i in range(max(1, int(copies or 1))):
try:
r = Printer(name).print(pdf_path, dry_run=dry_run)
results.append({'copies': i + 1, 'ok': bool(r.get('ok')), 'pages': len(r.get('pages') or [])})
config.log(f'{TAG} 第 {i + 1} 份 → {name} ok={bool(r.get("ok"))}')
except Exception as e: # noqa: BLE001
config.log(f'{TAG} 第 {i + 1} 份失败({name}):{e}', 'ERROR')
results.append({'copies': i + 1, 'ok': False, 'error': str(e)[:200]})
return results
@@ -0,0 +1,3 @@
requests>=2.25
openpyxl>=3.0
pymupdf>=1.24
@@ -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>
@@ -0,0 +1,22 @@
{
"name": "xq0012-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,255 @@
<template>
<div class="page">
<div class="toolbar">
<span class="spacer" />
<span class="saved" :class="{ 'is-idle': !lastSavedAt }">
<i />{{ lastSavedAt ? '已保存 ' + lastSavedAt : '尚未保存' }}
</span>
<el-select v-model="schemeSel" class="scheme-sel" size="small" :disabled="running"
placeholder="当前配置(自动保存)" @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 v-if="needLogin" class="notice is-warn">
<span class="n-ico">!</span>
<span>未登录:请先在壳子(工作台)登录统一账户,再刷新本界面</span>
</div>
<div v-else-if="notice" class="notice" :class="'is-' + notice.type">
<span class="n-ico">{{ notice.type === 'ok' ? '✓' : (notice.type === 'error' ? '✕' : '·') }}</span>
<span>{{ notice.text }}</span>
</div>
<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="sec-body">
<el-form label-position="top">
<el-form-item label="台账目录(自动取最新)">
<div class="dir-ctrl">
<el-input v-model="form.ledger_dir" class="dir-input" :disabled="running" clearable
placeholder="D:\资料\人资\预支" />
<el-button class="dir-btn" :disabled="running || picking" :loading="picking"
@click="pickDir">选择</el-button>
</div>
</el-form-item>
<el-form-item label="台账文件(可选,留空=按目录取最新)">
<el-input v-model="form.ledger_file" :disabled="running" clearable
placeholder="D:\资料\人资\预支\xxx.xlsx" />
</el-form-item>
<div class="tip">
读 sheet <b>预支报酬台账</b>:工号非空、金额 &gt; 0、不含 #N/A 的行才算有效;
组织名→编码取同工作簿 <b>辅助2-ERP组织机构</b> 表。
</div>
</el-form>
</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>
<div class="sec-body">
<el-form label-position="top">
<div class="inline-row">
<el-form-item label="申请日期" class="date-item">
<el-date-picker v-model="form.apply_date" type="date" value-format="YYYY-MM-DD"
placeholder="留空=今天" :disabled="running" style="width: 100%" />
</el-form-item>
<el-form-item label="付款用途">
<el-select v-model="form.pay_purpose" :disabled="running" style="width: 100%">
<el-option label="个人借款 SFKYT11" value="个人借款" />
<el-option label="工资预提 SFKYT45" value="工资预提" />
<el-option label="工资发放 SFKYT19" value="工资发放" />
</el-select>
</el-form-item>
<el-form-item label="期望付款日=申请日+N 天">
<el-input-number v-model="form.expect_days" :min="0" :max="60" :disabled="running"
style="width: 100%" />
</el-form-item>
</div>
<el-form-item label="申请部门编码">
<el-input v-model="form.apply_dept" :disabled="running" placeholder="BM000477" />
</el-form-item>
<div class="tip">
付款用途业务口径未定:人工导入模板是 <b>个人借款</b>,生产真实单是 <b>工资预提</b>,按当月批次选。
申请部门默认 <b>BM000477 人力资源部</b>(生产真实单口径)。
</div>
</el-form>
</div>
</section>
<section class="sec">
<div class="sec-head">
<span class="sec-badge">03</span>
<span class="sec-name">ERP 与执行</span>
<span class="sec-line" />
</div>
<div class="sec-body">
<el-form label-position="top">
<div class="inline-row">
<el-form-item label="ERP系统">
<el-select v-model="form.erp_system" :disabled="running" style="width: 100%">
<el-option label="新版" value="新版" />
<el-option label="旧版" value="旧版" />
</el-select>
</el-form-item>
<el-form-item label="ERP账号">
<el-input v-model="form.erp_username" :disabled="running" placeholder="ERP 登录账号" />
</el-form-item>
<el-form-item label="ERP密码">
<el-input v-model="form.erp_password" type="password" show-password :disabled="running"
placeholder="仅存本机" />
</el-form-item>
</div>
<div class="inline-row">
<el-form-item class="switch-item" label="试算模式(不写 ERP)">
<el-switch v-model="form.dry_run" :disabled="running" />
</el-form-item>
<el-form-item class="switch-item" label="建单后自动提交">
<el-switch v-model="form.submit" :disabled="running" />
</el-form-item>
<el-form-item class="switch-item" label="建单后套打打印">
<el-switch v-model="form.print_enabled" :disabled="running" />
</el-form-item>
<el-form-item class="switch-item" label="调试日志">
<el-switch v-model="form.debug_mode" :disabled="running" />
</el-form-item>
</div>
<div class="inline-row">
<el-form-item label="打印机">
<el-select v-model="form.printer" :disabled="running" style="width: 100%">
<el-option label="人力资源部(双面)" value="人力资源部" />
<el-option label="网络信息部(单面)" value="网络信息部" />
</el-select>
</el-form-item>
<el-form-item label="打印份数">
<el-input-number v-model="form.copies" :min="1" :max="5" :disabled="running"
style="width: 100%" />
</el-form-item>
</div>
<div class="inline-row">
<el-form-item class="switch-item" label="打印后钉钉提醒领取">
<el-switch v-model="form.dingtalk_enabled" :disabled="running" />
</el-form-item>
<el-form-item class="user-item" label="钉钉接收人(姓名/工号)">
<el-input v-model="form.dingtalk_users" :disabled="running || !form.dingtalk_enabled"
clearable placeholder="陈莲/37001090;多个用「、」分隔" />
</el-form-item>
</div>
<div class="tip">
<b>试算模式</b>只组装 + 查重 + 输出结果,不写 ERP;关掉试算才会建单。
「自动提交」关闭时只建草稿(A 状态),由 HR 在 ERP 里核对后再提交(提交后进入审批流)。
打印走 printkit 直连网络打印机,不弹窗。
</div>
</el-form>
</div>
</section>
<details class="help">
<summary><span>单据口径速查</span><span class="h-arrow">▾</span></summary>
<div class="help-body">
<div class="hb-line"><b>单据</b>:CN_PAYAPPLY 付款申请单,单据类型 FKSQ006.0YS 个人工资付款申请。</div>
<div class="hb-line"><b>单号</b>:系统生成 FKSQ+年月+流水,不要传。</div>
<div class="hb-line"><b>申请人</b>:FBJ_SQR 传工号(FSTAFFNUMBER);标准申请人=登录用户,不用传。</div>
<div class="hb-line"><b>顺序</b>:Model 里「部门」必须排在「申请人」之后,且分录最后(否则报申请人/部门必录)。</div>
<div class="hb-line"><b>保存</b>:IsAutoAdjustField 必须 false。</div>
<div class="hb-line"><b>分录</b>:费用项目 0111001 预支工资 / 结算方式 JSFS04_SYS 转账 / 币别 PRE001。</div>
<div class="hb-line"><b>套打</b>:自绘 PDF(A4、SimSun、与 ERP 套打样例一致),不走 ERP 打印接口。</div>
</div>
</details>
<div class="actions">
<el-button type="primary" class="btn-run" :loading="running" @click="run">
{{ running ? '执行中 ' + progress + '%' : (form.dry_run ? '开始试算' : '一键执行') }}
</el-button>
<el-button v-if="running" type="danger" plain :loading="stopping"
@click="forceStop">强制停止</el-button>
<span class="spacer" />
<el-button :disabled="running" @click="restoreLastFields">恢复上次参数</el-button>
<el-button :disabled="running" @click="saveNow(true)">保存配置</el-button>
<el-button text :disabled="running" @click="resetDefaults">恢复默认</el-button>
</div>
<div v-if="running" class="runline">
<span class="pulse" />
<span>正在执行,日志与进度实时显示在工作台下方「运行日志」区</span>
<span class="pct">{{ progress }}%</span>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue'
import { usePluginUI } from './usePluginUI'
import { ElMessage } from 'element-plus'
// DEFAULTS 与 plugin.json.fields 的 default 逐项一致
const DEFAULTS = () => ({
ledger_dir: 'D:\\资料\\人资\\预支',
ledger_file: '',
apply_date: '',
pay_purpose: '个人借款',
apply_dept: 'BM000477',
expect_days: 1,
erp_system: '新版',
erp_username: '',
erp_password: '',
dry_run: true,
submit: false,
print_enabled: false,
printer: '人力资源部',
copies: 1,
dingtalk_enabled: true,
dingtalk_users: '陈莲/37004121',
debug_mode: false,
})
const {
form, needLogin, notice, lastSavedAt, running, progress, stopping,
saveNow, resetDefaults, restoreLastFields,
schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
run, forceStop,
} = usePluginUI({
defaults: DEFAULTS,
validate() {
if (form.dry_run) return true
if (!form.erp_username || !form.erp_password) {
ElMessage.error('关闭试算模式必须填 ERP 账号密码')
return false
}
if (form.submit) {
ElMessage.warning('自动提交会把单据送进审批流,请确认台账与口径无误')
}
return true
},
})
const picking = ref(false)
async function pickDir() {
picking.value = true
try {
const r = await fetch('/api/dialog/directory', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: '选择预支台账目录', current: form.ledger_dir || '' }),
})
const d = await r.json().catch(() => ({}))
if (!r.ok) throw new Error(d.detail || d.error || ('HTTP ' + r.status))
if (d.path) form.ledger_dir = d.path
} catch (e) {
ElMessage.warning('打开文件夹选择失败:' + e.message)
} finally {
picking.value = false
}
}
</script>
@@ -0,0 +1,2 @@
// 插件身份声明(API 实现收敛在 usePluginUI.js 公共 kit)
export const PLUGIN_ID = 'xq0012'
@@ -0,0 +1,9 @@
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
// 注意顺序:style.css 必须在 element-plus 之后引入,才能覆盖 --el-* 变量映射到壳子 token
import './style.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,443 @@
/* ============================================================
插件 UI 基础样式(规范 v3 · 对齐壳子「白底面板 + 描边卡」)
- token 与壳子 frontend/src/style.css 同源(权威源 design-app/styles.css)
- Element Plus 变量映射到壳子 token
- 版式类:page / toolbar / notice / sec / grid / tip / actions / badge / table
规则:插件内只用 var(--xxx),不写字面色值;左右内边距由壳子提供,不要重复加
============================================================ */
:root {
/* 底色与卡面 */
--canvas: #F2F4F8;
--surface: #FFFFFF;
--field: #F5F6FA;
--subtle: #F7F8FC;
/* 描边 */
--line: #E8EAF1;
--line-soft: #F0F2F7;
--line-btn: #E3E6EF;
/* 文字五阶 */
--t1: #12141B;
--t2: #3C4250;
--t3: #6E7686;
--t4: #A3AAB8;
--t5: #C6CBD6;
/* 主色(靛蓝) */
--brand: #4F5AE8;
--brand-ink: #3D47D4;
--brand-soft: #EEF0FE;
--brand-track: #DDE1F8;
--brand-hover: #4550E0;
/* 语义色 */
--good: #0E9F76; --good-ink: #0B8A66; --good-soft: #EBF7F2; --good-line: #D3EDE3;
--warn: #D98218; --warn-ink: #B4700F; --warn-soft: #FDF3E4; --warn-line: rgba(217, 130, 24, .28);
--danger: #E5484D; --danger-ink: #CC3B40; --danger-soft: #FDEDED; --danger-line: #F6D7D8;
/* 圆角 */
--r-row: 8px;
--r-field: 9px;
--r-btn: 10px;
--r-sub: 12px;
--r-card: 14px;
--r-pill: 999px;
/* 阴影(插件内基本不用,保持与壳子同值) */
--sh-card: 0 2px 8px rgba(18, 20, 31, .05);
--sh-float: 0 8px 24px rgba(18, 20, 31, .10);
--sh-brand: 0 4px 12px rgba(79, 89, 232, .28);
--sh-brand-sm: 0 2px 8px rgba(79, 89, 232, .24);
/* 字体 */
--f-cn: "PingFang SC", "HarmonyOS Sans SC", "Microsoft YaHei", "Noto Sans SC", system-ui, -apple-system, sans-serif;
--f-num: "Inter", "SF Pro Display", -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--f-mono: "JetBrains Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
/* 间距 */
--space-1: 4px;
--space-1-5: 6px;
--space-2: 8px;
--space-2-5: 10px;
--space-3: 12px;
--space-4: 16px;
--space-5: 20px;
--space-6: 28px;
--dur: .15s;
--ease: cubic-bezier(.22, 1, .36, 1);
}
/* ---------- Element Plus → 壳子 token ---------- */
:root {
--el-color-primary: var(--brand);
--el-color-primary-light-3: #7A83EE;
--el-color-primary-light-5: #A6ACF4;
--el-color-primary-light-7: #C9CDF9;
--el-color-primary-light-8: #DDE0FB;
--el-color-primary-light-9: var(--brand-soft);
--el-color-primary-dark-2: var(--brand-ink);
--el-color-success: var(--good);
--el-color-success-light-9: var(--good-soft);
--el-color-warning: var(--warn);
--el-color-warning-light-9: var(--warn-soft);
--el-color-danger: var(--danger);
--el-color-danger-light-9: var(--danger-soft);
--el-color-error: var(--danger);
--el-text-color-primary: var(--t1);
--el-text-color-regular: var(--t2);
--el-text-color-secondary: var(--t3);
--el-text-color-placeholder: var(--t4);
--el-border-color: var(--line);
--el-border-color-light: var(--line);
--el-border-color-lighter: var(--line-soft);
--el-border-color-extra-light: var(--line-soft);
--el-fill-color-blank: var(--surface);
--el-fill-color-light: var(--field);
--el-bg-color: var(--surface);
--el-border-radius-base: var(--r-field);
--el-border-radius-small: var(--r-field);
--el-font-family: var(--f-cn);
--el-font-size-base: 12.5px;
--el-box-shadow-light: var(--sh-card);
}
/* ---------- 基础重置 ---------- */
* { box-sizing: border-box; }
html, body {
margin: 0;
padding: 0;
background: var(--surface);
color: var(--t1);
font-family: var(--f-cn);
font-size: 12.5px;
line-height: 1.5;
-webkit-font-smoothing: antialiased;
}
#app { padding: 0; }
/* ---------- 页面:只排垂直节奏(左右 24px 由壳子给) ---------- */
.page {
width: 100%;
display: flex;
flex-direction: column;
gap: var(--space-4);
padding: 2px 0 20px;
}
/* ---------- 工具条:方案下拉 + 存为方案 + 删除 + 已保存胶囊 ---------- */
.toolbar {
display: flex;
align-items: center;
gap: var(--space-2);
flex-wrap: wrap;
min-height: 32px;
}
.toolbar .spacer { flex: 1; }
.scheme-sel { width: 200px; }
.saved {
display: inline-flex;
align-items: center;
gap: 6px;
height: 22px;
padding: 0 9px;
border-radius: var(--r-pill);
background: var(--good-soft);
border: 1px solid var(--good-line);
color: var(--good-ink);
font: 500 11px/1 var(--f-cn);
white-space: nowrap;
}
.saved i { width: 5px; height: 5px; border-radius: 50%; background: var(--good); }
.saved.is-idle { background: var(--field); border-color: var(--line); color: var(--t4); }
.saved.is-idle i { background: var(--t5); }
/* ---------- 提示条(替代顶部大横幅) ---------- */
.notice {
display: flex;
align-items: flex-start;
gap: var(--space-2);
padding: 9px 12px;
border-radius: var(--r-sub);
border: 1px solid var(--line);
background: var(--subtle);
font: 400 12px/18px var(--f-cn);
color: var(--t2);
}
.notice .n-ico { flex: 0 0 auto; font-weight: 700; }
.notice.is-warn { background: var(--warn-soft); border-color: var(--warn-line); color: var(--warn-ink); }
.notice.is-error { background: var(--danger-soft); border-color: var(--danger-line); color: var(--danger-ink); }
.notice.is-ok { background: var(--good-soft); border-color: var(--good-line); color: var(--good-ink); }
/* ---------- 分区卡:与壳子列表卡/表格卡同一套 ---------- */
.sec {
background: var(--surface);
border: 1px solid var(--line);
border-radius: var(--r-sub);
overflow: hidden;
}
.sec-head {
display: flex;
align-items: center;
gap: var(--space-2);
padding: 10px 14px;
background: var(--subtle);
border-bottom: 1px solid var(--line);
}
.sec-badge {
width: 20px;
height: 20px;
border-radius: 6px;
display: inline-grid;
place-items: center;
font: 600 10.5px/1 var(--f-num);
color: var(--brand-ink);
background: var(--brand-soft);
flex-shrink: 0;
}
.sec-name { font: 600 13px/18px var(--f-cn); color: var(--t1); white-space: nowrap; }
.sec-line { flex: 1; height: 1px; background: var(--line-soft); }
.sec-body { padding: 14px 14px 6px; }
/* ---------- 栅格与表单 ---------- */
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 0 16px;
}
.grid-switch { grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); }
/* 日期行紧跟在开关行后,补一点呼吸 */
.grid-date { margin-top: 4px; }
.grid .el-form-item { margin-bottom: 12px; }
.grid .el-form-item__label {
padding-bottom: 6px !important;
font-weight: 500;
color: var(--t2);
}
.grid .el-input,
.grid .el-select,
.grid .el-date-editor,
.grid .el-input-number { width: 100% !important; }
/* 输入框 + 选择按钮同一行 */
.dir-ctrl { display: flex; gap: 8px; align-items: center; width: 100%; }
.dir-ctrl .dir-input { flex: 1 1 auto; min-width: 0; }
.dir-ctrl .dir-btn { flex: 0 0 auto; }
/* 日期段 + 开关同一行 */
.inline-row { display: flex; gap: 16px; align-items: flex-start; }
.inline-row .date-item { flex: 1 1 auto; min-width: 0; margin-bottom: 0; }
.inline-row .switch-item { flex: 0 0 auto; margin-bottom: 0; }
.inline-row .el-form-item__content { width: auto; }
.inline-row .date-item .el-form-item__content { width: 100%; }
/* ---------- 说明文字 ---------- */
.tip {
margin-top: var(--space-2);
font: 400 11.5px/1.65 var(--f-cn);
color: var(--t3);
}
.tip b { color: var(--t2); font-weight: 600; }
/* ---------- 执行摘要(操作区上方一行低调说明) ---------- */
.plan { display: flex; align-items: baseline; gap: var(--space-2); font-size: 11.5px; line-height: 1.6; color: var(--t3); }
.plan .p-tag { flex: 0 0 auto; font-weight: 600; color: var(--brand-ink); }
.plan .p-text { min-width: 0; }
.plan.is-empty .p-text { color: var(--warn); }
/* ---------- 操作区 ---------- */
.actions {
display: flex;
align-items: center;
gap: var(--space-2);
flex-wrap: wrap;
padding-top: 14px;
border-top: 1px solid var(--line-soft);
}
.actions .spacer { flex: 1; }
.btn-run {
min-width: 150px;
height: 34px;
border: none;
border-radius: var(--r-btn);
background: var(--brand);
color: #fff;
font: 600 12.5px/18px var(--f-cn);
letter-spacing: 1px;
box-shadow: var(--sh-brand);
transition: background var(--dur), box-shadow var(--dur), transform .06s;
}
.btn-run:hover { background: var(--brand-hover); }
.btn-run:active { transform: translateY(1px); box-shadow: var(--sh-brand-sm); }
.btn-run.is-loading { pointer-events: none; }
/* ---------- 状态胶囊(与壳子表格状态列同款) ---------- */
.badge {
display: inline-flex;
align-items: center;
gap: 5px;
height: 22px;
padding: 0 9px;
border: 1px solid transparent;
border-radius: 6px;
font: 500 11px/1 var(--f-cn);
white-space: nowrap;
}
.badge i { width: 5px; height: 5px; border-radius: 50%; flex-shrink: 0; }
.badge.ok { color: var(--good-ink); background: var(--good-soft); border-color: var(--good-line); }
.badge.ok i { background: var(--good); }
.badge.warn { color: var(--warn-ink); background: var(--warn-soft); border-color: var(--warn-line); }
.badge.warn i { background: var(--warn); }
.badge.bad { color: var(--danger-ink); background: var(--danger-soft); border-color: var(--danger-line); }
.badge.bad i { background: var(--danger); }
.badge.idle { color: var(--t3); background: var(--field); border-color: var(--line); }
.badge.idle i { background: var(--t5); }
/* ---------- 表格(插件内需要列表时用;与壳子表格同口径) ---------- */
.table-card {
background: var(--surface);
border: 1px solid var(--line);
border-radius: var(--r-sub);
overflow: hidden;
}
.table-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-3);
padding: 12px 16px;
background: var(--subtle);
border-bottom: 1px solid var(--line);
font: 600 13.5px/20px var(--f-cn);
color: var(--t1);
}
.table { width: 100%; border-collapse: collapse; table-layout: fixed; }
.table th {
padding: 10px 16px;
text-align: center;
font: 500 11px/16px var(--f-cn);
color: var(--t3);
background: var(--surface);
border-bottom: 1px solid var(--line);
}
.table td {
padding: 10px 16px;
text-align: center;
border-bottom: 1px solid var(--line-soft);
font: 400 12px/18px var(--f-cn);
color: var(--t2);
}
.table tr:last-child td { border-bottom: 0; }
.table tbody tr { transition: background var(--dur); }
.table tbody tr:hover { background: var(--field); }
.table td.is-name { text-align: left; font-weight: 600; color: var(--t1); }
.table th.is-name { text-align: left; }
/* ---------- 运行态一行文字(进度由壳子 RunIndicator 展示) ---------- */
.runline { display: flex; align-items: center; gap: var(--space-2); font-size: 12px; color: var(--t3); }
.runline .pct { font: 600 12px/1 var(--f-num); color: var(--brand-ink); font-variant-numeric: tabular-nums; }
.pulse { width: 7px; height: 7px; border-radius: 50%; background: var(--brand); animation: pulse 1.4s ease-out infinite; }
@keyframes pulse {
0% { box-shadow: 0 0 0 0 var(--brand-soft); }
70% { box-shadow: 0 0 0 7px transparent; }
100% { box-shadow: 0 0 0 0 transparent; }
}
/* ============================================================
v3.1 扩展:步骤卡 / 行式设置项 / 折叠说明
- 适用于「互斥步骤」「开关+联动下拉」「大段流程说明」
- 仍然只用 token,不写字面色值
============================================================ */
/* ---------- 步骤卡(互斥单选,≤4 项) ---------- */
.step-cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: var(--space-2-5);
}
.step-card {
position: relative;
display: flex;
flex-direction: column;
gap: 3px;
padding: 11px 32px 11px 13px;
background: var(--surface);
border: 1px solid var(--line);
border-radius: var(--r-sub);
cursor: pointer;
transition: border-color var(--dur), background var(--dur), box-shadow var(--dur);
}
.step-card:hover { border-color: var(--brand-track); background: var(--subtle); }
.step-card.on {
border-color: var(--brand);
background: var(--brand-soft);
box-shadow: inset 0 0 0 1px var(--brand-soft);
}
.step-card .sc-title { font: 600 13px/18px var(--f-cn); color: var(--t1); }
.step-card.on .sc-title { color: var(--brand-ink); }
.step-card .sc-desc { font: 400 11.5px/1.6 var(--f-cn); color: var(--t3); }
.step-card .sc-check {
position: absolute; top: 10px; right: 10px;
width: 16px; height: 16px; color: var(--brand);
}
.step-cards.is-disabled .step-card { opacity: .55; pointer-events: none; }
.sr-only {
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0;
}
/* ---------- 行式设置项(标题+说明在左,控件在右) ---------- */
.rows {
display: flex; flex-direction: column; gap: var(--space-2);
padding: var(--space-2);
background: var(--subtle);
border: 1px solid var(--line);
border-radius: var(--r-sub);
}
.row {
display: flex; align-items: center; justify-content: space-between;
gap: var(--space-4);
padding: 9px 12px;
background: var(--surface);
border: 1px solid var(--line-soft);
border-radius: var(--r-field);
}
.row .r-main { min-width: 0; }
.row .r-title { font: 500 12.5px/18px var(--f-cn); color: var(--t1); }
.row .r-desc { margin-top: 1px; font: 400 11.5px/1.6 var(--f-cn); color: var(--t3); }
.row .r-ctrl { flex: 0 0 auto; }
.row.is-hidden { display: none; }
/* ---------- 折叠说明(流程说明气泡卡片) ---------- */
.help {
background: var(--surface);
border: 1px solid var(--line);
border-radius: var(--r-sub);
overflow: hidden;
}
.help > summary {
display: flex; align-items: center; justify-content: space-between;
gap: var(--space-2); padding: 10px 14px;
background: var(--subtle);
font: 600 12.5px/18px var(--f-cn); color: var(--t2);
cursor: pointer; list-style: none;
}
.help > summary::-webkit-details-marker { display: none; }
.help[open] > summary { border-bottom: 1px solid var(--line); }
.help .h-arrow { color: var(--t4); transition: transform var(--dur); font-size: 11px; }
.help[open] .h-arrow { transform: rotate(180deg); }
.help-body {
padding: 12px 14px;
font: 400 12px/1.8 var(--f-cn); color: var(--t3);
}
.help-body b { color: var(--t2); font-weight: 600; }
.help-body .hb-line + .hb-line { margin-top: 6px; }
@@ -0,0 +1,356 @@
// 插件 UI 公共 kit v2(vendored 进各插件 ui-src,构建期内联,运行零外部依赖)。
//
// 与 v1 的差异(适配当前壳子):
// 1. 新增 restoreLastFields():调 /api/plugins/<id>/last-fields 恢复上次执行参数(password 不落盘);
// 2. 顶部大横幅 → 内联 notice:执行结果横幅、插件名/版本、运行 Indicator 已由壳子
// (PageHead + 结果横幅 + RunIndicator)统一渲染,插件内不再重复;
// 3. startRun 的 409 单独识别:壳子在 iframe fetch 上包了「入队确认」,用户取消会返回 409,
// 不能再当成普通失败提示。
//
// 保留能力:本机当前配置(加载/防抖自动保存/恢复默认)、多配置方案(供定时任务按 config_id 引用)、
// 执行状态机(执行/强停/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 Object.assign(new Error(msg), { code: res.status, status: res.status })
}
return res.json()
}
// ---- 后端 API(同源,统一账户会话 cookie 自动携带)----
const loadConfig = () => j(`/api/plugin-config/${PLUGIN_ID}`)
const saveConfig = (data) => j(`/api/plugin-config/${PLUGIN_ID}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
const loadLastFields = () => j(`/api/plugins/${PLUGIN_ID}/last-fields`)
const listSchemes = () => j(`/api/plugin-configs?plugin_id=${encodeURIComponent(PLUGIN_ID)}`)
const saveScheme = (name, fields) => j('/api/plugin-configs', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ plugin_id: PLUGIN_ID, name, fields }),
})
const deleteScheme = (cfgId) =>
j(`/api/plugin-configs/${encodeURIComponent(PLUGIN_ID)}/${encodeURIComponent(cfgId)}`, { method: 'DELETE' })
const startRun = (fields) => j('/api/runs', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
})
const getRun = (runId) => j(`/api/runs/${runId}`)
const stopRun = (runId) => 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))
// 本机配置的「上次保存时间」:后端只存字段、不返回时间戳,
// 这里用 localStorage 记住,刷新后仍能显示(取不到时静默)。
const SAVED_AT_KEY = `plugin:${PLUGIN_ID}:lastSavedAt`
function readSavedAt() {
try { return localStorage.getItem(SAVED_AT_KEY) || '' } catch (_) { return '' }
}
function writeSavedAt(v) {
try { localStorage.setItem(SAVED_AT_KEY, v) } catch (_) { /* 存储不可用时只保留内存态 */ }
}
// 保存字段合并规则:标量空值(''/null/undefined)不覆盖;数组照原样应用
// (空数组可能是有意配置,如「留空=不筛选」)
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
})
}
export function usePluginUI(opts = {}) {
const { defaults, validate, buildPayload } = opts
const form = reactive(defaults ? defaults() : {})
const loaded = ref(false)
const needLogin = ref(false)
const notice = ref(null) // { type: 'warn'|'error'|'ok', text }
const lastSavedAt = ref(readSavedAt())
const running = ref(false)
const progress = ref(0)
const stopping = ref(false)
let ws = null
let runId = ''
let pollTimer = null
let saveTimer = null
// 传空 type 视为清除横幅(不能留 {type:null},否则会渲染成只有"!"的空横幅)
const notify = (type, text) => { notice.value = type ? { type, text } : null }
// ---------- 当前配置:加载 / 防抖自动保存 ----------
// 登录由壳子统一处理(打开界面时会话必然就绪),这里读取失败一律静默回退默认值,
// 不弹任何提示;真到执行时才发现会话问题,再明确告知。
onMounted(async () => {
try {
const saved = await loadConfig()
mergeSaved(form, saved)
} catch (e) {
if (e.code === 401) needLogin.value = true
}
loaded.value = true
refreshSchemes()
})
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 })
writeSavedAt(lastSavedAt.value)
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) : {})
notify(null)
ElMessage.info('已恢复默认配置')
}
// 恢复上次执行参数(壳子记录,password 类字段不落盘)
async function restoreLastFields() {
try {
const r = await loadLastFields()
const fields = r.fields || {}
if (!Object.keys(fields).length) {
ElMessage.info('暂无上次执行参数')
return
}
mergeSaved(form, fields)
ElMessage.success('已恢复上次执行参数' + (r.at ? `(${r.at})` : ''))
} catch (e) {
if (e.code === 401) needLogin.value = true
else ElMessage.error('恢复上次参数失败:' + e.message)
}
}
// ---------- 多配置方案 ----------
const schemes = ref([])
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)
}
}
// ---------- 执行 ----------
// action: download(只下载)/ reconcile(只核对);不传则用 payload 里的 action
async function run(action) {
if (running.value) return
if (needLogin.value) {
try {
await loadConfig()
needLogin.value = false
} catch (_) {
notify('error', '登录态未就绪,请稍后重试')
return
}
}
if (validate && !validate(action)) return
await saveNow(false)
notify(null)
running.value = true
progress.value = 0
try {
const payload = buildPayload ? buildPayload(form) : clone(form)
if (action) payload.action = action
const r = await startRun(payload)
runId = r.run_id
connect()
startPolling()
} catch (e) {
running.value = false
stopPolling()
if (e.code === 401) {
needLogin.value = true
notify('error', '登录态未就绪,本次没有启动,请稍后重试')
} else if (e.code === 409) {
// 壳子「入队确认」里用户点了取消
notify('warn', '已取消加入执行队列,本次没有启动')
} else {
notify('error', '启动执行失败:' + 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
}
}
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() : (ev.status === 'cancelled' ? cancelled(ev.error) : 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 === 'cancelled') cancelled(r.error)
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
// 结果横幅由壳子统一展示,插件内仅在需要时给一句简短结论
if (summary) notify('ok', summary)
}
// 用户主动停止 / 排队取消 / 排队超时:不算失败,给中性的「已取消」提示
function cancelled(err) {
stopPolling()
running.value = false
notify('warn', '任务已取消:' + (err || '用户已停止'))
}
function failed(err) {
stopPolling()
running.value = false
notify('error', '执行失败:' + err)
}
return {
form, loaded, needLogin, notice, lastSavedAt, running, progress, stopping,
saveNow, resetDefaults, restoreLastFields,
schemes, schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
run, forceStop,
}
}
@@ -0,0 +1,21 @@
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// 插件 UI 由壳子后端托管在 /pui/xq0036/ 下,
// 构建产物直接输出到插件包 ui/ 目录(随插件 zip 发布,壳子零改动)。
// dev 模式经代理访问本机壳子后端,便于联调。
export default defineConfig({
plugins: [vue()],
base: '/pui/xq0012/',
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
@@ -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/xq0012/assets/index-Drjevmlm.js"></script>
<link rel="stylesheet" crossorigin href="/pui/xq0012/assets/index-Dy0-BAQJ.css">
</head>
<body>
<div id="app"></div>␍
</body>
</html>