feat(invoice-check): 通过invoice号反查tghx的采购单,生成PO订单

This commit is contained in:
sophie committed 2026-09-15 16:15:08 +08:00
1 parent 1c34ab962f
commit 40cead7430
27 files changed
+792 -74

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()
+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,
@@ -379,6 +380,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)
@@ -3,8 +3,8 @@ backend/app/services/voucher_check/adapters/erp_po_print.py
用途:ERP 反查 PO 后写入「PO订单」类型目录的 Adapter。
依赖:adapters.base、erp_po_repository、voucher_check.po_order。
逻辑:fetch_documents / publish_for_invoices 已接线(HXJM.oma99 → TGHX.pmm99)。
fetch() 仍占位,周任务不调用。render_given 只出本地 PDF。
逻辑:fetch_documents / publish_for_invoices 由独立排程 accounting-voucher-po-print(周二 05:00)调用。
fetch() 仍占位,检核 runner(周二 06:00)不调用。render_given 只出本地 PDF。
"""
from __future__ import annotations
@@ -30,7 +30,7 @@ class ErpPoPrintAdapter:
def fetch(self, *, period_month: date, subjects: list[SubjectRow]) -> list[ScannedFile]:
"""
周检核入口仍关闭。
【AI 触发时机】不要在周二 runner 中调用。独立抓取请用 fetch_documents / publish_for_invoices。
【AI 触发时机】不要在周二检核 runner 中调用。独立抓取排程请用 fetch_documents / publish_for_invoices。
"""
raise ServiceUnavailableError(
"ERP PO 打印尚未接入周检核",
@@ -50,7 +50,7 @@ class ErpPoPrintAdapter:
) -> list[PoOrderDocument]:
"""
按发票号从 ERP 组装制式采购单数据。
【AI 触发时机】独立抓取 PO、已有 invoice 清单时调用;不要在周二 runner 里调用。
【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
@@ -97,7 +97,7 @@ class ErpPoPrintAdapter:
) -> list[PoOrderPublishResult]:
"""
按发票号查 ERP、生成 PDF 并上传到当月「PO订单」目录。
【AI 触发时机】独立抓取任务要写入文档库时调用;不要在周二 runner 里调用。
【AI 触发时机】独立抓取任务要写入文档库时调用;检核 runner 不要调用。周二 05:00 排程走本方法。
"""
results: list[PoOrderPublishResult] = []
for document in self.fetch_documents(invoice_nos, config=config):
+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:
@@ -407,7 +407,7 @@ def fetch_po_documents_for_invoices(
) -> list[PoOrderDocument]:
"""
按销售发票号从 ERP 组装制式采购单数据。
【AI 触发时机】独立「抓取 PO」任务已有 invoice 清单、要生成 PDF 之前调用;不要在周二 runner 里调用。
【AI 触发时机】独立「抓取 PO」任务或周二 05:00 accounting-voucher-po-print 排程已有 invoice 清单、要生成 PDF 之前调用;不要在检核 runner 里调用。
核心逻辑:HXJM.oma99(空则 oga99/oea99)TRIM 后对 TGHX.pmm99;一票可多张 PO,每张一个文档。
@@ -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,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;subject_adapter=hxjm_apa 实际查 oma_file;erp_po_print.fetch / oa_sales_release 仅登记,不在周二 runner 调用。PO 独立抓取走 fetch_documents。
逻辑:周任务扫描 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
+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.fetch / oa_sales_release.fetch;命中文件复制到所有归档,同名跳过仍记 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},
)
@@ -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
@@ -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
+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'
)