diff --git a/.env.shared b/.env.shared index a50676a3..d2e1dba4 100644 --- a/.env.shared +++ b/.env.shared @@ -187,6 +187,26 @@ CONTRACT_PAYMENT_ERP_USERNAME=hxjm CONTRACT_PAYMENT_ERP_PASSWORD=hxjm ERP_TIMEOUT_SECONDS=30 TEXT2SQL_SCHEMA_PATH= +# 立账凭证销货放行单:E10 OpenAPI + ecology10(与 E9 OA_SQLSERVER_DATABASE=ecology 隔离) +# 开关/超时三环境一致;基址、corpId、应用密钥、SQL 主机与账号由 .env.local / .env. / Jenkins 注入 +OA_E10_SQLSERVER_DATABASE=ecology10 +OA_E10_SQLSERVER_PORT=1433 +OA_E10_SQLSERVER_ENCRYPT=no +OA_E10_SQLSERVER_TRUST_CERT=yes +OA_E10_SQLSERVER_TIMEOUT=10 +OA_E10_TIMEOUT_SECONDS=30 +OA_E10_TOKEN_REFRESH_SKEW_SECONDS=300 +OA_E10_OPENAPI_BASE_URL=http://192.168.100.184:10600/papi/openapi +OA_E10_CORPID=8c47e679b2e3a415b0381089af1a2e58 +OA_E10_APP_KEY=7a9c97b6a3f5525f1150985b006f96b8 +OA_E10_APP_SECRET=474922f5e071f972c46f357aa8a41eda +# 需要换成OA +OA_E10_USERID=1251671276931039236 +OA_E10_SQLSERVER_HOST=192.168.100.186 +OA_E10_SQLSERVER_USERNAME=AI_Knowledge_Base_OA +OA_E10_SQLSERVER_PASSWORD=hoo-thai@123_AI_OA +# 驱动可留空,留空会按本机已装驱动自动选:ODBC Driver 18 for SQL Server → 17 → SQL Server +OA_E10_SQLSERVER_DRIVER= # --- 8. 知识库与文件处理 --- # Knowledge base runtime diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 053c47b8..b76755b5 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -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() diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index 2a8eac1e..17872271 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -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') diff --git a/backend/app/services/schedule/job_registry.py b/backend/app/services/schedule/job_registry.py index 184ebae1..dba20992 100644 --- a/backend/app/services/schedule/job_registry.py +++ b/backend/app/services/schedule/job_registry.py @@ -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="在途收料文件抓取", diff --git a/backend/app/services/schedule/voucher_oa_sales_release_job.py b/backend/app/services/schedule/voucher_oa_sales_release_job.py new file mode 100644 index 00000000..196dbd88 --- /dev/null +++ b/backend/app/services/schedule/voucher_oa_sales_release_job.py @@ -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) diff --git a/backend/app/services/voucher_check/adapters/__init__.py b/backend/app/services/voucher_check/adapters/__init__.py index 183ca61a..c89d9fa6 100644 --- a/backend/app/services/voucher_check/adapters/__init__.py +++ b/backend/app/services/voucher_check/adapters/__init__.py @@ -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 ( diff --git a/backend/app/services/voucher_check/adapters/oa_sales_release.py b/backend/app/services/voucher_check/adapters/oa_sales_release.py index 16658713..4371170d 100644 --- a/backend/app/services/voucher_check/adapters/oa_sales_release.py +++ b/backend/app/services/voucher_check/adapters/oa_sales_release.py @@ -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) diff --git a/backend/app/services/voucher_check/config.py b/backend/app/services/voucher_check/config.py index 5f2aa72b..ce3c9b47 100644 --- a/backend/app/services/voucher_check/config.py +++ b/backend/app/services/voucher_check/config.py @@ -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: diff --git a/backend/app/services/voucher_check/oa_e10_client.py b/backend/app/services/voucher_check/oa_e10_client.py new file mode 100644 index 00000000..23337184 --- /dev/null +++ b/backend/app/services/voucher_check/oa_e10_client.py @@ -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 diff --git a/backend/app/services/voucher_check/oa_e10_repository.py b/backend/app/services/voucher_check/oa_e10_repository.py new file mode 100644 index 00000000..8a203722 --- /dev/null +++ b/backend/app/services/voucher_check/oa_e10_repository.py @@ -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 diff --git a/backend/app/services/voucher_check/oa_e10_settings.py b/backend/app/services/voucher_check/oa_e10_settings.py new file mode 100644 index 00000000..e440dcc1 --- /dev/null +++ b/backend/app/services/voucher_check/oa_e10_settings.py @@ -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, + ) diff --git a/backend/app/services/voucher_check/oa_sales_release_filename.py b/backend/app/services/voucher_check/oa_sales_release_filename.py new file mode 100644 index 00000000..752378e3 --- /dev/null +++ b/backend/app/services/voucher_check/oa_sales_release_filename.py @@ -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} diff --git a/backend/app/services/voucher_check/oa_sales_release_probe.py b/backend/app/services/voucher_check/oa_sales_release_probe.py new file mode 100644 index 00000000..16f5ac3c --- /dev/null +++ b/backend/app/services/voucher_check/oa_sales_release_probe.py @@ -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()) diff --git a/backend/app/services/voucher_check/oa_sales_release_publish.py b/backend/app/services/voucher_check/oa_sales_release_publish.py new file mode 100644 index 00000000..b3e1d9b7 --- /dev/null +++ b/backend/app/services/voucher_check/oa_sales_release_publish.py @@ -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, + ) diff --git a/backend/app/services/voucher_check/oa_sales_release_runner.py b/backend/app/services/voucher_check/oa_sales_release_runner.py new file mode 100644 index 00000000..090f1133 --- /dev/null +++ b/backend/app/services/voucher_check/oa_sales_release_runner.py @@ -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) diff --git a/backend/app/services/voucher_check/profiles/sales.py b/backend/app/services/voucher_check/profiles/sales.py index 2db876dd..d76a972f 100644 --- a/backend/app/services/voucher_check/profiles/sales.py +++ b/backend/app/services/voucher_check/profiles/sales.py @@ -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 diff --git a/backend/app/services/voucher_check/runner.py b/backend/app/services/voucher_check/runner.py index 4726b321..812c90d0 100644 --- a/backend/app/services/voucher_check/runner.py +++ b/backend/app/services/voucher_check/runner.py @@ -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。 """ diff --git a/backend/app/services/voucher_check/schedule_seed.py b/backend/app/services/voucher_check/schedule_seed.py index 13c5bde7..7fb8ca62 100644 --- a/backend/app/services/voucher_check/schedule_seed.py +++ b/backend/app/services/voucher_check/schedule_seed.py @@ -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") diff --git a/backend/tests/test_schedule_job_registry.py b/backend/tests/test_schedule_job_registry.py index 18239e2a..28547b3b 100644 --- a/backend/tests/test_schedule_job_registry.py +++ b/backend/tests/test_schedule_job_registry.py @@ -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 diff --git a/backend/tests/voucher_check/test_oa_sales_release_schedule.py b/backend/tests/voucher_check/test_oa_sales_release_schedule.py new file mode 100644 index 00000000..7d20fb94 --- /dev/null +++ b/backend/tests/voucher_check/test_oa_sales_release_schedule.py @@ -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 == [] diff --git a/docs/convention/环境变量规则.md b/docs/convention/环境变量规则.md index 10d78f9b..22d350f1 100644 --- a/docs/convention/环境变量规则.md +++ b/docs/convention/环境变量规则.md @@ -61,33 +61,3 @@ - 生产密钥不要放 `.env.shared`。 - 新增变量同步更新对应 env 文件和本文档。 - 继续清理对 `backend/.env` 的历史依赖。 - -## 7. 采购合同全面审核变量 - -采购合同审核的非敏感运行参数放在 `.env.shared`: - -- `PROCUREMENT_CONTRACT_STORAGE_ROOT` -- `PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS` -- `PROCUREMENT_CONTRACT_LLM_CONNECT_TIMEOUT_SECONDS` -- `PROCUREMENT_CONTRACT_LLM_READ_TIMEOUT_SECONDS` -- `PROCUREMENT_CONTRACT_LLM_MAX_TEXT_CHARS` -- `PROCUREMENT_CONTRACT_LLM_MAX_CLAUSES` - -以下采购合同 Dify Chatflow 相关变量可能因环境、Agent、地址和密钥不同,必须放在 `.env.dev`、`.env.test`、`.env.prod` 或 CI/Jenkins 密文变量,禁止放入 `.env.shared`: - -- `PROCUREMENT_CONTRACT_LLM_ENABLED` -- `PROCUREMENT_CONTRACT_LLM_PROVIDER` -- `PROCUREMENT_CONTRACT_LLM_AGENT_ID` -- `PROCUREMENT_CONTRACT_LLM_DIFY_APP_ID` -- `PROCUREMENT_CONTRACT_LLM_DIFY_API_KEY` -- `PROCUREMENT_CONTRACT_LLM_DIFY_BASE` - -`PROCUREMENT_CONTRACT_LLM_DIFY_API_KEY` 属于密钥;生产环境优先由 Jenkins/部署平台注入。当前优先通过 `PROCUREMENT_CONTRACT_LLM_AGENT_ID` 复用已配置的 Chatflow Agent,不在环境文件重复保存密钥。 - -## 8. 立账凭证检核文档库 - -三环境一致、非密钥的销售开票附件根目录放在 `.env.shared`: - -- `VOUCHER_CHECK_DMS_ROOT_FOLDER_ID` - -登录基址、LibraryID、账号默认复用 `CONTRACT_DMS_*`。如需覆盖再设 `VOUCHER_CHECK_DMS_BASE_URL` / `VOUCHER_CHECK_DMS_LIBRARY_ID` / `VOUCHER_CHECK_DMS_USERNAME` / `VOUCHER_CHECK_DMS_PASSWORD`(密码禁止写入仓库)。 diff --git a/docs/demand.md b/docs/demand.md index cbfd9da2..916eb43d 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -222,11 +222,11 @@ - AI 工作台中的“立账凭证”入口已迁入 Chat:作为 builtin Agent(`agent_code=voucher_check`),主区以 Tab 嵌入检核任务与企微发送记录;平台管理员另有「通知配置」按文件类型用公共选人弹窗(按部门筛选)选人。点击批次在当前 Tab 内下钻明细。第一期隐藏对话输入框与历史会话,不接 Dify。旧地址 `/workspace/accounting-voucher-check*` 重定向到对应 Chat 深链。平台 admin 或被授予该 Agent 的用户可访问;强制重检上月与通知配置仅管理员可见。 - **核心目标**:按业务方 Profile **每周二**增量检核**上一个自然月**;销售 invoice 清单来自 HXJM `oma_file`(`oma75`/`oma02`,已确认、未作废、状况码 1、帐款类别 11/12/13);从 ERP/OA/文档库获取必检资料,按 `invoice` 归入「所有归档」,输出缺件汇总 Excel。 - **销售一期资料**:PO 订单、报关资料、销货放行申请单、发票、报关单、提单。获取后先写入文档库 `销售开票附件/{年}/{月}/{类型目录}/`,再归档到同月 `所有归档/{invoice号}/`。 -- **OA**:一期仅模拟页面打销货放行单;后期对接新 OA 接口,规则不变。 +- **OA**:销货放行申请单走 E10 `ft_xqqgsq` + OpenAPI 下载表单 PDF(独立周批周二 05:30),规则与目录不变。 - **文档库**:复用现有文档管理系统(全公司一个库,LibraryID 与合同相同);销售开票附件是该库下独立文件夹,只单独配根 FolderID,不得复用合同根目录。 - **通知**:缺件按文件类型接收人拆成每人一封;平台管理员在 Chat「通知配置」维护。排程选人只用于技术失败告警。未配置则不发。 - **判定边界**:只做文件获取、命名/关联校验和归档结果;不读取文件内容、不使用 LLM、不核对金额/供应商等字段、不回写 ERP。 -- **实现状态**:周二 05:00 独立排程生成 PO PDF 并上传到「PO订单」;周二 06:00 检核周任务按上月 + 文档库扫描 + 按票归档(同名跳过)+ 缺件汇总。ERP 取数见 [technical-design.md §3.4](features/accounting-voucher-check/technical-design.md)(HXJM → TGHX,`TRIM(oma99)=TRIM(pmm99)`);OA 打印仍待接线。不做 Chatflow;查询走 `/api/workspace/accounting-voucher-check/*`,入口在 Chat Agent。 +- **实现状态**:周二 05:00 独立排程生成 PO PDF 并上传到「PO订单」;周二 05:30 独立排程从 E10 拉取销货放行单 PDF 到「销货单」;周二 06:00 检核周任务按上月 + 文档库扫描 + 按票归档(同名跳过)+ 缺件汇总。ERP 取数见 [technical-design.md §3.4](features/accounting-voucher-check/technical-design.md)(HXJM → TGHX,`TRIM(oma99)=TRIM(pmm99)`)。不做 Chatflow;查询走 `/api/workspace/accounting-voucher-check/*`,入口在 Chat Agent。 - 权威需求见 [docs/features/accounting-voucher-check/demand.md](features/accounting-voucher-check/demand.md)。 ### 3.x 货代发货通知库存源补充需求 diff --git a/docs/features/README.md b/docs/features/README.md index 9b848dd1..585e736e 100644 --- a/docs/features/README.md +++ b/docs/features/README.md @@ -9,7 +9,7 @@ | [auth](auth/README.md) | Casdoor 登录与产品内平级服务无感登录 | [hxops-peer-service-sso.md](auth/hxops-peer-service-sso.md) | | [shipping-notice](shipping-notice/README.md) | 货代发货通知 Agent | [technical.md](shipping-notice/technical.md) · [原型](shipping-notice/shipping_notice_agent_prototype.md) | | [file-check](file-check/README.md) | 文件检核(RoHS / MSDS 等) | [technical.md](file-check/technical.md) | -| [accounting-voucher-check](accounting-voucher-check/README.md) | 立账凭证资料检核(Chat Agent) | [需求说明](accounting-voucher-check/demand.md) · [技术设计](accounting-voucher-check/technical-design.md) · [原型](accounting-voucher-check/accounting-voucher-check-prototype.html) | +| [accounting-voucher-check](accounting-voucher-check/README.md) | 立账凭证资料检核(Chat Agent) | [需求说明](accounting-voucher-check/demand.md) · [技术设计](accounting-voucher-check/technical-design.md) · [OA 销货放行 E10](accounting-voucher-check/oa-sales-release-e10.md) · [原型](accounting-voucher-check/accounting-voucher-check-prototype.html) | | [fixed-assets](fixed-assets/README.md) | 固资快照同步与本地查询 | [technical.md](fixed-assets/technical.md) · [履历挂载命令](fixed-assets/history-share-mount.md) | | [procurement-contract](procurement-contract/README.md) | 采购合同审查 Agent(模板比对 / 单份审核) | [用户操作手册](procurement-contract/用户操作手册.md) · [demand.md](procurement-contract/demand.md) · [comprehensive-review-technical.md](procurement-contract/comprehensive-review-technical.md) · [原型](procurement-contract/procurement-contract-review-prototype.html) | | [contract-payment-plan](contract-payment-plan/) | 合同付款计划 / 预警 Agent | [方案 V3](contract-payment-plan/contract-payment-warning-proposal-v3.md) · [工作台原型](contract-payment-plan/contract-payment-plan-workspace-prototype-v2.html) · [Chat Agent 原型](contract-payment-plan/contract-payment-chat-agent-prototype.html) | diff --git a/docs/features/accounting-voucher-check/README.md b/docs/features/accounting-voucher-check/README.md index 9d60ddb1..43d4ac8a 100644 --- a/docs/features/accounting-voucher-check/README.md +++ b/docs/features/accounting-voucher-check/README.md @@ -9,10 +9,11 @@ | **部署验收清单** | 运维、研发 | [ops-checklist.md](ops-checklist.md) | | **PO 制式 PDF 样张 JSON** | 研发 | [po-order-sample.json](po-order-sample.json) · 入口 `python -m app.services.voucher_check.po_order --out-dir DIR --json FILE` | | **ERP 采购单取数表字段** | 研发 | [technical-design.md §3.4](technical-design.md)(发票 HXJM、采购单 TGHX;`TRIM(oma99)=TRIM(pmm99)`;独立抓取已接线) | +| **OA 销货放行单(E10)** | 研发 | [oa-sales-release-e10.md](oa-sales-release-e10.md):`ft_xqqgsq` + OpenAPI `attList`/`download`;独立周批周二 05:30 已接线 | **定位**:以业务方 Profile 驱动的批量资料检核;**每周二**增量处理上一个自然月。销售开票附件先落入文档库类型目录,再按 `invoice` 归入「所有归档」。 **要解决的问题**:不同业务方从 ERP、OA、固定目录等来源获取不同必检资料,统一检核、归档、汇总缺件并通知。 **检核内容**:只做必检文件的获取、存在性和归档结果;不做文件内容解析或金额、供应商等字段一致性核对。 **结果输出**:每批生成 Excel,区分缺件文件总数和缺件 `invoice` 数;企业微信按文件类型接收人拆成每人一封,完整明细以 Excel 与执行记录为准。 -**状态**:销售一期需求以 [demand.md](demand.md) 为准;查询入口为 Chat builtin Agent「立账凭证」。采购二期及其它业务方通过新增 Profile 扩展。周任务已切到文档库引擎;旧共享盘扫描、Chatflow Tool 与一票一状态表已移除。PO 制式 PDF 由周二 05:00 独立排程生成并上传;06:00 检核只扫描目录。OA 销货放行打印仍待接线。 +**状态**:销售一期需求以 [demand.md](demand.md) 为准;查询入口为 Chat builtin Agent「立账凭证」。采购二期及其它业务方通过新增 Profile 扩展。周任务已切到文档库引擎;旧共享盘扫描、Chatflow Tool 与一票一状态表已移除。PO 制式 PDF 由周二 05:00 独立排程生成并上传;销货放行单 PDF 由周二 05:30 独立排程从 E10 拉取并上传;06:00 检核只扫描目录。 diff --git a/docs/features/accounting-voucher-check/accounting-voucher-check-prototype.md b/docs/features/accounting-voucher-check/accounting-voucher-check-prototype.md index 145bc3a1..6894ac65 100644 --- a/docs/features/accounting-voucher-check/accounting-voucher-check-prototype.md +++ b/docs/features/accounting-voucher-check/accounting-voucher-check-prototype.md @@ -16,7 +16,7 @@ ## 业务口径 - 销售一期:**每周二**增量检核上一个自然月;invoice 来自 HXJM `oma_file`;获取后写入类型目录再归入 `所有归档/{invoice号}/`。 -- 销货放行申请单:一期模拟 OA 页面;后期换新接口。关联字段不完整时直接跳过。 +- 销货放行申请单:E10 `ft_xqqgsq` + OpenAPI 下载表单 PDF;独立周批周二 05:30 已接线。关联字段不完整时直接跳过。 - 采购二期:展示六类拟定文件规则;路径、主体来源和 Adapter 参数待确认,原型不执行采购检核。 - 批量缺件同时统计“缺件文件总数”和“缺件 `invoice` 数”;同一 `invoice` 缺多个文件时前者累计多个、后者只计一次。 - 统一 Excel 仅包含“检核结果”工作表:每行一个 `invoice`,直接展示各必检文件“有 / 缺件 / 未检核”和状态;全部文件均为“有”时状态为“完整”。 diff --git a/docs/features/accounting-voucher-check/demand.md b/docs/features/accounting-voucher-check/demand.md index 5f2aacbe..735eecbd 100644 --- a/docs/features/accounting-voucher-check/demand.md +++ b/docs/features/accounting-voucher-check/demand.md @@ -2,7 +2,7 @@ > 文档版本:v1.15 > 更新时间:2026-09-16 -> 状态:一期销售需求确认中;采购及其它业务方待后续 Profile 配置。PO 制式 PDF 由独立周批(周二 05:00)生成并上传;检核周批(周二 06:00)只扫描目录。ERP 取数 HXJM → TGHX,`TRIM(oma99)=TRIM(pmm99)`。 +> 状态:一期销售需求确认中;采购及其它业务方待后续 Profile 配置。PO 制式 PDF 由独立周批(周二 05:00)生成并上传;销货放行单 PDF 由独立周批(周二 05:30)从 E10 拉取并上传;检核周批(周二 06:00)只扫描目录。ERP 取数 HXJM → TGHX,`TRIM(oma99)=TRIM(pmm99)`。 > > 本文是本期需求权威。部署与冒烟见 [ops-checklist.md](ops-checklist.md)。旧共享盘存在性扫描、Chatflow Tool 与一票一状态表已移除,不得再按该口径扩展。 @@ -27,7 +27,7 @@ | 项目 | 规则 | | -------- | ----------------------------------------------------------------------------------------------------------------------- | -| 执行频率 | **两段周批(Asia/Shanghai)**:周二 **05:00** 生成并上传 PO 订单 PDF;周二 **06:00** 检核上月附件。 | +| 执行频率 | **三段周批(Asia/Shanghai)**:周二 **05:00** 生成并上传 PO 订单 PDF;周二 **05:30** 拉取销货放行单 PDF;周二 **06:00** 检核上月附件。 | | 检核期间 | 执行日的上一个自然月;例如 2026-08-18 执行,检核 2026-07 | | 执行方式 | 增量执行:已成功归档且来源文件/规则未变化的 `invoice + 文件规则` 可跳过;新增、缺件、规则变更或来源变更的记录重新检核。归档目录已有同名文件时按「同名跳过」不覆盖 | | 强制重检 | 支持对上一个自然月全量重检;不跳过任何主体。Chat「强制重检上月」入队 `force_all`(仅 admin) | @@ -116,7 +116,7 @@ Chat 第三 Tab「通知配置」按销售一期六类必检文件分行选人 | -------------- | ------------------------------ | -------------------------- | --------------------------------------------- | --------------------------- | ---------------------- | | PO 订单 | `{invoice号}-{订单号}.pdf` | 周二 05:00 独立排程按发票从 TGHX 取数生成制式 PDF 并上传到当月「PO订单」;06:00 检核只扫描该目录 | `文档库/销售开票附件/{yyyy}/{MM}/PO订单/` | `TRIM(HXJM.oma99)=TRIM(TGHX.pmm99)` → `pmm01` | **已确认**:发票 HXJM、采购单 TGHX。Job `accounting-voucher-po-print`(`SCH-ACCOUNTING-VOUCHER-PO-PRINT`)。同名跳过 | | 报关资料 | `{invoice号}.pdf` | 固定目录扫描 | `文档库/销售开票附件/{yyyy}/{MM}/报关资料/` | 文件名含 `invoice` | 扫描上月对应类型目录 | -| 销货放行申请单 | `{invoice号}-{销货单号}.pdf` | OA 自定义报表逐条打印 PDF | `文档库/销售开票附件/{yyyy}/{MM}/销货单/` | OA 列表读取发票号、销货单号 | 见 5.1 | +| 销货放行申请单 | `{invoice号}-{销货单号}.pdf` | 周二 05:30 独立排程查 E10 `ft_xqqgsq` 筛已归档行,按 `bdpdf` 调 OpenAPI 下载表单 PDF 并上传到当月「销货单」;06:00 检核只扫描该目录 | `文档库/销售开票附件/{yyyy}/{MM}/销货单/` | `fphm` = `invoice`,`xhdh` = 销货单号 | **已接线** Job `accounting-voucher-oa-sales-release`。见 5.1;技术细节 [oa-sales-release-e10.md](oa-sales-release-e10.md) | | 发票 | `{invoice号}-{发票号}.pdf` | 固定目录扫描 | `文档库/销售开票附件/{yyyy}/{MM}/发票/` | 文件名含 `invoice` | 扫描上月对应类型目录 | | 报关单 | `{invoice号}-{报关单号}.pdf` | 固定目录扫描 | `文档库/销售开票附件/{yyyy}/{MM}/报关单/` | 文件名含 `invoice` | 扫描上月对应类型目录 | | 提单 | `{invoice号}-提单.pdf` | 固定目录扫描 | `文档库/销售开票附件/{yyyy}/{MM}/提单/` | 文件名含 `invoice` | 扫描上月对应类型目录 | @@ -131,27 +131,26 @@ Chat 第三 Tab「通知配置」按销售一期六类必检文件分行选人 ## 5. 销售文件获取与归档 -### 5.1 销货放行申请单(OA) +### 5.1 销货放行申请单(OA E10) -一期**只支持按页面模拟**完成下列步骤;不依赖尚未提供的 OA 打印 API。后续对接新 OA 接口时,过滤条件、命名和归档规则不变,仅替换 Adapter 实现。 +**已确认**:不再模拟自定义报表打印。从 E10 表单库筛行,再用开放平台接口下载「表单 PDF」。命名、目录、归档规则不变。接口与字段见 [oa-sales-release-e10.md](oa-sales-release-e10.md)。**已接线**:独立排程 `accounting-voucher-oa-sales-release`(周二 05:30);检核 runner 不调用 `oa_sales_release.fetch()`。 -| 步骤 | 操作与规则 | -| ---- | --------------------------------------------------------------------- | -| 1 | 在 OA 进入“报表 → 流程报表 → 自定义报表”,选择“销货放行单” | -| 2 | 过滤申请日期为检核期间(上一个自然月) | -| 3 | 过滤流程状态为“归档”、账套为 `HXJM`、发票号码不为空 | -| 4 | 从结果列表读取发票号和销货单号,以二者关联并生成文件名 | -| 5 | 对关联字段完整的每条申请单:一期按页面逐步模拟打开并打印/保存 PDF;预留切换新 OA 接口,接口就绪后不改过滤与命名规则 | -| 6 | 关联字段不完整时直接丢弃该 OA 记录:不打印、不归档、不记录字段异常 | -| 7 | 校验后先写入当月「销货单」存放目录,再复制到「所有归档/{invoice号}/」 | +| 步骤 | 操作与规则 | +| ---- | --------- | +| 1 | 只读查询 `ecology10.dbo.ft_xqqgsq` | +| 2 | 过滤:`IS_DELETE = 0`、`bdpdf` 非空、`gdrq` 非空(已归档)、`chsj` 落在上一个自然月、账套 `zt = 'HXJM'`(已确认) | +| 3 | `fphm` 对应检核 `invoice`,`xhdh` 为销货单号;二者任一为空则丢弃该行(不下载、不归档、不记字段异常) | +| 4 | `bdpdf` 是**文档 ID**。先调「查询文档附件列表」,在结果里取 `type`/`extName` 为 `pdf` 的 `fileid`(不要用 html,也不要把 `bdpdf` 当 fileId 下载) | +| 5 | 用该 `fileid` 调文件下载,得到 PDF 流,命名 `{fphm}-{xhdh}.pdf` | +| 6 | 先写入当月「销货单」目录,再复制到「所有归档/{invoice号}/」,同名跳过 | ```mermaid flowchart TD - A[进入 OA 销货放行单自定义报表] --> B[过滤上月申请日期、归档、HXJM、发票号码非空] - B --> C[读取发票号与销货单号] + A[查询 ecology10.ft_xqqgsq] --> B[过滤未删除、已归档、bdpdf非空、出货时间上月、HXJM] + B --> C[读取 fphm 与 xhdh] C --> D{关联字段完整?} D -- 否 --> E[直接丢弃,不记录字段异常] - D -- 是 --> F[一期模拟页面打印 PDF / 后期改走 OA 接口] + D -- 是 --> F[attList 取 PDF fileid 并 download] F --> G[写入销货单目录并归档到所有归档/invoice] ``` @@ -271,7 +270,7 @@ flowchart TD 3. Excel 报告顶部可按资料所属期间选择年月,并单独展示执行时间;每个 `invoice` 一行,直接展示各必检文件为“有 / 缺件 / 未检核”和总体状态;全部必检文件均为“有”时状态为“完整”。 4. 企业微信按文件类型接收人拆成每人一封,正文只含该人负责的缺件类型,并提供本批 Excel 下载入口;完整 `invoice` 明细不在消息正文展开。审计仍是每批一条。 5. OA 关联字段不完整记录被直接丢弃,不进入异常、缺件、打印或归档结果。 -6. 销售 invoice 清单、文档库(同一 LibraryID、销售独立根 FolderID、建文件夹/复制接口)、周任务星期二、按文件类型选人界面已确认;ERP PO 取数:发票 HXJM、采购单 TGHX,关联 `TRIM(oma99)=TRIM(pmm99)` 已接线(独立抓取,见技术设计 §3.4);OA 模拟页细节仍通过配置承接,不能把凭据写死在通用逻辑中。 +6. 销售 invoice 清单、文档库(同一 LibraryID、销售独立根 FolderID、建文件夹/复制接口)、周任务星期二、按文件类型选人界面已确认;ERP PO 取数:发票 HXJM、采购单 TGHX,关联 `TRIM(oma99)=TRIM(pmm99)` 已接线(独立抓取,见技术设计 §3.4);OA 销货放行单取数已接线(E10 `ft_xqqgsq` + OpenAPI,独立排程周二 05:30),凭据只进环境变量。 7. 归档复制采用「同名跳过」:目标目录已有同名文件不覆盖、不报缺件。 ## 9. 待补充事项 @@ -280,9 +279,9 @@ flowchart TD | --- | --- | --- | | 销售 invoice 清单 | **已确认**:HXJM `oma_file.oma75/oma02`,`oma75` 至少 6 位字母或数字,`omaconf='Y'`、`omavoid='N'`、`oma64='1'`、`oma00 IN (11,12,13)`,期间为上一个月 | 无 | | ERP 反查 PO 并打印 | **打印、上传与取数已接线(周二 05:00 独立排程 `accounting-voucher-po-print`,06:00 检核不调用)**。采购单在 **TGHX**。关联 **已确认**:`TRIM(HXJM.oma99)=TRIM(TGHX.pmm99)`。`oma99` 为空时才走 `oma16` 备用。到货日 `pmn34`。详见 [technical-design.md §3.4](technical-design.md) | 制表者;卤素/环保是否拆列。原始编号优先 `ta_ima11` 否则 `pmn24`(业务仍略含糊)。`oma99` 为空的备用路径尚未用空值票验证 | -| OA 销货放行单 | **已确认方向**:一期只做模拟页面;后期对接新 OA 接口 | 模拟登录、分页、打印落盘细节 | +| OA 销货放行单 | **已接线**:E10 `ecology10.dbo.ft_xqqgsq`(`chsj` 上月、已归档、未删除、`bdpdf` 非空、`zt='HXJM'`)+ OpenAPI `attList`/`download`;独立排程 `accounting-voucher-oa-sales-release`(周二 05:30);`fphm`=`invoice`。详见 [oa-sales-release-e10.md](oa-sales-release-e10.md) | 注入 `OA_E10_*`;应用须已发布并授权附件列表与文件下载 | | 文档管理系统 | **已确认**:同一文档库 LibraryID;销售根 FolderID=`727c3683-dcdb-4d62-a5b1-b164224162bc`;建文件夹 `SaveFolder`、上传 `Attachment/Upload` + `Item/CreateFiles`、复制 `Item/Copy`;同名跳过 | 无 | | 企微接收人 | **已确认产品**:Chat「通知配置」按文件类型从系统用户多选;仅平台管理员可改 | 业务最终勾选哪些人 | -| 周任务 | **已确认**:周二 05:00 生成 PO PDF;周二 06:00 检核(上海时区) | 无 | +| 周任务 | **已确认**:周二 05:00 生成 PO PDF;周二 05:30 拉取销货放行单;周二 06:00 检核(上海时区) | 无 | | 销售类型目录名 | **已确认固定**:`PO订单`、`报关资料`、`销货单`、`发票`、`报关单`、`提单` | 无 | | 重复文件策略 | **已确认**:同名跳过 | 目标 `所有归档/{invoice}/` 或类型目录「PO订单」已有相同文件名则不覆盖 | diff --git a/docs/features/accounting-voucher-check/oa-sales-release-e10.md b/docs/features/accounting-voucher-check/oa-sales-release-e10.md new file mode 100644 index 00000000..4a544b2d --- /dev/null +++ b/docs/features/accounting-voucher-check/oa-sales-release-e10.md @@ -0,0 +1,219 @@ +# 立账凭证 · 销货放行申请单(OA E10)取数说明 + +> 文档状态:联调结论已确认,独立周批 `accounting-voucher-oa-sales-release`(周二 05:30)已接线。 +> 读者:研发、测试。 +> 需求入口:[demand.md §5.1](demand.md)。 +> 依据:E10 开放平台联调(`HX.postman_collection.json`,仅本地、不入库)+ 业务确认表 `ecology10.dbo.ft_xqqgsq`。 + +立账凭证销售一期的「销货放行申请单」不再走 OA 自定义报表模拟打印。改为:**先查 E10 表单库筛出已归档记录,再用 OpenAPI 把表单 PDF 下载下来**,写入当月「销货单」目录后按 `invoice` 归档。 + +## 1. 结论 + +| 项 | 结论 | +| ---------- | ------------------------------------------------------------------------------------------------ | +| 业务表 | `ecology10.dbo.ft_xqqgsq`(销货放行申请;**已确认**) | +| `bdpdf` | **文档 ID(docId)**,不是附件 fileId | +| 发票关联 | `fphm` = 立账凭证的 `invoice` | +| 文件名 | `{fphm}-{xhdh}.pdf`,即 `{invoice号}-{销货单号}.pdf` | +| 获取方式 | SQL 筛行 →`attList` 取 PDF 的 `fileid` → `download` 拉流 | +| 不走的接口 | `queryFileInfo`:应用默认无权限(`100010`),本链路不需要 | +| 库与现网 | 表在**E10 `ecology10`**,与现有知识库用的 E8 `ecology`(`OA_SQLSERVER_*`)不是同一库 | + +`bdpdf` 在表单上显示为「表单pdf」。点开是知识文档页,下面「附件」里才有 html / pdf。把 `bdpdf` 直接传给文件下载接口会返回 `1700009 附件不存在或已被删除`。 + +## 2. 库表筛选 + +只读查询 E10 库,筛选**上一个自然月、已归档、未删除、已有表单 PDF** 的销货放行单。 + +| 字段 | 含义 | 本链路用法 | +| ------------------- | ------------------- | ----------------------------------------------------------------- | +| `fphm` | 发票号码 | 对应检核主体 `invoice`;命名用 | +| `xhdh` | 销货单号 | 命名用 | +| `bdpdf` | 表单 PDF 文档 ID | 调 `attList` 的 `{docId}`;必须非空 | +| `gdrq` | 归档日期 | 非空 = 已归档 | +| `chsj` | 出货时间 | 落在检核月(上一个自然月) | +| `zt` | 账套 | **已确认**实值为 `HXJM`(与 Profile `scope_code` 一致) | +| `IS_DELETE` | 删除标记 | 必须为 `0` | +| `sqrq` / `djrq` | 申请日期 / 单据日期 | 联调可见,**本链路不用来过滤期间**(期间改看出货时间) | + +筛选条件(逻辑,实现时用参数化 SQL): + +```text +IS_DELETE = 0 +AND bdpdf IS NOT NULL AND LTRIM(RTRIM(bdpdf)) <> '' +AND gdrq IS NOT NULL +AND chsj >= 上月月初 AND chsj < 本月月初 +AND zt = 'HXJM' -- 已确认实值 +``` + +关联字段不完整(`fphm` 或 `xhdh` 空)的行:**直接丢弃**,不下载、不归档、不记字段异常(与现网 `incomplete_relation_policy=skip` 一致)。 + +ERP 发票清单里有、但本查询无对应 PDF 的 `invoice`,仍按缺件「销货放行申请单」统计。 + +`bdpdf`、`fileid` 均为 19 位左右长整型,**全程当字符串**,禁止经 JavaScript number 或会丢精度的 JSON number 传递。 + +## 3. OpenAPI 调用顺序 + +基址(示例,须走环境变量,禁止写进代码):`{OA_E10_OPENAPI_BASE}/` +联调入口形如 `http://:/papi/openapi`。 +应用须为已发布的**通用型应用**,并授权「查询文档附件列表」「文件下载」。凭证来自开放平台应用详情与「开发者资料」`corpId`,不入库。 + +```mermaid +flowchart TD + A[查 ecology10.ft_xqqgsq] --> B{bdpdf / fphm / xhdh 完整?} + B -- 否 --> C[丢弃该行] + B -- 是 --> D[authorize 取 code] + D --> E[access_token 换 token] + E --> F["GET attList/{bdpdf}"] + F --> G{列表中 type 或 extName 为 pdf?} + G -- 否 --> H[该票销货放行单缺件或获取失败] + G -- 是 --> I["GET download/{fileid} 得 PDF 流"] + I --> J["命名 {fphm}-{xhdh}.pdf"] + J --> K[写入销货单目录并归档到所有归档/invoice] +``` + +### 3.0 Token 生命周期(实现时必须按此处理) + +E10 三张票有效期不同,**不要每条销货放行单都重新拿 code**。 + +| 票据 | 默认有效期 | 次数 | 用途 | +| --- | --- | --- | --- | +| `code` | **10 分钟** | **一次性** | 只用来换 token,换完即作废 | +| `accessToken` | **2 小时**(以返回的 `expires_in` 秒为准) | 期内可反复调业务接口 | `attList` / `download` 的调用凭证 | +| `refreshToken` | **24 小时** | 期内可刷新 accessToken | `accessToken` 将过期或已过期时续期 | + +一次周批拉取(上月已归档行)通常远短于 2 小时,推荐: + +1. **任务启动时拿一次 token**:`authorize` 取 `code` → 立刻 `access_token` 换出 `accessToken` + `refreshToken` + `expires_in`。`code` 只在这两个请求之间活几秒,**不落库、不入日志、不跨任务复用**。 +2. **本进程内存缓存** `accessToken` / `refreshToken` / 到期时刻。同一 Job 里所有 `attList`、`download` 共用这一份。多 worker 时再考虑 Redis(TTL 按 `expires_in`),单次周二批处理用内存即可。 +3. **提前刷新**:到期前 **5 分钟**(防时钟偏差)调 `POST /oauth2/refresh_token`: + - Body:`{"grant_type":"refresh_token","refresh_token":"..."}`(同样走 JSON Body)。 + - 若 accessToken **已超时**:返回新的 `accessToken`、新的 `refreshToken`、新的超时。 + - 若 **未超时**:`accessToken` 不变,只把超时时间续上。 +4. **refreshToken 也失效**(文档:默认 24 小时后需重新授权,错误如 `300001`):整段重走 `authorize` → `access_token`,不要死循环刷 refresh。 +5. **业务接口返回 `200007` 无效 access_token**:刷新(或重授权)**一次**后重试当前请求;仍失败记技术失败,不要对同一文件无限重试。 + +不要把 token 写进 Excel、检核结果、Profile 或仓库。到期时刻用接口返回的 `expires_in`,不要写死 7200。 + +刷新接口:`POST {OA_E10_OPENAPI_BASE}/oauth2/refresh_token`。 + +### 3.1 获取 code + +```http +POST {OA_E10_OPENAPI_BASE}/oauth2/authorize?corpid={OA_E10_CORPID}&response_type=code&state={nonce} +``` + +文档亦允许 GET。`state` 用一次性随机串,不要空着。 + +成功:`errcode` 为 `"0"`,取 `code`。 + +### 3.2 用 code 换 accessToken + +```http +POST {OA_E10_OPENAPI_BASE}/oauth2/access_token +Content-Type: application/json +``` + +```json +{ + "app_key": "{OA_E10_APP_KEY}", + "app_secret": "{OA_E10_APP_SECRET}", + "grant_type": "authorization_code", + "code": "{上一步的 code}" +} +``` + +参数必须放 **JSON Body**(或 `x-www-form-urlencoded` Body),不要挂在 Query。成功字段名为 `accessToken`(不是 `access_token`)。 + +常见错误: + +| errcode | 含义 | 处理 | +| ---------- | ------------------------- | ---------------------------------------------- | +| `200005` | app_key / app_secret 无效 | 从当前 E10「通用型应用」详情复制;应用须已发布 | +| `200004` | code 无效 | 重新 authorize;code 不可复用、不可隔很久再换 token | +| `200007` | 无效的 access_token | 先 refresh,失败再重新 authorize,当前请求只重试一次 | +| `300001` | refresh_token 无效或过期 | 重新 authorize,不要继续 refresh | +| `100010` | 应用没有权限访问该接口 | 开放平台给该应用补 API 权限 | + +### 3.3 按文档 ID 查附件列表 + +`bdpdf` 作为路径中的 `{docId}`: + +```http +GET {OA_E10_OPENAPI_BASE}/api/doc/v2/attList/{bdpdf}?access_token={accessToken}&userid={OA_E10_USERID} +``` + +在返回数组中取 **`type` 或 `extName` 为 `pdf`** 的那一条(不要用 html)。下载用该条的 **`fileid`**。 + +同一文档常见两条:`.html` 与 `.pdf`。销货放行单归档只要 PDF。 + +列表里的 `loadlink`(`/papi/file/remotedownload/...`)是页面内部地址,OpenAPI 下载仍走下一节。 + +### 3.4 按 fileId 下载 + +```http +GET {OA_E10_OPENAPI_BASE}/api/file/v2/common/download/{fileid}?userid={OA_E10_USERID}&access_token={accessToken} +``` + +成功时 HTTP 200,响应体为 PDF 文件流。`module` 可用附件列表返回值(常见 `document`);联调不带 `module` 也能下到流。 + +不要把 `bdpdf` / `refId` / `docId` 填进 `{fileid}`。 + +## 4. 落盘与检核(规则不变) + +与 [demand.md](demand.md) 其它文件类型一致: + +1. 临时文件命名 `{invoice号}-{销货单号}.pdf`,即 `{fphm}-{xhdh}.pdf`。 +2. 先上传到 `文档库/销售开票附件/{yyyy}/{MM}/销货单/`。 +3. 再复制到 `文档库/销售开票附件/{yyyy}/{MM}/所有归档/{invoice}/`,同名跳过。 +4. 周检核仍只扫描类型目录;本 Adapter 负责把 PDF 放到类型目录。 + +已接线:独立排程 **`accounting-voucher-oa-sales-release`**(默认周二 **05:30**,`SCH-ACCOUNTING-VOUCHER-OA-SALES-RELEASE`),介于 PO 生成 05:00 与检核 06:00。`oa_sales_release.fetch()` 仍占位,检核 runner 不调用。 + +## 5. 失败归类 + +| 场景 | 归类 | +| -------------------------------------------------------- | ---------------------------------------------------------------------- | +| 筛选后无行,或 `fphm`/`xhdh` 空 | 丢弃 OA 行;该 `invoice` 若在 ERP 清单中则销货放行单为**缺件** | +| `attList` 无 pdf | 该票销货放行单**缺件**(禁止用 html 顶替) | +| OpenAPI / SQL 连不上、token 失败、`100010`、下载非 PDF | **技术失败**,不计缺件,走排程技术告警 | +| 目标目录已有同名文件 | 同名跳过,记已归档 | + +## 6. 环境变量 + +凭据只进环境变量 / Secret,禁止提交 Postman 导出或硬编码。现有 `OA_SQLSERVER_*` 指向 E9 `ecology`,本链路需要 E10 `ecology10` 与 OpenAPI,**不要混用**。`OA_E10_SQLSERVER_DATABASE` 默认 `ecology10`;若误配成 `ecology` 批次启动即失败。SQL 主机/账号未单独配置时可回退 `OA_SQLSERVER_HOST` / `USERNAME` / `PASSWORD`,**DATABASE 不回退**。 + +| 变量 | 用途 | +| --- | --- | +| `OA_E10_OPENAPI_BASE_URL` | OpenAPI 基址,含 `/papi/openapi` | +| `OA_E10_CORPID` | 开放平台 → 开发者资料 | +| `OA_E10_APP_KEY` / `OA_E10_APP_SECRET` | 已发布通用型应用 | +| `OA_E10_USERID` | 调 OpenAPI 的 E10 用户长 ID | +| `OA_E10_TIMEOUT_SECONDS` | OpenAPI HTTP 超时,默认 30 | +| `OA_E10_TOKEN_REFRESH_SKEW_SECONDS` | accessToken 到期前提前刷新秒数,默认 300 | +| `OA_E10_SQLSERVER_DATABASE` | 固定 `ecology10` | +| `OA_E10_SQLSERVER_HOST` / `PORT` / `USERNAME` / `PASSWORD` / `DRIVER` | E10 只读连接;主机账号可回退 `OA_SQLSERVER_*` | + +章节顺序按 [环境变量规则](../../convention/环境变量规则.md) 归入「企业系统集成」。部署清单见 [ops-checklist.md](ops-checklist.md)。 + +## 7. 明确不做 + +- 不模拟「报表 → 自定义报表 → 逐条打印」。 +- 不把 `bdpdf` 当 fileId 下载。 +- 不调用 `queryFileInfo` 作为主路径。 +- 不把 html 附件当作销货放行单正本。 +- 本期不改检核 Excel 列名、目录名、同名跳过策略。 + +## 8. 联调:只下一张 PDF + +不要用周批「立即执行」做第一次连通性验证(会扫上月全部已归档行)。在 `backend/` 用探测命令只下载本地文件,默认**不上传文档库**: + +```bash +# 上一个自然月的第一张 +python -m app.services.voucher_check.oa_sales_release_probe --out-dir ./tmp/oa-sales --limit 1 + +# 指定发票号(fphm) +python -m app.services.voucher_check.oa_sales_release_probe --out-dir ./tmp/oa-sales --invoice EWZZ26090002 --period 2026-08 +``` + +成功会打印本地路径 `{invoice}-{销货单号}.pdf`,用阅读器打开确认是表单 PDF。加 `--upload` 才会写入当月「销货单」目录。配置须已注入 `OA_E10_*`(见 §6);缺项会报 `VOUCHER_CHECK.CONFIG_INVALID` 并列 missing,不会打印密钥。 diff --git a/docs/features/accounting-voucher-check/ops-checklist.md b/docs/features/accounting-voucher-check/ops-checklist.md index 36a138eb..892959a5 100644 --- a/docs/features/accounting-voucher-check/ops-checklist.md +++ b/docs/features/accounting-voucher-check/ops-checklist.md @@ -1,6 +1,6 @@ # 立账凭证检核 — 部署验收清单 -> 覆盖当前引擎:每周二 **05:00** 生成 PO PDF 并上传到「PO订单」,**06:00** 检核**上一个自然月**、HXJM `oma_file` 发票清单、文档库类型目录扫描与按票归档(Copy,同名跳过)、单文件结果与企微批次汇总。TGHX 只读授权见 §2。 +> 覆盖当前引擎:每周二 **05:00** 生成 PO PDF 并上传到「PO订单」,**05:30** 从 E10 拉取销货放行单 PDF 到「销货单」,**06:00** 检核**上一个自然月**、HXJM `oma_file` 发票清单、文档库类型目录扫描与按票归档(Copy,同名跳过)、单文件结果与企微批次汇总。TGHX 只读授权见 §2;E10 见 §2 环境变量。 > > 产品需求见 [demand.md](demand.md),设计见 [technical-design.md](technical-design.md)。 > @@ -10,9 +10,9 @@ | 项 | 值 | | --- | --- | -| Job key | `accounting-voucher-check`(检核)· `accounting-voucher-po-print`(PO 生成) | -| 默认排程号 | `SCH-ACCOUNTING-VOUCHER-CHECK` · `SCH-ACCOUNTING-VOUCHER-PO-PRINT` | -| Cron | 检核 `0 6 * * 2`;PO 生成 `0 5 * * 2`(Asia/Shanghai,周二,生成早于检核) | +| Job key | `accounting-voucher-check`(检核)· `accounting-voucher-po-print`(PO 生成)· `accounting-voucher-oa-sales-release`(销货放行单) | +| 默认排程号 | `SCH-ACCOUNTING-VOUCHER-CHECK` · `SCH-ACCOUNTING-VOUCHER-PO-PRINT` · `SCH-ACCOUNTING-VOUCHER-OA-SALES-RELEASE` | +| Cron | 检核 `0 6 * * 2`;PO 生成 `0 5 * * 2`;销货放行单 `30 5 * * 2`(Asia/Shanghai,周二,拉取早于检核) | | 检核期间 | 上一个自然月 | | 销售类型目录 | PO订单、报关资料、销货单、发票、报关单、提单 | | 引擎表 | `voucher_check_profiles` / `runs` / `subjects` / `file_results` / `notifications` / `notify_configs` | @@ -40,8 +40,16 @@ flask db upgrade ```sql SELECT id, schedule_no, name, cron_expr, platform_api_path, enabled, next_run_at FROM schedule_tasks - WHERE schedule_no IN ('SCH-ACCOUNTING-VOUCHER-CHECK', 'SCH-ACCOUNTING-VOUCHER-PO-PRINT') - OR platform_api_path IN ('accounting-voucher-check', 'accounting-voucher-po-print'); + WHERE schedule_no IN ( + 'SCH-ACCOUNTING-VOUCHER-CHECK', + 'SCH-ACCOUNTING-VOUCHER-PO-PRINT', + 'SCH-ACCOUNTING-VOUCHER-OA-SALES-RELEASE' + ) + OR platform_api_path IN ( + 'accounting-voucher-check', + 'accounting-voucher-po-print', + 'accounting-voucher-oa-sales-release' + ); ``` - [ ] 若无用户时尚无种子:先建管理员账号,再重启 `hxops-backend`(启动钩子会补建) @@ -70,11 +78,22 @@ VOUCHER_CHECK_DMS_ROOT_FOLDER_ID= # 可选:制式采购单中文字体(默认 Windows 宋体或镜像 fonts-noto-cjk) # VOUCHER_CHECK_PO_FONT_PATH= + +# E10 销货放行单(DATABASE 必须 ecology10,禁止回退 E9 ecology;密钥勿提交仓库) +OA_E10_OPENAPI_BASE_URL=http://:/papi/openapi +OA_E10_CORPID= +OA_E10_APP_KEY= +OA_E10_APP_SECRET= +OA_E10_USERID= +OA_E10_SQLSERVER_DATABASE=ecology10 +# OA_E10_SQLSERVER_HOST= # 未设时回退 OA_SQLSERVER_HOST +# OA_E10_SQLSERVER_USERNAME= +# OA_E10_SQLSERVER_PASSWORD= ``` 检查: -- [ ] `hxops-backend` 与 `hxops-schedule-worker` 均注入相同 `VOUCHER_CHECK_ERP_*` / `VOUCHER_CHECK_DMS_*` +- [ ] `hxops-backend` 与 `hxops-schedule-worker` 均注入相同 `VOUCHER_CHECK_ERP_*` / `VOUCHER_CHECK_DMS_*` / `OA_E10_*` - [ ] 密码未出现在 `job_params`、日志样例、Excel 字段中 - [ ] 不再配置 `VOUCHER_CHECK_LOCAL_ROOT` / `VOUCHER_CHECK_SHARE_*`(旧共享盘方案已移除) - [ ] 只读账号除 HXJM `oma_file` 外,还须能读 **TGHX** 采购单及码表、以及 HXJM 备用出货/订单表(周二 05:00 PO 生成排程需要;06:00 检核仍不查 TGHX)。DBA 对只读用户执行(把 `` 换成实际账号,勿把密码写进工单附件以外的仓库): @@ -98,6 +117,13 @@ GRANT SELECT ON TGHX.pme_file TO ; GRANT SELECT ON TGHX.zo_file TO ; ``` +- [ ] E10 SQL 只读账号可查询 `ecology10.dbo.ft_xqqgsq`(与 E9 `ecology` 不是同一库): + +```sql +USE ecology10; +GRANT SELECT ON dbo.ft_xqqgsq TO ; +``` + --- ## 3. 排程与通知配置 @@ -148,7 +174,17 @@ GRANT SELECT ON TGHX.zo_file TO ; - [ ] 管理台可见 `SCH-ACCOUNTING-VOUCHER-PO-PRINT`,Cron 早于检核 - [ ] 「立即执行」后文档库 `销售开票附件/{年}/{月}/PO订单/` 出现 `{发票}-{pmm01}.pdf`(同名跳过) - [ ] 检核周批日志中**没有** `fetch_po_documents_for_invoices`;PO 排程日志关键字 `[voucher-po-print]` -- [ ] 工作台「最近一次检核」卡片仍只显示 `accounting-voucher-check`,不被 PO 生成排程抢入口 +- [ ] 工作台「最近一次检核」卡片仍只显示 `accounting-voucher-check`,不被 PO 生成或销货放行单排程抢入口 + +### 4.6 销货放行单拉取排程(周二 05:30) + +- [ ] 已注入 `OA_E10_OPENAPI_BASE_URL` / `CORPID` / `APP_KEY` / `APP_SECRET` / `USERID`;通用型应用已发布且含「查询文档附件列表」「文件下载」 +- [ ] `OA_E10_SQLSERVER_DATABASE=ecology10`,只读账号可 `SELECT` `dbo.ft_xqqgsq` +- [ ] 管理台可见 `SCH-ACCOUNTING-VOUCHER-OA-SALES-RELEASE`,Cron `30 5 * * 2` 早于检核 +- [ ] 「立即执行」后文档库 `销售开票附件/{年}/{月}/销货单/` 出现 `{发票}-{销货单号}.pdf`(同名跳过) +- [ ] 检核周批日志中**没有** `oa_sales_release.fetch`;拉取日志关键字 `[voucher-oa-sales-release]` / `[oa-e10]` +- [ ] 日志与 Excel 中无 code / accessToken / refreshToken / app_secret +- [ ] 首次联调用 `python -m app.services.voucher_check.oa_sales_release_probe --out-dir DIR --limit 1` 只落本地 PDF(见 [oa-sales-release-e10.md §8](oa-sales-release-e10.md)) --- @@ -156,10 +192,10 @@ GRANT SELECT ON TGHX.zo_file TO ; 平台排程仍走统一 `schedule` 队列,**`domain`/`job_type` 会一直是 `schedule` / `schedule_run`**。 -| 列 | 检核 | PO 生成 | -| --- | --- | --- | -| `business_ref` | `schedule_run:{id}:accounting-voucher-check` | `schedule_run:{id}:accounting-voucher-po-print` | -| `payload_json.platform_api_path` | `accounting-voucher-check` | `accounting-voucher-po-print` | +| 列 | 检核 | PO 生成 | 销货放行单 | +| --- | --- | --- | --- | +| `business_ref` | `schedule_run:{id}:accounting-voucher-check` | `schedule_run:{id}:accounting-voucher-po-print` | `schedule_run:{id}:accounting-voucher-oa-sales-release` | +| `payload_json.platform_api_path` | `accounting-voucher-check` | `accounting-voucher-po-print` | `accounting-voucher-oa-sales-release` | ```sql SELECT id, status, business_ref, message, payload_json @@ -169,15 +205,18 @@ SELECT id, status, business_ref, message, payload_json AND ( business_ref LIKE '%:accounting-voucher-check' OR business_ref LIKE '%:accounting-voucher-po-print' + OR business_ref LIKE '%:accounting-voucher-oa-sales-release' OR payload_json->>'platform_api_path' IN ( - 'accounting-voucher-check', 'accounting-voucher-po-print' + 'accounting-voucher-check', + 'accounting-voucher-po-print', + 'accounting-voucher-oa-sales-release' ) ) ORDER BY id DESC LIMIT 20; ``` -Worker 日志关键字:`[voucher-check]`(检核)或 `[voucher-po-print]`(PO 生成)。 +Worker 日志关键字:`[voucher-check]`(检核)、`[voucher-po-print]`(PO 生成)或 `[voucher-oa-sales-release]`(销货放行单)。 --- diff --git a/docs/features/accounting-voucher-check/technical-design.md b/docs/features/accounting-voucher-check/technical-design.md index a25070e2..298b5db1 100644 --- a/docs/features/accounting-voucher-check/technical-design.md +++ b/docs/features/accounting-voucher-check/technical-design.md @@ -2,7 +2,7 @@ > 文档版本:v2.11 > 更新时间:2026-09-14 -> 状态:销售一期引擎已落地。周二 05:00 `accounting-voucher-po-print` 从 TGHX 取数生成 PO PDF 并上传;周二 06:00 检核只扫描目录。OA 打印仍待接线 +> 状态:销售一期引擎已落地。周二 05:00 `accounting-voucher-po-print` 从 TGHX 取数生成 PO PDF 并上传;周二 05:30 `accounting-voucher-oa-sales-release` 从 E10 拉取销货放行单 PDF;周二 06:00 检核只扫描目录。 > 需求基线:[demand.md](demand.md) > > 本文替代旧实现「当月 + 单一共享盘 + 固定文件名存在性」。旧表、共享盘扫描与 Chatflow Tool 已删除,不得按旧口径扩展。 @@ -266,7 +266,7 @@ flowchart TD ### 4.2 销售 OA 特殊规则 -OA 销货放行申请单 Adapter 固定使用:上月申请日期、流程状态“归档”、账套 `HXJM`、发票号码非空。读取发票号和销货单号后,关联字段不完整的记录直接丢弃:不打印、不归档、不记录字段异常;字段完整的记录才进入 PDF 打印与后续归档。 +OA 销货放行申请单改为查 E10 `ecology10.dbo.ft_xqqgsq`:出货时间 `chsj` 为上月、`gdrq` 非空(已归档)、`IS_DELETE = 0`、`bdpdf` 非空、账套 `zt = 'HXJM'`(已确认)。`fphm` 对应 `invoice`,`xhdh` 为销货单号;关联字段不完整的记录直接丢弃:不下载、不归档、不记录字段异常。`bdpdf` 是文档 ID,须先 `attList` 再按 PDF 的 `fileid` 下载,细节见 [oa-sales-release-e10.md](oa-sales-release-e10.md)。独立排程 **`accounting-voucher-oa-sales-release`(周二 05:30)** 写入「销货单」目录;`oa_sales_release.fetch` 保持 `wired=False`,检核 runner 不调用。 ## 5. 归档与结果模型 @@ -366,9 +366,9 @@ ERP/OA 打印或目录扫描的成功文件先写入类型存放目录;完成 1. **已做**:Profile、文件规则、批次/单文件结果表、上月期间、周二 cron、销售 DMS 只读、directory_scan、缺件聚合、按类型接收人拆信、Chat Agent 任务列表 / 企微记录 / 通知配置(admin,公共选人弹窗按部门筛选)、最近一次检核卡片。 2. **已做**:`dms_archive` 建文件夹(`SaveFolder`)+ 复制(`Item/Copy`),重复策略同名跳过;命中文件记 `archived`。 -3. **已做**:制式采购单 PDF(`save_po_order_pdf`)及上传到当月「PO订单」目录(`publish_po_order_pdf` / `upload_given`),命名 `{invoice}-{order_no}.pdf`,同名跳过;`erp_po_print.fetch` 与 OA 仍占位,检核 runner 不调用生成或上传。 +3. **已做**:制式采购单 PDF(`save_po_order_pdf`)及上传到当月「PO订单」目录(`publish_po_order_pdf` / `upload_given`),命名 `{invoice}-{order_no}.pdf`,同名跳过;`erp_po_print.fetch` 仍占位,检核 runner 不调用生成或上传。 4. **已做**:ERP PO 取数 + 独立周批 `accounting-voucher-po-print`(周二 05:00,早于检核 06:00)。检核 runner 不要生成或上传 PDF。关联:`TRIM(HXJM.oma99)=TRIM(TGHX.pmm99)`。 -5. 接入 OA 模拟页;采购通过新增 Profile 和 Adapter 参数接入。 +5. **已做**:OA 销货放行单走 E10 SQL + OpenAPI,独立周批 `accounting-voucher-oa-sales-release`(周二 05:30);`oa_sales_release.fetch` 仍占位。采购通过新增 Profile 和 Adapter 参数接入。 ## 10. 验收重点 @@ -392,7 +392,7 @@ ERP/OA 打印或目录扫描的成功文件先写入类型存放目录;完成 | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- | | 每日 `0 6 * * *`,检核**当前自然月** | **每周二** `0 6 * * 2`,检核**上一个自然月** | | HXJM `apa_file.apa08/apa09` 拉发票清单 | 改为 `oma_file`:`oma75` 发票号码、`oma02` 帐款日期;仅 `omaconf='Y'`、`omavoid='N'`、`oma64='1'`、`oma00` 为 11/12/13;期间为上一个月 | -| 共享盘 `vouche/{YYYY}/{MM}/{invoice_no}/` 只做文件名存在性 | 从文档库类型目录扫描(PO 由 05:00 独立排程写入类型目录;OA 打印一期未接线),先落入 `销售开票附件/{年}/{月}/{类型}/`,再归档到同月 `所有归档/{invoice}/` | +| 共享盘 `vouche/{YYYY}/{MM}/{invoice_no}/` 只做文件名存在性 | 从文档库类型目录扫描(PO 由 05:00、销货放行单由 05:30 独立排程写入类型目录),先落入 `销售开票附件/{年}/{月}/{类型}/`,再归档到同月 `所有归档/{invoice}/` | | 必检「核价单.pdf」「采购单.pdf」 | 销售一期:PO、报关资料、销货放行申请单、发票、报关单、提单 | | 一票一状态;缺资料按票发企微 textcard、同票同日节流 | 单文件结果;每批一条汇总通知 + invoice 行 Excel | | Chatflow Tool `/api/accounting-voucher-check/tools/*` | 已删除;查询走工作台 `/api/workspace/accounting-voucher-check/*` | diff --git a/docs/features/accounting-voucher-check/technical.md b/docs/features/accounting-voucher-check/technical.md index b038f296..15e93b5f 100644 --- a/docs/features/accounting-voucher-check/technical.md +++ b/docs/features/accounting-voucher-check/technical.md @@ -48,7 +48,7 @@ flowchart TD E --> F{Source Adapter} F -->|directory_scan| G[固定目录扫描] F -->|erp_query_print| H[ERP查询并打印] - F -->|oa_report_print| I[OA报表过滤并打印] + F -->|oa_report_print| I[E10表筛选并下载表单PDF] F -->|oa_relation_print| J[按关联单号查询OA并打印] F -->|upload_directory_scan| K[网盘或上传目录扫描] F -->|custom_adapter| L[其它来源适配器] @@ -203,14 +203,14 @@ error_message 失败原因 | ------------------------- | ---------------------------------- | -------------------------------- | | `directory_scan` | 固定目录按规则扫描文件 | 销售发票、提单;采购对账单、发票 | | `erp_query_print` / `erp_po_print` | 销售 PO:独立排程 `accounting-voucher-po-print`(周二 05:00)按发票从 TGHX 取数并上传到「PO订单」;`fetch()` 仍占位,检核 runner(06:00)不调用。表字段见 [technical-design.md §3.4](technical-design.md) | 销售 PO、采购 PO | -| `oa_report_print` | OA 报表过滤后逐条打印 | 销售销货放行单 | +| `oa_report_print` / `oa_sales_release` | E10 表单库筛选 + OpenAPI 下载表单 PDF;独立排程 `accounting-voucher-oa-sales-release`(周二 05:30)写入「销货单」;`fetch()` 仍占位,检核 runner(06:00)不调用。口径见 [oa-sales-release-e10.md](oa-sales-release-e10.md) | 销售销货放行单 | | `oa_relation_print` | 根据出货单号等关联字段查 OA 并打印 | 采购核价单 | | `upload_directory_scan` | 网盘或上传目录扫描 | 采购送货单 | | `payment_download` | 出纳/付款系统下载回单 | 采购付款回单 | Adapter 必须满足:参数化查询、超时控制、失败分类、临时文件隔离、日志脱敏和可重复执行。 -关联字段缺失时的处理由文件规则决定。销售销货放行申请单使用 `skip`:直接跳过该 OA 记录,不打印、不归档,也不记录字段异常;其它文件规则可按业务要求记录失败或阻断。 +关联字段缺失时的处理由文件规则决定。销售销货放行申请单使用 `skip`:直接跳过该 OA 记录,不下载、不归档,也不记录字段异常;其它文件规则可按业务要求记录失败或阻断。 ## 6. 数据模型 @@ -532,7 +532,7 @@ backend/app/domains/document_check/ | 销售 invoice 主体来源与 ERP 字段 | 已确认:HXJM `oma_file` `oma75`/`oma02`,`oma75` 至少 6 位字母或数字,`omaconf='Y'`、`omavoid='N'`、`oma64='1'`、`oma00 IN (11,12,13)`,期间上一个月 | | 采购 invoice 主体来源 | 待确认 | | ERP PO 查询字段与打印方式 | **打印与取数已接线(周二 05:00 独立排程)**。发票 HXJM、采购单 **TGHX**。关联 `TRIM(oma99)=TRIM(pmm99)`。对照 apmr900。到货日 `pmn34`。检核 runner 不调用 | -| OA 登录、报表分页和打印接口 | 一期模拟页面;后期对接新 OA 接口 | +| OA 登录、报表分页和打印接口 | 销货放行单已接线:E10 SQL + OpenAPI,独立排程周二 05:30;检核 runner 不调用 `fetch()` | | 文档管理系统 | 已确认:同一文档库 LibraryID;销售根 FolderID=`727c3683-dcdb-4d62-a5b1-b164224162bc`;建文件夹 `SaveFolder`、上传 `Attachment/Upload` + `Item/CreateFiles`、复制 `Item/Copy`;同名跳过 | | 企业微信通知接收人、模板和频率 | Chat「通知配置」按文件类型选人(仅平台管理员);每周二;具体人选可后配 | | Profile 管理方式 | 首期可使用版本化 YAML/JSON,后续评估管理后台配置 | diff --git a/docs/funclist.md b/docs/funclist.md index 8af86e53..98fb452f 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -227,9 +227,10 @@ | 功能项 | 状态 | 说明 | | --- | --- | --- | -| 销售一期需求、规格与技术设计 | 已文档化 | [需求](features/accounting-voucher-check/demand.md) · [规格](features/accounting-voucher-check/technical.md) · [设计](features/accounting-voucher-check/technical-design.md);每周增量检核上一个月;销售 invoice 来自 HXJM `oma_file.oma75`(已确认、未作废、状况码 1、帐款类别 11/12/13) | -| 通用 Profile + Adapter 架构 | 实施中 | 销售 Profile 与 Adapter 协议已落地;周任务扫描文档库类型目录;OA 销货放行单打印仅占位 | +| 销售一期需求、规格与技术设计 | 已文档化 | [需求](features/accounting-voucher-check/demand.md) · [规格](features/accounting-voucher-check/technical.md) · [设计](features/accounting-voucher-check/technical-design.md) · [OA 销货放行 E10 取数](features/accounting-voucher-check/oa-sales-release-e10.md);每周增量检核上一个月;销售 invoice 来自 HXJM `oma_file.oma75`(已确认、未作废、状况码 1、帐款类别 11/12/13) | +| 通用 Profile + Adapter 架构 | 实施中 | 销售 Profile 与 Adapter 协议已落地;周任务扫描文档库类型目录;OA 销货放行单由独立周批拉取([oa-sales-release-e10.md](features/accounting-voucher-check/oa-sales-release-e10.md)) | | PO 订单制式 PDF | 已实现(周二 05:00 独立排程) | 排程 `accounting-voucher-po-print`(`SCH-ACCOUNTING-VOUCHER-PO-PRINT`,`0 5 * * 2`)按上月发票从 TGHX 取数并上传到 `销售开票附件/{年}/{月}/PO订单/`;检核 `accounting-voucher-check` 仍为周二 06:00 只扫目录;`erp_po_print.fetch` 不进检核 runner | +| 销货放行单 PDF | 已实现(周二 05:30 独立排程) | 排程 `accounting-voucher-oa-sales-release`(`SCH-ACCOUNTING-VOUCHER-OA-SALES-RELEASE`,`30 5 * * 2`)查 E10 `ecology10.dbo.ft_xqqgsq` 并经 OpenAPI 下载表单 PDF,上传到 `销售开票附件/{年}/{月}/销货单/`;`oa_sales_release.fetch` 不进检核 runner | | 单一共享盘旧检核 | 已移除 | 已删除共享盘扫描、Chatflow Tool、`voucher_check_invoice_states` / `voucher_check_run_items` | | 增量、归档与缺件通知 | 实施中 | 每周二上月;单文件结果;归档复制同名跳过;企微按文件类型接收人拆成每人一封,审计仍每批一条 | | 工作台查询 | 已实现 | 已迁入 Chat Agent「立账凭证」(`agent_code=voucher_check`):Tab 为检核任务、企微发送记录,管理员另有通知配置(按六类文件用公共选人弹窗按部门选人);期间为年+月(默认上月,月份可「全部」看该年);Tab 下「最近一次检核」终态矮指标格、执行中才展开进度,不跟筛选;「强制重检上月」在卡片上(仅 admin);点击批次在当前 Tab 内下钻明细。平台 admin 或被授予该 Agent 的用户可访问;通知配置仅 admin。旧 `/workspace/accounting-voucher-check*` 重定向到 Chat。 | diff --git a/docs/tec.md b/docs/tec.md index 67fd02c6..85004b9c 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -217,12 +217,12 @@ PDF 证据锚定优先使用现有 `pypdfium2` 逐字文本坐标定位,并由 - 前端入口为 Chat builtin Agent `voucher_check`(`task_chat`,第一期不走 completions)。旧路由 `/workspace/accounting-voucher-check*` 重定向到 `/chat/:agentId?view=`;工作台侧栏不再展示该入口。 - `/api/workspace/accounting-voucher-check/*` 查询校验平台 admin 或 `user_agent_permissions` 中启用的该 Agent。无授权返回 403(`VOUCHER_CHECK.FORBIDDEN`)。`POST /runs` 强制重检与 `GET/PUT /notify-config` 额外要求 `role=admin`(`VOUCHER_CHECK.ADMIN_REQUIRED`)。 - **目标架构**:通用检核引擎 + 业务方 Profile + 来源 Adapter。**每周二**处理上一个自然月;invoice 主体来自 HXJM `oma_file`(`oma75`/`oma02`,`omaconf='Y'`、`omavoid='N'`、`oma64='1'`、`oma00` 为 11/12/13);引擎负责增量、归档、缺件双口径、Excel 与企微批次汇总。 -- **销售一期来源**:PO 订单由 HXOPS 按制式采购单生成 PDF 并上传到当月「PO订单」目录。发票在 HXJM,采购单在 **TGHX**(多角);关联已确认 `TRIM(oma99)=TRIM(pmm99)`,见 [technical-design.md §3.4](features/accounting-voucher-check/technical-design.md)。OA 销货放行单一期模拟页面、文档库扫描报关资料/发票/报关单/提单。获取后写入 `销售开票附件/{yyyy}/{MM}/{类型目录}/`,再归档到同月 `所有归档/{invoice}/`。 +- **销售一期来源**:PO 订单由 HXOPS 按制式采购单生成 PDF 并上传到当月「PO订单」目录。发票在 HXJM,采购单在 **TGHX**(多角);关联已确认 `TRIM(oma99)=TRIM(pmm99)`,见 [technical-design.md §3.4](features/accounting-voucher-check/technical-design.md)。OA 销货放行单由独立周批从 E10 `ft_xqqgsq` + OpenAPI `attList`/`download` 拉取(见 [oa-sales-release-e10.md](features/accounting-voucher-check/oa-sales-release-e10.md));文档库扫描报关资料/发票/报关单/提单。获取后写入 `销售开票附件/{yyyy}/{MM}/{类型目录}/`,再归档到同月 `所有归档/{invoice}/`。 - **文档库**:复用现有 DMS(`CONTRACT_DMS_BASE_URL`、`/Login/_api/Login`、`/Api/_api/APS/Public/Item/Page`、`SaveFolder`、`Attachment/Upload`、`Item/CreateFiles`、`Item/Copy`、现有账号);LibraryID 与合同相同,销售开票附件只单独配置根 FolderID。类型目录上传与归档复制均为同名跳过。 - **通知**:缺件按文件类型接收人拆信,配置在 Chat「通知配置」(仅 admin,公共选人弹窗按部门筛选);排程选人只用于技术失败告警。未配置不发送。 - **判定边界**:不读取文件内容、不调用 LLM 判断合格、不回写 ERP。批次级依赖不可用时整批失败,不得把空结果批量判为缺件。 -- **当前代码**:周二 05:00 `accounting-voucher-po-print` 按上月 `oma_file` 从 TGHX 取数生成 PO PDF 并上传到「PO订单」;周二 06:00 检核扫描类型目录 + 按票归档(Copy,同名跳过)+ 单文件结果 + 批次企微。`erp_po_print.fetch` / OA 仍为占位,检核 runner 不调用生成。旧共享盘扫描、Chatflow Tool 与 `voucher_check_invoice_states` / `voucher_check_run_items` 已删除。 -- 详细业务需求见 [docs/features/accounting-voucher-check/demand.md](features/accounting-voucher-check/demand.md),研发落地设计见 [docs/features/accounting-voucher-check/technical-design.md](features/accounting-voucher-check/technical-design.md)。 +- **当前代码**:周二 05:00 `accounting-voucher-po-print` 按上月 `oma_file` 从 TGHX 取数生成 PO PDF 并上传到「PO订单」;周二 05:30 `accounting-voucher-oa-sales-release` 从 E10 拉取销货放行单 PDF 并上传到「销货单」;周二 06:00 检核扫描类型目录 + 按票归档(Copy,同名跳过)+ 单文件结果 + 批次企微。`erp_po_print.fetch` / `oa_sales_release.fetch` 仍占位。旧共享盘扫描、Chatflow Tool 与 `voucher_check_invoice_states` / `voucher_check_run_items` 已删除。 +- 详细业务需求见 [docs/features/accounting-voucher-check/demand.md](features/accounting-voucher-check/demand.md),研发落地设计见 [docs/features/accounting-voucher-check/technical-design.md](features/accounting-voucher-check/technical-design.md),OA 销货放行取数见 [oa-sales-release-e10.md](features/accounting-voucher-check/oa-sales-release-e10.md)。 ### 2.x 货代发货通知批次库存能力 diff --git a/frontend/src/features/contract-payment/components/ContractPaymentChatPanel.vue b/frontend/src/features/contract-payment/components/ContractPaymentChatPanel.vue index 8cedc558..f56a85cc 100644 --- a/frontend/src/features/contract-payment/components/ContractPaymentChatPanel.vue +++ b/frontend/src/features/contract-payment/components/ContractPaymentChatPanel.vue @@ -1,14 +1,16 @@ diff --git a/frontend/src/features/contract-payment/views/ContractPaymentWeeklyBatchesPage.vue b/frontend/src/features/contract-payment/views/ContractPaymentWeeklyBatchesPage.vue index 605b6261..9867a8cc 100644 --- a/frontend/src/features/contract-payment/views/ContractPaymentWeeklyBatchesPage.vue +++ b/frontend/src/features/contract-payment/views/ContractPaymentWeeklyBatchesPage.vue @@ -3,6 +3,7 @@ 用途:独立展示合同付款预警的周汇总批次及其企业微信发送审计摘要,并下载 Excel 明细。 依赖:contract-payment.api、统一消息提示。 逻辑:后端扫描产生的批次在此集中查看;Excel 经受控接口下载;Chat 顶栏共用发送入口,本页 embedded 时隐藏页头与发送按钮。 + 嵌入布局仅表格区域滚动,表头 sticky,滚动条常显。 -->