Merge branch 'fix-contract' into dev
This commit is contained in:
commit
d13c881efb
26 files changed
+1599
-117
No files matched your search
@@ -3,7 +3,8 @@ backend/app/api/contract_payment.py
|
||||
|
||||
用途:采购合同付款预警 Agent 的合同台账、付款计划、待发送摘要、台账汇总卡和同步 API。
|
||||
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、Agent 授权、contract_payment 服务和通用 Job 队列。
|
||||
逻辑:页面查询合同、节点、本周待发送摘要与四张汇总卡;同步和预警操作入队,避免请求线程执行外部系统和企微调用。
|
||||
逻辑:页面查询合同、节点、本周待发送摘要、四张汇总卡和周汇总批次;失败批次返回可展示原因。同步和预警操作入队,避免请求线程执行外部系统和企微调用;发送后可按 Job 查询是否真正完成。
|
||||
下载和单合同重解析走 read_contract_attachment_bytes:原文还在则直接读,被临时清理删掉则按附件 ID 从 OA/DMS 重新下载。
|
||||
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍。
|
||||
鉴权:查询接口要求平台 admin 或持有 `agent_code=contract_payment` 的 Agent 授权;
|
||||
同步/扫描/周汇总发送仅 `role=admin`。
|
||||
@@ -28,16 +29,20 @@ from app.models import (
|
||||
ContractPaymentContract,
|
||||
ContractPaymentNode,
|
||||
FileAsset,
|
||||
Job,
|
||||
)
|
||||
from app.services.contract_payment.alert_service import build_weekly_alert_summary
|
||||
from app.services.contract_payment.alert_service import build_weekly_alert_summary, describe_batch_failure
|
||||
from app.services.contract_payment.ledger_focus import (
|
||||
LEDGER_FOCUS_VALUES,
|
||||
apply_ledger_focus,
|
||||
ledger_focus_counts,
|
||||
)
|
||||
from app.services.contract_payment.parse_service import unique_parse_issues
|
||||
from app.services.contract_payment.sync_service import build_payment_plan, build_payment_plan_from_bytes
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
from app.services.contract_payment.sync_service import (
|
||||
build_payment_plan,
|
||||
build_payment_plan_from_bytes,
|
||||
read_contract_attachment_bytes,
|
||||
)
|
||||
|
||||
|
||||
contract_payment_bp = Blueprint("contract_payment", __name__)
|
||||
@@ -354,7 +359,8 @@ def download_contract_attachment(contract_id: int, attachment_id: int):
|
||||
"""
|
||||
下载合同详情中已归档的原文附件。
|
||||
|
||||
核心逻辑:附件必须同时属于请求中的合同和本地 FileAsset,避免通过附件 ID 越权读取其他合同原文。
|
||||
核心逻辑:附件必须属于请求中的合同。本地 FileAsset 仍可读时直接返回;
|
||||
若临时清理已删除对象,则按 OA/DMS 附件 ID 重新下载后再返回。
|
||||
|
||||
Args:
|
||||
contract_id: 合同台账主键。
|
||||
@@ -364,20 +370,19 @@ def download_contract_attachment(contract_id: int, attachment_id: int):
|
||||
受控下载的附件二进制流。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 合同、附件或其保存的文件资产不存在。
|
||||
NotFoundError: 合同或附件不存在,或原文已被清理且无法从原系统重新下载。
|
||||
"""
|
||||
_require_contract_payment_access()
|
||||
row = db.session.get(ContractPaymentContract, contract_id)
|
||||
attachment = db.session.query(ContractPaymentAttachment).filter_by(id=attachment_id, contract_id=contract_id).first()
|
||||
if not attachment or not attachment.file_asset_id:
|
||||
raise NotFoundError("合同原文附件不存在")
|
||||
asset = db.session.get(FileAsset, attachment.file_asset_id)
|
||||
if not asset:
|
||||
if not row or not attachment or not attachment.file_asset_id:
|
||||
raise NotFoundError("合同原文附件不存在")
|
||||
data = read_contract_attachment_bytes(row, attachment)
|
||||
return send_file(
|
||||
BytesIO(read_asset_bytes(asset)),
|
||||
mimetype=attachment.mime_type or asset.mime_type or "application/octet-stream",
|
||||
BytesIO(data),
|
||||
mimetype=attachment.mime_type or "application/octet-stream",
|
||||
as_attachment=True,
|
||||
download_name=attachment.file_name or asset.original_filename,
|
||||
download_name=attachment.file_name or "contract",
|
||||
)
|
||||
|
||||
|
||||
@@ -464,9 +469,55 @@ def enqueue_weekly_alert_send():
|
||||
return ok({"job_id": job_id}, request_id=getattr(g, "request_id", None), status=202)
|
||||
|
||||
|
||||
_CONTRACT_PAYMENT_JOB_TYPES = {
|
||||
JobType.CONTRACT_PAYMENT_SYNC.value,
|
||||
JobType.CONTRACT_PAYMENT_ALERT.value,
|
||||
JobType.CONTRACT_PAYMENT_ALERT_WEEKLY.value,
|
||||
}
|
||||
|
||||
|
||||
@contract_payment_bp.route("/jobs/<int:job_id>", methods=["GET"])
|
||||
def get_contract_payment_job(job_id: int):
|
||||
"""查询当前管理员提交的合同付款后台任务是否已经跑完。
|
||||
|
||||
核心逻辑:只返回本人创建的合同付款 Job,避免用任务号读到其它域的执行结果。
|
||||
周汇总发送的 result 含 sent / failed,供页面在刷新批次列表前判断这次有没有真正发出。
|
||||
|
||||
Args:
|
||||
job_id: jobs 表主键。
|
||||
|
||||
Returns:
|
||||
标准成功 envelope,含 status、message 与 result。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 任务不存在,或不属于当前管理员的合同付款任务。
|
||||
"""
|
||||
user = _require_contract_payment_admin()
|
||||
row = db.session.get(Job, job_id)
|
||||
if (
|
||||
row is None
|
||||
or row.domain != "procurement_contract"
|
||||
or row.job_type not in _CONTRACT_PAYMENT_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))
|
||||
|
||||
|
||||
@contract_payment_bp.route("/alert-batches", methods=["GET"])
|
||||
def list_alert_batches():
|
||||
"""查询近期合同付款预警周汇总批次。"""
|
||||
"""查询近期合同付款预警周汇总批次。
|
||||
|
||||
核心逻辑:按创建时间倒序最多返回 100 条。失败批次附带 failure_reasons,
|
||||
供周汇总页点击图标展示;成功批次不返回原因,也不下发企微原始轨迹。
|
||||
Returns:
|
||||
标准成功 envelope,items 含批次摘要;失败项另含 failure_reasons。
|
||||
"""
|
||||
_require_contract_payment_access()
|
||||
rows = db.session.query(ContractPaymentAlertBatch).order_by(ContractPaymentAlertBatch.created_at.desc()).limit(100).all()
|
||||
return ok({"items": [{
|
||||
@@ -475,6 +526,11 @@ def list_alert_batches():
|
||||
"summary": row.summary_json, "excel_file_name": row.excel_file_name,
|
||||
"excel_file_size": row.excel_file_size, "sent_at": row.sent_at.isoformat() if row.sent_at else None,
|
||||
"created_at": row.created_at.isoformat(),
|
||||
"failure_reasons": (
|
||||
describe_batch_failure(row.wecom_trace_json, fallback=row.error_message)
|
||||
if row.status == "failed"
|
||||
else []
|
||||
),
|
||||
} for row in rows]}, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@@ -519,8 +575,8 @@ def reparse_contract_attachment(contract_id: int):
|
||||
"""
|
||||
使用已归档的合同原文附件重新生成付款解析结果。
|
||||
|
||||
核心逻辑:管理员在待确认合同中发现旧规则或附件抽取异常时触发;服务端只读取该合同
|
||||
已保存的附件,优先盖章完成合同上传,覆盖付款节点、解析状态和问题列表,不调用 OA。
|
||||
核心逻辑:管理员在待确认合同中发现旧规则或附件抽取异常时触发;优先读取该合同
|
||||
已保存的附件(盖章完成合同上传优先)。原文若已被临时清理删除,则按附件 ID 重新下载后再解析。
|
||||
Args:
|
||||
contract_id: 合同付款台账主键。
|
||||
Returns:
|
||||
@@ -543,10 +599,8 @@ def reparse_contract_attachment(contract_id: int):
|
||||
raise ValidationError("当前合同没有已归档的原文附件,无法重新解析", code="CONTRACT_PAYMENT.ATTACHMENT_REQUIRED")
|
||||
# [STEP 1] 使用同步链路同一附件优先级,保证人工重跑与首次解析的结果可复现。
|
||||
attachment = min(attachments, key=_attachment_parse_priority)
|
||||
asset = db.session.get(FileAsset, attachment.file_asset_id)
|
||||
if not asset:
|
||||
raise ValidationError("当前合同原文附件不存在,无法重新解析", code="CONTRACT_PAYMENT.ATTACHMENT_REQUIRED")
|
||||
result = build_payment_plan_from_bytes(row, filename=attachment.file_name, data=read_asset_bytes(asset))
|
||||
data = read_contract_attachment_bytes(row, attachment)
|
||||
result = build_payment_plan_from_bytes(row, filename=attachment.file_name, data=data)
|
||||
return ok({
|
||||
"contract": _serialize_contract(row),
|
||||
"parse_result": result,
|
||||
|
||||
@@ -3,7 +3,7 @@ services/contract_payment/alert_service.py
|
||||
|
||||
用途:按付款阶段生成待发送预警,在每周五按收件人汇总发送企业微信和 Excel 明细,并提供工作台待发送摘要。
|
||||
依赖:合同付款模型、用户目录、openpyxl、企业微信通知服务、OA 上级矩阵、排程时区工具。
|
||||
逻辑:每日任务只写入 pending 审计;周汇总任务锁定本周收件人批次,发送一条汇总卡片和一份逐笔 Excel;摘要接口与周五发送使用同一 pending 口径。
|
||||
逻辑:每日任务只写入 pending 审计;周汇总任务锁定本周收件人批次,发送一条汇总卡片和一份逐笔 Excel;发送失败时把原因写入批次审计。摘要接口与周五发送使用同一 pending 口径。
|
||||
第一轮按台账申请人 `real_name` 唯一匹配系统用户;第二、三轮查 OA HrmResource + Matrixtable_3,用 zz/jfl 作为企微 userid,不向第一轮兜底。
|
||||
"""
|
||||
|
||||
@@ -152,11 +152,106 @@ def _resolve_pending_alerts(*, node_id: int) -> int:
|
||||
return len(rows)
|
||||
|
||||
|
||||
_FAILURE_REASON_LABELS: dict[str, str] = {
|
||||
"notify_disabled": "企业微信通知未启用",
|
||||
"event_disabled": "合同付款预警通知事件未启用",
|
||||
"user_unbound": "收件人未绑定企业微信账号",
|
||||
"textcard_failed": "企业微信卡片发送失败",
|
||||
"file_upload_failed": "企业微信附件上传失败",
|
||||
"file_failed": "企业微信附件发送失败",
|
||||
"unknown": "发送失败",
|
||||
}
|
||||
|
||||
|
||||
def _append_failure_reason(reasons: list[dict[str, str]], code: str, detail: str = "") -> None:
|
||||
"""向失败原因列表追加一条去重后的记录。
|
||||
|
||||
核心逻辑:压缩 detail 空白并截断到 500 字;code 与 detail 都相同则跳过。
|
||||
|
||||
Args:
|
||||
reasons: 正在组装的原因列表,就地修改。
|
||||
code: 前端可翻译的原因编码。
|
||||
detail: 企微或异常返回的补充说明,可为空。
|
||||
"""
|
||||
normalized = " ".join(str(detail or "").split())[:500]
|
||||
if any(item["code"] == code and item["detail"] == normalized for item in reasons):
|
||||
return
|
||||
reasons.append({"code": code, "detail": normalized})
|
||||
|
||||
|
||||
def describe_batch_failure(trace: dict | None, *, fallback: str | None = None) -> list[dict[str, str]]:
|
||||
"""把周汇总企微发送轨迹整理成可展示的失败原因。
|
||||
|
||||
核心逻辑:优先识别卡片失败、附件上传异常和附件发送失败;「未绑定企微」只保留一条。
|
||||
轨迹无法识别时回退到已保存的 error_message,避免历史失败批次没有原因可看。
|
||||
|
||||
Args:
|
||||
trace: 批次 wecom_trace_json。非字典时忽略。
|
||||
fallback: 轨迹无法识别时使用的已存错误文本。
|
||||
|
||||
Returns:
|
||||
原因列表。每项含 code 与 detail;没有可展示原因时返回空列表。
|
||||
"""
|
||||
reasons: list[dict[str, str]] = []
|
||||
# [STEP 1] 卡片发送失败优先按已知原因码归类,企微 errmsg 放在 detail。
|
||||
if isinstance(trace, dict):
|
||||
textcard = trace.get("textcard") if isinstance(trace.get("textcard"), dict) else {}
|
||||
if textcard and not textcard.get("ok"):
|
||||
reason = str(textcard.get("reason") or "").strip()
|
||||
raw = textcard.get("raw") if isinstance(textcard.get("raw"), dict) else {}
|
||||
errmsg = str(raw.get("errmsg") or "").strip()
|
||||
if reason in {"notify_disabled", "event_disabled", "user_unbound"}:
|
||||
_append_failure_reason(reasons, reason)
|
||||
else:
|
||||
_append_failure_reason(reasons, "textcard_failed", errmsg)
|
||||
|
||||
# [STEP 2] 附件失败与卡片失败分开记录;未绑定账号不重复展示。
|
||||
file_error = str(trace.get("file_error") or "").strip()
|
||||
if file_error:
|
||||
_append_failure_reason(reasons, "file_upload_failed", file_error)
|
||||
else:
|
||||
file_result = trace.get("file") if isinstance(trace.get("file"), dict) else {}
|
||||
errcode = file_result.get("errcode")
|
||||
if errcode not in (None, 0, "0"):
|
||||
errmsg = str(file_result.get("errmsg") or "").strip()
|
||||
if errmsg == "user_unbound":
|
||||
_append_failure_reason(reasons, "user_unbound")
|
||||
else:
|
||||
_append_failure_reason(reasons, "file_failed", errmsg or str(errcode))
|
||||
|
||||
if reasons:
|
||||
return reasons
|
||||
stored = " ".join(str(fallback or "").split())
|
||||
if stored:
|
||||
_append_failure_reason(reasons, "unknown", stored[:2000])
|
||||
return reasons
|
||||
|
||||
|
||||
def render_batch_failure_message(reasons: list[dict[str, str]]) -> str:
|
||||
"""把失败原因编码拼成写入批次审计字段的中文摘要。
|
||||
|
||||
核心逻辑:使用固定中文标签,detail 非空时接在标签后,多条以分号连接。
|
||||
|
||||
Args:
|
||||
reasons: describe_batch_failure 的返回值。
|
||||
|
||||
Returns:
|
||||
最长 2000 字的中文摘要;没有原因时返回空字符串。
|
||||
"""
|
||||
parts: list[str] = []
|
||||
for item in reasons:
|
||||
label = _FAILURE_REASON_LABELS.get(str(item.get("code") or ""), "发送失败")
|
||||
detail = str(item.get("detail") or "").strip()
|
||||
parts.append(f"{label}:{detail}" if detail else label)
|
||||
return ";".join(parts)[:2000]
|
||||
|
||||
|
||||
def send_weekly_alerts(*, today: date | None = None) -> dict[str, int]:
|
||||
"""按收件人发送本周合同付款预警汇总及 Excel 明细。
|
||||
|
||||
AI 触发时机:每周五 18:00 的排程或管理员补发时调用。
|
||||
核心逻辑:每位收件人每周只产生一个批次;企微正文仅发送总笔数和阶段数量,逐笔信息写入附件。
|
||||
发送失败时把卡片和附件的原因写入 error_message,并把 sent_at 记为最近一次尝试时间,供周汇总页查看。
|
||||
Args:
|
||||
today: 用于确定 ISO 周标识,测试可显式传入。
|
||||
Returns:
|
||||
@@ -231,7 +326,9 @@ def send_weekly_alerts(*, today: date | None = None) -> dict[str, int]:
|
||||
sent += 1
|
||||
else:
|
||||
batch.status = "failed"
|
||||
batch.error_message = str(trace)[:2000]
|
||||
# 失败也记录尝试时刻,周汇总「发送时间」不再空白;重试时覆盖为最近一次。
|
||||
batch.sent_at = datetime.utcnow()
|
||||
batch.error_message = render_batch_failure_message(describe_batch_failure(trace)) or str(trace)[:2000]
|
||||
failed += 1
|
||||
db.session.commit()
|
||||
return {"batches": batches, "sent": sent, "failed": failed, "alerts": detail_count}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/contract_payment/ledger_focus.py
|
||||
|
||||
用途:合同台账汇总卡口径——即将到期、逾期未付、进行中、本月应付,均按合同计数。
|
||||
用途:合同台账汇总卡口径——即将到期、逾期未付、未到期(7日外)、本月应付,均按合同计数。
|
||||
依赖:ContractPaymentContract、ContractPaymentNode、业务时区 Asia/Shanghai。
|
||||
逻辑:由 list/summary API 调用;即将到期/逾期/进行中互斥,本月应付可与这三项重叠。行级「待补充」不进汇总卡。
|
||||
逻辑:由 list/summary API 调用;即将到期/逾期/未到期互斥,本月应付可与这三项重叠。行级「待补充」不进汇总卡。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -138,7 +138,7 @@ def collect_ledger_focus(*, session: Session, today: date | None = None) -> dict
|
||||
"""
|
||||
扫描全部已解析台账合同,按汇总卡口径收集合同 ID。
|
||||
|
||||
核心逻辑:不应用页面 keyword;待确认合同不进入台账汇总。进行中为未到期且未逾期的未付合同;本月应付可与即将到期、逾期或进行中重叠。
|
||||
核心逻辑:不应用页面 keyword;待确认合同不进入台账汇总。未到期为付款日在 7 日以外且未逾期的未付合同;本月应付可与即将到期、逾期或未到期重叠。
|
||||
Args:
|
||||
session: 当前请求的 SQLAlchemy 会话。
|
||||
today: 可选业务日。
|
||||
|
||||
@@ -5,6 +5,7 @@ services/contract_payment/oa_client.py
|
||||
依赖:requests、lxml、Flask 配置;由 sync_service 负责将本客户端的标准化结果落库。
|
||||
逻辑:同一登录会话顺序扫描待办和已办归档列表并翻页;满页大小以 OA 实际返回行数为准(泛微默认 10 条/页),
|
||||
不得用配置页大小把首页短页误判为到底;首次全量翻到短页为止,增量触顶页上限时标记截断供同步层不推进断点。
|
||||
合同原文被临时文件清理删掉后,可按流程 ID 与附件 ID 重新打开详情并下载。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -340,6 +341,49 @@ class ContractOaClient:
|
||||
content_type = (response.headers.get("content-type") or "application/octet-stream").split(";", 1)[0].strip().lower()
|
||||
return data, content_type, _filename_from_disposition(response.headers.get("content-disposition"))
|
||||
|
||||
def download_attachment_by_id(self, *, process_id: str, attachment_id: str) -> tuple[bytes, str, str | None]:
|
||||
"""
|
||||
按 OA 流程和附件 ID 重新下载合同原文。
|
||||
|
||||
用途:合同附件曾按临时 FileAsset 落库,清理任务删除对象后,详情页下载和重解析用本方法找回字节。
|
||||
核心逻辑:打开 ViewRequest.jsp,在详情解析出的附件里匹配 attachment_id,再走 download_attachment。
|
||||
|
||||
Args:
|
||||
process_id: OA requestid,对应合同台账 oa_record_id。
|
||||
attachment_id: 详情页附件 ID,对应附件 source_key 去掉 `oa:` 前缀后的值。
|
||||
|
||||
Returns:
|
||||
文件字节、MIME 类型和响应头文件名。
|
||||
|
||||
Raises:
|
||||
ValueError: 流程 ID 或附件 ID 为空。
|
||||
RuntimeError: OA 未配置、详情打不开,或详情中没有该附件。
|
||||
requests.RequestException: 登录失效或 OA 下载失败。
|
||||
"""
|
||||
process_id = str(process_id or "").strip()
|
||||
attachment_id = str(attachment_id or "").strip()
|
||||
if not process_id or not attachment_id:
|
||||
raise ValueError("缺少 OA 流程或附件 ID")
|
||||
if not self.is_configured():
|
||||
raise RuntimeError("OA 未配置,无法重新下载合同附件")
|
||||
session = self._session()
|
||||
detail = self._fetch_detail(session, {
|
||||
"process_id": process_id,
|
||||
"detail_url": f"/workflow/request/ViewRequest.jsp?requestid={process_id}",
|
||||
})
|
||||
if not detail:
|
||||
raise RuntimeError("无法打开 OA 合同详情")
|
||||
match = next(
|
||||
(
|
||||
item for item in (detail.get("attachments") or [])
|
||||
if str(item.get("attachment_id") or "").strip() == attachment_id
|
||||
),
|
||||
None,
|
||||
)
|
||||
if match is None:
|
||||
raise RuntimeError("OA 详情中找不到原合同附件")
|
||||
return self.download_attachment(match)
|
||||
|
||||
def _session(self, *, refresh: bool = False) -> requests.Session:
|
||||
"""复用 20 分钟 OA 登录会话;登录字段通过环境变量覆盖以适配不同 OA 部署。"""
|
||||
with _SESSION_LOCK:
|
||||
|
||||
@@ -4,7 +4,7 @@ backend/app/services/contract_payment/parse_service.py
|
||||
用途:从 DOC/DOCX/PDF/TXT 抽取采购合同关键字段,并生成四个付款阶段的节点草稿。
|
||||
依赖:标准库正则与日期处理;原文抽取由调用方传入,避免绑定某一种文件解析器。
|
||||
逻辑:先识别固定字段和付款比例,再校验金额/比例/日期;无法确定的事实进入 needs_review,不猜测。
|
||||
同一付款阶段的相同比例重复抽取不报重复;详情接口展示前对 issues 去重。
|
||||
合同金额以正文抽出的正数为准;OA 的 0 与空值都不是有效总额。同一付款阶段的相同比例重复抽取不报重复。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -84,6 +84,26 @@ def _parse_decimal(value: str | None) -> Decimal | None:
|
||||
return None
|
||||
|
||||
|
||||
def positive_amount(value: object) -> Decimal | None:
|
||||
"""把金额归一为大于 0 的 Decimal。
|
||||
|
||||
核心逻辑:员工在 OA「合同金额」手填 0 时,0 与空值一样,都不能当成有效总额。
|
||||
正文抽出的正数才会用于阶段金额,并在台账总额为 0 或空时回写。
|
||||
|
||||
Args:
|
||||
value: OA 字段、正文抽取结果或库里的金额,可为 str、Decimal 或 None。
|
||||
|
||||
Returns:
|
||||
大于 0 的金额;空值、0、负数或非法格式返回 None。
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
parsed = _parse_decimal(str(value))
|
||||
if parsed is None or parsed <= 0:
|
||||
return None
|
||||
return parsed
|
||||
|
||||
|
||||
def _to_days(value: int, unit: str) -> int:
|
||||
"""
|
||||
将质保期限统一为自然日。
|
||||
@@ -284,8 +304,9 @@ def parse_contract_text(text: str, *, total_amount: Decimal | None = None, deliv
|
||||
|
||||
AI 触发时机:合同附件保存后,需要自动获得付款节点时调用。
|
||||
参数约束:text 为已抽取正文;不允许用模型猜测缺失日期或比例,结果必须可序列化为 JSON。
|
||||
口径约定:合同正文是条款事实的权威来源;正文能抽取金额/交货期限时,即使与 OA 表单不同,
|
||||
也以正文为准,不生成“与OA字段不一致”的待确认问题;仅当正文无法抽取时才回退 OA 表单值。
|
||||
口径约定:合同正文抽出的正数金额优先于 OA。OA「合同金额」为 0 或空视为未录入,
|
||||
不生成“与OA字段不一致”的待确认问题;正文没有正数时才回退 OA 里大于 0 的金额。
|
||||
两边都没有有效金额时进入待确认,不把 0 当成总额。
|
||||
Returns:
|
||||
包含 fields、nodes、status、issues、evidence 的结构化结果。
|
||||
"""
|
||||
@@ -293,14 +314,11 @@ def parse_contract_text(text: str, *, total_amount: Decimal | None = None, deliv
|
||||
if body.startswith("[binary:"):
|
||||
body = ""
|
||||
issues: list[str] = []
|
||||
# 合同正文是条款事实的权威来源;OA 字段只在正文未写明时作为补充。
|
||||
# 正文能抽到金额/交货期限即以其为准,即使与 OA 表单不同也不再生成“不一致”待确认问题,
|
||||
# 避免 OA 申请人录入错误把本可自动预警的合同永久卡在待复核。
|
||||
# [STEP 1] 金额:正文正数优先。OA 手填 0 与空值都不是有效总额,不能拿来乘付款比例。
|
||||
# 正文没有正数时,才用 OA 里大于 0 的金额;两边都没有则金额留空并进入待确认。
|
||||
amount_match = _MONEY_RE.search(body)
|
||||
amount_from_contract = _parse_decimal(amount_match.group(1)) if amount_match else None
|
||||
# OA 字段 total_amount 可能是字符串(如 _parse_amount 返回的 "221000.00"),统一归一为 Decimal,
|
||||
# 否则下方 `amount * percentage` 会因字符串与 Decimal 相乘抛出 TypeError。
|
||||
total_decimal = _parse_decimal(total_amount)
|
||||
amount_from_contract = positive_amount(amount_match.group(1)) if amount_match else None
|
||||
total_decimal = positive_amount(total_amount)
|
||||
# 正文缺失时需回退 OA 交货期限;OA 字段可能以字符串到达(如 "2026-09-10"),
|
||||
# 归一为 date 避免交付节点在 due_date.isoformat() 处因字符串抛错。
|
||||
delivery_due_date = _parse_date(delivery_due_date)
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
backend/app/services/contract_payment/sync_service.py
|
||||
|
||||
用途:将 OA 合同、验收归档通知同步为合同付款预警事实,并由 ERP `apa_file` 提供付款完成事实。
|
||||
依赖:ContractOaClient、acceptance_oa_service、ContractPayment* 模型、parse_service。
|
||||
依赖:ContractOaClient、acceptance_oa_service、ContractPayment* 模型、parse_service、file_assets.service。
|
||||
逻辑:合同申请单走 HTTP 待办/已办;验收归档走 OA SQL(formtable_main_324.cgdh × workflow_requestbase.currentnodetype=3);
|
||||
通知按 source_event_id 幂等;合同编号与采购单号以 OA 为准;列表翻页截断时入库但不推进增量断点;
|
||||
付款状态不再读取 OA 请款作业;合同 owner_user_id 由申请人真实姓名匹配系统用户,附件存储所有者仍可回退默认账号。
|
||||
OA 合同金额为 0 或空时不当有效总额;正文抽出的正数在解析时回写台账,强制覆盖也不能把正数总额改成 0。
|
||||
OA/DMS 合同原文落库后标为已引用;临时清理删掉对象后,下载和重解析按附件 ID 重新下载。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,6 +20,7 @@ from typing import Any
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import (
|
||||
ContractPaymentAttachment,
|
||||
ContractPaymentContract,
|
||||
@@ -34,9 +37,14 @@ from app.services.contract_payment.acceptance_oa_service import (
|
||||
)
|
||||
from app.services.contract_payment.oa_client import ContractOaClient
|
||||
from app.services.contract_payment.dms_client import ContractDmsClient
|
||||
from app.services.contract_payment.parse_service import parse_contract_bytes, parse_contract_text
|
||||
from app.services.contract_payment.parse_service import parse_contract_bytes, parse_contract_text, positive_amount
|
||||
from app.services.contract_payment.alert_service import bind_contract_owner_from_applicant
|
||||
from app.services.file_assets.service import create_derived_file_asset_from_bytes, generate_asset_no
|
||||
from app.services.file_assets.service import (
|
||||
create_derived_file_asset_from_bytes,
|
||||
generate_asset_no,
|
||||
mark_asset_referenced,
|
||||
read_asset_bytes,
|
||||
)
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
|
||||
@@ -172,7 +180,7 @@ def sync_notifications(*, client: ContractOaClient | None = None, force: bool =
|
||||
purchase_order_no=str(item.get("purchase_order_no") or "").strip() or None,
|
||||
supplier_name=str(item.get("supplier_name") or "").strip() or None,
|
||||
applicant_name=str(item.get("applicant_name") or "").strip() or None,
|
||||
total_amount=item.get("total_amount"),
|
||||
total_amount=positive_amount(item.get("total_amount")),
|
||||
currency=str(item.get("currency") or "").strip() or None,
|
||||
effective_date=_as_date(item.get("effective_date")),
|
||||
delivery_due_date=_as_date(item.get("delivery_due_date")),
|
||||
@@ -192,9 +200,12 @@ def sync_notifications(*, client: ContractOaClient | None = None, force: bool =
|
||||
contract.purchase_order_no = contract.purchase_order_no or str(item.get("purchase_order_no") or "").strip() or None
|
||||
contract.applicant_name = contract.applicant_name or str(item.get("applicant_name") or "").strip() or None
|
||||
# [STEP 0] 普通同步只回填“仍为空”的 OA 标量字段,不用本次值覆盖已有值。
|
||||
# 合同金额/供应商/币别/生效/交货期限仅在创建时写入;早前创建时缺失的历史合同可由此自愈。
|
||||
# 合同金额的 0 与空相同,不能挡住正文正数,也不能用 OA 的 0 覆盖已有正数。
|
||||
contract.supplier_name = contract.supplier_name or str(item.get("supplier_name") or "").strip() or None
|
||||
contract.total_amount = contract.total_amount or item.get("total_amount")
|
||||
if positive_amount(contract.total_amount) is None:
|
||||
incoming_amount = positive_amount(item.get("total_amount"))
|
||||
if incoming_amount is not None:
|
||||
contract.total_amount = incoming_amount
|
||||
contract.currency = contract.currency or (str(item.get("currency") or "").strip() or None)
|
||||
contract.effective_date = contract.effective_date or _as_date(item.get("effective_date"))
|
||||
contract.delivery_due_date = contract.delivery_due_date or _as_date(item.get("delivery_due_date"))
|
||||
@@ -453,8 +464,8 @@ def _overwrite_oa_fields(contract: ContractPaymentContract, item: dict[str, Any]
|
||||
"""
|
||||
显式强制同步时,用 OA 本次返回的非空字段覆盖合同主表值。
|
||||
|
||||
核心逻辑:只接受 OA 明确返回的非空值,避免 OA 页面临时缺字段把本地正确值清空;同时把
|
||||
before/after 和操作人写入 source_payload_json,便于追溯“为什么金额发生变化”。
|
||||
核心逻辑:只接受 OA 明确返回的非空值,避免 OA 页面临时缺字段把本地正确值清空。
|
||||
合同金额为 0 视为未录入,不覆盖台账上已有的正数总额。变更写入 source_payload_json。
|
||||
Args:
|
||||
contract: 待更新的合同主记录。
|
||||
item: OA 合同归档事件。
|
||||
@@ -466,7 +477,7 @@ def _overwrite_oa_fields(contract: ContractPaymentContract, item: dict[str, Any]
|
||||
"purchase_order_no": lambda value: str(value).strip() or None,
|
||||
"supplier_name": lambda value: str(value).strip() or None,
|
||||
"applicant_name": lambda value: str(value).strip() or None,
|
||||
"total_amount": lambda value: value,
|
||||
"total_amount": lambda value: positive_amount(value),
|
||||
"currency": lambda value: str(value).strip() or None,
|
||||
"effective_date": lambda value: _as_date(value),
|
||||
"delivery_due_date": lambda value: _as_date(value),
|
||||
@@ -608,6 +619,155 @@ def sync_vendor_prepayment_requests(*, client: ContractOaClient) -> tuple[int, i
|
||||
return created, skipped
|
||||
|
||||
|
||||
def _stored_asset_is_readable(asset: FileAsset | None) -> bool:
|
||||
"""
|
||||
判断合同附件指向的 FileAsset 是否还能读出字节。
|
||||
|
||||
核心逻辑:软删除、上传未完成,或仍为 temporary 且已过期,都视为不可读。
|
||||
这类行不能再被普通同步当成“已保存”跳过,否则下载和重解析会一直报文件资产不存在。
|
||||
"""
|
||||
if asset is None or asset.deleted_at is not None:
|
||||
return False
|
||||
if str(asset.upload_status or "") != "ready":
|
||||
return False
|
||||
if asset.expires_at and asset.expires_at < datetime.utcnow() and str(asset.lifecycle_status or "") == "temporary":
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _retain_contract_file_asset(asset: FileAsset | None) -> None:
|
||||
"""
|
||||
把合同原文标成已引用,避免临时文件清理任务删掉 MinIO 对象。
|
||||
|
||||
核心逻辑:派生资产默认 lifecycle=temporary、reference_count=0,到期会被 cleanup 软删并删对象。
|
||||
已经是 referenced 且没有过期时间时不再 +1,避免每次下载都抬高引用计数。
|
||||
"""
|
||||
if asset is None or asset.id is None or asset.deleted_at is not None:
|
||||
return
|
||||
if (
|
||||
str(asset.lifecycle_status or "") == "referenced"
|
||||
and asset.expires_at is None
|
||||
and int(asset.reference_count or 0) > 0
|
||||
):
|
||||
return
|
||||
mark_asset_referenced(asset)
|
||||
|
||||
|
||||
def _attachment_external_id(attachment: ContractPaymentAttachment) -> str:
|
||||
"""从附件元数据或 source_key 取出 OA/DMS 侧的附件 ID。"""
|
||||
meta = attachment.metadata_json if isinstance(attachment.metadata_json, dict) else {}
|
||||
explicit = str(meta.get("attachment_id") or "").strip()
|
||||
if explicit:
|
||||
return explicit
|
||||
prefix = f"{attachment.source}:"
|
||||
key = str(attachment.source_key or "")
|
||||
if key.startswith(prefix):
|
||||
return key[len(prefix):].strip()
|
||||
return ""
|
||||
|
||||
|
||||
def _restore_contract_attachment_bytes(
|
||||
contract: ContractPaymentContract,
|
||||
attachment: ContractPaymentAttachment,
|
||||
) -> bytes:
|
||||
"""
|
||||
从 OA 或 DMS 重新下载已被清理的合同原文,并写回新的已引用 FileAsset。
|
||||
|
||||
核心逻辑:按 source 与附件 ID 拉取字节,挂到原合同父资产下,再标记 referenced。
|
||||
下载或落库失败时抛出 ATTACHMENT_UNAVAILABLE,避免前端只看到笼统的“文件资产不存在”。
|
||||
|
||||
Args:
|
||||
contract: 附件所属合同。OA 恢复使用 oa_record_id。
|
||||
attachment: 已落库但 FileAsset 不可读的附件行。
|
||||
|
||||
Returns:
|
||||
恢复后的原文字节。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 无法从原系统重新下载。code=CONTRACT_PAYMENT.ATTACHMENT_UNAVAILABLE。
|
||||
"""
|
||||
source = str(attachment.source or "").strip()
|
||||
external_id = _attachment_external_id(attachment)
|
||||
owner_id = contract.owner_user_id or _default_owner_user_id()
|
||||
try:
|
||||
if source == "oa":
|
||||
process_id = str(contract.oa_record_id or "").strip()
|
||||
if not process_id or not external_id or not owner_id:
|
||||
raise RuntimeError("缺少 OA 流程、附件 ID 或文件所有者")
|
||||
data, mime_type, response_name = ContractOaClient().download_attachment_by_id(
|
||||
process_id=process_id,
|
||||
attachment_id=external_id,
|
||||
)
|
||||
parent = _ensure_oa_parent_asset(owner_id=owner_id, contract=contract)
|
||||
asset_role = "contract_oa_attachment"
|
||||
elif source == "dms":
|
||||
if not external_id or not owner_id or not ContractDmsClient.is_configured():
|
||||
raise RuntimeError("缺少 DMS 附件 ID、文件所有者,或 DMS 未配置")
|
||||
data, mime_type, response_name = ContractDmsClient.download_attachment(external_id)
|
||||
parent = _ensure_dms_parent_asset(owner_id=owner_id, contract=contract)
|
||||
asset_role = "contract_dms_attachment"
|
||||
else:
|
||||
raise RuntimeError(f"不支持的附件来源 {source}")
|
||||
filename = (response_name or attachment.file_name or "contract").strip()[:255] or "contract"
|
||||
asset, _created = create_derived_file_asset_from_bytes(
|
||||
user_id=owner_id,
|
||||
parent=parent,
|
||||
data=data,
|
||||
filename=filename,
|
||||
mime_type=mime_type or mimetypes.guess_type(filename)[0],
|
||||
source_attachment_key=attachment.source_key,
|
||||
asset_role=asset_role,
|
||||
)
|
||||
# [STEP 1] 新落下的合同原文立刻改为已引用,避免再次进入 72 小时临时清理。
|
||||
_retain_contract_file_asset(asset)
|
||||
attachment.file_name = filename
|
||||
if mime_type:
|
||||
attachment.mime_type = mime_type[:128]
|
||||
attachment.file_asset_id = asset.id
|
||||
attachment.status = "stored"
|
||||
db.session.flush()
|
||||
return read_asset_bytes(asset)
|
||||
except NotFoundError:
|
||||
raise
|
||||
except Exception:
|
||||
current_app.logger.exception(
|
||||
"合同付款预警:合同原文已清理且重新下载失败 contract_id=%s attachment_id=%s",
|
||||
contract.id,
|
||||
attachment.id,
|
||||
)
|
||||
raise NotFoundError(
|
||||
"合同原文已被清理,且无法从原系统重新下载",
|
||||
code="CONTRACT_PAYMENT.ATTACHMENT_UNAVAILABLE",
|
||||
)
|
||||
|
||||
|
||||
def read_contract_attachment_bytes(
|
||||
contract: ContractPaymentContract,
|
||||
attachment: ContractPaymentAttachment,
|
||||
) -> bytes:
|
||||
"""
|
||||
读取合同原文。临时资产还在时顺手改为已引用;已被清理时从 OA 或 DMS 重新下载。
|
||||
|
||||
核心逻辑:先读本地 FileAsset;deleted_at 或过期 temporary 视为丢失,再按附件来源恢复。
|
||||
详情下载、单合同重解析和批量重解析都走这里,避免三处各自判断清理状态。
|
||||
|
||||
Args:
|
||||
contract: 附件所属合同,重新下载 OA 时要用 oa_record_id。
|
||||
attachment: 已落库的合同附件行。
|
||||
|
||||
Returns:
|
||||
原文字节。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 资产不存在且无法从原系统恢复。
|
||||
"""
|
||||
asset = db.session.get(FileAsset, attachment.file_asset_id) if attachment.file_asset_id else None
|
||||
if _stored_asset_is_readable(asset):
|
||||
_retain_contract_file_asset(asset)
|
||||
return read_asset_bytes(asset)
|
||||
return _restore_contract_attachment_bytes(contract, attachment)
|
||||
|
||||
|
||||
def save_oa_attachments(
|
||||
contract: ContractPaymentContract,
|
||||
*,
|
||||
@@ -651,10 +811,15 @@ def save_oa_attachments(
|
||||
contract_id=contract.id, source="oa", source_key=source_key
|
||||
).first()
|
||||
if existing and existing.file_asset_id and existing.status == "stored":
|
||||
# 已保存的附件不得随普通 OA 增量同步重复解析:该同步可能与详情页单合同重解析
|
||||
# 并发,旧解析结果会覆盖人工刚确认的状态。规则升级时只能由显式批量重解析执行。
|
||||
contract.status = "active"
|
||||
return {"found": len(attachments), "saved": saved}
|
||||
stored_asset = db.session.get(FileAsset, existing.file_asset_id)
|
||||
if _stored_asset_is_readable(stored_asset):
|
||||
# 已保存且仍可读的附件不得随普通 OA 增量同步重复解析:该同步可能与详情页单合同重解析
|
||||
# 并发,旧解析结果会覆盖人工刚确认的状态。规则升级时只能由显式批量重解析执行。
|
||||
# 顺手把仍是 temporary 的历史附件标为已引用,避免清理任务之后删掉原文。
|
||||
_retain_contract_file_asset(stored_asset)
|
||||
contract.status = "active"
|
||||
return {"found": len(attachments), "saved": saved}
|
||||
# 资产已被临时文件清理删掉时不要跳过,继续按当前 OA 下载地址重新落库。
|
||||
try:
|
||||
current_app.logger.info("合同付款预警:开始下载 OA 附件 attachment_id=%s label=%s", attachment_id, attachment.get("label"))
|
||||
data, mime_type, response_name = client.download_attachment(attachment)
|
||||
@@ -669,6 +834,7 @@ def save_oa_attachments(
|
||||
source_attachment_key=source_key,
|
||||
asset_role="contract_oa_attachment",
|
||||
)
|
||||
_retain_contract_file_asset(asset)
|
||||
if existing is None:
|
||||
existing = ContractPaymentAttachment(
|
||||
contract_id=contract.id, source="oa", source_key=source_key, file_name=filename
|
||||
@@ -686,7 +852,6 @@ def save_oa_attachments(
|
||||
contract.status = "active"
|
||||
db.session.flush()
|
||||
try:
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
build_payment_plan_from_bytes(contract, filename=filename, data=read_asset_bytes(asset))
|
||||
except Exception:
|
||||
current_app.logger.exception("合同付款预警:OA 附件已保存但付款条款解析失败,合同编号=%s", contract.contract_no)
|
||||
@@ -737,8 +902,9 @@ def reparse_existing_contracts(*, limit: int = 1000) -> dict[str, int]:
|
||||
使用已归档附件批量刷新存量合同解析结果。
|
||||
|
||||
AI 触发时机:解析规则升级后,管理员需要清理数据库中遗留的旧待确认原因时调用。
|
||||
核心逻辑:不依赖 OA 增量通知,直接按“盖章完成合同上传”优先选择已保存附件并重跑解析;
|
||||
没有可用附件的合同跳过,解析失败的合同保留 needs_review。
|
||||
核心逻辑:不走 OA 增量通知列表,按“盖章完成合同上传”优先选择已保存附件并重跑解析。
|
||||
原文若已被临时文件清理删除,则按附件 ID 从 OA 或 DMS 重新下载后再解析,不改 OA 表单字段。
|
||||
没有可用附件的合同跳过;解析失败的合同保留 needs_review;仅重新下载失败时不改解析状态。
|
||||
Args:
|
||||
limit: 本次最多重解析合同数,防止单个 Job 长时间占用 Worker。
|
||||
Returns:
|
||||
@@ -746,7 +912,6 @@ def reparse_existing_contracts(*, limit: int = 1000) -> dict[str, int]:
|
||||
"""
|
||||
rows = db.session.query(ContractPaymentContract).order_by(ContractPaymentContract.id.asc()).limit(max(int(limit or 0), 0)).all()
|
||||
scanned = reparsed = failed = skipped = 0
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
for contract in rows:
|
||||
scanned += 1
|
||||
attachments = (
|
||||
@@ -759,13 +924,12 @@ def reparse_existing_contracts(*, limit: int = 1000) -> dict[str, int]:
|
||||
skipped += 1
|
||||
continue
|
||||
attachment = min(attachments, key=lambda row: (0 if str((row.metadata_json or {}).get("label") or "").strip() == "盖章完成合同上传" else 1, row.id))
|
||||
asset = db.session.get(FileAsset, attachment.file_asset_id)
|
||||
if not asset:
|
||||
skipped += 1
|
||||
continue
|
||||
try:
|
||||
build_payment_plan_from_bytes(contract, filename=attachment.file_name, data=read_asset_bytes(asset))
|
||||
data = read_contract_attachment_bytes(contract, attachment)
|
||||
build_payment_plan_from_bytes(contract, filename=attachment.file_name, data=data)
|
||||
reparsed += 1
|
||||
except NotFoundError:
|
||||
failed += 1
|
||||
except Exception:
|
||||
failed += 1
|
||||
contract.parse_status = "needs_review"
|
||||
@@ -814,8 +978,11 @@ def supplement_from_dms(contract: ContractPaymentContract) -> dict[str, int]:
|
||||
source_key = f"dms:{attachment_id}"
|
||||
existing = db.session.query(ContractPaymentAttachment).filter_by(contract_id=contract.id, source="dms", source_key=source_key).first()
|
||||
if existing and existing.file_asset_id:
|
||||
contract.status = "active"
|
||||
return {"found": 1, "saved": 0}
|
||||
stored_asset = db.session.get(FileAsset, existing.file_asset_id)
|
||||
if _stored_asset_is_readable(stored_asset):
|
||||
_retain_contract_file_asset(stored_asset)
|
||||
contract.status = "active"
|
||||
return {"found": 1, "saved": 0}
|
||||
try:
|
||||
data, mime_type, response_name = ContractDmsClient.download_attachment(attachment_id)
|
||||
filename = response_name or str(row.get("LeafName") or "contract").strip() or "contract"
|
||||
@@ -838,6 +1005,7 @@ def supplement_from_dms(contract: ContractPaymentContract) -> dict[str, int]:
|
||||
source_attachment_key=source_key,
|
||||
asset_role="contract_dms_attachment",
|
||||
)
|
||||
_retain_contract_file_asset(asset)
|
||||
if existing is None:
|
||||
existing = ContractPaymentAttachment(contract_id=contract.id, source="dms", source_key=source_key, file_name=filename[:255])
|
||||
db.session.add(existing)
|
||||
@@ -852,7 +1020,6 @@ def supplement_from_dms(contract: ContractPaymentContract) -> dict[str, int]:
|
||||
db.session.flush()
|
||||
# 解析服务读取私有 FileAsset;失败时保留已保存附件并进入待复核。
|
||||
try:
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
build_payment_plan_from_bytes(contract, filename=filename, data=read_asset_bytes(asset))
|
||||
except Exception:
|
||||
contract.parse_status = "needs_review"
|
||||
@@ -962,9 +1129,10 @@ def build_payment_plan(contract: ContractPaymentContract, *, text: str = "") ->
|
||||
|
||||
def _persist_payment_plan(contract: ContractPaymentContract, *, result: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
持久化条款与节点,并只用附件正文回填真实合同编号。
|
||||
持久化条款与节点,并用正文正数金额回填台账总额。
|
||||
|
||||
核心逻辑:保持节点编码稳定以支持重解析覆盖;仅解析成功时启用提醒,防止不完整条款触发正式通知。
|
||||
台账总额为 0 或空、且本次解析得到正数金额时,用该正数覆盖 0。已有正数总额不被正文改写。
|
||||
若验收归档事件已先入库,节点生成后立即回放归档日到验收款/质保款。
|
||||
Args:
|
||||
contract: 当前合同台账记录。
|
||||
@@ -992,9 +1160,10 @@ def _persist_payment_plan(contract: ContractPaymentContract, *, result: dict[str
|
||||
contract.parse_status = "needs_review"
|
||||
else:
|
||||
contract.contract_no = parsed_contract_no
|
||||
if not contract.total_amount and fields.get("total_amount"):
|
||||
from decimal import Decimal
|
||||
contract.total_amount = Decimal(str(fields["total_amount"]))
|
||||
# [STEP 2] OA 手填 0 不是有效总额。解析结果里的正数(正文优先,否则为 OA 正数)只填补 0 或空值。
|
||||
parsed_amount = positive_amount(fields.get("total_amount"))
|
||||
if parsed_amount is not None and positive_amount(contract.total_amount) is None:
|
||||
contract.total_amount = parsed_amount
|
||||
contract.parse_result_json = result
|
||||
contract.parse_status = str(result.get("status") or "needs_review")
|
||||
contract.warranty_period_days = fields.get("warranty_period_days") or contract.warranty_period_days
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/tests/test_contract_payment_parse.py
|
||||
|
||||
用途:验证合同付款预警解析器、三轮预警升级、ERP 金额匹配、周汇总摘要及企微 Excel 收件人列。
|
||||
依赖:contract_payment.parse_service、alert_service、erp_payment_service、supervisor_oa_service(三轮测试 mock)、openpyxl。
|
||||
逻辑:覆盖确定性解析边界、pending 计数与下一次周五 18:00;三轮升级 mock OA 矩阵,不调用外部 OA、文档库或企业微信;Excel 用例只断言「收件人」列为真实姓名。
|
||||
逻辑:覆盖确定性解析边界、pending 计数与下一次周五 18:00;三轮升级 mock OA 矩阵,不调用外部 OA、文档库或企业微信;Excel 用例只断言「收件人」列为真实姓名;失败原因用例只断言轨迹归类;OA 金额为 0 时断言正文正数回写台账;合同原文被清理后断言按附件 ID 重新下载。
|
||||
"""
|
||||
|
||||
from datetime import date, datetime
|
||||
@@ -15,6 +15,7 @@ from app.models import (
|
||||
ContractPaymentAttachment,
|
||||
ContractPaymentAlert,
|
||||
ContractPaymentNode,
|
||||
FileAsset,
|
||||
User,
|
||||
)
|
||||
from io import BytesIO
|
||||
@@ -24,7 +25,9 @@ from openpyxl import load_workbook
|
||||
from app.services.contract_payment.alert_service import (
|
||||
bind_contract_owner_from_applicant,
|
||||
build_weekly_alert_summary,
|
||||
describe_batch_failure,
|
||||
generate_alerts,
|
||||
render_batch_failure_message,
|
||||
_alert_status_label,
|
||||
_build_excel,
|
||||
_recipient_display_name,
|
||||
@@ -35,7 +38,12 @@ from app.services.contract_payment.dms_client import ContractDmsClient
|
||||
from app.services.contract_payment.oa_client import ContractOaClient
|
||||
from app.services.contract_payment.erp_payment_service import resolve_paid_node_ids
|
||||
from app.services.contract_payment.sync_service import _overwrite_oa_fields, _with_force_sync_audit
|
||||
from app.services.contract_payment.sync_service import _persist_payment_plan, save_oa_attachments
|
||||
from app.services.contract_payment.sync_service import (
|
||||
_persist_payment_plan,
|
||||
_retain_contract_file_asset,
|
||||
read_contract_attachment_bytes,
|
||||
save_oa_attachments,
|
||||
)
|
||||
|
||||
|
||||
def test_force_oa_sync_overwrites_only_non_empty_values_and_keeps_audit():
|
||||
@@ -68,6 +76,53 @@ def test_force_oa_sync_overwrites_only_non_empty_values_and_keeps_audit():
|
||||
}
|
||||
|
||||
|
||||
def test_force_oa_sync_does_not_replace_positive_amount_with_zero():
|
||||
"""OA 手填 0 不能在强制覆盖时清掉台账上已有的正数总额。"""
|
||||
contract = ContractPaymentContract(
|
||||
purchase_order_no="PO-KEEP",
|
||||
total_amount=Decimal("150.00"),
|
||||
)
|
||||
changed = _overwrite_oa_fields(contract, {"total_amount": "0.00"}, operator_id=7)
|
||||
# 0 与空值相同,不是一次有效的 OA 金额覆盖。
|
||||
assert changed == 0
|
||||
assert contract.total_amount == Decimal("150.00")
|
||||
|
||||
|
||||
def test_parse_uses_contract_text_when_oa_amount_is_zero():
|
||||
"""正文有正数金额时,不用 OA 的 0 去乘付款比例。"""
|
||||
result = parse_contract_text(
|
||||
"合同金额:150元;预付款30%;出货款30%;验收款35%;质保款5%;交货期限:2026年10月12日。",
|
||||
total_amount="0.00",
|
||||
)
|
||||
# 阶段金额按正文 150 计算,30% 为 45。
|
||||
assert result["status"] == "parsed"
|
||||
assert result["fields"]["total_amount"] == "150"
|
||||
prepayment = next(item for item in result["nodes"] if item["node_type"] == "prepayment")
|
||||
assert prepayment["amount"] == "45.00"
|
||||
|
||||
|
||||
def test_zero_oa_amount_is_replaced_when_plan_is_persisted(app):
|
||||
"""台账总额已是 0 时,解析落库应回写正文中的正数金额。"""
|
||||
with app.app_context():
|
||||
contract = ContractPaymentContract(
|
||||
contract_no="HT-ZERO-AMOUNT",
|
||||
purchase_order_no="PO-ZERO-AMOUNT",
|
||||
total_amount=Decimal("0.00"),
|
||||
)
|
||||
db.session.add(contract)
|
||||
db.session.flush()
|
||||
result = parse_contract_text(
|
||||
"合同编号:HT-ZERO-AMOUNT;合同金额:150元;预付款30%;出货款30%;验收款35%;质保款5%;交货期限:2026年10月12日。",
|
||||
total_amount=contract.total_amount,
|
||||
)
|
||||
_persist_payment_plan(contract, result=result)
|
||||
# 0 被正文 150 替换,节点金额与比例同时落库。
|
||||
assert contract.total_amount == Decimal("150")
|
||||
node = db.session.query(ContractPaymentNode).filter_by(contract_id=contract.id, node_code="prepayment").one()
|
||||
assert Decimal(str(node.amount)) == Decimal("45.00")
|
||||
assert Decimal(str(node.percentage)) == Decimal("30")
|
||||
|
||||
|
||||
def test_payment_plan_requires_purchase_order_for_automatic_alerts(app):
|
||||
"""关键断言:采购单号缺失时,解析结果不能进入自动付款预警台账。"""
|
||||
with app.app_context():
|
||||
@@ -89,12 +144,39 @@ def test_payment_plan_requires_purchase_order_for_automatic_alerts(app):
|
||||
assert contract.plan_status == "needs_review"
|
||||
|
||||
|
||||
def _contract_file_asset(user_id: int, *, asset_no: str, **overrides) -> FileAsset:
|
||||
"""构造测试用合同原文资产;调用方负责 add/flush。"""
|
||||
values = dict(
|
||||
asset_no=asset_no,
|
||||
owner_user_id=user_id,
|
||||
original_filename="盖章合同.pdf",
|
||||
storage_provider="minio",
|
||||
storage_bucket="test",
|
||||
storage_key=f"contract-oa/{asset_no}",
|
||||
content_hash=asset_no.ljust(64, "0")[:64],
|
||||
file_size=4,
|
||||
mime_type="application/pdf",
|
||||
upload_status="ready",
|
||||
lifecycle_status="referenced",
|
||||
reference_count=1,
|
||||
expires_at=None,
|
||||
deleted_at=None,
|
||||
)
|
||||
values.update(overrides)
|
||||
return FileAsset(**values)
|
||||
|
||||
|
||||
def test_normal_oa_sync_does_not_overwrite_a_single_contract_reparse(app, monkeypatch):
|
||||
"""关键断言:已归档附件在普通 OA 同步中不再重解析,避免覆盖单合同重解析结果。"""
|
||||
"""关键断言:仍可读的已归档附件在普通 OA 同步中不再重解析,避免覆盖单合同重解析结果。"""
|
||||
with app.app_context():
|
||||
owner = User(username="cp-live-asset", email="cp-live-asset@example.com", status="active")
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
asset = _contract_file_asset(owner.id, asset_no="FA-CP-LIVE")
|
||||
db.session.add(asset)
|
||||
contract = ContractPaymentContract(
|
||||
contract_no="HT-SINGLE-REPARSE",
|
||||
owner_user_id=1,
|
||||
owner_user_id=owner.id,
|
||||
parse_status="parsed",
|
||||
plan_status="active",
|
||||
)
|
||||
@@ -105,25 +187,135 @@ def test_normal_oa_sync_does_not_overwrite_a_single_contract_reparse(app, monkey
|
||||
source="oa",
|
||||
source_key="oa:sealed-1",
|
||||
file_name="盖章合同.pdf",
|
||||
file_asset_id=1,
|
||||
file_asset_id=asset.id,
|
||||
status="stored",
|
||||
))
|
||||
db.session.flush()
|
||||
monkeypatch.setattr(
|
||||
'app.services.contract_payment.sync_service.build_payment_plan_from_bytes',
|
||||
"app.services.contract_payment.sync_service.build_payment_plan_from_bytes",
|
||||
lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("普通 OA 同步不应重新解析已归档附件")),
|
||||
)
|
||||
|
||||
class Client:
|
||||
def download_attachment(self, _attachment):
|
||||
raise AssertionError("仍可读的附件不应重新下载")
|
||||
|
||||
result = save_oa_attachments(
|
||||
contract,
|
||||
item={"attachments": [{"attachment_id": "sealed-1", "file_name": "盖章合同.pdf", "priority": 0}]},
|
||||
client=object(),
|
||||
client=Client(),
|
||||
)
|
||||
|
||||
assert result == {"found": 1, "saved": 0}
|
||||
assert contract.parse_status == "parsed"
|
||||
|
||||
|
||||
def test_retain_marks_temporary_contract_asset_referenced(app):
|
||||
"""关键断言:仍存活的临时合同原文会被标为已引用,且重复调用不继续加引用计数。"""
|
||||
with app.app_context():
|
||||
owner = User(username="cp-retain-asset", email="cp-retain-asset@example.com", status="active")
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
asset = _contract_file_asset(
|
||||
owner.id,
|
||||
asset_no="FA-CP-TEMP",
|
||||
lifecycle_status="temporary",
|
||||
reference_count=0,
|
||||
expires_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
|
||||
_retain_contract_file_asset(asset)
|
||||
db.session.refresh(asset)
|
||||
assert asset.lifecycle_status == "referenced"
|
||||
assert asset.expires_at is None
|
||||
assert asset.reference_count == 1
|
||||
|
||||
_retain_contract_file_asset(asset)
|
||||
db.session.refresh(asset)
|
||||
assert asset.reference_count == 1
|
||||
|
||||
|
||||
def test_deleted_contract_attachment_is_redownloaded(app, monkeypatch):
|
||||
"""关键断言:软删除的合同原文按 OA 流程和附件 ID 重新下载,并写回已引用资产。"""
|
||||
with app.app_context():
|
||||
owner = User(username="cp-deleted-asset", email="cp-deleted-asset@example.com", status="active")
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
dead = _contract_file_asset(
|
||||
owner.id,
|
||||
asset_no="FA-CP-DEAD",
|
||||
upload_status="deleted",
|
||||
lifecycle_status="expired",
|
||||
deleted_at=datetime.utcnow(),
|
||||
)
|
||||
parent = _contract_file_asset(owner.id, asset_no="FA-CP-PARENT", asset_role="contract_oa_root")
|
||||
db.session.add_all([dead, parent])
|
||||
contract = ContractPaymentContract(
|
||||
contract_no="HT-REDOWNLOAD",
|
||||
oa_record_id="5203",
|
||||
owner_user_id=owner.id,
|
||||
)
|
||||
db.session.add(contract)
|
||||
db.session.flush()
|
||||
attachment = ContractPaymentAttachment(
|
||||
contract_id=contract.id,
|
||||
source="oa",
|
||||
source_key="oa:att-9",
|
||||
file_name="盖章合同.pdf",
|
||||
file_asset_id=dead.id,
|
||||
status="stored",
|
||||
metadata_json={"attachment_id": "att-9"},
|
||||
)
|
||||
db.session.add(attachment)
|
||||
db.session.flush()
|
||||
calls: dict[str, tuple[str, str]] = {}
|
||||
|
||||
def fake_download(self, *, process_id, attachment_id):
|
||||
calls["ids"] = (process_id, attachment_id)
|
||||
return b"pdf-bytes", "application/pdf", "restored.pdf"
|
||||
|
||||
def fake_create(**kwargs):
|
||||
live = _contract_file_asset(
|
||||
owner.id,
|
||||
asset_no="FA-CP-RESTORED",
|
||||
lifecycle_status="temporary",
|
||||
reference_count=0,
|
||||
expires_at=datetime.utcnow(),
|
||||
parent_asset_id=parent.id,
|
||||
)
|
||||
db.session.add(live)
|
||||
db.session.flush()
|
||||
return live, True
|
||||
|
||||
monkeypatch.setattr(ContractOaClient, "download_attachment_by_id", fake_download)
|
||||
monkeypatch.setattr(
|
||||
"app.services.contract_payment.sync_service._ensure_oa_parent_asset",
|
||||
lambda **_kwargs: parent,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.contract_payment.sync_service.create_derived_file_asset_from_bytes",
|
||||
fake_create,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.contract_payment.sync_service.read_asset_bytes",
|
||||
lambda _asset: b"pdf-bytes",
|
||||
)
|
||||
|
||||
data = read_contract_attachment_bytes(contract, attachment)
|
||||
db.session.refresh(attachment)
|
||||
restored = db.session.get(FileAsset, attachment.file_asset_id)
|
||||
# 断言留在同一会话内,避免上下文结束后 ORM 实例过期。
|
||||
assert data == b"pdf-bytes"
|
||||
assert calls["ids"] == ("5203", "att-9")
|
||||
assert attachment.file_name == "restored.pdf"
|
||||
assert restored is not None
|
||||
assert restored.asset_no == "FA-CP-RESTORED"
|
||||
assert restored.lifecycle_status == "referenced"
|
||||
assert restored.deleted_at is None
|
||||
|
||||
|
||||
def test_parse_standard_payment_plan():
|
||||
"""关键断言:预付款纳入节点,出货款到期锚点为交货期限,金额按比例计算。"""
|
||||
result = parse_contract_text(
|
||||
@@ -621,6 +813,37 @@ def test_recipient_display_name_falls_back_to_username(app):
|
||||
assert _recipient_display_name(None) == "—"
|
||||
|
||||
|
||||
def test_describe_batch_failure_collapses_unbound_recipient():
|
||||
"""收件人未绑定企微时,卡片和附件的同一原因只保留一条。"""
|
||||
reasons = describe_batch_failure({
|
||||
"textcard": {"ok": False, "reason": "user_unbound"},
|
||||
"file": {"errcode": -1, "errmsg": "user_unbound"},
|
||||
})
|
||||
# 未绑定账号是配置问题,不把附件失败再报一遍。
|
||||
assert reasons == [{"code": "user_unbound", "detail": ""}]
|
||||
assert render_batch_failure_message(reasons) == "收件人未绑定企业微信账号"
|
||||
|
||||
|
||||
def test_describe_batch_failure_keeps_card_and_file_errors():
|
||||
"""卡片与附件分别失败时,两条原因和企微 errmsg 都要保留。"""
|
||||
reasons = describe_batch_failure({
|
||||
"textcard": {"ok": False, "reason": "send_failed", "raw": {"errcode": 81013, "errmsg": "user ticket invalid"}},
|
||||
"file_error": "upload timeout",
|
||||
})
|
||||
# 卡片失败看 errmsg,附件上传异常单独成条,不混成一条未知错误。
|
||||
assert reasons == [
|
||||
{"code": "textcard_failed", "detail": "user ticket invalid"},
|
||||
{"code": "file_upload_failed", "detail": "upload timeout"},
|
||||
]
|
||||
|
||||
|
||||
def test_describe_batch_failure_falls_back_to_stored_message():
|
||||
"""没有发送轨迹时,回退展示已保存的错误文本。"""
|
||||
reasons = describe_batch_failure(None, fallback="gateway timeout")
|
||||
# 历史批次可能只有 error_message,页面仍要能点开原因。
|
||||
assert reasons == [{"code": "unknown", "detail": "gateway timeout"}]
|
||||
|
||||
|
||||
def test_alert_status_label_uses_chinese():
|
||||
"""关键断言:Excel 状态列把 pending/sent/failed 写成中文,未知码保留原文。"""
|
||||
assert _alert_status_label("pending") == "待发送"
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@
|
||||
- 覆盖预付款、出货款、验收款、质保款四阶段:预付款为合同申请单归档后第 7/14/21 天;出货款为交货期限前 7 天、当天、后 14 天;验收款为验收归档后第 30/40/60 天;质保款为质保到期前 7 天、当天、后 14 天。
|
||||
- 三轮收件人依次为采购负责人、采购部负责人、采购分管领导。预付款及出货款以 ERP `apa_file` 付款事实判定;匹配付款后仅关闭尚未发送的轮次,保留已发送审计。
|
||||
- 每日定时扫描仅生成待发送预警;每周五 18:00 按收件人归并发送一条企业微信汇总。消息仅展示总笔数及阶段数量;每位收件人附件一份 Excel,列明需付款合同及付款明细。
|
||||
- 工作台入口已迁入 Chat:合同付款预警作为 builtin Agent(`agent_code=contract_payment`),主区以 Tab 嵌入合同台账、待确认合同、周汇总批次;点击合同在当前 Tab 内下钻详情。第一期隐藏对话输入框与历史会话,不接 Dify。旧地址 `/workspace/contract-payment*` 重定向到对应 Chat 深链。平台 admin 或被授予该 Agent 的用户可访问;同步 OA、强制覆盖、批量重解析、扫描预警和发送预警仅管理员可见。点击合同可查看详情、解析原因和原文附件。合同台账四张汇总卡为即将到期(7 日内)、逾期未付、进行中、本月应付。关键词可搜申请人。
|
||||
- 工作台入口已迁入 Chat:合同付款预警作为 builtin Agent(`agent_code=contract_payment`),主区以 Tab 嵌入合同台账、待确认合同、周汇总批次(发送失败可点击图标查看原因);点击合同在当前 Tab 内下钻详情。第一期隐藏对话输入框与历史会话,不接 Dify。旧地址 `/workspace/contract-payment*` 重定向到对应 Chat 深链。平台 admin 或被授予该 Agent 的用户可访问;同步 OA、强制覆盖、批量重解析、扫描预警和发送预警仅管理员可见。点击合同可查看详情、解析原因和原文附件。合同台账四张汇总卡为即将到期(7 日内)、逾期未付、未到期(7 日外)、本月应付。关键词可搜申请人。
|
||||
- OA 合同申请单同时存在“合同附件”和“盖章完成合同上传”时,必须优先下载并解析后者;普通合同附件仅在盖章完成合同缺失或下载失败时作为备用。
|
||||
- OA 下载的扫描版 PDF 先通过 MinerU 转为保留标题、表格和阅读顺序的 Markdown,再运行合同付款条款规则;MinerU 失败或无结果时回退原 PDF 文字层/OCR,仍无法确认的合同保留在“待确认合同”。
|
||||
|
||||
|
||||
@@ -138,7 +138,8 @@ OA“厂商预付款请款作业”的流程状态不作为付款完成依据;
|
||||
- 重复同步不得产生重复合同或重复 OA 事件;ERP 查询应按采购单号去重汇总。
|
||||
- 外部 OA 不可用、字段变化或解析失败时,应保留已有数据,记录失败原因并允许下次重试。
|
||||
- 普通 OA 同步不得覆盖已有本地 OA 字段。管理员可显式发起“强制覆盖 OA 字段”:仅以本次 OA 明确返回的非空值覆盖,并记录操作人、时间及字段变更前后值;之后仍按既有流程下载附件和解析付款计划。
|
||||
- 解析规则升级后,管理员可发起“批量重新解析存量合同”。任务直接使用已归档的合同附件刷新历史解析结果、付款节点和待确认原因,不访问 OA,也不覆盖 OA 字段;没有可用附件的合同保留原状态并计入跳过。
|
||||
- OA「合同金额」为 0 或空视为未录入。合同正文抽出大于 0 的金额时,阶段金额用该正数,并把台账总额从 0 或空回写成正文金额;正文没有正数且 OA 大于 0 时继续用 OA。普通同步和强制覆盖都不得把已有正数总额改成 0。两边都没有有效金额时进入待确认,不猜测。
|
||||
- 解析规则升级后,管理员可发起“批量重新解析存量合同”。任务优先使用已归档的合同附件刷新历史解析结果、付款节点和待确认原因,不覆盖 OA 字段。合同原文按已引用文件长期保存;若历史临时文件已被清理删除,则按附件 ID 从 OA 或 DMS 重新下载后再解析。没有可用附件的合同计入跳过;重新下载失败的合同保留原解析状态并计入失败。
|
||||
|
||||
### FR-03 每日扫描与周汇总发送
|
||||
|
||||
@@ -165,8 +166,9 @@ OA“厂商预付款请款作业”的流程状态不作为付款完成依据;
|
||||
- 工作台应展示各付款阶段的规则说明、合同付款节点、日期依据和当前状态。
|
||||
- 合同详情应展示每条预警的付款阶段、轮次、计划日期、实际汇总发送时间、收件人、汇总批次和发送状态。
|
||||
- 工作台应展示下一次汇总发送时间(每周五 18:00)及本周待发送笔数。
|
||||
- 周汇总批次发送失败时,发送状态旁提供图标;点击后展示该批次的失败原因(如收件人未绑定企业微信、卡片或附件发送失败及企微返回说明)。
|
||||
- 合同台账与待确认列表应支持按合同编号、流程编号、采购单号、供应商名称或申请人模糊检索。
|
||||
- 合同台账应展示四张汇总卡(即将到期 7 日内、逾期未付、进行中、本月应付),均按合同计数、统计全部已解析台账;点击卡片过滤下方列表,再次点击取消过滤。即将到期、逾期未付、进行中互斥;本月应付可与这三项重叠。行级「待补充」仍可出现在状态列,但不作为汇总卡。
|
||||
- 合同台账应展示四张汇总卡(即将到期 7 日内、逾期未付、未到期 7 日外、本月应付),均按合同计数、统计全部已解析台账;点击卡片过滤下方列表,再次点击取消过滤。即将到期、逾期未付、未到期互斥;本月应付可与这三项重叠。行级「待补充」仍可出现在状态列,但不作为汇总卡。
|
||||
- 同步 OA、强制覆盖 OA 字段、批量重解析存量合同、扫描生成预警和发送预警仅管理员可见;普通授权用户只可查询台账、详情和周汇总批次。
|
||||
- 管理员可手动触发 OA 同步和预警扫描;执行应后台异步化,不阻塞页面请求。
|
||||
|
||||
@@ -231,6 +233,9 @@ OA“厂商预付款请款作业”的流程状态不作为付款完成依据;
|
||||
|
||||
| 日期 | 版本 | 变更内容 |
|
||||
| --- | --- | --- |
|
||||
| 2026-09-23 | V1.15 | 合同原文落库后标为已引用;已被临时清理删除的附件,下载和重解析会按附件 ID 从 OA 或 DMS 重新下载。 |
|
||||
| 2026-09-23 | V1.14 | OA 合同金额为 0 或空时视为未录入;正文正数金额回写台账总额,且不能被强制覆盖成 0。 |
|
||||
| 2026-09-22 | V1.13 | 周汇总批次发送失败时,可点击状态旁图标查看失败原因。 |
|
||||
| 2026-09-16 | V1.12 | 合同台账与待确认列表的 keyword 增加申请人模糊匹配。 |
|
||||
| 2026-09-10 | V1.10 | 企微周汇总 Excel「收件岗位」列改为「收件人」,单元格写系统用户真实姓名(为空回退用户名);「状态」列改写中文(待发送/已发送/发送失败/已关闭),不再输出 pending 等英文码;三轮升级规则表仍按岗位定义。 |
|
||||
| 2026-09-10 | V1.9 | 合同台账增加四张汇总卡:即将到期(7日内)、逾期未付、待补充、本月应付;均按合同计数、统计全量台账,点击过滤列表。 |
|
||||
|
||||
@@ -0,0 +1,672 @@
|
||||
<!doctype html>
|
||||
<!--
|
||||
docs/features/training/annual-training-plan-prototype.html
|
||||
用途:年度计划、月度计划与培训看板的可点击原型。月度计划可由讲师新建,也可从年度计划行转入。
|
||||
依赖:浏览器原生 HTML/CSS/JavaScript,无需构建。图表用内联 SVG,不引入第三方库。
|
||||
逻辑:角色切换区分 HR、财务部负责人、仓储课讲师;看板统计计划次数、已排场次、分类和讲师时长。
|
||||
-->
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>年度教育训练计划 · 原型</title>
|
||||
<style>
|
||||
:root { --ink:#142033; --muted:#64748b; --line:#dce4ef; --bg:#f4f7fb; --nav:#111c31; --brand:#2563eb; --soft:#eaf2ff; --green:#067647; --amber:#b54708; --red:#b42318; }
|
||||
* { box-sizing:border-box; } body { margin:0; background:var(--bg); color:var(--ink); font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei",sans-serif; } button,select,input,textarea { font:inherit; } button { cursor:pointer; }
|
||||
.top { display:flex; justify-content:space-between; gap:16px; align-items:center; padding:12px 24px; background:var(--nav); color:#fff; } .top small { color:#aac0db; margin-left:8px; } .tabs { display:flex; gap:5px; } .tabs button { border:0; border-radius:7px; padding:7px 11px; color:#c5d3e6; background:transparent; font-weight:700; font-size:12px; } .tabs button.active { color:#fff; background:var(--brand); } .tabs button .later { margin-left:6px; padding:1px 6px; border-radius:99px; color:#7c2d12; background:#ffedd5; font-size:10px; }
|
||||
.role { display:flex; align-items:center; gap:8px; color:#c5d3e6; font-size:12px; } .role select { padding:6px 8px; border:0; border-radius:8px; font-weight:700; }
|
||||
main { width:min(1280px,calc(100% - 32px)); margin:auto; padding:22px 0 48px; } .view { display:none; } .view.active { display:block; }
|
||||
.banner { margin-bottom:14px; padding:10px 12px; border:1px solid #f3d7b0; border-radius:10px; color:#7c2d12; background:#fff7ed; font-size:12px; }
|
||||
.hero { display:flex; justify-content:space-between; gap:16px; align-items:flex-start; margin-bottom:14px; } .hero h1 { margin:0; font-size:24px; } .hero p { margin:5px 0 0; color:var(--muted); }
|
||||
.btn { border:1px solid var(--line); border-radius:8px; padding:8px 11px; background:#fff; font-size:12px; font-weight:700; } .btn.primary { border-color:var(--brand); color:#fff; background:var(--brand); } .btn:disabled { opacity:.45; cursor:not-allowed; }
|
||||
.grid { display:grid; gap:12px; } .four { grid-template-columns:repeat(4,1fr); margin-bottom:14px; } .three { grid-template-columns:repeat(3,1fr); } .charts { margin-bottom:12px; } .card { border:1px solid var(--line); border-radius:13px; background:#fff; overflow:hidden; }
|
||||
.chart-hd { padding:14px 14px 0; } .chart-hd h2 { margin:0; font-size:14px; } .chart-hd p { margin:4px 0 0; color:var(--muted); font-size:12px; } .chart-bd { padding:6px 8px 12px; } .legend { display:flex; gap:14px; padding:0 14px 4px; color:var(--muted); font-size:11px; } .swatch { display:inline-block; width:8px; height:8px; margin-right:4px; border-radius:2px; }
|
||||
.metric { padding:14px 16px; } .metric b { display:block; font-size:26px; } .metric span { color:var(--muted); font-size:12px; }
|
||||
.filters { display:flex; flex-wrap:wrap; align-items:end; gap:10px; padding:12px 14px; margin-bottom:12px; } .filters label,.field label { display:grid; gap:4px; color:var(--muted); font-size:11px; font-weight:700; } .filters select,.field input,.field select,.field textarea { padding:8px; border:1px solid #b8c8dd; border-radius:8px; color:var(--ink); background:#fff; } .filters select { min-width:120px; }
|
||||
.workbook { overflow:auto; } table { width:100%; border-collapse:collapse; font-size:12px; } th,td { padding:10px 8px; border-bottom:1px solid var(--line); text-align:left; vertical-align:top; } th { color:var(--muted); background:#f9fbfe; white-space:nowrap; } tr:hover td { background:#f8fbff; }
|
||||
.badge { display:inline-flex; padding:2px 8px; border-radius:99px; font-size:11px; font-weight:800; } .green { color:var(--green); background:#eafaf1; } .amber { color:var(--amber); background:#fff7e6; } .red { color:var(--red); background:#fff0ef; } .blue { color:#175cd3; background:var(--soft); } .gray { color:#475569; background:#edf1f6; }
|
||||
.link { border:0; padding:0; color:#175cd3; background:transparent; font-size:12px; font-weight:800; } .names { color:#334155; } .note { color:var(--muted); } .ops { display:flex; gap:10px; white-space:nowrap; } .chips { display:flex; flex-wrap:wrap; gap:6px; margin-top:6px; } .chip { padding:4px 8px; border-radius:99px; background:#f1f5f9; font-size:12px; }
|
||||
.mask { position:fixed; inset:0; display:none; background:rgba(15,23,42,.35); } .mask.show { display:block; }
|
||||
.drawer { position:fixed; top:0; right:0; width:min(460px,100%); height:100%; display:flex; flex-direction:column; background:#fff; box-shadow:-12px 0 40px rgba(15,23,42,.12); transform:translateX(100%); transition:.2s; } .mask.show .drawer { transform:none; }
|
||||
.drawer header,.drawer footer { padding:16px 18px; border-bottom:1px solid var(--line); } .drawer footer { border-bottom:0; border-top:1px solid var(--line); display:flex; justify-content:flex-end; gap:8px; } .drawer h2 { margin:0; font-size:16px; } .drawer .body { padding:16px 18px 24px; overflow:auto; } .field { margin-bottom:12px; } .field textarea { min-height:64px; resize:vertical; } .readonly { padding:8px; border-radius:8px; color:#334155; background:#f8fafc; }
|
||||
.people { max-height:220px; overflow:auto; border:1px solid var(--line); border-radius:8px; } .person { display:flex; gap:8px; align-items:center; padding:8px 10px; border-bottom:1px solid var(--line); } .person:last-child { border-bottom:0; } .person small { color:var(--muted); }
|
||||
.hint { margin:0 0 8px; color:var(--muted); font-size:12px; }
|
||||
.two { display:grid; grid-template-columns:1fr 360px; gap:14px; } .phone { width:100%; padding:16px; border-radius:24px; color:#fff; background:#172033; } .phone small { display:block; color:#aab9cc; text-align:center; } .notice { margin-top:12px; overflow:hidden; border-radius:12px; color:var(--ink); background:#fff; } .notice h3 { margin:0; padding:14px 14px 6px; font-size:15px; } .notice p { margin:0; padding:0 14px 14px; white-space:pre-line; color:#3d4b61; font-size:13px; } .notice button { width:100%; padding:11px; border:0; border-top:1px solid var(--line); color:var(--brand); background:#fff; font-weight:800; }
|
||||
.kv { display:grid; grid-template-columns:88px 1fr; gap:8px; padding:8px 0; border-bottom:1px solid var(--line); font-size:13px; } .kv b { color:var(--muted); font-weight:700; }
|
||||
.toast { position:fixed; right:18px; bottom:18px; z-index:5; padding:10px 12px; border-radius:9px; color:#fff; background:#142036; opacity:0; transition:.2s; } .toast.show { opacity:1; }
|
||||
.charts { display:grid; gap:12px; margin-bottom:12px; } .charts.two { grid-template-columns:1fr 1fr; } .charts.three { grid-template-columns:1fr 1fr 1fr; }
|
||||
.chart-hd { display:flex; justify-content:space-between; gap:8px; align-items:flex-start; padding:12px 14px 0; } .chart-hd h2 { margin:0; font-size:14px; } .chart-hd p { margin:3px 0 0; color:var(--muted); font-size:12px; }
|
||||
.chart-bd { padding:4px 8px 10px; } .chart-bd svg { display:block; width:100%; height:auto; }
|
||||
.legend { display:flex; gap:10px; color:var(--muted); font-size:11px; font-weight:700; } .legend i { display:inline-block; width:8px; height:8px; margin-right:4px; border-radius:2px; }
|
||||
@media (max-width:900px) { .top,.hero { align-items:flex-start; flex-direction:column; } .four,.three,.two,.charts.two,.charts.three { grid-template-columns:1fr; } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="top">
|
||||
<div><b>教育训练计划</b><small>原型 · 年度收集与月度排课</small></div>
|
||||
<nav class="tabs" id="tabs">
|
||||
<button class="active" data-v="board">培训看板</button>
|
||||
<button data-v="annual">年度计划</button>
|
||||
<button data-v="courses" id="tabCourses">课程管理</button>
|
||||
<button data-v="notice">收集提醒</button>
|
||||
<button data-v="monthly">月度计划</button>
|
||||
</nav>
|
||||
<label class="role">查看身份
|
||||
<select id="role">
|
||||
<option value="hr">HR · 全部主办单位</option>
|
||||
<option value="dept">部门负责人 · 财务部</option>
|
||||
<option value="teacher">讲师 · 仓储课</option>
|
||||
</select>
|
||||
</label>
|
||||
</header>
|
||||
<main>
|
||||
<section class="view active" id="v-board">
|
||||
<div class="hero">
|
||||
<div>
|
||||
<h1>培训看板</h1>
|
||||
<p>按年度计划和已排月度场次统计。已取消场次不计入。出勤率等签到上线后再加。</p>
|
||||
</div>
|
||||
</div>
|
||||
<article class="card filters">
|
||||
<label>年度<select id="boardYear"><option>2026</option><option>2027</option></select></label>
|
||||
<label>月份<select id="boardMonth"><option value="">全年</option><option value="01">1月</option><option value="02">2月</option><option value="03">3月</option><option value="04">4月</option><option value="05">5月</option><option value="06">6月</option><option value="07">7月</option><option value="08">8月</option><option value="09">9月</option><option value="10">10月</option><option value="11">11月</option><option value="12">12月</option></select></label>
|
||||
<label>厂区<select id="boardPlant"><option value="">全部</option><option>1厂</option><option>2厂</option></select></label>
|
||||
<label>主办单位<select id="boardUnit"></select></label>
|
||||
</article>
|
||||
<div class="grid four" id="boardKpis"></div>
|
||||
<div class="charts two">
|
||||
<article class="card"><div class="chart-hd"><div><h2>各月开课场次</h2><p>折线始终按全年,方便看淡旺季</p></div></div><div class="chart-bd" id="chartSessions"></div></article>
|
||||
<article class="card"><div class="chart-hd"><div><h2>各月培训时长</h2><p>单位:小时</p></div></div><div class="chart-bd" id="chartHours"></div></article>
|
||||
</div>
|
||||
<div class="charts three">
|
||||
<article class="card"><div class="chart-hd"><div><h2>主办单位排课</h2><p>计划次数为全年,已排跟随月份</p></div><div class="legend"><span><i style="background:#2563eb"></i>计划次数</span><span><i style="background:#0f9f6e"></i>已排</span></div></div><div class="chart-bd" id="chartUnits"></div></article>
|
||||
<article class="card"><div class="chart-hd"><div><h2>一级分类场次</h2><p>按已排月度场次</p></div></div><div class="chart-bd" id="chartCats"></div></article>
|
||||
<article class="card"><div class="chart-hd"><div><h2>讲师授课时长</h2><p>单位:小时</p></div></div><div class="chart-bd" id="chartTeachers"></div></article>
|
||||
</div>
|
||||
</section>
|
||||
<section class="view" id="v-annual">
|
||||
<div class="hero">
|
||||
<div>
|
||||
<h1>2026 年度教育训练计划</h1>
|
||||
<p id="annualDesc">按主办单位收集。计划行从课程库选课,参加人员点名,不含培训费用。</p>
|
||||
</div>
|
||||
<div>
|
||||
<button class="btn" id="exportBtn">导出年度表</button>
|
||||
<button class="btn primary" id="addLine">新增计划行</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="grid four" id="progress"></div>
|
||||
<article class="card filters">
|
||||
<label>年度<select id="year"><option>2026</option><option>2027</option></select></label>
|
||||
<label>厂区<select id="plant"><option value="">全部</option><option>1厂</option><option>2厂</option></select></label>
|
||||
<label>主办单位<select id="unit"></select></label>
|
||||
<button class="btn" id="resetFilter">重置</button>
|
||||
</article>
|
||||
<article class="card"><div class="workbook"><table>
|
||||
<thead><tr><th>编号</th><th>厂区</th><th>主办单位</th><th>课程名称</th><th>一级分类</th><th>二级分类</th><th>次数</th><th>已排</th><th>参加人员</th><th>地点</th><th>分类</th><th>内/外</th><th></th></tr></thead>
|
||||
<tbody id="planRows"></tbody>
|
||||
</table></div></article>
|
||||
</section>
|
||||
|
||||
<section class="view" id="v-courses">
|
||||
<div class="hero">
|
||||
<div><h1>课程管理</h1><p>课程可被多个年度、多个主办单位重复选用。停用后不能进入新计划,已引用的计划仍保留。</p></div>
|
||||
<button class="btn primary" id="addCourse">新增课程</button>
|
||||
</div>
|
||||
<article class="card"><div class="workbook"><table>
|
||||
<thead><tr><th>课程名称</th><th>一级分类</th><th>二级分类</th><th>分类</th><th>状态</th><th>被计划引用</th><th></th></tr></thead>
|
||||
<tbody id="courseRows"></tbody>
|
||||
</table></div></article>
|
||||
</section>
|
||||
|
||||
<section class="view" id="v-notice">
|
||||
<div class="hero"><div><h1>年底收集提醒</h1><p>每年 12 月 1 日 09:00 通知部门负责人提交下一年度计划,截止 12 月 31 日。</p></div></div>
|
||||
<div class="two">
|
||||
<div class="phone"><small>企业微信 · 应用消息</small><div class="notice"><h3>请提交 2027 年度教育训练计划</h3><p>主办单位:财务部
|
||||
接收人:财务部负责人
|
||||
截止:2026-12-31
|
||||
请从课程库选择课程,并点名参加人员。培训费用不在本次收集范围。
|
||||
逾期仍可补交,将标记为逾期提交。</p><button id="goFill">去填写年度计划</button></div></div>
|
||||
<article class="card"><div class="hd" style="padding:14px 16px 0"><h2 style="margin:0;font-size:14px">发送规则</h2></div><div style="padding:8px 16px 16px">
|
||||
<div class="kv"><b>对象</b><span>各主办单位的部门负责人</span></div>
|
||||
<div class="kv"><b>之后</b><span>部门提交年度计划后,讲师在「月度计划」里排课。开课提醒和出勤不在本原型。</span></div>
|
||||
<div class="kv"><b>进度</b><span>HR 在年度计划页看到未提交 / 已提交 / 逾期提交</span></div>
|
||||
</div></article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="view" id="v-monthly">
|
||||
<div class="hero">
|
||||
<div>
|
||||
<h1>月度计划</h1>
|
||||
<p id="monthlyDesc">讲师创建。从年度计划转入时带出课程、地点和已选人员;直接新建的记为计划外。</p>
|
||||
</div>
|
||||
<div>
|
||||
<button class="btn" id="convertMonthly">从年度计划转入</button>
|
||||
<button class="btn primary" id="createMonthly">新建月度计划</button>
|
||||
</div>
|
||||
</div>
|
||||
<article class="card filters">
|
||||
<label>月份<select id="monthFilter"><option value="">全部</option><option>2026-02</option><option>2026-03</option><option>2026-04</option><option>2026-05</option><option>2026-06</option><option>2026-07</option><option>2026-08</option><option>2026-09</option><option>2026-10</option><option>2026-11</option></select></label>
|
||||
<label>主办单位<select id="monthUnit"></select></label>
|
||||
</article>
|
||||
<article class="card"><div class="workbook"><table>
|
||||
<thead><tr><th>月份</th><th>来源</th><th>课程</th><th>主办单位</th><th>上课时间</th><th>时长</th><th>讲师</th><th>资料</th><th>参加人员</th><th>状态</th><th></th></tr></thead>
|
||||
<tbody id="monthRows"></tbody>
|
||||
</table></div></article>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<div class="mask" id="mask"><aside class="drawer">
|
||||
<header><h2 id="drawerTitle">新增计划行</h2><p class="hint" id="drawerHint"></p></header>
|
||||
<div class="body" id="drawerBody"></div>
|
||||
<footer><button class="btn" id="drawerCancel">取消</button><button class="btn primary" id="drawerSave">保存</button></footer>
|
||||
</aside></div>
|
||||
<div class="toast" id="toast"></div>
|
||||
<script>
|
||||
/**
|
||||
* 原型交互:切换 HR、部门负责人、讲师后刷新年度计划、课程和月度计划。
|
||||
* 月度计划可从年度行转入,也可由讲师直接新建;已取消的场次不占年度次数。
|
||||
*/
|
||||
(() => {
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const people = [
|
||||
{ id:'wang', name:'王敏', dept:'财务部' }, { id:'li', name:'李强', dept:'财务部' },
|
||||
{ id:'zhao', name:'赵琳', dept:'财务部' }, { id:'chen', name:'陈浩', dept:'财务部' },
|
||||
{ id:'zhou', name:'周宁', dept:'财务部' }, { id:'sun', name:'孙悦', dept:'财务部' },
|
||||
{ id:'wu', name:'吴凯', dept:'仓储课' }, { id:'zheng', name:'郑兰', dept:'仓储课' },
|
||||
{ id:'feng', name:'冯涛', dept:'仓储课' }, { id:'xu', name:'许静', dept:'品质课' }
|
||||
];
|
||||
const finance = ['wang','li','zhao','chen'];
|
||||
const financeAll = ['wang','li','zhao','chen','zhou','sun'];
|
||||
const warehouse = ['wu','zheng','feng'];
|
||||
let courses = [
|
||||
['应收系统账务处理操作','专业技能','职能类','知识','enabled'],
|
||||
['应付系统账务处理操作','专业技能','职能类','知识','enabled'],
|
||||
['出口免抵退税办理流程','专业技能','职能类','知识','enabled'],
|
||||
['付款冲账作业','专业技能','职能类','知识','enabled'],
|
||||
['票据资金系统账务处理操作','专业技能','职能类','知识','enabled'],
|
||||
['外债还息还本作业','专业技能','职能类','知识','enabled'],
|
||||
['税务申报内容及方法','专业技能','职能类','知识','enabled'],
|
||||
['固定资产账务处理及方法','专业技能','职能类','知识','enabled'],
|
||||
['付款冲账操作','专业技能','职能类','知识','enabled'],
|
||||
['员工借支、报销作业SOP','企业文化类','规章制度与合规','知识','enabled'],
|
||||
['年度预算编制方法及要点','专业技能','职能类','知识','enabled'],
|
||||
['存货账龄分析','专业技能','职能类','知识','enabled'],
|
||||
['叉车安全操作规范','专业技能','行业类(EHS)','知识','enabled'],
|
||||
['化学品操作规范','专业技能','行业类(EHS)','知识','enabled'],
|
||||
['ERP 基本操作','专业技能','数字化转型','知识','enabled']
|
||||
];
|
||||
const line = (no, plant, unit, course, times, ids, note, place, side) => ({ no, plant, unit, course, times, ids, note, place, side });
|
||||
let plans = [
|
||||
line(1,'1厂','财务部','应收系统账务处理操作',1,finance,'财会人员','教育训练室','内'),
|
||||
line(2,'1厂','财务部','应付系统账务处理操作',1,finance,'财会人员','教育训练室','内'),
|
||||
line(3,'1厂','财务部','出口免抵退税办理流程',1,finance,'财会人员','教育训练室','内'),
|
||||
line(4,'1厂','财务部','付款冲账作业',1,finance,'财会人员','教育训练室','内'),
|
||||
line(5,'1厂','财务部','票据资金系统账务处理操作',1,finance,'财会人员','教育训练室','内'),
|
||||
line(6,'1厂','财务部','外债还息还本作业',1,finance,'财会人员','教育训练室','内'),
|
||||
line(7,'1厂','财务部','税务申报内容及方法',1,finance,'财会人员','教育训练室','内'),
|
||||
line(8,'1厂','财务部','固定资产账务处理及方法',1,finance,'财会人员','教育训练室','内'),
|
||||
line(9,'1厂','财务部','付款冲账操作',1,finance,'财会人员','教育训练室','内'),
|
||||
line(10,'1厂','财务部','员工借支、报销作业SOP',1,financeAll,'全体人员','教育训练室','内'),
|
||||
line(11,'1厂','财务部','年度预算编制方法及要点',1,finance,'财会人员','教育训练室','内'),
|
||||
line(12,'1厂','财务部','存货账龄分析',1,finance,'财会人员','教育训练室','内'),
|
||||
line(13,'1厂','仓储课','叉车安全操作规范',1,warehouse,'仓储全员','现场','内'),
|
||||
line(14,'1厂','仓储课','化学品操作规范',1,warehouse,'仓储全员','现场','内'),
|
||||
line(15,'1厂','仓储课','ERP 基本操作',1,warehouse,'仓储全员','现场','内')
|
||||
];
|
||||
const units = [
|
||||
['财务部','已提交','green','12 门 · 12-08'],
|
||||
['仓储课','已提交','green','3 门 · 12-11'],
|
||||
['品质课','未提交','amber','截止 12-31'],
|
||||
['生产课','逾期提交','red','仍可补交']
|
||||
];
|
||||
let monthlies = [
|
||||
{ id:1, annualNo:13, month:'2026-03', unit:'仓储课', plant:'1厂', course:'叉车安全操作规范', place:'现场', side:'内', start:'2026-03-12T14:00', end:'2026-03-12T15:30', hours:'1.5', instructor:'吴凯', files:['叉车操作规范.mp4'], ids:warehouse.slice(), status:'scheduled' },
|
||||
{ id:2, annualNo:0, month:'2026-03', unit:'仓储课', plant:'1厂', course:'ERP 基本操作', place:'教育训练室', side:'内', start:'2026-03-18T09:00', end:'2026-03-18T11:00', hours:'2', instructor:'郑兰', files:['ERP入门.pdf'], ids:['wu','zheng'], status:'scheduled' },
|
||||
{ id:3, annualNo:1, month:'2026-02', unit:'财务部', plant:'1厂', course:'应收系统账务处理操作', place:'教育训练室', side:'内', start:'2026-02-18T09:00', end:'2026-02-18T11:00', hours:'2', instructor:'王敏', files:['应收操作.pptx'], ids:finance.slice(), status:'scheduled' },
|
||||
{ id:4, annualNo:2, month:'2026-04', unit:'财务部', plant:'1厂', course:'应付系统账务处理操作', place:'教育训练室', side:'内', start:'2026-04-09T14:00', end:'2026-04-09T16:00', hours:'2', instructor:'赵琳', files:['应付流程.pdf'], ids:finance.slice(), status:'scheduled' },
|
||||
{ id:5, annualNo:4, month:'2026-05', unit:'财务部', plant:'1厂', course:'付款冲账作业', place:'教育训练室', side:'内', start:'2026-05-14T09:00', end:'2026-05-14T10:30', hours:'1.5', instructor:'赵琳', files:[], ids:finance.slice(), status:'scheduled' },
|
||||
{ id:6, annualNo:10, month:'2026-06', unit:'财务部', plant:'1厂', course:'员工借支、报销作业SOP', place:'教育训练室', side:'内', start:'2026-06-11T09:00', end:'2026-06-11T11:00', hours:'2', instructor:'王敏', files:['报销SOP.pdf'], ids:financeAll.slice(), status:'scheduled' },
|
||||
{ id:7, annualNo:14, month:'2026-06', unit:'仓储课', plant:'1厂', course:'化学品操作规范', place:'现场', side:'内', start:'2026-06-20T14:00', end:'2026-06-20T15:00', hours:'1', instructor:'吴凯', files:['化学品规范.mp4'], ids:warehouse.slice(), status:'scheduled' },
|
||||
{ id:8, annualNo:0, month:'2026-07', unit:'仓储课', plant:'1厂', course:'叉车安全操作规范', place:'现场', side:'内', start:'2026-07-08T14:00', end:'2026-07-08T15:00', hours:'1', instructor:'吴凯', files:[], ids:warehouse.slice(), status:'scheduled' },
|
||||
{ id:9, annualNo:11, month:'2026-08', unit:'财务部', plant:'1厂', course:'年度预算编制方法及要点', place:'教育训练室', side:'内', start:'2026-08-13T09:00', end:'2026-08-13T11:00', hours:'2', instructor:'王敏', files:['预算要点.pptx'], ids:finance.slice(), status:'scheduled' },
|
||||
{ id:10, annualNo:3, month:'2026-09', unit:'财务部', plant:'1厂', course:'出口免抵退税办理流程', place:'教育训练室', side:'内', start:'2026-09-10T09:00', end:'2026-09-10T11:00', hours:'2', instructor:'赵琳', files:['退税流程.pdf'], ids:finance.slice(), status:'scheduled' },
|
||||
{ id:11, annualNo:12, month:'2026-10', unit:'财务部', plant:'1厂', course:'存货账龄分析', place:'教育训练室', side:'内', start:'2026-10-15T14:00', end:'2026-10-15T15:30', hours:'1.5', instructor:'王敏', files:[], ids:finance.slice(), status:'scheduled' },
|
||||
{ id:12, annualNo:15, month:'2026-11', unit:'仓储课', plant:'1厂', course:'ERP 基本操作', place:'教育训练室', side:'内', start:'2026-11-05T09:00', end:'2026-11-05T11:00', hours:'2', instructor:'郑兰', files:['ERP入门.pdf'], ids:warehouse.slice(), status:'scheduled' }
|
||||
];
|
||||
const instructors = ['王敏','赵琳','吴凯','郑兰'];
|
||||
let role = 'hr';
|
||||
let drawerMode = '';
|
||||
let editingNo = 0;
|
||||
let editingCourse = '';
|
||||
let editingMonthly = 0;
|
||||
let draftFiles = [];
|
||||
const courseOf = (name) => courses.find((item) => item[0] === name);
|
||||
const personName = (id) => (people.find((item) => item.id === id) || {}).name || id;
|
||||
const toast = (message) => { $('toast').textContent = message; $('toast').classList.add('show'); setTimeout(() => $('toast').classList.remove('show'), 2200); };
|
||||
const scopeUnit = () => role === 'dept' ? '财务部' : role === 'teacher' ? '仓储课' : '';
|
||||
const isTeacher = () => role === 'teacher';
|
||||
|
||||
/**
|
||||
* 统计某条年度计划已排且未取消的月度场次。
|
||||
* @param {number} annualNo 年度计划行编号,0 表示计划外
|
||||
* @returns {number}
|
||||
*/
|
||||
function scheduledCount(annualNo) {
|
||||
return monthlies.filter((item) => item.annualNo === annualNo && item.status !== 'cancelled').length;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按当前身份和筛选条件列出计划行。部门负责人只看财务部。
|
||||
* @returns {Array<object>}
|
||||
*/
|
||||
function visiblePlans() {
|
||||
const plant = $('plant').value;
|
||||
const locked = scopeUnit();
|
||||
const unit = locked || $('unit').value;
|
||||
return plans.filter((item) => (!plant || item.plant === plant) && (!unit || item.unit === unit));
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染提交进度。部门负责人只看本单位,HR 看四家主办单位。
|
||||
*/
|
||||
function renderProgress() {
|
||||
const locked = scopeUnit();
|
||||
const cards = locked ? units.filter((item) => item[0] === locked) : units;
|
||||
$('progress').innerHTML = cards.map(([name, status, tone, extra]) => '<article class="card metric"><b>' + name + '</b><span><span class="badge ' + tone + '">' + status + '</span> ' + extra + '</span></article>').join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染年度计划表。参加人员显示姓名,对象说明附在后面。
|
||||
*/
|
||||
function renderPlans() {
|
||||
$('annualDesc').textContent = scopeUnit()
|
||||
? '当前只看' + scopeUnit() + '。参加人员需要点名,不会默认带出全部门。已排满次数后不能再转月度计划。'
|
||||
: '按主办单位收集。计划行从课程库选课,参加人员点名,不含培训费用。';
|
||||
$('addLine').disabled = isTeacher();
|
||||
const rows = visiblePlans();
|
||||
$('planRows').innerHTML = rows.map((item) => {
|
||||
const course = courseOf(item.course) || [];
|
||||
const names = item.ids.map(personName).join('、');
|
||||
const used = scheduledCount(item.no);
|
||||
const edit = isTeacher() ? '' : '<button class="link" data-edit="' + item.no + '">编辑</button>';
|
||||
return '<tr><td>' + item.no + '</td><td>' + item.plant + '</td><td>' + item.unit + '</td><td><b>' + item.course + '</b></td><td>' + (course[1] || '') + '</td><td>' + (course[2] || '') + '</td><td>' + item.times + '</td><td>' + used + '/' + item.times + '</td><td><span class="names">' + names + '</span>' + (item.note ? '<br><span class="note">' + item.note + '</span>' : '') + '</td><td>' + item.place + '</td><td>' + (course[3] || '') + '</td><td>' + item.side + '</td><td><div class="ops">' + edit + '<button class="link" data-convert="' + item.no + '">转为月度</button></div></td></tr>';
|
||||
}).join('') || '<tr><td colspan="13" class="hint">这一年度还没有计划行。</td></tr>';
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染课程库,并标出被多少条年度计划引用。
|
||||
*/
|
||||
function renderCourses() {
|
||||
$('tabCourses').style.display = role === 'hr' ? '' : 'none';
|
||||
$('courseRows').innerHTML = courses.map((item) => {
|
||||
const used = plans.filter((plan) => plan.course === item[0]).length;
|
||||
const status = item[4] === 'enabled' ? '<span class="badge green">启用</span>' : '<span class="badge gray">停用</span>';
|
||||
return '<tr><td><b>' + item[0] + '</b></td><td>' + item[1] + '</td><td>' + item[2] + '</td><td>' + item[3] + '</td><td>' + status + '</td><td>' + used + '</td><td><button class="link" data-course="' + item[0] + '">编辑</button></td></tr>';
|
||||
}).join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新主办单位筛选。部门负责人锁定财务部。
|
||||
*/
|
||||
function renderUnitFilter() {
|
||||
const select = $('unit');
|
||||
select.innerHTML = '<option value="">全部</option>' + units.map(([name]) => '<option>' + name + '</option>').join('');
|
||||
const locked = scopeUnit();
|
||||
select.disabled = Boolean(locked);
|
||||
if (locked) select.value = locked;
|
||||
}
|
||||
|
||||
/**
|
||||
* 画折线。横轴为月份,纵轴按当前序列最大值拉开。
|
||||
* @param {Array<{label:string,value:number}>} series
|
||||
* @param {string} color 线条颜色
|
||||
* @returns {string} SVG 标记
|
||||
*/
|
||||
function lineSvg(series, color) {
|
||||
const w = 560, h = 210, l = 36, r = 10, t = 16, b = 28;
|
||||
const max = Math.max(1, ...series.map((item) => item.value));
|
||||
const innerW = w - l - r, innerH = h - t - b;
|
||||
const x = (index) => l + innerW * index / (series.length - 1);
|
||||
const y = (value) => t + innerH - (value / max) * innerH;
|
||||
const line = series.map((item, index) => (index ? 'L' : 'M') + x(index).toFixed(1) + ',' + y(item.value).toFixed(1)).join(' ');
|
||||
const area = line + ' L' + x(series.length - 1).toFixed(1) + ',' + (t + innerH) + ' L' + x(0).toFixed(1) + ',' + (t + innerH) + ' Z';
|
||||
const grid = [0, 0.5, 1].map((step) => '<line x1="' + l + '" y1="' + (t + innerH - step * innerH) + '" x2="' + (w - r) + '" y2="' + (t + innerH - step * innerH) + '" stroke="#e7edf5" />').join('');
|
||||
const dots = series.map((item, index) => '<circle cx="' + x(index).toFixed(1) + '" cy="' + y(item.value).toFixed(1) + '" r="3.2" fill="' + color + '" /><text x="' + x(index).toFixed(1) + '" y="' + (y(item.value) - 7) + '" text-anchor="middle" fill="#334155" font-size="10">' + (item.value || '') + '</text>').join('');
|
||||
const labels = series.map((item, index) => '<text x="' + x(index).toFixed(1) + '" y="' + (h - 8) + '" text-anchor="middle" fill="#64748b" font-size="10">' + item.label + '</text>').join('');
|
||||
return '<svg viewBox="0 0 ' + w + ' ' + h + '" role="img">' + grid + '<path d="' + area + '" fill="' + color + '" opacity="0.12" /><path d="' + line + '" fill="none" stroke="' + color + '" stroke-width="2.4" />' + dots + labels + '</svg>';
|
||||
}
|
||||
|
||||
/**
|
||||
* 画单色柱状图。
|
||||
* @param {Array<{label:string,value:number}>} rows
|
||||
* @param {string} color 柱子颜色
|
||||
* @returns {string} SVG 标记
|
||||
*/
|
||||
function barSvg(rows, color) {
|
||||
if (!rows.length) return '<p class="hint">当前筛选没有可绘制的数据</p>';
|
||||
const w = 380, h = 230, l = 28, r = 8, t = 16, b = 52;
|
||||
const max = Math.max(1, ...rows.map((item) => item.value));
|
||||
const innerW = w - l - r, innerH = h - t - b;
|
||||
const gap = 10;
|
||||
const width = Math.max(12, (innerW - gap * rows.length) / rows.length);
|
||||
const bars = rows.map((item, index) => {
|
||||
const bh = (item.value / max) * innerH;
|
||||
const x = l + index * (width + gap);
|
||||
const y = t + innerH - bh;
|
||||
return '<rect x="' + x.toFixed(1) + '" y="' + y.toFixed(1) + '" width="' + width.toFixed(1) + '" height="' + Math.max(bh, item.value ? 2 : 0).toFixed(1) + '" rx="3" fill="' + color + '" /><text x="' + (x + width / 2).toFixed(1) + '" y="' + (y - 4) + '" text-anchor="middle" fill="#334155" font-size="10">' + item.value + '</text><text x="' + (x + width / 2).toFixed(1) + '" y="' + (h - 28) + '" text-anchor="middle" fill="#64748b" font-size="10">' + item.label + '</text>';
|
||||
}).join('');
|
||||
return '<svg viewBox="0 0 ' + w + ' ' + h + '" role="img"><line x1="' + l + '" y1="' + (t + innerH) + '" x2="' + (w - r) + '" y2="' + (t + innerH) + '" stroke="#e7edf5" />' + bars + '</svg>';
|
||||
}
|
||||
|
||||
/**
|
||||
* 画分组柱:每个主办单位一根计划次数、一根已排场次。
|
||||
* @param {Array<{label:string,plan:number,done:number}>} rows
|
||||
* @returns {string} SVG 标记
|
||||
*/
|
||||
function groupSvg(rows) {
|
||||
const w = 380, h = 230, l = 28, r = 8, t = 16, b = 36;
|
||||
const max = Math.max(1, ...rows.flatMap((item) => [item.plan, item.done]));
|
||||
const innerW = w - l - r, innerH = h - t - b;
|
||||
const group = innerW / rows.length;
|
||||
const width = Math.min(16, group / 3);
|
||||
const bars = rows.map((item, index) => {
|
||||
const x = l + index * group + group / 2;
|
||||
const planH = (item.plan / max) * innerH;
|
||||
const doneH = (item.done / max) * innerH;
|
||||
return '<rect x="' + (x - width - 2).toFixed(1) + '" y="' + (t + innerH - planH).toFixed(1) + '" width="' + width + '" height="' + planH.toFixed(1) + '" rx="2" fill="#2563eb" /><rect x="' + (x + 2).toFixed(1) + '" y="' + (t + innerH - doneH).toFixed(1) + '" width="' + width + '" height="' + doneH.toFixed(1) + '" rx="2" fill="#0f9f6e" /><text x="' + x.toFixed(1) + '" y="' + (h - 14) + '" text-anchor="middle" fill="#64748b" font-size="11">' + item.label + '</text>';
|
||||
}).join('');
|
||||
return '<svg viewBox="0 0 ' + w + ' ' + h + '" role="img"><line x1="' + l + '" y1="' + (t + innerH) + '" x2="' + (w - r) + '" y2="' + (t + innerH) + '" stroke="#e7edf5" />' + bars + '</svg>';
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染培训看板。折线按所选年度的 1–12 月;柱状图和数字跟随月份、厂区、主办单位。
|
||||
*/
|
||||
function renderBoard() {
|
||||
const year = $('boardYear').value;
|
||||
const month = $('boardMonth').value;
|
||||
const plant = $('boardPlant').value;
|
||||
const locked = scopeUnit();
|
||||
const unitSelect = $('boardUnit');
|
||||
const kept = unitSelect.value;
|
||||
unitSelect.innerHTML = '<option value="">全部</option>' + units.map(([name]) => '<option>' + name + '</option>').join('');
|
||||
unitSelect.disabled = Boolean(locked);
|
||||
unitSelect.value = locked || kept;
|
||||
if (locked) unitSelect.value = locked;
|
||||
const unit = locked || unitSelect.value;
|
||||
const matchPlan = (item) => (!plant || item.plant === plant) && (!unit || item.unit === unit);
|
||||
const matchSession = (item) => item.status !== 'cancelled' && item.month.startsWith(year) && (!plant || item.plant === plant) && (!unit || item.unit === unit);
|
||||
const yearSessions = monthlies.filter(matchSession);
|
||||
const periodSessions = yearSessions.filter((item) => !month || item.month.endsWith('-' + month));
|
||||
const scopedPlans = plans.filter(matchPlan);
|
||||
const planTimes = scopedPlans.reduce((sum, item) => sum + item.times, 0);
|
||||
const outside = periodSessions.filter((item) => !item.annualNo).length;
|
||||
const peopleCount = periodSessions.reduce((sum, item) => sum + item.ids.length, 0);
|
||||
const submittedNames = units.filter((item) => item[1] === '已提交' && (!unit || item[0] === unit)).length;
|
||||
const unitTotal = unit ? 1 : units.length;
|
||||
$('boardKpis').innerHTML = [
|
||||
[submittedNames + '/' + unitTotal, '已提交主办单位'],
|
||||
[periodSessions.length + ' / ' + planTimes, month ? '本月已排 / 全年计划次数' : '已排场次 / 计划次数'],
|
||||
[String(outside), '计划外场次'],
|
||||
[String(peopleCount), '计划受训人次']
|
||||
].map(([value, label]) => '<article class="card metric"><b>' + value + '</b><span>' + label + '</span></article>').join('');
|
||||
const months = ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'];
|
||||
const byMonth = months.map((label, index) => {
|
||||
const key = year + '-' + String(index + 1).padStart(2, '0');
|
||||
const rows = yearSessions.filter((item) => item.month === key);
|
||||
return { label, sessions: rows.length, hours: rows.reduce((sum, item) => sum + Number(item.hours || 0), 0) };
|
||||
});
|
||||
$('chartSessions').innerHTML = lineSvg(byMonth.map((item) => ({ label: item.label, value: item.sessions })), '#2563eb');
|
||||
$('chartHours').innerHTML = lineSvg(byMonth.map((item) => ({ label: item.label, value: Math.round(item.hours * 10) / 10 })), '#0f766e');
|
||||
const unitNames = unit ? [unit] : units.map((item) => item[0]);
|
||||
$('chartUnits').innerHTML = groupSvg(unitNames.map((name) => ({
|
||||
label: name,
|
||||
plan: plans.filter((item) => item.unit === name && (!plant || item.plant === plant)).reduce((sum, item) => sum + item.times, 0),
|
||||
done: periodSessions.filter((item) => item.unit === name && item.annualNo).length
|
||||
})));
|
||||
const catMap = {};
|
||||
periodSessions.forEach((item) => {
|
||||
const cat = (courseOf(item.course) || [])[1] || '未分类';
|
||||
catMap[cat] = (catMap[cat] || 0) + 1;
|
||||
});
|
||||
$('chartCats').innerHTML = barSvg(Object.entries(catMap).map(([label, value]) => ({ label, value })), '#7c3aed');
|
||||
const teacherMap = {};
|
||||
periodSessions.forEach((item) => { teacherMap[item.instructor] = (teacherMap[item.instructor] || 0) + Number(item.hours || 0); });
|
||||
$('chartTeachers').innerHTML = barSvg(Object.entries(teacherMap).map(([label, value]) => ({ label, value: Math.round(value * 10) / 10 })), '#b45309');
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染月度计划。已取消场次仍展示,但不计入年度已排次数。
|
||||
*/
|
||||
function renderMonthly() {
|
||||
const locked = scopeUnit();
|
||||
const unitSelect = $('monthUnit');
|
||||
const current = unitSelect.value;
|
||||
unitSelect.innerHTML = '<option value="">全部</option>' + units.map(([name]) => '<option>' + name + '</option>').join('');
|
||||
unitSelect.disabled = Boolean(locked);
|
||||
unitSelect.value = locked || current;
|
||||
if (locked) unitSelect.value = locked;
|
||||
$('monthlyDesc').textContent = locked
|
||||
? locked + '讲师可新建月度计划,或从本单位未排满的年度计划转入。'
|
||||
: '讲师创建。从年度计划转入时带出课程、地点和已选人员;直接新建的记为计划外。';
|
||||
const month = $('monthFilter').value;
|
||||
const unit = locked || unitSelect.value;
|
||||
const rows = monthlies.filter((item) => (!month || item.month === month) && (!unit || item.unit === unit));
|
||||
$('monthRows').innerHTML = rows.map((item) => {
|
||||
const when = (item.start || '').replace('T', ' ') + (item.end ? ' – ' + item.end.slice(11) : '');
|
||||
const source = item.annualNo ? '<span class="badge blue">年度 #' + item.annualNo + '</span>' : '<span class="badge amber">计划外</span>';
|
||||
const state = item.status === 'cancelled' ? '<span class="badge gray">已取消</span>' : '<span class="badge green">待开课</span>';
|
||||
const cancel = item.status === 'cancelled' ? '' : '<button class="link" data-cancel="' + item.id + '">取消</button>';
|
||||
return '<tr><td>' + item.month + '</td><td>' + source + '</td><td><b>' + item.course + '</b></td><td>' + item.unit + '</td><td>' + when + '</td><td>' + item.hours + ' 小时</td><td>' + item.instructor + '</td><td>' + (item.files.join('、') || '—') + '</td><td class="names">' + item.ids.map(personName).join('、') + '</td><td>' + state + '</td><td><div class="ops"><button class="link" data-medit="' + item.id + '">编辑</button>' + cancel + '</div></td></tr>';
|
||||
}).join('') || '<tr><td colspan="11" class="hint">这个范围还没有月度计划。</td></tr>';
|
||||
}
|
||||
|
||||
function openMask() { $('mask').classList.add('show'); }
|
||||
function closeMask() { $('mask').classList.remove('show'); drawerMode = ''; }
|
||||
|
||||
/**
|
||||
* 打开计划行抽屉。分类从课程带出且只读,人员默认不勾选。
|
||||
* @param {object|null} plan 为空时是新增
|
||||
*/
|
||||
function openPlan(plan) {
|
||||
drawerMode = 'plan';
|
||||
editingNo = plan ? plan.no : 0;
|
||||
$('drawerTitle').textContent = plan ? '编辑计划行 ' + plan.no : '新增计划行';
|
||||
$('drawerHint').textContent = '不含培训费用。一级分类、二级分类、分类随课程带出。';
|
||||
const selected = new Set(plan ? plan.ids : []);
|
||||
const options = courses.filter((item) => item[4] === 'enabled' || (plan && item[0] === plan.course)).map((item) => '<option' + (plan && item[0] === plan.course ? ' selected' : '') + '>' + item[0] + '</option>').join('');
|
||||
const locked = scopeUnit();
|
||||
const unitField = locked
|
||||
? '<div class="field"><label>主办单位</label><div class="readonly">' + locked + '</div></div>'
|
||||
: '<div class="field"><label>主办单位</label><select id="f-unit">' + units.map(([name]) => '<option' + (plan && plan.unit === name ? ' selected' : '') + '>' + name + '</option>').join('') + '</select></div>';
|
||||
$('drawerBody').innerHTML = '<div class="field"><label>厂区</label><select id="f-plant"><option' + (!plan || plan.plant === '1厂' ? ' selected' : '') + '>1厂</option><option' + (plan && plan.plant === '2厂' ? ' selected' : '') + '>2厂</option></select></div>' + unitField + '<div class="field"><label>课程</label><select id="f-course">' + options + '</select></div><div class="field"><label>分类(只读)</label><div class="readonly" id="f-cats"></div></div><div class="field"><label>次数</label><input id="f-times" type="number" min="1" value="' + (plan ? plan.times : 1) + '" /></div><div class="field"><label>地点</label><input id="f-place" value="' + (plan ? plan.place : '教育训练室') + '" /></div><div class="field"><label>内/外培训</label><select id="f-side"><option' + (!plan || plan.side === '内' ? ' selected' : '') + '>内</option><option' + (plan && plan.side === '外' ? ' selected' : '') + '>外</option></select></div><div class="field"><label>对象说明(选填)</label><input id="f-note" placeholder="如财会人员、仓储全员" value="' + (plan ? plan.note : '') + '" /></div><div class="field"><label>参加人员</label><p class="hint">从在职用户中勾选,可跨部门。不会默认选中主办单位全员。</p><div class="people" id="f-people">' + people.map((item) => '<label class="person"><input type="checkbox" value="' + item.id + '"' + (selected.has(item.id) ? ' checked' : '') + ' />' + item.name + '<small>' + item.dept + '</small></label>').join('') + '</div></div>';
|
||||
const syncCats = () => { const course = courseOf($('f-course').value) || []; $('f-cats').textContent = (course[1] || '') + ' / ' + (course[2] || '') + ' / ' + (course[3] || ''); };
|
||||
$('f-course').addEventListener('change', syncCats);
|
||||
syncCats();
|
||||
openMask();
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开课程抽屉。已有课程改分类不影响已保存计划行的展示快照,原型里用当前课程库直接展示。
|
||||
* @param {Array<string>|null} course
|
||||
*/
|
||||
function openCourse(course) {
|
||||
drawerMode = 'course';
|
||||
editingCourse = course ? course[0] : '';
|
||||
$('drawerTitle').textContent = course ? '编辑课程' : '新增课程';
|
||||
$('drawerHint').textContent = '停用后不能被新的年度计划选用。';
|
||||
$('drawerBody').innerHTML = '<div class="field"><label>课程名称</label><input id="c-name" value="' + (course ? course[0] : '') + '" /></div><div class="field"><label>一级分类</label><input id="c-1" value="' + (course ? course[1] : '') + '" placeholder="专业技能" /></div><div class="field"><label>二级分类</label><input id="c-2" value="' + (course ? course[2] : '') + '" placeholder="职能类" /></div><div class="field"><label>分类</label><input id="c-3" value="' + (course ? course[3] : '知识') + '" /></div><div class="field"><label>状态</label><select id="c-status"><option value="enabled"' + (!course || course[4] === 'enabled' ? ' selected' : '') + '>启用</option><option value="disabled"' + (course && course[4] === 'disabled' ? ' selected' : '') + '>停用</option></select></div>';
|
||||
openMask();
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开月度计划抽屉。从年度转入时带出课程、地点、内/外和参加人员。
|
||||
* @param {object|null} record 已有月度计划,为空则新建
|
||||
* @param {object|null} annual 来源年度计划行
|
||||
*/
|
||||
function openMonthly(record, annual) {
|
||||
if (annual && scheduledCount(annual.no) >= annual.times && !(record && record.annualNo === annual.no)) {
|
||||
toast('「' + annual.course + '」次数已排满。可先提高年度计划的次数,或取消一场未开课的月度计划');
|
||||
return;
|
||||
}
|
||||
drawerMode = 'monthly';
|
||||
editingMonthly = record ? record.id : 0;
|
||||
const source = annual || (record && record.annualNo ? plans.find((item) => item.no === record.annualNo) : null);
|
||||
draftFiles = (record ? record.files : []).slice();
|
||||
$('drawerTitle').textContent = record ? '编辑月度计划' : (source ? '从年度计划转入' : '新建月度计划');
|
||||
$('drawerHint').textContent = source ? '来自年度计划 #' + source.no + '。上课时间和资料由讲师填写。' : '未关联年度计划,保存后记为计划外。';
|
||||
const selected = new Set(record ? record.ids : (source ? source.ids : []));
|
||||
const courseName = record ? record.course : (source ? source.course : '');
|
||||
const courseOptions = courses.filter((item) => item[4] === 'enabled' || item[0] === courseName).map((item) => '<option' + (item[0] === courseName ? ' selected' : '') + '>' + item[0] + '</option>').join('');
|
||||
const annualOptions = '<option value="0">不关联,记为计划外</option>' + visiblePlans().map((item) => '<option value="' + item.no + '"' + (source && source.no === item.no ? ' selected' : '') + '>#' + item.no + ' ' + item.course + '(已排 ' + scheduledCount(item.no) + '/' + item.times + ')</option>').join('');
|
||||
const unitName = record ? record.unit : (source ? source.unit : (scopeUnit() || '财务部'));
|
||||
$('drawerBody').innerHTML = '<div class="field"><label>来源</label><select id="m-source"' + (record ? ' disabled' : '') + '>' + annualOptions + '</select></div><div class="field"><label>月份</label><input id="m-month" type="month" value="' + (record ? record.month : '2026-04') + '" /></div><div class="field"><label>课程</label>' + (source ? '<div class="readonly" id="m-course">' + courseName + '</div>' : '<select id="m-course">' + courseOptions + '</select>') + '</div><div class="field"><label>主办单位</label><div class="readonly" id="m-unit">' + unitName + '</div></div><div class="field"><label>开始</label><input id="m-start" type="datetime-local" value="' + (record ? record.start : '') + '" /></div><div class="field"><label>结束</label><input id="m-end" type="datetime-local" value="' + (record ? record.end : '') + '" /></div><div class="field"><label>时长(小时)</label><input id="m-hours" value="' + (record ? record.hours : '1') + '" /></div><div class="field"><label>地点</label><input id="m-place" value="' + (record ? record.place : (source ? source.place : '教育训练室')) + '" /></div><div class="field"><label>讲师</label><select id="m-instructor">' + instructors.map((name) => '<option' + ((record ? record.instructor : instructors[0]) === name ? ' selected' : '') + '>' + name + '</option>').join('') + '</select></div><div class="field"><label>课件 / 视频</label><div class="chips" id="m-files"></div><div class="ops" style="margin-top:8px"><input id="m-file" placeholder="文件名,如 课件.pdf" /><button class="btn" id="m-add-file" type="button">添加</button></div></div><div class="field"><label>参加人员</label><p class="hint">默认带出年度计划已选人员,可按这一场增删。</p><div class="people" id="m-people">' + people.map((item) => '<label class="person"><input type="checkbox" value="' + item.id + '"' + (selected.has(item.id) ? ' checked' : '') + ' />' + item.name + '<small>' + item.dept + '</small></label>').join('') + '</div></div>';
|
||||
const paintFiles = () => { $('m-files').innerHTML = draftFiles.map((name) => '<span class="chip">' + name + '</span>').join('') || '<span class="note">还没有资料</span>'; };
|
||||
const applySource = () => {
|
||||
const no = Number($('m-source').value);
|
||||
const plan = plans.find((item) => item.no === no);
|
||||
if (!plan || $('m-course').tagName !== 'DIV') return;
|
||||
$('m-course').textContent = plan.course;
|
||||
$('m-unit').textContent = plan.unit;
|
||||
$('m-place').value = plan.place;
|
||||
document.querySelectorAll('#m-people input').forEach((input) => { input.checked = plan.ids.includes(input.value); });
|
||||
};
|
||||
$('m-add-file').addEventListener('click', () => {
|
||||
const name = $('m-file').value.trim();
|
||||
if (!name) return;
|
||||
draftFiles.push(name);
|
||||
$('m-file').value = '';
|
||||
paintFiles();
|
||||
});
|
||||
if (!record) $('m-source').addEventListener('change', () => {
|
||||
const no = Number($('m-source').value);
|
||||
if (!no) {
|
||||
$('drawerHint').textContent = '未关联年度计划,保存后记为计划外。';
|
||||
return;
|
||||
}
|
||||
const plan = plans.find((item) => item.no === no);
|
||||
if (plan && scheduledCount(plan.no) >= plan.times) { toast('这条年度计划次数已排满'); $('m-source').value = '0'; return; }
|
||||
$('drawerHint').textContent = '来自年度计划 #' + plan.no + '。上课时间和资料由讲师填写。';
|
||||
if ($('m-course').tagName === 'DIV') applySource();
|
||||
else {
|
||||
$('m-unit').textContent = plan.unit;
|
||||
$('m-place').value = plan.place;
|
||||
$('m-course').value = plan.course;
|
||||
document.querySelectorAll('#m-people input').forEach((input) => { input.checked = plan.ids.includes(input.value); });
|
||||
}
|
||||
});
|
||||
paintFiles();
|
||||
openMask();
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存抽屉。计划行至少点名 1 人;课程名称不能空;月度计划必须填写上课时间。
|
||||
*/
|
||||
function saveDrawer() {
|
||||
if (drawerMode === 'monthly') {
|
||||
const ids = [...document.querySelectorAll('#m-people input:checked')].map((item) => item.value);
|
||||
if (!ids.length) { toast('请至少选择 1 名参加人员'); return; }
|
||||
if (!$('m-start').value || !$('m-end').value) { toast('请填写开始和结束时间'); return; }
|
||||
const annualNo = Number($('m-source').value || 0);
|
||||
const annual = plans.find((item) => item.no === annualNo);
|
||||
if (annual && scheduledCount(annual.no) >= annual.times && editingMonthly === 0) { toast('次数已排满'); return; }
|
||||
const courseEl = $('m-course');
|
||||
const payload = {
|
||||
annualNo, month:$('m-month').value, unit:$('m-unit').textContent,
|
||||
plant: annual ? annual.plant : '1厂',
|
||||
course: courseEl.tagName === 'DIV' ? courseEl.textContent : courseEl.value,
|
||||
place:$('m-place').value.trim() || '教育训练室', side: annual ? annual.side : '内',
|
||||
start:$('m-start').value, end:$('m-end').value, hours:$('m-hours').value || '1',
|
||||
instructor:$('m-instructor').value, files:draftFiles.slice(), ids, status:'scheduled'
|
||||
};
|
||||
if (editingMonthly) Object.assign(monthlies.find((item) => item.id === editingMonthly), payload);
|
||||
else monthlies.push({ id: monthlies.reduce((max, item) => Math.max(max, item.id), 0) + 1, ...payload });
|
||||
toast(editingMonthly ? '已更新月度计划' : (annualNo ? '已从年度计划转入' : '已新建计划外月度计划'));
|
||||
closeMask();
|
||||
renderPlans();
|
||||
renderMonthly();
|
||||
renderBoard();
|
||||
go('monthly');
|
||||
return;
|
||||
}
|
||||
if (drawerMode === 'plan') {
|
||||
const ids = [...document.querySelectorAll('#f-people input:checked')].map((item) => item.value);
|
||||
if (!ids.length) { toast('请至少选择 1 名参加人员'); return; }
|
||||
const times = Number($('f-times').value || 1);
|
||||
const payload = { plant:$('f-plant').value, unit:scopeUnit() || $('f-unit').value, course:$('f-course').value, times: times > 0 ? times : 1, ids, note:$('f-note').value.trim(), place:$('f-place').value.trim() || '教育训练室', side:$('f-side').value };
|
||||
if (editingNo) Object.assign(plans.find((item) => item.no === editingNo), payload);
|
||||
else plans.push({ no: plans.reduce((max, item) => Math.max(max, item.no), 0) + 1, ...payload });
|
||||
toast(editingNo ? '已更新计划行' : '已新增计划行');
|
||||
} else if (drawerMode === 'course') {
|
||||
const name = $('c-name').value.trim();
|
||||
if (!name) { toast('请填写课程名称'); return; }
|
||||
const next = [name, $('c-1').value.trim() || '未分类', $('c-2').value.trim() || '未分类', $('c-3').value.trim() || '知识', $('c-status').value];
|
||||
if (editingCourse) {
|
||||
const index = courses.findIndex((item) => item[0] === editingCourse);
|
||||
plans.forEach((item) => { if (item.course === editingCourse) item.course = name; });
|
||||
courses[index] = next;
|
||||
} else if (courses.some((item) => item[0] === name)) { toast('课程名称已存在'); return; }
|
||||
else courses.push(next);
|
||||
toast(editingCourse ? '已更新课程' : '已新增课程');
|
||||
renderCourses();
|
||||
}
|
||||
closeMask();
|
||||
renderPlans();
|
||||
renderCourses();
|
||||
renderBoard();
|
||||
}
|
||||
|
||||
function go(view) {
|
||||
if (view === 'courses' && role !== 'hr') { toast('课程库由 HR 维护'); return; }
|
||||
document.querySelectorAll('.view').forEach((item) => item.classList.toggle('active', item.id === 'v-' + view));
|
||||
document.querySelectorAll('#tabs button').forEach((item) => item.classList.toggle('active', item.dataset.v === view));
|
||||
}
|
||||
|
||||
$('role').addEventListener('change', () => { role = $('role').value; if (role !== 'hr' && document.getElementById('v-courses').classList.contains('active')) go('annual'); renderUnitFilter(); renderProgress(); renderPlans(); renderCourses(); renderMonthly(); renderBoard(); });
|
||||
$('tabs').addEventListener('click', (event) => { const button = event.target.closest('[data-v]'); if (button) go(button.dataset.v); });
|
||||
$('plant').addEventListener('change', renderPlans);
|
||||
$('unit').addEventListener('change', renderPlans);
|
||||
$('year').addEventListener('change', () => toast($('year').value === '2027' ? '2027 年尚未收集,可新增计划行' : '已切回 2026 年样例'));
|
||||
$('resetFilter').addEventListener('click', () => { $('plant').value = ''; if (!scopeUnit()) $('unit').value = ''; renderPlans(); });
|
||||
$('exportBtn').addEventListener('click', () => toast('示意导出:编号、厂区、主办单位、课程名称、一级分类、二级分类、次数、参加人员、地点、分类、内/外培训'));
|
||||
$('addLine').addEventListener('click', () => openPlan(null));
|
||||
$('addCourse').addEventListener('click', () => openCourse(null));
|
||||
$('planRows').addEventListener('click', (event) => {
|
||||
const edit = event.target.closest('[data-edit]');
|
||||
const convert = event.target.closest('[data-convert]');
|
||||
if (edit) openPlan(plans.find((item) => item.no === Number(edit.dataset.edit)));
|
||||
if (convert) openMonthly(null, plans.find((item) => item.no === Number(convert.dataset.convert)));
|
||||
});
|
||||
$('monthRows').addEventListener('click', (event) => {
|
||||
const edit = event.target.closest('[data-medit]');
|
||||
const cancel = event.target.closest('[data-cancel]');
|
||||
if (edit) openMonthly(monthlies.find((item) => item.id === Number(edit.dataset.medit)), null);
|
||||
if (cancel) {
|
||||
const item = monthlies.find((row) => row.id === Number(cancel.dataset.cancel));
|
||||
item.status = 'cancelled';
|
||||
toast('已取消,这场不再占用年度次数');
|
||||
renderPlans();
|
||||
renderMonthly();
|
||||
renderBoard();
|
||||
}
|
||||
});
|
||||
$('monthFilter').addEventListener('change', renderMonthly);
|
||||
$('monthUnit').addEventListener('change', renderMonthly);
|
||||
$('createMonthly').addEventListener('click', () => openMonthly(null, null));
|
||||
$('convertMonthly').addEventListener('click', () => {
|
||||
const candidate = visiblePlans().find((item) => scheduledCount(item.no) < item.times);
|
||||
if (!candidate) { toast('当前范围的年度计划次数都已排满'); return; }
|
||||
openMonthly(null, candidate);
|
||||
});
|
||||
$('courseRows').addEventListener('click', (event) => { const button = event.target.closest('[data-course]'); if (button) openCourse(courseOf(button.dataset.course)); });
|
||||
$('drawerCancel').addEventListener('click', closeMask);
|
||||
$('drawerSave').addEventListener('click', saveDrawer);
|
||||
$('mask').addEventListener('click', (event) => { if (event.target === $('mask')) closeMask(); });
|
||||
$('goFill').addEventListener('click', () => { $('role').value = 'dept'; $('role').dispatchEvent(new Event('change')); go('annual'); });
|
||||
['boardYear','boardMonth','boardPlant','boardUnit'].forEach((id) => $(id).addEventListener('change', renderBoard));
|
||||
renderUnitFilter(); renderProgress(); renderPlans(); renderCourses(); renderMonthly(); renderBoard();
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+4
-4
@@ -6,11 +6,11 @@
|
||||
| ------------------------ | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| OA 合同与请款同步 | 已实现 | 合同申请单走 HTTP 待办/已办;验收归档查 OA SQL(`formtable_main_324.cgdh` × `workflow_requestbase.currentnodetype=3`)按采购单号落事件;普通同步只补空字段,管理员可强制覆盖 OA 非空字段并保留变更审计。 |
|
||||
| 四阶段三轮预警扫描 | 已实现 | 每日扫描只生成 pending 预警;第一轮按台账申请人真实姓名匹配系统用户,第二、三轮按申请人部门查 OA `HrmResource` + `Matrixtable_3`(`zz`/`jfl` 即企微 userid)。 |
|
||||
| 企业微信周汇总 | 已实现 | 每周五 18:00 按收件人发一条汇总卡片及逐笔 Excel 附件;Excel「收件人」列为系统用户真实姓名;并在“周汇总批次”独立入口保留批次审计。 |
|
||||
| 合同付款台账与详情 | 已实现 | Chat Agent「合同付款预警」以 Tab 展示合同台账:服务端分页展示合同、流程、采购、供应商、四阶段金额比例日期、申请人和简洁状态标签;关键词同时匹配合同号、流程号、采购单号、供应商和申请人;四张汇总卡按合同统计即将到期(7日内)、逾期未付、进行中、本月应付(全量台账),点击过滤列表;点击合同在当前 Tab 内查看概览、原文附件、付款计划和预警记录。 |
|
||||
| 企业微信周汇总 | 已实现 | 每周五 18:00 按收件人发一条汇总卡片及逐笔 Excel 附件;Excel「收件人」列为系统用户真实姓名;“周汇总批次”保留批次审计,发送失败可点击图标查看原因。 |
|
||||
| 合同付款台账与详情 | 已实现 | Chat Agent「合同付款预警」以 Tab 展示合同台账:服务端分页展示合同、流程、采购、供应商、四阶段金额比例日期、申请人和简洁状态标签;关键词同时匹配合同号、流程号、采购单号、供应商和申请人;四张汇总卡按合同统计即将到期(7日内)、逾期未付、未到期(7日外)、本月应付(全量台账),点击过滤列表;点击合同在当前 Tab 内查看概览、原文附件、付款计划和预警记录。 |
|
||||
| 通用合同解析与待确认合同 | 已实现 | 不再校验 V4 或其他固定模板;只校验合同号、金额、交期、采购单号及四阶段付款比例完整、无重复、合计 100%。关键事实或比例校验失败合同归入 Chat「待确认」Tab,不得触发自动预警。 |
|
||||
| 扫描版合同 MinerU 解析 | 已实现 | OA PDF 附件优先经 MinerU 生成 Markdown 后再解析合同号、金额、交期与四阶段付款比例;服务未配置、失败或空结果时安全回退既有文字层/OCR,历史合同可用“批量重新解析存量合同”刷新。 |
|
||||
| 存量合同批量重解析 | 已实现 | 管理员可直接用已归档附件批量刷新历史解析结果,不拉取 OA、不覆盖 OA 字段,用于规则升级后的待确认合同恢复。 |
|
||||
| 存量合同批量重解析 | 已实现 | 管理员可直接用已归档附件批量刷新历史解析结果,不覆盖 OA 字段。原文若已被临时文件清理删除,则按附件 ID 从 OA 或 DMS 重新下载后再解析。 |
|
||||
| 合同付款 Agent 授权 | 已实现 | 入口为 Chat builtin Agent `contract_payment`:平台 admin 默认可访问,普通用户需在用户管理授予该 Agent。旧功能权限 `contract_payment.access` 由迁移写入 Agent 授权后删除。无授权直链提示并回应用管理,API 返回 403。同步 OA、强制覆盖、批量重解析、扫描预警和发送预警仅平台管理员可见并可调用。 |
|
||||
| OA 盖章合同优先 | 已实现 | 合同申请单存在“盖章完成合同上传”时固定优先下载和解析该附件;“合同附件”仅作为失败降级来源。 |
|
||||
|
||||
@@ -716,7 +716,7 @@
|
||||
| OA 厂商请款判定 | 已实现 | 同步「厂商预付款请款作业」,预付款/出货款存在对应请款事实即停止后续升级。 |
|
||||
| 每日扫描与周五汇总 | 已实现 | 每日生成到期轮次待发送记录;仅周五 18:00 按收件人发送一条企业微信汇总及 Excel 明细附件(「收件人」列为实际姓名)。 |
|
||||
| OA 增量同步 | 已实现 | 合同 HTTP 列表以 `oa-contract-archive` 为游标;验收 SQL 以 `oa-acceptance-archive` 独立游标。首次全量,增量按时间窗口 + 采购单号回补;触顶不推进合同断点;重复运行不重复入库。 |
|
||||
| 工作台与审计 | 已实现 | Chat Agent「合同付款预警」以 Tab 分为合同台账、待确认与周汇总批次;台账/待确认支持按合同号、流程号、采购单号或供应商模糊检索;台账展示本周待发送笔数和下一次周五 18:00;周汇总 Tab 可查看批次并下载 Excel 附件。平台 admin 或被授予该 Agent 的用户可访问,不要求把功能权限勾到用户表;同步/扫描/发送仅管理员。旧 `/workspace/contract-payment*` 重定向到 Chat。 |
|
||||
| 工作台与审计 | 已实现 | Chat Agent「合同付款预警」以 Tab 分为合同台账、待确认与周汇总批次;台账/待确认支持按合同号、流程号、采购单号或供应商模糊检索;台账展示本周待发送笔数和下一次周五 18:00;周汇总 Tab 可查看批次、下载 Excel 附件,发送失败可点击图标查看原因。平台 admin 或被授予该 Agent 的用户可访问,不要求把功能权限勾到用户表;同步/扫描/发送仅管理员。旧 `/workspace/contract-payment*` 重定向到 Chat。 |
|
||||
|
||||
- [X] Admin 模板比对区域配置、V4 默认恢复与识别预览
|
||||
- [X] 默认启用模板区域规则自动应用于 Chat 双文件比对
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* 合同付款预警 API 类型与请求封装。
|
||||
* 依赖:统一 requestJson;后端 /api/contract-payment。
|
||||
* 逻辑:台账/合同详情查询、汇总卡统计、待发送摘要、每日扫描入队、周五汇总入队及批次附件下载。
|
||||
* 逻辑:台账/合同详情查询、汇总卡统计、待发送摘要、每日扫描入队、周五汇总入队、批次附件下载、失败原因及后台任务状态。
|
||||
*/
|
||||
import { requestBlob, requestJson } from '@/shared/api/client';
|
||||
|
||||
@@ -28,7 +28,8 @@ export interface LedgerSummary {
|
||||
active: number;
|
||||
due_this_month: number;
|
||||
}
|
||||
export interface AlertBatch { id: number; batch_no: string; week_key: string; status: string; summary?: { total?: number; stages?: Record<string, number> }; excel_file_name?: string | null; excel_file_size?: number | null; sent_at?: string | null; }
|
||||
export interface AlertBatchFailureReason { code: string; detail?: string | null; }
|
||||
export interface AlertBatch { id: number; batch_no: string; week_key: string; status: string; summary?: { total?: number; stages?: Record<string, number> }; excel_file_name?: string | null; excel_file_size?: number | null; sent_at?: string | null; created_at?: string | null; failure_reasons?: AlertBatchFailureReason[]; }
|
||||
export interface AlertSummary { pending_count: number; next_send_at?: string | null; timezone?: string | null; }
|
||||
|
||||
/**
|
||||
@@ -37,7 +38,7 @@ export interface AlertSummary { pending_count: number; next_send_at?: string | n
|
||||
* @param params.keyword - 模糊检索词,可为空。
|
||||
* @param params.parse_status - 解析状态精确筛选。
|
||||
* @param params.reviewOnly - 为 true 时只查 needs_review。
|
||||
* @param params.focus - 汇总卡口径:即将到期 / 逾期未付 / 进行中 / 本月应付。
|
||||
* @param params.focus - 汇总卡口径:即将到期 / 逾期未付 / 未到期 / 本月应付。
|
||||
* @returns 分页后的合同列表。
|
||||
*/
|
||||
export const listContractPaymentContracts = (params?: { keyword?: string; parse_status?: string; reviewOnly?: boolean; focus?: LedgerFocus; page?: number; pageSize?: number }) => {
|
||||
@@ -55,7 +56,16 @@ export const enqueueContractPaymentSync = (force = false) => requestJson<{ job_i
|
||||
/** 提交存量合同批量重解析,直接使用已归档附件刷新历史解析结果。 */
|
||||
export const enqueueContractPaymentReparse = () => requestJson<{ job_id: string }>('/api/contract-payment/sync', { method: 'POST', body: JSON.stringify({ reparse_existing: true }) });
|
||||
export const enqueueContractPaymentAlertScan = () => requestJson<{ job_id: string }>('/api/contract-payment/alerts/run', { method: 'POST' });
|
||||
export const enqueueContractPaymentWeeklyAlert = () => requestJson<{ job_id: string }>('/api/contract-payment/alerts/weekly-run', { method: 'POST' });
|
||||
export const enqueueContractPaymentWeeklyAlert = () => requestJson<{ job_id: number }>('/api/contract-payment/alerts/weekly-run', { method: 'POST' });
|
||||
export interface ContractPaymentJobResult { batches?: number; sent?: number; failed?: number; alerts?: number; }
|
||||
export interface ContractPaymentJob { id: number; status: string; message?: string | null; result?: ContractPaymentJobResult | null; }
|
||||
/**
|
||||
* 查询当前管理员刚提交的合同付款后台任务。
|
||||
* 核心逻辑:发送预警只是入队,页面需轮询本接口直到 success / failed,再刷新周汇总列表。
|
||||
* @param jobId - 入队接口返回的任务主键。
|
||||
* @returns 任务状态与发送计数。
|
||||
*/
|
||||
export const getContractPaymentJob = (jobId: number) => requestJson<ContractPaymentJob>(`/api/contract-payment/jobs/${jobId}`);
|
||||
/** 查询本周待发送笔数和下一次周五汇总发送时间。 */
|
||||
export const getContractPaymentAlertSummary = () => requestJson<AlertSummary>('/api/contract-payment/alerts/summary');
|
||||
/**
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
view / contractId 写入 /chat/:agentId 查询参数,旧工作台地址重定向后仍可深链打开。
|
||||
列表 Tab 内容区 overflow-hidden,把纵向滚动交给子页表格区域;Chat 顶栏仅保留标题。
|
||||
管理员顶栏顺序:同步 OA → 发送预警 → 更多;前两者常显,低频操作收进「更多」以节省小屏高度。
|
||||
发送预警结束后重新拉取周汇总批次,避免列表停在点击前的失败记录。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
|
||||
@@ -37,6 +38,16 @@ const reviewCount = ref(0);
|
||||
const moreMenuOpen = ref(false);
|
||||
const moreMenuRef = ref<HTMLElement | null>(null);
|
||||
|
||||
const batchesPage = ref<{ reload: () => Promise<void> } | null>(null);
|
||||
|
||||
/**
|
||||
* 周汇总发送结束后刷新当前批次表。
|
||||
* 核心逻辑:只有停在周汇总 Tab 时组件才挂载;其它 Tab 下次进入会自行加载。
|
||||
*/
|
||||
async function reloadWeeklyBatches(): Promise<void> {
|
||||
await batchesPage.value?.reload();
|
||||
}
|
||||
|
||||
const {
|
||||
isAdmin,
|
||||
actionLoading,
|
||||
@@ -45,7 +56,7 @@ const {
|
||||
run,
|
||||
confirmForceSync,
|
||||
confirmReparseExisting,
|
||||
} = useContractPaymentAdminActions();
|
||||
} = useContractPaymentAdminActions(reloadWeeklyBatches);
|
||||
|
||||
const tabs = computed(() => ([
|
||||
{ key: 'ledger' as const, label: t('admin.contractPayment.ledger') },
|
||||
@@ -258,6 +269,7 @@ watch(
|
||||
/>
|
||||
<ContractPaymentWeeklyBatchesPage
|
||||
v-else
|
||||
ref="batchesPage"
|
||||
class="h-full min-h-0 flex-1"
|
||||
embedded
|
||||
/>
|
||||
|
||||
+62
-8
@@ -3,6 +3,7 @@
|
||||
* 用途:合同付款预警管理员异步任务(同步 / 重解析 / 扫描 / 发送)共用入口。
|
||||
* 依赖:contract-payment.api、useAuthStore、useMessage、i18n。
|
||||
* 逻辑:Chat 顶栏与旧台账页共用;非管理员直接忽略,强制覆盖和存量重解析先走确认框。
|
||||
* 发送预警会等到后台任务结束,再按 sent/failed 提示,并回调刷新周汇总列表。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
@@ -14,14 +15,37 @@ import {
|
||||
enqueueContractPaymentReparse,
|
||||
enqueueContractPaymentSync,
|
||||
enqueueContractPaymentWeeklyAlert,
|
||||
getContractPaymentJob,
|
||||
type ContractPaymentJob,
|
||||
} from '../api/contract-payment.api';
|
||||
|
||||
export type ContractPaymentAdminAction = 'sync' | 'force-sync' | 'reparse-existing' | 'scan' | 'weekly';
|
||||
|
||||
const WEEKLY_JOB_POLL_MS = 1000;
|
||||
const WEEKLY_JOB_TIMEOUT_MS = 90_000;
|
||||
const WEEKLY_JOB_DONE = new Set(['success', 'failed', 'dead', 'cancelled']);
|
||||
|
||||
/**
|
||||
* 轮询周汇总发送任务,直到进入终态或超时。
|
||||
* 核心逻辑:入队接口立即返回,真正的企微发送在 Worker 里;页面不能把「已提交」当成发送完成。
|
||||
* @param jobId - 刚入队的任务主键。
|
||||
* @returns 终态任务;超时返回 null。
|
||||
*/
|
||||
async function waitForWeeklyJob(jobId: number): Promise<ContractPaymentJob | null> {
|
||||
const deadline = Date.now() + WEEKLY_JOB_TIMEOUT_MS;
|
||||
while (Date.now() < deadline) {
|
||||
const job = await getContractPaymentJob(jobId);
|
||||
if (WEEKLY_JOB_DONE.has(job.status)) return job;
|
||||
await new Promise((resolve) => window.setTimeout(resolve, WEEKLY_JOB_POLL_MS));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提供合同付款预警管理员操作状态与提交函数。
|
||||
* 核心逻辑:仅 role=admin 可提交;入队成功只提示任务已提交,不阻塞等待 Worker。
|
||||
* @param onAfterScanOrWeekly - 扫描或发送后刷新本周待发送摘要的回调
|
||||
* 核心逻辑:仅 role=admin 可提交。同步、重解析、扫描入队后即提示已提交。
|
||||
* 发送预警会等到 Worker 结束,先刷新列表,再按 sent/failed 提示。
|
||||
* @param onAfterScanOrWeekly - 扫描提交后或周汇总发送结束后刷新列表的回调
|
||||
*/
|
||||
export function useContractPaymentAdminActions(onAfterScanOrWeekly?: () => Promise<void> | void) {
|
||||
const { t } = useI18n();
|
||||
@@ -32,9 +56,36 @@ export function useContractPaymentAdminActions(onAfterScanOrWeekly?: () => Promi
|
||||
const showForceSyncConfirm = ref(false);
|
||||
const showReparseExistingConfirm = ref(false);
|
||||
|
||||
/**
|
||||
* 按周汇总任务的 sent/failed 给出结果,避免把入队成功说成已经发出。
|
||||
* 核心逻辑:全部失败用错误提示,部分失败用警告,没有待发送记录时说明列表不会变化。
|
||||
* @param job - 已结束的任务;null 表示轮询超时。
|
||||
*/
|
||||
function reportWeeklyJob(job: ContractPaymentJob | null): void {
|
||||
if (!job) {
|
||||
msg.warning(t('admin.contractPayment.weeklyJobTimeout'));
|
||||
return;
|
||||
}
|
||||
if (job.status !== 'success') {
|
||||
msg.error(job.message || t('admin.contractPayment.weeklyJobError'));
|
||||
return;
|
||||
}
|
||||
const sent = Number(job.result?.sent || 0);
|
||||
const failed = Number(job.result?.failed || 0);
|
||||
if (sent > 0 && failed > 0) {
|
||||
msg.warning(t('admin.contractPayment.weeklyJobPartial', { sent, failed }));
|
||||
} else if (failed > 0) {
|
||||
msg.error(t('admin.contractPayment.weeklyJobFailed', { failed }));
|
||||
} else if (sent > 0) {
|
||||
msg.success(t('admin.contractPayment.weeklyJobSent', { sent }));
|
||||
} else {
|
||||
msg.info(t('admin.contractPayment.weeklyJobEmpty'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交合同付款预警后台任务。
|
||||
* 核心逻辑:按操作类型调用相应异步接口;扫描和发送成功后刷新摘要。
|
||||
* 核心逻辑:同步、重解析、扫描入队后立即提示。发送预警先等到 Worker 结束,刷新批次列表,再按发送计数提示。
|
||||
*/
|
||||
async function submitAction(action: ContractPaymentAdminAction): Promise<void> {
|
||||
if (!isAdmin.value) return;
|
||||
@@ -42,16 +93,19 @@ export function useContractPaymentAdminActions(onAfterScanOrWeekly?: () => Promi
|
||||
try {
|
||||
if (action === 'sync' || action === 'force-sync') {
|
||||
await enqueueContractPaymentSync(action === 'force-sync');
|
||||
msg.success(t('admin.contractPayment.jobSubmitted'));
|
||||
} else if (action === 'reparse-existing') {
|
||||
await enqueueContractPaymentReparse();
|
||||
msg.success(t('admin.contractPayment.jobSubmitted'));
|
||||
} else if (action === 'scan') {
|
||||
await enqueueContractPaymentAlertScan();
|
||||
msg.success(t('admin.contractPayment.jobSubmitted'));
|
||||
if (onAfterScanOrWeekly) await onAfterScanOrWeekly();
|
||||
} else {
|
||||
await enqueueContractPaymentWeeklyAlert();
|
||||
}
|
||||
msg.success(t('admin.contractPayment.jobSubmitted'));
|
||||
if ((action === 'scan' || action === 'weekly') && onAfterScanOrWeekly) {
|
||||
await onAfterScanOrWeekly();
|
||||
const queued = await enqueueContractPaymentWeeklyAlert();
|
||||
const job = await waitForWeeklyJob(Number(queued.job_id));
|
||||
if (onAfterScanOrWeekly) await onAfterScanOrWeekly();
|
||||
reportWeeklyJob(job);
|
||||
}
|
||||
} catch (error) {
|
||||
msg.error(error instanceof BusinessError ? error.message : t('admin.contractPayment.actionFailed'));
|
||||
|
||||
@@ -48,13 +48,13 @@ export function nodeDueReference(node: Pick<PaymentNode, 'due_date' | 'anchor_da
|
||||
return node.due_date || node.anchor_date || null;
|
||||
}
|
||||
|
||||
/** 台账级付款状态编码:进行中 / 即将到期 / 已逾期 / 已完成 / 待补充。 */
|
||||
/** 台账级付款状态编码:未到期 / 即将到期 / 已逾期 / 已完成 / 待补充。 */
|
||||
export type ContractNodeStatusCode = 'active' | 'due' | 'overdue' | 'completed' | 'needs_completion';
|
||||
|
||||
/**
|
||||
* 按付款节点聚合出合同台账的进度/逾期状态。
|
||||
* 核心逻辑:先在合同层排除「待补充」(非激活或解析待确认);否则若存在未付且已过 due_date 的
|
||||
* 节点 → 已逾期;存在 7 天内到期 → 即将到期;仍有未付节点 → 进行中;全部节点已付 → 已完成。
|
||||
* 节点 → 已逾期;存在 7 天内到期 → 即将到期;仍有未付且付款日在 7 日外 → 未到期;全部节点已付 → 已完成。
|
||||
* @param nodes - 合同的付款节点列表。
|
||||
* @returns 台账状态编码。
|
||||
*/
|
||||
|
||||
@@ -274,11 +274,11 @@ onMounted(() => void load());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="section-gap animate-fade-in-up">
|
||||
<section class="section-gap contract-detail animate-fade-in-up">
|
||||
<header class="mb-5 flex items-start justify-between gap-3">
|
||||
<div v-if="contract" class="min-w-0">
|
||||
<h2 class="text-2xl font-bold text-primary">{{ contract.contract_no || t('admin.contractPayment.contractNoPending') }}</h2>
|
||||
<p class="mt-1 text-sm text-muted">{{ contract.supplier_name || '—' }}<span v-if="contract.purchase_order_no"> · {{ contract.purchase_order_no }}</span></p>
|
||||
<p class="mt-1 text-sm text-muted">{{ contract.supplier_name || '—' }}</p>
|
||||
</div>
|
||||
<div class="flex shrink-0 gap-2"><button class="btn-secondary-ds" :disabled="reparsing" @click="reparseContract"><RefreshCw class="h-4 w-4" :class="{ 'animate-spin': reparsing }" />{{ t('admin.contractPaymentReparse.action') }}</button><button class="btn-secondary-ds" @click="backToLedger"><ArrowLeft class="h-4 w-4" />{{ t('admin.contractPayment.backToLedger') }}</button></div>
|
||||
</header>
|
||||
@@ -353,7 +353,8 @@ onMounted(() => void load());
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.detail-summary-grid { display: grid; grid-template-columns: repeat(4, minmax(150px, 1fr)); gap: 12px; }.detail-summary-card { min-height: 82px; padding: 14px; border: 1px solid #d7e1ef; border-radius: 12px; background: #f8fbff; }.detail-summary-card span { display: block; color: #58749f; font-size: 12px; }.detail-summary-card strong { display: block; margin-top: 6px; color: #102d59; font-size: 14px; word-break: break-word; }.detail-tabs { display: flex; width: fit-content; max-width: 100%; overflow-x: auto; border: 1px solid #d7e1ef; border-radius: 999px; background: #f1f5fb; padding: 4px; }.detail-tabs button { flex: none; border-radius: 999px; padding: 8px 14px; color: #58749f; font-size: 13px; font-weight: 700; }.detail-tabs button.active { background: #fff; color: #2875d5; box-shadow: 0 1px 3px rgba(35, 68, 113, .12); }.detail-panel { border: 1px dashed #b9cbe2; border-radius: 12px; background: #fff; padding: 18px; }.detail-panel h3 { margin-bottom: 14px; color: #102d59; font-size: 16px; font-weight: 750; }.detail-description-list { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px 28px; }.detail-description-list div { display: flex; gap: 8px; }.detail-description-list dt { color: #58749f; }.detail-description-list dd { color: #102d59; font-weight: 650; }.detail-note { margin-top: 16px; border-radius: 8px; background: #f7faff; padding: 10px 12px; color: #58749f; font-size: 13px; }.attachment-row { display: flex; align-items: center; gap: 12px; border-top: 1px solid #e4ecf6; padding: 13px 0; }.attachment-row:first-of-type { border-top: 0; }.attachment-row span { color: #58749f; font-size: 12px; }.payment-node-row { position: relative; display: flex; gap: 14px; padding: 0 0 18px 6px; }.payment-node-row::before { position: absolute; top: 18px; bottom: -2px; left: 12px; width: 2px; background: #d7e1ef; content: ''; }.payment-node-row:last-child::before { display: none; }.timeline-dot { z-index: 1; width: 14px; height: 14px; margin-top: 8px; flex: none; border-radius: 999px; background: #fff; border: 2px solid #3b82e5; }.payment-node-card { flex: 1; border: 1px solid #d7e1ef; border-radius: 12px; padding: 13px 15px; }.payment-node-card strong { color: #102d59; }.payment-node-card p { margin-top: 5px; color: #58749f; font-size: 13px; }.node-status { display: inline-flex; min-height: 22px; align-items: center; border-radius: 999px; background: #edf5ff; padding: 2px 8px; color: #2563eb; font-size: 12px; font-weight: 700; }.node-alert-list { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; }.node-alert-list span { border-radius: 6px; background: #f7faff; padding: 4px 7px; color: #58749f; font-size: 12px; }.alert-row { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 18px; border-top: 1px solid #e4ecf6; padding: 12px 0; color: #58749f; font-size: 13px; }.alert-row:first-of-type { border-top: 0; }.alert-row strong { color: #102d59; }.detail-empty { padding: 38px; color: var(--text-muted); text-align: center; } @media (max-width: 1280px) { .detail-summary-grid { grid-template-columns: repeat(3, minmax(160px, 1fr)); } } @media (max-width: 640px) { .detail-summary-grid, .detail-description-list { grid-template-columns: 1fr; }.attachment-row { align-items: flex-start; flex-wrap: wrap; }.attachment-row button { margin-left: 32px; } }
|
||||
/* 四张概要卡按详情区域宽度排:够宽时一行,窄于 640px 再折成两行。 */
|
||||
.contract-detail { container-type: inline-size; }.detail-summary-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; }.detail-summary-card { min-width: 0; min-height: 82px; padding: 14px; border: 1px solid #d7e1ef; border-radius: 12px; background: #f8fbff; }.detail-summary-card span { display: block; color: #58749f; font-size: 12px; }.detail-summary-card strong { display: block; margin-top: 6px; color: #102d59; font-size: 14px; word-break: break-word; }.detail-tabs { display: flex; width: fit-content; max-width: 100%; overflow-x: auto; border: 1px solid #d7e1ef; border-radius: 999px; background: #f1f5fb; padding: 4px; }.detail-tabs button { flex: none; border-radius: 999px; padding: 8px 14px; color: #58749f; font-size: 13px; font-weight: 700; }.detail-tabs button.active { background: #fff; color: #2875d5; box-shadow: 0 1px 3px rgba(35, 68, 113, .12); }.detail-panel { border: 1px dashed #b9cbe2; border-radius: 12px; background: #fff; padding: 18px; }.detail-panel h3 { margin-bottom: 14px; color: #102d59; font-size: 16px; font-weight: 750; }.detail-description-list { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px 28px; font-size: 13px; }.detail-description-list div { display: flex; gap: 8px; min-width: 0; }.detail-description-list dt { flex: none; color: #58749f; }.detail-description-list dd { min-width: 0; color: #102d59; font-weight: 650; white-space: nowrap; }.detail-note { margin-top: 16px; border-radius: 8px; background: #f7faff; padding: 10px 12px; color: #58749f; font-size: 13px; }.attachment-row { display: flex; align-items: center; gap: 12px; border-top: 1px solid #e4ecf6; padding: 13px 0; }.attachment-row:first-of-type { border-top: 0; }.attachment-row span { color: #58749f; font-size: 12px; }.payment-node-row { position: relative; display: flex; gap: 14px; padding: 0 0 18px 6px; }.payment-node-row::before { position: absolute; top: 18px; bottom: -2px; left: 12px; width: 2px; background: #d7e1ef; content: ''; }.payment-node-row:last-child::before { display: none; }.timeline-dot { z-index: 1; width: 14px; height: 14px; margin-top: 8px; flex: none; border-radius: 999px; background: #fff; border: 2px solid #3b82e5; }.payment-node-card { flex: 1; border: 1px solid #d7e1ef; border-radius: 12px; padding: 13px 15px; }.payment-node-card strong { color: #102d59; }.payment-node-card p { margin-top: 5px; color: #58749f; font-size: 13px; }.node-status { display: inline-flex; min-height: 22px; align-items: center; border-radius: 999px; background: #edf5ff; padding: 2px 8px; color: #2563eb; font-size: 12px; font-weight: 700; }.node-alert-list { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; }.node-alert-list span { border-radius: 6px; background: #f7faff; padding: 4px 7px; color: #58749f; font-size: 12px; }.alert-row { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 18px; border-top: 1px solid #e4ecf6; padding: 12px 0; color: #58749f; font-size: 13px; }.alert-row:first-of-type { border-top: 0; }.alert-row strong { color: #102d59; }.detail-empty { padding: 38px; color: var(--text-muted); text-align: center; } @container (max-width: 640px) { .detail-summary-grid, .detail-description-list { grid-template-columns: repeat(2, minmax(0, 1fr)); } } @media (max-width: 640px) { .detail-description-list { grid-template-columns: 1fr; }.attachment-row { align-items: flex-start; flex-wrap: wrap; }.attachment-row button { margin-left: 32px; } }
|
||||
.help-label { position: relative; cursor: help; }.help-label::after { position: absolute; z-index: 20; top: calc(100% + 6px); left: 0; width: max-content; max-width: min(280px, 70vw); padding: 7px 9px; border-radius: 6px; background: #334155; color: #fff; content: attr(data-help); font-size: 11px; font-weight: 400; line-height: 1.45; opacity: 0; pointer-events: none; transition: opacity .15s ease; white-space: normal; }.help-label:hover::after { opacity: 1; }.detail-parse-issues { margin-top: 14px; border-radius: 8px; background: #fff7ed; padding: 10px 12px; color: #9a3412; font-size: 13px; }.detail-parse-issues strong { display: block; margin-bottom: 4px; font-weight: 700; }.detail-parse-issues ul { margin: 0; padding-left: 16px; }.detail-parse-issues li { line-height: 1.6; }
|
||||
.timeline-dot.dot-paid, .timeline-dot.dot-current { background: #16a34a; border-color: #16a34a; }.timeline-dot.dot-due { background: #ea580c; border-color: #ea580c; }.timeline-dot.dot-overdue { background: #dc2626; border-color: #dc2626; }.timeline-dot.dot-pending { background: #fff; border-color: #93a7c8; }.timeline-dot.dot-review { background: #f59e0b; border-color: #f59e0b; }.node-status.status-paid { background: #e8f7ee; color: #16a34a; }.node-status.status-current { background: #e8f7ee; color: #16a34a; }.node-status.status-due { background: #fff4e8; color: #ea580c; }.node-status.status-overdue { background: #fee2e2; color: #dc2626; }.node-status.status-pending { background: #eef3fa; color: #5c76a0; }.node-status.status-review { background: #fff7ed; color: #c2410c; }.payment-node-pay-line { margin-top: 6px; color: #102d59; font-weight: 650; }
|
||||
</style>
|
||||
@@ -42,7 +42,7 @@ const page = ref(1); const pageSize = ref(20); const total = ref(0); const pages
|
||||
const ledgerFocusCards = computed(() => ([
|
||||
{ key: 'due' as const, label: t('admin.contractPayment.ledgerFocus.due'), hint: t('admin.contractPayment.ledgerFocus.dueHint'), value: ledgerSummary.value.due, tone: 'due' },
|
||||
{ key: 'overdue' as const, label: t('admin.contractPayment.ledgerFocus.overdue'), hint: '', value: ledgerSummary.value.overdue, tone: 'overdue' },
|
||||
{ key: 'active' as const, label: t('admin.contractPayment.ledgerFocus.active'), hint: '', value: ledgerSummary.value.active, tone: 'in-progress' },
|
||||
{ key: 'active' as const, label: t('admin.contractPayment.ledgerFocus.active'), hint: t('admin.contractPayment.ledgerFocus.activeHint'), value: ledgerSummary.value.active, tone: 'in-progress' },
|
||||
{ key: 'due_this_month' as const, label: t('admin.contractPayment.ledgerFocus.dueThisMonth'), hint: t('admin.contractPayment.ledgerFocus.dueThisMonthHint'), value: ledgerSummary.value.due_this_month, tone: 'month' },
|
||||
]));
|
||||
const stage = (item: ContractPaymentContract, name: string) => item.nodes.find((node) => node.node_type === name);
|
||||
@@ -72,7 +72,7 @@ const paymentCell = (item: ContractPaymentContract, name: string) => {
|
||||
return { amountRatio, date, missingDate: !date };
|
||||
};
|
||||
/**
|
||||
* 按付款节点聚合台账状态:进行中 / 即将到期 / 已逾期 / 已完成 / 待补充。
|
||||
* 按付款节点聚合台账状态:未到期 / 即将到期 / 已逾期 / 已完成 / 待补充。
|
||||
* 核心逻辑:合同层先排除「待补充」(非激活或解析待确认);否则按节点到期/逾期状态取最高优先级展示,
|
||||
* 让台账行一眼看出是否有逾期款。 @param item - 合同台账行。 @returns 状态标签和对应的视觉色调。
|
||||
*/
|
||||
|
||||
+132
-13
@@ -1,13 +1,13 @@
|
||||
<!--
|
||||
features/contract-payment/views/ContractPaymentWeeklyBatchesPage.vue
|
||||
用途:独立展示合同付款预警的周汇总批次及其企业微信发送审计摘要,并下载 Excel 明细。
|
||||
依赖:contract-payment.api、统一消息提示。
|
||||
逻辑:后端扫描产生的批次在此集中查看;Excel 经受控接口下载;Chat 顶栏共用发送入口,本页 embedded 时隐藏页头与发送按钮。
|
||||
嵌入布局仅表格区域滚动,表头 sticky,滚动条常显。
|
||||
依赖:contract-payment.api、统一消息提示、lucide 图标。
|
||||
逻辑:后端扫描产生的批次在此集中查看;Excel 经受控接口下载;发送失败时点击图标查看原因。
|
||||
Chat 顶栏共用发送入口,本页 embedded 时隐藏页头与发送按钮。嵌入布局仅表格区域滚动,表头 sticky,滚动条常显。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { CalendarClock, Download } from 'lucide-vue-next';
|
||||
import { onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { CalendarClock, CircleAlert, Download, X } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { formatLocalDateTime } from '@/shared/utils/dateTime';
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
downloadContractPaymentAlertBatchExcel,
|
||||
listContractPaymentAlertBatches,
|
||||
type AlertBatch,
|
||||
type AlertBatchFailureReason,
|
||||
} from '../api/contract-payment.api';
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
@@ -27,6 +28,7 @@ const msg = useMessage();
|
||||
const batches = ref<AlertBatch[]>([]);
|
||||
const loading = ref(false);
|
||||
const downloadingId = ref<number | null>(null);
|
||||
const failureBatch = ref<AlertBatch | null>(null);
|
||||
|
||||
/**
|
||||
* 加载合同付款周汇总批次列表。
|
||||
@@ -94,16 +96,81 @@ function displayStatus(status?: string | null): string {
|
||||
|
||||
/**
|
||||
* 格式化批次发送时间为用户本地时间的 YYYY-MM-DD HH:mm:ss。
|
||||
* 核心逻辑:发送时间由后端以 UTC 存储(datetime.utcnow),需换算到浏览器时区展示;
|
||||
* 空值回退 '—',非法日期回退原值以便排障。
|
||||
* @param iso - 后端返回的 ISO 发送时间字符串。
|
||||
* @returns 本地时间文本。
|
||||
* 核心逻辑:成功与失败都展示最近一次尝试时间。历史失败批次没有 sent_at 时,回退到批次创建时间。
|
||||
* @param batch - 周汇总批次。
|
||||
* @returns 本地时间文本;两边都空时返回 '—'。
|
||||
*/
|
||||
function displaySentAt(iso?: string | null): string {
|
||||
return iso ? formatLocalDateTime(iso) : '—';
|
||||
function displaySentAt(batch: AlertBatch): string {
|
||||
const iso = batch.sent_at || batch.created_at;
|
||||
if (!iso) return '—';
|
||||
const text = formatLocalDateTime(iso);
|
||||
return text === '-' ? '—' : text;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断批次是否为发送失败,用于展示失败原因图标。
|
||||
* 核心逻辑:只认后端 status=failed,大小写不敏感。
|
||||
* @param status - 批次发送状态。
|
||||
* @returns 是否展示失败原因入口。
|
||||
*/
|
||||
function isFailed(status?: string | null): boolean {
|
||||
return String(status || '').trim().toLowerCase() === 'failed';
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开指定失败批次的原因弹层。
|
||||
* 核心逻辑:原因来自列表接口的 failure_reasons,点击图标时不再额外请求。
|
||||
* @param batch - 当前失败批次。
|
||||
*/
|
||||
function openFailureReason(batch: AlertBatch): void {
|
||||
failureBatch.value = batch;
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭失败原因弹层。
|
||||
* 核心逻辑:清空当前批次即可卸下弹层与 Esc 监听。
|
||||
*/
|
||||
function closeFailureReason(): void {
|
||||
failureBatch.value = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把失败原因编码翻译成当前语言的多行文本。
|
||||
* 核心逻辑:已知 code 走 i18n;有 detail 时拼到标签后;没有任何原因时展示空态文案。
|
||||
* @param batch - 当前失败批次。
|
||||
* @returns 弹层正文。
|
||||
*/
|
||||
function failureReasonText(batch: AlertBatch): string {
|
||||
const reasons = (batch.failure_reasons || []).filter((item): item is AlertBatchFailureReason => Boolean(item?.code || item?.detail));
|
||||
if (!reasons.length) return t('admin.contractPayment.batchFailureReasonEmpty');
|
||||
return reasons.map((item) => {
|
||||
const code = String(item.code || 'unknown').trim() || 'unknown';
|
||||
const key = `admin.contractPayment.batchFailureReasonCode.${code}`;
|
||||
const label = te(key) ? t(key) : t('admin.contractPayment.batchFailureReasonCode.unknown');
|
||||
const detail = String(item.detail || '').trim();
|
||||
return detail ? t('admin.contractPayment.batchFailureReasonLine', { reason: label, detail }) : label;
|
||||
}).join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* 失败原因弹层打开时按 Esc 关闭。
|
||||
* 核心逻辑:只处理 Escape,避免拦截弹层外的其它按键。
|
||||
* @param event - 窗口键盘事件。
|
||||
*/
|
||||
function onFailureKeydown(event: KeyboardEvent): void {
|
||||
if (event.key === 'Escape') closeFailureReason();
|
||||
}
|
||||
|
||||
watch(failureBatch, (batch) => {
|
||||
if (batch) window.addEventListener('keydown', onFailureKeydown);
|
||||
else window.removeEventListener('keydown', onFailureKeydown);
|
||||
});
|
||||
|
||||
onMounted(() => void load());
|
||||
onBeforeUnmount(() => window.removeEventListener('keydown', onFailureKeydown));
|
||||
|
||||
/** 供发送预警完成后重新拉取批次,避免列表停在点击前的状态。 */
|
||||
defineExpose({ reload: load });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -129,7 +196,21 @@ onMounted(() => void load());
|
||||
<tr v-for="batch in batches" :key="batch.id">
|
||||
<td class="font-mono font-semibold text-primary">{{ batch.batch_no || '—' }}</td>
|
||||
<td>{{ batch.week_key || '—' }}</td>
|
||||
<td><span class="batch-status">{{ displayStatus(batch.status) }}</span></td>
|
||||
<td>
|
||||
<span class="batch-status-wrap">
|
||||
<span class="batch-status" :class="{ 'is-failed': isFailed(batch.status) }">{{ displayStatus(batch.status) }}</span>
|
||||
<button
|
||||
v-if="isFailed(batch.status)"
|
||||
class="failure-reason-btn"
|
||||
type="button"
|
||||
:aria-label="t('admin.contractPayment.batchFailureReasonAria')"
|
||||
:title="t('admin.contractPayment.batchFailureReason')"
|
||||
@click.stop="openFailureReason(batch)"
|
||||
>
|
||||
<CircleAlert class="h-4 w-4" />
|
||||
</button>
|
||||
</span>
|
||||
</td>
|
||||
<td>{{ batch.summary?.total || 0 }}</td>
|
||||
<td>
|
||||
<button
|
||||
@@ -145,7 +226,7 @@ onMounted(() => void load());
|
||||
</button>
|
||||
<span v-else class="text-muted">—</span>
|
||||
</td>
|
||||
<td>{{ displaySentAt(batch.sent_at) }}</td>
|
||||
<td>{{ displaySentAt(batch) }}</td>
|
||||
</tr>
|
||||
<tr v-if="!loading && !batches.length">
|
||||
<td colspan="6" class="weekly-batch-empty">
|
||||
@@ -156,6 +237,40 @@ onMounted(() => void load());
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="failureBatch"
|
||||
class="fixed inset-0 z-[80] flex items-center justify-center bg-slate-900/30 p-6"
|
||||
@click.self="closeFailureReason"
|
||||
>
|
||||
<div
|
||||
class="w-full max-w-[420px] rounded-2xl bg-white p-4 text-[#183c72] shadow-[0_18px_50px_rgba(15,23,42,0.18)]"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-label="t('admin.contractPayment.batchFailureReason')"
|
||||
>
|
||||
<div class="flex items-start gap-2.5">
|
||||
<CircleAlert class="mt-0.5 h-5 w-5 shrink-0 text-rose-600" />
|
||||
<div class="min-w-0 flex-1">
|
||||
<h3 class="text-[15px] font-bold leading-snug">{{ t('admin.contractPayment.batchFailureReason') }}</h3>
|
||||
<p class="mt-0.5 break-all font-mono text-xs text-slate-500">{{ failureBatch.batch_no || '—' }}</p>
|
||||
</div>
|
||||
<button
|
||||
class="inline-flex h-7 w-7 items-center justify-center rounded-lg text-slate-500 hover:bg-slate-100 hover:text-slate-900"
|
||||
type="button"
|
||||
:aria-label="t('common.close')"
|
||||
@click="closeFailureReason"
|
||||
>
|
||||
<X class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
<p class="mt-3.5 max-h-60 overflow-auto whitespace-pre-wrap break-words rounded-xl bg-rose-50 px-3.5 py-3 text-[13px] leading-relaxed text-rose-800">
|
||||
{{ failureReasonText(failureBatch) }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
@@ -179,6 +294,10 @@ onMounted(() => void load());
|
||||
.weekly-batch-table tbody tr:last-child td { border-bottom: 0; }
|
||||
.weekly-batch-table tbody tr:hover { background: #fbfdff; }
|
||||
.batch-status { display: inline-flex; min-height: 24px; align-items: center; border-radius: 999px; background: #edf5ff; padding: 2px 9px; color: #2563eb; font-size: 12px; font-weight: 700; }
|
||||
.batch-status.is-failed { background: #fff1f2; color: #e11d48; }
|
||||
.batch-status-wrap { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.failure-reason-btn { display: inline-flex; align-items: center; justify-content: center; width: 22px; height: 22px; margin: 0; border: 0; border-radius: 999px; background: transparent; padding: 0; color: #e11d48; cursor: pointer; }
|
||||
.failure-reason-btn:hover { background: #fff1f2; }
|
||||
.excel-download { display: inline-flex; max-width: 360px; align-items: center; gap: 6px; color: #2563eb; font-weight: 650; }
|
||||
.excel-download:disabled { opacity: .55; }
|
||||
.weekly-batch-empty { padding: 36px !important; color: var(--text-muted); text-align: center; }
|
||||
|
||||
@@ -4811,7 +4811,7 @@
|
||||
}
|
||||
},
|
||||
"contractPayment": {
|
||||
"title": "Contract Payment Alerts", "subtitle": "Sync OA contract, acceptance, and vendor prepayment requests; notify procurement roles through three escalation rounds.", "sessionHint": "Chat and history are hidden in this phase. Use the tabs above to open the ledger.", "sync": "Sync OA data", "moreActions": "More", "forceSync": "Force overwrite OA fields", "forceSyncConfirm": "This will overwrite existing OA data with non-empty fields returned this time and record an audit trail. Continue?", "reparseExisting": "Reparse existing contracts", "reparseExistingConfirm": "This will refresh all existing contract parsing results from archived attachments using the current rules. OA fields will not be synced or overwritten. Continue?", "scanAlerts": "Scan to generate alerts", "jobSubmitted": "Job submitted", "actionFailed": "Action failed", "loadFailed": "Failed to load contracts", "searchPlaceholder": "Search contract number, purchase order, supplier, or applicant", "allStatus": "All", "search": "Search", "ledger": "Contract ledger", "items": "items", "empty": "No contract data", "purchaseOrder": "Purchase order", "supplier": "Supplier", "amount": "Contract amount", "deliveryDate": "Delivery due date", "timeline": "Payment plan timeline", "notAvailable": "—", "stats": {"contracts": "Contracts", "pendingParse": "Pending contracts", "readyPlans": "Plans ready", "alerts": "Alert nodes"}, "ledgerFocus": {"due": "Due soon", "dueHint": "within 7 days", "overdue": "Overdue unpaid", "active": "In progress", "dueThisMonth": "Due this month", "dueThisMonthHint": "this calendar month"}, "status": {"completed": "Completed", "needs_review": "Needs review", "pending": "Pending parse"}, "stateLabel": {"parsed": "Parsed", "needs_review": "Needs review", "pending": "Pending parse", "active": "Active"}, "nodeType": {"prepayment": "Prepayment", "shipment": "Shipment payment", "acceptance": "Acceptance payment", "warranty": "Warranty payment"}, "ruleConfirmed": "Confirmed", "prepaymentRule": "Alerts at 7/14/21 days after contract archival; request status comes from OA vendor prepayment requests.", "shipmentRule": "Alerts 7 days before delivery, on the due date, and 14 days after; request status comes from OA vendor prepayment requests.", "acceptanceRule": "Alerts at 30/40/60 days after acceptance archival; warranty alerts are 7 days before, on, and 14 days after maturity.", "pendingAlerts": "Pending alerts", "processing": "Payment initiated", "dataPending": "Data pending", "paid": "Paid", "amountRatioDate": "Amount / ratio · date", "applicant": "Applicant", "statusLabel": "Status", "contractPrefix": "Contract", "datePending": "Date pending", "statusNormal": "Normal", "statusNeedsCompletion": "Needs completion", "statusOverdue": "Overdue", "statusUpcoming": "Due soon", "statusActive": "In progress", "statusCompleted": "Completed", "totalPrefix": "Total", "contractSupplier": "Contract / supplier", "nextAlert": "Next alert", "triggerBasis": "Trigger basis", "alertDate": "Alert date", "alertFirstRound": "Round 1", "payDate": "Payment date", "processStatus": "Status", "owner": "Procurement owner", "oaData": "OA data", "contractRule": "Contract rule", "ownerDefault": "Procurement owner", "workflowNo": "Workflow number", "contractNoPending": "Contract number pending attachment parsing", "synced": "Synced", "detailSubtitle": "OA data, payment nodes, and WeCom alert records", "backToOverview": "Back to overview", "contractInfo": "OA contract details", "alertHistory": "Alert history", "alertRound": "Alert round {round}", "alertAudit": "Alert delivery record", "alertAuditEmpty": "No alert records", "alertNode": "Payment stage", "alertScheduledAt": "Scheduled date", "alertSentAt": "Sent at", "alertStatus": {"pending": "Pending", "sent": "Sent", "failed": "Failed"}, "roundValue": "Round {round}", "weeklyBatchesTitle": "Weekly Summary Batches", "weeklyBatchesSubtitle": "Review recipient-level payment-alert summaries, Excel attachments, and delivery records.", "weeklySend": "Send alerts", "weeklyBatchSubmitted": "Send alert job submitted", "weeklyBatchesLoadFailed": "Failed to load weekly summary batches", "batchNo": "Batch no.", "weekKey": "Week", "batchStatusLabel": "Delivery status", "batchTotal": "Summary count", "batchExcel": "Excel attachment", "batchSentAt": "Sent at", "weeklyBatchesEmpty": "No weekly summary batches", "weeklyPendingSummary": "{count} pending this week · next send {datetime}", "weeklyPendingCountOnly": "{count} pending this week", "downloadExcel": "Download Excel", "excelDownloadFailed": "Failed to download the alert attachment", "batchStatus": {"pending": "Pending", "sent": "Sent", "failed": "Failed", "processing": "Processing", "resolved": "Alerts stopped"}, "backToLedger": "Back", "detailLoadFailed": "Failed to load contract details", "detailLoading": "Loading contract details…", "detailOverview": "Contract Overview", "detailAttachments": "Original Attachments", "detailPaymentPlan": "Payment Plan", "detailAlertLine truncated
|
||||
"title": "Contract Payment Alerts", "subtitle": "Sync OA contract, acceptance, and vendor prepayment requests; notify procurement roles through three escalation rounds.", "sessionHint": "Chat and history are hidden in this phase. Use the tabs above to open the ledger.", "sync": "Sync OA data", "moreActions": "More", "forceSync": "Force overwrite OA fields", "forceSyncConfirm": "This will overwrite existing OA data with non-empty fields returned this time and record an audit trail. Continue?", "reparseExisting": "Reparse existing contracts", "reparseExistingConfirm": "This will refresh all existing contract parsing results from archived attachments using the current rules. OA fields will not be synced or overwritten. Continue?", "scanAlerts": "Scan to generate alerts", "jobSubmitted": "Job submitted", "actionFailed": "Action failed", "loadFailed": "Failed to load contracts", "searchPlaceholder": "Search contract number, purchase order, supplier, or applicant", "allStatus": "All", "search": "Search", "ledger": "Contract ledger", "items": "items", "empty": "No contract data", "purchaseOrder": "Purchase order", "supplier": "Supplier", "amount": "Contract amount", "deliveryDate": "Delivery due date", "timeline": "Payment plan timeline", "notAvailable": "—", "stats": {"contracts": "Contracts", "pendingParse": "Pending contracts", "readyPlans": "Plans ready", "alerts": "Alert nodes"}, "ledgerFocus": {"due": "Due soon", "dueHint": "within 7 days", "overdue": "Overdue unpaid", "active": "Not yet due", "activeHint": "beyond 7 days", "dueThisMonth": "Due this month", "dueThisMonthHint": "this calendar month"}, "status": {"completed": "Completed", "needs_review": "Needs review", "pending": "Pending parse"}, "stateLabel": {"parsed": "Parsed", "needs_review": "Needs review", "pending": "Pending parse", "active": "Active"}, "nodeType": {"prepayment": "Prepayment", "shipment": "Shipment payment", "acceptance": "Acceptance payment", "warranty": "Warranty payment"}, "ruleConfirmed": "Confirmed", "prepaymentRule": "Alerts at 7/14/21 days after contract archival; request status comes from OA vendor prepayment requests.", "shipmentRule": "Alerts 7 days before delivery, on the due date, and 14 days after; request status comes from OA vendor prepayment requests.", "acceptanceRule": "Alerts at 30/40/60 days after acceptance archival; warranty alerts are 7 days before, on, and 14 days after maturity.", "pendingAlerts": "Pending alerts", "processing": "Payment initiated", "dataPending": "Data pending", "paid": "Paid", "amountRatioDate": "Amount / ratio · date", "applicant": "Applicant", "statusLabel": "Status", "contractPrefix": "Contract", "datePending": "Date pending", "statusNormal": "Normal", "statusNeedsCompletion": "Needs completion", "statusOverdue": "Overdue", "statusUpcoming": "Due soon", "statusActive": "Not yet due", "statusCompleted": "Completed", "totalPrefix": "Total", "contractSupplier": "Contract / supplier", "nextAlert": "Next alert", "triggerBasis": "Trigger basis", "alertDate": "Alert date", "alertFirstRound": "Round 1", "payDate": "Payment date", "processStatus": "Status", "owner": "Procurement owner", "oaData": "OA data", "contractRule": "Contract rule", "ownerDefault": "Procurement owner", "workflowNo": "Workflow number", "contractNoPending": "Contract number pending attachment parsing", "synced": "Synced", "detailSubtitle": "OA data, payment nodes, and WeCom alert records", "backToOverview": "Back to overview", "contractInfo": "OA contract details", "alertHistory": "Alert history", "alertRound": "Alert round {round}", "alertAudit": "Alert delivery record", "alertAuditEmpty": "No alert records", "alertNode": "Payment stage", "alertScheduledAt": "Scheduled date", "alertSentAt": "Sent at", "alertStatus": {"pending": "Pending", "sent": "Sent", "failed": "Failed"}, "roundValue": "Round {round}", "weeklyBatchesTitle": "Weekly Summary Batches", "weeklyBatchesSubtitle": "Review recipient-level payment-alert summaries, Excel attachments, and delivery records.", "weeklySend": "Send alerts", "weeklyBatchSubmitted": "Send alert job submitted", "weeklyJobSent": "Sent {sent} batch(es)", "weeklyJobFailed": "{failed} batch(es) failed. The list has been refreshed; open the failure icon for the reason.", "weeklyJobPartial": "Sent {sent} batch(es); {failed} failed", "weeklyJobEmpty": "There are no pending alerts, so the batch list will not change", "weeklyJobTimeout": "The send task is still running in the background. Reopen this page later to see the result.", "weeklyJobError": "The send task failed", "weeklyBatchesLoadFailed": "Failed to load weekly summary batches", "batchNo": "Batch no.", "weekKey": "Week", "batchStatusLabel": "Delivery status", "batchFailureReason": "Failure reason", "batchFailureReasonEmpty": "No specific failure reason was recorded", "batchFailureReasonAria": "View the send failure reason", "batchFailureReasonLine": "{reason}: {detail}", "batchFailureReasonCode": {"notify_disabled": "WeCom notificLine truncated
|
||||
},
|
||||
"contractPaymentReview": {"title": "Contracts for Confirmation", "subtitle": "Contracts that do not match the equipment procurement synonym title groups, fail payment-ratio validation, or conflict with OA fields are excluded from payment alerts. Download the original contract to verify it.", "searchPlaceholder": "Contract number, purchase order, supplier, or applicant", "loadFailed": "Failed to load contracts for confirmation", "contractWorkflow": "Contract / workflow number", "reason": "Reason for confirmation", "fallbackIssue": "Parsing result requires manual confirmation", "empty": "No contracts need confirmation"},
|
||||
"contractPaymentReparse": {"action": "Reparse contract original", "success": "Reparsed with attachment “{attachment}”", "failed": "Failed to reparse contract"},
|
||||
|
||||
@@ -135,6 +135,7 @@
|
||||
"CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED": "Too many attachments (maximum 200). Remove some and try again.",
|
||||
"CONTRACT_PAYMENT_FORBIDDEN": "You do not have access to contract payment alerts.",
|
||||
"CONTRACT_PAYMENT_ADMIN_REQUIRED": "Only administrators can sync, scan, or send contract payment alerts.",
|
||||
"CONTRACT_PAYMENT_ATTACHMENT_UNAVAILABLE": "The contract file was removed and could not be downloaded again from the source system. Sync OA data and try again.",
|
||||
"VOUCHER_CHECK_FORBIDDEN": "You do not have access to accounting voucher check.",
|
||||
"VOUCHER_CHECK_ADMIN_REQUIRED": "Only administrators can force a voucher recheck or change missing-file notification recipients.",
|
||||
"SHIPPING_TASK_SELECTION_INVALID": "Select between 1 and 100 shipping tasks.",
|
||||
|
||||
@@ -4680,7 +4680,7 @@
|
||||
}
|
||||
},
|
||||
"contractPayment": {
|
||||
"title": "แจ้งเตือนการชำระเงินตามสัญญา", "subtitle": "ซิงก์สัญญา OA การรับมอบ และคำขอเบิกเงินล่วงหน้าของผู้ขาย พร้อมแจ้งเตือน 3 ระดับ", "sessionHint": "ระยะนี้ยังไม่ใช้แชทและประวัติการสนทนา เปิดบัญชีจากแท็บด้านบน", "sync": "ซิงก์ข้อมูล OA", "moreActions": "เพิ่มเติม", "forceSync": "เขียนทับฟิลด์ OA แบบบังคับ", "forceSyncConfirm": "ระบบจะเขียนทับข้อมูล OA เดิมด้วยฟิลด์ที่ไม่ว่างจาก OA ครั้งนี้และบันทึกการตรวจสอบ ต้องการดำเนินการต่อหรือไม่?", "reparseExisting": "แยกวิเคราะห์สัญญาเดิมทั้งหมดใหม่", "reparseExistingConfirm": "ระบบจะรีเฟรชผลการแยกข้อมูลของสัญญาเดิมทั้งหมดจากไฟล์แนบที่จัดเก็บตามกฎปัจจุบัน โดยจะไม่ซิงก์หรือเขียนทับฟิลด์ OA ต้องการดำเนินการต่อหรือไม่?", "scanAlerts": "สแกนเพื่อสร้างแจ้งเตือน", "jobSubmitted": "ส่งงานแล้ว", "actionFailed": "ดำเนินการไม่สำเร็จ", "loadFailed": "โหลดสัญญาไม่สำเร็จ", "searchPlaceholder": "ค้นหาเลขที่สัญญา ใบสั่งซื้อ ผู้ขาย หรือผู้ขอ", "allStatus": "ทั้งหมด", "search": "ค้นหา", "ledger": "ทะเบียนสัญญา", "items": "รายการ", "empty": "ไม่มีข้อมูลสัญญา", "purchaseOrder": "ใบสั่งซื้อ", "supplier": "ผู้ขาย", "amount": "มูลค่าสัญญา", "deliveryDate": "กำหนดส่งมอบ", "timeline": "ไทม์ไลน์แผนการชำระเงิน", "notAvailable": "—", "stats": {"contracts": "สัญญา", "pendingParse": "สัญญาที่รอดำเนินการ", "readyPlans": "แผนพร้อมใช้", "alerts": "จุดแจ้งเตือน"}, "ledgerFocus": {"due": "ใกล้ครบกำหนด", "dueHint": "ใน 7 วัน", "overdue": "ค้างชำระเกินกำหนด", "active": "กำลังดำเนินการ", "dueThisMonth": "ถึงกำหนดเดือนนี้", "dueThisMonthHint": "เดือนปฏิทินนี้"}, "status": {"completed": "เสร็จสิ้น", "needs_review": "ต้องตรวจสอบ", "pending": "รอแยกข้อมูล"}, "stateLabel": {"parsed": "แยกข้อมูลแล้ว", "needs_review": "ต้องตรวจสอบ", "pending": "รอแยกข้อมูล", "active": "ใช้งานอยู่"}, "nodeType": {"prepayment": "เงินล่วงหน้า", "shipment": "เงินก่อนส่ง", "acceptance": "เงินรับมอบ", "warranty": "เงินประกัน"}, "ruleConfirmed": "ยืนยันแล้ว", "prepaymentRule": "แจ้งเตือนวันที่ 7/14/21 หลังจัดเก็บสัญญา; สถานะคำขออ้างอิง OA.", "shipmentRule": "แจ้งเตือนก่อนกำหนดส่ง 7 วัน วันครบกำหนด และหลังครบกำหนด 14 วัน; สถานะคำขออ้างอิง OA.", "acceptanceRule": "แจ้งเตือนวันที่ 30/40/60 หลังจัดเก็บใบรับมอบ; เงินประกันแจ้งก่อนครบกำหนด 7 วัน วันครบกำหนด และหลังครบกำหนด 14 วัน.", "pendingAlerts": "แจ้งเตือนที่รอดำเนินการ", "processing": "เริ่มชำระแล้ว", "dataPending": "รอข้อมูล", "paid": "ชำระแล้ว", "amountRatioDate": "จำนวนเงิน / สัดส่วน · วันที่", "applicant": "ผู้ขอ", "statusLabel": "สถานะ", "contractPrefix": "สัญญา", "datePending": "รอระบุวันที่", "statusNormal": "ปกติ", "statLine truncated
|
||||
"title": "แจ้งเตือนการชำระเงินตามสัญญา", "subtitle": "ซิงก์สัญญา OA การรับมอบ และคำขอเบิกเงินล่วงหน้าของผู้ขาย พร้อมแจ้งเตือน 3 ระดับ", "sessionHint": "ระยะนี้ยังไม่ใช้แชทและประวัติการสนทนา เปิดบัญชีจากแท็บด้านบน", "sync": "ซิงก์ข้อมูล OA", "moreActions": "เพิ่มเติม", "forceSync": "เขียนทับฟิลด์ OA แบบบังคับ", "forceSyncConfirm": "ระบบจะเขียนทับข้อมูล OA เดิมด้วยฟิลด์ที่ไม่ว่างจาก OA ครั้งนี้และบันทึกการตรวจสอบ ต้องการดำเนินการต่อหรือไม่?", "reparseExisting": "แยกวิเคราะห์สัญญาเดิมทั้งหมดใหม่", "reparseExistingConfirm": "ระบบจะรีเฟรชผลการแยกข้อมูลของสัญญาเดิมทั้งหมดจากไฟล์แนบที่จัดเก็บตามกฎปัจจุบัน โดยจะไม่ซิงก์หรือเขียนทับฟิลด์ OA ต้องการดำเนินการต่อหรือไม่?", "scanAlerts": "สแกนเพื่อสร้างแจ้งเตือน", "jobSubmitted": "ส่งงานแล้ว", "actionFailed": "ดำเนินการไม่สำเร็จ", "loadFailed": "โหลดสัญญาไม่สำเร็จ", "searchPlaceholder": "ค้นหาเลขที่สัญญา ใบสั่งซื้อ ผู้ขาย หรือผู้ขอ", "allStatus": "ทั้งหมด", "search": "ค้นหา", "ledger": "ทะเบียนสัญญา", "items": "รายการ", "empty": "ไม่มีข้อมูลสัญญา", "purchaseOrder": "ใบสั่งซื้อ", "supplier": "ผู้ขาย", "amount": "มูลค่าสัญญา", "deliveryDate": "กำหนดส่งมอบ", "timeline": "ไทม์ไลน์แผนการชำระเงิน", "notAvailable": "—", "stats": {"contracts": "สัญญา", "pendingParse": "สัญญาที่รอดำเนินการ", "readyPlans": "แผนพร้อมใช้", "alerts": "จุดแจ้งเตือน"}, "ledgerFocus": {"due": "ใกล้ครบกำหนด", "dueHint": "ใน 7 วัน", "overdue": "ค้างชำระเกินกำหนด", "active": "ยังไม่ถึงกำหนด", "activeHint": "เกิน 7 วัน", "dueThisMonth": "ถึงกำหนดเดือนนี้", "dueThisMonthHint": "เดือนปฏิทินนี้"}, "status": {"completed": "เสร็จสิ้น", "needs_review": "ต้องตรวจสอบ", "pending": "รอแยกข้อมูล"}, "stateLabel": {"parsed": "แยกข้อมูลแล้ว", "needs_review": "ต้องตรวจสอบ", "pending": "รอแยกข้อมูล", "active": "ใช้งานอยู่"}, "nodeType": {"prepayment": "เงินล่วงหน้า", "shipment": "เงินก่อนส่ง", "acceptance": "เงินรับมอบ", "warranty": "เงินประกัน"}, "ruleConfirmed": "ยืนยันแล้ว", "prepaymentRule": "แจ้งเตือนวันที่ 7/14/21 หลังจัดเก็บสัญญา; สถานะคำขออ้างอิง OA.", "shipmentRule": "แจ้งเตือนก่อนกำหนดส่ง 7 วัน วันครบกำหนด และหลังครบกำหนด 14 วัน; สถานะคำขออ้างอิง OA.", "acceptanceRule": "แจ้งเตือนวันที่ 30/40/60 หลังจัดเก็บใบรับมอบ; เงินประกันแจ้งก่อนครบกำหนด 7 วัน วันครบกำหนด และหลังครบกำหนด 14 วัน.", "pendingAlerts": "แจ้งเตือนที่รอดำเนินการ", "processing": "เริ่มชำระแล้ว", "dataPending": "รอข้อมูล", "paid": "ชำระแล้ว", "amountRatioDate": "จำนวนเงิน / สัดส่วน · วันที่", "applicant": "ผู้ขอ", "statusLabel": "สถานะ", "contractPrefix": "สัญญา", "datePending": "รอระบุวันทีLine truncated
|
||||
},
|
||||
"contractPaymentReview": {"title": "สัญญาที่รอยืนยัน", "subtitle": "สัญญาที่ไม่ตรงกับกลุ่มหัวข้อคำพ้องของสัญญาจัดซื้ออุปกรณ์ ตรวจสอบสัดส่วนการชำระเงินไม่ผ่าน หรือขัดแย้งกับฟิลด์ OA จะไม่เข้าสู่การแจ้งเตือนการชำระเงิน โปรดดาวน์โหลดต้นฉบับเพื่อตรวจสอบ", "searchPlaceholder": "เลขที่สัญญา ใบสั่งซื้อ ผู้ขาย หรือผู้ขอ", "loadFailed": "โหลดสัญญาที่รอยืนยันไม่สำเร็จ", "contractWorkflow": "เลขที่สัญญา / เวิร์กโฟลว์", "reason": "เหตุผลที่ต้องยืนยัน", "fallbackIssue": "ผลการแยกข้อมูลต้องยืนยันโดยผู้ใช้", "empty": "ไม่มีสัญญาที่รอยืนยัน"},
|
||||
"contractPaymentReparse": {"action": "แยกข้อมูลจากต้นฉบับอีกครั้ง", "success": "แยกข้อมูลใหม่ด้วยไฟล์แนบ “{attachment}” แล้ว", "failed": "แยกข้อมูลสัญญาใหม่ไม่สำเร็จ"},
|
||||
|
||||
@@ -135,6 +135,7 @@
|
||||
"CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED": "ไฟล์แนบเกินจำนวนที่อนุญาต (สูงสุด 200 ไฟล์) โปรดลดจำนวนแล้วลองใหม่",
|
||||
"CONTRACT_PAYMENT_FORBIDDEN": "คุณไม่มีสิทธิ์เข้าถึงการแจ้งเตือนการชำระเงินตามสัญญา",
|
||||
"CONTRACT_PAYMENT_ADMIN_REQUIRED": "เฉพาะผู้ดูแลระบบเท่านั้นที่ซิงก์ สแกน หรือส่งการแจ้งเตือนการชำระเงินตามสัญญาได้",
|
||||
"CONTRACT_PAYMENT_ATTACHMENT_UNAVAILABLE": "ไฟล์ต้นฉบับของสัญญาถูกลบไปแล้ว และไม่สามารถดาวน์โหลดใหม่จากระบบต้นทางได้ โปรดซิงก์ข้อมูล OA แล้วลองอีกครั้ง",
|
||||
"VOUCHER_CHECK_FORBIDDEN": "คุณไม่มีสิทธิ์เข้าถึงการตรวจเอกสารบัญชี",
|
||||
"VOUCHER_CHECK_ADMIN_REQUIRED": "เฉพาะผู้ดูแลระบบเท่านั้นที่บังคับตรวจเอกสารบัญชีใหม่ หรือแก้ผู้รับการแจ้งเตือนไฟล์ขาดได้",
|
||||
"SHIPPING_TASK_SELECTION_INVALID": "เลือกงานจัดส่งได้ 1 ถึง 100 งาน",
|
||||
|
||||
@@ -4822,15 +4822,15 @@
|
||||
"timeline": "付款计划时间线",
|
||||
"notAvailable": "—",
|
||||
"stats": {"contracts": "合同总数", "pendingParse": "待处理合同", "readyPlans": "计划已生成", "alerts": "待预警节点"},
|
||||
"ledgerFocus": {"due": "即将到期", "dueHint": "7日内", "overdue": "逾期未付", "active": "进行中", "dueThisMonth": "本月应付", "dueThisMonthHint": "本自然月"},
|
||||
"ledgerFocus": {"due": "即将到期", "dueHint": "7日内", "overdue": "逾期未付", "active": "未到期", "activeHint": "7日外", "dueThisMonth": "本月应付", "dueThisMonthHint": "本自然月"},
|
||||
"status": {"completed": "已完成", "needs_review": "待复核", "pending": "待解析"}, "stateLabel": {"parsed": "已解析", "needs_review": "待复核", "pending": "待解析", "active": "已生效"},
|
||||
"nodeType": {"prepayment": "预付款", "shipment": "出货款", "acceptance": "验收款", "warranty": "质保款"},
|
||||
"ruleConfirmed": "已确定",
|
||||
"prepaymentRule": "合同归档后第 7/14/21 天预警;请款以 OA 厂商预付款请款作业为准。",
|
||||
"shipmentRule": "交货期限前 7 天、到期日、到期后 14 天预警;请款以 OA 厂商预付款请款作业为准。",
|
||||
"acceptanceRule": "验收归档后第 30/40/60 天预警;质保款在质保到期前 7 天、到期日、到期后 14 天预警。",
|
||||
"pendingAlerts": "待处理预警", "processing": "已发起付款", "dataPending": "数据待确认", "paid": "已付款", "amountRatioDate": "金额 / 比例 · 日期", "applicant": "申请人", "statusLabel": "状态", "contractPrefix": "合同", "datePending": "待补充日期", "statusNormal": "正常", "statusNeedsCompletion": "待补充", "statusOverdue": "已逾期", "statusUpcoming": "即将到期", "statusActive": "进行中", "statusCompleted": "已完成",
|
||||
"totalPrefix": "共", "contractSupplier": "合同号 / 供应商", "nextAlert": "下一预警", "triggerBasis": "触发依据", "alertDate": "预警日期", "alertFirstRound": "首轮", "payDate": "付款日期", "processStatus": "处理状态", "owner": "采购负责人", "oaData": "OA 数据", "contractRule": "合同规则", "ownerDefault": "采购负责人", "workflowNo": "流程编号", "contractNoPending": "合同号待从附件解析", "synced": "已同步", "detailSubtitle": "OA 数据、付款节点与企业微信提醒记录", "backToOverview": "返回总览", "contractInfo": "OA 合同信息", "alertHistory": "预警记录", "alertRound": "第 {round} 次预警", "alertAudit": "预警发送记录", "alertAuditEmpty": "暂无预警记录", "alertNode": "付款节点", "alertScheduledAt": "计划日期", "alertSentAt": "发送时间", "alertStatus": {"pending": "待发送", "sent": "已发送", "failed": "发送失败"}, "roundValue": "第 {round} 次", "weeklyBatchesTitle": "周汇总批次", "weeklyBatchesSubtitle": "查看按收件人生成的付款预警周汇总、Excel 附件及发送记录。", "weeklySend": "发送预警", "weeklyBatchSubmitted": "发送预警任务已提交", "weeklyBatchesLoadFailed": "加载周汇总批次失败", "batchNo": "批次号", "weekKey": "周次", "batchStatusLabel": "发送状态", "batchTotal": "汇总笔数", "batchExcel": "Excel 附件", "batchSentAt": "发送时间", "weeklyBatchesEmpty": "暂无周汇总批次", "weeklyPendingSummary": "本周待发送 {count} 笔 · 下次发送 {datetime}", "weeklyPendingCountOnly": "本周待发送 {count} 笔", "downloadExcel": "下载 Excel", "excelDownloadFailed": "下载预警附件失败", "batchStatus": {"pending": "待发送", "sent": "已发送", "failed": "发送失败", "processing": "处理中", "resolved": "已停止提醒"}, "backToLedger": "返回", "detailLoadFailed": "加载合同详情失败", "detailLoading": "正在加载合同详情…", "detailOverview": "合同概览", "detailAttachments": "原文附件", "detailPaymentPlan": "付款计划", "detailAlertHistory": "预警记录", "archiveDate": "合同归档日期", "archiveDateHint": "该日期为合同申请单的归档日期", "parseStatus": "解析状态", "parseIssueTitle": "解析提示", "planStatus": "计划状态", "attachmentsEmpty": "暂无已归档的合同原文附件", "downloadAttachment": "下载附件", "attachmentDownloadFailed": "下载合同附件失败", "paymentPlanEmpty": "暂无可展示的付款计划", "anchorDate": "日期依据", "nodeStatus": {"pending": "待处理", "active": "进行中", "paid": "已付", "processing": "处理中", "resolved": "已停止提醒", "upcoming": "即将到期", "notStarted": "待起算", "overdue": "已逾期", "review": "待复核"}, "reparse": "重新解析合同原文", "reparseSuccess": "已使用附件“{attachment}”重新解析", "reparseFailed": "重新解析合同失败", "reviewTitle": "待确认合同", "reviewSubtitle": "未匹配设备采购合同同义标题组、付款比例校验失败或关键字段冲突的合同不会进入付款预警,请下载原文核对。", "reviewSearchPlaceholder": "合同编号、采购编号或供应商", "reviewLoadFailed": "待确认合同加载失败", "reviewContractWorkflow": "合同号 / 流程编号", "reviewReason": "待确认原因", "reviewFallbackIssue": "解析结果待人工确认", "reviewEmpty": "暂无待确认合同"
|
||||
"pendingAlerts": "待处理预警", "processing": "已发起付款", "dataPending": "数据待确认", "paid": "已付款", "amountRatioDate": "金额 / 比例 · 日期", "applicant": "申请人", "statusLabel": "状态", "contractPrefix": "合同", "datePending": "待补充日期", "statusNormal": "正常", "statusNeedsCompletion": "待补充", "statusOverdue": "已逾期", "statusUpcoming": "即将到期", "statusActive": "未到期", "statusCompleted": "已完成",
|
||||
"totalPrefix": "共", "contractSupplier": "合同号 / 供应商", "nextAlert": "下一预警", "triggerBasis": "触发依据", "alertDate": "预警日期", "alertFirstRound": "首轮", "payDate": "付款日期", "processStatus": "处理状态", "owner": "采购负责人", "oaData": "OA 数据", "contractRule": "合同规则", "ownerDefault": "采购负责人", "workflowNo": "流程编号", "contractNoPending": "合同号待从附件解析", "synced": "已同步", "detailSubtitle": "OA 数据、付款节点与企业微信提醒记录", "backToOverview": "返回总览", "contractInfo": "OA 合同信息", "alertHistory": "预警记录", "alertRound": "第 {round} 次预警", "alertAudit": "预警发送记录", "alertAuditEmpty": "暂无预警记录", "alertNode": "付款节点", "alertScheduledAt": "计划日期", "alertSentAt": "发送时间", "alertStatus": {"pending": "待发送", "sent": "已发送", "failed": "发送失败"}, "roundValue": "第 {round} 次", "weeklyBatchesTitle": "周汇总批次", "weeklyBatchesSubtitle": "查看按收件人生成的付款预警周汇总、Excel 附件及发送记录。", "weeklySend": "发送预警", "weeklyBatchSubmitted": "发送预警任务已提交", "weeklyJobSent": "已发送 {sent} 个批次", "weeklyJobFailed": "{failed} 个批次发送失败,列表已更新,可点击失败图标查看原因", "weeklyJobPartial": "已发送 {sent} 个批次,另有 {failed} 个失败", "weeklyJobEmpty": "没有待发送的预警,批次记录不会变化", "weeklyJobTimeout": "发送任务仍在后台执行,请稍后重新打开本页查看", "weeklyJobError": "发送任务执行失败", "weeklyBatchesLoadFailed": "加载周汇总批次失败", "batchNo": "批次号", "weekKey": "周次", "batchStatusLabel": "发送状态", "batchFailureReason": "失败原因", "batchFailureReasonEmpty": "未记录具体失败原因", "batchFailureReasonAria": "查看发送失败原因", "batchFailureReasonLine": "{reason}:{detail}", "batchFailureReasonCode": {"notify_disabled": "企业微信通知未启用", "event_disabled": "合同付款预警通知事件未启用", "user_unbound": "收件人未绑定企业微信账号", "textcard_failed": "企业微信卡片发送失败", "file_upload_failed": "企业微信附件上传失败", "file_failed": "企业微信附件发送失败", "unknown": "发送失败"}, "batchTotal": "汇总笔数", "batchExcel": "Excel 附件", "batchSentAt": "发送时间", "weeklyBatchesEmpty": "暂无周汇总批次", "weeklyPendingSummary": "本周待发送 {count} 笔 · 下次发送 {datetime}", "weeklyPendingCountOnly": "本周待发送 {count} 笔", "downloadExcel": "下载 Excel", "excelDownloadFailed": "下载预警附件失败", "batchStatus": {"pending": "待发送", "sent": "已发送", "failed": "发送失败", "processing": "处理中", "resolved": "已停止提醒"}, "backToLedger": "返回", "detailLoadFailed": "加载合同详情失败", "detailLoading": "正在加载合同详情…", "detailOverview": "合同概览", "detailAttachments": "原文附件", "detailPaymentPlan": "付款计划", "detailAlertHistory": "预警记录", "archiveDate": "合同归档日期", "archiveDateHint": "该日期为合同申请单的归档日期", "parseStatus": "解析状态", "parseIssueTitle": "解析提示", "planStatus": "计划状态", "attachmentsEmpty": "暂无已归档的合同原文附件", "downloadAttachment": "下载附件", "attachmentDownloadFailed": "下载合同附件失败", "paymentPlanEmpty": "暂无可展示的付款计划", "anchorDate": "日期依据", "nodeStatus": {"pending": "待处理", "active": "进行中", "paid": "已付", "processing": "处理中", "resolved": "已停止提醒", "upcoming": "即将到期", "notStarted": "待起算", "overdue": "已逾期", "review": "待复核"}, "reparse": "重新解析合同原文", "reparseSuccess": "已使用附件“{attachment}”重新解析", "reparseFailed": "重新解析合同失败", "reviewTitle": "待确认合同", "reviewSubtitle": "未匹配设备采购合同同义标题组、付款比例校验失败或关键字段冲突的合同不会进入付款预警,请下载原文核对。", "reviewSearchPlaceholder": "合同编号、采购编号或供应商", "reviewLoadFailed": "待确认合同加载失败", "reviewContractWorkflow": "合同号 / 流程编号", "reviewReason": "待确认原因", "reviewFallbackIssue": "解析结果待人工确认", "reviewEmpty": "暂无待确认合同"
|
||||
},
|
||||
"contractPaymentReview": {"title": "待确认合同", "subtitle": "未匹配设备采购合同同义标题组、付款比例校验失败或关键字段冲突的合同不会进入付款预警,请下载原文核对。", "searchPlaceholder": "合同编号、采购编号、供应商或申请人", "loadFailed": "待确认合同加载失败", "contractWorkflow": "合同号 / 流程编号", "reason": "待确认原因", "fallbackIssue": "解析结果待人工确认", "empty": "暂无待确认合同"},
|
||||
"contractPaymentReparse": {"action": "重新解析合同原文", "success": "已使用附件“{attachment}”重新解析", "failed": "重新解析合同失败"},
|
||||
|
||||
@@ -135,6 +135,7 @@
|
||||
"CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED": "附件数量超过上限(最多 200 个),请减少后重试。",
|
||||
"CONTRACT_PAYMENT_FORBIDDEN": "你没有合同付款预警的访问权限。",
|
||||
"CONTRACT_PAYMENT_ADMIN_REQUIRED": "仅管理员可执行合同付款预警的同步、扫描或发送操作。",
|
||||
"CONTRACT_PAYMENT_ATTACHMENT_UNAVAILABLE": "合同原文已被清理,且无法从原系统重新下载。请先同步 OA 数据后再试。",
|
||||
"VOUCHER_CHECK_FORBIDDEN": "你没有立账凭证检核的访问权限。",
|
||||
"VOUCHER_CHECK_ADMIN_REQUIRED": "仅管理员可强制重检或修改立账凭证通知配置。",
|
||||
"SHIPPING_TASK_SELECTION_INVALID": "请选择 1 到 100 个发货任务。",
|
||||
|
||||
@@ -4685,7 +4685,7 @@
|
||||
}
|
||||
},
|
||||
"contractPayment": {
|
||||
"title": "合約付款預警", "subtitle": "同步 OA 合約、驗收和廠商預付款請款作業,按三輪規則通知採購職位", "sessionHint": "本期不使用對話和歷史會話,請從上方 Tab 查看台帳。", "sync": "同步 OA 資料", "moreActions": "更多", "forceSync": "強制覆蓋 OA 欄位", "forceSyncConfirm": "將以本次 OA 回傳的非空欄位覆蓋既有 OA 資料,並記錄變更稽核。是否繼續?", "reparseExisting": "批量重新解析既有合約", "reparseExistingConfirm": "將使用已歸檔的合約附件依目前規則更新所有既有合約的解析結果,不會同步或覆蓋 OA 欄位。是否繼續?", "scanAlerts": "掃描產生預警", "jobSubmitted": "工作已提交", "actionFailed": "操作失敗", "loadFailed": "載入合約失敗", "searchPlaceholder": "搜尋合約編號、採購單號、供應商或申請人", "allStatus": "全部", "search": "查詢", "ledger": "合約台帳", "items": "筆", "empty": "暫無合約資料", "purchaseOrder": "採購單號", "supplier": "供應商", "amount": "合約金額", "deliveryDate": "交貨期限", "timeline": "付款計畫時間線", "notAvailable": "—", "stats": {"contracts": "合約總數", "pendingParse": "待處理合約", "readyPlans": "計畫已產生", "alerts": "待預警節點"}, "ledgerFocus": {"due": "即將到期", "dueHint": "7日內", "overdue": "逾期未付", "active": "進行中", "dueThisMonth": "本月應付", "dueThisMonthHint": "本自然月"}, "status": {"completed": "已完成", "needs_review": "待覆核", "pending": "待解析"}, "stateLabel": {"parsed": "已解析", "needs_review": "待複核", "pending": "待解析", "active": "已生效"}, "nodeType": {"prepayment": "預付款", "shipment": "出貨款", "acceptance": "驗收款", "warranty": "質保款"}, "ruleConfirmed": "已確定", "prepaymentRule": "合約歸檔後第 7/14/21 天預警;請款以 OA 廠商預付款請款作業為準。", "shipmentRule": "交貨期限前 7 天、到期日、到期後 14 天預警;請款以 OA 廠商預付款請款作業為準。", "acceptanceRule": "驗收歸檔後第 30/40/60 天預警;質保款在質保到期前 7 天、到期日、到期後 14 天預警。", "pendingAlerts": "待處理預警", "processing": "已發起付款", "dataPending": "資料待確認", "paid": "已付款", "amountRatioDate": "金額 / 比例 · 日期", "applicant": "申請人", "statusLabel": "狀態", "contractPrefix": "合約", "datePending": "待補充日期", "statusNormal": "正常", "statusNeedsCompletion": "待補充", "statusOverdue": "已逾期", "statusUpcoming": "即將到期", "statusActive": "進行中", "statusCompleted": "已完成", "totalPrefix": "共", "contractSupplier": "合約號 / 供應商", "nextAlert": "下一預警", "triggerBasis": "觸發依據", "alertDate": "預警日期", "alertFirstRound": "首輪", "payDate": "付款日期", "processStatus": "處理狀態", "owner": "採購負責人", "oaData": "OA 資料", "contractRule": "合約規則", "ownerDefault": "採購負責人", "workflowNo": "流程編號", "contractNoPending": "合約號待從附件解析", "synced": "已同步", "detailSubtitle": "OA 資料、付款節點與企業微信提醒記錄", "backToOverview": "返回總覽", "contractInfo": "OA 合約資訊", "alertHistory": "預警記錄", "alertRound": "第 {round} 次預警", "alertAudit": "預警發送記錄", "alertAuditEmpty": "暫無預警記錄", "alertNode": "付款節點", "alertScheduledAt": "計畫日期", "alertSentAt": "發送時間", "alertStatus": {"pending": "待發送", "sent": "已發送", "failed": "發送失敗"}, "roundValue": "第 {round} 次", "weeklyBatchesTitle": "週彙總批次", "weeklyBatchesSubtitle": "查看依收件人產生的付款預警週彙總、Excel 附件與發送記錄。", "weeklySend": "傳送預警", "weeklyBatchSubmitted": "發送預警任務已提交", "weeklyBatchesLoadFailed": "載入週彙總批次失敗", "batchNo": "批次號", "weekKey": "週次", "batchStatusLabel": "發送狀態", "batchTotal": "彙總筆數", "batchExcel": "Excel 附件", "batchSentAt": "發送時間", "weeklyBatchesEmpty": "暫無週彙總批次", "weeklyPendingSummary": "本週待發送 {count} 筆 · 下次發送 {datetime}", "weeklyPendingCountOnly": "本週待發送 {count} 筆", "downloadExcel": "下載 Excel", "excelDownloadFailed": "下載預警附件失敗", "batchStatus": {"pending": "待發送", "sent": "已發送", "failed": "發送失敗", "processing": "處理中", "resolved": "已停止提醒"}, "backToLedger": "返回", "detailLoadFailed": "載入合約詳情失敗", "detailLoading": "正在載入合約詳情…", "detailOverview": "合約概覽", "detailAttachments": "原文附件", "detailPaymentPlan": "付款計畫", "detailAlertHistory": "預警記錄", "archiveDate": "合約歸檔日期", "archiveDateHint": "該日期為合約申請單的歸檔日期", "parseStatus": "解析狀態", "parseIssueTitle": "解析提示", "Line truncated
|
||||
"title": "合約付款預警", "subtitle": "同步 OA 合約、驗收和廠商預付款請款作業,按三輪規則通知採購職位", "sessionHint": "本期不使用對話和歷史會話,請從上方 Tab 查看台帳。", "sync": "同步 OA 資料", "moreActions": "更多", "forceSync": "強制覆蓋 OA 欄位", "forceSyncConfirm": "將以本次 OA 回傳的非空欄位覆蓋既有 OA 資料,並記錄變更稽核。是否繼續?", "reparseExisting": "批量重新解析既有合約", "reparseExistingConfirm": "將使用已歸檔的合約附件依目前規則更新所有既有合約的解析結果,不會同步或覆蓋 OA 欄位。是否繼續?", "scanAlerts": "掃描產生預警", "jobSubmitted": "工作已提交", "actionFailed": "操作失敗", "loadFailed": "載入合約失敗", "searchPlaceholder": "搜尋合約編號、採購單號、供應商或申請人", "allStatus": "全部", "search": "查詢", "ledger": "合約台帳", "items": "筆", "empty": "暫無合約資料", "purchaseOrder": "採購單號", "supplier": "供應商", "amount": "合約金額", "deliveryDate": "交貨期限", "timeline": "付款計畫時間線", "notAvailable": "—", "stats": {"contracts": "合約總數", "pendingParse": "待處理合約", "readyPlans": "計畫已產生", "alerts": "待預警節點"}, "ledgerFocus": {"due": "即將到期", "dueHint": "7日內", "overdue": "逾期未付", "active": "未到期", "activeHint": "7日外", "dueThisMonth": "本月應付", "dueThisMonthHint": "本自然月"}, "status": {"completed": "已完成", "needs_review": "待覆核", "pending": "待解析"}, "stateLabel": {"parsed": "已解析", "needs_review": "待複核", "pending": "待解析", "active": "已生效"}, "nodeType": {"prepayment": "預付款", "shipment": "出貨款", "acceptance": "驗收款", "warranty": "質保款"}, "ruleConfirmed": "已確定", "prepaymentRule": "合約歸檔後第 7/14/21 天預警;請款以 OA 廠商預付款請款作業為準。", "shipmentRule": "交貨期限前 7 天、到期日、到期後 14 天預警;請款以 OA 廠商預付款請款作業為準。", "acceptanceRule": "驗收歸檔後第 30/40/60 天預警;質保款在質保到期前 7 天、到期日、到期後 14 天預警。", "pendingAlerts": "待處理預警", "processing": "已發起付款", "dataPending": "資料待確認", "paid": "已付款", "amountRatioDate": "金額 / 比例 · 日期", "applicant": "申請人", "statusLabel": "狀態", "contractPrefix": "合約", "datePending": "待補充日期", "statusNormal": "正常", "statusNeedsCompletion": "待補充", "statusOverdue": "已逾期", "statusUpcoming": "即將到期", "statusActive": "未到期", "statusCompleted": "已完成", "totalPrefix": "共", "contractSupplier": "合約號 / 供應商", "nextAlert": "下一預警", "triggerBasis": "觸發依據", "alertDate": "預警日期", "alertFirstRound": "首輪", "payDate": "付款日期", "processStatus": "處理狀態", "owner": "採購負責人", "oaData": "OA 資料", "contractRule": "合約規則", "ownerDefault": "採購負責人", "workflowNo": "流程編號", "contractNoPending": "合約號待從附件解析", "synced": "已同步", "detailSubtitle": "OA 資料、付款節點與企業微信提醒記錄", "backToOverview": "返回總覽", "contractInfo": "OA 合約資訊", "alertHistory": "預警記錄", "alertRound": "第 {round} 次預警", "alertAudit": "預警發送記錄", "alertAuditEmpty": "暫無預警記錄", "alertNode": "付款節點", "alertScheduledAt": "計畫日期", "alertSentAt": "發送時間", "alertStatus": {"pending": "待發送", "sent": "已發送", "failed": "發送失敗"}, "roundValue": "第 {round} 次", "weeklyBatchesTitle": "週彙總批次", "weeklyBatchesSubtitle": "查看依收件人產生的付款預警週彙總、Excel 附件與發送記錄。", "weeklySend": "傳送預警", "weeklyBatchSubmitted": "發送預警任務已提交", "weeklyJobSent": "已發送 {sent} 個批次", "weeklyJobFailed": "{failed} 個批次發送失敗,列表已更新,可點擊失敗圖示查看原因", "weeklyJobPartial": "已發送 {sent} 個批次,另有 {failed} 個失敗", "weeklyJobEmpty": "沒有待發送的預警,批次記錄不會變化", "weeklyJobTimeout": "發送任務仍在背景執行,請稍後重新開啟本頁查看", "weeklyJobError": "發送任務執行失敗", "weeklyBatchesLoadFailed": "載入週彙總批次失敗", "batchNo": "批次號", "weekKey": "週次", "batchStatusLabel": "發送狀態", "batchFailureReason": "失敗原因", "batchFailureReasonEmpty": "未記錄具體失敗原因", "batchFailureReasonAria": "查看發送失敗原因", "batchFailureReasonLine": "{reason}:{detail}", "batchFailureReasonCode": {"notify_disabled": "企業微信通知未啟用", "event_disabled": "合約付款預警通知事件未啟用", "user_unbound": "收件人未綁定企業微信帳號", "textcard_failed": "企業微信卡片發送失敗", "file_upload_failed": "企業微Line truncated
|
||||
},
|
||||
"contractPaymentReview": {"title": "待確認合約", "subtitle": "未符合設備採購合約同義標題組、付款比例驗證失敗或關鍵欄位衝突的合約,不會進入付款預警,請下載原文核對。", "searchPlaceholder": "合約編號、採購單號、供應商或申請人", "loadFailed": "待確認合約載入失敗", "contractWorkflow": "合約號 / 流程編號", "reason": "待確認原因", "fallbackIssue": "解析結果待人工確認", "empty": "暫無待確認合約"},
|
||||
"contractPaymentReparse": {"action": "重新解析合約原文", "success": "已使用附件“{attachment}”重新解析", "failed": "重新解析合約失敗"},
|
||||
|
||||
@@ -135,6 +135,7 @@
|
||||
"CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED": "附件數量超過上限(最多 200 個),請減少後重試。",
|
||||
"CONTRACT_PAYMENT_FORBIDDEN": "你沒有合約付款預警的存取權限。",
|
||||
"CONTRACT_PAYMENT_ADMIN_REQUIRED": "僅管理員可執行合約付款預警的同步、掃描或發送操作。",
|
||||
"CONTRACT_PAYMENT_ATTACHMENT_UNAVAILABLE": "合約原文已被清理,且無法從原系統重新下載。請先同步 OA 資料後再試。",
|
||||
"VOUCHER_CHECK_FORBIDDEN": "你沒有立帳憑證檢核的存取權限。",
|
||||
"VOUCHER_CHECK_ADMIN_REQUIRED": "僅管理員可強制重檢或修改立帳憑證通知設定。",
|
||||
"SHIPPING_TASK_SELECTION_INVALID": "請選擇 1 到 100 個發貨任務。",
|
||||
|
||||
Reference in new issue
Block a user