feat(invoice-check): ww OA下载销货放行单
This commit is contained in:
1 parent
f25f59142a
commit
d13f1035cc
40 files changed
+2284
-103
No files matched your search
@@ -103,14 +103,16 @@ def create_app(config_name='default'):
|
||||
try:
|
||||
from app.services.voucher_check.schedule_seed import (
|
||||
ensure_default_voucher_check_schedule,
|
||||
ensure_default_voucher_oa_sales_release_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()
|
||||
ensure_default_voucher_oa_sales_release_schedule()
|
||||
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||
logger.warning('Failed to ensure accounting-voucher-check / po-print schedules: %s', exc)
|
||||
logger.warning('Failed to ensure accounting-voucher-check / po-print / oa-sales-release schedules: %s', exc)
|
||||
try:
|
||||
from app.services.contract_payment.schedule_seed import ensure_default_contract_payment_schedules
|
||||
ensure_default_contract_payment_schedules()
|
||||
|
||||
@@ -625,6 +625,24 @@ class Config:
|
||||
VOUCHER_CHECK_DMS_LIBRARY_ID = os.getenv('VOUCHER_CHECK_DMS_LIBRARY_ID', '').strip()
|
||||
VOUCHER_CHECK_DMS_ROOT_FOLDER_ID = os.getenv('VOUCHER_CHECK_DMS_ROOT_FOLDER_ID', '').strip()
|
||||
|
||||
# 立账凭证销货放行单:E10 OpenAPI + ecology10(密码仅 env;DATABASE 禁止回退 E9 ecology)
|
||||
OA_E10_OPENAPI_BASE_URL = os.getenv('OA_E10_OPENAPI_BASE_URL', '').strip().rstrip('/')
|
||||
OA_E10_CORPID = os.getenv('OA_E10_CORPID', '').strip()
|
||||
OA_E10_APP_KEY = os.getenv('OA_E10_APP_KEY', '').strip()
|
||||
OA_E10_APP_SECRET = os.getenv('OA_E10_APP_SECRET', '')
|
||||
OA_E10_USERID = os.getenv('OA_E10_USERID', '').strip()
|
||||
OA_E10_TIMEOUT_SECONDS = int(os.getenv('OA_E10_TIMEOUT_SECONDS', '30') or '30')
|
||||
OA_E10_TOKEN_REFRESH_SKEW_SECONDS = int(os.getenv('OA_E10_TOKEN_REFRESH_SKEW_SECONDS', '300') or '300')
|
||||
OA_E10_SQLSERVER_HOST = os.getenv('OA_E10_SQLSERVER_HOST', '').strip()
|
||||
OA_E10_SQLSERVER_PORT = os.getenv('OA_E10_SQLSERVER_PORT', '').strip()
|
||||
OA_E10_SQLSERVER_DATABASE = os.getenv('OA_E10_SQLSERVER_DATABASE', 'ecology10').strip() or 'ecology10'
|
||||
OA_E10_SQLSERVER_USERNAME = os.getenv('OA_E10_SQLSERVER_USERNAME', '').strip()
|
||||
OA_E10_SQLSERVER_PASSWORD = os.getenv('OA_E10_SQLSERVER_PASSWORD', '')
|
||||
OA_E10_SQLSERVER_DRIVER = os.getenv('OA_E10_SQLSERVER_DRIVER', '').strip()
|
||||
OA_E10_SQLSERVER_ENCRYPT = os.getenv('OA_E10_SQLSERVER_ENCRYPT', '').strip()
|
||||
OA_E10_SQLSERVER_TRUST_CERT = os.getenv('OA_E10_SQLSERVER_TRUST_CERT', '').strip()
|
||||
OA_E10_SQLSERVER_TIMEOUT = os.getenv('OA_E10_SQLSERVER_TIMEOUT', '').strip()
|
||||
|
||||
# MinIO 配置
|
||||
MINIO_ENDPOINT = os.getenv('MINIO_ENDPOINT', '127.0.0.1:9000')
|
||||
MINIO_ACCESS_KEY = os.getenv('MINIO_ACCESS_KEY', 'minioadmin')
|
||||
|
||||
@@ -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、voucher_po_print_job、job_params。
|
||||
依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、voucher_po_print_job、voucher_oa_sales_release_job、job_params。
|
||||
逻辑:internal_jobs API 与 platform_job 排程通过 platform_api_path 引用已注册 key;
|
||||
api/schedule/platform_tasks.py 下发 params_schema 供前端 DynamicTaskParamsForm 通用渲染。
|
||||
"""
|
||||
@@ -140,12 +140,17 @@ 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_oa_sales_release_job import run_voucher_oa_sales_release_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, DEFAULT_PO_PRINT_JOB_PARAMS
|
||||
from app.services.voucher_check.config import (
|
||||
DEFAULT_JOB_PARAMS,
|
||||
DEFAULT_OA_SALES_RELEASE_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,
|
||||
@@ -430,6 +435,43 @@ def _register_builtin_platform_jobs() -> None:
|
||||
),
|
||||
defaults=dict(DEFAULT_PO_PRINT_JOB_PARAMS),
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="accounting-voucher-oa-sales-release",
|
||||
label="立账凭证销货放行单拉取",
|
||||
label_key="admin.schedule.form.platformJobAccountingVoucherOaSalesRelease",
|
||||
handler=run_voucher_oa_sales_release_schedule,
|
||||
description="每周二 05:30 从 E10 筛上月已归档销货放行单,下载表单 PDF 并上传到「销货单」;早于 06:00 检核周批。",
|
||||
description_key="admin.schedule.form.accountingVoucherOaSalesReleaseHint",
|
||||
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_OA_SALES_RELEASE_JOB_PARAMS),
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="in-transit-receipt-file",
|
||||
label="在途收料文件抓取",
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
"""
|
||||
backend/app/services/schedule/voucher_oa_sales_release_job.py
|
||||
|
||||
用途:立账凭证销货放行单拉取 platform_job 薄封装。
|
||||
依赖:voucher_check.oa_sales_release_runner。
|
||||
逻辑:job_registry 注册 accounting-voucher-oa-sales-release 后由 schedule worker 调用;早于检核周批。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.voucher_check.oa_sales_release_runner import (
|
||||
ScheduleExecuteResult,
|
||||
run_oa_sales_release_batch,
|
||||
)
|
||||
|
||||
|
||||
def run_voucher_oa_sales_release_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""
|
||||
执行立账凭证销货放行单拉取排程。
|
||||
核心逻辑:委托 oa_sales_release_runner;默认周二 05:30,检核周批 06:00 只扫目录。
|
||||
"""
|
||||
return run_oa_sales_release_batch(task, run)
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/adapters/__init__.py
|
||||
|
||||
用途:登记销售一期 Adapter(主体、目录扫描、PO 取数、OA 占位、归档)。
|
||||
依赖:各 adapter 模块;PO 制式 PDF 在 voucher_check.po_order;ERP 取数在 erp_po_repository。
|
||||
逻辑:import 本包即完成 register_adapter;runner 只通过 registry 取实例,不调用 erp_po_print.fetch。
|
||||
用途:登记销售一期 Adapter(主体、目录扫描、PO 取数、OA 销货放行单、归档)。
|
||||
依赖:各 adapter 模块;PO 制式 PDF 在 voucher_check.po_order;ERP 取数在 erp_po_repository;OA 在 oa_e10_*。
|
||||
逻辑:import 本包即完成 register_adapter;runner 只通过 registry 取实例,不调用 erp_po_print.fetch / oa_sales_release.fetch。
|
||||
"""
|
||||
|
||||
from app.services.voucher_check.adapters.base import (
|
||||
|
||||
@@ -1,32 +1,39 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/adapters/oa_sales_release.py
|
||||
|
||||
用途:OA 销货放行单模拟页面打印的占位 Adapter。
|
||||
依赖:adapters.base。
|
||||
逻辑:一期规则已定但页面自动化未实现;周任务不调用,只扫描「销货单」目录。
|
||||
用途:从 E10 下载销货放行单 PDF 并写入「销货单」类型目录的 Adapter。
|
||||
依赖:adapters.base、oa_e10_client、oa_e10_repository、oa_sales_release_publish。
|
||||
逻辑:fetch_rows / download_pdf / upload_given 由独立排程 accounting-voucher-oa-sales-release(周二 05:30)调用。
|
||||
fetch() 仍占位,检核 runner(周二 06:00)不调用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.voucher_check.adapters.base import ScannedFile, SubjectRow
|
||||
from app.services.voucher_check.oa_e10_repository import SalesReleaseRow
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.services.voucher_check.oa_e10_client import OaE10OpenApiClient
|
||||
from app.services.voucher_check.oa_sales_release_publish import SalesReleasePublishResult
|
||||
|
||||
|
||||
class OaSalesReleaseAdapter:
|
||||
"""销货放行单打印占位;未接线时禁止生成假 PDF。"""
|
||||
"""销货放行单:E10 取数与上传已就绪;周检核 fetch 仍不启用。"""
|
||||
|
||||
source_type = "oa_sales_release"
|
||||
wired = False
|
||||
|
||||
def fetch(self, *, period_month: date, subjects: list[SubjectRow]) -> list[ScannedFile]:
|
||||
"""
|
||||
预留:按上月/归档/HXJM/发票号非空过滤后逐条打印。
|
||||
【AI 触发时机】仅当独立「抓取销货放行单」任务上线后调用。
|
||||
周检核入口仍关闭。
|
||||
【AI 触发时机】不要在周二检核 runner 中调用。独立抓取排程请用 fetch_rows / upload_given。
|
||||
"""
|
||||
raise ServiceUnavailableError(
|
||||
"OA 销货放行单打印尚未接线",
|
||||
"OA 销货放行单尚未接入周检核",
|
||||
code="VOUCHER_CHECK.ADAPTER_NOT_WIRED",
|
||||
details={
|
||||
"adapter": self.source_type,
|
||||
@@ -34,3 +41,49 @@ class OaSalesReleaseAdapter:
|
||||
"subject_count": len(subjects),
|
||||
},
|
||||
)
|
||||
|
||||
def fetch_rows(
|
||||
self,
|
||||
*,
|
||||
period_month: date,
|
||||
scope_code: str = "HXJM",
|
||||
) -> list[SalesReleaseRow]:
|
||||
"""
|
||||
按出货时间所在自然月从 ecology10.ft_xqqgsq 列出可下载行。
|
||||
【AI 触发时机】独立抓取销货放行单、需要 SQL 清单时调用;检核 runner 不要调用。
|
||||
"""
|
||||
from app.services.voucher_check.oa_e10_repository import fetch_sales_release_rows
|
||||
|
||||
return fetch_sales_release_rows(period_month, scope_code=scope_code)
|
||||
|
||||
def download_pdf(self, row: SalesReleaseRow, *, client: OaE10OpenApiClient) -> bytes | None:
|
||||
"""
|
||||
attList 取 PDF fileid 再下载。
|
||||
【AI 触发时机】已有 bdpdf、需要表单 PDF 字节时。无 PDF 附件返回 None(记跳过,不用 html)。
|
||||
|
||||
Args:
|
||||
row: SQL 筛出的销货放行单。
|
||||
client: 同一 Job 共用的 OpenAPI 客户端(带 token 缓存)。
|
||||
|
||||
Returns:
|
||||
PDF 字节;attList 无 pdf 时 None。
|
||||
"""
|
||||
file_id = client.list_pdf_file_id(row.doc_id)
|
||||
if not file_id:
|
||||
return None
|
||||
return client.download_pdf(file_id)
|
||||
|
||||
def upload_given(
|
||||
self,
|
||||
row: SalesReleaseRow,
|
||||
content: bytes,
|
||||
*,
|
||||
period_month: date,
|
||||
) -> SalesReleasePublishResult:
|
||||
"""
|
||||
把已下载 PDF 上传到销售开票附件/{年}/{月}/销货单/。
|
||||
【AI 触发时机】已拿到 PDF 字节、需要写入文档库类型目录时。同名跳过;不要在周检核 runner 中调用。
|
||||
"""
|
||||
from app.services.voucher_check.oa_sales_release_publish import publish_sales_release_pdf
|
||||
|
||||
return publish_sales_release_pdf(row, content, period_month=period_month)
|
||||
@@ -1,10 +1,10 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/config.py
|
||||
|
||||
用途:解析立账凭证检核 / PO 生成环境变量与 ScheduleTask.job_params。
|
||||
用途:解析立账凭证检核 / PO 生成 / 销货放行单拉取的环境变量与 ScheduleTask.job_params。
|
||||
依赖:Flask current_app.config、core.errors.ValidationError。
|
||||
逻辑:runner / po_print_runner / erp_repository 启动前调用;非法配置抛 VOUCHER_CHECK.CONFIG_INVALID;
|
||||
ERP 账号优先 VOUCHER_CHECK_ERP_*,否则 ERP_*,再回退 CONTRACT_PAYMENT_ERP_*。
|
||||
逻辑:runner / po_print_runner / oa_sales_release_runner / erp_repository 启动前调用;非法配置抛 VOUCHER_CHECK.CONFIG_INVALID;
|
||||
ERP 账号优先 VOUCHER_CHECK_ERP_*,否则 ERP_*,再回退 CONTRACT_PAYMENT_ERP_*。销货放行单 Job 不读 ERP。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -30,6 +30,12 @@ DEFAULT_PO_PRINT_JOB_PARAMS: dict[str, Any] = {
|
||||
"notify_failure_enabled": True,
|
||||
}
|
||||
|
||||
DEFAULT_OA_SALES_RELEASE_JOB_PARAMS: dict[str, Any] = {
|
||||
"profile_code": "sales",
|
||||
"scope_code": "HXJM",
|
||||
"notify_failure_enabled": True,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VoucherCheckEngineConfig:
|
||||
|
||||
@@ -0,0 +1,452 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/oa_e10_client.py
|
||||
|
||||
用途:泛微 E10 OpenAPI 客户端(authorize / token / refresh / attList / download)。
|
||||
依赖:requests、oa_e10_settings、core.errors。
|
||||
逻辑:独立周批 accounting-voucher-oa-sales-release 共用进程内 token;检核 runner 不调用。
|
||||
不把 code / accessToken / refreshToken 写入日志或仓库。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from urllib.parse import quote
|
||||
|
||||
import requests
|
||||
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
from app.services.voucher_check.oa_e10_settings import OaE10Settings, load_oa_e10_settings
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_TOKEN_LOCK = threading.Lock()
|
||||
_TOKEN_CACHE: dict[str, Any] = {
|
||||
"access_token": None,
|
||||
"refresh_token": None,
|
||||
"expires_at": 0.0,
|
||||
}
|
||||
|
||||
ERR_INVALID_ACCESS_TOKEN = "200007"
|
||||
ERR_INVALID_REFRESH_TOKEN = "300001"
|
||||
_PDF_MAGIC = b"%PDF"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OaE10TokenBundle:
|
||||
"""内存中的 access / refresh 与绝对过期时刻(epoch 秒)。"""
|
||||
|
||||
access_token: str
|
||||
refresh_token: str
|
||||
expires_at: float
|
||||
|
||||
|
||||
def errcode_of(payload: Any) -> str:
|
||||
"""从 OpenAPI JSON 取出 errcode,统一成字符串。"""
|
||||
if not isinstance(payload, dict):
|
||||
return ""
|
||||
value = payload.get("errcode")
|
||||
if value is None:
|
||||
value = payload.get("errCode")
|
||||
if value is None:
|
||||
return ""
|
||||
return str(value).strip()
|
||||
|
||||
|
||||
def is_ok_errcode(payload: Any) -> bool:
|
||||
"""errcode 为 0 / 缺省且带业务字段时视为成功。"""
|
||||
code = errcode_of(payload)
|
||||
return code in {"", "0", "ok", "OK"}
|
||||
|
||||
|
||||
def pick_pdf_file_id(items: list[Any]) -> str | None:
|
||||
"""
|
||||
从 attList 数组中取 PDF 附件的 fileid。
|
||||
核心逻辑:看 type / extName / 文件名,禁止把 html 当正本。
|
||||
|
||||
Args:
|
||||
items: attList 返回的附件对象列表。
|
||||
|
||||
Returns:
|
||||
fileid 字符串;没有 PDF 则 None。
|
||||
"""
|
||||
for item in items:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
type_name = str(item.get("type") or "").strip().lower().lstrip(".")
|
||||
ext_name = str(
|
||||
item.get("extName") or item.get("extname") or item.get("ext") or ""
|
||||
).strip().lower().lstrip(".")
|
||||
filename = str(
|
||||
item.get("name") or item.get("filename") or item.get("fileName") or item.get("imagefileName") or ""
|
||||
).strip().lower()
|
||||
if type_name != "pdf" and ext_name != "pdf" and not filename.endswith(".pdf"):
|
||||
continue
|
||||
file_id = item.get("fileid")
|
||||
if file_id is None:
|
||||
file_id = item.get("fileId") or item.get("file_id")
|
||||
text = str(file_id or "").strip()
|
||||
if text:
|
||||
return text
|
||||
return None
|
||||
|
||||
|
||||
def extract_att_list(payload: Any) -> list[Any]:
|
||||
"""从 attList 响应中取出附件数组。"""
|
||||
if isinstance(payload, list):
|
||||
return payload
|
||||
if not isinstance(payload, dict):
|
||||
return []
|
||||
for key in ("data", "Data", "list", "attList", "attachments"):
|
||||
value = payload.get(key)
|
||||
if isinstance(value, list):
|
||||
return value
|
||||
if isinstance(value, dict):
|
||||
for inner in ("list", "data", "Data", "items", "attList"):
|
||||
nested = value.get(inner)
|
||||
if isinstance(nested, list):
|
||||
return nested
|
||||
return []
|
||||
|
||||
|
||||
def is_pdf_bytes(content: bytes) -> bool:
|
||||
"""判断下载体是否为 PDF(看魔数,不看文件名)。"""
|
||||
return bool(content) and content.lstrip()[:4] == _PDF_MAGIC
|
||||
|
||||
|
||||
def reset_oa_e10_token_cache() -> None:
|
||||
"""清空进程内 token,供测试隔离。"""
|
||||
with _TOKEN_LOCK:
|
||||
_TOKEN_CACHE["access_token"] = None
|
||||
_TOKEN_CACHE["refresh_token"] = None
|
||||
_TOKEN_CACHE["expires_at"] = 0.0
|
||||
|
||||
|
||||
def _token_failed(message: str, *, details: dict[str, Any] | None = None) -> ServiceUnavailableError:
|
||||
return ServiceUnavailableError(
|
||||
message,
|
||||
code="VOUCHER_CHECK.OA_E10_TOKEN_FAILED",
|
||||
details=details or {},
|
||||
)
|
||||
|
||||
|
||||
def _download_failed(message: str, *, details: dict[str, Any] | None = None) -> ServiceUnavailableError:
|
||||
return ServiceUnavailableError(
|
||||
message,
|
||||
code="VOUCHER_CHECK.OA_E10_DOWNLOAD_FAILED",
|
||||
details=details or {},
|
||||
)
|
||||
|
||||
|
||||
class OaE10OpenApiClient:
|
||||
"""
|
||||
E10 OpenAPI:任务启动换 token,业务接口共用;到期前 5 分钟 refresh。
|
||||
不要在周检核 runner 中构造本客户端去扫票。
|
||||
"""
|
||||
|
||||
def __init__(self, settings: OaE10Settings, *, session: requests.Session | None = None):
|
||||
self._settings = settings
|
||||
self._session = session or requests.Session()
|
||||
|
||||
@classmethod
|
||||
def from_config(cls) -> "OaE10OpenApiClient":
|
||||
"""从环境加载配置并构造客户端。"""
|
||||
return cls(load_oa_e10_settings())
|
||||
|
||||
def ensure_access_token(self) -> str:
|
||||
"""
|
||||
返回当前可用的 accessToken。
|
||||
【AI 触发时机】本 Job 第一次调 attList/download 前,以及发现将过期时。
|
||||
|
||||
核心逻辑:缓存有效则直接用;将过期走 refresh;refresh 返回 300001 则重新 authorize。
|
||||
"""
|
||||
with _TOKEN_LOCK:
|
||||
return self._ensure_access_token_locked()
|
||||
|
||||
def list_pdf_file_id(self, doc_id: str) -> str | None:
|
||||
"""
|
||||
按 bdpdf(docId)查附件列表,返回 PDF 的 fileid。
|
||||
【AI 触发时机】SQL 已筛出销货放行单、需要下载表单 PDF 时。
|
||||
|
||||
Args:
|
||||
doc_id: 表字段 bdpdf,必须当字符串,禁止当 JS number。
|
||||
|
||||
Returns:
|
||||
PDF fileid;列表无 PDF 则 None(调用方记缺件/跳过,不要用 html)。
|
||||
"""
|
||||
wanted = str(doc_id or "").strip()
|
||||
if not wanted:
|
||||
raise ValidationError(
|
||||
"缺少 bdpdf/docId",
|
||||
code="VOUCHER_CHECK.OA_SALES_RELEASE_INVALID",
|
||||
details={"field": "doc_id"},
|
||||
)
|
||||
path = f"/api/doc/v2/attList/{quote(wanted, safe='')}"
|
||||
payload = self._json_with_token("GET", path)
|
||||
items = extract_att_list(payload)
|
||||
return pick_pdf_file_id(items)
|
||||
|
||||
def download_pdf(self, file_id: str) -> bytes:
|
||||
"""
|
||||
按 fileid 下载 PDF 字节流。
|
||||
【AI 触发时机】attList 已定位 PDF 附件之后。不要传入 bdpdf。
|
||||
|
||||
Args:
|
||||
file_id: attList 返回的 fileid。
|
||||
|
||||
Returns:
|
||||
PDF 内容。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: 下载失败或响应不是 PDF。
|
||||
"""
|
||||
wanted = str(file_id or "").strip()
|
||||
if not wanted:
|
||||
raise ValidationError(
|
||||
"缺少 fileid",
|
||||
code="VOUCHER_CHECK.OA_SALES_RELEASE_INVALID",
|
||||
details={"field": "file_id"},
|
||||
)
|
||||
path = f"/api/file/v2/common/download/{quote(wanted, safe='')}"
|
||||
content = self._bytes_with_token("GET", path)
|
||||
if not is_pdf_bytes(content):
|
||||
raise _download_failed("E10 下载响应不是 PDF", details={"file_id_len": len(wanted)})
|
||||
return content
|
||||
|
||||
def _ensure_access_token_locked(self) -> str:
|
||||
now = time.time()
|
||||
access = str(_TOKEN_CACHE.get("access_token") or "").strip()
|
||||
expires_at = float(_TOKEN_CACHE.get("expires_at") or 0.0)
|
||||
skew = self._settings.token_refresh_skew_seconds
|
||||
if access and now < (expires_at - skew):
|
||||
return access
|
||||
refresh = str(_TOKEN_CACHE.get("refresh_token") or "").strip()
|
||||
if refresh:
|
||||
try:
|
||||
bundle = self._refresh_token(refresh)
|
||||
self._store_bundle(bundle)
|
||||
return bundle.access_token
|
||||
except ServiceUnavailableError as exc:
|
||||
details = exc.details or {}
|
||||
if str(details.get("errcode") or "") != ERR_INVALID_REFRESH_TOKEN:
|
||||
raise
|
||||
_LOGGER.info("[oa-e10] refresh_token invalid, re-authorize")
|
||||
bundle = self._authorize_and_exchange()
|
||||
self._store_bundle(bundle)
|
||||
return bundle.access_token
|
||||
|
||||
def _store_bundle(self, bundle: OaE10TokenBundle) -> None:
|
||||
_TOKEN_CACHE["access_token"] = bundle.access_token
|
||||
_TOKEN_CACHE["refresh_token"] = bundle.refresh_token
|
||||
_TOKEN_CACHE["expires_at"] = bundle.expires_at
|
||||
|
||||
def _authorize_and_exchange(self) -> OaE10TokenBundle:
|
||||
# [STEP 1] 立即取 code,不落库、不打日志
|
||||
state = secrets.token_urlsafe(16)
|
||||
auth_payload = self._request_json(
|
||||
"POST",
|
||||
"/oauth2/authorize",
|
||||
params={
|
||||
"corpid": self._settings.corpid,
|
||||
"response_type": "code",
|
||||
"state": state,
|
||||
},
|
||||
)
|
||||
if not is_ok_errcode(auth_payload):
|
||||
raise _token_failed(
|
||||
"E10 authorize 失败",
|
||||
details={"errcode": errcode_of(auth_payload)},
|
||||
)
|
||||
code = str(auth_payload.get("code") or "").strip()
|
||||
if not code:
|
||||
raise _token_failed("E10 authorize 未返回 code")
|
||||
# [STEP 2] 立刻用 code 换 token;code 一次性,此处用完即弃
|
||||
token_payload = self._request_json(
|
||||
"POST",
|
||||
"/oauth2/access_token",
|
||||
json_body={
|
||||
"app_key": self._settings.app_key,
|
||||
"app_secret": self._settings.app_secret,
|
||||
"grant_type": "authorization_code",
|
||||
"code": code,
|
||||
},
|
||||
)
|
||||
return self._parse_token_payload(token_payload, stage="access_token")
|
||||
|
||||
def _refresh_token(self, refresh_token: str) -> OaE10TokenBundle:
|
||||
payload = self._request_json(
|
||||
"POST",
|
||||
"/oauth2/refresh_token",
|
||||
json_body={
|
||||
"grant_type": "refresh_token",
|
||||
"refresh_token": refresh_token,
|
||||
},
|
||||
)
|
||||
code = errcode_of(payload)
|
||||
if code == ERR_INVALID_REFRESH_TOKEN:
|
||||
raise _token_failed(
|
||||
"E10 refresh_token 无效或过期",
|
||||
details={"errcode": code},
|
||||
)
|
||||
return self._parse_token_payload(payload, stage="refresh_token")
|
||||
|
||||
def _parse_token_payload(self, payload: dict[str, Any], *, stage: str) -> OaE10TokenBundle:
|
||||
if not is_ok_errcode(payload):
|
||||
raise _token_failed(
|
||||
f"E10 {stage} 失败",
|
||||
details={"errcode": errcode_of(payload)},
|
||||
)
|
||||
access = str(payload.get("accessToken") or payload.get("access_token") or "").strip()
|
||||
refresh = str(payload.get("refreshToken") or payload.get("refresh_token") or "").strip()
|
||||
if not access:
|
||||
raise _token_failed(f"E10 {stage} 未返回 accessToken")
|
||||
expires_raw = payload.get("expires_in")
|
||||
if expires_raw is None:
|
||||
expires_raw = payload.get("expiresIn")
|
||||
try:
|
||||
expires_in = int(expires_raw)
|
||||
except (TypeError, ValueError):
|
||||
raise _token_failed(f"E10 {stage} 未返回有效 expires_in") from None
|
||||
if expires_in <= 0:
|
||||
raise _token_failed(f"E10 {stage} expires_in 非法")
|
||||
if not refresh:
|
||||
refresh = str(_TOKEN_CACHE.get("refresh_token") or "").strip()
|
||||
return OaE10TokenBundle(
|
||||
access_token=access,
|
||||
refresh_token=refresh,
|
||||
expires_at=time.time() + expires_in,
|
||||
)
|
||||
|
||||
def _json_with_token(self, method: str, path: str) -> dict[str, Any]:
|
||||
payload = self._request_json(method, path, with_token=True)
|
||||
if errcode_of(payload) != ERR_INVALID_ACCESS_TOKEN:
|
||||
if not is_ok_errcode(payload):
|
||||
raise _download_failed(
|
||||
"E10 OpenAPI 业务调用失败",
|
||||
details={"errcode": errcode_of(payload), "path": path},
|
||||
)
|
||||
return payload
|
||||
# [STEP 3] 200007:刷新或重授权一次后再试,同一请求不无限循环
|
||||
self._recover_token_once()
|
||||
payload = self._request_json(method, path, with_token=True)
|
||||
if not is_ok_errcode(payload):
|
||||
raise _download_failed(
|
||||
"E10 OpenAPI 在刷新 token 后仍失败",
|
||||
details={"errcode": errcode_of(payload), "path": path},
|
||||
)
|
||||
return payload
|
||||
|
||||
def _bytes_with_token(self, method: str, path: str) -> bytes:
|
||||
content, payload = self._request_bytes(method, path, with_token=True)
|
||||
if payload is None:
|
||||
return content
|
||||
if errcode_of(payload) != ERR_INVALID_ACCESS_TOKEN:
|
||||
raise _download_failed(
|
||||
"E10 文件下载失败",
|
||||
details={"errcode": errcode_of(payload), "path": path},
|
||||
)
|
||||
self._recover_token_once()
|
||||
content, payload = self._request_bytes(method, path, with_token=True)
|
||||
if payload is None:
|
||||
return content
|
||||
raise _download_failed(
|
||||
"E10 文件下载在刷新 token 后仍失败",
|
||||
details={"errcode": errcode_of(payload), "path": path},
|
||||
)
|
||||
|
||||
def _recover_token_once(self) -> None:
|
||||
"""accessToken 被业务口判无效:保留 refreshToken 先续期,失败再 authorize。"""
|
||||
with _TOKEN_LOCK:
|
||||
_TOKEN_CACHE["access_token"] = None
|
||||
_TOKEN_CACHE["expires_at"] = 0.0
|
||||
self._ensure_access_token_locked()
|
||||
|
||||
def _token_query(self) -> dict[str, str]:
|
||||
token = self.ensure_access_token()
|
||||
return {
|
||||
"access_token": token,
|
||||
"userid": self._settings.userid,
|
||||
}
|
||||
|
||||
def _request_json(
|
||||
self,
|
||||
method: str,
|
||||
path: str,
|
||||
*,
|
||||
params: dict[str, str] | None = None,
|
||||
json_body: dict[str, Any] | None = None,
|
||||
with_token: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
query = dict(params or {})
|
||||
if with_token:
|
||||
query.update(self._token_query())
|
||||
response = self._send(method, path, params=query, json_body=json_body)
|
||||
try:
|
||||
payload = response.json()
|
||||
except ValueError as exc:
|
||||
raise _download_failed("E10 OpenAPI 返回非 JSON", details={"path": path}) from exc
|
||||
if not isinstance(payload, dict):
|
||||
raise _download_failed("E10 OpenAPI JSON 不是对象", details={"path": path})
|
||||
return payload
|
||||
|
||||
def _request_bytes(
|
||||
self,
|
||||
method: str,
|
||||
path: str,
|
||||
*,
|
||||
with_token: bool = False,
|
||||
) -> tuple[bytes, dict[str, Any] | None]:
|
||||
query = self._token_query() if with_token else {}
|
||||
response = self._send(method, path, params=query, json_body=None)
|
||||
content_type = str(response.headers.get("Content-Type") or "").lower()
|
||||
body = response.content or b""
|
||||
looks_json = "json" in content_type or body.lstrip()[:1] in {b"{", b"["}
|
||||
if looks_json and not is_pdf_bytes(body):
|
||||
try:
|
||||
payload = response.json()
|
||||
except ValueError:
|
||||
payload = None
|
||||
if isinstance(payload, dict):
|
||||
return b"", payload
|
||||
return body, None
|
||||
|
||||
def _send(
|
||||
self,
|
||||
method: str,
|
||||
path: str,
|
||||
*,
|
||||
params: dict[str, str],
|
||||
json_body: dict[str, Any] | None,
|
||||
) -> requests.Response:
|
||||
url = f"{self._settings.openapi_base_url}{path}"
|
||||
timeout = self._settings.timeout_seconds
|
||||
try:
|
||||
if json_body is not None:
|
||||
response = self._session.request(
|
||||
method,
|
||||
url,
|
||||
params=params,
|
||||
json=json_body,
|
||||
timeout=timeout,
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
else:
|
||||
response = self._session.request(
|
||||
method,
|
||||
url,
|
||||
params=params,
|
||||
timeout=timeout,
|
||||
)
|
||||
except requests.RequestException as exc:
|
||||
_LOGGER.warning("[oa-e10] request failed path=%s error=%s", path, type(exc).__name__)
|
||||
raise _download_failed("E10 OpenAPI 网络失败", details={"path": path}) from exc
|
||||
if response.status_code >= 400:
|
||||
raise _download_failed(
|
||||
"E10 OpenAPI HTTP 失败",
|
||||
details={"path": path, "http_status": response.status_code},
|
||||
)
|
||||
return response
|
||||
@@ -0,0 +1,174 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/oa_e10_repository.py
|
||||
|
||||
用途:只读查询 E10 ecology10.dbo.ft_xqqgsq,筛上月已归档销货放行单。
|
||||
依赖:pyodbc、oa_e10_settings、integrations.oa.sqlserver(仅挑 ODBC 驱动)。
|
||||
逻辑:独立周批取数;不走 E9 ecology;fphm/xhdh 空行在 Python 丢弃。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
from app.services.voucher_check.oa_e10_settings import OaE10Settings, load_oa_e10_settings
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
SALES_RELEASE_TABLE = "dbo.ft_xqqgsq"
|
||||
|
||||
_LIST_SQL = f"""
|
||||
SELECT fphm, xhdh, bdpdf
|
||||
FROM {SALES_RELEASE_TABLE}
|
||||
WHERE ISNULL(IS_DELETE, 0) = 0
|
||||
AND bdpdf IS NOT NULL
|
||||
AND LTRIM(RTRIM(CONVERT(varchar(64), bdpdf))) <> ''
|
||||
AND gdrq IS NOT NULL
|
||||
AND LTRIM(RTRIM(CONVERT(varchar(64), gdrq))) <> ''
|
||||
AND LTRIM(RTRIM(CONVERT(varchar(32), zt))) = ?
|
||||
AND TRY_CONVERT(datetime, chsj) IS NOT NULL
|
||||
AND TRY_CONVERT(datetime, chsj) >= ?
|
||||
AND TRY_CONVERT(datetime, chsj) < ?
|
||||
"""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SalesReleaseRow:
|
||||
"""一条可下载的销货放行单:发票号、销货单号、表单 PDF 文档 ID。"""
|
||||
|
||||
invoice_no: str
|
||||
delivery_no: str
|
||||
doc_id: str
|
||||
|
||||
|
||||
def _cell_text(value: Any) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
return str(value).strip()
|
||||
|
||||
|
||||
def _sql_failed(message: str, *, details: dict[str, Any] | None = None) -> ServiceUnavailableError:
|
||||
return ServiceUnavailableError(
|
||||
message,
|
||||
code="VOUCHER_CHECK.OA_E10_SQL_FAILED",
|
||||
details=details or {},
|
||||
)
|
||||
|
||||
|
||||
def _open_connection(settings: OaE10Settings):
|
||||
"""
|
||||
打开 ecology10 只读连接。
|
||||
核心逻辑:驱动名可回退本机已装 ODBC;不复用 E9 ecology 库名。
|
||||
"""
|
||||
try:
|
||||
import pyodbc
|
||||
except ImportError as exc:
|
||||
raise _sql_failed("未安装 pyodbc,无法连接 E10 SQL Server") from exc
|
||||
|
||||
from app.services.integrations.oa.sqlserver import OASQLServerService
|
||||
|
||||
driver = str(settings.sql_driver or "").strip() or OASQLServerService._pick_driver()
|
||||
available = pyodbc.drivers()
|
||||
if driver not in available:
|
||||
driver = OASQLServerService._pick_driver()
|
||||
|
||||
conn_str = (
|
||||
f"DRIVER={{{driver}}};"
|
||||
f"SERVER={settings.sql_host},{settings.sql_port};"
|
||||
f"DATABASE={settings.sql_database};"
|
||||
f"UID={settings.sql_username};"
|
||||
f"PWD={settings.sql_password};"
|
||||
)
|
||||
if driver != "SQL Server":
|
||||
conn_str += (
|
||||
f"Encrypt={settings.sql_encrypt};"
|
||||
f"TrustServerCertificate={settings.sql_trust_cert};"
|
||||
)
|
||||
try:
|
||||
return pyodbc.connect(conn_str, timeout=settings.sql_timeout)
|
||||
except Exception as exc:
|
||||
_LOGGER.warning("[oa-e10] sql connect failed error=%s", type(exc).__name__)
|
||||
raise _sql_failed("连接 E10 ecology10 失败") from exc
|
||||
|
||||
|
||||
def map_sales_release_row(raw: Any) -> SalesReleaseRow | None:
|
||||
"""
|
||||
把查询行收成 SalesReleaseRow;fphm / xhdh / bdpdf 任一空则丢弃。
|
||||
核心逻辑:与 incomplete_relation_policy=skip 一致,不记字段异常。
|
||||
"""
|
||||
if isinstance(raw, dict):
|
||||
invoice_no = _cell_text(raw.get("fphm") or raw.get("invoice_no"))
|
||||
delivery_no = _cell_text(raw.get("xhdh") or raw.get("delivery_no"))
|
||||
doc_id = _cell_text(raw.get("bdpdf") or raw.get("doc_id"))
|
||||
else:
|
||||
invoice_no = _cell_text(raw[0] if len(raw) > 0 else "")
|
||||
delivery_no = _cell_text(raw[1] if len(raw) > 1 else "")
|
||||
doc_id = _cell_text(raw[2] if len(raw) > 2 else "")
|
||||
if not invoice_no or not delivery_no or not doc_id:
|
||||
return None
|
||||
return SalesReleaseRow(invoice_no=invoice_no, delivery_no=delivery_no, doc_id=doc_id)
|
||||
|
||||
|
||||
def fetch_sales_release_rows(
|
||||
period_month: date,
|
||||
*,
|
||||
scope_code: str = "HXJM",
|
||||
settings: OaE10Settings | None = None,
|
||||
connection: Any | None = None,
|
||||
) -> list[SalesReleaseRow]:
|
||||
"""
|
||||
查询上月已归档、未删除、有表单 PDF 的销货放行单。
|
||||
【AI 触发时机】独立周批要列出待下载 PDF 时调用;不要从检核 runner 调。
|
||||
|
||||
Args:
|
||||
period_month: 检核月首日(上一个自然月)。
|
||||
scope_code: 对应 zt,一期固定 HXJM。
|
||||
settings: 可注入配置;缺省从环境加载。
|
||||
connection: 测试可注入已打开连接。
|
||||
|
||||
Returns:
|
||||
关联字段完整的行;空 fphm/xhdh 已丢弃。
|
||||
"""
|
||||
month = period_month.replace(day=1) if period_month.day != 1 else period_month
|
||||
if month.month == 12:
|
||||
next_month = date(month.year + 1, 1, 1)
|
||||
else:
|
||||
next_month = date(month.year, month.month + 1, 1)
|
||||
zt = str(scope_code or "").strip().upper() or "HXJM"
|
||||
start = datetime(month.year, month.month, 1, 0, 0, 0)
|
||||
end = datetime(next_month.year, next_month.month, 1, 0, 0, 0)
|
||||
cfg = settings if settings is not None else load_oa_e10_settings()
|
||||
own_connection = connection is None
|
||||
conn = connection if connection is not None else _open_connection(cfg)
|
||||
rows: list[SalesReleaseRow] = []
|
||||
skipped_incomplete = 0
|
||||
try:
|
||||
cursor = conn.cursor()
|
||||
try:
|
||||
cursor.execute(_LIST_SQL, (zt, start, end))
|
||||
for raw in cursor.fetchall():
|
||||
mapped = map_sales_release_row(raw)
|
||||
if mapped is None:
|
||||
skipped_incomplete += 1
|
||||
continue
|
||||
rows.append(mapped)
|
||||
except Exception as exc:
|
||||
if isinstance(exc, (ServiceUnavailableError, ValidationError)):
|
||||
raise
|
||||
_LOGGER.warning("[oa-e10] sql query failed error=%s", type(exc).__name__)
|
||||
raise _sql_failed("查询 E10 ft_xqqgsq 失败") from exc
|
||||
finally:
|
||||
cursor.close()
|
||||
finally:
|
||||
if own_connection:
|
||||
conn.close()
|
||||
_LOGGER.info(
|
||||
"[oa-e10] listed period=%s rows=%s skipped_incomplete=%s",
|
||||
month.isoformat(),
|
||||
len(rows),
|
||||
skipped_incomplete,
|
||||
)
|
||||
return rows
|
||||
@@ -0,0 +1,144 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/oa_e10_settings.py
|
||||
|
||||
用途:读取立账凭证销货放行单所用的 E10 OpenAPI 与 ecology10 SQL 配置。
|
||||
依赖:Flask current_app.config、环境变量 OA_E10_*;SQL 主机/账号可回退 OA_SQLSERVER_*。
|
||||
逻辑:由 oa_e10_client / oa_e10_repository 在批次开始前调用;DATABASE 默认 ecology10,禁止落到 E9 ecology。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
|
||||
from flask import current_app, has_app_context
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
DEFAULT_E10_DATABASE = "ecology10"
|
||||
_FORBIDDEN_E9_DATABASE = "ecology"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OaE10Settings:
|
||||
"""E10 OpenAPI + ecology10 只读连接;凭据不入日志。"""
|
||||
|
||||
openapi_base_url: str
|
||||
corpid: str
|
||||
app_key: str
|
||||
app_secret: str
|
||||
userid: str
|
||||
timeout_seconds: int
|
||||
token_refresh_skew_seconds: int
|
||||
sql_host: str
|
||||
sql_port: str
|
||||
sql_database: str
|
||||
sql_username: str
|
||||
sql_password: str
|
||||
sql_driver: str
|
||||
sql_encrypt: str
|
||||
sql_trust_cert: str
|
||||
sql_timeout: int
|
||||
|
||||
|
||||
def _cfg(key: str, fallback: str = "") -> str:
|
||||
"""优先 Flask config,再环境变量。"""
|
||||
if has_app_context():
|
||||
value = current_app.config.get(key)
|
||||
if value is not None and str(value).strip():
|
||||
return str(value).strip()
|
||||
return str(os.getenv(key) or fallback or "").strip()
|
||||
|
||||
|
||||
def _cfg_raw(key: str, fallback: str = "") -> str:
|
||||
"""读取可能含空格的密钥;密码不强剥首尾以外的内容。"""
|
||||
if has_app_context():
|
||||
value = current_app.config.get(key)
|
||||
if value is not None and str(value) != "":
|
||||
return str(value)
|
||||
env = os.getenv(key)
|
||||
if env is not None and env != "":
|
||||
return env
|
||||
return fallback
|
||||
|
||||
|
||||
def _as_int(raw: str, default: int, *, minimum: int = 1) -> int:
|
||||
try:
|
||||
return max(minimum, int(str(raw).strip() or default))
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def load_oa_e10_settings() -> OaE10Settings:
|
||||
"""
|
||||
组装 E10 配置。
|
||||
核心逻辑:OpenAPI 五项必填;SQL HOST/USER/PASSWORD 可回退 OA_SQLSERVER_*,DATABASE 只认 OA_E10_*(默认 ecology10)。
|
||||
|
||||
Returns:
|
||||
OaE10Settings
|
||||
|
||||
Raises:
|
||||
ValidationError: 缺必填项,或 DATABASE 误配成 E9 ecology。
|
||||
"""
|
||||
openapi_base_url = _cfg("OA_E10_OPENAPI_BASE_URL").rstrip("/")
|
||||
sql_host = _cfg("OA_E10_SQLSERVER_HOST") or _cfg("OA_SQLSERVER_HOST")
|
||||
sql_port = _cfg("OA_E10_SQLSERVER_PORT") or _cfg("OA_SQLSERVER_PORT") or "1433"
|
||||
sql_database = _cfg("OA_E10_SQLSERVER_DATABASE") or DEFAULT_E10_DATABASE
|
||||
sql_username = _cfg("OA_E10_SQLSERVER_USERNAME") or _cfg("OA_SQLSERVER_USERNAME")
|
||||
sql_password = _cfg_raw("OA_E10_SQLSERVER_PASSWORD") or _cfg_raw("OA_SQLSERVER_PASSWORD")
|
||||
sql_driver = _cfg("OA_E10_SQLSERVER_DRIVER") or _cfg("OA_SQLSERVER_DRIVER")
|
||||
sql_encrypt = (_cfg("OA_E10_SQLSERVER_ENCRYPT") or _cfg("OA_SQLSERVER_ENCRYPT") or "no").lower()
|
||||
sql_trust_cert = (_cfg("OA_E10_SQLSERVER_TRUST_CERT") or _cfg("OA_SQLSERVER_TRUST_CERT") or "yes").lower()
|
||||
sql_timeout = _as_int(
|
||||
_cfg("OA_E10_SQLSERVER_TIMEOUT") or _cfg("OA_SQLSERVER_TIMEOUT") or "10",
|
||||
10,
|
||||
)
|
||||
|
||||
missing = [
|
||||
key
|
||||
for key, value in (
|
||||
("OA_E10_OPENAPI_BASE_URL", openapi_base_url),
|
||||
("OA_E10_CORPID", _cfg("OA_E10_CORPID")),
|
||||
("OA_E10_APP_KEY", _cfg("OA_E10_APP_KEY")),
|
||||
("OA_E10_APP_SECRET", _cfg_raw("OA_E10_APP_SECRET")),
|
||||
("OA_E10_USERID", _cfg("OA_E10_USERID")),
|
||||
("OA_E10_SQLSERVER_HOST", sql_host),
|
||||
("OA_E10_SQLSERVER_USERNAME", sql_username),
|
||||
("OA_E10_SQLSERVER_PASSWORD", sql_password),
|
||||
)
|
||||
if not str(value or "").strip()
|
||||
]
|
||||
if missing:
|
||||
raise ValidationError(
|
||||
"E10 OpenAPI 或 ecology10 SQL 配置不完整",
|
||||
code="VOUCHER_CHECK.CONFIG_INVALID",
|
||||
details={"missing": missing},
|
||||
)
|
||||
if sql_database.lower() == _FORBIDDEN_E9_DATABASE:
|
||||
raise ValidationError(
|
||||
"OA_E10_SQLSERVER_DATABASE 不能使用 E9 库 ecology",
|
||||
code="VOUCHER_CHECK.CONFIG_INVALID",
|
||||
details={"database": sql_database},
|
||||
)
|
||||
return OaE10Settings(
|
||||
openapi_base_url=openapi_base_url,
|
||||
corpid=_cfg("OA_E10_CORPID"),
|
||||
app_key=_cfg("OA_E10_APP_KEY"),
|
||||
app_secret=_cfg_raw("OA_E10_APP_SECRET"),
|
||||
userid=_cfg("OA_E10_USERID"),
|
||||
timeout_seconds=_as_int(_cfg("OA_E10_TIMEOUT_SECONDS") or "30", 30),
|
||||
token_refresh_skew_seconds=_as_int(
|
||||
_cfg("OA_E10_TOKEN_REFRESH_SKEW_SECONDS") or "300",
|
||||
300,
|
||||
minimum=0,
|
||||
),
|
||||
sql_host=sql_host,
|
||||
sql_port=sql_port,
|
||||
sql_database=sql_database,
|
||||
sql_username=sql_username,
|
||||
sql_password=sql_password,
|
||||
sql_driver=sql_driver,
|
||||
sql_encrypt=sql_encrypt,
|
||||
sql_trust_cert=sql_trust_cert,
|
||||
sql_timeout=sql_timeout,
|
||||
)
|
||||
@@ -0,0 +1,59 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/oa_sales_release_filename.py
|
||||
|
||||
用途:按销售 Profile 规则生成销货放行申请单 PDF 文件名。
|
||||
依赖:core.errors.ValidationError。
|
||||
逻辑:固定 `{invoice}-{delivery_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]|(\.\.)')
|
||||
SALES_RELEASE_FILENAME_TEMPLATE = "{invoice}-{delivery_no}.pdf"
|
||||
|
||||
|
||||
def build_sales_release_filename(*, invoice_no: str, delivery_no: str) -> str:
|
||||
"""
|
||||
生成 `{invoice号}-{销货单号}.pdf`。
|
||||
【AI 触发时机】保存或匹配销货放行单 PDF 文件名时调用;不要自行拼接。
|
||||
|
||||
Args:
|
||||
invoice_no: 销售 invoice(fphm),禁止空串与路径字符。
|
||||
delivery_no: 销货单号(xhdh),禁止空串与路径字符。
|
||||
|
||||
Returns:
|
||||
仅文件名,不含目录。
|
||||
|
||||
Raises:
|
||||
ValidationError: 缺号或含非法字符。
|
||||
"""
|
||||
invoice = str(invoice_no or "").strip()
|
||||
delivery = str(delivery_no or "").strip()
|
||||
if not invoice:
|
||||
raise ValidationError(
|
||||
"缺少 invoice_no",
|
||||
code="VOUCHER_CHECK.OA_SALES_RELEASE_INVALID",
|
||||
details={"field": "invoice_no"},
|
||||
)
|
||||
if not delivery:
|
||||
raise ValidationError(
|
||||
"缺少 delivery_no",
|
||||
code="VOUCHER_CHECK.OA_SALES_RELEASE_INVALID",
|
||||
details={"field": "delivery_no"},
|
||||
)
|
||||
if _UNSAFE_RE.search(invoice) or _UNSAFE_RE.search(delivery):
|
||||
raise ValidationError(
|
||||
"invoice 或销货单号含非法路径字符",
|
||||
code="VOUCHER_CHECK.OA_SALES_RELEASE_INVALID",
|
||||
details=_unsafe_details(invoice, delivery),
|
||||
)
|
||||
return f"{invoice}-{delivery}.pdf"
|
||||
|
||||
|
||||
def _unsafe_details(invoice: str, delivery: str) -> dict[str, Any]:
|
||||
return {"invoice_no": invoice, "delivery_no": delivery}
|
||||
@@ -0,0 +1,105 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/oa_sales_release_probe.py
|
||||
|
||||
用途:联调时从 E10 下载 1 张(或少量)销货放行单 PDF 到本地,验证 SQL → token → attList → download。
|
||||
依赖:Flask create_app、OaSalesReleaseAdapter、OaE10OpenApiClient、oa_sales_release_filename。
|
||||
逻辑:python -m app.services.voucher_check.oa_sales_release_probe --out-dir DIR [--invoice NO] [--limit 1]
|
||||
默认不上传文档库;加 --upload 才写入「销货单」。不把 token 打到 stdout。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _parse_period(raw: str | None) -> date:
|
||||
"""
|
||||
解析 YYYY-MM;空则用上一个自然月(与周批一致)。
|
||||
"""
|
||||
if not raw:
|
||||
from app.services.voucher_check.erp_repository import previous_period_bounds
|
||||
|
||||
period_month, *_ = previous_period_bounds()
|
||||
return period_month
|
||||
text = str(raw).strip()
|
||||
parts = text.split("-")
|
||||
if len(parts) != 2:
|
||||
raise ValueError("period 须为 YYYY-MM")
|
||||
year, month = int(parts[0]), int(parts[1])
|
||||
return date(year, month, 1)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
"""
|
||||
命令行入口:查 ecology10 → 下载 PDF 到 --out-dir。
|
||||
【AI 触发时机】需要验证 E10 销货放行单链路、且不要跑整月周批时运行本模块。
|
||||
|
||||
Returns:
|
||||
0 至少成功下载一张;1 无行 / 无 PDF / 配置失败。
|
||||
"""
|
||||
parser = argparse.ArgumentParser(description="从 E10 下载销货放行单 PDF(联调用,默认不上传文档库)")
|
||||
parser.add_argument("--out-dir", required=True, help="PDF 输出目录")
|
||||
parser.add_argument("--invoice", help="只处理该发票号(fphm);不填则按期间取前 N 张")
|
||||
parser.add_argument("--period", help="出货月 YYYY-MM,默认上一个自然月")
|
||||
parser.add_argument("--limit", type=int, default=1, help="最多成功下载张数,默认 1")
|
||||
parser.add_argument("--scope", default="HXJM", help="账套 zt,默认 HXJM")
|
||||
parser.add_argument(
|
||||
"--upload",
|
||||
action="store_true",
|
||||
help="同时上传到销售开票附件/{年}/{月}/销货单/(同名跳过)",
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
limit = max(1, int(args.limit or 1))
|
||||
out_dir = Path(args.out_dir)
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
from app import create_app
|
||||
from app.services.voucher_check.adapters.oa_sales_release import OaSalesReleaseAdapter
|
||||
from app.services.voucher_check.oa_e10_client import OaE10OpenApiClient
|
||||
from app.services.voucher_check.oa_e10_settings import load_oa_e10_settings
|
||||
from app.services.voucher_check.oa_sales_release_filename import build_sales_release_filename
|
||||
|
||||
app = create_app()
|
||||
with app.app_context():
|
||||
load_oa_e10_settings()
|
||||
period_month = _parse_period(args.period)
|
||||
adapter = OaSalesReleaseAdapter()
|
||||
rows = adapter.fetch_rows(period_month=period_month, scope_code=str(args.scope).strip().upper() or "HXJM")
|
||||
invoice = str(args.invoice or "").strip()
|
||||
if invoice:
|
||||
rows = [row for row in rows if row.invoice_no == invoice]
|
||||
if not rows:
|
||||
target = invoice or period_month.isoformat()[:7]
|
||||
print(f"no sales-release row for {target}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
client = OaE10OpenApiClient.from_config()
|
||||
client.ensure_access_token()
|
||||
downloaded = 0
|
||||
for row in rows:
|
||||
content = adapter.download_pdf(row, client=client)
|
||||
if content is None:
|
||||
print(f"skipped_no_pdf invoice={row.invoice_no} delivery={row.delivery_no}", file=sys.stderr)
|
||||
continue
|
||||
filename = build_sales_release_filename(invoice_no=row.invoice_no, delivery_no=row.delivery_no)
|
||||
dest = out_dir / filename
|
||||
dest.write_bytes(content)
|
||||
extra = ""
|
||||
if args.upload:
|
||||
result = adapter.upload_given(row, content, period_month=period_month)
|
||||
extra = " skipped_same_name" if result.skipped_same_name else " uploaded"
|
||||
print(f"{dest}{extra}")
|
||||
downloaded += 1
|
||||
if downloaded >= limit:
|
||||
break
|
||||
if downloaded == 0:
|
||||
print("no pdf downloaded", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,91 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/oa_sales_release_publish.py
|
||||
|
||||
用途:把已下载的销货放行单 PDF 上传到文档库当月「销货单」目录。
|
||||
依赖:SalesDmsClient、filename_match、oa_sales_release_filename。
|
||||
逻辑:同名跳过。不进周检核 runner;归档复制仍由检核阶段 directory_scan 之后完成。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
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.oa_e10_repository import SalesReleaseRow
|
||||
from app.services.voucher_check.oa_sales_release_filename import (
|
||||
SALES_RELEASE_FILENAME_TEMPLATE,
|
||||
build_sales_release_filename,
|
||||
)
|
||||
|
||||
SALES_RELEASE_TYPE_FOLDER = "销货单"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SalesReleasePublishResult:
|
||||
"""一次销货放行单落库结果。"""
|
||||
|
||||
file: ScannedFile
|
||||
skipped_same_name: bool
|
||||
|
||||
|
||||
def publish_sales_release_pdf(
|
||||
row: SalesReleaseRow,
|
||||
content: bytes,
|
||||
*,
|
||||
period_month: date,
|
||||
type_folder: str = SALES_RELEASE_TYPE_FOLDER,
|
||||
) -> SalesReleasePublishResult:
|
||||
"""
|
||||
将 `{invoice}-{销货单号}.pdf` 上传到销售开票附件/{年}/{月}/销货单/。
|
||||
【AI 触发时机】已从 E10 下到 PDF 字节、需要写入类型目录时调用。不要在周检核 runner 里调用。
|
||||
|
||||
核心逻辑:校验文件名 → 确保年/月/销货单目录 → 同名跳过否则 Upload+CreateFiles。
|
||||
|
||||
Args:
|
||||
row: 含 fphm / xhdh 的销货放行单。
|
||||
content: PDF 字节,禁止空。
|
||||
period_month: 类型目录所属自然月。
|
||||
type_folder: 默认「销货单」,须与销售 Profile 一致。
|
||||
|
||||
Returns:
|
||||
文档库中的文件元数据;skipped_same_name 表示沿用已有同名文件。
|
||||
"""
|
||||
filename = build_sales_release_filename(invoice_no=row.invoice_no, delivery_no=row.delivery_no)
|
||||
if match_filename(filename, template=SALES_RELEASE_FILENAME_TEMPLATE, invoice_no=row.invoice_no) is None:
|
||||
raise ValidationError(
|
||||
"生成的文件名不符合 {invoice}-{delivery_no}.pdf",
|
||||
code="VOUCHER_CHECK.OA_SALES_RELEASE_INVALID",
|
||||
)
|
||||
if not content:
|
||||
raise ValidationError("销货放行单 PDF 内容为空", code="VOUCHER_CHECK.OA_SALES_RELEASE_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)
|
||||
row_meta, skipped = SalesDmsClient.upload_file_skip_same_name(
|
||||
parent_folder_id=folder_id,
|
||||
leaf_name=filename,
|
||||
content=content,
|
||||
)
|
||||
item_id = str(row_meta.get("ID") or "").strip() or None
|
||||
return SalesReleasePublishResult(
|
||||
file=ScannedFile(
|
||||
filename=str(row_meta.get("LeafName") or filename).strip() or filename,
|
||||
item_id=item_id,
|
||||
folder_id=folder_id,
|
||||
path=str(row_meta.get("Path") or f"{folder_path}/{filename}"),
|
||||
extra={
|
||||
"skipped_same_name": skipped,
|
||||
"version_id": row_meta.get("VersionID"),
|
||||
"type_folder": type_folder,
|
||||
"doc_id": row.doc_id,
|
||||
},
|
||||
),
|
||||
skipped_same_name=skipped,
|
||||
)
|
||||
@@ -0,0 +1,238 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/oa_sales_release_runner.py
|
||||
|
||||
用途:立账凭证「销货放行单」周批:查 ecology10 → OpenAPI 下载 PDF → 上传到「销货单」。
|
||||
依赖:oa_e10_settings、OaE10OpenApiClient、OaSalesReleaseAdapter、dms_client、notification。
|
||||
逻辑:独立排程 accounting-voucher-oa-sales-release 调用;不要从检核 runner 调用。
|
||||
同名跳过;无 PDF 附件记 skipped;不写 voucher_check_runs。
|
||||
"""
|
||||
|
||||
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.oa_sales_release import OaSalesReleaseAdapter
|
||||
from app.services.voucher_check.config import DEFAULT_OA_SALES_RELEASE_JOB_PARAMS
|
||||
from app.services.voucher_check.dms_client import SalesDmsClient
|
||||
from app.services.voucher_check.erp_repository import previous_period_bounds
|
||||
from app.services.voucher_check.notification import send_failure_alert
|
||||
from app.services.voucher_check.oa_e10_client import OaE10OpenApiClient, reset_oa_e10_token_cache
|
||||
from app.services.voucher_check.oa_e10_settings import load_oa_e10_settings
|
||||
|
||||
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
|
||||
|
||||
|
||||
def _as_bool(value: Any, default: bool) -> bool:
|
||||
"""排程 job_params 布尔开关;非法值回退 default。"""
|
||||
if value is None:
|
||||
return default
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
text = str(value).strip().lower()
|
||||
if text in {"1", "true", "yes", "on"}:
|
||||
return True
|
||||
if text in {"0", "false", "no", "off"}:
|
||||
return False
|
||||
return default
|
||||
|
||||
|
||||
def _job_params(task: ScheduleTask) -> dict[str, Any]:
|
||||
params = dict(DEFAULT_OA_SALES_RELEASE_JOB_PARAMS)
|
||||
raw = task.job_params if isinstance(task.job_params, dict) else {}
|
||||
params.update({k: v for k, v in raw.items() if v is not None})
|
||||
return params
|
||||
|
||||
|
||||
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_oa_sales_release"] = payload
|
||||
run.response_summary_json = summary
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def run_oa_sales_release_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""
|
||||
按上月已归档销货放行单下载 PDF 并上传到文档库「销货单」。
|
||||
【AI 触发时机】仅 accounting-voucher-oa-sales-release 排程(默认周二 05:30)调用;检核周批不要调用。
|
||||
|
||||
核心逻辑:previous_period_bounds → SQL 筛行 → 共用 token 调 attList/download → upload_given(同名跳过)。
|
||||
不调用 OaSalesReleaseAdapter.fetch,不写 voucher_check_runs。
|
||||
|
||||
Returns:
|
||||
ScheduleExecuteResult:(行数, 新上传数, 失败数, 跳过数, details, errors, step_logs)
|
||||
跳过 = 同名已存在 + attList 无 PDF。
|
||||
"""
|
||||
step_logs: list[dict[str, Any]] = []
|
||||
errors: list[str] = []
|
||||
details: list[dict[str, Any]] = []
|
||||
adapter = OaSalesReleaseAdapter()
|
||||
current_app.logger.info(
|
||||
"[voucher-oa-sales-release] start name=%s path=accounting-voucher-oa-sales-release run_no=%s",
|
||||
getattr(task, "name", None) or "立账凭证销货放行单拉取",
|
||||
run.run_no,
|
||||
)
|
||||
_mark_domain_notification_managed(run)
|
||||
params = _job_params(task)
|
||||
notify_failure = _as_bool(params.get("notify_failure_enabled"), True)
|
||||
scope_code = str(params.get("scope_code") or "HXJM").strip().upper() or "HXJM"
|
||||
reset_oa_e10_token_cache()
|
||||
|
||||
try:
|
||||
load_oa_e10_settings()
|
||||
SalesDmsClient.ensure_configured()
|
||||
period_month, _current, _start, _end = previous_period_bounds()
|
||||
client = OaE10OpenApiClient.from_config()
|
||||
client.ensure_access_token()
|
||||
except AppError as exc:
|
||||
send_failure_alert(
|
||||
task=task,
|
||||
run=run,
|
||||
stage="config_or_token",
|
||||
error_code=exc.code,
|
||||
error_message=exc.message,
|
||||
enabled=True,
|
||||
title=f"立账凭证销货放行单拉取失败: {task.name}",
|
||||
)
|
||||
raise
|
||||
|
||||
try:
|
||||
rows = adapter.fetch_rows(period_month=period_month, scope_code=scope_code)
|
||||
except AppError as exc:
|
||||
send_failure_alert(
|
||||
task=task,
|
||||
run=run,
|
||||
stage="oa_sql",
|
||||
error_code=exc.code,
|
||||
error_message=exc.message,
|
||||
enabled=notify_failure,
|
||||
title=f"立账凭证销货放行单拉取失败: {task.name}",
|
||||
)
|
||||
raise
|
||||
|
||||
step_logs.append(
|
||||
{
|
||||
"step": "list_rows",
|
||||
"status": "success",
|
||||
"detail": {"period": period_month.isoformat(), "row_count": len(rows)},
|
||||
}
|
||||
)
|
||||
if not rows:
|
||||
_write_summary(
|
||||
run,
|
||||
{
|
||||
"period": period_month.isoformat(),
|
||||
"row_count": 0,
|
||||
"uploaded": 0,
|
||||
"skipped_same_name": 0,
|
||||
"skipped_no_pdf": 0,
|
||||
"failed": 0,
|
||||
},
|
||||
)
|
||||
return (0, 0, 0, 0, [], [], step_logs)
|
||||
|
||||
uploaded = 0
|
||||
skipped_same_name = 0
|
||||
skipped_no_pdf = 0
|
||||
failed = 0
|
||||
for row in rows:
|
||||
try:
|
||||
content = adapter.download_pdf(row, client=client)
|
||||
if content is None:
|
||||
skipped_no_pdf += 1
|
||||
details.append(
|
||||
{
|
||||
"invoice_no": row.invoice_no,
|
||||
"delivery_no": row.delivery_no,
|
||||
"status": "skipped_no_pdf",
|
||||
}
|
||||
)
|
||||
continue
|
||||
result = adapter.upload_given(row, content, 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": row.invoice_no,
|
||||
"delivery_no": row.delivery_no,
|
||||
"status": status,
|
||||
"filename": result.file.filename,
|
||||
}
|
||||
)
|
||||
except Exception as exc:
|
||||
failed += 1
|
||||
errors.append(f"{row.invoice_no}/{row.delivery_no}: {type(exc).__name__}")
|
||||
details.append(
|
||||
{
|
||||
"invoice_no": row.invoice_no,
|
||||
"delivery_no": row.delivery_no,
|
||||
"status": "failed",
|
||||
"error_type": type(exc).__name__,
|
||||
}
|
||||
)
|
||||
current_app.logger.exception(
|
||||
"[voucher-oa-sales-release] download/upload failed invoice=%s delivery=%s",
|
||||
row.invoice_no,
|
||||
row.delivery_no,
|
||||
)
|
||||
|
||||
skipped = skipped_same_name + skipped_no_pdf
|
||||
if failed:
|
||||
send_failure_alert(
|
||||
task=task,
|
||||
run=run,
|
||||
stage="download_or_upload",
|
||||
error_code="VOUCHER_CHECK.OA_SALES_RELEASE_PARTIAL",
|
||||
error_message=f"失败 {failed} 张,成功 {uploaded},跳过 {skipped}",
|
||||
enabled=notify_failure,
|
||||
title=f"立账凭证销货放行单拉取部分失败: {task.name}",
|
||||
)
|
||||
step_logs.append(
|
||||
{
|
||||
"step": "download_upload",
|
||||
"status": "failed" if failed else "success",
|
||||
"detail": {
|
||||
"uploaded": uploaded,
|
||||
"skipped_same_name": skipped_same_name,
|
||||
"skipped_no_pdf": skipped_no_pdf,
|
||||
"failed": failed,
|
||||
},
|
||||
}
|
||||
)
|
||||
_write_summary(
|
||||
run,
|
||||
{
|
||||
"period": period_month.isoformat(),
|
||||
"row_count": len(rows),
|
||||
"uploaded": uploaded,
|
||||
"skipped_same_name": skipped_same_name,
|
||||
"skipped_no_pdf": skipped_no_pdf,
|
||||
"failed": failed,
|
||||
},
|
||||
)
|
||||
current_app.logger.info(
|
||||
"[voucher-oa-sales-release] done period=%s rows=%s uploaded=%s skipped=%s failed=%s",
|
||||
period_month.isoformat(),
|
||||
len(rows),
|
||||
uploaded,
|
||||
skipped,
|
||||
failed,
|
||||
)
|
||||
return (len(rows), 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 PDF 由独立排程 accounting-voucher-po-print(周二 05:00)写入类型目录。
|
||||
逻辑:周任务扫描 source_type=directory_scan;subject_adapter=hxjm_apa 实际查 oma_file;erp_po_print.fetch / oa_sales_release.fetch 仅登记,不在检核 runner 调用。PO PDF 由独立排程 accounting-voucher-po-print(周二 05:00)写入类型目录;销货放行单 PDF 由 accounting-voucher-oa-sales-release(周二 05:30)写入「销货单」。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -3,7 +3,7 @@ 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;PO PDF 由独立排程 accounting-voucher-po-print 提前写入类型目录。
|
||||
逻辑:不调用 erp_po_print.fetch / oa_sales_release.fetch;PO PDF 由 accounting-voucher-po-print(周二 05:00)、销货放行单由 accounting-voucher-oa-sales-release(周二 05:30)提前写入类型目录。
|
||||
命中文件复制到所有归档,同名跳过仍记 archived。
|
||||
"""
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
backend/app/services/voucher_check/schedule_seed.py
|
||||
|
||||
用途:确保立账凭证检核(周二 06:00)与 PO 订单生成(周二 05:00)默认 ScheduleTask 存在。
|
||||
用途:确保立账凭证检核(周二 06:00)、PO 订单生成(周二 05:00)、销货放行单拉取(周二 05:30)默认 ScheduleTask 存在。
|
||||
依赖:ScheduleTask/User、timezone_util、voucher_check.config。
|
||||
逻辑:迁移种子 + create_app / User after_commit 幂等补建;检核排程剥离 schema 外的旧 job_params。
|
||||
"""
|
||||
@@ -19,7 +19,11 @@ 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, DEFAULT_PO_PRINT_JOB_PARAMS
|
||||
from app.services.voucher_check.config import (
|
||||
DEFAULT_JOB_PARAMS,
|
||||
DEFAULT_OA_SALES_RELEASE_JOB_PARAMS,
|
||||
DEFAULT_PO_PRINT_JOB_PARAMS,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -33,6 +37,11 @@ DEFAULT_VOUCHER_PO_PRINT_PLATFORM_PATH = "accounting-voucher-po-print"
|
||||
DEFAULT_VOUCHER_PO_PRINT_CRON = "0 5 * * 2"
|
||||
DEFAULT_VOUCHER_PO_PRINT_NAME = "立账凭证 PO 订单生成(周批)"
|
||||
|
||||
DEFAULT_VOUCHER_OA_SALES_RELEASE_SCHEDULE_NO = "SCH-ACCOUNTING-VOUCHER-OA-SALES-RELEASE"
|
||||
DEFAULT_VOUCHER_OA_SALES_RELEASE_PLATFORM_PATH = "accounting-voucher-oa-sales-release"
|
||||
DEFAULT_VOUCHER_OA_SALES_RELEASE_CRON = "30 5 * * 2"
|
||||
DEFAULT_VOUCHER_OA_SALES_RELEASE_NAME = "立账凭证销货放行单拉取(周批)"
|
||||
|
||||
_HOOKS_REGISTERED = False
|
||||
_SESSION_INFO_KEY = "_seed_voucher_check_schedule"
|
||||
|
||||
@@ -275,6 +284,100 @@ def ensure_default_voucher_po_print_schedule(
|
||||
return task
|
||||
|
||||
|
||||
def ensure_default_voucher_oa_sales_release_schedule(
|
||||
*,
|
||||
commit: bool = True,
|
||||
session: Any | None = None,
|
||||
) -> ScheduleTask | None:
|
||||
"""
|
||||
幂等确保默认销货放行单拉取周批排程存在(周二 05:30,介于 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_OA_SALES_RELEASE_SCHEDULE_NO)
|
||||
| (ScheduleTask.platform_api_path == DEFAULT_VOUCHER_OA_SALES_RELEASE_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-oa-sales-release 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_OA_SALES_RELEASE_CRON,
|
||||
timezone_name="Asia/Shanghai",
|
||||
) or now
|
||||
|
||||
task = ScheduleTask(
|
||||
schedule_no=DEFAULT_VOUCHER_OA_SALES_RELEASE_SCHEDULE_NO,
|
||||
name=DEFAULT_VOUCHER_OA_SALES_RELEASE_NAME,
|
||||
schedule_type="platform_job",
|
||||
owner_user_id=int(owner.id),
|
||||
cron_expr=DEFAULT_VOUCHER_OA_SALES_RELEASE_CRON,
|
||||
schedule_timezone="Asia/Shanghai",
|
||||
wait_seconds=0,
|
||||
platform_api_path=DEFAULT_VOUCHER_OA_SALES_RELEASE_PLATFORM_PATH,
|
||||
job_params=dict(DEFAULT_OA_SALES_RELEASE_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_OA_SALES_RELEASE_SCHEDULE_NO)
|
||||
| (ScheduleTask.platform_api_path == DEFAULT_VOUCHER_OA_SALES_RELEASE_PLATFORM_PATH)
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if existing is not None:
|
||||
return existing
|
||||
raise
|
||||
else:
|
||||
sess.flush()
|
||||
_LOGGER.info("seeded accounting-voucher-oa-sales-release schedule id=%s", task.id)
|
||||
return task
|
||||
|
||||
|
||||
def register_voucher_check_schedule_hooks() -> None:
|
||||
"""注册 User after_commit 补建钩子(幂等)。"""
|
||||
global _HOOKS_REGISTERED
|
||||
@@ -294,6 +397,7 @@ def register_voucher_check_schedule_hooks() -> None:
|
||||
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)
|
||||
ensure_default_voucher_oa_sales_release_schedule(commit=True, session=new_sess)
|
||||
except Exception:
|
||||
_LOGGER.exception("voucher-check schedule seed after_commit failed")
|
||||
|
||||
|
||||
@@ -219,6 +219,7 @@ def test_get_platform_jobs_api(client, admin_jwt_headers):
|
||||
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"
|
||||
assert by_key["accounting-voucher-oa-sales-release"]["label_key"] == "admin.schedule.form.platformJobAccountingVoucherOaSalesRelease"
|
||||
|
||||
defs = client.get("/api/admin/platform-tasks/definitions", headers=admin_jwt_headers)
|
||||
assert defs.status_code == 200
|
||||
|
||||
@@ -0,0 +1,392 @@
|
||||
"""
|
||||
backend/tests/voucher_check/test_oa_sales_release_schedule.py
|
||||
|
||||
用途:销货放行单周批早于检核,且不走 oa_sales_release.fetch。
|
||||
依赖:pytest、app fixture;不连 E10 SQL / OpenAPI / 文档库。
|
||||
逻辑:断言 cron 05:30、种子幂等、下载后上传、无 PDF 跳过、检核 fetch 仍关闭。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.voucher_check.adapters.oa_sales_release import OaSalesReleaseAdapter
|
||||
from app.services.voucher_check.oa_e10_client import (
|
||||
OaE10OpenApiClient,
|
||||
pick_pdf_file_id,
|
||||
reset_oa_e10_token_cache,
|
||||
)
|
||||
from app.services.voucher_check.oa_e10_repository import SalesReleaseRow, map_sales_release_row
|
||||
from app.services.voucher_check.oa_e10_settings import OaE10Settings, load_oa_e10_settings
|
||||
from app.services.voucher_check.oa_sales_release_filename import build_sales_release_filename
|
||||
from app.services.voucher_check.oa_sales_release_runner import run_oa_sales_release_batch
|
||||
from app.services.voucher_check.schedule_seed import (
|
||||
DEFAULT_VOUCHER_CHECK_CRON,
|
||||
DEFAULT_VOUCHER_OA_SALES_RELEASE_CRON,
|
||||
DEFAULT_VOUCHER_OA_SALES_RELEASE_PLATFORM_PATH,
|
||||
DEFAULT_VOUCHER_OA_SALES_RELEASE_SCHEDULE_NO,
|
||||
DEFAULT_VOUCHER_PO_PRINT_CRON,
|
||||
ensure_default_voucher_check_schedule,
|
||||
ensure_default_voucher_oa_sales_release_schedule,
|
||||
ensure_default_voucher_po_print_schedule,
|
||||
)
|
||||
|
||||
|
||||
def _settings(**overrides) -> OaE10Settings:
|
||||
payload = dict(
|
||||
openapi_base_url="http://e10.test/papi/openapi",
|
||||
corpid="corp-1",
|
||||
app_key="key-1",
|
||||
app_secret="secret-1",
|
||||
userid="1001",
|
||||
timeout_seconds=10,
|
||||
token_refresh_skew_seconds=300,
|
||||
sql_host="sql.test",
|
||||
sql_port="1433",
|
||||
sql_database="ecology10",
|
||||
sql_username="reader",
|
||||
sql_password="hidden",
|
||||
sql_driver="",
|
||||
sql_encrypt="no",
|
||||
sql_trust_cert="yes",
|
||||
sql_timeout=10,
|
||||
)
|
||||
payload.update(overrides)
|
||||
return OaE10Settings(**payload)
|
||||
|
||||
|
||||
class _FakeResponse:
|
||||
def __init__(self, payload=None, content=b"", status=200, content_type="application/json"):
|
||||
self._payload = payload
|
||||
self.content = content
|
||||
self.status_code = status
|
||||
self.headers = {"Content-Type": content_type}
|
||||
|
||||
def json(self):
|
||||
if self._payload is None:
|
||||
raise ValueError("no json")
|
||||
return self._payload
|
||||
|
||||
|
||||
class _FakeSession:
|
||||
def __init__(self, routes: dict[str, list[_FakeResponse]]):
|
||||
self.routes = routes
|
||||
self.calls: list[str] = []
|
||||
|
||||
def request(self, method, url, **kwargs):
|
||||
path = url.split("openapi", 1)[-1] if "openapi" in url else url
|
||||
key = f"{method.upper()} {path.split('?')[0]}"
|
||||
self.calls.append(key)
|
||||
queue = self.routes.get(key)
|
||||
if not queue:
|
||||
raise AssertionError(f"unexpected request {key}")
|
||||
return queue.pop(0)
|
||||
|
||||
|
||||
def test_oa_sales_release_cron_is_between_po_and_check():
|
||||
"""周二 05:30 介于 PO 05:00 与检核 06:00。"""
|
||||
assert DEFAULT_VOUCHER_PO_PRINT_CRON == "0 5 * * 2"
|
||||
assert DEFAULT_VOUCHER_OA_SALES_RELEASE_CRON == "30 5 * * 2"
|
||||
assert DEFAULT_VOUCHER_CHECK_CRON == "0 6 * * 2"
|
||||
|
||||
|
||||
def test_ensure_oa_sales_release_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="oa-sales-seed-admin",
|
||||
email="oa-sales-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)
|
||||
po = ensure_default_voucher_po_print_schedule(commit=True)
|
||||
first = ensure_default_voucher_oa_sales_release_schedule(commit=True)
|
||||
second = ensure_default_voucher_oa_sales_release_schedule(commit=True)
|
||||
assert check is not None
|
||||
assert po is not None
|
||||
assert first is not None
|
||||
assert first.id == second.id
|
||||
assert first.schedule_no == DEFAULT_VOUCHER_OA_SALES_RELEASE_SCHEDULE_NO
|
||||
assert first.platform_api_path == DEFAULT_VOUCHER_OA_SALES_RELEASE_PLATFORM_PATH
|
||||
assert first.cron_expr == DEFAULT_VOUCHER_OA_SALES_RELEASE_CRON
|
||||
assert first.platform_api_path != check.platform_api_path
|
||||
assert first.platform_api_path != po.platform_api_path
|
||||
|
||||
|
||||
def test_pick_pdf_file_id_skips_html():
|
||||
"""只要 PDF 的 fileid,忽略 html。"""
|
||||
file_id = pick_pdf_file_id(
|
||||
[
|
||||
{"type": "html", "fileid": "111"},
|
||||
{"extName": "pdf", "fileid": "1317512696036114467"},
|
||||
]
|
||||
)
|
||||
assert file_id == "1317512696036114467"
|
||||
assert pick_pdf_file_id([{"type": "html", "fileid": "111"}]) is None
|
||||
|
||||
|
||||
def test_map_sales_release_row_skips_incomplete():
|
||||
assert map_sales_release_row(("INV-1", "XH-1", "8448")) == SalesReleaseRow(
|
||||
invoice_no="INV-1",
|
||||
delivery_no="XH-1",
|
||||
doc_id="8448",
|
||||
)
|
||||
assert map_sales_release_row(("", "XH-1", "8448")) is None
|
||||
assert map_sales_release_row(("INV-1", "", "8448")) is None
|
||||
|
||||
|
||||
def test_build_sales_release_filename():
|
||||
assert build_sales_release_filename(invoice_no="EWZZ01", delivery_no="XH-9") == "EWZZ01-XH-9.pdf"
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
build_sales_release_filename(invoice_no="a/b", delivery_no="XH-9")
|
||||
assert exc.value.code == "VOUCHER_CHECK.OA_SALES_RELEASE_INVALID"
|
||||
|
||||
|
||||
def test_load_settings_rejects_e9_ecology(app):
|
||||
with app.app_context():
|
||||
app.config["OA_E10_OPENAPI_BASE_URL"] = "http://e10.test/papi/openapi"
|
||||
app.config["OA_E10_CORPID"] = "corp"
|
||||
app.config["OA_E10_APP_KEY"] = "key"
|
||||
app.config["OA_E10_APP_SECRET"] = "secret"
|
||||
app.config["OA_E10_USERID"] = "1"
|
||||
app.config["OA_E10_SQLSERVER_HOST"] = "sql"
|
||||
app.config["OA_E10_SQLSERVER_USERNAME"] = "reader"
|
||||
app.config["OA_E10_SQLSERVER_PASSWORD"] = "hidden"
|
||||
app.config["OA_E10_SQLSERVER_DATABASE"] = "ecology"
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
load_oa_e10_settings()
|
||||
assert exc.value.code == "VOUCHER_CHECK.CONFIG_INVALID"
|
||||
|
||||
|
||||
def test_token_cached_then_refresh_on_200007():
|
||||
"""任务内缓存 accessToken;业务口 200007 时刷新一次再试。"""
|
||||
reset_oa_e10_token_cache()
|
||||
session = _FakeSession(
|
||||
{
|
||||
"POST /oauth2/authorize": [
|
||||
_FakeResponse({"errcode": "0", "code": "once-code"}),
|
||||
],
|
||||
"POST /oauth2/access_token": [
|
||||
_FakeResponse(
|
||||
{
|
||||
"errcode": "0",
|
||||
"accessToken": "atk-1",
|
||||
"refreshToken": "rtk-1",
|
||||
"expires_in": 7200,
|
||||
}
|
||||
),
|
||||
],
|
||||
"POST /oauth2/refresh_token": [
|
||||
_FakeResponse(
|
||||
{
|
||||
"errcode": "0",
|
||||
"accessToken": "atk-2",
|
||||
"refreshToken": "rtk-2",
|
||||
"expires_in": 7200,
|
||||
}
|
||||
),
|
||||
],
|
||||
"GET /api/doc/v2/attList/8448": [
|
||||
_FakeResponse({"errcode": "200007", "errmsg": "invalid token"}),
|
||||
_FakeResponse(
|
||||
{
|
||||
"errcode": "0",
|
||||
"data": [{"type": "pdf", "fileid": "1317"}],
|
||||
}
|
||||
),
|
||||
],
|
||||
}
|
||||
)
|
||||
client = OaE10OpenApiClient(_settings(), session=session)
|
||||
first = client.ensure_access_token()
|
||||
second = client.ensure_access_token()
|
||||
assert first == second == "atk-1"
|
||||
file_id = client.list_pdf_file_id("8448")
|
||||
assert file_id == "1317"
|
||||
assert any(item.startswith("POST /oauth2/refresh_token") for item in session.calls)
|
||||
reset_oa_e10_token_cache()
|
||||
|
||||
|
||||
def test_oa_sales_release_batch_uploads_and_skips_no_pdf(app, monkeypatch):
|
||||
"""有 PDF 的行上传;attList 无 PDF 记 skipped_no_pdf;不调用 fetch()。"""
|
||||
uploaded: list[str] = []
|
||||
rows = [
|
||||
SalesReleaseRow(invoice_no="EWZZ26090002", delivery_no="XH-1", doc_id="8448"),
|
||||
SalesReleaseRow(invoice_no="EWZZ26090099", delivery_no="XH-2", doc_id="8449"),
|
||||
]
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.oa_sales_release_runner.load_oa_e10_settings",
|
||||
lambda: _settings(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.oa_sales_release_runner.SalesDmsClient.ensure_configured",
|
||||
lambda: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.oa_sales_release_runner.previous_period_bounds",
|
||||
lambda now=None: (date(2026, 8, 1), date(2026, 9, 1), None, None),
|
||||
)
|
||||
|
||||
class _DummyClient:
|
||||
def ensure_access_token(self):
|
||||
return "atk"
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.oa_sales_release_runner.OaE10OpenApiClient.from_config",
|
||||
lambda: _DummyClient(),
|
||||
)
|
||||
monkeypatch.setattr(OaSalesReleaseAdapter, "fetch_rows", lambda self, period_month, scope_code="HXJM": rows)
|
||||
|
||||
def fake_download(self, row, *, client):
|
||||
if row.delivery_no == "XH-2":
|
||||
return None
|
||||
return b"%PDF-1.4 fake"
|
||||
|
||||
monkeypatch.setattr(OaSalesReleaseAdapter, "download_pdf", fake_download)
|
||||
|
||||
def fake_upload(self, row, content, *, period_month):
|
||||
uploaded.append(row.delivery_no)
|
||||
return SimpleNamespace(
|
||||
skipped_same_name=False,
|
||||
file=SimpleNamespace(filename=f"{row.invoice_no}-{row.delivery_no}.pdf"),
|
||||
)
|
||||
|
||||
monkeypatch.setattr(OaSalesReleaseAdapter, "upload_given", fake_upload)
|
||||
monkeypatch.setattr("app.services.voucher_check.oa_sales_release_runner.send_failure_alert", lambda **kwargs: None)
|
||||
|
||||
with app.app_context():
|
||||
task = ScheduleTask(
|
||||
schedule_no="SCH-TEST-OA",
|
||||
name="oa sales",
|
||||
schedule_type="platform_job",
|
||||
platform_api_path="accounting-voucher-oa-sales-release",
|
||||
owner_user_id=1,
|
||||
cron_expr="30 5 * * 2",
|
||||
job_params={"profile_code": "sales", "scope_code": "HXJM", "notify_failure_enabled": False},
|
||||
)
|
||||
run = ScheduleRun(run_no="RUN-OA-1", schedule_task_id=1, status="running")
|
||||
total, success, failed, skipped, details, errors, logs = run_oa_sales_release_batch(task, run)
|
||||
|
||||
assert total == 2
|
||||
assert success == 1
|
||||
assert failed == 0
|
||||
assert skipped == 1
|
||||
assert uploaded == ["XH-1"]
|
||||
assert any(item.get("status") == "skipped_no_pdf" for item in details)
|
||||
assert OaSalesReleaseAdapter.wired is False
|
||||
with pytest.raises(ServiceUnavailableError) as exc:
|
||||
OaSalesReleaseAdapter().fetch(period_month=date(2026, 8, 1), subjects=[])
|
||||
assert exc.value.code == "VOUCHER_CHECK.ADAPTER_NOT_WIRED"
|
||||
|
||||
|
||||
def test_oa_sales_release_batch_counts_upload_failure(app, monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.oa_sales_release_runner.load_oa_e10_settings",
|
||||
lambda: _settings(),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.oa_sales_release_runner.SalesDmsClient.ensure_configured",
|
||||
lambda: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.oa_sales_release_runner.previous_period_bounds",
|
||||
lambda now=None: (date(2026, 8, 1), date(2026, 9, 1), None, None),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.oa_sales_release_runner.OaE10OpenApiClient.from_config",
|
||||
lambda: SimpleNamespace(ensure_access_token=lambda: "atk"),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
OaSalesReleaseAdapter,
|
||||
"fetch_rows",
|
||||
lambda self, period_month, scope_code="HXJM": [
|
||||
SalesReleaseRow(invoice_no="EWZZ26090002", delivery_no="XH-FAIL", doc_id="8448")
|
||||
],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
OaSalesReleaseAdapter,
|
||||
"download_pdf",
|
||||
lambda self, row, *, client: b"%PDF-1.4 fail",
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
OaSalesReleaseAdapter,
|
||||
"upload_given",
|
||||
lambda self, row, content, *, period_month: (_ for _ in ()).throw(RuntimeError("dms down")),
|
||||
)
|
||||
alerts: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.oa_sales_release_runner.send_failure_alert",
|
||||
lambda **kwargs: alerts.append(kwargs.get("stage") or ""),
|
||||
)
|
||||
with app.app_context():
|
||||
task = ScheduleTask(
|
||||
schedule_no="SCH-TEST-OA2",
|
||||
name="oa sales",
|
||||
schedule_type="platform_job",
|
||||
platform_api_path="accounting-voucher-oa-sales-release",
|
||||
owner_user_id=1,
|
||||
cron_expr="30 5 * * 2",
|
||||
job_params={},
|
||||
)
|
||||
run = ScheduleRun(run_no="RUN-OA-2", schedule_task_id=1, status="running")
|
||||
total, success, failed, skipped, details, errors, logs = run_oa_sales_release_batch(task, run)
|
||||
assert total == 1
|
||||
assert success == 0
|
||||
assert failed == 1
|
||||
assert "download_or_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-oa-sales-release")
|
||||
assert job is not None
|
||||
assert job.label_key == "admin.schedule.form.platformJobAccountingVoucherOaSalesRelease"
|
||||
assert job.handler is not None
|
||||
|
||||
|
||||
def test_probe_writes_one_local_pdf(app, monkeypatch, tmp_path):
|
||||
"""联调命令默认只落本地 PDF,不上传文档库。"""
|
||||
from app.services.voucher_check.oa_sales_release_probe import main
|
||||
|
||||
row = SalesReleaseRow(invoice_no="EWZZ26090002", delivery_no="XH-1", doc_id="8448")
|
||||
monkeypatch.setattr("app.create_app", lambda *a, **k: app)
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.oa_e10_settings.load_oa_e10_settings",
|
||||
lambda: _settings(),
|
||||
)
|
||||
monkeypatch.setattr(OaSalesReleaseAdapter, "fetch_rows", lambda self, period_month, scope_code="HXJM": [row])
|
||||
monkeypatch.setattr(
|
||||
OaSalesReleaseAdapter,
|
||||
"download_pdf",
|
||||
lambda self, item, *, client: b"%PDF-1.4 probe",
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.voucher_check.oa_e10_client.OaE10OpenApiClient.from_config",
|
||||
lambda: SimpleNamespace(ensure_access_token=lambda: "atk"),
|
||||
)
|
||||
uploaded: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
OaSalesReleaseAdapter,
|
||||
"upload_given",
|
||||
lambda self, item, content, *, period_month: uploaded.append(item.delivery_no),
|
||||
)
|
||||
code = main(["--out-dir", str(tmp_path), "--period", "2026-08", "--limit", "1"])
|
||||
dest = tmp_path / "EWZZ26090002-XH-1.pdf"
|
||||
assert code == 0
|
||||
assert dest.read_bytes().startswith(b"%PDF")
|
||||
assert uploaded == []
|
||||
Reference in new issue
Block a user