Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c200dab57 | ||
|
|
e32e13c1f1 | ||
|
|
4fa716a0e2 | ||
|
|
eeeaed1e14 | ||
|
|
4941e8b6c0 | ||
|
|
6d214aa4cb | ||
|
|
0f61236884 | ||
|
|
9cd24e3cb6 | ||
|
|
12ff003249 |
+10
@@ -105,3 +105,13 @@ vc_redist_x86/
|
||||
.assets/
|
||||
# lotsmall 联调账号配置(含明文密码,勿入库)
|
||||
tests/lotsmall_probe/account.json
|
||||
|
||||
# aitable 探针落盘产物(银行卡/身份证照片等员工隐私材料,禁止入库)
|
||||
tests/aitable_probe/_out/
|
||||
|
||||
# 测试下载/生成的图片与数据集(证件照、银行卡照片等员工隐私材料 + OCR 训练图,禁止入库)
|
||||
tests/_out/
|
||||
tests/dataset*/
|
||||
tests/*_dataset*.zip
|
||||
tests/下载/
|
||||
tests/downloads/
|
||||
|
||||
+12676
File diff suppressed because it is too large
Load Diff
@@ -45,8 +45,14 @@ const grantedRows = computed(() => {
|
||||
}))
|
||||
})
|
||||
|
||||
const statusTag = (s: string) => (s === 'published' ? 'success' : s === 'disabled' ? 'warning' : 'danger')
|
||||
const statusLabel = (s: string) => (s === 'published' ? '已发布' : s === 'disabled' ? '已停用' : '已吊销')
|
||||
const STATUS_TAG: Record<string, string> = {
|
||||
published: 'success', testing: 'primary', disabled: 'warning', revoked: 'danger'
|
||||
}
|
||||
const STATUS_LABEL: Record<string, string> = {
|
||||
published: '已发布', testing: '测试中', disabled: '已停用', revoked: '已吊销'
|
||||
}
|
||||
const statusTag = (s: string) => STATUS_TAG[s] || 'info'
|
||||
const statusLabel = (s: string) => STATUS_LABEL[s] || s
|
||||
|
||||
// ---------- 表格多选批量撤销 ----------
|
||||
const tableRef = ref()
|
||||
|
||||
@@ -53,8 +53,14 @@ const recentPlugins = computed(() =>
|
||||
.slice(0, 6)
|
||||
)
|
||||
|
||||
const statusTag = (s: string) => (s === 'published' ? 'success' : s === 'disabled' ? 'warning' : 'danger')
|
||||
const statusLabel = (s: string) => (s === 'published' ? '已发布' : s === 'disabled' ? '已停用' : '已吊销')
|
||||
const STATUS_TAG: Record<string, string> = {
|
||||
published: 'success', testing: 'primary', disabled: 'warning', revoked: 'danger'
|
||||
}
|
||||
const STATUS_LABEL: Record<string, string> = {
|
||||
published: '已发布', testing: '测试中', disabled: '已停用', revoked: '已吊销'
|
||||
}
|
||||
const statusTag = (s: string) => STATUS_TAG[s] || 'info'
|
||||
const statusLabel = (s: string) => STATUS_LABEL[s] || s
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
|
||||
@@ -87,7 +87,8 @@ plugins/XQ0001-0100/XQ0042 抖音平台核对/
|
||||
|
||||
### 2. 参数解析与校验(Xq0042Plugin.run 前半段)
|
||||
- `_parse_day` 兼容 `YYYY-MM-DD` / `YYYY/MM/DD` / `YYYYMMDD`;`_resolve_pair(raw_from, raw_to, default_days)`:双空 = `today-(default_days-1) ~ today`、单端 = 单日、颠倒自动换序(核销、提现各解析一次,互不影响);`_company_ranges` 按 `config.COMPANIES[].default_days` 逐家公司取默认天数(金色印象 3 天 = 前日~今日、金色湖畔 2 天 = 昨日~今日,`DEFAULT_EXPORT_DAYS=2` 兜底),显式填了日期则各公司共用同一区间;
|
||||
- `save_dir`:`strip().strip('"')` 后为空 → `WORK_DIR=D:\资料\财务\抖音平台核对`;
|
||||
- `save_dir`:`strip().strip('"')` 后为空 → `WORK_DIR=D:\资料\财务\抖音平台核对`(导出下载目录,并台账时也从这里找明细);
|
||||
- `ledger_dir`:同上归一,为空 → `WORK_DIR`;台账文件(`抖音到账统计*.xlsx`)与备份只落在该目录,`merge_ledger.run(..., detail_dir=save_dir, ledger_dir=ledger_dir)` / `stat_links.run(..., ledger_dir=ledger_dir)` 分别传入,两目录可不同;
|
||||
- `_limit`:非整数或 < `RECORD_LIMIT_MIN(5)` → 回退默认(`RECORD_LIMIT_VERIFY=60` / `RECORD_LIMIT_WITHDRAW=25`);
|
||||
- `do_verify` / `do_withdraw` 默认 True(显式 False 才关);均 False → RuntimeError;
|
||||
- 进度:启动日志后 5% → 登录后 30% → 核销后 65% → 提现后 95% → 全成功 100%。
|
||||
|
||||
@@ -70,7 +70,7 @@
|
||||
### 1. 参数解析与校验(进度 5%)
|
||||
- 注入运行上下文:`ctx.log` / `ctx.progress` 写入 config 全局钩子,`debug_mode` 决定 DEBUG 级日志(页面跳转轨迹、限流等待等)是否输出;
|
||||
- `_resolve_pair` 解析核销、提现两个区间:都空 = 按公司默认天数(`config.COMPANIES[].default_days`:金色印象 3 天 = 前日~今日、金色湖畔 2 天 = 昨日~今日,兜底 2 天);只给一端 = 单日;起止颠倒自动换序;日期支持 `YYYY-MM-DD` / `YYYY/MM/DD` / `YYYYMMDD`;
|
||||
- `save_dir` 留空 = `D:\资料\财务\抖音平台核对`(首尾空白与引号自动剥离);保留条数非法或 <5 回退默认(核销 60 / 提现 25);
|
||||
- `save_dir` 留空 = `D:\资料\财务\抖音平台核对`(首尾空白与引号自动剥离),导出文件下载到这里、并台账也从这里找明细;`ledger_dir`(台账目录)留空同上,只用于找台账与写备份,两目录可不同;保留条数非法或 <5 回退默认(核销 60 / 提现 25);
|
||||
- 两项导出均未勾选 → `RuntimeError('请至少勾选一项导出内容(核销明细 / 提现记录)')` 终止;
|
||||
- `run_merge` / `run_stat_links` 默认开、`dry_run` 默认关;导出两项 + 并入台账 + 补核对表**全关** → `RuntimeError('请至少选择一项执行内容(导出核销明细 / 导出提现记录 / 并入台账 / 补核对表取数)')` 终止;只勾后两项时跳过浏览器与登录,直接补账/补公式;
|
||||
- 打印本次执行摘要(导出类目、两个区间、保存目录、保留条数、是否并入台账 / 演练、是否强制登录)后 `progress(5)`。
|
||||
@@ -98,7 +98,7 @@
|
||||
|
||||
### 5. 并入台账(进度 → 100%/96%/20%,run_merge=True 时)
|
||||
|
||||
- 选表:目录 `D:\资料\财务\抖音平台核对` 下 `抖音到账统计*.xlsx` 按文件名**月份最新**(正则 `(年份)[.\-年](月)月`),排除含「备份」与 `.rebuild.tmp` 的文件;
|
||||
- 选表:**台账目录**下 `抖音到账统计*.xlsx` 按文件名**月份最新**(正则 `(年份)[.\-年](月)月`),排除含「备份」与 `.rebuild.tmp` 的文件(明细则从保存目录取);
|
||||
- `_scan_ledger` 自写流式扫描(不整体加载 314MB sheet):解析 `xl/sharedStrings.xml` 取文本,逐行匹配 `<row>`:
|
||||
表头(第 1 行)建「列名 → 列号」映射;真实数据末行按「订单编号/券码/核销时间」任一非空判定(尾部 1.4 万行只剩公式,`max_row` 与 `dimension` 都不可信);
|
||||
取「核销时间」最大值与同秒行键;保留最后一个数据行作为**模板行**与末 30 行列类型统计;顺带收集共享公式主定义 `{si: (定义行, 公式)}`;
|
||||
|
||||
@@ -134,7 +134,8 @@ sheet `金色印象--抖音`(表头第 1 行、数据第 2 行起,A~CC 共 8
|
||||
| 并入台账(金色印象--抖音) | `run_merge` | 默认开;核销明细按「核销时间」增量并入台账,公式列自动下拉 |
|
||||
| 补核对表同源取数公式 | `run_stat_links` | 默认开;扫整行 `[n]资金组取数!` 公式,按 A 列日期换成当天共享总表链接 |
|
||||
| 只统计不写入(演练) | `dry_run` | 默认关;只报将追加的行数与起止行号,不改文件 |
|
||||
| 保存目录 | `save_dir` | 留空 = `D:\资料\财务\抖音平台核对` |
|
||||
| 保存目录 | `save_dir` | 留空 = `D:\资料\财务\抖音平台核对`;导出下载目录,并台账时也从这里找 `核销明细*.xlsx` |
|
||||
| 台账目录 | `ledger_dir` | 留空 = `D:\资料\财务\抖音平台核对`;`抖音到账统计YYYY.M月.xlsx` 所在目录(并台账 / 补取数只读这里),可与保存目录不同 |
|
||||
| 强制重新登录 | `force_login` | 忽略 profile 残留登录态,直接等人工登录(换账号 / 排查登录问题用) |
|
||||
| 调试日志 | `debug_mode` | 输出页面跳转轨迹等 DEBUG 级日志,默认关闭 |
|
||||
|
||||
|
||||
@@ -38,11 +38,37 @@ $cli = "libs\aitable\aitable\cli.py"
|
||||
& $py $cli list workplan --sheet hERWDMS --month 上线日期=2026-10 --json
|
||||
& $py $cli summary workplan --sheet hERWDMS --by 状态
|
||||
& $py $cli update workplan --sheet hERWDMS --record <id> --data '{\"状态\":\"上线\"}' --dry-run
|
||||
& $py $cli download hr --sheet uavChPe --field 银行卡卡号面照片,持卡人身份证照片 --limit 10 --name-field 持卡人姓名 --prefix
|
||||
```
|
||||
|
||||
base 支持三种写法:别名(`workplan` / `hr`)、baseId、`https://alidocs.dingtalk.com/i/nodes/<baseId>?sheetId=xxx`。
|
||||
新增常用表在 `aitable/client.py` 的 `BASE_ALIASES` 里登记。
|
||||
|
||||
## 附件(图片 / 文件)下载
|
||||
|
||||
`attachment` 字段的元数据里带阿里云 OSS **预签名地址**(`url`,免 token 直连、约 2 小时过期),
|
||||
库里已封装解析 + 下载(`resourceUrl` 是相对路径,不能直连):
|
||||
|
||||
```python
|
||||
from aitable import AiTable, attachment_items
|
||||
|
||||
cli = AiTable()
|
||||
rows = cli.records("hr", "uavChPe") # 银行卡-变更收集表
|
||||
for r in rows:
|
||||
v = r["fields"].get("银行卡卡号面照片")
|
||||
print(attachment_items(v)) # [{resourceId, filename, size, type, url}]
|
||||
for res in cli.download_attachments(v, r"D:\资料\银行卡照片\<姓名>"):
|
||||
print(res["ok"], res["path"], res["kind"], res["size_match"])
|
||||
```
|
||||
|
||||
返回字段:`ok / path / bytes / status / kind / content_type / size_match / expires_in / expired / error`。
|
||||
要点:
|
||||
|
||||
- `expired=True`(预签名地址剩余 <60s 或下载 403)→ **重新拉记录换新 url**,不要重试同一地址;
|
||||
- 落盘按 `prefix + 原文件名`,同名自动加 `-2`,非法字符换 `_`,文件名限长 120;
|
||||
- `kind` 按文件头魔数判断真实类型,`size_match` 与表格里声明的 `size` 比对,防止存成错误页/半截文件;
|
||||
- 单文件失败自动重试 3 次,仍失败在 `error` 里给原因;隐私图片勿入库(见根 `.gitignore`)。
|
||||
|
||||
## 月报 / 周报数据采集
|
||||
|
||||
```powershell
|
||||
@@ -68,3 +94,5 @@ base 支持三种写法:别名(`workplan` / `hr`)、baseId、`https://alid
|
||||
3. 日期是**毫秒时间戳 + 北京时间**(UTC 16:00 = 次日 00:00),自行换算易整体差一天。
|
||||
4. 写入:`singleSelect` 传选项名、`multipleSelect` 传数组、`date` 传毫秒、`user` 传 unionId 数组、`autoNumber` 只读。
|
||||
5. 部分 Windows 机器 `api.dingtalk.com` 的 A 记录解析失败(11001),库内置 DoH 兜底,可用 `AITABLE_DNS_IP` 覆盖。
|
||||
6. 附件 `url` 是预签名地址(含 `Expires`),**约 2 小时过期**:拉记录后要立刻下载,不能存 url 隔夜用;过期后只能重新 `records()` 换新地址。
|
||||
7. 读接口拿不到附件二进制,只能按 `resourceId/filename/size/type/url` 走 `download_attachments()`;`resourceUrl` 是相对路径,直连会 404。
|
||||
|
||||
@@ -10,6 +10,7 @@ from __future__ import annotations
|
||||
import os
|
||||
import sys
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
@@ -109,6 +110,102 @@ def test_filters() -> None:
|
||||
ok(len(cli.apply_filters(rows, [], ["上线日期=2026-10"])) == 1, "仅月份过滤")
|
||||
|
||||
|
||||
def test_attachment_helpers() -> None:
|
||||
from aitable.client import (attachment_items, parse_expires, safe_filename,
|
||||
sniff_kind, unique_path)
|
||||
val = [{"resourceId": "r1", "filename": "a.jpg", "size": 10, "type": "image",
|
||||
"url": "https://x.oss-cn/y.jpg?Expires=1794886717&Signature=abc"},
|
||||
{"resourceId": "r2", "filename": "b.png", "size": 5, "type": "image",
|
||||
"resourceUrl": "/core/api/resources/img/zz"}]
|
||||
its = attachment_items(val)
|
||||
ok(len(its) == 2, "attachment 字段值拆出 2 个附件")
|
||||
ok(its[0]["url"].startswith("https://") and its[0]["size"] == 10, "直连 url 与声明大小保留")
|
||||
ok(its[1]["url"] == "", "相对 resourceUrl 不当作可直连地址")
|
||||
ok(attachment_items(None) == [] and attachment_items({"filename": "c"})[0]["url"] == "",
|
||||
"空值/单个 dict 兼容")
|
||||
ok(parse_expires(its[0]["url"]) == 1794886717, "解析预签名 Expires")
|
||||
ok(parse_expires("https://x/y.jpg") == 0, "无 Expires 返回 0")
|
||||
|
||||
ok(safe_filename('a/b:c*?"<>|.jpg') == "a_b_c_.jpg", "非法字符换下划线")
|
||||
ok(safe_filename("", "") == "file" and safe_filename(" .. ") == "file", "空名兜底")
|
||||
ok(len(safe_filename("x" * 200)) == 120, "文件名限长 120")
|
||||
|
||||
import tempfile
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
png, jpg, txt = (Path(d) / n for n in ("a.png", "b.jpg", "c.txt"))
|
||||
png.write_bytes(b"\x89PNG\r\n\x1a\n" + b"\0" * 8)
|
||||
jpg.write_bytes(b"\xff\xd8\xff\xe0" + b"\0" * 8)
|
||||
txt.write_text("hello", encoding="utf-8")
|
||||
ok(sniff_kind(png) == "png" and sniff_kind(jpg) == "jpg", "按魔数识别 png/jpg")
|
||||
ok(sniff_kind(txt) == "unknown", "非图片判为 unknown")
|
||||
ok(sniff_kind(Path(d) / "nope.png") == "missing", "不存在的文件判为 missing")
|
||||
ok(unique_path(png) == Path(d) / "a-2.png", "同名文件改名 -2")
|
||||
(Path(d) / "a-2.png").write_bytes(b"x")
|
||||
ok(unique_path(png) == Path(d) / "a-3.png", "再同名改名 -3")
|
||||
|
||||
|
||||
def test_attachment_download() -> None:
|
||||
"""本地 HTTP 服务模拟 OSS:验证下载、魔数/大小校验、同名不覆盖、403/过期判定。"""
|
||||
import http.server
|
||||
import socketserver
|
||||
import tempfile
|
||||
import threading
|
||||
from aitable.client import AiTable, ATTACH_MIN_REMAIN # noqa: F401
|
||||
|
||||
png = b"\x89PNG\r\n\x1a\n" + b"\0" * 24
|
||||
|
||||
class _H(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
if self.path.startswith("/ok"):
|
||||
self.send_response(200)
|
||||
self.send_header("content-type", "image/png")
|
||||
self.send_header("content-length", str(len(png)))
|
||||
self.end_headers()
|
||||
self.wfile.write(png)
|
||||
else:
|
||||
self.send_response(403)
|
||||
self.end_headers()
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
with socketserver.TCPServer(("127.0.0.1", 0), _H) as srv:
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
port = srv.server_address[1]
|
||||
base = f"http://127.0.0.1:{port}"
|
||||
try:
|
||||
cli_ = AiTable.__new__(AiTable) # 只测下载,不走鉴权初始化
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
r1 = cli_.download_attachment({"url": f"{base}/ok.png", "size": len(png)},
|
||||
Path(d) / "x.png")
|
||||
ok(r1["ok"] and r1["kind"] == "png" and r1["size_match"] is True
|
||||
and r1["bytes"] == len(png), "下载成功 + 魔数/大小校验通过")
|
||||
|
||||
r2 = cli_.download_attachment({"url": f"{base}/ok.png", "size": len(png)},
|
||||
Path(d) / "x.png")
|
||||
ok(Path(r2["path"]).name == "x-2.png", "同名附件不覆盖,自动加 -2")
|
||||
|
||||
r3 = cli_.download_attachment({"url": f"{base}/deny.png"}, Path(d) / "y.png")
|
||||
ok(r3["expired"] is True and r3["ok"] is False, "403 判定预签名 url 过期")
|
||||
|
||||
r4 = cli_.download_attachment({"url": f"{base}/ok.png?Expires=1000"},
|
||||
Path(d) / "z.png")
|
||||
ok(r4["expired"] is True and not (Path(d) / "z.png").exists(),
|
||||
"Expires 已过期 → 不发请求、直接报过期")
|
||||
|
||||
multi = cli_.download_attachments(
|
||||
[{"url": f"{base}/ok.png", "filename": "卡号面.jpg", "size": len(png)},
|
||||
{"url": f"{base}/ok.png", "filename": "身份证.png", "size": len(png)}],
|
||||
Path(d) / "sub", prefix="银行卡-", col="银行卡卡号面照片")
|
||||
names = sorted(Path(x["path"]).name for x in multi)
|
||||
ok(len(multi) == 2 and all(x["ok"] for x in multi), "多附件字段批量下载")
|
||||
ok(names == ["银行卡-卡号面.jpg", "银行卡-身份证.png"], "prefix + 原文件名")
|
||||
ok(multi[0]["col"] == "银行卡卡号面照片" and multi[1]["index"] == 2,
|
||||
"结果带字段名与序号")
|
||||
finally:
|
||||
srv.shutdown()
|
||||
|
||||
|
||||
def test_online() -> None:
|
||||
from aitable import AiTable
|
||||
cli_ = AiTable()
|
||||
@@ -131,6 +228,8 @@ def main() -> int:
|
||||
test_resolve_base()
|
||||
test_period()
|
||||
test_filters()
|
||||
test_attachment_helpers()
|
||||
test_attachment_download()
|
||||
if "--online" in sys.argv:
|
||||
test_online()
|
||||
print(f"\n全部通过:{_passed} 项")
|
||||
|
||||
@@ -1,20 +1,23 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""aitable · 钉钉 AI 表格(notable)读写库 + 月报/周报数据采集。
|
||||
|
||||
对外只暴露三样:
|
||||
- AiTable 表格客户端(列 sheet/字段、分页读、批量增改)
|
||||
- cli / report 两个命令行入口(python -m aitable / python -m aitable.report)
|
||||
- 值归一工具 norm / to_ms / coerce_for_fields / flatten(写插件回填时常用)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .client import ( # noqa: F401
|
||||
BASE_ALIASES, DEFAULT_OPERATOR, AiTable, coerce_for_fields, flatten,
|
||||
install_dns_fallback, ms_to_str, norm, resolve_base, to_ms,
|
||||
)
|
||||
|
||||
__version__ = "1.0.0"
|
||||
__all__ = [
|
||||
"AiTable", "BASE_ALIASES", "DEFAULT_OPERATOR", "coerce_for_fields", "flatten",
|
||||
"install_dns_fallback", "ms_to_str", "norm", "resolve_base", "to_ms",
|
||||
]
|
||||
# -*- coding: utf-8 -*-
|
||||
"""aitable · 钉钉 AI 表格(notable)读写库 + 月报/周报数据采集。
|
||||
|
||||
对外暴露:
|
||||
- AiTable 表格客户端(列 sheet/字段、分页读、批量增改、附件下载)
|
||||
- cli / report 两个命令行入口(python -m aitable / python -m aitable.report)
|
||||
- 值归一工具 norm / to_ms / coerce_for_fields / flatten(写插件回填时常用)
|
||||
- 附件工具 attachment_items / safe_filename / sniff_kind / parse_expires
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .client import ( # noqa: F401
|
||||
BASE_ALIASES, DEFAULT_OPERATOR, AiTable, attachment_items, coerce_for_fields,
|
||||
flatten, install_dns_fallback, ms_to_str, norm, parse_expires, resolve_base,
|
||||
safe_filename, sniff_kind, to_ms,
|
||||
)
|
||||
|
||||
__version__ = "1.1.0"
|
||||
__all__ = [
|
||||
"AiTable", "BASE_ALIASES", "DEFAULT_OPERATOR", "attachment_items",
|
||||
"coerce_for_fields", "flatten", "install_dns_fallback", "ms_to_str", "norm",
|
||||
"parse_expires", "resolve_base", "safe_filename", "sniff_kind", "to_ms",
|
||||
]
|
||||
|
||||
@@ -20,12 +20,12 @@ from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
try: # 作为包导入
|
||||
from .client import (AiTable, DEFAULT_OPERATOR, coerce_for_fields, flatten,
|
||||
resolve_base)
|
||||
from .client import (AiTable, DEFAULT_OPERATOR, attachment_items,
|
||||
coerce_for_fields, flatten, norm, resolve_base, safe_filename)
|
||||
except ImportError: # 直接执行文件
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from aitable.client import (AiTable, DEFAULT_OPERATOR, coerce_for_fields, # noqa: F401
|
||||
flatten, resolve_base)
|
||||
from aitable.client import (AiTable, DEFAULT_OPERATOR, attachment_items, # noqa: F401
|
||||
coerce_for_fields, flatten, norm, resolve_base, safe_filename)
|
||||
|
||||
|
||||
# ==================== 过滤 / 输出 ====================
|
||||
@@ -179,6 +179,61 @@ def _cmd_summary(args, cli) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def _cmd_download(args, cli) -> int:
|
||||
"""把 attachment 字段(图片/文件)下载到本地:每记录一个子目录,按字段分组落盘。"""
|
||||
base, link_sheet = resolve_base(args.base)
|
||||
sheet = _sheet_arg(args, cli, base, link_sheet)
|
||||
cols = [c.strip() for c in args.field.split(",") if c.strip()]
|
||||
if not cols:
|
||||
raise SystemExit("[x] --field 至少给一个字段名")
|
||||
|
||||
recs = cli.records(base, sheet)
|
||||
if args.where:
|
||||
keep = {r["_id"] for r in apply_filters([flatten(x) for x in recs], args.where, [])}
|
||||
recs = [x for x in recs if x.get("id") in keep]
|
||||
|
||||
out_root = Path(args.out or f"aitable_downloads/{sheet}")
|
||||
results, people, total = [], 0, 0
|
||||
for rec in recs:
|
||||
f = rec.get("fields") or {}
|
||||
got = {c: attachment_items(f.get(c)) for c in cols}
|
||||
if not any(got.values()): # 该记录这些字段都没有附件,跳过
|
||||
continue
|
||||
if args.limit and people >= args.limit:
|
||||
break
|
||||
people += 1
|
||||
label = str(norm(f.get(args.name_field))) if args.name_field else ""
|
||||
folder = out_root / safe_filename(label or rec.get("id", ""), rec.get("id", "rec"))
|
||||
for c in cols:
|
||||
prefix = f"{safe_filename(c)}-" if args.prefix else ""
|
||||
for r in cli.download_attachments(got[c], folder, prefix=prefix, col=c):
|
||||
total += 1
|
||||
results.append({"记录id": rec.get("id", ""), "姓名": label,
|
||||
"字段": c, "文件": r.get("filename", ""),
|
||||
"ok": r.get("ok"), "path": r.get("path", ""),
|
||||
"bytes": r.get("bytes", 0), "kind": r.get("kind", ""),
|
||||
"size_match": r.get("size_match"),
|
||||
"expired": r.get("expired"), "error": r.get("error", "")})
|
||||
|
||||
okn = sum(1 for r in results if r["ok"])
|
||||
bad = [r for r in results if not r["ok"]]
|
||||
expired = [r for r in results if r.get("expired")]
|
||||
summary = {"sheet": sheet, "fields": cols, "out": str(out_root),
|
||||
"records": people, "attachments": total, "downloaded": okn,
|
||||
"failed": len(bad), "expired": len(expired),
|
||||
"bytes": sum(r["bytes"] or 0 for r in results)}
|
||||
if args.json:
|
||||
emit_json({"summary": summary, "items": results})
|
||||
else:
|
||||
print(f"{people} 条记录 / {total} 个附件 → 成功 {okn},失败 {len(bad)}"
|
||||
f"(过期 {len(expired)}),共 {summary['bytes'] / 1024:.0f} KB")
|
||||
print(f"落盘:{out_root}")
|
||||
for r in bad:
|
||||
print(f"[x] {r['记录id']} {r['姓名']} {r['字段']} {r['文件']}:"
|
||||
f"{r['error'] or '下载失败'}")
|
||||
return 0 if not bad else 1
|
||||
|
||||
|
||||
def _load_data(raw: str, file_path: str) -> dict:
|
||||
if raw and file_path:
|
||||
raise SystemExit("[x] --data 与 --data-file 只能二选一")
|
||||
@@ -262,6 +317,20 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
s.add_argument("--month", action="append", default=[], metavar="日期字段=YYYY-MM")
|
||||
s.set_defaults(func=_cmd_summary)
|
||||
|
||||
s = sub.add_parser("download", help="下载 attachment(图片/文件)字段到本地目录",
|
||||
parents=[common])
|
||||
s.add_argument("base")
|
||||
s.add_argument("--sheet", default="")
|
||||
s.add_argument("--field", required=True, metavar="字段名[,字段名]",
|
||||
help="要下载的附件字段,逗号分隔")
|
||||
s.add_argument("--out", default="", help="落盘根目录(默认 aitable_downloads/<sheetId>)")
|
||||
s.add_argument("--limit", type=int, default=0, help="最多处理多少条记录,0=全部")
|
||||
s.add_argument("--name-field", default="", help="用该字段值作子目录名,默认记录 id")
|
||||
s.add_argument("--prefix", action="store_true", help="文件名前加字段名,便于区分多列")
|
||||
s.add_argument("--where", action="append", default=[], metavar="字段=值",
|
||||
help="等值过滤,可重复(AND)")
|
||||
s.set_defaults(func=_cmd_download)
|
||||
|
||||
s = sub.add_parser("add", help="新增记录", parents=[common])
|
||||
s.add_argument("base")
|
||||
s.add_argument("--sheet", default="")
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""钉钉 AI 表格(notable)客户端:鉴权、分页读取、字段归一、按类型写值。
|
||||
"""钉钉 AI 表格(notable)客户端:鉴权、分页读取、字段归一、按类型写值、附件下载。
|
||||
|
||||
凭证读取顺序(**不读已废弃的 desktop/controlplane/.env**):
|
||||
1. 环境变量 AITABLE_ENV_FILE 指定的 .env
|
||||
@@ -11,8 +11,10 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import time
|
||||
import urllib.parse as urllib_parse
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
@@ -183,6 +185,85 @@ def flatten(rec: dict) -> dict:
|
||||
return row
|
||||
|
||||
|
||||
# ==================== 附件(图片 / 文件)====================
|
||||
|
||||
ATTACH_RETRY = 3 # 单文件下载重试次数
|
||||
ATTACH_TIMEOUT = 30
|
||||
ATTACH_MIN_REMAIN = 60 # 预签名 url 剩余有效期低于该秒数即视为不可用
|
||||
_BAD_NAME = re.compile(r'[\\/:*?"<>|\r\n\t]+')
|
||||
_MAGIC = ((b"\xff\xd8\xff", "jpg"), (b"\x89PNG\r\n\x1a\n", "png"),
|
||||
(b"GIF87a", "gif"), (b"GIF89a", "gif"), (b"BM", "bmp"), (b"%PDF", "pdf"))
|
||||
|
||||
|
||||
def attachment_items(value: Any) -> list:
|
||||
"""attachment 字段值 → [{resourceId, filename, size, type, url}]。
|
||||
|
||||
notable 返回的附件元数据里 `url` 是阿里云 OSS **预签名地址**(免 token 直连,
|
||||
约 2 小时过期);`resourceUrl` 是相对路径,不能直连,故只保留绝对 url。
|
||||
"""
|
||||
if not value:
|
||||
return []
|
||||
if isinstance(value, dict):
|
||||
value = [value]
|
||||
out = []
|
||||
for it in value:
|
||||
if not isinstance(it, dict):
|
||||
continue
|
||||
url = str(it.get("url") or "")
|
||||
if not url.startswith(("http://", "https://")):
|
||||
url = ""
|
||||
out.append({"resourceId": it.get("resourceId") or "",
|
||||
"filename": it.get("filename") or "",
|
||||
"size": int(it.get("size") or 0),
|
||||
"type": it.get("type") or "",
|
||||
"url": url})
|
||||
return out
|
||||
|
||||
|
||||
def parse_expires(url: str) -> int:
|
||||
"""预签名 url 的 `Expires` 秒级时间戳;取不到返回 0(不限时的地址)。"""
|
||||
try:
|
||||
q = urllib_parse.parse_qs(urllib_parse.urlparse(url).query)
|
||||
return int((q.get("Expires") or ["0"])[0] or 0)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
def safe_filename(name: Any, fallback: str = "file") -> str:
|
||||
"""文件名净化:Windows 非法字符换 `_`、去首尾点空格、限长 120。"""
|
||||
s = _BAD_NAME.sub("_", str(name or "")).strip(" .")
|
||||
if not s:
|
||||
s = _BAD_NAME.sub("_", str(fallback or "file")).strip(" .") or "file"
|
||||
return s[:120]
|
||||
|
||||
|
||||
def sniff_kind(path: Any) -> str:
|
||||
"""按文件头魔数判断真实类型(防止把错误页/占位图当图片)。"""
|
||||
try:
|
||||
head = Path(path).read_bytes()[:16]
|
||||
except OSError:
|
||||
return "missing"
|
||||
if head[:4] == b"RIFF" and b"WEBP" in head[:16]:
|
||||
return "webp"
|
||||
for sig, kind in _MAGIC:
|
||||
if head.startswith(sig):
|
||||
return kind
|
||||
return "unknown"
|
||||
|
||||
|
||||
def unique_path(dest: Path) -> Path:
|
||||
"""目标已存在时追加 `-2`、`-3`…,避免同名附件互相覆盖。"""
|
||||
dest = Path(dest)
|
||||
if not dest.exists():
|
||||
return dest
|
||||
n = 2
|
||||
while True:
|
||||
cand = dest.with_name(f"{dest.stem}-{n}{dest.suffix}")
|
||||
if not cand.exists():
|
||||
return cand
|
||||
n += 1
|
||||
|
||||
|
||||
# ==================== 客户端 ====================
|
||||
|
||||
class AiTable:
|
||||
@@ -292,6 +373,77 @@ class AiTable:
|
||||
ok += len(d.get("value") or batch)
|
||||
return ok
|
||||
|
||||
# ---- 附件(图片 / 文件)下载 ----
|
||||
def download_attachment(self, item: dict, dest: Any, retries: int = ATTACH_RETRY,
|
||||
overwrite: bool = False) -> dict:
|
||||
"""下载单个附件到 dest。
|
||||
|
||||
返回 dict:ok / path / bytes / status / kind / content_type / size_match /
|
||||
expires_in / expired / error。`expired=True` 表示预签名 url 已过期或 403,
|
||||
需重新拉记录换新 url(不要重试同一个地址)。
|
||||
"""
|
||||
dest = Path(dest)
|
||||
info: dict = {"ok": False, "path": str(dest), "bytes": 0, "status": 0,
|
||||
"kind": "", "content_type": "", "size_match": None,
|
||||
"expires_in": None, "expired": False, "error": ""}
|
||||
item = item or {}
|
||||
url = str(item.get("url") or "")
|
||||
if not url:
|
||||
info["error"] = "附件没有可直连的 url(只有相对 resourceUrl)"
|
||||
return info
|
||||
exp = parse_expires(url)
|
||||
if exp:
|
||||
info["expires_in"] = int(exp - time.time())
|
||||
if info["expires_in"] <= ATTACH_MIN_REMAIN:
|
||||
info["expired"] = True
|
||||
info["error"] = f"预签名 url 已过期/即将过期(剩 {info['expires_in']}s),请重新拉记录"
|
||||
return info
|
||||
|
||||
target = dest if overwrite else unique_path(dest)
|
||||
info["path"] = str(target)
|
||||
last: Any = None
|
||||
for attempt in range(1, retries + 1):
|
||||
try:
|
||||
r = requests.get(url, timeout=ATTACH_TIMEOUT)
|
||||
if r.status_code == 403: # OSS 签名过期/无权限:重试同一地址无意义
|
||||
info.update(status=403, expired=True,
|
||||
error="下载被拒(403,url 可能已过期),请重新拉记录")
|
||||
return info
|
||||
r.raise_for_status()
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(r.content)
|
||||
declared = int(item.get("size") or 0)
|
||||
info.update(ok=True, status=r.status_code, bytes=len(r.content),
|
||||
content_type=r.headers.get("content-type", ""),
|
||||
kind=sniff_kind(target),
|
||||
size_match=(None if not declared else
|
||||
len(r.content) == declared))
|
||||
return info
|
||||
except Exception as exc: # 网络抖动 / 限流 / 5xx
|
||||
last = exc
|
||||
if attempt < retries:
|
||||
time.sleep(RETRY_DELAY_BASE * attempt)
|
||||
info["error"] = repr(last)
|
||||
return info
|
||||
|
||||
def download_attachments(self, value: Any, save_dir: Any, prefix: str = "",
|
||||
col: str = "", retries: int = ATTACH_RETRY,
|
||||
overwrite: bool = False) -> list:
|
||||
"""下载一个 attachment 字段的全部附件到 save_dir/(`prefix + 原文件名` 命名)。
|
||||
|
||||
返回每个附件的 download_attachment 结果列表(额外带 col/index/filename/
|
||||
resourceId/declared_size)。多图字段按 index 顺序落盘,重名自动加 `-2`。
|
||||
"""
|
||||
out = []
|
||||
for i, it in enumerate(attachment_items(value), 1):
|
||||
name = safe_filename(it["filename"], it["resourceId"] or f"{col or 'file'}{i}")
|
||||
dest = Path(save_dir) / safe_filename(f"{prefix}{name}" if prefix else name)
|
||||
r = self.download_attachment(it, dest, retries=retries, overwrite=overwrite)
|
||||
r.update(col=col or "", index=i, filename=it["filename"],
|
||||
resourceId=it["resourceId"], declared_size=it["size"])
|
||||
out.append(r)
|
||||
return out
|
||||
|
||||
|
||||
def resolve_base(raw: str) -> tuple:
|
||||
"""别名 / baseId / alidocs 链接 → (baseId, 链接里带的 sheetId 或空)。"""
|
||||
|
||||
@@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "aitable"
|
||||
version = "1.0.0"
|
||||
description = "钉钉 AI 表格(notable)读写库:列 sheet/字段、分页读取、过滤统计、按类型写值,附月报/周报数据采集"
|
||||
version = "1.1.0"
|
||||
description = "钉钉 AI 表格(notable)读写库:列 sheet/字段、分页读取、过滤统计、按类型写值、附件图片下载,附月报/周报数据采集"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.9"
|
||||
dependencies = [
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
| 截图(全屏/区域/窗口) | `screenshot(path)` |
|
||||
| **离线图片标记**(不碰屏幕,框出命中位置) | `mark(image, [tpl1, tpl2], out_path)` |
|
||||
| **文字识别取坐标** | `read_text()` → `[TextItem(text, center, score)]` |
|
||||
| **身份证 / 银行卡照片识别** | `ocr_card(path)` / `ocr_cards(folder)` → 号码、姓名、发卡行、校验结果 |
|
||||
| **按文字判断/等待/点击** | `text_exists("导出")` / `wait_text` / `click_text` |
|
||||
| **多状态按钮** | `find_any([tpl可用, tpl禁用])` → `(命中, 模板名)` |
|
||||
| **输入文本(中文)** | `paste("内容")`(写剪贴板+Ctrl+V)/ `type_text` |
|
||||
@@ -382,6 +383,62 @@ python -m desktopauto --mode ocr --window "钉钉" --text "工作台"
|
||||
| 坐标 | 实时截图返回**屏幕物理像素**,可直接 `click_text`;离线图(`mark` / `--image`)返回图内坐标 |
|
||||
| 稳定性 | OCR 是「看图」不是无障碍接口,界面改版就可能失效;重要流程建议「模板匹配 + OCR」互为兜底 |
|
||||
|
||||
## 证件照识别(身份证 / 银行卡)
|
||||
|
||||
拍照上传的身份证人像面、银行卡卡号面 → 结构化字段。纯离线(RapidOCR + onnxruntime),
|
||||
模型随包,不联网;识别结果用**身份证校验码(模 11-2)/ 银行卡 Luhn** 把 OCR 认错的数字纠回来。
|
||||
|
||||
```python
|
||||
from desktopauto import ocr_card, ocr_cards
|
||||
|
||||
res = ocr_card(r"D:\照片\张三\银行卡.jpg", expected_name="张三")
|
||||
print(res["bank_card"]["number"], # 6214 8338 3144 5443
|
||||
res["bank_card"]["luhn_ok"], # True
|
||||
res["bank_card"]["bank"], # 招商银行(BIN + 卡面文字双通道)
|
||||
res["flags"]) # ['duplicate_photo'] 等
|
||||
|
||||
rows = ocr_cards(r"D:\照片") # 按「姓名/图片」目录批量,同人多图合并、同图去重
|
||||
```
|
||||
|
||||
输出(每个人的一条记录):
|
||||
|
||||
| 字段 | 说明 |
|
||||
|---|---|
|
||||
| `id_card.number / checksum_ok / name / gender / birth / address / issue / valid_to` | 身份证:号码、校验是否通过、姓名、性别、出生、住址、签发机关、有效期 |
|
||||
| `bank_card.number / luhn_ok / length / bank / expiry / card_type` | 银行卡:卡号、Luhn、位数、发卡行、有效期、卡类型 |
|
||||
| `confidence` | `high / medium / low`(身份证、卡号各一份) |
|
||||
| `flags` | `id_not_found` `card_not_found` `id_checksum_fail` `card_luhn_fail` `duplicate_photo` `low_resolution` `rotated_90` … |
|
||||
| `digit_runs` | 照片里所有数字片段(和已知号码比对时找证据) |
|
||||
|
||||
识别策略(为什么不是「一步 OCR 全图」):
|
||||
|
||||
1. **粗识别**:缩到 1440 长边定位文字块(快);
|
||||
2. **精修**:字段缺失时回原图按原生分辨率切块重识别(准);
|
||||
3. **多路兜底**:灰度/CLAHE 整图、短边<800px 的缩略图 4 倍放大、数字带黑帽/Otsu/锐化(窄条图跳过检测网络,单路 0.1~0.3s);
|
||||
4. **按行抓号码**:同一行合并、不同行切开,避免把卡号后面的有效期连成假号码;
|
||||
5. **校验位裁判**:易混字符(`b→6/8`、`O→0`、`l→1`…)枚举候选,只有通过校验的才接受;多位可纠时**只认唯一解**,歧义宁可标人工。
|
||||
|
||||
实测(10 人真实样本,人工填真值):身份证号 **100%**、姓名 **80%**、银行卡号 **55.6%** 逐位正确;
|
||||
**认出来的 100% 正确**,错在「读不出」(缩略图/浮雕/反光),不读错。读不出的会带 `card_not_found` 交人工。
|
||||
|
||||
批量核对闭环(Excel 留「待填正确答案」列,填完回读算准确率):
|
||||
|
||||
```python
|
||||
from desktopauto import cardocr
|
||||
cardocr.write_review_workbook(rows, "核对表.xlsx") # 需要 openpyxl
|
||||
print(cardocr.verify_workbook("核对表.xlsx")) # 准确率统计
|
||||
```
|
||||
|
||||
命令行:
|
||||
|
||||
```powershell
|
||||
python -m desktopauto.cardocr scan D:\照片 --json result.json --xlsx 核对表.xlsx
|
||||
python -m desktopauto.cardocr image D:\照片\张三\银行卡.jpg --name 张三
|
||||
```
|
||||
|
||||
依赖:OCR 需 `rapidocr` + `onnxruntime`(可选依赖 `desktopauto[ocr]` / `desktopauto[card]`),
|
||||
导出/回读 Excel 另需 `openpyxl`(`desktopauto[report]`);没装 openpyxl 时导入本库不受影响。
|
||||
|
||||
## 模板图怎么准备
|
||||
|
||||
1. 用 `--mode shot` 截一张,再用画图工具裁出**目标区域**(比目标稍大一点、带完整边框/图标);
|
||||
|
||||
@@ -285,6 +285,45 @@ def main() -> int:
|
||||
ok(0.009 <= waited <= 0.021, f"sleep 随机等待生效({waited:.3f}s)")
|
||||
ok(_S2().wait_all([absent], timeout=0.5) is False, "wait_all:有模板不存在返回 False")
|
||||
|
||||
# ---- 18. 浮雕卡号裁决(离线,不依赖图片/OCR) ----
|
||||
from desktopauto.cardocr import enhance as _en # noqa: PLC0415
|
||||
from desktopauto.cardocr.validators import luhn_ok as _luhn # noqa: PLC0415
|
||||
|
||||
def _fake_group(digits, votes=None):
|
||||
g = _en.GroupRead(rect=(0, 0, 10, 10), offset=0.0)
|
||||
g.digits = digits
|
||||
g.reads = {"eq": digits}
|
||||
g.votes = votes or [{c: 1} for c in digits]
|
||||
return g
|
||||
|
||||
clean = [_fake_group("6214"), _fake_group("8323"),
|
||||
_fake_group("7766"), _fake_group("0399")]
|
||||
r_clean = _en._resolve(clean, "招商银行")
|
||||
ok(r_clean.status == "ok" and r_clean.confidence == "high",
|
||||
f"投票串本身合法 → ok/high(实际 {r_clean.status}/{r_clean.confidence})")
|
||||
ok(r_clean.number == "6214832377660399" and r_clean.luhn_ok,
|
||||
f"卡号裁决正确({r_clean.number})")
|
||||
ok(r_clean.bank == "招商银行", f"BIN 命中招商银行({r_clean.bank})")
|
||||
ok(_luhn("6214832377660399") and not _luhn("6214832377660390"),
|
||||
"Luhn:尾号 99 合法、90 非法")
|
||||
|
||||
# 尾位 6 被反光误认成 8 → 应在易混对里改回 6,并降级为候选(不硬猜)
|
||||
noisy = [_fake_group("6214"), _fake_group("8323"),
|
||||
_fake_group("7788"), _fake_group("0399")]
|
||||
r_noisy = _en._resolve(noisy, "招商银行")
|
||||
ok(r_noisy.status == "candidate" and r_noisy.number != "6214832377880399",
|
||||
f"误认为 8 时不直接采信({r_noisy.number}/{r_noisy.status})")
|
||||
ok(all(c["luhn_ok"] for c in r_noisy.candidates), "候选全部通过 Luhn")
|
||||
|
||||
# 卡面银行与 BIN 冲突 → 该候选必须被剔除
|
||||
conflicted = _en._resolve(clean, "中国工商银行")
|
||||
ok(conflicted.number == "" and conflicted.status == "failed",
|
||||
"卡面银行与 BIN 冲突时不给号码(宁可失败)")
|
||||
|
||||
# 空白投票(完全没读出)→ failed,不抛异常
|
||||
blank = _en._resolve([_fake_group("0000")] * 4, "")
|
||||
ok(blank.status in ("failed", "candidate"), "全 0 投票不抛异常")
|
||||
|
||||
print(f"\n全部通过:{_passed} 项;临时目录 {TMP}")
|
||||
return 0
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""desktopauto —— 屏幕识图 / 文字识别 / 鼠标键盘 工具库(面向无元素树的桌面自动化)。
|
||||
"""desktopauto —— 屏幕识图 / 文字识别 / 鼠标键盘 / 证件照 OCR 工具库(面向无元素树的桌面自动化)。
|
||||
|
||||
只依赖 opencv-python + numpy + pillow(OCR 另需 rapidocr + onnxruntime),
|
||||
鼠标键盘窗口全部走 ctypes 调系统 API,不依赖 pyautogui / pywin32 / 任何底座代码。
|
||||
@@ -14,11 +14,18 @@
|
||||
s.hotkey("ctrl", "enter") # 组合键
|
||||
s.wait_stable_text = s.wait_text("发送成功") # 文字确认
|
||||
|
||||
证件照识别(身份证 / 银行卡,离线,供插件核对上传材料):
|
||||
from desktopauto import ocr_card, ocr_cards
|
||||
|
||||
res = ocr_card(path, expected_name="张三") # 单张
|
||||
rows = ocr_cards(folder) # 按「姓名/图片」目录批量
|
||||
|
||||
分组:
|
||||
截图 grab / screenshot
|
||||
识图 find / find_all / find_any / exists / wait / click / click_at
|
||||
文字 read_text / recognize / find_text / find_all_text / text_exists /
|
||||
wait_text / click_text
|
||||
证件照 ocr_card / ocr_cards / cardocr(身份证、银行卡号码与姓名)
|
||||
输入 paste / type_text / press / hotkey / key_down / key_up
|
||||
鼠标 scroll / drag(click 已含左/右/中键与连击)
|
||||
窗口 list_windows / find_window(s) / wait_window / child_windows /
|
||||
@@ -30,9 +37,11 @@
|
||||
模板不存在/无法解码、窗口找不到、依赖缺失 → RuntimeError(配置错误,需要修);
|
||||
图/文字没匹配到 → None / False(业务上的「不存在」,不是异常)。
|
||||
"""
|
||||
from . import clipboard, colors, fs, keys, ocr, process
|
||||
from . import cardocr, clipboard, colors, fs, keys, ocr, process
|
||||
from ._win32 import click_at
|
||||
from .capture import screenshot
|
||||
from .cardocr import analyze_folder, analyze_image
|
||||
from .cardocr.enhance import read_bank_card_number
|
||||
from .colors import ColorMatch, diff_ratio, find_colors
|
||||
from .process import (is_running, kill_process, launch, list_processes, open_path,
|
||||
open_url, run_or_open, wait_process)
|
||||
@@ -52,6 +61,10 @@ from .window import (
|
||||
foreground_window, get_window, list_windows, wait_window, window_info, window_rect,
|
||||
)
|
||||
|
||||
# 证件照识别的插件级别名(名字直白,少一层记忆)
|
||||
ocr_card = analyze_image
|
||||
ocr_cards = analyze_folder
|
||||
|
||||
__all__ = [
|
||||
# 门面
|
||||
"Screen",
|
||||
@@ -67,6 +80,9 @@ __all__ = [
|
||||
"read_text", "recognize", "match_text", "find_text", "find_all_text",
|
||||
"text_exists", "wait_text", "click_text", "ocr_available", "ocr",
|
||||
"ocr_text", "ocr_text_with_position",
|
||||
# 证件照(身份证 / 银行卡)
|
||||
"cardocr", "ocr_card", "ocr_cards", "analyze_image", "analyze_folder",
|
||||
"read_bank_card_number",
|
||||
# RPA 指令别名
|
||||
"image_exists", "wait_image", "click_image", "hover_image", "wait_text_exists",
|
||||
# 输入
|
||||
@@ -88,4 +104,4 @@ __all__ = [
|
||||
"mark", "summarize",
|
||||
]
|
||||
|
||||
__version__ = "0.4.0"
|
||||
__version__ = "0.5.3"
|
||||
|
||||
@@ -10,13 +10,14 @@ import numpy as np
|
||||
|
||||
from . import matcher
|
||||
|
||||
EXPECTED_VERSION = "0.4.0"
|
||||
EXPECTED_VERSION = "0.5.3"
|
||||
|
||||
#: 插件实际用到的门面 API,缺失即视为破坏性变更
|
||||
REQUIRED_EXPORTS = (
|
||||
"Screen", "find", "find_all", "exists", "click", "click_at", "hotkey",
|
||||
"paste", "screenshot", "find_windows", "get_window", "Window",
|
||||
"mark", "summarize", "ocr", "fs", "keys", "sleep",
|
||||
"cardocr", "ocr_card", "ocr_cards",
|
||||
)
|
||||
|
||||
|
||||
@@ -42,5 +43,17 @@ def main() -> int:
|
||||
if hit.center != (hit.left + 30, hit.top + 15):
|
||||
raise AssertionError(f"中心点换算错误:{hit.center}")
|
||||
|
||||
# 证件照识别:只校验纯算法(不加载 OCR 模型、不读图片)
|
||||
from .cardocr import match, validators # noqa: PLC0415
|
||||
|
||||
if not validators.id_checksum_ok("530425198904041120"):
|
||||
raise AssertionError("身份证校验码算法异常")
|
||||
if not validators.luhn_ok("6214833831445443"):
|
||||
raise AssertionError("银行卡 Luhn 算法异常")
|
||||
runs = ["6214832337534461", "621483237534461"]
|
||||
cov, status, _ = match.coverage("6214832377534461", runs, id_digits="530425198904041120")
|
||||
if status not in ("strong", "exact") or cov < 0.85:
|
||||
raise AssertionError(f"卡号命中分析异常:cov={cov:.2f} status={status}")
|
||||
|
||||
print(f"[OK] desktopauto {version} SDK 冒烟通过({len(REQUIRED_EXPORTS)} 项门面 API)")
|
||||
return 0
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""身份证 / 银行卡照片识别(纯离线 OCR),供插件直接调用。
|
||||
|
||||
能力:
|
||||
照片 → 卡片定位/透视矫正 → 多遍 OCR → 字段提取 → 身份证校验码 / 银行卡 Luhn 纠错
|
||||
身份证:号码、姓名、性别、民族、出生、住址、签发机关、有效期
|
||||
银行卡:卡号、发卡行、有效期、卡类型
|
||||
批量:按「姓名/图片」目录跑,同人多图合并,自动去重(两列传同一张图)
|
||||
核对:导出带「待填正确答案」的 Excel;已知号码时做命中分析(一致/高度疑似/部分命中/读不出)
|
||||
|
||||
插件里最简单的用法:
|
||||
from desktopauto import ocr_card, ocr_cards
|
||||
|
||||
res = ocr_card(r"D:\\照片\\张三\\银行卡.jpg", expected_name="张三")
|
||||
print(res["bank_card"]["number"], res["bank_card"]["luhn_ok"], res["flags"])
|
||||
|
||||
rows = ocr_cards(r"D:\\照片") # [{folder, id_card, bank_card, flags, ...}]
|
||||
|
||||
依赖:opencv-python / numpy / pillow(本库已有)+ rapidocr / onnxruntime(OCR 可选依赖)。
|
||||
模型随 rapidocr 包内置,纯离线,不联网。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .match import check_person, check_persons
|
||||
from .pipeline import analyze_folder, analyze_image
|
||||
|
||||
__version__ = "0.4.1"
|
||||
|
||||
__all__ = [
|
||||
"analyze_image", "analyze_folder",
|
||||
"check_person", "check_persons",
|
||||
"write_review_workbook", "verify_workbook",
|
||||
"__version__",
|
||||
]
|
||||
|
||||
|
||||
def write_review_workbook(persons, path, source_root: str = "") -> str:
|
||||
"""导出带「待填正确答案」列的核对工作簿(需要 openpyxl)。"""
|
||||
try:
|
||||
from .review import write_review_workbook as _impl # noqa: PLC0415
|
||||
except ImportError as e: # pragma: no cover
|
||||
raise RuntimeError("需要 openpyxl 才能导出核对工作簿:pip install openpyxl") from e
|
||||
return _impl(persons, path, source_root=source_root)
|
||||
|
||||
|
||||
def verify_workbook(path: str) -> dict:
|
||||
"""回读人工填好的核对工作簿,统计识别准确率(需要 openpyxl)。"""
|
||||
try:
|
||||
from .review import verify_workbook as _impl # noqa: PLC0415
|
||||
except ImportError as e: # pragma: no cover
|
||||
raise RuntimeError("需要 openpyxl 才能回读核对工作簿:pip install openpyxl") from e
|
||||
return _impl(path)
|
||||
@@ -0,0 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""python -m desktopauto.cardocr scan <目录> [--json out.json] [--xlsx 核对表.xlsx]"""
|
||||
from .cli import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,138 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""银行卡字段抽取:卡号 / 发卡行 / 有效期 / 卡类型。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, List, Optional, Sequence
|
||||
|
||||
from .engine import Line, join_text
|
||||
from .validators import (BIN_BANK, CardCandidate, bin_bank, card_candidates,
|
||||
luhn_ok, normalize_text)
|
||||
|
||||
BANK_KEYWORDS = ("银行", "银联", "UnionPay", "UNIONPAY", "Debit", "Credit", "借记卡",
|
||||
"信用卡", "储蓄卡", "一卡通", "招商", "农业", "工商", "建设", "民生",
|
||||
"兴业", "浦发", "交通", "邮政", "中信", "光大", "华夏", "广发", "平安")
|
||||
|
||||
BANK_NAMES = ("重庆农村商业银行", "重庆三峡银行", "中国工商银行", "中国农业银行",
|
||||
"中国建设银行", "中国银行", "招商银行", "中国民生银行", "兴业银行",
|
||||
"浦发银行", "交通银行", "中国邮政储蓄银行", "中信银行", "中国光大银行",
|
||||
"华夏银行", "广发银行", "平安银行")
|
||||
|
||||
_VALID_BANK_LEN = (16, 18, 19)
|
||||
|
||||
|
||||
@dataclass
|
||||
class BankCardResult:
|
||||
number: str = ""
|
||||
luhn_ok: bool = False
|
||||
length: int = 0
|
||||
bank: str = ""
|
||||
bank_source: str = "" # bin / face / ""
|
||||
expiry: str = ""
|
||||
card_type: str = ""
|
||||
found: bool = False
|
||||
confidence: str = "low"
|
||||
evidence: List[str] = field(default_factory=list)
|
||||
candidates: List[dict] = field(default_factory=list)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"found": self.found,
|
||||
"number": self.number,
|
||||
"luhn_ok": self.luhn_ok,
|
||||
"length": self.length,
|
||||
"bank": self.bank,
|
||||
"bank_source": self.bank_source,
|
||||
"expiry": self.expiry,
|
||||
"card_type": self.card_type,
|
||||
"confidence": self.confidence,
|
||||
"evidence": self.evidence,
|
||||
"candidates": self.candidates,
|
||||
}
|
||||
|
||||
|
||||
def looks_like_bank_card(text: str) -> bool:
|
||||
return any(k.lower() in text.lower() for k in BANK_KEYWORDS)
|
||||
|
||||
|
||||
def _bank_from_face(text: str) -> str:
|
||||
for name in BANK_NAMES:
|
||||
if name in text:
|
||||
return name
|
||||
# OCR 常见残缺写法
|
||||
short = {"工商": "中国工商银行", "农业": "中国农业银行", "建设": "中国建设银行",
|
||||
"招商": "招商银行", "民生": "中国民生银行", "兴业": "兴业银行",
|
||||
"浦发": "浦发银行", "交通": "交通银行", "邮政": "中国邮政储蓄银行",
|
||||
"中信": "中信银行", "光大": "中国光大银行", "华夏": "华夏银行",
|
||||
"广发": "广发银行", "平安": "平安银行",
|
||||
"重庆农商": "重庆农村商业银行", "重庆农村商业": "重庆农村商业银行",
|
||||
"三峡": "重庆三峡银行"}
|
||||
for k, v in short.items():
|
||||
if k + "银行" in text or k in text:
|
||||
return v
|
||||
return ""
|
||||
|
||||
|
||||
def _expiry(text: str) -> str:
|
||||
m = re.search(r"(0[1-9]|1[0-2])/(2\d{1,2}|9\d)", text)
|
||||
return m.group(0) if m else ""
|
||||
|
||||
|
||||
def _card_type(text: str) -> str:
|
||||
if "Credit" in text or "信用卡" in text:
|
||||
return "信用卡"
|
||||
if "Debit" in text or "借记卡" in text or "储蓄卡" in text:
|
||||
return "借记卡"
|
||||
return ""
|
||||
|
||||
|
||||
def parse(lines: Sequence[Line], full_text: str = "",
|
||||
exclude: Sequence[str] = (), rows: Optional[Sequence[str]] = None) -> BankCardResult:
|
||||
"""从银行卡那一面的 OCR 结果里抽字段。
|
||||
|
||||
rows 是「行文本」(推荐),没有时退回 full_text。
|
||||
"""
|
||||
res = BankCardResult()
|
||||
text = full_text or join_text(lines)
|
||||
if not text:
|
||||
return res
|
||||
|
||||
cands: List[CardCandidate] = card_candidates(rows if rows else text, exclude=exclude)
|
||||
if cands:
|
||||
top = cands[0]
|
||||
res.number = top.number
|
||||
res.luhn_ok = top.luhn_ok
|
||||
res.length = top.digits
|
||||
res.found = True
|
||||
res.bank = top.bank
|
||||
res.bank_source = "bin" if top.bank else ""
|
||||
res.candidates = [{"number": c.number, "luhn_ok": c.luhn_ok,
|
||||
"length": c.digits, "bank": c.bank,
|
||||
"origin": c.origin, "edits": c.edits,
|
||||
"votes": c.votes, "score": round(c.score, 2)}
|
||||
for c in cands]
|
||||
if top.origin == "repaired":
|
||||
res.evidence.append(f"卡号经 {top.edits} 位纠错后通过 Luhn 校验")
|
||||
if not top.luhn_ok:
|
||||
res.evidence.append("⚠ 卡号未通过 Luhn 校验")
|
||||
if not res.bank:
|
||||
b = _bank_from_face(text)
|
||||
if b:
|
||||
res.bank, res.bank_source = b, "face"
|
||||
res.expiry = _expiry(text)
|
||||
res.card_type = _card_type(text)
|
||||
|
||||
if not res.found:
|
||||
res.confidence = "low"
|
||||
return res
|
||||
clean_len = res.length in _VALID_BANK_LEN
|
||||
if res.luhn_ok and clean_len and res.bank:
|
||||
res.confidence = "high"
|
||||
elif res.luhn_ok and clean_len:
|
||||
res.confidence = "medium"
|
||||
else:
|
||||
res.confidence = "low"
|
||||
if not clean_len:
|
||||
res.evidence.append(f"⚠ 卡号位数 {res.length} 不在 16/18/19")
|
||||
return res
|
||||
@@ -0,0 +1,266 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""卡片区域定位:在照片里找出身份证 / 银行卡的四边形,做透视矫正。
|
||||
|
||||
一张照片里可能同时有两张卡(很多人把两张卡摆在一起拍),所以返回多个候选。
|
||||
定位失败时由上层的整图识别兜底,不影响主流程。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Optional, Sequence, Tuple
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
from .img import CARD_ASPECT, four_point_warp, order_points, quad_area, to_gray
|
||||
|
||||
|
||||
@dataclass
|
||||
class CardRegion:
|
||||
pts: np.ndarray # 4x2 原图坐标
|
||||
area: float # 像素面积
|
||||
aspect: float # 长宽比(已归一化到 >=1)
|
||||
score: float # 越像卡片分越高
|
||||
warped: Optional[np.ndarray] = None
|
||||
source: str = "contour" # contour / fallback
|
||||
|
||||
|
||||
def _aspect_score(ar: float) -> float:
|
||||
"""长宽比越接近 1.585 分越高(身份证、银行卡同尺寸)。"""
|
||||
if ar <= 0:
|
||||
return 0.0
|
||||
# 允许 1.3~1.9 的透视偏差
|
||||
dev = abs(ar - CARD_ASPECT) / CARD_ASPECT
|
||||
if dev > 0.28:
|
||||
return 0.0
|
||||
return max(0.0, 1.0 - dev / 0.28)
|
||||
|
||||
|
||||
def _rect_score(pts: np.ndarray) -> float:
|
||||
"""四个角接近直角、对边接近等长的程度。"""
|
||||
pts = order_points(pts)
|
||||
sides = []
|
||||
for i in range(4):
|
||||
sides.append(float(np.linalg.norm(pts[(i + 1) % 4] - pts[i])))
|
||||
if min(sides) <= 0:
|
||||
return 0.0
|
||||
# 对边长度比
|
||||
pair_ok = min(sides[0], sides[2]) / max(sides[0], sides[2]) * \
|
||||
min(sides[1], sides[3]) / max(sides[1], sides[3])
|
||||
# 直角性:用相邻边点积
|
||||
ang_ok = 1.0
|
||||
for i in range(4):
|
||||
a = pts[(i - 1) % 4] - pts[i]
|
||||
b = pts[(i + 1) % 4] - pts[i]
|
||||
cosv = abs(float(np.dot(a, b)) / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-9))
|
||||
ang_ok *= max(0.0, 1.0 - cosv)
|
||||
return float(max(0.0, pair_ok) * max(0.0, ang_ok) ** 0.25)
|
||||
|
||||
|
||||
def _candidate_quads(gray: np.ndarray) -> List[np.ndarray]:
|
||||
quads: List[np.ndarray] = []
|
||||
h, w = gray.shape[:2]
|
||||
scale = 1000.0 / max(h, w)
|
||||
if scale < 1.0:
|
||||
small = cv2.resize(gray, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA)
|
||||
inv = 1.0 / scale
|
||||
else:
|
||||
small, inv = gray, 1.0
|
||||
blur = cv2.GaussianBlur(small, (5, 5), 0)
|
||||
for lo, hi in ((40, 120), (80, 200)):
|
||||
edges = cv2.Canny(blur, lo, hi)
|
||||
edges = cv2.morphologyEx(edges, cv2.MORPH_CLOSE,
|
||||
cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7)))
|
||||
contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
|
||||
for c in contours:
|
||||
area = cv2.contourArea(c)
|
||||
if area < (small.shape[0] * small.shape[1]) * 0.03:
|
||||
continue
|
||||
peri = cv2.arcLength(c, True)
|
||||
for eps in (0.02, 0.035, 0.05):
|
||||
ap = cv2.approxPolyDP(c, eps * peri, True)
|
||||
if len(ap) == 4:
|
||||
quads.append(np.asarray(ap, dtype=np.float32).reshape(4, 2) * inv)
|
||||
break
|
||||
# 面积由小到大的合并去重(同一张卡的多层轮廓只留一个)
|
||||
return quads
|
||||
|
||||
|
||||
def _dedupe(regions: Sequence[CardRegion], iou_thr: float = 0.6) -> List[CardRegion]:
|
||||
kept: List[CardRegion] = []
|
||||
for r in sorted(regions, key=lambda x: -x.score):
|
||||
dup = False
|
||||
for k in kept:
|
||||
# 用外接矩形 IoU 判重
|
||||
a = cv2.boundingRect(np.asarray(r.pts, dtype=np.int32))
|
||||
b = cv2.boundingRect(np.asarray(k.pts, dtype=np.int32))
|
||||
from .img import iou_rect # noqa: PLC0415
|
||||
|
||||
if iou_rect(a, b) > iou_thr:
|
||||
dup = True
|
||||
break
|
||||
if not dup:
|
||||
kept.append(r)
|
||||
return kept
|
||||
|
||||
|
||||
def find_cards(img: np.ndarray, max_cards: int = 3,
|
||||
warp_width: int = 0) -> List[CardRegion]:
|
||||
"""在照片里定位卡片,返回按可信度排序的区域(含透视矫正图)。"""
|
||||
gray = to_gray(img)
|
||||
quads = _candidate_quads(gray)
|
||||
cands: List[CardRegion] = []
|
||||
for q in quads:
|
||||
ar_raw = max(quad_area(q), 1e-6)
|
||||
ar = 0.0
|
||||
pts = order_points(q)
|
||||
w1 = float(np.linalg.norm(pts[1] - pts[0]))
|
||||
w2 = float(np.linalg.norm(pts[2] - pts[3]))
|
||||
h1 = float(np.linalg.norm(pts[3] - pts[0]))
|
||||
h2 = float(np.linalg.norm(pts[2] - pts[1]))
|
||||
ww, hh = (w1 + w2) / 2.0, (h1 + h2) / 2.0
|
||||
if min(ww, hh) > 0:
|
||||
ar = max(ww / hh, hh / ww)
|
||||
score = _aspect_score(ar) * _rect_score(pts)
|
||||
if score <= 0.05:
|
||||
continue
|
||||
cands.append(CardRegion(pts=pts, area=ar_raw, aspect=ar, score=sqrt_(score)))
|
||||
cands = _dedupe(cands)
|
||||
out: List[CardRegion] = []
|
||||
for r in cands[:max_cards]:
|
||||
r.warped, _ = four_point_warp(img, r.pts, width=warp_width or 0)
|
||||
out.append(r)
|
||||
return out
|
||||
|
||||
|
||||
def sqrt_(x: float) -> float:
|
||||
return float(np.sqrt(max(0.0, x)))
|
||||
|
||||
|
||||
def expand_pts(pts: np.ndarray, ratio: float, shape: Tuple[int, int]) -> np.ndarray:
|
||||
"""把四边形向外扩一点(卡片边缘会把字裁掉时用)。"""
|
||||
c = pts.mean(axis=0)
|
||||
return (pts - c) * (1.0 + ratio) + c
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 色块兜底定位
|
||||
# Canny 找四边形要求卡边基本连续,反光/压边/桌面同色时常直接失败(实测有的卡图
|
||||
# 一张都找不到)。卡面通常是一整块同色区域,所以再补两条更宽松的路子:
|
||||
# 1) 量化主色相 → 色块掩膜 → 最大轮廓 → 最小外接矩形;
|
||||
# 2) Canny 边缘闭运算桥接反光断口 → 最大几个轮廓 → 最小外接矩形。
|
||||
|
||||
def _mask_card_rects(small: np.ndarray) -> List[Tuple]:
|
||||
hsv = cv2.cvtColor(small, cv2.COLOR_BGR2HSV)
|
||||
h, w = small.shape[:2]
|
||||
sel = (hsv[..., 1] > 60) & (hsv[..., 2] > 25)
|
||||
if int(sel.sum()) < h * w * 0.02:
|
||||
return []
|
||||
hue = hsv[..., 0][sel].astype(np.int32)
|
||||
hist = np.bincount(hue // 15, minlength=12)[:12]
|
||||
out: List[Tuple] = []
|
||||
for t in np.argsort(hist)[::-1][:2]:
|
||||
if hist[t] < h * w * 0.01:
|
||||
continue
|
||||
lo = int(t * 15)
|
||||
m = cv2.inRange(hsv, (lo, 60, 25), (lo + 14, 255, 255))
|
||||
m = cv2.morphologyEx(m, cv2.MORPH_CLOSE, np.ones((41, 41), np.uint8))
|
||||
m = cv2.morphologyEx(m, cv2.MORPH_OPEN, np.ones((11, 11), np.uint8))
|
||||
cnts, _ = cv2.findContours(m, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||
if not cnts:
|
||||
continue
|
||||
c = max(cnts, key=cv2.contourArea)
|
||||
if cv2.contourArea(c) < h * w * 0.05:
|
||||
continue
|
||||
out.append(cv2.minAreaRect(c))
|
||||
return out
|
||||
|
||||
|
||||
def _edge_card_rects(small: np.ndarray) -> List[Tuple]:
|
||||
h, w = small.shape[:2]
|
||||
edges = cv2.Canny(cv2.GaussianBlur(to_gray(small), (5, 5), 0), 40, 120)
|
||||
# 大核闭运算把反光造成的断口接上,否则轮廓不闭合
|
||||
edges = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, np.ones((15, 15), np.uint8))
|
||||
cnts, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||
out: List[Tuple] = []
|
||||
for c in sorted(cnts, key=cv2.contourArea, reverse=True)[:5]:
|
||||
if cv2.contourArea(c) < h * w * 0.05:
|
||||
continue
|
||||
out.append(cv2.minAreaRect(c))
|
||||
return out
|
||||
|
||||
|
||||
def _warp_card(img: np.ndarray, rect: Tuple, width: int) -> np.ndarray:
|
||||
"""按最小外接矩形矫正,并保证「卡长边 → 图宽」(否则会横拉成瘦长条)。"""
|
||||
(cx, cy), (rw, rh), ang = rect
|
||||
box = cv2.boxPoints(((cx, cy), (rw, rh), ang)).astype(np.float32)
|
||||
pts = order_points(box)
|
||||
e_w = float(np.linalg.norm(pts[1] - pts[0])) # 将映射到「宽」的那条边
|
||||
e_h = float(np.linalg.norm(pts[3] - pts[0])) # 将映射到「高」的那条边
|
||||
if e_w < e_h: # 横边是短边 → 卡长边在竖直方向
|
||||
pts = np.roll(pts, -1, axis=0)
|
||||
w = int(width)
|
||||
h = int(round(width / CARD_ASPECT))
|
||||
m = cv2.getPerspectiveTransform(
|
||||
pts, np.float32([[0, 0], [w - 1, 0], [w - 1, h - 1], [0, h - 1]]))
|
||||
return cv2.warpPerspective(img, m, (w, h), flags=cv2.INTER_CUBIC)
|
||||
|
||||
|
||||
def find_card_color(img: np.ndarray, warp_width: int = 1712) -> Optional[CardRegion]:
|
||||
"""色块/边缘兜底找卡(find_cards 失败时用),返回已矫正的卡图。
|
||||
|
||||
比例按 85.6:54 还原,长边对应图宽;方向(上下/左右)不在这里判,由调用方
|
||||
根据 OCR 结果决定,避免再引入一次不可靠的方向猜测。
|
||||
"""
|
||||
h, w = img.shape[:2]
|
||||
scale = 1000.0 / max(h, w)
|
||||
if scale < 1.0:
|
||||
small = cv2.resize(img, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA)
|
||||
inv = 1.0 / scale
|
||||
else:
|
||||
small, inv = img, 1.0
|
||||
rects = _mask_card_rects(small) + _edge_card_rects(small)
|
||||
best, best_score = None, 0.0
|
||||
for rect in rects:
|
||||
(cx, cy), (rw, rh), ang = rect
|
||||
if min(rw, rh) <= 0:
|
||||
continue
|
||||
# 只按长宽比评分,不奖励面积:边缘法经常把「卡+桌面」框成一个同样比例的大矩形,
|
||||
# 按面积优选就会选中那个,矫正后的卡反而变小、卡号更难认。
|
||||
score = _aspect_score(max(rw, rh) / min(rw, rh))
|
||||
if score > best_score:
|
||||
best, best_score = rect, score
|
||||
if best is None:
|
||||
return None
|
||||
(cx, cy), (rw, rh), ang = best
|
||||
rect_full = ((cx * inv, cy * inv), (rw * inv, rh * inv), ang)
|
||||
pts = order_points(cv2.boxPoints(rect_full).astype(np.float32))
|
||||
region = CardRegion(pts=pts, area=rw * rh * inv * inv,
|
||||
aspect=max(rw, rh) / min(rw, rh), score=best_score,
|
||||
source="color")
|
||||
region.warped = _warp_card(img, rect_full, warp_width)
|
||||
return region
|
||||
|
||||
|
||||
def _digit_score(lines) -> int:
|
||||
n = sum(1 for x in lines for ch in x.text if ch.isdigit())
|
||||
rows = sum(1 for x in lines if sum(ch.isdigit() for ch in x.text) >= 4)
|
||||
return n + 5 * rows
|
||||
|
||||
|
||||
def locate_bank_card(img: np.ndarray, warp_width: int = 1712) -> Optional[np.ndarray]:
|
||||
"""色块兜底找卡 + 用 OCR 结果判方向,返回「摆正的卡图」;找不到返回 None。"""
|
||||
region = find_card_color(img, warp_width=warp_width)
|
||||
if region is None or region.warped is None or region.warped.size == 0:
|
||||
return None
|
||||
from .engine import lines as ocr_lines # noqa: PLC0415 避免循环引用
|
||||
|
||||
card = region.warped
|
||||
scored = [(_digit_score(ocr_lines(np.ascontiguousarray(np.rot90(card, k)))), k)
|
||||
for k in (0, 2)]
|
||||
scored.sort(reverse=True)
|
||||
if scored[0][0] <= 0: # 0/180 都读不到数字,说明卡是横躺的
|
||||
scored = [(_digit_score(ocr_lines(np.ascontiguousarray(np.rot90(card, k)))), k)
|
||||
for k in (1, 3)]
|
||||
scored.sort(reverse=True)
|
||||
k = scored[0][1]
|
||||
return np.ascontiguousarray(np.rot90(card, k))
|
||||
@@ -0,0 +1,110 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""命令行:scan / image / review / verify"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from .match import check_persons, print_report
|
||||
from .pipeline import analyze_folder, analyze_image, summary_table
|
||||
from .review import (load_persons, load_truth_workbook, print_verify, verify_workbook,
|
||||
write_review_workbook)
|
||||
|
||||
|
||||
def _setup_stdout() -> None:
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
_setup_stdout()
|
||||
logging.basicConfig(level=logging.INFO, format="%(message)s", stream=sys.stdout)
|
||||
ap = argparse.ArgumentParser(prog="cardocr", description="身份证 / 银行卡照片识别")
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
|
||||
def common(sp):
|
||||
sp.add_argument("--json", default="", help="结果写入 JSON 文件")
|
||||
sp.add_argument("--xlsx", default="", help="结果写成核对工作簿(含待填列)")
|
||||
sp.add_argument("--mark", default="", help="标注图输出目录")
|
||||
sp.add_argument("--no-extra", action="store_true", help="关闭卡号多遍增强识别(更快)")
|
||||
sp.add_argument("--fast", action="store_true", help="只跑粗识别(最快,精度下降)")
|
||||
sp.add_argument("--limit", type=int, default=0, help="每个目录最多取几张图(0=全部)")
|
||||
|
||||
sp_scan = sub.add_parser("scan", help="按「姓名/图片」目录批量识别")
|
||||
sp_scan.add_argument("root", help="照片根目录")
|
||||
common(sp_scan)
|
||||
|
||||
sp_one = sub.add_parser("image", help="识别单张图片")
|
||||
sp_one.add_argument("path", help="图片路径")
|
||||
sp_one.add_argument("--name", default="", help="预期姓名(用于校验身份证姓名)")
|
||||
common(sp_one)
|
||||
|
||||
sp_rev = sub.add_parser("review", help="把 JSON 结果导出成核对工作簿")
|
||||
sp_rev.add_argument("--json", required=True, help="scan 输出的 JSON")
|
||||
sp_rev.add_argument("--out", required=True, help="输出的 xlsx 路径")
|
||||
|
||||
sp_ver = sub.add_parser("verify", help="回读填好的核对工作簿,算准确率")
|
||||
sp_ver.add_argument("xlsx", help="核对工作簿路径")
|
||||
|
||||
sp_chk = sub.add_parser("check", help="用人工填写的正确值做「命中分析」")
|
||||
sp_chk.add_argument("--json", required=True, help="scan 输出的 JSON")
|
||||
sp_chk.add_argument("--truth", required=True, help="填好的核对工作簿 xlsx")
|
||||
sp_chk.add_argument("--out", default="", help="命中分析结果写入 JSON")
|
||||
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
if args.cmd == "scan":
|
||||
persons = analyze_folder(args.root, mark_dir=args.mark or None,
|
||||
extra_passes=not args.no_extra, fast=args.fast,
|
||||
limit=args.limit)
|
||||
print(summary_table(persons))
|
||||
payload = {"root": str(Path(args.root).resolve()), "persons": persons}
|
||||
if args.json:
|
||||
Path(args.json).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(args.json).write_text(json.dumps(payload, ensure_ascii=False, indent=1),
|
||||
encoding="utf-8")
|
||||
print(f"\n已写入 {args.json}")
|
||||
if args.xlsx:
|
||||
write_review_workbook(persons, args.xlsx, source_root=payload["root"])
|
||||
print(f"\n核对工作簿已写入 {args.xlsx}")
|
||||
return 0
|
||||
|
||||
if args.cmd == "image":
|
||||
res = analyze_image(args.path, expected_name=args.name, mark_dir=args.mark or None,
|
||||
extra_passes=not args.no_extra, fast=args.fast)
|
||||
print(json.dumps(res, ensure_ascii=False, indent=1))
|
||||
if args.json:
|
||||
Path(args.json).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(args.json).write_text(json.dumps({"images": [res]}, ensure_ascii=False,
|
||||
indent=1), encoding="utf-8")
|
||||
return 0
|
||||
|
||||
if args.cmd == "review":
|
||||
persons = load_persons(args.json)
|
||||
write_review_workbook(persons, args.out)
|
||||
print(f"核对工作簿已写入 {args.out}({len(persons)} 行)")
|
||||
return 0
|
||||
|
||||
if args.cmd == "check":
|
||||
persons = load_persons(args.json)
|
||||
truth = load_truth_workbook(args.truth)
|
||||
rows = check_persons(persons, truth)
|
||||
print(print_report(rows))
|
||||
if args.out:
|
||||
Path(args.out).write_text(json.dumps(rows, ensure_ascii=False, indent=1),
|
||||
encoding="utf-8")
|
||||
print(f"\n命中分析已写入 {args.out}")
|
||||
return 0
|
||||
|
||||
result = verify_workbook(args.xlsx)
|
||||
print_verify(result)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,206 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""OCR 引擎封装(RapidOCR / onnxruntime,纯离线,模型随包)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
from dataclasses import dataclass
|
||||
from typing import Iterable, List, Optional
|
||||
|
||||
import numpy as np
|
||||
|
||||
logger = logging.getLogger("cardocr")
|
||||
|
||||
_ENGINE = None
|
||||
_LOCK = threading.Lock()
|
||||
|
||||
|
||||
@dataclass
|
||||
class Line:
|
||||
"""一段识别文本 + 图内像素框。"""
|
||||
|
||||
text: str
|
||||
left: int
|
||||
top: int
|
||||
width: int
|
||||
height: int
|
||||
score: float
|
||||
|
||||
@property
|
||||
def right(self) -> int:
|
||||
return self.left + self.width
|
||||
|
||||
@property
|
||||
def bottom(self) -> int:
|
||||
return self.top + self.height
|
||||
|
||||
@property
|
||||
def x_mid(self) -> float:
|
||||
return self.left + self.width / 2.0
|
||||
|
||||
@property
|
||||
def y_mid(self) -> float:
|
||||
return self.top + self.height / 2.0
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {"text": self.text, "left": self.left, "top": self.top,
|
||||
"width": self.width, "height": self.height,
|
||||
"score": round(float(self.score), 3)}
|
||||
|
||||
|
||||
def engine_available() -> bool:
|
||||
try:
|
||||
import importlib.util # noqa: PLC0415
|
||||
|
||||
return importlib.util.find_spec("rapidocr") is not None
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
def _silence_rapidocr() -> None:
|
||||
"""把 RapidOCR 自带的控制台日志压到 ERROR。
|
||||
|
||||
RapidOCR 在 import 时给 "RapidOCR" logger 挂了 stderr handler,识别不到文字等
|
||||
WARNING 会直接写 stderr,被执行机当成 ERROR 刷进运行日志(`[ERROR] [WARNING] ...`)。
|
||||
这里只压掉 WARNING 及以下的噪音,ERROR 仍然保留。
|
||||
"""
|
||||
lg = logging.getLogger("RapidOCR")
|
||||
lg.setLevel(logging.ERROR)
|
||||
lg.propagate = False
|
||||
|
||||
|
||||
def _get_engine():
|
||||
global _ENGINE
|
||||
if _ENGINE is not None:
|
||||
return _ENGINE
|
||||
with _LOCK:
|
||||
if _ENGINE is not None:
|
||||
return _ENGINE
|
||||
from rapidocr import RapidOCR # noqa: PLC0415
|
||||
|
||||
# 固定线程数:默认会按核数开线程,在共享办公机上反而抖动严重(同一张图 2s~13s)
|
||||
params = {
|
||||
"Global.log_level": "ERROR",
|
||||
"EngineConfig.onnxruntime.intra_op_num_threads": 4,
|
||||
"EngineConfig.onnxruntime.inter_op_num_threads": 1,
|
||||
}
|
||||
try:
|
||||
_ENGINE = RapidOCR(params=params)
|
||||
except Exception: # noqa: BLE001 旧版本不支持 params
|
||||
_ENGINE = RapidOCR()
|
||||
_silence_rapidocr()
|
||||
return _ENGINE
|
||||
|
||||
|
||||
def lines(img: np.ndarray, min_score: float = 0.0) -> List[Line]:
|
||||
"""对一张 BGR / 灰度图做识别,返回按阅读顺序排序的文本行。"""
|
||||
if img is None or img.size == 0:
|
||||
return []
|
||||
if img.ndim == 3:
|
||||
bgr = img
|
||||
else:
|
||||
bgr = np.dstack([img, img, img])
|
||||
engine = _get_engine()
|
||||
# 显式给全开关:RapidOCR 会把上次调用的开关记在实例上,写错一次后面全错
|
||||
out = engine(np.ascontiguousarray(bgr), use_det=True, use_cls=True, use_rec=True)
|
||||
boxes = getattr(out, "boxes", None)
|
||||
txts = getattr(out, "txts", None)
|
||||
scores = getattr(out, "scores", None)
|
||||
if boxes is None or txts is None:
|
||||
return []
|
||||
res: List[Line] = []
|
||||
for i, (box, text) in enumerate(zip(boxes, txts)):
|
||||
text = str(text or "").strip()
|
||||
if not text:
|
||||
continue
|
||||
score = float(scores[i]) if scores is not None and i < len(scores) else 1.0
|
||||
if score < min_score:
|
||||
continue
|
||||
pts = np.asarray(box, dtype=np.float32).reshape(-1, 2)
|
||||
l, t = int(np.floor(pts[:, 0].min())), int(np.floor(pts[:, 1].min()))
|
||||
r, b = int(np.ceil(pts[:, 0].max())), int(np.ceil(pts[:, 1].max()))
|
||||
if r <= l or b <= t:
|
||||
continue
|
||||
res.append(Line(text=text, left=l, top=t, width=r - l, height=b - t, score=score))
|
||||
res.sort(key=lambda x: (x.top // 10, x.left))
|
||||
return res
|
||||
|
||||
|
||||
def text_line(img: np.ndarray) -> str:
|
||||
"""把「只含一行文字」的裁剪图直接送进识别网络(跳过检测网络,快约 10 倍)。
|
||||
|
||||
卡号带这种窄条图只有一行字,检测/分类没有意义,跳过能省掉一次 1~5s 的推理。
|
||||
"""
|
||||
if img is None or img.size == 0:
|
||||
return ""
|
||||
if img.ndim == 2:
|
||||
bgr = np.dstack([img, img, img])
|
||||
else:
|
||||
bgr = img
|
||||
engine = _get_engine()
|
||||
try:
|
||||
try:
|
||||
out = engine(np.ascontiguousarray(bgr), use_det=False, use_cls=False)
|
||||
finally:
|
||||
# 这两个开关会写进引擎实例,必须恢复,否则后面的整图识别会全部变成「无框」
|
||||
engine.update_params(use_det=True, use_cls=True, use_rec=True)
|
||||
except TypeError: # 老版本不支持这些开关
|
||||
return join_text(lines(img))
|
||||
except Exception: # noqa: BLE001
|
||||
return join_text(lines(img))
|
||||
txts = getattr(out, "txts", None)
|
||||
if not txts:
|
||||
return ""
|
||||
return " ".join(str(t) for t in txts if t)
|
||||
|
||||
|
||||
def join_text(items: List[Line]) -> str:
|
||||
"""把多行文本拼成一段(换行变空格,便于人看 / 关键词判断,不用于抓号码)。"""
|
||||
return " ".join(x.text for x in items)
|
||||
|
||||
|
||||
def row_texts(items: List[Line], y_tol: float = 0.75, gap_factor: float = 1.6) -> List[str]:
|
||||
"""把同一视觉行上的文字框合并成「行文本」,再按横向间距切成若干段。
|
||||
|
||||
抓号码必须在「行」粒度上做:整图拼接会把相邻两行的数字连成一个假号码
|
||||
(例如卡号 5443 后面紧跟有效期里的 2000,会被读成 19 位)。
|
||||
"""
|
||||
if not items:
|
||||
return []
|
||||
med_h = float(np.median([x.height for x in items]))
|
||||
clusters: List[List[Line]] = []
|
||||
for ln in sorted(items, key=lambda x: x.y_mid):
|
||||
for cl in clusters:
|
||||
if abs(ln.y_mid - cl[-1].y_mid) <= y_tol * max(med_h, ln.height):
|
||||
cl.append(ln)
|
||||
break
|
||||
else:
|
||||
clusters.append([ln])
|
||||
rows: List[str] = []
|
||||
for cl in clusters:
|
||||
cl.sort(key=lambda x: x.left)
|
||||
parts: List[str] = [cl[0].text]
|
||||
last = cl[0]
|
||||
for ln in cl[1:]:
|
||||
if ln.left - last.right <= gap_factor * med_h:
|
||||
parts[-1] = parts[-1] + " " + ln.text
|
||||
else:
|
||||
parts.append(ln.text)
|
||||
last = ln
|
||||
rows.extend(parts)
|
||||
return rows
|
||||
|
||||
|
||||
def row_texts_multi(views: Iterable) -> List[str]:
|
||||
"""多个视图的行文本汇总(每个视图单独分行,避免跨卡片串号)。"""
|
||||
out: List[str] = []
|
||||
for v in views:
|
||||
out.extend(row_texts(v.lines))
|
||||
return out
|
||||
|
||||
|
||||
|
||||
def load(path: str) -> Optional[np.ndarray]:
|
||||
from .img import imread # noqa: PLC0415
|
||||
|
||||
return imread(path)
|
||||
@@ -0,0 +1,520 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""浮雕/反光银行卡号增强识别(卡号带定位 + 4 位分组识别 + Luhn 裁决)。
|
||||
|
||||
为什么单独一层:普通整图 OCR 会把 16 位卡号当成「一行长文本」送进识别网络,
|
||||
而识别网络输入宽度有限(约 320px),16 位挤在一起每个字只剩十几像素,必然丢字;
|
||||
浮雕数字(卡面暗、字是同色凸起)又会和背景花纹混在一起,检测网络经常直接看不见。
|
||||
|
||||
这一层不改模型,只改「怎么喂」:
|
||||
1. 用 MSER 找到「一排字高一致的大字」,定位卡号带(它比背景花纹更成块);
|
||||
多行候选按「跨度 + 字高」排序,再用一次便宜的试读挑出真正能读出 4 位的那条;
|
||||
2. 按卡片宽度先验把卡号带切成 4 组,每组左右微调,挑「能稳定读出 4 位」的窗口;
|
||||
3. 每组在多路增强(灰度/均衡/CLAHE/梯度/形态学梯度)上各识别一次,逐位投票;
|
||||
4. 用 Luhn + 位数 + BIN/卡面银行 做裁决;投票有分歧时在「易混数字」里做
|
||||
代价递增的有限搜索,只返回通过 Luhn 的候选,并按「改动代价」排序。
|
||||
|
||||
原则:宁可返回候选 + 需人工,也不硬猜一个通过不了校验的号码。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, List, Optional, Sequence, Tuple
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
from .engine import text_line
|
||||
from .img import imread, to_gray
|
||||
from .validators import bin_bank, digitize, luhn_ok, prefix_ok
|
||||
|
||||
logger = logging.getLogger("cardocr")
|
||||
|
||||
# 卡号带的 y 区间先验(标准卡面比例):卡号一般在卡高 40%~92% 处(含拍歪/留白)
|
||||
_BAND_Y_RATIO = (0.40, 0.92)
|
||||
# 卡号横向跨度先验(占卡宽比例),按可能性排序;主假设失败才试后面的
|
||||
_SPAN_RATIOS = ((0.045, 0.955), (0.060, 0.920), (0.075, 0.900))
|
||||
# 分组窗口的左右微调量(相对组宽)
|
||||
_OFFSETS = (0.0, 0.10, -0.10, 0.20, -0.20)
|
||||
# 识别通路:灰度 / 全局均衡 / CLAHE / 梯度 / 形态学梯度(后两者对浮雕边缘最敏感)
|
||||
_VARIANTS = ("gray", "eq", "clahe", "grad", "morph")
|
||||
_PROBE = ("eq", "morph") # 挑窗口时只跑这两路,省时间
|
||||
_MAX_CANDIDATES = 5
|
||||
_MAX_COST = 5 # 候选最多容许的「改动代价」总和
|
||||
_MAX_NODES = 300000 # 搜索节点上限,防病态图卡死
|
||||
_MAX_BANDS = 3
|
||||
|
||||
# 浮雕数字的易混对:反光会把 6 认成 8、0 认成 9、7 认成 2、5 认成 6
|
||||
_EMBOSS_CONFUSION: Dict[str, str] = {
|
||||
"0": "089", "1": "17", "2": "27", "3": "38", "4": "4",
|
||||
"5": "56", "6": "658", "7": "712", "8": "8630", "9": "904",
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class GroupRead:
|
||||
"""一个 4 位分组的识别情况。"""
|
||||
|
||||
rect: Tuple[int, int, int, int] # x1, y1, x2, y2
|
||||
offset: float # 相对基线的微调量(组宽倍数)
|
||||
reads: Dict[str, str] = field(default_factory=dict) # 通路 → 数字串
|
||||
digits: str = "" # 逐位投票结果
|
||||
votes: List[Dict[str, int]] = field(default_factory=list)
|
||||
|
||||
def options(self, i: int) -> List[Tuple[str, int, int]]:
|
||||
"""第 i 位的候选 (数字, 改动代价, 票数),按「代价低、票数高」排序。"""
|
||||
votes = self.votes[i] if i < len(self.votes) else {}
|
||||
if not votes:
|
||||
return [(d, 3, 0) for d in "0123456789"]
|
||||
top = max(votes.items(), key=lambda kv: (kv[1], kv[0]))[0]
|
||||
alts = _EMBOSS_CONFUSION.get(top, top)
|
||||
pool = set(votes) | set(alts) | {top}
|
||||
out: List[Tuple[str, int, int]] = []
|
||||
for d in pool:
|
||||
if d == top:
|
||||
cost = 0
|
||||
elif d in votes:
|
||||
cost = 1
|
||||
elif d in alts:
|
||||
cost = 2
|
||||
else:
|
||||
cost = 3
|
||||
out.append((d, cost, votes.get(d, 0)))
|
||||
out.sort(key=lambda o: (o[1], -o[2], o[0]))
|
||||
return out
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {"rect": list(self.rect), "offset": round(self.offset, 3),
|
||||
"digits": self.digits, "reads": self.reads,
|
||||
"votes": [dict(v) for v in self.votes]}
|
||||
|
||||
|
||||
@dataclass
|
||||
class NumberReading:
|
||||
number: str = ""
|
||||
luhn_ok: bool = False
|
||||
length: int = 0
|
||||
bank: str = ""
|
||||
confidence: str = "low" # high / medium / low
|
||||
status: str = "failed" # ok / candidate / failed
|
||||
band: Tuple[int, int, int, int] = (0, 0, 0, 0)
|
||||
groups: List[GroupRead] = field(default_factory=list)
|
||||
candidates: List[dict] = field(default_factory=list)
|
||||
elapsed_s: float = 0.0
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {"number": self.number, "luhn_ok": self.luhn_ok,
|
||||
"length": self.length, "bank": self.bank,
|
||||
"confidence": self.confidence, "status": self.status,
|
||||
"band": list(self.band),
|
||||
"groups": [g.to_dict() for g in self.groups],
|
||||
"candidates": self.candidates,
|
||||
"elapsed_s": round(self.elapsed_s, 2)}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 卡号带定位
|
||||
def _mser_boxes(gray: np.ndarray) -> List[Tuple[int, int, int, int]]:
|
||||
h, w = gray.shape[:2]
|
||||
mser = cv2.MSER_create()
|
||||
mser.setMinArea(max(800, int(h * w * 0.0004)))
|
||||
mser.setMaxArea(int(h * w * 0.08))
|
||||
mser.setDelta(5)
|
||||
try:
|
||||
_, bboxes = mser.detectRegions(gray)
|
||||
except cv2.error: # 个别 OpenCV 构建没编 MSER
|
||||
return []
|
||||
boxes: List[Tuple[int, int, int, int]] = []
|
||||
for (x, y, bw, bh) in bboxes:
|
||||
if bh < h * 0.030 or bh > h * 0.130:
|
||||
continue
|
||||
if bw < bh * 0.15 or bw > bh * 1.80:
|
||||
continue
|
||||
boxes.append((int(x), int(y), int(bw), int(bh)))
|
||||
# MSER 会对同一个字给出多个尺度,按中心点去重(保留面积最大的)
|
||||
boxes.sort(key=lambda b: -b[2] * b[3])
|
||||
keep: List[Tuple[int, int, int, int]] = []
|
||||
tol = max(12, int(min(h, w) * 0.02))
|
||||
for b in boxes:
|
||||
cx, cy = b[0] + b[2] / 2.0, b[1] + b[3] / 2.0
|
||||
if any(abs(cx - (k[0] + k[2] / 2.0)) < tol
|
||||
and abs(cy - (k[1] + k[3] / 2.0)) < tol for k in keep):
|
||||
continue
|
||||
keep.append(b)
|
||||
return keep
|
||||
|
||||
|
||||
def _cluster_rows(boxes: Sequence[Tuple[int, int, int, int]]):
|
||||
if not boxes:
|
||||
return []
|
||||
items = sorted(boxes, key=lambda b: b[1] + b[3] / 2.0)
|
||||
rows: List[List[Tuple[int, int, int, int]]] = []
|
||||
for b in items:
|
||||
yc = b[1] + b[3] / 2.0
|
||||
for row in rows:
|
||||
ref_c = float(np.median([x[1] + x[3] / 2.0 for x in row]))
|
||||
ref_h = float(np.median([x[3] for x in row]))
|
||||
if abs(yc - ref_c) < ref_h * 0.60 and 0.55 < b[3] / ref_h < 1.8:
|
||||
row.append(b)
|
||||
break
|
||||
else:
|
||||
rows.append([b])
|
||||
return rows
|
||||
|
||||
|
||||
def find_number_bands(gray: np.ndarray, limit: int = _MAX_BANDS
|
||||
) -> List[Tuple[int, int, int, int]]:
|
||||
"""定位卡号带的若干候选(按可能性排序),返回 [(x1, y1, x2, y2), ...]。
|
||||
|
||||
返回的 x 跨度是 MSER 行自己的实际范围(不再写死整图 3%~97%),
|
||||
这样卡片没占满画面、或者只是裁出来的卡图,分组窗口都能对得上。
|
||||
"""
|
||||
if gray is None or gray.size == 0:
|
||||
return []
|
||||
h, w = gray.shape[:2]
|
||||
scale = 1400.0 / max(h, w)
|
||||
small = gray if scale >= 1.0 else cv2.resize(gray, None, fx=scale, fy=scale,
|
||||
interpolation=cv2.INTER_AREA)
|
||||
rows = _cluster_rows(_mser_boxes(small))
|
||||
scraped = []
|
||||
for row in rows:
|
||||
if len(row) < 3:
|
||||
continue
|
||||
x1 = min(b[0] for b in row)
|
||||
x2 = max(b[0] + b[2] for b in row)
|
||||
span = (x2 - x1) / float(small.shape[1])
|
||||
if span < 0.45:
|
||||
continue
|
||||
yc = float(np.median([b[1] + b[3] / 2.0 for b in row])) / small.shape[0]
|
||||
if not (_BAND_Y_RATIO[0] <= yc <= _BAND_Y_RATIO[1]):
|
||||
continue
|
||||
med_h = float(np.median([b[3] for b in row]))
|
||||
score = 2.0 * span + min(len(row), 12) / 12.0 + 12.0 * (med_h / small.shape[0])
|
||||
scraped.append((score, float(np.median([b[1] + b[3] / 2.0 for b in row])), med_h,
|
||||
float(x1), float(x2)))
|
||||
scraped.sort(key=lambda x: -x[0])
|
||||
|
||||
inv = 1.0 / scale if scale < 1.0 else 1.0
|
||||
out: List[Tuple[int, int, int, int]] = []
|
||||
centers: List[float] = []
|
||||
for _score, yc_s, med_h_s, x1_s, x2_s in scraped:
|
||||
yc, med_h = yc_s * inv, med_h_s * inv
|
||||
if any(abs(yc - c) < max(med_h * 0.6, 8) for c in centers):
|
||||
continue
|
||||
# 卡号字高一般占卡高 6%~9%;MSER 常把上下花纹并进来,这里收到上限,避免竖条太高
|
||||
half = min(med_h * 0.70, h * 0.050)
|
||||
half = max(half, h * 0.030)
|
||||
y1 = max(0, int(yc - half))
|
||||
y2 = min(h, int(yc + half))
|
||||
# x 跨度用 MSER 行自己的实际范围(原来写死 3%~97%,卡片没占满画面时分组窗口会整体错位)
|
||||
x1, x2 = int(x1_s * inv), int(x2_s * inv)
|
||||
pad = max(4, int((x2 - x1) * 0.04))
|
||||
out.append((max(0, x1 - pad), y1, min(w, x2 + pad), y2))
|
||||
centers.append(yc)
|
||||
if len(out) >= limit:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 分组识别
|
||||
def _variant(name: str, crop: np.ndarray) -> Optional[np.ndarray]:
|
||||
if name == "gray":
|
||||
return crop
|
||||
if name == "eq":
|
||||
return cv2.equalizeHist(crop)
|
||||
if name == "clahe":
|
||||
try:
|
||||
return cv2.createCLAHE(3.0, (8, 8)).apply(crop)
|
||||
except Exception: # noqa: BLE001
|
||||
return cv2.equalizeHist(crop)
|
||||
if name == "grad":
|
||||
gx = np.abs(cv2.Sobel(crop, cv2.CV_32F, 1, 0, ksize=3))
|
||||
gy = np.abs(cv2.Sobel(crop, cv2.CV_32F, 0, 1, ksize=3))
|
||||
return cv2.normalize(cv2.magnitude(gx, gy), None, 0, 255,
|
||||
cv2.NORM_MINMAX).astype(np.uint8)
|
||||
if name == "morph":
|
||||
big = cv2.resize(crop, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
|
||||
return cv2.morphologyEx(big, cv2.MORPH_GRADIENT, np.ones((3, 3), np.uint8))
|
||||
return None
|
||||
|
||||
|
||||
def _read_crop(gray: np.ndarray, rect: Tuple[int, int, int, int],
|
||||
variants: Sequence[str]) -> Dict[str, str]:
|
||||
h, w = gray.shape[:2]
|
||||
x1, y1, x2, y2 = rect
|
||||
x1, y1 = max(0, x1), max(0, y1)
|
||||
x2, y2 = min(w, x2), min(h, y2)
|
||||
if x2 - x1 < 20 or y2 - y1 < 20:
|
||||
return {}
|
||||
crop = gray[y1:y2, x1:x2]
|
||||
reads: Dict[str, str] = {}
|
||||
for name in variants:
|
||||
img = _variant(name, crop)
|
||||
if img is not None:
|
||||
reads[name], _ = digitize(text_line(img))
|
||||
return reads
|
||||
|
||||
|
||||
def _vote(reads: Dict[str, str]) -> Tuple[str, List[Dict[str, int]]]:
|
||||
"""逐位投票:只采纳「正好 4 位」的识别结果。"""
|
||||
good = [v for v in reads.values() if len(v) == 4]
|
||||
votes: List[Dict[str, int]] = [{} for _ in range(4)]
|
||||
for s in good:
|
||||
for i, ch in enumerate(s):
|
||||
votes[i][ch] = votes[i].get(ch, 0) + 1
|
||||
digits = "".join(
|
||||
max(v.items(), key=lambda kv: (kv[1], kv[0]))[0] if v else "0" for v in votes)
|
||||
return digits, votes
|
||||
|
||||
|
||||
def _pick_group(gray: np.ndarray, xa: int, xb: int, y1: int, y2: int) -> GroupRead:
|
||||
"""在 [xa, xb] 附近微调窗口位置,选出「最像一组 4 位数字」的窗口。"""
|
||||
gw = max(60, xb - xa)
|
||||
best_score, best_ratio, best_rect = -1e9, 0.0, (xa, y1, xb, y2)
|
||||
# 先试基线窗口:形态学梯度能读出 4 位就直接用(多数分组都命中,省一轮扫描)
|
||||
if len(_read_crop(gray, best_rect, ("morph",)).get("morph", "")) == 4:
|
||||
g = GroupRead(rect=best_rect, offset=0.0)
|
||||
g.reads = _read_crop(gray, g.rect, _VARIANTS)
|
||||
g.digits, g.votes = _vote(g.reads)
|
||||
return g
|
||||
for k, ratio in enumerate(_OFFSETS):
|
||||
d = int(round(gw * ratio))
|
||||
rect = (xa + d, y1, xb + d, y2)
|
||||
probe = _read_crop(gray, rect, _PROBE)
|
||||
exact = sum(1 for v in probe.values() if len(v) == 4)
|
||||
score = 2.0 * exact - 0.3 * abs(k)
|
||||
if score > best_score:
|
||||
best_score, best_ratio, best_rect = score, ratio, rect
|
||||
if exact >= 2: # 两路都稳定读出同一组 4 位,不用再试别的偏移
|
||||
break
|
||||
g = GroupRead(rect=best_rect, offset=best_ratio)
|
||||
g.reads = _read_crop(gray, g.rect, _VARIANTS)
|
||||
g.digits, g.votes = _vote(g.reads)
|
||||
return g
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 规则裁决
|
||||
def _search(groups: Sequence[GroupRead], face_bank: str,
|
||||
budget: int) -> Dict[str, Tuple[int, int]]:
|
||||
"""在「改动代价 ≤ budget」的范围内搜出所有通过 Luhn 的号码。
|
||||
|
||||
代价递增搜索:投票串本身合法(代价 0)或只需改 1~2 位时,解空间很小;
|
||||
不用 itertools.product 全量展开(歧义位多时是 8^16,必然被截断漏解)。
|
||||
"""
|
||||
opts: List[List[Tuple[str, int, int]]] = []
|
||||
for g in groups:
|
||||
for i in range(4):
|
||||
opts.append(g.options(i))
|
||||
n = len(opts)
|
||||
found: Dict[str, Tuple[int, int]] = {}
|
||||
nodes = 0
|
||||
digits: List[str] = []
|
||||
|
||||
def dfs(pos: int, cost: int, votes: int) -> None:
|
||||
nonlocal nodes
|
||||
if nodes >= _MAX_NODES:
|
||||
return
|
||||
nodes += 1
|
||||
if pos == n:
|
||||
num = "".join(digits)
|
||||
if len(num) not in (16, 18, 19) or not prefix_ok(num) or not luhn_ok(num):
|
||||
return
|
||||
bank = bin_bank(num)
|
||||
if face_bank and bank and bank != face_bank:
|
||||
return
|
||||
prev = found.get(num)
|
||||
if prev is None or (cost, -votes) < (prev[0], -prev[1]):
|
||||
found[num] = (cost, votes)
|
||||
return
|
||||
for d, c, v in opts[pos]:
|
||||
if cost + c > budget:
|
||||
continue
|
||||
digits.append(d)
|
||||
dfs(pos + 1, cost + c, votes + v)
|
||||
digits.pop()
|
||||
|
||||
dfs(0, 0, 0)
|
||||
return found
|
||||
|
||||
|
||||
def _resolve(groups: Sequence[GroupRead], face_text: str = "") -> NumberReading:
|
||||
"""投票结果 → Luhn 裁决 → 排序候选。"""
|
||||
res = NumberReading()
|
||||
res.groups = list(groups)
|
||||
voted = "".join(g.digits for g in groups)
|
||||
res.number = voted
|
||||
res.length = len(voted)
|
||||
face_bank = _bank_from_text(face_text)
|
||||
|
||||
found: Dict[str, Tuple[int, int]] = {}
|
||||
for budget in range(1, _MAX_COST + 1):
|
||||
found = _search(groups, face_bank, budget)
|
||||
if found or budget >= 3:
|
||||
break
|
||||
|
||||
ranked = sorted(found.items(), key=lambda kv: (kv[1][0], -kv[1][1], kv[0]))
|
||||
res.candidates = [{"number": n, "luhn_ok": True, "length": len(n),
|
||||
"bank": bin_bank(n), "cost": c, "votes": v}
|
||||
for n, (c, v) in ranked[:_MAX_CANDIDATES]]
|
||||
if not res.candidates:
|
||||
res.number = "" # 没有通过校验的解:不返回可疑号码,交由人工
|
||||
res.status, res.confidence = "failed", "low"
|
||||
return res
|
||||
|
||||
top_num, (top_cost, _) = ranked[0]
|
||||
res.number = top_num
|
||||
res.length = len(top_num)
|
||||
res.luhn_ok = True
|
||||
res.bank = bin_bank(top_num) or face_bank
|
||||
# 投票串本身就合法 → 高置信;靠易混枚举纠回来 → 中/低置信(建议人工复核)
|
||||
if voted == top_num and top_cost == 0:
|
||||
res.status, res.confidence = "ok", "high"
|
||||
elif top_cost <= 1:
|
||||
res.status, res.confidence = "candidate", "medium"
|
||||
else:
|
||||
res.status, res.confidence = "candidate", "low"
|
||||
return res
|
||||
|
||||
|
||||
def _bank_from_text(text: str) -> str:
|
||||
from .bankcard import _bank_from_face # noqa: PLC0415 避免循环引用
|
||||
|
||||
return _bank_from_face(text) if text else ""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 对外接口
|
||||
def _warp_fallback(bgr: np.ndarray) -> Optional[np.ndarray]:
|
||||
"""整图找不到卡号带时的兜底:按色块/边缘找卡并摆正,失败返回 None。"""
|
||||
try:
|
||||
from .cards import locate_bank_card # noqa: PLC0415 避免循环引用
|
||||
return locate_bank_card(bgr)
|
||||
except Exception: # noqa: BLE001 兜底链路不允许把主流程带崩
|
||||
logger.debug("找卡兜底失败", exc_info=True)
|
||||
return None
|
||||
|
||||
|
||||
def _text_bands(bgr: np.ndarray) -> List[Tuple[int, int, int, int]]:
|
||||
"""MSER 找不到卡号带时的兜底:用 OCR 检出的数字行定 y、卡宽定 x。
|
||||
|
||||
浮雕卡片的数字是「同色凸起」,MSER 经常整行都检测不到;而 OCR 检测网络对
|
||||
这类卡面仍能框出部分数字(哪怕只读到 4 位),用它定纵向位置更稳。
|
||||
"""
|
||||
try:
|
||||
from .engine import lines as ocr_lines # noqa: PLC0415 避免循环引用
|
||||
ls = ocr_lines(bgr)
|
||||
except Exception: # noqa: BLE001
|
||||
return []
|
||||
h, w = bgr.shape[:2]
|
||||
rows = [ln for ln in ls if sum(1 for ch in ln.text if ch.isdigit()) >= 2]
|
||||
rows.sort(key=lambda ln: -ln.width)
|
||||
out: List[Tuple[int, int, int, int]] = []
|
||||
for ln in rows[:2]:
|
||||
cy = (ln.top + ln.bottom) / 2.0
|
||||
half = max(24, int(ln.height * 0.75))
|
||||
out.append((int(w * _SPAN_RATIOS[0][0]), max(0, int(cy - half)),
|
||||
int(w * _SPAN_RATIOS[0][1]), min(h, int(cy + half))))
|
||||
return out
|
||||
|
||||
|
||||
def _band_probe(gray: np.ndarray, band: Tuple[int, int, int, int]) -> int:
|
||||
"""便宜地试读一条带子:只跑 morph 一路,数「正好 4 位」的分组个数。"""
|
||||
xa, y1, xb, y2 = band
|
||||
h, w = gray.shape[:2]
|
||||
if xb - xa < w * 0.6: # 带子比整图窄:按带子自己的跨度切
|
||||
xa, xb = max(0, xa), min(w, xb)
|
||||
else:
|
||||
xa, xb = int(w * _SPAN_RATIOS[0][0]), int(w * _SPAN_RATIOS[0][1])
|
||||
gw = (xb - xa) / 4.0
|
||||
good = 0
|
||||
for i in range(4):
|
||||
rect = (int(round(xa + gw * i)), y1, int(round(xa + gw * (i + 1))), y2)
|
||||
v = _read_crop(gray, rect, ("morph",)).get("morph", "")
|
||||
if len(v) == 4:
|
||||
good += 1
|
||||
return good
|
||||
|
||||
|
||||
def _quality(groups: Sequence[GroupRead]) -> int:
|
||||
"""分组读得干不干净:4 位命中次数 + 每位最高票数(用于在多个跨度假设间选优)。"""
|
||||
q = 0
|
||||
for g in groups:
|
||||
q += 2 * sum(1 for v in g.reads.values() if len(v) == 4)
|
||||
q += sum(max(v.values()) for v in g.votes if v)
|
||||
return q
|
||||
|
||||
|
||||
def read_bank_card_number(image, face_text: str = "") -> NumberReading:
|
||||
"""识别一张卡图上的卡号(浮雕/反光卡兜底用)。
|
||||
|
||||
Args:
|
||||
image: 图片路径,或已读入的 BGR/灰度 ndarray(建议传入已摆正/透视矫正的卡图)。
|
||||
face_text: 卡面 OCR 文本(含银行名时用于 BIN 交叉校验,如 "招商银行")。
|
||||
|
||||
Returns:
|
||||
NumberReading;`.number` 为最终号码,`.candidates` 为按可信度排序的候选,
|
||||
`.status` 为 ok / candidate / failed。读不准就返回候选并把 status 置为
|
||||
candidate/failed,不硬猜。
|
||||
"""
|
||||
t0 = time.time()
|
||||
src = image if isinstance(image, np.ndarray) else imread(str(image))
|
||||
if src is None or getattr(src, "size", 0) == 0:
|
||||
return NumberReading(elapsed_s=time.time() - t0)
|
||||
gray = to_gray(src)
|
||||
res = NumberReading()
|
||||
bands = find_number_bands(gray)
|
||||
if not bands and getattr(src, "ndim", 0) == 3:
|
||||
# 整图定位不到卡号带(卡没占满画面、拍歪、反光打断):先自动找卡摆正再试
|
||||
warped = _warp_fallback(src)
|
||||
if warped is not None:
|
||||
gray = to_gray(warped)
|
||||
bands = find_number_bands(gray) or _text_bands(warped)
|
||||
if not bands and getattr(src, "ndim", 0) == 3:
|
||||
bands = _text_bands(src)
|
||||
if not bands:
|
||||
res.elapsed_s = time.time() - t0
|
||||
return res
|
||||
|
||||
# 用一次便宜试读挑带子:顶部花纹/有效期行通常读不出 4 位
|
||||
scored = [(_band_probe(gray, b), -i, b) for i, b in enumerate(bands)]
|
||||
scored.sort(reverse=True)
|
||||
ordered = [b for s, _, b in scored if s >= 2] or bands
|
||||
|
||||
h, w = gray.shape[:2]
|
||||
best: Optional[NumberReading] = None
|
||||
best_key = (-1, -1, -1, -1)
|
||||
for band in ordered[:2]:
|
||||
bx1, y1, bx2, y2 = band
|
||||
pad = max(4, int((y2 - y1) * 0.06))
|
||||
y1, y2 = max(0, y1 - pad), min(h, y2 + pad)
|
||||
spans = []
|
||||
if 0 < bx2 - bx1 < w * 0.85:
|
||||
# 带子明显比整图窄:优先用它自己的实际跨度(卡没占满画面时固定百分比会错位)
|
||||
pw = max(4, int((bx2 - bx1) * 0.04))
|
||||
spans.append((max(0, bx1 - pw) / float(w), min(w, bx2 + pw) / float(w)))
|
||||
spans.extend(_SPAN_RATIOS)
|
||||
for (ra, rb) in spans:
|
||||
xa, xb = int(w * ra), int(w * rb)
|
||||
gw = (xb - xa) / 4.0
|
||||
groups = [_pick_group(gray, int(round(xa + gw * i)),
|
||||
int(round(xa + gw * (i + 1))), y1, y2)
|
||||
for i in range(4)]
|
||||
cand = _resolve(groups, face_text)
|
||||
cand.band = band
|
||||
cand.elapsed_s = time.time() - t0
|
||||
if cand.status == "ok": # 投票串本身就合法,直接返回
|
||||
return cand
|
||||
q = _quality(groups)
|
||||
key = (q, *_rank(cand))
|
||||
if best is None or key > best_key:
|
||||
best, best_key = cand, key
|
||||
if q >= 12: # 本带已读得很干净,不必再试更窄的跨度
|
||||
break
|
||||
assert best is not None
|
||||
best.elapsed_s = time.time() - t0
|
||||
return best
|
||||
|
||||
|
||||
def _rank(res: NumberReading) -> Tuple[int, int, int]:
|
||||
level = {"high": 3, "medium": 2, "low": 1}.get(res.confidence, 0)
|
||||
min_cost = min([c.get("cost", 9) for c in res.candidates] or [9])
|
||||
return (1 if res.luhn_ok else 0, level, -min_cost)
|
||||
@@ -0,0 +1,186 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""身份证字段抽取:号码 / 姓名 / 性别 / 民族 / 出生 / 住址。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, List, Optional, Sequence
|
||||
|
||||
from .engine import Line, join_text
|
||||
from .validators import (IdCandidate, id_birth, id_candidates, id_checksum_ok,
|
||||
id_gender, id_plausible, id_region, normalize_text)
|
||||
|
||||
ID_KEYWORDS = ("公民身份号码", "身份号码", "姓名", "性别", "民族", "出生", "住址",
|
||||
"签发机关", "有效期限", "中华人民共和国", "居民身份证")
|
||||
|
||||
# 这些词不能当姓名
|
||||
_NOT_NAME = set(ID_KEYWORDS) | {"男", "女", "汉", "回", "苗", "彝", "壮", "藏", "维吾尔",
|
||||
"身份证", "公民", "号码", "地址", "出生日期"}
|
||||
|
||||
|
||||
@dataclass
|
||||
class IdCardResult:
|
||||
number: str = ""
|
||||
checksum_ok: bool = False
|
||||
birth: str = ""
|
||||
gender: str = ""
|
||||
name: str = ""
|
||||
ethnicity: str = ""
|
||||
address: str = ""
|
||||
issue: str = ""
|
||||
valid_to: str = ""
|
||||
confidence: str = "low" # high / medium / low
|
||||
evidence: List[str] = field(default_factory=list)
|
||||
candidates: List[dict] = field(default_factory=list)
|
||||
found: bool = False
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"found": self.found,
|
||||
"number": self.number,
|
||||
"checksum_ok": self.checksum_ok,
|
||||
"birth": self.birth,
|
||||
"gender": self.gender,
|
||||
"name": self.name,
|
||||
"ethnicity": self.ethnicity,
|
||||
"address": self.address,
|
||||
"issue": self.issue,
|
||||
"valid_to": self.valid_to,
|
||||
"confidence": self.confidence,
|
||||
"evidence": self.evidence,
|
||||
"candidates": self.candidates,
|
||||
}
|
||||
|
||||
|
||||
def looks_like_id(text: str) -> bool:
|
||||
hits = sum(1 for k in ID_KEYWORDS if k in text)
|
||||
return hits >= 2 or "公民身份号码" in text or "居民身份证" in text
|
||||
|
||||
|
||||
def _norm_name(s: str) -> str:
|
||||
s = normalize_text(s)
|
||||
s = re.sub(r"^姓名", "", s)
|
||||
s = re.sub(r"[·•.\s]", "", s)
|
||||
return s
|
||||
|
||||
|
||||
# 这些词长得像姓名,绝不能当姓名
|
||||
_BANK_WORDS = ("银行", "银联", "UNIONPAY", "信用卡", "借记卡", "储蓄卡", "一卡通",
|
||||
"有限公司", "保险", "支行", "分行")
|
||||
|
||||
|
||||
def _name_candidate(text: str) -> str:
|
||||
t = _norm_name(text)
|
||||
if not (2 <= len(t) <= 4 and re.fullmatch(r"[一-龥]+", t)):
|
||||
return ""
|
||||
if t in _NOT_NAME or any(w in t.upper() for w in _BANK_WORDS):
|
||||
return ""
|
||||
return t
|
||||
|
||||
|
||||
def _pick_name(lines: Sequence[Line], expected: str, full_text: str) -> str:
|
||||
"""姓名优先用外部给的姓名做交叉验证,其次取「姓名」标签旁边那一段 2~4 字中文。"""
|
||||
if expected:
|
||||
exp = _norm_name(expected)
|
||||
if exp and exp in normalize_text(full_text):
|
||||
return exp
|
||||
# 情况一:OCR 把标签和名字连成一段(「姓名李诗灿」)
|
||||
for ln in lines:
|
||||
m = re.match(r"姓名([一-龥]{2,4})$", normalize_text(ln.text))
|
||||
if m and _name_candidate(m.group(1)):
|
||||
return _name_candidate(m.group(1))
|
||||
# 情况二:标签和名字是两段,取离「姓名」标签最近的那段中文
|
||||
labels = [ln for ln in lines if "姓名" in normalize_text(ln.text)]
|
||||
cands = []
|
||||
for ln in lines:
|
||||
c = _name_candidate(ln.text)
|
||||
if not c:
|
||||
continue
|
||||
for lab in labels:
|
||||
d = abs(ln.y_mid - lab.y_mid) * 2.0 + abs(ln.left - lab.right)
|
||||
cands.append((d, c))
|
||||
if cands:
|
||||
cands.sort(key=lambda x: x[0])
|
||||
return cands[0][1]
|
||||
return ""
|
||||
|
||||
|
||||
def _pick_field(text: str, patterns: Sequence[str]) -> str:
|
||||
for pat in patterns:
|
||||
m = re.search(pat, text)
|
||||
if m:
|
||||
return m.group(1)
|
||||
return ""
|
||||
|
||||
|
||||
def parse(lines: Sequence[Line], expected_name: str = "",
|
||||
full_text: str = "", rows: Optional[Sequence[str]] = None) -> IdCardResult:
|
||||
"""从身份证那一面的 OCR 结果里抽字段。"""
|
||||
res = IdCardResult()
|
||||
text = normalize_text(full_text) if full_text else normalize_text(join_text(lines))
|
||||
if not text:
|
||||
return res
|
||||
|
||||
cands: List[IdCandidate] = id_candidates(rows if rows else text)
|
||||
if not cands:
|
||||
# 逐行再试(号码被拆成两段时)
|
||||
for ln in lines:
|
||||
cands.extend(id_candidates(ln.text))
|
||||
cands = sorted(cands, key=lambda c: -c.score)[:8]
|
||||
|
||||
if cands:
|
||||
top = cands[0]
|
||||
res.candidates = [{"number": c.number, "checksum_ok": c.checksum_ok,
|
||||
"origin": c.origin, "edits": c.edits,
|
||||
"score": round(c.score, 2)} for c in cands]
|
||||
res.number = top.number
|
||||
res.checksum_ok = top.checksum_ok
|
||||
res.birth = id_birth(top.number)
|
||||
res.gender = id_gender(top.number)
|
||||
res.found = True
|
||||
if top.origin == "repaired":
|
||||
res.evidence.append(f"号码经 {top.edits} 位纠错后通过校验码(原始识别有误)")
|
||||
|
||||
# 与 OCR 文字里的「出生 / 性别」交叉核对,不一致时优先相信 OCR 文字并打标注
|
||||
birth_txt = _pick_field(text, (r"出生(\d{4}年\d{1,2}月\d{1,2}日)",
|
||||
r"出生(\d{4}[.\-/]\d{1,2}[.\-/]\d{1,2})"))
|
||||
if birth_txt:
|
||||
res.evidence.append(f"卡面出生:{birth_txt}")
|
||||
|
||||
gender_txt = ""
|
||||
m = re.search(r"性别[男女]", text) or re.search(r"(男|女)", text)
|
||||
if m:
|
||||
gender_txt = "女" if "女" in m.group(0) else "男"
|
||||
if gender_txt:
|
||||
res.evidence.append(f"卡面性别:{gender_txt}")
|
||||
if res.gender and res.gender != gender_txt:
|
||||
res.evidence.append(f"⚠ 号码推导性别({res.gender})与卡面({gender_txt})不一致")
|
||||
|
||||
eth = _pick_field(text, (r"民族([\u4e00-\u9fa5]{1,4}?)(?=出生|性别|姓名|住址|公|$)",))
|
||||
res.ethnicity = eth
|
||||
|
||||
res.name = _pick_name(lines, expected_name, text)
|
||||
|
||||
# 住址:从「住址」开始到号码/签发机关之前
|
||||
m = re.search(r"住址(.+?)(公民身份号码|签发机关|有效期限|$)", text)
|
||||
addr = m.group(1) if m else ""
|
||||
res.address = re.sub(r"[。,,]", "", addr)[:60]
|
||||
|
||||
res.issue = _pick_field(text, (r"签发机关([^有效]+?)(?:有效|$)",))
|
||||
vt = re.search(r"有效期限?(\d{4}[.\-/年]\d{1,2}[.\-/月]\d{1,2}[日]?(?:[-—~至]\d{4}[.\-/年]\d{1,2}[.\-/月]\d{1,2}[日]?|长期))", text)
|
||||
res.valid_to = vt.group(1) if vt else ""
|
||||
|
||||
# 置信度
|
||||
high = res.checksum_ok and bool(res.name) and bool(res.birth)
|
||||
if (expected_name and res.name and _norm_name(res.name) != _norm_name(expected_name)):
|
||||
high = False
|
||||
res.evidence.append(f"⚠ 姓名({res.name})与表格姓名({expected_name})不一致")
|
||||
if not res.checksum_ok:
|
||||
res.confidence = "low" if not cands else "medium"
|
||||
elif high and (top.origin == "raw" if cands else False):
|
||||
res.confidence = "high"
|
||||
else:
|
||||
res.confidence = "medium"
|
||||
if res.birth and not id_plausible(res.number or ""):
|
||||
res.evidence.append("⚠ 号码生日不合法")
|
||||
return res
|
||||
@@ -0,0 +1,174 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""图像基础操作:中文路径读取、缩放、增强、旋转、透视矫正。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import Iterable, List, Optional, Sequence, Tuple
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
# 身份证 / 银行卡物理尺寸 85.6 x 54 mm,长宽比 ≈ 1.585
|
||||
CARD_ASPECT = 85.6 / 54.0
|
||||
|
||||
|
||||
def imread(path: str) -> np.ndarray:
|
||||
"""读取图片(支持中文路径 / 空格,cv2.imread 在 Windows 下会失败)。"""
|
||||
p = str(path)
|
||||
if not os.path.isfile(p):
|
||||
raise FileNotFoundError(f"图片不存在:{p}")
|
||||
data = np.fromfile(p, dtype=np.uint8)
|
||||
if data.size == 0:
|
||||
raise ValueError(f"图片为空:{p}")
|
||||
img = cv2.imdecode(data, cv2.IMREAD_COLOR)
|
||||
if img is None:
|
||||
# 部分手机的 JPEG(CMYK / 特殊 EXIF)cv2 解不出,退 Pillow
|
||||
from PIL import Image, ImageOps # noqa: PLC0415
|
||||
|
||||
with Image.open(p) as im:
|
||||
im = ImageOps.exif_transpose(im).convert("RGB")
|
||||
img = cv2.cvtColor(np.array(im), cv2.COLOR_RGB2BGR)
|
||||
return img
|
||||
|
||||
|
||||
def apply_exif(img: np.ndarray, path: str) -> np.ndarray:
|
||||
"""按 EXIF Orientation 摆正(手机竖拍常带 90/180/270 标记)。"""
|
||||
try:
|
||||
from PIL import Image, ImageOps # noqa: PLC0415
|
||||
|
||||
with Image.open(path) as im:
|
||||
exif = im.getexif()
|
||||
o = int(exif.get(274, 1) or 1)
|
||||
if o in (1, 0):
|
||||
return img
|
||||
im2 = ImageOps.exif_transpose(im).convert("RGB")
|
||||
return cv2.cvtColor(np.array(im2), cv2.COLOR_RGB2BGR)
|
||||
except Exception: # noqa: BLE001 EXIF 不可用不算错
|
||||
return img
|
||||
|
||||
|
||||
def resize_side(img: np.ndarray, max_side: int = 0, min_side: int = 0) -> np.ndarray:
|
||||
"""按长边上限缩小 / 短边下限放大(等比)。"""
|
||||
h, w = img.shape[:2]
|
||||
scale = 1.0
|
||||
if max_side and max(h, w) > max_side:
|
||||
scale = max_side / float(max(h, w))
|
||||
elif min_side and min(h, w) < min_side:
|
||||
scale = min_side / float(min(h, w))
|
||||
if abs(scale - 1.0) < 1e-3:
|
||||
return img
|
||||
interp = cv2.INTER_AREA if scale < 1 else cv2.INTER_CUBIC
|
||||
return cv2.resize(img, (max(1, int(round(w * scale))), max(1, int(round(h * scale)))),
|
||||
interpolation=interp)
|
||||
|
||||
|
||||
def to_gray(img: np.ndarray) -> np.ndarray:
|
||||
if img.ndim == 2:
|
||||
return img
|
||||
return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||
|
||||
|
||||
def rotate90(img: np.ndarray, k: int) -> np.ndarray:
|
||||
"""逆时针旋转 k*90 度。"""
|
||||
return np.ascontiguousarray(np.rot90(img, k % 4))
|
||||
|
||||
|
||||
def gray_variants(gray: np.ndarray, upscale: float = 1.0) -> List[Tuple[str, np.ndarray]]:
|
||||
"""生成多路灰度增强图(浮雕卡号、反光、低对比度各有用),供多遍 OCR 投票。"""
|
||||
g = gray
|
||||
if upscale > 1.0:
|
||||
g = cv2.resize(g, None, fx=upscale, fy=upscale, interpolation=cv2.INTER_CUBIC)
|
||||
out: List[Tuple[str, np.ndarray]] = [("gray", g)]
|
||||
try:
|
||||
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)).apply(g)
|
||||
out.append(("clahe", clahe))
|
||||
except Exception: # noqa: BLE001
|
||||
clahe = g
|
||||
# 反光/低对比:白顶帽 + 黑底帽 强调字迹
|
||||
k = cv2.getStructuringElement(cv2.MORPH_RECT, (13, 5))
|
||||
try:
|
||||
tophat = cv2.morphologyEx(g, cv2.MORPH_TOPHAT, k)
|
||||
blackhat = cv2.morphologyEx(g, cv2.MORPH_BLACKHAT, k)
|
||||
out.append(("tophat", cv2.normalize(tophat, None, 0, 255, cv2.NORM_MINMAX)))
|
||||
out.append(("blackhat", cv2.normalize(blackhat, None, 0, 255, cv2.NORM_MINMAX)))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
# 二值化(Otsu / 自适应),深色卡面反相后号码变白底黑字
|
||||
try:
|
||||
_, otsu = cv2.threshold(g, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
|
||||
out.append(("otsu", otsu))
|
||||
out.append(("otsu_inv", cv2.bitwise_not(otsu)))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
try:
|
||||
adap = cv2.adaptiveThreshold(g, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
||||
cv2.THRESH_BINARY, 31, 9)
|
||||
out.append(("adaptive", adap))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
# 锐化(浮雕数字边缘)
|
||||
try:
|
||||
blur = cv2.GaussianBlur(g, (0, 0), 1.2)
|
||||
out.append(("sharp", cv2.addWeighted(g, 1.6, blur, -0.6, 0)))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
def order_points(pts: Sequence[Sequence[float]]) -> np.ndarray:
|
||||
"""四个点按 左上/右上/右下/左下 排序。"""
|
||||
pts = np.asarray(pts, dtype=np.float32).reshape(4, 2)
|
||||
s = pts.sum(axis=1)
|
||||
d = np.diff(pts, axis=1).reshape(-1)
|
||||
out = np.zeros((4, 2), dtype=np.float32)
|
||||
out[0] = pts[np.argmin(s)]
|
||||
out[2] = pts[np.argmax(s)]
|
||||
out[1] = pts[np.argmin(d)]
|
||||
out[3] = pts[np.argmax(d)]
|
||||
return out
|
||||
|
||||
|
||||
def four_point_warp(img: np.ndarray, pts: Sequence[Sequence[float]],
|
||||
width: int = 0, height: int = 0) -> Tuple[np.ndarray, np.ndarray]:
|
||||
"""把四边形透视矫正成矩形(宽度默认按目标长宽比 1.585 推算)。"""
|
||||
src = order_points(pts)
|
||||
tl, tr, br, bl = src
|
||||
w_top = float(np.linalg.norm(tr - tl))
|
||||
w_bot = float(np.linalg.norm(br - bl))
|
||||
h_lef = float(np.linalg.norm(bl - tl))
|
||||
h_rig = float(np.linalg.norm(br - tr))
|
||||
w = (w_top + w_bot) / 2.0
|
||||
h = (h_lef + h_rig) / 2.0
|
||||
if width and height:
|
||||
w, h = float(width), float(height)
|
||||
elif width:
|
||||
h = width / CARD_ASPECT
|
||||
elif height:
|
||||
w = height * CARD_ASPECT
|
||||
elif w > 0 and h > 0:
|
||||
# 拉正成标准卡比例,避免斜拍把字压扁
|
||||
if w / h > CARD_ASPECT * 1.12:
|
||||
h = w / CARD_ASPECT
|
||||
elif h / w > 1.0 / CARD_ASPECT * 1.12:
|
||||
w = h * CARD_ASPECT
|
||||
dst = np.array([[0, 0], [w - 1, 0], [w - 1, h - 1], [0, h - 1]], dtype=np.float32)
|
||||
m = cv2.getPerspectiveTransform(src, dst)
|
||||
out = cv2.warpPerspective(img, m, (max(1, int(round(w))), max(1, int(round(h)))),
|
||||
flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
|
||||
return out, m
|
||||
|
||||
|
||||
def quad_area(pts: np.ndarray) -> float:
|
||||
return float(abs(cv2.contourArea(np.asarray(pts, dtype=np.float32).reshape(-1, 1, 2))))
|
||||
|
||||
|
||||
def iou_rect(a: Tuple[int, int, int, int], b: Tuple[int, int, int, int]) -> float:
|
||||
ax, ay, aw, ah = a
|
||||
bx, by, bw, bh = b
|
||||
x1, y1 = max(ax, bx), max(ay, by)
|
||||
x2, y2 = min(ax + aw, bx + bw), min(ay + ah, by + bh)
|
||||
if x2 <= x1 or y2 <= y1:
|
||||
return 0.0
|
||||
inter = (x2 - x1) * (y2 - y1)
|
||||
union = aw * ah + bw * bh - inter
|
||||
return inter / float(union) if union > 0 else 0.0
|
||||
@@ -0,0 +1,153 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""命中分析:拿「已知正确号码」去比对识别结果,回答「这张照片能不能证明是这张卡」。
|
||||
|
||||
识别精确率是 100%(认出来的都对),但召回受照片质量限制(有的卡号只读到一半)。
|
||||
和业务上已有的工资卡数据比对时,不需要「完整读出」才有价值——读到前缀 + 后缀、
|
||||
或者除 1 位外全对,就已经能判定「照片与登记号码一致」。
|
||||
|
||||
状态定义:
|
||||
exact 完整命中(识别结果逐位一致)
|
||||
strong 高度一致(≥85% 位命中,通常只差 1 位且是 Luhn 歧义)
|
||||
partial 部分命中(30%~85% 位命中,能看到前缀/后缀)
|
||||
weak 基本读不出(<30%)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import difflib
|
||||
from typing import Dict, Iterable, List, Sequence, Tuple
|
||||
|
||||
from .validators import PRIMARY, bin_bank, normalize_text
|
||||
|
||||
EXACT, STRONG, PARTIAL, WEAK = "exact", "strong", "partial", "weak"
|
||||
LABEL = {EXACT: "一致", STRONG: "高度疑似", PARTIAL: "部分命中", WEAK: "读不出"}
|
||||
|
||||
|
||||
def digits(text: str) -> str:
|
||||
s = normalize_text(text)
|
||||
return "".join(ch if ch.isdigit() else PRIMARY.get(ch, "") for ch in s)
|
||||
|
||||
|
||||
def _keep(run: str, exp: str, card_mode: bool, id_digits: str) -> bool:
|
||||
"""只有「像卡号片段」的游程才参与卡号比对,否则身份证号/日期会把命中率抬虚。"""
|
||||
if len(run) < 8:
|
||||
return False
|
||||
if not card_mode:
|
||||
return True
|
||||
if id_digits and (run == id_digits or id_digits in run or run in id_digits):
|
||||
return False
|
||||
return run.startswith("62") or bool(bin_bank(run)) or run in exp or exp.find(run) >= 0
|
||||
|
||||
|
||||
def coverage(expected: str, runs: Iterable[str], card_mode: bool = True,
|
||||
id_digits: str = "") -> Tuple[float, str, str]:
|
||||
"""返回 (命中率 0~1, 状态, 命中最多的片段)。"""
|
||||
exp = digits(expected)
|
||||
if not exp:
|
||||
return 0.0, WEAK, ""
|
||||
best_cov, best_run, best_status = 0.0, "", WEAK
|
||||
for raw in runs:
|
||||
run = digits(raw)
|
||||
if not _keep(run, exp, card_mode, id_digits):
|
||||
continue
|
||||
if run == exp:
|
||||
return 1.0, EXACT, run
|
||||
covered: set[int] = set()
|
||||
pos = 0
|
||||
while True:
|
||||
i = exp.find(run, pos)
|
||||
if i < 0:
|
||||
break
|
||||
covered.update(range(i, i + len(run)))
|
||||
pos = i + 1
|
||||
pos_cov = len(covered) / len(exp) if covered else 0.0
|
||||
# 只有够长的片段才用模糊相似度,避免 8~10 位噪声凑出虚高命中率
|
||||
ratio = difflib.SequenceMatcher(None, exp, run, autojunk=False).ratio() \
|
||||
if len(run) >= 14 else 0.0
|
||||
cov = max(pos_cov, ratio)
|
||||
if cov > best_cov:
|
||||
best_cov, best_run = cov, run
|
||||
best_status = STRONG if cov >= 0.85 else (PARTIAL if cov >= 0.30 else WEAK)
|
||||
return best_cov, best_status, best_run
|
||||
|
||||
|
||||
def _runs_of(person: dict) -> List[str]:
|
||||
out: List[str] = []
|
||||
for r in (person.get("raw") or []):
|
||||
out.extend(r.get("digit_runs") or [])
|
||||
return out
|
||||
|
||||
|
||||
def check_person(person: dict, truth: Dict[str, str]) -> dict:
|
||||
"""比对一个人的识别结果和人工填写的正确值。"""
|
||||
idc = person.get("id_card") or {}
|
||||
bk = person.get("bank_card") or {}
|
||||
runs = _runs_of(person)
|
||||
|
||||
t_id = digits(truth.get("id") or "")
|
||||
t_card = digits(truth.get("card") or "")
|
||||
t_name = (truth.get("name") or "").strip()
|
||||
|
||||
got_id = digits(idc.get("number") or "")
|
||||
if t_id:
|
||||
if got_id == t_id:
|
||||
id_status, id_cov = EXACT, 1.0
|
||||
else:
|
||||
id_cov, id_status, _ = coverage(t_id, runs, card_mode=False)
|
||||
else:
|
||||
id_status, id_cov = WEAK, 0.0
|
||||
|
||||
if t_card:
|
||||
if digits(bk.get("number") or "") == t_card:
|
||||
card_status, card_cov = EXACT, 1.0
|
||||
else:
|
||||
card_cov, card_status, _ = coverage(t_card, runs, card_mode=True,
|
||||
id_digits=got_id or t_id)
|
||||
else:
|
||||
card_cov, card_status = 0.0, WEAK
|
||||
|
||||
got_name = (idc.get("name") or "").strip()
|
||||
if t_name:
|
||||
name_status = EXACT if got_name == t_name else (PARTIAL if not got_name else WEAK)
|
||||
else:
|
||||
name_status = WEAK
|
||||
|
||||
return {
|
||||
"folder": person.get("folder", ""),
|
||||
"truth_name": t_name,
|
||||
"id_recognized": got_id or "",
|
||||
"id_status": id_status,
|
||||
"id_coverage": round(id_cov, 3),
|
||||
"card_recognized": digits(bk.get("number") or ""),
|
||||
"card_status": card_status,
|
||||
"card_coverage": round(card_cov, 3),
|
||||
"name_recognized": got_name,
|
||||
"name_status": name_status,
|
||||
"runs": runs[:12],
|
||||
}
|
||||
|
||||
|
||||
def check_persons(persons: Sequence[dict], truth_map: Dict[str, Dict[str, str]]) -> List[dict]:
|
||||
rows = []
|
||||
for p in persons:
|
||||
t = truth_map.get(p.get("folder", "")) or {}
|
||||
if not t:
|
||||
continue
|
||||
rows.append(check_person(p, t))
|
||||
return rows
|
||||
|
||||
|
||||
def print_report(rows: Sequence[dict]) -> str:
|
||||
lines = [f"{'姓名':<9}{'身份证识别':<20}{'状态':<9}{'卡号识别':<20}{'卡号状态':<9}"
|
||||
f"{'命中率':<8}姓名"]
|
||||
lines.append("-" * 100)
|
||||
for r in rows:
|
||||
lines.append(
|
||||
f"{r['folder']:<9}"
|
||||
f"{(r['id_recognized'] or '-'):<20}"
|
||||
f"{LABEL.get(r['id_status'], r['id_status']):<9}"
|
||||
f"{(r['card_recognized'] or '-'):<20}"
|
||||
f"{LABEL.get(r['card_status'], r['card_status']):<9}"
|
||||
f"{r['card_coverage']:<8.2f}"
|
||||
f"{'一致' if r['name_status'] == EXACT else ('未识别' if not r['name_recognized'] else '不一致')}"
|
||||
)
|
||||
return "\n".join(lines)
|
||||
@@ -0,0 +1,652 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""识别流水线:粗识别 → 方向补测 → 文字块精修 → 字段抽取 → 交叉校验。
|
||||
|
||||
为什么不直接「一步 OCR 全图」:手机拍的照片边长动辄 4000~5700 像素,
|
||||
PP-OCR 的检测网络会先把整图缩到 ~1600,卡面上的小字(尤其浮雕卡号)就直接糊了。
|
||||
所以这里做两级:先小图定位文字块(快),再把原图上对应的块按原分辨率切出来精识别
|
||||
(准),卡号读不出来时再对数字带做多路增强 + 多遍投票,最后用校验位把错字纠回来。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional, Sequence, Tuple
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
from . import bankcard, idcard
|
||||
from .cards import find_cards, locate_bank_card
|
||||
from .engine import Line, join_text, lines as ocr_lines, row_texts, text_line
|
||||
from .img import apply_exif, gray_variants, imread, resize_side, rotate90, to_gray
|
||||
from .validators import (_CONFUSABLE, PRIMARY, card_candidates, id_candidates,
|
||||
normalize_text)
|
||||
|
||||
logger = logging.getLogger("cardocr")
|
||||
|
||||
IMAGE_EXT = {".jpg", ".jpeg", ".png", ".bmp", ".webp", ".tif", ".tiff"}
|
||||
|
||||
# 粗识别缩图边长:太小丢小字,太大慢且和精修重复
|
||||
_COARSE_SIDE = 1440
|
||||
# 精修块最长边
|
||||
_FINE_SIDE = 2200
|
||||
# 数字带目标字高
|
||||
_STRIP_H = 120
|
||||
# 数字带做增强的通道(越多越准;跳过检测网络后单路只要 0.1~0.3s)
|
||||
_STRIP_VARIANT_NAMES = ("gray", "blackhat", "otsu_inv", "sharp", "tophat")
|
||||
|
||||
|
||||
|
||||
@dataclass
|
||||
class View:
|
||||
"""一次 OCR 的输入区域(整图粗识别 / 精修块 / 卡片矫正图)。"""
|
||||
|
||||
name: str
|
||||
image: np.ndarray
|
||||
source: str # coarse / fine / strip / quad
|
||||
rect: Tuple[int, int, int, int]
|
||||
lines: List[Line] = field(default_factory=list)
|
||||
text: str = ""
|
||||
kind: str = "unknown" # id / bank / both / unknown
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {"name": self.name, "source": self.source, "rect": list(self.rect),
|
||||
"size": [int(self.image.shape[1]), int(self.image.shape[0])],
|
||||
"kind": self.kind, "lines": len(self.lines), "text": self.text[:180]}
|
||||
|
||||
|
||||
def classify(text: str) -> str:
|
||||
if not text.strip():
|
||||
return "unknown"
|
||||
is_id = idcard.looks_like_id(text)
|
||||
is_bank = bankcard.looks_like_bank_card(text)
|
||||
if is_id and is_bank:
|
||||
return "both"
|
||||
if is_id:
|
||||
return "id"
|
||||
if is_bank:
|
||||
return "bank"
|
||||
return "unknown"
|
||||
|
||||
|
||||
def _digitish(text: str) -> int:
|
||||
return sum(1 for ch in text if ch.isdigit() or ch in _CONFUSABLE)
|
||||
|
||||
|
||||
def number_runs(text: str, min_len: int = 6) -> List[str]:
|
||||
"""从一段文本里抽数字串(易混字母按首选映射还原),用于人工核对时的「命中分析」。"""
|
||||
s = normalize_text(text)
|
||||
norm = "".join(ch if ch.isdigit() else PRIMARY.get(ch, " ") for ch in s)
|
||||
runs: List[str] = []
|
||||
cur = []
|
||||
for ch in norm:
|
||||
if ch.isdigit():
|
||||
cur.append(ch)
|
||||
else:
|
||||
if len(cur) >= min_len:
|
||||
runs.append("".join(cur))
|
||||
cur = []
|
||||
if len(cur) >= min_len:
|
||||
runs.append("".join(cur))
|
||||
return runs
|
||||
|
||||
|
||||
def _looks_rotated(lines: Sequence[Line]) -> bool:
|
||||
"""文字框普遍「高 > 宽」→ 照片被拍成横的,值得转 90/270 度补测。"""
|
||||
if not lines:
|
||||
return True
|
||||
tall = sum(1 for x in lines if x.height > 1.6 * x.width)
|
||||
return tall >= max(2, len(lines) * 0.3)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 文字块
|
||||
def group_blocks(lines: Sequence[Line], max_blocks: int = 12) -> List[List[Line]]:
|
||||
"""把同一张卡上的文字行聚成块(按竖直间距 + 水平重叠)。"""
|
||||
if not lines:
|
||||
return []
|
||||
items = sorted(lines, key=lambda x: (x.top, x.left))
|
||||
med_h = float(np.median([x.height for x in items])) if items else 0.0
|
||||
blocks: List[List[Line]] = []
|
||||
cur = [items[0]]
|
||||
for ln in items[1:]:
|
||||
prev = cur[-1]
|
||||
vgap = ln.top - prev.bottom
|
||||
overlap = min(ln.right, prev.right) - max(ln.left, prev.left)
|
||||
same_row = overlap > 0.15 * min(ln.width, prev.width) and \
|
||||
abs(ln.y_mid - prev.y_mid) < 0.6 * max(ln.height, prev.height)
|
||||
if vgap <= max(10.0, med_h * 1.2) or same_row or vgap < 0:
|
||||
cur.append(ln)
|
||||
else:
|
||||
blocks.append(cur)
|
||||
cur = [ln]
|
||||
blocks.append(cur)
|
||||
blocks.sort(key=lambda b: -len(b))
|
||||
return blocks[:max_blocks]
|
||||
|
||||
|
||||
def _bbox(lines: Sequence[Line], pad_x: float, pad_y: float,
|
||||
bounds: Tuple[int, int]) -> Tuple[int, int, int, int]:
|
||||
x1 = min(x.left for x in lines)
|
||||
y1 = min(x.top for x in lines)
|
||||
x2 = max(x.right for x in lines)
|
||||
y2 = max(x.bottom for x in lines)
|
||||
px = int((x2 - x1) * pad_x) + 8
|
||||
py = int((y2 - y1) * pad_y) + 8
|
||||
w, h = bounds
|
||||
return max(0, x1 - px), max(0, y1 - py), min(w, x2 + px), min(h, y2 + py)
|
||||
|
||||
|
||||
def _fit(img: np.ndarray, max_side: int = _FINE_SIDE, min_h: int = 0) -> np.ndarray:
|
||||
out = img
|
||||
if max(out.shape[:2]) > max_side:
|
||||
out = resize_side(out, max_side=max_side)
|
||||
if min_h and min(out.shape[:2]) < min_h:
|
||||
out = resize_side(out, min_side=min_h)
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 精修
|
||||
def _fine_views(img: np.ndarray, coarse: View,
|
||||
budget: int = 3) -> List[View]:
|
||||
"""从粗识别文字块里挑出信息最密的若干块,回原图按原生分辨率切开精识别。"""
|
||||
blocks = group_blocks(coarse.lines)
|
||||
picked: List[Tuple[float, List[Line]]] = []
|
||||
for b in blocks:
|
||||
t = join_text(b)
|
||||
s = 0.0
|
||||
if idcard.looks_like_id(t):
|
||||
s += 3.0
|
||||
if bankcard.looks_like_bank_card(t):
|
||||
s += 2.5
|
||||
d = _digitish(t)
|
||||
if d >= 8:
|
||||
s += 2.0
|
||||
elif d >= 6:
|
||||
s += 1.0
|
||||
if len(b) >= 2:
|
||||
s += 0.5
|
||||
if s > 0:
|
||||
picked.append((s, b))
|
||||
picked.sort(key=lambda x: -x[0])
|
||||
h, w = img.shape[:2]
|
||||
# 粗识别是在缩图(≤1440)上做的,坐标要按比例放大回原图
|
||||
scale = w / float(coarse.image.shape[1])
|
||||
out: List[View] = []
|
||||
for s, b in picked[:budget]:
|
||||
x1, y1, x2, y2 = _bbox(b, 0.18, 0.55, (w, h))
|
||||
x1, y1 = int(x1 * scale), int(y1 * scale)
|
||||
x2, y2 = min(w, int(x2 * scale)), min(h, int(y2 * scale))
|
||||
if x2 <= x1 or y2 <= y1:
|
||||
continue
|
||||
crop = img[y1:y2, x1:x2]
|
||||
if crop.size == 0:
|
||||
continue
|
||||
# 与已有精修块大面积重叠则跳过(同一张卡被拆成多块时会重复)
|
||||
if any(_iou_rect((x1, y1, x2 - x1, y2 - y1), v.rect) > 0.55 for v in out):
|
||||
continue
|
||||
crop = _fit(crop)
|
||||
out.append(View(name=f"fine{len(out) + 1}", image=crop, source="fine",
|
||||
rect=(x1, y1, x2 - x1, y2 - y1)))
|
||||
return out
|
||||
|
||||
|
||||
def _iou_rect(a, b) -> float:
|
||||
ax, ay, aw, ah = a
|
||||
bx, by, bw, bh = b
|
||||
x1, y1 = max(ax, bx), max(ay, by)
|
||||
x2, y2 = min(ax + aw, bx + bw), min(ay + ah, by + bh)
|
||||
if x2 <= x1 or y2 <= y1:
|
||||
return 0.0
|
||||
inter = (x2 - x1) * (y2 - y1)
|
||||
return inter / float(aw * ah + bw * bh - inter)
|
||||
|
||||
|
||||
def _strip_variants(view: View, lines: Sequence[Line], want: int = 2):
|
||||
"""对数字行做多路增强识别,逐路 yield 行文本(调用方可以随时提前收工)。
|
||||
|
||||
窄条图直接用识别网络(跳过检测网络),单路约 0.1~0.3s,可放心多跑几路。
|
||||
"""
|
||||
jobs = [ln for ln in lines if _digitish(ln.text) >= 6 and ln.width >= 100]
|
||||
jobs.sort(key=lambda x: -_digitish(x.text))
|
||||
for ln in jobs[:want]:
|
||||
h, w = view.image.shape[:2]
|
||||
px = max(6, int(ln.height * 0.2))
|
||||
x1, y1 = max(0, ln.left - px), max(0, ln.top - px)
|
||||
x2, y2 = min(w, ln.right + px), min(h, ln.bottom + px)
|
||||
crop = _fit(view.image[y1:y2, x1:x2], max_side=1600, min_h=96)
|
||||
if crop.size == 0:
|
||||
continue
|
||||
gray = to_gray(crop)
|
||||
for name, var in gray_variants(gray, upscale=1.0):
|
||||
if name in _STRIP_VARIANT_NAMES:
|
||||
text = text_line(var)
|
||||
if text:
|
||||
yield [text]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 主流程
|
||||
def analyze_image(path: str, expected_name: str = "",
|
||||
mark_dir: Optional[str] = None,
|
||||
extra_passes: bool = True,
|
||||
fast: bool = False) -> dict:
|
||||
"""识别单张照片,返回结构化结果。
|
||||
|
||||
Args:
|
||||
path: 图片路径(支持中文 / 空格)。
|
||||
expected_name: 表格或文件夹里的姓名,用来校验身份证上的姓名。
|
||||
mark_dir: 若给目录,把命中区域的标注图存下去方便人工复核。
|
||||
extra_passes: 卡号/身份证号没读准时,是否追加多遍增强识别。
|
||||
fast: 只跑粗识别(快,但精度下降)。
|
||||
"""
|
||||
t0 = time.time()
|
||||
p = Path(path)
|
||||
img = imread(str(p))
|
||||
img = apply_exif(img, str(p))
|
||||
H, W = img.shape[:2]
|
||||
views: List[View] = []
|
||||
|
||||
def add_view(v: View) -> None:
|
||||
v.lines = ocr_lines(v.image)
|
||||
v.text = join_text(v.lines)
|
||||
v.kind = classify(v.text)
|
||||
views.append(v)
|
||||
|
||||
# ---- 1) 粗识别(原方向;缩略图先放大,否则小字根本没有像素)
|
||||
coarse_src = img if max(H, W) >= 1000 else resize_side(img, min_side=1000)
|
||||
coarse_img = resize_side(coarse_src, max_side=_COARSE_SIDE)
|
||||
coarse = View(name="coarse", image=coarse_img, source="coarse", rect=(0, 0, W, H))
|
||||
add_view(coarse)
|
||||
chosen_rot = 0
|
||||
img_work = img
|
||||
|
||||
# ---- 2) 方向补测:只在「身份证号 / 卡号」都没读准时才做(每多一次约 2~4s)
|
||||
if not fast:
|
||||
def quick_q(views: Sequence[View]) -> int:
|
||||
idok = any(c.checksum_ok for c in id_candidates(rows_of(views, "id"), limit=3))
|
||||
cok = any(c.luhn_ok for c in card_candidates(rows_of(views, "bank"), limit=3))
|
||||
return int(idok) + int(cok)
|
||||
|
||||
q = quick_q(views)
|
||||
# 文字是竖排的(整张照片拍横了)或几乎没识别到字,才值得换方向重认
|
||||
rotated_text = _looks_rotated(coarse.lines)
|
||||
few_text = len(coarse.lines) <= 2
|
||||
if q < 2 and (rotated_text or few_text):
|
||||
best_q, best_k = q, 0
|
||||
for k in (1, 3):
|
||||
small = resize_side(rotate90(img, k), max_side=_COARSE_SIDE)
|
||||
probe = View(name="probe", image=small, source="coarse", rect=(0, 0, W, H))
|
||||
probe.lines = ocr_lines(small)
|
||||
probe.text = join_text(probe.lines)
|
||||
probe.kind = classify(probe.text)
|
||||
qk = quick_q([probe])
|
||||
if qk > best_q:
|
||||
best_q, best_k = qk, k
|
||||
if qk == 2:
|
||||
break
|
||||
if best_k:
|
||||
chosen_rot = best_k
|
||||
img_work = rotate90(img, chosen_rot)
|
||||
views.clear()
|
||||
coarse = View(name="coarse",
|
||||
image=resize_side(img_work, max_side=_COARSE_SIDE),
|
||||
source="coarse",
|
||||
rect=(0, 0, img_work.shape[1], img_work.shape[0]))
|
||||
add_view(coarse)
|
||||
|
||||
# ---- 3) 首版字段抽取
|
||||
id_res, bank_res = _extract(views, expected_name)
|
||||
extra_used = 0
|
||||
extra_rows: List[str] = []
|
||||
|
||||
# ---- 4) 精修:只在字段缺失 / 不可信时,回原图按原生分辨率切块重识别
|
||||
need_id = not id_res.checksum_ok
|
||||
need_card = not (bank_res.found and bank_res.luhn_ok
|
||||
and bank_res.length in (16, 18, 19))
|
||||
if (need_id or need_card) and not fast:
|
||||
budget = 2
|
||||
for v in _fine_views(img_work, coarse, budget=budget):
|
||||
add_view(v)
|
||||
id_res, bank_res = _extract(views, expected_name)
|
||||
|
||||
# ---- 5) 多路增强:数字带换灰度/黑帽/Otsu 反相再识别一遍(浮雕字、反光靠这层)
|
||||
if extra_passes and not fast and (not id_res.checksum_ok
|
||||
or not (bank_res.found and bank_res.luhn_ok)):
|
||||
# 5.1 整图灰度/CLAHE 通道:彩色图上漏掉的卡号,灰度图经常能出来(实测很有效)
|
||||
if not (bank_res.found and bank_res.luhn_ok):
|
||||
base = resize_side(img_work, max_side=_COARSE_SIDE)
|
||||
for vname, var in gray_variants(to_gray(base), upscale=1.0):
|
||||
if vname not in ("gray", "clahe"):
|
||||
continue
|
||||
add_view(View(name=f"gray_{vname}", image=var, source="fine",
|
||||
rect=(0, 0, base.shape[1], base.shape[0])))
|
||||
id_res, bank_res = _extract(views, expected_name)
|
||||
if bank_res.found and bank_res.luhn_ok:
|
||||
break
|
||||
|
||||
# 5.2 小图放大补识别:短边 <800px 的缩略图,卡号笔画往往只有几个像素
|
||||
if (not (bank_res.found and bank_res.luhn_ok)) and min(W, H) < 800:
|
||||
big = resize_side(img_work, min_side=2400)
|
||||
for vname, var in gray_variants(to_gray(big), upscale=1.0):
|
||||
if vname not in ("gray", "adaptive"):
|
||||
continue
|
||||
add_view(View(name=f"zoom_{vname}", image=var, source="fine",
|
||||
rect=(0, 0, big.shape[1], big.shape[0])))
|
||||
id_res, bank_res = _extract(views, expected_name)
|
||||
if bank_res.found and bank_res.luhn_ok:
|
||||
break
|
||||
|
||||
# 5.3 数字带窄条:跳过检测网络,多路增强 + 出现合法卡号就收工
|
||||
if not (bank_res.found and bank_res.luhn_ok):
|
||||
digit_views = [v for v in views if v.source in ("fine", "quad", "coarse")]
|
||||
digit_views.sort(key=lambda v: -_digitish(v.text))
|
||||
for v in digit_views[:2]:
|
||||
for rows in _strip_variants(v, v.lines, want=2):
|
||||
extra_rows.extend(rows)
|
||||
extra_used += len(rows)
|
||||
id_res, bank_res = _extract(views, expected_name, extra_rows=extra_rows)
|
||||
if bank_res.found and bank_res.luhn_ok:
|
||||
break
|
||||
if bank_res.found and bank_res.luhn_ok:
|
||||
break
|
||||
|
||||
# ---- 6) 兜底:卡号/身份证没读出来时,试一次卡片矫正
|
||||
# 注意条件不能只看「几乎没文字」:手机拍卡常能认出「招商银行/银联」几行,
|
||||
# 文字够多但卡号一个都没检出,这时同样需要矫正后再认一遍。
|
||||
if not fast and (len([ln for v in views for ln in v.lines]) < 3
|
||||
or (not (bank_res.found and bank_res.luhn_ok)
|
||||
and bankcard.looks_like_bank_card(
|
||||
" ".join(v.text for v in views)))):
|
||||
quads = list(find_cards(img_work, max_cards=2, warp_width=1712))
|
||||
if not quads:
|
||||
# Canny 四边形找不到(反光打断卡边)时,退到色块/边缘兜底
|
||||
flat = locate_bank_card(img_work, warp_width=1712)
|
||||
if flat is not None:
|
||||
add_view(View(name="quad1", image=flat, source="quad",
|
||||
rect=(0, 0, flat.shape[1], flat.shape[0])))
|
||||
for i, r in enumerate(quads):
|
||||
if r.warped is not None and r.warped.size:
|
||||
add_view(View(name=f"quad{i + 1}", image=r.warped, source="quad",
|
||||
rect=cv2.boundingRect(np.asarray(r.pts, dtype=np.int32))))
|
||||
if len(views) > 1:
|
||||
id_res, bank_res = _extract(views, expected_name)
|
||||
|
||||
# ---- 5) 汇总标记
|
||||
flags: List[str] = []
|
||||
if id_res.found and not id_res.checksum_ok:
|
||||
flags.append("id_checksum_fail")
|
||||
if not id_res.found:
|
||||
flags.append("id_not_found")
|
||||
if not bank_res.found:
|
||||
flags.append("card_not_found")
|
||||
elif not bank_res.luhn_ok:
|
||||
flags.append("card_luhn_fail")
|
||||
if bank_res.found and bank_res.length not in (16, 18, 19):
|
||||
flags.append("card_length_odd")
|
||||
if id_res.number and bank_res.number and id_res.number == bank_res.number:
|
||||
flags.append("same_number_id_and_card")
|
||||
if expected_name and id_res.name and id_res.name != expected_name:
|
||||
flags.append("id_name_mismatch")
|
||||
if min(H, W) < 400:
|
||||
flags.append("low_resolution")
|
||||
if chosen_rot:
|
||||
flags.append(f"rotated_{chosen_rot * 90}")
|
||||
|
||||
# 所有识别到过的数字片段(含被淘汰的候选),供「和已知号码比对」时找证据
|
||||
runs: List[str] = []
|
||||
for row in rows_of(views) + extra_rows:
|
||||
runs.extend(number_runs(row, 6))
|
||||
unique_runs = list(dict.fromkeys(runs))[:40]
|
||||
|
||||
res = {
|
||||
"file": str(p), "filename": p.name,
|
||||
"bytes": p.stat().st_size if p.exists() else 0,
|
||||
"width": W, "height": H,
|
||||
"sha256": sha256_file(p),
|
||||
"elapsed_s": round(time.time() - t0, 2),
|
||||
"rotation_applied": chosen_rot * 90,
|
||||
"views": [v.to_dict() for v in views],
|
||||
"layout": _layout(views),
|
||||
"id_card": id_res.to_dict(),
|
||||
"bank_card": bank_res.to_dict(),
|
||||
"digit_runs": unique_runs,
|
||||
"flags": flags,
|
||||
"ocr_passes": len(views) + extra_used,
|
||||
}
|
||||
if mark_dir:
|
||||
res["marks"] = _save_marks(views, str(mark_dir), p.stem)
|
||||
return res
|
||||
|
||||
|
||||
def idline(views: Sequence[View], kind: str) -> List[Line]:
|
||||
focus = [v for v in views if v.kind in (kind, "both")]
|
||||
return [ln for v in (focus or views) for ln in v.lines]
|
||||
|
||||
|
||||
def bline(views: Sequence[View], kind: str) -> List[Line]:
|
||||
focus = [v for v in views if v.kind in (kind, "both")]
|
||||
return [ln for v in (focus or views) for ln in v.lines]
|
||||
|
||||
|
||||
def rows_of(views: Sequence[View], kind: str = "") -> List[str]:
|
||||
"""按视图取「行文本」;kind 传 id/bank 时只取对应卡片视图(没有则退回全部)。"""
|
||||
focus = [v for v in views if v.kind in (kind, "both")] if kind else list(views)
|
||||
out: List[str] = []
|
||||
for v in (focus or views):
|
||||
out.extend(row_texts(v.lines))
|
||||
return out
|
||||
|
||||
|
||||
def _extract(views: Sequence[View], expected_name: str,
|
||||
extra_rows: Optional[Sequence[str]] = None):
|
||||
"""按视图集合跑一遍字段抽取(extra_rows 是补充识别出来的行文本)。"""
|
||||
all_text = " ".join(v.text for v in views)
|
||||
extra = list(extra_rows or ())
|
||||
id_res = idcard.parse(idline(views, "id"), expected_name=expected_name,
|
||||
full_text=all_text, rows=rows_of(views, "id") + extra)
|
||||
bank_res = bankcard.parse(bline(views, "bank"), all_text,
|
||||
exclude=[id_res.number] if id_res.number else (),
|
||||
rows=rows_of(views, "bank") + extra)
|
||||
return id_res, bank_res
|
||||
|
||||
|
||||
def _layout(views: Sequence[View]) -> str:
|
||||
kinds = {v.kind for v in views}
|
||||
if "both" in kinds or ("id" in kinds and "bank" in kinds):
|
||||
return "both"
|
||||
if kinds == {"id"}:
|
||||
return "id_only"
|
||||
if kinds == {"bank"}:
|
||||
return "bank_only"
|
||||
return "unknown"
|
||||
|
||||
|
||||
def sha256_file(p: Path) -> str:
|
||||
h = hashlib.sha256()
|
||||
with open(p, "rb") as f:
|
||||
for chunk in iter(lambda: f.read(1 << 20), b""):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 标注图
|
||||
_FONT_CACHE: Dict[int, object] = {}
|
||||
|
||||
|
||||
def _font(size: int = 16):
|
||||
if size in _FONT_CACHE:
|
||||
return _FONT_CACHE[size]
|
||||
try:
|
||||
from PIL import ImageFont # noqa: PLC0415
|
||||
|
||||
for cand in (r"C:\Windows\Fonts\msyh.ttc", r"C:\Windows\Fonts\simhei.ttf",
|
||||
r"C:\Windows\Fonts\simsun.ttc"):
|
||||
if os.path.isfile(cand):
|
||||
try:
|
||||
_FONT_CACHE[size] = ImageFont.truetype(cand, size)
|
||||
return _FONT_CACHE[size]
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
_FONT_CACHE[size] = None
|
||||
return None
|
||||
|
||||
|
||||
def _save_marks(views: Sequence[View], out_dir: str, stem: str) -> List[str]:
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
font = _font(16)
|
||||
paths: List[str] = []
|
||||
for v in views:
|
||||
base = v.image.copy()
|
||||
for ln in v.lines:
|
||||
cv2.rectangle(base, (ln.left, ln.top), (ln.right, ln.bottom), (0, 200, 0), 1)
|
||||
if font is not None:
|
||||
from PIL import Image, ImageDraw # noqa: PLC0415
|
||||
|
||||
pil = Image.fromarray(cv2.cvtColor(base, cv2.COLOR_BGR2RGB))
|
||||
draw = ImageDraw.Draw(pil)
|
||||
for ln in v.lines:
|
||||
ty = ln.top - 18 if ln.top >= 18 else ln.bottom + 2
|
||||
draw.text((ln.left, ty), ln.text[:24], fill=(255, 0, 0), font=font)
|
||||
canvas = np.array(pil)[:, :, ::-1]
|
||||
else:
|
||||
canvas = base
|
||||
out = os.path.join(out_dir, f"{stem}.{v.name}.{v.kind}.png")
|
||||
ok, buf = cv2.imencode(".png", canvas)
|
||||
if ok:
|
||||
buf.tofile(out)
|
||||
paths.append(out)
|
||||
return paths
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 批量
|
||||
def analyze_folder(root: str, expected_names: Optional[Dict[str, str]] = None,
|
||||
mark_dir: Optional[str] = None, extra_passes: bool = True,
|
||||
fast: bool = False, limit: int = 0) -> List[dict]:
|
||||
"""按「姓名/图片」目录结构批量识别,同人多图合并成一条记录。"""
|
||||
root_p = Path(root)
|
||||
if not root_p.is_dir():
|
||||
raise FileNotFoundError(f"目录不存在:{root}")
|
||||
persons: List[dict] = []
|
||||
cache: Dict[str, dict] = {} # sha256 → 识别结果(同一张图被传到两列时只跑一遍)
|
||||
for d in sorted(root_p.iterdir()):
|
||||
if not d.is_dir():
|
||||
continue
|
||||
imgs = sorted(p for p in d.iterdir() if p.is_file() and p.suffix.lower() in IMAGE_EXT)
|
||||
if not imgs:
|
||||
continue
|
||||
name = (expected_names or {}).get(d.name, d.name)
|
||||
rows = []
|
||||
for p in (imgs[:limit] if limit else imgs):
|
||||
digest = ""
|
||||
try:
|
||||
digest = sha256_file(p)
|
||||
if digest in cache:
|
||||
cached = cache[digest]
|
||||
rows.append({**cached, "file": str(p), "filename": p.name,
|
||||
"reused_from": cached.get("filename")})
|
||||
continue
|
||||
res = analyze_image(str(p), expected_name=name, mark_dir=mark_dir,
|
||||
extra_passes=extra_passes, fast=fast)
|
||||
cache[digest] = res
|
||||
rows.append(res)
|
||||
logger.info("%s/%s 完成:%.1fs id=%s card=%s", d.name, p.name,
|
||||
res.get("elapsed_s", 0),
|
||||
res.get("id_card", {}).get("number") or "-",
|
||||
res.get("bank_card", {}).get("number") or "-")
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.exception("识别失败:%s", p)
|
||||
rows.append({"file": str(p), "filename": p.name, "ok": False,
|
||||
"sha256": digest, "error": f"{type(e).__name__}: {e}"})
|
||||
persons.append(_merge_person(d.name, name, rows))
|
||||
return persons
|
||||
|
||||
|
||||
def _merge_person(folder_name: str, expected_name: str, rows: List[dict]) -> dict:
|
||||
ok_rows = [r for r in rows if r.get("ok", True) and "id_card" in r]
|
||||
hashes = {r.get("sha256") for r in ok_rows if r.get("sha256")}
|
||||
|
||||
def best(key: str, prefer: str) -> dict:
|
||||
# 号码没识别出来,但卡面银行名 / 身份证姓名读到了,也要保留(交叉核对时有用)
|
||||
items = [r[key] for r in ok_rows
|
||||
if r.get(key, {}).get("found") or r.get(key, {}).get("bank")
|
||||
or r.get(key, {}).get("name")]
|
||||
if not items:
|
||||
return {}
|
||||
rank = {"high": 3, "medium": 2, "low": 1}
|
||||
|
||||
def score(d: dict) -> tuple:
|
||||
return (1 if d.get(prefer) else 0, rank.get(d.get("confidence"), 0),
|
||||
max([c.get("score", 0) for c in d.get("candidates", [])] or [0]))
|
||||
|
||||
return max(items, key=score)
|
||||
|
||||
id_best = best("id_card", "checksum_ok")
|
||||
bank_best = best("bank_card", "luhn_ok")
|
||||
flags: List[str] = []
|
||||
if len(ok_rows) < 2:
|
||||
flags.append("missing_one_photo")
|
||||
if len(hashes) == 1 and len(ok_rows) >= 2:
|
||||
flags.append("duplicate_photo")
|
||||
# 只按「人」的最终结果判定字段问题,不把「这张图没拍到身份证」当成整人的问题
|
||||
if not id_best.get("number"):
|
||||
flags.append("id_not_found")
|
||||
elif not id_best.get("checksum_ok"):
|
||||
flags.append("id_checksum_fail")
|
||||
elif expected_name and id_best.get("name") and id_best["name"] != expected_name:
|
||||
flags.append("id_name_mismatch")
|
||||
if not bank_best.get("number"):
|
||||
flags.append("card_not_found")
|
||||
elif not bank_best.get("luhn_ok"):
|
||||
flags.append("card_luhn_fail")
|
||||
elif bank_best.get("length") not in (16, 18, 19):
|
||||
flags.append("card_length_odd")
|
||||
# 图像质量类问题才从单图冒泡上来
|
||||
for r in ok_rows:
|
||||
for f in r.get("flags", []):
|
||||
if f in ("low_resolution", "rotated_90", "rotated_180", "rotated_270",
|
||||
"card_not_located", "multiple_cards_in_photo") and f not in flags:
|
||||
flags.append(f)
|
||||
|
||||
return {
|
||||
"folder": folder_name, "expected_name": expected_name,
|
||||
"files": [{"filename": r.get("filename"), "sha256": (r.get("sha256") or "")[:16],
|
||||
"layout": r.get("layout"), "flags": r.get("flags", [])} for r in rows],
|
||||
"id_card": id_best, "bank_card": bank_best,
|
||||
"duplicate_photo": len(hashes) == 1 and len(ok_rows) >= 2,
|
||||
"flags": flags,
|
||||
"raw": ok_rows,
|
||||
}
|
||||
|
||||
|
||||
def _disp_width(s: str) -> int:
|
||||
import unicodedata # noqa: PLC0415
|
||||
|
||||
return sum(2 if unicodedata.east_asian_width(c) in ("W", "F") else 1 for c in str(s))
|
||||
|
||||
|
||||
def _pad(s: str, width: int) -> str:
|
||||
s = str(s)
|
||||
return s + " " * max(1, width - _disp_width(s))
|
||||
|
||||
|
||||
def summary_table(persons: Sequence[dict]) -> str:
|
||||
head = (_pad("姓名", 9) + _pad("身份证号", 22) + _pad("校验", 5) + _pad("银行卡号", 24)
|
||||
+ _pad("Luhn", 6) + _pad("发卡行", 20) + "标记")
|
||||
lines = [head, "-" * 104]
|
||||
for p in persons:
|
||||
idc, bk = p.get("id_card", {}), p.get("bank_card", {})
|
||||
lines.append(
|
||||
_pad(p.get("folder", ""), 9)
|
||||
+ _pad(idc.get("number") or "-", 22)
|
||||
+ _pad("✓" if idc.get("checksum_ok") else "✗", 5)
|
||||
+ _pad(bk.get("number") or "-", 24)
|
||||
+ _pad("✓" if bk.get("luhn_ok") else "✗", 6)
|
||||
+ _pad(bk.get("bank") or "-", 20)
|
||||
+ ",".join(p.get("flags", [])))
|
||||
return "\n".join(lines)
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""核对工作簿:把识别结果导出成 Excel,留出「正确答案」列给人工填写,并可回读算准确率。
|
||||
|
||||
用法(代码):
|
||||
from cardocr.review import write_review_workbook, verify_workbook
|
||||
write_review_workbook(persons, "识别核对表.xlsx")
|
||||
print(verify_workbook("识别核对表.xlsx"))
|
||||
|
||||
命令行:
|
||||
python -m cardocr review --json result.json --out 识别核对表.xlsx
|
||||
python -m cardocr verify 识别核对表.xlsx
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Dict, List, Optional, Sequence
|
||||
|
||||
from openpyxl import Workbook, load_workbook
|
||||
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
HEADER_FILL = PatternFill("solid", fgColor="1F4E79")
|
||||
INPUT_FILL = PatternFill("solid", fgColor="FFF2CC")
|
||||
THIN = Side(style="thin", color="BFBFBF")
|
||||
BORDER = Border(left=THIN, right=THIN, top=THIN, bottom=THIN)
|
||||
|
||||
# 逐人核对表列定义:(key, 列名, 宽度)
|
||||
PERSON_COLS = [
|
||||
("pid", "ID", 8),
|
||||
("folder", "姓名(文件夹)", 12),
|
||||
("id_number", "身份证号(识别)", 22),
|
||||
("id_ok", "身份证校验", 10),
|
||||
("id_name", "身份证姓名(识别)", 14),
|
||||
("card_number", "银行卡号(识别)", 22),
|
||||
("card_ok", "Luhn", 7),
|
||||
("bank", "发卡行", 16),
|
||||
("id_conf", "身份证置信度", 12),
|
||||
("card_conf", "卡号置信度", 11),
|
||||
("photos", "图片数", 8),
|
||||
("files", "照片文件", 40),
|
||||
("dup", "重复图片", 9),
|
||||
("flags", "标记", 34),
|
||||
("evidence", "识别说明", 34),
|
||||
("truth_id", "【待填】正确身份证号", 22),
|
||||
("truth_name", "【待填】正确姓名", 14),
|
||||
("truth_card", "【待填】正确银行卡号", 22),
|
||||
("verdict", "【待填】判定", 10),
|
||||
("note", "【待填】说明", 26),
|
||||
]
|
||||
|
||||
IMAGE_COLS = [
|
||||
("iid", "图片ID", 10),
|
||||
("folder", "姓名(文件夹)", 12),
|
||||
("filename", "文件名", 34),
|
||||
("size", "分辨率", 14),
|
||||
("kb", "大小KB", 9),
|
||||
("layout", "布局", 10),
|
||||
("id_number", "身份证号(识别)", 22),
|
||||
("id_ok", "身份证校验", 10),
|
||||
("id_name", "姓名(识别)", 12),
|
||||
("card_number", "卡号(识别)", 22),
|
||||
("card_ok", "Luhn", 7),
|
||||
("bank", "发卡行", 16),
|
||||
("conf", "置信度", 10),
|
||||
("elapsed", "用时s", 8),
|
||||
("sha", "SHA256前12", 15),
|
||||
("flags", "标记", 30),
|
||||
("cands", "卡号候选", 30),
|
||||
("path", "路径", 55),
|
||||
]
|
||||
|
||||
|
||||
def _style_sheet(ws, cols: Sequence[tuple], truth_from: int = 0) -> None:
|
||||
for i, (_key, title, width) in enumerate(cols, 1):
|
||||
c = ws.cell(row=1, column=i, value=title)
|
||||
c.font = Font(bold=True, color="FFFFFF", size=10)
|
||||
c.fill = HEADER_FILL
|
||||
c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||
c.border = BORDER
|
||||
ws.column_dimensions[get_column_letter(i)].width = width
|
||||
ws.row_dimensions[1].height = 30
|
||||
ws.freeze_panes = "A2"
|
||||
if truth_from:
|
||||
for i in range(truth_from, len(cols) + 1):
|
||||
ws.cell(row=1, column=i).fill = PatternFill("solid", fgColor="C00000")
|
||||
|
||||
|
||||
def _fmt_id(p: dict) -> Dict[str, object]:
|
||||
idc = p.get("id_card") or {}
|
||||
bk = p.get("bank_card") or {}
|
||||
flags = p.get("flags", [])
|
||||
notes = list(idc.get("evidence") or [])
|
||||
if "low_resolution" in flags and bk.get("number"):
|
||||
notes.append("⚠ 原图是缩略图,卡号建议人工复核")
|
||||
if bk.get("number") and not bk.get("luhn_ok"):
|
||||
notes.append("⚠ 卡号未过 Luhn")
|
||||
return {
|
||||
"pid": "",
|
||||
"folder": p.get("folder", ""),
|
||||
"id_number": idc.get("number") or "未识别",
|
||||
"id_ok": "✓" if idc.get("checksum_ok") else ("✗" if idc.get("number") else ""),
|
||||
"id_name": idc.get("name") or "未识别",
|
||||
"card_number": bk.get("number") or "未识别",
|
||||
"card_ok": "✓" if bk.get("luhn_ok") else ("✗" if bk.get("number") else ""),
|
||||
"bank": bk.get("bank") or "-",
|
||||
"id_conf": idc.get("confidence", "") or "-",
|
||||
"card_conf": bk.get("confidence", "") or "-",
|
||||
"photos": len(p.get("files") or []),
|
||||
"files": ";".join(f.get("filename") or "" for f in (p.get("files") or [])),
|
||||
"dup": "是" if p.get("duplicate_photo") else "否",
|
||||
"flags": ",".join(p.get("flags", [])),
|
||||
"evidence": ";".join(notes) or "",
|
||||
}
|
||||
|
||||
|
||||
def _fmt_image(p: dict, r: dict, iid: str) -> Dict[str, object]:
|
||||
idc = r.get("id_card") or {}
|
||||
bk = r.get("bank_card") or {}
|
||||
cands = bk.get("candidates") or []
|
||||
top = [c.get("number", "") for c in cands[:2]]
|
||||
return {
|
||||
"iid": iid,
|
||||
"folder": p.get("folder", ""),
|
||||
"filename": r.get("filename", ""),
|
||||
"size": f"{r.get('width', '')}x{r.get('height', '')}",
|
||||
"kb": round((r.get("bytes") or 0) / 1024),
|
||||
"layout": r.get("layout", ""),
|
||||
"id_number": idc.get("number") or "未识别",
|
||||
"id_ok": "✓" if idc.get("checksum_ok") else ("✗" if idc.get("number") else ""),
|
||||
"id_name": idc.get("name") or "未识别",
|
||||
"card_number": bk.get("number") or "未识别",
|
||||
"card_ok": "✓" if bk.get("luhn_ok") else ("✗" if bk.get("number") else ""),
|
||||
"bank": bk.get("bank") or "-",
|
||||
"conf": f"身份证:{idc.get('confidence', '') or '-'} 卡:{bk.get('confidence', '') or '-'}",
|
||||
"elapsed": r.get("elapsed_s", ""),
|
||||
"sha": (r.get("sha256") or "")[:12],
|
||||
"flags": ",".join(r.get("flags", [])),
|
||||
"cands": " / ".join(top),
|
||||
"path": r.get("file", ""),
|
||||
}
|
||||
|
||||
|
||||
def write_review_workbook(persons: Sequence[dict], path: str,
|
||||
source_root: str = "") -> str:
|
||||
"""导出核对工作簿(3 个 sheet:逐人核对 / 逐图明细 / 填写说明)。"""
|
||||
wb = Workbook()
|
||||
ws1 = wb.active
|
||||
ws1.title = "逐人核对"
|
||||
ws2 = wb.create_sheet("逐图明细")
|
||||
ws3 = wb.create_sheet("填写说明")
|
||||
|
||||
truth_from = next((i for i, (_k, _t, _w) in enumerate(PERSON_COLS, 1)
|
||||
if _k.startswith("truth")), 0)
|
||||
_style_sheet(ws1, PERSON_COLS, truth_from=truth_from)
|
||||
_style_sheet(ws2, IMAGE_COLS)
|
||||
|
||||
stats = {"persons": len(persons), "photos": 0}
|
||||
id_ok = id_bad = 0
|
||||
card_ok = card_bad = 0
|
||||
r1 = 2
|
||||
r2 = 2
|
||||
for idx, p in enumerate(persons, 1):
|
||||
pid = f"P{idx:03d}"
|
||||
row = _fmt_id(p)
|
||||
row["pid"] = pid
|
||||
for col, (_key, _title, _w) in enumerate(PERSON_COLS, 1):
|
||||
c = ws1.cell(row=r1, column=col, value=row.get(_key, ""))
|
||||
c.border = BORDER
|
||||
c.alignment = Alignment(horizontal="left", vertical="center", wrap_text=True)
|
||||
if col >= 15:
|
||||
c.fill = INPUT_FILL
|
||||
ws1.row_dimensions[r1].height = 22
|
||||
if row["id_ok"] == "✓":
|
||||
id_ok += 1
|
||||
elif row["id_ok"] == "✗":
|
||||
id_bad += 1
|
||||
if row["card_ok"] == "✓":
|
||||
card_ok += 1
|
||||
elif row["card_ok"] == "✗":
|
||||
card_bad += 1
|
||||
|
||||
imgs = [r for r in (p.get("raw") or []) if r.get("id_card") or r.get("bank_card")]
|
||||
for j, r in enumerate(imgs, 1):
|
||||
row2 = _fmt_image(p, r, f"{pid}-{'AB'[min(j - 1, 1)]}")
|
||||
for col, (_key, _title, _w) in enumerate(IMAGE_COLS, 1):
|
||||
c = ws2.cell(row=r2, column=col, value=row2.get(_key, ""))
|
||||
c.border = BORDER
|
||||
c.alignment = Alignment(horizontal="left", vertical="center", wrap_text=True)
|
||||
ws2.row_dimensions[r2].height = 22
|
||||
r2 += 1
|
||||
stats["photos"] += 1
|
||||
r1 += 1
|
||||
|
||||
ws1.auto_filter.ref = f"A1:{get_column_letter(len(PERSON_COLS))}{r1 - 1}"
|
||||
ws2.auto_filter.ref = f"A1:{get_column_letter(len(IMAGE_COLS))}{r2 - 1}"
|
||||
ws3.column_dimensions["A"].width = 90
|
||||
lines = [
|
||||
"填写说明",
|
||||
"",
|
||||
"1. 只需要填「逐人核对」里黄色底的 5 列:正确身份证号 / 正确姓名 / 正确银行卡号 / 判定 / 说明。",
|
||||
"2. 判定填 对 / 错 / 部分:整行都识别对了填 对;哪里错了填 错,并在说明里写清楚(例如「卡号错 2 位」)。",
|
||||
"3. 识别为空但实际有值的,正确列请照实填写(这是最有价值的样本)。",
|
||||
"4. 身份证校验 / Luhn 是识别结果自带的数学校验,不代表业务上一定对;以你填的为准。",
|
||||
"5. 填好后运行:python -m cardocr verify 本文件.xlsx,会自动算准确率。",
|
||||
"",
|
||||
"标记含义",
|
||||
" duplicate_photo 同一个人两列上传了同一张图(数据录入问题)",
|
||||
" missing_one_photo 只找到一张照片",
|
||||
" id_not_found 没有识别到身份证号",
|
||||
" id_checksum_fail 识别到 18 位号码但校验码不通过",
|
||||
" id_name_mismatch 身份证姓名与文件夹姓名不一致",
|
||||
" card_not_found 没有识别到银行卡号",
|
||||
" card_luhn_fail 识别到候选卡号但 Luhn 不通过",
|
||||
" card_length_odd 卡号位数不是 16/18/19",
|
||||
" low_resolution 原图短边 < 400px(多为缩略图)",
|
||||
" rotated_90 / rotated_270 照片是横拍的,已自动转正后识别",
|
||||
" multiple_cards_in_photo 一张照片里有不止一张卡",
|
||||
" card_not_located 没定位到卡片轮廓,按整图识别",
|
||||
"",
|
||||
f"本次统计:{stats['persons']} 人 / {stats['photos']} 张图;"
|
||||
f"身份证号有号码且校验通过 {id_ok} 人、有号码但校验失败 {id_bad} 人;"
|
||||
f"卡号 Luhn 通过 {card_ok} 人、有候选但未通过 {card_bad} 人。",
|
||||
f"图片根目录:{source_root}" if source_root else "",
|
||||
]
|
||||
for i, text in enumerate(lines, 1):
|
||||
c = ws3.cell(row=i, column=1, value=text)
|
||||
c.alignment = Alignment(horizontal="left", vertical="center", wrap_text=True)
|
||||
if i == 1:
|
||||
c.font = Font(bold=True, size=14)
|
||||
else:
|
||||
c.font = Font(size=10.5)
|
||||
|
||||
wb.save(path)
|
||||
return path
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 回读核对
|
||||
def verify_workbook(path: str) -> dict:
|
||||
"""读回填好的核对表,统计身份证号 / 卡号 / 姓名三项准确率。"""
|
||||
wb = load_workbook(path, data_only=True)
|
||||
ws = wb["逐人核对"]
|
||||
idx = {c.value: i for i, c in enumerate(ws[1], 1) if c.value}
|
||||
|
||||
def cell(row, name: str) -> str:
|
||||
i = idx.get(name)
|
||||
if not i:
|
||||
return ""
|
||||
v = row[i - 1].value
|
||||
return "" if v is None else str(v).strip()
|
||||
|
||||
res = {"rows": 0, "id": [0, 0, 0], "name": [0, 0, 0], "card": [0, 0, 0],
|
||||
"skipped": []}
|
||||
errors: List[dict] = []
|
||||
|
||||
def is_truth(v: str) -> bool:
|
||||
"""「人工也无法识别 / 无 / -」这类填写不算真值,跳过统计。"""
|
||||
return bool(v) and v not in ("无", "-", "/") and "无法识别" not in v
|
||||
|
||||
for row in ws.iter_rows(min_row=2):
|
||||
pid = cell(row, "ID")
|
||||
if not pid:
|
||||
continue
|
||||
t_id = cell(row, "【待填】正确身份证号")
|
||||
t_name = cell(row, "【待填】正确姓名")
|
||||
t_card = cell(row, "【待填】正确银行卡号")
|
||||
if not (t_id or t_name or t_card):
|
||||
continue
|
||||
res["rows"] += 1
|
||||
for label, v in (("身份证号", t_id), ("姓名", t_name), ("银行卡号", t_card)):
|
||||
if v and not is_truth(v):
|
||||
res["skipped"].append({"ID": pid, "字段": label, "填写": v})
|
||||
|
||||
def cmp(truth: str, got_key: str, bucket: List[int], label: str) -> None:
|
||||
if not is_truth(truth):
|
||||
return
|
||||
got = cell(row, got_key)
|
||||
if got == "未识别":
|
||||
got = ""
|
||||
ok = got.upper() == truth.upper()
|
||||
bucket[0] += 1
|
||||
bucket[1 if ok else 2] += 1
|
||||
if not ok:
|
||||
errors.append({"ID": pid, "姓名": cell(row, "姓名(文件夹)"), "字段": label,
|
||||
"识别": got, "正确": truth})
|
||||
|
||||
cmp(t_id, "身份证号(识别)", res["id"], "身份证号")
|
||||
cmp(t_name, "身份证姓名(识别)", res["name"], "姓名")
|
||||
cmp(t_card, "银行卡号(识别)", res["card"], "银行卡号")
|
||||
|
||||
out = {"核对行数": res["rows"], "明细": {}, "错误": errors,
|
||||
"跳过": res["skipped"]}
|
||||
for key, label in (("id", "身份证号"), ("name", "姓名"), ("card", "银行卡号")):
|
||||
total, right, wrong = res[key]
|
||||
out["明细"][label] = {
|
||||
"有真值": total, "正确": right, "错误": wrong,
|
||||
"准确率": f"{(right / total * 100 if total else 0):.1f}%",
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
def print_verify(result: dict) -> None:
|
||||
print(f"核对行数:{result['核对行数']}")
|
||||
for label, d in result["明细"].items():
|
||||
print(f" {label}: 有真值 {d['有真值']},正确 {d['正确']},错误 {d['错误']},准确率 {d['准确率']}")
|
||||
if result["错误"]:
|
||||
print("\n错误明细:")
|
||||
for e in result["错误"]:
|
||||
print(f" {e['ID']} {e['姓名']} {e['字段']}:识别「{e['识别']}」 → 正确「{e['正确']}」")
|
||||
|
||||
|
||||
def load_persons(json_path: str) -> List[dict]:
|
||||
with open(json_path, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
return data.get("persons") or data.get("images") or []
|
||||
|
||||
|
||||
def load_truth_workbook(path: str) -> Dict[str, Dict[str, str]]:
|
||||
"""读回人工填好的核对表:文件夹姓名 → {id, name, card}。"""
|
||||
wb = load_workbook(path, data_only=True)
|
||||
ws = wb["逐人核对"]
|
||||
idx = {c.value: i for i, c in enumerate(ws[1], 1) if c.value}
|
||||
out: Dict[str, Dict[str, str]] = {}
|
||||
for row in ws.iter_rows(min_row=2, values_only=True):
|
||||
def cell(name: str) -> str:
|
||||
i = idx.get(name)
|
||||
if not i:
|
||||
return ""
|
||||
v = row[i - 1]
|
||||
return "" if v is None else str(v).strip()
|
||||
|
||||
folder = cell("姓名(文件夹)")
|
||||
if not folder:
|
||||
continue
|
||||
out[folder] = {"id": cell("【待填】正确身份证号"),
|
||||
"name": cell("【待填】正确姓名"),
|
||||
"card": cell("【待填】正确银行卡号"),
|
||||
"note": cell("【待填】说明")}
|
||||
return out
|
||||
|
||||
@@ -0,0 +1,423 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""号码校验与纠错:身份证 18 位校验码、银行卡 Luhn、OCR 易混字符还原。
|
||||
|
||||
两种号码都自带数学校验位,这让我们能把 OCR 出来的「b214 8338 3071 20bb」
|
||||
这类文本,在有限候选里反推出唯一合法号码——这是本模块敢离线跑的关键。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Dict, Iterable, List, Optional, Sequence, Tuple, Union
|
||||
|
||||
# ---------------------------------------------------------------- 字符归一
|
||||
# OCR 把数字认成字母(或反过来)的常见映射;值是「可能对应的数字」
|
||||
_CONFUSABLE: Dict[str, Tuple[str, ...]] = {
|
||||
"O": ("0",), "o": ("0",), "D": ("0",),
|
||||
"I": ("1",), "l": ("1",), "|": ("1",), "!": ("1",),
|
||||
"L": ("1",), "Z": ("2",), "z": ("2",),
|
||||
"S": ("5",), "s": ("5",), "$": ("5",),
|
||||
"B": ("6", "8"), "b": ("6", "8"),
|
||||
"G": ("9", "6"), "g": ("9", "6"), "q": ("9", "6"),
|
||||
"A": ("4",), "a": ("4",), "E": ("8",), "e": ("8",),
|
||||
"T": ("7",), "t": ("7",), "C": ("0", "6"),
|
||||
"X": ("X",), "x": ("X",),
|
||||
}
|
||||
|
||||
PRIMARY: Dict[str, str] = {k: v[0] for k, v in _CONFUSABLE.items()}
|
||||
|
||||
|
||||
def normalize_text(text: str) -> str:
|
||||
"""全角转半角、去空白(OCR 常在数字间插空格)。"""
|
||||
out = []
|
||||
for ch in str(text or ""):
|
||||
o = ord(ch)
|
||||
if 0xFF01 <= o <= 0xFF5E: # 全角 ASCII
|
||||
ch = chr(o - 0xFEE0)
|
||||
elif o == 0x3000: # 全角空格
|
||||
ch = " "
|
||||
out.append(ch)
|
||||
return re.sub(r"\s+", "", "".join(out))
|
||||
|
||||
|
||||
def digitize(text: str) -> Tuple[str, List[int]]:
|
||||
"""把文本压成数字串(字母按首选映射),并返回「有歧义」的位置下标。"""
|
||||
s = normalize_text(text)
|
||||
digits, ambiguous = [], []
|
||||
for ch in s:
|
||||
if ch.isdigit():
|
||||
digits.append(ch)
|
||||
elif ch in _CONFUSABLE:
|
||||
digits.append(PRIMARY[ch])
|
||||
if len(_CONFUSABLE[ch]) > 1:
|
||||
ambiguous.append(len(digits) - 1)
|
||||
return "".join(digits), ambiguous
|
||||
|
||||
|
||||
def digit_runs(text: str, min_len: int = 13) -> List[str]:
|
||||
"""从一段文本里抽出连续数字串(允许中间夹易混字母)。"""
|
||||
s = normalize_text(text)
|
||||
# 把易混字母当数字,再做游程切分
|
||||
norm = "".join(PRIMARY.get(c, c) if not c.isdigit() else c for c in s)
|
||||
runs = re.findall(r"[0-9]{%d,}" % min_len, norm)
|
||||
return runs
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 身份证
|
||||
# 18 位:6 位地址 + 8 位生日 + 3 位顺序 + 1 位校验
|
||||
_ID_WEIGHTS = (7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2)
|
||||
_ID_CHECK = "10X98765432"
|
||||
|
||||
|
||||
def id_checksum_ok(no: str) -> bool:
|
||||
if len(no) != 18:
|
||||
return False
|
||||
if not re.fullmatch(r"\d{17}[\dXx]", no):
|
||||
return False
|
||||
total = sum(int(no[i]) * _ID_WEIGHTS[i] for i in range(17))
|
||||
return _ID_CHECK[total % 11] == no[17].upper()
|
||||
|
||||
|
||||
def id_birth(no: str) -> str:
|
||||
"""从身份证号取生日 YYYY-MM-DD(含合法性检查,不合法返回空)。"""
|
||||
if len(no) != 18:
|
||||
return ""
|
||||
y, m, d = int(no[6:10]), int(no[10:12]), int(no[12:14])
|
||||
if not (1900 <= y <= 2020) or not (1 <= m <= 12) or not (1 <= d <= 31):
|
||||
return ""
|
||||
return f"{y:04d}-{m:02d}-{d:02d}"
|
||||
|
||||
|
||||
def id_gender(no: str) -> str:
|
||||
if len(no) != 18:
|
||||
return ""
|
||||
return "男" if int(no[16]) % 2 == 1 else "女"
|
||||
|
||||
|
||||
def id_region(no: str) -> str:
|
||||
return no[:2] if len(no) == 18 else ""
|
||||
|
||||
|
||||
_VALID_PROVINCE = {f"{i:02d}" for i in range(11, 66)}
|
||||
|
||||
|
||||
def id_plausible(no: str) -> bool:
|
||||
return (len(no) == 18
|
||||
and id_region(no) in _VALID_PROVINCE
|
||||
and bool(id_birth(no)))
|
||||
|
||||
|
||||
@dataclass
|
||||
class IdCandidate:
|
||||
number: str
|
||||
checksum_ok: bool
|
||||
origin: str = "raw" # raw / repaired
|
||||
edits: int = 0
|
||||
score: float = 0.0
|
||||
|
||||
|
||||
def id_candidates(text: Union[str, Sequence[str]], limit: int = 8) -> List[IdCandidate]:
|
||||
"""从 OCR 文本里找身份证号候选,并做 1~2 位纠错。
|
||||
|
||||
text 可以是单段文本,也可以是「行文本列表」(推荐:按行抓,避免跨行串号)。
|
||||
"""
|
||||
rows = [text] if isinstance(text, str) else list(text)
|
||||
seen: Dict[str, IdCandidate] = {}
|
||||
|
||||
def add(no: str, origin: str, edits: int) -> None:
|
||||
no = no.upper()
|
||||
if len(no) != 18:
|
||||
return
|
||||
c = seen.get(no)
|
||||
ok = id_checksum_ok(no)
|
||||
if c is None or (ok and not c.checksum_ok):
|
||||
seen[no] = IdCandidate(no, ok, origin, edits, score=0.0)
|
||||
|
||||
for row in rows:
|
||||
s = normalize_text(row)
|
||||
# 原始文本里的 18 位窗口(允许 X 结尾、允许混入易混字母)
|
||||
for raw in re.findall(r"[0-9OoIlLZzSBbGgqAaEeTtCc|!]{17}[0-9XxOoIl]", s):
|
||||
d, amb = digitize(raw)
|
||||
if len(d) == 18:
|
||||
add(d, "raw", 0)
|
||||
if len(amb) <= 4 and not id_checksum_ok(d):
|
||||
for combo in _enumerate_ambiguous(d, amb, limit=200):
|
||||
add(combo, "repaired", sum(1 for x, y in zip(d, combo) if x != y))
|
||||
# 纯数字窗口(含标签粘连)
|
||||
for m in re.finditer(r"\d{17}[\dXx]", s):
|
||||
add(m.group(0), "raw", 0)
|
||||
if not id_checksum_ok(m.group(0)):
|
||||
for combo in _one_digit_sub(m.group(0), limit=200):
|
||||
add(combo, "repaired", 1)
|
||||
|
||||
for c in seen.values():
|
||||
c.score = (3.0 if c.checksum_ok else 0.0) + (2.0 if id_plausible(c.number) else 0.0) \
|
||||
- 0.5 * c.edits
|
||||
return sorted(seen.values(), key=lambda x: -x.score)[:limit]
|
||||
|
||||
|
||||
def _enumerate_ambiguous(digits: str, positions: Sequence[int],
|
||||
limit: int = 200) -> List[str]:
|
||||
"""在歧义位置枚举替代数字。"""
|
||||
out = [digits]
|
||||
for pos in positions:
|
||||
ch = digits[pos]
|
||||
alts = [x for x in _CONFUSABLE.get(ch, ()) if x.isdigit()]
|
||||
if len(alts) <= 1:
|
||||
continue
|
||||
new = []
|
||||
for base in out:
|
||||
for a in alts:
|
||||
new.append(base[:pos] + a + base[pos + 1:])
|
||||
out = new[:limit]
|
||||
return out
|
||||
|
||||
|
||||
def _one_digit_sub(no: str, limit: int = 200) -> List[str]:
|
||||
out = []
|
||||
for i in range(len(no)):
|
||||
cur = no[i]
|
||||
for d in "0123456789":
|
||||
if d == cur:
|
||||
continue
|
||||
cand = no[:i] + d + no[i + 1:]
|
||||
if id_checksum_ok(cand) and id_plausible(cand):
|
||||
out.append(cand)
|
||||
if len(out) >= limit:
|
||||
return out
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 银行卡
|
||||
def luhn_ok(no: str) -> bool:
|
||||
if not no or not no.isdigit() or not (13 <= len(no) <= 19):
|
||||
return False
|
||||
total, alt = 0, False
|
||||
for ch in reversed(no):
|
||||
d = int(ch)
|
||||
if alt:
|
||||
d *= 2
|
||||
if d > 9:
|
||||
d -= 9
|
||||
total += d
|
||||
alt = not alt
|
||||
return total % 10 == 0
|
||||
|
||||
|
||||
def luhn_check_digit(prefix: str) -> str:
|
||||
"""给前 n-1 位算 Luhn 校验位。"""
|
||||
total, alt = 0, True
|
||||
for ch in reversed(prefix):
|
||||
d = int(ch)
|
||||
if alt:
|
||||
d *= 2
|
||||
if d > 9:
|
||||
d -= 9
|
||||
total += d
|
||||
alt = not alt
|
||||
return str((10 - total % 10) % 10)
|
||||
|
||||
|
||||
@dataclass
|
||||
class CardCandidate:
|
||||
number: str
|
||||
digits: int
|
||||
luhn_ok: bool
|
||||
prefix: str = ""
|
||||
bank: str = ""
|
||||
origin: str = "raw" # raw / consensus / repaired
|
||||
edits: int = 0
|
||||
votes: int = 1
|
||||
score: float = 0.0
|
||||
|
||||
|
||||
# 常见储蓄卡 BIN(6 位)→ 银行;只收录能确认的,其余留给卡面文字判断。
|
||||
# 与插件 XQ0005「银行卡检查」的已核验工资卡 BIN 对齐(重庆农商/三峡等本地卡种),
|
||||
# 同一 BIN 只能对应一家银行,勿重复登记(Python dict 重复键会静默覆盖)。
|
||||
BIN_BANK: Dict[str, str] = {
|
||||
# 工商银行
|
||||
"622200": "中国工商银行", "622202": "中国工商银行", "622203": "中国工商银行",
|
||||
"622208": "中国工商银行", "621225": "中国工商银行", "621226": "中国工商银行",
|
||||
"955880": "中国工商银行", "955882": "中国工商银行",
|
||||
# 农业银行
|
||||
"621336": "中国农业银行", "622841": "中国农业银行", "622845": "中国农业银行",
|
||||
"622846": "中国农业银行", "622848": "中国农业银行", "622849": "中国农业银行",
|
||||
# 建设银行
|
||||
"621081": "中国建设银行", "621499": "中国建设银行", "621700": "中国建设银行",
|
||||
"622280": "中国建设银行", "622700": "中国建设银行", "436742": "中国建设银行",
|
||||
# 中国银行
|
||||
"456351": "中国银行", "601382": "中国银行", "621660": "中国银行",
|
||||
"621661": "中国银行", "621662": "中国银行", "621663": "中国银行",
|
||||
"621665": "中国银行", "621785": "中国银行", "621786": "中国银行",
|
||||
"621787": "中国银行", "621788": "中国银行", "621789": "中国银行",
|
||||
# 招商银行
|
||||
"621286": "招商银行", "621483": "招商银行", "621485": "招商银行",
|
||||
"621486": "招商银行", "622575": "招商银行", "622576": "招商银行",
|
||||
"622577": "招商银行", "622578": "招商银行", "622579": "招商银行",
|
||||
"622588": "招商银行", "622609": "招商银行",
|
||||
# 民生银行
|
||||
"421393": "中国民生银行", "621691": "中国民生银行", "622600": "中国民生银行",
|
||||
"622601": "中国民生银行", "622602": "中国民生银行", "622603": "中国民生银行",
|
||||
"622615": "中国民生银行", "622617": "中国民生银行", "622619": "中国民生银行",
|
||||
"622620": "中国民生银行", "622621": "中国民生银行", "622622": "中国民生银行",
|
||||
"622623": "中国民生银行",
|
||||
# 兴业银行
|
||||
"621084": "兴业银行", "622908": "兴业银行", "622909": "兴业银行",
|
||||
# 浦发银行
|
||||
"621792": "浦发银行", "621793": "浦发银行", "622516": "浦发银行",
|
||||
"622517": "浦发银行", "622518": "浦发银行", "622521": "浦发银行",
|
||||
"622522": "浦发银行", "622523": "浦发银行", "622525": "浦发银行",
|
||||
"622526": "浦发银行",
|
||||
# 交通银行
|
||||
"622250": "交通银行", "622251": "交通银行", "622252": "交通银行",
|
||||
"622253": "交通银行", "622254": "交通银行", "622255": "交通银行",
|
||||
"622260": "交通银行", "622262": "交通银行",
|
||||
# 邮储银行
|
||||
"620062": "中国邮政储蓄银行", "621095": "中国邮政储蓄银行",
|
||||
"622188": "中国邮政储蓄银行", "622199": "中国邮政储蓄银行",
|
||||
"955100": "中国邮政储蓄银行",
|
||||
# 中信 / 光大 / 华夏 / 广发 / 平安
|
||||
"622690": "中信银行", "622691": "中信银行", "622692": "中信银行",
|
||||
"622660": "中国光大银行", "622661": "中国光大银行", "622662": "中国光大银行",
|
||||
"622630": "华夏银行", "622631": "华夏银行", "622632": "华夏银行",
|
||||
"623020": "华夏银行",
|
||||
"622568": "广发银行",
|
||||
"622155": "平安银行", "622156": "平安银行", "622157": "平安银行",
|
||||
# 重庆本地(工资卡主力卡种,XQ0005 实际数据核验)
|
||||
"621258": "重庆农村商业银行", "621465": "重庆农村商业银行",
|
||||
"621528": "重庆农村商业银行", "622867": "重庆农村商业银行",
|
||||
"621755": "重庆三峡银行",
|
||||
}
|
||||
|
||||
|
||||
def bin_bank(no: str) -> str:
|
||||
return BIN_BANK.get(no[:6], "") if len(no) >= 6 else ""
|
||||
|
||||
|
||||
def prefix_ok(no: str) -> bool:
|
||||
"""前缀是否像一张国内借记卡:62 开头,或命中已知 BIN(含 4/6/9 开头的老卡)。"""
|
||||
return bool(bin_bank(no)) or no.startswith("62")
|
||||
|
||||
|
||||
def _id_like(no: str) -> bool:
|
||||
"""18 位且通过身份证校验码、又不是 62 开头 → 基本可判定是身份证号,不是卡号。"""
|
||||
return len(no) == 18 and id_checksum_ok(no) and not no.startswith("62")
|
||||
|
||||
|
||||
def card_candidates(text: Union[str, Sequence[str]], want_lengths: Sequence[int] = (16, 19, 18),
|
||||
limit: int = 8, exclude: Sequence[str] = ()) -> List[CardCandidate]:
|
||||
"""从 OCR 文本里找卡号候选:游程 + 歧义枚举 + Luhn 校验。
|
||||
|
||||
Args:
|
||||
text: 单段文本或「行文本列表」(推荐按行传,避免跨行把两行数字连起来)。
|
||||
exclude: 已知的身份证号等「长得像卡号」的号码,直接排除。
|
||||
"""
|
||||
excludes = {normalize_text(x).upper() for x in exclude if x}
|
||||
rows = [text] if isinstance(text, str) else list(text)
|
||||
runs: List[str] = []
|
||||
for row in rows:
|
||||
norm = normalize_text(row)
|
||||
cur: List[str] = []
|
||||
for ch in norm:
|
||||
if ch.isdigit():
|
||||
cur.append(ch)
|
||||
elif ch in _CONFUSABLE:
|
||||
cur.append(PRIMARY[ch])
|
||||
else:
|
||||
if len(cur) >= 13:
|
||||
runs.append("".join(cur))
|
||||
cur = []
|
||||
if len(cur) >= 13:
|
||||
runs.append("".join(cur))
|
||||
|
||||
seen: Dict[str, CardCandidate] = {}
|
||||
|
||||
def add(no: str, origin: str, edits: int, votes: int = 1) -> None:
|
||||
if no in excludes or _id_like(no) or not prefix_ok(no):
|
||||
return
|
||||
ok = luhn_ok(no)
|
||||
if not ok and origin == "raw":
|
||||
return
|
||||
c = seen.get(no)
|
||||
if c is None:
|
||||
seen[no] = CardCandidate(number=no, digits=len(no), luhn_ok=ok,
|
||||
prefix=no[:6], bank=bin_bank(no),
|
||||
origin=origin, edits=edits, votes=votes)
|
||||
else:
|
||||
c.votes += votes
|
||||
c.luhn_ok = c.luhn_ok or ok
|
||||
|
||||
for run in runs:
|
||||
if run in excludes or _id_like(run) or not prefix_ok(run):
|
||||
continue
|
||||
add(run, "raw", 0)
|
||||
if luhn_ok(run):
|
||||
continue
|
||||
# 歧义位置枚举;只有唯一解才敢认定(多个解 = 不知道错在哪,宁可标人工)
|
||||
if 13 <= len(run) <= 19:
|
||||
solutions = _luhn_repair(run, max_edits=1)
|
||||
for s in solutions:
|
||||
add(s, "repaired", 1)
|
||||
# 多遍 OCR 的「共识」由上层合并;这里只保证数量
|
||||
cands = [c for c in seen.values() if c.luhn_ok]
|
||||
for c in cands:
|
||||
c.score = (4.0 if c.luhn_ok else 0.0) \
|
||||
+ (2.0 if c.digits in want_lengths else 0.0) \
|
||||
+ (1.0 if c.bank else 0.0) \
|
||||
+ 0.5 * min(c.votes, 4) - 0.5 * c.edits
|
||||
return sorted(cands, key=lambda x: -x.score)[:limit]
|
||||
|
||||
|
||||
def _luhn_repair(no: str, max_edits: int = 1) -> List[str]:
|
||||
"""返回「能通过 Luhn 的最少改动解」;多于一个解视为歧义,返回空。
|
||||
|
||||
卡号错一位时,Luhn 往往还能匹配出 5~9 种改法。若无其它证据(例如另一处
|
||||
小字印的同一卡号、卡面 BIN),宁可不认,避免把身份证号「纠」成合法卡号。
|
||||
"""
|
||||
if luhn_ok(no):
|
||||
return [no]
|
||||
found: List[str] = []
|
||||
if max_edits >= 1:
|
||||
for i in range(len(no)):
|
||||
for d in "0123456789":
|
||||
if d == no[i]:
|
||||
continue
|
||||
cand = no[:i] + d + no[i + 1:]
|
||||
if luhn_ok(cand):
|
||||
found.append(cand)
|
||||
if len(found) > 1:
|
||||
return []
|
||||
if max_edits >= 2 and not found:
|
||||
for i in range(len(no)):
|
||||
for j in range(i + 1, len(no)):
|
||||
for d1 in "0123456789":
|
||||
for d2 in "0123456789":
|
||||
cand = no[:i] + d1 + no[i + 1:j] + d2 + no[j + 1:]
|
||||
if luhn_ok(cand):
|
||||
found.append(cand)
|
||||
if len(found) > 1:
|
||||
return []
|
||||
return found
|
||||
|
||||
|
||||
def consensus(numbers: Iterable[str]) -> List[str]:
|
||||
"""多数投票:同长度、逐位取众数(用于多遍 OCR 结果合并)。"""
|
||||
groups: Dict[int, List[str]] = {}
|
||||
for n in numbers:
|
||||
if n.isdigit():
|
||||
groups.setdefault(len(n), []).append(n)
|
||||
out = []
|
||||
for length, items in groups.items():
|
||||
if not items:
|
||||
continue
|
||||
votes = []
|
||||
for i in range(length):
|
||||
counts: Dict[str, int] = {}
|
||||
for it in items:
|
||||
counts[it[i]] = counts.get(it[i], 0) + 1
|
||||
votes.append(max(counts.items(), key=lambda kv: kv[1])[0])
|
||||
cand = "".join(votes)
|
||||
score = sum(1 for it in items if it == cand)
|
||||
if score >= max(2, len(items) // 2 + 1):
|
||||
out.append(cand)
|
||||
return out
|
||||
@@ -72,6 +72,18 @@ class TextItem:
|
||||
|
||||
|
||||
# ==================== 引擎 ====================
|
||||
def _silence_rapidocr() -> None:
|
||||
"""把 RapidOCR 自带的控制台日志压到 ERROR。
|
||||
|
||||
RapidOCR 在 import 时给 "RapidOCR" logger 挂了 stderr handler,识别不到文字等
|
||||
WARNING 会直接写 stderr,被执行机当成 ERROR 刷进运行日志(`[ERROR] [WARNING] ...`)。
|
||||
这里只压掉 WARNING 及以下的噪音,ERROR 仍然保留。
|
||||
"""
|
||||
lg = logging.getLogger("RapidOCR")
|
||||
lg.setLevel(logging.ERROR)
|
||||
lg.propagate = False
|
||||
|
||||
|
||||
def _get_engine():
|
||||
"""懒加载 RapidOCR 单例(模型随包,离线可用)。"""
|
||||
global _ENGINE
|
||||
@@ -88,10 +100,10 @@ def _get_engine():
|
||||
"(模型随包内置,无需联网下载;识别失败时可删除 rapidocr/models 重新解压)"
|
||||
) from e
|
||||
try:
|
||||
_ENGINE = RapidOCR(params={"Global.log_level": "WARNING"})
|
||||
_ENGINE = RapidOCR(params={"Global.log_level": "ERROR"})
|
||||
except Exception: # noqa: BLE001 老版本不支持 params
|
||||
_ENGINE = RapidOCR()
|
||||
logging.getLogger("RapidOCR").setLevel(logging.WARNING)
|
||||
_silence_rapidocr()
|
||||
logger.debug("RapidOCR 引擎已初始化")
|
||||
return _ENGINE
|
||||
|
||||
|
||||
@@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "desktopauto"
|
||||
version = "0.4.0"
|
||||
description = "桌面自动化库:识图点击、图像存在判断、OCR 文字坐标、键鼠输入、窗口与进程管理(面向拿不到元素树的桌面程序)"
|
||||
version = "0.5.3"
|
||||
description = "桌面自动化库:识图点击、图像存在判断、OCR 文字坐标、身份证/银行卡照片识别、键鼠输入、窗口与进程管理"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.9"
|
||||
dependencies = [
|
||||
@@ -20,9 +20,18 @@ ocr = [
|
||||
"rapidocr>=3.0",
|
||||
"onnxruntime>=1.16",
|
||||
]
|
||||
# 证件照识别:依赖 OCR + openpyxl(导出核对工作簿)
|
||||
card = [
|
||||
"rapidocr>=3.0",
|
||||
"onnxruntime>=1.16",
|
||||
"openpyxl>=3.1",
|
||||
]
|
||||
report = [
|
||||
"openpyxl>=3.1",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Repository = "https://github.com/37du/37duAutomation"
|
||||
|
||||
[tool.setuptools]
|
||||
packages = ["desktopauto"]
|
||||
packages = ["desktopauto", "desktopauto.cardocr"]
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
"schema_version": 1,
|
||||
"id": "desktopauto",
|
||||
"name": "桌面自动化 SDK",
|
||||
"version": "0.4.0",
|
||||
"description": "屏幕识图点击、图像存在判断、OCR 文字坐标、键鼠输入、窗口与进程管理(面向拿不到元素树的桌面程序)",
|
||||
"version": "0.5.3",
|
||||
"description": "屏幕识图点击、图像存在判断、OCR 文字坐标、身份证/银行卡照片识别(号码纠错/命中分析)、键鼠输入、窗口与进程管理(面向拿不到元素树的桌面程序)",
|
||||
"provides": [
|
||||
"desktopauto"
|
||||
],
|
||||
|
||||
+30
-1
@@ -22,6 +22,7 @@
|
||||
| 群聊推送(文本/文件、标题、@所有人、@成员) | `dws.Dws`、`dws.push` | 同上 |
|
||||
| 防封控限流 + 推送记录 CSV | `Dws(rate_limit=...)`、`Dws(record_dir=...)` | 同上 |
|
||||
| AI 表格读写(sheet/字段/分页读/批量增改、值归一与类型转换) | `aitable.AiTable` | `libs/aitable/aitable/client.py` |
|
||||
| AI 表格附件下载(图片/文件字段、预签名过期检测、重试/命名/魔数校验) | `aitable.AiTable.download_attachments`、`aitable.attachment_items` | 新增(`libs/aitable` 1.1.0 同步实现) |
|
||||
| 月报/周报数据采集(Git + 需求表) | `report.collect`、`python -m dingtalk_sdk.report` | `libs/aitable/aitable/report.py` |
|
||||
|
||||
不在范围内:`workflows/share/dingtalk_sender.py`(已废弃的 OCR + 模拟点击单聊推送,
|
||||
@@ -96,6 +97,32 @@ with AiTable() as table: # 操作人取配置 AITABLE_OPERATOR_UN
|
||||
`base` 参数支持别名(`workplan` / `hr`)、baseId、alidocs 链接三种写法,方法内部自动转换
|
||||
(旧 `libs/aitable` 需要先调 `resolve_base`,SDK 里可省略)。
|
||||
|
||||
附件(图片/文件)字段的下载:
|
||||
|
||||
```python
|
||||
from dingtalk_sdk import AiTable, attachment_items
|
||||
|
||||
with AiTable() as table:
|
||||
rows = table.records("hr", "uavChPe") # 银行卡-变更收集表
|
||||
for record in rows:
|
||||
fields = record.get("fields") or {}
|
||||
photos = attachment_items(fields.get("银行卡卡号面照片")) # 元数据(含预签名 url)
|
||||
for res in table.download_attachments(fields.get("银行卡卡号面照片"),
|
||||
rf"D:\资料\银行卡照片\{fields.get('持卡人姓名', '')}",
|
||||
prefix="银行卡-"):
|
||||
print(res["ok"], res["path"], res["kind"], res["size_match"])
|
||||
```
|
||||
|
||||
要点:
|
||||
|
||||
- `attachment` 字段的 `url` 是阿里云 OSS **预签名地址**(免 token 直连,约 **2 小时过期**):
|
||||
拉完记录要立刻下载,过期只能重拉记录换新地址(抛 `AttachmentExpiredError`,重试同一地址无用);
|
||||
- `download_attachment()` 单文件失败抛异常;`download_attachments()` 批量时单文件失败**不中断**,
|
||||
结果里 `ok=False` + `error` + `expired`;
|
||||
- 落盘文件名为 `prefix + 原文件名`,同名自动加 `-2`,非法字符换 `_`,限长 120;
|
||||
- `kind` 按文件头魔数判断真实类型、`size_match` 与表格声明大小比对,防止把错误页/半截文件当图片;
|
||||
- `resourceUrl` 是相对路径,不能直连(`attachment_items` 会丢掉它)。
|
||||
|
||||
### 5. 月报 / 周报
|
||||
|
||||
```python
|
||||
@@ -135,6 +162,7 @@ dws 可执行文件解析顺序:`Dws(bin=...)` > `DINGTALK_DWS_BIN` > `~/.loca
|
||||
| 项 | 旧实现 | SDK |
|
||||
|---|---|---|
|
||||
| 错误 | `SystemExit` / 返回 dict 混用 | 统一异常(`ConfigError`/`ApiError`/`NetworkError`/`DwsError`);兼容入口 `robot.push` / `dws.push` 仍返回 dict |
|
||||
| 附件下载 | 无(只有 `attachment` 元数据) | `download_attachment(s)`;预签名过期抛 `AttachmentExpiredError`,批量失败项不中断 |
|
||||
| 输出 | 直接 `print` | 通过 `log=` 回调(默认静默),不污染插件日志 |
|
||||
| 环境定位 | 按 `__file__` 推仓库根 | 按 cwd 向上 + 环境变量 |
|
||||
| 影刀全局变量 | 写 `glv['push_record_path']` | 仍 best-effort 写;同时 `push()` 返回 `record_path` |
|
||||
@@ -173,7 +201,7 @@ cd libs\dingtalk; ..\..\.venv\Scripts\python.exe -m dingtalk_sdk._selftest; cd .
|
||||
# 直发正式(SDK 无独立入口、无法单测,不走测试通道;要小范围看就发消费插件的测试版)
|
||||
.venv\Scripts\python.exe tools\agent_cli.py --admin puddy --password 123456 `
|
||||
--base http://172.30.30.243:8800 `
|
||||
sdk-publish dist-sdk\dingtalk_sdk_v0.1.2.zip --baseline-sdk <上一版 zip> --prod
|
||||
sdk-publish dist-sdk\dingtalk_sdk_v0.1.3.zip --baseline-sdk <上一版 zip> --prod
|
||||
```
|
||||
|
||||
完整发版 SOP 见技能 `.skills/37du-SDK-Deploy/SKILL.md`;`^0.x` 是标准 caret 语义,
|
||||
@@ -190,3 +218,4 @@ cd libs\dingtalk; ..\..\.venv\Scripts\python.exe -m dingtalk_sdk._selftest; cd .
|
||||
5. **AI 表格必须带 `operatorId`**:操作人须是目标表协作者,个人空间文档默认不对应用开放。
|
||||
6. **日期是毫秒时间戳 + 北京时间**:`norm` / `to_ms` 已处理,自己拼时间戳容易整体差一天。
|
||||
7. **dws 限流**:默认 50 条/分钟,批量推送会阻塞等待(不丢消息),长批次请预留时间。
|
||||
8. **表格附件 url 约 2 小时过期**:`attachment` 字段里的 `url` 是预签名地址,必须“拉记录 → 立刻下载”,不能存 url 隔夜用;翻页拉 5000 条再回头下载前面的是常见翻车点。
|
||||
|
||||
+43
-4
@@ -1,13 +1,14 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"sdk_id": "dingtalk_sdk",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.3",
|
||||
"modules": {
|
||||
"dingtalk_sdk": {
|
||||
"exports": [
|
||||
"AccessToken",
|
||||
"AiTable",
|
||||
"ApiError",
|
||||
"AttachmentExpiredError",
|
||||
"AuthError",
|
||||
"CancelledError",
|
||||
"ConfigError",
|
||||
@@ -20,6 +21,7 @@
|
||||
"RobotAccount",
|
||||
"Settings",
|
||||
"aitable",
|
||||
"attachment_items",
|
||||
"auth",
|
||||
"build_sign",
|
||||
"build_url",
|
||||
@@ -38,12 +40,15 @@
|
||||
"media",
|
||||
"ms_to_str",
|
||||
"norm",
|
||||
"parse_expires",
|
||||
"parse_period",
|
||||
"push_dws",
|
||||
"push_robot",
|
||||
"report",
|
||||
"resolve_base",
|
||||
"robot",
|
||||
"safe_filename",
|
||||
"sniff_kind",
|
||||
"split_by_chars",
|
||||
"to_base_id",
|
||||
"to_ms",
|
||||
@@ -55,6 +60,7 @@
|
||||
"AccessToken",
|
||||
"AiTable",
|
||||
"ApiError",
|
||||
"AttachmentExpiredError",
|
||||
"AuthError",
|
||||
"CancelledError",
|
||||
"ConfigError",
|
||||
@@ -67,6 +73,7 @@
|
||||
"RobotAccount",
|
||||
"Settings",
|
||||
"aitable",
|
||||
"attachment_items",
|
||||
"auth",
|
||||
"build_sign",
|
||||
"build_url",
|
||||
@@ -85,12 +92,15 @@
|
||||
"media",
|
||||
"ms_to_str",
|
||||
"norm",
|
||||
"parse_expires",
|
||||
"parse_period",
|
||||
"push_dws",
|
||||
"push_robot",
|
||||
"report",
|
||||
"resolve_base",
|
||||
"robot",
|
||||
"safe_filename",
|
||||
"sniff_kind",
|
||||
"split_by_chars",
|
||||
"to_base_id",
|
||||
"to_ms",
|
||||
@@ -108,6 +118,7 @@
|
||||
"Robot": "(webhook: 'str' = '', secret: 'str' = '', server_name: 'str' = '', env: 'str' = 'prod', timeout: 'Optional[float]' = None, retries: 'Optional[int]' = None, log: 'Optional[Callable[[str], None]]' = None) -> 'None'",
|
||||
"RobotAccount": "(webhook: 'str' = '', secret: 'str' = '', server_name: 'str' = '37du 任务调度平台') -> None",
|
||||
"Settings": "(app_key: 'str' = '', app_secret: 'str' = '', operator: 'str' = '', dws_bin: 'str' = '', timeout: 'float' = 30.0, retries: 'int' = 3, rate_limit: 'int' = 50, rate_window: 'float' = 60.0, default_env: 'str' = 'prod', robots: 'Dict[str, RobotAccount]' = <factory>, base_aliases: 'Dict[str, str]' = <factory>) -> None",
|
||||
"attachment_items": "(value: 'Any') -> 'List[Dict[str, Any]]'",
|
||||
"build_sign": "(secret: 'str', timestamp_ms: 'Union[int, str]') -> 'str'",
|
||||
"build_url": "(webhook: 'str', secret: 'str' = '') -> 'str'",
|
||||
"coerce_for_fields": "(meta: 'dict', data: 'dict') -> 'dict'",
|
||||
@@ -120,10 +131,13 @@
|
||||
"markdown_image": "(media_id: 'str', alt: 'str' = '图片') -> 'str'",
|
||||
"ms_to_str": "(ms: 'Any', with_time: 'bool' = False) -> 'str'",
|
||||
"norm": "(value: 'Any') -> 'Any'",
|
||||
"parse_expires": "(url: 'str') -> 'int'",
|
||||
"parse_period": "(month: 'str' = '', week: 'Optional[str]' = None) -> 'dict'",
|
||||
"push_dws": "(messages: 'Iterable', record_dir: 'str' = '', chat_type: 'str' = '') -> 'dict'",
|
||||
"push_robot": "(text, title: 'str' = '消息通知', status: 'str' = 'info', webhook: 'str' = '', secret: 'str' = '', server_name: 'str' = '', env: 'str' = 'prod', batch: 'bool' = False, max_chars: 'int' = 15000, log: 'Optional[Callable[[str], None]]' = None) -> 'dict'",
|
||||
"resolve_base": "(raw: 'str', aliases: 'Optional[Dict[str, str]]' = None) -> 'Tuple[str, str]'",
|
||||
"safe_filename": "(name: 'Any', fallback: 'str' = 'file') -> 'str'",
|
||||
"sniff_kind": "(path: 'Any') -> 'str'",
|
||||
"split_by_chars": "(content: 'str', max_chars: 'int' = 15000) -> 'List[str]'",
|
||||
"to_base_id": "(base: 'str', aliases: 'Optional[Dict[str, str]]' = None) -> 'str'",
|
||||
"to_ms": "(value: 'Any') -> 'Optional[int]'",
|
||||
@@ -148,6 +162,7 @@
|
||||
"report",
|
||||
"robot",
|
||||
"test_aitable",
|
||||
"test_aitable_attachment",
|
||||
"test_config",
|
||||
"test_dws",
|
||||
"test_http",
|
||||
@@ -160,6 +175,7 @@
|
||||
"signatures": {
|
||||
"main": "() -> 'int'",
|
||||
"test_aitable": "() -> 'None'",
|
||||
"test_aitable_attachment": "() -> 'None'",
|
||||
"test_config": "() -> 'None'",
|
||||
"test_dws": "() -> 'None'",
|
||||
"test_http": "() -> 'None'",
|
||||
@@ -170,45 +186,66 @@
|
||||
},
|
||||
"dingtalk_sdk.aitable": {
|
||||
"exports": [
|
||||
"ATTACH_MIN_REMAIN",
|
||||
"ATTACH_TIMEOUT",
|
||||
"MAX_PAGES",
|
||||
"PAGE_SIZE",
|
||||
"TZ_CN",
|
||||
"WRITE_BATCH",
|
||||
"AiTable",
|
||||
"ApiError",
|
||||
"AttachmentExpiredError",
|
||||
"attachment_items",
|
||||
"coerce_for_fields",
|
||||
"flatten",
|
||||
"ms_to_str",
|
||||
"norm",
|
||||
"parse_expires",
|
||||
"resolve_base",
|
||||
"safe_filename",
|
||||
"sniff_kind",
|
||||
"to_base_id",
|
||||
"to_ms"
|
||||
"to_ms",
|
||||
"unique_path"
|
||||
],
|
||||
"all": [
|
||||
"ATTACH_MIN_REMAIN",
|
||||
"ATTACH_TIMEOUT",
|
||||
"MAX_PAGES",
|
||||
"PAGE_SIZE",
|
||||
"TZ_CN",
|
||||
"WRITE_BATCH",
|
||||
"AiTable",
|
||||
"ApiError",
|
||||
"AttachmentExpiredError",
|
||||
"attachment_items",
|
||||
"coerce_for_fields",
|
||||
"flatten",
|
||||
"ms_to_str",
|
||||
"norm",
|
||||
"parse_expires",
|
||||
"resolve_base",
|
||||
"safe_filename",
|
||||
"sniff_kind",
|
||||
"to_base_id",
|
||||
"to_ms"
|
||||
"to_ms",
|
||||
"unique_path"
|
||||
],
|
||||
"signatures": {
|
||||
"AiTable": "(operator: 'str' = '', app_key: 'str' = '', app_secret: 'str' = '', timeout: 'Optional[float]' = None, retries: 'Optional[int]' = None, log: 'Optional[Callable[[str], None]]' = None) -> 'None'",
|
||||
"ApiError": "(message: 'str', code: 'str' = '', errmsg: 'str' = '', payload=None)",
|
||||
"attachment_items": "(value: 'Any') -> 'List[Dict[str, Any]]'",
|
||||
"coerce_for_fields": "(meta: 'dict', data: 'dict') -> 'dict'",
|
||||
"flatten": "(record: 'dict') -> 'dict'",
|
||||
"ms_to_str": "(ms: 'Any', with_time: 'bool' = False) -> 'str'",
|
||||
"norm": "(value: 'Any') -> 'Any'",
|
||||
"parse_expires": "(url: 'str') -> 'int'",
|
||||
"resolve_base": "(raw: 'str', aliases: 'Optional[Dict[str, str]]' = None) -> 'Tuple[str, str]'",
|
||||
"safe_filename": "(name: 'Any', fallback: 'str' = 'file') -> 'str'",
|
||||
"sniff_kind": "(path: 'Any') -> 'str'",
|
||||
"to_base_id": "(base: 'str', aliases: 'Optional[Dict[str, str]]' = None) -> 'str'",
|
||||
"to_ms": "(value: 'Any') -> 'Optional[int]'"
|
||||
"to_ms": "(value: 'Any') -> 'Optional[int]'",
|
||||
"unique_path": "(dest: 'Path') -> 'Path'"
|
||||
}
|
||||
},
|
||||
"dingtalk_sdk.auth": {
|
||||
@@ -336,6 +373,7 @@
|
||||
"dingtalk_sdk.errors": {
|
||||
"exports": [
|
||||
"ApiError",
|
||||
"AttachmentExpiredError",
|
||||
"AuthError",
|
||||
"CancelledError",
|
||||
"ConfigError",
|
||||
@@ -345,6 +383,7 @@
|
||||
],
|
||||
"all": [
|
||||
"ApiError",
|
||||
"AttachmentExpiredError",
|
||||
"AuthError",
|
||||
"CancelledError",
|
||||
"ConfigError",
|
||||
|
||||
@@ -33,16 +33,17 @@ AI 表格(notable)读写 :class:`aitable.AiTable` 与值归一工具
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
__version__ = "0.1.2"
|
||||
__version__ = "0.1.3"
|
||||
|
||||
from . import aitable, auth, config, dws, errors, http, media, robot
|
||||
from .aitable import (AiTable, coerce_for_fields, flatten, ms_to_str, norm, resolve_base,
|
||||
from .aitable import (AiTable, attachment_items, coerce_for_fields, flatten, ms_to_str,
|
||||
norm, parse_expires, resolve_base, safe_filename, sniff_kind,
|
||||
to_base_id, to_ms)
|
||||
from .auth import AccessToken, invalidate as invalidate_token, token
|
||||
from .config import RobotAccount, Settings, get_settings, load_env_files
|
||||
from .dws import Dws, push as push_dws
|
||||
from .errors import (ApiError, AuthError, CancelledError, ConfigError, DingTalkError,
|
||||
DwsError, NetworkError)
|
||||
from .errors import (ApiError, AttachmentExpiredError, AuthError, CancelledError,
|
||||
ConfigError, DingTalkError, DwsError, NetworkError)
|
||||
from .media import markdown_image, upload_media
|
||||
from .robot import (DingTalkRobot, Robot, build_sign, build_url, compose_batch_messages,
|
||||
push as push_robot, split_by_chars)
|
||||
@@ -64,6 +65,7 @@ __all__ = [
|
||||
"AccessToken",
|
||||
"AiTable",
|
||||
"ApiError",
|
||||
"AttachmentExpiredError",
|
||||
"AuthError",
|
||||
"CancelledError",
|
||||
"ConfigError",
|
||||
@@ -76,6 +78,7 @@ __all__ = [
|
||||
"RobotAccount",
|
||||
"Settings",
|
||||
"aitable",
|
||||
"attachment_items",
|
||||
"auth",
|
||||
"build_sign",
|
||||
"build_url",
|
||||
@@ -94,12 +97,15 @@ __all__ = [
|
||||
"media",
|
||||
"ms_to_str",
|
||||
"norm",
|
||||
"parse_expires",
|
||||
"parse_period",
|
||||
"push_dws",
|
||||
"push_robot",
|
||||
"report",
|
||||
"resolve_base",
|
||||
"robot",
|
||||
"safe_filename",
|
||||
"sniff_kind",
|
||||
"split_by_chars",
|
||||
"to_base_id",
|
||||
"to_ms",
|
||||
|
||||
@@ -225,6 +225,97 @@ def test_aitable() -> None:
|
||||
"baseId 幂等")
|
||||
|
||||
|
||||
# ==================== AI 表格:附件下载 ====================
|
||||
|
||||
def test_aitable_attachment() -> None:
|
||||
import socketserver
|
||||
import http.server as httpserver
|
||||
import tempfile
|
||||
import threading
|
||||
|
||||
value = [{"resourceId": "r1", "filename": "卡号面.jpg", "size": 12, "type": "image",
|
||||
"url": "https://x.oss-cn/y.jpg?Expires=1794886717&Signature=abc"},
|
||||
{"resourceId": "r2", "filename": "身份证.png", "size": 8, "type": "image",
|
||||
"resourceUrl": "/core/api/resources/img/zz"}]
|
||||
items = aitable.attachment_items(value)
|
||||
_eq(len(items), 2, "attachment 字段值拆出 2 个附件")
|
||||
_eq(items[0]["size"], 12, "声明大小保留")
|
||||
_eq(items[1]["url"], "", "相对 resourceUrl 不当作可直连地址")
|
||||
_eq(aitable.attachment_items(None), [], "空附件返回空列表")
|
||||
_eq(aitable.attachment_items({"filename": "x"})[0]["url"], "", "单个 dict 兼容")
|
||||
_eq(aitable.parse_expires(items[0]["url"]), 1794886717, "解析预签名 Expires")
|
||||
_eq(aitable.parse_expires("https://x/y.jpg"), 0, "无 Expires 返回 0")
|
||||
|
||||
_eq(aitable.safe_filename('a/b:c*?"<>|.jpg'), "a_b_c_.jpg", "非法字符换下划线")
|
||||
_eq(aitable.safe_filename("", ""), "file", "空名兜底")
|
||||
_eq(len(aitable.safe_filename("x" * 200)), 120, "文件名限长 120")
|
||||
|
||||
# 本地 HTTP 服务模拟 OSS;不联网、不读生产凭证
|
||||
png = b"\x89PNG\r\n\x1a\n" + b"\0" * 24
|
||||
|
||||
class _Handler(httpserver.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
if self.path.startswith("/ok"):
|
||||
self.send_response(200)
|
||||
self.send_header("content-type", "image/png")
|
||||
self.send_header("content-length", str(len(png)))
|
||||
self.end_headers()
|
||||
self.wfile.write(png)
|
||||
else:
|
||||
self.send_response(403)
|
||||
self.end_headers()
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
table = object.__new__(aitable.AiTable) # 只测下载,不初始化鉴权
|
||||
table._http = http.HttpClient(retries=2, timeout=5, log=lambda m: None)
|
||||
|
||||
with socketserver.TCPServer(("127.0.0.1", 0), _Handler) as srv:
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
base = f"http://127.0.0.1:{srv.server_address[1]}"
|
||||
try:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
res = table.download_attachment({"url": f"{base}/ok.png", "size": len(png)},
|
||||
os.path.join(tmp, "a.png"))
|
||||
_ok(res["ok"] and res["kind"] == "png" and res["size_match"] is True,
|
||||
"下载成功 + 魔数/声明大小校验")
|
||||
|
||||
dup = table.download_attachment({"url": f"{base}/ok.png"},
|
||||
os.path.join(tmp, "a.png"))
|
||||
_eq(os.path.basename(dup["path"]), "a-2.png", "同名附件不覆盖")
|
||||
|
||||
_raises(aitable.AttachmentExpiredError,
|
||||
lambda: table.download_attachment({"url": f"{base}/deny.png"},
|
||||
os.path.join(tmp, "b.png")),
|
||||
"403 抛 AttachmentExpiredError")
|
||||
_raises(aitable.AttachmentExpiredError,
|
||||
lambda: table.download_attachment(
|
||||
{"url": f"{base}/ok.png?Expires=1000"},
|
||||
os.path.join(tmp, "c.png")),
|
||||
"Expires 已过期 → 不发请求直接报过期")
|
||||
_raises(config.ConfigError,
|
||||
lambda: table.download_attachment({"resourceUrl": "/x"},
|
||||
os.path.join(tmp, "d.png")),
|
||||
"无可直连 url 抛 ConfigError")
|
||||
|
||||
# 批量:单文件失败不中断,过期项打 expired,prefix 命名生效
|
||||
batch = table.download_attachments(
|
||||
[{"url": f"{base}/ok.png", "filename": "卡号面.jpg", "size": len(png)},
|
||||
{"url": f"{base}/deny.png", "filename": "身份证.png"}],
|
||||
os.path.join(tmp, "sub"), prefix="银行卡-", col="银行卡卡号面照片")
|
||||
_eq(len(batch), 2, "批量下载 2 个附件")
|
||||
_ok(batch[0]["ok"] and os.path.basename(batch[0]["path"]) == "银行卡-卡号面.jpg",
|
||||
"批量成功项落盘且带 prefix")
|
||||
_ok(batch[1]["ok"] is False and batch[1]["expired"] is True
|
||||
and "403" in batch[1]["error"], "批量失败项标 expired 并带原因")
|
||||
_eq(batch[1]["col"], "银行卡卡号面照片", "结果带字段名")
|
||||
_eq(batch[0]["index"], 1, "结果带序号")
|
||||
finally:
|
||||
srv.shutdown()
|
||||
srv.server_close()
|
||||
|
||||
|
||||
# ==================== 媒体 ====================
|
||||
|
||||
def test_media() -> None:
|
||||
@@ -264,6 +355,7 @@ def main() -> int:
|
||||
("http", test_http),
|
||||
("dws", test_dws),
|
||||
("aitable", test_aitable),
|
||||
("aitable_attachment", test_aitable_attachment),
|
||||
("media", test_media),
|
||||
("report", test_report),
|
||||
]
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""钉钉 AI 表格(notable)读写。
|
||||
|
||||
能力(与原 ``libs/aitable`` 一致):
|
||||
能力(在原 ``libs/aitable`` 一致基础上补齐附件下载):
|
||||
- 列 sheet / 字段定义;按 ``hasMore`` + ``nextToken`` 分页读全量记录;
|
||||
- 批量新增 / 更新记录(自动按 20 条一批);
|
||||
- 值归一(``norm``)、日期毫秒互转(``ms_to_str`` / ``to_ms``)、
|
||||
按字段类型转换写入值(``coerce_for_fields``)、记录拍平(``flatten``);
|
||||
- 附件(图片/文件)字段解析与下载:``attachment_items`` + ``AiTable.download_attachments``
|
||||
(``attachment`` 字段里带阿里云 OSS 预签名 url,免 token 直连、约 2 小时过期);
|
||||
- base 支持别名 / baseId / alidocs 链接三种写法(``resolve_base``)。
|
||||
|
||||
与旧实现的差异(SDK 契约要求):
|
||||
- 失败抛 ``ConfigError`` / ``ApiError`` / ``NetworkError``,**不再 SystemExit**;
|
||||
- 预签名附件地址过期抛 ``AttachmentExpiredError``(``ConfigError`` 子类),
|
||||
批量下载时单文件失败不中断,结果里 ``ok=False`` 并带原因;
|
||||
- 凭证与操作人可显式传入,缺省读配置(见 :mod:`dingtalk_sdk.config`)。
|
||||
"""
|
||||
|
||||
@@ -17,12 +21,17 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
import urllib.parse as urllib_parse
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Dict, List, Optional, Tuple
|
||||
|
||||
import requests
|
||||
|
||||
from .auth import KIND_V1, AccessToken
|
||||
from .config import BASE_ALIASES, get_settings
|
||||
from .errors import ApiError, ConfigError
|
||||
from .errors import ApiError, AttachmentExpiredError, ConfigError, NetworkError
|
||||
from .http import API_BASE, HttpClient, install_dns_fallback
|
||||
|
||||
TZ_CN = timezone(timedelta(hours=8)) # 表格日期按北京时间落库(毫秒时间戳)
|
||||
@@ -32,6 +41,12 @@ WRITE_BATCH = 20 # 批量写单次上限
|
||||
MAX_PAGES = 500 # 500 × 100 = 5 万条上限
|
||||
_TS_FLOOR = 1_000_000_000_000 # 毫秒时间戳判定下限
|
||||
|
||||
ATTACH_MIN_REMAIN = 60 # 预签名 url 剩余有效期低于该秒数即视为不可用
|
||||
ATTACH_TIMEOUT = 30.0 # 附件下载单次超时(秒)
|
||||
_BAD_NAME = re.compile(r'[\\/:*?"<>|\r\n\t]+')
|
||||
_MAGIC = ((b"\xff\xd8\xff", "jpg"), (b"\x89PNG\r\n\x1a\n", "png"),
|
||||
(b"GIF87a", "gif"), (b"GIF89a", "gif"), (b"BM", "bmp"), (b"%PDF", "pdf"))
|
||||
|
||||
|
||||
# ==================== 值归一 / 类型转换 ====================
|
||||
|
||||
@@ -106,6 +121,77 @@ def flatten(record: dict) -> dict:
|
||||
return row
|
||||
|
||||
|
||||
# ==================== 附件(图片 / 文件)====================
|
||||
|
||||
def attachment_items(value: Any) -> List[Dict[str, Any]]:
|
||||
"""``attachment`` 字段值 → ``[{resourceId, filename, size, type, url}]``。
|
||||
|
||||
notable 返回的附件元数据里 ``url`` 是阿里云 OSS **预签名地址**(免 token 直连、
|
||||
约 2 小时过期);``resourceUrl`` 是相对路径不能直连,故只保留绝对 url。
|
||||
"""
|
||||
if not value:
|
||||
return []
|
||||
if isinstance(value, dict):
|
||||
value = [value]
|
||||
out: List[Dict[str, Any]] = []
|
||||
for item in value:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
url = str(item.get("url") or "")
|
||||
if not url.startswith(("http://", "https://")):
|
||||
url = ""
|
||||
out.append({"resourceId": item.get("resourceId") or "",
|
||||
"filename": item.get("filename") or "",
|
||||
"size": int(item.get("size") or 0),
|
||||
"type": item.get("type") or "",
|
||||
"url": url})
|
||||
return out
|
||||
|
||||
|
||||
def parse_expires(url: str) -> int:
|
||||
"""预签名 url 的 ``Expires`` 秒级时间戳;取不到返回 0(不限时的地址)。"""
|
||||
try:
|
||||
query = urllib_parse.parse_qs(urllib_parse.urlparse(url).query)
|
||||
return int((query.get("Expires") or ["0"])[0] or 0)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
def safe_filename(name: Any, fallback: str = "file") -> str:
|
||||
"""文件名净化:Windows 非法字符换 ``_``、去首尾点空格、限长 120。"""
|
||||
text = _BAD_NAME.sub("_", str(name or "")).strip(" .")
|
||||
if not text:
|
||||
text = _BAD_NAME.sub("_", str(fallback or "file")).strip(" .") or "file"
|
||||
return text[:120]
|
||||
|
||||
|
||||
def sniff_kind(path: Any) -> str:
|
||||
"""按文件头魔数判断真实类型(避免把错误页/半截文件当图片存下来)。"""
|
||||
try:
|
||||
head = Path(path).read_bytes()[:16]
|
||||
except OSError:
|
||||
return "missing"
|
||||
if head[:4] == b"RIFF" and b"WEBP" in head[:16]:
|
||||
return "webp"
|
||||
for sig, kind in _MAGIC:
|
||||
if head.startswith(sig):
|
||||
return kind
|
||||
return "unknown"
|
||||
|
||||
|
||||
def unique_path(dest: Path) -> Path:
|
||||
"""目标已存在时追加 ``-2``、``-3``…,避免同名附件互相覆盖。"""
|
||||
dest = Path(dest)
|
||||
if not dest.exists():
|
||||
return dest
|
||||
index = 2
|
||||
while True:
|
||||
candidate = dest.with_name(f"{dest.stem}-{index}{dest.suffix}")
|
||||
if not candidate.exists():
|
||||
return candidate
|
||||
index += 1
|
||||
|
||||
|
||||
def resolve_base(raw: str, aliases: Optional[Dict[str, str]] = None) -> Tuple[str, str]:
|
||||
"""别名 / baseId / alidocs 链接 → ``(baseId, 链接里带的 sheetId 或空)``。"""
|
||||
mapping = dict(BASE_ALIASES)
|
||||
@@ -263,19 +349,124 @@ class AiTable:
|
||||
return self.update(base, sheet,
|
||||
[{"id": record_id, "fields": coerce_for_fields(meta, fields)}])
|
||||
|
||||
# ---- 附件(图片 / 文件)下载 ----
|
||||
def download_attachment(self, item: Dict[str, Any], dest: Any,
|
||||
overwrite: bool = False,
|
||||
timeout: Optional[float] = None) -> Dict[str, Any]:
|
||||
"""下载单个附件到 ``dest``,返回结果 dict(``ok`` 恒为 True)。
|
||||
|
||||
返回字段:``path`` / ``bytes`` / ``kind`` / ``content_type`` / ``size_match``
|
||||
(与表格声明大小比对)/ ``expires_in``(预签名剩余秒数)。
|
||||
|
||||
Raises:
|
||||
AttachmentExpiredError: 预签名地址已过期/即将过期,或下载被拒(403)——
|
||||
重新 ``records()`` 拉记录换新地址,重试同一地址无用
|
||||
ConfigError: 附件没有可直连 url(只有相对 ``resourceUrl``)
|
||||
ApiError: OSS 返回其它非 2xx
|
||||
NetworkError: 重试耗尽仍未下载成功
|
||||
"""
|
||||
target = Path(dest)
|
||||
item = item or {}
|
||||
url = str(item.get("url") or "")
|
||||
if not url:
|
||||
raise ConfigError("附件没有可直连的 url(只有相对 resourceUrl)")
|
||||
expires_in: Optional[int] = None
|
||||
expires = parse_expires(url)
|
||||
if expires:
|
||||
expires_in = int(expires - time.time())
|
||||
if expires_in <= ATTACH_MIN_REMAIN:
|
||||
raise AttachmentExpiredError(
|
||||
f"预签名 url 已过期/即将过期(剩 {expires_in}s),请重新拉记录换新地址")
|
||||
target = target if overwrite else unique_path(target)
|
||||
tmo = float(timeout if timeout is not None else ATTACH_TIMEOUT)
|
||||
last: Optional[BaseException] = None
|
||||
for attempt in range(1, self._http.retries + 1):
|
||||
try:
|
||||
resp = self._http.session.get(url, timeout=tmo)
|
||||
except requests.RequestException as exc: # 网络抖动
|
||||
last = NetworkError(f"附件下载失败({attempt}/{self._http.retries}):{exc}")
|
||||
else:
|
||||
if resp.status_code == 403:
|
||||
raise AttachmentExpiredError(
|
||||
"附件下载被拒(403,预签名 url 已过期或无权限),请重新拉记录")
|
||||
if resp.status_code >= 400:
|
||||
last = ApiError(f"附件下载失败:HTTP {resp.status_code}",
|
||||
code=str(resp.status_code))
|
||||
else:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(resp.content)
|
||||
declared = int(item.get("size") or 0)
|
||||
return {"ok": True, "path": str(target), "bytes": len(resp.content),
|
||||
"kind": sniff_kind(target),
|
||||
"content_type": resp.headers.get("content-type", ""),
|
||||
"size_match": (None if not declared
|
||||
else len(resp.content) == declared),
|
||||
"expires_in": expires_in}
|
||||
if attempt < self._http.retries:
|
||||
time.sleep(1.0 * attempt)
|
||||
assert last is not None
|
||||
if isinstance(last, (ApiError, NetworkError)):
|
||||
raise last
|
||||
raise NetworkError(f"附件下载失败:{last}")
|
||||
|
||||
def download_attachments(self, value: Any, save_dir: Any, prefix: str = "",
|
||||
col: str = "", overwrite: bool = False) -> List[Dict[str, Any]]:
|
||||
"""下载一个 ``attachment`` 字段的全部附件到 ``save_dir/``(``prefix + 原文件名``)。
|
||||
|
||||
单个附件失败不中断,结果里 ``ok=False`` 并带 ``error``/``expired``;成功项带
|
||||
``path``/``bytes``/``kind``/``size_match``。结果额外含 ``col``/``index``/
|
||||
``filename``/``resourceId``/``declared_size``,便于按字段归类落盘。
|
||||
|
||||
Example::
|
||||
|
||||
rows = table.records("hr", "uavChPe") # 银行卡-变更收集表
|
||||
for record in rows:
|
||||
fields = record.get("fields") or {}
|
||||
table.download_attachments(fields.get("银行卡卡号面照片"),
|
||||
rf"D:\\资料\\银行卡照片\\{fields.get('持卡人姓名','')}",
|
||||
prefix="银行卡-")
|
||||
"""
|
||||
results: List[Dict[str, Any]] = []
|
||||
for index, item in enumerate(attachment_items(value), 1):
|
||||
name = safe_filename(item["filename"],
|
||||
item["resourceId"] or f"{col or 'file'}{index}")
|
||||
target = Path(save_dir) / safe_filename(f"{prefix}{name}" if prefix else name)
|
||||
row: Dict[str, Any] = {
|
||||
"col": col or "", "index": index, "filename": item["filename"],
|
||||
"resourceId": item["resourceId"], "declared_size": item["size"],
|
||||
"ok": False, "path": "", "bytes": 0, "kind": "", "content_type": "",
|
||||
"size_match": None, "expires_in": None, "expired": False, "error": "",
|
||||
}
|
||||
try:
|
||||
row.update(self.download_attachment(item, target, overwrite=overwrite))
|
||||
except AttachmentExpiredError as exc:
|
||||
row.update(expired=True, error=str(exc))
|
||||
except (ConfigError, ApiError, NetworkError) as exc:
|
||||
row["error"] = str(exc)
|
||||
results.append(row)
|
||||
return results
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ATTACH_MIN_REMAIN",
|
||||
"ATTACH_TIMEOUT",
|
||||
"MAX_PAGES",
|
||||
"PAGE_SIZE",
|
||||
"TZ_CN",
|
||||
"WRITE_BATCH",
|
||||
"AiTable",
|
||||
"ApiError",
|
||||
"AttachmentExpiredError",
|
||||
"attachment_items",
|
||||
"coerce_for_fields",
|
||||
"flatten",
|
||||
"ms_to_str",
|
||||
"norm",
|
||||
"parse_expires",
|
||||
"resolve_base",
|
||||
"safe_filename",
|
||||
"sniff_kind",
|
||||
"to_base_id",
|
||||
"to_ms",
|
||||
"unique_path",
|
||||
]
|
||||
|
||||
@@ -18,6 +18,10 @@ class ConfigError(DingTalkError):
|
||||
"""配置缺失/非法(缺少 app key、webhook 未配置、dws 未安装等)。"""
|
||||
|
||||
|
||||
class AttachmentExpiredError(ConfigError):
|
||||
"""预签名附件地址已过期或被拒(403):需重新拉记录换新地址,重试同一地址无用。"""
|
||||
|
||||
|
||||
class NetworkError(DingTalkError):
|
||||
"""网络层失败(超时、连接中断、5xx),重试后仍失败才抛出。"""
|
||||
|
||||
@@ -56,6 +60,7 @@ class CancelledError(DingTalkError):
|
||||
|
||||
__all__ = [
|
||||
"ApiError",
|
||||
"AttachmentExpiredError",
|
||||
"AuthError",
|
||||
"CancelledError",
|
||||
"ConfigError",
|
||||
|
||||
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "dingtalk_sdk"
|
||||
version = "0.1.2"
|
||||
version = "0.1.3"
|
||||
description = "钉钉能力 SDK:群机器人推送 / 应用鉴权 / 媒体上传 / 单聊群聊推送(dws)/ AI 表格读写与月报周报采集"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.9"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "dingtalk_sdk",
|
||||
"name": "钉钉 SDK",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.3",
|
||||
"description": "钉钉能力集合:群机器人推送(加签/Markdown/状态色/分批/块格式/多环境)、企业内部应用鉴权(v1 + oapi)、媒体库上传、dws 单聊/群聊推送(文本/文件/@/限流/推送记录)、AI 表格读写与月报周报采集",
|
||||
"provides": [
|
||||
"dingtalk_sdk"
|
||||
|
||||
+22
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"sdk_id": "hr_sdk",
|
||||
"version": "0.2.3",
|
||||
"version": "0.2.4",
|
||||
"modules": {
|
||||
"hr_sdk": {
|
||||
"exports": [
|
||||
@@ -41,6 +41,7 @@
|
||||
"session_from_cookies",
|
||||
"shift",
|
||||
"wage",
|
||||
"wage_import",
|
||||
"workflow",
|
||||
"__version__"
|
||||
],
|
||||
@@ -81,6 +82,7 @@
|
||||
"session_from_cookies",
|
||||
"shift",
|
||||
"wage",
|
||||
"wage_import",
|
||||
"workflow",
|
||||
"__version__"
|
||||
],
|
||||
@@ -141,8 +143,10 @@
|
||||
"test_shift",
|
||||
"test_wage",
|
||||
"test_wage_base",
|
||||
"test_wage_import",
|
||||
"test_workflow",
|
||||
"wage",
|
||||
"wage_import",
|
||||
"workflow"
|
||||
],
|
||||
"all": [],
|
||||
@@ -166,6 +170,7 @@
|
||||
"test_shift": "() -> 'None'",
|
||||
"test_wage": "() -> 'None'",
|
||||
"test_wage_base": "() -> 'None'",
|
||||
"test_wage_import": "() -> 'None'",
|
||||
"test_workflow": "() -> 'None'"
|
||||
}
|
||||
},
|
||||
@@ -800,6 +805,22 @@
|
||||
"wage_cards": "(client, staff_id: 'str') -> 'List[dict]'"
|
||||
}
|
||||
},
|
||||
"hr_sdk.wage_import": {
|
||||
"exports": [
|
||||
"HEADERS",
|
||||
"build_xlsx",
|
||||
"import_cards"
|
||||
],
|
||||
"all": [
|
||||
"HEADERS",
|
||||
"build_xlsx",
|
||||
"import_cards"
|
||||
],
|
||||
"signatures": {
|
||||
"build_xlsx": "(rows: 'Iterable[Sequence[Any]]', headers: 'Optional[Sequence[str]]' = None) -> 'bytes'",
|
||||
"import_cards": "(rows: 'Optional[Iterable[Sequence[Any]]]' = None, *, xlsx: 'Optional[bytes]' = None, session: 'Any' = None, cookie_path: 'str' = '', fit_type: 'int' = 1, headless: 'bool' = True, timeout: 'float' = 300, log=<built-in function print>, keep_open: 'bool' = False) -> 'Dict[str, Any]'"
|
||||
}
|
||||
},
|
||||
"hr_sdk.workflow": {
|
||||
"exports": [
|
||||
"DEFAULT_PAGE_SIZE",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
分工:**SDK 出接口,插件出业务**。这里封装登录态访问、查询条件加密、异步导出、
|
||||
分页拉全、模板解析等接口事实;异常判定、店长分组、文案、列名映射、落盘策略留在插件。
|
||||
|
||||
当前版本(0.2.3)覆盖:
|
||||
当前版本(0.2.4)覆盖:
|
||||
|
||||
========================== ==========================================================
|
||||
接口 入口
|
||||
@@ -18,6 +18,7 @@
|
||||
组织机构 :mod:`org`(``rows``)
|
||||
工资待办 / 账套 / 起调薪 :mod:`wage`(``rows`` / ``accounts`` / ``account_items`` /
|
||||
``started`` / ``standards`` / ``submit_start`` / ``submit_change``)
|
||||
工资卡导入(浏览器上下文) :mod:`wage_import`(``build_xlsx`` / ``import_cards``)
|
||||
========================== ==========================================================
|
||||
|
||||
典型用法::
|
||||
@@ -34,10 +35,10 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
__version__ = "0.2.3"
|
||||
__version__ = "0.2.4"
|
||||
|
||||
from . import (attach, attendance, auth, client, config, contract, errors, export, imports,
|
||||
ledger, org, query, roster, seal, session, shift, wage, workflow)
|
||||
ledger, org, query, roster, seal, session, shift, wage, wage_import, workflow)
|
||||
from .client import HrClient
|
||||
from .config import HR_BASE_URL, WS_EXPORT_THEME, base_params, cookies_file
|
||||
from .errors import (ApiError, AuthError, CancelledError, ConfigError, ExportTimeoutError,
|
||||
@@ -82,6 +83,7 @@ __all__ = [
|
||||
"session_from_cookies",
|
||||
"shift",
|
||||
"wage",
|
||||
"wage_import",
|
||||
"workflow",
|
||||
"__version__",
|
||||
]
|
||||
|
||||
@@ -13,7 +13,7 @@ import os
|
||||
import tempfile
|
||||
from datetime import date
|
||||
|
||||
from . import attach, attendance, auth, contract, imports, seal, shift, wage, workflow
|
||||
from . import attach, attendance, auth, contract, imports, seal, shift, wage, wage_import, workflow
|
||||
from . import client as client_mod
|
||||
from . import config, errors, export, ledger, org, query, roster, session
|
||||
|
||||
@@ -566,6 +566,33 @@ def test_imports() -> None:
|
||||
"文件缺失抛 ConfigError")
|
||||
|
||||
|
||||
def test_wage_import() -> None:
|
||||
from io import BytesIO
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
row = ["胡检妹", "51052219830211222X", "胡检妹", "主卡", "51052219830211222X",
|
||||
"工资卡", "招商银行", "", "6214832790329259", "备注"]
|
||||
blob = wage_import.build_xlsx([row])
|
||||
sheet = load_workbook(BytesIO(blob)).active
|
||||
_eq([c.value for c in sheet[1]], list(wage_import.HEADERS), "模板表头固定 10 列")
|
||||
_eq(sheet.title, wage_import.SHEET_NAME, "工作表名")
|
||||
_eq(sheet.cell(row=2, column=9).value, 6214832790329259, "第 9 列卡号写数值")
|
||||
_eq(sheet.cell(row=2, column=9).data_type, "n", "卡号单元格类型为数值(否则报「卡号必须是数字」)")
|
||||
_raises(errors.ConfigError,
|
||||
lambda: wage_import.build_xlsx([row[:8] + ["6214 8327"] + row[9:]]),
|
||||
"卡号非纯数字抛 ConfigError")
|
||||
_raises(errors.ConfigError, lambda: wage_import.build_xlsx([row[:9]]),
|
||||
"列数不是 10 列抛 ConfigError")
|
||||
|
||||
class _Sess:
|
||||
cookies = {"a": "1"}
|
||||
|
||||
cookies = wage_import._cookie_list(_Sess())
|
||||
_eq(cookies[0]["name"], "a", "会话 cookies 转浏览器注入列表")
|
||||
_eq(cookies[0]["domain"], "hr.37du.co", "缺省域名 hr.37du.co")
|
||||
|
||||
|
||||
def test_auth() -> None:
|
||||
import base64 as _b64
|
||||
|
||||
@@ -621,6 +648,7 @@ def main() -> int:
|
||||
("contract", test_contract),
|
||||
("export_pipeline", test_export_pipeline),
|
||||
("imports", test_imports),
|
||||
("wage_import", test_wage_import),
|
||||
("auth", test_auth),
|
||||
]
|
||||
failed = 0
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""工资卡导入(浏览器上下文)。
|
||||
|
||||
为什么不用纯 HTTP
|
||||
----------------
|
||||
``POST {REDSEA}/uploadExtenalData/HrStaffWageCard.mc`` 只负责「接收文件 + 起异步任务」,
|
||||
永远返回 ``{"state":"1","meg":"处理成功"}``;真正的解析/落库由服务端异步任务执行,
|
||||
结果只通过 WS 主题 ``WAGE_BASE_CARD_IMPORT`` 推送。实测:同一个文件,浏览器发起
|
||||
→ 正常导入;requests/curl 发起 → 任务在「开始读取数据」阶段直接抛
|
||||
``over:{"result":"-1","msg":null}``(Cookie/请求头/报文与浏览器逐字节一致仍复现)。
|
||||
该异步任务与浏览器会话(同会话 WS 连接)强绑定,因此这里用 DrissionPage 打开
|
||||
HR 门户,在**页面内**用 ``fetch`` 上传并订阅 WS 读结果。
|
||||
|
||||
接口事实
|
||||
--------
|
||||
- 模板 10 列(固定顺序,第 1 行为表头)::
|
||||
|
||||
*姓名 / *身份证号 / *开户人姓名 / *是否主卡 / *开户人身份证号 /
|
||||
*银行卡类型 / *开卡银行 / 开户支行 / *银行卡号 / 备注
|
||||
|
||||
- **银行卡号必须是数值单元格**,写成文本会报「卡号必须是数字」。
|
||||
- ``fitType``:1=按身份证匹配,2=按工号匹配。
|
||||
- WS 末条消息以 ``over:`` 开头,正文是 JSON::
|
||||
|
||||
{"result":1,"total":1,"successNum":0,"errorNum":1,"state":"1","fileId":"...",
|
||||
"errorList":[{"line":2,"staffName":"..","idCard":"..","meg":"没有与身份证号匹配的人员"}]}
|
||||
|
||||
用法::
|
||||
|
||||
from hr_sdk import wage_import
|
||||
|
||||
rows = [["胡检妹", "51052219830211222X", "胡检妹", "主卡", "51052219830211222X",
|
||||
"工资卡", "招商银行", "", "6214832790329259", "影像核对一致"]]
|
||||
res = wage_import.import_cards(rows, session=client.session, log=print)
|
||||
if res["result"] == 1 and res["errorNum"] == 0:
|
||||
...
|
||||
|
||||
注意:导入要独占一份浏览器 profile(同一时刻只能有一个导入进程)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import time
|
||||
from io import BytesIO
|
||||
from typing import Any, Dict, Iterable, List, Optional, Sequence
|
||||
|
||||
from .config import HR_BASE_URL
|
||||
from .errors import ConfigError, ExportTimeoutError, HrError
|
||||
|
||||
#: 模板表头(固定顺序,勿改)
|
||||
HEADERS = ["*姓名", "*身份证号", "*开户人姓名", "*是否主卡", "*开户人身份证号",
|
||||
"银行卡类型", "*开卡银行", "开户支行", "*银行卡号", "备注"]
|
||||
|
||||
SHEET_NAME = "工资卡导入模板"
|
||||
UPLOAD_PATH = "/RedseaPlatform/uploadExtenalData/HrStaffWageCard.mc"
|
||||
PORTAL_URL = f"{HR_BASE_URL}/RedseaPlatform/PtPortal.mc?method=classic"
|
||||
WS_THEME = "WAGE_BASE_CARD_IMPORT"
|
||||
XLSX_MIME = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
|
||||
#: 页面内上传 + 订阅 WS 的脚本(结果写进 window.__result / window.__msgs)
|
||||
_JS_START = """
|
||||
var b64 = arguments[0], fitType = arguments[1], mime = arguments[2], theme = arguments[3], url = arguments[4];
|
||||
window.__msgs = [];
|
||||
window.__result = null;
|
||||
window.__uploadResp = null;
|
||||
(function () {
|
||||
var bin = atob(b64), arr = new Uint8Array(bin.length);
|
||||
for (var i = 0; i < bin.length; i++) { arr[i] = bin.charCodeAt(i); }
|
||||
var ws = new WebSocket('wss://' + location.host + '/RedseaPlatform/ws/service?theme=' + theme);
|
||||
ws.onopen = function () {
|
||||
ws.send(JSON.stringify({theme: theme, code: 'SUBCRIBE_THEME'}));
|
||||
var fd = new FormData();
|
||||
fd.append('importFile', new File([arr], 'wage_cards.xlsx', {type: mime}));
|
||||
fd.append('fitType', String(fitType));
|
||||
fetch(url, {
|
||||
method: 'POST', body: fd,
|
||||
headers: {'Csrf-Token': 'RP', 'X-Requested-With': 'XMLHttpRequest'}
|
||||
}).then(function (r) { return r.text(); }).then(function (t) { window.__uploadResp = t; });
|
||||
};
|
||||
ws.onmessage = function (e) {
|
||||
var txt = e.data;
|
||||
try { txt = JSON.parse(e.data).txt; } catch (err) { }
|
||||
window.__msgs.push(String(txt));
|
||||
if (String(txt).indexOf('over:') === 0) {
|
||||
window.__result = String(txt).slice(5);
|
||||
try { ws.close(); } catch (err) { }
|
||||
}
|
||||
};
|
||||
ws.onerror = function () { window.__msgs.push('[ws-error]'); };
|
||||
window.__ws = ws;
|
||||
})();
|
||||
return 'started';
|
||||
"""
|
||||
|
||||
|
||||
def build_xlsx(rows: Iterable[Sequence[Any]], headers: Optional[Sequence[str]] = None) -> bytes:
|
||||
"""按模板列顺序生成工资卡导入 xlsx(银行卡号强制数值)。"""
|
||||
from openpyxl import Workbook
|
||||
|
||||
wb = Workbook()
|
||||
sh = wb.active
|
||||
sh.title = SHEET_NAME
|
||||
sh.append(list(headers or HEADERS))
|
||||
for row in rows:
|
||||
values = list(row)
|
||||
if len(values) != len(HEADERS):
|
||||
raise ConfigError(f"工资卡导入行需 {len(HEADERS)} 列,实际 {len(values)} 列:{values!r}")
|
||||
# 第 9 列(下标 8)卡号必须是数字,否则服务端报「卡号必须是数字」
|
||||
card = str(values[8]).strip()
|
||||
if card:
|
||||
if not card.isdigit():
|
||||
raise ConfigError(f"银行卡号必须是纯数字:{card!r}")
|
||||
values[8] = int(card)
|
||||
sh.append(values)
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _cookie_list(source: Any, cookie_path: str = "") -> List[dict]:
|
||||
"""从 requests 会话 / cookies JSON / 文件路径取 cookie 列表(给浏览器注入)。"""
|
||||
if source is None or isinstance(source, str):
|
||||
path = source if isinstance(source, str) and source else cookie_path
|
||||
if not path:
|
||||
from .config import cookies_file
|
||||
path = cookies_file()
|
||||
if not path or not os.path.exists(path):
|
||||
raise ConfigError(f"未找到 HR 登录态 cookies:{path}")
|
||||
with open(path, encoding="utf-8") as fp:
|
||||
raw = json.load(fp)
|
||||
items = raw.get("cookies") if isinstance(raw, dict) else raw
|
||||
return [c for c in (items or []) if isinstance(c, dict) and c.get("name")]
|
||||
|
||||
cookies = getattr(source, "cookies", source)
|
||||
if isinstance(cookies, dict):
|
||||
return [{"name": k, "value": v, "domain": "hr.37du.co", "path": "/"}
|
||||
for k, v in cookies.items()]
|
||||
out = []
|
||||
for ck in cookies:
|
||||
name = getattr(ck, "name", None) or (ck.get("name") if isinstance(ck, dict) else None)
|
||||
if not name:
|
||||
continue
|
||||
value = getattr(ck, "value", None) if not isinstance(ck, dict) else ck.get("value", "")
|
||||
domain = (getattr(ck, "domain", "") if not isinstance(ck, dict) else ck.get("domain", "")) or "hr.37du.co"
|
||||
path = (getattr(ck, "path", "/") if not isinstance(ck, dict) else ck.get("path", "")) or "/"
|
||||
out.append({"name": name, "value": value or "", "domain": domain, "path": path})
|
||||
return out
|
||||
|
||||
|
||||
def _profile_dir() -> str:
|
||||
base = os.environ.get("LOCALAPPDATA") or tempfile.gettempdir()
|
||||
path = os.path.join(base, "37duAutomation", "_hr_browser")
|
||||
os.makedirs(path, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def import_cards(rows: Optional[Iterable[Sequence[Any]]] = None, *,
|
||||
xlsx: Optional[bytes] = None,
|
||||
session: Any = None, cookie_path: str = "",
|
||||
fit_type: int = 1, headless: bool = True,
|
||||
timeout: float = 300, log=print, keep_open: bool = False) -> Dict[str, Any]:
|
||||
"""导入工资卡并返回服务端结果。
|
||||
|
||||
Args:
|
||||
rows: 数据行(模板 10 列顺序),与 ``xlsx`` 二选一。
|
||||
xlsx: 直接给 xlsx 字节(需自备表头与数值卡号)。
|
||||
session: 借来的 requests 会话(取其中的 cookies 注入浏览器);也可传 cookies JSON 路径。
|
||||
fit_type: 1=按身份证,2=按工号。
|
||||
headless: 是否无头浏览器(无头实测可用)。
|
||||
timeout: 等待导入结果秒数。
|
||||
log: 日志回调。
|
||||
|
||||
Returns:
|
||||
``{"result": 1, "total": n, "successNum": n, "errorNum": n,
|
||||
"errorList": [...], "fileId": "...", "msgs": [...]}``
|
||||
"""
|
||||
log = log or (lambda *_a, **_k: None)
|
||||
if xlsx is None:
|
||||
if rows is None:
|
||||
raise ConfigError("rows 与 xlsx 至少给一个")
|
||||
xlsx = build_xlsx(rows)
|
||||
cookies = _cookie_list(session, cookie_path)
|
||||
b64 = base64.b64encode(xlsx).decode()
|
||||
|
||||
try:
|
||||
from DrissionPage import ChromiumOptions, ChromiumPage
|
||||
except ImportError: # pragma: no cover
|
||||
raise ConfigError("工资卡导入依赖 DrissionPage(pip install DrissionPage)") from None
|
||||
|
||||
options = ChromiumOptions(read_file=False)
|
||||
options.set_user_data_path(_profile_dir())
|
||||
options.set_argument("--remote-allow-origins=*")
|
||||
if headless:
|
||||
options.headless(True)
|
||||
page = ChromiumPage(options)
|
||||
try:
|
||||
page.set.cookies(cookies)
|
||||
page.get(PORTAL_URL, timeout=60)
|
||||
if "login" in (page.url or "").lower():
|
||||
raise ConfigError("HR 登录态已失效,请先登录")
|
||||
log(f"[wage_import] 页面就绪:{page.title}")
|
||||
page.run_js(_JS_START, b64, int(fit_type), XLSX_MIME, WS_THEME, UPLOAD_PATH)
|
||||
|
||||
deadline = time.time() + timeout
|
||||
raw = None
|
||||
while time.time() < deadline:
|
||||
time.sleep(2)
|
||||
raw = page.run_js("return window.__result")
|
||||
if raw:
|
||||
break
|
||||
msgs = page.run_js("return window.__msgs") or []
|
||||
upload_resp = page.run_js("return window.__uploadResp") or ""
|
||||
if not raw:
|
||||
raise ExportTimeoutError(
|
||||
f"等待工资卡导入结果超时({timeout}s);上传响应={str(upload_resp)[:120]},消息={msgs[-3:]}")
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except ValueError:
|
||||
raise HrError(f"导入结果无法解析:{raw!r}") from None
|
||||
data["msgs"] = msgs
|
||||
data["upload_resp"] = upload_resp
|
||||
log(f"[wage_import] 结果 result={data.get('result')} 成功 {data.get('successNum')} "
|
||||
f"失败 {data.get('errorNum')}")
|
||||
return data
|
||||
finally:
|
||||
if not keep_open:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
__all__ = ["HEADERS", "build_xlsx", "import_cards"]
|
||||
@@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "hr_sdk"
|
||||
version = "0.2.3"
|
||||
description = "HR(RedseaPlatform)接口 SDK:通用请求/分页/下载、commonQuery 加密、台账异步导出、花名册/预入职/调动/组织机构、工资账套与起调薪接口"
|
||||
version = "0.2.4"
|
||||
description = "HR(RedseaPlatform)接口 SDK:通用请求/分页/下载、commonQuery 加密、台账异步导出、花名册/预入职/调动/组织机构、工资账套与起调薪接口、工资卡导入(浏览器上下文)"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.9"
|
||||
dependencies = [
|
||||
@@ -13,6 +13,7 @@ dependencies = [
|
||||
"pandas>=1.5",
|
||||
"openpyxl>=3.1",
|
||||
"websocket-client>=1.5",
|
||||
"DrissionPage>=4.1",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
|
||||
@@ -2,3 +2,4 @@ requests>=2.28
|
||||
pandas>=1.5
|
||||
openpyxl>=3.1
|
||||
websocket-client>=1.5
|
||||
DrissionPage>=4.1
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
"schema_version": 1,
|
||||
"id": "hr_sdk",
|
||||
"name": "HR 系统 SDK",
|
||||
"version": "0.2.3",
|
||||
"description": "HR(RedseaPlatform)接口封装:通用请求/分页/下载、commonQuery 条件加密、台账异步导出(bridge+WS)、花名册/预入职/调动/合同台账/组织机构、审批流程(含「全部流程详细数据」导出)、考勤与排班、封存数据、附件下载、工资待办/账套/工资项/起调薪核对与提交、增减员导入(默认 dry-run)、登录原语",
|
||||
"version": "0.2.4",
|
||||
"description": "HR(RedseaPlatform)接口封装:通用请求/分页/下载、commonQuery 条件加密、台账异步导出(bridge+WS)、花名册/预入职/调动/合同台账/组织机构、审批流程(含「全部流程详细数据」导出)、考勤与排班、封存数据、附件下载、工资待办/账套/工资项/起调薪核对与提交、增减员导入(默认 dry-run)、工资卡导入(浏览器上下文 + WS 结果)、登录原语",
|
||||
"provides": [
|
||||
"hr_sdk"
|
||||
],
|
||||
@@ -11,7 +11,8 @@
|
||||
"requests",
|
||||
"pandas",
|
||||
"openpyxl",
|
||||
"websocket"
|
||||
"websocket",
|
||||
"DrissionPage"
|
||||
],
|
||||
"python": ">=3.9",
|
||||
"minRuntimeVersion": "",
|
||||
|
||||
@@ -10,13 +10,14 @@
|
||||
|
||||
| 项 | 规则 |
|
||||
|---|---|
|
||||
| 核查窗口 | 近 `days` 天(默认 9,含当天) |
|
||||
| 核查窗口 | 近 `days` 天(默认 9,含当天)再排除最近 2 天(当天/昨天),实际核查 7 天 |
|
||||
| 调动台账 | 按「调动时间」落在窗口内;`现职位序列` 含「职能」→ 比「现单位」,否则比「现四级部门」;当日排班属于该部门即正常 |
|
||||
| 排班归属 | 先按 `rf_s_kq_work_date_query` 查该部门全部排班名做成员判断;接口查不到集合时兜底「完整排班名包含部门名」 |
|
||||
| 预入职台账 | 按「操作时间」落在窗口内;「预入职日期」当天有排班即正常 |
|
||||
| 剔除不推送 | `现职位序列` 命中 经营系管理序列 / 职能系专业序列 / 门店技师序列 |
|
||||
| 单位未变 | 职能类序列且「原单位」=「现单位」→ 不纳入 |
|
||||
| 离职过滤 | 花名册查不到工号 → 按离职剔除(调动/入职都生效) |
|
||||
| 后勤剔除 | 花名册「一级部门」含「后勤」(如后勤(C))→ 不纳入异常、不推送 |
|
||||
| 店长解析 | 固定路由优先(`秒创传媒职能序列` → 刘凤琳 37010004);否则按工号取部门链(四级→三级→所属→二级)逐级找同名门店下岗位含「店长」的人;仍解析不到 → 默认处理人(多个轮流分配),无默认处理人则只留档不推送 |
|
||||
| 生物识别 | 考勤平台 BioData `q=工号` 记录为 0 → 标「未登记」,在店长消息尾部单独成段;平台异常时降级跳过 |
|
||||
|
||||
@@ -27,9 +28,8 @@
|
||||
| 字段 | 默认 | 说明 |
|
||||
|---|---|---|
|
||||
| `save_dir` | `D:\资料\人资\排班异常识别` | 名单、台账(`台账/`)、推送记录(`推送记录/`) |
|
||||
| `days` | 9 | 核查窗口天数 |
|
||||
| `refresh` | true | 关闭则复用已有台账/花名册 |
|
||||
| `roster_path` / `transfer_ledger` / `preentry_ledger` | 空 | 留空自动用 SDK 导出到 `save_dir/台账/` |
|
||||
| `days` | 9 | 核查窗口天数(再排除最近 2 天,实际核查 N-2 天) |
|
||||
| `roster_cache` | true | 花名册 30 分钟内复用;关闭则每次重新导出(台账每次都重新导) |
|
||||
| `push` | true | 关闭只出名单 |
|
||||
| `push_group` | 数字人沟通群 | 汇总群全称 |
|
||||
| `push_at_all` | false | 汇总群 @所有人 |
|
||||
@@ -37,6 +37,7 @@
|
||||
| `check_biometrics` | true | 生物识别核查开关 |
|
||||
| `bio_username` / `bio_password` | 空 | 考勤平台账号(留空用内置/环境变量) |
|
||||
| `dws_path` | 空 | 留空自动检测(`DINGTALK_DWS_BIN` → 用户目录 → PATH) |
|
||||
| `probe_dws` | false | 仅检测 dws(插件 UI「检测」按钮用):立即返回 `dws_available`/`dws_path`,不取数、不推送 |
|
||||
|
||||
## dws 检测
|
||||
|
||||
|
||||
@@ -53,7 +53,7 @@ class ShiftAbnormalPlugin(ScenePlugin):
|
||||
|
||||
id = "xq0001"
|
||||
name = "排班异常识别"
|
||||
version = "1.0.1"
|
||||
version = "1.0.3"
|
||||
description = ("核查近 N 天新入职/调入人员的当日排班是否属于应有门店,输出异常名单并按店长"
|
||||
"单聊 + 汇总群推送(依赖 hr_sdk / dingtalk_sdk;未装 dws 时只出名单不推送)。")
|
||||
platform = "hr"
|
||||
@@ -70,21 +70,9 @@ class ShiftAbnormalPlugin(ScenePlugin):
|
||||
"type": "int", "title": "核查窗口(天)", "default": config.DAYS_DEFAULT,
|
||||
"description": "近 N 天(含当天)内新入职/调动的人员",
|
||||
},
|
||||
"refresh": {
|
||||
"type": "boolean", "title": "重新导出台账与花名册", "default": True,
|
||||
"description": "关闭则复用输出目录下已有文件(调试用,避免每次重复导出)",
|
||||
},
|
||||
"roster_path": {
|
||||
"type": "string", "title": "花名册路径", "default": "",
|
||||
"description": "留空 = 自动导出到「输出目录/台账/员工花名册.xlsx」",
|
||||
},
|
||||
"transfer_ledger": {
|
||||
"type": "string", "title": "调动台账路径", "default": "",
|
||||
"description": "留空 = 自动导出到「输出目录/台账/调动台账.xlsx」",
|
||||
},
|
||||
"preentry_ledger": {
|
||||
"type": "string", "title": "预入职台账路径", "default": "",
|
||||
"description": "留空 = 自动导出到「输出目录/台账/预入职台账.xlsx」",
|
||||
"roster_cache": {
|
||||
"type": "boolean", "title": "花名册 30 分钟内复用", "default": True,
|
||||
"description": "开启后同一份在职花名册 30 分钟内直接复用;关闭则每次重新导出",
|
||||
},
|
||||
"push": {
|
||||
"type": "boolean", "title": "推送钉钉", "default": True,
|
||||
@@ -128,6 +116,20 @@ class ShiftAbnormalPlugin(ScenePlugin):
|
||||
def log(msg: str, level: str = "INFO") -> None:
|
||||
ctx.log(msg, level)
|
||||
|
||||
# ---- 0. 仅检测 dws(UI「检测」按钮:probe_dws=true,不取数、不推送) ----
|
||||
if bool(fields.get("probe_dws", False)):
|
||||
path = detect_dws(str(fields.get("dws_path") or ""))
|
||||
if path:
|
||||
log(f"[INFO] dws 检测通过:{path}")
|
||||
else:
|
||||
log("[WARN] 未检测到 dws:执行时将只出名单、不推送", "WARNING")
|
||||
return {
|
||||
"ok": True, "probe": True,
|
||||
"dws_available": bool(path), "dws_path": path,
|
||||
"summary": (f"dws 可用:{path}" if path
|
||||
else "未检测到 dws(执行时只出名单、不推送)"),
|
||||
}
|
||||
|
||||
save_dir = config.save_dir(fields)
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
|
||||
@@ -162,30 +164,24 @@ class ShiftAbnormalPlugin(ScenePlugin):
|
||||
def _run(self, client, fields: dict, save_dir: str, dws_path: str,
|
||||
log, ctx) -> dict:
|
||||
days = config.days(fields)
|
||||
refresh = bool(fields.get("refresh", True))
|
||||
ledger_dir = os.path.join(save_dir, config.LEDGER_SUBDIR)
|
||||
os.makedirs(ledger_dir, exist_ok=True)
|
||||
|
||||
# ---- 3. 取数(按需现导) ----
|
||||
roster_path = self._pick(fields.get("roster_path"),
|
||||
os.path.join(ledger_dir, config.ROSTER_FILENAME))
|
||||
if refresh or not os.path.exists(roster_path):
|
||||
log("[INFO] 导出员工花名册(在职)…")
|
||||
roster_path = hr_roster.export(
|
||||
client, statuses=["在职"], output=roster_path, ttl=0)
|
||||
# ---- 3. 取数:台账与花名册一律现导到「输出目录/台账/」 ----
|
||||
roster_path = os.path.join(ledger_dir, config.ROSTER_FILENAME)
|
||||
roster_ttl = config.ROSTER_TTL_CACHE if bool(fields.get("roster_cache", True)) else 0
|
||||
log("[INFO] 导出员工花名册(在职)…")
|
||||
roster_path = hr_roster.export(
|
||||
client, statuses=["在职"], output=roster_path, ttl=roster_ttl)
|
||||
ctx.progress(30)
|
||||
|
||||
transfer_path = self._pick(fields.get("transfer_ledger"),
|
||||
os.path.join(ledger_dir, config.TRANSFER_FILENAME))
|
||||
if refresh or not os.path.exists(transfer_path):
|
||||
log("[INFO] 导出调动台账…")
|
||||
transfer_path = hr_ledger.export_transfer(client, output=transfer_path)
|
||||
transfer_path = os.path.join(ledger_dir, config.TRANSFER_FILENAME)
|
||||
log("[INFO] 导出调动台账…")
|
||||
transfer_path = hr_ledger.export_transfer(client, output=transfer_path)
|
||||
|
||||
preentry_path = self._pick(fields.get("preentry_ledger"),
|
||||
os.path.join(ledger_dir, config.PREENTRY_FILENAME))
|
||||
if refresh or not os.path.exists(preentry_path):
|
||||
log("[INFO] 导出预入职台账…")
|
||||
preentry_path = hr_ledger.export_pre_entry(client, output=preentry_path)
|
||||
preentry_path = os.path.join(ledger_dir, config.PREENTRY_FILENAME)
|
||||
log("[INFO] 导出预入职台账…")
|
||||
preentry_path = hr_ledger.export_pre_entry(client, output=preentry_path)
|
||||
ctx.progress(45)
|
||||
|
||||
# ---- 4. 判定 ----
|
||||
@@ -215,6 +211,22 @@ class ShiftAbnormalPlugin(ScenePlugin):
|
||||
"WARNING")
|
||||
rows = [r for r in rows if rules.to_text(r.get("工号")) in roster_codes]
|
||||
|
||||
# 后勤组织过滤:花名册「一级部门」含「后勤」的(如后勤(C))不纳入异常
|
||||
if rows:
|
||||
dept1_by_code = manager_mod.dept1_map(roster_df)
|
||||
if not dept1_by_code:
|
||||
log(f"[WARN] 花名册缺少「{config.COL_DEPT1}」列,后勤组织剔除未生效",
|
||||
"WARNING")
|
||||
else:
|
||||
excluded = [r for r in rows
|
||||
if manager_mod.dept1_excluded(
|
||||
dept1_by_code.get(rules.to_text(r.get("工号")), ""))]
|
||||
if excluded:
|
||||
names = [f"{r.get('姓名')}/{r.get('工号')}" for r in excluded]
|
||||
log(f"[WARN] 一级部门含后勤,剔除 {len(excluded)} 人:{names}",
|
||||
"WARNING")
|
||||
rows = [r for r in rows if r not in excluded]
|
||||
|
||||
# 预入职台账无四级部门列 → 按工号回填
|
||||
for row in rows:
|
||||
if row.get("类别") == "入职" and not rules.clean(row.get("现四级部门")):
|
||||
@@ -275,11 +287,6 @@ class ShiftAbnormalPlugin(ScenePlugin):
|
||||
return summary
|
||||
|
||||
# ---------------- 工具 ----------------
|
||||
@staticmethod
|
||||
def _pick(explicit, fallback: str) -> str:
|
||||
value = str(explicit or "").strip()
|
||||
return os.path.abspath(value) if value else os.path.abspath(fallback)
|
||||
|
||||
@staticmethod
|
||||
def _push(payload, dws_path: str, save_dir: str, log) -> dict:
|
||||
"""执行推送(单聊 + 汇总群),返回摘要字段。"""
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""发布打包辅助(`_` 前缀,运行时不会被插件扫描加载)。
|
||||
|
||||
把插件压成 dist-plugin/xq0084_v<版本>.zip(zip 根含 plugin.json)。
|
||||
排除:ui-src、__pycache__、_selftest*、本脚本、*.pyc。
|
||||
"""
|
||||
import json
|
||||
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", "out", "images"}
|
||||
_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():
|
||||
raise SystemExit("ui=true 但缺少 ui/index.html:请先在 ui-src 下执行 npm run build")
|
||||
_OUT_DIR.mkdir(exist_ok=True)
|
||||
out = _OUT_DIR / f"{pid}_v{ver}.zip"
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for p in sorted(_HERE.rglob("*")):
|
||||
rel = p.relative_to(_HERE)
|
||||
if set(rel.parts) & _EXCLUDE_DIRS or p.name in _EXCLUDE_FILES:
|
||||
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()
|
||||
@@ -74,8 +74,10 @@ def test_rules() -> None:
|
||||
_eq(rules.clean("37000001.0"), "37000001", "去掉浮点尾缀")
|
||||
_eq(rules.clean(" nan "), "", "空占位清洗")
|
||||
_eq(rules.shift_name("2026-11-09_印象-门店-服务岗"), "印象-门店-服务岗", "排班名去日期前缀")
|
||||
_eq(rules.recent_window(date(2026, 11, 9), 9), (date(2026, 11, 1), date(2026, 11, 9)),
|
||||
"近 9 天窗口")
|
||||
_eq(rules.recent_window(date(2026, 11, 9), 9), (date(2026, 11, 1), date(2026, 11, 7)),
|
||||
"近 9 天窗口排除最近 2 天 → 实际 7 天")
|
||||
_eq(rules.recent_window(date(2026, 11, 9), 2), (date(2026, 11, 8), date(2026, 11, 8)),
|
||||
"窗口天数不大于排除天数时至少保留 1 天")
|
||||
_ok(rules.seq_excluded("经营系管理序列"), "剔除序列命中")
|
||||
_ok(not rules.seq_excluded("门店服务序列"), "非剔除序列不命中")
|
||||
|
||||
@@ -127,16 +129,16 @@ def test_rules() -> None:
|
||||
|
||||
def _roster() -> pd.DataFrame:
|
||||
return pd.DataFrame([
|
||||
{"工号": "E1", "姓名": "张三", "四级部门": "门店A", "三级部门": "", "所属部门": "",
|
||||
"二级部门": "", "岗位": "服务员"},
|
||||
{"工号": "M1", "姓名": "王店长", "四级部门": "门店A", "三级部门": "", "所属部门": "",
|
||||
"二级部门": "", "岗位": "店长"},
|
||||
{"工号": "E3", "姓名": "赵六", "四级部门": "", "三级部门": "门店C", "所属部门": "",
|
||||
"二级部门": "", "岗位": "技师"},
|
||||
{"工号": "M3", "姓名": "陈店长", "四级部门": "", "三级部门": "门店C", "所属部门": "",
|
||||
"二级部门": "", "岗位": "店长"},
|
||||
{"工号": "E4", "姓名": "孙七", "四级部门": "门店D", "三级部门": "", "所属部门": "",
|
||||
"二级部门": "", "岗位": "服务员"},
|
||||
{"工号": "E1", "姓名": "张三", "一级部门": "集团门店一部", "四级部门": "门店A",
|
||||
"三级部门": "", "所属部门": "", "二级部门": "", "岗位": "服务员"},
|
||||
{"工号": "M1", "姓名": "王店长", "一级部门": "集团门店一部", "四级部门": "门店A",
|
||||
"三级部门": "", "所属部门": "", "二级部门": "", "岗位": "店长"},
|
||||
{"工号": "E3", "姓名": "赵六", "一级部门": "集团门店一部", "四级部门": "",
|
||||
"三级部门": "门店C", "所属部门": "", "二级部门": "", "岗位": "技师"},
|
||||
{"工号": "M3", "姓名": "陈店长", "一级部门": "集团门店一部", "四级部门": "",
|
||||
"三级部门": "门店C", "所属部门": "", "二级部门": "", "岗位": "店长"},
|
||||
{"工号": "E4", "姓名": "孙七", "一级部门": "后勤(C)", "四级部门": "门店D",
|
||||
"三级部门": "", "所属部门": "", "二级部门": "", "岗位": "服务员"},
|
||||
])
|
||||
|
||||
|
||||
@@ -151,6 +153,12 @@ def test_manager() -> None:
|
||||
_eq(manager_mod.find_store_by_manager(frame, "M1", "王店长"), "门店A", "店长所属门店")
|
||||
_eq(manager_mod.lookup_dept4_by_code(frame, "E1"), "门店A", "按工号回填四级部门")
|
||||
|
||||
dept1_by_code = manager_mod.dept1_map(frame)
|
||||
_eq(dept1_by_code.get("E4"), "后勤(C)", "工号→一级部门映射")
|
||||
_ok(manager_mod.dept1_excluded(dept1_by_code.get("E4", "")), "一级部门含后勤命中剔除")
|
||||
_ok(not manager_mod.dept1_excluded(dept1_by_code.get("E1", "")), "非后勤一级部门不剔除")
|
||||
_eq(manager_mod.dept1_map(pd.DataFrame([{"工号": "E1"}])), {}, "无一级部门列返回空映射")
|
||||
|
||||
fixed = manager_mod.match_fixed_route({"现职位序列": "秒创传媒职能序列"})
|
||||
_eq(fixed, (("37010004", "刘凤琳"), "秒创传媒职能序列"), "固定路由命中")
|
||||
_eq(manager_mod.match_fixed_route({"现职位序列": "门店服务序列"}), None, "固定路由未命中")
|
||||
|
||||
@@ -17,10 +17,14 @@ ROSTER_FILENAME = "员工花名册.xlsx"
|
||||
TRANSFER_FILENAME = "调动台账.xlsx"
|
||||
PREENTRY_FILENAME = "预入职台账.xlsx"
|
||||
RECORD_SUBDIR = "推送记录"
|
||||
#: 花名册缓存有效期(秒):开启「30 分钟内复用」时同路径文件直接复用
|
||||
ROSTER_TTL_CACHE = 1800
|
||||
|
||||
# ==================== 核查窗口 ====================
|
||||
#: 近 N 天(含当天)
|
||||
DAYS_DEFAULT = 9
|
||||
#: 「近 N 天」中再排除最近 M 天(当天/昨天数据未稳定):9 天口径实际核查 7 天
|
||||
WINDOW_EXCLUDE_RECENT_DAYS = 2
|
||||
#: 每 N 次查询校验一次登录态(避免会话过期后逐人触发重登)
|
||||
SESSION_REVALIDATE_EVERY = 30
|
||||
|
||||
@@ -30,6 +34,7 @@ COL_CODE = "工号"
|
||||
COL_DEPT4 = "四级部门"
|
||||
COL_DEPT3 = "三级部门"
|
||||
COL_DEPT2 = "二级部门"
|
||||
COL_DEPT1 = "一级部门"
|
||||
COL_DEPT_SELF = "所属部门"
|
||||
COL_POSITION = "岗位"
|
||||
MANAGER_KEYWORD = "店长"
|
||||
@@ -40,6 +45,8 @@ ROSTER_REQUIRED = (COL_CODE, COL_NAME, COL_DEPT4, COL_POSITION)
|
||||
# ==================== 判定口径 ====================
|
||||
#: 现职位序列命中以下序列的异常不纳入、不推送
|
||||
EXCLUDE_SEQ_KEYWORDS = ("经营系管理序列", "职能系专业序列", "门店技师序列")
|
||||
#: 花名册「一级部门」含以下关键字的异常不纳入、不推送(集团下的后勤组织,如后勤(C))
|
||||
EXCLUDE_DEPT1_KEYWORDS = ("后勤",)
|
||||
#: 调动名单:命中以下职能序列且「原单位」=「现单位」的,不纳入异常
|
||||
FUNC_SEQ_UNIT_UNCHANGED_KEYWORDS = (
|
||||
"职能管理序列", "职能系管理序列", "职能专业序列", "职能系专业序列",
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import List, Optional, Tuple
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
import pandas as pd
|
||||
|
||||
@@ -118,6 +118,20 @@ def lookup_dept4_by_code(frame: pd.DataFrame, code: str) -> str:
|
||||
return to_text(hit.iloc[0][config.COL_DEPT4])
|
||||
|
||||
|
||||
def dept1_map(frame: pd.DataFrame) -> Dict[str, str]:
|
||||
"""工号 → 一级部门(花名册无「一级部门」列时返回空 dict)。"""
|
||||
if config.COL_DEPT1 not in frame.columns:
|
||||
return {}
|
||||
return {to_text(code): to_text(dept1) for code, dept1
|
||||
in zip(frame[config.COL_CODE], frame[config.COL_DEPT1])}
|
||||
|
||||
|
||||
def dept1_excluded(dept1: str) -> bool:
|
||||
"""一级部门命中剔除关键字(如「后勤」)→ True。"""
|
||||
text = clean(dept1)
|
||||
return any(keyword in text for keyword in config.EXCLUDE_DEPT1_KEYWORDS)
|
||||
|
||||
|
||||
def match_fixed_route(row: dict):
|
||||
"""命中固定路由返回 ``((工号, 姓名), 范围描述)``,未命中返回 ``None``。"""
|
||||
seq = to_text(row.get("现职位序列"))
|
||||
|
||||
@@ -69,9 +69,11 @@ def parse_date(value) -> Optional[date]:
|
||||
|
||||
def recent_window(end: Optional[date] = None, days: int = config.DAYS_DEFAULT
|
||||
) -> Tuple[date, date]:
|
||||
"""近 N 天闭区间(含当天)。"""
|
||||
"""核查窗口:近 N 天(含当天),再排除最近 M 天(当天/昨天),实际 N-M 天。"""
|
||||
end = end or date.today()
|
||||
return end - timedelta(days=max(1, days) - 1), end
|
||||
days = max(1, days)
|
||||
skip = min(config.WINDOW_EXCLUDE_RECENT_DAYS, days - 1)
|
||||
return end - timedelta(days=days - 1), end - timedelta(days=skip)
|
||||
|
||||
|
||||
# ==================== 台账 ====================
|
||||
@@ -251,7 +253,9 @@ def collect_rows(ledger_path: str, check_row, fetcher: ShiftFetcher,
|
||||
"""读台账 → 逐行判定 → 异常行列表。"""
|
||||
frame = load_ledger(ledger_path, log)
|
||||
begin, end_date = recent_window(end, days)
|
||||
log(f"[INFO] 筛选范围:{begin} ~ {end_date}(近 {days} 天)")
|
||||
log(f"[INFO] 筛选范围:{begin} ~ {end_date}(近 {days} 天,排除最近 "
|
||||
f"{config.WINDOW_EXCLUDE_RECENT_DAYS} 天,实际核查 "
|
||||
f"{(end_date - begin).days + 1} 天)")
|
||||
rows = []
|
||||
for _, raw in frame.iterrows():
|
||||
row = check_row(fetcher, dept_fetcher, raw, begin, end_date)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0001",
|
||||
"name": "排班异常识别",
|
||||
"version": "1.0.1",
|
||||
"version": "1.0.3",
|
||||
"description": "核查近 N 天新入职/调入人员的当日排班是否属于应有门店;输出异常名单(含店长/处理人、推送状态、生物识别),按店长单聊 + 汇总群推送。依赖 hr_sdk(取数与台账导出)与 dingtalk_sdk(单聊/群聊推送);本机未安装 dws 时只出名单不推送。",
|
||||
"category": "人资",
|
||||
"icon": "",
|
||||
@@ -40,31 +40,13 @@
|
||||
"type": "integer",
|
||||
"title": "核查窗口(天)",
|
||||
"default": 9,
|
||||
"description": "近 N 天(含当天)内新入职/调动的人员"
|
||||
"description": "近 N 天(含当天)内新入职/调动的人员,再排除最近 2 天(当天/昨天),实际核查 N-2 天"
|
||||
},
|
||||
"refresh": {
|
||||
"roster_cache": {
|
||||
"type": "boolean",
|
||||
"title": "重新导出台账与花名册",
|
||||
"title": "花名册 30 分钟内复用",
|
||||
"default": true,
|
||||
"description": "关闭则复用输出目录下已有文件(调试用,避免每次重复导出)"
|
||||
},
|
||||
"roster_path": {
|
||||
"type": "string",
|
||||
"title": "花名册路径",
|
||||
"default": "",
|
||||
"description": "留空 = 自动导出到「输出目录/台账/员工花名册.xlsx」"
|
||||
},
|
||||
"transfer_ledger": {
|
||||
"type": "string",
|
||||
"title": "调动台账路径",
|
||||
"default": "",
|
||||
"description": "留空 = 自动导出到「输出目录/台账/调动台账.xlsx」"
|
||||
},
|
||||
"preentry_ledger": {
|
||||
"type": "string",
|
||||
"title": "预入职台账路径",
|
||||
"default": "",
|
||||
"description": "留空 = 自动导出到「输出目录/台账/预入职台账.xlsx」"
|
||||
"description": "开启后同一份在职花名册 30 分钟内直接复用;关闭则每次重新导出(台账每次都重新导)"
|
||||
},
|
||||
"push": {
|
||||
"type": "boolean",
|
||||
@@ -114,6 +96,12 @@
|
||||
"title": "dws 路径",
|
||||
"default": "",
|
||||
"description": "留空自动检测(DINGTALK_DWS_BIN / 用户目录 / PATH);检测不到会跳过推送"
|
||||
},
|
||||
"probe_dws": {
|
||||
"type": "boolean",
|
||||
"title": "仅检测 dws",
|
||||
"default": false,
|
||||
"description": "插件 UI「检测」按钮使用:只检测 dws 是否可用并立即返回,不取数、不推送"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
|
||||
+1579
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<!-- ① 工具条:整组靠右(已保存 → 方案下拉 → 存为方案 → 删除) -->
|
||||
<!-- 方案工具条:本机配置自动保存;方案供壳子「定时任务」按 config_id 引用 -->
|
||||
<div class="toolbar">
|
||||
<span class="spacer" />
|
||||
<span class="saved" :class="{ 'is-idle': !lastSavedAt }">
|
||||
@@ -15,12 +15,12 @@
|
||||
@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">·</span><span>{{ notice.text }}</span>
|
||||
<span class="n-ico">{{ notice.type === 'ok' ? '✓' : (notice.type === 'error' ? '✕' : '!') }}</span>
|
||||
<span>{{ notice.text }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 01 执行设置 -->
|
||||
@@ -31,19 +31,16 @@
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="sec-body">
|
||||
<el-form label-position="top" @submit.prevent>
|
||||
<div class="grid">
|
||||
<el-form-item class="span-all" label="输出目录">
|
||||
<el-form label-position="top">
|
||||
<div class="grid-2">
|
||||
<el-form-item label="输出目录">
|
||||
<div class="dir-ctrl">
|
||||
<el-input v-model="form.save_dir" class="dir-input" :disabled="running" clearable
|
||||
placeholder="留空 = D:\资料\人资\排班异常识别" />
|
||||
<el-button class="dir-btn" :disabled="running || picking === 'save_dir'"
|
||||
:loading="picking === 'save_dir'" @click="pickDir('save_dir', '选择输出目录')">
|
||||
选择
|
||||
</el-button>
|
||||
<el-button class="dir-btn" :disabled="running || picking" :loading="picking"
|
||||
@click="pickDir">选择</el-button>
|
||||
</div>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="核查窗口(天)">
|
||||
<el-input-number v-model="form.days" :min="1" :max="60" :step="1"
|
||||
:disabled="running" controls-position="right" />
|
||||
@@ -53,104 +50,52 @@
|
||||
<div class="rows">
|
||||
<div class="row">
|
||||
<div class="r-main">
|
||||
<div class="r-title">重新导出台账与花名册</div>
|
||||
<div class="r-desc">关闭则复用「输出目录/台账/」下已有文件(调试用,避免每次重复导出)</div>
|
||||
<div class="r-title">花名册 30 分钟内复用</div>
|
||||
<div class="r-desc">开启后同一份在职花名册 30 分钟内直接复用;关闭则每次重新导出</div>
|
||||
</div>
|
||||
<div class="r-ctrl">
|
||||
<el-switch v-model="form.roster_cache" :disabled="running" />
|
||||
</div>
|
||||
<div class="r-ctrl"><el-switch v-model="form.refresh" :disabled="running" /></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="tip">
|
||||
核查口径:<b>近 N 天(含当天)</b>新入职/调入人员,
|
||||
调动按「调动时间」、入职按「预入职日期」查当日排班是否属于应有门店。
|
||||
台账与花名册自动导出到 <b>输出目录/台账/</b>;核查近 N 天(含当天)内新入职/调入人员,
|
||||
调动按「调动时间」、入职按「预入职日期」核对当日排班,再排除当天/昨天(默认 9 天实际核查 7 天)。
|
||||
</div>
|
||||
</el-form>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 02 台账来源 -->
|
||||
<!-- 02 钉钉推送 -->
|
||||
<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" @submit.prevent>
|
||||
<div class="grid">
|
||||
<el-form-item class="span-all" label="花名册路径">
|
||||
<div class="dir-ctrl">
|
||||
<el-input v-model="form.roster_path" class="dir-input" :disabled="running" clearable
|
||||
placeholder="留空自动导出:台账/员工花名册.xlsx" />
|
||||
<el-button class="dir-btn" :disabled="running || picking === 'roster_path'"
|
||||
:loading="picking === 'roster_path'"
|
||||
@click="pickFile('roster_path', '选择花名册文件', ['xlsx', 'xlsm'])">
|
||||
选择
|
||||
</el-button>
|
||||
</div>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="调动台账路径">
|
||||
<div class="dir-ctrl">
|
||||
<el-input v-model="form.transfer_ledger" class="dir-input" :disabled="running" clearable
|
||||
placeholder="留空自动导出:台账/调动台账.xlsx" />
|
||||
<el-button class="dir-btn" :disabled="running || picking === 'transfer_ledger'"
|
||||
:loading="picking === 'transfer_ledger'"
|
||||
@click="pickFile('transfer_ledger', '选择调动台账', ['xlsx', 'xlsm'])">
|
||||
选择
|
||||
</el-button>
|
||||
</div>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="预入职台账路径">
|
||||
<div class="dir-ctrl">
|
||||
<el-input v-model="form.preentry_ledger" class="dir-input" :disabled="running" clearable
|
||||
placeholder="留空自动导出:台账/预入职台账.xlsx" />
|
||||
<el-button class="dir-btn" :disabled="running || picking === 'preentry_ledger'"
|
||||
:loading="picking === 'preentry_ledger'"
|
||||
@click="pickFile('preentry_ledger', '选择预入职台账', ['xlsx', 'xlsm'])">
|
||||
选择
|
||||
</el-button>
|
||||
</div>
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">
|
||||
三项都留空时,插件会用 <b>hr_sdk</b> 现导花名册(在职)与两本台账到
|
||||
「输出目录/台账/」。表头均按第 2 行读取。
|
||||
</div>
|
||||
</el-form>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 03 推送 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">03</span>
|
||||
<span class="sec-name">钉钉推送</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="sec-body">
|
||||
<el-form label-position="top" @submit.prevent>
|
||||
<div class="rows">
|
||||
<div class="row">
|
||||
<div class="r-main">
|
||||
<div class="r-title">推送钉钉</div>
|
||||
<div class="r-desc">按店长单聊 + 汇总群;关闭则只出名单</div>
|
||||
</div>
|
||||
<div class="r-ctrl"><el-switch v-model="form.push" :disabled="running" /></div>
|
||||
<div class="rows">
|
||||
<div class="row">
|
||||
<div class="r-main">
|
||||
<div class="r-title">推送钉钉</div>
|
||||
<div class="r-desc">按店长单聊 + 汇总群;关闭则只出名单</div>
|
||||
</div>
|
||||
<div class="row" :class="{ 'is-hidden': !form.push }">
|
||||
<div class="r-main">
|
||||
<div class="r-title">汇总群 @所有人</div>
|
||||
<div class="r-desc">需群里有 @所有人 权限</div>
|
||||
</div>
|
||||
<div class="r-ctrl">
|
||||
<el-switch v-model="form.push_at_all" :disabled="running || !form.push" />
|
||||
</div>
|
||||
<div class="r-ctrl"><el-switch v-model="form.push" :disabled="running" /></div>
|
||||
</div>
|
||||
<div class="row" :class="{ 'is-hidden': !form.push }">
|
||||
<div class="r-main">
|
||||
<div class="r-title">汇总群 @所有人</div>
|
||||
<div class="r-desc">需群里有 @所有人 权限</div>
|
||||
</div>
|
||||
<div class="r-ctrl">
|
||||
<el-switch v-model="form.push_at_all" :disabled="running || !form.push" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-date">
|
||||
<el-form label-position="top" class="mt-3">
|
||||
<div class="grid">
|
||||
<el-form-item label="汇总群名">
|
||||
<el-input v-model="form.push_group" :disabled="running || !form.push" clearable
|
||||
placeholder="数字人沟通群" />
|
||||
@@ -159,48 +104,49 @@
|
||||
<el-input v-model="form.default_manager" :disabled="running" clearable
|
||||
placeholder="工号或姓名,多个用英文逗号分隔" />
|
||||
</el-form-item>
|
||||
<el-form-item class="span-all" label="dws 路径">
|
||||
<div class="dir-ctrl">
|
||||
<el-input v-model="form.dws_path" class="dir-input" :disabled="running" clearable
|
||||
placeholder="留空自动检测(DINGTALK_DWS_BIN / 用户目录 / PATH)" />
|
||||
<el-button class="dir-btn" :disabled="running || picking === 'dws_path'"
|
||||
:loading="picking === 'dws_path'"
|
||||
@click="pickFile('dws_path', '选择 dws.exe', ['exe'])">
|
||||
选择
|
||||
</el-button>
|
||||
</div>
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
<el-form-item label="dws 路径">
|
||||
<div class="dir-ctrl">
|
||||
<el-input v-model="form.dws_path" class="dir-input" :disabled="running" clearable
|
||||
placeholder="留空自动检测(DINGTALK_DWS_BIN / 用户目录 / PATH)" />
|
||||
<el-button class="dir-btn" :disabled="running || picking" :loading="picking"
|
||||
@click="pickDwsFile">选择</el-button>
|
||||
<el-button class="dir-btn" :disabled="running || probing" :loading="probing"
|
||||
@click="probeDws">检测</el-button>
|
||||
</div>
|
||||
</el-form-item>
|
||||
|
||||
<div class="tip">
|
||||
本机未安装 dws 时会<b>自动跳过推送</b>(名单照常留档),并在日志提示;
|
||||
本机未安装 dws 时会<b>自动跳过推送</b>(名单照常留档);「检测」会把找到的路径回填到输入框。
|
||||
解析不到店长的异常归入「默认处理人」(多个轮流分配),留空则只留档不推送。
|
||||
</div>
|
||||
</el-form>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 04 生物识别 -->
|
||||
<!-- 03 生物识别核查 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">04</span>
|
||||
<span class="sec-badge">03</span>
|
||||
<span class="sec-name">生物识别核查</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="sec-body">
|
||||
<el-form label-position="top" @submit.prevent>
|
||||
<div class="rows">
|
||||
<div class="row">
|
||||
<div class="r-main">
|
||||
<div class="r-title">核查是否已录指纹 / 人脸</div>
|
||||
<div class="r-desc">调考勤平台 BioData(与 HR 不同系统);存在账号互踢,可能顶掉当前考勤会话</div>
|
||||
</div>
|
||||
<div class="r-ctrl">
|
||||
<el-switch v-model="form.check_biometrics" :disabled="running" />
|
||||
</div>
|
||||
<div class="rows">
|
||||
<div class="row">
|
||||
<div class="r-main">
|
||||
<div class="r-title">核查是否已录指纹 / 人脸</div>
|
||||
<div class="r-desc">调考勤平台 BioData(与 HR 不同系统);存在账号互踢,可能顶掉当前考勤会话</div>
|
||||
</div>
|
||||
<div class="r-ctrl">
|
||||
<el-switch v-model="form.check_biometrics" :disabled="running" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-date" :class="{ 'is-dim': !form.check_biometrics }">
|
||||
<el-form label-position="top" class="mt-3" :class="{ 'is-dim': !form.check_biometrics }">
|
||||
<div class="grid">
|
||||
<el-form-item label="考勤平台账号">
|
||||
<el-input v-model="form.bio_username" :disabled="running || !form.check_biometrics"
|
||||
clearable placeholder="留空用内置 / attendance_login_username" />
|
||||
@@ -219,7 +165,7 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ④ 折叠说明 -->
|
||||
<!-- 判定口径与输出 -->
|
||||
<details class="help">
|
||||
<summary><span>判定口径与输出</span><span class="h-arrow">▾</span></summary>
|
||||
<div class="help-body">
|
||||
@@ -227,7 +173,8 @@
|
||||
当日排班属于该部门即正常(按部门查全部排班名做成员判断,查不到集合时兜底「排班名包含部门名」)。</div>
|
||||
<div class="hb-line"><b>入职</b>:预入职日期当天有排班即正常;台账无四级部门列时按工号回查花名册补齐。</div>
|
||||
<div class="hb-line"><b>不纳入</b>:现职位序列命中 经营系管理序列 / 职能系专业序列 / 门店技师序列;
|
||||
职能类序列且「原单位」=「现单位」;花名册查不到工号(按离职处理)。</div>
|
||||
职能类序列且「原单位」=「现单位」;花名册查不到工号(按离职处理);
|
||||
花名册「一级部门」含「后勤」(如后勤(C))。</div>
|
||||
<div class="hb-line"><b>店长解析</b>:固定路由优先(秒创传媒职能序列 → 刘凤琳 37010004),否则按部门链
|
||||
四级→三级→所属→二级逐级找同名门店下岗位含「店长」的人。</div>
|
||||
<div class="hb-line"><b>输出</b>:名单 <code>排班异常名单_YYYYMMDD_HHMMSS.xlsx</code>(17 列,含店长/处理人、
|
||||
@@ -235,7 +182,6 @@
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<!-- ⑤ 操作区 -->
|
||||
<div class="actions">
|
||||
<el-button type="primary" class="btn-run" :loading="running" @click="run()">
|
||||
{{ running ? '执行中 ' + progress + '%' : '一键执行' }}
|
||||
@@ -248,6 +194,12 @@
|
||||
<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>
|
||||
|
||||
@@ -255,15 +207,13 @@
|
||||
import { ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { usePluginUI } from './usePluginUI'
|
||||
import { PLUGIN_ID } from './api'
|
||||
|
||||
// 字段名必须与 plugin.json.fields.properties 完全一致
|
||||
const DEFAULTS = () => ({
|
||||
save_dir: 'D:\\资料\\人资\\排班异常识别',
|
||||
days: 9,
|
||||
refresh: true,
|
||||
roster_path: '',
|
||||
transfer_ledger: '',
|
||||
preentry_ledger: '',
|
||||
roster_cache: true,
|
||||
push: true,
|
||||
push_group: '数字人沟通群',
|
||||
push_at_all: false,
|
||||
@@ -293,8 +243,14 @@ function validate() {
|
||||
|
||||
function buildPayload(f) {
|
||||
return {
|
||||
...f,
|
||||
save_dir: String(f.save_dir || '').trim(),
|
||||
days: Number(f.days) || 9,
|
||||
roster_cache: !!f.roster_cache,
|
||||
push: !!f.push,
|
||||
push_group: String(f.push_group || '').trim(),
|
||||
push_at_all: !!f.push_at_all,
|
||||
default_manager: String(f.default_manager || '').trim(),
|
||||
check_biometrics: !!f.check_biometrics,
|
||||
bio_username: String(f.bio_username || '').trim(),
|
||||
bio_password: String(f.bio_password || '').trim(),
|
||||
dws_path: String(f.dws_path || '').trim(),
|
||||
@@ -308,59 +264,120 @@ const {
|
||||
run, forceStop,
|
||||
} = usePluginUI({ defaults: DEFAULTS, validate, buildPayload })
|
||||
|
||||
// ---------- 路径选择:调壳子原生对话框(只回路径、不写盘) ----------
|
||||
const picking = ref('')
|
||||
// ---------- 壳子原生对话框(只回路径、不写盘) ----------
|
||||
const picking = ref(false)
|
||||
|
||||
async function pickDirectory(field, title) {
|
||||
const r = await fetch('/api/dialog/directory', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ title, current: form[field] || '' }),
|
||||
})
|
||||
const d = await r.json().catch(() => ({}))
|
||||
if (!r.ok) throw new Error(d.detail || d.error || ('HTTP ' + r.status))
|
||||
if (d.path) form[field] = d.path
|
||||
}
|
||||
|
||||
async function pickDir(field, title) {
|
||||
picking.value = field
|
||||
async function pickDir() {
|
||||
picking.value = true
|
||||
try {
|
||||
await pickDirectory(field, title)
|
||||
const r = await fetch('/api/dialog/directory', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ title: '选择输出目录', current: form.save_dir || '' }),
|
||||
})
|
||||
const d = await r.json().catch(() => ({}))
|
||||
if (!r.ok) throw new Error(d.detail || d.error || ('HTTP ' + r.status))
|
||||
if (d.path) form.save_dir = d.path
|
||||
} catch (e) {
|
||||
ElMessage.warning('打开文件夹选择失败:' + e.message)
|
||||
} finally {
|
||||
picking.value = ''
|
||||
picking.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function pickFile(field, title, filters) {
|
||||
picking.value = field
|
||||
async function pickDwsFile() {
|
||||
picking.value = true
|
||||
try {
|
||||
const r = await fetch('/api/dialog/file', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ title, current: form[field] || '', filters }),
|
||||
body: JSON.stringify({ title: '选择 dws.exe', current: form.dws_path || '', filters: ['exe'] }),
|
||||
})
|
||||
// 老壳子(1.10.x)没有该接口:退化到选文件夹
|
||||
// 老壳子没有该接口:退化到选文件夹
|
||||
if (r.status === 404) {
|
||||
await pickDirectory(field, title)
|
||||
const d = await fetch('/api/dialog/directory', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ title: '选择 dws.exe 所在目录', current: form.dws_path || '' }),
|
||||
}).then((x) => x.json().catch(() => ({}))).catch(() => ({}))
|
||||
if (d.path) form.dws_path = d.path
|
||||
return
|
||||
}
|
||||
const d = await r.json().catch(() => ({}))
|
||||
if (!r.ok) throw new Error(d.detail || ('HTTP ' + r.status))
|
||||
if (d.path) form[field] = d.path
|
||||
if (!r.ok) throw new Error(d.detail || d.error || ('HTTP ' + r.status))
|
||||
if (d.path) form.dws_path = d.path
|
||||
} catch (e) {
|
||||
ElMessage.warning('选择文件失败:' + e.message)
|
||||
} finally {
|
||||
picking.value = ''
|
||||
picking.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- dws 检测:跑一次只检测的插件运行(probe_dws),命中路径回填输入框 ----------
|
||||
const probing = ref(false)
|
||||
|
||||
async function waitRunDone(runId) {
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 500))
|
||||
const r = await fetch('/api/runs/' + encodeURIComponent(runId))
|
||||
if (!r.ok) continue
|
||||
const d = await r.json().catch(() => ({}))
|
||||
if (['done', 'error', 'cancelled'].includes(d.status)) return d
|
||||
}
|
||||
throw new Error('检测超时(运行未结束)')
|
||||
}
|
||||
|
||||
async function probeDws() {
|
||||
probing.value = true
|
||||
try {
|
||||
const r = await fetch('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
plugin_id: PLUGIN_ID,
|
||||
fields: { ...buildPayload(form), probe_dws: true },
|
||||
}),
|
||||
})
|
||||
const d = await r.json().catch(() => ({}))
|
||||
if (!r.ok) throw new Error(d.detail || d.error || ('HTTP ' + r.status))
|
||||
if (!d.run_id) throw new Error('未返回 run_id')
|
||||
const run = await waitRunDone(d.run_id)
|
||||
const path = String((run.result || {}).dws_path || '')
|
||||
if (path) {
|
||||
form.dws_path = path
|
||||
ElMessage.success('dws 可用,已回填路径')
|
||||
} else if (run.status === 'error') {
|
||||
throw new Error(run.error || '检测失败')
|
||||
} else {
|
||||
ElMessage.warning('未检测到 dws:执行时将只出名单、不推送')
|
||||
}
|
||||
} catch (e) {
|
||||
ElMessage.warning('检测失败:' + (e.message || e))
|
||||
} finally {
|
||||
probing.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* 插件差异样式:只使用壳子 token,不写字面色值;左右内边距由壳子提供 */
|
||||
.dir-ctrl { display: flex; align-items: center; gap: var(--space-2); width: 100%; }
|
||||
.dir-ctrl .dir-input { flex: 1 1 auto; min-width: 0; }
|
||||
.dir-ctrl .dir-btn { flex: 0 0 auto; }
|
||||
.span-all { grid-column: 1 / -1; }
|
||||
|
||||
/* 输出目录 + 核查窗口同一行:路径自适应,天数固定窄列 */
|
||||
.grid-2 {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 150px;
|
||||
gap: 0 var(--space-4);
|
||||
}
|
||||
.grid-2 .el-form-item { margin-bottom: 12px; }
|
||||
.grid-2 .el-input-number { width: 100%; }
|
||||
|
||||
.mt-3 { margin-top: var(--space-3); }
|
||||
.is-dim { opacity: .72; }
|
||||
|
||||
@media (max-width: 560px) {
|
||||
.grid-2 { grid-template-columns: minmax(0, 1fr); }
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,431 @@
|
||||
/* ============================================================
|
||||
插件 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; }
|
||||
|
||||
/* ---------- 说明文字 ---------- */
|
||||
.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,
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -4,8 +4,8 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>排班异常识别</title>
|
||||
<script type="module" crossorigin src="/pui/xq0001/assets/index-BDGRb4em.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0001/assets/index-ClszVJW9.css">
|
||||
<script type="module" crossorigin src="/pui/xq0001/assets/index-B_NxccWb.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0001/assets/index-AdMpb9bA.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
||||
@@ -1,121 +0,0 @@
|
||||
:root {
|
||||
--bg: #f5f7fa;
|
||||
--card: #ffffff;
|
||||
--line: #e5e8ef;
|
||||
--text: #1f2430;
|
||||
--muted: #7a8296;
|
||||
--primary: #2f6fed;
|
||||
--primary-hover: #255fd6;
|
||||
--ok: #15a05a;
|
||||
--warn: #b7791f;
|
||||
--err: #d64545;
|
||||
--radius: 10px;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 16px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: 13px/1.6 -apple-system, "Segoe UI", "Microsoft YaHei", "PingFang SC", sans-serif;
|
||||
}
|
||||
|
||||
.wrap { display: flex; flex-direction: column; gap: 12px; max-width: 1020px; margin: 0 auto; }
|
||||
|
||||
.card {
|
||||
background: var(--card);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--radius);
|
||||
padding: 14px 16px;
|
||||
}
|
||||
|
||||
.card-head {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.card-head h2 { margin: 0; font-size: 14px; font-weight: 600; }
|
||||
.saved { color: var(--muted); font-size: 12px; }
|
||||
|
||||
.group { padding: 10px 0; border-top: 1px dashed var(--line); }
|
||||
.group:first-of-type { border-top: 0; padding-top: 0; }
|
||||
.group-title { font-size: 12px; color: var(--muted); margin-bottom: 8px; font-weight: 600; }
|
||||
.muted { color: var(--muted); font-weight: 400; }
|
||||
|
||||
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px 14px; }
|
||||
.field { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
|
||||
.field.span2 { grid-column: span 2; }
|
||||
.label { font-size: 12px; color: #3c4557; }
|
||||
.help { font-size: 11px; color: var(--muted); line-height: 1.5; }
|
||||
|
||||
input[type="text"], input[type="number"], input[type="password"] {
|
||||
width: 100%; height: 32px; padding: 0 10px;
|
||||
border: 1px solid var(--line); border-radius: 6px;
|
||||
background: #fff; color: var(--text); font-size: 13px; outline: none;
|
||||
transition: border-color .15s, box-shadow .15s;
|
||||
}
|
||||
input:focus { border-color: var(--primary); box-shadow: 0 0 0 2px rgba(47,111,237,.12); }
|
||||
|
||||
.switches { display: flex; flex-wrap: wrap; gap: 6px 18px; min-height: 32px; align-items: center; }
|
||||
.switch { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; user-select: none; }
|
||||
.switch input { width: 14px; height: 14px; accent-color: var(--primary); }
|
||||
|
||||
.actions { display: flex; flex-direction: column; gap: 10px; }
|
||||
.run-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
|
||||
.btn {
|
||||
height: 32px; padding: 0 14px; border-radius: 6px; font-size: 13px;
|
||||
border: 1px solid var(--line); background: #fff; color: var(--text); cursor: pointer;
|
||||
transition: all .15s;
|
||||
}
|
||||
.btn:hover { border-color: #cfd6e4; }
|
||||
.btn:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.btn.primary { background: var(--primary); border-color: var(--primary); color: #fff; }
|
||||
.btn.primary:hover { background: var(--primary-hover); }
|
||||
.btn.ghost { color: var(--err); border-color: #f3c9c9; }
|
||||
.btn.ghost:hover { background: #fff5f5; }
|
||||
.btn.link { border: 0; background: none; color: var(--primary); padding: 0 6px; height: 28px; }
|
||||
.btn.link:hover { text-decoration: underline; }
|
||||
.btn.small { font-size: 12px; }
|
||||
|
||||
.status { margin-left: auto; font-size: 12px; color: var(--muted); }
|
||||
.status.running { color: var(--primary); }
|
||||
.status.ok { color: var(--ok); }
|
||||
.status.err { color: var(--err); }
|
||||
|
||||
.progress { display: flex; align-items: center; gap: 10px; }
|
||||
.bar { flex: 1; height: 6px; background: #eef1f7; border-radius: 999px; overflow: hidden; }
|
||||
.bar > i { display: block; height: 100%; width: 0; background: linear-gradient(90deg, #4f8bff, #2f6fed); transition: width .3s; }
|
||||
.pct { width: 42px; text-align: right; color: var(--muted); font-size: 12px; }
|
||||
|
||||
.notice { padding: 8px 12px; border-radius: 6px; font-size: 12.5px; }
|
||||
.notice.warn { background: #fff8e6; color: var(--warn); border: 1px solid #f4e2b8; }
|
||||
.notice.error { background: #fff2f2; color: var(--err); border: 1px solid #f6cfcf; }
|
||||
.notice.ok { background: #f0fbf4; color: var(--ok); border: 1px solid #c3ecd6; }
|
||||
|
||||
.summary { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.chip {
|
||||
display: inline-flex; flex-direction: column; gap: 2px;
|
||||
padding: 6px 10px; border-radius: 8px; background: #f6f8fc; border: 1px solid var(--line);
|
||||
min-width: 88px;
|
||||
}
|
||||
.chip b { font-size: 14px; font-weight: 600; }
|
||||
.chip span { font-size: 11px; color: var(--muted); }
|
||||
.chip.path { flex: 1; min-width: 240px; }
|
||||
.chip.path b { font-size: 12px; font-weight: 500; word-break: break-all; }
|
||||
|
||||
.log {
|
||||
margin: 0; padding: 10px 12px; height: 260px; overflow: auto;
|
||||
background: #0f172a; color: #d6e2f5; border-radius: 8px;
|
||||
font: 12px/1.6 "Cascadia Code", Consolas, "Microsoft YaHei", monospace;
|
||||
white-space: pre-wrap; word-break: break-all;
|
||||
}
|
||||
.log .warn { color: #ffd58a; }
|
||||
.log .err { color: #ff9b9b; }
|
||||
.log .ts { color: #6b7c99; }
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.grid { grid-template-columns: 1fr; }
|
||||
.field.span2 { grid-column: span 1; }
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
流程编排(替代影刀版 4 个脚本的人工串行,WPS COM 替代人工 Ctrl+S 刷新公式):
|
||||
1) 花名册确保:源表缺失或超过 TTL(15 分钟)时自动从 HR 接口导出,新鲜度内复用;
|
||||
导出后补全职位序列:所属单位「灸生生事业部」且职位序列为空的员工按岗位映射回填花名册;
|
||||
2) 筛选复制:按类别 include/exclude 过滤花名册数据写入各目标表(F列工号强制文本);
|
||||
3) WPS/Excel 后台重算公式(替代人工打开文件 Ctrl+S,供调度读取公式缓存值);
|
||||
4) 三阶段名额调度:更新「手动维护-在参名单」+ 精细更新「变更清单」+ 备份;
|
||||
@@ -35,7 +36,7 @@ class EmployerInsurancePlugin(ScenePlugin):
|
||||
|
||||
id = "xq0002"
|
||||
name = "雇主险增减操作"
|
||||
version = "1.0.20"
|
||||
version = "1.0.21"
|
||||
description = ("雇主险名额调度全流程:花名册导出→筛选复制→WPS/Excel 后台取消筛选并重算公式→"
|
||||
"三阶段名额调度→更新在参名单与变更清单→生成增员/减员导入文件"
|
||||
"(可选自动导入 HR 系统)→钉钉群推送汇总与导入异常名单,"
|
||||
@@ -101,6 +102,16 @@ class EmployerInsurancePlugin(ScenePlugin):
|
||||
ctx.log(f"花名册准备失败:{e}", "WARN")
|
||||
ctx.progress(10)
|
||||
|
||||
# ---- 步骤1.5:职位序列补全(所属单位=灸生生事业部 且 职位序列为空 → 按岗位映射回填花名册) ----
|
||||
try:
|
||||
_, unmatched = roster_filter.fill_post_sequence(roster_path)
|
||||
if unmatched:
|
||||
notes.append(f"花名册职位序列补全:以下「{config.POST_SEQ_FILL_UNIT}」员工职位序列为空"
|
||||
f"且岗位不在映射表内,请核对:{';'.join(unmatched)}")
|
||||
except Exception as e:
|
||||
notes.append(f"花名册职位序列补全失败(不影响后续流程):{e}")
|
||||
ctx.log(f"花名册职位序列补全失败:{e}", "WARN")
|
||||
|
||||
# ---- 步骤2:筛选复制(10% ~ 45%) ----
|
||||
ok_categories = []
|
||||
n = len(categories)
|
||||
|
||||
@@ -73,6 +73,27 @@ EXCLUDE_NAME_KEYWORDS = ["虚拟", "人资", "测试"] # 姓名(N列)含
|
||||
# 采用关键字组合而非精确职位名,兼容括号/全角差异(后勤(C) / 后勤(C) / 后勤C 归一后均命中)
|
||||
EXCLUDE_POST_KEYWORDS = ["后勤", "C"]
|
||||
|
||||
# 职位序列补全规则(导出花名册后、筛选复制前执行):
|
||||
# 所属单位 = 灸生生事业部 且 职位序列(J列)为空 时,按岗位(I列)映射写入职位序列。
|
||||
# 岗位文本先做 NFKC 归一(全角括号/空格),与映射键归一后精确匹配。
|
||||
POST_SEQ_COL = 8 # J列 职位序列(B~O 切片 0-based 索引)
|
||||
POST_SEQ_FILL_UNIT = "灸生生事业部"
|
||||
POST_SEQ_FILL_MAP = {
|
||||
"店长(灸生生)": "灸生生经营管理序列",
|
||||
"管理顾问(灸生生)": "灸生生经营管理序列",
|
||||
"运营经理(灸生生)": "灸生生职能序列",
|
||||
"营销经理(灸生生)": "灸生生职能序列",
|
||||
"后勤保障总监(灸生生)": "灸生生职能序列",
|
||||
"线上运营经理(灸生生)": "灸生生职能序列",
|
||||
"香疗师(灸生生)": "灸生生门店技师序列",
|
||||
"工厂厂长(灸生生)": "灸生生职能序列",
|
||||
"事业部总经理(灸生生)": "灸生生职能序列",
|
||||
"商学院院长(灸生生)": "灸生生职能序列",
|
||||
"灸疗师(灸生生)": "灸生生门店技师序列",
|
||||
"培训经理(灸生生)": "灸生生职能序列",
|
||||
"高级人行专员(灸生生)": "灸生生职能序列",
|
||||
}
|
||||
|
||||
# 源表/目标表格式规范(共享「37du花名册导出」输出统一格式)
|
||||
SOURCE_HEADER_MARK = "所属单位" # 源表表头定位标记(B列)
|
||||
EXPORT_TEMPLATE = "雇主险增减员导出模板" # 雇主险源表使用的自定义导出模板
|
||||
|
||||
@@ -19,6 +19,7 @@ from ..config import (
|
||||
TARGET_HEADER_ROW, DATA_COLUMNS, CODE_COL, ID_COL, JOIN_DATE_COL, NAME_COL, POST_COL,
|
||||
EXCLUDE_REGIONS, EXCLUDE_NAME_KEYWORDS, EXCLUDE_POST_KEYWORDS, category_folder,
|
||||
employee_file, find_target_file, to_text, parse_join_date, ref_date, CACHE_DIR,
|
||||
POST_SEQ_COL, POST_SEQ_FILL_UNIT, POST_SEQ_FILL_MAP,
|
||||
)
|
||||
from ..data.roster_export_api import export_roster
|
||||
|
||||
@@ -48,6 +49,60 @@ def _read_source(employee_path):
|
||||
return data[data.iloc[:, 0].notna()]
|
||||
|
||||
|
||||
def fill_post_sequence(employee_path=""):
|
||||
"""导出后补全职位序列:所属单位=灸生生事业部 且 职位序列为空 的行按岗位映射回填。
|
||||
|
||||
直接改写花名册源表(仅在实际补全时保存),供后续筛选复制/调度使用。
|
||||
|
||||
Returns:
|
||||
(补全行数, 未匹配岗位的明细列表)
|
||||
"""
|
||||
path = os.path.abspath(employee_path or employee_file())
|
||||
if not os.path.exists(path):
|
||||
raise FileNotFoundError(f"源表不存在:{path}")
|
||||
|
||||
wb = load_workbook(path)
|
||||
ws = wb.worksheets[0]
|
||||
header_row = None
|
||||
for r in range(1, min(ws.max_row, 10) + 1):
|
||||
if str(ws.cell(row=r, column=2).value or "").strip() == SOURCE_HEADER_MARK:
|
||||
header_row = r
|
||||
break
|
||||
if header_row is None:
|
||||
raise ValueError(f"源表未找到表头行(B 列应为「{SOURCE_HEADER_MARK}」)")
|
||||
|
||||
unit_col, post_col, seq_col = 2, 2 + POST_COL, 2 + POST_SEQ_COL
|
||||
name_col, code_col = 2 + NAME_COL, 2 + CODE_COL
|
||||
mapping = {_norm_post(k): v for k, v in POST_SEQ_FILL_MAP.items()}
|
||||
|
||||
filled, unmatched = 0, []
|
||||
for r in range(header_row + 1, ws.max_row + 1):
|
||||
unit = str(ws.cell(row=r, column=unit_col).value or "").strip()
|
||||
if unit != POST_SEQ_FILL_UNIT:
|
||||
continue
|
||||
seq_cell = ws.cell(row=r, column=seq_col)
|
||||
if str(seq_cell.value or "").strip():
|
||||
continue
|
||||
post = ws.cell(row=r, column=post_col).value
|
||||
target = mapping.get(_norm_post(post))
|
||||
if target:
|
||||
seq_cell.value = target
|
||||
filled += 1
|
||||
else:
|
||||
name = to_text(ws.cell(row=r, column=name_col).value) or ""
|
||||
code = to_text(ws.cell(row=r, column=code_col).value) or ""
|
||||
unmatched.append(f"{name}({code}),岗位:{str(post or '').strip() or '空'}")
|
||||
|
||||
if filled:
|
||||
wb.save(path)
|
||||
logger.info("职位序列补全:所属单位「%s」且职位序列为空的行,补全 %d 行,未匹配 %d 行",
|
||||
POST_SEQ_FILL_UNIT, filled, len(unmatched))
|
||||
if unmatched:
|
||||
logger.warning("职位序列补全:以下行岗位不在映射表内,需人工确认:%s",
|
||||
";".join(unmatched))
|
||||
return filled, unmatched
|
||||
|
||||
|
||||
def filter_and_copy_roster(category, employee_path="", target_file=None):
|
||||
"""从员工花名册按类别筛选数据,复制到该类别的雇主险变更记录表(仅复制,不校验)。
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0002",
|
||||
"name": "雇主险增减操作",
|
||||
"version": "1.0.20",
|
||||
"version": "1.0.21",
|
||||
"description": "雇主险名额调度全流程:花名册导出→筛选复制→WPS/Excel 后台取消筛选并重算公式→三阶段名额调度→更新在参名单与变更清单→生成增员/减员导入文件(可选自动导入 HR 系统)→钉钉群推送汇总与导入异常名单,替代人工取消筛选与 Ctrl+S 刷新公式、人工上传导入环节",
|
||||
"category": "人事",
|
||||
"icon": "",
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0006 EHR系统周考勤异常处理 插件入口。
|
||||
|
||||
流程编排(由影刀版 attendance_abnormal.py 移植,登录态改由底座注入):
|
||||
1) 会话校验:底座注入 HR session → getCurUserInfo 校验(失效提示重新登录);
|
||||
2) 拉取查询月份(默认 1 号查上月,否则当月)全部「未调整」考勤异常;
|
||||
3) 导出 Excel 底稿(试算模式只做这一步);
|
||||
4) 自动确认:范围=查询范围内全部数据(分批调用确认接口);
|
||||
5) 钉钉推送(口径与影刀版一致):仅推送上周职能序列 + 推送范围单位
|
||||
(默认总办/集团财经中心/金色湖畔事业部,部门路径不含「大区」)的严重异常给当事人,
|
||||
并把条数汇总推送到群机器人。
|
||||
"""
|
||||
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
|
||||
|
||||
from . import config
|
||||
from .data import hr_api
|
||||
from .data.hr_api import HRSessionExpiredError
|
||||
from .logic import attendance_rules as rules
|
||||
from .report import attendance_report
|
||||
from .report import dingtalk_push
|
||||
|
||||
|
||||
def _as_bool(value, default=False):
|
||||
"""字段值转布尔(兼容 JSON 布尔与 "true"/"false" 字符串)。"""
|
||||
if value is None or value == "":
|
||||
return default
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
return str(value).strip().lower() in ("1", "true", "yes", "on")
|
||||
|
||||
|
||||
def _split_units(value):
|
||||
"""把「总办, 集团财经中心」这类多值文本拆成单位列表(支持中英文逗号/顿号/分号)。"""
|
||||
raw = str(value or "").strip()
|
||||
if not raw:
|
||||
return []
|
||||
for sep in (",", "、", ";", ";", "|", "\n"):
|
||||
raw = raw.replace(sep, ",")
|
||||
return [s.strip() for s in raw.split(",") if s.strip()]
|
||||
|
||||
|
||||
class WeeklyAttendanceAbnormalPlugin(ScenePlugin):
|
||||
"""EHR系统周考勤异常处理(需求 XQ0006)。"""
|
||||
|
||||
id = "xq0006"
|
||||
name = "EHR系统周考勤异常处理"
|
||||
version = "1.2.0"
|
||||
description = ("拉取查询月份未调整考勤异常并导出 Excel,整月全量自动确认;"
|
||||
"上周职能序列及推送范围单位(默认总办/集团财经中心/金色湖畔事业部/"
|
||||
"集团管理中心/集团营建中心/金色印象事业部,不含大区)的严重异常按人合并推送;"
|
||||
"支持试算模式(只出表、不确认不推送)。")
|
||||
platform = "hr"
|
||||
uses_month = True
|
||||
capabilities = ["xq0006"]
|
||||
permissions = {"platforms": ["hr"]}
|
||||
fields = {
|
||||
"ref_month": {
|
||||
"type": "string", "title": "执行月份",
|
||||
"default": "",
|
||||
"description": "留空=本月(1 号查上月);格式 YYYY-MM(如 2026-11)",
|
||||
},
|
||||
"save_dir": {
|
||||
"type": "string", "title": "输出目录",
|
||||
"default": config.DEFAULT_SAVE_DIR,
|
||||
"description": "考勤异常 Excel 底稿存放目录",
|
||||
},
|
||||
"dry_run": {
|
||||
"type": "boolean", "title": "试算模式", "default": False,
|
||||
"description": "开启后只导出 Excel 并统计,不自动确认、不发送任何钉钉消息",
|
||||
},
|
||||
"auto_confirm": {
|
||||
"type": "boolean", "title": "自动确认", "default": True,
|
||||
"description": "开启后对查询范围内全部异常调用确认接口(分批提交);试算模式下强制不确认",
|
||||
},
|
||||
"push_enabled": {
|
||||
"type": "boolean", "title": "钉钉推送", "default": True,
|
||||
"description": "开启后推送上周职能序列及推送范围单位的严重异常给当事人,并推送条数汇总到钉钉群;试算模式下强制不推送",
|
||||
},
|
||||
"push_units": {
|
||||
"type": "string", "title": "推送范围单位",
|
||||
"default": "总办,集团财经中心,金色湖畔事业部,集团管理中心,集团营建中心,金色印象事业部",
|
||||
"description": "除职能序列外,这些所属单位也推送(逗号/顿号分隔);留空=只推职能序列",
|
||||
},
|
||||
"push_exclude_keyword": {
|
||||
"type": "string", "title": "推送排除关键字", "default": "大区",
|
||||
"description": "部门路径包含该关键字则不推送;留空表示不按部门路径排除",
|
||||
},
|
||||
"dingtalk_webhook": {
|
||||
"type": "string", "title": "钉钉 Webhook", "default": "",
|
||||
"description": "留空使用内置默认机器人;需要发到其他群时填写完整 webhook 地址",
|
||||
},
|
||||
"dingtalk_secret": {
|
||||
"type": "string", "title": "钉钉加签密钥", "default": "",
|
||||
"description": "机器人启用加签安全设置时填写,留空表示不加签",
|
||||
},
|
||||
}
|
||||
|
||||
def run(self, fields: dict, ctx):
|
||||
try:
|
||||
return self._run(fields, ctx)
|
||||
except HRSessionExpiredError as e:
|
||||
ctx.log(f"HR 登录态已失效,请重新登录后再执行:{e}", "ERROR")
|
||||
raise RuntimeError("HR 登录态已失效,请重新登录 HR 后再执行") from e
|
||||
|
||||
def _run(self, fields: dict, ctx):
|
||||
# ---- 注入运行上下文 ----
|
||||
config.set_log(ctx.log)
|
||||
config.set_progress(ctx.progress)
|
||||
config.set_session(ctx.get_session("hr"))
|
||||
session = config.require_session()
|
||||
save_dir = (fields.get("save_dir") or "").strip() or config.DEFAULT_SAVE_DIR
|
||||
auto_confirm = _as_bool(fields.get("auto_confirm"), True)
|
||||
push_enabled = _as_bool(fields.get("push_enabled"), True)
|
||||
dry_run = _as_bool(fields.get("dry_run"), config.DEFAULT_DRY_RUN)
|
||||
if dry_run: # 试算:只导出,不产生任何写入/外发动作
|
||||
auto_confirm, push_enabled = False, False
|
||||
push_units = _split_units(fields.get("push_units"))
|
||||
if fields.get("push_units") is None:
|
||||
push_units = config.DEFAULT_PUSH_EXTRA_UNITS
|
||||
push_exclude = (fields.get("push_exclude_keyword") or "").strip()
|
||||
if fields.get("push_exclude_keyword") is None:
|
||||
push_exclude = config.DEFAULT_PUSH_EXCLUDE_KEYWORD
|
||||
webhook = (fields.get("dingtalk_webhook") or "").strip()
|
||||
secret = (fields.get("dingtalk_secret") or "").strip()
|
||||
|
||||
try:
|
||||
month = rules.resolve_month(fields.get("ref_month"))
|
||||
except ValueError as e:
|
||||
raise RuntimeError(str(e)) from e
|
||||
begin, end = rules.month_range(month)
|
||||
ctx.log(f"===== 周考勤异常处理启动:{month} 整月({begin} ~ {end}),"
|
||||
f"试算模式={'是(只导出)' if dry_run else '否'},"
|
||||
f"自动确认={'开(全量)' if auto_confirm else '关'},"
|
||||
f"钉钉推送={'开' if push_enabled else '关'} =====", "INFO")
|
||||
|
||||
# ---- 步骤1:会话校验 ----
|
||||
ctx.progress(5)
|
||||
user_id, treecode = hr_api.validate_session(session)
|
||||
config.set_user_id(user_id)
|
||||
ctx.progress(8)
|
||||
|
||||
# ---- 步骤2:拉取整月考勤异常 ----
|
||||
data = hr_api.fetch_all_attendance_abnormal(session, user_id, treecode, begin, end)
|
||||
ctx.log(f"考勤异常共获取 {len(data)} 条(调整状态:{config.IS_ADJUSTED or '所有'})", "INFO")
|
||||
if not data:
|
||||
ctx.log(f"{month} 无考勤异常数据,跳过导出与推送", "INFO")
|
||||
ctx.progress(100)
|
||||
return {
|
||||
"summary": f"{month} 无考勤异常数据,未导出、未确认、未推送",
|
||||
"detail": {"total": 0},
|
||||
"path": "",
|
||||
"save_dir": save_dir,
|
||||
}
|
||||
ctx.progress(30)
|
||||
|
||||
# ---- 步骤3:导出 Excel 底稿 ----
|
||||
path = attendance_report.export_excel(data, save_dir, month, dry_run=dry_run)
|
||||
ctx.progress(35)
|
||||
|
||||
# ---- 步骤4:自动确认(整月全量) ----
|
||||
split = rules.split_data(data, push_units, push_exclude)
|
||||
auto_count = len([it for it in data if it.get("abnormal_id")])
|
||||
confirmed_count, failed_ids = 0, []
|
||||
if auto_confirm:
|
||||
ctx.log(f"自动确认(整月全量){auto_count} 条 …", "INFO")
|
||||
_, confirmed_count, failed_ids = hr_api.auto_confirm_all(
|
||||
session, data,
|
||||
on_progress=lambda done, total: ctx.progress(
|
||||
35 + int(35 * done / max(total, 1))))
|
||||
else:
|
||||
if dry_run:
|
||||
ctx.log(f"试算模式:仅统计待确认 {auto_count} 条,未执行确认", "INFO")
|
||||
else:
|
||||
ctx.log(f"自动确认未启用,仅统计待确认 {auto_count} 条,未执行确认", "WARN")
|
||||
ctx.progress(72)
|
||||
|
||||
# ---- 步骤5:钉钉推送(只通知,不改口径) ----
|
||||
messages = rules.group_messages(split["func_list"])
|
||||
push_result = {"sent": 0, "failed": []}
|
||||
if push_enabled:
|
||||
if messages:
|
||||
push_result = dingtalk_push.push_person_messages(
|
||||
messages,
|
||||
on_progress=lambda done, total: ctx.progress(
|
||||
72 + int(15 * done / max(total, 1))))
|
||||
else:
|
||||
ctx.log("无需推送的异常,跳过当事人钉钉通知", "INFO")
|
||||
else:
|
||||
if dry_run:
|
||||
ctx.log("试算模式:未发送任何钉钉消息", "INFO")
|
||||
else:
|
||||
ctx.log("钉钉推送未启用,未发送任何钉钉消息", "INFO")
|
||||
ctx.progress(90)
|
||||
|
||||
# ---- 步骤6:汇总日志 + 群条数汇总 ----
|
||||
group_message = rules.build_group_summary(
|
||||
len(data), auto_count, confirmed_count, len(split["non_func_list"]),
|
||||
len(split["func_list"]), len(messages), len(split["other_list"]),
|
||||
month, begin, end)
|
||||
group_sent = False
|
||||
if push_enabled:
|
||||
group_sent = dingtalk_push.send_group_text(
|
||||
group_message, webhook=webhook, secret=secret)
|
||||
|
||||
ctx.log("=" * 60, "INFO")
|
||||
ctx.log(group_message, "INFO")
|
||||
ctx.log(f"导出文件:{path}", "INFO")
|
||||
if failed_ids:
|
||||
ctx.log(f"自动确认失败 {len(failed_ids)} 条:{','.join(str(i) for i in failed_ids[:20])}", "WARN")
|
||||
if push_result["failed"]:
|
||||
ctx.log(f"当事人推送失败 {len(push_result['failed'])} 人:"
|
||||
f"{';'.join(push_result['failed'][:10])}", "WARN")
|
||||
ctx.log("=" * 60, "INFO")
|
||||
|
||||
counts = {
|
||||
"total": len(data),
|
||||
"auto_confirm_total": auto_count,
|
||||
"confirmed": confirmed_count,
|
||||
"confirm_failed": len(failed_ids),
|
||||
"func_lastweek": len(split["func_list"]),
|
||||
"non_func_lastweek": len(split["non_func_list"]),
|
||||
"other": len(split["other_list"]),
|
||||
"push_people": len(messages),
|
||||
"push_sent": push_result["sent"],
|
||||
"push_failed": len(push_result["failed"]),
|
||||
"group_pushed": group_sent,
|
||||
}
|
||||
summary = f"{month} 周考勤异常处理完成:共 {counts['total']} 条"
|
||||
if dry_run:
|
||||
summary += ",试算模式(仅导出,未确认、未推送)"
|
||||
elif auto_confirm:
|
||||
summary += f",自动确认 {confirmed_count}/{auto_count} 条"
|
||||
else:
|
||||
summary += ",自动确认已关闭"
|
||||
if push_enabled:
|
||||
summary += f",推送 {counts['push_people']} 人(成功 {counts['push_sent']})"
|
||||
summary += f";导出:{path}"
|
||||
ctx.progress(100)
|
||||
return {"summary": summary, "detail": counts, "path": path, "save_dir": save_dir}
|
||||
|
||||
|
||||
PLUGINS.append(WeeklyAttendanceAbnormalPlugin())
|
||||
@@ -0,0 +1,52 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0006 EHR系统周考勤异常处理 插件打包脚本(统一规范版)。
|
||||
|
||||
打包产物统一输出到仓库根 dist-plugin/<id>_v<版本>.zip(目录不入库),
|
||||
zip 根含 plugin.json,可被 agent_cli publish 直接发布。详见 docs/插件/插件开发规范.md 与 docs/插件/发版规范.md。
|
||||
|
||||
用法(任意 cwd 均可):
|
||||
d:\\work\\code\\37duAutomation\\.venv\\Scripts\\python.exe "plugins\\XQ0001-0100\\XQ0006 EHR系统周考勤异常处理\\_pack.py"
|
||||
随后发布(测试通道,转正由人工执行):
|
||||
.venv\\Scripts\\python.exe tools/agent_cli.py publish \
|
||||
dist-plugin\\xq0006_v<版本>.zip --id xq0006 --version <版本>
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
# 仓库根 = plugins/XQ0001-0100/<插件目录>/ 的 parents[2],统一出包位置
|
||||
_REPO_ROOT = _HERE.parents[2]
|
||||
_OUT_DIR = _REPO_ROOT / "dist-plugin"
|
||||
|
||||
# 排除项:打包脚本自身 / 前端源码与依赖 / 缓存 / 调试文件(_ 前缀为私有辅助)
|
||||
_EXCLUDE_DIRS = {"ui-src", "__pycache__", ".git", ".idea", "debug", ".sessions"}
|
||||
_EXCLUDE_FILES = {"_pack.py"}
|
||||
_EXCLUDE_SUFFIXES = (".pyc", ".pyo")
|
||||
|
||||
|
||||
def main():
|
||||
manifest = json.loads((_HERE / "plugin.json").read_text(encoding="utf-8"))
|
||||
pid = manifest["id"]
|
||||
ver = manifest["version"]
|
||||
# 带 UI 插件必须已构建前端产物(ui/ 由底座 /pui/<id>/ 托管)
|
||||
if manifest.get("ui") and not (_HERE / "ui" / "index.html").is_file():
|
||||
sys.exit(f"插件 {pid} 声明 ui=true 但缺少 ui/index.html:请先在 ui-src 下执行 npm install && npm run build")
|
||||
_OUT_DIR.mkdir(exist_ok=True)
|
||||
out = _OUT_DIR / f"{pid}_v{ver}.zip"
|
||||
count = 0
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for p in sorted(_HERE.rglob("*")):
|
||||
rel = p.relative_to(_HERE)
|
||||
if set(rel.parts) & _EXCLUDE_DIRS or p.name in _EXCLUDE_FILES \
|
||||
or p.suffix in _EXCLUDE_SUFFIXES:
|
||||
continue
|
||||
if p.is_file():
|
||||
zf.write(p, str(rel))
|
||||
count += 1
|
||||
print(f"已打包: {out}({count} 个文件,{out.stat().st_size / 1024:.0f} KB)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,196 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0006 EHR系统周考勤异常处理 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:只依赖 Python 标准库 / 第三方库(requests、pandas)/ 底座注入的 RunContext。
|
||||
所有业务模块统一经 config.logger 输出日志、config.require_session()/require_user_id() 取登录态。
|
||||
登录态由底座注入(hr 平台),插件不自行读 cookies 文件、不做自动补登。
|
||||
"""
|
||||
import os
|
||||
|
||||
# ==================== 共享目录(与影刀版同路径) ====================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
|
||||
# ==================== HR 系统接口 ====================
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
ATTENDANCE_ABNORMAL_URL = f"{HR_BASE_URL}/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
# 考勤异常确认/调整接口(type=1 自动确认异常)
|
||||
ATTENDANCE_ADJUST_URL = f"{HR_BASE_URL}/RedseaPlatform/abnormalAdjust/KqCountAbnormal.mc"
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# ==================== 输出与口径常量(与影刀版一致) ====================
|
||||
DEFAULT_SAVE_DIR = r"D:\资料\人资\考勤异常"
|
||||
|
||||
# 英文字段 → 中文字段映射(仅导出这些列)
|
||||
COL_MAP = {
|
||||
"base_code": "工号",
|
||||
"STAFF_NAME": "姓名",
|
||||
"sex": "性别",
|
||||
"age": "年龄",
|
||||
"ORG_FULL_PATH": "部门路径",
|
||||
"BELONG_UNIT_ORG_NAME": "所属单位",
|
||||
"DEPT_ORG_NAME": "部门",
|
||||
"POST_ORG_NAME": "岗位",
|
||||
"join_date": "入职日期",
|
||||
"work_day": "日期",
|
||||
"bc_name": "班次",
|
||||
"abnormal": "异常类型",
|
||||
"is_adjusted": "处理状态",
|
||||
"actual_begin_time": "开始时间",
|
||||
"actual_end_time": "结束时间",
|
||||
"abnormal_minute": "时长(分)",
|
||||
"add_reason": "补签原因",
|
||||
"operateName": "操作人",
|
||||
"operateTime": "操作时间",
|
||||
}
|
||||
|
||||
# 导出列顺序(「班段」由 begin_time~end_time 合成)
|
||||
SHOW_ORDER = [
|
||||
"工号", "姓名", "性别", "年龄", "部门路径", "所属单位", "部门", "岗位",
|
||||
"入职日期", "日期", "班次", "班段", "异常类型", "处理状态", "处理方式",
|
||||
"开始时间", "结束时间", "时长(分)", "补签原因", "操作人", "操作时间",
|
||||
]
|
||||
|
||||
# 处理状态 is_adjusted 编码 → 中文(0=未调整、1=补签调整、2=确认异常、3=正常调整)
|
||||
STATUS_MAP = {
|
||||
"0": "未调整",
|
||||
"1": "补签调整",
|
||||
"2": "确认异常",
|
||||
"3": "正常调整",
|
||||
}
|
||||
|
||||
# 考勤异常调整状态过滤:0=未调整、1=补签调整、2=确认异常、3=正常调整、空=所有
|
||||
IS_ADJUSTED = "0"
|
||||
|
||||
# 自动确认:自 2026-11 起范围扩展为「查询范围内全部数据」(不再只限轻微异常)
|
||||
DEFAULT_AUTO_CONFIRM = True
|
||||
# 自动确认分批条数(接口按 abnormalIds 逗号串提交,分批降低单次请求体积)
|
||||
CONFIRM_BATCH_SIZE = 200
|
||||
|
||||
# 钉钉推送总开关(与影刀版一致,默认启用;通知内容/推送规则保持不变)
|
||||
DEFAULT_PUSH_ENABLED = True
|
||||
|
||||
# 试算模式:只导出 Excel,不做自动确认、不发任何钉钉消息
|
||||
DEFAULT_DRY_RUN = False
|
||||
|
||||
# 推送范围扩充:除职能序列外,这些所属单位也推送(部门路径不含关键字,界面可覆盖)
|
||||
DEFAULT_PUSH_EXTRA_UNITS = ["总办", "集团财经中心", "金色湖畔事业部",
|
||||
"集团管理中心", "集团营建中心", "金色印象事业部"]
|
||||
DEFAULT_PUSH_EXCLUDE_KEYWORD = "大区"
|
||||
|
||||
# ==================== 钉钉推送(企业内部应用工作通知 + 群机器人) ====================
|
||||
# 个人通知:企业内部应用「工作通知」(按工号精确匹配接收人),与 XQ0012/XQ0052 同一应用。
|
||||
DINGTALK_APP_KEY = 'dingc1fnokzybr3u5bbl'
|
||||
DINGTALK_APP_SECRET = ('AOKyKOc0byGpQkzd20_GqK9-G1LI-Py2qlNeOiCQpR2TnBtzuJCpBuldIqRWX58A')
|
||||
DINGTALK_AGENT_ID = '4974749954'
|
||||
DINGTALK_TOKEN_V1_URL = "https://api.dingtalk.com/v1.0/oauth2/accessToken"
|
||||
DINGTALK_TOKEN_OAPI_URL = "https://oapi.dingtalk.com/gettoken"
|
||||
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"
|
||||
|
||||
# 群汇总:群机器人 Webhook(与 XQ0003/XQ0004 同一套默认机器人)
|
||||
DEFAULT_WEBHOOK = ('https://oapi.dingtalk.com/robot/send?access_token='
|
||||
'65dd3f38dea12d2419743aad62ed25f5544ae1ff2ff7d2f667682e0dc912ff6e')
|
||||
DEFAULT_SECRET = ""
|
||||
DINGTALK_GROUP_TITLE = "考勤异常处理汇总"
|
||||
|
||||
HTTP_TIMEOUT = 20
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
_progress = None
|
||||
_session = None
|
||||
_user_id = ""
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
"""注入 ctx.log(RunContext.log),各模块经 log()/logger 输出。"""
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:保留影刀版 logger.info(...) 调用点,统一转发到 ctx.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
|
||||
|
||||
def set_progress(fn):
|
||||
global _progress
|
||||
_progress = fn
|
||||
|
||||
|
||||
def progress(pct):
|
||||
if _progress:
|
||||
try:
|
||||
_progress(int(pct))
|
||||
except Exception: # noqa: BLE001 - 进度上报失败不影响主流程
|
||||
pass
|
||||
|
||||
|
||||
def set_session(session):
|
||||
global _session
|
||||
_session = session
|
||||
|
||||
|
||||
def get_session():
|
||||
return _session
|
||||
|
||||
|
||||
def require_session():
|
||||
"""取插件运行期注入的 HR session(缺失抛错,提示先在插件界面登录 HR)。"""
|
||||
if _session is None:
|
||||
raise RuntimeError("未注入 HR 登录态,请先在插件界面完成 HR 登录")
|
||||
return _session
|
||||
|
||||
|
||||
def set_user_id(uid):
|
||||
global _user_id
|
||||
_user_id = str(uid or "")
|
||||
|
||||
|
||||
def get_user_id():
|
||||
return _user_id
|
||||
|
||||
|
||||
def require_user_id():
|
||||
uid = _user_id
|
||||
if not uid:
|
||||
raise RuntimeError("获取当前用户 userId 失败,请重新完成 HR 登录")
|
||||
return uid
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0006 数据层:HR 考勤异常查询与确认接口。"""
|
||||
@@ -0,0 +1,165 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0006 数据层:HR 考勤异常查询与确认接口(纯接口,无浏览器)。"""
|
||||
import time
|
||||
|
||||
from .. import config
|
||||
|
||||
IS_ADJUSTED = config.IS_ADJUSTED
|
||||
PAGE_MAX_SIZE = config.PAGE_MAX_SIZE
|
||||
MAX_ATTEMPTS = 3
|
||||
RETRY_WAIT = 1.0
|
||||
|
||||
|
||||
class HRSessionExpiredError(RuntimeError):
|
||||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def hr_request_json(session, method, url, params, label, timeout=config.HTTP_TIMEOUT):
|
||||
"""POST/GET 请求并校验返回 JSON;失效抛 HRSessionExpiredError。"""
|
||||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
text = resp.text
|
||||
if not text or not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON),请重新登录 HR 后重试")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def fetch_cur_user_info(session):
|
||||
return hr_request_json(session, "POST", config.GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
|
||||
|
||||
def validate_session(session):
|
||||
"""校验底座注入的 HR 会话,返回 (user_id, treecode);会话无效抛错提示重新登录。"""
|
||||
info = fetch_cur_user_info(session)
|
||||
user_id = str(info.get("userId", "") or "")
|
||||
treecode = str(info.get("rootId", "") or "")
|
||||
if not user_id or not treecode:
|
||||
raise RuntimeError(f"员工基础信息接口未返回 userId/rootId:{info}")
|
||||
config.logger.info("HR 会话校验通过,user_id=%s,treecode=%s", user_id, treecode)
|
||||
return user_id, treecode
|
||||
|
||||
|
||||
def fetch_attendance_abnormal_page(session, user_id, treecode, begin_date, end_date,
|
||||
page_no=1, page_size=PAGE_MAX_SIZE,
|
||||
is_adjusted=IS_ADJUSTED, abnormal_type=""):
|
||||
params = {
|
||||
"treecode": treecode,
|
||||
"user_id": user_id,
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"sqlId": "kq_count_abnormal_Select",
|
||||
"redapiId": "rf_p_kq_count_abnormal_Select",
|
||||
"treeCodeList": "",
|
||||
"abnormal_type": abnormal_type,
|
||||
"base_code": "",
|
||||
"join_date": "",
|
||||
"join_date_end": end_date,
|
||||
"person_status": "",
|
||||
"staff_id": "",
|
||||
"post_no": "",
|
||||
"post_type": "1",
|
||||
"period_order": "",
|
||||
"identity_test": "",
|
||||
"identity": "",
|
||||
"sex": "",
|
||||
"age": "",
|
||||
"age_end": "",
|
||||
"start_operat_time": "",
|
||||
"end_operat_time": "",
|
||||
"operator_username": "",
|
||||
"operator_userid": "",
|
||||
"is_adjusted": is_adjusted,
|
||||
"begin_date": begin_date,
|
||||
"end_date": end_date,
|
||||
"STAFF_NAME": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc",
|
||||
"sortName": "work_day",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", config.ATTENDANCE_ABNORMAL_URL, params, "考勤异常")
|
||||
|
||||
|
||||
def fetch_all_attendance_abnormal(session, user_id, treecode, begin_date, end_date,
|
||||
is_adjusted=IS_ADJUSTED, abnormal_type=""):
|
||||
"""分页拉取全部考勤异常。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
data = fetch_attendance_abnormal_page(
|
||||
session, user_id, treecode, begin_date, end_date,
|
||||
page_no, PAGE_MAX_SIZE, is_adjusted, abnormal_type)
|
||||
if str(data.get("state")) != "1":
|
||||
raise RuntimeError(f"考勤异常第 {page_no} 页请求失败:{data.get('meg')}")
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = int(data.get("pageCount", 0) or 0)
|
||||
config.logger.info("考勤异常已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
def adjust_abnormal(session, abnormal_ids, type_code=1):
|
||||
"""确认/调整考勤异常单据(type=1 自动确认异常)。"""
|
||||
if isinstance(abnormal_ids, (list, tuple)):
|
||||
ids = ",".join(str(i) for i in abnormal_ids)
|
||||
else:
|
||||
ids = str(abnormal_ids)
|
||||
params = {"abnormalIds": ids, "type": type_code}
|
||||
return hr_request_json(session, "POST", config.ATTENDANCE_ADJUST_URL, params, "考勤异常确认")
|
||||
|
||||
|
||||
def _confirm_batch(session, ids):
|
||||
"""确认一批异常(最多重试 3 次),失败抛错。"""
|
||||
last_err = None
|
||||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
result = adjust_abnormal(session, ids)
|
||||
if str(result.get("state")) == "1":
|
||||
return True
|
||||
last_err = result.get("meg") or result
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e: # noqa: BLE001 - 网络/接口异常统一重试
|
||||
last_err = e
|
||||
config.logger.warning("考勤异常自动确认第 %d/%d 次失败:%s",
|
||||
attempt, MAX_ATTEMPTS, last_err)
|
||||
if attempt < MAX_ATTEMPTS:
|
||||
time.sleep(RETRY_WAIT * attempt)
|
||||
raise RuntimeError(f"考勤异常自动确认失败({len(ids)} 条):{last_err}")
|
||||
|
||||
|
||||
def auto_confirm_all(session, data, batch_size=config.CONFIRM_BATCH_SIZE, on_progress=None):
|
||||
"""自动确认查询范围内的全部异常(分批提交,批次失败不中断其余批次)。
|
||||
|
||||
Returns:
|
||||
(待确认条数, 确认成功条数, 失败 id 列表)
|
||||
"""
|
||||
ids = [it.get("abnormal_id") for it in data if it.get("abnormal_id")]
|
||||
if not ids:
|
||||
config.logger.info("无可确认的异常单据编号,跳过自动确认")
|
||||
return 0, 0, []
|
||||
|
||||
confirmed = 0
|
||||
failed = []
|
||||
total = len(ids)
|
||||
for start in range(0, total, batch_size):
|
||||
batch = ids[start:start + batch_size]
|
||||
try:
|
||||
_confirm_batch(session, batch)
|
||||
confirmed += len(batch)
|
||||
config.logger.info("自动确认进度:%d/%d 条", confirmed, total)
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e: # noqa: BLE001 - 单批失败继续其余批次
|
||||
failed.extend(batch)
|
||||
config.logger.error("自动确认失败(%d 条):%s", len(batch), e)
|
||||
if on_progress:
|
||||
on_progress(confirmed, total)
|
||||
return total, confirmed, failed
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0006 逻辑层:分级规则、日期范围、通知文本与汇总口径。"""
|
||||
@@ -0,0 +1,146 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0006 逻辑层:日期范围、分级分类、通知文本与汇总口径(规则与影刀版一致)。"""
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
# ==================== 日期范围 ====================
|
||||
def query_month(today=None):
|
||||
"""默认查询月份:1 号(2 号之前,不含 2 号)查上月,否则查当月。"""
|
||||
today = today or date.today()
|
||||
if today.day < 2:
|
||||
return (today.replace(day=1) - timedelta(days=1)).strftime("%Y-%m")
|
||||
return today.strftime("%Y-%m")
|
||||
|
||||
|
||||
def resolve_month(value):
|
||||
""""YYYY-MM" / "YYYYMM" / 留空 → 查询月份;格式非法抛错。"""
|
||||
raw = str(value or "").strip()
|
||||
if not raw:
|
||||
return query_month()
|
||||
digits = raw.replace("-", "").replace("/", "")
|
||||
if len(digits) != 6 or not digits.isdigit():
|
||||
raise ValueError(f"查询月份格式不正确:{value}(应为 YYYY-MM)")
|
||||
try:
|
||||
datetime.strptime(digits + "01", "%Y%m%d")
|
||||
except ValueError:
|
||||
raise ValueError(f"查询月份格式不正确:{value}(应为 YYYY-MM)")
|
||||
return f"{digits[:4]}-{digits[4:]}"
|
||||
|
||||
|
||||
def month_range(month):
|
||||
"""整月查询范围(与影刀版一致:-01 ~ -31)。"""
|
||||
return f"{month}-01", f"{month}-31"
|
||||
|
||||
|
||||
def last_week_range(today=None):
|
||||
"""返回上周范围:(上周一, 上周日)。"""
|
||||
today = today or date.today()
|
||||
this_monday = today - timedelta(days=today.weekday())
|
||||
return ((this_monday - timedelta(days=7)).strftime("%Y-%m-%d"),
|
||||
(this_monday - timedelta(days=1)).strftime("%Y-%m-%d"))
|
||||
|
||||
|
||||
def in_last_week(item, push_begin, push_end):
|
||||
"""按 work_day 判断是否落在上周范围;缺失返回 False。"""
|
||||
work_day = str(item.get("work_day") or "")[:10]
|
||||
return bool(work_day) and push_begin <= work_day <= push_end
|
||||
|
||||
|
||||
# ==================== 分级分类 ====================
|
||||
def classify_abnormal(item):
|
||||
"""是否需要钉钉推送:迟到/早退<30 分钟为轻微(不推送),其余需推送。"""
|
||||
abnormal = str(item.get("abnormal", ""))
|
||||
try:
|
||||
minute = int(item.get("abnormal_minute", 0) or 0)
|
||||
except (TypeError, ValueError):
|
||||
minute = 0
|
||||
if ("迟到" in abnormal or "早退" in abnormal) and minute < 30:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def is_func_staff(item):
|
||||
"""是否职能序列(first_type_name 含「职能」才推送)。"""
|
||||
return "职能" in str(item.get("first_type_name", "") or "")
|
||||
|
||||
|
||||
def is_push_scope(item, extra_units=None, exclude_keyword=None):
|
||||
"""是否属于当事人推送范围:
|
||||
职能序列,或所属单位在「推送范围单位」内且部门路径不含排除关键字。
|
||||
"""
|
||||
if is_func_staff(item):
|
||||
return True
|
||||
units = config.DEFAULT_PUSH_EXTRA_UNITS if extra_units is None else extra_units
|
||||
keyword = config.DEFAULT_PUSH_EXCLUDE_KEYWORD if exclude_keyword is None \
|
||||
else exclude_keyword
|
||||
if not units:
|
||||
return False
|
||||
unit = str(item.get("BELONG_UNIT_ORG_NAME", "") or "").strip()
|
||||
return unit in units and (not keyword
|
||||
or keyword not in str(item.get("ORG_FULL_PATH", "") or ""))
|
||||
|
||||
|
||||
def split_data(data, push_units=None, push_exclude_keyword=None):
|
||||
"""按推送口径切分;自动确认范围不在此切分(由 run 全量确认)。"""
|
||||
push_begin, push_end = last_week_range()
|
||||
push_list = [it for it in data
|
||||
if classify_abnormal(it) and in_last_week(it, push_begin, push_end)]
|
||||
other_list = [it for it in data
|
||||
if classify_abnormal(it) and not in_last_week(it, push_begin, push_end)]
|
||||
return {
|
||||
"push_list": push_list,
|
||||
"other_list": other_list,
|
||||
"func_list": [it for it in push_list
|
||||
if is_push_scope(it, push_units, push_exclude_keyword)],
|
||||
"non_func_list": [it for it in push_list
|
||||
if not is_push_scope(it, push_units, push_exclude_keyword)],
|
||||
"push_begin": push_begin,
|
||||
"push_end": push_end,
|
||||
}
|
||||
|
||||
|
||||
def group_messages(items):
|
||||
"""按「工号-姓名」合并为 [(姓名, 工号, 通知文本)],一人一条。"""
|
||||
groups = {}
|
||||
for it in items:
|
||||
name = it.get("STAFF_NAME", "") or ""
|
||||
if not name:
|
||||
config.logger.warning("异常记录缺少姓名,跳过:%s", it)
|
||||
continue
|
||||
groups.setdefault((it.get("base_code", "") or "", name), []).append(it)
|
||||
return [(name, code, build_notify_text(group)) for (code, name), group in groups.items()]
|
||||
|
||||
|
||||
def build_notify_text(items):
|
||||
"""按人员合并拼接钉钉通知文本(内容与影刀版完全一致)。"""
|
||||
first = items[0]
|
||||
lines = [
|
||||
"【考勤异常提醒】",
|
||||
f"姓名:{first.get('STAFF_NAME', '')}",
|
||||
f"工号:{first.get('base_code', '')}",
|
||||
f"共{len(items)}条考勤异常,请在2日内主动对接人事处理考勤异常确认/请假审批/漏打卡监控查询等,"
|
||||
"超时未对接,将视为考勤异常直接封存",
|
||||
]
|
||||
for idx, item in enumerate(items, 1):
|
||||
abnormal = str(item.get("abnormal", "") or "").strip() or "考勤异常"
|
||||
minute = item.get("abnormal_minute") or "0"
|
||||
lines.append(
|
||||
f"{idx}、考勤日期:{item.get('work_day', '')}|异常类型:{abnormal}|异常时长:{minute}分钟"
|
||||
)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def build_group_summary(total_count, auto_count, confirmed_count, non_func_count, func_count,
|
||||
push_count, other_count, month, begin, end):
|
||||
"""群汇总文本(推送段落口径不变;自动确认段落为整月全量)。"""
|
||||
return (
|
||||
"【考勤异常处理汇总】\n\n"
|
||||
f"查询范围:{begin} ~ {end}({month} 整月,推送仅上周)\n\n"
|
||||
f"考勤异常总数:{total_count} 条\n\n"
|
||||
f"自动确认(整月全量):{auto_count} 条,确认成功 {confirmed_count} 条\n\n"
|
||||
f"待通知(职能及指定单位,上周):{func_count} 条,合并为 {push_count} 条推送\n\n"
|
||||
f"上周非职能(不推送):{non_func_count} 条\n\n"
|
||||
f"本月其他严重异常(非上周,仅导出留痕):{other_count} 条"
|
||||
)
|
||||
@@ -0,0 +1,87 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0006",
|
||||
"name": "EHR系统周考勤异常处理",
|
||||
"version": "1.2.0",
|
||||
"description": "拉取查询月份未调整考勤异常并导出 Excel,整月全量自动确认;上周职能序列及推送范围单位(默认总办/集团财经中心/金色湖畔事业部/集团管理中心/集团营建中心/金色印象事业部,不含大区)的严重异常按人合并推送;支持试算模式(只出表、不确认不推送)。",
|
||||
"category": "人事考勤",
|
||||
"icon": "",
|
||||
"platform": "hr",
|
||||
"uses_month": true,
|
||||
"ui": true,
|
||||
"capabilities": [
|
||||
"xq0006"
|
||||
],
|
||||
"permissions": {
|
||||
"platforms": [
|
||||
"hr"
|
||||
]
|
||||
},
|
||||
"requires": {
|
||||
"sdks": {
|
||||
"dingtalk_sdk": {
|
||||
"compat": "^0.1"
|
||||
}
|
||||
}
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ref_month": {
|
||||
"type": "string",
|
||||
"title": "执行月份",
|
||||
"default": "",
|
||||
"description": "留空=本月(1 号查上月);格式 YYYY-MM(如 2026-11)"
|
||||
},
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "输出目录",
|
||||
"default": "D:\\资料\\人资\\考勤异常",
|
||||
"description": "考勤异常 Excel 底稿存放目录"
|
||||
},
|
||||
"dry_run": {
|
||||
"type": "boolean",
|
||||
"title": "试算模式",
|
||||
"default": false,
|
||||
"description": "开启后只导出 Excel 并统计,不自动确认、不发送任何钉钉消息"
|
||||
},
|
||||
"auto_confirm": {
|
||||
"type": "boolean",
|
||||
"title": "自动确认",
|
||||
"default": true,
|
||||
"description": "开启后对查询范围内全部异常调用确认接口(分批提交);试算模式下强制不确认"
|
||||
},
|
||||
"push_enabled": {
|
||||
"type": "boolean",
|
||||
"title": "钉钉推送",
|
||||
"default": true,
|
||||
"description": "开启后推送上周职能序列及推送范围单位的严重异常给当事人,并推送条数汇总到钉钉群;试算模式下强制不推送"
|
||||
},
|
||||
"push_units": {
|
||||
"type": "string",
|
||||
"title": "推送范围单位",
|
||||
"default": "总办,集团财经中心,金色湖畔事业部,集团管理中心,集团营建中心,金色印象事业部",
|
||||
"description": "除职能序列外,这些所属单位也推送(逗号/顿号分隔);留空=只推职能序列"
|
||||
},
|
||||
"push_exclude_keyword": {
|
||||
"type": "string",
|
||||
"title": "推送排除关键字",
|
||||
"default": "大区",
|
||||
"description": "部门路径包含该关键字则不推送;留空表示不按部门路径排除"
|
||||
},
|
||||
"dingtalk_webhook": {
|
||||
"type": "string",
|
||||
"title": "钉钉 Webhook",
|
||||
"default": "",
|
||||
"description": "留空使用内置默认机器人;需要发到其他群时填写完整 webhook 地址"
|
||||
},
|
||||
"dingtalk_secret": {
|
||||
"type": "string",
|
||||
"title": "钉钉加签密钥",
|
||||
"default": "",
|
||||
"description": "机器人启用加签安全设置时填写,留空表示不加签"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0006 报告层:Excel 导出与钉钉推送。"""
|
||||
@@ -0,0 +1,63 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0006 报告层:考勤异常 Excel 导出(列口径与影刀版一致)。"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from .. import config
|
||||
from ..logic import attendance_rules as rules
|
||||
|
||||
COL_MAP = config.COL_MAP
|
||||
SHOW_ORDER = config.SHOW_ORDER
|
||||
STATUS_MAP = config.STATUS_MAP
|
||||
|
||||
|
||||
def _status_cn(value):
|
||||
"""处理状态编码转中文;空值/未知编码保持原样。"""
|
||||
if value is None or value == "":
|
||||
return ""
|
||||
return STATUS_MAP.get(str(value), str(value))
|
||||
|
||||
|
||||
def export_excel(data, save_dir, month_str, dry_run=False):
|
||||
"""导出考勤异常底稿,返回文件绝对路径;试算模式文件名带「试算」前缀。"""
|
||||
if not data:
|
||||
raise ValueError("未查询到任何考勤异常数据,无法导出")
|
||||
|
||||
df = pd.DataFrame(data)
|
||||
|
||||
# 处理方式:轻微异常(自动确认)/ 需核实(钉钉推送)
|
||||
df["处理方式"] = df.apply(
|
||||
lambda r: "自动确认" if not rules.classify_abnormal(r) else "钉钉推送", axis=1)
|
||||
|
||||
# 班段:begin_time~end_time(如 "09:00~18:00",无班段留空)
|
||||
df["班段"] = df.apply(
|
||||
lambda r: (
|
||||
f"{str(r.get('begin_time') or '').strip()}~{str(r.get('end_time') or '').strip()}"
|
||||
if (r.get("begin_time") or r.get("end_time")) else ""
|
||||
),
|
||||
axis=1,
|
||||
)
|
||||
|
||||
df.rename(columns=COL_MAP, inplace=True)
|
||||
if "处理状态" in df.columns:
|
||||
df["处理状态"] = df["处理状态"].apply(_status_cn)
|
||||
|
||||
for col in SHOW_ORDER:
|
||||
if col not in df.columns:
|
||||
df[col] = ""
|
||||
df = df[SHOW_ORDER]
|
||||
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
prefix = "周考勤异常_试算" if dry_run else "周考勤异常"
|
||||
save_path = os.path.abspath(os.path.join(save_dir, f"{prefix}_{month_str}_{ts}.xlsx"))
|
||||
try:
|
||||
df.to_excel(save_path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试")
|
||||
config.logger.info("考勤异常数据:%d 条", len(data))
|
||||
config.logger.info("文件已保存:%s", save_path)
|
||||
return save_path
|
||||
@@ -0,0 +1,180 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0006 报告层:钉钉推送。
|
||||
|
||||
推送口径与影刀版一致(消息文本不改):
|
||||
- 当事人:一人一条文本,按「姓名+工号」精确定位钉钉账号,走企业内部应用工作通知;
|
||||
- 群汇总:条数汇总文本推送到群机器人,走 dingtalk_sdk 统一格式
|
||||
(彩色标题 + 正文 + 页脚署名/时间,Markdown)。
|
||||
所有发送失败只记日志与计数,不中断主流程。
|
||||
"""
|
||||
import time
|
||||
|
||||
import requests
|
||||
from dingtalk_sdk.robot import Robot
|
||||
|
||||
from .. import config
|
||||
|
||||
MAX_ATTEMPTS = 3
|
||||
RETRY_WAIT = 1.0
|
||||
|
||||
_TOKEN_V1 = {"token": "", "exp": 0.0}
|
||||
_TOKEN_OAPI = {"token": "", "exp": 0.0}
|
||||
|
||||
|
||||
# ==================== 重试 ====================
|
||||
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.logger.warning("%s 第 %d/%d 次失败:%s", what, attempt, MAX_ATTEMPTS, e)
|
||||
if attempt < MAX_ATTEMPTS:
|
||||
time.sleep(RETRY_WAIT * attempt)
|
||||
raise last
|
||||
|
||||
|
||||
# ==================== 令牌 ====================
|
||||
def _token_v1():
|
||||
now = time.time()
|
||||
if _TOKEN_V1["token"] and now < _TOKEN_V1["exp"]:
|
||||
return _TOKEN_V1["token"]
|
||||
data = requests.post(config.DINGTALK_TOKEN_V1_URL,
|
||||
json={"appKey": config.DINGTALK_APP_KEY,
|
||||
"appSecret": config.DINGTALK_APP_SECRET},
|
||||
timeout=20).json()
|
||||
token = str(data.get("accessToken") or "")
|
||||
if not token:
|
||||
raise RuntimeError(f"钉钉 accessToken(v1) 获取失败:{data}")
|
||||
ttl = int(data.get("expireIn") or 7200)
|
||||
_TOKEN_V1.update(token=token, exp=now + max(ttl - 120, 60))
|
||||
return token
|
||||
|
||||
|
||||
def _token_oapi():
|
||||
now = time.time()
|
||||
if _TOKEN_OAPI["token"] and now < _TOKEN_OAPI["exp"]:
|
||||
return _TOKEN_OAPI["token"]
|
||||
data = requests.get(config.DINGTALK_TOKEN_OAPI_URL,
|
||||
params={"appkey": config.DINGTALK_APP_KEY,
|
||||
"appsecret": config.DINGTALK_APP_SECRET},
|
||||
timeout=20).json()
|
||||
token = str(data.get("access_token") or "")
|
||||
if not token:
|
||||
raise RuntimeError(f"钉钉 access_token(oapi) 获取失败:{data}")
|
||||
ttl = int(data.get("expires_in") or 7200)
|
||||
_TOKEN_OAPI.update(token=token, exp=now + max(ttl - 120, 60))
|
||||
return token
|
||||
|
||||
|
||||
# ==================== 接收人解析 ====================
|
||||
def _search_by_name(name):
|
||||
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):
|
||||
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(f"钉钉 user/get 失败:{data.get('errmsg')}")
|
||||
return data
|
||||
|
||||
|
||||
def resolve_user_id(name, code):
|
||||
"""按姓名搜索,再用工号(jobnumber)精确挑人;重名且无工号时抛错。"""
|
||||
ids = _search_by_name(name)
|
||||
if not ids:
|
||||
raise RuntimeError(f"钉钉通讯录里没搜到「{name}」")
|
||||
cands = []
|
||||
for uid in ids:
|
||||
detail = _user_detail(uid)
|
||||
cands.append({
|
||||
"uid": uid,
|
||||
"name": str(detail.get("name") or ""),
|
||||
"jobnumber": str(detail.get("jobnumber") or "").strip(),
|
||||
})
|
||||
hint = ";".join(f"{c['name'] or name}(工号 {c['jobnumber'] or '无'} / userId {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(f"「{name}」的候选中没有工号 {code},请核对:{hint}")
|
||||
if len(cands) == 1:
|
||||
return cands[0]["uid"]
|
||||
raise RuntimeError(f"「{name}」在钉钉里有多个人,请带工号重试:{hint}")
|
||||
|
||||
|
||||
# ==================== 发送 ====================
|
||||
def _send_work_notice(user_id, content):
|
||||
data = requests.post(
|
||||
config.DINGTALK_WORK_SEND_URL,
|
||||
params={"access_token": _token_oapi()},
|
||||
json={"agent_id": config.DINGTALK_AGENT_ID,
|
||||
"userid_list": user_id,
|
||||
"msg": {"msgtype": "text", "text": {"content": content}}},
|
||||
timeout=30).json()
|
||||
if int(data.get("errcode") or 0) != 0:
|
||||
raise RuntimeError(f"工作通知失败 errcode={data.get('errcode')} errmsg={data.get('errmsg')}")
|
||||
|
||||
|
||||
def push_person_messages(messages, on_progress=None):
|
||||
"""逐人推送工作通知。
|
||||
|
||||
Args:
|
||||
messages: [(姓名, 工号, 文本)],一人一条(文本与影刀版一致)
|
||||
on_progress: 可选回调 (done, total)
|
||||
|
||||
Returns:
|
||||
dict: sent 成功人数 / failed 失败明细 / no_uid 未匹配到账号数
|
||||
"""
|
||||
sent, failed = 0, []
|
||||
total = len(messages)
|
||||
for idx, (name, code, content) in enumerate(messages, 1):
|
||||
label = f"{name}/{code}" if code else name
|
||||
try:
|
||||
uid = _retry(lambda: resolve_user_id(name, code), f"解析接收人「{label}」")
|
||||
_retry(lambda: _send_work_notice(uid, content), f"发送工作通知「{label}」")
|
||||
sent += 1
|
||||
config.logger.info("当事人推送成功:%s(userId=%s)", label, uid)
|
||||
except Exception as e: # noqa: BLE001 - 单人失败不影响其他人
|
||||
failed.append(f"{label}:{str(e)[:200]}")
|
||||
config.logger.error("当事人推送失败:%s:%s", label, e)
|
||||
if on_progress:
|
||||
on_progress(idx, total)
|
||||
return {"sent": sent, "failed": failed, "no_uid": len(failed)}
|
||||
|
||||
|
||||
def send_group_text(text, webhook="", secret="", title=""):
|
||||
"""群机器人推送统一格式 Markdown(彩色标题 + 正文 + 页脚,走 dingtalk_sdk)。
|
||||
|
||||
正文口径与影刀版一致;消息体由 dingtalk_sdk 渲染,仅去掉与标题重复的首行标签。
|
||||
返回 True/False。
|
||||
"""
|
||||
webhook = webhook or config.DEFAULT_WEBHOOK
|
||||
secret = secret or config.DEFAULT_SECRET
|
||||
if not webhook:
|
||||
config.logger.warning("未配置群机器人 Webhook,跳过群汇总推送")
|
||||
return False
|
||||
title = title or config.DINGTALK_GROUP_TITLE
|
||||
body = str(text or "").replace(f"【{title}】", "", 1).strip()
|
||||
try:
|
||||
Robot(webhook=webhook, secret=secret, log=config.logger.info).send(
|
||||
title, body, status="info")
|
||||
config.logger.info("群汇总推送成功(Markdown + 页脚)")
|
||||
return True
|
||||
except Exception as e: # noqa: BLE001
|
||||
config.logger.error("群汇总推送失败:%s", e)
|
||||
return False
|
||||
@@ -0,0 +1,3 @@
|
||||
requests
|
||||
pandas
|
||||
openpyxl
|
||||
@@ -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>EHR系统周考勤异常处理</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "xq0006-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,268 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<!-- 方案工具条:方案供「定时任务」按 config_id 引用,到点自动取方案最新参数 -->
|
||||
<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="notice" class="notice" :class="'is-' + notice.type">
|
||||
<span class="n-ico">{{ notice.type === 'ok' ? '✓' : (notice.type === 'error' ? '✕' : '!') }}</span>
|
||||
<span>{{ notice.text }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 01 查询范围 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">01</span>
|
||||
<span class="sec-name">查询范围</span>
|
||||
<span class="sec-line" />
|
||||
<span class="sec-tag">{{ form.dry_run ? '试算(只出表)' : '正式执行' }}</span>
|
||||
</div>
|
||||
<div class="sec-body">
|
||||
<el-form label-position="top">
|
||||
<div class="grid">
|
||||
<el-form-item label="执行月份">
|
||||
<el-date-picker v-model="form.ref_month" type="month" value-format="YYYY-MM"
|
||||
placeholder="留空 = 本月(1 号查上月)" :disabled="running" clearable />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">
|
||||
查询该月整月「未调整」考勤异常(<b>1 号运行查上月</b>,2 号及以后查当月;也可手动指定月份)。
|
||||
推送仍只取<b>上周(周一~周日)</b>的严重异常。
|
||||
</div>
|
||||
</el-form>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 02 输出与处理 -->
|
||||
<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="grid row-4">
|
||||
<el-form-item class="dir-cell" label="输出目录">
|
||||
<div class="dir-ctrl">
|
||||
<el-input v-model="form.save_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>
|
||||
<template #label>
|
||||
<el-tooltip placement="top"
|
||||
content="开启后只导出 Excel 并统计,不自动确认、不发送任何钉钉消息(文件名带「试算」前缀)">
|
||||
<span class="lbl">试算模式</span>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<el-switch v-model="form.dry_run" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<template #label>
|
||||
<el-tooltip placement="top"
|
||||
content="对查询范围内全部异常(不再只限迟到/早退<30 分钟)批量调用确认接口,接口按批次提交">
|
||||
<span class="lbl">自动确认(全量)</span>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<el-switch v-model="form.auto_confirm" :disabled="running || form.dry_run" />
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<template #label>
|
||||
<el-tooltip placement="top"
|
||||
content="推送上周职能序列及下方推送范围单位的严重异常给当事人,并把条数汇总推送到钉钉群;消息内容与影刀版一致">
|
||||
<span class="lbl">钉钉推送</span>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<el-switch v-model="form.push_enabled" :disabled="running || form.dry_run" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">
|
||||
自动确认会<b>真正提交</b>到 EHR(范围=本次查询到的全部异常),关闭则只导出与统计。
|
||||
<b>试算模式</b>只出表:不确认、不推送,用于核对数据。
|
||||
钉钉推送口径:仅上周严重异常,覆盖职能序列 + 推送范围单位
|
||||
(部门路径不含排除关键字),按人合并推送,当事人需 2 日内对接人事处理。
|
||||
</div>
|
||||
</el-form>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 03 推送设置 -->
|
||||
<section v-show="form.push_enabled && !form.dry_run" class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">03</span>
|
||||
<span class="sec-name">推送设置</span>
|
||||
<span class="sec-line" />
|
||||
<span class="sec-tag">群汇总</span>
|
||||
</div>
|
||||
<div class="sec-body">
|
||||
<el-form label-position="top">
|
||||
<div class="grid">
|
||||
<el-form-item label="推送范围单位">
|
||||
<el-input v-model="form.push_units" :disabled="running" clearable
|
||||
placeholder="总办,集团财经中心,金色湖畔事业部,集团管理中心,集团营建中心,金色印象事业部(留空 = 只推职能序列)" />
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<template #label>
|
||||
<el-tooltip placement="top"
|
||||
content="部门路径包含该关键字则不推送;留空表示不按部门路径排除">
|
||||
<span class="lbl">排除部门路径关键字</span>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
<el-input v-model="form.push_exclude_keyword" :disabled="running" clearable
|
||||
placeholder="留空 = 不排除" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="grid">
|
||||
<el-form-item label="钉钉 Webhook(可选)">
|
||||
<el-input v-model="form.dingtalk_webhook" placeholder="留空 = 内置机器人"
|
||||
:disabled="running" clearable />
|
||||
</el-form-item>
|
||||
<el-form-item label="加签密钥(可选)">
|
||||
<el-input v-model="form.dingtalk_secret" type="password" show-password
|
||||
placeholder="机器人启用了加签才填" :disabled="running" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">
|
||||
当事人提醒走企业内部应用「工作通知」(按<b>工号</b>精确匹配账号);
|
||||
群汇总走群机器人。推送范围=职能序列 ∪ 上方单位(部门路径不含排除关键字),
|
||||
单位与关键字均可改,留空分别=只推职能序列 / 不按部门路径排除。
|
||||
</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>:按执行月份查询整月「未调整」考勤异常
|
||||
(1 号运行查上月,否则查当月;手动指定月份则查该月),自动分页拉全。</div>
|
||||
<div class="hb-line"><b>② 导出</b>:按固定列口径导出 Excel 底稿到输出目录,
|
||||
文件名「周考勤异常_YYYY-MM_时间戳.xlsx」;试算模式只做这一步,文件名带「_试算」前缀。</div>
|
||||
<div class="hb-line"><b>③ 自动确认(全量)</b>:对查询范围内<b>全部异常</b>批量调用确认接口
|
||||
(每 200 条一批,失败自动重试 3 次、单批失败不影响其余批次);试算模式不执行。</div>
|
||||
<div class="hb-line"><b>④ 当事人推送</b>:仅取<b>上周</b>、<b>严重异常</b>(迟到/早退 ≥ 30 分钟或其他类型),
|
||||
推送范围=<b>职能序列</b> ∪ <b>推送范围单位</b>(默认总办 / 集团财经中心 / 金色湖畔事业部 /
|
||||
集团管理中心 / 集团营建中心 / 金色印象事业部,部门路径不含排除关键字,界面可改),
|
||||
按「姓名+工号」合并为一人一条文本,经内部应用工作通知发送。</div>
|
||||
<div class="hb-line"><b>⑤ 群汇总</b>:推送条数汇总(总数、自动确认、待通知、上周非职能、
|
||||
其他严重异常)到钉钉群,走 dingtalk_sdk 统一格式(彩色标题 + 正文 + 页脚署名/时间);
|
||||
「自动确认」段落为<b>整月全量</b>口径,「待通知」含职能与推送范围单位。
|
||||
试算模式不发送任何钉钉消息。</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<!-- 操作 -->
|
||||
<div class="actions">
|
||||
<el-button type="primary" class="btn-run" :loading="running" @click="start">
|
||||
{{ running ? '执行中 ' + progress + '%' : '一键执行' }}
|
||||
</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 { ElMessage } from 'element-plus'
|
||||
import { usePluginUI } from './usePluginUI'
|
||||
|
||||
const DEFAULTS = () => ({
|
||||
ref_month: '',
|
||||
save_dir: '',
|
||||
dry_run: false,
|
||||
auto_confirm: true,
|
||||
push_enabled: true,
|
||||
push_units: '总办,集团财经中心,金色湖畔事业部,集团管理中心,集团营建中心,金色印象事业部',
|
||||
push_exclude_keyword: '大区',
|
||||
dingtalk_webhook: '',
|
||||
dingtalk_secret: '',
|
||||
})
|
||||
|
||||
const {
|
||||
form, notice, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults, restoreLastFields,
|
||||
schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
run, forceStop,
|
||||
} = usePluginUI({
|
||||
defaults: DEFAULTS,
|
||||
buildPayload(f) {
|
||||
const t = (v) => (v || '').trim()
|
||||
return {
|
||||
ref_month: t(f.ref_month),
|
||||
save_dir: t(f.save_dir),
|
||||
dry_run: !!f.dry_run,
|
||||
auto_confirm: !!f.auto_confirm,
|
||||
push_enabled: !!f.push_enabled,
|
||||
push_units: t(f.push_units),
|
||||
push_exclude_keyword: t(f.push_exclude_keyword),
|
||||
dingtalk_webhook: t(f.dingtalk_webhook),
|
||||
dingtalk_secret: t(f.dingtalk_secret),
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
function start() {
|
||||
run()
|
||||
}
|
||||
|
||||
// 调用壳子本机接口打开原生「选择文件夹」对话框(壳子 /api/dialog/directory,仅返回路径)
|
||||
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.save_dir || '' }),
|
||||
})
|
||||
const d = await r.json().catch(() => ({}))
|
||||
if (!r.ok) throw new Error(d.detail || d.error || ('HTTP ' + r.status))
|
||||
if (d.path) form.save_dir = d.path
|
||||
} catch (e) {
|
||||
ElMessage.warning('打开文件夹选择失败:' + e.message)
|
||||
} finally {
|
||||
picking.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* 插件差异样式:只用壳子 token,不写字面色值;左右内边距由壳子提供 */
|
||||
.dir-ctrl { display: flex; align-items: center; gap: var(--space-2); width: 100%; }
|
||||
.dir-ctrl .dir-input { flex: 1 1 auto; min-width: 0; }
|
||||
.dir-ctrl .dir-btn { flex: 0 0 auto; }
|
||||
/* 输出与处理:输出目录占一半,三个开关平分另一半 */
|
||||
.row-4 { grid-template-columns: repeat(6, minmax(0, 1fr)); }
|
||||
.row-4 .dir-cell { grid-column: span 3; }
|
||||
.row-4 .lbl { cursor: help; white-space: nowrap; border-bottom: 1px dashed var(--line-soft); }
|
||||
/* 区块标题右侧的即时摘要 */
|
||||
.sec-tag { flex: 0 0 auto; font-size: 12px; opacity: 0.6; white-space: nowrap; }
|
||||
</style>
|
||||
@@ -0,0 +1 @@
|
||||
export const PLUGIN_ID = 'xq0006'
|
||||
@@ -0,0 +1,9 @@
|
||||
import { createApp } from 'vue'
|
||||
import ElementPlus from 'element-plus'
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
import 'element-plus/dist/index.css'
|
||||
// 注意顺序:style.css 必须在 element-plus 之后引入,才能覆盖 --el-* 变量映射到壳子 token
|
||||
import './style.css'
|
||||
import App from './App.vue'
|
||||
|
||||
createApp(App).use(ElementPlus, { locale: zhCn }).mount('#app')
|
||||
@@ -0,0 +1,431 @@
|
||||
/* ============================================================
|
||||
插件 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; }
|
||||
|
||||
/* ---------- 说明文字 ---------- */
|
||||
.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,20 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// 插件 UI 由壳子托管在 /pui/xq0006/ 下,构建产物输出到插件包 ui/ 目录。
|
||||
// dev 端口 5184(5180/5181/5182 已被 xq0002/xq0047/xq0041 占用),代理到本机壳子 8799。
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
base: '/pui/xq0006/',
|
||||
build: {
|
||||
outDir: '../ui',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
server: {
|
||||
port: 5184,
|
||||
proxy: {
|
||||
'/api': { target: 'http://127.0.0.1:8799', changeOrigin: true },
|
||||
'/ws': { target: 'ws://127.0.0.1:8799', ws: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
+26
-26
File diff suppressed because one or more lines are too long
+1
-1
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>EHR系统周考勤异常处理</title>
|
||||
<script type="module" crossorigin src="/pui/xq0006/assets/index-D1cP9BaK.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0006/assets/index-Dx1hGP4s.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -11,7 +11,7 @@
|
||||
5. **执行方式三选一**:`试算`(不写 ERP,只组装+查重+校验)/ `只建草稿`(Save 成草稿 A,人工在 ERP 核对后提交)/ `建单并提交`(Save 后立即 Submit 进审批流)。
|
||||
6. **套打打印**:按 ERP 套打样例自绘 PDF(A4 / SimSun / 表格线坐标实测),`printkit` 直连网络打印机出纸。
|
||||
7. **异常清单**:哪一行、什么原因没建成/没打成,逐条返回。
|
||||
8. **钉钉提醒**:打印成功后用企业内部应用「工作通知」推给指定接收人(单号/收款人/金额/打印机),提醒去领取签字(默认开;失败只记日志)。
|
||||
8. **钉钉提醒**:打印成功后用企业内部应用「工作通知」推给**默认发起人**(单号/收款人/金额/打印机),提醒去领取签字(默认开;失败只记日志)。
|
||||
|
||||
## 界面字段(plugin.json)
|
||||
|
||||
@@ -19,13 +19,13 @@
|
||||
|---|---|
|
||||
| `ref_month` | 台账月份(**月份选择器**,YYYY-MM;留空=当月) |
|
||||
| `ledger_dir` / `ledger_workbook` / `ledger_file` | 台账目录(可浏览选择)/ 目标工作簿 / 指定现成 xlsx |
|
||||
| `default_applicant_staff` / `default_applicant_name` | 默认发起人(单据头 E/F 列 + 建单报文申请人),默认 `37001090/刘纤` |
|
||||
| `default_applicant_staff` / `default_applicant_name` | 默认发起人(单据头 E/F 列 + 建单报文申请人 + 钉钉提醒接收人),默认 `37004121/陈莲` |
|
||||
| `erp_system` | 自动分流 / 强制新版 / 强制旧版 |
|
||||
| `erp_username` / `erp_password` | **新版** ERP 账号密码 |
|
||||
| `erp_username_old` / `erp_password_old` | **旧版** ERP 账号密码(旧系统是另一套站点;留空沿用新版) |
|
||||
| `run_mode` | **执行方式(三选一)**:`dry_run` 试算(不写 ERP)/ `draft` 只建草稿(A,人工核对后提交)/ `submit` 建单并提交(B,进审批流);默认 `dry_run` |
|
||||
| `print_enabled` / `printer` / `copies` | 套打打印、打印机(人力资源部双面 / 信息技术部单面)、份数(1~5) |
|
||||
| `dingtalk_enabled` / `dingtalk_users` | 打印后钉钉提醒(默认开)、接收人「姓名/工号」 |
|
||||
| `dingtalk_enabled` | 打印后钉钉提醒(默认开);接收人固定为默认发起人,无需单独配置 |
|
||||
| `debug_mode` | 调试日志 |
|
||||
|
||||
> 发起前对账、刷新「预支办结流程」**固定开启**,不提供开关。
|
||||
|
||||
@@ -99,12 +99,7 @@ class PrepayPayApplyPlugin(ScenePlugin):
|
||||
'dingtalk_enabled': {
|
||||
'type': 'boolean', 'title': '打印后钉钉提醒领取',
|
||||
'default': config.DINGTALK_ENABLED_DEFAULT,
|
||||
'description': '打印成功后推送一条群提醒(单号/收款人/金额/打印机),提醒去领取签字',
|
||||
},
|
||||
'dingtalk_users': {
|
||||
'type': 'string', 'title': '钉钉接收人(姓名/工号)',
|
||||
'default': config.DINGTALK_USERS_DEFAULT,
|
||||
'description': '多个用「、」「,」「;」或换行分隔;重名必须带工号;留空=不提醒',
|
||||
'description': '打印成功后用工作通知提醒默认发起人(单号/收款人/金额/打印机),提醒去领取签字',
|
||||
},
|
||||
'debug_mode': {'type': 'boolean', 'title': '调试日志', 'default': False},
|
||||
}
|
||||
@@ -373,14 +368,15 @@ class PrepayPayApplyPlugin(ScenePlugin):
|
||||
else:
|
||||
try:
|
||||
from .report import notify
|
||||
recipient = f'{bh_name}/{bh_staff}' if bh_name else bh_staff
|
||||
out['notify'] = notify.notify_printed(
|
||||
out['printed'],
|
||||
out.get('printer') or str(fields.get('printer') or ''),
|
||||
out.get('print_failed', 0),
|
||||
users_text=str(fields.get('dingtalk_users') or ''),
|
||||
users_text=recipient,
|
||||
dry_run=dry_run)
|
||||
if out['notify'].get('ok'):
|
||||
log(f'[钉钉] 已提醒 {out["notify"].get("sent")} 人去领取')
|
||||
log(f'[钉钉] 已提醒发起人「{recipient}」领取')
|
||||
else:
|
||||
log(f'[钉钉] 提醒未发出:'
|
||||
f'{out["notify"].get("error") or out["notify"].get("skipped")}', 'WARN')
|
||||
|
||||
@@ -48,7 +48,7 @@ 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')
|
||||
@@ -81,8 +81,8 @@ BILLHEAD_SHEET = '付款申请单#单据头(FBillHead)' # 金蝶引入模板 sh
|
||||
BH_COL_DATE = '(单据头)申请日期'
|
||||
BH_COL_APPLICANT_NO = '(单据头)申请人#编码'
|
||||
BH_COL_APPLICANT_NAME = '(单据头)申请人#名称'
|
||||
DEFAULT_APPLICANT_STAFF = '37001090' # 默认发起人工号(HR 代提人)
|
||||
DEFAULT_APPLICANT_NAME = '刘纤'
|
||||
DEFAULT_APPLICANT_STAFF = '37004121' # 默认发起人工号(HR 代提人;也是钉钉提醒接收人)
|
||||
DEFAULT_APPLICANT_NAME = '陈莲'
|
||||
|
||||
# ==================== 流程详细数据(银行卡信息来源) ====================
|
||||
# FBillHead 的 AM/AN/AO = XLOOKUP(工号, 预支办结流程!O:O, V/AC/AD)
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
F_VTUY_Text_apv1 / FDescription
|
||||
不收:``#Name`` 列(ERP 按编码自动带出)、A/AA 序号、Z(*Split*1) 间隔列、
|
||||
AQ~AS(工作簿本地的标准化门店/参保/新旧系统辅助列)。
|
||||
申请人(E/F 列)= 界面「默认发起人」(代提人,默认 37001090 刘纤);
|
||||
申请人(E/F 列)= 界面「默认发起人」(代提人,默认 37004121 陈莲);
|
||||
往来/收款单位(H/K/L 列)= 受款员工;收款账户三项(AM/AN/AO)取「预支办结流程」
|
||||
的 V/AC/AD(与单据头 XLOOKUP 同源),由 ``data.ledger.load_flow_banks`` 提供;
|
||||
AP FDescription 按 ``config.DESCRIPTION_SOURCE`` 取值(默认金额)。
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0012",
|
||||
"name": "EHR预支及支付报酬自动发起ERP付款申请",
|
||||
"version": "0.3.4",
|
||||
"version": "0.3.5",
|
||||
"description": "按月份从 EHR 接口导出预支报酬台账(默认当月)→ 按月扫描「流程监控-已办结」预支流程刷新「预支办结流程」(全部流程详细数据,供建单报文与单据头 XLOOKUP 取收款人/银行/账号)→ 写入单据头申请日期/发起人 → Excel 重算并校验必录信息(含银行卡,缺失行跳过)→ 与 ERP 付款申请单对账回填「已付」→ 剩余未付行按台账「新旧系统」口径自动分流建单(默认试算不写库),可选提交,打印两份(每张 ERP 单据套打 + 「单子传递打印」本批行汇总);含幂等查重与异常清单;打印完成后钉钉提醒去领取",
|
||||
"category": "人资",
|
||||
"icon": "",
|
||||
@@ -63,13 +63,13 @@
|
||||
"default_applicant_staff": {
|
||||
"type": "string",
|
||||
"title": "默认发起人工号",
|
||||
"default": "37001090",
|
||||
"description": "即单据头 E 列「申请人#编码」,同时作为 ERP 建单报文的申请人(代提人,不是受款员工)"
|
||||
"default": "37004121",
|
||||
"description": "即单据头 E 列「申请人#编码」,同时作为 ERP 建单报文的申请人(代提人,不是受款员工),也是钉钉提醒接收人"
|
||||
},
|
||||
"default_applicant_name": {
|
||||
"type": "string",
|
||||
"title": "默认发起人姓名",
|
||||
"default": "刘纤",
|
||||
"default": "陈莲",
|
||||
"description": "单据头 F 列「申请人#名称」;建单报文按编码带出姓名,此值只写工作簿"
|
||||
},
|
||||
"erp_system": {
|
||||
@@ -147,13 +147,7 @@
|
||||
"type": "boolean",
|
||||
"title": "打印后钉钉提醒领取",
|
||||
"default": true,
|
||||
"description": "打印成功后用企业内部应用「工作通知」提醒接收人去领取签字"
|
||||
},
|
||||
"dingtalk_users": {
|
||||
"type": "string",
|
||||
"title": "钉钉接收人(姓名/工号)",
|
||||
"default": "陈莲/37004121",
|
||||
"description": "多个用「、」「,」「;」或换行分隔;重名必须带工号,如 陈莲/37001090;留空=不提醒"
|
||||
"description": "打印成功后用企业内部应用「工作通知」提醒默认发起人去领取签字(接收人=上面的默认发起人,无需单独配置)"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
`topapi/message/corpconversation/asyncsend_v2` 发工作通知给「姓名/工号」指定的接收人。
|
||||
|
||||
接收人解析:
|
||||
- 界面填「姓名/工号」,多个用「、」「,」「;」或换行分隔;
|
||||
- 固定取「默认发起人」(姓名/工号由调用方传入),界面不再单独配置;
|
||||
- 先按姓名搜索 userId(钉钉通讯录搜索会命中重名),再用工号(jobnumber)精确挑人;
|
||||
- 只填姓名且搜到多个 → 报错并列出候选,要求补工号。
|
||||
|
||||
@@ -145,10 +145,10 @@ def notify_printed(printed: list, printer: str, failed: int = 0, *,
|
||||
"""打印完成提醒。返回 {'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)
|
||||
recipients = parse_recipients(users_text)
|
||||
if not recipients:
|
||||
config.log(f'{TAG} 未配置接收人,跳过提醒')
|
||||
return {'ok': False, 'sent': 0, 'failed': [], 'skipped': '未配置接收人'}
|
||||
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}')
|
||||
|
||||
@@ -129,16 +129,17 @@
|
||||
<div class="grid">
|
||||
<el-form-item label="默认发起人工号(E 列 / 报文申请人)">
|
||||
<el-input v-model="form.default_applicant_staff" :disabled="running" clearable
|
||||
placeholder="37001090" />
|
||||
placeholder="37004121" />
|
||||
</el-form-item>
|
||||
<el-form-item label="默认发起人姓名(F 列)">
|
||||
<el-input v-model="form.default_applicant_name" :disabled="running" clearable
|
||||
placeholder="刘纤" />
|
||||
placeholder="陈莲" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
</el-form>
|
||||
<div class="tip">
|
||||
发起人两列按这里回填「付款申请单#单据头(FBillHead)」E/F 列,也是建单报文的申请人(代提人)。
|
||||
发起人两列按这里回填「付款申请单#单据头(FBillHead)」E/F 列,也是建单报文的申请人(代提人);
|
||||
打印完成后的钉钉提醒同样发给此人,无需再单独配置接收人。
|
||||
其余口径逐行读模板:申请日期=D 列(当天)、付款用途=AH 列、期望付款日=AK 列($D+1)、
|
||||
申请部门=W 列(BM000477 / BM000881)。
|
||||
</div>
|
||||
@@ -174,19 +175,13 @@
|
||||
<el-form-item label="建单后打印">
|
||||
<el-switch v-model="form.print_enabled" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item label="打印后钉钉提醒">
|
||||
<el-form-item label="打印后钉钉提醒发起人">
|
||||
<el-switch v-model="form.dingtalk_enabled" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item label="调试日志">
|
||||
<el-switch v-model="form.debug_mode" :disabled="running" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="grid">
|
||||
<el-form-item label="钉钉接收人(姓名/工号)">
|
||||
<el-input v-model="form.dingtalk_users" :disabled="running || !form.dingtalk_enabled"
|
||||
clearable placeholder="陈莲/37004121;多个用「、」分隔,重名必须带工号" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
</el-form>
|
||||
<div class="tip">
|
||||
<b>试算</b>不写 ERP,只组装+查重+校验;<b>只建草稿</b>会真的建单(A 状态),
|
||||
@@ -247,8 +242,8 @@ const DEFAULTS = () => ({
|
||||
ledger_dir: 'D:\\资料\\人资\\预支',
|
||||
ledger_workbook: 'D:\\资料\\人资\\预支\\1030工资预支付款申请--已付.xlsx',
|
||||
ledger_file: '',
|
||||
default_applicant_staff: '37001090',
|
||||
default_applicant_name: '刘纤',
|
||||
default_applicant_staff: '37004121',
|
||||
default_applicant_name: '陈莲',
|
||||
erp_system: '自动',
|
||||
erp_username: '',
|
||||
erp_password: '',
|
||||
@@ -259,7 +254,6 @@ const DEFAULTS = () => ({
|
||||
printer: '人力资源部',
|
||||
copies: 1,
|
||||
dingtalk_enabled: true,
|
||||
dingtalk_users: '陈莲/37004121',
|
||||
debug_mode: false,
|
||||
})
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user