feat: add configurable SMB archival and notification queues
This commit is contained in:
1 parent
34770ed338
commit
c2f16a5c56
29 files changed
+809
-26
No files matched your search
@@ -2,12 +2,13 @@
|
||||
|
||||
面向团队的 BPM 订单工作台,提供业务日历、异常待办与转交、连接管理和运行监管配置;保留 Chrome 已登录订单页导出本地 PDF 的能力。
|
||||
|
||||
**项目最终目标**:无人值守识别匹配订单、按模板整理、上传 210、按产品线群组每天两次自动发送邮件。当前实现团队工作台与 BPM Web 登录、会话保存,订单处理规则后续确定;BPM 知会不自动处理。已接入新版门户只读扫描;上传、ZCode 和业务自动通知仍待接入。完整流程背景见 [无人值守系统设计](docs/unattended-system-design.md),登录实现见 [BPM 登录设计](docs/superpowers/specs/2026-10-16-bpm-login-design.md)。
|
||||
**项目最终目标**:无人值守识别匹配订单、按模板整理、上传 210、按产品线群组每天两次自动发送邮件。当前实现团队工作台与 BPM Web 登录、会话保存,订单处理规则后续确定;BPM 知会不自动处理。已接入新版门户只读扫描;新增可配置 SMB 归档和通用通知队列。实际 BPM 简要说明字段与产业接口人规则等待同事整理后配置,ZCode 尚未接入。完整流程背景见 [无人值守系统设计](docs/unattended-system-design.md),登录实现见 [BPM 登录设计](docs/superpowers/specs/2026-10-16-bpm-login-design.md)。
|
||||
|
||||
## 设计与部署入口
|
||||
|
||||
- [设计要求(当前基准)](docs/design-requirements.md):功能范围、架构、数据存储、权限、验收和实施顺序。
|
||||
- [部署说明](docs/deployment.md):安装、HTTPS、状态目录及备份。
|
||||
- [后续业务资料整理表](docs/business-configuration.md):SMB 参数、来源字段和产业接口人需要整理的信息。
|
||||
- [扫描验证记录](docs/bpm-scan-verification-2026-10-16.md):最近验证及实际范围。
|
||||
|
||||
## Web 看板
|
||||
@@ -17,7 +18,7 @@
|
||||
3. 业务日历支持月历、公司工作日/休息日/停发覆盖,采集与发送分别设置;可恢复每周默认规则,并预览发送时段。保存配置不会执行采集或发送。
|
||||
4. 异常待办支持创建、认领、转交、提交验证、填写人工核验依据后关闭和重新打开;显示负责人和流转记录,防止多人同时覆盖。operator 可处理异常,viewer 只读,admin 可管理全部配置。
|
||||
5. BPM 连接支持创建、账号托管、网页登录、检查保存、重启复用和停用。每个连接独立保存会话,由负责人或管理员操作。运行监管目前保存默认负责人、通知方式和重试上限草稿,不调用 ZCode、不执行恢复、不发送通知。
|
||||
6. 邮箱管理支持公司 SMTP / IMAP、模板邮件收取、预览确认和历史版本;原 PDF 记录、每日两次时间、产品线群组、团队账号和操作记录继续可用。新版 BPM 扫描结果按流程到达日期分区;自动批量发信等待业务规则联调。
|
||||
6. 邮箱管理支持公司 SMTP / IMAP、模板邮件收取、预览确认和历史版本;原 PDF 记录、每日两次时间、产品线群组、团队账号和操作记录继续可用。新版 BPM 扫描结果按流程到达日期分区;业务通知使用独立通用队列,默认暂停,BPM 来源适配等待字段核实。
|
||||
|
||||
界面复用 [Tabler](https://tabler.io/admin-template) 免费开源版(@tabler/core 1.6.1),CSS/JS 全部在本机提供;MIT 原文见 licenses/Tabler-MIT.txt。青龙已有独立部署准备和 CLI,尚未接通业务,本次不启动它或复制其内部源码。
|
||||
|
||||
@@ -30,12 +31,23 @@
|
||||
3. 从名单内的邮箱新建邮件发送到托管邮箱,主题为 `[模板][海外运营]订单通知 {{日期}}`;正文和附件作为对应产品线模板。`[模板]订单通知` 表示默认模板。回复/转发主题、范围标记不完整、未授权发件人和超出 10 MB 的邮件不导入。首次及邮箱 UID 变化只处理近 7 天邮件,保留该日期边界和 UID 游标;只读访问,不标记已读、不移动或删除邮件。
|
||||
4. 打开 **模板与收件群组 → 预览并确认**,核对来源、发信标题、产品线、表格、图片和附件后点击 **确认生效**。可调整标题和产品线,或切换为纯文本编辑正文。旧版本留作历史;多人确认发生冲突时不覆盖新版本。名单控制导入,管理员确认后才生效。
|
||||
5. 支持明确变量 `{{产品线}}`、`{{订单号}}`、`{{日期}}`、`{{订单列表}}`,不执行模板表达式。HTML 预览隔离,阻断脚本及外链图片;保留原 EML,管理员可下载原邮件与附件。邮件中的 To/Cc 不会修改业务收件群组。
|
||||
6. 已生效模板可点击 **发送测试到本邮箱** 并确认目标。使用真实 SMTP 发送到托管邮箱自身,先记录发送任务,不自动重试不确定结果。此操作不会发给产品线群组。批量订单发信在后续业务规则接入。
|
||||
6. 已生效模板可点击 **发送测试到本邮箱** 并确认目标。使用真实 SMTP 发送到托管邮箱自身,先记录发送任务,不自动重试不确定结果。此操作不会发给产品线群组。业务通知另在“业务通知”中配置来源映射,正文直接使用来源简要说明,不使用模板附件。
|
||||
|
||||
旧模板草稿首次启动迁为待确认版本,确认时选择实际托管邮箱。邮箱维护须从部署机回环地址或已配置的 HTTPS 反向代理访问;与 BPM 登录使用同一传输要求。密码留空保留原值,更换邮箱、登录账号或服务器时须重新录入。后台持续检查不要求一直打开网页。
|
||||
|
||||
复用 [Nodemailer](https://nodemailer.com/) 10.1.1、[ImapFlow](https://imapflow.com/) 2.4.3、[MailParser](https://nodemailer.com/extras/mailparser/) 3.9.39 和 [sanitize-html](https://github.com/apostrophecms/sanitize-html) 2.18.1,版本已锁定。公司邮箱真实连接需管理员录入参数后检查。
|
||||
|
||||
## 存储服务器与业务通知
|
||||
|
||||
- **存储服务器**:管理员配置 SMB 主机、共享名称、归档子目录及独立账号密码。密码加密保存在部署机,留空编辑保留原值;更换主机、共享或账号需重新录入。保存配置不连接服务器,点击“检查读写”会创建、读取并清理一个随机探测文件。账号维护要求部署机回环地址或可信 HTTPS。
|
||||
- **文件管理**:管理员与操作员可浏览归档目录、创建子目录、下载 PDF,将已有成功导出的 PDF 归档。目标存在相同内容时幂等完成;不同内容保留新文件,原件不覆盖。只读成员查看服务器和归档记录。启用自动归档后仅处理新导出的 PDF,历史文件由人选择归档;失败记录可通过重新选择同一任务重试。
|
||||
- **Windows SMB**:使用原生协议,不映射盘符、不强行断开已有共享连接。同一主机已有其他账号连接而产生 1219 冲突时,由部署机管理员处理。共享及所配置归档根目录需已存在并授予读写权限。PDF 上限 64 MiB,单层浏览最多 500 项。
|
||||
- **业务通知**:配置来源名称、JSON 字段路径、托管发件邮箱及尝试上限,产业接口人维护在现有“模板与收件群组”。通知 ID、产业、简要说明必填;正文复制简要说明原文,**不附带 PDF,也不因 PDF 存档而触发邮件**。可粘贴样本预览字段及收件人,预览不入队、不发信。
|
||||
- **自动发送**:默认暂停。开启前需要 SMTP 检查通过及产业收件组;开启后每 30 秒检查既有的两个北京时间时段及业务日历,逐项或按产业汇总。错过时段保留待发数据至下个正常时段;空队列不发信。SMTP 检查失败受尝试次数限制,发送结果不明确或部分收件人未接受则停在“待核实”,管理员填写核验依据后才能确认成功或重新入队。
|
||||
- **后续业务配置**:标准来源事件通过已认证同源 `POST /api/notifications/events` 提交 `{ "data": { ...来源对象... } }`;`/api/notifications/preview` 使用相同结构进行预览。当前没有把 BPM 全部待阅记录直接转成通知;同事整理实际字段与产业映射后,再接入来源适配器。不能将当前通用模块视为已完成 BPM、SMB 实机及公司邮件端到端联调。
|
||||
|
||||
存储配置及记录位于本机 `storage/storage.sqlite`;通知配置、加密队列正文和发送批次位于 `notifications/notifications.sqlite`。与其他状态目录一起停服备份,不提交至 Git。
|
||||
|
||||
## BPM 登录
|
||||
|
||||
### 自动扫描与流程到达记录
|
||||
@@ -90,7 +102,7 @@ Chrome 加载扩展只需做一次。修改扩展源码、重新配对或变更
|
||||
- 本地程序使用隔离的无界面 Chrome 排版,禁用页面脚本和网络;保存后关闭该排版进程,不影响你正在使用的 Chrome。
|
||||
- 不导出密码、隐藏控件、ViewState、讨论输入和操作按钮,不提交或修改 BPM 订单。
|
||||
- **输出是页面导出样稿,不是服务器原版 PDF,也不保证与 XForm 原生打印完全一致。** 不支持的图片、资源读取失败会在扩展中提示。网页内的附件只显示名称,不会自动合并附件。
|
||||
- 本版包含 PDF 导出、团队协作、BPM 托管、SMTP / IMAP 邮箱与模板审核及明确操作的测试发信。上传 210、业务规则匹配、按批次自动发信及 ZCode 监管尚未接入;不会自动处理知会或修改 BPM 审批。
|
||||
- 本版包含 PDF 导出、团队协作、BPM 托管、SMTP / IMAP 邮箱与模板审核及明确操作的测试发信。支持 SMB 服务器配置、PDF 归档和通用通知队列;BPM 业务匹配与简要说明自动入队、ZCode 监管尚未接入;不会自动处理知会或修改 BPM 审批。
|
||||
|
||||
## 故障处理
|
||||
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# 后续业务资料整理表
|
||||
|
||||
本轮交付通用配置能力。下面的信息整理完成后,可在工作台录入并联调,不需要把服务器地址或产业接口人写进源码。
|
||||
|
||||
## 存储服务器
|
||||
|
||||
| 项目 | 需要整理的内容 |
|
||||
|---|---|
|
||||
| 名称 | 便于同事识别的服务器名称 |
|
||||
| 地址 | 主机名或 IPv4 地址,不带共享路径 |
|
||||
| 共享名称 | `\\主机\共享名称` 中的共享部分 |
|
||||
| 归档子目录 | 共享目录下已有的归档根目录,可留空 |
|
||||
| 登录账号 | 独立账号,域账号可使用 `域\账号` |
|
||||
| 密码 | 管理员在工作台录入,不放在业务资料表中 |
|
||||
| 自动归档 | 是否作为新导出 PDF 的自动归档目标 |
|
||||
|
||||
## 业务通知来源
|
||||
|
||||
请提供一份脱敏来源对象样本,并标明以下字段的真实路径。支持中文、英文及嵌套对象点路径;不执行表达式。
|
||||
|
||||
| 字段 | 用途 | 必填 |
|
||||
|---|---|---|
|
||||
| 通知 ID | 标识同一条来源记录 | 是 |
|
||||
| 版本 | 区分更改版本;留空时使用简要说明的内容摘要 | 否 |
|
||||
| 产业 | 对应工作台收件组的产业 / 产品线名称 | 是 |
|
||||
| 简要说明 | 作为邮件正文的原文,保留换行 | 是 |
|
||||
| 标题 | 邮件标题;留空时使用产业业务通知标题 | 否 |
|
||||
| 业务时间 | 标准日期时间,建议带 `+08:00` 时区 | 否 |
|
||||
|
||||
仅用于解释格式的虚构样本:
|
||||
|
||||
```json
|
||||
{
|
||||
"来源": {
|
||||
"编号": "DEMO-001",
|
||||
"版本": "1",
|
||||
"产业": "示例产业",
|
||||
"简要说明": "第一行原文\n第二行原文",
|
||||
"标题": "示例业务通知",
|
||||
"时间": "2026-10-17T09:00:00+08:00"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
对应路径分别为 `来源.编号`、`来源.版本`、`来源.产业`、`来源.简要说明`、`来源.标题`、`来源.时间`。先使用“来源样本预览”核对原文与收件人;预览不入队、不发信。
|
||||
|
||||
## 产业接口人与发送安排
|
||||
|
||||
| 项目 | 需要整理的内容 |
|
||||
|---|---|
|
||||
| 产业 / 产品线 | 与来源产业字段一致的名称 |
|
||||
| 收件人 To | 该产业接口人的邮箱,可多个 |
|
||||
| 抄送 Cc | 可选,可多个 |
|
||||
| 发件邮箱 | 管理员托管的 SMTP 邮箱及参数 |
|
||||
| 两个时段 | 每日两个北京时间;每单或按产业汇总 |
|
||||
| 日历 | 周末是否发送、公司调休和停发日期 |
|
||||
|
||||
PDF 仅归档至 SMB,不作为业务通知附件。通知内容只取来源简要说明。实际 BPM 来源如何取得上述字段,待资料整理后核实并接入标准队列接口。
|
||||
@@ -1,12 +1,12 @@
|
||||
# 订单通知自动化:设计要求
|
||||
|
||||
更新日期:2026-10-16。本文为当前设计要求入口;与早期调研或阶段计划冲突时,以本文及对应模块最新设计为准。业务规则的调整需要同步本文、实现与验收记录。
|
||||
更新日期:2026-10-17。本文为当前设计要求入口;与早期调研或阶段计划冲突时,以本文及对应模块最新设计为准。业务规则的调整需要同步本文、实现与验收记录。
|
||||
|
||||
## 1. 产品目标与运行方式
|
||||
|
||||
团队成员在各自电脑访问同一台常驻服务器,通过 Web 管理 BPM 连接、流程到达记录、业务日历、异常、邮件模板和收件群组。正式工作台使用真实持久数据,不预置演示账号或虚构订单,不提供默认管理员密码。
|
||||
|
||||
最终业务链路:发现符合规则的订单 → 提取字段及生成 PDF → 归档并上传 210 → 按产品线选择模板与群组 → 每日两个约定时段发送 → 保存结果并处理异常。
|
||||
最终业务按两条链路组织:PDF 提取生成后归档到可配置 SMB 服务器;业务通知将 BPM 简要说明原文按产业发送给接口人,使用每日两个约定时段。PDF 归档不触发邮件,也不附加 PDF;具体 BPM 字段与产业规则由同事整理后配置。
|
||||
|
||||
当前阶段优先保证账号托管、只读扫描、日期视图与邮件模板维护。业务匹配规则由后续表格确定;在规则确认前,不将知会状态等同于可处理订单,不自动已阅、审批或发送业务通知。
|
||||
|
||||
@@ -22,8 +22,8 @@
|
||||
| 邮箱渠道 | 公司 SMTP/IMAP、加密凭据、连接检查、定时收信 | 公司真实邮箱连通性验收 |
|
||||
| 邮件模板 | 模板邮件解析、预览确认、版本、HTML/CID/附件、自发测试 | 接入正式订单数据渲染与发送批次 |
|
||||
| PDF | Chrome 扩展手动采集、离线生成、四字段命名、重名保留 | 按业务表单适配无人值守详情与导出 |
|
||||
| 210 上传 | 尚未接入 | 确认协议、路径、权限与结果校验 |
|
||||
| 自动业务邮件 | 已有时间与群组配置,未接通业务执行 | 批次持久化、去重、恢复、结果核验 |
|
||||
| SMB 存储服务器 | 独立凭据加密、地址管理、读写检查、目录浏览、PDF 手动与新文件自动归档 | 录入服务器与权限,完成实机验收 |
|
||||
| 自动业务邮件 | 通用来源字段映射、样本预览、持久队列、两时段调度、去重与人工核验 | 核实 BPM 简要说明来源和产业接口人映射后接通来源 |
|
||||
| ZCode 监管 | 方向预留,未接入 | 确认 GLM ZCode 接口、诊断范围及通知渠道 |
|
||||
| 青龙 | 保留部署准备及 CLI | 暂停部署,不作为当前服务启动依赖 |
|
||||
|
||||
@@ -98,7 +98,7 @@ flowchart LR
|
||||
|
||||
异常需包含连接或任务引用、失败步骤、负责人、状态、时间和流转记录,支持认领及转交。核验关闭保存操作人和核验依据;自动步骤的结果来自实际执行回执。产品页面只呈现必要的业务操作、状态、数据和结果。
|
||||
|
||||
后续执行链路必须持久化订单版本、导出、上传、待发、发送结果及批次;重启可恢复,同一版本不重复通知。缺少群组、上传失败或发送结果不明时停在对应步骤。上线前明确历史补发、漏过时段补发、空批次和更改单策略。
|
||||
后续执行链路必须持久化订单版本、导出、上传、待发、发送结果及批次;重启可恢复,同一版本不重复通知。缺少群组或发送结果不明时停在通知步骤;PDF 上传失败单独记录,不生成邮件任务。上线前明确历史补发、漏过时段补发、空批次和更改单策略。
|
||||
|
||||
ZCode 后续用于有限诊断与修复建议;任务状态、重试上限和外部结果判定由确定性程序维护。接入前明确接口人及通知渠道,不向模型发送密码、Cookie 或完整业务表单。
|
||||
|
||||
@@ -114,6 +114,8 @@ ZCode 后续用于有限诊断与修复建议;任务状态、重试上限和
|
||||
| `bpm-keys/` | Windows DPAPI 保护的主密钥 |
|
||||
| `mail/mail.sqlite` | 邮箱、模板、原邮件、游标及测试发送记录 |
|
||||
| `bpm-scan/scan.sqlite` | 流程到达记录、扫描设置与运行结果 |
|
||||
| `storage/storage.sqlite` | 加密 SMB 服务器配置、自动归档设置与归档记录 |
|
||||
| `notifications/notifications.sqlite` | 字段映射、加密简要说明队列、发送批次及核验 |
|
||||
|
||||
敏感载荷使用 AES-GCM 加密,主密钥绑定 Windows 运行身份。账号 API 不返回已保存密码,客户端不取得 BPM Cookie。远程画面不录制,输入不写日志;导出快照移除密码及隐藏数据。
|
||||
|
||||
@@ -133,3 +135,7 @@ ZCode 后续用于有限诊断与修复建议;任务状态、重试上限和
|
||||
自动验证入口为 `npm test`。不同阶段记录有各自范围,不能把隔离夹具测试当成公司真实系统的端到端验收。最近扫描验证详情见 [BPM 扫描验证记录](bpm-scan-verification-2026-10-16.md),其他阶段见 [验证历史](verification.md)。
|
||||
|
||||
相关模块设计:[框架](superpowers/specs/2026-10-16-application-framework-design.md)、[BPM 登录](superpowers/specs/2026-10-16-bpm-login-design.md)、[扫描](superpowers/specs/2026-10-16-bpm-scan-design.md)、[邮件](superpowers/specs/2026-10-16-mail-design.md)。
|
||||
|
||||
## 2026-10-17 通用配置补充
|
||||
|
||||
存储与通知的设计分别见 [SMB 存储设计](superpowers/specs/2026-10-17-storage-design.md) 与 [通用通知设计](superpowers/specs/2026-10-17-notification-design.md)。业务通知以简要说明原文为正文,不改写、不附加归档 PDF;来源字段未核实时不从标题推断。源数据由标准入队接口接收,实际 BPM 适配由后续业务资料确定。通用功能默认关闭,参数通过工作台配置,不硬编码服务器、产业、接口人或实际流程名。
|
||||
@@ -0,0 +1,13 @@
|
||||
# 通用通知执行记录
|
||||
|
||||
用户在本轮将范围明确为通用、可配置模块,业务细节由同事后续整理。执行依据为 [通用通知设计](../specs/2026-10-17-notification-design.md),与 SMB 存储分别交付。
|
||||
|
||||
- [x] 先写并运行缺少 notifications 模块的失败测试:原文复制、去重、暂停、发送结果不明、无产业映射。
|
||||
- [x] 实现 NotificationStore 的加密正文、来源版本去重、批次状态、重启恢复、核验依据;NotificationService 提供字段映射、preview/ingest、两时段 tick 和显式启停。
|
||||
- [x] 实现 `/api/notifications`、`/settings`、`/preview`、`/events` 和 `/batches/:id/resolve`;通过 HTTP 角色、同源与预览无副作用测试。
|
||||
- [x] 实现业务通知页面:来源名称、字段路径、邮箱、产业收件组入口、次数上限、暂停开关、样本预览、队列和待核实批次处理。
|
||||
- [x] 先观察无页面入口的浏览器失败,再验证配置保存、原文预览、无自动入队和移动宽度。
|
||||
- [x] 独立只读审查发现后,先添加失败回归,再修复无产业映射堵队、较早待核实批次不可见、邮箱忙碌消耗时段。另加入中文字段路径与来源改名不重复入队验证。
|
||||
- [x] 复审确认五项重要问题均已修正;文件路径和归档返回值两项由存储测试共同覆盖。
|
||||
|
||||
最终运行时、界面和相关模块回归结果记录在 `docs/verification-2026-10-17.md`。生产数据与实际邮件收发不在本次资料尚未提供阶段执行。
|
||||
@@ -0,0 +1,48 @@
|
||||
# SMB 存储服务器实施计划
|
||||
|
||||
> **For agentic workers:** 使用 superpowers:executing-plans 在当前会话逐项执行,不创建额外聊天。
|
||||
|
||||
**Goal:** 可在工作台管理 SMB 服务器、验证读写并归档已有和新生成的 PDF。
|
||||
|
||||
**Architecture:** StorageStore 负责加密配置与归档状态;SmbClient/FileArea 负责认证与目录受限的真实文件操作;StorageService 串联导出任务,storageApi 与 StorageViews 接入现有工作台。
|
||||
|
||||
**Tech Stack:** Node.js >=22.13、内置 SQLite、Windows PowerShell/Win32、现有 Tabler、AES-GCM/DPAPI。
|
||||
|
||||
**Spec:** ../specs/2026-10-17-storage-design.md
|
||||
|
||||
## 全局约束
|
||||
|
||||
- PDF 只归档,存储功能不调用邮件发送。
|
||||
- 独立 SMB 账号密码加密保存;只在本机或可信 HTTPS 维护。
|
||||
- 路径限制、同名不覆盖、SHA-256 和 64 MiB 上限适用于全部归档入口。
|
||||
- 真实服务器参数由管理员录入;本地测试不替代 210 实机验收。
|
||||
|
||||
## Task 1:加密配置和受限文件操作
|
||||
|
||||
文件:新增 src/storage-store.cjs、src/storage-files.cjs、src/smb-native.cjs、scripts/smb-native.ps1、tests/storage.test.cjs。
|
||||
|
||||
- [x] 先写行为测试:磁盘不含密码、旧版本拒绝、更换身份需新密码;真实临时目录拒绝越界、文件内容一致、重试不重复、同名异内容不覆盖。
|
||||
- [x] 运行 `node --test --test-timeout=90000 tests/storage.test.cjs`,确认因缺少模块失败。
|
||||
- [x] 实现 `StorageStore(dir)` 的 saveServer/publicServer/servers/secret/settings/saveSettings/beginArchive/finishArchive/archives/close;实现 `FileArea(root).list/mkdir/check/archive/readPdf`;Windows 原生认证和不覆盖发布通过固定 PowerShell 脚本、stdin JSON 调用。
|
||||
- [x] 重跑测试,验证数据库、文件和错误状态,而不是仅验证替身被调用。
|
||||
|
||||
## Task 2:服务、HTTP 和导出集成
|
||||
|
||||
文件:新增 src/storage-service.cjs、src/storage-api.cjs、tests/storage-http.test.cjs;修改 src/dashboard.cjs、src/server.cjs。
|
||||
|
||||
- [x] 先写认证、角色、同源、脱敏、归档源目录限制、自动归档启用时间和概览真实状态的 HTTP 测试,运行确认失败。
|
||||
- [x] 实现 `StorageService({store,jobs,outputDir,client})`,提供 saveServer/check/list/mkdir/readPdf/archive/automatic/saveSettings/busy/stop。
|
||||
- [x] 接入 `/api/storage`、`/servers`、`/servers/:id/check|files|folders|archive|file`、`/settings`;只有保存凭据需要安全传输,所有文件操作仍要求认证和角色权限。
|
||||
- [x] 正式服务初始化存储服务,PDF 成功记录后调用 automatic,归档失败不把导出改为失败;停止服务等待正在进行的存储操作。
|
||||
- [x] 运行新 HTTP 测试及既有 server/dashboard 测试。
|
||||
|
||||
## Task 3:工作台页面和交付验证
|
||||
|
||||
文件:新增 web/storage.js;修改 web/index.html、web/app.js、README.md、docs/design-requirements.md;新增 tests/storage-ui.test.cjs。
|
||||
|
||||
- [x] 写浏览器场景:添加服务器、密码不回填、检查连接、创建目录、归档成功、只读权限,先运行确认缺少入口。
|
||||
- [x] 新增存储服务器导航、表单、目录浏览、已有 PDF 归档、自动归档设置和历史;错误与处理中状态可见,异步返回受 isActive 保护。
|
||||
- [x] 运行新模块测试、相关现有回归、全部新增脚本语法与 git diff --check。
|
||||
- [x] 更新真实验证结果与实机待验条件,不把已启动但未结束的完整基线称为通过。
|
||||
|
||||
最终验证:相关后端 31/31、两个真实浏览器页面 2/2 通过。完整历史基线中止及实机待验范围见 `docs/verification-2026-10-17.md`。
|
||||
@@ -0,0 +1,19 @@
|
||||
# 可配置业务通知
|
||||
|
||||
2026-10-17 用户要求做成通用、可配置模块,具体业务由同事整理后提供。邮件只复制 BPM 简要说明,按产业通知接口人;PDF 仅存档。
|
||||
|
||||
## 通用入口
|
||||
|
||||
提供独立业务通知页面,配置来源名称、字段路径映射、发件邮箱和明确失败时的尝试上限。字段映射为通知 ID、版本、产业、简要说明、标题、业务时间,支持普通 JSON 对象的点分隔路径,不执行表达式。管理员可粘贴样本预览映射,不创建任务、不发信。标准事件接口接受真实来源数据,重复来源 ID + 版本 + 产业不重复入队;内容变更但版本未变时拒绝静默覆盖。
|
||||
|
||||
产业接口人使用现有产品线群组的 To/Cc,邮箱使用现有托管 SMTP,两个发送时段及公司日历使用已有配置。正文严格取映射后的简要说明,保留换行及原文,不附加 PDF、SMB 地址或模型改写内容。多个事件按已有整理方式逐项或按产业合并,合并时只以空行连接原文。
|
||||
|
||||
未提供业务样本时不把 BPM 列表标题当作简要说明,不猜测产业、不从正文猜收件人、不把全部待阅流程自动入队。后续来源适配器只需调用相同入队接口并按已核实字段配置映射。
|
||||
|
||||
## 队列与调度
|
||||
|
||||
默认暂停发送。启用要求已验证 SMTP、已配置群组及完整字段映射。后台每 30 秒检查,北京时间每日两个时段,遵循现有业务日历。错过执行时段时保留队列,等待下一个正常发送时段,不在重启时立即补发旧批次。空队列不发送。
|
||||
|
||||
发送前冻结正文、标题、收件人与来源版本至本机 notifications/notifications.sqlite,正文及批次内容用 AES-GCM/DPAPI 加密。SMTP 验证失败可在后续时段按配置次数尝试;进入 sendMail 后失败、部分收件人未接受或重启中断,标记结果待核实,不自动重发。管理员填写核验依据后才能标记已发送或重新入队。
|
||||
|
||||
业务配置由管理员修改;操作员可预览和提交来源事件;只读成员查看队列和记录。正式服务器与邮件连通性需要管理员后续录入并验收。自动调度接入不表示 BPM 业务字段已联调。
|
||||
@@ -0,0 +1,23 @@
|
||||
# SMB 存储服务器与通知边界
|
||||
|
||||
依据:2026-10-17 用户确认使用 SMB,工作台管理独立账号和密码并加密保存;PDF 只归档至服务器;业务邮件只复制 BPM 简要说明,通知不同产业的接口人。
|
||||
|
||||
## 本次存储交付
|
||||
|
||||
新增独立“存储服务器”页面,支持服务器名称、主机、共享名、归档子目录、登录账号、密码、启停、连接读写检查、目录浏览、创建目录、下载 PDF,以及将已导出的 PDF 归档到选定目录。支持指定一个自动归档目标,对启用之后新导出的 PDF 自动归档。历史 PDF 由用户选择归档,避免首次启用回灌全部历史。
|
||||
|
||||
使用 Windows 原生 SMB(WNetAddConnection2),不映射盘符、不保存明文凭据至 Windows 命令行、不强制断开已有共享连接。相比维护第三方 SMB 协议客户端,这条路线复用部署机的 SMB 协议与认证支持;相比依赖人工映射盘符,重启后可根据已加密配置重新连接。1219 凭据冲突明确提示用户处理,不清理其他软件的会话。
|
||||
|
||||
服务器配置与归档记录存储在本机 storage/storage.sqlite;账号密码使用现有 AES-GCM/DPAPI 密钥体系加密。接口只返回密码是否存在。编辑留空保留密码,改变主机、共享或账号必须重新填写。配置有版本号,防止覆盖并发修改。管理员维护服务器和自动归档设置;操作员可浏览目录和归档;只读用户查看状态和归档记录。凭据维护沿用回环地址或可信 HTTPS 代理要求。
|
||||
|
||||
文件操作限定在配置的共享及归档根目录,拒绝父目录跳转、绝对路径、设备名和符号链接。目录浏览最多返回 500 项,PDF 下载和归档上限 64 MiB。归档仅接受工作台已有成功导出任务,源文件真实路径必须属于 outputDir。
|
||||
|
||||
归档流程:验证源 PDF → 写入目标目录临时文件 → 校验 SHA-256 → 原生不覆盖重命名发布 → 再验证最终文件 → 记录成功。相同文件幂等成功,不同内容同名使用内容摘要后缀保留两个版本。服务重启时未完成记录显示“已中断”,用户可重试并核对已有同内容文件。归档结果与 PDF 导出结果分别记录。
|
||||
|
||||
## 连接检查与验收
|
||||
|
||||
保存配置不访问服务器。用户点击“检查读写”后,创建本工具随机命名的探测文件,读取核对后仅删除该文件;失败返回可操作的脱敏错误。没有真实服务器地址前,以真实本地文件系统验证目录限制、发布、哈希、幂等、重启记录和 HTTP 权限,不能表述为已完成 210 实机联调。
|
||||
|
||||
## 邮件边界
|
||||
|
||||
归档操作不创建邮件任务,也不向邮件附加 PDF 或自动插入 SMB 地址。邮件正文来源为 BPM 简要说明,不由模型改写。产业到接口人的收件配置继续沿用群组管理。当前列表适配器只存 processInstanceSubject 等列表字段,尚需核实其是否就是页面“简要说明”,再接通通知来源;通知来源与正式收件映射未核实前,不发送业务邮件。
|
||||
@@ -0,0 +1,56 @@
|
||||
# 2026-10-17 通用存储与通知验证
|
||||
|
||||
## 交付范围
|
||||
|
||||
- 通用 SMB 服务器配置、独立凭据加密、读写检查、目录浏览、创建目录、PDF 下载和归档、新导出文件可选自动归档。
|
||||
- 通用通知来源字段映射、中文字段路径、产业收件组、原文预览、版本去重、两时段调度、批次与人工核验。
|
||||
- PDF 归档不生成邮件,业务通知正文仅复制来源简要说明,不附加 PDF。
|
||||
- 实际业务参数由同事整理后在工作台配置;整理表为 `docs/business-configuration.md`。
|
||||
|
||||
## 自动验证结果
|
||||
|
||||
最终相关后端回归:31 项通过,0 失败,0 跳过。
|
||||
|
||||
```text
|
||||
node --test --test-concurrency=2 --test-timeout=180000
|
||||
tests/storage.test.cjs tests/storage-http.test.cjs
|
||||
tests/notifications.test.cjs tests/notifications-http.test.cjs
|
||||
tests/dashboard-http.test.cjs tests/dashboard-navigation.test.cjs
|
||||
tests/server.test.cjs tests/bpm-runtime.test.cjs
|
||||
tests/workspace.test.cjs tests/mail-service.test.cjs tests/mail-http.test.cjs
|
||||
```
|
||||
|
||||
真实 Chrome 界面回归:2 项通过,0 失败,0 跳过。
|
||||
|
||||
```text
|
||||
node --test --test-concurrency=1 --test-timeout=180000
|
||||
tests/storage-ui.test.cjs tests/notifications-ui.test.cjs
|
||||
```
|
||||
|
||||
界面场景覆盖添加服务器、密码不回填、检查读写、创建目录、归档和读取真实本地 PDF、保存来源配置、样本只预览不入队、正文换行实际布局,以及移动视口没有横向溢出。Windows 加密请求在资源争用下耗时较长,浏览器归档用例明确等待保存响应后继续。
|
||||
|
||||
74 个已跟踪及新增 JS/CJS 脚本通过 `node --check`;后续修改的两个界面测试和通知脚本再次通过语法检查。固定 PowerShell 脚本通过本地中文路径实际发布用例;没有使用真实 SMB 账号。
|
||||
|
||||
本地截图:`output/verification/storage-desktop.png`、`output/verification/notifications-desktop.png`;测试数据全部为临时目录和虚构业务信息。后端日志为临时目录中的 `order-final-regression-20261017.log`。
|
||||
|
||||
## 审查与修正
|
||||
|
||||
独立只读审查提出五项问题,均先观察回归失败,再修正并复测:
|
||||
|
||||
1. 从共享边界逐段验证配置根目录,拒绝中间 junction 越界。
|
||||
2. 先按已配置产业筛选再限制队列读取量,避免未配置产业阻塞有效通知。
|
||||
3. 归档结果直接返回更新记录,不从仅 100 条的历史中反查。
|
||||
4. 待核实批次优先展示,较早批次不被普通发送历史遮蔽。
|
||||
5. 邮箱互斥锁获取成功后才消耗发送时段,收信占用时仍能在该时段内重试。
|
||||
|
||||
此外修正 Windows 子进程 UTF-8 输入,中文文件名原生发布已通过;修正简要说明预览被样式折叠换行的问题,浏览器用实际行位置验证。
|
||||
|
||||
复审确认上述五项修正有效,无剩余具体重要问题。
|
||||
|
||||
## 验证范围与运行状态
|
||||
|
||||
本次没有将完整历史测试集称为通过。最初完整基线运行到多个浏览器集成用例,耗时较长而被中止,保留原日志;最终结果仅指以上 33 项相关验证。
|
||||
|
||||
没有真实服务器地址、账号或公司邮箱配置,因此未执行真实 SMB 上传、公司邮件发送或 BPM 业务字段端到端联调。通用来源 API 已就绪,当前不会自动把所有 BPM 待阅条目作为业务通知。
|
||||
|
||||
后台启动正式工作台的隐藏窗口 Start-Process 操作被自动审批拦截,工具原因仅为 `blocked by policy`。未采用其他方式绕过;可由用户手动运行项目 `启动工具.cmd`。隔离运行时的正常启动、停止和重启保留账号已通过上述测试。
|
||||
@@ -0,0 +1,33 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
[Console]::InputEncoding = New-Object System.Text.UTF8Encoding($false)
|
||||
[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
|
||||
try {
|
||||
$orderSmbRequest = [Console]::In.ReadToEnd() | ConvertFrom-Json
|
||||
Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class OrderSmbNative {
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
public struct NETRESOURCE {
|
||||
public int scope, type, displayType, usage;
|
||||
public string localName, remoteName, comment, provider;
|
||||
}
|
||||
[DllImport("mpr.dll", CharSet = CharSet.Unicode)]
|
||||
public static extern int WNetAddConnection2W(ref NETRESOURCE resource, string password, string username, int flags);
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
public static extern bool MoveFileExW(string existingName, string newName, int flags);
|
||||
}
|
||||
'@
|
||||
if ($orderSmbRequest.operation -eq 'connect') {
|
||||
$orderSmbResource = New-Object OrderSmbNative+NETRESOURCE
|
||||
$orderSmbResource.type = 1
|
||||
$orderSmbResource.remoteName = $orderSmbRequest.remote
|
||||
$orderSmbCode = [OrderSmbNative]::WNetAddConnection2W([ref]$orderSmbResource, $orderSmbRequest.password, $orderSmbRequest.username, 4)
|
||||
} elseif ($orderSmbRequest.operation -eq 'publish') {
|
||||
$orderSmbMoved = [OrderSmbNative]::MoveFileExW($orderSmbRequest.source, $orderSmbRequest.target, 8)
|
||||
$orderSmbCode = if ($orderSmbMoved) { 0 } else { [Runtime.InteropServices.Marshal]::GetLastWin32Error() }
|
||||
} else { throw 'Unsupported operation' }
|
||||
@{ ok = ($orderSmbCode -eq 0); code = $orderSmbCode } | ConvertTo-Json -Compress
|
||||
} catch {
|
||||
@{ ok = $false; code = -1 } | ConvertTo-Json -Compress
|
||||
}
|
||||
+8
-2
@@ -4,11 +4,13 @@ const {workspaceApi}=require('./workspace-api.cjs');
|
||||
const {bpmApi}=require('./bpm-api.cjs');
|
||||
const {mailApi}=require('./mail-api.cjs');
|
||||
const {bpmScanApi}=require('./bpm-scan-api.cjs');
|
||||
const {storageApi}=require('./storage-api.cjs');
|
||||
const {notificationApi}=require('./notification-api.cjs');
|
||||
const {SessionStore,SESSION_MS}=require('./dashboard-sessions.cjs');
|
||||
const isLoopback=address=>['127.0.0.1','::1','::ffff:127.0.0.1'].includes(address);
|
||||
const publicJob=({path:ignored,...job})=>({...job,downloadable:job.status==='success'});
|
||||
|
||||
function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,mail,scanner,trustedProxy=false}) {
|
||||
function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,mail,scanner,storage,notifications,trustedProxy=false}) {
|
||||
const sessions=new SessionStore(path.dirname(store.file));const failures=new Map();
|
||||
const sessionCookieName=previewUserId?'order_preview_session':'order_session';
|
||||
const sessionCookiePattern=new RegExp('(?:^|;\\s*)'+sessionCookieName+'=([a-f0-9]{64})(?:;|$)');
|
||||
@@ -20,6 +22,8 @@ function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,ma
|
||||
'/bpm.js':{path:path.join(webRoot,'bpm.js'),type:'text/javascript'},
|
||||
'/mail.js':{path:path.join(webRoot,'mail.js'),type:'text/javascript'},
|
||||
'/orders.js':{path:path.join(webRoot,'orders.js'),type:'text/javascript'},
|
||||
'/storage.js':{path:path.join(webRoot,'storage.js'),type:'text/javascript'},
|
||||
'/notifications.js':{path:path.join(webRoot,'notifications.js'),type:'text/javascript'},
|
||||
'/app.css':{path:path.join(webRoot,'app.css'),type:'text/css'},
|
||||
'/vendor/tabler.css':{path:require.resolve('@tabler/core/dist/css/tabler.min.css'),type:'text/css'},
|
||||
'/vendor/tabler.js':{path:require.resolve('@tabler/core/dist/js/tabler.min.js'),type:'text/javascript'}
|
||||
@@ -82,13 +86,15 @@ function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,ma
|
||||
if(await bpmApi({workspace,bpmSessions,user,sessionId:token,route,method:request.method,body,request,response,reply,trustedProxy}))return;
|
||||
if(await mailApi({mail,workspace,user,route,method:request.method,body,request,response,reply,trustedProxy}))return;
|
||||
if(await bpmScanApi({scanner,workspace,user,sessionId:token,url,route,method:request.method,body,reply}))return;
|
||||
if(await storageApi({storage,workspace,user,url,route,method:request.method,body,request,response,reply,trustedProxy}))return;
|
||||
if(await notificationApi({notifications,workspace,user,route,method:request.method,body,reply}))return;
|
||||
if(workspaceApi({workspace,store,user,route,method:request.method,body,reply,bpmSessions}))return;
|
||||
if(route==='/api/overview' && request.method==='GET') {
|
||||
const jobs=store.jobs();const settings=store.settings();const mailChannels=mail?.store.channels()||[];const mailTemplates=mail?.store.templates()||[];
|
||||
const today=new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date());
|
||||
const todayJobs=jobs.filter(job=>new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date(job.updatedAt))===today);
|
||||
const scan=scanner?.store.status();
|
||||
return reply(200,{stats:{total:jobs.length,today:todayJobs.length,completed:jobs.filter(job=>job.status==='success').length,failed:jobs.filter(job=>['error','interrupted'].includes(job.status)).length,running:jobs.filter(job=>job.status==='running').length},scan,automation:{enabled:false,reason:'待接入订单规则表和归档目录,业务自动处理尚未启用。'},connections:[{name:'PDF 导出',ready:true,detail:'浏览器扩展导出与任务记录已接入'},{name:'订单规则表',ready:false,detail:'等待提供表格,随后配置列映射与筛选'},{name:'BPM 自动扫描',ready:!!scan?.runs.some(r=>r.status==='success'),detail:scan?`${scan.config.enabled?'已开启':'已暂停'},每 ${scan.config.intervalMinutes} 分钟扫描 · 已收录 ${scan.total} 条流程`:'扫描服务未启动'},{name:'210 服务器',ready:false,detail:'等待完整地址、协议和归档目录'},{name:'邮件渠道',ready:mailChannels.some(c=>c.state.smtp&&c.state.imap),detail:`已配置 ${mailChannels.length} 个邮箱`},{name:'邮件模板',ready:mailTemplates.some(t=>t.status==='active'),detail:`${mailTemplates.filter(t=>t.status==='active').length} 个已生效,${mailTemplates.filter(t=>t.status==='pending').length} 个待确认`},{name:'产品线群组',ready:settings.groups.length>0,detail:`已配置 ${settings.groups.length} 个产品线`}],nextSlots:nextSlots(settings.schedule,new Date(),2,workspace?workspace.snapshot(store.users()).calendar.overrides:[]),schedule:settings.schedule,jobs:jobs.slice(0,6).map(publicJob),audit:store.audit().slice(0,5)});
|
||||
return reply(200,{stats:{total:jobs.length,today:todayJobs.length,completed:jobs.filter(job=>job.status==='success').length,failed:jobs.filter(job=>['error','interrupted'].includes(job.status)).length,running:jobs.filter(job=>job.status==='running').length},scan,automation:{enabled:false,reason:'待核实并接入 BPM 业务规则,完整订单自动处理尚未启用。'},connections:[{name:'PDF 导出',ready:true,detail:'浏览器扩展导出与任务记录已接入'},{name:'订单规则表',ready:false,detail:'等待提供表格,随后配置列映射与筛选'},{name:'BPM 自动扫描',ready:!!scan?.runs.some(r=>r.status==='success'),detail:scan?`${scan.config.enabled?'已开启':'已暂停'},每 ${scan.config.intervalMinutes} 分钟扫描 · 已收录 ${scan.total} 条流程`:'扫描服务未启动'},{name:'存储服务器',ready:!!storage?.store.servers().some(s=>s.enabled&&s.state.readable&&s.state.writable),detail:storage?`已配置 ${storage.store.servers().length} 个 SMB 存储服务器`:'存储服务未启动'},{name:'邮件渠道',ready:mailChannels.some(c=>c.state.smtp&&c.state.imap),detail:`已配置 ${mailChannels.length} 个邮箱`},{name:'邮件模板',ready:mailTemplates.some(t=>t.status==='active'),detail:`${mailTemplates.filter(t=>t.status==='active').length} 个已生效,${mailTemplates.filter(t=>t.status==='pending').length} 个待确认`},{name:'产品线群组',ready:settings.groups.length>0,detail:`已配置 ${settings.groups.length} 个产品线`}],nextSlots:nextSlots(settings.schedule,new Date(),2,workspace?workspace.snapshot(store.users()).calendar.overrides:[]),schedule:settings.schedule,jobs:jobs.slice(0,6).map(publicJob),audit:store.audit().slice(0,5)});
|
||||
}
|
||||
if(route==='/api/settings') {
|
||||
if(request.method==='GET')return reply(200,store.settings());
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
'use strict';
|
||||
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
|
||||
async function notificationApi({notifications,workspace,user,route,method,body,reply}){
|
||||
if(!route.startsWith('/api/notifications'))return false;if(!notifications)fail('业务通知服务暂不可用。',503);
|
||||
if(route==='/api/notifications'&&method==='GET'){reply(200,{settings:notifications.store.settings(),items:notifications.store.items(),batches:notifications.store.batches()});return true;}
|
||||
if(method!=='POST')fail('没有找到此通知操作。',404);
|
||||
if(user.role==='viewer')fail('只读成员不能提交通知数据或修改配置。',403);
|
||||
if(route==='/api/notifications/settings'){if(user.role!=='admin')fail('仅管理员可以修改业务通知配置。',403);const saved=notifications.saveSettings(body);workspace?.record(user,'保存业务通知配置',saved.enabled?'已启用':'已暂停');reply(200,saved);return true;}
|
||||
if(route==='/api/notifications/preview'||route==='/api/notifications/events'){if(!body||Object.keys(body).some(k=>k!=='data'))fail('请提交来源数据对象。');const preview=route.endsWith('/preview');const result=preview?notifications.preview(body.data):notifications.ingest(body.data);if(!preview)workspace?.record(user,'通知数据入队',result.sourceId);reply(preview?200:201,result);return true;}
|
||||
const match=/^\/api\/notifications\/batches\/([\w-]+)\/resolve$/.exec(route);if(match){if(user.role!=='admin')fail('仅管理员可以核验发送结果。',403);const result=notifications.resolve(match[1],body,user.username);workspace?.record(user,'核验通知发送结果',match[1]);reply(200,result);return true;}
|
||||
fail('没有找到此通知操作。',404);
|
||||
}
|
||||
module.exports={notificationApi};
|
||||
@@ -0,0 +1,76 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs');const path=require('node:path');const crypto=require('node:crypto');const {DatabaseSync}=require('node:sqlite');const {BpmVault}=require('./bpm-vault.cjs');const {nextSlots}=require('./schedule.cjs');
|
||||
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
|
||||
const hash=value=>crypto.createHash('sha256').update(value).digest('hex');
|
||||
const DEFAULT_MAP={id:'id',version:'version',industry:'industry',brief:'brief',subject:'subject',occurredAt:'occurredAt'};
|
||||
function validateMap(map){if(!map||typeof map!=='object'||Array.isArray(map)||Object.keys(map).some(k=>!Object.hasOwn(DEFAULT_MAP,k)))fail('通知字段映射无效。');for(const key of Object.keys(DEFAULT_MAP)){const p=map[key];if(typeof p!=='string'||p.length>200||(p&&!/^[\p{L}\p{N}_-]+(?:\.[\p{L}\p{N}_-]+)*$/u.test(p))||p.split('.').some(s=>['__proto__','constructor','prototype'].includes(s)))fail('字段路径只支持普通对象的点分隔路径。');if(['id','industry','brief'].includes(key)&&!p)fail('请配置通知 ID、产业与简要说明字段。');}return {...map};}
|
||||
function valueAt(data,p){if(!p)return undefined;for(const part of p.split('.')){if(!data||typeof data!=='object'||!Object.hasOwn(data,part))return undefined;data=data[part];}return data;}
|
||||
class NotificationStore{
|
||||
constructor(dir){fs.mkdirSync(dir,{recursive:true});this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});this.db=new DatabaseSync(path.join(dir,'notifications.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
|
||||
CREATE TABLE IF NOT EXISTS settings(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS items(id TEXT PRIMARY KEY,payload BLOB NOT NULL,status TEXT NOT NULL,attempts INTEGER NOT NULL DEFAULT 0,error TEXT,batch_id TEXT,created_at TEXT NOT NULL,industry TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS batches(id TEXT PRIMARY KEY,status TEXT NOT NULL,payload BLOB NOT NULL,error TEXT,created_at TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);
|
||||
UPDATE items SET status='pending',batch_id=NULL WHERE batch_id IN(SELECT id FROM batches WHERE status='prepared');
|
||||
UPDATE items SET status='unknown',error='服务重启,发送结果需要核实。' WHERE batch_id IN(SELECT id FROM batches WHERE status='sending');
|
||||
UPDATE batches SET status='cancelled' WHERE status='prepared';
|
||||
UPDATE batches SET status='unknown',error='服务重启,发送结果需要核实。' WHERE status='sending';`);
|
||||
this.db.prepare('INSERT OR IGNORE INTO settings VALUES(1,?)').run(JSON.stringify({version:1,enabled:false,sourceKey:crypto.randomUUID(),sourceName:'业务来源',channelId:'',fieldMap:DEFAULT_MAP,maxAttempts:3}));
|
||||
if(!this.db.prepare('PRAGMA table_info(items)').all().some(c=>c.name==='industry')){this.db.exec("ALTER TABLE items ADD COLUMN industry TEXT NOT NULL DEFAULT ''");for(const row of this.db.prepare('SELECT id,payload FROM items').all())this.db.prepare('UPDATE items SET industry=? WHERE id=?').run(this.decode(row.id,row.payload).industry,row.id);}
|
||||
this.db.exec('CREATE INDEX IF NOT EXISTS notification_pending ON items(status,industry,attempts)');
|
||||
}
|
||||
transaction(work){this.db.exec('BEGIN IMMEDIATE');try{const result=work();this.db.exec('COMMIT');return result;}catch(e){this.db.exec('ROLLBACK');throw e;}}
|
||||
encode(id,data){try{return this.vault.encode(id,data);}catch{fail('通知内容加密不可用,请联系管理员。',503);}}
|
||||
decode(id,data){try{return this.vault.decode(id,data);}catch{fail('通知内容无法解密,请联系管理员。',503);}}
|
||||
settings(){return JSON.parse(this.db.prepare('SELECT value FROM settings WHERE id=1').get().value);}
|
||||
saveSettings(input){const old=this.settings();if(!input||Object.keys(input).some(k=>!['version','enabled','sourceKey','sourceName','channelId','fieldMap','maxAttempts'].includes(k)))fail('通知配置无效。');if(input.version!==old.version)fail('通知配置已被修改,请刷新。',409);if(typeof input.enabled!=='boolean'||typeof input.sourceName!=='string'||!input.sourceName.trim()||input.sourceName.length>80||typeof input.channelId!=='string'||input.channelId.length>100||!Number.isInteger(input.maxAttempts)||input.maxAttempts<1||input.maxAttempts>10)fail('请检查来源、邮箱和尝试次数(1–10)。');if(input.sourceKey&&input.sourceKey!==old.sourceKey)fail('来源标识不能更改。');const saved={...input,sourceKey:old.sourceKey,sourceName:input.sourceName.trim(),fieldMap:validateMap(input.fieldMap),version:old.version+1};this.db.prepare('UPDATE settings SET value=? WHERE id=1').run(JSON.stringify(saved));return saved;}
|
||||
scheduleState(){const row=this.db.prepare("SELECT value FROM metadata WHERE key='schedule'").get();return row?JSON.parse(row.value):null;}
|
||||
setSchedule(value){this.db.prepare("INSERT INTO metadata VALUES('schedule',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(JSON.stringify(value));}
|
||||
ingest(event){const id=hash([event.sourceKey,event.sourceId,event.sourceVersion,event.industry].join('\0')),old=this.db.prepare('SELECT * FROM items WHERE id=?').get(id);if(old){const value=this.decode(id,old.payload);if(value.brief!==event.brief||value.subject!==event.subject)fail('同一通知版本的内容已变化,请核实来源版本。',409);return this.item(old);}this.db.prepare('INSERT INTO items(id,payload,status,created_at,industry) VALUES(?,?,?,?,?)').run(id,this.encode(id,event),'pending',new Date().toISOString(),event.industry);return this.item(this.db.prepare('SELECT * FROM items WHERE id=?').get(id));}
|
||||
item({payload,...row}){return {...this.decode(row.id,payload),...row};}
|
||||
items(){return this.db.prepare('SELECT * FROM items ORDER BY rowid DESC LIMIT 100').all().map(r=>this.item(r));}
|
||||
pending(attempts,industries){if(!industries.length)return [];return this.db.prepare("SELECT * FROM items WHERE status IN('pending','blocked') AND attempts<? AND industry IN("+industries.map(()=>'?').join(',')+") ORDER BY rowid LIMIT 200").all(attempts,...industries).map(r=>this.item(r));}
|
||||
blockUnmapped(industries){this.db.prepare("UPDATE items SET status='blocked',error='此产业尚未配置接口人收件组。' WHERE status IN('pending','blocked')"+(industries.length?' AND industry NOT IN('+industries.map(()=>'?').join(',')+')':'')).run(...industries);}
|
||||
block(id,message){this.db.prepare("UPDATE items SET status='blocked',error=? WHERE id=? AND status IN('pending','blocked')").run(message,id);}
|
||||
prepare(items,snapshot){return this.transaction(()=>{const id=crypto.randomUUID();this.db.prepare('INSERT INTO batches VALUES(?,?,?,?,?)').run(id,'prepared',this.encode(id,snapshot),null,new Date().toISOString());for(const item of items){const result=this.db.prepare("UPDATE items SET status='reserved',attempts=attempts+1,error=NULL,batch_id=? WHERE id=? AND status IN('pending','blocked')").run(id,item.id);if(!result.changes)fail('通知队列已变化,请重试。',409);}return id;});}
|
||||
mark(id,status,message=null){this.transaction(()=>{this.db.prepare('UPDATE batches SET status=?,error=? WHERE id=?').run(status,message,id);if(status!=='sending')this.db.prepare('UPDATE items SET status=?,error=? WHERE batch_id=?').run(status==='failed'?'pending':status,message,id);});}
|
||||
batches(){return this.db.prepare("SELECT * FROM batches ORDER BY CASE status WHEN 'unknown' THEN 0 ELSE 1 END,rowid DESC LIMIT 100").all().map(({payload,...r})=>({...this.decode(r.id,payload),...r}));}
|
||||
resolve(id,input,actor){return this.transaction(()=>{const row=this.db.prepare('SELECT * FROM batches WHERE id=?').get(id);if(!row||row.status!=='unknown')fail('只能核验结果待核实的批次。',409);if(!input||!['sent','retry'].includes(input.resolution)||typeof input.note!=='string'||input.note.trim().length<5||input.note.length>2000)fail('请选择核验结果并填写至少 5 字的核验依据。');const data={...this.decode(id,row.payload),resolution:input.resolution,note:input.note.trim(),resolvedBy:actor,resolvedAt:new Date().toISOString()};this.db.prepare('UPDATE batches SET status=?,payload=? WHERE id=?').run('resolved_'+input.resolution,this.encode(id,data),id);this.db.prepare('UPDATE items SET status=?,error=NULL,attempts=CASE WHEN ? THEN 0 ELSE attempts END WHERE batch_id=?').run(input.resolution==='sent'?'sent':'pending',input.resolution==='retry'?1:0,id);return {ok:true};});}
|
||||
close(){if(this.db){this.db.close();this.db=null;}this.vault.destroy();}
|
||||
}
|
||||
class NotificationService{
|
||||
constructor({store,mail,settings,calendar=()=>[],clock=()=>new Date()}){this.store=store;this.mail=mail;this.settings=settings;this.calendar=calendar;this.clock=clock;this.running=null;this.stopped=false;}
|
||||
map(data){if(!data||typeof data!=='object'||Array.isArray(data))fail('通知来源必须是 JSON 对象。');const config=this.store.settings(),raw=Object.fromEntries(Object.entries(config.fieldMap).map(([key,p])=>[key,valueAt(data,p)]));if(!['string','number'].includes(typeof raw.id)||!String(raw.id).trim()||String(raw.id).length>200||/[\x00-\x1f]/.test(String(raw.id))||typeof raw.industry!=='string'||!raw.industry.trim()||raw.industry.length>100||/[\x00-\x1f]/.test(raw.industry)||typeof raw.brief!=='string'||!raw.brief.trim()||raw.brief.length>20000)fail('通知 ID、产业和简要说明不能为空,正文最多 20000 字。');if(raw.subject!==undefined&&(typeof raw.subject!=='string'||raw.subject.length>300||/[\r\n\x00]/.test(raw.subject)))fail('通知标题最多 300 字,不能包含换行。');if(raw.version!==undefined&&(!['string','number'].includes(typeof raw.version)||String(raw.version).length>200||/[\x00-\x1f]/.test(String(raw.version))))fail('来源版本无效。');if(raw.occurredAt!==undefined&&(typeof raw.occurredAt!=='string'||!Number.isFinite(Date.parse(raw.occurredAt))))fail('业务时间无效。');return {source:config.sourceName,sourceKey:config.sourceKey,sourceId:String(raw.id).trim(),sourceVersion:raw.version===undefined||raw.version===''?hash(raw.brief):String(raw.version),industry:raw.industry.trim(),brief:raw.brief,subject:raw.subject||raw.industry.trim()+'业务通知',occurredAt:raw.occurredAt||this.clock().toISOString()};}
|
||||
preview(data){try{const event=this.map(data),group=this.settings().groups.find(g=>g.productLine===event.industry);return {valid:!!group,event,to:group?.to||[],cc:group?.cc||[],issues:group?[]:['此产业尚未配置接口人收件组。']};}catch(e){if(!e.status)throw e;return {valid:false,issues:[e.message]};}}
|
||||
ingest(data){return this.store.ingest(this.map(data));}
|
||||
saveSettings(input){if(this.running)fail('通知正在发送,请稍后修改配置。',409);if(input?.enabled){const c=this.mail.store.publicChannel(input.channelId);if(!c.state.smtp)fail('请先验证发件邮箱的 SMTP 连接。',409);if(!this.settings().groups.length)fail('请先配置产业接口人收件组。',409);}const old=this.store.settings(),saved=this.store.saveSettings(input);if(saved.enabled&&!old.enabled)this.resetSchedule(this.clock());return saved;}
|
||||
resetSchedule(now){const schedule=this.settings().schedule,calendar=this.calendar();const state={signature:JSON.stringify([schedule,calendar]),next:nextSlots(schedule,now,1,calendar)[0]};this.store.setSchedule(state);return state;}
|
||||
tick(now=this.clock()){
|
||||
if(this.stopped||this.running)return this.running||Promise.resolve();
|
||||
const task=this.perform(now);this.running=task;task.finally(()=>{if(this.running===task)this.running=null;}).catch(()=>{});return task;
|
||||
}
|
||||
async perform(now){
|
||||
const config=this.store.settings();if(!config.enabled)return;
|
||||
const settings=this.settings(),calendar=this.calendar(),signature=JSON.stringify([settings.schedule,calendar]);let schedule=this.store.scheduleState();
|
||||
if(!schedule||schedule.signature!==signature){this.resetSchedule(now);return;}if(!schedule.next||Date.parse(schedule.next)>now.getTime())return;
|
||||
const due=Date.parse(schedule.next);if(now.getTime()-due>60000){this.resetSchedule(now);return;}
|
||||
const industries=settings.groups.filter(g=>g.to?.length).map(g=>g.productLine);this.store.blockUnmapped(industries);const grouped=new Map();for(const item of this.store.pending(config.maxAttempts,industries)){const group=settings.groups.find(g=>g.productLine===item.industry);if(!group||!group.to?.length){this.store.block(item.id,'此产业尚未配置接口人收件组。');continue;}const key=settings.schedule.mode==='order'?item.id:item.industry;if(!grouped.has(key))grouped.set(key,{items:[],group});if(grouped.get(key).items.length<50)grouped.get(key).items.push(item);}
|
||||
if(!grouped.size){this.resetSchedule(now);return;}
|
||||
await this.mail.exclusive(config.channelId,async()=>{
|
||||
this.resetSchedule(now);
|
||||
for(const {items,group}of grouped.values()){
|
||||
if(this.stopped)break;
|
||||
const channel=this.mail.store.channelSecret(config.channelId),snapshot={channelId:channel.id,industry:items[0].industry,sourceIds:items.map(i=>i.sourceId),subject:items.length===1?items[0].subject:items[0].industry+'业务通知',text:items.map(i=>i.brief).join('\n\n'),to:[...group.to],cc:[...group.cc],slot:new Date(due).toISOString()};
|
||||
const batch=this.store.prepare(items,snapshot);let transport,sending=false;
|
||||
try{transport=this.mail.smtpFactory(channel.smtp);await transport.verify();this.mail.store.guard(channel.id,channel.version);this.store.mark(batch,'sending');sending=true;
|
||||
const result=await transport.sendMail({from:{address:channel.email,name:channel.name},to:snapshot.to,cc:snapshot.cc,subject:snapshot.subject,text:snapshot.text,attachments:[],messageId:`<${batch}@${channel.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true});
|
||||
const accepted=new Set((result.accepted||[]).map(a=>String(a.address||a).toLowerCase()));if(result.rejected?.length||[...snapshot.to,...snapshot.cc].some(a=>!accepted.has(a.toLowerCase()))){this.store.mark(batch,'unknown','部分收件人未被邮件服务器接受,请核实后处理。');}else this.store.mark(batch,'sent');
|
||||
}catch{this.store.mark(batch,sending?'unknown':'failed',sending?'发信结果待核实,请查询邮件服务器记录。':'SMTP 检查失败,等待下个时段按次数上限重试。');}finally{transport?.close?.();}
|
||||
}
|
||||
}).catch(e=>{if(e.status!==409)throw e;});
|
||||
}
|
||||
resolve(id,input,actor){if(this.running)fail('通知正在发送,请稍后核验。',409);return this.store.resolve(id,input,actor);}
|
||||
start(){this.timer=setInterval(()=>this.tick().catch(()=>{}),30000);this.timer.unref?.();}
|
||||
async stop(){this.stopped=true;clearInterval(this.timer);if(this.running)await this.running.catch(()=>{});}
|
||||
}
|
||||
module.exports={NotificationStore,NotificationService};
|
||||
+16
-8
@@ -13,6 +13,9 @@ const { MailStore } = require('./mail-store.cjs');
|
||||
const { MailService } = require('./mail-service.cjs');
|
||||
const { BpmScanStore } = require('./bpm-scan-store.cjs');
|
||||
const { BpmScanner } = require('./bpm-scanner.cjs');
|
||||
const { StorageStore } = require('./storage-store.cjs');
|
||||
const { StorageService } = require('./storage-service.cjs');
|
||||
const { NotificationStore, NotificationService } = require('./notifications.cjs');
|
||||
|
||||
function createServer(options) {
|
||||
let busy = false;
|
||||
@@ -58,7 +61,8 @@ function createServer(options) {
|
||||
catch(error) {busy=false;jobs.delete(jobId);throw error;}
|
||||
reply(202,{status:'running',jobId});
|
||||
renderSnapshot(snapshot, options).then(result => {
|
||||
options.store?.recordJob({status:'success',jobId,...result});
|
||||
const saved=options.store?.recordJob({status:'success',jobId,...result});
|
||||
if(saved)options.storage?.automatic(saved).catch(()=>{});
|
||||
jobs.set(jobId,{status:'success',jobId,...result});
|
||||
console.log(`已保存:${result.filename} (${result.bytes} bytes)`);
|
||||
}).catch(error=>{const failed={status:'error',jobId,error:error.message || '导出失败。'};jobs.set(jobId,failed);try{options.store?.recordJob(failed);}catch(storeError){console.error('保存任务状态失败:'+storeError.message);}}).finally(()=>{busy=false;});
|
||||
@@ -105,18 +109,20 @@ async function main(options = {}) {
|
||||
const custodian=new BpmCustodian({workspace,manager:bpmSessions});
|
||||
let server;
|
||||
let dashboard;
|
||||
let mailStore,mail,scanStore,scanner;
|
||||
let mailStore,mail,scanStore,scanner,storageStore,storage,notificationStore,notifications;
|
||||
try {
|
||||
mailStore=new MailStore(path.join(stateDir,'mail'));mail=new MailService({store:mailStore});
|
||||
mailStore.migrateLegacy(store.settings().templates);
|
||||
scanStore=new BpmScanStore(path.join(stateDir,'bpm-scan'));scanner=new BpmScanner({store:scanStore,workspace,manager:bpmSessions,settings:()=>store.settings()});
|
||||
storageStore=new StorageStore(path.join(stateDir,'storage'));storage=new StorageService({store:storageStore,jobs:store,outputDir});
|
||||
notificationStore=new NotificationStore(path.join(stateDir,'notifications'));notifications=new NotificationService({store:notificationStore,mail,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides});
|
||||
await bpmSessions.migrateAccounts(workspace.snapshot().connections);
|
||||
workspace.markSessionChecksPending();
|
||||
server=await startService({token,port,outputDir,scale:config.scale,installedExtension,extensionSourceDir:path.join(root,'extension'),store});
|
||||
dashboard=createDashboard({store,workspace,outputDir,bpmSessions,mail,scanner,trustedProxy:dashboardConfig.trustedProxy===true});
|
||||
await new Promise((resolve,reject)=>{dashboard.once('error',reject);dashboard.listen(dashboardPort,dashboardHost,resolve);});store.recoverJobs();mailStore.recoverSends();custodian.start();mail.start();scanner.start();
|
||||
server=await startService({token,port,outputDir,scale:config.scale,installedExtension,extensionSourceDir:path.join(root,'extension'),store,storage});
|
||||
dashboard=createDashboard({store,workspace,outputDir,bpmSessions,mail,scanner,storage,notifications,trustedProxy:dashboardConfig.trustedProxy===true});
|
||||
await new Promise((resolve,reject)=>{dashboard.once('error',reject);dashboard.listen(dashboardPort,dashboardHost,resolve);});store.recoverJobs();mailStore.recoverSends();custodian.start();mail.start();scanner.start();notifications.start();
|
||||
}
|
||||
catch(error){if(server?.listening)await new Promise(resolve=>server.close(resolve));if(dashboard?.listening)await new Promise(resolve=>dashboard.close(resolve));await scanner?.stop();scanStore?.close();await mail?.stop();mailStore?.close();await bpmSessions.shutdown();workspace.close();throw error;}
|
||||
catch(error){if(server?.listening)await new Promise(resolve=>server.close(resolve));if(dashboard?.listening)await new Promise(resolve=>dashboard.close(resolve));await notifications?.stop();notificationStore?.close();await storage?.stop();storageStore?.close();await scanner?.stop();scanStore?.close();await mail?.stop();mailStore?.close();await bpmSessions.shutdown();workspace.close();throw error;}
|
||||
if(!options.quiet){
|
||||
console.log('订单通知中心已启动。\nWeb 工作台支持业务日历、异常待办与转交、BPM 连接管理。\n在 Chrome 订单页仍可点击扩展中的“导出当前订单”。');
|
||||
console.log(`首次使用:Chrome 扩展管理 → 开发者模式 → 加载已解压的扩展程序\n选择目录:${installedExtension}\n输出目录:${outputDir}\n本地服务:http://127.0.0.1:${port}`);
|
||||
@@ -125,13 +131,15 @@ async function main(options = {}) {
|
||||
}
|
||||
let stopping;
|
||||
const stop=()=>stopping ||= (async()=>{
|
||||
await scanner.stop();await mail.stop();await custodian.stop();await bpmSessions.shutdown();
|
||||
await notifications.stop();await storage.stop();await scanner.stop();await mail.stop();await custodian.stop();await bpmSessions.shutdown();
|
||||
await Promise.all([dashboard,server].map(socket=>new Promise((resolve,reject)=>socket.close(error=>error?reject(error):resolve()))));
|
||||
workspace.close();
|
||||
mailStore.close();
|
||||
scanStore.close();
|
||||
storageStore.close();
|
||||
notificationStore.close();
|
||||
})();
|
||||
return {server,dashboard,workspace,bpmSessions,custodian,mail,scanner,stop};
|
||||
return {server,dashboard,workspace,bpmSessions,custodian,mail,scanner,storage,notifications,stop};
|
||||
}
|
||||
if (require.main === module) main().then(app=>{
|
||||
const stop=()=>app.stop().then(()=>process.exit(0),()=>process.exit(1));
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
'use strict';
|
||||
const {execFile}=require('node:child_process');
|
||||
const fs=require('node:fs/promises');
|
||||
const path=require('node:path');
|
||||
|
||||
const messages={5:'存储服务器拒绝访问,请检查账号权限。',53:'找不到存储服务器,请检查地址与网络。',67:'找不到共享目录,请检查共享名称。',86:'SMB 账号或密码不正确。',1326:'SMB 账号或密码不正确。',1219:'此服务器已使用其他账号连接,请先由管理员处理 Windows SMB 凭据冲突。',183:'目标文件已存在。',80:'目标文件已存在。'};
|
||||
function native(operation,input){
|
||||
return new Promise((resolve,reject)=>{
|
||||
const child=execFile('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-ExecutionPolicy','Bypass','-File',path.resolve(__dirname,'../scripts/smb-native.ps1')],{windowsHide:true,timeout:25000,maxBuffer:16384,encoding:'utf8'},(error,stdout)=>{
|
||||
let result;try{result=JSON.parse(stdout.replace(/^\uFEFF/,''));}catch{}
|
||||
if(result?.ok)return resolve();
|
||||
const code=result?.code;const failure=Object.assign(new Error(messages[code]||'SMB 操作未完成,请检查网络、共享权限或服务器状态。'),{status:502});
|
||||
if([80,183].includes(code))failure.code='EEXIST';
|
||||
if(error?.killed)failure.message='SMB 操作超时,请检查服务器和网络。';
|
||||
reject(failure);
|
||||
});
|
||||
child.stdin.on('error',()=>{});child.stdin.end(JSON.stringify({operation,...input}));
|
||||
});
|
||||
}
|
||||
async function connect(server){
|
||||
if(process.platform!=='win32')throw Object.assign(new Error('SMB 连接需要在 Windows 部署机运行。'),{status:503});
|
||||
await native('connect',{remote:`\\\\${server.host}\\${server.share}`,username:server.username,password:server.password});
|
||||
}
|
||||
async function publishExclusive(source,target){
|
||||
if(process.platform==='win32')return native('publish',{source,target});
|
||||
await fs.link(source,target);await fs.unlink(source);
|
||||
}
|
||||
module.exports={connect,publishExclusive};
|
||||
@@ -0,0 +1,26 @@
|
||||
'use strict';
|
||||
const {secureBpmTransport}=require('./bpm-api.cjs');
|
||||
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
|
||||
function payload(body,keys){if(!body||Object.keys(body).some(k=>!keys.includes(k)))fail('存储操作参数无效。');}
|
||||
async function storageApi({storage,workspace,user,url,route,method,body,request,response,reply,trustedProxy}){
|
||||
if(!route.startsWith('/api/storage'))return false;if(!storage)fail('存储服务暂不可用。',503);
|
||||
const audit=(action,detail)=>workspace?.record(user,action,detail);
|
||||
if(route==='/api/storage'&&method==='GET'){reply(200,{servers:storage.store.servers(),settings:storage.store.settings(),archives:storage.store.archives()});return true;}
|
||||
if(user.role==='viewer')fail('仅管理员和操作员可以操作归档文件。',403);
|
||||
if(route==='/api/storage/servers'&&method==='POST'){
|
||||
if(user.role!=='admin')fail('仅管理员可以维护存储服务器。',403);
|
||||
if(!secureBpmTransport(request,trustedProxy))fail('请在部署机本地或 HTTPS 页面维护存储账号。',403);
|
||||
const saved=storage.saveServer(body);audit('保存存储服务器',saved.name);reply(body.id?200:201,saved);return true;
|
||||
}
|
||||
if(route==='/api/storage/settings'&&method==='POST'){if(user.role!=='admin')fail('仅管理员可以修改自动归档设置。',403);payload(body,['serverId','enabled']);const saved=storage.saveSettings(body);audit('保存自动归档设置',saved.enabled?'已启用':'已暂停');reply(200,saved);return true;}
|
||||
const match=/^\/api\/storage\/servers\/([\w-]+)\/(check|files|folders|archive|file)$/.exec(route);
|
||||
if(match){const [,id,action]=match;
|
||||
if(action==='check'&&method==='POST'){if(user.role!=='admin')fail('仅管理员可以检查存储服务器。',403);payload(body,[]);const checked=await storage.check(id);audit('检查存储服务器',checked.name);reply(200,checked);return true;}
|
||||
if(action==='files'&&method==='GET'){reply(200,await storage.list(id,url.searchParams.get('path')||''));return true;}
|
||||
if(action==='folders'&&method==='POST'){payload(body,['path']);const result=await storage.mkdir(id,body.path);audit('创建归档目录',result.path);reply(201,result);return true;}
|
||||
if(action==='archive'&&method==='POST'){payload(body,['jobId','directory']);const result=await storage.archive(id,body.jobId,body.directory??'',user.username);audit('PDF 归档完成',result.relativePath);reply(200,result);return true;}
|
||||
if(action==='file'&&method==='GET'){const file=await storage.readPdf(id,url.searchParams.get('path')||'');response.writeHead(200,{'Content-Type':'application/pdf','Content-Disposition':"attachment; filename*=UTF-8''"+encodeURIComponent(file.filename)});response.end(file.bytes);return true;}
|
||||
}
|
||||
fail('没有找到此存储操作。',404);
|
||||
}
|
||||
module.exports={storageApi};
|
||||
@@ -0,0 +1,67 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs/promises');
|
||||
const path=require('node:path');
|
||||
const crypto=require('node:crypto');
|
||||
const native=require('./smb-native.cjs');
|
||||
const MAX_FILE=64*1024*1024;
|
||||
const fail=(message,status=400)=>Object.assign(new Error(message),{status});
|
||||
function segments(relative=''){
|
||||
if(typeof relative!=='string'||relative.length>1500||/^[\\/]|[<>:"|?*\x00-\x1f]/.test(relative))throw fail('请使用归档目录内的相对路径。');
|
||||
if(!relative)return [];
|
||||
const parts=relative.replace(/\\/g,'/').split('/');
|
||||
if(parts.some(p=>!p||p==='.'||p==='..'||/[. ]$/.test(p)||/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(p)||p.length>200))throw fail('目录或文件名无效,不能跳转到归档根目录之外。');
|
||||
return parts;
|
||||
}
|
||||
function inside(root,file){const rel=path.relative(root,file);return !path.isAbsolute(rel)&&rel!=='..'&&!rel.startsWith('..'+path.sep);}
|
||||
function digest(bytes){return crypto.createHash('sha256').update(bytes).digest('hex');}
|
||||
async function pdf(file){const info=await fs.stat(file);if(!info.isFile()||info.size>MAX_FILE)throw fail('PDF 必须为不超过 64 MiB 的文件。');const bytes=await fs.readFile(file);if(bytes.length>MAX_FILE||bytes.subarray(0,5).toString()!=='%PDF-')throw fail('文件不是有效的 PDF。');return bytes;}
|
||||
class FileArea{
|
||||
constructor(root,{boundary=root}={}){this.root=path.resolve(root);this.boundary=path.resolve(boundary);if(!inside(this.boundary,this.root))throw fail('归档根目录超出共享目录。');}
|
||||
async resolve(relative='',create=false){
|
||||
const prefix=segments(path.relative(this.boundary,this.root)),parts=[...prefix,...segments(relative)];let current=this.boundary;
|
||||
const rootInfo=await fs.lstat(current);if(rootInfo.isSymbolicLink()||!rootInfo.isDirectory())throw fail('归档根目录不可用或为目录链接。');
|
||||
const realRoot=await fs.realpath(current);
|
||||
for(const [index,part]of parts.entries()){
|
||||
current=path.join(current,part);
|
||||
if(create&&index>=prefix.length)try{await fs.mkdir(current);}catch(e){if(e.code!=='EEXIST')throw e;}
|
||||
const info=await fs.lstat(current);if(info.isSymbolicLink())throw fail('不能访问目录链接。');
|
||||
if(!inside(realRoot,await fs.realpath(current)))throw fail('路径超出归档根目录。');
|
||||
}
|
||||
return current;
|
||||
}
|
||||
async list(relative=''){
|
||||
const directory=await this.resolve(relative),entries=[];let truncated=false;
|
||||
const iterator=await fs.opendir(directory);
|
||||
for await(const entry of iterator){if(entry.name.startsWith('.order-'))continue;if(entries.length>=500){truncated=true;break;}entries.push({name:entry.name,type:entry.isSymbolicLink()?'blocked':entry.isDirectory()?'directory':'file'});}
|
||||
entries.sort((a,b)=>(a.type==='directory'?0:1)-(b.type==='directory'?0:1)||a.name.localeCompare(b.name,'zh-CN'));
|
||||
return {path:segments(relative).join('/'),entries,truncated};
|
||||
}
|
||||
async mkdir(relative){if(!segments(relative).length)throw fail('请输入要创建的目录名称。');await this.resolve(relative,true);return {path:segments(relative).join('/')};}
|
||||
async check(){
|
||||
const root=await this.resolve(''),file=path.join(root,'.order-probe-'+crypto.randomUUID()),bytes=crypto.randomBytes(32);let owned=false;
|
||||
try{await fs.writeFile(file,bytes,{flag:'wx'});owned=true;if(!(await fs.readFile(file)).equals(bytes))throw fail('共享目录读写校验失败。',502);}finally{if(owned)await fs.unlink(file);}
|
||||
return {readable:true,writable:true};
|
||||
}
|
||||
async readPdf(relative){if(path.extname(relative).toLowerCase()!=='.pdf')throw fail('仅支持下载归档 PDF。');const file=await this.resolve(relative);return {bytes:await pdf(file),filename:path.basename(file)};}
|
||||
async archive(source,filename,relative=''){
|
||||
if(segments(filename).length!==1||path.extname(filename).toLowerCase()!=='.pdf')throw fail('归档文件名必须为 PDF 文件名。');
|
||||
const bytes=await pdf(source),sha256=digest(bytes),directory=await this.resolve(relative,true);
|
||||
const same=async target=>{try{return digest(await pdf(target))===sha256;}catch(e){if(e.code==='ENOENT')return false;if(e.status===400)return false;throw e;}};
|
||||
const candidateNames=[filename,filename.slice(0,-4).slice(0,130)+'_'+sha256+'.pdf'];
|
||||
for(const name of candidateNames){
|
||||
const target=path.join(directory,name);const result={filename:name,relativePath:[...segments(relative),name].join('/'),bytes:bytes.length,sha256};
|
||||
try{const stat=await fs.lstat(target);if(stat.isSymbolicLink())throw fail('目标文件为链接,不能归档。');if(await same(target))return result;continue;}catch(e){if(e.code!=='ENOENT')throw e;}
|
||||
const temp=path.join(directory,'.order-upload-'+crypto.randomUUID());
|
||||
try{
|
||||
await fs.writeFile(temp,bytes,{flag:'wx'});if(!await same(temp))throw fail('上传后校验失败,请重试。',502);
|
||||
try{await native.publishExclusive(temp,target);}catch(e){if(e.code!=='EEXIST')throw e;if(!await same(target))continue;}
|
||||
if(!await same(target))throw fail('归档文件校验失败,请检查服务器。',502);return result;
|
||||
}finally{await fs.unlink(temp).catch(e=>{if(e.code!=='ENOENT')throw e;});}
|
||||
}
|
||||
throw fail('存在同名文件且内容不同,请选择其他归档目录。',409);
|
||||
}
|
||||
}
|
||||
class SmbClient{
|
||||
async area(server){await native.connect(server);const boundary=path.win32.join('\\\\'+server.host,server.share),root=path.win32.join(boundary,...segments(server.directory));return new FileArea(root,{boundary});}
|
||||
}
|
||||
module.exports={FileArea,SmbClient,segments,inside,MAX_FILE};
|
||||
@@ -0,0 +1,33 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs/promises');const path=require('node:path');
|
||||
const {SmbClient,segments,inside}=require('./storage-files.cjs');
|
||||
const fail=(message,status=400)=>Object.assign(new Error(message),{status});
|
||||
const safe=e=>e.status?e:fail(({ENOENT:'找不到文件或归档目录,请检查路径。',EACCES:'没有共享目录访问权限。',EPERM:'没有共享目录操作权限。',ENOSPC:'存储服务器空间不足。',ENOTDIR:'指定路径不是目录。'})[e.code]||'存储操作未完成,请检查服务器与网络。',502);
|
||||
class StorageService{
|
||||
constructor({store,jobs,outputDir,client=new SmbClient()}){this.store=store;this.jobs=jobs;this.outputDir=outputDir;this.client=client;this.running=new Map();this.stopped=false;}
|
||||
busy(id){return this.running.has(id);}
|
||||
saveServer(input){if(input?.id&&this.busy(input.id))throw fail('此服务器正在执行操作,请稍后保存。',409);return this.store.saveServer(input);}
|
||||
saveSettings(input){if(input?.enabled){const server=this.store.publicServer(input.serverId);if(!server.enabled||!server.state.readable||!server.state.writable)throw fail('请先启用服务器并检查读写成功。',409);}return this.store.saveSettings(input);}
|
||||
run(id,work){
|
||||
if(this.stopped)return Promise.reject(fail('存储服务正在停止。',503));
|
||||
const previous=this.running.get(id)||Promise.resolve();
|
||||
const task=previous.catch(()=>{}).then(async()=>{const server=this.store.secret(id);if(!server.enabled)throw fail('此存储服务器已停用。',409);try{return await work(server);}catch(e){throw safe(e);}});
|
||||
this.running.set(id,task);task.finally(()=>{if(this.running.get(id)===task)this.running.delete(id);}).catch(()=>{});return task;
|
||||
}
|
||||
check(id){return this.run(id,async server=>{try{const area=await this.client.area(server),result=await area.check();const state={...result,checkedAt:new Date().toISOString(),message:'共享目录读写正常'};this.store.setState(id,server.version,state);return this.store.publicServer(id);}catch(e){const error=safe(e);this.store.setState(id,server.version,{readable:false,writable:false,checkedAt:new Date().toISOString(),message:error.message});throw error;}});}
|
||||
list(id,relative){return this.run(id,async server=>(await this.client.area(server)).list(relative));}
|
||||
mkdir(id,relative){return this.run(id,async server=>(await this.client.area(server)).mkdir(relative));}
|
||||
readPdf(id,relative){return this.run(id,async server=>(await this.client.area(server)).readPdf(relative));}
|
||||
archive(id,jobId,directory='',actor='自动归档'){
|
||||
return this.run(id,async server=>{
|
||||
segments(directory);if(typeof jobId!=='string'||!jobId||jobId.length>200)throw fail('请选择已完成的 PDF 导出任务。');
|
||||
const job=this.jobs.jobs().find(j=>j.jobId===jobId);if(!job||job.status!=='success'||typeof job.path!=='string')throw fail('请选择已完成且存在的 PDF。');
|
||||
const record=this.store.beginArchive(id,jobId,actor,directory);
|
||||
try{const [root,file]=await Promise.all([fs.realpath(this.outputDir),fs.realpath(job.path)]);if(!inside(root,file)||file===root||path.extname(file).toLowerCase()!=='.pdf')throw fail('PDF 不在本工具输出目录内。');const area=await this.client.area(server),result=await area.archive(file,path.basename(file),directory);return this.store.finishArchive(record.id,'success',{...result,serverName:server.name});}
|
||||
catch(e){const error=safe(e);this.store.finishArchive(record.id,'error',{error:error.message,serverName:server.name});throw error;}
|
||||
});
|
||||
}
|
||||
async automatic(job){const settings=this.store.settings();if(!settings.enabled||job.status!=='success'||!job.createdAt||job.createdAt<settings.since)return null;return this.archive(settings.serverId,job.jobId,'','自动归档');}
|
||||
async stop(){this.stopped=true;await Promise.allSettled([...this.running.values()]);}
|
||||
}
|
||||
module.exports={StorageService};
|
||||
@@ -0,0 +1,51 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs');
|
||||
const path=require('node:path');
|
||||
const crypto=require('node:crypto');
|
||||
const {DatabaseSync}=require('node:sqlite');
|
||||
const {BpmVault}=require('./bpm-vault.cjs');
|
||||
const {segments}=require('./storage-files.cjs');
|
||||
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
|
||||
const text=(v,label,max=200)=>{if(typeof v!=='string'||!v.trim()||v.length>max||/[\x00-\x1f]/.test(v))fail(label+'格式不正确。');return v.trim();};
|
||||
const now=()=>new Date().toISOString();
|
||||
class StorageStore{
|
||||
constructor(dir){
|
||||
fs.mkdirSync(dir,{recursive:true});this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});
|
||||
this.db=new DatabaseSync(path.join(dir,'storage.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
|
||||
CREATE TABLE IF NOT EXISTS servers(id TEXT PRIMARY KEY,version INTEGER NOT NULL,payload BLOB NOT NULL,state TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS settings(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL);
|
||||
INSERT OR IGNORE INTO settings VALUES(1,'{"serverId":"","enabled":false,"since":null}');
|
||||
CREATE TABLE IF NOT EXISTS archives(id TEXT PRIMARY KEY,server_id TEXT NOT NULL,job_id TEXT NOT NULL,status TEXT NOT NULL,value TEXT NOT NULL,UNIQUE(server_id,job_id));
|
||||
UPDATE archives SET status='interrupted' WHERE status='running';`);
|
||||
}
|
||||
row(id){if(typeof id!=='string')fail('请选择存储服务器。');const row=this.db.prepare('SELECT * FROM servers WHERE id=?').get(id);if(!row)fail('存储服务器不存在。',404);return row;}
|
||||
secret(id){const row=this.row(id);try{return {...this.vault.decode(id,row.payload),id,version:row.version,state:JSON.parse(row.state)};}catch{fail('存储凭据无法解密,请联系管理员。',503);}}
|
||||
publicServer(id){const {password,...server}=this.secret(id);return {...server,hasPassword:!!password};}
|
||||
servers(){return this.db.prepare('SELECT id FROM servers ORDER BY rowid').all().map(r=>this.publicServer(r.id));}
|
||||
saveServer(input){
|
||||
const fields=['id','version','name','host','share','directory','username','password','enabled','state','hasPassword','createdAt','updatedAt'];
|
||||
if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).some(k=>!fields.includes(k)))fail('存储服务器配置无效。');
|
||||
const old=input.id?this.secret(input.id):null;if(old&&input.version!==old.version)fail('服务器已被修改,请刷新后重试。',409);
|
||||
const host=text(input.host,'服务器地址',253).toLowerCase();if(!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(host)||host.includes('..'))fail('服务器地址只填写主机名或 IPv4 地址。');
|
||||
const share=text(input.share,'共享名称',80);if(segments(share).length!==1)fail('共享名称不能包含路径。');
|
||||
const username=text(input.username,'登录账号',200),directory=segments(input.directory).join('/');
|
||||
if(typeof input.enabled!=='boolean')fail('请选择服务器是否启用。');
|
||||
if(old&&input.password===''&&(host!==old.host||share!==old.share||username!==old.username))fail('更换服务器、共享或登录账号时,请重新填写密码。');
|
||||
const password=input.password===''&&old?old.password:input.password;if(typeof password!=='string'||!password||password.length>2048)fail('请输入 SMB 登录密码。');
|
||||
const id=old?.id||crypto.randomUUID(),saved={name:text(input.name,'服务器名称',80),host,share,directory,username,password,enabled:input.enabled,createdAt:old?.createdAt||now(),updatedAt:now()};
|
||||
let payload;try{payload=this.vault.encode(id,saved);}catch{fail('存储凭据加密不可用,请联系管理员。',503);}
|
||||
const changed=!old||['host','share','directory','username','password'].some(k=>saved[k]!==old[k]);
|
||||
const state=changed?{checkedAt:null,readable:false,writable:false,message:'待检查连接'}:old.state;
|
||||
this.db.prepare('INSERT INTO servers VALUES(?,?,?,?) ON CONFLICT(id) DO UPDATE SET version=excluded.version,payload=excluded.payload,state=excluded.state').run(id,(old?.version||0)+1,payload,JSON.stringify(state));
|
||||
if(old&&(!saved.enabled||changed)&&this.settings().serverId===id)this.saveSettings({serverId:id,enabled:false});
|
||||
return this.publicServer(id);
|
||||
}
|
||||
setState(id,version,state){if(this.row(id).version!==version)fail('服务器配置已变化,请重试。',409);this.db.prepare('UPDATE servers SET state=? WHERE id=?').run(JSON.stringify(state),id);}
|
||||
settings(){return JSON.parse(this.db.prepare('SELECT value FROM settings WHERE id=1').get().value);}
|
||||
saveSettings(input){if(!input||Object.keys(input).some(k=>!['serverId','enabled'].includes(k))||typeof input.serverId!=='string'||typeof input.enabled!=='boolean')fail('自动归档设置无效。');if(input.serverId)this.row(input.serverId);if(input.enabled&&!input.serverId)fail('请选择自动归档服务器。');const old=this.settings();const saved={...input,since:input.enabled?(old.enabled&&old.serverId===input.serverId?old.since:now()):null};this.db.prepare('UPDATE settings SET value=? WHERE id=1').run(JSON.stringify(saved));return saved;}
|
||||
beginArchive(serverId,jobId,actor,directory){const prior=this.db.prepare('SELECT id,value FROM archives WHERE server_id=? AND job_id=?').get(serverId,jobId),id=prior?.id||crypto.randomUUID();const value={...(prior?JSON.parse(prior.value):{}),actor,directory,startedAt:now(),finishedAt:null,error:null};this.db.prepare('INSERT INTO archives VALUES(?,?,?,?,?) ON CONFLICT(server_id,job_id) DO UPDATE SET status=excluded.status,value=excluded.value').run(id,serverId,jobId,'running',JSON.stringify(value));return {id,serverId,jobId,status:'running',...value};}
|
||||
finishArchive(id,status,patch){const row=this.db.prepare('SELECT value FROM archives WHERE id=?').get(id);const value={...JSON.parse(row.value),...patch,finishedAt:now()};const saved=this.db.prepare('UPDATE archives SET status=?,value=? WHERE id=? RETURNING id,server_id AS serverId,job_id AS jobId,status').get(status,JSON.stringify(value),id);return {...value,...saved};}
|
||||
archives(){return this.db.prepare("SELECT id,server_id AS serverId,job_id AS jobId,status,value FROM archives ORDER BY COALESCE(json_extract(value,'$.finishedAt'),json_extract(value,'$.startedAt')) DESC,rowid DESC LIMIT 100").all().map(({value,...r})=>({...JSON.parse(value),...r}));}
|
||||
close(){if(this.db){this.db.close();this.db=null;}this.vault.destroy();}
|
||||
}
|
||||
module.exports={StorageStore};
|
||||
@@ -0,0 +1,9 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');const {Store}=require('../src/dashboard-store.cjs');const {NotificationStore,NotificationService}=require('../src/notifications.cjs');const {createDashboard}=require('../src/dashboard.cjs');
|
||||
test('notification HTTP exposes configurable mapping and preview without sending, with role and origin checks',async t=>{
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'notice-http-')),store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');for(const role of ['operator','viewer'])store.addUser({username:role,password:'Test-password-123',role},'admin');const notificationStore=new NotificationStore(path.join(dir,'notifications')),notifications=new NotificationService({store:notificationStore,mail:{},settings:()=>store.settings()}),server=createDashboard({store,notifications,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{await notifications.stop();server.closeAllConnections();await new Promise(r=>server.close(r));notificationStore.close();await fs.rm(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+server.address().port,call=(route,body,cookie,origin=base)=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{'Content-Type':'application/json',Origin:origin}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)}),login=async username=>(await call('/api/login',{username,password:'Test-password-123'})).headers.get('set-cookie').split(';')[0];
|
||||
assert.equal((await call('/api/notifications')).status,401);const admin=await login('admin'),operator=await login('operator'),viewer=await login('viewer');const config=notificationStore.settings();assert.equal((await call('/api/notifications/settings',config,operator)).status,403);assert.equal((await call('/api/notifications/settings',config,admin,'https://evil.test')).status,403);assert.equal((await call('/api/notifications/settings',config,admin)).status,200);
|
||||
const data={id:'external-1',industry:'待配置产业',brief:'简要说明原文\n保持换行'};const preview=await(await call('/api/notifications/preview',{data},operator)).json();assert.equal(preview.event.brief,data.brief);assert.equal(notificationStore.items().length,0);
|
||||
assert.equal((await call('/api/notifications/events',{data},viewer)).status,403);assert.equal((await call('/api/notifications/events',{data},operator)).status,201);assert.equal(notificationStore.items().length,1);
|
||||
assert.equal((await call('/api/notifications',undefined,viewer)).status,200);
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');const {Store}=require('../src/dashboard-store.cjs');const {NotificationStore,NotificationService}=require('../src/notifications.cjs');const {createDashboard}=require('../src/dashboard.cjs');const {loadPlaywright,browserOptions}=require('../src/runtime.cjs');
|
||||
test('notification page saves field maps and previews original text without queuing or sending',{timeout:90000},async t=>{
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'notice-ui-')),store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');const notificationStore=new NotificationStore(path.join(dir,'notifications')),notifications=new NotificationService({store:notificationStore,mail:{},settings:()=>store.settings()}),server=createDashboard({store,notifications,outputDir:dir});await new Promise(r=>server.listen(0,'127.0.0.1',r));let browser;t.after(async()=>{await browser?.close();await notifications.stop();server.closeAllConnections();await new Promise(r=>server.close(r));notificationStore.close();await fs.rm(dir,{recursive:true,force:true});});browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(6000);const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto('http://127.0.0.1:'+server.address().port+'/#notifications');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByLabel('来源名称',{exact:true}).fill('团队业务');await page.getByRole('button',{name:'保存通知配置',exact:true}).click();await page.getByText('业务通知配置已保存。',{exact:true}).waitFor();assert.equal(notificationStore.settings().sourceName,'团队业务');await page.getByLabel('来源 JSON 样本',{exact:true}).fill(JSON.stringify({id:'SAMPLE-001',industry:'同事后续配置',brief:'原始简要说明\n第二行'}));await page.getByRole('button',{name:'预览字段映射',exact:true}).click();await page.locator('#notification-preview pre').getByText('原始简要说明\n第二行',{exact:true}).waitFor();assert.equal(notificationStore.items().length,0);assert.equal(await page.locator('#notification-preview pre').evaluate(el=>{const node=el.firstChild,index=node.textContent.indexOf('\n'),range=document.createRange();range.setStart(node,0);range.setEnd(node,1);const first=range.getBoundingClientRect().top;range.setStart(node,index+1);range.setEnd(node,index+2);return range.getBoundingClientRect().top>first;}),true);await fs.mkdir(path.resolve('output/verification'),{recursive:true});await page.evaluate(()=>window.scrollTo(0,0));await page.screenshot({path:path.resolve('output/verification/notifications-desktop.png'),fullPage:true});await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.deepEqual(errors,[]);
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');
|
||||
const {NotificationStore,NotificationService}=require('../src/notifications.cjs');const {MailStore}=require('../src/mail-store.cjs');const {MailService}=require('../src/mail-service.cjs');
|
||||
const fields={id:'flow.id',version:'flow.version',industry:'flow.industry',brief:'flow.brief',subject:'flow.subject',occurredAt:'flow.at'};
|
||||
const event={flow:{id:'FLOW-001',version:'v1',industry:'宽带',brief:'第一行原文\n第二行 <原文> & 保留',subject:'业务提醒',at:'2026-10-17T08:00:00+08:00'}};
|
||||
async function fixture(t,{uncertain=false}={}){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-notice-'));const store=new NotificationStore(path.join(dir,'notifications'));const mailStore=new MailStore(path.join(dir,'mail'));const channel=mailStore.saveChannel({name:'工作邮箱',email:'notice@company.test',smtp:{host:'smtp.company.test',port:465,security:'tls',user:'notice',password:'Fixture-only-password'},imap:{host:'imap.company.test',port:993,security:'tls',user:'notice',password:'Fixture-only-password'},senders:['author@company.test'],enabled:false});mailStore.setState(channel.id,1,{smtp:true});const sent=[];const mail=new MailService({store:mailStore,smtpFactory:()=>({verify:async()=>{},sendMail:async payload=>{sent.push(payload);if(uncertain)throw new Error('socket disconnected');return {accepted:['interface@company.test'],rejected:[]};},close(){}})});const service=new NotificationService({store,mail,settings:()=>({schedule:{times:['09:00','17:00'],timezone:'Asia/Shanghai',weekends:true,mode:'product_line',missed:'next_window'},groups:[{productLine:'宽带',to:['interface@company.test'],cc:[]}]}),calendar:()=>[],clock:()=>new Date('2026-10-17T08:59:00+08:00')});service.saveSettings({version:1,enabled:false,sourceName:'业务流程',channelId:channel.id,fieldMap:fields,maxAttempts:3});t.after(async()=>{await service.stop();await mail.stop();store.close();mailStore.close();await fs.rm(dir,{recursive:true,force:true});});return {dir,store,service,sent,channel};}
|
||||
|
||||
test('mapped notifications copy brief text, deduplicate versions and send no attachments at a configured slot',async t=>{
|
||||
const {store,service,sent}=await fixture(t);const preview=service.preview(event);assert.equal(preview.event.brief,event.flow.brief);assert.equal(store.items().length,0);
|
||||
const item=service.ingest(event);assert.equal(service.ingest(event).id,item.id);assert.equal(store.items().length,1);
|
||||
assert.throws(()=>service.ingest({flow:{...event.flow,brief:'changed without version'}}),e=>e.status===409);
|
||||
service.saveSettings({...store.settings(),sourceName:'来源改名'});assert.equal(service.ingest(event).id,item.id);
|
||||
await service.tick(new Date('2026-10-17T09:00:01+08:00'));assert.equal(sent.length,0);
|
||||
const settings=store.settings();service.saveSettings({...settings,enabled:true});await service.tick(new Date('2026-10-17T09:00:01+08:00'));assert.equal(sent.length,1);
|
||||
assert.equal(sent[0].text,'第一行原文\n第二行 <原文> & 保留');assert.deepEqual(sent[0].attachments,[]);assert.deepEqual(sent[0].to,['interface@company.test']);assert.equal(store.items()[0].status,'sent');
|
||||
await service.tick(new Date('2026-10-17T09:00:20+08:00'));assert.equal(sent.length,1);
|
||||
});
|
||||
|
||||
test('unmapped industries cannot starve a later valid notification behind the queue read limit',async t=>{
|
||||
const {store,service,sent}=await fixture(t);for(let i=0;i<201;i++)service.ingest({flow:{...event.flow,id:'unmapped-'+i,industry:'尚未配置'}});
|
||||
service.ingest(event);service.saveSettings({...store.settings(),enabled:true});await service.tick(new Date('2026-10-17T09:00:00+08:00'));
|
||||
assert.equal(sent.length,1);assert.equal(sent[0].text,event.flow.brief);
|
||||
});
|
||||
|
||||
test('uncertain delivery remains blocked across restart and requires recorded human evidence to retry',async t=>{
|
||||
const {store,service,sent}=await fixture(t,{uncertain:true});service.ingest(event);service.saveSettings({...store.settings(),enabled:true});await service.tick(new Date('2026-10-17T09:00:00+08:00'));assert.equal(store.items()[0].status,'unknown');assert.equal(store.batches()[0].status,'unknown');
|
||||
await service.tick(new Date('2026-10-17T17:00:00+08:00'));assert.equal(sent.length,1);
|
||||
const unknownId=store.batches()[0].id;for(let index=0;index<101;index++){const item=service.ingest({flow:{...event.flow,id:'newer-'+index}}),batch=store.prepare([item],{industry:'宽带',to:['interface@company.test'],cc:[],text:'newer',subject:'newer'});store.mark(batch,'sent');}
|
||||
assert.equal(store.batches().some(batch=>batch.id===unknownId),true);
|
||||
assert.throws(()=>service.resolve(unknownId,{resolution:'retry',note:''},'admin'),e=>e.status===400);
|
||||
service.resolve(unknownId,{resolution:'sent',note:'已在 SMTP 服务端核实发送成功'},'admin');assert.equal(store.items()[0].status,'sent');
|
||||
});
|
||||
|
||||
test('an IMAP operation occupying the due slot does not consume the notification window',async t=>{
|
||||
const {store,service,sent}=await fixture(t);service.ingest(event);service.saveSettings({...store.settings(),enabled:true});
|
||||
let release;const occupied=service.mail.exclusive(store.settings().channelId,()=>new Promise(resolve=>{release=resolve;}));await Promise.resolve();
|
||||
await service.tick(new Date('2026-10-17T09:00:00+08:00'));assert.equal(sent.length,0);release();await occupied;
|
||||
await service.tick(new Date('2026-10-17T09:00:30+08:00'));assert.equal(sent.length,1);
|
||||
});
|
||||
|
||||
test('incomplete and unsafe field maps cannot enable delivery and unmapped industries stay visible',async t=>{
|
||||
const {store,service}=await fixture(t);assert.equal(service.preview({flow:{...event.flow,industry:'未配置产业'}}).valid,false);
|
||||
assert.throws(()=>service.ingest({flow:{...event.flow,brief:''}}),e=>e.status===400);
|
||||
assert.throws(()=>service.saveSettings({...store.settings(),fieldMap:{...fields,brief:'__proto__.secret'}}),e=>e.status===400);
|
||||
service.ingest({flow:{...event.flow,industry:'未配置产业'}});service.saveSettings({...store.settings(),enabled:true});await service.tick(new Date('2026-10-17T09:00:00+08:00'));assert.equal(store.items()[0].status,'blocked');
|
||||
});
|
||||
|
||||
test('field mapping supports Chinese object keys and rejects control characters in identity fields',async t=>{
|
||||
const {store,service}=await fixture(t);service.saveSettings({...store.settings(),fieldMap:{id:'来源.编号',version:'',industry:'来源.产业',brief:'来源.简要说明',subject:'',occurredAt:''}});
|
||||
const sample={来源:{编号:'FLOW-CN',产业:'宽带',简要说明:'中文字段原文'}};assert.equal(service.preview(sample).event.brief,'中文字段原文');
|
||||
assert.throws(()=>service.ingest({来源:{...sample.来源,编号:'bad\u0000identity'}}),e=>e.status===400);
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');
|
||||
const {Store}=require('../src/dashboard-store.cjs');const {StorageStore}=require('../src/storage-store.cjs');const {StorageService}=require('../src/storage-service.cjs');const {FileArea}=require('../src/storage-files.cjs');const {createDashboard}=require('../src/dashboard.cjs');
|
||||
const config={name:'210',host:'storage.company.test',share:'orders',directory:'',username:'archive',password:'Private-storage-password',enabled:true};
|
||||
async function fixture(t){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-storage-http-'));const outputDir=path.join(dir,'pdf'),remote=path.join(dir,'remote');await fs.mkdir(outputDir);await fs.mkdir(remote);const store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');for(const role of ['operator','viewer'])store.addUser({username:role,password:'Test-password-123',role},'admin');const storageStore=new StorageStore(path.join(dir,'storage'));const storage=new StorageService({store:storageStore,jobs:store,outputDir,client:{area:async()=>new FileArea(remote)}});const server=createDashboard({store,storage,outputDir});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{await storage.stop();server.closeAllConnections();await new Promise(r=>server.close(r));storageStore.close();await fs.rm(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+server.address().port;const call=(route,body,cookie,origin=base)=>fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{'Content-Type':'application/json',Origin:origin}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)});const login=async username=>(await call('/api/login',{username,password:'Test-password-123'})).headers.get('set-cookie').split(';')[0];return {dir,outputDir,remote,store,storage,storageStore,call,login};}
|
||||
|
||||
test('storage HTTP enforces roles, redacts passwords and archives only successful in-root PDFs',async t=>{
|
||||
const {dir,outputDir,store,storageStore,call,login}=await fixture(t);assert.equal((await call('/api/storage')).status,401);
|
||||
const admin=await login('admin'),operator=await login('operator'),viewer=await login('viewer');
|
||||
assert.equal((await call('/api/storage/servers',config,operator)).status,403);assert.equal((await call('/api/storage/servers',config,admin,'https://evil.test')).status,403);
|
||||
const saved=await call('/api/storage/servers',config,admin);assert.equal(saved.status,201);const server=await saved.json();assert.equal(server.password,undefined);
|
||||
assert.doesNotMatch(JSON.stringify(await(await call('/api/storage',undefined,viewer)).json()),/Private-storage/);
|
||||
assert.equal((await call(`/api/storage/servers/${server.id}/files`,undefined,viewer)).status,403);
|
||||
assert.equal((await call(`/api/storage/servers/${server.id}/check`,{},admin)).status,200);
|
||||
const overview=await(await call('/api/overview',undefined,admin)).json();assert.equal(overview.connections.find(c=>c.name==='存储服务器').ready,true);
|
||||
await fs.writeFile(path.join(outputDir,'order.pdf'),'%PDF-1.7\nHTTP document');store.recordJob({jobId:'job-1',status:'success',path:path.join(outputDir,'order.pdf'),filename:'order.pdf'});
|
||||
assert.equal((await call(`/api/storage/servers/${server.id}/archive`,{jobId:'job-1',directory:'产业A'},viewer)).status,403);
|
||||
const archived=await call(`/api/storage/servers/${server.id}/archive`,{jobId:'job-1',directory:'产业A'},operator);assert.equal(archived.status,200);assert.equal((await archived.json()).status,'success');
|
||||
assert.equal(storageStore.archives().length,1);
|
||||
const downloaded=await call(`/api/storage/servers/${server.id}/file?path=${encodeURIComponent('产业A/order.pdf')}`,undefined,operator);assert.equal(downloaded.status,200);assert.equal(await downloaded.text(),'%PDF-1.7\nHTTP document');
|
||||
store.recordJob({jobId:'outside',status:'success',path:path.join(dir,'outside.pdf'),filename:'outside.pdf'});await fs.writeFile(path.join(dir,'outside.pdf'),'%PDF-1.7\noutside');
|
||||
assert.equal((await call(`/api/storage/servers/${server.id}/archive`,{jobId:'outside',directory:''},admin)).status,400);
|
||||
});
|
||||
|
||||
test('automatic storage is opt-in, starts with new jobs and never queues mail',async t=>{
|
||||
const {outputDir,remote,store,storage,storageStore}=await fixture(t);const server=storage.saveServer(config);await fs.writeFile(path.join(outputDir,'new.pdf'),'%PDF-1.7\nnew');
|
||||
const old=store.recordJob({jobId:'old-job',status:'success',path:path.join(outputDir,'new.pdf'),filename:'new.pdf',createdAt:'2000-01-01T00:00:00Z'});
|
||||
await storage.automatic(old);assert.deepEqual(await fs.readdir(remote),[]);
|
||||
await assert.rejects(Promise.resolve().then(()=>storage.saveSettings({serverId:server.id,enabled:true})),e=>e.status===409);
|
||||
await storage.check(server.id);storage.saveSettings({serverId:server.id,enabled:true});await storage.automatic(old);assert.deepEqual(await fs.readdir(remote),[]);
|
||||
const job=store.recordJob({jobId:'new-job',status:'success',path:path.join(outputDir,'new.pdf'),filename:'new.pdf',createdAt:new Date(Date.now()+1).toISOString()});await storage.automatic(job);
|
||||
assert.deepEqual(await fs.readdir(remote),['new.pdf']);assert.equal(storageStore.archives()[0].status,'success');
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const os=require('node:os');const path=require('node:path');
|
||||
const {Store}=require('../src/dashboard-store.cjs');const {StorageStore}=require('../src/storage-store.cjs');const {StorageService}=require('../src/storage-service.cjs');const {FileArea}=require('../src/storage-files.cjs');const {createDashboard}=require('../src/dashboard.cjs');const {loadPlaywright,browserOptions}=require('../src/runtime.cjs');
|
||||
test('storage page edits redacted credentials, checks files and archives an exported PDF', {timeout:150000}, async t=>{
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'storage-ui-')),remote=path.join(dir,'remote'),output=path.join(dir,'output');await fs.mkdir(remote);await fs.mkdir(output);const store=new Store(path.join(dir,'users'));store.bootstrap('admin','Test-password-123');await fs.writeFile(path.join(output,'order.pdf'),'%PDF-1.7\nUI test');store.recordJob({jobId:'ui-job',filename:'order.pdf',path:path.join(output,'order.pdf'),status:'success'});const storageStore=new StorageStore(path.join(dir,'storage')),storage=new StorageService({store:storageStore,jobs:store,outputDir:output,client:{area:async()=>new FileArea(remote)}}),server=createDashboard({store,storage,outputDir:output});await new Promise(r=>server.listen(0,'127.0.0.1',r));let browser;t.after(async()=>{await browser?.close();await storage.stop();server.closeAllConnections();await new Promise(r=>server.close(r));storageStore.close();await fs.rm(dir,{recursive:true,force:true});});browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(30000);const errors=[];page.on('pageerror',e=>errors.push(e.message));await page.goto('http://127.0.0.1:'+server.address().port+'/#storage');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'添加服务器',exact:true}).click();
|
||||
for(const [label,value]of Object.entries({'服务器名称':'210 归档','服务器地址':'storage.company.test','共享名称':'orders','登录账号':'archive','SMB 密码':'UI-test-password'}))await page.getByLabel(label,{exact:true}).fill(value);
|
||||
const saveResponse=page.waitForResponse(r=>r.url().endsWith('/api/storage/servers')&&r.request().method()==='POST',{timeout:45000});await page.getByRole('button',{name:'保存服务器',exact:true}).click();const savedResponse=await saveResponse;assert.equal(savedResponse.status(),201,await savedResponse.text());await page.getByRole('button',{name:'检查读写',exact:true}).click();await page.getByText('共享目录读写正常',{exact:true}).waitFor();await page.getByRole('button',{name:'管理服务器',exact:true}).click();assert.equal(await page.getByLabel('SMB 密码',{exact:true}).inputValue(),'');await page.getByRole('button',{name:'取消编辑',exact:true}).click();await page.getByRole('button',{name:'浏览目录',exact:true}).click();await page.getByLabel('新目录名称',{exact:true}).fill('产业A');await page.getByRole('button',{name:'创建目录',exact:true}).click();await page.getByText('产业A',{exact:true}).waitFor();await page.getByLabel('归档 PDF',{exact:true}).selectOption('ui-job');await page.getByRole('button',{name:'归档到当前目录',exact:true}).click();await page.getByText('PDF 已归档。',{exact:true}).waitFor();assert.equal(await fs.readFile(path.join(remote,'order.pdf'),'utf8'),'%PDF-1.7\nUI test');await fs.mkdir(path.resolve('output/verification'),{recursive:true});await page.evaluate(()=>window.scrollTo(0,0));await page.screenshot({path:path.resolve('output/verification/storage-desktop.png'),fullPage:true});await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);assert.deepEqual(errors,[]);
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
'use strict';
|
||||
const {test}=require('node:test');
|
||||
const assert=require('node:assert/strict');
|
||||
const fs=require('node:fs/promises');
|
||||
const os=require('node:os');
|
||||
const path=require('node:path');
|
||||
const {StorageStore}=require('../src/storage-store.cjs');
|
||||
const {FileArea}=require('../src/storage-files.cjs');
|
||||
const config={name:'210 归档',host:'storage.company.test',share:'orders',directory:'通知书',username:'DOMAIN\\archive',password:'Storage-secret-123',enabled:true};
|
||||
async function fixture(t){const dir=await fs.mkdtemp(path.join(os.tmpdir(),'order-storage-'));t.after(()=>fs.rm(dir,{recursive:true,force:true}));return dir;}
|
||||
|
||||
test('storage persists encrypted credentials, keeps blank passwords and rejects stale or changed identities',async t=>{
|
||||
let store;t.after(()=>store?.close());const dir=await fixture(t);store=new StorageStore(dir);
|
||||
const saved=store.saveServer(config);assert.equal(saved.hasPassword,true);assert.equal(saved.password,undefined);
|
||||
assert.doesNotMatch(JSON.stringify(store.servers()),/Storage-secret/);
|
||||
assert.doesNotMatch((await fs.readFile(path.join(dir,'storage.sqlite'))).toString('utf8'),/Storage-secret-123/);
|
||||
assert.equal(store.secret(saved.id).password,'Storage-secret-123');
|
||||
assert.equal(store.saveServer({...saved,password:'',name:'归档服务器'}).version,2);
|
||||
assert.throws(()=>store.saveServer({...saved,password:''}),e=>e.status===409);
|
||||
const current=store.publicServer(saved.id);
|
||||
assert.throws(()=>store.saveServer({...current,host:'other.company.test',password:''}),e=>e.status===400);
|
||||
assert.throws(()=>store.saveServer({...current,directory:'../outside',password:''}),e=>e.status===400);
|
||||
assert.throws(()=>store.saveServer({...current,share:'orders\\other',password:''}),e=>e.status===400);
|
||||
store.close();store=new StorageStore(dir);assert.equal(store.secret(saved.id).password,'Storage-secret-123');
|
||||
const record=store.beginArchive(saved.id,'job-1','admin','');assert.equal(record.status,'running');
|
||||
store.close();store=new StorageStore(dir);assert.equal(store.archives()[0].status,'interrupted');
|
||||
for(let index=0;index<101;index++)store.beginArchive(saved.id,'later-'+index,'admin','');
|
||||
assert.equal(store.finishArchive(record.id,'success',{filename:'old.pdf'}).status,'success');
|
||||
});
|
||||
|
||||
test('file area publishes real PDFs idempotently and preserves different same-name content',async t=>{
|
||||
const dir=await fixture(t),root=path.join(dir,'remote');await fs.mkdir(root);const area=new FileArea(root);
|
||||
await area.check();assert.deepEqual(await fs.readdir(root),[]);
|
||||
await area.mkdir('产业A');const file=path.join(dir,'source.pdf');await fs.writeFile(file,'%PDF-1.7\nfirst document\n%%EOF');
|
||||
const first=await area.archive(file,'订单.pdf','产业A');assert.equal(first.filename,'订单.pdf');assert.equal(first.bytes,29);
|
||||
assert.equal((await area.readPdf('产业A/订单.pdf')).bytes.toString(),'%PDF-1.7\nfirst document\n%%EOF');
|
||||
const again=await area.archive(file,'订单.pdf','产业A');assert.equal(again.relativePath,first.relativePath);
|
||||
await fs.writeFile(file,'%PDF-1.7\nsecond document\n%%EOF');
|
||||
const second=await area.archive(file,'订单.pdf','产业A');assert.notEqual(second.filename,first.filename);
|
||||
assert.equal((await fs.readdir(path.join(root,'产业A'))).length,2);
|
||||
assert.equal((await area.readPdf('产业A/订单.pdf')).bytes.toString(),'%PDF-1.7\nfirst document\n%%EOF');
|
||||
assert.deepEqual((await area.list('')).entries.map(e=>e.name),['产业A']);
|
||||
});
|
||||
|
||||
test('file area rejects parent paths, alternate streams, symlinks and non-PDF sources',async t=>{
|
||||
const dir=await fixture(t),root=path.join(dir,'remote'),outside=path.join(dir,'outside');await fs.mkdir(root);await fs.mkdir(outside);const area=new FileArea(root);
|
||||
for(const relative of ['../outside','C:\\secret','\\\\other\\share','a:stream','CON','folder./secret','a/../b'])await assert.rejects(area.list(relative),e=>e.status===400);
|
||||
await fs.symlink(outside,path.join(root,'escape'),'junction');await assert.rejects(area.mkdir('escape/nested'),e=>e.status===400);
|
||||
const file=path.join(dir,'not.pdf');await fs.writeFile(file,'not a PDF');await assert.rejects(area.archive(file,'file.pdf',''),e=>e.status===400);
|
||||
await assert.rejects(area.readPdf('not.txt'),e=>e.status===400);
|
||||
});
|
||||
|
||||
test('configured archive root cannot escape through an intermediate directory junction',async t=>{
|
||||
const dir=await fixture(t),share=path.join(dir,'share'),outside=path.join(dir,'outside');await fs.mkdir(share);await fs.mkdir(path.join(outside,'nested'),{recursive:true});await fs.symlink(outside,path.join(share,'redirect'),'junction');
|
||||
const area=new FileArea(path.join(share,'redirect','nested'),{boundary:share});
|
||||
await assert.rejects(area.list(''),e=>e.status===400);
|
||||
assert.deepEqual(await fs.readdir(path.join(outside,'nested')),[]);
|
||||
});
|
||||
@@ -13,3 +13,5 @@
|
||||
#mail-editor .form-fieldset{min-width:0;margin-bottom:0}
|
||||
#mail-template-detail{scroll-margin-top:20px}
|
||||
.scan-interval{width:6rem}.arrival-date{font-weight:700;font-size:1.05rem;font-variant-numeric:tabular-nums}.arrival-day>summary{cursor:pointer;list-style:none}.arrival-day>summary::-webkit-details-marker{display:none}.arrival-day>summary:before{content:"▾";margin-right:.8rem;color:#64748b}.arrival-day:not([open])>summary:before{content:"▸"}.arrival-table th:first-child{min-width:175px}.arrival-table th:nth-child(2){min-width:170px}.arrival-subject{min-width:250px;white-space:normal;overflow-wrap:anywhere;max-width:600px}.arrival-table td:last-child{min-width:115px}
|
||||
|
||||
.notification-brief{white-space:pre-wrap;overflow-wrap:anywhere;font:inherit;color:inherit;background:transparent;padding:0;border:0;margin:0}
|
||||
+6
-6
@@ -5,7 +5,7 @@ const formatDate=value=>{const date=new Date(value);return value&&!Number.isNaN(
|
||||
const roles={admin:'管理员',operator:'操作员',viewer:'只读成员'};
|
||||
const statusMap={running:['处理中','blue'],success:['已完成','green'],error:['失败','red'],interrupted:['已中断','orange']};
|
||||
let currentUser=null,settings=null,currentView='overview',overview=null,refreshTimer=null,viewGeneration=0;
|
||||
const views={overview:['工作总览','团队工作一目了然,每一次协作都有记录'],calendar:['业务日历','按公司实际安排设置工作日、休息日与暂停日期'],exceptions:['异常待办','认领、转交和跟进异常'],bpm:['BPM 连接','管理连接及负责人'],supervisor:['运行监管','配置负责人、通知方式与重试上限'],records:['订单与导出记录','查询已经采集的订单,下载已完成的 PDF'],rules:['订单匹配规则','管理订单筛选和匹配条件'],schedule:['发送计划','设置每日两个发送时间和批次整理方式'],templates:['模板与收件群组','预览确认发信模板,维护产品线收件群组'],mail:['邮箱管理','维护托管邮箱、模板收信与连接状态'],connections:['服务接入','查看各个环节的接入情况'],users:['团队账号','为局域网内的同事分配访问权限'],audit:['操作记录','查看配置变更和导出任务的处理记录']};
|
||||
const views={storage:['存储服务器','配置 SMB 共享目录、检查连接与管理 PDF 归档'],notifications:['业务通知','配置来源字段、产业接口人与通知队列'],overview:['工作总览','团队工作一目了然,每一次协作都有记录'],calendar:['业务日历','按公司实际安排设置工作日、休息日与暂停日期'],exceptions:['异常待办','认领、转交和跟进异常'],bpm:['BPM 连接','管理连接及负责人'],supervisor:['运行监管','配置负责人、通知方式与重试上限'],records:['订单与导出记录','查询已经采集的订单,下载已完成的 PDF'],rules:['订单匹配规则','管理订单筛选和匹配条件'],schedule:['发送计划','设置每日两个发送时间和批次整理方式'],templates:['模板与收件群组','预览确认发信模板,维护产品线收件群组'],mail:['邮箱管理','维护托管邮箱、模板收信与连接状态'],connections:['服务接入','查看各个环节的接入情况'],users:['团队账号','为局域网内的同事分配访问权限'],audit:['操作记录','查看配置变更和导出任务的处理记录']};
|
||||
async function api(route,body) {
|
||||
const response=await fetch('/api'+route,{credentials:'same-origin',keepalive:route.endsWith('/login/close'),method:body===undefined?'GET':'POST',headers:body?{'Content-Type':'application/json'}:{},body:body?JSON.stringify(body):undefined});
|
||||
const result=await response.json();
|
||||
@@ -19,7 +19,7 @@ function notify(message,type='success') {
|
||||
function badge(status){const [label,color]=statusMap[status] || ['待处理','secondary'];return `<span class="badge bg-${color}-lt">${label}</span>`;}
|
||||
function navItem(id,symbol){return `<li class="nav-item"><a class="nav-link ${currentView===id?'active':''}" href="#${id}" data-view="${id}"><span class="nav-link-icon" aria-hidden="true">${symbol}</span><span class="nav-link-title">${views[id][0]}</span></a></li>`;}
|
||||
function shell() {
|
||||
root.innerHTML=`<div class="page"><aside class="navbar navbar-vertical navbar-expand-lg"><div class="container-fluid"><button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#sidebar-menu" aria-controls="sidebar-menu" aria-label="展开菜单"><span class="navbar-toggler-icon"></span></button><a class="navbar-brand" href="#overview"><span class="brand-mark">单</span>订单通知中心</a><div class="collapse navbar-collapse" id="sidebar-menu"><ul class="navbar-nav pt-lg-3">${navItem('overview','▦')}${navItem('calendar','▣')}${navItem('exceptions','☷')}${navItem('bpm','⇄')}${navItem('supervisor','◎')}<li class="nav-item mt-3"><span class="nav-link text-secondary small">订单与通知</span></li>${navItem('records','≡')}${navItem('rules','⌕')}<li class="nav-item mt-3"><span class="nav-link text-secondary small">通知配置</span></li>${navItem('schedule','◷')}${navItem('templates','✉')}${navItem('mail','@')}${navItem('connections','⇄')}<li class="nav-item mt-3"><span class="nav-link text-secondary small">团队管理</span></li>${currentUser.role==='admin'?navItem('users','♙'):''}${navItem('audit','☷')}</ul><div class="mt-auto p-3 text-secondary small d-none d-lg-block">团队共享工作台<br><span class="sidebar-status"><i></i> 本地运行 · 北京时间</span></div></div></div></aside><header class="navbar d-print-none"><div class="container-xl"><div class="d-flex gap-2 flex-wrap"><span class="badge bg-yellow-lt">自动处理未启用</span></div><div class="navbar-nav flex-row order-md-last ms-auto align-items-center gap-3"><div><div class="account-name">${esc(currentUser.username)}</div><div class="small text-secondary">${roles[currentUser.role]}</div></div><button class="btn btn-sm" id="logout">退出</button></div></div></header><div class="page-wrapper"><div class="page-header d-print-none"><div class="container-xl"><div class="row g-2 align-items-center"><div class="col"><div class="page-pretitle">订单通知自动化</div><h1 class="page-title" id="view-title"></h1><div class="text-secondary mt-2" id="view-description"></div></div><div class="col-auto ms-auto"><button class="btn" id="refresh">刷新数据</button></div></div></div></div><div class="page-body"><div class="container-xl" id="content"></div></div><footer class="footer footer-transparent d-print-none"><div class="container-xl"><div class="row text-secondary align-items-center"><div class="col">订单通知中心 · 局域网工作台</div><div class="col-auto">UI 基于 <a href="https://tabler.io" target="_blank" rel="noreferrer">Tabler</a> · MIT</div></div></div></footer></div></div>`;
|
||||
root.innerHTML=`<div class="page"><aside class="navbar navbar-vertical navbar-expand-lg"><div class="container-fluid"><button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#sidebar-menu" aria-controls="sidebar-menu" aria-label="展开菜单"><span class="navbar-toggler-icon"></span></button><a class="navbar-brand" href="#overview"><span class="brand-mark">单</span>订单通知中心</a><div class="collapse navbar-collapse" id="sidebar-menu"><ul class="navbar-nav pt-lg-3">${navItem('overview','▦')}${navItem('calendar','▣')}${navItem('exceptions','☷')}${navItem('bpm','⇄')}${navItem('supervisor','◎')}<li class="nav-item mt-3"><span class="nav-link text-secondary small">订单与通知</span></li>${navItem('records','≡')}${navItem('rules','⌕')}<li class="nav-item mt-3"><span class="nav-link text-secondary small">通知配置</span></li>${navItem('schedule','◷')}${navItem('templates','✉')}${navItem('mail','@')}${navItem('storage','▤')}${navItem('notifications','✉')}${navItem('connections','⇄')}<li class="nav-item mt-3"><span class="nav-link text-secondary small">团队管理</span></li>${currentUser.role==='admin'?navItem('users','♙'):''}${navItem('audit','☷')}</ul><div class="mt-auto p-3 text-secondary small d-none d-lg-block">团队共享工作台<br><span class="sidebar-status"><i></i> 本地运行 · 北京时间</span></div></div></div></aside><header class="navbar d-print-none"><div class="container-xl"><div class="d-flex gap-2 flex-wrap"><span class="badge bg-yellow-lt">自动处理未启用</span></div><div class="navbar-nav flex-row order-md-last ms-auto align-items-center gap-3"><div><div class="account-name">${esc(currentUser.username)}</div><div class="small text-secondary">${roles[currentUser.role]}</div></div><button class="btn btn-sm" id="logout">退出</button></div></div></header><div class="page-wrapper"><div class="page-header d-print-none"><div class="container-xl"><div class="row g-2 align-items-center"><div class="col"><div class="page-pretitle">订单通知自动化</div><h1 class="page-title" id="view-title"></h1><div class="text-secondary mt-2" id="view-description"></div></div><div class="col-auto ms-auto"><button class="btn" id="refresh">刷新数据</button></div></div></div></div><div class="page-body"><div class="container-xl" id="content"></div></div><footer class="footer footer-transparent d-print-none"><div class="container-xl"><div class="row text-secondary align-items-center"><div class="col">订单通知中心 · 局域网工作台</div><div class="col-auto">UI 基于 <a href="https://tabler.io" target="_blank" rel="noreferrer">Tabler</a> · MIT</div></div></div></footer></div></div>`;
|
||||
document.querySelector('#logout').onclick=async()=>{++viewGeneration;await window.BpmLogin?.dispose();await api('/logout',{});currentUser=null;clearInterval(refreshTimer);await boot();};
|
||||
document.querySelector('#refresh').onclick=()=>renderView().catch(error=>notify(error.message,'danger'));
|
||||
document.querySelectorAll('[data-view]').forEach(link=>link.onclick=()=>{document.querySelector('#sidebar-menu').classList.remove('show');});
|
||||
@@ -45,7 +45,7 @@ async function viewPdfRecords(container,isActive=()=>true) {
|
||||
}
|
||||
async function viewSchedule(container,isActive=()=>true) {
|
||||
const loaded=await api('/settings');if(!isActive())return;settings=loaded;const s=settings.schedule;const disabled=currentUser.role!=='admin'?'disabled':'';
|
||||
container.innerHTML=`<div class="settings-width">${readOnlyNote()}<div class="alert alert-info">自动发送未启用</div><form id="schedule-form"><div class="card"><div class="card-header"><h2 class="card-title">每日两次通知</h2><span class="badge bg-blue-lt">北京时间</span></div><div class="card-body"><div class="row g-4"><div class="col-sm-6"><label class="form-label required" for="time-first">第一个发送时间</label><input class="form-control schedule-time" id="time-first" type="time" value="${s.times[0]}" required ${disabled}></div><div class="col-sm-6"><label class="form-label required" for="time-second">第二个发送时间</label><input class="form-control schedule-time" id="time-second" type="time" value="${s.times[1]}" required ${disabled}></div><div class="col-12"><label class="form-check form-switch"><input class="form-check-input" type="checkbox" id="weekends" ${s.weekends?'checked':''} ${disabled}><span class="form-check-label">周六、周日照常发送</span></label><div class="form-hint">关闭后仅在周一至周五发送;公司调休与暂停安排可在 <a href="#calendar">业务日历</a> 中按日期覆盖。</div></div><div class="col-sm-6"><label class="form-label" for="send-mode">邮件整理方式</label><select class="form-select" id="send-mode" ${disabled}><option value="product_line" ${s.mode==='product_line'?'selected':''}>按产品线汇总为一封邮件</option><option value="order" ${s.mode==='order'?'selected':''}>每个订单单独发送一封</option></select></div><div class="col-sm-6"><label class="form-label" for="missed">停机错过时段后</label><select class="form-select" id="missed" ${disabled}><option value="next_window" ${s.missed==='next_window'?'selected':''}>保留待发订单,下一时段合并处理</option><option value="skip" ${s.missed==='skip'?'selected':''}>跳过错过时段,继续正常计划</option></select></div></div></div><div class="card-footer d-flex align-items-center"><span class="text-secondary small">配置供整个团队共用</span>${currentUser.role==='admin'?'<button class="btn btn-primary ms-auto" type="submit">保存发送计划</button>':''}</div></div></form></div>`;
|
||||
container.innerHTML=`<div class="settings-width">${readOnlyNote()}<div class="alert alert-info">请在 <a href="#notifications">业务通知</a> 中配置来源并设置自动发送开关。</div><form id="schedule-form"><div class="card"><div class="card-header"><h2 class="card-title">每日两次通知</h2><span class="badge bg-blue-lt">北京时间</span></div><div class="card-body"><div class="row g-4"><div class="col-sm-6"><label class="form-label required" for="time-first">第一个发送时间</label><input class="form-control schedule-time" id="time-first" type="time" value="${s.times[0]}" required ${disabled}></div><div class="col-sm-6"><label class="form-label required" for="time-second">第二个发送时间</label><input class="form-control schedule-time" id="time-second" type="time" value="${s.times[1]}" required ${disabled}></div><div class="col-12"><label class="form-check form-switch"><input class="form-check-input" type="checkbox" id="weekends" ${s.weekends?'checked':''} ${disabled}><span class="form-check-label">周六、周日照常发送</span></label><div class="form-hint">关闭后仅在周一至周五发送;公司调休与暂停安排可在 <a href="#calendar">业务日历</a> 中按日期覆盖。</div></div><div class="col-sm-6"><label class="form-label" for="send-mode">邮件整理方式</label><select class="form-select" id="send-mode" ${disabled}><option value="product_line" ${s.mode==='product_line'?'selected':''}>按产品线汇总为一封邮件</option><option value="order" ${s.mode==='order'?'selected':''}>每个订单单独发送一封</option></select></div><div class="col-sm-6"><label class="form-label" for="missed">停机错过时段后</label><select class="form-select" id="missed" ${disabled}><option value="next_window" ${s.missed==='next_window'?'selected':''}>保留待发订单,下一时段合并处理</option><option value="skip" ${s.missed==='skip'?'selected':''}>跳过错过时段,继续正常计划</option></select></div></div></div><div class="card-footer d-flex align-items-center"><span class="text-secondary small">配置供整个团队共用</span>${currentUser.role==='admin'?'<button class="btn btn-primary ms-auto" type="submit">保存发送计划</button>':''}</div></div></form></div>`;
|
||||
document.querySelector('#schedule-form').onsubmit=async event=>{event.preventDefault();try{const updated=await api('/settings',{version:settings.version,schedule:{times:[document.querySelector('#time-first').value,document.querySelector('#time-second').value],timezone:'Asia/Shanghai',weekends:document.querySelector('#weekends').checked,mode:document.querySelector('#send-mode').value,missed:document.querySelector('#missed').value}});settings=updated;notify('发送计划已保存。');}catch(error){notify(error.message,'danger');}};
|
||||
}
|
||||
async function viewTemplates(container,isActive=()=>true) {
|
||||
@@ -60,7 +60,7 @@ async function viewTemplates(container,isActive=()=>true) {
|
||||
await window.MailViews.templates(container.querySelector('#mail-templates'),isActive);
|
||||
}
|
||||
async function viewConnections(container,isActive=()=>true) {
|
||||
const data=await api('/overview');if(!isActive())return;container.innerHTML=`<div class="mb-3 btn-list"><a class="btn btn-primary" href="#mail">邮箱管理</a><a class="btn" href="#bpm">BPM 连接</a></div><div class="row row-cards">${data.connections.map(item=>`<div class="col-md-6"><div class="card"><div class="card-body"><div class="d-flex align-items-center mb-2"><h3 class="card-title mb-0">${esc(item.name)}</h3><span class="badge bg-${item.ready?'green':'yellow'}-lt ms-auto">${item.ready?'已就绪':'待接入'}</span></div><div class="text-secondary">${esc(item.detail)}</div></div></div></div>`).join('')}</div>`;
|
||||
const data=await api('/overview');if(!isActive())return;container.innerHTML=`<div class="mb-3 btn-list"><a class="btn btn-primary" href="#mail">邮箱管理</a><a class="btn" href="#bpm">BPM 连接</a><a class="btn" href="#storage">存储服务器</a><a class="btn" href="#notifications">业务通知</a></div><div class="row row-cards">${data.connections.map(item=>`<div class="col-md-6"><div class="card"><div class="card-body"><div class="d-flex align-items-center mb-2"><h3 class="card-title mb-0">${esc(item.name)}</h3><span class="badge bg-${item.ready?'green':'yellow'}-lt ms-auto">${item.ready?'已就绪':'待接入'}</span></div><div class="text-secondary">${esc(item.detail)}</div></div></div></div>`).join('')}</div>`;
|
||||
}
|
||||
async function viewUsers(container,isActive=()=>true) {
|
||||
const {users}=await api('/users');if(!isActive())return;container.innerHTML=`<div class="row row-cards"><div class="col-lg-7"><div class="card"><div class="card-header"><h2 class="card-title">团队账号</h2></div><div class="table-responsive"><table class="table card-table"><thead><tr><th>账号</th><th>角色</th><th>创建时间</th></tr></thead><tbody>${users.map(user=>`<tr><td>${esc(user.username)}</td><td><span class="badge bg-${user.role==='admin'?'blue':'secondary'}-lt">${roles[user.role]}</span></td><td class="text-secondary small">${formatDate(user.createdAt)}</td></tr>`).join('')}</tbody></table></div></div></div><div class="col-lg-5"><form class="card" id="user-form"><div class="card-header"><h2 class="card-title">添加同事</h2></div><div class="card-body"><div class="mb-3"><label class="form-label required" for="new-username">登录账号</label><input class="form-control" id="new-username" autocomplete="off" required minlength="3" maxlength="40" pattern="[a-zA-Z0-9_.-]+"><div class="form-hint">英文、数字、点、下划线或短横线</div></div><div class="mb-3"><label class="form-label required" for="new-password">初始密码</label><input class="form-control" id="new-password" type="password" autocomplete="new-password" required minlength="12" maxlength="128"></div><div><label class="form-label" for="new-role">角色</label><select class="form-select" id="new-role"><option value="viewer">只读成员</option><option value="operator">操作员</option><option value="admin">管理员</option></select><div class="form-hint">管理员管理配置和账号;操作员处理异常;只读成员查看和下载。</div></div></div><div class="card-footer text-end"><button class="btn btn-primary" type="submit">创建账号</button></div></form></div></div>`;
|
||||
@@ -77,7 +77,7 @@ async function renderView() {
|
||||
document.querySelectorAll('[data-view]').forEach(link=>link.classList.toggle('active',link.dataset.view===currentView));
|
||||
document.querySelector('#view-title').textContent=views[currentView][0];document.querySelector('#view-description').textContent=views[currentView][1];
|
||||
const container=document.querySelector('#content');container.innerHTML='<div class="card"><div class="card-body text-secondary">正在加载…</div></div>';
|
||||
const fn={overview:viewOverview,calendar:window.WorkspaceViews?.calendar,exceptions:window.WorkspaceViews?.exceptions,bpm:window.WorkspaceViews?.bpm,supervisor:window.WorkspaceViews?.supervisor,records:viewRecords,schedule:viewSchedule,templates:viewTemplates,mail:window.MailViews?.accounts,connections:viewConnections,users:viewUsers,audit:viewAudit,rules:viewRules}[currentView];
|
||||
const fn={storage:window.StorageViews?.render,notifications:window.NotificationViews?.render,overview:viewOverview,calendar:window.WorkspaceViews?.calendar,exceptions:window.WorkspaceViews?.exceptions,bpm:window.WorkspaceViews?.bpm,supervisor:window.WorkspaceViews?.supervisor,records:viewRecords,schedule:viewSchedule,templates:viewTemplates,mail:window.MailViews?.accounts,connections:viewConnections,users:viewUsers,audit:viewAudit,rules:viewRules}[currentView];
|
||||
try{await fn(container,isActive);}catch(error){if(isActive())container.innerHTML=`<div class="alert alert-danger">${esc(error.message)}</div>`;}
|
||||
}
|
||||
async function authScreen() {
|
||||
@@ -85,7 +85,7 @@ async function authScreen() {
|
||||
root.innerHTML=`<div class="page page-center"><div class="container-tight py-4"><div class="text-center mb-4"><span class="avatar bg-blue text-white mb-3">单</span><h1 class="h2">订单通知中心</h1><div class="text-secondary">团队协同工作台</div></div><form class="card card-md" id="login-form"><div class="card-body"><h2 class="h2 text-center mb-4">${initialize?'创建管理员账号':'登录工作台'}</h2>${setup.required && !setup.canSetup?'<div class="alert alert-info">请先由部署机在本机地址创建管理员,再为团队开通账号。</div>':''}<div class="mb-3"><label class="form-label" for="username">账号</label><input class="form-control" id="username" autocomplete="username" required ${initialize?'minlength="3" maxlength="40" pattern="[a-zA-Z0-9_.-]+"':''}></div><div class="mb-3"><label class="form-label" for="password">密码</label><input class="form-control" type="password" id="password" autocomplete="${initialize?'new-password':'current-password'}" required ${initialize?'minlength="12" maxlength="128"':''}>${initialize?'<div class="form-hint">设置至少 12 位密码,后续可在看板中创建同事账号。</div>':''}</div><div class="text-danger mb-3" id="auth-error" role="alert"></div><div class="form-footer"><button class="btn btn-primary w-100" type="submit" ${setup.required && !setup.canSetup?'disabled':''}>${initialize?'创建账号并进入':'登录'}</button></div></div></form><p class="text-center text-secondary small mt-4 login-note">${initialize?'首次设置仅允许从部署机访问。':'使用管理员分配的账号访问。'}<br>界面基于 Tabler 开源模板</p></div></div>`;
|
||||
document.querySelector('#login-form').onsubmit=async event=>{event.preventDefault();const button=event.target.querySelector('button[type="submit"]');button.disabled=true;try{const result=await api(initialize?'/bootstrap':'/login',{username:document.querySelector('#username').value,password:document.querySelector('#password').value});currentUser=result.user;enter();}catch(error){document.querySelector('#auth-error').textContent=error.message;}finally{button.disabled=false;}};
|
||||
}
|
||||
function enter(){window.OrderViews?.configure({api,esc,formatDate,notify,user:currentUser});window.MailViews?.configure({api,esc,formatDate,notify,user:currentUser});window.WorkspaceViews?.configure({api,esc,formatDate,notify,user:currentUser});shell();renderView();clearInterval(refreshTimer);refreshTimer=setInterval(()=>{if(currentUser && currentView==='overview' && !document.hidden){const generation=++viewGeneration;viewOverview(document.querySelector('#content'),()=>generation===viewGeneration && !!currentUser && currentView==='overview').catch(()=>{});}},15000);}
|
||||
function enter(){window.StorageViews?.configure({api,esc,formatDate,notify,user:currentUser});window.NotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderViews?.configure({api,esc,formatDate,notify,user:currentUser});window.MailViews?.configure({api,esc,formatDate,notify,user:currentUser});window.WorkspaceViews?.configure({api,esc,formatDate,notify,user:currentUser});shell();renderView();clearInterval(refreshTimer);refreshTimer=setInterval(()=>{if(currentUser && currentView==='overview' && !document.hidden){const generation=++viewGeneration;viewOverview(document.querySelector('#content'),()=>generation===viewGeneration && !!currentUser && currentView==='overview').catch(()=>{});}},15000);}
|
||||
async function boot(){try{const setup=await api('/bootstrap/status');currentUser=(await api('/me')).user;enter();}catch{await authScreen();}}
|
||||
window.addEventListener('pagehide',()=>{window.BpmLogin?.dispose({unload:true});});
|
||||
window.addEventListener('hashchange',()=>{if(currentUser)renderView();});
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>订单通知中心</title><link href="/vendor/tabler.css" rel="stylesheet"><link href="/app.css" rel="stylesheet"></head>
|
||||
<body><div id="app"><div class="page page-center"><div class="container-tight py-4"><div class="card"><div class="card-body text-center">正在连接订单通知中心…</div></div></div></div></div><script src="/vendor/tabler.js" defer></script><script src="/bpm.js" defer></script><script src="/workspace.js" defer></script><script src="/mail.js" defer></script><script src="/orders.js" defer></script><script src="/app.js" defer></script></body></html>
|
||||
<body><div id="app"><div class="page page-center"><div class="container-tight py-4"><div class="card"><div class="card-body text-center">正在连接订单通知中心…</div></div></div></div></div><script src="/vendor/tabler.js" defer></script><script src="/bpm.js" defer></script><script src="/workspace.js" defer></script><script src="/mail.js" defer></script><script src="/orders.js" defer></script><script src="/storage.js" defer></script><script src="/notifications.js" defer></script><script src="/app.js" defer></script></body></html>
|
||||
@@ -0,0 +1,16 @@
|
||||
(() => {
|
||||
'use strict';
|
||||
let api,esc,formatDate,notify,user;
|
||||
const names={id:'通知 ID 字段',version:'版本字段',industry:'产业字段',brief:'简要说明字段',subject:'标题字段',occurredAt:'业务时间字段'};
|
||||
const labels={pending:'待发送',blocked:'配置待补全',reserved:'处理中',sent:'已提交邮件服务器',unknown:'结果待核实',prepared:'已准备',sending:'发送中',failed:'检查失败',cancelled:'已取消',resolved_sent:'已核实发送',resolved_retry:'已核实重新入队'};
|
||||
async function render(container,isActive=()=>true){
|
||||
const [data,mail,business]=await Promise.all([api('/notifications'),api('/mail').catch(()=>({channels:[]})),api('/settings')]);if(!isActive())return;
|
||||
const config=data.settings,admin=user.role==='admin',operator=user.role!=='viewer',disabled=admin?'':'disabled';
|
||||
container.innerHTML=`<div class="alert alert-${config.enabled?'success':'info'}">业务通知${config.enabled?'已启用,将按发送计划处理已入队数据':'已暂停,可先配置并预览字段映射'}</div><form class="card mb-3" id="notification-settings"><div class="card-header"><h2 class="card-title">业务通知配置</h2><a class="btn btn-sm ms-auto" href="#schedule">发送计划</a></div><div class="card-body"><div class="row g-3"><div class="col-md-6"><label class="form-label" for="notification-source">来源名称</label><input class="form-control" id="notification-source" value="${esc(config.sourceName)}" maxlength="80" required ${disabled}></div><div class="col-md-6"><label class="form-label" for="notification-channel">发件邮箱</label><select class="form-select" id="notification-channel" ${disabled}><option value="">请选择托管邮箱</option>${mail.channels.map(c=>`<option value="${c.id}" ${config.channelId===c.id?'selected':''}>${esc(c.name)} · ${esc(c.email)}</option>`).join('')}</select><div class="form-hint"><a href="#mail">管理邮箱及检查 SMTP</a></div></div><div class="col-md-6"><label class="form-label" for="notification-attempts">连接检查失败尝试上限</label><input class="form-control" id="notification-attempts" type="number" min="1" max="10" value="${config.maxAttempts}" required ${disabled}><div class="form-hint">发送结果不明的批次需要人工核验。</div></div><div class="col-md-6"><div class="form-label">产业接口人</div><p class="mb-1">已配置 ${business.groups.length} 个收件组</p><a href="#templates">维护产业 / 产品线收件群组</a></div></div><hr><h3 class="card-title">来源字段映射</h3><div class="text-secondary mb-3">填写来源对象中的字段路径,例如 <code>flow.brief</code>。通知 ID、产业和简要说明为必填;正文直接使用简要说明原文。</div><div class="row g-3">${Object.entries(names).map(([key,label])=>`<div class="col-md-6"><label class="form-label" for="notification-field-${key}">${label}</label><input class="form-control" id="notification-field-${key}" value="${esc(config.fieldMap[key])}" maxlength="200" ${['id','industry','brief'].includes(key)?'required':''} ${disabled}></div>`).join('')}</div><label class="form-check form-switch mt-4"><input class="form-check-input" type="checkbox" id="notification-enabled" ${config.enabled?'checked':''} ${disabled}><span class="form-check-label">启用自动业务通知</span></label></div>${admin?'<div class="card-footer text-end"><button class="btn btn-primary" type="submit">保存通知配置</button></div>':''}</form>${operator?'<form class="card mb-3" id="notification-preview-form"><div class="card-header"><h3 class="card-title">来源样本预览</h3></div><div class="card-body"><label class="form-label" for="notification-sample">来源 JSON 样本</label><textarea class="form-control font-monospace" id="notification-sample" rows="6" required maxlength="80000"></textarea><div class="form-hint">按已保存的字段映射预览正文和收件人。预览不会创建通知或发送邮件。</div><div id="notification-preview" class="mt-3"></div></div><div class="card-footer text-end"><button class="btn" type="submit">预览字段映射</button></div></form>':''}<section class="card mb-3"><div class="card-header"><h3 class="card-title">通知队列</h3></div><div class="table-responsive"><table class="table card-table"><thead><tr><th>来源 / 产业</th><th>简要说明</th><th>状态</th></tr></thead><tbody>${data.items.map(i=>`<tr><td class="text-break">${esc(i.sourceId)}<div class="small text-secondary">${esc(i.industry)}</div></td><td class="text-break"><details><summary>${esc(i.subject)}</summary><pre class="notification-brief mt-2">${esc(i.brief)}</pre></details></td><td>${esc(labels[i.status]||i.status)}${i.error?`<div class="small text-danger">${esc(i.error)}</div>`:''}</td></tr>`).join('')||'<tr><td colspan="3" class="text-secondary">暂无通知。待来源字段与产业收件组确定后接入业务数据。</td></tr>'}</tbody></table></div></section><section class="card"><div class="card-header"><h3 class="card-title">发送批次与核验</h3></div><div class="list-group list-group-flush">${data.batches.map(b=>`<div class="list-group-item"><div class="d-flex flex-wrap gap-2"><strong>${esc(b.industry)} · ${esc(b.subject)}</strong><span class="ms-auto">${esc(labels[b.status]||b.status)}</span></div><div class="small text-secondary mt-2">${formatDate(b.created_at)} · ${esc(b.to.join('、'))}</div>${b.error?`<div class="text-danger mt-2">${esc(b.error)}</div>`:''}${b.status==='unknown'&&admin?`<form class="mt-3" data-notification-resolve="${b.id}"><label class="form-label" for="notice-resolution-${b.id}">核验结果</label><select class="form-select mb-2" id="notice-resolution-${b.id}" name="resolution"><option value="sent">已核实发送成功</option><option value="retry">已核实需要重发,重新入队</opti
Line truncated
|
||||
async function action(button,work){button.disabled=true;try{await work();}catch(e){if(isActive())notify(e.message,'danger');}finally{if(button.isConnected)button.disabled=false;}}
|
||||
if(admin)container.querySelector('#notification-settings').onsubmit=e=>{e.preventDefault();return action(e.submitter,async()=>{const fieldMap=Object.fromEntries(Object.keys(names).map(k=>[k,container.querySelector('#notification-field-'+k).value.trim()]));await api('/notifications/settings',{...config,sourceName:container.querySelector('#notification-source').value,channelId:container.querySelector('#notification-channel').value,fieldMap,maxAttempts:Number(container.querySelector('#notification-attempts').value),enabled:container.querySelector('#notification-enabled').checked});if(isActive()){notify('业务通知配置已保存。');await render(container,isActive);}});};
|
||||
if(operator)container.querySelector('#notification-preview-form').onsubmit=e=>{e.preventDefault();return action(e.submitter,async()=>{let sample;try{sample=JSON.parse(container.querySelector('#notification-sample').value);}catch{throw new Error('样本不是有效的 JSON 对象。');}const result=await api('/notifications/preview',{data:sample});if(!isActive())return;container.querySelector('#notification-preview').innerHTML=`${result.issues?.length?`<div class="alert alert-warning">${result.issues.map(esc).join('<br>')}</div>`:''}${result.event?`<div class="card card-body"><div class="fw-medium">${esc(result.event.industry)} · ${esc(result.event.subject)}</div><div class="small text-secondary mt-2">收件人:${esc(result.to.join('、')||'待配置')}</div><pre class="notification-brief mt-3 mb-0">${esc(result.event.brief)}</pre></div>`:''}`;});};
|
||||
container.querySelectorAll('[data-notification-resolve]').forEach(form=>form.onsubmit=e=>{e.preventDefault();return action(e.submitter,async()=>{await api('/notifications/batches/'+form.dataset.notificationResolve+'/resolve',{resolution:form.elements.resolution.value,note:form.elements.note.value});if(isActive()){notify('核验结果已保存。');await render(container,isActive);}});});
|
||||
}
|
||||
window.NotificationViews={configure:helpers=>({api,esc,formatDate,notify,user}=helpers),render};
|
||||
})();
|
||||
@@ -0,0 +1,24 @@
|
||||
(() => {
|
||||
'use strict';
|
||||
let api,esc,formatDate,notify,user;
|
||||
const labels={running:'归档中',success:'已归档',error:'归档失败',interrupted:'已中断'};
|
||||
const join=(directory,name)=>[directory,name].filter(Boolean).join('/');
|
||||
async function render(container,isActive=()=>true){
|
||||
const [data,jobs]=await Promise.all([api('/storage'),api('/jobs')]);if(!isActive())return;
|
||||
const admin=user.role==='admin',canFiles=user.role!=='viewer';
|
||||
container.innerHTML=`<div class="card mb-3"><div class="card-body d-flex flex-wrap align-items-center gap-3"><div><h2 class="card-title mb-1">SMB 存储服务器</h2><div class="text-secondary">管理共享目录与 PDF 归档</div></div>${admin?'<button class="btn btn-primary ms-auto" id="storage-add">添加服务器</button>':''}</div></div><div id="storage-editor"></div><div class="row row-cards">${data.servers.map(s=>`<div class="col-lg-6"><section class="card h-100"><div class="card-header"><h3 class="card-title">${esc(s.name)}</h3><span class="badge bg-${s.enabled?'blue':'secondary'}-lt ms-auto">${s.enabled?'已启用':'已停用'}</span></div><div class="card-body"><div class="text-break fw-medium">${esc('\\\\'+s.host+'\\'+s.share+(s.directory?'\\'+s.directory.replace(/\//g,'\\'):''))}</div><div class="text-secondary mt-3">${esc(s.state.message)}</div><div class="small text-secondary mt-2">上次检查:${formatDate(s.state.checkedAt)}</div></div><div class="card-footer btn-list">${admin?`<button class="btn btn-sm" data-storage-edit="${s.id}">管理服务器</button><button class="btn btn-sm" data-storage-check="${s.id}" ${s.enabled?'':'disabled'}>检查读写</button>`:''}${canFiles?`<button class="btn btn-sm btn-primary" data-storage-browse="${s.id}" ${s.enabled?'':'disabled'}>浏览目录</button>`:''}</div></section></div>`).join('')||'<div class="col-12"><div class="card card-body text-secondary text-center py-5">尚未配置存储服务器</div></div>'}</div><div id="storage-browser" class="mt-3"></div><form class="card mt-3" id="storage-auto"><div class="card-header"><h3 class="card-title">自动归档</h3><span class="badge bg-${data.settings.enabled?'green':'secondary'}-lt ms-auto">${data.settings.enabled?'已开启':'已暂停'}</span></div><div class="card-body"><label class="form-label" for="storage-default">归档服务器</label><select class="form-select" id="storage-default" ${admin?'':'disabled'}><option value="">请选择</option>${data.servers.map(s=>`<option value="${s.id}" ${data.settings.serverId===s.id?'selected':''}>${esc(s.name)}</option>`).join('')}</select><label class="form-check form-switch mt-3"><input class="form-check-input" type="checkbox" id="storage-enabled" ${data.settings.enabled?'checked':''} ${admin?'':'disabled'}><span class="form-check-label">自动归档启用后新导出的 PDF</span></label><div class="form-hint">请先检查服务器读写。历史 PDF 可在目录浏览中手动归档。</div></div>${admin?'<div class="card-footer text-end"><button class="btn btn-primary" type="submit">保存自动归档设置</button></div>':''}</form><div class="card mt-3"><div class="card-header"><h3 class="card-title">归档记录</h3></div><div class="table-responsive"><table class="table card-table"><thead><tr><th>文件 / 服务器</th><th>状态</th><th>时间</th></tr></thead><tbody>${data.archives.map(a=>`<tr><td class="text-break">${esc(a.relativePath||a.jobId)}<div class="small text-secondary">${esc(a.serverName||data.servers.find(s=>s.id===a.serverId)?.name||'—')}</div></td><td>${esc(labels[a.status]||a.status)}${a.error?`<div class="text-danger small">${esc(a.error)}</div>`:''}</td><td class="small text-secondary">${formatDate(a.finishedAt||a.startedAt)}</td></tr>`).join('')||'<tr><td colspan="3" class="text-secondary">暂无归档记录</td></tr>'}</tbody></table></div></div>`;
|
||||
async function action(button,work){button.disabled=true;try{await work();}catch(e){if(isActive())notify(e.message,'danger');}finally{if(button.isConnected)button.disabled=false;}}
|
||||
function editor(s={name:'',host:'',share:'',directory:'',username:'',enabled:true}){
|
||||
const host=container.querySelector('#storage-editor');host.innerHTML=`<form class="card mb-3" id="storage-form"><div class="card-header"><h3 class="card-title">${s.id?'管理服务器':'添加服务器'}</h3></div><div class="card-body"><div class="row g-3">${[['name','服务器名称',80],['host','服务器地址',253],['share','共享名称',80],['directory','归档子目录',1500],['username','登录账号',200]].map(([key,label,max])=>`<div class="col-md-6"><label class="form-label" for="storage-${key}">${label}</label><input class="form-control" id="storage-${key}" value="${esc(s[key])}" maxlength="${max}" ${key==='directory'?'':'required'} autocomplete="off"></div>`).join('')}<div class="col-md-6"><label class="form-label" for="storage-password">SMB 密码</label><input class="form-control" type="password" id="storage-password" maxlength="2048" autocomplete="new-password" ${s.id?'':'required'}><div class="form-hint">${s.id?'留空保留现有密码;更换主机、共享或账号时请重新填写。':'密码加密保存在部署机。'}</div></div></div><label class="form-check mt-3"><input class="form-check-input" type="checkbox" id="storage-active" ${s.enabled?'checked':''}><span class="form-check-label">启用服务器</span></label><div class="text-danger mt-3" id="storage-error" role="alert"></div></div><div class="card-footer btn-list"><button class="btn" type="button" id="storage-cancel">取消编辑</button><button class="btn btn-primary ms-auto" type="submit">保存服务器</button></div></form>`;
|
||||
host.querySelector('#storage-cancel').onclick=()=>host.replaceChildren();host.querySelector('form').onsubmit=async e=>{e.preventDefault();await action(e.submitter,async()=>{const input={...(s.id?{id:s.id,version:s.version}:{}),enabled:host.querySelector('#storage-active').checked};for(const key of ['name','host','share','directory','username','password'])input[key]=host.querySelector('#storage-'+key).value;try{await api('/storage/servers',input);if(isActive()){notify('存储服务器已保存。');await render(container,isActive);}}catch(error){if(isActive())host.querySelector('#storage-error').textContent=error.message;}});};host.scrollIntoView({block:'start',behavior:'smooth'});
|
||||
}
|
||||
if(admin){container.querySelector('#storage-add').onclick=()=>editor();container.querySelectorAll('[data-storage-edit]').forEach(b=>b.onclick=()=>editor(data.servers.find(s=>s.id===b.dataset.storageEdit)));container.querySelectorAll('[data-storage-check]').forEach(b=>b.onclick=()=>action(b,async()=>{await api('/storage/servers/'+b.dataset.storageCheck+'/check',{});if(isActive()){notify('存储服务器读写检查成功。');await render(container,isActive);}}));container.querySelector('#storage-auto').onsubmit=e=>{e.preventDefault();return action(e.submitter,async()=>{await api('/storage/settings',{serverId:container.querySelector('#storage-default').value,enabled:container.querySelector('#storage-enabled').checked});if(isActive()){notify('自动归档设置已保存。');await render(container,isActive);}});};}
|
||||
async function browse(id,directory=''){
|
||||
const listing=await api('/storage/servers/'+id+'/files?path='+encodeURIComponent(directory));if(!isActive())return;const host=container.querySelector('#storage-browser'),server=data.servers.find(s=>s.id===id);
|
||||
host.innerHTML=`<section class="card"><div class="card-header"><h3 class="card-title">${esc(server.name)} · 目录浏览</h3><button class="btn btn-sm ms-auto" id="storage-browser-close">关闭目录</button></div><div class="card-body"><div class="d-flex gap-2 align-items-center mb-3"><button class="btn btn-sm" id="storage-up" ${directory?'':'disabled'}>上一级</button><span class="text-break">/${esc(directory)}</span></div><div class="list-group mb-3">${listing.entries.map((entry,index)=>`<div class="list-group-item d-flex gap-2 align-items-center"><span class="text-break flex-fill">${esc(entry.name)}</span>${entry.type==='directory'?`<button class="btn btn-sm" data-storage-dir="${index}">打开目录</button>`:entry.type==='file'&&/\.pdf$/i.test(entry.name)?`<a class="btn btn-sm" href="/api/storage/servers/${id}/file?path=${encodeURIComponent(join(directory,entry.name))}" download>下载 PDF</a>`:''}</div>`).join('')||'<div class="text-secondary p-3">当前目录为空</div>'}</div>${listing.truncated?'<div class="text-secondary small mb-3">仅显示前 500 项</div>':''}<form id="storage-folder-form" class="d-flex flex-wrap gap-2 mb-4"><label class="visually-hidden" for="storage-folder">新目录名称</label><input class="form-control flex-fill" id="storage-folder" placeholder="新目录名称" required maxlength="200"><button class="btn" type="submit">创建目录</button></form><form id="storage-archive-form"><label class="form-label" for="storage-job">归档 PDF</label><select class="form-select" id="storage-job" required><option value="">请选择已完成的 PDF</option>${jobs.jobs.filter(j=>j.downloadable).map(j=>`<option value="${esc(j.jobId)}">${esc(j.filename||j.metadata?.order||j.jobId)}</option>`).join('')}</select><div class="text-end mt-3"><button class="btn btn-primary" type="submit">归档到当前目录</button></div></form></div></section>`;
|
||||
host.querySelector('#storage-browser-close').onclick=()=>host.replaceChildren();host.querySelector('#storage-up').onclick=e=>action(e.currentTarget,()=>browse(id,directory.split('/').slice(0,-1).join('/')));host.querySelectorAll('[data-storage-dir]').forEach(b=>b.onclick=()=>action(b,()=>browse(id,join(directory,listing.entries[Number(b.dataset.storageDir)].name))));host.querySelector('#storage-folder-form').onsubmit=e=>{e.preventDefault();return action(e.submitter,async()=>{const name=host.querySelector('#storage-folder').value;if(/[\\/]/.test(name))throw new Error('请输入单个目录名称。');await api('/storage/servers/'+id+'/folders',{path:join(directory,name)});await browse(id,directory);});};host.querySelector('#storage-archive-form').onsubmit=e=>{e.preventDefault();return action(e.submitter,async()=>{await api('/storage/servers/'+id+'/archive',{jobId:host.querySelector('#storage-job').value,directory});if(isActive()){notify('PDF 已归档。');await render(container,isActive);await browse(id,directory);}});};
|
||||
}
|
||||
container.querySelectorAll('[data-storage-browse]').forEach(b=>b.onclick=()=>action(b,()=>browse(b.dataset.storageBrowse)));
|
||||
}
|
||||
window.StorageViews={configure:helpers=>({api,esc,formatDate,notify,user}=helpers),render};
|
||||
})();
|
||||
Reference in new issue
Block a user