Merge branch 'invoice-check' into dev

This commit is contained in:
sophie committed 2026-09-16 08:44:42 +08:00
commit ef6bc42c20
67 files changed
+5207 -248

No files matched your search

+3 -1
View File
@@ -103,12 +103,14 @@ def create_app(config_name='default'):
try:
from app.services.voucher_check.schedule_seed import (
ensure_default_voucher_check_schedule,
ensure_default_voucher_po_print_schedule,
register_voucher_check_schedule_hooks,
)
register_voucher_check_schedule_hooks()
ensure_default_voucher_check_schedule()
ensure_default_voucher_po_print_schedule()
except Exception as exc: # pragma: no cover - 表未就绪时容忍
logger.warning('Failed to ensure accounting-voucher-check schedule: %s', exc)
logger.warning('Failed to ensure accounting-voucher-check / po-print schedules: %s', exc)
try:
from app.services.contract_payment.schedule_seed import ensure_default_contract_payment_schedules
ensure_default_contract_payment_schedules()
+14 -4
View File
@@ -1,9 +1,9 @@
"""
backend/app/api/workspace/voucher_check.py
用途:工作台立账凭证检核查询与强制重检 API(任务列表 / 批次明细 / 企微发送记录)。
用途:工作台立账凭证检核查询与强制重检 API(任务列表 / 最近一次检核 / 批次明细 / 企微发送记录)。
依赖:auth.jwt、response_utils envelope、voucher_check.query_service。
逻辑:对话与检核任务页共用;GET notifications 为企微发送记录;POST runs 仅 admin,以 force_all 入队周批排程。
逻辑:对话与检核任务页共用;GET runs/latest 不跟筛选;GET notifications 为企微发送记录;POST runs 仅 admin,以 force_all 入队周批排程。
"""
from __future__ import annotations
@@ -37,7 +37,7 @@ def _require_admin():
def workspace_voucher_runs():
"""
分页查看检核任务列表。
核心逻辑:委托 query_service.list_runs,按资料所属期间/业务方/状态筛选。
核心逻辑:委托 query_service.list_runs;period 为 YYYY 或 YYYY-MM,可再按业务方/状态筛选。
"""
_require_user()
data = query_service.list_runs(
@@ -69,6 +69,16 @@ def workspace_voucher_force_run():
return ok(data)
@workspace_voucher_check_bp.route("/accounting-voucher-check/runs/latest", methods=["GET"])
def workspace_voucher_latest_run():
"""
读取最近一次立账凭证检核批次(含排队/执行中)。
核心逻辑:委托 query_service.get_latest_run;不跟列表 period/status;无批次时 data 为 null。
"""
_require_user()
return ok(query_service.get_latest_run())
@workspace_voucher_check_bp.route("/accounting-voucher-check/runs/<int:run_id>/items", methods=["GET"])
def workspace_voucher_run_items(run_id: int):
"""
@@ -89,7 +99,7 @@ def workspace_voucher_run_items(run_id: int):
def workspace_voucher_notifications():
"""
分页查看企微缺件汇总发送记录。
核心逻辑:委托 query_service.list_notifications,可按期间和发送状态筛选。
核心逻辑:委托 query_service.list_notifications;period 为 YYYY 或 YYYY-MM,可再按发送状态筛选。
"""
_require_user()
data = query_service.list_notifications(
+40 -2
View File
@@ -2,7 +2,7 @@
backend/app/services/schedule/job_registry.py
用途:平台内置排程 Job Registry(任务契约中心:key → handler + 展示信息 + params_schema + defaults)。
依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、job_params。
依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、voucher_po_print_job、job_params。
逻辑:internal_jobs API 与 platform_job 排程通过 platform_api_path 引用已注册 key;
api/schedule/platform_tasks.py 下发 params_schema 供前端 DynamicTaskParamsForm 通用渲染。
"""
@@ -140,11 +140,12 @@ def _register_builtin_platform_jobs() -> None:
run_shipping_post_ot_auto_fulfill_compensation_schedule,
)
from app.services.schedule.voucher_check_job import run_voucher_check_schedule
from app.services.schedule.voucher_po_print_job import run_voucher_po_print_schedule
from app.services.schedule.contract_payment_job import (
run_contract_payment_alert_schedule,
run_contract_payment_sync_schedule,
)
from app.services.voucher_check.config import DEFAULT_JOB_PARAMS
from app.services.voucher_check.config import DEFAULT_JOB_PARAMS, DEFAULT_PO_PRINT_JOB_PARAMS
from app.services.schedule.contract_payment_job import (
run_contract_payment_alert_schedule,
run_contract_payment_sync_schedule,
@@ -388,6 +389,43 @@ def _register_builtin_platform_jobs() -> None:
),
defaults=dict(DEFAULT_JOB_PARAMS),
))
register_platform_job(PlatformJobDefinition(
key="accounting-voucher-po-print",
label="立账凭证 PO 订单生成",
label_key="admin.schedule.form.platformJobAccountingVoucherPoPrint",
handler=run_voucher_po_print_schedule,
description="每周二 05:00 按上月发票从 TGHX 取数,生成制式采购单 PDF 并上传到「PO订单」;早于 06:00 检核周批。",
description_key="admin.schedule.form.accountingVoucherPoPrintHint",
category="finance",
params_schema=(
{
"key": "scope_code",
"type": "select",
"label": "账套",
"label_key": "admin.schedule.form.voucherCheckScope",
"required": True,
"default": "HXJM",
"options": [{"value": "HXJM", "label": "HXJM"}],
},
{
"key": "profile_code",
"type": "text",
"label": "业务方 Profile",
"label_key": "admin.schedule.form.voucherCheckProfile",
"required": True,
"default": "sales",
},
{
"key": "notify_failure_enabled",
"type": "boolean",
"label": "失败告警",
"label_key": "admin.schedule.form.voucherCheckNotifyFailure",
"required": False,
"default": True,
},
),
defaults=dict(DEFAULT_PO_PRINT_JOB_PARAMS),
))
register_platform_job(PlatformJobDefinition(
key="in-transit-receipt-file",
label="在途收料文件抓取",
@@ -0,0 +1,20 @@
"""
backend/app/services/schedule/voucher_po_print_job.py
用途:立账凭证 PO 订单生成 platform_job 薄封装。
依赖:voucher_check.po_print_runner。
逻辑:job_registry 注册 accounting-voucher-po-print 后由 schedule worker 调用;早于检核周批。
"""
from __future__ import annotations
from app.models import ScheduleRun, ScheduleTask
from app.services.voucher_check.po_print_runner import ScheduleExecuteResult, run_po_print_batch
def run_voucher_po_print_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
执行立账凭证 PO 订单生成排程。
核心逻辑:委托 po_print_runner;默认周二 05:00,检核周批 06:00 只扫目录。
"""
return run_po_print_batch(task, run)
@@ -1,9 +1,9 @@
"""
backend/app/services/voucher_check/adapters/__init__.py
用途:登记销售一期 Adapter(主体、目录扫描、PO/OA 占位、归档占位)。
依赖:各 adapter 模块。
逻辑:import 本包即完成 register_adapter;runner 只通过 registry 取实例。
用途:登记销售一期 Adapter(主体、目录扫描、PO 取数、OA 占位、归档)。
依赖:各 adapter 模块;PO 制式 PDF 在 voucher_check.po_order;ERP 取数在 erp_po_repository。
逻辑:import 本包即完成 register_adapter;runner 只通过 registry 取实例,不调用 erp_po_print.fetch。
"""
from app.services.voucher_check.adapters.base import (
@@ -80,7 +80,7 @@ class DirectoryScanAdapter(Protocol):
class AcquireAdapter(Protocol):
"""把外部单据打印后写入类型目录;PO / 销货放行单一期仅占位。"""
"""把外部单据打印后写入类型目录;PO 制式 PDF 见 po_order,ERP 取数见 erp_po_repository。"""
source_type: str
wired: bool
@@ -88,7 +88,7 @@ class AcquireAdapter(Protocol):
def fetch(self, *, period_month: date, subjects: list[SubjectRow]) -> list[ScannedFile]:
"""
获取并落入类型目录。
【AI 触发时机】仅当独立抓取任务启用且 Adapter.wired=True 时调用;周任务不调用。
【AI 触发时机】仅当 Adapter.wired=True 且独立抓取走本方法时调用;周任务不调用。PO 独立抓取请用 ErpPoPrintAdapter.fetch_documents,不要走 fetch。
"""
...
@@ -1,32 +1,39 @@
"""
backend/app/services/voucher_check/adapters/erp_po_print.py
用途:ERP 反查 PO 并打印 PDF 写入「PO订单」类型目录的占位 Adapter。
依赖:adapters.base。
逻辑:查询/打印方式待确认,周任务不调用;独立抓取任务启用前 wired=False。
用途:ERP 反查 PO 后写入「PO订单」类型目录的 Adapter。
依赖:adapters.base、erp_po_repository、voucher_check.po_order。
逻辑:fetch_documents / publish_for_invoices 由独立排程 accounting-voucher-po-print(周二 05:00)调用。
fetch() 仍占位,检核 runner(周二 06:00)不调用。render_given 只出本地 PDF。
"""
from __future__ import annotations
from datetime import date
from pathlib import Path
from typing import TYPE_CHECKING, Any, Mapping, Sequence
from app.core.errors import ServiceUnavailableError
from app.services.voucher_check.adapters.base import ScannedFile, SubjectRow
if TYPE_CHECKING:
from app.services.voucher_check.config import VoucherCheckEngineConfig
from app.services.voucher_check.po_order import PoOrderDocument, PoOrderPublishResult
class ErpPoPrintAdapter:
"""PO 打印占位;未接线时禁止生成假 PDF。"""
"""PO 获取:ERP 取数与上传已就绪;周检核 fetch 仍不启用。"""
source_type = "erp_po_print"
wired = False
def fetch(self, *, period_month: date, subjects: list[SubjectRow]) -> list[ScannedFile]:
"""
预留:按 invoice 反查 PO 并打印到类型目录。
【AI 触发时机】仅当独立「抓取 PO」任务上线后调用,不要在周检核 runner 中调用。
周检核入口仍关闭。
【AI 触发时机】不要在周二检核 runner 中调用。独立抓取排程请用 fetch_documents / publish_for_invoices。
"""
raise ServiceUnavailableError(
"ERP PO 打印尚未接线",
"ERP PO 打印尚未接入周检核",
code="VOUCHER_CHECK.ADAPTER_NOT_WIRED",
details={
"adapter": self.source_type,
@@ -34,3 +41,65 @@ class ErpPoPrintAdapter:
"subject_count": len(subjects),
},
)
def fetch_documents(
self,
invoice_nos: Sequence[str],
*,
config: VoucherCheckEngineConfig | None = None,
) -> list[PoOrderDocument]:
"""
按发票号从 ERP 组装制式采购单数据。
【AI 触发时机】独立抓取 PO、已有 invoice 清单时调用;检核 runner 不要调用。周二 05:00 排程走本方法。
"""
from app.services.voucher_check.config import load_engine_config
from app.services.voucher_check.erp_po_repository import fetch_po_documents_for_invoices
engine = config if config is not None else load_engine_config()
return fetch_po_documents_for_invoices(engine, invoice_nos)
def render_given(
self,
document: PoOrderDocument | Mapping[str, Any],
output_dir: str | Path,
*,
overwrite: bool = True,
) -> Path:
"""
根据给定采购单数据生成 `{invoice}-{订单号}.pdf` 到本地目录。
【AI 触发时机】只需核对版式、不上传文档库时调用。
"""
from app.services.voucher_check.po_order import save_po_order_pdf
return save_po_order_pdf(document, output_dir, overwrite=overwrite)
def upload_given(
self,
document: PoOrderDocument | Mapping[str, Any],
*,
period_month: date,
) -> PoOrderPublishResult:
"""
生成制式 PDF 并上传到销售开票附件/{年}/{月}/PO订单/。
【AI 触发时机】已拿到 invoice 与 PO 字段、需要写入文档库类型目录时调用。
同名跳过;不要在周检核 runner 中调用。
"""
from app.services.voucher_check.po_order import publish_po_order_pdf
return publish_po_order_pdf(document, period_month=period_month)
def publish_for_invoices(
self,
invoice_nos: Sequence[str],
*,
period_month: date,
config: VoucherCheckEngineConfig | None = None,
) -> list[PoOrderPublishResult]:
"""
按发票号查 ERP、生成 PDF 并上传到当月「PO订单」目录。
【AI 触发时机】独立抓取任务要写入文档库时调用;检核 runner 不要调用。周二 05:00 排程走本方法。
"""
results: list[PoOrderPublishResult] = []
for document in self.fetch_documents(invoice_nos, config=config):
results.append(self.upload_given(document, period_month=period_month))
return results
@@ -1,9 +1,9 @@
"""
backend/app/services/voucher_check/adapters/hxjm_apa_subject.py
用途:从 HXJM apa_file 拉取上一个月销售 invoice 清单。
用途:从 HXJM oma_file 拉取上一个月销售 invoice 清单。
依赖:erp_repository.fetch_month_invoices、fingerprint。
逻辑:周任务 subject_adapter=hxjm_apa;期间由 erp_repository 按上月计算。
逻辑:周任务 subject_adapter=hxjm_apa(历史注册名,实际查 oma_file);期间由 erp_repository 按上月计算。
"""
from __future__ import annotations
@@ -17,14 +17,14 @@ from app.services.voucher_check.fingerprint import build_material_fingerprint
class HxjmApaSubjectAdapter:
"""HXJM apa08/apa09 主体 Adapter。"""
"""HXJM oma_file 主体 Adapter(注册名 hxjm_apa,查询 oma10/oma02 及确认/作废/状况/类别过滤)。"""
source_type = "hxjm_apa"
def fetch(self, *, period_month: date, config: Any) -> list[SubjectRow]:
"""
查询上月发票号集合并生成主体指纹。
核心逻辑:委托 fetch_month_invoices;返回期间必须与传入 period_month 一致。
查询上月已确认且未作废的发票号集合并生成主体指纹。
核心逻辑:委托 fetch_month_invoices(oma_file.oma10/oma02,确认/未作废/状况码 1/类别 11-13);返回期间必须与传入 period_month 一致。
Args:
period_month: 检核月首日,由 runner 预先算好。
+8 -2
View File
@@ -1,9 +1,9 @@
"""
backend/app/services/voucher_check/config.py
用途:解析立账凭证检核环境变量与 ScheduleTask.job_params。
用途:解析立账凭证检核 / PO 生成环境变量与 ScheduleTask.job_params。
依赖:Flask current_app.config、core.errors.ValidationError。
逻辑:runner / erp_repository / 引擎启动前调用;非法配置抛 VOUCHER_CHECK.CONFIG_INVALID;
逻辑:runner / po_print_runner / erp_repository 启动前调用;非法配置抛 VOUCHER_CHECK.CONFIG_INVALID;
ERP 账号优先 VOUCHER_CHECK_ERP_*,否则 ERP_*,再回退 CONTRACT_PAYMENT_ERP_*。
"""
@@ -24,6 +24,12 @@ DEFAULT_JOB_PARAMS: dict[str, Any] = {
"notify_failure_enabled": True,
}
DEFAULT_PO_PRINT_JOB_PARAMS: dict[str, Any] = {
"profile_code": "sales",
"scope_code": "HXJM",
"notify_failure_enabled": True,
}
@dataclass(frozen=True)
class VoucherCheckEngineConfig:
@@ -1,9 +1,9 @@
"""
backend/app/services/voucher_check/dms_client.py
用途:销售开票附件文档库客户端(登录、列目录、建文件夹、复制;不移动原件)。
用途:销售开票附件文档库客户端(登录、列目录、建文件夹、上传、复制;不移动原件)。
依赖:requests、Flask 配置;登录接口与合同库相同。
逻辑:LibraryID 复用文档库;根 FolderID 必须是销售开票附件。归档复制策略为同名跳过。
逻辑:LibraryID 复用文档库;根 FolderID 必须是销售开票附件。上传走 Attachment/Upload + Item/CreateFiles;归档复制同名跳过。
"""
from __future__ import annotations
@@ -11,6 +11,7 @@ from __future__ import annotations
import threading
import time
from datetime import date
from pathlib import Path
from typing import Any
import requests
@@ -178,9 +179,44 @@ class SalesDmsClient:
raise ServiceUnavailableError(
data.get("Msg") or failure_message,
code=failure_code,
details={"dms_data": data.get("Data")} if data.get("Data") not in (None, "", {}) else {},
)
return data
@classmethod
def _post_multipart(
cls,
path: str,
*,
files: dict[str, Any],
data: dict[str, Any] | None = None,
timeout: int = 60,
failure_code: str = "VOUCHER_CHECK.DMS_UNAVAILABLE",
failure_message: str = "文档库上传失败",
) -> dict[str, Any]:
"""
POST multipart 到现网 DMS(用于附件 Upload)。
核心逻辑:不手工设 Content-Type,交给 requests 带 boundary;401/403 刷新会话后重试。
"""
url = f"{cls.base_url()}{path}"
try:
session = cls._session()
response = session.post(url, files=files, data=data or {}, timeout=timeout)
if response.status_code in {401, 403}:
session = cls._session(refresh=True)
response = session.post(url, files=files, data=data or {}, timeout=timeout)
response.raise_for_status()
payload = response.json()
except (requests.RequestException, ValueError) as exc:
raise ServiceUnavailableError(failure_message, code=failure_code) from exc
if int(payload.get("Code") or 0) != 0:
raise ServiceUnavailableError(
payload.get("Msg") or failure_message,
code=failure_code,
details={"dms_data": payload.get("Data")} if payload.get("Data") not in (None, "", {}) else {},
)
return payload
@classmethod
def page(cls, *, parent_folder_id: str, leaf_name: str = "", recursion: bool = False) -> list[dict[str, Any]]:
"""
@@ -400,3 +436,144 @@ class SalesDmsClient:
details={"leaf_name": wanted},
)
return dest_row, False
@classmethod
def ensure_period_type_folder(cls, *, period_month: date, type_folder: str) -> str:
"""
确保销售开票附件/{yyyy}/{MM}/{类型目录} 存在并返回 FolderID。
【AI 触发时机】要把新生成的 PO PDF 写入类型目录时调用;年/月/类型目录没有就建。
Args:
period_month: 检核月份(用年、月两位目录名)。
type_folder: 类型目录名,销售 PO 固定为「PO订单」。
"""
wanted = str(type_folder or "").strip()
if not wanted:
raise ValidationError("类型目录名不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
cls.ensure_configured()
root = cls.root_folder_id()
year_id = cls.ensure_folder(parent_folder_id=root, leaf_name=f"{period_month.year:04d}")
month_id = cls.ensure_folder(parent_folder_id=year_id, leaf_name=f"{period_month.month:02d}")
return cls.ensure_folder(parent_folder_id=month_id, leaf_name=wanted)
@classmethod
def upload_attachment(cls, *, filename: str, content: bytes) -> dict[str, Any]:
"""
把文件二进制上传为未入目录的附件,返回 Data(须含 ID)。
核心逻辑:现网「新建文件」先 Upload 附件,再 CreateFiles 挂到文件夹。
"""
name = str(filename or "").strip()
if not name:
raise ValidationError("上传文件名不能为空", code="VOUCHER_CHECK.PO_PDF_INVALID")
if not content:
raise ValidationError("上传文件内容不能为空", code="VOUCHER_CHECK.PO_PDF_INVALID")
payload = cls._post_multipart(
"/Api/_api/DMS/Public/Attachment/Upload",
files={"file": (name, content, "application/pdf")},
timeout=120,
failure_code="VOUCHER_CHECK.PO_UPLOAD_FAILED",
failure_message="文档库上传附件失败",
)
data = payload.get("Data")
if not isinstance(data, dict) or not str(data.get("ID") or "").strip():
raise ServiceUnavailableError(
"文档库上传附件后未返回 AttachmentID",
code="VOUCHER_CHECK.PO_UPLOAD_FAILED",
)
return data
@classmethod
def create_files(
cls,
*,
parent_folder_id: str,
files: list[dict[str, Any]],
) -> dict[str, Any]:
"""
把已上传附件登记到指定文件夹(现网 functionCreationFile)。
核心逻辑:POST Item/CreateFiles;Files[].AttachmentID 来自 Attachment/Upload。
"""
dest = str(parent_folder_id or "").strip()
if not dest:
raise ValidationError("上传目标文件夹不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
if not files:
raise ValidationError("上传文件列表不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
return cls._post_json(
"/Api/_api/APS/Public/Item/CreateFiles",
{
"LibraryID": cls.library_id(),
"CategoryID": "",
"ParentFolderID": dest,
"Files": files,
"TermID": [],
"CheckedOutState": 0,
"CheckedOutMemo": "",
},
timeout=60,
failure_code="VOUCHER_CHECK.PO_UPLOAD_FAILED",
failure_message="文档库创建文件失败",
)
@classmethod
def upload_file_skip_same_name(
cls,
*,
parent_folder_id: str,
leaf_name: str,
content: bytes,
) -> tuple[dict[str, Any], bool]:
"""
上传文件到类型目录;目标已有同名则跳过、不覆盖。
核心逻辑:先 Page 查 LeafName;没有则 Upload 附件再 CreateFiles。CreateFiles 报同名视为跳过。
"""
wanted = str(leaf_name or "").strip()
dest = str(parent_folder_id or "").strip()
if not dest:
raise ValidationError("上传目标文件夹不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
if not wanted:
raise ValidationError("上传文件名不能为空", code="VOUCHER_CHECK.PO_PDF_INVALID")
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
if existing:
return existing, True
attachment = cls.upload_attachment(filename=wanted, content=content)
extension = str(attachment.get("Extension") or Path(wanted).suffix or ".pdf").strip()
if extension and not extension.startswith("."):
extension = f".{extension}"
file_row = {
"LeafName": wanted,
"AttachmentID": str(attachment.get("ID") or "").strip(),
"CheckedOutState": 0,
"CheckedOutMemo": "",
"Extension": extension,
"FieldValues": [],
}
try:
cls.create_files(parent_folder_id=dest, files=[file_row])
except ServiceUnavailableError as exc:
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
if existing:
return existing, True
same_names = ((exc.details or {}).get("dms_data") or {}).get("SameLeafNames") or []
if same_names or _is_name_conflict(exc.message):
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
if existing:
return existing, True
raise
dest_row = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
if dest_row:
return dest_row, False
# 部分现网 CreateFiles 后 LeafName 不含扩展名,再按无后缀查一次。
stem = Path(wanted).stem
dest_row = cls.find_child_file(parent_folder_id=dest, leaf_name=stem)
if dest_row:
return dest_row, False
raise ServiceUnavailableError(
"上传成功但类型目录未找到同名文件",
code="VOUCHER_CHECK.PO_UPLOAD_FAILED",
details={"leaf_name": wanted},
)
@@ -0,0 +1,464 @@
"""
backend/app/services/voucher_check/erp_po_repository.py
用途:按销售发票从 HXJM.oma99 对 TGHX.pmm99,取出制式采购单字段。
依赖:erp_repository.open_erp_connection、po_order.models、voucher_check.config。
逻辑:独立抓取任务调用;不进周二 runner。oma99 为空时用 oma16 走 oga99(12/13)或 oea99(11)。
"""
from __future__ import annotations
from collections import defaultdict
from dataclasses import dataclass
from datetime import date, datetime
from decimal import ROUND_HALF_UP, Decimal
from typing import Any, Iterable, Mapping, Sequence
from app.core.errors import ServiceUnavailableError
from app.services.voucher_check.config import VoucherCheckEngineConfig
from app.services.voucher_check.erp_repository import _erp_unavailable, is_sales_invoice_no, open_erp_connection
from app.services.voucher_check.po_order.models import PoOrderDocument, PoOrderLine
INVOICE_SCHEMA = "HXJM"
PO_SCHEMA = "TGHX"
_BATCH_SIZE = 80
_TA_IMA02 = {"1": "无卤", "2": "不管控"}
_TA_IMA03 = {"1": "RoHS", "0": "非环保", "9": "ERS"}
@dataclass(frozen=True)
class InvoiceFlow:
"""一张发票对应的多角流程序号。"""
invoice_no: str
flow_no: str
oma00: str = ""
oma16: str = ""
def _as_text(value: Any) -> str:
"""TRIM 后收成字符串;None 当空串。"""
if value is None:
return ""
return str(value).strip()
def _chunks(items: Sequence[str], size: int) -> Iterable[list[str]]:
"""按绑定 IN 列表切批,避免超长 SQL。"""
for index in range(0, len(items), size):
yield list(items[index : index + size])
def _in_clause(prefix: str, values: Sequence[str]) -> tuple[str, dict[str, str]]:
"""
生成 :prefix0,:prefix1 绑定与参数。
核心逻辑:占位符名由本函数生成,禁止把业务值拼进 SQL。
"""
binds: dict[str, str] = {}
names: list[str] = []
for index, value in enumerate(values):
key = f"{prefix}{index}"
names.append(f":{key}")
binds[key] = value
return ", ".join(names), binds
def _format_date(value: Any) -> str:
"""展示用日期:2016/5/28,月日不补零。"""
if value is None:
return ""
if isinstance(value, datetime):
value = value.date()
if not isinstance(value, date):
return _as_text(value)
return f"{value.year}/{value.month}/{value.day}"
def _format_decimal(value: Any, scale: int, *, thousands: bool = False) -> str:
"""按 azi 小数位格式化;金额可带千分位。"""
if value is None or value == "":
return ""
digits = max(0, int(scale or 0))
quant = Decimal("1").scaleb(-digits)
number = Decimal(str(value)).quantize(quant, rounding=ROUND_HALF_UP)
if thousands:
return f"{number:,.{digits}f}"
if digits == 0:
return str(int(number))
return f"{number:.{digits}f}"
def _format_qty(value: Any) -> str:
"""采购量去掉无意义的尾随零。"""
if value is None or value == "":
return ""
number = Decimal(str(value))
if number == number.to_integral_value():
return str(int(number))
return format(number.normalize(), "f")
def _join_address(*parts: Any) -> str:
"""送货/账单地址:空段丢掉再拼接。"""
chunks = [_as_text(part) for part in parts]
return "".join(chunk for chunk in chunks if chunk)
def _halogen_text(ta_ima02: Any, ta_ima03: Any) -> str:
"""版面目前一列;优先环保等级(样张 RoHS),否则卤素管控。"""
code3 = _as_text(ta_ima03)
if code3 in _TA_IMA03:
return _TA_IMA03[code3]
code2 = _as_text(ta_ima02)
return _TA_IMA02.get(code2, "")
def _azi_scale(value: Any, default: int) -> int:
"""币别小数位;空则用默认。"""
text = _as_text(value)
if not text:
return default
try:
return max(0, int(Decimal(text)))
except Exception:
return default
def map_po_document(invoice_no: str, line_rows: Sequence[Mapping[str, Any]]) -> PoOrderDocument:
"""
把同一张 TGHX 采购单的明细行收成 PoOrderDocument。
【AI 触发时机】ERP 已查出 pmm/pmn 行、生成 PDF 之前调用。
核心逻辑:头栏取首行;合计对 pmn88/pmn88t 求和;到货日用 pmn34;版本 pmnud02;
原始编号优先 ta_ima11,否则 pmn24。不写 SQL。
Args:
invoice_no: 销售发票号,只用于文件名。
line_rows: 同一 pmm01 的有序明细(已是 dict,键为小写列名)。
Returns:
可交给 save_po_order_pdf 的文档。
Raises:
ValueError: 无明细或缺少 pmm01。
"""
if not line_rows:
raise ValueError("采购单没有明细行")
head = line_rows[0]
po_no = _as_text(head.get("po_no") or head.get("pmm01"))
if not po_no:
raise ValueError("缺少采购单号")
price_scale = _azi_scale(head.get("azi03"), 6)
amount_scale = _azi_scale(head.get("azi04"), 2)
total_scale = _azi_scale(head.get("azi05"), amount_scale)
price_code = _as_text(head.get("price_term_code"))
price_name = _as_text(head.get("price_term_name"))
price_term = f"{price_code} {price_name}".strip()
lines: list[PoOrderLine] = []
untax_total = Decimal("0")
tax_total = Decimal("0")
for raw in line_rows:
untax_amt = raw.get("pmn88")
tax_amt = raw.get("pmn88t")
if untax_amt not in (None, ""):
untax_total += Decimal(str(untax_amt))
if tax_amt not in (None, ""):
tax_total += Decimal(str(tax_amt))
origin_no = _as_text(raw.get("ta_ima11")) or _as_text(raw.get("pmn24"))
lines.append(
PoOrderLine(
seq=_as_text(raw.get("pmn02") or (len(lines) + 1)),
item_no=_as_text(raw.get("pmn04")),
name=_as_text(raw.get("pmn041")),
spec=_as_text(raw.get("ima021")),
qty=_format_qty(raw.get("pmn20")),
unit=_as_text(raw.get("pmn07")),
arrive=_format_date(raw.get("pmn34")),
origin_no=origin_no,
version=_as_text(raw.get("pmnud02")),
untax_price=_format_decimal(raw.get("pmn31"), price_scale),
tax_price=_format_decimal(raw.get("pmn31t"), price_scale),
untax_amt=_format_decimal(untax_amt, amount_scale, thousands=True),
tax_amt=_format_decimal(tax_amt, amount_scale, thousands=True),
halogen=_halogen_text(raw.get("ta_ima02"), raw.get("ta_ima03")),
vendor_item=_as_text(raw.get("pmn06")),
)
)
return PoOrderDocument(
invoice_no=_as_text(invoice_no),
po_no=po_no,
po_date=_format_date(head.get("po_date") or head.get("pmm04")),
po_type=_as_text(head.get("po_type") or head.get("smydesc")),
pay_term=_as_text(head.get("pay_term") or head.get("pma02")),
tax_type=_as_text(head.get("tax_type") or head.get("gec02")),
price_term=price_term,
currency=_as_text(head.get("currency") or head.get("pmm22")),
ship_address=_join_address(
head.get("ship031"),
head.get("ship032"),
head.get("ship033"),
head.get("ship034"),
head.get("ship035"),
),
bill_address=_join_address(
head.get("bill031"),
head.get("bill032"),
head.get("bill033"),
head.get("bill034"),
head.get("bill035"),
),
vendor_code=_as_text(head.get("vendor_code") or head.get("pmm09")),
vendor_name=_as_text(head.get("vendor_name") or head.get("pmc081")),
vendor_tel=_as_text(head.get("vendor_tel") or head.get("pmc10")),
vendor_fax=_as_text(head.get("vendor_fax") or head.get("pmc11")),
vendor_addr=_as_text(head.get("vendor_addr") or head.get("pmc091")),
company_name=_as_text(head.get("company_name") or head.get("zo02")),
company_address=_as_text(head.get("company_address") or head.get("zo041")),
company_phone=_as_text(head.get("company_phone") or head.get("zo05")),
company_fax=_as_text(head.get("company_fax") or head.get("zo09")),
maker="",
untax_total=_format_decimal(untax_total, total_scale, thousands=True),
tax_total=_format_decimal(tax_total, total_scale, thousands=True),
lines=tuple(lines),
)
def _invoice_key_sql(placeholders: str) -> str:
"""HXJM 应收头:发票号 → 类别、来源单、多角序号。"""
return f"""
SELECT DISTINCT
TRIM(oma10) AS invoice_no,
TRIM(oma00) AS oma00,
TRIM(oma16) AS oma16,
TRIM(oma99) AS oma99
FROM {INVOICE_SCHEMA}.oma_file
WHERE TRIM(oma10) IN ({placeholders})
AND TRIM(omaconf) = 'Y'
AND TRIM(omavoid) = 'N'
AND TRIM(oma64) = '1'
AND TRIM(oma00) IN ('11', '12', '13')
"""
def _fallback_sql(table: str, key_col: str, flow_col: str, placeholders: str) -> str:
"""oma99 为空时,从出货单或订单借多角序号。"""
return f"""
SELECT TRIM({key_col}) AS doc_no,
TRIM({flow_col}) AS flow_no
FROM {INVOICE_SCHEMA}.{table}
WHERE TRIM({key_col}) IN ({placeholders})
"""
def _po_detail_sql(placeholders: str) -> str:
"""TGHX 采购单头身 + 码表,对照 apmr900;过滤作废/无效/BKR。"""
s = PO_SCHEMA
return f"""
SELECT TRIM(pmm.pmm99) AS flow_no,
TRIM(pmm.pmm01) AS po_no,
pmm.pmm04 AS po_date,
TRIM(smy.smydesc) AS po_type,
TRIM(pma.pma02) AS pay_term,
TRIM(gec.gec02) AS tax_type,
TRIM(pmm.pmm41) AS price_term_code,
TRIM(pnz.pnz02) AS price_term_name,
TRIM(pmm.pmm22) AS currency,
TRIM(pmm.pmm09) AS vendor_code,
TRIM(pmc.pmc081) AS vendor_name,
TRIM(pmc.pmc10) AS vendor_tel,
TRIM(pmc.pmc11) AS vendor_fax,
TRIM(pmc.pmc091) AS vendor_addr,
TRIM(ship.pme031) AS ship031,
TRIM(ship.pme032) AS ship032,
TRIM(ship.pme033) AS ship033,
TRIM(ship.pme034) AS ship034,
TRIM(ship.pme035) AS ship035,
TRIM(bill.pme031) AS bill031,
TRIM(bill.pme032) AS bill032,
TRIM(bill.pme033) AS bill033,
TRIM(bill.pme034) AS bill034,
TRIM(bill.pme035) AS bill035,
TRIM(zo.zo02) AS company_name,
TRIM(zo.zo041) AS company_address,
TRIM(zo.zo05) AS company_phone,
TRIM(zo.zo09) AS company_fax,
pmn.pmn02 AS pmn02,
TRIM(pmn.pmn04) AS pmn04,
TRIM(pmn.pmn041) AS pmn041,
TRIM(pmn.pmn06) AS pmn06,
TRIM(pmn.pmn07) AS pmn07,
pmn.pmn20 AS pmn20,
TRIM(pmn.pmn24) AS pmn24,
pmn.pmn31 AS pmn31,
pmn.pmn31t AS pmn31t,
pmn.pmn34 AS pmn34,
pmn.pmn88 AS pmn88,
pmn.pmn88t AS pmn88t,
TRIM(pmn.pmnud02) AS pmnud02,
TRIM(ima.ima021) AS ima021,
TRIM(ima.ta_ima02) AS ta_ima02,
TRIM(ima.ta_ima03) AS ta_ima03,
TRIM(ima.ta_ima11) AS ta_ima11,
azi.azi03 AS azi03,
azi.azi04 AS azi04,
azi.azi05 AS azi05
FROM {s}.pmm_file pmm
JOIN {s}.pmn_file pmn ON pmn.pmn01 = pmm.pmm01
LEFT JOIN {s}.smy_file smy ON pmm.pmm01 LIKE TRIM(smy.smyslip) || '-%'
LEFT JOIN {s}.pmc_file pmc ON TRIM(pmc.pmc01) = TRIM(pmm.pmm09)
LEFT JOIN {s}.pma_file pma ON TRIM(pma.pma01) = TRIM(pmm.pmm20)
LEFT JOIN {s}.gec_file gec ON TRIM(gec.gec01) = TRIM(pmm.pmm21) AND TRIM(gec.gec011) = '1'
LEFT JOIN {s}.pnz_file pnz ON TRIM(pnz.pnz01) = TRIM(pmm.pmm41)
LEFT JOIN {s}.azi_file azi ON TRIM(azi.azi01) = TRIM(pmm.pmm22)
LEFT JOIN {s}.ima_file ima ON TRIM(ima.ima01) = TRIM(pmn.pmn04)
LEFT JOIN {s}.pme_file ship ON TRIM(ship.pme01) = TRIM(pmm.pmm10)
LEFT JOIN {s}.pme_file bill ON TRIM(bill.pme01) = TRIM(pmm.pmm11)
LEFT JOIN {s}.zo_file zo ON zo.zo01 = '1'
WHERE TRIM(pmm.pmm99) IN ({placeholders})
AND TRIM(pmm.pmm18) != 'X'
AND TRIM(pmm.pmmacti) = 'Y'
AND NVL(TRIM(pmm.pmm02), ' ') != 'BKR'
ORDER BY pmm.pmm01, pmn.pmn02
"""
def _rows_as_dicts(cursor: Any) -> list[dict[str, Any]]:
"""把游标行收成小写键 dict。"""
columns = [str(col[0]).lower() for col in (cursor.description or [])]
return [dict(zip(columns, raw)) for raw in cursor]
def _fetch_invoice_keys(cursor: Any, invoice_nos: Sequence[str]) -> list[dict[str, Any]]:
"""分批查 HXJM 应收头。"""
found: list[dict[str, Any]] = []
for batch in _chunks(list(invoice_nos), _BATCH_SIZE):
placeholders, binds = _in_clause("inv", batch)
cursor.execute(_invoice_key_sql(placeholders), binds)
found.extend(_rows_as_dicts(cursor))
return found
def _fetch_doc_flows(cursor: Any, table: str, key_col: str, flow_col: str, doc_nos: Sequence[str]) -> dict[str, str]:
"""出货单/订单号 → 多角序号。"""
mapping: dict[str, str] = {}
unique = [item for item in dict.fromkeys(doc_nos) if item]
for batch in _chunks(unique, _BATCH_SIZE):
placeholders, binds = _in_clause("doc", batch)
cursor.execute(_fallback_sql(table, key_col, flow_col, placeholders), binds)
for row in _rows_as_dicts(cursor):
doc_no = _as_text(row.get("doc_no"))
flow_no = _as_text(row.get("flow_no"))
if doc_no and flow_no:
mapping[doc_no] = flow_no
return mapping
def resolve_invoice_flows(cursor: Any, invoice_nos: Sequence[str]) -> list[InvoiceFlow]:
"""
发票号 → 多角流程序号。
核心逻辑:优先 TRIM(oma99);空则 12/13 查 oga99、11 查 oea99。同一发票多个序号会去重保留。
"""
wanted = [item for item in dict.fromkeys(_as_text(no) for no in invoice_nos) if is_sales_invoice_no(item)]
if not wanted:
return []
keys = _fetch_invoice_keys(cursor, wanted)
oga_docs = [_as_text(row.get("oma16")) for row in keys if _as_text(row.get("oma00")) in {"12", "13"} and not _as_text(row.get("oma99"))]
oea_docs = [_as_text(row.get("oma16")) for row in keys if _as_text(row.get("oma00")) == "11" and not _as_text(row.get("oma99"))]
oga_flows = _fetch_doc_flows(cursor, "oga_file", "oga01", "oga99", oga_docs) if oga_docs else {}
oea_flows = _fetch_doc_flows(cursor, "oea_file", "oea01", "oea99", oea_docs) if oea_docs else {}
flows: list[InvoiceFlow] = []
seen: set[tuple[str, str]] = set()
for row in keys:
invoice_no = _as_text(row.get("invoice_no"))
oma00 = _as_text(row.get("oma00"))
oma16 = _as_text(row.get("oma16"))
flow_no = _as_text(row.get("oma99"))
if not flow_no:
if oma00 in {"12", "13"}:
flow_no = oga_flows.get(oma16, "")
elif oma00 == "11":
flow_no = oea_flows.get(oma16, "")
if not invoice_no or not flow_no:
continue
pair = (invoice_no, flow_no)
if pair in seen:
continue
seen.add(pair)
flows.append(InvoiceFlow(invoice_no=invoice_no, flow_no=flow_no, oma00=oma00, oma16=oma16))
return flows
def _fetch_po_lines(cursor: Any, flow_nos: Sequence[str]) -> list[dict[str, Any]]:
"""按多角序号批量取 TGHX 采购明细。"""
lines: list[dict[str, Any]] = []
unique = [item for item in dict.fromkeys(flow_nos) if item]
for batch in _chunks(unique, _BATCH_SIZE):
placeholders, binds = _in_clause("flow", batch)
cursor.execute(_po_detail_sql(placeholders), binds)
lines.extend(_rows_as_dicts(cursor))
return lines
def fetch_po_documents_for_invoices(
config: VoucherCheckEngineConfig,
invoice_nos: Sequence[str],
) -> list[PoOrderDocument]:
"""
按销售发票号从 ERP 组装制式采购单数据。
【AI 触发时机】独立「抓取 PO」任务或周二 05:00 accounting-voucher-po-print 排程已有 invoice 清单、要生成 PDF 之前调用;不要在检核 runner 里调用。
核心逻辑:HXJM.oma99(空则 oga99/oea99)TRIM 后对 TGHX.pmm99;一票可多张 PO,每张一个文档。
Args:
config: Oracle 只读连接。
invoice_nos: 销售发票号;非 6 位以上字母数字的项会跳过。
Returns:
PoOrderDocument 列表,按发票号、采购单号排序。找不到 PO 的发票不出现在结果里。
Raises:
ServiceUnavailableError: Oracle 不可用。
"""
wanted = [item for item in dict.fromkeys(_as_text(no) for no in invoice_nos) if is_sales_invoice_no(item)]
if not wanted:
return []
connection = None
try:
connection = open_erp_connection(config)
cursor = connection.cursor()
# [STEP 1] 发票 → 多角序号
flows = resolve_invoice_flows(cursor, wanted)
if not flows:
return []
# [STEP 2] 序号 → TGHX 采购单明细
po_lines = _fetch_po_lines(cursor, [item.flow_no for item in flows])
by_flow: dict[str, dict[str, list[dict[str, Any]]]] = defaultdict(lambda: defaultdict(list))
for row in po_lines:
flow_no = _as_text(row.get("flow_no"))
po_no = _as_text(row.get("po_no"))
if flow_no and po_no:
by_flow[flow_no][po_no].append(row)
# [STEP 3] 发票 × 采购单 交叉成文档
documents: list[PoOrderDocument] = []
seen: set[tuple[str, str]] = set()
for flow in flows:
for po_no, rows in by_flow.get(flow.flow_no, {}).items():
key = (flow.invoice_no, po_no)
if key in seen:
continue
seen.add(key)
documents.append(map_po_document(flow.invoice_no, rows))
documents.sort(key=lambda item: (item.invoice_no, item.po_no))
return documents
except ServiceUnavailableError:
raise
except Exception as exc:
raise _erp_unavailable(config, exc) from exc
finally:
if connection is not None:
try:
connection.close()
except Exception:
pass
@@ -1,13 +1,15 @@
"""
backend/app/services/voucher_check/erp_repository.py
用途:从 Oracle HXJM 套账 apa_file 查询上一个自然月发票号集合。
用途:从 Oracle HXJM 套账 oma_file 查询上一个自然月发票号集合;并提供共用只读连接。
依赖:oracledb、Text2SQLService._init_oracle_client、voucher_check.config。
逻辑:runner 阶段 A 调用;仅只读 SELECT;失败映射为 VOUCHER_CHECK.ERP_UNAVAILABLE。
逻辑:runner 阶段 A 调用 fetch_month_invoices;采购单取数见 erp_po_repository,复用 open_erp_connection。
只读 SELECT 已确认、未作废、状况码 1、帐款类别 11/12/13;失败映射为 VOUCHER_CHECK.ERP_UNAVAILABLE。
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from datetime import date, datetime
from zoneinfo import ZoneInfo
@@ -16,16 +18,21 @@ from app.core.errors import ServiceUnavailableError
from app.services.voucher_check.config import VoucherCheckEngineConfig
_TZ = ZoneInfo("Asia/Shanghai")
_INVOICE_NO_RE = re.compile(r"^[A-Za-z0-9]{6,}$")
_INVOICE_SQL = """
SELECT DISTINCT
TRIM(apa08) AS invoice_no,
TRUNC(apa09) AS invoice_date
FROM apa_file
WHERE apa09 >= :period_start
AND apa09 < :next_period_start
AND TRIM(apa08) IS NOT NULL
ORDER BY TRUNC(apa09), TRIM(apa08)
TRIM(oma10) AS invoice_no,
TRUNC(oma02) AS invoice_date
FROM oma_file
WHERE oma02 >= :period_start
AND oma02 < :next_period_start
AND REGEXP_LIKE(TRIM(oma10), '^[A-Za-z0-9]{6,}$')
AND TRIM(omaconf) = 'Y'
AND TRIM(omavoid) = 'N'
AND TRIM(oma64) = '1'
AND TRIM(oma00) IN ('11', '12', '13')
ORDER BY TRUNC(oma02), TRIM(oma10)
"""
@@ -37,6 +44,20 @@ class ErpInvoiceRow:
invoice_date: date | None
def is_sales_invoice_no(value: str | None) -> bool:
"""
判断 oma10 是否为可检核的销售发票号。
核心逻辑:TRIM 后至少 6 位字母或数字(如 6975101806、EWZZ26090002)。现场 oma10 是手工录入,常被填成 0、空值或中文备注,那些不能当 invoice。
Args:
value: oma10 原文。
Returns:
True 表示可作为检核主体。
"""
return bool(_INVOICE_NO_RE.fullmatch(str(value or "").strip()))
def current_period_bounds(now: datetime | None = None) -> tuple[date, date, datetime, datetime]:
"""
按 Asia/Shanghai 计算当前自然月起止。
@@ -79,6 +100,64 @@ def previous_period_bounds(now: datetime | None = None) -> tuple[date, date, dat
return period_month, current_month, period_start, next_start
def open_erp_connection(config: VoucherCheckEngineConfig):
"""
打开立账凭证 Oracle 只读连接。
核心逻辑:复用 Text2SQL 的 Instant Client 初始化;超时单位毫秒。调用方必须 close。
Args:
config: 含 DSN/账号/超时的检核配置。
Returns:
oracledb 连接。
Raises:
ServiceUnavailableError: 驱动缺失或连接失败。
"""
try:
import oracledb
except ImportError as exc:
raise ServiceUnavailableError(
"Oracle 驱动不可用",
code="VOUCHER_CHECK.ERP_UNAVAILABLE",
) from exc
from app.services.text2sql import Text2SQLService
try:
Text2SQLService._init_oracle_client(oracledb)
connection = oracledb.connect(
user=config.erp_username,
password=config.erp_password,
dsn=config.erp_dsn,
)
connection.call_timeout = max(1, int(config.erp_timeout_seconds)) * 1000
return connection
except ServiceUnavailableError:
raise
except Exception as exc:
raise _erp_unavailable(config, exc) from exc
def _erp_unavailable(config: VoucherCheckEngineConfig, exc: BaseException) -> ServiceUnavailableError:
"""把 Oracle 异常收成统一错误码,日志只记类型不记密码。"""
try:
from flask import current_app
current_app.logger.error(
"[voucher-check] ERP query failed dsn=%s error_type=%s",
config.erp_dsn,
type(exc).__name__,
)
except Exception:
pass
return ServiceUnavailableError(
"Oracle 查询失败",
code="VOUCHER_CHECK.ERP_UNAVAILABLE",
details={"error_type": type(exc).__name__},
)
def fetch_month_invoices(
config: VoucherCheckEngineConfig,
*,
@@ -86,6 +165,7 @@ def fetch_month_invoices(
) -> tuple[date, list[ErpInvoiceRow]]:
"""
查询上一个自然月发票清单。
核心逻辑:从 oma_file 按帐款日期 oma02 取上月;发票号 oma10 须为至少 6 位字母或数字(排除 0、空值、中文备注);仅确认(omaconf='Y')、未作废(omavoid='N')、状况码 oma64='1'、帐款类别 oma00 为 11/12/13。
Args:
config: 含 Oracle DSN/账号的检核配置。
@@ -98,26 +178,9 @@ def fetch_month_invoices(
ServiceUnavailableError: Oracle 不可用。
"""
period_month, _current_month, period_start, next_start = previous_period_bounds(now)
try:
import oracledb
except ImportError as exc:
raise ServiceUnavailableError(
"Oracle 驱动不可用",
code="VOUCHER_CHECK.ERP_UNAVAILABLE",
) from exc
from flask import current_app
from app.services.text2sql import Text2SQLService
connection = None
try:
Text2SQLService._init_oracle_client(oracledb)
connection = oracledb.connect(
user=config.erp_username,
password=config.erp_password,
dsn=config.erp_dsn,
)
connection.call_timeout = max(1, int(config.erp_timeout_seconds)) * 1000
connection = open_erp_connection(config)
cursor = connection.cursor()
cursor.execute(
_INVOICE_SQL,
@@ -130,7 +193,7 @@ def fetch_month_invoices(
seen: set[str] = set()
for raw_no, raw_date in cursor:
invoice_no = str(raw_no or "").strip()
if not invoice_no or invoice_no in seen:
if not is_sales_invoice_no(invoice_no) or invoice_no in seen:
continue
seen.add(invoice_no)
invoice_date: date | None = None
@@ -144,19 +207,7 @@ def fetch_month_invoices(
except ServiceUnavailableError:
raise
except Exception as exc:
try:
current_app.logger.error(
"[voucher-check] ERP query failed dsn=%s error_type=%s",
config.erp_dsn,
type(exc).__name__,
)
except Exception:
pass
raise ServiceUnavailableError(
"Oracle 查询失败",
code="VOUCHER_CHECK.ERP_UNAVAILABLE",
details={"error_type": type(exc).__name__},
) from exc
raise _erp_unavailable(config, exc) from exc
finally:
if connection is not None:
try:
@@ -1,9 +1,9 @@
"""
backend/app/services/voucher_check/notification.py
用途:立账凭证检核批次级企微汇总与技术失败告警。
用途:立账凭证检核缺件汇总、以及检核 / PO 生成排程的技术失败告警。
依赖:wecom_notify、ScheduleTask.notify_user_ids_json、engine_persistence。
逻辑:一个批次一条缺件汇总;未配置接收人不发送;设置 domain_notification_managed 避免通用排程重复通知。
逻辑:检核批次一条缺件汇总;PO 生成只在技术失败时告警;未配置接收人不发送;domain_notification_managed 避免通用排程重复通知。
"""
from __future__ import annotations
@@ -186,8 +186,14 @@ def send_failure_alert(
error_code: str,
error_message: str,
enabled: bool,
title: str | None = None,
) -> None:
"""批次级技术失败告警(ERP/DMS/配置异常),不计入缺件通知。"""
"""
批次级技术失败告警(ERP/DMS/配置/上传异常),不计入缺件通知。
Args:
title: 企微标题;默认「立账凭证检核失败」。PO 生成排程传入自己的标题。
"""
if not enabled:
return
if not current_app.config.get("WECOM_NOTIFY_ENABLED", True):
@@ -203,7 +209,7 @@ def send_failure_alert(
if not users:
return
title = f"立账凭证检核失败: {task.name}"
title = title or f"立账凭证检核失败: {task.name}"
description = (
f"批次 {run.run_no}\n"
f"失败阶段:{stage}\n"
@@ -0,0 +1,25 @@
"""
backend/app/services/voucher_check/po_order/__init__.py
用途:立账凭证「PO订单」制式采购单 PDF 的对外入口。
依赖:models、filename、save、publish。
逻辑:调用方先组装 PoOrderDocument(ERP 取数见 erp_po_repository),save_po_order_pdf 只写本地;
publish_po_order_pdf 再上传。周检核 runner / erp_po_print.fetch 不要调用本包。
"""
from app.services.voucher_check.po_order.filename import build_po_order_filename
from app.services.voucher_check.po_order.models import PoOrderDocument, PoOrderLine, parse_po_order_document
from app.services.voucher_check.po_order.publish import PoOrderPublishResult, publish_po_order_pdf
from app.services.voucher_check.po_order.sample import sample_po_order_document
from app.services.voucher_check.po_order.save import save_po_order_pdf
__all__ = [
"PoOrderDocument",
"PoOrderLine",
"PoOrderPublishResult",
"build_po_order_filename",
"parse_po_order_document",
"publish_po_order_pdf",
"sample_po_order_document",
"save_po_order_pdf",
]
@@ -0,0 +1,55 @@
"""
backend/app/services/voucher_check/po_order/__main__.py
用途:用给定 JSON、对照样张或 ERP 发票号生成 `{invoice}-{订单号}.pdf`。
依赖:save_po_order_pdf、sample_po_order_document;--invoice 另依赖 Flask 配置与 erp_po_repository。
逻辑:python -m app.services.voucher_check.po_order --out-dir DIR [--json FILE|--sample|--invoice NO]
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
def main(argv: list[str] | None = None) -> int:
"""
命令行入口:JSON / 样张 / ERP 发票号 → 指定目录 PDF。
【AI 触发时机】需要出 PO 订单 PDF、且不走周检核时运行本模块。
"""
parser = argparse.ArgumentParser(description="生成 PO 订单制式 PDF")
parser.add_argument("--out-dir", required=True, help="PDF 输出目录")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--json", dest="json_path", help="采购单 JSON(含 invoice_no、po_no、lines)")
group.add_argument("--sample", action="store_true", help="使用对照样张数据")
group.add_argument("--invoice", help="从 ERP 按销售发票号取 TGHX 采购单(需应用配置)")
args = parser.parse_args(argv)
from app.services.voucher_check.po_order.save import save_po_order_pdf
if args.sample:
from app.services.voucher_check.po_order.sample import sample_po_order_document
documents = [sample_po_order_document()]
elif args.invoice:
from app import create_app
from app.services.voucher_check.config import load_engine_config
from app.services.voucher_check.erp_po_repository import fetch_po_documents_for_invoices
app = create_app()
with app.app_context():
documents = fetch_po_documents_for_invoices(load_engine_config(), [args.invoice])
if not documents:
print("no purchase order for invoice", args.invoice, file=sys.stderr)
return 1
else:
payload = json.loads(Path(args.json_path).read_text(encoding="utf-8"))
documents = [payload]
for document in documents:
print(save_po_order_pdf(document, args.out_dir))
return 0
if __name__ == "__main__":
raise SystemExit(main())
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

@@ -0,0 +1,50 @@
"""
backend/app/services/voucher_check/po_order/filename.py
用途:按销售 Profile 规则生成 PO 订单 PDF 文件名。
依赖:core.errors.ValidationError。
逻辑:固定 `{invoice}-{order_no}.pdf`;禁止路径字符,供落盘与后续目录扫描共用。
"""
from __future__ import annotations
import re
from typing import Any
from app.core.errors import ValidationError
_UNSAFE_RE = re.compile(r'[<>:"/\\|?*\x00-\x1f]|(\.\.)')
def build_po_order_filename(*, invoice_no: str, order_no: str) -> str:
"""
生成 `{invoice号}-{订单号}.pdf`。
【AI 触发时机】保存或匹配 PO 订单 PDF 文件名时调用;不要自行拼接。
Args:
invoice_no: 销售 invoice,禁止空串与路径字符。
order_no: 采购单号(po_no),禁止空串与路径字符。
Returns:
仅文件名,不含目录。
Raises:
ValidationError: 缺号或含非法字符。
"""
invoice = str(invoice_no or "").strip()
order = str(order_no or "").strip()
if not invoice:
raise ValidationError("缺少 invoice_no", code="VOUCHER_CHECK.PO_PDF_INVALID", details={"field": "invoice_no"})
if not order:
raise ValidationError("缺少 po_no", code="VOUCHER_CHECK.PO_PDF_INVALID", details={"field": "po_no"})
if _UNSAFE_RE.search(invoice) or _UNSAFE_RE.search(order):
raise ValidationError(
"invoice 或订单号含非法路径字符",
code="VOUCHER_CHECK.PO_PDF_INVALID",
details=_unsafe_details(invoice, order),
)
return f"{invoice}-{order}.pdf"
def _unsafe_details(invoice: str, order: str) -> dict[str, Any]:
return {"invoice_no": invoice, "po_no": order}
@@ -0,0 +1,70 @@
"""
backend/app/services/voucher_check/po_order/fonts.py
用途:为制式采购单注册中文字体。
依赖:reportlab;可选环境变量 VOUCHER_CHECK_PO_FONT_PATH。
逻辑:优先系统宋体/Noto CJK(Docker 已装 fonts-noto-cjk),失败再回退 CID STSong-Light。
"""
from __future__ import annotations
import os
from pathlib import Path
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.cidfonts import UnicodeCIDFont
from reportlab.pdfbase.ttfonts import TTFont
_FONT_FAMILY = "VoucherPoCjk"
_CID_FALLBACK = "STSong-Light"
_REGISTERED: str | None = None
_CANDIDATES: tuple[tuple[str, int], ...] = (
(r"C:\Windows\Fonts\simsun.ttc", 0),
(r"C:\Windows\Fonts\simsun.ttf", 0),
(r"C:\Windows\Fonts\msyh.ttc", 0),
("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", 2),
("/usr/share/fonts/opentype/noto/NotoSansCJKsc-Regular.otf", 0),
("/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc", 2),
("/usr/share/fonts/opentype/noto/NotoSerifCJK-Regular.ttc", 2),
("/usr/share/fonts/truetype/wqy/wqy-microhei.ttc", 0),
("/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc", 0),
)
def resolve_po_font() -> str:
"""
返回已注册的中文字体名,进程内只注册一次。
核心逻辑:VOUCHER_CHECK_PO_FONT_PATH → 常见系统字体 → CID 内置宋体。
"""
global _REGISTERED
if _REGISTERED:
return _REGISTERED
env_path = str(os.getenv("VOUCHER_CHECK_PO_FONT_PATH") or "").strip()
if env_path:
registered = _try_ttf(Path(env_path), 0) or _try_ttf(Path(env_path), 2)
if registered:
_REGISTERED = registered
return _REGISTERED
for raw, index in _CANDIDATES:
registered = _try_ttf(Path(raw), index)
if registered:
_REGISTERED = registered
return _REGISTERED
pdfmetrics.registerFont(UnicodeCIDFont(_CID_FALLBACK))
_REGISTERED = _CID_FALLBACK
return _REGISTERED
def _try_ttf(path: Path, subfont_index: int) -> str | None:
"""尝试把 TTF/TTC 注册为 VoucherPoCjk;文件不存在或 reportlab 拒收时返回 None。"""
if not path.is_file():
return None
try:
pdfmetrics.registerFont(TTFont(_FONT_FAMILY, str(path), subfontIndex=subfont_index))
return _FONT_FAMILY
except Exception:
return None
@@ -0,0 +1,162 @@
"""
backend/app/services/voucher_check/po_order/models.py
用途:制式采购单 PDF 的给定数据结构(与 ERP 查询解耦)。
依赖:core.errors.ValidationError。
逻辑:独立抓取任务拿到 invoice + PO 明细后填入本模型;renderer 只消费这些字段。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Mapping
from app.core.errors import ValidationError
def _as_text(value: Any) -> str:
"""把给定值收成版面用字符串,None 当空串。"""
if value is None:
return ""
return str(value).strip()
def _po_invalid(message: str, *, details: dict[str, Any] | None = None) -> ValidationError:
return ValidationError(message, code="VOUCHER_CHECK.PO_PDF_INVALID", details=details or {})
@dataclass(frozen=True)
class PoOrderLine:
"""采购单明细行;金额/数量已格式化成展示字符串,渲染层不再重算。"""
seq: str
item_no: str
name: str = ""
spec: str = ""
extra_spec: str = ""
qty: str = ""
unit: str = ""
arrive: str = ""
origin_no: str = ""
version: str = ""
untax_price: str = ""
tax_price: str = ""
untax_amt: str = ""
tax_amt: str = ""
halogen: str = ""
vendor_item: str = ""
@dataclass(frozen=True)
class PoOrderDocument:
"""
一张采购单的给定数据。
invoice_no 只用于文件名 `{invoice}-{po_no}.pdf`,不印在 Crystal 风格版面上。
"""
invoice_no: str
po_no: str
po_date: str = ""
po_type: str = ""
pay_term: str = ""
tax_type: str = ""
price_term: str = ""
currency: str = ""
ship_address: str = ""
bill_address: str = ""
vendor_code: str = ""
vendor_name: str = ""
vendor_tel: str = ""
vendor_fax: str = ""
vendor_addr: str = ""
company_name: str = ""
company_address: str = ""
company_phone: str = ""
company_fax: str = ""
maker: str = ""
untax_total: str = ""
tax_total: str = ""
lines: tuple[PoOrderLine, ...] = field(default_factory=tuple)
def parse_po_order_document(payload: Mapping[str, Any]) -> PoOrderDocument:
"""
把给定 dict/JSON 收成 PoOrderDocument。
【AI 触发时机】调用方已从 ERP 或手工 JSON 拿到采购单字段、要生成 PDF 之前调用。
核心逻辑:只做必填校验与类型收口,不查库、不补默认公司名。
Args:
payload: 须含 invoice_no、po_no;lines 为明细列表。其余键与样张字段同名。
Returns:
可交给 save_po_order_pdf 的冻结文档。
Raises:
ValidationError: invoice / 订单号缺失。
"""
if not isinstance(payload, Mapping):
raise _po_invalid("采购单数据必须是对象")
invoice_no = _as_text(payload.get("invoice_no") or payload.get("invoice"))
po_no = _as_text(payload.get("po_no") or payload.get("order_no"))
if not invoice_no:
raise _po_invalid("缺少 invoice_no", details={"field": "invoice_no"})
if not po_no:
raise _po_invalid("缺少 po_no", details={"field": "po_no"})
raw_lines = payload.get("lines") or []
if raw_lines and not isinstance(raw_lines, list):
raise _po_invalid("lines 必须是数组", details={"field": "lines"})
lines: list[PoOrderLine] = []
for index, raw in enumerate(raw_lines):
if not isinstance(raw, Mapping):
raise _po_invalid("明细行必须是对象", details={"field": "lines", "index": index})
seq = _as_text(raw.get("seq") or raw.get("item_seq") or (index + 1))
item_no = _as_text(raw.get("item_no") or raw.get("part_no"))
lines.append(
PoOrderLine(
seq=seq,
item_no=item_no,
name=_as_text(raw.get("name")),
spec=_as_text(raw.get("spec")),
extra_spec=_as_text(raw.get("extra_spec")),
qty=_as_text(raw.get("qty")),
unit=_as_text(raw.get("unit")),
arrive=_as_text(raw.get("arrive") or raw.get("arrive_date")),
origin_no=_as_text(raw.get("origin_no")),
version=_as_text(raw.get("version")),
untax_price=_as_text(raw.get("untax_price")),
tax_price=_as_text(raw.get("tax_price")),
untax_amt=_as_text(raw.get("untax_amt")),
tax_amt=_as_text(raw.get("tax_amt")),
halogen=_as_text(raw.get("halogen")),
vendor_item=_as_text(raw.get("vendor_item")),
)
)
return PoOrderDocument(
invoice_no=invoice_no,
po_no=po_no,
po_date=_as_text(payload.get("po_date")),
po_type=_as_text(payload.get("po_type")),
pay_term=_as_text(payload.get("pay_term")),
tax_type=_as_text(payload.get("tax_type")),
price_term=_as_text(payload.get("price_term")),
currency=_as_text(payload.get("currency")),
ship_address=_as_text(payload.get("ship_address")),
bill_address=_as_text(payload.get("bill_address")),
vendor_code=_as_text(payload.get("vendor_code")),
vendor_name=_as_text(payload.get("vendor_name")),
vendor_tel=_as_text(payload.get("vendor_tel")),
vendor_fax=_as_text(payload.get("vendor_fax")),
vendor_addr=_as_text(payload.get("vendor_addr")),
company_name=_as_text(payload.get("company_name")),
company_address=_as_text(payload.get("company_address")),
company_phone=_as_text(payload.get("company_phone")),
company_fax=_as_text(payload.get("company_fax")),
maker=_as_text(payload.get("maker")),
untax_total=_as_text(payload.get("untax_total")),
tax_total=_as_text(payload.get("tax_total")),
lines=tuple(lines),
)
@@ -0,0 +1,93 @@
"""
backend/app/services/voucher_check/po_order/publish.py
用途:生成制式采购单 PDF 并上传到文档库当月「PO订单」目录。
依赖:save_po_order_pdf、SalesDmsClient、filename。
逻辑:先本地渲染,再 Attachment/Upload + CreateFiles;同名跳过。不进周检核 runner。
"""
from __future__ import annotations
import tempfile
from dataclasses import dataclass
from datetime import date
from pathlib import Path
from typing import Any, Mapping
from app.services.voucher_check.adapters.base import ScannedFile
from app.services.voucher_check.dms_client import SalesDmsClient
from app.services.voucher_check.filename_match import match_filename
from app.services.voucher_check.po_order.filename import build_po_order_filename
from app.services.voucher_check.po_order.models import PoOrderDocument, parse_po_order_document
from app.services.voucher_check.po_order.save import save_po_order_pdf
PO_TYPE_FOLDER = "PO订单"
PO_FILENAME_TEMPLATE = "{invoice}-{order_no}.pdf"
@dataclass(frozen=True)
class PoOrderPublishResult:
"""一次制式采购单落库结果。"""
file: ScannedFile
skipped_same_name: bool
def publish_po_order_pdf(
document: PoOrderDocument | Mapping[str, Any],
*,
period_month: date,
type_folder: str = PO_TYPE_FOLDER,
) -> PoOrderPublishResult:
"""
生成 `{invoice}-{订单号}.pdf` 并上传到销售开票附件/{年}/{月}/PO订单/。
【AI 触发时机】已拿到给定采购单数据、需要写入文档库类型目录时调用。
不要在周检核 runner 里调用。ERP 取数由 fetch_po_documents_for_invoices 或调用方完成。
核心逻辑:渲染到临时文件 → 确保年/月/PO订单目录 → 同名跳过否则 Upload+CreateFiles。
Args:
document: PoOrderDocument 或同结构 dict。
period_month: 类型目录所属自然月(用其年、月两位文件夹名)。
type_folder: 默认「PO订单」,须与销售 Profile 一致。
Returns:
文档库中的文件元数据;skipped_same_name 表示沿用已有同名文件。
"""
payload = document if isinstance(document, PoOrderDocument) else parse_po_order_document(document)
filename = build_po_order_filename(invoice_no=payload.invoice_no, order_no=payload.po_no)
if match_filename(filename, template=PO_FILENAME_TEMPLATE, invoice_no=payload.invoice_no) is None:
from app.core.errors import ValidationError
raise ValidationError("生成的文件名不符合 {invoice}-{订单号}.pdf", code="VOUCHER_CHECK.PO_PDF_INVALID")
SalesDmsClient.ensure_configured()
yyyy = f"{period_month.year:04d}"
mm = f"{period_month.month:02d}"
folder_path = f"销售开票附件/{yyyy}/{mm}/{type_folder}"
folder_id = SalesDmsClient.ensure_period_type_folder(period_month=period_month, type_folder=type_folder)
with tempfile.TemporaryDirectory(prefix="hxops-po-") as tmp:
local_path = save_po_order_pdf(payload, tmp, overwrite=True)
content = Path(local_path).read_bytes()
row, skipped = SalesDmsClient.upload_file_skip_same_name(
parent_folder_id=folder_id,
leaf_name=filename,
content=content,
)
item_id = str(row.get("ID") or "").strip() or None
return PoOrderPublishResult(
file=ScannedFile(
filename=str(row.get("LeafName") or filename).strip() or filename,
item_id=item_id,
folder_id=folder_id,
path=str(row.get("Path") or f"{folder_path}/{filename}"),
extra={
"skipped_same_name": skipped,
"version_id": row.get("VersionID"),
"type_folder": type_folder,
},
),
skipped_same_name=skipped,
)
@@ -0,0 +1,343 @@
"""
backend/app/services/voucher_check/po_order/renderer.py
用途:按已确认的 Crystal / apmr900 对照样张画出制式采购单 PDF。
依赖:reportlab、fonts、models、页眉 Logo。
逻辑:无满格单元格;项次最左;表头三行折行;不查询 ERP。多页时续页只重复页眉与表头。
"""
from __future__ import annotations
from pathlib import Path
from reportlab.lib.colors import HexColor
from reportlab.lib.pagesizes import A4
from reportlab.lib.units import mm
from reportlab.pdfgen import canvas
from app.services.voucher_check.po_order.fonts import resolve_po_font
from app.services.voucher_check.po_order.models import PoOrderDocument, PoOrderLine
INK = HexColor("#111111")
LINE = HexColor("#333333")
DEFAULT_LOGO = Path(__file__).resolve().parent / "assets" / "welltrust-logo.png"
ROW_H = 13 * mm
HEADER_H = 11 * mm
FOOT_Y = 18 * mm
TOTALS_H = 16 * mm
def render_po_order_pdf(document: PoOrderDocument, out_path: Path, *, logo_path: Path | None = None) -> None:
"""
把给定采购单画到 out_path(调用方已定文件名)。
核心逻辑:先分页再逐页绘制,避免明细把合计和签核挤出页外。
"""
font = resolve_po_font()
out_path.parent.mkdir(parents=True, exist_ok=True)
page_w, page_h = A4
left = 16 * mm
right = page_w - 16 * mm
pages = _paginate(document.lines, page_h)
page_count = len(pages)
c = canvas.Canvas(str(out_path), pagesize=A4)
c.setTitle(f"采购单 {document.po_no}")
c.setAuthor("HXOPS")
logo = logo_path if logo_path is not None else DEFAULT_LOGO
for index, page_lines in enumerate(pages):
page_no = f"{index + 1}/{page_count}"
is_last = index == page_count - 1
_draw_page(
c,
document=document,
lines=page_lines,
font=font,
left=left,
right=right,
page_h=page_h,
page_no=page_no,
show_po_fields=(index == 0),
show_totals=is_last,
logo_path=logo,
)
c.showPage()
c.save()
def _paginate(lines: tuple[PoOrderLine, ...], page_h: float) -> list[list[PoOrderLine]]:
"""按版心高度切页;末页预留合计高度。"""
remaining = list(lines)
pages: list[list[PoOrderLine]] = []
first = True
if not remaining:
return [[]]
while remaining:
last_max = _max_rows(page_h, first_page=first, last_page=True)
if len(remaining) <= last_max:
pages.append(remaining)
break
# 留至少一行给末页,避免把合计画进已排满的页。
max_rows = _max_rows(page_h, first_page=first, last_page=False)
take = min(max(1, max_rows), len(remaining) - 1)
pages.append(remaining[:take])
remaining = remaining[take:]
first = False
return pages or [[]]
def _max_rows(page_h: float, *, first_page: bool, last_page: bool) -> int:
"""估算一页能放下的明细行数。"""
header_block = 86 * mm if first_page else 42 * mm
reserved = FOOT_Y + 8 * mm + HEADER_H
if last_page:
reserved += TOTALS_H
usable = page_h - header_block - reserved
return max(1, int(usable // ROW_H))
def _draw_page(
c: canvas.Canvas,
*,
document: PoOrderDocument,
lines: list[PoOrderLine],
font: str,
left: float,
right: float,
page_h: float,
page_no: str,
show_po_fields: bool,
show_totals: bool,
logo_path: Path,
) -> None:
y = page_h - 10 * mm
y = _draw_letterhead(c, document, font, left, right, y, page_no, logo_path)
if show_po_fields:
y = _draw_po_fields(c, document, font, left, right, y)
else:
y -= 4 * mm
_hline(c, left, right, y, 0.8)
y -= 1 * mm
y = _draw_table_header(c, font, left, right, y)
y = _draw_table_rows(c, lines, font, left, y)
if show_totals:
_draw_totals(c, document, font, left, y)
_draw_footer(c, font, left, right)
def _draw_letterhead(
c: canvas.Canvas,
document: PoOrderDocument,
font: str,
left: float,
right: float,
y: float,
page_no: str,
logo_path: Path,
) -> float:
"""Logo 在左;右侧公司名、「采购单」、地址、电话;制表者/页次下一行靠右。"""
logo_w = 52 * mm
logo_h = 14 * mm
logo_bottom = y - logo_h
if logo_path.is_file():
c.drawImage(
str(logo_path),
left,
logo_bottom,
width=logo_w,
height=logo_h,
mask="auto",
preserveAspectRatio=True,
anchor="sw",
)
text_x = left + 56 * mm
block_mid = (text_x + right) / 2
_text(c, font, block_mid, y - 3.5 * mm, document.company_name, 11, centre=True)
_text(c, font, block_mid, y - 8.2 * mm, "采购单", 10, centre=True)
fax = document.company_fax or ""
_text(c, font, text_x, y - 13 * mm, f"地址:{document.company_address}", 8)
_text(c, font, text_x, y - 17.5 * mm, f"公司电话:{document.company_phone} 公司传真:{fax}", 8)
_text(c, font, right - 52 * mm, y - 22.5 * mm, f"制表者: {document.maker}", 8)
_text(c, font, right, y - 22.5 * mm, f"页次: {page_no}", 8, right_align=True)
y = min(logo_bottom, y - 24 * mm) - 2 * mm
_hline(c, left, right, y, 0.8)
return y - 6 * mm
def _draw_po_fields(
c: canvas.Canvas,
document: PoOrderDocument,
font: str,
left: float,
right: float,
y: float,
) -> float:
"""左栏采购单号、右栏采购日期,与对照样张一致。"""
col2 = left + 98 * mm
val1 = left + 22 * mm
val2 = col2 + 20 * mm
po_label = f"{document.po_no} {document.po_type}".rstrip()
_text(c, font, left, y, "采购单号:")
_text(c, font, val1, y, po_label)
_text(c, font, col2, y, "采购日期:")
_text(c, font, val2, y, document.po_date)
y -= 5.2 * mm
_text(c, font, left, y, "付款条件:")
_text(c, font, val1, y, document.pay_term)
_text(c, font, col2, y, "税 种:")
_text(c, font, val2, y, document.tax_type)
y -= 5.2 * mm
_text(c, font, left, y, "价格条件:")
_text(c, font, val1, y, document.price_term)
_text(c, font, col2, y, "币 种:")
_text(c, font, val2, y, document.currency)
y -= 5.2 * mm
_text(c, font, left, y, "送货地址:")
_text(c, font, val1, y, document.ship_address or " ")
y -= 5.2 * mm
_text(c, font, left, y, "帐单地址:")
_text(c, font, val1, y, document.bill_address or " ")
y -= 6 * mm
_text(c, font, left, y, "供应厂商:")
_text(c, font, val1, y, f"{document.vendor_code} {document.vendor_name}".strip())
_text(c, font, left + 118 * mm, y, f"Tel: {document.vendor_tel}")
y -= 5 * mm
_text(c, font, val1, y, document.vendor_addr, 8)
_text(c, font, left + 118 * mm, y, f"Fax: {document.vendor_fax}")
y -= 4 * mm
_hline(c, left, right, y, 0.8)
return y - 1 * mm
def _table_columns(left: float) -> dict[str, float]:
return {
"seq": left,
"item": left + 8 * mm,
"origin": left + 50 * mm,
"arrive": left + 80 * mm,
"qty": left + 108 * mm,
"unit": left + 116 * mm,
"price": left + 142 * mm,
"amt": left + 164 * mm,
"halo": left + 168 * mm,
}
def _draw_table_header(c: canvas.Canvas, font: str, left: float, right: float, y: float) -> float:
"""Crystal 风格:无竖格,表头三行折行,项次最左。"""
cols = _table_columns(left)
table_top = y
_hline(c, left, right, table_top, 0.7)
h1 = table_top - 3.6 * mm
h2 = table_top - 7.0 * mm
h3 = table_top - 10.2 * mm
_text(c, font, cols["seq"], h1, "项次", 7)
_text(c, font, cols["item"], h1, "料件编号", 7)
_text(c, font, cols["item"], h2, "品名/规格", 7)
_text(c, font, cols["item"], h3, "厂商料号额外品名规格说明", 6.5)
_text(c, font, cols["origin"], h1, "原始编号", 7)
_text(c, font, cols["origin"], h2, "版本", 7)
_text(c, font, cols["origin"], h3, "行序", 6.5)
_text(c, font, cols["arrive"], h1, "到货日", 7)
_text(c, font, cols["qty"] - 8 * mm, h1, "数 量", 7)
_text(c, font, cols["unit"], h1, "单 位", 7)
_text(c, font, cols["price"], h1, "税前单价", 7, right_align=True)
_text(c, font, cols["price"], h2, "含税单价", 7, right_align=True)
_text(c, font, cols["amt"], h1, "税前金额", 7, right_align=True)
_text(c, font, cols["amt"], h2, "含税金额", 7, right_align=True)
_text(c, font, cols["halo"], h1, "卤素", 7)
_text(c, font, cols["halo"], h2, "管控", 7)
_text(c, font, cols["halo"] + 10 * mm, h1, "环保", 7)
_text(c, font, cols["halo"] + 10 * mm, h2, "等级", 7)
c.setStrokeColor(LINE)
c.setLineWidth(0.4)
c.line(cols["price"] - 22 * mm, h2 - 1.2 * mm, cols["price"], h2 - 1.2 * mm)
c.line(cols["amt"] - 22 * mm, h2 - 1.2 * mm, cols["amt"], h2 - 1.2 * mm)
y = table_top - HEADER_H
_hline(c, left, right, y, 0.5)
return y
def _draw_table_rows(c: canvas.Canvas, lines: list[PoOrderLine], font: str, left: float, y: float) -> float:
"""每笔三行:料号/品名/规格,无斑马底、无竖线格。"""
cols = _table_columns(left)
for line in lines:
r1 = y - 3.8 * mm
r2 = y - 7.6 * mm
r3 = y - 11.2 * mm
_text(c, font, cols["seq"], r1, line.seq, 8)
_text(c, font, cols["item"], r1, line.item_no, 8)
_text(c, font, cols["item"], r2, line.name, 8)
_text(c, font, cols["item"], r3, line.spec or line.extra_spec, 8)
_text(c, font, cols["origin"], r1, line.vendor_item, 8)
origin_second = line.origin_no or line.version
_text(c, font, cols["origin"], r2, origin_second, 8)
_text(c, font, cols["arrive"], r1, line.arrive, 8)
_text(c, font, cols["qty"], r1, line.qty, 8, right_align=True)
_text(c, font, cols["unit"], r1, line.unit, 8)
_text(c, font, cols["price"], r1, line.untax_price, 8, right_align=True)
_text(c, font, cols["price"], r2, line.tax_price, 8, right_align=True)
_text(c, font, cols["amt"], r1, line.untax_amt, 8, right_align=True)
_text(c, font, cols["amt"], r2, line.tax_amt, 8, right_align=True)
_text(c, font, cols["halo"], r1, line.halogen, 8)
y -= ROW_H
return y
def _draw_totals(c: canvas.Canvas, document: PoOrderDocument, font: str, left: float, y: float) -> None:
"""合计靠右,金额带细框。"""
cols = _table_columns(left)
y -= 6 * mm
box_w = 22 * mm
box_h = 4.6 * mm
_text(c, font, cols["price"] - 28 * mm, y, "税前金额总和:", 8)
_rect(c, cols["amt"] - box_w, y - 1.2 * mm, box_w, box_h)
_text(c, font, cols["amt"] - 1.2 * mm, y, document.untax_total, 8, right_align=True)
y -= 6 * mm
_text(c, font, cols["price"] - 28 * mm, y, "含税金额总和:", 8)
_rect(c, cols["amt"] - box_w, y - 1.2 * mm, box_w, box_h)
_text(c, font, cols["amt"] - 1.2 * mm, y, document.tax_total, 8, right_align=True)
def _draw_footer(c: canvas.Canvas, font: str, left: float, right: float) -> None:
"""核准/审核/经办横排;线左 (apmr900)、线右 (结束)。"""
span = right - left
_text(c, font, left + 10 * mm, FOOT_Y + 5 * mm, "核准", 10)
_text(c, font, left + span / 2, FOOT_Y + 5 * mm, "审核", 10, centre=True)
_text(c, font, right - 10 * mm, FOOT_Y + 5 * mm, "经办", 10, right_align=True)
_hline(c, left, right, FOOT_Y, 0.7)
_text(c, font, left, FOOT_Y - 1.1 * mm, "(apmr900)", 8)
_text(c, font, right, FOOT_Y - 1.1 * mm, "(结束)", 8, right_align=True)
def _text(
c: canvas.Canvas,
font: str,
x: float,
y: float,
text: str,
size: float = 9,
*,
colour=INK,
right_align: bool = False,
centre: bool = False,
) -> None:
c.setFillColor(colour)
c.setFont(font, size)
value = text or ""
if centre:
c.drawCentredString(x, y, value)
elif right_align:
c.drawRightString(x, y, value)
else:
c.drawString(x, y, value)
def _hline(c: canvas.Canvas, x1: float, x2: float, y: float, width: float = 0.4) -> None:
c.setStrokeColor(LINE)
c.setLineWidth(width)
c.line(x1, y, x2, y)
def _rect(c: canvas.Canvas, x: float, y: float, w: float, h: float) -> None:
c.setStrokeColor(LINE)
c.setLineWidth(0.5)
c.rect(x, y, w, h, stroke=1, fill=0)
@@ -0,0 +1,79 @@
"""
backend/app/services/voucher_check/po_order/sample.py
用途:对照 apmr900 原件的样张数据,供单测与本地出样,不是正式业务数据。
依赖:models.parse_po_order_document。
逻辑:字段来自 e:\\Work\\Agent\\立账凭证\\采购单.pdf;invoice_no 仅用于文件名演示。
"""
from __future__ import annotations
from typing import Any
from app.services.voucher_check.po_order.models import PoOrderDocument, parse_po_order_document
SAMPLE_PO_ORDER_PAYLOAD: dict[str, Any] = {
"invoice_no": "INV-SAMPLE",
"company_phone": "0512-63136988",
"company_fax": "",
"company_address": "江苏省苏州市吴江区经济开发区山湖西路789号",
"company_name": "苏州和信精密科技有限公司",
"maker": "AI",
"po_date": "2016/5/28",
"po_no": "5201-1605280003",
"po_type": "原料采购单",
"price_term": "A01 取核价单价",
"ship_address": "",
"pay_term": "月结一个月",
"tax_type": "进项(17%含税)",
"currency": "RMB",
"bill_address": "",
"vendor_name": "北川科技(苏州)有限公司",
"vendor_code": "VCCD00013",
"vendor_tel": "0512-62810369",
"vendor_fax": "0512-62810368",
"vendor_addr": "苏州市工业园区胜浦分区银胜路61号",
"untax_total": "4,455.50",
"tax_total": "5,212.94",
"lines": [
{
"item_no": "3450541801",
"seq": "1",
"qty": "730",
"unit": "PCS",
"arrive": "2016/6/16",
"untax_price": "3.350000",
"untax_amt": "2,445.50",
"halogen": "RoHS",
"name": "FRAME CUBE CORNER",
"spec": "H20*W36.5*L36.7",
"tax_price": "3.919500",
"tax_amt": "2,861.24",
"origin_no": "3301-1605260004",
"version": "-0001",
"vendor_item": "3450541801",
},
{
"item_no": "3450541801",
"seq": "2",
"qty": "600",
"unit": "PCS",
"arrive": "2016/6/16",
"untax_price": "3.350000",
"untax_amt": "2,010.00",
"halogen": "RoHS",
"name": "FRAME CUBE CORNER",
"spec": "H20*W36.5*L36.7",
"tax_price": "3.919500",
"tax_amt": "2,351.70",
"origin_no": "3301-1605100007",
"version": "-0001",
"vendor_item": "3450541801",
},
],
}
def sample_po_order_document() -> PoOrderDocument:
"""返回对照样张用的采购单数据;正式任务必须改用真实给定数据。"""
return parse_po_order_document(SAMPLE_PO_ORDER_PAYLOAD)
@@ -0,0 +1,46 @@
"""
backend/app/services/voucher_check/po_order/save.py
用途:根据给定采购单数据生成 PDF,并按 `{invoice}-{订单号}.pdf` 保存到本地。
依赖:filename、models、renderer。
逻辑:不查 ERP。上传文档库请用 publish_po_order_pdf。周检核 runner 不要调用。
"""
from __future__ import annotations
from pathlib import Path
from typing import Any, Mapping
from app.services.voucher_check.po_order.filename import build_po_order_filename
from app.services.voucher_check.po_order.models import PoOrderDocument, parse_po_order_document
from app.services.voucher_check.po_order.renderer import render_po_order_pdf
def save_po_order_pdf(
document: PoOrderDocument | Mapping[str, Any],
output_dir: str | Path,
*,
overwrite: bool = True,
) -> Path:
"""
生成制式采购单 PDF 并保存。
【AI 触发时机】已拿到销售 invoice 与一张 PO 的给定字段、需要落盘 PDF 时调用。
不要在周检核 runner 里调用。ERP 取数见 erp_po_repository.fetch_po_documents_for_invoices。
核心逻辑:解析/校验文档 → `{invoice}-{po_no}.pdf` → Crystal 风格渲染到 output_dir。
Args:
document: PoOrderDocument 或同结构 dict(须含 invoice_no、po_no)。
output_dir: 本地目录;不存在则创建。上传文档库请改用 publish_po_order_pdf。
overwrite: 为 False 且目标已存在时直接返回现有路径,不覆盖。
Returns:
生成(或已存在)的 PDF 绝对路径。
"""
payload = document if isinstance(document, PoOrderDocument) else parse_po_order_document(document)
filename = build_po_order_filename(invoice_no=payload.invoice_no, order_no=payload.po_no)
target = Path(output_dir).expanduser().resolve() / filename
if target.exists() and not overwrite:
return target
render_po_order_pdf(payload, target)
return target
@@ -0,0 +1,206 @@
"""
backend/app/services/voucher_check/po_print_runner.py
用途:立账凭证「PO 订单生成」周批:上月发票 → TGHX 取数 → 制式 PDF 上传到「PO订单」。
依赖:config、erp_repository、ErpPoPrintAdapter、dms_client、notification。
逻辑:独立排程 accounting-voucher-po-print 调用;不要从检核 runner 调用。
同名跳过;找不到 PO 的发票记 skipped,不阻断其它票。
"""
from __future__ import annotations
from typing import Any
from flask import current_app
from app import db
from app.core.errors import AppError
from app.models import ScheduleRun, ScheduleTask
from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter
from app.services.voucher_check.config import load_engine_config
from app.services.voucher_check.dms_client import SalesDmsClient
from app.services.voucher_check.erp_repository import fetch_month_invoices
from app.services.voucher_check.notification import send_failure_alert
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
def _mark_domain_notification_managed(run: ScheduleRun) -> None:
"""避免通用排程再发一条企微;本任务只在技术失败时告警。"""
summary = dict(run.response_summary_json or {})
summary["domain_notification_managed"] = True
run.response_summary_json = summary
db.session.commit()
def _write_summary(run: ScheduleRun, payload: dict[str, Any]) -> None:
summary = dict(run.response_summary_json or {})
summary["domain_notification_managed"] = True
summary["voucher_po_print"] = payload
run.response_summary_json = summary
db.session.commit()
def run_po_print_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
按上月销售发票生成制式采购单 PDF 并上传到文档库「PO订单」。
【AI 触发时机】仅 accounting-voucher-po-print 排程(默认周二 05:00)调用;检核周批不要调用。
核心逻辑:fetch_month_invoices → fetch_documents → 逐张 upload_given(同名跳过)。
不调用 ErpPoPrintAdapter.fetch,不写 voucher_check_runs。
Returns:
ScheduleExecuteResult:(发票数, 新上传数, 失败数, 跳过数, details, errors, step_logs)
跳过 = 同名已存在 + 发票没有对应 TGHX 采购单。
"""
step_logs: list[dict[str, Any]] = []
errors: list[str] = []
details: list[dict[str, Any]] = []
adapter = ErpPoPrintAdapter()
current_app.logger.info(
"[voucher-po-print] start name=%s path=accounting-voucher-po-print run_no=%s",
getattr(task, "name", None) or "立账凭证 PO 订单生成",
run.run_no,
)
_mark_domain_notification_managed(run)
try:
config = load_engine_config(task.job_params if isinstance(task.job_params, dict) else {})
SalesDmsClient.ensure_configured()
period_month, invoices = fetch_month_invoices(config)
except AppError as exc:
send_failure_alert(
task=task,
run=run,
stage="config_or_erp",
error_code=exc.code,
error_message=exc.message,
enabled=True,
title=f"立账凭证 PO 生成失败: {task.name}",
)
raise
invoice_nos = [row.invoice_no for row in invoices]
step_logs.append(
{
"step": "list_invoices",
"status": "success",
"detail": {"period": period_month.isoformat(), "invoice_count": len(invoice_nos)},
}
)
if not invoice_nos:
_write_summary(
run,
{
"period": period_month.isoformat(),
"invoice_count": 0,
"uploaded": 0,
"skipped_same_name": 0,
"skipped_no_po": 0,
"failed": 0,
},
)
return (0, 0, 0, 0, [], [], step_logs)
try:
documents = adapter.fetch_documents(invoice_nos, config=config)
except AppError as exc:
send_failure_alert(
task=task,
run=run,
stage="erp_po",
error_code=exc.code,
error_message=exc.message,
enabled=config.notify_failure_enabled,
title=f"立账凭证 PO 生成失败: {task.name}",
)
raise
covered = {item.invoice_no for item in documents}
skipped_no_po = 0
for invoice_no in invoice_nos:
if invoice_no not in covered:
skipped_no_po += 1
details.append({"invoice_no": invoice_no, "status": "skipped_no_po"})
uploaded = 0
skipped_same_name = 0
failed = 0
for document in documents:
try:
result = adapter.upload_given(document, period_month=period_month)
if result.skipped_same_name:
skipped_same_name += 1
status = "skipped_same_name"
else:
uploaded += 1
status = "uploaded"
details.append(
{
"invoice_no": document.invoice_no,
"po_no": document.po_no,
"status": status,
"filename": result.file.filename,
}
)
except Exception as exc:
failed += 1
errors.append(f"{document.invoice_no}/{document.po_no}: {type(exc).__name__}")
details.append(
{
"invoice_no": document.invoice_no,
"po_no": document.po_no,
"status": "failed",
"error_type": type(exc).__name__,
}
)
current_app.logger.exception(
"[voucher-po-print] upload failed invoice=%s po=%s",
document.invoice_no,
document.po_no,
)
skipped = skipped_same_name + skipped_no_po
if failed:
send_failure_alert(
task=task,
run=run,
stage="upload",
error_code="VOUCHER_CHECK.PO_PRINT_PARTIAL",
error_message=f"上传失败 {failed} 张,成功 {uploaded},跳过 {skipped}",
enabled=config.notify_failure_enabled,
title=f"立账凭证 PO 生成部分失败: {task.name}",
)
step_logs.append(
{
"step": "upload",
"status": "failed" if failed else "success",
"detail": {
"uploaded": uploaded,
"skipped_same_name": skipped_same_name,
"skipped_no_po": skipped_no_po,
"failed": failed,
},
}
)
_write_summary(
run,
{
"period": period_month.isoformat(),
"invoice_count": len(invoice_nos),
"po_count": len(documents),
"uploaded": uploaded,
"skipped_same_name": skipped_same_name,
"skipped_no_po": skipped_no_po,
"failed": failed,
},
)
current_app.logger.info(
"[voucher-po-print] done period=%s invoices=%s uploaded=%s skipped=%s failed=%s",
period_month.isoformat(),
len(invoice_nos),
uploaded,
skipped,
failed,
)
return (len(invoice_nos), uploaded, failed, skipped, details, errors, step_logs)
@@ -3,7 +3,7 @@ backend/app/services/voucher_check/profiles/sales.py
用途:销售一期 Profile 定义(六类必检文件、类型目录、命名模板)。
依赖:无外部 IO;由 profile_loader 发布快照。
逻辑:周任务扫描 source_type=directory_scan;erp_po_print / oa_sales_release 仅登记,不在周二 runner 调用。
逻辑:周任务扫描 source_type=directory_scan;subject_adapter=hxjm_apa 实际查 oma_file;erp_po_print.fetch / oa_sales_release 仅登记,不在检核 runner 调用。PO PDF 由独立排程 accounting-voucher-po-print(周二 05:00)写入类型目录。
"""
from __future__ import annotations
@@ -1,9 +1,9 @@
"""
backend/app/services/voucher_check/query_service.py
用途:查询检核批次列表、批次明细、企微发送记录,以及工作台强制重检入队。
依赖:models.voucher_check、ScheduleRun、aggregator、schedule.queue_service。
逻辑:只读引擎表;明细同时返回 invoice 行与 by_file_type;强制重检写入 run_options.mode=force_all。
用途:查询检核批次列表、最近一次检核、批次明细、企微发送记录,以及工作台强制重检入队。
依赖:models.voucher_check、ScheduleRun、aggregator、schedule.queue_service、schedule_seed。
逻辑:只读引擎表;列表 period 支持 YYYY 或 YYYY-MM;GET latest 不跟筛选;明细同时返回 invoice 行与 by_file_type;强制重检写入 run_options.mode=force_all。
"""
from __future__ import annotations
@@ -20,6 +20,7 @@ from app.models.voucher_check import (
)
from app.services.voucher_check.aggregator import aggregate_file_results
from app.services.voucher_check.erp_repository import previous_period_bounds
from app.services.voucher_check.schedule_seed import DEFAULT_VOUCHER_CHECK_PLATFORM_PATH
def parse_period_month(raw: str | None) -> date:
@@ -38,9 +39,92 @@ def parse_period_month(raw: str | None) -> date:
raise ValidationError(
"period 格式须为 YYYY-MM",
code="VOUCHER_CHECK.CONFIG_INVALID",
details={"period": text},
) from exc
def parse_period_filter(raw: str | None) -> tuple[date | None, date | None]:
"""
将工作台列表 period 解析为 [start, end) 半开区间。
核心逻辑:空值不过滤;YYYY 覆盖该自然年;YYYY-MM / YYYY-MM-DD 覆盖该自然月。
Args:
raw: 查询参数 period,允许 YYYY、YYYY-MM、YYYY-MM-DD 或空。
Returns:
(start, end);空 period 时为 (None, None)。
Raises:
ValidationError: 格式无法解析。
"""
if not raw or not str(raw).strip():
return None, None
text = str(raw).strip()
try:
if len(text) == 4 and text.isdigit():
year = int(text)
return date(year, 1, 1), date(year + 1, 1, 1)
start = parse_period_month(text)
if start.month == 12:
end = date(start.year + 1, 1, 1)
else:
end = date(start.year, start.month + 1, 1)
return start, end
except ValidationError as exc:
raise ValidationError(
"period 格式须为 YYYY 或 YYYY-MM",
code="VOUCHER_CHECK.CONFIG_INVALID",
details={"period": text},
) from exc
except (TypeError, ValueError, OverflowError) as exc:
raise ValidationError(
"period 格式须为 YYYY 或 YYYY-MM",
code="VOUCHER_CHECK.CONFIG_INVALID",
details={"period": text},
) from exc
def _apply_period_filter(query, column, period: str | None):
"""
按 period 的年或月区间过滤 period_month 列。
Args:
query: SQLAlchemy 查询。
column: 期间列,通常为 VoucherCheckRun.period_month。
period: YYYY、YYYY-MM,或空。
Returns:
加上区间条件后的查询;period 为空时原样返回。
"""
start, end = parse_period_filter(period)
if start is None or end is None:
return query
return query.filter(column >= start, column < end)
def _period_value_in_filter(period_month: str | None, period: str | None) -> bool:
"""
判断 YYYY-MM 文本是否落在列表 period 筛选区间内。
Args:
period_month: 批次期间,例如 2026-08。
period: 与列表查询相同的 YYYY 或 YYYY-MM。
Returns:
无需过滤或文本落在区间内时为 True。
"""
start, end = parse_period_filter(period)
if start is None or end is None:
return True
if not period_month:
return False
try:
row = datetime.strptime(str(period_month)[:7], "%Y-%m").date().replace(day=1)
except ValueError:
return False
return start <= row < end
def _serialize_engine_run(run: VoucherCheckRun) -> dict[str, Any]:
return {
"id": run.id,
@@ -93,6 +177,238 @@ def _serialize_schedule_fallback_run(run: ScheduleRun) -> dict[str, Any]:
}
def _as_summary_dict(raw: Any) -> dict[str, Any]:
"""把 JSON 字段收成 dict;非 dict 视为空。"""
return raw if isinstance(raw, dict) else {}
def _iso_dt(value: datetime | None) -> str | None:
"""将 datetime 转 ISO 文本,空值保持 None。"""
return value.isoformat() if value else None
def _latest_voucher_summary(schedule_run: ScheduleRun) -> dict[str, Any]:
"""从排程 response_summary_json 取出 voucher_check 快照。"""
summary = _as_summary_dict(schedule_run.response_summary_json)
voucher = summary.get("voucher_check")
return voucher if isinstance(voucher, dict) else {}
def _latest_current_step(schedule_run: ScheduleRun) -> dict[str, Any]:
"""从排程 response_summary_json 取出 runner 写入的 current_step。"""
summary = _as_summary_dict(schedule_run.response_summary_json)
current = summary.get("current_step")
return current if isinstance(current, dict) else {}
def _latest_run_mode(
schedule_run: ScheduleRun,
engine: VoucherCheckRun | None,
voucher_summary: dict[str, Any],
) -> str:
"""
解析最近一批的执行模式。
核心逻辑:优先引擎批次 mode;否则读 api_request_json.run_options,再回退 summary。
"""
if engine and engine.mode:
return str(engine.mode)
request_json = _as_summary_dict(schedule_run.api_request_json)
options = request_json.get("run_options")
option_mode = options.get("mode") if isinstance(options, dict) else None
return str(option_mode or voucher_summary.get("mode") or "incremental")
def _latest_period_month(
schedule_run: ScheduleRun,
engine: VoucherCheckRun | None,
voucher_summary: dict[str, Any],
) -> str:
"""最近一批的资料所属期间;无快照时回退上一个自然月。"""
if engine and engine.period_month:
return engine.period_month.strftime("%Y-%m")
raw = voucher_summary.get("period")
if raw:
return str(raw)[:7]
period_month, *_ = previous_period_bounds()
return period_month.strftime("%Y-%m")
def _latest_card_status(schedule_run: ScheduleRun, engine: VoucherCheckRun | None) -> str:
"""
将排程状态与引擎批次状态收成工作台卡片状态。
核心逻辑:queued/running 必须保留,不能走建批前失败那条 technical_failed 映射。
"""
schedule_status = str(schedule_run.status or "")
if schedule_status == "queued":
return "queued"
if schedule_status == "running":
return "running"
if schedule_status == "failed":
return "technical_failed"
if engine is not None:
return str(engine.status or "completed")
if schedule_status in {"success", "partial_failed"}:
return "completed"
return schedule_status or "queued"
def _latest_progress_percent(
*,
card_status: str,
step: str | None,
processed: int,
subject_count: int,
) -> int:
"""
按 runner 步骤估算进度百分比。
核心逻辑:无精确进度字段;scan_dms 用已处理 invoice / 总数插值,终态固定 100。
"""
if card_status in {"completed", "missing"}:
return 100
if not step and card_status == "queued":
return 8
if step == "scan_dms" and subject_count > 0:
return min(86, 22 + int(64 * processed / subject_count))
step_base = {
"queued": 8,
"fetch_erp": 18,
"scan_dms": 22,
"persist": 88,
"notify": 94,
"done": 100,
}
if step in step_base:
return step_base[step]
if card_status == "technical_failed":
return 18
if card_status == "running":
return 12
return 0
def _serialize_latest_run(schedule_run: ScheduleRun, engine: VoucherCheckRun | None) -> dict[str, Any]:
"""
序列化工作台「最近一次检核」卡片。
核心逻辑:进度与四指标来自 ScheduleRun.response_summary_json 与引擎快照;不跟列表 period 筛选。
"""
voucher_summary = _latest_voucher_summary(schedule_run)
current_step = _latest_current_step(schedule_run)
card_status = _latest_card_status(schedule_run, engine)
step_code = str(current_step.get("step") or "") or None
if not step_code and card_status == "queued":
step_code = "queued"
processed = int(current_step.get("processed_count") or 0)
subject_count = int(
(engine.subject_count if engine is not None else 0)
or voucher_summary.get("subject_count")
or 0
)
archived_file_count = int(
(engine.archived_file_count if engine is not None else 0)
or voucher_summary.get("archived_file_count")
or 0
)
missing_file_count = int(
(engine.missing_file_count if engine is not None else 0)
or voucher_summary.get("missing_file_count")
or 0
)
missing_invoice_count = int(
(engine.missing_invoice_count if engine is not None else 0)
or voucher_summary.get("missing_invoice_count")
or 0
)
started_at = (engine.started_at if engine is not None else None) or schedule_run.started_at
finished_at = (engine.finished_at if engine is not None else None) or schedule_run.finished_at
if card_status in {"queued", "running"}:
finished_at = None
return {
"schedule_run_id": schedule_run.id,
"engine_run_id": engine.id if engine is not None else None,
"run_no": schedule_run.run_no,
"period_month": _latest_period_month(schedule_run, engine, voucher_summary),
"mode": _latest_run_mode(schedule_run, engine, voucher_summary),
"status": card_status,
"progress_percent": _latest_progress_percent(
card_status=card_status,
step=step_code,
processed=processed,
subject_count=subject_count,
),
"subject_count": subject_count,
"archived_file_count": archived_file_count,
"missing_file_count": missing_file_count,
"missing_invoice_count": missing_invoice_count,
"processed_count": processed,
"started_at": _iso_dt(started_at),
"finished_at": _iso_dt(finished_at),
"error_message": schedule_run.error_message,
"current_step": {
"step": step_code,
"label": str(current_step.get("label") or "") or None,
"processed_count": processed,
}
if step_code
else None,
}
def _serialize_latest_from_engine(engine: VoucherCheckRun) -> dict[str, Any]:
"""
无对应排程时,用引擎批次充当最近一次检核。
核心逻辑:历史/测试数据可能只有 voucher_check_runs;终态进度为 100。
"""
card_status = str(engine.status or "completed")
return {
"schedule_run_id": engine.schedule_run_id,
"engine_run_id": engine.id,
"run_no": engine.run_no,
"period_month": engine.period_month.strftime("%Y-%m") if engine.period_month else None,
"mode": engine.mode,
"status": card_status,
"progress_percent": _latest_progress_percent(
card_status=card_status,
step="done" if card_status in {"completed", "missing"} else None,
processed=int(engine.subject_count or 0),
subject_count=int(engine.subject_count or 0),
),
"subject_count": int(engine.subject_count or 0),
"archived_file_count": int(engine.archived_file_count or 0),
"missing_file_count": int(engine.missing_file_count or 0),
"missing_invoice_count": int(engine.missing_invoice_count or 0),
"processed_count": int(engine.subject_count or 0),
"started_at": _iso_dt(engine.started_at),
"finished_at": _iso_dt(engine.finished_at),
"error_message": None,
"current_step": {"step": "done", "label": None, "processed_count": int(engine.subject_count or 0)}
if card_status in {"completed", "missing"}
else None,
}
def get_latest_run() -> dict[str, Any] | None:
"""
取立账凭证最近一次排程批次(按 ScheduleRun.id 倒序),不跟随列表 period/status。
核心逻辑:有排程则 join 引擎快照与 response_summary_json;仅有引擎批次时回退引擎表。
Returns:
卡片载荷;从未跑过任何批次时为 None。
"""
schedule_run = (
ScheduleRun.query.join(ScheduleTask, ScheduleRun.schedule_task_id == ScheduleTask.id)
.filter(ScheduleTask.platform_api_path == DEFAULT_VOUCHER_CHECK_PLATFORM_PATH)
.order_by(ScheduleRun.id.desc())
.first()
)
if schedule_run is not None:
engine = VoucherCheckRun.query.filter_by(schedule_run_id=schedule_run.id).first()
return _serialize_latest_run(schedule_run, engine)
latest_engine = VoucherCheckRun.query.order_by(VoucherCheckRun.id.desc()).first()
if latest_engine is None:
return None
return _serialize_latest_from_engine(latest_engine)
def list_runs(
*,
period: str | None = None,
@@ -105,12 +421,11 @@ def list_runs(
工作台任务列表:按执行时间倒序返回引擎批次及建批前失败的排程记录。
核心逻辑:正常场景读取 VoucherCheckRun 统计快照;若配置校验等错误发生在
create_run 之前,则回退显示对应 ScheduleRun,保证强制重检结果可见。
period 支持 YYYY(全年)或 YYYY-MM(单月)。
"""
page = max(1, int(page or 1))
page_size = max(1, min(int(page_size or 50), 200))
q = VoucherCheckRun.query
if period:
q = q.filter(VoucherCheckRun.period_month == parse_period_month(period))
q = _apply_period_filter(VoucherCheckRun.query, VoucherCheckRun.period_month, period)
if profile_code:
q = q.filter(VoucherCheckRun.profile_code == str(profile_code).strip())
if status:
@@ -120,7 +435,7 @@ def list_runs(
fallback_query = (
ScheduleRun.query.join(ScheduleTask, ScheduleRun.schedule_task_id == ScheduleTask.id)
.filter(
ScheduleTask.platform_api_path == "accounting-voucher-check",
ScheduleTask.platform_api_path == DEFAULT_VOUCHER_CHECK_PLATFORM_PATH,
ScheduleRun.status == "failed",
)
)
@@ -132,7 +447,7 @@ def list_runs(
row
for row in fallback_rows
if row.id not in engine_schedule_run_ids
and (not period or _serialize_schedule_fallback_run(row)["period_month"] == parse_period_month(period).strftime("%Y-%m"))
and _period_value_in_filter(_serialize_schedule_fallback_run(row)["period_month"], period)
]
merged = [_serialize_engine_run(row) for row in engine_rows]
merged.extend(_serialize_schedule_fallback_run(row) for row in fallback_rows)
@@ -284,6 +599,7 @@ def list_notifications(
"""
分页查询企微缺件汇总发送记录。
核心逻辑:以 voucher_check_notifications 为真相源,关联引擎批次取期间/批次号,并回填接收人姓名。
period 支持 YYYY(全年)或 YYYY-MM(单月)。
"""
page = max(1, int(page or 1))
page_size = max(1, min(int(page_size or 50), 200))
@@ -291,8 +607,7 @@ def list_notifications(
VoucherCheckRun,
VoucherCheckNotification.run_id == VoucherCheckRun.id,
)
if period:
q = q.filter(VoucherCheckRun.period_month == parse_period_month(period))
q = _apply_period_filter(q, VoucherCheckRun.period_month, period)
status_filter = str(send_status or "").strip()
if status_filter:
q = q.filter(VoucherCheckNotification.send_status == status_filter)
+2 -1
View File
@@ -3,7 +3,8 @@ backend/app/services/voucher_check/runner.py
用途:销售一期周批次编排(上月清单、目录扫描、按票归档、缺件聚合、Excel、企微汇总)。
依赖:profile_loader、adapters、dms_client、aggregator、engine_persistence、excel_rows、notification。
逻辑:不调用 erp_po_print / oa_sales_release;命中文件复制到所有归档,同名跳过仍记 archived。
逻辑:不调用 erp_po_print.fetch / oa_sales_release.fetch;PO PDF 由独立排程 accounting-voucher-po-print 提前写入类型目录。
命中文件复制到所有归档,同名跳过仍记 archived。
"""
from __future__ import annotations
@@ -1,9 +1,9 @@
"""
backend/app/services/voucher_check/schedule_seed.py
用途:确保 accounting-voucher-check 默认周批 ScheduleTask 存在(周二 06:00 Asia/Shanghai)。
依赖:ScheduleTask/User、timezone_util、voucher_check.config.DEFAULT_JOB_PARAMS。
逻辑:迁移种子 + create_app / User after_commit 幂等补建;已存在的日批改成周二,并剥离 schema 外的旧 job_params。
用途:确保立账凭证检核(周二 06:00)与 PO 订单生成(周二 05:00)默认 ScheduleTask 存在。
依赖:ScheduleTask/User、timezone_util、voucher_check.config。
逻辑:迁移种子 + create_app / User after_commit 幂等补建;检核排程剥离 schema 外的旧 job_params。
"""
from __future__ import annotations
@@ -19,7 +19,7 @@ from sqlalchemy.orm.attributes import flag_modified
from app import db
from app.models import ScheduleTask, User
from app.services.schedule.timezone_util import compute_next_run_at
from app.services.voucher_check.config import DEFAULT_JOB_PARAMS
from app.services.voucher_check.config import DEFAULT_JOB_PARAMS, DEFAULT_PO_PRINT_JOB_PARAMS
_LOGGER = logging.getLogger(__name__)
@@ -28,6 +28,11 @@ DEFAULT_VOUCHER_CHECK_PLATFORM_PATH = "accounting-voucher-check"
DEFAULT_VOUCHER_CHECK_CRON = "0 6 * * 2"
DEFAULT_VOUCHER_CHECK_NAME = "立账凭证检核(周批)"
DEFAULT_VOUCHER_PO_PRINT_SCHEDULE_NO = "SCH-ACCOUNTING-VOUCHER-PO-PRINT"
DEFAULT_VOUCHER_PO_PRINT_PLATFORM_PATH = "accounting-voucher-po-print"
DEFAULT_VOUCHER_PO_PRINT_CRON = "0 5 * * 2"
DEFAULT_VOUCHER_PO_PRINT_NAME = "立账凭证 PO 订单生成(周批)"
_HOOKS_REGISTERED = False
_SESSION_INFO_KEY = "_seed_voucher_check_schedule"
@@ -163,6 +168,113 @@ def ensure_default_voucher_check_schedule(
return task
def _pick_schedule_owner(sess: Any) -> Any | None:
"""优先管理员,否则任意用户;尚无用户时返回 None。"""
owner = (
sess.query(User)
.filter(User.role == "admin")
.order_by(User.id.asc())
.first()
)
if owner is None:
owner = sess.query(User).order_by(User.id.asc()).first()
return owner
def ensure_default_voucher_po_print_schedule(
*,
commit: bool = True,
session: Any | None = None,
) -> ScheduleTask | None:
"""
幂等确保默认 PO 订单生成周批排程存在(周二 05:00,早于检核 06:00)。
核心逻辑:已存在同 schedule_no / platform_api_path 则跳过;新建时尽量复用检核任务的企微接收人。
Args:
commit: 是否立即提交。
session: 可选独立 Session。
Returns:
新建或已存在的 ScheduleTask;尚无用户时返回 None。
"""
sess = session if session is not None else db.session
existing = (
sess.query(ScheduleTask)
.filter(
(ScheduleTask.schedule_no == DEFAULT_VOUCHER_PO_PRINT_SCHEDULE_NO)
| (ScheduleTask.platform_api_path == DEFAULT_VOUCHER_PO_PRINT_PLATFORM_PATH)
)
.first()
)
if existing is not None:
return existing
owner = _pick_schedule_owner(sess)
if owner is None:
_LOGGER.info("skip seed accounting-voucher-po-print schedule: no users yet")
return None
check_task = (
sess.query(ScheduleTask)
.filter(
(ScheduleTask.schedule_no == DEFAULT_VOUCHER_CHECK_SCHEDULE_NO)
| (ScheduleTask.platform_api_path == DEFAULT_VOUCHER_CHECK_PLATFORM_PATH)
)
.first()
)
notify_ids = []
if check_task is not None and isinstance(check_task.notify_user_ids_json, list):
notify_ids = list(check_task.notify_user_ids_json)
now = datetime.utcnow()
next_run = compute_next_run_at(
DEFAULT_VOUCHER_PO_PRINT_CRON,
timezone_name="Asia/Shanghai",
) or now
task = ScheduleTask(
schedule_no=DEFAULT_VOUCHER_PO_PRINT_SCHEDULE_NO,
name=DEFAULT_VOUCHER_PO_PRINT_NAME,
schedule_type="platform_job",
owner_user_id=int(owner.id),
cron_expr=DEFAULT_VOUCHER_PO_PRINT_CRON,
schedule_timezone="Asia/Shanghai",
wait_seconds=0,
platform_api_path=DEFAULT_VOUCHER_PO_PRINT_PLATFORM_PATH,
job_params=dict(DEFAULT_PO_PRINT_JOB_PARAMS),
kb_sync_enabled=False,
notify_user_ids_json=notify_ids,
notify_enabled=True,
enabled=True,
next_run_at=next_run,
created_by=int(owner.id),
updated_by=int(owner.id),
created_at=now,
updated_at=now,
)
sess.add(task)
if commit:
try:
sess.commit()
except Exception:
sess.rollback()
existing = (
sess.query(ScheduleTask)
.filter(
(ScheduleTask.schedule_no == DEFAULT_VOUCHER_PO_PRINT_SCHEDULE_NO)
| (ScheduleTask.platform_api_path == DEFAULT_VOUCHER_PO_PRINT_PLATFORM_PATH)
)
.first()
)
if existing is not None:
return existing
raise
else:
sess.flush()
_LOGGER.info("seeded accounting-voucher-po-print schedule id=%s", task.id)
return task
def register_voucher_check_schedule_hooks() -> None:
"""注册 User after_commit 补建钩子(幂等)。"""
global _HOOKS_REGISTERED
@@ -181,6 +293,7 @@ def register_voucher_check_schedule_hooks() -> None:
factory = sessionmaker(bind=bind)
with factory() as new_sess:
ensure_default_voucher_check_schedule(commit=True, session=new_sess)
ensure_default_voucher_po_print_schedule(commit=True, session=new_sess)
except Exception:
_LOGGER.exception("voucher-check schedule seed after_commit failed")
@@ -0,0 +1,136 @@
"""
backend/migrations/versions/vc4e5f6a7b8c_seed_voucher_po_print_schedule.py
用途:写入立账凭证 PO 订单生成周批(周二 05:00),早于检核周批(06:00)。
依赖:Alembic revision vc3d4e5f6a7b;schedule_tasks / users 已存在。
逻辑:有用户则插入 SCH-ACCOUNTING-VOUCHER-PO-PRINT;无用户时跳过,由应用钩子补建。
企微接收人尽量从检核排程复制。downgrade 只删本 schedule_no。
Revision ID: vc4e5f6a7b8c
Revises: vc3d4e5f6a7b
Create Date: 2026-09-14 19:40:00.000000
"""
from __future__ import annotations
import json
from datetime import datetime, timedelta, timezone
import sqlalchemy as sa
from alembic import op
revision = "vc4e5f6a7b8c"
down_revision = "vc3d4e5f6a7b"
branch_labels = None
depends_on = None
_SCHEDULE_NO = "SCH-ACCOUNTING-VOUCHER-PO-PRINT"
_CRON_EXPR = "0 5 * * 2"
_TZ_NAME = "Asia/Shanghai"
_JOB_PARAMS = {
"profile_code": "sales",
"scope_code": "HXJM",
"notify_failure_enabled": True,
}
def _compute_next_run_at_utc_naive() -> datetime:
"""按周二 05:00 Asia/Shanghai 计算下次执行,返回 UTC naive。"""
try:
from croniter import croniter
from zoneinfo import ZoneInfo
tz = ZoneInfo(_TZ_NAME)
base = datetime.now(tz)
next_local = croniter(_CRON_EXPR, base).get_next(datetime)
if next_local.tzinfo is None:
next_local = next_local.replace(tzinfo=tz)
return next_local.astimezone(timezone.utc).replace(tzinfo=None)
except Exception:
tz = timezone(timedelta(hours=8))
now_local = datetime.now(tz)
next_local = now_local.replace(hour=5, minute=0, second=0, microsecond=0)
while next_local <= now_local or next_local.weekday() != 1:
next_local = next_local + timedelta(days=1)
next_local = next_local.replace(hour=5, minute=0, second=0, microsecond=0)
return next_local.astimezone(timezone.utc).replace(tzinfo=None)
def upgrade() -> None:
conn = op.get_bind()
exists = conn.execute(
sa.text(
"SELECT 1 FROM schedule_tasks "
"WHERE schedule_no = :sno OR platform_api_path = 'accounting-voucher-po-print' "
"LIMIT 1"
),
{"sno": _SCHEDULE_NO},
).first()
if exists:
return
owner = conn.execute(
sa.text("SELECT id FROM users WHERE role = 'admin' ORDER BY id ASC LIMIT 1")
).first()
if owner is None:
owner = conn.execute(sa.text("SELECT id FROM users ORDER BY id ASC LIMIT 1")).first()
if owner is None:
return
notify_row = conn.execute(
sa.text(
"SELECT notify_user_ids_json FROM schedule_tasks "
"WHERE schedule_no = 'SCH-ACCOUNTING-VOUCHER-CHECK' "
" OR platform_api_path = 'accounting-voucher-check' "
"LIMIT 1"
)
).first()
notify_ids = notify_row[0] if notify_row and notify_row[0] is not None else []
if not isinstance(notify_ids, list):
notify_ids = []
now = datetime.utcnow()
next_run = _compute_next_run_at_utc_naive()
conn.execute(
sa.text(
"""
INSERT INTO schedule_tasks (
schedule_no, name, schedule_type, owner_user_id,
cron_expr, schedule_timezone, wait_seconds,
platform_api_path, job_params, notify_user_ids_json,
kb_sync_enabled, notify_enabled,
enabled, next_run_at, last_run_at,
created_by, updated_by, created_at, updated_at
) VALUES (
:schedule_no, :name, 'platform_job', :owner_user_id,
:cron_expr, 'Asia/Shanghai', 0,
'accounting-voucher-po-print', CAST(:job_params AS JSONB), CAST(:notify_ids AS JSONB),
false, true,
true, :next_run_at, NULL,
:owner_user_id, :owner_user_id, :now, :now
)
"""
).bindparams(
sa.bindparam("job_params", type_=sa.String()),
sa.bindparam("notify_ids", type_=sa.String()),
),
{
"schedule_no": _SCHEDULE_NO,
"name": "立账凭证 PO 订单生成(周批)",
"owner_user_id": int(owner[0]),
"cron_expr": _CRON_EXPR,
"job_params": json.dumps(_JOB_PARAMS, ensure_ascii=False),
"notify_ids": json.dumps(notify_ids, ensure_ascii=False),
"next_run_at": next_run,
"now": now,
},
)
def downgrade() -> None:
"""仅删除本迁移约定的 schedule_no,避免误删管理员手工创建的同路径排程。"""
conn = op.get_bind()
conn.execute(
sa.text("DELETE FROM schedule_tasks WHERE schedule_no = :sno"),
{"sno": _SCHEDULE_NO},
)
+2
View File
@@ -29,6 +29,8 @@ pillow==11.3.0
numpy==2.3.3
pypdf==6.1.0
pypdfium2==5.0.0
# 立账凭证制式采购单 PDF(Crystal/apmr900 对照版式);不替代 pypdf 的读/合并能力。
reportlab==4.4.3
python-pptx==1.0.2
beautifulsoup4==4.14.2
lxml==6.0.2
@@ -38,6 +38,7 @@ def test_platform_jobs_registered():
assert "shipping-inventory-rpa" in keys
assert "faq-aggregate-hot" in keys
assert "fixed-assets-snapshot" in keys
assert "accounting-voucher-po-print" in keys
assert get_platform_job("shipping-inventory-rpa") is not None
@@ -217,6 +218,7 @@ def test_get_platform_jobs_api(client, admin_jwt_headers):
assert by_key["shipping-inventory-rpa"]["label_key"] == "admin.schedule.form.platformJobShippingInventory"
assert by_key["faq-aggregate-hot"]["label_key"] == "admin.schedule.form.platformJobFaqHotAggregate"
assert by_key["fixed-assets-snapshot"]["label_key"] == "admin.schedule.form.platformJobFixedAssetsSnapshot"
assert by_key["accounting-voucher-po-print"]["label_key"] == "admin.schedule.form.platformJobAccountingVoucherPoPrint"
defs = client.get("/api/admin/platform-tasks/definitions", headers=admin_jwt_headers)
assert defs.status_code == 200
@@ -3,7 +3,7 @@ backend/tests/voucher_check/test_engine_profile_and_scan.py
用途:销售一期引擎的期间、命名匹配、缺件双口径、Adapter 占位与目录扫描单测。
依赖:pytest;不连 Oracle / 文档库。
逻辑:覆盖上月边界、六类文件名、同一 invoice 多缺件、PO/OA 未接线。
逻辑:覆盖上月边界、oma_file 发票 SQL、六类文件名、同一 invoice 多缺件、PO fetch()/OA 仍未接线。
"""
from __future__ import annotations
@@ -18,11 +18,39 @@ from app.services.voucher_check.adapters.dms_directory_scan import DmsDirectoryS
from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter
from app.services.voucher_check.adapters.oa_sales_release import OaSalesReleaseAdapter
from app.services.voucher_check.aggregator import aggregate_file_results
from app.services.voucher_check.erp_repository import previous_period_bounds
from app.services.voucher_check.erp_repository import _INVOICE_SQL, is_sales_invoice_no, previous_period_bounds
from app.services.voucher_check.filename_match import first_match, match_filename
from app.services.voucher_check.profiles.sales import SALES_PROFILE, required_file_rules
def test_invoice_sql_reads_confirmed_oma_file():
"""销售 invoice 清单来自 oma_file:已确认、未作废、状况码 1、帐款类别 11/12/13;oma10 至少 6 位字母或数字。"""
sql = " ".join(_INVOICE_SQL.split())
assert "FROM oma_file" in sql
assert "TRIM(oma10)" in sql
assert "TRUNC(oma02)" in sql
assert "REGEXP_LIKE(TRIM(oma10), '^[A-Za-z0-9]{6,}$')" in sql
assert "TRIM(omaconf) = 'Y'" in sql
assert "TRIM(omavoid) = 'N'" in sql
assert "TRIM(oma64) = '1'" in sql
assert "TRIM(oma00) IN ('11', '12', '13')" in sql
assert "apa_file" not in sql
assert "apa08" not in sql
def test_sales_invoice_no_rejects_placeholder_and_chinese():
"""正规发票号为至少 6 位字母或数字;0、空值、中文备注不能进主体清单。"""
assert is_sales_invoice_no("6975101806") is True
assert is_sales_invoice_no("394522129") is True
assert is_sales_invoice_no("EWZZ26090002") is True
assert is_sales_invoice_no("ewzz26090006") is True
assert is_sales_invoice_no("0") is False
assert is_sales_invoice_no("泰国HUB仓出货") is False
assert is_sales_invoice_no("") is False
assert is_sales_invoice_no(" ") is False
assert is_sales_invoice_no(None) is False
def test_previous_period_bounds_from_early_september():
"""周二跑批时检核上个月;2026-09-01 应得到 2026-08。"""
now = datetime(2026, 9, 1, 6, 0, 0, tzinfo=ZoneInfo("Asia/Shanghai"))
@@ -0,0 +1,307 @@
"""
backend/tests/voucher_check/test_erp_po_repository.py
用途:HXJM.oma99 → TGHX.pmm99 采购单取数与字段映射。
依赖:pytest;不连 Oracle。
逻辑:断言 TRIM 关联、oma99 空走 oga/oea、到货日 pmn34、周检核 fetch 仍未接线。
"""
from __future__ import annotations
from datetime import date
from types import SimpleNamespace
import pytest
from app.core.errors import ServiceUnavailableError
from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter
from app.services.voucher_check.erp_po_repository import (
INVOICE_SCHEMA,
PO_SCHEMA,
_po_detail_sql,
fetch_po_documents_for_invoices,
map_po_document,
resolve_invoice_flows,
)
pytestmark = pytest.mark.pure_unit
class _NamedCursor:
"""按 SQL 关键字返回带列名的预制行。"""
def __init__(self, scripts: dict[str, tuple[list[str], list[tuple]]]):
self.scripts = scripts
self.executed: list[tuple[str, dict | None]] = []
self.description: list[tuple[str]] = []
self._rows: list[tuple] = []
def execute(self, sql: str, params=None):
self.executed.append((sql, params))
compact = " ".join(sql.split()).upper()
for needle, (columns, rows) in self.scripts.items():
if needle.upper() in compact:
self.description = [(name,) for name in columns]
self._rows = list(rows)
return
raise AssertionError(f"unexpected sql: {sql}")
def __iter__(self):
return iter(self._rows)
def _config():
return SimpleNamespace(erp_dsn="host/db", erp_username="ro", erp_password="x", erp_timeout_seconds=5)
_OMA_COLS = ["invoice_no", "oma00", "oma16", "oma99"]
_FLOW_COLS = ["doc_no", "flow_no"]
def test_po_sql_targets_tghx_and_trims_flow_no():
"""采购单必须查 TGHX,并用 TRIM(pmm99) 对多角序号。"""
sql = " ".join(_po_detail_sql(":flow0").split())
assert f"FROM {PO_SCHEMA}.pmm_file" in sql
assert f"{PO_SCHEMA}.pmn_file" in sql
assert "TRIM(pmm.pmm99) IN" in sql
assert "TRIM(pmm.pmm18) != 'X'" in sql
assert "TRIM(pmm.pmmacti) = 'Y'" in sql
assert "BKR" in sql
assert "pmn34" in sql
assert INVOICE_SCHEMA not in sql
def test_map_po_document_uses_pmn34_and_sample_like_fields():
"""到货日用 pmn34;环保等级 RoHS;原始编号优先 ta_ima11。"""
document = map_po_document(
"EWZZ26090002",
[
{
"po_no": "5220-2609010001",
"po_date": date(2026, 9, 1),
"po_type": "原料采购单",
"pay_term": "月结一个月",
"tax_type": "进项(17%含税)",
"price_term_code": "A01",
"price_term_name": "取核价单价",
"currency": "RMB",
"vendor_code": "V001",
"vendor_name": "测试厂",
"vendor_tel": "0512-1",
"vendor_fax": "0512-2",
"vendor_addr": "苏州",
"ship031": "送货路",
"ship032": "1号",
"bill031": "账单路",
"company_name": "TGHX公司",
"company_address": "地址",
"company_phone": "123",
"company_fax": "",
"pmn02": 1,
"pmn04": "3450541801",
"pmn041": "FRAME",
"ima021": "H20",
"pmn20": 730,
"pmn07": "PCS",
"pmn34": date(2026, 9, 16),
"pmn33": date(2026, 9, 10),
"pmn24": "3301-1",
"ta_ima11": "RAW-11",
"pmnud02": "-0001",
"pmn31": "3.35",
"pmn31t": "3.9195",
"pmn88": "2445.5",
"pmn88t": "2861.24",
"ta_ima02": "1",
"ta_ima03": "1",
"pmn06": "VEN-1",
"azi03": 6,
"azi04": 2,
"azi05": 2,
}
],
)
assert document.invoice_no == "EWZZ26090002"
assert document.po_no == "5220-2609010001"
assert document.po_date == "2026/9/1"
assert document.price_term == "A01 取核价单价"
assert document.ship_address == "送货路1号"
assert document.lines[0].arrive == "2026/9/16"
assert document.lines[0].halogen == "RoHS"
assert document.lines[0].origin_no == "RAW-11"
assert document.lines[0].version == "-0001"
assert document.untax_total == "2,445.50"
assert document.maker == ""
def test_map_po_document_falls_back_origin_and_halogen():
"""原始编号空 ta_ima11 时用 pmn24;无环保码时用卤素管控。"""
document = map_po_document(
"INV0001",
[
{
"po_no": "PO1",
"pmn02": 1,
"pmn24": "3301-9",
"ta_ima11": " ",
"ta_ima02": "1",
"ta_ima03": "",
"pmn88": 0,
"pmn88t": 0,
}
],
)
assert document.lines[0].origin_no == "3301-9"
assert document.lines[0].halogen == "无卤"
def test_resolve_invoice_flows_prefers_oma99():
cursor = _NamedCursor(
{
"OMA_FILE": (
_OMA_COLS,
[("EWZZ26090002", "12", "8520-2609010002", "S004 -26090001")],
)
}
)
flows = resolve_invoice_flows(cursor, ["EWZZ26090002"])
assert len(flows) == 1
assert flows[0].flow_no == "S004 -26090001"
assert not any("OGA_FILE" in sql.upper() or "OEA_FILE" in sql.upper() for sql, _ in cursor.executed)
def test_resolve_invoice_flows_uses_oga99_when_oma99_empty():
cursor = _NamedCursor(
{
"OMA_FILE": (_OMA_COLS, [("EWZZ1A", "12", "8520-1", "")]),
"OGA_FILE": (_FLOW_COLS, [("8520-1", "S004-FALLBACK")]),
}
)
flows = resolve_invoice_flows(cursor, ["EWZZ1A"])
assert flows[0].flow_no == "S004-FALLBACK"
assert any("OGA_FILE" in sql.upper() for sql, _ in cursor.executed)
def test_resolve_invoice_flows_uses_oea99_for_deposit():
cursor = _NamedCursor(
{
"OMA_FILE": (_OMA_COLS, [("EWZZ1B", "11", "1101-1", None)]),
"OEA_FILE": (_FLOW_COLS, [("1101-1", "S004-SO")]),
}
)
flows = resolve_invoice_flows(cursor, ["EWZZ1B"])
assert flows[0].oma00 == "11"
assert flows[0].flow_no == "S004-SO"
assert any("OEA_FILE" in sql.upper() for sql, _ in cursor.executed)
def test_fetch_po_documents_crosses_invoice_and_po(monkeypatch):
"""同一流程序号下的采购单挂到对应发票;绑定值已 TRIM。"""
class _Cursor(_NamedCursor):
def execute(self, sql, params=None):
super().execute(sql, params)
compact = " ".join(sql.split()).upper()
if "PMM_FILE" in compact:
assert params is not None
assert "S004-26090001" in params.values()
class _Conn:
def cursor(self):
return _Cursor(
{
"OMA_FILE": (_OMA_COLS, [("EWZZ26090002", "12", "8520-1", "S004-26090001")]),
"PMM_FILE": (
["flow_no", "po_no", "po_date", "pmn02", "pmn04", "pmn20", "pmn34", "pmn88", "pmn88t"],
[
("S004-26090001", "5220-2609010001", date(2026, 9, 1), 1, "P1", 10, date(2026, 9, 16), 100, 117),
],
),
}
)
def close(self):
return None
monkeypatch.setattr(
"app.services.voucher_check.erp_po_repository.open_erp_connection",
lambda config: _Conn(),
)
docs = fetch_po_documents_for_invoices(_config(), ["EWZZ26090002"])
assert len(docs) == 1
assert docs[0].invoice_no == "EWZZ26090002"
assert docs[0].po_no == "5220-2609010001"
assert docs[0].lines[0].arrive == "2026/9/16"
def test_fetch_po_documents_one_invoice_many_pos(monkeypatch):
"""一票可对应多张 TGHX 采购单。"""
class _Conn:
def cursor(self):
return _NamedCursor(
{
"OMA_FILE": (_OMA_COLS, [("EWZZ26090002", "12", "8520-1", "S004-26090001")]),
"PMM_FILE": (
["flow_no", "po_no", "pmn02", "pmn88", "pmn88t"],
[
("S004-26090001", "5220-2609010001", 1, 10, 11),
("S004-26090001", "5220-2609010002", 1, 20, 22),
],
),
}
)
def close(self):
return None
monkeypatch.setattr(
"app.services.voucher_check.erp_po_repository.open_erp_connection",
lambda config: _Conn(),
)
docs = fetch_po_documents_for_invoices(_config(), ["EWZZ26090002"])
assert [item.po_no for item in docs] == ["5220-2609010001", "5220-2609010002"]
def test_fetch_po_documents_skips_blank_invoice_list(monkeypatch):
monkeypatch.setattr(
"app.services.voucher_check.erp_po_repository.open_erp_connection",
lambda config: (_ for _ in ()).throw(AssertionError("should not connect")),
)
assert fetch_po_documents_for_invoices(_config(), ["0", " "]) == []
def test_adapter_fetch_stays_unwired_while_documents_work(monkeypatch):
adapter = ErpPoPrintAdapter()
assert adapter.wired is False
with pytest.raises(ServiceUnavailableError) as exc:
adapter.fetch(period_month=date(2026, 8, 1), subjects=[])
assert exc.value.code == "VOUCHER_CHECK.ADAPTER_NOT_WIRED"
monkeypatch.setattr(
"app.services.voucher_check.erp_po_repository.fetch_po_documents_for_invoices",
lambda config, invoices: [map_po_document("INV0001", [{"po_no": "PO1", "pmn02": 1}])],
)
docs = adapter.fetch_documents(["INV0001"], config=_config())
assert docs[0].po_no == "PO1"
def test_adapter_publish_for_invoices_uploads_each(monkeypatch):
adapter = ErpPoPrintAdapter()
uploaded: list[str] = []
monkeypatch.setattr(
adapter,
"fetch_documents",
lambda invoices, config=None: [
map_po_document("EWZZ26090002", [{"po_no": "PO-A", "pmn02": 1}]),
map_po_document("EWZZ26090002", [{"po_no": "PO-B", "pmn02": 1}]),
],
)
monkeypatch.setattr(
adapter,
"upload_given",
lambda document, period_month: uploaded.append(document.po_no) or document.po_no,
)
results = adapter.publish_for_invoices(["EWZZ26090002"], period_month=date(2026, 8, 1), config=_config())
assert uploaded == ["PO-A", "PO-B"]
assert results == ["PO-A", "PO-B"]
@@ -0,0 +1,79 @@
"""
backend/tests/voucher_check/test_po_order_pdf.py
用途:制式采购单 PDF 命名与给定数据落盘。
依赖:pytest、pypdf、voucher_check.po_order。
逻辑:不连 ERP / 文档库;断言文件名 `{invoice}-{订单号}.pdf` 且正文含采购单号。
"""
from __future__ import annotations
from pathlib import Path
import pytest
from pypdf import PdfReader
from app.core.errors import ValidationError
from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter
from app.services.voucher_check.po_order import (
build_po_order_filename,
parse_po_order_document,
sample_po_order_document,
save_po_order_pdf,
)
pytestmark = pytest.mark.pure_unit
def test_build_po_order_filename():
"""文件名固定 invoice-订单号.pdf。"""
assert build_po_order_filename(invoice_no="INV001", order_no="5201-1605280003") == "INV001-5201-1605280003.pdf"
def test_build_po_order_filename_rejects_path_chars():
with pytest.raises(ValidationError) as exc:
build_po_order_filename(invoice_no="INV/001", order_no="PO1")
assert exc.value.code == "VOUCHER_CHECK.PO_PDF_INVALID"
def test_parse_requires_invoice_and_po():
with pytest.raises(ValidationError) as exc:
parse_po_order_document({"po_no": "PO1"})
assert exc.value.code == "VOUCHER_CHECK.PO_PDF_INVALID"
def test_save_po_order_pdf_uses_invoice_order_filename(tmp_path: Path):
"""给定样张数据后保存为 {invoice}-{订单号}.pdf,且可抽出采购单号。"""
document = sample_po_order_document()
path = save_po_order_pdf(document, tmp_path)
assert path.name == "INV-SAMPLE-5201-1605280003.pdf"
assert path.is_file()
assert path.stat().st_size > 1000
text = "".join((page.extract_text() or "") for page in PdfReader(str(path)).pages)
assert "5201-1605280003" in text
assert "北川科技" in text
assert "FRAME CUBE CORNER" in text
def test_save_po_order_pdf_from_dict(tmp_path: Path):
path = save_po_order_pdf(
{"invoice_no": "INV001", "po_no": "PO-9", "company_name": "测试公司", "lines": [{"seq": "1", "item_no": "A1", "qty": "2"}]},
tmp_path,
)
assert path.name == "INV001-PO-9.pdf"
def test_overwrite_false_keeps_existing(tmp_path: Path):
first = save_po_order_pdf({"invoice_no": "INV001", "po_no": "PO-9"}, tmp_path)
stamp = first.stat().st_mtime_ns
again = save_po_order_pdf({"invoice_no": "INV001", "po_no": "PO-9", "maker": "B"}, tmp_path, overwrite=False)
assert again == first
assert first.stat().st_mtime_ns == stamp
def test_adapter_render_given_does_not_wire_fetch(tmp_path: Path):
"""fetch 仍未接线;render_given 只根据给定数据出 PDF。"""
adapter = ErpPoPrintAdapter()
assert adapter.wired is False
path = adapter.render_given(sample_po_order_document(), tmp_path)
assert path.name == "INV-SAMPLE-5201-1605280003.pdf"
@@ -0,0 +1,179 @@
"""
backend/tests/voucher_check/test_po_order_upload.py
用途:制式采购单 PDF 上传到文档库「PO订单」目录。
依赖:pytest;mock SalesDmsClient,不连文档库。
逻辑:同名跳过、年/月/类型目录确保存在、CreateFiles 载荷含 AttachmentID。
"""
from __future__ import annotations
from datetime import date
import pytest
from app.core.errors import ServiceUnavailableError
from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter
from app.services.voucher_check.dms_client import SalesDmsClient
from app.services.voucher_check.po_order import publish_po_order_pdf, sample_po_order_document
pytestmark = pytest.mark.pure_unit
def test_ensure_period_type_folder_creates_year_month_type(monkeypatch):
"""销售开票附件下按 年/月/PO订单 逐级建目录。"""
created: list[tuple[str, str]] = []
def ensure_folder(*, parent_folder_id: str, leaf_name: str) -> str:
created.append((parent_folder_id, leaf_name))
return f"{parent_folder_id}/{leaf_name}"
monkeypatch.setattr(SalesDmsClient, "ensure_configured", lambda: None)
monkeypatch.setattr(SalesDmsClient, "root_folder_id", lambda: "sales-root")
monkeypatch.setattr(SalesDmsClient, "ensure_folder", ensure_folder)
folder_id = SalesDmsClient.ensure_period_type_folder(period_month=date(2026, 8, 1), type_folder="PO订单")
assert created == [("sales-root", "2026"), ("sales-root/2026", "08"), ("sales-root/2026/08", "PO订单")]
assert folder_id.endswith("PO订单")
def test_upload_file_skips_when_same_name_exists(monkeypatch):
monkeypatch.setattr(
SalesDmsClient,
"find_child_file",
lambda **_kwargs: {"ID": "exist-1", "LeafName": "INV001-PO-9.pdf"},
)
uploads: list[object] = []
monkeypatch.setattr(SalesDmsClient, "upload_attachment", lambda **kwargs: uploads.append(kwargs) or {})
row, skipped = SalesDmsClient.upload_file_skip_same_name(
parent_folder_id="po-folder",
leaf_name="INV001-PO-9.pdf",
content=b"%PDF-fake",
)
assert skipped is True
assert row["ID"] == "exist-1"
assert uploads == []
def test_upload_file_creates_when_missing(monkeypatch):
listing = {"n": 0}
def find_child_file(**_kwargs):
listing["n"] += 1
if listing["n"] == 1:
return None
return {"ID": "new-1", "LeafName": "INV001-PO-9.pdf"}
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
monkeypatch.setattr(
SalesDmsClient,
"upload_attachment",
lambda **_kwargs: {"ID": "att-1", "Extension": ".pdf", "LeafName": "INV001-PO-9"},
)
created: list[dict] = []
monkeypatch.setattr(SalesDmsClient, "create_files", lambda **kwargs: created.append(kwargs) or {"Code": 0})
row, skipped = SalesDmsClient.upload_file_skip_same_name(
parent_folder_id="po-folder",
leaf_name="INV001-PO-9.pdf",
content=b"%PDF-fake",
)
assert skipped is False
assert row["ID"] == "new-1"
assert created[0]["parent_folder_id"] == "po-folder"
assert created[0]["files"][0]["AttachmentID"] == "att-1"
assert created[0]["files"][0]["LeafName"] == "INV001-PO-9.pdf"
def test_upload_treats_create_same_name_as_skip(monkeypatch):
listing = {"n": 0}
def find_child_file(**_kwargs):
listing["n"] += 1
if listing["n"] == 1:
return None
return {"ID": "exist-2", "LeafName": "INV001-PO-9.pdf"}
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
monkeypatch.setattr(SalesDmsClient, "upload_attachment", lambda **_kwargs: {"ID": "att-2", "Extension": ".pdf"})
monkeypatch.setattr(
SalesDmsClient,
"create_files",
lambda **_kwargs: (_ for _ in ()).throw(
ServiceUnavailableError(
"存在同名文件",
code="VOUCHER_CHECK.PO_UPLOAD_FAILED",
details={"dms_data": {"SameLeafNames": ["INV001-PO-9.pdf"]}},
)
),
)
row, skipped = SalesDmsClient.upload_file_skip_same_name(
parent_folder_id="po-folder",
leaf_name="INV001-PO-9.pdf",
content=b"%PDF-fake",
)
assert skipped is True
assert row["ID"] == "exist-2"
def test_upload_finds_leaf_name_without_extension(monkeypatch):
"""部分现网 CreateFiles 后 LeafName 不含 .pdf,按无后缀再查一次。"""
listing = {"n": 0}
def find_child_file(*, parent_folder_id: str, leaf_name: str):
listing["n"] += 1
if listing["n"] == 1:
return None
if str(leaf_name).endswith(".pdf"):
return None
return {"ID": "new-stem", "LeafName": leaf_name}
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
monkeypatch.setattr(SalesDmsClient, "upload_attachment", lambda **_kwargs: {"ID": "att-3", "Extension": ".pdf"})
monkeypatch.setattr(SalesDmsClient, "create_files", lambda **_kwargs: {"Code": 0})
row, skipped = SalesDmsClient.upload_file_skip_same_name(
parent_folder_id="po-folder",
leaf_name="INV001-PO-9.pdf",
content=b"%PDF-fake",
)
assert skipped is False
assert row["ID"] == "new-stem"
assert row["LeafName"] == "INV001-PO-9"
def test_publish_po_order_pdf_uploads_to_type_folder(monkeypatch):
"""给定数据生成后上传到 销售开票附件/{年}/{月}/PO订单/。"""
monkeypatch.setattr(SalesDmsClient, "ensure_configured", lambda: None)
monkeypatch.setattr(SalesDmsClient, "ensure_period_type_folder", lambda **_kwargs: "po-folder")
captured: dict[str, object] = {}
def upload_file_skip_same_name(*, parent_folder_id: str, leaf_name: str, content: bytes):
captured["parent_folder_id"] = parent_folder_id
captured["leaf_name"] = leaf_name
captured["size"] = len(content)
return {"ID": "item-1", "LeafName": leaf_name, "Path": f"销售开票附件/2026/08/PO订单/{leaf_name}"}, False
monkeypatch.setattr(SalesDmsClient, "upload_file_skip_same_name", upload_file_skip_same_name)
result = publish_po_order_pdf(sample_po_order_document(), period_month=date(2026, 8, 1))
assert result.skipped_same_name is False
assert result.file.filename == "INV-SAMPLE-5201-1605280003.pdf"
assert result.file.folder_id == "po-folder"
assert result.file.path == "销售开票附件/2026/08/PO订单/INV-SAMPLE-5201-1605280003.pdf"
assert captured["parent_folder_id"] == "po-folder"
assert captured["leaf_name"] == "INV-SAMPLE-5201-1605280003.pdf"
assert int(captured["size"] or 0) > 1000
def test_adapter_upload_given_does_not_wire_fetch(monkeypatch):
"""fetch 仍未接线;upload_given 只根据给定数据上传。"""
captured: dict[str, object] = {}
def fake_publish(document, period_month):
captured["period_month"] = period_month
captured["invoice_no"] = getattr(document, "invoice_no", None)
return type("R", (), {"file": None, "skipped_same_name": False})()
monkeypatch.setattr("app.services.voucher_check.po_order.publish_po_order_pdf", fake_publish)
adapter = ErpPoPrintAdapter()
assert adapter.wired is False
adapter.upload_given(sample_po_order_document(), period_month=date(2026, 8, 1))
assert captured["period_month"] == date(2026, 8, 1)
assert captured["invoice_no"] == "INV-SAMPLE"
@@ -0,0 +1,184 @@
"""
backend/tests/voucher_check/test_po_print_schedule.py
用途:PO 订单生成周批早于检核,且不走 erp_po_print.fetch。
依赖:pytest、app fixture;不连 Oracle / 文档库。
逻辑:断言 cron 05:00、种子幂等、取数后上传、无 PO 跳过、检核 fetch 仍关闭。
"""
from __future__ import annotations
from datetime import date
from types import SimpleNamespace
import pytest
from app.core.errors import ServiceUnavailableError
from app.models import ScheduleRun, ScheduleTask
from app.services.voucher_check.adapters.erp_po_print import ErpPoPrintAdapter
from app.services.voucher_check.erp_po_repository import map_po_document
from app.services.voucher_check.po_print_runner import run_po_print_batch
from app.services.voucher_check.schedule_seed import (
DEFAULT_VOUCHER_CHECK_CRON,
DEFAULT_VOUCHER_PO_PRINT_CRON,
DEFAULT_VOUCHER_PO_PRINT_PLATFORM_PATH,
DEFAULT_VOUCHER_PO_PRINT_SCHEDULE_NO,
ensure_default_voucher_check_schedule,
ensure_default_voucher_po_print_schedule,
)
def test_po_print_cron_is_earlier_than_check():
"""周二 05:00 早于检核 06:00。"""
assert DEFAULT_VOUCHER_PO_PRINT_CRON == "0 5 * * 2"
assert DEFAULT_VOUCHER_CHECK_CRON == "0 6 * * 2"
def test_ensure_po_print_schedule_is_idempotent(app):
with app.app_context():
from app import db
from app.models import User
if db.session.query(User).first() is None:
user = User(
username="po-print-seed-admin",
email="po-print-seed-admin@example.com",
role="admin",
status="active",
)
user.set_password("test")
db.session.add(user)
db.session.commit()
check = ensure_default_voucher_check_schedule(commit=True)
first = ensure_default_voucher_po_print_schedule(commit=True)
second = ensure_default_voucher_po_print_schedule(commit=True)
assert check is not None
assert first is not None
assert first.id == second.id
assert first.schedule_no == DEFAULT_VOUCHER_PO_PRINT_SCHEDULE_NO
assert first.platform_api_path == DEFAULT_VOUCHER_PO_PRINT_PLATFORM_PATH
assert first.cron_expr == DEFAULT_VOUCHER_PO_PRINT_CRON
assert check.cron_expr == DEFAULT_VOUCHER_CHECK_CRON
assert first.platform_api_path != check.platform_api_path
def test_po_print_batch_uploads_and_skips_no_po(app, monkeypatch):
"""有 PO 的发票上传;没有 TGHX 采购单的发票记 skipped_no_po;不调用 fetch()。"""
uploaded: list[str] = []
def fake_fetch_month(config):
return (
date(2026, 8, 1),
[
SimpleNamespace(invoice_no="EWZZ26090002"),
SimpleNamespace(invoice_no="EWZZ26090099"),
],
)
monkeypatch.setattr(
"app.services.voucher_check.po_print_runner.fetch_month_invoices",
fake_fetch_month,
)
monkeypatch.setattr(
"app.services.voucher_check.po_print_runner.SalesDmsClient.ensure_configured",
lambda: None,
)
monkeypatch.setattr(
"app.services.voucher_check.po_print_runner.load_engine_config",
lambda params=None: SimpleNamespace(notify_failure_enabled=False),
)
monkeypatch.setattr(
ErpPoPrintAdapter,
"fetch_documents",
lambda self, invoices, config=None: [map_po_document("EWZZ26090002", [{"po_no": "5220-1", "pmn02": 1}])],
)
def fake_upload(self, document, period_month):
uploaded.append(document.po_no)
return SimpleNamespace(
skipped_same_name=False,
file=SimpleNamespace(filename=f"{document.invoice_no}-{document.po_no}.pdf"),
)
monkeypatch.setattr(ErpPoPrintAdapter, "upload_given", fake_upload)
monkeypatch.setattr("app.services.voucher_check.po_print_runner.send_failure_alert", lambda **kwargs: None)
with app.app_context():
task = ScheduleTask(
schedule_no="SCH-TEST-PO",
name="po print",
schedule_type="platform_job",
platform_api_path="accounting-voucher-po-print",
owner_user_id=1,
cron_expr="0 5 * * 2",
job_params={"profile_code": "sales", "scope_code": "HXJM", "notify_failure_enabled": False},
)
run = ScheduleRun(run_no="RUN-PO-1", schedule_task_id=1, status="running")
total, success, failed, skipped, details, errors, logs = run_po_print_batch(task, run)
assert total == 2
assert success == 1
assert failed == 0
assert skipped == 1
assert uploaded == ["5220-1"]
assert any(item.get("status") == "skipped_no_po" for item in details)
assert ErpPoPrintAdapter.wired is False
with pytest.raises(ServiceUnavailableError) as exc:
ErpPoPrintAdapter().fetch(period_month=date(2026, 8, 1), subjects=[])
assert exc.value.code == "VOUCHER_CHECK.ADAPTER_NOT_WIRED"
def test_po_print_batch_counts_upload_failure(app, monkeypatch):
monkeypatch.setattr(
"app.services.voucher_check.po_print_runner.fetch_month_invoices",
lambda config: (date(2026, 8, 1), [SimpleNamespace(invoice_no="EWZZ26090002")]),
)
monkeypatch.setattr(
"app.services.voucher_check.po_print_runner.SalesDmsClient.ensure_configured",
lambda: None,
)
monkeypatch.setattr(
"app.services.voucher_check.po_print_runner.load_engine_config",
lambda params=None: SimpleNamespace(notify_failure_enabled=False),
)
monkeypatch.setattr(
ErpPoPrintAdapter,
"fetch_documents",
lambda self, invoices, config=None: [map_po_document("EWZZ26090002", [{"po_no": "PO-FAIL", "pmn02": 1}])],
)
monkeypatch.setattr(
ErpPoPrintAdapter,
"upload_given",
lambda self, document, period_month: (_ for _ in ()).throw(RuntimeError("dms down")),
)
alerts: list[str] = []
monkeypatch.setattr(
"app.services.voucher_check.po_print_runner.send_failure_alert",
lambda **kwargs: alerts.append(kwargs.get("stage") or ""),
)
with app.app_context():
task = ScheduleTask(
schedule_no="SCH-TEST-PO2",
name="po print",
schedule_type="platform_job",
platform_api_path="accounting-voucher-po-print",
owner_user_id=1,
cron_expr="0 5 * * 2",
job_params={},
)
run = ScheduleRun(run_no="RUN-PO-2", schedule_task_id=1, status="running")
total, success, failed, skipped, details, errors, logs = run_po_print_batch(task, run)
assert total == 1
assert success == 0
assert failed == 1
assert "upload" in alerts
assert errors
def test_platform_job_registered():
from app.services.schedule.job_registry import get_platform_job
job = get_platform_job("accounting-voucher-po-print")
assert job is not None
assert job.label_key == "admin.schedule.form.platformJobAccountingVoucherPoPrint"
assert job.handler is not None
@@ -0,0 +1,253 @@
"""
backend/tests/voucher_check/test_workspace_latest_run.py
用途:工作台「最近一次检核」接口契约(含排队/执行中/终态/建批前失败)。
依赖:pytest、Flask client、voucher_check.query_service。
逻辑:GET /runs/latest 按 ScheduleRun.id 倒序,不跟列表 period;queued 不得被标成 technical_failed。
"""
from __future__ import annotations
from datetime import date, datetime
from tests.conftest import parse_api_data
from app import db
from app.models import ScheduleRun, User
from app.models.voucher_check import VoucherCheckRun
from app.services.voucher_check.schedule_seed import ensure_default_voucher_check_schedule
def _ensure_user(*, username: str, role: str) -> User:
"""测试用户幂等创建。"""
user = db.session.query(User).filter_by(username=username).first()
if user:
user.role = role
user.status = "active"
db.session.commit()
return user
user = User(
username=username,
email=f"{username}@example.com",
role=role,
status="active",
)
user.set_password("test")
db.session.add(user)
db.session.commit()
return user
def _add_schedule_run(
*,
run_no: str,
status: str,
mode: str | None = None,
error_message: str | None = None,
summary: dict | None = None,
started_at: datetime | None = None,
finished_at: datetime | None = None,
) -> ScheduleRun:
"""为本任务排程插入一条 ScheduleRun。"""
task = ensure_default_voucher_check_schedule(commit=True)
assert task is not None
payload = {"run_options": {"mode": mode}} if mode else None
run = ScheduleRun(
schedule_task_id=task.id,
run_no=run_no,
trigger_type="manual",
status=status,
total_count=0,
success_count=0,
failed_count=1 if status == "failed" else 0,
error_message=error_message,
api_request_json=payload,
response_summary_json=summary,
started_at=started_at,
finished_at=finished_at,
)
db.session.add(run)
db.session.flush()
return run
def _add_engine_run(
*,
schedule_run: ScheduleRun,
status: str = "missing",
period_month: date | None = None,
subject_count: int = 128,
archived_file_count: int = 742,
missing_file_count: int = 11,
missing_invoice_count: int = 6,
) -> VoucherCheckRun:
"""为排程批次挂一条引擎快照。"""
payload = schedule_run.api_request_json if isinstance(schedule_run.api_request_json, dict) else {}
options = payload.get("run_options") if isinstance(payload.get("run_options"), dict) else {}
engine = VoucherCheckRun(
schedule_run_id=schedule_run.id,
run_no=schedule_run.run_no,
profile_code="sales",
profile_version="1",
profile_snapshot_json={"profile_code": "sales"},
period_month=period_month or date(2026, 8, 1),
mode=str(options.get("mode") or "incremental"),
status=status,
subject_count=subject_count,
archived_file_count=archived_file_count,
missing_file_count=missing_file_count,
missing_invoice_count=missing_invoice_count,
started_at=schedule_run.started_at,
finished_at=schedule_run.finished_at,
)
db.session.add(engine)
return engine
def test_workspace_latest_run_returns_queued_force_all(app, client, user_headers):
"""入队中的强制重检必须显示 queued,而不是建批前失败口径。"""
with app.app_context():
_ensure_user(username="user", role="user")
_add_schedule_run(
run_no="RUN-LATEST-QUEUED",
status="queued",
mode="force_all",
)
db.session.commit()
response = client.get(
"/api/workspace/accounting-voucher-check/runs/latest",
headers=user_headers,
)
assert response.status_code == 200
payload = parse_api_data(response.get_json())
assert payload is not None
assert payload["run_no"] == "RUN-LATEST-QUEUED"
assert payload["status"] == "queued"
assert payload["mode"] == "force_all"
assert payload["progress_percent"] == 8
assert payload["current_step"]["step"] == "queued"
def test_workspace_latest_run_returns_completed_metrics(app, client, user_headers):
"""终态缺件批次返回四指标与 100% 进度。"""
with app.app_context():
_ensure_user(username="user", role="user")
sched = _add_schedule_run(
run_no="RUN-LATEST-DONE",
status="success",
mode="incremental",
started_at=datetime(2026, 9, 8, 1, 48, 7),
finished_at=datetime(2026, 9, 8, 1, 50, 19),
summary={
"current_step": {"step": "done", "label": "检核完成", "processed_count": 128},
"voucher_check": {"period": "2026-08", "mode": "incremental", "subject_count": 128},
},
)
_add_engine_run(schedule_run=sched, status="missing")
db.session.commit()
response = client.get(
"/api/workspace/accounting-voucher-check/runs/latest",
headers=user_headers,
)
assert response.status_code == 200
payload = parse_api_data(response.get_json())
# 关键断言:卡片数字来自引擎快照,状态用缺件而非排程 success。
assert payload["run_no"] == "RUN-LATEST-DONE"
assert payload["status"] == "missing"
assert payload["period_month"] == "2026-08"
assert payload["mode"] == "incremental"
assert payload["progress_percent"] == 100
assert payload["subject_count"] == 128
assert payload["archived_file_count"] == 742
assert payload["missing_file_count"] == 11
assert payload["missing_invoice_count"] == 6
def test_workspace_latest_run_running_progress_ignores_list_period(app, client, user_headers):
"""执行中进度跟 runner 步骤走,且 latest 不吃列表 period。"""
with app.app_context():
_ensure_user(username="user", role="user")
old = _add_schedule_run(
run_no="RUN-LATEST-OLD-AUG",
status="success",
mode="incremental",
finished_at=datetime(2026, 9, 1, 6, 0, 0),
)
_add_engine_run(schedule_run=old, status="completed", period_month=date(2026, 8, 1), subject_count=10)
_add_schedule_run(
run_no="RUN-LATEST-RUNNING",
status="running",
mode="force_all",
started_at=datetime(2026, 9, 9, 6, 5, 22),
summary={
"current_step": {
"step": "scan_dms",
"label": "扫描销售开票附件类型目录",
"processed_count": 54,
},
"voucher_check": {
"period": "2026-07",
"mode": "force_all",
"subject_count": 128,
"missing_file_count": 3,
"missing_invoice_count": 2,
},
},
)
db.session.commit()
latest = client.get(
"/api/workspace/accounting-voucher-check/runs/latest",
headers=user_headers,
)
assert latest.status_code == 200
payload = parse_api_data(latest.get_json())
assert payload["run_no"] == "RUN-LATEST-RUNNING"
assert payload["status"] == "running"
assert payload["period_month"] == "2026-07"
assert payload["processed_count"] == 54
assert payload["progress_percent"] == min(86, 22 + int(64 * 54 / 128))
assert payload["finished_at"] is None
filtered = client.get(
"/api/workspace/accounting-voucher-check/runs?period=2026-08",
headers=user_headers,
)
assert filtered.status_code == 200
nos = {item["run_no"] for item in parse_api_data(filtered.get_json())["items"]}
# 关键断言:列表按 8 月过滤看不到 7 月执行中批次,但 latest 仍是该批。
assert "RUN-LATEST-RUNNING" not in nos
assert payload["run_no"] == "RUN-LATEST-RUNNING"
def test_workspace_latest_run_pre_engine_failure(app, client, user_headers):
"""建批前失败仍作为最近一次检核,状态为技术失败。"""
with app.app_context():
_ensure_user(username="user", role="user")
_add_schedule_run(
run_no="RUN-LATEST-FAILED",
status="failed",
mode="incremental",
error_message="未配置销售开票附件文档库根目录",
started_at=datetime(2026, 9, 7, 8, 31, 51),
finished_at=datetime(2026, 9, 7, 8, 32, 10),
summary={
"current_step": {"step": "fetch_erp", "label": "拉取上月销售 invoice", "processed_count": 0},
"voucher_check": {"period": "2026-08"},
},
)
db.session.commit()
response = client.get(
"/api/workspace/accounting-voucher-check/runs/latest",
headers=user_headers,
)
assert response.status_code == 200
payload = parse_api_data(response.get_json())
assert payload["run_no"] == "RUN-LATEST-FAILED"
assert payload["status"] == "technical_failed"
assert payload["error_message"] == "未配置销售开票附件文档库根目录"
assert payload["current_step"]["step"] == "fetch_erp"
assert payload["progress_percent"] == 18
@@ -0,0 +1,185 @@
"""
backend/tests/voucher_check/test_workspace_period_filter.py
用途:工作台检核任务 / 企微发送记录的期间筛选(YYYY 全年、YYYY-MM 单月)。
依赖:pytest、Flask client、voucher_check.query_service。
逻辑:同一年多个月份应被 year 筛出;单月筛仍精确;建批前失败记录按年也能命中。
"""
from __future__ import annotations
from datetime import date, datetime
import pytest
from tests.conftest import parse_api_data, parse_api_error
from app import db
from app.core.errors import ValidationError
from app.models import ScheduleRun, User
from app.models.voucher_check import VoucherCheckNotification, VoucherCheckRun
from app.services.voucher_check.query_service import parse_period_filter
from app.services.voucher_check.schedule_seed import ensure_default_voucher_check_schedule
def _ensure_user(*, username: str, role: str) -> User:
"""测试用户幂等创建。"""
user = db.session.query(User).filter_by(username=username).first()
if user:
user.role = role
user.status = "active"
db.session.commit()
return user
user = User(
username=username,
email=f"{username}@example.com",
role=role,
status="active",
)
user.set_password("test")
db.session.add(user)
db.session.commit()
return user
def _engine_run(*, run_no: str, period_month: date, status: str = "missing") -> VoucherCheckRun:
"""构造列表用引擎批次。"""
return VoucherCheckRun(
run_no=run_no,
profile_code="sales",
profile_version="1",
profile_snapshot_json={"profile_code": "sales"},
period_month=period_month,
mode="incremental",
status=status,
subject_count=1,
finished_at=datetime(period_month.year, period_month.month, 2, 6, 0, 0),
)
def test_parse_period_filter_year_and_month():
"""YYYY 覆盖全年,YYYY-MM 只覆盖该月。"""
start, end = parse_period_filter("2026")
assert start == date(2026, 1, 1)
assert end == date(2027, 1, 1)
start, end = parse_period_filter("2026-08")
assert start == date(2026, 8, 1)
assert end == date(2026, 9, 1)
start, end = parse_period_filter("2026-12")
assert start == date(2026, 12, 1)
assert end == date(2027, 1, 1)
assert parse_period_filter(None) == (None, None)
with pytest.raises(ValidationError) as exc:
parse_period_filter("2026-13")
assert exc.value.code == "VOUCHER_CHECK.CONFIG_INVALID"
def test_workspace_lists_runs_by_year_or_month(app, client, user_headers):
"""任务列表 year 筛出同年多月,month 仍只返回单月。"""
with app.app_context():
_ensure_user(username="user", role="user")
db.session.add(_engine_run(run_no="VC-202608-Y", period_month=date(2026, 8, 1)))
db.session.add(_engine_run(run_no="VC-202607-Y", period_month=date(2026, 7, 1)))
db.session.add(_engine_run(run_no="VC-202512-Y", period_month=date(2025, 12, 1)))
db.session.commit()
year_resp = client.get(
"/api/workspace/accounting-voucher-check/runs?period=2026",
headers=user_headers,
)
assert year_resp.status_code == 200
year_payload = parse_api_data(year_resp.get_json())
year_nos = {item["run_no"] for item in year_payload["items"]}
# 关键断言:全年筛选包含 7、8 月,不含跨年 12 月。
assert "VC-202608-Y" in year_nos
assert "VC-202607-Y" in year_nos
assert "VC-202512-Y" not in year_nos
month_resp = client.get(
"/api/workspace/accounting-voucher-check/runs?period=2026-08",
headers=user_headers,
)
assert month_resp.status_code == 200
month_payload = parse_api_data(month_resp.get_json())
month_nos = {item["run_no"] for item in month_payload["items"]}
assert "VC-202608-Y" in month_nos
assert "VC-202607-Y" not in month_nos
def test_workspace_year_filter_includes_pre_engine_failure(app, client, admin_headers):
"""建批前失败记录在按年筛选时仍须出现。"""
with app.app_context():
_ensure_user(username="admin", role="admin")
task = ensure_default_voucher_check_schedule(commit=True)
assert task is not None
db.session.add(
ScheduleRun(
schedule_task_id=task.id,
run_no="RUN-PREENGINE-YEAR",
trigger_type="manual",
status="failed",
total_count=0,
success_count=0,
failed_count=1,
error_message="未配置销售开票附件文档库根目录",
response_summary_json={"voucher_check": {"period": "2026-08"}},
)
)
db.session.commit()
response = client.get(
"/api/workspace/accounting-voucher-check/runs?period=2026&status=technical_failed",
headers=admin_headers,
)
assert response.status_code == 200
payload = parse_api_data(response.get_json())
nos = {item["run_no"] for item in payload["items"]}
assert "RUN-PREENGINE-YEAR" in nos
def test_workspace_lists_notifications_by_year(app, client, user_headers):
"""企微发送记录按年筛选应覆盖该年各月。"""
with app.app_context():
_ensure_user(username="user", role="user")
august = _engine_run(run_no="VC-202608-N", period_month=date(2026, 8, 1))
july = _engine_run(run_no="VC-202607-N", period_month=date(2026, 7, 1), status="completed")
db.session.add_all([august, july])
db.session.flush()
db.session.add_all(
[
VoucherCheckNotification(
run_id=august.id,
send_status="sent",
summary_json={"period": "2026-08"},
),
VoucherCheckNotification(
run_id=july.id,
send_status="skipped_no_missing",
summary_json={"period": "2026-07"},
),
]
)
db.session.commit()
response = client.get(
"/api/workspace/accounting-voucher-check/notifications?period=2026",
headers=user_headers,
)
assert response.status_code == 200
payload = parse_api_data(response.get_json())
nos = {item["run_no"] for item in payload["items"]}
assert "VC-202608-N" in nos
assert "VC-202607-N" in nos
def test_workspace_rejects_invalid_period(app, client, user_headers):
"""非法 period 返回配置错误,而不是空列表。"""
with app.app_context():
_ensure_user(username="user", role="user")
response = client.get(
"/api/workspace/accounting-voucher-check/runs?period=2026-13",
headers=user_headers,
)
assert response.status_code == 400
error = parse_api_error(response.get_json())
assert error["code"] == "VOUCHER_CHECK.CONFIG_INVALID"
+1 -1
View File
@@ -81,7 +81,7 @@ def _log_queue_startup_diagnostics(logger: logging.Logger, app, queue_names: lis
if 'schedule' in queue_names:
logger.info(
'schedule 队列身份:domain/job_type 固定为 schedule/schedule_run;'
'立账凭证检核看 business_ref 后缀 accounting-voucher-check 或 payload.platform_api_path'
'立账凭证检核看 accounting-voucher-check;PO 生成看 accounting-voucher-po-print'
)
+2 -2
View File
@@ -215,13 +215,13 @@
### 3.x 立账凭证检核补充需求
- AI 工作台中的“立账凭证”入口及页面仅对 `role=admin` 用户开放;普通用户不展示入口,直接访问地址时返回工作台应用页。
- **核心目标**:按业务方 Profile **每周二**增量检核**上一个自然月**;销售 invoice 清单沿用旧口径(HXJM `apa_file.apa08/apa09`);从 ERP/OA/文档库获取必检资料,按 `invoice` 归入「所有归档」,输出缺件汇总 Excel。
- **核心目标**:按业务方 Profile **每周二**增量检核**上一个自然月**;销售 invoice 清单来自 HXJM `oma_file`(`oma10`/`oma02`,已确认、未作废、状况码 1、帐款类别 11/12/13);从 ERP/OA/文档库获取必检资料,按 `invoice` 归入「所有归档」,输出缺件汇总 Excel。
- **销售一期资料**:PO 订单、报关资料、销货放行申请单、发票、报关单、提单。获取后先写入文档库 `销售开票附件/{年}/{月}/{类型目录}/`,再归档到同月 `所有归档/{invoice号}/`。
- **OA**:一期仅模拟页面打销货放行单;后期对接新 OA 接口,规则不变。
- **文档库**:复用现有文档管理系统(全公司一个库,LibraryID 与合同相同);销售开票附件是该库下独立文件夹,只单独配根 FolderID,不得复用合同根目录。
- **通知**:每个检核批次一条企业微信汇总;接收人在界面从系统用户多选,未配置则不发。
- **判定边界**:只做文件获取、命名/关联校验和归档结果;不读取文件内容、不使用 LLM、不核对金额/供应商等字段、不回写 ERP。
- **实现状态**:周任务已按上月 + 文档库扫描 + 按票归档(同名跳过)+ 缺件汇总落地;PO/OA 打印仍待接线。不做 Chatflow;查询走工作台 API。
- **实现状态**:周二 05:00 独立排程生成 PO PDF 并上传到「PO订单」;周二 06:00 检核周任务按上月 + 文档库扫描 + 按票归档(同名跳过)+ 缺件汇总。ERP 取数见 [technical-design.md §3.4](features/accounting-voucher-check/technical-design.md)(HXJM → TGHX,`TRIM(oma99)=TRIM(pmm99)`);OA 打印仍待接线。不做 Chatflow;查询走工作台 API。
- 权威需求见 [docs/features/accounting-voucher-check/demand.md](features/accounting-voucher-check/demand.md)。
### 3.x 货代发货通知库存源补充需求
@@ -5,12 +5,14 @@
| **需求说明** | 产品、业务、测试 | [demand.md](demand.md) |
| **技术设计** | 研发 | [technical-design.md](technical-design.md) |
| **技术规格** | 研发、测试 | [technical.md](technical.md) |
| **原型** | 产品、业务、测试 | [accounting-voucher-check-prototype.html](accounting-voucher-check-prototype.html) · [说明](accounting-voucher-check-prototype.md) |
| **原型** | 产品、业务、测试 | [accounting-voucher-check-prototype.html](accounting-voucher-check-prototype.html) · [说明](accounting-voucher-check-prototype.md) · [最近一次检核卡片](accounting-voucher-check-latest-run-prototype.html) |
| **部署验收清单** | 运维、研发 | [ops-checklist.md](ops-checklist.md) |
| **PO 制式 PDF 样张 JSON** | 研发 | [po-order-sample.json](po-order-sample.json) · 入口 `python -m app.services.voucher_check.po_order --out-dir DIR --json FILE` |
| **ERP 采购单取数表字段** | 研发 | [technical-design.md §3.4](technical-design.md)(发票 HXJM、采购单 TGHX;`TRIM(oma99)=TRIM(pmm99)`;独立抓取已接线) |
**定位**:以业务方 Profile 驱动的批量资料检核;**每周二**增量处理上一个自然月。销售开票附件先落入文档库类型目录,再按 `invoice` 归入「所有归档」。
**要解决的问题**:不同业务方从 ERP、OA、固定目录等来源获取不同必检资料,统一检核、归档、汇总缺件并通知。
**检核内容**:只做必检文件的获取、存在性和归档结果;不做文件内容解析或金额、供应商等字段一致性核对。
**结果输出**:每批生成 Excel,区分缺件文件总数和缺件 `invoice` 数;企业微信每批一条汇总通知,完整明细以 Excel 与执行记录为准。
**状态**:销售一期需求以 [demand.md](demand.md) 为准;采购二期及其它业务方通过新增 Profile 扩展。周任务已切到文档库引擎;旧共享盘扫描、Chatflow Tool 与一票一状态表已移除。ERP PO / OA 销货放行打印仍待接线。
**状态**:销售一期需求以 [demand.md](demand.md) 为准;采购二期及其它业务方通过新增 Profile 扩展。周任务已切到文档库引擎;旧共享盘扫描、Chatflow Tool 与一票一状态表已移除。PO 制式 PDF 由周二 05:00 独立排程生成并上传;06:00 检核只扫描目录。OA 销货放行打印仍待接线。
@@ -0,0 +1,409 @@
<!doctype html>
<!--
docs/features/accounting-voucher-check/accounting-voucher-check-latest-run-prototype.html
用途:立账凭证工作台「最近一次检核」卡片原型(Tab 下方、筛选栏上方)。
依赖:浏览器原生 HTML/CSS/JS,无需构建。
逻辑:默认展示最近一批终态;点「强制重检上月」切入执行中进度;原型预览可切换完成/执行中/失败。
-->
<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: #e2e8f0;
--bg: #f4f7fb;
--panel: #fff;
--brand: #2563eb;
--brand-soft: #eff6ff;
--red: #b42318;
--green: #067647;
--amber: #b54708;
}
* { 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 { font: inherit; }
button { cursor: pointer; }
.page { width: min(1120px, calc(100% - 32px)); margin: 24px auto 48px; }
.proto-note {
margin-bottom: 16px;
padding: 10px 12px;
border: 1px dashed #bfdbfe;
border-radius: 10px;
background: #f8fbff;
color: #334155;
font-size: 12px;
}
.proto-note b { color: var(--brand); }
.proto-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 8px; }
header h1 { margin: 0; font-size: 24px; }
header p { margin: 6px 0 0; color: var(--muted); font-size: 13px; }
.tabs { display: flex; gap: 4px; margin: 18px 0 0; border-bottom: 1px solid var(--line); }
.tabs button {
border: 0;
border-bottom: 2px solid transparent;
margin-bottom: -1px;
padding: 10px 16px;
color: var(--muted);
background: transparent;
font-weight: 600;
}
.tabs button.active { color: var(--brand); border-bottom-color: var(--brand); }
.filters {
display: flex;
flex-wrap: wrap;
align-items: flex-end;
gap: 12px;
margin: 14px 0;
padding: 12px 16px;
border: 1px solid var(--line);
border-radius: 16px;
background: var(--panel);
}
.filters label { display: grid; gap: 4px; color: var(--muted); font-size: 11px; font-weight: 700; }
.filters select {
min-width: 76px;
padding: 6px 10px;
border: 1px solid var(--line);
border-radius: 12px;
background: #fff;
}
.btn {
display: inline-flex;
align-items: center;
gap: 6px;
border: 1px solid var(--line);
border-radius: 12px;
padding: 7px 12px;
background: #fff;
font-size: 13px;
font-weight: 650;
}
.btn.primary { border-color: var(--brand); color: #fff; background: var(--brand); }
.btn:disabled { opacity: .55; cursor: not-allowed; }
.latest {
overflow: hidden;
margin-top: 16px;
border: 1px solid var(--line);
border-radius: 16px;
background: var(--panel);
}
.latest-actions { display: flex; flex-shrink: 0; align-items: center; gap: 8px; }
.btn.warn { border-color: #fcd34d; color: #92400e; background: #fffbeb; }
.latest-hd {
display: flex;
justify-content: space-between;
gap: 12px;
align-items: flex-start;
padding: 14px 16px 12px;
background: var(--brand-soft);
}
.latest-hd h2 { margin: 0; font-size: 15px; }
.latest-meta { margin: 4px 0 0; color: var(--muted); font-size: 12px; }
.latest-meta span { margin-right: 12px; }
.badge {
display: inline-flex;
padding: 3px 10px;
border-radius: 99px;
font-size: 12px;
font-weight: 750;
white-space: nowrap;
}
.badge.ok { color: var(--green); background: #ecfdf3; }
.badge.miss { color: var(--red); background: #fff1f2; }
.badge.run { color: #175cd3; background: #dbeafe; }
.badge.fail { color: var(--red); background: #fff1f2; }
.latest-bd { padding: 14px 16px 16px; }
.bar { height: 10px; overflow: hidden; border-radius: 99px; background: #e8eef5; }
.bar i { display: block; height: 100%; width: 0; border-radius: 99px; background: #0f766e; transition: width .35s ease; }
.bar.fail i { background: #e11d48; }
.bar-row { display: flex; justify-content: space-between; gap: 12px; margin: 8px 0 14px; color: var(--muted); font-size: 12px; }
.metrics { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; }
.metric {
padding: 12px 10px;
border: 1px solid var(--line);
border-radius: 10px;
background: #f8fafc;
}
.metric b { display: block; font-size: 22px; line-height: 1.2; }
.metric span { color: var(--muted); font-size: 12px; }
.metric.warn b { color: var(--red); }
.step-line { margin: 12px 0 0; color: #334155; font-size: 13px; }
.step-line small { display: block; margin-top: 2px; color: var(--muted); }
.latest-ft { display: flex; justify-content: flex-end; margin-top: 12px; }
.link { border: 0; padding: 0; color: #175cd3; background: transparent; font-weight: 700; }
.table-wrap {
overflow: auto;
margin-top: 14px;
border: 1px solid var(--line);
border-radius: 16px;
background: var(--panel);
}
table { width: 100%; border-collapse: collapse; font-size: 13px; }
th, td { padding: 11px 14px; border-bottom: 1px solid #eef2f6; text-align: left; white-space: nowrap; }
th { color: var(--muted); background: #f8fafc; font-size: 12px; }
tr:last-child td { border-bottom: 0; }
.pill { display: inline-flex; padding: 2px 8px; border-radius: 99px; font-size: 12px; font-weight: 700; }
.pill.miss { color: var(--red); background: #fff1f2; }
.pill.fail { color: #475569; background: #f1f5f9; }
.err { max-width: 240px; overflow: hidden; color: var(--red); text-overflow: ellipsis; }
.toast {
position: fixed; right: 18px; bottom: 18px;
padding: 10px 12px; border-radius: 9px; color: #fff; background: #142036;
opacity: 0; pointer-events: none; transition: .2s;
}
.toast.show { opacity: 1; }
@media (max-width: 820px) {
.metrics { grid-template-columns: 1fr 1fr; }
.btn.warn { margin-left: 0; }
}
</style>
</head>
<body>
<div class="page">
<div class="proto-note">
这是<strong>原型</strong>,不是工作台代码。最近一次检核放在 Tab 下方、筛选栏上方:它是整页状态,不跟着年/月过滤。强制重检放在卡片上,点击后进度就在本卡更新。
<div class="proto-actions">
预览状态:
<button class="btn" type="button" data-preview="done">完成 · 缺件</button>
<button class="btn" type="button" data-preview="running">执行中</button>
<button class="btn" type="button" data-preview="failed">技术失败</button>
</div>
</div>
<header>
<h1>立账凭证检核任务</h1>
<p>每周二增量检核上一个自然月;扫描销售开票附件类型目录后按 invoice 归档,并汇总缺件。</p>
</header>
<nav class="tabs">
<button class="active" type="button">检核任务</button>
<button type="button" disabled>企微发送记录</button>
</nav>
<article class="latest" id="latest" aria-live="polite"></article>
<section class="filters">
<label>资料所属期间
<span>
<select><option>2026</option></select>
<select><option>8月</option><option>全部</option></select>
</span>
</label>
<label>状态
<select><option>全部</option><option>缺件</option><option>完整</option><option>技术失败</option></select>
</label>
<button class="btn primary" type="button">查询</button>
</section>
<section class="table-wrap">
<table>
<thead>
<tr>
<th>批次号</th>
<th>资料所属期间</th>
<th>invoice总数</th>
<th>invoice缺件数</th>
<th>缺件文件数</th>
<th>状态</th>
<th>执行时间</th>
<th>失败原因</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><b>RUN2026090801480719A3</b></td>
<td>2026-08</td>
<td>128</td>
<td>6</td>
<td>11</td>
<td><span class="pill miss">缺件</span></td>
<td>2026-09-08 09:50:19</td>
<td>—</td>
<td><button class="link" type="button">查看详情</button></td>
</tr>
<tr>
<td>RUN202609070831512538</td>
<td>2026-08</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td><span class="pill fail">技术失败</span></td>
<td>2026-09-07 16:32:10</td>
<td class="err">未配置销售开票附件文档库根目录</td>
<td><button class="link" type="button">查看详情</button></td>
</tr>
</tbody>
</table>
</section>
</div>
<div class="toast" id="toast"></div>
<script>
/**
* 原型状态机:完成 / 执行中 / 失败。强制重检走一套示意步骤,不请求后端。
*/
(() => {
const latestEl = document.getElementById("latest");
const toastEl = document.getElementById("toast");
let timer = null;
let busy = false;
const snapshots = {
done: {
title: "最近一次检核",
runNo: "RUN2026090801480719A3",
period: "2026-08",
mode: "增量",
status: "缺件",
statusClass: "miss",
barClass: "",
percent: 100,
started: "2026-09-08 09:48:07",
finished: "2026-09-08 09:50:19",
step: "本批已完成,缺件结果已写入 Excel。",
hint: "",
metrics: [128, 742, 11, 6],
},
running: {
title: "最近一次检核",
runNo: "RUN202609090605221C4B",
period: "2026-08",
mode: "全量重检",
status: "执行中",
statusClass: "run",
barClass: "",
percent: 42,
started: "2026-09-09 14:05:22",
finished: "进行中",
step: "扫描销售开票附件类型目录",
hint: "已处理 54 / 128 张 invoice",
metrics: [128, 310, 3, 2],
},
failed: {
title: "最近一次检核",
runNo: "RUN202609070831512538",
period: "2026-08",
mode: "增量",
status: "技术失败",
statusClass: "fail",
barClass: "fail",
percent: 18,
started: "2026-09-07 16:31:51",
finished: "2026-09-07 16:32:10",
step: "拉取上月销售 invoice 未完成",
hint: "未配置销售开票附件文档库根目录",
metrics: [0, 0, 0, 0],
},
};
const forceSteps = [
{ percent: 8, status: "排队中", step: "已入队强制重检上月", hint: "等待 schedule worker 领取", metrics: [0, 0, 0, 0] },
{ percent: 22, status: "执行中", step: "拉取上月销售 invoice", hint: "HXJM oma_file · 期间 2026-08", metrics: [128, 0, 0, 0] },
{ percent: 58, status: "执行中", step: "扫描销售开票附件类型目录", hint: "已处理 74 / 128 张 invoice", metrics: [128, 410, 5, 3] },
{ percent: 82, status: "执行中", step: "按 invoice 归档(同名跳过)", hint: "正在写入所有归档", metrics: [128, 690, 9, 5] },
{ percent: 100, status: "缺件", step: "本批已完成,缺件结果已写入 Excel。", hint: "", metrics: [128, 742, 11, 6], done: true },
];
function toast(message) {
toastEl.textContent = message;
toastEl.classList.add("show");
setTimeout(() => toastEl.classList.remove("show"), 2200);
}
function render(data) {
const warn = data.metrics[2] > 0 || data.metrics[3] > 0;
const labels = ["invoice总数", "已归档文件", "缺件文件数", "缺件 invoice 数"];
latestEl.innerHTML =
'<div class="latest-hd">' +
"<div><h2>" + data.title + "</h2>" +
'<p class="latest-meta"><span>批次 ' + data.runNo + "</span><span>期间 " + data.period + "</span><span>" + data.mode + "</span></p></div>" +
'<div class="latest-actions">' +
'<span class="badge ' + data.statusClass + '">' + data.status + "</span>" +
'<button class="btn warn" type="button" data-force="1"' + (busy ? " disabled" : "") + ">强制重检上月</button>" +
"</div>" +
"</div>" +
'<div class="latest-bd">' +
'<div class="bar ' + data.barClass + '"><i style="width:' + data.percent + '%"></i></div>' +
'<div class="bar-row"><span>进度 ' + data.percent + "%</span><span>开始:" + data.started + " 完成:" + data.finished + "</span></div>" +
'<div class="metrics">' +
data.metrics.map(function (value, index) {
const hot = warn && index > 1;
return '<div class="metric' + (hot ? " warn" : "") + '"><b>' + value + "</b><span>" + labels[index] + "</span></div>";
}).join("") +
"</div>" +
'<p class="step-line">' + data.step + (data.hint ? "<small>" + data.hint + "</small>" : "") + "</p>" +
(data.percent === 100 && data.statusClass !== "fail"
? '<div class="latest-ft"><button class="link" type="button">查看本批详情</button></div>'
: "") +
"</div>";
}
function show(key) {
if (timer) {
clearInterval(timer);
timer = null;
}
busy = false;
render(snapshots[key]);
}
function startForce() {
if (busy) return;
busy = true;
let index = 0;
const started = "2026-09-09 14:08:01";
const runNo = "RUN2026090906080119F2";
function paint() {
const step = forceSteps[index];
render({
title: "最近一次检核",
runNo: runNo,
period: "2026-08",
mode: "全量重检",
status: step.status,
statusClass: step.done ? "miss" : "run",
barClass: "",
percent: step.percent,
started: started,
finished: step.done ? "2026-09-09 14:10:26" : "进行中",
step: step.step,
hint: step.hint,
metrics: step.metrics,
});
if (step.done) {
clearInterval(timer);
timer = null;
busy = false;
toast("原型示意:强制重检已完成,列表稍后出现新批次。");
}
index += 1;
}
paint();
timer = setInterval(function () {
if (index >= forceSteps.length) return;
paint();
}, 900);
}
document.querySelectorAll("[data-preview]").forEach(function (button) {
button.addEventListener("click", function () {
show(button.getAttribute("data-preview"));
});
});
latestEl.addEventListener("click", function (event) {
if (event.target.closest("[data-force]")) startForce();
});
show("done");
})();
</script>
</body>
</html>
@@ -15,7 +15,7 @@
## 业务口径
- 销售一期:**每周二**增量检核上一个自然月;invoice 来自 HXJM `apa_file`;获取后写入类型目录再归入 `所有归档/{invoice号}/`。
- 销售一期:**每周二**增量检核上一个自然月;invoice 来自 HXJM `oma_file`;获取后写入类型目录再归入 `所有归档/{invoice号}/`。
- 销货放行申请单:一期模拟 OA 页面;后期换新接口。关联字段不完整时直接跳过。
- 采购二期:展示六类拟定文件规则;路径、主体来源和 Adapter 参数待确认,原型不执行采购检核。
- 批量缺件同时统计“缺件文件总数”和“缺件 `invoice` 数”;同一 `invoice` 缺多个文件时前者累计多个、后者只计一次。
@@ -1,8 +1,8 @@
# 立账凭证资料检核需求说明
> 文档版本:v1.9
> 更新时间:2026-09-08
> 状态:一期销售需求确认中;采购及其它业务方待后续 Profile 配置
> 文档版本:v1.14
> 更新时间:2026-09-14
> 状态:一期销售需求确认中;采购及其它业务方待后续 Profile 配置。PO 制式 PDF 由独立周批(周二 05:00)生成并上传;检核周批(周二 06:00)只扫描目录。ERP 取数 HXJM → TGHX,`TRIM(oma99)=TRIM(pmm99)`。
>
> 本文是本期需求权威。部署与冒烟见 [ops-checklist.md](ops-checklist.md)。旧共享盘存在性扫描、Chatflow Tool 与一票一状态表已移除,不得再按该口径扩展。
@@ -27,7 +27,7 @@
| 项目 | 规则 |
| -------- | ----------------------------------------------------------------------------------------------------------------------- |
| 执行频率 | 每周二执行一次(默认 06:00,Asia/Shanghai) |
| 执行频率 | **两段周批(Asia/Shanghai)**:周二 **05:00** 生成并上传 PO 订单 PDF;周二 **06:00** 检核上月附件。 |
| 检核期间 | 执行日的上一个自然月;例如 2026-08-18 执行,检核 2026-07 |
| 执行方式 | 增量执行:已成功归档且来源文件/规则未变化的 `invoice + 文件规则` 可跳过;新增、缺件、规则变更或来源变更的记录重新检核。归档目录已有同名文件时按「同名跳过」不覆盖 |
| 强制重检 | 支持对上一个自然月全量重检;不跳过任何主体。工作台「强制重检上月」入队 `force_all` |
@@ -44,7 +44,7 @@
新增业务方时优先新增或调整 Profile;只有新增外部系统或获取协议时才开发新的来源 Adapter。
销售一期主体清单**沿用旧方案 ERP 口径**:HXJM 套账只读查询 `apa_file`,`apa08` 为发票号、`apa09` 为发票日期,发票号非空。检核期间仍按上表取**上一个自然月**(例如周二跑批则检核上个月),不沿用旧实现的「当前月」。
销售一期主体清单来自 HXJM 套账只读查询 `oma_file`:`oma10` 为发票号码,须为至少 6 位字母或数字(如 `6975101806`、`EWZZ26090002`;排除 NULL、空串、`0`、中文备注),`oma02` 为帐款日期(DATE),且 `omaconf='Y'`(已确认)、`omavoid='N'`(未作废)、`oma64='1'`(状况码)、`oma00` 为 `11`/`12`/`13` 之一(帐款类别)。检核期间仍按上表取**上一个自然月**(例如周二跑批则检核上个月),不沿用旧实现的「当前月」。
### 3.3 结果状态
@@ -57,16 +57,17 @@
### 3.4 检核任务列表
检核任务列表是用户查看历史批次和进入详情的主入口。默认按最新批次展示,支持筛选后查看对应的执行明细、企业微信通知附件 Excel 和通知记录。
检核任务列表是用户查看历史批次和进入详情的主入口。默认展示**上一个自然月**的批次,支持把月份改为「全部」查看该年全部批次,再进入对应的执行明细、企业微信通知附件 Excel 和通知记录。
「最近一次检核」卡片放在 Tab 下方、筛选栏上方,只出现在「检核任务」Tab:展示**最近一批**(按执行时间,不跟年/月/状态筛选)的批次号、期间、模式、状态、进度、开始/完成时间、当前步骤,以及 invoice 总数 / 已归档 / 缺件文件 / 缺件 invoice。强制重检上月(仅管理员)放在这张卡片上,入队后进度在本卡更新。
| 区域 | 内容 |
| ------------ | ------------------------------------------------------------------------------------------------- |
| 顶部统计 | 当前筛选条件下的主体总数、已归档文件数、缺件文件数、缺件 `invoice` 数 |
| 筛选条件 | 资料所属期间、业务方、任务状态 |
| 任务列表字段 | 批次号、业务方、资料所属期间、执行时间、主体总数、已归档数、缺件文件数、缺件 `invoice` 数、状态 |
| 状态 | 缺件、已完成、技术失败、待配置 |
| 最近一次检核 | 最近一批进度与四指标;强制重检上月(全量 `force_all`,期间固定上一个自然月,不用筛选栏期间) |
| 筛选条件 | 资料所属期间(年必选、月可选「全部」;进页默认上一个自然月)、任务状态 |
| 任务列表字段 | 批次号、资料所属期间、执行时间、主体总数、缺件文件数、缺件 `invoice` 数、状态、失败原因 |
| 状态 | 排队中、执行中、缺件、完整、技术失败 |
| 操作 | 查看详情;进入该批次的执行记录,并可查看企业微信通知附件 Excel |
| 任务入口 | 支持新建任务、强制重检(仅上一个月);企微接收人从系统用户多选,可复用排程通知人选择器 |
### 3.5 企业微信发送记录
@@ -74,7 +75,7 @@
| 区域 | 内容 |
| -------- | --------------------------------------------------------------------------------------------- |
| 筛选条件 | 资料所属期间、发送状态 |
| 筛选条件 | 资料所属期间(与检核任务同一套年/月口径)、发送状态 |
| 列表字段 | 批次号、资料所属期间、invoice 总数、invoice 缺件数、缺件文件数、发送状态、未发送原因、接收人、发送时间、Excel |
| 操作 | 有附件时可下载该批 Excel;查看详情进入对应批次明细 |
@@ -99,7 +100,7 @@
| 文件类型 | 命名方式 | 获取方式 | 存放路径 | `invoice` 关联 | 扫描/查询条件 |
| -------------- | ------------------------------ | -------------------------- | --------------------------------------------- | --------------------------- | ---------------------- |
| PO 订单 | `{invoice号}-{订单号}.pdf` | ERP 查询对应 PO 后打印 PDF | `文档库/销售开票附件/{yyyy}/{MM}/PO订单/` | 以销售 `invoice` 反查 PO | **待确认**:查询字段、关联与打印方式 |
| PO 订单 | `{invoice号}-{订单号}.pdf` | 周二 05:00 独立排程按发票从 TGHX 取数生成制式 PDF 并上传到当月「PO订单」;06:00 检核只扫描该目录 | `文档库/销售开票附件/{yyyy}/{MM}/PO订单/` | `TRIM(HXJM.oma99)=TRIM(TGHX.pmm99)` → `pmm01` | **已确认**:发票 HXJM、采购单 TGHX。Job `accounting-voucher-po-print`(`SCH-ACCOUNTING-VOUCHER-PO-PRINT`)。同名跳过 |
| 报关资料 | `{invoice号}.pdf` | 固定目录扫描 | `文档库/销售开票附件/{yyyy}/{MM}/报关资料/` | 文件名含 `invoice` | 扫描上月对应类型目录 |
| 销货放行申请单 | `{invoice号}-{销货单号}.pdf` | OA 自定义报表逐条打印 PDF | `文档库/销售开票附件/{yyyy}/{MM}/销货单/` | OA 列表读取发票号、销货单号 | 见 5.1 |
| 发票 | `{invoice号}-{发票号}.pdf` | 固定目录扫描 | `文档库/销售开票附件/{yyyy}/{MM}/发票/` | 文件名含 `invoice` | 扫描上月对应类型目录 |
@@ -144,12 +145,29 @@ flowchart TD
| 步骤 | 操作与规则 |
| ---- | -------------------------------------------------------- |
| 1 | 以上月销售 `invoice` 清单为入口 |
| 2 | 在 ERP 查询并反查对应 PO 订单 |
| 3 | 每个 PO 订单打印并保存一个 PDF |
| 4 | 按 `invoice + 订单号` 命名,写入当月「PO订单」存放目录 |
| 5 | 再复制到「所有归档/{invoice号}/」 |
| 6 | **待确认**:ERP 查询字段、invoice 与 PO 关联、打印入口与 PDF 落盘方式 |
| 1 | 以上月销售 `invoice` 清单为入口(HXJM `oma_file.oma10`) |
| 2 | 在 **TGHX** 套账按 `TRIM(oma99)=TRIM(pmm99)` 反查采购单号 `pmm01`(多角贸易;见技术设计 §3.4.1) |
| 3 | 按 [technical-design.md §3.4](technical-design.md) 从 **TGHX** 的 `pmm_file`(头)、`pmn_file`(身)及码表取出制式 PDF 字段;不跑 TIPTOP 客户端打印 |
| 4 | 每个 PO 用 HXOPS 制式采购单生成一个 PDF(对照 apmr900) |
| 5 | 按 `{invoice号}-{订单号}.pdf` 命名,写入当月「PO订单」存放目录 |
| 6 | 再复制到「所有归档/{invoice号}/」 |
| 7 | 周检核只扫描类型目录,不在周二 runner 里生成 PDF |
制式 PDF:`save_po_order_pdf` 只写本地;写入文档库用 `publish_po_order_pdf`(`ErpPoPrintAdapter.upload_given`)。周二 05:00 排程 `accounting-voucher-po-print` 按上月发票取数并上传;06:00 检核只扫描「PO订单」目录。`invoice_no` 只出现在文件名,不印在采购单版面。年/月/「PO订单」目录没有就建。目标已有同名文件则跳过、不覆盖。
拿到 `pmm01` 之后的主表(业务可读摘要;完整对照见技术设计 §3.4):
| 业务栏 | 表.字段 |
| --- | --- |
| 采购单号 / 日期 / 单别 | `pmm01` / `pmm04` / `smydesc` |
| 付款条件 / 税种 / 价格条件 / 币种 | `pma02` / `gec02` / `pmm41`+`pnz02` / `pmm22` |
| 送货 / 账单地址 | `pme_file`(码为 `pmm10` / `pmm11`) |
| 供应商 | `pmm09`,名称地址电话传真来自 `pmc_file` |
| 公司抬头 | `zo_file`(`zo02`/`zo041`/`zo05`/`zo09`) |
| 明细:项次、料号、品名、规格、数量单位、单价金额 | `pmn02`/`pmn04`/`pmn041`/`ima021`/`pmn20`/`pmn07`/`pmn31`/`pmn31t`/`pmn88`/`pmn88t` |
| 到货日 | `pmn34`(原始到厂日期;不用 `pmn33`) |
| 请购单号 / 厂商料号 | `pmn24` / `pmn06` |
| 卤素 / 环保 | `ima_file.ta_ima02` / `ta_ima03`(码值转文案) |
### 5.3 通用存放与归档流程
@@ -186,11 +204,13 @@ flowchart TD
| 登录接口 | `POST {基址}/Login/_api/Login`,body:`LoginName` / `Pwd` |
| 目录/文件查询 | `POST {基址}/Api/_api/APS/Public/Item/Page`(`LibraryID`、`ParentFolderID`、分页) |
| 建文件夹 | `POST {基址}/Api/_api/APS/Public/Item/SaveFolder`(`LibraryID`、`ParentFolderID`、`LeafName`、`FieldValues`) |
| 上传附件 | `POST {基址}/Api/_api/DMS/Public/Attachment/Upload`(multipart 字段名 `file`),返回 `Data.ID` 作为 AttachmentID |
| 登记到目录 | `POST {基址}/Api/_api/APS/Public/Item/CreateFiles`(`ParentFolderID` 为当月「PO订单」FolderID;`Files[].LeafName` 带 `.pdf`;`Files[].AttachmentID` 来自 Upload) |
| 复制文件 | `POST {基址}/Api/_api/APS/Public/Item/Copy`(`ItemID` 数组、目标 `ParentFolderID`)。归档**禁止**使用 Move |
| 账号 | 复用现有 DMS 账号;用户名与密码只放环境变量/密钥注入,禁止写入代码、Profile JSON、Excel 或日志 |
| 库与目录 | 全公司只有一个文档库:`LibraryID` 与现网 `CONTRACT_DMS_LIBRARY_ID` 相同(`LibraryName` 为「文档库」)。「设备合同书」「销售开票附件」都是该库下的文件夹,**不要另配 LibraryID**。销售根目录单独配置 FolderID,**不得**复用合同根目录。现网销售根 FolderID 为 `727c3683-dcdb-4d62-a5b1-b164224162bc`(接口无 `FolderID` 字段,用条目 `ID` / `IDPath`) |
下载、建文件夹、复制到「所有归档」须走同一套已登录会话。归档只复制、不移动;目标已有同名文件则跳过。仍不把凭据写入需求正文。
下载、建文件夹、上传到类型目录、复制到「所有归档」须走同一套已登录会话。归档只复制、不移动;类型目录上传与归档复制均为同名跳过。仍不把凭据写入需求正文。
## 6. 批量缺件汇总与企业微信通知
@@ -237,18 +257,18 @@ flowchart TD
3. Excel 报告顶部可按资料所属期间选择年月,并单独展示执行时间;每个 `invoice` 一行,直接展示各必检文件为“有 / 缺件 / 未检核”和总体状态;全部必检文件均为“有”时状态为“完整”。
4. 企业微信每批仅发送一条缺件汇总通知,并提供本批 Excel 下载入口;完整 `invoice` 明细不在消息正文展开。
5. OA 关联字段不完整记录被直接丢弃,不进入异常、缺件、打印或归档结果。
6. 销售 invoice 清单、文档库(同一 LibraryID、销售独立根 FolderID、建文件夹/复制接口)、周任务星期二、企微选人界面已确认;ERP PO 反查与打印、OA 模拟页细节仍通过配置承接,不能把凭据写死在通用逻辑中。
6. 销售 invoice 清单、文档库(同一 LibraryID、销售独立根 FolderID、建文件夹/复制接口)、周任务星期二、企微选人界面已确认;ERP PO 取数:发票 HXJM、采购单 TGHX,关联 `TRIM(oma99)=TRIM(pmm99)` 已接线(独立抓取,见技术设计 §3.4);OA 模拟页细节仍通过配置承接,不能把凭据写死在通用逻辑中。
7. 归档复制采用「同名跳过」:目标目录已有同名文件不覆盖、不报缺件。
## 9. 待补充事项
| 待确认项 | 当前结论 | 仍缺什么 |
| --- | --- | --- |
| 销售 invoice 清单 | **已确认**:HXJM `apa_file.apa08/apa09`,期间为上一个月 | 无 |
| ERP 反查 PO 并打印 | **待确认** | 查询字段、关联、打印入口、PDF 保存 |
| 销售 invoice 清单 | **已确认**:HXJM `oma_file.oma10/oma02`,`oma10` 至少 6 位字母或数字,`omaconf='Y'`、`omavoid='N'`、`oma64='1'`、`oma00 IN (11,12,13)`,期间为上一个月 | 无 |
| ERP 反查 PO 并打印 | **打印、上传与取数已接线(周二 05:00 独立排程 `accounting-voucher-po-print`,06:00 检核不调用)**。采购单在 **TGHX**。关联 **已确认**:`TRIM(HXJM.oma99)=TRIM(TGHX.pmm99)`。`oma99` 为空时才走 `oma16` 备用。到货日 `pmn34`。详见 [technical-design.md §3.4](technical-design.md) | 制表者;卤素/环保是否拆列。原始编号优先 `ta_ima11` 否则 `pmn24`(业务仍略含糊)。`oma99` 为空的备用路径尚未用空值票验证 |
| OA 销货放行单 | **已确认方向**:一期只做模拟页面;后期对接新 OA 接口 | 模拟登录、分页、打印落盘细节 |
| 文档管理系统 | **已确认**:同一文档库 LibraryID;销售根 FolderID=`727c3683-dcdb-4d62-a5b1-b164224162bc`;建文件夹 `SaveFolder`、复制 `Item/Copy` | 无 |
| 文档管理系统 | **已确认**:同一文档库 LibraryID;销售根 FolderID=`727c3683-dcdb-4d62-a5b1-b164224162bc`;建文件夹 `SaveFolder`、上传 `Attachment/Upload` + `Item/CreateFiles`、复制 `Item/Copy`;同名跳过 | 无 |
| 企微接收人 | **已确认产品**:界面从系统用户多选;人可以后配 | 业务最终勾选哪些人 |
| 周任务 | **已确认**:每周二(默认 06:00 上海时区) | 无 |
| 周任务 | **已确认**:周二 05:00 生成 PO PDF;周二 06:00 检核(上海时区) | 无 |
| 销售类型目录名 | **已确认固定**:`PO订单`、`报关资料`、`销货单`、`发票`、`报关单`、`提单` | 无 |
| 重复文件策略 | **已确认**:同名跳过 | 目标 `所有归档/{invoice}/` 已有相同文件名则不覆盖,记已归档 |
| 重复文件策略 | **已确认**:同名跳过 | 目标 `所有归档/{invoice}/` 或类型目录「PO订单」已有相同文件名则不覆盖 |
@@ -0,0 +1,46 @@
"""
docs/features/accounting-voucher-check/hxops-po-sample.py
用途:用对照样张数据调用生产渲染器,生成「HXOPS 制式采购单」供与 apmr900 并排看。
依赖:backend app.services.voucher_check.po_order(需在 backend 目录或 PYTHONPATH 含 backend)。
逻辑:不再维护第二套画表代码;正式落盘请用 save_po_order_pdf,文件名为 {invoice}-{订单号}.pdf。
"""
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[3]
BACKEND = ROOT / "backend"
if str(BACKEND) not in sys.path:
sys.path.insert(0, str(BACKEND))
from app.services.voucher_check.po_order import save_po_order_pdf, sample_po_order_document # noqa: E402
def main() -> None:
"""
生成样张 PDF。
核心逻辑:生产命名为 INV-SAMPLE-5201-1605280003.pdf,并复制一份对照文件名便于并排打开。
"""
document = sample_po_order_document()
targets = [
ROOT / "docs" / "features" / "accounting-voucher-check",
Path(r"e:\Work\Agent\立账凭证"),
]
for folder in targets:
try:
path = save_po_order_pdf(document, folder)
alias = folder / "采购单-hxops-sample.pdf"
alias.write_bytes(path.read_bytes())
print(path)
print(alias)
except PermissionError:
print(f"skip locked: {folder}")
except OSError as exc:
print(f"skip {folder}: {exc}")
if __name__ == "__main__":
main()
@@ -1,6 +1,6 @@
# 立账凭证检核 — 部署验收清单
> 覆盖当前引擎:每周二检核**上一个自然月**、HXJM `apa_file` 发票清单、文档库类型目录扫描与按票归档(Copy,同名跳过)、单文件结果与企微批次汇总。
> 覆盖当前引擎:每周二 **05:00** 生成 PO PDF 并上传到「PO订单」,**06:00** 检核**上一个自然月**、HXJM `oma_file` 发票清单、文档库类型目录扫描与按票归档(Copy,同名跳过)、单文件结果与企微批次汇总。TGHX 只读授权见 §2。
>
> 产品需求见 [demand.md](demand.md),设计见 [technical-design.md](technical-design.md)。
>
@@ -10,9 +10,9 @@
| 项 | 值 |
| --- | --- |
| Job key | `accounting-voucher-check` |
| 默认排程号 | `SCH-ACCOUNTING-VOUCHER-CHECK` |
| Cron | `0 6 * * 2`(Asia/Shanghai,每周二 06:00) |
| Job key | `accounting-voucher-check`(检核)· `accounting-voucher-po-print`(PO 生成) |
| 默认排程号 | `SCH-ACCOUNTING-VOUCHER-CHECK` · `SCH-ACCOUNTING-VOUCHER-PO-PRINT` |
| Cron | 检核 `0 6 * * 2`;PO 生成 `0 5 * * 2`(Asia/Shanghai,周二,生成早于检核) |
| 检核期间 | 上一个自然月 |
| 销售类型目录 | PO订单、报关资料、销货单、发票、报关单、提单 |
| 引擎表 | `voucher_check_profiles` / `runs` / `subjects` / `file_results` / `notifications` |
@@ -40,8 +40,8 @@ flask db upgrade
```sql
SELECT id, schedule_no, name, cron_expr, platform_api_path, enabled, next_run_at
FROM schedule_tasks
WHERE schedule_no = 'SCH-ACCOUNTING-VOUCHER-CHECK'
OR platform_api_path = 'accounting-voucher-check';
WHERE schedule_no IN ('SCH-ACCOUNTING-VOUCHER-CHECK', 'SCH-ACCOUNTING-VOUCHER-PO-PRINT')
OR platform_api_path IN ('accounting-voucher-check', 'accounting-voucher-po-print');
```
- [ ] 若无用户时尚无种子:先建管理员账号,再重启 `hxops-backend`(启动钩子会补建)
@@ -67,6 +67,9 @@ VOUCHER_CHECK_DMS_ROOT_FOLDER_ID=<sales-root-folder-id>
# VOUCHER_CHECK_DMS_LIBRARY_ID=
# VOUCHER_CHECK_DMS_USERNAME=
# VOUCHER_CHECK_DMS_PASSWORD=
# 可选:制式采购单中文字体(默认 Windows 宋体或镜像 fonts-noto-cjk)
# VOUCHER_CHECK_PO_FONT_PATH=
```
检查:
@@ -74,16 +77,37 @@ VOUCHER_CHECK_DMS_ROOT_FOLDER_ID=<sales-root-folder-id>
- [ ] `hxops-backend` 与 `hxops-schedule-worker` 均注入相同 `VOUCHER_CHECK_ERP_*` / `VOUCHER_CHECK_DMS_*`
- [ ] 密码未出现在 `job_params`、日志样例、Excel 字段中
- [ ] 不再配置 `VOUCHER_CHECK_LOCAL_ROOT` / `VOUCHER_CHECK_SHARE_*`(旧共享盘方案已移除)
- [ ] 只读账号除 HXJM `oma_file` 外,还须能读 **TGHX** 采购单及码表、以及 HXJM 备用出货/订单表(周二 05:00 PO 生成排程需要;06:00 检核仍不查 TGHX)。DBA 对只读用户执行(把 `<readonly-user>` 换成实际账号,勿把密码写进工单附件以外的仓库):
```sql
-- HXJM:发票头;oma99 为空时备用
GRANT SELECT ON HXJM.oma_file TO <readonly-user>;
GRANT SELECT ON HXJM.oga_file TO <readonly-user>;
GRANT SELECT ON HXJM.oea_file TO <readonly-user>;
-- TGHX:采购单头身 + apmr900 码表
GRANT SELECT ON TGHX.pmm_file TO <readonly-user>;
GRANT SELECT ON TGHX.pmn_file TO <readonly-user>;
GRANT SELECT ON TGHX.smy_file TO <readonly-user>;
GRANT SELECT ON TGHX.pmc_file TO <readonly-user>;
GRANT SELECT ON TGHX.pma_file TO <readonly-user>;
GRANT SELECT ON TGHX.gec_file TO <readonly-user>;
GRANT SELECT ON TGHX.pnz_file TO <readonly-user>;
GRANT SELECT ON TGHX.azi_file TO <readonly-user>;
GRANT SELECT ON TGHX.ima_file TO <readonly-user>;
GRANT SELECT ON TGHX.pme_file TO <readonly-user>;
GRANT SELECT ON TGHX.zo_file TO <readonly-user>;
```
---
## 3. 排程与通知配置
- [ ] 管理后台打开任务「立账凭证检核(周批)」
- [ ] `enabled=true`,时区 `Asia/Shanghai`,Cron `0 6 * * 2`
- [ ] 管理后台打开任务「立账凭证检核(周批)」与「立账凭证 PO 订单生成(周批)」
- [ ] 二者 `enabled=true`,时区 `Asia/Shanghai`
- [ ] PO 生成 Cron `0 5 * * 2`;检核 Cron `0 6 * * 2`(生成必须早于检核)
- [ ] `kb_sync_enabled=false`(本域不需要进知识库)
- [ ] `notify_enabled=true`,`notify_user_ids_json` 填已绑定企微的用户;未配置则不发
- [ ] `job_params.profile_code=sales`,`scope_code=HXJM`
- [ ] 两任务 `job_params.profile_code=sales`,`scope_code=HXJM`
---
@@ -105,8 +129,10 @@ VOUCHER_CHECK_DMS_ROOT_FOLDER_ID=<sales-root-folder-id>
### 4.3 工作台记录页
- [ ] 打开 `/workspace/accounting-voucher-check`
- [ ] 「检核任务」可按月/状态筛选,分页可用
- [ ] 「企微发送记录」可按月/发送状态筛选,能看到接收人、未发送原因与 Excel 下载入口
- [ ] 「检核任务」Tab 下方有「最近一次检核」卡片(不跟年/月/状态筛选);排队/执行中进度会更新
- [ ] 「强制重检上月」在卡片上,仅管理员可见;确认后本卡切到排队/执行中
- [ ] 「检核任务」可按年/月/状态筛选(进页默认上月,月份「全部」看该年),分页可用
- [ ] 「企微发送记录」可按年/月/发送状态筛选,能看到接收人、未发送原因与 Excel 下载入口
- [ ] 「查看详情」进入 `/workspace/accounting-voucher-check/runs/:runId`(`runId` 为 ScheduleRun.id)
### 4.4 文档库 / ERP 故障
@@ -114,20 +140,24 @@ VOUCHER_CHECK_DMS_ROOT_FOLDER_ID=<sales-root-folder-id>
- [ ] DMS 或 ERP 不可用时批次 `failed`,不得把空结果批量判为缺件
- [ ] 企微失败告警到达(若开启)
### 4.5 PO 订单生成排程(周二 05:00)
- [ ] 只读账号已 GRANT TGHX(见 §2)
- [ ] 管理台可见 `SCH-ACCOUNTING-VOUCHER-PO-PRINT`,Cron 早于检核
- [ ] 「立即执行」后文档库 `销售开票附件/{年}/{月}/PO订单/` 出现 `{发票}-{pmm01}.pdf`(同名跳过)
- [ ] 检核周批日志中**没有** `fetch_po_documents_for_invoices`;PO 排程日志关键字 `[voucher-po-print]`
- [ ] 工作台「最近一次检核」卡片仍只显示 `accounting-voucher-check`,不被 PO 生成排程抢入口
---
## 5. 在 jobs 表识别立账凭证检核
## 5. 在 jobs 表识别立账凭证排程
平台排程(含立账凭证)仍走统一 `schedule` 队列,**`domain`/`job_type` 会一直是 `schedule` / `schedule_run`**,这是 worker 认领约定,不要按这两列区分业务。
平台排程仍走统一 `schedule` 队列,**`domain`/`job_type` 会一直是 `schedule` / `schedule_run`**。
升级后新入队的 Job:
| 列 | 立账凭证检核示例 |
| --- | --- |
| `business_ref` | `schedule_run:{id}:accounting-voucher-check` |
| `payload_json.platform_api_path` | `accounting-voucher-check` |
| `payload_json.task_name` | `立账凭证检核` |
| `message` | `立账凭证检核等待后台执行` |
| 列 | 检核 | PO 生成 |
| --- | --- | --- |
| `business_ref` | `schedule_run:{id}:accounting-voucher-check` | `schedule_run:{id}:accounting-voucher-po-print` |
| `payload_json.platform_api_path` | `accounting-voucher-check` | `accounting-voucher-po-print` |
```sql
SELECT id, status, business_ref, message, payload_json
@@ -136,13 +166,16 @@ SELECT id, status, business_ref, message, payload_json
AND job_type = 'schedule_run'
AND (
business_ref LIKE '%:accounting-voucher-check'
OR payload_json->>'platform_api_path' = 'accounting-voucher-check'
OR business_ref LIKE '%:accounting-voucher-po-print'
OR payload_json->>'platform_api_path' IN (
'accounting-voucher-check', 'accounting-voucher-po-print'
)
)
ORDER BY id DESC
LIMIT 20;
```
Worker 日志关键字:`[voucher-check]` 或 `[schedule-run] name=立账凭证检核 path=accounting-voucher-check`。
Worker 日志关键字:`[voucher-check]`(检核)或 `[voucher-po-print]`(PO 生成)。
---
@@ -0,0 +1,43 @@
{
"invoice_no": "INV-SAMPLE",
"po_no": "5201-1605280003",
"po_date": "2016/5/28",
"po_type": "原料采购单",
"pay_term": "月结一个月",
"tax_type": "进项(17%含税)",
"price_term": "A01 取核价单价",
"currency": "RMB",
"ship_address": "",
"bill_address": "",
"vendor_code": "VCCD00013",
"vendor_name": "北川科技(苏州)有限公司",
"vendor_tel": "0512-62810369",
"vendor_fax": "0512-62810368",
"vendor_addr": "苏州市工业园区胜浦分区银胜路61号",
"company_name": "苏州和信精密科技有限公司",
"company_address": "江苏省苏州市吴江区经济开发区山湖西路789号",
"company_phone": "0512-63136988",
"company_fax": "",
"maker": "AI",
"untax_total": "4,455.50",
"tax_total": "5,212.94",
"lines": [
{
"seq": "1",
"item_no": "3450541801",
"name": "FRAME CUBE CORNER",
"spec": "H20*W36.5*L36.7",
"qty": "730",
"unit": "PCS",
"arrive": "2016/6/16",
"origin_no": "3301-1605260004",
"version": "-0001",
"untax_price": "3.350000",
"tax_price": "3.919500",
"untax_amt": "2,445.50",
"tax_amt": "2,861.24",
"halogen": "RoHS",
"vendor_item": "3450541801"
}
]
}
@@ -1,8 +1,8 @@
# 立账凭证资料检核技术设计
> 文档版本:v2.3
> 更新时间:2026-09-08
> 状态:销售一期引擎已落地;ERP PO / OA 打印仍待接线
> 文档版本:v2.11
> 更新时间:2026-09-14
> 状态:销售一期引擎已落地。周二 05:00 `accounting-voucher-po-print` 从 TGHX 取数生成 PO PDF 并上传;周二 06:00 检核只扫描目录。OA 打印仍待接线
> 需求基线:[demand.md](demand.md)
>
> 本文替代旧实现「当月 + 单一共享盘 + 固定文件名存在性」。旧表、共享盘扫描与 Chatflow Tool 已删除,不得按旧口径扩展。
@@ -58,7 +58,7 @@ business_profiles/
| 配置项 | 说明 |
| -------------------------------------- | ------------------------------------------------------------------------------------------------- |
| `profile_code` / `profile_version` | 业务方及发布版本,例如 `sales:v1` |
| `subject_adapter` | 获取本期 `invoice` 主体清单。销售一期:HXJM `apa_file`(`apa08`/`apa09`),期间为上一个月 |
| `subject_adapter` | 获取本期 `invoice` 主体清单。销售一期:HXJM `oma_file`(`oma10` 至少 6 位字母或数字、`oma02` 帐款日期,`omaconf='Y'`、`omavoid='N'`、`oma64='1'`、`oma00` 为 11/12/13),期间为上一个月 |
| `file_rules` | 必检标识、命名模板、关联字段、来源 Adapter、查询/扫描条件、临时/归档模板 |
| `notification` | 企业微信接收人、启用开关、模板、去重策略 |
| `incremental_policy` | 指纹字段、可跳过状态、强制重检规则 |
@@ -75,6 +75,165 @@ business_profiles/
Adapter 不负责归档、Excel 或通知;引擎不理解 ERP/OA 的具体页面、SQL、目录规则。
### 3.3 PO 订单制式 PDF
不调用 TIPTOP 客户端打印。给定一张 PO 的字段后,由 HXOPS 按 Crystal `apmr900` 对照样张生成 PDF。
| 项 | 约定 |
| --- | --- |
| 本地落盘 | `save_po_order_pdf`;Adapter `ErpPoPrintAdapter.render_given` |
| 上传文档库 | `publish_po_order_pdf`;Adapter `ErpPoPrintAdapter.upload_given`。目标 `销售开票附件/{yyyy}/{MM}/PO订单/`;年/月/类型目录没有就 `SaveFolder` |
| 上传接口 | 现网「新建文件」:`Attachment/Upload`(multipart `file` → `Data.ID`)再 `Item/CreateFiles`(`ParentFolderID` + `Files[].AttachmentID` / `LeafName` 带 `.pdf`) |
| 同名 | 类型目录已有相同 `LeafName` 则跳过、不覆盖(与归档 Copy 一致) |
| 命令行 | 在 `backend/` 执行 `python -m app.services.voucher_check.po_order --out-dir DIR [--json FILE.json|--sample|--invoice 发票号]`(只出本地 PDF,不上传) |
| 文件名 | `{invoice_no}-{po_no}.pdf`;`invoice_no` 只用于命名,不印在采购单版面 |
| 数据 | 给定 `PoOrderDocument` / JSON,或 `fetch_po_documents_for_invoices` / `--invoice` 从 Oracle 组装;`po_order` 模块不要写 SQL |
| 周任务 | 检核仍只扫描「PO订单」目录;`erp_po_print.fetch` 保持 `wired=False`。生成/上传走独立排程 `accounting-voucher-po-print`(周二 05:00) |
| 字体 | 默认 Windows 宋体或镜像内 `fonts-noto-cjk`;可选 `VOUCHER_CHECK_PO_FONT_PATH` |
对照样张数据在 `po_order/sample.py`,仅供版式核对。
### 3.4 ERP 采购单取数(对照 apmr900;独立抓取已接线)
对照现场 TIPTOP 打印作业 `apmr900.4gl`(採購單)。销售发票在 **HXJM**;对应采购单在 **TGHX**(多角贸易抛转后的采购厂,不是 HXJM 自己的 `pmm_file`,也不是 HOX)。拿到 `TGHX.pmm01` 之后按本节填 `PoOrderDocument`;**不要**调 TIPTOP 客户端打印。码表(`pmc`/`pme`/`smy`/`zo` 等)随采购单走 **TGHX**。
实现:`erp_po_repository.fetch_po_documents_for_invoices`;Adapter `fetch_documents` / `upload_given`。由独立排程 **`accounting-voucher-po-print`(默认周二 05:00)** 调用,**不要**从检核 runner(06:00)调用,也**不要**把 `wired` 改成 `True`。只读账号需 GRANT 见 [ops-checklist.md](ops-checklist.md)。
#### 3.4.1 入口与关联
销售发票号 `oma10` **不会**写在采购单上。两边靠同一条多角流程序号:
```text
HXJM.oma_file.oma10 发票号码(检核主体)
│
▼
HXJM.oma_file.oma99 多角序号
│ TRIM 后等值(已用样本验证)
▼
TGHX.pmm_file.pmm99 多角贸易流程序号
│
▼
TGHX.pmm_file.pmm01 采购单号 → 文件名 {invoice}-{pmm01}.pdf
```
**已验证样本**(2026-09-14):发票 `EWZZ26090002`(`oma00=12` 出货应收,帐款单 `R012-2609010003`,出货单 `oma16=8520-2609010002`)→ `oma99` / `pmm99` 均为 `S004-26090001` 一类值(中间可能有空格,JOIN 必须 `TRIM`)→ TGHX 采购单 `5220-2609010001`,`pmm02=TRI`,`pmm901=Y`,`pmm904=S004`。本样本一对一。该票 `oma66=HXJM`,**不能**用 `oma66` 判断采购单套账。
| 步骤 | 来源 | 字段 | 状态 |
| --- | --- | --- | --- |
| 本期发票清单 | `HXJM.oma_file` | `oma10` / `oma02`;过滤与主体 Adapter 相同 | 已确认 |
| 采购单套账 | `TGHX.pmm_file` / `TGHX.pmn_file` | 销售开票附件要印的 PO 在 TGHX | **已确认** |
| 发票 → 采购单号 | `TRIM(HXJM.oma99) = TRIM(TGHX.pmm99)` | 得到 `pmm01`。JOIN 前两边都 TRIM(流程序号可能含空格) | **已确认** |
| `oma99` 为空 | `oma16` 备用 | 类别 12/13:`HXJM.oga_file.oga99`;类别 11:`HXJM.oea_file.oea99`;再对 `TGHX.pmm99`。本样本 `oma99` 有值,备用路径尚未跑过 | 仅当 `oma99` 空时使用 |
| 多角辅助栏 | `pmm901` / `pmm02` / `pmm904` | 样本为 `pmm901='Y'`、`pmm02='TRI'`、流程 `S004`。不要用 `oma66` 当套账 | 核对用,不是单号 |
| 一票几张 PO | 本样本 1 张 | 实现仍按一票可多张:每个 `pmm01` 一个 PDF `{invoice}-{pmm01}.pdf` | 本样本 1:1;多单时按 1:N 出文件 |
| 文件名中的订单号 | `TGHX.pmm01` | → `PoOrderDocument.po_no` | 已确认 |
取数示例(与样本同一口径):
```sql
SELECT oma01, oma00, oma10, oma16, oma66, oma99
FROM HXJM.oma_file
WHERE TRIM(oma10) = :invoice
AND omaconf = 'Y' AND omavoid = 'N' AND oma64 = '1';
SELECT pmm01, pmm02, pmm09, pmm18, pmm25, pmm99, pmm901, pmm904
FROM TGHX.pmm_file
WHERE TRIM(pmm99) = TRIM(:oma99)
AND pmm18 != 'X'
AND pmmacti = 'Y'
AND pmm02 != 'BKR';
```
#### 3.4.2 主查询(与 apmr900 主 SQL 一致)
头 `pmm_file` 内连身 `pmn_file`(`pmm01 = pmn01`),再左连码表。建议排序 `pmm01, pmn02`。
apmr900 固定过滤(**已确认沿用**,含未审核单;`pmm18` 确认码为 Y/N/X,只排除作废 X):
- `pmm18 != 'X'`(未作废;Y 已确认、N 未确认都出)
- `pmmacti = 'Y'`(有效)
- `pmm02 != 'BKR'`(排除备用金采购)
- `gec011 = '1'`(进项税别;与 `gec_file` 连上后该条件实际接近内连)
不额外要求 `pmm25` 已核准/已发出。
| 表 | 关联 | 取出字段 | 用途 |
| --- | --- | --- | --- |
| `pmm_file` | 主表 | `pmm01` 采购单号、`pmm04` 采购日期、`pmm09` 厂商编号、`pmm10` 送货地址码、`pmm11` 账单地址码、`pmm20` 付款条件码、`pmm21` 税别码、`pmm22` 币别、`pmm41` 价格条件码、`pmm43` 税率 | 头栏 |
| `pmn_file` | `pmn01 = pmm01` | `pmn02` 项次、`pmn04` 料号、`pmn041` 品名规格、`pmn06` 厂商料号、`pmn07` 单位、`pmn20` 数量、`pmn24` 请购单号、`pmn25` 请购项次、`pmn31`/`pmn31t` 未税/含税单价、`pmn33` 交货日、`pmn34` 到厂日、`pmn88`/`pmn88t` 未税/含税金额、`pmnud02` 版本 | 明细 |
| `smy_file` | `pmm01 LIKE smyslip \|\| '-%'` | `smydesc` 单别说明 | `po_type`(如「原料采购单」) |
| `pmc_file` | `pmc01 = pmm09` | `pmc081` 供应商全名、`pmc091` 地址、`pmc10` 电话、`pmc11` 传真 | 供应厂商 |
| `pma_file` | `pma01 = pmm20` | `pma02` | `pay_term` |
| `gec_file` | `gec01 = pmm21` 且 `gec011 = '1'` | `gec02` | `tax_type`(说明里通常已含税率,如「进项(17%含税)」;不必再拼 `pmm43`) |
| `pnz_file` | `pnz01 = pmm41` | `pnz02` | 价格条件说明;`price_term` 建议 `pmm41` + 空格 + `pnz02`(样张「A01 取核价单价」) |
| `azi_file` | `azi01 = pmm22` | `azi03`/`azi04`/`azi05` | 单价/金额/合计小数位,格式化用,不印字段名 |
| `ima_file` | `ima01 = pmn04` | `ima021` 规格、`ta_ima02` 卤素管控、`ta_ima03` 环保等级、`ta_ima11` 原始编号(现场备忘列名) | 明细规格、环保列、原始编号候选 |
`ta_ima02` / `ta_ima03` 在 apmr900 里已转成文案后再进 Crystal:
| 字段 | 码值 | 打印文案 |
| --- | --- | --- |
| `ta_ima02` | `1` / `2` | 无卤 / 不管控 |
| `ta_ima03` | `1` / `0` / `9` | RoHS / 非环保 / ERS |
#### 3.4.3 循环内补查(每行或每单一次)
| 表 | 条件 | 取出字段 | 用途 |
| --- | --- | --- | --- |
| `pme_file` | `pme01 = pmm10` | `pme031`~`pme035` | `ship_address`;空段丢掉再拼接 |
| `pme_file` | `pme01 = pmm11` | `pme031`~`pme035` | `bill_address`;同上 |
| `zo_file` | `zo01 = '1'`(简体),**TGHX** 套账 | `zo02` 公司名、`zo041` 地址、`zo05` 电话、`zo09` 传真 | `company_*`。抬头是采购单所属厂(TGHX),不一定是苏州 HXJM |
| `gfe_file` | `gfe01 = pmn07` 或 `pmn86` | `gfe03` | 数量小数位 |
合计:同一 `pmm01` 对 `pmn88`、`pmn88t` 求和,格式化后写入 `untax_total` / `tax_total`(apmr900 在 4gl 里先算好再进 Crystal)。
#### 3.4.4 `PoOrderDocument` 对照(一期 PDF 实际用到的)
`invoice_no` 只用于文件名,不从采购单表取,沿用主体清单的 `oma10`。
| `PoOrderDocument` / `PoOrderLine` | ERP | 说明 |
| --- | --- | --- |
| `po_no` | `pmm01` | |
| `po_date` | `pmm04` | 展示格式待与样张对齐(样张 `2016/5/28`) |
| `po_type` | `smydesc` | |
| `pay_term` | `pma02` | |
| `tax_type` | `gec02` | |
| `price_term` | `pmm41` + `pnz02` | |
| `currency` | `pmm22` | |
| `ship_address` / `bill_address` | `pme031`~`pme035` | 分别按 `pmm10` / `pmm11` |
| `vendor_code` / `vendor_name` / `vendor_tel` / `vendor_fax` / `vendor_addr` | `pmm09` / `pmc081` / `pmc10` / `pmc11` / `pmc091` | |
| `company_name` / `company_address` / `company_phone` / `company_fax` | `zo02` / `zo041` / `zo05` / `zo09` | `zo12` 是否覆盖电话待确认 |
| `maker` | **待确认** | 现场打印通常是当前用户;批处理没有登录人。候选:`pmm12` 采购员姓名(需再连员工表)或固定文案 |
| `untax_total` / `tax_total` | `SUM(pmn88)` / `SUM(pmn88t)` | |
| `seq` | `pmn02` | |
| `item_no` | `pmn04` | |
| `name` | `pmn041` | |
| `spec` | `ima021` | |
| `qty` / `unit` | `pmn20` / `pmn07` | 一期按采购数量/单位。计价 `pmn87`/`pmn86`、双单位 `pmn80`~`pmn85` 待确认是否要印 |
| `arrive` | `pmn34` | **已确认**:版面「到货日」用原始到厂日期。不要用 `pmn33`(发货日)或 `pmn35`~`pmn37` |
| `origin_no` | `ta_ima11` 或 `pmn24` | **待确认**。现场备忘把「原始编号」写成 `ima.ta_ima11`;`pmn24` 是请购单号,样张 `3301-…` 也像请购单 |
| `vendor_item` | `pmn06` | 厂商料号 |
| `untax_price` / `tax_price` / `untax_amt` / `tax_amt` | `pmn31` / `pmn31t` / `pmn88` / `pmn88t` | 按 `azi03`/`azi04` 格式化 |
| `halogen` | `ta_ima02` 和/或 `ta_ima03` | 版面有「卤素管控」「环保等级」两列,模型目前一个字段;样张 `RoHS` 对应 `ta_ima03`。是否拆字段待确认 |
| `version` | `pmnud02` | 现场备忘「自订栏位-文字 = 版本」;apmr900 主查询已取 `pmnud02` |
| `extra_spec` | **待确认** | 表头「厂商料号额外品名规格说明」在 apmr900 里来自 `pmq_file`(开关 `tm.d`) |
**到货日**:HXOPS 印 `pmn34`(原始到厂日期)。apmr900 的 4gl 虽把 `pmn33` 也塞进 Crystal,本取数不采用。`pmn35`~`pmn37` 不要取。
#### 3.4.5 一期默认不取(apmr900 有、当前 PDF 没有)
未确认前不要查、不要扩模型:
| 表 | apmr900 用途 |
| --- | --- |
| `pmo_file` | 单据前/后、项次前/后特别说明 |
| `pmq_file` | 厂商料号额外品名规格(`tm.d = 'Y'`) |
| 历史 `pmm_file`+`pmn_file` | 同料号最近采购记录(`tm.c` 笔数) |
| `pmk_file` + `gem_file` | 请购部门(`pmn24` → `pmk13` → `gem02`) |
| `pmmud01`、`pmn100`、`ta_pmm03`/`ta_pmm04`/`ta_pmm05` | 现场加过进 CR,当前版面未用 |
打印次数 `pmmprno + 1` 是 TIPTOP 客户端副作用;HXOPS 只读,**不要**回写。
## 4. 周度上月增量流程
```mermaid
@@ -162,14 +321,17 @@ ERP/OA 打印或目录扫描的成功文件先写入类型存放目录;完成
### 6.3 检核任务列表
检核任务列表以 `voucher_check_runs` 的批次统计快照为数据源,不在列表查询时重新汇总单文件结果。支持按 `period_month`、`profile_code` 和批次状态筛选,按执行时间倒序分页。
检核任务列表以 `voucher_check_runs` 的批次统计快照为数据源,不在列表查询时重新汇总单文件结果。`period` 支持 `YYYY`(该自然年)或 `YYYY-MM`(该自然月),并可按 `profile_code` 和批次状态筛选,按执行时间倒序分页。工作台进页默认上一个自然月;月份选「全部」时传 `YYYY`。建批前失败的 `ScheduleRun` 使用同一期间口径。企微发送记录列表共用该 `period` 参数。
「最近一次检核」走独立接口 `GET /api/workspace/accounting-voucher-check/runs/latest`:按 `ScheduleRun.id` 倒序取该平台最近一条排程,join 引擎快照与 `response_summary_json.current_step`,**不跟**列表 `period`/`status`。排队中、执行中的排程必须按 `queued`/`running` 返回,不得套用建批前失败的 `technical_failed` 映射。进度百分比由步骤码估算(`scan_dms` 用已处理 invoice / 总数插值),不是精确字节进度。
| 列/操作 | 数据来源或行为 |
| --------------------------------------------------- | -------------------------------------------------------------------------- |
| 最近一次检核卡片 | `GET .../runs/latest`;强制重检按钮仅 admin,入队后前端轮询本接口 |
| 批次号、业务方、资料所属期间、执行时间 | `voucher_check_runs` |
| 主体总数、已归档数、缺件文件数、缺件 `invoice` 数 | 批次结束时固化的统计快照 |
| 状态 | `completed`、`missing`、`technical_failed`、`draft` 的前端业务映射 |
| 查看详情 | 携带 `run_id` 跳转执行记录;详情读取 `voucher_check_file_results` |
| 主体总数、已归档数、缺件文件数、缺件 `invoice` 数 | 批次结束时固化的统计快照;执行中可来自 `response_summary_json.voucher_check` |
| 状态 | 列表:`completed`、`missing`、`technical_failed`;卡片另含 `queued`、`running` |
| 查看详情 | 携带 `schedule_run_id` 跳转执行记录;详情读取 `voucher_check_file_results` |
| 通知附件 | 通过该批次的 Excel 文件标识进入企业微信通知附件 Excel 预览或下载 |
## 7. 企业微信通知附件 Excel 设计
@@ -201,11 +363,11 @@ ERP/OA 打印或目录扫描的成功文件先写入类型存放目录;完成
## 9. 实施顺序
1. **已做**:Profile、文件规则、批次/单文件结果表、上月期间、周二 cron、销售 DMS 只读、directory_scan、缺件聚合、批次企微、工作台任务列表与企微发送记录。
1. **已做**:Profile、文件规则、批次/单文件结果表、上月期间、周二 cron、销售 DMS 只读、directory_scan、缺件聚合、批次企微、工作台任务列表、最近一次检核卡片与企微发送记录。
2. **已做**:`dms_archive` 建文件夹(`SaveFolder`)+ 复制(`Item/Copy`),重复策略同名跳过;命中文件记 `archived`。
3. **已预留**:`erp_po_print`、`oa_sales_release` Adapter,周任务不调用。
4. 接入 ERP PO 打印与 OA 模拟页,作为独立抓取任务写入类型目录。
5. 采购通过新增 Profile 和 Adapter 参数接入。
3. **已做**:制式采购单 PDF(`save_po_order_pdf`)及上传到当月「PO订单」目录(`publish_po_order_pdf` / `upload_given`),命名 `{invoice}-{order_no}.pdf`,同名跳过;`erp_po_print.fetch` 与 OA 仍占位,检核 runner 不调用生成或上传。
4. **已做**:ERP PO 取数 + 独立周批 `accounting-voucher-po-print`(周二 05:00,早于检核 06:00)。检核 runner 不要生成或上传 PDF。关联:`TRIM(HXJM.oma99)=TRIM(TGHX.pmm99)`。
5. 接入 OA 模拟页;采购通过新增 Profile 和 Adapter 参数接入。
## 10. 验收重点
@@ -228,14 +390,14 @@ ERP/OA 打印或目录扫描的成功文件先写入类型存放目录;完成
| 旧实现 | 当前实现 |
| ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- |
| 每日 `0 6 * * *`,检核**当前自然月** | **每周二** `0 6 * * 2`,检核**上一个自然月** |
| HXJM `apa_file.apa08/apa09` 拉发票清单 | **沿用该口径**,仅把期间改为上一个月 |
| 共享盘 `vouche/{YYYY}/{MM}/{invoice_no}/` 只做文件名存在性 | 从文档库类型目录扫描(ERP/OA 打印一期未接线),先落入 `销售开票附件/{年}/{月}/{类型}/`,再归档到同月 `所有归档/{invoice}/` |
| HXJM `apa_file.apa08/apa09` 拉发票清单 | 改为 `oma_file`:`oma10` 发票号码、`oma02` 帐款日期;仅 `omaconf='Y'`、`omavoid='N'`、`oma64='1'`、`oma00` 为 11/12/13;期间为上一个月 |
| 共享盘 `vouche/{YYYY}/{MM}/{invoice_no}/` 只做文件名存在性 | 从文档库类型目录扫描(PO 由 05:00 独立排程写入类型目录;OA 打印一期未接线),先落入 `销售开票附件/{年}/{月}/{类型}/`,再归档到同月 `所有归档/{invoice}/` |
| 必检「核价单.pdf」「采购单.pdf」 | 销售一期:PO、报关资料、销货放行申请单、发票、报关单、提单 |
| 一票一状态;缺资料按票发企微 textcard、同票同日节流 | 单文件结果;每批一条汇总通知 + invoice 行 Excel |
| Chatflow Tool `/api/accounting-voucher-check/tools/*` | 已删除;查询走工作台 `/api/workspace/accounting-voucher-check/*` |
约束:
- 不得按旧「核价单/采购单」文件名或**当前月**期间扩展;销售主体仍用 `apa_file` 上月清单。
- 不得按旧「核价单/采购单」文件名或**当前月**期间扩展;销售主体用 `oma_file` 上月清单(已确认、未作废、状况码 1、帐款类别 11/12/13)。
- 不得再写入 `voucher_check_invoice_states` / `voucher_check_run_items`。
- 部署与冒烟见 [ops-checklist.md](ops-checklist.md)。
@@ -202,7 +202,7 @@ error_message 失败原因
| Adapter | 用途 | 销售/采购示例 |
| ------------------------- | ---------------------------------- | -------------------------------- |
| `directory_scan` | 固定目录按规则扫描文件 | 销售发票、提单;采购对账单、发票 |
| `erp_query_print` | ERP 查询业务单据并打印 PDF | 销售 PO、采购 PO |
| `erp_query_print` / `erp_po_print` | 销售 PO:独立排程 `accounting-voucher-po-print`(周二 05:00)按发票从 TGHX 取数并上传到「PO订单」;`fetch()` 仍占位,检核 runner(06:00)不调用。表字段见 [technical-design.md §3.4](technical-design.md) | 销售 PO、采购 PO |
| `oa_report_print` | OA 报表过滤后逐条打印 | 销售销货放行单 |
| `oa_relation_print` | 根据出货单号等关联字段查 OA 并打印 | 采购核价单 |
| `upload_directory_scan` | 网盘或上传目录扫描 | 采购送货单 |
@@ -529,10 +529,10 @@ backend/app/domains/document_check/
| -------------------------------- | ------------------------------------------------ |
| 销售开票附件文档库路径 | 已确认固定:`销售开票附件/{年}/{月}/{类型目录}`,类型目录为 `PO订单`/`报关资料`/`销货单`/`发票`/`报关单`/`提单`,归档 `所有归档/{invoice}` |
| 采购各固定目录路径 | 待确认 |
| 销售 invoice 主体来源与 ERP 字段 | 已确认:HXJM `apa_file` `apa08`/`apa09`,期间上一个月 |
| 销售 invoice 主体来源与 ERP 字段 | 已确认:HXJM `oma_file` `oma10`/`oma02`,`oma10` 至少 6 位字母或数字,`omaconf='Y'`、`omavoid='N'`、`oma64='1'`、`oma00 IN (11,12,13)`,期间上一个月 |
| 采购 invoice 主体来源 | 待确认 |
| ERP PO 查询字段与打印方式 | **待确认** |
| ERP PO 查询字段与打印方式 | **打印与取数已接线(周二 05:00 独立排程)**。发票 HXJM、采购单 **TGHX**。关联 `TRIM(oma99)=TRIM(pmm99)`。对照 apmr900。到货日 `pmn34`。检核 runner 不调用 |
| OA 登录、报表分页和打印接口 | 一期模拟页面;后期对接新 OA 接口 |
| 文档管理系统 | 已确认:同一文档库 LibraryID;销售根 FolderID=`727c3683-dcdb-4d62-a5b1-b164224162bc`;建文件夹 `SaveFolder`、复制 `Item/Copy`;同名跳过 |
| 文档管理系统 | 已确认:同一文档库 LibraryID;销售根 FolderID=`727c3683-dcdb-4d62-a5b1-b164224162bc`;建文件夹 `SaveFolder`、上传 `Attachment/Upload` + `Item/CreateFiles`、复制 `Item/Copy`;同名跳过 |
| 企业微信通知接收人、模板和频率 | 界面从系统用户多选;每周二;具体人选可后配 |
| Profile 管理方式 | 首期可使用版本化 YAML/JSON,后续评估管理后台配置 |
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

+4 -3
View File
@@ -219,11 +219,12 @@
| 功能项 | 状态 | 说明 |
| --- | --- | --- |
| 销售一期需求、规格与技术设计 | 已文档化 | [需求](features/accounting-voucher-check/demand.md) · [规格](features/accounting-voucher-check/technical.md) · [设计](features/accounting-voucher-check/technical-design.md);每周增量检核上一个月,按 Profile 从 ERP、OA、目录获取并归档 |
| 通用 Profile + Adapter 架构 | 实施中 | 销售 Profile 与 Adapter 协议已落地;周任务扫描文档库类型目录;ERP PO / OA 销货放行单打印仅占位 |
| 销售一期需求、规格与技术设计 | 已文档化 | [需求](features/accounting-voucher-check/demand.md) · [规格](features/accounting-voucher-check/technical.md) · [设计](features/accounting-voucher-check/technical-design.md);每周增量检核上一个月;销售 invoice 来自 HXJM `oma_file`(已确认、未作废、状况码 1、帐款类别 11/12/13) |
| 通用 Profile + Adapter 架构 | 实施中 | 销售 Profile 与 Adapter 协议已落地;周任务扫描文档库类型目录;OA 销货放行单打印仅占位 |
| PO 订单制式 PDF | 已实现(周二 05:00 独立排程) | 排程 `accounting-voucher-po-print`(`SCH-ACCOUNTING-VOUCHER-PO-PRINT`,`0 5 * * 2`)按上月发票从 TGHX 取数并上传到 `销售开票附件/{年}/{月}/PO订单/`;检核 `accounting-voucher-check` 仍为周二 06:00 只扫目录;`erp_po_print.fetch` 不进检核 runner |
| 单一共享盘旧检核 | 已移除 | 已删除共享盘扫描、Chatflow Tool、`voucher_check_invoice_states` / `voucher_check_run_items` |
| 增量、归档与缺件通知 | 实施中 | 每周二上月;单文件结果;归档复制同名跳过;企微每批一条汇总 |
| 工作台查询 | 已实现 | 工作台含检核任务与企微发送记录两 Tab;「强制重检上月」;`/runs`、`/notifications` 只读引擎表 |
| 工作台查询 | 已实现 | 工作台含检核任务与企微发送记录两 Tab;期间为年+月(默认上月,月份可「全部」看该年);Tab 下「最近一次检核」卡片不跟筛选;「强制重检上月」在卡片上(admin);`GET /runs/latest`、`/runs`、`/notifications` |
### 采购合同审查
+4 -4
View File
@@ -215,12 +215,12 @@ PDF 证据锚定优先使用现有 `pypdfium2` 逐字文本坐标定位,并由
### 2.x 立账凭证检核(accounting-voucher-check)
- 前端路由 `/workspace/accounting-voucher-check` 标记 `requiresAdmin`,工作台侧栏按当前用户角色隐藏入口;全局路由守卫负责阻止非管理员直接访问。
- **目标架构**:通用检核引擎 + 业务方 Profile + 来源 Adapter。**每周二**处理上一个自然月;invoice 主体来自 HXJM `apa_file`(`apa08`/`apa09`);引擎负责增量、归档、缺件双口径、Excel 与企微批次汇总。
- **销售一期来源**:ERP 打印 PO(查询与打印方式待确认)、OA 销货放行单一期模拟页面(后期换新接口)、文档库扫描报关资料/发票/报关单/提单。获取后写入 `销售开票附件/{yyyy}/{MM}/{类型目录}/`,再归档到同月 `所有归档/{invoice}/`。
- **文档库**:复用现有 DMS(`CONTRACT_DMS_BASE_URL`、`/Login/_api/Login`、`/Api/_api/APS/Public/Item/Page`、`SaveFolder`、`Item/Copy`、现有账号);LibraryID 与合同相同,销售开票附件只单独配置根 FolderID。归档复制策略为同名跳过。
- **目标架构**:通用检核引擎 + 业务方 Profile + 来源 Adapter。**每周二**处理上一个自然月;invoice 主体来自 HXJM `oma_file`(`oma10`/`oma02`,`omaconf='Y'`、`omavoid='N'`、`oma64='1'`、`oma00` 为 11/12/13);引擎负责增量、归档、缺件双口径、Excel 与企微批次汇总。
- **销售一期来源**:PO 订单由 HXOPS 按制式采购单生成 PDF 并上传到当月「PO订单」目录。发票在 HXJM,采购单在 **TGHX**(多角);关联已确认 `TRIM(oma99)=TRIM(pmm99)`,见 [technical-design.md §3.4](features/accounting-voucher-check/technical-design.md)。OA 销货放行单一期模拟页面、文档库扫描报关资料/发票/报关单/提单。获取后写入 `销售开票附件/{yyyy}/{MM}/{类型目录}/`,再归档到同月 `所有归档/{invoice}/`。
- **文档库**:复用现有 DMS(`CONTRACT_DMS_BASE_URL`、`/Login/_api/Login`、`/Api/_api/APS/Public/Item/Page`、`SaveFolder`、`Attachment/Upload`、`Item/CreateFiles`、`Item/Copy`、现有账号);LibraryID 与合同相同,销售开票附件只单独配置根 FolderID。类型目录上传与归档复制均为同名跳过。
- **通知**:排程/任务界面从系统用户多选企微接收人;未配置不发送。
- **判定边界**:不读取文件内容、不调用 LLM 判断合格、不回写 ERP。批次级依赖不可用时整批失败,不得把空结果批量判为缺件。
- **当前代码**:周任务已切到上月清单 + 文档库类型目录扫描 + 按票归档(Copy,同名跳过)+ 单文件结果 + 批次企微;ERP PO / OA 打印仍为占位 Adapter。旧共享盘扫描、Chatflow Tool 与 `voucher_check_invoice_states` / `voucher_check_run_items` 已删除。
- **当前代码**:周二 05:00 `accounting-voucher-po-print` 按上月 `oma_file` 从 TGHX 取数生成 PO PDF 并上传到「PO订单」;周二 06:00 检核扫描类型目录 + 按票归档(Copy,同名跳过)+ 单文件结果 + 批次企微。`erp_po_print.fetch` / OA 仍为占位,检核 runner 不调用生成。旧共享盘扫描、Chatflow Tool 与 `voucher_check_invoice_states` / `voucher_check_run_items` 已删除。
- 详细业务需求见 [docs/features/accounting-voucher-check/demand.md](features/accounting-voucher-check/demand.md),研发落地设计见 [docs/features/accounting-voucher-check/technical-design.md](features/accounting-voucher-check/technical-design.md)。
### 2.x 货代发货通知批次库存能力
@@ -1,6 +1,6 @@
/**
* features/workspace/api/voucherCheck.api.ts
* 用途:工作台立账凭证检核任务列表、批次明细、企微发送记录与强制重检 API 客户端。
* 用途:工作台立账凭证检核任务列表、最近一次检核、批次明细、企微发送记录与强制重检 API 客户端。
* 依赖:@/shared/api/client、getAuthHeaders。
* 逻辑:AccountingVoucherCheckView / DetailView 调用;对应 /api/workspace/accounting-voucher-check/* 与排程 Excel 下载。
*/
@@ -71,8 +71,45 @@ export interface VoucherCheckForceRunResponse {
status: string;
}
export interface VoucherCheckLatestStep {
step: string;
label?: string | null;
processed_count: number;
}
export interface VoucherCheckLatestRun {
schedule_run_id: number | null;
engine_run_id?: number | null;
run_no: string;
period_month: string | null;
mode: string;
status: string;
progress_percent: number;
subject_count: number;
archived_file_count: number;
missing_file_count: number;
missing_invoice_count: number;
processed_count: number;
started_at?: string | null;
finished_at?: string | null;
error_message?: string | null;
current_step?: VoucherCheckLatestStep | null;
}
/**
* 读取最近一次立账凭证检核(含排队/执行中),不跟列表 period/status。
* @returns 无任何批次时为 null
*/
export function getLatestVoucherCheckRun() {
return requestJson<VoucherCheckLatestRun | null>(
'/api/workspace/accounting-voucher-check/runs/latest',
{ headers: getAuthHeaders() },
);
}
/**
* 分页查询检核任务列表。
* @param params.period - YYYY 表示该年全部月份,YYYY-MM 表示单月
*/
export function listVoucherCheckRuns(params: {
period?: string;
@@ -136,6 +173,7 @@ export interface VoucherCheckNotificationsResponse {
/**
* 分页查询企微缺件汇总发送记录。
* @param params.period - YYYY 表示该年全部月份,YYYY-MM 表示单月
*/
export function listVoucherCheckNotifications(params?: {
period?: string;
@@ -1,6 +1,6 @@
/**
* features/workspace/utils/voucherCheck.display.ts
* 用途:立账凭证检核列表与明细页共用的状态文案、缺件列表、缺件数、缺失占比与企微发送状态展示。
* 用途:立账凭证检核列表、最近一次检核卡片与明细页共用的状态/模式/步骤文案。
* 依赖:vue-i18n 的 t()。
* 逻辑:AccountingVoucherCheckView / AccountingVoucherCheckDetailView 调用。
*/
@@ -18,9 +18,37 @@ export function voucherCheckStatusLabel(t: (key: string) => string, value: strin
if (value === 'technical_error' || value === 'technical_failed') return t('workspace.voucherCheck.statusTechError');
if (value === 'failed') return t('workspace.voucherCheck.statusTechError');
if (value === 'pending') return t('workspace.voucherCheck.statusPending');
if (value === 'queued') return t('workspace.voucherCheck.statusQueued');
if (value === 'running') return t('workspace.voucherCheck.statusRunning');
return value || '-';
}
/**
* 将批次执行模式映射为工作台文案。
* @param t - i18n 翻译函数
* @param value - incremental / force_all / single
*/
export function voucherCheckModeLabel(t: (key: string) => string, value: string): string {
if (value === 'force_all') return t('workspace.voucherCheck.modeForceAll');
if (value === 'single') return t('workspace.voucherCheck.modeSingle');
return t('workspace.voucherCheck.modeIncremental');
}
/**
* 将 runner 步骤码映射为工作台当前步骤文案。
* @param t - i18n 翻译函数
* @param step - current_step.step
*/
export function voucherCheckStepLabel(t: (key: string) => string, step?: string | null): string {
if (step === 'queued') return t('workspace.voucherCheck.stepQueued');
if (step === 'fetch_erp') return t('workspace.voucherCheck.stepFetchErp');
if (step === 'scan_dms') return t('workspace.voucherCheck.stepScanDms');
if (step === 'persist') return t('workspace.voucherCheck.stepPersist');
if (step === 'notify') return t('workspace.voucherCheck.stepNotify');
if (step === 'done') return t('workspace.voucherCheck.stepDone');
return step || '-';
}
/**
* 将企微汇总发送状态码映射为工作台文案。
* @param t - i18n 翻译函数
@@ -1,28 +1,36 @@
<script setup lang="ts">
/**
* features/workspace/views/AccountingVoucherCheckView.vue
* 用途:立账凭证检核任务列表——按资料所属期间查看批次统计。
* 依赖:voucherCheck.api、vue-i18n、useMessage、DeleteConfirmDialog、PaginationBar、formatLocalDateTime、voucherCheck.display。
* 逻辑:路由 /workspace/accounting-voucher-check;Tab 切换检核任务与企微发送记录;查看详情进入独立明细页;企微 ?run_id= 重定向到明细路由。
* 用途:立账凭证检核任务列表——按资料所属期间(年 + 月)查看批次统计,并展示最近一次检核进度。
* 依赖:voucherCheck.api、vue-i18n、useMessage、DeleteConfirmDialog、PaginationBar、formatLocalDateTime、voucherCheck.display、auth。
* 逻辑:路由 /workspace/accounting-voucher-check;进页默认上一个自然月;「最近一次检核」不跟筛选;强制重检仅 admin,进度在本卡轮询。
*/
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { Download, Loader2, RefreshCw, RotateCcw, Search } from 'lucide-vue-next';
import { ChevronDown, Download, Loader2, RotateCcw, Search } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import PaginationBar from '@/shared/components/PaginationBar.vue';
import { useMessage } from '@/shared/composables/useMessage';
import { getStoredAuthUser } from '@/shared/utils/auth';
import { formatLocalDateTime } from '@/shared/utils/dateTime';
import { WORKSPACE_PATHS } from '../constants/routes';
import {
downloadVoucherCheckExcel,
getLatestVoucherCheckRun,
listVoucherCheckNotifications,
listVoucherCheckRuns,
triggerVoucherCheckForceAll,
type VoucherCheckLatestRun,
type VoucherCheckNotificationItem,
type VoucherCheckRunItem,
} from '../api/voucherCheck.api';
import { voucherCheckNotifyStatusLabel, voucherCheckStatusLabel } from '../utils/voucherCheck.display';
import {
voucherCheckModeLabel,
voucherCheckNotifyStatusLabel,
voucherCheckStatusLabel,
voucherCheckStepLabel,
} from '../utils/voucherCheck.display';
const { t } = useI18n();
const msg = useMessage();
@@ -36,7 +44,8 @@ const items = ref<VoucherCheckRunItem[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(50);
const period = ref('');
const periodYear = ref('');
const periodMonth = ref('');
const status = ref('');
const listTab = ref<'tasks' | 'notifications'>('tasks');
const notifyLoading = ref(false);
@@ -45,19 +54,63 @@ const notifyTotal = ref(0);
const notifyPage = ref(1);
const notifyPageSize = ref(50);
const notifyStatus = ref('');
const latestRun = ref<VoucherCheckLatestRun | null>(null);
const latestLoading = ref(false);
let forcePollTimer: ReturnType<typeof setInterval> | null = null;
const isAdmin = computed(() => String(getStoredAuthUser()?.role || '').trim().toLowerCase() === 'admin');
const latestInProgress = computed(() => {
const cardStatus = latestRun.value?.status;
return cardStatus === 'queued' || cardStatus === 'running';
});
const latestHasMissing = computed(() => {
const row = latestRun.value;
if (!row) return false;
return (row.missing_file_count || 0) > 0 || (row.missing_invoice_count || 0) > 0;
});
const latestCanOpenDetail = computed(() => {
const row = latestRun.value;
if (!row?.schedule_run_id) return false;
return row.status === 'missing' || row.status === 'completed';
});
const MONTH_VALUES = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'] as const;
/**
* 默认资料所属期间为上一个自然月 YYYY-MM。
* 进页默认资料所属期间为上一个自然月。
*/
function previousPeriod(): string {
function previousYearMonth(): { year: string; month: string } {
const d = new Date();
d.setDate(1);
d.setMonth(d.getMonth() - 1);
const m = String(d.getMonth() + 1).padStart(2, '0');
return `${d.getFullYear()}-${m}`;
return {
year: String(d.getFullYear()),
month: String(d.getMonth() + 1).padStart(2, '0'),
};
}
/**
* 组装列表查询 period:有月份则为 YYYY-MM,否则为 YYYY。
*/
const periodQuery = computed(() => {
if (!periodYear.value) return undefined;
if (periodMonth.value) return `${periodYear.value}-${periodMonth.value}`;
return periodYear.value;
});
const yearOptions = computed(() => {
const now = new Date().getFullYear();
const years: string[] = [];
for (let year = now - 5; year <= now; year += 1) {
years.push(String(year));
}
if (periodYear.value && !years.includes(periodYear.value)) {
years.unshift(periodYear.value);
years.sort();
}
return years;
});
const statusOptions = computed(() => [
{ value: '', label: t('workspace.voucherCheck.statusAll') },
{ value: 'missing', label: t('workspace.voucherCheck.statusMissing') },
@@ -89,7 +142,7 @@ async function loadNotifications() {
notifyLoading.value = true;
try {
const data = await listVoucherCheckNotifications({
period: period.value || undefined,
period: periodQuery.value,
send_status: notifyStatus.value || undefined,
page: notifyPage.value,
page_size: notifyPageSize.value,
@@ -117,6 +170,7 @@ function setListTab(tab: 'tasks' | 'notifications') {
}
page.value = 1;
void loadRuns();
void loadLatestRun();
}
/**
@@ -132,17 +186,6 @@ function searchCurrentTab() {
void loadNotifications();
}
/**
* 当前 Tab 刷新列表,不重置页码。
*/
function refreshCurrentTab() {
if (listTab.value === 'tasks') {
void loadRuns();
return;
}
void loadNotifications();
}
/**
* 下载该发送记录对应批次的 Excel。
* @param row - 企微发送记录
@@ -197,7 +240,7 @@ async function loadRuns() {
loading.value = true;
try {
const data = await listVoucherCheckRuns({
period: period.value || undefined,
period: periodQuery.value,
status: status.value || undefined,
page: page.value,
page_size: pageSize.value,
@@ -238,15 +281,96 @@ function openRunDetail(row: VoucherCheckRunItem) {
}
/**
* 停止强制重检后的列表轮询。
* 停止最近一次检核的进度轮询。
*/
function stopForcePoll() {
function stopLatestPoll() {
if (forcePollTimer) {
clearInterval(forcePollTimer);
forcePollTimer = null;
}
}
/**
* 拉取最近一次检核卡片;不跟下方列表的年/月/状态筛选。
* @param options.silent - 轮询时不切换卡片 loading,避免进度条闪烁
*/
async function loadLatestRun(options?: { silent?: boolean }) {
if (!options?.silent) latestLoading.value = true;
try {
latestRun.value = await getLatestVoucherCheckRun();
} catch (e: any) {
if (!options?.silent) {
msg.error(e?.message || t('workspace.voucherCheck.latestLoadFailed'));
}
} finally {
if (!options?.silent) latestLoading.value = false;
}
}
/**
* 排队或执行中时轮询卡片;进入终态后刷新下方列表。
*/
function syncLatestPoll() {
stopLatestPoll();
if (listTab.value !== 'tasks' || !latestInProgress.value) return;
forcePollTimer = setInterval(() => {
void (async () => {
const previous = latestRun.value?.status;
await loadLatestRun({ silent: true });
const next = latestRun.value?.status;
if ((previous === 'queued' || previous === 'running') && next !== 'queued' && next !== 'running') {
stopLatestPoll();
void loadRuns();
}
})();
}, 3000);
}
/**
* 最近一次检核状态徽章样式。
* @param value - 卡片状态
*/
function latestBadgeClass(value: string): string {
if (value === 'missing' || value === 'technical_failed') return 'bg-rose-50 text-rose-700';
if (value === 'completed') return 'bg-emerald-50 text-emerald-700';
if (value === 'queued' || value === 'running') return 'bg-blue-50 text-blue-700';
return 'bg-surface-soft text-secondary';
}
/**
* 卡片当前步骤主文案:终态用完成提示,其余按步骤码翻译。
* @param row - 最近一次检核
*/
function latestStepText(row: VoucherCheckLatestRun): string {
if (row.status === 'queued') return t('workspace.voucherCheck.stepQueued');
if (row.status === 'missing' && (row.current_step?.step === 'done' || !row.current_step)) {
return t('workspace.voucherCheck.latestDoneHint');
}
if (row.status === 'completed' && (row.current_step?.step === 'done' || !row.current_step)) {
return t('workspace.voucherCheck.latestCompleteHint');
}
if (row.status === 'technical_failed' && row.current_step?.step === 'fetch_erp') {
return t('workspace.voucherCheck.stepFetchErpIncomplete');
}
return voucherCheckStepLabel(t, row.current_step?.step);
}
/**
* 卡片步骤辅文案:失败原因、排队等待或扫描进度。
* @param row - 最近一次检核
*/
function latestHintText(row: VoucherCheckLatestRun): string {
if (row.error_message) return row.error_message;
if (row.status === 'queued') return t('workspace.voucherCheck.stepQueuedHint');
if (row.status === 'running' && row.current_step?.step === 'scan_dms' && row.subject_count > 0) {
return t('workspace.voucherCheck.processedHint', {
processed: row.processed_count,
total: row.subject_count,
});
}
return '';
}
/**
* 打开强制重检确认框;用公共 DeleteConfirmDialog 替代原生 window.confirm。
*/
@@ -264,13 +388,8 @@ async function forceRecheck() {
try {
const data = await triggerVoucherCheckForceAll();
msg.success(t('workspace.voucherCheck.forceQueued', { runNo: data.run_no }));
await loadRuns();
stopForcePoll();
const started = Date.now();
forcePollTimer = setInterval(() => {
void loadRuns();
if (Date.now() - started > 120_000) stopForcePoll();
}, 5000);
await loadLatestRun({ silent: true });
syncLatestPoll();
} catch (e: any) {
msg.error(e?.message || t('workspace.voucherCheck.forceFailed'));
} finally {
@@ -278,16 +397,40 @@ async function forceRecheck() {
}
}
/**
* 从最近一次检核卡片打开本批明细。
*/
function openLatestDetail() {
const row = latestRun.value;
if (!row?.schedule_run_id) {
msg.error(t('workspace.voucherCheck.loadFailed'));
return;
}
void router.push({
path: WORKSPACE_PATHS.accountingVoucherCheckDetail(row.schedule_run_id),
query: row.run_no ? { runNo: row.run_no } : undefined,
});
}
/**
* 仅在检核任务 Tab 且最近一批仍在排队/执行时轮询卡片。
*/
watch([listTab, latestInProgress], () => {
syncLatestPoll();
});
onMounted(async () => {
if (redirectLegacyRunQuery()) return;
period.value = previousPeriod();
const previous = previousYearMonth();
periodYear.value = previous.year;
periodMonth.value = previous.month;
const qStatus = route.query.status;
if (typeof qStatus === 'string' && qStatus) status.value = qStatus;
await loadRuns();
await Promise.all([loadRuns(), loadLatestRun()]);
});
onUnmounted(() => {
stopForcePoll();
stopLatestPoll();
});
</script>
@@ -321,22 +464,143 @@ onUnmounted(() => {
</button>
</div>
<article
v-if="listTab === 'tasks'"
class="overflow-hidden rounded-2xl border border-default bg-surface"
aria-live="polite"
>
<div class="flex flex-wrap items-start justify-between gap-3 bg-blue-50 px-4 py-3.5">
<div>
<h2 class="text-[15px] font-semibold text-primary">{{ $t('workspace.voucherCheck.latestTitle') }}</h2>
<p v-if="latestRun" class="mt-1 text-xs text-muted">
<span class="mr-3">{{ $t('workspace.voucherCheck.latestBatch', { runNo: latestRun.run_no }) }}</span>
<span class="mr-3">{{ $t('workspace.voucherCheck.latestPeriod', { period: latestRun.period_month || '-' }) }}</span>
<span>{{ voucherCheckModeLabel(t, latestRun.mode) }}</span>
</p>
</div>
<div class="flex shrink-0 items-center gap-2">
<span
v-if="latestRun"
class="inline-flex rounded-full px-2.5 py-1 text-xs font-semibold"
:class="latestBadgeClass(latestRun.status)"
>
{{ voucherCheckStatusLabel(t, latestRun.status) }}
</span>
<button
v-if="isAdmin"
type="button"
class="inline-flex items-center gap-1 rounded-xl border border-amber-300 bg-amber-50 px-3 py-1.5 text-sm font-medium text-amber-900 transition-colors hover:bg-amber-100 disabled:opacity-50"
:disabled="forcing || latestInProgress"
@click="openForceRecheck()"
>
<Loader2 v-if="forcing" class="h-3.5 w-3.5 animate-spin" />
<RotateCcw v-else class="h-3.5 w-3.5" />
{{ $t('workspace.voucherCheck.forceRecheck') }}
</button>
</div>
</div>
<div class="px-4 py-3.5">
<div v-if="latestLoading && !latestRun" class="flex items-center justify-center gap-2 py-8 text-sm text-muted">
<Loader2 class="h-4 w-4 animate-spin" />
{{ $t('workspace.voucherCheck.loading') }}
</div>
<p v-else-if="!latestRun" class="py-8 text-center text-sm text-muted">
{{ $t('workspace.voucherCheck.latestEmpty') }}
</p>
<template v-else>
<div class="h-2.5 overflow-hidden rounded-full bg-slate-200">
<div
class="h-full rounded-full transition-[width] duration-300"
:class="latestRun.status === 'technical_failed' ? 'bg-rose-600' : 'bg-teal-700'"
:style="{ width: `${latestRun.progress_percent || 0}%` }"
/>
</div>
<div class="mt-2 mb-3.5 flex flex-wrap justify-between gap-3 text-xs text-muted">
<span>{{ $t('workspace.voucherCheck.progress', { percent: latestRun.progress_percent || 0 }) }}</span>
<span>
{{ $t('workspace.voucherCheck.startedAt') }}:{{ formatLocalDateTime(latestRun.started_at) }}
 {{ $t('workspace.voucherCheck.finishedAt') }}:{{ latestInProgress ? $t('workspace.voucherCheck.inProgress') : formatLocalDateTime(latestRun.finished_at) }}
</span>
</div>
<div class="grid grid-cols-2 gap-2 md:grid-cols-4">
<div class="rounded-[10px] border border-default bg-slate-50 px-2.5 py-3">
<b class="block text-[22px] font-semibold leading-tight text-primary">{{ latestRun.subject_count }}</b>
<span class="text-xs text-muted">{{ $t('workspace.voucherCheck.subjectCount') }}</span>
</div>
<div class="rounded-[10px] border border-default bg-slate-50 px-2.5 py-3">
<b class="block text-[22px] font-semibold leading-tight text-primary">{{ latestRun.archived_file_count }}</b>
<span class="text-xs text-muted">{{ $t('workspace.voucherCheck.archivedFiles') }}</span>
</div>
<div class="rounded-[10px] border border-default bg-slate-50 px-2.5 py-3">
<b
class="block text-[22px] font-semibold leading-tight"
:class="latestHasMissing ? 'text-rose-700' : 'text-primary'"
>{{ latestRun.missing_file_count }}</b>
<span class="text-xs text-muted">{{ $t('workspace.voucherCheck.missingFiles') }}</span>
</div>
<div class="rounded-[10px] border border-default bg-slate-50 px-2.5 py-3">
<b
class="block text-[22px] font-semibold leading-tight"
:class="latestHasMissing ? 'text-rose-700' : 'text-primary'"
>{{ latestRun.missing_invoice_count }}</b>
<span class="text-xs text-muted">{{ $t('workspace.voucherCheck.missingInvoices') }}</span>
</div>
</div>
<p class="mt-3 text-[13px] text-slate-700">
{{ latestStepText(latestRun) }}
<small v-if="latestHintText(latestRun)" class="mt-0.5 block text-muted">{{ latestHintText(latestRun) }}</small>
</p>
<div v-if="latestCanOpenDetail" class="mt-3 flex justify-end">
<button
type="button"
class="text-sm font-semibold text-brand-700 hover:underline"
@click="openLatestDetail"
>
{{ $t('workspace.voucherCheck.viewLatestDetail') }}
</button>
</div>
</template>
</div>
</article>
<section class="flex flex-wrap items-end gap-3 rounded-2xl border border-default/80 bg-surface/70 px-4 py-3 shadow-sm">
<label class="flex flex-col gap-1 text-xs font-medium text-muted">
{{ $t('workspace.voucherCheck.period') }}
<input v-model="period" type="month" class="rounded-xl border border-default bg-surface px-3 py-1.5 text-sm text-primary" />
<span class="flex items-center gap-2">
<span class="period-select">
<select v-model="periodYear" class="period-select__control w-[4.75rem]">
<option v-for="year in yearOptions" :key="year" :value="year">{{ year }}</option>
</select>
<ChevronDown class="period-select__icon" aria-hidden="true" />
</span>
<span class="period-select">
<select v-model="periodMonth" class="period-select__control w-[4.75rem]">
<option value="">{{ $t('workspace.voucherCheck.periodMonthAll') }}</option>
<option v-for="month in MONTH_VALUES" :key="month" :value="month">
{{ $t('workspace.voucherCheck.periodMonthValue', { n: Number(month) }) }}
</option>
</select>
<ChevronDown class="period-select__icon" aria-hidden="true" />
</span>
</span>
</label>
<label v-if="listTab === 'tasks'" class="flex flex-col gap-1 text-xs font-medium text-muted">
{{ $t('workspace.voucherCheck.status') }}
<select v-model="status" class="rounded-xl border border-default bg-surface px-3 py-1.5 text-sm text-primary">
<option v-for="opt in statusOptions" :key="opt.value || 'all'" :value="opt.value">{{ opt.label }}</option>
</select>
<span class="period-select">
<select v-model="status" class="period-select__control w-[6rem]">
<option v-for="opt in statusOptions" :key="opt.value || 'all'" :value="opt.value">{{ opt.label }}</option>
</select>
<ChevronDown class="period-select__icon" aria-hidden="true" />
</span>
</label>
<label v-else class="flex flex-col gap-1 text-xs font-medium text-muted">
{{ $t('workspace.voucherCheck.notifyStatus') }}
<select v-model="notifyStatus" class="rounded-xl border border-default bg-surface px-3 py-1.5 text-sm text-primary">
<option v-for="opt in notifyStatusOptions" :key="opt.value || 'all'" :value="opt.value">{{ opt.label }}</option>
</select>
<span class="period-select">
<select v-model="notifyStatus" class="period-select__control w-[7.25rem]">
<option v-for="opt in notifyStatusOptions" :key="opt.value || 'all'" :value="opt.value">{{ opt.label }}</option>
</select>
<ChevronDown class="period-select__icon" aria-hidden="true" />
</span>
</label>
<button
type="button"
@@ -346,25 +610,6 @@ onUnmounted(() => {
<Search class="h-3.5 w-3.5" />
{{ $t('workspace.voucherCheck.search') }}
</button>
<button
type="button"
class="inline-flex items-center gap-1 rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft"
@click="refreshCurrentTab"
>
<RefreshCw class="h-3.5 w-3.5" />
{{ $t('workspace.voucherCheck.refresh') }}
</button>
<button
v-if="listTab === 'tasks'"
type="button"
class="ml-auto inline-flex items-center gap-1 rounded-xl border border-amber-300 bg-amber-50 px-3 py-1.5 text-sm font-medium text-amber-900 transition-colors hover:bg-amber-100 disabled:opacity-50"
:disabled="forcing"
@click="openForceRecheck()"
>
<Loader2 v-if="forcing" class="h-3.5 w-3.5 animate-spin" />
<RotateCcw v-else class="h-3.5 w-3.5" />
{{ $t('workspace.voucherCheck.forceRecheck') }}
</button>
</section>
<section v-if="listTab === 'tasks'" class="overflow-hidden rounded-2xl border border-default bg-surface">
@@ -524,3 +769,51 @@ onUnmounted(() => {
/>
</div>
</template>
<style scoped>
/**
* 隐藏系统原生下拉箭头(含 Chromium ::picker-icon / Edge ::-ms-expand)。
* 只保留模板里的 ChevronDown,避免 Windows 下年份与月份箭头叠在一起。
*/
.period-select {
position: relative;
display: inline-flex;
align-items: center;
}
.period-select__control {
box-sizing: border-box;
border-radius: 0.75rem;
border: 1px solid var(--border-default);
background-color: var(--bg-surface);
background-image: none;
padding: 0.375rem 1.75rem 0.375rem 0.625rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--text-primary);
font-size: 0.875rem;
line-height: 1.25rem;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
.period-select__control::-ms-expand {
display: none;
}
.period-select__control::picker-icon {
display: none;
content: none;
}
.period-select__icon {
pointer-events: none;
position: absolute;
right: 0.5rem;
height: 0.875rem;
width: 0.875rem;
color: var(--text-muted);
}
</style>
+2
View File
@@ -2365,6 +2365,8 @@
"difySystemPromptPlaceholder": "e.g. You are a material compliance assistant. Based on record test data, return JSON with dify_result (pass/fail/manual review) and dify_message.",
"platformJobAccountingVoucherCheck": "Accounting voucher check",
"accountingVoucherCheckHint": "Every Tuesday, check the previous calendar month of sales invoice attachments: load the ERP invoice list, scan document-library type folders, and archive by invoice (skip same names).",
"platformJobAccountingVoucherPoPrint": "Accounting voucher PO print",
"accountingVoucherPoPrintHint": "Every Tuesday at 05:00, fetch last month's invoices from ERP, generate purchase-order PDFs, and upload them to the PO-order folder—before the 06:00 check. Skip same names.",
"voucherCheckScope": "Ledger scope",
"voucherCheckProfile": "Business profile",
"voucherCheckNotifyMissing": "Notify on missing materials",
+2
View File
@@ -528,6 +528,8 @@
"VOUCHER_CHECK_RUN_IN_PROGRESS": "An accounting voucher check is already queued or running. Try again later.",
"VOUCHER_CHECK_SCHEDULE_NOT_FOUND": "The accounting voucher check schedule was not found.",
"VOUCHER_CHECK_PERSIST_FAILED": "Failed to persist voucher check results.",
"VOUCHER_CHECK_PO_PDF_INVALID": "Purchase-order PDF data is invalid. Provide a valid invoice number and order number.",
"VOUCHER_CHECK_PO_UPLOAD_FAILED": "Failed to upload the purchase-order PDF to the DMS PO-order folder.",
"TRANSFER_PERMISSION_DENIED": "No in-transit transfer permission.",
"TRANSFER_RECEIPT_NOT_MATURED": "Same-day receipt is not matured yet.",
"TRANSFER_FILE_NOT_READY": "Receipt file is not ready.",
+31 -3
View File
@@ -784,6 +784,8 @@
"title": "Accounting voucher check tasks",
"subtitle": "Every Tuesday the job incrementally checks the previous calendar month, scans sales invoice attachment folders, archives by invoice, and summarizes missing files.",
"period": "Document period",
"periodMonthAll": "All",
"periodMonthValue": "Month {n}",
"status": "Status",
"statusAll": "All",
"statusComplete": "Complete",
@@ -791,6 +793,8 @@
"statusSkipped": "Skipped",
"statusTechError": "Technical failure",
"statusPending": "Pending",
"statusQueued": "Queued",
"statusRunning": "Running",
"invoiceNo": "invoice",
"invoiceDate": "Invoice date",
"invoicePlaceholder": "Filter by invoice",
@@ -800,7 +804,6 @@
"checkedAt": "Run time",
"result": "Result",
"search": "Search",
"refresh": "Refresh",
"loading": "Loading…",
"empty": "No check batches yet",
"loadFailed": "Failed to load voucher check tasks",
@@ -826,9 +829,34 @@
"viewDetail": "View details",
"forceRecheck": "Force recheck last month",
"failureReason": "Failure reason",
"forceConfirm": "This will fully recheck the previous calendar month. Already archived files will not be skipped, and the period filter above is ignored. Continue?",
"forceQueued": "Force recheck queued ({runNo}). The list will refresh when it finishes.",
"forceConfirm": "This will fully recheck the previous calendar month. Already archived files will not be skipped, and the period filter below is ignored. Continue?",
"forceQueued": "Force recheck queued ({runNo}). Progress will update on this card.",
"forceFailed": "Failed to queue the force recheck",
"latestTitle": "Latest check",
"latestEmpty": "No check batches yet",
"latestLoadFailed": "Failed to load the latest check",
"latestBatch": "Batch {runNo}",
"latestPeriod": "Period {period}",
"modeIncremental": "Incremental",
"modeForceAll": "Full recheck",
"modeSingle": "Single invoice",
"progress": "Progress {percent}%",
"startedAt": "Started",
"finishedAt": "Finished",
"inProgress": "In progress",
"viewLatestDetail": "View this batch",
"archivedFiles": "Archived files",
"processedHint": "Processed {processed} / {total} invoices",
"latestDoneHint": "This batch is complete. Missing-file results have been written to Excel.",
"latestCompleteHint": "This batch is complete.",
"stepQueued": "Force recheck of last month is queued",
"stepQueuedHint": "Waiting for the schedule worker to pick it up",
"stepFetchErp": "Fetching last month’s sales invoices",
"stepFetchErpIncomplete": "Fetching last month’s sales invoices did not finish",
"stepScanDms": "Scanning sales invoice attachment type folders",
"stepPersist": "Writing check records",
"stepNotify": "Sending the WeCom summary",
"stepDone": "Check complete",
"tabTasks": "Check tasks",
"tabNotifications": "WeCom send log",
"notifyEmpty": "No WeCom send records yet",
+2
View File
@@ -2243,6 +2243,8 @@
"difySystemPromptPlaceholder": "เช่น คุณเป็นผู้ช่วยตรวจสอบความสอดคล้องของวัสดุ จากข้อมูล record ให้คืน JSON: dify_result (ผ่าน/ไม่ผ่าน/ตรวจด้วยมือ) และ dify_message",
"platformJobAccountingVoucherCheck": "ตรวจสอบเอกสารบัญชี",
"accountingVoucherCheckHint": "ทุกวันอังคาร ตรวจเอกสารใบแจ้งหนี้ขายของเดือนก่อน: ดึงรายการใบแจ้งหนี้จาก ERP สแกนโฟลเดอร์ประเภทในคลังเอกสาร แล้วจัดเก็บตาม invoice (ข้ามชื่อซ้ำ)",
"platformJobAccountingVoucherPoPrint": "สร้างใบสั่งซื้อ PO สำหรับเอกสารบัญชี",
"accountingVoucherPoPrintHint": "ทุกวันอังคาร 05:00 ดึงใบแจ้งหนี้เดือนก่อนจาก ERP สร้าง PDF ใบสั่งซื้อมาตรฐาน แล้วอัปโหลดไปยังโฟลเดอร์ PO — ก่อนงานตรวจ 06:00 ข้ามชื่อซ้ำ",
"voucherCheckScope": "ชุดบัญชี",
"voucherCheckProfile": "โปรไฟล์ฝ่ายธุรกิจ",
"voucherCheckNotifyMissing": "แจ้งเตือนเมื่อขาดเอกสาร",
+2
View File
@@ -528,6 +528,8 @@
"VOUCHER_CHECK_RUN_IN_PROGRESS": "งานตรวจเอกสารบัญชียังอยู่ในคิวหรือกำลังทำงาน โปรดลองใหม่ภายหลัง",
"VOUCHER_CHECK_SCHEDULE_NOT_FOUND": "ไม่พบตารางงานตรวจเอกสารบัญชี",
"VOUCHER_CHECK_PERSIST_FAILED": "บันทึกผลการตรวจไม่สำเร็จ",
"VOUCHER_CHECK_PO_PDF_INVALID": "ข้อมูล PDF ใบสั่งซื้อไม่ถูกต้อง กรุณาระบุเลขที่ใบแจ้งหนี้และเลขที่ใบสั่งที่ถูกต้อง",
"VOUCHER_CHECK_PO_UPLOAD_FAILED": "อัปโหลดไฟล์ PDF ใบสั่งซื้อไปยังโฟลเดอร์ PO订单 ในคลังเอกสารไม่สำเร็จ",
"TRANSFER_PERMISSION_DENIED": "ไม่มีสิทธิ์โอนระหว่างคลัง",
"TRANSFER_RECEIPT_NOT_MATURED": "การรับของวันนี้ยังไม่พร้อมดำเนินการ",
"TRANSFER_FILE_NOT_READY": "ไฟล์รับของยังไม่พร้อม",
+31 -3
View File
@@ -720,6 +720,8 @@
"title": "งานตรวจเอกสารบัญชี",
"subtitle": "ทุกวันอังคารตรวจเดือนปฏิทินก่อนหน้าแบบเพิ่มส่วน แสกนโฟลเดอร์เอกสารขาย แล้วจัดเก็บตาม invoice พร้อมสรุปไฟล์ที่ขาด",
"period": "ช่วงเอกสาร",
"periodMonthAll": "ทั้งหมด",
"periodMonthValue": "เดือน {n}",
"status": "สถานะ",
"statusAll": "ทั้งหมด",
"statusComplete": "ครบ",
@@ -727,6 +729,8 @@
"statusSkipped": "ข้าม",
"statusTechError": "ล้มเหลวทางเทคนิค",
"statusPending": "รอดำเนินการ",
"statusQueued": "อยู่ในคิว",
"statusRunning": "กำลังทำงาน",
"invoiceNo": "invoice",
"invoiceDate": "วันที่ใบแจ้งหนี้",
"invoicePlaceholder": "กรองด้วย invoice",
@@ -736,7 +740,6 @@
"checkedAt": "เวลาที่รัน",
"result": "ผลลัพธ์",
"search": "ค้นหา",
"refresh": "รีเฟรช",
"loading": "กำลังโหลด…",
"empty": "ยังไม่มีรอบการตรวจ",
"loadFailed": "โหลดงานตรวจไม่สำเร็จ",
@@ -762,9 +765,34 @@
"viewDetail": "ดูรายละเอียด",
"forceRecheck": "ตรวจเดือนที่แล้วใหม่ทั้งชุด",
"failureReason": "สาเหตุที่ล้มเหลว",
"forceConfirm": "ระบบจะตรวจเดือนปฏิทินก่อนหน้าทั้งชุด ไม่ข้ามไฟล์ที่จัดเก็บแล้ว และไม่ใช้ช่วงที่กรองด้านบน ต้องการเริ่มหรือไม่?",
"forceQueued": "จัดคิวตรวจใหม่แล้ว ({runNo}) รายการจะรีเฟรชเมื่อเสร็จ",
"forceConfirm": "ระบบจะตรวจเดือนปฏิทินก่อนหน้าทั้งชุด ไม่ข้ามไฟล์ที่จัดเก็บแล้ว และไม่ใช้ช่วงที่กรองด้านล่าง ต้องการเริ่มหรือไม่?",
"forceQueued": "จัดคิวตรวจใหม่แล้ว ({runNo}) ความคืบหน้าจะอัปเดตบนการ์ดนี้",
"forceFailed": "จัดคิวตรวจใหม่ไม่สำเร็จ",
"latestTitle": "การตรวจล่าสุด",
"latestEmpty": "ยังไม่มีรอบการตรวจ",
"latestLoadFailed": "โหลดการตรวจล่าสุดไม่สำเร็จ",
"latestBatch": "รอบ {runNo}",
"latestPeriod": "ช่วง {period}",
"modeIncremental": "แบบเพิ่มทีละส่วน",
"modeForceAll": "ตรวจใหม่ทั้งชุด",
"modeSingle": "ใบเดียว",
"progress": "ความคืบหน้า {percent}%",
"startedAt": "เริ่ม",
"finishedAt": "เสร็จ",
"inProgress": "กำลังดำเนินการ",
"viewLatestDetail": "ดูรายละเอียดรอบนี้",
"archivedFiles": "ไฟล์ที่จัดเก็บแล้ว",
"processedHint": "ประมวลผลแล้ว {processed} / {total} ใบ invoice",
"latestDoneHint": "รอบนี้เสร็จแล้ว ผลไฟล์ที่ขาดถูกเขียนลง Excel",
"latestCompleteHint": "รอบนี้เสร็จแล้ว",
"stepQueued": "จัดคิวตรวจเดือนที่แล้วใหม่ทั้งชุดแล้ว",
"stepQueuedHint": "รอให้ schedule worker รับงาน",
"stepFetchErp": "กำลังดึง invoice ขายของเดือนที่แล้ว",
"stepFetchErpIncomplete": "ดึง invoice ขายของเดือนที่แล้วยังไม่เสร็จ",
"stepScanDms": "กำลังสแกนโฟลเดอร์ประเภทเอกสารใบแจ้งหนี้ขาย",
"stepPersist": "กำลังบันทึกผลตรวจ",
"stepNotify": "กำลังส่งสรุป WeCom",
"stepDone": "ตรวจเสร็จแล้ว",
"tabTasks": "งานตรวจ",
"tabNotifications": "ประวัติส่ง WeCom",
"notifyEmpty": "ยังไม่มีประวัติส่ง WeCom",
+2
View File
@@ -2477,6 +2477,8 @@
"difySystemPromptPlaceholder": "例如:你是物料合规判定助手。根据 record 中的检测数据判定是否合格,仅返回 JSON:dify_result(合格/不合格/人工判定)与 dify_message。",
"platformJobAccountingVoucherCheck": "立账凭证检核",
"accountingVoucherCheckHint": "每周二检核上一个自然月的销售开票附件:拉取 ERP 发票清单,扫描文档库类型目录并按 invoice 归档(同名跳过)。",
"platformJobAccountingVoucherPoPrint": "立账凭证 PO 订单生成",
"accountingVoucherPoPrintHint": "每周二 05:00 按上月发票从 ERP 取数,生成制式采购单 PDF 并上传到「PO订单」目录;早于 06:00 检核周批。同名跳过。",
"voucherCheckScope": "账套",
"voucherCheckProfile": "业务方 Profile",
"voucherCheckNotifyMissing": "缺资料通知",
+2
View File
@@ -528,6 +528,8 @@
"VOUCHER_CHECK_RUN_IN_PROGRESS": "立账凭证检核正在执行或排队中,请稍后再试。",
"VOUCHER_CHECK_SCHEDULE_NOT_FOUND": "未找到立账凭证检核排程任务。",
"VOUCHER_CHECK_PERSIST_FAILED": "检核结果落库失败。",
"VOUCHER_CHECK_PO_PDF_INVALID": "采购单 PDF 数据无效:请提供合法的发票号和订单号。",
"VOUCHER_CHECK_PO_UPLOAD_FAILED": "采购单 PDF 上传到文档库「PO订单」目录失败。",
"TRANSFER_PERMISSION_DENIED": "无在途调拨权限。",
"TRANSFER_RECEIPT_NOT_MATURED": "当天收料尚未成熟,不可查询或调拨。",
"TRANSFER_FILE_NOT_READY": "收料文件尚未就绪。",
+31 -3
View File
@@ -784,6 +784,8 @@
"title": "立账凭证检核任务",
"subtitle": "每周二增量检核上一个自然月;扫描销售开票附件类型目录后按 invoice 归档,并汇总缺件。",
"period": "资料所属期间",
"periodMonthAll": "全部",
"periodMonthValue": "{n}月",
"status": "状态",
"statusAll": "全部",
"statusComplete": "完整",
@@ -791,6 +793,8 @@
"statusSkipped": "跳过",
"statusTechError": "技术失败",
"statusPending": "待处理",
"statusQueued": "排队中",
"statusRunning": "执行中",
"invoiceNo": "invoice",
"invoiceDate": "发票日期",
"invoicePlaceholder": "输入 invoice 筛选",
@@ -800,7 +804,6 @@
"checkedAt": "执行时间",
"result": "结论",
"search": "查询",
"refresh": "刷新",
"loading": "加载中…",
"empty": "暂无检核批次",
"loadFailed": "加载检核任务失败",
@@ -826,9 +829,34 @@
"viewDetail": "查看详情",
"forceRecheck": "强制重检上月",
"failureReason": "失败原因",
"forceConfirm": "将全量重检上一个自然月,不跳过已归档记录,也不使用上方筛选的期间。确定开始?",
"forceQueued": "已入队强制重检({runNo}),完成后列表会自动刷新。",
"forceConfirm": "将全量重检上一个自然月,不跳过已归档记录,也不使用下方筛选的期间。确定开始?",
"forceQueued": "已入队强制重检({runNo}),进度将在本卡更新。",
"forceFailed": "强制重检入队失败",
"latestTitle": "最近一次检核",
"latestEmpty": "暂无检核批次",
"latestLoadFailed": "加载最近一次检核失败",
"latestBatch": "批次 {runNo}",
"latestPeriod": "期间 {period}",
"modeIncremental": "增量",
"modeForceAll": "全量重检",
"modeSingle": "单票",
"progress": "进度 {percent}%",
"startedAt": "开始",
"finishedAt": "完成",
"inProgress": "进行中",
"viewLatestDetail": "查看本批详情",
"archivedFiles": "已归档文件",
"processedHint": "已处理 {processed} / {total} 张 invoice",
"latestDoneHint": "本批已完成,缺件结果已写入 Excel。",
"latestCompleteHint": "本批已完成。",
"stepQueued": "已入队强制重检上月",
"stepQueuedHint": "等待 schedule worker 领取",
"stepFetchErp": "拉取上月销售 invoice",
"stepFetchErpIncomplete": "拉取上月销售 invoice 未完成",
"stepScanDms": "扫描销售开票附件类型目录",
"stepPersist": "写入检核记录",
"stepNotify": "发送企微汇总",
"stepDone": "检核完成",
"tabTasks": "检核任务",
"tabNotifications": "企微发送记录",
"notifyEmpty": "暂无企业微信发送记录",
+2
View File
@@ -2248,6 +2248,8 @@
"difySystemPromptPlaceholder": "例如:你是物料合規判定助手。根據 record 中的檢測資料判定是否合格,僅返回 JSON:dify_result(合格/不合格/人工判定)與 dify_message。",
"platformJobAccountingVoucherCheck": "立帳憑證檢核",
"accountingVoucherCheckHint": "每週二檢核上一個自然月的銷售開票附件:拉取 ERP 發票清單,掃描文件庫類型目錄並依 invoice 歸檔(同名略過)。",
"platformJobAccountingVoucherPoPrint": "立帳憑證 PO 訂單產生",
"accountingVoucherPoPrintHint": "每週二 05:00 依上月發票從 ERP 取數,產生制式採購單 PDF 並上傳到「PO訂單」目錄;早於 06:00 檢核週批。同名略過。",
"voucherCheckScope": "帳套",
"voucherCheckProfile": "業務方 Profile",
"voucherCheckNotifyMissing": "缺資料通知",
+2
View File
@@ -528,6 +528,8 @@
"VOUCHER_CHECK_RUN_IN_PROGRESS": "立帳憑證檢核正在執行或排隊中,請稍後再試。",
"VOUCHER_CHECK_SCHEDULE_NOT_FOUND": "找不到立帳憑證檢核排程任務。",
"VOUCHER_CHECK_PERSIST_FAILED": "檢核結果寫入失敗。",
"VOUCHER_CHECK_PO_PDF_INVALID": "採購單 PDF 資料無效:請提供合法的發票號和訂單號。",
"VOUCHER_CHECK_PO_UPLOAD_FAILED": "採購單 PDF 上傳到文件庫「PO訂單」目錄失敗。",
"TRANSFER_PERMISSION_DENIED": "無在途調撥權限。",
"TRANSFER_RECEIPT_NOT_MATURED": "當天收料尚未成熟,不可查詢或調撥。",
"TRANSFER_FILE_NOT_READY": "收料檔案尚未就緒。",
+31 -3
View File
@@ -784,6 +784,8 @@
"title": "立帳憑證檢核任務",
"subtitle": "每週二增量檢核上一個自然月;掃描銷售開票附件類型目錄後按 invoice 歸檔,並彙總缺件。",
"period": "資料所屬期間",
"periodMonthAll": "全部",
"periodMonthValue": "{n}月",
"status": "狀態",
"statusAll": "全部",
"statusComplete": "完整",
@@ -791,6 +793,8 @@
"statusSkipped": "跳過",
"statusTechError": "技術失敗",
"statusPending": "待處理",
"statusQueued": "排隊中",
"statusRunning": "執行中",
"invoiceNo": "invoice",
"invoiceDate": "發票日期",
"invoicePlaceholder": "輸入 invoice 篩選",
@@ -800,7 +804,6 @@
"checkedAt": "執行時間",
"result": "結論",
"search": "查詢",
"refresh": "重新整理",
"loading": "載入中…",
"empty": "暫無檢核批次",
"loadFailed": "載入檢核任務失敗",
@@ -826,9 +829,34 @@
"viewDetail": "查看詳情",
"forceRecheck": "強制重檢上月",
"failureReason": "失敗原因",
"forceConfirm": "將全量重檢上一個自然月,不跳過已歸檔紀錄,也不使用上方篩選的期間。確定開始?",
"forceQueued": "已排入強制重檢({runNo}),完成後列表會自動重新整理。",
"forceConfirm": "將全量重檢上一個自然月,不跳過已歸檔紀錄,也不使用下方篩選的期間。確定開始?",
"forceQueued": "已排入強制重檢({runNo}),進度將在本卡更新。",
"forceFailed": "強制重檢排入失敗",
"latestTitle": "最近一次檢核",
"latestEmpty": "暫無檢核批次",
"latestLoadFailed": "載入最近一次檢核失敗",
"latestBatch": "批次 {runNo}",
"latestPeriod": "期間 {period}",
"modeIncremental": "增量",
"modeForceAll": "全量重檢",
"modeSingle": "單票",
"progress": "進度 {percent}%",
"startedAt": "開始",
"finishedAt": "完成",
"inProgress": "進行中",
"viewLatestDetail": "查看本批詳情",
"archivedFiles": "已歸檔檔案",
"processedHint": "已處理 {processed} / {total} 張 invoice",
"latestDoneHint": "本批已完成,缺件結果已寫入 Excel。",
"latestCompleteHint": "本批已完成。",
"stepQueued": "已排入強制重檢上月",
"stepQueuedHint": "等待 schedule worker 領取",
"stepFetchErp": "拉取上月銷售 invoice",
"stepFetchErpIncomplete": "拉取上月銷售 invoice 未完成",
"stepScanDms": "掃描銷售開票附件類型目錄",
"stepPersist": "寫入檢核紀錄",
"stepNotify": "發送企微彙總",
"stepDone": "檢核完成",
"tabTasks": "檢核任務",
"tabNotifications": "企微發送紀錄",
"notifyEmpty": "暫無企業微信發送紀錄",