Compare commits

..
1 Commits
Author SHA1 Message Date
sophieandCursor 537e3e18f0 feat(equipment-acceptance): 预警扫描发送改异步并错开合同付款排程
手动扫描/发送入队由 schedule worker 执行,避免 Nginx 504;默认扫描 06:30、周五发送 18:30。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-30 15:09:16 +08:00
16 changed files with 334 additions and 73 deletions

No files matched your search

@@ -2,8 +2,9 @@
backend/app/api/equipment_acceptance/__init__.py
用途:设备验收预警的 Chat 作业面接口。
依赖:JWT 当前用户、Agent 授权、sync_service、统一成功响应。
逻辑:持有 equipment_acceptance Agent 的用户可看停留列表、发送记录、已归档 Excel 和配置;同步、扫描、发送和保存配置仅平台管理员。
依赖:JWT 当前用户、Agent 授权、sync_service、统一成功响应、jobs.queue。
逻辑:持有 equipment_acceptance Agent 的用户可看停留列表、发送记录、已归档 Excel 和配置;
同步、扫描、发送和保存配置仅平台管理员。扫描与发送改为入队,由 schedule worker 执行,避免 HTTP 504。
"""
from __future__ import annotations
@@ -12,15 +13,17 @@ from io import BytesIO
from flask import Blueprint, g, request, send_file
from app import db
from app.core.auth.jwt import get_current_user
from app.core.errors import ForbiddenError, UnauthorizedError
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError
from app.core.response import ok
from app.models import Agent
from app.jobs.queue import enqueue
from app.jobs.types import JobType
from app.models import Agent, Job
from app.services.equipment_acceptance.config_service import (
get_acceptance_config,
save_acceptance_config,
)
from app.services.equipment_acceptance.alert_service import generate_alerts, send_pending_alerts
from app.services.equipment_acceptance.send_record_service import get_send_file, list_send_files, list_send_records
from app.services.equipment_acceptance.sync_service import (
get_acceptance_order,
@@ -28,6 +31,11 @@ from app.services.equipment_acceptance.sync_service import (
sync_acceptance_snapshots,
)
_EQUIPMENT_ACCEPTANCE_JOB_TYPES = {
JobType.EQUIPMENT_ACCEPTANCE_ALERT_SCAN.value,
JobType.EQUIPMENT_ACCEPTANCE_ALERT_WEEKLY.value,
}
equipment_acceptance_bp = Blueprint("equipment_acceptance", __name__)
EQUIPMENT_ACCEPTANCE_AGENT_CODE = "equipment_acceptance"
@@ -149,16 +157,79 @@ def save_equipment_acceptance_config():
@equipment_acceptance_bp.route("/alerts/scan", methods=["POST"])
def scan_equipment_acceptance_alerts():
"""管理员立即同步 E10 并生成待发送记录。不发企业微信。"""
_require_equipment_acceptance_admin()
return ok(generate_alerts(), request_id=getattr(g, "request_id", None))
"""
将设备验收扫描任务入队。
核心逻辑:仅平台管理员。Worker 同步后生成待发送,不发企业微信。
同业务键已有 queued/running 时复用,避免连点重复扫。
Returns:
HTTP 202 与 job_id。
"""
user = _require_equipment_acceptance_admin()
job_id = enqueue(
JobType.EQUIPMENT_ACCEPTANCE_ALERT_SCAN,
{},
domain="equipment_acceptance",
business_ref="daily-alert",
created_by_id=user.id,
message="等待扫描设备验收预警",
)
return ok({"job_id": job_id}, request_id=getattr(g, "request_id", None), status=202)
@equipment_acceptance_bp.route("/alerts/send", methods=["POST"])
def send_equipment_acceptance_alerts():
"""管理员立即把待发送记录按收件人发到企业微信。"""
_require_equipment_acceptance_admin()
return ok(send_pending_alerts(), request_id=getattr(g, "request_id", None))
"""
将设备验收发送任务入队。
核心逻辑:仅平台管理员。Worker 按收件人发企微后改发送记录状态。
同业务键已有 queued/running 时复用,避免连点重复发。
Returns:
HTTP 202 与 job_id。
"""
user = _require_equipment_acceptance_admin()
job_id = enqueue(
JobType.EQUIPMENT_ACCEPTANCE_ALERT_WEEKLY,
{},
domain="equipment_acceptance",
business_ref="weekly-alert",
created_by_id=user.id,
message="等待发送设备验收预警",
)
return ok({"job_id": job_id}, request_id=getattr(g, "request_id", None), status=202)
@equipment_acceptance_bp.route("/jobs/<int:job_id>", methods=["GET"])
def get_equipment_acceptance_job(job_id: int):
"""
查询当前管理员提交的设备验收后台任务是否跑完。
核心逻辑:只返回本人创建的设备验收 Job。发送任务的 result 含 sent/failed。
Args:
job_id: jobs 表主键。
Returns:
status、message、result。
Raises:
NotFoundError: 任务不存在或不属于当前管理员。
"""
user = _require_equipment_acceptance_admin()
row = db.session.get(Job, job_id)
if (
row is None
or row.domain != "equipment_acceptance"
or row.job_type not in _EQUIPMENT_ACCEPTANCE_JOB_TYPES
or row.created_by_id != user.id
):
raise NotFoundError("任务不存在")
return ok(
{
"id": row.id,
"status": row.status,
"message": row.message,
"result": row.result_json or {},
},
request_id=getattr(g, "request_id", None),
)
@equipment_acceptance_bp.route("/send-files", methods=["GET"])
+1
View File
@@ -7,6 +7,7 @@ backend/app/jobs/handlers/__init__.py
from app.jobs.handlers import ( # noqa: F401
contract_payment,
equipment_acceptance,
file_check_run,
in_transit_transfer_item,
in_transit_transfer_match,
@@ -0,0 +1,55 @@
"""
backend/app/jobs/handlers/equipment_acceptance.py
用途:执行设备验收预警域后台任务(手动扫描、手动发送)。
依赖:jobs.registry、equipment_acceptance.alert_service、jobs.queue.finish_job。
逻辑:与周五排程共用 generate_alerts / send_pending_alerts。成功须显式 finish_job,
否则 Job 停在 running,超时回收后会重复发送。
"""
from __future__ import annotations
from app.jobs.context import JobContext
from app.jobs.queue import finish_job
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.services.equipment_acceptance.alert_service import generate_alerts, send_pending_alerts
@register_handler(JobType.EQUIPMENT_ACCEPTANCE_ALERT_SCAN)
def run_equipment_acceptance_alert_scan(ctx: JobContext, payload: dict) -> None:
"""
执行一次设备验收同步并生成待发送记录。
核心逻辑:不发企业微信。供管理员「扫描预警」入队后由 Worker 执行。
Args:
ctx: 后台任务上下文。
payload: 含通用队列注入的 job_id。
Returns:
None;结果写入 Job.result_json。
"""
job_id = int(payload.get("job_id") or 0)
result = generate_alerts()
ctx.logger.info("equipment acceptance alert scan result=%s", result)
if job_id:
finish_job(job_id, result=result, message="设备验收预警扫描完成")
@register_handler(JobType.EQUIPMENT_ACCEPTANCE_ALERT_WEEKLY)
def run_equipment_acceptance_alert_weekly(ctx: JobContext, payload: dict) -> None:
"""
执行一次设备验收待发送记录的企业微信汇总发送。
核心逻辑:按收件人发卡片和 Excel,发完后才改发送记录状态。
供管理员「发送预警」入队;与周五排程共用同一发送函数。
Args:
ctx: 后台任务上下文。
payload: 含通用队列注入的 job_id。
Returns:
None;sent/failed 写入 Job.result_json,页面轮询后展示。
"""
job_id = int(payload.get("job_id") or 0)
result = send_pending_alerts()
ctx.logger.info("equipment acceptance weekly alert result=%s", result)
if job_id:
finish_job(job_id, result=result, message="设备验收预警发送完成")
+27 -1
View File
@@ -109,6 +109,23 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
timeout_seconds=float(current_app.config.get("CONTRACT_PAYMENT_JOB_TIMEOUT_SECONDS", 1800)),
job_type=job_type,
)
equipment_acceptance_types = (
JobType.EQUIPMENT_ACCEPTANCE_ALERT_SCAN,
JobType.EQUIPMENT_ACCEPTANCE_ALERT_WEEKLY,
)
if {item.value for item in equipment_acceptance_types} & allowed_types:
from app.jobs.queue import recover_stale_jobs
from flask import current_app
# 设备验收发送可能要给很多收件人发企微,超时与合同付款周汇总同级。
for job_type in equipment_acceptance_types:
if job_type.value not in allowed_types:
continue
recover_stale_jobs(
domain="equipment_acceptance",
timeout_seconds=float(current_app.config.get("CONTRACT_PAYMENT_JOB_TIMEOUT_SECONDS", 1800)),
job_type=job_type,
)
# [STEP 2] 按队列优先级 claim
for name in queue_names:
@@ -149,13 +166,22 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
)
if job:
return _normalize_generic_job(job)
# file-check / 企微通讯录同步与排程共用 schedule worker,但 domain 不同
# file-check / 企微通讯录同步 / 设备验收手动扫描发送与排程共用 schedule worker
job = claim_next_job(
domain=None,
job_types=[JobType.FILE_CHECK_RUN, JobType.WECOM_DIRECTORY_SYNC],
)
if job:
return _normalize_generic_job(job)
job = claim_next_job(
domain="equipment_acceptance",
job_types=[
JobType.EQUIPMENT_ACCEPTANCE_ALERT_SCAN,
JobType.EQUIPMENT_ACCEPTANCE_ALERT_WEEKLY,
],
)
if job:
return _normalize_generic_job(job)
elif name == 'transfer':
# 在途调拨域:预检/票级执行/行级任务共用 domain="in_transit_transfer"
# (与 execution_service 入队口径一致);缺此分支时 transfer worker
+10 -1
View File
@@ -42,6 +42,9 @@ class JobType(StrEnum):
CONTRACT_PAYMENT_SYNC = 'contract_payment_sync'
CONTRACT_PAYMENT_ALERT = 'contract_payment_alert'
CONTRACT_PAYMENT_ALERT_WEEKLY = 'contract_payment_alert_weekly'
# 设备验收预警:管理员手动扫描 / 发送入队,由 schedule worker 执行,避免 HTTP 504。
EQUIPMENT_ACCEPTANCE_ALERT_SCAN = 'equipment_acceptance_alert_scan'
EQUIPMENT_ACCEPTANCE_ALERT_WEEKLY = 'equipment_acceptance_alert_weekly'
# 在途仓自动调拨:文件准备 + 只读匹配(Phase 1);执行 Run/Item 在 Phase 2 注册。
TRANSFER_MATCH = 'in_transit_transfer_match'
TRANSFER_RUN = 'in_transit_transfer_run'
@@ -84,7 +87,13 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress',
}),
'contract': frozenset({'procurement_contract_review', 'contract_payment_sync', 'contract_payment_alert', 'contract_payment_alert_weekly'}),
'schedule': frozenset({'schedule_run', 'file_check_run', 'wecom_directory_sync'}),
'schedule': frozenset({
'schedule_run',
'file_check_run',
'wecom_directory_sync',
'equipment_acceptance_alert_scan',
'equipment_acceptance_alert_weekly',
}),
'transfer': frozenset({
'in_transit_transfer_match', 'in_transit_transfer_run', 'in_transit_transfer_item',
}),
@@ -1,7 +1,7 @@
"""
backend/app/services/equipment_acceptance/schedule_seed.py
用途:设备验收预警的默认排程:每日扫描和周五 18:00 发送。
用途:设备验收预警的默认排程:每日 06:30 扫描和周五 18:30 发送。
依赖:ScheduleTask、permission_roles.service.first_schedule_owner_user、timezone_util。
逻辑:应用启动时幂等创建。已有同编号或同任务键时不覆盖管理员改过的 Cron。
"""
@@ -17,8 +17,10 @@ from app.services.schedule.timezone_util import compute_next_run_at
_DEFAULTS = (
("SCH-EQUIPMENT-ACCEPTANCE-SCAN", "equipment-acceptance-alert-scan", "设备验收预警扫描(日批)", "0 6 * * *"),
("SCH-EQUIPMENT-ACCEPTANCE-WEEKLY", "equipment-acceptance-alert-weekly", "设备验收预警发送(周五 18:00)", "0 18 * * 5"),
# 每天 06:30,错开合同付款预警扫描的 06:00
("SCH-EQUIPMENT-ACCEPTANCE-SCAN", "equipment-acceptance-alert-scan", "设备验收预警扫描(日批 06:30)", "30 6 * * *"),
# 周五 18:30,错开合同付款预警的周五 18:00
("SCH-EQUIPMENT-ACCEPTANCE-WEEKLY", "equipment-acceptance-alert-weekly", "设备验收预警发送(周五 18:30)", "30 18 * * 5"),
)
@@ -26,7 +28,7 @@ def ensure_default_equipment_acceptance_schedules(*, commit: bool = True):
"""
幂等创建设备验收每日扫描和周五发送两个排程。
核心逻辑:发送时刻不在预警配置表。默认与合同付款一样,周五 18:00,时区 Asia/Shanghai。
核心逻辑:发送时刻不在预警配置表。默认每天 06:30、周五 18:30(错开合同付款 06:00 / 18:00),时区 Asia/Shanghai。
Args:
commit: 为 False 时只 flush,交给外层事务提交。
Returns:
+2 -2
View File
@@ -33,8 +33,8 @@
## 设备验收预警(2026-09)
- 从 OA 资产验收单第一次进入「使用部门担当」起按自然日累计停留;只监控未归档、有效、可以验收的流程。归档、退回、撤回、作废或无法验收立即停表。再进入时计时起点不改,仍按第一次写入的 `sbsyrjssj` 计算,不从 0 重计。`sfzfth` 不考虑从退回改回正常。
- 超过 30/37/44/51 天各发一次企业微信。第 4 轮默认关闭,配置打开后才通知总经理。第 1 档主送使用部门担当,第 2 档主送其经副理,直接主管也取这个人;E8 与 E10 相同,不取当前节点未办人。采购担当取流程申请人。采购经副理、COO、总经理可在界面配置。每日扫描只生成待发送,初始每周五 18:00 按收件人发送汇总卡片和 Excel 明细。
- 规则已冻结。验收单读 E10 `ecology10.dbo.ft_gdzcysdv2`,人员 ID 经 `eteams.dbo.employee` 用工号对上系统用户。流程状态读 `wfc_requestbase.flowstatus`,`7`、`8`、`99`、`-99` 都按撤销停表。当前节点读 `wfc_currentnode` 再关联 `wfp_node`,当前处理人读 `wfc_operate.userid`。直接主管取 `employee.SUPERIOR`,经副理按 `employee.DEPARTMENT` 查 E10 部门矩阵。申请人 `sqr` 是人员 ID。退回为 `sfzfth = 0`。无法验收说明正文是 `ycsm`,只留痕。只读同步、停留列表、发送记录、每日扫描和周五企业微信已实现,入口与合同付款预警相同(内置 Chat Agent `equipment_acceptance`)。不查询、不保存 `isremark`。默认每天 06:00 扫描、每周五 18:00 按收件人发送。停表取消未发送,已发送不撤回。需求见 [设备验收预警需求](features/equipment-acceptance-warning/demand.md),数据设计见 [technical.md](features/equipment-acceptance-warning/technical.md)。
- 超过 30/37/44/51 天各发一次企业微信。第 4 轮默认关闭,配置打开后才通知总经理。第 1 档主送使用部门担当,第 2 档主送其经副理,直接主管也取这个人;E8 与 E10 相同,不取当前节点未办人。采购担当取流程申请人。采购经副理、COO、总经理可在界面配置。每日扫描只生成待发送,初始每周五 18:30 按收件人发送汇总卡片和 Excel 明细(错开合同付款 18:00)。
- 规则已冻结。验收单读 E10 `ecology10.dbo.ft_gdzcysdv2`,人员 ID 经 `eteams.dbo.employee` 用工号对上系统用户。流程状态读 `wfc_requestbase.flowstatus`,`7`、`8`、`99`、`-99` 都按撤销停表。当前节点读 `wfc_currentnode` 再关联 `wfp_node`,当前处理人读 `wfc_operate.userid`。直接主管取 `employee.SUPERIOR`,经副理按 `employee.DEPARTMENT` 查 E10 部门矩阵。申请人 `sqr` 是人员 ID。退回为 `sfzfth = 0`。无法验收说明正文是 `ycsm`,只留痕。只读同步、停留列表、发送记录、每日扫描和周五企业微信已实现,入口与合同付款预警相同(内置 Chat Agent `equipment_acceptance`)。不查询、不保存 `isremark`。默认每天 06:30 扫描、每周五 18:30 按收件人发送。停表取消未发送,已发送不撤回。需求见 [设备验收预警需求](features/equipment-acceptance-warning/demand.md),数据设计见 [technical.md](features/equipment-acceptance-warning/technical.md)。 |
- E8 补抓已接上(2026-10-26)。与 E10 分来源保存。暂停按撤销停表。没有作废、强制结束。见 [设备验收预警需求](features/equipment-acceptance-warning/demand.md)、[technical.md](features/equipment-acceptance-warning/technical.md)。
## 合同付款预警 Agent(2026-08)
@@ -38,5 +38,5 @@
## 3. 怎么发
- 每天扫描,生成待发送。默认每周五 18:00 按收件人发一条企业微信汇总,并附一份只含该人的 Excel。时刻可改。
- 每天 06:30 扫描,生成待发送(错开合同付款 06:00)。默认每周五 18:30 按收件人发一条企业微信汇总,并附一份只含该人的 Excel(错开合同付款周五 18:00)。时刻可改。
- 已发送的不撤回、不重发。
+3 -3
View File
@@ -56,9 +56,9 @@
| 停留预警规则 | 需求已冻结 | 从第一次进入「使用部门担当」起按自然日累计,直到停表。未归档且已开始计时的单据,可以验收为是或未标明都监控,明确为否才不监控。再进入仍用第一次写入的 `sbsyrjssj`,不从 0 重计。权威:[features/equipment-acceptance-warning/demand.md](features/equipment-acceptance-warning/demand.md)。 |
| 只读同步 | 已实现 | 平台管理员 `POST /api/equipment-acceptance/sync` 拉取 E10 与 E8 未归档验收单、流程状态、当前节点和操作人。不抓归档(E10 `flowstatus = 3`,E8 `currentnodetype = 3`)。按 `sfkyzcys`、`sfzfth`、`flowstatus` 4/5 标停表;`flowstatus` 为 7、8、99、-99 时记为已撤销并不再提醒。本次结果里没有的本地单删除,并取消未发送预警。不查询、不保存 `isremark`。不保存 `optgroupid`、`batch_number`、`operate_log_id`。 |
| 停留列表 | 已实现 | 入口与合同付款预警相同:内置 Chat Agent `equipment_acceptance` 替换对话区。只列出未归档单据,并展示流程编号、标题和创建时间。有权限的用户看列表和详情,同步按钮只给平台管理员。 |
| 预警配置 | 已实现 | 停留情况旁的「预警配置」页。四档天数默认 30/37/44/51,第 4 轮默认关闭,打开后才通知总经理。采购经副理、COO、总经理选择系统用户。发送时刻不在此页,由排程 Cron 配置,默认每周五 18:00。 |
| 发送记录 | 已实现 | Chat 页签「发送记录」。按验收单和档位列出主送、抄送、结果、Excel 附件和发送时间。发给每位收件人的 Excel 归档后挂在对应行上,点文件名下载。`GET /api/equipment-acceptance/sends`。管理员可立即扫描或发送。 |
| 四档企业微信升级 | 已按使用部门担当 | 超过 30/37/44/51 天各发一次。第 1 档主送使用部门担当,第 2 档主送其经副理,直接主管也取这个人。E8 与 E10 相同。采购担当取流程申请人。采购经副理、COO、总经理为可配置固定岗位。每天 06:00 同步并生成待发送,每周五 18:00 按收件人发送一条汇总卡片和一份 Excel 明细。停表取消未发送。已发送不撤回、不重发。设计:[features/equipment-acceptance-warning/technical.md](features/equipment-acceptance-warning/technical.md)。 |
| 预警配置 | 已实现 | 停留情况旁的「预警配置」页。四档天数默认 30/37/44/51,第 4 轮默认关闭,打开后才通知总经理。采购经副理、COO、总经理选择系统用户。发送时刻不在此页,由排程 Cron 配置,默认每周五 18:30(错开合同付款 18:00)。 |
| 发送记录 | 已实现 | Chat 页签「发送记录」。按验收单和档位列出主送、抄送、结果、Excel 附件和发送时间。发给每位收件人的 Excel 归档后挂在对应行上,点文件名下载。`GET /api/equipment-acceptance/sends`。管理员「扫描预警 / 发送预警」入队由 schedule worker 执行(避免 HTTP 504),页面轮询 Job 后再刷新结果。 |
| 四档企业微信升级 | 已按使用部门担当 | 超过 30/37/44/51 天各发一次。第 1 档主送使用部门担当,第 2 档主送其经副理,直接主管也取这个人。E8 与 E10 相同。采购担当取流程申请人。采购经副理、COO、总经理为可配置固定岗位。每天 06:30 同步并生成待发送,每周五 18:30 按收件人发送一条汇总卡片和一份 Excel 明细(错开合同付款 06:00 / 18:00)。停表取消未发送。已发送不撤回、不重发。设计:[features/equipment-acceptance-warning/technical.md](features/equipment-acceptance-warning/technical.md)。 |
| E8 补抓 | 已接上查询 | 读取 `ecology` 上的验收单,与 E10 分来源保存。计时起点 `syddjssj`。暂停 `currentstatus = 0` 按撤销停表。没有作废、强制结束。见 [technical.md](features/equipment-acceptance-warning/technical.md)。 |
## 知识库同步状态校验
+1 -1
View File
@@ -24,7 +24,7 @@
## 设备验收预警(2026-10)
- 已实现的同步只读 E10:`OA_E10_SQLSERVER_*`,验收单 `ecology10.dbo.ft_gdzcysdv2`,流程 `wfc_requestbase` / `wfc_currentnode` / `wfc_operate`,人员 `eteams.dbo.employee`。不回退 E8。本地快照按 `request_id` 唯一。每天 06:00 先同步再生成待发送,每周五 18:00 只发送。
- 已实现的同步只读 E10:`OA_E10_SQLSERVER_*`,验收单 `ecology10.dbo.ft_gdzcysdv2`,流程 `wfc_requestbase` / `wfc_currentnode` / `wfc_operate`,人员 `eteams.dbo.employee`。不回退 E8。本地快照按 `request_id` 唯一。每天 06:30 先同步再生成待发送,每周五 18:30 只发送(错开合同付款 06:00 / 18:00)。
- E8 补抓已接上。`OA_SQLSERVER_*` 读 `ecology`。与 E10 分来源保存。暂停 `currentstatus = 0` 按撤销停表。没有作废、强制结束。字段见 [features/equipment-acceptance-warning/technical.md](features/equipment-acceptance-warning/technical.md)。
## 货代发货通知 STP + 例外工作台(2026-07-29)
@@ -7,6 +7,7 @@
* 配置只保存天数和系统用户,不保存发送时刻。
* 保存配置自行声明 Content-Type: application/json,供 Flask get_json 解析。
* 发送记录只读已落库的行。每位收件人的 Excel 可再下载。
* 扫描/发送改为入队,再用 jobs 接口轮询结果,避免 Nginx 504。
*/
import { requestBlob, requestJson } from '@/shared/api/client';
@@ -126,33 +127,43 @@ export function syncEquipmentAcceptance() {
return requestJson<EquipmentAcceptanceSyncResult>('/api/equipment-acceptance/sync', { method: 'POST' });
}
export interface EquipmentAcceptanceScanResult {
created: number;
updated: number;
cancelled: number;
}
export interface EquipmentAcceptanceSendResult {
sent: number;
failed: number;
records_sent: number;
records_failed: number;
export interface EquipmentAcceptanceJob {
id: number;
status: string;
message?: string | null;
result?: {
created?: number;
updated?: number;
cancelled?: number;
sent?: number;
failed?: number;
records_sent?: number;
records_failed?: number;
} | null;
}
/**
* 管理员立即同步 E10 并生成待发送记录。
* @returns 新增、更新和取消条数
* 管理员将扫描任务入队(Worker 同步并生成待发送,不发企微)。
* @returns 后台任务主键
*/
export function scanEquipmentAcceptanceAlerts() {
return requestJson<EquipmentAcceptanceScanResult>('/api/equipment-acceptance/alerts/scan', { method: 'POST' });
export function enqueueEquipmentAcceptanceAlertScan() {
return requestJson<{ job_id: number }>('/api/equipment-acceptance/alerts/scan', { method: 'POST' });
}
/**
* 管理员立即把待发送记录按收件人发到企业微信。
* @returns 成功和失败的收件人数
* 管理员将发送任务入队(Worker 按收件人发企微后改状态)。
* @returns 后台任务主键
*/
export function sendEquipmentAcceptanceAlerts() {
return requestJson<EquipmentAcceptanceSendResult>('/api/equipment-acceptance/alerts/send', { method: 'POST' });
export function enqueueEquipmentAcceptanceAlertSend() {
return requestJson<{ job_id: number }>('/api/equipment-acceptance/alerts/send', { method: 'POST' });
}
/**
* 查询本人提交的设备验收后台任务状态。
* @param jobId - jobs 表主键
*/
export function getEquipmentAcceptanceJob(jobId: number) {
return requestJson<EquipmentAcceptanceJob>(`/api/equipment-acceptance/jobs/${jobId}`);
}
export interface EquipmentAcceptanceSendRecord {
@@ -6,6 +6,7 @@
本文件引入 Element 样式并包住 ElConfigProvider。标题和页签压到两行,下面整块留给当前页。
view=config 打开预警配置;view=sends 打开发送记录;orderId 只在停留列表下钻。
同步只在停留列表。扫描和发送只在发送记录,且仅平台管理员可见。
扫描与发送改为入队后轮询 Job,避免长请求被 Nginx 504。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
@@ -27,9 +28,11 @@ import { useAuthStore } from '@/features/auth/stores/auth.store';
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
import { useMessage } from '@/shared/composables/useMessage';
import {
scanEquipmentAcceptanceAlerts,
sendEquipmentAcceptanceAlerts,
enqueueEquipmentAcceptanceAlertScan,
enqueueEquipmentAcceptanceAlertSend,
getEquipmentAcceptanceJob,
syncEquipmentAcceptance,
type EquipmentAcceptanceJob,
} from '../api/equipment-acceptance.api';
import EquipmentAcceptanceConfigPage from '../views/EquipmentAcceptanceConfigPage.vue';
import EquipmentAcceptanceDetailPage from '../views/EquipmentAcceptanceDetailPage.vue';
@@ -38,6 +41,10 @@ import EquipmentAcceptanceSendsPage from '../views/EquipmentAcceptanceSendsPage.
type WorkspaceView = 'ledger' | 'sends' | 'config';
const JOB_POLL_MS = 2000;
const JOB_TIMEOUT_MS = 600_000;
const JOB_DONE = new Set(['success', 'failed', 'dead', 'cancelled']);
const { t } = useI18n();
const route = useRoute();
const router = useRouter();
@@ -49,6 +56,68 @@ const runningAction = ref<'scan' | 'send' | null>(null);
const listPage = ref<{ reload: () => Promise<void> } | null>(null);
const sendsPage = ref<{ reload: () => Promise<void> } | null>(null);
/**
* 轮询后台任务直到终态或超时。
* 核心逻辑:入队接口立即返回;真正扫描/发送在 schedule worker 里,不能把「已提交」当成完成。
* @param jobId - 刚入队的任务主键
* @returns 终态任务;超时返回 null
*/
async function waitForJob(jobId: number): Promise<EquipmentAcceptanceJob | null> {
const deadline = Date.now() + JOB_TIMEOUT_MS;
while (Date.now() < deadline) {
const job = await getEquipmentAcceptanceJob(jobId);
if (JOB_DONE.has(job.status)) return job;
await new Promise((resolve) => window.setTimeout(resolve, JOB_POLL_MS));
}
return null;
}
/**
* 按扫描任务结果提示。
* @param job - 已结束的任务;null 表示仍在后台跑
*/
function reportScanJob(job: EquipmentAcceptanceJob | null): void {
if (!job) {
msg.warning(t('admin.equipmentAcceptance.jobTimeout'));
return;
}
if (job.status !== 'success') {
msg.error(job.message || t('admin.equipmentAcceptance.jobError'));
return;
}
msg.success(t('admin.equipmentAcceptance.scanDone', {
created: Number(job.result?.created || 0),
updated: Number(job.result?.updated || 0),
cancelled: Number(job.result?.cancelled || 0),
}));
}
/**
* 按发送任务结果提示。
* @param job - 已结束的任务;null 表示仍在后台跑
*/
function reportSendJob(job: EquipmentAcceptanceJob | null): void {
if (!job) {
msg.warning(t('admin.equipmentAcceptance.jobTimeout'));
return;
}
if (job.status !== 'success') {
msg.error(job.message || t('admin.equipmentAcceptance.jobError'));
return;
}
const sent = Number(job.result?.sent || 0);
const failed = Number(job.result?.failed || 0);
if (sent > 0 && failed > 0) {
msg.warning(t('admin.equipmentAcceptance.sendPartial', { sent, failed }));
} else if (failed > 0) {
msg.error(t('admin.equipmentAcceptance.sendFailedCount', { failed }));
} else if (sent > 0) {
msg.success(t('admin.equipmentAcceptance.sendDone', { sent, failed: 0 }));
} else {
msg.info(t('admin.equipmentAcceptance.sendEmpty'));
}
}
const isAdmin = computed(() => Boolean(auth.isAdmin));
const activeView = computed<WorkspaceView>(() => {
if (route.query.view === 'config') return 'config';
@@ -105,8 +174,8 @@ function onTabChange(name: string | number): void {
}
/**
* 管理员在发送记录页确认后立即扫描或发送。
* 核心逻辑:确认框取消会拒绝,这里直接返回。扫描会同步 E10;发送把待发送记录推到企业微信。
* 管理员在发送记录页确认后,将扫描或发送入队并等待 Worker。
* 核心逻辑:确认框取消直接返回。入队后轮询 Job,完成再刷新列表并按 sent/failed 提示。
* @param action - scan 或 send
*/
async function askAlert(action: 'scan' | 'send'): Promise<void> {
@@ -125,21 +194,14 @@ async function askAlert(action: 'scan' | 'send'): Promise<void> {
}
runningAction.value = action;
try {
if (action === 'scan') {
const result = await scanEquipmentAcceptanceAlerts();
msg.success(t('admin.equipmentAcceptance.scanDone', {
created: result.created,
updated: result.updated,
cancelled: result.cancelled,
}));
} else {
const result = await sendEquipmentAcceptanceAlerts();
msg.success(t('admin.equipmentAcceptance.sendDone', {
sent: result.sent,
failed: result.failed,
}));
}
const queued = action === 'scan'
? await enqueueEquipmentAcceptanceAlertScan()
: await enqueueEquipmentAcceptanceAlertSend();
msg.info(t('admin.equipmentAcceptance.jobSubmitted'));
const job = await waitForJob(Number(queued.job_id));
await sendsPage.value?.reload();
if (action === 'scan') reportScanJob(job);
else reportSendJob(job);
} catch (error) {
msg.error(error instanceof BusinessError ? error.message : t('admin.equipmentAcceptance.syncFailed'));
} finally {
+9 -3
View File
@@ -6102,7 +6102,7 @@
"tabLedger": "Waiting orders",
"tabSends": "Send records",
"tabConfig": "Alert settings",
"sendsLead": "The daily scan creates records waiting to be sent. They appear here after the Friday 18:00 summary goes out to each recipient. Names stay as they were at send time.",
"sendsLead": "The daily scan creates records waiting to be sent. They appear here after the Friday 18:30 summary goes out to each recipient. Names stay as they were at send time.",
"excelColumn": "Excel attachment",
"sentExcelTitle": "Sent Excel files",
"sentExcelHint": "One file per recipient. You can download the copy that was sent.",
@@ -6111,10 +6111,16 @@
"sendsFailed": "Failed to load send records",
"scanAlerts": "Scan alerts",
"sendAlerts": "Send alerts",
"scanConfirm": "This syncs from E10 and creates records waiting to be sent.",
"sendConfirm": "This sends the waiting records to WeCom, one message per recipient.",
"scanConfirm": "This queues a background sync and creates records waiting to be sent. The page will not wait for the whole run.",
"sendConfirm": "This queues background WeCom sends, one message per recipient. Do not click again until it finishes, or people may get duplicates.",
"scanDone": "Added {created}, updated {updated}, cancelled {cancelled}",
"sendDone": "Sent to {sent} people, {failed} failed",
"sendPartial": "Sent to {sent} people; {failed} failed",
"sendFailedCount": "{failed} people failed. Refresh the list for reasons.",
"sendEmpty": "There are no pending alerts, so send records will not change",
"jobSubmitted": "The job was queued for the background worker",
"jobTimeout": "The job is still running in the background. Refresh send records later for the result.",
"jobError": "The background job failed",
"sendResult": "Result",
"failureReason": "Failure reason",
"failureReasonEmpty": "No failure reason was recorded",
+9 -3
View File
@@ -6102,7 +6102,7 @@
"tabLedger": "รายการค้าง",
"tabSends": "บันทึกการส่ง",
"tabConfig": "ตั้งค่าการเตือน",
"sendsLead": "การสแกนรายวันสร้างรายการที่รอส่ง หลังสรุปส่งทุกวันศุกร์ 18:00 ตามผู้รับแล้ว จะแสดงที่นี่ ชื่อคงตามตอนที่ส่ง",
"sendsLead": "การสแกนรายวันสร้างรายการที่รอส่ง หลังสรุปส่งทุกวันศุกร์ 18:30 ตามผู้รับแล้ว จะแสดงที่นี่ ชื่อคงตามตอนที่ส่ง",
"excelColumn": "ไฟล์แนบ Excel",
"sentExcelTitle": "ไฟล์ Excel ที่ส่งแล้ว",
"sentExcelHint": "หนึ่งไฟล์ต่อผู้รับหนึ่งคน ดาวน์โหลดสำเนาที่ส่งไปแล้วได้",
@@ -6111,10 +6111,16 @@
"sendsFailed": "โหลดบันทึกการส่งไม่สำเร็จ",
"scanAlerts": "สแกนการเตือน",
"sendAlerts": "ส่งการเตือน",
"scanConfirm": "ระบบจะซิงก์จาก E10 และสร้างรายการที่รอส่ง",
"sendConfirm": "ระบบจะส่งรายการที่รอส่งไป WeCom คนละหนึ่งข้อความ",
"scanConfirm": "ระบบจะส่งงานไปทำงานพื้นหลังเพื่อซิงก์และสร้างรายการที่รอส่ง หน้าจอจะไม่รอจนจบ",
"sendConfirm": "ระบบจะส่งงานพื้นหลังไป WeCom คนละหนึ่งข้อความ อย่ากดซ้ำจนกว่าจะเสร็จ เพื่อเลี่ยงข้อความซ้ำ",
"scanDone": "เพิ่ม {created} รายการ อัปเดต {updated} รายการ ยกเลิก {cancelled} รายการ",
"sendDone": "ส่งถึง {sent} คน ไม่สำเร็จ {failed} คน",
"sendPartial": "ส่งถึง {sent} คน และมี {failed} คนที่ไม่สำเร็จ",
"sendFailedCount": "{failed} คนส่งไม่สำเร็จ รีเฟรชรายการเพื่อดูสาเหตุ",
"sendEmpty": "ไม่มีรายการที่รอส่ง บันทึกการส่งจะไม่เปลี่ยน",
"jobSubmitted": "ส่งงานเข้าคิวพื้นหลังแล้ว",
"jobTimeout": "งานยังทำงานอยู่พื้นหลัง โปรดรีเฟรชบันทึกการส่งภายหลัง",
"jobError": "งานพื้นหลังล้มเหลว",
"sendResult": "ผลลัพธ์",
"failureReason": "สาเหตุที่ล้มเหลว",
"failureReasonEmpty": "ไม่ได้บันทึกสาเหตุ",
+9 -3
View File
@@ -6116,7 +6116,7 @@
"tabLedger": "停留情况",
"tabSends": "发送记录",
"tabConfig": "预警配置",
"sendsLead": "每日扫描生成待发送。默认每周五 18:00 按收件人汇总发出后记在这里。已发送的姓名保持发送当时的人。",
"sendsLead": "每日扫描生成待发送。默认每周五 18:30 按收件人汇总发出后记在这里。已发送的姓名保持发送当时的人。",
"excelColumn": "Excel 附件",
"sentExcelTitle": "已发送的 Excel",
"sentExcelHint": "每位收件人一份,可再次下载当时发出的文件。",
@@ -6125,10 +6125,16 @@
"sendsFailed": "读取发送记录失败",
"scanAlerts": "扫描预警",
"sendAlerts": "发送预警",
"scanConfirm": "将从 E10 同步,并生成待发送记录。",
"sendConfirm": "将把待发送记录按收件人发到企业微信。",
"scanConfirm": "将在后台同步并生成待发送记录,页面不会一直等待。",
"sendConfirm": "将在后台按收件人发到企业微信。发送完前请勿重复点击,以免重复通知。",
"scanDone": "新增 {created} 条,更新 {updated} 条,取消 {cancelled} 条",
"sendDone": "已向 {sent} 人发送,{failed} 人失败",
"sendPartial": "已向 {sent} 人发送,另有 {failed} 人失败",
"sendFailedCount": "{failed} 人发送失败,可刷新列表查看原因",
"sendEmpty": "没有可发送的预警,发送记录不会变化",
"jobSubmitted": "任务已提交后台执行",
"jobTimeout": "任务仍在后台执行,请稍后刷新发送记录查看结果",
"jobError": "后台任务执行失败",
"sendResult": "结果",
"failureReason": "失败原因",
"failureReasonEmpty": "没有记下失败原因",
+9 -3
View File
@@ -6102,7 +6102,7 @@
"tabLedger": "停留情況",
"tabSends": "發送記錄",
"tabConfig": "預警配置",
"sendsLead": "每日掃描產生待發送。預設每週五 18:00 按收件人彙總發出後記在這裡。已發送的姓名保持發送當時的人。",
"sendsLead": "每日掃描產生待發送。預設每週五 18:30 按收件人彙總發出後記在這裡。已發送的姓名保持發送當時的人。",
"excelColumn": "Excel 附件",
"sentExcelTitle": "已發送的 Excel",
"sentExcelHint": "每位收件人一份,可再次下載當時發出的檔案。",
@@ -6111,10 +6111,16 @@
"sendsFailed": "讀取發送記錄失敗",
"scanAlerts": "掃描預警",
"sendAlerts": "發送預警",
"scanConfirm": "將從 E10 同步,並產生待發送記錄。",
"sendConfirm": "將把待發送記錄按收件人發到企業微信。",
"scanConfirm": "將在背景同步並產生待發送記錄,頁面不會一直等待。",
"sendConfirm": "將在背景按收件人發到企業微信。發送完前請勿重複點擊,以免重複通知。",
"scanDone": "新增 {created} 條,更新 {updated} 條,取消 {cancelled} 條",
"sendDone": "已向 {sent} 人發送,{failed} 人失敗",
"sendPartial": "已向 {sent} 人發送,另有 {failed} 人失敗",
"sendFailedCount": "{failed} 人發送失敗,可重新整理列表查看原因",
"sendEmpty": "沒有可發送的預警,發送記錄不會變化",
"jobSubmitted": "任務已提交背景執行",
"jobTimeout": "任務仍在背景執行,請稍後重新整理發送記錄查看結果",
"jobError": "背景任務執行失敗",
"sendResult": "結果",
"failureReason": "失敗原因",
"failureReasonEmpty": "沒有記下失敗原因",